text
stringlengths 180
608k
|
---|
[Question]
[
*This is a [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") challenge. For the robbers thread, go [here](https://codegolf.stackexchange.com/q/109951/42963).*
This challenge involves two [OEIS](https://oeis.org/) sequences chosen by the cops -- **S1**, **S2** -- and how well those sequences can be golfed and obfuscated.
### The Cops' Challenge
Your challenge as a cop is to pick a [freely available language](http://meta.codegolf.stackexchange.com/a/7212/42963), and two OEIS sequences. Then, write code **A** in that language that takes input *n* and produces S1(n). When that code is modified by a [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance) of **X** characters (with X no more than `0.5 * (length A)`), and turned into code **B** in the same language, it must then produce S2(n). You must actually write this code **B**, but don't reveal it until your challenge is safe (see below).
The cops' submissions must include the language name, the full code **A**, the byte-count of **A**, the **X** value of how many changes to get to their secret **B** code, and the chosen **S1** and **S2** sequence numbers. You can choose whether each sequence is 0-indexed or 1-indexed, but please specify that in your submission.
To crack a particular submission, robbers must come up with a program **C** in the same language (and version) that produces S2(n) and is **Y** character changes away from **A** (with `Y <= X`). Robbers do not necessarily need to find the exact same **B** code that the cop (secretly) produced.
### Winning and Scoring
If your cop answer has not been cracked within 7 days (168 hours), you may reveal your own **B** solution, at which point your answer is considered safe. As long as you don't reveal your solution, it may still be cracked by robbers, even if the 7 days have already passed. If your answer does get cracked, please indicate this in the header of your answer, along with a link to the corresponding robber's answer.
Cops win by having the uncracked submission with the shortest **A**. If tied, then the smallest **X** will be used as tie-breaker. If still tied, the earlier submission will win.
### Further Rules
* You must not use any built-ins for hashing, encryption, or random number generation (even if you seed the random number generator to a fixed value).
* Either programs or functions are allowed, but the code must not be a snippet and you must not assume a REPL environment.
* You may take input and give output [in any convenient format](http://meta.codegolf.stackexchange.com/q/2447/42963). The input/output methods must be the same for both sequences.
* The definitive calculator for the Levenshtein distance for this challenge is [this one](http://planetcalc.com/1720/?license=1) on Planet Calc.
* In addition to being a CnR challenge, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply.
[Answer]
# ~~[Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 28 bytes, Distance of 4, [A002817](http://oeis.org/A002817), [A090809](http://oeis.org/A090809)~~ [Cracked](https://codegolf.stackexchange.com/a/110547/56656)
This answer uses 1-indexing
```
(({({}[()])}{}){({}[()])}{})
```
[Try it online](https://tio.run/nexus/brain-flak#@6@hUa1RXRutoRmrWVtdq4nC@f/fDAA)
For anyone interested there are 27475 valid Brain-Flak programs with Levenshtein distance 4 from this program and 27707 with distance 4 or less. So a brute force solution would be feasible on a consumer grade computer.
[Answer]
# [7](https://esolangs.org/wiki/7), 33 characters, 13 bytes, X = 10, [A000124](http://oeis.org/A000124) → [A000142](http://oeis.org/A000142), Safe
```
171720514057071616777023671335133
```
[Try it online!](https://tio.run/nexus/7#DcOBDQAwCMOwl1oY5P/Lyiw5xpTGT4PwegFVL@6ePykd)
The Levenshtein distance is measured in terms of characters, so I've written the program in terms of the characters it contains above (and Try it online!, including the language itself, is happy to run programs encoded in ASCII). However, the program is stored in disk using 7's sub-byte encoding, meaning that the program itself is actually the following hexdump (thus 13 bytes long):
```
00000000: 3cf4 2982 f1ce 3bfe 13dc b74b 7f <.)...;....K.
```
(Because the Levenshtein distance is measured in terms of characters, you aren't necessarily adding/deleting/changing 10 *bytes* here, so it's probably best to work with the original ASCII.)
The program as written implements A000124 (triangular numbers + 1); any crack must implement A000142 (factorials). Both programs take input from stdin (as decimal integers), write their output to stdout, and treat an input of 1 as meaning the first element of the sequence (and an input of 2 as the second element, etc.).
Hopefully the very high X value will stop people brute-forcing the program, this time (which is always a risk with cops-and-robbers entries in 7).
## The solution
```
177172051772664057074056167770236713351353
```
[Try it online!](https://tio.run/nexus/7#DcXBAcAwDAKxlYwp3P6TuflIJxA7eW/7TRieVYFZF9mR47v8 "7 – TIO Nexus")
Differences from the original:
```
17 172051 405707 **1** 61677702367133513 3
17**7**172051**77266**405707**405**61677702367133513**5**3
```
I don't have explanations prepared for how these work, so it's going to take me a while to get an explanation up, as I'm going to have to figure it out from almost-scratch. Hopefully there will be an explanation eventually.
[Answer]
## Pyke, Levenshtein distance of 1, [A036487](https://oeis.org/A036487), [A135628](https://oeis.org/A135628).
### [Cracked!](https://codegolf.stackexchange.com/a/109957/32686)
```
X*e
```
[Try it here!](http://pyke.catbus.co.uk/?code=X%2ae&input=10)
[Answer]
# [Perl 6](http://perl6.org/), 10 bytes, X = 1, [A000012](http://oeis.org/A000012) → [A001477](http://oeis.org/A001477)
### [Cracked!](https://codegolf.stackexchange.com/a/109963/14880)
```
*[0]o 1***
```
* **S1** = A000012 = `1,1,1,1,1,...` = The all 1's sequence. *(0-indexed)*
* **S2** = A001477 = `0,1,2,3,4,...` = The nonnegative integers. *(0-indexed)*
[Try it online!](https://tio.run/nexus/perl6#y61UUEtTsP2vFW0Qm69gqKWl9d@aqzixUiE3sQAoo6NgqKdnZGD9HwA "Perl 6 – TIO Nexus")
Confirmed to work with [Perl 6 release 2017.01](http://rakudo.org/downloads/star/), and with the Perl6 version running on TIO.
(**A** could be further golfed to `1***` – I hope it it's also allowed as it is.)
[Answer]
# [Perl 6](https://perl6.org), 13 bytes, X = 1, [A161680](http://oeis.org/A161680) → [A000217](http://oeis.org/A000217)
### Safe!
```
{[+] [,] ^$_}
```
* **S1** = A161680 = `0 0 1 3 6 10 15 21...` = Zero followed by the triangular numbers.
* **S2** = A000217 = `0 1 3 6 10 15 21 28 ...` = The triangular numbers.
* Zero-indexed.
[Try it online!](https://tio.run/nexus/perl6#y61UUEtTsP1fHa0dqxCtE6sQpxJf@784sVJBKfhRU6MCCNgqKOko2BgoGCgYKhgrmCkYAhmmCkaGCkYWCsZmCiamCqamCmZmCuYWCpaGQFlTBUMjoBKglKGpsYKhOVDM0sDOmgtmahOKqRSYCVQPN1cJShelFpfmlEBMz00sAPpOR8FAT8/IwPo/AA "Perl 6 – TIO Nexus")
(Confirmed to work with the Perl 6 version running on TIO.)
### Solution
```
{[+] [\,] ^$_}
```
How the original works:
```
{ } # A lambda.
$_ # Lambda argument. e.g. 4
^ # Range from 0 to n-1. e.g. 0, 1, 2, 3
[,] # Reduce with comma operator. e.g. 0, 1, 2, 3
[+] # Reduce with addition operator. e.g. 6
```
How the solution works:
```
{ } # A lambda.
$_ # Lambda argument. e.g. 4
^ # Range from 0 to n-1. e.g. 0, 1, 2, 3
[\,] # Triangle reduce with comma operator. e.g. (0), (0,1), (0,1,2), (0,1,2,3)
[+] # Reduce with addition operator. e.g. 10
```
Exploits the fact that numeric operators like addition treat a list as its number of elements, so in the example the sum is `1 + 2 + 3 + 4 = 10`.
And yeah, the "Reduce with comma operator" no-op in the original is kinda skirting the code-golf rules, but I prefer to look at it as a silly algorithm which has been golfed as much as possible (whitespace etc.) for what it is... :)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes, X = 5, [A005185](https://oeis.org/A005185) → [A116881](https://oeis.org/A116881)
```
ịḣ2S;
1Ç¡ḊḢ
```
This is a full program that takes an integer as command-line argument and prints an integer.
Both sequences are indexed as on OEIS, i.e, [A005185](https://oeis.org/A005185) is 1-indexed and [A116881](https://oeis.org/A116881) is 0-indexed.
[Try it online!](https://tio.run/nexus/jelly#ARsA5P//4buL4bijMlM7CjHDh8Kh4biK4bii////MjA "Jelly – TIO Nexus")
[Answer]
## Javascript, 41 bytes, Distance of 3, [A061313](https://oeis.org/A061313), [A004526](https://oeis.org/A004526), [Cracked](https://codegolf.stackexchange.com/a/109981/12012)
```
f=x=>{return x>1?x%2?f(x+1)+1:f(x/2)+1:0}
```
[Try it Online](https://tio.run/nexus/javascript-node#@59mW2FrV12UWlJalKdQYWdoX6FqZJ@mUaFtqKltaAVk6BuBGAa1/0tso2O50vKLNKxL9HJS89JLMmwMDQyAnILS4gwNmBhQn6Y1V3J@XnF@TqpeTn46UCY3sUAjTVPzPwA)
Uses 1 based indexing, solution uses 0 based indexing.
Once again, a different solution...
```
f=x=>{return x>1?x<2?f(x-1)+1:f(x-2)+1:0}
```
[Answer]
# [Perl 6](https://perl6.org), 19 bytes, X = 1, [A000045](http://oeis.org/A000045) → [A000035](http://oeis.org/A000035)
### [Cracked!](https://codegolf.stackexchange.com/a/110006/14880)
```
{(0,1,*+*...*)[$_]}
```
* **S1** = A000045 = `0 1 1 2 3 5 8 13 21 34...` = "Fibonacci numbers". (*0-indexed*)
* **S2** = A000035 = `0 1 0 1 0 1 0 1 0 1...` = "Period 2". (*0-indexed*)
[Try it online!](https://tio.run/nexus/perl6#jY@9CsIwHMT3PsVRRDSGkH8@TEKtL@EoIsUqOhSFuhRxsI/qi8SA7eTiHcdxyw@u6TA9oYyPmeTE2YIJIdh8O9nvnrGtOuSbd//CoBI5x0qCkhU0LDxIQxG0gU0rgIyB0hraOSxJIngHssFBWW9gyNO6yEZw/wv@IyMgH/p@vrQ4XOvjF9NUt3SJQwpBocjiBw "Perl 6 – TIO Nexus")
(Confirmed to work with the Perl 6 version running on TIO.)
[Answer]
# ~~WolframAlpha, 18 bytes, X = 1~~
**[Cracked by math\_junkie!](https://codegolf.stackexchange.com/a/110059/56178)**
```
(sum1to#of n^1)*2&
```
Sometimes WolframAlpha will actually be able to display a pure function like this in functional form (other times it gets confused); but it can be cheerfully invoked with a given input—for example, `(sum1to#of n^1)*2&@5` yields `30`.
**S1** = [A002378](https://oeis.org/A002378) (pronic numbers)
**S2** = [A000537](https://oeis.org/A000537) (sum of the first `n` cubes)
Both sequences are 0-indexed.
[Answer]
## Pyke, Levenshtein distance of 2, [A008788](https://oeis.org/A008788), [A007526](https://oeis.org/A007526)
### [Cracked!](https://codegolf.stackexchange.com/a/110071/32686)
```
'th^
```
[Try it here!](http://pyke.catbus.co.uk/?code=%27th%5E&input=5)
Let's get slightly harder shall we?
The first answer is 1 based and the crack is 0 based.
[Answer]
# Javascript, 15704 bytes, distance of 2, [A059841](http://oeis.org/A059841) and [A000004](https://oeis.org/A000004) - [cracked](https://codegolf.stackexchange.com/a/110069/54187)
This solution is extremely long, so you can find the full code [at this github gist.](https://gist.github.com/DJMcMayhem/103703e44534336bae7ccb39dd287f28)
The original answer (this one) is 1 indexed.
(I know this is way too long, it is just for fun.)
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 16 bytes, Levenshtein distance of 4, [A000217](https://oeis.org/A000217) and [A002378](https://oeis.org/A002378) -- [Cracked by Martin Ender!](https://codegolf.stackexchange.com/a/110078/31716)
```
({({}[()])()}{})
```
[Try it online!](https://tio.run/nexus/brain-flak#@69RrVFdG62hGaupoVlbXav5/785AA "Brain-Flak – TIO Nexus")
This should be fairly easy to crack.
[Answer]
## Javascript, 30 bytes, Distance of 4, [A000290](https://oeis.org/A000290), [A000079](https://oeis.org/A000079), **-**[Cracked!](https://codegolf.stackexchange.com/a/109964/64505)
```
f=x=>{return x?2*x-1+f(x-1):0}
```
0-based indexing
@Kritixi Lithos's solution was actually different from mine
```
f=x=>{return x?f(x-1)+f(x-1):1}
```
[Try it online](https://tio.run/#Mjo5U)
[Answer]
# Javascript (ES6), distance is 1, [A000079](https://oeis.org/A000079 "A000079") and [A000004](https://oeis.org/A000004 "A000004") - [cracked](https://codegolf.stackexchange.com/a/109976/54187)
```
as=function(){ return 2*2**((11)*-1*~arguments[0]/11-(4-(as+[]).length%89))-(as+[]).length%7}
```
The original answer (this one) is 0 based.
Now that it has been cracked, here is the original B function:
```
as=function(){ return 2*2**((1^1)*-1*~arguments[0]/11-(4-(as+[]).length%89))-(as+[]).length%7}
```
[Answer]
# [Perl 6](https://perl6.org), 7 bytes, X = 2, [A059841](http://oeis.org/A059841) → [A001477](http://oeis.org/A001477)
### [Cracked!](https://codegolf.stackexchange.com/a/110001/14880)
```
+(*%%2)
```
* **S1** = A059841 = `1 0 1 0 1 0 1 0...` = "\*Period 2: Repeat (1,0)". *(0-indexed)*
* **S2** = A001477 = `0 1 2 3 4 5 6 7...` = "The nonnegative integers". *(0-indexed)*
[Try it online!](https://tio.run/nexus/perl6#jY7LCoJQAET3fsXhgtFDxLk@L2Y/0RdID2ohBbZxmZ/aj5iREe0aGAZm4DBNx@xINazmS9@3i6H02rrDbB/9nUkVJmAtIv7w5gvofwGv2RKTkJKRU@DQWApZFKMEpShDOSqQ@6DMlLfTuWV32R/ewKa@jtcDojCUK73hCQ "Perl 6 – TIO Nexus")
(Confirmed to work with the Perl 6 version running on TIO.)
[Answer]
# Java 7, Levenshtein distance of 4, [A094683](https://oeis.org/A094683), [A000290](https://oeis.org/A000290), [Cracked](https://codegolf.stackexchange.com/questions/109951/change-the-code-change-the-sequence-robbers/110043#110043)
```
int x{double r=1;for(int i=0;i<42;i++)r=r/2+n/r/2;int k=(int)((int)n*(float)n/Math.pow(n,(Math.sin(n)*Math.sin(n)+Math.cos(n)*Math.cos(n))/2));return n%4%2==(int)Math.log10(Math.E)/Math.log((double)'H'-'@')?(int)r:k;}
```
0-indexed.
[Try it here!](http://ideone.com/xx2BLx)
] |
[Question]
[
Write a program or named function that will output or return the sequence up to the `n`th integer in the Iccanobif sequence, documented on OEIS as [A014258](https://oeis.org/A014258). Note that only the zeroth element in the sequence (`0`) will be printed if `n` is zero.
The sequence is generated by starting like the standard Fibonacci sequence, but after adding the two previous numbers, you flip the result and drop any leading zeros. An interesting fact, to me at least, is that this sequence is not strictly increasing (see the list below). It also seems to be (and probably is) strictly greater than or equal to the Fibonacci sequence.
Your program's input must be an integer.
The first 20 numbers of the sequence are provided here for your viewing pleasure:
```
0, 1, 1, 2, 3, 5, 8, 31, 93, 421, 415, 638, 3501, 9314, 51821, 53116, 739401, 715297, 8964541, 8389769
```
Standard loopholes are forbidden.
Shortest program wins.
EDIT: Added a note to clarify that the sequence starts with the zeroth element and should be included if `n` is zero.
### Example IO possibilities:
```
0 -> 0
1 -> 0 1
6 -> 0 1 1 2 3 5 8
17 -> [0, 1, 1, 2, 3, 5, 8, 31, 93, 421, 415, 638, 3501, 9314, 51821, 53116, 739401, 715297]
```
Now that there are several answers, below are my implementations in Python 2 that I worked hard to hide with markup:
Iterative:
>
>
> ```
> #Closest to my initial program. 73 bytes. It should also be noted that this program
> cannot reach a stack overflow. It runs for n=5000 in less than 10 seconds.
>
> i,a,b=input(),0,1
> print a
> while i:print b;i,a,b=i-1,b,int(str(a+b)[::-1])
> ```
>
>
>
>
Recursive:
>
>
> ```
> #Note that this prints n trailing newlines. 64 bytes.
> Will hit a stack overflow error for large values of n.
>
> def f(n,i=0,j=1):print i,n and f(n-1,j,int(str(i+j)[::-1]))or'';
> ```
>
>
>
>
[Answer]
## Python 2, 58 bytes
```
a=0;b=1
exec"print a;a,b=b,int(str(a+b)[::-1]);"*-~input()
```
Uses `str` to convert rather than backticks because large enough numbers in Python 2 are written with an L at the end. I tried a recursive function, but it turned out longer (61):
```
f=lambda n,a=0,b=1:-~n*[0]and[a]+f(n-1,b,int(str(a+b)[::-1]))
```
[Answer]
# Pyth, ~~17~~ ~~15~~ 14
```
Pu+Gs_`s>2GQU2
```
[Try it online](https://pyth.herokuapp.com/?code=Pu%2BGs_%60s%3E2GQU2&input=17&debug=0)
Very basic implementation, starts with `range(2)` and adds a number of elements equal to the input, then ~~slices off the extras~~ pops off the last element.
Thanks @Jakube for pointing out the `>` reversal thingy.
### Explanation
```
Pu+Gs_`s>2GQU2 : Q = eval(input) (implicit)
P : all but the last element
u QU2 : reduce Q times starting with [0, 1]
+G : add to the previous result
s>2G : sum of the last two elements of G
s_` : int(reversed(repr(above value)))
```
[Answer]
# Julia, 79 bytes
```
f=n->(t=[0,1];for i=2:n push!(t,t[i]+t[i-1]|>string|>reverse|>int)end;t[1:n+1])
```
This creates a function that accepts an integer as input and returns an integer array.
Ungolfed + explanation:
```
function f(n)
# Start with the usual Fibonacci stuff
t = [0,1]
# Looooooooooooooop
for i = 2:n
# Compute the Iccanobif number by piping results
iccanobif = t[i] + t[i-1] |> string |> reverse |> int
# Jam it into t
push!(t, iccanobif)
end
# Return the first n + 1
t[1:n+1]
end
```
Examples:
```
julia> f(1)
2-element Array{Int64,1}:
0
1
julia> f(17)
18-element Array{Int64,1}:
0
1
1
2
3
5
8
31
93
421
415
638
3501
9314
51821
53116
739401
715297
```
[Answer]
# T-SQL, 149
Very straight forward inline table function that uses a recursive CTE query. As it is using INTs this will top out at 37. Adding in CASTs for bigints will allow it to go further to 63
```
create function i(@ int)returns table return with r as(select 0I,1N union all select n,reverse(i+n)+0from r)select 0n union all select top(@)n from r
```
It is used as follows
```
select * from i(0)
n
-----------
0
(1 row(s) affected)
select * from i(1)
n
-----------
0
1
(2 row(s) affected)
select * from i(6)
n
-----------
0
1
1
2
3
5
8
(7 row(s) affected)
select * from i(17)
n
-----------
0
1
1
2
3
5
8
31
93
415
421
638
3501
9314
51821
53116
715297
739401
(18 row(s) affected)
```
[Answer]
# K, ~~25~~ 23 bytes
```
{-1_ x{x,.|$+/-2#x}/!2}
```
A simple modification of one of the examples at [No Stinking Loops](http://kx.com/a/k/examples/recur.k).
The phrase `.|$` casts a number to a string, reverses it and then evaluates it.
## Edit:
Sloppy attention to boundary conditions on my part. More correct now:
```
{-1_ x{x,.|$+/-2#x}/!2}'0 1 6 10
(,0
0 1
0 1 1 2 3 5 8
0 1 1 2 3 5 8 31 93 421 415)
```
## Edit 2:
`(x+1)#` can be replaced with `-1_`, saving 2 characters. The space is necessary because otherwise `_x` would be an identifier, when I want the "drop" operator applied to a variable called `x`.
[Answer]
# Haskell, ~~64~~ 49 bytes
```
a!b=a:b!(read$reverse$show$a+b)
q n=0:take n(1!1)
```
Usage example: `q 15` -> `[0,1,1,2,3,5,8,31,93,421,415,638,3501,9314,51821,53116]`
How it works: `!` recursively builds an infinite list of iccanobif numbers starting with it's first argument (the second argument must be the next iccanobif number). `q` takes the first `n` numbers from the iccanobif list starting with `1, 1` and prepends a `0`.
[Answer]
# CJam, 18 bytes
```
U1{_2$+sW%i}ri*;]p
```
**How it works**
```
U1 e# First two numbers in the series
{ }ri* e# Run the loop input numbers times
_2$+ e# Get sum of last two numbers in the series
sW%i e# Convert to string, inverse and convert back to a number
; e# Remove the last number to get only first n + 1 numbers.
]p e# Wrap all numbers in an array and print the array
```
[Try it online here](http://cjam.aditsu.net/#code=U1%7B_2%24%2BsW%25i%7Dri*%3B%5Dp&input=17)
[Answer]
# Java - ~~126~~ 124
I haven't seen Java around this site in awhile...
```
void f(int b){for(int c=0,d=1,g;b-->=0;d=Integer.valueOf(new StringBuilder(c+(c=d)+"").reverse()+""))System.out.println(c);}
```
`f(5)` prints `0 1 1 2 3 5 8 31 93 421 415 638`
[Answer]
# SWI-Prolog, ~~141~~ ~~131~~ 121 bytes
```
a(X,R):-X>1,A is X-1,a(A,B),reverse(B,[K,L|_]),W is K+L,name(W,Z),reverse(Z,Y),name(E,Y),nth0(X,R,E,B);X=1,R=[0,1];R=[0].
```
Running `a(17,X).` outputs:
```
[0, 1, 1, 2, 3, 5, 8, 31, 93, 421, 415, 638, 3501, 9314, 51821, 53116, 739401, 715297]
```
Takes about 10 seconds to output the result of `a(10000,X).` on my computer.
Edit: The 121 bytes version above is a one predicate definition = one liner.
The old 131 bytes version is the following (must be runned as `p(17,X)`):
```
a(0,[0]).
a(1,[1,0]).
a(X,[E|B]):-A is X-1,a(A,B),B=[K,L|_],W is K+L,name(W,Z),reverse(Z,Y),name(E,Y).
p(X,Y):-a(X,Z),reverse(Z,Y).
```
[Answer]
## [><> (Fish)](http://esolangs.org/wiki/Fish) ~~592~~ 254 Bytes
Not super golfed (42/43 blanks that do nothing and a total of 30 redirection tokens) , but was an interesting exercise getting it working in the first place.
```
10!/{:}0=?v/{1-}}:{+:0}!/a,:1%-:0=?!v~{:1!/$:@0=?!v$~}}:&{{&*\
/-$/ ;n/\oo", "n: \ }+1{/ \$-1$*a /|.!20}}01@/
* :{:}(?v:{!":}-1!/$:@0=?!v$~{:}1!/$:@0=?!v$~}}}:&{{{&*:1%-*&{{&+}}{1+}02.
b .1 +bb \ \$-1$*a / \$-1$,a /
\*9{~~~{/
```
You can test it [here](http://fishlanguage.com/playground/6rsxwkJHFgobme6gf), providing the desired length in the initial stack.
EDIT: More than halved byte count
[Answer]
# PHP, 114, 109 bytes
```
function f($n){if($n==0)return 0;$f=[0,1];for($i=2;$i<=$n;++$i){$f[$i]=strrev($f[$i-1]+$f[$i-2]);}return $f;}
```
Nothing fancy, just an average fibonacci algorithm with the string reverse magic.
Ungolfed:
```
function f($n)
{
if($n == 0) return 0;
$f = [0, 1];
for ($i=2; $i<=$n; ++$i){
$f[$i] = strrev($f[$i-1] + $f[$i-2]);
}
return $f;
}
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 10 bytes
```
↑¡ȯ↔Σ↑_2ŀ2
```
[Try it online!](https://tio.run/##yygtzv7//1HbxEMLT6x/1Dbl3GIgO97oaIPR////DS0A "Husk – Try It Online")
[Answer]
### Excel VBA, 279 bytes
```
n = InputBox("n")
For i = 0 To n
If i < 2 Then
Cells(i + 1, 1) = i
ElseIf i > 6 Then
x = Cells(i, 1) + Cells(i - 1, 1)
l = Len(x)
v = CStr(x)
For j = 1 To l
r = r + Right(v, 1)
v = Left(v, l - j)
Next j
Cells(i + 1, 1) = r
r = ""
Else
Cells(i + 1, 1) = Cells(i, 1) + Cells(i - 1, 1)
End If
Next i
```
Running the macro will prompt the user to enter a value for n.
The results will then be printed row by row in column A:

[Answer]
# JavaScript (ES2015), ~~81~~ 73 bytes
```
(a,b=0,c=1)=>{for(;a-->-1;c=[...(b+(b=+c)+"")].reverse().join``)alert(b)}
```
Running this function (named `f`) with `6`:
```
f(6);// alerts: 0, 1, 1, 2, 3, 5, 8
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 13 bytes
I'm pretty sure all the features used in this program were present in Pip before this question was asked.
```
LaSio:+RVi+oi
```
Takes input as command-line argument. [Try it online!](https://tio.run/nexus/pip#@@@TGJyZb6UdFJapnZ/5//9/SwA "Pip – TIO Nexus")
### Explanation
```
a is 1st cmdline arg; i is 0; o is 1 (implicit)
La Loop (a) times:
RVi+o Reverse of i+o
+ Unary + treats its operand as a number, thus removing leading 0's
o: Assign the result to o...
Si ... before swapping i and o
i After the loop, output i
```
The two variables' values evolve like so:
```
Iter o i (output)
0 1 0
1 0 1
2 1 1
3 1 2
4 2 3
5 3 5
6 5 8
7 8 31
8 31 93
9 93 421
10 421 415
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
+ṚḌɗС1
```
[Try it online!](https://tio.run/##ARkA5v9qZWxsef//K@G5muG4jMmXw5DCoTH//zEw "Jelly – Try It Online")
Reads `n` from STDIN
## How it works
```
+ṚḌɗС1 - Main link. No arguments
- By default, set the left argument to 0
1 - Set the right argument to 0
С - Read n from STDIN and do the following n times:
Start with x = 0, y = 1, then update according to
x, y = y, f(x,y), collecting each intermediate step
ɗ - Define f(x, y):
+ - x + y
Ṛ - Reversed digits
Ḍ - Back to integer
```
[Answer]
# [R](https://www.r-project.org/), 87 bytes
```
function(n)while(n+1){n=n-1;show(+F);F=T+(T=F);F=F%/%10^(z=0:log10(F))%%10%*%10^rev(z)}
```
[Try it online!](https://tio.run/##Rc05CoAwEEDR0wRmDGKmVabNCawFDS4BmYArKJ49Lo3d5zV/it65WkLjO47dKm7xQUBwH/zYgmjCU1hSKuYh7KAtFpZLDSV/ZVWmyFRwsMnH0JMBi6geUsnrU7vBgde/ACKMNw "R – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `W`, ~~10~~ 9 bytes
```
01?(~+Ṙ)_
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJXIiwiIiwiMDE/KH4r4bmYKV8iLCIiLCIxNyJd)
-1 thanks to Steffan
Similar to the [CJam](https://codegolf.stackexchange.com/a/52092/107299) answer.
```
01?(~+Ṙ)_ # 'W' flag prints the entire stack
01 # Push 0, then 1
?( ) # Loop input number of times
~+ # Add the previous 2 numbers without popping
Ṙ # Reverse the result (given a number, the output will be a number)
_ # Pop the last result
```
[Answer]
# [Pushy](https://github.com/FTcode/Pushy), 18 bytes (non-competing)
```
Z1{:2d+vFs@KjkvF;_
```
**[Try it online!](https://tio.run/nexus/pushy#@x9lWG1llKJd5lbs4J2VXeZmHf///38jAwMA "Pushy – TIO Nexus")**
It's not the most elegant of programs, but it works.
```
Z1 \ Push 0 and 1 to begin the sequence
{: \ Input times do:
2d+ \ Add the last two terms
vF \ Send to second stack
s \ Split into digits
@Kjk \ Reverse and join into one number
vF; \ Send back to first stack
_ \ At the end of the program, print the whole stack.
```
[Answer]
# R, 134 bytes
```
i=function(n){s=c(0,1);for(i in 3:n){s[i]=as.numeric(paste0(rev(strsplit(as.character(s[i-2]+s[i-1]),'')[[1]]),collapse=''))};cat(s)}
```
Example:
```
> i(10)
0 1 1 2 3 5 8 31 93 421
```
Would love to see if somebody had a better R alternative than to take your number, make it a string, reverse it and turn it back into a number again.
[Answer]
# Groovy, 70 bytes
```
{r={"$it".reverse() as int};f={n->n<3?1:r(f(n-1))+r(f(n-2))};r(f(it))}
```
---
```
{
r={"$it".reverse() as int}; // Reverse digits, costly using string.
f={n->n<3?1:r(f(n-1))+r(f(n-2))}; // Recursive Iccanobbif implementation.
r(f(it)) // Reverse final output.
}
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Outputs the `n`th element, 0-indexed.
```
@Zä+ Ìsw}g
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QFrkKyDMc3d9Zw&input=MTc)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
0+ṚV$¥Ð¡1
```
[Try it online!](https://tio.run/##y0rNyan8/99A@@HOWWEqh5YennBooeH///8NzQE "Jelly – Try It Online")
] |
[Question]
[
We've already got a [meta-regex-golf problem](https://codegolf.stackexchange.com/q/17718/2180) as inspired by the xkcd comic

But, this regex golf looks fun, too! I want to distinguish between the states of the US and the regions of Italy. Why? I'm a citizen of both countries, and I always have trouble with this\*.
The regions of Italy are
```
Abruzzo, Valle d'Aosta, Puglia, Basilicata, Calabria, Campania, Emilia-Romagna, Friuli-Venezia Giulia, Lazio, Liguria, Lombardia, Marche, Molise, Piemonte, Sardegna, Sicilia, Trentino-Alto Adige/Südtirol, Toscana, Umbria, Veneto
```
and the states of the USA are
```
Alabama, Alaska, Arizona, Arkansas, California, Colorado, Connecticut, Delaware, Florida, Georgia, Hawaii, Idaho, Illinois, Indiana, Iowa, Kansas, Kentucky, Louisiana, Maine, Maryland, Massachusetts, Michigan, Minnesota, Mississippi, Missouri, Montana, Nebraska, Nevada, New Hampshire, New Jersey, New Mexico, New York, North Carolina, North Dakota, Ohio, Oklahoma, Oregon, Pennsylvania, Rhode Island, South Carolina, South Dakota, Tennessee, Texas, Utah, Vermont, Virginia, Washington, West Virginia, Wisconsin, Wyoming
```
Your job is to write a program which distinguishes these lists with a regular expression. This is a new game, so here's the
**Rules**
* Distinguishing between lists must be done with a single matching regular expression.
* Your score is the length of that regular expression, smaller is better.
To be clear: all work must be done by the regular expression -- no filtering, no replacements, no nothing... even if those are also done with regular expressions. That is, the input should be passed directly into a regular expression, and only the binary answer (match / no match) can be used by later parts of the code. The input should never be inspected or changed by anything but the matching expression. *Exception*: eating a newline with something akin to Ruby's `chomp` is fine.
Your program should take a single entry (optionally followed by `\n` or `EOF` if it makes things easier) from either list from stdin, and print to stdout the name of that list. In this case, our lists are named `Italy` and `USA`.
To test your code, simply run both lists through it. Behavior may be undefined for strings which do not occur in the list.
**Scoring Issues**
This might have to be done on a language-by-language basis. In Perl,
```
m/foobarbaz/
```
is a matching regular expression. However, in Python,
```
import re
re.compile('foobarbaz')
```
does the same thing. We wouldn't count the quotes for Python, so I say we don't count the `m/` and final `/` in Perl. In both languages, the above should receive a score of 9.
To clarify a point raised by [Abhijit](https://codegolf.stackexchange.com/users/7638/abhijit), the actual length of the matching expression is the score, even if you generate it dynamically. For example, if you found a magical expression `m`,
```
n="foo(bar|baz)"
m=n+n
```
then you should not report a score of 12: `m` has length 24. And just to be extra clear, the generated regular expression can't depend on the input. That would be reading the input before passing it into the regular expression.
**Example Session**
```
input> Calabria
Italy
input> New Hampshire
USA
input> Washington
USA
input> Puglia
Italy
```
\* Actually, that's a lie. I have never had any trouble with this at all.
[Answer]
# Perl - ~~51~~ 36 bytes (for regex)
```
print<>=~/.A|ise|net|te|z.o|[cp]a|[lr]ia|r[cd]/?"Italy
":"USA
"
```
~~Nothing special, but may as well post it, because it's different to other 51 bytes solution.~~
Or alternatively, shorten my already short solution by 15 bytes. This wins for now, I think.
[Answer]
## Perl, 40 chars
Approaching this from the other direction, i.e. matching the U.S. states:
```
[DNIOWy]|ss|M.n|^A.*a|or|[aguh]i|[sth]\b
```
The only Perl/PCRE-specific feature in the regexp is the `\b` word boundary anchor, which I used instead of the `$` end-of-string anchor to let it match "South Carolina".
Here's the regexp in a Perl one-liner for testing:
```
perl -nE 'say /[DNIOWy]|ss|M.n|^A.*a|or|[aguh]i|[sth]\b/ ? "USA" : "Italy"'
```
[Answer]
# Regex ([POSIX ERE](https://en.wikibooks.org/wiki/Regular_Expressions/POSIX-Extended_Regular_Expressions)), 28 bytes
Matching the regions of Italy:
```
[eldrz]..$|[cpVS]a|-|[hst]e$
```
[Try it online!](https://tio.run/##TVPbTttAEH3ufsUKRaR9MFVfCzykoUAKAYQhqIqiauKd2qOsd9LdNSGWP61v/bB01qEXy9KeueyZOTP2EkK18whGZ97o4VD7k5Pht9dnuJujNb5dHB0NunmxnuUL6LJuXoW4wMHuT5raVGRRT87zU/1KpW3XzXXm9MHAHujFsWH1RuxWD4JedB0WFR@H0w/HvW@f03Vvk7u3Oiw9rnX2A8X0B/rwUPcxIZxEsNuP@ztd99f9mI/2znfKsMPdaOmbtmU1AyutmeGIQwR115SWQH2CQJYKEM8YLCw9JVCvwQn4XEsMsnuuoXSgzj01lrIZOmwJ9EWyQF1DS6yuqWzS3Wuul@CNoCn4okI1ZUsB1R1hzS6iyiWKiS2nIrGrB48ukuNsZCPrkaES3@e/fppInq164FCAZD/WfWupdmSlRtIq1JDOsJLDU8sunStwAULSQt/ZJxFjtuxBpj5m57CIVDRRnaGFDXhU5xIkA@oC2ZeSfSluIjUxULGaWCuNUVATJ4qEf8IbUFf7ElfSdlOstiK5odCHp0AOk/CtBWcEhABF1QSMMagpFRWV4ARIH4Fl4lMKIb3rNfWYZYQyMBcT2Q0ufS/uBp/BpGOjL2UzoSLpO1lf0Afc9nCKL1RwD7@yX6kb9rHSY5ARUuLqzTNYpaq3lezrdmVFoUzw1mPJTt2hc2Frn/u931ds5CMOvYqcm/@p9uYr1QMmKQFR0IvM5DFCJTvyadVqRjLRRPckPxa5MkqZJwxR/wtQKNgFEv@Wa0n5DQ "Bash – Try It Online")
Since we're being scored on the length of the pure regex, it just makes sense to show that alone above. The TIO test harness uses bash and egrep, but practically any regex engine would work. The only thing that makes this require POSIX ERE instead of POSIX BRE are the unescaped `|` alternative separators. Here is a bash oneliner to apply it:
```
egrep -q '[eldrz]..$|[cpVS]a|-|[hst]e$'&&echo Italy||echo USA
```
I used [regexp-golf-coffeescript](https://github.com/amitayd/regexp-golf-coffeescript.git), with a little parameter tuning, to brute-force this.
You can experiment with deleting characters from the character classes or deleting alternatives in the TIO to see how many correct matches are lost by doing so. For many, it's just one each.
There may be further optimization possible. The script I used only searches the space in which a single character class is used per alternative, but some regex golf problems of this type benefit from multiple character classes in a single alternative, like `[bgr].[ei]`. However, given the characteristics of this data set, I expect that the benefit, if any, would probably be no more than a couple bytes.
# Regex ([POSIX ERE](https://en.wikibooks.org/wiki/Regular_Expressions/POSIX-Extended_Regular_Expressions)), 41 bytes
Matching the states of the USA:
```
[IfKNOWwhy]..|[kamed].$|t$|iz|ta.|[guaM]i
```
[Try it online!](https://tio.run/##TVPbbtswDH2evkIogmV7SIe9ru1Dlq6t1zopml4wFMHA2KxNWBYzSW5qw5@2t31YRjndxTCgw4sOeUh7Db7cOYRcT1yux2Ptjo/H31@f8e4xebqcLx62Zbs6POwfK6gxXx2O@jDqqesDiK9oIF3R7s8dtS3JoE7Olif6lVebvn/UE6sPRuZAr45yVm/E7vTI61XfY1bykT/5eDT49jl9/y66B6vHwuFGT36gmO5Av32rh5gQ3i2nn/Y3@v6vMwlg2r37vcrZ4m66dk3XsboHI63l4yn7AOq6KQyB@gyeDGUgnhkYWDuKoN6AFfCllhhMbriGwoI6c9QYmtyjxY5An0cL1BV0xOqKiibeveJ6DS4XlILLSlQpG/KorglrtgHVUqIY2ZaURXZ169AGsjyZmsB6mlOBH5a/fuaBHBt1yz4Dyb6rh9Zi7cBKTaVVqCGevpLDUcc2nhVYDz5qoSd2UcSMDTuQqc/YWswCZU1Qp2hgCw7VmQQpB3WO7ArJvhA3kUpyKFklxkhj5FViRZHwJ7wFdbkvcSltN1nViuSG/BBOgSxG4a0BmwvwHrKy8RiCVyllJRVgBUgfnmXiKXkf382GBswyQhmYDZFsjms3iJvjM@Tx2OoL2YwvSfqO1ld0HtsBpvhCGQ/wG7tKzdmFUs9ARkiRazBPoYpVF6Xsa1EZUSgTXDgs2KprtNa35nnY@03JuXzEflCx5OZ/qr35SnWLUYpHFPQiM7kLUMqOXFy1uieZaKR7kL@MbBGkzAP6oP8FyGdsPYm/5VpSfgM "Bash – Try It Online")
[Answer]
# Ruby (plain regex), 44
```
$_ = gets.chomp
puts /'|-|(([^gn]i|gn|at)a|[hst]e|to|zo)$|To|La|pa/ ? "Italy" : "USA"
```
You know what? Case sensitivity is the best start-of-word anchor.
I'm not sure, but I think I owe the `pa` to [Hax0r778's answer](https://codegolf.stackexchange.com/a/17859/7209).
[Answer]
## Perl - 51
```
(<STDIN> =~ m/'|-|ru|pu|at|pa|az|gu|mb|rc|ie|rd|ci|os|abr|mol|ven/)?printf("Italy\n"):printf("USA\n");
```
[Answer]
# JavaScript 42
`alert(/at|gn|mp|sc|-|'|((zi?|t)o|[hts]e|[lrd]ia)$/g.test(prompt())?"Italy":"USA")`
I was initially going to work this out from the USA side, as eliminating KWXY from the USA list strips a lot of the States away... But Italy had it bested by a good 17 characters...
If we go with fat arrow notation we can reduce this to a simple function with a return variable.
`r=s=>/at|gn|mp|sc|-|'|((zi?|t)o|[hts]e|[lrd]ia)$/g.test(s)?"Italy":"USA"`
```
> r("South Dakota") // USA
> r("Puglia") // Italy
```
] |
[Question]
[
Halloween is almost here, the holiday after which most people need to wean themselves off a hollow diet of sugar.
Write a program that takes in a positive integer. If the integer is less than 31 (1 through 30), output this ASCII-art jack-o'-lantern, looking to the right as if looking forward to Halloween:
```
_____I_____
| | | | | | |
| | |^| |^| |
| | | |^| | |
| | |VvVvV| |
|_|_|_|_|_|_|
```
If the input *is* 31 (the October date Halloween is on), output the same ASCII-o'-lantern, but looking left:
```
_____I_____
| | | | | | |
| |^| |^| | |
| | |^| | | |
| |VvVvV| | |
|_|_|_|_|_|_|
```
If the input is greater than 31, output a bloated-looking ASCII-o'-lantern who probably ate too much candy. He can face either left or right since queasyness can be disorientating. So output:
```
_____I_____
| | | | | | |
| |o| |o| | |
| | |^| | | |
| |XXXXX| | |
|_|_|_|_|_|_|
```
*or*
```
_____I_____
| | | | | | |
| | |o| |o| |
| | | |^| | |
| | |XXXXX| |
|_|_|_|_|_|_|
```
Whichever you prefer. It may even be different for different numbers above 31.
**The shortest code in bytes wins.**
[Answer]
# [아희(Aheui)](http://esolangs.org/wiki/Aheui), 914 bytes
```
붕빠뿌빠삮빠싸빠받따싼사주따반따퍄속맣이
숚뽀빠소뚜번범뻐터번선야챠슊산받발따다뿌
분뽀더번투빠뿌삮뿌다뿌쑬섣뽀빠뼈ㅇ뚜범쑬
받발따또싾솒빠쏟싿솓아삲쏠쑧뽀터벋터볼설
뿌뻐뻐뻐선썬뻐퍼섟썫선뻐퍼샧셗뺘쎣뺘뼈선
받따반타파빠빠받따받반타타싾삲빠빠빠빠뿌
숟썭뻐선썭뻐섣썭뻐선썭뻐섣썯터범떠범뻐선
빠싽술빠싽산빠싽삳빠싽숟삮쎨뿌서탸쥬싸셔
쀼이썭솓쀼섣싻이연우섞빠쏠뱐선반노쌹뻐숛
손빠쓞유삯쏢으산뽀쌹쏡야뼈섣싺이셗처솓썱
아솓썲솑쏢삱쏜빠쌄숞뚜범범섩뻐분터뿌뻐튜
번이손쎫ㅇ야샨우쌃이쀼뱔뿌떠뽀투또뿌뽀노
본떠벋뻐떠번떠숃볌쎬볌섩뿌빠뽀펴봄벌뽀뻐
샯이멓삭뭏ㅇㅇ이멓샥뎌뵥뿌븀범이멓삭뭏맣
맣이ㅇ몋섨희ㅇㅇㅇㅇㅇ먛뻐살뽀ㅇ솕멓샮속
```
[Try it here! (please copy and paste the code manually)](http://jinoh.3owl.com/aheui/jsaheui_en.html)
Aheui might not be for golfing, but it's fun nonetheless. :)
**Outputs:**
N = 10
```
_____I_____
| | | | | | |
| | |^| |^| |
| | | |^| | |
| | |VvVvV| |
|_|_|_|_|_|_|
```
N = 31
```
_____I_____
| | | | | | |
| |^| |^| | |
| | |^| | | |
| |VvVvV| | |
|_|_|_|_|_|_|
```
N = 40
```
_____I_____
| | | | | | |
| |o| |o| | |
| | |^| | | |
| |XXXXX| | |
|_|_|_|_|_|_|
```
[Answer]
# JavaScript (ES6), ~~185~~ ~~142~~ ~~140~~ 136 bytes
Now you can tweet-a-pumpkin!
```
n=>` _____I_____
0 4 1
02421
0 |^| 1
031
|_|_|_|_|_|_|`.replace(/\d/g,x=>x-2?x-3?x^n>30?"| |":"| | |":n>31?"XXXXX":"VvVvV":n>31?"o":"^")
```
Probably still room for improvement...
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 73 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
“ẋƥḷỊKNṇ&JƝ¡'Ɲṣ,c;|Ṙɗ.hṿ#⁴ɠ³Ṙṅ’b8ị“ I|o^Xv_”
<32ị“o^XV“vX”y¢s13µ¹U31=³¤?Y
```
Full program
**[TryItOnline!](http://jelly.tryitonline.net/#code=4oCc4bqLxqXhuLfhu4pLTuG5hyZKxp3CoSfGneG5oyxjO3zhuZjJly5o4bm_I-KBtMmgwrPhuZjhuYXigJliOOG7i-KAnCBJfG9eWHZf4oCdCjwzMuG7i-KAnG9eWFbigJx2WOKAnXnConMxM8K1wrlVMzE9wrPCpD9Z&input=&args=MzE)**
Might be possible to golf this with the aid of bounce, `ŒḄ`.
### How?
```
“ẋƥḷỊKNṇ&JƝ¡'Ɲṣ,c;|Ṙɗ.hṿ#⁴ɠ³Ṙṅ’b8ị“ I|o^Xv_” - Link 1, Jack construction
“ẋƥḷỊKNṇ&JƝ¡'Ɲṣ,c;|Ṙɗ.hṿ#⁴ɠ³Ṙṅ’ - a base 250 integer
b8 - convert to base 8
ị - index into
“ I|o^Xv_” - literal " I|o^Xv_"
- makes this, without the line feeds:
_____I_____
| | | | | | |
| |o| |o| | |
| | |^| | | |
| |XvXvX| | |
|_|_|_|_|_|_|
<32ị“o^XV“vX”y¢s13µ¹U31=³¤?Y - Main link: n
<32 - 1 if n is less than 32 else 0
ị - index into
“o^XV“vX” - list of strings, ["o^XV","vX"]
y - map those characters (o->^ and X->V OR v->X) in string:
¢ - call last link (1) as a nilad
s13 - split into chunks of length 13
µ - monadic chain separation
? - ternary if:
¤ - nilad and links as a nilad
31=³ - 31 equals first argument
¹ - identity (do nothing if true)
U - upend (reverse each if false)
Y - join with line feeds
```
[Answer]
# Ruby, 137 bytes
Face points left on and after the 31st.
```
->n{puts ' _____I_____',(0..4).map{|i|s=[?|]*7*' _'[i/4]
s[5-n/31*2,5]=' | | o| |o |^| VvVvV_|_|_'[i*5,5];s.tr('ovV','^vVoX'[n/32*3,3])}}
```
**Ungolfed in test program**
```
f=->n{
puts ' _____I_____', #Draw top of pumpkin
(0..4).map{|i| #then 5 more lines
s=[?|]*7*' _'[i/4] #of 7 | separated by space or _ .
s[5-n/31*2,5]=' | | o| |o |^| VvVvV_|_|_'[i*5,5] #Add a line of face with 'o' eyes and 'VvVvV' mouth.
s.tr('ovV','^vVoX'[n/32*3,3]) #Substitute characters as necessary.
}
}
f[gets.to_i]
```
[Answer]
# Pyth - 84 bytes
Manual base compression.
```
+dj\Im*5\_2Xjb@_MBsMc5@L"^|_V ve"jC"mËÝ8|0càvll+DzSïë¬Ê"7qQ31"Vve"?>Q31"XXo""Vv^
```
[Test Suite](http://pyth.herokuapp.com/?code=%2Bdj%5CIm%2a5%5C_2Xjb%40_MBsMc5%40L%22%5E%7C_V+ve%22jC%22%14m%C3%8B%C3%9D8%7C0%1Cc%C2%8D%C3%A0vll%2B%C3%87%C2%B2S%C3%AF%C3%AB%C2%AC%C3%8A%C2%88%227qQ31%22Vve%22%3F%3EQ31%22XXo%22%22Vv%5E&test_suite=1&test_suite_input=30%0A31%0A32&debug=0).
[Answer]
# PHP, ~~178~~ ~~176~~ 171 bytes
```
$e="| | ";$b=($n=$argv[1]-31)?" |^":"^| ";$c=$n<1?VvVvV:XXXXX;$a=$n<1?$b:" |o";echo" _____I_____\n$e$e$e|\n| |$a|$a$e\n$e|$b$e|\n| |",$n?" |$c":"$c| ","$e\n|_|_|_|_|_|_|";
```
could save 5 bytes with physical linebreaks. Run with `-r`.
[Answer]
## [Charcoal](http://github.com/somebody1234/Charcoal), 71 bytes
```
NβA‹β³²τA§o^τεA§XVτφA§XvτθF³«P↑⁵|_»↑⁵←I←×_⁵‖O→↙↙←←ε↙←^↖↓ε↓→φθφθφ¿⁼β³¹‖←
```
**Note**: This code does not work in the most recent commit as of posting, because string indexing is broken. It should, however, work in [this version](https://github.com/somebody1234/Charcoal/commit/a148001cce2b2e4eb46fb56b03503b4de922d3fc) from October 25. It also runs successfully on the version currently on [Try It Online](http://charcoal.tryitonline.net/#code=77yuzrLvvKHigLnOssKzwrLPhO-8ocKnb17PhM6177yhwqdYVs-Ez4bvvKHCp1h2z4TOuO-8psKzwqvvvLDihpHigbV8X8K74oaR4oG14oaQSeKGkMOXX-KBteKAlu-8r-KGkuKGmeKGmeKGkOKGkM614oaZ4oaQXuKGluKGk8614oaT4oaSz4bOuM-GzrjPhsK_4oG8zrLCs8K54oCW4oaQ&input=MzA).
### Explanation
Charcoal is a language designed for ASCII-art. Output is put onto a canvas, which is printed at the end of the program.
**Setup**
Get input and calculate face characters:
```
Nβ Input number into beta
A‹β³²τ Assign beta<32 to tau for easy reuse
A§o^τε Assign appropriate eye character (selected via indexing into "o^") to epsilon
A§XVτφ Assign outside and middle mouth character to phi
A§Xvτθ Assign other mouth character to theta
```
**Draw the pumpkin**
```
F³« » Do this three times:
P↑⁵ Draw a 5-character line upward (using | by default); don't move the cursor
|_ Draw that string, rightward
```
After this loop, we have
```
| | |
| | |
| | |
| | |
|_|_|_
```
Next:
```
↑⁵ Draw a 5-character line upward
←I Draw the stem leftward
←×_⁵ Draw 5 underscores leftward
‖O→ Reflect the canvas rightward, overlapping in the middle
```
Result:
```
_____I_____
| | | | | | |
| | | | | | |
| | | | | | |
| | | | | | |
|_|_|_|_|_|_|
```
**Draw the face**
We will draw the face looking rightward and change it later if necessary.
```
↙↙←←ε Move to the correct spot and draw the right eye (our right, pumpkin's left)
↙←^ Move to the correct spot and draw the nose
↖↓ε Move to the correct spot and draw the left eye
↓→φθφθφ Move to the correct spot and draw the mouth with alternating characters
```
Result (for input `31`):
```
_____I_____
| | | | | | |
| | |^| |^| |
| | | |^| | |
| | |VvVvV| |
|_|_|_|_|_|_|
```
Reflect if it's Halloween:
```
¿⁼β³¹ If beta equals 31:
‖← Reflect canvas leftward
```
Final output:
```
_____I_____
| | | | | | |
| |^| |^| | |
| | |^| | | |
| |VvVvV| | |
|_|_|_|_|_|_|
```
[Answer]
# [V](http://github.com/DJMcMayhem/V), 97 bytes
```
é|6i| Y5PÒ_r $.7|rIGÓ /_
3G3f r^jll.kll.5G3f RVvVvVLá
Àé*ñ30|l2GGkld$PñGñ31|l3GÓÞ/o
5GÓãv/Xñͪ
```
[Try it online!](http://v.tryitonline.net/#code=w6l8Nml8IBtZNVDDkl9yICQuN3xySUfDkyAvXwozRzNmIHJeamxsLmtsbC41RzNmIFJWdlZ2VhtMw6EKw4DDqSrDsTMwfGwyRxZHa2xkJFDDsUfDsTMxfGwzR8OTw54vbwo1R8OTw6N2L1jDscONwqo&input=&args=MzA)
I'm dissapointed with how long this turned out. It is more convoluted than usual since V can barely handle numbers, a *lot* of bytes come from creating hacky conditionals. I would post a detailed explanation, but it took a long time to come up with, so I might get around to it later. Here is a hexdump:
```
0000000: e97c 3669 7c20 1b59 3550 d25f 7220 242e .|6i| .Y5P._r $.
0000010: 377c 7249 47d3 202f 5f0a 3347 3366 2072 7|rIG. /_.3G3f r
0000020: 5e6a 6c6c 2e6b 6c6c 2e35 4733 6620 5256 ^jll.kll.5G3f RV
0000030: 7656 7656 1b4c e10a c0e9 2af1 3330 7c6c vVvV.L....*.30|l
0000040: 3247 1647 6b6c 6424 50f1 47f1 3331 7c6c 2G.Gkld$P.G.31|l
0000050: 3347 d3de 2f6f 0a35 47d3 e376 2f58 f1cd 3G../o.5G..v/X..
0000060: aa .
```
FYI this will run *very* slowly. It will take about 10 seconds. I know why this happens, and I'm looking into fixes.
[Answer]
# Pyth, 76 bytes
```
+dX*11\_5\IjbmX.<.[14d"| "yqQ31<G3?>Q31"XXo""Vv^"c"
|c| |c
|^
|ababa"bt*7"_|
```
[Try it online.](http://pyth.herokuapp.com/?code=%2BdX%2a11%5C_5%5CIjbmX.%3C.%5B14d%22%7C+%22yqQ31%3CG3%3F%3EQ31%22XXo%22%22Vv%5E%22c%22%0A%7Cc%7C+%7Cc%0A%7C%5E%0A%7Cababa%22bt%2a7%22_%7C&input=30&test_suite_input=30%0A31%0A32&debug=0)
Uses no compression. (I tried using some to a version of the face data string, but it ended up the same length.)
[Answer]
# Java 7, 237 bytes
```
String c(int n){char a=n==31?94:n>31?'o':32,b=n<31?'^':32;return(" _____I_____ \n~~~~~~|\n~|"+a+"|"+b+"|"+a+"|"+b+"~|\n~~|"+(n>31?94:a)+"|"+b+"~~|\n~"+(n<31?"~|VvVvV|":n==31?"|VvVvV~|":"|XXXXX~|")+" |\n|_|_|_|_|_|_|").replace("~","| ");}
```
**Ungolfed & test code:**
[Try it here.](https://ideone.com/VPs8Os)
```
class M{
static String c(int n){
char a = n == 31
? 94
: n > 31
? 'o'
: 32,
b = n < 31
? '^'
: 32;
return (" _____I_____ \n~~~~~~|\n~|"+a+"|"+b+"|"+a+"|"+b+"~|\n~~|"
+(n > 31
? 94
:a)
+"|"+b+"~~|\n~"
+(n < 31
? "~|VvVvV|"
: n == 31
? "|VvVvV~|"
: "|XXXXX~|")
+" |\n|_|_|_|_|_|_|")
.replace("~", "| ");
}
public static void main(String[] a){
System.out.println(c(12));
System.out.println();
System.out.println(c(31));
System.out.println();
System.out.println(c(100));
}
}
```
**Output:**
```
_____I_____
| | | | | | |
| | |^| |^| |
| | | |^| | |
| | |VvVvV| |
|_|_|_|_|_|_|
_____I_____
| | | | | | |
| |^| |^| | |
| | |^| | | |
| |VvVvV| | |
|_|_|_|_|_|_|
_____I_____
| | | | | | |
| |o| |o| | |
| | |^| | | |
| |XXXXX| | |
|_|_|_|_|_|_|
```
[Answer]
# C++, ~~222~~ ~~204~~ 194 bytes
-18 bytes thanks to Kevin Cruijssen and -10 bytes for explicit top part
```
using S=std::string;S f(int n){char L[80],o=2*(n>30),i=-1;while(i++<80)L[i]=47<i&i<53?88:i%2?'|':i==20|i==24|i==36?n<32|i>35?94:'o':(i-o)%14?i-o<55?32:95:10;return" _____I_____ "+S(L+o,L+70+o);}
```
Ungolfed
```
#include <string>
using S=std::string;
S f(int n){
char L[80];
int o=2*(n>30);
for (int i=0;i<80;i++){
L[i]=
(47<i && i<53) ?
'X' :
(
(i%2) ?
'|' :
(
i==20||i==24||i==36 ?
(n<32||i>35?'^':'o') :
((i-o)%14?(i-o<55?' ':'_'):'\n')
)
);
}
return " _____I_____ " + S(L+o,L+70+o);
}
```
[Answer]
# PHP, 222 Bytes
```
for($s=" ".str_pad("I",11,_,2)." \n";$i<5;$i++)$s.=str_pad("",13,$i<4?"| ":"|_")."\n";$p=($a=$argv[1])<31||!($a%2)?2:0;$s=substr_replace($s,$a>31?XXXXX:VvVvV,$p+59,5);$s[$p+31]=$s[$p+35]=($a>31?o:"^");$s[$p+47]="^";echo$s;
```
## Output
```
input:29
_____I_____
| | | | | | |
| | |^| |^| |
| | | |^| | |
| | |VvVvV| |
|_|_|_|_|_|_|
input:30
_____I_____
| | | | | | |
| | |^| |^| |
| | | |^| | |
| | |VvVvV| |
|_|_|_|_|_|_|
input:31
_____I_____
| | | | | | |
| |^| |^| | |
| | |^| | | |
| |VvVvV| | |
|_|_|_|_|_|_|
input:32
_____I_____
| | | | | | |
| | |o| |o| |
| | | |^| | |
| | |XXXXX| |
|_|_|_|_|_|_|
input:33
_____I_____
| | | | | | |
| |o| |o| | |
| | |^| | | |
| |XXXXX| | |
|_|_|_|_|_|_|
input:34
_____I_____
| | | | | | |
| | |o| |o| |
| | | |^| | |
| | |XXXXX| |
|_|_|_|_|_|_|
input:35
_____I_____
| | | | | | |
| |o| |o| | |
| | |^| | | |
| |XXXXX| | |
|_|_|_|_|_|_|
```
[Answer]
## Groovy Script, ~~273~~ ~~265~~ ~~216~~ ~~202~~ 198 bytes
```
i=args[0]as int
a=i<32?'^| |^':'o| |o'
b=i<32?'VvVvV':'XXXXX'
j=i>30
print" _____I_____\n| | | | | | |\n| |${j?"$a| ":" |$a"}| |\n| | |${j?'^| ':' |^'}| | |\n| |${j?"$b| ":" |$b"}| |\n|_|_|_|_|_|_|"
```
Ungolfed version
```
i = args[0] as int
a = i < 32 ? '^| |^' : 'o| |o'
b = i < 32 ? 'VvVvV' : 'XXXXX'
j = i > 30
print """ _____I_____
| | | | | | |
| |${j ? "$a| " : " |$a"}| |
| | |${j ? '^| ' : ' |^'}| | |
| |${j ? "$b| " : " |$b"}| |
|_|_|_|_|_|_|"""
```
[Try it here](https://goo.gl/AVB3XS)
### Edit
As Titus mentioned, I can save some size with `i < 32` instead of `i in 1..31`
### Edit 2
Removed all possible spaces around operators... Forgot to do so in the beginning
### Edit 3
Rewrote ternary conditions to use the saved variable, replaced `;` with newlines, removed explicit variable definition
### Edit 4
As Otávio mentioned, I can save another 4 bytes if I switch from `| |${j ? ' |^| | ' : ' | |^| '}| |` to `| | |${j ? '^| ' : ' |^'}| | |`
[Answer]
## JavaScript (ES6), ~~163~~ 125 bytes
```
f=
n=>` _____I_____
3 5 4
30504
3 |^| 4
3121214
|_|_|_|_|_|_|`.replace(/\d/g,c=>(n>31?`oXX`:`^Vv`)[c]||(c-3^n>30?`| |`:`| | |`))
;
```
```
<input type=number oninput=o.textContent=f(this.value)><pre id=o>
```
Now shamelessly stealing @ETHproduction's trick for positioning the face. Encoding: `0` is an eye, `1` and `2` are teeth, `3` is the left side, `4` is the right side and `5` is the bridge of the nose.
[Answer]
## Ruby, 168 bytes
```
->i{s=(Zlib.inflate Base64.decode64 "eJxTiAcBTzDJVaOABCG8OCiGycUhyYWVASGYF48EuRTwGhmHZkgckhzMQBKNzIdibEZGgAA2IwFZA1N4").lines;puts i<31?s[0..5]:i<32?s[6..11]:s[12..17]}
```
Probably far from optimal. Requires the `base64` and `zlib` libraries.
Call as a lambda function.
[Answer]
# Python 2, 167 bytes
```
i=input()
b='| |';e='^o'[i>31]+b;print'\n'.join(x[::[1,-1][i>30]]for x in[' _____I_____ ','| '*5+b,b+' |'+e+e,b+' | |^| '+b,b+' |'+['VvVvV','X'*5][i>31]+b,'|_'*6+'|'])
```
[Answer]
## C# 6, 223 215 bytes
`int d=int.Parse(args[0]);var x="| | |\n| |";var s=d<31?" |^| |^| |\n| | | |^"+x+" |VvVvV":(d==31?"^| |^"+x+" |^| "+x+"VvVvV| ":"o| |o"+x+" |^| "+x+"XXXXX| ");Write(" _____I_____\n| | | | "+x+s+"| |\n|_|_|_|_|_|_|");`
Entire program ungolfed:
```
using static System.Console;
namespace Halloween
{
public class Program
{
public static void Main(string[] args)
{
int d = int.Parse(args[0]);
var x = "| | |\n| |";
var s = d < 31 ? " |^| |^| |\n| | | |^" + x + " |VvVvV"
: (d == 31 ? "^| |^" + x + " |^| " + x + "VvVvV| "
: "o| |o" + x + " |^| " + x + "XXXXX| ");
Write(" _____I_____\n| | | | " + x + s + "| |\n|_|_|_|_|_|_|");
}
}
}
```
] |
[Question]
[
In [Minecraft](http://en.wikipedia.org/wiki/Minecraft), the [default item textures](https://i.stack.imgur.com/mbk6q.png) are all reasonably simple 16×16 pixel images, which makes them seem ideal for [golfing](http://en.wikipedia.org/wiki/Code_golf).
Below are simplified textures of the five "core" diamond tools in Minecraft: [pickaxe](http://minecraft.gamepedia.com/Pickaxe), [shovel](http://minecraft.gamepedia.com/Shovel), [axe](http://minecraft.gamepedia.com/Axe), [sword](http://minecraft.gamepedia.com/Sword), and [hoe](http://minecraft.gamepedia.com/Hoe).
**The images shown are enlarged to show their detail. Click on an image to view its correctly sized 16×16 pixel version.**
[](https://i.stack.imgur.com/tMLhy.png) [](https://i.stack.imgur.com/xqFA2.png) [](https://i.stack.imgur.com/51TKK.png) [](https://i.stack.imgur.com/7vXjE.png) [](https://i.stack.imgur.com/hc3zB.png)
To make golfing easier, I've modified each of them from [the originals](https://i.stack.imgur.com/zOWJm.png) to only use the five same 24-bit RGB colors:
* `R=75 G=82 B=73` for the background.
* `R=51 G=235 B=203` for the diamond tool heads.
* `R=14 G=63 B=54` for the diamond outlines.
* `R=137 G=103 B=39` for the wooden handle core.
* `R=40 G=30 B=11` for the wooden handle outlines.
Choose your favorite tool out of the five and write a program that outputs its simplified 16×16 pixel texture in any common lossless truecolor image format (such as `bpm`, `png`, `ppm`, etc.).
So, for example, if you chose the axe, you would write a program that outputs this image: 
No input should be taken and a web connection should not be required. The image can be output as a file with the name of your choice, or the raw image file data can be output to stdout, or you can simply display the image.
You only need to choose *one* of the five images. **The program that outputs any one of the five images in the fewest number of bytes is the winner.**
You may write programs for more than one of the images, but only the one with the minimum number of bytes counts towards your score. If there's a tie, the highest voted post wins.
---
*If you enjoy [PPCG](https://codegolf.stackexchange.com/) and play Minecraft, I invite you to come join our trial Minecraft server. Just ask in [the dedicated chatroom](http://chat.stackexchange.com/rooms/24544/ppcg-minecraft-server).*
[Answer]
# Minecraft 18w11a (.mcfunction), 757 bytes
```
fill ~ ~ ~ ~15 ~ ~15 ice
fill ~13 ~ ~13 ~7 ~ ~11 cyan_wool
fill ~12 ~ ~14 ~10 ~ ~8 cyan_wool
fill ~12 ~ ~13 ~10 ~ ~11 diamond_block
fill ~11 ~ ~12 ~9 ~ ~10 diamond_block
fill ~10 ~ ~11 ~8 ~ ~9 diamond_block
fill ~3 ~ ~4 ~1 ~ ~2 dirt
setblock ~3 ~ ~4 oak_planks
setblock ~2 ~ ~3 oak_planks
clone ~3 ~ ~4 ~1 ~ ~2 ~4 ~ ~5
setblock ~4 ~ ~5 oak_planks
setblock ~4 ~ ~7 ice
setblock ~6 ~ ~5 ice
clone ~6 ~ ~5 ~4 ~ ~7 ~7 ~ ~8
setblock ~9 ~ ~10 diamond_block
setblock ~4 ~ ~4 dirt
setblock ~3 ~ ~5 dirt
setblock ~7 ~ ~7 dirt
setblock ~6 ~ ~8 dirt
setblock ~1 ~ ~2 ice
fill ~12 ~ ~9 ~12 ~ ~8 ice
setblock ~11 ~ ~8 ice
fill ~8 ~ ~13 ~7 ~ ~13 ice
setblock ~7 ~ ~12 ice
fill ~ ~ ~ ~15 ~ ~15 light_gray_concrete replace ice
fill ~ ~ ~ ~9 ~ ~10 dark_oak_bark replace dirt
```
Of course someone had to answer the question with Minecraft. Place answer inside of a datapack, and run with `/function <packname>:<filename>`. The shovel is drawn relative to you in the +X and +Z direction. Colors are wrong but I'll count that as a language limitation ;)
But the shovel is actually made out of wood and diamonds!!!!
## Output
[](https://i.stack.imgur.com/hL2dC.png)
[Answer]
# JavaScript ES6, 353 bytes
```
document.write(`<p style="width:1px;height:1px;box-shadow:${'931a31b31841940a40b40c41951a51b50c50d51e53f52b61c60d60e62f63c73d70e70f71b83c82d83e81a93b92c939a3aa2ba38b39b2ab37c38c29c36d37d28d35e36e27e34f35f26f34g35g3'.replace(/.../g,e=>(p=parseInt)(e[0],17)+`px ${p(e[1],17)}px 0 #${['33EBCB','0E3F36','896727','281E0B'][e[2]]},`)}9px 9px 0 8px #4B5249"`)
```
This heavily abuses CSS3 [box-shadows](https://developer.mozilla.org/en-US/docs/Web/CSS/box-shadow) to create a pixelized version of the image, in this case the Minecraft hoe. The Stack Snippet below uses ES5 for easy testing and is somewhat ungolfed (You'll have to zoom in to see it well).
```
s='931a31b31841940a40b40c41951a51b50c50d51e53f52b61c60d60e62f63c73d70e70f71b83c82d83e81a93b92c939a3aa2ba38b39b2ab37c38c29c36d37d28d35e36e27e34f35f26f34g35g3'.replace(/.../g,function(e){
return parseInt(e[0],17)+'px '+parseInt(e[1],17)+'px 0 #'+['33EBCB','0E3F36','896727','281E0B'][e[2]]+','
})
document.write('<p style="width:1px;height:1px;box-shadow:'+s+'9px 9px 0 8px #4B5249"')
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 119 bytes
```
'P3NGSGN255N]o67T"…vîþáy$<OW¥ÓNZ"256b9b~99T]2/e~W%"LRI?6jêÌ'
…f-":i3/f=F,_W%:)+{)/(\:~}%{G/({)S*S+oNo}%1>\:~+}G*
```
[Try it online!](https://tio.run/##S85KzP3/Xz3A2M892N3PyNTULzbfzDxE6VBr2eF1h/cdXijEwlypYuMffmjp4cn8h@b6RSkZmZolWSbVWVqGxBrpp9aFqyr5BHlK2ZtlHV51uEddjutQa5quklWmsX6arZtOfLiqlaZ2taa@RoxVXa1qtbu@RrVmsFawdr5ffq2qoR1QVLvWXev/fwA "CJam – Try It Online")
I've chosen the shovel.
This program prints a PPM file to STDOUT.
The basic idea is to unroll the image along antidiagonals and then use run-length encoding. With this technique, the shovel contains the fewest runs. For reference the number of runs per image (in the order given in the challenge) is:
```
{60, 26, 38, 43, 37}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~113~~ 97 bytes
*-16 by using RLE (run-length encoding) for the color palette indices.*
```
„P3žvD₅•P{¡æjž²+JGÀ‰íÔñ•Ƶ‡в3ô•N…ý~îc|\мï¶„Ä^€¿^•5⦕RθŪ`<≠cλS²bÖ"₁Þ@„ÉI¬5øëY4ÀΘØ¥P@û h•29вÅΓ蘻»
```
[Try it online!](https://tio.run/##AbcASP9vc2FiaWX//@KAnlAzxb52ROKCheKAolB7wqHDpmrFvsKyK0pHw4DigLDDrcOUw7HigKLGteKAodCyM8O04oCiTuKApsO9fsOuY3xc0LzDr8K24oCew4Re4oKswr9e4oCiNdCywqbigKJSzrjDhcKqYDziiaBjzrtTwrJiw5Yi4oKBw55A4oCew4lJwqw1w7jDq1k0w4DOmMOYwqVQQMO7IGjigKIyOdCyw4XOk8Ooy5zCu8K7//8 "05AB1E – Try It Online") Beats all other answers. Outputs a plain PPM of a diamond hoe.
**Note:** The first `»` can be a `)` (or a `¶`, `ð`, or `õ`) to output the image data separated by spaces: [Try it online!](https://tio.run/##AbYASf9vc2FiaWX//@KAnlAzxb52ROKCheKAolB7wqHDpmrFvsKyK0pHw4DigLDDrcOUw7HigKLGteKAodCyM8O04oCiTuKApsO9fsOuY3xc0LzDr8K24oCew4Re4oKswr9e4oCiNdCywqbigKJSzrjDhcKqYDziiaBjzrtTwrJiw5Yi4oKBw55A4oCew4lJwqw1w7jDq1k0w4DOmMOYwqVQQMO7IGjigKIyOdCyw4XOk8Ooy5wpwrv//w "05AB1E – Try It Online") However, in the [official PPM Format Specification](http://netpbm.sourceforge.net/doc/ppm.html), under [*Plain PPM*](http://netpbm.sourceforge.net/doc/ppm.html#plainppm), it states:
>
> * No line should be longer than 70 characters.
>
>
>
It still renders properly, but is not recommended.
The first `»` can also be a ``` with no change in functionality: [Try it online!](https://tio.run/##AbYASf9vc2FiaWX//@KAnlAzxb52ROKCheKAolB7wqHDpmrFvsKyK0pHw4DigLDDrcOUw7HigKLGteKAodCyM8O04oCiTuKApsO9fsOuY3xc0LzDr8K24oCew4Re4oKswr9e4oCiNdCywqbigKJSzrjDhcKqYDziiaBjzrtTwrJiw5Yi4oKBw55A4oCew4lJwqw1w7jDq1k0w4DOmMOYwqVQQMO7IGjigKIyOdCyw4XOk8Ooy5xgwrv//w "05AB1E – Try It Online")
### Pure GIF compression, ~~109~~ 107 bytes
```
•+Ùι1Ù³œ¤∞4ûи„ĆQ´ηÏzεÝ₅¼úΣ¨ü6Ó…Ï,È–ð:<û∞¢Þ§α»«¥<çp:Ù“ζÞ¢ó‡lÿнδßiÌ$}ªiƒ*₅xΛxJ=yh‹×м’’®']!JͦZ¹JQc›Vàÿ¸Ìм•h2ô
```
[Try it online!](https://tio.run/##FYxPS8JwGMdfSyAE2sWQDmJvYDcvHoIOGoKDoKCLCsKDUHhQBHeIkU5dpaEgyuafuYXwfMvjj72G543Mef78eXoplvRyFAnZKZjKS8Nk59/gL2lZGfjhTsj6e8uzq7bo1tUaA2m@coC9@uQfBDcwhCboXqElZGCZzcGPS7Zh8VSt2Oc5f@cwfc7CFOqrDc7MERo/4hD@KhdDHe1Eg2f6sZeM11X1UdVuaxUhD@9hIBRnJi8u7y80dHhyx56WfxDaFzDCgXdonx27cg03ik4 "05AB1E – Try It Online") Outputs as a list of hexadecimal codepoints.
```
•...•h2ô # trimmed program
•...• # 121686424391392225557581524495943776461362082974476220323034665137613008241067075561955081975776948192923502794622971144661356950543760600319115998403445050769039958830830234731371315671091547736084642764295720991029129326629299863698388004372539...
h # in hexadecimal...
ô # split into pieces of length...
2 # literal
# implicit output
```
[Answer]
# Node.JS using [jimp](https://www.npmjs.com/package/jimp), ~~393~~ ~~377~~ 376 bytes
377, 376 thanks to [Makonede](https://codegolf.stackexchange.com/questions/51556/golf-your-favorite-minecraft-tool#comment516210_222504)
```
new(require('jimp'))(16,16,1263684095,(e,i)=>{i.z=i.setPixelColor;i.z(x=673057791,2,12);i.z(x,4,14);i.z(d=871091199,13,3);for(j=0;j<8;j++){i.z(w=2305239039,3+j,13-j);i.z(x,2+j,13-j);i.z(x,3+j,14-j)}for(j=0;j<3;j++){i.z(e=239023871,11+j,2);i.z(e,14,3+j);i.z(e,8+j,5-j);i.z(d,9+j,5-j);i.z(d,10+j,5-j);i.z(d,10+j,6-j);i.z(d,11+j,6-j);i.z(d,11+j,7-j);i.z(e,11+j,8-j)}i.write('')})
```
I'm not sure if this one is allowed as it uses a separate library for processing the image.
Uses hex colors in decimal, sets `i.s` to `i.setPixelColor` to save bytes, sets color variables as it's first used
[Answer]
## Python 3, 483 bytes
I chose to make the sword
```
from PIL import Image as IG, ImageColor as IC
s=IG.new('RGB',(16,16))
w='#6b6727'
b='#4b5249'
d='#33ebcb'
a='#0e3f36'
n='#281e0b'
t=b*13+a*3+b*12+a+d*2+a+b*11+a+d*3+a+b*10+a+d*3+a+b+b*9+a+d*3+a+b*2+b*8+a+d*3+a+b*3+b*2+a*2+b*3+a+d*3+a+b*4+b*2+a+d+a+b+a+d*3+a+b*5+b*3+a+d+a+d*3+a+b*6+b*3+a+d+a+d*2+a+b*7+b*4+a+d+a*2+b*8+b*3+n+w+a+d*2+a+b*7+b*2+n+w+n+b+a*2+d+a+b*6+a*2+w+n+b*4+a*2+b*6+a+d+a+b*13+a*3+b*13
s.putdata([IC.getrgb(t[i:i+7]) for i in range(0,len(t),7)])
s.save('s.png','PNG')
```
here is the output:
[](https://i.stack.imgur.com/UITsI.png)
I created a string for each color, and combined them to get a string of hexadecimal numbers. Then I used the python image library to convert that string into an image.
[Answer]
# [GIF](https://www.w3.org/Graphics/GIF/spec-gif89a.txt), 102 bytes
Hexdump:
```
00000000: 4749 4638 3961 1000 1000 7000 002c 0000 GIF89a....p..,..
00000010: 0000 1000 1000 824b 5249 0e3f 3633 ebcb .......KRI.?63..
00000020: 281e 0b89 6727 0000 0000 0000 0000 0003 (...g'..........
00000030: 3308 babc f12d 8220 4490 8cd6 8b67 b59d 3....-. D....g..
00000040: b785 1a98 71a2 9981 25da 506d 078f a4e5 ....q...%.Pm....
00000050: 4a03 a1dd 4c3e 4cb0 c883 f073 f082 21c5 J...L>L....s..!.
00000060: 8327 4900 003b .'I..;
```
Renders as:

] |
[Question]
[
This is a code-golf challenge whereby you need to devise a program that acts like a quine or a quine that modifies itself to illustrate machine learning.
# Background
There is a basic artificial intelligence program called 'the pangolin game' which is described [here](https://studentnet.cs.manchester.ac.uk/ugt/COMP26120/lab/ex9game.html). The basic ideas is that the program when run the first time asks:
>
> **OK, please think of something**
>
>
> **Is it a pangolin?**
>
>
>
You may then reply either:
>
> *Yes*
>
>
>
In which case it says:
>
> **Good. That was soooo easy.**
>
>
>
Or if not it says:
>
> **Oh. Well you win then -- What were you thinking of?**
>
>
>
To which you might say:
>
> *a dog*
>
>
>
To which it would say
>
> **Please give me a question about a dog, so I can tell the difference between a dog and a pangolin**
>
>
>
you might reply
>
> *Does it eat ants?*
>
>
>
It would then ask:
>
> **What is the answer for a dog?**
>
>
>
To which you would say
>
> *no*
>
>
>
And it would say
>
> **Thanks**
>
>
>
Next time it runs, it would ask the question above, and would build up a binary tree of such questions.
# The challenge
Enough of the background. This challenge is to write a self modifying pangolin program. The rules are as follows:
1. Program output (as described above) should be to `STDERR`. The final response will always be "Good. That was soooo easy." or "Thanks". After this, it should output either the current version of the program, or a new version of the program that incorporates the question to `STDOUT`. No answer written in a language that does not support writing to `STDOUT` and `STDERR` or reading from `STDIN` will be valid.
2. In other words under UNIX you could invoke the program like this:
example:
```
$ mylanguage myprogram > myprogram.1
[dialog goes here]
$ mylanguage myprogram1 > myprogram.2
[dialog goes here]
```
3. The program has to use exactly the specified prompts (because shortening the prompts shows no skill). The prompts are (without the quotes, and where %s is substituted) as follows:
list:
```
"OK, please think of something"
"Is it %s?"
"Good. That was soooo easy."
"Oh. Well you win then -- What were you thinking of?"
"Please give me a question about %s, so I can tell the difference between %s and %s"
"What is the answer for %s?"
"Thanks"
```
4. When expecting yes/no answers, your program should accept `y` or `yes` in any case for 'yes', and `n` or `no` in any case for 'no'. What you do with non-conforming inputs is up to you. For instance you might decide to take any answer that begins with `y` or `Y` as 'yes', and anything else as no.
5. You may assume that the names of the things supplied and the questions consist only ASCII letters, numbers, spaces, hyphens, question marks, commas, full stops, colons, and semicolons, i.e. they match following regex `^[-?,.;: a-zA-Z]+$`. If you can cope with more than that (especially the quoting characters in your chosen language) you get to be smug, but don't gain any extra points.
6. Your program may not read or write any file (excluding `STDIN`, `STDOUT`, and `STDERR`), or from the network; specifically it may neither read nor write its own code from disk. Its state must be saved in the program code itself.
7. When the program is run and guesses the answer correctly, it *must* perform exactly as a quine, i.e. it must write to `STDOUT` exactly its own code, unchanged.
8. When the program is run and guesses the answer incorrectly, it *must* encode the provided new question and answer within its own code and write it to `STDOUT` in its own code, so it is capable of distinguishing between its original guess and the provided new object, in addition to distinguishing between all previously given objects.
9. You must be able to cope with multiple sequential runs of the software so it learns about many objects. See [here](https://studentnet.cs.manchester.ac.uk/ugt/COMP26120/lab/ex9game.html) for examples of multiple runs.
10. Test runs are given at the [link in the head](https://studentnet.cs.manchester.ac.uk/ugt/COMP26120/lab/ex9game.html) (obviously covering only the `STDIN` and `STDERR` dialog).
11. [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny/1063#1063) are excluded.
[Answer]
# Common Lisp, ~~631~~ 576
```
(let((X"a pangolin"))#1=(labels((U(M &AUX(S *QUERY-IO*))(IF(STRINGP M)(IF(Y-OR-N-P"Is it ~A?"M)(PROG1 M(FORMAT S"Good. That was soooo easy.~%"))(LET*((N(PROGN(FORMAT S"Oh. Well you win then -- What were you thinking of?~%")#2=(READ-LINE S)))(Q(PROGN(FORMAT S"Please give me a question about ~A, so I can tell the difference between ~A and ~A~%"N N M)#2#)))(PROG1(IF(Y-OR-N-P"What is the answer for ~A?"N)`(,Q ,N ,M)`(,Q ,M ,N))(FORMAT S"Thanks~%"))))(DESTRUCTURING-BIND(Q Y N)M(IF(Y-OR-N-P Q)`(,Q ,(U Y),N)`(,Q ,Y,(U N)))))))(write(list'let(list`(X',(U x)))'#1#):circle t)()))
```
### Example session
Name the script `pango1.lisp` and execute as follows (using SBCL):
```
~$ sbcl --noinform --quit --load pango1.lisp > pango2.lisp
Is it a pangolin? (y or n) n
Oh. Well you win then -- What were you thinking of?
a cat
Please give me a question about a cat, so I can tell the difference between a cat and a pangolin
Does it sleep a lot?
What is the answer for a cat? (y or n) y
Thanks
```
Another round, adding the bear:
```
~$ sbcl --noinform --quit --load pango2.lisp > pango3.lisp
Does it sleep a lot? (y or n) y
Is it a cat? (y or n) n
Oh. Well you win then -- What were you thinking of?
a bear
Please give me a question about a bear, so I can tell the difference between a bear and a cat
Does it hibernate?
What is the answer for a bear? (y or n) y
Thanks
```
Adding a sloth (we test the case where the answer is "no"):
```
~$ sbcl --noinform --quit --load pango3.lisp > pango4.lisp
Does it sleep a lot? (y or n) y
Does it hibernate? (y or n) n
Is it a cat? (y or n) n
Oh. Well you win then -- What were you thinking of?
a sloth
Please give me a question about a sloth, so I can tell the difference between a sloth and a cat
Does it move fast?
What is the answer for a sloth? (y or n) n
Thanks
```
Testing the last file:
```
~$ sbcl --noinform --quit --load pango4.lisp > pango5.lisp
Does it sleep a lot? (y or n) y
Does it hibernate? (y or n) n
Does it move fast? (y or n) y
Is it a cat? (y or n) y
Good. That was soooo easy.
```
### Remarks
* I first forgot printing `"Thanks"`, here it is.
* As you can see, questions are followed by `(y or n)`, which is because I'am using the existing `y-or-n-p` function. I can update the answer to remove this output if needed.
* Common Lisp has a bidirectional `*QUERY-IO*` stream dedicated to user-interaction, which is what I'am using here. Standard output and user-interaction do not mess, which follows IMHO the spirit of the question.
* Using `SAVE-LISP-AND-DIE` would be a better approach in practice.
### Generated output
Here is the last generated script:
```
(LET ((X
'("Does it sleep a lot?"
("Does it hibernate?" "a bear"
("Does it move fast?" "a cat" "a sloth"))
"a pangolin")))
#1=(LABELS ((U (M &AUX (S *QUERY-IO*))
(IF (STRINGP M)
(IF (Y-OR-N-P "Is it ~A?" M)
(PROG1 M (FORMAT S "Good. That was soooo easy.~%"))
(LET* ((N
(PROGN
(FORMAT S
"Oh. Well you win then -- What were you thinking of?~%")
#2=(READ-LINE S)))
(Q
(PROGN
(FORMAT S
"Please give me a question about ~A, so I can tell the difference between ~A and ~A~%"
N N M)
#2#)))
(PROG1
(IF (Y-OR-N-P "What is the answer for ~A?" N)
`(,Q ,N ,M)
`(,Q ,M ,N))
(FORMAT S "Thanks~%"))))
(DESTRUCTURING-BIND
(Q Y N)
M
(IF (Y-OR-N-P Q)
`(,Q ,(U Y) ,N)
`(,Q ,Y ,(U N)))))))
(WRITE (LIST 'LET (LIST `(X ',(U X))) '#1#) :CIRCLE T)
NIL))
```
### Explanations
A decision tree can be:
* a string, like `"a pangolin"`, which represents a leaf.
* a list of three elements: `(question if-true if-false)` where `question` is a closed *yes/no* question, as a string, and `if-true` and `if-false` are the two possible subtrees associated with the question.
The `U` function *walks* and *returns* a possibly modified tree.
Each question are asked in turn, starting from the root until reaching a leaf, while interacting with the user.
* The returned value for an intermediate node `(Q Y N)` is `(Q (U Y) N)` (resp. `(Q Y (U N))`) if the answer to question `Q` is *yes* (resp. *no*).
* The returned value for a leaf is either the leaf itself, if the program correctly guessed the answer, or a refined tree where the leaf is replaced by a question and two possible outcomes, according to the values taken from the user.
This part was rather straightforward. In order to print the source code, we use reader variables to build self-referential code. ~~By setting `*PRINT-CIRCLE*` to true, we avoid infinite recursion during pretty-printing.~~ The trick when using [`WRITE`](http://clhs.lisp.se/Body/f_wr_pr.htm) with `:print-circle T` is that the function might also returns the value to the REPL, depending on whether write is the last form, and so, if the REPL doesn't handle circular structures, like it is defined by the standard default value of `*PRINT-CIRCLE*`, there will be an infinite recursion. We only need to make sure the circular structure is not returned to the REPL, that's why there is a NIL in the last position of the LET. This approach greatly reduces the problem.
[Answer]
# Python 2.7.6, ~~820~~ 728 bytes
(Might work on different versions but I'm not sure)
```
def r(O,R):
import sys,marshal as m;w=sys.stderr.write;i=sys.stdin.readline;t=O;w("OK, please think of something\n");u=[]
def y(s):w(s);return i()[0]=='y'
while t:
if type(t)==str:
if y("Is it %s?"%t):w("Good. That was soooo easy.")
else:w("Oh. Well you win then -- What were you thinking of?");I=i().strip();w("Please give me a question about %s, so I can tell the difference between %s and %s"%(I,t,I));q=i().strip();a=y("What is the answer for %s?"%q);w("Thanks");p=[q,t];p.insert(a+1,I);z=locals();exec"O"+"".join(["[%s]"%j for j in u])+"=p"in z,z;O=z["O"]
t=0
else:u+=[y(t[0])+1];t=t[u[-1]]
print"import marshal as m;c=%r;d=lambda:0;d.__code__=m.loads(c);d(%r,d)"%(m.dumps(R.__code__),O)
r('a pangolin',r)
```
Well, it's not not as short as the Common Lisp answer, but here is some code!
[Answer]
# Python 3, 544 bytes
```
q="""
d=['a pangolin'];i=input;p=print
p("OK, Please think of something")
while len(d)!=1:
d=d[1+(i(d[0])[0]=="n")]
x=i("Is it "+d[0]+"?")
if x[0]=="n":
m=i("Oh. Well you win then -- What were you thinking of?")
n=[i("Please give me a question about "+m+", so I can tell the difference between "+d[0]+" and "+m),*[[d[0]],[m]][::(i("What is the answer for "+m+"?")[0]=="n")*2-1]]
p("Thanks")
q=repr(n).join(q.split(repr(d)))
else:
p("Good. That was soooo easy.")
q='q=""'+'"'+q+'""'+'"'+chr(10)+'exec(q)'
p(q)
"""
exec(q)
```
[Try it Online!](https://tio.run/##PZLBbtswDIbvegpOF0t1YjTbLYXQS4Gi2KE7FOjB8EGN6FirTdmWsiRPn1FuUgEybEr8/4@kx3PqAv26XCYjpRTO1IWF0dI@9J6K5sEbT@MhPYxmnD0lMSr5@nsFf3q0ESF1nj4htBDDgPljL7U4dr5H6JGU0z/MZiuAlzOu3pTKK1ffN5q3MZKkbsTJeCVfIvgEssyHpXxkEd/C6XbrS2HIF1@7Ct6x7@EcDnD0xARIsF7De2cTHHHG5WThYhpGy2I5nUzN@Vfuvf@HMCBYmA4Ykw8E9iMcMsJQyhWXAy@wsyyfvdgDnG9bVqcdwgemI7LrDRcsuZyoV3d1nUPNqh6apt5uuVy5gPm4iFiKjAhtmL@MmO27E3c/15umWVC5x2@dpc94RZ/MjOOsSFd/gyc1VXHsfVJL0GmtBfYRt7fU5xBcBW9LP2zkUngBV32uWG4yRR50URa8J35eX3fdrDb3uizwhDs16YIHPWmRf4lr5HKhIFzYi6eAy7SQDSyl@Cgo/Ac)
The questions/answers/responses are stored in an array, where if the array stores three items (e.g. `['Does it eat ants',['a pangolin'],['a dog']]`) then it gets an answer to the question and repeats with just the contents of either the second or third item, depending on the answer. When it gets to an array with only one item, it asks the question, and since it has its entire source codeas a string it is able to use the split-join method to insert the extension to the array in order to add the new branch.
I originally wrote this not realising the quine requirement, so rereading the question and having to find a way that I could both execute code and use it as a string was difficult, but I eventually stumbled upon the idea of the nice expandable quine format:
```
q="""
print("Some actual stuff")
q='q=""'+'"'+q+'""'+'"'+chr(10)+'exec()'
print(q)
"""
exec(q)
```
[Answer]
# [Python 3](https://docs.python.org/3/), 497 bytes
```
t=["a pangolin"];c='''p=print;i=input;a=lambda q:i(q)[0]in"Yy"
def q(t):
if len(t)<2:
g=t[0]
if a(f"Is it {g}?"):p("Good. That was soooo easy.")
else:s=i("Oh. Well you win then -- What were you thinking of?");n=i(f"Please give me a question about {s}, so I can tell the difference between {s} and {g}.");t[0]=n;t+=[[g],[s]][::1-2*a(f"What is the answer for {s}?")];p("Thanks")
else:q(t[2-a(t[0])])
p("Ok, please think of something");q(t);p(f"t={t};c=''{c!r}'';exec(c)")''';exec(c)
```
Quite similar to Harmless' answer for tree representation. It recursively asks the next question, while going deeper into the list, until there is only one response.
Ungolfed version (without quining)
```
tree = ['a pangolin']
def ask(question):
answer = input(question + '\n')
if answer.lower() in ['yes', 'no']:
return answer.lower() == 'yes'
else:
print('Please answer "yes" or "no".')
return ask(question)
def query(tree):
if len(tree) == 1:
guess = tree.pop()
if ask(f'Is it {guess}?'):
print('Good. That was soooo easy.')
tree.append(guess)
else:
thing = input('Oh. Well you win then -- What were you thinking of?\n')
new_question = input(f'Please give me a question about {thing}, so I can tell the difference between {thing} and {guess}.\n')
answer = ask(f'What is the answer for {thing}?')
print('Thanks')
tree.append(new_question)
if answer:
tree.append([thing])
tree.append([guess])
else:
tree.append([guess])
tree.append([thing])
else:
if ask(tree[0]):
query(tree[1])
else:
query(tree[2])
while True:
input('Ok, please think of something\n')
query(tree)
```
] |
[Question]
[
Given the following Python "reference implementation" of non-terminating FizzBuzz:
```
i=1
while True:
if i%15 == 0:
print("FizzBuzz")
elif i%3 == 0:
print("Fizz")
elif i%5 == 0:
print("Buzz")
else:
print(i)
i += 1
```
We can represent its output as an infinite array of chars/bytes (assuming \n line terminators) that looks like the following:
```
['1', '\n', '2', '\n', 'F', 'i', 'z', 'z', '\n', '4', '\n', 'B', 'u', 'z', 'z', '\n', 'F', 'i', 'z', 'z', ...]
```
**Your task is to write the shortest function or program that returns the character at the Nth index of this array.**
Sounds easy? Your code should also work for extremely large values of N, for example 1e100.
It is possible to calculate the Nth byte of this output array in O(log(n)) time (or possibly better) - *how* is left as an exercise for the reader.
**Your solution must run in O(poly(log(n))) time (or better).** There is no hard execution time limit, but as a rough guideline you should be able to solve the `N=1e100` case almost instantaneously.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"): the shortest code in bytes wins.
# Test cases:
```
f(0) == '1'
f(1) == '\n'
f(2) == '2'
f(10) == '\n'
f(100) == '\n'
f(1000) == 'z'
f(100000) == 'F'
f(1e10) == '5'
f(1e100) == '0'
```
Some more, randomly generated testcases: <https://gist.github.com/DavidBuchanan314/65eccad5032c427218eb9c269b55e869>
Note: these test cases are correct to the best of my knowledge. If you have contradictory findings, I am open to discussion.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 145 bytes
*Saved 2 bytes thanks to @user202729*
Expects a BigInt. Outputs `#` instead of `\n` for readability.
```
f=(n,k=0n,p=10n**k,x=55n+8n*k,q=p*3n/5n*x||30n)=>n<q?(g=p=>j--&&([["Fizz"][p%3n]]+[["Buzz"][p%5n]]||p)+'#'+g(++p))(p+n/x*(j=15n))[n%x]:f(n-q,-~k)
```
[Try it online!](https://tio.run/##dVLZThsxFH3nK1AryExCyt1tVx0q9YGfSPOAKCAWOUOhVYSi/jo9RnQhpRPJcu651z6Lr06@n9ydfr0c7@d19eXs8fF86OrB9UD1YByY6nR6fbAe3OssV2xvh3Gq9dDrdL3ZKNV@OKofbj92F8M4HF3N5/v73WLx5vjy4eHNcjHuaV0uZyh8@vZccBQ2m7GfTd5OZhfdbDb2fTfO6uF62l0N7LXvF3VvvXx/3tX57cH8x3X/eLqqd6ubs3c3q4vuvMOd/e7zd3i4yzsvYX4Jf65buLzEZXv8r@NfG2f60/Af/HcD8IdX4F8NgI//vX06faYA2F@Hn3DAtLOD9Ww9np3eX9aL3YlMtgZyZA8pWDxKShFchI2U3DgsnEWESE3Ug1HLhJ9pCVcnUyFxJynBVjKGSMzNKUqoKqlzIcmaOLVuLpmck5gxDmPViJQSgKKZ2UsEJjy5M0vyHCESORVXQVtSSgxmhY0JZzCThCVxAQNcr15IJXNwArVkSuyahEoxbzswoqKBuhdLjrmcchCYZcLN8KFYKdAWZiJaOHtBV7hY02@KKwIMoQXmbvuatn311MzIMKB9DqYMCpCfIaz5RpRgfZKC22EFvAQVzmyQWCAkwhMLa2qD@IvThOAkYyUMIQd2BMbZQBwKWwH@WIbecBhRmovRNBp2zTNkHLAIU/QEQ5ArI1NLVqIg@UDE8JrJzMHbAkQzjGJqdsAibXVEjmwwTngTinpQCz9l@GSAMlzCQ0iSC2IRzYm1ESO8ivJkowry9yakBYjTuSSFr48/AQ "JavaScript (Node.js) – Try It Online")
## How?
### Method
We use a recursive function that quickly computes the number of characters required to build all blocks of 15 terms using numbers of \$1\$, \$2\$, ..., \$N\$ digits. This takes \$\approx \log(n)\$ iterations, where \$n\$ is the input.
The only block that is explicitly generated is the last one, which contains the character we're looking for.
### Formulae
Below is the template of a block of 15 terms of the sequence, where `#` is the separator and `@` is a placeholder for a full number. (Note that the leading term modulo \$15\$ can be anything between \$0\$ and \$14\$. The length of the block doesn't depend on that.)
```
<--------- 55 characters and 8 full numbers ---------->
FizzBuzz#@#@#Fizz#@#Buzz#Fizz#@#@#Fizz#Buzz#@#Fizz#@#@#
^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
mod 15: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
```
All terms in such a block are meant to have the same number of digits \$k+1\$. For \$k>0\$, the length of the block is \$55+8k\$ characters. For \$k=0\$, we can only build a partial block of 9 terms whose length is \$30\$ characters:
```
<------ 30 characters ------->
1#2#Fizz#4#Buzz#Fizz#7#8#Fizz#
```
The number of terms with \$k+1\$ digits is \$9\times 10^k\$.
The number of blocks with \$k+1\$ digits is:
$$\left\lceil10^k\times\dfrac{9}{15}\right\rceil=\left\lceil10^k\times\dfrac{3}{5}\right\rceil$$
(where the ceiling is only needed for \$k=0\$)
And the number of characters is:
$$\cases{
30&k=0\\
10^k\times\dfrac{3}{5}\times (55+8k)&k>0
}$$
## Commented
```
f = ( // f is a recursive function taking:
n, // n = input
k = 0n, // k = exponent
p = 10n ** k, // p = 10 ** k
x = 55n + 8n * k, // x = length of a block of 15 terms, using numbers of
// k + 1 digits
q = p * 3n / 5n * x // q = number of characters added when all numbers of
|| 30n // k + 1 digits are used (p = 1 is an edge case)
) => //
n < q ? // if n is less than q:
( g = p => // g is a recursive function that builds the block of 15
// terms in which lies the character we're looking for
j-- && // abort if j = 0 (decrement it afterwards)
( // otherwise:
[["Fizz"][p % 3n]] + // append 'Fizz' if p is a multiple of 3
[["Buzz"][p % 5n]] // append 'Buzz' if p is a multiple of 5
|| p // append p if it's neither a multiple of 3 or 5
) + '#' + // append the separator
g(++p) // append the result of a recursive call to g
)(p + n / x * (j = 15n)) // initial call to g: we set j to 15 and add to p the
// number of terms that can be generated with n
// characters, using only full blocks of 15 terms
[n % x] // extract the character at n modulo x
: // else:
f(n - q, -~k) // recursive call to f with n - q and k + 1
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~216~~ ~~212~~ ~~209~~ ~~189~~ ~~183~~ 182 bytes
```
f=lambda i,j=90:j*"."and f(i,j-1)+("Fizz"*(j%3<1)+"Buzz"*(j%5==1)or str(10*i+j-1))+"\n"
n,i,l=input()-30,1,len
while n/i/l(f(i)):n-=l(f(i))*i;i*=10
s=f(i+n/l(f(i))*9);print s[n%l(s)]
```
[Try it online!](https://tio.run/##PY1BDoIwFET3nKJpQtKWIq3EBWA3LryEusAg4ZP6IVBi5PK1Juis5k1eMuPbdQPuvW@NrZ/3piYge1Ooshd0R2tsSMvCkmqeMHqGdaWC9XF@DExPy4YHYzQfJjK7iWklIPn6QbgijVCCtAZwXBzjaa6klvaB0asD@yCYQWZZeOC8xNRsVUAFwmgVzSZwgj9FFLwaJ0BH5gvGls385r1W/3wA "Python 2 – Try It Online") Compares `n` against a number increasing by more than tenfold every iteration, so I assume this should take log time. Edit: Saved 4 bytes thanks to @Danis. Saved ~~3~~ 6 bytes thanks to @JonathanAllan. Saved 1 byte thanks to @ovs.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~170 ... 139~~ 138 bytes
```
f=->n,d=0,c=55,a=30,b=6,t=1{n<a ?((b%10-5..10).map{|x|:FizzBuzzz[x**4%-15,x==0?8:4]||d+(n/c)*15+x}*$/)[n%c]:f[n-a,d+t*15,c+=8,b*c,b*10,b]}
```
[Try it online!](https://tio.run/##NY6xDoJAEER7v4JC5DgW3FXOEOJqYuFPEAo4QmLhhSgkeOK3I2AsZiYzW@x7dOVrHGsOTwYqRtCsFBS8Ryj5AC3T2xwL5yxE6RKGKooI/eheNO@hH9LrzdpLZ63NeiljNyQFPTOekzTOh6EKhNlqX5IK@o9cb/3MuDpP68yEBVRBOx1AB5xAKfUkml7mn7FxMgSCHUydcNHPlpCS/oH5zCE2tb9quvbpCJzh8Ic3z9Lzxi8 "Ruby – Try It Online")
### How:
```
f=->n,d=0,c=55,a=30,b=6,t=1
```
Initialize some parameters: d is the last number of the previous block, c is the size in bytes of the 15-number sequence in the current block, a is the length of the current block, b is the number of sequences in the next block, and t is the number of sequences in the current block.
```
{n<a ?
```
First check: is the byte in the current block?
```
((b%10-5..10)
```
Build a FizzBuzz sequence, starting from 1 for the first iteration, and from -5 after that. We could stop at 9, but going to 10 adds the final newline (the last "Buzz" is ignored) at the cost of 1 byte.
```
:FizzBuzzz[x**4%-15,x==0?8:4]||d+(n/c)*15+x
```
Courtesy of [Lynn](https://codegolf.stackexchange.com/a/58841/18535): shortest Ruby FizzBuzz generator ever. The Fizzes and Buzzes are in fixed position, we have to find the beginning of the sequence, which is the (n/c)th sequence of the current block. The starting number is d plus 15 times the position of the sequence in the block.
```
}*$/)[n%c]:
```
Join using newlines, get the nth character of the block, and since this is the (n/c)th slice, this is the (n%c)th byte of this slice.
```
f[n-a,d+t*15,c+=8,b*c,b*10,b]}
```
If the byte is not in the current block, move to the next:
* decrease n by the length of the current block
* increase d by 15 times the number of sequences in the current block
* increase the length in byte of a sequence by 8
* calculate the number of bytes in the next block
* multiply the number of sequences in a block by 10
* ~~still lose to Javascript by 1 byte~~???
* reduce by 1 byte every day (and thanks Dingus for -1 byte)
] |
[Question]
[
A Window is an ASCII-art square with odd side length of at least 3, with a single character border around the edge as well as vertical and horizontal strokes in the middle:
```
#######
# # #
# # #
#######
# # #
# # #
#######
```
An MS Window is a window where the border is made only of the characters `M` and `S`. Your task is to write a program (or function) that takes a string and outputs a truthy value if the input is a valid MS Window, and a falsey value if it is not.
# Specifications
* You may take the input as a newline-separated string or an array of strings representing each line.
* The border of an MS Window may contain a mix of M and S characters, but the inside will always be composed of spaces.
* You can choose to detect only windows with trailing newlines, or only windows without trailing newlines, but not both.
# Test Cases
Truthy:
```
MMM
MMM
MMM
SMSMS
M M S
SMSMM
S S M
SMSMS
MMMMMMM
M S M
M S M
MSSSSSM
M S M
M S M
MMMMMMM
```
Falsey:
```
Hello, World!
MMMM
MSSM
MS M
MMMM
MMSMM
M S.M
sSSSS
M S M
MMSMM
MMMMMMM
M M M
MMMMMMM
M M M
MMMMMMM
MMMMMMM
M M M M
MMMMMMM
M M M M
MMMMMMM
M M M M
MMMMMMM
MMSSMSSMM
M M M
S S S
S S S
MMSSMSSMM
S S S
S S S
M M M
MMSSMSSMM
```
[Answer]
## [Retina](https://github.com/m-ender/retina), ~~68~~ 67 bytes
Byte count assumes ISO 8859-1 encoding.
```
S
M
^(M((M)*M)\2)((?<-9>¶M((?<9-3> )*(?(3)!)M|\5)\5)*(?(9)!)¶\1)\4$
```
[Try it online!](https://tio.run/nexus/retina#jU4xDsIwDNz9ilQCya4oEhSGqqhdWW7ywBIhBtgqKsHKu/qAfqzEbUEV6kAcxz7f5RJ/p5z0kue05FA6JdCZwQyJIX4rzOUhyYq2gXVZkhZOYi45lUjw8nsJ23AWcNv4jfjdousA0CdJEYLgQsz0pkGvdU6dm1S1NTMf9XS8VVW9cqf6UV2jwccu2THKbKi9ta5BT/Ozvmd1oL9vY@r9iyfE8Pc/8Rs "Retina – TIO Nexus")
[Answer]
## [Grime](https://github.com/iatorm/grime), ~~39~~ 38 bytes
*Thanks to Zgarb for saving 1 byte.*
```
e`BB/BB/W+ W/+
B=W|B/W\ * W/\ /*
W=[MS
```
[Try it online!](https://tio.run/nexus/grime#@5@a4OSkD0Th2grh@tpcTrbhNUBOjIIWkBujoK/FFW4b7Rv8/78vBHD5KigEKygg0cEggEUcAgA "Grime – TIO Nexus")
I'm not sure whether there's a simpler way to enforce the square aspect ratio of the individual window components than using a recursive nonterminal, but this seems to be working quite well.
### Explanation
It's best to read the program from the bottom up.
```
W=[MS
```
This simply defines a nonterminal (which you can think of as a subroutine that matches a rectangle) `W` which matches either an `M` or an `S` (there's an implicit `]` at the end of the line).
```
B=W|B/W\ * W/\ /*
```
This defines a non-terminal `B` which matches about a quarter of the output, i.e. one window panel with the left and top border. Something like this:
```
MSM
S
M
```
To ensure that this window panel is square, we define `B` recursively. It's either a window character `W`, or it's `B/W\ * W/\ /*` which adds one layer to the right and to the bottom. To see how it does this, let's remove some syntactic sugar:
```
(B/W[ ]*)(W/[ ]/*)
```
This is the same, because horizontal concatenation can be written either `AB` or `A B`, but the latter has lower precedence than the vertical concatenation `/` while for the former has higher. So `B/W[ ]*` is a `B` with a window character and a row of spaces below. And then we horizontally append `W/[ ]/*` which is a window character with a column of spaces.
Finally, we assemble these nonterminals into the final window shape:
```
BB/BB/W+ W/+
```
That's four window panels `B` followed by a row of window characters and a column of window characters. Note that we make no explicit assertion that the four window panels are the same size, but if they aren't it's impossible to concatenate them into rectangle.
Finally the `e`` at the beginning is simply a configuration which tells Grime to check that the entire input can be matched by this pattern (and it prints `0` or `1` accordingly).
[Answer]
## JavaScript (ES6), ~~115~~ 113 bytes
```
a=>(l=a.length)&a.every((b,i)=>b.length==l&b.every((c,j)=>(i&&l+~i-i&&l+~i&&j&&l+~j-j&&l+~j?/ /:/[MS]/).test(c)))
```
Takes input as a an array of arrays of characters (add 5 bytes for an array of strings) and returns `1` or `0`. After verifying that the height is odd, every row is checked to ensure the array is square, and every character is verified to be one of the character(s) that we expect in that particular position. Edit: Saved 2 bytes thanks to @PatrickRoberts.
[Answer]
# Perl, ~~124~~ ~~123~~ ~~119~~ ~~95~~ ~~93~~ 84
The following Perl script reads one candidate MS Window from the standard input. It then exits with a zero exit status if the candidate is an MS Window and with a non-zero exit status if it isn't.
It works by generating two regular expressions, one for the top, middle and bottom line and one for every other line, and checking the input against them.
Thanks, @Dada. And again.
```
map{$s=$"x(($.-3)/2);$m="[MS]";($c++%($#a/2)?/^$m$s$m$s$m$/:/^${m}{$.}$/)||die}@a=<>
```
[Answer]
# Mathematica, 166 bytes
```
Union[(l=Length)/@data]=={d=l@#}&&{"M","S"}~(s=SubsetQ)~(u=Union@*Flatten)@{#&@@(p={#,(t=#~TakeDrop~{1,-1,d/2-.5}&)/@#2}&@@t@#),p[[2,All,1]]}&&{" "}~s~u@p[[2,All,2]]&
```
Unnamed function taking a list of lists of characters as input and returning `True` or `False`. Here's a less golfy version:
```
(t = TakeDrop[#1, {1, -1, d/2 - 0.5}] &;
Union[Length /@ data] == {d = Length[#1]}
&&
(p = ({#1, t /@ #2} &) @@ t[#1];
SubsetQ[{"M", "S"}, Union[Flatten[{p[[1]], p[[2, All, 1]]}]]]
&&
SubsetQ[{" "}, Union[Flatten[p[[2, All, 2]]]]])) &
```
The first line defines the function `t`, which separates a list of length `d` into two parts, the first of which is the first, middle, and last entries of the list, and the second of which is all the rest. The second line checks whether the input is a square array in the first place. The fourth line uses `t` twice, once on the input itself and once on all\* of the strings in the input, to separate the characters that are supposed to be `"M"` or `"S"` from the characters that are supposed to be spaces; then the fifth and seventh lines check whether they really are what they're supposed to be.
[Answer]
## JavaScript (ES6), ~~108~~ 106 bytes
Input: array of strings / Output: `0` or `1`
```
s=>s.reduce((p,r,y)=>p&&r.length==w&(y==w>>1|++y%w<2?/^[MS]+$/:/^[MS]( *)[MS]\1[MS]$/).test(r),w=s.length)
```
### Test cases
```
let f =
s=>s.reduce((p,r,y)=>p&&r.length==w&(y==w>>1|++y%w<2?/^[MS]+$/:/^[MS]( *)[MS]\1[MS]$/).test(r),w=s.length)
console.log('Testing truthy test cases...');
console.log(f([
'MMM',
'MMM',
'MMM'
]));
console.log(f([
'SMSMS',
'M M M',
'SMSMS',
'M M M',
'SMSMS'
]));
console.log(f([
'MMMMMMM',
'M S M',
'M S M',
'MSSSSSM',
'M S M',
'M S M',
'MMMMMMM'
]));
console.log('Testing falsy test cases...');
console.log(f([
'Hello, World!'
]));
console.log(f([
'MMMM',
'MSSM',
'MS M',
'MMMM'
]));
console.log(f([
'MMSMM',
'M S.M',
'sSSSS',
'M S M',
'MMSMM'
]));
console.log(f([
'MMMMMMM',
'M M M',
'MMMMMMM',
'M M M',
'MMMMMMM'
]));
console.log(f([
'MMMMMMM',
'M M M M',
'MMMMMMM',
'M M M M',
'MMMMMMM',
'M M M M',
'MMMMMMM'
]));
```
[Answer]
# JavaScript (ES6), ~~140~~ ~~138~~ ~~141~~ 140 bytes
I know this isn't a winning byte count (although thanks to Patrick Roberts for -3, and I realised it threw false positives for 1 instead of M/S: +3), but I did it a slightly different way, I'm new to this, and it was fun...
Accepts an array of strings, one for each line and returns true or false. Newline added for clarity (not included in byte count).
```
f=t=>t.every((e,i)=>e.split`S`.join`M`==[...p=[b='M'.repeat(s=t.length),
...Array(z=-1+s/2|0).fill([...'MMM'].join(' '.repeat(z)))],...p,b][i])
```
Instead of checking input against a generalised pattern, I construct an 'M' window of the same size, replace S with M on input, and compare the two.
## Ungolfed
```
f = t => t.every( // function returns true iff every entry in t
// returns true below
(e, i) => e.split`S`.join`M` // replace all S with M
// to compare to mask
== [ // construct a window of the same size made of Ms and
// spaces, compare each row
...p = [ // p = repeated vertical panel (bar above pane)
// which will be repeated
b = 'M'.repeat(s = t.length),
// b = bar of Ms as long as the input array
...Array(z = -1 + s/2|0).fill([...'MMM'].join(' '.repeat(z)))],
// z = pane size; create enough pane rows with
// Ms and enough spaces
...p, // repeat the panel once more
b][i] // finish with a bar
)
console.log(f(["111","111","111"]))
console.log(f(["MMMMM","M S M","MSSSM","M S M","MSSSM"]))
```
## Test cases
```
f=t=>t.every((e,i)=>e.split`S`.join`M`==[...p=[b='M'.repeat(s=t.length),
...Array(z=-1+s/2|0).fill([...'MMM'].join(' '.repeat(z)))],...p,b][i])
truthy=`MMM
MMM
MMM
SMSMS
M M M
SMSMS
M M M
SMSMS
MMMMMMM
M S M
M S M
MSSSSSM
M S M
M S M
MMMMMMM`.split('\n\n')
falsey=`Hello, World!
MMMM
MSSM
MS M
MMMM
MMSMM
M S.M
sSSSS
M S M
MMSMM
MMMMMMM
M M M
MMMMMMM
M M M
MMMMMMM
MMMMMMM
M M M M
MMMMMMM
M M M M
MMMMMMM
M M M M
MMMMMMM`.split('\n\n')
truthy.forEach(test=>{
console.log(test,f(test.split('\n')))
})
falsey.forEach(test=>{
console.log(test,f(test.split('\n')))
})
```
[Answer]
## Pyke, ~~34~~ 31 bytes
```
lei}t\Mcn+it*i\M*+s.XM"QJ\S\M:q
```
[Try it here!](http://pyke.catbus.co.uk/?code=lei%7Dt%5CMcn%2Bit%2ai%5CM%2a%2Bs.XM%22QJ%5CS%5CM%3Aq&input=%22MMMMM%22%2C%22M+M+M%22%2C%22MMSMM%22%2C%22M+M+M%22%2C%22MMMMM%22)
```
lei - i = len(input)//2
}t - (^ * 2) - 1
\Mc - "M".center(^)
n+ - ^ + "\n"
it* - ^ * (i-1)
+ - ^ + V
i\M* - "M"*i
s - palindromise(^)
.XM" - surround(^, "M")
q - ^ == V
QJ - "\n".join(input)
\S\M: - ^.replace("S", "M")
```
[Answer]
# JavaScript (ES6), ~~109~~ ~~107~~ ~~106~~ ~~105~~ 99 bytes
```
s=>!s.split`S`.join`M`.search(`^((M{${r=s.search`
`}})(
(M( {${w=(r-3)/2}})M\\5M
){${w}}))\\1\\2$`)
```
**Edit**: Whoa, Arnauld saved me 6 bytes by changing `s.split`\n`.length` to `s.search`\n``! Thanks!
This takes a single multiline string and constructs a `RegExp`-based validation using the length of the input string. Returns `true` or `false`. Assumes a valid window ~~has~~ *does not have* a trailing newline.
# Demo
```
f=s=>!s.split`S`.join`M`.search(`^((M{${r=s.search`
`}})(
(M( {${w=(r-3)/2}})M\\5M
){${w}}))\\1\\2$`);
`MMM
MMM
MMM
SMSMS
M M M
SMSMS
M M M
SMSMS
MMMMMMM
M S M
M S M
MSSSSSM
M S M
M S M
MMMMMMM
Hello, World!
MMMM
MSSM
MS M
MMMM
MMSMM
M S.M
sSSSS
M S M
MMSMM
MMMMMMM
M M M
MMMMMMM
M M M
MMMMMMM
MMMMMMM
M M M M
MMMMMMM
M M M M
MMMMMMM
M M M M
MMMMMMM`.split`
`.forEach(test=>{console.log(test,f(test));});
```
] |
[Question]
[
Write a program that reads a \$n\times n \times n\$ array of binary values which represent an \$n\times n \times n\$ cube, that consists of \$n^3\$ smaller cubes. Each value says whether there is a voxel (small cube) present in the given position or not. The program must output the given array as an ASCII graphic (that means output through console or writing to a file).
### Examples
Let us consider the following \$2\times 2\times 2\$ arrays:
```
[
[[0,0],
[1,0]]
[[1,1],
[1,0]],
]
[
[[0,0],
[0,0]]
[[1,1],
[1,1]],
]
```
In this case the output should look like this (it does not look as good here as it does in code editors/consoles with less vertical space):
```
+----+
/ /|-+----+
+----+ | /|
| | +----+ |
| | | | +
+ + | |/
| | +----+
| |/
+----+
+----+----+
/ /|
+ + |
/ / +
+----+----+ /
| | +
| |/
+----+----+
```
An example for a \$12\times 12\times 12\$ input string can be found [here (pastebin).](http://pastebin.com/GBwSyuvp) A new example for a \$7\times 7\times 7\$ input string can be found [here.](http://pastebin.com/XZncYSTR)
### Specifications of the ASCII
Each corner of a voxel is represented by a `+` as long as there is any edge leading to it. The `+` are also drawn when there is a straight edge that is more than one unit long. There are three types of edges: The horizontal left to right `----`, the horizontal back to front `/` and the vertical
```
|
|
```
Each of those has to end in a `+` (as long visible). The edges will not be drawn when they subdivide one planar plane into two or more pieces (unlike the `+` in relation to the edges as stated above). Structures that are hidden behind others must not be drawn.
The 'drawing' is basically a parallel projection so only top, right and front sides are visible - always from the same angle.
### Details
The code must be working for inputs of size \$n=1,2,\ldots,12\$. Trailing spaces and unnecessary newlines before/after are allowed (so you *could* write a code that always basically outputs the \$12\times 12\times 12\$ grid even when the actual size of the drawing is only \$3\times 3\times 3\$ or so).
Input formatting and method is up to you, you can use csv, JSON or any other stuff, but it has to consist of \$1\$ and \$0\$ for the state of each voxel. The order must be as in the examples:
* 1st dimension: layer by layer from the uppermost to the lowermost
* 2nd dimension: row by row back (furthest away) to front (nearest)
* 3rd dimension: voxels in each row left to right
Whether you use console or reading files as input and output is up to you. **Please** tell us about your code / how you approached it.
### Judging
This is codegolf so the fewest number of bytes wins. This includes ONLY the part that actually does the work - when counting bytes you can consider the input already as parsed and saved in a variable and you have to have the output string saved to a variable, ready to be printed. The parsing and the output itself does not count.
(And I will upvote submissions with creative examples=)
This was inspired by [Rob's Puzzle page](http://www.robspuzzlepage.com/interlocking.htm).
[Answer]
# Lua (1442 bytes)
**Bonus animations! :)**
*If you have any cool voxel art in the same format as the examples, link it in the comments and I'll make an animation out of it*
7x7x7

12x12x12

This is my first code golf, so its quite messy and I plan on improving it or porting it to a different language.
Here is what i have, right now at just under 2.5kB barely-golfed (just removed indentation whitespace at this point, I will continue more later)
Here is the now ~1.4kB golfed and minified version (note the "a" table on the first line is the placeholder for the voxel matrix):
```
local a={}
local b,c=table,string;local d,e,f,g,h,i=b.concat,#a,c.gsub,c.gmatch,ipairs,b.insert;local function j(k,l,m)return a[k]and a[k][l]and a[k][l][m]==1 end;local n={}for o=1,e*5+1 do n[o]={}for p=1,e*7+1 do n[o][p]=" "end end;local q=[[
__6hhhh7
_g ij
1aaaa2 j
b d 5
b de_
3cccc4__
]]local function r(k,l,m)local s=q;if j(k,l,m)then local t,u,v,w,x,y,z,A=j(k-1,l,m),j(k+1,l,m),j(k,l,m-1),j(k,l,m+1),j(k,l-1,m),j(k+1,l+1,m),j(k+1,l,m+1)," "if t then s=f(s,"[ai]"," ")end;if u and not y then A=A.."c"end;if u and not z then A=A.."e"end;if v then A=A.."bg"end;if w then A=A.."di"end;if x then if not j(k,l-1,m+1)then A=A.."j"end;A=A.."h"end;if t then if w and j(k-1,l,m+1)then A=A.."2"end;if v and j(k-1,l,m-1)then A=A.."1"end end;if u then if w and j(k+1,l,m+1)then A=A.."4"end;if v and j(k+1,l,m-1)then A=A.."3"end end;if x then if w and j(k,l-1,m+1)then A=A.."7"end;if v and j(k,l-1,m-1)then A=A.."6"end;if u and j(k+1,l-1,m)then A=A.."5"end end;s=f(f(f(f(f(s,"["..A.."]"," "),"[ach]","-"),"[bdj]","|"),"[gie]","/"),"[1234567]","+")else s=nil end;return s end;local B,C;local D=e*2-1;local E=1;for k=e,1,-1 do for l=1,e do for m=1,e do B=(l-1)*-2+(m-1)*5+D;C=(l-1)*2+(k-1)*3+E;local s=r(k,l,m)if s then local F={}for G in s:gmatch("[^\n]+")do local H={}for I in G:gmatch(".")do i(H,I)end;i(F,H)end;for J,K in h(F)do for L,I in h(K)do if I~="_"then n[C+J-1][B+L-1]=I end end end end end end end;for o,a in h(n)do print(d(a))end
```
**Edit**: Here is the original (over 3kB) ungolfed version, including my edits for making the animation (if you are running it yourself and want the animation, change the `false` near the bottom of the code to `true`.
```
local v = {}
local depth = #v;
function voxel(y,z,x)
return (v[y] and v[y][z] and v[y][z][x]==1)
end
local canvas = {}
print("Constructing canvas of depth",depth)
for i=1,depth*5+1 do
canvas[i] = {}
for j=1,depth*7+1 do
canvas[i][j] = " "
end
end
local voxelProto = [[
__6hhhh7
_g ij
1aaaa2 j
b d 5
b de_
3cccc4__
]]
function renderVoxel(y,z,x)
local vox = voxelProto
if (voxel(y,z,x)) then
local up = voxel(y-1,z,x)
local down = voxel(y+1,z,x)
local left = voxel(y,z,x-1)
local right = voxel(y,z,x+1)
local back = voxel(y,z-1,x)
local downFront = voxel(y+1,z+1,x)
local downRight = voxel(y+1,z,x+1)
if (up) then
vox = vox:gsub("[ai]"," ")
end
if (down and not downFront) then
vox = vox:gsub("[c]"," ")
end
if (down and not downRight) then
vox = vox:gsub("[e]"," ")
end
if (left) then
vox = vox:gsub("[bg]"," ")
end
if (right) then
vox = vox:gsub("[di]"," ")
end
if (back and not voxel(y,z-1,x+1)) then
vox = vox:gsub("[j]"," ")
end
if (back or up) then
vox = vox:gsub("[h]"," ")
end
if (up and right and voxel(y-1,z,x+1)) then
vox = vox:gsub("[2]"," ")
end
if (up and left and voxel(y-1,z,x-1)) then
vox = vox:gsub("[1]"," ")
end
if (down and right and voxel(y+1,z,x+1)) then
vox = vox:gsub("[4]"," ")
end
if (down and left and voxel(y+1,z,x-1)) then
vox = vox:gsub("[3]"," ")
end
if (back and right and voxel(y,z-1,x+1)) then
vox = vox:gsub("[7]"," ")
end
if (back and left and voxel(y,z-1,x-1)) then
vox = vox:gsub("[6]"," ")
end
if (back and down and voxel(y+1,z-1,x)) then
vox = vox:gsub("[5]"," ")
end
vox = vox:gsub("[ach]","-")
vox = vox:gsub("[bdj]","|")
vox = vox:gsub("[gie]","/")
vox = vox:gsub("[1234567]","+")
else
vox = nil
end
return vox
end
local xpos,ypos
local minx = depth*2-1
local miny = 1;
local pic = {}
function drawCanvas()
for k,v in pairs(canvas) do
pic[k] = table.concat(v)
end
return table.concat(pic,"\n")
end
local timeline = {}
print("Compositing voxels")
for y=depth,1,-1 do
for z=1,depth do
for x = 1,depth do
xpos = (z-1)*-2 + (x-1)*5 + minx
ypos = (z-1)*2 + (y-1)*3 + miny
local vox = renderVoxel(y,z,x)
if (vox) then
local vt = {}
for line in vox:gmatch("[^\n]+") do
local vtl = {}
for c in line:gmatch(".") do
table.insert(vtl,c)
end
table.insert(vt,vtl)
end
for ly,chars in ipairs(vt) do
for lx,c in ipairs(chars) do
if (c ~= "_") then
canvas[ypos+ly-1][xpos+lx-1] = c
end
end
end
table.insert(timeline,drawCanvas())
end
end
end
end
if (false) then -- change to true if you want to see the animation!
for i=1,#timeline do
local t = os.clock() + 0.05
io.write(timeline[i],'\n\n')
io.flush()
while (t > os.clock()) do end
end
end
print(timeline[#timeline])
```
Here is a sample of code that will populate the voxel matrix from a string for a 3x3x3 voxel matrix. (It will take any string in a similar format, but make sure it is a cube or things will probably break.)
To use this, insert this chunk right after the first line `local v = {}`
```
local vs = [[
100
000
000
110
100
000
111
110
101
]]
for layer in vs:gmatch("[^a]+") do
local a = {}
for row in layer:gmatch("[^\n]+") do
local b = {}
for _vox in row:gmatch("[01]") do
table.insert(b,(_vox=="1") and 1 or 0)
end
table.insert(a,b)
end
table.insert(v,a)
end
```
Here is the output from [the given 12x12x12 voxel](http://pastebin.com/GBwSyuvp) pattern: (and yes it does look better on a normal console/text viewing apparatus, there is a bit too much vertical spacing here)
```
+----+----+
/ /|
+----+----+ |
| | +
+----+ | |/
/ /| + +----+
+----+ | | | +----+
| | + | |/ /|
| | | + +----+ |
+ + | | | +
+----+----+ +----+--| | + | |/
/ /| / | | | + +----+
+----+----+ | +----+----+ + | | | +----+
| | + | | + | |/ /|
| |/ +----+----+----+ | | | + +----+ |
+ +----+ / /| + +----+ + | | | +
| | + +----+----+----+ | | | +--| | + | |/
| | | | | + | |/ | | | +----+----+
+ + | | | | + +----+ + |
| | + + +----+ + | | | +
| | | | | +--| | + | |/
+ + | | |/ | | | +----+----+----+
| | +----+ + +----+ + |
| |/ /| | | +
+ +----+ | | |/
| | + +----+----+----+
| |/
+----+----+ +----+----+
/ /|
+----+ +----+----+ |
/ /| | | +
+----+ | | |/
| | + + +----+
+----+----+----+ +----+----+----+----+---| | |---+| | +----+-+----+----+
/ /| / + + | | |/ /| /|
+----+----+----+ |+ | | + + +----+ | + |
| | + | | | | | + / +
| | | +----+----+----+ + + | | |/ + /
+ +----+ + | / /| | | + + +----+ / +
| | +--| | + +----+----+----+ | | | | | | + + /
| |/ | | | | | + + + | | | | / +
+ +----+ + | | | | | | + + + | + /
| | + + +----+ + | | | | | | + / +
| | | | | +--| | + + + | | |/ + /
+----+----+ + | | |/ | | | | | + +----+ / +
+----+--| | + + +----+ + | | |/ + /
/ | | | | | + +----+ / +
+----+----+ + | | |/ + /
| | + +----+----+----+ / +
| |/ + /
+----+----+----+ / +
+ + /
/ / +
+ + /
/ / +
+ + /
/ / +
+----+----+----+----+----+----+----+----+----+----+----+----+ /
| | +
| |/
+----+----+----+----+----+----+----+----+----+----+----+----+
```
Here is the output from [the 7x7x7 example here](http://pastebin.com/XZncYSTR)
```
+----+----+----+ +----+----+----+
/ /| / /|
+ +----+ + | + +----+ + |
/ /| / / + / /| / / +
+ + | + + / + + | + + /
/ / +-/ / + / / +-/ / +
+----+ /-+----+ /-+----+ /-+----+ /--+
| | + | | + | | + | | + /|
+----+ | |+----+ | |+----+ | |+----+ | | + |
/ /| + / /| + / /| + / /| + |/ +
+ + | |+ + | |+ + | |+ + | | + |
/ / + / / + / / + / / + | + |
+ +----+ + |+ +----+ + | + /| +
/ / + / / + | | + | |
+----+----+----+ /|+----+----+----+ /| + |/--+ |
| | + || | + | |-+ / +
| |/--+| |/--+ | + /
+----+----+----+ / +----+----+----+ / + / +
+ + / + +----+ + /-+ + /--+ /--+
/ / + / / + / / + | + /|
+----+ / +----+----+----+ /-+----+ /--+ |/ + |
| | + | | + | | + /|-+ / +
| | |-+| |/ +| | | + | + /
+ + | +----+----+----+ /|+ + |/ + / +
| | +----+----+ | |+ + || | + /--+ /
| |/ /| + / / +| | + | +
+ +----+----+ | |+----+ /-+ + /--+ |/
| | + || | + | | + /|-+
| | | +| | | +| |/ + |
+----+----+ + | |+ + |/|+----+ / +
+ +--| | + || | + | + + /
/ | | |-+| | +-/ / +
+----+----+ + | + + / +----+ /
| | + | | + | | +
| |/ | |/ | |/
+----+----+----+ +----+ +----+
```
[Answer]
# Python ( 444 361 354 bytes)
*Edit:* I found another bug that would omit a corner cross in very special cases. A straight forward fix added 50 bytes to the code so I tried to golf it down a bit further. Now the bug is fixed and it's even 83 bytes shorter. It's becoming very hacky. I also wanted to get rid of the fivefold for loop but could not yet find a solution. Any ideas?
*Edit 2:* With a very long import I can save another 7 characters.
Neither very short nor very elegant, but then again it is a complex problem:
```
#input:
u=[[[1,1,1],[1,0,1],[1,1,1]],
[[1,0,1],[0,0,0],[1,0,1]],
[[1,1,1],[1,0,1],[1,1,1]]]
#actual code that counts:
r=range
n=len(u)
g=r(n)
a=([' ']*9*n+['\n'])*6*n
t='/|-+\n '
d=dict(zip(t+'%!=*',2*t))
for y,z,x,i,j in __import__('itertools').product(g,g,g[::-1],r(6),r(8)):
if abs(i+j-6)<5*u[x][y][z]:a[(9*n+1)*(i+3*x+2*y)+j+5*z-2*y+2*n]+='./ %|+====* || ! *| !/.*----+'[8*i+j-8]
o=''.join((d[x[-1]],' ')[x[-2:]in('%/','!|','=-')or x[-4:]=='*++*']for x in a)
#output:
print o
```
It first draws all the individual voxels with all lines on top of each other. Then it outputs only the topmost characters and gets rid of those lines and crosses on planar planes that should not be drawn according to the specs.
I guess it's possible to golf this down quite some more, but 444 is such a nice number. :)
Example 3x3x3 and 7x7x7 output (with some newlines removed):
```
+----+----+----+
/ /|
+ +----+ + |
/ /| / / +
+ +----+ + |
/ / + |
+----+----+----+ /| +
| | + | |
| | |-+ |
+ +----+ + |/ +
| | +--| | + /
| |/ | | +
+ +----+ + /
| | +
| |/
+----+----+----+
+----+----+----+ +----+----+----+
/ /| / /|
+ +----+ + | + +----+ + |
/ /| / / + / /| / / +
+ + | + + / + + | + + /
/ / +-/ / + / / +-/ / +
+----+ /-+----+ /-+----+ /-+----+ /--+
| | + | | + | | + | | + /|
+----+ | |+----+ | |+----+ | |+----+ | | + |
/ /| + / /| + / /| + / /| + |/ +
+ + | |+ + | |+ + | |+ + | | + |
/ / + / / + / / + / / + | + |
+ +----+ + |+ +----+ + | + /| +
/ / + / / + | | + | |
+----+----+----+ /|+----+----+----+ /| + |/--+ |
| | + || | + | |-+ / +
| |/--+| |/--+ | + /
+----+----+----+ / +----+----+----+ / + / +
+ + / + +--- + + /-+ + /--+ /--+
/ / + / / + / / + | + /|
+----+ / +----+----+----+ /-+----+ /--+ |/ + |
| | + | | + | | + /|-+ / +
| | |-+| |/ +| | | + | + /
+ + | +----+----+----+ /|+ + |/ + / +
| | +----+----+ | |+ + || | + /--+ /
| |/ /| + / / +| | + | +
+ +----+----+ | |+----+ /-+ + /--+ |/
| | + || | + | | + /|-+
| | | +| | | +| |/ + |
+----+----+ + | |+ + |/|+----+ / +
+ +--| | + || | + | + + /
/ | | |-+| | +-/ / +
+----+----+ + | + + / +----+ /
| | + | | + | | +
| |/ | |/ | |/
+----+----+----+ +----+ +----+
```
] |
[Question]
[
There was a challenge to [convert a number to its numeral in English](https://codegolf.stackexchange.com/q/32151/29750), but that was too straightforward. Given a number 0–100, your task is to output the corresponding numeral in French. The French numeral system has a more complex logic behind it compared to the English one:
```
Number Numeral
---------------
0 zéro (note the accent)
1 un
2 deux
3 trois
4 quatre
5 cinq
6 six
7 sept
8 huit
9 neuf
10 dix
11 onze
12 douze
13 treize
14 quatorze
15 quinze
16 seize
17 dix-sept (literally ten seven)
18 dix-huit
19 dix-neuf
20 vingt
21 vingt et un (no hyphens)
22 vingt-deux
...
30 trente
...
40 quarante
...
50 cinquante
...
60 soixante
...
70 soixante-dix (literally sixty ten)
71 soixante et onze
...
80 quatre-vingts (note the s; literally four twenties)
81 quatre-vingt-un (note the hyphens)
...
90 quatre-vingt-dix
91 quatre-vingt-onze
...
99 quatre-vingt-dix-neuf (4*20+10+9)
100 cent
```
For a complete list, follow <http://quizlet.com/996950/> (<http://www.webcitation.org/6RNppaJx0>).
## Further rules/explanations
* There will always be a hyphen between words EXCEPT when the number ends in 1.
* When the number ends in 1, the word *et* (meaning *and*) is added before the *un* or *onze*. (31 = trente et un)
* However, 81 and 91 are formatted the same as the other numbers. (81 = quatre-vingt-un)
* At 60, the system switches from base 10 to base 20.
* There are some minor discrepancies across the web about this; refer to the list linked above for questions.
* [Loopholes that are forbidden by default](https://codegolf.meta.stackexchange.com/q/1061/29750) are not allowed.
* Using an external source such as a website, as well as any libraries, APIs, functions, or the like that convert numbers to numerals or translate to French are not allowed.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the answer with the fewest bytes wins.
* If available, please link to an online compiler to allow for easy testing of your code.
## Input
* Input shall be taken from however your language takes input. (STDIN, command line, etc.)
* Input will be a single string, consisting of a whole number between 0 and 100 inclusive (leading zeroes optional).
* You can assume the input will always be well-formed.
## Output
* The result shall be output to the most convenient method for your language. (STDOUT, dialog box, etc.)
* Case does not matter in the output.
## Examples
Test your code against these:
```
Input Output
-------------
0 zéro
18 dix-huit
51 cinquante et un
80 quatre-vingts
91 quatre-vingt-onze
99 quatre-vingt-dix-neuf
```
[Answer]
# JavaScript (ES6) 318 ~~321~~
*Edit* Bug fix (managing leading 0s) and golfed more
*Credit for the camel case trick* [@Core1024](https://codegolf.stackexchange.com/questions/35036/what-is-your-star-sign/35271#comment77106_35050)
**With input/output via popup**
```
alert((n=prompt(),w='ZéroUnDeuxTroisQuatreCinqSixSeptHuitNeufDixOnzeDouzeTreizeQuatorzeQuinzeSeizeDix-septDix-huitDix-neufVingtTrenteQuaranteCinquanteSoixante'.match(/[A-Z][^A-Z]+/g),
u=n%10,s=u-1|n>80?d='-':' et ',n>99?'Cent':n<21?w[n|0]:n<70?w[18+n/10|0]+(u?s+w[u]:''):(n<80?w[24]:w[4]+d+w[20])+(n-80?s+w[n%20]:'s')))
```
**As a testable function**
```
F=n=>(
w='ZéroUnDeuxTroisQuatreCinqSixSeptHuitNeufDixOnzeDouzeTreizeQuatorzeQuinzeSeizeDix-septDix-huitDix-neufVingtTrenteQuaranteCinquanteSoixante'
.match(/[A-Z][^A-Z]+/g),
u=n%10,s=u-1|n>80?d='-':' et ',
n>99?'Cent':
n<21?w[n|0]:
n<70?w[18+n/10|0]+(u?s+w[u]:''):
(n<80?w[24]:w[4]+d+w[20])+(n-80?s+w[n%20]:'s')
)
```
**To Test** In FireFox console or FireBug
```
for (i = 0; i < 100; console.log(r),i+= 10)
for (j=0, r=''; j < 10; j++)
r+=(i+j)+':'+F(i+j+'')+", "; // specific: input is a string
F('100')
```
**Test Output**
```
0:Zéro, 1:Un, 2:Deux, 3:Trois, 4:Quatre, 5:Cinq, 6:Six, 7:Sept, 8:Huit, 9:Neuf,
10:Dix, 11:Onze, 12:Douze, 13:Treize, 14:Quatorze, 15:Quinze, 16:Seize, 17:Dix-sept, 18:Dix-huit, 19:Dix-neuf,
20:Vingt, 21:Vingt et Un, 22:Vingt-Deux, 23:Vingt-Trois, 24:Vingt-Quatre, 25:Vingt-Cinq, 26:Vingt-Six, 27:Vingt-Sept, 28:Vingt-Huit, 29:Vingt-Neuf,
30:Trente, 31:Trente et Un, 32:Trente-Deux, 33:Trente-Trois, 34:Trente-Quatre, 35:Trente-Cinq, 36:Trente-Six, 37:Trente-Sept, 38:Trente-Huit, 39:Trente-Neuf,
40:Quarante, 41:Quarante et Un, 42:Quarante-Deux, 43:Quarante-Trois, 44:Quarante-Quatre, 45:Quarante-Cinq, 46:Quarante-Six, 47:Quarante-Sept, 48:Quarante-Huit, 49:Quarante-Neuf,
50:Cinquante, 51:Cinquante et Un, 52:Cinquante-Deux, 53:Cinquante-Trois, 54:Cinquante-Quatre, 55:Cinquante-Cinq, 56:Cinquante-Six, 57:Cinquante-Sept, 58:Cinquante-Huit, 59:Cinquante-Neuf,
60:Soixante, 61:Soixante et Un, 62:Soixante-Deux, 63:Soixante-Trois, 64:Soixante-Quatre, 65:Soixante-Cinq, 66:Soixante-Six, 67:Soixante-Sept, 68:Soixante-Huit, 69:Soixante-Neuf,
70:Soixante-Dix, 71:Soixante et Onze, 72:Soixante-Douze, 73:Soixante-Treize, 74:Soixante-Quatorze, 75:Soixante-Quinze, 76:Soixante-Seize, 77:Soixante-Dix-sept, 78:Soixante-Dix-huit, 79:Soixante-Dix-neuf,
80:Quatre-Vingts, 81:Quatre-Vingt-Un, 82:Quatre-Vingt-Deux, 83:Quatre-Vingt-Trois, 84:Quatre-Vingt-Quatre, 85:Quatre-Vingt-Cinq, 86:Quatre-Vingt-Six, 87:Quatre-Vingt-Sept, 88:Quatre-Vingt-Huit, 89:Quatre-Vingt-Neuf,
90:Quatre-Vingt-Dix, 91:Quatre-Vingt-Onze, 92:Quatre-Vingt-Douze, 93:Quatre-Vingt-Treize, 94:Quatre-Vingt-Quatorze, 95:Quatre-Vingt-Quinze, 96:Quatre-Vingt-Seize, 97:Quatre-Vingt-Dix-sept, 98:Quatre-Vingt-Dix-huit, 99:Quatre-Vingt-Dix-neuf,
"Cent"
```
[Answer]
# Haskell, 390 bytes
```
b=(words"zéro un deux trois quatre cinq six sept huit neuf dix onze douze treize quatorze quinze seize vingt trente quarante cinquante soixante"!!)
a!b=a++"-"++b
f 0=b 0
f 71=f 60++" et onze"
f 80=f 4!b 17++"s"
f 100="cent"
f x|x<17=b x|x<20=b 10!b(x-10)|x>80=b 4!b 17!f(x-80)|m==1=f(x-1)++" et un"|x>60=f 60!f(x-60)|m==0=b(15+div x 10)|1<2=f(x-m)!f m where m=mod x 10
main=interact$f.read
```
Ungolfed
```
base :: Int -> String
-- 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
base i = words "zéro un deux trois quatre cinq six sept huit neuf dix onze douze treize quatorze quinze seize vingt trente quarante cinquante soixante" !! i
hyphen :: String -> String -> String
a `hyphen` b = a ++ "-" ++ b
say :: Int -> String
say 0 = base 0
say 71 = say 60 ++ " et onze"
say 80 = say 4 `hyphen` base 17 ++ "s"
say 100 = "cent"
say x
| x < 17 = base x
| x < 20 = base 10 `hyphen` base (x - 10)
| x > 80 = base 4 `hyphen` base 17 `hyphen` say (x - 80)
| m == 1 = say (x - 1) ++ " et un"
| x > 60 = say 60 `hyphen` say (x - 60)
| m == 0 = base (div x 10 + 15)
| otherwise = say (x - m) `hyphen` say m
where m = mod x 10
main = putStr.say.read=<<getLine
```
Functional programming languages are quite suitable for this job.
[Answer]
# Python - 344 ~~(348)(380)(445)(537)~~ bytes
Thanks to grc, Ray and isaacg for their help in the golfing process.
The code consists of the initial dictionary definition and a list comprehension that fills in the blanks with the junction of the dictionary's elements.
You can check the code online at [repl.it](http://repl.it/WLD/2)
```
r=range
def f(a):b=a/60*10+10;d[a]=d[a-a%b]+(' et ','-')[a%10!=1or a>80]+d[a%b]
d=dict(zip(r(17)+r(20,70,10)+[80,100],'zéro un deux trois quatre cinq six sept huit neuf dix onze douze treize quatorze quinze seize vingt trente quarante cinquante soixante quatre-vingt cent'.split()))
[f(v)for v in r(100)if(v in d)<1]
d[80]+='s'
print d[input()]
```
My latest attempts to golf this code have been to forgo the generation process and with that reduction refine the function to just generate the requested number on the spot. However, since the 60 and 80's numbers need uncalculated elements, the struggle has been to create such a function while decreasing code.
[Answer]
## Ruby, 333 bytes
```
l=['']+%w{un deux trois quatre cinq six sept huit neuf dix onze douze treize quatorze quinze seize}
d=%w{vingt trente quarante cinquante soixante _ quatre-vingt}+['']*2
n=gets.to_i
v=n%20
t=n%10
puts n<1?'zéro':n>99?'cent':d[(n<70?n:n-v)/10-2]+(n<21||t<1&&n<61?'':v<1??s:t==1&&n<80?' et ':?-)+(n>60||n<20?v<17?l[v]:'dix-'+l[t]:l[t])
```
It's mostly just two look up tables and a bunch of ternary operators that encode all of the weird rules and tell you which lookup table to use when. Let me know if you want to know more. ;)
[Answer]
# Python - 392 bytes
It has a list with base numbers which it uses to generate the other numbers. Most of the generation logic is in the list comprehension on line 2, using list indexing for conditionals. Once the list is generated it then looks up the inputted number and prints it.
Edit: Shortened from 426 bytes using grc's tip.
```
a='_un_deux_trois_quatre_cinq_six_sept_huit_neuf_dix_onze_douze_treize_quatorze_quinze_seize_dix-sept_dix-huit_dix-neut'.split('_')
a+=[[['vingt','trente'],['quarante','cinquante'],['soixante']*2,[a[4]+'-vingt']*2][b][c>9]+['','-',' et '][(c%[10,20][b>1]>0)+(c%10==1)*(b<3)]+a[c%[10,20][b>1]]for b in[0,1,2,3]for c in range(20)]
a[0]='zéro'
a[80]+='s'
a+=['cent']
print(a[int(input())])
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~150~~ 149 bytes
```
`UV7*Y8÷6*xsYαƵΓYåi<6LXåDX«U_}X8+).•2!ÛÄÒÁw§#Kºγ‚¼8&òo£Ù0ÿM¾…hTвcтv›IÈΩ{т3)`pñ"O|BεÆõ¿-∍£¸±<¥Ð~„Ñzä₂-bζÅ'á`†^=/Rú÷hÕS»•#ÁsèõK…-ˆÆ ć‚R7L1«IåèýI_i"zéro
```
[Try it online!](https://tio.run/##Ae8AEP9vc2FiaWX//2BVVjcqWTjDtzYqeHNZzrHGtc6TWcOlaTw2TFjDpURYwqtVX31YOCspLuKAojIhw5vDhMOSw4F3wqcjS8K6zrPigJrCvDgmw7JvwqPDmTDDv03CvuKApmhU0LJj0YJ24oC6ScOIzql70YIzKWBww7EiT3xCzrXDhsO1wr8t4oiNwqPCuMKxPMKlw5B@4oCew5F6w6TigoItYs62w4Unw6Fg4oCgXj0vUsO6w7dow5VTwrvigKIjw4Fzw6jDtUvigKYty4bDhiDEh@KAmlI3TDHCq0nDpcOow71JX2kiesOpcm///zA3MQ "05AB1E – Try It Online") or [validate all possible inputs](https://tio.run/##Af4AAf9vc2FiaWX/0YLGkk7igoQrwqb/YFVWNypZOMO3Nip4c1nOsca1zpNZw6VpPDZMWMOlRFjCq1VffVg4Kyku4oCiMiHDm8OEw5LDgXfCpyNLwrrOs@KAmsK8OCbDsm/Co8OZMMO/TcK@4oCmaFTQsmPRgnbigLpJw4jOqXvRgjMpYHDDsSJPfELOtcOGw7XCvy3iiI3Co8K4wrE8wqXDkH7igJ7DkXrDpOKCgi1izrbDhSfDoWDigKBePS9Sw7rDt2jDlVPCu@KAoiPDgXPDqMO1S@KApi3LhsOGIMSH4oCaUjdMMcKrTsOlw6jDvU5faSJ6w6lyb/8iwqh9LClc/w)
Takes input 0-padded to length 3.
[Answer]
# Python 3, (503 bytes)
Compress the table using bzip2 and then use ascii85 encoding to store the result. The table is:
```
zéro
un
deux
trois
quatre
cinq
...
cent
```
Very naive method, but it's not that bad.
# Golfed
```
import bz2,base64 as B
print(bz2.decompress(B.a85decode('6<\\%_0gSqh;d"=$\\VU:fOjTBn&3p:MiVu^S+:%s4!Q6o8\\8%r<Bp,5\\LT&Q+19!OmJC@3n\'bD<]UHekq<8OP<;]9BZ,;>836X4<[@KJ,)FsD^8j9Q=]O]&/8\'rjSK&0Sh0W[ru0E0!!M-tL69NZF6N\'Lc#$Q=?S_P0+uEZP"[H;%Ucch??nYC76\'k<)isZIBqqOKi(,IHp""^8d/EqRpc_I<IRj[\'4KB`/."%5,"pjr&27q+&t.6J+ik=Jdd2A)j]\'jt5ts0>:sr9.@E>V0F9L?9r&pX\'E.NUP:r&?>\'*(gKmd;/1QkUb*1&JhfWiE7Kl,P,o1go+.3O&l))Y,$/PO)%"al^4H2,n-l\\PuM!W1rBB9t.,U>DhAs83burMn(%%-qHG<gr+^')).decode().split('\n')[int(input())])
```
## Ungolfed
```
import bz2, base64
s = '6<\\%_0gSqh;d"=$\\VU:fOjTBn&3p:MiVu^S+:%s4!Q6o8\\8%r<Bp,5\\LT&Q+19!OmJC@3n\'bD<]UHekq<8OP<;]9BZ,;>836X4<[@KJ,)FsD^8j9Q=]O]&/8\'rjSK&0Sh0W[ru0E0!!M-tL69NZF6N\'Lc#$Q=?S_P0+uEZP"[H;%Ucch??nYC76\'k<)isZIBqqOKi(,IHp""^8d/EqRpc_I<IRj[\'4KB`/."%5,"pjr&27q+&t.6J+ik=Jdd2A)j]\'jt5ts0>:sr9.@E>V0F9L?9r&pX\'E.NUP:r&?>\'*(gKmd;/1QkUb*1&JhfWiE7Kl,P,o1go+.3O&l))Y,$/PO)%"al^4H2,n-l\\PuM!W1rBB9t.,U>DhAs83burMn(%%-qHG<gr+^'
table = bz2.decompress(base64.a85decode(s)).decode().split('\n')
num = int(input())
print(table[num])
```
---
## Bonus
Can you find the word "Vim" in the compressed string ?
[Answer]
# Bash, ~~456 440 421~~ 408
Assumes valid input (integer from 0 to 100 with any number of leading zeroes).
```
v=`sed 's/0*//'<<<$1`
f=('' dix vingt trente quarante cinquante soixante soixante-dix quatre-vingts quatre-vingt-dix)
s=('' ' et un' -deux -trois -quatre -cinq -six -sept -huit -neuf)
o=${f[${v: -2:1}]}${s[${v: -1:1}]}
[ "${o:0:1}" = \ ]&&o=un
((v>99))&&o=cent
sed 's/^-//
s/s-/-/
s/s et /-/
s/dix et un/onze/
s/di.*ux/douze/
s/d.*s$/treize/
s/d.*re/quatorze/
s/d.*q/quinze/
s/di.*ix/seize/'<<<${o:-zéro}
```
[Answer]
# JavaScript 459 (No Camel Casing)
@edc65 can't take that from you... ;)
`A="0un0deux0trois0quatre0cinq0six0sept0huit0neuf0dix0onze0douze0treize0quatorze0quinze0seize0dix-sept0dix-huit0dix-neuf".split(0);S="soixante";Q=A[4]+"-vingt";T=10;V=20;N=59;for(b=5;1<b--;)for(c=V;c--;)X=b*V+c,A[X]=[,["vingt","trente"],["quarante","cinquante"],[S,S],[Q,Q]][b][c/T|0]+(X%T?X>N?X%V==T?"-dix":"":"":"")+(1>X%T?"":(1==X%(X>N?V:T)|71==X)&81!=X?" et ":"-")+(X>N&X%V==T?"-dix":A[c%(X>N?V:T)]);A[0]="zéro";A[80]+="s";A[100]="cent";alert(A[prompt()])`
] |
[Question]
[
We see a lot of challenges here asking for a function to create a sequence from the [OEIS](https://oeis.org/). While these challenges are fun, as a programmer I see an opportunity for automation.
Your challenge is to make a program that takes the index of a sequence (e.g. [A172141](https://oeis.org/A172141)) and some integer n (e.g. 7), and pulls the appropriate value from the appropriate webpage.
## I/O
As mentioned, your program should take a sequence index and some value n as input and output the nth term in that sequence. You accept any index in the sequence's [B-files](https://oeis.org/wiki/B-files). If the index is greater than the largest index listed in the B-files you may throw an exception or output whatever you choose (these are not in the test cases). Standard methods of input and output are permitted.
## Restrictions on web use
You should not access any websites other than <https://oeis.org> and <http://oeis.org>. This includes url shorteners, your own personal website, and this question itself. If you would like to access some other website and you believe that it is not unfair to allow you to do so, you can leave a comment and I will arbitrate.
## Scoring
This is a code golf challenge so the program with the least bytes used in its source code wins. Standard loopholes are disallowed.
## Test Cases
Assuming that your machine has proper internet connection and the OEIS servers are up and running the following inputs and outputs should correspond.
```
A172141, 7 -> 980
A173429, 4 -> 276
A190394, 6 -> 16
A002911, 11 -> 960
A052170, 3 -> 24
A060296, 8 -> 3
A178732, 5 -> 27
A000001, 1 -> 1
A000796, 314 -> 3
A001622, 162 -> 8
A002206, -1 -> 1
```
## Tip
* When accessing the B-files `http://oeis.org/b<A-number>.txt` will redirect to the proper B-file.
[Answer]
# Bash + coreutils + w3m, ~~51~~ ~~45~~ 42 bytes
```
w3m oeis.org/b${1:1}.txt|sed "s/^$2 //p;d"
```
*Thanks to @EamonOlive for golfing off 3 bytes!*
### Example run
```
$ bash oeis.sh A172141 7
980
```
### How it works
[*w3m*](http://w3m.sourceforge.net/) is a text-based web browser, which displays both HTML and plain text in readable format. Unlike *curl*, it follows redirects by default (this is required, since `oeis.org/bxxxxxx.txt` redirects to `oeis.org/Axxxxxx/bxxxxxx.txt`), doesn't produce any stray output to STDERR, and has a three-byte name.
The command
```
w3m oeis.org/b${1:1}.txt
```
the desired URL, where `${1:1}` is the first command-line argument without its first character.
The output is piped to the command
```
sed "s/^$2 //p;d"
```
which extracts the desired output. `s/^$2 //p` attempts to replace `^$2` (start of line, followed by the second command-line argument, followed by a space) with the empty string. If the substitution is successful, `p` prints its result. Afterwards, `d` unconditionally deletes the pattern to prevent *sed* from printing the entire input.
[Answer]
# Mathematica + [OEIS.m](http://oeis.org/wiki/User%3aEnrique_P%C3%A9rez_Herrero/OEIS_Package#Download_and_Install_OEIS.m), 31
```
(OEISFunction@ToString@#;#@#2)&
```
example usage: `%[A172141,36]`
---
# Mathematica, 85
```
#2/.Rule@@@Import["http://oeis.org/b"<>#~StringDrop~1<>".txt","Data"]~DeleteCases~{}&
```
example usage: `%["A002206",-1]`
[Answer]
## Perl, 59 bytes
```
($_,$v)=@ARGV;/./;say`curl oeis.org/$_/b$'.txt`=~/$v (.*)/m
```
Needs `-M5.010` or `-E` to run. For instance :
```
$ cat oeis.pl
($_,$v)=@ARGV;/./;say`curl oeis.org/$_/b$'.txt`=~/$v (.*)/m
$ perl -M5.010 oeis.pl A178932 5 2>&-
27
```
*Saved 8 bytes thanks to @Dennis [answer](https://codegolf.stackexchange.com/a/89386/55508), by removing `http://`, as he did.*
[Answer]
# CJam, 36 bytes
```
"oeis.org/b"r1>+".txt"+gN%Sf%z~\ra#=
```
### Example run
```
$ cjam oeis.cjam <<< 'A172141 7'
980
```
[Answer]
# Python 2, ~~125~~ ~~118~~ 113 bytes
***~~7~~ 12 bytes saved thanks to Lynn***
```
import re,urllib2 as u;lambda x,y:re.findall("(?<=%d ).*"%y,u.urlopen("http://oeis.org/b%s.txt"%x[1:]).read())[0]
```
Well heres my go at my own problem. It is likely suboptimal but I think I did a pretty decent job. It creates an anonymous function that takes a string and integer as arguments and returns a string as the result or throws an error if the index is out of range.
This can be made into a 124 bytes full program.
```
import re,urllib2 as u;print re.findall("(?<=%d ).*"%input(),u.urlopen("http://oeis.org/b%s.txt"%raw_input()[1:]).read())[0]
```
This prompts the user for the input. First asking for the index and then the A-number of the sequence.
[Answer]
# Python 3, ~~153~~ ~~146~~ 135 bytes
**7 bytes thanks to FryAmTheEggman.**
**6 bytes thanks to Eamon Olive.**
**5 bytes thanks to Rod.**
```
from urllib.request import*
def f(a,n):
for l in urlopen("http://oeis.org/b%s.txt"%a[1:]):
p,q=l.split()
if n==p.decode():return q
```
Call it like this:
```
print(f("A000796","314"))
```
Run on a machine where the default is utf-8.
[Answer]
# PHP 5.6, ~~93~~ 92 bytes
```
function f($i,$l){echo explode(' ',file('http://oeis.org/b'.substr($i,1).'.txt')[--$l])[1];}
```
This one is pretty straight forward. Pull the page with `file()`, get the line at `$line - 1` (0-index), explode on the space and print out the second array element from that.
[Answer]
# [Nim](http://nim-lang.org/), ~~123~~ ~~115~~ 113 bytes
```
import httpclient,nre,future
(a,n)=>get getContent("http://oeis.org/b"&a[1..^0]&".txt").find re "(?<="&n&r" )\d+"
```
This is a lambda expression; to use it, it must be passed as an argument to a testing procedure. A complete program that can be used for testing is given here:
```
import httpclient,nre,future
proc test(x: (string, string) -> RegexMatch) = echo x("A172141", "7") # Your input here
test((a,n)=>get getContent("http://oeis.org/b"&a[1..^0]&".txt").find re "(?<="&n&r" )\d+")
```
Expects input as two strings. Example usage:
```
$ nim c oeis.nim
$ ./oeis
980
```
We use `httpclient`'s `getContent` proc to get the OEIS b-file, then use a regex to `find` the line with the index. `find` returns an `Option[RegexMatch]`, so we use `get` to retrieve the value from the `Option`. `echo` automatically stringifies, so we leave stringification out.
[Answer]
## R, ~~94~~ 89 bytes
```
t=read.table(paste0("http://oeis.org/b",substring(scan(,""),2),".txt"));t[t$V1==scan(),2]
```
Using `sprintf` instead of `paste0` results in the same bytecount:
```
t=read.table(sprintf("http://oeis.org/b%s.txt",substring(scan(,""),2)));t[t$V1==scan(),2]
```
*Five bytes saved thanks to [plannapus](https://codegolf.stackexchange.com/users/6741/plannapus).*
[Answer]
## Clojure, 103
```
#(read-string((re-find(re-pattern(str %2" (\\d+)"))(slurp(str"http://oeis.org/b"(subs % 1)".txt")))1)))
```
`re-find` finds a vector of first matche's regex groups, it is used as a function and `1` gets the string at position `1`. `read-string` converts string to int. I'm not 100% sure if this regex always finds the correct row.
[Answer]
# R, 87 bytes
```
f=function(A,n)(R<-read.table(gsub("A(\\d+)","http://oeis.org/b\\1.txt",A)))[R$V1==n,2]
```
Build the URL string with regexes instead of `paste` or `sprintf`.
[Answer]
# Node.js + `request`, 109 bytes
```
x=>n=>require('request')(`http://oeis.org/b${x.slice(1)}.txt`,(a,b)=>console.log(b.body.match(n+` (.+)`)[1]))
```
Takes the sequence ID and a number.
[Answer]
# Julia, 88 bytes
```
x\y=match(Regex("$y (.*)"),readall(Requests.get("http://oeis.org/b$(x[2:end]).txt")))[1]
```
*Golfed with some help from @Dennis!*
Make sure you have `Requests.jl` installed before running.
[Answer]
## [ListSharp](https://github.com/timopomer/ListSharp), 266 bytes
```
STRG a=READ[<here>+"\\a.txt"]
ROWS x=ROWSPLIT a BY [","]
STRG a=GETRANGE x[0] FROM [2] TO [a LENGTH]
NUMB y=<c#int.Parse(x[1])c#>
STRG a=DOWNLOAD["http://oeis.org/b"+a+".txt"]
ROWS x=ROWSPLIT a BY [<newline>]
STRG a=GETLINE x [y]
ROWS x=ROWSPLIT a BY [" "]
SHOW=x[1]
```
Its sad when a language made for web scraping needs so many lines because nesting statements in ListSharp is *taboo*
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 29 bytes
```
¦’ÏÁ€ˆ.µÔ/bÿ.í¼t’.w¶¡€#˜DIk>è
```
Beats all other answers.
```
¦’...’.w¶¡€#˜DIk>è # trimmed program
è # 0-based...
k # 0-based index of...
I # input...
k # in...
˜D # flattened list of...
.w # content of response from url...
# (implicit) "http://" concatenated with...
’...’ # "oeis.org/bÿ.txt"...
# (implicit) with ÿ replaced by...
# implicit input...
¦ # excluding the first character...
¡ # split by...
¶ # newlines...
€ # with each element...
# # split by spaces...
> # plus 1...
è # th element in...
˜ # flattened list of...
.w # content of response from url...
# (implicit) "http://" concatenated with...
’...’ # "oeis.org/bÿ.txt"...
# (implicit) with ÿ replaced by...
# implicit input...
¦ # excluding the first character...
¡ # split by...
¶ # newlines...
€ # with each element...
# # split by spaces
```
] |
[Question]
[
Your task is to take a sequence of characters (the music) as input (in a function or program), and print (or return) the music as it would look like in a music box.
You will only receive the characters `ABCDEFG.()` as input, and the input will never be empty. You may also receive the letters in lowercase, if you wish for it.
This is an empty music box, of length 3:
```
.......
.......
.......
```
As you can see, the lines are 7 characters long, and since the length of the music box is 3, we have 3 lines. There are only `.`s here, since the music box is empty. Let's put some music in it!
First, we create the music box. In this example, the input will be `CDAG.DAG`.
The length of `CDAG.DAG` is 8, so we need a music box of length 8:
```
.......
.......
.......
.......
.......
.......
.......
.......
```
Then, we read the input, one character at a time, and place an `O` at its respective position.
The first character is `C`, and the location of each note is equivalent to this (I added spaces for clarity):
```
A B C D E F G
. . . . . . .
. . . . . . .
(and so on)
```
If the input character is a `.`, then we just print an empty line `.......`
So, the `C` would be the 3rd character along. Let's put it in our music box at the top:
```
..O....
.......
.......
.......
.......
.......
.......
.......
```
We will repeat this process for all the other characters (the text in brackets is just to show you the note, you shouldn't output that):
```
..O.... (C)
...O... (D)
O...... (A)
......O (G)
....... (.)
...O... (D)
O...... (A)
......O (G)
```
Because of how music boxes work, if we use a character other than `O`, `.` and `<insert newline here>`, such as a space, in our output, then it won't play the correct music!
This is a chord:
```
(ACE)
```
This chord is instructing us to play the notes `A`, `C` and `E` at the same time. There will never be a pause (ie a `.`) in a chord.
This is how it would be written:
```
O.O.O...
```
And this is how it might appear in music: `B(ACE)D`
You will never receive a chord in a chord, ie this won't be valid: `(AB(CD)EF)` or this: `A(B())`, and chord will not be empty, ie this won't be valid: `A()B`
You will never receive an invalid input.
### Examples:
```
B(ACE)D
.O.....
O.O.O..
...O...
B
.O.....
GGABC
......O
......O
O......
.O.....
..O....
...
.......
.......
.......
A..F.C(DA).
O......
.......
.......
.....O.
.......
..O....
O..O...
.......
.(ABCDEF)
.......
OOOOOO.
```
Trailing/leading whitespace on the output is permitted.
As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code wins!
[Answer]
# [Python 2](https://docs.python.org/2/), ~~95~~ 94 bytes
-1 byte thanks to Value Ink
```
x=1
for i in input():
if x:o=['.']*7
if'@'<i:o[ord(i)-65]='O'
if'*'>i:x=i>'('
if x:print o
```
[Try it online!](https://tio.run/nexus/python2#@19ha8iVll@kkKmQmQdEBaUlGppWXAqZaQoVVvm20ep66rFa5iC@uoO6TaZVfnR@UYpGpqaumWmsrbq/OlhGS90u06rCNtNOXUMdqrWgKDOvRCH//391Jw1HZ1dNF/X/AA "Python 2 – TIO Nexus") or [Try all test cases](https://tio.run/nexus/python2#VY47CsMwDED3nEKb7JAKOrQFU4c637EHSLOlBi12MCnk9q6T0KGDJPQe@sTpbcEKdvNnkSqDVZ8zsD4AAzvYcaLAFlbl9YCEY37bAT7wzsoPPkyC5el6GTU@8VA5lqxWzSUK/E3Pgd0CPv4vF9vRQ@HLYcHZ9o2MA1bC1K1ssMAqRd@bqk6ViFI2RB3VojFy60gk17SdxDF@AQ "Python 2 – TIO Nexus")
### Explanation
`'@'<i` is to check if `i` is a letter, replacing the `.` by `O` on the right position.
`'*'>i` is to check if `i` is a parenthesis, if it is `x=i>'('` will put `0` on `x` to prevent the printing/clearing of `o`, when `i==')'`, it will put `1` on `x` re-enabling the printing/clearing of `o`.
When `i=='.'` nothing will be changed, and `'.......'` will be printed.
The charater order is given by their ASCII code, where `'('<')'<'*'<'.'<'@'<'A'`
[Answer]
## Batch, 209 bytes
```
@set s=%1
@set p=)
@for %%n in (a b c d e f g)do @set %%n=.
:g
@if %s:~,1% lss @ (set "p=%s:~,1%")else set %s:~,1%=O
@set s=%s:~1%
@if %p%==( goto g
@echo %a%%b%%c%%d%%e%%f%%g%
@if not "%s%"=="" %0 %s%
```
Works by accumulating letters and outputting the line if the last symbol seen was not a `(`.
[Answer]
# [Röda](https://github.com/fergusq/roda), ~~97~~ ~~78~~ 76 bytes
```
{search`\(\w+\)|.`|{|c|seq 65,71|{|l|["O"]if[chr(l)in c]else["."]}_;["
"]}_}
```
[Try it online!](https://tio.run/nexus/roda#VYq7DoJAFERr@IqbW@0q3sRCLYgF79IPWIiQdTeQIChoLFi@HYHYWM2cOXMvqmawLX1Op6FXRSfLPGXpZ5tyQ7kZjDS9esLx4Jz2M9VG4AWzSgtZdqzmVQMyU3WvBBJm49UVaC85TpZAn3lBxEN0AJPE84OlENESHlFMAQs9viKxWYdRnHDMwMAAj65qXiDbm3J/HXe4Oc3w7st1n2/6z8EIuu1WZ4/TFw "Röda – TIO Nexus")
It's an anonymous function that reads the input from the stream. Use it like this: `main { f={...}; push("ABCD") | f() }`. It uses the regex from ETHproductions' answer.
Ungolfed:
```
{
search(`\(\w+\)|.`) | for chord do
seq(ord("A"), ord("G")) | for note do
if [ chr(note) in chord ] do
push("O")
else
push(".")
done
done
push("\n")
done
}
```
Previous answer:
```
f s{(s/"(?=([^()]*(\\([^()]*\\))?)*$)")|{|c|seq 65,71|{|l|["O"]if[chr(l)in c]else["."]}_;["
"]}_}
```
[Try it online!](https://tio.run/nexus/roda#ZYm7DoJAEEVr@YrJxGKG4BoLpSCG8C79gGU1BiGSICjYsXw7AqGzOufcOxbQ9dTtkdwzySuxMilNV0tTZpfNLSPrXme6yz9wOlr2YapKS7ygKguZPVuquKwhU3nV5RIFquHmSDRmDuPrPn29sZHokxdEHKIFmCSeH8wihJjhCRGLgEKPlxQ03WEUJ4wKNPTwbsv6C1nzyJ3VcYem7UDxP8IARdMuuzGMPw "Röda – TIO Nexus")
It works by splitting the given string at places where the string following contains only matched parentheses. Then, for each chord, it iterates through possible notes and print `O` if the note is a member of the chord and `.` otherwise.
[Answer]
# JavaScript (ES6), ~~86~~ ~~85~~ 76 bytes
*Saved 9 bytes thanks to @Neil*
```
let f =
s=>s.replace(r=/\(\w+\)|./g,x=>`ABCDEFG
`.replace(r,c=>x.match(c)?"O":"."))
```
```
<input oninput="if(/^([A-G.]|\([A-G]+\))+$/.test(value))O.textContent=f(value)"><br>
<pre id=O></pre>
```
### Explanation
First, we match what will form each line of the output: chords, and chars that aren't part of a chord. Then, for each line, we take the string `ABCDEFG\n` and replace each non-newline character in it with an `O` if the line contains it, and a `.` otherwise.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 29 bytes
28 bytes of code, +1 for `-l` flag.
```
'.X7RA_'OMz@?a@`\(\w+.|.`@XL
```
Takes input in lowercase as a command-line argument. [Try it online!](https://tio.run/nexus/pip#@6@uF2Ee5Biv7u9b5WCf6JAQoxFTrq1Xo5fgEOHz//9/3Zz/iXp6aXrJGimJmnoA "Pip – TIO Nexus")
### Explanation
```
a is 1st cmdline arg; XL is `[a-z]`; z is lowercase alphabet
a@`\(\w+.|.` List of all matches in a of this regex:
Either a ( followed by letters followed by another
character (i.e. the closing paren), or any one character
@XL For each of those matches, a list of all matches of this
regex (effectively, split the match into a list of
characters and keep only the lowercase letters)
z@? Find index of each letter in the lowercase alphabet
M To that list of lists of indices, map this function:
'.X7 Take a string of 7 periods
RA_ and replace the characters at all indices in the argument
'O with O
Finally, autoprint the resulting list, with each item on
its own line (-l flag)
```
Here's a sample of how an input is transformed:
```
"b.(ceg)"
["b" "." "(ceg)"]
[["b"] [] ["c" "e" "g"]]
[[1] [] [2 4 6]]
[".O....." "......." "..O.O.O"]
```
[Answer]
## JavaScript (ES6), ~~118~~ ~~116~~ 114 bytes
```
f=([c,...t],s)=>c?((s?0:x=[...'.......'],c='ABCDEFG)('.indexOf(c))>6?c-7:(x[c]='O',s))?f(t,1):x.join``+`
`+f(t):''
```
### Test cases
```
f=([c,...t],s)=>c?((s?0:x=[...'.......'],c='ABCDEFG)('.indexOf(c))>6?c-7:(x[c]='O',s))?f(t,1):x.join``+`
`+f(t):''
console.log(f("B(ACE)D"))
console.log(f("GGABC"))
console.log(f("..."))
console.log(f("A..F.C(DA)."))
console.log(f(".(ABCDEF)"))
```
[Answer]
# Ruby, ~~78~~ ~~75~~ 71 bytes
```
->x{x.scan(/\(\w+\)|./).map{|x|l=?.*7
x.bytes{|x|x>47?l[x-65]=?O:1};l}}
```
Returns an array of strings.
## Ungolfed + explanation
```
def boxes string
string.scan(/\(\w+\)|./) # Split the string into an array of chords.
.map do |chord| # Replace each chord with...
line = '.' * 7 # a line, where by default each character is a '.',
chord.bytes do |note| # but for each note in the chord...
if note > '.'.ord # (if it is in fact a note and not a dot or paren)
line[note-65] = 'O' # replace the corresponding dot with an 'O'.
end
end
line
end
end
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 30 [bytes](https://codegolf.meta.stackexchange.com/questions/9428/when-can-apl-characters-be-counted-as-1-byte-each/9429#9429)
```
'.O'[⍉(⍳7)∘.∊⍎⍕⎕A⍳@(~∊∘'()')⎕]
```
[Try it online!](https://tio.run/##ZcyxbsIwEMbx3U9x29lDT926YhJAnWBHDCZ1SoQVqsQSYmGEgGTUBYmlT9E3uhdJrx06wPq7@/7uIzy97VzYvPd8ub5O@fD5rLg7lj3SFOecTprT94vh7kbcnTldOF3l04oO9P6Xuhtqg0Zw0cuyL0HhUNtsZHJUSliaiMDpC2ZNVUdYBlevIVS1b2Hp49b7GrwrVhB9G6FwrYdy00ARXFPFHShVSlBS/60/mUzsMMM7JKJ7skRjynRuzcOJtCTy0djgDw "APL (Dyalog Unicode) – Try It Online")
Only 1b off the Pip solution, what a shame!
## Explanation
```
'.O'[⍉(⍳7)∘.∊⍎⍕⎕A⍳@(~∊∘'()')⎕] ⍝
⎕ ⍝ Read input. For below examples, this starts at '(AC).D'
⎕A⍳ ⍝ Converts to the index (⍳) of the alphabet (⎕A)...
@ ⍝ ... For characters which are...
(~∊∘'()') ⍝ ... Not (~) an element (∊) of '()'. Characters outside the alphabet (e.g. dots) will get index 26
⍝ e.g. '(AC).D' -> ( 0 2 ) 26 3
⍕ ⍝ Convert the mixed array (numerics and characters) to characters (⍕)
⍎ ⍝ Evaluate this string. This abuses the remaining brackets to work as groups, e.g. ( 0 2 ) 26 3 -> three array elements (0 2) 26 3
∘. ⍝ For each element, compute the outer product of...
(⍳7) ⍝ Each number 0-6...
∊ ⍝ ... vs a boolean of whether this integer is contained in the corresponding vector. Result is a boolean matrix
⍉ ⍝ Transpose this matrix. The result is now in the correct shape with 1 where 'O' needs to be and 0 where a '.' needs to be
'.O'[ ] ⍝ For each element of the boolean matrix, treat it as an index of the string '.O'. This will turn 1 into 'O' and 0 into '.'
```
[Answer]
# PHP, 171 bytes
```
preg_match_all('#[A-G\.]|\([A-G]+\)#',$argv[1],$m);foreach($m[0]as$l){if($l=='.')echo".......";else foreach([A,B,C,D,E,F,G]as$a)echo strpos($l,$a)!==false?O:'.';echo"\n";}
```
**Breakdown :**
```
preg_match_all('#[A-G\.]|\([A-G]+\)#',$argv[1],$m); // Matches either one character in the range [A-G.] OR multiple [A-G] characters between parentheses
foreach($m[0]as$l) // For each match :
if($l=='.') // If no note is played
echo"......."; // Echo empty music line
else // Else
foreach([A,B,C,D,E,F,G]as$a) // For each note in the [A-G] range
echo strpos($l,$a)!==false?O:'.'; // Echo O i the note is played, . if not
echo"\n"; // Echo new line
}
```
[Try it here!](https://eval.in/752255)
[Answer]
# [Retina](https://github.com/m-ender/retina), 120 bytes
```
O`(?<=\([^)]*)[^)]
T`L.`d
(?<=\([^)]*)\d
$*x
\)
m¶
+`\b(x+) \1(x+) m
$1 m$2
m?x
T`x m(`.\O_
\d
$*.O¶
¶
6$*.¶
%7>`.
```
I'm sure there's room for golfing, but it works now, so I'll try to golf it more later.
[Try it online!](https://tio.run/nexus/retina#@@@foGFvYxujER2nGaulCSK5QhJ89BJSuJDFY1K4VLQqFLhiNLlyD23j0k6ISdKo0NZUiDEEU7lcKoYKuSpGClwKufYVXApAIyoUcjUS9GL847nAevX8gdqAyAzIBFKq5nYJelz//zvq6bnpOWu4OGrqAQA "Retina – TIO Nexus")
**How it works**
Basically, the program works by changing each character to a number, then assigning a `O` to that position in a line. It maps `ABCDEFG.` to `01234569`.
To generate the single note lines, all that has to be done is to put an `O` after the corresponding number of `.`s, then pad out the line to 7 characters long.
However, the chords are a bit trickier to do. A similar process is used, but the numbers have to be translated to increments, i.e. the first note in the chord is (whatever), the second is X positions after the first, the third is Y positions after that, etc.
**Code**
```
O`(?<=\([^)]*)[^)]
```
Start out by sorting all characters within chords.
```
T`L.`d
```
Perform the transliteration (mapping) from letters to numbers.
```
(?<=\([^)]*)\d
$*x
```
Replace all digits within brackets with a unary representation (using `x`s), followed by a space.
```
\)
m¶
```
Replace all closing brackets with `m` followed by a newline. The `m` will be used as a marker of sorts for the coming loop:
```
+`\b(x+) \1(x+) m
$1 m$2
```
This is a replacement stage that loops until it can't replace anymore. It takes the last two sequences of `x`s before an `m`, and subtracts the first from the second, moving the `m` back. The marker `m` is needed because it has to perform this operation from right to left.
```
m?x
```
Remove the first `x` in each sequence except the first one.
```
T`x m(`.\O_
```
`T`ransliterate by replacing `x` with `.`, space with `O`, and deleting `m` and `(`.
At this point, all the lines for the chords have been created. Now the single-note lines have to be created.
```
\d
$*.O¶
```
Replace each digit with that many `.`s, followed by an `O` and a newline.
```
¶
6$*.¶
%7>`.
```
Pad each line to length 7 by adding `.`s to the right. This works by adding 6 `.`s to the end of each line (each line will have at least 1 other character), then replacing every character after the first 7 on each line with nothing. (Since `.` maps to 9, the `O` will be cut out on those lines)
[Answer]
# Perl, ~~87~~ ~~71~~ 45 + 2 (`-nl` flag) = 47 bytes
```
#!/usr/bin/env perl -nl
use v5.10;
say map$&=~/$_/i?O:".",a..g while/\(\w+\)|./g
```
Using:
```
perl -nlE 'say map$&=~/$_/i?O:".",a..g while/\(\w+\)|./g' <<< "A..F.C(DA)."
```
[Try it on Ideone.](http://ideone.com/ZCtlsD)
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 52 bytes
```
\(\w+\)|.
abcdefg$&¶
+`([a-g])(.*)\1
O$2
T`().l`___.
```
[Try it online!](https://tio.run/##K0otycxL/P8/RiOmXDtGs0aPKzEpOSU1LV1F7dA2Lu0EjehE3fRYTQ09Lc0YQy5/FSOukAQNTb2chPj4eL3//xP19NL0kjVSEjX1AA "Retina 0.8.2 – Try It Online") Takes input in lower case. Explanation:
```
\(\w+\)|.
abcdefg$&¶
```
Split the music into chords or notes, and start building the output by adding the list of note equivalents.
```
+`([a-g])(.*)\1
O$2
```
For each note in each chord, change the output to an `O` and delete the note from the chord.
```
T`().l`___.
```
Delete all the now extraneous music, and change all the unmatched notes to empty.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 24 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
žuS¡2Å€S}˜ε'.7×AySkv'Oyǝ
```
Input with lowercase letters; output as a list of lines.
[Try it online](https://tio.run/##ATkAxv9vc2FiaWX//8W@dVPCoTLDheKCrFN9y5zOtScuN8OXQXlTa3YnT3nHnf9dwrv/YS4uZi5jKGRhKS4) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TpuSZV1BaYqWgZF@pw6XkX1oC4elU/j@6rzT40EKjw62PmtYE156ec26rup754emOlcHZZer@lcfn/q@tPbRb59A2@/9JGonJqZopXElc6emJSclcenp6XIl6eml6yRopiZp6XHoaQNGU1DRNLiBDMzlFA8jUSEzXBAA). (The `]»` in the footer is used to pretty-print the output by joining with newlines. Feel free to remove it to see the actual output-list.)
**Explanation:**
```
žu # Push builtin string "()<>[]{}"
S # Convert "()<>[]{}" to a list of characters
¡ # Split the (implicit) input by these characters
# (NOTE: If the input starts with a "("
# the first item will be an empty string)
2Å€ } # For every item at a 0-based index that is divisible by 2:
S # Convert the string to a list of characters
˜ # Flatten the list
ε # Map each item to:
'.7× '# Push a string with 7 "."s: "......."
A # Push the lowercase alphabet
y # Push the current item we're mapping over
S # Convert it to a list of characters
k # Get the index of each in the alphabet (-1 if it's a ".")
v # Loop over those indices:
'O '# Push an "O"
yǝ # Insert it in the "......." string at the current index
# (`ǝ` doesn't work with -1, but still pops the "O" and -1)
# (after which the resulting list of lines is output implicitly)
```
[Answer]
# Perl 5 - 78 + 1(flag) + 2(Input Quotes) = 81 Bytes
```
for(;/(\([a-g]+\)|[a-g\.])/g;){$i=$1;print$i=~/$_/?'o':'.'for(a..g);print"\n"}
```
Can be run like so:
```
perl -n <name of file holding script> <<< <input in quotations>
```
[Answer]
# Ruby, 68 bytes
```
->s{w=?.*m=7
s.bytes{|i|i>64?w[i-65]=?O:m=i!=40;m&&(puts w;w=?.*7)}}
```
The idea is to modify the string `.......` every time we find a letter, then output and reset it, but only when we are outside brackets. `(` switches the outputting off. `)` and `.` both switch/leave the outputting on, but the latter is inconsequential as it will never be found inside a bracket.
**Ungolfed in test program**
```
f=->s{w=?.*m=7 #set m to a truthy value (7) and w to seven .'s
s.bytes{|i| #for each byte in the string
i>64?w[i-65]=?O:m=i!=40 #if a letter, modify the appropriate character of w ELSE set m to false if inside brackets, true otherwise.
m&&(puts w;w=?.*7) #if m is true, output the contents of w and reset to seven .'s
}
}
p 1
f["B(ACE)D"]
p 2
f["B"]
p 3
f["GGABC"]
p 4
f["A..F.C(DA)."]
p 5
f[".(ABCDEF)"]
```
[Answer]
# Python 3, 94 bytes
An anonymous function
```
import re
lambda s:[''.join('.O'[c in x]for c in'ABCDEFG')for x in re.findall(r'\(\w+\)|.',s)]
```
[Answer]
# [Haskell](https://www.haskell.org/), 101 bytes
```
c#s|elem c s=c|1<3='.'
s?r=map(#s)"ABCDEFG":p r
p('(':r)|(x,_:t)<-span(')'<)r=x?t
p(x:r)=[x]?r
p e=[]
```
[Try it online!](https://tio.run/nexus/haskell#FYpLCoMwFAD3nuKhhbxAGyjdiQ/xEz2ESAkhC0FDSCxkkbunuhpmmKyrkMxuDtAQSKd38yEmWBFaT4dyWAVedv0wymkuawe@cMiQ1Z4njM/vxeYVnLLIOGu4p9jeR7w6LXG9BQwtaz7UZoFgs6fxSp/wgJ/dN2sCCHC5Ez0OI5fYj5JP8x8 "Haskell – TIO Nexus") Usage: `p "AB.(CA)D"`. Returns a list of strings.
**Explanation:**
The function `p` recurses over the string. If it finds an opening bracket `'('` then `(x,_:t)<-span(')'<)r` partitions the rest string `r` into the strings `x` before the occurrence of the closing bracket `')'` and `t` after it. Otherwise the current character `x` is turned into a string `[x]`. In both cases the function `?` is called with the current string of notes and the rest string.
`?` maps the function `#` over the string `"ABCDEFG"`, where `#` replaces all chars that are not in the current string of notes with `'.'`. The resulting music box line is prepended to the recursive call of `p` on the rest list `r`.
[Answer]
# PHP, 93 bytes
```
for($s=$t="
.......";$c=ord($argn[$i++]);$d||$s=$t.!print$s)$c<65?$c-46&&$d=~$c&1:$s[$c&7]=O;
```
Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/57df5ed6f63565a5a75890edabcde6712aee9839).
**breakdown**
```
for($s=$t="\n......."; // init
$c=ord($argn[$i++]); // loop through characters
$d|| // 2. if chord flag is unset
$s=$t.!print$s) // then print and reset chord
$c<65 // 1. if not note
?$c-46 // and not dot
&&$d=~$c&1 // then set or clear chord flag
:$s[$c&7]=O // else set note in chord
;
```
] |
[Question]
[
Your task is write a program or function that can fill a given rectangle with
prime numbers. The `width` and `height` of the rectangle will be the input. The
output must be a list of `height` strings consisting of `width` digits and
spaces. Each horizontal (left to right) and vertical (top to bottom) digit
sequence (delimited by space or rectangle borders) of length 2 or greater must
be a prime number. Each prime number may be used only once. Leading zeros are
not allowed. A trailing new line is optional on the output.
### Example:
```
With input (5, 3) a valid output would be:
11 13
7 0
173
which scores 11, 13, 173, 17, 103 for a total of 5 points.
```
### Score:
The rectangle size for scoring will be `80, 60`.
Each horizontal or vertical prime number of length 2 or more in the rectangle
scores one point. The answer with the most points wins. In the event of a tie,
the earliest answer will win.
### Rules:
* Standard loopholes are prohibited.
* Your program must not be designed for the `80, 60` size. If I suspect an
answer is optimised for this size, I reserve the right to change the rectangle
size up to `100, 100`.
* The primes used must be real primes (not probabilistic or pseudoprimes). Your program may compute or check numbers at run time, or have them hard coded. The method of finding the primes is not an important part of the challenge.
* Your answer should include the output text and your code. If your program is too large, you may just include some core algorithm code, with a little explanation.
*Edit: Clarified that real primes needed. Added maximum rectangle size.*
*Edit 2: Clarified what code needs to be posted.*
[Answer]
## Smalltalk, 1098 primes
First off, nice hard question - as evidenced by the lack of non-trivial responses thus far.
I had a solution cooking at work, but had to wait for the long weekend to have time to clean it up a bit. Even so, it's quite "heavy", so excuse the length of this answer - thankfully this isn't a code-golf question. There were plenty of little gotchas along the way, but I'm pretty sure it's bug-free now, though there is plenty of room for improvement and fine-tuning.
## Language
My language of choice for this sort of thing is **Smalltalk** - the superior debugging and the ability to test-as-you-code beats anything else I know. Plus, even non-coders can read it and understand the basics of what's going on. I've limited the code below to the interesting part, because I thought the approach and results would be more interesting than the boilerplate code, but a file-out of the full code is pasted [here](http://pastebin.com/kfJhhpBr) if anyone wants to try it out (just save as a `*.st` and file it in from a file browser in Pharo). I used Pharo 4.0, which is FOSS and can be downloaded from [pharo.org](http://pharo.org/download) for Win/Mac/Linux. Also happy to paste the full code here, but I took the "should include the output text and your code" as a suggestion - let me know if I'm wrong.
## Approach
So, my thinking was, what if you could start in the middle, stuff as many long primes as you could in the box, and work your way outwards from there? Let's start with a `Box` object, containing a `matrix` of characters, and then use a `Stuffer` object to try to fill it up by finding the best `Insertion` (another object) for each point in the matrix and for each prime (starting with the long ones). Pharo has nice `Matrix` and `Point` classes with a bunch of useful methods (though the matrix way of using row-major notation versus using x-y-coordinates of points can get a little confusing if you're not careful).
The basic steps of my algorithm are:
1. Create a `Stuffer` instance for given dimensions.
2. Have the stuffer initialise its box to size 5x5 (unless dimensions
are smaller).
3. Ask the Stuffer to stuff its box.
* Iterate over a list of primes from largest to smallest.
* Iterate over all points in the matrix.
* Find the best spot to insert the prime, and insert if possible.
4. While the box can "grow" (until the target dimensions are reached),
increase it by one row/column on each side and copy the old contents
into the middle of the bigger one, then go to step 3.
Configurable:
* The dimensions
* The largest prime to start from
* The "rating" of insertions (when choosing from multiple possible places to insert a prime)
For the matrix below, I used 80x60, primes below 20,000 (since the combined length of those is just under 10,000 characters, i.e. the maximum for a stuffed, though invalid, 100x100 box), and, after some experimentation, the following rating for `each` insertion:
```
(each accidentalPrimes size * 1) + (each numberOfOverlaps * 2)
```
where `accidentalPrimes` are the perpendicular primes "accidentally" created when inserting between neighbouring primes, and `numberOfOverlaps` is how many characters are overwritten (e.g. when adding a `3` at the end of `11` to insert `113`). I initially had it weighted more towards `accidentalPrimes`, but got a few more primes in the box by doing it this way - not entirely sure why (feel free to test/tweak).
## Result
```
| 1 3449 8 19489 8 7 9277 2 7 419 6 9533 19211 19373 4 79379 9 6 1 1|
|8861 1 7 26701 6 19219 6 97577 6 319211 84631 3 9649 8 19207 6 7 10399 9|
| 7 8 98669 19469 5 0 19301 2 6997 4 9787 19441 7 18899 9 2 47297 1 0 0|
|8839 8 7 1613 5 6 149837 0 97213 319289 6 8291 915991 431 909113 1 3382373|
| 7 7607 1 9 9 19543 1 8 3779 5743 6 19813 1946981 19423 139 9 9431 1 1|
| 6911 8933 2 9 9 1 4198013 9497 19447 1093 9 1194899 8 569 4 487749433 |
| 1 1 1 3 0 5653 19583 5 101429 4691 4 119813 9923 9 5 9 1811 47293 3533 1 1|
| 8849 8 86959 0 1 0 4 195071 7589 19429 5 1 4 3863 219763 9 2 1 9391 87833|
| 9 813613 7 719 19471 6 19727 809 7 19759 619867 6 988069 1 5 11 191 9 1 9 8|
|541 0 7 3547 1 70919 93715816451 19609 3 6 3 41 757219717 9803 9 9 9283 4 7|
| 3 1 9 1 691 6 4 177493124562997 7 1 719483 152993 8 9 6173 7 4871 0 7 15797|
|5171 373 9 1 4 318191 263 19843 19919 8 19889953 4 169639 9679 6 8887 9 |
| 8 8 1 5449 2 9 9399647333 7907 8 8 677 2 6 6 9967 101 8111 7 7 3 7 1907 1 |
| 7 67901 2 2 757 8 5 9 119759 7499 19853 19751 19913 59879 0 6469 171179 6 487|
|8747 0 9 78167 4 8 78839 6 99317 1 3 9 9 9 9 16993 7 8117 3373 9 9 8093 9 |
| 3 913457 31193 9 107 7 198439 9 19861 19697 99125471 1 16979 2819 0 9 1 |
|9 1951 0 1879 1 7 1 1 6569 853 18397 83 8 656269159547193329 97871 7 2 1 4337 |
|14831 9157 6449 0 9 9613 8 15619 148436196977821 19597 9 9 6907 8 383 16573 1 1|
|7 9 8 4518803 15647 9 941 19661 19963 149 19937 43913 2393 1433 1 1 1 9 9 8|
|3 1 3613719596827 8 2 6 5163998629 467 6271 13967 29399 51673 9 15973 87473 9|
| 9127 9 927191 19157 0 8 66938969 176597 19949 5779513 1319 6 92779 14717 3 7 1|
| 1 98849 8 9 9 8 3371771169929 169937 4 65519 79769 9 906473 58699 9 78173|
| 8 0 6 9907 682771709 9 9 3319763 947387669 479978309 8597 35393 369731 5 |
| 6211 1823 1 318691 96918839 9 19 918481 1997911733 58271 6 2 9 1 1 92219 661 |
| 7 8 7349 9 369739 7297 1 8641 4 12983 6 61991 619793 7 3 8297 15791 0 3 |
| 9 8 1 1 1 5 619 8 510589 396932999 7 5897537 997379 6 39313 4 439 69911 1 |
|1 64969 9 54139 7069 739 99639719 58693 4951 977 9 9151 8 9 6689 257 4 37199 |
|8 9 0 37529 9 4 91193 6 6 9 7 6 8 11117 3970331 11969963 661911661 727 9 3 |
|3613 0 8 5 3 2 8 9 1 499787 9137 71 19997 971939 13999 787 0 9 9 701 7 151 8 |
|7 8 6961 97607 1 15569 9 8 1 1 1171 99929 99733 1759 9817931 3 8941 193 968819|
|9 8 0 6 0 99767 8 769 88969 9859 979871393 1733 9377113 95111 5 8 2 94033 1|
| 9041 6 14519 1063 6 937 8 8 8999 92993171 11519 313 89417 7 317 5233 4 3 9 8|
|433 8179 6113 8971 3191 7559 17 63313 939793919 971 198769 5693 9 7 14657 6 7|
| 9 1 725189 1 7591139 9 93911 3919 9257 33739 9293 29 1973 2 9161 9511 17239|
|349 87151 99349 57529 7 36637 6359 81999119371933 4 98573 7549 6317 6619 8 9 3 3|
| 3 8 99371 8 8 374718269 1144935789717977 83177 9 233 1499 8 1571 4 8 6803 9 |
| 9 15641 3 1607 3 8 761 393388937 9 3967 9 9719 13997 1259 7 9639079 0 443|
| 1 9 2 14969 1109 8313931 8 198174119963 5 997 9 9 991 8 1217 52579 1 3911 1 |
|5281 277 1979 32909 9 986983 19991 61399991 127997 9 82939 907 571847 4 9 3 |
| 7 8 9 617 8 4 21613 2 95792383 919979 4951997317 93719 4 641379379 1 12487 |
|1 9 66959 8 8 4 3339313613 5119963 189967 359 337361 25933 83891 8 8191 7 1|
|8 7 8 61516883 1619 839 799859 2 7 19927 5 19777 6737 9769 37799 9 19079 0 9 1 9|
|57331 2 4 9 1 1 7691 9697 61 19577 6 9949 9 9 31979399 1 1 8737 509 1 49871 8 8|
|9 1 6397 109 99133 3 313888397 59419699 1986133 8387 9 988319 5 47237 7 8 9 0|
|3 62131 1 38629 8699 9 8599 953 397 736903 1991933 877 3 4799 1 1 77171|
| 1 8 8 9091 7 86491 627673 593 1 19853377 9781 8 3 76919 7 49739 1511 9 |
| 8 76991 0 938747 9 924629743 193873 2 699823 8719801 907871 19181 4 9 9 93371|
|6959 7 88867 6 7757 792383 8 9 0 1981337 3947 3 3917 2089979 9 92831 0 4 2 8|
| 4 5953 1 3739 69473 7 19709 99016787 379 9619759 196991 6 56393 9 3 82373 9|
|273613 1163 13883 919531 8 7433 6337 8893 6917 9 9 1693 8 0 7 709 93199 9 1|
|631 97159 8 181 9 6 0 0 7819753 673 9 9 9901 19699 18119 7 1 1 111779|
|9 8 0 9 0 2 7919 4419559 98179 6 9 19553 9851 4 9 9067 9857 4957 14939 9397 |
| 8753 0 3631 4 4 18973 9 7 89923 19793 1 8 3491954199497 53 2969 9 0 0 0 0 6 |
|1 9 1 5 1 5 24337 9 19603 7 9 3 4 195312373619977 9 119489 8 96293 643 0 4 |
|8 3 18461 7577 1 19541 8 3929 19463 6 3 49937 3 9 98297 71347 3 4 7 9 1 9 1 |
|87541 9 92707 9817 2 58237 1 4 6 919423 5 19403 77383 194179 9601 1 1 1 1|
|6 9 38923 4 261631 61937389 19387 390739 9 19319 6 495617 9 5 9 7 93979 8 8 8|
|9 449 5 4658147899073 7 3 60293 5 7 8231 2641930937 7 1950139511 6 0 26993 7|
| 0 0 2 34789739 1 3619501 61930959767 7 19237 7 9 9829 7 7 27773 5 7 5|
|823 7211 7 3 3 919231 9631 337 1 3 7 9 3 1 3943 19141 653 3 15971 7|
```
This matrix contains 1098 primes, which is a "load" of about 70%.
These are the primes (`box primesUsed asSortedCollection printString`):
```
11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 107 109 113 127 131 137 139 149 151 163 167 173 179 181 191 193 197 199 233 257 263 269 271 277 283 293 307 311 313 317 331 337 347 349 359 367 373 379 383 389 397 419 431 433 439 443 449 467 479 487 491 499 509 541 547 557 563 569 571 577 587 593 599 601 617 619 631 641 643 647 653 659 661 673 677 683 691 701 709 719 727 733 739 743 751 757 761 769 773 787 797 809 811 821 823 827 829 839 853 857 859 863 877 881 883 887 907 911 919 929 937 941 947 953 967 971 977 983 991 997 1063 1093 1109 1117 1153 1163 1171 1181 1217 1259 1319 1361 1399 1433 1499 1511 1571 1607 1613 1619 1637 1663 1667 1693 1697 1699 1733 1759 1811 1823 1879 1907 1913 1933 1949 1951 1973 1979 1987 1993 1997 1999 2393 2459 2617 2819 2927 2939 2969 3191 3229 3343 3373 3389 3449 3533 3539 3547 3613 3617 3631 3643 3733 3739 3769 3779 3793 3797 3821 3863 3911 3917 3919 3929 3931 3943 3947 3967 3989 4337 4409 4493 4691 4799 4871 4951 4957 4967 4999 5039 5099 5101 5171 5233 5281 5347 5399 5449 5479 5653 5693 5743 5939 5953 6079 6113 6131 6173 6197 6199 6211 6271 6317 6337 6359 6397 6449 6469 6569 6571 6599 6607 6619 6653 6661 6689 6737 6779 6781 6793 6803 6823 6829 6899 6907 6911 6917 6949 6959 6961 6967 6977 6997 7069 7079 7109 7193 7211 7219 7229 7297 7307 7349 7393 7433 7499 7549 7559 7577 7589 7607 7621 7691 7727 7757 7883 7907 7919 7949 7951 8093 8111 8117 8171 8179 8191 8219 8231 8291 8293 8297 8387 8419 8537 8539 8563 8597 8599 8641 8647 8681 8689 8693 8699 8719 8737 8747 8753 8779 8831 8839 8849 8861 8863 8887 8893 8929 8933 8941 8951 8963 8969 8971 8999 9007 9041 9067 9091 9109 9127 9137 9151 9157 9161 9173 9181 9187 9199 9257 9277 9281 9283 9293 9371 9377 9391 9397 9413 9419 9421 9431 9437 9461 9463 9467 9473 9479 9491 9497 9511 9521 9533 9539 9547 9551 9587 9601 9613 9619 9623 9629 9631 9643 9649 9661 9677 9679 9689 9697 9719 9721 9733 9739 9743 9749 9767 9769 9781 9787 9791 9803 9811 9817 9829 9833 9839 9851 9857 9859 9871 9883 9887 9901 9907 9923 9929 9931 9941 9949 9967 9973 10399 10979 11117 11519 11939 11959 11981 12487 12983 13313 13339 13463 13499 13763 13877 13883 13907 13931 13963 13967 13997 13999 14519 14657 14717 14831 14939 14969 15091 15569 15619 15641 15647 15791 15797 15971 15973 16573 16699 16937 16979 16993 17239 17333 17519 17761 17891 18119 18371 18379 18397 18461 18593 18691 18719 18757 18773 18787 18803 18839 18859 18869 18899 18911 18913 18917 18919 18959 18973 18979 19001 19009 19013 19031 19037 19051 19069 19073 19079 19081 19087 19121 19139 19141 19157 19163 19181 19183 19207 19211 19213 19219 19231 19237 19249 19259 19267 19273 19289 19301 19309 19319 19333 19373 19379 19381 19387 19391 19403 19417 19421 19423 19427 19429 19433 19441 19447 19457 19463 19469 19471 19477 19483 19489 19501 19507 19531 19541 19543 19553 19559 19571 19577 19583 19597 19603 19609 19661 19681 19687 19697 19699 19709 19717 19727 19739 19751 19753 19759 19763 19777 19793 19801 19813 19819 19841 19843 19853 19861 19867 19889 19891 19913 19919 19927 19937 19949 19961 19963 19973 19979 19991 19993 19997 21613 24239 24337 25933 26449 26701 26959 26993 27773 27919 29399 31193 32909 33739 35393 36637 36761 37199 37529 37799 38333 38629 38839 38861 38923 39293 39313 39733 43913 43943 45281 47237 47293 47297 47933 47939 48311 48761 49123 49199 49739 49871 49937 49999 51193 51673 52379 52579 54139 55313 56393 56983 57173 57331 57529 58237 58271 58693 58699 59743 59879 60293 61979 61991 62131 62873 63313 64969 65519 66491 66959 67339 67901 67993 69337 69473 69623 69697 69911 69941 70919 71347 71777 71933 75347 76163 76733 76919 76991 77171 77213 77383 77591 78167 78173 78839 78941 79379 79613 79631 79769 79967 80933 81919 82373 82939 83177 83891 84631 86491 86959 87151 87473 87541 87833 88499 88867 88951 88969 89413 89417 89519 89923 91193 91813 91997 92219 92593 92647 92707 92779 92831 93199 93371 93719 93911 93913 93971 93979 94033 94397 94399 95111 96233 96293 96587 96911 96959 96979 97159 97213 97577 97607 97787 97871 97919 98179 98297 98299 98573 98669 98837 98849 99133 99233 99317 99349 99371 99497 99733 99767 99907 99929 101429 111149 111779 119489 119759 119813 127997 149837 152993 167747 168863 169639 169937 171179 176597 179099 179111 183797 187973 188693 189473 189967 190811 191837 193813 193873 194179 195071 195319 196817 196871 196991 197273 197599 198013 198017 198439 198673 198769 199373 199679 199739 219763 261631 273613 277793 316879 318191 318691 319031 319069 319211 319289 319427 319727 319973 337361 369731 369739 390739 391753 414347 419801 439883 495617 499787 510589 519031 571847 601189 615749 616367 618719 619543 619583 619753 619763 619793 619813 619867 627673 639631 669923 698339 699823 716987 719009 719441 719483 719801 719813 725189 736903 792383 796553 799859 809339 813613 815569 819373 819457 829733 906473 907871 909113 912797 913457 914813 915641 915991 917159 918481 918679 918793 919183 919231 919381 919421 919423 919531 919559 919913 919979 927191 935639 938747 939439 943913 962971 968819 971939 976777 986983 988069 988319 991733 997319 997379 1194899 1518379 1678739 1691189 1867993 1899907 1903703 1923151 1942771 1946981 1950149 1981337 1986133 1988999 1991933 2089979 2919031 3110651 3190871 3193913 3197633 3319763 3382373 3619501 3970331 4198013 4419559 4518803 5119963 5195077 5319289 5619139 5779513 5897537 6119801 6129587 6189137 6194891 6198139 6649871 7219427 7591139 7819753 7937939 7982969 8019727 8313931 8419381 8719801 8783371 9119909 9189797 9323173 9377113 9619759 9639079 9679799 9717317 9721301 9721991 9817931 9911789 9923369 9967759 11969963 15619867 16981331 19669931 19717099 19793479 19853377 19889953 21968773 27519469 31979399 34789739 40699733 59419699 61399991 61516883 61897937 61937389 63519427 66938969 69719801 74969767 91938191 92993171 93369931 95792383 96918839 99016787 99125471 99639719 126919421 179319979 199733981 199739717 313888397 342719753 374718269 393388937 396932999 439314797 479978309 487749433 577519913 613799299 631819381 641379379 661911661 682771709 689194217 757219717 924629743 936195479 939793919 947387669 979871393 991579637 1903149343 1921376857 1945706473 1950139511 1960317529 1997911733 2641930937 3339313613 4951997317 4952523041 5163998629 7017198679 7981707577 9013119991 9119993297 9399647333 9945519919 18919323977 19031318947 19919788793 31879359403 61930959767 61960309907 91734751987 92774649739 93715816451 95479219889 98371979359 99551395387 191830198139 198012194899 198017187931 198174119963 213963819763 419801418947 819853319867 1937327699987 3189735598139 3371771169929 3491954199497 3613719596827 4658147899073 81999119371933 148436196977821 177493124562997 195312373619977 1144935789717977 656269159547193329 735547997331319937 11572771955941937959
```
As you can see, some of the "accidental" primes get quite long... 20 digits for the longest one. :-)
## Details
To understand how it works, here is the output from doing the first few steps - inserting `19997` first (if you look in the middle of the big matrix, you'll see `19997` there as well), then down the list where there's space in the 5x5 box (`>` means insert going right, `v` means going down; anything in `{}` are accidentally added primes:
```
Insertion at: (1@1) > {} of 19997
Box 5x5 (1 prime, load: 20%):
|19997|
| |
| |
| |
| |
Insertion at: (1@1) v {} of 19993
Box 5x5 (2 primes, load: 36%):
|19997|
|9 |
|9 |
|9 |
|3 |
Insertion at: (3@1) v {} of 9973
Box 5x5 (3 primes, load: 48%):
|19997|
|9 9 |
|9 7 |
|9 3 |
|3 |
Insertion at: (1@4) > {} of 9931
Box 5x5 (4 primes, load: 56%):
|19997|
|9 9 |
|9 7 |
|9931 |
|3 |
Insertion at: (1@3) > {89, 11} of 9871
Box 5x5 (7 primes, load: 64%):
|19997|
|9 9 |
|9871 |
|9931 |
|3 |
Insertion at: (5@1) v {98713, 99317} of 7937
Box 5x5 (10 primes, load: 76%):
|19997|
|9 9 9|
|98713|
|99317|
|3 |
Insertion at: (4@3) v {} of 113
Box 5x5 (11 primes, load: 80%):
|19997|
|9 9 9|
|98713|
|99317|
|3 3 |
11 old primes: 19997, 19993, 9973, 9931, 9871, 89, 11, 7937, 98713, 99317, 113
8 new primes: 19997, 98713, 99317, 19993, 89, 9973, 113, 7937
Insertion at: (4@1) v {} of 19973
Box 7x7 (9 primes, load: 42%):
| 1 |
| 19997 |
| 9 9 9 |
| 98713 |
| 99317 |
| 3 3 |
| |
```
In the insertion immediately above, the box becomes a 7x7, and is filled with the 5x5 contents before the next insertion happens. I also re-calculate the primes used at this point, because some are "freed up" due to overwriting (`11` was inserted, but then overwritten by `113`).
## Code
Here are the most relevant parts of the code:
**Stuffer class**
*Class side*
```
forDimensions: aPoint
^self new
width: aPoint x;
height: aPoint y;
initializeBox;
yourself
```
*Instance side*
```
initializeBox
box := Box width: (width min: 5) height: (height min: 5)
stuffBox
self stuffCurrentBox.
[self canGrow] whileTrue: [
box growMatrixByOneUpTo: width @ height.
self stuffCurrentBox
]
canGrow
^width > box width or: [height > box height]
stuffCurrentBox
self class primes reverseDo: [:eachPrime |
| string insertion |
(box primesUsed includes: eachPrime) ifFalse: [
string := eachPrime asString.
(insertion := box bestInsertionFor: string) ifNotNil: [
Transcript crShow: insertion printString, ' of ', string.
box doInsertion: insertion of: eachPrime.
Transcript crShow: box
]
]
].
box updatePrimesUsed.
```
**Box class**
*Instance side*
```
bestInsertionFor: aString
| insertions |
insertions := OrderedCollection new.
self pointsDo: [:eachPoint |
insertions
addIfNotNil: (self insertionOf: aString at: eachPoint isHorizontal: true);
addIfNotNil: (self insertionOf: aString at: eachPoint isHorizontal: false)
].
insertions removeAllSuchThat: [:each |
self isInsertion: each invalidWith: aString asInteger
].
^insertions detectMax: [:each |
(each accidentalPrimes size * 1) + (each numberOfOverlaps * 2)
]
insertionOf: aString at: aPoint isHorizontal: isHorizontal
| point insertion |
point := aPoint.
(self canFitEndsAt: point length: aString size isHorizontal: isHorizontal)
ifFalse: [^nil].
(self isAlreadyThere: aString at: aPoint isHorizontal: isHorizontal)
ifTrue: [^nil].
insertion := Insertion at: point isHorizontal: isHorizontal.
1 to: aString size do: [:eachIndex |
| eachCharacter |
eachCharacter := aString at: eachIndex.
(self canDoInsertion: insertion of: eachCharacter at: point)
ifTrue: [
(self at: point) == eachCharacter
ifTrue: [insertion increaseOverlaps].
point := point + (self offset: isHorizontal)
]
ifFalse: [^nil]
].
^insertion
isInsertion: anInsertion invalidWith: aPrime
| otherPrimes |
otherPrimes := anInsertion accidentalPrimes.
^(primesUsed includesAny: otherPrimes)
or: [(otherPrimes includes: aPrime)
or: [otherPrimes copy removeDuplicates size < otherPrimes size]]
canDoInsertion: anInsertion of: aCharacter at: aPoint
"Answer whether anInsertion of aCharacter is valid at aPoint. If so,
also update anInsertion with any accidental insertions."
| perpendicularSequence offset front back |
(self at: aPoint) == aCharacter
ifTrue: [^true].
(self isFreeAt: aPoint)
ifFalse: [^false].
perpendicularSequence := OrderedCollection with: aCharacter.
offset := self offset: anInsertion isHorizontal not.
front := aPoint - offset.
back := aPoint + offset.
[self isFreeOrBorder: front] whileFalse: [
perpendicularSequence addFirst: (self at: front).
front := front - offset
].
[self isFreeOrBorder: back] whileFalse: [
perpendicularSequence addLast: (self at: back).
back := back + offset
].
^perpendicularSequence size == 1
or: [
| string number |
string := String withAll: perpendicularSequence.
number := string asInteger.
(string first ~~ $0 and: [number isPrime])
ifTrue: [anInsertion addAccidentalPrime: number. true]
ifFalse: [false]
]
doInsertion: anInsertion of: aPrime
self
insert: aPrime printString
at: anInsertion point
horizontalIf: anInsertion isHorizontal.
primesUsed
add: aPrime;
addAll: anInsertion accidentalPrimes
growMatrixByOneUpTo: aDimension
| smallMatrix rowOffset columnOffset |
smallMatrix := matrix copy.
matrix := Matrix
rows: (self height + 2 min: aDimension y)
columns: (self width + 2 min: aDimension x)
element: Character space.
rowOffset := (self height - smallMatrix numberOfRows) min: 1.
columnOffset := (self width - smallMatrix numberOfColumns) min: 1.
self copy: smallMatrix to: (1 + columnOffset) @ (1 + rowOffset)
copy: aMatrix to: aPoint
matrix
atRows: aPoint y
to: aPoint y + aMatrix numberOfRows - 1
columns: aPoint x
to: aPoint x + aMatrix numberOfColumns - 1
put: aMatrix
```
**Collection**
Oh, and I added one method to the instance side of `Collection`, just for convenience:
```
addIfNotNil: anElement
anElement ifNotNil: [self add: anElement]
```
## Running it
To run my code, all I need to do is select the following code in a workspace ("playground" in Pharo) or in any text pane, and "do it" from the context menu:
```
(Stuffer forDimensions: 80@60)
stuffBox
```
The rest of the code is relatively boring.
As I said, room for improvement, but at 80x60, each run takes over 3 minutes on my machine. Clearly, performance hasn't been my concern, but there are a LOT of primes flying around. This sure has been an interesting challenge. :-)
[Answer]
# [Clingo](http://potassco.sourceforge.net/) with Python, ~~1600~~ ~~1689~~ 1740 primes
## Approach
I generate a giant constraint satisfaction problem and solve it using an industrial strength satisfiability solver. Lots of magic has gone into making satisfiability solvers relatively fast (even though the problem is NP-complete in general), but fortunately I don’t have to worry about that part.
Specifically, I fix the positions of the digits in a pattern designed for close packing of 4 and 5 digit numbers, with occasional 2 and 3 digit numbers on the boundary, and add constraints saying that each number is a distinct prime. The current packing uses a large fraction of all 4 digit primes (854 of 1061).
## Code
```
#script (python)
import re
def primesto(n):
p = [False]*2 + [True]*(n - 2)
for k in xrange(n):
if p[k]:
yield k
p[k*k::k] = [False]*(-(-n//k) - k)
def main(prg):
width = prg.get_const('width')
height = prg.get_const('height')
primes = list(primesto(30000))
counts = {4: 4, 5: 4}
def get_bands(counts):
if counts:
for k, v in counts.iteritems():
counts1 = counts.copy()
if v == 1:
del counts1[k]
else:
counts1[k] = v - 1
for p in get_bands(counts1):
yield (k,) + p
else:
yield ()
def get_img(bands, offset):
tile = ''.join('#'*k + ' ' for k in bands)
tile = tile[offset:] + tile[:offset]
def get_edge(it, corner):
if not next(it): return True
if not next(it): return corner
if not next(it): return True
if not next(it): return True
if not next(it): return True
return False
def get_cell(x, y):
return \
(x == 0 and get_edge((get_cell(i, y) for i in xrange(1, width - 1)), not 1 <= y < height - 1)) or \
(y == 0 and get_edge((get_cell(x, j) for j in xrange(1, height - 1)), not 1 <= x < width - 1)) or \
(x == width - 1 and get_edge((get_cell(i, y) for i in xrange(width - 2, 0, -1)), not 1 <= y < height - 1)) or \
(y == height - 1 and get_edge((get_cell(x, j) for j in xrange(height - 2, 0, -1)), not 1 <= x < width - 1)) or \
(1 <= x < width - 1 and 1 <= y < height - 1 and tile[(x + y)%len(tile)] == '#')
img = [[get_cell(x, y) for x in xrange(width)] for y in xrange(height)]
def get_spaces():
for y, row in enumerate(img):
for m in re.finditer('#{2,}', ''.join(' #'[cell] for cell in row)):
yield [(x, y) for x in range(m.start(), m.end())]
for x, col in enumerate(zip(*img)):
for m in re.finditer('#{2,}', ''.join(' #'[cell] for cell in col)):
yield [(x, y) for y in range(m.start(), m.end())]
spaces = list(get_spaces())
return img, spaces
img, spaces = max((get_img(p, o) for p in get_bands(counts) for o in xrange(p[0] + 1)), key=lambda (img, spaces): len(spaces))
def data():
for p in primes:
yield 'prime({}, {}).\n'.format(p, len(str(p)))
for j, d in enumerate(str(p)):
yield 'primedigit({}, {}, {}).\n'.format(p, j, int(d))
for i, space in enumerate(spaces):
yield 'space({}, {}).\n'.format(i, len(space))
for j, c in enumerate(space):
yield 'cell({}, {}, {}).\n'.format(i, j, c)
def on_model(model):
digit = {}
for atom in model.atoms():
if atom.name() == 'digit':
c, d = atom.args()
digit[c] = d
for y in xrange(height):
print ''.join(str(digit.get((x, y), ' ')) for x in xrange(width))
prg.add('data', [], ''.join(data()))
prg.ground([('base', []), ('data', [])])
prg.solve_async(on_model=on_model).wait()
#end.
#program base.
1 {loc(P, S) : prime(P, L)} 1 :- space(S, L).
:- prime(P, L), 2 {loc(P, S) : space(S, L)}.
digit(C, D) :- loc(P, S), cell(S, J, C), primedigit(P, J, D).
:- cell(S, J, C), 2 {digit(C, D) : D=0..9}.
#show digit/2.
```
## Usage
```
clingo -q2 -c width=80 -c height=60 stuff.lp
```
Warning: at 80×60, this takes about 8 minutes and uses 3 GB of memory. You may want to start with smaller sizes if you just want to see it running.
## Output (80×60, 1740 primes):
```
13 293 4153 4217 9137 239 3169 223 127 281 9281 9173 4253 257 9239 3
719 28349 2039 7159 4603 17491 6299 17207 19463 19793 3301 4483 5657 20639 10061
7 26417 7307 2687 9479 14767 3571 10957 21341 14057 5813 6689 2383 19553 2647 3
15679 6679 6217 1303 19037 5821 11551 18797 28723 3457 6581 5309 12043 4441 2
14327 4783 5881 6131 21107 2549 12953 24001 12113 7247 9973 8287 16573 5519 149
20177 4967 5647 1907 24439 7237 28979 24781 26083 9859 6691 3701 25237 9041 1637
2953 6781 2851 7079 10139 4001 20981 20341 23531 1913 5081 7639 25169 7457 29437
743 3907 6949 1237 10937 3203 19213 23971 18367 5227 5879 8191 17827 4561 16927
9 1613 8369 3911 23327 1571 25741 15889 19417 3083 3049 4421 25111 8147 10391
9 9151 3019 3499 11839 5851 23669 16823 14891 9829 9403 1069 26099 8737 21911 2
17389 3217 7963 13337 5779 19841 16007 10313 7673 7703 5897 23911 4409 26737 131
2711 9697 8563 29611 2699 20231 27631 15823 7127 7937 8171 23623 6067 14489 1307
751 2179 7877 12263 7331 17923 26153 11443 7603 1429 8861 28871 8291 20599 20129
3 3251 5087 28949 4519 22501 15667 28837 2543 3617 2837 15217 4129 20357 29879
2 7507 4127 27479 2521 11423 17497 12409 6599 7297 1249 14813 6301 10501 24151
21487 1777 20143 7109 12239 22063 23761 9931 1579 8929 26641 3221 18251 29429 1
3511 2389 27103 9767 27763 23399 18481 5869 8431 2141 15259 6367 29131 17789 137
941 6719 29269 1811 12829 14929 11953 4817 9787 6469 21377 2473 17033 11311 1453
3 4549 11491 2777 11351 28879 21061 3607 5441 5861 15493 8941 15101 14437 28579
3 3229 18719 7841 18701 23087 23561 8597 6637 7487 19681 6229 25321 16417 14717
15131 13151 6997 27947 26669 24179 5981 4297 5683 18979 4937 16787 24421 20089
2531 13127 5507 10973 13121 25759 8353 9413 6343 17713 7211 21523 12143 10477 1
107 19381 6871 18803 20117 20849 9091 4051 2333 11399 5987 21617 13147 12281 251
3 21713 4027 15299 15031 14389 7789 2617 4993 18493 1103 27983 22739 26987 2339
22853 1297 15959 19531 12799 2269 4943 3917 10093 4657 25999 16603 11617 12919
14923 1021 15313 11287 14969 1009 2503 9907 25247 4523 16411 12979 22397 8819 7
18191 5039 21019 13619 29947 2087 6793 3529 29671 2861 22259 20921 17291 6703 4
1523 4919 21379 23071 20051 9133 8761 6029 11813 7517 14503 28927 17707 8311 701
311 2939 28183 12347 10357 6143 5437 6011 13789 7573 23629 21773 28703 5059 8609
7 4799 17333 28069 17921 9803 8543 9601 28151 9059 10457 12119 15661 3593 21937
1 7759 13399 19207 21407 3433 7187 5717 22571 7949 19489 12251 10271 8363 2879 3
13883 10663 20023 12583 1193 5011 1889 20147 4723 25447 15887 29921 4679 7459 4
2887 14341 14759 20593 2267 1567 9901 14411 1229 12041 20483 10889 6163 3517 947
983 24799 13099 13763 4733 9029 5281 17231 6947 29311 22709 11657 2113 8167 2081
1 24359 29399 11117 2111 9341 9187 25931 7433 20347 16481 17293 5021 8681 17419
21323 14737 18311 1559 1279 2273 20509 7283 21739 28549 22193 8011 9887 2293 3
21011 19231 16127 6197 5107 7151 21013 2551 22943 28057 13229 9277 7229 1721 1
19927 22549 20641 8053 6529 5737 29021 1483 23027 24977 17623 3347 6791 1213 157
8573 23447 24499 4273 8963 6257 21881 3343 27329 17627 28307 2393 4493 3613 1117
167 15991 17029 2803 6673 3797 28219 4621 22277 12071 13043 6661 6323 8297 19433
7 24517 11777 1609 9941 2437 26189 8831 10771 11467 24091 2371 3331 7607 14947
22727 13967 1471 7451 1367 11113 7477 11527 24007 23557 1277 4969 6829 28097
12073 11887 3181 8999 5641 13411 7321 22901 28001 20939 3889 5231 8863 26357 3
20011 23671 5669 1291 9421 12689 4903 21647 19483 12157 4861 5381 9067 11471 283
2663 22123 2833 1663 8677 19891 8039 19141 23321 17417 2027 9949 6389 23459 7351
967 15901 1831 1013 5527 12697 5573 16547 14029 23333 3623 9007 6047 12739 18539
7 14369 9719 6199 7499 20663 3413 23339 25097 12973 9791 9643 2459 18353 9371 1
16843 8329 1451 5279 13441 9433 27647 28643 12007 4463 6269 7523 22861 6899 1
18143 5743 2591 4211 27551 9461 27689 11279 14533 2731 3001 6857 13757 3259 277
22483 3943 9011 8933 18593 6569 26891 22381 22109 4721 1733 2377 11549 5387 1459
6203 5351 9851 6133 29573 4513 28517 14083 15773 3109 9967 5113 29063 1427 17257
911 8713 8783 9613 27253 3851 25537 16993 17683 3037 4007 5651 12487 6779 26251
1 7243 3023 4751 10459 4931 25639 25867 12101 6373 4201 8123 15227 7589 10601
1 9631 1061 1549 10159 1381 18047 26687 20411 2129 2011 1583 12899 9749 26339 1
25127 3389 4013 15647 1669 25933 24443 21557 7853 3449 6089 28771 1847 21491 263
8501 2309 2797 16189 2003 22637 15973 28697 2741 2729 1361 25667 2131 23633 2297
359 9551 6553 11597 6451 20123 10259 29287 5923 8233 1423 10133 1373 23773 11633
7 5119 7829 24019 7691 12479 14143 20873 5323 1493 3709 18947 5701 12413 27997
4 3697 5261 17359 1657 26371 20443 11239 4093 7013 5303 15767 4259 13499 13597 5
31 3919 7393 199 9397 379 971 193 3319 1979 1931 173 3391 937 397 19
```
[Answer]
# Javascript, score 659
Almost certainly suboptimal.
```
lenof=function(a){return (""+a).length}
Array.prototype.peek=function(){return this[this.length-1]}
primes=[
11, 13, 17, 19, 23, 29, 31,
37, 41, 43, 47, 53, 59, 61,
67, 71, 73, 79, 83, 89, 97,
101, 103, 107, 109, 113, 127,
131, 137, 139, 149, 151, 157,
163, 167, 173, 179, 181, 191,
193, 197, 199, 211, 223, 227,
229, 233, 239, 241, 251, 257,
263, 269, 271, 277, 281, 283,
293, 307, 311, 313, 317, 331,
337, 347, 349,401, 409, 419,
421, 431, 433, 439, 443, 449,
457, 461, 463, 467, 479, 487,
491, 499, 503, 509, 521, 523,
541, 547, 557, 563, 569, 571,
577, 587, 593, 599, 601, 607,
613, 617, 619, 631, 641, 643,
647, 653, 659, 661, 673, 677,
683, 691, 701, 709, 719, 727,
733, 739, 743, 751, 757, 761,
769, 773, 787, 797, 809, 811,
821, 823, 827, 829, 839, 853,
857, 859, 863, 877, 881, 883,
887, 907, 911, 919, 929, 937,
941, 947, 953, 967, 971, 977,
983, 991, 997,1009, 1013, 1019,
1021, 1031, 1033, 1039, 1049,
1051, 1061, 1063, 1069, 1087,
1091, 1093, 1097, 1103, 1109,
1117, 1123, 1129, 1151, 1153,
1163, 1171, 1181, 1187, 1193,
1201, 1213, 1217, 1223, 1229,
1231, 1237, 1249, 1259, 1277,
1279, 1283, 1289, 1291, 1297,
1301, 1303, 1307, 1319, 1321,
1327, 1361, 1367, 1373, 1381,
1399, 1409, 1423, 1427, 1429,
1433, 1439, 1447, 1451, 1453,
1459, 1471, 1481, 1483, 1487,
1489, 1493, 1499, 1511, 1523,
1531, 1543, 1549, 1553, 1559,
1567, 1571, 1579, 1583, 1597,
1601, 1607, 1609, 1613, 1619,
1621, 1627, 1637, 1657, 1663,
1667, 1669, 1693, 1697, 1699,
1709, 1721, 1723, 1733, 1741,
1747, 1753, 1759, 1777, 1783,
1787, 1789, 1801, 1811, 1823,
1831, 1847, 1861, 1867, 1871,
1873, 1877, 1879, 1889, 1901,
1907, 1913, 1931, 1933, 1949,
1951, 1973, 1979, 1987, 1993,
1997, 1999, 2003, 2011, 2017,
2027, 2029, 2039, 2053, 2063,
2069, 2081, 2083, 2087, 2089,
2099, 2111, 2113, 2129, 2131,
2137, 2141, 2143, 2153, 2161,
2179, 2203, 2207, 2213, 2221,
2237, 2239, 2243, 2251, 2267,
2269, 2273, 2281, 2287, 2293,
2297, 2309, 2311, 2333, 2339,
2341, 2347, 2351, 2357, 2371,
2377, 2381, 2383, 2389, 2393,
2399, 2411, 2417, 2423, 2437,
2441, 2447, 2459, 2467, 2473,
2477, 2503, 2521, 2531, 2539,
2543, 2549, 2551, 2557, 2579,
2591, 2593, 2609, 2617, 2621,
2633, 2647, 2657, 2659, 2663,
2671, 2677, 2683, 2687, 2689,
2693, 2699, 2707, 2711, 2713,
2719, 2729, 2731, 2741, 2749,
2753, 2767, 2777, 2789, 2791,
2797, 2801, 2803, 2819, 2833,
2837, 2843, 2851, 2857, 2861,
2879, 2887, 2897, 2903, 2909,
2917, 2927, 2939, 2953, 2957,
2963, 2969, 2971, 2999, 3001,
3011, 3019, 3023, 3037, 3041,
3049, 3061, 3067, 3079, 3083,
3089, 3109, 3119, 3121, 3137,
3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209, 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271, 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331, 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391, 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467, 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533, 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583, 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643, 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709, 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779, 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851, 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917, 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989, 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049, 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111, 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177, 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243, 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297, 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391, 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457, 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519, 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597, 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657, 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729, 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799, 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889, 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951, 4957, 4967, 4969, 4973, 4987, 4993, 4999, 5003, 5009, 5011, 5021, 5023, 5039, 5051, 5059, 5077, 5081, 5087, 5099, 5101, 5107, 5113, 5119, 5147, 5153, 5167, 5171, 5179, 5189, 5197, 5209, 5227, 5231, 5233, 5237, 5261, 5273, 5279, 5281, 5297, 5303, 5309, 5323, 5333, 5347, 5351, 5381, 5387, 5393, 5399, 5407, 5413, 5417, 5419, 5431, 5437, 5441, 5443, 5449, 5471, 5477, 5479, 5483, 5501, 5503, 5507, 5519, 5521, 5527, 5531, 5557, 5563, 5569, 5573, 5581, 5591, 5623, 5639, 5641, 5647, 5651, 5653, 5657, 5659, 5669, 5683, 5689, 5693, 5701, 5711, 5717, 5737, 5741, 5743, 5749, 5779, 5783, 5791, 5801, 5807, 5813, 5821, 5827, 5839, 5843, 5849, 5851, 5857, 5861, 5867, 5869, 5879, 5881, 5897, 5903, 5923, 5927, 5939, 5953, 5981, 5987, 6007, 6011, 6029, 6037, 6043, 6047, 6053, 6067, 6073, 6079, 6089, 6091, 6101, 6113, 6121, 6131, 6133, 6143, 6151, 6163, 6173, 6197, 6199, 6203, 6211, 6217, 6221, 6229, 6247, 6257, 6263, 6269, 6271, 6277, 6287, 6299, 6301, 6311, 6317, 6323, 6329, 6337, 6343, 6353, 6359, 6361, 6367, 6373, 6379, 6389, 6397, 6421, 6427, 6449, 6451, 6469, 6473, 6481, 6491, 6521, 6529, 6547, 6551, 6553, 6563, 6569, 6571, 6577, 6581, 6599, 6607, 6619, 6637, 6653, 6659, 6661, 6673, 6679, 6689, 6691, 6701, 6703, 6709, 6719, 6733, 6737, 6761, 6763, 6779, 6781, 6791, 6793, 6803, 6823, 6827, 6829, 6833, 6841, 6857, 6863, 6869, 6871, 6883, 6899, 6907, 6911, 6917, 6947, 6949, 6959, 6961, 6967, 6971, 6977, 6983, 6991, 6997, 7001, 7013, 7019, 7027, 7039, 7043, 7057, 7069, 7079, 7103, 7109, 7121, 7127, 7129, 7151, 7159, 7177, 7187, 7193, 7207, 7211, 7213, 7219, 7229, 7237, 7243, 7247, 7253, 7283, 7297, 7307, 7309, 7321, 7331, 7333, 7349, 7351, 7369, 7393, 7411, 7417, 7433, 7451, 7457, 7459, 7477, 7481, 7487, 7489, 7499, 7507, 7517, 7523, 7529, 7537, 7541, 7547, 7549, 7559, 7561, 7573, 7577, 7583, 7589, 7591, 7603, 7607, 7621, 7639, 7643, 7649, 7669, 7673, 7681, 7687, 7691, 7699, 7703, 7717, 7723, 7727, 7741, 7753, 7757, 7759, 7789, 7793, 7817, 7823, 7829, 7841, 7853, 7867, 7873, 7877, 7879, 7883, 7901, 7907, 7919, 7927, 7933, 7937, 7949, 7951, 7963, 7993, 8009, 8011, 8017, 8039, 8053, 8059, 8069, 8081, 8087, 8089, 8093, 8101, 8111, 8117, 8123, 8147, 8161, 8167, 8171, 8179, 8191, 8209, 8219, 8221, 8231, 8233, 8237, 8243, 8263, 8269, 8273, 8287, 8291, 8293, 8297, 8311, 8317, 8329, 8353, 8363, 8369, 8377, 8387, 8389, 8419, 8423, 8429, 8431, 8443, 8447, 8461, 8467, 8501, 8513, 8521, 8527, 8537, 8539, 8543, 8563, 8573, 8581, 8597, 8599, 8609, 8623, 8627, 8629, 8641, 8647, 8663, 8669, 8677, 8681, 8689, 8693, 8699, 8707, 8713, 8719, 8731, 8737, 8741, 8747, 8753, 8761, 8779, 8783, 8803, 8807, 8819, 8821, 8831, 8837, 8839, 8849, 8861, 8863, 8867, 8887, 8893, 8923, 8929, 8933, 8941, 8951, 8963, 8969, 8971, 8999, 9001, 9007, 9011, 9013, 9029, 9041, 9043, 9049, 9059, 9067, 9091, 9103, 9109, 9127, 9133, 9137, 9151, 9157, 9161, 9173, 9181, 9187, 9199, 9203, 9209, 9221, 9227, 9239, 9241, 9257, 9277, 9281, 9283, 9293, 9311, 9319, 9323, 9337, 9341, 9343, 9349, 9371, 9377, 9391, 9397, 9403, 9413, 9419, 9421, 9431, 9433, 9437, 9439, 9461, 9463, 9467, 9473, 9479, 9491, 9497, 9511, 9521, 9533, 9539, 9547, 9551, 9587, 9601, 9613, 9619, 9623, 9629, 9631, 9643, 9649, 9661, 9677, 9679, 9689, 9697, 9719, 9721, 9733, 9739, 9743, 9749, 9767, 9769, 9781, 9787, 9791, 9803, 9811, 9817, 9829, 9833, 9839, 9851, 9857, 9859, 9871, 9883, 9887, 9901, 9907, 9923, 9929, 9931, 9941, 9949, 9967, 9973
];
width=+prompt`Width`;
height=+prompt`Height`;
pre=document.createElement("pre");
lis=[];
q=0;
z:while(lis.length<height){
s=lis.length%2?"":" ";
while(true){
v=primes[q++];
if((s+(" "+v).slice(-4)).length>width)break;
s=s+(" "+v).slice(-4);
if(q>=primes.length){lis.push(s);break z;}
if(s.length<width)s+=" ";
}
lis.push((s+" ".repeat(width)).substring(0,width));
}
document.body.appendChild(pre);
for(z of lis){
pre.innerHTML+=z+"\n";
}
```
Results for 30x30:
```
11 13 17
23 29 31 37
43 47 53
61 67 71 73
83 89 97
103 107 109 113
131 137 139
151 157 163 167
179 181 191
197 199 211 223
229 233 239
251 257 263 269
277 281 283
307 311 313 317
337 347 349
409 419 421 431
439 443 449
461 463 467 479
491 499 503
521 523 541 547
563 569 571
587 593 599 601
613 617 619
641 643 647 653
661 673 677
691 701 709 719
733 739 743
757 761 769 773
797 809 811
823 827 829 839
```
And for the 60x60 case:
```
11 13 17 19 23 29 31 37 41 43
53 59 61 67 71 73 79 83 89 97
103 107 109 113 127 131 137 139 149 151
163 167 173 179 181 191 193 197 199 211
227 229 233 239 241 251 257 263 269 271
281 283 293 307 311 313 317 331 337 347
401 409 419 421 431 433 439 443 449 457
463 467 479 487 491 499 503 509 521 523
547 557 563 569 571 577 587 593 599 601
613 617 619 631 641 643 647 653 659 661
677 683 691 701 709 719 727 733 739 743
757 761 769 773 787 797 809 811 821 823
829 839 853 857 859 863 877 881 883 887
911 919 929 937 941 947 953 967 971 977
991 997 1009 1013 1019 1021 1031 1033 1039 1049
1061 1063 1069 1087 1091 1093 1097 1103 1109 1117
1129 1151 1153 1163 1171 1181 1187 1193 1201 1213
1223 1229 1231 1237 1249 1259 1277 1279 1283 1289
1297 1301 1303 1307 1319 1321 1327 1361 1367 1373
1399 1409 1423 1427 1429 1433 1439 1447 1451 1453
1471 1481 1483 1487 1489 1493 1499 1511 1523 1531
1549 1553 1559 1567 1571 1579 1583 1597 1601 1607
1613 1619 1621 1627 1637 1657 1663 1667 1669 1693
1699 1709 1721 1723 1733 1741 1747 1753 1759 1777
1787 1789 1801 1811 1823 1831 1847 1861 1867 1871
1877 1879 1889 1901 1907 1913 1931 1933 1949 1951
1979 1987 1993 1997 1999 2003 2011 2017 2027 2029
2053 2063 2069 2081 2083 2087 2089 2099 2111 2113
2131 2137 2141 2143 2153 2161 2179 2203 2207 2213
2237 2239 2243 2251 2267 2269 2273 2281 2287 2293
2309 2311 2333 2339 2341 2347 2351 2357 2371 2377
2383 2389 2393 2399 2411 2417 2423 2437 2441 2447
2467 2473 2477 2503 2521 2531 2539 2543 2549 2551
2579 2591 2593 2609 2617 2621 2633 2647 2657 2659
2671 2677 2683 2687 2689 2693 2699 2707 2711 2713
2729 2731 2741 2749 2753 2767 2777 2789 2791 2797
2803 2819 2833 2837 2843 2851 2857 2861 2879 2887
2903 2909 2917 2927 2939 2953 2957 2963 2969 2971
3001 3011 3019 3023 3037 3041 3049 3061 3067 3079
3089 3109 3119 3121 3137 3163 3167 3169 3181 3187
3203 3209 3217 3221 3229 3251 3253 3257 3259 3271
3301 3307 3313 3319 3323 3329 3331 3343 3347 3359
3371 3373 3389 3391 3407 3413 3433 3449 3457 3461
3467 3469 3491 3499 3511 3517 3527 3529 3533 3539
3547 3557 3559 3571 3581 3583 3593 3607 3613 3617
3631 3637 3643 3659 3671 3673 3677 3691 3697 3701
3719 3727 3733 3739 3761 3767 3769 3779 3793 3797
3821 3823 3833 3847 3851 3853 3863 3877 3881 3889
3911 3917 3919 3923 3929 3931 3943 3947 3967 3989
4003 4007 4013 4019 4021 4027 4049 4051 4057 4073
4091 4093 4099 4111 4127 4129 4133 4139 4153 4157
4177 4201 4211 4217 4219 4229 4231 4241 4243 4253
4261 4271 4273 4283 4289 4297 4327 4337 4339 4349
4363 4373 4391 4397 4409 4421 4423 4441 4447 4451
4463 4481 4483 4493 4507 4513 4517 4519 4523 4547
4561 4567 4583 4591 4597 4603 4621 4637 4639 4643
4651 4657 4663 4673 4679 4691 4703 4721 4723 4729
4751 4759 4783 4787 4789 4793 4799 4801 4813 4817
4861 4871 4877 4889 4903 4909 4919 4931 4933 4937
4951 4957 4967 4969 4973 4987 4993 4999 5003 5009
```
] |
[Question]
[
In the [PPCG](https://codegolf.stackexchange.com/) chatroom the [Nineteenth Byte](https://chat.stackexchange.com/rooms/240/the-nineteenth-byte), using carets `^` (or [carrots](http://meta.codegolf.stackexchange.com/a/7330/26997)) is a way of indicating that you agree with one of the previously made comments just above yours.
A caret message consists solely of N `^` characters (where N is a positive integer) and it means agreement with the Nth previous message. So a single `^` means agreement with the message immediately previous, `^^` means agreement with the message two lines up, `^^^` means agreement with the message three lines up, and so on.
Additionally, when a caret message X is in agreement (a.k.a. pointing towards) another caret message Y, then X is said to be in agreement with what Y is in agreement with. There may be multiple layers of this and, in the end, all caret messages are indicating agreement with one non-caret message.
For example, if a chat transcript looks like this: (one message per line)
```
I like dogs [line 1]
I like cats [line 2]
^ [line 3]
^^^ [line 4]
^^ [line 5]
I like turtles [line 6]
^ [line 7]
^^^ [line 8]
^^ [line 9]
```
Then lines 1, 2, and 6 are non-caret messages and all the others are caret messages which point to non-caret messages:
* Line 3 points directly to line 2.
* Line 4 points directly to line 1.
* Line 5 points to line 3, which points to line 2.
* Line 7 points to line 6.
* Line 8 points to line 5, which points to line 3, which points to line 2.
* Line 9 points to line 7, which points to line 6.
Thus, including the users who wrote the non-caret message (and assuming people don't caret their own message) we can conclude that:
* 2 people agree with `I like dogs` (Lines 1 and 4.)
* 4 people agree with `I like cats` (Lines 2, 3, 5, and 8.)
* 3 people agree with `I like turtles` (Lines 6, 7, and 9.)
# Challenge
Write a program or function that takes in a multiline string similar to the example above where every line represents a chat message, with older messages coming first.
Every line will have at least one character and there will be at least one line. All messages will either be caret messages consisting solely of `^`'s, or be non-caret messages consisting of letters and spaces (`[ a-zA-Z]+` in regex).
For every non-caret message, in any order, output the number of people that agree with it in some clear format that contains the message text, e.g.
```
2 - I like dogs
4 - I like cats
3 - I like turtles
```
or
```
I like cats (4)
I like dogs (2)
I like turtles (3)
```
or
```
{"I like cats" : 4, "I like turtles" : 3, "I like dogs" : 2}
```
You can assume that:
* People always agree with their own messages and do not caret themselves.
* No two non-caret messages are identical.
* Caret messages won't point to things before the first message.
* Lines will not contain leading or trailing spaces.
**The shortest code in bytes wins.**
# Test Cases
```
bread is bread
1 - bread is bread
---
animals are fuzzy
^
^
^
^^^
^^
^^^^^^
7 - animals are fuzzy
---
pie
^
^^
pi
^
^^
^^^^
^
^^^^^
^^^^^
^^^
^^^^
^^
^
^^^^^^^^^
9 - pie
6 - pi
---
a
b
c
^
^
^
1 - a
1 - b
4 - c
---
a
b
c
^
^^
^^^
1 - a
1 - b
4 - c
---
a
b
c
^^^
^^^^
^^^^^
4 - a
1 - b
1 - c
---
W
^
^^
X
^^^
^^^^
Y
^^^^^
^^^^^^
Z
^^^^^^^
^^^^^^^^
1 - Y
3 - X
1 - Z
7 - W
---
ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqretuvwxyz
^
ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqretuvwxyz
2 - ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqretuvwxyz
1 - ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqretuvwxyz
---
I like dogs
I like cats
^
^^^
^^
I like turtles
^
^^^
^^
2 - I like dogs
4 - I like cats
3 - I like turtles
```
[Answer]
# CJam, 18
```
qN/{_'^e=$\;}%$e`p
```
2 bytes eliminated thanks to Martin :)
[Try it online](http://cjam.aditsu.net/#code=qN%2F%7B_%27%5Ee%3D%24%5C%3B%7D%25%24e%60p&input=I%20like%20dogs%0AI%20like%20cats%0A%5E%0A%5E%5E%5E%0A%5E%5E%0AI%20like%20turtles%0A%5E%0A%5E%5E%5E%0A%5E%5E)
**Explanation:**
```
q read the input
N/ split into lines
{…}% transform each line as follows:
_ make a copy
'^e= count '^' characters in the string
$ copy the corresponding earlier line from the stack
if 0, it copies the current line again
\; discard the current line (from before the copied line)
* after the loop, all caret lines have been replaced
* with the original messages they agree with
$ sort the messages
e` RLE encode
p pretty print
```
[Answer]
# Pyth, ~~19~~ 18 bytes
```
rSu+G@+HG_/H\^.zY8
```
[Demonstration](https://pyth.herokuapp.com/?code=rSu%2BG%40%2BHG_%2FH%5C%5E.zY8&input=pie%0A%5E%0A%5E%5E%0Api%0A%5E%0A%5E%5E%0A%5E%5E%5E%5E%0A%5E%0A%5E%5E%5E%5E%5E%0A%5E%5E%5E%5E%5E%0A%5E%5E%5E%0A%5E%5E%5E%5E%0A%5E%5E%0A%5E%0A%5E%5E%5E%5E%5E%5E%5E%5E%5E&debug=0)
A similar approach to aditsu, especially the rle part.
```
rSu+G@+HG_/H\^.zY8
u .zY Reduce over the list input lines, starting with [].
G is the working value, H is the next input line.
+G Append to the current value
+HG H prependeded to G
@ _/H\^ Indexed at -(H.count('^')). This is H if no carets are in H,
or the appropiate distance from the end of G otherwise.
S Sort
r 8 Run length encode
```
[Answer]
# JavaScript (ES6), 110 bytes
```
x=>(r={},l=x.split`
`,l.map((_,i)=>(a=n=>(m=l[n])[0]=="^"?a(n-m.length):r[m]=r[m]+1||1)(i)),JSON.stringify(r))
```
## Explanation
```
x=>(
r={}, // r = results
l=x.split`
`, // l = array of messages
l.map((_,i)=> // check each message
(a=n=> // n = index of the message to agree with
(m=l[n]) // m = message
[0]=="^" // if this is a caret message
?a(n-m.length) // agree with the message it points to
:r[m]=r[m]+1||1 // else add one to this message's agreements
)(i)
),
JSON.stringify(r) // return the results as a string
)
```
## Test
```
<textarea id="input" rows="7">I like dogs
I like cats
^
^^^
^^
I like turtles
^
^^^
^^</textarea>
<br />
<button onclick='result.textContent=(
x=>(r={},l=x.split`
`,l.map((_,i)=>(a=n=>(m=l[n])[0]=="^"?a(n-m.length):r[m]=r[m]+1||1)(i)),JSON.stringify(r))
)(input.value)'>Go</button>
<pre id="result"></pre>
```
[Answer]
# Mathematica, ~~83~~ 77 bytes
```
Tally@#[[Range@Length@#-#~StringCount~"^"//.x_:>x[[x]]]]&@StringSplit[#,"
"]&
```
[Answer]
# Ruby 89
```
m={}
v={}
i=0
$<.map{|l|(t=l.chop![/\^+/])?v[m[i]=o=m[i-t.size]]+=1:v[m[i]=l]=1;i+=1}
p v
```
This is a program that gets input from STDIN and prints out the result.
It keeps track of the messages and their vote counts in the variable `v`, which is a `Hash`.
Online demos:
* <http://ideone.com/SdRcPD>
* <http://ideone.com/H7fWVf>
[Answer]
## Python 2.7 - ~~122~~ 114 bytes
```
def c(s):
l=s.split('\n');c=len(l);d=[1]*c
while c:
c-=1
if'^'in l[c]:d[c-len(l[c])]+=d[c]
else:print l[c],d[c]
```
Pretty much the most straightforward solution there is, and not particularly golfed.
[Answer]
**Python 2.7 96 bytes**
```
l=s.split();b={}
for i in l:_=l.index(i);l[_]=l[_-i.count('^')];b[l[_]]=b.get(l[_],0)+1
print b
```
explanation:
in-place overwrite of l, each call of `l[_] = ...` stores the word pointed to, and a dictionary is used to tally the results by initializing or adding to the current count of `b[l[_]]`
] |
[Question]
[
## The winner (pretty obviously) is Dennis ♦, who used Jelly with 10 bytes!
This challenge will still be up here, however results won't be taken anymore.
---
The powertrain of a number is a concept by John Conway (who is also notable for making Conway's Game of Life, but that's not the point). It is defined as so:
For any number [](https://i.stack.imgur.com/wS3oK.gif)..., the powertrain of the number is [](https://i.stack.imgur.com/pUxdi.gif)... (i.e. every 2nd digit, from left to right, is a power of the digit before that). This process is repeated until the result is a single digit.
EXAMPLES:
`2592 => (2^5)(9^2) = 2592 <= Cannot be further decomposed
135 => (1^3)5 = 5
1234 => (1^2)(3^4) = 81 => (8^1) = 8
1100 => (1^1)(0^0) = 1 # (0^0) = 1
-42 => -42 # Negative numbers output the input`
Your challenge is, for any number `n` in the input, return `powertrain(n)` (i.e. `n` after the powertrain decomposition is finished) as output.
This is code golf, so shortest amount of bytes wins.
DISCLAIMER-THINGS:
* You can have an odd number of digits in the input, the last digit just won't have a power.
* 0^0 is 1, because if it was 0, then a lot of numbers would instantly collapse to 0 or 1.
* If the number is indestructible in any part of the computation process (e.g. if it ends up with `2592`), then you can just output the number.
* If the input is `< 10` (i.e. all single digit numbers and negatives), output the input.
I'll probably announce a winner after a few hours days.
Current leaderboard:
>
> 1. Jelly ([Dennis ♦](https://codegolf.stackexchange.com/a/75102/49561)): 10
> 2. Pyth ([DenkerAffe](https://codegolf.stackexchange.com/a/75088/49561)): 16
> 3. MATL ([Don Muesli](https://codegolf.stackexchange.com/a/75103/49561)): 21
> 4. Perl ([Ton Hospel](https://codegolf.stackexchange.com/a/75096/49561)): 42
> 5. Haskell ([Damien](https://codegolf.stackexchange.com/a/75101/49561)): 64
> 6. Javascript ES6 ([edc65](https://codegolf.stackexchange.com/a/75089/49561)): 71
> 7. Mathematica ([murphy](https://codegolf.stackexchange.com/a/75383/49561)): 74
> 8. Mathematica ([LegionMammal978](https://codegolf.stackexchange.com/a/75107/49561)) and Haskell ([Renzeee](https://codegolf.stackexchange.com/a/75098/49561)): 77
> 9. Python 2 ([mathmandan](https://codegolf.stackexchange.com/a/75170/49561)): 111
> 10. Python 3 ([Erwan](https://codegolf.stackexchange.com/a/75087/49561)): 161
> 11. Java 8 ([Blue](https://codegolf.stackexchange.com/a/75427/49561)): 229
> 12. Oracle SQL 11.2 ([Jeto](https://codegolf.stackexchange.com/a/75180/49561)): 456
> 13. Befunge '93 ([Lex](https://codegolf.stackexchange.com/a/75189/49561)): 490
>
>
>
[Answer]
# Haskell, ~~67~~ 64 bytes
**(>>=(==))>>=until$p.show** is an unnamed function taking an integer as input and returning its powertrain.
Saved 3 bytes thanks to Zgarb
```
p(x:y:r)=p[x]^p[y]*p r;p[]=1;p x=read x
(>>=(==))>>=until$p.show
```
[Answer]
# Jelly, ~~15~~ ~~14~~ ~~12~~ 10 bytes
```
Ds2*/€Pµ³¡
```
[Try it online!](http://jelly.tryitonline.net/#code=RHMyKi_igqxQwrXCs8Kh&input=&args=MTIzNA)
### How it works
```
Ds2*/€Pµ³¡ Main link. Argument: n
D Convert n into the array of its decimal digits.
s2 Split into pairs of digits.
*/€ Reduce each pair by exponentiation.
P Take the product of the resulting powers.
µ Push the preceding chain as a link, and start a new one.
³¡ Execute the link n times and return the last result.
```
[Answer]
# Perl, 42 ~~48~~ bytes
Include +2 for `-lp` (you can drop the `-l` too but I like newlines)
Run with input on STDIN, e.g.
```
perl -lp powertrain.pl <<< 1234
```
`powertrain.pl`:
```
s/\B/1&pos?"**":"*"/eg until++$.>($_=eval)
```
(on older perls you can also drop the space between the regex and until)
This won't be able to handle the fixed point `24547284284866560000000000` but that large a value won't work anyways because by that time perl switched to exponential notation.
The above version is will in fact work fast (at most `2592` loops) for all numbers that perl can represent without using exponential notation since it is proven that there are no fixed points between `2592` and `24547284284866560000000000` (<https://oeis.org/A135385>)
This does however assume something as yet unproven. In principle there could be a reduction that takes more than `X=10^7` steps (it is conjectured that no non-fixed point takes more than 16 steps, <https://oeis.org/A133503>) whose value dips below `X` (but above `10^7`) and then goes up again. If that is the case I must fall back to:
```
s/\B/1&pos?"**":"*"/eg until$s{$_=eval}++||/-/
```
## Explanation
The code works by putting `**` and `*` (alternating) between the digits
```
s/\B/1&pos?"**":"*"/eg
```
so `2592` becomes `2**5*9**2` and `12345` becomes `1**2*3**4*5`. These are
valid perl expressions that can be evaluated with
```
$_ = eval
```
(`0**0` is `1` in perl). Then just put a loop around that with a counter that makes it expire. Since except for the fixed points the values go down extremely quickly the powertrain series converges before the counter gets a chance to really get going
[Answer]
# Pyth, ~~25~~ ~~18~~ ~~11~~ 16 bytes
```
?<Q0Qu*F^McjGT2Q
```
[Try it here!](http://pyth.herokuapp.com/?code=%3F%3CQ0Qu*F%5EMcjGT2Q&input=0&test_suite=1&test_suite_input=2592%0A135%0A1234%0A-4&debug=0)
~~7~~ 14 bytes saved with help from @Jakube
## Explanation
```
?<Q0Qu*F^McjGT2Q # Q = eval(input)
?<Q0Q # If input is negative return Q
u Q # apply the following function until we reach a cycle
# starting value is Q and the current value is in G
jGT # split input into a list of digits
c 2 # split into pairs of 2
^M # compute the power for every pair
*F # compute the product of all powers
```
[Answer]
# Python 2, 111 bytes
```
def p(n,b=0,o=''):
if n<1:return n
for c in str(n):o+=c+'**'[b:];b=~b
j=eval(o+'1');return p(j)if j-n else j
```
The idea is to make a string where the digits of `n` are separated by operations which alternate between `*` and `**`, and then `eval` that string. (Other solutions use this same idea; see for example [Ton Hospel's Perl answer](https://codegolf.stackexchange.com/a/75096/36885).)
So, the operation switches back and forth between `'**'[0:]`, which is `**`, and `'**'[-1:]`, which is just `*`.
However, by the end of the `for`-loop, the string ends with an operation (one or the other), so we either need to drop the last operation, or else add another digit, in order for the string to make sense.
Fortunately, appending a `1` on the end will work no matter which operation is last. (If you like, `1` is a one-sided identity from the right, for both multiplication and exponentiation. Another way of saying this is that `powertrain(n) == powertrain(10*n + 1)` for all `n>0`.)
Finally, if the result of the `eval` happens to be the same as the input (as in a length-`1` cycle), the function terminates. Otherwise, the function calls itself on the result. (It will hang forever on any cycle of length `> 1`, but according to the OP's comments I am allowed to assume there are no such cycles.)
(Note: the above explanation works for single-digit positive integers, since a single-digit input `n` will be completed to `n**1` which will result in a `1`-cycle. However, we also need to accept non-positive input, so there's a condition at the beginning that short-circuits if the input is less than `1`. We could eliminate that line, and save 17 bytes, if the input were guaranteed to be non-negative.)
[Answer]
## Java 8, ~~265~~ ~~244~~ 229 bytes
This is my first answer, but I have been reading this site for a while and think I know what I'm doing. At least it beats befunge and SQL...
Unfortunately, like other answers, this one does not work for 24547284284866560000000000 due to java'a built in restrictions on how large integers can get.
Saved 36 bytes thanks to @JackAmmo
```
public int p(int n){if(n<10)return n;int i=1,t=1,s=(int)Math.log10(n)+1,r[]=new int[s];for(;i<=s;){int a=(int)Math.pow(10,i);r[s-i++]=n%a/(a/10);}for(i=0;i<s-1;i++)t*=Math.pow(r[i],r[++i]);if(s%2==1)t*=r[s-1];return n==t?n:p(t);}
```
**Ungolfed Explanation**
```
public int powertrain(int input){
//handles negative and 1-digit cases
if(input<10)return input;
//initialize output variable
int total=1;
// get "length" of number. Shorter than getting length of string representation
int size=(int)Math.log10(input)+1;
//initialize array to store digits
int[] array=new int[size];
//Now, because Java doesn't have support
// for the "**" operation, and the way of turning
// an integer into a string takes too many bytes,
// I decided just to put every digit into an array with
// math and iterate from there
for(int i=1;i<=size;){
int place=(int)Math.pow(10,i);
//crazy math. Saved 1 byte by incrementing i when accessed
array[size-i++]=input%place/(place/10);
}
for(int i=0;i<size-1;i++)
//This is where the train happens.
//Saved 1 byte by incrementing while accessing
//again, instead of i+=2 and i+1
total*=Math.pow(array[i],array[++i]);
//Make sure last number isn't left out if size is odd
if(size%2==1)
total*=array[size-1];
//if we end up with same number, stop.
//otherwise, keep recurring
return input==total?input:powertrain(total);
}
```
[Answer]
# JavaScript (ES6) 71
A recursive function, stopping when a repetition is found. This could not work for longer loops (2 or more value repeating) but it seems this could not happen, at least in the limited range of javascript number precision (17 digits)
```
f=n=>[...n+'1'].map((c,i)=>i&1?r*=Math.pow(d,c):d=c,r=1)&&n-r?f(r):n
```
**Test**
```
f=n=>[...n+'1'].map((c,i)=>i&1?r*=Math.pow(d,c):d=c,r=1)&&n-r?f(r):n
function go()
{
v=+I.value
R.textContent=f(v)
}
go()
```
```
<input id=I value="1234"><button onclick="go()">Go</button>
<span id=R></span>
```
[Answer]
# Mathematica, 77 bytes
```
Times@@(If[#2<1,1,#^#2]&)@@@Partition[IntegerDigits@#,2,2,1,1]&~FixedPoint~#&
```
Anonymous function. Not too complicated.
[Answer]
## Befunge ~~720~~ 490 bytes
Couldn't resist to do one more after the [Never tell me the odds](https://codegolf.stackexchange.com/questions/75071/never-tell-me-the-odds/75097#75097) thing. So, I've optimized the "ASCII-fier" of the previous one. In this case I saw no need to let the instruction pointer run over the digits to read them, so I haven't taken the effort to make them human readable. So it's more of a digitifier, now.
Again, if you guys want an explanation, let me know in the comments, I'll try to create some helpful descriptions. You can copy paste the code into [the interpreter](http://www.quirkster.com/iano/js/befunge.html). I've found that the example 24547284284866560000000000 outputs 0, but that seems to be a problem with getting such a large value from a point on the grid, as you can clearly see the correct value being stored in the final steps.
```
v //top row is used for "variables"
>&:0`#v_.@ //initialize the counter
v < g01_v#-p01: < //on our way back to the digitifier, check if we're done
>::>210p>55+%:10g0p-55+/:v >10g.@ //digitifier, creates a series of ASCII characters at the top line, one for each digit in the source
^p01+1g01 _v#:<
v1$$ < //forget some remainders of the digitifier, put 1 on the stack as a base of calculation
v p0-1g01-1g0-1g01*g0g01< //taking powers of each pair of digit
>10g2-!#v_10g1-!#v_ 1> 10g1-0g|
^ p01-2g01 *<
>10g0g* > ^ //extra multiplication with last digit if the number of digits was odd
```
This version also supports negative input. It's a great improvement on the previous version, if I say so myself. At least 1 bug was fixed and the size was reduced greatly.
[Answer]
# Haskell, ~~100~~ ~~79~~ 77 bytes
```
g x|x==h x=x|1<2=g$h x;h=i.map(read.(:[])).show;i[]=1;i[a]=a;i(a:b:c)=a^b*i c
```
Not golfed:
```
g x|x==h x=x|1<2=g$h x
h=i.map(read.(:[])).show
i[]=1
i[a]=a
i(a:b:c)=a^b*i c
```
This function splits the input into digits and does the trick via `i`.
EDIT: Thanks to nimi for some tips.
[Answer]
# Mathematica, 74 bytes
```
0~f~0=f[]=1
f@n_=n
f[a_,b_,c___]:=f[c]a^b
#//.i_/;i>0:>f@@IntegerDigits@i&
```
**Explanation**
This solution uses a helper function `f`, which takes the digits of the number as arguments and applies one iteration of the power train operation. The last line is a pure function that is crafted to exploit the `ReplaceRepeated` function (or `//.` for short), which applies a rule to an expression (in this case the argument `#` of the pure function) until it doesn't change anymore.
The rule `i_/;i>0:>f@@IntegerDigits@i` replaces anything non-negative with the function `f` applied to its decimal digits.
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 21 bytes
```
tt0>*:"V!UtQgv9L2#)^p
```
It may take a few seconds to produce the output.
*EDIT (July 30, 2016): the linked code replaces `9L` by `1L` to adapt to recent changes in the language.*
[**Try it online!**](http://matl.tryitonline.net/#code=dHQwPio6IlYhVXRRZ3YxTDIjKV5w&input=LTM)
This uses the following two tricks to reduce byte count at the expense of code efficiency:
* Iterate `n` times instead of waiting until a cycle is found. This is acceptable as per OP's comments.
* For an odd number of digits a final `1` would have to be appended to complete the final power operation. Instead of that, the number of added `1` is the number of digits. This ensures an even number, so all power operations can be done (even if the last ones are unnecessary `1^1` operations).
Code:
```
t % implicitly take input x. Duplicate
t0>* % duplicate. Is it greater than 0? Multiply. This gives 0 if input is negative,
% or leaves the input unchanged otherwise
: % Generate array [1,2,...,x]
" % for each (repeat x times)
V % convert x to string
! % transpose into column char array
U % convert each char into number
tQg % duplicate. Add 1 so that no entry is zero. Convert to logical: gives ones
v % concatenate vertically
9L2#) % separate odd-indexed and even-indexed entries
^ % element-wise power
p % product of all entries
% implicitly end for each
% implicitly display
```
[Answer]
## Python 3, ~~169~~ 161 bytes
```
def f(s):
o=[['1',s]['-'in s]]
while s not in o:
o+=[s];s+='1'*(len(s)%2==1);r=1;
for i,j in zip(s[::2],s[1::2]):r*=int(i)**int(j);s=str(r);
return o[-1]
```
**Ungoldfed**
```
def f(s):
o=[['1',s]['-'in s]]
while s not in o:
o+=[s]
s+='1'*(len(s)%2==1)
r=1
for i,j in zip(s[::2],s[1::2]):
r*=int(i)**int(j)
s=str(r)
return o[-1]
```
## Results
```
>>> [f(i) for i in ['135', '1234', '642', '2592', '-15']]
['5', '8', '2592', '2592', '-15']
```
[Answer]
# Oracle SQL 11.2, 456 bytes
```
WITH v(n,c,i,f,t)AS(SELECT:1+0,CEIL(LENGTH(:1)/2),1,'1',0 FROM DUAL UNION ALL SELECT DECODE(SIGN(c-i+1),-1,t,n),DECODE(SIGN(c-i+1),-1,CEIL(LENGTH(t)/2),c),DECODE(SIGN(c-i+1),-1,1,i+1),DECODE(SIGN(c-i+1),-1,'1',RTRIM(f||'*'||NVL(POWER(SUBSTR(n,i*2-1,1),SUBSTR(n,i*2,1)),SUBSTR(n,i*2-1,1)),'*')),DECODE(SIGN(c-i+1),-1,0,TO_NUMBER(column_value))FROM v,XMLTABLE(f)WHERE i<=c+2 AND:1>9)CYCLE n,c,i,f,t SET s TO 1 DEFAULT 0SELECT NVL(SUM(n),:1) FROM v WHERE s=1;
```
Un-golfed
```
WITH v(n,c,i,f,t) AS
(
SELECT :1+0,CEIL(LENGTH(:1)/2),1,'1',0 FROM DUAL
UNION ALL
SELECT DECODE(SIGN(c-i+1),-1,t,n),
DECODE(SIGN(c-i+1),-1,CEIL(LENGTH(t)/2),c),
DECODE(SIGN(c-i+1),-1,1,i+1),
DECODE(SIGN(c-i+1),-1,'1',RTRIM(f||'*'||NVL(POWER(SUBSTR(n,i*2-1,1),SUBSTR(n,i*2,1)),SUBSTR(n,i*2-1,1)),'*')),
DECODE(SIGN(c-i+1),-1,0,TO_NUMBER(column_value))
FROM v,XMLTABLE(f) WHERE i<=c+2 AND :1>9
)
CYCLE n,c,i,f,t SET s TO 1 DEFAULT 0
SELECT NVL(SUM(n),:1) FROM v WHERE s=1;
```
v is a recursive view, parameters are
n : number to split in 2 digits parts
c : number of 2 digits parts
i : current 2 digits part to compute
f : string concatenating the powers with \* as separator
t : evaluation of f
The DECODEs switch to the next number to split and compute when all the parts of the current number are done.
XMLTABLE(f) takes an expression an evaluates it, putting the result in the pseudo column "column\_value".
It's the golfed version of <http://tkyte.blogspot.fr/2010/04/evaluating-expression-like-calculator.html>
CYCLE is the oracle build in cycle detection and is used as the exit condition.
Since the result for :1<10 is :1 and v returns no row for those cases, SUM forces a row with NULL as the value.
NVL returns :1 as the result if the row is null.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 10 bytes
```
ωöΠmF`^C2d
```
[Try it online!](https://tio.run/##yygtzv7//3zn4W3nFuS6JcQ5G6X8///f0MjYBAA "Husk – Try It Online")
## Explanation
```
ωöΠmF`^C2d
ωö apply the following functions till a fixed point is reached:
d get base-10 digits
C2 split into groups of two
mF`^ map each pair to power
Π multiply all the powers.
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 13 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
Èì ò ®rpÃ×}gN
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=yOwg8iCucnDD131nTg&input=MTIzNA)
] |
[Question]
[
# Santa's Decision:
In this challenge, you will help Santa Claus decide whether somebody on their list has been naughty or nice, and subsequently get `coal` or `toys`.
But unfortunately, Santa is unorganised, in some of his entries, the `naughty`, `nice` and `name` fields are in the wrong order.
## Input
Input will come in the following, interchangeable format:
* the person's name (cannot contain a colon, only `a-zA-Z0-9`)
* the word `naughty` followed directly by a colon and an non-negative integer representing the amount of times Santa caught you being naughty
* the word `nice` followed directly by a colon and an non-negative integer representing the amount of times Santa caught you being nice
All separated with a single whitespace (ASCII 32) between each of them.
Additionally, the name will have no whitespace between the parts of the name `Santa Claus` -> `SantaClaus`.
## Bonus:
* **(25%)**: He is Santa Claus, so he needs to check the list *twice*, and make sure there are no duplicates. (In which case, it just gets the first scores that user has)
## Example:
```
Quill naughty:4 nice:0
naughty:0 Doorknob nice:3
naughty:2 Quill nice:6
nice:3 balpha naughty:3
pops nice:4 naughty:2
```
## Output:
The output should consist of:
The name of the person followed by:
* If there's more points in `naughty`, then `coal`:
* If there's more points in `nice`, then `toys`.
* But if `naughty` and `nice` are equal, then `needs more data`
### Example output:
* With organisation bonus and duplicate removal bonus:
```
Quill coal
Doorknob toys
balpha needs more data
pops toys
```
* Without bonus:
```
Quill coal
Doorknob toys
Quill toys
balpha needs more data
pops toys
```
# Lowest byte count wins!
[Answer]
# Julia, ~~176~~ 169 bytes
```
s->for l=split(s,"\n") M(r)=parse(matchall(r,l)[1]);g=M(r"e:\K\d+");b=M(r"y:\K\d+");println(replace(l,r" *\w+:\d+ *","")," ",g>b?"toys":b>g?"coal":"needs more data")end
```
This is an anonymous function that accepts a string and prints the result to STDOUT. To call it, give it a name, e.g. `f=s->...`.
Ungolfed:
```
function santa(s::AbstractString)
# Split the input on newlines and process each line separately
for l in split(s, "\n")
# Define a function to get the number from the result of a
# regular expression match
M(r) = parse(matchall(r, l)[1])
# Goodness
g = M(r"e:\K\d+")
# Badness
b = M(r"y:\K\d+")
# Get the name by replacing the naughty and nice specifications
# with empty strings and print the line to STDOUT
println(replace(l, r" *\w+:\d+ *", ""), " ",
g > b ? "toys" : b > g ? "coal" : "needs more data")
end
end
```
[Answer]
# Pyth, 68 bytes - 25% = 51
```
V.zI-hA.g}\:kcNdY=+YGjd+G@c"needs more data
coal
toys"b._-Fmsecd\:SH
```
Try it online: [Demonstration](https://pyth.herokuapp.com/?code=V.zI-hA.g%7D%5C%3AkcNdY%3D%2BYGjd%2BG%40c%22needs+more+data%0Acoal%0Atoys%22b._-Fmsecd%5C%3ASH&input=Quill+naughty%3A4+nice%3A0%0Anaughty%3A0+Doorknob+nice%3A3%0Anaughty%3A2+Quill+nice%3A6%0Anice%3A3+balpha+naughty%3A3%0Apops+nice%3A4+naughty%3A2&debug=0)
[Answer]
# Pyth - 64 bytes
Will try to use packed strings.
```
jmj\ +hK.g@k\:cd\ @c"needs more data
coal
toys"b._-Fmseck\:SeK.z
```
[Try it online here](http://pyth.herokuapp.com/?code=jmj%5C+%2BhK.g%40k%5C%3Acd%5C+%40c%22needs+more+data%0Acoal%0Atoys%22b._-Fmseck%5C%3ASeK.z&input=naughty%3A0+Doorknob+nice%3A3%0AQuill+naughty%3A4+nice%3A0%0Anice%3A3+balpha+naughty%3A3%0Apops+nice%3A4+naughty%3A2&debug=0).
[Answer]
# Ruby, ~~144~~ ~~123~~ 155 \* .75 = 116.25 bytes
```
->s{d={}
s.split("
").map{|l|
a=l.split
b=a.grep /:/
i,j,v=(b.sort*'').scan(/\d+/)+a-b
d[v]||(d[v]=0
puts v+' '+['needs more data','coal','toys'][i<=>j])}}
```
Thanks to histocrat for suggesting `grep` method.
**164 \* .75 = 123 bytes**
```
->s{d={}
s.split("
").map{|l|
a=l.split
b=a.select{|t|t[?:]}
i,j,v=(b.sort*'').scan(/\d+/)+a-b
d[v]||(d[v]=0
puts v+' '+['needs more data','coal','toys'][i<=>j])}}
```
**144 bytes**
```
->s{puts s.split("
").map{|l|b=(a=l.split).select{|t|t[?:]};i,j=(b.sort*'').scan(/\d+/);(a-b)[0]+' '+['needs more data','coal','toys'][i<=>j]}}
```
**Ungolfed**
```
->s{
d={}
s.split("
").map{ |l|
a = l.split
b = a.grep /:/
i, j, v = (b.sort * '').scan(/\d+/) + a-b
d[v] ||
(d[v]=0
puts v + ' ' + ['needs more data','coal','toys'][i<=>j]
)
}
}
```
**Usage:**
```
# Assign the anonymous function to a variable
f = ->s{d={}
s.split("
").map{|l|
a=l.split
b=a.grep /:/
i,j,v=(b.sort*'').scan(/\d+/)+a-b
d[v]||(d[v]=0
puts v+' '+['needs more data','coal','toys'][i<=>j])}}
f["Quill naughty:4 nice:0
naughty:0 Doorknob nice:3
naughty:2 Quill nice:6
nice:3 balpha naughty:3
pops nice:4 naughty:2"]
Quill coal
Doorknob toys
balpha needs more data
pops toys
```
[Answer]
## Perl, ~~138~~ ~~113~~ ~~105~~ ~~103~~ ~~102~~ 96 - 25% = 72
*includes +1 for `-p`*
```
s/ *\w*(.):(\d+) */$$1=$2,()/eg;$$_++?$_='':s/\n/$".('needs more data',toys,coal)[$e<=>$y].$&/e
```
# Less golfed:
```
s/ *\w*(.):(\d+) */$$1=$2,()/eg; # strip naughty/nice, set $a to naughty, $i to nice
# $_ is now the input name followed by \n
$$_++ ? $_='' : # only output once per name
s/\n/ # replace newlines with:
$". # a space,
('needs more data',toys,coal) # one of these strings,
[$e<=>$y] # indexed by -1, 0 or 1
.$& # and the matched newline.
/ex # (/x only for legibility)
```
---
* *update 113*
+ save 25 bytes by using 1 letter from `nice` or `naughty` as variable name;
+ loose 5 bytes by fixing bug when name is last
* *update 105* save 8 bytes by using `<=>` to index a list of output strings.
* *update 103* save 2 bytes by using regex to append output string
* *update 102* save 1 byte by using last letter of `nice` or `naughty` instead of 2nd.
* *update 96* save 6 bytes by changing `$$_ ? ... : ($$_++, ...)` into `$$_++ ? ... : ...`
*(why didn't I see that before).*
[Answer]
# JavaScript (ES6), 174 bytes - 25% bonus = 130.5 score
```
s=>s.split`
`.map(l=>l.split` `.map(p=>(m=p.match(/\w:\d+/))?(n=+m[0].slice(2),m>"f")?b=n:c=n:a=p)&&d[a]?"":d[a]=a+" "+(b>c?`coal
`:b<c?`toys
`:`needs more data
`),d={}).join``
```
## Explanation
```
s=>
s.split`
`.map(l=> // for each line l of Santa's list
l.split` `.map(p=> // for each word p in l
(m=p.match(/\w:\d+/)) // m = "y:x" for naughty, "e:x" for nice or null for name
?(n=+m[0].slice(2), // n = number at end of match
m>"f")?b=n:c=n // if naughty matched b = n, if nice matched c = n
:a=p // if no match, a = name
)
&&d[a]?"": // if the name has been used before, add nothing to output
d[a]= // else set d[name] to true
// Add the appropriate text to the output
a+" "+(b>c?`coal
`:b<c?`toys
`:`needs more data
`),
// NOTE: This line is executed BEFORE the code above it in the map function...
d={} // d = list of names that have been output
)
.join`` // return the list of outputs as a string
```
## Test
```
var solution = s=>s.split`
`.map(l=>l.split` `.map(p=>(m=p.match(/\w:\d+/))?(n=+m[0].slice(2),m>"f")?b=n:c=n:a=p)&&d[a]?"":d[a]=a+" "+(b>c?`coal
`:b<c?`toys
`:`needs more data
`),d={}).join``
```
```
<textarea rows="5" cols="40" id="input">Quill naughty:4 nice:0
naughty:0 Doorknob nice:3
naughty:2 Quill nice:6
nice:3 balpha naughty:3
pops nice:4 naughty:2</textarea><br />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```
[Answer]
# CJam, 64 bytes
```
qN/{S/':f/_{,1=},_@^$1f=:~:-g"needs more data
coal
toys"N/=S\N}/
```
[Try it online!](http://cjam.tryitonline.net/#code=cU4ve1MvJzpmL197LDE9fSxfQF4kMWY9On46LWcibmVlZHMgbW9yZSBkYXRhCmNvYWwKdG95cyJOLz1TXE59Lw&input=UXVpbGwgbmF1Z2h0eTo0IG5pY2U6MApuYXVnaHR5OjAgRG9vcmtub2IgbmljZTozCm5hdWdodHk6MiBRdWlsbCBuaWNlOjYKbmljZTozIGJhbHBoYSBuYXVnaHR5OjMKcG9wcyBuaWNlOjQgbmF1Z2h0eToy)
[Answer]
# Lua, 329 Bytes - 25% bonus = 246.75
```
a={...}p={}u=" "k=ipairs for i=1,#a/3 do p[i]={}end for i,v in k(a)do p[math.floor((i+2)/3)][(v:find("y:")and 3)or(v:find("e:")and 2)or 1]=v:gsub("%a+%:","")end for i,v in k(p)do d=tonumber b,g,n=d(v[3]),d(v[2]),v[1]if(not u:find(" "..n.." "))then u=u..n.." "print(n..(g<b and" coal"or g>b and" toys"or" needs more data"))end end
```
Will edit in ungolfed version and explanations later, a bit tired at the moment. All input is taken in through command line, space separated.
[Answer]
# Python 2, 206 bytes - 25% = 154.5
```
s=[]
x=[0,0]
for p in zip(*(iter(input().split()),)*3):
for w in p:
j=w.find(':')+1
if j:x[j<6]=int(w[j:])
else:N=w
b,g=x
if N not in s:print N,['needs more data','coal','toys'][(b>g)-(g>b)];s+=[N]
```
[Answer]
# JavaScript (ES6) 120 (160-25%)
Anonymous function using template strings, there are 4 newlines that are significant and included in the byte count
```
l=>l.split`
`.map(r=>k[r=r.replace(/\S+:(\d+)/g,(a,c)=>(t-=a[1]<'i'?c:-c,''),t=0).trim()]?'':k[r]=r+(t>0?` toys
`:t<0?` coal
`:` needs more data
`),k={}).join``
```
] |
[Question]
[
You are required to write a Hangman solver. Testing against [this](https://gist.github.com/adrianiainlam/10152724) English word list[1], the solver that solves the most number of words wins, with the number of total incorrect guesses being the tie-breaker. All words in the word list will be tested in random order.
[1]: This word list is taken from [here](http://www.kilgarriff.co.uk/bnc-readme.html), then the numbers are removed, then words with length 1 or with non-alphabetical characters are removed, then the most frequent 4096 unique words are chosen as this word list.
### The details:
Your program will interact with the game program, which will give you through stdin the underscores and correctly guessed letters. Your program will give to stdout your guesses, and it has to infer from the input whether the previous guess was right or wrong. After being wrong for 6 times, your program loses. Your program must be ready for the next game after each game ends (after win or loss).
Your code length must be strictly less than 2048 bytes, and your program must not use any external resources (including but not limited to accessing the wordlist on local storage or from the Internet).
**Example**: (Input is preceded by `>` here only for clarification - it is not actually present in the input)
```
>_______ // 7 underscores
a // Now you wait for input again
>_a___a_
e
>_a___a_ // Implies that your guess is wrong
>_____ // new round, this will be given ONLY IF you already have 6 losses
```
Suppose you are wrong for 6 times, you will receive a final input which implies your guess is wrong, and your program must be ready to start a new round (i.e. take another input).
If you win,
```
>_angman
h
>hangman
>_____ // new round
```
After knowing that you have won (because the input has no underscores), you must be ready to accept the next round.
Your program must terminate when it receives an input `END`.
If your program is not deterministic (depends on randomness, pseudorandomness, system time, ambient temperature, my mood etc.), you must explicitly state that in your submission, and your score will be taken 10 times (by me, unless otherwise instructed) and averaged.
**Note**: if you use languages like python, please explicitly flush your stdout after each print statement.
The game program is as follows (credit to [nneonneo](https://codegolf.stackexchange.com/questions/25496/hangman-solver-king-of-the-hill?noredirect=1#comment55833_25496)):
```
import sys, random, subprocess
proc = subprocess.Popen(sys.argv[1:], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
def p(x):
proc.stdin.write(x+'\n')
proc.stdin.flush()
wordlist=[]
f=open('wordlist.txt', 'r')
for i in f:
wordlist.append(i[:-1] if i[-1]=='\n' else i)
# wordlist=[i[:-1] for i in f]
random.shuffle(wordlist)
score=0
totalerr=0
for s in wordlist:
s2=[]
for i in s:
s2.append('_')
err=0
p(''.join(s2))
while err<6 and '_' in s2:
c=proc.stdout.readline().strip()
nomatch=True
for i in range(0, len(s)):
if s[i]==c:
s2[i]=c
nomatch=False
if nomatch:
err+=1
totalerr+=1
p(''.join(s2))
if err<6:
score+=1
p('END')
sys.stderr.write('score is '+str(score)+', totalerr is '+str(totalerr)+'\n')
```
Usage: `python ./game.py [yoursolverprogram]`
Example: `python ./game.py ruby ./solver.rb`
This should work like the old scoring program, but does not depend on named pipes, so it can work on other platforms. Refer to the revision history if you are interested in the old one.
[Answer]
# Python: 2006 bytes, score=1501
# ~~1885 bytes, score=1337~~
# ~~1961 bytes, score=1207~~
Here's my submission:
```
import sys
b='eJwdVQuW4ygMvJdyGgwYtAGJQQKHOf2Wp9/rJqGxVaqP+HxUMlGx5F86/XoqsUuonzAz5cf5vqjJ6OlQudxOJR3ibJ8cwuSmsTX12daVht8ubj15miaEH/GrESXrQrXbl1K0m2hs6dRjMkp1PuS2/9JoVslkLmp2L6J6f5kij4s0nkSPni/5GZtixSuKcKd7lYvsfi7yNYxseKXqV6fURkc//KXe+P6Hc071xuZteixiSRtzMnavwNfqcydqSzb+9hMTlW/UQSNe5uRx1EVp1OhA7gXb0v+i0rKN1rYsGlWBufozlFbzP+i2KXCpNKNjfTwkytcBnv+OgoV6blJ/8NDjF6iqUd2ojqcbrScmIaurHJxs6yHjck96brZJwncsIOHhzwyemZurKFrkmpIX9yXSNGsKdF+F+rF2fam0+KAMj3YdoXFJR+nY7AL4y1jaopNuBhk6sl03pSd7x2IxoyeLO6dGedjp9V0inusji0EAyR4pBttN6dt+UR/SYBHCVwuxPZSvqNYpZhPIWXM3Segs30IFXKZKSzqDkcdORud59xVJ8o4WsJQelUqXnIAjV/2whDybo1mDmhYCeAjZV4552gSWOa5aSG3WZ0SaqZVe4Y+o7R+Ps5knum0pDGNxrKA3De3Lwo/si420aemw2g/tdq5sKN1HyltpLNeY/qPUYwsLatc/pwRq5eSwK4l5LhHEnSIZhhG9xsFqeqDMRctmTnVQRoamwUtloiLNrgV+a0uzHBKAyUYl61yD+m++GkgeW1eiuMDEoCR6504z32V9JHD25tPVHFyXOGOc+A2vABogIw9vfxWBatuHwaWggEELdS+8De8z7ZHhir70cLoQpYYDOgfMw+ASbrhnbrwQ27x4TNt/3qHBEPSmwzlagqlH5J4Bk2FBqEvc9fXORUnnnceiMAc2kALwNdOB4W87eAw2uAwsIncpu+IYutsJwsJ/JfusCZNipqyL8uwjNHuDN3MJQBSg/Sr1ppByfD9RWaAt/QhLGDDv2C1PxSvBbfyEFqNO5ZwZpE2yqd2PjEwueV1aJoBdGxNjSl8klx3nuWAAxgCxKePt0bykLrCcQWspM61K3qcNuJYa53VMBWKNJCsrYkzZGfZf49fotx3ZYURvyYQ+GR6iOVCfT6fB4hkehfOws/k3PjFo82ZgaE60TxccO4DqKEKDVXSsuknSmuzZwB8C+h7YBS3oaRPSyGvurfnNvM2bMustIxXMYsM/WdvAvLn8hIx5CMCJQxEM2P2yLuyWYHvZziC+T8IWooeMVWDnvoF6wcETdOUVYBFcFdCop/CJ07RpwyjNy1kslHYwdfNxGYGtX4lWduETDAFIeLJntoAk/sjHlLI5tIwp6mcLF5gxJOR2eugsO5/fey0EhMb72J+mrwyB3rkw2eT0cCPuAOUc5cw/b7mQi8942Eaig4nkYUE9xi3D+FTVRxd80XLL9MXhgISod0JBHxjPPCNirRsh/0TgWdrB/6u01zHbvUnBDc4yhknZxCXgrgSWdv8h1oQR3q8hjdbbE5zK6e4U9nhNkHxCwjCdN26sS9+BIMPe7+EDExPGccPLQYvC8+SY1ioz3AxVUWfdJi3RNjjEMyiWq31CjITE1cQPTO5En39bkFEzri7c2f8Dkow6qw=='.decode('base64').decode('zlib').split(';')
R=raw_input
def G(c):print c;sys.stdout.flush()
def P(w):
if'END'==w:exit()
d=b[len(w)].split(':');l=len(d[0]);p=f=0
while p<l:
G(d[0][p]);x=R();r=w==x;w=x;f+=r;p+=p+1+r
if'_'not in x:return
for c in d[p-l+1]+'zq':
G(c);x=R();r=w==x;w=x;f+=r
if'_'not in x or f>5:break
while 1:P(R())
```
Score output:
```
score is 1501, totalerr is 21608
```
This program is fully deterministic. The giant blob (which is a base-64-encoded chunk of `zlib` compressed data) is a list of decision trees (one tree per word length). Each decision tree encodes a complete binary tree with a depth between 2 and 5. Each internal node is a single character, and the decision proceeds based on whether the character is present or not in the hangman word.
Each leaf node of the binary tree contains an optimized frequency table specific to that branch of the tree search. The table is specifically optimized to favor completion of certain words, while completely ignoring others (which it cannot reach due to the limited "failure" budget). The table isn't optimized to minimize errors, and thus the totalerr count of the program is high despite its (relatively) good score.
The optimizer, which isn't shown, uses a nondeterministic nonlinear optimizer utilizing a randomized gradient descent strategy to produce the frequency tables.
[Answer]
## Ruby
A joint submission from user [PragTob](https://codegolf.stackexchange.com/users/20217/pragtob) and myself.
```
MAX_TURNS = 6
frequencies = {?t=>[3,48,145,214,252,266,249,223,191,142,63,44,16,1,0,1],?h=>[2,14,81,125,85,91,60,42,30,14,11,6,1,1],?e=>[5,49,260,316,456,408,328,279,202,125,50,32,12,0,0,1],?a=>[4,60,211,259,249,266,253,192,152,111,51,42,15,1,0,1],?n=>[4,30,120,136,214,252,238,214,189,128,59,45,16,0,0,1],?d=>[1,25,100,104,131,123,131,81,63,36,14,15,7,1],?f=>[2,13,51,58,64,67,41,40,28,18,11,9,3,1],?o=>[9,44,150,165,195,220,214,168,155,104,46,37,14,1,0,1],?r=>[1,25,140,246,312,310,263,206,150,95,45,32,11,1],?y=>[3,29,41,58,86,94,83,63,52,31,21,12,2],?u=>[2,23,67,117,126,154,107,97,85,48,27,16,2,0,0,1],?b=>[2,22,53,60,72,59,41,30,36,16,7,6,1],?i=>[3,38,143,179,223,299,270,241,205,134,64,44,16,1,0,1],?s=>[3,23,129,176,195,208,177,136,117,71,44,23,13,1],?c=>[0,12,68,122,146,194,180,163,130,85,49,25,7,0,0,1],?l=>[0,18,153,172,190,196,164,131,125,67,35,20,5,0,0,1],?g=>[1,19,42,75,82,104,78,60,39,30,12,10,0,1],?w=>[1,21,56,56,40,41,18,16,6,2,1,0,0,1],?m=>[2,10,77,68,119,94,104,76,68,45,15,17,8,0,0,1],?p=>[1,24,82,84,94,129,105,88,99,56,24,11,7],?k=>[1,6,65,37,28,24,6,10,3,4],?j=>[0,5,5,6,7,6,5,6,2,0,1,1],?x=>[0,6,4,7,15,22,13,16,9,9,2,2],?v=>[0,3,21,39,47,58,63,42,40,23,10,9,2],?z=>[0,0,3,3,3,5,2,3,0,0,1],?q=>[0,0,1,9,5,13,8,3,5,4,3,2]}
while !(input=gets.chomp)['END']
current_turns = MAX_TURNS
won = false
chars = frequencies.keys.sort_by {|c|
-(frequencies[c][input.length-2] || 0)
}
i=0
while (current_turns > 0) && !won
c=chars[i]
i += 1
puts c
$stdout.flush
old_input = input
input = gets.chomp
if input == old_input
current_turns -= 1
# else
# frequencies[c][input.length-2] -= 1
end
won = !input[?_]
end
end
```
Result:
```
score is 625, totalerr is 23196
```
This has 1672 characters and isn't golfed yet so we have ample room for algorithmic improvement.
First we store a hash of character frequencies (computed from the word list) grouped by word length.
Then in each round we simply sort all characters by the frequencies for the current length and try them from most common to least common one. Using this approach we obviously fail every single word that has even just a medium common character.
[Answer]
**Update**
Using method similar to @nneonneo, I arrive to this code, **exactly 2047 chars**.
Score:
```
score is 987, totalerr is 21964
```
Code:
```
import sys,re
R=raw_input
F=';;;topenayr;elsatrodin;eatslroncih;eastrinclodu;etnocsiralupd;enostciarldpmu;eitnoasrclupmdy;einocstarlpumdyg;itacslnorepumdgyv;intaoslecrupymdgfh;nitaoerclsmudpygfvh;itneaorscmpdlfuvybh;ratdgfihosw;;ceimontalu'.split(';')
G=[''.join('.'*int(c)if i%2 else c for i,c in enumerate(re.split(r'(\d+)',w)))if w else''for w in 'eJwdlA2S4yoMhK+0CpPJ28ppQPxuQFBITMq3f52JXY5TdpC69TXP50ziQ6RWKxV3stBw+XEtIXXvx4u+g5I5e1x0V+fGN236S/b0aU+7UjMNFoyOvVc8hSInersrxBWr0BUqNSchUXT835YlWCyUTtW9Q6PL1UfhRtmVR3gm72dvu/Vts3c+sqPFoSaWbUWqqi9dylLXe65MWM12/CEdkcLX6LVXU7HBuQXSqDyMKTOjgX40Dty966CXY66Q2H/r7b3b7qat2zF8NLbWZ1QpTLvXWN+1NancuPdoE8sXNi1DqrtssxY+7RzRdxUWa5FLDVPzJJnWpTZW4xN4Uay1BFvUIxNKtz2le7/N47Bt3XedKjyttQgl/dhlcfvNZaNkFN8OnsrULiPQGqeeOsZRPZVl+sXsT61413rvqr751pbIBR/CSyWWs+JLrl66li+lM1j2JVDQowzxlUeo451DGDXOnDlD5Dw+7jcrnC855BmvCr8jGpzsa1P/E0VeWqKGwWGtEKVNiodj/4mTRXtgUDQChs4k7UWZ/py7ldsbv5WZ44ugjdj735MDzpFDffPgtQruJdO6vT7rVwYMQa+dCc7xCgVyJ57+65bH6yxj43/D7cxl3vaPAS/YEGfzo/Ess2iINV5To1/5VbMqrXMsV7ZYZJU1KPAZH4rrUNA/pK8MjlCcYAipoCYryaesw1wbD6SFb2+n7YfOZ6xexOb0RZv34Kprn743BtGwYsnZXbadfX3Yw8jAFGtbYGxxc1p08LF4bbbDdYdsvA7wyPUVm3GD70u9t9I9q8oAMUPbaVdV/oXKNwNUIkCCTDyAnd46e21yAyJQFFRn35+G5i97rXeZwuW+tcPYa0VesXNAXzguNviOKGEyEbYjkT56VehF14eRgNYHSjePNnl3L3CAJsMDhNhP072ng0sRvk0Gq0LeMHqRvRUj3/xQNwt3cyBiaEH0we28VZ4LMIse/O34T32sybiAlf1sCXHEzgUNU3wiqOt74zXdqc/pOpXC1UIffoyNUCAjiyfjFb8fehue6hbaPKjXgI4RwIVgBAmXeiC5J5ihGFZKnGAFxLF/WmpxJ6HPtuXTdM1D8m3iWfKPSQFKQPEdmSL/+WA7vItr9JuMKGWsi/7kTrzGLXDoPzvy/jjxq4gMi0E+87xnz7SS+p08EXbM7h32M5QOxRNk3py6TdrHd0kftelzravf4MDBcrCGWvJu4toejG9Ok75SffANw9hp3/6Osegr6L1hfx4YRXoCVUrkXbwFecx74on+P/VTUoewuekqaRrP5/N/1MpqAw=='.decode('base64').decode('zlib').split(';')]
while 1:
w=R();i=0
if'END'==w:break
f=0;l=len(w);g=set()
if G[l]:
while i<len(G[l]):
c=G[l][i];print c;sys.stdout.flush();g.add(c);x=R();i=2*i+2-(w==x);f+=w==x;w=x
if'_'not in x or f>5:i=0;break
if i>=len(G[l]):
for c in F[l]:
if c in g:continue
print c;sys.stdout.flush();x=R();f+=w==x;w=x
if'_'not in x or f>5:break
```
---
**Old entry**
Result:
```
score is 656, totalerr is 22962
```
It's not an average since this algorithm is deterministic, i.e., it always gives the same score for any shuffled list of words.
Here is my entry in Python 2.7; golfed (717 characters)
```
import sys
class S():
def __init__(s):
s.l=6
s.g=set()
s.p=''
F=[0,0,'onastifeybhmudgkprw','topenayridsubwglfhcmkxjv','elsatrodinphmcukwbfgyvjxzq','eatslroncihudpgmfbywvkqxjz','eastrinclodumphygbfvwkxjqz','etnocsiralupdmgyhfbvwkxqjz','enostciarldpmuygvhfbwxqkjz','eitnoasrclupmdyghfvbwxkjqz','einocstarlpumdygvbhfxwqkj','itacslnorepumdgyvfbhxkqw','intaoslecrupymdgfhvbqxjwz','nitaoerclsmudpygfvhbqxj','itneaorscmpdlfuvybh','ratdgfihosw',0,'ceimontalu']
s=S()
while 1:
c=raw_input()
if c=='END':sys.exit()
if '_' not in c:s=S();continue
if c==s.p:s.l-=1
if s.l==0:s=S();continue
s.p=c
for x in F[len(s.p)]:
if x not in s.g:
s.g.add(x)
print x
try:
sys.stdout.flush()
finally:
break
```
This uses similar idea as @m.buettner, storing an ordered list of letters following which the guesses will be made. But, this does not use frequency data directly, rather, it just tries almost every possible letter permutation and simulate the game, and finally taking the permutation that gives the best score.
This version is optimized using the top-9 letters, so for 2-letter and 3-letter words, the permutation is already the optimal one, in the class of algorithm where the information from previous input is ignored. I'm currently still running the code for top-10 letters, optimizing the 4-letter words (and also finding better solution for longer words).
---
**Invalid entry**
For my benchmarking, here is the code that uses the full decision tree, 11092 chars.
Score:
```
score is 2813, totalerr is 17539
```
Code:
```
import sys,re
R=raw_input
F=';;;topenayri;elsatrodin;eatslroncih;eastrinclodu;etnocsiralupd;enostciarldpmu;eitnoasrclupmdy;einocstarlpumdyg;itacslnorepumdgyv;intaoslecrupymdgfh;nitaoerclsmudpygfvh;itneaorscmpdlfuvybh;ratdgfihosw;;ceimontalu'.split(';')
G=[''.join('.'*int(c)if i%2 else c for i,c in enumerate(re.split(r'(\d+)',w)))if w else''for w in 'eJw1momWqyyzhm8pgENc/9UoNGILSoto3Fd/nsq3zt49pBNlKKreAfzf//afbZycWkJQs6l+U8n4/smbKubuV9VNRZ3m7B/VFmNSpw41qPN/48+xn8/PcpbpnE5Vzzu7Oitnf9RtnsllFzb1TEEtZpt+lDP2fWx5o7FpjiqYe1rUY0I/20V5M/eT6r0956LmPKvJ+N+oNhP72Qd+f/pf1cZpYmihT6r1pg3RqWS9OkygzZUhx+PhUttX1S7TL28d2kSjbP6hg9hnWjBq6dV669NYF5jf2cfkGW/sg2q3+aM+Sk2qfYzabFS7yX1t+r0zy3TzV+o31V581pmkmqaoZs5FZXNIbD45q6wITrsaVcuih2Nojz22m1LDpnS/ptxmGUUx6tOZ3DTvRzVn0xevSzvQqD0O3RofMj/5bn/2S5lCl1rz66WbI/HJb3lapXL7Ggq/f0vh1c3VQ370q+luLjTp+/Mtb7zz/37GcY/LscTj3GO0dTvc6VI5t9Of2alQylpysVvI956J6JbPw12qJKemJsUQw1m2k2Avkyqu2HRa5a1lZWMtLvHqDol4WxtYoKhe52HP80jrOQeacFuu3qltruSXXeZpt5Pa/MJf28znLKnzTznIlUgLk9mcVZZoO09/Zus3rR83zZOV93nztE65krnfpWUKc1AnuVZNnlcyVXI3TMtC3pAeG2sXGNvSP056XMjodiuhTLNVU0p0cBQyiaV2XO7MJIucyDrPS4LPAlnLFLZVTesvozvXPN0ntzAn5jMd9By55lSnzWrKN2O/l9Ke/X0u5NYtueWmKSSG/SRJu2WdGFLuT4Kw/neBpQwCcy1Nv65bKLmqcEU6CK5+U0yCG+iIIU1B5uXlZTbq3mYaWXvHWI2ahzYET+QfZve08dHfqc0h25m6ctobe0cVuT0H/x0eKRkInQt6vX95J6u79f3mKHvd20k/uj+MTqty66ryercTmXz39q7fsN0MqITvPJ5v8i+rk0ooSqmUb7tOq7K9LToz+pgiVX9IjRYq8DBFZkFNzWv5tsb8z87MBGjhL0p9NmrqjAdzfrc1pU3/htQ6FjGrhmKb/wJJrH0427lf++j0QfNM6Sg6KfV8g3Kua/VmfbpE6StdVUPDZGL7tG1YO127jtQ3i07Nrpq8Xnpw/qNupa6mv+aH2T5fHLhlFrcGWbSZClgV9GwFdSba9Hd3Sc/JP6oq7m4/jP2LM1fPUA+j/lH3F1cx55smCLuscH99Q+BlmroP5s3wyCZ95v7ZlPFDF1TNoCrxaALN5K5qcxvGfSv98sk8KmmTB+LCQijNVI0aytA8Q/coLd/9tB4Axez1DXiV1qva1t5V80qMSeDpCQCNYRwnsQajmPowXf/UZda2fTqzykXgTO77V1bm0U3/tM3aNMOigZu7eVc1vDxXMFfTOkGgHFRzSbglTTst/Xwe3TbnL9D1jyv0uj3KfLQZtr7rb6369hxer6Re6n2aV6/CDIaRY7Wj00Fdffe+5P3cKt6gn+cLb8dxLEc8yxLPevKvuGWJuysbVX7E4MIdlmULdrExunMHzWZ7ljltwTygVZltXWrdyh02u52Ls3OY9uJ3te1n3MJiy2nrRH27EObpzCqCRbCGD+Cmm47Dbtsat5rLHJ2zFVbZLLgR3Px46+3jVdyeNO+bykkY7QQEbf34fVlsoF0bqrtBnRn+Pc0cNjqj4qwgYXkswER9A7pxKnbaqrV5cqm66Mvq1VLnuEy83n6thULLM28rIOtpeAMk0z6BP2XfU2Bg1rl9okLh3FSW9R/8uzEs456bKi59CPa8t3BPPvzN/lI50FveVQbwLjI9+8s9KkT6Mdmf3Hn105LO09FbtVLGiwM+V961X+qdjS7T5tZNEY4p0ElYQcRakt8ooQRQy2wnn1Vq4jr5JUzq9tpmTZTUFlWK2prF+tmGrJ4SiQdQ8Jjy/rO7SBVXZv5ntfstK37fk8BmnfaJdQVdOio+bc8e8g4Bp1rbB23R7do4m3wNjwdCqjtXMu43RFZhrwmoWiTKinXhjrMKpJxudVfVM0V0lY2I3P1pt/aknNOW1kXnurOE+Zdk4bPLJiJy9TuI42TlVwE/33WnSmiNomK7qofm4M1Z3emvAOdu1gAiMFJZmz7O0a+P8ivg446jjZL6t6wzSVW6pb0ZCyjrUruZvHWp92mmwvNQEFbZoFS8mglbbRExeu8DU8vIiLspvi29m5Y1q0XtV8cyN9WosJdlQf5UAHQAaBAns1trdvb581P41deJuDMbOgMiuuO2V40KaLdLI3fmGpRFZWW9Gz5AU6XHvDyyL0dWThjDRcBACe6Ff52+9qeeZtv6jzLTmtpVm3mRxDqBmwDpCEKATLcy71PH5oTCBYFe6WYxK7j/H+Re+hUlB7u7R7neqilal2Z52qqJVXODY6rLGchB3DCid1dp5dYvdBZgQgaSPO/HDPsypz3p7gKDoKO9PL+wRr10M/yC2BM8nvWZiBdI9chEGvhxbvIlk7sRgP/U3RA+4cdtaOINgpuTOaSmZ2E6chroRgBe5mobxzrLJwlQprXB7Zq04sXHDEC9Es3Z66eB8i4Ww7zg49djWrPpPy033OryQbcEKGvUIWN97U6ZKw/mDwzT0fQ9sjI1jzZn9+qeBVb4A6ubm5Xpub/tzJ9WQxaEbfJdIU5j6imq80W+Gk3Kd502wO1y7Fscx+Mc+X8eZxxj2ctm93NZHGIx1vM53TEedj6AWbeNS+XTbS9xSwBPqqGGlGopNdhtH7O1Yw2Ba88YYynjMi5L3rYHqTmtZXMziQdPUAZlJpdrstvxbKB2dFvaxmAT4ur205SC2z1wC7DvdXTHbRF6ZfaT390TkLSOAe52DEsZLwdil9mVKdkpg6bbsitXrYuX2+1W4mSBlTRhLkCgZaWEXkDADNdZVQTbkTVuU3Ycv1924itRHLdNwOXM642V1qu0Hyx6eyrPAQ1wcZ5mpgui6t94+kRhnfa0v8kc3s67Pq6T4iIMbl/GtNh93ueCkHDPXtyY/Ro82iPXenqg2s1bnslD6CSJAwtJgDltMXukOp0rAqLKRp+2qE26NXDZYhNOzyIHynKpKiIBhNjaR7tJu4OpIyVYMEyY+m0zIppWGLmaE4CZwBPsQUAY36dUqoubml3VjzBDjZEyNbUrIKf/GomMgP/bD5CFOkKt7I3Xe540LQksmAmwOswNsaLQHF+ZhIN76lD1pI+ekp9GajJdwY/XJ+96npc5L8GDr3bWLPgMybnP7CZSS00fyObe8Xurwy8gNh/YbkVwLeVcJD7d7FV4rE6hc/Rr4pSmS1lo1dUJ8LB87mf9S2i9ye6XnyQSC+MBlhTsvq8ajYrWDwobkN8g+qP6f2prA1fAQpjBok1V4qRJW6o1iCIq00Nxb0yp8rstXZrxHM12lqpY+WJeaHBdnt6b0oIbzAYVv6sHfYa0qqG5mrlJ+oOonPVAM0M11zt20thbuOqqKRPlfRrVH8ysRyGS3P7pcKEAEDnpgf+nko2vfakJ0kFhIQlXr12oTamdX1csrS5mBaTv9Fwkd0Yawr4qodXvpp7okdkC+BAgAOjrElr/IY/aBWxFgtg6V2u8oYjIkHkF1C4ofjV7TxY000PzqU+zeMdPH6J55TVNOfwReya7AeNwIVWCo9MoXmBPPf3dsgZEEBrtix5qDxe0vAA8e0i9AL8YEbQpqYxjau4O1GsR2Kmt6tNj6YnIZ9dY+wd+02sWCC0GJPx0F/CvpisoIJ9e0QxFAL7/JZq6/zUo7RML5WVDpHZnvvQJg+jtRhJuaRC7kFS3qNewAWtRE4GnDULJN41GfDuRmkm3Is4HPL9ZbqfgvagGjBZifFr8pGe9pFYI/jW4SUAYz6aZzvB0LXx6o4Frr/MMvV2aBFC7MkSgR/cXlHJBaIvOnuZ/+vJQP1JcNaxMDg+FiYOh24JTxnogOzbuGpqKPO9mQX5UO/ZEz8373TytJpBQJPp8/Vefd36bLRq9Sh9VtzoS3Puis0W2JSC11ytL1iPU1bttLiGMcdvOfR/nsowjKj2WuI9xseceAdm81SNux1mPR5Q8ZIBCt2XJKPZsF4OuS7ae7jnsWW04Jo/RrhCPR0Uup11A9FzG8ZzjaEvZElyEsK3LgzinRsJq4zOjSFEvE7ThXLIPXn8le/cDYE72KAeGPlruA1DX82Ttxs+4L/uTxnyONtWd26KbQN4RXLZuh7TBKCfyfZ7xBtO+hx3PEeYlxzkrtMWBbUvqQLOGjeKP8xq1z6HazarT3hgJV4JFmgP9MR41OgyF3QP3qXN3Oxcc6c/inf8ExHM+g3c+1xhsPb6bIBPUdmoRkrNL+ZRvHA+kG8dzijmvowWeCfo0Qzo+RFeSGpnL7qnNNE/zmLEJ13P9XQm3IZQLe0K4f2nyj5N9GwF0l/FCy7YVTyWgF11GwNmraQTCjhaZn+MX8GLu4ESkLQjXwDDHgZ+prp7hNAwWNkiia7O+qX7adoj17Xr/CVxxF+BCDsUTrwEnxuc0H0quANvOg+Fpnl2uU8WanEd3YG1yhKsSPijDoCrlIFo3rcR1BXdUiTrFm+K6k767DLrpZa0jk3aTwzahaKcQLue0SyHadcfS84kOp6/2OieqvjZrTMhKd0e0ArIc4+P4HgGcbOInZX+nGCbx+bNo3KBhiXaaIWBHhN20RbFxi3cLyiTapfoIs218ZG810Qz2RV2VSiAg/umSx6zO+SkiubMW27Xseut31PPEN/AMLQzwog4bSUYcDdEo5UBvasiTDw8sCEmkRIK+oYQAbhXE0wEwBkVF9yJ9UbT7d//SnFDPrX7NadN+Ht8CRm/CNTO2oGRsU9WntO1BhqdP+qlAcjXC8LXo85+pwKs6IJIDWD3hO/jINbX/Z/qzxRHRbVYfjxmrhmS6dqTK+TnVvfg5TX+ZWFzN2UVkKm0mdf7l9qPzb0fW/JIY5xXhOryOeFFSSJxqAaL35myvLsXu8yaDotljw1KsCAu0OYurRJWI/doYqWJsGRbetLcRWUI7qBgzeVYQaYDv+oX2V0a5gYw7YE5Vryr5rgzBUPQbYes32Ov53POypyes5K6pd1HpRhvWNsT16h7Au61YtNsEdQHZ3a7e79h0xQywlx5kFZ7GyD5Ra5IhCczTPOdwiu7HBLS4MyV8x4sTJd+aC3Tn4yJBCASqAeujEWdU+xtuTEoP17AIel/NX06BO14fLRVUzacVCuhvTRf/TJMu3M1eu+GjwHD4lEGZS8eh5qZzhO7f2lzdBxoweAls1wfuakm9jG2Lb6TM3S13XNR0F1Z8aZDZvn2u7voscHF79eK+sxou3W1PwSbyZjE67ouui4JjMKJR7Iy+MGmmdHrxsBZzzw3UNVD07bDJvnefG2HGljsG5qmMGEosyUc36iRx+xbLdg0tJcX8zdOZp+1RTKo0vpvEjEGQ79KZf12L6hBd1FfIkXD8NV2LXBkGRETVOvbmLdvqMPQbvfA1OuNyYnS2DZuizm3cobHxjHYsy6axLajsqZQ9HkJl+9cPLRE3vNm5PUpE7D8gTHYRdrCF/4898QI2nbgFMHp0pxvdWAoaHL6rQP28xEQBg08YRoxGTLDeJMZJ0tdtUT3xmC1akYIP9olxTu4Qme8c5hoCtAV+splCplfncElp38lcRgLCT3w0An3jZpGCvLXUHZYtHm8HnAAmTz8Zq9wIR4UIlvsbLHaPf8hTC9xQNTjgOVI4sCekZax37lHR+ZAcCAocz7PshOXpwPlT95PVOBXZUamzi26MNswpAbmANW6quHPGrEwVbs1j8bMbr3GilTLZWPmawP2Q8QRjYlzPNNfFQq12RikmrGKdXNlhQLWL/XRX9EsWCdw20K859CFnNb5zJzlJit+oylPPXhfZ0Nu+2zAgb0nD1rmMILqMxdpjDdQeGuZLC/AbY+wcvufYvbiBHbKL+Jpf6gWljK0NRcecUtEXqgK+T9DSgLmBMHJu04TBRP9e+2PsGmc4ABIB/DFI8fP7YMx2gK40WQeH4wiXTl7f8HmYyzXZfYWur3EO+/w8+6X2RAd4nTQLgwRN8KufYP88PS5vLixhq6vLrsg2qHYOxwuvoCDSHNJ2WXGlGNlxJkObOfoY8/bMJQuHxXnHxqngAUCTs0tpcV4j1WG+UIJ0r1SXmwEyuQdJ1bYMaNQE++ImgwNzN4U8VkNRRhSoCm/EEPkTIYrH5Li/YzJOtjw6H34FIYMoJqKySwvvbK6r2WdYJO6IzScfWJaanw6jeCA17s4/sXSRBREOZKX1i4rphZSeCgvuf4URYInzWdrz7f64qirZ5p5DV6G3S4wy6HgpwLW0+W1xwqm3fv/0z9WktBsUoUYyq8Ract9nx5v5T/vX544/20+fUndrwgSTXOnazHZNf7Pst23xkw1a6LqbvAF7vFe/e2a19XAMRoqFy2nTqygAILUfPR1dWLtLtgMbAA2O+H/3SNDgb723EIX6joiJdKGgDgrz2HcdsF+PeiWxhoCeaR6ATRhkuFkE3Yq1xK30dRi2Bh8ECL5T7frLfLfiuj0TBKBS4zqr6f8iMX4O0bH4df2pEFqjIBOAwnwjCbHxplV9bO/+o4Yk9owGi+od8ApXGNrFSz5/sqv4T6EhIp6NuL92UkEOgTqo7ZZzmu6KNLlpCSF34VGS+DLiIpPYlByP1e5p0qNze4kP1Aggcqmp7bv0f4povKisV7kftRaufAgb89Z5H8QOqqd7E7oGcQS/HurVR/3GRr6q6eS4JDXMoYqDLl+CVkPW4t//9IuJDlU2D2Ug4qwIQ8toL35fQlrQ+fAy9T0M/9Tr9d0kW0Ycij3iuGF+1G6xP+i3cT/LcexMMTkwB5yGLNSI37DbdhzFjvawfTH7bCNcL4Zkjpik7WF97Z5P2KVUbkPDQiC0aflhx1HOl/oNETOpzW4d4I2MncoGbaRqC5VXsAxHtu0ODFnAxE3TFk6QAkWdyp5DsmrKdmSQro5xn8c5Xq6Mxc1lhLKyc4Y5tyJSEQF49qpS9Uo7HBvKt6Ax4RjlgXzxAhCSB51dxUO7vE8Jz/VltrnO2hUnJygJQV+A7YzNjr6eEWm8bQ5Ut9Msl8ApsCftIdNVcKOqwmDjzGg/LgBp5D88Mtk01TyNAS4u6SoA4fxAQoevuXZkPYVXBRj6k7YeoL3FUchgASmpy9KCKAfqGR99aJcRZBkb5uMhJ+/ByqYjNiQTyX0qnrxAIjtQ7wy1FfydESQhwQlyYgJTzwhmbkXeQjJatpLwLLgDfyo5eTey+TS72d2OcBB+vibyA1E8r6gm7GogjuliApp13yc+mLUcIV/KynYjXmeKSfA4kEkAAzZ/d79gJw5oSrKLtXp1/wsXNlijNT7+CfECwUvyERwN6XDz7+jHsZDh4Pcje9dX1yPAZyVbS18Pu5lLxBiY0x9mAOfQXOCCbEy9UVHH1IZZgicRqc3R1db40l+gDQi89r9DpI5KTF0y5x6E7BCxzwActin+6YhazVRD3Oqm8yo7aFA4GJvjI0kmaj9mnErR04UdY6nyrkHEzoPtgP+v8PCAsyApgYUWmytwComFNosxfRpcBMuJxcsI9a+ZJFwNa1zbf51ssgTZjKRJyDhgS8sVAX3ZT0pd7eLfWCNI/NFRz7ePuS2hNh86g3Xwl9D71P02r+7pAQ3THlTIAf6m5i0n4m+sGb/Ioou8gQZ6OWUFfXLbo6mTAaJMHu7h1P1Ha8yxOfuNeF/f7cFLToJ78RGD7NkRfSm89jF7L/jzDE8DL/vmkYdW9hYwlzxHef9ThIRmwsN7Kuy03s8C8MQAcyI7RY9i8N2nFRijvz4yLnGGCBPp6QK1PWirJUSqroA/HqNTpEiXzXfD+HvUobuhNjCBnCLAPwA84N1jaxhqC3O039nSY8d8UFe9nKsr09XybuVk+hFKqfote0c5tk33ulq4Rplm+Lxfr/q/5efct59N5PW+jT+g1xiPAwAsx09EnqDMZhtOymFM6YgAWEb+7pZLxoPhpBGluqnDUi2BHLIRuCMQ0zY9ZaScjn2f0WZT/vmxP6h0YNuOAGrL5ST7hM+6ZfvInGiphDTbpfWYKzglUhnZkNSoSGGD1Ue/54hwt8V4WyKCjHFmBPo8HblGAIoEyzYKmn6R1OE+5ohIZaUKinPvSVtvT+flqQ4Pw4PkHjxX5cAhxBkNvndz+prvSbaVZ8nwbcr9BPJMitCY4oFxhuYQzIlMiwJhKKeki5vST3p8dUROTEW5MuTgadqh8yb8CN7MTuCm7BNms2L9vnYVwy8wIflVGHmzZ4G4pC2AsWe4lcpl8h7mR8IxY9kH+5sRkGg4MOj4bhE588vNUGDsBXHdIdJLbW11I7zgiZZqEuJPdpM0BsBNe8dUHjcp3+ye2YGmH+jFCj5lJGQJVEJytOOIgwOMfdnFXdji0QZWg+LHhVKvQABTxGBk4Rj3l/+eyZf5qoXVjDACJdIxoH6T8lByGth2h0CgHgCudm/mmtFgyhopNCJSuopSC/kxfxJMAAa/IwsqRupSTh8VZUXMaAyfWUT8SnbLg0cigYCTQ8vW/gD1XINsgSGEL2T1/H1Cx5QG9ZtqE0w0MIZBwQkUA7msSQysCFom7ZcgmK7t9FN+5PwWlEQ943VVA8GiYWVtmV8WPn9aDzp8DSVL+dFX/qO9WdT3cTD2kPVFoN4Iy8lr2TO8qmlFsDH2Q4NF/X8Fr/IgGvX87/S17EBd8929GA6G+zFEgOtAKaYswmr4Uok8JqeOfjiaHhjTdzQtUMgscfCyy4GGf/t3J1sbFN4rNk9CGAugoOPknKpxeLgsYE5PuePubIzHpB0qdYcQV+yuLLtkDQOrXQCsSNWP+oC+UQM/rnazrzr3SrYM0AjIQ+h82IEj1gI4Av73oW+vnjG94RBNDIdr+Gga1E3P6qu77b9rSX5cvIO07NFur4FRdv+R5tCK8+kFt/93/izu+NmUPPE4/uxmGRGHegdrfsZ+VxOaz05juyUEofyzP6rdzKK+B5Nuw+iCrh4phHyZ7BSvw9lDNONhCGYyYm9G2DBMmDZKD5zDdFl4b7dlF+GXld8dDhXAnGY56/wB8QQwOwPcbYy96sX1GVyognNoX1uAL9vIM0NhImucmhLKzXkpjr2I1MsgzuHpN894/Zg9hYUxtUDlz8+c0zGXIthjIY9ixTq0FYEgkr4t/W7k6H6n5GorDwPu6krl/U1wLLUCAmIjJ1PAqM9iSv/DpP0rQ0oK3A6iCnCkQHmZ8h8t54LRlSO8OVQcdAX/Emns5yAQEF3y01+WvZBsrzxpyW2iUJtezoL02ryhvEceCriElmtkdFBYLwPPcpyytduQWkSW8QKtRc87ZpjC7HBMHyE44Xx+HOJQGa+SWsR7XdBhkTPPP4QGNhdBwVVYe8BfjjwJ4ZHiobFKpDfS2a/o7EO+Ueq5zo8rs4S8uFbKWn93AFvZK7ual4DW1f5HLNhxcZxDkK3ZpgSxKeo1gDrEvL96Sc/HUBECVMAtKxDlJFh8TuplVV5ZZeBeRejjVhgqQO3zaQCM+ql5+MhDAri3pjE77kiOf0zfHpSBRkTm9+utHyFvdZLneBhcR+tRrvmnjMfPyNqqEEcI1FMV0zwqGF1WlwVEL84/Quw/8jPkSCIe1R5Sd04nSFxOvIQ6dwLm99hLJl4/eGuE+g8YCJOLz2vmv3YPf2SyDxr1M2y92IkA1rU/knw+gPkvcvxwVU8ohOOYIYL4M1utv2qaUAKMIPeBOmkRwWTFzgTheU/Cvi6HKep/vtemrHU8JNuEhULrLqHI6cfRRI7YCe3R7PkiZPkre/5T1wJS9RAnSUdDEa5oBelyN7vOHFIzDTYIfG8Q4s0QuZdpIDKVaGEcqcMs/5p/Qr9okauLOkMXYQCNyWnxrFqwajhorvtyzEAawzlFMl6Ea+5zf+i2ts3noHklyRrNizRhsOAh7rg9/ocKU8uPwMzys/SW3/ZnV81PgGXxIcfPoQd4RjVTaRd5Sgs/+9MOoj+KHr4Phkbt985j8KZUPIYGo00cuGjWFW7J3Pc9jgfDCDAmT/1QBqg7eOfoT0LCLaF331q9sGu9RB63Jfvo8pCIjvOPiz85uWgvW5petswfSZdTmkCmzMjy2k896v5AG11fOSO7GRfuVP/9QoqxzAJ/Txk62UJ5Gu5gaqYbJKn8t0HZBGmLQcCiD0ygUqpsTejs+9Ik4ZtBy3FtQ7X1KrZSf32UXX/YED7spT7sqX7Abaenrd/bHysnFVIaJDF5oI0kePlJHUKgF4g+0L8O2XwMrTzmCqFl9xN/jqaRh2ddK1kJ0Pv4Y99DewyNPKN0RPyIgMp/G2z9IKfWiuV+/ve///0fiWqMOQ=='.decode('base64').decode('zlib').split(';')]
while 1:
w=R();i=0
if'END'==w:break
f=0;l=len(w);g=set()
if G[l]:
while i<len(G[l]):
c=G[l][i];print c;sys.stdout.flush();g.add(c);x=R();i=2*i+2-(w==x);f+=w==x;w=x
if'_'not in x or f>5:i=0;break
if i>=len(G[l]):
for c in F[l]:
if c in g:continue
print c;sys.stdout.flush();x=R();f+=w==x;w=x
if'_'not in x or f>5:break
```
[Answer]
# Perl, 1461 bytes, score=1412, totalerr=21050
```
$|++;
while(!eof) {
$l = $pg = '';
%d = "[eaitrnoslcdupmhygfbvwkxjqz]<[scpardetmfbilwhognuvjkyqz]a[tlrncsidbpgmyuvkfwxzhoj]b[leoairusytjvmb]c[oetahiulrkcysq]d[eiaourlyvdgsmfwjnhqt]e[rnaslcdtmxevpfgqiwyobhkzju]f[ieoauflrty]g[erhiaunolygsmtdb]h[eaoituyrnldmbcw]i[notsclvdagrmefbpzxkuq]j[uoea]k[einaslywftogd]l[eyialoutdfvskcmpbwnr]m[eaipombuysnftl]n[tgedcsaionvufkylmhjqwxp]o[nrumlstwpocvdgfbaikyexjh]p[reoaliptuhsymdbfw]q[u]r[eaiotymdsruncgvklpbfwh]s[teisuhpoacmlykwfqndbr]t[iearhoyultcmwnsfbpg]u[rnstliceampbgdfyok]v[eiaoyu]w[aiehonrlsdtkfy]x[pctiaehuy]y[esomatpcwbildgrn]z[eoaiy]"
=~ /(.?)\[(.*?)\]/g;
%r = ">[etynrldgshmkpcwfoabxui]a[retclmnphisfvwbudgoxykjz]b[aiumoerylbhgspt]c[ienaouscrxtlyh]d[neairoludhsywgpk]e[rtldsvcmnphgefibkuwyzjox]f[eifnoalrustdmkwp]g[niaeroudgykt]h[tcsgwpenrxado]i[trsldnacmfhvpugwbekoxyz]j[nbdeao]k[carnosilewu]l[aeliobpuctfsrdgnwhkym]m[oeiarumstdynlghbp]n[oieaurngwkhtmsldy]o[icrplthmsfnobdwvgejyuzak]p[msaoepuixrlynt]q[eisncd]r[eaotpuigcrbdfhwlys]s[iesaunorbydclptmkgw]t[ansicreuolthpfxbygkwmd]u[ostcqlrfdbpagnmjhixev]v[ieoanrdlb]w[oaesrtydnlkph]x[eiaon]y[ltradcnsheomfbgpkuvzxw]z[iae]"
=~ /(.?)\[(.*?)\]/g;
while (<>) {
chomp; last if !/_/ or /^END$/;
$l++ unless /$pg/;
last if $l>5;
s/$pg//g for values %d, values %r;
$_ = "<$_>";
my %s;
while (/([^_]?)_/g) {
$x = $d{$1} || $d{''};
$s = 180;
for (split //, $x ){ $s{$_} += $s; $s -= 100 / length $x }
}
while (/_([^_])/g) {
$x = $r{$1} || $d{''};
$s = 180;
for (split //, $x ) { $s{$_} += $s; $s -= 100 / length $x }
}
($pg) = sort { $s{$b} <=> $s{$a} } a..z;
print $pg, $/
}
}
```
(Note, it's 1461 bytes after removing quite a bit of optional whitespace. As printed, it's a hundred or so heavier, but still well under 2000.)
I tried a bunch of more "subtle" approaches, but this one ended up beating them all. The two data strings are simply ranked lists of the characters most likely to follow each character, and the characters most likely to precede each character (with digraphs that don't occur in the wordlist not represented at all). `<` and `>` are used to represent the beginning and end of the word. As an example, `"w[aiehonrlsdtkfy]"` means that "wa" is more common than "wi" is more common than "we" etc. `%d`, the forward mapping, includes a global ranking, stored as `$d{''}`. It's used for places where there are two unknowns in a row, or where all the digraphs in the wordlist are exhausted (so we must be dealing with a non-wordlist word).
For every unknown position in the word, it looks at the preceding character, gives each possible following character a score, starting at 180 for the top-ranked, and decreasing to 80 at the end of the list; then the same thing is done for the following character. All the scores for all characters are added up, and the one with the highest score is selected.
After a letter is guessed, it's removed directly from the ranking tables, so it can't be guessed again (until we start a new word and re-initialize the tables).
**Update:** gained a bunch of points by fixing a bug (we weren't removing letters from the reverse table) and changing the way the points drop off as we go down the list.
[Answer]
# Python: 2046 bytes, score=1365
score is 1365, totalerr is 21343
```
import sys
from math import factorial as f
z=lambda r,x:f(r+x)/f(r)/f(x)
d='eJxtVouWwygI/dYEV03rg5Fg63z9Apo+ZtczZ5JU5HG5gP+0cyvHlhjORrI6lQpnZoq0Z8o46GO5\noJ/YE8XwpBw6UXGEcLPdM2MacpBzO8kVcr1TSttJxx5/Rg/u7h5EDJlI/jgBiRkCO1sDuWUETVci\nxkxM+junUWBQF+OeSgxUxg+B+ExnbB2hgJxp8cR5fA/dT6U7q7+Ovhf8/ahIEWrGQyR3+3X8ORKY\nnvI48vw88jClT4IDh+fh4mMQ2Nn8cWyfxpkmspj73EXYD9sfxzkwP6GKYP7ya3lQ5ZgsD30lIM6n\nZKZPkYqQzyV9bkeGgbGKeMyfUcxj96UUHOoP/IwrngrDIHtswBqFQ+YTDpftHeshJKkggNNWXd7U\nU5yw4me818L5KDjD/Lv8jyC6XldyulpFzvswm4T6faiQy0K6JmTKRyEYgZ7hrWm+VjezxuH1tcPK\nBLA8sNq7f/mHXkV4NDfeFG/0Fgp3PZErqM4s+WEXKb+ZhBQqXrH6PdE+E0SjUGWJzwfNei8KwM2L\nDdObnZ+WEt+IGcQxc73QAcYSU6q+V2XPF3NxKnhHMb0Nwj2Tc2lcGR4XMGFxL3tjoRQVe5gBL/rA\nqHpaQZqizuyoMGv5MGfEx4Q6HNMhV/nTh0WF+js35a8RZHAGeqiyfTxY2kSW4yN40NK3wvTLkq7I\nk/4QVcJedkvanSsdBTPEnjEstrUs2FHyCO3Dj14HXeUNgmQS1wI4n9YhaT1egUmATRwABYwkd4tQ\ncCTWdqPiK5ssve67F1R6mUjznIMJJRZnv3/X8bXScmHZYiiTngWOIJCnHCjG+jZBv23gXsdOWpkX\n88IRd4FSMRW+CElyPYoEOMbes+IWG4Xo60PSaNrw6nZXjPMJPks+9lgHR41S+KutQOh6ViiiWdSL\nzI1etbyiz/3qJd8bK49tmakpe/F81vL0vUmUt7+tmDBtCtnCeG5v2cDy35IZTdtKpmQJh0yCdmmM\nWgAUcZ5crBA0nnY2bd32iySehf8Om0vHwPrMY78sPL97WZQKTtZDU0Mz64SRDYTJyo6B4qiojsog\nddZ9tH/vNKwtmUYVi0F4xFOtvFnFcNmSdBYZJenOacfqNc3mcJCJM+N34wUMG06oQmuOHH1BU+NU\nvXrSIc3asfhunl5kngmyCZ6pJ4lFN8CzTm33B24TVm06WoMVFoUcP7dfNaL/f3arAp6Ta0OSsgX8\nPuAsL8/5saVdRhS5hTlkG0nJhyal7kJXlrOATf5BG2j3xd4/EySk1aTElqLB3tOupqNr4aHd+wdq\nSNz0uhJA7iFkk1Gqp0mnG8k6gcyZq74XDbRp6ZxruSfLlx9Q1xZhHNq8pYgiti2AjHyItUme1fRO\n3S1l/EzGt/9b60aQ94vt8b/79vwoML/q15lP0sZlUDw3bQvGMJkjXfKtPT3Ny9VSYXix0E1dyf50\nYdbbJteynCo8esQcfqeUrTKklKQAuXSy3ndC+RMAvqVdXQH79Yxhee12LnBXr884xPqQtr8i1jvj\n4o4aWFNbZsxNPH2GWSX1IX1IwqlFDqILelFIesMRdwQEH2TqSdcq0yHWuxSpiakW5J6UJB2OJro3\nvULus01HDncbYPWRYORC/wJ6k9G1\n'.decode('base64').decode('zip')
D=len(d)
R=raw_input
def G(c):print c;sys.stdout.flush()
def P(w):
if'END'==w:exit()
i,l,X=0,'e',6
r=x=''
while 1:
if l not in r+x:
G(l);w=R()
if l in w:r+=l
else:x+=l;X-=1
if not(X and'_'in w):return
if l in w:j=1
else:j=z(12-len(r),X)
i=(i+j)%D;l=d[i]
while 1:P(R())
```
Much of the code borrows from [nneonneo's python submission](https://codegolf.stackexchange.com/a/25624/3787) (without which I wouldn't have got this under the 2048 byte limit). Originally I thought this should score about 200 more, but I discovered an error in my data string creation tool. Now that's fixed my score is a much more reasonable 1365.
Rather than creating binary trees based on length, I created a single binary tree to hold the frequency information. The tree isn't uniform depth, as there's no point storing frequency information for anything deeper than six incorrect guesses (but the correct guesses could in theory be twelve deep for "considerably" and "uncomfortable"). This awkwardly shaped tree is navigated by the factorial code (actually using the [combination](http://en.wikipedia.org/wiki/Combination) function). In order to make the data string more compressable I padded all unused indexes with 's'.
I used a script to calculate good strings to store as d, and if someone can golf a few more characters out of the rest of the script, then here are some replacements that should result in better scores. The top row is the string encoded in the program above.
```
score | length of encoded string | actual string
1365 | 1646 | ertanialuctrssssvsnoctmushsbmsmpyssssssssssssdgyssspvlshgxsmgvssndspcjssssstmplyushumrtsdnsdvvsllatsibhqyvgdkdwssucmssmssulcsmusscsssssogsdssssssspsssstlsupmsusgsdsulyncysvyssfsnhgsnyqscalusthrvpcncpssrhtpsssspsbgvfsssssobuysssdssssssssssssssscsssssssssssscsssopshcompidssbsssssysssssssssssssssgusxsssimssssssimydssssxscipyfuydhwyscbssssmsssssssssssbssdsssusssssvspmvmssssspcbissssbyitypmxcossdmcssssssssssssyssssssosvssssfcvsssssdghsssssdsmpvysssssopcmtysssssstaimcyphocvshmsysssssssssshssssskssssssocdphsssuxhssssssiocyfsssswacubsssdpuutcidmsssdppoitanoclussaodmacssspdssssspmssssssssssssssssssspssssssnpbissssssssssssssssssssfqssgssssssfdssssssvbssspumbydmsssspbsssigsssdmgysrsdvminscygsxgssssssssssgsssssodbsssssugssssodbssbcssmsssscumsspomssssfssssssssppfssbcuyrdympysssssssrsssssfsssssgkmsssmocugssmcosudhsmdssssssssspsgopssssspssfblsbvssssssynsouqssfgusssvnisssjfpysfssssmdfssssrslujsuucpombssssnsicussssopssscssmossbsdsssssssssssspssssmdsfssssssssssssfsgdhwdssssdlyssksssssysgsssssogsusssssmfssusslsuufcpyssssvyssssscyodsssmsspusssssdpssssusslubuysuumppwsssgssgidsssssdoussssssssssssspdssssozsssssdssdrscmcdomsssgospdiwudspmidsygfcsulcuysssfssssusssssshucssssschgfcsssschbmsssskuosinpmchvmpgmssssssrmucpslfpcrsssssssssssvoyssscssssscopslsspgcdflssssssrucmfgssslcpruysclysssblsgsssssscilugsdslsssvssssssupvlysssssssssssssosssscssssslgsssssdcvysssspndcssssmcsssssssssssssssssssslsssssrugssssssucnmsssscncigdpslmgshhosssssossssszrypboybsyfssmdssssssgihbudsospdcusmosmoindflyybvmfcsshrsghfowsdphossspscssssssgsssssscgssssscfmspmbhoyuhssuplsbhsssvnitocnusmdcucfmjssspssssssssssssomvsshsssssspssssssssssssssussssrgssssssolmfbsydmssssdsssssrdpsjdssssssssssssssssplasssmyssssssdsssssamlssssfssssssssssssssmpdmsssflsssssdslpyhgsrdssssssshssdlshpssssfsrsssssshrsxssssmlavssdlsnpruupysdprdliypoxmybssssssssxpmsssssssssssshguslsyssslrpflsssdbmsrcdspvsssypsamssmhsblssfssdbssssmsssssfdasssalpmsssamsshglysusssshglyspdsssunalcosydslkulbpofmdssxssssgsgufsssssdyssssdssssusmysspmdssvmsssssivsssssmpohsssshgopsssssinocdusyspvssssvssssssssssrgyssspmsvlmsrvssscfulyusdfssssssssssssssssssrpssspssrgoyssssgmhssssssssssssvssssssupssssqbvysssussysssapsuoscpmhssssssssssssdsrsssxssssssalbhmssdmsssssscmphssslfgrmchdgvdsosucdssfwsacdhsmpvvmsssssssssssplslssshrlhssmssvlbyssshdrgwkmssqcoglurspvlgcllascyphoudsrpusylfgsssspblyssssssbssssssomsslussrmvlussssfycossssssosphyssrscgshpragcscbchoralpbyssbsvdyssssssuxlssdlsssssssssssssssssssssdsssussmbdsssssamhssssssssssssssdsssssssdpssssssssssfsgsssssdlussslsusopxasmdspmssscpovdussvyslssmssussssssdmssssuspdlsssmftdglasssmalatmlocwvhpmgzssssussssssnyshsmlsunvsvlysstcnssssssssssssssspsssussssssdoyssssssfysssssshgpssssssdbunckgsssthylssycsubdssssssndsvsssssslyssugssssowssjuspxgusssshowcnuysloncsupdgfdsslsstacnslusfghwdlsbnsssspsussbyscsubssssslcghslsvddsmhssssjulynbyssssphugkousssowlcymns
1381 | 1662 | ertaniocvsplttushtpyutsudwbvumgdlatcpisppmgdsyusuqphplgpmypppplppppppuhslypppppppyvpppppsulcspommdbpppppppppppppppppppppnjpppppsgppppydncmpppppfsnhgpmuqycalinscyvpcncpppppspppppppppppppppppppposbpgpppisbhpmpgxyppppppodbdppppupppppvfpppppmulympppbusoybppfscipypslhppodbpdppppppffpppppppopfppppuppppypppmppppppppcbipppppyityfcvppppdmcpppppppppuvppppppppxbppppppocmxppldgmpyppppsmpobuppppopcmtypgpppstaimcyphpchmvxpppppplppppphpgpppkppppppocdphpppuxhpppppgiophyppppwacubpsdvmuutcivappubppoitanocluspaddmacopfpdgpppplvmpppppppppppppppppppuypppplpppppppgupppppppppppppbfqppsgpppppugpppppppvbbcpdmppppcumppbgpppppppppppprpppppmpppyppppppppppppppppppppppppppygnpppppppppppppppppppvpsfplmpyppppppppppppppbrpppxrdyppppppppppppppppppppppppppppppvyupsmpppppppppppppppcyppppcuypppppppsbpumpppspppfpsuqpgkmpponmocucuddpppcfujppmdcmcoprslujpuuppppppppbgppupppppppppppnupppfblsonppppppnsicupphbmdppppppppppppppfppppwdppppdlyppkppppppppppyppdspupdpppmfpbvpplsuppppyppgpppppogppghpppdspppuppgohdpspsdhpslubyppcumpppugppypppppufcpppvypppppyodpppppwppppppgidpppppdroupppppppppppppppppgozpppygdpppppcmcdompspfospdiwpuupmidpcppgfcpppppppppppgupppppucuhpppplchdigprmhchbmppcruuosinpmchvmpgmppdppppppppplppppplflpppppprucmfgppplcpruypbdspocgdpppppppppppppppkppblplfocdpppgxpppyppppppppppogppppcvpppplyupvlysgypppppcilybppplpcppppplgpppppdcvypppppndcrugomcpppppppppppppppppppslmphsoocdmsopppucnrypboxncigdpplmgppppppppouppppmzppppppvppppomybsdpuvgirsghfowpdcuppdppvindflyppvmfchbugdppfpcfoypgppoyuhsphopscxppppmpgoncusmpsspmbhppsupsuplbhppppvnitoclaspdcucyffqpppppppuppppppprjdpppppppomvppppppppdppppprdpppppppphsppppppmuppbpppppmyppuppsdpgsppfppolmfbppddmpppppppppmpppvppflsupppxpruyppppppppppppppppppppppppppmppppppspppppppuslpppdmlrshyppypppppmppppyhppppspafspppchpppppumpppppppmpppppppslpybpdlycsrcupsducymliypuyvybppppppppppppnpppmppdppmppppudnyoxmpmhglyppppuahglyfdapppunalcosyddlkulpuppmdpusppppvpppppppppppppppppppppbpofpppgufpppppppppppppppppppphpppppyppmdpmvpppppppsdypppsppdpprvpsvgrdgysgmrpppmpmppppxmpohpppphgopppqupinocdushppvscfurgoyfvlmfppppppmpgsppppyppppppmpxdpppbusmyppmsyypppppposcpmhsppppppppplypprpppvpppadppppppppdmppppppcmphhupgfgrmchppsalosucddpfwschdswppppxppppppddvgppluvmppprdgacdlpprvgxlfpprgwkpppphgglursplubcllascyphohmdfylppgfpcosulxpgplgpppbpbhmlvumppppvbrmyppufpyrypdpppppdosphyppgppfshpragcpvmchoralpbyppbpvdyppdplupppppmpppppdfpppppplpbypmppppppmbdpppppppppppppppppppppuppppplappppvllyppppamhspppppppppppppppppspplpppppsppppppfsgpppppdlupmppppsospxappppxuuppppppmmftpvplppppuvyppppumqppppmcpovudppddglanyppppatmlocsvotcnspppppxmgzpppppdlpppppplgpyvmwgpppbfyppphpphpgpppunpdbusvlypppthuglypncfbsppgpppwspuppppppdoypppppppppppfudppwgsdjupppcnuyppppsyupdfnpsoumytacnslupgghwdlpvlpsdpppppyoypppppxpppppphowlppypsoncvboculynbcsubpphuglcghpppplcymnpppdjdvalutcrspgppknmcpypowodppppguppppppbchgxpsysppoctmduppppsmpnryppppkppsyrhppppupprtsdnsuqlwp
1382 | 1796 | ertaniocvsluuuuuluouuuuflbvuuuurucmfguuulcpruyubuuuuuudsuuuuupgohcuuuygnuuuuuuuuuuuuuuuuuuuuuuuuuuuuouuuuuuuuuuuuuuuuuuuuyuuuuuybuuuuudmuuuuuuuuuuuuuouuuuusmuuuuuruguuuuosuuuuudmuuuuuuuuuuuusbpumuuusohuuupmrypblouoyfuuucnuuuuucfuuouupcnmoulonbuvuuuuuuybsduuusprsghuuuvqhopsuuuuuusonpuufownsicuudhbluvbuuuuuoyhuuuuuysfyuuuumpconcusmlxfmumcuuuuuuuuuuduuumuuuuuuuuuuuuuupuguuuuuoguuuuguuulrvmuuuuuuuuuuuuujvyuuduycyordpumuuuuguuuuuuuuuuuububuuusguuupwsduuuugidvbuuudouuuusdvmuugumyuuuuuufluuuuuopruyuuucdomuuuguspdiwuuupmiduumuuuuuusuuuuuuuusllpuuulrshcuuuuchidguuuuchbmuuuuuuosinpmchvmpgmuuuuuupydcumuuuslpybuugfvsrcdbuuccymcdyuuuuuuuuucgduuuuuuuuuuuuumpvuubluudncduuunhglyuguuuuhglyryguuuunalcosydulyupvuuumduuuuuuuuuuvuguuuuupvuuuuudcvkmuuupndcuuuumcuuduuuhmuuuulmpyuuduluuuuxucpmuuuuvucnmucyuxncimoculmgdurdgyuurpuuuufbuuuuugdpuuuumduuguzpgihbudvufpdcuuuurgoindflgkuvmfcpyuuuuuuuuuyuuymuuuucubvyuugsusyuuugsuuoscpmspmhbuuufusuplbhuuruvnitoclaumdcudmfuuuupcmphudugfgrmchuuuduosucduyfwschdswuuuuuuuuuspuuuuuulufcuuvrgdhuuuuprvuuuuuurgwkuuuuhgglurspyxpcllascyphoudsrpguusyguuuuuuuhguuuuubsuuuuupduuuuufmryuuuuuurypdulcuduosphypmuudfshprgfuucychoralpbyuuspadvyuuuuuuyuuuuubuuuumuuuuuuuuufsuuuuuuuuuuuuuuuuuuuukuuyuulfoyuuuuuuuuuuuuumuuuucmpuuucopuuuupgcuuuuuuuuauuuufdausuualpmuulduuuuusguuuuuuciluguuuluuuuuuuuxuumftuuuuuuuuuyuuuugsuuuuuuuuuuuuuuduuunusmyuupunvtymuyutcnsuuuuuuuumdsuuusvguuuusgmhuuymxuuuufyuuuuuuhpguuuuuqdbunckvlmuthugscfulfbsdfucpuwsuuuuuuuuuuyulyuuuuuuuuuuuuhwguuuuuuucnuyuuovuuupdfnuupluutacnsluuushwdaduuuuuuuluuuuyuuuuuuuhuuuuuxuuuuuualbhmuudvlynbuuuuuuhuguyuuuuudlcymnuvmuuuualcautlrsxgxnmcpyuhsuuuuuomduuuudsuuuuulhuuysuualvbyfughcossulquvdyluntryuuuufurtsdbfluuuomutsdyuxuuuvcyyrhtmuluguytnguuuuuuuuuuuuuuuuuuuushuuuudhpuuuufuuuuuuuuuuuuuuuuuuuumudluumbdupsluuuuliypoxmybuuuuuuuuuplauuuuvluuuuuuamhsuuuuuuuuuuuuuuuuuuuuluvuuuuuuuuuufsguuuuudluuuuuuusopxadbpuluuuuuuuuuuuuuuulubpofuuugufudmuuuuuupdluuuualdglahuuuhoatmlovavopmgzsdypuuuuuuuuuuuuuuuuuuuuuuuuuuivuuuuumpohuuuuhgopcuuuuinocdusyupvuuuucwhuuuguuuuuuuuuuuuuuuuuuuuuuuuuuufuduuuusdjuuuuuuuuuuuuuuuuspuuuuuuuucopuuuuguuuuuuulpsuuuuupypuuuuuuuuuuuuuuuuuuupsuuuuubocsuuuucsubuuuuulcghuyuuddvghuuuuuuuuuuuuuuuuuuklfuuuuowoduuuugusuuuubbchgxmpvuupoctmpuuuuusmpkuuuuuuuuuuuuuuuuusduuuuuusqulyuuusuquvuuuhltmpyuuuydtsubqlyuugdlatisbhdpmgdsuyuuuuuuuuuuuuuuuuuuuuudflyuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuslpbvfuuuuyuuuuuuuuuuuvuuuguvluudoupspumcopduuuuuuuuuuuuuuuuuuuumuuuydusuvydcuxpuuucoguuuuuuuumuuuuumuuuuulumquuuhgcpovdxyuuuuuubsouyuuuuscipyfuuvguuuuuuusuuuuuuuuuuuuubuuuuumuuuuuuuupmuuuuuuupcbhluuuuyityfcvuuuudmcuuuuuuuuuuusvluuuuuxbdoyuupocmxuuudghuuuuuusmpobuuvuuopcmsyuuuuustaimcythmlhmvuuuuuuuuuuuuuhuupuukuuuuuuocdphuuuuxhuuuuonuidouuuuuwacubuuupjgitcivauuudppoitanoclusuaddmacoufpduuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuusofquuuuuucvsyuuuuuuuuuuuuuuuuumyuuuupbspduuuhwkuuuurupcpmuuuusmvuuuuuuuuuuuuuuuuuuuujuuuuuysuuuuuususmcuuvuulcssfuucuuuuuuuuuuuuuuuubpuuudrdyuuuusguruuuuncyuhuuufsnhguuqyucalinscyvpcncvluuugpuuuupuumuuuuuuuuuuuuucugusuufuusuquuufguuuuodbuujfuuufuuuodmdfuuuurslujuuupbuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuopfuuuuuuuuumduuuuuuuuuuuuuufuuuuwduuuudlyuukuuuuuuuuuuuuvuuuuuuuuumfuuuuulsuuuupyumpyuuuuuuuuuuuuuuuuupuuuuuudpsuuuuuslubyuuuumpuuuuuuuuuuuguuuuuuuuuuuuuuuuuuuuuuuuuugouuuuuuuudruuuuuuuuuuuuuuuupubcuuumcygfcuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuugfcuuuuuuuuuuuuuuuuuuouuuuuuuduuuuuurmucpupupcrupuuuuuuuuu
1388 | 1800 | ertanioclcpruyuuuuuuuuuuuuuuuuouugohucmfguuulbvuuuuuuygnuuuuuuuuuuduouuuuuuuuuuuuuuuuuuuuyuuuuuybuuuuvsuuuuuuuuuuuuuuouuubusmuuuuurugupmuoduuuuuuuuuuuuuuuuuuuuhsouuuusouuuuuurpsumbuuyfuuuuuuuuuuuuuuonuuuusvuuuuuycfuuuucybsonuduhrsghobdvqhodmouuyuuvuuuuufwduuupslhsonpuuuuunscifyohbuvsyfuuubuuooncusmpuuumucuuuuuuuuuuuuuuuuuuuuuuuulxuuuuuuunuuuuuuuuuuumudrjduuyoduuuuuuhouuuuupombugrduplvuyuufuuogiuuuuuubuuumumyuuuuusduuugufuuuuuupwuuuubugidsguumpuuuuufluuuvbuprdmuuuusdvmuxgduuuuuuucdomuuuuyspdiospupmimdusluuuuulrshyzuuuuucuuguuhucuuuuuchlpuuucuchbmuumuuuosinpmchvmpgslpybuumuusrcduuugchmcdbuucumuumuuuupyducvuuufluucgduuuuuudnyuuuuuhglybluuuuhglyrupvuuunalcosydulkuluuuhcduuulmupvlyuuuuuuuuuuuuuuuuuucuuuuulguuuupdcvyuuuupndcuuuumcuvyuuuxuuuupmuuuuuuulucyuuuccuyuurvucmnrdgyxncigdpfumguugkmuuuumocuguzduuuupvuuuuumrpuuuuugirhbududpdcufbluuuindflyuuvmfcoyuuuuuduuuuuumpyuuucuuoscpgsuuuuuugsuuuuuumspmbmhuufusuplbhudmuvnitoclaumdcucgrmchupfhuosucduufwschdswuuumpduuuuurgduuuluuuuudgrdhuuuuprvuuuusurgwkspuuhuglurspgyucllascyphoudsrpuuuuuguuuuuuuuvuuuusbuuuhguomuxufcurmyuuuuuurypduuuuudosphypduuufshpragcycycporalpbyuubgvdyuuuudsuuufsspamuuubuuumuuuuuuuuuuufuuyhuuuuuuuuuuuuuuuuuuuuuukuuuuuuuyuuuuuuuuuuuuvuuuuulfoyuuumpuuuuuuuuuuuuucsuuuucuaopuupxauuuualpmuuufduuuuuuuuuuuuugcumftusguuuuuuciluguuuluuuuuuuuuyuugsxunyuuuuuuunvtyuuuutcnsuupmdsuduuuuuuuuuuusmyuumuuyuusvgufyusgmhuhpmxuuuuudbunckguuuthuglquyufbsvlmuuuwsscfulyuydfuuuuuuuuuuuuuuuuuwguuuuuuucnuyuuuuuuupdfnuuuluutacnsluuughwdluuuuuuuuuuuuvypamovuuuuuuuuuuuuuuusmhduuuuulyhouuualbhuguxuuunbulcymnuuusyumalutcrsuuuvmnmcpyuacdlhsuxgxuuuudvguuuugvysuuuuulnrgsuulvonhcumdyflssyrhcosulubrtsdnquuuwlputsdyuuuyuucyyrhtmuuuuxuunguuuuuuuuuuguuuuuuuuuuuuuuuuuuuuuuuuuuuuuuduuuuuuuuuuuuuuuuuhpuuuuuuuumuuuuuumbduuuuuuuuudluuuuuupsluuuuliypoxmybvluuuuuuamhsuuuuuuuuuuuuuuuuuuuuluuuuulmfbuuufsguuvuudluuuuuuusopxauupuldbuuuusuuuuuuuuluuuuuuuuuuuudmuuubpopdlugufaldglafdmualatmlocwvhpmgzuyuuuuuuvushuuhusdypuuufgyuupuuuuuuuuuuuuuuuuuivuuuuumpohuuuuhgopuuuuuinocdusyupvuuuuuuuuuuuuuuuufduuuuguuuuuusdjuuuuuuuuuuuuuuuuuuuuuuuuuucopuuusguuuuuuulpsuuuuupyuupuuuuuuuuuuuuupuuuyuuuuuubocsuuuucpsuuuuuulcghuuuusdvguuuuuuuuuuuuuuuuuuukowduuuowuuuuuugulfuuuubchgxuuuuupoctmuduuuusmpksuuuuubuuuuuuuuuuupuuuuuusqulyuuusuquuuuuhltmpyuuuydtsulpmuuugdlatisbhddkgdsypblvmpuuuuuuuuuuuuuuuuuuuluuuuupmuuuuudflyuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuvfuuuuuuuuuuuuuuuuuuuuguuuuudouuuuumcopduuuuuuuuspuuuuuuuuuuuuuuyduuuuudcuuumuucogusuvyuuuxpuuuuuuuuuuuuuumuuhuumuuuxylumquubsocpovduscipyfuuvguuuuuuyuuuuuuuuuuuuuubusuuuuuuuuuuuupmuuuuumupcbiuuuuuyityfcvuuuhdmcuusvlyuuuuuuuuuuuuuxbuuuuupocmuuuudghdoyuuusmpobuuuuuopcmtyuuuuustaimcyphshhmvuuusoumyuuulyhuuvuukuuulyuocdphuuhuxhuuupxuiophyhowlwacuboncvmuutcivauuudppoitanoclusuaddmacoufpduuwuuuuuuuuuuuuuuuuusyuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuufquuuuuuuuuuuuuuuuspduuuuushuuuuluupbuuuuuuuuuuuygruuuvpmuuuymgvuuuuupcjuuuuusduuuuuuuuuuuuuuuuuuuumuuuuuuyvuuusfusucmuuuuuulcspuuucbruuuurdyuuuuuuuuuuuuunyuuuuusguuuuuuncyuuusmfsnhguuqyucalinscyppcncpuuumupuuuuuuuuusuuuuusuquuufgguuuuuuuujfuuufuuuuumdfuuuurslujuuupuuodbuuuuuuuuuuuuuuuuuuuuuuuuuuuuodbuuuuuuuuuuuuumduuopfuuuuuuuuufuuuuwduuuudlyuukuuuuuuuuuuuuuuuuuuuuuumfuuuuvlsuuuupyuuuuuuuuuuuuuuuuumpyupuuuuuudpsuuuuuslubyuuuumpuuuuuuuuuuuuuuuuuuuuuuuuuuuguuuuuuuuuuuuuuuuuuuudruuuugouuuuuuuuuuuuuuuuuuuygfcuuupubcuuumcouuuuuuuuuuuuuuuuuugfcuuuuuuuuuuuuuuuuuuuuuuuuuuduuuuuurmpucuuupcruuuuuuuuuuuuuuuuupuuuuuuuuuluuuuuufluuuuuur
1392 | 1848 | ertaniocvslogppppppppppppppppppppppppppvypppppcyopmppmppppppppppdppppuprvppuprdgyppwrpppppgidpppppdouppppppppppppmppppppozpppppdrgoypcdcmopfpmppspdiwpdhdmidfpmpopppkbvypppspsyupppppposcpmhppchuppppppchbrmpmppuosinpmchvmpdmlpppppcmphpppgfgrmchpppdposucdpplwschpslhbppppfpcgdppppyplpppppprdgppblpprvcdpppprgwkpppphgglurspgypcllascyphoupsrvlypppgppppppppppvpppbppplgcolmpdcvyrmyppndcurypmlvmppdosphypppppfshprauypcyccoralpbyucnmvdypxncigdpblmgpsgpdppppppmpppzpvbpppdmppppsdvmpxgfgihbudppppdcuplppppindflyppvmfgvppppdppppppppgpppppcppppppgspppslpgsppppppmspmbhpppfpsuplbhppppvnitoclaumdcufmtppppppdpcumppppppppppppugpvpdppppnvtypmppmnybcppsptcnsppppppppvppvpppppppppppppphypppgupfyplmpyphpgppppppdbunckghgxthuglyycpfbsppppppwspppppppppppppvyppppppppppppwgpppppcycnsucuypppupdfnpppppptacnslupsphwdlpppymocugppgkyppppyhppppppuppppampsmhpppppflynbppppuyhugpppppppplcymnpppmpppalutcrspppppnmcpypfbppppppppppfdappppalpmyspxppppnryppppdsnhcmappppssyrhpppxppprtsdnapppwpyutsdgspppppcyyrhtmppdypppusmypppmdspvmghppupppppufcppdpppppsvgppppsgmhpppmxppppppppppppppupppppqupppppvlmgppppscfulyupdfppppppsppppppdpppppppppppppppppppplcppppgfpppppudvppppsbppppppppppppppppppppadpppppppppppppppppppphuppppxspppppalbhmppdvppppppkppppplfyoppppdvgppppvmpppppcacdlpcoxgxpppgcppppppppppppppplhppppplvbylypmdylsgpgfpcocisulxpllgpppfpppppvppppppppppppppppppppgppppppppppppppppppppppppppppppppppppppppppppppdpppppppppppppppppppppppppppmppppppmbdpppphpppppppppppppppppppppplappppvlppppamhspppppppppppppppppppplppppppppppppfsgppgppdlulugpppsopxapppplppppppppppppppplpppppuppppppdmpppppppdlpphoaldglappppalatmlocwpvpmgzpomvppvppppppphppppppppppppphupppppolmfbppdmpppppppppppppppppppppppppppppppgpppppppppppppppppppppppppppfudppppsdjuppppppdmpppppppppppppppppcopppppgpshpppplpuslppppypppppppppppppppppppphpppppphdlppppyliypoxmpblcowkdgpppppppppppppppppppppppppppppcshgpppppdguppvppppchgxppppppoctmppdbppsmusppppppppppppppppppdupppppsbpofpppsdylpppphlduymppppptsubqlypppplatisbgupmgdsusdypppfyvpypppppppppppppppppppivpppppmpohpppphgohpppppinocdusyppvppppupppppvfppppppppppppppppppppgpppppdopppppmcopdppppppppppppppspppppppppydpppppdcppppupcogupppppppppppppppppppppppppppsuppppxyppppppbsouyppppscipyfppvgpppppppppppppppppppppblfppppuppppppppmsppppbupcbimpvppyityfcvppppdmcppppppppppppppppppsxbppppppocmxpppdghpvppppsmpobpppppopcmtypppppstaimcyphpchmvppppppppppppphpppppkppdflyocdphpppuxhppppppiophyppppwacubpppvmuutcivapppsppoitanocluspaddmacopfpdpppvluppppspppppbplyppppppppppppppppppmppppppsuvypppxpuppfqpppppppppmpppppmppppplumqpppggcpopvdupppppppbppprpppppmpppypppppppppppspppppppppppppppppppmppppppppppppppppppsfhlpppsvlyppppppppppbrpppprdypppppuppppppdoypppppppppppppppppppsmpppppvppppppsyupppppsoumyppplypppppppppsppppdsuqpphfguppppxpppjfphowlppppmoncupprsldfppuppppppppppppppppppppppppppppppujppppppppppppppppppmdppppppppppppppfppppwdvsypdlyppkppppppppppppppppupspdpmfpushplsulpppypppppppppppygppppvlpppupmgvpdpsppcjpslubyppuumppppppppppppppppmupppppyvppppppsucmpppppulcsppppcdrppppppppppppppppppppnypppygsgfcppppncypppppfsnhgppqypcalinscgfpcncpppppppppppppppppcpppppdpppppprmucpppppcrppppppppppyppppppppppppodbylppppppflpppppprucmfgppplcpruypypppppppppppppppppppopfppppppppppppppppppppppppppppppoppppppppppppppppppppypuvppybppppppppppppppppppppompyppsmppppprugppppodmppppppppppppppppppphsoppppsopppppprypbopppyfppppppppppppgpouppgomoppppphwdpppppybsdpppgprsghfowdqmcopppppppppppppppppppcubppppcfoyppppoyuhpppppsfyppppmpconcusmppfmumcppppppppppppppppppppppppppppppppppppppppppppoppprjdbvppppppppppppppppdppppprdpppdsppppppgohcpppygnbppppmypppppsdpppppfpppppppppppppppppppppmppppppflpppppppruypppppppppppppppppppppppuppmppppppspppppppuslppppplrshyppppsbpumpppppppppppppppppponppppcumppppcfpyducpcnuslpybbmkfvsrcdvppccymcdyonphoppppppombppppsonppppmpnsicupudhuvbppnhglypppnyphglyrpppppunalcosydplkulppppmdpppppdppppppppppppppp
1396 | 1865 | ertaniocvsluuuuuuuuuuuuuuuuuuuuuuuvyupmucyoduuuuuuuuuuuuuuurvuugurdgyuuurpuupwuuuuuugiduuuuudouuuuuuumuuuuuufuuuuuozrgoyuduukgucmcdomudmuospdiwuuupmiduuumfouuuuusyuuuuuuuoscpmhhucuuuuuchdigurluchbmuuuuuuosinpmchvmpgmdrcguuuuugrmchuuuuuosucpmufwschdswuudulbuuupslhucgdduuuuuurdgyuuuuprvbluuuurcluuuuxhgglurspyuuuulascyphovdsrpuupvllxuuugduuuuyuuubuuucumomulguuurmdcvuuuurpndcuuuumosphyulvyufshpragcucychoralpcduubuvducnmuuguxncigdpulmguubmuuusguuuuuuzuuuuupvvbuuudmuuuusdgiuhgbduupdcuuuuuuuindflyuuvmfcuuuuuuvuuuuuuuguuuuucuuuuubgsuuuuuugsuumvuumspmbhuuufusuplbhuuyuvnitoclmftdlucyfquuuuupuuuubcucumuuuuuuuuuuunyuuuuuuunvtyuuutcnsuuuuuuuuuuuuuupuuuuuuupvuuuyuuuuuufyuuhuuuhpguuuulmdbunckguuuthuglyycafbsuuuuuuwsuuuuupyuuuuuuuuuxuuuuuuuuvywguuuuuudcnuyuuuusyupdfnucyluutacnsluupghwdlspafuyhuugkmuyuumocugudmduuuuuuuuusmhuuuuuulynbuuuuuuhuguuyuuuuulcymnuuuuuuualutcrsumpuunmcpyuuuuuumuuuuuuuauuuffdauuysalpmubnryuuuudunhcuuuuuussyrhpuuuuuurtsdnuuuuwuputsdyxuuyugcyyrhtmuuuuuuunguuuuusymuupmdsuvmuusuduuuuuuuuuudufcuusdghuuusgmhuuumxuuuuuuuuuuuuuuuuuuuuquuuuuuvlmuuuuuscfulyuudfuuuuuuuuuuuuguuuuupduuuuuuuuuuuuuuuuuuuulcuuuugfuvuuuudsuuuusbuuuuuuuuuuuuuuaduuuuuuuuuuuuuuuuuuuuhuuuuuxuuuuuualbhmuudvuuuuuuuuuuuuukyuuulfdvguuuuvmuuuuuuacdlucuxgxucopuuuupgoyuuuuuuuulhuuuuulvbycuumdylyfugfucosulxuvciluguuusguuuuuuuuuuuuuuuuuuuuuuguuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuduuuuuuuuuuuuuuuuuuuuuuuuuuumuuuuuumbduuuuuuuuuuuuhouuuuuuuuuuuuplauuuuvluuuuuuamhsuuuuuuuuuuuuuuuuuuuuluupuuuuuuuuufsguuuuudlusuuuuuspoxauvuumuuuuuuuuuuuuuuuluuuuuuuuuuuudluuuuuulafuuuugudglaouuuuuatmlocwvopmgzuuuuuupomvuuuuhuuuuuuuuuuuuupuuuuuhhuuuuuolmfbuudmuuuuuuguuuuuuuuuuuuuuuuuuguuuuuuuuuuuuuuuuuuuuuuuuuuufuduuuusdjuuuuuuuuuuuuudmuuuuuuuuuuucopuuuuguuuuuuulpsuuuuhpyuuuuuuuuuuuuuuuuuushyuuuugybocsuuupcsubuuliylcghybuuddvguuuuuuuuuuuuuuuuuuukowduuuowuuuuuuguuuuuuubchgxuuuuupoctmpuuuuusmpkuuuuusuuuuuuuuuuuuduuuuuusqulyuubsuquuuguhltmpyupoydtsubqlyuugdlatisbhdpmgdsypdxuuusdyuuuuuvuuuuuuuuuuuuvuuuuuuuuivuuuuumpohuuuuhgopuuuuuinocdusydpvuuubvfuuuuuuuuuuuuuuuuuuuuguuuuudouuuuumcopduuuuuuuuuuuuuuuuuuuuspuuyduuuuudcuuuuuucoguuuuuuuuuuuuupuuuuuuuuuuuuuhuuuuupsuuuuuuubsouyuuupscipyfuuvguuuuuuuuuuuuuuuuuuuuubuuuuuuluuuuuuupmuuuuuufpcbibuuuuyitpmvuuugudmcuuuuuuuuuuuuuuuuuuuuuuuuuuxcyouuuufycvuuususmpsblyuuuopcmtyuuuuustaimcyphvmhmvuuuuuuuuuuuvuhuuulukuuusluocdfuuuuuxhuuuuuuiophyuuuuwacubuuuvmuutcivauuudppoitanoclusuaddmacoufpduuuuuuuuuuuuuuuuspuuuuuuuuuuuuuuuuuuuuuuuuuumlyuuuusuvyuufxpuuuuuuuuuuuuuumuuuqumuuuuulumquupbgcpovduuuuuuuruuuupmuuuyuuuuuuuuuuuuuuuusuuuuuuuuuuuuuuuuuuumuuuuuuuuuuuuusfuuuuuhluuuusvlyuuuubruuuurdyuuuuuuuuuuuuuuuuuudoyuuuuuuuuuuuuusmuuuuuuuuuuuvuuuuuusyuuuuuusoumyuuulyuuupuuuuusuquudfguuuhwuuuujpxuufuuuhomdfuuuuosrpndcuuduuuuuuuuuuuuuuuuuuuuuuuuuuuuuuvuuuuuuuuuuuuuuuuuulujuuuuuuuuuuuuuuuuuumduuuuumpcuufuuuuuuuuuuuuuuudguuuuluuuuuudrunhuupuuuuuuuuuuuuuuulyyguulumcuuumrfuuuuslcnvcypypuuuuuuuuuuuuuuuuuuuuuuuuuuuuupjuuuuuupyvuuuuululcsgfyuubuuuuuuuuuuuuuuupuuuuubyuuuuusguuuuunncyuuudrfsnhguuqyucalinscyvpcncyluuuupuuuuuuuuuuuuuuuuuuuuuuugupcruuuuuuuuuuuuuuuodbuuuuuuuuuluodbuufluuuuuurucmfguuulcpruyubuuuuuuuuuuuuuuugfcuuuuuuuopfuuuuuuuuuuuuuuuuduuuuuurmucpuuuduuuuuuuuuuuuuouuuuuybuvuuuuuuuuuuuuuuuuuuouuuuusmpyuuuruguuuuodmuuuuuuuuuuuuuuuuuuuhsouuuusouuuuuurypbouugyfuuuuuuuuuuuuuuouuuuumouugouhwduuuuuybsduuugprsghfowduhospuumcouuupbcuuuuuuucuuuuuucfoyuuuuoyuhuuuuusfyuuuumpconcusmpufmumcuuuuuuuuuuuuuuuupuuuuupuuuuuuuuuuuuuuuuuuuuuuuuurjduuuuuubvuuuuuuuuuuduuuuurdpuuuuuuuudsuuuuupgohbuuuygmyuucuusduuuuufuuuuuuuuuuuuuuuuuuuuumpuuuuufluuuuuupruyuuuuuuuuuuuuuuuuuuuuuuuuuumuunuuusuuuuuuuusluuuuulrshyuuuuuuuuuusbpumuuuuuuuuuuuucuuuuuoumuuucuupyducfuuuslpcnuuufvsrcdvuuuybmcdyuyhgkbuuuhouuuuupombuuuusonpuuuuunsicuuuhbumbuuuuuuuhglyruuuumunalcosyluykuluuuuduuuuuuuuuuuuduuuuuuuuuuuuuuuuuuuug
1402 | 1909 | ertaniocvslpppkgpwppppppgidpppppumfoppuppsyppppppposcpomhppppdpppppzmcdomrpppospdiwpuupmdmipppfocmphpppgfgrmcupppdposuchphfwchcdswpppcmpoppppiuosinpmchdgpgmpppppvprvpppppdrgwkpppphgglurspyppcllascyphoudsrdscgppgppppppppppppppblppppcgpplpppprmypppppprypddlbppdsophlypupcfshprafcppymcoralpbyvlbpvdlglyppydcvypppppndcppppmcpppppppppppgpppppppplppppppcdppppppucnmppppxncigdpplmgppppppppppplpxpzppppppvpppppmdpppsppgihbudpvbpdcuqpppmpindflyppvmfcpuupppppppmftpgvmpppcdmpppusdgugxgpgscpyuppuspmnyplyfpsuplbhppppdnitoclaumvcucyfqpbhppppppppnvtypppmvfpvpppjdpbcupppppptcnspppppsthugllypppbspvppppppubcppcumpppppppppppppppppppwghppppppcubckgpxppupsycmlppnltacnspvppdhwdlppmpppphppppguppplmpypppppupppppppsmhpppxpplynblupppphugppppspamlcymnmppppvyalutcrsfyhppnmcpyppcyppppcuypppppppppppppyuspppfpnrypgkmpfnhmocugudssyrhpdpmppprtsdnppppwpputsdypppyppcayrhtmpppppppngpfblppppppppppppypppppppppppppppppmpppppppppppppppppppppuappppfdappppulpmpppdapppppppppxppppgspppppmdspdmsgmhpppplusmpppppppppdsupppppqupppppvlmpppypscfuufcldfppupgpppppppppppppyppppppppppppppppppppppppppppppvpgppppppppppppppppppppspppadpdpppppppppppppppppphulcppxpgfpppaludsppdvsbppppppppppppbhmpppdvgppppvmppppppacdlpppxgxppppppkppppppppppppplhppppplvbypplmdylfvpgfpcosulxppplgppppppcoppppppgcpppppppppppppgpppppfoypppplypppppsgpppppccilugppplppppppppppdpppppppppppppppppppppppppppmppppppmbdppppppppppppppppppppppppppplappppvlppppppamhspppppppppppppppppppplpppppphoppppfsgpppppdluppppppsopxapppplppppppppppppppplpppppuppppppdmpppppppdlppppamdglappspalatmlocwvhpmgzpspppppppppppphppppppppppppppppppppppppomvpppppppppppppppppppppppphspppppppgppppppppppppupppppgspppppolfudppdmsdjupppppppppppppppppppppppppmbpppppgcoppppplpsupppppyppppppppppppppppppppypdmpppbocsppppcsubppppplcghppshddvgphpppppfpppppppppppkowdpppowppdlppgupupslpbchliypoxmpoctmpypbppsmpkppppppppppppppgxppduppmppsqulypppsuqpvppphltmpyuppydtsubqlyupgdlatisubppmgdsuypppppppppppppppppbpofgufmppppppppppppppppppphppmppyppppppvpppppppsdyppppppdopppppppppppppppppppibhppppmpohpppmhgopppvfpinocdusyppvppppppppcopdpppdyppppppcogupppppppppppppppppppppppppphppppppxyppspppbsouyppppscipyfppvgpppppppppppppppppppppbppppppuppppsuppmppppppppcbipppppyityfcvppppdmcpppppppppppppppppppxlfbppppocmxpppdghppppbusmpompvpppopcmtypppppstaimcyphpchmvppppppspppppphpppppkppppppocdphpppuxhppppppiophyppppwacubpppvmuutcivapppdppoitanocluspaddmacopfpdpppppppvppppppppppppppppppppppppppppppppslpbyppppppppppppfqpppupppppvlupppppflyppppppppppppppbppppppppppspprpppspmpppyxpupppppppppppppppppppuvyppppumqppppmcpovdupppppppsfpppppppppppppppppppbrpppsrdyppppppppppppppppmpppppppppppppppppsmphlppppsvlyppppppppppppppppppppppppupppsppdoysuqpppfguppppppppjfpppfpppvpmdfppsyrslujpsoupppuplyppppppppppppppmypppphwppppppxpppppphowlpppmdoncvsyppfdppppfppppwdppppdlyppkppppppppppppppppupppppmfppppplsuppppypppppppppppppppppppuppupppppdpspppppslubyppuumpspdppppushpppplpppppppppppppppygppppvlpppppmgvppdrppcjpppppsdppppppppppppppygfcppmupppppyvppppppsucmpppppulcspgfccppppppppppppppppppppppnypdpppsgprmucpncypcrppfsnhgppqypcalinscyvpcncpplppppppflpppppprucmfgppplcpruypbppppppppppppppppgpppppppppodbpodbpppppppppppppppppppoppppppppppppppppppppypppppybppppopfpppppppppppppopppppsmppppprugppppodmpppppppppppppppppuvhsoppppsopppppprypbopppyfmpypppppppppppouppppmoppppphwdpppppybsdpppgprsghfowdqhospgpppppppppppppppppcppppppcfgoppppoyuhpppppsfypppompconcusmppfmmcouppppppppppppbcppppppppppppppppppppppppppppppppprjdppppppppppppppppppdppppprdppppppppppppppppppppbpppppmypppppsdpppppbvppppppppppppppppppppmppppppflppppppprsdhppyggnpppppohcpppppppppppuypppppsppppppmuslppppplrshypppppppppppppppppppppppppppcppppppumuppppppyducvpppslpybpppfvsrcdpppccsmcdyppyppppppppppppppppubpppompppppcfudnyppcnuhglynbmkpphglyrpppppunalcosydplkulpombmdppsonppppppnsicdpphbuvbppppppppppppppppppppppppppppppppppppppppppppppppuppppppppppppppppppppmpppppogrdypprppppppppppppppppppppvypppppcyodpppmfppppppprgoy
```
The script I used to generate the data strings is [here](https://ideone.com/b8Piz7), in case it's useful to anybody!
[Answer]
# Python 2, score=2111
Run with `python -u`. (For testing with the given controller, `python ./game.py python -u ./solver.py`.) This is 2044 code bytes + 1 for `-u` = 2045 bytes.
```
I=raw_input
a=I()
while'^'<a:
c=g=''
while len(set(g)-set(a))<6and'_'in a:
m=1879
while c in g:c='eunotitihencatpangnaottoesthesdoeitmbolocepnngcbelympvhanlrarnnccinatceaesdabceatelittlvuumineiltlatrnrttnomnnlnaildplttryliaxgtssclhemngfrssioninssenryinoeovortpcntapeetedlrruitardooiitacteutrsotdsoanedytsacnstshesmoeloluaiaceaceuhlortnegveprreanslrraneioeitslincssdsisuosycmieiebrinncrueoinytnabatepcciamenitnisecgaannehiphanotntnorvrvpcaddcdiittdnnieirsytescdeaaorfrerroleomdaeripmaandrgndipaimesctrsliavnopstmhiagamnimnlaaieceotlarscnbvnssvtaslplpisoiicinynriilirelaiohllvlndohenossvildgerltgterisahcreridsctnedainmteooeelnppeiemitceciyndetgfltrtsnatlrasrnsreiueletunsttainrctreydcpmiieecpedarulcaosoiulinrtpinoopptcpuarnioredabtilsnleoonslmltircninloaludrltrviocsatcgratduioeietnseaidltmmryalaaaorbctaglnlatatiosnloettuongaetlndesicircelunoeaofaciunhcdnnteeadtaadteairceneangugipadcrhaetftoloilisesaeaishtcinemcoleiibloyuoeiupovgtrccttsuttialnnnncatbamtrrndtperieonsavseoalncrrvvmctdmornstsunilnrscariranagloeoeciteptiplctpmadtnertslioractotlairneutorccaocletedoaammiiaurcadgdsmtmooaefmhedetvoelmoaemoaacoeieneislsaccllsunacnnspaomtdpnioocposrocniciicounnatosuvrsrodreacloapcansrsnrohlnotpiiptdneauaaatorofaatsnigiioegloreraiipaitnsssrststetomtoneifencntopxmstsruiosgopanriapiapelteeeelraaeeeipavauptneaalinnrlgipgoteienenrnfdmorouslpcaprmaeusnnnclltpcasrsitiuaictigsarsdenteetrtelnrecurupmautosotrssnisrdsnnulisrgomnpeatyotioipetalyanluatsoteoytirsmssyeatpryrtfclfnttniscloeuiaerasniracntfglaylurotngoaesuetillrrldnranosteldmpooonticteaprdcdmoecaafnftaivsmtrtlrpigcrnodueusmyepeotpnotltalgtltlvyhspphrtaliemyrtehrrdeiesoiiteptsptintnypmoinspsgiocacurarpruiardmnmrpgtpnoimtlsonpacrsnenpcinantayvryumpncyaelnrtrsisrdmnspgmarlttttptitsmeipuaervntgcunnncrtrnnitbltarssmaircptrenrerrerpceoiedchecefbrttutbumnbsnoeitaenutetreccosttofcdtgslgeaoacmicuiotelornahmticcsrdswaoignancoelrrsarnrnrrptiyadetilcricnasnoasenpstasiopdtnossrccllsoelirtfarrioemaeosioaeorcaesfnfsthklcsrdhlwakl'[int(a.replace('_','1'),36)%m];m-=6
print c;g+=c;a=I()
a=I()
```
### Result
```
score is 2111, totalerr is 20751
```
### How it works
The program replaces all `_`s with `1`s in the current state, treats the result as a base-36 integer, and takes it modulo 1879, giving us a crude hash function. It chooses a letter to guess by indexing this hash value into the long string of letters. If it already guessed that letter before, it decreases the modulus by 6 (so it always remains relatively prime to 36) and picks a different letter, repeating until it finds a letter that it didn’t guess yet.
I designed this strategy to have many tweakable variables (the individual letters of the long string), most of which will independently affect the final score by a small amount. That makes it well suited to hill-climbing style optimization—I used [Diversified Late Acceptance Search](https://arxiv.org/abs/1806.09328).
# Python 2, score=2854
With liberal usage of non-printable bytes and built-in compression, we can squeeze in a lot more information.
Decode with `xxd -r`, and run with `python -u`. (For testing with the given controller, `python ./game.py python -u ./solver.py`.) This is 2047 code bytes + 1 for `-u` = 2048 bytes.
```
00000000: efbb bf49 3d72 6177 5f69 6e70 7574 0a61 ...I=raw_input.a
00000010: 3d49 2829 0a77 6869 6c65 275e 273c 613a =I().while'^'<a:
00000020: 0a20 633d 673d 2727 0a20 7768 696c 6520 . c=g=''. while
00000030: 6c65 6e28 7365 7428 6729 2d73 6574 2861 len(set(g)-set(a
00000040: 2929 3c36 616e 6427 5f27 696e 2061 3a0a ))<6and'_'in a:.
00000050: 096d 3d33 3433 310a 0977 6869 6c65 2063 .m=3431..while c
00000060: 2069 6e20 673a 633d 2727 2778 da05 c101 in g:c='''x....
00000070: 62a8 3808 04d0 b322 1923 bf04 b230 b1f5 b.8....".#...0..
00000080: f6fb 1e42 6c73 475a e2e1 277d 3d19 d0c1 ...BlsGZ..'}=...
00000090: 5f9e d177 4f21 50d6 67ab 49b2 9ce1 09cb _..wO!P.g.I.....
000000a0: b4ca 793e ab4a 49a6 c567 e530 b9bf 41a9 ..y>.JI..g.0..A.
000000b0: 61b1 4dcc 77a1 7a3a c5a8 cb6a 3008 5958 a.M.w.z:...j0.YX
000000c0: fc15 ff50 d515 e0b3 326f 44d7 aecf 32fb ...P....2oD...2.
000000d0: 4050 03b0 3302 5e1c f038 1ea2 bf04 19f6 @P..3.^..8......
000000e0: a847 1a8a 2571 47a3 0c68 a6c6 4b5c 72ed .G..%qG..h..K\r.
000000f0: e463 a51a 509b aae2 bd85 dc96 5ca7 dbb0 .c..P.......\...
00000100: a5af bddc 6b77 f9ef 020c 86c1 8bba 2734 ....kw........'4
00000110: 4cb6 20bb e2b6 68af ba5d 5d4a 44ce 73a7 L. ...h..]]JD.s.
00000120: 5c72 4ad8 1d3a 0eed ea63 9629 9c56 518f \rJ..:...c.).VQ.
00000130: e51b 32fa 2f4f da18 3592 de3c 335d edae ..2./O..5..<3]..
00000140: 1f1f cd86 bedb cb3b 44c5 cf91 8047 d8b4 .......;D....G..
00000150: 33c2 aeff eea6 3184 5332 09bb a051 1191 3.....1.S2...Q..
00000160: 18dc f1dc a3a5 4220 36d7 c95c 7bb4 fc2d ......B 6..\{..-
00000170: a518 9d56 937d bb35 b962 2e6d bdb6 dc07 ...V.}.5.b.m....
00000180: 5b10 ca25 275b 2523 d57c 1363 5ad7 f9ca [..%'[%#.|.cZ...
00000190: 249e 8ea2 83c6 6af4 3de3 1fea 15ba ec1d $.....j.=.......
000001a0: e70c 96b8 38d8 b225 62a4 63d0 fa2e 5c72 ....8..%b.c...\r
000001b0: 6057 ecf8 3db2 9f7d 185c 72ee 8e5a e519 `W..=..}.\r..Z..
000001c0: 02db bfbb c25a c738 d2b6 b454 8d56 5ab6 .....Z.8...T.VZ.
000001d0: 11ae 27cc e476 81e8 2321 9135 c833 3a4b ..'..v..#!.5.3:K
000001e0: 8a89 919e 26e8 3623 e44d aaec 59db 6f6e ....&.6#.M..Y.on
000001f0: 79da 3941 29e8 d274 7eb6 0aac 3249 8b1b y.9A)..t~...2I..
00000200: b25d 1ff1 c496 f75c d125 e2aa f3b4 21a0 .].....\.%....!.
00000210: 7a55 d31d 4939 8433 ea97 f927 f9f3 0954 zU..I9.3...'...T
00000220: a861 2baa 7568 e1ce d489 f59d 1365 a69e .a+.uh.......e..
00000230: fc22 bef1 a0cc 7dfc a320 7ad5 fa39 3f5d ."....}.. z..9?]
00000240: 16b0 58b0 253c c54b f4d8 5729 cfb6 2371 ..X.%<.K..W)..#q
00000250: c328 c5ab 1315 fcc2 27ad 8462 b5d5 d6f8 .(......'..b....
00000260: 76aa fb12 c775 1733 24df 98f9 dd86 cbbe v....u.3$.......
00000270: 0c6e eb38 695f 705b 062d e231 3812 bdc4 .n.8i_p[.-.18...
00000280: 4664 ae0e 30a9 2cfb 3cf2 84dc 806e eb86 Fd..0.,.<....n..
00000290: 7988 d147 1bc9 f7b3 ad1f 1914 2d97 99c2 y..G........-...
000002a0: d096 711b 4f24 74d3 ebd9 8d11 7a4a 6518 ..q.O$t.....zJe.
000002b0: e25a 9c0c 79b2 661c 8188 6a88 7315 ed7e .Z..y.f...j.s..~
000002c0: b7ce 6d18 b06a 34d0 0a89 de1c 0509 65b4 ..m..j4.......e.
000002d0: ae5d 303d d2f2 7e98 cf07 ebb6 a4c0 e311 .]0=..~.........
000002e0: 13c4 1133 9b69 ecb6 9da7 75c8 1806 c136 ...3.i....u....6
000002f0: 2531 acbe aaa1 9353 fa13 ff28 fa62 999b %1.....S...(.b..
00000300: b59f f13d 47ca a7f5 e706 06f1 9374 78b1 ...=G........tx.
00000310: 649a ea19 a156 efe0 084a b06b 31c0 d86d d....V...J.k1..m
00000320: c913 a3d4 dbb0 6248 851f 688f 11fb cd91 ......bH..h.....
00000330: f339 9fb9 c9fe 0ecc acfc 6eeb 1544 6469 .9........n..Ddi
00000340: 223c 5d5e 14bd caaf f3ca fc4c 6cc4 b2a2 "<]^.......Ll...
00000350: ade5 5656 df3f 7046 c9ab cd63 3c5a caf3 ..VV.?pF...c<Z..
00000360: eec4 23ce aeb0 5aa8 7273 c1a7 d5b3 627a ..#...Z.rs....bz
00000370: 4b5b ec3b 7f87 48cb 5740 51d8 79aa f4cd K[.;[[email protected]](/cdn-cgi/l/email-protection)...
00000380: 5315 f53b ed89 2d7f 5736 d4f4 12e1 f1a0 S..;..-.W6......
00000390: 7d5b f45b 8323 4bd8 37fb 173e ed3e e85d }[.[.#K.7..>.>.]
000003a0: 7f82 e83d de15 2925 cbb4 702f 04c4 b8f0 ...=..)%..p/....
000003b0: 4998 b5f4 7ad3 b8f3 9ad3 5008 1722 c7ee I...z.....P.."..
000003c0: ca10 40f2 3fb1 8f2b 2262 f70e 8358 c2ac ..@.?..+"b...X..
000003d0: 0b78 4ca2 163b 2f74 3c02 df67 a4eb f9f9 .xL..;/t<..g....
000003e0: 799c b5c4 14b6 d672 54d5 37c3 6a7d 1675 y......rT.7.j}.u
000003f0: f219 bd6e ee58 eda8 3af1 6989 c8c9 f1a8 ...n.X..:.i.....
00000400: eeeb dcfa bed7 eef5 4ea7 50ff bde8 92f8 ........N.P.....
00000410: 6648 2980 ebf9 7645 84d9 0ef5 1192 c672 fH)...vE.......r
00000420: 254f e460 8da5 79d6 0fbc 2138 1edf b1ad %O.`..y...!8....
00000430: 355a 98ab 548b db38 43ef 12db ef01 b93c 5Z..T..8C......<
00000440: 933a cbf1 44e6 2b85 f22c f6db e922 e1e3 .:..D.+..,..."..
00000450: 113e 803f 562c 83df 898c 3dca 86fc c809 .>.?V,....=.....
00000460: c09d 8585 87b0 4a78 8908 fc4f e0f3 4731 ......Jx...O..G1
00000470: 671f c4de 53f3 a85f 8954 fed5 ee2c 99c4 g...S.._.T...,..
00000480: f091 6feb 5307 4f70 7df4 2620 d7d9 dca4 ..o.S.Op}.& ....
00000490: 4644 a948 4016 44bc 80df 7d6f c686 6499 [[email protected]](/cdn-cgi/l/email-protection)...}o..d.
000004a0: a4bc 75d0 2506 bf1d 2747 6b54 95be cfb1 ..u.%...'GkT....
000004b0: 7b4b d70a 89b0 ac68 e2c4 1394 ba20 4d01 {K.....h..... M.
000004c0: 204c 64f3 721f 2a53 862d 89f5 59df b273 Ld.r.*S.-..Y..s
000004d0: 7c32 470f 7055 ef6e 2167 d4dd f546 9c0e |2G.pU.n!g...F..
000004e0: 9eda bf3a 78ce d946 28b5 2c8d f79f 7c31 ...:x..F(.,...|1
000004f0: f940 d75d 8940 aca2 f6af f538 1eaf 6ef7 .@.][[email protected]](/cdn-cgi/l/email-protection).
00000500: c81d 56c5 955c 0506 7474 fa7d 4627 b6fe ..V..\..tt.}F'..
00000510: 4aa9 9abd 825d 166f 852c 8a4b b87e 727f J....].o.,.K.~r.
00000520: 43c6 d657 eeb5 46cb 449b ce1b cc11 a25c C..W..F.D......\
00000530: 72b1 8ccd 7feb ac50 8c21 a75c 30cb a3a7 r......P.!.\0...
00000540: ebc3 326c 0a9e 8b3a 513e 560b 2c31 cb61 ..2l...:Q>V.,1.a
00000550: c6bc 6748 90e1 6e3c ae15 8e37 9264 f73f ..gH..n<...7.d.?
00000560: 696b 3c62 47a8 f091 82a7 0f4e 2f7d 1343 ik<bG......N/}.C
00000570: d202 b436 3e36 7825 7fc7 8b0b 2543 cdff ...6>6x%....%C..
00000580: 2a33 08af e34a 652e d547 d87d 0c4f b6d8 *3...Je..G.}.O..
00000590: 5105 ad4b 47e9 31ad 2bec 98f0 d6aa 487d Q..KG.1.+.....H}
000005a0: d26b 33fa 651c 67b7 f189 7c01 cf87 24ee .k3.e.g...|...$.
000005b0: f2d5 3634 49f3 6aad 898c 914f e6fe 202d ..64I.j....O.. -
000005c0: 8f18 2e3b a1dc fe8c 624c 3d66 27ca 54da ...;....bL=f'.T.
000005d0: 1183 c790 96fa f357 bee8 6171 d69e 451d .......W..aq..E.
000005e0: 5aad 5bd5 681a 0cc1 b6ce c3d4 82d9 d7a6 Z.[.h...........
000005f0: e269 4bac bbff c406 7388 85d6 6dda f2c4 .iK.....s...m...
00000600: 0f75 e17c dd1d acfd 6086 904c c59c 935b .u.|....`..L...[
00000610: 0a8f cef8 c935 51ad d44a d9b2 aa0b e01c .....5Q..J......
00000620: 3ff9 bb87 3190 b4cc 2fed 4bd1 58a1 f06b ?...1.../.K.X..k
00000630: ee44 1a6c 435d ae3a e7ef a501 a30e 6def .D.lC].:......m.
00000640: 21ea 3b89 32e1 631b 53f8 c14a f636 51f9 !.;.2.c.S..J.6Q.
00000650: d662 ef32 b386 ed27 6b87 5b5e 8f5b 9776 .b.2...'k.[^.[.v
00000660: dfe0 e83d 1f29 fbf2 dc5b b843 60bf cbc8 ...=.)...[.C`...
00000670: aa9a 9ad2 f94e 2ea9 96b0 296c 937e 65a3 .....N....)l.~e.
00000680: eafd a4d0 85b5 9f4a c671 7ece 5811 c7b7 .......J.q~.X...
00000690: d3c6 75e0 70b3 224d c9aa d8f1 fb6e f4ea ..u.p."M.....n..
000006a0: 1d7a cef7 5fc7 5a98 7fd5 28b5 753f 7c43 .z.._.Z...(.u?|C
000006b0: da79 9d90 1a51 33ae ca7a d5ea a990 fed3 .y...Q3..z......
000006c0: 5ff5 2975 7b99 8333 44c2 a7fa 17a3 875d _.)u{..3D......]
000006d0: 70ef 2361 6d5a 1cc8 13a7 d482 30c6 2b84 p.#amZ......0.+.
000006e0: 4d4a a765 c81b 2e16 3e62 08d8 ce5a 2beb MJ.e....>b...Z+.
000006f0: a823 42ef 633f 7858 cdaa 755c 3097 f029 .#B.c?xX..u\0..)
00000700: 2afa 06d8 47c0 2714 f3fa 1554 d8a5 1a8b *...G.'....T....
00000710: 77ac b319 ac47 9b5e 5ba7 a5ae 7dc7 c86f w....G.^[...}..o
00000720: e73b 2a62 7a3e 7b29 6583 b227 0417 bb6e .;*bz>{)e..'...n
00000730: 98ef 9097 6f9b c655 8f20 32ce a60e 6556 ....o..U. 2...eV
00000740: ce62 c8c9 afab c30e 6908 5675 19c6 5019 .b......i.Vu..P.
00000750: 62dd 131b 9c2d 3968 3f42 5b96 e7c9 1e23 b....-9h?B[....#
00000760: f1b0 0280 9ce9 f9cc 92ec 7eb5 a7c6 9619 ..........~.....
00000770: 5aab b832 b7cf 865c 72f1 9454 e33a 9975 Z..2...\r..T.:.u
00000780: 5b8a d8e8 5f46 0a22 2397 7d77 f70a 33b7 [..._F."#.}w..3.
00000790: 5183 5d5e 7267 54c5 a204 1e2f 470a dad2 Q.]^rgT..../G...
000007a0: a554 e493 7f06 7ff9 5fdd dfff 8428 a74f .T......_....(.O
000007b0: 2727 272e 6465 636f 6465 2827 7a69 7027 '''.decode('zip'
000007c0: 295b 696e 7428 612e 7265 706c 6163 6528 )[int(a.replace(
000007d0: 275f 272c 2731 2729 2c33 3629 256d 5d3b '_','1'),36)%m];
000007e0: 6d2d 3d36 0a09 7072 696e 7420 633b 672b m-=6..print c;g+
000007f0: 3d63 3b61 3d49 2829 0a20 613d 4928 29 =c;a=I(). a=I()
```
### Result
```
score is 2854, totalerr is 19482
```
[Answer]
The **[D](http://dlang.org/index.html)** programming language is my tool of choice for this challenge.
Just shy of the 2,048 byte limit, although it is slightly golfed in some parts to get the byte count down, all the heavy lifting remains perfectly readable. This solver isn't very good at its job, and I expect it will be beaten easily, but this is just to get the ball rolling. Kick things off, so to speak.
**EDIT #1**: ~~As it has been pointed out, the original code is prone to dying a horrible death when it exhausts all the vowels. As it doesn't work properly, I've replaced it with a somewhat more brutish approach to random guessing.~~
**EDIT #2**: Original code has been fixed and now stands.
### [Score](https://codegolf.stackexchange.com/questions/25496/hangman-solver-king-of-the-hill/25533?noredirect=1#comment55268_25533):
`25.7; totalerr: 24,529.9 (average of 10 tests).`
### How it works
This solver is completely random. Even the randomness is random, fun times!
When the program receives input, it will guess one random character that it hasn't already guessed and send it to STDOUT.
The guessing algorithm works thusly:
1. Randomly select one of two character groups (consonants or vowels).
2. Randomly select one of two modes:
* Use [letter frequency](http://en.wikipedia.org/wiki/Letter_frequency#Relative_frequencies_of_letters_in_the_English_language) as weight on the RNG. Higher frequency is more likely to be selected.
* Pick a character at a random index, disregarding frequency.
3. Return a single character based on the mode selected in step 2.
```
import std.stdio, std.random, std.array, std.math, std.algorithm;
alias double[char] Hash;
alias uniform U;
bool first = true;
Hash cons, vowel;
char[] guessed;
Mt19937 rng;
int fails;
void main()
{
rng.seed( unpredictableSeed );
auto get() { return stdin.readln.replace( "\r", "" ).replace( "\n", "" ); }
string input, last;
while( ( input = get ) != "END" )
{
if( first ) last = input;
if( input == last && !first ) ++fails;
if( fails == 6 || !input.any!( x => x == '_' ) )
{
fails = 0;
last = null;
guessed = [];
first = true;
continue;
}
stdout.writeln( guess );
stdout.flush;
if( !first ) last = input;
if( first ) first = false;
}
}
char guess()
{
reroll:
Hash group;
double min, max;
bool useWeight = U( 0, 2, rng ) == 1;
if( guessed.filter!( c => vowel.keys.any!( x => x == c ) ).count < vowel.length && U( 0, 2, rng ) == 1 )
{
group = vowel;
min = useWeight ? 2.758 : 0;
max = useWeight ? 12.702 : 4;
}
else
{
group = cons;
min = useWeight ? 0.074 : 0;
max = useWeight ? 9.056 : 20;
}
double choice = U!( "()" )( min, max, rng );
char chr;
if( useWeight )
{
foreach( k, v; group )
if( v < choice )
chr = k;
}
else
{
int counter = 0;
foreach( k, v; group )
{
if( counter == cast( int )choice.floor )
{
chr = k;
break;
}
++counter;
}
}
if( guessed.any!( x => chr == x ) || chr == char.init )
goto reroll;
else
{
guessed ~= chr;
return chr;
}
}
K keys( K, V )( V[K] a )
{
K[] ks;
foreach( k, v; a ) ks ~= k;
return ks;
}
static this()
{
cons = [ 't': 9.056, 'n': 6.749, 's': 6.327, 'h': 6.049, 'r': 5.987, 'd': 4.253, 'l': 4.025, 'c': 2.782, 'm': 2.406, 'w': 2.360, 'f': 2.228, 'g': 2.015, 'y': 1.974, 'p': 1.929, 'b': 1.492, 'v': 0.978, 'k': 0.772, 'j': 0.153, 'x': 0.150, 'q': 0.095, 'z': 0.074 ];
vowel = [ 'e': 12.702, 'a': 8.167, 'o': 7.507, 'i': 6.966, 'u': 2.758 ];
}
```
] |
[Question]
[
You probably know the game mastermind:
The player tries to guess a code of 4 slots, with 8 possible colors - no duplicates this time.
Let's call those colors A through H, so possible solutions could be ABCD or BCHD.
Each time you place a guess, the game master will respond with two information: how many slots you got right, and how many colors you got right but in the wrong place.
Some examples:
```
If the code is ABCD
and your guess is ACHB
the response 12: the color A is correctly placed, the two colors B&C are in the wrong place.
Code is ABCD
you guess EFGH
response is 00
Code is ABCD
you guess ABCD
response is 40
A full representation would be:
ABCD04,DCBA40
or
ABCD00,EFGH22,EFHG13,HFGE40
A partial game does not contain the final solution,
nor necessarily enough data to define a unique solution.
ABCD00,EFGH22,EFHG13
An example for an invalid partial game would be:
ABCD03,EFGH02: This would require that 5 colors are present
```
In essence, all games that cannot have a solution are invalid. The gamemaster made a mistake.
**Your task**
Never trust a game master. Your task is to write a program that takes a partial or full game description and validates whether such a game state is possible.
* Expect that no game description is longer than 8 attempts.
* Expect that the gamemaster can make a mistake on the very first turn, e.g. ABCD41
* The player can make an "invalid" guess to gain further information, e.g. AAAA to check if there is an A at all. Such a game is still valid, you only evaluate the gamemaster's responses. In such a case, exact hit takes precedence over near-misses, for code ABCD it's AAAA10, not AAAA14.
* You can format the input and output in whatever way you see fit, including replacing the colors by digits etc.
* Any pre-generated hashtable counts towards the total number of bytes.
* You know the loophole thing.
**The shortest code wins.**
Additional test cases:
```
- ABCD11,ACEG02,HGFE11,CCCC10,CDGH01 => valid
- ABCD01,EFGH03,CGGH11,HGFE21 => valid
- ABCD22,EFGH01,ACDE11 => invalid
- ABCD02,EFGH01,AABB21,AEDH30 => invalid
- ABCD03,DCBA02 => invalid
- ABCD32 => invalid
```
You can generate any number of valid cases by [playing the game.](https://www.webgamesonline.com/mastermind/index.php)
Invalid solutions are hard to come up with. If you find invalid combinations that first slipped through your code, please comment it below for your fellow golfers.
**Bonus:**
Bonus points if you come up with a solution that uses a significantly different approach than generating and traversing all possible permutations.
[Answer]
# JavaScript (ES6), ~~116 112~~ 107 bytes
Expects an array of entries in the following format: `[[a,b,c,d], "XY"]`, where `a` to `d` are integers in `[0..7]`, `X` is the number of correct digits and `Y` is the number of near-misses.
Returns **0** or **1**.
```
f=(a,n)=>n>>12?0:!a.some(([a,x])=>!a.every(o=(d,i)=>o[x-=d^(v=n>>i*3&7)?a.includes(v):10,v]^=1)|x)|f(a,-~n)
```
[Try it online!](https://tio.run/##dZDBTtwwEIbvPIW5ELt4jZMsqkSVRVkn69w4cEyDZCXO1ihrL3GIFgE99gH6iH2RZbJUoogyh7E8880/v32rRuXr3myHmXWN3u/bBCtqSbKwi0UYXfKLY8W822iMS0V3FTSgoEfdP2CX4IYaqLhyN0uaGzwmMGS@xCdfyaVixtbdfaM9HslFyOlY3SQhedqRpxY2zH5asu/13b3pNQ5aHxDWa9WsTKevH2yNOWGDux56Y9eYML/tzICD7xaw1vW5qn9gj5IFejxCSKEE4Q0kzzZqgM5Zmc6K6nH@zNjZmhCobl/pEpWMMc98Z2qNOUVzUh269dQN0qXI8pUsArDe6N1Vi2tCKPLlvEKncJxXqCLfYGPtrHedZp1b4w27dcbiAIG1rWpy2@B4ToAP0J9fvyGfIngvgblnsp82hCFNRS55RAu5yuEmIOB/RCYLHk5GRtWZ5mhieUgnQzymQsoC2GkkCtHfeMdG0Ss7yWegi94HsMb@o/xGp8tlBEeeFTH/jI5pJpYpj9B/441GBzz@hPsoLqQQYEWmEsSpSOFDoo/0gX0B "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f is a recursive function taking:
a, // a[] = input
n // n = 12-bit counter, initially undefined, to
) => // describe all possible codes
n >> 12 ? // if n = 4096:
0 // stop the recursion
: // else:
!a.some(([a, x]) => // for each entry [a, x, y] in a[], with a[] =
// guess, x = correct digits and near-misses:
!a.every(o = // we use the object o to keep track of the
// digits that were already extracted from n,
// in order to discard invalid codes
(d, i) => // for each value d at position i in a[]:
o[ //
x -= // update x:
d ^ ( // compare d with ...
v = // ... v which is defined as ...
n >> i * 3 // ... the next 3-bit digit extracted from n
& 7 //
) ? // if d is not equal to v, decrement x if ...
a.includes(v) // ... v appears elsewhere in a[]
: // else:
10, // subtract 10 from x
v // actual index in o to ...
] ^= 1 // ... mark this digit as used; or yield 0
// and exit every() if it was already used
) // end of every(); the iteration fails if it's
| x // falsy or x is not equal to 0
) // end of some()
| f(a, -~n) // do a recursive call with n + 1
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 47 bytes
```
⊙EX⁸¦⁴E⁴§α﹪÷ιX⁸λ⁸∧⬤ι⁼№ιλ¹⬤θ⁼I…⮌λ²ΣEι∨⁼ν§λξ∧№λνχ
```
[Try it online!](https://tio.run/##RU7LCsIwEPyV0NMGImjpoeApRC09iKJH8RDagIE10bSp9utjUl972WUeO9NcpGusxBD2TpseuBlhK2@wtw/loGSkoIwkoGCE97Vp1RNkRGzr0UJt@pUedKtAM/KzII2ektK0uGmBIyZ@ffcSOxDWxxydZIwsJk3k739edj2IsUElLvYGBzUo1ylI6jypj/46NYwfdg4@JvNvh4w8v8nvrIiYlDWn31mGcDplohJinmcsq3jFp0PwzXqRZ@dzmA34Ag "Charcoal – Try It Online") Link is to verbose version of code. Brute-force, but only takes a second or so on TIO. Outputs a Charcoal boolean, i.e. `-` for truthy, nothing for falsy. Explanation:
```
⊙EX⁸¦⁴E⁴§α﹪÷ιX⁸λ⁸
```
Generate all possible codes including duplicates, and see if any of them satisfies the following.
```
∧⬤ι⁼№ιλ¹
```
Check that the code contains no duplicates, and...
```
⬤θ
```
... check whether all of the guesses satisfy the following.
```
⁼I…⮌λ²
```
Get the result of the guess and check that it equals the following.
```
ΣEι
```
Map over each character of the code.
```
∨⁼ν§λξ
```
Check whether it's an exact match.
```
∧№λνχ
```
Check whether it's misplaced.
~~60~~ ~~46~~ 44-byte version for a version that allows duplicates in the code:
```
⊙EX⁸¦⁴E⁴§α﹪÷ιX⁸λ⁸⬤θ⁼Σλ⁺×⁹ΣEι⁼ν§λξΣEα⌊⟦№ιν№λν
```
[Try it online!](https://tio.run/##RY5LC8IwEIT/SuhpAxFUPCieQtTSg1DQW@kh2IIL28Q@4uPXx8Rq3Ut2PmZ2crnq7mI1eZ93aAaQ5gVHfYPcPuoO1oKtuGARrASTQ2aq@gk6EFs5spCZYYd3rGpAwaYI8ZBZcx4fSQStYPvWaerh5BqgQHNyPZyxqXvYCBZprMDJZ/5lJNiTj7d@vtiPBpsgC2Vd@HVImmAYBUVR8u9svS@KRKVKzZeJSFKZys@i5GG/WCZl6Wd3egM "Charcoal – Try It Online") Link is to verbose version of code. Brute-force, so takes a few seconds on TIO for falsy cases. Outputs a Charcoal boolean, i.e. `-` for truthy, nothing for falsy. Explanation:
```
⊙EX⁸¦⁴E⁴§α﹪÷ιX⁸λ⁸
```
Generate all possible codes including duplicates, and see if any of them satisfies the following.
```
⬤θ
```
Check whether all of the guesses satisfy the following.
```
⁼Σλ⁺
```
Extract the result of the guess (when passed a string which contains non-digits, `Sum` looks for embedded integer(s) and takes their sum rather than their digital sum) and check that it equals the sum of the following:
```
×⁹ΣEι⁼ν§λξ
```
Count 9 for each exact match.
```
ΣEα⌊⟦№ιν№λν
```
Count each match (whether exact or misplaced).
Edit: I had inadvertently calculated 4⁸ instead of 8⁴, so the code was taking 16 times longer than it needed to.
[Answer]
## Python3, ~~304~~ 140 bytes
```
lambda l:any(all(sum((x in t)+9*(x==y)for x,y in zip(p,t))==int(t[4:])for t in l)for p in permutations('ABCDEFGH',4))
from itertools import*
```
Lambda expecting input in the form of an array. [Try it online!](https://tio.run/##RY7BboQgEIbvPsXcFramQdykrYkHRBffoe2BTbUlQSCIifblLeihXGbm//5/BreFH2vKV@f3sf7YtZweXxJ0Jc2GpNZoXiaEVlAGAn56u6K1rjc8Wg9rviX1Vznk8oBxXSsTUHi/VZ8HD4nqo3WpdYOfliCDsmZGF9bwtruL/pLfMM5GbydQYfDBWj2Dmpz14bqnrEpZL833gEgOL7gC59OhESnjloDw8@y0ihXjPS0tCmC8E4RCL@5dnHh8BQHeip4UWbKQAtJpUgIXoo@W5KQno/RkaUsb42fgX2RNQ2Pp2r4kJyuh5Q0j9JhKmnHBeQwIJqIInMVP0D8)
Or 156 bytes as a full python program with textual input/output:
```
from itertools import*
l=input()
print(any(all(sum((x in t)+9*(x==y)for x,y in zip(p,t))==int(t[4:])for t in l.split())for p in permutations('ABCDEFGH',4)))
```
[(try it online)](https://tio.run/##RY/BboQgFEX3fsXLbAZaM0GcpO0kLBAd/IemCzOlLQkCQUy0P29BF2VD3r333Lzn1/jjbP3qw/Zwn4qdTqdNj96FCDqqEJ0zEwwT6MIwbf0cES580Daiwa5oMAZN84jQAtpCxM9vT2hhbMVfLsBSrln91R75MmLMWMbi@/X2sfsxu@YyeaNT6y75LOmLV2Gc4xC1sxM680a03V325/KKMd7ShkXO6pwNg/1WiJTwgm@gFvVA@Qq8ZaaqgItOEgq9vHdpEulVBEQre1IVOUIqyM2kBiFlnyI5SQ@P0sPLLW3CD@Bf5E1D09e1fU0Or4ZWNJzQfappIaQQCZBcJhEET0vQPw)
Could save 2 bytes by replacing `'ABCDEFGH'` with `range(8)`, but then input should be in the form `012311,024602,765411,222210,236701`.
**History of edits:** move `r=[0,1,2,3]` outside of function and remove `[]` to save 3 bytes; remove `()` around `return` value to save 2 bytes; replace `def f(p,t):` with `lambda p,t:` to save about 8 bytes; replace `[...].count(True)` with `sum(...)` to save 5+3=8 bytes; remove intermediary variable `m` to save 5 bytes; use `:=` in a much better way to get rid of the nested `lambda` and the awkward `(,,)[-1]` and save 26 bytes; [@Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld) fixed a mistake with the rules of mastermind and golfed it down to 221 bytes; @Arnauld did some magic with the booleans and ints to golf it to 185; replace `for i in range(4)` with `for x,y in zip(p,t)` to save 7 bytes; save 10 bytes by replacing `(lambda l:...)(input())` with `l=input() ...`; @Arnauld saves 8 bytes by replacing `t.count(x)and 1+9*(x==y)` with `(x in t)+9*(x==y)` (which is also easier to understand in my opinion) plus 3 bytes by requiring whitespace-separated input to replace `.split(',')` with `.split()`, @Arnauld saves 1 byte by replacing `import itertools as i` with `from itertools import*`; @Arnauld removed 16 bytes by making it a lambda instead of a full python program
**Less compact, more readable version**
```
import itertools as i
r=0,1,2,3
def f(p,t):
correct = [p[i]==t[i] for i in r]
misplaced = [t.count(p[i]) and not correct[i] for i in r]
return sum(correct) * 10 + sum(misplaced) == int(t[4:])
def z(line):
return any(all(f(p,t) for t in line.split(',')) for p in i.permutations('ABCDEFGH',4))
print(z(input()))
```
* `f(p,t)` is `True` if combination `p` passes test `t`. `p` is a size-4 array which might not contain duplicates (eg `ABCD`). `t` is a size-6 array which might contain duplicates (eg `CCCC10`).
* `z(line)` is `True` if there exists at least one legal combination `p` which passes all tests `t`; tests are described by the comma-separated string `line`.
[Answer]
# [R](https://www.r-project.org/) + gtools, ~~130~~ 125 bytes
```
function(l)any(apply(permutations(8,4),1,function(c)all(sapply(l,function(g)g[[2]]==c(x<-sum(c==el(g)),sum(c%in%el(g))-x)))))
```
[Try it online!](https://tio.run/##hZNNb@IwEIbv@RUWqwpbSnfzAZRWm0MIIRx6atkTQsgYL0R1PmQ7FVD1t7O2gVIWAnMa@533mbET8y1LZxzzNVzIomACWRkWkvIszedTsqTkLdj@rXIi0yKHDOF8DXFZsjUsVU0lsd4XsGu3kO3aX4UEYcag2FWy4/4CLcZjbzIJAgJXv@9FlUESBJQpAdlmdZfmd7v1/Qrp2Gb4jU7TvKzklKVCBl@wFfqwgAq2a7M6tlnvFR2boMq1DwrJRclSCdd2s4nQscANMizJEm7G7lNrYj/Ho1H88nos4FRWXB1eQzaujcXPNJd0QblytJ86E7SHfSLr07IkFVITT4aGBDbCXtR33YbdCKM4cTyVDJNBbHYiFa6jk34ydNwGQuAHeMcsnRucV4dztDkeKI@vzUkyNDjN9c4ofh3F8w6U3XR9PZQxp/nR3qod4tQe9nqeSeL@0HfOOe1ajj5DP@qFCvjdBYytU2fzvfMeDxeLVbjO/7fSrS31T6cIgCyAeRCg5JTQOc0JBbxi1HAeL3GiJIrM9SRhEpokCtUn974Nobghz3HF5k0BdD2gK5yVe6rr1IzXO/wlOJuli6qoBCBYUBvMCrkE75QL/S4BJoSWEs8Uzjp72NB00JDRy5/4suxdl30tD8Ln1xq9dUNv39A7N/SH6@N1b9gfr9td56CDX3vM9h8 "R – Try It Online")
Colours are represented by digits 1..8. Returns 'TRUE' for valid games and 'FALSE' for invalid gamemaster responses.
**Commented:**
```
mastermind_check=function(l) # l=list of lists of [guess,response]
any( # do any of...
apply(permutations(8,4),1, # all possible codes...
function(c)all( # produce all valid responses for...
sapply(l, # every [guess,response] pair...
function(g) # using this function to define valid response:
all(g[[2]]==c( # - both of these must be the same:
x<-sum(c==el(g)), # - response[1] == sum of correct cols in correct pos
sum(c%in%el(g))-x # - response[2] == sum of correct cols in any pos
) # minus response[1]
))))) # ...?
```
---
# [R](https://www.r-project.org/), 114 bytes
```
function(l){while(T)T=!all(y<-sample(1:8,4),sapply(l,function(g)g[[2]]==c(x<-sum(y==el(g)),sum(y%in%el(g))-x)));1}
```
[Try it online!](https://tio.run/##hZRLb@IwFIX3@RUeUIUtpW0e0NdMFiGkYdEVZVYVQm7wEKuOiWKnhVb8dmqbV1vI4JWTe87n45vY5SrHQpIyp3wyTjOSvgSrfxVPJZ1xyNDHW0YZgUM0DH5hxuDiz7nAeaFeuXc3dhvZAhcFW0Bm70xTNH168kajIEjhXMmrHC6CgDBVUHL9dEb52fr5fI4Q@u0uVYgXMqa8qOSYUSGDHW2OPiygBluvM9@vs9hU9HgPKq59UMhSFIxKuLBbLYT2AjfIsUwz@P7k3rVH9kM8HMaDx72gJLIq1Y415N21sbigXJIpKZWjc3c1QhvYEllLy5JESE38FhqmsBF2o57rNuxGGMWJ46lJP7mPzZtIDdfRk17Sd9wGQqAJXjGjE4Pz6nCONsf3yuNrc5L0DU5zvQOKX0fxvC1lna6nQxkz5Xt7uzbEd3vY7XpmEvf6vnPI6dRy9B56UTdUwK8uYGxXdTbfO1zj@qhYDdf52ZWbWqn/PUUA5AyYUwCKkqRkQnhKQFkxYji3xzhREkWmPUmYhGYSheqTe19CKG5YclyxSUsArQdkbk7R@kdyauJ1t38Jzp/ptJpVAqRYEBs8z2QGXkkp1DkQAKcpKSR@VjirCfhMEiAzLLeburwPHx5j4xTgjTKmJSDDTF4AMCD57FXryWbDlE9Bq9lSTcAlTtXFsOuIUlvWz8sCmg3ojMPB3/h42duVm@CowNcCk7JO0T6p6JxUXO0VR@vXp2LenADc/r8NrrOtA0i5ajldf04ELjfU1Sc "R – Try It Online")
Stochastic function that checks random codes until it finds one that could satisfy the gamemaster responses, at which point it halts and returns `1`.
Halting is assured in finite time for all valid gamemaster responses.
If gamemaster response is invalid, function never halts.
] |
[Question]
[
I saw [a cool gif](https://i.stack.imgur.com/ZBHdI.gif) of the twin dragon curve made from a square, and wondered what would happen if we started from another base image. So I wrote a program to do this.

It's so cool that I thought it would be fun to do it as a challenge.
# Task
You will take in a square image with an edge length that is a power of 2 (greater than 4).
To make this image you should start by dividing your image into 4 vertical bands of equal size and shifting adjacent bands one 8th of the size of the image in opposite directions (shifted bands should wrap around to the other side). You should then repeat this process each time splitting the image into twice as many divisions and shifting by half as far as the previous time. Each iteration you should alternate between vertical and horizontal shifts. You should iterate until the shift requires you to shift by a fractional number of pixels (this will always be 1/2) at which point you are done.
When shifting vertically odd numbered bands from the left (zero-indexed) should shift down while even shift up. When shifting horizontally odd numbered bands from the top should shift left while even numbered bands should shift right.
You need only output/display the end result of the transformation, not all the intermediate steps like in the gif.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to minimize the length of you source code as measured in bytes.
## Worked through example
I will work through the cat gif shown at the top of the page frame by frame.
Here is the starting image:

This image is 512 by 512 pixels. We will break it in 4 bands to start and shift each band by 1/8 the image size (64 pixels) vertically.

We will now divide it into twice as many bands (8 bands) and shift it half as far as last time (32 pixels). This time we will shift horizontally.

We will now shift vertically again this time splitting into 16 bands and shifting each band by 16 pixels.

32 bands, 8 pixels, horizontal shift

64 bands, 4 pixels, vertical shift.

128 bands, 2 pixels, horizontal shift.

256 bands, 1 pixel, vertical shift.

Since the next shift would require us to move each band by half a pixel we will stop at this point and output the result.
## Test cases
I have a working script that can make these images so I thought I would let you guys choose the images for the test cases. So if you have a square image that is a power of 2 wide that you would like to see become dragonified. Feel free to send it to me and I'll make it a test case.
[](https://i.stack.imgur.com/hazab.png)
[](https://i.stack.imgur.com/1S0cQ.png)


You should also test on a plain white or solid black image so that you can determine whether or not pixels are disappearing or not.
[Answer]
# MATLAB, 237 bytes
```
function A=r(A);n=size(A,1);p=@(a,v)permute(a,[v,3]);k=n/8;v=1:2;while k>=1;b=mod(0:n-1,4*k)<2*k;x=find(b);y=find(~b);c=[k+1:n,1:k;n-k+1:n,1:n-k];A=p(A,v);c=c(3-v,:);A(x,:,:)=A(x,c(1,:),:);A(y,:,:)=A(y,c(2,:),:);A=p(A,v);k=k/2;v=3-v;end
```
Took a little bit of guess work as I did not understand the procedure from the specs, but with the help of the image it worked.

[Answer]
# Python 2, ~~317~~ ~~313~~ ~~304~~ 298
```
from PIL import Image
I=Image.open(input())
w,h=I.size
b,p,q,s=4,w/8,1,1
while p>1:o=I.copy();o.paste(I,[(w-p,0),(0,w-p)][q==1]);o.paste(I,[(p-w,0),(0,p-w)][q==1]);q*=-1;x=0;exec'o.paste(I.crop([(0,x,w,x+p*2),(x,0,x+p*2,w)][s%2]),[(q*p,x),(x,q*p)][s%2]);q*=-1;x+=p*2;'*b;p/=2;I=o;s+=1;b*=2
o.show()
```
[Answer]
# [APL (dzaima/APL)](https://github.com/dzaima/APL), ~~109~~ 107 bytes
```
f←{x←⊃P5.size←⍵.sz⋄s←4⋄P5.setup←{0 0P5.G.img P5.img{r←x÷s×2÷x⍴(x÷s)⌿1¯1⋄2|2⍟s+←s:←⍵⌽⍨-r⋄⍉r⌽⍉⍵}⍣{s=x}⍵.mat}}
```
[Try it online!](https://tio.run/##SyzI0U2pSszMTfz/P@1R24TqCiDxqKs5wFSvOLMqFcTp3apXXPWou6UYyDEB0iCp1JLSApBqAwUDINddLzM3XQHIAFLVRUDxisPbiw9PNzq8veJR7xYNEE/zUc9@w0PrDYH6jWqMHvXOL9YGqiu2gljwqGfvo94VukVA2Ue9nUVgbidQvPZR7@LqYtuKWpAjchNLamv//wcA "APL (dzaima/APL) – Try It Online")
-2 bytes from Adám.
A dfn which takes an `APLImg` object as an argument, and displays the dragonized image.
Here are some cool dragons I found:
[](https://i.stack.imgur.com/r5JFu.jpg) [](https://i.stack.imgur.com/8HNRQ.png)
[](https://i.stack.imgur.com/Hb3Nj.jpg) [](https://i.stack.imgur.com/xMZOx.png)
Image courtesy: [ThisGuy](https://unsplash.com/photos/SK6KOj0MaRc) and [GuillaumeDeGermain](https://unsplash.com/photos/vg4QEMxw9-I) on unsplash.
[Answer]
## Haskell + [hip](https://hackage.haskell.org/package/hip), 256 bytes
```
import Graphics.Image
(d?s)w@(x,y)|k<-div s$2^d,k>0,(y,x)<-(d+1)?s$(y,x)=(mod(x+(-1)^(mod(div y k)2+d)*div k 2)s,y)|1>0=w
q::Image VS YCbCr Word8->IO()
q i=writeImageExact JPG[]"o"$backpermute(dims i)(2?rows i)i
main=readImageExact JPG"i">>=either print q
```
I lose a lot of bytes in this answer to weirdness going on in the hip library. Namely I have to use the `Exact` functions for some reason I can only imagine is a bug with the non-exact counter parts, and I have to add a type signature for `q`. I'd also prefer to display the image instead of writing but there is an issue with the native display being non-blocking and when I make it blocking the image is output in negative for some reason. Maybe fiddling with the input format would make this shorter, currently it takes a jpg image stored in a file called `i` and outputs to one called `o`.
[](https://i.stack.imgur.com/WyhHz.jpg) [](https://i.stack.imgur.com/lP322.jpg)
[Answer]
# Mathematica, 177 bytes
It is slow and not fully golfed.
```
r=ImageRotate;r[#2,Pi/2(3-#)]&@@Nest[{#+1,ImageAssemble@MapIndexed[RotateLeft[#,(-1)^#2]&]@ImagePartition[r@#2,Reverse@d/2^{#,#-1}]}&@@#&,{3,#},Log2@Min[d=ImageDimensions@#]-2]&
```
This is Lena:
[](https://i.stack.imgur.com/GcW5w.png)
This is Lena the Dragon:
[](https://i.stack.imgur.com/cQxL1.png)
] |
[Question]
[
There are *n* people on a 2D plane. Using distances between them we're going to find their positions. To get a unique answer you must make four assumptions:
1. There are at least 3 people.
2. The first person is at position (0, 0).
3. The second person is at position (x, 0) for some x > 0.
4. The third person is at position (x, y) for some y > 0.
So your challenge is to write a program or function that given a 2D array of distances (where `D[i][j]` gives the distance between person `i` and `j`) returns a list of their coordinates. Your answer must be accurate to at least 6 significant figures. Shortest solution in bytes wins.
---
### Examples
```
[[0.0, 3.0, 5.0], [3.0, 0.0, 4.0], [5.0, 4.0, 0.0]]
=>
[[0.0, 0.0], [3.0, 0.0], [3.0, 4.0]]
[[0.0, 0.0513, 1.05809686, 0.53741028, 0.87113533], [0.0513, 0.0, 1.0780606,
0.58863967, 0.91899559], [1.05809686, 1.0780606, 0.0, 0.96529704,
1.37140397], [0.53741028, 0.58863967, 0.96529704, 0.0, 0.44501955],
[0.87113533, 0.91899559, 1.37140397, 0.44501955, 0.0]]
=>
[[0.0, 0.0], [0.0513, 0.0], [-0.39, 0.9836], [-0.5366, 0.0295], [-0.8094, -0.3221]]
[[0.0, 41.9519, 21.89390815, 108.37048253, 91.40006121, 49.35063671,
82.20983622, 83.69080223, 80.39436793, 86.5204431, 91.24484876, 22.32327813,
99.5351474, 72.1001264, 71.98278813, 99.8621559, 104.59071383, 108.61475753,
94.91576952, 93.20212636], [41.9519, 0.0, 24.33770482, 144.67214389,
132.28290899, 49.12079288, 85.34321428, 117.39095617, 103.60848008,
79.67795144, 69.52024038, 42.65007733, 105.60007249, 110.50120501,
89.92218111, 60.03623019, 133.61394005, 76.26668715, 130.54041305,
122.74547069], [21.89390815, 24.33770482, 0.0, 130.04213984, 112.98940283,
54.26427666, 71.35378232, 104.72088677, 81.67425703, 90.26668791,
71.13288376, 18.74250061, 109.87223765, 93.96339767, 69.46698314,
84.37362794, 124.38527485, 98.82541733, 116.43603102, 113.07526035],
[108.37048253, 144.67214389, 130.04213984, 0.0, 37.8990613, 111.2161525,
176.70411028, 28.99007398, 149.1355788, 124.17549005, 198.6298252,
126.02950495, 101.55746829, 37.24713176, 152.8114446, 189.29178553,
34.96711005, 180.83483984, 14.33728853, 35.75999058], [91.40006121,
132.28290899, 112.98940283, 37.8990613, 0.0, 111.05881157, 147.27385449,
44.12747289, 115.00173099, 134.19476383, 175.9860033, 104.1315771,
120.19673135, 27.75062658, 120.90347767, 184.88952087, 65.64187459,
183.20903265, 36.35677531, 60.34864715], [49.35063671, 49.12079288,
54.26427666, 111.2161525, 111.05881157, 0.0, 125.59451494, 82.23823276,
129.68328938, 37.23819968, 118.38443321, 68.15130552, 56.84347674,
84.29966837, 120.38742076, 78.30380948, 91.88522811, 72.15031414,
97.00421525, 82.23460459], [82.20983622, 85.34321428, 71.35378232,
176.70411028, 147.27385449, 125.59451494, 0.0, 158.1002588, 45.08950594,
161.43320938, 50.02998891, 59.93581537, 180.43028005, 139.95387244,
30.1390519, 133.42262669, 182.2085151, 158.47101132, 165.61965338,
170.96891788], [83.69080223, 117.39095617, 104.72088677, 28.99007398,
44.12747289, 82.23823276, 158.1002588, 0.0, 136.48099476, 96.57856065,
174.901291, 103.29640959, 77.53059476, 22.95598599, 137.23185588,
160.37639016, 26.14552185, 152.04872054, 14.96145727, 17.29636403],
[80.39436793, 103.60848008, 81.67425703, 149.1355788, 115.00173099,
129.68328938, 45.08950594, 136.48099476, 0.0, 166.89727482, 92.90019808,
63.53459104, 177.66159356, 115.1228903, 16.7609065, 160.79059188,
162.35278463, 179.82760993, 140.44928488, 151.9058635], [86.5204431,
79.67795144, 90.26668791, 124.17549005, 134.19476383, 37.23819968,
161.43320938, 96.57856065, 166.89727482, 0.0, 148.39351779, 105.1934756,
34.72852943, 106.44495924, 157.55442606, 83.19240274, 96.09890812,
61.77726814, 111.24915274, 89.68625779], [91.24484876, 69.52024038,
71.13288376, 198.6298252, 175.9860033, 118.38443321, 50.02998891,
174.901291, 92.90019808, 148.39351779, 0.0, 72.71434547, 175.07913091,
161.59035051, 76.3634308, 96.89392413, 195.433818, 127.21259331,
185.63246606, 184.09218079], [22.32327813, 42.65007733, 18.74250061,
126.02950495, 104.1315771, 68.15130552, 59.93581537, 103.29640959,
63.53459104, 105.1934756, 72.71434547, 0.0, 121.04924013, 88.90999601,
52.48935172, 102.51264644, 125.51831504, 117.54806623, 113.26375241,
114.12813777], [99.5351474, 105.60007249, 109.87223765, 101.55746829,
120.19673135, 56.84347674, 180.43028005, 77.53059476, 177.66159356,
34.72852943, 175.07913091, 121.04924013, 0.0, 93.63052717, 171.17130953,
117.77417844, 69.1477611, 95.81237385, 90.62801636, 65.7996984],
[72.1001264, 110.50120501, 93.96339767, 37.24713176, 27.75062658,
84.29966837, 139.95387244, 22.95598599, 115.1228903, 106.44495924,
161.59035051, 88.90999601, 93.63052717, 0.0, 117.17351252, 159.88686894,
48.89223072, 156.34374083, 25.76186961, 40.13509273], [71.98278813,
89.92218111, 69.46698314, 152.8114446, 120.90347767, 120.38742076,
30.1390519, 137.23185588, 16.7609065, 157.55442606, 76.3634308, 52.48935172,
171.17130953, 117.17351252, 0.0, 145.68608389, 162.51692098, 166.12926334,
142.8970605, 151.6440003], [99.8621559, 60.03623019, 84.37362794,
189.29178553, 184.88952087, 78.30380948, 133.42262669, 160.37639016,
160.79059188, 83.19240274, 96.89392413, 102.51264644, 117.77417844,
159.88686894, 145.68608389, 0.0, 169.4299171, 33.39882791, 175.00707479,
160.25054951], [104.59071383, 133.61394005, 124.38527485, 34.96711005,
65.64187459, 91.88522811, 182.2085151, 26.14552185, 162.35278463,
96.09890812, 195.433818, 125.51831504, 69.1477611, 48.89223072,
162.51692098, 169.4299171, 0.0, 156.08760216, 29.36259602, 11.39668734],
[108.61475753, 76.26668715, 98.82541733, 180.83483984, 183.20903265,
72.15031414, 158.47101132, 152.04872054, 179.82760993, 61.77726814,
127.21259331, 117.54806623, 95.81237385, 156.34374083, 166.12926334,
33.39882791, 156.08760216, 0.0, 167.00907734, 148.3962894], [94.91576952,
130.54041305, 116.43603102, 14.33728853, 36.35677531, 97.00421525,
165.61965338, 14.96145727, 140.44928488, 111.24915274, 185.63246606,
113.26375241, 90.62801636, 25.76186961, 142.8970605, 175.00707479,
29.36259602, 167.00907734, 0.0, 25.82164171], [93.20212636, 122.74547069,
113.07526035, 35.75999058, 60.34864715, 82.23460459, 170.96891788,
17.29636403, 151.9058635, 89.68625779, 184.09218079, 114.12813777,
65.7996984, 40.13509273, 151.6440003, 160.25054951, 11.39668734,
148.3962894, 25.82164171, 0.0]]
=>
[[0.0, 0.0], [41.9519, 0.0], [19.6294, 9.6969], [-88.505, -62.5382],
[-88.0155, -24.6423], [21.2457, -44.5433], [14.7187, 80.8815], [-59.789,
-58.5613], [-29.9331, 74.6141], [34.5297, -79.3315], [62.6017, 66.3826],
[5.2353, 21.7007], [6.1479, -99.3451], [-62.597, -35.7777], [-13.6408,
70.6785], [96.8736, -24.2478], [-61.4216, -84.6558], [92.2547, -57.3257],
[-74.7503, -58.4927], [-55.0613, -75.199]]
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~74~~ 59 [bytes](https://codegolf.meta.stackexchange.com/a/9429/78410)
```
+⍣(0>11○3⊃⊢)p÷×2⊃p←0j1⊥2↑⍉⊃⌹∘⍉⍨/1 .5*⍨2↑8415⌶.5×(⊣.+⍨-⊢)×⍨⎕
```
[Try it online!](https://tio.run/##vZjNjl1HFYXH9FOcWdrQ91A/u/4mSEyRDAOGVg9atOOAOrTlWKCMkUww6SgZWGbChAgpT5CIsd/kvoj59q7T7rMvGaNIzr19T1Xtn7XWXnWunt8crj@/url99v5xPL76@vjqm@NXb37129/8@qMnT8IaLhb@KTFfLJH/9zBqr/q3kpvEkLp@7i3GXHK@vFie3D9tS1nSeqihXrCg95pHbfrTiH2MUoYu2G/78PyyHT1qSaMFuYhrblFCHm2esj/fbX2/4H4HkRIih11ePHmIdB@EHnu/936B7XB5@dHZ4/SjdZG4jhJZnuLaRx6hR9bE0NktSE@FU0ZcJYRQY4osGGsuoeba@NLTmsLouabEl7xW1oeUWNPDmofw1NAvdS0piORomyWRLr1Rn5TWnHJqXYs9BvUoURppt7TGEGKq@pkQO8/cP9RrijPjIGsZocXc84y5sro0i1koTWl1FCIbmTATu@Wqdf@Qs1UgyZpzs2TZRGStLUXJXQ/I5NcTSY1hmccU2kidfvWyZsk8qM2LsZFtGKXGpoFQiECGIfBbG2zYOE9IpQ4tRKJL/CJprSWE1rJFX1jEtyR6cAQPpB/4h7PGOlKKPUa@VIKm3jlEC5CjIoUOga61uqZaK/DQFma2kCD8X79R6SZFWqiGV9dtV4EJeRYHSezcRaNJdIBDkta5CKdIapxkvQGJrdPE2Y@WAjhulKFHEpdUWtB2hC20EW0Rle09KwRiX/UphZfuQHsbAGq1WNtGzQBaSUHppFawFomoE3GjCm1oeBp/L6lJ10V9BbUSZ1VjXQFhyJBMv2WoWRLfi5HWofy09fsKWFFyo2aDOG1jYBxrLEmLS@HZJk4mp77yVGis1E0BTS6lKWY00NiKDOtWJNKaQLYiFGyuIY0SZBj94soaqWDPzk0CyKOVq6QVIIiI1W6sacTWiyaQgTysjHN3CNiz9K2D1mFKbs@VtZVBjKVrFRy7PeJ94/f5T5REkz3CKQp7Ic5GI0QRTDEjHeFM26essLnlYLsSaBzS6qRtK5wB9CcL@CmznYoL8Oe52jIFpKyNqENNtfT50whZmkEjAofeYXroChSIJLGDdj2rK/V5NCmgcgWtgLPkSSTqU6msgcHpmqO6A7xvvCvArEkqaJJAd4Wm6mNWcljrElLQAf5Q9mtXc4@DmaEbgcSOQGZtQu1rLMpbRUapaxcyrW3iPrGCXdosQiZPAlUmsgOyEoZ0E1l6nVJXxVAtLVBAlDmj0QlwbfFbeFKDzCHm1XwvcJ7mDu6@7T79WZHSVctT0VoKQKBToRhxK9Aj5WAFKUEZMGgkMRckLxfUyRIFy5I5bSI781sh8aSKCk35Qyj3aigpgZFqrdd0eqGUMwg6HZAAzUAxArSYoZpB04HblUdGCDfHTqV9r3CO6Q7wvu/7AmzyiizRKiUBLWE6QmEMg2kJLEb5R5yDJI0qnM6erTEetXDb4NSp38sklGIpogKmMgpsyMUu@mBdowCkqNqo4oHckUGZojAYmKUlzazpUZnDzAC58e0HmtN1r2@e5g7uvvEu/1mSCs5HUxHXgU167DS6HlgziQPRqH4oUoYK/UBHnScy2vqwWIBlhetWRorQgAX2yEqCz2BAdKmmOAyZpI9acqJmCaaLPVnwBlC6zgmxNy5ukLt5dqLrTt48zR3gfd9d/rMkAqXJk5THNAhxIASad1YYQnBapL9QTVIoI2mBCjiBjMkMKFiO/DkkVQ8OhN469DmCUFprqfYom6oJhsme69q4Sofb2AbEg2NzDsYPcjfPnKo7dXM838PdNd0nb/VAxzC4WV3MPACBRiVtG7LBCSLgSnb0KVfEK8wiq9FJYlN7FK1/jzZC6AxyNbI2F3qsNSccRqhzoIQBZ8KsgLOp3rY593IyxHezzEu6EzdHco/1fctd9tuoYfqIdlfD6ogRiB5VHSM8l27VM1uW1qJWuopsCs1YZCTIlLcCFWudYkcsNWORRNOJKmnkDE4MBzt/fmJXnW3z7sVPcTfNvK47ffM093D3nXdFsLpgGysbpWaKrRht@nDZ1Lxx5UIJphuPaiF0SIIMaJF1kBm7K1FF9ND8RKOs@Cgtwv5i4l26c6vOsznr4ke4m2Ve1J20eYo7tLvGu9w3k9YoAH2bvAR7TC/@Ux2GY52bRQ4GE3oDaZoE1S1QQmF6HQps0SFbYESz4eAuZP5ysjfp3qp6x@asi5/hfpbtJN0J257jHu3/0/CH7DdZLSpvZGnWtCo56lDjM1UYMYID2QZkUk3mKl/mZIBAYD5vZPhwD3VXMn81cQbd@1Rn2E6sixvhfpadKvpO3TzPHdR9330JtvlL6wBmVLUiGDwNLZ4SrVO9BbzNFhp6x7Arcd6h3B3c3Uf9xcxdT5xJd27V2TbvXtwUd8PMC/te4PYc93A/afwu/c22cgAjLySzUdwOmIiQzO6RlEeHf5b7a@TDiwd3CfeXUX8lczcT59FPzKo3bc68@CHuJ5pTdidvnuke8771rgYbTvQCMXT8yf2URiuHVcK9dDl5AeFv4u4@ur@VufvJiU93ftXbNudfToa5G2pO2p3IebY70PvuuwrMV0hUlxLRZ@PE7nWTf/PiX0G4m7i7j7qbmb@gOKfu/Krzbd7D@Fm@H2lO253Ieao70Lu@u@w/vG08fvHXj9//7Hj37Xn4RYzHt3/Px9d/Ob7@16Pn73549zbx5fnx1dfhD/H4@t9J30re/U0f@PI/xy/@oZ/vvvt5XNbyUz7oz11iOX75/VrevT0/vv52ZefvDrrdu7d8On715j0H6qHPzo53/1x@eX399Hr5@PbFp1cvX/7@j8@Wl7fLp7cvni6/u3l69eLm8@WzT27/vLz8hD/c3r64/uzsT1c3C/Es/8eIz@R492ZQVtavHEcImsD7n5DCq2/Ow5KX8ug8L2GRR@dlkSU8OjscDmf8/jh@@JTsk26lMfzYW@/TF56mWEOdus4PbrrzheABG1EU@QfVRe6ulxf2txD1HfIBJa@S8vbqMIm@7zhw5S0yX5gDrxZ1qqnG9flG5cDMaQyYA3LG9dmeOyT1vnadEhVN4wuTQV93syPixo@2mjBwNApW5KGnSjwFTqhgEEGDnPaUqjuJHZjHeGPbzjKw7ZRfm3k9QDwo0y/gUmUeG0@Znk05qulh1/pczR3N9O4Ag2rZXpLBR3PeB1xIhmJaHlLA12X9I4INg2bWKIe9Izs0te8DOvwX "APL (Dyalog Unicode) – Try It Online")
Lots of golfing at various places thanks to @H.PWiz and @ngn.
Uses the formula shown in [the paper](https://arxiv.org/pdf/1502.07541.pdf) shared by [Jonathan Allan](https://codegolf.stackexchange.com/questions/144053/distances-to-coordinates#comment353150_144053). The formula on the paper involves [EVD (eigenvalue decomposition)](https://en.wikipedia.org/wiki/Eigendecomposition_of_a_matrix), and fortunately Dyalog APL has its generalized version [SVD(singular value decomposition)](https://en.wikipedia.org/wiki/Singular_value_decomposition). For square symmetric matrix \$M\$ as input, it exactly computes orthonormal \$U\$ and the diagonal matrix of eigenvalues \$\Lambda\$ in \$M=U\Lambda U^T\$.
### Ungolfed and how it works
```
f←{
m←×⍨⍵ ⍝ square of distances
v←1⌷m ⍝ first row
G←.5×v+⍤1⍉m-⍤1⍨v ⍝ -(m - column v - row v)÷2
m-⍤1⍨v ⍝ add v to -m by rows (rank 1)
⍉ ⍝ transpose
v+⍤1 ⍝ add v to that by rows
.5× ⍝ halve
U E←2↑8415⌶G ⍝ singular value decomposition
8415⌶G ⍝ SVD built-in
⍝ since G is square and symmetric, it is identical to EVD
⍝ and gives orthonormal U, eigenvalue diagonal E,
⍝ transpose of V (≡ U), and a boolean indicator for success
2↑ ⍝ we need only U and E
pts←0j1⊥⊖(2↑E*.5)+.×⍉U ⍝ compute pts as shown in the paper
⍝ and convert to complex
(2↑E*.5) ⍝ first 2 rows of element-wise sqrt of E
+.×⍉U ⍝ matmul with transposed U
⍝ the resulting matrix is 2-row matrix where
⍝ 1st row is x-coords and 2nd is y-coords
0j1⊥⊖ ⍝ compute x+yi for post-processing
pts←pts×+×2⊃pts ⍝ rotate by 2nd point's angle reversed
2⊃pts ⍝ the 2nd point
× ⍝ signum; unit vector (representing angle)
+ ⍝ complex conjugate (negation of angle)
pts× ⍝ rotate all points by that angle
+⍣(0>11○3⊃pts)⊢pts ⍝ mirror w.r.t. x-axis if 3rd point is below x-axis
+⍣( ) ⍝ conjugate all points (mirror w.r.t. x-axis) if...
3⊃pts ⍝ the 3rd point
11○ ⍝ its complex part
0> ⍝ is negative
}
```
[Answer]
## R, 107
```
function(d){y=t(cmdscale(d))
y=y-y[,1]
p=cbind(c(y[3],-y[4]),y[4:3])%*%y/sum(y[,2]^2)^.5
p*c(1,sign(p[6]))}
```
The big head start is on line 1 where I use R's function for Multi-Dimensional Scaling (MDS). The rest is probably inefficient (thanks for making suggestions on how to improve): line 2 translates the data so that the first point is at (0, 0); line 3 rotates the points so that the second point is at (0,x); line 4 flips everything so that the third point is at y>0.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~183~~ ~~178~~ ~~166~~ ~~161~~ ~~160~~ ~~159~~ ~~158~~ 156 bytes
*Saved 1 byte thanks to @Giuseppe and 2 bytes thanks to @JonathanFrech.*
```
def f(D):
X=D[0][1];o=[0,X];O=[0,0];n=2
for d in D[2:]:y=d[0]**2;x=(y-d[1]**2)/X/2+X/2;y-=x*x;o+=x,;O+=y**.5*(y>d[2]**2-(x-o[2])**2or-1),;n+=1
return o,O
```
[Try it online!](https://tio.run/##fZhLbxw5EoTv/hUNzEWSSzVMMvmy0HPy3VcDDR0MyN71YSRD9gDS/nnvl6yWxawZDAxL3a0imY@IyGB/e/7x34f7@PPn3ecvhy8X7y/fvTl8PL4/hduT3N48HE9h@Xh788F@h9ub@2N8c/jy8Hi4O3y9P7w/xXe3756Pdzx9dRVvno4Xz9d3rOPN5e8ff49v@X/zfH18unq6eXh7fFpuPrw9Pl9drfnq4vmPu1O0J68vnq4feHnJ64fHa7lcbu7fHuXN4fHzj78e7w8Py4efvx3@9/Xb98Onu7vPd@P8H4@f7r/z4s@v9/8hlB8Ph6fl@fDt09fH72@@PfKBLbi4@nJxOoU1LIdkP/IabpfDabwen@r2QT6/Hp/e3l5e/uMW/MiSloPwu4VeWrHPcqoqITZ73apIyinZni9Pj6UsqS2UUBYWtFZSL9X@1KX1nnO3BfO2r88fzkf3kmOvQRdZUxUNqdftlPl8t/XLgpcdVHMQDrtdTq@RzkHYsS97zwv@vSoqa8/C4ihr66mHJqyQ0NgraIuZM7qsGkIoEoUFfU05lFSqLC2uMfSWSozLoaW1sDzEyJIW1tSVh7q9KWuOQTXJ2CuqNm2V4sS4pphibVS6d2qRRSsp17hKCBKLvSbAxiP2zIGHWomyZRt0zT1USS1tERdW50rEXalKrqVn4uqJICObpWIl/5XwSD/qmlIdmbKH6lpqFE2tL5JIrkUy6n1kLTHUHhudanlNmnjO2iZSSTX0XKRaGFQhkF4Ibamd7SqnKXmUbkWItIdFGteSQ6g1jdAza3gX1dISgEDugR9L62uPUZoIpStETKlTsOglcZBQ4xDoVy1rLKUAC2teYgcNyu@8CDWumrWGMmDq2uyy35DO2qCRjZtaLJHic0akxFk5Q2PlnNEV8Fcb3ds6UWMAvZUSNCFrjbkGa1g4B9ZlYQ1FbS1Z66Wt9pChyjagrxXg1JJHw3pJoNiYQNm0FDAmujTCrVSgdovNgm85Vm22pq1gVWUrqJQV7IUEsewdglFz5L2Rx0PbtXyX/SY8lXp1ohz7Al4pkiN1peTsIht3Y1t5KFQW2p6AJeVcDSsWptSsffRJiLNE8AwwQeQaYs9B@2CcrCzRAuTGqVFBtoxS5biCAFUddetr7FJbJvwEzuGhbHvDuZa0nVs3Wku1LcuU15o7EeZmGJj57GHuGu5y39AhQ@UIJhvWlSgrPVBwSx2FXnDi2AZJDjQjjE0JU7rWshG1Zo4A7xv0@VNiN8QEyPNYqYnaUdFKyKHEkkcRkbmQtA5ICDhoDW6HZgCBPCoNjMPZZlznyWg4SgWMAsmcNvJQm0JR81CBScUcuR3K54bvkt/qETMSpBDcEGlqmIwRNE0i3G@gvRvdrZ2pSWc62D4AsKGGyeS0tFWyMdWkKpe1KWnCHwN7ZAGb1K0AiRyJ0sjHBshI6NqGoNLkGJtJhAlnBvcKW3qlB4B5BD9i0xJ0G1ZeuGc5m4ntMe7avUt9q0ZuJtsxG@4VBNCjwDMLFVwt3TCKkYPBvtNBAs4IXMqI0cgSBGvisA3Pib9lsmZeLBCT9yG/SJ/GCDaKvRu5tEwVtxBocYDzxnzDBpBiUDaSsaHajDqDBG5c7UV81rOZ2w7lc7998mcpRYVokiGfNjEDIS2ewLQD3iLxXbaBEXtRzmbLWhmCVrPzdLS53vJGIsOQQHsOEEMzfGITe66souBHTAhNLBA3ws@bCnSmYq7R0qp2UuIsHM7JTWg3tryCezWbie0xPjd8l/tWjgK4ezW9tqFMbmzUG@eVRNIAU8ztCCUoMA5UlO08JljrIxLQWGC3cdsqUMED5sfKgY9gEjQtQ2AYJtGeHJmpOSGorSP@zPSHxCUNFZiMiZvV89TaK7gTs5nYHuVzv3e5b@VQSEyS5Ns3CyAd5pN0MvDBaJpjf6CQxJ97tOJk8AH/4rCWIFj4OESzTJwHoW2ux4VAaq2xNNGzhil2aDzWrGWF1tZ@ngSvbmx2KH5WT1Nrp99Oy2Zmzxifm71LfNQC1cK3JnMp2/5oMZJou5AKHg@pNnYjR6kgVWGrr/mYqGMw92ylbzJmBT1BnXqiq1BiLSniIELZBkfo8CRs2c/2c2fJJneyn9OvE2sn3k7KZlp7gE@t9pmfRwpTRq2tFlRDe8BxL3hBiK1tFG5YrrhmM8hF9SzGDD@0Xzcxy7CvlE3aiKQkDJCSi5iAkS/4GP2fTPfOhjpL5tyJH9TzzNopuFMzR2yP8bnjuwKMmmAIC/vEOsTZoFntYZyNpVq5QEH9zWKLeQSbhCACKiSbV4PPhZgE8RuGoVJRXBIqON80nPP2LtT5sdma@Ck9T6ydfDshm0ntIT433Od9NmCV5OnYRkUgx5DiH5oLrRp3hRQGPOgKRKkaTKVAB0VppZvXVpukGRrUcc@dr1f@tjEZ750F9W5stiZ@TE8Ty4u3k7GZ1TPGXaN3mZ8lNJuYkeLwnMUYUbr5mk1xER@Anygx3EZ@uZDnbQRAGoCezgz4daN0F6z5suFM985/OjO2sybzmHYT62/aPWmZZ/YMcNfvXfrnGUvTwKOYOBEKloXeDlYZx0INeJc@QkHcGGlZxlcX/ibtbpb@mjVfOGbj7V2os2TencyTeh5ZOwmf5Wxm9QzyfcOn1M92lP0ZbNz9jbQYfuYexBpXQkpj8z3p@Ub466sDf5X210p/wZrvGrPv3ptQb8icOZkHtZtbOw13Yua57YDuW@7yP@PD7gTdhpy@TGKEsetgwvSlifsKYX@fdjfL@Y413zic9975UG/JnD9xA9uNLi/iTtI8v2ek@6677Levfygs5aHBgwjTV0WGwtdvTpb5SwR3n3Y3S3fPslBerxzL5L6dD3WezHsUK87rvF5eB5dTcSdpm@i8kNshfZn67TL/9QXhz/8D "Python 2 – Try It Online")
Uses the first 3 points to calculate the rest. Returns a pair of `x-coords, y-coords` [as allowed in comments](https://codegolf.stackexchange.com/questions/144053/distances-to-coordinates/144078#comment353097_144053).
[Answer]
# JavaScript (ES7), ~~202~~ 193 bytes
```
d=>{for(k=7;(a=d.map((r,i)=>[x=(r[0]**2-r[1]**2+a*a)/2/a,(d[0][i]**2-x*x)**.5*(k>>i&1||-1)],a=d[0][1])).some(([x,y],i)=>a.some(([X,Y],j)=>(Math.hypot(x-X,y-Y)-d[i][j])**2>1e-6));k+=8);return a}
```
### Test cases
```
let f =
d=>{for(k=7;(a=d.map((r,i)=>[x=(r[0]**2-r[1]**2+a*a)/2/a,(d[0][i]**2-x*x)**.5*(k>>i&1||-1)],a=d[0][1])).some(([x,y],i)=>a.some(([X,Y],j)=>(Math.hypot(x-X,y-Y)-d[i][j])**2>1e-6));k+=8);return a}
format = a => a.map(JSON.stringify).join`\n`
console.log(format(f([[0.0,3.0,5.0],[3.0,0.0,4.0],[5.0,4.0,0.0]])))
console.log(format(f([[0.0,0.0513,1.05809686,0.53741028,0.87113533],[0.0513,0.0,1.0780606,0.58863967,0.91899559],[1.05809686,1.0780606,0.0,0.96529704,1.37140397],[0.53741028,0.58863967,0.96529704,0.0,0.44501955],[0.87113533,0.91899559,1.37140397,0.44501955,0.0]])))
console.log(format(f([[0.0,41.9519,21.89390815,108.37048253,91.40006121,49.35063671,82.20983622,83.69080223,80.39436793,86.5204431,91.24484876,22.32327813,99.5351474,72.1001264,71.98278813,99.8621559,104.59071383,108.61475753,94.91576952,93.20212636],[41.9519,0.0,24.33770482,144.67214389,132.28290899,49.12079288,85.34321428,117.39095617,103.60848008,79.67795144,69.52024038,42.65007733,105.60007249,110.50120501,89.92218111,60.03623019,133.61394005,76.26668715,130.54041305,122.74547069],[21.89390815,24.33770482,0.0,130.04213984,112.98940283,54.26427666,71.35378232,104.72088677,81.67425703,90.26668791,71.13288376,18.74250061,109.87223765,93.96339767,69.46698314,84.37362794,124.38527485,98.82541733,116.43603102,113.07526035],[108.37048253,144.67214389,130.04213984,0.0,37.8990613,111.2161525,176.70411028,28.99007398,149.1355788,124.17549005,198.6298252,126.02950495,101.55746829,37.24713176,152.8114446,189.29178553,34.96711005,180.83483984,14.33728853,35.75999058],[91.40006121,132.28290899,112.98940283,37.8990613,0.0,111.05881157,147.27385449,44.12747289,115.00173099,134.19476383,175.9860033,104.1315771,120.19673135,27.75062658,120.90347767,184.88952087,65.64187459,183.20903265,36.35677531,60.34864715],[49.35063671,49.12079288,54.26427666,111.2161525,111.05881157,0.0,125.59451494,82.23823276,129.68328938,37.23819968,118.38443321,68.15130552,56.84347674,84.29966837,120.38742076,78.30380948,91.88522811,72.15031414,97.00421525,82.23460459],[82.20983622,85.34321428,71.35378232,176.70411028,147.27385449,125.59451494,0.0,158.1002588,45.08950594,161.43320938,50.02998891,59.93581537,180.43028005,139.95387244,30.1390519,133.42262669,182.2085151,158.47101132,165.61965338,170.96891788],[83.69080223,117.39095617,104.72088677,28.99007398,44.12747289,82.23823276,158.1002588,0.0,136.48099476,96.57856065,174.901291,103.29640959,77.53059476,22.95598599,137.23185588,160.37639016,26.14552185,152.04872054,14.96145727,17.29636403],[80.39436793,103.60848008,81.67425703,149.1355788,115.00173099,129.68328938,45.08950594,136.48099476,0.0,166.89727482,92.90019808,63.53459104,177.66159356,115.1228903,16.7609065,160.79059188,162.35278463,179.82760993,140.44928488,151.9058635],[86.5204431,79.67795144,90.26668791,124.17549005,134.19476383,37.23819968,161.43320938,96.57856065,166.89727482,0.0,148.39351779,105.1934756,34.72852943,106.44495924,157.55442606,83.19240274,96.09890812,61.77726814,111.24915274,89.68625779],[91.24484876,69.52024038,71.13288376,198.6298252,175.9860033,118.38443321,50.02998891,174.901291,92.90019808,148.39351779,0.0,72.71434547,175.07913091,161.59035051,76.3634308,96.89392413,195.433818,127.21259331,185.63246606,184.09218079],[22.32327813,42.65007733,18.74250061,126.02950495,104.1315771,68.15130552,59.93581537,103.29640959,63.53459104,105.1934756,72.71434547,0.0,121.04924013,88.90999601,52.48935172,102.51264644,125.51831504,117.54806623,113.26375241,114.12813777],[99.5351474,105.60007249,109.87223765,101.55746829,120.19673135,56.84347674,180.43028005,77.53059476,177.66159356,34.72852943,175.07913091,121.04924013,0.0,93.63052717,171.17130953,117.77417844,69.1477611,95.81237385,90.62801636,65.7996984],[72.1001264,110.50120501,93.96339767,37.24713176,27.75062658,84.29966837,139.95387244,22.95598599,115.1228903,106.44495924,161.59035051,88.90999601,93.63052717,0.0,117.17351252,159.88686894,48.89223072,156.34374083,25.76186961,40.13509273],[71.98278813,89.92218111,69.46698314,152.8114446,120.90347767,120.38742076,30.1390519,137.23185588,16.7609065,157.55442606,76.3634308,52.48935172,171.17130953,117.17351252,0.0,145.68608389,162.51692098,166.12926334,142.8970605,151.6440003],[99.8621559,60.03623019,84.37362794,189.29178553,184.88952087,78.30380948,133.42262669,160.37639016,160.79059188,83.19240274,96.89392413,102.51264644,117.77417844,159.88686894,145.68608389,0.0,169.4299171,33.39882791,175.00707479,160.25054951],[104.59071383,133.61394005,124.38527485,34.96711005,65.64187459,91.88522811,182.2085151,26.14552185,162.35278463,96.09890812,195.433818,125.51831504,69.1477611,48.89223072,162.51692098,169.4299171,0.0,156.08760216,29.36259602,11.39668734],[108.61475753,76.26668715,98.82541733,180.83483984,183.20903265,72.15031414,158.47101132,152.04872054,179.82760993,61.77726814,127.21259331,117.54806623,95.81237385,156.34374083,166.12926334,33.39882791,156.08760216,0.0,167.00907734,148.3962894],[94.91576952,130.54041305,116.43603102,14.33728853,36.35677531,97.00421525,165.61965338,14.96145727,140.44928488,111.24915274,185.63246606,113.26375241,90.62801636,25.76186961,142.8970605,175.00707479,29.36259602,167.00907734,0.0,25.82164171],[93.20212636,122.74547069,113.07526035,35.75999058,60.34864715,82.23460459,170.96891788,17.29636403,151.9058635,89.68625779,184.09218079,114.12813777,65.7996984,40.13509273,151.6440003,160.25054951,11.39668734,148.3962894,25.82164171,0.0]])))
```
### How?
Let ***di,j*** be the input and ***xi***, ***yi*** be the expected output.
By the challenge rules, we know that:
* For any pair ***(i, j)***: ***di,j = √((xi - xj)² + (yi - yj)²)***
* ***x0 = y0 = y1 = 0***
We can immediately deduce that:
1. ***x1 = d0,1***
2. ***d0,j = √((x0 - xj)² + (y0 - yj)²) = √(xj² + yj²)***
***d0,j² = xj² + yj²***
3. ***d1,j = √((x1 - xj)² + (y1 - yj)²) = √((x1 - xj)² + yj²)***
***d1,j² = (x1 - xj)² + yj² = x1² + xj² + 2x1xj + yj² = d0,1² + xj² + 2d0,1xj + yj²***
**Computing *xj***
By using 2 and 3, we get:
***xj² - (d0,1² + xj² - 2d0,1xj) = d0,j² - d1,j²***
Which leads to:
>
> ***xj = (d0,j² - d1,j² + d0,1²) / 2d0,1***
>
>
>
**Computing *yj***
Now that ***xj*** is known, we have:
***yj² = d0,j² - xj²***
Which gives:
>
> ***yj = ±√(d0,j² - xj²)***
>
>
>
We determine the sign of each ***yj*** by simply trying all possible combinations until we match the original distances. We also have to make sure that we have ***y2 > 0***.
We do that by using the bitmask ***k*** where ***1***'s are interpreted as positive and ***0***'s are interpreted as negative. We start with ***k = 7*** (***111*** in binary) and add ***8*** at each iteration. This way, positive values of ***yj*** are guaranteed to be selected for ***0 ≤ j ≤ 2***. (We could start with ***k = 4*** just as well, because ***y0 = y1 = 0*** anyway. But using ***7*** prevents [negative zeros](https://en.wikipedia.org/wiki/Signed_zero) from appearing.)
[Answer]
# [R](https://www.r-project.org/), ~~227~~ ~~215~~ ~~209~~ ~~176~~ 169 bytes
```
function(d){x=y=c(0,0)
x[2]=a=d[1,2]
d=d^2
i=3:nrow(d)
D=d[1,i]
x[i]=(D+a^2-d[2,i])/2/a
y[3]=e=sqrt(d[1,3]-x[3]^2)
y[i]=(D-d[3,i]+x[3]^2+e^2-2*x[3]*x[i])/2/e
Map(c,x,y)}
```
[Try it online!](https://tio.run/##VZDLbsIwEEX3/oooG2ww4EderuodWzZVd8ZILklRJBTSPNpEVb89tUNTQhaO5869Z0auhqatitfry940Vd55z2vvvS1OTX4tYI0aWJuyvPQw@zQXWJqqzmAjz3X7Bv3DQfvYRz6eSmXLS1430Mc1sh9uC1ciBM4WO/xjU/TdyV6eIMEEgU4xLY1MFcVMg1SmRwZyyZ@K6vplrWA3tnJtjbmWcLcyR7ZOFbMS2rKtAb3iWmay/qga6KxcrzsrHRmyrTFi7dzaVzd5lVkAW7pi6ZiOkoG9KeEJd7hHP8MZeg@PAhdKkQ3Bnj1CyrFH7T8hIkoip4U8DihhibsnMaU85FxjT03uMWojcUIiEmFgE0kScRHFridoIkQYCpeYc@8B72@2iEImYhJgQDc8pgHhIr7NmW/wwJ4SEyIIQkLtNI2Bui87X8MNnuDzxIjQeoHQ8As "R – Try It Online")
Once upon a time, I took a course in Computational Geometry. I'd like to say that helped, but I clearly learned nothing.
Input is an R matrix, with the output a list of 2-element vectors `(x,y)` (which is closer to the spec *and* saves bytes).
The problem here is, of course, the first three points. Once you fix three points, you can compute all the others based on those.
I just used a bit of algebra to simplify things and then noticed that since I'm only using the first 3 points to solve for the others, this all vectorized very neatly.
[Outgolfed by flodel](https://codegolf.stackexchange.com/a/144102/67312)
[Answer]
# JavaScript (ES7), ~~140~~ ~~139~~ ~~126~~ ~~121~~ ~~118~~ 117 bytes
*Saved 1 byte thanks to @Giuseppe.*
```
/* this line for testing only */ f =
D=>D.map((d,n)=>n>1?(y=d[0]**2,D[n]=x=(y-d[1]**2)/X/2+X/2,y-=x*x,[x,y**.5*(y>d[2]**2-(x-D[2])**2||-1)]):[X=n*d[0],0])
```
```
<!-- HTML for testing only --><textarea id="i" oninput="test()">[[0.0, 0.0513, 1.05809686, 0.53741028, 0.87113533], [0.0513, 0.0, 1.0780606, 0.58863967, 0.91899559], [1.05809686, 1.0780606, 0.0, 0.96529704, 1.37140397], [0.53741028, 0.58863967, 0.96529704, 0.0, 0.44501955], [0.87113533, 0.91899559, 1.37140397, 0.44501955, 0.0]]</textarea><pre id="o"></pre><script>window.onload=test=function(){try{document.querySelector("#o").innerHTML=JSON.stringify(f(JSON.parse(document.querySelector("#i").value)))}catch(e){}}</script>
```
Works somewhat like my Python answer. Returning `[x,y]` pairs turned out much shorter than separate X and Y lists in JS. Overwrites the argument list, so don't use it as input multiple times.
[Answer]
# Mathematica, 160 bytes
```
(s=Table[0{,},n=Tr[1^#]];s[[2]]={#[[1,2]],0};f@i_:=RegionIntersection~Fold~Table[s[[j]]~Circle~#[[j,i]],{j,i-1}];s[[3]]=Last@@f@3;Do[s[[i]]=#&@@f@i,{i,4,n}];s)&
```
The program use built-in `RegionIntersection` to calculate intersection point of circles. Program requires exact coordinate to work.
This assumes `RegionIntersection` always make the point with higher y-coordinate the last one in its result if the x-coordinate is equal. (at least it is true on Wolfram Sandbox)
For some reason `RegionIntersection` doesn't work if there is too many circles in its input so I have to process each pair once by using `Fold`.
Demonstrate screenshot:[](https://i.stack.imgur.com/1eanM.png)
] |
[Question]
[
This challenge is to score a Cribbage hand. If you don't play Cribbage, you've got some learning to do. We play with a standard poker deck, and a hand consists of four cards plus the "up card". There are two types of hand: normal, and a 'crib hand'.
Cards come in the format `vs` where `v` is one of: `A23456789TJQK` (T for ten) and `s` is one of `SCDH`. A hand will be given in the form (for example)
```
AS 2D 3H JS | 4S
```
where `4S` is the up card. A crib hand will have the format
```
JD 3C 4H 5H | 5S !
```
Face cards have a value of 10, and the ace has a value of 1. Scoring is performed as follows.
* Fifteens: for each subset of five cards whose sum is 15, add two points.
* Pairs: for each pair of cards with the same rank (not value), add two points.
* Runs: for each maximal run of consecutive cards of length longer than 2, add the length of the run in points.
* Flush: if all five cards are the same suit, add five points. Otherwise, if all but the up card are the same suit, add four points. If this is a crib hand, the four-point variant is not counted.
* Nobs: if there is a jack in hand with the same suit of the up card, add one point.
**Notes:**
* Triples and fours of a kind are not special -- there are three pairs in a triple, so a triple is worth 6 points.
* Runs can overlap. For example, `AS AH 2D 3C | 2C` (a double double run) has four runs of length 3 and two pair, so is worth 3+3+3+3+2+2 = 16 points.
* Only maximal runs are counted, so `KS QD JD TC | 9S` is worth 5 points, since it is a run of 5. The sub-runs are not counted.
**House Rule:**
It's impossible to score 19 points in a hand. Instead of zero, report a score of 19.
**Examples:**
```
5S 5H 5D JS | KS
21
AS 2D 3H JS | 4S !
9
JD 3C 4H 5H | 5S
12
9S 8S 7S 6S | 5H !
9
9S 8S 7S 6S | 5H
13
8D 7D 6D 5D | 4D !
14
8D 7D 6D 5D | 4D
14
AD KD 3C QD | 6D
19
```
This is code golf. Shortest solution wins.
[Answer]
## C, 364 388 chars
It's big and ugly (though not as big as it once was):
```
char*L="CA23456789TJQKDHS",b[20],p[15],r[5],s[5],v,i=4,t,m,q;
g(j){++p[r[i]=strchr(L,b[j])-L];s[i]=strchr(L,b[j+1])-L;}
f(j,u){u==15?v+=2:++j<5&&f(j,u,f(j,u+(r[j]>9?10:r[j])));}
main(){gets(b);for(g(14);i--;r[i]^11|s[i]^s[4]||++v)g(i*3);
for(f(i,0);++i<15;v+=q?q*q-q:t>2?t*m:0,t=q?t+1:0,m=q?m*q:1)q=p[i];
while(++t<5&&s[t]==*s);v+=t>4-!b[16]?t:0;printf("%d\n",v?v:19);}
```
(Line breaks were added to make it easier to read; those aren't included in the above tally.)
The problem description didn't specify if the code needed to check for invalid input, so naturally I assumed that the program was free to misbehave at will if the input, say, contained extra whitespace.
Here's the ungolfed version:
```
#include <stdio.h>
#include <string.h>
/* A-K correspond to values 1-13. Suit values are arbitrary.
*/
static char const *symbols="CA23456789TJQKDHS";
/* Used as both an input buffer and to bucket cards by rank.
*/
static char buf[20];
/* The cards.
*/
static int rank[5], suit[5];
/* The cards broken down by rank.
*/
static int buckets[15];
static int score;
static int touching, matching, i;
/* Read card number i from buf at position j.
*/
static void getcard(int j)
{
rank[i] = strchr(symbols, buf[j]) - symbols;
suit[i] = strchr(symbols, buf[j+1]) - symbols;
++buckets[rank[i];
}
/* Recursively find all combinations that add up to fifteen.
*/
static void fifteens(int j, int total)
{
for ( ; j < 5 ; ++j) {
int subtotal = total + (rank[j] > 9 ? 10 : rank[j]);
if (subtotal == 15)
score += 2;
else if (subtotal < 15)
fifteens(j + 1, subtotal);
}
}
int main(void)
{
fgets(buf, sizeof buf, stdin);
score = 0;
/* Read cards from buf */
for (i = 0 ; i < 4 ; ++i)
getcard(i * 3);
getcard(14);
/* Score fifteens */
fifteens(0, 0);
/* Score any runs and/or pairs */
touching = 0;
matching = 1;
for (i = 1 ; i < 15 ; ++i) {
if (buckets[i]) {
score += buckets[i] * (buckets[i] - 1);
++touching;
matching *= buckets[i];
} else {
if (touching > 2)
score += touching * matching;
touching = 0;
matching = 1;
}
}
/* Check for flush */
for (i = 1 ; i < 5 && suit[i] == suit[0] ; ++i) ;
if (i >= (buf[17] == '!' ? 5 : 4))
score += i;
/* Check for hisnob */
for (i = 0 ; i < 4 ; ++i)
if (rank[i] == 11 && suit[i] == suit[4])
++score;
printf("%d\n", score ? score : 19);
return 0;
}
```
[Answer]
## Ruby 1.9, 359 356
It's far too long - almost as much as the C solution.
```
R='A23456789TJQK'
y=gets
f=y.scan /\w+/
o=f.map(&:chr).sort_by{|k|R.index k}
s=0
2.upto(5){|i|o.combination(i){|j|t=0
j.map{|k|t+=k==?A?1:k<?:?k.hex: 10}
(t==15||i<3&&j.uniq!)&&s+=2}}
m=n=l=1
(o+[z=?_]).map{|k|k[z]?n+=1:R[z+k]?(m*=n
l+=n=1):(l>2&&s+=l*m*n
l=n=m=1)
z=k}
x=f.take_while{|k|k[y[1]]}.size
x>(y[?!]?4:3)&&s+=x
y[?J+f[4][1]+' ']&&s+=1
p s>0?s:19
```
[Answer]
# Something to begin with.. Ruby, ~~422 365 355~~ 352
```
c=gets
a,b=c.scan(/(\w)(\w)/).transpose
f=->x{x.uniq.size<2}
s=f[b]?5:!c[/!/]&f[b[0,4]]?4:0
c[/J(.).*\1 ?!?$/]&&s+=1
s+=[5,4,3].map{|i|a.permutation(i).map{|x|'A23456789TJQK'[x*'']?i:0}.inject :+}.find{|x|x>0}||0
a.map{|x|s+=a.count(x)-1}
2.upto(5){|i|s+=2*a.map{|x|x.tr(?A,?1).sub(/\D/,'10').to_i}.combination(i).count{|x|x.inject(:+)==15}}
p s<1?19:s
```
Slightly ungolfed:
```
def t(c)
s=0
if c.scan(/[SDHC]/).uniq.size<2 # Flush
s+=5
elsif c[0..9].scan(/[SDHC]/).uniq.size<2 && c[-1]!=?! # Flush
s+=4
end
s+=1 if c =~ /J(.).*(\1$|\1\s.$)/ # Nobs
c=c.scan(/[^ \|]+/).map{|x|x[0]}[0..4]
d = (3..5).map{|i|c.permutation(i).map{|x| 'A23456789TJQK'.include?(x*'') ? i : 0}.inject(:+)}.reverse.find{|x|x>0} || 0# Runs
s+=d
c.map{|x|s+=c.count(x)-1} # Pairs
c.map!{|x|x.tr('A','1').gsub(/[JQK]/,'10').to_i}
(2..5).map{|i|s+=2*c.combination(i).count{|x|15==x.inject(:+)}} # 15s
s<1 ? 19 : s
end
```
Unit tests for golfed version:
```
require "test/unit"
def t(c)
c=gets
a,b=c.scan(/(\w)(\w)/).transpose
f=->x{x.uniq.size<2}
s=f[b]?5:!c[/!/]&f[b[0,4]]?4:0
c[/J(.).*\1 ?!?$/]&&s+=1
s+=[5,4,3].map{|i|a.permutation(i).map{|x|'A23456789TJQK'[x*'']?i:0}.inject :+}.find{|x|x>0}||0
a.map{|x|s+=a.count(x)-1}
2.upto(5){|i|s+=2*a.map{|x|x.tr(?A,?1).sub(/\D/,'10').to_i}.combination(i).count{|x|x.inject(:+)==15}}
p s<1?19:s
end
class Test1 < Test::Unit::TestCase
def test_simple
assert_equal 21, t("5S 5H 5D JS | KS")
assert_equal 21, t("JS 5H 5D 5S | KS")
assert_equal 12, t("JD 3C 4H 5H | 5S")
assert_equal 13, t("9S 8S 7S 6S | 5H")
assert_equal 14, t("8D 7D 6D 5D | 4D")
assert_equal 19, t("AD KD 3C QD | 6D")
assert_equal 9, t("AS 2D 3H JS | 4S !")
assert_equal 9, t("JS 2D 3H AS | 4S !")
assert_equal 14, t("8D 7D 6D 5D | 4D !")
assert_equal 9, t("9S 8S 7S 6S | 5H !")
end
end
```
Results:
```
% ruby ./crib.rb
Run options:
# Running tests:
21
21
12
13
14
19
9
9
14
9
.
Finished tests in 0.014529s, 68.8281 tests/s, 688.2813 assertions/s.
1 tests, 10 assertions, 0 failures, 0 errors, 0 skips
```
[Answer]
# Python, 629 characters
I'm only posting mine because no one else has. It's pretty long :(
```
g=range
i=raw_input().split()
r,u=zip(*[tuple(x)for x in i if x not in'!|'])
v=map(int,[((x,10)[x in'TJQK'],1)[x=='A']for x in r])
z=list(set(map(int,[(x,dict(zip('ATJQK',[1,10,11,12,13])).get(x))[x in'ATJQK']for x in r])))
z.sort()
z=[-1]*(5-len(z))+z
s=p=l=0
for a in g(5):
for b in g(a+1,5):
s+=2*(v[a]+v[b]==15)
p+=2*(r[a]==r[b])
if z[a:b+1]==g(z[a],z[b]+1)and b-a>1:l=max(l,b+1-a)
for c in g(b+1,5):s+=2*(v[a]+v[b]+v[c]==15)
for d in g(5):s+=2*(sum(v)-v[d]==15)
n=len(set(u))
s+=4*(n==2 and u[-1] not in u[:4] and i[-1]!='!')+5*(n<2)+('J'+u[4]in i[:4])+2*(sum(v)==15)+p+((l*3,l*p)[p<5]or l)
print(s,19)[s<1]
```
[Answer]
### GolfScript, 187 178 174 characters
```
:c"J"c{"SCDH"?)},1/:s-1=+/,([s)-!5*s);)-!4*c"!"?)!*]$-1=+0.14,{c{"A23456789TJQK"?)}%{},:v\{=}+,,.{@*\)}{;.2>**+1 0}if}/;;5-v{{=+}+v\/}/[0]v{.9>{;10}*{1$+}+%}/{15=},,2*+.!19*+
```
Since I never played cribbage I don't know any fancy scoring tricks. Therefore I thought the only way to compete (at least a little bit) is using a golf language. The code is pretty plain GolfScript, the test cases can be found [here](http://golfscript.apphb.com/?c=ewo6YyJKImN7IlNDREgiPyl9LDEvOnMtMT0rLywoW3MpLSE1KnMpOyktITQqYyIhIj8pISpdJC0xPSswLjE0LHtjeyJBMjM0NTY3ODlUSlFLIj8pfSV7fSw6dlx7PX0rLCwue0AqXCl9ezsuMj4qKisxIDB9aWZ9Lzs7NS12e3s9K30rdlwvfS9bMF12ey45Pns7MTB9KnsxJCt9KyV9L3sxNT19LCwyKisuITE5KisKfTpDT0RFOwoKOyI1UyA1SCA1RCBKUyB8IEtTIglDT0RFIHAJIyAyMQo7IkFTIDJEIDNIIEpTIHwgNFMgISIJQ09ERSBwCSMgOQo7IkpEIDNDIDRIIDVIIHwgNVMiCUNPREUgcAkjIDEyCjsiOVMgOFMgN1MgNlMgfCA1SCAhIglDT0RFIHAJIyA5CjsiOVMgOFMgN1MgNlMgfCA1SCIJQ09ERSBwCSMgMTMKOyI4RCA3RCA2RCA1RCB8IDREICEiCUNPREUgcAkjIDE0CjsiOEQgN0QgNkQgNUQgfCA0RCIJQ09ERSBwCSMgMTQKOyJBRCBLRCAzQyBRRCB8IDZEIglDT0RFIHAJIyAxOQo%3D).
The code in a more readable fashion (*reformatted and ungolfed a little*):
```
# Save cards to <c>
:c;
# Is it a non-crib hand? <r>
c"!"?)!:r;
# Values go to <v>
c{"A23456789TJQK"?)}%{},:v;
# Suits go to <s>
c{"SCDH"?)},1/:s;
# Print score for Fifteens
[0]v{.9>{;10}*{1$+}+%}/{15=},,2* .p
# Print score for Pairs
-5v{{=+}+v\/}/ .p
# Print score for Runs
0..14,{v\{=}+,,.{*\)\}{;\.2>**+0 1}if}/;; .p
# Print score for Flush
[s)-!5*s);)-!4*r*]$-1= .p
# And finally print the score for Nobs
c"J"s-1=+/,( .p
# Sum up the sub-scores and if score is zero set to 19
++++
.!19*+
```
*Edit:* Changed logic for fifteens and flushes.
[Answer]
# Python 2, ~~606~~ 584 bytes
Saved 22 bytes due to [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king)'s golfing.
```
from itertools import*
s,S,C,E=sum,sorted,combinations,enumerate
def f(a):a=a.split();a.pop(4);e=a.pop(5)if a[-1]<"$"else 0;b=S("A23456789TJQK".index(i)for i,j in a);d=S(set(b));h=[j for i,j in a];z=len([s(k)for r in range(6)for k in C([[10,k+1][k<10]for k in b],r)if s(k)==15])*2+s(2for i,j in C(b,2)if i==j)+[4*(e<1),5][len(set(h))<2]*(len(set(h[:4]))<2)+(a[4][1]in[j for i,j in a[:4]if i=="J"])+s(reduce(lambda x,y:x*y,[b.count(k)for k in m])*len(m)for m in[d[s(x[:i]):s(x[:i])+j]for x in[[len(list(e))for i,e in groupby(j-i for i,j in E(d))]]for i,j in E(x)if j>2]);return z or 19
```
[Try it online!](https://tio.run/##fZLNbqMwFIX3eYpbNAs7caNAIX@EkapQKUpWFbOzvIDgNCZgkDESqfruGUw6UdLF7Ozz3eN7fO3qrI@ldC6XgyoLEJorXZZ5DaKoSqWHg5pEZE3egropSN0pPCX7skiEjLUoZU24bAquYs0HKT/AAcV4GQfxuK5yoRH243FVVsjFPg@uSw@LA8T02WYr65fF85rDxE@CCFmvzovrTWfzxZ/t@84aC5nyFgl8KBUIkoGQEGM/7SprrlGCsX8MaAb3mPmfQc4lojU69T5lZBXLD46mvXAywhpRak/IaWQzelrZE3YjCSPK5DP@ILA9hofOqEbOXZM1SohjakQQZHhE3SHiKxsTj1HT2mQ7Yrxy2BDd9nTpMqPhEYqpy6jNhPwR3ZRcD7W2FsNdU8XTZs9RHhdJGkNLzst2eCY0Ge/LRurvC/apiy6m6VX0UveIkqbdCFq6FAwv/y1GWX/P1uA@ai5qjTj@HjA3J32osqmSM8qexX26N5RizNiD0poZZL8dhn3FdaMkfELH7cWlUkLq7idYXgTeBrwQthF8wS6y8ODGXiNwQnjZXJkbwdM93XZoDe7G@L/Ae3AuIphHMItgapxdwdP/6D2bhzALYRqaSF3P8NH5kz6kDWHXR3o3bNqxy18 "Python 2 – Try It Online")
Slightly shorter than [grc](https://codegolf.stackexchange.com/a/5581/73368)'s answer, and takes a different route to get there.
## Explanation:
```
# import everything from "itertools" library. We only need "combinations" and "groupby".
from itertools import*
# alias functions to shorter names
s,S,C,E=sum,sorted,combinations,enumerate
# function f which takes the hand+up card+crib string as its argument
def f(a):
# convert space-separated string into list of items.
a=a.split()
# remove the 4th index, which is always "|".
a.pop(4)
# change golfed by Jo King
# if the final item in the list is a "!" (if it is <"$"), remove it from the list and assign it to variable "e".
# otherwise, assign 0 to variable "e".
# a non-empty string will evaluate to True and 0 will evaluate to False in IF checks later.
e=a.pop(5)if a[-1]<"$"else 0
# for each card in the list, split the identifiers into the value(i) and the suit(j).
# return the value's index in the string "A23456789TJQK".
# so, ["5S", "5H", "5D", "JS", "KS"] will return [4, 4, 4, 10, 12].
# using the aliased built-in function sorted(), sort the list numerically ascending.
b=S("A23456789TJQK".index(i)for i,j in a)
# get the unique items in b, then sort the result numerically ascending.
d=S(set(b))
# for each card in the list, split the identifiers into the value(i) and the suit(j).
# return the suits.
h=[j for i,j in a]
# fifteens
# changes golfed by Jo King
# generate pairs of (10, value + 1) for all cards (since they are zero-indexed)
# since True and False evaluate to 1 and 0 in python, return 10 if k>=10
# and reduce all values >10 to 10
# get all unique combinations of cards for 5 cards, 4 cards, 3 cards, 2 cards, and 1 card
# add the values of all unique combinations, and return any that equal 15
# multiply the number of returned 15s by 2 for score
z=len([s(k)for r in range(6)for k in C([[10,k+1][k<10]for k in b],r)if s(k)==15])*2
+
# pairs
# using itertools.combinations, get all unique combinations of cards into groups of 2.
# then, add 2 for each pair where both cards have an identical value.
s(2for i,j in C(b,2)if i==j)
+
# flush
# changes golfed by Jo King
# using list indexing
# [4 * (0 if crib else 1), 5], get item at index [0 if more than one suit in hand+up card else 1]
# -> 4 if not crib and not all suits same
# -> 5 if all cards same
# -> 0 otherwise
# * (0 if more than one suit in hand else 1)
# -> 4 * 0 if not crib and not all suits same
# -> 4 * 1 if not crib and all suits same
# -> 5 * 1 if all cards same
# -> 0 otherwise
[4*(e<1),5][len(set(h))<2]*(len(set(h[:4]))<2)
+
# nobs
# check if the suit of the 5th card (4, zero-indexed) matches the suit of any of the other 4 cards, and if it does is that card a Jack
(a[4][1]in[j for i,j in a[:4]if i=="J"])
+
# runs
s(reduce(lambda x,y:x*y,[b.count(k)for k in m])*len(m)for m in[d[s(x[:i]):s(x[:i])+j]for x in[[len(list(e))for i,e in groupby(j-i for i,j in E(d))]]for i,j in E(x)if j>2])
# since only 0 evaluates to false, iff z==0 return 19, else return z.
print z or 19
```
## Explanation for runs logic specifically:
```
# for each index and value in the list, add the value minus the index
# since the list is sorted and reduced to unique values, this means adjacent values will all be the same value after offset
# ex: "JD 3C 4H 5H | 5S" -> [2, 3, 4, 10] - > [2, 2, 2, 7]
z = []
for i,j in enumerate(d):
z.append(j-i)
# group the values by unique value
# then add the length of the groups to the list
# ex: [2, 2, 2, 7] -> [2:[2,2,2], 7:[7]]
# [2:[2,2,2], 7:[7]] -> [[3], [1]]
w = []
for i,e in groupby(z):
w.append([len(list(e))])
# list is double-nested so that the combined list comprehension leaves "x" available in both places it is needed
z = []
for x in w:
for i,j in enumerate(x):
if j>2:
# if the group length is larger than 2
# slice the list of unique card values to obtain only run values
# since the run can be anywhere in the list, sum the preceding lengths to find the start and end index
a = d[ sum(x[:i]) : sum(x[:i])+j ]
z.append(a)
w = []
for m in z:
# get the number of times the value is in the entire hand
# ex: "JD 3C 4H 5H | 5S" -> [2,3,4,4,10] and (2,3,4) -> [1, 1, 2]
a = [b.count(k)for k in m]
# multiply all values together
# [1, 1, 2] = 1*1*2 = 2
a = reduce(lambda x,y:x*y, a)
# length of the run * number of duplicate values
a *= len(m)
w.append(a)
# sum the results of the runs
return sum(w)
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 106 bytes
```
Çí╬Δ╓↔╥.L§º♦½┌§└─»◄G≤n▒HJ♀p$¼♥,Q¢▲»Δ÷♠º≈r↑Vo\b■┌4Üé∟]e:┬A½f║J4σ↔└ΓW6O?╧φ¡╫╠├√├ùß5₧k%5ê╜ò/Φ/7w╠█91I◘┬n≥ìk♂╪
```
[Run and debug online!](https://staxlang.xyz/#p=80a1ceffd61dd22e4c15a704abda15c0c4af1147f36eb1484a0c7024ac032c519b1eaffff606a7f77218566f5c62feda349a821c5d653ac241ab66ba4a34e51dc0e257364f3fcfedadd7ccc3fbc397e1359e6b253588bd952fe82f3777ccdb39314908c26ef28d6b0bd8&i=5S+5H+5D+JS+%7C+KS%0AAS+2D+3H+JS+%7C+4S+%21%0AJD+3C+4H+5H+%7C+5S%0A9S+8S+7S+6S+%7C+5H+%21%0A9S+8S+7S+6S+%7C+5H%0A8D+7D+6D+5D+%7C+4D+%21%0A8D+7D+6D+5D+%7C+4D%0AAD+KD+3C+QD+%7C+6D&a=1&m=2)
Bonus for CP437: See those suits symbol in the packed Stax? Too bad that the clubs do not appear ...
The ASCII equivalent is
```
jc%7<~6(4|@Y{h"A23456789TJQK"I^mXS{{A|mm|+15=_%2=_:u*+f%HxS{{o:-u1]=f{%mc3+|Msn#*+y{H"SHCD"ImY:uc5*s!yNd:u;**HH++yN|Ixs@11#+c19?
```
## Explanation
```
jc%7<~6(4|@Y...X...Y...c19?
j Split on space
c%7<~ Is it a crib hand? Put it on input stack for later use
6( Remove "!" if it exists
4|@ Remove "|"
Y Store list of cards in y
...X Store ranks in x
... Perform scoring for ranks
Y Store suits in y
... Perform scoring for suits
c19? If the score is 0, change it to 19
{h"..."I^mX
{ m Map each two character string to
h The first character
"..."I^ 1-based index of the character in the string
S{{A|mm|+15=_%2=_:u*+f%H
S Powerset
{ f%H Twice the number of elements that satisfy the predicate
{A|mm Value of card. Take the minimum of the rank and 10
|+15= Sum of values equal 15 (*)
_%2= Length is 2 (**)
_:u All elements are the same (***)
*+ ( (***) and (**) ) or (*)
xS{{o:-u1]=f{%mc3+|Msn#*+
xS Powerset of ranks
{ f Filter with predicate
{o Sort
:-u Unique differences between elements
1]= Is [1]
{%mc Length of all runs
3+|M Maximum of all the lengths and 3
sn# Number of runs with maximal length
* Multiplied by its length
+ Add to score
y{H"SHCD"ImY
y{ mY For each two character string
H"SHCD"I 0-based index of the second character in the string "SHCD"
:uc5*s!yNd:u;**HH++
:uc5* 5 points if all cards have same suit
s! Not all cards have same suit (#)
yNd:u First four cards have same suit (##)
; Not a crib hand (###)
**HH++ 4 points if (#) and (##) and (###), add to score
yN|Ixs@11#+
yN|I Index of cards with the same suit of last card (not including itself)
xs@ The rank at these indices
11# Number of Jacks with the same suit of last card
+ Add to score
```
] |
[Question]
[
Problem 4 in the [2019 BMO, Round 1](https://bmos.ukmt.org.uk/home/bmo1-2020.pdf) describes the following setup:
>
> There are \$2019\$ penguins waddling towards their favourite restaurant. As
> the penguins arrive, they are handed tickets numbered in ascending order
> from \$1\$ to \$2019\$, and told to join the queue. The first penguin starts the queue.
> For each \$n > 1\$ the penguin holding ticket number \$n\$ finds the greatest \$m < n\$
> which divides \$n\$ and enters the queue directly behind the penguin holding
> ticket number \$m\$. This continues until all \$2019\$ penguins are in the queue.
>
>
>
The second part of the question asked candidates to determine the penguins standing directly in front of, and directly behind, penguin \$33\$. This could be done by examining the patterns in the queue, considering prime factors: see the online [video solutions](https://bmos.ukmt.org.uk/solutions/bmo1-2020/) for more information.
---
## The Challenge
Your task is to design a program or function which, given a positive integer \$k\$ representing the penguin with ticket number \$k\$, outputs the ticket numbers of the penguins *directly before and after* this penguin.
For example, penguin \$33\$, stands directly behind \$1760\$ and directly in front of \$99\$, so the program should output, in some reasonable format, \$[1760, 99]\$.
---
## Rules
* The input will be an integer in the range \$1 < k \le 2019\$.
* Your program should output two integers, in any reasonable format, representing the ticket numbers of the penguins before and after.
* These can be output in any order, (front first or behind first) but this order must be consistent.
* The penguin will not be at the front or back of the queue: so you don't have to handle the edge cases of \$k = 1\$ or \$k = 1024\$.
* As penguins find it difficult to read human glyphs, your program should be as short as possible. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") - so the shortest program (in bytes) wins!
---
## Test Cases
These outputs are given in the format `[front, behind]`.
```
33 -> [1760, 99]
512 -> [256, 1024]
7 -> [1408, 49]
56 -> [28, 112]
1387 -> [1679, 1241]
2019 -> [673, 1346]
2017 -> [1, 2011]
2 -> [1536, 4]
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~79~~ ~~76~~ 71 bytes
```
{($!=sort {[R,] -$_,{first $_%%*,$_^..1}...1},^2020)[+(@$!...$_)X-2,0]}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WkNF0bY4v6hEoTo6SCdWQVclXqc6LbOouERBJV5VVUtHJT5OT8@wVg9E6MQZGRgZaEZrazioKAJFVOI1I3SNdAxia/8XJ1YqpGkYG2ta/wcA "Perl 6 – Try It Online")
Sorts numbers 1 to 2019 lexicographically by the reversed, negated sequence of largest divisors, then finds the neighbors. Example mappings:
```
1760 => (-1 -11 -55 -110 -220 -440 -880 -1760)
33 => (-1 -11 -33)
99 => (-1 -11 -33 -99)
```
In other words, the negated cumulative product of prime factors in descending order.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
⁽¥ØÆfṚNƊÞṣị"@Ø.
```
A monadic Link accepting an integer between 1 and 2019 \* which yields a list of two integers, `[in-front, behind]`.
\* If `1` or `1024` is input the missing ticket number will be shown as `0`.
**[Try it online!](https://tio.run/##ASkA1v9qZWxsef//4oG9wqXDmMOGZuG5mk7GisOe4bmj4buLIkDDmC7///8zMw "Jelly – Try It Online")**
### How?
```
⁽¥ØÆfṚNƊÞṣị"@Ø. - Link: n
⁽¥Ø - literal 2019
Þ - sort (range [1..2019]) by:
Ɗ - last three links as a monad:
Æf - prime factorisation (e.g. 1100 -> [2,2,5,5,11])
Ṛ - reversed
N - negated
ṣ - split at (n)
Ø. - literal [0,1]
@ - with swapped arguments:
" - zip with:
ị - index into (1-based & modular)
- i.e. [last of left list, first of right list]
```
[Answer]
# JavaScript (ES6), ~~105 ... 101~~ 100 bytes
A straightforward implementation that builds the full queue and looks for the penguin with the input ticket within it.
Returns `[front, behind]`.
```
k=>[eval("for(n=q=[];m=++n%2020;q.splice(q.indexOf(m),0,n))while(n%--m)q")[i=q.indexOf(k)+1],q[i-2]]
```
[Try it online!](https://tio.run/##bcrdCoMgGADQ@z1GEPhRhhr7I9wr7AHEiyjdLNOs0fb2bndjuNvDGdqtXbvFzA/sfK@i5nHkF6G21qJM@wU5HriQzcSLwuWMMNKEap2t6RQKlXG9el01mqAkpQN43o1VyOUYTxAyEIZ/zwgFlWUQBjMpY@fd6q2qrL8hjeoaYPdLe8oSO6brkBCtT@ljhJ7/4WfGNw "JavaScript (Node.js) – Try It Online")
### Commented
The code in `eval()` builds and returns the queue in reverse order:
```
for( // outer loop:
n = q = []; // q[] = queue, n = counter (initially zero'ish)
m = ++n % 2020; // increment n; set m to n mod 2020, so that we
// stop when n = 2020
q.splice( // after each iteration:
q.indexOf(m), 0, n // insert n before m in q[] (should be *after* m to build
) // the queue from first to last, but it's shorter this way)
) while(n % --m) // inner loop: decrement m until it divides n
q // dummy loop statement so that q[] is returned by eval()
```
which gives \$q[\:]=[1024,512,...,2017,1]\$.
Wrapper code:
```
k => [ // k = input
eval("...") // build q[]
[i = q.indexOf(k) + 1], // return the element after k ('in front of')
q[i - 2] // and the element before k ('behind')
] //
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~16~~ 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Ž7ëLΣÒR(}ûI¡€θ¨
```
Port of [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/196778/52210), so make sure to upvote him!
-1 byte thanks to *@Grimmy*.
Outputs in the order `[front, behind]`.
[Try it online](https://tio.run/##ASUA2v9vc2FiaWX//8W9N8OrTM6jw5JSKH3Du0nCoeKCrM64wqj//zMz) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKS/f@je80Pr/Y5t/jwpCCN2sO7Kw8tfNS05tyOQyv@6/yPNjbWMTU00jHXMTXTMTS2MNcxMjC0BBHmsQA).
**Explanation:**
```
Ž7ë # Push compressed integer 2019
L # Pop and push a list in the range [1,2019]
Σ # Sort this list by:
Ò # Get the prime factors (with duplicates)
R # Reverse it
( # Negate each inner value
}û # After the sort: palindromize this list ([a,b,c] → [a,b,c,b,a])
I¡ # Split this pallindromized list by the input-integer
€θ # For each inner list: only leave the last value
¨ # And remove the last value, so the pair remains
# (after which this pair is output implicitly as result)
```
[See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `Ž7ë` is `2019`.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~137~~ ~~133~~ 121 bytes
```
q=[1]
for n in range(2,2020):j=q.index(max(m for m in q if n%m<1))+1;q=q[:j]+[n]+q[j:]
print q[q.index(input())-1::2][:2]
```
[Try it online!](https://tio.run/##PZBPb8IwDMXP@FP4MkFFmRqntLRbd2PXXXaLcmAQRrs1baKiwadnTvlzcGT98vye5f48HDpLl223M9V0Or24SgkN@86jxdqi39hvM6OYEkqisqncc2135jRrN1wYZG2QOaz3aJ/aVxFFc/HiKqfKRs@V1XOnmlJD72s7oFP3@dr2x2EWRQtRlqQV14XTAf4O9a/BT380JUwGf@Z3Yk5mi2FB4HZr@gHXH@9r7zsffr@82fwAhGkpEXHxhkrkWRJjUWhYCroiWmYxioRSDTneZWmyijENsuyGiIEQpEHIVX4VZXnBjFI@CyWiGGGWS2YyzUZ2E8bIfVA9/JeSQzkxHFbKsAzknDWaj2bjNNA/ "Python 2 – Try It Online")
4 bytes thx to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld); 11 bytes thx to [FlipTack](https://codegolf.stackexchange.com/users/60919/fliptack).
Another naive implementation.
[Answer]
# [C++ (clang)](http://clang.llvm.org/), ~~288~~ \$\cdots\$ ~~210~~ 203 bytes
Saved a whopping ~~22~~ 29 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!!
Saved a byte thanks to @AZTECCO!!!!
```
#import<bits/stdc++.h>
#define l find(begin(q),end(q)
using v=std::vector<int>;v f(int p){v q{1};for(int n=1,d,i;d=i=++n<2020;q.insert(l,d),n))for(;++i<n&d<2;)d=n%i?d:n/i;auto t=l,p);return{*++t,t[-2]};}
```
[Try it online!](https://tio.run/##TVDLboMwELzzFatErXDtJED6xEA/JM2BYJNagsWAoQfEt6fGVFF92J0Ze9c7W2i9K6ocr7fbVtW66UxyUaY/9EYUlO6/M28rZKlQQgU2Cf8irwr9ljBpSUu8oVd4hTG1BXE8ysI0XaLQZHyE0rcANJlGaKdw5mXTOQXTkAmmuEhVSikmURAFvN0r7GVn/IoJwpCQ5TWnVCX4KJKIE5Hig/oUMR4UzwfTgEkrpgnvpBk6nJ4oNcycdtF55rP1gkU1CAmJanrTyby2Rv5pdY5KZ94yTZ1bP8SbPLBnBNFDCtPxyOAljBi82fzKIDy@WxQF4YeLC565q7BjgnMlILbFxIlrs@W4SbVtWfqC8LvstlU0g4EkWUkvzY//TO68kqW7FEvYwC6D02aB@hScncTgj4crP3/hZv1g9lxaFwMB9@bbLw "C++ (clang) – Try It Online")
Ungolfed:
```
#include <vector>
#include <algorithm>
auto f(int p)
{
std::vector<int> q{1};
for (int n = 2; n <= 2019; ++n)
{
int d = 1;
for (int i = 2; i < n; ++i)
{
if (n % i == 0)
{
d = n / i;
break;
}
}
auto it = find(begin(q), end(q), d);
q.insert(it, n);
}
auto it = find(begin(q), end(q), p);
std::vector<int> r = {*(it + 1), *(it - 1)};
return r;
}
```
[Answer]
# [Perl 5](https://www.perl.org/), 88 bytes
```
sub f{$_=1;for$n(2..2019){map{$n%$_ or$m=$_}1..$n/2;s/\b$m\b/$&,$n/}/(\d+),$_[0],(\d+)/}
```
[Try it online!](https://tio.run/##VZDBioMwEIbvfYqhzC7KBnVi1FpJ6QvsbW8qomyEwpqK2sMiPrsbtUg3p5/vy59h0qruJ5jn/lFBPWIhKanvHWqLOw73KLbHpmxH1G9YgOGNxGIix0Ht8qR3swqbrHLxnRkwuVb2/WEzLFIvZ2t2p/nRK/hS/XA@f947BYOJvbyQSA5mjgWp7wOAvABFoccgjnN2gOWkAfFV8CBkQB4Xu4ngWRHeiYF4qYSb4AYT8Z2Tf4rWQhjFxnBBu1p2XFQY@cb4Inw1W4mBiZTb4yqaXws1w4phacsrFslK2@6mBzhqaRxUyqympLkDZT2oTmKZ6WPyrMO1lrV5w97ArbcA6@XHACv4D2mB5QKn@Q8 "Perl 5 – Try It Online")
Same ungolfed:
```
sub f {
$_=1; # $_ is the comma separated queue "array string"
# ...with 1 as the first penguin
for $n (2..2019){ # process the rest of the penguins 2-2019
map { $n%$_ or $m=$_ } 1..$n/2; # find max $m divisible by current $n
s/\b$m\b/$&,$n/ # search-replace to place current $n behind $m
}
/(\d+),$_[0],(\d+)/ # find and return the two numbers:
# the one before and the one after the input
# parameter $_[0] in the $_ array string
}
```
[Answer]
# [R](https://www.r-project.org/), ~~90~~ 89 bytes
```
for(i in 2:2019)T=append(T,i,match(max(which(!i%%1:(i-1))),T));T[match(scan(),T)+c(-1,1)]
```
[Try it online!](https://tio.run/##K/r/Py2/SCNTITNPwcjKyMDQUjPENrGgIDUvRSNEJ1MnN7EkOUMjN7FCozwjE8hSzFRVNbTSyNQ11NTU1AnR1LQOiYaoKU5OzNMACWkna@ga6hhqxv4HGfcfAA "R – Try It Online")
Builds up the list into `T` and extracts the relevant values.
As a bonus, it works for `1` and *almost* works for `1024`, as R's 1-based indexing returns nothing for index `0` and `NA` for index `2020`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~23~~ 21 bytes
```
ḍƇṀ=⁸k⁸j
⁽¥ØRç/ṣ⁸ṪḢƭ€
```
[Try it online!](https://tio.run/##y0rNyan8///hjt5j7Q93Ntg@atyRDcRZXI8a9x5aenhG0OHl@g93LgYKPdy56uGORcfWPmpa8///f3MA "Jelly – Try It Online")
Naïve answer that simply generates the list of penguins and finds the relevant place. A pair of links which, when called as a monad, takes an integer as its argument and returns a pair of integers indicating the penguins before and after in the list of penguins.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~104 101~~ 95 bytes
```
->n{*w=1;(2..2019).map{|z|w.insert(1+w.index(w.select{|x|z%x<1}.max),z)};w[w.index(n)-1,3]-[n]}
```
[Try it online!](https://tio.run/##Nc1LCsIwFIXhrTgREr0N3oQapdaNhA58pCDopbSVxDRde0wRJ4cz@ODv39dPautUnGnauBorJoWQOzxy8bp0UwzRiQcNth8Zbpd7t545MdinvY1T9DGs/QnnjD2HwOfKmb8iXiCopjDUzMkoBSVK0FDuAdVBwxJZRje/EsVuZQjazLP/Ag "Ruby – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 36 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
1k
#É9ò2@iUaXâ n- gJÑ)ÄX
g[J1]c+UaNg
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=MWsKI8k58jJAaVVhWOIgbi0gZ0rRKcRYCmdbSjFdYytVYU5n&input=MzM)
```
1k assign [1] to U
#É9ò2 pass range 2...2019 to function:
@i ... X insert each value in U at index:
Ua find max divisor of X in U:
Xâ divisors
n- sorted
gJÑ)Ä 2nd to last
g get elements at
[J1] [-1,1]
c+UaNg add index of 1st input in U
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 109 bytes
```
^
2019$*_
_
$`_¶
(_+)\1+¶
$1 $&
+m`^(_+)¶((_+¶)*)\1 (_+¶)
$1¶$4$2
_+
$.&
^(.+¶)*(.+)¶(.+)(¶.+)(¶.+)*¶\3$
$2$4
```
[Try it online!](https://tio.run/##PYs7DoMwEET7OQXFCBlbQrHNcZCXFClSQIFytj3AXsxZiJRm5mk@5@vzPp69N5RHZhQIuIkpgqRpzcmJeeCItG/tykyDm@kUvR5@6BNTLiyQBM4jWpjvidt1cA2mf42mayVYuPRe6xc "Retina 0.8.2 – Try It Online") Note: Link only goes to 201 as 2019 is too slow for TIO. Explanation:
```
^
2019$*_
```
Prepend 2019 in unary.
```
_
$`_¶
```
Count from 1 to 2019.
```
(_+)\1+¶
$1 $&
```
Precede each number with its highest proper factor (except 1, which remains unchanged).
```
+m`^(_+)¶((_+¶)*)\1 (_+¶)
$1¶$4$2
```
Insert in turn each number after its highest proper factor.
```
_+
$.&
```
Convert to decimal.
```
^(.+¶)*(.+)¶(.+)(¶.+)(¶.+)*¶\3$
$2$4
```
Extract the predecessor and successor of the original input.
118 byte version that's fast enough to handle 2019 on TIO:
```
^
2019$*_
_
$`_¶
(_+)\1+\b
$.1;$.&
_
1
m{`^(\d+)¶\1;
$1¶
}`^(\d+¶)(\d+;\d+¶)
$2$1
^(.+¶)*(.+)¶(.+)(¶.+)(¶.+)*¶\3$
$2$4
```
[Try it online!](https://tio.run/##K0otycxL/P8/jsvIwNBSRSueK55LJSH@0DYujXhtzRhD7ZgkLhU9Q2sVPTWgjCFXbnVCnEZMirbmoW0xhtZcKoZAlbUQoUPbNEGUNYTJpWKkYsgVp6EH4mgBKaAOEKlxaBuc1AIaYqwCUmny/7@xMQA "Retina 0.8.2 – Try It Online") Explanation:
```
^
2019$*_
_
$`_¶
```
Prepend all of the unary numbers from 1 to 2019.
```
(_+)\1+\b
$.1;$.&
```
Convert to decimal and prepend the largest factor.
```
_
1
```
Except 1, which just becomes the first entry in the list.
```
m{`^(\d+)¶\1;
$1¶
}`^(\d+¶)(\d+;\d+¶)
$2$1
```
Bubble up each line until it finds its insertion point.
```
^(.+¶)*(.+)¶(.+)(¶.+)(¶.+)*¶\3$
$2$4
```
Extract the predecessor and successor of the original input.
[Answer]
# [Scala](http://www.scala-lang.org/), 163 bytes
```
n=>{val a=(2 to 2019).map(x=>(x,((1 to x/2).filter(x%_==0)).max)).foldLeft(Seq(1))((l,e)=>l.patch(l.indexOf(e._2)+1,Seq(e._1),0));val i=a indexOf n;(a(i-1),a(i+1))
```
[Try it online!](https://tio.run/##VZDfa8IwEMff/SuOwuCCWdektbWVCHscDPbg4xiS2dR1xrarZUTEv7276pzuIZdLPve9X7uVtrqv3z/NqoMaDpCbAra6rFBn8Ni2ev@66NqyWr8xgt/aQpE9VZ2aI1lOh6m@UvPDQLRCCV0NMhAp87e6QUdxjiOK4ds9SOYXpe1Mi@5uqVTAhihHtqht/myKDhfmCwVjiJYbpubWb3S3@kDrl1Vu3EuBxl9KNhZ8CCRfME5ZZkP1Umn4jYJqhhrLe6J0jSlhfxwNg9UbdNlf53x/9RkoaGjOzlZYFtS42jOv3njG7oxX1bSbTQZrur2xG3tgXEMLMzk992xEaaHAMGQcAFAkccDTlMEFTIQcCMpJzEUgoytJTgqSRMGUR7eS@JxLTrkg9d@/CKeDBkWcpFzISFzRaeuE4iTkIozif@Qs4uTdKi7VJ2HMT10dj/0P "Scala – Try It Online")
] |
[Question]
[
# Introduction
You're a criminal tasked with stealing some secret plans from the new tech startup Dejavu. You sneak in over the back wall, but find a door that requires a pin to open it. You recognize the make of the lock and know that it takes a 5 digit pin using all numbers from 0 to 4. After each digit entered, the lock checks the last 5 digits entered and opens if the code is correct. You have to get past this lock, and fast.
# Superpermutations in a Nutshell
A permutation is all possible combinations of a certain set of digits. for example, all the permutations of the digits 0, 1, 2 are:
012, 021, 102, 120, 201, and 210.
If we concatenate all these permutations together, we get a superpermutation:
012021102120201210
this superpermutation contains all the permutations of 0, 1, 2, but it's possible to make one shorter than this. I'm going to skip a bit here, but the shortest superpermutation of these digits is:
012010210
For our intents and purposes, this is essentially the shortest string of digits that contains all possible permutations of those digits, i.e. a superpermutation.
# Task
Your task is a bit harder than the superpermutation example as shown above, because you have two more digits to worry about. - If you haven't read about superpermutations, or my example above was a bit unclear, I highly suggest you read this great article by Patrick Honner on the subject (this challenge was quite heavily inspired by his article, so kudos to him): <https://www.quantamagazine.org/unscrambling-the-hidden-secrets-of-superpermutations-20190116/>. Your goal is to write the shortest program possible that generates a superpermutation of the digits 0 to 4.
# Scoring
Your program does not take any input of any sort, and produce a superpermutation of the digits from 0 to 4. This resulting superpermutation must be printed to the console or visibly displayed to the user to the extent provided by your language of choice. This doesn't have to be the shortest permutation possible, it just has to be a valid superpermutation. Because of this, the goal is to write the shortest program with the shortest superpermutation, so you should calculate your score like so:
**file size (bytes) \* generated superpermutation length (digits)**
for example, if I had a 40 byte program, and my superpermutation is 153 digits long, my score will be:
**40 \* 153 = 6120**
as always, the goal is to get this score as low as possible.
# Template
Here is how you should post your answer:
>
> ## Language | Score
>
>
> link to code in working environment (if possible)
>
>
> `code snippet`
>
>
> code explanation, etc.
>
>
>
# Finalities
This is one of my first questions on this site. So please tell me if I'm missing anything or a section of my challenge is unclear. Thank you, and have fun golfing!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), score = 1673 (7 bytes · 239)
```
žBœ∊{3ý
```
[Try it online!](https://tio.run/##yy9OTMpM/f//6D6no5MfdXRVGx/e@/8/AA "05AB1E – Try It Online")
### How it works
```
žB push 1024
œ permutations: ["1024", "1042", …, "4201"]
∊ vertically mirror: ["1024", "1042", …, "4201", "4201", …, "1042", "1024"]
{ sort: ["0124", "0124", "0142", "0142", …, "4210", "4210"]
3 push 3
ý join: "01243012430142301423…3421034210"
```
# [Pyth](https://github.com/isaacg1/pyth), score = 1944 (9 bytes · 216)
```
s+R+4d.p4
```
[Try it online!](https://tio.run/##K6gsyfj/v1g7SNskRa/A5P9/AA "Pyth – Try It Online")
### How it works
```
+R .p4 append to each permutation d of [0, 1, 2, 3]:
+4d [4] + d
s concatenate
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), score = 2907 (19 bytes × 153)
```
4⟦pᶠP∧~l.g;Pz{sᵈ}ᵐ∧
```
Too slow to see anything, but if you change `4` by `2` you can test it: [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/3@jR/GUFD7ctCHjUsbwuRy/dOqCquvjh1o7ah1snAIX@//8fBQA "Brachylog – Try It Online")
This finds the shortest superpermutation as such:
```
4⟦ The range [0,1,2,3,4]
pᶠP P is the list of all permutations of this range
∧
~l. Try increasing lengths for the output
g;Pz Zip the output with P
{sᵈ}ᵐ For each permutation, it must be a substring of the output
∧
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3000 (600\*5 bytes)
```
5ḶŒ!F
```
[Try it online!](https://tio.run/##y0rNyan8/9/04Y5tRycpuv3/DwA "Jelly – Try It Online")
[Answer]
# JavaScript (ES6), 26975 (325 \* 83 bytes)
With this scoring system, there's little room for something between *'hardcode the optimal supermutation'* and *'just use a short built-in to concatenate all permutations'*, at least in non-esolangs.
Here's an attempt anyway.
```
f=(a=[0,1,2,3,4],p=r='')=>a.map((v,i)=>f(a.filter(_=>i--),p+v))|~r.search(p)?r:r+=p
```
[Try it online!](https://tio.run/##XcpLCsIwEADQvafILjN0GvythKlX6F5EYk3alNiEJBQE8erRtcsHb9arzkNysbRLeJhaLYPmy5Z2tKcDHa8UObGUyJ1WTx0BVnI/WNDKOl9Mght3rm2RYrMivj9JZaPTMEHEczqlhmPtBQsLuBnCkoM3yocReuXNMpZJNEKK@6uYLP8C1i8 "JavaScript (Node.js) – Try It Online")
It generates a string of 325 bytes:
```
012340124301324013420142301432021340214302314023410241302431031240314203214032410341203421
041230413204213042310431204321102341024310324103421042310432201342014320314203412041320431
210342104330124301423021430241304123042131024310423201432041321044012340132402134023140312
4032141023410324201342031421034301243021431024320143210
```
[Answer]
# [Python 2](https://docs.python.org/2/), Score: ~~24327~~ ~~15147~~ ~~12852~~ 12628 (154\*82 bytes)
```
S=str(int('OH97GKT83A0GJRVO309F4SGSRWD0S2T292S1JBPVKJ6CRUY8O',36))
print S+S[::-1]
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9i2uKRIIzOvREPd38PS3N07xMLY0cDdKyjM39jA0s0k2D04KNzFINgoxMjSKNjQyykgzNvLzDkoNNLCX13H2ExTk6ugCKhdIVg7ONrKStcw9v9/AA "Python 2 – Try It Online")
---
Also:
# [Python 2](https://docs.python.org/2/), 12628 (154\*82 bytes)
```
S=oct(int('FS02C3XQJX14OTVMGM70CGCPWU41MNJZ0CO37ZMU0A0Y',36))[:-1]
print S+S[::-1]
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9g2P7lEIzOvREPdLdjAyNk4ItArwtDEPyTM193X3MDZ3TkgPNTE0NfPK8rA2d/YPMo31MDRIFJdx9hMUzPaStcwlqugCKhdIVg7ONoKxP//HwA "Python 2 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), score: ~~5355~~ 2160 (216 \* 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage))
```
3ÝœJε4yJ}J
```
Port of [*@AndersKaseorg*'s Pyth answer](https://codegolf.stackexchange.com/a/179614/52210), so make sure to upvote him!
[Try it online.](https://tio.run/##yy9OTMpM/f/f@PDco5O9zm01qfSq9fr/HwA)
**Explanation:**
```
3Ý # Push a list in the range [0,3]: [0,1,2,3]
œ # Get all possible permutations of this list
J # Join each inner list together to a single string
ε # Map each string `y` to:
# (Push string `y` implicitly)
4 # Push 4
y # Push string `y` again
J # Join all three together
}J # After the map: Join all strings together to a single string
# (and output it implicitly as result)
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 27 x 442 = 11934
```
'01234'(perms(1:5)'(4:445))
```
[Try it online!](https://tio.run/##y08uSSxL/f9f3cDQyNhEXaMgtSi3WMPQylRTXcPEysTEVFPz/38A "Octave – Try It Online")
So, it turns out, naively generating *all* the permutations and then truncating to the shortest substring that is still a valid superpermutation is shorter than generating the shortest superpermutation. Sadly, this time the score is not a palindrome.
### [Octave](https://www.gnu.org/software/octave/), 97 x 153 = 14841
```
a=sym(9);while i<120
i=0;a+=1;q='01234';for t=q(perms(1:5))'
i+=any(regexp(char(a),t'));end
end
a
```
[Try it online!](https://tio.run/##NZDBboMwEETvfMVeIkCJIhvSQ0r5gN77AWxgUywROwGTNF9PZ2kj4Scxy8wsDm3kuywb@qROzs4LsaeGG@plFGqHMAnFQLEXmuarjHguc@Togt/pgIchPP7GYZhVTjaqI8pNPZ3kHJCj8144ooNjT@G8KrN3dxkn2dNXoAs7H3HWSRvGUdpIyDo9o77PPu6wI3eddMTUnOrpecmOeUP/llc9KrHRPkl4/SK1RXkwCmsUhVGURmEPRgEJKI3CGkVxMApIAHxAYRQWWYrCKKxRIAuARQEJKI0CFgAlCkgAfIDVLJvm1fL6i@rRu0HIfaAncbWpeFvb6lan6@ZphUukWN8yvf0ps@9veZ4mbluzf2ajfMvPNWt7HjPOdzHN80p8l@jhZfkF "Octave – Try It Online")
Entry updated for a few things
* `a++` is not implemented for symbolic numbers.
* `contains()` is not implemented in Octave. Replaced with `any(regexp())`.
* In the online link, I manually entered an `a` very close to the 153-length superpermutation. This allows for the solution to be verified.
[Answer]
## CJam (6 \* 240 = 1440)
```
5e!72>
```
[Online demo](http://cjam.aditsu.net/#code=5e!72%3E), [validation](http://cjam.aditsu.net/#code=5e!72%3E%0A%0Ae_5e!%5Cf%7B%5C%23%7Dp) (outputs the index at which each permutation of `0..4` can be found; it needs to flatten the output because the original program gives suitable output to stdout but what it places on the stack is not directly usable).
Approach [stolen from Sanchises](https://codegolf.stackexchange.com/a/179644/194), although the permutation order of CJam is different, giving a different substring.
---
## CJam (22 \* 207 = 4554)
```
0a4{)W@+W+1$)ew\a*W-}/
```
[Online demo](http://cjam.aditsu.net/#code=0a4%7B)W%40%2BW%2B1%24)ew%5Ca*W-%7D%2F), [validation](http://cjam.aditsu.net/#code=0a4%7B)W%40%2BW%2B1%24)ew%5Ca*W-%7D%2F%0A%0A5e!%5Cf%7B%5C%23%7Dp).
### Dissection
This uses a simple recursive construction.
```
0a e# Start with a superpermutation of one element, [0]
4{ e# for x = 0 to 3:
) e# increment it: n = x+1
W@+W+ e# wrap the smaller superpermutation in [-1 ... -1]
1$)ew e# split into chunks of length n+1
\a* e# insert an n between each chunk
W- e# remove the -1s from the ends
}/
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 29 bytes, output length 153, score 4437
```
”)⊞⧴�r3⁼H⁴↓¦σ✳LïpWS [T↑ZωÞ”‖O
```
[Try it online!](https://tio.run/##FcsxCoAwEETR3mNYaSFskulyCMUbhBBRCCoheP11p3nFh5/P1PKTqurWrrtPozgfQATEgXgQCSCWDA8iIC6AWDLsMxzIOMdhL0ctua9faTW90xxVdfnqDw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Like @TFeld, I just print half of a superpermutation and mirror it. I calculated the superpermutation using the following code:
```
Push(u, w);
for (u) {
Assign(Plus(Plus(i, Length(i)), i), h);
Assign(Ternary(i, Join(Split(w, i), h), h), w);
Assign(Incremented(Length(i)), z);
if (Less(z, 5)) for (z) Push(u, Slice(h, k, Plus(k, z));
}
Print(w);
```
This translates to a 45-byte program in Charcoal so would have scored 6885.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 16 x 442 = 7072
```
4Y25:Y@!)K442&:)
```
[Try it online!](https://tio.run/##y00syfn/3yTSyNQq0kFR09vExEjNSvP/fwA "MATL – Try It Online")
MATL port of my Octave answer. -442 thanks to Luis Mendo
[Answer]
# Japt -P, 2376 (11 x 216)
```
4o ¬á Ë+4+D
```
[Try it!](https://ethproductions.github.io/japt/?v=1.4.6&code=NG8grOEgyys0K0Q=&input=LVA=)
-1 byte thanks to @ Shaggy!
Port of Anders Kaseorg's [Pyth answer](https://codegolf.stackexchange.com/a/179614/8340).
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 7191 (153\*47 bytes)
```
say first *.comb(permutations(5).all.join),0..*
```
[Try it online!](https://tio.run/##K0gtyjH7/784sVIhLbOouERBSy85PzdJoyC1KLe0JLEkMz@vWMNUUy8xJ0cvKz8zT1PHQE9P6/9/AA "Perl 6 – Try It Online")
Finds the first number that contains all permutations of the digits 0 to 4. This will take a *long* time to execute, but you can test it with the first two permutations [`0`](https://tio.run/##K0gtyjH7/784sVIhLbOouERBSy85PzdJoyC1KLe0JLEkMz@vWMNQUy8xJ0cvKz8zT1PHQE9P6/9/AA) and [`0,1`](https://tio.run/##K0gtyjH7/784sVIhLbOouERBSy85PzdJoyC1KLe0JLEkMz@vWMNIUy8xJ0cvKz8zT1PHQE9P6/9/AA)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 153\*95 bytes, 14535
```
Nest[Flatten[Join[#,{Max@#+1},#]&/@Partition[#,Max@#+1,1]]//.{b__,a__,a__,c__}:>{b,a,c}&,{0},4]
```
[Try it online!](https://tio.run/##NcmxCsIwEIDh3aeQBrp4GAtOgpLJQap0DyFcQ0gDNoX2BiHk2U@EOPzwwT8jTX5Gig45XPnlN9L3NxL5pB9LTFpAfuJHiUNXQJhWqgFXihSX36oHOmOkPObRWsCas7ZcbnkEBFdayKcCZ8PDGhPtVdhVNM1fvU@BJhWYvw "Wolfram Language (Mathematica) – Try It Online")
] |
[Question]
[
If we take a positive integer \$n\$ and write out its factors. Someone can determine \$n\$ just from this list alone. In fact it is trivial to do this since the number is its own largest factor.
However if we take \$n\$ and write only the first half of its factors (factors that are smaller than or equal to \$\sqrt{n}\$), it becomes a lot more difficult to tell the original number from the list alone. In fact, it frequently becomes impossible to tell at all. For example both \$28\$ and \$16\$ give
\$
\begin{array}{ccc}
1 & 2 & 4
\end{array}
\$
as the first half of their factors (along with an infinite number of other solutions). So if you show this list to someone they cannot know for sure what your original number was.
But some special cases do have a single unique solution. For example
\$
\begin{array}{ccc}
1 & 2 & 3 & 5
\end{array}
\$
is unique to \$30\$. No other number has these as its smaller factors.
---
The goal of this challenge is to write a program or function which takes as input an integer \$n\$ and determines if the first half of its factors are unique or not.
Your output should be one of two consistent values, one corresponding to inputs that are unique and one to inputs that are not.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with fewer bytes being the goal.
---
## Test cases
The first 120 truthy values are:
```
24 30 40 50 56 60 70 80 84 90 98 100 105 108 112 120 126 132 135 140 150 154 162 165 168 176 180 182 189 192 195 196 198 208 210 220 231 234 240 242 252 260 264 270 273 280 286 288 294 297 300 306 308 312 315 320 324 330 336 338 340 351 352 357 360 363 364 374 378 380 384 385 390 396 399 408 416 418 420 429 432 440 442 448 450 455 456 459 462 468 476 480 484 494 495 504 507 510 513 520 528 532 540 544 546 552 560 561 570 572 576 578 585 588 594 595 598 600 608 612
```
If you want more test cases I've written a reasonably fast generator (generates the first 500 in under 3 seconds on TIO).
[Try it online!](https://tio.run/##jVRNj9owEL3nV7zDHpJdkkKkXtAGVVVVqYd2pXKphJaVWRywYjtfjggSv710EkLWAdruIbE9eW8@3oyzZWXCpTwKlaWFQV4xKWLB1/jCDAvm3ICVoOXoBofAw3TqAC6@acM3BZNgdPToAaIZGPzu9TlNpaNAFGhE9F2la9opRBHGjuOIeU7BOmdPxbr1M8KPSt3y2MEbP5uU@MBuywvegshgULdb4IDw3mAW9YaoWwHTQ1JD5J0o@RWGfLnmYeLBrX1y5E88SnXLZPyTCb1Kd@@ofkHL84Bzqn@BxGmCJ3j0W8ICEwQBTpVp4jT1JyfFaP9MkSst8oqX/456CniGdhJRvwKuMrNHOBBrlVZ6jRpx2VethBaKZL/rVXBrLBFi6lk2IBbS8ALuDLVnmZtCsmWIe@TLcGA/IKNaKdTAOkJ@05rhQ4R8YGwk6LpSUs7nhCU3PczS@dcnV7Jiw0szV0zKr@zVpAWmePGsBg8Y/ZAA3Ubo3iJii9TIqbhaUf12RLwVQSOlLUKbMun4gMmbWFyWfOg3LS6UtLPbN3fFDneh7v48SbaDJuS1DBewUQtrevZfKE3oeWb@mgra4b11ulbFbaQUuuQ09EMpvZt6Weyamvk@Dy38qOjD6dfDsu8vyAqhDe5gWMLxcTxGd2WOv19jyTbl0X8K/wA "Haskell – Try It Online")
For falsy values I recommend you check everything under 50 not on this list, but in particular 12.
[Answer]
# [J](http://jsoftware.com/), 40 bytes
```
1=1#.]-:&(([#~0=|)~i.#~%:>:i.)"+[:i.1+*:
```
[Try it online!](https://tio.run/##RY3BCsIwEETv@Yq1RdMYu2zS2tZAvAiePPVaiohYWhEErQdB@usxVkSYYdi3DHN2q4lJcqiBYO@ttWYB8gasAQ4LT4x3jLApd1unrAqxjs0siqpwIPsSQ4fhMDVr06EIZOVDyblxgvW3R98@LeoUEoKUYOmVQUaQExTEmsPl7t@Rkh0WJD4T3wpjp2N7hSaQPzDenP/52HVv "J – Try It Online")
Here are all test cases, with squaring replaced by `5*x` so it finishes on TIO:
[Try it online!](https://tio.run/##RZJNaxsxEIbv@yumNo3tuFk0X9rVgnsp9NRTriGEUGriUig06aFQ/NfdRymlsC@S3hk9zIz266W9WXySeynygMxsWI2boxwW2cg7nAXdjPLh9tPHix50Pd7fLFfb7d36XA6/d@fTuD6/Xd4vp3G32t@x6D6vri@74eXHz5enX4fRQrxIFEm@KrXIVGTmC2lF2ixaCkrEXk3UOFsVdfaOz13NrhCteBWvkjuRA0hnvLmJNtZGrOHDNXimvSXkikIMloWJJaIUq3jUY5OLwbK5Iu41/DZReUEVzeLU5pri8Lx3RVvuxJwYXE9F5CT3YHt1RN7URQ58p2ufYdC6U6e3xmhmCa2IFXYYHr0HzIi@4tN/ZCLykjhzCGYQzCDgBtxoXcmcA02S9J7qkjDTZkmY2d8hiEeVpNas/VFUkhnkxBleUmtSYzKHhJmdyTwrs6jUWtWG4@O3Z952q/vTyHnX/5C/Dz4MXz4/fZfjav/PeD1vNv/918uXPw "J – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 31 bytes
```
Nθ≔EX⊕θ²Φ⊕ι∧λ¬∨›Xλ²ι﹪ιλη⁼¹№η§ηθ
```
[Try it online!](https://tio.run/##XY0xDsIwDEV3TpHRlcJAxdapQoAytPQKoYloJNdp0wS4fXDUDUuW7O/3v8dJh9FrzFnRkmKf5qcNsFbNod029yLo9AKD/7CoaAx2thStYUCKmvvmMP6dHMstGUApeh/hEeAerC7UHoO7s2CdNwk9OCmwKiXFxI@H4CjCdU0aNzhJcfGJ94lToyJjv2VcC97kXJ/z8Y0/ "Charcoal – Try It Online") Link is to verbose version of code. Inefficiently outputs a Charcoal boolean, i.e. `-` for unique, nothing if not. Explanation:
```
Nθ
```
Input `n`.
```
≔EX⊕θ²Φ⊕ι∧λ¬∨›Xλ²ι﹪ιλη
```
For all integers up to `(n+1)²`, list those factors that do not exceed its square root.
```
⁼¹№η§ηθ
```
See whether the `n`th list is unique.
Edit: Switching from `(2n)²` to `(n+1)²` made the code an order of magnitude faster without generating false positives. At a cost of 3 bytes, `2+⁴√n⁵` would be even faster; this works because the worst case scenario is of the form `p₁²p₂` where `p₁<p₂<p₁²`; the next integer with the same half rainbow is `p₁p₂²`, and since `p₂<p₁²` we have `p₂³<p₁⁶` and therefore `(p₁p₂²)⁴<(p₁²p₂)⁵`.
[Answer]
# [Haskell](https://www.haskell.org/), 68 bytes
```
f n=[x|x<-[1..n],x*x<=n,n`mod`x<1]
g n=[1|x<-[2..n*n],f n==f x]==[1]
```
[Try it online!](https://tio.run/##RYzBCoJAFEX3fcVdtBKTNzaZwry/aCcDCqlJ@gwreIv@fRrbBGd3z7m39nnvpimEHsK1ftQdapNl4lNN1LGk0szLtVFn/G7YFPNT8qgkUdoq7qGe4@LD3I4CxmMd5bX/vxkinw5Q5sv67nzILY4ESzhFChSEM6GMWFSEqkQM8AU "Haskell – Try It Online")
* thanks to @ovs for fixing an error at no cost!
[all test cases](https://tio.run/##7ZFNahxBDEb3OUUtsoiNYkp/1V0wfQvvhgYPZOwY253gONAL3338KpvcIQT6o6qlTw9J9f306@n8/Hy53JdtOe7v@@HrUW9utlX26/2wbLLdvfz4drcfdP30MCz6x2JYrnOVUbXcl31dyKyXl9PjVpby8/Vxe/tcvrydns5Frf7lrvJQ9mW5ff19XstVWZZytBCvElWSr0mrMlWZ@UJ6lT6L1ooScVcTgKiJOncnTq3mUIg2Yo1YwzvhAaQzsbmLds5OrhOHa/BMqxg8c0UhBsvCxBLRijVi9GOTi8GyuSHqOvE@0XlFDc3i9Oaa4vB8TMVY7uScHFxPRXiSOtjeHOGbhvDAd6b2GQajO31676xmltCGOGGHEWP2gBkxTuLMH5kIX5JnD8EOgh0E3IAbfSjZc6BJktlTXRJm2iwJM8c7BPlokvSabTyKSrKDnPiHl/Sa9JjsIWHmYLLPxi4avTa19fL/Vf@9V/0A "Haskell – Try It Online") with 5n instead of n squared to finish on Tio ( @Jonah trick )
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 80 bytes
```
(l=#;Tr[1^(S=Select)[Range[l^2+1],d@#==d@l&]]<2)&
d@n_:=S[Divisors@n,#<=Sqrt@n&]
```
[Try it online!](https://tio.run/##JcxBCsMgEADAe19RECShHmKObRb2kAeU2ptsikSxgtlSI/2@PWQeMJur77C5mlbXIrQug7g9i9VLZ8CEHNba24fjGGxexosm5VEAeMySaBp7efLIrysYO6df2j9lR1ZiAvMtFVlSu5fE9YxHdUyoh0FFan8 "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), 85 bytes
Based on [Noodle9's answer](https://codegolf.stackexchange.com/a/220919/64121).
The `1<<n` is only necessary for `n=1`, otherwise `n*n` would be shorter and a lot more efficient.
```
lambda n:2>(w:=[[a for a in range(x)if x>=a*a>1>x%a]for x in range(1<<n)]).count(w[n])
```
[Try it online!](https://tio.run/##RcqxDoMgEADQvV9xSxOugwl2MUb4EcpwraIk9iCERvr11C66veHFb14C37uYqlOPutL7ORJw32qx9coYAhcSEHiGRDxPoqB3ULSiG2mpy5XsP5QzyGFgtNi8woez2AxbrDH53U5IxMvhFrH@AA "Python 3.8 (pre-release) – Try It Online") or [Try it with `n*n`!](https://tio.run/##Rcy9CsIwFMXx3ac4i5AUEVoHJZC8SMxw/Yhe0JsQKo1PH1uXbmf4nX/@js8kh1MuLdpze9H7ciOIGZyajPWeEFMBgQWF5HFXVXNEdZY6cr2rWwoLqCuQTnTQ@2v6yKgmL0G3RfAqhh2OvTYbYE5Fxf8J5MLzg3X7AQ)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 80 bytes
```
n=>(q=t=>t&&q(t-1)+(g(t)==g(n)))(n*n+9)<2
g=n=>(h=i=>i*i>n||h(~-i)+[n%i?'':i])()
```
[Try it online!](https://tio.run/##FcrBDoIwDADQu//haGlmgjfFzvO@wXggyEYN6QQWT8Rfn3p8yXt2727tF3llq@kxlMBF2cHMmV02ZoZsGySIkJE5giIiaK10wstxF/l/RxZ2UovTbRvhYwXppnu5VtVZ7ghYQlrAc9O2RB4DeDSmT7qmaThMKf5cvg "JavaScript (Node.js) – Try It Online")
Can replace `n*n+9` to `2**n` in theory but not practical. `i` in `h` is negative so concatting lead to something like `true-3-2-1` for 12
[Answer]
# [Python 3](https://docs.python.org/3/), ~~103~~ 97 bytes
Saved 6 bytes ~~stealing~~ "borrowing" good golf ideas from [ovs](https://codegolf.stackexchange.com/users/64121/ovs)'s [answer](https://codegolf.stackexchange.com/a/220923/9481)!!!
```
lambda n,d=lambda x:[a for a in range(x)if x>=a*a>1>x%a]:all(d(n)!=d(a)for a in range(n*n)if a-n)
```
[Try it online!](https://tio.run/##XZLditswEIXv8xTqRYm9eCH6GdkKOC@yuxdqYndDU21IUkgJefZ0PrGlUIOOJc2ZOZojHX9f3j@Kf8zj6@OQf37bZVO63fg5va5fspk/TiabfTGnXL5PzbXdz@a6GfNT3tjN9Wt@W@fDodk1pf0y7prc/scvT4WM/Fzax3Q9TtvLtBsbFzrjV50JOoQROxP13@sYGBpP@k9DZ@xqBQjA0joFx57TLOtZeqIUs1JB020kEAlE0nrI1LYDgSEpJGYJSiKKmkPDWeU5NJy3gNZzlHdBM5wAHNdFAhza9V6B8m6IAFUS0dTT6gqIgAY8LXiruh4NX93ADu@heCioebEAZKEKkj56gIy@AmR0PZ75gaI45@nIp4THSgk2AsyQDI4A1gWEQqgzovgXRAAyBB5OBkwMmBhQC6iFVEG4wwDoIQXrxOohBSFxmiYISb3rAC9oFaEtifXutUvBROnZQ0NoS2hGcFIQkirEHUXsjLQVrWsX2/dp@2M6jc3y9Zfrw3bZmTqzftkueI7l33O0nV3Zdr0w@p3NaGZ9t3Ux6aLy/j7Suns87culmZe3cjfPG3M7383tU@5lGsfz233ZPv4A "Python 3 – Try It Online")
[Answer]
# Excel, 127 bytes
```
=LET(L,2+A1^1.3,x,SEQUENCE(L),y,SEQUENCE(L^0.5),u,TRANSPOSE(y),z,MMULT((MOD(x,u)=0)*(u<=SQRT(x)),2^y),SUM((INDEX(z,A1)=z)*1)=1)
```
modified Neil's upper bound to use n^1.3 instead of 1.25 to save a byte. n^2 would use too much memory with this solution.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
²‘½ḍƇ$€ċⱮ`⁸ịỊ
```
A monadic Link accepting a positive integer, \$n\$, that yields `1` if \$n\$ is a unique half rainbow or `0` if not.
**[Try it online!](https://tio.run/##ASsA1P9qZWxsef//wrLigJjCveG4jcaHJOKCrMSL4rGuYOKBuOG7i@G7iv///zU2 "Jelly – Try It Online")** Or see [those up to 60](https://tio.run/##ATEAzv9qZWxsef//wrLigJjCveG4jcaHJOKCrMSL4rGuYOKBuOG7i@G7iv/Dh@KCrFT//zYw "Jelly – Try It Online")
### How?
```
²‘½ḍƇ$€ċⱮ`⁸ịỊ - Link: integer, n
² - square (n)
‘ - increment
$€ - for each i in [1..n²+1]:
½ - square root (i)
Ƈ - filter [1..⌊√i⌋] keeping those which:
ḍ - divide (i)
Ɱ` - map across itself with:
ċ - count occurrences
⁸ị - get entry at index n
Ị - is insignificant (effectively = 1?)
```
[Answer]
# [Scala](https://www.scala-lang.org/), 97 bytes
Golfed version. [Try it online!](https://tio.run/##PY6xCsIwEIb3PsUtlqSDtI7FCI4OTuIkDrEmoRKvkl4lUvrsMWnRWw5@vu/u7xtpZehuD9UQHGWLMIa70qAZ1gckLlgF1AHytW4tKce82PnCbwXmOa68ECXPEm9@/Mg2s1BEpekGpGTEa1wIzTyPq5oCQHKe8R2TzvQ17J2Tn8uJXIvmyms4Y0sgYMwgzltacKofbIqWPlVZ/hsZPlOv6JJFtpApm7IpfAE)
```
def f(n:Int)=(1 to n).filter(x=>x*x<=n&&n%x==0)
def g(n:Int)={(2 to n*n).count(x=>f(n)==f(x))==1}
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `MAB`, ~~17~~ 13 bytes
```
²›ƛ₌K√ɾ↔;~iOṅ
```
-4 thanks to @lyxal!
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJNQUIiLCIiLCLCsuKAusab4oKMS+KImsm+4oaUO35pT+G5hSIsIiIsIjIzXG4yNFxuMjdcbjMwIl0=)
[Answer]
# [R](https://www.r-project.org/), ~~104 88 83 78~~ 74 bytes
```
m=scan();n=1:m^.5;for(i in 2:m^2)F=F+all(n[!m%%n]==(a<-1:i^.5)[!i%%a]);F<2
```
[Try it online!](https://tio.run/##K/r/P9e2ODkxT0PTOs/W0Co3Ts/UOi2/SCNTITNPwQjIN9J0s3XTTszJ0ciLVsxVVc2LtbXVSLTRNbTKBKrVjFbMVFVNjNW0drMx@m9i8B8A "R – Try It Online")
following [Neil's solution](https://codegolf.stackexchange.com/a/220937/85958) checking for all integers till n².
] |
[Question]
[
In this challenge you will be given an alphabetic string as input. We will define the "anti-string" of a given input to be the string with the case of all the letters inverted. For example
```
AaBbbUy -> aAbBBuY
```
You should write a program that takes a string as input and searches for the longest contiguous substring whose anti-string is also a contiguous substring. The two substrings should not overlap.
As an example if you were given the string
```
f**AbbA**cGf**aBBa**gF
```
The bolded portions would be the longest string anti-string pair.
Your program should, once it has found the pair, collapse them into a single character each. It should do this by removing all but the first character of each substring. For example the string above
```
f**AbbA**cGf**aBBa**gF
```
would become
```
f**A**cGf**a**gF
```
Your program should then repeat the process until the longest string anti-string pair is a single character or shorter.
For example working with the same string the new longest pair after the collapse is
```
fAc**Gf**a**gF**
```
So we collapse the string again
```
fAc**G**a**g**
```
Now the string cannot be collapsed further so we should output it.
In the case of a tie between candidate pairs (example `AvaVA`) you may make either reduction (`AaA` or `AvV`, but not `Aa`).
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with fewer bytes being better.
## Test Cases
```
fAbbAcGfaBBagF -> fAcGag
AvaVA -> AaA / AvV
QQQQQQQ -> QQQQQQQ
fAbbAcQQQQaBBacqqqqA -> fAbcQBcq
gaq -> gaq
fAbbAcGfaBBagFaBBa -> fcGaBBag
```
## Motivations
While this problem may seem arbitrary it is actually a problem I encountered while making code to process fundamental polygons. This process can be used to reduce a fundamental polygon to a smaller **n**-gon. After I tried it I thought it would make a nice little golf.
[Answer]
# Perl, ~~64~~ 61 bytes
Includes `+1` for `p`
```
perl -pE 's/(.\K.{$%})(.*)(?=(.))(??{$1^$"x$%.$"})/$2$3/ while$%=--pos' <<< fAbbAcGfaBBagFaBBa
```
[Answer]
# JavaScript (ES6), 200 bytes
Uses arrays of characters for I/O.
```
f=a=>(m=M=C=>a.map((_,i)=>a.map((_,j)=>C(i,j-i+1))))(I=>M((i,j)=>a.slice(i,i+j).some((n,k)=>n[c='charCodeAt']()^(a[I+k]||'')[c]()^32)|I+j>i|j<m||(x=[i,I],m=j)))&&m-->1?f(a,x.map(p=>a.splice(p+1,m))):a
```
[Try it online!](https://tio.run/##hVC9bsIwEN55ikzkrDhGtFtVpzJIrTIwsLBEKRxuktrgJBCEGPLuqZ0y0Cq0N5x0d9@fTuMZG3lU9Sksq4@s63KOPALDF3zOI2QGa4A1VeRm0HaYg6I6VMGU2IKYRwtwmx7W7JXM7KQCTVhTmQygpDt7KhPJffmJx7m1Eic/BfIOmMTBLm1b3yeJdJvHB9LGgY5Uq59N28KFJ4rGKTVcW6/x2IRhNH3JAemlT1T3nnVvWgdTaizqCTtZlU21z9i@KiCHhDHm52K7FfItx9kMi1c/JUxXqtxsiHetycTLLQCL0QBbnHElBkjeDVug8Gw/r4YElt91X8IKXDGju@nd1eWXB1s/4/Tpt3I5k4chfoGHv9L3fIsZ/fs4138pOWv7N3fuvgA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 119 bytes
```
.+
$&¶$&
T`Ll`lL`.*¶
/(.).*¶.*\1/^&0A`
¶&Lv$`(?<=(.)*)((.)(.)*).*¶(?>((?<-1>.)*.)(?<-4>.)*)(.*)\2
$5$6$3$'
N$`
$.&
}0G`
```
[Try it online!](https://tio.run/##VY3NCoJAFIX39zlu0zjRqP2tShkXuZEgiFYSd5SUQAIj3PVaPoAvZnds1VkcPs45l/u6vx9PG44zmdKoF4Bi6FHAhbKGmoy0GnrwpfYcaJWH/k0EhmDoRdYhyXh/4FJ5kn0Ct5NxJLlZhhEnnDNuommllZevALe4wzXO4YQEqAV8An4@VqYoTJlWNklsfQTT2auB80/wKx26umxZBmrbwv@V8y8 "Retina – Try It Online") Link includes test cases. Explanation:
```
.+
$&¶$&
T`Ll`lL`.*¶
```
Duplicate the input and flip the case of the first copy.
```
/(.).*¶.*\1/^&0A`
```
If there are no anti-strings at all then delete the flipped duplicate.
```
¶&Lv$`(?<=(.)*)((.)(.)*).*¶(?>((?<-1>.)*.)(?<-4>.)*)(.*)\2
$5$6$3$'
```
List all the possible collapsed anti-strings.
```
N$`
$.&
}0G`
```
Sort them in order of length, take the shortest (i.e. longest anti-string), and repeat until all the anti-strings have been collapsed.
[Answer]
# [Python 3](https://docs.python.org/3/), 189 181 bytes
Credit to Jonathan Frech for making it pure one-liner.
```
f=lambda s,x=set():any(u in s[j+i:]and(x.add(s[:j+1]+s[j+i:].replace(u,u[0],1))or 1)for i in range(len(s),1,-1)for j in range(len(s))for u in[s[j:j+i].swapcase()])and f(x.pop())or s
```
[Try it online!](https://tio.run/##dVA9b4MwEN3zK7zZFi4q6obEYIZmzpIFeTgMpiBiPgxt8uupDRZKUXrD6e69u3tP1z@mr05/LItKWrjlBSDD7okpJ0Jj0A8yo1ojkzVBHQvQBbmHUBTEZHETRCLwRDiWfQuyJDObs3fBIkq7EUVU2Vy7AyPoqiRtqYmhLGJvG9UcqRV1ipk9bBVqEZof6CWYklBBrT5S1kHf9WRVMEs/1noiimDF85zLs4I0heoTU4ZegChJkAXlGSpMT/su/4Yr9yu@ds4yzIFjhix2xeJp/rKF39i79frenQ7WHOp8yMEG/2PwSHmbubykcni@VMHgF9dqnVur0z9/cPnlLzZiE7LvcBimyy8 "Python 3 – Try It Online")
My own version, now obsolete (189 bytes):
```
x=set()
def f(s):
while any(u in s[j+i:]and(x.add(s[:j+1]+s[j+i:].replace(u,u[0],1))or 1)for i in range(len(s),1,-1)for j in range(len(s))for u in[s[j:j+i].swapcase()]):s=x.pop()
return s
```
[Try it online!](https://tio.run/##dVCxjoMwDN35imxJBIcO3YbEEIbr3KULYjAhoSAUIIEr/XouAYR6qOfBst@zn5/cP8d7p76WZU6MGAn1SiGRJIbGHnrc61YgUE8yoVohkzV@HeegSjKHUJbEZHHjR7m/E6EWfQtckCmYss88iCjtNIqotLl2AhpUJUgrlJUPouBjo5oztaLuYmaF7YU6D80Deg5GEJrT2CRz2He99Yq0GCdtnS29rtVIJMGSFQXjFwlpCtU3pgF6A6IkQRbkF6gw9Y5d9gM3tq/stfOWYQYMB8hiN5y/zF@32DeOblU/Ou9kzaHOBx9ssD8Gz9Rus@DXlA@vShUM@@JarXNr5f3zB5ff/mIjtkP2HQ7DdPkF "Python 3 – Try It Online")
`any()` to break out nested loops early, and `set()` for mutable global object usable in the comprehension. The rest is just the straightforward implementation of the requirements using `str.swapcase`.
# [Python 2](https://docs.python.org/2/), 160 bytes
```
def f(s):
for i in range(len(s),1,-1):
for j in range(len(s)):
u=s[j:j+i].swapcase()
if u in s[j+i:]:return f(s[:j+1]+s[j+i:].replace(u,u[0],1))
return s
```
[Try it online!](https://tio.run/##dVA9b4MwEJ3Lr7jNtnCj0hGJwQzJnCULYjCuTY0iBwxulF9PbbBQilIP1t37uHu6/jF938znPH9JBQqPJE9A3Sxo0AYsN63EV2k8TjP6nnn2LbDdng0EuGKsurxLdX0Y77wXfJSYeFwrcMHg2VTndW7l5KwJ2yqvzuo0Egcr@ysXEjvqqo@aZoQkEMXj3FttJqwwUqxpmDgpXpa8PSJC4QUIRQEeFCfeIpJsXvbDLyxaYh2SVYhxhih47ILqJ/15fdGxdcv0rUt20QIacojBP/Yn4J6KMRtxLsXwPKnlQzQu1aJbquSfO4T/5S1WYl3kzxEwROZf "Python 2 – Try It Online")
Turns out that regular nested for loop with early breaking through `return` is way shorter than the "clever" trick with `any`.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~240~~ ~~238~~ ~~227~~ ~~225~~ ~~222~~ 216 bytes
* Saved two bytes; removed a stray variable definition.
* Saved ~~eleven~~ thirteen bytes; golfed `b|=S[p+m]!=S[q+m]+32-(S[q+m]>90)*64` to `b|=abs(S[p+m]-S[q+m])-32` to `b|=32-S[p+m]+S[q+m]&63`.
* Saved three bytes; golfed `for(...;...;p++)S[p+1]=S[p+L];` to `for(...;...;S[++p]=S[p+L]);`.
* Saved six bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat).
```
p,P,q,Q,l,L,b,m;f(char*S){for(p=0;S[p];p++)for(l=0;S[l+++p];)for(q=0;b=S[q+~-l];!b&p+l<=q&l>L?L=l,P=p,Q=q:0,q++)for(b=0,m=l;m--;)b|=32-S[p+m]+S[q+m]&63;for(;b-2;)for(p=b++?-~Q-L:P;S[p];S[++p]=S[L+p]);~-L?L=0,f(S):0;}
```
[Try it online!](https://tio.run/##ZZA/b4MwEMXn9lO0DBGubQklUoe4bmSSwMIQhNQFMdiWoJWgtdM/S5p8deojBoZ68Envfs/vzpo2Wve9IQdiSU5akhFFOlaH@lUeHwp0qj@OoeERK0pTMYMxAqEdhBZj7MRBsU5RvCgtvtC2YvdqYXD7xO2ifc42GW/JgRuSc7uOiPWPKB6Rjreso5Qh9ctXS@pCcFdheKarFo8rBhxTdHkNMVxhvKGXnGbrw3WiooQZXHDmCmIXCmkRqcMCrSN27jv59h6i0@0N7HMnyooHtVBK6LSWcSybJHC7CsTM99fnVB2iU9kEiHlfDD7xI18E4LHHxhoIKWZ2C2x@PUBvPTXWqTc5dvNU0IC5tHVnCNt5226eTek81nb278HfSAv43mNjHfSJTP7vDzcYE29Iphz3BUDM7hTcUkohhLvBlHp4rIEcOs5x7v8A "C (gcc) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 180 bytes
```
def f(s):
L=len(s)
for x,y in[(i,i+j)for j in range(L,1,-1)for i in range(L-j)]:
t=s[x:y];T=t.swapcase()
if T in s[y:]:return f(s.replace(t,t[0],1).replace(T,T[0],1))
return s
```
[Try it online!](https://tio.run/##TZBNb8MgDIbP5Vf4BmhOtezIlEnpYbv0MinaBeVAM8iIKpoC25pfn8XNvnywXj@82Jhxym@ncDfPr9aBE0kqBvvqaMMiGbhThAtO4IMWHv3NIIkMSw3RhN6KPZZYlFfq/9FikK1im1wlfVFTe99UeZs@zdiZZIVkG@@gIXvSk2pVtPk9Bpq@jXY8ms6KjFnftljKX9Jgs5LlWd8X0kxzEzXS3NWHQ909ObPbmf6RI/D6w7zUJJ7XILm6qCJfd17iaunN@e/4pwllTnuM0YcMCXnxwJE@ic1f "Python 2 – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 30 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
î☼fúΩ§☺æ╒ºê@Ñ▀'╫Iqa{d]∟Sa5♦⌂─╚
```
[Run and debug it](https://staxlang.xyz/#c=%C3%AE%E2%98%BCf%C3%BA%CE%A9%C2%A7%E2%98%BA%C3%A6%E2%95%92%C2%BA%C3%AA%40%C3%91%E2%96%80%27%E2%95%ABIqa%7Bd%5D%E2%88%9FSa5%E2%99%A6%E2%8C%82%E2%94%80%E2%95%9A&i=fAbbAcGfaBBagF%0AAvaVA%0AQQQQQQQ%0AfAbbAcQQQQaBBacqqqqAgaq%0AfAbbAcGfaBBagFaBBa&a=1&m=2)
The corresponding ascii representation of the same program is this.
```
c%Dc:e{%orF..*:{_{32|^mY++_h.$1yh++R
```
It uses a regex approach. It repeatedly regex string replacement. It builds these from each contiguous substring of the current value. For instance for the input `fAbbAcGfaBBagF`, one of the substrings is `AbbA`, in which case the regex `AbbA(.*)aBBa` will be replaced with `A$1a`.
```
c get number of characters
%D repeat rest of program that many times
c:e get all substrings
{%or order substrings longest to shortest
F for each substring, execute the rest
..*:{ build the string "(.*)"
_{32|^m current substring with case inverted
Y save the inverted case in register y
++ concatenate search regex together
e.g. "aBc(.*)AbC"
_h first character of substring
.$1 "$1"
yh first character of inverted case
++ concatenate replacement regex together
e.g. "a$1A"
R do regex replacement
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 148 bytes
```
#//.s_:>MinimalBy[StringReplaceList[s,a:(p_~~__)~~x___~~b:(q_~~__)/;(32==##&@@Abs[(t=ToCharacterCode)@a-t@b]):>p<>x<>q]/.{}->{s},StringLength][[1]]&
```
[Try it online!](https://tio.run/##RY1fS4RAFMW/ymUEUdAdqjdbB3WhXjZoK3oZhuFqow6srn@m2BD96qZJdB4u557z494KTakqNDrDOYcQZovSXS8D9qRrXeE5@eavptN18aKaM2bqqHvDew8Dp5HTJKU7TVcpF5sGTrsl9N65uw1Dy7KjKE577pjw7XIoscPMqO5w@VBuhL6JUuEGrNmz6561gu6G0WdDP3rbu6OqC1MKzm@EsOfnJTLc8oCAz4B4kHNLCLCBRjCQPE7TOHvMMUmweFhaEn/he7ya06bVbtS6rVzWLvpFCmz/678j6yQjUAqnT63M/AM "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), 33 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
à ñÊÅÔ£=rX+"(.*)"+Xc^H ÈÎ+Y+XÎc^H
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=4CDxysXUoz1yWCsiKC4qKSIrWGNeSCDIzitZK1jOY15I&input=ImZBYmJBY0dmYUJCYWdGIg)
```
à ñÊÅÔ£=rX+"(.*)"+Xc^H ÈÎ+Y+XÎc^H :Implicit input of string U
à :Combinations
ñ :Sort by
Ê : Length
Å :Remove first element (the empty string)
Ô :Reverse
£ :Map each X
= : Reassign to U
r : Global replacement
X+"(.*)"+ : Append "(.*)" to X and then append
Xc : Charcodes of X
^H : XORed with 32
È : Pass each match X, with captured group Y, through the following function
Î+Y+ : Append Y to the first character of X and then append
XÎc^H : The charcode of the first character of X XORed with 32
```
] |
[Question]
[
*(related: [one](https://codegolf.stackexchange.com/questions/19912/acrostic-poem-programming), [two](https://codegolf.stackexchange.com/questions/7105/create-an-acrostic), [three](https://codegolf.stackexchange.com/questions/4422/acrostic-polyglot-programming))*
An [acrostic](https://en.wikipedia.org/wiki/Acrostic) is a style of poem/writing where the beginning character of each line, when read vertically, also produces a word or message. For example,
```
Together
Everyone
Achieves
More
```
also spells out the word `TEAM` when the first column is read vertically.
Acrostics are a subset of [mesostic](https://en.wikipedia.org/wiki/Mesostic)s, where the vertical word can be anywhere in the horizontal words. For example, the `TEAM` one above could also be written as a mesostic as follows
```
togeTher
everyonE
Achieves
More
```
along with several other variations.
The challenge here will be to produce an acrostic or mesostic from a given list of input words.
### Input
* A list of words in any [any suitable format](http://meta.codegolf.stackexchange.com/q/2447/42963).
* The list will only contain words made from lowercase `[a-z]`.
* The list is guaranteed to form an acrostic or a mesostic (no need to handle bogus input).
* One of the words in the input will form the vertical word, while the rest make the horizontal words - part of the challenge here is to find the appropriate vertical word, so it *cannot* be taken separately.
### Output
* The ASCII-art acrostic or mesostic formed from the input words, written to STDOUT or returned, in any reasonable format.
* The corresponding vertical word must be capitalized (as in the examples).
* Leading spaces to get the vertical word to line up appropriately are **required**. Trailing spaces, and leading/trailing newlines are optional. *Extra* leading spaces are fine as well, so long as the words align correctly.
* If *both* an acrostic and mesostic are possible, output *only* the acrostic.
* If more than one acrostic/mesostic is possible, your code can output any or all of them.
### Rules
* Either a full program or a function are acceptable.
* [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins.
### Examples
```
['together', 'team', 'everyone', 'achieves', 'more']
Together
Everyone
Achieves
More
['aaa', 'aaa', 'aaa', 'aaa']
Aaa
Aaa
Aaa
# One output, or multiple (of the same) output is allowed
['aaa', 'aaa', 'aab', 'baa']
Aaa
Aaa
Baa
# This is the only allowed output, since others would be mesostic, which are lower priority
['live', 'every', 'love', 'very', 'ohio']
Live
Ohio
Very
Every
# Note that 'live' couldn't be the vertical word since then it would be a mesostic, which is lower priority output
['cow', 'of', 'fox']
cOw
Fox
# A shorter mesostic test case
['late', 'ballroom', 'anvil', 'to', 'head']
anviL
bAllroom
To
hEad
```
[Answer]
# [Brachylog](http://github.com/JCumin/Brachylog), 145 bytes
```
p~c[A:B:C],Bl1,A:CcP@pz:cahgB,P:1a~@nw|lL,?:laot:" "rjg:Ljb:sa:?z:cap~c[A:B:C],Bl1,A:Cc@pz:caZ:LmgB,Zl-yM,Z:M:Lz:2az:ca~@nw
bB,?h@u:Bc
b#=,?h@u|h
```
[Try it online!](http://brachylog.tryitonline.net/#code=cH5jW0E6QjpDXSxCbDEsQTpDY1BAcHo6Y2FoZ0IsUDoxYX5Abnd8bEwsPzpsYW90OiIgInJqZzpMamI6c2E6P3o6Y2FwfmNbQTpCOkNdLEJsMSxBOkNjQHB6OmNhWjpMbWdCLFpsLXlNLFo6TTpMejoyYXo6Y2F-QG53CmJCLD9oQHU6QmMKYiM9LD9oQHV8aA&input=WyJjb3ciOiJvZiI6ImZveCJd&debug=on)
(Takes half a minute, so be patient.)
[Answer]
# JavaScript (ES6), 255 ~~263 269 286~~
*Edit* 17 bytes saved as arbitrary number of leading spaces is allowed
*Edit2* some shuffling, 6 byte saved
*Edit3* return a list of string instead of a single string with newlines (OP comment to feersum's answer), 8 more bytes saved
For each word in the input list, I use a recursive DFS to find all possibile mesostics/acrostics. Each one is stored as an array with word and target letter position inside the word. Every result found is saved in global result array at position 1 (if it's an acrostic) or 0 if it's a mesostic.
After the complete scan for all words, I get the result at last position in array and build and return its ascii art rapresentation.
```
l=>(l.map((w,i)=>(r=(p,v,i,a)=>(l[i]='.',w[p]?l.map((v,i)=>~(j=v.search(w[p]))&&r(p+1,v,i,a|j,m[p]=[j,v])):l[p+1]?0:s[+!a]=[...m],l[i]=v))(0,w,i,m=[]),s=[]),m=s.pop(),m.map(([j,v])=>' '.repeat((l+0).length-j)+v.slice(0,j)+v[j].toUpperCase()+v.slice(j+1)))
```
*Less golfed*
```
f=l=>(
l.map((w,i)=>
// r: recursive DFS function
// defined here as it uses local w variable
(r = (p,v,i,a) => (
l[i] = '.'
, w[p]
? l.map(
(v,i) => ~(j=v.search(w[p])) &&
r(p+1, v, i, a|j, m[p] = [j,v])
)
: l[p+1] ? 0 // invalid if there are still unused words
: s[+!a]=[...m] // a is 0 if acrostic
, l[i] = v)
)(0, w, i, m=[])
, s=[]),
m = s.pop(), // get last result
// m.map(([j]) => o = o<j ? j : o, o=0), // find offset for alignment
// no need to find the optimal offset as leading blanks are allowed
m.map(([j,v]) => ' '.repeat((l+0).length-j)
+ v.slice(0,j)
+ v[j].toUpperCase()
+ v.slice(j+1)
)
)
```
**Test**
```
f=l=>(l.map((w,i)=>(r=(p,v,i,a)=>(l[i]='.',w[p]?l.map((v,i)=>~(j=v.search(w[p]))&&r(p+1,v,i,a|j,m[p]=[j,v])):l[p+1]?0:s[+!a]=[...m],l[i]=v))(0,w,i,m=[]),s=[]),m=s.pop(),m.map(([j,v])=>' '.repeat((l+0).length-j)+v.slice(0,j)+v[j].toUpperCase()+v.slice(j+1)))
console.log=x=>O.textContent+=x+'\n\n'
;[
['together', 'team', 'everyone', 'achieves', 'more']
,['aaa', 'aaa', 'aaa', 'aaa']
,['aaa', 'aaa', 'aab', 'baa']
,['live', 'every', 'love', 'very', 'ohio']
,['cow', 'of', 'fox']
,['late', 'ballroom', 'anvil', 'to', 'head']
].forEach(l=>console.log(f(l).join`\n`))
```
```
<pre id=O></pre>
```
[Answer]
## Perl6, ~~287~~ ~~277~~ 269 bytes
```
my @w=$*IN.words;my ($q,$r)=gather for ^@w {my @[[email protected]](/cdn-cgi/l/email-protection)($_);my \[[email protected]](/cdn-cgi/l/email-protection);for @v.permutations {my @o=flat($_ Z d.comb).map:{$^a.index: $^b};take $_,@o if @o>>.defined.all}}.sort(*[1].sum)[0];for @$q Z @$r ->(\a,\b){say " "x($r.max -b)~a.substr(0,b)~a.substr(b).tc}
```
[Answer]
# Mathematica 10.0, 139 bytes
An unnamed function returning a list of lines:
```
Sort[{q=Max[p=Min/@Position@@@({z={##2},#})],Array[" "&,q-#2]<>ToUpperCase~MapAt~##&@@@({z,p})}&@@@Permutations@Characters@#][[1,2]]&
```
Example usage:
```
In[144]:= f = Sort[{q=Max[p=Min/@Position@@@({z={##2},#})],Array[" "&,q-#2]ToUpperCase~MapAt~##&@@@({z,p})}&@@@Permutations@Characters@#][[1,2]]&;
In[145]:= f @ {"late","ballroom","anvil","to","head"} // Column
*... several pages of warnings ...*
Out[145]= baLlroom
Anvil
To
hEad
```
~~I'm looking for suggestions on better ways to do the capitalization.~~ I found a very nice function `MapAt` for capitalizing the letter in the string.
[Answer]
# Pyth, ~~52~~ ~~49~~ ~~47~~ 46 bytes
```
jm++*;-lsQhAd<HGr>HG4hhMDfhhShMTm.b,xNYNtdhd.p
```
[Try it online.](http://pyth.herokuapp.com/?code=jm%2B%2B%2a%3B-lsQhAd%3CHGr%3EHG4hhMDfhhShMTm.b%2CxNYNtdhd.p&input=%5B%22late%22%2C+%22ballroom%22%2C+%22anvil%22%2C+%22to%22%2C+%22head%22%5D&debug=0)
This is probably very golfable. It prints a bunch of leading spaces.
[Answer]
## Haskell, ~~214~~ ~~206~~ ~~204~~ 202 bytes
```
import Data.List
z=zipWith
h i j t|(u,v:w)<-splitAt j t=([1..sum i-j]>>" ")++u++toEnum(fromEnum v-32):w
f x=uncurry(z=<<h)$sort[(head<$>z elemIndices w l,l)|w:l<-permutations x,(True<$w)==z elem w l]!!0
```
Returns a list of space padded strings, e.g. `f ["late","ballroom","anvil","to","head"]` -> `[" baLlroom"," Anvil"," To"," hEad"]` or more display friendly:
```
*Main> mapM_ putStrLn $ f ["late", "ballroom", "anvil", "to", "head"]
baLlroom
Anvil
To
hEad
```
`f` selects the words that are written horizontally together with a list of offsets. `h` pads each word according to the corresponding offset and inserts the uppercase letter. In detail:
```
permutations x -- for each permutation of the input list x
w:l<- -- bind w to the first word and l to the rest
(True<$w)==z elem w l -- keep it if the list of other words
-- containing the next letter of w
-- equals (length w) times True, i.e. we have
-- as many matching letters as letters in w.
-- This rules out combinations shortcut by zipWith
-- for all the remaining w and l make a pair
head<$>z elemIndices w l -- the first element of the list of list of
-- indices where the letter appears in the word
l -- and l itself
sort -- sort the pairs (all 0 indices, i.e. acrostics
-- go first)
!!0 -- pick the first
-- now we have a pair like
-- ([2,0,0,1],["ballroom","anvil","to","head"])
uncurry(z=<<h) -- loop over (index,word) and
-- provide the third parameter for h
h i j t -- h takes the list of indices and
-- an index j and a word t
(u,v:w)<-splitAt j t -- split the word at the index and bind
-- u: part before the split
-- v: letter at the split
-- w: part after the split
[1..sum i-j]>>" " -- the spaces to pad
++ u -- followed by u
++ toEnum(fromEnum v-32) -- and uppercase v
: -- and w
```
[Answer]
# Python, 249 bytes
Probably still very golfable
```
from itertools import*;e=enumerate;lambda l:[[[' ']*(max(j for k,(j,c)in o[1:])-i)+l[k][:i]+[c.upper()]+l[k][i+1:]for k,(i,c)in o[1:]]for p in product(*[list(e(w))for w in l])for o in permutations(list(e(p)))if[c for k,(i,c)in o[1:]]==l[o[0][0]]][0]
```
Takes and returns a list of list of characters.
- e.g. `" bAllroom"` is `[' ',' ',' ','b','A','l','l','r','o','o','m']`
Only ever returns the first result and checks in an order such that all the acrostics are checked first.
See all test cases printed in the display format on [**ideone**](http://ideone.com/KNWvvV)
---
Here is a more readable functional form that does the same (except it returns the first result immediately rather than evaluating and then returning the first result):
```
from itertools import*
def f(l):
for p in product(*[list(enumerate(w)) for w in l]):
for o in permutations(list(enumerate(p))):
if [c for k,(i,c) in o[1:]] == l[o[0][0]]:
return [ [' '] * (max(j for k,(j,c) in o[1:]) - i)
+ l[k][:i]
+ [c.upper()]
+ l[k][i+1:]
for k, (i, c) in o[1:]
]
```
[Answer]
# Perl 6, 177 bytes
```
->\a{for first({.[0] eq[~] .[1]»[1]},map |*,[Z] map {.[0]X [X] map {.comb[(^$_,$_,$_^..* for ^.chars)]},.[1..*]},a.permutations)[1] ->$/ {say [~] " "x a.comb-$0,|$0,$1.uc,|$2}}
```
Brute-force solution.
### How it works
```
-> \a {
for first({.[0] eq[~] .[1]»[1]}, # For the first valid candidate
map |*, [Z] # among the transposed
map { # lists of candidates
.[0] X [X] map {
.comb[(^$_,$_,$_^..* for ^.chars)]
}, .[1..*]
},
a.permutations # for all permutations of the input:
)[1] ->$/ {
say [~] " "x a.comb-$0,|$0,$1.uc,|$2 # Print the candidate as ASCII art.
}
}
```
Each candidate looks like:
```
"of", (("c"),"o",("w")), ((),"f",("o","x"))
```
Transposing the list of lists of candidates is necessary to ensure that an acrostic, if it exists, is found before any mesostic.
] |
[Question]
[
As part of a city planning project, you've gotten the assignment of creating a program or function that will display the city skyline, given some input from the architects. The project is only in the startup phase, so a very rough sketch is sufficient. The easiest approach is of course to simply draw the skyline in ASCII-art.
All buildings will be by the river, thus they are all aligned. The architects will give the height of each building as input, and your code should display the skyline.
The input from the architects will either be an integer or a half-integer. If the number is an integer, the building will have a flat roof, while a half-integer will result in a pitched roof. A zero will just be flat ground. The walls of a building are 3 characters apart, while a zero will be a single character wide. Adjacent buildings share walls.
For details and clarifications regarding the output, please have a look at the examples below:
```
N = 3
___
| |
| |
|___|
N = 3.5
_
/ \
| |
| |
|___|
N = 6
___
| |
| |
| |
| |
| |
|___|
n = 0
_
```
Example input: `3 3.5 0 2`
```
_
___ / \
| | | ___
| | | | |
|___|___|_|___|
```
Example input: `0 0 2.5 3 0 4 1`
```
___
_ ___ | |
/ \| | | |
| | | | |___
__|___|___|_|___|___|
```
[Louisville](https://i.stack.imgur.com/eePKt.jpg), `0 2 1 3.5 0 4 2 4 2 4 6 1 6 0 5 1`
```
___ ___
| | | | ___
_ ___ ___ ___| | | | | |
/ \ | | | | | | | | | | |
___ | | | |___| |___| | | | | | |
| |___| | | | | | | | |___| | | |___
_|___|___|___|_|___|___|___|___|___|___|___|___|_|___|___|
```
The ASCII-characters used are: newline, space, and `/\_|` (code points 10, 32, 47, 92, 95, 124).
**Rules:**
* It's optional to make a program that only take integers as input, by multiplying all numbers by two. So, instead of taking `3 3.5 2`, your program may take `6 7 4`. If the second input format is chosen, an input of 6 should result in a 3 story building, 7 should be a 3 story building with pitched roofs etc.
* The output should be exactly as described above, but trailing spaces and newlines are OK.
* The exact format of the input is optional. Whatever is best in your language.
* The result must be displayed on the screen, so that the architects can have a look at it.
* You can assume there will be at least one integer given, and that only valid input will be given.
**This is codegolf, so the shortest code in bytes win.**
[Answer]
# Python 2, ~~199~~ ~~193~~ ~~188~~ 185 bytes
```
a=map(int,raw_input().split())
l=max(a)+1|1
while~l:print''.join((x%2*'/ _\\ '[x<l::2]*(x<=l<x+4)or'_ '[x|1!=l>1]*3)[x<1:x+2]+'| '[x<=l>=y]*(x+y>0)for x,y in zip([0]+a,a+[0]))[1:];l-=2
```
This is a full program that accepts integers as input. [Example input](http://ideone.com/M2uYzL).
[Answer]
# MATLAB, ~~219 209~~ 203 bytes
```
i=input('');x=1;c=0;m(1:4*numel(i))='_';for a=i;b=fix(a);m(1:b,x)='|';s=95;if a~=b;m(b+2,x+2)=95;s='/ \';end;m(b+1,x+(1:3))=s;x=x+(a>0)*3+1;m(1:b,x)='|';x=x+(a<1&c>0);c=a;end;disp(flipud(m(:,1:x-(a<1))))
```
This unfortunately doesn't work on **Octave**. Not entirely sure why, seems to be something to do with the disp/flipud bit that breaks.
Also, there is currently no definition of what a 0.5 height building looks like, nor any mention of them, so in this code I assume that they are disallowed.
The following is the code in a slightly more readable way:
```
i=input(''); %e.g. [0 0 2 1 3.5 0 4 2 4 2 4 6 1 6 0 5 1 0 0 1 0]
x=1;
c=0;
m(1:4*numel(i))='_';
for a=i;
b=fix(a);
m(1:b,x)='|';
s=95;
if a~=b;
m(b+2,x+2)=95;
s='/ \';
end;
m(b+1,x+(1:3))=s;
x=x+(a>0)*3+1;
m(1:b,x)='|';
x=x+(a<1&c>0);
c=a;
end;
disp(flipud(m(:,1:x-(a<1))))
```
---
First we take an input as an array, and do some variable initialisation.
```
i=input(''); %e.g. [0 0 2 1 3.5 0 4 2 4 2 4 6 1 6 0 5 1]
x=1;
c=0;
```
Because the zero height buildings are a pain - they basically end up with a width which is dependent on what they are next to (though what is printed doesn't change), we simplify things by drawing enough ground for all of the buildings. We assume each building will be 4 characters wide (because adjacent buildings merge together) - zero height ones aren't, but the excess will be trimmed later.
```
m(1:4*numel(i))='_';
```
Now we draw out each building in turn.
```
for a=i
```
First we get the integer part of the height as this will determine how many '|' we need.
```
b=fix(a);
```
Now draw in the wall for this building - if there are two adjacent buildings, the wall for this new one will be in the same column as the wall from the last one.
```
m(1:b,x)='|';
```
Check to see if this is a half height building. If it is, then the roof will be different. For the half heights, the roof is going to be `/ \` whereas full height ones it will be `___` (Matlab will implicitly replicate this from a single underscore, so save a couple of bytes there). There is an extra bit of roof one row higher for the half height buildings, so that is added as well.
```
s=95;
if a~=b;
m(b+2,x+2)=95;
s='/ \';
end;
```
Draw in the roof
```
m(b+1,x+(1:3))=s;
```
Now move to the start of the next building and draw in the shared wall (if the wall is too short at this point, it will be made larger when the next building is drawn). Note that zero height buildings are 1 wide, normal buildings are 4 wide, so we simplify what would otherwise be an if-else by treating (a>0) as a decimal number not a Boolean.
```
x=x+(a>0)*3+1;
m(1:b,x)='|';
```
Next comes a bit of hackery to work with zero height buildings. Basically what this says is if this building was zero height, and the one before that wasn't, it means the place of the next building needs incrementing by 1 because a zero height building sandwiched between two other buildings is effectively twice as wide - this accounts for the extra wall which is normally shared with an adjacent building. We also keep track of this building height for doing this check next time.
```
x=x+(a<1&c>0);
c=a;
end;
```
Once done, flip the building matrix to be the correct way up, and display it. Note that we also trim off any excess ground here as well.
```
disp(flipud(m(:,1:x-(a<1))))
```
---
So, when we run this script, we are asked for our input, for example:
```
[0 0 2 1 3.5 0 4 2 4 2 4 6 1 6 0 5 1 0 0 1 0]
```
It then generates the building and displays the result. For the above input, the following is generated:
```
___ ___
| | | | ___
_ ___ ___ ___| | | | | |
/ \ | | | | | | | | | | |
___ | | | |___| |___| | | | | | |
| |___| | | | | | | | |___| | | |___ ___
__|___|___|___|_|___|___|___|___|___|___|___|___|_|___|___|__|___|_
```
[Answer]
## Kotlin, ~~447~~ 442 bytes
```
val a={s:String->val f=s.split(" ").map{it.toFloat()}.toFloatArray();val m=(f.max()!!+1).toInt();for(d in m downTo 0){var l=0f;for(c in f){val h=c.toInt();print(if(h==d&&d!=0)if(h<l-0.5)"|" else{" "}+if(c>h)"/ \\" else "___" else if(h<d)if(d<l-0.5)"|" else{" "}+if(h==0)" " else if((c+0.5).toInt()==d)" _ " else " " else{if(h==0)if(l<1)" " else "| " else "| "}.replace(' ',if(d==0)'_' else ' '));l=c;};if(d<l-0.5)print("|");println();}}
```
## Ungolfed version:
```
val ungolfed: (String) -> Unit = {
s ->
val floats = s.split(" ").map { it.toFloat() }.toFloatArray()
val maxH = (floats.max()!! + 1).toInt()
for (drawHeight in maxH downTo 0) {
var lastBuildingH = 0f
for (f in floats) {
val buildingH = f.toInt()
if (drawHeight == 0) {
// Baseline
if (buildingH == 0)
if (lastBuildingH.toInt() == 0) print("__")
else print("|_")
else print("|___")
} else if (buildingH == drawHeight) {
// Ceiling
if (buildingH < lastBuildingH - 0.5) print("|")
else print(" ")
if (f > buildingH) print("/ \\")
else print("___")
} else if (buildingH < drawHeight) {
// Above building
if (drawHeight < lastBuildingH - 0.5) print("|")
else print(" ")
if (buildingH == 0) print(" ")
else {
if ((f + 0.5).toInt() == drawHeight) print(" _ ")
else print(" ")
}
} else {
if (buildingH == 0) print("| ")
else print("| ")
}
lastBuildingH = f;
}
if (drawHeight < lastBuildingH - 0.5) print("|")
println()
}
}
```
[Answer]
## Python 2, ~~357~~ ~~306~~ ~~299~~ ~~294~~ ~~287~~ ~~281~~ 276 bytes
```
def s(l):
d=len(l)+1;l=[0]+l+[0];h=(max(l)+3)/2;o=''
for i in range(d*h):
a=l[i%d+1];c=l[i%d];b=2*(h-1-i/d);o+="|"if(a>b+1)+(c>b+1)else" "*(a+c>0);o+=" _/__ _\\"[a-b+1::3]if b*(1>=abs(a-b))else" "*(1+2*(a>0))
if b==0:o=o.replace(" ","_")
if i%d==d-1:print o[:-1];o=''
```
This uses the "doubled" encoding, to be passed to the function as a list.
Edit: Shaved bytes by redoing part of the big conditional as an array selector, and switching to the doubled encoding. Shaved more bytes by rearranging the conditional even more and converting more logic to arithmetic.
EDIT: [xsot's is better](https://codegolf.stackexchange.com/a/65293/47050)
### Explanation:
```
d=len(l)+1;l=[0]+l+[0];m=max(l);h=m/2+m%2+1;o=''
```
`d` is 1 more than the length of the array, because we're going to add zeros on each end of the list from the second element up to the zero we added on the end. `h` is the height of the drawing. (We have to divide by 2 in this calculation because we are using the doubled representation, which we use specifically to avoid having to cast floats to ints all over the place. We also add 1 before dividing so odd heights--pointy buildings--get a little more clearance than the regular kind.) `o` is the output string.
```
for i in range(d*h):
```
A standard trick for collapsing a double for loop into a single for loop. Once we do:
```
a=l[i%d+1];c=l[i%d];b=2*(h-1-i/d)
```
we have now accomplished the same as:
```
for b in range(2*h-2,-2,-2):
for j in range(d):
a=l[j+1];c=l[j]
```
but in a way which nets us ten bytes saved (including whitespace on the following lines).
```
o+="|"if(a>b+1)+(c>b+1)else" "*(a+c>0)
```
Stick a wall in any time the height of either the current building or the previous building is taller than the current line, as long as there is at least one building boundary here. It's the equivalent of the following conditional:
```
o+=("|" if a>b+1 or c>b+1 else " ") if a or c else ""
```
where b is the current scan height, a is the current building height, and c is the previous building height. The latter part of the conditional prevents putting walls between ground spaces.
```
o+=" _/__ _\\"[a-b+1::3]if b*(1>=abs(a-b))else" "*(1+2*(a>0))
```
This is the part that draws the correct roof, selecting roof parts by comparing the building's height with the current scan height. If a roof doesn't go here, it prints an appropriate number of spaces (3 when it's an actual building, e.g., a>0, otherwise 1). Note that when we're at ground level, it never attempts to draw a roof, which means 0.5 size buildings don't get pointy roofs. Oh well.
```
if b==0:o=o.replace(" ","_")
```
When we're at ground level, we want underscores instead of spaces. We just replace them all in at once here.
```
if i%d==d-1:print o[:-1];o=''
```
Just before we start processing the next line, print the current one and clear the output line. We chop off the last character because it is the "\_" corresponding to the ground space we added by appending a zero at the beginning of the function. (We appended that zero so we would not have to add a special case to insert a right wall, if it exists, which would add far more code than we added by adding the 0 and chopping off the "\_".)
[Answer]
# Python 3
## ~~725 bytes~~
## 608 bytes
Golfed code:
```
import sys,math;
m,l,w,s,bh,ls,ins,r,a="| |","___","|"," ",0,[],[],range,sys.argv[1:]
def ru(n):return math.ceil(n)
def bl(h,n):
if(n>ru(h)):return(s*5,s)[h==0]
if(h==0):return"_"
if(n==0):return w+l+w
if(n<h-1):return m
return(" _ "," / \ ")[n==ru(h)-1]if(h%1)else(s+l+s,m)[n==h-1]
for arg in a:
f=ru(float(arg))
if(bh<f):bh=f
for i in r(bh,-1,-1):
ln=""
for bld in a:ln+=bl(float(bld),i)
ls.append(ln)
for i in r(len(ls[-1])-1):
if(ls[-1][i]==ls[-1][i+1]==w):ins.append(i-len(ins))
for ln in ls:
for i in ins:ln=(ln[:i]+ln[i+1:],ln[:i+1]+ln[i+2:])[ln[i]==w]
print(ln)
```
Here's the ungolfed code. There are some comments but the basic idea is to create buildings with double walls, so the bottom line looks like:
```
_|___||___|_|___||___|
```
Then to get indexes of those double walls and remove those columns so we get:
```
_|___|___|_|___|___|
```
Code:
```
import sys
import numbers
import math
mid="| |";
l="___";
w="|";
s=" ";
def printList(lst):
for it in lst:
print(it);
# h = height of building
# l = line numeber starting at 0
def buildingline(h,n):
#if (h==0):
# return " " if(n>math.ceil(h)) else " ";
if(n>math.ceil(h)):
return s if(h == 0) else s*5;
if(h==0): return "_";
if(n==0): return w+l+w;
if(n<h-1): return mid;
if(h.is_integer()):
return mid if(n==h-1) else s+l+s;
else:
return " / \ " if (n==math.ceil(h)-1) else " _ ";
# max height
bh=0;
for arg in sys.argv[1:]:
f = math.ceil(float(arg));
if(bh<f):bh=f;
# lines for printing
lines = []
for i in range(bh,-1,-1):
line="";
for bld in sys.argv[1:]:
bld=float(bld);
line += buildingline(bld,i);
#lh = bld;
lines.append(line);
#for line in lines:
# print(line);
#printList(lines);
# column merging
#find indexes for merging (if there are | | next to each other)
indexes = [];
for i in range(len(lines[-1])-1):
if (lines[-1][i]=='|' and lines[-1][i+1] == '|'):
indexes.append(i-len(indexes));
#printList(indexes);
#index counter
for line in lines:
newLine = line;
for i in indexes:
if newLine[i] == '|' :
newLine=newLine[:i+1] + newLine[i+2:];
else : newLine = newLine[:i] + newLine[i+1:];
print(newLine);
```
Time to do some golfing!
[Answer]
## PHP, ~~307~~ ~~297~~ 293 bytes
```
<?$r=str_pad("",$p=((max($argv)+1)>>1)*$w=4*$argc,str_pad("\n",$w," ",0));for(;++$i<$argc&&$r[$p++]=_;$m=$n)if($n=$argv[$i]){$q=$p+=!$m;eval($x='$r[$q-1]=$r[$q]=$r[$q+1]=_;');for($h=$n>>1;$h--;$q-=$w)$r[$q-2]=$r[$q+2]="|";$n&1?($r[$q-1]="/")&($r[$q-$w]=_)&$r[$q+1]="\\":eval($x);$p+=3;}echo$r;
```
Takes arguments\*2 from command line. save to file, run with `php <filename> <parameters>`.
**breakdown**
```
// initialize result
$r=str_pad("", // nested str_pad is 3 bytes shorter than a loop
$p= // cursor=(max height-1)*(max width)=(start of last line)
((max($argv)+1)>>1) // max height-1
*
$w=4*$argc // we need at least 4*($argc-1)-1, +1 for newline
,
// one line
str_pad("\n",$w," ",0) // (`str_pad("",$w-1)."\n"` is one byte shorter,
); // but requires `$w+1`)
// draw skyline
for(;
++$i<$argc // loop through arguments
&&$r[$p++]=_ // 0. draw empty ground and go one forward
;
$m=$n // 7. remember value
)
if($n=$argv[$i]) // if there is a house
{
$q= // 2. copy $p to $q
$p+=!$m; // 1. go one forward if there was no house before this
// offset all further positions by -2 (overwrite empty ground, share walls)
eval($x= // 3. draw floor
'$r[$q-1]=$r[$q]=$r[$q+1]=_;'
);
for($h=$n>>1;$h--;$q-=$w) // 4. draw walls
$r[$q-2]=$r[$q+2]="|";
$n&1 // 5. draw roof
?($r[$q-1]="/")&($r[$q-$w]=_)&$r[$q+1]="\\"
:eval($x) // (eval saved 7 bytes)
; // (ternary saved 6 bytes over `if`)
$p+=3; // 6. go three forward (5-2)
}
// output
echo$r;
```
[Answer]
# C++, ungolfed
(or maybe ungolfable)
Assuming there are less than 100 elements and each element is less than 100. `s` is the number of buildings (required in input).
```
#include <iostream>
using namespace std;
int main()
{
float a[100];
int i,j,s;
cin>>s;
for(i=0;i<s;++i)
cin>>a[i];
for(i=100;i>=1;--i)
{
for(j=0;j<s;++j)
{
if((a[j]>=i)||(a[j-1]>=i))
cout<<"|";
else
cout<<" ";
if(i==1)
cout<<"___";
else if(a[j]+1==i)
cout<<"___";
else if(a[j]+1.5==i)
cout<<" _ ";
else if(a[j]+0.5==i)
cout<<"/ \\";
else cout<<" ";
}
if(a[s-1]>=i)
cout<<"|";
cout<<endl;
}
}
```
] |
[Question]
[
### Intro
Something I've played around with in recreational mathematics has been construction of a divisor table to visually compare/contrast the prime divisors of a set of numbers. The set of input numbers are across the top as column labels, the prime divisors are on the left as row labels, and a mark indicates where the two line up.
For example, for input `6, 9, 14, 22` a table similar to the following would be constructed:
```
6 9 14 22
2 * * *
3 * *
7 *
11 *
```
This is because `6` has prime divisors of `2` and `3`, `9` has prime divisors of `3`, and so on.
### Construction
* The table is constructed such that the input numbers form column labels that are separated by spaces and in ascending order (you can assume they are pre-sorted), and the prime divisors are listed on the left in ascending order one per line forming the row labels.
* Note that leading spaces on the prime divisors and input numbers may be required if the numbers are different lengths, so that all columns are the same width and line up appropriately.
* Each divisor is represented by a single `*` (or other suitable ASCII character of your choosing, so long as the same character is used for all occurrences).
* Multiple divisors are ignored (e.g., `3 x 3 = 9` but there's only one `*` for that intersection).
* The `*` can be placed anywhere horizontally in the column, so long as it's unambiguous (I have all my examples with the `*` right-aligned).
### Input
* A list of positive integers [in any convenient format](http://meta.codegolf.stackexchange.com/q/2447/42963), each `>1`.
* You can assume that the input is pre-sorted.
* The input is guaranteed to have only unique values.
### Output
The resulting ASCII art representation of the prime divisor table.
### Rules
* Leading or trailing newlines or whitespace are all optional, so long as the characters themselves line up correctly.
* If it's shorter to have a divider line separating the column/row headings from the tabular data, that's allowed, too.
* 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 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
```
6,9,14,22
6 9 14 22
2 * * *
3 * *
7 *
11 *
2,3,5,7
2 3 5 7
2 *
3 *
5 *
7 *
2,4,8,16,32
2 4 8 16 32
2 * * * * *
75,99,151,153
75 99 151 153
3 * * *
5 *
11 *
17 *
151 *
```
[Answer]
# Mathematica, ~~101~~ 90 bytes
*Thanks to ngenisis for saving 11 bytes!*
```
TableForm[Outer[If[#∣#2,Y,""]&,f=#&@@@FactorInteger[1##],g={##}],TableHeadings->{f,g}]&
```
The `∣` character about a third of the way through is U+2223 (3 bytes). Unnamed function of a variable number of arguments, each of which is a nonzero integer, which returns a `TableForm` object (formatted output) like so:
[](https://i.stack.imgur.com/8u5Dx.png)
`f=#&@@@FactorInteger[1##]` defines `f` to be the set of all primes dividing any of the inputs (equivalently, dividing their product `1##`), while `g` is the list consisting of the inputs. `Outer[If[#∣#2,Y,""]&,f,g]` makes a table of `Y`s and empty strings corresponding to divisibility (we use the undefined token `Y` instead of a string `"Y"` or `"*"` to save two bytes). Then we use `TableForm[...,TableHeadings->{f,g}]` to format the resulting array with appropriate row and column headings.
Previous submission:
```
Grid[p=Prepend;Thread[q[Outer[If[#∣#2,Y,""]&,f=#&@@@FactorInteger[1##],g={##}]~p~g,f~p~""]]/.q->p]&
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes
```
PÆfQ0;ðḍ€+W}⁸;"o⁶G
```
Uses `1` instead of `*`, as allowed by the rules.
[Try it online!](https://tio.run/nexus/jelly#@x9wuC0t0MD68IaHO3ofNa3RDq991LjDWin/UeM29/@H24FCWY8a5hzadmjb///RZjqWOoYmOkZGsToK0UY6xjqmOuYQpomOhY6hmY4xWMbcVMcSqNDUEIiNYwE "Jelly – TIO Nexus")
### How it works
```
PÆfQ0;ðḍ€+W}⁸;"o⁶G Main link. Argument: A (array of integers greater than 1)
P Take the product of the integers in A.
Æf Compute all prime factors (with multiplicity) of the product.
Q Unique; deduplicate the prime factors.
0; Prepend a 0. Let's call the result P.
ð Begin a new, dyadic chain. Left argument: P. Right argument: A
ḍ€ Divisible each; for each p in P, test all integers in A for
divisibility by P. Yields one row of the shape of A for each p.
Note that the first element of P is 0, so the first row of the
resulting matrix contains only zeroes.
W} Wrap right; yield [A].
+ Add the results to both sides. Because of how Jelly's auto-
vectorization works, this adds the first row of [A] (just A) to
the first row of the divisibility matrix (all zeroes) and
leaves the other rows untouched.
⁸;" Prepend the elements of P to the corresponding rows of the
previous result.
o⁶ OR space; replace all zeroes with spaces.
G Grid; format the matrix as requested in the challenge spec.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~25~~ 23 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
PÆfQ©ḍþµị⁾* ³;"Z⁶;®¤;"G
```
**[Try it online!](https://tio.run/nexus/jelly#@x9wuC0t8NDKhzt6D@87tPXh7u5Hjfu0FA5ttlaKetS4zfrQukNLrJXc////H21uqmNpqWNoagjExrEA)**
### How?
It may well be shorter to use `ÆE` and filter out empty rows.
```
PÆfQ©ḍþµị⁾* ³;"Z⁶;®¤;"G - Main link: list of numbers, L
µ - monadic chain separation
P - product of L - multiply them all together
Æf - prime factors (with repetitions, in ascending order)
Q - unique items, maintaining order
- note that the product was performed to keep order
© - place in the register for later use, and yield
þ - form the outer product of that and L using the dyad:
ḍ - isDivisor - 1 if divides, 0 if not
ị⁾* <space - index into "* " (1s to "*", 0s to " ")
³ - program's first input, L
;" - zip with concatenation (column headers to the left)
Z - transpose (get it around the right way)
¤ - nilad followed by link(s) as a nilad
⁶;® - space (⁶) concatenated with (;) the register value (®)
;" - zip with concatenation (row labels to the left)
G - format the result as a grid (join items with spaces and
rows with line feeds so they align)
- implicit print
```
[Answer]
# JavaScript (ES6), ~~264~~ ~~260~~ ... ~~179~~ 173 bytes
```
a=>[for(c of s=' '.repeat(w=a.slice(-1),i=0))if(!+(r=[i++?i:s,...i<2?a:a.map(x=>x%i&&c)].map(y=>(s+y).slice(-(w+1).length),a=a.map(d=x=>i<2|x%i?x:d(x/i))).join``))r].join`
`
```
I think this approach has now permanently exceeded the recursive one (currently 178 bytes):
```
f=(a,i=0,w=a.slice(-1))=>i++-w?(+(r=[i<2?'':i,...i<2?a:a.map(x=>x%i&&' ')].map(y=>(' '.repeat(w)+y).slice(-(w+1).length)).join``)?'':r+`
`)+f(a.map(d=x=>i<2|x%i?x:d(x/i)),i,w):''
```
Uses `0` in place of `*`, which is allowed by the challenge.
### Test snippet
```
let g =
a=>[for(c of s=' '.repeat(w=a.slice(-1),i=0))if(!+(r=[i++?i:s,...i<2?a:a.map(x=>x%i&&c)].map(y=>(s+y).slice(-(w+1).length),a=a.map(d=x=>i<2|x%i?x:d(x/i))).join``))r].join`
`
console.log(g([6,9,14,22]))
console.log(g([2,3,5,7]))
console.log(g([2,4,8,16,32]))
console.log(g([75,99,151,153]))
```
[Answer]
# Python 2 - 197 bytes
Switched to Python 2 for easier input handling and allowing `` for string conversion. Uses `gmpy2` for generating the next prime. Output format still based on previous Python 3 submission (see below), namely filling a list `g` with symbols and formatting it.
```
import gmpy2
i=input()
n=len(i)+1
p=1;g=[' ']+i
while p<i[-1]:
p=gmpy2.next_prime(p)
t=['*'[m%p:]for m in i]
if'*' in t:g+=[p]+t
print((('{:>%d}'%(len(`i[-1]`)+1)*n+'\n')*(len(g)/n)).format(*g))
```
[Try it online!](https://tio.run/nexus/python2#HY7BCsIwEETPzVfkUpJtqtIigtX4IzGoYI0LZl1KREX89hp7nBnezIwY@T4kGSK/W4EWiR9JgyB760kjmEawbTbBOiWVNyieV7z1krfoZo3vRMF2QufUv9KBB4y9ZhBFykClXCy585f7IKNEkuhFgZfs/0XqgrGOvUkiY5S01urT7crzV5X6P36cJo75AlRk1J4UVFMQYEEA81wbT0lXAWAc3ape182yblv/Aw "Python 2 – TIO Nexus")
## Explanation
For those who don't want to decode it themselves.
```
import gmpy2 # arithmetic library
i=input()
n=len(i)+1 # saves bytes by not needing ()
# afterwards
p=1 # starting number
g=[' ']+i # initialsing header row
while p<i[-1]: # looping until last character
p=gmpy2.next_prime(p) # get the next prime
t=['*'[m%p:] for m in i] # verify whether p is a
# divisor of each number
if'*'in t:g+=[p]+t # if any divisor found, append
# p + divisors to g.
print(
(('{:>%d}'%(len(`i[-1]`)+1) # compute right formatting element
# for length of last character + 1
*n+'\n' # repeat for each input + once
# for the prime and add newline
)*(len(g)/n) # repeat row format until g
# can be inserted
).format(*g) # format using g
)
```
# Previous
## Python 3 - 251 bytes
Pretty sure someone can do better. Based on [this answer](https://codegolf.stackexchange.com/a/6297/63647) for generating the primes < `k`.
```
i=list(map(int,input().split(',')))
l=len(str(i[-1]))+1
n=len(i)+1
g=[0]+i+sum([l for l in [[k]+[j%k==0for j in i]for k in range(2,i[-1])if all(k%f for f in range(2,k))]if 1in l],[])
print((('{:>%d}'%l*n+'\n')*(len(g)//n)).format(*g).replace('0',' '))
```
Ungolfed version and explanation will follow.
[Answer]
# Mathematica, 165 bytes
Rather verbose - maybe someone can do something with it:
```
(j=Join;a=#[[All,1]]&/@FactorInteger@#;b=Sort@DeleteDuplicates@Flatten@a;Grid[j[{j[{""},#]},Transpose@j[{b},Table[If[MemberQ[a[[t]],#],"*",""]&/@b,{t,Length@a}]]]])&
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + GNU utilities, ~~134~~ ~~133~~ ~~132~~ ~~125~~ 123 bytes
```
q=printf\ ;u=$q%9s
$u
$q%9d $@
echo
for p in $($u\\n `factor $@`|bc|sort -un)
{
$q%9d $p
for x;{ ((x%p))&&$u||$u X;}
echo
}
```
[Try it online!](https://tio.run/nexus/bash#NYyxCoMwFEX3fMUbnpIMDlKkhCD4GQ4ZtKlBlyTGBATjZ3dObUuHC4cD5@a1dX4xQUsQscW14BvBSD7wBOzIpGZLtPXgYDGAFKOUBgY9qnBJ7Ib0UGmzPkAVDSPHv3TfaBcHULoXjrGyxJgSRujF@Xs9c873JnOe66a@dnsZW6lRzdMb "Bash – TIO Nexus")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~181~~ 179 bytes
-2 bytes thanks to FlipTack
```
n=input()
p=[]
t="%%%ss "%len(`n[-1]`)*-~len(n)
print t%(('',)+n)
i=2
while n[-1]/i:
if all(i%j for j in p):
p+=[i];s=['*'[m%i:]for m in n]
if'*'in s:print t%tuple([i]+s)
i+=1
```
The input must be a tuple.
[Try it online!](https://tio.run/nexus/python2#NY1BCsMgFETX9RSfgKjRUCylpRZPIkK6SOgPxko0dNerp6bQ3czwZmaLFmNaCxckWedJsQ2lNGdoaBgi76PrtO9F2312Gyu1YCxQKOeMKSFrgvZE3k8MA/zgIxoCOMIjBI50gvG1wAQYIQlDDklah/6erWMtczNF43dg3oHoyQHHmledzf@orCkMvJZkFnVYWr1t/KJuSp@Vvoov "Python 2 – TIO Nexus")
[Answer]
## Batch, 451 bytes
```
@echo off
set/am=0,w=2,p=1
for %%n in (%*)do set/a"n=m-%%n,m+=(n>>31)*n
for /l %%i in (0,1,9)do set/am/=10,w+=!!m
set s=
for %%n in ("" %*)do set t=%%~n&call:t
set v=%*
:g
if not %s: =%==%p% echo%s%
if %m%==1 exit/b
set/at=p+=1,m=0
set s=
call:t
set v=&for %%n in (%v%)do set n=%%n&set t=&call:c
goto g
:c
set/ar=n%%p
if %r%==0 set/an/=p&set t=*&goto c
set/a"m|=n
set v=%v% %n%
:t
set t= %t%
call set s=%%s%%%%t:~-%w%%%
```
Explanation: Starts by calculating the field width `w` via the maximum of the input values `m`. Generates the first line of output by padding an empty string and the input numbers to the width `w` using the subroutine `t`. Then loops through the integers starting at 2, generating the line of output by padding the integer and then calling the subroutine `c` to pad an empty string or an asterisk as appropriate for each value, however the generated line is then skipped if it contains no asterisks. As the output is generated, each value is divided by the integer until it would leave a remainder, so the loop terminates when no value is greater than 1.
Note that the `set v=` gets executed *after* the `%v%` is substituted into the `for` loop on the same line.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~157~~ ~~148~~ ~~146~~ ~~145~~ 143 bytes
```
def p(*t):print'%%%ds '%len(`x[-1]`)*len(t)%t
def f(x):k=m=1;p(' ',*x);exec"r=[n%k and' 'for n in x]\nif 0in m%k*r:p(k,*r)\nm*=k*k;k+=1;"*x[-1]
```
Uses `0` instead of `*`, as allowed by the rules.
[Try it online!](https://tio.run/nexus/python2#JU9dC4MwDHyevyIIxbbLYPVzKv0lKjimgnR20vWh/9617iFwudwll2OaF9gpt6zZzaptQgiZvpCQ96zp6LqbGEbGQ2MZsVFQL9SxRslNinanCSTIHWtnN79iIztNFDz15OnlY0DDqsENvV4XuHu4EcVNs1OF3LBeb1wqrlp19atifh47gs0FGy2xRpFjmjIEmmKGBVZ/mOMDRYnZOakKrL2wEL4y1kSXkC@6nN8cPw "Python 2 – TIO Nexus")
### Background
To identify primes, we use a corollary of [Wilson's theorem](https://en.wikipedia.org/wiki/Wilson%27s_theorem):

### How it works
The first line defines a helper function.
```
def p(*t):print'%%%ds '%len(`x[-1]`)*len(t)%t
```
**p** takes a variable number of arguments which it stores in the tuple **t**.
The `'%%%ds '%len(`x[-1]`)` uses a format string to construct a format string; `%%` is a literal percent sign, `%d` is a placeholder for the integer that `len(`x[-1]`)` returns, i.e., the number of digits of the last element in **x** (the input, not yet defined), and `s` is literal.
If, e.g., the last element of **x** has three digits, this yields `%3s`, which `*len(t)` repeats once for every element of **x**. Finally, `%t` applies that format string to the tuple **t**, constructing a string of **t**'s elements, space-separated and all right-justified to a certain length.
The second line defines the actual submission: a function **f** that takes a list **x** as input. After replacing the `exec` statement, which executes the string it precedes `x[-1]` times, with a `for` loop, we get the following code.
```
def f(x):
k=m=1;p(' ',*x)
for _ in range(x[-1]):
r=[n%k and' 'for n in x]
if 0in m%k*r:p(k,*r)
m*=k*k;k+=1
```
First, **f** initializes **k** and **m** to **1**. Note that **(k - 1)! = 0! = 1 = m**.
Then, `p(' ',*x)` prints a space and the integers in **x**, using the function **p**.
Now, we enter the loop to print the remaining output.
First, `r=[n%k and' 'for n in x]` constructs the list of the remainders of each integer **n** in **x** divided by **k**. Positive remainders, i.e, remainders that do not correspond to multiples of **k**, are truthy and get replaced with a space by `and' '`.
Next, we construct `m%k*r`. Since **m = (k - 1)!**, by the corollary of Wilson's theorem, this will be simply **r** if **k** is prime, but an empty list if not. If there is at least one **0** in the result, i.e., if **k** is prime and at least one integer in **x** is divisible by **k**, `0in m%k*r` will return *True* and `p(k,*r)` get called, printing **k** and the divisibility indicators: `0` if divisible, a space if not.
Finally, we multiply **m** by **k²** and increment **k**, so the quality **m = (k - 1)!** continues to hold.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 31 bytes
```
pYfu!Gy\~h0GhwvVZ{'(?<!\d)0'0YX
```
This uses `1` instead of `*`, as allowed by the challenge.
[Try it online!](https://tio.run/nexus/matl#@18QmVaq6F4ZU5dh4J5RXhYWVa2uYW@jGJOiaaBuEBnx/3@0mY6CpY6CoYmOgpFRLAA "MATL – TIO Nexus") Or [verify all test cases](https://tio.run/nexus/matl#S4jw/l8QmVaq6F0ZU5dh4J1RXhYWVa2uYW@jGJOiaaBuEBnx3yXkf7SZjoKljoKhiY6CkVEsV7SRjoKxjoKpjoI5hAMUtwBKA1UZg6TNgTKWIPWmhiDCOBYA).
### Explanation (*outdated*)
```
p % Implictly input array of numbers. Push product of array
Yf % Prime factors as a row vector
u % Keep only unique values
! % Transpose into column vector
G % Push input again
y % Duplicate column vector of unique prime factors onto top
\ % Modulo, element-wise with broadcast
~ % Negate
h % Concatenate horizontally
0 % Push 0
G % Push input again
h % Concatenate horizontally
w % Swap
v % Concatenate vertically
V % Char array representation
Z{ % Convert to cell array of strings. Each row gives a string
'(?<!\d)0' % Push this string: match '0' not preceded by a digit
0 % Push this string: '0' will be replaced by char 0
YX % Regexp replace
% Implicit inoput. Char 0 is displayed as space
```
[Answer]
## Racket 176 bytes
```
(let((p printf))(display" ")(for((x nl))(p" ~a " x))(displayln"")(for((i '(2 3 7 11)))
(p"~a " i)(for((j nl))(if(member i(prime-divisors j))(p" * ")(p" ")))(displayln"")))
```
Ungolfed:
```
(define (f nl)
(let ((p printf))
(display " ")
(for ((x nl))
(p " ~a " x))
(displayln "")
(for ((i '(2 3 7 11)))
(p "~a " i)
(for ((j nl))
(if (member i (prime-divisors j))
(p " * ")
(p " ")))
(displayln ""))))
```
Testing:
```
(f '(6 9 14 22))
```
Output:
```
6 9 14 22
2 * * *
3 * *
7 *
11 *
```
] |
[Question]
[
Given a list of strings `s_0, s_1, ..., s_n` find the shortest string `S` that contains each of `s_0, s_1, ..., s_n` as a [substring](http://en.wikipedia.org/wiki/Substring#Substring).
*Examples*:
* `S('LOREM', 'DOLOR', 'SED', 'DO', 'MAGNA', 'AD', 'DOLORE')='SEDOLOREMAGNAD'`
* `S('ABCDE', 'BCD', 'C')='ABCDE'`
Write the shortest program (or function) that solves this problem. You can represent strings as arrays or lists of characters/integers if you want. Standard libraries are OK. For input/output you can use whatever is more convenient: STDIN/STDOUT, user prompt, parameter/return value of a function etc.
Performance is not critical - let's say, for an input of total length < 100 characters the result must be computed in < 10 second on average modern hardware.
[Answer]
# Python 2, 170 153/157/159
Shortened thanks to some of [Baptiste's ideas](https://codegolf.stackexchange.com/a/11630/7409).
```
from itertools import*
print min((reduce(lambda s,w:(w+s[max(i*(s[:i]==w[-i:])for i in range(99)):],s)[w in s],p)
for p in permutations(input())),key=len)
```
The second line break is not needed.
Input: `'LOREM', 'DOLOR', 'SED', 'DO', 'MAGNA', 'AD', 'DOLORE'`
Output: `SEDOLOREMAGNAD`
Even with long input strings, this runs in less than 2 seconds if there are at most 7 input strings (as is the case in the example given, which runs in 1.7 1.5 seconds on my machine). With 8 or more input strings, however, it takes more than 10 seconds, since the time complexity is `O(n!)`.
As Baptiste pointed out, `range(99)` needs to be replaced with `range(len(w))` if arbitrary input lengths should be supported (making the total length of the code 157 characters). If empty input strings should be supported, it has to be changed to `range(len(w)+1)`. I think `range(99)` works correctly for any total input length less than 200, though.
More tests:
```
>>> "AD", "DO", "DOLOR", "DOLORE", "LOREM", "MAGNA", "SED", "ORE", "R"
SEDOLOREMAGNAD
>>> 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', 'abcdefghijklmnopqrstuvw
... xyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstu
... vwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 'ZOOM', 'aZ', 'Za', 'ZA'
aZABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZOOM
```
[Answer]
# Mathematica 337 418 372
After trying unsuccessfully to implement using Mathematica's `LongestCommonSubsequencePositions`, I turned to pattern matching.
```
v=Length;
p[t_]:=Subsets[t,{2}];
f[w_]:=Module[{c,x,s=Flatten,r={{a___,Longest[y__]},{y__,b___}}:>{{a,y},{y,b},{y},{a,y,b}}},
c=p@w;
x=SortBy[Cases[s[{#/.r,(Reverse@#)/.r}&/@c,1],{_,_,_,_}],v[#[[3]]]&][[-1]];
Append[Complement[w,{x[[1]],x[[2]]}],x[[4]]]]
g[r_]:=With[{h=Complement[r,Cases[Join[p@r,p@Reverse@r],y_/;!StringFreeQ@@y:>y[[2]]]]},
FixedPoint[f,Characters/@h,v@h-1]<>""]
```
The pattern-matching rule,
```
r={{a___,Longest[y__]},{y__,b___}}:> {{a,y},{y,b},{y},{a,y,b}}},
```
takes an ordered pair of words (represented as lists of characters) and returns: (1) the words,`{a,y}` and `{y,b}` followed by (2) the common substring,`y`, that links the end of one word with the beginning of the other word, and, finally, the combined word `{a,y,b}` that will replace the input words. See Belisarius for a related example: <https://mathematica.stackexchange.com/questions/6144/looking-for-longest-common-substring-solution>
Three consecutive underscore characters signify that the element is a sequence of zero or more characters.
`Reverse` is employed later to ensure that both orders are tested. Those pairs that share linkable letters are returned unchanged and ignored.
**Edit**:
The following removes from the list words that are "buried" (i.e. fully contained) in another word, (in response to @flornquake's comment).
```
h=Complement[r,Cases[Join[p@r,p@Reverse@r],x_/;!StringFreeQ@@x:> x[[2]]]]
```
---
**Example**:
```
{{"D", "O", "L", "O", "R", "E"}, {"L", "O", "R", "E", "M"}} /. r
```
returns
>
> {{"D", "O", "L", "O", "R", "E"}, {"L", "O", "R", "E", "M"}, {"L", "O",
> "R", "E"}, {"D", "O", "L", "O", "R", "E", "M"}}
>
>
>
---
**Usage**
```
g[{"LOREM", "ORE", "R"}]
AbsoluteTiming[g[{"AD", "DO", "DOLOR", "DOLORE", "LOREM", "MAGNA", "SED", "ORE", "R"}]]
```
>
> "LOREM"
>
>
> {0.006256, "SEDOLOREMAGNAD"}
>
>
>
[Answer]
# Python 2, 203 187 200
```
from itertools import permutations as p
def n(c,s=''):
for x in c:s+=x[next((i+1 for i,l in [(j,x[:j+1])for j in range(len(x))][::-1]if s.endswith(l)),0):]
return s
print min(map(n,p(input())),key=len)
```
Input: `['LOREM', 'DOLOR', 'SED', 'DO', 'MAGNA', 'AD', 'DOLORE']`
Output: `SEDOLOREMAGNAD`
**Edit**
Using `reduce` and some dirty import trickery, I can reduce this further (and to one line only!):
```
print min((reduce(lambda a,x:a+x[next((i+1 for i,l in [(j,x[:j+1])for j in range(len(x))][::-1]if a.endswith(l)),0):],P,'')for P in __import__('itertools').permutations(input())),key=len)
```
**Edit 2**
As flornquake noted, this gives incorrect results when one word is contained in another. The fix for this adds another 13 chars:
```
print min((reduce(lambda a,x:a+(x[next((i+1 for i,l in [(j,x[:j+1])for j in range(len(x))][::-1]if a.endswith(l)),0):],'')[x in a],P,'')for P in __import__('itertools').permutations(input())),key=len)
```
Here's the cleaned up version:
```
from itertools import permutations
def solve(*strings):
"""
Given a list of strings, return the shortest string that contains them all.
"""
return min((simplify(p) for p in permutations(strings)), key=len)
def prefixes(s):
"""
Return a list of all the prefixes of the given string (including itself),
in ascending order (from shortest to longest).
"""
return [s[:i+1] for i in range(len(s))]
return [(i,s[:i+1]) for i in range(len(s))][::-1]
def simplify(strings):
"""
Given a list of strings, concatenate them wile removing overlaps between
successive elements.
"""
ret = ''
for s in strings:
if s in ret:
break
for i, prefix in reversed(list(enumerate(prefixes(s)))):
if ret.endswith(prefix):
ret += s[i+1:]
break
else:
ret += s
return ret
print solve('LOREM', 'DOLOR', 'SED', 'DO', 'MAGNA', 'AD', 'DOLORE')
```
It's possible to shave off a few characters at the cost of theoretical correctness by using `range(99)` instead of `range(len(x))` (credits to flornquake for thinking of this one).
[Answer]
## Python, 144 chars
```
S=lambda A,s:min(S(A-set([a]),s+a[i:])for a in A for i in range(len(a)+1)if i==0 or s[-i:]==a[:i])if A else(len(s),s)
T=lambda L:S(set(L),'')[1]
```
`S` takes a set of words `A` that still need placing and a string `s` containing words placed so far. We pick a remaining word `a` from `A` and overlap it from `0` to `len(a)` characters with the end of `s`.
Takes only about 0.15 seconds on the given example.
[Answer]
# Haskell, 121
```
import Data.List
a p []=[(length p,p)]
a p s=[r|w<-s,t<-tails w,isInfixOf w$p++t,r<-a(p++t)(s\\[w])]
s=snd.minimum.a ""
```
Minus two if the function doesn't need to be bound to a name
] |
[Question]
[
Write a program (or function) that takes in a positive integer.
If the input is `1`, print (or return) two diamonds neighboring side-by-side, each with a side length of 1 slash:
```
/\/\
\/\/
```
For every input `N` greater than 1, look at the output for `N-1` and for each pair of neighboring diamonds, insert a new diamond in between them whose side length is the sum of the side lengths of the two neighbors. Print (or return) this new diamond pattern.
So when `2` is input, we look at the output for `1` and can see that there are two neighboring diamonds, both with side length 1. So we insert a side length 2 (1+1) diamond in between them:
```
/\
/\/ \/\
\/\ /\/
\/
```
For input `3` we look at the output for `2` and add two diamonds with side length 3 (1+2 and 2+1) in between the two pairs of neighboring diamonds:
```
/\ /\
/ \ /\ / \
/\/ \/ \/ \/\
\/\ /\ /\ /\/
\ / \/ \ /
\/ \/
```
Continuing the pattern, the output for `4` is:
```
/\ /\
/\ / \ / \ /\
/ \ /\ / \ / \ /\ / \
/ \ / \ / \ /\ / \ / \ / \
/\/ \/ \/ \/ \/ \/ \/ \/\
\/\ /\ /\ /\ /\ /\ /\ /\/
\ / \ / \ / \/ \ / \ / \ /
\ / \/ \ / \ / \/ \ /
\/ \ / \ / \/
\/ \/
```
And so on.
Your outputs may have trailing spaces on any lines but only up to one trailing newline (and no leading newlines).
**The shortest code in bytes wins.**
[Answer]
# Pyth, ~~50~~ 49 bytes
```
L.rR"\/"_bjbyK.tsm+Jm+*\ k\\dyJu.iGsM.:G2tQjT9djK
```
[Demonstration](https://pyth.herokuapp.com/?code=L.rR%22%5C%2F%22_bjbyK.tsm%2BJm%2B%2a%5C+k%5C%5CdyJu.iGsM.%3AG2tQjT9djK&input=3&debug=0)
Explanation:
```
L.rR"\/"_bjbyK.tsm+Jm+*\ k\\dyJu.iGsM.:G2tQjT9djK
Implicit:
Q = eval(input())
T = 10
d = ' '
b = '\n'
L def y(b): return
.rR"\/" Swap \ and / in
_b reversed input.
This effectively vertically
mirrors the input.
u Apply the function repeatedly
jT9 Starting with [1, 1]
tQ and repeating Q - 1 times
.iG interlace G (input) with
.:G2 All 2 element substrings of G
sM mapped to their sums.
m map over these values
implicitly cast to ranges
m d map over the range values
impicitly cast to ranges
+*\ k\\ to k spaces followed by
a backslash.
J Save to J, which is roughly:
\
\
+ yJ And add on y(J), giving
\
\
/
/
s Combine the half diamonds
into one list.
.t d Traspose, filling with ' '.
K Save to K, giving
something like:
\ /
\/
y Vertically mirror.
jb Join on newlines and print.
jK Join K on (implicitly)
newlines and print.
```
[Answer]
# Common Lisp, 425
```
(labels((a(n)(if(> n 1)(loop for(x y)on(a(1- n))by #'cdr collect x when y collect(+ x y))'(1 1))))(lambda(~ &aux(l(a ~))(h(apply'max l))(w(*(apply'+ l)2))(o(* 2 h))(m(make-array(list o w):initial-element #\ ))(x 0)(y h))(labels((k(^ v)(setf(aref m y x)^(aref m(- o y 1)x)v)(incf x))(d(i)(when(plusp i)(k #\\ #\/)(incf y)(d(1- i))(decf y)(k #\/ #\\))))(mapc #'d l))(dotimes(j o)(fresh-line)(dotimes(i w)(princ(aref m j i))))))
```
## Example
```
(funcall *fun* 4)
/\ /\
/\ / \ / \ /\
/ \ /\ / \ / \ /\ / \
/ \ / \ / \ /\ / \ / \ / \
/\/ \/ \/ \/ \/ \/ \/ \/\
\/\ /\ /\ /\ /\ /\ /\ /\/
\ / \ / \ / \/ \ / \ / \ /
\ / \/ \ / \ / \/ \ /
\/ \ / \ / \/
\/ \/
```
## Ungolfed
```
(labels
((sequence (n)
(if (> n 1)
(loop for(x y) on (sequence (1- n)) by #'cdr
collect x
when y
collect(+ x y))
'(1 1))))
(defun argyle (input &aux
(list (sequence input))
(half-height (apply'max list))
(width (* (apply '+ list) 2))
(height (* 2 half-height))
(board (make-array
(list height width)
:initial-element #\ ))
(x 0)
(y half-height))
(labels ((engrave (^ v)
(setf (aref board y x) ^ ;; draw UP character
(aref board (- height y 1) x) v ;; draw DOWN character (mirrored)
)
(incf x) ;; advance x
)
(draw (i)
(when (plusp i)
(engrave #\\ #\/) ;; write opening "<" shape of diamond
(incf y)
(draw (1- i)) ;; recursive draw
(decf y)
(engrave #\/ #\\) ;; write closing ">" shape of diamond
)))
;; draw into board for each entry in the sequence
(mapc #'draw list))
;; ACTUAL drawing
(dotimes(j height)
(fresh-line)
(dotimes(i width)
(princ (aref board j i))))
board))
```
[Answer]
# CJam, ~~59~~ ~~58~~ 57 bytes
```
YXbri({{_2$+\}*]}*:,_:|,S*0'\tf{fm>_W%'\f/'/f*}:+zN*_W%N@
```
*Thanks to @MartinBüttner for golfing off 1 byte.*
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=YXbri(%7B%7B_2%24%2B%5C%7D*%5D%7D*%3A%2C_%3A%7C%2CS*0'%5Ctffm%3E%7B_W%25'%5Cf%2F'%2Ff*%7D%25%3A%2BzN*_W%25N%40&input=4).
### Idea
For input **3**, for example, we generate
```
\
/
\
\
\
/
/
/
\
\
/
/
\
\
\
/
/
/
\
/
```
by rotating the string `\` and replacing some backslashes with slashes.
Then, we zip the resulting array (transpose rows and columns) to obtain the lower half of the desired output.
The upper half is byte per byte equal to the lower half in reverse.
### Code
```
YXb e# Push A := [1 1] and 2 in unary.
ri( e# Read an integer fro STDIN and subtract 1.
{ e# Do the following that many times:
{ e# For each I in A but the first:
_2$ e# Push a copy of I and the preceding array element.
+\ e# Compute the sum of the copies and swap it with I.
}* e#
] e# Collect the entire stack in an array.
}* e#
:, e# Replace each I in A with [0 ... I-1].
_ e# Push a copy of A.
:| e# Perform set union of all the ranges.
,S* e# Get the length (highest I in A) and push a string of that many spaces.
0'\t e# Replace the first space with a backslash.
f{ e# For each range in A, push the generated string; then:
fm> e# Rotate the string by each amount in the array.
_W% e# Push a reversed copy of the resulting array of strings.
'\f/ e# In each string, split at backslashes.
'/f* e# Join each string, separating with slashes.
} e#
:+ e# Concatenate the resulting arrays of strings.
zN* e# Zip and join, separating by linefeeds.
_W% e# Push a reversed copy of the string.
N@ e# Push a linefeed and rotate the original string on top of it.
```
[Answer]
# Rev 1: Ruby 170
New method avoiding creating the big diamond and reducing.
```
->n{a=[1]
m=1<<n-1
(m-1).times{|i|a<<a[i]<<a[i]+a[i+1]}
(-b=a.max).upto(b-1){|j|0.upto(m){|i|d=' '*q=a[-i]*2
(j*2+1).abs<q&&(d[j%q]=?\\;d[-1-j%q]=?/)
print d}
puts""}}
```
# Rev 0: Ruby, 187
```
->n{a=[1]
m=1<<n-1
(m-1).times{|i|a<<a[i]<<a[i]+a[i+1]}
(2*b=a.max).times{|j|
0.upto(m){|i|d=' '*b*2;d[(b+j)%(b*2)]='\\';d[(b-1-j)%(b*2)]=?/
r=b-a[-i]
d.slice!(b-r,r*2)
print d}
puts ""}}
```
The sizes of the diamonds are calculated in accordance with the recurrence relation from <https://oeis.org/A002487> Thus we make the array `a` containing all the elements for all the rows from 1 to `n`. We are only interested in the last `1<<n-1` elements (Ruby allows us to get them from the array using negative indexes, -1 being the last element in the array), plus an inital `1` from position 0.
Line by line and diamond by diamond, we draw the row of characters for the biggest diamond, then cut out the middle columns to get the row for the required diamond. Rev 1 is shorter, but I liked this method.
Modular arithmetic is used to wrap around so that the same expression adds all `/` directly and likewise one expression adds all `\` directly.
**Ungolfed in test program**
```
f=->n{
a=[1]
m=1<<n-1
(m-1).times{|i|a<<a[i]<<a[i]+a[i+1]} #concatenate a[i] and a[i]+a[i+1] to the end of a
(2*b=a.max).times{|j| #run through lines (twice the largest number in a
0.upto(m){|i| #run through an initial '1' plus the last m numbers in a
d=' '*b*2;d[(b+j)%(b*2)]='\\';d[(b-1-j)%(b*2)]=?/ #d is the correct string for this line of the largest diamond
r=b-a[-i] #calculate number of characters to be deleted from middle of d
d.slice!(b-r,r*2) #and delete them
print d #print the result
}
puts "" #at the end of the line, print a newline
}
}
f.call(gets.to_i)
```
] |
[Question]
[
This challenge is in honor of the Rookie of the Year category winners of [Best of PPCG 2015](https://codegolf.meta.stackexchange.com/questions/8007/cast-your-vote-for-best-of-ppcg-2015): [muddyfish](https://codegolf.stackexchange.com/users/32686/muddyfish) (for [I'm not the language you're looking for!](https://codegolf.stackexchange.com/questions/55960/im-not-the-language-youre-looking-for)) and [quartata](https://codegolf.stackexchange.com/users/45151/quartata) (for [Implement a Truth-Machine](https://codegolf.stackexchange.com/questions/62732/implement-a-truth-machine)).
Congratulations!
## Background
In the deepest trenches of the ocean, there lives a rare and elusive square-shaped fish called the *quartata-fish*.
It looks like the [glider](https://en.wikipedia.org/wiki/Glider_%28Conway's_Life%29) from the Game of Life cellular automaton.
Here are two quartata-fish of different sizes:
```
-o-
--o
ooo
--oo--
--oo--
----oo
----oo
oooooo
oooooo
```
You have managed to snap a photo of the quartata-fish, but the fish is rather hard to see since it's covered in mud.
Now you'll have to write a program to clean up the photo.
## Input
Your input is a rectangular 2D grid of the characters `.-o#`, given as a newline-separated string.
If you want, you can use pipes `|` instead of newlines as the separators, and you may assume one trailing and/or preceding separator.
The input will contain exactly one quartata-fish of some side-length `3*n`, where `n ≥ 1` is a positive integer, surrounded by periods `.` that represent the ocean floor.
The fish will always be in the orientation depicted above.
Overlaid on this grid, there will be exactly one non-empty rectangular region of hashes `#`, which represents a blob of mud.
The blob may cover the quartata-fish partially or entirely.
An example input would be
```
............
..--oo--....
..--oo--....
..---#####..
..---#####..
..ooo#####..
..oooooo....
```
## Output
Your output shall be generated from the input by replacing all the hashes with the characters `.-o`, so that the grid contains exactly one quartata-fish.
There will always be a unique way to perform this replacement properly; in particular, the blob of mud will cover the fish entirely only if its size is 3×3.
The output shall use the same separator as the input.
For the above input, the correct output would be
```
............
..--oo--....
..--oo--....
..----oo....
..----oo....
..oooooo....
..oooooo....
```
## Rules and scoring
You can write a full program or a function.
The lowest byte count wins, and [standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default/) are disallowed.
There are no time bounds: if your submission would eventually halt given unlimited time and resources, you're fine.
## Test cases
```
Input:
.......
...-o-.
...--o.
##.ooo.
##.....
Output:
.......
...-o-.
...--o.
...ooo.
.......
Input:
...-o-.
...-#o.
...ooo.
.......
Output:
...-o-.
...--o.
...ooo.
.......
Input:
.........
.###.....
.###.....
.ooo.....
Output:
.........
.-o-.....
.--o.....
.ooo.....
Input:
.....
.###.
.###.
.###.
Output:
.....
.-o-.
.--o.
.ooo.
Input:
......
......
......
...###
...###
...###
Output:
......
......
......
...-o-
...--o
...ooo
Input:
###o--....
###o--....
###-oo....
###-oo....
###ooo....
###ooo....
###.......
Output:
--oo--....
--oo--....
----oo....
----oo....
oooooo....
oooooo....
..........
Input:
............
..--oo--....
..--oo--....
..---#####..
..---#####..
..ooo#####..
..oooooo....
Output:
............
..--oo--....
..--oo--....
..----oo....
..----oo....
..oooooo....
..oooooo....
Input:
...--oo--....
.#########...
.#########...
.#########...
...oooooo....
...oooooo....
.............
.............
Output:
...--oo--....
...--oo--....
...----oo....
...----oo....
...oooooo....
...oooooo....
.............
.............
Input:
..............
..............
.########.....
.########.....
.########-....
.########-....
.########o....
.########o....
.########o....
.########o....
.########.....
..............
Output:
..............
..............
..............
..............
....--oo--....
....--oo--....
....----oo....
....----oo....
....oooooo....
....oooooo....
..............
..............
Input:
.................
.................
..---ooo---......
..--#########....
..--#########....
..--#########....
..--#########....
..--#########....
..oo#########....
..oo#########....
..oo#########....
....#########....
Output:
.................
.................
..---ooo---......
..---ooo---......
..---ooo---......
..------ooo......
..------ooo......
..------ooo......
..ooooooooo......
..ooooooooo......
..ooooooooo......
.................
Input:
.........................
.........................
....----oooo----.........
....----########.........
....----########.........
....----########.........
....----########.........
....----########.........
....----########.........
....----########.........
....oooo########.........
....oooo########.........
....oooooooooooo.........
....oooooooooooo.........
.........................
Output:
.........................
.........................
....----oooo----.........
....----oooo----.........
....----oooo----.........
....----oooo----.........
....--------oooo.........
....--------oooo.........
....--------oooo.........
....--------oooo.........
....oooooooooooo.........
....oooooooooooo.........
....oooooooooooo.........
....oooooooooooo.........
.........................
```
[Answer]
## Python 2, ~~433~~ 411 bytes
```
import re;i,o,l,j=input(),range,lambda s,r:s.replace(*r),"".join;i=l(l(l(i,".1"),"#."),"| ");s=o(len(i))
for x in s:
for y in s:
for q in s:
r=map(list,l(l(i,"o."),"-.").split(" "))
try:
for v in o(q):r[x+v][y:y+q]=["".join(c*(q/3)for c in b)for b in["-o-","--o","ooo"]][3*v/q]
m=re.match(i," ".join(j(i)for i in r))
except:0
if sum("-"in p for p in r)and m:print"|".join(l(j(i),"1.")for i in r);_
```
Exits with a `NameError`. Takes input pipe separated.
I'm mixing tabs and spaces here. SE doesn't render tabs properly.
```
'###o--....|###o--....|###-oo....|###-oo....|###ooo....|###ooo....|###.......'
--oo--....|--oo--....|----oo....|----oo....|oooooo....|oooooo....|..........
'.....|.###.|.###.|.###.'
.....|.-o-.|.--o.|.ooo.
'...-o-.|...-#o.|...ooo.|.......'
...-o-.|...--o.|...ooo.|.......
```
(Note extra spaces at the start are for prettiness only and aren't actually printed)
[Answer]
# JavaScript (ES6), 291 bytes
```
g=>eval('w=g.search`\n`;h=g.length/w|0;for(n=(w<h?w:h)/3|0;s=n*3;n--)for(x=w+1-s;x--;)for(y=h+1-s;y--;[...g].every((c,i)=>c==o[i]|c=="#")?z=p:0)for(p="",i=h;i--;)p=(l=[,"-o-","--o","ooo"][(i-y)/n+1|0],l?"."[t="repeat"](x)+l.replace(/./g,c=>c[t](n))+"."[t](w-x-s):"."[t](w))+(p?`\n`:"")+p;z')
```
## Explanation
Takes input grid as a newline separated string. Not completely golfed, will do more when I get time.
It works by:
* Getting every possible position and size of a fish in the bounds of the input grid.
* For each position/size, it builds a grid string with a fish in that position.
* Checks if this is the correct output by iterating over every character. If each character either matches or is a hash, it outputs the built string.
```
var solution =
g=>
eval(`
// Get size of input grid
w=g.search\`\n\`;
h=g.length/w|0;
// Check every possible size (n) and position (x and y) of fish
for(n=(w<h?w:h)/3|0;s=n*3;n--)
for(x=w+1-s;x--;)
for(y=h+1-s;y--;
// Check if possible solution matches input grid
[...g].every((c,i)=>c==p[i]|c=="#")?z=p:0
)
// Create possible solution grid
for(p="",i=h;i--;)
p=(
l=[,"-o-","--o","ooo"][(i-y)/n+1|0],
l?
"."[t="repeat"](x)+
l.replace(/./g,c=>c[t](n))+
"."[t](w-x-s)
:"."[t](w)
)+(p?\`\n\`:"")+p;
z
`)
```
```
<textarea id="input" rows="6" cols="40">..............
..............
.########.....
.########.....
.########-....
.########-....
.########o....
.########o....
.########o....
.########o....
.########.....
..............</textarea><br />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```
[Answer]
## Python 2, 325 bytes
```
def f(s):
s=map(list,s.split());R=range;L=len(s);M=len(s[0])
for h in R(L/3*3,0,-3):
for x in R(M-h+1):
for y in R(L-h+1):
if all(s[v%L][v/L]in".-#o #"[0<=v%L-y<h>v/L-x>=0::2]for v in R(L*M)):
for k in R(h*h):s[y+k/h][x+k%h]="-o"[482>>k/h*3/h*3+k%h*3/h&1]
return'\n'.join(map(''.join,s)).replace('#','.')
```
A badly golfed solution for now – the `for .. in range(...)`s are an utter train wreck. Inputs/outputs newline separated strings.
The byte count currently assumes space indents only – I'll switch to mixed tabs/spaces later when I'm done golfing, if necessary.
] |
[Question]
[
Digging around in the depths of your temp folder, you find some compositions for the piano. Unfortunately, these compositions were written with note names and durations only, and you only have access to a text terminal. Therefore, your task is to write a program to display the compositions as ASCII art.
## Input
Your program should accept two strings as input. The first string will represent the notes of the top staff (with the treble clef), while the second string will represent the notes of the bottom staff.
The notes will be passed in [scientific pitch notation](https://en.wikipedia.org/wiki/Scientific_pitch_notation). The top staff's notes will always be between `C4` and `C6` inclusive. The bottom staff's notes will always be between `C2` and `C4` inclusive.
Each note will come with a duration, which will be one of: `1`, `2`, `4`, `8`. These represent a whole note (semibreve), a half note (minim), a quarter note (crotchet), and an eighth note (quaver) respectively.
Notes of any other duration will never appear in the input.
How the note and duration is separated, and how each note is separated from other notes in the input is up to your discretion. The following is a sample input for the top staff:
```
E4/4 A4/8 C#5/8 E5/2
```
Here, the notes are separated by a space, and the duration is separated from the note with a forward slash. These delimeters are not fixed, and you may choose to change them or omit them altogether.
You may assume there is at least one note in each staff. There are no rests in the input.
## Output
Your program is to output the score as ASCII art, conforming to the following descriptions.
The clefs should be the first thing at the left of your output (the distance between the two staves should not be changed):
```
^
| |
------|/----
/
-----/|-----
/ |
---/--__----
| / \
---\-\|-|---
\ | /
------|-----
|
\_/
----___-----
/ \ |
---\---|----
| |
-------/----
/
-----/------
------------
```
A note's stem (the vertical line next to the circle) should point upwards if the note is below the middle line of a staff. It should point downwards if the note is above the middle line of a staff. If the note is on the middle line, then the stem may point in either direction. (The only exception to this is for the bonus, and occurs when connecting eighth notes, described later). The stem should begin on the line above/below the circle, and be `6` lines tall.
All types of notes except whole notes have stems. The flag of an eighth note is represented by two forward slashes on different lines (see example notes below).
A filled in note head (for quarter and eighth notes) is represented by `(@)`. An empty note head (for half and whole notes) is represented by `( )`.
Accidentals (sharps, flats, naturals) should be placed as shown in the example notes, with exactly one character between the right side of the accidental and the left side of the note head.
Ledger lines should be used when necessary, and should be `7` characters in length, centered around the note head.
Each note should be `12` characters wide.
Example notes:
```
|_
|_| ( )
| |------
|
------------ ---------|-- ------------ ------------ ------------
|
------------ ---------|-- ---|-------- ------------ ------------
(@) _|_|_ | |_
-----|------ _|_|_-( )--- ---|/-(@)--- ------------ ---------|\-
| | | | | \
-----|------ ------------ -----|------ ------------ ---------|--
| | |
-----|------ ------------ -----|------ ------------ ---------|--
| | / |
|/ --(@)--
quarter note half note eighth note whole note eighth note
sharped flatted natural
```
After the 12-character note, leave `2 * 12 - 12 = 12` characters blank (either or `-` depending on the line) if the note is a quarter note. If the note is a half note, leave `4 * 12 - 12 = 36` characters blank. If the note is a whole note, leave `8 * 12 - 12 = 84` characters blank. Do not add extra characters for eighth notes.
At the end of each measure (96 characters after either the clef or bar line), output a bar line. This is done by going down every character between the uppermost and bottom-most lines (inclusive), and replacing with `|` and `-` with `+`. (See example output at bottom of question).
At the end of the piece, output the music end by outputting 3 bar lines in a row, but with a space between the first and second. That is:
```
+-++
| ||
+-++
| ||
. ..
. ..
```
Note that sharps, flats, and naturals last until the end of the measure. The natural sign should only be used to cancel out a sharp or flat used earlier in the same measure.
For the purpose of this task, sharps, flats, and naturals only affect a note in one octave, and in one clef (a sharp on A5 does not cause A4 to be sharped, and a flat on C4 in the top staff does not cause C4 in the bottom staff to be flatted).
**Information for the bonus only**
The bonus involves properly connecting eighth notes.
When there are two consecutive eighth notes, aligned to the quarter note beat (in other words, the number of characters before the first eighth note is a multiple of 24), the two eighth notes are to be connected.
Let note **A** be the note farthest from the middle of the staff. If both notes are the same distance from the middle, either note may be note **A**. Let the other note be note **B**.
The direction of *both* stems should be the direction of the stem of note **A**.
The stem of one of the notes should be `6` lines tall (as is the case for stems in general), and the stem of the other note should be extended to the end of the stem of the other note.
The stems should be connected with `_`.
Example connected eighth notes:
```
___________
| |
| |
| |
| | --(@)--
| | | |
------------------------ ---|_----|-----------|-- -----|------------------
|/ (@) | | |_
------------------------ ---------------------|-- -----|--------|_|-(@)---
(@) _|_|_ | | ||
-----|------_|_|_-(@)--- ---------------------|-- -----|-----------|------
| | | | | | |
-----|-----------|------ ---------------------|-- -----|-----------|------
| | | | |
-----|-----------|------ ------------------(@)--- -----|___________|------
| |
|___________|
```
## Example input and output
**Input**:
```
A#4/4 G#4/4 F#4/2 A#4/4 G#4/4 F#4/2 F#4/8 F#4/8 F#4/8 F#4/8 G#4/8 G#4/8 G#4/8 G#4/8 A#4/4 G#4/4 F#4/2
A#3/4 G#3/4 F#3/2 A#3/4 G#3/4 F#3/2 F#3/2 G#3/2 F#3/4 E#3/4 F#3/2
```
**Output**:
```
^
| | | | |
------|/-------------|-----------------------|--------------------------------------------------------------+---------|-----------------------|--------------------------------------------------------------+----------___________-------------___________------------|\----------|\----------|\----------|\-+---------|-----------------------|--------------------------------------------------------------+-++
/ | | | | | | | | | | | | | \ | \ | \ | \| | | | | ||
-----/|--------------|-----------------------|-----------------------|--------------------------------------+---------|-----------------------|-----------------------|--------------------------------------+---------|-----------|-----------|-----------|-----------|-----------|-----------|-----------|--+---------|-----------------------|-----------------------|--------------------------------------+-++
/ | | | | | | | | | | | | | | | | | | | | | | ||
---/--__----_|_|_----|-----------------------|-----------------------|--------------------------------------+_|_|_----|-----------------------|-----------------------|--------------------------------------+---------|-----------|-----------|-----------|-----------|-----------|-----------|-----------|--+_|_|_----|-----------------------|-----------------------|--------------------------------------+-++
| / \ _|_|_ (@) _|_|_ | | |_|_|_ (@) _|_|_ | | | | | | | _|_|_ | | | | |_|_|_ (@) _|_|_ | | | ||
---\-\|-|----|-|--------------------_|_|_-(@)---------------_|_|_----|--------------------------------------+-|-|--------------------_|_|_-(@)---------------_|_|_----|--------------------------------------+_|_|_----|-----------|-----------|-----------|--_|_|_-(@)---------(@)---------(@)---------(@)---+-|-|--------------------_|_|_-(@)---------------_|_|_----|--------------------------------------+-++
\ | / | | _|_|_ ( ) | | | _|_|_ ( ) |_|_|_ (@) (@) (@) (@) | | | | | _|_|_ ( ) | ||
------|------------------------------------------------------|-|--------------------------------------------+-------------------------------------------------|-|--------------------------------------------+-|-|--------------------------------------------------------------------------------------------+-------------------------------------------------|-|--------------------------------------------+-++
| | | | | ||
\_/ | | | | ||
| | | | ||
| | | | ||
| | | | ||
| | | | ||
_|_|_ |_|_|_ | | | ||
----___-----_|_|_-(@)---------------_|_|_-------------------------------------------------------------------+_|_|_-(@)---------------_|_|_-------------------------------------------------------------------+------------------------------------------------_|_|_-------------------------------------------+------------------------------------------------------------------------------------------------+-++
/ \ | | | | _|_|_ (@) _|_|_ | | | | _|_|_ (@) _|_|_ |_|_|_ _|_|_ ( ) |_|_|_ | ||
---\---|---------|-------------------|-|-|------------------_|_|_-( )---------------------------------------+-----|-------------------|-|-|------------------_|_|_-( )---------------------------------------+_|_|_-( )----------------------------------------|-|-|------------------------------------------+_|_|_ (@)---------------_|_|_-------------------------( )---------------------------------------+-++
| | | | | | | | | | | | | | | | | | | | | | _|_|_ (@) | | ||
-------/---------|-----------------------|-----------------------|------------------------------------------+-----|-----------------------|-----------------------|------------------------------------------+-----|-----------------------------------------------|------------------------------------------+-----|-------------------|-|-|-----------------------|------------------------------------------+-++
/ | | | | | | | | | | | | | | | ||
-----/-----------|-----------------------|-----------------------|------------------------------------------+-----|-----------------------|-----------------------|------------------------------------------+-----|-----------------------------------------------|------------------------------------------+-----|-----------------------|-----------------------|------------------------------------------+-++
| | | | | | | | | | | | | ||
-----------------------------------------------------------------|------------------------------------------+-----------------------------------------------------|------------------------------------------+-----|------------------------------------------------------------------------------------------+-----|-----------------------|-----------------------|------------------------------------------+-++
|
```
For the sake of demonstration, in the third measure, the `F#` eighth notes are connected, whereas the `G#` eighth notes are not. Your program should either connect the eighth notes whenever applicable (for the bonus), or leave them all disconnected.
## Other information
* Any amount of trailing whitespace/lines is acceptable.
* There should be no extra whitespace before the clefs, nor whitespace between notes. Any number of blank lines may be emitted before/after the output.
* The bonus for connecting eighth notes is **0.75 \* number of bytes of source code**.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins.
[Answer]
# Python - 8.85... KB (~~9369~~ 9066 B)
HaHA! Fastest gun in the... West?
This is FAR from being properly golfed, but it at least functions. At the moment of posting this, it's the shortest entry, so... yay?
Let me start by saying that I've never golfed anything this big, and I don't even know where to START.
This entry does *not* contain the bonus points yet, but I'd still like to add that before golfing.
I basically wrote a kind of ASCII rendering class that stores the characters that make up each "block" in a 2D format so that any number of different "symbols" could be drawn over the 2D grid. For note blocks, the staff was drawn first, then any staff extending bars as necessary, then the note head, followed by the stem and tail (where applicable) and last the accidental.
When given the following two inputs for trebble and bass clefs:
```
A#4/4 G#4/4 F#4/2 A#4/4 G#4/4 F#4/2 F#4/8 F#4/8 F#4/8 F#4/8 G#4/8 G#4/8 G#4/8 G#4/8 A#4/4 G#4/4 F#4/2
A#3/4 G#3/4 F#3/2 A#3/4 G#3/4 F#3/2 F#3/2 G#3/2 F#3/4 E#3/4 F#3/2
```
The following output results:
```
^
| | | | |
------|/-------------|-----------------------|--------------------------------------------------------------+---------|-----------------------|--------------------------------------------------------------+---------------------------------------------------------|\----------|\----------|\----------|\-+---------|-----------------------|--------------------------------------------------------------+-++
/ | | | | | | | | |\ |\ |\ |\ | \ | \ | \ | \| | | | | ||
-----/|--------------|-----------------------|-----------------------|--------------------------------------+---------|-----------------------|-----------------------|--------------------------------------+---------|-\---------|-\---------|-\---------|-\---------|-----------|-----------|-----------|--+---------|-----------------------|-----------------------|--------------------------------------+-++
/ | | | | | | | | | | | | | | | | | | | | | | ||
---/--__----_|_|_----|-----------------------|-----------------------|--------------------------------------+_|_|_----|-----------------------|-----------------------|--------------------------------------+---------|-----------|-----------|-----------|-----------|-----------|-----------|-----------|--+_|_|_----|-----------------------|-----------------------|--------------------------------------+-++
| / \ _|_|_ (@) _|_|_ | | |_|_|_ (@) _|_|_ | | | | | | | _|_|_ | | | | |_|_|_ (@) _|_|_ | | | ||
---\-\|-|----|-|--------------------_|_|_-(@)---------------_|_|_----|--------------------------------------+-|-|--------------------_|_|_-(@)---------------_|_|_----|--------------------------------------+_|_|_----|-----------|-----------|-----------|--_|_|_-(@)---------(@)---------(@)---------(@)---+-|-|--------------------_|_|_-(@)---------------_|_|_----|--------------------------------------+-++
\ | / | | _|_|_ ( ) | | | _|_|_ ( ) |_|_|_ (@) (@) (@) (@) | | | | | _|_|_ ( ) | ||
------|------------------------------------------------------|-|--------------------------------------------+-------------------------------------------------|-|--------------------------------------------+-|-|--------------------------------------------------------------------------------------------+-------------------------------------------------|-|--------------------------------------------+-++
| | | | | ||
\_/ | | | | ||
| | | | ||
| | | | ||
| | | | ||
| | | | ||
_|_|_ |_|_|_ | | | ||
----___-----_|_|_-(@)---------------_|_|_-------------------------------------------------------------------+_|_|_-(@)---------------_|_|_-------------------------------------------------------------------+------------------------------------------------_|_|_-------------------------------------------+------------------------------------------------------------------------------------------------+-++
/ \ | | | | _|_|_ (@) _|_|_ | | | | _|_|_ (@) _|_|_ |_|_|_ _|_|_ ( ) |_|_|_ | ||
---\---|---------|-------------------|-|-|------------------_|_|_-( )---------------------------------------+-----|-------------------|-|-|------------------_|_|_-( )---------------------------------------+_|_|_-( )----------------------------------------|-|-|------------------------------------------+_|_|_-(@)---------------_|_|_-------------------------( )---------------------------------------+-++
| | | | | | | | | | | | | | | | | | | | | | _|_|_ (@) | | ||
-------/---------|-----------------------|-----------------------|------------------------------------------+-----|-----------------------|-----------------------|------------------------------------------+-----|-----------------------------------------------|------------------------------------------+-----|-------------------|-|-|-----------------------|------------------------------------------+-++
/ | | | | | | | | | | | | | | | ||
-----/-----------|-----------------------|-----------------------|------------------------------------------+-----|-----------------------|-----------------------|------------------------------------------+-----|-----------------------------------------------|------------------------------------------+-----|-----------------------|-----------------------|------------------------------------------+-++
| | | | | | | | | | | | | ||
-----------------------------------------------------------------|------------------------------------------+-----------------------------------------------------|------------------------------------------+-----|------------------------------------------------------------------------------------------+-----|-----------------------|-----------------------|------------------------------------------+-++
```
[Here's a working version](https://repl.it/BIbE/55) of the code with some faux input code since this particular python web IDE didn't allow for simulated input or separate files.
**grandstaff.py**
Contains both trebble and bass clef staffs, and handles drawing the barlines between the two.
```
class GrandStaff:
def __init__(self, trebbleStr, bassStr):
self.trebbleStr = trebbleStr
self.bassStr = bassStr
self.trebbleStaff = Staff("trebble", self.trebbleStr)
self.bassStaff = Staff("bass", self.bassStr)
self.bassOffset = 16
self.lines = {}
maxmin = self.trebbleStaff.getYExtremes()
for y in range(maxmin[0], maxmin[1] + 1):
self.lines[y] = self.trebbleStaff.lines[y]
maxmin = self.bassStaff.getYExtremes()
for y in range(maxmin[0], maxmin[1] + 1):
self.lines[y + self.bassOffset] = self.bassStaff.lines[y]
for y in range(5, 12):
self.lines.setdefault(y, [" " for x in range(len(self.trebbleStaff.getLineStr(0)))])
xpos = 0
for block in self.trebbleStaff.getBlocks():
if block.type == "barline":
self.lines[y][xpos] = '|'
elif block.type == "finalDoubleBarline":
for x in [0, 2, 3]:
self.lines[y][xpos + x] = '|'
xpos += block.width
def __str__(self):
outstr = ""
maxmin = sorted(self.lines.keys())
for y in range(maxmin[0], maxmin[-1]):
self.lines.setdefault(y, [" " for x in range(len(self.trebbleStaff.getLineStr(0)))])
outstr += ''.join(self.lines[y]) + '\n'
return outstr
```
**staff.py**
A single staff. Contains an array of "Block" objects that represent notes, barlines, clefs, etc. This class handles the spacing of the notes and insertion of the barlines at the appropriate places.
```
class Staff:
def __init__(self, clef, inputStr):
self.clef = clef
self.inStr = inputStr
self.lines = {}
self.__blocks = []
if clef == "trebble":
self.__blocks.append(Block("trebbleClef"))
elif clef == "bass":
self.__blocks.append(Block("bassClef"))
notes = inputStr.split(" ");
measureLength = 0
for note in notes:
if measureLength >= 1:
self.__blocks.append(Block("barline"))
measureLength -= 1
parts = note.split("/")
noteLength = 0
if len(parts) == 2:
noteLength += 1 / float(parts[1])
measureLength += noteLength
self.__blocks.append(Block("note", note, self.clef))
for n in range(int(noteLength * 8) - 1):
self.__blocks.append(Block("staff"))
self.__blocks.append(Block("finalDoubleBarline"))
sharps = []
flats = []
naturals = []
for block in self.__blocks:
if block.type == "note":
val = block.value
if block.isSharp:
if val not in sharps:
sharps.append(val)
else:
block.clearAccidental()
elif block.isFlat:
if val not in flats:
flats.append(val)
else:
block.clearAccidental()
else:
if val in sharps:
sharps.remove(val)
block.setNatural()
if val in flats:
flats.remove(val)
block.setNatural()
elif block.type == "barline" or block.type == "finalDoubleBarline":
sharps = []
flats = []
maxmin = self.getYExtremes()
for y in range(maxmin[0], maxmin[1] + 1):
self.lines[y] = list(self.getLineStr(y))
def getLineStr(self, lineNum):
outstr = ""
for block in self.__blocks:
outstr += block.getLineStr(lineNum)
return outstr
def getYExtremes(self):
maxmin = [0, 0]
for block in self.__blocks:
mm = block.getYExtremes()
maxmin[0] = mm[0] if mm[0] < maxmin[0] else maxmin[0]
maxmin[1] = mm[1] if mm[1] > maxmin[1] else maxmin[1]
return maxmin
def getBlocks(self):
return self.__blocks
def __str__(self):
maxmin = self.getYExtremes()
outstr = ""
for line in range(maxmin[0], maxmin[1] + 1):
outstr += self.getLineStr(line) + "\n"
return outstr
```
**block.py**
This class handles the "rendering" (or perhaps composition) of the ASCII text. Inside are the hard-coded symbols such as the trebble and bass clefs, a blank staff, barlines, accidentals, and the necessary pieces to build notes of different durations. These are "drawn" onto a 2D grid of character "pixels" in sequential order to produce the final ASCII block.
```
class Block:
__staff = [[range(-4, 5, 2),"w",'-']]
__trebble = [[-6, 7, '^'], [range(-5, 6), 6, '|'], [-5, 8, '|'], [-4, 7, '/'], [-3, 6, '/'], [-2, 5, '/'], [-1, 4, '/'], [0, 3, '/'], [0, range(6,8), '_'], [1, 3, '|'], [1, 5, '/'], [1, 6, ' '], [1, 8, '\\'], [2, 3, '\\'], [2, 5, '\\'], [2, 8, '|'], [3, 4, '\\'], [3, 8, '/'], [6, 4, '\\'], [6, 5, '_'], [6, 6, '/']]
__bass = [[-4, range(4, 7), '_'], [-3, 3, '/'], [-3, 7, '\\'], [range(-3, 0, 2), 9, '|'], [-2, 3, '\\'], [range(-2, 0), 7, '|'], [0, 7, '/'], [1, 6, '/'], [2, 5, '/']]
__sharp = [[range(-1, 1), range(0, 5), '_'], [range(-1, 2), range(1, 4, 2), '|']]
__flat = [[range(-2, 1), 3, '|'], [-1, 4, '_'], [0, 4, '/']]
__natural = [[range(-1, 1), 2, '|'], [range(-1, 1), 3, '_'], [range(0, 2), 4, '|']]
__noteOpen = [[0, 6, '('], [0, 7, ' '], [0, 8, ')']]
__noteClosed = [[0, 6, '('], [0, 7, '@'], [0, 8, ')']]
__stemUp = [[range(-6, 0), 9, '|']]
__stemDown = [[range(1, 7), 5, '|']]
__eighthTailUp = [[-6, 10, '\\'], [-5, 11, '\\']]
__eighthTailDown = [[6, 6, '/'], [5, 7, '/']]
__barline = [[range(-4, 5), 0, '+'], [range(-3, 4, 2), 0, '|']]
__finalBarline = [[range(-4, 5, 2), [0, 2, 3], '+'], [range(-3, 4, 2), [0, 2, 3], '|'], [range(-4, 5, 2), 1, '-']]
__staffExtender = [[0, range(4, 11), '-']]
def __init__(self, type, notestr = "", clef = "trebble"):
if type == "note":
self.clef = clef
self.notestr = notestr.upper().split('/')[0]
self.duration = int(notestr.upper().split('/')[1])
self.isSharp = True if notestr[1] == '#' else False
self.isFlat = True if notestr[1] == 'b' else False
self.isNatural = False;
self.__clefCallibration = {"trebble":{"A":1,"B":0,"C":6,"D":5,"E":4,"F":3,"G":2,"octave":4}, "bass":{"A":-4,"B":-5,"C":1,"D":0,"E":-1,"F":-2,"G":-3,"octave":3}}
self.value = self.__clefCallibration[self.clef][self.notestr[0]] + ((self.__clefCallibration[self.clef]["octave"] - int(self.notestr[-1])) * 7)
self.lines = {}
self.type = type
self.__drawBlock()
def __drawBlock(self):
self.lines = {}
if self.type == "note":
self.width = 12
self.__draw(self.__staff)
for y in range(6, self.value + 1, 2):
self.__draw(self.__staffExtender, y)
for y in range(-6, self.value - 1, -2):
self.__draw(self.__staffExtender, y)
if self.duration in [1, 2]:
self.__draw(self.__noteOpen, self.value)
else:
self.__draw(self.__noteClosed, self.value)
if self.duration != 1:
if self.value < 0:
self.__draw(self.__stemDown, self.value)
if self.duration == 8:
self.__draw(self.__eighthTailDown, self.value)
else:
self.__draw(self.__stemUp, self.value)
if self.duration == 8:
self.__draw(self.__eighthTailUp, self.value)
if self.isSharp:
self.__draw(self.__sharp, self.value)
elif self.isFlat:
self.__draw(self.__flat, self.value)
elif self.isNatural:
self.__draw(self.__natural, self.value)
# self.__draw(__staffExtender, self.value)
elif self.type == "staff":
self.width = 12
self.__draw(self.__staff)
elif self.type == "barline":
self.width = 1
self.__draw(self.__barline)
elif self.type == "finalDoubleBarline":
self.width = 4
self.__draw(self.__finalBarline)
elif self.type == "trebbleClef":
self.width = 12
self.__draw(self.__staff)
self.__draw(self.__trebble)
elif self.type == "bassClef":
self.width = 12
self.__draw(self.__staff)
self.__draw(self.__bass)
def __draw(self, data, yOffset = 0):
for char in data:
self.__drawChunk(char, yOffset)
def __drawChunk(self, char, yOffset = 0):
xrng = []
yrng = []
drawChr = char[2]
if type(char[0]) == int:
yrng = [char[0]]
elif type(char[0]) == list:
yrng = char[0]
else:
print("ERROR: invalid y range input")
if type(char[1]) == str:
if char[1] == 'w':
xrng = range(self.width)
elif type(char[1]) == int:
xrng = [char[1]]
elif type(char[1]) == list:
xrng = char[1]
else:
print("ERROR: invalid x range input")
yrng = [y + yOffset for y in yrng]
for y in yrng:
self.lines.setdefault(y,[" " for i in range(self.width)])
for x in xrng:
self.lines[y][x] = drawChr
def getLineStr(self, lineNum):
return "".join(self.lines.setdefault(lineNum, [" " for i in range(self.width)]))
def getYExtremes(self):
k = sorted(self.lines.keys())
return [k[0], k[-1]]
def setSharp(self):
self.isSharp = True
self.isFlat = False
self.isNatural = False
self.__drawBlock()
def setFlat(self):
self.isSharp = False
self.isFlat = True
self.isNatural = False
self.__drawBlock()
def setNatural(self):
self.isSharp = False
self.isFlat = False
self.isNatural = True
self.__drawBlock()
def clearAccidental(self):
self.isSharp = False
self.isFlat = False
self.isNatural = False
self.__drawBlock()
def __str__(self):
strOut = ""
first = sorted(self.lines.keys())[0]
last = sorted(self.lines.keys())[-1]
for line in range(first, last + 1):
strOut += self.getLineStr(line) + "\n"
return strOut
```
**main.py**
This class simply "runs" the program by creating an instance of GrandStaff, passing it the given string inputs, and printing it's string value.
```
import sys
from block import *
from grandstaff import *
from staff import *
print (GrandStaff(sys.argv[1],sys.argv[2]))
```
] |
[Question]
[
Implement the shortest Sudoku solver.
**Sudoku Puzzle:**
```
| 1 2 3 | 4 5 6 | 7 8 9
-+-----------------------
A| 3 | 1 |
B| 6 | | 5
C| 5 | | 9 8 3
-+-----------------------
D| 8 | 6 | 3 2
E| | 5 |
F| 9 3 | 8 | 6
-+-----------------------
G| 7 1 4 | | 9
H| 2 | | 8
I| | 4 | 3
```
**Answer:**
```
| 1 2 3 | 4 5 6 | 7 8 9
-+-----------------------
A| 8 3 2 | 5 9 1 | 6 7 4
B| 4 9 6 | 3 8 7 | 2 5 1
C| 5 7 1 | 2 6 4 | 9 8 3
-+-----------------------
D| 1 8 5 | 7 4 6 | 3 9 2
E| 2 6 7 | 9 5 3 | 4 1 8
F| 9 4 3 | 8 1 2 | 7 6 5
-+-----------------------
G| 7 1 4 | 6 3 8 | 5 2 9
H| 3 2 9 | 1 7 5 | 8 4 6
I| 6 5 8 | 4 2 9 | 1 3 7
```
**Rules:**
1. Assume all sudokus are solvable by logic only.
2. All input will be 81 characters long. Missing characters will be 0.
3. Output the solution as a single string.
4. The "grid" may be stored internally however you wish.
5. The solution must use a non-guessing solution. (see [Sudoku Solver](http://www.sudokusolver.co.uk/))
**Example I/O:**
```
>sudoku.py "030001000006000050500000983080006302000050000903800060714000009020000800000400030"
832591674496387251571264983185746392267953418943812765714638529329175846658429137
```
[Answer]
**RUBY** (449 436 chars)
```
I=*(0..8)
b=$*[0].split('').map{|v|v<'1'?I.map{|d|d+1}:[v.to_i]};f=b.map{|c|!c[1]}
[[z=I.map{|v|v%3+v/3*9},z.map{|v|v*3}],[x=I.map{|v|v*9},I],[I,x]
].map{|s,t|t.map{|i|d=[a=0]*10;s.map{|j|c=b[i+j];c.map{|v|d[v]+=1if !f[i+j]}
v,r=*c;s.map{|k|b[i+k].delete(v)if j!=k}if !r
s[(a+=1)..8].map{|k|s.map{|l|b[i+l]-=c if l!=k&&l!=j}if c.size==2&&c==b[i+k]}}
v=d.index 1;f[i+k=s.find{|j|b[i+j].index v}]=b[i+k]=[v]if v}}while f.index(!1)
p b*''
```
Example:
```
C:\golf>soduku2.rb 030001000006000050500000983080006302000050000903800060714000009020000800000400030
"832591674496387251571264983185746392267953418943812765714638529329175846658429137"
```
quick explanation:
Board `b` is an array of 81 arrays holding all the possible values for each cell.
The array on line three holds [offset,start\_index] for each group (boxes,rows,columns).
Three tasks are performed while iterating through the groups.
1. The value of any cell of size 1 is removed from the rest of the group.
2. If any pair of cells contain the same 2 values, these values are removed from the rest of the group.
3. The count of each value is stored in `d` - if there is only 1 instance of a value, we set the containing cell to that value, and mark the cell fixed in `f`
Repeat until all cells are fixed.
[Answer]
# Prolog - 493 Characters
```
:-use_module(library(clpfd)).
a(X):-all_distinct(X).
b([],[],[]).
b([A,B,C|X],[D,E,F|Y],[G,H,I|Z]):-a([A,B,C,D,E,F,G,H,I]),b(X,Y,Z).
c([A,B,C,D,E,F,G,H,I|X])-->[[A,B,C,D,E,F,G,H,I]],c(X).
c([])-->[].
l(X,Y):-length(X,Y).
m(X,Y):-maplist(X,Y).
n(L,M):-l(M,L).
o(48,_).
o(I,O):-O is I-48.
:-l(L,81),see(user),m(get,L),seen,maplist(o,L,M),phrase(c(M),R),l(R,9),m(n(9),R),append(R,V),V ins 1..9,m(a,R),transpose(R,X),m(a,X),R=[A,B,C,D,E,F,G,H,I],b(A,B,C),b(D,E,F),b(G,H,I),flatten(R,O),m(write,O).
```
**Output:**
Inputting:
`000000000000003085001020000000507000004000100090000000500000073002010000000040009`
Outputs:
`987654321246173985351928746128537694634892157795461832519286473472319568863745219`
Inputting:
`030001000006000050500000983080006302000050000903800060714000009020000800000400030`
Outputs:
`832591674496387251571264983185746392267953418943812765714638529329175846658429137`
[Answer]
# [Perl 5](https://www.perl.org/), 295 bytes
```
sub P{$r=$p/9;$c=$p%9;$q=3*~~($r/3)+$c/3}sub N{($i,$u)=@_;P;$G[$p]=$u*$i;$R[$r]{$i}=$C[$c]{$i}=$Q[$q]{$i}=$u}sub S{if($p>80){print@G;exit}if($G[$p]){S(++$p);$p--}else{N($_,1),S(++$p),$p--,N($_)for grep{P;$R[$r]{$_}+$C[$c]{$_}+$Q[$q]{$_}<1}1..9}}@G=split'',$ARGV[0];N($G[$p=$_],1)for 0..80;$p=0;S
```
[Try it online!](https://tio.run/##PY5Ra4MwEMe/Sh9u1FSr57JuSpbh2INvxVXYi4gwsSMgWxoVBiH96s6o6x3kLr//cfeXjWoP49gNn5tMg@Igg5hBPdW7qV443V2vDqiAEhfqgBo7eNQOCA8GwpOKZQzSAmTJYdiBYHAqQJUahOHwVkC9tu8FXNZ2mHfkWpwdkC8REi2V@O6TlDW/ojcWzwuJzh3XBUkYyP3eNG3X6KMDlRcSb1U8q3gWkvOP2nypRursZqEy7r8F264WKvMcmtD3Y2OSlHeyFf1268HrKf0osGTH5TqHqpwO2a3o@xFOHjiyfBxHpIgYoo1H@xymtBFHFCMLKd4v3EKkM8On8GGZWsRo/lhE8Q8 "Perl 5 – Try It Online")
Shortened from 339 to 317 to 315 to 314 to 310 to 309 to 298 to 295
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~491~~ ~~490~~ ~~488~~ ~~465~~ 463 bytes
```
$w=,0*81;$c=,(1..9)*81
$a=(24,24,6)*3|%{,(0..8|%{($r++)});,(0..8|%{$v%81;$v+=9});$v++;,((1,1,7)*3|%{+$q;$q+=$_});$q-=$_}
filter g($v,$i){if($v){$a|?{$i-in$_}|%{$_|%{$c[$_]=$c[$_]-ne$v}};$w[$i]=$v;$c[$i]=@()}}
$args|% t*y|%{g($_-48)($i++)}
for(;$a|%{($b=$_)|?{($v=$c[$_])}|?{(($c[$b]|%{"$_"})-eq$v).Count-eq$v.Count
$c[$b]|%{$_}|group|? C* -eq 1|? N* -in $v|%{$v=+$_.Name;1}}|%{$b|?{"$v"-ne$c[$_]}|%{$c[$_]=@($c[$_]|?{$_-notin$v})}
g($v[0]*!$v[1])$_
1}}){}
-join$w
```
[Try it online!](https://tio.run/##VVHbjpswEH3nK1zkNDhA5PulCO1K@74/sIpQNku2tClsSEJaEb49HUM2VZ3IPnPmjOeM@WjOZXv4Xu52V7zN@ys@5wldWJbhTZ5EbLl0BKIAr/OIywT@mizEZdYnEV0uLYAIt3FMBpLdGdzNfH0X5w5oOGPIRSxhiZlqY7zP8D7OceHz@9SDYFvtjmWL3iPcJbgifbUFRHq8vjz0uEqrGkT@8sJvmxdcrPLpSOsSd8OQ4fMLroDsMs8DeozIMIDz9v1wmaHj4g9UwvVFKi2JcOVdB9umjTLo4ed4BR8EukHf29Vk8GHkg9cVaEJchANJyz04Wz41p/o44gkGd5l3@t42p4/LA3paINAgBvAZYFUj3I1vlMe4WD6vf5UZG8bBXqFXiLvQzzN2H/5N@hhNwL9FkdbNEZ6jG8C/f64Xulp8gYOtCC4CuI30Q5D@aEBzvg5B8BgFQRKhkApKKaN@ab8p@PnlrKDWk4LyifckFSNHDZOTakraMfCUoGESIIRCK7hyTBspnRbWcMWUYVxLuJdZZaQWjnNtnBKSWSeFZdxokEDCKu4Ed8woK7WGDbAwISKj4zn9b4FL5Qfgt1hRczfDRoef/LgMjMtv895Ubj46njsLBqTgjEvNjHBWCcUct@CVcQiMdmBOWsdhFDAOtB/SS7Q0QhoumFPaWi2MVJy5uXdM0AXNUO87IHw4vTU/TwnC5e@PcnMs31CO4OuMubY8nHZHIL7i7adyzIQ4uiXTTVMf11V9uNeTb5@FYTBc/wI "PowerShell – Try It Online")
Implemented Solving methods: Single, Naked Pair, Naked Trio, Naked Quad and Hidden Single.
See [Terms related to solving](https://en.wikipedia.org/wiki/Glossary_of_Sudoku#Terms_related_to_solving)
See also the [code with debug output](https://tio.run/##ZVVbb@o4EH7Pr/BJ3Y2dm3Ijl0VRu1rt2@po3xFCAUybXZrQJEAp@Ld3x3YgKcegxB7PfHP77OzqI2vaV7bdfuG/mqZu/lh1ZV3907ANa1i1YihHetvVO13TNvtKbqJN3bwVnbNr6iUjs7Lq5ri01bupjxSdNQQDH8AWH2e4nKv1qqjW5broBCZeDfLNWye8nD3bifjZt31@DsRUR84GkcFs5rluOEfOv3VZIcOgNriwvylErpuOFBT8J4BLERGeZiQ0ZZSu28@QhQI6p5rULjcE4nYAEf0YgKnKSAwdAHU0Gg@orbcHtpYanG1bBhg/riADhvtnva865Gw7lI3w8GeOP52G7bbFihnIsA3HuHP2gESli2W5LbsTqqvtafB1H9gDE01U@xof9ezYlB1ziqZRFlDK9PJ4xqccL24QIvkTcqB4oR2PYhSD2AQiM/2QmiGV5TSsIVB@mwFwIIChsGPoPlXVh6vzj3sNMQx0MUyCP25x/KIxph8imYlPFv6gSLj8psvpnfu7cDnEcBOp@rzWbYf6oLhiBC7GariurvRdzEUOC355aer97vKE@gazd@RfHtHP4o0NZqvdYPUkrR7PuljpV/u2bjrYcIWd@zerXrpXLh1IiUV0U7dgIZ1QKFA/dSrmUz6ik/SzUx2ykaF96@7nXVfHWf9SHmU6UjGc0QBk0MCb/PyFj7ltGGbqa3iV28R33YzKVZGTILLhHwNrIBn72nqCG8uinE5vEnx4TP0pPlh5BmJ4W7BH4DKwE2Vr4fcpfreAMmL/3RGTgd4vcGxtXNKzPMD0DF2DMpfAIVVrvBAPWf9cvaBw@MD5VN1QOT5M1Z2UPxPKOcTevLTQxs48gSXAL5wopQSXIm4NKEimkhkELyESCt7Abw9NuVgS3Mn1UvBExwudU@AGBNc3TszVVLupfaOT2XPpCf005WnAB1mo3OpJMfW5zG0J7nR80EVKMgA@JPtMRqxzqrqDihw4pCAqNvPmJlxVM39OgfSA1tPjdllAiyWT8PELmv1MNM0mSPdCz/N8T4xYPCbwEyNLQy8VwtALlFwIvVDKvMSPlJbaTOVCiEJPt4VbPQ2DSebHSRRlcZgmwcSfJH4QR4Drp5MkisMsCOIkm4SRn2ZRmPpBEoMKbKSTIAuDzE8maRTH8IB5mOgIrnWKLujx@k1q9@v6vz18OdjHjq06thbHRZ133LB2vxWfot/w5qopd3RM@k1nVVddUVbtzZ7@fjXUNf71Pw "PowerShell – Try It Online").
] |
[Question]
[
You must write a program that evaluates a string that would be entered into an advanced calculator.
The program must accept input using stdin and output the correct answer. For languages that do no have functions to accept stdin, you may assume the functions `readLine` and `print` to handle these tasks.
**Requirements:**
* Does not use any kind of "eval" functions
* Can handle floating point and negative numbers
* Supports at least the +, -, \*, /, and ^ operators
* Supports brackets and parenthesis for overriding the normal order
* Can handle input containing one **or more** spaces between the operators and numbers
* Evaluates the input using the standard [order of operations](http://en.wikipedia.org/wiki/Order_of_operations)
## Test Cases
Input
```
10 - 3 + 2
```
Output
```
9
```
---
Input
```
8 + 6 / 3 - 7 + -5 / 2.5
```
Output
```
1
```
---
Input
```
4 + [ ( -3 + 5 ) * 3.5 ] ^ 2 - 12
```
Output
```
41
```
[Answer]
## C++, 640 583
```
string k="[]()+-*/^";stack<double> m;stack<char> n;
#define C(o,x,y) ('^'==o?x<y:x<=y)
#define Q(a) double a=m.top();m.pop();
#define R(o) {Q(b)Q(a)m.push(o=='+'?a+b:o=='-'?a-b:o=='*'?a*b:o=='/'?a/b:o=='^'?pow(a,b):0);n.pop();}
while(!cin.eof()){string s;getline(cin,s,' ');if(s.empty())continue;if('\n'==*--s.end())s.erase(--s.end());(s.size()==1&&s.npos!=k.find(s[0]))?({char c=s[0]=='['?'(':s[0]==']'?')':s[0];while(!n.empty()&&'('!= c&&C(c,k.find(c),k.find(n.top())))R(n.top());')'==c?n.pop():n.push(c);}):m.push(strtod(s.c_str(),0));}while(!n.empty())R(n.top());cout<<m.top()<<endl;
```
**Indented**
```
string k="[]()+-*/^";
stack<double> m;
stack<char> n;
#define C(o,x,y) ('^'==o?x<y:x<=y)
#define Q(a) double a=m.top();m.pop();
#define R(o) {Q(b)Q(a)m.push(o=='+'?a+b:o=='-'?a-b:o=='*'?a*b:o=='/'?a/b:o=='^'?pow(a,b):0);n.pop();}
while(!cin.eof())
{
string s;
getline(cin,s,' ');
if(s.empty())continue;
if('\n'==*--s.end())s.erase(--s.end());
(s.size()==1&&s.npos!=k.find(s[0]))?({
char c=s[0]=='['?'(':s[0]==']'?')':s[0];
while(!n.empty()&&'('!= c&&C(c,k.find(c),k.find(n.top())))
R(n.top());
')'==c?n.pop():n.push(c);
}):m.push(strtod(s.c_str(),0));
}
while(!n.empty())
R(n.top());
cout<<m.top()<<endl;
```
My first code golf, so looking forward to comments & criticism!
[Answer]
# PHP - ~~394~~ ~~354~~ 312 characters
```
<?=e(!$s=preg_split('#\s+#',`cat`,-1,1),$s);function e($P,&$s){$S='array_shift';if(($a=$S($s))=='('|$a=='['){$a=e(0,$s);$S($s);}while($s&&($p=strpos(' +-*/^',$o=$s[0]))&&$p>=$P){$b=e($p+($S($s)!='^'),$s);if($o=='+')$a+=$b;if($o=='-')$a-=$b;if($o=='*')$a*=$b;if($o=='/')$a/=$b;if($o=='^')$a=pow($a,$b);}return$a;}
```
Indented:
```
<?
preg_match_all('#\d+(\.\d+)?|\S#',`cat`,$m);
$s=$m[0];
function e($P) {
global $s;
if (strpos(" ([",$s[0])){
array_shift($s);
$a=e(0);
array_shift($s);
} else {
$a=array_shift($s);
if ($a=='-')$a.=array_shift($s);
}
while ($s && ($p=strpos(' +-*/^',$o=$s[0])) && $p >= $P) {
array_shift($s);
$b = e($p+($o!='^'));
switch($o){
case'+':$a+=$b;break;
case'-':$a-=$b;break;
case'*':$a*=$b;break;
case'/':$a/=$b;break;
case'^':$a=pow($a,$b);
}
}
return $a;
}
echo e(0);
```
[Answer]
# Postscript, 446
This uses the shunting yard algorithm.
```
[/*[/p
2/e{mul}>>/d[/p
2/e{div}>>/+[/p
1/e{add}>>/-[/p
1/e{sub}>>/o[/p
9/e{}>>/c[/p
-1/e{}>>/^[/p
3/e{exp}>>/p
0>>begin/s(%stdin)(r)file 999 string readline pop def
0 1 s length 1 sub{s exch[0 1 255{}for]dup[(\(o)([o)(\)c)(]c)(/d)]{{}forall
put dup}forall
pop
3 copy pop
get
get
put}for{s token not{exit}if
exch/s exch store{cvr}stopped{load
dup/p get
p
le{currentdict end
exch begin/e get exec}{begin}ifelse}if}loop{{e end}stopped{exit}if}loop
=
```
Un-golfed and commented:
```
% We associate the operators with their precedence /p and the executed commend /e
[
(*)[/p 2 /e{mul}>>
(d)[/p 2 /e{div}>> % This is division
(+)[/p 1 /e{add}>>
(-)[/p 1 /e{sub}>>
(o)[/p 9 /e{ }>> % This is open bracket
(c)[/p -1 /e{ }>> % This is close bracket
(^)[/p 3 /e{exp}>>
/p 0
>>begin
% Let's read the input string
/s(%stdin)(r)file 999 string readline pop def
% If we want to use the token operator, we have to replace (, [, ), ] and / to get meaningful results
% We use kind of an encoding array (familiar to PostScripters) to map those codes to o, c, and d.
0 1 s length 1 sub{ % index
s exch % string index
[0 1 255{}for] dup % string index translationArray translationArray
[(\(o) ([o) (\)c) (]c) (/d)] % string index translationArray translationArray reencodeArray
{ % string index translationArray translationArray translationString
{}forall % string index translationArray translationArray charCode newCharCode
put dup % string index translationArray translationArray
}forall % string index translationArray translationArray
pop % string index translationArray
3 copy pop % string index translationArray string index
get % string index translationArray charCode
get % string index translatedCharCode
put % -/-
}for
% Now we can actually start interpreting the string
% We use the stack for storing numbers we read and the dictionary stack for operators that are "waiting"
{ % number*
s token not{exit}if % number* string token
exch /s exch store % number* token
% We try to interpret the token as a number
{cvr}stopped{ % number* token
% If interpretation as number fails, we have an operator
load % number* opDict
% Compare operator precedence with last operator on dictstack
dup /p get % number* opDict opPrec
p % number* opDict opPrec prevOpPrec
le { % number* opDict
% If the last operator on the stack has at least the same precedence, execute it
currentdict end % number* opDict prevOpDict
exch begin % number* prevOpDict
/e get exec % number*
}{ % number* opDict
% If last operator doesn't have higher precedence, put the new operator on the dictstack as well
begin
}ifelse
}if
}loop
% If we're finished with interpreting the string, execute all operators that are left on the dictstack
{{e end}stopped{exit}if}loop
=
```
**TODO**: Right-associativity of exponentation
[Answer]
# [Python 2](https://docs.python.org/2/),~~339~~ 335 bytes
```
import re
x,s=input(),re.sub
def f(y):
y,r=s('- ','+ -',y).split(),['^','*','/','+','-']
for c in r:
while c in y:d=y.index(c)-1;a,b=map(float,[y[d],y[d+2]]);y=y[:d]+[((a,-a)[a<0]**b,a*b,a/b,a+b,a-b)[r.index(c)]]+y[d+3:]
return`y[0]`
w=lambda b:s("[([]+[\d+\-*/^ .]*[)\]]",lambda m:f(m.group()[1:]),s(' +',' ',b))
print f(w(w(x)))
```
[Try it online!](https://tio.run/nexus/python2#PZDJbsMgEIbvfoqRL2YMOFtzIfWTEKKAwQ2SN2FbCQ/ec4rVqoM@xKxi/rfvpzEsEFz2YnPth2ldCLLgqnk1mXUttCSiyCCyUM@k4FCwggIvWMRqnjq/VcvilqJlYrdlE7xQGbRjgAb8ACH1w/PhO/frR2HrWPnBuhdpkB8umpm61xNpu1EvTEZpFUsXPSqFl1hHKayikhDNuEapP/eqLA3TG7sETXCDMvzPVIpu/SeRvhHcsobhHuVe3bNn3eneWA1GzCSXRKa5V0uvvNzdoFKlxKtSOfsr6kVL@uorjOtEUB6EQpY0gG3DpINBzKbghyVp9EznhYjvd/4BFCQQ4Kf0OAMglACn6gwKbnAEDpsdjvn3MPJGNw/3Aw "Python 2 – TIO Nexus")
* -4 bytes by changing str(x) with backticks ``!
[Answer]
# Postscript, ~~1000~~ ~~695~~ ~~665~~ 494
Stole ideas from ThomasW. ~~Added feature: accepts strings with or without spaces around operators.~~*[feature removed]*
---
Using `ARGUMENTS` is shorter than `%stdin`, and easier to test, to boot!
---
Simplified the substitution to just replace brackets with parens.
```
575(1)10:36 PM:ps 0> gsnd -q -- calc2bg.ps '10 - 3 + 2'
9
576(1)10:37 PM:ps 0> gsnd -q -- calc2bg.ps '8 + 6 / 3 - 7 + -5 / 2.5'
1.0
577(1)10:37 PM:ps 0> gsnd -q -- calc2bg.ps '4 + [ ( -3 + 5 ) * 3.5 ] ^ 2 - 12'
41.0
```
Code:
```
/T[/^[/C{exp}/P 4/X{le}>>/*[/C{mul}/P 3/X{lt}>>/[/C{div}/P
3/X{lt}>>/+[/C{add}/P 2/X{lt}>>/-[/C{sub}/P
2/X{lt}>>>>def[/integertype{}/realtype{}/stringtype{V}/nametype{cvlit/N
exch store{P T N get dup/P get exch/X get exec{exit}if C end}loop T N get
begin}91 40 93 41>>begin/V{0 1 2 index length 1 sub{2 copy get
dup where{exch get}if 3 copy put pop pop}for[/N 0/R 0/P 0/C{}>>begin{token
not{exit}if exch/R exch store dup type exec R}loop{P 0 eq{end exit}if C
end}loop}def ARGUMENTS{V ==}forall
```
Ungolfed and commented:
```
%!
%Shunting-Yard Algorithm using dictstack for operators
%invoke with %gsnd -q -- calc2bg.ps [ 'expr1' ]*
%The operator table. C:code P:precedence X:test(implements associativity)
/T[
/^[/C{exp}/P 4/X{le}>>
/*[/C{mul}/P 3/X{lt}>>
/[/C{div}/P 3/X{lt}>>
/+[/C{add}/P 2/X{lt}>>
/-[/C{sub}/P 2/X{lt}>>
>>def
%The type-dispatch dictionary
%numbers: do nothing
%string: recurse
%name: process op
[%/integertype{}/realtype{} %now uses `where` below
/stringtype{V}/nametype{
pstack()=
cvlit/N exch store %stash cur-op
{
P %prec(tos)
T N get %prec(tos) cur-op-dict
dup/P get %prec(tos) cur-op-dict prec(cur-op)
exch/X get %prec(tos) prec(cur-op) test(cur-op)
exec{exit}if %exit if prec(tos) < || <= prec(cur-op)
/C load ==
C %pop-and-apply
end
pstack()=
} loop
T N get begin %push cur-op
}>>begin
%substitutions
[91 40 93 41>>begin %replace brackets with parens
/V {
%pre-process
0 1 2 index length 1 sub {
2 copy get
dup where { exch get } if
3 copy put pop pop
} for
dup ==
[/N 0/R 0/P 0/C{}>>begin %dummy base operator and storage
{ token not{exit}if exch /R exch store %extract token, stash Remainder
pstack(>)=
%dispatch type procedure
dup type dup where { pop exec }{ pop } ifelse
R }loop
pstack()=
{
P 0 eq{end exit}if %hit dummy op: exit
/C load ==
C end %pop and apply
} loop
} def
ARGUMENTS{V ==}forall %iterate through the command-line arguments
```
] |
[Question]
[
When I see code-golf entries that knock a few characters off, whittling down the code, I go look at the edit history for a side-by-side diff. See and learn :)
This challenge is to make a program that produces the prettiest animated diffs.
* The input will be any ordered series of text versions.
* The program may be written in any programming language.
* It is allowed that the program limit itself to input data in some specific programming languages.
* The program should not be tuned to the specific input data; the program should be generic and work for any ordered series of text versions.
* For each version in the input there must be a corresponding time in the output animation where the full text of the version is displayed. You must animate the diff between version stages, and all version stages must be present and in order in the output. On these key frames, the version size must be shown and the viewer should understand this is a complete version they are seeing at that point.
* The program may not use any third party code to compute the diffs.
* Syntax highlighting output is optional. If the program colours syntax, it may not use any third party code to do so.
* The output will be an animated GIF.
* The program may use a third party library to author the GIF.
* This is a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"), so as per the definition of *popularity-contest* on this site, *the entry with the most votes wins*.
[Here's a simple example script](https://gist.github.com/williame/263bf661f0d0ba173c44#file-anim_code_golf-py-L144) that uses Python's [ndiff](https://docs.python.org/2/library/difflib.html) and [Pillow's](https://pypi.python.org/pypi/Pillow) rudimentary animated GIF support and animates each add and remove step:

Personally, I think this a pretty poor job. It doesn't do syntax highlighting, it doesn't try and move code chunks that get rearranged, it doesn't feel like someone is live editing it, and so on. It also breaks the rules regards showing the size of the input in bytes on key frames, and it uses a third party library to do the diffing. Lots of room for improvement!
And hopefully the popular entries will become useful fun tools for the codegolf.stackexchange.com community too. So its appreciated if the programs are easy for others to get running and use.
[Answer]
(OP)

This is based on the example Python script in the question.
I used the simplest edit distance rather than a cleverer patience diff.
For aligning genomes there's [Multi Sequence Alignment](http://en.wikipedia.org/wiki/Multiple_sequence_alignment) algorithms and they could well make an even better job than just considering each pair of adjacent frames?
I was pleasantly surprised how straightforward it was to implement [edit distance](https://gist.github.com/williame/2e93260c918e4bc1434e#file-anim1-py-L148) for the diff, and made it compatible with Python's `difflib.ndiff` format. There are plenty of Python implementations of edit distance to be found on the web, but I think my formulation is that little bit tidier and deals with the tricky but essential part of actually determining the path in the table too; in our context, we need to know the steps to turn one into another and not just how many steps there are.
I introduced syntax highlighting using a [very simple tokenizer](https://gist.github.com/williame/2e93260c918e4bc1434e#file-anim1-py-L211) that ought to be able to cope with most c-like languages including, by its laxity, Python and such. It splits the source into punctuation, whitespace, strings (with escape support) and everything else is an identifier and checked against a list of keywords. The [colouring](https://gist.github.com/williame/2e93260c918e4bc1434e#file-anim1-py-L202) is also easy to change.
It was easy to integrate the syntax highlighting into a dynamic language; the highlighter outputs a list of character and colour pairs, and the differ is agnostic to whether its diffing strings or any arbitrary iterables of comparables! An interesting - and deliberate - effect of highlighting first and then diffing is that characters that remain unchanged but change colour get animated. I didn't want to compute the highlight each frame as that would mean that as you delete a closing string you'd suddenly flash a big chunk of text up as string.
Python's support for authoring GIF is rather limited. PIL doesn't do it, and Pillow does it rather badly. I use Pillow, but then have to run through gifsicle to compress and add looping etc; Pillow doesn't correctly write frame timing and doesn't let you manage disposal methods etc, which is a shame as the differ has so much better understanding of the scene than a post-processing step dealing with flattened frames :(
[Sourcecode](https://gist.github.com/williame/2e93260c918e4bc1434e)
] |
[Question]
[
Consider all `2^n` different binary strings of length `n` and assume `n > 2`. You are allowed to delete exactly `b < n/2` bits from each of the binary strings, leaving strings of length `n-b` remaining. The number of distinct strings remaining depends on which bits you delete. Assuming your aim is to leave as few remaining different strings as possible, this challenge is to write code to compute how few can you leave as a function of `n`.
Example, `n=3` and `b = 1`. You can leave only the two strings `11` and `00`.
For `n=9` and `b = 1,2,3,4` we have `70,18,6,2`
For `n=8` and `b = 1,2,3` we have `40,10,4`
For `n=7` and `b = 1,2,3` we have `20,6,2`
For `n=6` and `b = 1,2` we have `12,4`
For `n=5` and `b = 1,2` we have `6,2`
This question was originally posed by me in 2014 in a different form on [MO](https://mathoverflow.net/questions/142857/puzzle-on-deleting-k-bits-from-binary-vectors-of-length-3k).
**Input and output**
Your code should take in an integer`n` and output a single integer for each value of `b` starting at `b = 0` and increasing.
**Score**
Your score is the largest `n` for which your code completes for all `b < n/2` in under a minute on my Linux based PC. In case of tie breaks, the largest `b` your code gets to for the joint largest `n` wins. In case of tie breaks on that criterion too, the fastest code for the largest values of `n` and `b` decides. If the times are within a second or two of each other, the first posted answer wins.
**Languages and libraries**
You can use any language of library you like. Because I have to run your code, it would help if it was free (as in beer) and worked in Linux.
[Answer]
**Python 2.7 / Gurobi** n=9
This solution is very straight usage of Gurobi's ILP solver for the boolean Mixed-Integer Problems (MIP).
The only trick is to take out symmetry in 1's complement to halve the problem sizes.
Using Gurobi LLC's limited time "free" licence we are restricted to 2000 constraints, but solving 10 del 1 is well outside the 60 second time-limit anyway on my laptop.
```
from gurobipy import *
from itertools import combinations
def mincover(n,d):
bs = pow(2,n-1-d)
m = Model()
m.Params.outputFlag = 0
b = {}
for i in range(bs):
b[i] = m.addVar(vtype=GRB.BINARY, name="b%d" % i)
m.update()
for row in range(pow(2,n-1)):
x = {}
for i in combinations(range(n), n-d):
v = 0
for j in range(n-d):
if row & pow(2,i[j]):
v += pow(2,j)
if v >= bs:
v = 2*bs-1-v
x[v] = 1
m.addConstr(quicksum(b[i] for i in x.keys()) >= 1)
m.setObjective(quicksum(b[i] for i in range(bs) ), GRB.MINIMIZE)
m.optimize()
return int(round(2*m.objVal,0))
for n in range(4,10):
for d in range((n//2)+1):
print n, d, mincover(n,d)
```
UPDATE+CORR: 10,2 has optimal solution size 31 (see e.g.) Gurobi shows no symmetric solution of size 30 exists (returns problem infeasible) .. [my attempt to show asymmetric feasibility at 30 remained inconclusive after 9.5hrs runtime]
e.g. bit patterns of integers `0 7 13 14 25 28 35 36 49 56 63 64 95 106 118 128 147 159 170 182 195 196 200 207 225 231 240 243 249 252 255` or `0 7 13 14 19 25 28 35 36 49 56 63 64 95 106 118 128 159 170 182 195 196 200 207 225 231 240 243 249 252 255`
[Answer]
# C++, n=6
Brute force with some small optimizations.
```
#include<cassert>
#include<iostream>
#include<vector>
// ===========
/** Helper struct to print binary representation.
`std::cout<<bin(str,len)` prints (str:len) == the bitstring
represented by last (len) bits of (str).
*/
struct bin{
int str,len;
bin(int str,int len):str(str),len(len){}
};
std::ostream& operator<<(std::ostream& str,bin a){
if(a.len)
return str<<bin(a.str>>1,a.len-1)<<char('0'+(a.str&1));
else if(a.str)
return str<<"...";
else
return str;
}
// ===========
/// A patten of (len) bits of ones.
int constexpr pat1(int len){
return (1<<len)-1;
}
// TODO benchmark: make (res) global variable?
/**Append all distinct (subseqs+(sfx:sfxlen)) of (str:len)
with length (sublen) to (res).
*/
void subseqs_(
int str,int len,int sublen,
int sfx,int sfxlen,
std::vector<int>& res
){
// std::cout<<"subseqs_ : str = "<<bin(str,len)<<", "
// "sublen = "<<sublen<<", sfx = "<<bin(sfx,sfxlen)<<'\n';
assert(len>=0);
if(sublen==0){ // todo remove some branches can improve perf?
res.push_back(sfx);
return;
}else if(sublen==len){
res.push_back(str<<sfxlen|sfx);
return;
}else if(sublen>len){
return;
}
if(str==0){
res.push_back(sfx);
return;
}
int nTrail0=0;
for(int ncut;str&&nTrail0<sublen;
++nTrail0,
ncut=__builtin_ctz(~str)+1, // cut away a bit'0' of str
// plus some '1' bits
str>>=ncut,
len-=ncut
){
ncut=__builtin_ctz(str)+1; // cut away a bit'1' of str
subseqs_(str>>ncut,len-ncut,sublen-nTrail0-1,
sfx|1<<(sfxlen+nTrail0),sfxlen+nTrail0+1,
res
); // (sublen+sfxlen) is const. TODO global var?
}
if(nTrail0+len>=sublen) // this cannot happen if len<0
res.push_back(sfx);
}
std::vector<int> subseqs(int str,int len,int sublen){
assert(sublen<=len);
std::vector<int> res;
if(__builtin_popcount(str)*2>len){ // too many '1's, flip [todo benchmark]
subseqs_(pat1(len)^str,len,sublen,0,0,res);
int const p1sublen=pat1(sublen);
for(int& r:res)r^=p1sublen;
}else{
subseqs_(str,len,sublen,0,0,res);
}
return res;
}
// ==========
/** Append all distinct (supersequences+(sfx:sfxlen)) of (str:len)
with length (suplen) to (res).
Define (a) to be a "supersequence" of (b) iff (b) is a subsequence of (a).
*/
void supseqs_(
int str,int len,int suplen,
int sfx,int sfxlen,
std::vector<int>& res
){
assert(suplen>=len);
if(suplen==0){
res.push_back(sfx);
return;
}else if(suplen==len){
res.push_back(str<<sfxlen|sfx);
return;
}
int nTrail0; // of (str)
if(str==0){
res.push_back(sfx);
// it's possible that the supersequence is '0000..00'
nTrail0=len;
}else{
// str != 0 -> str contains a '1' bit ->
// supersequence cannot be '0000..00'
nTrail0=__builtin_ctz(str);
}
// todo try `nTrail0=__builtin_ctz(str|1<<len)`, eliminates a branch
// and conditional statement
for(int nsupTrail0=0;nsupTrail0<nTrail0;++nsupTrail0){
// (nsupTrail0+1) last bits of supersequence matches with
// nsupTrail0 last bits of str.
supseqs_(str>>nsupTrail0,len-nsupTrail0,suplen-1-nsupTrail0,
sfx|1<<(nsupTrail0+sfxlen),sfxlen+nsupTrail0+1,
res);
}
int const strMatch=str?nTrail0+1:len;
// either '1000..00' or (in case str is '0000..00') the whole (str)
for(int nsupTrail0=suplen+strMatch-len;nsupTrail0-->nTrail0;){
// because (len-strMatch)<=(suplen-1-nsupTrail0),
// (nsupTrail0<suplen+strMatch-len).
// (nsupTrail0+1) last bits of supersequence matches with
// (strMatch) last bits of str.
supseqs_(str>>strMatch,len-strMatch,suplen-1-nsupTrail0,
sfx|1<<(nsupTrail0+sfxlen),sfxlen+nsupTrail0+1,
res);
}
// todo try pulling constants out of loops
}
// ==========
int n,b;
std::vector<char> done;
unsigned min_undone=0;
int result;
void backtrack(int nchoice){
assert(!done[min_undone]);
++nchoice;
std::vector<int> supers_s;
for(int s:subseqs(min_undone,n,n-b)){
// obviously (s) is not chosen. Try choosing (s)
supers_s.clear();
supseqs_(s,n-b,n,0,0,supers_s);
for(unsigned i=0;i<supers_s.size();){
int& x=supers_s[i];
if(!done[x]){
done[x]=true;
++i;
}else{
x=supers_s.back();
supers_s.pop_back();
}
}
unsigned old_min_undone=min_undone;
while(true){
if(min_undone==done.size()){
// found !!!!
result=std::min(result,nchoice);
goto label1;
}
if(not done[min_undone])
break;
++min_undone;
}
if(nchoice==result){
// backtrack more will only give worse result
goto label1;
}
// note that nchoice is already incremented
backtrack(nchoice);
label1: // undoes the effect of (above)
for(int x:supers_s)
done[x]=false;
min_undone=old_min_undone;
}
}
int main(){
std::cin>>n>>b;
done.resize(1<<n,0);
result=1<<(n-b); // the actual result must be less than that
backtrack(0);
std::cout<<result<<'\n';
}
```
Run locally:
```
[user202729@archlinux golf]$ g++ -std=c++17 -O2 delbits.cpp -o delbits
[user202729@archlinux golf]$ time for i in $(seq 1 3); do ./delbits <<< "6 $i"; done
12
4
2
real 0m0.567s
user 0m0.562s
sys 0m0.003s
[user202729@archlinux golf]$ time ./delbits <<< '7 1'
^C
real 4m7.928s
user 4m7.388s
sys 0m0.173s
[user202729@archlinux golf]$ time for i in $(seq 2 3); do ./delbits <<< "7 $i"; done
6
2
real 0m0.040s
user 0m0.031s
sys 0m0.009s
```
[Answer]
# MATLAB, n=9
Mixed-integer linear programming (MILP)
Use the `intlinprog` function of the optim package
```
% mincover.m
function result = mincover(n, d)
bs = 2^(n - 1 - d);
% define problem
f = ones(bs, 1);
intcon = 1:bs;
lb = zeros(bs, 1);
ub = ones(bs, 1);
A = [];
b = [];
for row = 0:(2^(n-1) - 1)
x = zeros(bs, 1);
combs = nchoosek(1:n, n-d);
for i = 1:size(combs, 1)
v = 0;
for j = 1:(n-d)
if bitand(row, 2^(combs(i, j) - 1))
v = v + 2^(j - 1);
end
end
if v >= bs
v = 2*bs - 1 - v;
end
x(v + 1) = 1;
end
A = [A; x'];
b = [b; 1];
end
options = optimoptions('intlinprog','Display','off');
[x, fval] = intlinprog(f, intcon, -A, -b, [], [], lb, ub, options);
result = round(2 * fval);
end
```
```
% run_mincover.m
for n = 3:9
for d = 0:floor(n/2)
fprintf('n=%d, d=%d, mincover=%d\n', n, d, mincover(n, d))
end
end
```
```
n=3, d=0, mincover=8
n=3, d=1, mincover=2
n=4, d=0, mincover=16
n=4, d=1, mincover=4
n=4, d=2, mincover=2
n=5, d=0, mincover=32
n=5, d=1, mincover=6
n=5, d=2, mincover=2
n=6, d=0, mincover=64
n=6, d=1, mincover=12
n=6, d=2, mincover=4
n=6, d=3, mincover=2
n=7, d=0, mincover=128
n=7, d=1, mincover=20
n=7, d=2, mincover=6
n=7, d=3, mincover=2
n=8, d=0, mincover=256
n=8, d=1, mincover=40
n=8, d=2, mincover=10
n=8, d=3, mincover=4
n=8, d=4, mincover=2
n=9, d=0, mincover=512
n=9, d=1, mincover=70
n=9, d=2, mincover=18
n=9, d=3, mincover=6
n=9, d=4, mincover=2
```
] |
[Question]
[
[Ohm's law](https://en.wikipedia.org/wiki/Ohm%27s_law) tells us that the current (I) in amps flowing through a resistance (R) in Ohms when a voltage (V) is applied across it is given as follows:
```
V = I / R
```
Similarly the [power (P) in watts](https://en.wikipedia.org/wiki/Watt#Examples) dissipated by that resistance is given by:
```
P = V * I
```
By rearrangement and substitution, formulae may be derived for calculating two of these quantities when any of the other two is given. These formulae are summarised as follows (note this image uses `E` instead of `V` for volts):
[](https://i.stack.imgur.com/1MEBo.png "Absolute Power Corrupts Absolutely! Resistance is Futile!")
Given an input of any two of these quantities in a string, output the other two.
* Input numbers will be decimals in whatever format is appropriate for your language. Precision should be to at least 3 decimal places. ([IEEE 754-2008 binary32 floats](https://en.wikipedia.org/wiki/Single-precision_floating-point_format) are sufficient.)
* Each input number will be suffixed with a unit. This will be one of `V A W R` for Voltage, Amperage, Power and Resistance (or the equivalent lowercase). Additionally, you may use `Ω` instead of `R`. The units will not have any decimal prefixes (Kilo-, milli-, etc).
* The two input quantities will be given in any order in one string, separated by a single space.
* Input quantities will always be real numbers greater than 0.
* Output will be in the same format as input.
* Equation-solving builtins are disallowed.
### Example Inputs
```
1W 1A
12V 120R
10A 10V
8R 1800W
230V 13A
1.1W 2.333V
```
### Corresponding Outputs
```
1V 1R
0.1A 1.2W
1R 100W
120V 15A
2990W 17.692R
0.471A 4.948R
```
It should be noted that solutions to this challenge will effectively be self-inverses. In other words if you apply a solution to input `A B` and get output `C D`, then apply a solution to input `C D`, then the output should be `A B` again, though possibly out of order and perturbed due to FP rounding. So test inputs and outputs may be used interchangeably.
[Answer]
# Ruby 171 bytes
Input as function argument. Output to stdout with trailing space (can be revised if necessary.)
```
->s{a,b,c,d=s.split.map{|z|[z[-1],z.to_f]}.sort.flatten
%w{EA9.EAAVAA.WVA GS;.A?#WWV.RRR}.map{|w|m=w[n=(a+c+?!).sum%10].ord;print (b**(m%9-4)*d**(m/9-5))**0.5,w[n+7],' '}}
```
**Explanation**
All formulas can be expressed in the form `b**x*d**y` where b & d are the two input values and x & y are powers. For golfing reasons the expression `(b**x*d**y)**0.5` was finally preferred as it means x and y become integers in the range -4 to 4.
The following table shows the required expressions (inputs are assumed sorted alphabetically) and the encoded values for the powers. Where x and y are the doubled powers, they are encoded as `(x+4)+(y+4)*9+9` or equivalently `(x+4)+(y+5)*9`. This puts all encodings in the printable ASCII range. Power operators are omitted from the formulas for brevity.
`n` is a kind of checksum made from the input unit symbols; it can take the values 0,1,2,4,5,6 (3 is not used.)
```
n formula 1 formula 2 formula 1 formula 2
value powers x+4 y+4 encoding powers x+4 y+4 encoding
0 A*R=V A2*R=W 1 1 6 6 69 E 2 1 8 6 71 G
1 R-1*V=A R-1*V2=W -1 1 2 6 65 A -1 2 2 8 83 S
2 R-.5*W.5=A R.5*W.5=V -.5 .5 3 5 57 9 .5 .5 5 5 59 ;
3 . . . .
4 A*V=W A-1*V=R 1 1 6 6 69 E -1 1 2 6 65 A
5 A-1*W=V A-2*W=R -1 1 2 6 65 A -2 1 0 6 63 ?
6 V-1*W=A V2*W-1=R -1 1 2 6 65 A 2 -1 8 2 35 #
```
**Ungolfed in test program**
```
f=->s{
a,b,c,d=s.split.map{|z|[z[-1],z.to_f]}. #split the input into an array [[symbol1,value1],[symbol2,value2]]
sort.flatten #sort alphabetically by symbol and flatten to assign the 4 objects to different variables
n=(a+c+?!).sum%10 #sum the ascii codes of the symbols (plus that of ! for good value distribution) and take mod 10. gives a number 0..6 (3 is not used)
%w{EA9.EAAVAA.WVA GS;.A?#WWV.RRR}. #for each of the outputs, there is a 14 character string. 1st 7 characters encode powers, 2nd 7 characters are output symbol
map{|w| #iterate through the 2 outputs
m=w[n].ord #select one character according to value of n and convert to a number encoding the powers to raise the two inputs to
print (b**(m%9-4)*d**(m/9-5))**0.5,w[n+7],' '#decode the powers, evaluate the expression and output, append the unit symbol and a space
}
}
f["6W 3A"]
puts
f["12V 120R"]
puts
f["10A 10V"]
puts
f["8R 1800W"]
puts
f["6W 2V"]
puts
f["2A 3R"]
puts
```
**Output**
```
2.0V 0.6666666666666666R
0.1A 1.2W
100.0W 1.0R
15.0A 120.0V
3.0A 0.6666666666666666R
6.0V 12.0W
```
[Answer]
# Python 3, ~~193~~ ~~187~~ 190 bytes
```
import re
exec(re.sub('(.+?) (.)',r'\2=\1;',input()))
for s,r in zip('AVRW'*3,'V/R (W*R)**.5 V/A V*V/R W/V W/A V*V/W R*A*A (W/R)**.5 A*R W/A**2 V*A'.split()):
try:print(eval(r),s)
except:0
```
[**Try it online**](https://tio.run/##LY/PasQgEMbvPsWQi38qRiOFJSEUX8GDXvbSbl1WSBMxbrvbl08N6WE@mG9@8w2TnuW2zHr7ucUpgOrDI1xIbppmi19pyQVyQIcXxHr/IJiIlzcKRFDMMz5341kNmMc53QuhlKLrkmHlGeIMvzERbJz1mGmOXWuBeGYpY@IVXGvAsd3zrat1dB4sM8xUrv3nDNsJw1hXAYPFmqa4H@oRlPzsU45zIeH7fSKZ8pUiCI9LSKWXW32BDsecDmZ0ox39KIfPMIHhjlvuNwUeFBikajioToJFSoKBKg6dwII6SQkedVrugN5RsS91QmsN7g8)
Converts the input of the form `<value> <unit> <value> <unit>` into assignment statements. Then, use `eval` on every formula, with the `try/except` ignoring the errors from the ones for which the variables haven't been assigned.
Edit (190): Idk how the bug stayed in the program for 3 years, but I fixed the program giving some wrong answers. It was previously doing sqrt before dividing. The TIO program now runs all test cases at once.
[Answer]
# Python 3, ~~329~~ ~~347~~ ~~343~~ ~~339~~ ~~326~~ ~~305~~ ~~267~~ ~~251~~ ~~249~~ ~~245~~ 237 bytes
This is pretty bloated. There is definitely still a lot of golfing to do.
**Edit:** ~~Temporarily fixed the output. For some reason, `return' '.join(str(eval(z[m][i]))+t[i]for i in range(2))` refuses to work properly.~~
**Edit:** Dropped `eval`.
This function now borrows parts of [Level River St's answer](https://codegolf.stackexchange.com/a/75181/47581). I changed the `ops` dictionary, first into a dictionary of modified exponents `exponent*2+4` for `b**((p-4)/2) * d**((q-4)/2)`, so that each `p` and `q` would be a one digit number. For example, `b*d == b**1*d**1 == b**((6-4)/2)*d**((6-4)/2)`, and the result would be `66` in the dictionary.
Then, I turned the dictionary into a string `z` with those modified exponents and the units that are needed in a line and in a particular order. First, the ASCII value of each character in `ARVW` mod 10 is `5, 2, 6, 7`. When any two of these values are added, they give a unique number mod 10. Thus, each two-character combination can be given a unique number with `(ord(x[0]) + ord(y[10] + 3) % 10`, giving `AR: 0, AV: 4, AW: 5, RV: 1, RW: 2, VW: 6` (very similar to Lever River St's checksum). Arranging the modified exponents to be in this order, i.e. `[AR] [RV] [RW] [blank] [AV] [AW] [VW]`, allows `z` to be accessed efficiently (in terms of bytes).
**Edit:** Golfed the list comprehension under `return`. Golfed the definition of `m`.
## Code:
```
def e(s):x,y=sorted((i[-1],float(i[:-1]))for i in s.split());m=(ord(x[0])+ord(y[0])+3)%10*6;z="6686VW2628AW3555AV0000002666RW0626RV2682AR";return' '.join(str((x[1]**(int(z[m+i*2])-4)*y[1]**(int(z[m+i*2+1])-4))**.5)+z[m+i+4]for i in(0,1))
```
**Ungolfed:**
```
def electric(s):
x, y = sorted((i[-1],float(i[:-1]))for i in s.split())
m = (ord(x[0]) + ord(y[0]) + 3) % 10 * 6
z = "6686VW2628AW3555AV0000002666RW0626RV2682AR"
h = []
for i in range(2):
f = (x[1] ** (int(z[m*6+i*2])-4) * y[1] ** (int(z[m*6+i*2+1])-4)) ** 0.5
h.append(str(f)+z[m*6+i+4])
return ' '.join(h)
```
] |
[Question]
[
OCTOBER 22 IS [INTERNATIONAL CAPS LOCK DAY](http://capslockday.com)! UNFORTUNATELY, SOME DO NOT RECOGNIZE THE GLORY OF THE ALMIGHTY CAPS LOCK. THEY SAY IT SEEMS "OBNOXIOUS" OR "LIKE SHOUTING" OR SOME NONSENSE. IN ORDER TO CONFORM TO THESE OBVIOUSLY ILLOGICAL AND INANE COMPLAINTS, PLEASE WRITE ME A PROGRAM THAT TURNS NORMAL TEXT INTO "SENSIBLE" OR "REASONABLE" TEXT TO MAKE PEOPLE STOP COMPLAINING.
## Description
The input and output for your solution will both be strings that contain only printable ASCII characters.
The input string will contain zero or more *caps lock runs*. A *caps lock run* (or CLR for short) is defined as the following:
* The CLR must contain no lowercase letters (`a-z`), *except* as the first character of a *word*.
+ A *word*, for the purposes of this challenge, is a sequence of non-spaces. So, `PPCG`, `correcthorsebatterystaple`, and `jkl#@_>00()@#__f-023\f[` are all considered *word*s.
* The CLR must also contain at least one space; hence, it must be at least two *word*s.
* Each of the *word*s in the CLR must contain at least two letters (`A-Za-z`).
+ Note that this refers to the CLR taken by itself, without any surrounding characters that may not have been included in the CLR. For example, `fo**O B**ar` is *not* a CLR because the string `O B` by itself has *word*s with less than two letters.
CLRs should be parsed "greedily"—that is, you should always find the longest CLRs possible.
Once you have identified all of the CLRs in the input string, swap the case of all letters inside of the CLRs and output the resulting string.
## Test cases
The first line is input, and the second is output. Bolded portions of the input are substrings that are considered CLRs.
```
**CAPS LOCK IS THE BEST!**
caps lock is the best!
```
```
I really **LOVE pROGRAMMING pUZZLES AND cO**de Golf!
I really love Programming Puzzles and Code Golf!
```
```
This is a challenge on PPCG. This is a test **CASE. TEST**
This is a challenge on PPCG. This is a test case. test
```
```
Lor**EM iPSUM DOL**oR sIT amet, conSECTETur ADIPISci**NG eLIT. MAECENAS iD** orci
Lorem Ipsum doloR sIT amet, conSECTETur ADIPIScing Elit. maecenas Id orci
```
```
**;'>}{/[]'"A\*(389971(\*(#$&B#@\*(% c'>#{@D#$!** :,>/;[e.[{$893F
;'>}{/[]'"a*(389971(*(#$&b#@*(% C'>#{@d#$! :,>/;[e.[{$893F
```
```
**iT'S cAPS lOCK DAY!!! cEL**ebra**TE TH**is WONDERFUL key
It's Caps Lock day!!! Celebrate this WONDERFUL key
```
```
aBc**DE fGHI**j KLm**NO pQ**rST (uVw**XY) ZZ\_\_\_Z**z__Z
aBcde Fghij KLmno PqrST (uVwxy) zz___zz__Z
```
```
#aA# aA
#aA# aA
```
## Rules
* You may assume that the input will never contain two or more spaces in a row, and that it will never contain a leading or trailing space.
* 20% bonus (multiply your code length by .8) if your entire code is a CLR. ;) (mostly just for fun, since it's unlikely that the winning submission will have this bonus)
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
[Answer]
# CJam, ~~100~~ ~~86~~ ~~83~~ 81 bytes
```
Ml{_,),{1$<_S/(4$!>\1f>s+_eu=*S%_{'[,_el^:Af&s,2<},!*1>},_{W=/(AA26m>er}{;(}?\s}h
```
Try [this fiddle](http://cjam.aditsu.net/#code=Ml%7B_%2C)%2C%7B1%24%3C_S%2F(4%24!%3E%5C1f%3Es%2B_eu%3D*S%25_%7B'%5B%2C_el%5E%3AAf%26s%2C2%3C%7D%2C!*1%3E%7D%2C_%7BW%3D%2F(AA26m%3Eer%7D%7B%3B(%7D%3F%5Cs%7Dh&input=I%20really%20LOVE%20pROGRAMMING%20pUZZLES%20AND%20cOde%20Golf!) in the CJam interpreter or [verify all test cases at once](http://cjam.aditsu.net/#code=qN%2F%7B%0A%20%20ML%7B_%2C)%2C%7B1%24%3C_S%2F(4%24!%3E%5C1f%3Es%2B_eu%3D*S%25_%7B'%5B%2C_el%5E%3AAf%26s%2C2%3C%7D%2C!*1%3E%7D%2C_%7BW%3D%2F(AA26m%3Eer%7D%7B%3B(%7D%3F%5Cs%7Dh%0AN%5Do%7DfL&input=CAPS%20LOCK%20IS%20THE%20BEST!%0AI%20really%20LOVE%20pROGRAMMING%20pUZZLES%20AND%20cOde%20Golf!%0AThis%20is%20a%20challenge%20on%20PPCG.%20This%20is%20a%20test%20CASE.%20TEST%0ALorEM%20iPSUM%20DOLoR%20sIT%20amet%2C%20conSECTETur%20ADIPISciNG%20eLIT.%20MAECENAS%20iD%20orci%0A%3B'%3E%7D%7B%2F%5B%5D'%22A*(389971(*(%23%24%26B%23%40*(%25%20c'%3E%23%7B%40D%23%24!%20%3A%2C%3E%2F%3B%5Be.%5B%7B%24893F%0AiT'S%20cAPS%20lOCK%20DAY!!!%20cELebraTE%20THis%20WONDERFUL%20key%0AaBcDE%20fGHIj%20KLmNO%20pQrST%20(uVwXY)%20ZZ___Zz__Z%0A%23aA%23%20aA).
### Algorithm
1. Identify the longest possible CLR that starts with the first character.
2. If it exists, swap its case, print it, and remove it from the beginning of the string.
Else, remove a single character from the beginning of the string, and print it unmodified.
3. If there are more characters left, go back to step 1.
### How it works
```
Ml e# Push an empty string and a line from STDIN.
{ e# Do:
_, e# Copy the string on the stack and compute its length (L).
), e# Push [0 ... L].
{ e# Filter; for each integer I in that array:
1$< e# Copy the string and keep its first I characters.
_S/ e# Push a copy and split at spaces.
( e# Shift out the first word.
4$! e# Push the logical NOT of the fifth topmost item of the stack.
e# This pushes 1 for the empty string on the bottom, and 0
e# for non-empty strings and printable characters.
> e# Remove that many characters from the beginning of the first word.
e# This will remove the first character iff the string on the
e# stack is the entire input. This is to account for the fact that
e# the first word is not preceded by a space.
\1f> e# Remove the first character of all remaining words.
s+ e# Concatenate all of them.
_eu= e# Convert a copy to uppercase and check for equality.
* e# Repeat the I characters 1 or 0 times.
S%_ e# Split at runs of spaces, and push a copy.
{ e# Filter; for each non-empty word:
'[, e# Push the string of all ASCII characters up to 'Z'.
_el e# Push a copy and convert to lowercase.
^ e# Perform symmetric difference, pushing all letters (both cases).
:A e# Store the result in A.
f&s e# Intersect A with each character of the word. Cast to string.
s e# This removes all non-letters from the word.
,2< e# Count the letters, and compare the result to 2.
}, e# If there are less than 2 letters, keep the word.
! e# Push the logical NOT of the result.
e# This pushes 1 iff all words contain enough letters.
* e# Repeat the array of words that many times.
1> e# Remove the first word.
}, e# Keep I if there are still words left.
_{ e# If at least one I was kept:
W= e# Select the last (highest) one.
/ e# Split the string on the stack into chunks of that length.
( e# Shift out the first chunk.
AA26m> e# Push "A...Za...z" and "a...zA...Z".
er e# Perform transliteration to swap cases.
}{ e# Else:
; e# Discard the filtered array.
( e# Shift out the first character of the string on the stack.
}? e#
\s e# Swap the shifted out chunk/character with the rest of the string.
}h e# If the remainder of the string is non-empty, repeat.
```
[Answer]
## Perl, 96 82 80 bytes
```
-pe'$y=qr/[^a-z ]{2,}|\b\S[^a-z ]+/;s#$y( $y)+#join$,,map{uc eq$_?lc:uc}$&=~/./g#eg'
```
---
Passes all tests. Assumes input from `STDIN`, prints to `STDOUT`.
How it works:
* setup a regex (`$y`) that matches
+ at least two non-lowercase, non-whitespace characters **OR**
+ a word boundary, followed by a non-whitespace character, followed by one or more non-lowercase, non-whitespace characters
* match multiple instances of space-separated strings that match `$y`, use `s///` to invert case
I'm sure there's room for improvement. If there is a way to get rid of the whole `join-map-split` deal there may still be a chance to qualify for the bonus :)
[Answer]
# Javascript, 193
```
decapslock =
a=>a.replace(/(^[a-z][^a-z ]+|[^a-z ]{2,})( [a-z][^a-z ]+| [^a-z ]{2,})+/g,b=>b.split` `.some(f=>f.split(/[a-z]/i).length<3)?b:b.split``.map(e=>e==(E=e.toUpperCase())?e.toLowerCase():E).join``)
```
```
<!-- Snippet UI -->
<input placeholder='sAMPLE tEXT' oninput="document.getElementsByTagName('p')[0].innerText=decapslock(this.value)" />
<p></p>
```
Explanation:
```
a=>a.replace(/* giant regex */,
b=>
b.split` `.some(
f=>
f.split(/[a-z]/i).length < 3 // check for 2+ letters
)
? b // .some() immediately returns true if it's invalid
: b.split``.map( // otherwise it's valid, so flip case
e=>
e == (E = e.toUpperCase()) // is it uppercase?
? e.toLowerCase() // change it to LC
: E // change it to UC, which was already done for
// the case check
).join``
)
```
```
(
^[a-z][^a-z ]+ // check for a CLR starting at the beginning with LC
|
[^a-z ]{2,} // check for a CLR that begins in the middle of a word or starts at the
// beginning with UC
// in both cases, 2+ letters are required
)
(
[a-z][^a-z ]+ // check for the next word of the CLR, starting with LC
|
[^a-z ]{2,} // check for the next word of the CLR, starting with UC
)+ // check for 1 or more next words
```
] |
[Question]
[
[MarioLANG](http://esolangs.org/wiki/MarioLANG) is a two-dimensional programming language where the source code resembles a Super Mario Bros. level. Furthermore, its instruction set is very similar to [Brainfuck](http://esolangs.org/wiki/Brainfuck)'s. This means that MarioLANG is essentially a 2-D Brainfuck where the instruction pointer moves like Mario. So [when I wrote my MarioLANG submission](https://codegolf.stackexchange.com/a/54928/8478) for the Programming Language Quiz, I started by converting a Brainfuck "Hello, World!" program to MarioLANG. I noticed that this is possible with a very systematic process, so let's write a Brainfuck-to-MarioLANG compiler!
*Note:* The MarioLANG spec isn't entirely unambiguous, so I'm assuming the interpretation of the [Ruby implementation](https://github.com/mynery/mariolang.rb/blob/master/mariolang.rb).
I'll explain the process with the following Brainfuck program:
```
++[>+++++[>+++++++>++++++++++>+++>+<<<<-]<-]>>++.>+.+++++++..+++.>+++.>.
```
It prints `Hello!` and a trailing newline.
1. Convert `<` and `>` to `(` and `)`, respectively:
```
++[)+++++[)+++++++)++++++++++)+++)+((((-](-]))++.)+.+++++++..+++.)+++.).
```
2. Add a floor for Mario to walk on:
```
++[)+++++[)+++++++)++++++++++)+++)+((((-](-]))++.)+.+++++++..+++.)+++.).
========================================================================
```
3. Now the issue is that MarioLANG doesn't have loops like `[` and `]`. Instead, we have to use elevators and directional instructions to make Mario actually walk in a loop. First, we replace `[` with `>` and change the floor to `"`. And we also replace `]` with `[!` and change the floor to `=#`:
```
++>)+++++>)+++++++)++++++++++)+++)+((((-[!(-[!))++.)+.+++++++..+++.)+++.).
=="======"===============================#===#============================
```
4. The `"` and `#` can form elevators (starting from `#`, ending at `"`), so now all we need are auxiliary floors for Mario to walk back on. The start with `!` and end with `<`:
```
++>)+++++>)+++++++)++++++++++)+++)+((((-[!(-[!))++.)+.+++++++..+++.)+++.).
=="======"===============================#===#============================
! <
#==============================="
! <
#=========================================="
```
Note that all lines must be at least as long as the largest enclosing loop, because the interpreter isn't able to connect elevator ends across shorter lines. Therefore, we pad the middle lines with spaces.
And that's it. We've got a fully functional, equivalent MarioLANG program.
## The Challenge
Given a valid Brainfuck program, implement the above procedure to compile it into a MarioLANG program.
You may assume that there are only command characters in the input, i.e. no characters except `,.+-<>[]`.
All auxiliary floor must be as close as possible to the main program floor. You may choose to pad the lines of intermediate floors either as little as possible (up to the width of the largest enclosing loop) or to the end of the main program.
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. If you don't print the result to STDOUT, it should still be a single newline-separated string.
This is code golf, so the shortest answer (in bytes) wins.
## Test Cases
The test cases are formatted as follows: the first line is the Brainfuck program (your input), then there's an empty line, and everything until the next empty line is the expected output in MarioLANG. These examples use the minimal amount of padded spaces. Alternatively, you may pad each line with spaces to the width of the first line of the output.
```
>,++-.<
),++-.(
=======
,[.,]
,>.,[!
="===#
! <
#==="
>>[-]<<[->>+<<]
))>-[!((>-))+(([!
=="==#=="=======#
! < ! <
#==" #======="
++[>+++++[>+++++++>++++++++++>+++>+<<<<-]<-]>>++.>+.+++++++..+++.>+++.>.
++>)+++++>)+++++++)++++++++++)+++)+((((-[!(-[!))++.)+.+++++++..+++.)+++.).
=="======"===============================#===#============================
! <
#==============================="
! <
#=========================================="
[][[[][[]]][]][[]]
>[!>>>[!>>[![![!>[![!>>[![!
"=#"""=#""=#=#=#"=#=#""=#=#
! < ! < ! < ! < ! <
#=" #=" #=" #=" #="
! < ! <
#====" #===="
! <
#=========="
! <
#================"
>>+++++++>>++>>++++>>+++++++>>+>>++++>>+>>+++>>+>>+++++>>+>>++>>+>>++++++>>++>>++++>>+++++++>>+>>+++++>>++>>+>>+>>++++>>+++++++>>+>>+++++>>+>>+>>+>>++++>>+++++++>>+>>+++++>>++++++++++++++>>+>>+>>++++>>+++++++>>+>>+++++>>++>>+>>+>>++++>>+++++++>>+>>+++++>>+++++++++++++++++++++++++++++>>+>>+>>++++>>+++++++>>+>>+++++>>++>>+>>+>>+++++>>+>>++++++>>+>>++>>+>>++++++>>+>>++>>+>>++++++>>+>>++>>+>>++++++>>+>>++>>+>>++++++>>+>>++>>+>>++++++>>+>>++>>+>>++++++>>++>>++++>>+++++++>>+>>+++++>>+++++++>>+>>+++++>>+>>+>>+>>++++>>+>>++>>+>>++++++>>+>>+++++>>+++++++>>+>>++++>>+>>+>>++>>+++++>>+>>+++>>+>>++++>>+>>++>>+>>++++++>>+>>+++++>>+++++++++++++++++++>>++>>++>>+++>>++>>+>>++>>++++>>+++++++>>++>>+++++>>++++++++++>>+>>++>>++++>>+>>++>>+>>++++++>>++++++>>+>>+>>+++++>>+>>++++++>>++>>+++++>>+++++++>>++>>++++>>+>>++++++[<<]>>[>++++++[-<<++++++++++>>]<<++..------------------->[-<.>>+<]>[-<+>]>]<<[-[-[-[-[-[-[>++>]<+++++++++++++++++++++++++++++>]<++>]<++++++++++++++>]<+>]<++>]<<[->.<]<<]
))+++++++))++))++++))+++++++))+))++++))+))+++))+))+++++))+))++))+))++++++))++))++++))+++++++))+))+++++))++))+))+))++++))+++++++))+))+++++))+))+))+))++++))+++++++))+))+++++))++++++++++++++))+))+))++++))+++++++))+))+++++))++))+))+))++++))+++++++))+))+++++))+++++++++++++++++++++++++++++))+))+))++++))+++++++))+))+++++))++))+))+))+++++))+))++++++))+))++))+))++++++))+))++))+))++++++))+))++))+))++++++))+))++))+))++++++))+))++))+))++++++))+))++))+))++++++))++))++++))+++++++))+))+++++))+++++++))+))+++++))+))+))+))++++))+))++))+))++++++))+))+++++))+++++++))+))++++))+))+))++))+++++))+))+++))+))++++))+))++))+))++++++))+))+++++))+++++++++++++++++++))++))++))+++))++))+))++))++++))+++++++))++))+++++))++++++++++))+))++))++++))+))++))+))++++++))++++++))+))+))+++++))+))++++++))++))+++++))+++++++))++))++++))+))++++++>(([!))>)++++++>-((++++++++++))[!((++..-------------------)>-(.))+([!)>-(+)[!)[!((>->->->->->->)++)[!(+++++++++++++++++++++++++++++)[!(++)[!(++++++++++++++)[!(+)[!(++)[!((>-).([!(([!
========================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================="===#=="======="================#=========================="========#="=====#==#=="="="="="="="=====#================================#=====#=================#====#=====#=="=====#===#
! < ! < ! < ! < ! < ! <
#===" #================" #========" #=====" #=====" #====="
! < ! <
#=======================================================================" #========================================"
! <
#================================================"
! <
#===================================================================="
! <
#==========================================================================="
! <
#==================================================================================="
! <
#=================================================================================================="
```
[Answer]
# CJam, ~~148~~ 144 bytes
```
q"<>[""()>"er']/"[!"*_">!"1$|"\"#=":Cer:FF,[{SF,*L{'=t}/FI>(C#"['=-{_'##}{_CW</s}w],2*(:M'#tM('!tLM+ ;LW=34ctLW=('<tLW< ;L"S/=~:L;}fI]z~]{S-},N*
```
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q%22%3C%3E%5B%22%22()%3E%22er'%5D%2F%22%5B!%22*_%22%3E!%221%24%7C%22%5C%22%23%3D%22%3ACer%3AFF%2C%5B%7BSF%2C*L%7B'%3Dt%7D%2FFI%3E(C%23%22%5B'%3D-%7B_'%23%23%7D%7B_CW%3C%2Fs%7Dw%5D%2C2*(%3AM'%23tM('!tLM%2B%20%3BLW%3D34ctLW%3D('%3CtLW%3C%20%3BL%22S%2F%3D~%3AL%3B%7DfI%5Dz~%5D%7BS-%7D%2CN*&input=%5B%5D%5B%5B%5B%5D%5B%5B%5D%5D%5D%5B%5D%5D%5B%5B%5D%5D).
[Answer]
# Python, 707 chars
```
def b(c):
c,l,o,x,j,m=list(c.replace(">",")").replace("<","(")),[list("="*len(c))],[],[],0,0
for i,z in enumerate(c):
i+=j
if"["==z:
c[i],l[0][i]=">",'"'
x.append(i)
if"]"==z:
c[i],l[0][i]="[!","=#"
c,l[0],m,d,b=list("".join(c)),list("".join(l[0])),max(m,len(x)),0,x.pop()
for a in o:d+=b<a[0]and-~i>a[0]or b<a[1]and-~i>a[1]
o.append((b,i+1,d))
j+=1
for q in o:
d=q[2]*2+1
while len(l)<=d+1:l.append(list(" "*len(c)))
l[d][q[0]],l[d+1][q[0]],l[d][q[1]],l[d+1][q[1]]="!","#","<",'"'
for i in range(q[0]+1,q[1]):l[d+1][i]="="
g="\n".join(l.rstrip()for l in("".join(c)+"\n"+"\n".join("".join(f)for f in l)).split("\n"))
while"\n\n"in g:g=g.replace("\n\n","\n")
return g
```
There's probably a lot of space to be golfed. Doesn't work for the last test case.
Example usage:
```
>>> print b("++[>+++<-]>[<+++>-]<.")
=="=======#="=======#==
! < ! <
#=======" #======="
```
No lines in the output contains trailing spaces.
] |
[Question]
[
Lets say you saw your friend enter his or her password into their Android phone. You don't remember how they made the pattern but you remember what the pattern looks like. Being the concerned friend that you are you want to know how secure their password is. Your job is to calculate all the ways that a particular pattern can be made.
## How Android patterns work
Patterns are drawn on a 3x3 grid of nodes. In a pattern one visits a series of nodes without ever lifting their finger from the screen. Each node they visit is connected to the previous node by a edge. There are two rules to keep in mind.
* You may not visit any one node more than once
* An edge may not pass through an unvisited node
Note that, while typically very hard to perform and thus not very common in real android lock combinations, it is possible to move like a [Knight](https://en.wikipedia.org/wiki/Knight_(chess)). That is, it is possible to move from one side to a non-adjacent corner or the other way around. Here are two examples of patterns employing such a move:


Here is a an animated [Gif](https://i.imgur.com/VupUN46.gifv) of it being performed.
## Solving a pattern
A typical pattern might look something like this:

With a simple pattern like this one it there are two ways two draw the pattern. You can start at either of the two loose ends and traveling through the highlighted nodes to the other. While this is true for many patterns particularly ones that human beings typically employ this is not true for all patterns.
Consider the following pattern:

There are two immediately recognizable solutions. One starting in the upper left:

And one starting in the bottom center:

However because a line is permitted to pass through a point once it has already been selected there is an additional pattern starting in the top middle:

This particular pattern has 3 solutions but patterns can have anywhere between 1 and 4 solutions[citation needed].
Here are some examples of each:
### 1.

### 2.

### 3.

### 4.

## I/O
A node can be represented as the integers from zero to nine inclusive, their string equivalents or the characters from a to i (or A to I). Each node must have a unique representation from one of these sets.
A solution will be represented by an ordered container containing node representations. Nodes must be ordered in the same order they are passed through.
A pattern will be represented by an unordered container of pairs of nodes. Each pair represents an edge starting connecting the two points in the pair. Pattern representations are not unique.
You will take a pattern representation as input via standard input methods and output all the possible solutions that create the same pattern via standard output methods.
You can assume each input will have at least one solution and will connect at least 4 nodes.
You may choose to use a ordered container in place of an unordered one, if you so desire or are forced to by language selection.
## Test Cases
With the nodes arranged in the following pattern:
```
0 1 2
3 4 5
6 7 8
```
Let `{...}` be an unordered container, `[...]` be a ordered container, and `(...)` be a pair.
The following inputs and outputs should match
```
{(1,4),(3,5),(5,8)} -> {[1,4,3,5,8]}
{(1,4),(3,4),(5,4),(8,5)} -> {[1,4,3,5,8]}
{(0,4),(4,5),(5,8),(7,8)} -> {[0,4,5,8,7],[7,8,5,4,0]}
{(0,2),(2,4),(4,7)} -> {[0,1,2,4,7],[1,0,2,4,7],[7,4,2,1,0]}
{(0,2),(2,6),(6,8)} -> {[0,1,2,4,6,7,8],[1,0,2,4,6,7,8],[8,7,6,4,2,1,0],[7,8,6,4,2,1,0]}
{(2,3),(3,7),(7,8)} -> {[2,3,7,8],[8,7,3,2]}
{(0,7),(1,2),(1,4),(2,7)} -> {[0,7,2,1,4],[4,1,2,7,0]}
{(0,4),(0,7),(1,3),(2,6),(2,8),(3,4),(5,7)} -> {[1,3,4,0,7,5,8,2,6]}
{(1,3),(5,8)} -> {}
```
An imgur album of all the test cases as pictures can be found [here](https://i.stack.imgur.com/2nI2B.jpg). Patterns are in blue solutions in red.
## Scoring
This is code golf. Fewest bytes wins.
[Answer]
# Python 2.7, ~~493~~ 430 bytes
```
exec("L=['012','345','678','036','147','258','048','246'];L+=[i[::-1]IL];S=sorted;F=lambda t:''.join(str(i)It)\ndef N(x):\n s=' '.join(F(S(i))Ix)\nIL:s=s.replace(i[::2],i[:2]+' '+i[1:])\n return S(set(s.split()))\ndef P(s):\n e=0\nIL:e|=-1<s.find(i[::2])<s.find(i[1])\n return[zip(s[:-1],s[1:]),L][e]\nx=N(input());print[F(i)I__import__('itertools').permutations({iI`x`if i.isdigit()})if x==N(P(F(i)))]".replace('I',' for i in '))
```
The single line version wraps the program with `exec("...".replace('I',' for i in '))` so that all for-loops and generators can be shorted with a single `I` and saves 15 bytes over this more readable version:
```
L=['012','345','678','036','147','258','048','246'];L+=[i[::-1]for i in L]
S=sorted;F=lambda t:''.join(str(i)for i in t)
def N(x):
s=' '.join(F(S(i))for i in x)
for i in L:s=s.replace(i[::2],i[:2]+' '+i[1:])
return S(set(s.split()))
def P(s):
e=0
for i in L:e|=-1<s.find(i[::2])<s.find(i[1])
return[zip(s[:-1],s[1:]),L][e]
x=N(input())
print[F(i)for i in __import__('itertools').permutations({i for i in`x`if i.isdigit()})if x==N(P(F(i)))]
```
The program takes the input in the manner shown (e.g. `{(1,4),(3,4),(5,4),(8,5)}`) or as a list of string (e.g. `['14','34','54','85']`) (or in other python friendly formats) and returns the output as a list of strings. *So we technically have an ordered container of ordered containers.*
The function `N` normalizes a pattern so that two patterns can be easily compared. The normalization sorts the pairs denoting edges (so `'02'` instead of `'20'`), use string replacement to expand double edges (e.g. `'02'` becomes `'01 12'`), splits the edges into a set to remove duplicates, and sorts the result.
The function `F` flattens tuples of ints/strings to strings, so we can normalize paths produced in different ways.
The list `L` contains all lines on screen.
We then take each permutation of all digits in the normalized pattern and compute a valid path or `L` if invalid (which never normalizes to list of pairs like real paths would), or a list of pairs indicating the order nodes are visited if valid. If this normalizes to the same pattern then we have a valid solution and include it in the final list.
The main check needed to validate a permutation as a string `s` is `-1<s.find(i[::2])<s.find(i[1])`, which detects an error with a line `i`. For instance with the line `'210'` the code detects an error if `'20'` occurs (i.e. it's index is greater than -1) and `'1'` occurs after it. *We don't have to worry about 1 not occurring because the 1 will show up in the normalized pattern when it wasn't in the input.*
---
***NOTE:*** I know replacing `str(i)for i in t` *with* `map(str,t)` *and* `{i for i in`x`if i.isdigit()}` *with* `set('012345678')&set(`x`)` *would make the original code shorter, but this would still be slightly longer that substituting* `I`.
] |
[Question]
[
When I was a kid, there was a "really cool" shortcut to count to 100:
`1, 2, miss a few, 99, 100`
Output the exact string above, in the fewest characters possible, without using these characters: `0`, `1`, `2`, `9`
[Answer]
# JavaScript (ES6), 43 bytes
Browser only.
```
_=>atob`MSwgMiwgbWlzcyBhIGZldywgOTksIDEwMA`
```
[Try it online!](https://tio.run/##TcxNC4IwHIDxu5/ijxeVSisiqNBIipCQDgZBETl1W9ZysU3Fvry9nLw9l99zRxWSqchfalDwDLdI8QRckOB64JeEYGETwZ@mhB4YRh@MBEk8nRiWrXikRF5Q01poGnHbq@v9cBxGNQ3zmiZH9k4b/xZsTyxraro/PGSw3tThKm5TXkjOsM04NZ3zcDSeXRxbYalM0vlasAQ9KCrE8gwkL0WKdZiDHv0T9jvd0ron8iXtBw "JavaScript (Node.js) – Try It Online") (with a polyfill)
---
# JavaScript (ES6), 45 bytes
```
_=>[4-3,5-3,'miss a few',33*3,5*5*4].join`, `
```
[Try it online!](https://tio.run/##TYyxDoIwFEV3v@KlC4VAUYEBE3Q2Dg6MhEgDLSnBPtNW/PzaODnc5OQk5y5843Y06uUyjZPwsvGP5tyVWZFWYdFTWQscpPhEaVEkwSZVUvZsQaWHFAY/ora4CrbiTPNufzjWfc6csI5K5rB1RumZxjFcgFz1xlc1gcW3GQWBE5D2h3C/kXj3/yRD4r8 "JavaScript (Node.js) – Try It Online")
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + coreutils, 40
```
tr 3-? /-:<<<"5, 6, miss a few, ==, 544"
```
[Try it online!](https://tio.run/##S0oszvj/v6RIwVjXXkFf18rGxkbJVEfBTEchN7O4WCFRIS21XEfB1lZHwdTEROn/fwA "Bash – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~43~~ 41 bytes
```
cat(T+F:T,"miss a few",3*33+F:T,sep=", ")
```
[Try it online!](https://tio.run/##K/r/PzmxRCNE280qREcpN7O4WCFRIS21XEnHWMvYGCxanFpgq6SjoKT5/z8A "R – Try It Online")
`T` and `F` are equal to `TRUE` and `FALSE`. They get coerced to integers `1` and `0` by the operators `+` and `:`.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~54~~, ~~51~~, ~~47~~ 42 bytes
Saved **2 bytes** thanks to Digial Trauma's suggestion to replace `8*8+35 = 99` with `33*3 = 99`.
Saved **1 byte** by realizing that I could replace `8*8+36 = 100` with `4*5*5 = 100`.
Saved **4 bytes** thanks to dingledooper's suggestion to use `sep=', '` in the `print`!
Saved **5 bytes** thanks to ovs' suggestion to use `bytes` objects.
## New Answer
```
print(*b"","miss a few",*b"cd",sep=", ")
```
```
The b"" is equivalent to b"\1\2".
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EQytJiZFJSUcpN7O4WCFRIS21XEkHKJacoqRTnFpgq6SjoKT5/z8A "Python 3 – Try It Online")
## Old Answer:
```
print(f"{4-3}, {6-4}, miss a few, {33*3}, {4*5*5}")
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EI02p2kTXuFZHodpM1wRI5WYWFyskKqSllgOFjI21wFImWqZaprVKmv//AwA "Python 3 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 23 bytes
```
3Ṗ,³ṭ’¤j“¤mɗʂɠẉ⁾»W¤j⁾,
```
[Try it online!](https://tio.run/##ATYAyf9qZWxsef//M@G5lizCs@G5reKAmcKkauKAnMKkbcmXyoLJoOG6ieKBvsK7V8KkauKBviwg//8 "Jelly – Try It Online")
## How it works
One thing to note: Jelly has the `Ṙ` atom, which prints a string Jelly representation of it's argument. Lists in Jelly do not use `[` and `]` as open/close markers, instead they consist of comma-separated values:
```
1,2,3,4,5Ṙ
```
prints `1,2,3,4,5`, unfortunately, without spaces.
```
3Ṗ,³ṭ’¤j“¤mɗʂɠẉ⁾»W¤j⁾, - Main link. Takes no arguments
3 - Yield 3;
Ṗ - Pop from 3, yielding [1, 2]
¤ - Group the previous links into a nilad:
³ - 100
’ - Decrement; 99
ṭ - Tack; [99, 100]
, - Pair; [[1, 2], [99, 100]]
¤ - Group the previous links into a nilad:
“¤mɗʂɠẉ⁾» - The compressed string "miss a few"
W - Wrap; ["miss a few"]
j - Join; [1, 2, ["miss a few"], 99, 100]
j⁾, - Join with ", "; "1, 2, miss a few, 99, 100"
```
[Answer]
# HTML + CSS, 118 bytes
```
<c>, <c>, miss a few, <d><d><c>, <c><style>c:before{content:counter(a);counter-increment:a}d{counter-increment:a 48}
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 42 bytes
```
$><<[3/3,6/3,'miss a few',33*3,5*5*4]*", "
```
[Try it online!](https://tio.run/##KypNqvz/X8XOxibaWN9YxwyI1XMzi4sVEhXSUsvVdYyNtYx1TLVMtUxitZR0FJT@/wcA "Ruby – Try It Online")
-4 from Jonah. Borrows from Arnauld's answer.
# [Ruby](https://www.ruby-lang.org/), ~~46~~ 44 bytes
```
$><<"cd".bytes.insert(2,"miss a few")*", "
```
[Try it online!](https://tio.run/##KypNqvz/X8XOxkaJkSk5RUkvqbIktVgvM684tahEw0hHKTezuFghUSEttVxJU0tJR0Hp/38A "Ruby – Try It Online")
The three unprintables for codepoints 1, 2 and 3 are in the string containing "cd".
-2 from manatwork. [Other version with same bytecount](https://tio.run/##KypNqvz/v9hWiZGJOTlFSS@psiS1mKs42ijWVik3s7hYIVEhLbVciUvFzsamWEtJR0Hp/38A "Ruby – Try It Online")
[Answer]
# [Whispers v3](https://github.com/cairdcoinheringaahing/Whispers), ~~124..120~~ 114 bytes
```
>> Each 5 57
>> Then 7 3 6 3 4 3 54 3 8
> ", "
> "miss a few"
>> "L"
>> #3
>> #5
>> 53*6
>> #4
>> 8-7
>> Output 56
```
[Try it online!](https://tio.run/##HYwxDoAgFEN3T9HgZnQRPjqxuZm4eAFjMDBojEg8PvIZ@po3tJ/z4bZP6FMyBtO2OxBoqLKszl4YIKFzVA4xxspAtBBcpw8BGw77CR6IuVQtC4lJstHFFHPsyvES3zu@IJ3SDw)
**Explanation:**
I use the fact that each line with the line number \$x\$ can be called with \$x + k \cdot n \$, where \$k \in \mathbb{N} \$ and \$n\$ is total number of lines of code.
Example from code with 11 lines: the reference to line `1` can be replaced by `12`, `23`, `34`, and so on.
[Try the translated version online!](https://tio.run/##K8/ILC5ILSo2@v/fzk7BNTE5Q8FUwYgLyA7JSM1TMFcwVjADYhMgNjQAEhZcdgpKOgpKICo3s7hYIVEhLbVcCaRByQdMKRuDSVMQaallBuaYgEgLXXMQ5V9aUlBaomD4/z8A)
**Line by line:**
As always in Whispers, we run the last line first:
```
>> Output 56
```
This line outputs the result from line 56. Since the code does not have 56 lines it actually outputs line \$ 56 \mod 11 = 1\$:
```
>> Each 5 57
```
Applying the same trick again we can replace this line with:
```
>> Each 5 2
```
In line 5 we can expect a function and in line 2 an array. The function will be applied on each element of the array and it replaces the element with the result. Let us first look at line 5:
```
>> "L"
```
`L` is an argument from the `Each` statement in line 1. `L` is converted to a string.
Now line 2:
```
>> Then 7 3 6 3 4 3 54 3 8
```
`Then` creates an array with the arguments as its elements. If we would print this line we get the following array:
```
[1, ', ', 2, ', ', 'miss a few', ', ', 99, ', ', 100]
```
**Explanation of the arguments:**
Line 3 and 4: simple strings
Line 6: Returns the length of line 3, so we get `2`
Line 7: Returns the length of line 5, so we get a `1`
Line 8: Returns the result of line 53 (actually 9) raised to the power of the result of line 6, so we get `100`
Line 54 (actually 10): Subtracts result of line 8 with the result of line 7, so we get a `99`
[Answer]
# [PHP](https://php.net/), ~~57~~ ~~56~~ 53 bytes
```
printf('%c, %d, miss a few, %d, %o',7*7,5-3,33*3,64);
```
[Try it online!](https://tio.run/##K8go@G9jXwAkC4oy80rSNNRVk3UUVFN0FHIzi4sVEhXSUsshfNV8dR1zLXMdU11jHWNjLWMdMxNN6///AQ "PHP – Try It Online")
A `printf`, some spices, stir
EDIT: -1 byte thanks to Digital Trauma
EDIT 2: -3 bytes thanks to Michael Dorgan for octal, thought about 153 with `%x` for hex but it has a 1..
**Also, less fun but 2 bytes shorter by manatwork, improved by BadHorsie (it seems that `<?=` can also take multiple arguments with comas):**
# [PHP](https://php.net/), ~~51~~ 49 bytes
```
<?=5-4,', ',5-3,', miss a few, ',33*3,', ',5*5*4;
```
[Try it online!](https://tio.run/##K8go@P/fxt7WVNdER11HQV3HVNcYxMjNLC5WSFRISy0HCRobaxlDpbVMtUys//8HAA "PHP – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~54~~ 56 bytes
```
l(){printf("%c, %d, miss a few %d, %o",7*7,5-3,'c',64);}
```
[Try it online!](https://tio.run/##S9ZNT07@r5yZl5xTmpJqU1ySkpmvl2HHlZlXopCjoWkNZuQmZuZpaFaD@ApFqSWlRXkKBta1/4H86oIioII0DSXVZB0F1RQdhdzM4mKFRIW01HIwVzVfScdcy1zHVNdYRz1ZXcfMRBOo8T8A "C (gcc) – Try It Online")
Let's save a couple bytes using Octal for the 100. Thanks to Sheik Yerbouti for saving a byte and point out the no commas issue.
[Answer]
# [R](https://www.r-project.org/), 52 bytes
```
cat(chartr("@-K","/-:","B, C, miss a few, JJ, BAA"))
```
[Try it online!](https://tio.run/##K/r/PzmxRCM5I7GopEhDyUHXW0lHSV/XCkg66Sg46yjkZhYXKyQqpKWW6yh4eekoODk6Kmlq/v8PAA "R – Try It Online")
Encodes numbers as uppercase letters and then applies character range translation. Since we can't directly type `0-9`, we expand the range by 1 character in both directions resulting in `/-:`.
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 146 bytes
```
-[----->+>+>+>++>++<<<<<]>>>--.-----.------------.<-.------.>.>+++++++.>+++.<++++++..<.>>--------.<<.>>+++++.-.<++++.<<.>.<<++++++..>.>.<+++++.-..
```
[Try it online!](https://tio.run/##NYtRCoBgCIMPFO4EsotEDxUEEfQQdH77pzlFnPvcnvW8j3e/Imw2iVOV2qWFpBkyrPkL3h7EoFO5wH8Dh56bl6vACsnTGI1TrglEfA "brainfuck – Try It Online")
A fairly straightforward 255/5=51 loop giving ASCII 51 and ASCII 102 as `333ff` in 5 consecutive cells, followed by hunt and peck strategy.
[Answer]
# [Perl 5](https://www.perl.org/), 42 bytes
```
$,=", ";say!!3,5-3,"miss a few",3*33,4*5*5
```
Sets the record separator, and prints a few numbers and a string.
[Try it online!](https://tio.run/##K0gtyjH9/19Fx1ZJR0HJujixUlHRWMdU11hHKTezuFghUSEttVxJx1jL2FjHRMtUC6j2X35BSWZ@XvF/XV9TPQNDAwA "Perl 5 – Try It Online")
# [Perl 5](https://www.perl.org/), 43 bytes
```
say"C, D, miss a few, KK, CBB"=~y,A-L,/-:,r
```
Translates B-K to 0-9 (extended by one more ASCII code on each side of the range) and prints.
[Try it online!](https://tio.run/##K0gtyjH9/784sVLJWUfBRUchN7O4WCFRIS21XEfB21tHwdnJScm2rlLHUddHR1/XSqfo//9/@QUlmfl5xf91fU31DAwNAA "Perl 5 – Try It Online")
# [Perl 5](https://www.perl.org/), 44 bytes
```
$,=", ";say unpack"c3/acc","
miss a fewcd"
```
Sets the record separator, and unpacks values to be printed.
[Try it online!](https://tio.run/##K0gtyjH9/19Fx1ZJR0HJujixUqE0ryAxOVsp2Vg/MTlZSUeJkYkrN7O4WCFRIS21PDlF6f//f/kFJZn5ecX/dX1N9QwMDQA "Perl 5 – Try It Online")
[Answer]
# [Julia](http://julialang.org/), 41 bytes
```
()->join([b"";"miss a few";b"cd"],", ")
```
[Try it online!](https://tio.run/##yyrNyUw0rPifZvtfQ1PXLis/M08jOkmJkUnJWik3s7hYIVEhLbVcyTpJKTlFKVZHSUdBSfN/QVFmXolGmoam5n8A "Julia 1.0 – Try It Online")
the first string is `"\1\2"` which is allowed if I understand the challenge correctly
`b"str"` converts the string in an array of the value of each character so `b"\1\2" => [1,2]` and `b"cd" => [99,100]`
[Answer]
# [Husk](https://github.com/barbuz/Husk), 31 bytes
```
mȯ←←←"4/#5/#plvv#d#ihz/#<</#433
```
[Try it online!](https://tio.run/##yygtzv7/P/fE@kdtEyBIyURf2VRfuSCnrEw5RTkzo0pf2cZGX9nE2Pj/fwA "Husk – Try It Online")
Explanation:
```
m Map the function...
ȯ←←← Decrement character 3 times
"4/#5/#plvv#d#ihz/#<</#433 desired string "ASCII-shifted" by 3
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 22 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
³ḊĖ.ịṚj“¤mɗʂɠẉ⁾»W¤j⁾,
```
A full program that prints the result.
**[Try it online!](https://tio.run/##ATUAyv9qZWxsef//wrPhuIrEli7hu4vhuZpq4oCcwqRtyZfKgsmg4bqJ4oG@wrtXwqRq4oG@LCD//w "Jelly – Try It Online")**
### How?
```
³ḊĖ.ịṚj“¤mɗʂɠẉ⁾»W¤j⁾, - Link: no arguments
³ - 100
Ḋ - dequeue -> [2,3,...,99,100]
Ė - enumerate -> [[1,2],[2,3],...,[98,99],[99,100]]
. - 0.5
ị - index into -> [[99,100],[1,2]]
Ṛ - reverse
¤ - nilad followed by links as a nilad:
“¤mɗʂɠẉ⁾» - dictionary compression of "miss a few"
W - wrap in a list -> ["miss a few"]
j - join -> [1,2,"miss a few",99,100]
⁾, - ", "
j - join -> [1,", ",2,", ","miss a few",", ",99,", ",100]
- implicit print -> `1, 2, miss a few, 99, 100`
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 16 bytes
I don't think this would be shorter with `0`, `1`, `2` and `9`.
```
XY…š§€…†Óт<т„, ý
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/IvJRw7KjCw8tf9S0Bsh61LDg8OSLTTYXmx41zNNROLz3/38A "05AB1E – Try It Online")
```
X # push 1
Y # push 2
…š§€…†Ó # push compressed dictionary string "miss a few"
т< # push 100-1
т # push 100
„, # push string ", "
ý # join the stack with this string
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 20 19 17 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
saved 2 bytes thanks to Razetime
```
ü←φr5╧wL'•↔♦$▒ò╠‼
```
[Run and debug it](https://staxlang.xyz/#p=811bed7235cf774c27071d0424b195cc13&i=)
Original brain-dead solution for reference purposes only:
# [Stax](https://github.com/tomtheisen/stax), 22 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ü2Φÿßbÿ»f╙m¡6¿₧|░╘;┬u»
```
[Run and debug it](https://staxlang.xyz/#p=8132e898e16298af66d36dad36a89e7cb0d43bc275af&i=)
[Answer]
# C++, 56 bytes
```
[]{for(int x:"4/#5/#plvv#d#ihz/#<</#433"s)putchar(x-3);}
```
Inspired by a [comment](https://codegolf.stackexchange.com/questions/219495/1-2-miss-a-few-99-100#comment511335_219544).
Usage:
```
#include <string>
#include <stdio.h>
using namespace std;
int main() {
auto k = [](){for(int x:"4/#5/#plvv#d#ihz/#<</#433"s)putchar(x-3);};
k();
return 0;
}
```
[Try it online!](http://cpp.sh/3lefr)
[Answer]
# [Barrel](https://www.github.com/LorenDB/barrel), 31 34 bytes
```
+n, +n, 'miss a few, '#44+#45+n, +n
```
This is my own esolang, follow the link for more info.
Increments the accumulator, prints it, implicitly prints some strings (`,` and `miss a few,` are implicitly printed), does a loop on accumulator incrementation, and finishes as it started.
Edit: I realized that "97" used a "9". *smacks forehead*
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 32 bytes
```
B, C, miss a few, JJ, BAA
T`L`d
```
[Try it online!](https://tio.run/##K0otycxL/P@fy0lHwVlHITezuFghUSEttVxHwctLR8HJ0ZErJMEnIeX/fwA "Retina 0.8.2 – Try It Online") Explantion:
```
B, C, miss a few, JJ, BAA
```
Replace the empty input with the literal string.
```
T`L`d
```
Transliterate upper case letters to digits.
[Answer]
# [PowerShell (ASCII answer)](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 128 bytes
```
$k=3-3;((@(46+3),@(53-3),@('miss a few'),@(57,57),@((46+3),48,48))|%{$k++;if($k-eq3){$_}else{($_|%{[char]$_})-join''}})-join', '
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/XyXb1ljX2FpDw0HDxEzbWFPHQcMUKACi1XMzi4sVEhXSUsvVweLmOqbmIAZUpYkFEGlq1qhWq2Rra1tnpmmoZOumFhprVqvE16bmFKdWa6jEA2WjkzMSi2KBYpq6WfmZeerqtTCWjoL6//8A "PowerShell – Try It Online")
# [PowerShell (Base64 one)](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 135 bytes
```
[Text.Encoding]::Unicode.GetString([Convert]::FromBase64string('MQAsACAAMgAsACAAbQBpAHMAcwAgAGEAIABmAGUAdwAsACAAOQA5ACwAIAAxADAAMAA='))
```
[Try it online!](https://tio.run/##JYuxCsIwFEU/p3bppA4Fh5tYo0OQoJ2Kg7aPWmiTkgTTv4@BTPdwDnc1gaz70jzH2D1p81WjezNMenzVdaunxFQJ8g9vk9t13OgfWZ/ixZqFvR0d9y63Qio4cECOeT@KrbhK9AEjRIMb2ALRYgi53xUO4CF5bDinH3AqyjLGPw "PowerShell – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 23 bytes
```
“×ƤṪ5Ġpṃ:Ƒ5ṫȷØJkxXp⁺¥ġ»
```
[Try it online!](https://tio.run/##ATMAzP9qZWxsef//4oCcw5fGpOG5qjXEoHDhuYM6xpE14bmryLfDmEpreFhw4oG6wqXEocK7//8 "Jelly – Try It Online")
Same length as caird's answer, much more boring.
[Answer]
# [Python 2](https://docs.python.org/2/), 59 bytes
```
print ', '.join(map(str,(4-3,5-3,'miss a few',33*3,5*5*4)))
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69EQV1HQV0vKz8zTyM3sUCjuKRIR8NE11jHFIjVczOLixUSFdJSy9V1jI21gKJaplommpqa//8DAA "Python 2 – Try It Online")
Thanks to @arnauld for js answer
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 29 bytes
```
j+\,d[=hZhZ"miss a few"t=*TTT
```
[Try it online!](https://tio.run/##K6gsyfj/P0s7Ricl2jYjKiNKKTezuFghUSEttVypxFYrJCTk/38A "Pyth – Try It Online")
---
Python 3.8 translation:
```
Z=0
T=10
print(", ".join(map(str,[(Z:=Z+1),Z+1,"miss a few",(T:=T*T)-1,T])))
```
[Answer]
# [PHP](https://php.net/), 48 bytes
```
<?=join(', ',[!'',~-3,'miss a few',33*3,45^73]);
```
[Try it online!](https://tio.run/##K8go@P/fxt42Kz8zT0NdR0FdJ1pRXV2nTtdYRz03s7hYIVEhLbVcXcfYWMtYx8Q0ztw4VtP6/38A "PHP – Try It Online")
[Answer]
# Vim, 37 keystrokes
```
i3, 3, miss a few, 8, <esc>|<C-x><C-x>l.l<C-a>ylp$pp<C-a>
```
[Answer]
# PHP, 58 54 bytes
```
<?=join(', ',[$i=3/3,++$i,'miss a few',$i=33*3,++$i]);
```
PHP doesnt really want to be typed short, but I liked coming up with this :)
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), ~~21~~ ~~20~~ 19 bytes
```
3ɽ÷«eeȮǒḋp«₁‹₁W‛, j
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=3%C9%BD%C3%B7%C2%ABee%C8%AE%C7%92%E1%B8%8Bp%C2%AB%E2%82%81%E2%80%B9%E2%82%81W%E2%80%9B%2C%20j&inputs=&header=&footer=)
## Explained
```
3ɽ÷ # stack = [1, 2]
«eeȮǒḋp« # stack = [1, 2, "miss a few"]
₁‹₁ # stack = [1, 2, "miss a few", 99, 100]
W‛, j # join stack on ", "
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 45 bytes
```
say join ", ",5-4,5-3,"miss a few",3*33,4*5*5
```
[Try it online!](https://tio.run/##K0gtyjH7/784sVIhKz8zT0FJB4hMdU2A2FhHKTezuFghUSEttVxJx1jL2FjHRMtUy/T/fwA "Perl 6 – Try It Online")
] |
[Question]
[
In the C standard library, header names end with a `.h` suffix:
```
stdio.h
```
In C++, those header names are available in an alternative form, with a `c` prefix instead:
```
cstdio
```
Write a function that converts the first form into the second. You can do the conversion in-place, or leave the original string intact and return a new string. Whatever feelds natural in your language of choice.
The code must be compiled/interpreted without errors. Compiler warnings are acceptable.
Here is your baseline C solution. It has **70 characters** and generates a warning about `strlen`:
```
void f(char*h){int i=strlen(h);h[--i]=0;while(--i)h[i]=h[i-1];*h='c';}
```
The shortest solution (measured in number of characters) wins.
**Update:** If your language of choice does not support functions, whole programs are also acceptable.
**Update:** As suggested by FUZxxl, here is a complete list of the header files in the C standard library:
```
assert.h
ctype.h
errno.h
float.h
limits.h
locale.h
math.h
setjmp.h
signal.h
stdarg.h
stddef.h
stdio.h
stdlib.h
string.h
time.h
```
Specifically, there are no header names with multiple dots in them.
[Answer]
# 80386 machine code, 13 bytes
Hexdump of the code:
```
b0 63 86 01 41 3c 2e 75 f9 c6 01 00 c3
```
Source code (can be compiled by Visual Studio):
```
__declspec(naked) void __fastcall conv(char s[])
{
_asm {
mov al, 'c'; // b0 63
myloop:
xchg al, [ecx]; // 86 01
inc ecx; // 41
cmp al, '.'; // 3c 2e
jne myloop; // 75 f9
mov byte ptr [ecx], 0; // c6 01 00
ret; // c3
}
}
```
It converts the string in-place. The code is so simple, it doesn't need to save and restore registers (using only `al` and `ecx`, which the `fastcall` convention allows to clobber).
[Answer]
# Python: 19 characters
```
lambda s:'c'+s[:-2]
```
[Answer]
# CJam, 6 bytes
```
'clW(<
```
This is a full program which reads the string via STDIN
**Explanation**:
```
'c "Put character c on stack";
l "Read a line from STDIN";
W "W is a predefined variable with value -1";
( "Decrease the value by 1";
< "Remove last 2 characters from the string on stack, the input argument";
```
[Try it online here](http://cjam.aditsu.net/#code='clW(%3C)
[Answer]
## Java 8 — 25 characters
```
h->"c"+h.replace(".h","")
```
[Answer]
# brainfuck - ~~25~~ 23 bytes
```
,[>,]<-----.<,<[<]>[.>]
```
>
> If your language of choice does not support functions, whole programs are also acceptable.
>
>
>
This is a whole program that takes input from STDIN.
```
,[>,] get all bytes of input
<-----. subtract 5 from last byte (always "h"; "h" minus 5 = "c") and print result
<, set second last byte to 0 by abusing comma
<[<]> go to first byte
[.>] print byte and move right until hitting 0
```
[Answer]
## Haskell — 23 characters
```
('c':).takeWhile(/='.')
```
## Haskell — 16 characters, as suggested by nimi
```
('c':).init.init
```
[Answer]
# C, 38
[See on Ideone](http://ideone.com/hDbAax)
```
f(s,o){snprintf(o,strlen(s),"c%s",s);}
```
`s` is a pointer to the input string, and `o` is where the output should be written to.
I found a way to abuse `snprintf`. The output string conveniently happens to be one character shorter than the input, and the maximum length of the string written by `snprintf` is 1 less than the `n` argument, so it cuts off the `.h`. Note: this technique will not work with Microsoft's implementation because it does the wrong thing and fails to null-terminate the string.
[Answer]
# TIS Node Type T21 Architecture - 85 bytes
**This answer is just for fun; the language came into existence after this challenge was written and I therefore cannot win with it. (Not that I was going to.)**

Okay, I had a little fun with this one. I probably *should* just call the language "TIS-100", but why break character? :D
TIS-100 is a game about programming a computer with a totally unique and bizarre architecture. I wrote a [custom puzzle](http://pastebin.com/zvnps8JV) for this challenge, which allows me to take input and check output against a known-correct "string". Unfortunately, there's no way to handle strings or characters, so this program simply uses the ASCII value of each character for input and output.
If you'd like to see it in action, you can use [this emulator](http://tise.hansihe.com/), or just watch me run it in the actual game [here](https://www.youtube.com/watch?v=zBbGYkiKGW4). Note that in the video, the final line of the first node is `D:MOV UP NIL`. After finishing the video, I realized I could golf that down to `D:ADD UP`. Functionally there's no difference, because the value of ACC is immediately overwritten anyway.
This is the string I used for my byte count:
```
MOV 99 ANY
MOV -46 ACC
ADD UP
JEZ D
ADD ACC ANY
JRO -5
D:ADD UP
MOV UP ANY
MOV UP ANY
```
That's the text of each non-empty node, seperated by newlines (effectively adding 1 byte for each node used beyond the first, mirroring our rule about code in multiple files).
[Answer]
**Windows Batch file 11**
```
@echo c%~n1
```
The first parameter passed in is %1. The ~n modifier returns just the filename without extension.
If it's acceptable to echo the expanded command to the screen as well, then the initial @ could be removed.
[Answer]
## Dyalog APL (8 characters)
```
'c',¯2↓⊢
```
This solution is exactly the same as the J solution I submitted but uses one character less due to `↓` being one character less than `}.`.
[Answer]
## J (9 characters)
```
'c',_2}.]
```
* `|y` is the *magnitude* of `y` (also called absolute value)
* `x }. y` drops `|x` items from `y`; items are dropped from the front if `x` is positive, from the end if `x` is negative.
* `x , y` appends `x` and `y`.
* `'c' , _2 }. y` does the transformation you want; in tacit notation this can be expressed as `'c' , _2 }. ]`.
[Answer]
# [Ostrich 0.6.0](https://github.com/KeyboardFire/ostrich-lang/releases/tag/v0.6.0-alpha), 8 characters
```
););"c\+
```
`)` is the "right uncons" operator. When applied to a string, it turns, for example, ``foo`` into ``fo` `o``. `;` is used to pop the extra character off, and this is done again.
Then, `"c` is pushed. This is simply a shorthand for ``c``.
`\+` swaps the top two stack elements and concatenates them.
[Answer]
# piet (9x11 = 99 8X11=88)

## another try (2x37 = 74)

Hard to make it much smaller since it needs to generate a 99 ('c') and a 46('.'), and that takes space in piet.
[Answer]
## F# - ~~39~~ ~~37~~ 31
*31 - Because typeinference in F# rocks!*
```
fun s->("c"+s).Replace(".h","")
```
*37*
```
fun(s:string)->"c"+s.Replace(".h","")
```
*39*
```
fun(s:string)->"c"+s.Remove(s.Length-2)
```
[Answer]
# gema, 6
```
*.h=c*
```
([Gema](http://gema.sourceforge.net/new/index.shtml) is an obscure macro language.)
[Answer]
# GNU sed -r, 14
sed doesn't really have any concept of functions, so here is a complete sed program instead:
```
s/(.*)../c\1/
```
### Output
```
$ sed -r 's/(.*)../c\1/' <<< stdio.h
cstdio
$
```
The `-r` has been included in the score as one extra character.
[Answer]
# Bash, 18
```
f()(echo c${1%.*})
```
### Output:
```
$ f stdio.h
cstdio
$
```
[Answer]
# [Prelude](http://esolangs.org/wiki/Prelude), 31 characters
Since full program submissions are apparently acceptable, here is a program that reads the C-style header from STDIN and prints the C++-style header to STDOUT:
```
99+9+(?)###(#
9(1-) ^)(!)
```
This requires a standard-compliant interpreter which prints output as character codes. If you're using [the Python interpreter](http://web.archive.org/web/20060504072747/http://z3.ca/~lament/prelude.py) you'll need to set `NUMERIC_OUTPUT = False`.
It also requires that there's no trailing newline on STDIN.
## Explanation
In Prelude all lines are executed in parallel, one column at a time. Each line has its own stack, initialised to an infinite amount of `0`s.
```
99+9+
9(1-)
```
This is the shortest I could come up with to get a `99` onto the top stack (the character code of `c`). First I add up `18` on the top stack and push a `9` onto the bottom stack. The bottom then counts down to `0` in a loop, while the top stack adds more `9`s up. This adds up to `99` on the top stack, and the bottom stack is left with `0`s again. Note that all of `+9+` is part of the loop, so there are actually two addition operations per iteration, but that's not an issue, thanks to the infinite supply of `0`s underneath.
Now `(?)` reads STDIN, one character at a time and pushes onto the top stack. The loop terminates at the end of the input, when `?` pushes a zero. `###` gets rid of that zero, the `h` and the `.`. Now the next loop pops numbers from the top stack while copying them to the bottom stack. This essentially reverses the stack. Note that the opening and closing parentheses are on different lines - this is not an issue, because the vertical position of the `)` is irrelevant in Prelude, but it saves me a byte on the first line.
Lastly, `(!)` prints all the characters until the stack is empty.
[Answer]
# Pyth, 7 characters
```
L+\cPPb
```
Explanation:
```
L def y(b):return
+\c "c" +
PPb b[:-1][:-1]
```
Try this:
```
L+\cPPb
y"stdio.h
```
on the online [Pyth Compiler/Executor](http://pyth.herokuapp.com/)
---
If full programs were allowed:
# Pyth, 6 characters
```
+\cPPQ
```
[Answer]
# C++14, 41 characters
```
[](auto&s){s="c"+s.substr(0,s.size()-2);}
```
Inspired by [this](https://codegolf.stackexchange.com/a/45698/25315) other answer. I made it a separate answer because here I use a feature that is new in c++14, [generic lambda](https://stackoverflow.com/q/17233547/509868).
See it in action [here](https://ideone.com/bB7F47).
[Answer]
## T-SQL — 58 characters
```
CREATE PROC Q(@ VARCHAR(MAX))AS
SELECT'c'+LEFT(@,LEN(@)-2)
```
Run as EXEC Q (your string here)
[Answer]
## Perl — 20 characters
```
sub{c.pop=~s/..$//r}
```
Note how `c` is a bareword and as such this requires a lack of `use strict`. This must be used as an expression, not a statement.
[Answer]
# Marbelous, 24
```
@063
-Z//
3W<C+Z
]]!!
@0
```
Takes input through STDIN, outputs to STDOUT.
This works by checking each byte with `.` (`0x46`). As `0x46` cannot fit inside a single base-36 digit, we subtract 35 (`Z`) before comparing, and add it back before outputting.
Each marble is duplicated by `3W` (three-way duplicator, but the left side is discarded off the side of the board). The marble sent downwards fetches the next byte from STDIN. The marble to the right is checked to `.`, then either outputted, or sent to `!!`, which terminates the program.
The program starts by passing `c` (`0x63`) through, which will be output to STDOUT.
[Try it online here.](https://codegolf.stackexchange.com/a/40808/29611) Libraries must be enabled, cylindrical boards must be disabled.
[Answer]
# C, 64
Mildly shorter than the c reference:
```
f(char*h){char*d=strstr(h,".");memmove(h+1,h,d++-h);*d=0;*h=99;}
```
Probably more golfing to be done with this.
---
### C, 48 (libc hack)
```
f(char*h){strcpy(h+1,h);*strstr(h,".")=0;*h=99;}
```
The `strcpy` manpage explicitly states "The strings may not overlap". However I found that the libc I am using appears to be coded safely to handle this correctly all the same. This is GNU C Library (Ubuntu EGLIBC 2.19-0ubuntu6.4) on Ubuntu 14.04.
[Answer]
# JavaScript (ES6) 20
Can't believe ES6 was still missing
```
s=>'c'+s.slice(0,-2)
```
[Answer]
# Perl, 15 (14 + -p)
```
s/(.*)\.h/c$1/
```
[Answer]
## mk, 34 characters
mk(1) is the Plan 9 replacement for make. Just for fun, this mkfile converts C header names into C++ header names:
```
c%:Q:
:
%.h:Q: c%
echo $prereq
```
There is a single tab before `:` and `echo`. Use like this:
```
% mk stdio.h
cstdio
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 5 bytes
```
\cpṪṪ
```
Explanation:
```
\cpṪṪ # full program
\c # c
p # prepend using implicit input
ṪṪ # remove last two letters
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%5Ccp%E1%B9%AA%E1%B9%AA&inputs=stdio.h&header=&footer=)
[Answer]
# CoffeeScript - 16
```
(x)->"c"+x[..-3]
```
[Answer]
# TI-BASIC 83/84, 15
```
"c"+sub(Ans,1,length(Ans)-2
```
] |
[Question]
[
Implement the classic rock paper scissors.
Conditions:
* user will input 'r', 'p' or 's'
* program will output 'r', 'p' or 's' and the result
* program choice ('r', 'p' or 's') has to be pseudo random (**I'm looking at you Howard**)
* result can be represented with any printable character, there should always be three possible results for what the user has input (the user wins, lose or is a tie).
* what happens if the user inputs nothing, or something different that 'r', 'p' or 's' should be not important.
You need to:
* Provide the golfed code.
* The ungolfed code
* How do you invoke the program
* A sample run
**I will choose the answer with less characters, if a tie presents the most up voted answer will be chosen.**
Good golfing and may luck be ever in your favor.
I will be posting an answer my self, in Java.
For the ones that live in a mountain under a rock:
>
> r = rock
>
>
> p = paper
>
>
> s = scissors
>
>
> rock: wins to scissors, loses with paper, a tie with rock.
>
>
> paper: wins to rock, loses with scissors, a tie with paper.
>
>
> scissors: wins to paper, loses with rock, a tie with scissors.
>
>
>
Current Positions:
* UN: Username
* PL: Programming Language
* CC: Character Count
* UV: Up votes
>
>
> ```
> ╔══════════════════╦════════════╦══════╦════╗
> ║ UN ║ PL ║ CC ║ UV ║
> ╠══════════════════╬════════════╬══════╬════╣
> ║ Howard ║ GolfScript ║ 6 ║ 15 ║
> ║ primo ║ Perl ║ 27 ║ 7 ║
> ║ TwiNight ║ APL ║ 31 ║ 4 ║
> ║ primo ║ Perl ║ 33 ║ 7 ║
> ║ marinus ║ APL ║ 36 ║ 5 ║
> ║ primo ║ Perl ║ 38 ║ 7 ║
> ║ primo ║ Perl ║ 48 ║ 7 ║
> ║ yehuda-schwartz ║ javascript ║ 49 ║ 1 ║
> ║ manatwork ║ Ruby ║ 54 ║ 13 ║
> ║ w0lf ║ GolfScript ║ 62 ║ 4 ║
> ║ tmartin ║ K ║ 67 ║ 2 ║
> ║ Abhijit ║ Python 3 ║ 74 ║ 5 ║
> ║ beary605 ║ Python 3 ║ 76 ║ 4 ║
> ║ rlemon ║ javascript ║ 85 ║ 4 ║
> ║ ugoren ║ C ║ 86 ║ 3 ║
> ║ Egor Skriptunoff ║ LUA ║ 87 ║ 4 ║
> ║ Fors ║ Befunge ║ 107 ║ 3 ║
> ║ Vi. ║ Clojure ║ 129 ║ 1 ║
> ║ Henrik ║ C# ║ 167 ║ 4 ║
> ║ dystroy ║ Go ║ 169 ║ 1 ║
> ║ primo ║ ferNANDo ║ 259 ║ 5 ║
> ║ anakata ║ Java ║ 259 ║ 1 ║
> ║ epoch ║ Java ║ 387 ║ 1 ║
> ║ jdstankosky ║ LOLCODE ║ 1397 ║ 15 ║
> ╚══════════════════╩════════════╩══════╩════╝
>
> ```
>
>
I can't select Howards answer, since it was a (successful) attempt to bend the rules, but I change them, to make them extra explicit.
primo 27 character answer can't be selected because it's not pseudo random per se
primo -p answer, I'm gonna go with "-p would be counted as 3 bytes: one for the -, one for the p, and one more the necessary whitespace."
**Thanks to all who answered, I hope you have had a good time!**
***NOTE: I will be trying to edit this every other week, to adjust the table, and change my selected answer if someone beats the current one, so If you just got here, post your answer if you want!***
[Answer]
# LOLCODE, 1397
***Note:** I submitted this before I noticed the winning requirement was changed from popularity with golf tie-break to golf with popularity tie-break.*
There's not really any strict syntax, but I'm sure this is acceptable.
```
HAI
I HAS A CRAZY, LUCKY, CHALLENGE, TREAT
I HAS YUMMY ITZ "LOL U LOZED"
I HAS MEH ITZ "NOWAI TIED"
I HAS GROSS ITZ "OMG U WONNED"
I HAS BURNT ITZ "LAME"
GIMMEH CHALLENGE
BTW I HOPE I R TEH WINZ
LOL CRAZY IZ BETWEEN 1 AN 3
I HAS A SUPA ITZ A BUKKIT
LOL SUPA'Z 1 R "ROCK"
LOL SUPA'Z 2 R "PAPER"
LOL SUPA'Z 3 R "SCIZZORS"
LOL LUCKY R SUPA'Z CRAZY
GOT CHALLENGE, WTF?
OMG "Rock"
GOT LUCKY, WTF?
OMG ROCK, LOL TREAT R MEH, GTFO
OMG PAPER, LOL TREAT R YUMMY, GTFO
OMG SCIZZORS, LOL TREAT R GROSS, GTFO
OIC
OMG "Paper"
GOT LUCKY, WTF?
OMG ROCK, LOL TREAT R GROSS, GTFO
OMG PAPER, LOL TREAT R MEH, GTFO
OMG SCIZZORS, LOL TREAT R YUMMY, GTFO
OIC
OMG "Scissors"
GOT LUCKY, WTF?
OMG ROCK, LOL TREAT R YUMMY, GTFO
OMG PAPER, LOL TREAT R GROSS, GTFO
OMG SCIZZORS, LOL TREAT R MEH, GTFO
OIC
OMGWTF
VISIBLE "WHAT U SAYZ?", LOL TREAT R BURNT
GTFO
OIC
BOTH SAEM TREAT AN BURNT, O RLY?
YARLY
VISIBLE "YOU BURNTED MAH TREAT!"
NOWAI
VISIBLE SMOOSH "I GUESSED " AN LUCKY
VISIBLE TREAT
KTHX
KTHXBAI
```
If this were to be successfully executed as `RockPaperScissors.LOL`, here's what some possible random outcomes could be:
* Input: `Rock` - Output: `I GUESSED SCIZZORS U WONNED`
* Input: `Paper` - Output: `I GUESSED PAPER NOWAI TIED`
* Input: `Scissors` - Output: `I GUESSED ROCK LOL U LOZED`
* Input: `Tuna` - Output: `WHAT U SAYZ? YOU BURNTED MAH TREAT!`
[Answer]
### GolfScript
```
n"Draw"
```
Above code implements the required functionality. Additionally, it ensures that the player will never be left angry because of a (perceived) unfairness of computer's strategy.
**Ungolfed version**
```
n"Draw"
```
**How to invoke the program**
The input (a single character of 'r', 'p', 's') has to be provided on STDIN, possibly terminated with newline.
**A sample run**
```
> echo r | ruby golfscript.rb rockpaperscissors.gsc
r
Draw
```
**Explanation of the code**
For all those not familiar with GolfScript I'll add an detailed explanation of how this code works. The code essentially exists of three parts.
```
### Computer's strategy ###
# The strategy used to play r/p/s.
# The computer is so fast, it can really guess in an instance
# what the player has played. Since the computer should
# not play unfair, the best strategy is to always go for a
# draw and choose the same move.
# on the stack is player's move
# choose to play the same -> now the computer's move is on the stack
### Fiddle with input ###
# The input may of may not be delimited by newline.
# In order to make the output readable, we'll give
# a newline here.
n # Push a newline onto the stack
### Give the result ###
# We can skip a complicated calculation of the result
# since we chose to play draw anyways.
"Draw" # Push the result onto the stack
# Output is printed automatically when GolfScript code terminates.
```
**Notes**
Since this is not code-golf but popularity contest I didn't choose the shortest version. Maybe in case of a tie a shorter code will knock out my solution. Nevertheless, for those interested in golfing, the following possibilities are given:
* Deal only with proper input and force user to provide a newline. This will save one character.
* The rules have a small insufficiency which allows to save another character by bending the rules. The result can always be printed as "Win" - it was not specified that the correct result has to be printed. But note that players will soon get angry if you choose to implement a cheating program.
* The output format is not well specified. We can choose `0` as output for draw. Thus, the shortest valid program is the single-character code `0`.
[Answer]
# Ruby: ~~61~~ 54 characters
```
o="rps";p o[c=rand(3)],%w{Draw Win Lose}[c.-o.index$_]
```
Somehow explained:
The entire problem is reduced to calculating the following results:
```
╲ machine
h ╲| 0 1 2
u ──┼──────
m 0 │ 0 1 2
a 1 │ 2 0 1
n 2 │ 1 2 0
```
Where the numbers mean:
* choice: 0 rock, 1 paper, 2 scissor
* result: 0 draw, 1 win, 2 lose
For this I used the formula: machine\_choice - human\_choice. This occasionally results negative value, but as it is only used as index and negative index is counted backward, will pick the correct array element.
```
# ┌── choosable object type
# │ ┌── machine's choice numeric code
# │ │ ┌── result type
# │ │ │ ┌── human's choice
# │ │ ┌───────┴───────┐ │
o="rps";p o[c=rand(3)],%w{Draw Win Lose}[c.-o.index$_]
# └─────┬────┘ └─────┬────┘
# └── machine's choice letter │
# └── result numeric code
```
Used methods (others then `Fixnum`'s obvious ones):
* [Kernel.p(obj) → obj](http://ruby-doc.org/core-2.0/Kernel.html#method-i-p) – “For each object, directly writes *obj*.`inspect` followed by a newline to the program’s standard output.”
* [Kernel.rand(max=0) → number](http://ruby-doc.org/core-2.0/Kernel.html#method-i-rand) – “If called without an argument, or if `max.to_i.abs == 0`, rand returns a pseudo-random floating point number between 0.0 and 1.0, including 0.0 and excluding 1.0.”
* [String.index(substring [, offset]) → fixnum or nil](http://ruby-doc.org/core-2.0/String.html#method-i-index) – “Returns the index of the first occurrence of the given *substring* or *pattern* (regexp) in *str*.”
Ungolfed:
```
object_type = "rps";
result_type = %w{Draw Win Lose}
machine_choice = rand(3)
human_choice = $_
p object_type[machine_choice]
result_code = machine_choice - object_type.index(human_choice)
p result_type[result_code]
```
Sample run:
```
bash-4.2$ ruby -nle 'o="rps";p o[c=rand(3)],%w{Draw Win Lose}[c.-o.index$_]'
r
"p"
"Win"
p
"p"
"Draw"
s
"p"
"Lose"
```
[Answer]
## APL, 31
```
'TWL'[1+3|-/x⍳⎕←⍞,(?3)⌷x←'rps']
```
`x←'rps'` Assign string `'rps'` to `x`
`(?3)⌷` Choose random integer 1~3, choose that index of `x`
`⍞,` Prepend user input to machine choice
`⎕←` Output resulting string
`x⍳` Convert to numerical array by indexOf in `x`
`-/` Difference of the two numbers
`1+|3` Modulus 3 and plus 1
`'TWL'[...]` indexing from `'TWL'`
**Sample**
```
r
rp
L
```
User choose rock, program choose paper: Lose
[Answer]
## C# (167 characters)
My very first try at golfing.
**Golfed**
`using System;class P{static void Main(string[] i){var m="rspr";var a=m[Environment.TickCount%3];Console.WriteLine(a+" "+(i[0][0]==a?"T":m.Contains(i[0]+a)?"W":"L"));}}`
**Un-golfed**
```
using System;
class P
{
static void Main(string[] i)
{
var m = "rspr";
var a = m[Environment.TickCount % 3];
Console.WriteLine(a + " " + (i[0][0] == a ? "T" : m.Contains(i[0] + a) ? "W" : "L"));
}
}
```
**Sample Run**
The app requires single char inputs as argument 1 to the application, either `r`, `s` or `p`.
```
cmd > app.exe r
```
**All possible outcomes**
* `cmd > app.exe r` gives output `r T` (rock, tie)
* `cmd > app.exe r` gives output `p L` (paper, lost)
* `cmd > app.exe r` gives output `s W` (scissors, win)
* `cmd > app.exe p` gives output `r W` (rock, win)
* `cmd > app.exe p` gives output `p T` (paper, tie)
* `cmd > app.exe p` gives output `s L` (scissors, lost)
* `cmd > app.exe s` gives output `r L` (rock, lost)
* `cmd > app.exe s` gives output `p W` (paper, win)
* `cmd > app.exe s` gives output `s T` (scissors, tie)
[Answer]
## Perl 48 bytes
```
$%=rand 3;print"$%
"^B,(Draw,Lose,Win)[$%-=<>^B]
```
The script prints the result from the computer's perspective, for example if the player chooses `r` and the computer chooses `s`, the result is `Lose`. `$%` (format page number) is used to store the computer's move, as it may only contain an integer value, which saves an int cast.
Ungolfed:
```
# choose a random move index 0, 1, or 2
$cindex = int(rand 3);
# convert this index to a move
# 0 => r, 1 => s, 2 => p
$cmove = "$cindex" ^ B;
# read the player's move
$pmove = <>;
# convert this move to its index
$pindex = $pmove ^ B;
# print computer's move
print $cmove, $/;
# compare indices, and output result
@result = (Draw, Lose, Win);
print $result[$cindex - $pindex];
```
Sample usage:
```
$ echo p | perl rps.pl
s
Win
$ echo r | perl rps.pl
r
Draw
$ echo s | perl rps.pl
p
Lose
```
The script may also be run interactively, by typing your move followed by `Enter`:
```
$ perl rps.pl
r
s
Lose
```
---
## Rule Stretching
### Perl 35 +3 bytes
```
$_=($%=rand 3).(D,L,W)[$%-($_^B)]^B
```
Requires the `-p` command line switch (counted as 3 bytes). Each of the outcomes `Win`, `Lose` and `Draw` have been mapped to `W`, `L`, `D`. The newline between the computer's choice and the result has been excluded.
Sample usage:
```
$ echo r | perl -p rps.pl
sL
```
---
### Perl 30 +3 bytes
```
$_=($%=rand 3).($%-($_^B))%3^B
```
Once again requires `-p`. Here `Win`, `Lose` and `Draw` have been mapped to `2`, `1` and `0` respectively. This is still technically compliant, as they are printable characters.
Sample usage:
```
$ echo r | perl -p rps.pl
s1
```
---
### Perl 24 +3 bytes
```
$_=$^T%3 .($^T-($_^B))%3^B
```
Requires `-p`, WLD mapped to `2`, `1`, `0` as before. Each `^T` should be replaced with a literal ascii character 20. This one is admittedly a bit of a stretch; `$^T` returns the number of seconds since epoch from when the script was started. All outcomes are possible, but it doesn't quite qualify as pseudo-random.
Sample usage:
```
$ echo r | perl -p rps.pl
s1
```
[Answer]
## APL (~~38~~ 36)
```
c[i],(⌽↑⌽∘'TWL'¨⍳3)[⍞⍳⍨c←'rps';i←?3]
```
Outputs 'T', 'W' and 'L' for tie, win and lose.
Sample run:
```
c[i],(⌽↑⌽∘'TWL'¨⍳3)[⍞⍳⍨c←'rps';i←?3]
p
rW
```
(User types 'p' for paper. Computer chooses 'r' (rock), user wins)
Explanation:
* `⌽↑⌽∘'TWL'¨⍳3`: generates the following matrix:
```
TLW
WTL
LWT
```
* `⍞⍳⍨c←'rps'`: set `c` to the string `'rps'`, read user input and get the index of the user input in the string (this will be a value from 1 to 3). This index is used as the Y coordinate into the matrix.
* `i←?3`: get a random number from 1 to 3 and store it in `i`, this is the computer's choice. This is used as the X coordinate into the matrix.
* `c[i]`: use `i` as an index into `c`, displaying the computer's choice as 'r', 'p', or 's'.
[Answer]
## [ferNANDo](http://esolangs.org/wiki/FerNANDo) 1184 (259 golfed) bytes
*An interpreter written in Python can be found at the bottom of the linked page.*
ferNANDo is a esoteric language which supports only one variable type, boolean, and only one operation, NAND. As you might imagine, this can lead to some fairly long logic to accomplish seemingly simple tasks. It has support for reading from stdin (one byte at a time), writing to stdout (also one byte at a time), conditional loops, and also a random boolean generator.
There are no keywords whatsoever; everything is a variable. A statement's function is determined solely by the number of variables it contains. There are also no comments, so I've done my best to make the code self-commenting. The last four lines might be a bit confusing, but it will probably suffice to say that it prints `Win!`, `Lose`, or `Draw` depending on the outcome.
```
not sure, but right now i'm guessing you're_not_paper you're_scissors
you're_paper not you're_not_paper
you're_not_scissors not you're_scissors
you're_rock you're_not_paper you're_not_scissors
you're_rock you're_rock
o_shi-
i'm_not_paper right ?
i'm_scissors right ?
i'm_paper not i'm_not_paper
i'm_not_scissors not i'm_scissors
o_shi- i'm_paper i'm_scissors
o_shi- o_shi-
o_shi-
i'm_rock i'm_not_paper i'm_not_scissors
i'm_rock i'm_rock
print right now but only if i'm_not_paper i'm_scissors
print a newline here, not more, not less
i_win_if i'm_scissors you're_paper
or_if i'm_rock you're_scissors
or_even_if i'm_paper you're_rock
i_win i_win_if or_if
i_win i_win
i_win or_even_if
i_lose_if i'm_paper you're_scissors
or_if i'm_scissors you're_rock
or_even_if i'm_rock you're_paper
i_lose i_lose_if or_if
i_lose i_lose
i_lose or_even_if
i_don't_win not i_win
i_don't_lose not i_lose
we_tie i_don't_win i_don't_lose
we_tie we_tie
we_don't_tie not we_tie
print now if i_win i_lose not i_win i_win
print but not we_tie we_don't_tie i_lose i_don't_win we_don't_tie
print right now i_lose i_win i_win we_don't_tie i_don't_win
print i_don't_win but we_tie or i_don't_win we_tie now
```
The script can be run interactively, by typing your move followed by `Enter`.
Sample usage (assuming you've named the interpreter `nand.py`):
```
$ python nand.py rps.nand
p
s
Win!
$ python nand.py rps.nand
r
r
Draw
$ python nand.py rps.nand
s
p
Lose
```
---
**Edit:** Just to prove that ferNANDo can compete with Java, here's a 'golfed' version at **259 bytes**. The logic is sightly different; it checks `not win` and `not tie`, which saves a few NAND gates (because then I only need the `not` versions of the player's moves, and because `not lose` wasn't required for the output). Not nearly as interesting to read, though.
```
1 _ _ _ _ _ _ A b
B 1 b
C A B
o
P 1 ?
s 1 ?
p 1 P
S 1 s
o p s
o o
o
r P S
r r
0 1 1 1 0 0 P s
0 0 0 0 1 0 1 0
t s A
u r B
v p C
W t u
W W
W v
t p A
u s B
v r C
D t u
D D
D v
w 1 W
d 1 D
l W D
l l
0 1 0 w l 1 w w
0 1 1 d D l W D
0 1 1 l w w D W
0 W 1 d 0 W d 1
```
[Answer]
# [Python 3](https://docs.python.org/3/), 55 bytes
```
q={*'rps'}.pop()
print(q,'rrppssrpsr'.count(q+input()))
```
[Try it online!](https://tio.run/##FYyxDsIgGAZ3noKwAGq6uJF0rKuLL6D4JyUa@PsBsY3x2ZGud7njrcwpnptPTxqVUm0ZvwcNzvo3cGJjBSPEYpaTBphz7gp68Knu8Bgi12Ksta234jOHN8kbKjkhZcHmJK3kzT63ndDqiYucrpcJSHDyAbq/GgSL/Ac "Python 3 – Try It Online")
With the [release of Python 3.3](https://www.python.org/downloads/release/python-330/) came default hash randomization. As such, we can use the `set.pop` method to get a random character from the string `'rps'`.
The program appends the input character to the randomly generated character and counts how often the combination appears in the string `'rrppssrpsr'`.
Outputs `0` for program win, `1` for tie and `2` for player win.
[Answer]
**Python 3.x: 74 Characters**
```
import time
A,f="psr",time.gmtime()[5]%3
print(A[(A.find(input())+f)%3],f)
```
How it works
```
Before Machine Proceeds it determines the outcome of the game and based
on the outcome, it determines the choice which would result in the outcome
viz Human's choice
\ Outcome
\ 0 1 2
\_____________
H |
U 0| 0 1 2
M 1| 1 2 0
A 2| 2 0 1
N |
Where Choices are represented as
0 --> Paper
1 --> Scissor
2 --> Rock
Outcome (From Computer's Perspective)
0 --> Draw
1 --> Win
2 --> Fail
Given the sequence of choices as a string
"psr"
So its easy to see, if computer needs to win, it needs to choose the character
next to what human chooses.
If computer needs to loose, it needs to choose the previous character to what
human chooses
MACHINE's| CHOICES | Formulation
FATE |-----------------| For Machine's
| P S R | Choice
---------|-----------------|-----------------------------
WIN(1) | H ---> M | (CHOICE+1) % 3 = (CHOICE+WIN)%3
---------|-----------------|-----------------------------
LOSS(2) | M H -----\ | (CHOICE+2)%3 = (CHOICE+LOSS)%3
| ^ | |
| |____________| |
---------|-----------------|------------------------------
DRAW(0) | H | (CHOICE+0)%3 = (CHOICE+DRAW)%3
| M |
---------|-----------------|
Combining all the above we have
MACHINE's CHOICE = (HUMAN CHOICE + MACHINE's FATE) % 3
```
Based on the fate, it determines what should it's choice be based on the formula
```
result = (User_choice + machines_fate) % no_of_choices
machine_choice = "psr"[result]
```
Un-golfed Version
```
import time
choices = "psr"
#time.gmtime() returns the time structure in gmt
#time.gmtime()[5] is the current second tick
fate = time.gmtime()[5]%3
user_choice = input()
result = (choices.find(user_choice)+fate)%len(choices)
machine_choice = choices[result]
print(machine_choice, fate)
```
Sample run
```
D:\temp\rivalry>rps.py
r
r 0
D:\temp\rivalry>rps.py
r
p 1
D:\temp\rivalry>rps.py
p
r 2
D:\temp\rivalry>rps.py
p
r 2
D:\temp\rivalry>rps.py
p
s 1
D:\temp\rivalry>rps.py
p
s 1
D:\temp\rivalry>rps.py
p
p 0
```
[Answer]
## Lua, 87
```
c,n=os.time()%3+1,'rps'print(n:sub(c,c),({'Draw','Win','Defeat'})[(n:find(...)-c)%3+1])
```
Usage:
```
$ lua rps.lua p
s Defeat
```
Ungolfed:
```
names = 'rps'
comp_idx = os.time()%3 + 1 -- 1, 2 or 3 (depends on timer)
comp_move = names:sub(comp_idx, comp_idx) -- 'r', 'p' or 's'
user_move = ... -- input parameter: 'r', 'p' or 's'
user_idx = names:find(user_move) -- 1, 2 or 3
delta_idx = (user_idx - comp_idx) % 3 -- 0, 1 or 2
all_results = {'Draw', 'Win', 'Defeat'} -- [1]=='Draw', [2]=='Win', [3]=='Defeat'
game_result = all_results[delta_idx + 1]
print(comp_move, game_result)
```
[Answer]
## GolfScript 62
An alternative GolfScript solution, much more boring than [Howard's](https://codegolf.stackexchange.com/a/11193/3527) :).
The program chooses a move randomly and displays the result from the perspective of the user.
### The Code
```
'rssppr'.[6rand=]''+:§@+..&,({?)§\'Lose''Win'if}{;;§'Draw'}if`
```
### Sample run
>
> > echo s | ruby golfscript.rb rps.gs
>
>
> r"Lose"
>
>
>
### Online test
You can run the program and experiment with different inputs here: <http://golfscript.apphb.com/?c=OydzJwoKJ3Jzc3BwcicuWzZyYW5kPV0nJys6wqdAKy4uJiwoez8pwqdcJ0xvc2UnJ1dpbidpZn17OzvCpydEcmF3J31pZmA%3D>
Note, however, that the parameter (user move) that's usually passed in the command line is now added to the stack in the code itself (there's no way to provide "real" command line parameters in this online tool).
### "Ungolfed" version
I don't have any idea what *ungolfed* means when it comes to GolfScript, so I tried to add comments. Hopefully that will clarify how the code works and make it a bit more readable:
```
# initially, the input (user's move) is on the stack
'rssppr' # push the string 'rsspr' on the stack...
. # ...twice.
[
6rand # get a pseudo-random integer in the [0-5] range
= # use the random index to get
# a letter from the string above
]''+ # workaroud to get the actual letter instead of the
# ASCII code
:§ # assign the randomly chosen letter (computer's move)
# to a nice variable called "§"
@ # rotates last 3 elements on the stack, bringing
# the user input in the uppermost position
# So, now we have: "rssppr" <computer_move> <user_move>
# on the stack
+ # concatenate the two moves, so now we have a string
# that contains both (ex: "rs")
.. # copy the move string twice
& # do a setwise AND to get the DISTINCT elements
,( # get the length of the resulting string and subtract 1
# (now we have 0 if the letters were equal and non-zero otherwise)
{ # beginning of block to execute when the moves are different:
# now we have on the stack two strings:
# - the string 'rssppr'
# - the string containing the moves (ex: 'rs')
? # find the second string inside the first one,
# and get the index at which it occurs
# (or -1 if it does not)
) # increment that number (we now get 0 if no occurrence, 1 otherwise)
§ # recall the § variable (so we display the computermove)
\ # rotate the uppermost two stack entries
'Lose''Win'if # if the move pair is found in the 'rssppr' string,
# then print 'Lose', otherwise print 'Win'
}
{ # beginning of block to execute when the moves are identical:
;; # discard the latest two stack items (not needed in this case)
§ # display computer's move
'Draw' # display the text 'Draw'
}
if # if computer's and user's moves were NOT equal,
# execute the first block.
# if they were, execute the second block
` # put the last word in quotes to separate it from computer's move
```
[Answer]
## C, 92 86 chars
```
main(y){
srand(time(0));
y="rps"[rand()%3];
printf("%c%c\n",y,"LWWTLLW"[getchar()-y+3]);
}
```
Prints the computer's choice, and the result from the user's point of view - W=you win, L=you lose, T=tie.
The simple formula `x-y`, given the ASCII values of the choices, gives 0 on draw (obviously) and a unique value in each other case.
[Answer]
## Python 2 (~~86~~ ~~84~~ ~~80~~ 78), Python 3 - 76 chars
0 - tie, 1 - lose, 2 - win
```
from random import*
a=raw_input()
b=choice('psr')
print(a!=b)+(b+a in'rpsr'),b
from random import*
a=input()
b=choice('psr')
print((a!=b)+(b+a in'rpsr'),b)
```
Ungolfed
```
from random import*
moves = 'psr'
inp = raw_input()
comp = choice(moves)
match = comp+inp
is_not_tie = inp!=comp
wins = 'r' + moves #rpsr; rock beats scissors, scissors beats paper, paper beats rock
print is_not_tie + (match in wins), comp
```
How to run:
`python file_name_here.py`
Problems:
Computer AI: 35 characters
[Answer]
First try without reviewing others.
golfed: 107 85 bytes
```
i=prompt(),c="rps"[new Date%3],w={r:"s",p:"r",s:"p"};alert(c+(i==w[c]?2:w[i]==c?1:3))
```
output is [npc-choice][1:win, 2:loss, 3:tie]
ungolfed:
```
var input = prompt(),
choices = ["r","p","s"],
computer_choice = choices[Math.floor(Math.random() * 3)],
outcomes = {'r':'s','p':'r','s':'p'},
winner;
if( input == outcomes[computer_choice] ) {
winner = 'NPC';
} else if ( computer_choice == outcomes[input] ) {
winner = 'You';
} else {
winner = 'No one, it was a Tie!';
}
alert('Computer chose: ' + computer_choice + '\n' +
'The winner is: ' + winner);
```
[Answer]
## PowerShell: 144 133 117 111 92 73
>
> **Changes from original:**
>
>
> * Completely re-wrote script after seeing [Danko Durbic's three-player even or odd solution](https://codegolf.stackexchange.com/a/15550/9387).
> * Changed $s to a single string instead of a character array.
> * Used IndexOf as a direct method on $s, instead of spelling out the .NET class & method.
> * Removed redundant `%3`s.
>
>
> All told, nearly cut the length in half from my original answer!
>
>
>
**Golfed code:**
```
$p=($s='rps').IndexOf((read-host));$s[($c=Random 3)];"TWLLTWWLT"[$p+$c*3]
```
Can be run straight from the console.
**Ungolfed, with comments:**
```
# Variable $p will store the player's selection as a ternary digit by finding its position in a string containing the possible choices.
$p=(
# Possible choices will be stored in a variable, $s, for later reuse.
$s='rps'
# Get the position of the player's choice from $s.
).IndexOf((read-host));
# Express the computer's choice by outputting the appropriate character from $s.
$s[(
# Computer's choice will be stored as a ternary digit in $c.
$c=Random 3
)];
# Outcome for the player will be chosen from a string of possible outcomes by looking up the decimal repesentation of a two-digit ternary number.
# The threes digit is represented by $c, ones digit by $p.
"TWLLTWWLT"[$p+$c*3]
# Variable cleanup - do not include in golfed code.
rv p,s,c
```
Some sample runs at the console:

[Answer]
**JAVA 259 :(**
```
class c {public static void main(String[]a){char y=a[0].charAt(0);char m="rps".charAt(new java.util.Random().nextInt(3));if(y==m)a[0]="T";else if((y=='r'&& m=='s')||(y=='s'&& m=='p')||(y=='p'&& m=='r'))a[0]="1";else a[0]="0";System.out.println(m+":"+a[0]);}}
```
Highly ungolfed code:
```
class c {
public static void main(String[] a) {
char y = a[0].charAt(0);
char m = "rps".charAt(new java.util.Random().nextInt(3));
if (y == m) {
a[0] = "T";
} else if ((y == 'r' && m == 's') || (y == 's' && m == 'p') || (y == 'p' && m == 'r')) {
a[0] = "1";
} else {
a[0] = "0";
}
System.out.println(m + ":" + a[0]);
}
}
```
Sample runs:
>
> C:>java c r
>
>
> s:1
>
>
> C:>java c p
>
>
> p:T
>
>
> C:>java c s
>
>
> s:T
>
>
>
[Answer]
# Befunge: 107 characters
```
~v@,"w"< < < <
v?v3.14159265@,"l"<
"""358979323846>3-|
rps26433832>:1+|
"""7950>:2+|
>>>:,-:|
28@,"t"<
```
Slightly clunky. It is shrinkable, the question is by how much.
[Answer]
## JavaScript (87)
Golfed:
```
o='LDW'[2*((a=prompt())+(b='prs'[new Date%3])!='ps'&a<b|a+b=='sp')+ +(a==b)];alert(b+o)
```
Ungolfed:
```
var player = prompt(),
computer = 'prs'[new Date%3], // Date mod 3 "pseudo-random"
outcome = 'LDW'[2*(player+computer != 'ps'
& player < computer
| player + computer == 'sp') // convert boolean W/L outcome to int (0,2)
+
+(player == computer)]; // convert D outcome to int (0,1)
alert(computer + outcome);
```
You can simply paste the code in your browser's javascript console to run it.
If I'm allowed to print the result before printing the computer's selection **(83)**:
```
alert('LDW'[2*((a=prompt())+(b='prs'[new Date%3])!='ps'&a<b|a+b=='sp')+ +(a==b)]+b)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
“rps”ɓ3XṄ+i@ị
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw5yiguJHDXNPTjaOeLizRTvT4eHu7v@H24FslUdNa/7/LyoqKigoKC4uBgA "Jelly – Try It Online")
Decides and prints the outcome (3 for a tie, 2 for a win, 1 for a loss) *before* determining its own move, so the validity might be somewhat dubious.
```
“rps” Set the left argument to "rps",
ɓ then start a dyadic link with reversed arguments:
3X choose 1, 2, or 3,
Ṅ print that number with a newline,
+ add it to
i@ the index of the left argument in the right argument,
ị and take the element of the right argument at that modular index.
```
Without going backwards:
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
“rps”ðXṄ⁸i_i%3
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw5yiguJHDXMPb4h4uLPlUeOOzPhMVeP/h9uBPJVHTWv@/y8qKiooKCguLgYA "Jelly – Try It Online")
0 for tie, 2 for win, 1 for loss.
```
“rps” Set the left argument to "rps",
ð then start a dyadic link:
X choose a random element of the left argument,
Ṅ print it,
⁸i find its index in the left argument,
_ subtract
i the right argument's index in the left argument,
%3 and mod 3.
```
[Answer]
## x86-64 machine code (Linux), 98 bytes
```
00000000 54 5d 31 c0 31 ff 48 8d 75 f0 6a 02 5a 0f 05 8a |T]1.1.H.u.j.Z...|
00000010 5d f0 b8 3e 01 00 00 48 8d 7d f0 6a 01 5e 31 d2 |]..>...H.}.j.^1.|
00000020 0f 05 8a 45 f0 6a 03 59 48 f7 f1 8a 8a 58 00 00 |...E.j.YH....X..|
00000030 00 88 4d f0 28 cb 80 c3 03 8a 8b 5b 00 00 00 88 |..M.(......[....|
00000040 4d f1 6a 01 58 6a 01 5f 48 8d 75 f0 6a 02 5a 0f |M.j.Xj._H.u.j.Z.|
00000050 05 6a 3c 58 31 ff 0f 05 72 70 73 6c 77 77 64 6c |.j<X1...rpslwwdl|
00000060 6c 77 |lw|
```
Disassembly:
```
0: 54 push rsp
1: 5d pop rbp ; Setup basic frame pointer
2: 31 c0 xor eax,eax
4: 31 ff xor edi,edi
6: 48 8d 75 f0 lea rsi,[rbp-0x10]
a: 6a 02 push 0x2
c: 5a pop rdx
d: 0f 05 syscall ; Read 2 bytes from STDIN into RBP-0x10 (input char + newline)
f: 8a 5d f0 mov bl,BYTE PTR [rbp-0x10] ; Move input into BL
12: b8 3e 01 00 00 mov eax,0x13e
17: 48 8d 7d f0 lea rdi,[rbp-0x10]
1b: 6a 01 push 0x1
1d: 5e pop rsi
1e: 31 d2 xor edx,edx
20: 0f 05 syscall ; Get 1 random byte
22: 8a 45 f0 mov al,BYTE PTR [rbp-0x10]
25: 6a 03 push 0x3
27: 59 pop rcx
28: 48 f7 f1 div rcx
2b: 8a 8a 58 00 00 00 mov cl,BYTE PTR [rdx+0x58]
31: 88 4d f0 mov BYTE PTR [rbp-0x10],cl ; Get random throw
34: 28 cb sub bl,cl
36: 80 c3 03 add bl,0x3
39: 8a 8b 5b 00 00 00 mov cl,BYTE PTR [rbx+0x5b]
3f: 88 4d f1 mov BYTE PTR [rbp-0xf],cl ; Decide win/lose/draw
42: 6a 01 push 0x1
44: 58 pop rax
45: 6a 01 push 0x1
47: 5f pop rdi
48: 48 8d 75 f0 lea rsi,[rbp-0x10]
4c: 6a 02 push 0x2
4e: 5a pop rdx
4f: 0f 05 syscall ; Print 2 chars to STDOUT (the computer's throw (r/p/s) and the winner (w/l/d))
51: 6a 3c push 0x3c
53: 58 pop rax
54: 31 ff xor edi,edi
56: 0f 05 syscall ; Exit with return code 0
58: 727073 6c7777646c6c77 (data)
```
Outputs 'w' for win, 'l' for lose, and 'd' for draw.
Example run:
```
$ ./rps
r
sw
```
User picked rock and computer picked scissors. User wins.
[Answer]
## K, 67
```
{-1'f:x,*1?"rps";$[f in b:("pr";"rs";"sp");"W";f in|:'b;"L";"D"]}
```
Prints W,L,D for win/lose/draw.
Ungolfed:
```
rps:{[x]
res:x,*1?"rps"; // join user input to random selection of r,p,s
-1'f; // print the user input and the program selection to stdout
wins:("pr";"rs";"sp"); // the universe of winning combinations
losses:|:'wins; // reverse each win to the get losses
$[f in wins;
"win";
f in losses;
"lose";
"draw"]
}
```
Or in Q, which is more readable:
```
rps:{[x]
res:x,rand["rps"]; // join user input to random selection of r,p,s
-1 each f; // print the user input and the program selection to stdout
wins:("pr";"rs";"sp"); // the universe of winning combinations
losses:reverse each wins; // reverse each win to the get losses
$[f in wins;
"win";
f in losses;
"lose";
"draw"]
}
```
Sample Run:
```
k){-1'f:x,*1?"rps";$[f in b:("pr";"rs";"sp");"W";f in|:'b;"L";"D"]}"r"
r
s
"W"
k){-1'f:x,*1?"rps";$[f in b:("pr";"rs";"sp");"W";f in|:'b;"L";"D"]}"s"
s
s
"D"
k){-1'f:x,*1?"rps";$[f in b:("pr";"rs";"sp");"W";f in|:'b;"L";"D"]}"p"
p
s
"L"
```
[Answer]
## Javascript, 117 characters
Here's a data-driven approach to the problem. This can probably be optimized by generating the win/lose/draw data instead of mapping it manually, but it's a start :)
Golfed:
```
alert((r=[{v:"r",r:d="D",p:w="W",s:l="L"},{v:"p",r:l,p:d,s:w},{v:"s",r:w,p:l,s:d}][Math.random()*3|0]).v+r[prompt()])
```
Ungolfed:
```
//Output the result to the user
alert(
(
//Store the random computer outcome data
randomRPSData =
//Create the data for if the computer chooses r, p, or s
[
{
value: "r",
r: (d = "Draw"),
p: (w = "Win"),
s: (l = "Lose")},
{
value: "p",
r: l,
p: d,
s: w},
{
value: "s",
r: w,
p: l,
s: d}
]
//Have the computer pick a random variable
[Math.random() * 3 | 0]
//Output the value the computer chose
).value
//Output whether the user won or not
+ r[prompt()]
);
```
Finally, [here's a fiddle](http://jsfiddle.net/briguy37/NJyma/) with both.
[Answer]
Javascript: **256**
golfed:
```
i=prompt(),a=['p','r','s'];a=a[Math.floor(Math.random()*(3-1+1))+1];if(i==a){alert('d');}else if(i=='p'){if(a=='s'){alert('l');}else{alert('w');}}else if(i=='r'){if(a=='s'){alert('w');}else{alert('l');}}else if(i=='s'){if(a=='r'){alert('l');}else{alert('w')}}
```
ungolfed:
```
i=prompt(),a=['p','r','s'];
a=a[Math.floor(Math.random()*(3-1+1))+1];
if(i==a){
alert('d');
}
else if(i=='p'){
if(a=='s'){
alert('l');
}else{alert('w');}
}else if(i=='r'){
if(a=='s'){
alert('w');
}else{alert('l');}
}else if(i=='s'){
if(a=='r'){
alert('l');
}else{alert('w')}
}
```
[Answer]
Clojure:
```
(def r 0) (def s 1) (def p 2)
(def object-name #(get {'p "Paper", 's "Scissors", 'r "Rock"} %))
(def result-name #(get {\d "Draw", \w "Win", \l "Lose"} %))
(defn computer-choice [] (nth ['r 's 'p] (int (rand 3))))
(defn game [a b] (get "dwlldwwld" (+ (* 3 a) b) ))
(defn print-game [user comp result] (print (format
"User: %s\nComputer: %s\nResult: %s\n"
(object-name user) (object-name comp) (result-name result))))
(println "Enter 'p', 's' or 'r' and press return")
(let [comp (computer-choice), user (read)] (print-game user comp (game (eval user) (eval comp))))
```
Mini version (129 code characters):
```
java -jar clojure.jar -e \
"(def r 0)(def s 1)(def p 2)(let[u(read),c(nth['r 's 'p](int(rand 3)))](print c)(print (get \"dwlldwwld\"(+(* 3(eval u))(eval c)))))"
```
[Answer]
**JAVA (387)** first code golf!
```
import java.util.HashMap;public class _ {public static void main(String i[]){HashMap l = new HashMap(){{put('r',0);put('p',1);put('s',2);put(0,'T');put(1,'L');put(2,'W');}};char u =i[0].charAt(0);char c ="rps".charAt((int)(Math.random()*3)%3);int[][] m =new int[][]{{0,1,2},{2,0,1},{1,2,0}};System.out.println("U"+u+"C"+c+"R"+(Character)l.get(m[(Integer)l.get(u)][(Integer)l.get(c)]));}}
```
---
**Ungolfed**
```
import java.util.HashMap;
public class _ {
public static void main(String[] input) {
input = new String[] {"s"};
HashMap lookup = new HashMap(){{
put('r', 0);
put('p', 1);
put('s', 2);
put(0, 'T');
put(1, 'L');
put(2, 'W');
}};
char user = input[0].charAt(0);
char computer = new char[] {'r', 'p', 's'}[(int)(Math.random()*3)%3];
int[][] matrix = new int[][] {{0,1,2}, {2,0,1}, {1,2,0}};
Integer userChoice = (Integer) lookup.get(user);
Integer computerChoice = (Integer) lookup.get(computer);
Character result = (Character) lookup.get(matrix[userChoice][computerChoice]);
System.out.println("u:" + user + ",c:" + computer + ",r:" + result);
}
/*
t = 0, l = 1, w = 2
*
+---------------+
| * | r | p | s |
+---------------+
| r | 0 | 1 | 2 |
+---------------+
| p | 2 | 0 | 1 |
+---------------+
| s | 1 | 2 | 0 |
+---------------+
*/
}
```
---
**Golfed (Spacing/Indentation)**
```
import java.util.HashMap;
public class _ {
public static void main(String i[]) {
HashMap l = new HashMap(){{
put('r',0);put('p',1);put('s',2);put(0,'T');put(1,'L');put(2,'W');
}};
char u =i[0].charAt(0);char c = "rps".charAt((int)(Math.random()*3)%3);
int[][] m =new int[][]{{0,1,2},{2,0,1},{1,2,0}};
System.out.println("U"+u+"C"+c+"R:"+(Character)l.get(m[(Integer)l.get(u)][(Integer)l.get(c)]));
}}
```
---
Not the shortest code, but my first try
[Answer]
**Go (169)**
Golfed :
```
package main
import("fmt";"os")
func main(){v:=map[uint8]int{114:0,112:1,115:2}
u:=os.Args[1][0]
c:="rps"[os.Getpid()%3]
fmt.Printf("%c\n%c\n",c,"TWL"[(3+v[c]-v[u])%3])}
```
Ungolfed (as formatted by `go fmt`):
```
package main
import (
"fmt"
"os"
)
func main() {
v := map[uint8]int{114: 0, 112: 1, 115: 2}
u := os.Args[1][0]
c := "rps"[os.Getpid()%3]
fmt.Printf("%c\n%c\n", c, "TWL"[(3+v[c]-v[u])%3])
}
```
Run :
>
> go run main.go p
>
>
> s
>
>
> W
>
>
>
[Answer]
**Groovy, 89**
```
v='rps'
r=new Random().nextInt(3)
print"${v[r]}${'TLW'[((r-v.indexOf(this.args[0]))%3)]}"
```
Takes user choice as argument. Example:
```
groovy rps.groovy p
sL
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth/blob/master/pyth.py), 23
```
J"rps"K+wOJK%-XJ'KXJtK3
```
Output is in the form:
Tie: 0
Win: 1
Loss: 2
Explanation:
```
J"rps" J="rps"
K+wOJ K=input()+random_choice(J)
K print K
XJ'K index of K[0] in J
XJtK index of K[1] in J
-XJ'KXJtK difference of above indexes
%-XJ'KXJtK3 above difference mod 3
```
Run as follows:
```
$ cat rps
J"rps"K+wOJK%-XJ'KXJtK3
s
$ cat rps | python3 pyth.py
< Extraneous debug output removed>
sp
1
```
---
For only 4 more characters, we can use T for tie, W for win and L for loss:
```
J"rps"K+wOJKr@"TWL"-XJ'KXJtK
```
Everything is the same up until the difference of indexes, at which point we use the difference as the index into the string`"TWL"`.
---
Note: while I did develop this language after the challenge was posted, I had not seen the challenge until today. The challenge did not influence any aspect of the language.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes
```
“rsp”
¢i¢ṙi¢XṄ¤
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw5yi4oJHDXO5Di3KPLTo4c6ZQDLi4c6WQ0v@H25/1LTm/3@lAiUA "Jelly – Try It Online")
This returns:
* 3 if you tie
* 2 if you lose
* 1 if you win
and expects input as one of `r`, `p` or `s`
## How it works
```
“rsp” - Helper link. Return "rsp"
¢i¢ṙi¢XṄ¤ - Main link. Takes a character C on the left e.g. "r"
¢ - "rsp"
i - Get the 1-index of C in "rsp", i e.g. 1
¢ - "rsp"
ṙ - Rotate "rsp" i steps to the left e.g. "spr"
¤ - Create a nilad:
¢ - "rsp"
X - Random element, X e.g. "r", "s", "p"
Ṅ - Print
i - 1-Index of X in the rotated "rsp" e.g. 3 , 1 , 2
```
] |
[Question]
[
An \$n\times n\$ [Latin Square](https://en.wikipedia.org/wiki/Latin_square) is a grid containing exactly \$n\$ distinct values where the values in each row and column are distinct. For example,
$$\begin{matrix}
A & B & C \\
C & A & B \\
B & C & A \\
\end{matrix}$$
is a Latin square as no row or column contains a repeated value.
You are to take a positive integer \$n\$ as input and output an \$n\times n\$ Latin Square. The values can be any \$n\$ distinct values, and do not have to be consistent for different \$n\$. Your program should be consistent and deterministic, so running it with the same input should always produce the same output.
You may output in any reasonable manner, including a flat array consisting of \$n^2\$ values, or as a list of \$n\$ lists, each containing \$n\$ values. You may input and output in any [convenient method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods)
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
## Test cases
These are just some possible outputs, your program may differ so long as the output is correct
```
1 [[1]]
2 [[1, 2], [2, 1]]
3 [[1, 2, 3], [2, 3, 1], [3, 1, 2]]
4 [[1, 2, 3, 4], [2, 1, 4, 3], [3, 4, 1, 2], [4, 3, 2, 1]]
5 [[1, 2, 3, 4, 5], [2, 3, 5, 1, 4], [3, 5, 4, 2, 1], [4, 1, 2, 5, 3], [5, 4, 1, 3, 2]]
```
[Answer]
# [Python 2](https://docs.python.org/2/), 37 bytes
Outputs a flattened \$ n \times n \$ latin square.
```
lambda n:((range(n)*-~n)[1:]*n)[::~n]
```
[Try it online!](https://tio.run/##RcuxCsIwGATgPU9xYxIrWAeHH/okNUOkjf6g1xK6uPTVY0IHlzs4vlu/22vhtaThXt7x85giKNbmyOds6fx5pxt7Cb6WyM5Q0pJBKHGYvsPNiUHMGQNS/Rg0on9y6UDPGs1hzcqt8VFFTwzmWMoP "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
RṙⱮ
```
[Try it online!](https://tio.run/##y0rNyan8/z/o4c6Zjzau@3@43f3/f2MA "Jelly – Try It Online")
## Explanation
```
RṙⱮ Monadic link, takes an argument z
R [1, 2, ..., z-1, z]
Ɱ For each on right argument (z, defaults to loop over range)
ṙ Rotate the left list by the right amount
```
Alternative solution: `+þ%`. Generates the \$n\times n\$ addition table and then applies modulo to bring the elements into range.
[Answer]
# [R](https://www.r-project.org/), 30 bytes
```
n=scan();outer(1:n,1:n,`+`)%%n
```
[Try it online!](https://tio.run/##K/r/P8@2ODkxT0PTOr@0JLVIw9AqTweEE7QTNFVV8/6b/gcA "R – Try It Online")
[Answer]
# [APL (dzaima/APL)](https://github.com/dzaima/APL), 4 bytes
```
⌽ᐵ⍨⍳
```
```
⌽ rotate
ᐵ each left, apply each left element to the entire right argument
⍨ apply to both arguments
⍳ range
```
[Try it online!](https://tio.run/##SyzI0U2pSszMTfz/P@1R24RHPXsfTtj6qHfFo97NXI/6pgKF0hRM4SyT//8B "APL (dzaima/APL) – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 6 [bytes](https://github.com/abrudz/SBCS)
```
⍳⌽,⍨⍴⍳
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT////1Hv5kc9e3Ue9a541LsFyPmf9qhtwqPevkddzYfWGz9qm/iob2pwkDOQDPHwDP6fpmACAA "APL (Dyalog Unicode) – Try It Online")
There's already a nice [4-byter in dzaima/APL](https://codegolf.stackexchange.com/a/223592/78410) by rak1507, but I wanted to share a non-trivial short one in vanilla Dyalog. It is shorter than a modulo addition table `⊢|⍳∘.+⍳` and ties with the trivial port of rak's `⍳⌽¨∘⊂⍳`.
Takes n and creates a flat matrix of numbers.
```
⍳⌽,⍨⍴⍳ ⍝ Input: n
,⍨ ⍝ [n, n]
⍴⍳ ⍝ Reshape [1..n] into an n×n matrix
⍝ For n = 4, this looks like this:
⍝ 1 2 3 4
⍝ 1 2 3 4
⍝ 1 2 3 4
⍝ 1 2 3 4
⍳⌽ ⍝ Rotate first row once, second row twice, ..., n-th row n times
⍝ 2 3 4 1
⍝ 3 4 1 2
⍝ 4 1 2 3
⍝ 1 2 3 4
```
[Answer]
# [Haskell](https://www.haskell.org/), 32 bytes
```
f n=[[x..n]++[1..x-1]|x<-[1..n]]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00hzzY6ukJPLy9WWzvaUE@vQtcwtqbCRhfEzouN/Z@bmJmnYKuQm1jgq6ABJguKMvNKFPQU0jQVQIpMY/8DAA "Haskell – Try It Online")
A kind-of boring approach, just concatenates the ranges.
**34 bytes**
```
f n=[mod(k+div(-k)n)n|k<-[1..n*n]]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00hzzY6Nz9FI1s7JbNMQzdbM08zrybbRjfaUE8vTysvNvZ/bmJmnoKtQm5iga9CQVFmXomCCoijkKYAUmMa@x8A "Haskell – Try It Online")
Outputs a flat list, zero-indexed, using the method from [my Python answer](https://codegolf.stackexchange.com/a/223604/20260). A slight adaptation is needing to make it work for `[1..n*n]` instead of `[0..n*n-1]`.
[Answer]
# [J](http://jsoftware.com/), 7 bytes
```
|i.+/i.
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/azL1tPUz9f5rcqUmZ@QrpCkYQhjqurrqMCHT/wA "J – Try It Online")
Creates an "addition table" of the range 0..n with itself `i.+/i.` and then takes the mod of each element by n `|`.
[Answer]
# [Julia 1.0](http://julialang.org/), 19 bytes
```
!n=((N=1:n).+N').%n
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/XzHPVkPDz9bQKk9TT9tPXVNPNe9/SmZxQU5ipYaioaZ1QVFmXklOnoYmF1zUCKuoKVZRQwMk4f8A "Julia 1.0 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 40 bytes
```
lambda n:[(k+k/n)%n for k in range(n*n)]
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKlojWztbP09TNU8hLb9IIVshM0@hKDEvPVUjTytPM/Y/SDAPIWioY6ZpVVCUmVeikKaRp/kfAA "Python 2 – Try It Online")
Since the challenge allows a flat list of `n*n` outputs, we make do mapping `k=0, 1, ... n*n-1` to the corresponding entry with `(k+k/n)%n`. We can get this by adding the row index `k/n` and column `k%n` and reducing modulo `n`, and removing the redundant inner `%n`. We could also do `k*-~n/n%n`.
[Answer]
# [Haskell](https://www.haskell.org/), ~~37~~ 35 bytes
Saved 2 bytes thanks to @Delfad0r
Would have saved 5 bytes thanks to @AZTECCO (see [xnor's answer](https://codegolf.stackexchange.com/a/223609/95792))
```
f n=[mod(x+o)n|x<-[1..n],o<-[1..n]]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00hzzY6Nz9Fo0I7XzOvpsJGN9pQTy8vVicfxor9n5uYmadgZaXg6a@gockF5tkqFBRl5pUoqCjkJhYopCmAlJrG/gcA "Haskell – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 22 bytes
```
.+
*
Y`\_`w
L$`.
$<'$`
```
[Try it online!](https://tio.run/##K0otycxLNPz/X0@bS4srMiEmPqGcy0clQY9LxUZdJeH/fxMA "Retina – Try It Online") Explanation:
```
.+
*
```
Convert the input to unary.
```
Y`\_`w
```
Take the first `n` word characters (or use `p` for printable ASCII etc.)
```
L$`.
$<'$`
```
Create cycled rows. (`$<'` is the same as `$&$'`.)
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 21 bytes
```
@(n,x=1:n)mod(x+x',n)
```
[Try it online!](https://tio.run/##y08uSSxL/f/fQSNPp8LW0CpPMzc/RaNCu0JdJ0/zf2JesYal5n8A "Octave – Try It Online")
The same thing as many other answers...
-2 bytes by [Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe)
[Answer]
# [Arturo](https://arturo-lang.io/), 33 bytes
```
$[n][map 0..(n*n)-1'x[(x+x/n)%n]]
```
[Try it on the Arturo Playground!](http://arturo-lang.io/playground?HMWlRd) **Note: it seems that editing the code edits it for everyone, so don't do that.**
[Answer]
# [Perl 5](https://www.perl.org/) `-a`, 34 bytes
```
$,=$";say$_.."@F",1..$_-1for 1..$_
```
[Try it online!](https://tio.run/##K0gtyjH9/19Fx1ZFybo4sVIlXk9PycFNScdQT08lXtcwLb9IAcz8/9/kX35BSWZ@XvF/XV9TPQNDg/@6iQA "Perl 5 – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 23 bytes
```
+##&~Array~{#,#}~Mod~#&
```
or (as @Roman suggested)
```
Plus~Array~{#,#}~Mod~#&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277X1tZWa3OsagosbKuWllHubbONz@lTlntf0BRZl6Jgr5DerRp7P//AA "Wolfram Language (Mathematica) – Try It Online")
-2 bytes thanks to @att
[Answer]
# [jq](https://stedolan.github.io/jq/), 20 bytes
```
range(.*.)*(1+1/.)%.
```
[Try it online!](https://tio.run/##yyr8/78oMS89VUNPS09TS8NQ21BfT1NV7/9/EwA "jq – Try It Online")
output is flattened
(my first jq answer)
[Answer]
# [Python 2](https://docs.python.org/2/), 43 bytes
```
lambda x,r=range:[r(i,x)+r(i)for i in r(x)]
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaFCp8i2KDEvPdUqukgjU6dCUxtIaablFylkKmTmKRRpVGjG/i8oyswrUUjTMNTkgjGNEExjBNMEwTTV/A8A "Python 2 – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-m`](https://codegolf.meta.stackexchange.com/a/14339/), 3 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Output as a 2D array.
```
WéU
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW0&code=V%2blV&input=NAotUQ)
Or without the `-m` flag:
## [Japt](https://github.com/ETHproductions/japt), 4 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ÆZéX
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=xlrpWA&input=NAotUQ)
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~73~~ \$\cdots\$ ~~49~~ 46 bytes
Saved 3 bytes thanks to [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)!!!
```
a;f(n){for(a=n*n;a;)printf("%d ",--a*~n/n%n);}
```
[Try it online!](https://tio.run/##PY3BCoMwEETv@YolIGy0ofTSy9aPWVIigp2KWnqQ9NObBpXOZdiZt0zwYVB0OatEhlvjc2JtUUNU3Dj1WCLb6k725L3WH5xRwUnKD@3BzqyGisoTcUEJ1NJFit3oKtQ0cFu/UxtZNuR/ja9lZmuPJJlk8jfEQbs5@/cP "C (clang) – Try It Online")
Inputs \$n\$ and prints the Latin Square as a flat array consisting of \$n^2\$ values.
[Answer]
# JavaScript (ES6), 46 bytes
```
n=>[...Array(n)].map((_,i,a)=>a.map(_=>i++%n))
```
[Try it online!](https://tio.run/##LclBCoNADEDRq8ymmKDN1lUGeo4qEqzKiE0kiuDpp0Xcvc@f5ZCt97TuT7XPkEfOyvFNRC93OUGxpa@sAF2VKkGOcmXHMZXlQxFzb7rZMtBiE4xQ4/U9cAxOsyWFIhSINxv9O/8A "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), 42 bytes
As pointed out by [@tsh](https://codegolf.stackexchange.com/users/44718/tsh), returning a flatten array is shorter.
```
n=>[...Array(n*n)].map((_,i)=>(i/n+i)%n|0)
```
[Try it online!](https://tio.run/##DcvbCoJAEADQX/FFnEmbTQp8WsHvCJFlvTSiM7JKENW3b533M7un233g7TiL9kMcbRRb34moCcG9QE6CLa1uA@gKRlsDG8kZU/lcMHqVXZeBFp1ghAppVhbIkgz/5fAPMPQur0V5@5oJMf4A "JavaScript (Node.js) – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 3 bytes
```
5YL
```
[Try it online!](https://tio.run/##y00syfn/3zTS5/9/CwA "MATL – Try It Online")
```
%implicit input n
5YL % create circular matrix of size n
```
Equivalent to the following Octave/MATLAB code
# [Octave](https://www.gnu.org/software/octave/), 23 bytes
```
@(n)gallery('circul',n)
```
[Try it online!](https://tio.run/##y08uSSxL/Z@mYKugp6f330EjTzM9MScntahSQz05syi5NEddJ0/zf5qGpeZ/AA "Octave – Try It Online")
Alternately, this is equivalent to [tsh's Octave answer](https://codegolf.stackexchange.com/a/223622/67312).
# [MATL](https://github.com/lmendo/MATL), 5 bytes
```
:&+G\
```
[Try it online!](https://tio.run/##y00syfn/30pN2z3m/39TAA "MATL – Try It Online")
```
% implicit input n
: % range 1:n
&+ % add to itself transposed, with broadcast
G\ % push n and modulo n
% implicit output
```
[Answer]
# [yuno (abandoned)](https://github.com/hyper-neutrino/yuno-abandoned/), 4 [bytes](https://github.com/hyper-neutrino/yuno-abandoned/wiki/Byte-count)
```
ップア@%
```
## Explanation
```
ップ outer product table; for each (first) and for each (second)
ア add
@ swap top two
% modulo
```
Can be written as `ppua@%`. Code is grouped as `[ップ][ア][@][%]`. To prove this is actually 4 bytes, the bytecode is `'~\x00ðó'` (use the `b` flag to interpret code from bytecode).
[Answer]
# Scala, 44 bytes
```
n=>1 to n flatMap(_=>1 to n)sliding n take n
```
[Try it in Scastie!](https://scastie.scala-lang.org/EZzhiRjVQgOTdOfyHL2c5Q)
This is so simple it hardly needs an explanation, but here's one anyway:
```
n => //The input
1 to n //Make a range of n numbers
flatMap(_ => 1 to n) //Map each to the range [1, n] and flatten
//This creates a list of n*n numbers
sliding n //Take n-sized chunks and move ahead by one each time
take n //Keep the first n chunks
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes
```
LD._
```
[Try it online!](https://tio.run/##yy9OTMpM/f/fx0Uv/v9/UwA "05AB1E – Try It Online")
```
LD._ # full program
._ # push...
L # [1, 2, 3, ...,
# ..., implicit input...
L # ]...
._ # rotated to the left...
# (implicit) each element in...
LD # [1, 2, 3, ...,
# ..., implicit input...
LD # ]
# implicit output
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 7 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
o £o éX
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=byCjbyDpWA&input=NC1S)
```
o - [0..U)
£ - map by:
o éX > rotate X times [0..U)
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 61 bytes
```
param($n)(0..($n*$n-1)|%{[math]::floor($_+$_/$n)%$n})-join" "
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVPU8NATw9Ia6nk6Rpq1qhWR@cmlmTEWlml5eTnF2moxGurxOsDlamq5NVq6mblZ@YpKSj9///fCAA "PowerShell – Try It Online")
[Answer]
# [V (vim)](https://github.com/DJMcMayhem/V), ~~38~~ 30 bytes
```
"aD@aO0<ESC>V{g<C-A>V}JqqYpdw$pq@a@qdk
```
[Try it online!](https://tio.run/##K/v/XynRxSHR38DGNdjZLqw63cZZ19EurNarsDCyIKVcpaDQIdGhMCX7/39jg/@6ZQA "V (vim) – Try It Online")
Input as a single number.
Range creating script taken from Leo's [Range, Reverse, Sum](https://codegolf.stackexchange.com/a/223249/80214) answer.
-8 bytes from Leo using `J`.
Fixed the problem with multidigit numbers.
## Explanation
```
"aD@aO0<ESC>V{g<C-A>V}J
"aD delete first line and store in register a
@aO0<ESC> print 0 on a newline a times
V{g<C-A> convert the zeroes to a range
V}J select all, join with spaces
$xqqYp2x$pq@a@qdk
$x remove the last space
qq start macro q:
Yp duplicate current line
dw remove first word (number + space)
$p paste at the end
q end macro
@a@q replay macro a times
dk delete last two extra iterations
```
[Answer]
# Ruby, 33 bytes
```
->n{(0..n*n-1).map{|x|(x+x/n)%n}}
```
[Try it online!](https://tio.run/##KypNqvyfqGCr8F/XLq9aw0BPL08rT9dQUy83saC6pqJGo0K7Qj9PUzWvtvZ/gUKiXnJiTo6CMRecafofAA)
A lambda proc returning a flat array of n\*n elements.
[Answer]
# [Java (JDK)](http://jdk.java.net/), 56 bytes
```
n->{for(int i=n*n;i-->0;)System.out.println((i/n+i)%n);}
```
[Try it online!](https://tio.run/##jU09T8MwEN3zK54qIcWNYrqwYNKFiYGpI2IwblJdSM6Rfa6Eqvz24JaPhQ4Mp6d7n7092rrfvy80Tj4I@vzrJDTotSn@cF1iJ@T5LLrBxohnS4xTAUzpbSCHKFYyHD3tMWat3EkgPry8woZDVBcr8MTy6DmmsQ3omoXr7anzoSQWUMNrNlTX241Ru48o7ah9Ej3lGhm4LOmWK1I3rMy8mEtbjuIriwYbk@GhwV3GqvoZBK5UUbW6Xynzbei0da6dpKRf6krmH9pcnG9ePgE "Java (JDK) – Try It Online")
[Answer]
# Python 2, 79 bytes
```
n=input()
f=lambda b:f(b+b[-1:]+b[-n:-1])if len(b)<n*n else b
print f(range(n))
```
[Try it online!](https://tio.run/##FcWxDkAwEAbg3VPceEcMJJaGJxFDL1qa1K@hBk9f8S1fevN@oi8FU0B6Mkvlp2gPXS2p8ayNzm1nlj@YtlskeIoOrDKiBrl4O9IqXQGZPF8Wm2OIlDJ8)
] |
[Question]
[
>
> *Inspired by [this](https://chat.stackexchange.com/transcript/message/61463602#61463602) accidental misspelling*
>
>
>
If you could read the title, then you already know what the challenge is about. If not, then I'll tell you. Easy: simply take each word (single space delimited), and swap the positions of the first two letters. You may assume that the input will contain only lowercase ASCII letters and spaces and that there will be no one-letter words. You many optionally take a list of words instead of a sentence.
## Testcases
```
hello world -> ehllo owrld
this is an easy challenge -> htis si na aesy hcallenge
reverse the first two letters of each word -> erverse hte ifrst wto eltters fo aech owrd
pptx is one of ooxml format -> pptx si noe fo ooxml ofrmat
(empty) -> (empty)
```
## Leaderboard
```
/* Configuration */
var QUESTION_ID = 249523; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 107299; // This should be the user ID of the challenge author.
/* App */
var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;
function answersUrl(index) {
return "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, user: a.user, size: a.size, link: a.link};
});
var langs = [];
for (var lang in languages)
if (languages.hasOwnProperty(lang))
langs.push(languages[lang]);
langs.sort(function (a, b) {
if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1;
return 0;
});
for (var i = 0; i < langs.length; ++i)
{
var language = jQuery("#language-template").html();
var lang = langs[i];
language = language.replace("{{LANGUAGE}}", lang.lang)
.replace("{{NAME}}", lang.user)
.replace("{{SIZE}}", lang.size)
.replace("{{LINK}}", lang.link);
language = jQuery(language);
jQuery("#languages").append(language);
}
}
```
```
body {
text-align: left !important;
display: block !important;
}
#answer-list {
padding: 10px;
width: 290px;
float: left;
}
#language-list {
padding: 10px;
width: 500px;
float: left;
}
table thead {
font-weight: bold;
}
table td {
padding: 5px;
}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/all.css?v=ffb5d0584c5f">
<div id="language-list">
<h2>Shortest Solution by Language</h2>
<table class="language-list">
<thead>
<tr><td>Language</td><td>User</td><td>Score</td></tr>
</thead>
<tbody id="languages">
</tbody>
</table>
</div>
<div id="answer-list">
<h2>Leaderboard</h2>
<table class="answer-list">
<thead>
<tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
</thead>
<tbody id="answers">
</tbody>
</table>
</div>
<table style="display: none">
<tbody id="answer-template">
<tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
</tbody>
</table>
<table style="display: none">
<tbody id="language-template">
<tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
</tbody>
</table>
```
[Answer]
# x86-64 machine code, 12 bytes
```
B0 20 66 C1 07 08 AE 72 FD 74 F7 C3
```
[Try it online!](https://tio.run/##dVJha9swFPxs/YqbR6jcJqXtyijNvC/b17ERBhskKSjys60hS0ZS2pTSvz7vOVk3VjoQlnzv7t6hJz1rtB4GFTtILHIpThvrN8qiFvW1yDp/C2WnOMKRcLRLdz5UDAdv8e3z4iO@fF1gGSqznuJqT7CUEgWmRK3iRmQ/NvgL8y/hyYZdKIkiRzEXulUBtdxvx5EB8do4bbcV4V1MlfGn7ft/oGBcM2LGJXTKOFmIB5Ht9XF5fnG1novsrjWWIDmIq2U@Wd6s3Br5FLFAWeK8EBlLslqO/bKs36Z4OD6KrGf/xKKV@6R0axxB@4qu87GsvYsJWxdN46jCIXOPEvLFSlHPn0GaTSqPpx6YnF1851i6PO5PToo5fufWeFXibPfhzdj0D1lODDb3iWKxcizqZ//ryqrHYWjJWg@@bluJ1JoIXsqBVLwfmdaSa0gEuqUQCakl1CawHU8Ih5lF@Jr5usV@aH2fdqOJ5zvhgve7jt@KD51K4qeurWriMOveXvKH31TJqcn@Ag "C (gcc) – Try It Online")
Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes the address of the input, as a null-terminated byte string, in RDI, and modifies the string in place.
In assembly:
```
f:
mov al, ' ' # Set AL to the ASCII code of the space.
nextword:
rol WORD PTR [rdi], 8 # Rotate 2 bytes at the address RDI left by 8 bits.
# This swaps the current and next characters.
nextletter:
scasb # Compare AL with the current character, advancing the pointer.
jb nextletter # Jump back if AL is less than the character read.
je nextword # Jump back further if AL is equal to the character read.
ret # Return (if AL is greater than the character read).
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~7~~ ~~6~~ ~~5~~ 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
εΣN≠
```
-1 byte thanks to *@CommandMaster*
[Try it online.](https://tio.run/##NYzNDcIwDIV3yZlZWABxMMUlkdy4si1aRmALJGZgjQ7BIsEO6uX9yM8fK1wKtrZ9tvfx@3y1dkoZiTgd0sJCV3fLRd26QHVB0IfbkIEI6w09C95RFPs6dCyiFm0JEqGZnz3x2P@H/OcHfp5t3fFccR8xrxMFiWUCS@cf)
**Explanation:**
```
ε # Map over each word of the (implicit) input-list:
Σ # (Stable) sort its characters by:
N # Where the 0-based index
≠ # Is not 1
# (after which the list of modified words is output implicitly)
```
The `N≠` will make the 0-based indices of the characters in each word `[1,0,1,1,1,...]`, basically putting the second character at the front.
[Answer]
# [V (vim)](https://github.com/DJMcMayhem/V), 4 bytes
```
òxpW
```
[Try it online!](https://tio.run/##K/v///CmioLw//89UnNy8hXK84tyUhQy8ssVEotSFSrzSwE "V (vim) – Try It Online")
Explanation:
```
ò # Recursively...
x # Delete one letter
p # Paste the last deleted letter
W # Move forward one word
```
[Answer]
# [Brainfuck](https://github.com/TryItOnline/brainfuck), 30 bytes
*Thanks to [tsh](https://codegolf.stackexchange.com/users/44718/tsh) for -4 bytes.*
```
,[>,.<[.[-<++++++++>]<[,>]<],]
```
Explanation:
```
,[ loop every word
>,. print second character of word
<[ loop through next letters of word including first one
. print next letter
[-<++++++++>] multiply the letter by 8 (8*32=256; 256%256=0)
<[ check if the result is zero
,> if not then load next letter
]<
]
,]
```
Characters `@` and ``` can also be used as word separators as `8*64=512; 512%256=0` and `8*96=768; 768%256=0`.
[Attempt This Online!](https://ato.pxeger.com/run?1=m70yqSgxMy-tNDl7wYKlpSVpuhb7dKLtdPRsovWidW20ocAu1iZaB0jE6sRCFEHVLlidkZqTk69Qnl-UkwIRAgA)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
żḢF)
```
A monadic Link that takes, as allowed in the comments, a list of words and yields a list of words.
**[Try it online!](https://tio.run/##y0rNyan8///onoc7Frlp/n@4Y9Phdu///4tSy1KLilMVSjJSFdIyi4pLFErK8xVyUktKgMIK@WkKqYnJGQrl@UUpAA "Jelly – Try It Online")**
### How?
```
żḢF) - Link: list of lists of characters, words e.g. [..., "upend", ...]
) - for each word:
Ḣ - head (word) -> remove and get the first character "u"
ż - (beheaded word) zip with (head character) ["pu","e","n","d"]
F - flatten that back into to a list of characters "puend"
```
Also requires no empty words, also allowed in the comments (as `Ḣ` would yield a zero).
Note: I would say that the `F` is necessary since without this flatten a callable link would return each new word as a list of lists of characters while as a full program it would smash the characters together when it prints.
[Answer]
# JavaScript (ES6), 33 bytes
```
s=>s.replace(/\b(\S)(.)/g,'$2$1')
```
[Try it online!](https://tio.run/##hZCxbsMgEED3fsUpihSQWlvtnn5AhnbImoWSw1BhzoJTHH@9e8RdmkYJYkK8dzy@zckUm8PAL4mOOLvtXLbvpck4RGNRtYcvddhr1ei2e96s39avGz1bSoUiNpE65dTKY4wEI@V4XGkND1bbAvoK0CjA05WLfSgg2yRAUyaw3sSIqcObZnF5ltslQDJgUABvf4Frc8YT5oLAHsGFXBh4JIjILMdATuZZXysuEfWVeQE8IwRXgZEJMC6AI5kngFT8ixgGPtcISljFROc@CpB7wzcyZNQFqBGEVbwA5Crwx73bf340hXNIXXBTHSU@ff@zFfYDT7BQev4B "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python 3](https://www.python.org/), 35 bytes
*Thanks to [steffan](https://codegolf.stackexchange.com/users/92689/steffan) for -34 bytes.*
```
lambda a:[x[1::-1]+x[2:]for x in a]
```
[Try it out](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3lXMSc5NSEhUSraIrog2trHQNY7Uroo2sYtPyixQqFDLzFBJjIUr3FBRl5pVopGlEq2ek5uTkq-soqJfnF-WkqMdqakKULFgAoQE)
p.s. This is my first serious attempt at Code Golf all feedback is appreciated!
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~9~~ 8 bytes
```
{pᶠkt↔}ᵐ
```
[Try it online!](https://tio.run/##NYw9DsIwDIXvkpmJ44AY0uA2FW4cORZthViZGTgAlyj3KRcJTlCX9yM/fw1b52ekbp/zLa6f90W@j9d9XZ45H40HRDI7MxLjWV18n9Sq2KACNs1qzltECB1oZrgCJ6jrom3PSUobCwlBRM@aqK3/zv/5BR@jTBueAmwjomnAQiIerJhTPvwA "Brachylog – Try It Online")
An extremely stupid solution but shorter than my initial, more straightforward idea.
*-1 byte thanks to @UnrelatedString with an event stupider idea*
### Explanation
```
{ }ᵐ Map for each word:
pᶠ Find all permutations of the word
kt Get the penultimate one
↔ Reverse it
```
This works because `p` will always try permutations in the same order, and it happens that the penultimate one is the input in reverse order, with the last two characters swapped. It also works for 2 letter words because the penultimate permutation here will be the first one, i.e. the identity, and reversing it is the same as swapping the two characters.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 9 8 5 4 bytes
- x bytes thanks to [@Steffan](https://codegolf.stackexchange.com/users/92689/steffan)
```
ƛḣ$Y
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLGm+G4oyRZIiwiIiwiW1wicmV2ZXJzZVwiLCBcInRoZVwiLCBcImZpcnN0XCIsIFwidHdvXCIsIFwibGV0dGVyc1wiLCBcIm9mXCIsIFwiZWFjaFwiLCBcIndvcmRcIl0iXQ==) | [`S` Flag to join by spaces](https://vyxal.pythonanywhere.com/#WyJTIiwiIiwixpvhuKMkWSIsIiIsIltcInJldmVyc2VcIiwgXCJ0aGVcIiwgXCJmaXJzdFwiLCBcInR3b1wiLCBcImxldHRlcnNcIiwgXCJvZlwiLCBcImVhY2hcIiwgXCJ3b3JkXCJdIl0=)
## Explanation
```
ƛḣ$Y
ƛ Map through each word
ḣ Push all but the first letter and the first letter
$ Swap the first two elements
Y Interleave
```
[Answer]
# [Piet](https://www.dangermouse.net/esoteric/piet.html) + [ascii-piet](https://github.com/dloscutoff/ascii-piet), ~~28~~ 25 bytes (13×2=26 codels)
```
tU?QjCuJsNrMbQvQsQjIJjMmm
```
[Try Piet online!](https://piet.bubbler.one/#eJw1TFuOwzAIvArim0hxH2qaq6T9sFJSRyJ2ZNNtV6u9--J0i9AMMMP84JhujP0wtHS80uA6Ohh15Op2pM5wTyfDHTlXDYfN4Dbcf8ztm85v2nyu8pWw8Io9Nk2DhDIvNrvWyjYuI_aTl8KEc1wfalpgkQTPlOV2ifZ0iRrmAtY-AvvyDWPwIhzv_K9n_uJcGDQwTHMuCvpMIKxqZ0iTfY2hJn4C11VfNTBFrnJKr0VgSnnxir9_Yt1TIw)

−3 by switching to a vertical layout, allowing two white codels to be removed and one black codel to be implicit.
The program starts with *in(char), in(char), out(char), out(char)*, taking the first two letters from the input and outputting them in reversed order.
After that, it enters a loop:
* *in(char), duplicate, out(char)*: Read the next character from the input, and output it while leaving a copy on the stack.
* *push[3], duplicate, multiply, duplicate, multiply, push[1], add*: Create the value 82 on the stack.
* *divide*: Divide the character code by 82. This produces 1 for lowercase letters (97–122) and 0 for a space (32).
* *pointer*: Rotate the Direction Pointer clockwise by the value on the stack.
+ For lowercase letters, this sends execution rightwards and executes *subtract, out(char)*, which does nothing with the stack empty, before repeating the loop.
+ For spaces, execution continues upwards into the white area and returns to the start of the program to process the next word.
+ When the end of the input is reached, *in(char), duplicate, out(char)* does nothing and leaves the stack empty. The calculation of 82 still works, but then the *divide* does nothing because there is only one value on the stack, and the *pointer* rotates the Direction Pointer by 82, which is congruent to 2 modulo 4, sending it downwards. None of the reversed instructions are *push*es, so they all do nothing (because the stack is empty), and execution reaches the halting structure at the bottom.
[Answer]
# [Zsh](https://www.zsh.org/) `--extendedglob`, 29 bytes
```
<<<${@/(#m)??/`rev<<<$MATCH`}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjU7SSrm5qRUlqXkpqSnpOfpJS7E294tQShaLUstSi4lSFkoxUhbTMouIShZLyfIWc1JISoLBCfppCamJyhkJ5flHK0tKSNF2LvTY2NirVDvoayrma9vb6CUD9IBFfxxBnj4RaiJoFUApKAwA)
Zsh's pattern matching is pretty limited.
-1 byte thanks to @GammaFunction.
[Answer]
# [R](https://www.r-project.org), 28 bytes
```
\(x)sub("(.)(.)","\\2\\1",x)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZZDBSgQxDIbx6lOEemlhV9CTF32SwlLH1A5kJkObdWafxcso-BY-iU9javeyIwRawvf_-ZP3j7x-xsevo8T9w7e3iyvHZ2vsrdMyO-P9vfd3Zre4hvxcHaJFskVymagXaxISMcyc6UV5MM65G9g_Aaba51n71xuJpL6AVhgBQzlBlwIRjq94YZBEkdLDGCCgUqk7U1u7jG-YC4IkhNjnIiAzA6GItoGjDulSTbgJmJssCUIfq2wWBqQmi6xTVaYL_Ms_TbLU_DxitWdeBlJBHoJcTPjj6gaM1a9xHCunlsYoZXGY5OQqff62O69re38B)
Simple regex-breast, errr..., I mean... regex-based solution.
Takes input as a vector of words - this works nicely as `sub` is vectorised over the 3rd argument.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 28 bytes
```
->s{s.map{|w|(w.slice!1)+w}}
```
[Try it online!](https://tio.run/##DcjLCYAwDADQVaInRSw4gC4iHvykWKi0JNEg2tmr7/joXO5s@9wO/LA55vi8@lZq2LsVi65uNKUcwY4l4YXECLIjWEcsIBrAo8jfECzgvO6ggbbScPROpvwB "Ruby – Try It Online")
[Answer]
# [QuadR](https://github.com/abrudz/QuadRS), ~~18~~ ~~14~~ 9 bytes
```
\b\w.
⌽⍵M
```
[Try it online!](https://tio.run/##FYxBCsIwEEX3OcVf1o2gXicIoZmYwjRTJ6NtwbvHBN7q/8d7f0LU1qbnD5fpOnD@5h/@3lomZsEuytFZXio6oYBCPTHnwEzlRU7pS1oJlglp0WqwXcBk1mdI6v6cRyW6bbNjRKTQOESOlZFE12DuDw "QuadR – Try It Online")
PCRE **R**eplace:
`\b` a word boundary
`\w` any word character, and then
`.` any character
with:
`⌽⍵M` the reversed Match
[Answer]
# [APL (dzaima/APL)](https://github.com/dzaima/APL), 6 bytes
OP [seems](https://codegolf.stackexchange.com/questions/249523/erverse-hte-ifrst-wto-eltters-fo-aech-owrd?noredirect=1#comment556971_249523) to have allowed input as a list, so here goes…
```
⌽@1 2¨
```
[Try it online!](https://tio.run/##TU07DsIwDN05RTfDgAScgKtYrUMquXWVRLQwMjAgQCzcgQOwsnCUXCQkRVW7PNvP74MNL4sjlhUG5c@PefDXz3adbb6vsJj5@zNyKgNNzAIZtGK4gJF3urSR7gHrCIT2EEeukZnqHU20hvZkLEFyJVSlsS5dbUpmci6@4yaqz8n1v29a1zSuG@qkpkEs0lWcEsVU6Eb9yt/e/nICCD8 "APL (dzaima/APL) – Try It Online")
`⌽` reverse
`@` at indices
`1 2` one and two
`¨` for each word
[Answer]
# [Perl 5](https://www.perl.org/) + `-p040`, 13 bytes
Uses `-040` to work on each space separated section so that the replacement can be one off avoiding the need for `/g`, which makes it possible to use the implicit `;` from `-p` as the terminating separator.
```
s;(.)(.);$2$1
```
[Try it online!](https://tio.run/##K0gtyjH9/7/YWkNPE4isVYxUDP//z0jNyclXKM8vykn5l19QkpmfV/xft8DAxAAA "Perl 5 – Try It Online")
[Answer]
# [sed](https://www.gnu.org/software/sed/) `-r`, 17 bytes
```
s/\<(.)(.)/\2\1/g
```
[Try it online!](https://tio.run/##K05N@f@/WD/GRkNPE4j0Y4xiDPXT//8vycgsVgCixDyF1MTiSoXkjMScnNS89NR/@QUlmfl5xf91iwA "sed 4.2.2 – Try It Online")
Uses the rare 'start of word' marker `\<`.
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), ~~10~~ 8 bytes
*Edit: -2 bytes thanks to DLosc*
```
⌽⌾(2⊸↑)¨
```
[Try it at BQN REPL](https://mlochbaum.github.io/BQN/try.html#code=UmV2Rmlyc3QyIOKGkCDijL3ijL4oMuKKuOKGkSnCqAoKeCDihpAg4p+oInJldmVyc2UiLCJ0aGUiLCJmaXJzdCIsInR3byIsImxldHRlcnMiLCJvZiIsImVhY2giLCJ3b3JkIuKfqQpSZXZGaXJzdDIgeA==)
```
¨ # for each element of input
⌽ # reverse
⌾ # under
(2⊸↑) # take first 2 elements
```
The [BQN](https://mlochbaum.github.io/BQN/) 'under' modifier applies a function (here, take first 2 elements) and then applies another function on the result (here, reverse), and finally undoes the first function (so, it 'undoes' taking elements 1&2, thereby putting the result back into these positions).
Think 'operating under anaesthetic', where the anaesthetic is done before the operation and undone afterwards.
[Answer]
# [Haskell](https://www.haskell.org/), 34 bytes
```
unwords.map(\(a:b:c)->b:a:c).words
```
[Try it online!](https://tio.run/##HclBCoAgEEbhq8zSFnkAwU7S5s/GlGwKNaLTmwQPvsULKDun1A5EIUtRKme4Sr55e8tz5rXoAxepWcEsxg3jtBh09f9aqyEW6kGIUV5yASmxbPwB "Haskell – Try It Online")
[Answer]
# [Python](https://www.python.org), 48 bytes
*Thanks to user `Kalobi` for -3 bytes and `pxeger` for another -3 bytes.*
```
print(*(i[1::-1]+i[2:]for i in input().split()))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LY5BDoJADEX3c4qGFWgw4spwFcOCYHGalOlkpgiexY0Lde11vI1DMPnJb9rf197f_qZW3OMzWWKEqsYZuzzLsteofXn87n0gp_kmp1NV12XVbOl0qJteAhCQS_Kj5sUueqbkRbHuPRPhXz6-ziKzwCSBz0YtRUhqHWAbb9DZlhndBU3AK4aIoBahpxAVdBJgVE1tkD7lO7tQzsZ7nReIOFwGIvPAkH4aWjVmPfsD)
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 7 bytes
```
V`\b\w.
```
[Try it online!](https://tio.run/##FYxBDsMgDATvvMIvqNTP9JRDnWQpSA6OjBWS11OQ5rSzGoPnwu/eP99lXdqr9wQRpaYme/CUKw24ELg@tCUWQfkhGC5YBXkCxWzVyZuSwH3MpHH8tzQrezhPv2dEC6ZQvQ@hqHawhz8 "Retina – Try It Online") Link includes test cases. Explanation: A simple use of Retina's reVerse command on the first two letters of each word.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), ~~10~~ ~~7~~ 6 bytes
```
U2œ?U)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700KzUnp3LBgqWlJWm6FstDjY5Otg_VXFKclFy8-HC7N0T4pnu0UrR6UWpZalFxqrqOgnpJBphKyywqLgHzy_NBVE5qSQlQCYiZnwYiUxOTM0B0eX5RinqsUizUGgA)
-3 bytes by doing I/O as a list rather than a space-separated string, now that the OP has allowed that.
-1 thanks to @Unrelated String
Explanation:
Given a word \$ a\_n \cdots a\_3 a\_2 a\_1 \$, the permutation \$ a\_n \cdots a\_3 a\_1 a\_2 \$ is at index 2 in the list of permutations of that word.
```
) map over each word:
U reverse
2œ? index 2 into all permutations of the reversed input
U (un-)reverse
```
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), ~~38~~ 37 bytes
```
s->s.replaceAll("\\b(\\S)(.)","$2$1")
```
[Try it online!](https://tio.run/##LY6xCoMwGIR3n@InOCSggXa1Fbp06@RYO0SNbexvEky0SPHZbYpOd3DHfdeJSaTGSt0177VG4RzchNLwjQCcF17V0IUKH71C3o669spoft3NqfCD0s8ENs2hhfPq0tzxQVoUtbwgUlKWFS3LglHOSELiY3wgbM2iQLBjhYGwgyajGugDnW5z9wcI9j8Cxey87LkZPbch8ahpy4W1OFPykogGPmbAhjCWhfoSLesP "Java (OpenJDK 8) – Try It Online")
-1 thanks to @KevinCruijssen
Couldn't come up with a less boring version. The shortest other idea I had was just swapping `i+1` and `i+2` in an array where index `i` is a space, but just `toCharArray()` is 13 chars :(
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 5 bytes (10 nibbles)
```
:\<2@>2@
```
```
# implicit map over input:
: # append
\ # the reverse of
<2@ # take first 2 characters of each arg
# onto
>2@ # drop first 2 characters from each arg
```
[](https://i.stack.imgur.com/KF3gN.png)
[Answer]
# [Java (JDK)](http://jdk.java.net/), 36 bytes
```
l->l.peek(s->s[0]^=s[1]^(s[1]=s[0]))
```
[Try it online!](https://tio.run/##bVDBahsxEL37K6YLAW2xRXu144USmltOPjoOqOuRV45WEppZ20vJt6uSvS2YFCQN897Me6M5qpNaHPfvyfTBR4ZjzuXAxsqvq9knTA@uZePdf0niiKovVGsVEbwo4@D3DCAMv6xpgVhxDidv9tBnTmw4GnfY7kDFA9XXUoDnyeJxc5V7bDsVt7tmfp82oGGd7KKxMiC@C1o0tP22e1vT9vvuTZR3XYC6TqurrPYRxEnF4gXLO0eAghOs4eYhvRaZlxSsYVFBVddSG8sYxWXRfLlIQz/7wKPIeK/C9I3lkv1THu5HjGqsV5NyUdVShWBHQf/Q4heRBsuZpjsRh@datt5abFk83aKPJI/euFxwG@evzmYkxjzvwDLkdtaieq0e6LVawi0@uGpe/jqf7KbOj1m5Hyl1aK2Hs492n7gzBPkoB6hohLzp7O4OmCKeMBICdwjaRGLgsweLnFdC4HWub7uisk8h8KWIeIeF8P7S27L7XnH6Aw "Java (JDK) – Try It Online")
* Takes input as `Stream<char[]>`, and returns another `Stream<char[]>`, with each `char[]` being a word.
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 11 bytes
```
{x@>1=!#x}'
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6qucLAztFVUrqhV5+JKc1BSUIpRykjNyclXKM8vyklRyMgvV0gsSlWozC9VAgA7oA49)
[Answer]
# Knight, 78 bytes
```
;=s+" "P;=i~1;=r"";W<=i+1iLs=r+r+=gGs i 1I?g" ";=i+2i+Gs i 1Gs-i 1 1""O Gr 1Lr
```
[Try it online!](https://tio.run/##rVltU9tIEv5s/4pBKWzJlhNJcFVblmWKZIGilkAWkssH8AUhy/bUybJPkmFZQv56rrtnRhrZJne5WyplWTPP9MszPd09TtSbRtH3VzyNktU4HuTFmC9ez4ZNfSThd7WhqHhcxmugjKfT2lDB5wIzjic8jVmSsGSRTumjWY5@PP/0nrnV69XHS@ZVr38/vGT71evx@Tv2S/V6@Ym5Ffj47ErDnn8606Cfzt8fXv1m5hYz8aPFvrl/s8rZwytQKyajWZixjlUt0FFgayliOGT71dz50WecTGGSPPrK8PtgsIZBNYRBNwGTJBYCa5i3FxdnBMKPA3Kyj75phlyeCACs12y9D5NVbFnX6chqNskP2JXrUXBpHF0cm9/9IO8azPjgB/yb6weZYfifBwHvuvwsD7Ju1g2mJznjzD09mAIOYF2Pd8XQSd6DT@YaxgU7yZh7ln23QKjhCz0dUBSHcxagRr/ZBLOWYZbHpsWemg2eFoz7zQaMkok260xWaQQjtDiC92K@tPNleu2NgifHdp5BRoODOMLD08GBN29QPF@yhxkv4nwZRnGzAd@T2IRxWG4KM2xm3BQ36c3kJmNPz9cj0@q/MiwypcEnzCytDVj7VdtiQoQa3YHRmxSGu10xAnY24iSP9YFnYU40i6N/sskiY@lqfhdnubSHmTwf8ykvlFTQju64dumReHaY67Au60jLu12L9VjbaYMKtJRbLIuLVZYyFVRiGcWVv27DfZjx8C6JlRVgRLJ4iDMzAn3KEPb1K1PGRfQWERFf2pakh29xnQeuDXsUlMNr1uExleEMkHS8Wpq4pUxy2mPwtmmwSBq5kCbMuGm3K5uMttg0WAwelEYxEAJJBr6DZcswL1gxi0FYmBUAlhvQUYzihkYWeqKM1c7ei8bCp2vRRjcqMsh8DN2CL1IwGyPWGYFpkWIkXy2XSLilokqN6PTr8Qe0a2SjDBXKyxTiGBIeRq60XLDysV1mBTFwjAOY/PqY9NBMFWSUL4WrJtqNpoZJsojMfcd2LXQQh0snyMF0lSRh9qg7Wu3PpbY9H9qlZaRQrl@la6tJhYsqZFLY5unh0dt3t7/vnP168U3zWJd7x7cK9jYF79Qkn5xevSCxiDMSGaZj9q9VqF5R7L2uYm9ThWDgpF2ScbqFDFq8X19cxzxTrsxWKW6RL7N2p1jkpkqWdAIgtgseMZq9W02uvf2RtEPsdIvyQ2lAvoRzVUxMgIL/u0kyNlTioaplo5B1AXAqSgGiHgr9NdyAuXt1P9F5DMYDZhTZKjYgCMtxjEkYn4SQQnDCwNAyKhLQT/RdFi6i48vbxSKBmbs6Ay/6Wrn1I4c6P@@RbubdhpkJ2pj@pTZC0BaLJDF1U23m2FAi/geT0w2TsQy/P/xwbmMxFoEGr6fXruM4EE7gCryqt5z/GX8pGD58LUY1b5EBeLPxw6PPvcBVNR1THJZ1fNCnJx57ADg@PTvqsAlkR79RhrbUh3k4Cpd2EqfUAmhcqb5KcAbn7iUy1hdiccLahhXH5NRMQDEeEBc@VBWOk2XeiObLtR0gkvioSiFIEx@hmvyBF9HM7AAzG20YcMTkX4SFqn3Y7jPUIgABEoqNHKRhq0VOSfGylayFrOVTGa4Q1K8WGdYualmvR9ZTFWbQQVFyF4ovQXFddgYZz7Razh8T/KuQHwAJUgVH07hIoNs0W7SXLdwhrJFjnlo@n5gm7Sd2BNEsQ1tsiFPLEtscOP5WW@FhUR8g9B0JfaJ1xGwgCfGVvUiSzJ2VlW8rfwS@nHlXzeBKneIScwsYjAaIv2C5WMapqSm2jcygXgGsCuaiVEI8Bp6z/wuNy@7CFC3JBEwfo1PQw0HI2tjgARyaB3pDHaBahZcJg6wbUC@EJxaQlqQb5JAuoholdALm6U1LRWPlye/gSfwH9HF42jf83KntOl0qdjCTbQDPNsIDtCR1XjT4tw14b6v@X9t92VBuCfgyQ8pKZZxT/2xirbJUsRoO962qA91Im2rpFXWR5m6OC@uHZnMx0A49kq4XMq5lVFA1gWUoDlMp9qVSJ2ubvlMyB0kWLioW8ACJGxKSK/a9RjFrtejG1ushdCT64RvqyxvKrN3XnRzsMeHNYupIZpr5qyJXUVLGjmgKhUHd0iDKp5BXMXVjCGrbI9ruRn2bxfUX0XBBYGrPPbHn2CjToREbQCgcxmwQKC89a3tIR2GhHrI9dbsVTZb6jrIsaFttehYyl0i/ehthqUUl9vR1e8WiTrU7W1hYL@NbeOhs8CD2dRsL8y2udQgT6EJoAdQqkzJp0L6B2yCC/F6P5EmiqLSub7RgtKhliTc/JObNdmJ2f7hod/uifxCbNYfEHYPGPN1LX9IuWA9Yzy1ZJixQ78I567lwxlwd7P0kegBptIYNAoSS3r4acRTlRLQ3dCTXnkVtTScg/pvrB4ImyRW4S1AixlIE3/FqMYuzuJ2zdAG9Nk8KnrKH8BF4Y@MFXF6LeBpnsGa5SOO04CHeNuAkL9hDzGbhfQxAKQjhBZuH6QrC5/E1jqJ3d8g4UEFM5KukwF8XSHmZ8BSkp2OUyjXK9HUlZE08ynsZ6bxsSAkb1FAOXeTDBGvoI3idjpN4zG4rs29LKU/4TTRwmpLKmSEK6/XUu0XwhoR2NNOfyzw4oGBdK5CY9Gp5MahnxQOmH/6BfgxwaV/@sNdiAnDAag0lDdpMy4YowxErVWn2RB1A7E4A1UbrloZwKDG0FuNFn83jebTEMEvZ8Pbg/3Vl@Be4MlSu7GzxJZC@SFcOXmZfaN1iMk4fsBrAKxGeKqA72@ysXkr3VObRBZTmtar0h75sqw0H@kqZSsr1X/@b9TIHaWLK9X67r6Nr7fA6Nqiybn36py88qgeubjyIa9RuPWUqJAxKHAW11VqaxBWI6HbLZcLkz@Ce@HlMb0hr3jG9d5HLTuvdPUK19Qdef0@j5URcLQKtw@rqBWjzLpXKC4pdnoW9WuN7JYheE@qvlzxvW8nbs8o@wCtX79Pgf2iI0DB84lZE5SWhbIf03sgDD1Fr18UmiRoEEf9ikh6E6MqTANrH8SSEJAmeqQ6TpzDJx/RjUxgVUKbau1Ebe04csdgLt10UVtZA6AblDw7zkKfYrLIwm0Y2Ce104Pu9hT9r0T0U/5/IdMia@nXv@Xsx4zmDf2HK4jB/xOUJeDuN/w0 "C (gcc) – Try It Online")
Expanded code:
```
;= s (+" " PROMPT)
;= i ~1
;= r ""
;WHILE <(= i + 1 i) (LENGTH s)
=r + r
+ (=g (GET s i 1))
IF (?g " ")
;=i (+ 2 i)
+ ((GET s i 1)
(GET s (- i 1) 1))
""
OUTPUT (GET r 1 (LENGTH r))
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
Ḳµḣ2Uo)K
```
[Try it online!](https://tio.run/##HcwxDsIwDIXhqzxlQ2LiGswMjFFxSJEbV4lF25WFg3RlQkLqDCcpFwkJkid/ev@FmKec1@X5fq3LvDvIZp8/9@/tcczZ@KKCQSKfzBZGfZtQzgaQTRMab5kpnKlipCvFRFBPcG1MCh0ETKrlDXFl0vja@qf6XseakkDVRMaO4SR2ViubHw "Jelly – Try It Online")
## How it works
```
Ḳµḣ2Uo)K - Main link. Takes a string
Ḳ - Split by spaces
µ ) - Over each word:
ḣ2 - Take the first two characters
U - Reverse them
o - Logical Or, overwriting the first two characters of the word
K - Join with spaces
```
[Answer]
# Python 3, 51 bytes
```
lambda s:' '.join(w[1::-1]+w[2:]for w in s.split())
```
[Try it online!](https://tio.run/##VY5BCoMwEEX3PcXgRqVUsN0JPUnrItVJkzJmQjI0evo0bgrC38znzeP7TQy7W9b3Zya1vGYFcaih7j5sXZMe/TBc@vGcHtdh1BwggXUQu@jJStO22QfrpNFNZZCIIXGguWrb078XYyOUKAeo4gaTUUTo3nigAn4xRAQxCNqGKCCJgVCk1MC6/E5mtx/l3su6y9nhDjGvC0GZuSg5cOXIPw "Python 3 – Try It Online")
[Answer]
# APL+WIN, 26 bytes
Prompts for sentence
```
(⌽¨2↑¨s),¨2↓¨s←(s≠' ')⊂s←⎕
```
[Try it online! Thanks to Dyalog Classic](https://tio.run/##JYw7DsIwEER7n2I7BwkK4BRIIM5ghTWOtGQj2@LTUoSPEAIhekouQcNRfJGwCdIWb2Z2xlQ0WOwM8XKQkwmhyJt0fc6mqb6NldBkLjRU6XiwTZYun@97lOr79x16/Q4fgvKRhXR6adC9dN63WpqNdFRjlXZIxLBhTwutREdXBJAzJaAJO8idIcJyiV3qcY0@IESHYAsfIsQNA2GMYgNb6eSuXfuPVVXctmNcYhsyb1cElv3KxC7XPw "APL (Dyalog Classic) – Try It Online")
] |
[Question]
[
It's a common problem to navigate in a 2D matrix. We've seen it many times and will see again. So let's help future us and develop the shortest solutions to generate all eight possible steps in a 2D matrix.
## Challenge
Your code must output the following 8 pairs of -1,0,1 in any order:
```
(0,1)
(0,-1)
(1,0)
(-1,0)
(1,1)
(1,-1)
(-1,1)
(-1,-1)
```
## Rules
1. There is no input.
2. Output order is not relevant
3. Output is flexible. Pairs of numbers just need to be distinguishable
4. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 24 bytes
```
dec2base([0:3,5:8],3)-49
```
[Try it online!](https://tio.run/##y08uSSxL/f8/JTXZKCmxOFUj2sDKWMfUyiJWx1hT18Ty/38A "Octave – Try It Online")
I haven't seen this approach yet.
Creates a list of integers `[0, 1, 2, 3, 5, 6, 7, 8]`, and converts it to ternary, returning a character array:
```
00
01
02
10
12
20
21
22
```
Subtracting `49` (ASCII-value for `1`) from all characters gives a numeric array:
```
-1 -1
-1 0
-1 1
0 -1
0 1
1 -1
1 0
1 1
```
[Answer]
# Pure [Bash](https://www.gnu.org/software/bash/) (no external utilities), 36
```
a=({0,-1,1},{0,-1,1})
echo ${a[@]:1}
```
[Try it online!](https://tio.run/##S0oszvj/P9FWo9pAR9dQx7BWB8bQ5EpNzshXUKlOjHaItTKs/f8fAA "Bash – Try It Online")
---
# [Bash](https://www.gnu.org/software/bash/) with Sed, 35
```
printf %s\\n {-1..1},{-1..1}|sed 5d
```
[Try it online!](https://tio.run/##S0oszvj/v6AoM68kTUG1OCYmT6Fa11BPz7BWB0rXFKemKJim/P8PAA "Bash – Try It Online")
[Answer]
# T-SQL, ~~80~~ 78 bytes
```
SELECT-1n INTO t;INSERT t VALUES(0),(1)SELECT*FROM t,t z WHERE t.n<>0OR z.n<>0
```
Creates a (permanent) table **t** containing `(-1,0,1)`, and performs a self-join with a `WHERE` clause that excludes the `0,0` row. The table **t** is not cleaned up by my code, you must drop it yourself.
Sadly nearly twice as long as the boring solution (**44 bytes**), since SQL allows returns in strings:
```
PRINT'0,1
0,-1
1,0
-1,0
1,1
1,-1
-1,1
-1,-1'
```
[Answer]
# [Python 2](https://docs.python.org/2/), 33 bytes
```
i=9;exec"print-i%3-1,i/5;i-=2;"*8
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9PW0jq1IjVZqaAoM69EN1PVWNdQJ1Pf1DpT19bIWknL4v9/AA "Python 2 – Try It Online")
Dennis saved ~~3~~ 5 bytes, wow. Thanks!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~8~~ ~~7~~ 6 bytes
```
3p_2ẸƇ
```
[Try it online!](https://tio.run/##y0rNyan8/9@4IN7o4a4dx9r//wcA "Jelly – Try It Online")
My first ever Jelly answer! Much thanks to Dennis for the final piece of the puzzle.
Now, let's see if I can explain it ... lol.
```
3p_2ẸƇ Main program, takes no input.
3p Product with Range 3, yields [[1,1], [1,2], [1,3], [2,1], [2,2], ...]
_2 Decrement twice, vectorizes, yields [[-1,-1], [-1,0], [-1,1], [0,-1], ...]
ẸƇ Comb, removes those that contain only falsey values, the [0,0]
Implicit output
```
*-1 byte thanks to Erik; -1 byte thanks to Mr Xcoder and Dennis*
[Answer]
# [Haskell](https://www.haskell.org/), 22 bytes
```
_:l=mapM(:[1,-1])[0,0]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P94qxzY3scBXwyraUEfXMFYz2kDHIPZ/bmJmnm1BUWZeiULO/3/JaTmJ6cX/dZMLCgA "Haskell – Try It Online")
*Laikoni saved 1 byte.*
[Answer]
# [R](https://www.r-project.org/), ~~26~~ 24 bytes
Credits to @JDoe for saving two more bytes with a direct approach:
```
paste(-1:1,-3:5%/%3)[-5]
```
[Try it online!](https://tio.run/##K/r/vyCxuCRVQ9fQylBH19jKVFVf1VgzWtc09v9/AA "R – Try It Online")
The original asnwer:
```
outer(-1:1,-1:1,paste)[-5]
```
[Try it online!](https://tio.run/##K/r/P7@0JLVIQ9fQylAHTBQkFpekakbrmsb@/w8A "R – Try It Online")
Or for 27 bytes
```
sapply(-1:1,paste,-1:1)[-5]
```
[Try it online!](https://tio.run/##K/r/vzixoCCnUkPX0MpQpyCxuCRVB8TUjNY1jf3/HwA "R – Try It Online")
Or for 34 bytes with factors:
```
(gl(3,3,,-1:1):gl(3,1,9,-1:1))[-5]
```
[Try it online!](https://tio.run/##K/r/XyM9R8NYx1hHR9fQylDTCswz1LGEcDWjdU1j//8HAA "R – Try It Online")
This last solution might be the golfiest if the output could be from 1 to 3 rather than from -1 to 1.
See [the other R answer](https://codegolf.stackexchange.com/a/164763/80010) for alternate solutions with `expand.grid` or with `cbind`.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~13~~ ~~12~~ 11 bytes
*Saved a byte thanks to @Shaggy*
```
9ó8_ìJõ é)Å
```
[Try it online!](https://tio.run/##y0osKPn/3/LwZov4w2u8Dm9VOLxS83Dr//@6QQA "Japt – Try It Online") Uses `-R` flag to put each item on its own line.
### Explanation
```
9ó8_ìJõ é)Å
9ó8 Create the range [9, 9+8). [9, 10, ..., 16]
_ Map each item in this range through this function:
Jõ é) Generate the range [-1...1] and rotate to get [1, -1, 0].
ì Convert the item to an array of base-3 digits,
mapping [0,1,2] to [1,-1,0]. [[-1, 1, 1], [-1, 1,-1], [-1, 1, 0],
[-1,-1, 1], [-1,-1,-1], [-1,-1, 0],
[-1, 0, 1], [-1, 0,-1]]
Å Remove the first item (gets rid of the leading -1).
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) `-Q`, ~~15~~ 13 bytes
I'm sure there's a shorter way, but I liked this approach.
```
##ü80ì3 mÉ ò
##ü80 // Take 14425280
ì3 // and turn it into an array of base-3 numbers.
mÉ // Subtract one from each digit
ò // and then split them pairwise.
```
Shaved off two bytes thanks to [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy).
[Try it online!](https://ethproductions.github.io/japt/?v=2.0a0&code=I5Aj/Dgw7DMgbckg8g==&input=LVE=)
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 23 bytes
```
{(1,-1,0 X 1,-1,0)[^8]}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WsNQR9dQx0AhQgHC0IyOs4it/V@cWKmQpqFp/R8A "Perl 6 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~8~~ 7 bytes
```
2Ý<ãʒĀZ
```
[Try it online!](https://tio.run/##MzBNTDJM/f/f6PBcm8OLT0060hD1/z8A "05AB1E – Try It Online")
**Explanation**
```
2Ý< # Range of 2 decremented, yields [-1, 0, 1]
ã # Cartesian product of the list with itself
ʒ # Filter by ...
ĀZ # Maximum of the truthified values, yields 0 only if both values are 0.
```
-1 byte thanks to Emigna !
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~7~~ 6 bytes
There are a lot of different ways (the tricky/costly part is getting rid of `[0,0]`), ~~7 bytes is the shortest I could come up~~ thanks to [Leo](https://codegolf.stackexchange.com/users/62393/leo?tab=profile) for pointing out to use decimal conversion (`d`) as a filter:
```
fdπ2ṡ1
```
[Try it online!](https://tio.run/##yygtzv7/Py3lfIPRw50LDf//BwA "Husk – Try It Online")
### Explanation
```
fdπ2ṡ1 -- constant function (expects no arguments)
ṡ1 -- symmetric range [-n..n]: [-1,0,1]
π2 -- cartesian power of 2: [[-1,-1],[-1,0],[0,-1],[-1,1],[0,0],[1,-1],[0,1],[1,0],[1,1]]
f -- filter only elements that are truthy when
d -- | decimal conversion (interpret as polynomial and evaluate at x=10)
-- : [[-1,-1],[-1,0],[0,-1],[-1,1],[1,-1],[0,1],[1,0],[1,1]]
```
---
## Alternative, 7 bytes
```
tπ2ṙ1ṡ1
```
[Try it online!](https://tio.run/##yygtzv7/v@R8g9HDnTMNH@5caPj/PwA "Husk – Try It Online")
### Explanation
```
tπ2ṙ1ṡ1 -- constant function (expects no arguments)
ṡ1 -- symmetric range [-n..n]: [-1,0,1]
ṙ1 -- rotate by 1: [0,1,-1]
π2 -- cartesian power of 2: [[0,0],[0,1],[1,0],[0,-1],[1,1],[-1,0],[1,-1],[-1,1],[-1,-1]]
t -- tail: [[0,1],[1,0],[0,-1],[1,1],[-1,0],[1,-1],[-1,1],[-1,-1]]
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 12 bytes
```
9:q4X-3YA49-
```
[Try it online!](https://tio.run/##y00syfn/39Kq0CRC1zjS0cRS9/9/AA "MATL – Try It Online")
Because it's MATL month, here's a MATL port of @Stewie's Octave answer. The sequence [0 1 2 3 5 6 7 8] is generated as the set difference between [0 ... 8] and 4.
[Answer]
# Java 8, ~~83~~ 42 bytes
```
v->"1,1 1,0 1,-1 0,1 0,-1 -1,1 -1,0 -1,-1"
```
-41 bytes thanks to *@AdmBorkBork* by hard-coding..
[Try it online.](https://tio.run/##LU5BCoMwELz3FYunCEbMWdof1IvQS@lhG22JjVHMGijFt6cbFHZgd4aZnQEDyqH7RG3Re7iicb8TgHHULy/UPTTpBGhpMe4NWtwm00HIa2Y3Bo8nJKOhAQdniEFeMlUoUEXFkAqqIoEXmWiZeJmELNa7f16flv1HTEj5I9cQ@8v7A/OjwtdTP5bTSuXMCglXauFWa/OjzRb/)
---
Non hard-coded version as reference (**~~83~~ ~~72~~ ~~70~~ 68 bytes**):
```
v->{for(int i=9;i-->1;)System.out.println(~i%3+1+","+(~(i/3)%3+1));}
```
-11 bytes thanks to *@OlivierGrégoire*.
-2 bytes creating a port of [*@ETHproductions*'s JavaScript (ES6) answer](https://codegolf.stackexchange.com/a/164797/52210).
[Try it online.](https://tio.run/##LY7BCoMwDIbve4owGLS4OsTTKPoG8yLsMnboqo66WsVWYYi@ehenkBD@hPz/V4tRsLr4eKmFtXATykwHAGVc2VdClpCtEmBsVQGS3NcxUo67GRvLOuGUhAwMJOBHlk5V2xP8B5VcuWIsjTjNv9aVTdgOLux6vGlDFnWKgyg4no8BWYi6xHTVlPLZ8825G14anfeAP0CDeCR3aPF@PAXd0EwoiRm03qlm/wM)
[Answer]
# [R](https://www.r-project.org/), 27 bytes
```
expand.grid(-1:1,-1:1)[-5,]
```
[Try it online!](https://tio.run/##K/r/P7WiIDEvRS@9KDNFQ9fQylAHRGhG65rqxP7/DwA "R – Try It Online")
30 and 35 bytes:
```
cbind(-1:1,rep(-1:1,e=3))[-5,]
expand.grid(rep(list(-1:1),2))[-5,]
```
[Answer]
# JavaScript (ES6)
Two alternate methods, both longer than hardcoding.
## 49 bytes
```
_=>[...'11202200'].map((n,i,a)=>[~-n,~-a[i+3&7]])
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/e1i5aT09P3dDQyMDIyMBAPVYvN7FAQyNPJ1MnURMoWaebp1OnmxidqW2sZh4bq/k/OT@vOD8nVS8nP10jTUNT8z8A "JavaScript (Node.js) – Try It Online")
## 51 bytes
```
f=(n=1679887e3)=>n?[n%4-1,~-(n/4%4)]+' '+f(n>>4):''
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVYjz9bQzNzSwsI81VjT1i7PPjpP1UTXUKdOVyNP30TVRDNWW11BXTtNI8/OzkTTSl39f3J@XnF@TqpeTn66RpqGpuZ/AA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~28~~ 27 bytes
```
tail.mapM id$[0,1,-1]<$"ao"
```
[Try it online!](https://tio.run/##y0gszk7NyfmfZhvzvyQxM0cvN7HAVyEzRSXaQMdQR9cw1kZFKTFf6X9uYmaebUFRZl6JQtr/f8lpOYnpxf91kwsKAA "Haskell – Try It Online")
[Answer]
# [J](http://jsoftware.com/), ~~18~~ 16 bytes
```
echo}.,{;~0 1 _1
```
[Try it online!](https://tio.run/##y/r/PzU5I79WT6faus5AwVAh3vD/fwA)
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 41 bytes
```
(1..-1|%{$i=$_;1..-1|%{"$i,$_"}})-ne'0,0'
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X8NQT0/XsEa1WiXTViXeGsZTUsnUUYlXqq3V1M1LVTfQMVD//x8A "PowerShell – Try It Online")
Double-for loop over the range `1..-1`, with a `-n`ot`e`quals at the end to pull out the extraneous `0,0` entry. They're each individually left on the pipeline and implicit `Write-output` at program completion gives us newlines for free.
---
Sadly, just the barebones string output is two bytes shorter:
```
'1,1
1,0
1,-1
0,1
0,-1
-1,1
-1,0
-1,-1'
```
But that's boring.
[Answer]
# [Python 2](https://docs.python.org/2/), 39 bytes
```
n=6;exec'n+=~(n==2);print n/3,n%3-1;'*8
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P8/WzDq1IjVZPU/btk4jz9bWSNO6oCgzr0QhT99YJ0/VWNfQWl3L4v9/AA "Python 2 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 27 bytes
```
tail$(,)<$>t<*>t
t=[0,1,-1]
```
[Try it online!](https://tio.run/##y0gszk7Nyfmfm5iZp2CrUFCUmVeioKIQ878kMTNHRUNH00bFrsRGy66Eq8Q22kDHUEfXMPb//3/JaTmJ6cX/dSOcAwIA "Haskell – Try It Online")
The output is `[(0,1),(0,-1),(1,0),(1,1),(1,-1),(-1,0),(-1,1),(-1,-1)]`.
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 13 bytes
```
3,:(2m*{2b},`
```
[Try it online!](https://tio.run/##S85KzP3/31jHSsMoV6vaKKlWJ@H/fwA "CJam – Try It Online")
## Explanation
```
3, e# Range [0,3): [0 1 2]
:( e# Decrement each: [-1 0 1]
2m* e# Cartesian square: [[-1 -1] [-1 0] [-1 1] [0 -1] [0 0] [0 1] [1 -1] [1 0] [1 1]]
{ e# Filter by
2b e# conversion to binary:
}, e# [[-1 -1] [-1 0] [-1 1] [0 -1] [0 1] [1 -1] [1 0] [1 1]]
` e# Stringify: "[[-1 -1] [-1 0] [-1 1] [0 -1] [0 1] [1 -1] [1 0] [1 1]]"
```
[Answer]
# [Befunge-93](https://github.com/catseye/Befunge-93), 24 bytes
```
11#v91090~9~19~<
9.._@#,
```
[Try it online!](https://tio.run/##S0pNK81LT/3/39BQuczS0MDSoM6yztCyzobLUk8v3kFZ5/9/AA "Befunge-93 – Try It Online")
I feel like this challenge is missing answers from 2D languages, even if most don't move diagonally. This outputs space separated numbers, each pair separated by tabs.
[Answer]
# [F# (Mono)](http://www.mono-project.com/), 54 bytes
```
let f=Seq.where((<>)(0,0))(Seq.allPairs[-1..1][-1..1])
```
[Try it online!](https://tio.run/##SyvWzc3Py///Pye1RCHNNji1UK88I7UoVUPDxk5Tw0DHQFNTAySYmJMTkJhZVByta6inZxgLpTT/pynU2CmAFGSWpBYpaBQUZeaVpOUpKKk6Kmn@BwA "F# (Mono) – Try It Online")
44 bytes - thanks to Laikoni:
```
let f=Seq.tail(Seq.allPairs[0;-1;1][0;-1;1])
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes
```
Ċ{ṡᵐ≜}ᶠb
```
[Try it online!](https://tio.run/##ASEA3v9icmFjaHlsb2cy///EinvhuaHhtZDiiZx94bagYv///1o "Brachylog – Try It Online")
### Explanation
```
Ċ Couple: take a list of two elements [A,B]
{ }ᶠ Find all…
≜ …possible values of…
ṡᵐ …signs of A and B
b Behead: remove the first one which is [0,0]
```
[Answer]
## [Perl 5](https://www.perl.org/), 31 bytes
```
map/1/&&say,<{-1,0,1},{-1,0,1}>
```
[Try it online!](https://tio.run/##K0gtyjH9/z83sUDfUF9NrTixUsemWtdQx0DHsFYHxrD7//9ffkFJZn5e8X9dX1M9A0MDAA "Perl 5 – Try It Online")
[Answer]
## [Bash](https://www.gnu.org/software/bash/), 30 bytes
```
echo "
"{-1..1},{-1..1}|grep 1
```
[Try it online!](https://tio.run/##S0oszvj/PzU5I19BiUupWtdQT8@wVgdK16QXpRYoGP7/DwA "Bash – Try It Online")
Prints a trailing space on each line but the last. (Thanks to [@Neil](https://codegolf.stackexchange.com/users/17602/neil) - this originally printed a leading space, but a trailing space is better as per their comment)
[Answer]
# [MATL](https://github.com/lmendo/MATL), 12 bytes
```
3:qq2Z^[]5Y(
```
[Try it at MATL Online!](https://matl.io/?code=3%3Aqq2Z%5E%5B%5D5Y%28&inputs=&version=20.9.1)
My first ever serious MATL answer! Thanks a lot to [Luis Mendo](https://codegolf.stackexchange.com/users/36398/luis-mendo), [Sanchises](https://codegolf.stackexchange.com/users/32352/sanchises) and [DJMcMayhem](https://codegolf.stackexchange.com/users/31716/djmcmayhem) for the help.
### How it works
```
3:qq2Z^[]5Y( – Full program. Outputs to STDOUT.
3: – Range 3. Push [1 2 3] to the stack.
qq – Decrement by 2. Yields [-1 0 1].
2Z^ – Cartesian power of 2.
5Y( – Replace the row at index 5 with...
[] – An empty vector.
```
[Answer]
## Batch, 77 bytes
```
@for %%x in (-1 0 1)do @for %%y in (-1 0 1)do @if not %%x%%y==00 echo %%x %%y
```
63 bytes if a nonstandard separator is allowed:
```
@for %%x in (-1/-1 -1/0 -1/1 0/-1 0/1 1/-1 1/0 1/1)do @echo %%x
```
[Answer]
# Pyth, ~~11~~ 9 bytes
```
t^+U2_1 2
```
[Try it here](http://pyth.herokuapp.com/?code=t%5E%2BU2_1+2&debug=0)
### Explanation
```
t^+U2_1 2
+U2_1 [0, 1, -1]
^ 2 Product with itself.
t Exclude the first.
```
Equivalently, we could use `t*J+U2_1J`, but that's not any shorter.
] |
[Question]
[
A number is [whole](https://en.wikipedia.org/wiki/Natural_number) if it is a non-negative integer with no decimal part. So `0` and `8` and `233494.0` are whole, while `1.1` and `0.001` and `233494.999` are not.
---
## Input
A floating-point number in the default base/encoding of your language.
For example, the default integer representation for [Binary Lambda Calculus](//esolangs.org/wiki/Binary_lambda_calculus) would be [Church numerals](https://en.wikipedia.org/wiki/Church_encoding). But the default integer representation for [Python](//python.org) is [*base 10 decimal*](https://en.wikipedia.org/wiki/Decimal), not [Unary](https://en.wikipedia.org/wiki/Unary_numeral_system).
## Output
A [truthy](https://codegolf.meta.stackexchange.com/a/2194/60919) value if the input is whole, a [falsy](https://codegolf.meta.stackexchange.com/a/2194/60919) value if it is not.
Note that if your language only supports decimal precision to, say, 8 places, `1.000000002` can be considered whole.
Input and output may be done via any [standard I/O methods](https://codegolf.meta.stackexchange.com/q/2447/61563).
---
# Test cases
```
Input -> Output
332 -> true
33.2 -> false
128239847 -> true
0.128239847 -> false
0 -> true
0.000000000 -> true
1.111111111 -> false
-3.1415926 -> false
-3 -> false
```
---
# Scoring
As with [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest submission wins. Good luck!
[Answer]
# [Haskell](https://www.haskell.org/), ~~27~~ 16 bytes
This function checks whether `x` is contained in the list of nonnegative integers that are not greater than `x`.
```
f x=elem x[0..x]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P02hwjY1JzVXoSLaQE@vIvZ/bmJmnoKtQkFRZl6JgkaagrGeoYmhqaaCgp0dsqABEGiiiGnoGmpq/gcA "Haskell – Try It Online")
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 3 bytes
```
⌊≡|
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RHPV2POhfWADkKxsZGXCBSD0QZGlkYGVtamJgD2QZ6KDywiAEMgNTqGcIAkHdovbGeoYmhqaWRGYQHAA "APL (Dyalog Unicode) – Try It Online")
Note that `f←` has been prepended in the TIO link due to technical limitations, but it's not normally needed.
[Answer]
# Pyth, 4 bytes
```
qs.a
```
[Test suite](https://pyth.herokuapp.com/?code=qs.a&test_suite=1&test_suite_input=332%0A33.2%0A128239847%0A0.128239847%0A0%0A0.000000000%0A1.111111111%0A-3.1415926%0A-3&debug=0)
Is the number equal (`q`) to the floor (`s`) of its absolute value (`.a`)?
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~17~~ ~~15~~ 14 bytes
*Saved 1 byte thanks to Not a tree!*
```
#>=0==#~Mod~1&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2Zl@1/ZztbA1la5zjc/pc5Q7X9AUWZeSbRGtbJOWrRybK2apr5DtbGxkY6xsZ6RjqGRhZGxpYWJuY6BHhIbyDOAAR1DPUMY0NE11jM0MTS1NDIDMmtj/wMA "Wolfram Language (Mathematica) – Try It Online")
First Mathematica answer \o/
## Mathematica, 15 bytes
*Saved 2 bytes thanks to @user202729!*
```
#==⌊Abs@#⌋&
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 3 bytes
```
£ΘN
```
[Try it online!](https://tio.run/##yygtzv6vkKtR/KipsUjz0Lb/hxafm@H3//9/Y2MjLmNjPSMuQyMLI2NLCy4DPSjLxJzLAMgzgAEuQz1DGODSNdYzNDE0tTQyAzIB "Husk – Try It Online")
The third test case times out in TIO, so I chopped off a couple of digits.
I tried to run it locally, but killed it after a couple of minutes since it was using over 6GB of memory and my computer started to stutter.
It should theoretically finish at some point...
## Explanation
This corresponds to the challenge description pretty directly.
```
£ΘN Implicit input: a number.
N The infinite list [1,2,3,4...
Θ Prepend 0: [0,1,2,3,4...
£ Is the input an element of this list?
```
[Answer]
# [Python 2](https://docs.python.org/2/), 18 bytes
```
lambda n:n%1==0<=n
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKk/V0NbWwMY2739icXFqUYlCmoaxsZGmQmaxQkhRaSoXkqgeRNgtMacYSdzQyMLI2NLCxByLHgM9VFk0rQZYtRjAABZZQz1DGMBmoK6xnqGJoamlkRl2WSTRgqLMvBINJcecHIWS1OKSYoUCkLoUPSXN/wA "Python 2 – Try It Online")
[Answer]
# [///](https://esolangs.org/wiki////), 94 bytes, input hard-coded
```
/=/\/x://:/\/\///-0/-:.0/.:.|/|:-|/|:0=1=2=3=4=5=6=7=8=9=|x/|:||/true:x:/-:/.:/|/+:++/false/||
```
[Try it online!](https://tio.run/##FYw7DoAgFAQPRGDxry/Zm9BQYCyoRBOKd3fEZqeYzJYcy5VKayACqgDSGQBYDyvOw4lTqNh/PAeOnDhz4cqNOw9q7UIVz/0m6QdWegKFEWNwxlwSVFv7AA "/// – Try It Online")
Input between the two terminating vertical lines (`||`)
Strips `-00...0` and `.00...0`, converts all remaining digits to `x`s, then tests whether the remaining number still has `x`s after `.` or a `-` not followed by `.`.
Could save up to 7 bytes depending on what's counted as truthy and falsey since this language doesn't have native truthy/falsey values, currently is outputting `true` and `false` but could change to, for example, `T` and `F` for 87 bytes if that's allowed.
[Answer]
# [Python 2](https://docs.python.org/2/) and [Python 3](https://docs.python.org/3/), ~~21~~ 18 bytes
```
lambda n:n>=0==n%1
```
[Try it online! (Py2)](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKs/O1sDWNk/V8H9BUWZeiUaahrGxkaYmF4Knh8w1NLIwMra0MDFHEjPQwyqKosIABpDN0jOEASRRXWM9QxNDU0sjMxRBTc3/AA "Python 2 – Try It Online")
[Try it online! (Py3)](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPKs/O1sDWNk/V8H9BUWZeiUaahrGxkaYmF4Knh8w1NLIwMra0MDFHEjPQwyqKosIABpDN0jOEASRRXWM9QxNDU0sjMxRBTc3/AA "Python 3 – Try It Online")
3 bytes saved thanks to Mr. XCoder.
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 15 bytes
```
@(x)any(x==0:x)
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0IzMa9So8LW1sCqQvN/moaxsZECFGgqKKgqlBSVpnKBhPWMkIXTEnOKQeKGRhZGxpYWJuaoyg304BIoyg0UFLCZbqBnAAPIwoZ6hjCAYoqusZ6hiaGppZGZApo4qulg8f8A "Octave – Try It Online")
This one is based on the approach used in [@flawr's Haskell answer](https://codegolf.stackexchange.com/a/148476/42295).
While it brings the byte count down to 15, it is shamefully inefficient (no offence intended), creating a list of every integer from `0` to `x` and seeing if `x` is contained within.
---
# [Octave](https://www.gnu.org/software/octave/), 18 bytes
```
@(x)fix(x)==abs(x)
```
[Try it online!](https://tio.run/##bYxJCoAwDEX3niIbQReGJnVcFLxKFQuCIDjh7euAihX/IoH3P6@vJ7001ihEtGWwhqZd96uUrsb9WxNIyXAlBPBhGubGOzDyGxvdjQcnzlkWeZy5c4FP4cwFwJ9doLjzxoR0x7FEEimmpOAUPty1n9xu "Octave – Try It Online")
Takes input as a double precision number. Returns true if whole.
Checks if the input when rounded is equal to the magnitude of the input. This will only be the case when the number is positive and whole.
---
# [Octave](https://www.gnu.org/software/octave/), 18 bytes
```
@(x)~mod(x,+(x>0))
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0KzLjc/RaNCR1ujws5AU/N/moaxsZECFGgqKKgqlBSVpnKBhPWMkIXTEnOKQeKGRhZGxpYWJuaoyg304BIoyg0UFLCZbqBnAAPIwoZ6hjCAYoqusZ6hiaGppZGZApo4qulg8f8A "Octave – Try It Online")
An alternate solution for 18 bytes. Sadly the `mod` function in Octave won't implicitly convert a `bool` to a `double`, so the `+( )` is needed around the greater than comparison. Otherwise this solution would have been shorter.
---
# [Octave](https://www.gnu.org/software/octave/), 18 bytes
```
@(x)x>=0&~mod(x,1)
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0Kzws7WQK0uNz9Fo0LHUPN/moaxsZECFGgqKKgqlBSVpnKBhPWMkIXTEnOKQeKGRhZGxpYWJuaoyg304BIoyg0UFLCZbqBnAAPIwoZ6hjCAYoqusZ6hiaGppZGZApo4qulg8f8A "Octave – Try It Online")
And another one... ~~I can't seem to get lower than 18 bytes~~. All because of having to allow for 0 to be true with the `>=` instead of just `>`.
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), 33 bytes
```
int f(float x){return(uint)x==x;}
```
[Try it online!](https://tio.run/##PU9di4MwEHz3Vyz0xdBUNGnvzqr3R45SJCZHQGPRDciJv91bE@g87NcMw6x6vS6/Su0n61TvOw21HWecdDt879YhmNT0Y4uwsHXS6CeXejqzpWmWaguKobUuZcmaACGKnR/mnwc0sIKUgkuZCcML8XX95HlGXciSZsNzWnMCkVnxhuEXmRXX4laKj2OGrYre45TO9k8/EZC884paDWUF5zOyoIgZDszY3e9q9KSo6YcQCB/s2AKlXddH1y3U@Bt5Jtv@Dw "C++ (gcc) – Try It Online")
[Answer]
# [Aceto](https://github.com/aceto/aceto), 6 bytes
```
rfdi±=p
```
```
r grabs input
f converts it to a float
d and i duplicates it and converts it to an integer
± pushes the absolute value of it (b/c can't be negative)
= checks if they are equal
p prints out the result
```
[Try it online!](https://tio.run/##S0xOLcn//78oLSXz0Ebbgv//jfUMDMwB "Aceto – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 6 bytes
```
&gQZsI
```
[Try it online!](https://tio.run/##K6gsyfj/Xy09MKrY8/9/XWM9AwMDAA "Pyth – Try It Online")
[Answer]
# [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 17 bytes
```
?(:=int(a))*(a>0)
```
## Explanation
```
? PRINT
(:=int(a)) if the input (: assigns the cmd line param to 'a') equals itself
cast to int, -1 else 0
* times
(a>0) if the input > 0, -1 else 0
```
If either check fails, this returns 0. If both are true, it returns -1 x -1 = 1
[Answer]
# C (gcc), ~~27~~ ~~28~~ ~~27~~ 25 bytes
*-2 thanks to PrincePolka*
```
#define g(f)!fmod(f,f>=0)
```
[Try it online!](https://tio.run/##bY/fCoIwGMXvfYqlCBvocJuRUvkk3Yz90YGbkRZC9OrZivBCPZfnd873cURaCzFFxon2LhU4WT40uKmmSCptnAI11GinbSehTnR1ztBMBtUPgvcKjghcb8YNGoaxBDDW6OLCxDdHlIARHYPAQ2C5cfDRGYmCZwC85j5jFGc@tjAxXXqEFpSVRX5YxzM8wzXaSGc/rR5g8teSpAyTnOzLDf975TX5EW@hW173U9raDw)
Defines a macro "function" `g` that takes a parameter `f` (of any type). Then checks if casting `f mod 1` is zero, and if `f` is non-negative.
[Answer]
## C#, Java : 43 bytes
-1 byte thanks to Zacharý
-1 byte thanks to TheLetalCoder
```
int w(float n){return(n==(int)n&&n>=0)?1:0;}
```
C# has a special 33 bytes optimization that you can not do in java :
```
bool w(float n){return(int)n==n;}
```
### For testing
C# code :
```
class Program {
int w(float n){return(n==(int)n&&n>=0)?1:0;}
static void Main(string[] args)
{
var p = new Program();
float[] fTab = new float[]{
332,33.2f,128239847,0.128239847f,0,0.0000f,1.1111111111f,-3.1415926f,-3
};
foreach (float f in fTab) {
Console.WriteLine(string.Format("{0} = {1}", f, (p.w(f) != 0).ToString()));
}
Console.ReadKey();
}
}
```
Java Code :
```
public class MainApp {
int w(float n){return(n==(int)n&&n>=0)?1:0;}
public static void main(String[]a) {
MainApp m = new MainApp();
float testArr[] = new float[]{
332,33.2f,128239847,0.128239847f,0,0.0000f,1.1111111111f,-3.1415926f,-3
};
for (float v : testArr) {
System.out.println(v + " = " + String.valueOf(m.w(v)!=0));
}
}
}
```
[Answer]
# Google Sheets, 10 Bytes
Anonymous worksheet function that tales input from cell `A1` and outputs to the calling cell.
```
=A1=Int(A1
```
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), 24 bytes
```
f(X):-X>=0,round(X)=:=X.
```
[Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/P00jQtNKN8LO1kCnKL80LwXItbWyjdADyRgbGWnqcQFpYz0Iw9DIwsjY0sLEHMwz0EPjQ0UNYACiR88QBsB8XWM9QxNDU0sjMyhXUw8A "Prolog (SWI) – Try It Online")
[Answer]
# [Ly](https://github.com/LyricLy/Ly), ~~35~~ 47 bytes
```
ir"-"=[0u;]pr[["0"=![psp>l"."=[ppr!u;]p<2$]pp]]
```
[Try it online!](https://tio.run/##y6n8/z@zSElXyTbaoNQ6tqAoOlrJQMlWMbqguMAuR0kPKF5QUKQIkrIxUoktKIiN/f/fxMhYz8DUxAgA "Ly – Try It Online")
Ly has float support, but the only way to create a float currently is by performing division. There is no way to take a float as input, so I had to manually check the string instead.
Lost 13 bytes adding support for negative numbers.
[Answer]
# JavaScript, 14
```
n=>!(n<0||n%1)
```
[Answer]
# Perl 5, 11 +1(-p) bytes
```
$_=abs==int
```
The `-l` switch not counted because for tests display
[try it online](https://tio.run/##TccxDoAgDEDRvedwhdAWFAbOYjRxICFAhPNbXUj80/vturMTWfZ4nD3GVIYIMwGzJkDyxMHbDYz@@TszA9Q4M6BYo0UXaP341DZSLV1Uyy8)
[Answer]
# [Perl 6](https://perl6.org), ~~15~~ 13 bytes
```
{.narrow~~UInt}
```
[Test it](https://tio.run/##ZY5PT4NAEMXv@ykmTRXWwpRdKraSNl6966n2QOiSkCywsot/QugX8@YXQ6gt0vhOk99782aUKGXQVlrAW4BxSLJPuI6LvYB1W2MelWXxfjg8P@amaTvrwQhtYA0yzYW26fcXaiVTY89f9A1Y7saCbphTzCJ1X8MMt97OAdyyHYhXsExZCQsa0l976opComSUw@zYGpKkKE8H3A3Y0zRXlXFgKj6UiI3YU6gJQKqhf@9k05HvwOQXYpIZ27piXFu0rxoSKGObTkjT@j6HQV2if4z4PvIxTCKpBWF8yf3VcnE3jno4wkPUA/jf6qF31h9kyM4a7bs@sgW7XfEALuhl65H@AA "Perl 6 – Try It Online")
```
{.Int==$_>=0}
```
[Test it](https://tio.run/##ZY5PT4NAEMXv@ykmDbpgYcruVmwlNF69e6uNIXRJSBaK7GI0hE/mzS@G0D9I4ztNfu/NmyllpYKu1hI@AkxCkn/BbXLYS4i6Bp8LE0XW2yby2643nozUBiJQWSG17fx8oy5VZuzFq74D6m0o9MPCwTwuHxuY49bfuYBbtgP5DtRUtaTQkuHWS18UklLFBcyPrSFJD9X5gLcB28qKsjYuWPKzlImRewcaApBpGJ47287Ed2F2gpjmxqY3jGvqDFVjAlViOzPSdkJwGNUnhseIEMinMI2VloTxFRfr1fJhGvVxgseoD/C/1Uf/oj/IkF002fcEsiW7X/MAruh165H@Ag "Perl 6 – Try It Online")
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 14 bytes
```
n->n%1==0&n>=0
```
[Try it online!](https://tio.run/##ZZBBa4QwEIXv/oq5dFHQrNFtu9uip14LhT2WHrKaLHHdRMy4UIq/3UZTi7UDyZB8897Aq9iNRbrhqiovQ9OdallAUTNj4JVJBV8ewM@vQYa23bQs4WqZf8RWqvP7B7D2bIJpFKCyfqRDWRPRqQKlVuRFWwP@1vJSFgw5iGxQUa7uaJbFG5Vn8fA8SctpzvohN2ggs45pmoTwW9stRDlg23ELyII4IFhtuEeTfZIe9rvHcCWJyRItJfFix0oSzxX@AZTQuVZeUUrojt4fkocQ1uT/FkfGd@8yELoF3wUxxfDkwpjTBTh@GuRXojskjY0fa@ULMs744xUEzqb3xtMP3w "Java (OpenJDK 8) – Try It Online")
[Answer]
# C#, ~~40~~ ~~37~~ 29 bytes
```
bool z(float x)=>x%1==0&x>=0;
```
Saved 8 bytes thanks to @Dennis\_E!
Old Answer (37 bytes)
```
bool z(float x){return x%1==0&&x>=0;}
```
Old old answer (40 bytes):
```
bool z(float x){return (int)x==x&&x>=0;}
```
[Answer]
# JavaScript, ~~17~~ 15 bytes
```
_=>_<0?0:_==~~_
```
```
_=>_<0?0:_==(_|0)
```
Thanks to edc65 for catching my mistakes.
[Answer]
# Unexpanded Sinclair ZX81, 20 bytes
```
1 INPUT A
2 PRINT ABS A=INT A
```
20 bytes because BASIC is tokenized.
Simply will output 1 (true) if number is positive and the value of the number entered equals its integer value. Outputs 0 either of those conditions are not met.
[Answer]
## C, C++ : ~~38~~ 37 bytes
-1 byte thanks to Zacharý
-1 byte thanks to ceilingcat
```
int w(float n){return(int)n==n&n>=0;}
```
### For Testing
C : [Try it online](https://tio.run/##PU/BboMwDL33K6xMrRI1jULSdaUp3YdsPSBKViQWpmDUA@LbmYGt72A/y8/PdrH7KorxpQpF3d1KOLd4qxp1v4xVQHhwXzc5QhB9LLGLAUKWceqIsNmES6bdMOu@8ypwAf0KCMuI/7hCBj1Ya6S1yniZmKOx6XH/JrV6ci81lZpAApU84eXOqmSfvKbmMHEY3Gw@bcOF@iYCB6Qt2lE6Q@pgu8X/Myb8RNJ7ztaeVOv2MzBJh@FVTp9RFu8MY1eyE/N13pZMLM7DHP8@1m41jL8)
C Code :
```
#include <stdio.h>
int main() {
float f[] = { 332,33.2f,128239847,0.128239847f,0,0.0000f,1.1111111111f,-3.1415926f,-3 };
int t;
for ( t = 0; t < 9; ++t) {
printf("%f = %s\n", f[t], w(f[t])?"true":"false");
}
return 0;
}
```
C++ Code :
```
#include <iostream>
int main() {
std::initializer_list <std::pair<float,bool>> test{
{332.f,true}, {33.2f,false}, {128239847.f,true}, {0.128239847f,false}, {0.f,true}, {0.000000f,true}, {1.111111f,false}, {-3.1415926f,false}, {-3.f,false}
};
for (const auto& a : test) {
if (w(a.first) != a.second) {
std::cout << "Error with " << a.first << '\n';
}
}
return 0;
}
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 11 bytes
```
n=>n<0==n%1
```
[Try it online!](https://tio.run/##ZcxBDoIwEAXQPafoxqTVMrQFFYLlIsZIg4VosBCoXr9qDFjiX8zi5c@/qacaq@Ha29B0F@1q6YwszIFJaVbc5UEZxLFAc8IC2eGh3wjCx1q1ow64SEWcpcnerzLweK4yhP5XGbApP@TAp3j/YQw84dtM7NBCl6tfLWHQfasqjSMMaxIWnxvdG4rPVFNLZFF1ZuxaDW3X4GONN5pQeyIkdy8 "JavaScript (Node.js) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 7 4 bytes
Removed the unnecessary celing check after the solution of Erik The Outgolfer
```
<.=|
```
[Try it online!](https://tio.run/##RczBCoAgEATQu18xdImgFl2tVPJrIokuHbzWt1sXdWBheAN75ZgQPCT@yxuFJw@iI/Qx@B4jXo@YhDj280aE1twq1a7YsnbWrEAhSRUrtU2W1A@kSgpNmpRRs@OlCfIH "J – Try It Online")
[Answer]
# Common Lisp, ~~36~~ 32 bytes
```
(lambda(n)(=(max n 0)(floor n)))
```
[Try it online!](https://tio.run/##S87JLC74r1FQlJlXoqDxXyMnMTcpJVEjT1PDViM3sUIhT8FAUyMtJz@/SCFPU1Pzv7GeARgAmQA)
Transposition of [marmeladze’s answer](https://codegolf.stackexchange.com/a/148480/41789).
[Answer]
# [Symbolic Python](https://github.com/FTcode/Symbolic-Python), 21 bytes
```
_=_%(_==_)==(_!=_)<=_
```
**[Try it online!](https://tio.run/##K67MTcrPyUzWLagsycjP@/8/3jZeVSPe1jZe09ZWI14RSNvYxv///1/XFAA "Symbolic Python – Try It Online")**
Uses a chained comparison:
* `_%(_==_) == (_!=_)` checks if `n%1 == 0`, only true if `n` has no decimal part.
* `(_!=_) <= _` checks if `0 <= n`, only true if the integer is non-negative.
] |
[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 8 years ago.
[Improve this question](/posts/8506/edit)
This is the first of a series of C++ puzzles for you. Hope you will enjoy.
So, puzzle no.1:
Given the following program:
```
#include <iostream>
int main()
{
const int a=1;
const int b=2;
const float c=0.5;
std::cout << a/b-a*c;
}
```
Insert some code on a single new line anywhere inside the program so that the output will be 0. The new line will contain AT MOST 18 characters (including spaces), and the rest of the lines will remain unmodified.
To be clear, here is an example of a valid new code:
```
#include <iostream>
int main()
{
const int a=1;
const int b=2;
int* p = NULL;
const float c=0.5;
std::cout << a/b-a*c;
}
```
A new line with 15 characters was inserted so it's ok. However it does not solve the problem.
If this is too simple for you, don't worry, more is coming!!
[Answer]
We can get rid of a=1 by moving it into another scope:
```
#include <iostream>
main()
{
int a=0;if(0)
const int a=1;
const int b=2;
const float c=0.5;
std::cout << a/b-a*c;
}
```
This is I think 13 characters. Or better yet get a new `a` that also results in 0:
```
#include <iostream>
int main()
{
const int a=1;
const int b=2;
const float c=0.5;
if(int a=2)
std::cout << a/b-a*c;
}
```
That's 11 characters
[Answer]
```
#include <iostream>
main()
{
const int a=1;
#define a 0
const int b=2;
const float c=0.5;
std::cout << a/b-a*c;
}
```
1 new line, 12 new chars
[Answer]
So, `#define a 0`, Done. I saw that was posted - unsurprisingly.
Surprisingly, this wasn't posted:
```
#include <iostream>
main()
{
const int a=1;
const int b=2;
const float c=0.5;
std::cout<<0||
std::cout << a/b-a*c;
}
```
*14 chars*
That should do, right?
[Answer]
```
#include <iostream>
main()
{
const int a=0;//\
const int a=1;
const int b=2;
const float c=0.5;
std::cout << a/b-a*c;
}
```
17 chars.
By the way, the original program doesn't compile under MSVC, which complains that `main` doesn't have a return type.
[Answer]
```
#define int float
```
should work as well and is the same length.
[Answer]
18, including newline
```
#define float int
```
[Answer]
```
#include <iostream>
int main()
{
const int a=1;
const int b=2;
const float c=0.5;
1?std::cout<<0:
std::cout << a/b-a*c;
}
```
15 chars.
[Answer]
```
#include <iostream>
main()
{
const int a=1;
const int b=2;
const float c=0.5;
#define a 0;1
std::cout << a/b-a*c;
}
```
14 characters.
[Answer]
```
#include <iostream>
main()
{
const int a=1;
const int b=2;
const float c=0.5;
return puts("0");
std::cout << a/b-a*c;
}
```
17 chars.
[Answer]
```
#include <iostream>
main()
{
const int a=1;
const int b=2;
const float c=0.5;
std::cout<<0;//\
std::cout << a/b-a*c;
}
```
It's 17 characters so it just fits.
[Answer]
I do not know C++, however based on the question, couldn't you just input a line to simply output 0? the question specifies the output should be 0, it does not specify you must CHANGE the output to 0.
```
std::cout << 0
```
(I have 0 clue on C++, perhaps somebody can use this concept though)
[Answer]
12 chars, similar to mob's solution
```
#include <iostream>
int main()
{
const int a=1;
const int b=2;
const float c=0.5;
#define a b
std::cout << a/b-a*c;
}
```
other combinations also work, like `#define a c` or `#define c 0`
[Answer]
I know it's not [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), but I seem to be wearing that hat today!
```
#include <iostream>
int main()
{
const int a=1;
const int b=2;
const float c=0.5;
```
# --a;
```
std::cout << a/b-a*c;
}
```
five chars, including the newline;
[Answer]
c++ whatever...
```
echo "0"; exit
#include <iostream>
int main()
{
const int a=1;
const int b=2;
const float c=0.5;
std::cout << a/b-a*c;
}
```
run via:
```
sh mp.cpp
```
[Answer]
A variant on [Mr Lister's answer](/a/8513) but slightly less obvious.
```
#include <iostream>
int main()
{
const float a=1; //??/
const int a=1;
const int b=2;
const float c=0.5;
std::cout << a/b-a*c;
}
```
[Answer]
```
#include <iostream>
int main()
{
int a;if(a)
const int a=1;
const int b=2;
const float c=0.5;
std::cout << a/b-a*c;
}
```
How about these 11 chars...
[Answer]
```
#define a 0
```
<http://codepad.org/N06weGJc>
```
#include <iostream>
int main()
{
const int a=1;
const int b=2;
const float c=0.5;
#define a 0
std::cout << a/b-a*c;
}
```
] |
[Question]
[
We all know that the [Euler's number](//en.wikipedia.org/wiki/E_(mathematical_constant)), denoted by \$e\$, to the power of some variable \$x\$, can be approximated by using the [Maclaurin Series](http://mathworld.wolfram.com/MaclaurinSeries.html) expansion:
$$e^x=\sum\_{k=0}^{\infty}{\frac{x^k}{k!}}=1+x+\frac{x^2}{2!}+\frac{x^3}{3!}+\frac{x^4}{4!}+\dots$$
By letting \$x\$ equal \$1\$, we obtain
$$\sum\_{k=0}^{\infty}{\frac{1}{k!}{=\frac{1}{0!}+\frac{1}{1!}+\frac{1}{2!}+\frac{1}{3!}+\frac{1}{4!}+\dots\\=1+1+\frac{1}{2}+\frac{1}{6}+\frac{1}{24}+\dots}}$$
## Challenge
Write a program in any language which approximates Euler's number by taking in an input \$n\$ and calculates the series to the \$n\$th term. Note that the first term has denominator \$0!\$, not \$1!\$, i.e. \$n=1\$ corresponds to \$\frac{1}{0!}\$.
## Scoring
Program with least amount of bytes wins.
[Answer]
# [Wistful-C](https://github.com/Nazek42/wistful-c) - 336 bytes
My first real wistful- program! There is actually a little golfing I did, with using `someday` instead of `wait for` because the first had a shorter length.
```
if only <stdio.h> were included...
if only int f were 1...
if only int N were 0...
wish for "%d",&N upon a star
if only int i were 0...
if only double e were 0...
someday i will be N...
if only e were e+1./f...
if only i were i+1...
if only f were f*i...
*sigh*
wish "%f\n",e upon a star
if wishes were horses...
```
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
R’!İS
```
[Try it online!](http://jelly.tryitonline.net/#code=UuKAmSHEsFM&input=&args=MjA)
### How it works
```
R’!İS Main link. Argument: n
R Yield the range [1, ..., n].
’ Map decrement over the list.
! Map factorial over the list.
İ Map inverse over the list.
S Compute the sum.
```
[Answer]
## Pyth, ~~7~~ 6 bytes
```
smc1.!
```
[Try it here.](https://pyth.herokuapp.com/?code=smc1.%21&input=100&debug=0)
```
m map over range 0..input:
.! factorial
c1 1 / ^
s sum
```
Thanks to [FryAmTheEggman](https://codegolf.stackexchange.com/users/31625/fryamtheeggman) for a byte!
[Answer]
# TI-84 BASIC, 12 15 14
```
Input N
Σ(A!⁻¹,A,0,N
```
TI is a tokenized language ([bytes are counted via tokens](http://meta.codegolf.stackexchange.com/questions/1541/how-to-score-ti-basic), not individual characters).
[Answer]
# [Julia 0.6](http://julialang.org/), ~~28~~ ~~27~~ 21 bytes
```
n->sum(1./gamma(1:n))
```
[Try it online!](https://tio.run/##yyrNyUw0@59m@z9P1664NFfDUE8/PTE3N1HD0CpPU/N/Wn6RQqaCrYKhlaEBlwIQFBRl5pXk5GmkaWRqanKl5qX8BwA "Julia 0.6 – Try It Online")
This is an anonymous function that accepts an integer and returns a float. To call it, assign it to a variable.
The approach is quite straightforward. We `sum` 1 divided by the gamma function evaluated at each of 1 through *n*. This takes advantage of the property *n*! = Γ(*n*+1).
Saved 1 byte thanks to Dennis and 6 thanks to Glen O!
[Answer]
## Python, 36 bytes
**Python 2:**
```
f=lambda n,i=1:n/i and 1.+f(n,i+1)/i
```
**Python 3:**
```
f=lambda n,i=1:i<=n and 1+f(n,i+1)/i
```
[Answer]
# dc, 43 bytes
```
[d1-d1<f*]sf[dlfx1r/r1-d1<e+]se1?dk1-d1<e+p
```
This is a fairly direct translation of the series. I tried to be cleverer, but that resulted in longer code.
## Explanation
```
[d1-d1<f*]sf
```
A simple factorial function, for n>0
```
[dlfx1r/r1-d1<e+]se
```
Execute the factorial for n,...,1; invert and sum
```
1?dk1-
```
Prime the stack with 1; accept input and set an appropriate precision
```
d1<e+
```
If input was 0 or 1, we can just pass it on, else compute the partial sum.
```
p
```
Print the result.
## Test results
The first 100 expansions:
```
0
1
2
2.500
2.6666
2.70832
2.716665
2.7180553
2.71825394
2.718278766
2.7182815251
2.71828180110
2.718281826194
2.7182818282857
2.71828182844671
2.718281828458223
2.7182818284589936
2.71828182845904216
2.718281828459045062
2.7182818284590452257
2.71828182845904523484
2.718281828459045235331
2.7182818284590452353584
2.71828182845904523536012
2.718281828459045235360273
2.7182818284590452353602862
2.71828182845904523536028736
2.718281828459045235360287457
2.7182818284590452353602874700
2.71828182845904523536028747123
2.718281828459045235360287471339
2.7182818284590452353602874713514
2.71828182845904523536028747135253
2.718281828459045235360287471352649
2.7182818284590452353602874713526606
2.71828182845904523536028747135266232
2.718281828459045235360287471352662481
2.7182818284590452353602874713526624964
2.71828182845904523536028747135266249759
2.718281828459045235360287471352662497738
2.7182818284590452353602874713526624977552
2.71828182845904523536028747135266249775705
2.718281828459045235360287471352662497757231
2.7182818284590452353602874713526624977572453
2.71828182845904523536028747135266249775724691
2.718281828459045235360287471352662497757247074
2.7182818284590452353602874713526624977572470919
2.71828182845904523536028747135266249775724709352
2.718281828459045235360287471352662497757247093683
2.7182818284590452353602874713526624977572470936984
2.71828182845904523536028747135266249775724709369978
2.718281828459045235360287471352662497757247093699940
2.7182818284590452353602874713526624977572470936999574
2.71828182845904523536028747135266249775724709369995936
2.718281828459045235360287471352662497757247093699959554
2.7182818284590452353602874713526624977572470936999595729
2.71828182845904523536028747135266249775724709369995957475
2.718281828459045235360287471352662497757247093699959574944
2.7182818284590452353602874713526624977572470936999595749646
2.71828182845904523536028747135266249775724709369995957496673
2.718281828459045235360287471352662497757247093699959574966943
2.7182818284590452353602874713526624977572470936999595749669652
2.71828182845904523536028747135266249775724709369995957496696740
2.718281828459045235360287471352662497757247093699959574966967601
2.7182818284590452353602874713526624977572470936999595749669676254
2.71828182845904523536028747135266249775724709369995957496696762747
2.718281828459045235360287471352662497757247093699959574966967627699
2.7182818284590452353602874713526624977572470936999595749669676277220
2.71828182845904523536028747135266249775724709369995957496696762772386
2.718281828459045235360287471352662497757247093699959574966967627724050
2.7182818284590452353602874713526624977572470936999595749669676277240739
2.71828182845904523536028747135266249775724709369995957496696762772407632
2.718281828459045235360287471352662497757247093699959574966967627724076601
2.7182818284590452353602874713526624977572470936999595749669676277240766277
2.71828182845904523536028747135266249775724709369995957496696762772407663006
2.718281828459045235360287471352662497757247093699959574966967627724076630325
2.7182818284590452353602874713526624977572470936999595749669676277240766303508
2.71828182845904523536028747135266249775724709369995957496696762772407663035328
2.718281828459045235360287471352662497757247093699959574966967627724076630353518
2.7182818284590452353602874713526624977572470936999595749669676277240766303535449
2.71828182845904523536028747135266249775724709369995957496696762772407663035354729
2.718281828459045235360287471352662497757247093699959574966967627724076630353547565
2.7182818284590452353602874713526624977572470936999595749669676277240766303535475915
2.71828182845904523536028747135266249775724709369995957496696762772407663035354759429
2.718281828459045235360287471352662497757247093699959574966967627724076630353547594542
2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945681
2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457111
2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571352
2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713792
2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138185
2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571382143
2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821752
2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217826
2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178492
2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785218
2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852481
2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178525131
2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251635
2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516607
2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178525166394
```
Using 1000 terms:
```
2.7182818284590452353602874713526624977572470936999595749669676277240\
766303535475945713821785251664274274663919320030599218174135966290435\
729003342952605956307381323286279434907632338298807531952510190115738\
341879307021540891499348841675092447614606680822648001684774118537423\
454424371075390777449920695517027618386062613313845830007520449338265\
602976067371132007093287091274437470472306969772093101416928368190255\
151086574637721112523897844250569536967707854499699679468644549059879\
316368892300987931277361782154249992295763514822082698951936680331825\
288693984964651058209392398294887933203625094431173012381970684161403\
970198376793206832823764648042953118023287825098194558153017567173613\
320698112509961818815930416903515988885193458072738667385894228792284\
998920868058257492796104841984443634632449684875602336248270419786232\
090021609902353043699418491463140934317381436405462531520961836908887\
070167683964243781405927145635490613031072085103837505101157477041718\
986106873969655212671546889570350116
```
[Answer]
# J, 10 bytes
```
[:+/%@!@i.
```
Straight-forward approach.
## Explanation
```
[:+/%@!@i. Input: n
i. Creates the range [0, 1, ..., n-1]
!@ Maps factorial to each
%@ Map 1/x to each
[:+/ Take the sum of the values and return it
```
[Answer]
# CJam, 11
```
r~,:m!Wf#:+
```
or
```
r~{m!W#}%:+
```
Try it online: [first version](http://cjam.aditsu.net/#code=r%7E%2C%3Am!Wf%23%3A%2B&input=7) and [second version](http://cjam.aditsu.net/#code=r%7E%7Bm!W%23%7D%25%3A%2B&input=7)
**Explanation:**
`r~` = read and evaluate
`m!` = factorial
`W#` = raise to the -1 power (`W` = -1)
`:+` = sum of array
First version constructs the [0…N-1] array and applies factorial and inverse to all its elements; 2nd version does factorial and inverse for each number then puts them in an array.
[Answer]
# JavaScript ES6, ~~44 42~~ 40
```
n=>{for(k=s=m=1;m<n;s+=k/=m++);return s}
```
An unnamed function now.
Thanks for saving 2 bytes @AlexA and thanks to @LeakyNun for another 2 bytes!
[Answer]
# MATL, ~~11~~ 7 bytes
```
:Ygl_^s
```
*4 bytes saved thanks to @Luis's recommendation to use `gamma` (`Yg`)*
[**Try it Online**](http://matl.tryitonline.net/#code=OllnbF9ecw&input=MTAw)
**Explanation**
```
% Implicitly grab input (N)
: % Create an array from 1...N
Yg % Compute factorial(x-1) for each element (x) in the array
l_^ % Take the inverse
s % Sum all elements
% Implicitly display the result
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 6 bytes
```
q_t1Zh
```
This computes the sum using the [hypergeometric function](https://en.wikipedia.org/wiki/Hypergeometric_function) 1*F*1(*a*;*b*;*z*):
[](https://i.stack.imgur.com/G1aYq.gif)
Works on Octave and on the online compiler, but not on Matlab, due to [a difference](https://math.stackexchange.com/q/1822112/91216) in how the hypergeometric function is defined (which will be corrected).
[**Try it online!**](http://matl.tryitonline.net/#code=cV90MVpo&input=NQ)
### Explanation
```
q_ % Take N implicitly. Compute -N+1
t % Duplicate
1 % Push 1
Zh % Hypergeometric function 1F1(-N+1;-N+1;1). Implicitly display
```
[Answer]
# C, 249 bytes
```
#include <stdio.h>
#include <stdlib.h>
#define z double
z f(z x){z r=1;z n=1;while(x>0){r*=n;n++;x--;}return r;}int main(int argc, char **argv){z e=0;z p=0;z d=0;p=strtod(argv[1],NULL);while(p>0){e+=1.0d/f(d);printf("%.10f\n",e);p--;d++;}return 0;}
```
Ungolfed:
```
/* approximate e */
#include <stdio.h>
#include <stdlib.h>
double fact(double x){
double result = 1;
double num = 1;
while (x > 0){
result *= num;
num++;
x--;
}
return result;
}
int main(int argc, char **argv){
double e = 0;
double precision = 0;
double denom = 0;
precision = strtod(argv[1], NULL);
while (precision > 0){
e += 1.0d / fact(denom);
printf("%.10f\n", e);
precision--;
denom++;
}
return 0;
}
```
Takes a number as an argument to determine number of iterations.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 5 bytes
```
⍳⊥⊢÷!
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/x/1bn7UtfRR16LD2xX/pwGFHvX2QWS7mg@tN37UNhHICw5yBpIhHp7B/9MOrVAwVDBSMFYwUTBVMAMA "APL (Dyalog Unicode) – Try It Online")
Using the mixed base trick found in [my answer](https://codegolf.stackexchange.com/a/194817/78410) of [another challenge](https://codegolf.stackexchange.com/q/194801/78410). Uses `⎕IO←0`.
### How it works
```
⍳⊥⊢÷! Right argument: n, the number of terms
⊢÷! v: 1÷(n-1)!
⍳ B: The array of 0 .. n-1
⊥ Expand v to length-n array V,
then mixed base conversion of V in base B
Base | Digit | Value
--------------------
0 | v | v×(1×2×..×(n-1)) = 1÷0!
1 | v | v×(2×3×..×(n-1)) = 1÷1!
2 | v | v×(3×..×(n-1)) = 1÷2!
.. | .. | ..
n-2 | v | v×(n-1) = 1÷(n-2)!
n-1 | v | v = 1÷(n-1)!
```
[Answer]
# k (13 bytes)
Subject to overflows for `N>20`
```
{+/%*\1,1+!x}
```
[Answer]
## 05AB1E, 6 bytes
```
$L<!/O
```
**Explained**
```
$ # push 1 and input: N = 5
L< # range [0..N-1]: [0,1,2,3,4]
! # factorial over range [1,1,2,6,24]
/ # divide 1/range: [1.0, 1.0, 0.5, 0.16666666666666666, 0.041666666666666664]
O # sum: 2.708333333333333
```
[Try it online](http://05ab1e.tryitonline.net/#code=JEw8IS9P&input=NQ)
[Answer]
## Pyke, 10 bytes
```
FSBQi^R/)s
```
[Try it here!](http://pyke.catbus.co.uk/?code=FSBQi%5ER%2F%29s&input=2%0A10)
Or 8 bytes if power=1
```
FSB1R/)s
```
[Try it here!](http://pyke.catbus.co.uk/?code=FSB1R%2F%29s&input=10)
[Answer]
## JavaScript (ES6), 28 bytes
```
f=(n,i=1)=>n&&1+f(n-1,i+1)/i
```
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), 6 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319)
```
+/÷!⍳⎕
```
`+/` sum of
`÷` the reciprocals of
`!` the factorials of
`⍳` the numbers from 0 to
`⎕` numerical input
Assumes `⎕IO←0`, which is default on many systems.
[TryAPL](http://tryapl.org/?a=%u2395IO%u21900%20%u22C4%20%u2395PP%u219017%20%u22C4%20+/%F7%21%u237318&run)!
[Answer]
## Haskell, 37 bytes
```
((scanl(+)0$(1/)<$>scanl(*)1[1..])!!)
```
Not the shortest, but arguably the prettiest.
---
Also courtesy of [Laikoni](https://codegolf.stackexchange.com/users/56433/laikoni), here is a solution that is **2 bytes** shorter:
```
sum.(`take`((1/)<$>scanl(*)1[1..]))
```
---
```
λ> let f = ((scanl (+) 0 $ (1/) <$> scanl (*) 1 [1..]) !!)
λ> map f [1..5]
[1.0,2.0,2.5,2.6666666666666665,2.708333333333333]
λ> f 10
2.7182815255731922
λ> f 100
2.7182818284590455
λ> log (f 10)
0.9999998885745155
λ> log (f 100)
1.0
```
[Answer]
# [jq](https://stedolan.github.io/jq/), 25 bytes
```
[range(.)+1|1/tgamma]|add
```
[Try it online!](https://tio.run/##yyr8/z@6KDEvPVVDT1PbsMZQvyQ9MTc3MbYmMSXl/38zAA "jq – Try It Online")
jq currently only has IEEE754 double-precision (64-bit) floating point number support, luckily it works in its favour here.
[Answer]
# [Raku](http://raku.org/), ~~21~~ 19 bytes
```
{1+sum [\/] 1..^$_}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/2lC7uDRXITpGP1bBUE8vTiW@9n9xYqWCkkq8gq2dQnWaAlBESSEtvwgkbWjwHwA "Perl 6 – Try It Online")
*-2 bytes thanks to Jo King*
`[\/]` performs a "triangular reduction" (or "scan") using the division operator over the sequence `1, 2, ..., $_-1` (where `$_` is the argument to the function). So for example `[\/] 1..4` is the sequence `1`, `1/2`, `1/2/3`, `1/2/3/4`, which are the terms required for the `n = 5` case.
[Answer]
## Actually, 6 bytes
```
r♂!♂ìΣ
```
[Try it online!](http://actually.tryitonline.net/#code=cuKZgiHimYLDrM6j&input=Nw)
Explanation:
```
r♂!♂ìΣ
r range(N) ([0, N-1])
♂! factorial of each element
♂ì reciprocal of each element
Σ sum
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 18 bytes
```
:1-:0r:ef:$!a:/a+.
```
### Explanation
```
:1- Subtract 1 from Input
:0r Create the list [0, Input - 1]
:ef Find all integers between 0 and Input - 1
:$!a Apply factorial to each member of that list
:/a Apply inverse to each element of that list
+. Unify the output with the sum of the list
```
[Answer]
# Maple, 18
```
add(1/i!,i=0..n-1)
```
Usage:
```
> f:=n->add(1/i!,i=0..n-1);
> f(1);
1
> f(4);
8/3
```
[Answer]
# C, 69 bytes
```
double f(int n){double s=1,f=1;for(int i=0;i++<n;s+=f)f/=i;return s;}
```
[Ideone it!](http://ideone.com/MnPt3U)
[Answer]
# Java with [Ten Foot Laser Pole](https://github.com/SuperJedi224/Ten-Foot-Laser-Pole), ~~238~~ 236 bytes
```
import sj224.tflp.math.*;interface U{static void main(String[]a){BigRational r=null,s,t;r=s=t=r.ONE;for(int n=new java.util.Scanner(System.in).nextInt()-1;n-->0;){t=t.multiply(r);s=s.add(t.pow(-1));r=r.add(r.ONE);}System.out.print(s);}}
```
Has much better overflow resistance than most of the other answers. For 100 terms, the result is
```
31710869445015912176908843526535027555643447320787267779096898248431156738548305814867560678144006224158425966541000436701189187481211772088720561290395499/11665776930493019085212404857033337561339496033047702683574120486902199999153739451117682997019564785781712240103402969781398151364608000000000000000000000
```
[Answer]
# [Julia 0.6](http://julialang.org/), 28 bytes
```
~k=k<1?1:1/gamma(k+1)+~(k-1)
```
[Try it online!](https://tio.run/##yyrNyUw0@/@/Lts228bQ3tDKUD89MTc3USNb21BTu04jW9dQ839BUWZeSU6enoZenYaBlZGBpuZ/AA "Julia 0.6 – Try It Online")
## Explanation
```
~k= #Define ~ to be
k<1 #If k is less than 1
?1 #to be one
:1/gamma(k+1) #else add the reciprocal factorial to
+~(k-1) #the function applied to the predecessor value
```
`gamma(k+1)` is equal to `factorial(k)` for positive integer inputs, and generalizes it for all values other than the nonnegative integers. It saves one byte, so why not use it?
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), ~~51~~ 43 bytes
```
param($a)++$p..$a-ge1|%{$s+=$p/=$_}
$s+!!$a
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNydFNzi9K/f@/ILEoMVdDJVFTW1ulQE9PJVE3PdWwRrVapVjbVqVA31YlvpYLyFZUVEn8//@/AQA "PowerShell Core – Try It Online")
-6 bytes thanks to *mazzy*!
-2 bytes thanks to *Zaelin Goodman*!
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2) `S`, 3 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
LwỊ
```
[Try it online!](https://Not-Thonnu.github.io/run?header=&code=Lw%E1%BB%8A&footer=&input=20&flags=S)
#### Explanation
```
LwỊ # Implicit input
L # Lowered range
w # Factorial
Ị # Reciprocal
# Sum
# Implicit output
```
] |
[Question]
[
### Your task
Given a string of lowercase letters, output the "alphabet checksum" of that string, as a letter.
### Example
Let's say we have the string *"helloworld"*. With `a = 0`, `b = 1`, `c = 2` ... `z = 25`, we can replace all of the letters with numbers:
```
h e l l o w o r l d
7 4 11 11 14 22 14 17 11 3
```
Now, we can sum these:
```
7+4+11+11+14+22+14+17+11+3 = 114
```
If we mod this by 26, we get:
```
114 % 26 = 10
```
Now, using the same numbering system as before, get the 10th letter, `k`. This is our answer.
### Test cases
```
Input Output
helloworld k
abcdef p
codegolf h
stackexchange e
aaaaa a
```
**This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins.**
[Answer]
# Excel (ms365), ~~59~~, 58 bytes
-1 Thanks to [@TheThonnu](https://codegolf.stackexchange.com/users/114446/the-thonnu)
```
=CHAR(MOD(SUM(CODE(MID(A1,SEQUENCE(LEN(A1)),1))+7),26)+97)
```
[](https://i.stack.imgur.com/Cd5An.png)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 51 bytes
```
s=>(B=Buffer)([B(s).map(c=>t+=c+7,t=0)|97+t%26])+''
```
[Try it online!](https://tio.run/##Zc69DoIwFAXg3adoSAxtqmAcJA5l4DWMQ73cglK5hNafwXevEtABz/zlnHPRd@2gP3d@3VKJwajgVM4LVdyMwV7wQ8GdSK6646ByLxXIbOXVRrz2mfTL7e4oZBwHoNaRxcRSxQ2ParSWHtTbMmKMCcHSlDWLGdInKNEMgP1QN0fwOVWRndiI6jlyXkODT6h1W2E0IvybG/Jdm5p0eAM "JavaScript (Node.js) – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 10 bytes
```
2Y2j97-sQ)
```
[Try it online!](https://matl.io/?code=2Y2j97-sQ%29&inputs=helloworld&version=22.7.4) Or [verify all test cases](https://tio.run/##y00syfmf8N8o0ijL0ly3OFDzv0vI/4zUnJz88vyinBSuxKTklNQ0ruT8lNT0/Jw0ruKSxOTs1IrkjMS89FSuRBAAAA).
### Explanation
```
2Y2j97-sQ)
2Y2 % Push predefined literal: string 'abc···xyz'
% STACK: 'abc···xyz'
j % Take input as a string
% STACK: 'abc···xyz', 'helloworld'
97- % Push 97 (ASCII code of 'a'), and subtract element-wise
% STACK: 'abc···xyz', [7 4 11 11 14 22 14 17 11 3]
s % Sum
% STACK: 'abc···xyz', 114
Q) % Add 1, and use as index (1-based, modular). Implicit display
% STACK: 'k'
```
[Answer]
# [Go](https://go.dev), 68 bytes
```
func(s string)(t int){for _,r:=range s{t+=int(r)-97}
return t%26+97}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=hY9NasMwEIX3OoUQBCSSdNFF_kC7HCA3KIosOSayFGbGScH0JNmYQu_TrW8TOfHamc0wzON9791_y9T1_GLs2ZSO16aKrKovCehD-JoEuxrgqP8a8stNv_dNtBI5ElSxVJJ4FUm1PgH_WsBOg4nZBFua6_yQoJbb9Q8DRw1ETrPP1Tzfo9f_4PUESsVbhjstTi6EdEsQCsEOmUAhSlyMNOklKqUYamGOtnB-WmNT4coU3qiQcnH3bU9D8DfQYSYkY6-ue-0H)
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), ~~142~~ 126 bytes
```
,[>++++++++[-<------------>]<-[->>>>+<<<<],]>>>>>+++++[->+++++<]>+<<[>+>->+<[>]>[<+>-]<<[<]>-]>>>>++++++++[-<++++++++++++>]<+.
```
[Try it online!](https://tio.run/##TYxdCoAwDIMPtNUTlF6k9MFfFIeDgXj8Gp3Ivpe0SZuh9NuxnOPuHlXChxJTgxiTkoDAwKLJu9TTqmxPiAqBATVRxmzwEJH9D7U@NKA@dO7rnFK@cknTDQ "brainfuck – Try It Online")
Edit: -16 bytes due to common sense. Remembered I didn't have to load 97 into its own cell before adding/subtracting.
My first time golfing in brainfuck! Here's the ungolfed code for your viewing displeasure:
```
, GET EACH CHARACTER IN THE INPUT
[
>++++++++[-<------------>]<- SUBTRACT 97 (8 TIMES 12 PLUS 1) FROM CELL 0
[->>>>+<<<<] ADD CELL 0 TO CELL 4
, INPUT TO CELL 0
]
>>>> GO TO CELL 4
>+++++[->+++++<]>+<< LOAD 26 (5 TIMES 5 PLUS 1) INTO CELL 6
[>+>->+<[>]>[<+>-]<<[<]>-] TAKE CELL 4 MOD CELL 6
>>> GO TO RESULT IN CELL 7
>++++++++[-<++++++++++++>]<+ ADD 97 (8 TIMES 12 PLUS 1) TO CELL 7
. DISPLAY
```
[Answer]
# [R](https://www.r-project.org/) v4.2.0, 63 59
*-4 thanks to Dominic van Essen*
```
\(x,l=letters)l[(sum(match(el(strsplit(x,"")),l)-1)%%26)+1]
```
The input string `x` is parsed as characters, and `match` is used to retrieve the index of each character in the `letters` builtin, minus one to convert from 1-based to 0-based.
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), ~~16~~ 15 bytes
```
⟨c97%⟩¦Σ26%97+c
```
[Try it online!](https://tio.run/##S0/MTPz//9H8FcmW5qqP5q88tOzcYiMzVUtz7eT//4tLEpOzUyuSMxLz0lMB "Gaia – Try It Online")
Pretty standard implementation of what the challenge asks.
I was able to save a byte thanks to the golfing advice given by
Dominic van Essen!
## Explained
```
⟨c97%⟩¦Σ26%97+c
⟨ ⟩¦ # To each letter in the input {
c97% # modulo the character code by 96
# }
Σ26% # Get the sum of that list and modulo 26
97+c # and add 97 to turn it back into an ascii letter
```
[Answer]
# Mathematica, ~~60~~ 48 bytes
```
FromLetterNumber[Tr[LetterNumber@#-1]~Mod~26+1]&
```
[View it on Wolfram Cloud!](https://www.wolframcloud.com/obj/ec33c9bc-7802-4cb5-ace8-cd76d01dae4e)
*-12 bytes thanks to [JSorngard](https://codegolf.stackexchange.com/users/88906/jsorngard)!*
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ADIkOè
```
Input as a list of characters.
[Try it online](https://tio.run/##yy9OTMpM/f/f0cUz2//wiv//o5UylHSUUoE4B4rzgbgcShdBxVKUYgE) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVw6H9Hl4hs/8Mr/uv8j1bKSM3JyS/PL8pJUdJRSkxKTklNAzKS81NS0/NzQMziksTk7NSK5IzEvPRUkBoQUIoFAA).
**Explanation:**
```
A # Push the lowercase alphabet
D # Duplicate it
I # Push the input-list
k # Get the index of each character in the (top) alphabet
O # Sum these together
è # (Modular 0-based) index it into the alphabet
# (after which this character is output as result)
```
[Answer]
# [Factor](https://factorcode.org/) + `math.unicode`, ~~25~~ 24 bytes
```
[ 7 v+n Σ 26 mod 97 + ]
```
-1 byte thanks to some black magic from Arnauld!
[Try it online!](https://tio.run/##JYtBDoIwFET3nGJC4orEhQuJegDjxo1xhSzq7y8lQgttARPjabyPV6qis5iXSd4oQcG6eD4djvstlHWtCKE2Fb7Uv1oOpiYr@T9Gnn2PfoLnfmBD7LFLkn56QHPT2Mm6RkJcSbLC/Ktso@CDoBvfSQtTMcQcPGOBHGNm8H5htUZrJTY5MpSxFR0KpAu6mBSdq01QKMGCdPwA "Factor – Try It Online")
```
! "helloworld"
7 ! "helloworld" 7
v+n ! { 111 108 115 115 118 126 118 121 115 107 }
Σ ! 1154
26 ! 1154 26
mod ! 10
97 ! 10 97
+ ! 107
```
[Answer]
# [Python 3](https://docs.python.org/3/), 43 bytes
-1 byte from @Arnauld
```
lambda s:chr(sum(ord(c)+7for c in s)%26+97)
```
[Try it online!](https://tio.run/##BcFBCoAgEADAr3gJd/FWkBT0ky6miYK6shrR622mfj1QWYY/zpFMvpwRbbeBoT0ZiB1YVNoTCytiEQ2neVWbxlE5lg4eZLhTopc4OYk4fg "Python 3 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
O+7S‘ịØa
```
A monadic Link that accepts a list of characters and yields a character.
**[Try it online!](https://tio.run/##y0rNyan8/99f2zz4UcOMh7u7D89I/P//f3J@Smp6fk4aAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/99f2zz4UcOMh7u7D89I/P9w95bD7Y@a1kT@/58BlM8vzy/KSeFKTEpOSU3jSs5PSU3Pz0njKi5JTM5OrUjOSMxLT@VKBAEA "Jelly – Try It Online").
### How?
```
O+7S‘ịØa - Link: list of characters, Message
O - ordinals (Message)
+7 - add seven (vectorises)
S - sum
‘ - increment
Øa - "abc...xyz"
ị - index into (1-based and modular)
```
[Answer]
# [jq](https://stedolan.github.io/jq/), 37 bytes
```
explode|map(.-97)|[add%26+97]|implode
```
[Try it online!](https://tio.run/##yyr8/z@1oiAnPyW1JjexQENP19JcsyY6MSVF1chM29I8tiYzFyz7/39Gak5Ofnl@UU4KV2JSckpqGlcyUDw9PyeNq7gkMTk7tSI5IzEvPZUrEQT@5ReUZObnFf/XDQIA "jq – Try It Online")
[Answer]
# [Raku](https://raku.org/), 27 bytes
```
{chr sum(.ords X-97)%26+97}
```
[Try it online!](https://tio.run/##FcHRCoJAEAXQX7mIRhH10IMipN/Rm6y7My40NjFblIjfvtE5TzKp87xgx@jy6qMhvef9WS0k3E5tc6gu9bFttpzcgqIc0PVYGeWwFWA1XCOJ6EdNAtzoAzG8BppUGOnl/J2@PrrHRHB/ff4B "Perl 6 – Try It Online")
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 7 bytes (14 nibbles)
```
+%+.$-$;'a'26
```
```
. # map over
$ # the input:
- # subtract
'a' # the letter 'a'
; # (and save it)
$ # from each letter
# (which gives its 0-based index)
+ # now sum this list
% 26 # apply modulo-26
+ # and add back the saved letter 'a'
```
[](https://i.stack.imgur.com/YvD1C.png)
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~16~~ 14 bytes
```
`c$97+26!+/97!
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs0pIVrE01zYyU9TWtzRX5OJKi1bKSM3JyS/PL8pJUYoF8ROTklNS0yDs5PyU1PT8HCivuCQxOTu1IjkjMS89FaoYBJRiAZ5hG88=)
*-2 bytes thanks to coltim!*
Explanation:
```
`c$97+26!+/97! Main function. Takes implicit input
97! Modulo by 97 to each character in the string
to convert them into the 0..25 system
(In K, every character in a string is also an ASCII charcode)
+/ Sum
26! Modulo by 26
97+ + 97 to each of them to convert them back to ASCII charcode
`c$ And convert them back to characters
```
[Answer]
# [Julia 1.0](http://julialang.org/), ~~36~~ 26 bytes
```
!s=sum([s...].-'a')%26+'a'
```
[Try it online!](https://tio.run/##HY1BDoIwEEX3nGKYYGwjNtGFO05CXNR2gEptCQORePlaeJv/Fi/579U7fdtSKrnh9SNaVko91fWsz/J0f1zypi7OILgGLcEF@LlJCBzI@/iNs7dYA@qXsdTtZqKlPvrDedFmpM0MOvR0ZDso6xbHaSCN@5UsIDPNLiw@CKwYKlGyhNyXDE2TXwsKNv0B "Julia 1.0 – Try It Online")
-10 MarcMush
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~33~~ 32 bytes
-1 byte thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)
```
->a{(a.sum{_1.ord+7}%26+97).chr}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3FXTtEqs1EvWKS3Or4w318otStM1rVY3MtC3NNfWSM4pqIer2F5SWFCu4RauWR2copCrkAGG-QjkQFwFZKbGxEFULFkBoAA)
[Answer]
# [simply](https://github.com/ismael-miguel/simply), 76 bytes
It is a pretty long one...
Creates an anonymous function that outputs the expected result.
```
fn($S){$X=0each$S as$C;$X=&add($X&sub(&ord($C)97))out!ABCL[$_=&mod($X,26)];}
```
Yes, that's right, I'm assigning the result of `&mod` into a variable.
Without it, it gives a syntax error, because ... I made mistakes in the compiler...
# Using the code
Simply call the function.
```
$fn = fn($S){$X=0each$S as$C;$X=&add($X&sub(&ord($C)97))out!ABCL[$_=&mod($X,26)];}
// should output "h"
call $fn("codegolf");
```
# Ungolfed
Somewhat code-y looking:
```
$fn = fn($string) => {
$sum = 0;
each $string as $char {
$sum = &add($sum, &sub(&ord($char), 97));
}
$index = call &mod($sum, 26);
echo !ABCL[$index];
}
```
Plain English-ish/Pseudo-code looking:
```
Set $fn to an anonymous function($string).
Begin.
Set $sum to 0.
Loop through $string as $char.
Begin.
Set $sum to the result of calling the function &add(
$sum,
Call the function &sub(
Call the function &ord($char),
97
)
).
End.
Set $index to the result of calling the function &mod($sum, 26).
Show the value !ABCL[$index].
End.
```
Both versions do exactly the same.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
;x!aC gC
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=O3ghYUMgZ0M&input=WwpbImgiLCJlIiwibCIsImwiLCJvIiwidyIsIm8iLCJyIiwibCIsImQiXQpbImEiLCJiIiwiYyIsImQiLCJlIiwiZiJdClsiYyIsIm8iLCJkIiwiZSIsImciLCJvIiwibCIsImYiXQpbInMiLCJ0IiwiYSIsImMiLCJrIiwiZSIsIngiLCJjIiwiaCIsImEiLCJuIiwiZyIsImUiXQpbImEiLCJhIiwiYSIsImEiLCJhIl0KXS1tUg)
Input as an array of characters.
Explanation:
```
;x!aC gC
; # C = "abcdefghijklmnopqrstuvwxyz"
x # Compute the following for each character, then sum the results:
!aC # Find its index in C
gC # Get the character at that index in C (wrapping)
```
You can also rearrange things [like this](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=O0NnVXghYUM&input=WwpbImgiLCJlIiwibCIsImwiLCJvIiwidyIsIm8iLCJyIiwibCIsImQiXQpbImEiLCJiIiwiYyIsImQiLCJlIiwiZiJdClsiYyIsIm8iLCJkIiwiZSIsImciLCJvIiwibCIsImYiXQpbInMiLCJ0IiwiYSIsImMiLCJrIiwiZSIsIngiLCJjIiwiaCIsImEiLCJuIiwiZyIsImUiXQpbImEiLCJhIiwiYSIsImEiLCJhIl0KXS1tUg) for a different 8 byte solution which works almost exactly the same way.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 14 bytes
```
ạ+₇ᵐ+%₂₆+₉₇g~ạ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@GuhdqPmtofbp2grfqoqelRUxuQ2wkUSa8DSv3/r5QEU6z0PwoA "Brachylog – Try It Online")
### Explanation
```
ạ String to char codes
+₇ᵐ Add 7 to each code (a <-> 97 becomes 104 = 0 (mod 26))
+ Sum
%₂₆ Mod 26
+₉₇ Add 97
g Wrap into a list
~ạ Char code to string
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes
```
øA‹∑₄%›øA
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLDuEHigLniiJHigoQl4oC6w7hBIiwiIiwic3RhY2tleGNoYW5nZSJd)
```
øA‹∑₄%›øA
øA Letter to number (1-indexed)
‹ Decrement each value in list
∑ Sum it up
₄%› Modulo by 26 and increment
øA Number to letter
```
[Answer]
# [Pushy](https://github.com/FTcode/Pushy), 7 bytes
```
L7*SvOq
```
[Try it online!](https://tio.run/##Kygtzqj8/9/HXCu4zL/w////SsUlicnZqRXJGYl56alKAA "Pushy – Try It Online")
```
The input is implicitly converted into bytecodes on the stack.
L7* Push the length of the input, times 7.
S Push the sum of the stack.
vO Send this to the 'output stack'.
q Index into the ASCII lowercase alphabet (mod 26) and print the result.
```
Pushing 7 times the length comes from the fact that `a` has bytecode 97, and \$ -97 \equiv 7 \ (\text{mod} \, 3) \$. So it's equivalent to subtracting 97 from each bytecode.
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 132 bytes
```
interface T{static void main(String[]a){int i=a[0].length(),s=0;for(;i-->0;s+=a[0].charAt(i)+7);System.out.print((char)(97+s%26));}}
```
[Try it online!](https://tio.run/##JczRCoIwFIDhV9lNcIYp0kUSo6BnsDvx4qBTj81NtpMR4rMvo@vv5x9xwdTN2o7tM0ayrH2HjRaPNTAyNWJx1IoJyULJnmxf1SjXvRN0xSqvM6NtzwPIY7jmqnMeFKXpLVch@XszoL8zkEwKqcpPYD1l7sXZvM8Y4McSLkUSDqezlGrbYoyDNsa9nTftFw "Java (OpenJDK 8) – Try It Online")
[Answer]
## C# (.Net 6), 64 bytes
```
int i=0,j=0;for(;i<a.Length;)j+=a[i++]-97;return(char)(97+j%26);
```
[Try it here](https://dotnetfiddle.net/KaXcug)
[Answer]
# [J](https://www.jsoftware.com), 19 bytes
```
(26|+/)&.(_97+3&u:)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmuxWcPIrEZbX1NNTyPe0lzbWK3UShMic9NVkys1OSNfyUAhTc1OQT0jNScnvzy_KCdF3Vo9MSk5JTUNyEjOT0lNz88BMYtLEpOzUyuSMxLz0lNBakBAHWLYggUQGgA)
```
(26|+/)&.(_97+3&u:)
&. NB. F&.G y applies G⁻¹(F(G x)) to y, rank is decided by G
(_97+3&u:) NB. fork converting str to char codes and subtracting 97 from each
(26|+/) NB. fork that sums the arg and mods the result by 26
NB. +/ can be used because u: operates on y as a whole
NB. The inverse of G in this case would be to add 97 to
NB. the result of F and then convert char code to str
```
[Answer]
# [Bits](https://github.com/nayakrujul/bits), 130 bits = 16.25 bytes
```
1110000111000001110001011111110111010100000001100111110101011100011000000110001011001101101110000000110100111001111101010111111100
```
This was very painful.
### Explanation
```
11100001 // Get a string input
1100000 // Push 0 to the stack [this will be our running sum]
11100010 // For each character in the input string:
111111101 // Get ord(c)
1101010 // Add [to the running sum]
000000 // Separator so the numbers don't get joined together
1100111 // Push 7
1101010 // Add [to the running sum]
11100011 // ENDFOR
000000 // Separator so the numbers don't get joined together
1100010 // Push 2
1100110 // Push 6 [this gets joined into 26]
1101110 // Mod our running sum by 26
000000 // Separator so the numbers don't get joined together
1101001 // Push 9
1100111 // Push 7 [this gets joined into 97]
1101010 // Add [to the result of the mod]
111111100 // Get chr(x)
// [implicit output of the item on the top of the stack]
```
### Output
[](https://i.stack.imgur.com/QELKh.png)
[Answer]
# [R](https://www.r-project.org/), ~~44~~ ~~43~~ 42 bytes
```
letters[sum(utf8ToInt(scan(,""))+7)%%26+1]
```
[Try it online!](https://tio.run/##K/r/Pye1pCS1qDi6uDRXo7QkzSIk3zOvRKM4OTFPQ0dJSVNT21xTVdXITNsw9n9Gak5Ofnl@UU7KfwA "R – Try It Online")
(or [38 bytes](https://ato.pxeger.com/run?1=m72waMHK5IzU5Ozi0lzbpaUlaboWN9ViNCo0c1JLSlKLiqOB4hpAYYuQfM-8EqC4trmmqqqRmbZhLET1NphuDaWM1Jyc_PL8opwUJU2I5IIFEBoA) as a function in [R](https://www.r-project.org/) ≥ 4.1).
[Answer]
# [Thon (Symbols)](https://github.com/nayakrujul/thon-symbols) `s` flag, 10 [bytes](https://github.com/nayakrujul/thon-symbols/blob/main/Codepage.md)
```
$åị$Σ26%å`
```
### Explanation
```
$åị$Σ26%å` // (implicit input as a string)
$ $ // For each character in the input string:
åị // Get the index in the alphabet
// (implicitly create a list of all of these indexes)
Σ // Sum the list
26% // Mod by 26
å` // Get that letter of the alphabet
// (implicit output)
```
[Answer]
# [Python](https://docs.python.org/3/), 74 bytes
```
from string import*
f=lambda s,l=ascii_lowercase:l[sum(map(l.index,s))%26]
```
[Try it online!](https://tio.run/##DczBCsIwDADQu1/Ri6yV4UHBg7AvEZG4ti6QNCWpuH193f3x6tYWKdfeswo7a4rl45CraDsd8kTA7wjORprAZsQXyS/pDJbu9LAve4bq6YwlpnW0EI6X27PXPWk@@2FJtHtRikMI/Q8 "Python 3 – Try It Online")
# [Python](https://docs.python.org/3/) + [`golfing-shortcuts`](https://github.com/nayakrujul/golfing-shortcuts), 47 bytes
```
lambda S:Sl[s(m(Sl.index,S))%26]
from s import*
```
(Is this one a competitive answer?)
] |
[Question]
[
**Task**
Given a positive integer `n` less than `2^30` specified as input in any way you choose, your code should output a random integer between `0` and `n`, inclusive. The number you generate should be chosen *uniformly at random*. That is each value from `0` to `n` must occur with equal probability (see Rules and Caveats).
**Rules and Caveats**
Your code can assume that any random number generator built into your language or standard library that claims to be uniformly random is in fact uniform. That is you don't have to worry about the quality of the random source you are using. However,
* You do have to establish that if the random source you are using is uniform then your code correctly outputs a uniform random integer from `0` to `n`.
* **Any arguments when calling a built in or library random function must be constant. That is they must be completely independent of the input value.**
* Your code may terminate [with probability 1](https://en.wikipedia.org/wiki/Almost_surely) rather than being guaranteed to terminate.
**Notes**
* `randInt(0,n)` is not valid as it takes the input as an argument to a builtin or library function.
* `rand()%n` will **not** give a uniform random number in general. As an example given by betseg, if `intmax == 15` and `n = 10`, then you will be much more likely to get `0-5` than `6-10`.
* `floor(randomfloat()*(n+1))` will also not give a uniform random number in general due to the finite number of different possible floating point values between 0 and 1.
[Answer]
## x86 machines with `rdrand` instruction, 10 bytes
```
BITS 64
_try_again:
rdrand eax
jnc _try_again
cmp eax, edi
ja _try_again
ret
```
machine code
```
0FC7F0 73FB 39F8 77F7 C3
```
---
The input is in the register `rdi` and the output in `rax`.
This respects the [SYS V AMD64 ABI](https://software.intel.com/sites/default/files/article/402129/mpx-linux64-abi.pdf) so the code effectively implement a C function
```
unsigned int foo(unsigned int max);
```
with 32-bit ints.
The instruction `rdrand` is described by Intel
>
> `RDRAND` returns random numbers that are supplied by a cryptographically secure, deterministic random bit generator DRBG. The DRBG is designed to meet the [NIST SP 800-90A](http://csrc.nist.gov/publications/nistpubs/800-90A/SP800-90A.pdf) standard.
>
>
>
Dealing with CSRNG it is implicit that the distribution is uniform, anyway, quoting the NIST SP 800-90A:
>
> A random number is an instance of an unbiased random variable,
> that is, the output produced by a **uniformly** distributed random process.
>
>
>
---
The procedure generates a random number and if it is non-strictly greater than the input it is returned.
Otherwise, the process is reiterated.
Since `eax` is 32-bit, `rdrand` returns a number between 0 and 232-1, so for every *n* in [0, 232-1] the number of expected iterations is 232/(n+1) which is defined for all *n* in [0, 230).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~7~~ 6 bytes
```
⁴!!X%‘
```
*Thanks to @JonathanAllan for golfing off 1 byte!*
Cannot be run on TIO because **(16!)!** is a *huge* number.
### How it works
```
⁴!!X%‘ Main link. Argument: n
⁴ Set the return value to 16.
!! Compute (16!)!.
X Pseudo-randomly choose an integer between 1 and (16!)!.
Since (16!)! is evenly divisible by any k ≤ 2**30, it is evenly divisible
by n+1.
%‘ Take the result modulo n+1.
```
[Answer]
## Mathematica, 29 bytes
*Based on [Dennis's Jelly answer](https://codegolf.stackexchange.com/a/111656/8478).*
```
RandomInteger[2*^9!-1]~Mod~#&
```
I wouldn't recommend actually running this. `2e9!` is a pretty big number...
It turns out to be shortest to generate a huge number that is divisible by all possible inputs and the map the result to the required range with a simple modulo.
### Rejection Sampling, 34 bytes
My old approach that led to somewhat more interesting code:
```
13!//.x_/;x>#:>RandomInteger[13!]&
```
Basic rejection sampling. We initialise the output to **13!** (which is larger than the maximum input **230**) and then repeatedly replace it with a random integer between **0** and **13!** as long as the value is bigger than the input.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 9 bytes
```
≥.∧13ḟṙ|↰
```
[Try it online!](https://tio.run/nexus/brachylog2#@/@oc6neo47lhsYPd8x/uHNmzaO2Df//GxqAwf8oAA "Brachylog – TIO Nexus")
This uses `13!` like in Martin Ender's answer (`13ḟ` is one byte less than `2^₃₀`).
`ṙ` is implemented using [`random_between/3`](http://www.swi-prolog.org/pldoc/doc_for?object=random_between/3), which, when digging its source, uses [`random_float/0`](http://www.swi-prolog.org/pldoc/doc_for?object=f(random_float/0)) which is linked to [`random/1`](http://www.swi-prolog.org/pldoc/man?function=random/1) which uses the Mersenne Twister algorithm which is uniform for our purposes.
### Explanation
```
≥. Input ≥ Output
∧ And
13ḟṙ Output = rand(0, 13!)
| Else
↰ Call recursively with the same input
```
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org/), 38 bytes
```
X*Y:-Z is 2^31,random(0,Z,Y),Y=<X;X*Y.
```
Works by rejection sampling.
Generate a random number between *0* and *2^31-1* = *2147483647* until one less than or equal to the input has been found.
I feel as if I should be able to use a cut instead of the else, but I can't see how.
[Answer]
## [Labyrinth](https://github.com/m-ender/labyrinth), 63 bytes
```
?
#00}__""*_
; #" _
{-{= } "><)
!{ : ;"({ +
@ }}: >`#
```
*(Thanks to @MartinEnder for help with some heavy golfing here.)*
Labyrinth is a 2D language, and its only source of randomness is in a situation like the following:
```
x
"<)
" "
" "
```
Assume the instruction pointer is on the `x` and moving downwards. It next lands on the `<`, which if the top of stack is 0 (which is always the case in the actual program above) shifts the current row left by 1:
```
"
"<)
" "
" "
```
The instruction pointer is now on the `<` moving downwards. At a junction, Labyrinth turns based on the top of stack - negative is turn left, positive is turn right and zero is move forward. If the top of stack is still zero at this point, we can't move forward or backward since there's no path, so Labyrinth will randomise between turning left or turning right with equal probability.
Essentially what the program above does is use the randomness feature to generate 100-bit numbers (100 specified by `#00` here) and continue looping until it generates a number `<= n`.
For testing, it'll probably help to use `#0"` instead for 10-bit numbers, with the `"` being a no-op path. [Try it online!](https://tio.run/nexus/labyrinth#@69gz6WgbKBUGx@vpKQVz6VgrQAEykoKCvFc1brVtgoKtQpKdjaaXIrVClYK1koa1QraXA5A0VorBQW7BOX//02/5uXrJicmZ6QCAA)
Rough explanation:
```
? <--- ? is input and starting point
#0"}__""*_ <--- * here: first run is *0, after that is *2 to double
; #" _
{-{= } "><) <--- Randomness section, +0 or +1 depending on path.
!{ : ;"({ + After <, the >s reset the row for the next inner loop.
@ }}: >`#
^ ^
| |
| The " junction in this column checks whether the
| 100-bit number has been generated, and if not then
| continue by turning right into }.
|
Minus sign junction here checks whether the generated number <= n.
If so, head into the output area (! is output as num, @ is terminate).
Otherwise, head up and do the outer loop all over again.
```
[Answer]
# Python, 61 bytes
```
from random import*
lambda n,x=2.**30:int(randrange(x)*-~n/x)
```
Edit:
Updated to avoid forbidden form
Edit2:
Saved 2 bytes, thanks @[JonathanAllan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)
Edit3:
Paid 2 bytes for a fully functional solution - thanks again @JonathanAllan
Edit4:
Removed `f=`, saving 2 bytes
Edit5:
Saved 1 more byte thanks to @[JonathanAllan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)
Edit6:
Saved 2 more bytes thanks to @[JonathanAllan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)
By now, git blame would point at me for the bad things, and JonathanAllan for the stuff that helps.
Edit7:
When it rains, it pours - another 2 bytes
Edit8:
And another 2 bytes
[Answer]
# [Python 2](https://docs.python.org/2/), 61 bytes
```
from random import*
lambda n:map(randrange,range(1,2**31))[n]
```
Pseudo-randomly chooses integers between **0** and **k** for all values of **k** between **0** and **231 - 2**, then takes the integer corresponding to **k = n**.
[Answer]
## Batch, 64 bytes
```
@set/ar=%random%*32768+%random%
@if %r% gtr %1 %0 %1
@echo %r%
```
`%random%` only gives 15 bits of randomness, so I have to combine two random numbers. Loops until the random value lies within the desired range, so slow for low `n`; 98 bytes for a faster version:
```
@set/a"n=%1+1,m=~(3<<30)/n*n,r=%random%*32768+%random%
@if %r% geq %m% %0 %1
@cmd/cset/a%r%%%%n%
```
[Answer]
# Bash (+coreutils), 44 bytes
[/dev/urandom](https://linux.die.net/man/4/urandom) based solution
```
od -w4 -vtu4</d*/ur*|awk '($0=$2)<='$1|sed q
```
Will read unsigned 32 bit integers from `/dev/urandom`, and filter them out with `awk` until it finds one within a given range, then `sed q` will abort the pipe.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 12 bytes
*Thanks to [@AdmBorkBork](https://codegolf.stackexchange.com/users/42963/admborkbork) and to [@Suever](https://codegolf.stackexchange.com/users/51939/suever) for telling me how to disable TIO cache.*
```
`30WYrqG>}2M
```
[Try it online!](https://tio.run/nexus/matl#@59gbBAeWVTobldr5Pv/v6EBFHzNy9dNTkzOSAUA).
This uses a [rejection method](https://en.wikipedia.org/wiki/Rejection_sampling): generate a random integer from `0` to `2^30-1`, and repeat while it exceeds the input `n`. This is guaranteed to terminate with probability `1`, but the average number of iterations is `2^30/n`, and so it takes very long for `n` significantly smaller than `2^30`.
```
` % Do...while
30W % Push 2^30
Yr % Random integer from 1 to 2^30
q % Subtract 1
G> % Does it exceed the input? If so: next iteration. Else: exit
} % Finally (execute right before exiting the loop)
2M % Push the last generated integer
% End (implicit). Display (implicit)
```
[Answer]
# [PowerShell](https://github.com/PowerShell/PowerShell), 35 bytes
```
for(;($a=Random 1gb)-gt"$args"){}$a
```
[Try it online!](https://tio.run/nexus/powershell#@5@WX6RhraGSaBuUmJeSn6tgmJ6kqZteoqSSWJRerKRZXauS@P//f1MDg9ykr3n5usmJyRmpAA "PowerShell – TIO Nexus")
Another rejection sampling method. This is an infinite `for` loop, setting the value of `$a` to be a `Random` integer between `0` and `1gb` (`= 1073741824 = 2^30`), and keeps looping so long as that integer is `-g`reater`t`han the input `$args`. Once the loop is complete, we just put `$a` on the pipeline and output is implicit.
Note: This will take a ***long*** time if the input is a small number.
[Answer]
## JavaScript (ES6), ~~55~~ 54 bytes
```
f=(n,m=1)=>m>n?(x=Math.random()*m|0)>n?f(n):x:f(n,m*2)
```
Generates integers in the range **[0 ... 2k - 1]**, where **k** is the smallest integer such that **2k** is greater than **n**. Repeats until the result falls into **[0 ... n]**.
### Why?
This is based on the following assumptions:
* Internally, the pseudo-random integer values generated by the JS engine to feed `Math.random()` are uniform over any interval **[0 ... 2k-1]** (with **k < 32**).
* Once multiplied by an exact power of 2, the IEEE 754 float values returned by `Math.random()` are still uniform over such intervals.
If anyone can confirm or refute these hypotheses, please let me know in the comments.
### Demo
Generates 1 million values in **[0 ... 2]** and displays the outcome statistics.
```
f=(n,m=1)=>m>n?(x=Math.random()*m|0)>n?f(n):x:f(n,m*2)
for(i = 0, stat = []; i < 1000000; i++) {
r = f(2);
stat[r] = (stat[r] || 0) + 1;
}
console.log(stat.join` `)
```
[Answer]
# Haskell, 70 bytes
```
import System.Random
g n=head.filter(<=n).randomRs(0,2^30)<$>getStdGen
```
Not a very efficient algorithm but it works. It generates an infinite list of integers (or floats if needed, because of Haskell's type system) bounded by [0,2^30] and takes the first one less than or equal to n. For small n this can take a long time. The random numbers should be uniformly distributed, as specified in the documentation for [randomR](https://www.stackage.org/haddock/lts-8.3/random-1.1/System-Random.html#v:randomR) so all numbers in the interval [0,2^30] should have the same probability (1/(2^30+1)) therefore all the numbers in [0,n] have the same probability.
Alternate Version:
```
import System.Random
g n=head.filter(<=n).map abs.randoms<$>getStdGen
```
This version is terrible but it saves a whole byte. `randoms` uses an arbitrary range defined by the type to generate an infinite list of numbers. This may include negatives so we need to map it with `abs` to force them positive (or zero). This is extremely slow for any values of n that aren't absurdly large. **EDIT**: I realized later that this version isn't uniformly distributed because the probability of getting 0 is worse than the other numbers due to the use of `abs`. To produce some number `m` the generator could produce `m` or `-m` but in the case of 0 only 0 itself will work, therefore its probability is half of the other numbers.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
⁴!Ẋ’>Ðḟ⁸Ṫ
```
**[Try it online!](https://tio.run/nexus/jelly#AS0A0v//MTDhuorigJk@w5DhuJ/igbjhuar/wrPDhzvCtTMwwqH//zP1bm8tY2FjaGU)** - code above wont run on TIO since a range of size 16! must be built first (not to mention the fact that they then need to be shuffled and then filtered!), so this is the same thing on a much smaller scale, repeated 30 times for an input of 3 with a bound of 10.
### How?
```
⁴!Ẋ’>Ðḟ⁸Ṫ - Main link: n
⁴ - 16
! - factorial: 20922789888000
Ẋ - shuffle random: builds a list of the integers 1 through to 16! inclusive and
- returns a random permutation via Python's random.shuffle (pretty resource hungry)
’ - decrement (vectorises - a whole pass of this huge list!)
Ðḟ - filter out if: (yep, yet another pass of this huge list!)
> - greater than
⁸ - left argument, n
Ṫ - tail: return the rightmost remaining entry.
```
*Note:* it would be over a thousand time more efficient for the same byte-count if `ȷ⁵` would do what one would naively expect and return ten to the ten, but that is not the case since the `⁵` is not evaluated as a literal ten to be used by the number literal `ȷ...` but rather two separate literals are parsed, `ȷ` with it's default exponent of three yielding one thousand, and `⁵` yielding ten.
[Answer]
# JDK 9 on jshell, ~~75~~ 59 bytes
```
n->(new Random()).ints(0,1<<30).dropWhile(x->x>n).findAny()
```
### Usage
```
((IntFunction)(n->(new Random()).ints(0,1<<30).dropWhile(x->x>n).findAny())).apply(<n>)
```
* -16 bytes: Thanks Jakob!
* Assumes that we consider jshell to be a valid runtime environment.
* jshell itself, as a runtime environment, doesn't require explicit imports for core libraries and doesn't require semicolons.
* Returns an `OptionalInt`. Rules don't specify that return type must be a primitive and I'm considering an `OptionalInt` to be a valid representation of the result.
[Answer]
# PHP, 30 bytes
```
while($argn<$n=rand());echo$n;
```
Run with `echo <N> | php -Rn '<code>'`.
picks a random number between 0 and [`getrandmax()`](http://php.net/getrandmax) (2\*\*31-1 on my 64 bit machine);
repeats while that is larger than the input.
This *may* take a while ... my AMD C-50 (1 GHz) needed between 0.3 and 130 seconds for `N=15`.
A faster way for average `N` (**46 bytes**):
```
for(;++$i<$x=1+$argn;)$n+=rand()%$x;echo$n%$x;
```
or
```
for(;++$i<$x=1+$argn;$n%=$x)$n+=rand();echo$n;
```
takes `N+1` random integers, sums them up and takes the modulo with `N+1`.
The C-50 needs approx. 8 seconds for 1 million runs.
An invalid solution for **19 bytes**:
```
echo rand(0,$argn);
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~72~~ 69 bytes
-3 bytes thanks to xnor (override the `id` built-in as a variable)
```
from random import*
n=input()
while id>n:id=randrange(2**30)
print id
```
**[Try it online!](https://tio.run/nexus/python2#@59WlJ@rUJSYlwKkMnML8otKtLjybDPzCkpLNDS5yjMyc1IVMlPs8qwyU2xByoA4PVXDSEvL2ECTq6AoM68EKP3/v6GBgcHXvHzd5MTkjFQA)**
`randrange(2**30)` produces a pseudo-uniformly distributed number (Mersenne Twister **219937-1**) from the range **[0,230)**. Since `n` is guaranteed to be below **230** this can simply be called repeatedly until it is not greater than the input. It will take a long expected time for very low values of `n`, but usually works within the a minute even for inputs as low as 50.
[Answer]
# Java 8, ~~84~~ ~~83~~ ~~80~~ ~~71~~ 62 bytes
```
n->{int r;for(;(r=(int)(Math.random()*(1<<30)))>n;);return r;}
```
-1 byte thanks to *@OliverGrégoire*.
-3 bytes thanks to *@Jakob*.
-9 bytes converting Java 7 to Java 8.
-9 bytes by changing `java.util.Random().nextInt(1<<30)` to `(int)(Math.random()*(1<<30))`.
**Explanation:**
[Try it here.](https://tio.run/##NY7NCsJADITvPkWOiWCpeFz1DfTiUUTidtXVNlu2qSDSZ6@7/hwykMlk@G784Flondyq@2hr7jrYsJfXBMCLunhm62Cb148BFrMKmeQMkySdsnoLWxBYwSiz9SsHojmHiAbjKucJN6zXIrJUoUGa4ny5XJREtBZDJjrto6SXYTS5se1PdWr8FT@Cr6BJSLjT6OWyPwDTl2f37NQ1Rei1aNNJa0EpLM6PZVn@h36kw/gG)
```
n->{ // Method with integer parameter and integer return-type
int r; // Result-integer
for(;(r=(int)(Math.random()*(1<<30)))>n;);
// Loop as long as the random integer is larger than the input
// (the random integer is in the range of 0 - 1,073,741,824 (2^30))
return r; // Return the random integer that is within specified range
} // End method
```
NOTE: May obviously take very long for small inputs.
**Example output:**
```
407594936
```
[Answer]
# Python 3, 51 bytes
Here is a python solution with an unorthodox random source.
```
print(list(set(map(str,range(int(input())+1))))[0])
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EIyezuESjOLVEIzexQKO4pEinKDEvPVUDJJWZV1BaoqGpqW2oCQTRBrGa//8bGhgAAA "Python 3 – Try It Online")
So to break this down.
```
int(input())+1
```
Gets the input number, and adds `1` to it.
```
set(range(...))
```
Creates the set `{0, 1, 2, 3, 4, ... n}` for all possible results.
```
print(list(...)[0])
```
Takes the set, converts it to list, and grabs the first item.
This works because in Python 3, the order of `set()` is established by [PYTHONHASHSEED](https://docs.python.org/3/using/cmdline.html#envvar-PYTHONHASHSEED) ([can't be obtained](https://stackoverflow.com/q/32538764/) but is established on script execution).
Admittedly, I am guessing that this is a uniform distribution, as the `hash()` value is randomly assigned and I am looking at randomly picking the value with a specific `hash()`, rather then just returning the `hash(input())` itself.
If anyone knows whether this is a uniform distribution, or how I could test that, please comment.
[Answer]
# [Perl 6](https://perl6.org), 29 bytes
```
{first 0..$_,^2**30 .roll(*)}
```
Inspired by [Martin Ender's Mathematica solution](https://codegolf.stackexchange.com/a/111615/14880).
Generates a lazy infinite sequence of random integers between 0 and 2^30-1, and takes the first one that is between 0 and the input.
[Try it online!](https://tio.run/nexus/perl6#y61UUEtTsP1fnZZZVFyiYKCnpxKvE2ekpWVsoKBXlJ@To6GlWfu/OLFSIU3B0MAg3sDAwJqLFO5/AA "Perl 6 – TIO Nexus")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes
```
žIÝ.rDI›_Ϥ
```
[Try it online!](https://tio.run/nexus/05ab1e#@292aMPhuXpFLp6PGnbFH@4/tOT/f0MjYxNTs695@brJickZqQA)
**Explanation**
```
žIÝ # push the inclusive range [0 ... 2^31]
.r # get a random permutation (pythons random.shuffle)
D # duplicate this list
I # push input
›_Ï # keep only elements from the list not greater than input
¤ # take the last one
```
As the list `[0 ... 2147483648]` is too large for TIO, the link uses `1.000.000` instead.
**Alternate (on average) much faster 11 byte solution**
```
[žIÝ.RD¹›_#
```
[Try it online](https://tio.run/nexus/05ab1e#@x9tdmjD4bl6QS6Hdj5q2BWv/P@/oZGxianZ17x83eTE5IxUAA)
**Explanation**
```
[ # start loop
žIÝ # push the inclusive range [0 ... 2^31]
.R # pick a random integer (pythons random.chiose)
D # duplicate
¹ # push input
›_# # break if random number is not greater than input
# implicitly output top of stack (the random number)
```
[Answer]
# Python 2, 89 bytes
```
l=range(2**31)
import random
random.shuffle(l)
n=input()
print filter(lambda x:x<=n,l)[0]
```
## Explanation
```
L=range(2**31) # Create a list from 0 to 2^31 exclusive. Call it <L>.
import random # Import the module <random>.
random.shuffle(L) # Use 'shuffle' function from <random> module,
# to shuffle the list <L>.
n=input() # Take the input -> <n>.
print
filter( # Create a new sequence,
lambda x:x<=n # where each element is less than or equal to <n>.
,L) # from the list <L>.
[0] # Take the first element.
```
This is *very* inefficient, as it creates **2^31** integers, shuffles and filters them.
I see no point in sharing a TIO link, where it's creating such large lists, so here is a TIO link for `n` = 100.
[Try it online!](https://tio.run/nexus/python2#JcgxCoAgFADQ3VM4KlToGnmSaLDUFL5fMYUu3mxB2@P1EHMqlRaNJkUC6sNpmRSSk/@myzfnwDLgBFXA3CrjJJeAlboA1RYGOu5G03u@F4UD8FVsvUshHkzjoQ9vXw)
[Answer]
# [R](https://www.r-project.org/), 37 bytes
```
which.min(sample(2^30)[0:scan()+1])-1
```
Takes `n` from stdin. First it generates a random sample of all the integers in the range, then selects the first `n+1` values, finds the index of the minimum, and then subtracts one, to generate a number between `0` and `n`, inclusive. It won't run on TIO because it can't allocate an array of size `2^30` to sample from.
I'm fairly confident this is uniformly random.
[Try it online!](https://tio.run/##K/r/vzwjMzlDLzczT6M4MbcgJ1XDKM7YQDPawKo4OTFPQ1PbMFZT1/C/4X8A "R – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 51 bytes
```
lambda n:randrange(1<<31)*n>>31;from random import*
```
[Attempt this online!](https://ato.pxeger.com/run?0=ZVI9T8MwEJUYw584YCCpWpRQPqoWWJjYGZEq1760Fo4d7AuImV_BxgJ_hxl-DRcnopFqyb7hvXfP7-z3r_qVNs5-lnAND58NlZPZz9SIaqUE2LkXVvFeY1pcXU2LbGRvbqbFovSughbjoqvaeRp10t-9_YgFEqQDaRl6HOpACp-TiEpnDErSzv7Dt66xhD5JjoAwEKBaI0gRMKm9tpT2eFqmRQal87AEbaG_Wp5lWZIoLKM2NbrSNAbNfBFNsnkCvLpOu2gEJeffmkTSjtFAw36t6gjuN5pDBBDGwB14rLBaoYeYs3odDgJVI6P6hInK2WOCR-teYMObHIc1sjGCEATUk2dhGuwtGAyRtBHEB4Lijl6vmrZZ610K7RdQIhr2RWwFQqmOr-3BIPzh9xtcH47710jlSfQJaTvAAatCEhNu9dSglRrDnCVKy-0zDIU8ijj24nR6dn5xORtDkefLPM-z7k98dOUP) Includes a test suite.
Here is a proof that this is fair: <https://arxiv.org/abs/1805.10941>. It's also much faster than a typical modulo reduction because it's just a multiplication and a shift. (although this isn't as noticeable in Python...)
Uses an interesting approach, is O(1), and is the shortest Python answer yet!
[Answer]
# C#, 57 bytes
```
n=>{int x=n+1;while(x>n)x=new Random().Next();return x;};
```
Anonymous function which returns an integer between 0 and n inclusive.
The smaller the input number, the longer the time to return a random value.
Full program:
```
using System;
class RandomNumber
{
static void Main()
{
Func<int, int> f =
n=>{int x=n+1;while(x>n)x=new Random().Next();return x;};
// example
Console.WriteLine(f(100000));
}
}
```
[Answer]
# SmileBASIC, 38 bytes
```
INPUT N@L
R=RND(1<<30)ON N<=R GOTO@L?R
```
Generates random numbers until it gets one that is smaller than the input.
[Answer]
## Ruby, ~~23 15 23 32~~ 29 bytes
```
->n{1while n<q=rand(2**30);q}
```
### How it works:
* `1while [...];` executes the statement at least once: `1` before `while` acts as a nop
* Get a random number in the range 0..2^30-1 (*lower than 2^30*, as specified)
* Repeat if the number is higher than the input parameter (Could take some time when n is small)
[Answer]
# Ohm, 26 bytes
```
IΩ
D31º#╬D0[>?D-+∞;,
```
Explanation:
```
IΩ ■Main wire
IΩ ■Call wire below
D31º#╬D0[>?D-+∞;, ■"Real main" wire
D ■Duplicate input
31º#╬D ■Push random_int in [0..2^31] twice
0[ ■Push input again
>? ; ■If(random_int > input){
D-+ ■ remove the random_int
∞ ■ recursion
; ■}
, ■Print random_int
```
[Answer]
# Go, ~~63~~ 61 bytes
```
import."math/rand"
var n=0;func R(){q:=n;for;q<n+1;n=Int(){}}
```
Use it like this:
```
func main() {
n = 5000
R()
print(n)
}
```
[Test it live at the go playground](https://play.golang.org/p/_T9OreOzcE)
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 6 years ago.
[Improve this question](/posts/32381/edit)
**Short and sweet description of the challenge:**
Based off the ideas of several other questions on this site, your challenge is to write the most creative code in any program that takes as input a number written out in English and converts it to integer form.
**Really dry, long and thorough specifications:**
* Your program will receive as input an integer in **lowercase** English between `zero` and `nine hundred ninety-nine thousand nine hundred ninety-nine` inclusive.
* It must output only the integer form of the number between `0` and `999999` and nothing else (no whitespace).
* The input will **NOT** contain `,` or `and`, as in `one thousand, two hundred` or `five hundred and thirty-two`.
* When the tens and ones places are both nonzero and the tens place is greater than `1`, they will be separated by a HYPHEN-MINUS character `-` instead of a space. Ditto for the ten thousands and thousands places. For example, `six hundred fifty-four thousand three hundred twenty-one`.
* The program may have undefined behavior for any other input.
**Some examples of a well-behaved program:**
`zero` -> `0`
`fifteen` -> `15`
`ninety` -> `90`
`seven hundred four` -> `704`
`sixty-nine thousand four hundred eleven` -> `69411`
`five hundred twenty thousand two` -> `520002`
[Answer]
# Applescript
A silly, hacky mash-up that might upset some Cupertino/Mountain View folks, but I *think* its a creative silly, hacky mash-up.
```
set myNumber to text returned of (display dialog ¬
"Enter number as text:" buttons {"Continue…"} ¬
default answer "" default button 1)
tell application "Google Chrome"
activate
open location "https://www.google.com"
end tell
delay 5
say "ok google. " & myNumber
delay 2
tell application "System Events"
tell application process "Google Chrome"
set fullURL to value of text field 1 of toolbar 1 of window 1
end tell
end tell
set AppleScript's text item delimiters to "="
display alert item 2 of text items of fullURL
```
Uses OSX text to speech to speak the text number, and google audio search to listen for it and convert it to an integer.
Requirements
* OSX
* Google chrome
* speech-recognition enabled in your google account
* volume turned up to a reasonable level
The delay timings may need to be adjusted depending on your chrome load time and google lookup time.
Example input:

Example output:

[Answer]
# Bash, 93 64 55 characters\*
In the fantastic `bsd-games` package that's available on most Linux operating systems, there's a small command-line toy called `number`. It turns numbers into English text, that is, it does the exact opposite of this question. It really is the exact opposite: all the rules in the question are followed by `number`. It's almost too good to be a coincidence.
```
$ number 42
forty-two.
```
Of course, `number` doesn't answer the question. We want it the other way around. I thought about this for a while, tried string parsing and all that, then realised that I can just call `number` on all 999.999 numbers and see if something matches the input. If so, the first line where it matches has twice the line number I'm looking for (`number` prints a line of dots after every number). Simple as that. So, without further ado, here's the complete code for my entry:
```
seq 0 999999|number -l|awk "/$1/{print (NR-1)/2;exit}"
```
It even short-circuits, so converting "two" is quite fast, and even higher numbers are usually decoded in under a second on my box. Here's an example run:
```
wn@box /tmp> bash unnumber.sh "zero"
0
wn@box /tmp> bash unnumber.sh "fifteen"
15
wn@box /tmp> bash unnumber.sh "ninety"
90
wn@box /tmp> bash unnumber.sh "seven hundred four"
704
wn@box /tmp> bash unnumber.sh "sixty-nine thousand four hundred eleven"
69411
wn@box /tmp> bash unnumber.sh "five hundred twenty thousand two"
520002
```
Of course, you'll need to have `number` installed for this to work.
---
\*: Yes, I know, this is not a `code-golf` challenge, but shortness is pretty much the only discerning quality of my entry, so... :)
[Answer]
# Javascript
```
(function parse(input) {
var pat = "ze/on/tw/th.?r/fo/fi/ix/se/ei/ni/ten/ele".split("/");
var num = "", last = 0, token = input.replace(/-/g, " ").split(" ");
for(var i in token) {
var t = token[i];
for(var p in pat) if(t.match(RegExp(pat[p])) !== null) num += "+" + p;
if(t.indexOf("een") >= 0) num += "+10";
if(t.indexOf("lve") >= 0) num += "+10";
if(t.indexOf("ty") >= 0) num += "*10";
if(t.indexOf("dr") >= 0) { last = 100; num += "*100"; }
if(t.indexOf("us") >= 0) {
if(last < 1000) num = "(" + num + ")"; last = 0;
num += "*1000";
}
}
alert(eval(num));
})(prompt());
```
Do you like some `eval()`?
Run this script on your browser's console.
**Edit:** Thanks for the feedback. Bugs fixed (again).
[Answer]
## Python
Just to get the ball rolling.
```
import re
table = {'zero':0,'one':1,'two':2,'three':3,'four':4,'five':5,'six':6,'seven':7,'eight':8,'nine':9,
'ten':10,'eleven':11,'twelve':12,'thirteen':13,'fourteen':14,'fifteen':15,'sixteen':16,'seventeen':17,'eighteen':18,'nineteen':19,
'twenty':20,'thirty':30,'forty':40,'fifty':50,'sixty':60,'ninety':90}
modifier = {'hundred':100,'thousand':1000}
while True:
text = raw_input()
result = 0
tmp = 0
last_multiplier = 1
for word in re.split('[- ]', text):
multiplier = modifier.get(word, 1)
if multiplier > last_multiplier:
result = (result+tmp)*multiplier
tmp = 0
else:
tmp *= multiplier
if multiplier != 1:
last_multiplier = multiplier
tmp += table.get(word,0)
print result+tmp
```
[Answer]
# Perl + CPAN
Why reinvent the wheel, when it has been done already?
```
use feature 'say';
use Lingua::EN::Words2Nums;
say words2nums $_ while <>;
```
This program reads English strings from standard input (or from one or more files specified as command line arguments), one per line, and prints out the corresponding numbers to standard output.
I have tested this code using both the sample inputs from the challenge, as well as an exhaustive test suite consisting of the numbers from 0 to 999999 converted to text using the bsd-games `number` utility (thanks, Wander Nauta!), and it correctly parses all of them. As a bonus, it also understands such inputs as e.g. `minus seven` (−7), `four and twenty` (24), `four score and seven` (87), `one gross` (144), `a baker's dozen` (13), `eleventy-one` (111) and `googol` (10100).
(*Note:* In addition to the Perl interpreter itself, this program also requires the CPAN module [Lingua::EN::Words2Nums](http://search.cpan.org/perldoc?Lingua%3A%3AEN%3A%3AWords2Nums). Here are some [instructions for installing CPAN modules](http://www.cpan.org/modules/INSTALL.html). Debian / Ubuntu Linux users may also install this module via the APT package manager as *liblingua-en-words2nums-perl*.)
[Answer]
# Python
A general recursive solution, with validity checking. Could be simplified for the range of numbers required, but here's to showing off I guess:
```
terms = 'zero one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen'.split()
tee = 'twenty thirty forty fifty sixty seventy eighty ninety'.split()
for t in tee:
terms.append(t)
for s in terms[1:10]:
terms.append(t+'-'+s)
terms = dict(zip(terms, range(100)))
modifiers = [('hundred', 100), ('thousand', 1000), ('million', 10**6), ('billion', 10**9)]
def read_num(words):
if len(words) == 0: return 0
elif len(words) == 1:
if words[0] in terms:
return terms[words[0]]
else:
raise ValueError(words[0]+' is not a valid english number.')
else:
for word, value in reversed(modifiers):
if word in words:
i = words.index(word)
return read_num(words[:i])*value+read_num(words[i+1:])
raise ValueError(' '.join(words)+' is not a valid english number.')
while True:
try:
print(read_num(input().split()))
except ValueError as e:
print(e)
```
[Answer]
## VBScript 474
This is a fairly routine answer... unfortunately, so routine that @Snack pretty much posted the same process but before me.
```
i=split(REPLACE(REPLACE(inputbox(""),"lve","een"),"tho","k"))
o=split("z on tw th fo fi si se ei ni ten ele")
y=split("red *100) k )*1000 ty *10) een +10)")
z=""
p=0
for t=0 to UBOUND(i)
s=split(i(t),"-")
u=ubound(s)
r=s(0)
for x=0 to UBOUND(o)
IF INSTR(r,o(x)) THEN
z=z+"+"+CSTR(x)
END IF
IF u Then
IF INSTR(s(1),o(x)) THEN
z=z+CSTR(x)
END IF
END IF
next
for m=0 to UBOUND(y)
IF INSTR(r,y(m))AND u=0 THEN
z=z+y(m+1)
p=p+1
END IF
next
next
Execute("MSGBOX "+String(p,"(")+z)
```
[Answer]
## Haskell
Similar to other recursive solutions I guess, but I took the time to make it clean.
Here is the complete source with all explanations : <http://ideone.com/fc8zcB>
```
-- Define a type for a parser from a list of tokens to the value they represent.
type NParse = [Token] -> Int
-- Map of literal tokens (0-9, 11-19 and tens) to their names.
literals = [
("zero", 0), ("one", 1), ("two", 2), ("three", 3), ("four", 4), ("five", 5), ("six", 6), ("seven", 7), ("eight", 8), ("nine", 9),
("eleven", 11), ("twelve", 12), ("thirteen", 13), ("fourteen", 14), ("fifteen", 15), ("sixteen", 16), ("seventeen", 17), ("eighteen", 18), ("nineteen", 19),
("ten", 10), ("twenty", 20), ("thirty", 30), ("fourty", 40), ("fifty", 50), ("sixty", 60), ("seventy", 70), ("eighty", 80), ("ninety", 90)
]
-- Splits the input string into tokens.
-- We do one special transformation: replace dshes by a new token. Such that "fifty-three" becomes "fifty tens three".
prepare :: String -> [Token]
-- Let's do the easy stuff and just parse literals first. We just have to look them up in the literals map.
-- This is our base parser.
parseL :: NParse
parseL [tok] = case lookup tok literals of
Just x -> x
-- We're going to exploit the fact that the input strings have a tree-like structure like so
-- thousand
-- hundred hundred
-- ten ten ten ten
-- lit lit lit lit lit lit lit lit
-- And recursively parse that tree until we only have literal values.
--
-- When parsing the tree
-- thousand
-- h1 h2
-- The resulting value is 1000 * h1 + h2.
-- And this works similarly for all levels of the tree.
-- So instead of writing specific parsers for all levels, let's just write a generic one :
{- genParse ::
NParse : the sub parser
-> Int : the left part multiplier
-> Token : the boundary token
-> NParse : returns a new parser -}
genParse :: NParse -> Int -> Token -> NParse
genParse delegate mul tok = newParser where
newParser [] = 0
newParser str = case splitAround str tok of
-- Split around the boundary token, sub-parse the left and right parts, and combine them
(l,r) -> (delegate l) * mul + (delegate r)
-- And so here's the result:
parseNumber :: String -> Int
parseNumber = parseM . prepare
where -- Here are all intermediary parsers for each level
parseT = genParse parseL 1 "tens" -- multiplier is irregular, because the fifty in fifty-three is already multiplied by 10
parseH = genParse parseT 100 "hundred"
parseK = genParse parseH 1000 "thousand"
parseM = genParse parseK 1000000 "million" -- For fun :D
test = (parseNumber "five hundred twenty-three thousand six hundred twelve million two thousand one") == 523612002001
```
[Answer]
# Common Lisp, 94
```
(write(cdr(assoc(read-line)(loop for i to 999999 collect(cons(format()"~r"i)i)):test #'equalp)))
```
Number to text conversion is built in to CL, but not the other way around. Builds a reverse mapping for the numbers and checks the input on it.
] |
[Question]
[
Following [this](https://stackoverflow.com/questions/4568645/printing-1-to-1000-without-loop-or-conditionals) popular question, present your solution which prints the numbers 1 to 1000 (all of them, not the string "1 to 1000" verbatim or something funny) in C++ without using any semi-colons. Unlike the original question, you may use conditionals and loops.
Solutions not requiring any compiler flags are preferred. Please mention any you use if you go against this. Undefined behaviour is allowed, so please specify the compiler and version you're using. Preference will be given to clever solutions. This is *not* a shortest code contest.
(I have a solution, which I'll post in 24 hours if a similar solution isn't posted before then.)
[Answer]
The semicolon is not needed if you know the magic word. And no need to go obfuscated.
My solution has the additional fanciness that it doesn't use any comma either ;)
```
#include <iostream>
#define Please(x) if (x) {}
int Number(int x)
{
if (x > 1)
Please(Number(x-1))
Please(std::cout << " " << x)
}
int main()
{
Please(Number(1000))
}
```
[Answer]
```
#error "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000"
```
[Answer]
```
main(){if(printf("1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000")){}}
```
[Answer]
Simple and almost idiomatic:
```
#include <iostream>
void loop(int low, int high)
{
if ( low <= high &&
std::cout << low << std::endl &&
(loop(low+1, high), false) )
{}
}
int main()
{
if (loop(1, 1000), false) {}
}
```
[Answer]
```
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void) {
if (char *p = (char *) malloc(10000U)) {
if (__LINE__ < 106 && printf("%d\n", __LINE__ - 5)) {
if (FILE *fp = fopen(__FILE__ ".tmp", "w")) {
if (putc('\n', fp) &&
fwrite(p, 1U,
fread(p, 1U, 10000U, fopen(__FILE__, "r")), fp) &&
fclose(fp) ||
rename(__FILE__ ".tmp", __FILE__) ||
system("g++ " __FILE__ " && exec ./a.out")) {
}
}
}
}
}
```
[Answer]
Very similar to other solutions, but with a minor variation: The step variable is declared in the `if` condition:
```
#include <iostream>
int main(){
if (int x = 1)
while (x <= 1000 && std::cout << x++ << std::endl) {}
}
```
[Answer]
This works great on my Linux machine:
```
#include <cstdlib>
int main()
{
if (system("seq 1 1000")){}
}
```
I know, I know, ...it's not portable.
[Answer]
```
/* No semicolons - or sense - //
// but at least there's //
// undefined behaviour //
*/ //
#define __ if
#define ___ int
#define ____ std
#define ______ &&
#define _______ {
#define ________ (
#define _________ )
#define __________ }
#define ___________ .
#define ____________ ,
#define _____________ <
#define ______________ >
#define _______________ ::
#define zero 0
#define five 5
#include <cstdio>
#include <vector>
___ _ ________ ____ _______________
vector
_____________ ___ ______________ _____ _________ _______ __ ________ ____ _______________
distance
________ _____ ___________
emplace
________ _____ ___________
end
________ _________ ____________
zero
_________ ____________ _____ ___________
end
________ _________ _________ ______
printf
________
"%d\n\0 I may have got a bit too carried away with the obfuscation."
____________ _____ ___________
size
________ _________ _________ _____________
five
______ _ ________ _____ _________ _________ _______ __________ __________ ___
main
________ _________ _______ __ ________ _ ________ _______ __________ _________ _________ _______ __________ __________
```
[Try it online!](https://tio.run/##nVNNb8IwDL3nVzyBxjY0KJddEOK@y34BUpSmLkRqk6pJQWPab@/SMUpbCp3mQ2o/P380sWWWzbZSliWAYIp3A0upkiYx2mIGk3tbW/JqEDBPCYCwcBAOCQnr4HaU06PFj1SUioFCRxQrTRFC2om9MkVeM6YB7ognjE@x4Bwqblje1K5pc1gXtQAPTSYdhOOzi3A8XUEcz9cYx1cPyDHvQzleemGOVT/Osb7h4Fgua9eRcoNFbcZqT3hlY6VlUkSElfS3oMy6gexJOpOvWZWIX366PhrCTlzWrn5NBG9H4/IdKBAp64SWxG6l8hxKs0QMUHTEusU71Vh1U6zf94@MvxrLcj93cU1lo4doozcLvCEVH/DjTdgavxIIld8HYyBFnis/@@Lg/QfldtWWwIRxYaVwyuj5iA30ZtWR/tLcmV8NBTt7MPRorefj/SpLhdLsbmSjDv6UuKHdb6AsvwE)
[Answer]
```
#include <iostream>
void main()
{
if (int i = 1)
{
while (std::cout << i << std::endl, i++ < 1000) {}
}
}
```
[Answer]
*Almost* any regular-looking program can do,
(no compiler specification necessary), like:
```
#include <stdio.h>
void main(int argc, char*argv[])
{
if(argc=1000)
while(argc-- && printf("%d ",1000-argc)) {}
}
```
can be formulated with C++ iostream in many different ways:
```
#include <iostream>
void main(int argc, char*argv[])
{
if( ! (argc ^= argc) )
while( argc++<1000 && std::cout.operator<<(argc) ) {
}
}
```
[Answer]
```
#include <fstream>
#include <stdlib.h>
static int write_code(std::string str, std::ofstream out = std::ofstream())
{
if (((
out.open("my-thousand-tmp.cpp"),
out) << str,
out).close(),
system("g++ -Wall -W -O3 my-thousand-tmp.cpp && exec ./a.out")
) {}
}
static int add_semicolons(std::string str, size_t i = 0)
{
while (i < str.size())
if (str[i++] == ':' && str[i-1]++) {}
if (write_code(str)) {}
}
int main()
{
if (add_semicolons(
"#include <iostream>\n"
"using namespace std:\n"
"\n"
"int main()\n"
"{\n"
"\tfor (int i = 1: i <= 1000: i++)\n"
"\t\tcout << i << endl:\n"
"\treturn 0:\n"
"}\n"
)) {}
}
```
I tried to initialize std::ofstream out by passing it as a parameter (i.e. `write_code(str, std::ofstream())` ), but apparently, the copy constructor is private, and an expression like this can't be passed by reference.
[Answer]
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
while(errno++ < 1000 && printf("%d ", errno)){}
}
```
[Answer]
```
#include <stdio.h>
#define __INTMAX_TYPE__ struct C { C(int x) { if (x == 1001?(puts(""),true):(printf("%d ",x),C(x+1),false)) {} } }
#include <stdint.h>
main(){if(intmax_t(1),false){}}
```
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), 57 bytes
This takes advantage that the number of operands is always 1. (Not a codegolf, but I want to golf it...)
Thx to @ceilingcat for replacing printf with `__builtin_printf`.
```
main(int i){while(1001-i&&__builtin_printf("%d ",i++)){}}
```
[Try it online!](https://tio.run/##Sy4o0E1PTv7/PzcxM08jM69EIVOzujwjMydVw9DAwFA3U00tPj6pNDOnJDMvvqAIqCBNQ0k1RUFJJ1NbW1Ozurb2/38A "C++ (gcc) – Try It Online")
# [C (gcc)](https://gcc.gnu.org/), 43 bytes
They are also [posting](https://codegolf.stackexchange.com/a/9245/85052) C answers, I assume?
```
main(i){while(1001-i&&printf("%d ",i++)){}}
```
[Try it online!](https://tio.run/##S9ZNT07@/z83MTNPI1OzujwjMydVw9DAwFA3U02toCgzryRNQ0k1RUFJJ1NbW1Ozurb2/38A "C (gcc) – Try It Online")
[Answer]
I just saw the last comment…
However I believe this is valid C++:
```
#include <cstdio>
int main(int argc, char**) {
while (argc != 1001
and std::printf("%d, ", argc++)) {}
}
```
[compiler explorer](https://godbolt.org/z/cnK3zTrnd)
[Answer]
```
int main(int i)
{
while(printf("%d ",i) && i<=1000 && i++){}
}
```
[Answer]
C++11 based solution using a lambda function:
```
/* golf.cpp */
#include <iostream>
int main() {
if( [] (int from, int to) -> bool {
while(std::cout << from << " " && ++from <= to
|| std::cout << std::endl && false) {}
} (1, 1000) ) {}
}
```
Compiles and works:
```
$ g++ --version | head -n1
g++ (GCC) 4.8.2 20131017 (Red Hat 4.8.2-1)
...
$ g++ -std=c++11 golf.cpp -o golf
$ ./golf
```
Bonus 1: Adjusting the range to be printed is as easy as editing the two parameters of the call.
Bonus 2: Output terminated by a new line.
[Answer]
Your run-o'-the-mill recursion-based answer.
```
#include <iostream>
int main(int i, char *k[]) {
if(
k != NULL && (
i = 0
),
std::cout << i << ' ',
i < 1e3 &&
main(i + 1, NULL)
) {}
}
```
[Answer]
# C++ with templates
```
#include <stdio.h>
#include <stdlib.h>
template<int THOU> void f() { while (printf("%d\n", THOU), f<THOU+1>(), 0) {} }
template<> void f<1001>() { while(exit(0), 0) {} }
int main()
{
while (f<1>(), 0) {}
}
```
Notes:
* Linux version 3.2.0-58-generic (buildd@allspice) (gcc version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5) ) #88-Ubuntu SMP Tue Dec 3 17:37:58 UTC 2013
* 64 bit (amd64) version of Kubuntu
] |
[Question]
[
This is taken from [this question](https://stackoverflow.com/questions/55823298/how-do-i-check-if-a-string-is-entirely-made-of-the-same-substring) (with permission ofcourse). I'll quote:
>
> Create a function which takes a string, and it should return true or
> false based on whether the input consists of ***only*** a repeated character
> sequence. The length of given string is always greater than 1 and the
> character sequence must have at least one repetition.
>
>
>
Some examples:
```
'aa' //true
'aaa' //true
'abcabcabc' //true
'aba' //false
'ababa' //false
'weqweqweqweqweqw' // false
```
Specifically, the check for a string strictly composed of repeating substrings (**Update**) can output any true or false representation, but no error output please. Strictly alphhanumeric strings. Otherwise standard code golf rules. This is Code Golf, so shortest answer in bytes for each language wins.
[Answer]
# JavaScript (ES6), 22 bytes
Returns a Boolean value.
```
s=>/^(.*)\1+$/.test(s)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/Y1k4/TkNPSzPGUFtFX68ktbhEo1jzf3J@XnF@TqpeTn66RpqGemKiugIEaGoq6OuXFJWmcmEoganBrSQpGYLU8ShBMSUtMacYmxqoKoSa/wA "JavaScript (Node.js) – Try It Online")
---
# Without a regular expression, ~~33~~ 29 bytes
Returns either `null` (falsy) or an object (truthy).
```
s=>(s+s).slice(1,-1).match(s)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/Y1k6jWLtYU684JzM5VcNQR9dQUy83sSQ5Q6NY839yfl5xfk6qXk5@ukaahnpioroCBGhqKujrlxSVpnJhKIGpwa0kKRmC1PEoQTElLTGnGJsaqCqEmv8A "JavaScript (Node.js) – Try It Online")
NB: Technically, \$s\$ is converted to a regular expression for *match()*, so the above title is a lie.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~4~~ 3 bytes
```
ġ=Ṁ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRuX/2obcOjpuZHHcuVSopKU5VqQKy0xJziVKXah7s6HzU11D7cOuH/kYW2D3c2/P8frZSYqKQDJMBkUjIEgdkQEQhdnlqIgpRiAQ "Brachylog – Try It Online")
## Explanation
```
ġ=Ṁ Implicit input, say "abcabc"
ġ Split into chunks of equal lengths (except maybe the last one): ["abc","abc"]
= Apply the constraint that all of the chunks are equal,
Ṁ and that there are multiple of them.
```
The program prints `true.` if the constraints can be satisfied, and `false.` if not.
[Answer]
# grep, 19
```
grep -qxE '(.+)\1+'
```
### Test
```
while read; do
<<<"$REPLY" grep -qxE '(.+)\1+' && t="true" || t="false"
echo "$REPLY: $t"
done < infile
```
Output:
```
aa: true
aaa: true
abcabcabc: true
aba: false
ababa: false
weqweqweqweqweqw: false
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 6 bytes
```
²é ¤øU
```
Saved one byte thanks to @Shaggy
[Try it online!](https://tio.run/##y0osKPn//9CmwysVDi05vCP0//9o9cREdR0uIAmhkpIhCMKBioEYsQq6uUEA "Japt – Try It Online")
```
Implicit input, stored in variable 'U'
² U+U, "abcabc" -> "abcabcabcabc"
é Rotate 1 char to the right "abcabcabcabc" -> "cabcabcabcab"
¤ Remove first two chars, "cabcabcabcab" -> "bcabcabcab"
øU Check if U is in the above
```
[Answer]
# Java, ~~25~~ 24 bytes
-1 byte thanks to Olivier Grégoire!
Boring regex answer
```
s->s.matches("(.+)\\1+")
```
[Try it online!](https://tio.run/##VY09b8IwEIZ3/4oTky2Epa6JisQAWyfG0uFibHDq2KnvQoWi/HbXtF2QnvuS7tHb4w03/fmzmIBE8IY@zsJHttmhsXCYu5SCxQhOHjn7eAFS7SLGqQveADFyHbfkzzBU9f/n/QMwX0jN4gAOXgtttqQHZHO1JFdSr9Xp9LJeqdKKvubriX3Qu5zxTpo4Wxzkr1@dUbqmcUq7lPdorvJ4J7aDThM3zVizOETVimUpBbFSqzN/1O1xPfq3/XriBw)
~~*It's just 1 byte longer than the python answer aaaaa*~~ I'm tied now :)
[Answer]
# Excel, 26 bytes
```
=FIND(A1,A1&A1,2)<=LEN(A1)
```
Inputs from A1, outputs to whatever cell you put this formula.
[Answer]
# [R](https://www.r-project.org/), 28 bytes
```
grepl("(.+)\\1+$",scan(,''))
```
[Try it online!](https://tio.run/##K/r/P70otSBHQ0lDT1szJsZQW0VJpzg5MU9DR11dU/O/UmISMlTiAgokgxGQWZ5aCEFIbJCKRLAyMAkCSv8B "R – Try It Online")
Simple Regex version. R is (sometimes) very similar to Python, so this is similar to TFeld's Python 2 regex answer, albeit shorter!
### Question (if anyone knows the answer)
I am still confused why this works, as the substring can be any length and will always work, and still works when I add a letter to the front of a valid string, like "cABABABABAB". If I personally read the regex, I see `(.+)`, which captures any group of any length. And then `\\1+$` which repeats the captured group any number of times until the end.
So why doesn't it capture just "AB" and find that it is repeated until the end of the string, especially since there is no restriction specified as to where the substring can start?
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 9 bytes
```
^(.+)\1+$
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wP05DT1szxlBb5f//xESuRBBOSoYgIAvEA0IA "Retina 0.8.2 – Try It Online") Link includes test cases.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~5~~ 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
I see now that the optimal way is to follow [xnor's method](https://codegolf.stackexchange.com/a/37855/53748)!
```
Ḋ;Ṗw
```
A monadic Link that accepts a list of characters and outputs an integer - the shortest possible length of a repeating slice or zero if none exists. Note that zero is falsey while non-zero numbers are truthy in Jelly.
**[Try it online!](https://tio.run/##y0rNyan8///hji7rhzunlf///z8xKRmKAA "Jelly – Try It Online")**
### How?
```
Ḋ;Ṗw - Link: list of characters, S e.g. "abcabcabc" or "abababa"
Ḋ - dequeue S "bcabcabc" "bababa"
Ṗ - pop from S "abcabcab" "ababab"
; - concatenate "bcabcabcabcabcab" "bababaababab"
w - first index of sublist 3 ^---here! 0 (not found)
```
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 14 bytes
```
$_=/^(.*)\1+$/
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3lY/TkNPSzPGUFtF////xH/5BSWZ@XnF/3V9TfUMDA3@6xYAAA "Perl 5 – Try It Online")
[Answer]
# [Pyke](https://github.com/muddyfish/PYKE), 4 bytes
```
+tO{
```
[Try it here!](https://pyke.catbus.co.uk/?code=%2BtO%7B&input=abcabc&warnings=1&hex=0)
```
+ - input+input
t - ^[1:]
O - ^[:-1]
{ - input in ^
```
[Answer]
# [Python 2](https://docs.python.org/2/), 24 bytes
```
lambda s:s in(s*2)[1:-1]
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHYqlghM0@jWMtIM9rQStcw9n9BUWZeiUKahnpiorqmsoK@fklRaSoXkih24aRkCMIuCdYDFE9LzClGlcAlVZ5aiIKgqhTQTYDYBxb9DwA "Python 2 – Try It Online")
Shamelessly stolen from [xnor's answer](https://codegolf.stackexchange.com/a/37855/38592) to the original question.
---
More intuitive version:
# [Python 2](https://docs.python.org/2/), ~~59~~ ~~55~~ 53 bytes
```
lambda s:s in[len(s)/i*s[:i]for i in range(1,len(s))]
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHYqlghMy86JzVPo1hTP1OrONoqMzYtv0ghEyisUJSYl56qYagDkdaM/V9QlJlXopCmoZ6YqK6prKCvX1JUmsqFJIpdOCkZgrBLgvUAxdMSc4pRJXBJlacWoiCoKgWwsv8A "Python 2 – Try It Online")
---
**Boring regex version:**
# [Python 2](https://docs.python.org/2/), 44 bytes
```
lambda s:re.match(r'(.+)\1+$',s)>0
import re
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHYqihVLzexJDlDo0hdQ09bM8ZQW0Vdp1jTzoArM7cgv6hEoSj1f0FRZl6JQpqGemKiuqaygr5@SVFpKheSKHbhpGQIwi4J1gMUT0vMKUaVwCVVnlqIgqCqFMDK/gMA "Python 2 – Try It Online")
[Answer]
# [J](http://jsoftware.com/), ~~26 25 15~~ 14 bytes
Using xnor method
```
+./@E.}:@}.@,~
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/tfX0HVz1aq0cavUcdOr@a3KlJmfkK6QpqCcmqisgcRLVEZykZAiCChko2EKEEzEE0IXKUwtRkPp/AA "J – Try It Online")
## original (two different approaches)
# [J](http://jsoftware.com/), 25 bytes
```
1<1#.(#%#\)=<\+/@E.&:>"{]
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DW0MlfU0lFWVYzRtbWK09R1c9dSs7JSqY/9rcqUmZ@QrpCmoJyaqKyBxEtURnKRkCIIKGSjYQoQTMQTQhcpTC1GQ@n8A "J – Try It Online")
# [J](http://jsoftware.com/), 26 bytes
```
1<1#.-@#\([:(-:##{.)<\)"{]
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DW0MlfV0HZRjNKKtNHStlJWr9TRtYjSVqmP/a3KlJmfkK6QpqCcmqisgcRLVEZykZAiCChko2EKEEzEE0IXKUwtRkPp/AA "J – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~24~~ 23 bytes
```
StringMatchQ[x__..~~x_]
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P7ikKDMv3TexJDkjMLoiPl5Pr66uIj72fwBQuMRBK03foZpLKTFRSQdEQqikZAiCcKBiUEZ5aiESKi8sV6r9DwA "Wolfram Language (Mathematica) – Try It Online")
```
StringMatchQ[ (*a function that checks if its input (string) matches:*)
x__.. (*a sequence of one or more characters, repeated one or more times*)
~~x_] (*and one more time*)
```
[Answer]
# GNU Bash, 28 bytes
```
[[ ${1:1}${1::-1} == *$1* ]]
```
Save the above script into a file, and run `bash file.sh "string to test"`.
Exit code 0 is truthy and non-zero is falsy. (as all Unix shells would interpret)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
[xnor's method](https://codegolf.stackexchange.com/a/37855/47066) from the previous question appears to be optimal in 05AB1E as well.
```
«¦¨så
```
[Try it online!](https://tio.run/##yy9OTMpM/f//0OpDyw6tKD689P//xKRkCAIA "05AB1E – Try It Online")
or as a [Test Suite](https://tio.run/##yy9OTMpM/V9TVllZ@f/Q6kPLDq0oPrz0v45mzP/ERK5EEE5KhiAgC8QDkeWphSgIAA)
**Explanation**
```
« # append input to input
¦¨ # remove the first and last character of the resulting string
så # check if the input is in this string
```
[Answer]
# PowerShell, ~~23~~ 24 bytes
+1 byte to fully match rules
```
"$args"-match"^(.+)\1+$"
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X0klsSi9WEk3N7EkOUMpTkNPWzPGUFtF6T9QKjEpGYiUAA "PowerShell – Try It Online")
Pretty boring. Based on the other Regex answers. Luckily PowerShell doesn't use `\` as an escape character!
[Answer]
## [C# (Visual C# Interactive Compiler)](https://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 70 bytes
xnor's shameless adaptation (**46 bytes**)
```
s=>(s+s).Substring(1,s.Length*2-2).Contains(s)
```
My non Regex Solution:
```
s=>s.Select((x,y)=>y).Count(z=>s.Replace(s.Substring(0,z+1),"")=="")>1
```
Explanation:
Replace every possible substring that starts at index 0 with an empty string. If the result is an empty string, the string is entirely made of that substring. Since this includes evaluating the entire string with itself, the amount of expected results must be greater than 1.
Example: **abcabc**
Possible substrings starting at index 0:
```
'a', 'ab', 'abc', 'abca', 'abcab', 'abcabc'
```
If we replace them with empty strings
```
Substring Result
'a' => 'bcbc'
'ab' => 'cc'
'abc' => ''
'abca' => 'bc'
'abcab' => 'c'
'abcabc' => ''
```
Since there is a substring other than 'abcabc' that returns an empty string, the string is entirely made of another substring ('abc')
[Try it online!](https://tio.run/##bYuxCsIwFEV3v6JkesFY7KzJIjg56eCcPF4lEBJtErT9@djSSQxc7nDuuRh3GG05Z4/HmAbrH8KE4FTTN7JEqWJ7I0eYAD5i5FKNvD2F7BNMy3alp9NIMFvZrHfYi2nbccEYl3Iu1ZXD5j7YRBfrCXpgWjPO/1gNGlxTm6p@Fb/p9ZPFKF8)
[Answer]
# [Python 3](https://docs.python.org/3/), ~~62~~ ~~60~~ ~~56~~ 54 bytes
*-4 bytes thanx to [ArBo](https://codegolf.stackexchange.com/users/82577/arbo)*
```
lambda s:s in(len(s)//l*s[:l]for l in range(1,len(s)))
```
1. Iterate over all possible prefixes in the string.
2. Try to build the string out of the prefix.
3. Return whether this succeeds with any prefix at all.
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHYqlghM08jJzVPo1hTXz9HqzjaKic2Lb9IIQcorlCUmJeeqmGoA5HX1PxfUJSZV6KRpqGUqKSpyYXgoXPR@EnJEIQmiq4KXaQ8tRAFASX/AwA "Python 3 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-n`, ~~16~~ 13 bytes
-3 bytes thanks to [south](https://codegolf.stackexchange.com/users/110888/south)
For completeness, more or less the same as the other regex answers. Prints `0` for truthy, `nil` for falsey.
```
p~/^(.+)\1+$/
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpclm0km6eUuyCpaUlaboWawvq9OM09LQ1Ywy1VfQhYlCpBTe1ExO5EkE4KRmCgCwQD0SWpxaiIIgeAA)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 10 bytes
*Returns a positive number if truthy and 0 if falsey. If you want a bool output just add `-¡` flag*
```
å+ k@rXÃÊÉ
```
---
```
å+ k@rXÃÊÉ Full program. Implicit input U.
e.g: U = "abcabcabc"
å+ Take all prefixes
U = ["a","ab","abc","abca","abcab","abcabc","abcabca","abcabcab","abcabcabc"]
k@ Filter U by:
rXÃ Values that return false (empty string)
when replacing each prefix in U
e.g: ["bcbcbc","ccc","","bcabc","cabc","abc","bc","c",""]
take ↑ and ↑
U = ["abc","abcabcabc"]
ÊÉ Get U length and subtract 1. Then return the result
```
[Try it online!](https://tio.run/##y0osKPn///BSbYVsh6KIw82Huw53/v8frZ6YqK7DBSQhVFIyBEE4UDEQI1ZBNzcIAA "Japt – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 6 bytes
```
Ṡ€ȯhtD
```
[Try it online!](https://tio.run/##yygtzv7//@HOBY@a1pxYn1Hi8v//f6XEpGQIUgIA "Husk – Try It Online")
I feel like this is one byte more than optimal, but I couldn't find an arrangement that made the explicit composition `ȯ` unnecessary.
# Explanation
```
Ṡ€ Find the argument in the result of applying the following function to the argument
ȯhtD Duplicate the argument, then remove the first and last elements.
```
[Answer]
# Mathematica 11.x, 74 bytes
```
{}!=StringCases[#,StartOfString~~x__/;(x!=#&&StringReplace[#,x->""]=="")]&
```
where, throughout, `#` represents the input string, and
```
StringCases[#,<pattern>]
```
finds substrings of the input string matching the pattern
```
StartOfString~~x__/;(x!=#&&StringReplace[#,x->""]=="")
```
This pattern requires matches, `x`, must start at the start of the string and must satisfy the condition that (1) the match is not the whole input string and (2) if we replace occurrences of the match in the input string with the empty string we obtain the empty string. Finally, comparing the list of matches to the empty list,
```
{}!=
```
is `True` if the list of matches is nonempty and `False` if the list of matches is empty.
Test cases:
```
{}!=StringCases[#,StartOfString~~x__/;(x!=#&&StringReplace[#,x->""]=="")]&["aa"]
(* True *)
{}!=StringCases[#,StartOfString~~x__/;(x!=#&&StringReplace[#,x->""]=="")]&["aaa"]
(* True *)
{}!=StringCases[#,StartOfString~~x__/;(x!=#&&StringReplace[#,x->""]=="")]&["abcabc"]
(* True *)
```
and
```
{}!=StringCases[#,StartOfString~~x__/;(x!=#&&StringReplace[#,x->""]=="")]&["aba"]
(* False *)
{}!=StringCases[#,StartOfString~~x__/;(x!=#&&StringReplace[#,x->""]=="")]&["ababa"]
(* False *)
{}!=StringCases[#,StartOfString~~x__/;(x!=#&&StringReplace[#,x->""]=="")]&["weqweqweqweqweqw"]
(* False *)
```
[Answer]
# Python 3, 84 bytes
```
import textwrap
lambda s:any(len(set(textwrap.wrap(s,l)))<2 for l in range(1,len(s)))
```
Uses `textwrap.wrap` (thanks to [this answer](https://stackoverflow.com/a/48860937/4533885)) to split the string into pieces of length `n` to test each possible length of repeating substring. The split pieces are then compared to each other by adding them to a set. If all of the pieces are equal, and the set is of length 1, then the string must be a repeating string. I used `<2` instead of `==1` because it saves a byte, and the length of the input string was guaranteed to be greater than zero.
If there is no `n` for which repeating substrings of length `n` make up the entire string, then return false for the whole function.
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 73 bytes
*Doesn't use regex.*
```
import StdEnv,Data.List
$s=or[isPrefixOf s(cycle t)\\t<-tl(tails s)|t>[]]
```
[Try it online!](https://tio.run/##VYy7CsIwFEB3vyJDoS1Yv8A61UEoWOiYZrikiVzIQ3Ovj4Lfbiw4CWc5wznaGQjZx/nujPCAIaO/xsRi5PkYHtsOGHY9Em8KamOSSEMyFl9nK6jSi14rrqeJ9w27igEdCarffJBK5ZFhHbWiELJ8mtsfpcofbR1cKDenPndLAI/6J4MDtjH5Lw "Clean – Try It Online")
Defines `$ :: [Char] -> Bool`.
Checks if the given string is a prefix of the repetition of any sub-string taken from the end.
[Answer]
# [Zsh](https://www.zsh.org/), 19 bytes
Outputs via error code:
```
[[ $1$1 = ?*$1*? ]]
```
[Try it online!](https://tio.run/##qyrO@F@ekZmTqlCUmpiikJOZl2qtkJLPVZxaoqCrq6ACEvgfHa2gYqhiqGCrYK@lYqhlrxAb@z81OSNfQcWeKyUfqCCRKxGEgDgpMQlMgCggCaO4AA "Zsh – Try It Online")
However, the challenge did specify "output on stdout":
### [Zsh](https://www.zsh.org/), 22 bytes
Outputs an empty string if true, and a non-empty string for false:
```
<<<${${:-$1$1}/?*$1*?}
```
If the output must be fixed:
### [Zsh](https://www.zsh.org/), 25 bytes
Outputs `0` for true, `1` for false
```
[[ $1$1 = ?*$1*? ]]
<<<$?
```
[Try it online!](https://tio.run/##qyrO@F@ekZmTqlCUmpiikJOZl2qtkJLPVZxaoqCrq6ACEvgfHa2gYqhiqGCrYK@lYqhlrxAby2VjY6Ni/z8lHyidyJUIQkCclJgEJkAUkIRRXAA "Zsh – Try It Online")
---
The heart of these solutions is `?*$1*?`, which is a glob which matches the string in question surrounded by at least one character on each side: `*` is a string of any length, and `?` is a single character. This is an alternate version of xnor's solution, but using globs to match extra characters rather than removing leading and trailing characters.
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), 36 bytes
```
#define f(x)(x+x).find(x,1)<x.size()
```
[Try it online!](https://tio.run/##bZBNDsIgEIX3nGJCF0KsGrcV60XcIKUNiUItVInGs1faGu2PL5MALx9vYERZrgohmkhpca4zCUwZ6yrJLyn6ecFRuhg6NymcqdImymSutISceEr80tN1OGbEx1vK/NqqhyS0UdrBhSsNhMITQZAw2jqwLkuSPol1@08fULqsHew/cCvMOY5hrM3GVbUcIjNmhpxEXz9wjvxJyfnZjpkpNWPu8jqqgA@Z1w51a24qILx2Bjwk/cfpN6QbijBhFmjYizEg7cDhALh9PA43cReN6RRcHPVih17NGw "C++ (gcc) – Try It Online")
Another port of xnor's solution. Uses a macro to expand the argument into the expression. The argument is assumed to be of type `std::string`.
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 11 bytes
```
&/1_=':#'=:
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs1LTN4y3VbdSVre14uJKi1ZKTEqGIKVYCDcRzkhCsICyANfzEKQ=)
*Thanks to PyGamer0 for the "check if all the values of a list are equal" code snippet!*
Return `1` for true and `0` for false
Explanations:
```
&/1_=':#'=: Main function. Takes implicit input with : on the right-most
= Group the characters into a dictionary
#' Get the length in the values of each of the keys
(The values are the occurence positions of the characters in the string)
: Apply everything on the left to the right
=' Check if the values of the values in the dictionary are equal
1_ Weed out the first one (as we know it will always be false)
&/ Get the minimum value
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `r`, ~~5~~ 4 bytes
```
dḢṪc
```
*-1 byte by porting [xnor's answer](https://codegolf.stackexchange.com/questions/37851/string-prototype-isrepeated/37855#37855) from the other question*
[Try it online!](https://vyxal.pythonanywhere.com/#WyJyQSIsIiIsImThuKLhuapjIiwiIiwiJ2FhJ1xuJ2FhYSdcbidhYmNhYmNhYmMnXG4nYWJhJ1xuJ2FiYWJhJ1xuJ3dlcXdlcXdlcXdlcXdlcXcnIl0=)
Concatenates the string to itself, removes the first and last characters, then checks if the input string is in that.
[Answer]
# QlikView Variable, 27 bytes
This should be defined as a variable, which then allows you to pass parameters, e.g. `$1` as your input value.
It returns `0` or `-1` (equivalent to QlikView's `TRUE()` function).
```
=substringcount($1&$1,$1)>2
```
] |
[Question]
[
>
> As of 27/12/20, the challenge is over as no new answers were posted on the 26th. With an astounding 55 points (and 21 answers), the winner is [pppery](https://codegolf.stackexchange.com/users/46076/pppery)!
>
>
> A quick shout out to the top 5 scorers as well:
>
>
> * 1st. [pppery](https://codegolf.stackexchange.com/users/46076/pppery) with 55 points across 21 answers
> * 2nd. [tsh](https://codegolf.stackexchange.com/users/44718/tsh) with 50 points across 21 answers
> * 3rd. [SunnyMoon](https://codegolf.stackexchange.com/users/98140/sunnymoon) with 21 points across 6 answers
> * 4th. [NieDzejkob](https://codegolf.stackexchange.com/users/55934/niedzejkob) with 17 points across 4 answers
> * 5th. [pxeger](https://codegolf.stackexchange.com/users/97857/pxeger) with 16 points across 7 answers
>
>
> A full table of everyone's daily scores can be found below. Empty cells indicate no answer
>
>
>
---
This challenge will function somewhat like an [answer-chaining](/questions/tagged/answer-chaining "show questions tagged 'answer-chaining'") question, in that new answers will (somewhat) depend on old answers. However, this is (as far as I can tell) a unique form of [answer-chaining](/questions/tagged/answer-chaining "show questions tagged 'answer-chaining'"), so be sure to read the entire challenge if you'd like to take part.
Normally, [answer-chaining](/questions/tagged/answer-chaining "show questions tagged 'answer-chaining'") challenges work in increments of answers. Each new answer is related to the previous answer, and so on. However, in this challenge, we will change the increments from single answers to single days.
Here's a step-by-step breakdown of how the challenge will work:
* The challenge will be posted at exactly 00:00UTC
* From then until 23:59UTC, users may post answers that complete the **task** (specified below) while also following some of the **restrictions** (also specified below). Each answer will include:
+ A language available to be used
+ A program in that language which completes the **task**
+ A single **restriction** on the source code of new answers
* At 00:00UTC, the **restrictions** will update from those listed in the body of the challenge, to those listed by answers posted the previous day.
* Repeat the previous 2 steps until the challenge ends.
## Task
All answers, regardless of when they were posted, must output the number of days the challenge has been going at the time of posting. So the first set of answers will output **1**, those posted on the second day **2**, third day **3** etc.
## Restrictions
For the answers posted on the first day, the first set of restrictions are:
* You must include the `0x10` byte in your source code
* You must have an even number of bytes in your source code
* You must only use even bytes in your source code
When you choose your restriction, you may only impose a restriction on the *source code*. This can be as weird as you like (e.g. it must be shaped like unfolded Hexagony code), or a basic as "cannot use this byte", but you may only restrict the source code, rather than e.g. language used. As a general rule, if a challenge including this restriction would be tagged [restricted-source](/questions/tagged/restricted-source "show questions tagged 'restricted-source'") or [source-layout](/questions/tagged/source-layout "show questions tagged 'source-layout'"), it's good to go.
## Scoring
**New answers do not have to follow all of the restrictions.** Instead, they must choose between 1 and all the restrictions to follow. Each answer is worth a number of points equal to the number of restrictions it follows. Your score is the total for all of your answers. Highest score at the end of the challenge wins.
## Ending criteria
The challenge ends when an entire day passes with no new answers, as the restrictions will be updated to nothing.
## Formatting
Please format your answer in the following way:
```
# Day <N>. <Language>, score <X>
<code>
This follows the restriction(s):
- <restriction 1>
etc.
- <restriction X>
Answers posted tomorrow may use the restriction that <restriction>
---
<Anything else you want to include>
```
## Rules
* You may only post 1 answer per day
* You may only specify 1 restriction in your answer. This restriction may be impossible (as people do not *have* to use it), and may be the same as another answer posted that day. It may also be the same as a restriction from a previous day, but I encourage you to choose more original restrictions over reusing ones.
* Your score only counts *unique* restrictions used. If the same restriction is specified by 3 previous day answers, you may only count it as 1.
* **You may use any language that hasn't been used on a previous day.** You may use a language that has already been used this day, so multiple answers on a specific day can use the same language.
* Byte count has no bearing here, so you are under no obligation to golf your code.
* If restrictions involve specific bytes to be avoided, included etc., you may use any *pre-existing* code page of your choice, so long as it is supported by your language
* You may submit either a full program or a function, so long as it operates under our [standard output formats](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods)
* Be sure to pay attention to *when* you are posting your answer. If it is posted at 00:00UTC, it is the first answer for the next day, not the last answer for the previous day.
* Times will be measured using SE's time and dating for posts, which can be seen by hovering your mouse over posts which still have "posted X hours ago" or "posted yesterday"
* Different versions of languages, e.g. Python 2 and Python 3 *are* different languages. As a general rule, if the different versions are both available on Try It Online, they are different languages, but keep in mind that this is a general rule and not a rigid answer.
+ Regardless of whether they're both on TIO, minor versions of a language (e.g. Python 3.4 and Python 3.8) are *not* different languages.
Good luck!
---
### Daily scores
| Day | Redwolf Programs | Lyxal | Bubbler | Jonathan Allan | Razetime | tsh | NieDzejkob | Noodle9 | SunnyMoon | pppery | user | PkmnQ | Ramillies | pxeger |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| Points | 9 | 3 | 3 | 3 | 3 | 50 | 17 | 2 | 21 | 55 | 6 | 11 | 6 | 16 |
| Answers | 2 | 1 | 1 | 1 | 1 | 21 | 4 | 1 | 6 | 21 | 1 | 2 | 1 | 7 |
| 1 | 3 | 3 | 3 | 3 | 3 | 3 | 3 | 2 | 3 | 3 | | | | |
| 2 | 6 | | | | | 6 | 5 | | 7 | 7 | 6 | 5 | 6 | |
| 3 | | | | | | | 5 | | 6 | 6 | | 6 | | |
| 4 | | | | | | 2 | 4 | | 2 | 4 | | | | |
| 5 | | | | | | | | | 1 | 2 | | | | |
| 6 | | | | | | 2 | | | | | | | | |
| 7 | | | | | | 1 | | | | 1 | | | | |
| 8 | | | | | | 2 | | | | 2 | | | | |
| 9 | | | | | | | | | 2 | 2 | | | | |
| 10 | | | | | | 2 | | | | 1 | | | | |
| 11 | | | | | | 2 | | | | 2 | | | | |
| 12 | | | | | | 2 | | | | 2 | | | | 2 |
| 13 | | | | | | 3 | | | | 3 | | | | |
| 14 | | | | | | 1 | | | | 1 | | | | 1 |
| 15 | | | | | | 3 | | | | 3 | | | | 3 |
| 16 | | | | | | 3 | | | | 2 | | | | 3 |
| 17 | | | | | | 3 | | | | 3 | | | | 3 |
| 18 | | | | | | 2 | | | | 2 | | | | |
| 19 | | | | | | 2 | | | | 2 | | | | |
| 20 | | | | | | 2 | | | | | | | | 2 |
| 21 | | | | | | 2 | | | | 2 | | | | 2 |
| 22 | | | | | | 3 | | | | 3 | | | | |
| 23 | | | | | | 2 | | | | 2 | | | | |
| 24 | | | | | | 2 | | | | | | | | |
[Answer]
# Day 2. [JavaScript (V8)](https://v8.dev/), score 6
```
e=>(2)//
//[]{}<//
//)2(>=g
//VVVVVVVVV//
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNEts/ifZvufK9XWTsNIU1@fS18/Ora61oYJzNQ00rCzTQcywmBAX/9/QVFmXolGmoam5n8A "JavaScript (V8) – Try It Online")
This follows the restrictions:
* The code uses each of `(){}[]<>` at least once
* It uses a byte which is a prime factor of 420 in its source code (`0x02`)
* The code also performs the task if reversed
* The sum of each byte is a number in the Fibonacci sequence (2584)
* It uses one vowel (`e`)
* It works when `//#` is inserted at the start
Answers posted tomorrow may use the restriction that the program's length is no more than its lowest byte (i.e., a program with a `0x02` byte couldn't be more than two bytes).
[Answer]
# Day 5, [A](https://esolangs.org/wiki/A), score 2
```
ANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANANAN
```
(The string `AN` repeated 18724 times.)
Another Unary variant, except this time the [reference transpiler](https://web.archive.org/web/20110319032415/http://www.sksk.info/a.html) actually cares that you type A and silently ignores all other characters. ROT13-ing this replaces each `AN` with a `NA`, which contains the same number of `A`s, so is treated identically. Rotating it by any other number will result in there being no `A`s, and thus make the code do nothing.
Satisfied restrictions:
* Your program must still work after being passed through ROT13, and must break after being passed through ROTn, for any n not divisible by 13.
* Answers today may follow half or less of all the other restrictions.
Answers tommorrow may use the restriction that they satisfy at most one restriction from days 1-5.
To be clear, this does include the original restrictions posted in the question body (that applied to day 1 answers), and does include restrictions posted in Day 4 answers, but does not include restrictions posted in Day 5 answers (and thus does not include itself)
[Answer]
# Day 3. [Rust](https://www.rust-lang.org/), score 5
```
fn/**/main(){print!("3");}//#$%2579?@AABCDEFGHIJKLMNOPQRTUWXYZ^`gjkxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx//};)1+ezisu/**/sa)(parwnu.)(tsrif.tupni*-ezisu/**/sa)(parwnu.)(tsal.tupni*==)(nel.tupni(!tressa;)(puded.tupni;)(tros.tupni;))y==x|)y,x(|(lla.))(ver.)(reti.senil(piz.)(reti.senil(!tressa;)(tcelloc.)'n\'b==x|x&|(tilps.tupni=>_<ceV:senil/**/tel};)s=!)(nel.)(>>_<teShsaH<::tcelloc.)s(yb_pets.)(reti.]..i[tupni(!tressa;)s=!)(nel.)(>>_<teShsaH<::tcelloc.)(reti.]s+s*i..s*i[tupni(!tressa{s..0/**/ni/**/i/**/rof;))(nel.tupni==s*s(!tressa;ezisu/**/sa)(trqs.)46f/**/sa)(nel.tupni(=s/**/tel;)(parwnu.)tupni&(8ftu_morf::rts::dts;)(parwnu.)tupni/**/tum&(dne_ot_daer.)(nidts::oi;)(wen::ceV=tupni/**/tum/**/tel{)(niam/**/nf;teShsaH::snoitcelloc::dts/**/esu;}*::edulerp,fles{::oi::dts/**/esu
```
[Try it online!](https://tio.run/##jVFrVxMxEP0tRSzJglkBn1mCIqL4fr8fS@jOajTNrplEWtr@9posW0o5x6P5MOfM5M69M3esRzedliZNkrQvlSF0VFtlXIcsbS7RbJKmF5Yvbly9fvPW7Z2dO7t39@7d33/w8NHjJ0@fPX/x8vWbd@8/fPx68O3Hz8H/vjSdZHR9FY4V@qiKkpJa2iPjGSUOrSqZ87VRyaW/QaRuEUJQYqDNSMdZQJRZwPoCipNqyJytcJbQoRCDMR2uDciYaC0ZpeQ32EBrwSmGYJQmtTpeLMyZXQ@0rnqMrpjPK4eRa9AdE6d03UqI7XyrB2950xhnd6DDvig6J6NSsh0QDl59R7m/xfkpIZLhYV6Dw5n0F8bUp3Ob/Zum7cVVTBRjISxSjJCxy3Eso2Jsgq3KYMzcSCEwwVPNhSM4@yvMd@VaOSvM3RfYbpvNb9X8dMmN0vm8X9mSc@uQ88LheVDT6/tdUhjIK5cXsjmKUUVsqOIZj8BwHqwVZxtazVGEyiYzZdbawjmaSrXONKrxH9Bnk4RzKLwGW6@VGnAUJc4iptM/ "Rust – Try It Online")
This follows the restrictions:
* Your program, when reversed, must check whether its input is compliant with all the restrictions that your program declares and follows, except for restrictions that are undecidable - [Try it online!](https://tio.run/##jVRpc9MwEP0t5UgltyiUG7kqlLPcd7kxbrymAkU2WpkmTfrby1pVzhmG5oMyu3r73h5euQb98XGD0E2SLvpCSl1JOUIw5XrtwDQFSJkcpfOIXmUM9LyuLEq5k@P@G/Bpadv7fq4t4yMDPlhN@NO2brzahZ6UFg4YT1sJYmqhwkFeZL7KwBasMx/ARWMPXF4TPqiid1KWrupnjS9vsM4yKGqiYuFGGCD6HFtfee0KF/jb@YmjQX0IaY4Izq8wTFCpuSCelpULeZwk054XhcDRJCBgP@sEhaBjDb8K7cFRMbEzUm7GtmxmW1vkD7QrCnm6RCHENBY91NnekOFpaI5itUZbQEmtJUQsAWujPRt3BuOBUnurX@zqlJDN9EPgRPpQ14sOB3@oDSI3ho3ZYH3IW64hNSZKVG0ro1FA0dRsqbKTVJVKopUjBUxnNTeECxFRavcvyNoG1dvtDk77@/Xzx/dvnz5@eP/u7etXL188f/b0yeNHOw8f3L9398729u1bN69fvXT@3Nlu9yjlZy6fYSvealePOLM677eqtjw@Xvica6ctVUbgkMnZc@cvXb1@89bt7e07d@/df/Bw59HjJ0@fPX/x8tXrt@/ef/j46dv3Hz9/nTrhkMnGGhxqbMInnHNW5@7ANoIzj06Xwje11cmFf0FyExFKURkQLarMAWKeEpb2uDjxkuVdhRODD5UajPlwfUCjNiYXnLM/4IjWgdcCwWrDan246Jgx@x4YU/UEX7VfVvdarkFnzLw2dZRQW9lmD3ZlCGxz92CoXlQrJ6lytkUID2/2Md/ZlHJKiGy4l9XgcSL9ldbt81Jl/6eJsbSmCa0bHYsUI1rii2HqerryriqpMbNGKkVPxFRzYQje/ab8rlwrJ45Z9xXGatPZrMJNh90ofZP1K1dK6Tw9ooXHZVCIbfodVljIKp8VeRiK1UUbULVjPABLjzHsqvmAqLnwOaexLfSI2krHzgTV9h6wSY8SKWmPDbh6vTSAo1ZiHvEX "Rust – Try It Online") (errors are reported by panicking)
* Your source code must form a valid UTF-8 stream.
* The bytes of the program, when sorted and duplicates removed, are all consecutive.
* The program is palindromic line-wise (as there's only one line)
* The program has a square number of characters. When formatted in a square grid, each row and column contains at least one duplicated character:
### Restriction for tomorrow
When the bytes of your program are interpreted as a big endian integer, it must be prime:
```
from Crypto.Util.number import *
lambda your_code: isPrime(bytes_to_long(your_code))
```
[Answer]
# Day 1. [Jelly](https://github.com/DennisMitchell/jelly), score 3
```
0‘ḷ“ Ñ
```
[Try it online!](https://tio.run/##y0rNyan8/9/gUcOMhzu2P2qYo3B44v//AA "Jelly – Try It Online")
The bytes are `[48, 252, 218, 254, 32, 16]` in Jelly code page.
Fulfills these three restrictions:
* You must include the `0x10` byte in your source code
* You must have an even number of bytes in your source code
* You must only use even bytes in your source code
## Tomorrow's restriction
* The code should use each of `(){}[]<>` at least once.
[Answer]
# Day 1. [dotcomma](https://github.com/Radvylf/dotcomma), score 3
```
.,
```
(There are two `0x10` bytes at the end)
[Try it online!](https://radvylf.github.io/dotcomma/?p=WyIuLFx1MDAxMFx1MDAxMCIsIiIsMCwwXQ)
This follows the restrictions:
* You must include the 0x10 byte in your source code
* You must have an even number of bytes in your source code
* You must only use even bytes in your source code
Answers posted tomorrow may use the restriction that each byte must be higher than the last (i.e., `20 2a 30 31` would be valid, but not `00 01 00 03`).
[Answer]
# Day 1. [Keg](https://github.com/JonoCode9374/Keg), score 3
```
24<#„22| „
```
[Try it online!](https://tio.run/##y05N///fyMRG@VHDPCOjGgUFIK3w/z8A "Keg – Try It Online")
The joys of having a custom code page and a parser that doesn't exactly ignore comments. `2` is less than `4`, so it pushes 1 and autoprints it. The mess after the comment is a string, which the parser tries to parse even though it's in a comment.
This follows all of the day 1 restrictions
## Tomorrow's Restriction
* Byte values must be a multiple of 69.
[Answer]
# Day 2, Lenguage, score 7
Program has a ton of unprintable characters. As a hex dump:
```
00000000 29 28 7b 68 7d 6a 5b 6c 5d 3c 6d 3e 41 00 01 00 |)({h}j[l]<m>A...|
00000010 01 00 01 00 01 00 01 00 01 00 01 00 01 00 01 00 |................|
*
000014f0 01 00 01 00 01 00 01 02 03 02 03 02 03 02 03 02 |................|
00001500 03 02 03 02 03 02 03 02 03 02 03 02 03 02 03 02 |................|
*
00002020
```
8224 bytes of code, equivalent brainfuck `>++.+`, outputting the character with code point 2.
Satisfies these restrictions:
* The code should use each of `(){}[]<>` at least once
* The code also performs the task if reversed.
* You must use any of the following bytes at least once in your code: `0x02, 0x03, 0x05, 0x07` (I use `0x02` and `0x03`)
* The sum of the byte values in your program should be a Fibonacci number (it's 10946, the 21st Fibbonacci number)
* The procedure of repeatedly removing pairs of odd byte, even byte (next to each other; in that order) must remove every byte of your code. That is, if you replaced each odd byte by A and each even byte by B, the sed script :a; s/AB//g; ta must produce no output (code consists purely of alternating odd and even characters)
* You code must include at least one vowel, either uppercase or lowercase i.e. matches /[aeiouAEIOU]/
* Your program should work when //# is inserted onto the start of it. (Adding `//#` adds 3 bytes, changing the last `+` in the brainfuck to a `<`, where it still does nothing.)
Answers posted tomorrow may use the restriction that they are [pristine](https://codegolf.stackexchange.com/q/63433/46076).
[Answer]
# Day 1. [MAWP](https://esolangs.org/wiki/MAWP), score 3
```
tt:
```
[Try it!](https://8dion8.github.io/MAWP/v1.1?code=tt%3A%10&input=)
There's a `0x10` character at the end.
This follows the restrictions:
* You must include the 0x10 byte in your source code (last char)
* You must have an even number of bytes in your source code (4)
* You must only use even bytes in your source code (`116 116 58 16`)
## Tomorrow's restriction:
You must use a byte which is a prime factor of 420 in your source code. `(2,3,5,7)`. To be more specific, use any of them at least once.
[Answer]
# Day 1. [Jelly](https://github.com/DennisMitchell/jelly), score 3
```
Ñ€PP
```
This follows the restrictions:
* You must include the 0x10 byte in your source code
* You must have an even number of bytes in your source code
* You must only use even bytes in your source code
Answers posted tomorrow may use the restriction that the code also performs the task if reversed.
---
**[Try it online!](https://tio.run/##y0rNyan8///wxEdNawIC/v8HAA "Jelly – Try It Online")**
The four, even, bytes are `0x10 0x0c 0x50 0x50` (`16 12 80 80`) in Jelly's [code-page](https://github.com/DennisMitchell/jelly/wiki/Code-page).
### How?
`0x10` (`Ñ`) is a little hard to use if we cannot use odd bytes, since the newline is a reference to an odd byte, `0x7f` (`¶`), while `Ñ` is an instruction to call the next, and hence only, line of source code as a monad. Luckily `0x0c` (`€`) is an even byte which, when given an integer will implicitly make a list from one up to that integer before it performs the provided instruction on the each of the list's elements, and a program's implicit input is zero, so `€` performs no recursive calls. Lastly the product of an empty set is one.
```
Ñ€PP - Main Link: no arguments
€ - for each (of implicit range of implicit input, 0, = []):
Ñ - call the next link (ÑƇPP) as a monad
P - product -> 1
P - product -> 1
```
[Answer]
# Day 1, Unary, score 3
```
```
Code consists of 84 `0x10` bytes. Equivalent brainfuck code is `+.`, producing the character with code point 1.
This follows the restrictions:
* You must include the 0x10 byte in your source code
* You must have an even number of bytes in your source code
* You must only use even bytes in your source code.
Answers posted tomorrow may use the restriction that there must be 3 or fewer distinct bytes used.
[Answer]
# Day 2, Free Pascal, score 6
```
begin write(2) end.
!"#$%&'()*+,-./0123456789:;?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
Some more fuzzy texts. So the bytes sum would be a Fibonacci number...
.dne )2(etirw nigeb
```
```
00000000: 0a62 6567 696e 2077 7269 7465 2832 2920 .begin write(2)
00000010: 656e 642e 1a0a 0102 0304 0506 0708 090a end.............
00000020: 0b0c 0d0e 0f10 1112 1314 1516 1718 191a ................
00000030: 1b1c 1d1e 1f20 2122 2324 2526 2728 292a ..... !"#$%&'()*
00000040: 2b2c 2d2e 2f30 3132 3334 3536 3738 393a +,-./0123456789:
00000050: 3b3c 3d3e 3f40 4142 4344 4546 4748 494a ;<=>?@ABCDEFGHIJ
00000060: 4b4c 4d4e 4f50 5152 5354 5556 5758 595a KLMNOPQRSTUVWXYZ
00000070: 5b5c 5d5e 5f60 6162 6364 6566 6768 696a [\]^_`abcdefghij
00000080: 6b6c 6d6e 6f70 7172 7374 7576 7778 797a klmnopqrstuvwxyz
00000090: 7b7c 7d7e 0a53 6f6d 6520 6d6f 7265 2066 {|}~.Some more f
000000a0: 757a 7a79 2074 6578 7473 2e20 536f 2074 uzzy texts. So t
000000b0: 6865 2062 7974 6573 2073 756d 2077 6f75 he bytes sum wou
000000c0: 6c64 2062 6520 6120 4669 626f 6e61 6363 ld be a Fibonacc
000000d0: 6920 6e75 6d62 6572 2e2e 2e0a 1a2e 646e i number......dn
000000e0: 6520 2932 2865 7469 7277 206e 6967 6562 e )2(etirw nigeb
000000f0: 0a .
```
* The code should use each of (){}[]<> at least once.
* use a byte which is a prime factor of 420 in your source code. (2,3,5,7).
* the code also performs the task if reversed.
* at least one vowel, either upper or lower case
* when //# is inserted onto the start of them
* The sum value of each (unsigned) bytes used in your program should be a number in Fibonacci sequence.
---
Free Pascal compiler just treat the byte `^Z` (`#$1A`) as the end of file. And ignore any following bytes... There is a `^Z` after `end.`. So you may write anything as you like.
---
Day 3:
Your source code as bytes stream should be able to decode as UTF-8.
[Answer]
# Day 2. [99](https://github.com/TryItOnline/99), score 7
Introducing my newest invention - A great rocket, *uh*, thingy... (Does this even look like a rocket?)
```
=>=>=>=>=>e
98989 98989 98989
98989 9 98989 9 98989
98989()<{>}~[]lO
98989 9 98989 9 98989
98989 98989 98989
=>=>=>=>=>e
```
[Try it online!](https://tio.run/##s7T8/9/WDgZTuSwtgFABiYSJKKDQEFENTZtqu9q66Ngcf3zKUIxDskzh/38A)
This follows the restrictions:
* The code should use each of `(){}[]<>` at least once. [They are all in the middle of the ship]
* The code also performs the task if reversed. [The ship becomes weird though. [Try it online!](https://tio.run/##s7T8/18h1c4WBrksLYBQAYmEiSig0Fz@ObHvGpqi62rtqm00NfCpxDQR2cL//wE "99 – Try It Online")]
* You must use any of the following bytes at least once in your code: `0x02, 0x03, 0x05, 0x07`[`` represents `0x02`; `0x02` is the heart of the ship :P]
* The sum of the byte values in your program should be a [Fibonacci number](https://oeis.org/A000045) [Adds up to 6765]
* The procedure of repeatedly removing pairs of odd byte, even byte (next to each other; in that order) must remove every byte of your code. That is, if you replaced each odd byte by `A` and each even byte by `B`, the sed script `:a; s/AB//g; ta` must produce no output [I have not used sed, but I used 05AB1E to check this rule]
* You code must include at least one vowel, either uppercase or lowercase i.e. matches `/[aeiouAEIOU]/` [Uses `e` & `O`]
* Your program should work when `//#` is inserted onto the start of it. [99 just ignores that. [Try it online!](https://tio.run/##s7T8/19fX9nWDgZTuSwtgFABiYSJKKDQEFENTZtqu9q66HcNTbE5/vhUopiIZJ/C//8A "99 – Try It Online")]
Since my answer is palindromic line-wise, answers posted tomorrow may use the restriction that their programs may be palindromic line-wise :)
---
Random fact: I spent hours focusing on the aesthetics of the program just to make it look like a spaceship or something.
# How does a rocket print 2?
Well, rockets in the 99 universe care only about 9's and whitespaces.
Without everything not 9 or not a whitespace, the program looks like this:
```
999 999 999
999 9 999 9 999
999
999 9 999 9 999
999 999 999
```
Read the [99 spec](https://codegolf.stackexchange.com/questions/47588/write-an-interpreter-for-99/) for going in detail with the program. Here is a weird explanation anyway:
```
999 999 999 # Set 999 to 999-999=0
999 9 999 9 999 # Set 999 to 9-0+9-0=18
999 # Print 999/9 => 2
999 9 999 9 999 # Set 999 to 18 again for in this case no reason
999 999 999 # Set 999 to 0-0=0 again AGAIN for no reason
```
[Answer]
# Day 4, [Bubblegum](https://esolangs.org/wiki/Bubblegum), score 2
Another 1 byte answer. xxd dump as:
```
00000000: 15
```
[Try it online!](https://tio.run/##SypNSspJTS/N/f/fAAqsFAxNFRT@/wcA "Bubblegum – Try It Online")
* deleting characters from the program cannot result in a program in the same language that prints 4 [Empty program does not print 4]
* Your code must be at least 50% control characters [100% Control characters!]
---
Day 5: Any source code with edit distance 1 to your source code (by inserting 1 byte / deleting 1 byte / replacing 1 byte) should not fit this questions requirement (print 5) in the same language.
[Answer]
# Day 1. [Ruby](https://www.ruby-lang.org/), score 3
```
p 4>>2
""
```
[Try it online!](https://tio.run/##KypNqvz/v0DBxM7OiEtJQOn/fwA "Ruby – Try It Online")
A `\u0010` in quotes.
---
Next day:
The sum value of each (unsigned) bytes used in your program should be a number in [Fibonacci sequence](https://oeis.org/A000045). (0, 1, 2, 3, 5, 8, 13, ...)
[Answer]
# Day 2, Scala 3, score 6
```
@main def m=print{2}//S[]<>//(2)tnirp=m fed niam@
```
[Try it online!](https://scastie.scala-lang.org/ey4snfasQayXZmsshHParQ)
This follows the restrictions:
* The code uses each of `(){}[]<>` at least once
* It uses a byte which is a prime factor of 420 in its source code (0x07)
* The code also performs the task if reversed
* The sum of each byte is a number in the Fibonacci sequence (4181)
* It uses at least one vowel (a, e, and i)
* It works when `//#` is inserted at the start
Answers posted tomorrow may use the restriction that the bytes of the program, when sorted and duplicates removed, are all consecutive, e.g. `0x03` `0x04` `0x03` `0x02` and `0x00` are valid, but not `0x00` `0x02` `0x03`.
[Answer]
# Day 2. [Befunge-98 (PyFunge)](https://pythonhosted.org/PyFunge/), score 5
```
\x07$'.269:@krsu{
```
[Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//9nV1HXMzKztHLILiourf7/HwA "Befunge-98 (PyFunge) – Try It Online")
This follows the restrictions:
* Each byte in your answer must be strictly higher than the last (`07 24 27 2e 32 36 39 3a 40 6b 72 73 75 7b`)
* The code also performs the task if reversed - [Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//@vLi0uynawsjQz0lNXYf//HwA "Befunge-98 (PyFunge) – Try It Online")
* You must use any of the following bytes at least once in your code: `0x02, 0x03, 0x05, 0x07` (`07` is present)
* The sum of the byte values in your program should be a Fibonacci number (987)
* Your code must include at least one vowel (`u`)
Answers posted tomorrow may use the restriction that your program, when reversed, must check whether its input is compliant with all the restrictions that your program declares and follows, except for restrictions that are undecidable. By Rice's theorem, the decidability condition excludes restrictions that ask about the behavior of the program on an infinite set of inputs, including my restriction.
---
### How does it work?
The `\x07` byte reflects the execution flow, converging with the control flow of the reversed code. `{` creates a new entry on the stack of stacks, to make `u` a valid command and satisfy the vowel restriction. `s` overwrites the next letter (`r`), this pair of bytes is used to increase the byte sum and make a Fibonacci number reachable.
`k` skips over the `@`, then `:96` pushes some garbage onto the stack. `2.` prints the 2. We would now like to reflect off of the `\x07` again to reach the `@`, but we must skip the `.` to avoid printing any garbage. This is accomplished by `'`, which pushes the ASCII value of the next byte instead of executing it, and the `$` to the left is a dummy instruction to be skipped over.
### Additional restrictions considered
I tried to make the `//#` restriction work. `#` would skip the `\x07`, so I had to find a way of composing skips and reflections to achieve what `\x07$'` does now. This conflicted with the strictly-increasing restriction. I also considered not skipping the output command at all, and instead switching to character-based I/O, hoping to output a whitespace character on the second round. I couldn't obtain the necessary ASCII values, though.
Another potential variant was to output and exit at the same time with `q`, but since `2` must be before `q` in the code, a skipping maneuver similar to `@k` would be necessary. There is no suitable byte after `q`, though.
The even/odd repeated removal restriction also cannot be used, as we would need an even byte after `{`, and none are suitable (in general, undefined bytes reflect).
[Answer]
# Day 4, DOS COM file (dosbox), score 4
```
00000000: 8a16 2b01 be0f 01b9 0a00 3014 46e2 fb89 ..+.......0.F...
00000010: 2432 873a fe12 f007 1700 0000 0000 0000 $2.:............
00000020: 0000 2233 3333 3435 3433 3533 .."333454353
```
* programs should contain at least 3 previous programs already submitted to this post ([contains 6](https://codegolf.stackexchange.com/questions/215883/quickly-group-together/215981?noredirect=1#comment504584_215981))
* The bytes of your program interpreted as a big endian integer must be prime
* Your code must be at least 50% control characters (0x00 to 0x1F, 0x7F to 0x9F).
* deleting characters from the program cannot result in a program in the same language that prints 4
Restriction for tomorrow: program must still work after being passed through ROT13, and must break after being passed through ROTn, for any n not divisible by 13.
---
Assembly code:
```
BITS 16
ORG 0x100
mov dl, [end-1] ; if any byte is removed, this pointer will break
mov si, encrypted ; moreover, any interference early enough will stop
mov cx, encrypted.end - encrypted ; the XOR loop from working properly
.decrypt: ; either way, execution eventually hits an illegal opcode
xor [si], dl
inc si
loop .decrypt
encrypted:
mov dx, .msg
mov ah, 9
int 0x21
ret
.msg:
db '4$'
.end:
times 10 db 0
db '333454353'
end:
```
Postprocessing script:
```
from Crypto.Util.number import *
with open('gt4.bin', 'rb') as f:
data = bytearray(f.read())
for i in range(15, 25):
data[i] ^= data[-1]
for b in range(256):
data[-10] = b
if isPrime(bytes_to_long(data)):
break
else:
raise hell
control = 0
for byte in data:
if byte in range(0, 0x20) or byte in range(0x7F, 0xA0):
control += 1
print(control / len(data))
with open('gt4.com', 'wb') as f:
f.write(data)
```
[Answer]
# Day 4. [!@#$%^&\*()\_+](https://github.com/ConorOBrien-Foxx/ecndpcaalrlp), score 2
```
333454333@
```
[Try it online!](https://tio.run/##S85ILErOT8z5//9dQ8v//wA "Charcoal – Try It Online")
Prints an end of transmission, [as it is allowed to output characters instead of integers](https://codegolf.meta.stackexchange.com/a/4719/98140).
This follows the following restrictions:
* programs should contain at least 3 previous programs already submitted to this post [`333454353` altogether contains 6 programs: 5 `3`'s and 1 `333454353`]
* Your code must be at least 50% control characters (0x00 to 0x1F, 0x7F to 0x9F). [10 Control codes, 10 other]
Answers tommorow may follow half or less of all the other restrictions. (as I did, :P)
---
[Answer]
# Day 9, [///](https://esolangs.org/wiki////), score 2
```
9
```
[Try it online!](https://tio.run/##K85JLM5ILf7/3/L/fwA "/// – Try It Online")
This is what happens if all restrictions prohibit you from doing something and none require you to.
Satisfies both restrictions:
* Programs must include no characters that are used in day 8 answers.
* Your source code should not contain duplicate bytes. That is to say, your source code should not contain two bytes which have the same byte value.
Answers tommorrow may use the restriction that their source code is only 1 byte long.
[Answer]
# Day 13, [Python 2](https://docs.python.org/2/), score 3
```
x="))]]]]}}}}}}}}bdfhjlnprt";print(ord(x[24])/2)
```
Note the unprintable character with codepoint 26 between `prt` and `"`" (it's in the TIO link)
Satisfies all 3 restrictions.
Deleting any parenthesis will break the code by making the string less than 24 characters wrong, making `x[24]` be an `IndexError`
Deleting even characters is more difficult to analyze.
1. The `x` can't be deleted because no valid Python program starts with `=`.
2. The first `"` can't be deleted because the `)` character will become unmatched and throw an invalid syntax error.
3. Deleting characters in the string will break the indexing and cause a `IndexError`
4. Deleting the second `"` causes the first `"` to be unmatched.
5. Deleting any of the characters in `print` will result in there being no code to print anything, and thus no output. (`x="))]]]]}}}}}}}}bdfhjlnprt";int(ord(x[24])/2)` is syntactically valid code that does nothing).
6. Deleting the `o` in ord will cause a `NameError` since `rd` isn't defined.
7. Deleting the `2` or `4` in `x[24]` produces `x[2]` or `x[4]`, which index into the parens start of the string.
Answers tomorrow may use the restriction that the average of the bytes is greater than 100.
[Try it online!](https://tio.run/##K6gsycjPM/r/v8JWSVMzFghqoSApJS0jKyevoKhESsm6oCgzr0QjvyhFoyLayCRWU99I8/9/AA "Python 2 – Try It Online")
[Answer]
# Day 1. [Z80Golf](https://github.com/lynn/z80golf), score 3
```
00000000: 3e30 3cc4 1076 7676 >0<..vvv
```
[Try it online!](https://tio.run/##q7IwSM/PSfv/3wAKrBSMU40NFIyTk00UDA3MzRTMzYAEVmBnYKOnV1ZW9v8/AA "Z80Golf – Try It Online")
This follows the restrictions:
* You must include the 0x10 byte in your source code
* You must have an even number of bytes in your source code
* You must only use even bytes in your source code
Answers posted tomorrow may use the restriction that the procedure of repeatedly removing pairs of `odd byte, even byte` (next to each other; in that order) must remove every byte of your input. That is, if you replaced each odd byte by `A` and each even byte by `B`, the sed script `:a; s/AB//g; ta` must produce no output.
---
Disassembled:
```
ld a, $30
inc a
call nz, $7610
halt
halt
```
[Answer]
# Day 1 [Python 3](https://docs.python.org/3/), score 2
```
print(len(' '))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EIyc1T0NdQV1TU@H/fwA "Python 3 – Try It Online")
Hexdump:
```
> hexdump -C quickly_group_together_day1.py
00000000 70 72 69 6e 74 28 6c 65 6e 28 27 10 27 29 29 0a |print(len('.')).|
00000010
```
This follows the restrictions:
* You must include the 0x10 byte in your source code **Note** the quoted character in my hexdump is `0x10`, couldn't figure out a way to get that into TIO
* You must have an even number of bytes in your source code **Note** there is a trailing `0x0a` character to even out the byte count to \$16\$
* ~~You must only use even bytes in your source code~~ Couldn't figure out a way to follow this in any version of Python.
Answers posted tomorrow may use the restriction that it uses at least one vowel, either upper or lower case, i.e. matches `/[aeiouAEIOU]/`.
[Answer]
# Day 1. [05AB1E](https://github.com/Adriandmen/05AB1E), score 3
```
X
```
This follows the restrictions:
* You must include the 0x10 byte [data link escape] in your source code [It is at the end]
* You must have an even number of bytes in your source code [The number of bytes is 2]
* You must only use even bytes in your source code [X: 88, DLE: 16]
Answers posted tomorrow may use programs that work when `//#` is inserted onto the start of them.
---
Uses the actual UTF-8 encoding.
[Try it online!](https://tio.run/##yy9OTMpM/f8/4l3DhP//wzPyFZITi1KL7QE)
## How?
```
X # Push 1 (Coding 1 would not work because it has an odd codepoint: 49)
# Do literally nothing
# Print 1!
```
[Answer]
# Day 2. [Actually](https://github.com/Mego/Seriously), score 5
```
♥►F
```
[Try it online!](https://tio.run/##S0wuKU3Myan8///RzKWPpu1y@/8fAA "Actually – Try It Online")
The bytes are `[0x03, 0x10, 0x46]`.
This follows the restrictions:
* Each byte in your answer must be strictly higher than the last.
* You must use any of the following bytes at least once in your code: 0x02, 0x03, 0x05, 0x07 (Uses `0x03`.)
* The sum of the byte values in your program should be a Fibonacci number. (Bytes sum to 89.)
* Your program should work when `//#` is inserted onto the start of it. (Check [here](https://tio.run/##S0wuKU3Myan8/19fX/nRzKWPpu1y@/8fAA "Actually – Try It Online").)
* There must be 3 or fewer distinct bytes used in your program.
---
Restriction: The output does not change when `/*` is added to the beginning.
[Answer]
# Day 2, [Raku](https://raku.org) (Perl 6), score 6
```
#
{+ords(<^C^E>[*])}#1d1d1d1f2#tnirp.2
```
*Here `^C` stands for `0x03` and `^E` for `0x05`.*
## Satisfied restrictions
* The code should use each of `(){}[]<>` at least once
* The code also performs the task if reversed.
* You must use any of the following bytes at least once in your code: `0x02, 0x03, 0x05, 0x07` (*0x03 and 0x05 are used.*)
* The sum of the byte values in your program should be a [Fibonacci number](https://oeis.org/A000045) (*The sum is 2584 = F18*.)
* The procedure of repeatedly removing pairs of odd byte, even byte (next to each other; in that order) must remove every byte of your code. That is, if you replaced each odd byte by `A` and each even byte by `B`, the sed script `:a; s/AB//g; ta` must produce no output
* You code must include at least one vowel, either uppercase or lowercase i.e. matches `/[aeiouAEIOU]/`.
## A bit of explanation
`<^C^E>` is a string of 2 bytes `"\x03\x05"`. We take everything of it `[*]`, take ASCII numbers with `ords` and then get the length of the list, which is 2. That is returned.
If reversed, it gives `2.print`, which just prints 2.
The first line is an artifact of me trying to satisfy the `//#` restriction. When I realized that no Raku program can ever satisfy this (`//` does not mean anything by itself), deleting it would destroy the Fibonacci restriction, so it's going to stay there.
## Restriction for tomorrow
Your program has exactly \$N^2\$ characters (for some integer \$N>0\$). If you write it into a table of \$N×N\$ cells (start at the top left and write 1 character per cell from left to right and then top to bottom), there must be at least one repeated character in each row and each column. (E. g. `AACABBCBB` is a valid string as it forms the table
```
AAC
ABB
CBB
```
and each row and each column contains a repeated character.)
*(Perhaps it can be formulated in a better way. Let me know if you find how.)*
[Answer]
# Day 3, [brainfuck](https://github.com/TryItOnline/brainfuck), score 6
```
...------
```
Outputs three null bytes (3 in unary).
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fT09PFwz@/wcA "brainfuck – Try It Online")
Satisifed restrictions:
* The program's length is no more than its lowest byte (length is 9, lowest byte is 45)
* The bytes of the program, when sorted and duplicates removed, are all consecutive (there are only two bytes, `.` (45) and `-` (46)).
* The output does not change when `/*` is added to the beginning. (brainfuck ignores both of those characters)
* The program has a square number of characters. When formatted in a square grid, each row and column contains at least one duplicated character.
As a grid:
```
...
---
---
```
* The program is palindromic line-wise (trivially satisfied because there is only one line)
* Your source code must form a valid UTF-8 stream.
Answers tomorrow may use the restriction that deleting characters from the program cannot result in a program in the same language that prints `4` (or, in other words, no adding useless fluff to your code to satisfy other restrictions).
Today is a boring day, because satisfying 6 restrictions is really easy, and satisfying 7 or more is really hard, maybe impossible.
[Answer]
# Day 3, [Trigger](http://yiap.nfshost.com/esoteric/trigger/trigger.html), score 6
```
333454353
```
[Try it online!](https://tio.run/##KynKTE9PLfr/39jY2MTUxNjU@P9/AA "Trigger – Try It Online")
## Restrictions used
* The program's length is no more than its lowest byte (Lowest byte is `51`.)
* The bytes of the program, when sorted and duplicates removed, are all consecutive. (`3`, `4`, `5`.)
* The output does not change when `/*` is added to the beginning. (We only print `3` and flip some triggers, of course this works.)
* The program has a square number of characters. When formatted in a square grid, each row and column contains at least one duplicated character.
```
333
454
353
```
* The program is palindromic line-wise. (There's only one line.)
* Your source code must form a valid UTF-8 stream. (`3`, `4`, and `5` are valid UTF-8.)
## Restriction for tomorrow
Your code must be at least 50% control characters (`0x00 to 0x1F`, `0x7F to 0x9F`).
[Answer]
# Day 4, [Ellipsis](https://listrophy.github.io/ellipsis/), score ~~3~~ 4
Effectively rewritten from scratch after several restrictions were changed in ways that contradicted my original interpretation of them.
Another really long code full of unprintables in a Unary variant. As a hexdump:
```
00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................|
*
00001b60 00 00 00 00 00 00 00 00 33 33 33 19 |........333.|
00001b6c
```
That is, 7016 null bytes, followed by 3 `3` characters (thereby satisying the different programs restriction), followed by the byte with codepoint 25 (to satisfy the prime restriction). Equivalent Brainfuck code is `....`.
The specification for Ellipsis says dots or Unicode ellipsis characters are mandatory, but the reference Ruby implementation cares only about the length, and languages are defined by their implementation on CGCC, so this is allowed.
Satisfied restrictions:
* programs should contain at least 3 previous programs already submitted to this post (question)!
* deleting characters from the program cannot result in a program in the same language that prints 4
* Your code must be at least 50% control characters (0x00 to 0x1F, 0x7F to 0x9F).
* The bytes of your program interpreted as a big endian integer must be prime.
Answers tomorrow may use the restriction that they satisfy more than half of the restrictions for any past day.
[Answer]
# Day 6, [V (vim)](https://github.com/DJMcMayhem/V), score 2
```
C5esckk^Aenter#255
```
[Try it online!](https://tio.run/##K/v/39lUOjubkevw/v//AQ "V (vim) – Try It Online")
* Your program should not contain 6 (#54) or any acknowledgment (#06).
* Your program satisfies at most one restriction from days 1-*4*.
+ Answers in day 5 may follow half or less of all the other restrictions.
---
Tomorrow:
Answer should not be an empty program and may only use bytes in range 128~255.
[Answer]
# Day 7, [なでしこ3](https://nadesi.com), score 1
```
「文文文文文文字」で「字」を文字検索を表示
```
Copy-paste above codes to this [online test page](https://nadesi.com/doc3/index.php?%E3%81%AA%E3%81%A7%E3%81%97%E3%81%933%E7%B0%A1%E6%98%93%E3%82%A8%E3%83%87%E3%82%A3%E3%82%BF) and hit the `▶ 実行` button.
* Your answer should not be an empty program and may only use bytes in range 128 to 255
I know nothing about this language before. When I wrote the requirement yesterday, I didn't take it too seriously. And didn't considered it could ever be done. But since someone had posted an answer today. I would just want to find out one...
I cannot understand the document of this language as they are all written in Japanese. To my (poor) understanding (based on kanji in it): `表示` means `print(...)`,
`文字検索` is `String indexOf`. So it is basiclly `print("文文文文文文字".indexOf("字"))`. And it seems to be 1-indexed while I don't know why.
---
So, next day:
When reverse your program, it should print -8 (as in day 8).
] |
[Question]
[
Write a program that takes no input and prints `Hello, World!` to stdout or your language's closest alternative. The catch is that each line in your program must only contain [printable ASCII characters](http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters) and it must be in lexicographical order, a.k.a. sorted.
Here are all 95 printable ASCII characters in order:
```
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
```
So, for example, the line `!!A0~` would be invalid because the `A` and `0` are out of order. The line `!!0A~` would be valid.
Each line in your program may be any length and there may be any number of lines. Empty lines are considered sorted. Each of the newlines in your program must be the same (no mixing `\n` and `\r\n`). Tabs and other non-printable ASCII characters are forbidden.
**Due to [popular demand](https://codegolf.stackexchange.com/questions/48207/shortest-sorted-hello-world/48211#comment113279_48207), the win condition has been switched around:**
The submission with the fewest *lines* wins. Tiebreaker goes to the shortest program (newlines count as single characters).
Only `Hello, World!` and an optional trailing newline should be output. Note that [HQ9+](http://esolangs.org/wiki/HQ9+) is invalid since it outputs `hello, world`. I may forbid languages similar to HQ9+ that have one character "Hello, World!" commands due to their triviality.
Hint:
>
> This is definitely possible in [Unary](http://esolangs.org/wiki/Unary) and [Lenguage](http://esolangs.org/wiki/Lenguage), though not very concisely.
>
>
>
[Answer]
# [///](http://esolangs.org/wiki////), 7 lines, 22 bytes
```
/
//Hello
,
Wor
l
d
!
```
A rare chance for /// to be competitive (well as long as no one starts with Unary and Lenguage...).
The code first encounters a `/`, and parses the
```
/
//
```
as a substitution instruction which removes all newlines from the remainder of the program. Afterwards, the program merely reads
```
Hello, World!
```
which is printed verbatim as it doesn't contain any further slashes.
[Answer]
# [Headsecks](http://esolangs.org/wiki/Headsecks), 1 line, 366 bytes
```
$(((((((((((((((((((((((((((((,000000044888<AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADIIIIIIIIIIIILPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPTXXXXXXXXXXXXXXXXXXXXXXXX\```diiiiiilqqqqqqqqtyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy|
```
Headsecks is a trivial Brainfuck substitution where the only thing that matters is the code point modulo 8. The equivalent Brainfuck is merely
```
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++++.+++++++..+++.-------------------------------------------------------------------.------------.+++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++++++++++++++++++++++.+++.------.--------.-------------------------------------------------------------------.
```
Luckily this naive approach *just* fits. There's some potential for golfing down bytes, but it might be hard.
Tested using [this Python interpreter](https://github.com/TieSoul/Multilang).
---
## Generating code
```
code = "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++++.+++++++..+++.-------------------------------------------------------------------.------------.+++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++++++++++++++++++++++.+++.------.--------.-------------------------------------------------------------------."
command_map = "+-<>.,[]"
last_point = 32
out = []
for char in code:
curr_mod = command_map.index(char)
last_mod = last_point % 8
if curr_mod > last_mod:
last_point += curr_mod - last_mod
elif curr_mod < last_mod:
last_point += (8 - last_mod) + curr_mod
out.append(chr(last_point))
print("".join(out))
```
[Answer]
# JavaScript (~~67~~ ~~66~~ 62 lines, ~~227~~ 269 bytes)
(Note: only tested on Firefox 36 and Safari 8, contains minor ES6 features (the `Set` class))
```
Z
=
!""+
(0[[]]
+
(
!!""+Set
));c
=Z[~
-22]
$=Z[
3]
$$=Z[
15]
$$$=Z[
24]
$$$$=Z[
1]
$$$$$=Z[
0]
Set
[c
+
$$$+Z[
5]
+Z[
16]
+
$$$$$+
$$$$+Z[
2]
+c
+
$$$$$+
$$$+
$$$$]
(Z[
14]
+
$$+
$+
$$$$+
$$$$$+
"(\
'H\
"+
$+
$$+
$$+
$$$+
",\
W\
"+
$$$+
$$$$+
$$+Z[
6]
+
"\
!')\
")
()
```
---
The code above basically does:
```
alert("Hello, World!")
```
Obviously `alert` is not sorted. So instead we need to generate the statement as a string, and "eval" it:
```
s = "alert('Hello, World!')"; // generate this using sorted code
eval(s)
```
How to generate the string? ES5 supports line continuation so that
```
"AL\
ERT" === "ALERT"
```
But the character code `\` appears *before* all lowercase letters, so we have to generate the lowercase letters using other methods.
We borrow some idea of [JSFuck](http://www.jsfuck.com/) here. The lowercase letters involved in the alert statements are:
```
t e r a o l d
```
all of these can be extracted from characters of standard objects, which may be expressed in terms of some sorted sequence:
```
t, e, r ← true = !""
a, l ← false = !!""
o ← function = Set
d ← undefined = 0[[]]
```
How do we evaluate the string? Surely we cannot use `eval(s)` as it is not sorted. Alternatively we could use `Function(s)()`, but we cannot use `Function` as it is not sorted either. However, `Function` is the constructor of all functions, which means `Set.constructor === Function`.
Adding the identifier `constructor` makes the list of lowercase letters become:
```
t e r a o l d c u n s
```
which fortunately could still be generated by `"truefalseundefinedfunction"`:
```
t, e, r, u ← true = !""
a, l, s ← false = !!""
o, c, n ← function = Set
d ← undefined = 0[[]]
```
---
After prettifying, the code above should read like:
```
// lines 1~8 defines our string containing all lowercase letters we want
Z = true + (undefined + (false + Set))
// Z = "trueundefinedfalsefunction Set() { [native code] }"
// lines 8~20 defines the variables `c`, `$` (e), `$$` (l), `$$$` (o),
// `$$$$` (r), `$$$$$` (t)
// for the corresponding lowercase letters extracted from `Z`
// the rest calls:
Set["constructor"]("alert('Hello, World')")()
// lines 22~36 generates the "constructor" string
// lines 37~61 generates the "alert('Hello, World')" string
```
---
Update: Renamed `E`, `L`, `O`, `R`, `T` to various repetition of `$` to reduce 4 lines.
[Answer]
# [Insomnia](https://codegolf.stackexchange.com/questions/40073/making-future-posts-runnable-online-with-stack-snippets/41868#41868), 4 lines, 59 bytes
```
FFFFGjnnnnooty
FLLddeejkopqyyyyy~~
(<ddjnoppppqrtu
<<Fddfj
```
This program is generated by optimizing for line count.
### 10 lines, 43 bytes
```
(u
pt
(dppty
p~
j
<Fptt{
(otz
?o
FLu
<?FFu~
```
This above program is generated by optimizing for byte count.
[Answer]
# Cygwin bash, 16 lines, 60 bytes
This only works due to the case-insensitive file name on Windows, and the fact that Cygwin look up the utilities case-insensitively even if you don't set it to recognize path case-insensitively.
```
A\
=Hello
A\
+=\
",
"Wor
A\
+=l
A\
+=d
A\
+=\
!
E\
CHO\
$A
```
Take note of that `ECHO` at the end.
[Answer]
# [><>](http://esolangs.org/wiki/Fish), 6 lines, 111 bytes
```
"""""""/;;Hello
&\o
&++\oooo~~
"++++++++\bbbdlr
+++++\ccccccccfooo}
$++66\cfffffooooopr
```
I'm having trouble golfing out an extra line, but in any case I'm happy to have beaten the 7-line method.
## Explanation
><> is a stack-based 2D language where instructions are single chars and program flow can be up, down, left or right. The `"` instruction toggles string parsing, pushing chars until a closing `"` is met, but because of the nature of ><> there's no such thing as "multi-line string parsing" like with CJam's strings or Python's triple quoted strings. This turned out to be a major problem because starting and ending a line with a `"` and having other chars in between (e.g. `"some chars"`) is not allowed!
Note that `/` and `\` reflect program flow, so we actually execute the first line then all of the lines in reverse order, and most lines are actually executed backwards!
```
[Line 1]
"""""" Three empty strings, push nothing
"/;;Hello " Push "/;;Hello ". Note the wrapping - ><> is toroidal!
"""""" Three empty strings, push nothing
[Line 6]
66++$ Turn the top " " into "," by adding 12, then swap top two
rp Reverse stack and pop top 3
ooooo Print "Hello", stack is now " ,"
fffffc Push some 15s and a 12
[Line 5]
+++++ Sum the 15s and 12 to give 87, or "W"
}ooo Move "W" to the back and output ", W"
fcccccccc Push a 15 and some 12s
[Line 4]
++++++++ Sum the 15 and 12s to give 111, or "o"
"rldbbb\++++++++" Push chars to stack
r Reverse stack
ld Push length of stack and 13, not used
bbb Push three 11s
[Line 3]
++& Sum the 11s to give 33, or "!" and put in register
~~ Pop top two
oooo Print "orld"
[Line 2]
& Put "!" from register to stack
o Print "!"
[Line 1]
; Terminate
```
---
On a side note, here's an amusing attempt at a ><> least bytes (23 lines, 47 bytes):
```
v
"
!
d
l
r
o
W
,
o
l
l
e
H
"
/<
l
?
!
;
o
\^
```
[Answer]
# CJam, ~~5~~ 4 lines, 162 bytes
```
"Hello
")))))))))))))))))))))))))))))))))))68S\cel
"Wor
")))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))@SX\c|
```
Same number of lines as Insomnia! (but a lot more bytes)
[Try it online](http://cjam.aditsu.net/#code=%22Hello%0A%22%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%2968S%5Ccel%0A%22Wor%0A%22%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%40SX%5Cc%7C).
## Explanation
```
"Hello\n" Push "Hello" and a newline
) Uncons the newline
)))...))) Increment the newline into a ","
68S\ Push 68 and a space then swap, leaving 68 on top
c Convert 68 into a char "D"
el Lowercase "D" into "d"
"Wor\n" Push "Wor" and a newline
) Uncons the newline
)))...))) Increment the newline into an "l"
@ Rotate top three elements, moving the "d" to the top
SX\ Push a space and 1 then swap, leaving the space on top
c Convert the space (which is an array) into a char
| Bitwise or the space (32) with 1 to give "!" (33)
```
CJam automatically prints the stack afterwards.
Thanks to @Optimizer for reminding me that `Sc` works, because otherwise `SX|` fails (it does a setwise or instead, giving the array consisting of a space and 1).
[Answer]
# [><> (Fish)](http://esolangs.org/wiki/Fish), 5 lines, many bytes
The code is extremely long, when I say `[6535529689086686142930090 '+' signs]` and `[6535529689086686142930090 'd' characters]` in the first line of the code, I mean that there are literally `6535529689086686142930090` plus signs in a row!
(And for the following lines add the necessary prefix spaces.)
```
'[6535529689086686142930090 '+' signs]^`[6535529689086686142930090 'd' characters]
**,/288
-/:o
%**288:;?\
(1:\
```
A shorter testable alternative which only prints `Hi`:
```
'+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++^`hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
**,/288
-/:o
%**288:;?\
(1:\
```
Method:
* In the first line we create a huge number representing the string in base128.
* In the rest of the lines (going from bottom to top) we print the following character in every loop until the value of the integer reaches 0.
* The looping code is `:1(?;:882**%:o-288**,`.
(We can print arbitrary 2+ chars long string with this method.)
[Answer]
# PHP (7 / 17 lines, 36 / 59 bytes):
Due to the amount of invalid answer, I rewrote this answer.
The browser version? Gone.
But I have 2 solutions, both based on bitwise `xor` (`^`) of strings in PHP.
This is an extremely powerful solution! Sometimes, it allows to save plenty of bytes.
First, the shortest answer:
```
Echo
Hello
,AM^mm
,Wor
,OOO^
"#+n
";
```
I know, it looks awful, but it works!
The next one depends on newlines.
Yes, it uses newlines (`\n`/UNIX style is required)!
```
Echo
Bo
.ff
.e
.
"&*]ex
fn
"^
"\n
\n
\n
\n
\n
\n
\n
",B^c
;
```
The newlines on this one are required to work.
It isn't perfect, but works!
---
Both answers were based on [@MartinBüttner](https://codegolf.stackexchange.com/users/8478/martin-b%C3%BCttner)'s [solution](http://pastebin.com/MskntTra):
```
Echo
Hello
.
chr
(44
).
chr
(29
+3
).Wor
.l
.d
."!
";
```
---
A special thank to [@n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳](https://codegolf.stackexchange.com/users/6638/n%CC%B4%CC%8B%CC%96h%CC%B7%CC%83%CD%89a%CC%B7%CC%BF%CC%ADh%CC%B8%CC%85%CC%A1t%CC%B5%CD%84%CC%A8d%CC%B7%CD%80%CC%B0h%CC%B7%CC%82%CC%B3), [@CJDennis](https://codegolf.stackexchange.com/users/29560/cj-dennis), [@MartinBüttner](https://codegolf.stackexchange.com/users/8478/martin-b%C3%BCttner) and [@skagedal](https://codegolf.stackexchange.com/users/38728/skagedal) for detecting all my mistakes and for their suggestions.
[Answer]
# Pyth, 7 lines, 23 bytes
```
-
"Hello
,
Wor
l
d
!"b
```
Pretty simple, just use a multiline string and remove the newlines.
[Try it here.](https://pyth.herokuapp.com/?code=-%0A%22Hello%0A%2C%0A%20Wor%0Al%0Ad%0A!%22b&debug=0)
[Answer]
# Forth, 41 lines, 143 bytes
[Try it online.](http://ideone.com/rnp5FC)
I'm very proud of this. I whipped it out pretty quickly once I found I could do it, having Google searched for case-insensitive languages, and I already know Forth decently. It can almost definitely be shortened, both bytes and lines. Suggestions are appreciated. :D
This program essentially pushes the decimal value of each ASCII character, then prints each one. I attempted to optimize while I wrote it, hence it is less readable than I'd like.
```
33
99
1
+
DUp
8
+
2DUp
6
+
SWap
11
+
2OVer
SWap
8
9
*
EMit
1
+
EMit
DUp
DUp
EMit
EMit
3
+
EMit
29
3
2DUp
+
EMit
*
EMit
EMit
EMit
EMit
EMit
EMit
```
[Answer]
# Marbelous, 9 lines, 94 bytes
```
3333
@ADD
358C
++--29\\
++--3555DE
<<<<<<>>~~
+++++446666D
++++++++../\
++------
```
[Test it online here.](https://codegolf.stackexchange.com/a/40808) `Using spaces for blank cells` must be checked.
**Visual representation of source:**

**Explanation:** Each hexadecimal value in this program moves downward every "tick" (unless it is on `\\`, in which case it moves to the right). `++` will increment the value, `--` decrement, `~~` apply a bitwise not, etc. Values that fall of the bottom are printed as an ASCII character.
For example: The `33` in the top corner becomes `(((0x33 +1 +1) << 1) +1 +1 = 0x6C (l)`.
[Answer]
## Batch - 39 Lines (202 bytes)
I wanted to cut down on the size by enabling delayed expansion by running the code inside of a `cmd` call using the `/v on` switch, but could not get past all the carats.
```
@S^
ET^
LO^
C^
AL^
EN^
ABL^
E^
DEL^
AY^
E^
DEX^
P^
ANS^
IO^
N
@S^
ET^
0=Hello
@S^
ET^
1=^
,^
Wor
@S^
ET^
2=l
@S^
ET^
3=d
@E^
CHO^
!^
0^
!!1^
!!2^
!!3^
!^^^
!
```
Without the newlines (and carats to escape newlines):
```
@SETLOCAL ENABLEDELAYEDEXPANSION
@SET 0=Hello
@SET 1=, Wor
@SET 2=l
@SET 3=d
@ECHO !0!!1!!2!!3!^^!
```
[Answer]
# Perl, 17 lines
```
$_
=
'pr
int
"Hello
,
Wor
l
d
!"';s
!
!!g
;s
!.
*
!$&
!eex
```
[Answer]
# Rebol - 15 lines (51 bytes)
```
PRin
AJOin
[
'Hello
Sp
+
12
Sp
'Wor
'l
'd
Sp
+
1
]
```
Words in Rebol are case-insensitive (eg. `PRINT`, `Print` and `print` would all call the same function).
The above code tidied up:
```
prin ajoin [
'Hello sp + 12 sp 'Wor 'l 'd sp + 1
]
```
NB. `sp` returns the space [char!](http://www.rebol.com/r3/docs/datatypes/char.html)
[Answer]
# [Unary](http://esolangs.org/wiki/Unary), 1 line, lots of bytes
Every character in this program is `0`. The source is too long to put in here, but it consists of a string of this many zeros:
```
327380789025192647555922325233404088310881092761595127419003295178342329930050528932118548
```
This is the decimal representation for this binary number:
```
0b1010010010010010010010010110000010010010010110000010010000010010010000010010010000010001001001001011111000010000010000011110001111001011111000000100000011011011100010010010010010010010100100010010010100000000100001011100001100010010010100011011011011011011100011011011011011011011011100000000010100
```
Which was created from this BrainF\*\*\* program:
```
++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>-[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.
```
See how I generated it: <http://ideone.com/lMT40p>
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 9 lines, 25 bytes
```
`
Hello
,
Wor
l
d
!`
\
-
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%60%0AHello%0A%2C%0A%20Wor%0Al%0Ad%0A!%60%0A%5C%0A-&inputs=&header=&footer=)
```
` #
Hello |
, |
Wor | Push 'Hello\n,\n Wor\nl\nd\n!'
l |
d |
!` #
\ # Push '\n'
- # Remove all '\n' from 'Hello\n,\n Wor\nl\nd\n!'
# Implicit output
```
[Answer]
# Ruby, 19 lines, 95 bytes
```
$;=
$>
$;<<
:Hello
$;<<
44::chr
$.=
33::
-1
$;<<
$.::chr
$;<<
:Wor
$;<<
:l
$;<<
:d
$;<<
33::chr
```
Possibly the second-hardest code restriction for Ruby I've seen on this site, after the monstrosity [here](https://codegolf.stackexchange.com/questions/36639/the-symbols-vs-the-letters/36654#36654).
Edit for explanation: The only Ruby output method that's sorted is the `<<` method on STDOUT. Unfortunately, the constant for STDOUT is `$>`, and `>` is higher ASCII than most symbols, so it's not really possible to call a method on it. We need a multi-line assignment statement to get it into a more tractable variable name, `$;` (semicolon is still pretty high, but most variables of this form are either non-assignable, or can only be strings).
Symbols (`:Wor`, etc. ) are the easiest way to do a literal, and I don't see a way to strip newlines from a string, so I need multiple print statements. The space and punctuation can't go into a symbol literal, but luckily the `chr` method on numbers is legal, so I can get a character from its ASCII value. `::` is an alternate way of calling methods. Space is tricky because I can't write `32`, so I subtract 1 from 33 and assign it to a variable.
[Answer]
# Retina, 12 lines, 29 bytes (non-competing)
The language is newer than the challenge.
```
Hello
$
,
$
Wor
$
l
$
d
$
!
```
[**Try it online**](https://tio.run/nexus/retina#@8/lkZqTk8@lwqUDxArh@UVAKgeIU4BY8f9/AA)
] |
[Question]
[
# Challenge
This challenge is pretty simple: Output the total number of possible Tweets. Given the fact that \$1{,}114{,}112\$ Unicode characters exist, and Tweets can be up to \$280\$ characters long, we calculate this number like so:
$$\sum\_{l=1}^{280}1{,}114{,}112^l$$
Calculated, this number becomes:
```
13806352273767118967309446652268353719030666987497438863889357319392349204238070937934701588382252733861344864045882375396168022346806583217340072802259387083359555134466517197703380759356965846365156977627360473773588169473731316369188960207815543356617430699549282184606847903882093344681639583363887920162736670339584230464092411246928128751923029979554646202579157612845521194257627831816510188786486205364038342997992390163377307319320795770580125829871827813635107055402218833285288428245530361070090385299410480471800097379723938710176776857154693492888113262310774952935141264656128106489715644469204223123574077687056241600407855644698999923182052787491366956979702291906138690639325270704272468782453957210692358210530379637285511395582363214078004388847219660731573151720107026864311541883029164798133330444260768597550725802772979408391647537342929574104808498797769614795400908507365237326804077132929339660443550229992211585154931729238484097424201567163596712698594520366545693861474171972272416897768579601352059483077847068448856472837079895280084051348757113747847034093121500403990822456362331568718364029903237356710927604336216180583115812490741333484187646966386074557181286407949971654502112671681454373869734610539296783900783568039838348725239932066066987739369537132033298306852573056479318562759091086979441683964087623025801925326064609304055115943692782207092740008073169526779422072953119459819275895282587278291133892079932466034984180041060600579941010427931676118356402267755461169199685582252347150686196242972686980783271232177904787906691872492956841276422272710260778534487171700075108866361285159161816004238666402986057371469198754307817645454320666214400
```
# Rules
* You may output a float with only zeros after the decimal point.
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* Trailing whitespace is allowed.
* If possible, please link to an online interpreter (e.g. [TIO](https://tio.run)) to run your program on.
* Please explain your answer. This is not necessary, but it makes it easier for others to understand.
* Languages newer than the question are allowed. This means you could create your own language where the empty program calculates this number, but don't expect any upvotes.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins!
[Answer]
# [Emotion](https://github.com/Quantum64/Emotion), 17 [bytes](https://quantum64.github.io/EmotionBuilds/1.1.0//?state=JTdCJTIybW9kZSUyMiUzQSUyMmNvZGVwYWdlJTIyJTdE)
```
üòçüòÉüíÅüßüü§ØüòÉüòßüòçüòÑü§∂üôÜüôÜüò¨üèÉüßõüòßü§†
```
Explanation
```
üòçüòÉüíÅüßü Push literal 280
ü§Ø Enter an iteration block over the first stack value and push the iteration element register at the begining of each loop.
üòÉ Push literal 1
üòß Push the sum of the second and first stack values.
üòçüòÑü§∂üôÜüôÜ Push literal 1114112
üò¨ Swap the top two stack values.
üèÉüßõ Push the first stack value to the power of the second stack value.
üòß Push the sum of the second and first stack values.
ü§† Ends a control flow structure.
```
[Try it online!](https://quantum64.github.io/EmotionBuilds/1.1.0//?state=JTdCJTIyaW50ZXJwcmV0ZXJDb2RlJTIyJTNBJTIyJUYwJTlGJTk4JThEJUYwJTlGJTk4JTgzJUYwJTlGJTkyJTgxJUYwJTlGJUE3JTlGJUYwJTlGJUE0JUFGJUYwJTlGJTk4JTgzJUYwJTlGJTk4JUE3JUYwJTlGJTk4JThEJUYwJTlGJTk4JTg0JUYwJTlGJUE0JUI2JUYwJTlGJTk5JTg2JUYwJTlGJTk5JTg2JUYwJTlGJTk4JUFDJUYwJTlGJThGJTgzJUYwJTlGJUE3JTlCJUYwJTlGJTk4JUE3JUYwJTlGJUE0JUEwJTIyJTJDJTIyaW50ZXJwcmV0ZXJBcmd1bWVudHMlMjIlM0ElMjIlMjIlMkMlMjJtb2RlJTIyJTNBJTIyaW50ZXJwcmV0ZXIlMjIlN0Q=)
[Answer]
# [Haskell](https://www.haskell.org/), 25 bytes
```
div(x^281-x)$x-1
x=8^5*34
```
[Try it online!](https://tio.run/##y0gszk7NyfmfaBvzPyWzTKMizsjCULdCU6VC15CrwtYizlTL2OR/bmJmnm1BUWZeiULi/3/JaTmJ6cX/dZMLCgA "Haskell – Try It Online")
## Why does it work?
1. \$8^5\cdot 34=1114112\$, but 1 byte shorter.
2. \$\sum\_{l=1}^n x^l=\frac{x^{n+1}-x}{x-1}\$.
---
# Boring answer, still 25 bytes
```
sum$map(1114112^)[1..280]
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 23 bytes
*-1 byte thanks to @Level River St.*
Based on the formula presented in [@Delfad0r's answer](https://codegolf.stackexchange.com/a/220930/88546).
```
x=17<<16
p x**281/~-x-1
```
[Try it online!](https://tio.run/##KypNqvz/v8LW0NzGxtCMq0ChQkvLyMJQv063Qtfw/38A "Ruby – Try It Online")
### [Ruby](https://www.ruby-lang.org/), 24 bytes
An interesting iterative solution. It uses the fact that `a + a*a + a*a*a...` is equal to `a*(1+a*(1+a*(1+...)))`.
```
p eval'+1114112*x=1'*280
```
[Try it online!](https://tio.run/##KypNqvz/v0AhtSwxR13b0NDQxNDQSKvC1lBdy8jC4P9/AA "Ruby – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 21 bytes
```
Tr[1114112^Range@280]
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277P6Qo2tDQ0MTQ0CguKDEvPdXByMIg9n9AUWZeiYJD@v//AA "Wolfram Language (Mathematica) – Try It Online")
-1 byte from @GregMartin
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~183~~ ~~181~~ ~~167~~ ~~162~~ 161 bytes
*-1 byte ceilingcat*
```
c;d;char s[1695],t[1695];x=281;y=1694;main(z){for(t[y-1]=1;--x;)for(z=y;z--;c/=10,d/=10)s[z]=(d+=s[z]+(t[z]=(c+=t[z]*17<<16)%10))%10;for(;y--;s[y]+=48);puts(s);}
```
[Try it online!](https://tio.run/##JUzLCsIwEPwVL0JiGnSl1sp2vyTkUDb4OPigqdBE/PaYxcu8mBm2F@ZSGAPydZxW0UF3Ovhm/jMutO8BE1XX4n28PVTWn/NzUrNLFjwBWrugliRTwmwt8pZg1wRBHV32pIIhEaaOxLIhERs4DgN0el17AignmOpDdMkbanuNr/ccVdT4LeUH "C (gcc) – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 33 bytes
```
f=(n=280n)=>n&&1114112n**n--+f(n)
```
[Try it online!](https://tio.run/##BcFRCoAgEAXA28iuYbTSRz92lzCNQt5GRtffZq7t23p@zvsN0L2Y1URIcZnAaYVzIjKLRHiPEIZKYMuKrq2MTQ@qxGw/ "JavaScript (Node.js) – Try It Online")
## 29 bytes
Porting [@Delfad0r's solution](https://codegolf.stackexchange.com/a/220930/58563) saves 4 bytes:
```
_=>((x=1114112n)**281n-x)/~-x
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/e1k5Do8LW0NDQxNDQKE9TS8vIwjBPt0JTv0634n9yfl5xfk6qXk5@ukaahqbmfwA "JavaScript (Node.js) – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 14 bytes
```
16W17*X$280:^s
```
[Try it online!](https://tio.run/##y00syfn/39As3NBcK0LFyMLAKq74/38A "MATL – Try It Online")
### Explanation
```
16 % Push 16
W % 2 raised to that
17 % Push 17
* % Multiply. Gives 1114112
X$ % Convert to symbolic (to achieve arbitrary precision)
280 % Push 280
: % Range. Gives [1 2 ... 280]
^ % Power, element-wise
s % Sum. Implicit display
```
[Answer]
# [J](http://jsoftware.com/), 20 bytes
```
1#.1114112x^1+i.@280
```
[Try it online!](https://tio.run/##y/pvqWhlbK4Qq2CgEA/ERkZGXEp66mkKtlYK6go6QBErINbVU3AO8nH7b6isZ2hoaGJoaFQRZ6idqedgZGHwX5MrNTkjXyFNXf0/AA "J – Try It Online")
Wasn't able to improve the straightforward answer.
[Answer]
# [Factor](https://factorcode.org/), ~~38~~ 27 bytes
-11 bytes thanks to Bubbler!
```
1114112 280 [1,b] n^v sum .
```
[Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQnVqUl5qjkJtYkqFXlJiXnloMYZelglQVKxSnFpam5iUDhQuKUktKKguKMvNKFKz/GxoamhgaGikYWRgoRBvqJMUq5MWVKRSX5iro/f8PAA "Factor – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `sr`, 9 bytes
```
⁺∑ƛ»∆#∆»e
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=sr&code=%E2%81%BA%E2%88%91%C6%9B%C2%BB%E2%88%86%23%E2%88%86%C2%BBe&inputs=&header=&footer=)
```
⁺∑ # push 280
∆õ # Map foreach (1...280)
»∆#∆» # Base-255 compressed 1112114
e # Exponentiation
```
The `s` flag sums the ToS at the end of execution. The `r` flag reverses the order in which functions take their arguments, so you have \$ 1112114^n\$ instead of \$ n^{1112114} \$.
# [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 9 bytes
```
»∆#∆»⁺∑ɾe
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=s&code=%C2%BB%E2%88%86%23%E2%88%86%C2%BB%E2%81%BA%E2%88%91%C9%BEe&inputs=&header=&footer=)
Thanks to Underslash for this
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 10 bytes
```
⁴‘æ«*Ɱ280S
```
[Try it online!](https://tio.run/##ARsA5P9qZWxsef//4oG04oCYw6bCqyrisa4yODBT//8 "Jelly – Try It Online")
-1 byte thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!
## How it works
```
⁴‘æ«*Ɱ280S - Main link. No arguments
‚Å¥ - Yield 16 and set the argument to 16
‘ - Increment to 17
æ« - Implicitly using the left argument, bitshift left, yielding 1114112
280 - Yield 280
Ɱ - Over each integer 1 ≤ i ≤ 280:
* - Yield 1114112 to the power i
S - Sum
```
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 19
```
B14112dd281^r-r1-/p
```
Uses @Delfad0r's sum trick.
Also in dc, `B` = 11, and `B14112` = 1114112.
[Try it online!](https://tio.run/##S0n@/9/J0MTQ0CglxcjCMK5It8hQV7/g/38A "dc – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
```
•HYH•Ƶ´LmO
```
[Try it online!](https://tio.run/##yy9OTMpM/f//UcMij0gPIHls66EtPrn@//8DAA "05AB1E – Try It Online")
Likely Makonede's answer.
Thanks to [Kevin's tip](https://codegolf.stackexchange.com/a/166851/66833) on compressing integers in 05AB1E. Make sure you upvote it!
## How it works
```
•HYH•Ƶ´LmO - Program
•HYH• - Compressed integer: 1114112
Ƶ´ - Compressed integer: 280
L - Range [1, 2, ..., 280]
m - Raise 1114112 to the power of each
O - Sum
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 14 bytes(?)
```
s^LhC\ÙèøøS280
```
[Try it here!](https://pythtemp.herokuapp.com/?code=s%5ELhC%5C%F4%8F%BF%BFS280&debug=0)
Pyth supposedly uses an SBCS, but I can't find any details about its actual codepage.
The reason I have my doubts about the byte count is that the code contains a character with codepoint 1114111, which certainly isn't normally represented in a single byte (and I VERY much doubt is in Pyth's code page). The code is 11 *characters* long, and Pyth reports the mystery character as taking 4 bytes. However, the interpreter reports a length of 12, and the number 1114111 takes 3 bytes. In short, 11, 12, 13, and 14 are all possible byte counts for this program.
I've chosen 14, as its the most likely (since, again, Pyth says the character is 4 bytes).
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 27 bytes
```
seq -f1114112^%g -s+ 280|bc
```
[Try it online!](https://tio.run/##S0oszvj/vzi1UEE3zdDQ0MTQ0ChONV1Bt1hbwcjCoCYp@f9/AA "Bash – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 44 bytes
```
1..280|%{$k+="[bigint]1114112*"*$_+1|iex};$k
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/31BPz8jCoEa1WiVb21YpOikzPTOvJNbQ0NDE0NBIS0lLJV7bsCYztaLWWiX7/38A "PowerShell – Try It Online")
**-18 bytes thanks to @ZaelinGoodman**
# Powershell v7, 37 bytes, thanks to @mazzy
```
1..280|%{$k+="1114112n*"*$_+1|iex};$k
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), 101 bytes
```
v->{var x=java.math.BigInteger.ZERO;for(int i=280;i>0;)x=x.add(x.valueOf(17<<16).pow(i--));return x;}
```
[Try it online!](https://tio.run/##LY5Ba4QwEIXv/oo5xlLDbg9tIeqhsAs9FKELPbT0kNXojo1JiBPrsvjbbZCeHo/3vZnXy0lmffOz4uCsJ@ij54FQ8zaYmtAafieSWstxhDeJBm4JgAtnjTWMJCnKZLGBIWbsRB5N9/UN0ndjuqEAx/87@Ufk7qtzr2oqoYVinbLyNkkPc7F9HSRd@At2r4ZUpzz/PLxXorWeoSHA4uF5J7DciXQuZi6bhs18kjqoqmX7pzzfP6bc2V@GWZamwisK3sAsllVsK07XkdTAbSDu4kjShrVcOqevzAStYyViS7Ksfw "Java (JDK) – Try It Online")
## Credits
* fix increasing byte count by 1, and 1 byte reduction by [iota](https://codegolf.stackexchange.com/users/99986/iota).
[Answer]
# Scala, ~~47~~ 44 bytes
Corrected answer *and* saved 3 bytes thanks to @mik!
```
()=>{val x=17<<16:BigInt;x.pow(281)/(x-1)-1}
```
[Try it in Scastie!](https://scastie.scala-lang.org/YgsAVMggQoO5y99qhKXFKg)
Not particularly short, but it uses the simplification of the sum to avoid all the exponentiation + summation, unlike the other answers.
[Answer]
# [Icon](https://github.com/gtownsend/icon), ~~59~~ 49 bytes
* 10 bytes thanks to mik!
```
procedure main();write(1114112^281/1114111-1);end
```
[Try it online!](https://tio.run/##y0zOz/v/v6AoPzk1pbQoVSE3MTNPQ9O6vCizJFXD0NDQxNDQKM7IwlAfwjbUNdS0Ts1L@f8fAA "Icon – Try It Online")
## Original solution, 59 bytes:
```
procedure main()
t:=0
t+:=1114112^(1to 280)&\z
write(t)
end
```
[Try it online!](https://tio.run/##y0zOz/v/v6AoPzk1pbQoVSE3MTNPQ5OrxMrWgKtE28rW0NDQxNDQKE7DsCRfwcjCQFMtpoqrvCizJFWjRJMrNS/l/38A "Icon – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 14 bytes
```
ṁ`^1114112ḣ280
```
[Try it online!](https://tio.run/##yygtzv7//@HOxoQ4Q0NDE0NDo4c7FhtZGPz/DwA "Husk – Try It Online")
I found out that if you run a Husk program that doesn't take an argument, and include an argument, it errors. [Here's an example](https://tio.run/##yygtzv7//@HOxoQ4Q0NDE0NDo4c7FhtZGPz//x8A "Husk – Try It Online").
## Explanation
```
·∏£280 # Range from 1 to 280
ṁ # Map over range and sum...
`^1114112 # ...114112^n
```
[Answer]
# Deadfish~, 8398 bytes
```
{i}dds{i}dsiis{{{i}i}iiii}iiiis{{{{{{ii}iiii}iiiii}iii}i}ddi}dds{{{{{{{{{{{{{i}ddi}di}ddi}dddi}ddi}d}i}iiii}i}ii}dddi}ddi}ds{{{{{{{{{{{{{{{{{{{{{{{{{{i}dd}iiiiiii}d}i}iiiii}ii}}iiii}iiiiii}iiiiiii}d}iiiiii}iiii}iiiiii}i}ddd}iiiii}iiiii}}iiii}iii}iiiiii}iii}d}iii}iiiis{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{i}}ii}ddd}iiiiii}iii}ii}iiii}i}di}ddi}d}i}iiii}dd}iiiii}}iii}d}iiiiii}iii}d}ii}ii}i}dd}ii}i}i}iiii}}ii}d}iii}d}iiii}iiiiii}dd}iiii}d}iiiiii}d}iiiii}ii}ii}iiii}iiii}iiiii}i}i}}i}d}iiiiiis{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{iii}iiiii}dddi}dd}}i}ddd}ii}ii}iiiii}iii}iiiii}i}dddi}dddi}ddd}iiii}i}iiiii}iiiiii}iiii}iiii}ii}ii}ii}iii}iiii}ddi}dd}iiiiii}ii}iiiiii}iiiii}i}iiiiii}}iiiiii}}}iiiiii}iiiiii}d}iiiii}dd}}iiiiii}}iii}dddi}d}iiiii}i}iiiiii}i}d}ii}iiiii}iiii}iii}iiiii}iiiii}d}i}}}iiii}i}i}i}ddi}ddd}i}iiiiii}iiiii}ddd}iii}iiiii}iii}dddi}dd}iiiiii}ddi}ddd}ii}iiiiii}iiiiii}ddd}iiiii}iiiiiii}dd}iiiiii}iiii}iiiii}ddd}iii}dd}i}i}ddd}iiiiii}d}i}di}dd}i}iiis{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{i}dd}i}iii}d}iii}ddi}d}iii}d}iiiiii}iii}iiiii}ddd}iiii}dd}ii}iiii}}iiiiiii}ddd}iiii}iiiiii}i}iii}iiiiii}di}dd}iiiiii}d}iii}iii}iii}iiiiii}iiiiii}d}i}iiiiiii}dd}ii}iii}iiiii}ddi}ddi}d}i}iiii}iiiiii}iiii}iiii}iiiii}ii}ddd}i}iiiiii}ii}iiii}i}iiii}iii}iiiii}iii}di}d}ii}dddi}di}di}dd}iiiii}d}i}iiiiii}iiiii}di}d}}ii}ddi}ddi}ddd}ii}iii}d}i}iii}ddd}}iiiii}iiiiii}ii}}iiiiiii}d}iiii}iiiiii}iii}}iiii}dd}iiii}ddi}dddi}ddi}d}iii}iiii}iiii}ii}iiii}dd}i}}i}ddd}ii}ddd}ii}iiii}dd}iii}i}ii}iii}ii}ii}iiiii}iiiiii}}i}ii}ddd}}iiiii}d}iiiiiii}dddi}ddi}ddd}i}iiiii}iiiii}iiiiii}iii}ddd}}i}d}iiiii}iiiii}i}iii}d}i}iiiii}iiiiiii}d}iii}iii}di}dd}iiiii}iiiii}iii}iiii}dd}iiii}ddi}dd}ii}iiii}iii}iiiii}iiii}dddi}di}ddi}dddi}ddd}iiiiii}dd}ii}iiii}iiiiii}iiii}iiii}}ii}ddi}ddi}dddi}dddi}ddd}iiiiii}iiiiii}iiii}ii}dddi}dd}ii}dd}ii}iii}iiii}iiiiii}ddd}}iiii}ii}dddi}ddd}iii}is{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{iiiii}iiiiii}d}iiii}i}ddd}i}iiii}dd}iii}ddd}ii}i}ddi}dd}iiii}iiiii}iiiiii}ii}iiiii}iiiii}i}d}iiiii}iiii}iiiiii}}iiiii}iiiii}dd}iiii}iiiii}di}dd}iiiii}ddd}iii}di}dd}ii}iii}ii}iiii}iiiiii}}iiiiiii}ddd}}iii}}i}iiiiii}ddd}}iiiii}i}iiiiii}d}ii}ii}iii}dd}ii}iiiii}iiiii}iiiii}ii}iiii}iiiiii}iii}}iiiiii}iiiiii}}iiii}iiiii}iiiii}i}i}d}i}i}i}iiii}ddd}iiiii}iii}ii}iiii}iii}dd}iiiiii}iii}i}iiiii}dd}ii}dd}}ii}iii}ii}iiiiii}iiiiii}i}ii}ddi}d}}ii}i}iiiiii}iiii}iiiiiii}d}iiiii}iiiii}iii}i}dddi}dddi}ddd}iii}d}iiiii}dddi}d}iiiii}iii}ddi}ddi}d}ii}di}ddd}iiii}iiiii}i}dd}ii}iiii}iii}iiiii}ii}iii}dddi}dd}iiiiii}dd}iiii}iiii}ddd}iii}ii}ii}iii}iiiiii}ddd}}iii}iiiiiii}dddi}di}d}iiiiii}d}iii}ddd}ii}iii}}i}iiiiii}}ii}}i}iiii}iii}iiiii}ii}}iiii}iiiiii}i}}iii}iiiiii}}iiii}iii}iii}iiiiii}}iiiii}i}iiiiii}dd}iii}ddd}iii}iiiii}iiiii}iiiii}i}iiiiii}i}di}dddi}d}ii}iii}dd}iiiii}iiiii}iiii}ddd}iii}iii}i}ddi}dd}iiiii}}iii}i}iiii}ii}iii}iiiiiii}dd}iii}ii}i}d}iiiiii}dd}iiii}}iiiiii}d}}ii}iiiiii}i}dddi}ddd}iii}ddi}di}ddd}iii}}ii}iiiiii}ii}d}iiiiiii}d}iiii}iiiiiii}dd}ii}ddd}i}iiiiii}ii}ddd}iii}iiiiii}di}dd}iii}}iiii}ddd}}iiiii}d}iiii}iiiii}ddd}iiii}d}iii}d}iiiii}dddi}d}ii}ii}iiiiii}i}d}iiiii}di}ddd}ii}iiiii}iii}iii}iiii}iiiiii}iiiii}iiiii}iiiiiii}dd}iiii}iiiii}ii}iiiiii}i}iiiiii}dd}}iii}d}iiiiii}i}ii}ii}iiiii}iiii}ddd}}iiiiii}iiiii}iiiiii}ii}iiiiii}iiiii}iii}ii}ddi}ddi}dd}iiiii}i}}ii}iiiii}dd}i}ddi}di}d}ii}dddi}dd}}iiiii}iiii}iiiii}ddi}dd}iiiiii}iiiiii}i}iii}iiii}iiiiii}iiiiii}dd}i}ddd}i}i}di}ddd}ii}i}iiii}ddd}ii}iii}di}dd}ii}iiiiii}iiii}dd}iiii}ii}dd}iiii}d}}ii}di}d}iiiiii}}ii}ii}iiiiiii}di}di}dd}iiiii}iii}i}i}iiiii}d}}iii}iiiiii}iiiiii}iiii}i}d}iii}iii}d}iii}dd}ii}iiiii}di}ddd}}iii}ds{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{iii}iiiii}i}iiii}d}i}ddi}dd}ii}iiiiii}iiii}ddd}}ii}dddi}ddd}iii}iiii}dd}iiiiii}dd}iiiii}iiiii}ii}iiiii}iii}iiii}}iiiii}ii}i}ddd}iiiiii}iiii}iiiiii}iiiiii}iii}ii}iiiii}}iiii}iiiiiii}dd}iiiiiii}dddi}di}dddi}ddd}iiiiii}dddi}ddd}iii}ddd}iii}ddi}ddd}}iiiii}ii}ddd}iiii}iiiiii}ddd}iiiiiii}d}iiiii}iiiii}iii}i}iiiiii}}ii}ddd}iiii}iiiiiii}ddi}di}d}iii}iiii}iiiiii}dd}}i}ddd}iiiii}}}}iiiii}ddd}}i}iiii}dd}iii}iiiii}iiiii}}iiii}ddi}ddd}iii}iiiii}i}iiiii}ii}d}i}ii}iii}iiiiii}d}iiiii}d}iiii}ddd}ii}iiii}ii}}i}}iiiiii}iiiii}}iiiiii}dd}iiii}iiiii}iii}ii}ddi}d}iiiiiii}ddd}iiii}ddi}ddi}di}dd}iii}ii}iii}i}iiiiiii}di}ddd}}ii}ddi}di}d}iiiii}d}}ii}}ii}ii}ii}dd}iiiiii}i}iiiii}dddi}ddd}iii}i}iii}ddi}ddd}iiii}d}i}iiiiii}dd}iiiiiii}dddi}d}iiii}i}iiii}d}i}ii}iii}d}}ii}iii}i}iiiiiii}dddi}ddi}ddd}i}iiiii}iiii}i}iii}iiiii}}iiiiii}d}iiii}}iiiiii}dd}iiii}d}i}iiii}i}ii}iiiiii}i}i}iiiiiii}di}ddd}iiii}iii}}iiii}ddi}di}ddd}iiiii}iii}ddi}dd}iiiiii}iiii}iii}iiii}ddd}iiii}iii}iiiiii}iiii}iiii}d}iiiiiii}ddd}iii}iiii}ddi}di}dd}i}d}iiiiii}iiiii}iiiii}dd}iii}iiii}i}ii}ddd}}iiiiii}dddi}ddd}iii}iiii}iiiiiii}d}iiiii}iiiiii}iii}iii}iiiii}dd}iiiii}iiiii}iiiiii}i}dddi}ddd}iiiiiii}ddd}iiii}ii}i}iii}iii}iiii}iiiii}ii}ii}ii}ddd}ii}iiiiii}di}dd}iiii}dd}iiii}iiiii}iiiiii}iiiii}iiiii}ddi}d}iiii}iiii}ii}iii}i}iiiiii}iii}}i}iiiii}iiii}d}i}iiiiii}iiiii}dddi}dd}iii}iii}di}d}iii}iiiii}dd}i}ddd}iiiiii}iiii}dddi}ddd}}iii}iii}ii}i}ddi}ddd}ii}dd}i}}iiiiii}dd}}iiii}ii}dddi}ddd}i}iii}i}iiiii}ddd}ii}dd}iiii}}i}iiiiii}ii}}iiiiii}dddi}d}ii}ii}iiii}iiiiii}i}ddd}iiiiii}iiiiiii}dd}i}iiiiii}iii}iiiiii}iiii}ddd}iiii}iiiiii}dddi}ddd}iiii}iiii}ii}i}ii}iii}ii}iiiiii}d}iiiiiii}di}ddi}ddi}dddi}dddi}d}iii}dd}iiiiiii}di}dd}iiiiii}iiiii}ddi}di}dd}i}iiiii}iiiiii}}iiiii}d}ii}ii}d}iii}iiii}ddd}iiiiii}i}}i}di}di}d}ii}ddd}ii}iii}dd}iiiiii}iiiii}d}iiiiiii}d}iii}ii}d}ii}iiiii}dd}}iiii}iii}iiii}ddd}iiiiii}iiii}iiiii}iiiii}ii}ii}iiiii}i}ddd}iiiii}iii}ii}iiiii}iii}iiiii}}}iii}iiiiii}}ii}}iiiiii}dd}iiiiii}ii}ii}i}iiiii}di}ddd}iiii}d}iiiiiii}ddi}ddd}iii}ddd}iiiiiii}di}ddd}ii}ddd}iiii}dd}}iii}iiiii}dd}iii}}iiiii}dd}ii}iiiii}}ii}ddd}ii}dd}iiiii}ddd}iiii}dd}i}i}iiiiii}i}i}iiiiii}di}d}iii}iii}iiiii}d}iiiiiii}dd}iii}iiiii}iiiii}di}d}iiiii}ddi}dddi}di}d}ii}i}}iiii}ii}iiiiii}ddd}i}i}iiiiii}iiiii}iii}iiiii}dd}iiiii}i}iiii}iiii}iiiiii}iiii}iii}ii}iiiii}dd}i}}iii}ii}iii}dd}ii}dd}iiiii}iii}iiii}iiiii}ii}d}iiiiiii}dd}iii}ii}ddi}d}iiiiii}d}i}ii}i}dddi}dd}iiiii}i}i}ddi}ddi}ddd}}iiii}ddd}iiii}iiiii}i}ii}ddd}iiiiii}iiii}iii}iiiii}}iiiii}dd}}iii}dd}ii}iiiii}ii}iii}ii}}iiiiii}i}iiii}iiiii}d}iiii}iiii}iiiiiii}ddd}iii}d}iii}ii}iii}iiiiii}i}i}iiiiii}ii}dd}iiiii}iii}ddd}iiii}iii}ii}iiii}iiiii}iiiiii}iiii}iii}i}iii}ddd}i}iiiii}dddi}ddi}ddi}ddd}ii}iiiiii}}i}i}i}iiii}}i}dddi}d}iii}ii}iiiiii}i}}iiiiiii}dddi}dd}i}i}iiiii}}iii}di}dd}iiiii}dd}i}iii}i}iiii}i}i}iiii}d}iii}dd}ii}iiii}ddd}}i}dd}iiiiii}dd}i}ddd}i}iiiiii}iiiii}i}ddi}di}d}i}iiiiiii}dd}iiiii}d}iiiiii}ii}iiiiiii}ddd}iiiiii}d}iii}ddd}iii}i}dd}i}di}dd}iiiiii}ddd}i}iiiiii}ddd}iiiiii}}iii}i}dd}i}ii}ii}d}iiiii}iiiii}ii}ddd}}}}ii}ii}}iii}i}i}}iiii}iiiii}d}ii}iiiiiii}dd}i}ddi}dd}iiiii}i}dd}iiiiii}iiiii}d}iiiii}dd}ii}iiii}ii}i}i}iiiiiii}di}dd}iiiii}ii}iiii}i}iiiiii}iiiiii}iii}ddd}}i}ddd}iiiiiii}d}iiii}iiii}dd}iii}iii}ii}ddd}iiiiiii}ddi}d}i}iiiii}iiiii}di}ddi}dd}}iiii}dd}ii}iiiiiii}dd}}ii}iiiii}d}ii}d}iiiii}iiiii}ddi}ddd}iiiiiii}dd}}iiiiii}ii}i}ddd}iiiii}iiiiii}do
```
Disclaimer: This crashes TIO. calculates then outputs the number.
# Deadfish / Deadfish~, 6536 bytes
```
iiosdoddddddddoiisiiodddoiiodddoosiiioddddosddodoioddddddooiisdoiodddoioddddodddoiiisodddddooiioododddoosiioiiodddddoiioddosddoddddddoiisodddddddddoiiiodddoiisiioooiiiodododddodsoddodddodosdooddodddosdooioddddddoiioiioddddoddoiisoddddddosodddddddoioiodsodddddddoddoiisoddoiosdoddddddddoiisiiiodddddddoiiisoddddddosddoiioddddddoioiiiodddddddoioisioiiioodddddosdoddddddoosiodddosiiioddddoosdoddodddddoiioioodsdoddoddoddddoiisoioiiiooddddddoiosddoddoddosodddodddddoisiioiioddddddddoiiooioioiioiioddddddddoiisiiodoiiiodddddododoisiiioddddoioddddooiisiiiodddddoisdoddddddddoiioosioddsoddddddosdododddddddoiiisdodddddooiioddsoddddoooddddoiioiooiioododdddoisiiioddddddoiisoddoodddddddoiiioosdoddddddddoiisiiioddoddsoddddddoiioioiiiodddodoiiioddddoiiodddoiiiododdddoisioioiiioddoododdddosiiioddddoiiioddddddoiisoiiioddddosddooddddoiioiiioodddddddoisiioiiiodddddoiiioddddosddoddddoddoiioddoisiiodddoiiioiiioddddddddoiisdooiodddoddddddoiioddoiisiiioiodddddddoisioododooiioioodddddoisiiiodddododddoiisiioiiiooddddododsodddddddoisdoddddddodoiisdoddddoiioddddddoiisiioiioddddoiiioiiodddddddddoiiiosdooddddddoddoiiisoddddddooiooiioiiodddddddoisiiodddosoddddoiiiodddddooiiiodddosdoodoiiodddddddoddoioisiioddddosiiioddddoiiiooiodddddddoiiioosoddddoiiioddddoddoiodddoiisoiioddoddddoiiisodddddddosodddooiosoiioiiiodddddddoisdodddddddoioisdododdoddddoiisodddddddoiodddoiioisooddoiioddddoodoiioddoiioddddoddoiiosioiioiioddddddddoisioiiododddddoioisdoddddoioodddodooiisodddddoddosioiiododdddosiiioiodddddoddoiisdodddddddoisiiododdddodoioiisdoodoioddoddodsdoddoddddoddoiisioddoiiioddoddddoiiiosdodddddoioddoisooddoiioodddddddoiosodddddddddoioisiiodddoosddooddddodddoiisiiioddddoddoiisoddddddododdoiisiiioiioddddoiioodddddddoiisioiiioddddddddoioiosioiiioddddddoisodododdddddoiisdoddddddosiiioiodddddddoiioiiiodddoiioddddodoiisiiiodddddddoiisioododdddoiioodoiisdoodddddoodoisdodddodddoisdooddddoddoisdoddddddosoiooddodddoiiioiiiodddddodoiisiiiodddddddooiiisodddddddddoiiiosdodddodddoisoodddddodddodoiisodsdoddddddddoiisoiiioddddddoiisdoddddddddoooiiisoddoddddosddoiioddodddddoiosoddddddosdododdddddodoioisiiiodoioodoiiodddoiioddddddoisiodoiioiiioddddddoiodsodddddddoisdooodddddddooiiodosiioddddoioddodoiisiiioodddodsoddddodddoisoddddddoiioddddoisodddoiosiioddoiiodoiodddddoioisdodddddddodoiisiioddodsdoioddoddddddoisioioddoooiioiiiodddddddoddoiisoddooioddoioioiioiiodddoddddoiisiiioodoiiododddddddoiisioioddddosodddoisiioddddddooiisoddddoiisiiioiodddooioddooiioiiiodoioooodddddddoioddoiisdoddddddoddoiisiodddosiiioiododddodsoddddddddoiioiiiooiiioddddoioiiioddoiioddodddddddoiiooisoddddddddoiisodddddddddoiisiiodddddoiiosdoddoiiiodddddddddoiisiiodddosoddddddodosiodddosiiiodddddddoiisiiiodddddddoiisoddosiiiodddddosoiioiiodoioddddddosoioddosoddddoiiodddddododoiisiioiiiodddddddoioiioiiioddddddododoiisioddodddoiiiosddoiiodddodddosddodddddoisdodddooddddooiiosoddddooiiioddddddoioiiiodddododoisoddddoiisiiioioddddddddooiisodosdoooddddoiiiodddddodoiisodddooddddddoiisiiioddddoddoisioiioddddoddoisioddddoisiiiodddddoddoiodoiisiiiodddddddoiiosiioiioddoddododdooisiododddoiisdoodddddodddoiioisoddddddddoisiioddoiiioiiododddddddoiioooodddoiisoooddosiioddddddoiisiiiodoiiodddoddsoddoddoodddddoiisiiiodddddosioiiioddddddddoiiosiiioodddddoisoddoiiodddddoddddoiiisdodddddosoddddddddoisiioddoiiioddoddosddoddddoioddoisodddddddoisoddddoiiodddodddodoiisodsdoddddddddoiiisdoddddodsododoiioddoodoiiiodddodddddoisoiiioiioddddododdddooiiisodddddddddoiiisdodddodddddoiisiiioddddoiiiododddoiosddoddddodosiioiioddddddddoiisoddddoiisiiiooddddddoiiodoisodddddddoisoddddddoosodddooddddddoiisoodoiioodddddoiiooisooodddddddoodooisioiiiodddoddddoisiododsoddddddoddoisiiiodddddoisodddddddoiosdoddddodsdoddddoddddoiiisoddodddoddosoddoddoioisioioioddddddoisiiodddoiioddsodddoioddddddoiosiioiiiododddoddsodddddoiodddoddoiiioiiioododoioioiiioddddddosdoddodddddoisoiiiodddodddoisiiioddddddoiisoddodddddoosiiiodddddosodddoisiioiioioddoodoiiodddoiioiiodddoddddddoioiioiiodddoddoiisioddsodddddodsdodddddodddoiisiiiooioddddoiiiodddddddoiisiioiioddddoodsdoodddoioddoiiiodddddoisdodddddosddodddddddoiisiiioiiodoioddddodddoisdoddddddddooiiisdoddddoddddoiisioddddoiioiodsdododdoiioddddddooiiosddodddoiiioioddddoiiiodddddddoiiioioddddoiiisoddddddoddoiodoisiodddddooiisoddddoiiiosoodddddddddoiiisdoddddddoosoioiodddoiiioddddoiooddoisioioiiododdddddoiisdodddddoiiioddoddddoiioisoodddddddddoiiiodoiosddoddddoiioioioddddddodoiiisodddddddosiiiododdddddoiisodooiiioddddodoisiiodddddoiisdoddddddddoiisioiiiodddddoddooisioiiiodddddddoiosodsodddddddddoiisiiiodddodddoiioooiodsdoddddodddoiisdodododdoiioiiiodddoodddosdoddoddddddoiisiiiodddoiooiioddddddoiisdodddddddoioisdoddoddoddddoiisiiioiiodddddodsooddoddddddoisiiododoiodddddoiiodooiosiioioddddddoisiioiiodddddddoisoiododosddoddddosdoddoiiioddoddddoioiiodddddodoiisioddosodddddddoisodddoioiodddddosodddddddddooiisiiioiodddddoiioioiioddddddddoiiiosododddddosdodddddoiodsdododddddosiodddoiosooddddddododdoiisiiooddddddoiisiiooiiiododooddddosoddddddoiiioiiioddddoddosddoddddddoiiododdoiiioodoisododddddodddoiisiioiiodddodddosioiioddddodddoiisioioddoiiioiioddddddoddoiisdodddoioddddosiiioddoddsodddddddddoiiisoddddddddodoiiisdoddoiiioddoiiodddddoodddoisiioiiodddddosodddoddoddddoiiisdodododdddoiodddoiiosioiiioddddddddoioiisodddddddosioddodosiioddddddoiisiioddoiioddddddoiiisoddddddodddoiisoddddoiisiooddddooisioddsodddddodoiiioiiiodddddddosiiioioddddddooddoiisiiiodddddddoiiisodddddddosiiiodddoddddoooiiisdoddddddddoiisiiioddddoddoisiioiiioddddodddosiioiooiiodddddoddooddoiisiiiodddddoisoddddoddoddooiisodddddoioddsododddddddoiisodddddddosiiioddoiiioioddddodddoisdoddddddosioiiiododddddosiiioioddddddoisoddddddddooiioosdoiodddddddoddoiisiiioiiooddddddodosoiiooddddddoiiioiodsododdddodddoiisdoddddddddooiisodddodoiisiioddddddoiisiioddddddooiisioiioiioodddddodddodoiodoiisoddosiiioiioddddddoddoisiioiododddddooiisdodddddoiioioddoddddoiioosiioiooddoodoiiodddddooisiioiiioddddddddoiisoodddoiiodddooiiioddddddoosiodddoioioiiioddddddoisiodddddoiisiioiioddodddddoiisodddoddddosoddoisoddodddddosiioiioddoiiiododdddddddoiisiiioiodddddodosiiioddddddoioiododoisiiiooiiodddddddddoiisoiiioiodoiiodddddddddoiisiiooiiioddddddddoiisdododddddosodsodddddddoisoddddoioiioddddodddoiosiiiododdoddooosiiiodddddosiiioddddddodoiiosiioddddddoiisiiiooiodddoddoioodsdododdddddoisiiioddddddoisiiiodddddddoooiisiiioddoddddodoiiisdooddoodddoiiiodddddoioisdodddoddddoisioddsoddddddddoisiiodddddoiisdodddddddoisiioddddddooiisoddoiosdoddoooddoddddoiioisododdoddddddoiisioiioddddosddoddddddoisoiioiiioddddddddoiisodododdodododddoiisiiioiodddddddoisiiiododdoiodoiododododdoiisiioooddddodoisooddddo
```
Just does the digits.
# Deadfish~, 5965 bytes
```
iiosdo{d}oiisiiodddoiiodddoosiiioddddosddodoio{d}iooiisdoiodddoioddddodddoiiisodddddooiioododddoosiioiiodddddoiioddosddo{d}ioiiso{d}oiiiodddoiisiioooiiiodododddodsoddodddodosdooddodddosdooioddddddoiioiioddddoddoiisoddddddoso{d}iioioiodso{d}iioddoiisoddoiosdo{d}oiisiiio{d}oiiisoddddddosddoiioddddddoioiiio{d}oioisioiiioodddddosdo{d}iioosiodddosiiioddddoosdoddo{d}ioiioioodsdoddoddo{d}oiisoioiiioo{d}iioiosddoddoddosodddo{d}ioisiioiio{d}oiiooioioiioiio{d}oiisiiodoiiiodddddododoisiiioddddoio{d}ooiisiiiodddddoisdo{d}oiioosioddsoddddddosdodo{d}oiiisdodddddooiioddsoddddoooddddoiioiooiioododdddoisiiio{d}ioiisoddoo{d}oiiioosdo{d}oiisiiioddoddsoddddddoiioioiiiodddodoiiioddddoiiodddoiiiododdddoisioioiiioddoododdddosiiioddddoiiio{d}oiisoiiioddddosddooddddoiioiiioo{d}ioisiioiiiodddddoiiioddddosddoddddoddoiioddoisiiodddoiiioiiio{d}ioiisdooiodddo{d}oiioddoiisiiioio{d}ioisioododooiioioo{d}ioisiiiodddododddoiisiioiiiooddddododso{d}iioisdo{d}iiodoiisdoddddoiio{d}oiisiioiioddddoiiioiio{d}oiiiosdoo{d}iioddoiiisoddddddooiooiioiio{d}ioisiiodddosoddddoiiiodddddooiiiodddosdoodoiio{d}iioddoioisiioddddosiiioddddoiiiooio{d}oiiioosoddddoiiioddddoddoiodddoiisoiioddo{d}oiiiso{d}iiosodddooiosoiioiiio{d}iioisdo{d}ioioisdododdoddddoiiso{d}iioiodddoiioisooddoiioddddoodoiioddoiioddddoddoiiosioiioiio{d}ioisioiiodo{d}ioioisdoddddoioodddodooiisodddddoddosioiiododdddosiiioiodddddoddoiisdo{d}ioisiiododdddodoioiisdoodoioddoddodsdoddoddddoddoiisioddoiiioddo{d}oiiiosdodddddoioddoisooddoiioo{d}iioioso{d}oioisiiodddoosddooddddodddoiisiiioddddoddoiisoddddddododdoiisiiioiioddddoiioo{d}oiisioiiio{d}oioiosioiiio{d}iioisododo{d}ioiisdo{d}iiosiiioio{d}ioiioiiiodddoiioddddodoiisiiio{d}oiisioodo{d}oiioodoiisdoodddddoodoisdodddodddoisdooddddoddoisdo{d}iiosoiooddodddoiiioiiio{d}iodoiisiiio{d}ooiiiso{d}oiiiosdodddodddoisoodddddodddodoiisodsdo{d}oiisoiiio{d}ioiisdo{d}oooiiisoddoddddosddoiioddodddddoiosoddddddosdodo{d}iodoioisiiiodoioodoiiodddoiio{d}ioisiodoiioiiioddddddoiodso{d}iioisdooo{d}iooiiodosiioddddoioddodoiisiiioodddodsoddddodddoisoddddddoiioddddoisodddoiosiioddoiiodoio{d}ioioisdo{d}iodoiisiioddodsdoioddo{d}ioisioioddoooiioiiio{d}iioddoiisoddooioddoioioiioiiodddo{d}oiisiiioodoiiodo{d}oiisioioddddosodddoisiio{d}ooiiso{d}oiisiiioiodddooioddooiioiiiodoioooo{d}iioioddoiisdo{d}iioddoiisiodddosiiioiododddodso{d}ioiioiiiooiiioddddoioiiioddoiioddo{d}oiiooiso{d}ioiiso{d}oiisiio{d}ioiiosdoddoiiio{d}oiisiiodddosoddddddodosiodddosiiio{d}oiisiiio{d}oiisoddosiiiodddddosoiioiiodoio{d}iiosoioddosoddddoiiodddddododoiisiioiiio{d}iioioiioiiio{d}iiododoiisioddodddoiiiosddoiiodddodddosddodddddoisdodddooddddooiiosoddddooiiio{d}iioioiiiodddododoiso{d}oiisiiioio{d}ooiisodosdoooddddoiiiodddddodoiisodddoo{d}oiisiiioddddoddoisioiioddddoddoisioddddoisiiiodddddoddoiodoiisiiio{d}oiiosiioiioddoddododdooisiododddoiisdoodddddodddoiioiso{d}ioisiioddoiiioiiodo{d}ioiioooodddoiisoooddosiio{d}oiisiiiodoiiodddoddsoddoddoo{d}oiisiiiodddddosioiiio{d}oiiosiiioodddddoisoddoiiodddddo{d}oiiisdodddddoso{d}ioisiioddoiiioddoddosddoddddoioddoiso{d}iioisoddddoiiodddodddodoiisodsdo{d}oiiisdoddddodsododoiioddoodoiiiodddo{d}ioisoiiioiioddddodo{d}ooiiiso{d}oiiisdodddo{d}oiisiiioddddoiiiododddoiosddoddddodosiioiio{d}oiiso{d}oiisiiioo{d}ioiiodoiso{d}iioisoddddddoosodddoo{d}oiisoodoiioo{d}oiiooisooo{d}iioodooisioiiiodddoddddoisiododsoddddddoddoisiiiodddddoiso{d}iioiosdoddddodsdoddddo{d}oiiisoddodddoddosoddoddoioisioioio{d}ioisiiodddoiioddsodddoio{d}ioiosiioiiiododddoddsodddddoiodddoddoiiioiiioododoioioiiioddddddosdoddo{d}ioisoiiiodddodddoisiiio{d}ioiisoddodddddoosiiiodddddosodddoisiioiioioddoodoiiodddoiioiiodddo{d}oioiioiiodddoddoiisioddsodddddodsdodddddodddoiisiiiooioddddoiiio{d}oiisiioiioddddoodsdoodddoioddoiiiodddddoisdodddddosddo{d}oiisiiioiiodoioddddodddoisdo{d}ooiiisdoddddo{d}oiisioddddoiioiodsdododdoiio{d}iooiiosddodddoiiioioddddoiiio{d}oiiioio{d}oiiisoddddddoddoiodoisio{d}ooiiso{d}oiiiosoo{d}oiiisdo{d}iioosoioiodddoiiioddddoiooddoisioioiiodo{d}ioiisdodddddoiiioddo{d}oiioisoo{d}oiiiodoiosddoddddoiioioio{d}iodoiiiso{d}iiosiiiodo{d}oiisodooiiioddddodoisiio{d}ioiisdo{d}oiisioiiiodddddoddooisioiiio{d}ioiosodso{d}oiisiiiodddodddoiioooiodsdoddddodddoiisdodododdoiioiiiodddoodddosdoddo{d}oiisiiiodddoiooiio{d}ioiisdo{d}ioioisdoddoddo{d}oiisiiioiiodddddodsooddo{d}ioisiiododoio{d}oiiodooiosiioio{d}ioisiioiio{d}ioisoiododosddoddddosdoddoiiioddoddddoioiio{d}iodoiisioddoso{d}iioisodddoioiodddddoso{d}ooiisiiioiodddddoiioioiio{d}oiiiosododddddosdodddddoiodsdododddddosiodddoiosooddddddododdoiisiioo{d}oiisiiooiiiododooddddosoddddddoiiioiiioddddoddosddo{d}ioiiododdoiiioodoisododddddodddoiisiioiiodddodddosioiioddddodddoiisioioddoiiioiioddddddoddoiisdodddoioddddosiiioddoddso{d}oiiiso{d}iodoiiisdoddoiiioddoiiodddddoodddoisiioiiodddddosodddoddo{d}oiiisdodododdddoiodddoiiosioiiio{d}oioiiso{d}iiosioddodosiio{d}oiisiioddoiio{d}oiiisoddddddodddoiiso{d}oiisiooddddooisioddsodddddodoiiioiiio{d}iiosiiioio{d}iiooddoiisiiio{d}oiiiso{d}iiosiiiodddo{d}oooiiisdo{d}oiisiiioddddoddoisiioiiioddddodddosiioiooiiodddddoddooddoiisiiiodddddoisoddddoddoddooiisodddddoioddsodo{d}ioiiso{d}iiosiiioddoiiioioddddodddoisdo{d}iiosioiiiododddddosiiioio{d}iioiso{d}iooiioosdoio{d}iioddoiisiiioiiooddddddodosoiioo{d}oiiioiodsododdddodddoiisdo{d}ooiisodddodoiisiio{d}oiisiio{d}ooiisioiioiioodddddodddodoiodoiisoddosiiioiioddddddoddoisiioiodo{d}iooiisdodddddoiioioddo{d}oiioosiioiooddoodoiio{d}iooisiioiiio{d}ioiisoodddoiiodddooiiio{d}iioosiodddoioioiiio{d}ioisio{d}oiisiioiioddo{d}ioiisodddoddddosoddoisoddodddddosiioiioddoiiiodo{d}oiisiiioiodddddodosiiio{d}ioioiododoisiiiooiio{d}oiisoiiioiodoiio{d}oiisiiooiiio{d}ioiisdododddddosodso{d}iioisoddddoioiioddddodddoiosiiiododdoddooosiiiodddddosiiio{d}iodoiiosiio{d}oiisiiiooiodddoddoioodsdodo{d}ioisiiio{d}ioisiiio{d}oooiisiiioddoddddodoiiisdooddoodddoiiio{d}ioioisdodddoddddoisioddso{d}ioisiio{d}ioiisdo{d}ioisiio{d}ooiisoddoiosdoddoooddo{d}oiioisododdo{d}oiisioiioddddosddo{d}ioisoiioiiio{d}ioiisodododdodododddoiisiiioio{d}ioisiiiododdoiodoiododododdoiisiioooddddodoisoo{d}o
```
Also just does the digits.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes
```
IΣX⍘!<JOγ…¹¦²⁸¹
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEI7g0VyMgvzy1SMMpsTg1uAQok66hpGjj5a@ko5CuqaMQlJiXnqphqKNgZGGoCQLW////1y3LAQA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
!<JO Literal string of printable ASCII
⍘ γ Convert from base 95
X Vectorised raise to power
…¹¦²⁸¹ Range from 1 to 280
Σ Take the sum
I Cast to string
Implicitly print
```
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 12 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
-„{“FR]„;^]∑
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjBEJXUyMDFFJXVGRjVCJXUyMDFDJXVGRjI2JXVGRjMyJXVGRjNEJXUyMDFFJXVGRjFCJXVGRjNFJXVGRjNEJXUyMjEx,v=8)
[Answer]
# [Perl 5](https://www.perl.org/), 33 bytes
```
say+(($q=1114112)**281-$q)/($q-1)
```
[Try it online!](https://tio.run/##K0gtyjH9/784sVJbQ0Ol0NbQ0NDE0NBIU0vLyMJQV6VQUx8oqmuo@f//v/yCksz8vOL/ur6megaGBkA6KTM9M68EAA "Perl 5 – Try It Online")
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), ~~44~~ ~~31~~ 30 bytes
Saved 13 bytes thanks to [Makonede](https://codegolf.stackexchange.com/users/94066/makonede)!!!
Saved a byte thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)!!!
```
print((x:=17<<16)**281//~-x-1)
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/v6AoM69EQ6PCytbQ3MbG0ExTS8vIwlBfv063QtdQ8/9/AA "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [cQuents](https://github.com/stestoltz/cQuents), 14 bytes
```
#280;1114112^$
```
[Try it online!](https://tio.run/##Sy4sTc0rKf7/X9nIwsDa0NDQxNDQKE7l/38A "cQuents – Try It Online")
## Explanation
```
#280 n = 280
; output sum of first n terms
1114112^$ each term is 1114112 ^ current index
```
[Answer]
# [Perl 5](https://www.perl.org/) `-Mbigint`, 26 bytes
```
say 1114112**281/1114111-1
```
[Try it online!](https://tio.run/##K0gtyjH9/784sVLB0NDQxNDQSEvLyMJQH8Ix1DX8//9ffkFJZn5e8X9dX1M9A0MDIJ2UmZ6ZVwIA "Perl 5 – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 30 bytes
```
say 1114112**281 div 1114111-1
```
[Try it online!](https://tio.run/##K0gtyjH7/784sVLB0NDQxNDQSEvLyMJQISWzDCpgqGv4/z8A "Perl 6 – Try It Online")
[Answer]
# [F# (.NET Core)](https://www.microsoft.com/net/core/platform), 60 bytes
```
printf"%A"(Seq.sumBy(fun i->bigint.Pow(1114112I,i)){1..280})
```
[Try it online!](https://tio.run/##SyvWTc4vSv3/v6AoM68kTUnVUUkjOLVQr7g016lSI600TyFT1y4pMx0oqReQX65haGhoYmho5KmTqalZbainZ2RhUKv5/z8A "F# (.NET Core) – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~39~~ 36 bytes
Based on the formula presented in [@Delfad0r's answer](https://codegolf.stackexchange.com/a/220942/80745).
```
[bigint]::Pow(1114112,281)/1114111-1
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/PzopMz0zryTWyiogv1zD0NDQxNDQSMfIwlBTH8Ix1DX8/x8A "PowerShell – Try It Online")
] |
[Question]
[
## Summary
We already have a challenge for the [minimal number of characters for Turing completeness](https://codegolf.stackexchange.com/q/110648/48931). But what about the minimal maximum byte?
## Challenge
For a language of your choice, find a subset of characters that allows your language to be [Turing complete](https://en.wikipedia.org/wiki/Turing_completeness) with the minimal maximum byte value.
## Example
If your language is using the UTF8 code page and Turing complete using only the characters `abcd()`, these characters have the byte values `97, 98, 99, 100, 40, 41`, and the maximum there is `d = 100`, so your score would be 100.
## Scoring
Your score is the maximum byte value of your Turing complete subset, expressed in the code page of your language's interpreter. For most languages this will be either LATIN-1 or UTF8, but if your language uses a different code page (such as [Jelly](https://github.com/DennisMitchell/jellylanguage/wiki/Code-page)) use that to score instead.
In the unlikely event that you require multibyte characters to be Turing complete, just use the maximum byte in the multibyte sequence to score. For example, if your UTF8 language required `Ȧ`, this is encoded as the literal byte sequence `200, 166`, so it would score 200.
The lowest score wins.
## Notes
* The minimum score is 0, the maximum is 255.
* For some languages ([cough](https://esolangs.org/wiki/Lenguage)) this challenge will be trivial to score low on. I urge you to upvote interesting answers over trivial ones.
* Provide an explanation of why your subset is Turing complete.
* Your subset only needs to be Turing complete, it does not need to be able to use every feature of the language.
[Answer]
# [Haskell](https://haskell.org), score 61 (`=`)
Characters used: `!#$%&()=`
The [SKI combinator calculus](https://en.wikipedia.org/wiki/SKI_combinator_calculus) can be implemented in Haskell with nothing but basic function definition, using `!#%&` as identifiers. Infix function application `$` is used to save on parentheses and strip down one character from both **`S`** and **`fix`**. Finally, **`K`** only takes two arguments and can be more shortly defined as an infix operator.
### `S` combinator: `s x y z = x z (y z)`
```
(!)(#)(%)(&)=(#)(&)$(%)(&)
```
### `K` combinator: `k x y = x`
```
(!)#($)=(!)
```
### `fix` combinator: `fix f = f (fix f)`
```
(&)(!)=(!)$(&)(!)
```
Since Haskell is a strongly typed language, the [fixed-point combinator](https://en.wikipedia.org/wiki/Fixed-point_combinator) **`fix`** is needed in order to make (typed) combinatory logic Turing-complete.
The **`I`** combinator is not strictly required since it is extensionally equivalent to **`SKK`**, but it can be defined as `(*)(!)=(!)`.
### [Try it online!](https://tio.run/##y0gszk7Nyfn/X0NRU0NZU0NVU0NN0xbEUtNUgfC4gFLKGipAUUUgW00TSIGYKhDm//8A)
[Answer]
# [Python 2](https://docs.python.org/2/) with exit code, 102 (`f`)
```
def TM_SIM(TRANSITIONS, STATE, TAPE=[], HEAD_POS=0):
TAPE += ["X"]
HEAD_POS += HEAD_POS < 0
SYMBOL = TAPE[HEAD_POS]
STATE, NEW_SYMBOL, HEAD_DIRECTION = TRANSITIONS[(STATE, SYMBOL)]
TAPE[HEAD_POS] = NEW_SYMBOL
HEAD_POS += HEAD_DIRECTION
STATE == "REJECT" < 1/0
STATE != "ACCEPT" == TM_SIM(TRANSITIONS, STATE, TAPE, HEAD_POS)
```
[Try it online!](https://tio.run/##jVVdj5pAFH1mfsV0kk0ki6n20ZSHGZyttH4FSGtrDbE6u5K4YAZ2o2n62@0FBsUVFhNCZuaec@@Zc8Nld0g2UfjpuIrWwiSEHNfiEXsj37VHLc@hY9f27MnYNbDrUY8b2KNTbs4XBh5w2venE9fs6D2kpcf43sRzMiMLpBXB9Oi0/ow7CGnuzxGbDLGZZZoXQeCoAmP@w88xqkbfdriVikg5Z0XzliLkYB0yaLmOc1JgnNNVqDqlBq6mFGDTxMThXyFAQHL3Y6cIfIAAtSw@hQCAGkw6O6QfwVeEdjIIE0wGwdNGxEn7zyEReLVZyuUqEbKH7@LfIcF3@Hm5b6XN0BESe7HC6RqhtCsJ0PzdchuEaxk9i1YMxiNtSof2uO9MRtwvSYGb/4VLtYg14NY3f8gfPN8aUIcYcAei93CLAPo7d1zuO/aXgefTNDSD131XN@qorJLKbqHOcqoyUBE6gM8IVWLe0UnLxaoArJ7LmrhKaX6HN0Xb3RrFrF4xa1LMGqxlTdwKxexaccWFMprDXe5lzSra0r7s47Wv6vsodbES/X7PK@TemJxdSLlJPWvWc5mp0hxaTn8ZqpTD6vEXPXvzpZza/Q@U2WPb89Vowlf4ApANYBNvgziBwQCniTzAXNbUlKqZEgYuZVebLJOONLFfiV2CfwkZ9YPXIA6ikEsZyTSrFMmLDPHDchsLVOw8@QKT6jGS@aSKExh4TzgI4adAwTjCwA1CGUvXlLLsyU6yd2Zv3li1pkxt8wOW4RdQPp@kpSLG1WwsBfXjfw "Python 2 – Try It Online")
This code limits itself to the keyword `def` for highest character `f`. The function definition is used for looping via recursion. Python's logical short-circuiting is used for control flow, avoiding the need for a keyword like `if`, `and`, `or`, or `while`. For example, the recursive call in `STATE != "ACCEPT" == TM_SIM(...)` does not happen if we're in the accept state -- because the first inequality already fails, Python moves on without evaluating further.
Because none of the usual output method work (`print`, `return`, `exit`, etc), we return via exit code by terminating with or without error. So, this code is limited to decision problems. In practice, large inputs will give a stack overflow ("maximum recursion depth exceeded").
The code shown is a function simulating an arbitrary Turing machine that's given as input, which is of course Turing complete. The [TIO](http://Try%20it%20online!) shows it tested with a Turing machine that checks palindromes.
We avoid all keywords except the `def`. Since the only characters bigger than lowercase in letters in byte value are `{|}~`, it was easy to do without them too. For clarity, the variables in the code have been given readable names, using uppercase since these are smaller than all lowercase letters. We could get rid of these and many other symbols, though this of course wouldn't affect the score.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), score=61 (`=`)
```
$01234567;=
```
This abuses the linker by forming a machine language program that spans several scalar variables and avoids array characters such as `[]{}`.
The following is an example of a "Hello, World!" "program" that should work on Linux and OSX for x86 and x86\_64.
```
$=01672007152;$$=011000000000;$$$=015733066145;$$$$=015725620054;$$$$$=04131066162;$$$$$$=010060030412;$$$$$$$=02141007620;$$$$$$$$=013100000000;$$$$$$$$$=015224251132;$$$$$$$$$$=026024655401;$$$$$$$$$$$=020063250004;$$$$$$$$$$$$=030304142203;$$$$$$$$$$$$$=037777630536;$$$$$$$$$$$$$$=012625655307;$$$$$$$$$$$$$$$=01134122;$$$$$$$$$$$$$$$$=0503601000;$$$$$$$$$$$$$$$$$=06127257132;$$$$$$$$$$$$$$$$$$=01700330300;$$$$$$$$$$$$$$$$$$$=0141405;
```
[Try it online!](https://tio.run/##bZDLSsNAFIZfJhQtFM59FsGHCUMN0moX7UIsvrrjf1KiSXV2833nXndjra11T8RRhKiwS9/ll2l@@CfwokoRbJ7gRsQDSW4TATJWzpiQG8kooiBSqJkBCht4QfLMMlJ52fIHu4iJM6v84qwRJBbuRrzgKdBRxVHGlgJGpzlMhHRlUhW8UHKNtcoJJLCou1K5c9OhFKvJvYBx0sj16Y@DDBZcr6yXWlQtuFmO@0/y5LEGed9eh5e3h8freLqctpuu/2xf9fk4jOe2@9i/7@v5MtTDNw "C (gcc) – Try It Online")
[Answer]
# [Whitespace](https://esolangs.org/wiki/Whitespace), score = 32
Characters: `\t\n` (chrs 32 9 10)
The only legal chars in the language.
[Answer]
# [PHP](https://php.net), Score = 82 (`R`).
## Rationale:
Let's start at the end of the ASCII range, and work backwards until we find a character that's required for PHP.
PHP is case-sensitive only for user-defined things (variable names, constants), and is case-insensitive for all other things, so we can ignore the lowercase range.
Other than lowercase characters, the only characters above the uppercase range are:
* 0x7f - unused.
* `~` - used only for bitwise negation, unnecessary for Turing completeness.
* `{` and `}` - used for blocks, but PHP has an "alternative syntax" for control structures that doesn't use characters above the uppercase range.
* `|` - used for boolean OR (`|`, `|=`, etc), unnecessary for Turing completeness, and for logical OR (`||`, `||=`, etc), which has an alternate text form `OR`.
* ``` - used only for external command execution, unnecessary for Turing completeness, and anyway there are alternatives (`EXEC()`, `PASSTHRU()`, `SYSTEM()`, etc)
* `_` - used in many library function names and all compile-time constants, but not used by any keywords, so, since methods can be called dynamically, we can call methods that contain underscores by replacing them with `CHR(95)`.
* `^` - used only for bitwise XOR, and in regexes, neither required for Turing completeness.
* `[` and `]` - used for array indexing, which poses a problem, but `array_pop` and friends can be used instead.
* `\` is used for character escapes, unnecessary for Turing completeness, and escaped characters can be generated using `CHR()` and similar tricks anyway.
This means our max must lie in the uppercase characters.
We could trivially use `eval()` and `chr()` to evaluate any string of numbers as PHP code, which would give us a max character of `V`... but I think we can do better!
If we can do everything brainfsck can, then it'll be Turing complete, so let's write one. I'll replace the `[ ]` square braces of normal brainfsck with `( )` round braces, just so I can have the brainfsck program inline without using any high characters.
## Proof of concept:
```
<?PHP
// Create function refs, for those which have characters too high.
$FILL = 'ARRA' . CHR(89) . CHR(95) . 'FILL'; // Array_fill to create the tape.
$CHOP = 'ARRA' . CHR(89) . CHR(95) . CHR(83) . 'LICE'; // Array_slice for array indexing.
$POP = 'ARRA' . CHR(89) . CHR(95) . CHR(83) . 'HIF' . CHR(84); // Array_shift for array indexing.
$DEPOP = 'ARRA' . CHR(89) . CHR(95) . CHR(83) . 'PLICE'; // Array_splice for array inserting.
$LEN = CHR(83) . CHR(84) . 'RLEN'; // Strlen
$LOP = CHR(83) . CHR(84) . 'R' . CHR(95) . CHR(83) . 'PLI' . CHR(84); // Str_split
// "Hello world!" - note using round braces instead of square in the brainfsck code.
$IN = (">+++++++++(<++++++++>-)<.>+++++++(<++++>-)<+.+++++++..+++.>>>++++++++(<++++>-)<.>>>++++++++++(<+++++++++>-)<---.<<<<.+++.------.--------.>>+.>++++++++++.");
$INLEN = $LEN($IN);
$IN = $LOP($IN);
// Init tape with 10 zeros (add more for longer tape).
$A = $FILL(0,10,0);
// Set $AA ptr to first cell of tape.
$AA = 0;
FOR ($I = 0; $I < $INLEN; $I++):
// Extract element: $CH = $IN[$I].
$CH = $CHOP($IN, $I);
$CH = $POP($CH);
// Increment element at $I.
//$CH++;
//$CH = $FN($AA, $I, 1, $CH);
// Only need one of '+' or '-' for TC if memory wraps.
IF ($CH == '>'):
$AA++;
ENDIF;
IF ($CH == '<'):
$AA--;
ENDIF;
// Only one of '+' or '-' is critical for Turing completeness.
IF ($CH == '+'):
// Increment element: $A[$AA]++;
$ID = $CHOP($A, $AA);
$ID = $POP($ID);
$ID++;
$DEPOP($A, $AA, 1, $ID);
ENDIF;
IF ($CH == '-'):
// Decrement element: $A[$AA]--;
$ID = $CHOP($A, $AA);
$ID = $POP($ID);
$ID--;
$DEPOP($A, $AA, 1, $ID);
ENDIF;
IF ($CH == ')'):
$ID = $CHOP($A, $AA);
$ID = $POP($ID);
IF ($ID):
FOR ($LOOP = 1; $LOOP > 0; ):
$CH = $CHOP($IN, --$I);
$CH = $POP($CH);
IF ($CH == '('):
$LOOP--;
ENDIF;
IF ($CH == ')'):
$LOOP++;
ENDIF;
ENDFOR;
ENDIF;
ENDIF;
// I/O is non-critical for TC.
IF ($CH == '.' ):
$ID = $CHOP($A, $AA);
$ID = $POP($ID);
ECHO CHR($ID);
ENDIF;
ENDFOR;
```
## Possible improvements:
I don't see a way to avoid using `CHR()` for array indexing without using something worse, like backslash, or string manipulation functions that use `S`.
And I don't see a way to avoid `FOR()` for looping back without using something worse like `GOTO`, `WHILE`, or the `{}` of a recursive function definition.
If we can get rid of those two keywords, the next highest is the P in `<?PHP`, which is required, at least in later versions of PHP that deprecate short open tags. However, they have made a commitment that the short echo tag, `<?=` will always be supported, so that could perhaps be exploited to execute arbitrary PHP. Then there are the O's in `ECHO`. However, I/O isn't critical for Turing completeness, so we could just remove that. Then there's the N in `ENDIF`, and the I and F in `IF`, which could be replaced by the ternary operator, `?:`.
But even if there's a way to avoid using any keywords or library functions by name, variables must begin with an alphabetic or underscore character, so I suspect we'll definitely need at least `A`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), score: 86
```
+1 .VB
```
These characters have the codepoints `[43,49,32,46,86,66]` in the [05AB1E codepage](https://github.com/Adriandmen/05AB1E/wiki/Codepage), of which `V=86` is the maximum.
My answer for [the *Fewest (distinct) characters for Turing Completeness* challenge in 05AB1E](https://codegolf.stackexchange.com/a/210771/52210) which I posted just yet is: `+X.VB`. With these 5 bytes, `X=88` would have been the maximum. We avoid the `X` by using `1` and a space instead. After that `V=86` is the maximum.
With the remaining 6 bytes we can:
* `+`: Pops the top two items on the stack, and adds them together
* `1` : Push 1 to the stack
* `.V`: Pops and evaluates the top string as 05AB1E code
* `B`: Pops the top two items on the stack, and does base-conversion
I've tried to get rid of `V`, which would only be possible with `.E` (execute as Python code - `exec`). Now we're using `.V` to evaluate and execute as 05AB1E code, for which we can first create the entire strings with certain single-byte builtins like `J` (join), `«` (append), etc. But if we would use `.E` we can't do that anymore. A potential fix for this is switching from [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands) to [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b). In the legacy version (which is built in Python) we can use `+` to concatenate characters, which isn't possible in the new version (which is built in Elixir). Unfortunately, the `.E` builtin is (evaluate as Python code - `eval`) in the legacy version, and `.e` is `exec`. With just `eval` we unfortunately can't do everything we want, like checking if the input is a prime number. (Maybe we can, but my Python knowledge is too limited for that. If someone knows a piece of Python 3 code which can be wrapped within `eval("...")` and will check if the `input()` is a prime number, lmk.) And the `e` in `.e` would be even higher than `.V`, so it's pointless to use that instead.
**Try it online:**
Here a few example programs using these six bytes:
[Try it online: 2+2.](https://tio.run/##yy9OTMpM/f/fUMFQG4S1//8HAA)
[Try it online: Check if the input is a prime number.](https://tio.run/##yy9OTMpM/f/fUIEOUJtkQBdnkeMwbSe9MGCoGQIA)
[Try it online: Print "Hello, World!".](https://tio.run/##yy9OTMpM/f/fUIEA1EYDBDWQBrWJA1S2lSw3jDCnkOMg@riJ3lCbXmA0jGgSLqO5iLrxNlxLwBFQwI2WX4Os1B@tKskBTnphw7CdQceWhrYTme4h3yPAOPv/HwA)
[Try it online: Print the infinite Fibonacci sequence.](https://tio.run/##yy9OTMpM/f/fUGEIQW2agCEVBIMl0EZqaI7G@tBNSSMyCY/m@sGbe5z0wkaLqtEik6pJikyvkh9GwESsF/b/PwA)
[Answer]
# [Lenguage](https://esolangs.org/wiki/Lenguage), score = 1 ()
```
```
Lenguage only cares about the length of the file, so we can use any character (in this case U+0001).
Yes, I am aware that I can use null bytes, but I wanted to give a fair chance to other people, so I made it 1.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), score 62 (`>`)
```
$=>()
```
[Check the score online!](https://tio.run/##LYwxCsMwDEX3nkJDBwla3cCBkrlTxxKIUNIkJbaCbYpv73rI8IcH7/2v/CRp3I58DzbNNbmxXl2HVEfOcfNIFwUHT8kreynIzO@2NDQ6sIDroLCuEvtWPzIStcBCsn3m3RbUG7zaT1j4E833p4hKVP8 "JavaScript (Node.js) – Try It Online")
Untyped lambda calculus again.
```
I = $=>$
K = $=>$$=>$
S = $=>$$=>$$$=>$($$$)($$($$$))
```
I think this is optimal, because *all* built-ins and keywords are banned now.
[Answer]
# [Brainfuck](https://esolangs.org/wiki/Brainfuck), Score = 93 (`]`).
```
> Move the pointer to the right.
< Move the pointer to the left.
+ Increment the memory cell at the pointer.
- Decrement the memory cell at the pointer.
. Output the character signified by the cell at the pointer.
, Input a character and store it in the cell at the pointer.
[ Jump past the matching ] if the cell at the pointer is 0.
] Jump back to the matching [ if the cell at the pointer is nonzero.
```
I/O is not required for Turing completeness, so `.` and `,` are optional: a canonical Turing machine leaves its calculated answer on the tape. However, I believe all other commands are required, so the highest codepoint the language uses, `]`, *is* required.
There are a number of trivially-similar languages. I'll cover these here as well, unless people feel they are genuinely worthy of separate answers. I have assumed for each language that their commands are case-sensitive unless otherwise stated.
You only need one of the two BF instructions `-` and `+` for Turing completeness. And if the tape/memory is limited and wraps around, then we only require one of `<` and `>`, too. I've updated the below lists to take these into account.
## Identical to BF for our purposes:
### [ASCII art-](https://esolangs.org/wiki/ASCII_art-), Score = 93 (`]`).
### [BFFB](https://esolangs.org/wiki/BFFB), Score = 93 (`]`) Requires code be a palindrome but uses the same characters as BF.
### [LolKek](https://esolangs.org/wiki/LolKek), Score = 93 (`]`).
### [Pi](https://esolangs.org/wiki/Pi), Score = 93 (`]`).
### [ReverseFuck](https://esolangs.org/wiki/ReverseFuck), Score = 93 (`]`).
### [RRF](https://esolangs.org/wiki/RRF), Score = 93 (`]`).
### [BF-](https://esolangs.org/wiki/Brainfuck_minus_-), Score = 93 (`]`).
.
## [TrivialBrainfuckSubstitution](https://esolangs.org/wiki/TrivialBrainfuckSubstitution)s:
### [???](https://esolangs.org/wiki/%3F%3F%3F), Score = 59 (`;`) 45 (`-`) Not quite a trivial substitution, but close enough. Omitted `?`, `;` and `.` as unnecessary for TC.
### [Alphuck!](https://esolangs.org/wiki/Alphuck), Score = 115 (`s`).
### [And then](https://esolangs.org/wiki/And_then), Score = 122 (`z` from required preamble).
### [Anguish](http://blogs.perl.org/users/zoffix_znet/2016/05/anguish-invisible-programming-language-and-invisible-data-theft.html), Score = 98 (`U+2062`) 97 (`U+2061`). Omitted `U+2062` as unnecessary for TC.
### [ASCII art](https://esolangs.org/wiki/ASCII_art), Score = 124 (`|`).
### [Blub](https://esolangs.org/wiki/Blub), Score = 117 (`u` from `Blub? Blub!`).
### [BrainFNORD](https://esolangs.org/wiki/BrainFNORD), Score = 115 (`s` in `eris`) 112 (`p` in `pineal`). Omitted `eris` and `fnord` as unnecessary for TC.
### [btjzxgquartfrqifjlv](https://esolangs.org/wiki/Btjzxgquartfrqifjlv) , Score = 90 (`Z` of `ZXG`).
### [Colonoscopy](https://esolangs.org/wiki/Colonoscopy), Score = 123 (`}` of `}}`).
### [Fluffle Puff](https://esolangs.org/wiki/Fluffle_Puff), Score = 116 (`t`) 115 (`s` of `*gasp*`).
### [FuckbeEs](https://esolangs.org/wiki/FuckbeEs), Score = 115 (`s`).
### [Fuckfuck](https://esolangs.org/wiki/Fuckfuck), Score = 116 (`t` of `b..t`).
### [GERMAN](https://esolangs.org/wiki/GERMAN), Score = 85 (`U` of `ADDITION` or `SUBTRAKTION`).
### [Headsecks](https://esolangs.org/wiki/Headsecks), Score = 7 (`U+07`).
### [Integral](https://esolangs.org/wiki/Integral), Score = 120 (`x` of the polynomial expressions).
### [LMBC](https://esolangs.org/wiki/LMBC), Score = 125 (`}` of `n\n\\n\>\<" }*/ continue;`).
### [Morsefuck](https://esolangs.org/wiki/Morsefuck), Score = 46 (`.`).
### [Omam](https://esolangs.org/wiki/Omam), Score = 46 (`y` of `this ship will carry`).
### [Oof](https://esolangs.org/wiki/Oof), Score = 111 (`o` of `oooooof`).
### [Ook!](https://esolangs.org/wiki/Ook!), Score = 107 (`k` of `Ook? Ook!`).
### [oOo CODE](https://esolangs.org/wiki/OOo_CODE), Score = 111 (`o` of `OOo`).
### [Pikalang](https://esolangs.org/wiki/Pikalang), Score = 117 (`u` from `chu`).
### [POGAACK](https://esolangs.org/wiki/POGAACK), Score = 112 (`p` from `poock?`).
### [PPAP++](https://github.com/izumariu/ppap-bf), Score = 86 (`V` from `I HAVE AN APPLE,` or `I HAVE PINEAPPLE,`).
### [Revolution 9](https://esolangs.org/wiki/Revolution_9), Score = 121 (`y` from `if you become naked`) 118 (`v` from `Revolution 1`).
### [RISBF](https://esolangs.org/wiki/RISBF), Score = 47 (`/` of `/+`)
### [Roadrunner](https://esolangs.org/wiki/Roadrunner), Score = 112 (`p` from `MEEp`).
### [Ternary](https://esolangs.org/wiki/Ternary), Score = 50 (`2` from `02`).
### [There Once was a Fish Named Fred](https://esolangs.org/wiki/There_Once_was_a_Fish_Named_Fred), Score = 119 (`w` from `was`) 114 (`r` from `Fred`).
### [tinyBF](https://esolangs.org/wiki/TinyBF), Score = 124 (`|`).
### [Unibrain](https://esolangs.org/wiki/Unibrain), Score = 48 (`0`, needs at least 1 alphanumeric).
### [VerboseFuck](https://esolangs.org/wiki/VerboseFuck), Score = 125 (`}` of `}; [... etc]`).
### [wepmlrio](https://esolangs.org/wiki/Wepmlrio), Score = 119 (`w`).
### [Wordfuck](https://esolangs.org/wiki/Wordfuck), Score = 32 ( space) or 33 (`!`) depends if chars < 32 are considered words.
### [ZZZ](https://esolangs.org/wiki/ZZZ), Score = 122 (`z` from `z-z`).
.
## [Turing tarpits](https://esolangs.org/wiki/Turing_tarpit):
### [Braincrash](https://esolangs.org/wiki/Braincrash), Score = 33 (`!`).
### [Placement](https://esolangs.org/wiki/Placement), Score = 63 (`?`).
.
## Binary:
### [Binaryfuck](https://esolangs.org/wiki/Binaryfuck), Score = 255 (`U+FF`) *or better???*
### [Brainfoctal](https://esolangs.org/wiki/Brainfoctal), Score = 255 (`U+FF`) *or better???*
### [CompressedFuck](https://esolangs.org/wiki/CompressedFuck), Score = 255 (`U+FF`) *or better???*
### [ShaFuck](https://esolangs.org/wiki/ShaFuck), Score = 255 (`U+FF`) *or better???*
### [Triplet](https://esolangs.org/wiki/Triplet), Score = 255 (`U+FF`) *or better???*
### [ZeroBF](https://esolangs.org/wiki/ZeroBF), Score = 255 (`U+FF`) *or better???*
Now, arguably, the score could be 49 (`1`), or 1 (`U+01`), or 255 (`U+FF`), or whatever. I pick 255.
These each replace the 8 BF command characters with their 3-bit binary equivalents, to give an octal number from 0 to 8. This converts the program to a binary stream of ones and zeroes, which can be represented as ASCII `1` and `0` characters, or as byte values, or as bit values, or as any base you like, hence the three possible scores.
The reason for my score of 255 for the bit-values version of binary BF programs is that `]` typically maps to `111`, so three of them in a row gives you a byte of all 1s, or 255.
It could be argued that you COULD write a Turing machine in these languages which never used three `]` commands in a row. So my score may be less generous than it need be. You can prove this, if you like! :D Until then, I'm scoring them 255.
Well, in the case of ShaFuck, it's more complicated, but still... I don't have proof that it doesn't require a 0xFF byte somewhere, so I'm giving it a score of 255 until proven otherwise.
### [Golunar](https://esolangs.org/wiki/Golunar), Score = 59 (`9`) *or better???*
So this is an interesting one. It takes a Unary program (well, any of the above "single character" solutions, and converts it to a decimal string.
In this way it is much like the other "binary" options, except it's explicitly stated to be a decimal number, one presumes in ascii.
That means that, if it could be proven that any program (or at least *a* Turing machine program) could be written in Unary that had a length that was describable without any 9s, the score would be able to drop, perhaps even as low as 49 (`1`).
## Replacement by sequences of a single character:
### [A](https://esolangs.org/wiki/A), Score = 65 (`A`).
### [Ecstatic](https://esolangs.org/wiki/Ecstatic), Score = 33 (`!`).
### [Ellipsis](https://esolangs.org/wiki/Ellipsis), Score = 46 (`.`) or 38 (`U+2026` ellipsis).
### [Lenguage](https://esolangs.org/wiki/Lenguage), Score = 0 (`U+00`).
### [MGIFOS](https://esolangs.org/wiki/MGIFOS), Score = 42 (`*`).
### [Unary](https://esolangs.org/wiki/Unary), Score = 48 (`0`) or 0 (`U+00`).
These are really just the binary options above, taken as a number that describes the length of a string made by repeating a single character.
## Other weird stuff:
### [BF-RLE](https://esolangs.org/wiki/BF-RLE), Score = 93 (`]`) to 247 (U+F7BFBFBF).
Run-length encoded BF. There are various methods. Base-10 prefix or suffix methods, or indeed any standard base up to 36 gets the same score as regular BF (because `]` is above the uppercase range). Base 37 then typically uses the lowercase range, for a score of 97, and each additional base up to base 62 gets one worse. Bases above 62 need additional non-alphanumeric characters, but these can be selected from those below the lowercase range until those run out at base 114 (assuming 8 characters remain reserved for the BF code itself), and they then get worse by one for each base increase to base-128. After that point, UTF-8 can be used to slow the rise of the limit so that it never hits 255 for any base within the limit for UTF-8's ability to represent (some 4 million).
## I dunno:
### [K-on Fuck](https://esolangs.org/wiki/K-on_Fuck)
### [( ͡° ͜ʖ ͡°)fuck](https://esolangs.org/wiki/(_%CD%A1%C2%B0_%CD%9C%CA%96_%CD%A1%C2%B0)fuck)
These use extended characters I can't be arsed to look up.
[Answer]
# [Python 3](https://docs.python.org/3/), score 109 (`m`)
```
lambd :()
```
[Check the score online!](https://tio.run/##K6gsycjPM/5frGCroK6u/j8nMTcpRcFKQ/M/kMeVDBTNTazQyE0s0MgvStFRKNbU5Cooyswr0UjWUUjOKNJI1tT8DwA "Python 3 – Try It Online")
We can implement untyped lambda calculus using just these chars:
```
I = lambda a:a
K = lambda a:lambda b:a
S = lambda a:lambda b:lambda d:a(d)(b(d))
```
With the known bound of `m`, we can't use any of `exec`, `eval`, `import`, `for`, `while`, `yield`. `def` is still available, but I doubt it will improve the score because I think making it Turing-complete necessitates the use of `return`.
[Answer]
# [Haskell](https://www.haskell.org/), score ~~95 (`_`)~~ 92 (`\`)
```
i = (\_A -> _A)
k = (\_A -> \_AA -> _A)
s = (\_A -> \_AA -> \_AAA -> (_A _AAA)(_AA _AAA))
```
```
i = (\(!) -> (!))
k = (\(!) -> \(!!) -> (!))
s = (\(!) -> \(!!) -> \(!!!) -> ((!) (!!!))((!!) (!!!)))
```
Untyped lambda calculus.
Annoying that Haskell can't have uppercase variable names, oh well.
-3 thanks to xnor
[Try it online!](https://tio.run/##y0gszk7Nyfn/P1PBVkEjRkNRU0HXTgFIaXJlI4sAaSSpYqxSIAZUEUgKzNPUAMtC2Jr//wMA "Haskell – Try It Online")
[Answer]
# [J](http://jsoftware.com/), score 94 (`^`)
```
"#%()*+.0123456789:<=]^
```
[Check the score online!](https://tio.run/##y/pfrGBrpWCgAMK6egrOQT5u/zU0NGJVjZUMNLVMtQxsDZT1DBSMla1iNbU1wDJGIBljmIwRRCZWy8AGwdeE8cD6NOOsNFQNNI0MDf5r/lfSUyjm0reqU6gDMWKTQdbb6ekbK5RaAflAIhkA "J – Try It Online")
The [winning J answer for least unique chars](https://codegolf.stackexchange.com/a/110731/78410) uses `u:` (convert charcodes to chars) to construct arbitrary string from integers. I decided to avoid `u` and find a more proper way for TC-ness.
Assuming `^:_` (repeat until converges) is hard to avoid, I decided to build a translation from [FRACTRAN](https://esolangs.org/wiki/Fractran), as it looked easy enough to translate to `(number_manipulation)^:_(starting_num)`.
A FRACTRAN program is defined as a sequence of fractions, and it runs like this: given a program `5/3 3/2` and some starting number `n`,
* If `n` is divisible by 3, multiply `n` by 5/3.
* Otherwise, if `n` is divisible by 2, multiply `n` by 3/2.
* (The "otherwise" chain continues for longer programs)
* If `n` did not change in this iteration, halt. Otherwise, move to the start of the program and continue with the updated value of `n`.
The if-then-else constructs can be translated to arithmetic:
```
If a then b else c = (a>0) * b + (a==0) * c
J: (b*(0<a))+c*0=a
```
The if-part says "`n` is divisible by a constant `m`". One would normally use the modulo function `|` for this, but it's way too high in ASCII, so I devised a way to simulate modulo using base conversion:
```
n modulo m = convert n into base m, interpret as base 0 and get an integer back
J: 0#.0 m#:n
```
The then- and else-parts are easy, because they can be simulated using multiply `*`, divide `%`, and self `]`.
So the translation of two-fraction FRACTRAN program `5/3 3/2` looks like this:
```
(((]%3"0)*5*0=0#.0 3#:])+((((]%2"0)*3*0=0#.0 2#:])+(]*0<0#.0 2#:]))*0<0#.0 3#:]))^:(%0)(starting_value)
```
I later changed the `_` (infinity literal) to `(%0)` (reciprocal of zero), getting rid of `_`. Since I can't avoid `^:` itself, the score of `^` is optimal in this approach.
[Answer]
# Julia, Score 63 (`?`)
we can actually get away with no letters, by abusing the fact that === is assignable for some reason. however, without a way to index or create arrays, this is not enough.
What gets us closer is tuple unpacking. this allows us to create a sort of "stack" with our one variable.
`(===) = (2,(===))`
`(===) = (3,(===))`
one problem is that we need another variable to unpack the argument into.
luckily \ is also assignable, so we can use that as a "register"
`(\,===) = (===)`
we can then perform some operation on these values and store the result
`(===) = (7+\==10,===)`
`(\,===) = (===)`
we can conditionaly execute code (and drop some parenthesies)
`====(\ ? 1 : 0,===)`
we can reuse names via shadowing, but this comes at the cost of recursion
`\ = (\) -> (\) + 3`
fortunately, there's another assignable value
`^ = (\) -> (\) < 2 ? (\) : ^((\)-1) + ^((\)-2)`
functions can go on the stack
`====(^,===)`
we also have NAND logic via && and ! (curried)
`^ = (^) -> (/) -> !((^)&&(/))`
the biggest problem is I/O, as we can't call any
Core or Base functions like print, but luckily we can use the -E flag or the REPL to print the result
[Answer]
# [PHP](https://php.net/) + `-r`, score 65 (`A`)
## Explanation
I saw the other PHP answer and felt like it should be possible to reduce that using [`create_function`](https://www.php.net/manual/en/function.create-function.php) and again abusing the fact that PHP allows functions to be called in a case-insensitive way.
Provided below is a compiler that should compile enough of a subset of PHP (maybe any PHP? I haven't tested exhaustively) using only `$()+.;=A`. This relies on the fact that `$A=A;$A++;print($A);` yields `B` and that `$A=A;$A++;$A++;$A.=A;$A++;$A++;$A++;$A++;$A++;$A++;$A++;print($A);` yields `CH`, any variable that isn't set that is incremented will produce `1` followed by the rest of the natural numbers, and that a function can be called using this string representation of its name (e.g. `$A=CHR;$B=$A(95);` stores `_` in `$B`).
This process means that first `CHR` is stored in `$A`, then the function name `CREATE_FUNCTION` is stored in `$AA` (utilising `$A(...)`) and the body of the function created by `CREATE_FUNCTION` is also built using `$A`.
The TIO link below allows you to provide PHP code to be compiled to this subset (and also executes it via `eval` to confirm it's working).
[Try it online!](https://tio.run/##vVVtb5swEP7uX3FFVrFF3po16xqaTvkH1b6uU0TBBEvURsZ0mqr99uwMbkKjbc3YtA9Y5u6e5547H6Yqqt3NxwpXmupMwApyWYrNVthNqpUVytYsRPdyOq1tJlXIY0KmU6iFhaaCtDCME6obWzUWwSFdr9ZxGO9NkxXU1myMqERiGbqjKA5Hc/4qAs2TU2BXw2AXV0eiDXrFJm9UaqVWvQI60rdK@FUNb6rpyRmEvDwF@AdCrv@RkFchvunXi5@R0zXDAD5Y8mKo4vls8HG9G5yT//eD@TA45eVf9YdQiV//DIMrI56kbmp8nS/ex@RrgfcJQ/eNQ5dCsfai4fyZUJsYvGgwUpusM3@mMoq@ICF@raluygySDB@oK5HKpIQ0qQXk2sAaCmHEGZE5O6S8BU/pyPu1uFsp@m0xfmpf8DH5TkSJuZ5PRMAY9jpa9FEvj2a/1yVP4DBYdB9WGaksc2AHAvRm4qHZHlMjK12P2jDWsne44JOom9KCzkE8JeXyXgUozG2ZJ@D70HvVef3rndFbkzyOIJi8nJlHTAJ4@GZFvezHH@h2O3c2zA@D64h8dP8URhWuUUQlxzlYzGKOjQVoZwPYeIzuW7jgaIIDyG/OzwH5sDMKzlZIhRk58xY3eQDdDGBsRyDSQgdUkgBb@gM "PHP – Try It Online")
[Answer]
# Keg, Score = 58
Characters:
`0+-*/():`
Simply the standard subset of TC chars
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), score 62 (`>`)
```
#$&()-./>
```
Using these characters we can implement the SKI combinators:
```
i = #&
k = $&/.$->#&
s = (#//$$//(#//$))&/.$$->#&/.$->#&
```
[Try it online!](https://tio.run/##VY5BCsMgEEXX5hqR4ARaT2D34qaQpbgYS6ES0kWThXp5O5pAWhgZ4b/3mQW313PBLTywlKD6oZsVH@SVX270X5XopeRcyrYBatKigyhiZDoyprSNjtGObITu/gnvzUYpg@sIMDFRYoiwyf0ziZqJm6GBU0yZ8mknbW5wFinDaWQyDmsF0pqnNTZPuzpYPcTTQeLD/ppTFWHEpAEM@ioaW2XnrKm69Y4p/1PgSa4l81FCF7cqcOUL "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), score: 110 (`n`)
```
<space>!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmn
```
Because of the trigraphs:
```
??= #
??( [
??/ \
??) ]
??' ^
??< {
??! |
??> }
??- ~
```
and the `main` function has to be defined so, no matter what, `n` has to be used. The ubiquitous semicolon (`;`) is there. And `return` is easily avoided through use of assignment (`=`) since gcc will return the last value assigned of the same type as the function return value. Type `int` is inferred by default for any variable or function definition.
[Answer]
# [Dreaderef](https://github.com/Reconcyl/dreaderef) (`-1` flag), score 42 (`*`)
Dreaderef is a ZISC; the program is a description of the initial tape contents. Dreaderef programs are typically written with an assembly-like syntax that is then run through a preprocessor to produce a list of integers, but quotes (`"`) can also be used to embed arbitrary data in the form of ASCII values.
The only restrictions on the contents of string literals are that:
* They can't contain newlines.
* For our purposes, they can't contain numbers greater than 42.
* They can't contain negative numbers.
The first two aren't a problem, but the third is. Dreaderef's only arithmetic operators are addition and multiplication, so we have no way to obtain negative numbers without including them when initializing. Additionally, the instruction pointer is stored in cell `-1`, and without accessing it we have no way to do control flow. Thus to achieve Turing-completeness we need to include the `*` byte (which is replaced with an integer from the command-line arguments at initialization time) and stipulate that the user always pass `-1` as an argument.
[Answer]
# [Unary](https://esolangs.org/wiki/Unary), score = 48 (`0`)
Unary only cares about number of `0` in the file.
Inspired by the [Lenguage answer](https://codegolf.stackexchange.com/a/210817/91267)
[Answer]
# Java, score: 117 (`u`)
```
0123456789ABCDEF\u
```
In Java, there are a few ways to create a full program:
```
// Regular class with main method (Java 1+):
class M{public static void main(String[]a){/*CODE GOES HERE*/}}
// Interface with main method, where we can remove public (Java 8+):
interface M{static void main(String[]a){/*CODE GOES HERE*/}}
// Exploiting a bug with enum (Java 5 or 6):
enum M{A;{/*CODE GOES HERE*/}}
// Creating a Java AWT GUI application with Applet:
class M extends java.applet.Applet{public void paint(java.awt.Graphics x){/*CODE GOES HERE*/}}
// Creating a JavaFX GUI application with Application:
class M extends javafx.application.Application{public void start(Stage stage){/*CODE GOES HERE*/}}
// Any of the above, but with \uHEXA escaped characters - i.e. here is the interface (excluding the comment within the main-method):
\u0069\u006E\u0074\u0065\u0072\u0066\u0061\u0063\u0065\u0020\u004D\u007B\u0073\u0074\u0061\u0074\u0069\u0063\u0020\u0076\u006F\u0069\u0064\u0020\u006D\u0061\u0069\u006E\u0028\u0053\u0074\u0072\u0069\u006E\u0067\u005B\u005D\u0061\u0029\u007B\u007D\u007D
```
Since all of them contain `}` (125), except for the last one with unicode escapes where `u` (117) is the maximum, that is our best score available in Java.
**Try it online:**
Here a few example programs using these eighteen bytes:
[Try it online: 2+2.](https://tio.run/##bVAxCsQwDHtRIXXiuFlL2lfcUripndvv54gcsOG6CBEpkvB5PMd0fq/WPncIuQC3jpLAGZzAM3AGRlMpdEwVzhUYXcLseLG/@ks0c3dqMjVX1@i20dKRXctY6DxZ4MEedjlUbOdIKH@b2dpps4XC5tF3Ce/tw4OdESqtjsMZ9VZ6t9raDw)
[Try it online: Check if the program argument is a prime number.](https://tio.run/##bZLJDsIwDES/CClLs11Dy1dwqcSpnOH3g@Kx5IFyGVnx9jztsb/3y/F4jnF/OZeb6Da1LBIniYPEWdSLRssGN3VZpbKLRprgKW7Wi66CmTfKLpbNK20ktlCnJtqihFSTi9QIT6I5oRnn@V7dK@9RuiK6rlaJd90Cf4r1gipXuwtsOr8aCdiiM0KwxU5u0wT0ahY@wP9uCnK8K@1mW9DLW9TDdvpqyfwPG5EkugW@uf/@f91Lvql77Zek4P9ZxxjefwA)
[Try it online: Print "Hello, World!".](https://tio.run/##bVBJCgMxDHtRIXEWT66d5RW9DPQ0PbffT4kcsKC9CBMpkuzr/Jy36/nq/fEOoTbgPlAz5oJZMFdgBCZnJQzMG5R3YCKHSHPzv/ZLzfMgNjtbN0qkbrIMLJQyG5KmKjToU8hHmvecDu2nc/F02b2hFtfYu4b/6VODngI2L@S8EsJZVt@6KCUKKc0zuqftkuzmdv@t9y8)
[Answer]
## Batch, score = 84 (`T`)
Batch is mostly case insensitive, so we don't need any lowercase letters. We need `T` in `SET` in order to be able to do any arithmetic. It also conveniently gives us `GOTO`, which makes arbitrary looping easier. What we don't get:
* `U` - `PAUSE` (can use `SET/P` to a similar effect); `PUSHD` (can use `CD` and `%CD%` to a similar effect)
* `X` - `EXIT` (can still `GOTO :EOF` but that doesn't set the error level)
* `Y` - `TYPE` (can still use `MORE` for small files)
* `^` - Quote single character (can still wrap most special characters in double quotes)
* `|` - bitwise OR (can be emulated using `A+B-(A&B)`); logical OR (can be emulated using `&&` and `GOTO`)
* `~` - bitwise NOT (can be emulated using `-1-X`); string slicing (not needed for arithmetic); parameter expansion (e.g. extracting the extension or size of a file), which needs lowercase letters anyway.
* Any executables whose names include the letters `U`..`Z`.
[Answer]
# MMIX, score 160 (`STB`)
Without some means of memory manipulation, it can't be Turing complete. The lowest-numbered instruction that allows touching memory is `STBU`, at `#A0`. (Well, that's not entirely true, there's also `CSWAP` at `#94`, but that's useless without being able to touch `rP`, which requires `PUT` at `#F6`.)
There's plenty of other stuff below, like branches from `#40` to `#5F`, plenty of arithmetic, floating-point arithmetic, shifts, conditional sets (and zero-or-set according to condition), and even (just barely) computed jumps!
The only things that aren't accessible are stores of anything longer than a byte (or of unsigned bytes), bitwise operations, MMIX's weird ops (`?DIF`, `MUX`, `SADD`, `M[X]OR`), immediate wyde operations, special register handling, unconditional 24-bit relative jumps, subroutine linkage, resumption from traps, user trips, saving/loading the register stack, and syncing memory. Even OS traps are available (though they are probably useless, since the traditional positioning for their arguments and results is `$255`).
[Answer]
# [Binary Lambda Calculus](https://tromp.github.io/cl/Binary_lambda_calculus.html), Score: 244.
It is known that [S and K are enough for lambda calculus (or combinatory logic) to be Turing-complete](https://esolangs.org/wiki/S_and_K_Turing-completeness_proof).
S and K are represented as following bits, respectively:
```
00000001 01111010 0111010
0000110
```
They have 23 and 7 bits respectively.
In worst case where you must use maximum octet value, an octet sequence 11110100 (which is 244) appears to your program.
[Answer]
# [Python 3](https://docs.python.org/3/), score 102 (`f`)
```
def():
[]=-1
```
[Bubbler observes](https://codegolf.stackexchange.com/a/210764/85334):
>
> With the known bound of `m`, [...] `def` is still available, but I doubt it will improve the score because I think making it Turing-complete necessitates the use of `return`.
>
>
>
With awkward and careful use of implicit globals, we can do without `return` by rolling our own stack! Using it is considerably more difficult, but it can still be used to implement SKI combinator calculus:
```
STACK = []
def RETURN(A):
STACK[:] = STACK + [A]
def POP():
STACK[-1:] = []
def I(A):
RETURN(A)
def K(A):
def INNER_K(B):
RETURN(A)
RETURN(INNER_K)
def S(A):
def INNER_S(B):
def INNER_INNER_S(C):
A(C)
R1 = STACK[-1]
POP()
B(C)
R2 = STACK[-1]
POP()
R1(R2)
RETURN(INNER_INNER_S)
RETURN(INNER_S)
```
For example, the infinite loop `S(I)(I)(S(I)(I))` can be expressed as
```
S(I)
*STACK, R = STACK
R(I)
*STACK, R = STACK
R(R)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwS1G9-AQR2dvBVuF6FiulNQ0hSDXkNAgPw1HTSsuBbBUtFUsUBaiSlsh2hGiLMA_QAOhRNcQrAhoBFjSE6IdbhRY0BsiCJb383MNivfWcAIJICmDMaHyEH3B6PqCofoQIjBxZ7C4giOQAaKDDGEOBzowFiQCdjWI4QRTYoRTSZChRpCRJsJ9KFahuzVYc2lpSZquxU2jYA1PTS4tsJE6CkEw07mCcAkHQXUugFJQGgA)
I suspect this is optimal.
[Answer]
# perl -MAcme::Bleach, score = 32
`Acme::Bleach` takes a program encoded using white space, and runs it after decoding.
[Answer]
# [Pxem](https://esolangs.org/wiki/Pxem), `W`: 87.
Characters are: `!-.01ACDOVW` (but `!` can be any others, and `O` can be anything that works as `pop one and discard it`).
Here's how to emulate cyclic tag system program `(101,001,10)` with input `1`, for example, in Pxem (`??.z ... .a` is pseudo-comment; can be erased):
```
??.z
# input is 1
# then loop begin
.a!1.W??.z
# exit if empty
.a.C.C.-.W.D.A??.z
# append 101 if top is NOT 0
.a.C0.-.W.V101.VWW.-.A??.z
# erase top (by printing it)
.a.O??.z
# exit if empty
.a.C.C.-.W.D.A??.z
# append 001 if top is NOT 0
.a.C0.-.W.V100.VWW.-.A??.z
# erase top (by printing it)
.a.O??.z
# exit if empty
.a.C.C.-.W.D.A??.z
# append 10 if top is NOT 0
.a.C0.-.W.V10.VWW.-.A??.z
# erase top (by printing it)
.a.O??.z
# end of loop
.a!.A
```
[Try it online!](https://tio.run/##vVhtV@LIEv7ur2gykXQMIWkERWJUBlyHXcWXcR1HQE8gQYMhZJOgaGD/@tzqThAIc2fv2Q9Xj6b7qae6qqu6Ot15Dp5@fPpUtvaM3m7P6hb6he2yuavu7PRKprpT6neNvmqqhWJJLZVIaSOwQiRbY208NIJnpKqFgmZNvJEfotPaQ/X0VK9pOHzzLPRohb2R289mWa83Gg4N1xQPFNN6Udyx46DCQZZks4nyRfX6i87xOOEh2ZsPwEQiH9GHVJnFDXnGzc3@2WzcPny9rusFVd2egxfnXxu3p98faudXV8e1a51oLcTx0efq1y8PN8dXXxvnzYr0NuOQjt5QJ5tlsxohbxTYk7gnfY5V7v6LhjUcO0ZooeCJ8UdeCM3XkW8GnmOH2azh2EaA5Eck8BGROP6Imwm6QJ9CNtv88/S0dlbXK8wGpvZMLXiy@6HG2ojyEsDqPY0Q/0mklgm1nAFDhZFjHmQh9C@Gg7gM6htOYHHT6bKMDc20J9PAMpEQKBPlTdEC@PeuCGzAd9ShSowFnLlqD4t4BEmoukh@CcdkGvpIrgWo3VLlvQ4SWm13qyNMH33LQ/l4cOW@uMMrUaWq8V2tqSltl/UvwNx9Pt92FUXrVrVZ3G3d03EIKfCKp2jhMlhW1zFCCK@MUuDu3jpGCGi7aWJ5HSNqiVfsNHF7HdsD3kMaA8u9FLazu44RAspBen7b6xgh4OJLmrizjhEVItZPu62uY0SFiFlpH/fWMUKKvOKnTRfWMUJA@zVN3F3HSAH8maSJ5XWMFMDHtzRxbx0jBfDnPZ0E9ScYuGOkJ11axwiB2IZpy8V1jKjgzjAd7911jKjgjpk2XV7HipB@KY2Bi3IK2wZeJo2B13waA2c2KTYTprhnJNuFKSZFyepViU5oUU40E@rvhGq3cb4ttnHbpf/zW22RV9rb7UKbKMAKlPwWVOtktb4rjsZnIqX1Onl7N8yOkomaWteBAWfaGxS7ghRNad0nUrrEeQWZysoYsouExHzr/ijXAbvgAW7FTXChcISoC08JJ8ZRfgtEzLPYOszHY27ySo6iXXABUhxBLxMF0Koqnta9BDSm5Y5ggA@i@UE0lfqcuEKbS5I4VHyNj2JzR4gODVscY6PqHAmrLLR8pgmStttC8ntny6Sjhf4SAlNi8enEk1WYyACax3IaT86ItWbgbeXyY8g88y28TO25STy@QGTqVYjLJEkui@wibnF8TpKR2F/sSuxJkvWfKQpo/upYSohi97FjdC1H17k24cSIzQS3vJFrP/SCl77lh0Mpw2/KHcpuEyxqymPMoeuxHZFce0ZFF7hNEpmx7FIw7mKOJoTLUe1DaHMV7ojLMbPiLDG4yv8Vuc4rXd8ynlkH8lbFnDMaecgdhWhohL0n233kgCrMpythUeliIjLfZNaRk16G9dS4w0Pnr3lnk3UoDYqRFaLQH/lJrMAjTRMjQfuoUmEmiOKP35rVs2NdODzMv298QrZrh7bhVFDXerRd9GqHT4gAHj5ZLqIub@SNDMl/Y/QNhD4ha2KHyO4ja@iFb4DkjXwNfuX8t3w9X2U8SjM8z4JzFbwYKBnOK8gOUPP8GqmJjspUboCQv/n2DToLXcs3Aovp4O4b8nzbDSFeyA7FWPf833qj/rM36v/PG6L@kzP/1hcgwvijPssgQjSH@aqwUTtvXh83r3VB2MBMtw9HNrYe@ETETV97SO6JcCj7Efg9Xfh8fNJoRlCAUmBZphj4cFjGrDnrj91eaI9cdIHrYvS19Zz7A4sdva5BsyNJC/kxFiPfCse@izIScBaS3xcSwA/IQvLHQkKHWwiuVwTUpEyWxLf4SoyudGAxN2RZS8hXC84Y18SIzR/VFugJvsrdfYwNlwHHdq0D9ZBXK/KSY19iAzzR2CZwz3YYCfYCjhNXIBRD6@b/pObHrr5ku4rP5h6dTTkoWIg/vXDAaloy7cHUX59sx8IZCKk4Wo4kdCIAp9MxvgXZQuDiRu4mV885Is0iU4xudOBoju5Y7mP4hG9EjW4bDbi1NPZ1RxPHGNd1mEsQ@vgm15CkHBHFvzk2L@6wLhXLlWJJnC2M2GD9Ap@sGH7AZ7la7i73XYzOdC7/UEFN2PwMZFo9ewi3CJis9Wj58PTGIafVdFDX7sAH6gvducDd4u5@LZut7ZfKIttONcBqf3P3xdZ2qcPDm@BOLxblWqIc77hAweVYjRQhIDVd3y6IUUyBCx4UzNia0YhTam2/WAbOQWlXpFBsfGE2Hln8ruPvIqrJxbJGs6dd4Lut70tz7c2jf4GvV4IQzAW3y8l6gZwMcjdi1NBVZnGgs3UM4R/QZZsbyHJHv6GJor1Gh4GQhw7rDzpLofcXpiGimNWnuEXXwJLB10XRrHszwZc5ZisD5UgjnIHeJVsiN/rlPuUmujcLpbdfKh38XOn9ww2qxdyQV1wJ55N5gtrVV0RDED3DYkFw/73AVL4k7GIDAhov8d/pCr/AxiGoSwaNROU2iYi22DG2dCIXtrCxr4pbNGfwXArqX@nxBknF3CaTxYMtR4QVA2a4/Ca8/vOwGrkKurN8OA3bL3YAw3B0odCkGIeDA@dwsOlUnM1BhbUV1oYczeIdFjzT1Q4sB7iyp/ZmbtoTOWHhXB8iscL62LvXr9C/uEHr8dEjPu/BcRqOIvRLhuy7z2TaG0PLFJCA5H5hfkaB4@kFzor0Kr/kjsUWc3z2iWDhsgX9LEmaJA32Md2E6aKFkMfhHyRdaIjaz6dBp2tajhVaCPIMpZBsT1AgktTYB3WJxCXB3jQNNqJEoE7iTV@K@52ZoNE3Ff3MAwfiHmKfgsa0QkZD@mEDQH8NXMTQLCK5WVwhTKfYC0A@Qp5t5qzQHlo5r@eNcy/Bu2YaoSUu56D4688YKDRsBy4pxaUA04tSVKaHVXYkFqbG6zOMhQxdLpDibrG8vVMsIyEyJJ1XZ8fNevLWMOBox238z/lPRk2iQx8cJABe@BwTCbwKJ2344VAQpwdzmyMux6uiMJ0Y/iPEoDFBSeYmG@jHfwA "ksh – Try It Online")
[Answer]
# [AAAAAAAAAAAAAA!!!!](https://esolangs.org/wiki/AAAAAAAAAAAAAA!!!!), Score: 65 (`A`).
Characters are `! ,A`.
Proven as in [this](https://esolangs.org/wiki/AAAAAAAAAAAAAA!!!!_Turing-completeness_proof).
] |
[Question]
[
This is the cops' thread. The robbers' thread [goes here](https://codegolf.stackexchange.com/questions/67757/printing-ascending-ascii-robbers).
Write a program or function consisting only of **printable ASCII characters** (that excludes tab and newline) that outputs at least 5 printable ASCII characters in ascending order (from space to tilde / 32 to 126). Characters can be outputted several times, as long as they are adjacent to each other. A single trailing newline is accepted. You must provide the full output, and for every 6 characters in your code you must provide one character in your code, at the position it appears. If your code has 5 or less characters, then you have to reveal only the length. You shall not reveal more than 1 character per 6 in your code.
So if your code `alphaprinter` outputs the alphabet from a-z, then you need to reveal 2 characters of your code (use underscore for the others), for instance:
```
al__________ // or
__p__p______ // or
__________er
```
Rules / specifications:
* You cannot append trailing white spaces that doesn't have a function.
* You can not use comments (but the robbers can use comments when cracking the code)
* Built-in cryptographic primitives (includes any rng, encryption, decryption, and hash) aren't allowed.
* In languages where the **default** output are like in MATLAB: `ans =`, then that's accepted, as long as it's **clearly stated** and shown that `ans =` is outputted. It should also be clearly stated whether this is part of the "ascending output" or not.
* The output must be deterministic
* Using a non-free language [is not accepted](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default/7212#7212)
* The output doesn't have to be consecutive characters. Both `abcde` and `abcdg` are valid outputs.
* The characters do not need to be distinct as long as the output contains at least 5 characters. `aaaaa` and `aaacc` are valid.
* Answers that assumes a REPL environment are not considered to be valid programs or functions and are therefore not allowed.
* STDERR is not considered valid output, but data may written to STDERR.
If the revealed characters are underscores, then you must identify it as shown below.
In this case, the second and sixth character are revealed underscores, while the others are unknown.
```
_____________
| |
```
**Note:** The robbers only need to find a code that produces the same output. The language, the length of the robbers solution, and the position of the revealed characters must also match.
Your score is the number of characters in your code. The winner will be the submission with the lowest score that hasn't been cracked in 7 days.
Only submissions that are posted in 2015 (UTC) are eligible for the win. Submissions that are posted later than this are welcome, but can not win.
In order to claim the win you need to reveal the full code (after 7 days).
Your post should be formatted like this (nn is the number of characters):
---
# Language, nn characters
Output:
```
abcdefghijklmnopqrstuvwxyz
```
Code (12 characters):
```
al__________
```
---
If the code is cracked, insert [Cracked](link to cracker) in the header.
If the submission is safe, insert "Safe" in the header and reveal the full code in your answer. Only answers that have revealed the full code will be eligible for the win.
[Answer]
## Perl, 46 characters (safe)
Output:
```
((()))*++,---../00011123445556667779::;;<<==??@@AAACEFGHHHIKKMMNOOOPPQQQRRSSSVWXXYY[[[\]]]^^^```aaeeffggghjjjnpppqqrttuwxxyzz{{{
```
Code:
```
print _______________________________________;
```
I somehow managed to delete the original in the space of a week, but I think this is right:
>
> `print chr()x(($i=($i*41+7)%97)&3)for(40..123);`
>
>
>
[Answer]
# Brainfuck, 48 characters, [cracked](https://codegolf.stackexchange.com/a/67823/34388) by Mitch Schwartz
I made this one for the robbers. It is definitely not going to be the winning submission :)
```
____[_____[_______]__]___[___________]___[_____]
```
This outputs:
```
ABCDEFGHIJKLMNOPQRSTUVWXYZ
```
**Solution:**
>
> `++++[>++++[>++++<-]<-]+++[>++++++++<-]>++[>+.<-]`
>
>
>
I tested it [here](https://copy.sh/brainfuck/).
**Hint:** Don't try to find programs generated by online generators haha. This was handwritten and can only be solved by logical thinking :)
[Answer]
## CJam, 13 characters
```
_____________
||
```
prints
```
7LLMYahnsuv
```
You can [try CJam online.](http://cjam.tryitonline.net/)
### Solution
```
{`__Jf^er$}_~
```
I thought basing a cop on a generalised quine was pretty clever and novel. The moment I posted this, I realised that `__` and `er` are completely useless, which is why I posted the 8-byte CJam cop for a more competitive score. Pietu cracked that one rather quickly, so I was afraid he'd figure out this one as well. I suppose the unnecessarily convoluted character transliteration saved it.
Anyway, the code takes its own characters (except the `_~`), XORs each one with 19 for obfuscation and then sorts them.
This cop led me to the "discovery" of [xorting](https://codegolf.stackexchange.com/q/68109/8478), although I'm not actually using it here (and it would probably be near impossible to make use of it with a short generalised quine).
[Answer]
## [Noisy 3SP](http://esolangs.org/wiki/Three_Star_Programmer#Variants), 89 characters (safe)
```
0 _____________________________ _ _ _ _ _ _ _ _ _ __2_2__________________________________
```
Original program:
```
0 0 0 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 0 3 2 2 2 2 0 3 0 1
```
This program prints
```
!"#$$
```
(note the leading space), and *nothing else!*
Explanation (\*n refers to the nth cell in memory):
```
0 0 0 Increment *0 to 3 (via the 0s in *0, *1, and *2)
2 (32 times) Increment *3 to 32 (via the 0 in *2 and the 3 in *0)
(Note that *3 mod 256 is the character that prints)
0 Increment *32 (via the 3 in *0 and the 32 in *3)
3 Increment *1 (via the 32 in *3 and the 1 in *32)
(Note that printing is on when *1 mod 2 is 1,
which means " " prints right here)
2 (4 times) Increment *3 to 36 (printing '!"#$')
0 Increment *36 (via *3) (printing "$" again)
3 Increment *1 to 2 (via *36) (printing turns off)
0 Increment *36 to 2 (via *3)
1 Increment *0 to 4 (via *2)
```
The last two commands turn out to be sufficient to prevent 1 from ever being incremented again on subsequent passes through the program, which means nothing is ever again printed, though it will go on setting all memory addresses from \*36 onward to the value 36 forever.
[Answer]
## [Hexagony](https://github.com/mbuettner/hexagony), 8 characters, safe
```
_______.
```
prints
```
123456
```
You can [try Hexagony online](http://hexagony.tryitonline.net/)
### Solution
```
`&)!."@.
```
The ``` is just misdirection to make the code look like it requires side-length 3. Unless the interpreter is executed with `-d` the backtick is simply stripped from the source code before determining the layout. Afterwards, the code fits into side-length 2:
```
& )
! . "
@ .
```
This moves the memory pointer (MP) around one hexagon of the memory grid, while copying the value to the next edge, incrementing it and printing it.
This is what the memory grid looks like, with the MP starting the marked position:
[](https://i.stack.imgur.com/P3TJa.png)
Initially all edges are zero. The first `&` is a no-op, but `)` increments the edge and `!` prints the `1`. Then `"` moves back to the left (the edge labelled *2*). There, `&` copies a value. Since the edge is currently zero, the left neighbour (in the direction of the MP) will be copied which is the `1` we just printed. `)` increments it, `!` prints the `2`. This continues as long as we're visiting new edges and we print all digits up to `6`. When we hit the edge we started on, `&` will copy the *right* neighbour instead (because the edge value is positive), so the edge becomes `0` again, and control flow jumps to the last row, where `@` terminates the program.
[Try it online.](http://hexagony.tryitonline.net/#code=YCYpIS4iQC4&input=)
[Answer]
# JavaScript (ES6), 60 characters, [Cracked by user81655](https://codegolf.stackexchange.com/a/67815/41859)
Not promising to win, but hopefully fun to crack:
```
e_e_______a__a____e___e________e__o___________o______o______
```
This is a function that returns:
```
:ERacddeeeeeeffiinnnoorrrrst
^^^^ -> 4 whitespaces
```
---
**Edit**
[user81655 cracked it](https://codegolf.stackexchange.com/a/67815/41859) character by character:
>
> `e=e=>{try{a}catch(e){return[...e.toString()].sort().join``}}`
>
>
>
[Answer]
# ~~Matlab~~ Octave, 27 characters, safe
### Challenge
Regarding the new language restrictions: It also works in Octave.
```
____________3_3___4_3______
```
Output (in Octave): (`ans =` is not part of the output, the first character of the output is `"`)
```
ans = """""""""""""""""""""""""""""""""""""""""""########$$$$$$%%%%&&&&'''(()))**++,,-../001223456789:;<=>?@BCDFGHJKMNPRTUWY[]_acehjloq
```
Output (in Matlab): (`ans = \n\n` is not part of the output, the output is just the last line)
```
ans =
"""""""""""""""""""""""""""""""""""""""""""########$$$$$$%%%%&&&&'''(()))**++,,-../001223456789:;<=>?@BCDFGHJKMNPRTUWY[]_acehjloq
```
### Solution
>
> `[fix((0:.07/3:3).^4+34),'']`
>
>
>
>
> We are basically looking at this function, converted to ASCII values.
> [](https://i.stack.imgur.com/MyQtb.png)
>
>
>
[Answer]
# R, 60 bytes, [cracked](https://codegolf.stackexchange.com/a/67911/6741) by plannapus
Output:
```
0123456789ABCDEFGHTUVWXYZdefghijklmnopqrstuvw
```
Code:
```
___(_(_:_____________]_____________6]_______s_4_____,___=___
```
I think this will not be so hard. We will see.
[Answer]
# [Jolf](https://github.com/ConorOBrien-Foxx/Jolf/), 27 characters, [Cracked by Adnan](https://codegolf.stackexchange.com/a/67881/31957)
```
________W___________--_____
|
```
prints
```
abcdefghijklmnopqrst
```
[Interpreter](http://conorobrien-foxx.github.io/Jolf/).
Original code:
```
on*2toHEWn)oH+H `pl$--$n}_H
on set n
*2t to twenty
oHE set H to the empty string
Wn) while(n){
oH+H append to H
`pl$--$n get the nth character of the alphabet, decrement n before
} }
_H print H reversed
```
Congrats to Adnan! You scare me.
---
Here, you can test your submission, to see how many characters must be removed.
```
setInterval(function(){r=document.querySelector("textarea").value;document.getElementById("output").innerHTML=r.length/6-r.split("").filter(function(x){return x=="_"}).length|0},20)
```
```
*{font-family:Consolas,monospace}textarea{width:100%;resize:none;height:auto;min-height:1.2em;}b{color:red;}
```
```
<textarea>Example Program</textarea><div>You must reveal <b id="output">n</b> characters.</div>
```
[Answer]
# Fortran, 45 characters, safe
Complete Output:
```
!"$)0<Ka|
```
Cat [attempted to cracked it here](https://codegolf.stackexchange.com/a/67822/46231)
Code (45 characters):
```
pr_gr_m____________________/___3____________
```
Program code:
>
> `program t;print*,(char(i**3/8+33),i=1,9);end`
>
>
>
[Answer]
# PHP, 46 characters, safe
Source:
```
for(_______________________=________________);
```
Outputs a 84 characters long string:
```
!!"#$%&'()*+,-./0123456789::;<=>?@AABCDEEFGHIIJKLLMNNOPPQRRSTTUUVWWXXYYZZ[[\\]]^^__`
```
**Hint**
>
> What'd you say? My cousine is involved?
>
>
>
**Revealed code**
>
> This method is relatively simply as it prints up to *64* characters starting at `chr(32)`. The obscuring part is, that the iterator `i` is not incremented linearly. It's incremented by it's own *cosine* value which will result in repeated and missing characters.
>
>
> `for(;$i<64;)echo chr(32+$i+=cos(deg2rad($i)));`
>
> `for(_______________________=________________);`
>
>
>
[Answer]
## Python 3.4, 127 characters - SAFE
This is my first coppers-post. I think/hope it's not too hard or too obvious.
The obfuscated code:
```
_______inspect__________________getsource_____________________________________________print__________c*s_______________________
```
creates this output (there are 5 spaces at the beginning; total length is 7740 characters):
```
""""""""""""(((((((((((((((((((((((((((((((((((((((((((((((((((((((()))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))**********************...................................................................................................................;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;==============================[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiijjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnoooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooopppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppprrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrsssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
```
## Edit 25 sept 2021, the answer in [Python 3](https://docs.python.org/3/)
```
import inspect;s=sorted(inspect.getsource(inspect.getmodule(inspect.currentframe())));print("".join([c*s.index(c) for c in s]))
```
[Try it online!](https://tio.run/##Tc0xDsIwDIXhq0SdEoYsjFVPghiQ41IjYke2I8HpQwYkeNv/La@9/RA@j0G1iXogtobgq202E0v8Qr6jm3QF/JcqpT9/Al0V2Xe9VYxpbm1K7HFZ8kOI4wVOlokLviKksIsGmIfBrimN8QE "Python 3 – Try It Online")
The code gets the code itself as a string and then repeaths every i-th character i times. Finally the resulting string is sorted.
Funny thing is thus that all the characters of the solution are in the output! ;-)
[Answer]
## CJam, 8 bytes, [Cracked by Pietu1998](https://codegolf.stackexchange.com/a/67917/8478)
```
__:_____
```
prints
```
%*;a|~
```
You can [try CJam online](http://cjam.tryitonline.net).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 13 characters, [cracked](https://codegolf.stackexchange.com/a/68072/34388) by quintopia
I'm an idiot. I forgot to implement power function (-\_-。). Here is the obfuscated code:
```
__D____<_____
```
My original code was:
```
99DF2}r<F*}bR
```
Explanation:
```
99DF2}r<F*}bR
99 # Pushes 99
D # Duplicates the top item
F } # Creates a for loop: For N in range(0, 99)
2 # Pushes 2 (this will be done 99 times)
r # Reverses the stack
< # Decrement on the last item
F } # Creates a for loop: For N in range(0, 98)
* # Multiplies the last two item of the stack, which now looks like
# [2, 2, 2, 2, 2, 2, 2, 2, ...]. Basically we're calculating 2^99
b # Converts the last item to binary
R # Reverses the last item of the stack
```
This will output:
```
0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001
```
Yes, that is 99 zeroes followed by a 1.
---
**Note**, I have a power function implemented right now. So this could be done in six bytes:
```
Y99mbR
```
[Answer]
# Pyth, 17 characters, [cracked by Pietu1998](https://codegolf.stackexchange.com/questions/67757/printing-ascending-ascii-robbers/68124#68124)
Output:
```
""''''''''''''''''''''0000000000111111111122222222223333333333XXXXXXXXXX[[[[[[]]]]]]
```
Code:
```
___________#____1
```
My solution:
```
Sjkm^dT%"'%#X"291
```
Pietu1998's solution:
```
S`u]G6*T`t"#X0231
```
[Answer]
# Malbolge, 254 characters, [cracked by Adnan](https://codegolf.stackexchange.com/questions/67757/printing-ascending-ascii-robbers/68219#68219)
Code:
```
_____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ __
```
Output:
```
`AB\cd`
```
I kinda cheated by putting a space for every 6th character. Oh well...
---
Adnan's cracked code:
```
('&%: ^"!65 4Xzyx w4-Qs rpo'K mlk"' ~Dfdc ba}v< ::8[Z XnVlq }0/mO ,*MbK JH^6# 4`C|0 ?U=Sw uPsaq L4on2 Mjjh, ged)c '<$$p ]!};Y WiVxS eRQ>= ).K]l Ij"Fh gfedc b,=;z L\q%H X3E2C /ng-k N*KJI 8%6#D ~2^Ai >g<<d tUr`6 oJ"!1 /|{CU f)d>b <A_^! \};Yj yUxTS dtsr` ML
```
The original code:
```
bCBA@ ?>=<; :9876 54321 0/.-, +*)(' &%$#" !~}|{ zyxwv utsrq ponml kjihg fedcb a`_^] \[ZYX WVUTS RQPON MLKJI HGFED CBA@? >=<;: 9y165 43210 /.-,+ *)('& }C#"! ~wv<z \xwvu tsrqp onmlk jihgf e^$ba `_^W\ UyYXW VUTSR QPONM FKJIH GFEDC BA@9] =<;:9 27654 3210) M:
```
I cheated again by using a text-to-Malbolge generator for this code.
[Answer]
# Mathematica 10.1, 98 characters, safe
Output is [here](http://pastebin.com/8PNpkHcD). The entire output has 838,316 characters and a trailing newline.
Code:
```
Print[""<>Chara__________________________________________________________________________________]
```
Yes, this must be run in 10.1. *(hint)* The original program:
```
Print[""<>Characters@ToCamelCase@ExampleData@{"Text","DonQuixoteIEnglish"}~SortBy~ToCharacterCode]
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 8 characters, safe
*Stable version of the compiler working in Octave hopefully coming soon. Meanwhile, this [GitHub commit works](https://github.com/lmendo/MATL/tree/77a5eba228ccedec8ac0d58d0f1842aba03858cc), and in particular runs the original code that produces the indicated output*
*This submission counts as posted on December 28, 2015, 15:30 UTC*
Output:
```
$**0016688??@HHQ
```
Code (8 characters):
```
_:______
```
### Solution
```
6:9tX*Sc
```
What it does:
```
6:9 % numeric vector [6 7 8 9]
t % duplicate
X* % Kronecker tensor product
S % sort in ascending order
c % convert to char. Implicit display
```
[Answer]
## [Labyrinth](https://github.com/mbuettner/labyrinth), 5 bytes, [Cracked](https://codegolf.stackexchange.com/a/67765/8478) by Adnan
```
_____
```
prints
```
000000
```
---
My original code was:
```
<!!@
```
Note the trailing space.
I suppose I should have gone for more characters and revealed one of the `!`, because Adnan's solution only grows linearly when adding more `!`, while mine grows quadratically.
[Answer]
# PHP, 28 characters
```
<?=________________________;
```
Outputs the string
```
abcdefghijklmnopqrstuvwxyz
```
[Answer]
## ES6, 17 characters, [cracked](https://codegolf.stackexchange.com/a/67801/41859) by Cᴏɴᴏʀ O'Bʀɪᴇɴ
```
__=____=_________
```
This is a function that will return the string
```
11233
```
[Answer]
# JavaScript, 83 chars, [Cracked by Martin Büttner](https://codegolf.stackexchange.com/questions/67757/printing-ascending-ascii-robbers/67807#67807)
Output
```
Hi~~~
```
Code
```
_=____r____=u____=__s__=_________=__________________u_______A__________e______"_~_"
```
Output is in the JS console of a browser like Chrome/Firefox.
Original code (which *might* be invalid):
```
q=w=e=r=t=y=u=i=o=p=s=d=f=g=h=j=k=l=z=x=c=v=b=n=m="Huh"[0]+"Alarms in here"[7]+"~~~"
```
[Answer]
# Pyth, 6 characters, [cracked](https://codegolf.stackexchange.com/a/67868/34388) by Pietu1998
Code:
```
S_____
```
Output:
```
.0113345678888999
```
You can try Pyth [here](https://pyth.herokuapp.com/)
[Answer]
# Octave, 18 bytes:
Output in Octave:
```
ans = $'())**+,,--../0011233
```
Note that `ans =_` (replace `_` with space) is how Octave prints output by default and is not part of the output string. The output string alone starts with a single leading space like this:
```
$'())**+,,--../0011233
```
Code:
```
[________:_______]
```
Disclaimer: If this miraculously should end up being the shortest uncracked submission, I'll award the win to the runner-up. This won't be a winning submission, I just wanted to have some fun too. *And* I figured a relatively short MATLAB/Octave submission could be fun for others. The other one was too hard for me at least.
[Answer]
# JavaScript ES6, 134 characters
Huh boy, that was fun. Good luck!
```
_=_=_____l____.______.________(___}__;___=______ru____"_____+_[________]______!____]__[_________e________.__U_________)__________\_____
```
Outputs:
```
((((((()))))))+...000000000000000000002233=>AAAAAAAAAAABBBBBCCCCCCCCCCCCCCCCCCDDDDDDDEEEEEEEEEEEEEEEEEEEFFFFFFFGHIIIIIIIIIIIIIIIIJJJJLLMMNNNNNNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOPRRRRRRRSSSSTTTTTTTTTTTTTTTTTTTTTTTUUUUUUUUUVVVVVVXXY[[[[[[[[]]]]]]]]````ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeffffffffffffffffffffffffffffffffffffffffffffffffffffffffiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiinnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu{{{{{{}}}}}}
```
[Answer]
# CJam, 12 characters, [Cracked](https://codegolf.stackexchange.com/a/67769) by jimmy23013
**Output**
```
#$%&'()*+,-./:;<=>?@[\]^_`
```
**Code**
```
_:____#_____
```
[Answer]
## [Seriously](http://seriouslylang.herokuapp.com), 7 bytes, [Cracked by Martin Büttner](https://codegolf.stackexchange.com/a/67912/47050)
```
______S
```
Output:
```
deeknnoow
```
Shouldn't be too difficult, even if the result is not exactly what you'd expect.
[Answer]
# Python 3, 58 characters, cracked by [Mitch Schwartz](https://codegolf.stackexchange.com/a/68000/45032)
Code:
```
______________print(_______(_______________________)_____)
```
>
> import string;print(''.join(sorted(string.printable))[5:])
>
>
>
Output:
```
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
```
[Answer]
# Befunge, 11 characters, [cracked](https://codegolf.stackexchange.com/a/68122/31203) (in funge-98) by MegaTom
Output:
```
1223788
```
Obfuscated code:
```
________.__
```
All one line, since the rules prohibit newlines. Tested using <http://www.quirkster.com/iano/js/befunge.html> .
Edit: This is legally cracked since I didn't specify a version, but note that there's a Befunge-93 solution still out there.
[Answer]
## Perl 5, 30 bytes, [cracked](/a/68132) by [Adnan](/u/34388)
Code:
```
print_________________________
```
Output:
```
9:;@AFGHLMNRSTYZ_`a
```
Cracked:
[Adnan](/u/34388) found a [trivial](//en.wikipedia.org/wiki/Triviality_%28mathematics%29) [crack](/a/68132): obviously, I didn't think this puzzle through well enough. I've composed [another](/a/68142) instead.
] |
[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.
**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.
# Pi is Wrong
A common method of computing pi is by throwing "darts" into a 1x1 box and seeing which land in the unit circle compared to the total thrown:
```
loop
x = rand()
y = rand()
if(sqrt(x*x + y*y) <= 1) n++
t++
pi = 4.0*(n/t)
```
Write a program that *looks* like it should correctly compute pi (using this or other common methods of computing pi) but computes [tau](http://tauday.com/) (tau = 2\*pi = 6.283185307179586...) instead. Your code must produce at least the first 6 decimal places: 6.283185
Winner is crowned June 6th (one week from today).
[Answer]
# JavaScript
```
alert(Math.atan2(0, -0) - Math.atan2(-0, -0) + Math.atan2(0, 0))
```
Help, [I'm trapped in a universe factory](http://xkcd.com/10/), and I'm not sure what I'm doing. `Math.atan2` is supposed to return pi with good values, right? `Math.atan2(0, -0)` returns pi, so if I subtract it, and add it, I should still have pi.
[Answer]
# BASIC
(More specifically, [Chipmunk Basic](http://www.nicholson.com/rhn/basic/))
This uses an [infinite series](http://helloacm.com/two-simple-equations-to-compute-pi/) discovered by Nilakantha Somayaji in the 15th century:
```
' Calculate pi using the Nilakantha series:
' 4 4 4 4
' pi = 3 + ----- - ----- + ----- - ------ + ...
' 2x3x4 4x5x6 6x7x8 8x9x10
i = pi = 0
numerator = -4
while i<10000
i = i + 2
numerator = -numerator
pi = pi + numerator / (i * (i+1) * (i+2))
wend
pi = pi + 3
print using "#.##########";pi
```
### Output
```
6.2831853072
```
If you can't figure out what's going on, here are a couple of hints:
>
> In Chipmunk Basic, the variable ***pi*** is preset to the value of π when the program starts running.
>
>
>
and
>
> In BASIC, the equals sign is used both for assigning variables and for testing equality. So ***a = b = c*** is interpreted as ***a = (b==c)***.
>
>
>
[Answer]
## C - The length of half a unit circle
One way to compute **π** is simply to measure the distance the point `(1, 0)` travels when rotating around the **origin** to `(-1, 0)` since it will be half the circumference of a **unit circle** (which is **2π**).

However, no `sin(x)` or `cos(x)` is needed since this can be done by *stepping* all the way around the **origin** and **adding the distance the point travels for each step**. The smaller size for each step the more accurate **π** you will get.
**Note:** The stepping will end when y is below zero (which is just as it passes `(-1, 0)`).
```
#include <stdio.h> // for printf
#define length(y, x) ((x * x) + (y * y))
int main()
{
double x, y;
double pi, tau, step;
// start at (2, 0) which actually calculates tau
x = 2;
y = 0;
// the step needs to be very low for high accuracy
step = 0.00000001;
tau = 0;
while (y >= 0)
{ // the derivate of (x, y) is itself rotated 90 degrees
double dx = -y;
double dy = x;
tau += length(dx, dy) * step; // add the distance for each step to tau
// add the distance to the point (make a tiny rotation)
x += dx * step;
y += dy * step;
}
pi = tau / 2; // divide tau with 2 to get pi
/* ignore this line *\ pi *= 2; /* secret multiply ^-^ */
// print the value of pi
printf("Value of pi is %f", pi); getchar();
return 0;
}
```
It gives the following output:
```
Value of pi is 6.283185
```
[Answer]
# C
(This ended up being longer than intended, but I'll post it anyways...)
In the 17th century, Wallis published an infinite series for Pi:

(See
[New Wallis- and Catalan-Type Infinite Products for π, e, and √(2 + √2)](http://arxiv.org/ftp/arxiv/papers/1005/1005.2712.pdf) for more information)
Now, in order to calculate Pi, we must first multiply by two to factor out the denominator:

My solution then calculates the infinite series for Pi/2 and two and then multiplies the two values together. Note that infinite products are incredibly slow to converge when calculating final values.
output:
```
pi: 6.283182
```
```
#include "stdio.h"
#include "stdint.h"
#define ITERATIONS 10000000
#define one 1
#define IEEE_MANTISSA_MASK 0xFFFFFFFFFFFFFULL
#define IEEE_EXPONENT_POSITION 52
#define IEEE_EXPONENT_BIAS 1023
// want to get an exact as possible result, so convert
// to integers and do custom 64-bit multiplication.
double multiply(double aa, double bb)
{
// the input values will be between 1.0 and 2.0
// so drop these to less than 1.0 so as not to deal
// with the double exponents.
aa /= 2;
bb /= 2;
// extract fractional part of double, ignoring exponent and sign
uint64_t a = *(uint64_t*)&aa & IEEE_MANTISSA_MASK;
uint64_t b = *(uint64_t*)&bb & IEEE_MANTISSA_MASK;
uint64_t result = 0x0ULL;
// multiplying two 64-bit numbers is a little tricky, this is done in two parts,
// taking the upper 32 bits of each number and multiplying them, then
// then doing the same for the lower 32 bits.
uint64_t a_lsb = (a & 0xFFFFFFFFUL);
uint64_t b_lsb = (b & 0xFFFFFFFFUL);
uint64_t a_msb = ((a >> 32) & 0xFFFFFFFFUL);
uint64_t b_msb = ((b >> 32) & 0xFFFFFFFFUL);
uint64_t lsb_result = 0;
uint64_t msb_result = 0;
// very helpful link explaining how to multiply two integers
// http://stackoverflow.com/questions/4456442/interview-multiplication-of-2-integers-using-bitwise-operators
while(b_lsb != 0)
{
if (b_lsb & 01)
{
lsb_result = lsb_result + a_lsb;
}
a_lsb <<= 1;
b_lsb >>= 1;
}
while(b_msb != 0)
{
if (b_msb & 01)
{
msb_result = msb_result + a_msb;
}
a_msb <<= 1;
b_msb >>= 1;
}
// find the bit position of the most significant bit in the higher 32-bit product (msb_answer)
uint64_t x2 = msb_result;
int bit_pos = 0;
while (x2 >>= 1)
{
bit_pos++;
}
// stuff bits from the upper 32-bit product into the result, starting at bit 51 (MSB of mantissa)
int result_position = IEEE_EXPONENT_POSITION - 1;
for(;result_position > 0 && bit_pos > 0; result_position--, bit_pos--)
{
result |= ((msb_result >> bit_pos) & 0x01) << result_position;
}
// find the bit position of the most significant bit in the lower 32-bit product (lsb_answer)
x2 = lsb_result;
bit_pos = 0;
while (x2 >>= 1)
{
bit_pos++;
}
// stuff bits from the lowre 32-bit product into the result, starting at whatever position
// left off at from above.
for(;result_position > 0 && bit_pos > 0; result_position--, bit_pos--)
{
result |= ((lsb_result >> bit_pos) & 0x01) << result_position;
}
// create hex representation of the answer
uint64_t r = (uint64_t)(/* exponent */ (uint64_t)IEEE_EXPONENT_BIAS << IEEE_EXPONENT_POSITION) |
(uint64_t)( /* fraction */ (uint64_t)result & IEEE_MANTISSA_MASK);
// stuff hex into double
double d = *(double*)&r;
// since the two input values were divided by two,
// need to multiply by four to fix the result.
d *= 4;
return d;
}
int main()
{
double pi_over_two = one;
double two = one;
double num = one + one;
double dem = one;
int i=0;
i=ITERATIONS;
while(i--)
{
// pi = 2 2 4 4 6 6 8 8 ...
// 2 1 3 3 5 5 7 7 9
pi_over_two *= num / dem;
dem += one + one;
pi_over_two *= num / dem;
num += one + one;
}
num = one + one;
dem = one;
i=ITERATIONS;
while(i--)
{
// 2 = 2 4 4 6 10 12 12 14
// 1 3 5 7 9 11 13 15
two *= num / dem;
dem += one + one;
num += one + one;
two *= num / dem;
dem += one + one;
two *= num / dem;
dem += one + one;
num += one + one;
two *= num / dem;
dem += one + one;
num += one + one + one + one;
}
printf("pi: %f\n", multiply(pi_over_two, two));
return 0;
}
```
>
> The exponent in the double conversion can't actually be ignored. If that's the only change (leave the divide by 2's, the multiply by 4, the integer multiplication) everything surprisingly works.
>
>
>
[Answer]
# Java - Nilakantha Series
The Nilakantha Series is given as:
```
pi = 3 + 4/(2*3*4) - 4/(4*5*6) + 4/(6*7*8) - 4/(8*9*10) ...
```
So for each term, the denominator is constructed by multiplying consecutive integers, with the start rising by 2 each term. Notice that you add/subtract alternating terms.
```
public class NilakanthaPi {
public static void main(String[] args) {
double pi = 0;
// five hundred terms
for(int t=1;t<500;t++){
// each i is 2*term
int i=t*2;
double part = 4.0 / ((i*i*t)+(3*i*t)+(2*t));
// flip sign for alternating terms
if(t%2==0)
pi -= part;
else
pi += part;
// add 3 for first term
if(t<=2)
pi += 3;
}
System.out.println(pi);
}
}
```
After five hundred terms, we get a reasonable estimation of pi:
```
6.283185311179568
```
[Answer]
# C++: Madhava of Sangamagrama
This infinite series is now known as *Madhava-Leibniz*:

Start with the square root of 48 and multiply it by the result of the sum of (-3)-k/(2k + 1). Very straightforward and simple to implement:
```
long double findPi(int iterations)
{
long double value = 0.0;
for (int i = 0; i < iterations; i++) {
value += powl(-3.0, -i) / (2 * i + 1);
}
return sqrtl(48.0) * value;
}
int main(int argc, char* argv[])
{
std::cout << "my pi: " << std::setprecision(16) << findPi(1000) << std::endl;
return 0;
}
```
Output:
```
my pi: 6.283185307179588
```
[Answer]
**Python - An Alternative to Nilakantha series**
This is another infinite series to calculate pi that is fairly easy to understand.

For this formula, take 6 and start alternating between adding and subtracting fractions with numerators of 2 and denominators that are the product of two consecutive integers and their sum. Each subsequent fraction begins its set of integers rising by 1. Carry this out even a few times and the results get fairly close to pi.
```
pi = 6
sign = 1
for t in range(1,500):
i = t+1
part = 2.0 / (i*t*(i+t))
pi = pi + sign * part
sign = - sign # flip sign for alternating terms
print(pi)
```
which gives 6.283185.
[Answer]
```
#include "Math.h"
#include <iostream>
int main(){
std::cout<<PI;
return 0;
}
```
Math.h:
```
#include <Math.h>
#undef PI
#define PI 6.28
```
Output: 6.28
#include "Math.h" is not the same as #include , but just by looking at the main file, almost no one would think to check. Obvious perhaps, but a similar issue appeared in a project I was working on, and went undetected for a long time.
] |
[Question]
[
# Introduction
Every string has an "alphabet", composed of the characters that make it up. For example, the alphabet of \$abcaabbcc\$ is \${a, b,c}\$. There are two operations you can do with alphabets: getting the alphabet of a string, and seeing if another string has a given alphabet.
# Challenge
Given two strings, you must write a function that finds the alphabet of the first string, and returns a truthy or falsy value based on whether that alphabet makes up the second string, ie. if the alphabet of the first string is the same as that of the second. However, the function should also return a truthy value if the alphabet of the first string is a superset of, or contains, the alphabet of the second.
* The two strings will be of variable length. They might be empty. If they are, their alphabets are considered and empty list/set. Any valid unicode string could be an input.
* The function must return a truthy or falsy value. Any type of output is OK, as long as, when converted to a boolean in your language (or the equivalent), it is `true`.
# Examples
* `String 1: "abcdef", String 2: "defbca"`
`Output: truthy`
* `String 1: "abc", String 2: "abc123"`
`Output: falsy`
* `String 1: "", String 2: ""`
`Output: truthy`
* `String 1: "def", String 2: "abcdef"`
`Output falsy`
* `String 1: "abcdef", String 2: "abc"`
`Output truthy`
* `String 1: "üòÄüòÅüòÜ", String 2: "üòÅüòÜüòÄ"`
* `Output: truthy`
# Rules
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins!
## The Catalogue
The Stack Snippet at the bottom of this post generates the catalogue 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:
```
## [><>](https://esolangs.org/wiki/Fish), 121 bytes
```
```
/* Configuration */
var QUESTION_ID = 194869; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 8478; // This should be the user ID of the challenge author.
/* App */
var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;
function answersUrl(index) {
return "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, user: a.user, size: a.size, link: a.link};
});
var langs = [];
for (var lang in languages)
if (languages.hasOwnProperty(lang))
langs.push(languages[lang]);
langs.sort(function (a, b) {
if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1;
return 0;
});
for (var i = 0; i < langs.length; ++i)
{
var language = jQuery("#language-template").html();
var lang = langs[i];
language = language.replace("{{LANGUAGE}}", lang.lang)
.replace("{{NAME}}", lang.user)
.replace("{{SIZE}}", lang.size)
.replace("{{LINK}}", lang.link);
language = jQuery(language);
jQuery("#languages").append(language);
}
}
```
```
body {
text-align: left !important;
display: block !important;
}
#answer-list {
padding: 10px;
width: 290px;
float: left;
}
#language-list {
padding: 10px;
width: 500px;
float: left;
}
table thead {
font-weight: bold;
}
table td {
padding: 5px;
}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/all.css?v=ffb5d0584c5f">
<div id="language-list">
<h2>Shortest Solution by Language</h2>
<table class="language-list">
<thead>
<tr><td>Language</td><td>User</td><td>Score</td></tr>
</thead>
<tbody id="languages">
</tbody>
</table>
</div>
<div id="answer-list">
<h2>Leaderboard</h2>
<table class="answer-list">
<thead>
<tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
</thead>
<tbody id="answers">
</tbody>
</table>
</div>
<table style="display: none">
<tbody id="answer-template">
<tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
</tbody>
</table>
<table style="display: none">
<tbody id="language-template">
<tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
</tbody>
</table>
```
[Answer]
# [Python 3](https://docs.python.org/3/), 21 bytes
```
lambda a,b:{*a}>={*b}
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSFRJ8mqWiux1s62Wiup9n95RmZOqoKhVUFRZl6JRpqGVmpZYo5GZl5BaYmGJhD8V0pMSk5JTVPSgTG4QAwI19DIGMgFsiGCEGUgEgA "Python 3 – Try It Online")
## Explanation
* `*` to [unpacks the sequence/collection into positional arguments](https://stackoverflow.com/a/2921893/6251742 "What does the star operator mean")
* `set >= other` to [test whether every element in other is in the set](https://docs.python.org/3.8/library/stdtypes.html#frozenset.issuperset "issuperset(other)/set >= other").
[Answer]
# [Haskell](https://www.haskell.org/), 13 bytes
```
all.flip elem
```
[Try it online!](https://tio.run/##NYpBDkAwEEX3TjEREhIkWPckWIzq0BjSqPMbGmx@3nv5C/rVMAupXpC5IrYODJtNsjRXFG1od1DgDrufkEAX46gnQ3H6QwGBXq@bNvgjX36fYQe5NDHOXkrt3A0 "Haskell – Try It Online")
Haskell doesn't have built-in set or subset functions, so we need to do it ourselves. This is a pointfree version of
**17 bytes**
```
a%b=all(`elem`a)b
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P1E1yTYxJ0cjITUnNTchUTPpf25iZp6CrUJBUWZeiYKKQrRSYlJySmqakiqMoaMAYkH4hkbGID6QAxWGqASRsf//JaflJKYX/9dNLigAAA "Haskell – Try It Online")
which it itself shortened from
**22 bytes**
```
a%b=and[elem c a|c<-b]
```
[Try it online!](https://tio.run/##NYo7DoAgEAWvsiHaSaG2chJCsaz4iUCIWnp2VwnavMxM3oLH5rxnxtoqjKN23gUgwIsGaQ0HXCMoSPsaT6hAC7Q0uknUPzSQqXjb9dlf@XJ55jV80@RxPlhSSg8 "Haskell – Try It Online")
[Answer]
# Regex (ECMAScript 2018 / Python[`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/) / .NET), 20 bytes
Takes the two strings in joined format, delimited by a single newline. That is why there are two newlines in the regex itself (saving 2 bytes compared to if `\n` were used):
```
((.)(?<=\2.*
.*))*$
```
[Try it online!](https://tio.run/##rVPLbtswELzrKxZEEYmOLMTpza6aQ9EC7aEFmt4sA6Gktc2AJtUlHRsIAqSXfkNv/cX@gUtKdvyAe@uB1JDc2ZkVl/fiQdiKZOP62tS4sU6Qwzq/GlH@FWfv101y60jqWUZidbeJkiTjyc2bvLjOelHW47z3anOXWSUrTAZpf8D5iPD7UhImMaGoldQY86zy2OFH7ZCmwoc@St0s3bAhU6G1mXW11E88MzqJW0aq8rePEcDWDlxcwEGsWbpsRdJ5jULHfLQLywcjz1Hjq0mexyz@J@vT7ZfPWSPI@gTj@FJdxhPv8d5I3SXMFsJV84T4DftGSxwCsCH7IJT1kPGgcTat4qMnvhlD4ACuxaJRaGESMVFWNU5ZCsx/ykqwiIUFOzzxyK///P717McPP36G3R0O@yyKxjBdkpsjdRoOrYNK2BeVymfDTqcqy1IIdrJd10eibcq2sFO/W0uD69eesLcY0KGNjnvsow09kmnB7Hx5z/sSn7sSF4bwtL4UpobAzaWFtnN2F@AbE/ogiVDhg9AOVnPhoI3y0QjsnW9qBqVZB2dp0ZorWOq9hLldBFzsTtjOwGll/8dBEEm3179V3uvWuDDaOvIvBZQxzdwo7NKcFw3pNa7Cg/FcJRe@CenlBtqfXuhtx/0F "JavaScript (Node.js) – Try It Online") - ECMAScript 2018
[Try it online!](https://tio.run/##rVK9btswEN71FIdDAImOIthJs6gVOhToE3STPFDS2WJAkwJJN@7mLn2Gbn3FvoFLUnYcGx47ULw7Hr8fHccfbtDq6SA2ozYODK1pl79YrRIDFRhEPCRZVrDs86eqeSxmSTFjbHZ38Af1onxYLD@CqObJShuQIBTokVQ2Z2UCIFYgShiNUC5jIa8WU1X6FsmAqx5kPSUeqKrSRqUlyErW84B8o3keujA9oZLqK/xmtlQCYGiO8gtL3HRDZnIIiMWLFioLlgqpeW@ztE7v5X26TBljQNIS4FfutxIwyDxDS3aoIcAD7fhmlGRhmSBvu55WmAP6re04JhgSfH/iI5///fN779dPv36F6ikOdUySGlZb4wYyE4cj66Dj9o2l82g08XRt23KOV@W@vyCNkNHJtd6jpMXjk79wlhii9zKmu5c6YusFTQzWt@3tzxb3k8WNNnTtL4fwXNwgrH8x49b5X647slaoNTyAMIYkfefKwevAHcQu3@3H9EX3hNDqXVCWN1Fcg7nXEr4xCXFzOsGTgGtn/0dBIMmP4z8yn3l72mhlneGOQGo9DlrSBHObNMArepVCkb8rxUY4PxLP4qf24blRcQABPub4Dw "Python 3 – Try It Online") - Python `import regex`
[Try it online!](https://tio.run/##rVPNattAEL77KaZDSHaNLGyXXuIqCYQWCgmFJqUHK4W1NLIXVj/srhMX15Be@gy99RX7Bu5IspPYuLcKVpr/7xvNbOJ6SWlpXaicXKUSgptvzlO@nDtdTOGWFj78RNO5UfbdorLknC4LN0qMcg7ypfPK6wTuS53CtdIFCLm8VxZcdIHrjhChFOdvo3gYdjthV8ru0RpHtd9GBT0AF6aFcOHNfOK8ZTwxCFx4RcXUz3pDGTT@j5WvIcPLMq@0oVQ2BaoXBS4QUYjz0zgOv4@/It7JrkSEbgDdQw6UoxYNzCgrrdCFhyzqj4SJLhmoNMQdq/RKFySkfBUVc8OB0UAudSays77cRn2x2lMbNuoA6AyE2bA/ewPHx2DG/bsoOsGTVtk6e4PWKjmpeXYKClz2V8vBCgMbfnDXyicz0c4k/Mc0wuY3hJ8LcomqSFRsqAzPUpgAjwZxcTREKeU53to5nQLgKb5XxrGIgWmoE2sHWDTuFT/rMdS5QAuVV4Yc3HVQTZKUMgwA@TNJFHawVvClhyXW//z@9cjnB5@ftXUr13bsdMaQza2fkW0xPDkPiXJPKAlXoxYnmUwmSuGeOU13QJuSTYP7fDeUBsPXnPBMsZZe0mhzd3k0oTswjTA93N7jc4uPbYs5X7L9/gLg9QM/0w50Uc09VLZM6pnyavZAW0uG7hVv58NMeWiiOJoAL8uUECblomYWxA25GAPmUr8bpZbjrQe3BPY7@z8MapBgM/4N8jNuSjnvlbfKE5iyrGa8Ym2Zw6B1eb7ahq8V5xqd8zLapwk0Pz0uNhv3Fw "C# (.NET Core) – Try It Online") - .NET
It just so happens that the order of String 1 and String 2 dictated by this question is the one that makes it a bit nontrivial in regex, impossible to do without variable-length lookbehind or non-atomic lookahead. If it were the other way around, it would be possible in vanilla ECMAScript.
```
\n # 1. Find the newline, so we can match against String 2
( # 2. Start loop at the beginning of String 2
(.) # 3. At every iteration, capture another character from String 2 into \2
(?<= # 4. positive lookbehind - look backwards
\2.* # 6. Assert that the captured character \2 can be found in String 1
\n.* # 5. Find the newline, so we can match against String 1
)
)* # 7. Continue the loop as long as possible
$ # 8. Assert that when the loop has finished, we've reached String 2's end
```
# Regex (Java), 29 or 27 bytes
Java has a limited sort of variable-length lookbehind. It's unlimited in length, but there are strict limits as to what is allowed in a lookbehind (most notably, all backreferences must be inside a lookahead inside the lookbehind), and stricter limits on what will actually work in a lookbehind. So in principle it has the same power as full-fledged variable-length lookbehind in its ability to solve computation problems, but will do so less efficiently.
In this case, two limits come into play: `\2` need to be backreferenced in a lookahead, and apparently, if an expression like `.*x.*` is in a lookbehind (where `x` is any character), it will silently fail to work properly. Here we work around this problem by collapsing the `.*\n.*` into `[\s\S]*`:
```
((.)(?<=^(?=.*\2)[\s\S]*))*$
```
**29 bytes** - [Try it online!](https://tio.run/##bVLdbtMwFL7PU5xZ02qHkXXjbiFUILErhhDlrukkJ3Fab46b2c5WVCqVG56BO16RNyjHabq1o5EiH5@f78f2LX/gr2@Lu7Ws6plxcIv7SM6iMIbdTOOkOpgzYiLmvlI3mZI55IpbC9dcalh0Keu4w@VhJguosECHzkg9AW4mdjRm4KZm9mjh4zwXtZMzHAwArqQSUCZaPLYhJVE@K0SEdcLiD01ZCiOKr4IXwkDWtu0n6Xay25aMxR2vPXXx49SDUptk6IAXn6QWlLGjRDdKMVlSG4n7hitLyVkYhoSxxX7rFsAdBFgggntCQIAzRMiw7y62r5Jeqnt@dfFyk1t@4c4Jo8EkXYRmq9oTWBbjYQxzrjUalbpuHCTgvXU5OvxunagiqRnejnYgk34MrTqgbX805fazmDuUBwtAZfIo6bNubIb1Gk/FKU09QHLu@ZBxc1QKyTYgGhE664gBVEVK6ImbUvauDycnoKJ8ys17R/ssSXqkx9pb3IG6Ryj/XGrFc3EljXWUpITSwWWKX/RjdJOSMQtZSiA8hfBwiZwCOT5P9fEFYXGHf81dPsXDqZDARNVmR@9R50uPJa2iUuqCMhgA@WYacQlA4BLIFV4UbhB0@d8UVZhdLgP/ENYBpRGjg7fJDR0kUZhesFFq0@E4ZCw8XvubXo/AI4OY86pWwsI4IDzLC1F68bhkOSdB64TsVjDC/d8/v1f4/8T/l89uY58nQTCCsjHOu205nLAOcm6fWHJEExuePMsyzsmLdFHskbaQrfmXejtJ5xdvcOBZoo92ZWxm93W0rXs0bTA5bG/1bHG1Iv8A "Java (JDK) – Try It Online")
This problem could also be solved by using comma as a delimiter instead of newline:
```
,((.)(?<=^(?=[^,]*\2).*))*$
```
**27 bytes** - [Try it online!](https://tio.run/##bVLdbtMwFL7vU5xZ02qH4rXjbiFUILErhhDjru0kJ3Fab46b2c5WVCqVG56BO16RNyjHaba1o5EiH5@f78f2jbgXr2/y240qq7n1cIN7ruY8imE3U3ulD@asnMpFqFR1qlUGmRbOwaVQBpZtynnhcbmfqxxKLNArb5WZgrBTN5ow8DM7f3DwcZHJyqs5DnYALpSWUCRGPjQhJTyb55JjnbD4Q10U0sr8qxS5tJA2bftJ@jjZbgvG4pbX9Xz8MAug1CUpOhD5J2UkZewoMbXWTBXUcXlXC@0oOY2iiDC23G99BPAHAZaI4J8QEOAUEVLsu43dq6Q7Nt2w@ni1za2@CO@lNWCTNkKzZRUIHIvxMK4yYQwaVaaqPSQQvLU5evXdeVlyZRjejvGgkn4MjTqgTT@fCfdZLjzKgyWgMnWU9Fk7Nsd6hafitaEBIBkEPmTcHpVGsi2IQYTWOmIA1VxLM/Uzyt714eQENM9mwr73tM@SpEu6rLnFHag7hArPpdIikxfKOk/JmFA6PB/jx3@MrsdkwiI2JhD1IDpcIj0gx4Pe8RlhcQt/KXw2w7MpEd/ycrujdyjzpcWClrxQJqcMhkC@2VqeAxA4B3KB94QbBF39N0U1ZlerTngHmx6lnNHh2@SaDpPRdW8Sjc8YjxiLjjfhmjcjCLggF6KstHQw6RCRZrksgnJc0kyQTmOD7FYwwv3fP7/X@P/E/1fIPsYhTzqdERS19cFrw@Gl85AJ98SSIZrc8mRpmgpBXqTzfI@0gWysv9TbShqcvcGBZ4kh2pWxnd3X0bTu0TTB9LC99bPF9Zr8Aw "Java (JDK) – Try It Online")
Or by using the `s` (dotall) flag with newline as the delimiter:
```
((.)(?<=^(?=[^
]*\2).*))*$
```
**27 bytes** - [Try it online!](https://tio.run/##bVLBbtswDL37K1ihaCQv89LuVs8LOmw9tduw9hangGzLiVpZdi25zZAFyC77ht32i/uDjHKcNuliwBD5SL5HUrrlD/z1bXa3kkVV1hZu0Q9kGfghbCONlWovVouJmLlI1SRKppAqbgxccqlh3kHGcovHQykzKDBAr2wt9QR4PTGjMQM7rctHA59mqaisLLHQAziXSkAeafHYmpQEaZmJAOOEhR@aPBe1yL4JnokakjZtF6Sbys7NGQs7XdO34ePUkVITJTgBzy6kFpSxg0g3SjGZUxOI@4YrQ8kb3/cJY/Pd1A2B3UswRwb7xIAEb5Ahwby70LyKerHuudOGizW2@MqtFbWGOuosHLaonIDpb5CPX67PLi5YiLu5SrnWOLfUVWMhAjdqh9Gr78aKIpCa4WVpCzIahNA2C7TND6bcfBYzi93CHLBReRANWFdWYrzCJVmlqSOIjp0eKq43p1BsTaKRodsEcgBVgRJ6YqeUvR/A0RGoIJ3y@szSAYuiHumx9lK3qO6Ryr2eSvFUnMvaWEpiQunwNMYv@DG6icmY@Swm4PfB3x8ifSCHx7E@PCEs7PgvuU2nuJwCBeqgWHv0Hvt8OWNOiyCXOqMMhkCu60acAhA4BXKO94YOki7@q6IK0cXCc@9i5VEaMDp8F93QYTS68cZ@fMICnzH/cOWufTUCxwtixotKCQNjj/AkzUTuWscjSTnx2jnIdgQt9P/@@b3E/yf@vxy6sR1OPG8EeVNbN2urYYWxkHLzpJIim1jrpEmScE5ewFm2I9pStqO/7Ldr6fjkLRY8t@is7TbWtbt9tKk7Mq0x2T/e8nnE5ZL8Aw "Java (JDK) – Try It Online")
# Regex (PCRE1), 48 bytes + `s` flag
It is possible to [emulate variable-length lookbehind](http://www.drregex.com/2019/02/variable-length-lookbehinds-actually.html) using recursive constant-width lookbehind:
```
((.)((?<=(?=
((?<=(?=$.|\2|(?4)).))|(?3)).)))*$
```
[Try it online!](https://tio.run/##rVVtb@JGEP7uXzHZ3oV1cFAIVVVhfNE1l1M/5JIKcVIrQMgsY3BibGttjiSXSOmX@w33rX@xv6B0dtcGw5FWqop4mZ2dneeZZzyLSNPjqRCr78JYRIsJQicVEhuzN5aY@RJGaX8IHnTZT8vl7bi1@O3@/tfe7IfljK8szhs252cdj595Vmm8ajwOTh/52fe23bBtMlrasI9erezdHMyBo9QbpfWma23ws3wSJopA1SXDeLrtCxPyoj//Nu6NFcY5pGTmI5QykVwkcZaDLuhojlnmT9H@TDjttqAA6HSg8CpT@zGeRC5IzBcyhqb7pFPO/TDmNny2gF5pn9AijHlqHzeH3okLC4ppnY5ySNRKHZiSoYN1TsOONtJF7oKSGY4kulBlR3TSXJrTErNFlBtb1REEGeYOJIucYKf5zOwkn1Dkiey3hgaKsno6@Ugk8zSMkKcO/HLevRi9u@69vbyER7P62Hv/owOHBtAYJcKJbVKFAfADiXapQ6A1DThVQ9EOMJVIU5PgExN9HF5P2vA6G8TU3UpOg1MkDugAV@QflFJanCnmURgjN10JY8foZLsU0yw1L0k92EB7SjFeG8S1Imu5qw/2T4aeV2O16tHdTogkvecFzFbQml/onTg3XtO5JZ7ubqoST6Xp3@yHq8bd0qaKbaD0M@ShUyXTbsdpklG5Y3qob@mB25dFI4X1@tBTZbtw6zXdvYHLmWq8Dq/XNTUglYhFSfbAqzm1dWOrs8I@hFmm1KEAZv/39Ozf0g@Yyg839fq3IE@AUYb/oOVG88GgBoeHWppGFj4gDWjHA6K1H/4qyWcK3g9ylKBOv1TkWmyaJwNH9h6q1ssrM8HlPOIdCi7RgauPl5eOYSxG1H5uO1X@NID6XUy2A60dhkqAInWHhvWFx7KIOPDMvF90u9fd0dX1h7e9859tKEaZXShZ2qA6oSUv/e99Wmm/tacxZVRPLihoK2qjQLCUYY5mwDaFmmVZaVMPQbKeQHM6kIjE317fwMVVaD2t@qAwAe/8eRphBkOL@WMxwYCuG0Y/Y@Ezi6kFq@6QRes///j6TJ/f6fNFeUtb@Zll9SFYyHxGz4XGyFFdyzSqJYqgbGhwxHg89n22455MtkB1Si3kLt@CUvO0RQc2FJVVpWHObvPQoVsw2pjuL@95U@KzKXGe0D/ETn2OvvFoMDLTHupvItDM6TGEUmKEn3y6D5czuud1FEUjsPNkggzGyZ1i5gw0uQFziIv61gtlD8odVhLYrez/YaBAnKL9BXJh/iWCyJ9mq@NIjeLf "C++ (gcc) – Try It Online") (C++)
[Try it on regex101](https://regex101.com/r/8MgdLJ/12)
The recursive lookbehind goes through two stages in this regex: first `(?3)` to find the newline, and then `(?4)` to find the captured character. The regex could be 1 byte shorter if some character that is guaranteed not to be present in the input were used as the dummy impossible match instead of `$.`.
`/s` single line mode (dotall) is used so that newline can be the delimiter, with the `.` in the lookbehinds being allowed to match it. With any other choice of delimiter (even a control character), this flag would not be needed. Therefore, I have not included it in the byte count. FWIW though, keeping newline as the delimiter and *not* using `/s` mode would require [upping the length to 52 bytes](https://regex101.com/r/8MgdLJ/5) (with a regex that runs much more slowly, due to putting the newline after the lookbehind), costing the same in bytes as adding `(?s)` would, thus not worthwhile.
# Regex (PCRE2 / Perl 5), 45 bytes + `s` flag
Same approach as PCRE1, but the dummy impossible match `$.` is no longer needed to avoid a "recursive call could loop indefinitely" error:
```
((.)((?<=(?=
((?<=(?=\2|(?4)).))|(?3)).)))*$
```
[Try it online!](https://tio.run/##rVZtb9pIEP7uXzFxT2ENTi6QuyqKcaM0uEqkhETE6NoCsoxZgxNjW2tTmrSVcl/6G/rt/uL9gsvNrtdgXnInnQ7xMjszO/PMq/GSZG/sec@vRtQPIgo3Zx2r4Zxdtyyn276wnd8uWvY5HCmvgsgLZyMKzcRjtLE/eaN4E5eBk/QGYEJHfTuf3w8PZx8eHt7bk9fzCXlWCNnXCDlpmuTEVAqi3/hKTn7RtH1NQ@JQEFr1p2dt3YCqQzUxnaRWN0re02wUxNx7mcWCaLzKC2LkUne6qfdGCaIMEiQzhzIWM@LFUZqBiKY6pWnqjqn2Bf0cH3uoAM0mSC4nBZ9Go9AARrMZi6BufNswyc9ePKIafFEAX8K4tNJr/Pp6YAh24AMR6XTGVF51pBbh13UgeT26Z@ennaOqJoU6pMEjjX1SwIWfC05JH/MqvPDXSjiqUALh7xjUFyMUtxdRKnmYUzeISBFX0sOkhjQiibZXH5gHBsxQ57DhZBCbBwgzxt7IId12397aF3bXthzrvW21W1YLvm7Kuu1by3asqxv7gwHc3xitKosQ8hqiIJllBuS545mCKqPFeepm3sQZuZmL9VzQuTVG01mY6XnsRuH@4qMlOL6fUhTGswxjGmeTFYVq/Il6Gd6SacHICv/TJAgpkbm/vbE7WqLLqx@tzrVjW52ri/apbbUKduvaPr28XCSga7/TYVeAkr8SyoG27JQdhoWW5Sg3m/iWeqXYzY10OHh2M@r4LJ46iZtllEWEYTe1u5eX0oAfMxDt@8irKXKOvRniaiB5DwWRnqdfM1CnXnRCAfJRA5TxfieVflSRVgupuNg7GJhmRa2Ur64X2IuTByLdrCgt8AXYX3dmXb9HnMa6qcIfN9O72@6urHePQq67T5mbUhLoZTDHx1ESpxjuENN3j9O@zYrwFNRqA5OHbcC9WTe2Ks4nvFeEeq0moAFmCVEUYHfMil7ZWmj1KkhTnh1UULX/bl79N/N9lduHu1pt08k3oGFK/yGXy5z3@xXY3RWp2efrCddG0wSEtd19O84m3L3rY2MCv/1SkItkY5Pn7pDeAlV5@ZQvgtUhEbNQnmKB3HOwDYiml@PAwRTv5WytDFE5HdJRE0f5hSaVGjvFprQ6neuO076@OrXPzvFSOUm5LtZGMH2iWnKJa4YsTCF45@JJCJQt5Su0bDZDpRWtZZ78OQsymo/hMg35schDXYxKvJjT/PbG5vEZpWR51sq7Oxficls8UvMo8Ynz3AOOEOhnd5qENIWBorpDD/@r4L8DFX@GnqsqKj@oZQlSeP7zjx9P@PkdP985t6A5X1WUHvgzlk2w14SPjPJ/ATj@hRcPrdHcjzccDl1XXWOPRitOhUmR9nW8ElK9cYgXlhA5VYaR313FIVRX3AhivD28p2WIT3mI0xifVGvx6WKL4rCleTGxG2KP5rO/BwFjNKSfXNyx84mLi5ZroTYF9QyrpcIw/syR6X0Brq/qiIV/iwOn@4VELQCsR/b/IOBOdFl@6VmSf3l@6I7T571QtNne0d8 "C++ (gcc) – Try It Online") - PCRE2 (C++)
[Try it online!](https://tio.run/##rVNBbtswELzrFduFEJOBYsdJT1EEH1qnCFAkhZubFQiUTFsKKFEg6SZAGiC99A299Yv9gbuU7ToxcuyB9nC5nJndpdqyXZ2P2rKF0EACOEDoQ2vkIjOyVaKQrDfoH46yrBTKZYWu20pJk7KUx@lkYHsR9GjNKZgtpE9onGycZVl2cfl5nGU8giEnShzYJcbBXBsWVslxHKpkThcs@3rz8fKKx/wRqjkL1dQ6o2RDiB8Nb5ME0wY5JdtlTicUjo6joyGPu@yKy6LUPiUGYh3GAVAc2I7j4IAoj4mnhz2SCOukq60WrihZaKI7XTXME0R3VjfZTBZ6JhlOsR@qPt4i5yTlRdY9UcK6TBpDVfB3yZfJ@FN2dZ2NJ5PryQjHPn4GeMbCeoQ3ZinPgHZ4IZQliMT0RAY7NgwVxk97XWU8XgWM9Tljo/OEjZJgC9KT72z0nvM@5wROO8APw9VqCl4H5IOoWyUt3AYo8mIm5xgB0l9eCAzQb/DlCSHa//n965nWD1o/fXSLfRyDYArzpXGlNGsNJ62DQth/KgWxybVOkee5ELgXns1eiXaUXTP2/W4sDU9O6cLOokcvbazvvvbRpb6S6cDi7fKedyU@r0ustZH79dF71gZcWVmomnbpaPa6kNZWzQKOoDJGKvlNNA7uS@Ggy6JsCfiBHg9Crh@8syjtzKUYkRf/2208TrcnuDWwX9n/ceBFos34N8o73ZmsdUMfinASlNZtqZVc07wt6ukbea@qRtJdVdWVo5FsJ9A1PW02L@4v "PHP – Try It Online") - PCRE2 (PHP – doesn't work, and I don't know why)
[Try it online!](https://tio.run/##rVLNbtNAEL77KUYrS/Yi12lauMRJQ0XgwKEc6C2OrLU9aYzWXuO1aVEICheegRuvyBuEWTsmP@qRw3q/@dn5vvFMiZV8tWs0wvuPH@4CMGgmajEazZq8xCqA/CvYdK2lSoQEexCQORnPbu9vbzbWUlWunU0ug/FNQPeQryFbkoevyyoramBhwYIN2BImoJtY15QeeRdDb8jxswnC9Mh/SREOI7CjwAIqBG4fkxQzTxzm8LUtqFqKiUox@qRVAc7c8W3pOwuHxJnga8rZzC8XvqHwO2u4CKAT5bom6TsM7Gqg@dS5rxocATgj552QmqDDgw0J6LJtGcAmit7ezaJoZ7muz113Op6404nVg/Dqmzt9ybnPOYHrFvAX9m43B1Mb8EnkpUQNC4uJOElxyTxgdMWJYBYzBjuOECL7z@9fWzo/6Pw03h4bP7OsOSybql5h1XHUqGtIhP7HklA17HiSOI6FYGfuND0hbUu2P@Bc717S8OqaHhwkGnQso3t7qqNNPaFpwcPz7W0PLW67FnNV4Xl/HtDWQb3KNGRF2dQ0J5Wg1lnxABeQVRVK/CJoco8rUUObRdkI7A0tDINYPRllXtiKC5lHWsy3NQwO@wjrBZx39n8UGBJvP/4984E3xVwVtPqiRpBKlSslsSvzPKkpX@CjzAqktzLLs5pG0k@g/elhsd@4vw "Perl 5 – Try It Online") - Perl 5
# Regex (PCRE2) length-limited, ~~39~~ 38\$+\lfloor log\_{10}L\_{max}\rfloor\$ bytes
It is possible to emulate molecular lookbehind (and some of the power of variable-length lookbehind) using [jaytea](https://codegolf.stackexchange.com/users/75057/jaytea)'s [lookahead quantification trick](http://www.drregex.com/2017/11/lookahead-quantification-utterly-loopy.html), but this limits the maximum possible length of String 2 to 1023 characters. In the linked blog post I commented (as Davidebyzero) on a way to extend this limit by a couple of orders of magnitude, but it nevertheless remains.
This trick does not work in Perl 5, because apparently it has the same ["no empty optional"](https://github.com/Davidebyzero/RegexMathEngine/issues/1) behavior as ECMAScript. *[Edit: This isn't true in most circumstances. Needs to be looked into.]*
1 byte can be saved by omitting the anchor. Any non-match will remain a non-match even if it is attempted from later positions in the first string, because if the second string isn't made up of a subset of the first string's characters, it certainly won't be made up of a smaller subset. This does result in a slowdown for non-matches.
```
((?=(?=.*
(\2?(.?))).*\3)){1,1023}?.*
\2$
```
[Try it online!](https://tio.run/##rVbrbuJGFP7vpzjxVsEGhwairqI43ihLvEqkDYmIUXcXkGXMGJwY2xqbZZM0UvbPPkP/9RX7BE3PXAzmklaqirjMnHPmfN@5jfHTdG/s@y9vRiQIYwLXrY7ddFtXZ7bbbV847q8XZ845HCpvwtiPZiMCx6lPSbM@eaf4E4@Cm/YGYEFHfT@f3w0PZp/v7z85k7fzifaiaScWvutVRes3T7T6ia7r9Wr/QNcfG0Zjv3nwdIK6fvOnF339sGpANbXctNYwS8hZPgoThlwW0TAer8rCBKXEm27avVPCOIcUl7lLKE2o5idxlgOPpDolWeaNif6IOEdHPhrA8TFIKVtyOYlHkQmU5DMaQ8N82nDJ9n4yIjo8KoAv7lx66TV/eTswuTgMQOOpdMdEHnWllcaOG6CJWnRb56edw6oulQZk4QNJAq2gCz8XkpI9ppqjsNdKOCo3Ao53BOqrEfLTiygVEebUC2OtiCvtYVIjEmupvtcYWPsmzNDmoOnmkFj7SDPBvhCUbrrvb5wLp@vYrv3Jsdtn9hn8tqnrtm9sx7Uvr53PJjC8MXpVFiGIGqIineUmiNyxTEGVkmI/9XJ/4o683MN6LtbCGyXZLMoNEbtZwF98sbkkCDKCymSWY0zjfLJiUE2@Ej/HUzItGFmBP03DiGgy9zfXTkdPDXn0i925ch27c3nRPnXss0LcdT4YsMtZyF@Jva8vW2OHYmVl/svdxb@lXSlYayN@F/deTtyAJlM39fKc0Fij2D7t7seP0kGQUOD9@sDKx5OMzRjhPaCJpgljQ@RbN9GmUZS@IPmgA@pYg2uVflyRXgstP9jbH1hWRa2Uj65X1E/Se03CrBgt@IXYULdWw7hDnua6qwKPuendbocr292hktnWCfUyooVGmczRUZwmGYY7xPTd4Xhv88KRwlptYLGwTbizGuZWw/mENQc3r9U4NcAsIYuC7I5VMSpbC61ehlnGsoMGqv7f3av/5r6vMv9wW6ttgjwBiTLyD7lc5rzfr8DuLk9Nnd1HeE8cW4C0tsO3k3zC4L0AGxPY6deCXCQbm1zA4XoLVeX1nZj81SHhs1AeW87cd7ENNN0ox4GDyd/L2VoZonI6JNAxjvIrTSotdoqr0e50rjpu@@ry1Gmd46FykoQt1oYLA0215a2tm7IwheKDhzuuULaUr7By6AyNVqyWeQrmNMyJGMNlGsS2yEODj0qymFNxeuPmCSgh2nKvly9rocTLbfEMFVHiI@alB4whkG/eNI1IBgNF9YY@/jHBvwMq/gx9T1VUtlHLGlzh/s8/fn/Gz3f8/GDSYs3kqqL0IJjRfIK9xjFywh77OP4Fio/eiMDxh8Oh56lr4tFoBZS75Glf5yspNZoHeGBJka3KNMTZVR7cdAWGL8bbw3tehvgsQpwm@Ghai8/gtygOWyaKid2Q@ETM/h6ElJKIfPXwjp1PPLxomRVaE1BbWC0Vhsk3xszoc3J91UAu7Jtv2LpfaNSCwHpk/w8DBmLI8ktkufzLDyJvnL3sRbzN9g7/Bg "C++ (gcc) – Try It Online") (C++)
[Try it online!](https://tio.run/##rVPNTttAEL7nKaYji@wi48ShveBaPrShQkJQpdxiZK2dTWy09lrrTUFCSPTSZ@itr9g3SGcdaCDiWMlrz99@3zc767ZsNx@TtmzBMxADjhACaI1cZUa2ShSSDUfBYZJlpVA2K3TdVkqalKU8SmejbujDkNaSgtlKuoLGysZ2LMtOz86nWcZ9CDlB4miN0WCpDfOqeBx5Kl5Sfce@XX0@u@ARv4dqyTw176xRsiGLH4XXcYxpg5yKu3VOGQr7Y/8o5FFfXXFZlNqVRECoYTQAigPbYRwcEOSYcIY4JAqvjvvWamGLknnGv9FVwxyAf9PpJlvIQi8kwzkGngrwGjknKkeyPRIlOptJY6gL/i7@Opt@yS4us@lsdjlLcOriJ4AnzKsTvDJreQLk4alQHZlISA8ksEdDT2H0sHeojEcbxpKYnuBwwNJJwoKEFASH6THn96EfjifHDwnl0om32czBcYC8E3WrZAfXAxR5sZBL9AHpkxcCB@gcfJkhi/w/v3890vpB66eLPtsujoPBHJZrY0tpthxWdhYK0f1jKQhNbnmKPM@FwL3wYvGKtIfsD2Jf75OkcHJMG3YSnfVSxnbvax196Sua3li93d7jrsXHbYu1NnK/P7rK2oAtqw6qpl1bmrsuZNdVzQqOoDJGKvldNBZuS2Ghr6JqCfiJLg5Cru@cMj/txaXokxb37h1np88ZfBaw39n/UeBI/KfxPzHveBey1g39JMJKUFq3pVZyC/M2qYNv5K2qGkl7VVVXlkZCLDS19x/Sph@Ag@99/As "PHP – Try It Online") (PHP)
# Regex (PCRE2) length-limited const, ~~36~~ 35\$+\lfloor log\_{10}L\_{max}\rfloor\$ bytes
The regex still works with a constant quantifier (for a total length of **39 bytes**), but will take more steps (but not necessarily much more time, depending on the optimization done by the regex engine).
```
((?=(?=.*
(\2?(.?))).*\3)){1149}.*
\2$
```
[Try it online!](https://tio.run/##rVbrTuNGFP7vpzh4K2InJiWhXVGMF7HgFUhLQMFRdzeJLMcZJyaObY2dzQJFon/6DP3XV@wTlJ65OHEutFLVKJeZc86c7zu3cfw03Rv5/subIQnCmMDNWdtuumfX57bbaV067s@X584FHCpvwtiPZkMCx6lPSbM@fqf4Y4@Cm3b7YEFbfT@fTwYHs8/395@c8dv5WHvRtBML3/WqovWaJ1r9RNf1erV3oOuPjcYPPz2hotf87kVfP6kaUE0tN601zBJslg/DhMGWRTSMR6uyMEEp8aabdu@UMM4hxWXuEkoTqvlJnOXAw6hOSZZ5I6I/Is7RkY8GcHwMUsqWXE7iYWQCJfmMxtAwnzZcsr2fDIkOjwrgizuXXrrNH9/2TS4OA9B4Ht0RkUddaaWx4wZoohCds4vT9mFVl0oDsvCBJIFW0IXvC0nJHvPMUdhrJRyVGwHHOwL11Qj56UWUighz6oWxVsSVdjGpEYm1VN9r9K19E2Zoc9B0c0isfaSZYFMISred97fOpdNxbNf@5Nitc/scftnUdVq3tuPaVzfOZxMY3gi9KosQRA1Rkc5yE0TuWKagSkmxn3q5P3aHXu5hPRdr4Y2SbBblhojdLOAvv9hcEgQZQWUyyzGmUT5eMagmX4mf4ymZFoyswJ@mYUQ0mfvbG6etp4Y8@sVuX7uO3b66bJ069nkh7jgfDNjlLOSvxN7Xl62xQ7GyMv/l7uLf0q4UrLURv4t7LyduQJOpm3p5TmisUWyfVufjR@kgSCjwfn1g5eNJxmaM8BLQRNOEsSHyrZto0yhKX5B80AF1rMG1Si@uSK@Flh/s7vctq6JWykfXK@on6b0mYVaMFvxCbKg7q2FMkKe57qrAY266d9vhynYTVDLbOqFeRrTQKJM5OorTJMNwB5i@CY73Ni8cKazV@hYL24SJ1TC3Gs7HrDm4ea3GqQFmCVkUZHesilHZWmj1Kswylh00UPX/7l79N/c9lfmHu1ptE@QJSJSRf8jlMue9XgV2d3lq6uw@wnvi2AKktR2@leRjBu8F2JjATr8W5CLZ2OQCDtdbqCqv78Tkrw4Jn4Xy2HLmvottoOlGOQ4cTP5eztbKEJXTIYGOcZRfaVJpsVNcjXa7fd12W9dXp87ZBR4qJ0nYYm24MNBUW97auikLUyg@eLjjCmVL@Qorh87QaMVqmadgTsOciDFcpkFsizw0@KgkizkVpzdunoASoi33evmyFkq83BbPUBElPmJeusAYAvnmTdOIZNBXVG/g478S/Dug4s/A91RFZRu1rMEV7v/84/dn/PyKn9@YtFgzuaooXQhmNB9jr3GMnLDHPo5/geKjNyJw/MFg4Hnqmng4XAHlLnna1/lKSo3mAR5YUmSrMg1xdpUHN12B4YvR9vCelyE@ixCnCT6a1uIz@C2Kw5aJYmI3JD4Rs78HIaUkIl89vGPnYw8vWmaF1gTUM6yWCoPkG2Nm9Di5nmogF/bNN2zdKzRqQWA9sv@HAQMxZPklslz@5QeRN8pe9iLeZnuHfwM "C++ (gcc) – Try It Online") (C++)
[Try it online!](https://tio.run/##rVPNTtwwEL7nKaajiLVRyBKgh5JGObTbCqmCasttgyIn690EOT@yvQUJIdFLn6G3vmLfYDvOQhdWHCvFyfz5@77xOH3Vr9@nfdWDryEBHCOE0Gu5zLXslSglG43D/TTPK6FsXnZNXyupM5bxOJuOzSiAEa0FBfOldAWtla01LM8/nX2Z5DkPIOIEieMVxt6i08yvk8PYV8mC6g37dvnx7JzH/A7qBfPVzFitZEsWP4iukgSzFjkVm1VBGQoHh8FBxOOhuuayrDpXEgOhRrEHFAe2xdjbI8hDwhnhiCj8Jhlaa4QtK@br4LqrW@YAgmvTtflclt1cMpxh6KsQr5BzonIkmyNRwthcak1d8DfJ1@nkc35@kU@m04tpihMXPwU8ZX6T4qVeyVMgDz8JZchEQrongQMa@grj@51DZTxeM5Ym9IT7HsuOUhampCDcz445v4uik3f3lMiO/PV6Bo4A5K1oeiUNXHkoinIuFxgA0qcoBXroHHyeIYv8P79/PdD6Qeuniz7ZLo6eN4PFSttK6g2HlcZCKcw/lpLQ5IanLIpCCNwJz@cvSAfI4RR29T5Kio6OacNWorOey9jsfaljKH1BMxjL19t72Lb4sGmx6bTc7Y/ucafBVrWBuu1XlobeldKYul3CAdRaSyW/i9bCTSUsDFVULQE/0K1BKLpbpyzIBnEZBqTFvQfH2dlTBp8E7Hb2fxQ4kuBx/I/MW965bLqW/hBhJaiu66tOyQ3M66QOvpU3qm4l7VV1U1saCbHQ1E7eZu0wAAc/@PgX "PHP – Try It Online") (PHP)
# Regex (Perl 5 / .NET / Java) length-limited const, ~~34~~ 33\$+\lfloor log\_{10}L\_{max}\rfloor\$ bytes
This version works in Perl, in which the quantifier can go up to `{32766}` (which would make a regex length of 40 bytes, and still execute fast), and in Java, in which the quantifier apparently can go up to `{400000000165150719}` (but must be much smaller for execution time to be practical).
PCRE1 (and PCRE2 earlier than v10.35), as well as Ruby, treat any quantifer greater than 1 on a lookaround as being 1, so the lookaround must be wrapped in a dummy group, costing 2 bytes. But in Perl 5, .NET, Java, and Python 3, lookarounds can be directly quantified:
```
(?=(?=.*
(\1?(.?))).*\2){9999}.*
\1$
```
[Try it online!](https://tio.run/##rVLNbptAEL7zFKMVEhARbJImlUwcN6rbQw/pobkZCy0wjqmWny5Lk8qici99ht76in0Ddxbs@kc5VmLZmflm5vtGsxVKcbVpaoQPnz7eB6CtKVd8NJo2eYUygPwbmHStRJlwAeYgIHd8M717uLttjUUpbTMbD4Ob24Bu31lBtqCIs6pkVihgYcGCFkwBY6ibuFaUHrnnvus7@EWDMDmIDwlxYARmFBhAjcDeYYIwXWIxy1mZnLqlmJQpRp/rsgBrZnmm8Ky5ReI0@IZy2tlw7mkKr/f8eQC9KNvWSd9hYMqBM7EeZIMjAGtkveeiJtNygpb4@2RTBNBG0bv7aRRt7MmYPu/MsEN/YnsTx3G8s/DCWV1evL6@bgkIfXOzmYHuCfjM80pgDXOD8ThJccFcYHTFCWcG0w47RMgi/8/vX2s6P@j81NGdrePMMGawaKRaouw5FNYKEl7/Y0moG/Y8SRzHnLOTcJoekXYtu8FP9W4l@ReXVLCXqK1DGX3tsY4u9YimMx5fHm@9H3Hdj5iXEk/nc4EeG6hlVkNWVI2i/ZQJ1nVWPMI5ZFKiwK@cNva05Aq6LMpGYG/pnTCIy2etzA07cSFzSYv@d462wx3CdgJOJ/s/CjSJu13/lnnPm2JeFvTiuUIQZVktS4F9m5dJdfsCn0RWINWKLM8UrYRYaGuvrsKiW4Bu3/nsLw "Perl 5 – Try It Online") - Perl 5
[Try it online!](https://tio.run/##rVPNahsxEL77KaZDSCWzXrJuc2jMxoHQQiGh0KT04E1B3pVtgfYHSU5cXEN66TP01lfsG7gjrd3Exr1VeNfz/32zM8ptL6@NXFeilLYRuYSbr9bJcjm3qprCrVy4@KOczrUwbxeNkdaqurKDXAtroVxaJ5zK4b5WBVwLVQHjy3thwKYXuGbDlH5xt8OyZMjiIec87mZ9vnxDZ0X2LDla48DHm7SSD0BAcsFsfDMfW2cInyWRja9kNXWzXp9Hwf@hcZ5CfFmXjdKy4KFA86zABSIyNjzLsvjb6AviHe9yROhG0D3kQD5o0UAPJrVhqnIwSU8GTKeXBFRrSV9AFFeqkozzF2k11xSYJnypJmxyfsK3UZ@NcrING3QA1ASY3rA/P4XjY9Cjk7s0fYkvW2Xr7CWtlVNSODsFGS5PVstkhZGJ39tr4fIZa2cU/2M6cfgM8adK2lw0kjVkaDTNlukIj5KsOuojzWKIt2YuzwDwDN8JbUnESAfqkrQDLIJ7RWc9Ap8LciHKRksLdx0U47yQE4wA6W@cC@ygV/C5hyTSf//6@UjPd3p@eOtW9nbsdEYwmRs3k6bFcNI6yIX9i5JTNdni5OPxWAjcMxfFDmgoGRrc57uhlPRfUcITRS89p9Hm7vIIoTswQZgebu/xqcXHtsWSLt1@fxHQ@oGbKQuqauYOGlPnfqa0mj1Qxkgt7wVt58NMOAhRFC0BL@tCIozrhWcWZYFchhFx8e@geDnbenBLYL@z/8PAg0Sb8W@Qn3ALWdJeOSOcBF3XzYxWrC1zGNSXp6ut6VpRrlYlLaPxKDS116dZFQbgywcd/wA "C# (.NET Core) – Try It Online") - .NET (C#)
[Try it online!](https://tio.run/##bVLBbtswDL37K1ihaCSvU5PutBpesAHraR2Gdbe4BWRbTtTKsmvJbYYsQHbZN@y2X9wfZJTjtkkXw4bIR/I9kvKNuBevb/LbtSrrqnFwgz5XFQ8j2EZap/RerJFTOfeRuk21yiDTwlq4EMrAooesEw6P@0rlUGKAXrpGmSmIZmonVwzcrKkeLHycZ7J2qsLCAOBcaQlFbORDZ1LCsyqXHOOERR/aopCNzL9KkcsG0i5tF6SPlb1bMBb1uvbYRQ8zT0ptnOIEIv@kjKSMHcSm1Zqpglou71qhLSUnYRgSxha7qY8Ebi/BAhncEwMSnCBDinm3kX0VDxIz8KeLlhts@UU4JxsDTdxbOGxZewHLIlzGZSaMwUGVqVsHMfjZeoxefrdOllwZhrdjHKh4GEHXHdAun8@E/SznDtuDBWBn6iAesr6swniNW3HaUE8Qj7weKm5WpVFsQ2KQoR8dOYBqrqWZuhll74ZwdASaZzPRvHd0yOJ4QAasu8Utqjuk8r9LrUUmz1VjHSUJoXR8luDDf0yuE3LFQpYQCI8h3B8ix0AOR4k5PCUs6vkvhMtmuJwSBRpebjx6h32@nLGgJS@UySmDMZBvTSvPAAicATnHi0IHSZf/VVGN6HIZ@B9hfU3HMb48DGgyGlM@ZozxMDlli7f4LBFPRodrf@PrCXgFkHNR1lpauAqISLNcFn4IPNJMkKCbiGxH0EL/75/fK/x@4vfLo4@2x3fTs4IEwQSKtnF@C52mk9ZBJuyTaobpcqObpWkqBHkB5/kOa0fZLeVl/32Lo9M3WPDcsre229jU7vbRpe7IdMZ0/7ir55FXK/IP "Java (JDK) – Try It Online") - Java - 1 byte longer – needs the anchor for some reason – this needs investigation
# Regex (PCRE1) length-limited, {~~45 or 42~~ 44 or 41}\$+\lfloor log\_{10}L\_{max}\rfloor\$ bytes
Due to a [fundamental flaw in PCRE1's design](https://bugs.exim.org/show_bug.cgi?id=2495), a workaround is needed to prevent the regex from returning truthy when the last character of String 2 is not present in String 1:
```
((?=(?=.*
(\2?(.?))).*\3.*(
\2))){1,481}?.*\4$
```
[Try it online!](https://tio.run/##rVXdbuJWEL73U0xOu8EGB8VhVa0w3mibzaoX2aRCrNQKI2TMGByMbR3bS34aKXuzz9C7vmKfoHTOOTYYlrRSVcTPzJyZ@b6Z8Rz8ND2Z@f76uzD2o2KK0Et9ju35W82fexzG6XAEDvTZj6vVYtIpfr2//2Uw/2E119e6fu7Qu93UdPfsXG@fG4bRbrqddlPX3DNSHi3z9Rvr6ZyMr79fG/sZmAnN1BmnLcvWtuhZPg0TAV838TCe7drChKzoLb/1e6uFcQ4pifkYOU@47idxloMsp7nELPNmaDwSTrfrkwP0elBahSjtGE8jGzjmBY/Bsp9kyqUXxroBjxrQKx0SWoSxnhon1sg5taEgn87ZOIdEaCJgRoJ0ljkVOzpIi9wG0WRocrShzo7opDlX0RyzIsqVLOoIggxzE5IiJ9hZPlcnyWf084QPOyMFRVkdmXzsJ8s0jFBPTfj5on85fn8zeHd1Bb8p7dPgwxsTjhWgEiqEU0OlCgPQjzgaVR8C2dNAp2rI2wQmEklqHDxiIsPh1bQLrzI3punWciqcMnFAAbog/yA6JZszwzwKY9TVVMLYVH0ybPKxqp5XpB4MoDPRMb3hxo0ya3UqA4enI8dpsEY9dH8SfpLe6yXMjtOGX@icmreOZS6Ip72fqsITaYa3h@Hqfgs6FL5t5F6GemjWyXS7cZpkVO6EHuoFPXCHskiksNUaOaJsGxaOZR90XM3F4KV7qyWpAXWJWFRkj5yG2dgMtr4r7GOYZaI75MCM/56e/Vt6l4n8cNtqfQvyBBhl@A@93PbcdRtwfCxb087CB6QF7TlAtA7DXyf5XMB7QY4cRPRLRW6aTfuk4Eg@QFV7WVMbXO0j3qGvczTh@tPVlakY@2Mav26Ydf60gPJdbrYJnT2GogFl6h4t6wuPZelx5Kh9v@z3b/rj65uP7wYXPxlQrjK7FG3pgpiEbHll/@CRJu3agcFUXgNekNOO17YDwYqHOaoF2xaq1KpSSy5BstlAFR1wROJvbG7g8irUntZDEJiAd94yjTCDkca8iT/FgK4bRj8T32MaEwqrn5BE@p9//P5Mny/0@SqslSzsTNOGEBQ8n9NzITFyFNcyrWqF4lM2VDj@ZDLxPLZnnk53QGVK2ch9viUl66xDAVuKQqrTULG7PKTrDowUZofLe96W@KxKXCb0D7FXnylvPFqMTI2H5pv4qPb0BELOMcLPHt2Hqznd89KLvBHYRTJFBpPkTjAzXUnOZSZxEd9SEbJbnbCKwH5l/w8DAWKW4y@RS/EvP4i8WbY@icQq/g0 "C++ (gcc) – Try It Online") (C++)
[Try it on regex101](https://regex101.com/r/8MgdLJ/10)
The regex still works with a constant quantifier, but will take more steps (but not necessarily much more time, depending on the optimization done by the regex engine):
```
((?=(?=.*
(\2?(.?))).*\3.*(
\2))){500}.*\4$
```
[Try it online!](https://tio.run/##rVXdbuJWEL73U0xOu8EGB0FoqwrjjbZpVr3IJhVipVYYIWPG4GBs6/iw5KeR0ps@Q@/6in2C0jnn2GBY0kpVET8zc2bm@2bGcwiy7GwWBJsvoiSIV1OEXhZwbM7fGsHc5zDOhiNwoc@@W68Xk87q54eHnwbzb9Zzc2OaFy69m3XD9M4vzOaFZVnNutdp1k3DOyfl6etW65ksX325sQ7DmQ31zB1njbZj7KBzMY1SiV018SiZ7duilKzoLz/3e2tEiYCMRDFGzlNuBmmSC1C11JeY5/4MrSfC6XYDcoBeDwqrFJUdk2nsAEex4gm0nWeVculHiWnBkwH0yoaEFmNiZtZZe@S2HFiRT@d8LCCVmgyYkaCcVU7Njg6ylXBAdhjqHB2osiM6meA6mmO@ioWWZR1hmKOwIV0Jgp2JuT5JP2EgUj7sjDQUZXVV8nGQLrMoRjOz4cfL/tX4@9vBu@tr@EVrHwfvv7XhVANqoURoWTpVFIJ5wtEq@xCqnoYmVUPeNjCZSFHj4BMTFQ5vpl14k3sJTbeSU@MUiUMKMCX5R9kp1ZwZijhK0NRTiRJb98lyyKdd9rwk9WgBncmOmTUvqRVZy1MVOGyNXLfGatXQw0kEafZgFjB7Tlt@kduy79y2vSCezmGqEk@mGd4dh6v6LehQ@jaR@zmakV0l0@0mWZpTuRN6qBf0wB3LopCiRmPkyrIdWLht56jjei4Hr9wbDUUNqEvEoiR74tbs2naw1V1hH6I8l90hB2b99/Ts39J7TOaHu0bjc5BnwDjHf@jlrueeV4PTU9WaZh49Ii1ozwWidRz@JhVzCe@HAjnI6NeK3Dab9knDkXyEqvG6pje43Ee8x8DkaMPNx@trWzMOxjR@07Kr/GkB1bvYbBs6BwxlA4rUPVrWVx7LwuPE1ft@1e/f9sc3tx/eDS5/sKBYZXYl29IFOQnV8tL@3idN2Y0jgym9BnxFTnteuw6Eax4J1Au2K1SrZaVttQTpdgN1dMgRib@1vYGLq9B43gxBYgLe@8ssxhxGBvMnwRRDum4Y/UwCnxlMKqx6QhLpf/7x@wt9fqXPb9JaytLODGMI4YqLOT0XCkOgvJZpVUuUgLKhxgkmk4nvswPzdLoHqlKqRh7yLSi1zzsUsKMopSoNHbvPQ7nuwShhdry8l12JL7rEZUr/EAf12erGo8XI9XhovmmAek/PIOIcY/zk0324ntM9r7zIG4FdplNkMEnvJTPbU@Q8ZhMX@a0UKXvlCSsJHFb2/zCQIHYx/gK5EP8Kwtif5ZuzWK7i3w "C++ (gcc) – Try It Online") (C++)
[Try it on regex101](https://regex101.com/r/8MgdLJ/11)
# Regex (Ruby) length-limited, ~~50~~ 49\$+\lfloor log\_{10}L\_{max}\rfloor\$ bytes
The lookahead quantification trick fully works in Ruby, and can go as high as `{100000}`. There is no support for nested backreferences, so `\2` must be copied to `\4` in a lookahead:
```
((?=(?=.*
(\4?(.?))).*\3(?=.*
(\2)))){1,100000}?.*
\2$
```
[Try it online!](https://tio.run/##rVPNjtMwEL7nKQYLKcluGrXd5bJVVK1YOHBYJNhbU1VOMm29cuNgu7QIgcqFZ@DGK/IGZew0dFvtkSg/M@Nv5vsmY@t18WWv8dNaaITw0ag6DDRk8AEXuG3SGjdwd/twm2rk1QhE1h/BZikkgswWaE0AIOYgXrh4s7ZmBFh73GDkFuSkN5hmGctrNqIMOemnaW849ag2lUIECFlILoAh5ncf39@nDdcGo3ASXsrLcBrG6aMSdeTqxB7YaFFbB/8OGsbAHvQabwAY3AB7y6Uhh3UsLVa27mz25v5uNttH0TijO70Iovx6HKXjOI7Ti/yqiw3Jj78OkkHfXd/GFMyHL/f7CTgqwC1fNRINTAPGi7LCOUuA0acoOQuYc9jTFbLI//P7146eH/T8dNHOdnEWBBOYr7Vdom45LBoLJTf/WEqqhi1PWRQF5@wsXFUnpL6k/xvneg@SBsMrSjhKdNZTGW3uqQ4PPaHxxuL59nbHFndtiytFG@2svwTmSoNdCgOipm1EI1MlGiPqBfRAaI0SP3Ma4mbJLXgUoRHYa1Uhg0JtnbIk9@JylpAW9/aOs/NuhXUCzjv7PwocSXIY/4H5yFvhStXGam7p8CjVLBWdIl/meVJXno6fFDVSrhQrYWkkxEJTu36V134Arrz32V8 "Ruby – Try It Online")
While Ruby's regex engine does have subroutine calls, and thus at first glance it might appear to be possible to adapt the solutions that emulate variable-length lookbehind to it, it does not appear to be possible to do so. Any attempt at recursion with subroutine calls generates the error "never ending recursion", even when there are clear-cut terminating conditions.
# Regex (Python[`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/)) length-limited const, 44\$+\lfloor log\_{10}L\_{max}\rfloor\$ bytes
The lookahead quantification trick works in Python 3 (using the [`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/) module rather than `re`), but only with a constant quantifier. This is a shame, because Python can go as high as `{4294967294}`, but increasing its value in this regex causes super-exponential slowdown. There is no support for nested backreferences, so just like the Ruby version, `\2` must be copied to `\4` in a lookahead.
```
(?=(?=.*
(\3?(.?))).*\2(?=.*
(\1))){300}.*
\1$
```
[Try it online!](https://tio.run/##rVLNjpswEL7zFCOrErDLorDpXqhQDpX6BL1BDgYmwStjI9tpsqoqpZc@Q299xb5BOoZks0lzXAnjmfHM9yN7eHGdVvOD6AdtHNgXmxhc4y55tloFBgowjLFDtCjoS@@CqJovonQRx3F6Vz2eahnl3@ez2Q/KquzDgUbKLH/Ilp9AFLNgpQ1IEMrDp9a1QuUBgFiByGEwQrko9nmRTVWJKpIxcNWCLKeEoIoirFSYgyxkOfPYN5pnvotR05FIb1y6NcJhxL6aDeYAzM@MDtOeu6aLTAIeN33WQkXedCo1b20UluG9vA@XIVkDlBaBfeG05cC82P8IZHwowZMA7ng/SLSwDBivmxZXLAFGW91wFjCfsLcnFFH@98/vPa2ftH756in2dRYEJaw2xnVoJg6H1kHD7StLQ2g48TR1XXPOrspte0E6Qo6GrvUeJWWPcxo4S/TRWxnT7KWOsfWCZgzWt@3tzxb3k8VeG7z2l4B/Pa4Tlh7QsHH0YHSD1gq1hgcQxqDEb1w52HbcwdhF3XRbn3WLDGq988qSahRXsYS0@P@Y@Lg6nbCTgGtn76PAkyTH6z8yn3lb7LWyznCHILUeOi1xgrlN6uEVbqVQSLNS9PQCjWehW/v4VKnxAjz8mLN/ "Python 3 – Try It Online")
# Regex ([RegexMathEngine](https://github.com/Davidebyzero/RegexMathEngine) `-xml`), 27 bytes
In RegexMathEngine, molecular (non-atomic) lookahead can be used in the form of `(?*...)` when enabled using the `-xml` command line parameter ("enable extension: molecular lookahead").
This needs to be anchored because the delimiter is inside a negative lookahead, so without the anchor, a non-match could become a match by leapfrogging the delimiter and starting its match within the second string.
```
^(?!(?*.*,(.)+)(?!.*\1.*,))
```
Comma is the delimiter because it is not yet possible to work with strings containing newlines when using command-line invocation of this regex engine (which works as a one-line-at-a-time grep).
# Regex (PCRE2 v10.35+), ~~27~~ 24 bytes
PCRE does not have variable-length lookbehinds, but PCRE2 v10.34 has introduced non-atomic lookarounds in the form of `(*napla:...)` and `(*naplb:...)` (with the added synonyms of `(?*...)` and `(?<*...)` in v10.35), making it also able to solve this problem in the general case. This is shorter than in RegexMathEngine thanks to the use of newline as a delimiter:
```
^(?!(?*.*
(.)+)(?!.*\1))
```
[Try it on regex101](https://regex101.com/r/SyAsid/1/)
[Attempt This Online!](https://ato.pxeger.com/run?1=rVPLattAFKVd6ituLiKecWU7TjclqvEidUugJMEJ3VipkOWRpTB6MDNOAiWQbvoJpdBFA6X_0G_Jqp_QT-gdyYljk2UXI93nOefO4_vPKq1u7579eT0kA1wFA8AeQhcqJeahEpWMYsFavW57GIZpJE0Yl3mVSaECFnA_GPd0y4MWrYSC4VzYgsKIwmgWhm8P3o_CkHvQ5wSJvQX6TnKpMiPYyemb0Xjs4fH-eLQLF8j99QShaBMVhrVsRfhhND45ODps8c06DArqdZJSMTcb7PiuHCSkQtv8wSH3-SfIEubKiTZKioIs3umfDQZ1HxXrxZQyFPZ2vE6f-3V1xkWclrbEB0Lt-w5QHNgKY3ubIHcIp4UtonDzQb1heWTilLnKOy-zglkA71yXRTgTcTkTDCfYdWUXz5DTIGBJmo2WkTahUIqm4FuD4_HoXXh4FNJ8R-Mhjmx8D3CPufkQT9VC7AF5-DaSmkwaH65JYI2GrkT_euOoGPd_LUzSefX7IxtusWG723ZYl7_g5HXbQZ_zJn27_N09_zoBywPiKsorKTScORhN45lI0AOk3zSO0EHr4OMMWeT__fHthtZnWl9s9N62cXScCSQLZVKhGg4jtIE40g8sMaGJhieeTqdRhBvh2WyNtIasN2NT71JSf_clNawkWuuxjKZ3XUddukZTG_Onx7tZjXjTjJiXSmzOR4-kVGDSTENWVAtDZ1_GQuusmEMHMqWEFBd05-EyjQzUVVQtAPfp8iBMyyurzAtqcQF6pMV-a8fawX0G7wVsTvZ_FFgSb3n8S-YV70zk9umqyAiQZVmlpRQNzNOkFr4QlzIrBPXKLKfHrR5OoN70oFjeuOZ-_gM) (PHP)
You can change the delimiter (for example to comma: `^(?!(?*.*,(.)+)(?!.*\1.*,))`), to test on the command line using `pcre2grep`.
# If the strings were in the other order: Regex (ECMAScript / Python), 19 bytes
If String 2 comes before String 1, there is no need for lookbehind or non-atomic lookahead, and the solution is universal to all regex engines that have lookahead. It does now need to be anchored though, because otherwise, any non-match could become a match by discarding the beginning of the first string.
```
^((.)(?=.*
.*\2))*
```
[Try it online!](https://tio.run/##rVNNj9MwEL3nVww@1HY2zX6AOGwU9oDgwAEklltTJCeZNl5cO7Ld3bKI314mbQo04sgpM@M37z17Jg/qUYXG6z7OQ69b9Btnv@H3vS8tPsFnXL/b9UI8l28u0/1XIXIp7so8TfK0upEyTfbp5bPMo7uPXtu1kHkwukHxOpu/krJYOS90eVUIU3pUrdEWhZQvSrs1ptDltfyhV0LLnnqjkEVicoN2HbvZzCyulmXJGZ/N@m0M0Qvx4f7Tx7xXPqDgC35hLviSy/zBaSt4ZbmU@UbFphNe3vEvfou3APyWv1cmUMhlMfIYWfzcL2BAAO7UpjcYYJmwFld1o1gGTNUNJSxhQ0Ifyv8uJwtYbX3s0B9JIoYIjQonmqaua3UiaqgHiaNt20llQnnweWaIDq9vXo6wo40BTPnUxrH33IcazR@a1hOxjfM4NZ8BTQtipwNoS28FvXcNhkBjhTlo79Hgo7IRnjoV4YAiNAJ761pkULvdIFuxbNDKqkG7OlxyKP2Oq@FgNDC1/X8cZOPFK3YWkDDptkjrTVugIoJxru@cwSPNv0UHevoPhsWlXqM3OtJ7L0/DqOyfrWG/AA "JavaScript (SpiderMonkey) – Try It Online") - ECMAScript
[Try it online!](https://tio.run/##rVK9btswEN71FAcukhxFsJNNhdChQJ@gm@QClHSOGFCkQNJ1srlLn6FbX7Fv4N5ZUlK7HjsQ5B3vvh/yxtfQW/N4UsNoXQD/6jOH2bO3JnJQghNCnL4mSZ4mH8t8FeWr@iFNV9GJ8tWmuN9sP4Aq19HOOtCgDAPkPnTKFBGA2oEqYHTKhCTluNxMWY0m0SlI04GupoCgyjKuTVyALnW1ZuwbxWuuElQ0E9l9yA9OBUzEF7fHAkBwj8Pco3Rtn7gMGDV/tsok7CvXVnY@iav4Tt/F2zhNU0DtEcRnSVsBgqX@A6/TUwVMAfgih1Gjh20kOtw1rRQZCNm0FIhIcEAbxRfp379@fqf1g9aRL3hfciKKKtjtXejRTRwBfYBW@oWlbZpGLjwtQSJBdl13lfmbkSDPhi700uXm4XEum1RyMcVLzyJj6r3UIWdv56ana3vHd4vH2xYH6/DaXwY8O6FXnsZn3AcaF9ui98o8wT0o51DjN2kCHHoZ4FxF1fRbn2yHAhr7wspqkTFjVrO8@vwOnHo713wxC7h29n8UZPPb1OLiQMTE2@FgjQ9OBgRt7dhbjRPMbVKGN3jQyiD1ajXQBLr5/@i9a/M@d@IP "Python 3 – Try It Online") - Python
```
^( # start loop at the beginning of String 2
(.) # at every iteration, capture another character from String 2 into \2
(?=.*\n # look ahead to String 1 (by finding the newline)
.*\2 # assert that the captured character \2 can be found in String 1
)
)* # continue the loop as long as possible
\n # assert that when the loop has finished, we've reached String 2's end
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~28~~ 23 bytes
```
lambda x,y:not{*y}-{*x}
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaFCp9IqL7@kWquyVrdaq6L2f0FRZl6JRpqGUmJSckpqmpKOghKQSkpOVNLU5EKWBMkAKUMjYxQZkDC6UoQ5QJn/AA "Python 3 – Try It Online")
-5 bytes thanks to Wizzwizz4
## 28 bytes
```
lambda x,y:not set(y)-set(x)
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaFCp9IqL79EoTi1RKNSUxdEVWj@LyjKzCvRSNNQSkxKTklNU9JRUAJSScmJSpqaXMiSIBkgZWhkjCIDEkZXijAHKPMfAA "Python 3 – Try It Online")
Simply turns the two inputs into sets and subtracts the sets from each other
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 3 bytes
```
dp⊆
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRuX/2obcOjpuaHWzsedSxXKikqTdVTqgEx0xJzioHs2oe7Omsfbp3wP6XgUVfb///RCtFKKalpScmJSjpKiUnJQLZSrE40iGloZAwRAwsAmWAapABFZVFqQWpiSTFQsCgVDqAyCL4OXF2sQiwA "Brachylog – Try It Online")
Takes string 1 as the output variable and string 2 as the input variable.
[Answer]
# JavaScript (ES6), 31 bytes
Takes arrays of characters as input.
```
a=>b=>b.every(c=>a.includes(c))
```
[Try it online!](https://tio.run/##hc7BCsMgDAbg@55CetLDLNvO9kXGDjHGrUN0qC306Z1MkDEKCznkh3wkT1ghYZxf@eiDoWJVATXp2pJWihtHNYGcPbrFUOIoRMHgU3AkXbhzy69SygE0GrLDTbRYZ41Qo2BsHFmOS35sh33XUZ1P50tD7OMsuLTLuunbvf6d@3nz@1xz5Q0 "JavaScript (Node.js) – Try It Online")
---
### 25 bytes
For the record, below is my original answer, which was designed for alphanumeric characters.
```
a=>b=>!b.match(`[^${a}]`)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i7J1k4xSS83sSQ5QyMhOk6lOrE2NkHzf3J@XnF@TqpeTn66RpqGUmJSckpqmpKmhhKQSkpOVNLUVFDQ11coKSotyajkwlQNUgqkDI2MwUoVwKrTEnOKMRSDVMLUwAE@oxEOQTIaovo/AA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), 1 byte
```
⊃
```
[Try it online!](https://tio.run/##S0/MTPz//1FX8///iUnJXEBsaGQMAA "Gaia – Try It Online")
Just a built-in. For strings, it checks for character-wise superset.
[Test Suite](https://tio.run/##S0/MTPz//1FX8/9qh4c7F6Y@ap9YWPuoqe1/YlJySmqaAhAnJSdyAXkKQGxoZMz1qGGOwqOGuVwgWYgiLqhaIMX1Yf6MBiBuBOI2BRgDJAgA)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 21 bytes
```
->x,y{!y.tr(x,"")[0]}
```
The `tr` method replaces all instances of the first string it's passed with the corresponding character in the second string it's passed. So all characters from x are removed from y. If there are any characters left, then it returns the first value (all values are truthy in ruby except `false` and `nil`) and inverses it. And if there are no characters left, then nil is inversed.
Golfy Tricks Implemented:
* Using `y.tr(x,"")` instead of `y.chars-x.chars`
* Using `!array[0]` instead of `array.empty?`
[Try it online!](https://tio.run/##KypNqvyfpmCr8F/XrkKnslqxUq@kSKNCR0lJM9ogtvZ/gUKaXnJiTo6GUmJSckpqmpKOghKQSkpOVNJUUFbwLy0pKC2xUigpKi3JqORCUQ1SCqQMjYxRlKYl5hQjqwQpw28W1FqoAxBKMYxCOBFkPZJCDCM/zJ/RAMSNQNwGUg9jg8QJeIx4S5CVYlX7HwA "Ruby – Try It Online")
[Answer]
# [W](https://github.com/a-ee/w), 2 bytes
Back then I definitely had the negation instruction. If you think it's boring then continue.
```
t!
```
## Explanation
```
t % Remove all characters of 1st input that appears in 2nd input.
% e.g. ['abcdef','abc'] -> 'def'
! % Negate the result. So if the resulting string had something,
% it will return falsy. Otherwise it will yield truthy.
```
# [W](https://github.com/myu-sername/w), 4 bytes
W is back, reimplemented!
```
t""=
```
If you want to specify your input and code, you look for imps.py and then re-set those variables like this:
```
read = ["abcabc","abc"]
prog = 't""='
```
Note that your inputs must be in a single array with the joined values.
# [Wren](https://github.com/munificent/wren), ~~86~~ ~~60~~ ~~30~~ 26 bytes
I didn't expect this. Wren is very hard to golf.
```
Fn.new{|a,b|b.trim(a)==""}
```
[Try it online!](https://tio.run/##FcpBCoAgEADAr8ieFMQfeO0DvWB3MxB0CbMksrdbXeY0rQQZJxa1HsLKqzGJk9DujpY6uVpi1mi8B3jGfO01ZLeVKFX/3zGmpAGJl7CChU9iBGPGCw)
## Explanation
```
Fn.new{ // New anonymous function
|a,b| // With parameters a and b
b.trim(a) // After removing all characters in a that are in b
// (If b can be assembled using a the result should
// be a null string; otherwise it should be a
// non-empty string.
==""} // Is this result an empty string?
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 3 bytes
```
√ó/‚àä
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT/////B0/UcdXf/THrVNeNTb96hvqqf/o67mQ@uNH7VNBPKCg5yBZIiHZ/D/R71zFYpLijLz0o0U0qAsQy71lNS0pOREdaCQemJSMpCnzgViGBoZw8SAAuoKEAAUgEiD1IF4cPXqUGmoHAA "APL (Dyalog Unicode) – Try It Online")
Use it as `string2 f string1`.
### How it works
```
√ó/‚àä
‚àä Does each char of string2 appear in string1?
√ó/ All of them?
```
[Answer]
# [J](http://jsoftware.com/), 5 bytes
```
*/@e.
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/tfQdUvX@a3JxpSZn5CsYKtgqqKekpiUlJ6orpCmoJyYlA3nqEEkDkCRQxNDIGCapjqQNLIamFKQZJAw25D8A "J – Try It Online")
Is each char of the 2nd string an element of `e.` the 1st string? This returns a boolean mask, whose elements we multiply together with `*/`. J is smart about 0 values so that if you apply `*/` to the empty list `''` you get `1`.
# [J](http://jsoftware.com/), 6 bytes
```
''-:-.
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/1dV1rXT1/mtycaUmZ@QrGCrYKqinpKYlJSeqK6QpqCcmJQN56hBJA5AkUMTQyBgmqY6kDSyGphSkGSQMNoTrPwA "J – Try It Online")
Does the empty string `''` match `-:` 1st string "set minused" `-.` from the 2nd?
[Answer]
# [Japt](https://github.com/ETHproductions/japt) `-!`, ~~15~~ ~~10~~ 5 bytes
```
k@V√∏X
```
[Try it online!](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LSE&code=a0BW%2bFg&input=ImFiY2RlZiIKImZlZGNiYSI)
Thanks to @Shaggy for -5.
[Answer]
# [Bracmat](https://github.com/BartJongejan/Bracmat), 51 bytes
```
(f=a b.!arg:(?a,?b)&vap$((=.@(!a:? !arg ?)&|F).!b))
```
The function f returns a list of Fs, one F for each character in b that is not in a's alphabet. An empty list means that b's alphabet is contained in a's alphabet. The function vap splits the second argument, which must be a string, in UTF-8 encoded characters if the second argument (!b in this case) is valid UTF-8, and otherwise in bytes.
[Try it online!](https://tio.run/##JYvBCsIwEETvfkUCId2FELDeAmV78gs89LrbNvWgWEqqF/89JvY0vHkzsvH45JQzxI6VeM3bEoDYkaB982oAOt@D5kCqOkVov1f0WhDz5/5oYJlTUx6OMNBgX3syEI0egr2VHWZgGac5uiPwVLnCub0UcEdRB3/7Aw "Bracmat – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~94~~ 85 bytes
```
f(a,b,c)int*a,*b,*c;{for(;*b;++b){for(c=a;*c&&*c!=*b;++c);if(!*c)return 0;}return 1;}
```
[Try it online!](https://tio.run/##jVGxTsMwEJ2br7gGUTmJWyUwgOQGCSExZYNOUFXOxQFLIUWJw1JFKgvfwNZf7B@ES9JChBgY7Ht3792zfcbpE2LTpEzymKOjc@NK7sbcRbFJ1wUTbiw8L3a6BEMpXJxMXByHXR0doVM2dtEplKmKHHxRH1Ag6qY0RYUGjCoNbKwRmQO5A7X2SaHKKjPCqjtJ@bCEsNVtIlvGmKjU5hDZFDGWBIOaH7mOoBicnRP0D0RXHQiPDt9m/o/DgBt07HefW1rvtD46@lfhX7r9brs9HFYL60TnmFWJgnm2Rpmp2fOVZbWPf5E6Z29rnTjtm0tlep5FN6vrKOJgq3y1uJst7m@nl7ZDE6MfANZ2ahqTLyjM4UKA5@nOYfRaEJky@zQrOfRbAmFI@2NO9@lHrJczOcDxAPe/wSFlf0ud9hK1VTdf "C (gcc) – Try It Online")
-9 bytes from [JL2210](https://codegolf.stackexchange.com/questions/194869/do-you-make-me-up/194963?noredirect=1#comment464041_194963)
Returns `int`: `1` for truthy and `0` for falsey.
Note: takes two parameters that are each pointers to null-terminated wide strings (`wchar_t` are the same size as `int` on the platform used on TIO, so we can take the strings as `int*` instead of including `wchar.h` and taking them as `wchar_t*`)
Explanation/Ungolfed:
```
#include <wchar.h>
int f(const wchar_t *a, const wchar_t *b) {
for ( ; *b != L'\0'; ++b) { // For each character in the second string
const wchar_t *temp;
for (temp = a; *temp != L'\0'; ++temp) {
if (*temp == *b) break;
// If the character is in the first string,
// then continue and check the next character
}
if (*temp == L'\0') return 0;
// If the character was not found, return 0 (falsey)
}
return 1; // If every character was found, return 1 (truthy)
}
```
[Answer]
# [Lua](https://www.lua.org/), 75 bytes
```
load'b,a=...return a:gsub(".",load"return not b:find(...,1,1)and [[]]")==a'
```
[Try it online!](https://tio.run/##Pc3BCoMwDAbge58iFEYaCAW3m@CTDA9pa4cgcbj2@V2dstOf/0sgS5V9WaMskKvGMq8K2QlDIPPeZi2/mcG1I0kYWAbv/TaVuilI//rU4Ky3fGztxboWCH2eNbl2yx13JJrg@RxHS8MguNP5gcykyZjsUEJMU0YGbBGiIF16UIvu/rj9rZWLTzoK0v4F "Lua – Try It Online")
Now this is a bit messy. `load` is used to create function here, so everything inside is its body. Here, after taking input, following transformation is done: every symbol in second string is checked in first one. If it is found, internal function return `false` and no replacement is done. Otherwise, symbol is removed (replaced with empty string). Resulting string is compared with one passed as input, efficiently checking that no deletions were performed.
TIO link also include test cases.
[Answer]
# [PHP](https://php.net/) (7.4), ~~26~~ ~~25~~ 28 bytes
```
fn($a,$b)=>''>=strtok($b,$a)
```
[Try it online!](https://tio.run/##fYw7CoAwEAX7nMJiYRNI4afU6FFkowZB1EWj148K6QJWA28ewzOHpuOZhQBngtskkAarTIvYmtMffl8kWA2kQi3ETUc/XitLcBLJDuPkUGf4wg6EStXJ49MvirJK9efSNTZj/aeZU6yGBw "PHP – Try It Online")
PHP's [strtok](https://www.php.net/manual/en/function.strtok.php), basically removes characters of its second parameter, form its first parameter and returns the result or false if the result is empty.
By removing `$a` characters from `$b`, if the result is empty (false), we output a truthy, else a falsy.
[Christoph](https://codegolf.stackexchange.com/users/29637/christoph) mentioned an issue with output of `'0'` from `strtok` (which equals to false), and to solve it, `''>=` is used instead of a simple NOT (`!`) at a cost of +3 bytes. `''==` would work the same way as well.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 7 bytes
```
g.{w.{w
```
[Try it online!](https://tio.run/##K6gsyfj/P12vuhyI/v9PTEpOSU3jAuKk5EQA "Pyth – Try It Online")
First string on first line of input, second string on second line.
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 5 bytes
```
ll\-!
```
[Try it online!](https://tio.run/##S85KzP3/PycnRlfx///EpGQuIDY0MgYA "CJam – Try It Online")
[Test Suite](https://tio.run/##S85KzP1fbf0/JydGV/F/Qa2Z6v/EpOSU1DQuIE5KTuQC8kDY0MiYiwskxgWVRlBcH@bPaADiRiBu44IxQIIA)
### Explanation
```
ll Read 2 lines of input
\ Swap their order
- Remove from the second input all characters in the first
! Negate
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 3 bytes
```
wmA
```
[Try it online!](https://tio.run/##y00syfn/vzzX8f9/9cSk5JTUNHUudSCZlJyoDgA) Or [verify all test cases](https://tio.run/##y00syfmf8L881/G/S8h/9cSk5JTUNHUudSCZlJwIZABFIKShkTGQAUEQNXDFyAwg@WH@jAYgbgTiNggXzAQJqwMA).
# Explanation
The code implicitly takes two strings as inputs, s`w`aps them, and verifies if `A`ll the characters in the first string (originally the second input) are `m`embers of the other string.
(A non-empty array containing exclusively ones is [truthy](https://codegolf.stackexchange.com/a/95057/36398) in MATL. This would allow omitting `A` if it wasn't for the case with empty inputs).
[Answer]
# [Kotlin](https://kotlinlang.org), 35 bytes
```
{a,b->(b.toSet()-a.toSet()).none()}
```
[Try it online!](https://tio.run/##dZGxasMwEIZ3P8VxeDiBHGi7BRxIh0Kh0IBXL3IqFRFVMrbcJRjapc/Qra/YN3AlO04wNILjhPT9/@lOB@eNtsO7MKDsGqjwjbavHKbMINvAvXNGCgv5cBS8yjZUrbwrpCeWiXnHVtZZSawfnbxsfQs5vIn6WVECYe2EbghFtX@RCjlgSNVeIAPvwDed5LDEIhPSze3dxChh2iUUiSv6U41TtSv6y1tiuf@Nfn@@P0J8hviK5LyP5xdJwpJEdTa0qy0xOI4GyjVEdXDh0Mi2M56BttNkZiSuOC4SHCoW5hXxxU0t2jhHrUjZmcrPfrjbFgWCDJ0BPmwfn/AsrsPveWMJS0xFGZ4eclVi/M50kq8hje7IRk0PST/8AQ "Kotlin – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 34 bytes
```
param($a,$b)0-notin($b|%{$_-in$a})
```
[Try it online!](https://tio.run/##jU7dCoIwFL73KcY4xQYKZXeB0HuEyLRjCWY2FwUm2E3P0F2v2BvYlpn93DQ4nI/v7yzf7FEWK0zTBmKvbHIhxZqBsCHkIyfbqCRjEB4HJQROkoGoeFNZ1oxZRD@bURFGC4ypTaheYSQ0AiV3yN8MRtVr7E6MGou06GWj/WSeja/ur0x/sy3/DN@ul1rPSc/ZeDps@H/MdR@o67fjnBzJgJSPJBRKJtlybHfI1QgPOUYKF8QjELQ2icUuVZoYQkzYPFoJOff9Ls1/KLf9GAX2jDq4ffXyaVdIraq5Aw "PowerShell – Try It Online")
Takes two arrays of chars as input.
[Answer]
# [K (ngn/k)](https://bitbucket.org/ngn/k), 5 bytes
```
~^&/?
```
[Try it online!](https://tio.run/##y9bNS8/7/z/Nqi5OTd/@f5qCnrqGhlJiUnJKapqStRKQTEpOVNK0BosBBYCkoZExWADIA9MQlVAtUJVwMbDAh/kzGoC4EYjbgMIwJkgYTUMy0ARNLq4YruCSosy8dAVDKwWYrI4CVMwIKAZ1F5d/aUlBaYmVQklRaUlGJReaNlQ9UKfD9aQl5hSjakFVj9d0DBdBXQnVg8VwbN4AuRGmA4slKOGGohElCAmEAqatyWkYev4DAA "K (ngn/k) – Try It Online")
A tacit function taking two arguments.
* `?` find the indices of the first matches of the right-hand argument in the left-hand argument; returns `0N` (null) if it's not present
* `&/` take the minimum
* `~^` is the minimum not null?
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 51 bytes
```
f(a,b)int*a,*b;{return wcschr(a,*b)&&f(a,b+1)|!*b;}
```
[Try it online!](https://tio.run/##jVGxTsMwEJ2brziCqJzWrRIYQEqDhJCYskEnqCrHcailkCDbgaFEKgvfwNZf7B@Ei9NChBgYfHe@99757swnj5w3TUYYTTxZmBGjoyRcK2EqVcAr13ylSJvzhkNLGgfe2xFS6kYbVXEDRmgDa2eAYkA1INZdlNBVbkKnthR9v4Co5a1jlyU8FZlLIXbR84RhGNT0gFkAfXB6hqG/B2y2RzxU@C7m/1ToYT3Fbvu5wfOO58PCvxL/4u22m83@sTp0jmXB8yoVMMtLznIxXV06Tjv8E5MFeSll6rUza2E6nMTXy6s4puCKYjm/nc7vbiYXrocby0oFpFVKXJMfopvBeQjjsbQVBs8KwYy4J7mm0JkUogjtQ4H9dCuWiynrxUkv7n6DQkb@pnptE7VTN18 "C (gcc) – Try It Online")
In this 51 bytes version I tweaked a little bit the 53 bytes version (see below, former answer) thanks to && :
* At each letter `*b` I check we can find it in string a.
* If not, it means `wcschr(a,*b)` equal 0, so the program will not bother to execute the second part `&&f(a,b+1)` (that allows us to go deeper in the recursive) and so it return 0...
* ...along with `!*b` | NOT of pointer b: if we had arrived at the end of b, the pointer is NULL so we return `0|!NULL <=> 0|1 <=> 1`. If the pointer is not NULL (which means wcschr(a,\*b) previously returned NULL before string a's \0) then we return `0|!PTR <=> 0|0 <=> 0`
# [C (gcc)](https://gcc.gnu.org/), 53 bytes
```
f(a,b)int*a,*b;{return*b&&wcschr(a,*b)?f(a,b+1):!*b;}
```
[Try it online!](https://tio.run/##jVGxTsMwEJ2brziCqJzUjRIYQKQFISSmbNAJqspxHGoppMh2YKgihYVv6NZf7B@ES9JChBgYfHe@99757szHz5zXdUoYjR2ZG5dRNw7XSphC5W48HL5zzZeKNGnnuqWNAufyCEllrY0quAEjtIG1NUA5oB4Q6y5K6CIzoVW2FP04h2nDW0c2i3kiUptCZKPnMcMwKOkBawH0wekZhv4eaLM94qHCdzH/p0IP6yl2202F5wPPZwv/SvyLt9tW1f6xMrSOZc6zIhEwyVacZcJbXllWM/wLkzl5W8nEaWbWwnQ4iW4XN1FEwRb5YnbvzR7uxhe2gxtLVwpIo5S4Jj9EN4HzEEYj2VYYvCoEU2KfZJpCZxKYTtE@5dhPt2I591gvjntx9xsUUvI31WmaKK2y/gI "C (gcc) – Try It Online")
This is a recursive function
* `wcschr(a,*b)` looks for unicode character \*b in string a, return NULL character is not found, else pointer to the character (!=NULL).
* We keep looking if 1/ we are not at the end of string b `(*b!=NULL)` and 2/ while we keep finding our char \*b in string a.
* If both conditions are true we inspect our next character in string b `f(a,b+1)`
* if not we return NOT of the pointer to \*b : if we had arrived at the end of b then \*b is NULL and our function return true, if not it means that wcschr failed before reaching end of string b.
NB: wcschr is the builtin function equivalent of strchr (man strchr)
```
#include <wchar.h>
#ifndef WCSCHR
# define WCSCHR __wcschr
#endif
/* Find the first occurrence of WC in WCS. */
wchar_t *
WCSCHR (const wchar_t *wcs, const wchar_t wc)
{
do
if (*wcs == wc)
return (wchar_t *) wcs;
while (*wcs++ != L'\0');
return NULL;
}
libc_hidden_def (__wcschr)
weak_alias (__wcschr, wcschr)
libc_hidden_weak (wcschr)
```
[Answer]
# Whispers v1, ~~50~~ 43 bytes
```
> Input
> Input
>> {2}
>> 3⊆1
>> Output 4
```
[Try it online!](https://tio.run/##K8/ILC5ILSr@/99OwTOvoLSEC07bKVQb1YIo40ddbYYghn9pCVBGweT//w/zZzQAcSMQt3Ehcz7Mb2gAAA)
**Squeezed pseudo code**:
```
>> Output ( Set(Input2) ⊆ Input 1)
```
**Explanation**:
As always in Whispers, we execute the last line first:
```
>> Output 4
```
Outputs the result of line 4:
```
>> 3⊆1
```
Returns a Boolean representing the result of line 3 being a subset of the result of line 1. Let's evaluate line 1 first:
```
>> Input
```
Takes the first line of the input.
Now line 3:
```
>> {2}
```
This line forms the set of the result of line 2, which takes the next line of input.
So we get the squashed pseudocode:
```
>> Output ( Set(Input2) ⊆ Input 1)
```
[Answer]
# x86-16 machine code, 14 bytes
```
00000000: 85c9 ac57 518b caf2 ae59 5fe1 f5c3 ...WQ....Y_...
```
**Listing:**
```
85 C9 TEST CX, CX ; check for empty string
S_LOOP:
AC LODSB ; next char in string 2
57 PUSH DI ; save first string pointer
51 PUSH CX ; save first string length
8B CA MOV CX, DX ; put first string length into scan counter
F2 AE REPNZ SCASB ; compare string 2 char to each in string 1 until match
59 POP CX ; restore first string length
5F POP DI ; restore first string pointer
E1 F5 LOOPZ S_LOOP ; loop until end of second string OR no matches
C3 RET ; return to caller
```
Callable function - input string 1 at `[DI]` length in `DX`, string 2 at `[SI]` length in `CX`. Output `ZF` if Truthy, `NZ` if Falsy.
*Programming note*: if input string 2 is empty, it will (harmlessly) loop 65,535 times in order to correctly return `ZF`. This is because `LOOPcc` decrements before testing for 0 so it must wrap around the 16-bit counter register before reaching 0 again. Otherwise a `JZ` or `JCXZ` after the `TEST` would eliminate this at a cost of +2 bytes, but hey, this is Code Golf not Efficiency Golf.
**Tests:**
[](http://twt86.co/?c=uj4BtArNIbQCsgrNIbpyAbQKzSG0ArIKzSEzyTPSvkABv3QBig5zAYoWPwGH/uiAALqrAXUDuqYBtAnNIcMyAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFRydWUkRmFsc2UkhcmsV1GLyvKuWV/h9cM=)
[Try it online!](http://twt86.co/?c=uj4BtArNIbQCsgrNIbpyAbQKzSG0ArIKzSEzyTPSvkABv3QBig5zAYoWPwGH/uiAALqrAXUDuqYBtAnNIcMyAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFRydWUkRmFsc2UkhcmsV1GLyvKuWV/h9cM=)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 5 bytes
```
⬤η№θι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMxJ0cjQ0fBOb8UyCnUUcjU1NS0/v8/MSk5JTWNKy0xOTXlv25ZDgA "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for true, nothing for false. Explanation:
```
⬤ All of
η Second string
‚Ññ Count (is non-zero) in
θ First string of
ι Character of second string
Implicitly print
```
[Answer]
# [Zsh](https://www.zsh.org/), 35 bytes
```
a=(${(s::)1})
((!${#${(s::)2}:|a}))
```
[Try it online!](https://tio.run/##TYrBCsIwEETv@xUjhnZzKLT1VvDqF3gWNjUhhWLB1EOt@fZYWwX3MPN4s8/gk2M9Jzmymjk0ja6iJuadmvdfUcfmJVHrFMkNdwgMmAAx7dU6AEuaVjaD9Rao6gP9YDN/DzlyQl6iyC688KdWU2S8rihJU@fgoATK0OjtDbb1A873x@gnsn2wmzhJHyZyXXoD "Zsh – Try It Online")
```
${(s::)2} # split second parameter into characters
${ :|a} # remove all elements of $a
${# } # count
((! )) # return truthy if 0, falsy if non-zero
```
[Answer]
# [Perl 5](https://www.perl.org/), 53 bytes
```
sub{local$_=pop;eval"y/@{[quotemeta pop]}//d";!y///c}
```
[Try it online!](https://tio.run/##RczbCoMwDAbge58iC0IVLJ0bu1nR@R5OpGoLg3qYh4GIz@6qc5ibkO9P0shW35ZyBFtBsHRDNuk6F9pOg6ZuuPwIjSOLpvg91L0sZS/AeDIzViA/jYyxfF64peoWHAtMxURkeSEV8YCYluWCJN6RrCyyzr9cD17tmPbb/cvBdGO6igvTpk37qnqHoAkiO43PiVlAEFUBf/J/REMwYCsaOkZdeAD27SAR7oBK6E6iB/is0OXWvHwB "Perl 5 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
fƑ@
```
[Try it online!](https://tio.run/##y0rNyan8/z/t2ESH/9aPGubqWD9q3AlkzFHQtVMA8q0PL@c6vFz/UdOayP//o7milRKTklNS05R0lIBkUnKiUqwORBAoAiQNjYwhIkAuXAqiHqQmlisWAA "Jelly – Try It Online")
A dyadic link taking two strings and returning a Boolean. If the order of the input s can be reversed, I could save one byte.
Works by checking whether the second string is unchanged when filtering to just the characters in the first.
[Answer]
# [Haskell](https://www.haskell.org/), 24 bytes
```
f a b=all(\c->elem c a)b
```
[Try it online!](https://tio.run/##LYtBDkAwFET3TjH5sSBhgXVdBIvfaqPxK4L7V6M2LzMvMxvfuxWJ0YGhFYtUs2lHKzbAgGsdA/sDCufljwclJgdibVbrCJSoDVODLOlj1w/ZpJpDHv@vpYgv "Haskell – Try It Online")
] |
[Question]
[
Your challenge today is to take an array, split it into chunks, and add those chunks.
Here's how this works: Your program or function will be given an array of integers `a` and a chunk size `L`. The array should be split into arrays of size `L`, if the array length is not divisible by `L` then the array should have 0's appended to it so that it is evenly divisible. Once the array is chunked, all chunks are to be added together element-wise. The resulting array is then output.
You can assume `L` is greater than 0, and that `a` is nonempty. You cannot make the assumption that `a`'s contents are positive.
Here's an example:
```
[1,2,3,4,5,6,7,8], 3 => [1,2,3]+[4,5,6]+[7,8,0] => [1+4+7,2+5+8,3+6+0] => [12,15,9]
```
Test cases:
```
Array Length Output
[1] 1 [1]
[1] 3 [1,0,0]
[0] 3 [0,0,0]
[1,2] 3 [1,2,0]
[1,2] 1 [3]
[-1,1] 2 [-1,1]
[-7,4,-12,1,5,-3,12,0,14,-2] 4 [12,-1,0,1]
[1,2,3,4,5,6,7,8,9] 3 [12,15,18]
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), fewest bytes wins!
[Answer]
# [Python 3](https://docs.python.org/3/), 67 65 42 bytes
Uses the fact that the sum of an empty array is 0
```
lambda x,y:[sum(x[i::y])for i in range(y)]
```
[Try it online!](https://tio.run/##TU/bDoIwFHuWr1h8YklJtoE3kvkjczETQUkUDWAiX49nw9vL0nZtT3of@vOtScdK78aLux6Ojj0x5KZ7XOOnqfN8sLy6taxmdcNa15zKeOB27Muu3xeuKzummTFGWkjQaxFwShgCInARuPhyCfV2qH@F8mlgiQRVKEwgKCtkSKQizwJJCkICkiSKZVSk6NMrnzJqz8i5xAprbKZjFF5Arq21UeQHORxQ@FG/KXk0u7d108f8A7xprrdzVB7yrz5RrQs@vgA)
[Answer]
# [MATL](https://github.com/lmendo/MATL), 4 bytes
```
e!Xs
```
[Try it online!](https://tio.run/##y00syfn/P1Uxovj//2hdcx0THV1DIx1DHVMdXWMdIMtAxxAoZBTLZQIA "MATL – Try It Online")
First bit of MATL code I've written! Takes two inputs, `a` as a row vector (comma-separated) and `l` as a number. Works out to be
```
e # reshape `a` into `l` rows (auto pads with 0)
! # transpose
Xs # sum down the columns
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~7~~ 6 bytes
1 byte thanks to Dennis.
```
;0$¬°sS
```
[Try it online!](https://tio.run/##y0rNyan8/9/aQOXQwuLg////RxvG/jcGAA "Jelly – Try It Online")
[Answer]
# Mathematica, 27 bytes
~~*Mathematica almost had a builtin for this*~~
```
Total@Partition[##,#2,1,0]&
```
[Try it on Wolfram Sandbox](https://sandbox.open.wolframcloud.com)
### Usage
```
Total@Partition[##,#2,1,0]&[{-7, 4, -12, 1, 5, -3, 12, 0, 14, -2}, 4]
```
>
> `{12, -1, 0, 1}`
>
>
>
### Explanation
```
Total@Partition[##,#2,1,0]&
Partition[##,#2,1,0] (* Partition the first input into sublists of length
second input, using offset second input, and
right-pad zeroes for incomplete partitions *)
Total@ (* Add all *)
```
[Answer]
# [Python 2](https://docs.python.org/2/), 49 bytes
```
lambda x,n:map(sum,zip(*zip(*[iter(x+n*[0])]*n)))
```
[Try it online!](https://tio.run/##TU9dj4IwEHyWX9H4RLkhaQueH0n9I7W5VIRIIpVATdQ/z@0VvbuXzczszGy2f4Tz1aup0Yfp4rrjybE7/K5zfTreOjzbPs3iMG2oh/T@4TMjLLeZ55xPoR7DV@XGemSaGWOkhQRNi4gLwhAQkYvIxS@XUC@H@q9Qvogsl6AKhRlEZY0SuVTkWSEvQEhAkkSxkooULX@Udxm1l@T8xBobbOdjFF5Bbqy1SdJcB@ZwRMVaz/5e2SWLfmh9iLul3i/RpAT5W56Z1hWbvgE "Python 2 – Try It Online")
[Answer]
# JavaScript (ES6), 51 bytes
```
a=>n=>a.map((v,i)=>o[i%n]+=v,o=Array(n).fill(0))&&o
```
Takes input in currying syntax: `f([1,2])(3)`.
## Test Cases
```
let f=
a=>n=>a.map((v,i)=>o[i%n]+=v,o=Array(n).fill(0))&&o
;[[[1], 1], [[1], 3], [[0], 3], [[1,2], 3], [[1,2], 1], [[-1,1], 2], [[-7,4,-12,1,5,-3,12,0,14,-2], 4], [[1,2,3,4,5,6,7,8,9], 3]]
.forEach(([A,N])=>console.log(`${JSON.stringify(A)}, ${N} -> ${f(A)(N)}`))
```
```
.as-console-wrapper{max-height:100%!important}
```
[Answer]
# Mathematica, 58 bytes
```
Total@Partition[PadRight[#,(s=Length@#)+Mod[-s,#2]],{#2}]&
```
**Input**
>
> [{1},3]
>
>
>
**Output**
>
> {1,0,0}
>
>
>
[Answer]
## Java 7, 86 bytes
No fancy folds or matrices, just a good ol' fashioned `for` loop :)
```
int[]o(int[]a,int l){int i=0,o[]=new int[l];for(;i<a.length;)o[i%l]+=a[i++];return o;}
```
[Try it on Ideone](https://ideone.com/j3MjBh)
Lined:
```
int[]o(int[]a,int l){
int i=0,
o[]=new int[l];
for(;i<a.length;)
o[i%l]+=a[i++];
return o;
}
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 9 bytes
```
S↑ȯ¡¬Fż+C
```
[Try it online!](https://tio.run/##yygtzv7/P/hR28QT6w8tPLTG7egebef///@b/I/WNdcx0dE1NNIx1DHV0TXWAbIMdAyBQkaxAA "Husk – Try It Online")
### Explanation
```
C Cut into lists of length n
Fż+ Sum them element-wise
ȯ¡¬ Append infinitely many 0s
S‚Üë Take the first n elements
```
[Answer]
# [Perl 6](https://perl6.org), 36 bytes
```
{[Z+] flat(@^a,0 xx$^b*2).rotor($b)}
```
[Test it](https://tio.run/##jZFPb4JAEMXv@ynmoAV0WFkQtRINPfTmoYemhxJNUNeWBIGwa0Nj/Ox0EWMhTY172Oyf38ubeZPxPB6VB8Hha0Q3HnnJ030kOI0S3TWo/OTJ9MiLSJ7I/hseNumWw6w8Bu/9JeziUOr@KkQLiqKzWvdsg@apTHO9szZOpeJ9yYWEGcRRwoVu0H2YTaFHn9@eFh6pPF/Vv0eyOEygf4Y9skvzi86cg@6H2InR50XGN5JvDTgSgEiYW86z@BuqemrGoItISIQrWt8VLbI8SuQONB26jiVQ7QIMAJjNoctcoVUQgB/STGVBxWEtpD7QQBugpuH0w6j/VRk1dzX4B/fIqQwY2ujgEF0c4RgnS4T2cq4PAbORufi4JAH7g7UXa4juwJseaKGlJNb9EusiUZ3cFLVc7LskjT4chZsMb7Zi/@JnVCnGKlqzCk4FbDqoThYy9XTxHbbSNavuWV1Xcygqc7w9FDZZ/gA "Perl 6 – Try It Online")
## Expanded:
```
{ # bare block lambda with 2 placeholder parameters ÔΩ¢@aÔΩ£, ÔΩ¢$bÔΩ£
[Z+]
flat(
@^a, # declare and use the first parameter
0 xx $^b * 2 # 0 list repeated 2 * the second parameter
)
.rotor($b) # split into chunks that are the size of the second param
}
```
```
[1,2], 3
( [1,2], (0,0,0,0,0,0) ) # @^a,0 xx$^b*2
(1,2,0,0,0,0,0,0) # flat(…)
( (1,2,0), (0,0,0) ) # .rotor($b) # (drops partial lists)
(1,2,0) # [Z+]
```
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 8 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn)
```
+˝↑˙⊸⋈⊸⥊
```
[Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgICvLneKGkcuZ4oq44ouI4oq44qWKIAojRiDihpAgeyvLneKGkeKAv/CdlanipYrwnZWofQoK4oCiU2hvdyAxIEYg4p+oMeKfqQrigKJTaG93IDMgRiDin6gx4p+pCuKAolNob3cgMyBGIOKfqDDin6kK4oCiU2hvdyAzIEYg4p+oMSwy4p+pCuKAolNob3cgMSBGIOKfqDEsMuKfqQrigKJTaG93IDIgRiDin6gtMSwx4p+pCuKAolNob3cgNCBGIOKfqC03LDQsLTEyLDEsNSwtMywxMiwwLDE0LC0y4p+pCuKAolNob3cgMyBGIOKfqDEsMiwzLDQsNSw2LDcsOCw54p+p)
`{+Àù‚Üë‚Äøùï©‚•äùï®}` is 1 longer. BQN's reshape is very good.
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 22 bytes
Takes `l` as left argument and `a` a right argument.
```
{+⌿s⍴⍵↑⍨×/s←⍺,⍨⌈⍺÷⍨≢⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///3zEl5VHbhGrtRz37ix/1bnnUu/VR28RHvSsOT9cvBko86t2lA@Q96ukAsg5vBzE7FwEV1f7//6hvqlewv5@CoQLQDAUoTz3aMFadCyZlTLSUAR5dOkZIkob4JI1QJXUNdZCtNEGTNdcx0dE1NNIx1DHV0TXWAbIMdAyBQkZ43aJjDNRmqmOmY65joWMZqw4A "APL (Dyalog Unicode) – Try It Online")
`{`…`}` anonymous function where `⍺` is the left argument (`l`) and `⍵` the right argument (`a`).
 `≢⍵` tally (length) of `a`
 `⍺÷⍨` divide by `l`
‚ÄÉ`‚åà`‚ÄÉceiling (round up)
‚ÄÉ`‚ç∫,‚ç®`‚ÄÉappend `l`
‚ÄÉ`s‚Üê`‚ÄÉstore in `s` (for **s**hape)
‚ÄÉ`√ó/`‚ÄÉproduct of that (i.e. how many integers are needed)
 `⍵↑⍨` take that many integers from `a` (padding with zeros)
 `s⍴` **r**eshape to shape `s` (rows, columns)
‚ÄÉ`+‚åø`‚ÄÉcolumnar sums
[Answer]
# [Haskell](https://www.haskell.org/), ~~59~~ 49 bytes
```
a%l=[sum$map((0:a)!!)[i,l+i..length a]|i<-[1..l]]
```
[Try it online!](https://tio.run/##rZHBTsMwDIbveQpPWqVNOFOctGwgduCOxANUOURiYhFpqbr2gIBnL2YD2nFIN2k5Wcn3x7/9b93uZRNC17kkrPNdW0wLV81m6tbNJ5N57jFc@cUibMrnZgvOfvg7mRNfWNsVzpewhqdXAVXtywamkJOFyEmAzmDNgFVnsITaXood@pWEEcsJ6CG7xBQlaSTMUBrkSiHx1b5dAumxBzSMZ3iNS1zhjf3vV7xLcV/X7i2yg4dDRACPbVO1jRhZL9BvweAobHqY51AsUKcK1I8gvumjDvoUQe/fMBzPBvQfvAfFSD6Q9m40Y99vB0eRoIYj8L8Z0soK@dl9AQ "Haskell – Try It Online")
[Answer]
# [Perl 6](https://perl6.org), 40 bytes
```
{[Z+] (|@^a,|(0 xx*)).rotor($^l)[0..@a]}
```
[Try it online!](https://tio.run/##ZY3NDoIwEITvPEUTObQ6kG7LnyEmPIcEEg56wmDQA0Z89rqIgRizl535Znavp75N3OUh/LM4CPcsj7tKyLGoG4xSi2HYKhX23b3rpV@3qtRhWDTVy@Wed2umlpQaCsKqXGwE7zxqQQSzMhb/jGZmsYKAQEzMTD5qZSkiBGRAiBFY8KZBbPGt6PvGcGByf17BcjFGghQZ9gp2CVMMypR7Aw "Perl 6 – Try It Online")
If you like the number 42, you can swap the `*` for an `∞`. That will make it 42 bytes :—).
**Explanation**:
```
{[Z+] (|@^a,|(0 xx*)).rotor($^l)[0..@a]} The whole function
{ } Anonymous block
( , ) List with 2 elements
@^a The first argument (it is a list)
(0 xx*) Infinite list of zeroes
| | Flatten both of the lists into the larger list.
.rotor($^l) Split the list into a list of lists, each (the second argument) long.
[0..@a] Only the first (1 + length of the first argument) of them.
[Z+] Add the corresponding elements up.
```
The magic behind the last "add up" is that the operator is a "reduce with zip with +". By the way, this would break down if we used it only on a list with 1 list inside, but that never happens if the original list was non-empty (due to the second-to-last row). Also note that we end up taking not only `@a`, but `@a * $l` items. Fortunately we added only zeroes which won't affect the final result.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 8 bytes
```
m+F%Q>vz
```
**[Try it here!](https://pyth.herokuapp.com/?code=m%2BF%25Q%3Evz&test_suite=1&test_suite_input=1%0A%5B%5D%0A%0A1%0A%5B1%5D%0A%0A3%0A%5B1%5D%0A%0A3%0A%5B0%5D%0A%0A3%0A%5B1%2C2%5D%0A%0A1%0A%5B1%2C2%5D%0A%0A2%0A%5B-1%2C1%5D%0A%0A4%0A%5B-7%2C4%2C-12%2C1%2C5%2C-3%2C12%2C0%2C14%2C-2%5D%0A%0A3%0A%5B1%2C2%2C3%2C4%2C5%2C6%2C7%2C8%2C9%5D%0A&debug=0&input_size=3)**
# [Pyth](https://github.com/isaacg1/pyth), 10 bytes
```
sMCc.[EZQQ
```
**[Try it here!](https://pyth.herokuapp.com/?code=sMCc.%5BEZQQ&input=3%0A%5B1%2C2%2C3%2C4%2C5%2C6%2C7%2C8%2C9%2C10%5D&test_suite=1&test_suite_input=1%0A%5B%5D%0A%0A1%0A%5B1%5D%0A%0A3%0A%5B1%5D%0A%0A3%0A%5B0%5D%0A%0A3%0A%5B1%2C2%5D%0A%0A1%0A%5B1%2C2%5D%0A%0A2%0A%5B-1%2C1%5D%0A%0A4%0A%5B-7%2C4%2C-12%2C1%2C5%2C-3%2C12%2C0%2C14%2C-2%5D%0A%0A3%0A%5B1%2C2%2C3%2C4%2C5%2C6%2C7%2C8%2C9%5D%0A&debug=0&input_size=3)**
# Explanation
### Explanation #1
```
m+F%Q>vz Full program. Q means input.
m Map over the implicit range [0, input_1), with a variable d.
>vz All the elements of input_2 after d; input_2[d:] in Python.
%Q Every Qth element of ^.
+F Sum. Implicitly output the result.
```
### Explanation #2
```
sMCc.[EZQQ Full program.
.[E Pad the second input to the right, with repeated copies of...
Z ... Zero (0), up to the nearest multiple of...
Q ... The first input.
c Q Chop into chunks of length equal to the first input.
C Matrix transpose. Get all the columns of the nested list.
sM Sum each.
Output (implicitly).
```
[Answer]
# [J](http://jsoftware.com/), ~~15~~ 12 bytes
```
]{.+/@(]\~-)
```
[Try it online!](https://tio.run/##y/qfVqxga6VgoADE/2Or9bT1HTRiY@p0Nf9rcinpKain2VqpK@go1FoppBVzcaUmZ@QrGCpoRFvHWqdpKhiiCxhDBAzQBQwVjPAJQc2JN0QyyggqZq5gApQwAsqYKsQbKwBZBgqGQCGEbhOEgcZAxaYKZgrmChYKlggb/wMA "J – Try It Online")
## Explanation
```
]{.+/@(]\~-) Input: array A (LHS), chunk size L (RHS)
- Negate L
]\~ Take each non-overlapping sublist of size L in A
+/@ Reduce the columns by addition
] Get L
{. Take that many, filling with 0's
```
[Answer]
# [R](https://www.r-project.org/), ~~62~~ 57 bytes
*-5 bytes thanks to user2390246*
```
function(a,l)rowSums(matrix(c(a,rep(0,l-sum(a|1)%%l)),l))
```
[Try it online!](https://tio.run/##HcpBCsIwEEbhvadwOSN/wGkrYmlP4QEkFCOFToJJgy68e0y7e3y8WNxxMMVlP61z8GSxcAyfe9ZEpKPaNc7fXflE6fl@2CX4FykPY8pK9ifMXBxJf0PLB0cTmSs6GGkguMC0qHWGVGoY3bZIPcsf "R – Try It Online")
Updated since it no longer has to handle the empty case.
pads `a` with zeros, constructs a matrix of `l` rows, and computes and returns the row sums.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
ô0ζO²Å0+
```
[Try it online!](https://tio.run/##MzBNTDJM/f//8BaDc9v8D2063Gqg/f9/tKGOglEslzEA "05AB1E – Try It Online")
```
ô0ζO²Å0+ Full program
ô Push <1st input> split into a list of <2nd input> pieces
0ζ Zip sublists with 0 as a filler
O Sum each sublist
--- from here, the program handles outputs shorter
than the required length
²Å0 Push a list of zeros of length <2nd input>
+ Sum the result with that list
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
Å0+¹ô0ζO
```
[Try it online!](https://tio.run/##MzBNTDJM/f//cKuB9qGdh7cYnNvm//@/MVe0oY6RjrGOiY6pjpmOuY6FjmUsAA "05AB1E – Try It Online")
```
√Ö0 # Push an arrary of all 0s with length l
+ # Add that to the array
¹ô # Split into chunks of length l
0ζ # Zip, padding with 0s
O # Sum each chunk
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes
```
ẇR∆ZR∩Ṡ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuodS4oiGWlLiiKnhuaAiLCIiLCI0XG5bLTcsNCwtMTIsMSw1LC0zLDEyLDAsMTQsLTJdIl0=)
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), 14 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
l⁵%⁵κ{0+}nI⌡∑¹
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=bCV1MjA3NSUyNSV1MjA3NSV1MDNCQSU3QjArJTdEbkkldTIzMjEldTIyMTElQjlGJTBBLiUyQyV1MjE5MkY_,inputs=NCUwQSU1Qi03JTJDNCUyQy0xMiUyQzElMkM1JTJDLTMlMkMxMiUyQzAlMkMxNCUyQy0yJTVE) or [Try all the test-cases.](https://dzaima.github.io/SOGLOnline/?code=bCV1MjA3NSUyNSV1MjA3NSV1MDNCQSU3QjArJTdEbkkldTIzMjEldTIyMTElQjlGJTBBaW5wdXRzLnZhbHVlJXUyMDFEJXUyMTkyJUI2JXUwMzk4JTdCJXUwM0I4X3IlM0IldTIxOTJGQCV1MjIxMVA_,inputs=JTVCMSU1RCUyMDElMEElNUIxJTVEJTIwMyUwQSU1QjAlNUQlMjAzJTBBJTVCMSUyQzIlNUQlMjAzJTBBJTVCMSUyQzIlNUQlMjAxJTBBJTVCLTElMkMxJTVEJTIwMiUwQSU1Qi03JTJDNCUyQy0xMiUyQzElMkM1JTJDLTMlMkMxMiUyQzAlMkMxNCUyQy0yJTVEJTIwNCUwQSU1QjElMkMyJTJDMyUyQzQlMkM1JTJDNiUyQzclMkM4JTJDOSU1RCUyMDM_) this is written as an unnamed function and expects `chunk length; array` on the stack.
Explanation:
```
padding zeroes
l get the array's length
⁵% modulo the chunk length
⁵κ chunk length - result of above
{ } that many times
0+ append a 0 to the array
adding the array together
n split into the chunks
I rotate clockwise
‚å° for each
‚àë sum
¬π wrap the results in an array
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes
```
gs÷*+Å0¹+ôøO
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/vfjwdi3tw60Gh3ZqH95yeIf////RuuY6Jjq6hkY6hjqmOrrGOkCWgY4hUMgolssEAA "05AB1E – Try It Online")
### Explanation
```
gs÷*+Å0¹+ôøO
g # Get the length of the first input (the array)
s # Push the second input on top of the result
√∑ # integer divide the two values
* # Multiply with the second input (the length)...
+ # and add the second input to the result
√Ö0 # Create a list of zeros with that length
¬π+ # Add it to the first input
ô # And finally split it into chunks of the input length...
√∏ # ...transpose it...
O # and sum each resulting subarray
# Implicit print
```
[Answer]
## Mathematica, 43 bytes
```
Plus@@#~ArrayReshape~{‚åàTr[1^#]/#2‚åâ,#2}&
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 10 bytes
```
Fż+So:`R0C
```
[Try it online!](https://tio.run/##yygtzv7/3@3oHu3gfKuEIAPn////G/@PNtQx0jHWMdEx1THTMdex0LGMBQA "Husk – Try It Online")
### Ungolfed/Explanation
```
-- implicit inputs n & xs | 3 [1,2,3,4]
S C -- cut xs into sublists of length n & ... | [[1,2,3], [4]]
(:`R0) -- ... prepend [0,...,0] (length n) | [[0,0,0], [1,2,3], [4]]
F -- accumulate the sublists with |
ż+ -- element-wise addition | [0+1+4, 0+2, 0+3]
```
[Answer]
# [Clojure](https://clojure.org/), 42 bytes
```
#(apply map +(partition %2 %2(repeat 0)%))
```
[Try it online!](https://tio.run/##VYxBCsMgFET3OcVACfxPEaImTe8SspBWwWLNR8yipzduC7N4PB7zSsfnLL7R2weEdiMnkn74OsGdxJUaazwyRtNHxYt3FROPzI2HgaTEXFMGBWxqxQylDTQWKItOE3RXZsfM/B9rGNjeL3hgxXOH7Y8X "Clojure – Try It Online")
[Answer]
# [Jq 1.5](https://stedolan.github.io/jq/), 31 bytes
```
[_nwise($n)]|transpose|map(add)
```
Sample Run
```
$ jq -Mc --argjson n 3 '[_nwise($n)]|transpose|map(add)' <<< "[1,2,3,4,5,6,7,8]"
[12,15,9]
```
Takes advantage of builtins: [\_nwise](https://github.com/stedolan/jq/blob/master/src/builtin.jq#L100), [transpose](https://github.com/stedolan/jq/blob/master/src/builtin.jq#L190), [add](https://github.com/stedolan/jq/blob/master/src/builtin.jq#L11) and [map](https://github.com/stedolan/jq/blob/master/src/builtin.jq#L3)
[Answer]
# [Stacked](https://github.com/ConorOBrien-Foxx/stacked), 24 bytes
```
[:@z#<[0 z rpad]map sum]
```
[Try it online!](https://tio.run/##bY7BDoIwEETv/YpJagIkSmiLokgM/4EEG4GLITYFLvx83aImHjzN29nJ7I6Tvj@61rkqLxdeVAkWWKPbetAG4zzUrsx7FjIgFJBQSLHHARmOEdTqfjT5zpC/JDw1AhSTK2bU0AgJQT2NAlECQRZl0z9XcPJtEZO8YKzKEccxetjOWFyxWdV/GpwRgN/I41ui3eU9Puep9nv3Ag "Stacked – Try It Online")
## Explanation
```
[:@z#<[0 z rpad]map sum]
[ ] anonymous function
:@z stores TOS as `z` (the length)
#< cut STOS in TOS slices
[ ]map for each slice
0 z rpad pad the slice with `z` zeroes
sum] summate all inner slices
```
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 64 bytes
```
n->a->{int k=0,r[]=new int[n];for(int i:a)r[k++%n]+=i;return r;}
```
[Try it online!](https://tio.run/##vVE9b4MwEN3zK26pBMJYQNJPClKXSh2aJSNicAlEJuRAxqSKIn47PQhplmwNveXOfnfvvbNzsRd2WaWYr7dd1XwVMoGkEHUNn0IiHGczoKi10ARkEkUBOY3wRsuCZw0mWpbIP1C/j/XrFfgXk6ijmMGQwhCWEHRoh8IOj3QF28BhKooDTL@HFoz9rFRGD8kXYapoa1l3GFuB9FWqG4Wg/Lbr/fknm6P/0e2@lGvY0RbGSiuJmygGoTa1SUvBGKtDrdMdLxvNK2rRBRoX@29KiUPNdXkaN5ZcVFVxMFxzLM4@Yzi6rWma/t945//I60zll4F3A2p3OmrvCrVN3Ld46cU17kcGCwa265EGg3sq51TRyaHUI96Ef8FgPsiT7AMDsvLE4Pmi187a7gc "Java (OpenJDK 8) – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt/), 7 bytes
Man, I fought with the wrong Japt method for far too long trying to get it to work for the `[1], 3` test case in a reasonable amount of bytes!
```
VÆëVX x
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=VsbrVlggeA==&input=Wy03LDQsLTEyLDEsNSwtMywxMiwwLDE0LC0yXQo0Ci1R)
---
## Explanation
Implicit input of array `U` and integer `V`.
```
VÆ
```
Generate an array of integers from `0` to `V-1` and pass each through a function with `X` being the current element.
```
ëVX
```
Grab every `V`th element of `U`, beginning at index `X`.
```
x
```
Reduce that array by addition.
[Answer]
# C, (GCC) 101 86 Bytes
[Try it online!](https://tio.run/##PY7LasMwEEXX9VcMhgQ9RtDWaWtQ/CXGC@HGyYBkFysQiNG3O2Ol7eYgHc0d3d6c@35dB0HjVTlkgs@MG1WQCw0iMllR4@3tQv4kaL9nF1pvyJhON8ppbaMxNg3CoceIQdqU1i0VHI1CwlIAQF4PDVT27@baumOxvOE7VnjAD/zEL6zT/4AK/CzySQbn/dSLSPfTlBtLUOBlnt0@5upQI4RfM83PIDWvFuhYMbTemrz8zOwHUe6@EUoMLXXPSCrS@gA)
```
f(int*a,int l,int s,int*m){if(s){int i=l;while(i&&s){m[l-i--]+=*a++;s--;}f(a,l,s,m);}}
```
## Usage
```
int main() {
int l = 3;
int a[8] = {1,2,3,4,5,6,7,8};
int *m = (int *)malloc(sizeof(int) * l);
f(a, l, 8, m);
for (int i=0; i<3; i++) {
printf("%d, ",m[i]);
}
}
```
Note that you have to pass in the length of the array (s) and a new dynamic array on the heap (m).
] |
[Question]
[
05AB1E has the `£` builtin which, given a list of integers `b` and a string `s`, splits `s` into sublists of lengths equal to the elements in `b`. For example, `[1,2,3,4,1] "hello world"£` produces `["h", "el", "lo ", "worl", "d"]`. Your task is to imitate this behaviour.
Given a list \$L\$ containing \$n\$ elements, and a list \$B\$ of positive integers that sum to \$n\$, emulate the behaviour of `£` in 05AB1E. \$L\$ will always contain positive digits (so `123456789`), \$n\$ will always be greater than or equal to \$1\$ and will never exceed your language's maximum integer.
If you have a builtin which mimics this *exact* behaviour, such as 05AB1E's `£`, you may not use it. Every other builtin, including ones that partition the input into slices of a given integer length are acceptable. Essentially, any command that is not a standalone answer to this challenge is acceptable.
You may take the two lists in any [convenient method](https://codegolf.meta.stackexchange.com/q/2447/66833) or format, including taking \$L\$ as an integer. You may optionally take \$n\$ as input. You may output in any format that clearly shows the sublists of \$L\$, distinct from each other. For example, outputting integers separated by newlines, or outputting a list of lists of digits.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
## Test cases
```
L, B -> output
[[4, 5, 1, 2, 6, 1, 7, 9, 6], [2, 4, 3]] -> [[4, 5], [1, 2, 6, 1], [7, 9, 6]]
[[4, 2, 8, 7, 3, 5, 9, 3, 1, 9, 1, 8, 1, 7, 2, 8, 3, 7, 6], [1, 3, 1, 14]] -> [[4], [2, 8, 7], [3], [5, 9, 3, 1, 9, 1, 8, 1, 7, 2, 8, 3, 7, 6]]
[[8, 7, 4, 6], [1, 3]] -> [[8], [7, 4, 6]]
[[7], [1]] -> [[7]]
[[6, 4, 3, 8, 9, 3, 6, 5, 7, 8, 3, 2, 5, 1, 2], [3, 3, 3, 3, 3]] -> [[6, 4, 3], [8, 9, 3], [6, 5, 7], [8, 3, 2], [5, 1, 2]]
[[2, 7, 9, 3, 8, 1, 5], [4, 3]] -> [[2, 7, 9, 3], [8, 1, 5]]
[[1, 9, 8, 9, 6, 3, 4, 2, 3, 4, 1, 8, 5, 5, 2, 9, 3, 6, 7], [3, 1, 2, 13]] -> [[1, 9, 8], [9], [6, 3], [4, 2, 3, 4, 1, 8, 5, 5, 2, 9, 3, 6, 7]]
[[1, 8, 7, 8, 9, 4, 2, 5, 2, 7, 1, 5, 2, 3, 8, 4, 6, 9, 1, 9, 3, 4, 6, 7, 6, 5, 3], [7, 7, 3, 8, 2]] -> [[1, 8, 7, 8, 9, 4, 2], [5, 2, 7, 1, 5, 2, 3], [8, 4, 6], [9, 1, 9, 3, 4, 6, 7, 6], [5, 3]]
[[7, 4, 4, 7, 5, 5], [1, 2, 3]] -> [[7], [4, 4], [7, 5, 5]]
[[9, 2, 8, 7, 2, 3, 9, 5, 8, 1, 5, 2], [2, 2, 2, 2, 2, 1, 1]] -> [[9, 2], [8, 7], [2, 3], [9, 5], [8, 1], [5], [2]]
[[8, 7, 3], [3]] -> [[8, 7, 3]]
[[8, 2, 7, 3, 9, 5, 6, 9, 5, 3, 1, 9, 7, 5, 3, 6, 4, 1], [2, 1, 2, 6, 2, 2, 3]] -> [[8, 2], [7], [3, 9], [5, 6, 9, 5, 3, 1], [9, 7], [5, 3], [6, 4, 1]]
[[8, 2, 3, 7, 4, 7, 7, 4, 5, 5, 8, 1, 2, 3, 3], [3, 7, 4, 1]] -> [[8, 2, 3], [7, 4, 7, 7, 4, 5, 5], [8, 1, 2, 3], [3]]
[[4, 3, 8, 9, 9, 3, 2, 5, 5, 8, 2, 8, 1, 1, 4, 1], [10, 5, 1]] -> [[4, 3, 8, 9, 9, 3, 2, 5, 5, 8], [2, 8, 1, 1, 4], [1]]
[[6, 3, 2, 9, 5, 6, 1, 4, 9, 4, 2, 5, 6, 8, 8, 5], [4, 3, 2, 1, 2, 2, 2]] -> [[6, 3, 2, 9], [5, 6, 1], [4, 9], [4], [2, 5], [6, 8], [8, 5]]
[[2, 2, 1, 6, 8, 5, 2, 6, 7, 9, 4, 5, 8, 1, 9, 6, 3, 8, 7, 3, 9, 1], [6, 7, 1, 2, 2, 2, 2]] -> [[2, 2, 1, 6, 8, 5], [2, 6, 7, 9, 4, 5, 8], [1], [9, 6], [3, 8], [7, 3], [9, 1]]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), 3 bytes
```
Rṁ@
```
[Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCJS4bmBQCIsIsOnQC/igqzFkuG5mOKCrFkiLCIiLFsiW1s0LCA1LCAxLCAyLCA2LCAxLCA3LCA5LCA2XSwgWzIsIDQsIDNdXSwgW1s0LCAyLCA4LCA3LCAzLCA1LCA5LCAzLCAxLCA5LCAxLCA4LCAxLCA3LCAyLCA4LCAzLCA3LCA2XSwgWzEsIDMsIDEsIDE0XV0sIFtbOCwgNywgNCwgNl0sIFsxLCAzXV0sIFtbN10sIFsxXV0sIFtbNiwgNCwgMywgOCwgOSwgMywgNiwgNSwgNywgOCwgMywgMiwgNSwgMSwgMl0sIFszLCAzLCAzLCAzLCAzXV0iXV0=)
Equivalently, `ṁR}` but with the arguments the other way around.
```
R Range (vectorizes)
ṁ@ Mold the right argument to the shape of the ranges
```
```
ṁ Mold the left argument to the shape of:
R} Range (vectorizes) of the right argument
```
[Answer]
# [Python 2](https://docs.python.org/2/), 39 bytes
```
lambda L,B:[map(L.pop,[0]*x)for x in B]
```
[Try it online!](https://tio.run/##VVLLbsIwELznK3yEyqqwnfiBxIUzf5DmQNWiRoIQIarSr0/tHa9xJR/W9u7M7M7Ov/ev66SX0@5tOR8v7x9HcZD7bX85zqvD63ydZb8ZXh7r0/UmHmKcxH5Yfr7G86dQ2yal7sZp/r6v1o2Yb@N0F6dVfFwvfStFJ4WSQkthKXBShBgPUvTxLf6boUlp8eLp11BJoEBRoOgLtUgzFBOI4kTVRiBAtNVffHQUx8CCkCBAYInMMaguclOJobd8Yrlm9YYFdSkt9wCtQLaUg64QoIeOjq7YXSbCiFQG8qwpMArKHFgZ16NVHlJgMovxUKZJBI4n61NrTY8ZtfTa5TagIAkIlRsgCpTmC3t2rz7JgWIAkRpcNXMDxHJQ7HV8hT0qg5el0UWYZz2OxSPoKnk624WxugxJK1aMD5XZKNRcrp4a1AbbgMUx7FvHm9z@t8cShK@WgueSZ4QNwpPlddDsVuBOPM/FsuIyPpJleQ2e0x/@AA "Python 2 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
I've tried to implement `£` manually way too often because the docs just say *`£` - Head. Push `a[0:b]`*, which is exactly what this builtin does if you just pass a single integer.
```
L˜Å¡¦
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f5/Scw62HFh5a9v9/tJmOgrmOgqGOghEcxXJFQ1hAUaC0hY6CKZgLUWqpo2ACFrEAK7AEixuDueZgBlDEMBYA "05AB1E – Try It Online")
`L` convert each length `n` into a range `[1 .. n]`
`˜` flatten into a list of integers
`Å¡` split the sequence on `1`'s (the only truthy value in 05AB1E)
`¦` remove the leading empty list that was created by splitting at index 0
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 3 bytes
-2 thanks to ovs!
```
⍸⍛⊆
```
How does it work?
Firstly `⍸2 4 3` is `1 1 2 2 2 2 3 3 3`.
We can then use this to partition (`⊆`) the right argument into chunks.
[Try it online!](https://tio.run/##jVQ9jxMxEO35Fe7S7Als79rrGukEFCARuihFTsnRnDgKChCiAkXi0EZQXEVFdx0VEvX9FP@RsJ55Y3tXnHRSFM3a4zdv3nxs3l6cbD9sLi5fn@zev9u92e62x2Mc/sbhZ7zaH0/j/nscDvHq8@1vG/c/4uF6@fLx@P/qydOlit@@qPPR4@NGnSXHw/Wz5Yvntzdx@EN3Z/Hrr/HpaRxuHm4@Hc/VYrVqG9U1SjfKNMqR4RsVRnvdqNV4Nt7b9Xohrum0OKcvcV8vHgjgeNsTjiXwQIYmQ9MVR2E3S7YDMDvqVkKCRYJLpk1/94YUSkymraIAvkcCbe1NgTQ8fD52rAUF4PCOsvMS0mQliSmd4QcwQKRrgCQTMDi1eC9QEt5IYaykS7WoylM8AEU@8p614rCOULhQbLCGHf1MlZ9HKlxyLaEAli4DUrBgcw/IilIv@gXhw96e2QtczyWScgeJ4bjQ5GlRSy8vTCE7DwOB54GgmzTK/4PhrS39Qrct3XaTEbG5iVibFhS7ujChmhfONpBHn5lhBupfmhGAB3jIiEgiAVR6zCl9mNlMWB4qTAOOKhcjejInJ0YePi@f3NsaDPKKMBMhenCVtgoQc4IL8j4LzQ3Wcso1NStz7cXoKukMZo9D@YxQvS/jP0Eo82MqifJ6yzsgVHPPYY0E10UO/YgXQ9midwKUbQcIWUV5BVkZpk7WdTsdHkfP@2o9SMOgecouAlapgcYTOpLV20H/Hqp09UpiZCejbmRKgmjZS6M4STv3kwawr9kVgnN00Jnjs0LcMg61lrUuc0AK/gM "APL (Dyalog Extended) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 6 bytes
```
</.~I.
```
[Try it online!](https://tio.run/##RYxNCoNADIX3nuLhZirEsTFT/9BVoSC46hWKIt30Br36NM0gLgLfy/t5x9y7DdMAB8IVg17pcX8ujzhW/jv7WGTra//gEgg3AhNqQmPQEnrlAhtqBMgZ1EhnvlipN2ADNiu1U0yMbYaPIIc01v6fCTsVolLiDw "J – Try It Online")
Called with the list as left arg, grouping mask as right arg.
The whole thing is a dyadic hook, so that...
* `I.` applies only to the grouping mask, and expands it in place using unique elements. Eg, `I. 2 4 3` becomes:
```
0 0 1 1 1 1 2 2 2
```
* `</.~` That mask is used to group `/.` the list itself, putting each group into a box `<`.
[Answer]
# [Python 2](https://docs.python.org/2/), 42 bytes
Inputs \$ L \$ and \$ B \$ as two comma separated lists from STDIN, and outputs sublists each on one line.
```
L,B=input()
for x in B:print L[:x];L=L[x:]
```
[Try it online!](https://tio.run/##VVK7bsMwDNz9FYKnFtBQSbYeLrJk9h8YngoXMVA4RpCi7tenEk9UVEADJZF3Rx733/vluunHz2X9WoQaxHIsH6Jt28coz6d127/vL6/N5/UmDrFu4jzst3W7i3Eajvl9PI3TMcwPemtS0dRJ0UuhpNBSWAqcFCHGsxRTfIv/Zm5SWrx4@jVUEihQFCj6Qi3SDMUEojhRdREIEF31Fx8dxTGwICQIEFgicwyqi9xUYugtn1iuWb1hQX1Kyz1AK5At5aArBOihp6MrdpeJMCKVgTxrCoyCMgdWxvVolYcUmMxiPJRpEoHjyfrUWjNhRh299rkNKEgCQuUGiAKl@cKe3atPcqAYQKQGV83cALEcFHsdX2GPyuBlaXQR5lmPY/EI@kqeznZhrC5D0ooV40NlNgo1l6unBvWGbcDiGPat503u/ttjCcJXS8FzyTPCBuHJ8jpoditwJ57nYllxGR/JsrwGz@nPfw "Python 2 – Try It Online")
[Answer]
# JavaScript (ES6), 44 bytes
Expects `(a)(b)`.
```
a=>g=([v,...b])=>v?[a.splice(0,v),...g(b)]:b
```
[Try it online!](https://tio.run/##HclNCsMgEEDhq8xyBqZD018aMD2IuFBrJEViiMXrW9vdx3tvW23x@7J9Dmt@hTarZtUUFerKIuIMqak@tZWypcUHPHKl34joyIyu@byWnIKkHHFGfWG4MgwMJ4bbH3eGR7ch1L31fzZE7Qs "JavaScript (Node.js) – Try It Online")
(or [**43 bytes**](https://tio.run/##HclNCsMgEEDhfU/hcoZMh/SfFkwPIkLUGkmQGGrw@la6@3hvMcVk9523/bimj6@TrEYOQYIqxMxWoxzK23De4uw89FSwGw9jF8Diy1aX1pyi55gCTKCuJG4kTiTOJO5/PEg8mzWCaq39i0asPw) with linefeeds)
[Answer]
# [Haskell](https://www.haskell.org/), 34 bytes
```
(zipWith take<*>).scanl(flip drop)
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P81WoyqzIDyzJEOhJDE71UbLTlOvODkxL0cjLSezQCGlKL9A839uYmaebUFRZl6JSpqCkgdQY6pCbn5OiqJStKGOsY6JjkHsfwA "Haskell – Try It Online")
`scanl(flip drop)` takes the input and sucessively drops off prefixes.
```
Prelude> scanl(flip drop) "Test string, test string, 123" [6,1,2,3]
[ "Test string, test string, 123"
, "tring, test string, 123"
, "ring, test string, 123"
, "ng, test string, 123"
, " test string, 123"
]
```
Note that the first result will always be the input string.
Once we have that we apply `zipWith take` to then take off the prefixes for each size.
[Answer]
# [R](https://www.r-project.org/) >= 4.1, ~~30~~ 29 bytes
```
\(L,B)split(L,rep(seq(!B),B))
```
[Try it online!](https://tio.run/##Hco7CoAwEITh3lOs3S5ME6MGBZvU3iIYEMRX4vnjajUfP3OXOJX47CGvx84zvKRzW7PqXk5Oy8W1F61SIgduQR3IgBpQ/8OBBrWAAmvUgxWpIjuYb8xoYaW8 "R – Try It Online")
An anonymous function taking two vectors and returning a list of vectors.
Thanks to @pajonk for saving a byte!
[Answer]
# [WolframLanguage (Mathematica)](https://www.wolfram.com/mathematica/), ~~28~~ 25 bytes
```
TakeDrop~FoldPairList~##&
```
–3 bytes from att.
[Try it online!](https://tio.run/##bVM9T8MwEN35FZYqMXnAdvw1IDEgJoYObIghgqpEpRSFbFX710Ny52fstFKGq@/uvXd3r/t2@Nzs26F7b8ft/fjS7jaP/eHn/HT4@li3Xf/c/Q7n1ep2XPfd9/CwfT02UlgplBRaCkeBlyJO8UmK4/Q25c3pTdyUDdNzoDpDzZECRYGiFKNwmaGY4BQKVVNBMlhTVFVpT6/Vk2NhRMD0jqR4UOo81txs6C19FZDGvAbC7dxwMTVPx2yOqnkPHPDUlj5dKPKJnNerLiADFEfgMYBnJWAIvBwsOILW8Wqp0sxUHlcJ8@DVDqmhobxNQ7KqWlQsrsvkkRpCVpR8UX7zRa8clCSZZUJDIwM7BNlCHj/5yCoRZovqK7ID1HoMyYEtxOt0fj6JT@ALa2dLxcJGDKEBpP51qTv22dKcBj6w@Fc19ZEdgYXCbthk2urSpZx0MJrG9SPmDNifwxR5zSTVwVa64hj/AA)
With the prohibitied built-in (introduced in 2017 with v. 11.2), it's 8 bytes:
```
TakeList
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 7 bytes
```
~cʰ\l₎ᵐ
```
[Try it online!](https://tio.run/##VVK7TsQwEPwVKwWVkbCd@NHwIyEFHIgrIkW65oQQFFcg0SA@5RoaPoG/uPuRkMx6jJFcrNfrmdmdvdvdbrZP4/Ro5@d9oy6vVbO/OL8dz4fD6fv95fT1Ob9ufo434/nwsV7mvm@2D@M4qf20G@8b3RtttdOtNsOg@77VqtPKaGW18giCVmmJB636Jbe8OxYu14h3h08JgUFg8CS/pcwhBoxhoWkBJSBt9Yp0wA2hF2IACY0HZSC0LbLXTw65fABg2YejsG4tLN2IakH3qJL@JJBuOhxbKQiZTMZlClSkskQc@RiEmchRmubAEum8jAqVbqUInHJcG8RsUNgi3@VmRIWISJU7QpZQGIuC7Gd9VkcqQ0DtmLDUIECeQbE88CpmmUxQVslW8iJVBTYhQVeJtNk@GXHIoHn1yiqkyn75aglg/nSYK9kPLpOjjx23vP1vlgdIrNaEE8rT4lZJ0nNBLN1L7CdyPp6qyxghzXMtbIU9/AI "Brachylog – Try It Online")
`~cʰ` split the left argument into groups, `\` transpose so we have a list of (group, length), `l₎ᵐ` map each pair: the right element is the length of the left element (which is also the output of `l`).
[Answer]
# [Haskell](https://www.haskell.org/), ~~35~~ 34 bytes
```
x?(c:d)=take c x:drop c x?d
x?_=[]
```
[Try it online!](https://tio.run/##bY5BCoMwEEX3nuITulCIC7WtNCBZd9UDhFDECIqpESvU26dJisVCZzH5A/PepKufQ6u1tSuPG6aSaqmHFg1WpmYz@cBVtPJ7JaR91P0IxnC9IU6iMFVQJgKmuR8XHEA65zJ4mVkrAg6RUeQUBcWRIpP4VppCkI5Q0mrXHOK6p9yjiNwZhQNPjg2ecwglxcVl6f15MBfyYwzLkm5n/bqfNuDHWwZ@/6f/FbyllPYN "Haskell – Try It Online")
-1, thanks Wheat Wizard!
[Answer]
# [Factor](https://factorcode.org/), 24 bytes
```
[ [ cut swap ] map nip ]
```
[Try it online!](https://tio.run/##lVbJbhsxDL37K9gPiFFJoy0Fcg166SXIyejBGEzRoI3jeiYoCsPf7mookdoSoE0GDmWRfI/r5Nt@XF5O18eHz1/ub2Gefr1Oh3Ga4cd0Okw/YT/PL@MMx9O0LH@Op6fDAp82m/MGws85/A4AGkAASACDggXwq3xZFcK3QUOFwwU@wM1dtsHrwg7P2fZSIgQdh44VonkUBAoCryJsVFMoGwaIqmJoORA/9IwHFf/8B0JmGfkNNXCF6DjEoTW2ZFMZ2ErHpEyuSJGewWRYoiRzJVI05VN5NlyVyNzzgXzSjWJ32XfmJKnainKU6trXvFAl30k9u4v5dqkHVqex9lGIddD4yCIHXLzUTaJBJq@o5TlMxUz/CaFi6SjtnihGC5uCSi5dKnXqIk84JvXPqqm4KyzZyI5/h0cV6TApt7kR38EmD6ppxFVnQB3dTKnquzPmb@AQdFtRX8xuzIlHLZdJ0xiWj4B2Fjyr5nHNAXum6niVaFLqp1Tlca/mk@4qfUmVicwNCbwfLB1NaiIix8tNvpU/xxHlBvZclhqGgrRV2XiQxRucFe0jS4IuMi95K0Rgm/00DIsG7ZwVgyzrrJbLm1eWL9aUTp2ezEWZOvExbbL2pfG@p2KXk7e8UcsVqmiyNb2uhnqKDTpx9SbL1ZTdeBZOi@IJtvYkEUfNpXOcQd2u1QhoaCFJGlxP2XfUfobywl0qGMBWtFvmHQwx7KA4l7ENDfdNfqepYtussVyuO9jB@LrA/Ht/hK/wHD4PT0G6noMC/ltxt363g@12G@6n/fj9@hc "Factor – Try It Online")
Mapping the lengths to the part of the input that gets 'cut off.' Cutting a sequence into two parts and getting at the results is efficient in bytes because both pieces just end up on the data stack, instead of locked away inside some collection. Process looks something like this:
1. `"hello world" { 1 2 3 4 1 }`
2. `"ello world" { "h" 2 3 4 1 }`
3. `"lo world" { "h" "el" 3 4 1 }`
4. `"world" { "h" "el" "lo " 4 1 }`
5. `"d" { "h" "el" "lo " "worl" 1 }`
6. `"" { "h" "el" "lo " "worl" "d" }`
7. `{ "h" "el" "lo " "worl" "d" }`
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-m`](https://codegolf.meta.stackexchange.com/a/14339/), 3 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Takes `B` as the first input.
```
VvU
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW0&code=VnZV&input=WzIsIDQsIDNdCls0LCA1LCAxLCAyLCA2LCAxLCA3LCA5LCA2XQotUQ)
```
VvU :Implicit map of each U in first input (B)
V :Second input (L)
vU :Remove and return the first U elements
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 8 bytes
```
{.=x!&y}
```
[Try it online!](https://ngn.bitbucket.io/k#eJx9VF1rGzEQfPevUCGUHIgQSSfp5KH/Im8hkL4YSguBPNmE9Ld3dlZ2nZaWA/lud2b2Uz7s3+6+HD99Pr3vdg/7t5vH08/X/SHchSOeX77j9vnw9dsPHHHC6/L0vnt4vF1DDSnk0Hj2MEJDDmsoC8yD6YE8y5MTctgILSQOnolnosXo5in8bSSaJ63UiSvEQCz4D8XVTXl1vlE36NN9kRJpQYxdn83yJNsUG5PpUspeD0qYD2WEhJAQEkJCSNfOKr4oqQpvwLRBNodZ5qbTCLVG2GmVVD55ZtJR1NFkGiIgDsYt+CfjLL6piCFpc3eLLNJmbVDbhiSatYy+wgZ1+bOiXSnggwKkgD8UiCke3Pq80lTn1NX+zpRXyOioMYdvKQ2aN5fngM8Ph04mcbCRW2DirIWIFTH/nnIBQ0S9TVtWJSbbdPqidL3ZCBPyXNU8EyQH0fo9cEVixG6FQaTlol60W11nncmblZnIllxRPb3CYeK4v+cb4Gs35rqZUpZaUpbp3nZQN+gvIC5A2+W5x0WbUHUH18v4G5GbL2PwwrOGPPGqONE7oBtWWe7GXOt5oY3TtGlZwx4qZ1NTmzLzdic0rUm+RLji4gOXOcP+IkhG12ithl+YaNNx)
Takes the list of values as `x` and the lengths of the chunks as `y`.
* `&y` convert length of chunks from e.g. `2 4 3` to `0 0 1 1 1 1 2 2 2`
* `x!` make a dictionary mapping the original input to these indices
* `=` "group" that dictionary (i.e., map the distinct values of the dictionary to their corresponding keys)
* `.` return just the values (i.e., the original values, split into chunks of the correct lengths)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 2 bytes
```
ɾ•
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLJvuKAoiIsIiIsIlsyLDQsM11cbls0LDUsMSwyLDYsMSw3LDksNl0iXQ==)
~~If generators weren't so broken, it'd just be `vɾ•` and flagless.~~ Thank goodness for Vyxal 2.8 lol.
## Explained
```
ɾ•
ɾ # vectorise range for each item in the shape list
• # and mold that to the shape list
```
So essentially, a port of hyper's jelly
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 3 bytes
```
m%s
```
[Run and debug it](https://staxlang.xyz/#c=m%25s&i=%22451261796%22,+%5B2,+4,+3%5D%0A%224287359319181728376%22,+%5B1,+3,+1,+14%5D%0A%228746%22,+%5B1,+3%5D%0A%227%22,+%5B1%5D%0A%22643893657832512%22,+%5B3,+3,+3,+3,+3%5D%0A%222793815%22,+%5B4,+3%5D%0A%221989634234185529367%22,+%5B3,+1,+2,+13%5D%0A%22187894252715238469193467653%22,+%5B7,+7,+3,+8,+2%5D%0A%22744755%22,+%5B1,+2,+3%5D%0A%22928723958152%22,+%5B2,+2,+2,+2,+2,+1,+1%5D%0A%22873%22,+%5B3%5D%0A%22827395695319753641%22,+%5B2,+1,+2,+6,+2,+2,+3%5D%0A%22823747745581233%22,+%5B3,+7,+4,+1%5D%0A%224389932558281141%22,+%5B10,+5,+1%5D%0A%226329561494256885%22,+%5B4,+3,+2,+1,+2,+2,+2%5D%0A%222216852679458196387391%22,+%5B6,+7,+1,+2,+2,+2,+2%5D%0A&m=2)
Takes a string of digits, and the partitions as an integer array.
outputs each slice with a newline.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 44 26 bytes
```
->b,l{b.map{|x|l.shift x}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5JJ6c6SS83saC6pqImR684IzOtRKGitvZ/gUJadLSRjomOcayOQrSBjgIQGSIhIwiKjeUCqzQEqTKPjf3/HwA "Ruby – Try It Online")
*-18 thanks to dingledooper*
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 10 bytes
```
≔⮌θθEη⭆ι⊟θ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU8jKLUstag4VaNQU0ehUNOaK6AoM69EwzexQCNDRyG4BMhLB3EydRQC8guAqoDA@v//6GgTHQVTHQVDHQUjHQUzMMNcR8ESyI7VUYgGigHljWNj/@uW5QAA "Charcoal – Try It Online") Link is to verbose version of code. Outputs a newline-separated list of digit strings. Explanation:
```
≔⮌θθ
```
Reverse `L`.
```
Eη⭆ι⊟θ
```
For each element of `B`, pop that many elements from `L`, and concatenate the digits into a string for output.
[Answer]
# Scala, 64 bytes
```
s=>_./:(Seq[Any]()->s){case(a->s,x)=>(a:+s.take(x),s drop x)}._1
```
[Try it online!](https://scastie.scala-lang.org/c5MQyZHoSTiM8VzZUy3NCw)
Called as `f(fullList)(sublistSizes)`
```
s => //The sequence of integers to be split
_ //The sizes for it to be split into
./: //Fold over it,
(Seq[Any]()->s) //Starting with an empty list of sublists, and the original list
{case(a->s,x) => //a is the current list of sublists, s is the current full list, x is the current element
(a:+s.take(x), //Add the first x elements of s as a sublist
s drop x) //Drop x elements from the full list
}._1 //Only keep the list of sublists
```
[Answer]
# [Desmos](https://desmos.com/calculator), ~~128~~ 117 bytes
```
a=length(B)
g(l)=\sum_{k=1}^{[1...length(l)]}l[k]
f=\prod_{n=1}^a\{g(B)[n]+n=[1...\length(L)+a]:0,1\}
h(L,B)=L[g(f)]f
```
Implements a function \$h(L,B)\$. Output is a list of numbers, with each sublist separated by a zero.
[Try It On Desmos!](https://www.desmos.com/calculator/igbi9nh40m)
[Try It On Desmos! - Verbose](https://www.desmos.com/calculator/qptje1kxju)
### Explanation:
`a=length(B)`: A helper value that stores the length of the list `B` specified in the challenge description.
`g(l)=\sum_{k=1}^{[1...length(l)]}l[k]`: A helper function that returns the running total(as a list) of the list argument `l`.
`f=\prod_{n=1}^a\{g(B)[n]+n=[1...\length(L)+a]:0,1\}`: Creates a list of 0's and 1's, which will be used later to determine the format of the final outputted list(`0`'s mean sublist separator, `1`'s mean to put an element of `L` there, where `L` is specified in the challenge description.).
`h(L,B)=L[g(f)]f`: The actual function that outputs the answer, with each sublist separated by a zero.
[Answer]
# [Python 3](https://docs.python.org/3/), 76 bytes
```
def f(x,n):x=iter(x);return[[*islice(x,a)]for a in n]
from itertools import*
```
[Try it online!](https://tio.run/##FcoxDsIwDADAnVdYnZLKSykTiJdEGSqaqJZSO3JdEV4fYL6rH9uE597XlCG7huzv7UmW1DX/0GSncggjHYVe6ceLj1kUFiAGjpesssN/m0g5gPYqamOvSmwuu2FLpQi8Rcs6YJjwijPecIre9y8 "Python 3 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~65~~ 58 bytes
```
f(s,b,l)int*s,*b;{for(;l--;s+=*b++)printf("%.*ls ",*b,s);}
```
[Try it online!](https://tio.run/##ZVNbboMwEPzPKSxLkXiYtn4kkDppL9AbpHzEJERIrlPFlVo14uqla56OQPKyzMzujjEUybkomqYMLFFEh5X5iiyJlLyVl2sgdZJIG@8iFcfh5xXIMsDLh0hbhEFEbCjrBlD0cahMEKLbAsHleiBL0Q69YbGibE3TzRrLHmcdzrKUrzacbmhGU5bxdFLwVpGlYoJEC6Xjs93ngNwsJdAQFoclajmMR4p2AuAEQbyWHco6FKqgACIVA8MnZoBED/lttduVrX5PlzJQNHzs0wjyvkozT8E8BRsV3FNwT8FHhfAUwlOI0PfS@QNPxI11gbvQ7ylCqn9Lygkc7@jhLcHxosD1qczx9AOyJ9mn22G0tdNoyCWK41YxnPN01s6u3bdkLkdu/GC0JWiP4YhCeV@ooFDNC50t7Sg9o0bbxnSe4b5F2nkzxjd2Z8AujzDemFeI@BlDVHtjcs9OPXOdo@QFYU8y/CLzDb6bQVcv6uavKPXhbJvk@x8 "C (gcc) – Try It Online")
Inputs a pointer to a list of digits as a wide-character string, a pointer to a list of integer lengths and that list's length (since pointers in C carry no length info).
Outputs the sub-lists separated by spaces.
[Answer]
# [Julia 1.0](http://julialang.org/), ~~33~~ ~~30~~ 25 bytes
```
l/b=b.|>a->splice!(l,1:a)
```
[Try it online!](https://tio.run/##jVXLbtswELz7K1jkkgBMGpISHwHsHzF0sFsXcCG4QawCPeTfXXF3ViSVFgggCCtyOTucfejn7/F8MH9ut/HrcXt8et8dHnfX1/H87fTlftTm5fBwm07X6brdb/b7TqteK6OV1cqTEbRKsz1otZ/X5n03DErfqcedYve8Uw7kLzkyMOC8EwnHEXgiw5BhaIujsJsj2wOUHU1XhwSTDJlNl1@fhs2UmExXRangIy7QiTcFMZVHoGXPWhA4h/Z0uyDh7KIksaQ1PBUYYLILgLIJKKw6YAhcDm8lMU6uSnlYpad4AYr88nnWiUN6QuFEscH69fTY6n4BV@F0mzoUALNDwhUcGH0CFpSi6JeED3sGZi5QkdMjqU6C7znJ5OmQxyAnbEt2HQoCr4NBNymWfwfEWcf1Qjsd7fRNe7imiFibDjR7SUyq@oVvm2g3LqxQ//WTe6QCT/CSFpGLJNCJ6FP6sFVPOG6oqhuwDBcrejInL8bSeEE@ua4Noi/jwX4QIoKrlFaCmA02yIdFaC4wilCoOenrIEZfSWfRexwmyOmGSCmbNUrpH1tk4vG2zIBU9T2HtRLcFDnMMw@Gdor@F6RMO8BgHPEIctJIvYzrrm0eT0djNR6kYFA87SwCXsmBwTFaktHbQ/8IVXoZSYzspc2tdEgSHaMUipcrL/VkABpqdi3BdQTQWcdghbhkPPItY136ICs4bH78elOTOl8U/QA3So36qLZqmq3Xt/NlGi/380/zQW1Ol@@3vw "Julia 1.0 – Try It Online")
Thanks to dingledooper for -3 bytes and to MarcMush to further -5.
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), 39 bytes
```
param($u,$v)$u|%{,$v[$s..(($s+=$_)-1)]}
```
[Try it online!](https://tio.run/##jVRdb9pAEHznV1ipW2H1HNVn@@xThYSE2oe@NCp9Qyii1GlSAaa2SSsl/Ha6O3t2AKdVsDh/7M7s7N7ubcvfRVXfFqtVuCyr4uDfjB4O20W1WA/9nfLvA3/3@PqBHmZ@fXk5HPr125F/HYRRMN8f9oPxcODRT42HfCUqVZHSytCaKatMQAatEhUHgfIuZjNymKuZc6EnOM3nF8Epi1Y54WNis7RGtEb0hTnZEtMdzBGMUdKSEyGQdI/p/x/0eUgOl3Skji@HwKTvncHPeWXnVsP5UiAObiiFDEG1lIaRsXKXYwCAYgFCd4DwTjDkQcDzKBoFjpFYyqxPRXYmMJDxHMkF4VCG0FxqXrlAKV3aqc5EJ29U1NICR6QWEpn@n@h@yBxlsAjIjhkrAzznCmOPLMgM7w/ZYpaQoQ1yqlur4YgIpTmiQsK8XaTxlA6ecW8byZyQOZUCcrJxt6mcXYIGSPsltK5DWb8lh1wkSLe3F3WmY7PQKo0pOi3mIMcM8JN@riFRga4Z@UPfS6NArMFglX7P8MR9FYkmmTh9lGEOTRgVZVGfjgD6MlczhfaMnoscY2gyrKmrgkZfo3kyhO@igesE4BpULHH/FJAhsm54mF8jRtTmFb3joeqOlp6/Ow@A4GOnP6kxejbFgZV07WkIlHdTpaR8umtCB3NFi9Aq/CbnT4qS5Ugu7U8tkxnMi0ZvWtQix7YZpCAbigQNmlufRD@iQLwjEuTIm2ewrXJ@SbtJ7oH36H0sqw@L5W34@dvPYtl4D5DnN0XdTBZ1oTy/@LMlQ/HdG3n@tVjrprrb/CBbvV3dNWxo/cVeFfVuxd/f@DetkwNRxEm5uS@q5msZfqrLjRdOyvWWEDWws6vpZFc35Vr0zMciiH/T3XJJbhzOBQiLX0/63neOr6YSavTSoAJqcxG9L4B8adN0emDYD/aDw18 "PowerShell Core – Try It Online")
Two test cases are not working because PowerShell flattens simple jagged arrays, i.e. `[[7]]` becomes `[7]`
[Answer]
# [Uiua](https://uiua.org), ~~5~~ 3 [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==)
```
⊕□⊚
```
[Try it!](https://uiua.org/pad?src=ZiDihpAg4oqV4pah4oqaCgpmIFsxIDIgMyA0IDFdICJoZWxsbyB3b3JsZCIKZiBbM10gWzggNyAzXQpmIFsxIDNdIFs4IDcgNCA2XQ==)
-2 thanks to Bubbler
```
⊕□⊚
⊚ # where
⊕□ # group with boxing
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~5~~ 4 bytes
```
CmR¹
```
[Try it online!](https://tio.run/##yygtzv7/3zk36NDO////RxvqmOgY6RjHglgwaASFhgYGsQA "Husk – Try It Online")
```
CmR¹ # 5-byte program, but this is equivalent to
CzR⁰⁰² # 6-byte program using the ¹ shortcut to use the 1st arg twice and implicit 2nd arg
m # map over
⁰ # the list of the 1st argument
R ⁰ # by repeating arg1 this number of times;
# now use the lengths of this list of lists to
C ² # cut the list of the 2nd argument
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 5 bytes
```
"@:&)
```
Inputs *B*, then *L*. Displays each sublist on a separate line.
[Try it online!](https://tio.run/##y00syfn/X8nBSk3z//9oIx0FEx0F41iuaCBlqqNgqKMAFDIDM8x1FCyB7FgA "MATL – Try It Online")
# Explanation
```
" % Implicit input: numeric vector B. For each k in B
@ % Push k
: % Range [1 2 ... k]
&) % Two-ouput indexing. The first time this takes as implicit input
% the numeric vector L; in subsequent iterations it uses as input
% what remains of L. Pushes a smaller vector according to the
% specified indices, and another vector with the remaining entries
% Implicit end. Implicit display stack
```
[Answer]
# [Arturo](https://arturo-lang.io), 36 bytes
```
$[a,b][map b'i[take a i a:drop a i]]
```
[Try it](http://arturo-lang.io/playground?bHfaGV)
```
$[a,b][ ; a function taking two arguments a and b
map b'i[ ; map over b and assign current elt to i
take a i ; the first i elts of a
a:drop a i ; assign a sans the first i elts to a
] ; end map
] ; end function
```
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata), 4 bytes
```
J$ᶻL
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PVI7TkMxEJQoOQWKKB0Jr_9XiLjB0ysCIg0KFAmnoUlBIk5Aw03ouAkzYz9kaZ_tnZ2dHb_3z5en59f99ri9TKv1fjWfzm_H3bpeNre_X9_3H4eHx8O4Ov1c7abokvPOXEYsrrk830zmogvzNXLmKm4DMA3RI3rcEMlMwJd4r5yPKCE8Lpc4F-7wzaRECWky6IrKrTcHJrixgDUJCWqUkOti2Jz1GRkKY6SYhGWDt4iJ4_heUtWoqYCwQkoVV8rUPE1UmbMgF0BRNHOFMAyAXMQ5SQqpydyGM2RqyNXOK--WBUeGIeQM2puYWZEVu6dFO1rkxdDfw0avqi5FKhjT6GeyiwMXVfK9usVtWEucCesHt7-j43qPINeSHj7-W5QBr4vrrksxGdFHynLcZFeTmKoRslr34dgoy-phxdz_tz8)
```
J$ᶻL Input L and R
J Non-deterministically split L into parts
$ Swap to get R
ᶻL Check that the length of each part is equal to the corresponding element of R
```
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/20646/edit).
Closed 2 years ago.
[Improve this question](/posts/20646/edit)
# Create an analogue clock
Goal: To create a working analogue clock using any programming language.
Requirements:
* Your clock should feature at least the hour and minute pointers.
* The produced clock could be in the form of an image, an animation or ASCII-art.
* It is expected that the clock shows local time.
Optional:
* You might make your clock to show the seconds pointer in addition to the minutes and hours pointers.
* You might also make the timezone to be configurable if you wish.
* You are free to choose if you may either neglect or handle issues about leap seconds.
* You might think about what happens to your program if the user adjusts the system clock or if a daylight change occurs.
Since this is a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"), please be creative and draw some nice and beautiful clocks to deserve the upvotes. **Most upvoted answer wins**, with the exception that I will not accept my own answer.
Finally, it is recommended (but not required) that you post at least one screenshot (or text output in case of ASCII-art) of your clock in your answer. This way, people will not need to compile and run it to see what it is.
---
This question is intended to be a revival of a deleted question.
Note that it is not a duplicate [of this other question](https://codegolf.stackexchange.com/questions/10759/build-an-analog-clock?lq=1). That question was a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") asking for ASCII-art. This one is not restricted to ASCII-art and is a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'") instead, so the answers are expected to be very different.
[Answer]
# SVG + Javascript

[**▶▶▶ Live demo here ◀◀◀**](http://ruletheweb.co.uk/clock.svg)
This uses SVG's built-in animation functions to turn the hands, with a bit of additional Javascript to fetch the local time and set the initial hand positions. It works OK in Chrome and Safari, and should be compatible with most modern browsers as it doesn't use any filter effects.
```
<?xml version="1.0"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 400 400" width="400" height="400" version="1.0">
<defs>
<linearGradient id="a" x1="0%" y1="100%" x2="0%" y2="0%">
<stop offset="0%" style="stop-color:#777799"/>
<stop offset="100%" style="stop-color:#ffffff"/>
</linearGradient>
<linearGradient id="b" x1="0%" y1="100%" x2="0%" y2="0%">
<stop offset="0%" style="stop-color:#ffffff"/>
<stop offset="25%" style="stop-color:#b6b6cc"/>
<stop offset="40%" style="stop-color:#515177"/>
<stop offset="48%" style="stop-color:#ffffff"/>
<stop offset="56%" style="stop-color:#ffffff"/>
<stop offset="75%" style="stop-color:#8b8baa"/>
<stop offset="98%" style="stop-color:#efeff4"/>
<stop offset="100%" style="stop-color:#fbfbfc"/>
</linearGradient>
<linearGradient id="c" x1="0%" y1="100%" x2="0%" y2="0%">
<stop offset="0%" style="stop-color:#ffffff"/>
<stop offset="100%" style="stop-color:#777799"/>
</linearGradient>
<radialGradient id="d" cx="50%" cy="50%" r="50%" fx="50%" fy="50%">
<stop offset="0%" style="stop-color:#ffffff"/>
<stop offset="40%" style="stop-color:#ffffff"/>
<stop offset="70%" style="stop-color:#e6e6ee"/>
<stop offset="92%" style="stop-color:#b6b6cc"/>
<stop offset="100%" style="stop-color:#636388"/>
</radialGradient>
<radialGradient id="e" cx="50%" cy="150%" r="200%" fx="50%" fy="150%">
<stop offset="0%" style="stop-color:#ffffff;stop-opacity:0"/>
<stop offset="59%" style="stop-color:#ffffff;stop-opacity:0"/>
<stop offset="60%" style="stop-color:#ffffff;stop-opacity:0.6"/>
<stop offset="70%" style="stop-color:#ffffff;stop-opacity:0.3"/>
<stop offset="100%" style="stop-color:#ffffff;stop-opacity:0.0"/>
</radialGradient>
</defs>
<g transform="translate(200 200)">
<circle cx="0" cy="0" r="200" fill="#cecedd"/>
<circle cx="0" cy="0" r="196" stroke="url(#a)" stroke-width="5" fill="url(#b)"/>
<circle cx="0" cy="0" r="170" stroke="url(#c)" stroke-width="4" fill="url(#d)"/>
<circle cx="0" cy="0" r="172" stroke="#ffffff" stroke-width="0.5" fill="none"/>
<circle cx="0" cy="0" r="193.5" stroke="#ffffff" stroke-width="0.5" fill="none"/>
<g id="O">
<polygon points="4,155 4,130 -4,130 -4,155" style="fill:#777799;stroke:#313155;stroke-width:1"/>
<polygon points="4,-155 4,-130 -4,-130 -4,-155" style="fill:#777799;stroke:#313155;stroke-width:1"/>
</g>
<g transform="rotate(30)"><use xlink:href="#O"/></g>
<g transform="rotate(60)"><use xlink:href="#O"/></g>
<g transform="rotate(90)"><use xlink:href="#O"/></g>
<g transform="rotate(120)"><use xlink:href="#O"/></g>
<g transform="rotate(150)"><use xlink:href="#O"/></g>
<polygon id="h" points="6,-80 6,18 -6,18 -6,-80" style="fill:#232344">
<animateTransform id="ht" attributeType="xml" attributeName="transform" type="rotate" from="000" to="000" begin="0" dur="86400s" repeatCount="indefinite"/>
</polygon>
<polygon id="m" points="3.5,-140 3.5,23 -3.5,23 -3.5,-140" style="fill:#232344">
<animateTransform id="mt" attributeType="xml" attributeName="transform" type="rotate" from="000" to="000" begin="0" dur="3600s" repeatCount="indefinite"/>
</polygon>
<polygon id="s" points="2,-143 2,25 -2,25 -2,-143" style="fill:#232344">
<animateTransform id="st" attributeType="xml" attributeName="transform" type="rotate" from="000" to="000" begin="0" dur="60s" repeatCount="indefinite"/>
</polygon>
<circle cx="0" cy="0" r="163" fill="url(#e)"/>
</g>
<script type="text/javascript"><![CDATA[
var d = new Date();
var s = d.getSeconds();
var m = d.getMinutes() + s/60;
var h = (d.getHours() % 12) + m/60 + s/3600;
document.getElementById('st').setAttribute('from',s*6);
document.getElementById('mt').setAttribute('from',m*6);
document.getElementById('ht').setAttribute('from',h*30);
document.getElementById('st').setAttribute('to',360+s*6);
document.getElementById('mt').setAttribute('to',360+m*6);
document.getElementById('ht').setAttribute('to',360+h*30);
]]></script>
</svg>
```
[Answer]
# Java 8
I made a clock that changes its colors accordingly to the hour of day, showing local time. As the time passes, it will slowly change it colors, using brighter colors at day and darker colors at night.
The window is resizable and the clock will resize automatically to whatever size you choose.
Further, if the user adjusts the system clock or if a daylight time change happens, the clock will automatically reflect that.
There are two forms to run it:
1. Running the `ClockDemo` file, i.e. `java clock.ClockDemo`. This will open a window and you will see the clock there.
2. Running the `ClockSave` file, i.e. `java clock.ClockSave filename width height [HH:mm:ss]`. This will just save the clock in a PNG file with the given file name, width and height. The clock will be draw with the given time, or if that is omitted, with current time. For example, if you run it as `java clock.ClockSave clock.png 600 500 12:38:24` it will save the clock in a 600x500 image in a `clock.png` file and the clock will be showing 12:38:24 AM. Use hours in the 00-23 interval.
---
## Screenshots
Here are some screenshots and generated files:
### 00:36:50 AM:

### 02:38:51 AM:

### 06:42:13 AM:

### 11:15:28 AM:

### 05:02:37 PM:

### 07:11:30 PM:

### 09:29:34 PM:

---
## Source code
I separated the source in five different files in a package called `clock`.
Also available at [**GitHub**](https://github.com/victorwss/jclock).
### ClockDemo.java
```
package clock;
import java.awt.EventQueue;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
public class ClockDemo {
public static void main(String[] args) {
EventQueue.invokeLater(ClockDemo::runIt);
}
private static void runIt() {
final JFrame j = new JFrame();
j.setTitle("JClock");
final JClock clock = new JClock(new CoolPaint());
j.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
clock.stop();
j.dispose();
}
});
j.add(clock);
j.setBounds(20, 20, 600, 500);
j.setVisible(true);
clock.start();
}
}
```
### ClockSave.java
```
package clock;
import java.io.IOException;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
public class ClockSave {
public static void main(String[] args) {
// Too much arguments.
if (args.length < 3 || args.length > 4) {
System.out.println("Bad usage: Should be java clock.ClockSave filename width height [HH:mm:ss]");
return;
}
// Parse the image size.
int h, w;
try {
w = Integer.parseInt(args[1]);
h = Integer.parseInt(args[2]);
} catch (NumberFormatException e) {
System.out.println("Bad usage: Should be java clock.ClockSave filename width height [HH:mm:ss]");
return;
}
// Parse the intended time.
LocalTime time;
if (args.length == 4) {
try {
DateTimeFormatter df = DateTimeFormatter.ofPattern("HH:mm:ss");
time = LocalTime.parse(args[3], df);
} catch (DateTimeParseException e) {
System.out.println("Bad usage: Should be java clock.ClockSave filename width height [HH:mm:ss]");
return;
}
} else {
time = LocalTime.now();
}
// Save to an image.
try {
new CoolPaint().saveClock(w, h, time, args[0]);
} catch (IOException e) {
System.out.println("Error on image output: " + e.getMessage());
}
}
}
```
### JClock.java
```
package clock;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.time.LocalTime;
import java.time.temporal.ChronoField;
import javax.swing.JComponent;
public class JClock extends JComponent {
private static final long serialVersionUID = 1L;
private final CoolPaint paint;
private final Object lock;
private Thread updater;
public JClock(CoolPaint paint) {
this.paint = paint;
this.lock = new Object();
}
private void runClock() {
int lastTime = -1;
try {
while (isRunning()) {
Thread.sleep(10);
int t = time();
if (t != lastTime) {
lastTime = t;
repaint();
}
}
} catch (InterruptedException e) {
// Do nothing, the thread will die naturally.
}
}
private int time() {
return LocalTime.now().get(ChronoField.SECOND_OF_DAY);
}
private boolean isRunning() {
synchronized (lock) {
return updater == Thread.currentThread();
}
}
public void start() {
synchronized (lock) {
if (updater != null) return;
updater = new Thread(this::runClock);
updater.start();
}
}
public void stop() {
synchronized (lock) {
updater = null;
}
}
@Override
public void paintComponent(Graphics g) {
paint.paintClock(getWidth(), getHeight(), time(), (Graphics2D) g);
}
}
```
### ClockPaint.java
```
package clock;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.time.LocalTime;
import java.time.temporal.ChronoField;
import javax.imageio.ImageIO;
public interface ClockPaint {
public void paintClock(int width, int height, int seconds, Graphics2D g2);
public default void paintClock(int width, int height, LocalTime time, Graphics2D g2) {
paintClock(width, height, time.get(ChronoField.SECOND_OF_DAY), g2);
}
public default void paintClock(int width, int height, Graphics2D g2) {
paintClock(width, height, LocalTime.now(), g2);
}
public default void saveClock(int width, int height, String fileName) throws IOException {
saveClock(width, height, LocalTime.now(), fileName);
}
public default void saveClock(int width, int height, LocalTime time, String fileName) throws IOException {
saveClock(width, height, time.get(ChronoField.SECOND_OF_DAY), fileName);
}
public default void saveClock(int width, int height, int seconds, String fileName) throws IOException {
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
paintClock(width, height, seconds, (Graphics2D) image.getGraphics());
String f = fileName.endsWith(".png") ? fileName : fileName + ".png";
ImageIO.write(image, "png", new File(f));
}
}
```
### CoolPaint.java
```
package clock;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.RadialGradientPaint;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
public class CoolPaint implements ClockPaint {
private static final int SECONDS_IN_MINUTE = 60;
private static final int SECONDS_IN_HALF_HOUR = 30 * SECONDS_IN_MINUTE;
private static final int SECONDS_IN_HOUR = 60 * SECONDS_IN_MINUTE;
private static final int SECONDS_IN_12_HOURS = 12 * SECONDS_IN_HOUR;
private static final int AM_0_00 = 0;
private static final int AM_3_00 = 3 * SECONDS_IN_HOUR;
private static final int AM_4_30 = 4 * SECONDS_IN_HOUR + SECONDS_IN_HALF_HOUR;
private static final int AM_7_30 = 7 * SECONDS_IN_HOUR + SECONDS_IN_HALF_HOUR;
private static final int AM_12_00 = 12 * SECONDS_IN_HOUR;
private static final int PM_4_30 = 16 * SECONDS_IN_HOUR + SECONDS_IN_HALF_HOUR;
private static final int PM_7_30 = 19 * SECONDS_IN_HOUR + SECONDS_IN_HALF_HOUR;
private static final int PM_9_00 = 21 * SECONDS_IN_HOUR;
private static final int PM_12_00 = 24 * SECONDS_IN_HOUR;
private static final Color BLACK = new Color(0, 0, 0);
private static final Color DARK_GRAY = new Color(32, 32, 32);
private static final Color DARK_BLUE = new Color(0, 0, 128);
private static final Color PURPLE = new Color(128, 0, 128);
private static final Color CYAN = new Color(0, 255, 255);
private static final Color YELLOW = new Color(225, 225, 0);
private static final Color PALE_YELLOW = new Color(224, 224, 64);
private static final Color RED = new Color(255, 0, 0);
private static final Color GREEN = new Color(0, 255, 0);
private static final Color LIGHT_BLUE = new Color(128, 128, 255);
private static final Color SKY_CYAN = new Color(48, 224, 224);
private static final Color[] COLOR_CYCLE = {
DARK_GRAY, LIGHT_BLUE, RED, PALE_YELLOW, GREEN, SKY_CYAN, LIGHT_BLUE, DARK_GRAY
};
private static final int RADIAL_PERIOD_LENGTH = PM_12_00 / COLOR_CYCLE.length;
private static final String[] ROMAN = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "XI", "XII"};
private static class Painter {
private final int width;
private final int height;
private final int seconds;
private final int radius;
private final Graphics2D g2;
private final int cx;
private final int cy;
private final int secondColorIndex;
private final int secondsInPeriod;
private final Color pointersAndNumbersColor;
public Painter(int width, int height, int seconds, Graphics2D g2) {
this.width = width;
this.height = height;
this.seconds = seconds;
this.radius = Math.min(width / 2, height / 2);
this.cx = width / 2;
this.cy = height / 2;
this.g2 = g2;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
this.secondColorIndex = seconds / RADIAL_PERIOD_LENGTH;
this.secondsInPeriod = seconds % RADIAL_PERIOD_LENGTH;
int startIndex = (secondColorIndex + COLOR_CYCLE.length + 5) % COLOR_CYCLE.length;
int endIndex = (secondColorIndex + COLOR_CYCLE.length + 6) % COLOR_CYCLE.length;
Color color1 = COLOR_CYCLE[startIndex];
Color color2 = COLOR_CYCLE[endIndex];
this.pointersAndNumbersColor = mixColors(color1, color2, 0, RADIAL_PERIOD_LENGTH, secondsInPeriod);
}
private int mixColorComponent(int startComponent, int endComponent, double position) {
int difference = endComponent - startComponent;
return startComponent + (int) (difference * position);
}
private Color mixColors(Color startColor, Color endColor, int startTime, int endTime, int currentTime) {
double normalized = (currentTime - startTime) / (double) (endTime - startTime);
return new Color(
mixColorComponent(startColor.getRed(), endColor.getRed(), normalized),
mixColorComponent(startColor.getGreen(), endColor.getGreen(), normalized),
mixColorComponent(startColor.getBlue(), endColor.getBlue(), normalized));
}
private Color upperBackgroundColor() {
if (seconds < 0) throw new IllegalArgumentException();
if (seconds <= AM_3_00) return BLACK;
if (seconds <= AM_4_30) return mixColors(BLACK, DARK_BLUE, AM_3_00, AM_4_30, seconds);
if (seconds <= AM_7_30) return mixColors(DARK_BLUE, CYAN, AM_4_30, AM_7_30, seconds);
if (seconds <= AM_12_00) return CYAN;
if (seconds <= PM_4_30) return CYAN;
if (seconds <= PM_7_30) return mixColors(CYAN, DARK_BLUE, PM_4_30, PM_7_30, seconds);
if (seconds <= PM_9_00) return mixColors(DARK_BLUE, BLACK, PM_7_30, PM_9_00, seconds);
if (seconds <= PM_12_00) return BLACK;
throw new IllegalArgumentException();
}
private Color lowerBackgroundColor() {
if (seconds < 0) throw new IllegalArgumentException();
if (seconds <= AM_3_00) return mixColors(BLACK, DARK_BLUE, AM_0_00, AM_3_00, seconds);
if (seconds <= AM_4_30) return mixColors(DARK_BLUE, PURPLE, AM_3_00, AM_4_30, seconds);
if (seconds <= AM_7_30) return mixColors(PURPLE, YELLOW, AM_4_30, AM_7_30, seconds);
if (seconds <= AM_12_00) return mixColors(YELLOW, CYAN, AM_7_30, AM_12_00, seconds);
if (seconds <= PM_4_30) return mixColors(CYAN, YELLOW, AM_12_00, PM_4_30, seconds);
if (seconds <= PM_7_30) return mixColors(YELLOW, PURPLE, PM_4_30, PM_7_30, seconds);
if (seconds <= PM_9_00) return mixColors(PURPLE, DARK_BLUE, PM_7_30, PM_9_00, seconds);
if (seconds <= PM_12_00) return mixColors(DARK_BLUE, BLACK, PM_9_00, PM_12_00, seconds);
throw new IllegalArgumentException();
}
private void paintBackground() {
Point2D p1 = new Point2D.Double(width / 2, 0);
Point2D p2 = new Point2D.Double(width / 2, height);
g2.setPaint(new GradientPaint(p1, upperBackgroundColor(), p2, lowerBackgroundColor()));
g2.fillRect(0, 0, width, height);
}
private RadialGradientPaint colorOnCycle(Point2D center, float radius) {
Color baseColor1 = COLOR_CYCLE[(secondColorIndex + COLOR_CYCLE.length - 1) % COLOR_CYCLE.length];
Color baseColor2 = COLOR_CYCLE[secondColorIndex];
Color baseColor3 = COLOR_CYCLE[(secondColorIndex + COLOR_CYCLE.length + 1) % COLOR_CYCLE.length];
Color baseColor4 = COLOR_CYCLE[(secondColorIndex + COLOR_CYCLE.length + 2) % COLOR_CYCLE.length];
Color start = mixColors(baseColor1, baseColor2, 0, RADIAL_PERIOD_LENGTH, secondsInPeriod);
Color end = mixColors(baseColor3, baseColor4, 0, RADIAL_PERIOD_LENGTH, secondsInPeriod);
float index2 = (RADIAL_PERIOD_LENGTH - secondsInPeriod) / (float) RADIAL_PERIOD_LENGTH / 2;
float index3 = 0.5f + index2;
float[] positions = index3 == 1.0 ? new float[] {0.0f, index2, 1.0f}
: new float[] {0.0f, index2, index3, 1.0f};
Color[] colors = index3 == 1.0 ? new Color[] {start, baseColor2, end}
: new Color[] {start, baseColor2, baseColor3, end};
return new RadialGradientPaint(center, radius, positions, colors);
}
private void paintClockArea() {
Point2D center = new Point2D.Double(width / 2, height / 2);
g2.setPaint(colorOnCycle(center, radius));
g2.fillOval(width / 2 - radius, height / 2 - radius, radius * 2, radius * 2);
}
private double pointerRevolutionsToRadians(double angle) {
return Math.toRadians((450 + angle * -360) % 360.0);
}
private void paintPointers() {
double hAngle = pointerRevolutionsToRadians(seconds % SECONDS_IN_12_HOURS / (double) SECONDS_IN_12_HOURS);
double mAngle = pointerRevolutionsToRadians(seconds % SECONDS_IN_HOUR / (double) SECONDS_IN_HOUR);
double sAngle = pointerRevolutionsToRadians(seconds % SECONDS_IN_MINUTE / (double) SECONDS_IN_MINUTE);
g2.setStroke(new BasicStroke(4.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
g2.drawLine(cx, cy, (int) (cx + Math.cos(hAngle) * radius * 0.55), (int) (cy - Math.sin(hAngle) * radius * 0.55));
g2.drawLine(cx, cy, (int) (cx + Math.cos(mAngle) * radius * 0.85), (int) (cy - Math.sin(mAngle) * radius * 0.85));
g2.setStroke(new BasicStroke(1.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
g2.drawLine(cx, cy, (int) (cx + Math.cos(sAngle) * radius * 0.85), (int) (cy - Math.sin(sAngle) * radius * 0.85));
}
private void paintNumbers() {
Font originalFont = g2.getFont();
double amplification = (int) Math.max(radius * 0.08, originalFont.getSize()) / (double) originalFont.getSize();
AffineTransform at0 = AffineTransform.getScaleInstance(amplification, amplification);
Font amplifiedFont = originalFont.deriveFont(at0);
g2.setFont(amplifiedFont);
FontMetrics fm = g2.getFontMetrics();
for (int i = 1; i <= 12; i++) {
double angle = pointerRevolutionsToRadians(i / 12.0);
double textInclination = Math.toRadians(30 * i);
AffineTransform at = AffineTransform.getRotateInstance(textInclination);
at.scale(amplification, amplification);
Font derivedFont = originalFont.deriveFont(at);
g2.setFont(derivedFont);
int pixelsOffset = fm.stringWidth(ROMAN[i]) / 2;
int xPlot = (int) (cx + Math.cos(angle) * radius * 0.9 - pixelsOffset * Math.cos(textInclination));
int yPlot = (int) (cy - Math.sin(angle) * radius * 0.9 - pixelsOffset * Math.sin(textInclination));
g2.drawString(ROMAN[i], xPlot, yPlot);
}
g2.setFont(originalFont);
}
private void paintDots() {
for (int i = 1; i < 60; i++) {
if (i % 5 == 0) continue;
double angle = pointerRevolutionsToRadians(i / 60.0);
g2.fillRect((int) (cx + Math.cos(angle) * radius * 0.9) - 1, (int) (cy - Math.sin(angle) * radius * 0.9) - 1, 3, 3);
}
}
public void paintClock() {
paintBackground();
paintClockArea();
g2.setColor(pointersAndNumbersColor);
g2.setPaint(pointersAndNumbersColor);
paintNumbers();
paintDots();
paintPointers();
}
}
@Override
public void paintClock(int width, int height, int seconds, Graphics2D g2) {
new Painter(width, height, seconds, g2).paintClock();
}
}
```
[Answer]
# Freepascal
This clock displays the time, date and phase of the moon. However unlike mechanical clocks that have a small window for displaying the phase of the moon, in my clock the whole face is used to display it. Today Feb 14 is a full moon. You can see the expected output over the next few days below.
```
uses graph,sysutils;
const hemisphere=-1; {-1=north,1=south}
MonthStr : array[1..12] of string [3] =
('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep ','Oct','Nov','Dec');
var yy,dd,mm,hh,mn,ss,ms: word;
var s: string; d2fullmoon,hour,min:real; sec:word;
var gd, gm, n : integer;
var right, left, centre: word;
begin
gd := D4bit;
gm := m640x480;
initgraph(gd,gm,'');
setbkcolor(blue);cleardevice; setbkcolor(black);
setlinestyle(0,0,3);
settextjustify(centertext,centertext);
settextstyle(defaultfont,horizdir,2);
while true do begin
{output to console}
DecodeDate(Date,YY,MM,DD);
Writeln (Format ('Today is %d/%d/%d',[dd,mm,yy]));
DecodeTime(Time,HH,Mn,SS,MS);
Writeln (format('The time is %d:%d:%d.%d',[hh,mm,ss,ms]));
d2fullmoon:=yy*(365*3+366)/4+mm*365/12+dd-2014*(365*3+366)/4-2*365/12-14;
writeln ('days since full moon 14 feb 2014 ',d2fullmoon);
if ss mod 15=0 then begin {Refresh display every 15 sec. Only the second hand is refreshed every sec.}
{Draw circle and 180deg pie in yellow/black. Draw yellow or black ellipse on top. Add boxes for date}
if sin(d2fullmoon/29.530588853*2*pi)*hemisphere>0 then right:=yellow else right:=black;
left:=yellow-right;
setcolor(right);setfillstyle(solidfill,right);
fillellipse(320,240,200,200);
setfillstyle(solidfill,left);setcolor(left);
pieslice(320,240,90,270,200);
if cos(d2fullmoon/29.530588853*2*pi)>0 then centre:=yellow else centre:=black;
setcolor(centre); setfillstyle(solidfill,centre);
fillellipse(320,240,abs(trunc(200*cos(d2fullmoon/29.530588853*2*pi))),200);
setcolor (blue); setfillstyle(solidfill,blue);
bar (270,135,370,165); bar (270,345,370,315);
{fill in numbers}
for n:=1 to 12 do begin
setcolor(blue); setfillstyle(solidfill,blue);
fillellipse(319+trunc(170*sin(n*pi/6)),240-trunc(170*cos(n*pi/6)),15,15);
fillellipse(320+trunc(170*sin(n*pi/6)),240-trunc(170*cos(n*pi/6)),15,15);
moveto(322+trunc(170*sin(n*pi/6)),240-trunc(170*cos(n*pi/6)));
setcolor(white);
str(n,s);outtext(s);
end;
{fill in date}
str(yy,s);
moveto(320,330);outtext(s);
str(dd,s);
moveto(320,150);outtext(s+monthstr[mm]);
{draw hour and minute hands}
hour:=hh+mn/60; min:=mn+ss/60;
setcolor(cyan) ;setfillstyle(solidfill,cyan);
moveto(320,240);
linerel(trunc(140*sin(min*pi/30)),trunc(-140*cos(min*pi/30)));
fillellipse(320+trunc(140*sin(min*pi/30)),240+trunc(-140*cos(min*pi/30)),7,7);
moveto(320,240);
linerel(trunc(100*sin(hour*pi/6)),trunc(-100*cos(hour*pi/6)));
fillellipse(320+trunc(100*sin(hour*pi/6)),240+trunc(-100*cos(hour*pi/6)),7,7);
fillellipse(320,240,10,10);
end;
{draw second hand in XOR mode, sleep for a second, then repeat to undraw}
sec:=ss;
setwritemode(xorput); setcolor(white);
moveto(320+trunc(12*sin(sec*pi/30)),240+trunc(-12*cos(sec*pi/30)));
linerel(trunc(150*sin(sec*pi/30)),trunc(-150*cos(sec*pi/30)));
Sleep(1000);
moveto(320+trunc(12*sin(sec*pi/30)),240+trunc(-12*cos(sec*pi/30)));
linerel(trunc(150*sin(sec*pi/30)),trunc(-150*cos(sec*pi/30)));
setwritemode(copyput);
end;
closegraph;
end.
```




[Answer]
A simple one my friend wrote in TI 84 BASIC:
```
StoreGDB 0
CoordOff
GridOff
AxesOff
LabelOff
ExprOff
ClrDraw
62->Ymax
0->Ymin
94->Xmax
0->Xmin
Func
FnOff 0,1,2,3,4,5,6,7,8,9
PlotsOff 1,2,3
Full
Xmax/2->Xmax
Ymax/2->Ymax
~Xmax->Xmin
~Ymax->Ymin
Degree
15->H
18->M
20->S
Circle(36,~22,7)
Circle(0,0,30)
For(X,1,12)
Text(28-int(cos(X*30)*25),46+int(sin(30*X)*25),X)
End
{0,0,0}->|LANG
While getKey=0
getTime->|LTIME
getDate->|LDATE
Text(0,0,"12 HR")
Text(50,0,"24 HR")
If |LTIME(1)>12:Then
Text(6,7,(|LTIME(1)-12))
Else
Text(6,7,|LTIME(1))
End
If |LTIME(1)<=9
Then
Text(56,4,"O")
Text(56,8,|LTIME(1))
Else
Text(56,4,|LTIME(1))
End
Text(29,4,|LTIME(2))
If |LDATE(2)=1
Text(0,70,"JAN")
If |LDATE(2)=2
Text(0,70,"FEB")
If |LDATE(2)=3
Text(0,70,"MAR")
If |LDATE(2)=4
Text(0,70,"APR")
If |LDATE(2)=5
Text(0,70,"MAY")
If |LDATE(2)=6
Text(0,70,"JUN")
If |LDATE(2)=7
Text(0,70,"JUL")
If |LDATE(2)=8
Text(0,70,"AUG")
If |LDATE(2)=9
Text(0,70,"SEP")
If |LDATE(2)=10
Text(0,70,"OCT")
If |LDATE(2)=11
Text(0,70,"NOV")
If |LDATE(2)=12
Text(0,70,"DEC"
Text(2,81,",")
Text(0,85,|LDATE(3))
Text(8,75,|LDATE(1))
If |LTIME(1)>=12
Then
Text(50,80,"PM")
Else
Text(50,80,"AM")
End
If |LTIME(3)!=|LANG(3)/6
Line(0,0,sin(|LANG(3))*S,cos(|LANG(3))*S,0)
If |LTIME(2)!=|LANG(2)/6
Then
Line(0,0,sin(|LANG(2))*M,cos(|LANG(2))*M,0)
Line(0,0,sin(|LANG(1))*H,cos(|LANG(1))*H,0)
End
|LTIME(1)*30+|LTIME(2)/2->|LANG(1)
|LTIME(2)*6->|LANG(2)
|LTIME(3)*6->|LANG(3)
Line(0,0,sin(|LANG(1))*H,cos(|LANG(1))*H
Line(0,0,sin(|LANG(2))*M,cos(|LANG(2))*M
Line(0,0,sin(|LANG(3))*S,cos(|LANG(3))*S
End
```

[Answer]
# Mathematica
A plain-vanilla, functioning clock that displays local time:
```
Dynamic@Refresh[ClockGauge@AbsoluteTime[], UpdateInterval -> 1]
```

---
**Standard Options**

---
**Hand-drawn clock gauge**
There are alternatives to the built-in clock gauge. Here is one.
Continuous sweep has been implemented for the hour and minute hands. They update together with the second hand.
```
u[i_, k_] := {Sin[2 \[Pi] i/k], Cos[2 \[Pi] i/k]};
Dynamic[{f = Date[], Clock[{1, 1}, 1]}]
Graphics[Dynamic@{Circle[{0, 0}, 1.175], Circle[{0, 0}, 1.2],
(* tick marks at minutes *)
Table[Text[".", u[i, 60]], {i, 60}],
(* hour labels *)
Table[Text[i, u[i, 12]], {i, 12}],
(* hour hand *)
{Darker@Red, Arrowheads[.12], Thickness[.0175], Arrow[{{0, 0}, .6 u[f[[4]]+f[[5]]/60, 12]}]},
(*minute hand *)
{Blue, Arrowheads[.08], Thickness[.0085], Arrow[{{0, 0}, .85 u[f[[5]]+f[[6]]/60, 60]}]},
(*second hand *)
{Thickness[.005], Arrow[{{0, 0}, .9 u[f[[6]], 60]}]}},
BaseStyle -> 25]
```

[Answer]
Postscript - originally written to help my children to learn to tell the time. Page 1 shows the current time, pages 2-4 are pages for learners. The pages for learners use `rand` to make random times, so they are different each time you process it. Use Ghostscript to make a PDF version if you want to show the current time. Sized for A4 paper.
```
%!PS-Adobe-3.0
%%Creator: Toby Thurston
%%Title: (Pages of pedagogical clocks)
%%CreationDate: (2014-02-14)
%%BoundingBox: 12 12 583 828
%%Pages: 1
%%EndComments
<< /PageSize [595 842] >> setpagedevice
%%BeginSetup
/clock {
/mins exch def
/hour exch def
/r exch def % radius
/cr r 100 div def
% draw the minute marks
12 { .5 setlinewidth 4 { 6 rotate r 0 moveto r 20 div 0 rlineto stroke } repeat
2 setlinewidth 6 rotate r 0 moveto r 20 div 0 rlineto stroke } repeat
% numbers
/fontsize r 0.14 mul def
/Helvetica findfont fontsize scalefont setfont
/s 2 string def
/rr r 0.9 mul def
1 1 12 { /n exch def /theta 90 30 n mul sub def
/st n s cvs def st stringwidth pop /dx exch 2 div neg def
rr theta cos mul rr theta sin mul moveto dx fontsize 3 div neg rmoveto st show
} for
% draw hands (unless hour is negative)
-1 hour lt {
gsave % hour hand first
90 60 hour mul mins add 2 div sub rotate
newpath
0 2 moveto
15 cr mul 3 cr mul 33 cr mul 0 cr mul 50 cr mul 3 cr mul curveto
55 cr mul 15 cr mul 60 cr mul 0 cr mul 76 cr mul 0 cr mul curveto
60 cr mul 0 cr mul 55 cr mul -15 cr mul 50 cr mul -3 cr mul curveto
33 cr mul 0 cr mul 15 cr mul -3 cr mul 0 cr mul -2 cr mul curveto
closepath 0 0 .677 setrgbcolor fill
grestore
gsave % minute hand on top
90 6 mins mul sub rotate
newpath
0 2 moveto
15 cr mul 3 cr mul 33 cr mul 0 50 cr mul 1 cr mul curveto
65 cr mul 3 cr mul 83 cr mul 0 97 cr mul 0 curveto
83 cr mul 0 65 cr mul -3 cr mul 50 cr mul -1 cr mul curveto
33 cr mul 0 15 cr mul -3 cr mul 0 -2 cr mul curveto
closepath .635 0 0 setrgbcolor fill
grestore
} if
% finally do central dot (to cover starts of hands) and outer band
.5 setlinewidth
0 0 moveto 0 0 r 20 div 0 360 arc fill
0 0 r 1.07 mul 0 360 arc stroke
} def
%%EndSetup
%%Page: 1 1
%%BeginPageSetup
/pgsave save def
%%EndPageSetup
297 480 translate
120
(%Calendar%) /IODevice resourcestatus {
pop pop (%Calendar%) currentdevparams
dup /Running get { dup /Hour get exch /Minute get }{ 0 0 } ifelse } { -1 -1 } ifelse
clock
pgsave restore
showpage
%%Page: 2 2
%%BeginPageSetup
/pgsave save def
%%EndPageSetup
75 -55 translate
4 {
5 { 0 165 translate % a page of clocks for learners
50 rand 12 mod rand 60 mod clock
% line underneath
gsave [1 3] 0 setdash 50 neg dup 1.8 mul moveto 50 2 mul 0 rlineto stroke grestore
} repeat
146 5 165 mul neg translate
} repeat
pgsave restore
showpage
%%Page: 3 3
%%BeginPageSetup
/pgsave save def
%%EndPageSetup
75 -55 translate
4 {
5 { 0 165 translate % whole multiple of five minutes only
50 rand 12 mod rand 12 mod 5 mul clock
gsave [1 3] 0 setdash 50 neg dup 1.8 mul moveto 50 2 mul 0 rlineto stroke grestore
} repeat
146 5 165 mul neg translate
} repeat
pgsave restore
showpage
%%Page: 4 4
%%BeginPageSetup
/pgsave save def
%%EndPageSetup
75 -55 translate
4 {
5 { 0 165 translate % quarter hours only
50 rand 12 mod rand 4 mod 15 mul clock
gsave [1 3] 0 setdash 50 neg dup 1.8 mul moveto 50 2 mul 0 rlineto stroke grestore
} repeat
146 5 165 mul neg translate
} repeat
pgsave restore
showpage
%%EOF
```


[Answer]
Here is one in processing:
```
int ax,ay,bx,by,cx,cy,dx,dy,last;
int q = 1;
float c = 0;
float h = 0;
float m = 0;
void setup() {
size(displayWidth, displayHeight);
background(0);
}
boolean sketchFullScreen() {
return true;
}
void draw() {
colorMode(HSB);
fill(c,255,255,4);
noStroke();
rect(0,0,width,height);
c+=0.4;
if (c > 255) c = 0;
colorMode(RGB);
ax = int(random(displayWidth));
ay = int(random(displayHeight));
bx = ax + int(random(-50,50));
by = ay + int(random(0,50));
strokeWeight(1);
if (random(0,1)>0.5) {
fill(random(255),random(255),random(255));
stroke(random(255),random(255),random(255));
}
else {
noFill();
stroke(random(255),random(255),random(255));
}
switch(int(random(6))) {
case 0: // line
line(ax,ay,bx,by);
break;
case 1: // bezier (arc)
cx = int(random(ax-20,bx+20));
cy = int(random(ay-20,by+20));
dx = int(random(ax-20,bx+20));
dy = int(random(ay-20,by+20));
bezier(ax,ay,cx,cy,dx,dy,bx,by);
break;
case 2: // box
quad(ax,ay,ax,by,bx,by,bx,ay);
break;
case 3: // ellipse
ellipse(ax,ay,random(15,50),random(15,50));
break;
case 4: // triangle
cx = int(random(ax-20,bx+20));
cy = int(random(ay-20,by+20));
dx = int(random(ax-20,bx+20));
dy = int(random(ay-20,by+20));
triangle(cx,cy,bx,by,dx,dy);
break;
case 5: // arc
arc(ax,ay,random(15,50),random(15,50),random(2)*PI,random(2)*PI);
break;
}
float s = map(second(), 0, 60, 0, TWO_PI) - HALF_PI;
float m = map(minute() + norm(second(), 0, 60), 0, 60, 0, TWO_PI) - HALF_PI;
float h = map(hour() + norm(minute(), 0, 60), 0, 24, 0, TWO_PI * 2) - HALF_PI;
cx = width/2;
cy = height/2;
// Draw the hands of the clock
stroke(255);
strokeWeight(1);
line(cx, cy, cx + cos(s) * 500, cy + sin(s) * 500);
strokeWeight(2);
line(cx, cy, cx + cos(m) * 400, cy + sin(m) * 400);
strokeWeight(4);
line(cx, cy, cx + cos(h) * 300, cy + sin(h) * 300);
}
void mouseMoved() {
exit();
}
void keyPressed() {
background(0);
}
```

[Answer]
Simple MATLAB code, written mostly to appreciate 24-hr dial at work.
[](https://i.stack.imgur.com/WJs3x.png)
while 1
runWatch()
pause(0.6);
end
```
% 20160829 :: [[email protected]](/cdn-cgi/l/email-protection)
function runWatch()
cla;
dialHours = 24; % You can set it to 12 but why?
midnightUp = true; % defines position of midnight
col.hr = 'k';
col.mn = 'b';
col.sc = 'r';
logoStr = ['Perpetuum'];
xo = 0; yo = 0;
RH = 0.7; RM = 0.95; Rb = 0.5*(RH+RM);
RarrH = RH; RarrM = Rb; RarrS = RM;
fig_handle = findobj(allchild(0), 'flat', 'type', 'figure');
if isempty(fig_handle), set(gcf,'Position',[100 100 500 500]); end
hoursPhase = 3*pi/2; if midnightUp == true, hoursPhase = pi/2; end
hold on;
circle(xo, yo, RH,col.hr);
circle(xo, yo, RM,col.mn);% ,'b');
circle(xo, yo, (RH+RM)/2,col.mn); %0.5*[1 1 1]);
text (xo - 2.5*RH/8+0.003, yo - RH/2-0.003, logoStr,'Color',0.5*[1 1 1],'FontAngle','italic');
text (xo - 2.5*RH/8, yo - RH/2, logoStr, 'FontAngle','italic')
axis equal; axis off;
% Hour dial
dh = pi/dialHours; h = 0:-dh:-pi+dh;
xH = RH*cos(2*h+hoursPhase); yH = RH*sin(2*h+hoursPhase);
xHb= Rb*cos(2*h+hoursPhase); yHb= Rb*sin(2*h+hoursPhase);
for n=1:length(xH)
plot([xH(n),xHb(n)],[yH(n),yHb(n)],col.hr);
end
% Minute dial
dm = pi/60; m = 0:-dm:-pi+dm;
xM = RM*cos(2*m+pi/2); yM = RM*sin(2*m+pi/2);
xMb= Rb*cos(2*m+pi/2); yMb= Rb*sin(2*m+pi/2);
for n=1:length(xM)
plot([xM(n),xMb(n)],[yM(n),yMb(n)],'Color',col.mn);
end
% Labels Hour
dhl = pi/dialHours; hl = 0:-dhl:-pi+dhl; ratioH = -dialHours/180;
xHl= 0.5*(Rb+RH)*cos(2*hl+hoursPhase);
yHl= 0.5*(Rb+RH)*sin(2*hl+hoursPhase);
for n=1:length(xHl)
octagon (xHl(n), yHl(n), 0.3*(RH-Rb), 'w');
text (xHl(n),yHl(n), num2str( rad2deg(hl(n)*ratioH) ),...
'HorizontalAlignment','center','Rotation',rad2deg(2*hl(n)+hoursPhase-pi/2),...
'FontWeight','b','FontSize',13,'Color',col.hr);
end
% Labels Minute
dml = pi/12; ml=0:-dml:-pi+dml; ratioM = -60/180;
xMl= 0.5*(Rb+RM)*cos(2*ml+pi/2); yMl= 0.5*(Rb+RM)*sin(2*ml+pi/2);
for n=1:length(xMl)
octagon (xMl(n), yMl(n), 0.3*(RM-Rb), 'w');
text (xMl(n),yMl(n), num2str( rad2deg(ml(n)*ratioM) ),...
'HorizontalAlignment','center','Rotation',rad2deg(2*ml(n)), ...
'FontWeight','b','Color',col.mn);
end
octagon (xo, yo-0.5*(RH+Rb), 0.04, col.hr);
octagon (xo, yo-0.5*(RH+Rb), 0.03, col.mn);
[now_year, now_month, now_day, ...
now_hour, now_minute, now_second] = datevec(now);
% Arrows
K = -2*pi/dialHours; D = hoursPhase;
now_hour = now_hour + now_minute/60;
xarrowh = RarrH*cos(K*now_hour+D);
yarrowh = RarrH*sin(K*now_hour+D);
plot([0,xarrowh],[0,yarrowh],'Color',col.hr,'LineWidth',6);
plot([0,xarrowh],[0,yarrowh],'Color',0.5*[1 1 1],'LineWidth',3);
arrowhead (xarrowh,yarrowh,0.02,atan2(yarrowh,xarrowh),col.hr);
K = -2*pi/60; D = pi/2;
now_minute = now_minute + now_second/60;
xarrowm = RarrH*cos(K*now_minute+D);
yarrowm = RarrH*sin(K*now_minute+D);
xarrowml = RarrM*cos(K*now_minute+D);
yarrowml = RarrM*sin(K*now_minute+D);
plot([0,xarrowml],[0,yarrowml],'Color','k', 'LineWidth',4);
plot([0,xarrowml],[0,yarrowml],'Color',col.mn, 'LineWidth',2);
arrowhead (xarrowml,yarrowml,0.02,atan2(yarrowml,xarrowml),col.mn);
K = -2*pi/60; D = pi/2;
now_second = round(now_second);
xarrows = RarrH*cos(K*now_second+D);
yarrows = RarrH*sin(K*now_second+D);
xarrowsl = RarrS*cos(K*now_second+D);
yarrowsl = RarrS*sin(K*now_second+D);
plot([0,xarrowsl],[0,yarrowsl],'Color',col.sc,'LineWidth',1);
arrowhead (xarrowsl,yarrowsl,0.02,atan2(yarrows,xarrows)-pi,col.sc);
text(0.7,1,...
[pad_with(floor(now_hour),2,'0'), ':', pad_with(floor(now_minute),2,'0'), ':', pad_with(now_second,2,'0')],...
'FontSize',8,'FontWeight','n','BackgroundColor','w');
% Dial center
plot(xo, yo, 'ko','MarkerSize',10,'MarkerFaceColor','k');
plot(xo, yo, 'ko','MarkerSize',8,'MarkerFaceColor',0.5*[0 1 1]);
end
function [XX,YY] = circle(varargin)
%x and y are the coordinates of the center of the circle
%r is the radius of the circle
%0.01 is the angle step, bigger values will draw the circle faster but
%you might notice imperfections (not very smooth)
col = 'k';
x = varargin{1};
y = varargin{2};
r = varargin{3};
if length(varargin) > 3
col = varargin{4};
end
ang=0:0.01:2*pi;
xp=r*cos(ang);
yp=r*sin(ang);
XX = x+xp; YY = y+yp;
plot(XX,YY,'Color',col);
end
function octagon (xo, yo, R, col)
t = (1/16:1/8:1)'*2*pi;
x = R*cos(t);
y = R*sin(t);
fill(xo+x, yo+y,col,'EdgeColor','none')
end
% 20151001 :: [[email protected]](/cdn-cgi/l/email-protection)
% Use :: str = pad_with (num, L, pad)
% function creates a string of L length
% padded with leading 'pad' symbol
% e.g., num=23, L=4, pad='.' --> '..23';
% e.g., num='23W', L=4, pad=' ' --> ' 23W';
%
function str = pad_with (num, L, pad)
if ~ischar(num)
num = num2str(num);
end
strL = length(num);
if L<strL, L = strL; end;
for n=1:L-strL, str(n) = pad; end;
c = 0;
for n=L-strL+1:L
c = c+1; str(n) = num(c);
end
end
function [x, y] = arrowhead (xo, yo, height, alpha, col)
x(1) = xo + height*sin(alpha);
y(1) = yo - height*cos(alpha);
x(2) = xo - height*sin(alpha);
y(2) = yo + height*cos(alpha);
x(3) = xo + 2*height*cos(alpha);
y(3) = yo + 2*height*sin(alpha);
fill(x, y,col,'EdgeColor','none')
end
```
[Answer]
Demo: <http://jsfiddle.net/kelunik/Vuuq8/7/embedded/result/>
```
var h = document.getElementById('h');
var m = document.getElementById('m');
var s = document.getElementById('s');
setInterval(function () {
refreshClock();
}, 1000);
function refreshClock() {
var time = new Date;
deg = time.getSeconds() * 6 - 90;
s.style.webkitTransform = s.style.MozTransform = s.style.msTransform = s.style.transform = "rotate(" + deg + "deg)";
deg = time.getMinutes() * 6 - 90;
m.style.webkitTransform = m.style.MozTransform = m.style.msTransform = m.style.transform = "rotate(" + deg + "deg)";
deg = time.getHours() % 12 * 30 - 90;
h.style.webkitTransform = h.style.MozTransform = h.style.msTransform = h.style.transform = "rotate(" + deg + "deg)";
}
window.onload = function () {
refreshClock();
};
```
```
html, body {
margin: 0;
padding: 0;
text-align: center;
}
#clock {
width: 100vmin;
height: 100vmin;
border-radius: 50%;
border: 1vmin solid #333;
position: relative;
box-shadow: 0 0 5vmin rgba(0, 0, 0, .3);
box-sizing: border-box;
margin: 0 auto;
transform: scale(.8);
}
#h, #m, #s {
top: 50vmin;
left: 50vmin;
position: absolute;
}
#h:before, #m:before, #s:before {
content:"";
position: absolute;
left: 100%;
height: 0;
box-shadow: 0 0 2vmin rgba(0,0,0,.2);
border-radius: 50%;
}
#h:before {
width: 25vmin;
}
#m:before {
width: 35vmin;
}
#s:before {
width: 45vmin;
}
#h:before {
background: black;
height: 4vmin;
transform: translateY(-2vmin);
}
#m:before {
background: black;
height: 2vmin;
transform: translateY(-1vmin);
}
#s:before {
background: red;
height: 2vmin;
transform: translateY(-1vmin);
}
```
```
<div id="clock">
<div id="h"></div>
<div id="m"></div>
<div id="s"></div>
</div>
```
[Answer]
# HTML + CSS3 + JS
I've used mostly CSS for this clock. There is a JS component that updates the attributes on the clock div with the current time, but outside of that the entire clock is CSS.

live demo here: <http://jsbin.com/nuvag/3>
source code over here: <http://jsbin.com/nuvag/3/edit>
[Answer]
GNUPLOT
```
unset clip points
set clip one
unset clip two
set bar 1.000000
unset border
set xdata
set ydata
set zdata
set x2data
set y2data
set timefmt x "%d/%m/%y,%H:%M"
set timefmt y "%d/%m/%y,%H:%M"
set timefmt z "%d/%m/%y,%H:%M"
set timefmt x2 "%d/%m/%y,%H:%M"
set timefmt y2 "%d/%m/%y,%H:%M"
set timefmt cb "%d/%m/%y,%H:%M"
set boxwidth
set style fill empty border
set dummy t,y
set format x "% g"
set format y "% g"
set format x2 "% g"
set format y2 "% g"
set format z "% g"
set format cb "% g"
set angles radians
unset grid
set key title ""
unset key
unset label
unset arrow
unset style line
unset style arrow
set style histogram clustered gap 2 title offset 0, 0, 0
unset logscale
set offsets 0, 0, 0, 0
set pointsize 1
set encoding default
unset polar
set parametric
unset decimalsign
set view 60, 30, 1, 1
set samples 100, 100
set isosamples 10, 10
set surface
unset contour
set clabel '%8.3g'
set mapping cartesian
set datafile separator whitespace
unset hidden3d
set cntrparam order 4
set cntrparam linear
set cntrparam levels auto 5
set cntrparam points 5
set size ratio 0 1,1
set origin 0,0
set style data points
set style function lines
set xzeroaxis linetype -2 linewidth 1.000
set yzeroaxis linetype -2 linewidth 1.000
set zzeroaxis linetype -2 linewidth 1.000
set x2zeroaxis linetype -2 linewidth 1.000
set y2zeroaxis linetype -2 linewidth 1.000
set ticslevel 0.5
set mxtics default
set mytics default
set mztics default
set mx2tics default
set my2tics default
set mcbtics default
set noxtics
set noytics
set noztics
set nox2tics
set noy2tics
set nocbtics
set title "" offset character 0, 0, 0 font "" norotate
set timestamp bottom
set timestamp "" offset character 0, 0, 0 font "" norotate
set rrange [ * : * ] noreverse nowriteback # (currently [0.000000:10.0000] )
set trange [ * : * ] noreverse nowriteback # (currently [-5.00000:5.00000] )
set urange [ * : * ] noreverse nowriteback # (currently [-5.00000:5.00000] )
set vrange [ * : * ] noreverse nowriteback # (currently [-5.00000:5.00000] )
set xlabel "" offset character 0, 0, 0 font "" textcolor lt -1 norotate
set x2label "" offset character 0, 0, 0 font "" textcolor lt -1 norotate
set xrange [ * : * ] noreverse nowriteback # (currently [-10.0000:10.0000] )
set x2range [ * : * ] noreverse nowriteback # (currently [-10.0000:10.0000] )
set ylabel "" offset character 0, 0, 0 font "" textcolor lt -1 rotate by 90
set y2label "" offset character 0, 0, 0 font "" textcolor lt -1 rotate by 90
set yrange [ * : * ] noreverse nowriteback # (currently [-10.0000:10.0000] )
set y2range [ * : * ] noreverse nowriteback # (currently [-10.0000:10.0000] )
set zlabel "" offset character 0, 0, 0 font "" textcolor lt -1 norotate
set zrange [ * : * ] noreverse nowriteback # (currently [-10.0000:10.0000] )
set cblabel "" offset character 0, 0, 0 font "" textcolor lt -1 norotate
set cbrange [ * : * ] noreverse nowriteback # (currently [-10.0000:10.0000] )
set zero 1e-008
set lmargin -1
set bmargin -1
set rmargin -1
set tmargin -1
set locale "C"
set pm3d explicit at s
set pm3d scansautomatic
set pm3d interpolate 1,1 flush begin noftriangles nohidden3d corners2color mean
set palette positive nops_allcF maxcolors 0 gamma 1.5 color model RGB
set palette rgbformulae 7, 5, 15
set colorbox default
set colorbox vertical origin screen 0.9, 0.2, 0 size screen 0.05, 0.6, 0 bdefault
set loadpath
set fontpath
set fit noerrorvariables
set arrow from 0,0 to sin(`date +%M`*3.1416/30),cos(`date +%M`*3.1416/30)
set arrow from 0,0 to sin((`date +%H`%12)*3.1416/6)/2,cos((`date +%H`%12)*3.1416/6)/2
plot sin(t),cos(t)
reread
```

[Answer]
Click run. It displays only in increments of 30 minutes because the clock is a single emoji.
```
function updateTick(){let e=new Date,t=e.getSeconds()+60*e.getMinutes()+e.getHours()%12*60*60,n=parseInt(t/3600*2)+1;document.documentElement.style.setProperty("--tick",n)}let d=new Date;setTimeout(()=>{setInterval(updateTick,18e5)},1e3*(d.getMinutes()+d.getSeconds())%30),updateTick();
```
```
@counter-style item{system:cyclic;symbols:"üïõ" "üïß" "üïê" "üïú" "üïë" "üïù" "üïí" "üïû" "üïì" "üïü" "üïî" "üï†" "üïï" "üï°" "üïñ" "üï¢" "üïó" "üï£" "üïò" "üï§" "üïô" "üï•" "üïö" "üï¶"}span.tik-terk-clerk::before{content:counters(item, "", item);counter-reset:item calc(var(--tick,1))}span.tik-terk-clerk::before{font-size:72pt}
```
```
<span class="tik-terk-clerk"></span>
```
[Answer]
**Python** *(with matplotlib)*
Here's a very basic clock that runs on the desktop. Change `interval` in the 2nd to last line to `1` for continuous motion instead of one tick per second.
```
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import datetime
plt.rcParams['toolbar'] = 'None'
fig = plt.figure(figsize=(4,4),facecolor='w')
ax = plt.subplot(111, polar=True)
plt.axes().get_yaxis().set_visible(False)
#12 labels, clockwise
marks = np.linspace(360./12,360,12, endpoint=True)
ax.set_thetagrids(marks,map(lambda m: int(m/30),marks),frac=.85,size='x-large')
ax.set_theta_direction(-1)
ax.set_theta_offset(np.pi/2)
ax.grid(None)
#hands
wids = [.2,.03,.01]
lens = [.75,.9,1]
clrs = plt.cm.winter(np.linspace(0, 1, 3))
factor = [12,60,60,1]
#convert time to radians
def timedata():
x = str(datetime.datetime.now().time())
fig.canvas.set_window_title(x[:8])
data = map(lambda n: float(n), x.split(':'))+[0]
for i in range(3):
data[i]=2*np.pi*(data[i]/factor[i]+data[i+1]/factor[i+1]/factor[i])
data[i]-=(wids[i]/2)
return data[:3]
#create hands
bars = ax.bar(timedata(), lens, width=wids, bottom=0.0, color=clrs, linewidth=0)
map(lambda b: b.set_alpha(0.5), bars)
#tick
def animate(i):
map(lambda bt: bt[0].set_x(bt[1]), zip(bars,timedata()))
return bars
ani = animation.FuncAnimation(fig, animate, np.arange(1, 200), interval=1000)
plt.show()
```

[Answer]
## Mathematica
Using more demo code from the Mathematica help browser than I probably should, I get

with
```
Voltmeter3[v_, label_] :=
Graphics[{{(*case*){EdgeForm[{Thickness[.007], GrayLevel[0]}],
GrayLevel[.2],
Rectangle[{-1.2, -1.1}, {1.2, 1.3},
RoundingRadius -> .2]},(*case holes*){White,
Disk[{-1, -.9}, .05], Disk[{1, -.9}, .05], Disk[{1, 1.1}, .05],
Disk[{-1, 1.1}, .05]},(*case outer rim*){Black,
Disk[{0, .1}, 1.15], GrayLevel[.5], Disk[{-.02, .12}, 1.13],
GrayLevel[.2], Disk[{0, .1}, 1.11]},(*face highlight*)
EdgeForm[{CapForm["Round"], Thickness[.02], Hue[.125, .7, .6]}],
Hue[.125, 1, 1],
Disk[{.02, .1},
1, {1.1 Pi, -.1 Pi}],(*face shadow*){EdgeForm[{CapForm["Round"],
Thickness[.01], Hue[.125, 1, 1]}], Hue[.125, 1, 1],
Disk[{-.02, .12}, 1, {1.1 Pi, -.1 Pi}]},(*face*){EdgeForm[],
Hue[.125, .5, 1],
Rotate[Polygon[({.1, -.04} + # &) /@
Flatten[{{{0, 0}, {0, 1}},
Array[{Sin[2 Pi*(#/50)], Cos[2 Pi*(#/50)]} &, 30]}, 1],
VertexColors ->
Flatten[{Hue[.125, 0, 1],
Array[Hue[.125, .5, 1] &, 50 + 1]}]],
30/50 Pi, {0,
0}]},(*case mid line highlight*){Hue[.125, .7, .6],
Thickness[.025], CapForm["Round"],
Line[{{-.95, -.2}, {0, .1}, {.95, -.2}}]},(*case mid disk \
highlight*){Hue[.125, .7, .6], Disk[{0, 0}, .25, {.95 Pi, .05 Pi}]}},
Inset[
AngularGauge[v, {0, 100}, GaugeFaceStyle -> None,
GaugeFrameStyle -> None,
GaugeMarkers ->
Graphics[{Hue[0, 1, .7],
Polygon[{{.1, .03}, {.1, -.03}, {.95, -.03}, {1,
0}, {.95, .03}}]}],
GaugeLabels -> {Placed[
Style[label, FontFamily -> "Helvetica", Bold,
FontSize -> Scaled[.08], White], {.5, .35}]},
LabelStyle ->
Directive[FontFamily -> "Helvetica", FontSize -> Scaled[.06]],
ScaleOrigin -> {{.85 Pi, .15 Pi}, .9},
ScaleDivisions -> {2, 10},
ScaleRanges -> {{Scaled[.75], Scaled[1]}},
ScaleRangeStyle -> Hue[0, 1, .7, .7], AxesStyle -> Opacity[0],
TicksStyle -> {Thickness[.01], Thickness[.005]},
ImageSize -> Automatic, ImagePadding -> None], {0, 0}, {0,
0}, {1.75, Automatic}], {(*case mid disk*)GrayLevel[.2],
Disk[{0, 0}, .2], GrayLevel[0], Disk[{0, 0}, .075],
Disk[{-.85, -.4}, .05], Disk[{.85, -.4}, .05]}},
PlotRangeClipping -> True];
Dynamic@Refresh[
GraphicsRow[{Voltmeter3[DateList[][[4]], "Hour"],
Voltmeter3[DateList[][[5]], "Minute"],
Voltmeter3[DateList[][[6]], "Second"]}], UpdateInterval -> 1]
```
[Answer]
# C+Cairo+xcb
Basically ripped-off the postscript solution and translated to Cairo. :)
Some gotchas in doing this: ps uses degrees, Cairo uses radians; ps orients the window with +y *up*, xcb orients it with +y *down*.
```
//xclock.c
//cc $(pkg-config --cflags --libs cairo xcb xcb-icccm) -o xclock xclock.c -lcairo -lxcb -lxcb-icccm
#include <math.h>
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <cairo.h>
#include <cairo-xcb.h>
#include <xcb/xcb.h>
#include <xcb/xcb_image.h>
#include <xcb/xcb_aux.h>
#include <xcb/xcb_icccm.h>
double deg_rad (double rad){
return rad * (180.0/M_PI);
}
double rad_deg (double deg){
return deg * (M_PI/180.0);
}
typedef struct {
int width, height;
int scrno;
xcb_screen_t *scr;
xcb_connection_t *connection;
xcb_drawable_t win;
unsigned int white;
xcb_visualtype_t *visual_type;
cairo_surface_t *surface;
cairo_t *cr;
} Window;
Window window;
int makewindow()
{
xcb_screen_iterator_t iter;
xcb_depth_iterator_t depth_iter;
uint32_t mask=0;
uint32_t values[2];
window.connection = xcb_connect(NULL,&window.scrno);
iter = xcb_setup_roots_iterator(xcb_get_setup(window.connection));
for (; iter.rem; --window.scrno, xcb_screen_next(&iter))
if (window.scrno == 0)
{
window.scr = iter.data;
break;
}
window.win = xcb_generate_id(window.connection);
window.white = window.scr->white_pixel;
mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK;
values[0] = window.white;
values[1] = XCB_EVENT_MASK_EXPOSURE;
xcb_create_window(window.connection, XCB_COPY_FROM_PARENT,
window.win, window.scr->root,
0, 0,
window.width, window.height,
5,
XCB_WINDOW_CLASS_INPUT_OUTPUT,
window.scr->root_visual,
mask,
values);
xcb_icccm_set_wm_name(window.connection, window.win, XCB_ATOM_STRING, 8, strlen("xcr"), "xcr");
xcb_map_window(window.connection, window.win);
xcb_flush(window.connection);
depth_iter = xcb_screen_allowed_depths_iterator(window.scr);
for (; depth_iter.rem; xcb_depth_next(&depth_iter)) {
xcb_visualtype_iterator_t visual_iter;
visual_iter = xcb_depth_visuals_iterator(depth_iter.data);
for (; visual_iter.rem; xcb_visualtype_next(&visual_iter)) {
if (window.scr->root_visual == visual_iter.data->visual_id) {
window.visual_type = visual_iter.data;
goto visual_found;
}
}
}
visual_found: ;
{
window.surface = cairo_xcb_surface_create (window.connection,
window.win, window.visual_type, window.width, window.height);
window.cr = cairo_create (window.surface);
//cairo_select_font_face (window.cr, "serif", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_BOLD);
//cairo_set_font_size (window.cr, 32.0);
cairo_set_source_rgb (window.cr, 0.0, 0.0, 0.0);
cairo_translate(window.cr, window.width / 2, window.width / 2);
cairo_scale(window.cr, 1, -1);
//cairo_move_to (window.cr, 10.0, 50.0);
//cairo_show_text (window.cr, "Hello, world");
//cairo_surface_flush(window.surface);
//xcb_flush(window.connection);
}
return 0;
}
int destroywindow() {
cairo_destroy (window.cr);
cairo_surface_destroy (window.surface);
xcb_disconnect(window.connection);
return 0;
}
int gettime(int *hour, int *min, int *sec) {
time_t t;
struct tm *tm;
time(&t);
tm = localtime(&t);
*hour = tm->tm_hour;
*min = tm->tm_min;
*sec = tm->tm_sec;
return 0;
}
void drawclock(int x) {
int hour, min, sec;
double radius, centradius;
int i, j;
(void)x;
signal(SIGALRM, drawclock);
//hour = 0; min = 30; sec = 30;
gettime(&hour, &min, &sec);
hour %= 12;
//printf("%02d:%02d:%02d\n", hour, min, sec);
radius = (double)window.width / 2.0;
radius -= 10.0;
centradius = radius / 100.0;
// Erase
cairo_set_source_rgb(window.cr, 1.0, 1.0, 1.0);
cairo_paint(window.cr);
cairo_set_source_rgb(window.cr, 0.0, 0.0, 0.0);
// Ticks
for (i = 0; i < 12; i++){
cairo_set_line_width(window.cr, 1);
for (j = 0; j < 4; j++){
cairo_rotate(window.cr, rad_deg(6));
cairo_move_to(window.cr, radius, 0);
cairo_rel_line_to(window.cr, (double)radius / 20.0, 0);
cairo_stroke(window.cr);
}
cairo_set_line_width(window.cr, 3);
cairo_rotate(window.cr, rad_deg(6));
cairo_move_to(window.cr, radius, 0);
cairo_rel_line_to(window.cr, (double)radius / 20.0, 0);
cairo_stroke(window.cr);
}
// Hour hand
cairo_save(window.cr);
cairo_rotate(window.cr, rad_deg(90.0 - (60.0 * (double)hour + (double)min)/2));
cairo_new_path(window.cr);
cairo_move_to(window.cr, 0, 2);
cairo_curve_to(window.cr, 15.0 * centradius, 3.0 * centradius,
33.0 * centradius, 0,
50.0 * centradius, 3.0 * centradius);
cairo_curve_to(window.cr, 55.0 * centradius, 15.0 * centradius,
60.0 * centradius, 0,
76.0 * centradius, 0);
cairo_curve_to(window.cr, 60.0 * centradius, 0,
55.0 * centradius, -15.0 * centradius,
50.0 * centradius, -3.0 * centradius);
cairo_curve_to(window.cr, 33.0 * centradius, 0,
15.0 * centradius, -3.0 * centradius,
0, -2.0 * centradius);
cairo_close_path(window.cr);
cairo_set_source_rgb (window.cr, 0.0, 0.0, 0.677);
cairo_fill(window.cr);
cairo_restore(window.cr);
// Minute hand
cairo_save(window.cr);
cairo_rotate(window.cr, rad_deg(90.0 - 6.0 * (double)min));
cairo_new_path(window.cr);
cairo_move_to(window.cr, 0, 2);
cairo_curve_to(window.cr, 15.0 * centradius, 3.0 * centradius,
33.0 * centradius, 0,
50.0 * centradius, centradius);
cairo_curve_to(window.cr, 65.0 * centradius, 3.0 * centradius,
83.0 * centradius, 0,
97.0 * centradius, 0);
cairo_curve_to(window.cr, 83.0 * centradius, 0,
65.0 * centradius, -3.0 * centradius,
50.0 * centradius, -1.0 * centradius);
cairo_curve_to(window.cr, 33.0 * centradius, 0,
15.0 * centradius, -3.0 * centradius,
0, -2.0 * centradius);
cairo_close_path(window.cr);
cairo_set_source_rgb (window.cr, 0.635, 0.0, 0.0);
cairo_fill(window.cr);
cairo_restore(window.cr);
cairo_surface_flush(window.surface);
xcb_flush(window.connection);
//printf("alarm in %d\n", 60 - sec);
alarm(60 - sec);
}
int main(int argc, char **argv)
{
xcb_generic_event_t *e;
window.width = window.height = 200;
signal(SIGALRM, drawclock);
makewindow();
while (e = xcb_wait_for_event(window.connection)){
switch(e->response_type & ~0x80){
case XCB_EXPOSE:
drawclock(0);
}
free(e);
//sleep(1);
}
destroywindow();
return 0;
}
```

[Answer]
Creating analog clocks has some sort of attractions with people learning programming. As a matter of fact I teach a JavaScript class this year and my students had ton of fun when we implemented an analog clock using p5.js...
[](https://i.stack.imgur.com/e51t9.png)
The source code for the analog clock is available at <https://github.com/mveteanu/JSCourse>
] |
[Question]
[
## Task
You're in charge of making a compass, of sorts.
Imagine your source code as the compass "needle" where running at different orientations produces distinct output.
Supported source code orientations are North, East, South, and West.
## Example
Let's say you have source code:
```
ABCD
J K
WXYZ
```
We'll consider this the North orientation, rotating 90 degrees clockwise points us to the East:
```
W A
XJB
Y C
ZKD
```
rotating again points South:
```
ZYXW
K J
DCBA
```
and finally, the last rotation to the West:
```
DKZ
C Y
BJX
A W
```
When ran, each of the above code examples should output a single, distinct [printable ASCII](http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters) character of your choosing.
## Notes
Your code shall take no input.
Empty spaces or new lines do not collapse/disappear when rotating.
Leading/trailing new lines are okay in output.
Answers may be whole programs or functions, thus output to STDOUT or return the function result.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply; shortest answer in bytes wins!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 2 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
*2
```
**[Try it online!](https://tio.run/##y0rNyan8/1/L6P9/AA "Jelly – Try It Online")**
Note that the main entry for a Jelly program is its last link, where any newline character will split links), neither of the two-line programs actually access their top link.
The four full programs, all of which implicitly print their result, are:
[North](https://tio.run/##y0rNyan8/1/L6P9/AA "Jelly – Try It Online"):
```
*2 -> (implicit) zero raised to the power of 2 = 0
```
[East](https://tio.run/##y0rNyan8/1@Ly@j/fwA "Jelly – Try It Online"):
```
*
2 -> literal 2 = 2
```
[South](https://tio.run/##y0rNyan8/99I6/9/AA "Jelly – Try It Online"):
```
2* -> two raised to the power of (implicit) 2 = 4
```
[West](https://tio.run/##y0rNyan8/9@IS@v/fwA "Jelly – Try It Online"):
```
2
* -> (implicit) zero raised to the power of (implicit) zero = 1
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~3~~ 2 bytes
```
gy
```
Somehow, *somehow*, I found an extremely hacky 2-byte solution...
---
[North](http://ethproductions.github.io/japt/?v=1.4.5&code=Z3k=&input=) outputs `0`:
```
gy
```
Since there's no implicit input, it defaults to `0`. `g` on a number returns the sign of the number regardless of its arguments (`"y"` in this case).
---
[East](http://ethproductions.github.io/japt/?v=1.4.5&code=Zwp5&input=) outputs `2`:
```
g
y
```
In a multi-line program, the first line sets the input to its result. This is basically a no-op, since `g` on `0` is `0`. Then `y` returns the GCD of `0` and... since it's missing an argument, it defaults to `2` (thanks, [@Oliver](https://chat.stackexchange.com/transcript/message/39035566#39035566)!). This gives `2` as the output.
---
[South](http://ethproductions.github.io/japt/?v=1.4.5&code=eWc=&input=) outputs `g`:
```
yg
```
`y`, as before, is GCD. Since **gcd(0, x)** is **x** for any value, `y` on `0` takes the liberty of just returning its argument. In this case, the argument is `"g"`, which is the result.
---
[West](http://ethproductions.github.io/japt/?v=1.4.5&code=eQpn&input=) outputs `1`:
```
y
g
```
`y` on 0, as before, returns `2`. This is then passed to `g`, which (as already discussed) is the sign function on numbers. Therefore, the result is `1`.
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), ~~7309~~ ~~4421~~ 855 bytes
-2888 bytes thanks to Leaky Nun
-3566 bytes thanks to Wheat Wizard
```
//i/////////////////////////////////////////////////////////////
//n//////////////////////////////////////////////////////////////////
interface M{static void main(String[]a){System.out.println(0);}}/////
//e//}};)2(nltnirp.tuo.metsyS{)a][gnirtS(niam diov citats{M ecafretni
//r//////////////////////////////////////////////////////////////////
//f}/////////////////////////////////////////////////////////////////
//a}//
//c;//
//e)//
// 3//
//M(//
//{n//
//sl//
//tt//
//an//
//ti//
//ir//
//cp//
// .//
//vt//
//ou//
//io//
//d.//
// m//
//me//
//at//
//is//
//ny//
//(S//
//S{//
//t)//
//ra//
//i]//
//n[//
//gg//
//[n//
//]i//
//ar//
//)t//
//{S//
//S(//
//yn//
//si//
//ta//
//em//
//m //
//.d//
//oi//
//uo//
//tv//
//. //
//pc//
//ri//
//it//
//na//
//tt//
//ls//
//n{//
//(M//
//1 //
//)e//
//;c//
//}a//
//}f//
///r//
///e//
//t//
//n//
//i//
```
[Try it online!](https://tio.run/##rZI9boUwEIR7TuHSLoLzU3IGKkpEYYFBfgEbmQUJIZ@dkB0ipX/PzSetZ2dnDQ@zmbcwW//ovs9Ta6efOZnWXj99MufJxt60VpTHQoZcK7bgOjEZ52VF0fmhbow6qn0hO@VhpXy@ijR6@a6KlP6yWK1TKtSn9CN5F@ec1pBPlpa9OpRp6uEqUiW9M5PoXNhE665py1EK25o@2qvpcokv2EjrPr3CxSRGW2A/xRBfjFIyDs9YRgYR@lAkx3ARLjPac8YGZVghCYwOd2JiTBZmULoFH3xnyIpRHRiEZNFA2UBZM4aBUSNSg0gGkRSsj9sMG@33RlASPO0dSTDyDuEhWRGeNtxBMreIdD8BBnnz/5XGeyPsIEvGB9oVdi/gktCXeoZG@N//LbvUBHjgmneePw "Java (OpenJDK 8) – Try It Online")
[Old version](https://tio.run/##pZgxboQwFET7PYVLKAKbpOQMVJSIwgKDvAGD4IOELM5OkH2E5xJpn8yf@TNoP/rQX/Ni3Kf7u@88tzk7rzx3FGGdmLXXrVGl30SLbdUx205N2rqkktW6oW506qtzEzNl8y7Z8jyU0SXvtLiucAujwImIlSCKgOgJIg0ITRC/AdESRMLH6QKCENQYECVBSEB4/iIbQdiAEIJYuS8WfossICxXBLlz59aaA@Lgs5gJYuLjNAHRcUXQOLeAmAji5Aav@Dh9bDOe4AlB6ICoCKLhy17zQhy4Io4rEuN34PFb8zVruMHRjsRmT7kinitS8R05efyiZld8zTr@rWV5/MZCzAji4IUYx7kTQssVsXwWcdkXbvCV3wLF78bj13NFyoAYubXQixje7NGd39wXKMH7gCh4IV58nNdVpD@JG8XZdclkn7PJyHZWPtVNPTwPpUqc1ZPq7Hyo1oqWzZfKtLpfzfOjF/znIbYZOk9e3Pc/ "Java (OpenJDK 8) – Try It Online")
Straightforward aproach with comments wrapping the code^2 square, this can be done in pretty much any language.
a (more readable) example in python
```
##p#####
# r 2 #
print 1#
# n t #
# t n #
#4 tnirp
# 3 r #
#####p##
```
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 33 bytes
```
##)(##))()() ((
(( ))## ()##
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/X1lZUwOINTWAUEFBQ4NLQ0NBQVNTWVkBCDSA9H8NDU1NoChYBZiAcFDF/gMA "Brain-Flak – Try It Online")
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 33 bytes
```
##) ## #
(( ))#)())()
# ( (
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/X1lZUwEElJUVlLk0NBQ0NZU1NTSBiAsopqChoPH/PwA "Brain-Flak – Try It Online")
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 36 bytes
```
#)## ## #
(())#)())()
# ( (
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/X1lTWVkBBICUMpeCgoaGpqayJpDQ0ORSAMloKGj8/w8A "Brain-Flak – Try It Online")
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 38 bytes
```
###### (#
(()()())#))((
#( ##
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/XxkMFBQ0lLk0NDRBUFNZU1NDg0sBApQ1gFj5/38A "Brain-Flak – Try It Online")
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 41 bytes
```
##(#####(#
(()()())#
##))()((
####((#)#)#
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/X1lZQxkENJS5NDQ0QVBTWVOZS1lZE8TR4ALLaSiDBP//BwA "Brain-Flak – Try It Online")
[Answer]
# [Alice](https://github.com/m-ender/alice), 17 bytes
```
1/ 3<
vPo</
5} @<
```
Outputs `1`. [Try it online!](https://tio.run/##S8zJTE79/99QX8HYhqssIN9Gn8u0VsHB5v9/AA "Alice – Try It Online")
```
5v1
}P/
o
@<3
</<
```
Outputs `x`. [Try it online!](https://tio.run/##S8zJTE79/9@0zJCrNkCfSyFfgcvBxpjLRt/m/38A "Alice – Try It Online")
```
<@ }5
/<oPv
<3 /1
```
Outputs `5`. [Try it online!](https://tio.run/##S8zJTE79/9/GQaHWlEvfJj@gjMvGWEHf8P9/AA "Alice – Try It Online")
```
</<
3<@
o
/P}
1v5
```
Outputs `3`. [Try it online!](https://tio.run/##S8zJTE79/99G34bL2MaBSyFfgUs/oJbLsMz0/38A "Alice – Try It Online")
[Answer]
# Befunge, ~~17~~ 13 bytes
I thought Befunge would be fun for a geometrical problem. There is a trivial 4x4 solution akin to others here (I need 3 commands) but I managed a bit better.
*Edit: forgot about newlines*
*Edit 2: realized I could create a cat*
*Edit 3: the cat is dead*
```
2v3
@.v
.
1@.
```
RIP kitty :<
```
1.@ 2
^._.^
3 @.4
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~5~~ 3 bytes
```
Y'X
```
[North](https://tio.run/##MzBNTDJM/f8/Uj3i/38A), [East](https://tio.run/##MzBNTDJM/f8/kkudK@L/fwA), [South](https://tio.run/##MzBNTDJM/f8/Qj3y/38A), [West](https://tio.run/##MzBNTDJM/f8/gkudK/L/fwA)
[Answer]
# [Lost](https://github.com/Wheatwizard/Lost), 45 bytes
```
v////v1//v(((
\(((%>2@0>%(((\
(((v//3v////v
```
[Try it online!](https://tio.run/##y8kvLvn/v0wfCMoMgVhDQ4MrBkio2hk5GNipAlkxXAoKQAqoxBii7P///7qBAA "Lost – Try It Online")
To recap the gimmick of lost from the esolangs wiki:
>
> Lost is a 2-Dimensional language where the instruction pointer starts at a random location, moving in a random direction. Despite this, Lost is still capable of creating completely deterministic programs.
>
>
>
So at first glace, Lost is perhaps not the ideal language for this challenge because of its incredible fragility.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 283 279 209 bytes
```
/////////)pm//
/////////;ua//
main(){//}ti//
puts("N"//sn//
);}///////((//
//////////")//
///"//////W{//
///E//////"///
//)"//////////
//((///////};)
//ns//"S"(stup
//it}//{)(niam
//au;/////////
//mp)/////////
```
[Try it online!](https://tio.run/##Tc0tDgQhDAVgP8eoasXmHQA9dsyK1QQxQUBIAEU4O9sM81f3pe@17rM7NwaukRSA5aapVhmsjywN6MUrUy2ZaSMgR6WYfqaZ312QTNLkr02u5xYHhZ7CMk8c040oY9bglziXmpS@6KsmHL0NSlvNuxuS3BzjDw "C (gcc) – Try It Online")
Same old comment trick here, but at least, in C this doesn't get **huuuge** ;)
* -4, thanks to [ETHproductions](https://codegolf.stackexchange.com/users/42545/ethproductions)!
* fixed `W` direction and -70 (!) bytes thanks to comments by [ETHproductions](https://codegolf.stackexchange.com/users/42545/ethproductions)
[Answer]
# [Starry](https://esolangs.org/wiki/Starry), 34 bytes
```
zz
+
.
+
```
Or with spaces shown as hyphens so you can see them:
```
--zz--
--+---
---.--
----+-
------
```
[Try it online!](https://tio.run/##Ky5JLCqq/P9fQaGqSkGBS0FBWwFMKehBKCAfTCko/P8PAA "Starry – Try It Online")
The commands in Starry are `+`, `.` and some other things, and what they do is determined by how many spaces there are before them: a `+` with *n* spaces pushes *n*−5 to the stack, and `.` with an even number of spaces prints it. The `z`s and newlines are ignored entirely.
There are 6 spaces before the first `+` so it pushes 6−5 = 1, and the `.` prints it.
And the rotations:
```
-----
-----
---+z
--.-z
-+---
-----
```
[Try it online!](https://tio.run/##Ky5JLCqq/P9fAQS44KR2FZDUUwCS2nDx//8B "Starry – Try It Online") This prints "8".
```
------
-+----
--.---
---+--
--zz--
```
[Try it online!](https://tio.run/##Ky5JLCqq/P9fAQy4FLQhlIIehALxgVRVlYLC//8A "Starry – Try It Online") This prints "2".
```
-----
---+-
z-.--
z+---
-----
-----
```
[Try it online!](https://tio.run/##Ky5JLCqq/P9fAQS4gFhbgatKQQ/IrtKGisDI//8B "Starry – Try It Online") And this prints "3".
[Answer]
## [Labyrinth](https://github.com/m-ender/labyrinth), 9 bytes
```
!
2@2
!)
```
Prints `0`. [Try it online!](https://tio.run/##y0lMqizKzCvJ@P9fkcvIwYhLQVHz/38A "Labyrinth – Try It Online")
```
2)
@!
!2
```
Prints `3`. [Try it online!](https://tio.run/##y0lMqizKzCvJ@P9fwUiTS8FBkUvR6P9/AA "Labyrinth – Try It Online")
```
)!
2@2
!
```
Prints `1`. [Try it online!](https://tio.run/##y0lMqizKzCvJ@P9fU5HLyMGIS0FB8f9/AA "Labyrinth – Try It Online")
```
2!
!@
)2
```
Prints `2`. [Try it online!](https://tio.run/##y0lMqizKzCvJ@P9fwUiRS9GBS9Po/38A "Labyrinth – Try It Online")
### Explanation
Each program starts at the first non-space in reading order (i.e. either the top left or top centre character), moving east. For the first program:
```
! Print an implicit zero.
The IP can't move east, so it moves south instead.
2 Push a 2.
The IP can't keep going south, so it turns east instead.
@ Terminate the program.
```
For the second program:
```
2 Push a 2.
) Increment it to 3.
The IP can't keep going east, so it turns south instead.
! Print the 3.
The IP can't keep going south, so it turns west instead.
@ Terminate the program.
```
For the third program:
```
) Increment an implicit zero to 1.
! Print the 1.
The IP can't keep going east, so it turns south instead.
@ Terminate the program.
```
For the fourth program:
```
2 Push a 2.
! Print the 2.
The IP can't keep going east, so it turns back around to move west.
2 Push another 2.
The IP can't keep going west, so it turns south instead.
@ Terminate the program.
```
[Answer]
## [Wumpus](https://github.com/m-ender/wumpus), 7 bytes
```
O@$
)))
```
Prints `0`. [Try it online!](https://tio.run/##Ky/NLSgt/v/f30GFS1NT8/9/AA "Wumpus – Try It Online")
```
)O
)@
)$
```
Prints `1`. [Try it online!](https://tio.run/##Ky/NLSgt/v9f059L04FLU@X/fwA "Wumpus – Try It Online")
```
)))
$@O
```
Prints `3`. [Try it online!](https://tio.run/##Ky/NLSgt/v9fU1OTS8XB//9/AA "Wumpus – Try It Online")
```
$)
@)
O)
```
Prints `2`. [Try it online!](https://tio.run/##Ky/NLSgt/v9fRZPLQZPLX/P/fwA "Wumpus – Try It Online")
### Explanation
The first program is easy enough: `O` prints an implicit zero and `@` terminates the program.
Starting at the second program, we need to look at the triangular grid layout to understand the control flow:
[](https://i.stack.imgur.com/dMQB9.png)
```
) Increment an implicit zero to 1.
O Print the 1.
)) Two irrelevant increments.
@ Terminate the program.
```
For the third program:
[](https://i.stack.imgur.com/jCi2j.png)
```
))) Increment an implicit zero to 3.
O Print the 3.
@ Terminate the program.
```
The fourth one is where it gets really funky. Dashed lines indicate cells that aren't executed because they are skipped by the `$`:
[](https://i.stack.imgur.com/zH5yt.png)
```
$ Skip the ).
$ Skip the @.
)) Increment an implicit zero to 2.
O Print the 2.
)) Two irrelevant increments.
@ Terminate the program.
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~20~~ 11 bytes
```
#4#
1#3
#2#
```
Abuses comments (`#`) like crazy, and the fact that a single number placed onto the pipeline gets output as-is. The above prints `1`. [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X9lEmctQ2ZhL2Uj5/38A "PowerShell – Try It Online")
From here, you can easily see that each rotation yields only one number that's on the "left" of the comments, and so there's only one number that will be output per rotation.
*Saved 9 bytes thanks to [Wheat Wizard](https://codegolf.stackexchange.com/users/56656/wheat-wizard)!*
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 9 bytes
```
1
2p3
4
```
[Try it online!](https://tio.run/##S0n@/1/BkMuowJhLweT/fwA "dc – Try It Online")
I think its obviousness is part of the charm.
[Answer]
# [Cardinal](https://www.esolangs.org/wiki/Cardinal), ~~20 17 12~~ 11 bytes
```
.$
Z%"
+$v
```
[Try it online!](https://tio.run/##S04sSsnMS8z5/19PhStKVYlLW6WM6/9/AA "Cardinal – Try It Online")
All this time and no-one answered in Cardinal? This first one outputs `0`.
### East
```
+Z.
$%$
v"
```
[Try it online!](https://tio.run/##S04sSsnMS8z5/19BO0qPS0FFVYVLoUzp/38A "Cardinal – Try It Online")
Outputs `1`.
### South
```
v$+
"%Z
$.
```
[Try it online!](https://tio.run/##S04sSsnMS8z5/5@rTEWbS0k1iktBRe//fwA "Cardinal – Try It Online")
Outputs a space.
### West
```
"v
$%$
.Z+
```
[Try it online!](https://tio.run/##S04sSsnMS8z5/19BqYxLRVWFSy9K@/9/AA "Cardinal – Try It Online")
Outputs `v`.
[Answer]
## Batch, 90 bytes
```
:: :::@:
:&s ohce@
:e : c:
:h:
:o o:
:h:
:c : w:
@echo n&:
:@::: ::
```
Batch doesn't really have a comment character. For whole-line comments, `:` works, as it introduces a label, but I still need something to terminate the `echo` command while being a no-op when reversed. `&:` seems to work, which is all I need here, but it really confuses Batch, erroring out if I don't put a `:` before the `@` on the next line, and also somehow forgetting to print a newline.
[Answer]
# JavaScript (ES6), 86 bytes
Outputs 0 for North, 1 for East, 2 for South, and 3 for West.
```
//// _//
//// =//
_=>0//>//
////1//
// //
//3////
//>//2>=_
//= ////
//_ ////
```
```
const source =
`//// _//
//// =//
_=>0//>//
////3//
// //
//1////
//>//2>=_
//= ////
//_ ////`;
function rotateTextCW(text) {
const lines = text.split("\n");
const maxLineLength = lines
.map(line => line.length)
.reduce((max, len) => Math.max(len, max), 0);
const paddedLines = lines.map(line => line.padEnd(maxLineLength));
const charGrid = paddedLines.map(line => line.split(""));
const rotatedGrid = [...new Array(maxLineLength)]
.map(v => new Array(charGrid.length));
for (let i = 0; i < charGrid.length; i++) {
for (let j = 0; j < charGrid[i].length; j++) {
rotatedGrid[j][charGrid.length - i - 1] = charGrid[i][j];
}
}
return rotatedGrid
.map(chars => chars.join("").trimRight())
.join("\n");
}
const orientations = ["North", "East", "South", "West"];
let rotatedSource = source;
let markup = "";
orientations.forEach(orientation => {
const code = `<pre>${rotatedSource}</pre>`;
const result = `<code>${eval(rotatedSource)()}</code>`;
const row = `
<td>${orientation}</td>
<td>${code}</td>
<td>${result}</td>`;
markup += `<tr>${row}</tr>`;
rotatedSource = rotateTextCW(rotatedSource);
});
document.querySelector("table tr:first-child")
.parentNode
.innerHTML += markup;
```
```
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="container">
<table class="table table-striped table-responsive">
<tr>
<th>Orientation</th>
<th>Source</th>
<th>Result</th>
</tr>
</table>
</div>
```
[Answer]
# MATLAB, ~~29 17 5~~ 11 bytes
Having realised that the question called for single ASCII characters not just a distinct output, here is a MATLAB approach which will do just that:
```
%4%
1%3
%2%
```
This will implicitly print 1, 2, 3, or 4 depending on the rotation.
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), 4 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
5H
I
```
Outputs `1`, [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=NUglMEFJ)
```
I5
H
```
Outputs `H`, [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=STUlMEElMjBI)
```
I
H5
```
Outputs `5`, [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JTIwSSUwQUg1)
```
H
5I
```
Outputs `6`, [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=SCUwQTVJ)
[Answer]
# [MATL](https://github.com/lmendo/MATL), 11 bytes
```
HxI
xFx
TxK
```
[Try it online!](https://tio.run/##y00syfn/36PCk6vCrYIrpML7/38A "MATL – Try It Online")
Let's get this started in MATL. The main challenge is that MATL just fails if a function requires input if the stack is empty. Perhaps something clever with modifiers like `X`, `Y`, `Z` and `&` could make for something shorter, but I couldn't find a suitable combination.
Explanation: all characters push a single integer on the stack, and `x` removes all of them but the last.
[Answer]
## Perl, 49 bytes
**48 bytes code + 1 for `-p`.**
Assumes empty input which TIO doesn't support, so a newline is added in its place and not used. Prints [N](https://tio.run/##K0gtyjH9/19ZQRkIuJSDbRXiVbiUrRXClbkUVOJt/YBi8QrxQNJWQQVIugKFlYGK///n@pdfUJKZn1f8X7cAAA), [E](https://tio.run/##K0gtyjH9/19ZRUFZAQi4lOOV/ZSVFZS5lBXCbeNVQCK2CvEKCsrKXArB1irxtq5AKZACIP7/n@tffkFJZn5e8X/dAgA), [S](https://tio.run/##FYkhDoBADAR9X7HJ1iJRpBKLQSCrECQXrgHeTyljJpmJ/WpjJggSAoAzBVTYL4dTuJhrPW6YKOqwtWIBZsrb4zn6eecQHw), [W](https://tio.run/##K0gtyjH9/19BWVkZhLmUXW3jVayDFbiAfIV4BVtlLgUFlXjbcAWgFFCBn3I8SERBQVlBRfn/f65/@QUlmfl5xf91CwA).
```
# ####
#S= _$
#; W#
$_=N#
#_ _#
#= $#
#E#
## #
```
[Try it online!](https://tio.run/##K0gtyjH9/19ZQRkIuJSDbRXiVbiUrRXClbkUVOJt/YBi8QrxQNJWQQVIugKFlYGK///n@pdfUJKZn1f8X7cAAA "Perl 5 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 120 bytes
I had hoped for more synergy between the variants.
```
//}=)f8 ///
// c{(7 ///
;rr; //}
;c=
78; /// r{)
f(r /// r(f
){r /// ;38
=c;
}// ;rr;
/// 9({c //
/// 6f)=}//
```
[North](https://tio.run/##Jc0xCsMwDAXQuTqFCBQkaNBQaFyEb9KlCBQy1BTTzfjsru1oevqCL1t3s9ZEamQPKCIgglZom0ZEzVm76/ActQhbGJlgLgxO@TQ5cDmt9wDRFOpwL4ARPqkYzgeCD@fYj@1IP/y8j0QMBS7f3Hen5WqvtNzQibl3tD8 "C (gcc) – Try It Online")
[East](https://tio.run/##NYzBCgIxDETP5ivCgpCASw6CWwn9Ey8SyLIHixRvpd/era6d0xuGNzavZq2J1Mi@IIqAiFihMFhzVkSsgP@oRbjdtc@CuTA45YPJgcvBugSIpkOB@vX6kfw@Ea9UbHBwjlWkbemDr@eWiKHA6Z17d5rO9kjTBZ2YFWrbAQ "C (gcc) – Try It Online")
[South](https://tio.run/##Nc2xCgMxCAbguT6FHBQUWhwKvRTJm3QpguWGhhK6hTx7LslRp89fVLu@zVoTqZH9jiICImiFHtOIqDlrdx2epRYh3EYmmAuDUz5MDlwOa1ghmv5XoI5sHOoe85WK4fwlGJxjn7ct/fDz2hIxFDh9c@@dlrM903JBJ2aF2nY "C (gcc) – Try It Online")
[West](https://tio.run/##NYzBCgIxDETP5ivCgpCASw6CWwn9Ey8SyLIHixRvpd/era6d0xuGNzavZq2J1MgeEEVARKzQdbDmrIhYAf9RixAW7bNgLgxO@WBy4HKw3m8QTYcC9ev1I/l9IgYqNnhxjlWkbemDr@eWiKHA6Z17d5rO9kjTBZ2YFWrbAQ "C (gcc) – Try It Online")
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 11 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
Þ2Þ
3 1
Þ0Þ
```
A bit boring, but since MathGolf implicitly outputs the entire stack joined together, I'm not sure if something shorter is possible here..
[Default](https://tio.run/##y00syUjPz0n7///wPKPD87iMFQy5Ds8zODzv/38A); [rotated once clockwise](https://tio.run/##y00syUjPz0n7///wPOPD87gMFIy4Ds8zPDzv/38A); [rotated two times clockwise](https://tio.run/##y00syUjPz0n7///wPIPD87gMFYy5Ds8zOjzv/38A); [rotated three times clockwise](https://tio.run/##y00syUjPz0n7///wPMPD87iMFAy4Ds8zPjzv/38A).
**Explanation:**
* `0123`: These push the digit to the stack
* : This pushes a space character to the stack
* `Þ`: This empties the stack except for the top value
And in the end the entire stack joined together is output implicitly as result.
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 72 bytes
```
++
+++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++++++++
+
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fW5tLmxDQI6iCS/v/fwA "brainfuck – Try It Online")
[Try it rotated once!](https://tio.run/##SypKzMxLK03O/v9fW1ubSwGMaYn0aGw@CP3/DwA "brainfuck – Try It Online")
[Try it rotated twice!](https://tio.run/##SypKzMxLK03O/v9fgWKgzaVNCOgRVMFFuTO0//8HAA "brainfuck – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 69 bytes
```
_=>0//
/* *_
/ =
1 >
> 3
= /
_* */
//2>=_
```
[Try it online!](https://tio.run/##JczLCoAgEIXh/TzFLFWo6bIeX0XEJApRSen1LfRffYvDue1ri3uuXKeYDt9ciqViRm5oWC9EQAr/lAHCHsM6oEEP7MADBGaMCZBo02z6Xwp@DukUWUjZPg "JavaScript (Node.js) – Try It Online")
This approach should work for any language with C-style comments.
[Answer]
# [MAWP](https://esolangs.org/wiki/MAWP), 5 bytes
## North: 3
```
2M:
2
```
[Try it!](https://8dion8.github.io/MAWP/v1.1?code=2M%3A%0A2&input=)
## East: 4
```
22
M
:
```
[Try it!](https://8dion8.github.io/MAWP/v1.1?code=2M%3A%0A2&input=)
## South: 2
```
2
:M2
```
[Try it!](https://8dion8.github.io/MAWP/v1.1?code=2M%3A%0A2&input=)
## West: 1
```
:
M
22
```
[Try it!](https://8dion8.github.io/MAWP/v1.1?code=2M%3A%0A2&input=)
The existing 1 in the stack is very convenient here.
[Answer]
# [Python 2](https://docs.python.org/2/), 71 bytes
```
##p#####
# r 2 #
print 1#
# n t #
# t n #
#4 tnirp
# 3 r #
#####p##
```
[Try it online!](https://tio.run/##bY5RDoAgDEP/OUWTnYDBoeQHCdmPp8ehMCW6r6aU15ZDtj1za0SF@jlCBRjkSk1Z4LuTAUEXAtUqIiSnWtQJ0Lw6/ZTgHkWI4y1Yev6fxLuDR6u/QGOHWxdFS4ffRWwd/rvoDQoGir8gbyBeQa2d)
Big thanks to [this answer!](https://codegolf.stackexchange.com/questions/137588/cardinal-code-challenge/137618#137618)
Note I **did not** copy it directly, but actually had a program in mind and golfed it with this.
] |
[Question]
[
[Vyxal](https://github.com/vyxal/vyxal) is a stack-based language, meaning that everything operates by popping and pushing values onto a stack. It has a bunch of useful flags, one of which is `r`.
Running a Vyxal program with the `r` flag causes functions to take their elements in reverse order.
For example, the program `5 3 -` means: Push 5 to stack, push 3 onto the stack, and subtract them by popping 3, popping 5, and subtracting the 3 from the 5 to yield 2. But with the `r` flag, it first pops the 5, then the 3, and subtracts 5 from 3 to yield -2.
For this challenge, we will be operating within a much-simplified version of Vyxal.
The digits 0-9 each push themselves to the stack , and lowercase letters are *dyadic* functions, meaning they pop two values from the stack and do something with them, before pushing the result. Everything else does nothing and won't be included in the input.
Your challenge is to take a program with this format and output a program that would do the same thing if the input order of each function is reversed.
This sounds complicated, so let's demonstrate with this example:
```
87a
```
To do this, we simply swap the 8 and the 7 to yield `78a`.
A more complicated example:
```
54a78bc
```
How it works:
```
c # c is a function taking...
78b # This, where:
b # b is a function taking
78 # 7 and 8
# And...
54a # This, where:
a # a is a function taking...
54 # 5 and 4
```
So to flip it, we just flip the operands of every function:
```
<-->
<->|| c
|| 78b
54a |
| |
<-->
```
Yielding:
```
87b45ac
```
Which is the result!
Another way to explain this is:
An operator is one of `a-z`
A token is either a single digit, or of the format [TOKEN][TOKEN][OPERATOR]
For each token of the format [TOKEN][TOKEN][OPERATOR], flip the two tokens.
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest wins!
# Testcases
You can assume there will always be two values to pop whenever there's a function/operator.
```
123ab => 32a1b
59a34bz => 43b95az
123456abcde => 65a4b3c2d1e
1 => 1
12a53bx7c08d9ef => 980de735b21axcf
12a34bc56d78efg => 87e65df43b21acg
```
As usual, these are created by hand, so please tell me if they're wrong.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~15~~ ~~12~~ ~~10~~ 9 bytes
-1 byte thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)!
This could be 8 bytes without the `l`, but why would I remove that?
```
**vyxal**iŠìì
```
[Try it online!](https://tio.run/##yy9OTMpM/V9TVvm/rLIiMSfz6ILDaw6v@V9bq/Pf0Mg4MYnL1DLR2CSpigvIMzE1S0xKTknlMgTyEk2NkyrMkw0sUixT00B8oKpkU7MUc4vUtHQA "05AB1E – Try It Online")
```
v # for each character y:
y # push y
x # duplicate TOS and double the copy
# double is a noop on alphabetic strings
a # is the doubled copy alphabetic / the current char a function?
l # convert the result to lowercase
i # if the command was a function:
# stack before: [..., x1, x2, f]
Š # triple-swap: [..., f, x1, x2]
ì # prepend: [..., f, x2x1]
ì # prepend: [..., x2x1f]
```
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 83 bytes
```
,[[>+>>>++++[>]<-<<[>]<<-]>>>>[-]<[+<<<<[<]<[[->+<]<]>+[>]>-[<<[<]>+[>]>-]]<,]<[.<]
```
[Try it online!](https://tio.run/##LYpJCoBAEAMfNNOCu4eQjzR9cBsRwYPg@8dWrEuSItM17me65yPnqMpAMjhKgwBvQMwlVQwa4Ci8qTB4Gt8rRT/9DzNEvxSwnMtqrJtpbrulH9a0PQ "brainfuck – Try It Online")
Maintains a stack of tokens. When an operator is read, append it to the top two tokens on the stack. Each token should be read from right to left.
```
For each character in input:
,[
Move forward one cell and compare to 85
[>+>>>++++[>]<-<<[>]<<-]
Clean up comparison cell
>>>>[-]<
If greater than 85 (and thus is operator):
[
Remove comparison result
+
Append last two tokens together
<<<<[<]<[[->+<]<]>
Append operator to end of this token
+[>]>-[<<[<]>+[>]>-]
]
<
,]
<[.<] output result
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), ~~18~~ ~~12~~ 8 bytes
```
(n:Ǎ[∇pp
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%28n%3A%C7%8D%5B%E2%88%87pp&inputs=123ab&header=&footer=)
*-5 thanks to @AUsername*
*and -1 to an extra golf on that golf*
*but then another -4 from A Username*
The irony here is that using the `r` flag makes this way too long.
## Explained
```
(n:Ǎ[∇pp
( # for each character in the input:
n:Ǎ # remove all letters from that character - if this is a letter, it will leave an empty string. Otherwise, it will leave it as-is.
[ # if the result isn't empty:
∇ # rotate the top three items
pp # and double prepend
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~34~~ 33 bytes
```
{$[y<58;x,y;(-2_x),,(,/2#|x),y]}/
```
[Try it online!](https://ngn.bitbucket.io/k#eJxLs6pWia60MbWwrtCptNbQNYqv0NTR0dDRN1KuAbIqY2v1ubjSFJQMjYwTk5RALFPLRGOTpColqKiJqVliUnJKKoQPFU00NU6qME82sEixTE2DiQF1JZuapZhbpKalKwEAN5UeZA==)
A single neat K scan.
Returns a singleton list with the output.
-1 byte from Traws.
## Explanation
```
{$[y<58;x,y;(-2_x),,(,/|-2#x),y]}/
{ }/ scan from left
$[ ] if
y<58; current command <58 (is digit)
x,y then join the two
; otherwise
(,/|-2#x) join the last two commands, reversed
,y concat with current command
(-2_x),, nest, and join with the rest of the output
```
[Answer]
# JavaScript (ES6), ~~52~~ 49 bytes
Expects an array of characters. Returns a string.
```
a=>a.map(c=>a.push(o=1/c?c:a.pop()+a.pop()+c))&&o
```
[Try it online!](https://tio.run/##dc9LCsIwEAbgfU9RupAEMTVN04dQPYi4mEySqmhTrIp4@RrFB0qdTSbwf8zMFs7Q4WHTHieN06a3VQ/VHNgeWoL3pj11a@IqHuMCZ/7rWkLHrxcpHY1cj67p3M6wnauJJUvGWMQTASpaURp@Ko5DkQBXwUBeliBSdf0SPp8KVUq4BsMTUpmBQm3eyotMQqoEJpqbQfWz01Px4QkghbrkOC10aexD@mxZTLXJhVQJhwvaP9JfgzLTeWFs/ZJFbjKprT/KU6z7Gw "JavaScript (Node.js) – Try It Online")
### Commented
```
a => // a[] = input array, re-used as the stack
a.map(c => // for each character c in a[]:
a.push( // push in the stack ...
o = // ... the new value o:
1 / c ? // if c is a digit:
c // just use c
: // else:
a.pop() + // use the concatenation of
a.pop() + // the last 2 values from the stack
c // followed by c
) // end of push()
) && o // end of map(); return the last value
```
[Answer]
# [Haskell](https://www.haskell.org/), 55 bytes
```
head.foldl(%)[]
s%x|x<'a'=[x]:s
(a:b:s)%x=(a++b++[x]):s
```
[Try it online!](https://tio.run/##y0gszk7Nyfmfm5iZZ1tQWhJcUuSTp6CikKagZGiUaGqcVGGebGCRYpmapsSVZhvzPyM1MUUvLT8nJUdDVTM6lqtYtaKmwkY9Ud02uiLWqphLI9EqyapYU7XCViNRWztJWxsorGlV/P//v@S0nMT04v@6yQUFAA "Haskell – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes
```
FS⊞υ⁺⭆⊗№βι⊟υιυ
```
[Try it online!](https://tio.run/##JYq7CoQwEAD7@4qUG/CK03sIltpYCAG/IIlPCNkQs/7@GrluZhi76WhRO@YFo4DeB0pjirtfQUqh6NiACqEcHfDPgw7QIRk3T9Ai@QSmELuUecIAdEO25qHynLI3zK9SV29jP9/pV8/Lys/TXQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Based on @Arnauld's answer; for every input character, if it is a letter then pop the top two elements off the result stack and concatenate the three, otherwise just push the digit to the stack, however in Charcoal it turns out to be golfier to pop `N` elements off the result stack where `N` is `2` for a letter and `0` for a digit, and concatenate the character.
```
FS
```
Loop over the characters of the input string.
```
⊞υ⁺⭆⊗№βι⊟υι
```
Count the number of appearances of the character in the predefined lowercase alphabet, double that, pop that many terms from the predefined empty list, join everything together, and push that to the list.
```
υ
```
Output the final result.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ªç8îá/╤╫╬∩
```
[Run and debug it](https://staxlang.xyz/#p=a687388ca02fd1d7ceef&i=123ab%0A59a34bz%0A123456abcde%0A1%0A12a53bx7c08d9ef%0A12a34bc56d78efg%0A&m=2)
same idea as my K answer.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), 17 bytes
```
;ṭ@Ṫ,Ṫ{;ʋ¥ØDi¥}?/
```
[Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCI74bmtQOG5qizhuap7O8qLwqXDmERpwqV9Py8iLCIiLCIiLFsiXCIxMmEzNGJjNTZkNzhlZmdcIiJdXQ==)
Since the input is guaranteed to be non-empty (clarified by OP), we do not need to reduce from an initial value and can replace `ƒ“”` with `/` (thanks to Leaky Nun for -2 bytes).
There's gotta be a better way to get rid of that `ṭ@Ṫ,Ṫ{;ʋ¥` mess in the middle.
```
;ṭ@Ṫ,Ṫ{;ʋ¥ØDi¥}?/ Main Link
/ Reduce
? If
} - The right argument
i - Appears in
ØD - "0123456789"
; - Append it to the accumulating stack
Otherwise
--======¥ - Previous two; 2,2-chain x (a b) y = x a (x b y)
ṭ@ - Append to the accumulator the result of
-=--=ʋ - Previous four; 1,2,2,2-chain x (A b c d) y = (x A) b (x c y) d y
Ṫ - Pop the last element off the stack
, - And pair it with
Ṫ{ - Pop the last element off the left side (the stack)
; - Append the incoming character
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~81~~ 77 bytes
Python port of the [Javascript answer](https://codegolf.stackexchange.com/a/231151/)
A recursive lambda might solve this with fewer bytes though.
*-4 bytes thanx to ovs*
```
def f(i,s=[]):
for c in i:s+=[c<'a'and c or s.pop()+s.pop()+c]
return s[-1]
```
[Try it online!](https://tio.run/##bckxDoQgEIXh3lNMNxBdE6NGY5aTEApEiTQDAbbY0yPNZhur9@d74ZsvT2Mpx2nBMtclIRXfGrA@ggFH4LbUCmneqFHTUa0eqQ8@MN7@1qgG4pk/kSDJ16BKiI4yw3nSy7ob7HBd9mnWtexfuRDPzssN "Python 3 – Try It Online")
[Answer]
# [Factor](https://factorcode.org/), 71 bytes
```
EBNF: A e=e e[a-z]=>[[first3 1string surround]]|[0-9]=>[[1string]];EBNF
```
[Try it online!](https://tio.run/##VY7LTsMwEEX3@Yoh@1ZJHOfRqpVAAtRNN4hVlMXYHqcVKA22I7UFvj3ESZFgZc25x3NHo3QnM7y@7PbPK0Bj8GKho2ZJotVg6aOnVpKFNzItvUNnyLlLZ46tA@vGp7GwDnb7FVhp0MnD8Piwf1rBPdCGgCpcXOvNtqr00VjHIJ7/gO2NOfWtquuvKlqUk3LL6nrtVwyfEMYJQxFCyEtkqbiGE0l5hkIq8tNEkDNxzmVUqJL0TEZb8kzlBekmhG@oxnuWUAOhPATBHUyLYbMFlmAsRnBr8ChlouR4na3fMh9kHFPBZKJi8qFH8WT9O8DjsogU5YyLJMaz1LP09yYvFTllXOmxbrRkM/wA "Factor – Try It Online")
EBNF definition strikes again :) Defines a function named `A` which takes a string, parses it, and returns its r-flagged version as a string.
(TIO version is slightly older than 0.98 stable, and requires ending `;EBNF` instead of surrounding the body with `[=[ ]=]`. The TIO version happens to be shorter.)
A bit of jankiness comes from the fact that the character class `[0-9]` gives its charcode, not any kind of sequence (array, vector, or string). `1string` is used to keep all intermediate results as strings.
## Ungolfed
```
! If part of a postfix expression,
! parse the two operands and the operator, swap the operands, and concatenate
expr = expr expr [a-z] => [[ first3 1string surround ]]
! Otherwise, take a single digit operand and make it a string
| [0-9] => [[ 1string ]]
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 27 bytes
```
∊{⍺∊⎕D:⍺,⍵⋄(2↑⍵)⍺⊂⍛,2↓⍵}/⍤⌽
```
[Try it online!](https://tio.run/##jYy9SgNBFIX7PMV2k8UN7u7s7I@VoIW2xk4sZnZmQyBsLCJEQyxUgkYn@EOwsBJS2FkJItjEN7kvEu9NREyXZuZyzvk@edSq6RPZajdqptsxpTZ61gP7fgD2AW6/4GrYq8Lw3HdCJ3DXNsF@YsS/n3DSX8eB74H9wP8MA2xgNN4@7Ff@DCvhSyyGS/gcRQXYyar8jLjFlLINPD2a3FxWQxjc4@lSS85nD5PHhc1OiC1gcAd2BMOL6Run9Whc39vCd39ntz5rlg72LAi5VMxhIpM8Uqd4YRKJWKpcG@ZUPRYwl0IpuOomuZ/qzBTzGQG5iHWSmqLBKu3jDgl5KAMSRlxlQpIwFjJSPA918E@Ypb42CRcqDGQ3J2GamFjoAjmM8l/h9UsxfW2WPw "APL (Dyalog Extended) – Try It Online")
Straightforward reduction, as in many other answers. Since APL's reduction is from right to left, the reduction is done on the input string reversed. Also, the top of the stack is on the left side, and the stack items are kept nested until the very end (where `∊` flattens the entire structure).
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 34 bytes
```
{⍵[⍒∊{0 2 1⊂⍤+@⍺∊3×⍵}/⌽0,⍸~⍵∊⎕D]}⌽
```
[Try it online!](https://tio.run/##jYy9SgNBFIX7PMV2k2CCOzs7@9MJWmhr7MRifkMgbCwirIZYKARdnKCCWAcs7KyEELCJb3JfZL0TRGKXZu5wzvk@cT7o6EsxGPY6phyZQhtdj8F9noJ7hocvuKvGTahuwiAKaGtnD9wSI/b9ipPJLg7CNrgF3msMsIHZy8HZpPFn2Ar/x2JYb@JrFBXg3rbmLUwfwc2gul19MJg@YdM93sf35PCoW/eLAHtCIyYkCQjPBYvlFf4wiXkipNKGBM02oaTlQ8GZLFMVZjo3dj3zgOKJTjNje6QxvBh5IYsE9cKYyZwLL0y4iCVTkaYbwjwLtUkZlxEVpfLCLDUJ1xY5jNSv8H5uV@/94gc "APL (Dyalog Extended) – Try It Online")
I had an idea of grade-and-indexing, where base 3 numbers define the ordering of elements. It works well, but it is unfortunately slightly longer than the easy solution.
This works by reconstructing the postfix structure based on the indices of operators.
```
Input: '59a34bz' (expected output: '43b95az')
{...}⌽ Reverse the string and pass onto the dfn.
This has the structure of prefix notation, with args swapped.
⍵←'zb43a95'
⍸~⍵∊⎕D Extract the (1-based) indices of operators.
v←1 2 5
{...}/⌽0, Reverse v and reduce on it with the starting value of 0.
⍺ gets the indices (1, 2, then 5), and ⍵ is the current vector.
∊3×⍵ Multiply all numbers in ⍵ by 3 and flatten it.
0 2 1⊂⍤+@⍺ Add 0 2 1 to the ⍺-th element in ⍵, creating a nested vector.
⍺←1, ⍵←0: ⊂(0 2 1)
⍺←2, ⍵←↑: 0 2 1 → 0 6 3 → 0(6 8 7)3
⍺←5, ⍵←↑: 0 6 8 7 3 → 0 18 24 21 9 → 0 18 24 21(9 11 10)
⍵[⍒∊...] Flatten the final result, and sort ⍵ by descending order of that.
Flatten: 0 18 24 21 9 11 10
Input(⍵): z b 4 3 a 9 5
Sort desc: 43b95az
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 29 bytes
```
S`\B
+1`(.+)¶(.+)¶(\D)
$2$1$3
```
[Try it online!](https://tio.run/##K0otycxL/P8/OCHGiUvbMEFDT1vz0DYoGeOiyaVipGKoYvz/v6GRcWISl6llorFJUhUXkGdiapaYlJySymUI5CWaGidVmCcbWKRYpqaB@EBVyaZmKeYWqWnpAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
S`\B
```
Split each character onto its own line. (Sadly `_S` doesn't seem to do what I want.)
```
+1`(.+)¶(.+)¶(\D)
$2$1$3
```
Processing each operator in turn, prefix it with its reversed operands.
[Answer]
# [J](http://jsoftware.com/), 41 bytes
```
[:|.@;((;@;1 0&{);2}.])`;@.(58>3 u:[)/@|.
```
[Try it online!](https://tio.run/##TY49C8IwFEV3f8XDwbSgsUn62jRBKQhOTq4imE/FxUkoVX97LWLQ4S73nAv3OkwpibBSQGAOBagxCwqb/W47HNSTtjrLdKsZFLNHrvmLHvOTbmmGci3grg75sn3SIZ8Ed7kBEdwwS2ChIAJhXBhLvqQUtkHTJ4aNEaXtE63QlFY47ln4W5dYGet8SBYjsPqgVDSy8KEWaDkznYu/qUFhu9oV0jchJlvWoUIfxyej7s5/9njFYeVrGeKZDG8 "J – Try It Online")
Well, this is quite long and inelegant because of the required boxing in J. Perhaps someone can suggest a better approach.
I believe the current approach is doing more or less the same thing as Razetime's K answer.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0 [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), 15 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Input as a character array, output as a string.
```
£pXiUoX²è\a)¬)Ì
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&flags=LWg&header=cQ&code=o3BYaVVvWLLoXGEprCnM&input=IjU0YTc4YmMi)
```
£pXiUoX²è\a)¬)Ì :Implicit input of array U
£ :Map each X
p : Push to U
Xi : Prepend to X
Uo : Pop this many elements from U
X² : Duplicate X
è : Count occurrences of
\a : RegEx /[a-z]/g
) : End pop
¬ : Join
) : End push
Ì : Last element
:Implicit output of last element of resulting array
```
[Answer]
# Vim, 51 bytes
```
:s/./\r&/g
qq{:/\v(.+)\n(.+)\n(\a)/s//\2\1\3
@qq@qJ
```
[Try it online!](https://tio.run/##K/v/36pYX08/pkhNP52rsLDaSj@mTENPWzMmD0rGJGrqF@vrxxjFGMYYczkUFjoUev3/b2iUaGySlGxqlmJukZqWDgA "V (vim) – Try It Online")
The `J` can be omitted if a leading newline is permissible.
[Answer]
# [Python 3](https://docs.python.org/3/), 80 bytes
```
f=lambda i,o=[]:i and f(i[1:],o+[(i[0]>'9'and o.pop()+o.pop()or'')+i[0]])or o[0]
```
[Try it online!](https://tio.run/##TU9LCoMwEN17iiEgJmiLrX9BLyJZJMa0gTYRzaLt5W2039nM@zGPGe/2bHSyLLK5sCsXDFRkmo7WCpgWILHqDjWNTNg5FNM2qIJVN/vRjJiE722mICDhGqAOg3FgscNsZ2gAe@AGHY4J4yh6kaxiScofH@q8NMsZ78XwlX4eyxJ@K/q4FNUg/2R3oc9yUZSDPCGPeJ501RaUhq263oLjpLTFyJ9h14I/I/AB28j9ZQkhyxM "Python 3 – Try It Online")
[Answer]
# [TypeScript](https://www.typescriptlang.org/)'s type system, 155 bytes
```
//@ts-ignore
type F<C,S=[]>=C extends[infer T,...infer C]?F<C,T extends`${number}`?[T,...S]:S extends[{},{},...infer N]?[`${S[0]}${S[1]}${T}`,...N]:S>:S[0]
```
[Try it at the TS playground](https://www.typescriptlang.org/play?#code/PTACBcGcFoEsHMB2B7ATgUwFDgJ4Ad0ACAMQB4BhAGgGUBeAbQF0A+W8w9AD3HUQBNI9WIgBm6VIQAqlAHRzhYieUYB+MlUkduvAQAMAJAG9EAVwC2AI3EBfXSvrS5M6owBc1LT36DD1yr9l5UXFCADlVegNDanoABkZrIxiARgSjSVtAmXD3Znc4xkxsfCJJdEhwZMJaElJ6ACIAZnrKeoAmFvqAQ07kzot6lkwQQlGAPRVigily8Dbq2oa+1o7W5tae1oGhkfHJoA)
This is a generic type `F<C>` where C is a tuple type of characters, which returns a string literal type.
If the input could instead be a tuple type of elements which are either character or number:
## [TypeScript](https://www.typescriptlang.org/)'s type system, 144 bytes
```
//@ts-ignore
type G<C,S=[]>=C extends[infer T,...infer C]?G<C,[T,S]extends[string,[{},{},...infer N]]?[`${S[0]}${S[1]}${T}`,...N]:[T,...S]>:S[0]
```
[Try it at the TS playground](https://www.typescriptlang.org/play?ssl=1&ssc=1&pln=2&pc=132#code/PTACBcGcFoEsHMB2B7ATgUwFDgJ4Ad0ACAcQB4BhAGgGUBeAbQF0A+W8w9AD3HUQBNI9WIgBm6VIQAqlAHRzhYieUYB+MlXrTqjLj36DI4VMPiV6AbwC+lK7PmjxhAHKNV9AAYASc9XoAGRktvXwBGQO9JS3c7GRcALk0Y7WY43wDMbHwiSXRDEMJaElJ6AGZKACZKACIAQyrKEOqAIyqWTBBCToA9FUyCKVzwcoKi+kbKstr6qpa2ju7eoA)
] |
[Question]
[
[This challenge](https://codegolf.stackexchange.com/questions/61808/lossy-sorting-implement-dropsort) already describes dropsort. However, I'm kinda lazy and I really only need my array to be a bit more sorted than before, it doesn't need to be sorted *all the way*.
In Drop Sort, we drop every element less than *any* element before it. In Lazy Drop Sort, we drop every element less than the one *strictly preceding* it.
Here's an example. Consider the following array:
```
8 6 9 9 7 2 3 8 1 3
```
Let's mark every element less than the one before it.
```
8 6 9 9 7 2 3 8 1 3
^ ^ ^ ^
```
Notice how neither `3` was marked, nor the last `8`. They are all larger than the single element to the left of them.
Completing the algorithm, removing the marked elements, we get:
```
8 9 9 3 8 3
```
That *basically* looks more sorted. Kinda. I'm lazy.
Your task, as you may have already deduced, is to implement this algorithm.
Input is an array of at least 1 positive integer between 1 and 9, so you can take a string of digits as well.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), fewest bytes wins!
Additional test cases:
```
1
1
1 2 3
1 2 3
5 3 1
5
1 2 3 2 1
1 2 3
1 1 1 9 9 9 1 1 1 9 9 9 1 1 1
1 1 1 9 9 9 1 1 9 9 9 1 1
9 9
9 9
5 2 4 2 3
5 4 3
```
[Answer]
# JavaScript (ES6), ~~28~~ 25 bytes
*Saved 3 bytes thanks to @Shaggy*
```
a=>a.filter(n=>~-a<(a=n))
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i5RLy0zpyS1SCPP1q5ON9FGI9E2T1Pzf3J@XnF@TqpeTn66RppGtIWOgpmOgiUYmesoGOkoGOsoAAUNgYxYoHIA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 4 bytes
```
m←ġ<
```
[Try it online!](https://tio.run/##yygtzv7/P/dR24QjC23@//8fbaFjpmMJhOY6RjrGOhY6hjrGsQA "Husk – Try It Online")
### Explanation
```
m←ġ<
ġ< Group the numbers into decreasing sequences
m← Keep the first element of each sequence
```
[Answer]
# [R](https://www.r-project.org/), 27 bytes
```
(l=scan())[c(T,diff(l)>=0)]
```
[Try it online!](https://tio.run/##K/r/XyPHtjg5MU9DUzM6WSNEJyUzLU0jR9PO1kAz9r@FgpmCJRCaKxgpGCtYKBgqGP8HAA "R – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~9~~ 8 bytes
Saved one byte thanks to Giuseppe.
```
0yd0<h~)
```
[Try it online!](https://tio.run/##y00syfn/36AyxcAmo07z//9oCwUzBUsgNFcwUjBWsFAwVDCOBQA "MATL – Try It Online")
---
**Explanation:**
```
0 % Push a zero
y % Implicitly grab the input and duplicate it.
% Stack: [8 6 9 9 7 2 3 8 1 3], 0, [8 6 9 9 7 2 3 8 1 3]
d % The difference between each number of the last element:
% Stack: [8 6 9 9 7 2 3 8 1 3], 0, [-2, 3, 0, -2, -5, 1, 5, -7, 2]
0< % Which are negative?
% Stack: [8 6 9 9 7 2 3 8 1 3], 0, [1 0 0 1 1 0 0 1 0]
h % Concatenate. Stack: [8 6 9 9 7 2 3 8 1 3], [0 1 0 0 1 1 0 0 1 0]
~ % Negate. Stack: [8 6 9 9 7 2 3 8 1 3], [1 0 1 1 0 0 1 1 0 1]
) % Index. Stack: [8 9 9 3 8 3]
```
[Answer]
# [Perl 5](https://www.perl.org/).10.0 + `-nl`, 16 bytes
```
$f>$_||say;$f=$_
```
[Try it online!](https://tio.run/##K0gtyjH9/18lzU4lvqamOLHSWiXNViX@/38LLjMuSyA05zLiMuay4DLkMv6XX1CSmZ9X/F83L@e/rq@pnqGBngEA "Perl 5 – Try It Online")
[Answer]
# Haskell, 29 bytes
```
f s=[b|(a,b)<-zip(0:s)s,a<=b]
```
just a simple list comprehension.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~8~~ 7 bytes
*Saved 1 byte thanks to @Oliver*
```
k@>(U=X
```
[Test it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=a0A+KFU9WA==&input=WzggNiA5IDkgNyAyIDMgOCAxIDNd)
Alternatives:
```
f@T§(T=X
k@ä>0 gY
i0 ò> mÅ c
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 5 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
âÿ╠╦░
```
[Run and debug this online](https://staxlang.xyz/#p=8398cccbb0&i=[8+6+9+9+7+2+3+8+1+3]&a=1)
Unpacking, ungolfing, and commenting the code, we get this.
```
Z Push a zero under the input
f Use the rest of the program as a filter on the input. Output passing elements.
> Current element is greater than previous?
_~ Push current element to the input stack; when the main stack is empty, pops fall back to this
! Logical not; applies to the result of the greater-than
```
[Run this one](https://staxlang.xyz/#c=Z%09Push+a+zero+under+the+input%0Af%09Use+the+rest+of+the+program+as+a+filter+on+the+input.++Output+passing+elements.%0A%3E%09Current+element+is+greater+than+previous%3F%0A_%7E%09Push+current+element+to+the+input+stack%3B+when+the+main+stack+is+empty,+pops+fall+back+to+this%0A%21%09Logical+not%3B+applies+to+the+result+of+the+greater-than&i=[8+6+9+9+7+2+3+8+1+3]&a=1)
The ordering of the instructions is awkward but there's a reason for it. Stax source code packing doesn't always yield the same size output for the same size input. Basically, you have a chance to save a byte if the last character of source has a lower character code. Well, `!` has one of the lowest codes you can get for a printable character. (33 specifically) Many 6 byte ASCII stax programs can't pack any smaller. But if they end with a `!`, then they can. So the reason for this particular ordering of instructions is to ensure that the logical not ends up at the end of the program.
[Answer]
# J, 12 Bytes
```
#~1,2&(<:/\)
```
### Explanation:
```
#~1,2&(<:/\) | Whole function, executed as a hook
<:/ | Distribute <: (greater or equal) over an array
2&( \) | Apply to each sub array of length 2
1, | Append a 1 to the front
#~ | Choose elements from the original array
```
### Examples:
```
2&(<:/\) 8 6 9 9 7 2 3 8 1 3
0 1 1 0 0 1 1 0 1
1,2&(<:/\) 8 6 9 9 7 2 3 8 1 3
1 0 1 1 0 0 1 1 0 1
(1 0 1 1 0 0 1 1 0 1) # 8 6 9 9 7 2 3 8 1 3
8 9 9 3 8 3
f =: #~1,2&(<:/\)
f 8 6 9 9 7 2 3 8 1 3
8 9 9 3 8 3
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/lesMdYzUNGys9GM0/2tyKXClJmfkK6QpWCiYKVgCobmCkYIxkGeoYPwfAA "J – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
>Ɲ0;¬×
```
I/O is on strings.
[Try it online!](https://tio.run/##y0rNyan8/9/u2FwD60NrDk////@/uoWZpaW5kbGFobE6AA "Jelly – Try It Online")
[Answer]
# Java 8, ~~66~~ ~~55~~ 48 bytes
```
l->{for(int i=0;;)if(i>(i=l.next()))l.remove();}
```
-11 bytes after a tip from *@OlivierGrégoire*.
-7 more bytes thanks to *@OlivierGrégoire*.
**Explanation:**
[Try it online.](https://tio.run/##fZBBa8IwFIDv/op3TCCGbcLm6Crs4EHYvHgcO2TxqenSRJLXriL97V1aJ4qHEQiEfHz5XgpVq3Gx/u60VTHCuzLuOAIwjjBslEZY9keA2ps1aFYkXFZkrHwzkRYJUuTDyyLhWwwzsDxLeDtKWyRFRsMSHOTQ2fHsuPGBJTGY/C7LuNkwM2Mmt9JhQ4xzbmXA0tfIeNZ2We/YV182Of5UQ0OZCtmKgnHbj0/FT3WXrNcQ1KFvuzQRRkoJDn/@5djNZZQq9gCbikfxnNaTeBATMRX3YsKHMQEoHE4BAE5q1r8k7dXHsDPYakV6d/XE0q8qvZtbLNHRvNG4J@MdYMPPwtUhEpbSVyT3aVqybvCfhcM3t90v)
```
l->{ // Method with Integer-ListIterator parameter and no return-type
for(int i=0;;) // Loop over all items
if(i>(i=l.next())) // If the current item is larger than the next
l.remove();} // Remove this next item
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 21 bytes
```
@(x)x(~[0,diff(x)<0])
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0KzQqMu2kAnJTMtDcixMYjV/J@mEW2hYKZgCYTmCkYKxgoWCoYKxkAJAA "Octave – Try It Online")
**Explanation:**
Take a vector `x` as input, and create a vector `[0, diff(x)<0]`, where `diff(x)` is a vector with the difference between all adjacent elements. Keep only those that are negative by comparing it to zero, giving us a list of all the elements we want to drop.
We then select the elements from the input vector that we want to keep.
[Answer]
# [V](https://github.com/DJMcMayhem/V), 25 bytes
```
òjälá k$yl+@"òç-/d
ç /dw
```
[Try it online!](https://tio.run/##K/v///CmrMNLcg4vVMhWqczRdlCSOLzp8HJd/RSuw8sV9FPK//@34DLjsgRCcy4jLmMuCy5DLmMA "V – Try It Online")
Hexdump:
```
00000000: f26a e46c e120 6b24 796c 2b40 2218 f2e7 .j.l. k$yl+@"...
00000010: 2d2f 640a e720 2f64 77 -/d.. /dw
```
Worst language for the job. But I did it [for a dare](https://chat.stackexchange.com/transcript/message/43567339#43567339).
[Answer]
# SWI-Prolog, 44 bytes
```
[A,B|C]-[A|E]:-B<A,[B|C]-[B|E];[B|C]-E. L-L.
```
Usage: Call "*List*-X" where *List* is a bracket-enclosed, comma-separated list e.g. [1,4,5,1,11,6,7].
[Answer]
# [Triangularity](https://github.com/Mr-Xcoder/Triangularity), 71 bytes
```
.....).....
....IEL....
...)rFD)...
..2+)IE)w..
.+h)2_stDO.
={M)IEm}...
```
[Try it online!](https://tio.run/##KynKTMxLL81JLMosqfz/Xw8ENMEkF4jwdPWBsTWL3Fw0IWwjbU1PV81yEFs7Q9MovrjExV@Py7baFyicWwtU8/9/tIWOmY4lEJrrGOkY61joGOoYxwIA "Triangularity – Try It Online")
## How it works?
```
)IEL)rFD)2+)IE)w+h)2_stDO={M)IEm} – Full program.
)IE – Get the 0th input I and evaluate it.
L)r – And push the range [0 ... length of I).
F { – Filter the integers in this range which satisfy:
D)2+)IE)w+h)2_stDO= – This condition. Runs each element E on a separate
stack and discard those that don't meet the criteria.
D)2+ – Duplicate and add 2 to the second copy.
)IE – Retrieve I again.
) – Push a 0 onto the stack.
w – Wrap the 0 in a list. [0]
+ – Prepend it to I.
h – Head. Trim the elements after index E+2.
)2_ – Literal -2.
st – Tail.
DO= – Check whether the result is invariant over sorting.
M)IEm} – Last part: indexing into the input.
M } – For each index that satisfies the conditions:
)IEm – Retrieve the element of I at that position.
```
[Answer]
# [Python](https://docs.python.org/2/), 40 bytes
```
f=lambda h,*t:t and h+f(*t)[h>t[0]:]or h
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIUNHq8SqRCExL0UhQztNQ6tEMzrDriTaINYqNr9IIeN/QVFmXokCUCIzr6C0RENT87@6hZmlpbmRsYWhsToA "Python 2 – Try It Online")
Input as tuple of characters.
---
# [Python 3](https://docs.python.org/3/), 41 bytes
```
p=''
for x in input():x<p or print(x);p=x
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v8BWXZ0rLb9IoUIhMw@ICkpLNDStKmwKFIBiBUWZeSUaFZrWBbYV//9bmFlamhsZWxgaAwA "Python 3 – Try It Online")
String input.
---
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 33 bytes
```
Pick[#,Arg[#-{0}~Join~Most@#],0]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78H1CUmVcS/T8gMzk7WlnHsSg9Wlm32qC2zis/M6/ON7@4xEE5VscgVu2/goNCtYWOmY4lEJrrGOkY61joGOoY1yrE/gcA "Wolfram Language (Mathematica) – Try It Online")
## How it works
The code `# - {0}~Join~Most@#` turns an array `{a,b,c,d,e,f}` into `{a,b-a,c-b,d-c,e-d,f-e}`. Applying `Arg` to this sets negative numbers to `Pi` and nonnegative numbers to `0`.
`Pick[#, ..., 0]&` picks out the entries of `#` where `...` has a `0`: in our case, exactly the elements that yield a nonnegative number when you subtract the previous element. In other words, these are exactly the entries we want to keep when lazydropsorting.
[Answer]
# [Wonder](https://github.com/wonderlang/wonder), 27 bytes
```
-> ':1.!> 'sS#<=.cns2.++[0]
```
Usage example:
```
(-> ':1.!> 'sS#<=.cns2.++[0])[8 6 9 9 7 2 3 8 1 3]
```
# Explanation
Ungolfed version:
```
(map get 1).(fltr sS <=).(cns 2).(++ [0])
```
Prepend `0`, get list of consecutive pairs, keep list items where first number <= second number, get second number of each pair.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 20 bytes
```
#&@@@Split[#,##>0&]&
(* or *)
Max/@Split[#,##>0&]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2ar8V9ZzcHBIbggJ7MkWllHWdnOQC1W7b@mNVdAUWZeiYNWmr5DNRdXtWGtDpDQUTDSUTAGMU2BtI4CsiiYhAlAkCUM4RQBKQcJQI0EmmACtYOLq/Y/AA "Wolfram Language (Mathematica) – Try It Online")
### Explanation
`Input = {8, 6, 9, 9, 7, 2, 3, 8, 1, 3}`
```
Split[#,##>0&]
```
Group consecutive elements that are strictly decresasing: `{{8, 6}, {9}, {9, 7, 2}, {3}, {8, 1}, {3}}`
```
#&@@@
```
Take the first element of each: `{8, 9, 9, 3, 8, 3}`
[Answer]
# [Python 2](https://docs.python.org/2/), ~~52~~ ~~46~~ ~~45~~ 42 bytes
```
lambda a:[v for v,w in zip(a,[1]+a)if v/w]
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHRKrpMIS2/SKFMp1whM0@hKrNAI1En2jBWO1EzM02hTL889n9BUWZeiUKaRrSFjpmOJRCa6xjpGOtY6BjqGMdqcsGlDcHCJjqmQGXmQGnLWM3/AA "Python 2 – Try It Online")
---
Saved:
* -3 bytes, thanks to Rod
[Answer]
# APL+WIN, 14 bytes
Prompts for screen input of a vector of integers.
```
(1,1>2-/v)/v←⎕
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
```
ĆÁü›_Ï
```
[Try it online!](https://tio.run/##MzBNTDJM/f//SNvhxsN7HjXsij/c//9/tIWOgpmOgiUYmesoGOkoGOsoAAUNgYxYAA "05AB1E – Try It Online")
**Explanation**
```
Ć # append the head of the list
Á # rotate right
ü› # apply pair-wise greater-than
_ # logical negate each
Ï # keep elements of input that are true in this list
```
[Answer]
# [Kotlin](https://kotlinlang.org), 39 bytes
```
a->a.filterIndexed{i,v->i<1||v>=a[i-1]}
```
[Try it online!](https://tio.run/##PYzLCsIwEEX3@YpZJpAIVfBFm31BcOFSXESalME0SpoGoe23x1jEYQbuHTjn8QwWXTKDg06ho1F55VvI1x/hEjy6lsFIIE9UFtzQ3bXvoQKLfTgbuuew5XBYdsdhzWHDIT@LHNiCvbIjUEN/KGNkJuTrMkegp2wpaxckAyHh37J/TEpItTJog/a1a/RbNyPyKCSWxTRFWakriuI2pzl9AA "Kotlin – Try It Online")
Filter items that are either the first item (index==0, or even shorter index<1) OR the current Value is greater than or equal to the previous item (a[i-1]).
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 11 [bytes](https://github.com/abrudz/SBCS)
```
{⍵⌿⍨1⍪2≤⌿⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pR79ZHPfsf9a4wfNS7yuhR5xIwb2vt//9pCo/aJijgVMCVpmChYKZgCYTmCkYKxkCeoYIxAA "APL (Dyalog Unicode) – Try It Online")
This is actually pretty similar to Graham's answer, but in Dyalog, and independently developed. Also, more symmetric.
[Answer]
# [K4](http://kx.com/download/), 10 bytes
**Solution:**
```
x_/|&<':x:
```
**Example:**
```
q)k)x_/|&<':x:8 6 9 9 7 2 3 8 1 3
8 9 9 3 8 3
```
**Explanation:**
Find indices where element is less than preceding, remove these indices from the input
```
x_/|&<':x: / the solution
x: / store input as x
<': / less-than each-previous
& / indices where true
| / reverse
_/ / drop-over
x / the input
```
[Answer]
# [Attache](https://github.com/ConorOBrien-Foxx/attache), 24 bytes
```
{Mask[1'(Delta!_>=0),_]}
```
[Try it online!](https://tio.run/##SywpSUzOSP2fpmBlq/C/2jexODvaUF3DJTWnJFEx3s7WQFMnPrb2f15@UW5iTmZVKkiZa1lijq1dcEFOZgkXl19qakpxtEpBQXJ6LBcXV0BRZl5JSGpxiXNicWpxdJoDXKeOQjSXkoWCmYIlEJorGCkYK1goGCoYK@lwKRmCCZAYiGEKlEKIADGUA4KWYIjBBikAciC6jRRMwEZxxcb@BwA "Attache – Try It Online")
## Explanation
`Mask` selects all elements from its second argument which correspond to truthy elements in its first argument. `1'(Delta!_>=0)` calculates the indices which correspond to elements that are supposed to be in the final array.
## Other attempts
28 bytes (pointfree): `~Mask#(1&`'##Delta#`>=#C[0])`
32 bytes: `{Mask[1'(&`<= =>Slices[_,2]),_]}`
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 33 + 18 = 51bytes
```
x=>x.Where((a,n)=>n<1||x[n-1]<=a)
```
[Try it online!](https://tio.run/##XVDBasJAFDxnv@LhKcE1kAqtJSYXsVBoTz14EJHX7VMXkpd032oV9dvTTe2hlLnMmwfDzBgZmcZRtxfLW3g7iac6V3@v9MXy5z9p1lQVGW8bllwx1iQtGoL2rEyFIj1pnT2gJxCP3hp42rOZWvbLlYbnOe9rcvheUbkpumNRHtPFjhzFMWpOipKn2eVyXPIoW00LTLpc/bocGvsBr2g5Fu9CnuUK0G0lOavoJsBaoIAbT@d160@5ijahIJpdfEAHCJZhEzN9wU@a80Tf68eAB32nx3qiMz2@Jr1htJYi2A1xONCDXF1VNAt1m4rShbOewioUryXpPwHdNw "C# (.NET Core) – Try It Online")
basically the statement is where x is the first int in the array, or is greater than or equal to the previous number, keep it. Else drop it.
[Answer]
# [Swift 4](https://developer.apple.com/swift/), ~~56~~ 55 bytes
```
{var l=0;print($0.filter{($0>=l,l=$0).0})}as([Int])->()
```
[Try it online!](https://tio.run/##Ky7PTCsx@Z@TWqKQpmD7v7ossUghx9bAuqAoM69EQ8VALy0zpyS1qBrItLPN0cmxVTHQ1DOo1axNLNaI9swridXUtdPQ/J@mEW2ho2Cmo2AJRuY6CkY6CsY6CkBBQyAjVvM/AA)
## Explanation
```
{var l=0; // Declare variable l
print($0.filter{( // Print every element e in the input
$0>=l, // where e >= l
l=$0).0}) // And set l to e
}as([Int])->() // Set the input type to integer array
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
0;>ƝżµḢÐṂ
```
[Try it online!](https://tio.run/##y0rNyan8/9/A2u7Y3KN7Dm19uGPR4QkPdzb9//8/2kLHTMcSCM11jHSMdSx0DHWMYwE "Jelly – Try It Online")
This feels pretty bulky, wouldn't be that surprised if there is a better way.
```
0;>ƝżµḢÐṂ
Ɲ For each adjacent pair in the input...
> ...is the first element greater than the second? (yields a list of 0/1)
0; prepend a zero to this list (always keep the first element)
ż zip with the input
µ new monadic link
ÐṂ keep elements of the list with minimal value of... (Ðḟ would have worked here and been slightly more clear but I'll leave it as it is)
Ḣ ...their first element
```
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~136~~, 120 bytes
```
((())){{}([{}]({}))([({}<(())>)](<>)){({}())<>}{}{((<{}>))<>{}}{}<>{}{{}(({})<>)(())(<>)}{}([][()])}{}{}<>{{}({}<>)<>}<>
```
Here it is formatted and *"readable"*.
```
((()))
{
{}
([{}]({}))
([({}<(())>)](<>)){({}())<>}{}{((<{}>))<>{}}{}<>{}
{
{}(({})<>)(())(<>)
}
{}
([][()])
}{}{}<>
{
{}
({}<>)<>
}<>
```
[Try it online!](https://tio.run/##HYwxCsNQDEOv4lEeOqSBpgHji3z@kAyF0JIhq/HZf6ziQX6ypf3ajvPx@W3fMQCoakSiRXZEqqKVGH3XDvM6l1FonpEBWKSTIospjDNav4wxk2zsDdq5/t/KobLGfIxJ3vKStWaRp8xFk8w3 "Brain-Flak – Try It Online")
] |
[Question]
[
Write a program that will test the primality of a specified number, and give the output as a Boolean value (True is prime). Your prime test can (but doesn't have to) be valid for the number 1.
Here's the catch: your program itself has to sum to a prime number. Convert every character (including spaces) to its Unicode/ASCII value ([table](http://www.theasciicode.com.ar/american-standard-code-information-interchange/ascii-codes-table.png)). Then, add all those numbers together to get the sum of your program.
For example, take this not-so-great program I wrote in Python 3.3:
```
q=None
y=int(input())
for x in range(2,int(y**0.5)+1):
if y%x==0:
q=False
if not q:
q=True
print(q)
```
If you convert all the characters to their corresponding Unicode/ASCII value, you get:
```
113 61 78 111 110 101 10 121 61 105 110 116 40 105 110 112 117 116 40 41 41 10 102 111 114 32 120 32 105 110 32 114 97 110 103 101 40 50 44 105 110 116 40 121 42 42 48 46 53 41 43 49 41 58 10 32 32 32 32 105 102 32 121 37 120 61 61 48 58 10 32 32 32 32 32 32 32 32 113 61 70 97 108 115 101 10 105 102 32 110 111 116 32 113 58 10 32 32 32 32 113 61 84 114 117 101 10 112 114 105 110 116 40 113 41
```
You can then find the sum of those numbers manually or with your own program. This specific program sums to 8293, which is a prime number.
Of course, this is Code Golf, so the smaller you can make your program, the better. As pointed out by other users, this program is not very golfy.
A few rules:
Valid inputs include STDIN and prompts (no functions, it's just a way to add free extra code). Spaces are permitted, but only if they are crucial to the functionality of your program. Output must be an output, not just stored in a variable or returned (use print, STDOUT, etc.)
Flags can be used and should be counted literally, not expanded. Comments are not allowed. As for non-ASCII characters, they should be assigned to the value in their respective encoding.
Make sure to list your program's size and the sum of the program. I will test to make sure programs are valid.
Good luck!
Here is a snippet to count the sum of your program and check if it is prime:
```
function isPrime(number) { var start = 2; while (start <= Math.sqrt(number)) { if (number % start++ < 1) return false; } return number > 1; } var inp = document.getElementById('number'); var text = document.getElementById('input'); var out = document.getElementById('output'); function onInpChange() { var msg; var val = +inp.value; if (isNaN(val)) { msg = inp.value.toSource().slice(12, -2) + ' is not a valid number.'; } else if (isPrime(val)) { msg = val + ' is a prime number!'; } else { msg = val + ' is not a prime number.'; } out.innerText = msg; } function onTextChange() { var val = text.value; var total = new Array(val.length).fill().map(function(_, i) { return val.charCodeAt(i); }).reduce(function(a, b) { return a + b; }, 0); inp.value = '' + total; onInpChange(); } text.onkeydown = text.onkeyup = onTextChange; inp.onkeydown = inp.onkeyup = onInpChange;
```
```
body { background: #fffddb; } textarea, input, div { border: 5px solid white; -webkit-box-shadow: inset 0 0 8px rgba(0,0,0,0.1), 0 0 16px rgba(0,0,0,0.1); -moz-box-shadow: inset 0 0 8px rgba(0,0,0,0.1), 0 0 16px rgba(0,0,0,0.1); box-shadow: inset 0 0 8px rgba(0,0,0,0.1), 0 0 16px rgba(0,0,0,0.1); padding: 15px; background: rgba(255,255,255,0.5); margin: 0 0 10px 0; font-family: 'Roboto Mono', monospace; font-size: 0.9em; width: 75%; }</style><meta charset="utf-8"><style>/**/
```
```
<link href="https://fonts.googleapis.com/css?family=Roboto+Mono" rel="stylesheet"><textarea id="input" tabindex="0">Insert your (UTF-8 encoded) code here
Or directly input a number below</textarea><br><input id="number" value="6296" tabindex="1"><br><div id="output">6296 is not a prime number.</div>
```
[Answer]
## [hello, world!](https://github.com/histocrat/hello_world), 13 bytes, `1193`
```
hello, world!
```
[Answer]
# Ruby, sum 3373, 37 bytes
```
require'prime'
g=gets.to_i
p g.prime?
```
[Answer]
# Microscript II, 2 bytes (sum 137)
```
N;
```
# Microscript II, 4 bytes (sum 353)
```
N;ph
```
I'm actually quite surprised that both of these wound up having prime byte sums.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes, `173`
```
p=
```
Explanation:
```
p # Checks if number is prime - returns 1 if true and 0 if false. Uses implicit input.
= # Wouldn't usually be required for this sort of program, but I added it to make the sum prime.
```
[Try it online!](https://tio.run/nexus/05ab1e#@19g@/@/KQA)
[Answer]
# Pyth, 2 bytes, `127`
```
/P
```
[Try it online](https://pyth.herokuapp.com/?code=%2FP&input=127&debug=0)
Outputs `1` for primes, `0` for non-primes.
`/` has code point `47`. `P` has code point `80`.
How it works:
```
/P
/PQQ Implicit variables.
Q = input
PQ Prime factorize Q.
/ Q Count how many times Q appears. 1 if prime, 0 if not.
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 1 byte, sum 23
```
æ
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C3%A6&inputs=23&header=&footer=)
`æ` is the built-in primality checker. Vyxal uses its own codepage, in which the character `æ` is `0x17`, or `23`, which is a prime number.
[Answer]
# Excel, ~~34~~ 30 bytes, sum ~~2039~~ 1759
```
=SUM(--(MOD(A2,ROW(A:A))=0))=2
```
Uses `ROW` instead of `SEQUENCE` which makes it shorter. As a added bonus, it now uses functions available at the time the question was asked.
## Original Answer
```
=SUM(--(MOD(A2,SEQUENCE(A2))=0))=2
```
Uses `SEQUENCE` which was not available when the question was posted.
[Answer]
# Python 2, 50 bytes, `4201`
Works for 1. Output is positive if prime, or zero if not.
```
p=input();print all(p%m for m in range(2,p))*~-p;p
```
[**Try it online**](https://tio.run/##K6gsycjPM/r/v8A2M6@gtERD07qgKDOvRCExJ0ejQDVXIS2/SCFXITNPoSgxLz1Vw0inQFNTq063wLrg/38TIwNDAA)
---
# Python 2, 44 bytes, `3701`
Doesn't work for 1. Outputs a Boolean.
```
p=input();print all(p%k for k in range(2,p))
```
[**Try it online**](https://tio.run/##K6gsycjPM/r/v8A2M6@gtERD07qgKDOvRCExJ0ejQDVbIS2/SCFbITNPoSgxLz1Vw0inQFPz/39jcwNDAA)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 2 bytes, `191`
```
Uj
```
`U` :`85`
`j` : `106`
[Try it online!](https://tio.run/nexus/japt#@x@a9f@/MQA "Japt – TIO Nexus")
[Answer]
# Haskell, 52 bytes, 4421
```
main=do
k<-readLn
print$product[1..k-1]`rem`k==k-1
```
Wilson theorem.
[Answer]
# PHP, 38 bytes, sum 2791
Fun fact: With `$h` instead of `$c`, the sum would be `2801` (also a prime), and its binary representation `101011110001` read as decimal is also a prime number.
```
for($b=$c=$argv[1];$c%--$b;);echo$b<2;
```
takes command line argument, prints `1` or empty string. Run with `-r`.
Code taken from [my own prime function](https://stackoverflow.com/questions/38008130/php-check-if-number-is-prime/39743570#39743570) (look at the original post if you can).
[Answer]
# JavaScript (ES6), 40 bytes, `3203`
*Saved 6 bytes thanks to [@l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)*
```
g=x=>m%--x?g(x):x<2;alert(g(m=prompt()))
```
[Try it online!](https://tio.run/##jY7NCsIwEITvPsVSEDbYLP7c1FTExxCRsA1RaZqQVsnbx1QvHr0O38w3D/3SA8d7GGXvW5N1Z@IICtj3g@8Mdd7OQvQuTOEVVAOrTbYqqcbNpUwHi0ls0369@xTRolNfHIUQ@WcFz0RU/dusLhRN@2SDGGpgMYkDLICJbzqeytNj4WpYFskb "JavaScript (Node.js) – Try It Online")
[Answer]
# R, 27 ~~32~~ bytes, sum 2243 ~~2609~~
Saved a 5 bytes thanks to @rturnbull
```
cat(gmp::isprime(scan(),r=43)>0)
```
This makes use of the gmp library's isprime function.
```
> sum(as.integer(charToRaw('cat(!!gmp::isprime(scan()))')))
[1] 2243
> cat(!!gmp::isprime(scan()))
1: 2243
2:
Read 1 item
TRUE
>
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/) + `dfns`, 7 bytes
## Sum: 569
```
1 pco⌈⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qc6SCekpaXrE616OO9rT/hgoFyfmPejqAMv@BAv850xS4DI2NzQE "APL (Dyalog Unicode) – Try It Online") or [Verify](https://tio.run/##SyzI0U2pTMzJT///qG@qc6SCekpaXrE616OO9rT/hgoFyfmPejqAMv@BAv850xS4DLhApCGYNAKTxmDSBCJuwsUFVP2obYK6OowRXJqrkJ@mkJyfklqQn5lXAjS9GCiurQ@U9/TXfdS7AshwDHvUu1kdyUKgIpgBnsUKAUWZuan26lxgBQrFAA "APL (Dyalog Unicode) – Try It Online")
The program uses the ceiling function(`⌈`) since it's a no-op on integers, and pads the codepoint sum to a prime number, according to APL's code page.
`pco` is a function from the dfns library which checks for primality.
[Answer]
# [Factor](https://factorcode.org/) + `math.primes`, sum 3373, 34 bytes
```
readln string>number prime? pprint
```
[Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQma@Qm1iSoVeQWFScWgRlF2XmphYrFBSllpRUAjl5JQrW/4tSE1Ny8hSKS4D8dLu80twkoHKwSnuFArCi//8NDQE "Factor – Try It Online")
Should be pretty self-explanatory I hope!
[Answer]
# Python 2, 44 bytes, byte-sum 3109
This is [xnor's 44 byte implementation](https://codegolf.stackexchange.com/a/58114/53748) with the lowest valued variable names that yield a prime byte sum.
Prints `1` if prime and `0` if not.
```
C=B=1
exec"B*=C*C;C+=1;"*~-input()
print B%C
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly) 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page), byte-sum 691
```
ƓÆḍ,ṠE
```
prints `1` if prime and `0` if not.
**[TryItOnline!](https://tio.run/nexus/jelly#@39s8uG2hzt6dR7uXOD6/78xAA)**
The bytes in hexadecimal are `93 0D D5 2C CD 45` (see the [code page](https://github.com/DennisMitchell/jelly/wiki/Code-page)), or in decimal are `147 13 213 44 205 69` which sum to 691, which is prime.
### How?
```
ƓÆḍ,ṠE - Main Link: no arguments
Ɠ - read and evaluate a line from STDIN (integer expected)
Æḍ - proper divisor count
, - paired with
Ṡ - sign
E - all equal? - returns a boolean (1 or 0)
- implicit print
```
The `Æḍ` functionality is such that primes and their negations return one while other integers do not (composites and their negations return numbers greater than one, one and minus one return zero and zero returns, oddly enough, minus one).
The `Ṡ` functionality is such that negative integers return minus one, zero returns zero and positive integers return one.
Thus the two functions only return the same value for the primes.
Note that the 3 byte program `ƓÆP` which directly tests if the input from STDIN is prime is unfortunately not a prime-sum program (240).
Testing for equality using `=`(equals), `e`(exists in), or `⁼`(non-vectorising equals) for 5 bytes also do not yield prime-sum programs.
---
# Alternative (maybe not acceptable) 4 bytes, sum 571
If the I/O restrictions still allow full programs that take an argument.
```
Æḍ⁼Ṡ
```
...using the same principle as above, where `⁼` is non-vectorising equality (the non-vectorising aspect has no effect since there is nothing to vectorise over anyway). The hex values are `0D D5 8C CD` which are `13 213 140 205` in decimal which sum to 571, a prime.
Again note that the 2 byte program `ÆP` does not have a prime sum (93).
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 4 bytes, byte-sum 439
```
qimp
```
Uses the built-in primality test.
[Try it online!](https://tio.run/nexus/cjam#@1@YmVvw/7@JsSUA "CJam – TIO Nexus")
### Alternate solution, 4 bytes, sum 461
```
r~mp
```
[Answer]
## Mathematica, 21 bytes, `1997`
```
Print@*PrimeQ@Input[]
```
`Input[]` reads a line of input (from STDIN if no front end is used, through a dialog box if the Mathematica front end is used), `Print@*PrimeQ` is the composition ([`@*`](http://reference.wolfram.com/language/ref/Composition.html)) of the `Print` and `PrimeQ` functions, and `@` is prefix function notation.
[Answer]
# [Perl 6](http://perl6.org/), ~~24~~ 22 bytes, `1949`
```
say .is-prime
for +get
```
All three whitespace characters are required.
(Perl 6 doesn't care what *kind* of whitespace character they are, though, so I chose a newline instead of the more commonly used space for the second one...)
[Answer]
## Pyth, 4 bytes, `367`
```
}QPQ
```
[Try it here!](http://pyth.herokuapp.com/?code=%7DQPQ&input=367&debug=0)
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 8 bytes, `511`
```
0Na%,a=1
```
I wrote a prime checker, and the sum was prime. Convenient. Verify inputs 1-30: [Try it online!](https://tio.run/nexus/pip#@@@mkKgQo2NsoFDNFaCQqFesp8HFZeCXqKqTaGvIxaVZ@///fyNjAA "Pip – TIO Nexus")
### Explanation
```
a is first command-line argument
,a Numbers from 0 to a-1
a% Take a mod each of those numbers (a%0 gives nil)
0N Count number of times 0 occurs in that list
=1 If 0 occurs only 1 time (for a%1), then a is prime
```
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 23 bytes, `2111`
```
print(2>=numdiv(input))
```
[Try it online!](https://tio.run/##K0gsytRNL/j/v6AoM69Ew8jONq80NyWzTCMzr6C0RFPz/38jQ0NDAA "Pari/GP – Try It Online")
[Answer]
# J, 18 Bytes, `1103`
```
echo 1&p:".(1!:1)1
```
Not far from optimal, the least I could golf a full program primality test to was 17 Bytes: `echo(p:[:".1!:1)1`, which unfortunately sums to 1133 = 11\*103.
Unfortunately I can't figure out how to get keyboard input working on TIO, so no link yet.
### Explanation:
```
echo 1&p:".(1!:1)1 | Full program
(1!:1)1 | Read a line of input from keyboard
". | Evaluate (converts string to int)
1&p: | 1 for prime, 0 for composite
echo | Print result. The space is required, as 'echo1' would be interpreted as a variable
```
Validating the program:
```
1 p:+/u:inv'echo 1&p:".(1!:1)1' NB. Convert to ints, sum, and test primality
1
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~62~~ 60 bytes, 4583
Pretty straight-forward. Outputs \* if prime, otherwise it outputs a space. Does not work for 1.
-2 thanks to [l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)
```
p;main(i){for(scanf("%d",&p);++i<p;)p=p%i?p:0;puts("*"+!p);}
```
[Try it online!](https://tio.run/##S9ZNT07@/7/AOjcxM08jU7M6Lb9Iozg5MS9NQ0k1RUlHrUDTWls706bAWrPAtkA1077AysC6oLSkWENJS0lbEShb@/@/iamFMQA "C (gcc) – Try It Online")
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 36 bytes, byte-sum 2239
```
{for(a=1;$0%++a&&a<$0;);$0=(a==$0)}1
```
[Try it online!](https://tio.run/##SyzP/v@/Oi2/SCPR1tBaxUBVWztRTS3RRsXAWhPItQUK26oYaNYa/v9vyGXEZcJlymVoyGVoxGVozGVmwGVmyAUA "AWK – Try It Online")
Outputs `0` if not prime and `1` for prime.
Definitely not the most efficient code, since it checks every integer greater than `1` to see if it divides the input.
[Answer]
# [Whispers v2](https://github.com/cairdcoinheringaahing/Whispers), 33 bytes
```
>>> ⊤ℙ∘ℕ
> Input
>> 1∘2
```
[Try it online!](https://tio.run/##K8/ILC5ILSo2@v/fzs5O4VHXkkctMx91zHjUMpXLTsEzr6C0hAsobggUAioxNAYA "Whispers v2 – Try It Online")
1. Score: `44381`
2. Only 6 bytes/2 characters added to make it valid!
3. **1** is not prime
## How it works
This is shown in the order it is executed in:
```
; Line 3:
>> ∘ ; Compose...
1 ; Line 1 with
2 ; The result of line 2
; Line 2:
> Input ; Retrieve a line of input
; Line 1:
>>> ⊤ ; The input is...
ℙ ; Prime
∘ ; And it is...
ℕ ; Natural
```
[Answer]
# Excel (57 bytes, code sum 3547)
```
=XOR(0<PRODUCT(MOD(A1,ROW(OFFSET(D2,0,,SQRT(A1))))),3>A1)
```
Excel doesn't really have an "input" as such, but this formula expects the number to be tested to be in A1 and outputs to whatever cell you drop it in. It's an array formula, so press Ctrl-Shift-Enter to enter it, rather than Enter.
[Answer]
# TI-Basic, 27 bytes, byte-sum 2843
```
Prompt F
3
For(A,2,sqrt(F
If not(remainder(F,A
0
End
Disp Ans
```
Prints `3` for prime and `0` for composite. Does not work for 1 (prints `3`).
TI-Basic is a [tokenized lanugage](http://tibasicdev.wikidot.com/one-byte-tokens). `remainder(` is a two-byte token; all others are one-byte tokens.
Explanation:
```
Prompt F # 0xdd, 0x46, 0x3f # Store input in F
3 # 0x33, 0x3f # Store 3 in Ans
For(A,2,sqrt(F # 0xd3, 0x41, 0x2b, 0x32, 0x2b, 0xbc, 0x46, 0x3f
# For each integer A from 2 to sqrt(F)
If not(remainder(F,A # 0xce, 0xb8, (0xef, 0x32), 0x46, 0x2b, 0x41, 0x3f
0 # 0x30, 0x3f
# If F is divisible by A, store 0 in Ans
End # 0xd4, 0x3f # end For loop
Disp Ans # 0xde, 0x72 (no newline) # Print Ans
```
Sum testing with Python:
```
>>> sum(eval(i) for i in ['0xdd', '0x46', '0x3f', '0x33', '0x3f', '0xd3', '0x41', '0x2b', '0x32', '0x2b', '0xbc', '0x46', '0x3f', '0xce', '0xb8', '0xef', '0x32', '0x46', '0x2b', '0x41', '0x3f', '0x30', '0x3f', '0xd4', '0x3f', '0xde', '0x72'])
2843
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes, [Σ](https://github.com/DennisMitchell/jelly/wiki/Code-page) = 239
```
ÆPa1
```
[Try it online!](https://tio.run/##y0rNyan8//9wW0Ci4f///40A "Jelly – Try It Online")
Proof: [Try it online!](https://tio.run/##y0rNyan8///wDK/MwxMeNa151DAz@HBbwP///9WBVKKhOgA "Jelly – Try It Online") (take the 1-based indices of the program's chars of Jelly's code page, decrement to make them 0-based, sum and then check if the result is prime).
] |
[Question]
[
>
> No, not the `^^vv<><>BA` kind of Easter eggs, real Easter eggs that we paint.
>
>
>
Here is an (awfully drawn) egg.
```
__
/ \
/ \
| |
\____/
```
In easter, we paint them with patterns. Like these:
```
__
/--\
/----\
|----|
\____/
__
/%%\
/%%%%\
|%%%%|
\____/
__
/~~\
/~~~~\
|~~~~|
\____/
```
---
# The challenge
Given a character (printable ascii) to paint the egg, print the painted egg.
**Examples:**
```
&:
__
/&&\
/&&&&\
|&&&&|
\____/
#:
__
/##\
/####\
|####|
\____/
```
# Specs
* Trailing newlines/spaces are allowed.
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak) `-c`, ~~270~~ ~~268~~ 266 bytes
```
(((((((((({}<(((([(()()())]((((((((((({}){}){}){}){}[()]))<>)<>{}())))))<>)<>(((()()()()()){}))({}()){})<>)<>>))))<<>({}<>)((()()()()()){})<>({}<>)>))))<<>((({})<>)({})<((()()()()()){})>[()()])>))<>((((({})<>)[(()()()()())({}){}])<((()()()()()){})<>((({}<>){}()))>))
```
[Try it online!](https://tio.run/nexus/brain-flak#ZY/dDcAgCITX4R66gWURw1PHMJ2dcvgTY4EElA9OXZa1tzBVEdBhsvewRRUYUDSivUHS8kQU08lCEogq@5pkcKGlOOF5v6jUJch00lpZGekuPOC6c/3h9p8e24PvP4gt7rdfzwc "Brain-Flak – TIO Nexus")
I was going to write an explanation, but I took a nap first and forgot how this whole thing works. Your guess is as good as mine.
[Answer]
## Python 2, 62 bytes
Super straight-forward. [Try it online](https://tio.run/nexus/python2#@19QlJlXolCkrq6uoBAfz6WgXxfDpV8HJGrq6mq4YuKBQB8oqVeUWpCTmJyqoV6nrpOZV1BaoqGpZaT5/7@6sjoA).
-1 byte, thanks to @mbomb007
```
print r''' __
/~\
/~~\
|~~|
\____/'''.replace('~',input()*2)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~30~~ ~~26~~ 16 bytes
*Two bytes saved thanks to @Neil by filling after making the shape*
```
__↗¹←↑¹↖²↓_‖M←¤S
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8@/lHb9EM7H7VNeNQ2EURPO7TpUdvk@EcN097vWQsUPrTk/Z7N//8rAwA "Charcoal – Try It Online")
### Explanation
The program works by first creating the right half of the egg, and then reflecting it to generate the left half.
```
__↗¹ Write the two bottom _s and write the /
←↑¹ Move left and write the |
↖² Then write two \s
↓_ And the top _
‖M← Reflect the canvas to the left
¤S Fill the shape with the string input
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~24~~ 22 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ḥ;“ ¶/\|_”“Ṁ¢ṚR;ḳ}AṠ’ṃ
```
**[Try it online!](https://tio.run/nexus/jelly#ATMAzP//4bikO@KAnCDCti9cfF/igJ3igJzhuYDCouG5mlI74bizfUHhuaDigJnhuYP///8nfic)**
### How?
```
Ḥ;“ ¶/\|_”“Ṁ¢ṚR;ḳ}AṠ’ṃ - Main link: character c e.g. '~'
Ḥ - double c: ['~','~']
“ _¶/\|” - string literal: [' ','_',<newline>,'/','\','|']
; - concatenate c: [['~','~'],' ','_',<newline>,'/','\','|']
“Ṁ¢ṚR;ḳ}AṠ’ - base 250 number: 3067183430901851641706
ṃ - base decompression with reversed @rguments:
- take the number and convert it to a base length(the list)
- then index (1-based) into that same list.
- i.e.: 3067183430901851641706 in base 7
= 22003241534115361163500004
indexed into [['~','~'],' ','_',<newline>,'/','\','|']
= [' ',' ','_','_',<newline>,' ','/',['~','~'],'\',<newline>,'/',['~','~'],['~','~'],'\',<newline>,'|',['~','~'],['~','~'],'|',<newline>,'\','_','_','_','_','/']
- implicit print: __
/~~\
/~~~~\
|~~~~|
\____/
```
[Answer]
# Sed, 43 characters
```
s:.: __\n /&&\\\n/&&&&\\\n|&&&&|\n\\____/:
```
Sample run:
```
bash-4.3$ sed 's:.: __\n /&&\\\n/&&&&\\\n|&&&&|\n\\____/:' <<< '★'
__
/★★\
/★★★★\
|★★★★|
\____/
```
[Answer]
# JavaScript (ES6), ~~53~~ ~~49~~ 47 bytes
I'm sure I can squeeze a bit more out of this - having to escape the `\`s is annoying me.
```
f=
c=>` __
/${c+=c}\\
/${c+=c}\\
|${c}|
\\____/`
console.log(f`-`)
console.log(f`%`)
console.log(f`~`)
console.log(f`&`)
console.log(f`#`)
```
* 4 bytes saved by moving the `s=c+c` variable assignment inside the first set of `{}`.
* 2 bytes saved by using `c+=c` instead of `s=c+c` & `s=s+s`, with thanks in part to [Neil](https://codegolf.stackexchange.com/users/17602/neil) who spotted this improvement at the same time as I was making it.
---
## Paint Your Own!
```
f=
c=>` __
/${c+=c}\\
/${c+=c}\\
|${c}|
\\____/`
o.innerText=f` `;i.addEventListener("input",function(){o.innerText=f(this.value||" ");})
```
```
<input maxlength="1" id="i">
<pre id=o></pre>
```
[Answer]
## [Alice](https://github.com/m-ender/alice), ~~53~~ 52 bytes, non-competing
*Thanks to Leo for indirectly saving 1 byte.*
```
/o *^i}'.*[;.h~r}}~"{.[^\\
@"S .^~ y~a}~~.["{!~"}^^^
```
[Try it online!](https://tio.run/nexus/alice#@6@fr6AVl1mrrqcVba2XUVdUW1unVK0XHRcTw@WgFKygF1enUFmXWFtXpxetVK1Yp1QbFxf3/38cAA "Alice – TIO Nexus")
Unfortunately, I had to fix a bug with `y` (transliteration) to make this work, so I've marked it as non-competing.
### Explanation
The basic idea is to create a string of the egg but with `~` as a placeholder for *two* copies of the input. However, the other characters of the input aren't particularly friendly for Alice strings, because those can't contain linefeeds, and all of `/\_|` would need escaping (because they're treated as mirrors and walls). So I can save some bytes by using placeholders for these as well, and then transliterating them. The placeholders for `/\_|` are `.[^{`, which are simply the character right before the one they represent. For the linefeed I'm using `}`.
Now the code... the entire program can be solved in Ordinal mode since we only need string processing and no processing of integers. Furthermore, we don't need any conditional control flow. The entire program can be expressed linearly. The general structure of the program is this:
```
/...//
@....
```
In such a program, the IP bounces up and down through the `...` section, first only executing half of the characters. Then the two `/` at the end move the IP right by one cell, so that on the way back it executes the other half (again bouncing up and down) until finally the `@` terminates the program. So if we unfold the funny zigzag structure in the middle, the program we're executing really looks like this:
```
" ^^} .~[}.~~[}{~~{}[^^^^.""!}"r.h~;a*y'~i.*So
```
Let's go through this:
```
" ^^} .~[}.~~[}{~~{}[^^^^."
This first string is simply the egg template I've talked about.
"!}" Push this string. It covers all the characters we need to replace
in the template except ~.
r Range expansion. Turns '!}' into '!"#$...z{|}'.
. Duplicate.
h~; Split off the first character, swap it to the top and discard it.
a* Append a linefeed.
We've now basically rotated the string to the left, but appended
a linefeed instead of the exclamation mark we've shifted off.
This maps each character in the string to the next one, except }
which gets mapped to a linefeed.
y Transliterate. Since the strings have the same length, this just maps
each character in the first string to the corresponding character in
the second string, replacing all of our placeholder characters.
'~ Push "~".
i.* Read the input and duplicate it.
S Substitute all "~" with the doubled input.
o Output the result.
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~50~~ ~~49~~ 48 bytes
```
' __
/11\
/1111\
|1111|
\____/'-replace1,$args
```
[Try it online!](https://tio.run/nexus/powershell#@6@uoBAfz6Wgb2gYwwUkQFQNiKrhiokHAn113aLUgpzE5FRDHZXEovTi////q6uqAwA "PowerShell – TIO Nexus")
Straightforward string replacement into a literal string. Not much room for golfing.
*-1 byte thanks to HyperNeutrino; -1 byte thanks to wubs*
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGLOnline), ~~21~~ ~~18~~ 16 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
0≈⁾‛≤¦¶W?5┼EB§ ‘
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=MCV1MjI0OCV1MjA3RSV1MjAxQiV1MjI2NCVBNiVCNlclM0Y1JXUyNTNDRUIlQTclMDkldTIwMTg_,inputs=Lw__,v=0.12)
The whole program is the following compressed:
```
__
/ŗŗ\
/ŗŗŗŗ\
|ŗŗŗŗ|
\____/
```
where `ŗ` gets replaced with the input.
[13 bytes](https://dzaima.github.io/SOGLOnline/?code=YyVCMk8lQTYldTI1NUQldTAxNTdAJTJDJXUwM0I4JXUyMDFBJUIyJXUyMDE4JXUyNTZD,inputs=JTI1,v=0.12) almost works too, but it does [unneeded things](https://dzaima.github.io/SOGLOnline/?code=YyVCMk8lQTYldTI1NUQldTAxNTdAJTJDJXUwM0I4JXUyMDFBJUIyJXUyMDE4JXUyNTZD,inputs=JTVD,v=0.12) with certain inputs..
[Answer]
# Brainfuck - 257 bytes 181 bytes
Golfed:
Live version click [here](https://copy.sh/brainfuck/?c=KysrKysrK1s-KysrKysrPC1dPls-Kz4rKz4rKz4rKzw8PDwtXT4rKysrKz4-Pj4rKysrKysrKysrWz4rKys-Kzw8PCsrKys8KzwrPj4-LV0-Kys8PDwtLTwrPj4-LD4uLjw8PDwuLj4-Pj4-LjwuPDw8PDwuPj4-Pi4uPDwuPj4-Pi48PDw8PDwuPj4-Pi4uLi48PC4-Pj4-Ljw8PC4-Li4uLjwuPj4-Ljw8PDwuPC4uLi48Lg$$)
```
+++++++[>++++++<-]>[>+>++>++>++<<<<-]>+++++>>>>++++++++++[>+++>+<<<++++<+<+>>>-]>++<<<--<+>>>,>..<<<<..>>>>>.<.<<<<<.>>>>..<<.>>>>.<<<<<<.>>>>....<<.>>>>.<<<.>....<.>>>.<<<<.<....<.
```
I'm not a professional golfer though; this is my first attempt.
Output:
```
__
/XX\
/XXXX\
|XXXX|
\____/ where X is the given char.
```
---
Ungolfed ( + comments) :
```
; chars:
; _ 95
; / 47
; \ 92
; | 142
; min val = 42 (7 times 6)
; lets do some math
+++++++[>++++++<-]> ; effectively 7 times 6
; now lets copy this to the next pointers multiplying by 2
the subsequent ones after the 1st
[>+>++>++>++<<<<-]
>+++++
>>>
> ; empty space starting from this pointer
++++++++++[>+++>+<<<++++<+<+>>>-]
>++<
<<--<+
>>>,
>..<<<<..>>>>>.<.
<<<<<.
>>>>..<<.>>>>.
<<<<<<.>>>>....<<.>>>>.
<<<.>....<.
>>>.<<<<.<....<.
```
[Answer]
# [Carrot](https://github.com/kritixilithos/Carrot), 34 bytes
```
__
/##\\
/####\\
|####|
\\____/
```
Try it online [here](http://kritixilithos.github.io/Carrot/).
First, we are in caret-mode, where every character gets pushed to the "stack". And finally the "stack" gets printed as output.
In caret-mode, `#` pushes the input, so the instances of `#` are basically replaced with the input (FYI `#` is a one-byte cat program).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~34~~ ~~33~~ 32 bytes
```
„__I244S×'/ì'\«`©¦¨'|.ø®R¹'_‡).c
```
[Try it online!](https://tio.run/nexus/05ab1e#ATEAzv//4oCeX19JMjQ0U8OXJy/DrCdcwqtgwqnCpsKoJ3wuw7jCrlLCuSdf4oChKS5j//9@ "05AB1E – TIO Nexus")
**Explanation**
```
„__ # push "__"
I244S× # push a list of the input repeated 2 and 4 and 4 times
'/ì # prepend "/"
'\« # append "\"
` # split list to separate items
© # store a copy of the last one in register
¦¨ # remove first and last item of the string
'|.ø # surround with pipes
®R # retrieve the string from register and reverse it
¹'_‡ # replace input with "_"
).c # print each line centered
```
[Answer]
# [Python 3.6](https://docs.python.org/3.6/), 53 bytes
```
lambda x:fr''' __
/{2*x}\
/{4*x}\
|{4*x}|
\____/'''
```
* Unnamed function taking the character `x` and returning a string.
* Uses Python 3.6's f-strings as an added alternative to earlier version's `.format()` - the `{}` enclosed parts of the f-string are code to be evaluated.
* The string is also an r-string and triple quoted saving one byte over:
```
lambda x:f' __\n /{2*x}\\\n/{4*x}\\\n|{4*x}|\n\____/'
```
~~I can't see an online interpreter for Python 3.6 though.~~
Try it at **[repl.it](https://repl.it/INeK)** (says 3.5 but it is 3.6)
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~43~~ 41 bytes
-2 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)
```
.
$&$&
..
__¶ /$&\¶/$&$&\¶|$&$&|¶\____/
```
[Try it online!](https://tio.run/##K0otycxL/P9fj0tFTUWNS0@PS0EhPv7QNgV9FbWYQ9v0QaJAugZE1xzaFhMPBPr//6sBAA "Retina 0.8.2 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~32~~ ~~29~~ 26 bytes (Thanks to Emigna/Adnan)
```
•jÀňiXƒÐ[Z•6B6ôvy5ÝJ¹"_ |/\ÿ"‡,
```
[Try it online!](https://tio.run/nexus/05ab1e#@/@oYVHW4YbDrafbMiOOTTo8IToKKGLmZHZ4S1ml6eG5Xod2KsUr1OjHHN6v9Khhoc7//xkA "05AB1E – TIO Nexus")
```
•jÀňiXƒÐ[Z•6B6ô # Push ['110011', '135541', '355554', '255552', '400003']
vy # For each encrypted block...
5ÝJ # Push 012345.
¹"_ |/\ÿ" # Push "_ |/\{input_char}".
‡, # Swap the charsets.
```
---
29 byte version (smarter w/o iteration needed due to encoding newlines as well):
# [05AB1E](https://github.com/Adriandmen/05AB1E), 29 bytes (Emigna)
```
•P£<r7»TwDšç6•5ÝJI"
_/ÿ\|"‡.c
```
[Try it online 2!](https://tio.run/nexus/05ab1e#@/@oYVHAocU2ReaHdoeUuxxdeHi5GVDI9PBcL08lrnj9w/tjapQeNSzUS/7/vw4A "05AB1E – TIO Nexus")
---
26 byte extension of Emigna's suggestion, using S to separate the chars into an array, then a[b] to interpolate each digit with the corresponding location in the previous array. This is essentially an element-wise transliteration (smart).
# [05AB1E](https://github.com/Adriandmen/05AB1E), 26 bytes (Adnan)
```
"
_/ÿ\|"•P£<r7»TwDšç6•Sè.c
```
[Try it online 3!](https://tio.run/nexus/05ab1e#@6/EFa9/eH9MjdKjhkUBhxbbFJkf2h1S7nJ04eHlZkCh4MMr9JL//08EAA "05AB1E – TIO Nexus")
[Answer]
# PHP, 51 bytes
```
$a.=$a=$argn;echo" __
/$a\
/$a$a\
|$a$a|
\____/";
```
PHP, 58 Bytes without physical linebreaks
```
$a.=$a=$argn;echo" __\n /$a\\\n/$a$a\\\n|$a$a|\n\\____/";
```
run this with `-R` option
61 Bytes
```
echo strtr(" __\n /88\\\n/8888\\\n|8888|\n\\____/",8,$argn);
```
[Answer]
## BF, ~~142~~ 140 bytes
```
++++[->++++<]>[->+++>++++++>+>++++++>++>++++++++<<<<<<],>->---->------>->..<..<.>>.<<<<.<..
>>.>.<<.<....>>.>.>>>----.<....>.<<<.<.>>....<<<.
```
This is split across two lines for clarity; the newline is not counted.
It's fairly easy to write this sort of thing in BF, but it's non-trivial how to optimize the order of the cells to minimize movement. I wrote a brute-forcer script to try all the combinations and find the shortest, and I golfed it a bit to account for a golfing opportunity I hadn't included in the brute-forcer.
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 114 bytes
```
-----[[<+>->++>++<<]->]<+++++++++++<+..<..>>.<.<<.>>,..<---.>>.<<<.>>....<.>>.<<<<---.>>>....<<<.>>>>.<<.+++....<.
```
[Try it online!](https://tio.run/##RYxRCoBACERP05c5Jxi8yLIfFQQR9BF0fnM1SESZN6PrvRzX/mynu45qjWJqItFkV@uUvygAAbOYZOw5dFwlSQCMRMnPKZZucsSjirlPLw "brainfuck – Try It Online")
I've used [BF Crunch](https://github.com/primo-ppcg/BF-Crunch) here to find a more optimal way to generate the individual characters.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~95~~ ~~88~~ 85 bytes
Thanks to Albert for -7 bytes
Thanks also to ceilingcat -3 bytes
```
f(c){for(int*s=L" __\n /00\\\n/0000\\\n|0000|\n\\____/\n";*s;s+=printf(*s%6?s:&c));}
```
[Try it online!](https://tio.run/##S9ZNT07@/z9NI1mzOi2/SCMzr0Sr2NZHSUEhPj4mT0HfwCAmJiYPSEEYNSBGTUxeTEw8EOjH5ClZaxVbF2vbFhQBdaZpaBWrmtkXW6kla2pa1/7nyk3MzNPQ5Krm4lIAgjQNdQd1TWsYWwvG5qr9DwA "C (gcc) – Try It Online")
[Answer]
# SpecBAS - 70 bytes
```
1 INPUT a$: ?" __"'" /";a$*2;"\"'"/";a$*4;"\"'"|";a$*4;"|"'"\____/"
```
`?` is shorthand for `PRINT` command, and apostrophe moves cursor to next line.
[Answer]
# [Röda](https://github.com/fergusq/roda), 46 bytes
```
{a=` __
/-\
/--\
|--|
\____/`a~="-",_*2;[a]}
```
[Try it online!](https://tio.run/nexus/roda#DcTRCoIwAAXQ592vuBiFRmPRYzH8kBZzYCMRN7F8cvrry/NwBtcFLvTUNHlxuiGtBZU0UHIvSZlg7E41btOFLC72fHs83WvNwseJPdsIIcapCz@O8/dT9hUTfVlBtDG8seYTDjjCYsMVd9R/ "Röda – TIO Nexus")
[Answer]
# Python, 59 bytes
```
lambda n:r''' __
/a\
/aa\
|aa|
\____/'''.replace('a',n*2)
```
[Answer]
# Lua, 66 bytes
```
print((([[ __
/ee\
/eeee\
|eeee|
\____/]]):gsub("e",io.read())))
```
((([[#NailedIt]])))
[Answer]
# [Retina](https://github.com/m-ender/retina), 41 bytes
```
.
$0$0
..
__¶ /$0\¶/$0$0\¶|$0$0|¶\____/
```
[Try it online!](https://tio.run/nexus/retina#@6/HpWKgYsClp8eloBAff2ibgr6KQcyhbfogUSBdA6JrDm2LiQcC/f//VQA "Retina – TIO Nexus")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 35 bytes
```
" __
/01
/001
|00|
1____/"d0U²1'\
```
[Try it online!](https://tio.run/nexus/japt#@6@koBAfz6Wgb2DIpW8AJGoMDGq4DOOBQF8pxSD00CZD9Zj//5XqlAA)
### 41-byte solution:
```
[S²'_²RS'/U²'\R'/U²²'\R'|U²²'|R'\'_²²'/]q
```
[Try it online!](https://tio.run/nexus/japt#@x8dfGiTevyhTUHB6vqhQGZMEJiGsGogrJog9RiQGiBTP7bw/3@lOiUA)
[Answer]
# [R], 65 bytes
```
cat(gsub('x',scan(,'')," __\n /xx\\\n/xxxx\\\n|xxxx|\n\\____/"))
```
Pretty unspectacular, please find a shorter one in R...
It's your basic gsub
[Answer]
## C++ 208 bytes
In response to comments:
This is a complete re-post.
```
#include<iostream>
using namespace std;int main(){char e;cin>>e;cout<<" __ \n";cout<<" /"<<e<<e<<"\\ "<<endl;cout<<"/"<<e<<e<<e<<e<<"\\"<<endl;cout<<"|"<<e<<e<<e<<e<<"|"<<endl;cout<<"\\____/ \n";return 0;}
```
[Answer]
## [C#](http://csharppad.com/gist/156803275214446f2e7334d7bc80f6aa), 56 bytes
---
**Golfed**
```
i=>" __\n /i\\\n/ii\\\n|ii|\n\\____/".Replace("i",i+i);
```
---
**Ungolfed**
```
i =>
" __\n /i\\\n/ii\\\n|ii|\n\\____/"
.Replace( "i", i + i );
```
---
[Answer]
# [C(gcc)](https://gcc.gnu.org/), 87 bytes
```
e(d){printf(" __\n /%c%c\\\n/%c%c%c%c\\\n|%c%c%c%c|\n\\____/\n",d,d,d,d,d,d,d,d,d,d);}
```
printf without stdio.h causes warnings but no errors, allowing successful compilation.
### Explanation
Printf statement that crams everything into one line, formatting the decoration character with %c.
[Try it online](https://tio.run/nexus/c-gcc#ZYzBCoMwDIbvPkUoCO106GG34l7EiEjVrYdF6dpd1L26s3Xusj8Q/j9fkrXjrZhGo8n2nAHUNRJksYoVIlIwR5iPMCMh1psyJJa2/yXksm4P4dFo4t405qZSUAM9Lah7Y@DkR6@yEjBFsMkvaRls4IOzo7PlpYIC2Dl@s531gwGui1x@ua6uuQSdJMcfr47/qNjPltBNZ50hyGW0ROsH)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 84 bytes
```
g(f){char e[]={f,f,f,f};printf(" __\n /%.2s\\\n/%.4s\\\n|%.4s|\n\\____/\n",e,e,e);}
```
[Try it online!](https://tio.run/nexus/c-gcc#Tc3BCsIwDAbg@54iTObaUZ2It@KTGClltHUHg9TpZauvPttCYfkv308IWR2zfB4e2oO53a@zFTlBvvxIk2U1gFJI0DfH8xsRKeKSsSQsSIgqTo9UC5PCZVjjKTz1SCxBezcIyC@6LpYvh7mCOI61h5bL4mbjXzSUst8sdhtDsTfTxxOcZBXWPw "C (gcc) – TIO Nexus")
] |
[Question]
[
I've already made this in Python, but it seems that it could be shortened a lot:
```
txt = input("Type something.. ")
c = "#"
b = " "
print(c * (len(txt) + 4))
print(c, b * len(txt), c)
print(c, txt, c)
print(c, b * len(txt), c)
print(c * (len(txt) + 4))
```
So if the user types:
```
Hello World
```
The program prints:
```
###############
# #
# Hello World #
# #
###############
```
---
Fewest bytes wins—and of course, the answer can be written in any language.
[Answer]
# CJam, ~~22~~ 20 bytes
```
qa{4/3*' +f+W%z}8/N*
```
[Test it here.](http://cjam.aditsu.net/#code=qa%7B4%2F3*32%2Bcf%2BW%25z%7D8%2FN*&input=Hello%20World)
## Explanation
How do you wrap a 2D grid of characters in one layer of spaces (or any other character)? Correct: four times, you append a space to each line and then rotate the grid by 90 degrees. That's exactly what I'm doing here with eight rotations: four for spaces, four for `#`:
```
qa e# Read the input and wrap it in an array, to make it a 2D grid.
{ e# Execute this block for each value from 0 to 7.
4/3* e# Divide by 4, multiply by 3. Gives 0 for the first four iterations and
e# and 3 for the other four.
' + e# Add the result to a space character (space + 3 == #).
f+ e# Append this to each line of the grid.
W%z e# Reverse the lines, then transpose the grid - together these rotate it.
}8/
N* e# Join the lines of the grid by newlines.
```
[Answer]
## vim, ~~28~~ 27 keystrokes
```
I# <esc>A #<esc>Y4PVr#G.kwv$3hr kk.
```
Assumes input is provided as a single line of text in the currently open file.
Explanation:
```
I# <esc> put a "#" and space at the beginning of the line
A #<esc> put a space and "#" at the end of the line
Y4P copy the line 4 times
Vr# replace the entirety of the first line with "#"s
G. do the same for the last line
kwv$3hr<space> replace middle of the fourth line with spaces
kk. do the same for the second line
```
This can also be run as a "program" like so:
```
echo 'Hello World' | vim - '+exe "norm I# \<esc>A #\<esc>Y4PVr#G.kwv$3hr kk."'
```
Which is a bit convoluted, but it works.
[Answer]
# [pb](https://esolangs.org/wiki/Pb) - 89 bytes
```
v[4]w[Y!-1]{b[35]^}w[B!0]{t[B]vvv>>b[T]^^^<}v>>>w[Y!4]{b[35]v}w[X!0]{b[35]^[Y]b[35]v[4]<}
```
This is the kind of challenge pb was made for! Not that it's *competitive* for this kind of challenge or anything. It's still a horrible golf language. However, challenges like this are a lot less of a pain to solve in pb than others are. Since pb treats its output as a 2D canvas and is able to write to any coords, anything involving positioning text/drawing around text (i.e. this challenge) is handled rather intuitively.
Watch it run:

This visualization was created with an in-development version of pbi, the pb interpreter. The line with the blue background is `Y=-1`, where input is stored when the program starts. The rectangle with the red background is the current location of the brush. The rectangles with yellow backgrounds are anywhere the ascii character 32 (a space) is explicitly written to the canvas. Any blank spaces without this background actually have the value `0`, which is converted to a space.
Here's the code with the comments I used while writing it, with some thematically relevant section headers ;)
```
################################
# #
# Handle first column oddities #
# #
################################
v[4] # Start from Y=4 and go up (so we land on input afterwords)
w[Y!-1]{ # While we're on the visible part of the canvas
b[35]^ # Write "#", then go up
}
#########################
# #
# Insert text of output #
# #
#########################
w[B!0]{ # For each character of input
t[B] # Save input char in T
vvv>> # Down 3 + right 2 = where text part of output goes
b[T]^^^< # Write T and go to next char
}
###############################
# #
# Handle last column oddities #
# #
###############################
v>>> # Go to Y=0, X=(X of last text output's location + 2)
w[Y!4]{ # Until we reach the last line of output
b[35]v # Draw "#", then go down
}
###########################
# #
# Loop to finish Y=0, Y=4 #
# #
###########################
w[X!0]{ # Until we've gone all the way left
b[35]^[Y] # Print "#" at Y=4, go to Y=0
b[35]v[4] # Print "#" at Y=0, go to Y=4
< # Move left, printing until output is complete
}
```
[Answer]
# brainfuck - 156 bytes
```
++++++++++>,[>>+++++[<+++++++>-],]<....[.---<<]>>+++>>+++.---.[.>>]<<.+++.[<]>.>>+++.---.<[.>>]<<<.>>.---[<]>.--->>+++.---[.>>]<<..+++.---[<]>[+++.>>]<<....
```
This is probably golfable. There's some places where I didn't know if it would be better to store a value somewhere for reuse or to remake it/go get it from elsewhere on the tape. Instead of doing the work to figure it out, I didn't do that. :D
With comments:
```
++++++++++> Place a 10 (\n) at the beginning of the tape
,[>>+++++[<+++++++>-],] Place a byte of input; place a 35 (#); repeat until end of input
<.... Print the last cell (35; #) 4 times
[.---<<] Print every noninput cell on the tape in reverse (one # for each byte of input; then \n)
After printing each cell; decrease it by 32
>>+++ Increase the 7 back up to 10
>>+++.---. Increase a 32 (space) back up to 35 (#); print it; put it back to 32 and print again
[.>>] Print every 32 on the tape (one for each byte of input)
<<.+++. Print the last space again; increase it by 3 and print the resulting #
[<]>. Go to the beginning of the tape and print the \n
>>+++.---. Increase a 32 (space) back up to 35 (#); print it; put it back to 32 and print again
<[.>>] Print every byte of input
<<<.>>.--- Print a space; then print a 35 (#} that was left behind earlier; Set it back to 32 after
[<]>.--- Go to the beginning of the tape and print the \n; decrease by 3
>>+++.--- Set a space to #; print it; set it back to space
[.>>] Print all spaces
<<..+++.--- Print a space twice more; set it to #; print it again; set it back to space
[<]> Go to the "newline" (currently a 7 instead of 10)
[+++.>>] Increase by 3; print; do the same for all spaces (to set them to # before printing)
<<.... Print the last # 4 more times
```
[Answer]
# K, 21 bytes
```
4(|+"#",)/4(|+" ",)/,
```
Enlist the string, Add a space to all four sides of a string, then add an octothorpe to each side of the string. In action:
```
4(|+"#",)/4(|+" ",)/,"Hello."
("##########"
"# #"
"# Hello. #"
"# #"
"##########")
```
Works in oK, Kona and k5.
There are quite a few variations within one character of length which remove the redundancy in the above, but none seem to break even when we only have to perform the "wrap" operation twice:
```
{x{|+x," #"y}/&4 4},:
{x{|+x,y}/,/4#'" #"},:
{x{|+x,y}/" #"@&4 4},:
{|+x,y}/[;" #"@&4 4],:
```
[Answer]
# Python 3, 88 bytes
Thanks @WorldSEnder
```
s=" ";n=s+input()+s
b=len(n)
h="#";x=h*(b+2);y=h+s*b+h;z="\n"
print(x+z+y+z+h+n+h+z+y+z+x)
```
## Example I/O:
```
This is a test
##################
# #
# This is a test #
# #
##################
```
[Answer]
# [Python 2](https://docs.python.org/2/), 67 bytes
```
s=input()
n=len(s)+2
y='#\n#'
x='#'*-~n+y+' '*n+y
print x,s,x[::-1]
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v9g2M6@gtERDkyvPNic1T6NYU9uIq9JWXTkmT1mdqwLIUNfSrcvTrtRWV1DXAtJcBUWZeSUKFTrFOhXRVla6hrH//yt5pObk5CuE5xflpCgBAA "Python 2 – Try It Online")
[Answer]
# Pyth, 31 bytes
```
Js[K\#*d+2lzKb*K+4lz)_Jjd[KzK)J
```
Thanks to people in comments giving hints on how to golf further, I really don't know the language well as you can (probably) tell.
[Answer]
# Perl, ~~43~~ 76 bytes
Transform each text input line as specified:
```
s/.*/($x=("#"x(4+($z=length))))."\n".($y="#"." "x(2+$z)."#\n")."# $& #\n$y$x"/e
```
For example:
```
echo surround a long string with pounds |
perl -ple's/.*/($x=("#"x(4+($z=length))))."\n".($y="#"." "x(2+$z)."#\n")."# $& #\n$y$x"/e'
######################################
# #
# surround a long string with pounds #
# #
######################################
```
Here’s how to see what it’s really doing:
```
perl -MO=Deparse,-p,-q,-x9 -ple '($x=("#"x(4+($z=length))))."\n".($y="#"." "x(2+$z)."#\n")."# $& #\n$y$x";'
BEGIN { $/ = "\n"; $\ = "\n"; }
LINE: while (defined(($_ = <ARGV>))) {
chomp($_);
(((($x = ('#' x (4 + ($z = length($_))))) . "\n") . ($y = (('#' . (' ' x (2 + $z))) . "#\n"))) . (((('# ' . $&) . " #\n") . $y) . $x));
}
continue {
(print($_) or die((('-p destination: ' . $!) . "\n")));
}
-e syntax OK
```
So something more like this:
```
((
(($x = ('#' x (4 + ($z = length($_))))) . "\n")
. ($y = (('#' . (' ' x (2 + $z))) . "#\n"))
)
. (((('# ' . $&) . " #\n") . $y) . $x)
)
```
[Answer]
# Perl 5.14+, ~~57~~ 56 bytes
```
perl -lpe '$_=join"#
#",($_=" $_ ",y// /cr,"#".y//#/cr)[2,1,0..2]'
```
54 bytes + 2 bytes for `-lp` (if input doesn't end in a newline, `-l` can be dropped to save one byte).
Accepts input on STDIN:
```
$ echo Hello World | perl -lpe '$_=join"#
#",($_=" $_ ",y// /cr,"#".y//#/cr)[2,1,0..2]'
###############
# #
# Hello World #
# #
###############
```
## How it works
The core of the program is a list slice:
```
($_=" $_ ",y// /cr,"#".y//#/cr)[2,1,0..2]'
```
This provides a compact way to store the three unique rows of the output (the first two rows of the bounding box are the same as the last two, only mirrored). For the input string `foo`, the results of the slice would be:
```
index value
--------------
2 "######"
1 " "
0 " foo "
1 " "
2 "######"
```
Joining these values with `#\n#` gives us our box.
Note that Perl 5.14+ is required to use the non-destructive `r` modifier to the transliteration operator `y///`.
[Answer]
# JavaScript (ES6), 73
Heavily using template string, the 2 newlines are significant and counted.
Test running the snippet below in any EcmaScript 6 compliant browser (FireFox and latest Chrome, maybe Safari).
```
f=s=>(z=c=>`*${c[0].repeat(s.length+2)}*
`)`*`+z` `+`* ${s} *
`+z` `+z`*`
// Less golfed
U=s=>(
z=c=>'*' + c.repeat(s.length+2) + '*\n',
z('*') + z(' ') + '* ' + s + ' *\n' + z(' ') + z('*')
)
// TEST
O.innerHTML=f('Hello world!')
```
```
<pre id=O></pre>
```
This is quite shorter than my first try, derived from [this other challenge](https://codegolf.stackexchange.com/a/57470/21348):
```
f=s=>(q=(c,b,z=c.repeat(b[0].length))=>[z,...b,z].map(r=>c+r+c))('*',q(' ',[s])).join`\n`
```
[Answer]
## Python 2, 74
```
s='# %s #'%input()
n=len(s)
b='\n#'+' '*(n-2)+'#\n'
print'#'*n+b+s+b+'#'*n
```
Takes input in quotes like `"Hello World"`.
* The third line is the input encased in `# _ #`.
* The second and fourth lines `b` are `# #` with the right number of spaces, surrounded with newlines to either side to take care of all four newlines.
* The first and fifth lines are `#` multiplied to the length of the input
The lines are concatenated and printed.
[Answer]
# MATLAB, ~~93~~ 91 bytes
Not the prettiest, but it gets the job done.
```
t=[32 input('','s') 32];m='#####'.';n=repmat('# ',numel(t),1)';disp([m [n;t;flipud(n)] m])
```
# Code Explanation
## Step #1
```
t=[32 input('','s') 32];
```
Read in a string from STDIN and place a leading and trailing single space inside it. 32 is the ASCII code for a space and reading in the input as a string type coalesces the 32s into spaces.
## Step #2
```
m='#####'.';
```
Declare a character array of 5 hash signs in a column vector.
## Step #3
```
n=repmat('# ',numel(t),1)'
```
Create a 2 row character matrix that is filled by hash signs first followed by white space after. The number of characters is the length of the input string plus 2 so that we can accommodate for the space before and after the string.
## Step #4
```
disp([m [n;t;flipud(n)] m])
```
We're going to piece everything together. We place the first column of 5 hashes, followed by the centre portion and followed by another column of 5 hashes. The centre portion consists of the 2 row character matrix created in Step #3, the input string itself which has a trailing and leading space, followed by the 2 row character matrix but reversed.
# Example Runs
```
>> t=[32 input('','s') 32];m='#####'.';n=repmat('# ',numel(t),1)';disp([m [n;t;flipud(n)] m])
This is something special for you
#####################################
# #
# This is something special for you #
# #
#####################################
>> t=[32 input('','s') 32];m='#####'.';n=repmat('# ',numel(t),1)';disp([m [n;t;flipud(n)] m])
Hello World
###############
# #
# Hello World #
# #
###############
>> t=[32 input('','s') 32];m='#####'.';n=repmat('# ',numel(t),1)';disp([m [n;t;flipud(n)] m])
I <3 Code Golf StackExchange!
#################################
# #
# I <3 Code Golf StackExchange! #
# #
#################################
```
[Answer]
# Ruby, 83 bytes
I guess it could be golfed further, but since there's no Ruby answer yet, here it is:
```
s=ARGV[0]
n=s.size
r="#"*(n+4)
t="\n#"+" "*(n+2)+"#\n"
puts r+t+"\n# "+s+" #\n"+t+r
```
[Answer]
## Pyke (noncompetitive), 6 bytes
```
.X".X#
```
[Try it here!](http://pyke.catbus.co.uk/?code=.X%22.X%23&input=Hello%2C+World%21)
Pyke was written after the challenge and is therefore noncompetitive.
```
.X" - surround string in spaces
.X# - surround string in hashes
```
`.X` takes a string and a string constant arg and surrounds a string with that group of characters. The constant arg can be up to 8 characters and have different effects on how the string is surrounded.
[Answer]
# PHP, ~~95~~ 93 bytes
Not exactly brilliant or anything similar, but it was actually fun!
```
$l=strlen($s=" $argv[1] ");printf("#%'#{$l}s#
#%1\${$l}s#
#$s#
#%1\${$l}s#
#%1\$'#{$l}s#",'');
```
Not exactly pretty or anything, but it works brilliantly!
---
Thanks to [@Titus](https://codegolf.stackexchange.com/users/55735/titus) for saving 2 bytes.
[Answer]
# [MAWP](https://esolangs.org/wiki/MAWP), 117 107 bytes
```
%|0_!!!3M[1A75W;]25W;%75W;1M[1A84W;]75W;25W;75W;84W;~[;]84W;75W;25W;%75W;1M[1A84W;]75W;25W;%3M[1A75W;]25W;.
```
-10 bytes from Dion.
[Try it!](https://8dion8.github.io/MAWP/?code=%25%7C0_!!!3M%5B1A75W%3B%5D25W%3B%2575W%3B1M%5B1A84W%3B%5D75W%3B25W%3B75W%3B84W%3B%7E%5B%3B%5D84W%3B75W%3B25W%3B%2575W%3B1M%5B1A84W%3B%5D75W%3B25W%3B%253M%5B1A75W%3B%5D25W%3B.&input=Hello%20World)
[Answer]
# [J](http://jsoftware.com/), 21 bytes
```
'#'g' '&g=.|.@|:@,^:4
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/1ZXV09UV1NXSbfVq9BxqrBx04qxM/mtypSZn5CukKehYqXuk5uTkK4TnF@WkqCMJe@XnJWao/wcA "J – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 82 bytes
```
d,h,s,m=input(),'#',' ','\n'
l=len(d)+2
print(l*h+h,l*s,s+d+s,l*s,l*h+h,sep=h+m+h)
```
[Try it online!](https://tio.run/##JcgxDoAgDEDR3VNoHADbSWd2b@DiCElJaiEWB0@PRoefvPxyV8qytBaQUPHwScpVrUMzGjT92y6mY89RbHAwd@VMUi1PBIQ8KSoE0E//01g8wQHkWlsjc8Z@yyeH4QE "Python 3 – Try It Online")
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 145 bytes
```
i:0(?v
[1+2l57*o1
*o:&v>]~]ao57
2(?v>84*o1-:
aov>~~57*o
rv>84*:57*:@oo$
o>l3(?v
o57*ov>roo&:1[a
:2(?v>84*o1-
oaov>]~75*
(?;>57*o1-:0
```
Probably very overcomplicated but it works and is kind of short.
Just gotta love ><>.
The code prints the output line by line. Every line has at least two lines responsible for it. One to print and the to "clean up" after the first line, deleting useless garbage in the stack, printing newlines, registering the register, etc.
[Try it here](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiaTowKD92XG5bMSsybDx2WzE6XG4tOjAoP3Y+NTcqbzFcbipvOiZ2Pl1+XWFvNTdcbjIoP3Y+ODQqbzEtOlxuYW92Pn5+NTcqb1xucnY+ODQqOjU3KjpAb28kXG5vPmwzKD92XG5vNTcqb3Y+cm9vJjoxW2FcbjoyKD92Pjg0Km8xLVxub2Fvdj5dfjc1KlxuKD87PjU3Km8xLTowIiwiaW5wdXQiOiJjYXQiLCJzdGFjayI6IiIsInN0YWNrX2Zvcm1hdCI6Im51bWJlcnMiLCJpbnB1dF9mb3JtYXQiOiJjaGFycyJ9)
(This was the hardest golf I've done)
[Answer]
# C++, 198 Bytes
```
#include <iostream>
#include <string>
int i;int main(){std::string t,n,o;std::getline(std::cin,o);t="\n#";o="# "+o+" #";for(;i<o.size();i++){n+="#";if(i>1)t+=" ";}t+="#\n";std::cout<<n+t+o+t+n;}
```
My first stab at codegolf, and while I learned C++ is probably not the best language for golfing, I felt I did decently(?) for my first try.
**Ungolfed**
```
#include <iostream>
#include <string>
int i; //globals default to a value of 0
int main()
{
std::string t, n, o;
std::getline(std::cin, o);
t = "\n#"; // t needs hashes at start and end, places hash at start here
o = "# " + o + " #"; // put hash at each end of input
for(; i < o.size(); i++) {
n += "#"; // fills n with hashes
if(i > 1) {
t += " "; // fill t with spaces between hashes, has two fewer spaces than n has hashes
}
}
t += "#\n"; // puts final hash at end of t
std::cout << n + t + o + t + n; // final output
}
```
n, o and t represent the fully hashed lines, the input (with hashes at each end) and the lines between the input and the hashed lines respectively.
[Answer]
## [><>](http://esolangs.org/wiki/Fish), ~~106~~ 104 Bytes
I get the feeling that ><> may not be the best language for this, but I've come too far to give up and not post this. The `*` at the end of line 4 is supposed to be a space. Don't you love how incredibly grotesque this code looks? Try it [online](http://fishlanguage.com/playground).
```
<v?(0:i
v>~" ## "}}l:::
>"#"o1-:?!v02.>~a"#"oo
"-2ooa"#"~<.31v!?:-1o"
7v?=3loroo"#"a<.4
.>";^"e3pa2p093
```
Here's a version without anything but direction changers to give an idea of how the pointer moves (note that I've left out the "teleport" statements, i.e. `.`).
**Direction flow:**
```
<v
v>
> v >
< v
v <
>
```
---
## Explanation
My visualization of the stack will be based off of the input `input`. ><> is a two dimensional language, so pay attention to where the pointer is moving between lines, as it executes code underneath it (in this code `<>v^` are primarily used to change direction). I'll be starting my explanations from where the pointer starts. Note that there will be two lines repeated, as the pointer moves backwards after the fifth line.
What I always find cool about ><> is its ability to modify its own source code, and I make use of it in this program. Lines 3 and 4 are reused to print the last two lines through a modification of a character in each.
**Line 1 :** Input loop
```
<v?(0:i
< change direction to left
(0:i checks if input is less than 0 (no input defaults to -1)
v? change direction to down if so
```
Stack: `[-1,t,u,p,n,i]`
---
**Line 2:** Generates third line of output
```
v>~" ## "}}l:::
>~" ## "}} remove -1 (default input value) from stack and pads with # and spaces
l::: push 4 lengths of padded input
```
Stack: `[9,9,9,9,#, ,t,u,p,n,i, ,#]`
---
**Line 3:** Prints first line of output
```
>"#"o1-:?!v02.>~a"#"oo
>"#"o print "#"
1- subtract 1 from length (it's at the top of the stack)
:?!v move down if top of stack is 0
```
Stack: `[0,9,9,9,#, ,t,u,p,n,i, ,#]`
Output:
```
#########
```
---
**Line 4:** Prints second line of output
```
"-2ooa"#"~<.31v!?:-1o"*
-2ooa"#"~< pops 0, prints newline, "#", then decrements length by 2
" o"* prints space (* is supposed to be space char)
-1 decrements top of stack
.31v!?: changes direction to down if top of stack is 0, else jumps back to "
```
Stack: `[0,9,9,#, ,t,u,p,n,i, ,#]`
Output (`*` represents space):
```
#########
#*******
```
---
**Line 5:** Prints third line of output
```
7v?=3loroo"#"a<.4
oo"#"a< prints "#",newline
r reverses stack
7v?=3lo .4 outputs until stack has 3 values, then changes direction to down
```
Stack: `[9,9,0]`
Output:
```
#########
# #
# input #
```
---
**Line 6:** Sets itself up to print fourth and fifth lines of output
```
.>";^"e3pa2p093
>";^" push ";",then "^"
e3p place "^" as the fifteenth character on line 4
a2p place ";" as the eleventh character on line 3
0 push a value (value doesn't matter -- it will be deleted)
. 93 jump to the tenth character on line 4
```
Stack: `[0,9,9,0]`
---
**Line 4:** Print fourth line of output
```
"-2ooa"#"~<.31^!?:-1o"*
ooa"#"~< delete 0 (unnecessary value pushed), then print newline,"#"
-2 subtract two from value on top of stack (length)
" .31^!?:-1o"* print space until top of stack is 0, then change direction to up
```
Stack: `[0,9,0]`
Output (`*` represents space):
```
#########
# #
# input #
#*******
```
---
**Line 3:** Print last line of output
```
"#"o1-:?!;02.>~a"#"oo
>~a"#"oo pop top of stack, print "#", newline
"#"o1-:?!;02. print "#" until top of stack is 0, then terminate
```
Stack: `[0,0]`
Output:
```
#########
# #
# input #
# #
#########
```
[Answer]
# PHP, ~~93~~ 91 bytes
```
$b=str_pad("",$e=strlen($s=" $argv[1] "));echo$h=str_pad("",2+$e,"#"),"
#$b#
#$s#
#$b#
$h";
```
Takes input from command line argument; escape spaces or use single quotes. Run with `-r`.
[Answer]
## C# - 142 bytes (method body is 104)
```
class P{static void Main(string[]a){for(int i=0;++i<6;)System.Console.Write("#{0}#\n",i==3?$" {a[0]} ":new string(" #"[i%2],a[0].Length+2));}}
```
Ungolfed:
```
class P
{
static void Main(string[] a)
{
for (int i = 0; ++i < 6;)
System.Console.Write("#{0}#\n", i == 3 ? $" {a[0]} " : new string(" #"[i%2], a[0].Length + 2));
}
}
```
[Answer]
# [Haskell](https://www.haskell.org/), 70 bytes
```
x a=(\s->s++a++reverse s)$concat["##",'#'<$a,"##\n# ",' '<$a," #\n# "]
```
[Try it online!](https://tio.run/##JcdBDkAwEEDRq0xaSUm5AU5gxw6LSU1SQUmnxO2rieQv/rPIG@17jC9gk09ctaw1au3pIc8EXGTmdAbDKKQUpZKqzrBMPzkJyfAbfs/xwNU11x364DuXv2KwK0MKwZwLiSJ@ "Haskell – Try It Online")
---
# [Haskell](https://www.haskell.org/), 68 bytes
```
x a=id<>pure a<>reverse$concat["##",'#'<$a,"##\n# ",' '<$a," #\n# "]
```
~~Try it online!~~ (Doesn't work since TIO uses an old GHC where `<>` isn't imported by default.)
---
# [Haskell](https://www.haskell.org/), 63 bytes
```
x a|s<-['#'<$a,"####\n# ",' '<$a," #\n# "]>>=id=s++a++reverse s
```
[Try it online!](https://tio.run/##JYhBDkAwEAC/smklJeUH6gVu3HDYsIkGJd0SB38viclcZmbkhdY1xhvw4bLolFRlgrmQH72TIHIF/4G/h6oydjKsNWrt6SLPBBw3tM4cZ2iCr116i3a2DJ8I4z6RyOIL "Haskell – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-n`, 51 bytes
```
map{say"#$_#"}($_=" $_ ",y// /cr,y//#/cr)[2,1,0..2]
```
[Try it online!](https://tio.run/##K0gtyjH9/z83saC6OLFSSVklXlmpVkMl3lZJQSVeQUmnUl9fQT@5CEQrA2nNaCMdQx0DPT2j2P//S1KLSxRyU4uLE9NT/@UXlGTm5xX/1/U11TMwNPivmwcA "Perl 5 – Try It Online")
[Answer]
# [MAWP](https://esolangs.org/wiki/MAWP), 108 bytes
```
%|_4M[75W;1A]%52W;75W;84W;_1M[84W;1A]%75W;25W;75W;84W;0__~[;]%84W;75W;52W;75W;1M![84W;1A]%75W;52W;2M[75W;1A]
```
[Try it!](https://8dion8.github.io/MAWP/?code=%25%7C_4M%5B75W%3B1A%5D%2552W%3B75W%3B84W%3B_1M%5B84W%3B1A%5D%2575W%3B25W%3B75W%3B84W%3B0__%7E%5B%3B%5D%2584W%3B75W%3B52W%3B75W%3B1M!%5B84W%3B1A%5D%2575W%3B52W%3B2M%5B75W%3B1A%5D&input=Yay%2C%20it%20works!)
Now an actually valid solution
Explanation:
```
% Remove the 1 already on stack
| Push input as ascii
_4M Push length of stack + 4
[75W;1A]% Print that many #
52W; Print a newline
75W; Print #
84W; Print a space
_1M Push length of stack + 1
[84W;1A]% Print that many spaces
75W;25W; Print # with a newline
75W;84W; Print # with a space
0 Push a 0
__ Push length of stack twice
~[;] Reverse stack and print until 0
% Remove top of stack
84W;75W;52W; Print a space, # and newline
75W; Print #
1M! Add 1 to top and duplicate it
[84W;1A]% Print that many spaces
75W;52W; Print # with a newline
2M[75W;1A] Add 2 and print that many #
```
[Answer]
# [R](https://www.r-project.org/), ~~106~~ 95 bytes
```
function(t,l=nchar(t),n="#
#",s=" ",`&`=strrep)cat(a<-"#"&l+3,b<-c(n,s&l+2,n),s,t,s,b,a,sep="")
```
[Try it online!](https://tio.run/##VY3BCsIwEETv/Yq4gZLg9qLX5uA/eBTsNkZSKJuS3X5/jTeFGZiB4U09Mkl@Ui07v8Lx3jnqUtgproFjpurUIwewnQWUAAZw6qcgWmvafCR1NA5goV/PV5zHITpGaeWC7FFQm2cklLQFAP975uCeFzFNZDSJgu@@OHhwS3@7GxfNqZrC6dQYHw "R – Try It Online")
*-5 bytes thanks to [@Dominic](https://codegolf.stackexchange.com/users/95126/dominic-van-essen)*, which led to further golfs.
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 20 bytes
```
g4+'#ש,¹' .ø'#.ø,®,
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/3URbXfnw9EMrdQ7tVFfQO7xDXRlI6Bxap/P/v6GRsYmpmbmFpQGCBQA "05AB1E (legacy) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `j`, 29 bytes
```
L4+\#*:\#?L½›꘍m:„W2\#ð+Ḃ?$++Ṁ
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=j&code=L4%2B%5C%23*%3A%5C%23%3FL%C2%BD%E2%80%BA%EA%98%8Dm%3A%E2%80%9EW2%5C%23%C3%B0%2B%E1%B8%82%3F%24%2B%2B%E1%B9%80&inputs=%22This%20is%20a%20test%22&header=&footer=)
For some reason Vertical mirror and center doesn't work
] |
[Question]
[
Given no input, output this interesting alphabet pattern in either case (the case has to be consistent) via an [accepted output method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods):
```
A
AB
ACBC
ADBDCD
AEBECEDE
AFBFCFDFEF
AGBGCGDGEGFG
AHBHCHDHEHFHGH
AIBICIDIEIFIGIHI
AJBJCJDJEJFJGJHJIJ
AKBKCKDKEKFKGKHKIKJK
ALBLCLDLELFLGLHLILJLKL
AMBMCMDMEMFMGMHMIMJMKMLM
ANBNCNDNENFNGNHNINJNKNLNMN
AOBOCODOEOFOGOHOIOJOKOLOMONO
APBPCPDPEPFPGPHPIPJPKPLPMPNPOP
AQBQCQDQEQFQGQHQIQJQKQLQMQNQOQPQ
ARBRCRDRERFRGRHRIRJRKRLRMRNRORPRQR
ASBSCSDSESFSGSHSISJSKSLSMSNSOSPSQSRS
ATBTCTDTETFTGTHTITJTKTLTMTNTOTPTQTRTST
AUBUCUDUEUFUGUHUIUJUKULUMUNUOUPUQURUSUTU
AVBVCVDVEVFVGVHVIVJVKVLVMVNVOVPVQVRVSVTVUV
AWBWCWDWEWFWGWHWIWJWKWLWMWNWOWPWQWRWSWTWUWVW
AXBXCXDXEXFXGXHXIXJXKXLXMXNXOXPXQXRXSXTXUXVXWX
AYBYCYDYEYFYGYHYIYJYKYLYMYNYOYPYQYRYSYTYUYVYWYXY
AZBZCZDZEZFZGZHZIZJZKZLZMZNZOZPZQZRZSZTZUZVZWZXZYZ
```
Trailing spaces and newlines are acceptable, [standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed, and this happens to be [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
ØAjṪ$Ƥż¹Y
```
[Try it online!](https://tio.run/##ARgA5/9qZWxsef//w5hBauG5qiTGpMW8wrlZ//8 "Jelly – Try It Online")
### How it works
```
ØAjṪ$Ƥż¹Y Main link. No arguments.
ØA Yield "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
Ƥ Map the link to the left over all prefixes, i.e., ["A", "AB", ...].
$ Combine the two links to the left into a chain.
Ṫ Tail; yield and remove the last letter of each prefix.
j Join the remainder, using that letter as separator.
ż¹ Zip the resulting strings and the letters of the alphabet.
Y Separate the results by linefeeds.
```
[Answer]
# C, 82 bytes
```
f(i,j){for(i=!puts("A");++i<26;puts(""))for(j=0;j++<i*2;)putchar(65+(j&1?j/2:i));}
```
[Try it online!](https://tio.run/##S9ZNT07@/z9NI1MnS7M6Lb9II9NWsaC0pFhDyVFJ01pbO9PGyMwaIqCkqQlSkGVrYJ2lrW2TqWVkrQmUSc5ILNIwM9XWyFIztM/SN7LK1NS0rv2fmVeikJuYmaehyVXNpQAEaRqa1ly1/wE)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 9 bytes
```
Eα⁺⪫…ακιι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3sUAjUUchIKe0WMMrPzNPw7kyOSfVOSMfLJytqaOQCcaamtb////XLcsBAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
α Predefined uppercase alphabet
E Map over each character
…ακ Get current prefix of alphabet
⪫ ι Join with current character
⁺ ι Append current character
Implicitly print on separate lines
```
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 7 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
Z[K*¹+]
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjNBJXVGRjNCJXVGRjJCJXVGRjBBJUI5JXVGRjBCJXVGRjNE,v=0,run)
Explanation:
```
Z[ ] for each prefix of the uppercase alphabet
K pop off the last letter
* and join the rest of the string with that character
¹+ and append the current iterated character to it
```
[Answer]
# [R](https://www.r-project.org/), 50 bytes
```
l=LETTERS
for(i in 0:25)cat(l[0:i],"
",sep=l[i+1])
```
[Try it online!](https://tio.run/##K/r/P8fWxzUkxDUomCstv0gjUyEzT8HAyshUMzmxRCMn2sAqM1ZHiUtJpzi1wDYnOlPbMFbz/38A "R – Try It Online")
Perhaps the cleverest part here is using `letters[0]` for the empty string to get `cat(character(0),'\n',sep="A")` to print the first line.
[Answer]
# [Python 2](https://docs.python.org/2/), 56 bytes
```
n=65;s='';exec'c=chr(n);print c.join(s)+c;s+=c;n+=1;'*26
```
[Try it online!](https://tio.run/##BcExCsAgDADAr3SLNlBQqEvIa4KgHaIYh/b16d38dhua3ZXLTcYAVN8qICxtBY00V9d9yPWMrsEiChmykCIngjMX9x8 "Python 2 – Try It Online")
[Answer]
# [6502 machine code](https://en.wikibooks.org/wiki/6502_Assembly) routine (C64), 39 bytes
```
A9 41 20 D2 FF AA A8 84 FB E4 FB B0 0B 8A 20 D2 FF 98 20 D2 FF E8 D0 F1 A9 0D
20 D2 FF A2 41 C0 5A F0 03 C8 D0 E1 60
```
Position-independet machine code subroutine, clobbers A, X and Y.
### [Online demo](https://vice.janicek.co/c64/#%7B%22controlPort2%22:%22joystick%22,%22primaryControlPort%22:2,%22keys%22:%7B%22SPACE%22:%22%22,%22RETURN%22:%22%22,%22F1%22:%22%22,%22F3%22:%22%22,%22F5%22:%22%22,%22F7%22:%22%22%7D,%22files%22:%7B%22calst.prg%22:%22data:;base64,AMCpQSDS/6qohPvk+7ALiiDS/5gg0v/o0PGpDSDS/6JBwFrwA8jQ4WA=%22%7D,%22vice%22:%7B%22-autostart%22:%22calst.prg%22%7D%7D)
The demo loads at `$C000`, so use `SYS49152` to call the routine.
---
### Commented disassembly:
```
A9 41 LDA #$41 ; 'A'
20 D2 FF JSR $FFD2 ; Kernal CHROUT (output character)
AA TAX ; copy to X (current pos)
A8 TAY ; copy to Y (current endpos)
.outerloop:
84 FB STY $FB ; endpos to temporary
.innerloop:
E4 FB CPX $FB ; compare pos with endpos
B0 0B BCS .eol ; reached -> do end of line
8A TXA ; current pos to accu
20 D2 FF JSR $FFD2 ; and output
98 TYA ; endpos to accu
20 D2 FF JSR $FFD2 ; and output
E8 INX ; next character
D0 F1 BNE .innerloop ; (repeat)
.eol:
A9 0D LDA #$0D ; load newline
20 D2 FF JSR $FFD2 ; and output
A2 41 LDX #$41 ; re-init current pos to 'A'
C0 5A CPY #$5A ; test endpos to 'Z'
F0 03 BEQ .done ; done when 'Z' reached
C8 INY ; next endpos
D0 E1 BNE .outerloop ; (repeat)
.done:
60 RTS
```
[Answer]
# [Uiua](https://uiua.org) 0.1.0, 21 [bytes](https://codegolf.stackexchange.com/questions/247669/i-want-8-bits-for-every-character/265917#265917)
```
∵(&p+@A♭≐⊂⇡.)⇡26&pf@A
```
[See it in action](https://uiua.org/pad?src=4oi1KCZwK0BB4pmt4omQ4oqC4oehLinih6EyNiZwZkBBCg==)
[Answer]
# Java 8, ~~93~~ ~~91~~ 90 bytes
```
v->{String t="";for(char c=64;++c<91;t+=c)System.out.println(t.join(c+"",t.split(""))+c);}
```
-1 byte thanks to *@OlivierGrégoire* by printing directly instead of returning
**Explanation:**
[Try it online.](https://tio.run/##LY7BCsIwDIbvPkXoqaVaEESQOt9AL4IX8VDj1M6ajjUbiOzZZ3VCfkLCD99Xuc7NYl1SdXkMGFxKsHWe3hMAT1w2V4cl7L4nQBf9BVAevqtTNv/6nDyJHXuEHRAUMHSzzXvPjacbcCGEvcZG4t01gMVyYbXG9WpuWReo9q/E5dPElk2d@xxIsqmiJ4laiCmbVAfPUgilNCrbD3bk1e05ZN4f@9N6Zmk5Uo8np0ZhMiipDeHv2g8f)
```
v->{ // Method with empty unused parameter and String return-type
String t=""; // Temp-String, starting empty
for(char c=64;++c<91; // Loop over the letters of the alphabet:
t+=c) // After every iteration: append the letter to the temp-String
System.out.println( // Print with trailing new-line:
r.join(c+"",t.split(""))
// The temp-String with the current letter as delimiter
+c);} // + the current letter as trailing character
```
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), ~~169~~ ~~143~~ ~~124~~ 123 bytes
```
L =LEN(1)
OUTPUT ='A'
I &UCASE (ARB K L) . R L . S :F(END)
O =K =
T R K L . K :F(O)
O =O K S :(T)
O OUTPUT =O :(I)
END
```
[Try it online!](https://tio.run/##K87LT8rPMfn/n9NHwdbH1U/DUJOL0z80JCA0RMFW3VGdy5NTLdTZMdhVQcMxyEnBW8FHU0FPIUjBB0gGK1i5abj6uYB0KNh6K9hyhXAGgZQA5bxBcv4QGX8gD6hWI0STy18Bbrg/UMRTkwuo//9/AA "SNOBOL4 (CSNOBOL4) – Try It Online")
Explanation for older version of the code:
```
i &ucase len(x) . r len(1) . s ;* set r to the first x characters and s to the x+1th.
o = ;* set o,i to empty string
i =
t r len(i) len(1) . k :f(o) ;* set k to the ith letter of r. on failure (no match), go to o.
o =o s k ;* concatenate o,s,k
i =i + 1 :(t) ;* increment i, goto t
o o s = ;* remove the first occurrence of s (the first character for x>1, and nothing otherwise)
output =o s ;* output o concatenated with s
x =lt(x,25) x + 1 :s(i) ;* increment x, goto i if x<25.
end
```
The problem here is the first line
using `o s k` will add an extra `s`eparator character at the beginning of each line and also not have an `s` at the end. This is OK because line `t` will jump over the following two lines when `x=0`. This means that `o` will still be blank. Hence, `o s =` will remove the first `s` character from `o`, and then we can simply print `o s` to have the appropriate last `s`.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 56 bytes
```
"A";65..89|%{([char[]](65..$_)-join[char]++$_)+[char]$_}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X8lRydrMVE/PwrJGtVojOjkjsSg6NlYDJKQSr6mblZ@ZBxaM1dYG8rUhbJX42v//AQ "PowerShell – Try It Online")
Loops `65` to `89`, each iteration constructing a `char` array of `65` to the current number `$_`, then `-join`s that array together into a string with the next character, then tacks on that character at the end.
Change the `89` to some other ASCII number to see the behavior better.
[Answer]
# [><>](https://esolangs.org/wiki/Fish), ~~44~~ 34 bytes
```
"BA"oao"ZA"\=?;1+40.
o1+:{::o}=?\:
```
[Try it online!](https://tio.run/##S8sszvj/X8nJUSk/MV8pylEpxtbe2lDbxECPK99Q26rayiq/1tY@xur/fwA "><> – Try It Online")
# [><>](https://esolangs.org/wiki/Fish), 44 bytes
```
"A"o10ao\55*=?;1+40.
1+:{:}=?\:"A"+o{:}"A"+o
```
[Try it online!](https://tio.run/##S8sszvj/X8lRKd/QIDE/xtRUy9be2lDbxECPy1Dbqtqq1tY@xgoorZ0PZIPp//8B "><> – Try It Online")
As I use a different route to producing the output I've posted my own ><> answer; The other ><> answer can be found [here.](https://codegolf.stackexchange.com/a/153190/62009)
Big thanks to Jo king for spotting I didn't need to keep putting "A" onto the stack if I just compared against "Z" instead of 26. (-10 bytes)
### Explanation
The explanation will follow the flow of the code.
```
"BA" : Push "BA" onto the stack;
[] -> [66, 65]
oao : Print the stack top then print a new line;
[66, 65] -> [66]
"ZA"\ : Push "ZA" onto the stack then move down to line 2;
[66, 90, 65]
o \: : Duplicate the stack top then print
1+: : Add one to the stack top then duplicate;
[66, 90, 65, 65]
{:: : Shift the stack right 1 place then duplicate the stack top twice;
[90, 65, 65, 66, 66]
o} : Print the stack top then shift the stack left 1 place;
[66, 90, 65, 65, 66]
=?\ : Comparison for equality on the top 2 stack items then move to line 1 if equal otherwise continue on line 2;
[66, 90, 65]
\=?; : Comparison for equality on the top 2 stack items then quit if equal else continue on line 1;
[66]
1+ : Add 1 to the stack top;
[67]
40. : Move the code pointer to column 4 row 0 of the code box and continue execution of code.
```
[Answer]
## JavaScript (ES6), 81 bytes
```
f=
_=>[..."ABCDEFGHIJKLMNOPQRSTUVWXYZ"].map((c,i,a)=>a.slice(0,i).join(c)+c).join`
`
;document.write('<pre>'+f());
```
Save 9 bytes if a string array return value is acceptable.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) (`-R` flag), ~~14~~ 12 bytes
*-2 bytes thanks to @Shaggy*
```
;B¬
ËiU¯E qD
```
[Test it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=O0KsCqNzMFkgcVggK1g=&input=LVI=)
[Answer]
# [Acc!!](https://github.com/dloscutoff/Esolangs/tree/master/Acc!!), 84 bytes
This is actually what inspired this challenge:
```
Write 65
Count i while i-26 {
Count b while b-i {
Write b+65
Write i+65
}
Write 10
}
```
[Try it online!](https://tio.run/##S0xOTkr6/z@8KLMkVcHMlMs5vzSvRCFToTwjMydVIVPXyEyhGiqYBBVM0s0EikF0JGkD9UCYmSBmLZRjaMBV@/8/AA "Acc!! – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~49~~ 48 bytes
```
'A':unlines[init['A'..x]>>=(:[x])|x<-['A'..'Z']]
```
[Try it online!](https://tio.run/##y0gszk7NyflfXFKUmZeuYKsQ81/dUd2qNC8nMy@1ODozL7MkGiigp1cRa2dnq2EVXRGrWVNhowsRVI9Sj439n5uYmQfUWVBaElxSpAAx6f@/5LScxPTi/7rJBQUA "Haskell – Try It Online")
*Edit: -1 byte thanks to totallyhuman!*
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform)
Port from Kevin Cruijssen's [answer](https://codegolf.stackexchange.com/a/153240/15214):
## ~~91~~ 90 bytes
```
_=>{var t="";for(char c='@';++c<91;t+=c)Console.WriteLine(string.Join(c+"",t.Skip(0))+c);}
```
[Try it online!](https://tio.run/##XY5BSwMxEIXv@RVhL02IhnqUGFH2UCgtCHvwHMapDq6JzUwLZdnfvgZBEY8Pvve@B3wNpeJyYsqveriw4EdQf5PvyzgiCJXMfoMZK8E/Ykf5GBSMiVk/TYolCYF@/O7oQRLVPjHqqBdj4/10TlVL7LpwKNXAW0sQVw@r4Bzc3d4EcRFs32xlRP9cSbDto2GpTem3hbIB13VX4od3@jRrax3YMC9B/ZjPhV70PjXQqkn9HjA2qFnNyxc "C# (.NET Core) – Try It Online")
## ~~132~~ ~~122~~ ~~110~~ ~~109~~ ~~104~~ 103 bytes
```
_=>"ABCDEFGHIJKLMNOPQRSTUVWXYZ".Select((c,i)=>string.Join(""+c,"ABCDEFGHIJKLMNOPQRSTUVWXYZ".Take(i))+c)
```
[Try it online!](https://tio.run/##fY/PTgIxEMbvfYrJntqAfYGFTXQFBEHRRVFvdRx1Ymlj2yUxhGdfaozRePA4@f7M98N4hD5Q10Z2L9B8xESbUvy@dO2tJUzsXdQTchQY/zjm7N5LgdbECMudiMkkRhi3DgfTkWs3FMyjpUFMIYeqCppkONQmEgyhk2pYFccn9eloPDmbzs7ni4vL5dV1s7q5Xd/dPxS6oc/3UmKfs/WrRM88O1kUPez/m12ZN5KsVA9VV4rvZVvPT7AwuUGJnXjO/AZfQW5NAM48wO5nolQK6ozuLel1yHKGzZXZpkqxF/vuAA "C# (.NET Core) – Try It Online")
* Replace `()` with `_` to show that we declare an unused variable. Thank you Kevin Cruijssen.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 22 bytes
```
ØAż€Ð€`F€µJ’Ḥ»1ż@¹ḣ/€Y
```
[Try it online!](https://tio.run/##y0rNyan8///wDMejex41rTk8AUgkuAGJQ1u9HjXMfLhjyaHdhkf3OBza@XDHYn2geOT//wA "Jelly – Try It Online")
How it works:
```
take argument implicitly
ØA the uppercase alphabet
Ѐ` for C in the alphabet
ż€ appends C to every letter in the alphabet
F€ flatten every sublist
J get indices
’ subtract 1
Ḥ and double
»1 take max([n, 1])
µ ż@¹ interleave alphabet list and indices
ḣ/€ reduce on head() for each element
Y join on newline
implicitly output
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~44~~ 34 bytes
```
?A.upto(?Z){|w|puts [*?A...w]*w+w}
```
[Try it online!](https://tio.run/##KypNqvz/395Rr7SgJF/DPkqzuqa8pqC0pFghWgsoqqdXHqtVrl1e@/8/AA "Ruby – Try It Online")
Thanks benj2240 for getting it down to 37 bytes. And of course crossed out 44 blah blah.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 29 bytes
```
'A,Au©.sRí¦®RSDgÝ×Rs)ø˜.Bíø»=
```
[Try it online!](https://tio.run/##ATIAzf8wNWFiMWX//ydBLEF1wqkuc1LDrcKmwq5SU0Rnw53Dl1JzKcO4y5wuQsOtw7jCuz3//w "05AB1E – Try It Online")
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 96 bytes
```
+++++[->+++++>++>+++++++++++++>+++++++++++++<<<<]>>>.<.<[->>>+>+[-<<.+>.>>+<]>[-<+<<->>>]<<<<.<]
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fGwSide3AtB0YIQFUng0QxNrZ2enZ6NkAtdjZAeWjdW1s9LTt9IAcoByQB1QFkooFKdazif3/HwA "brainfuck – Try It Online")
**Tape Layout:**
*`[Init] [Line Count] [newline] [Growing Ascii] [Repeated Ascii] [Loop 1] [Loop 2]`*
**Explanation:**
```
+++++[->+++++>++ Sets Line counter and newline cell
>+++++++++++++>+++++++++++++<<<<] Sets Ascii cells to 65 ('A')
>>>.<.< Prints first "A" and moves to Line loop
[->>>+>+ Increment Repeated Ascii cell in outer loop
[-<<.+>.>>+<]> Increment Growing Ascii cell in inner loop,
Prints both Ascii cells and Sets Loop 2
[-<+<<->>>] Resets Growing cell and Loop 1
<<<<.<] Prints newline and moves to next Line
```
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 81 bytes
```
+++[[->++<<+>]>]<<,<[----<<+>>]<+<+.<+<--.>[>+>>+[-<.+<.>>>+<]>[-<+<->>]<<<<<.>-]
```
[Try it online!](https://tio.run/##FYpBCsRQDEIPZJMTiBcJWbSFQhmYRaHnT/0uxKcez37/r/f8zQCoCgEk1GpyY4W12AgibRGpkhtUMMGUI1smj@u4lIqe@QA "brainfuck – Try It Online")
Prints in lowercase
### Explanation:
```
+++[[->++<<+>]>] Sets up the tape as 3*2^n (3,6,12,24,48,96,192,128)
<<, Removes excess 128
<[----<<+>>] Adds 196/4 to 48 resulting in 96
<+<+. Add 1 to both 96s and print A
<+<--. Add 1 to 25, subtract 2 from 12 to print a newline
Tape: 3 6 10 25 96 96 0 0
>[ Start loop
>+>>+ Add one to the unchanging ASCII and the inner loop counter
[-<.+<.>>>+<] Print row while preserving counter
>[-<+<->>] Undo changes to changing ASCII and return inner loop counter to its cell
<<<<<.>- Print newline and decrement loop counter
]
```
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 88 bytes
```
++++++++[->+++>+>++++++++>++++++++<<<<]>+>++>+.<.<[->>+>>+[-<+.<.>>>+<]>[-<+<->>]<<<<.<]
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fGwqide2ApJ22HUwAzrABgliwhJ22no2eDVAlkGcH1GED4tsBmUB5EM8GKBMLUq5nE/v/PwA "brainfuck – Try It Online")
should run on all brainfuck interpreters. No wrapping or negative values, no undefined input behaviour, values between 0 and 90.
**How it works**
```
Initialize tape: 25(row count) 10(lf) 64(row letter) 64(col letter) 0(col count) 0(temp)
++++++++[->+++>+>++++++++>++++++++<<<<]>+>++
>+.<. print "A" and lf
<[ for each letter count
- decrement letter count
>>+ increment row letter
>>+ increment col count
[ do col count times
- decrement col count
<+. increment and print col letter
<. print row letter
>>>+ move col count to temp
< return to colcount
]
>[-<+<->>] move value from temp back to col count and set col letter back to "A" minus 1
<<<<. print lf
< return to row count
]
```
[Answer]
# [Perl 5](https://www.perl.org/), ~~39~~ 38 bytes
*@DomHastings shaved off a byte*
```
say$.=A;say map$_.$.,A..$.++while$.!~Z
```
[Try it online!](https://tio.run/##K0gtyjH9/784sVJFz9bRGkgr5CYWqMTrqejpOOoBSW3t8ozMnFQVPcW6qP///@UXlGTm5xX/1/U11TMwNAAA "Perl 5 – Try It Online")
[Answer]
# Deadfish~, 4152 bytes
```
{i}cc{iiiii}iiiiic{ddddd}dddddc{iiiii}iiiiicic{ddddd}ddddddc{iiiii}iiiiiciicdcic{dddddd}iiic{iiiii}iiiiiciiicddciicdcic{dddddd}iic{iiiii}iiiiiciiiicdddciiicddciicdcic{dddddd}ic{iiiii}iiiiiciiiiicddddciiiicdddciiicddciicdcic{dddddd}c{iiiii}iiiiiciiiiiicdddddciiiiicddddciiiicdddciiicddciicdcic{dddddd}dc{iiiii}iiiiic{i}dddcddddddciiiiiicdddddciiiiicddddciiiicdddciiicddciicdcic{dddddd}ddc{iiiii}iiiiic{i}ddc{d}iiic{i}dddcddddddciiiiiicdddddciiiiicddddciiiicdddciiicddciicdcic{dddddd}dddc{iiiii}iiiiic{i}dc{d}iic{i}ddc{d}iiic{i}dddcddddddciiiiiicdddddciiiiicddddciiiicdddciiicddciicdcic{dddddd}ddddc{iiiii}iiiiic{i}c{d}ic{i}dc{d}iic{i}ddc{d}iiic{i}dddcddddddciiiiiicdddddciiiiicddddciiiicdddciiicddciicdcic{dddddd}dddddc{iiiii}iiiiic{i}ic{d}c{i}c{d}ic{i}dc{d}iic{i}ddc{d}iiic{i}dddcddddddciiiiiicdddddciiiiicddddciiiicdddciiicddciicdcic{dddddd}ddddddc{iiiii}iiiiic{i}iic{d}dc{i}ic{d}c{i}c{d}ic{i}dc{d}iic{i}ddc{d}iiic{i}dddcddddddciiiiiicdddddciiiiicddddciiiicdddciiicddciicdcic{{d}iii}iiic{iiiii}iiiiic{i}iiic{d}ddc{i}iic{d}dc{i}ic{d}c{i}c{d}ic{i}dc{d}iic{i}ddc{d}iiic{i}dddcddddddciiiiiicdddddciiiiicddddciiiicdddciiicddciicdcic{{d}iii}iic{iiiii}iiiiic{i}iiiic{d}dddc{i}iiic{d}ddc{i}iic{d}dc{i}ic{d}c{i}c{d}ic{i}dc{d}iic{i}ddc{d}iiic{i}dddcddddddciiiiiicdddddciiiiicddddciiiicdddciiicddciicdcic{{d}iii}ic{iiiii}iiiiic{i}iiiiic{d}ddddc{i}iiiic{d}dddc{i}iiic{d}ddc{i}iic{d}dc{i}ic{d}c{i}c{d}ic{i}dc{d}iic{i}ddc{d}iiic{i}dddcddddddciiiiiicdddddciiiiicddddciiiicdddciiicddciicdcic{{d}iii}c{iiiii}iiiiic{i}iiiiiic{d}dddddc{i}iiiiic{d}ddddc{i}iiiic{d}dddc{i}iiic{d}ddc{i}iic{d}dc{i}ic{d}c{i}c{d}ic{i}dc{d}iic{i}ddc{d}iiic{i}dddcddddddciiiiiicdddddciiiiicddddciiiicdddciiicddciicdcic{{d}iii}dc{iiiii}iiiiic{ii}dddc{d}ddddddc{i}iiiiiic{d}dddddc{i}iiiiic{d}ddddc{i}iiiic{d}dddc{i}iiic{d}ddc{i}iic{d}dc{i}ic{d}c{i}c{d}ic{i}dc{d}iic{i}ddc{d}iiic{i}dddcddddddciiiiiicdddddciiiiicddddciiiicdddciiicddciicdcic{{d}iii}ddc{iiiii}iiiiic{ii}ddc{dd}iiic{ii}dddc{d}ddddddc{i}iiiiiic{d}dddddc{i}iiiiic{d}ddddc{i}iiiic{d}dddc{i}iiic{d}ddc{i}iic{d}dc{i}ic{d}c{i}c{d}ic{i}dc{d}iic{i}ddc{d}iiic{i}dddcddddddciiiiiicdddddciiiiicddddciiiicdddciiicddciicdcic{{d}iii}dddc{iiiii}iiiiic{ii}dc{dd}iic{ii}ddc{dd}iiic{ii}dddc{d}ddddddc{i}iiiiiic{d}dddddc{i}iiiiic{d}ddddc{i}iiiic{d}dddc{i}iiic{d}ddc{i}iic{d}dc{i}ic{d}c{i}c{d}ic{i}dc{d}iic{i}ddc{d}iiic{i}dddcddddddciiiiiicdddddciiiiicddddciiiicdddciiicddciicdcic{{d}iii}ddddc{iiiii}iiiiic{ii}c{dd}ic{ii}dc{dd}iic{ii}ddc{dd}iiic{ii}dddc{d}ddddddc{i}iiiiiic{d}dddddc{i}iiiiic{d}ddddc{i}iiiic{d}dddc{i}iiic{d}ddc{i}iic{d}dc{i}ic{d}c{i}c{d}ic{i}dc{d}iic{i}ddc{d}iiic{i}dddcddddddciiiiiicdddddciiiiicddddciiiicdddciiicddciicdcic{{d}iii}dddddc{iiiii}iiiiic{ii}ic{dd}c{ii}c{dd}ic{ii}dc{dd}iic{ii}ddc{dd}iiic{ii}dddc{d}ddddddc{i}iiiiiic{d}dddddc{i}iiiiic{d}ddddc{i}iiiic{d}dddc{i}iiic{d}ddc{i}iic{d}dc{i}ic{d}c{i}c{d}ic{i}dc{d}iic{i}ddc{d}iiic{i}dddcddddddciiiiiicdddddciiiiicddddciiiicdddciiicddciicdcic{{d}iii}ddddddc{iiiii}iiiiic{ii}iic{dd}dc{ii}ic{dd}c{ii}c{dd}ic{ii}dc{dd}iic{ii}ddc{dd}iiic{ii}dddc{d}ddddddc{i}iiiiiic{d}dddddc{i}iiiiic{d}ddddc{i}iiiic{d}dddc{i}iiic{d}ddc{i}iic{d}dc{i}ic{d}c{i}c{d}ic{i}dc{d}iic{i}ddc{d}iiic{i}dddcddddddciiiiiicdddddciiiiicddddciiiicdddciiicddciicdcic{{d}ii}iiic{iiiii}iiiiic{ii}iiic{dd}ddc{ii}iic{dd}dc{ii}ic{dd}c{ii}c{dd}ic{ii}dc{dd}iic{ii}ddc{dd}iiic{ii}dddc{d}ddddddc{i}iiiiiic{d}dddddc{i}iiiiic{d}ddddc{i}iiiic{d}dddc{i}iiic{d}ddc{i}iic{d}dc{i}ic{d}c{i}c{d}ic{i}dc{d}iic{i}ddc{d}iiic{i}dddcddddddciiiiiicdddddciiiiicddddciiiicdddciiicddciicdcic{{d}ii}iic{iiiii}iiiiic{ii}iiiic{dd}dddc{ii}iiic{dd}ddc{ii}iic{dd}dc{ii}ic{dd}c{ii}c{dd}ic{ii}dc{dd}iic{ii}ddc{dd}iiic{ii}dddc{d}ddddddc{i}iiiiiic{d}dddddc{i}iiiiic{d}ddddc{i}iiiic{d}dddc{i}iiic{d}ddc{i}iic{d}dc{i}ic{d}c{i}c{d}ic{i}dc{d}iic{i}ddc{d}iiic{i}dddcddddddciiiiiicdddddciiiiicddddciiiicdddciiicddciicdcic{{d}ii}ic{iiiii}iiiiic{ii}iiiiic{dd}ddddc{ii}iiiic{dd}dddc{ii}iiic{dd}ddc{ii}iic{dd}dc{ii}ic{dd}c{ii}c{dd}ic{ii}dc{dd}iic{ii}ddc{dd}iiic{ii}dddc{d}ddddddc{i}iiiiiic{d}dddddc{i}iiiiic{d}ddddc{i}iiiic{d}dddc{i}iiic{d}ddc{i}iic{d}dc{i}ic{d}c{i}c{d}ic{i}dc{d}iic{i}ddc{d}iiic{i}dddcddddddciiiiiicdddddciiiiicddddciiiicdddciiicddciicdcic{{d}ii}c
```
[Try it online!](https://tio.run/##7ZZLDoMwDERP1ENVmVbNusvIZ0@JkyDAg/pR@cOCBZ7YM08EgtsVd/98XGIMXpwLPl2idxeQLtF7v9KvDYveoVVAtFO/3ghgZUaVZBiTW7XK8W4hWZcX4osmg8QNuqRFp80PPVnTpip/nEBG5AnTTLPjdML0c@3gVJc5HRAL6gGzuclN7P4L5Vl55ZbzxWwVX1iNS2qyusRKXXPTrWtsJYfZRLlp6OyxzUaj2dI3RPYXlWUtUXcenCTPUQ8FgVDQ36UcFggjkpHg0HjYcaX6qmfkk1QhRUFVUjjJjZLj4FpyOFl@zNLF@AI "Deadfish~ – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ØA;\;€Ṫ$€YFḊ
```
**[Try it online!](https://tio.run/##y0rNyan8///wDEfrGOtHTWse7lylAqQi3R7u6Pr/HwA "Jelly – Try It Online")**
Bah just got `ØAjṪ$ƤżØAY` which is a step between this and the already posted solution of Dennis :/
[Answer]
# [Pyth](https://pyth.readthedocs.io), 13 bytes
```
+\ajmPjedd._G
```
[Try it here!](https://pyth.herokuapp.com/?code=%2B%5CajmPjedd._G&debug=0), [Alternative](https://pyth.herokuapp.com/?code=jm%2BjedPded._G&debug=0)
That leading `a` though...
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
ØA¹Ƥ+"¹Ṗ€Yṭ”A
```
[Try it online!](https://tio.run/##ASIA3f9qZWxsef//w5hBwrnGpCsiwrnhuZbigqxZ4bmt4oCdQf// "Jelly – Try It Online")
# Explanation
```
ØA¹Ƥ+"¹Ṗ€Yṭ”A Main Link
ØA Uppercase Alphabet
¹Ƥ Prefixes
+"¹ Doubly-vectorized addition to identity (uppercase alphabet) (gives lists of lists of strings)
Ṗ€ a[:-1] of each (get rid of the double letters at the end)
Y Join on newlines
ṭ”A "A" + the result
```
partially abuses the way strings and character lists differ in Jelly
[Answer]
# [Python 2](https://docs.python.org/2/), ~~92~~ ~~86~~ ~~79~~ ~~75~~ 64 bytes
```
s=map(chr,range(65,91))
for d in s:print d.join(s[:ord(d)-65])+d
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v9g2N7FAIzmjSKcoMS89VcPMVMfSUFOTKy2/SCFFITNPodiqoCgzr0QhRS8rPzNPozjaKr8oRSNFU9fMNFZTO@X/fwA "Python 2 – Try It Online")
11 bytes thx to Rod.
[Answer]
# APL+WIN, 51 bytes
```
⍎∊'a←⎕av[65+⍳26]⋄a[n←1]',25⍴⊂'⋄,⊃a[⍳n-1],¨a[n←n+1]'
```
Explanation:
```
a←⎕av[65+⍳26] create a vector of upper case letters
a[n←1] first A
25⍴⊂'⋄,⊃a[⍳n-1],¨a[n←n+1]' create an implicit loop to concatenate subsequent letters
```
] |
[Question]
[
Let's see how good your language of choice is at selective randomness.
Given 4 characters, `A`, `B`, `C`, and `D`, or a string of 4 characters `ABCD` **as input**, output one of the characters with the following probabilities:
* `A` should have a 1/8 (12.5%) chance to be chosen
* `B` should have a 3/8 (37.5%) chance to be chosen
* `C` should have a 2/8 (25%) chance to be chosen
* `D` should have a 2/8 (25%) chance to be chosen
This is in-line with the following [Plinko](http://priceisright.wikia.com/wiki/Plinko) machine layout:
```
^
^ ^
^ ^ ^
A B \ /
^
C D
```
Your answer must make a genuine attempt at respecting the probabilities described. A proper explanation of how probabilities are computed in your answer (and why they respect the specs, disregarding pseudo-randomness and big numbers problems) is sufficient.
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so fewest bytes **in each language** wins!
[Answer]
# [Lean Mean Bean Machine](https://github.com/gunnerwolf/lmbm), ~~55~~ ~~43~~ 42 bytes
*-13 bytes thanks to Alex Varga*
```
O
i
^
^ ^
\ ^ ^
i / U
ii
^
i U
U
```
Hope you guys don't mind me answering my own question after only 2 hours, but I highly doubt anybody else was planning on posting an answer in LMBM.
This literally just reflects the Plinko layout shown in the OP, flipped horizontally to cut down on unnecessary whitespace.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ḋṁ7;ḢX
```
A monadic link taking a list of four characters and returning one with the probability distribution described.
**[Try it online!](https://tio.run/##y0rNyan8///hjq6HOxvNrR/uWBTx//9/RydnFwA "Jelly – Try It Online")**
### How?
```
Ḋṁ7;ḢX - Link: list of characters, s e.g. ABCD
Ḋ - dequeue s BCD
ṁ7 - mould like 7 (implicit range) BCDBCDB
Ḣ - head s A
; - concatenate BCDBCDBA
X - random choice Note that the above has 1*A, 3*B, 2*C, and 2*D
```
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix), ~~39~~ ~~24~~ ~~22~~ ~~21~~ 19 bytes
```
.<.^iD>D|@oioi.\i;U
```
[**View in the online interpreter!**](https://ethproductions.github.io/cubix/?code=LjwuXmlEPkR8QG9pb2kuXGk7VQ==&input=QUJDRA==&speed=20 "Cubix – Try It Online")
This maps out to the following cube net:
```
. <
. ^
i D > D | @ o i
o i . \ i ; U .
. .
. .
```
# Random Distribution Implementation Explanation
Cubix is a language in which an instruction pointer travels around the faces of a cube, executing the commands it encounters. The only form of randomness is the command `D`, which sends the IP in a random direction: an equal chance of `1/4` each way.
However, we can use this to generate the correct weighted probabilites: by using `D` twice. The first `D` has a `1/4` of heading to a second `D`. This second `D`, however, has two directions blocked off with arrows (`> D <`) which send the instruction pointer back to the `D` to choose another direction. This means there are only two possible directions from there, each with a `1/8` overall chance of happening. This can be used to generate the correct character, as shown in the diagram below:
[](https://i.stack.imgur.com/pLhpa.png)
(Note that, in the actual code, the arrow on the right is replaced with a mirror, `|`)
# Code Explanation
```
. <
. ^
IP> i D > D | @ o i
o i . \ i ; U .
. .
. .
```
The instruction pointer starts on the right, at the character `i`, facing right. It executes this `i`, taking the first character as input, and then moves onto the `D`, beginning the random process shown above.
* **Char A:** In the case that the first `D` sends us east, and the second south, we need to print character A. This is already on stack from the first `i`. The following is executed:
+ `\` - Reflect the IP so it heads east
+ `i;` - Take an input, then pop it again (no-op)
+ `U` - Perform a U-turn, turning the IP left twice
+ `o` - Output the TOS, character A
+ `@` - Terminate the program
* **Char B:** If either the first or second `D` head north, we need to generate character B, which will be the next input. Both paths execute the following commands:
+ `^` - Head north
+ `<` - Head west, wrapping round to...
+ `i` - Take another input, character B
+ `o` - Output the TOS, character B
+ `;` - Pop the TOS
+ `@` - Terminate the program
* **Char C:** If the first `D` sends us west, the following is executed:
+ `i` - Take another input, character B
+ `i` - Take another input, character C
+ `o` - Output TOS, character C
+ `@` - Terminate the program
* **Char D:** If the first `D` sends us south, the following is executed:
+ `i` - Take another input, character B
+ `..` - Two no-ops
+ `i` - Take another input, character C
+ `|` - This mirror reflects east-west, but the IP is heading north, so we pass through it.
+ `^` - This joins up with the path taken for character B. However, because we have taken two inputs already, the fourth character (character D) will end up being printed.
[Answer]
# [Python](https://docs.python.org/), 50 bytes
```
lambda x:choice(x[:2]+x[1:]*2)
from random import*
```
An unnamed function taking and returning strings (or lists of characters).
**[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHCKjkjPzM5VaMi2sooVrsi2tAqVstIkyutKD9XoSgxLwVIZeYW5BeVaP0vKMrMK9FI01BydHJ2UdLU/A8A "Python 2 – Try It Online")**
### How?
`random.choice` chooses a random element from a list, so the function forms a string with the correct distribution, that is, given `"ABCD"`, `"ABCD"[:2] = "AB"` plus `"ABCD"[1:]*2 = "BCD"*2 = "BCDBCD"` which is `"ABBCDBCD"`.
[Answer]
# [R](https://www.r-project.org/), 31 bytes
```
sample(scan(,''),1,,c(1,3,2,2))
```
Reads the characters from `stdin` separated by spaces. `sample` draws random samples from its first input in quantity of the second input (so `1`), (optional replacement argument), with weights given by the last argument.
[Try it online!](https://tio.run/##K/r/vzgxtyAnVaM4OTFPQ0ddXVPHUEcnWcNQx1jHSMdIU/N/okKSQrJCyn8A "R – Try It Online")
[Try it `n` times!](https://tio.run/##K/qfZ2toAAT/SxKTclI1ihNzC0BUcmKeho66uqZOnk6ITrKGoY6xjpGOkaampn7e/0SFJIVkhZT/AA "R – Try It Online")
For the latter code, I sample `n` times (set `n` in the header) with replacement set to `T`rue (it's false by default), tabulate the results, and divide by `n` to see the relative probabilities of the inputs.
[Answer]
# PHP, 28 bytes
```
<?=$argn[5551>>2*rand(0,7)];
```
Run as pipe with `-nR`.
`01112233` in base-4 is `5551` in decimal ...
[Answer]
# Java 8, ~~53~~ 44 bytes
```
s->s[-~Math.abs((int)(Math.random()*8)-6)/2]
```
This is a `Function<char[], Character>`.
[Try it online!](https://tio.run/##fZHRboIwFIbveYoTkwUqUtGLZQnOZHPZnVdeErJUQKmDlrTFxRj26uxUcc5lWVN6Ss/X8/9td2zPAlnnYpe9d7yqpTKwwzXaGF7STSNSw6Wgr/0kcpy6WZc8hbRkWsOScQFHxwFsfUIbZjDsJc@gwrS3MoqLbZwAU1tNkIa@XYrO0oKpOBnBAiNLTa7mYJWn8AidDuY6Dj6XzBSUrbXncWGId/pVTGSy8sjwgQT3ZDxNuui7NlKomMpGGKxyDEfQ9/bKnGXRsLKI@@SOwH22w8IOL257Uw5KXiE3eQvD0H7X5EYqsLaAYz6MMMwsjBPf/3neiyZY44iezkhZXZcHD02Q6Ja03uMTGgCaS3z/CrT/imMxWuZia4o/PawO2uQVlY2hNT6NKYWVj3kCPgzgg2l0KXUugK2RwSUfvLMbRMbgZRJfOienCxnCJAyJ3XgHcgOmyMHwKh@Q315bx2md7gs) (this test program runs the above function 1,000,000 times and outputs the experimental probabilities of choosing `A`, `B`, `C`, and `D`).
The general idea here is to find some way to map `0-7` to `0-3`, such that `0` appears `1/8` times, `1` appears `3/8` times, `2` appears `2/8` times, and `3` appears `2/8` times. `round(abs(k - 6) / 2.0))` works for this, where `k` is a random integer in the range `[0,8)`. This results in the following mapping:
```
k -> k - 6 -> abs(k-6) -> abs(k-6)/2 -> round(abs(k-6)/2)
0 -> -6 -> 6 -> 3 -> 3
1 -> -5 -> 5 -> 2.5 -> 3
2 -> -4 -> 4 -> 2 -> 2
3 -> -3 -> 3 -> 1.5 -> 2
4 -> -2 -> 2 -> 1 -> 1
5 -> -1 -> 1 -> 0.5 -> 1
6 -> 0 -> 0 -> 0 -> 0
7 -> 1 -> 1 -> 0.5 -> 1
```
Which, as you can see, results in the indices `0 111 22 33`, which produces the desired probabilities of `1/8`, `3/8`, `2/8` and `2/8`.
But wait! How in the world does `-~Math.abs(k-6)/2` achieve the same result (again, where `k` is a random integer in the range `[0,8]`)? It's pretty simple actually... `(x+1)/2` (integer division) is the same thing as `round(x/2)`, and `x + 1` is the same thing as `-~x`. Although `x+1` and `-~x` are the same length, in the above function it is better to use `-~x` since it `-~` takes precedence and thus does not require parenthesis.
[Answer]
# APL, 14 bytes
```
(?8)⊃1 3 2 2\⊢
```
Input as a string.
**How?**
`1 3 2 2\⊢` - repeat each letter x times (`'ABCD'` → `'ABBBCCDD'`)
`⊃` - take the element at index ..
`(?8)` - random 1-8
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 11 bytes
```
‽⟦εεζζηηηθ⟧
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCMoMS8lP1cjOlUnVacKCDPAsDBWU9P6/39HLicuZy6X/7pl/3WLcwA "Charcoal – Try It Online") Link is to verbose version of code, although you hardly need it; `‽` picks a random element, `⟦⟧` creates a list, and the variables are those that get the appropriate input letters (in reverse order because I felt like it).
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~8~~ 7 bytes
```
O+@Q1t+
```
Uses the exact same algorithm as in my Python answer.
[Try it here!](https://pyth.herokuapp.com/?code=O%2B%40Q1t%2B&input=%22ABCD%22&test_suite=1&test_suite_input=%22ABCD%22%0A%22ABCD%22%0A%22ABCD%22%0A%22ABCD%22%0A%22ABCD%22%0A%22ABCD%22%0A%22ABCD%22%0A%22ABCD%22%0A%22ABCD%22%0A%22ABCD%22%0A%22ABCD%22%0A%22ABCD%22&debug=0)
# [Pyth](https://github.com/isaacg1/pyth), ~~10~~ 8 bytes
```
O+<Q2*2t
```
Uses the exact same algorithm as is Jonathan Allan's Python answer.
[Try it here!](https://pyth.herokuapp.com/?code=O%2B%3CQ2%2a2t&input=%22ABCD%22&test_suite=1&test_suite_input=%22ABCD%22%0A%22ABCD%22%0A%22ABCD%22%0A%22ABCD%22%0A%22ABCD%22%0A%22ABCD%22%0A%22ABCD%22%0A%22ABCD%22%0A%22ABCD%22&debug=0)
---
### Explanation
* `O` - Takes a random element of the String made by appending (with `+`):
+ `<Q2` - The first two characters of the String.
+ `*2t` Double the full String (`*2`) except for the first character (`t`).
Applying this algorithm for `ABCD`:
* `<Q2` takes `AB`.
* `*2t` takes `BCD` and doubles it: `BCDBCD`.
* `+` joins the two Strings: `ABBCDBCD`.
* `O` takes a random character.
---
-2 thanks to Leaky Nun (second solution)
-1 thanks to mnemonic (first solution)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
122b4⁸xX
```
[Try it online!](https://tio.run/##y0rNyan8/9/QyCjJ5FHjjoqI////Kzk6ObsoAQA "Jelly – Try It Online")
Remove the `X` to see `"ABBBCCDD"`. The `X` chooses a random element.
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 76 55 bytes
```
s=>(s+s[1]+s[1]+s[2]+s[3])[new System.Random().Next(8)]
```
[Try it online!](https://tio.run/##PY47C8IwFIX3/orglFAtrS5CH@ADJ3WwgoN0COmtXqiJ5MYX0t9eK1iXjzN8h3MUjZSx0KpaEjHz9shJh4rdDZZsI1Fz8fbyFzm4BKubVgk5i/o0VGdpM1alLaUZJ5@OUdFj/MWkEEcND/ar7qQuzYWLYAtPx6eiaGOvMpajdgzTMMYk6uD7gv3XFkaTqSE4WHSwRg284oPZfLEcCBH30v5sQZbdoV8K8hrgyqMw7JzGa5r2Aw "C# (.NET Core) – Try It Online")
My first answer written directly on TIO using my mobile phone. Level up!
Explanation: if the original string is "ABCD", the function creates the string "ABCDBBCD" and takes a random element from it.
[Answer]
# Javascript 35 bytes
Takes a string `ABCD` as input, outputs `A` 1/8th of the time, `B` 3/8ths of the time, `C` 1/4th of the time, and `D` 1/4th of the time.
```
x=>x[5551>>2*~~(Math.random()*8)&3]
```
## Explanation
```
x=>x[ // return character at index
5551 // 5551 is 0001010110101111 in binary
// each pair of digits is a binary number 0-3
// represented x times
// where x/8 is the probability of selecting
// the character at the index
>> // bitshift right by
2 * // two times
~~( // double-bitwise negate (convert to int, then
// bitwise negate twice to get the floor for
// positive numbers)
Math.random() * 8 // select a random number from [0, 8)
) // total bitshift is a multiple of 2 from [0, 14]
&3 // bitwise and with 3 (111 in binary)
// to select a number from [0, 3]
]
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
¦Ćì.R
```
[Try it online!](https://tio.run/##MzBNTDJM/f//0LIjbYfX6AX9/@/o5OwCAA "05AB1E – Try It Online")
### Explanation
```
¦Ćì.R Argument s "ABCD"
¦ Push s[1:] "BCD"
Ć Enclose: Pop a, Push a + a[0] "BCDB"
ì Pop a, Concatenate a and s "ABCDBCDB"
.R Random pick
```
[Answer]
# [><>](https://esolangs.org/wiki/Fish), ~~25~~ ~~22~~ 19 bytes
```
i_ixio;o
ox</;
;\$o
```
[Try it online!](https://tio.run/##S8sszvj/PzM@syIz3zqfK7/CRt@ayzpGJf//fzfPYA8A "><> – Try It Online"), or watch it at the [fish playground](https://fishlanguage.com/playground)!
A brief overview of ><>: it's a 2D language with a fish that swims through the code, executing instructions as it goes. If it reaches the edge of the code, it wraps to the other side. The fish starts in the top left corner, moving right. Randomness is tricky in ><>: the only random instruction is `x`, which sets the fish's direction randomly out of up, down, left and right (with equal probability).
At the start of the program, the fish reads in two characters of input with `i_i` (each `i` reads a character from STDIN to the stack, and `_` is a horizontal mirror, which the fish ignores now). It then reaches an `x`.
If the `x` sends the fish rightwards, it reads in one more character (the third), prints it with `o` and halts with `;`. The left direction is similar: the fish reads two more characters (so we're up to the fourth), wraps around to the right, prints the fourth character and halts. If the fish swims up, it wraps and prints the second character, before being reflected right by `/` and halting. If it swims down, it gets reflected left by the `/` and hits another `x`.
This time, two directions just send the fish back to the `x` (right with an arrow, `<`, and up with a mirror, `_`). The fish therefore has 1/2 chance of escaping this `x` in each of the other two directions. Leftwards prints the top character on the stack, which is the second one, but downwards first swaps the two elements on the stack with `$`, so this direction prints the first character.
In summary, the third and fourth characters are printed with probability 1/4 each; the first character has probability 1/2 x 1/4 = 1/8; and the second character has probability 1/4 + 1/2 x 1/4 = 3/8.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
ìD1è0ǝ.R
```
[Try it online!](https://tio.run/##MzBNTDJM/f//8BoXw8MrDI7P1Qv6/z9aKVFJRykJiJOBOEUpFgA "05AB1E – Try It Online")
```
# Implicit input | [A,B,C,D]
ì # Prepend the input to itself | [A,B,C,D,A,B,C,D]
D1è # Get the second character | [A,B,C,D,A,B,C,D], B
0ǝ # Replace the first character with this one | [B,B,C,D,A,B,C,D]
.R # Pick a random character from this array | D
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~12~~ 10 bytes
```
l3HHvY"1Zr
```
[Try it online!](https://tio.run/##y00syfn/P8fYw6MsUskwquj/f3VHJ2cXdQA "MATL – Try It Online") Or [run it 1000 times](https://tio.run/##y00syflvaGBgYKX03z3H2MPDRKUsUskwquh/bFlwpPp/dUcnZxd1AA) (slightly modified code) and check the number of times each char appears.
### Explanation
```
l3HH % Push 1, 3, 2, 2
v % Concatenate all stack contents into a column vector: [1; 3; 2; 2]
Y" % Implicit input. Run-length decode (repeat chars specified number of times)
1Zr % Pick an entry with uniform probability. Implicit display
```
Changes in modified code: `1000:"Gl3HH4$vY"1Zr]vSY'`
* `1000:"...]` is a loop to repeat `1000` times.
* `G` makes sure the input is pushed at he beginning of each iteration.
* Results are accumulated on the stack across iterations. So `v` needs to be replaced by `4$v` to concatenate only the top `4` numbers.
* At the end of the loop, `v` concatenates the `1000` results into a vector, `S` sorts it, and `Y'` run-length encodes it. This gives the four letters and the number of times they have appeared.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
```
«À¨Ć.R
```
[Try it online!](https://tio.run/##MzBNTDJM/f//0OrDDYdWHGnTC/r/39HJ2QUA "05AB1E – Try It Online")
**Explanation**
Works for both lists and strings.
```
« # concatenate input with itself
À # rotate left
¨ # remove the last character/element
Ć # enclose, append the head
.R # pick a character/element at random
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~50~~ 49 bytes
```
i[8]={1,1,1,2,2,3,3};f(char*m){m=m[i[rand()%8]];}
```
[Try it online!](https://tio.run/##S9ZNT07@/z8z2iLWttpQBwSNgNBYx7jWOk0jOSOxSCtXszrXNjc6M7ooMS9FQ1PVIjbWuvZ/bmJmnoYmVzWXAhAUg6VKMnNTNQw0Na3BYgVFmXklaRpKqskxeUo6QIajk7OLEk7Z8IjIKLBsLdd/AA "C (gcc) – Try It Online")
[Answer]
# Ruby, 34 33 29 27 bytes
Saved 2 bytes thanks to @Value Inc
Input as four characters
```
a=$**2
a[0]=a[1]
p a.sample
```
construct an array `[B,B,C,D,A,B,C,D]` and sample it.
[try it online!](https://tio.run/##KypNqvz/P9FWRUvLiCsx2iDWNjHaMJarQCFRrzgxtyAn9f///47/nf47/3cBAA)
[try it `n` times!](https://tio.run/##VY3NCoJAFIX3PsWhCLTEtF3CLMrewkSmvFbkHzNjIeqz24zUors4nPv3HdFeumnKKEduc3F7ORbAmXHrnbGxnzAeB4nxnuRlU5BFVWZZgmRbKAmGHocQvovjrNGsJ60YzVVDXOmjva5f66lHSRJZraFfTJzbq7d9wBERTo7jqTqVXZlgwxD85XnEr3f9iuFJnYsXL1oaNKcRj0phsez1eAyx7OfN9hdYp/l4rhYGNU0f) (I converted it to a function to repeat it more easily, but the algorithm is the same)
[Answer]
# Pyth, 7 bytes
```
@z|O8 1
```
[Test suite](https://pyth.herokuapp.com/?code=%40z%7CO8+1&input=%0A&test_suite=1&test_suite_input=ABCD%0AABCD%0AABCD%0AABCD&debug=0)
`O8` generates a random number from 0 to 7. `| ... 1` applies a logical or with 1, converting the 0 to a 1 and leaving everything else the same. The number at this stage is 1 2/8th of the time, and 2, 3, 4, 5, 6, 7 or 8 1/8 of the time.
`@z` indexes into the input string at that position. The indexing is performed modulo the length of the string, so 4 indexes at position 0, 5 at position 1, and so on.
The probabilities are:
* Position 0: Random number 4. 1/8 of the time.
* Position 1: Random number 0, 1 or 5. 3/8 of the time.
* Position 2: Random number 2 or 6. 2/8 of the time.
* Position 3: Random number 3 or 7. 2/8 of the time.
[Answer]
# Javascript, ~~31~~ 30 bytes / 23 bytes
Seeing asgallant's earlier Javascript answer got me to thinking about JS. As he said:
>
> Takes a string `ABCD` as input, outputs `A` 1/8th of the time, `B`
> 3/8ths of the time, `C` 1/4th of the time, and `D` 1/4th of the time.
>
>
>
Mine is:
```
x=>(x+x)[Math.random()*8&7||1]
```
**Explanation:**
```
x=>(x+x)[ // return character at index of doubled string ('ABCDABCD')
Math.random()*8 // select a random number from [0, 8]
&7 // bitwise-and to force to integer (0 to 7)
||1 // use it except if 0, then use 1 instead
]
```
From `Math.random()*8&7` it breaks down as follows:
```
A from 4 = 12.5% (1/8)
B from 0,1,5 = 37.5% (3/8)
C from 2,6 = 25% (1/4)
D from 3,7 = 25% (1/4)
```
## Version 2, 23 bytes
But then thanks to Arnauld, who posted after me, when he said:
>
> If a time-dependent formula is allowed, we can just do:
>
>
>
which, if it is indeed allowed, led me to:
```
x=>(x+x)[new Date%8||1]
```
in which `new Date%8` uses the same break-down table as above.
And `%8` could also be `&7`; take your pick. Thanks again, Arnauld.
[Answer]
# ngn/apl, 10 bytes
[```
⎕a[⌈/?2 4]
```](https://ngn.github.io/apl/web/index.html#code=%u2395a%5B%u2308/%3F2%204%5D)
`?2 4` chooses randomly a pair of numbers - the first among 0 1 and the second among 0 1 2 3
`⌈/` is "max reduce" - find the larger number
`⎕a` is the uppercase alphabet
`[ ]` indexing
---
note the chart for max(a,b) when a∊{0,1} and b∊{0,1,2,3}:
```
┏━━━┯━━━┯━━━┯━━━┓
┃b=0│b=1│b=2│b=3┃
┏━━━╋━━━┿━━━┿━━━┿━━━┫
┃a=0┃ 0 │ 1 │ 2 │ 3 ┃
┠───╂───┼───┼───┼───┨
┃a=1┃ 1 │ 1 │ 2 │ 3 ┃
┗━━━┻━━━┷━━━┷━━━┷━━━┛
```
if a and b are chosen randomly and independently, we can substitute 0123=ABCD to get the desired probability distribution
[Answer]
# [Python 3](https://docs.python.org/3/), ~~64 55~~ 51 bytes
*-9 bytes thanks to @ovs*
```
lambda s:choice((s*2)[1:]+s[1])
from random import*
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHYKjkjPzM5VUOjWMtIM9rQKla7ONowVpMrrSg/V6EoMS8FSGXmFuQXlWj9LyjKzCvRSNPIzCsoLdHQ1NT87@jk7AIA "Python 3 – Try It Online")
---
## Explanation
`random.choice()` gets a random character of the String, while `(s*2)[1:]+s[1]` creates `BCDABCDB` for an input of `ABCD`, which has 1/8 `A`s, 2/8 `C`s, 2/8 `D`s and 3/8 `B`s.
[Answer]
# [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 27 bytes
```
?_s;+;+B+B+;+C+;+D,_r1,8|,1
```
## Explanation
```
? PRINT
_s A substring of
;+ A plus
;+B+B+ 3 instances of B plus
;+C+ 2 instances of C plus
;+D 2 instances of D plus
,_r1,8| from position x randomly chosen between 1 and 8
,1 running for 1 character
```
[Answer]
# ><>, 56 bytes
```
v
!
"
D
C
B
A ;
" o
! @
! ^<
x!^xv!
@ v<
@ o
o ;
;
o
```
[Try it online!](https://tio.run/##S8sszvj/v4xLkYtLicuFy5nLictRwZpLSSGfS1HBAYjjbLgqFOMqyhS5HBQUymxAZD5XvgJQjTVX/v//AA)
[Answer]
# [Chip](https://github.com/Phlarx/chip), 60 bytes
```
)//Z
)/\Z
)\/^.
)\x/Z
)\\\+t
|???`~S
|z*
`{'AabBCcdDEefFGghH
```
[Try it online!](https://tio.run/##S87ILPj/X1NfP4pLUz8GSMTox@kByQqQQExMjHYJV429vX1CXTBXTZUWV0K1umNikpNzcoqLa2qam3t6hsf//4lJySkA "Chip – Try It Online")
The three `?`'s each produce a random bit. On the first cycle, these bits are run through the switches above (`/`'s and `\`'s) to determine which value we are going to output from this table:
```
000 a
01_ b
0_1 b
10_ c
11_ d
```
(where `_` can be either `0` or `1`). We then walk along the input as necessary, printing and terminating when the correct value is reached.
The big alphabetic blob at the end is copied wholesale from the cat program, this solution simply suppresses output and terminates to get the intended effect.
[Answer]
# Ruby, 32 bytes
Pretty straightforward..?
```
->s{s[[0,1,1,1,2,2,3,3].sample]}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1664ujg62kDHEAyNgNBYxzhWrzgxtyAnNbb2f2ZeQWmJgq2CkqOTs4sSV0lqMYhnYWCgV5KZm1qsl5tYoFCtkBYNVherUMvFBaSLFcBcveSMxCKYkprkGgUl5erkWisF5WqQMXrJ@aV5JRrJmrVKCrX/AQ "Ruby – Try It Online")
[Answer]
# Applesoft, ~~29~~ oops, 32 bytes
A little "retrocomputing" example. Bear with me, I'm brand new at this. I gather that what is designated **as** the "input" need not be byte-counted itself. As stated in the OP, the input would be given as "ABCD". (I didn't initially realize that I needed to specify input being obtained, which added 4 bytes, while I golfed the rest down a byte.)
```
INPUTI$:X=RND(1)*4:PRINTMID$(I$,(X<.5)+X+1,1)
```
The terms INPUT, RND, PRINT and MID$ are each encoded internally as single-byte tokens.
First, X is assigned a random value in the range 0 < X < 4. This is used to choose one of the characters from I$, according to (X < .5) + X + 1. Character-position value is taken as truncated evaluation of the expression. X < .5 adds 1 if X was less than .5, otherwise add 0. Results from X break down as follows:
```
A from .5 ≤ X < 1 = 12.5%
B from X < .5 or 1 ≤ X < 2 = 37.5%
C from 2 ≤ X < 3 = 25%
D from 3 ≤ X < 4 = 25%
```
[Answer]
# [Common Lisp](http://www.clisp.org/), 198 bytes
```
(setf *random-state*(make-random-state t))(defun f(L)(setf n(random 8))(cond((< n 1)(char L 0))((and(>= n 1)(< n 4))(char L 1))((and(>= n 4)(< n 6))(char L 2))((>= n 6)(char L 3))))(princ(f "ABCD"))
```
[Try it online!](https://tio.run/##VctNCsIwEIbhqwxdfVMoWC3FhQr@LHuJ0CRYtNOSxPPH1EDV2c37zPTPwc8xwptgqXRK9DRWPqhgSozqYarfRIEZ2tiXkEXH@UmQT2ifsJ9EAwcSqtNyV4462qSOdILTMfeFG169/vMme/v17eIfa9e24zSY3SA9LBXny/VWMMf4Bg "Common Lisp – Try It Online")
Readable:
```
(setf *random-state* (make-random-state t))
(defun f(L)
(setf n (random 8))
(cond
((< n 1)
(char L 0))
((and (>= n 1)(< n 4))
(char L 1))
((and (>= n 4)(< n 6))
(char L 2))
((>= n 6)
(char L 3))
)
)
(princ (f "abcd"))
```
] |
[Question]
[
## Task
Your goal, should you choose to accept it, is to write a program, that, given an input string (or array of characters), outputs every possible permutation of the letters in that string. I'm finicky with my output, so it should be sorted alphabetically, with no duplicates.
**Example:**
Input: `buzz`
Output:
```
buzz
bzuz
bzzu
ubzz
uzbz
uzzb
zbuz
zbzu
zubz
zuzb
zzbu
zzub
```
## Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code wins.
* Trailing spaces on each/any line are ok
* A single newline after the last line is allowed (but no more)
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 5 bytes
```
ṢŒ!QY
```
[Try it online!](http://jelly.tryitonline.net/#code=4bmixZIhUVk&input=&args=J2J1enon)
### Explanation
```
Ṣ Sort
Œ! All permutations
Q Unique
Y Join by linefeeds
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~4~~ 3 bytes
Updated, since an update to `œ` broke the old version,
which also saved a byte as suggested by *Magic Octopus Urn*.
```
œê»
```
[Try it online!](https://tio.run/##yy9OTMpM/f//6OTDqw7t/v@/qqo0CQA "05AB1E – Try It Online")
**Explanation**
```
œ # get all permutations of input
ê # sort and remove duplicates
» # join list by newlines
```
[Answer]
# [MATL](http://github.com/lmendo/MATL), 4 bytes
```
Y@Xu
```
[Try it online!](http://matl.tryitonline.net/#code=WUBYdQ&input=J2J1enon)
### Explanation
```
Y@ % Implicit input. Push 2D array of all permutations, each on a row, sorted
Xu % Unique rows. Implicitly display
```
[Answer]
## Python 3.5, 79 bytes
```
def f(s,w=''):
s or print(w)
for c in sorted({*s}):t=s*1;t.remove(c);f(t,w+c)
```
A function that takes input as a list of characters and outputs by printing.
Recursively makes every distinct permutation by taking each possible next character alphabetically out of the remaining distinct characters, and appending it to the output in progress `w`. Then, we recurse with this character removed. Once the input is emptied, we print `w`.
[Answer]
# [CJam](http://sourceforge.net/projects/cjam/), 5 bytes
*Thanks to [@EriktheOutgolfer](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer) for a correction (`q` instead of `r`)*
```
qe!N*
```
[Try it online!](https://tio.run/nexus/cjam#@1@Yquin9f9/UmlVFQA)
### Explanation
```
q e# Read input as a string
e! e# Unique permutations, sorted
N* e# Join by newline. Implicitly display
```
[Answer]
# Pyth - 5 bytes
```
jS{.p
```
[Try it online here](http://pyth.herokuapp.com/?code=jS%7B.p&input=%22buzz%22&debug=0).
```
j Join. Implictly joins on newlines.
S Sort
{ Uniquify
.p All permutations, implicitly run on input.
```
[Answer]
## Haskell, 46 bytes
```
import Data.List;unlines.sort.nub.permutations
```
2 bytes saved thanks to nimi
[Answer]
# J, 19 bytes
```
/:~@~.@:{~!@#A.&i.#
```
## Test case
```
f =: /:~@~.@:{~!@#A.&i.#
f 'buzz'
buzz
bzuz
bzzu
ubzz
uzbz
uzzb
zbuz
zbzu
zubz
zuzb
zzbu
zzub
```
## Explanation
This is a 4-train:
```
/- ~ --- /:
/- @ -^- ~.
/- ~ --- @: -^- {
|
| /- !
--< /- @ --^- #
| |
\-----< /- A.
>- & --^- i.
\- #
```
Basically:
```
/:~@~.@:{~!@#A.&i.#
! A.& get permutations
@# i.# of range (0..length)
{~ map indices to chars in string
@: then
~. unique
@ then
/:~ sort
```
[Answer]
# JavaScript (Firefox 30+), ~~129~~ 124 bytes
```
f=(a,i=-1)=>a[1]?[for(x of a.sort())if(a.indexOf(x)==++i)f([...a.slice(0,i),...a.slice(i+1)]).replace(/^/gm,x)].join`
`:a[0]
```
Not too bad for a language with no permutation built-ins...
[Answer]
# Python 3.5, 81 bytes:
```
from itertools import*;lambda i:'\n'.join(sorted({*map(''.join,permutations(i))}))
```
Really...81 bytes when the next longest answer is 48 bytes...*sigh*. Well, I will try this golf this more as much as I can, but golfing tips are still very much appreciated.
Also, here is the shortest solution I could get in Python 2 at **86 bytes**:
```
from itertools import*;lambda f:'\n'.join(sorted({''.join(i)for i in permutations(f)}))
```
Apparently in Python 2, `[*...]` returns a `Syntax Error`, and since `permutations` returns `itertools.permutations object at 0x...`, the next shortest way (that I know) of extracting the *unique* permutations is using `{''.join(i)for i in permutations(f)}` where `f` is the input string.
Finally, note that these are both lambda functions and thus must be called in the format `print(<Function Name>(<Input String>))`.
[Answer]
# [Brachylog](http://github.com/JCumin/Brachylog), 9 bytes
```
:pfdo~@nw
```
[Try it online!](http://brachylog.tryitonline.net/#code=OnBmZG9-QG53&input=ImJ1enoi)
### Explanation
```
:pf Find all outputs of p - Permute with the main Input as input
d Remove Duplicates
o Order
~@n Concatenate into a single string with linebreaks as separator
w Write to STDOUT
```
[Answer]
# [Perl 6](https://perl6.org), ~~49~~ 44 bytes
String as input
```
*.comb.permutations.sort».join.squish.map: *.put
```
List of characters as input
```
*.permutations.sort».join.squish.map: *.put
```
# Expanded
```
*\ # Whatever lambda
# .comb\ # split into a list of characters
.permutations\ # returns a list of lists
.sort\
».join\ # join the second level lists
.squish\ # remove adjacent repeated values
.map: *.put # print each on its own line
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog) (v2), 5 bytes
```
pᵘoẉᵐ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v@Dh1hn5D3d1Ptw64f9/paqq0iQlAA "Brachylog – Try It Online")
Find `ᵘ`nique `p`ermutations of input, s`o`rt them, `ᵐ`ap `ẉ`riteln (write with newline) over that array.
[Answer]
# Mathematica, ~~34~~ 23 bytes
```
Print@@@Permutations@#&
```
The input must be a list of characters.
**Explanation**
```
Permutations@
```
Find all permutations of the input, sorted and duplicate-free.
```
Print@@@
```
Print them one by one.
[Answer]
# Python 3, ~~77~~ 85 bytes
Now sorts!
```
import itertools as i
for a in sorted(set(i.permutations(input()))):print("".join(a))
```
[Answer]
## PowerShell v3+, 171 bytes
```
param([char[]]$x)$a,$b=$x;$a=,$a;while($b){$z,$b=$b;$a+=$a|%{0..($y=($c="$_").Length)|%{-join($c[0..$_]+$z+$c[++$_..$y])};"$z$c";"$c$z"}}$a|?{$_.length-eq$x.count}|sort -u
```
PowerShell v3 introduced the `-Unique` flag on the `Sort-Object` cmdlet, so it's a few bytes shorter than the below v2 version, since we don't need to `Select` first.
v2 version, 178 bytes:
```
param([char[]]$x)$a,$b=$x;$a=,$a;while($b){$z,$b=$b;$a+=$a|%{0..($y=($c="$_").Length)|%{-join($c[0..$_]+$z+$c[++$_..$y])};"$z$c";"$c$z"}}$a|?{$_.length-eq$x.count}|select -u|sort
```
---
PowerShell doesn't have any built-in permutations, so I borrowed my code from [Prime Factors Buddies](https://codegolf.stackexchange.com/a/94323/42963) and slightly tweaked it for use here.
This is essentially three portions, which I'll expand on below.
`param([char[]]$x)$a,$b=$x;$a=,$a` Takes input `$x`, casts it as a `char`-array, strips off the first letter into `$a` and the rest into `$b`, and then recasts `$a` as an array with the comma-operator.
`while($b){$z,$b=$b;$a+=$a|%{0..($y=($c="$_").Length)|%{-join($c[0..$_]+$z+$c[++$_..$y])};"$z$c";"$c$z"}}` Loops through the remaining letters (`$b`), each iteration taking the next letter and storing it into `$z` and leaving the remaining in `$b`, then array-concatenating onto `$a` the result of sending `$a` through its own loop -- each item of `$a` (temporarily stored into `$c`) is looped over its own `.length`, and then `$z` is inserted into every position, including prepending and appending with `$z$c` and `$c$z`. For example, for `$c = '12'` and `$z = '3'`, this will result in `'132','312','123'` being concatenated back into `$a`.
The final portion `$a|?{$_.length-eq$x.count}|select -u|sort` takes each element of `$a` and uses `Where-Object` clause to filter out only those that have the same length as the input string, then `select`s only the `-u`nique items, and finally `sort`s those alphabetically. The resulting strings are all left on the pipeline, and output via implicit `Write-Output` happens at program completion.
```
PS C:\Tools\Scripts\golfing> .\alphabetically-permute-a-string.ps1 'PPCG'
CGPP
CPGP
CPPG
GCPP
GPCP
GPPC
PCGP
PCPG
PGCP
PGPC
PPCG
PPGC
```
[Answer]
## JavaScript (ES6), 119 bytes
```
f=(s,t=[...s].sort().join``,p=``)=>t?t.replace(/./g,(c,i)=>t.indexOf(c)==i?f(s,t.slice(0,i)+t.slice(i+1),p+c):``):p+`\n`
```
Where `\n` represents the literal newline character. Port of @ETHproduction's answer to use strings instead of arrays. Reversing the output, or moving the trailing newline to the beginning, saves 3 bytes.
[Answer]
## R, 113 bytes
```
x=scan(,"");cat(sort(unique(apply(matrix(x[permute:::allPerms(l<-length(x))],,l),1,paste,collapse=""))),sep="\n")
```
Reads input from stdin. The `permute` package is assumed to be installed in order to call the `allPerms` function.
Will add an explanation as I get home from work.
[Answer]
# Java ~~302~~ 300 bytes
```
import java.util.*;class M{public static void main(String[]a){for(Object s:p(new TreeSet(),"",a[0]))System.out.println(s);}static Set p(Set l,String p,String s){int n=s.length(),i=0;if(n>1)for(;i<n;p(l,p+s.charAt(i),s.substring(0,i)+s.substring(++i,n)));else if(!l.contains(p+=s))l.add(p);return l;}}
```
**Ungolfed & test code:**
[Try it here.](https://ideone.com/PiGtqI)
```
import java.util.*;
class M{
static Set p(Set l, String p, String s){
int n = s.length(),
i = 0;
if(n > 1){
for(; i < n; p(l, p + s.charAt(i), s.substring(0, i) + s.substring(++i, n)));
} else if(!l.contains(p+=s)){
l.add(p);
}
return l;
}
public static void main(String[] a){
for(Object s : p(new TreeSet(), "", a[0])){
System.out.println(s);
}
}
}
```
**Input:** test
**Output:**
```
estt
etst
etts
sett
stet
stte
test
tets
tset
tste
ttes
ttse
```
[Answer]
## Racket 82 bytes
```
(sort(remove-duplicates(map list->string(permutations(string->list s)))) string<?)
```
Ungolfed:
```
(define(f s)
(sort
(remove-duplicates
(map
list->string
(permutations
(string->list s))))
string<?))
```
Testing:
```
(f "buzz")
```
Ouput:
```
'("buzz" "bzuz" "bzzu" "ubzz" "uzbz" "uzzb" "zbuz" "zbzu" "zubz" "zuzb" "zzbu" "zzub")
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 3 bytes
```
uOP
```
[Try it online!](https://tio.run/##yygtzv7/v9Q/4P///0mlVVUA "Husk – Try It Online")
No Unicode!
[Answer]
# Groovy, 69 Bytes
```
{(it as List).permutations().unique().sort().each{println it.join()}}
```
[Answer]
# Ruby, 51 bytes
```
->s{puts s.chars.permutation.map(&:join).uniq.sort}
```
[Answer]
# [Actually](http://github.com/Mego/Seriously), 8 bytes
Golfing suggestions welcome! [Try it online!](http://actually.tryitonline.net/#code=O2xA4pWo4pmCzqPilZRp&input=ImJ1enoi)
```
;l@╨♂Σ╔i
```
**Ungolfing**
```
Implicit input s.
;l Get len(s).
@╨ Get all len(s)-length permutations of s.
♂Σ Sum them all back into strings.
╔ uniq() the list of strings.
i Flatten the list of strings.
Implicit print the stack, separated by newlines.
```
[Answer]
## [Pip](http://github.com/dloscutoff/pip), 8 bytes
7 bytes of code, +1 for `-n` flag.
```
SSUQPMa
```
Takes a string as a command-line argument. [Try it online!](http://pip.tryitonline.net/#code=U1NVUVBNYQ&input=&args=LW4+YnV6eg)
Pip's scanner breaks runs of uppercase letters into two-letter chunks. So this code is `SS UQ PM a`--i.e. `SortString(UniQue(PerMutations(a)))`, with `a` being the command-line arg. The `-n` flag ensures the result list is newline-separated. That's all there is to it.
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), 14 bytes
**Solution:**
```
?x@<x@:prm@#x:
```
[Try it online!](https://tio.run/##y9bNz/7/377CwabCwaqgKNdBucJKKam0qkrp/38A "K (oK) – Try It Online")
**Explanation:**
Use the built-in permutation function, `prm`, to generate permutations of length of the input, apply these permutations to the input, sort alphabetically and then take distinct values.
```
?x@<x@:prm@#x: / the solution
x: / store input as x
# / count length of x
prm@ / apply (@) function prm
x@: / apply indices to x and save result back into x
< / indices to sort ascending
x@ / apply to x
? / take distint
```
[Answer]
# [Perl 5](https://www.perl.org/) `-MList::Util=uniq -F`, 68 bytes
```
$"=',';@b=sort@F;map{say if"@b"eq join$",sort/./g}uniq glob"{@b}"x@b
```
[Try it online!](https://tio.run/##K0gtyjH9/19FyVZdR93aIcm2OL@oxMHNOjexoLo4sVIhM03JIUkptVAhKz8zT0VJByStr6efXlual1mokJ6Tn6RU7ZBUq1ThkPT/f1JpVdW//IKSzPy84v@6vqZ6BoYGQNons7jEyiq0JDPHFqTrv64bAA "Perl 5 – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0 [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 5 bytes
```
á â n
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&flags=LVI&code=4SDiIG4&input=Inp6dWIi)
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), ~~132~~ 128 bytes
```
#include<bits/stdc++.h>
using namespace std;int main(){string s;for(cin>>s;cout<<s<<endl,next_permutation(s.begin(),s.end()););}
```
[Try it online!](https://tio.run/##FctBCoMwEEDRfU8hdJOgtQdI8ColGafpgBmDMwGx9Oyprt//UMojAbR2J4alzugjqTxFZ@j78TPdqhCnjkNGKQGwO8URa5cDsbFf0e1yce91M0A8TeJgreq9eI88LwPjrq@CW64alFY2MkZM1zzIeBbGWmfdr7VYj@MP "C++ (gcc) – Try It Online")
[Answer]
# [Clam](https://github.com/dylanrenwick/Clam), 9 bytes
```
p_D`Sq@~Q
```
## Explanation
```
- Implicit Q = first input
p - Print...
_ - Sorted ascending value (alphabetical order)
D - Distinct from...
`Sq - Joined (map(q=>q.join(""))
@~Q - Permutations of Q
```
] |
[Question]
[
It seems that many people would like to have this, so it's now a sequel to [this challenge](https://codegolf.stackexchange.com/questions/167106/recover-the-prime-from-the-prime-power)!
**Definition**: a *prime power* is a natural number that can be expressed in the form pn where p is a prime and n is a natural number.
**Task**: Given a prime power pn > 1, return the power n.
**Testcases**:
```
input output
9 2
16 4
343 3
2687 1
59049 10
```
**Scoring**: This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in bytes wins.
[Answer]
# [Python 2](https://docs.python.org/2/), 37 bytes
```
f=lambda n,i=2:i/n or(n%i<1)+f(n,i+1)
```
[Try it online!](https://tio.run/##DYpBCsIwFAX3nuJthIQGa1KpWuxJxEXVFj80P@EnXfT0MQOzGSbu@RfYFfIxSEba06F6SnOW@bNJosArecrKniu6LOM6@fd3Ahsa3UAtI4jiIz2sbhZVa2PrFQQMYjydwd3A9gbdpTNw/e36GhCFOKPuuvwB "Python 2 – Try It Online")
Counts factors. Apparently I wrote the [same golf](https://codegolf.stackexchange.com/a/64948/20260) in 2015.
Narrowly beats out the non-recursive
**[Python 2](https://docs.python.org/2/), 38 bytes**
```
lambda n:sum(n%i<1for i in range(1,n))
```
[Try it online!](https://tio.run/##FchBCoMwFAXAq7yNkMDfJEpaRU/Suoi0qQF9SrQLTx/JLGe/znmjzWF458Wv08eD3fFfFavYm7AlREQief6@ygi1ziVZ8mUFrcA4Qd3UAuuej7HDniJPBEWdbw "Python 2 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes
```
Òg
```
[Try it online!](https://tio.run/##MzBNTDJM/f//8KT0//9NLQ1MLAE "05AB1E – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 49 bytes
```
f=lambda n,x=2:n%x and f(n,x+1)or n/x<2or-~f(n/x)
```
[Try it online!](https://tio.run/##DYtBDoIwFAX3nOJtTNpYBQqiEDmJcVEFYhP4Je03KRuvjn3JLGaSt278cVTtdlmdZ4QtZIlzGNmP768P1tFsF8uiLNLkPvWzWV6DAanY644OEYYGTCL5sZTOg/J4186ffqnlMT1SY1jCo1UoG4WqrhR0c7sqXNqibp9dBqzeEotJsJT7Hw "Python 3 – Try It Online")
Outputs `True` instead of 1 ([as allowed by OP](https://codegolf.stackexchange.com/questions/167199/recover-the-power-from-the-prime-power#comment404175_167199)). Recursive function that repeatedly finds the lowest factor and then calls the function again with the next lowest power until it reaches 1. This is an extension of [my answer](https://codegolf.stackexchange.com/a/167125/76162) to the previous question.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), \$\require{cancel}\xcancel 4 3\$ bytes
```
|f%
```
[Run and debug it](https://staxlang.xyz/#c=%7Cf%25&i=9%0A16%0A343%0A2687%0A59049&a=1&m=2)
Length of prime factorization.
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + GNU utilities, 22
* 2 bytes saved thanks to @H.PWiz and @Cowsquack
```
factor|tr -cd \ |wc -c
```
[Try it online!](https://tio.run/##RYpBCsIwEEX3c4pP0WVBba2GgifpJs5MSUEaSQa6yd1jEcS/erz3nz6HuoXlpUjqBabZ2GcdIZGw752W1WY0R0H7QIPD7/GtyiH@FQqmOnu2mIoltCyYUDbeqUpctTo6D9T1HV2G@42u7tQ7@gA "Bash – Try It Online")
[Answer]
# [R](http://cran.r-project.org) 22 bytes
Power `n` is the number of multiples of `p` in `p^n` when `p` is prime:
```
sum(!(b<-scan())%%2:b)
```
[Try it online!](https://tio.run/##K/r/v7g0V0NRI8lGtzg5MU9DU1NV1cgqSfO/5X8A "R – Try It Online")
[Answer]
## [Nibbles](http://golfscript.com/nibbles) 5 bytes
```
,|`,$~^%@
```
This is 9 nibbles each of which is encoded in a half byte in the binary form. I think this is the shortest solution that doesn't use built in factoring.
Translation:
```
, length
| filter
`,$ 0..input
~ not \x->
^ pow (so that 0 which would have been 0 from the mod isn't)
% mod
@ input
implicit $ (x)
implicit $ (x)
```
It works by just counting the number of numbers the input divides evenly
You could run it passing in a list of numbers to process in stdin or as a command line arg. Nibbles isn't on TIO.run yet...
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), ~~50~~ 41 bytes
```
1si[dli1+dsi%0<X]dsXx[dli/dli<Y]sYdli<Yzp
```
[Try it online!](https://tio.run/##S0n@b2j@37A4MzolJ9NQO6U4U9XAJiI2pTiiAiSiD8Q2kbHFkWC6quD/fwA "dc – Try It Online")
Takes input from the top of the stack (in TIO, put the input in the header to load it onto the stack before execution). Outputs to stdout.
# Explanation
**Registers used:**
`i`: the current trial divisor, while `X` is running. Later, the divisor we've found.
`X`: the macro `dli1+dsi%0<X`, which has the effect "increment `i`, then check the modulus with the value on the stack (which will be the original input). If it's not zero, repeat".
`Y`: the macro `dli/dli<Y`, which has the effect "Add to the stack a copy of the current top of the stack, divided by `i`. Repeat until `i` is reached."
Full program:
```
1si Initialize i
[dli1+dsi%0<X]dsXx Define and run X
[dli/dli<Y]sY Define Y
dli<Y Run Y, but only if needed (if the input wasn't just i)
z The stack is i^n, i^(n-1), ... ,i, so print the stack depth
```
[Answer]
# Pyth, 2
Count prime factors:
```
lP
```
[Online test](https://pyth.herokuapp.com/?code=lP&input=59049&test_suite=1&test_suite_input=9%0A16%0A343%0A2687%0A59049&debug=0).
[Answer]
# [face](https://github.com/KeyboardFire/face), 86 bytes
```
(%d@)\$*,c'$,io>Av"[""mN*c?*m1*mp*m%*s1"$pN1p:~+p1p%%Np?%~:=/NNp+?1?-%N1?%=p%'$i?w1'%>
```
Hooray, longer than Java!
[Try it online!](https://tio.run/##BcFBCoNADAXQuwzzmTZaakAXCpr2ArlAu5GpgovBgNDuvHr63jrnxf2Cz@P6jlTnFOttn57f8AqhKGWhwlSMCujgEE3ZhrMyNkBNcA7jXdUqYblBWTAaUtzkxwmTu3d90/Z/)
I am particularly fond of the trick of using the return value of `sscanf`.
Normally the return value would be discarded,
but here it will always be 1,
because we're always reading a single number as input.
We can take advantage of this
by assigning its return value to the variable `1`,
saving the 2 bytes that would otherwise be required
to assign `1` to 1 explicitly.
```
(%d@)
\$*,c'$,io> ( setup - assign $ to "%d", * to a number, o to stdout )
Av"[""mN* ( set " to input and allocate space for N for int conversion )
c?* ( calloc ?, starting it at zero - this will be the output )
m1* ( allocate variable "1", which gets the value 1 eventually )
mp*m%* ( p is the prime, % will be used to store N mod p )
s1"$pN ( scan " into N with $ as format; also assigns 1 to 1 )
1p:~ ( begin loop, starting p at 1 )
+p1p ( increment p )
%%Np ( set % to N mod p )
?%~ ( repeat if the result is nonzero, so that we reach the factor )
:= ( another loop to repeatedly divide N by p )
/NNp ( divide N by p in-place )
+?1? ( increment the counter )
-%N1 ( reuse % as a temp variable to store N-1 )
?%= ( repeat while N-1 is not 0 -- i.e. break when N = 1 )
p%'$i? ( sprintf ? into ', reusing the input format string )
w1'%> ( write to stdout )
```
[Answer]
# [Attache](https://github.com/ConorOBrien-Foxx/Attache) and [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/) polyglot, 10 bytes
```
PrimeOmega
```
[Try Attache online!](https://tio.run/##SywpSUzOSP2fpmBlq/A/oCgzN9U/NzU98b9fampKcbRKQUFyeiwXUDyvJCS1uMQ5sTi1ODpNRyHaUkfB0ExHwdjEWEfByMzCXEfB1NLAxDI29j8A "Attache – Try It Online") [Try Mathematica online!](https://tio.run/##y00syUjNTSzJTE78n6Zgq/A/oCgzN9U/NzU9EcTMK4n2TSyITtNRqLbUUTA001EwNjHWUTAyszDXUTC1NDCxrI2N/Q8A "Wolfram Language (Mathematica) – Try It Online")
Simply a builtin for computing the number of prime factors **N** has.
## Explanation
Since **N** = **p***k*, Ω(**N**) = Ω(**p***k*) = *k*, the desired result.
[Answer]
# Whitespace, 141 bytes
```
[S S S N
_Push_0][S N
S _Duplicate_0][T N
T T _Read_STDIN_as_number][T T T _Retrieve][S S S T N
_Push_1][N
S S N
_Create_Label_LOOP_1][S S S T N
_Push_1][T S S S _Add][S N
S _Duplicate][S T S S T S N
_Copy_2nd_input][S N
T _Swap_top_two][T S T T _Modulo][N
T S S N
_If_0_Jump_to_Label_BREAK_1][N
S N
N
_Jump_to_Label_LOOP_1][N
S S S N
_Create_Label_BREAK_1][S S S N
_Push_0][S T S S T S N
_Copy_2nd_input][N
S S T N
_Create_Label_LOOP_2][S N
S _Duplicate_input][S S S T N
_Push_1][T S S T _Subtract][N
T S S S N
_If_0_Jump_to_Label_BREAK_2][S N
T _Swap_top_two][S S S T N
_Push_1][T S S S _Add][S N
T _Swap_top_two][S T S S T S N
Copy_2nd_factor][T S T S _Integer_divide][N
S N
T N
_Jump_to_Label_LOOP_2][N
S S S S N
_Create_Label_BREAK_2][S N
N
_Discard_top][T N
S T _Print_as_number]
```
Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.
[Try it online](https://tio.run/##TYxLCoAwEEPXySnmDvVCIgXdCQoef5p0urAfyGRe8p3X2597P3pmRFAXhI8mkLYsPFrCT5T2mK4QGov6tTfI6VS08o79yrBgrMbZYiUZyGxbGw) (with raw spaces, tabs and new-lines only).
**Explanation in pseudo-code:**
```
Integer n = STDIN as input
Integer f = 1
Start LOOP_1:
f = f + 1
if(n modulo-f == 0)
Call function BREAK_1
Go to next iteration of LOOP_1
function BREAK_1:
Integer r = 0
Start LOOP_2:
if(n == 1)
Call function BREAK_2
r = r + 1
n = n integer-divided by f
Go to next iteration of LOOP_2
function BREAK_2:
Print r as number to STDOUT
Program stops with an error: Exit not defined
```
**Example run: [`input = 9`](https://tio.run/##TYxLCoBADEPXySl6DY8jMjDuBAWPX5N2Fs4H0vQl7zyfcV/7MTIjgrogfDSBtGXh0RJ@orRHuUJoLPr33iDL6WjnHfuVYcFYjdViJRnI3D4)**
```
Command Explanation Stack Heap STDIN STDOUT STDERR
SSSN Push 0 [0]
SNS Duplicate top (0) [0,0]
TNTT Read STDIN as number [0] {0:9} 9
TTT Retrieve [9] {0:9}
SSSTN Push 1 [9,1] {0:9}
NSSN Create Label_LOOP_1 [9,1] {0:9}
SSSTN Push 1 [9,1,1] {0:9}
TSSS Add top two (1+1) [9,2] {0:9}
SNS Duplicate top (2) [9,2,2] {0:9}
STSSTSN Copy 2nd from top [9,2,2,9] {0:9}
SNT Swap top two [9,2,9,2] {0:9}
TSTT Modulo top two (9%2) [9,2,1] {0:9}
NTSSN If 0: Jump to Label_BREAK_1 [9,2] {0:9}
NSNN Jump to Label_LOOP_1 [9,2] {0:9}
SSSTN Push 1 [9,2,1] {0:9}
TSSS Add top two (2+1) [9,3] {0:9}
SNS Duplicate top (3) [9,3,3] {0:9}
STSSTSN Copy 2nd [9,3,3,9] {0:9}
SNT Swap top two [9,3,9,3] {0:9}
TSTT Modulo top two (9%3) [9,3,0] {0:9}
NTSSN If 0: Jump to Label_BREAK_1 [9,3] {0:9}
NSSSN Create Label_BREAK_1 [9,3] {0:9}
SSSN Push 0 [9,3,0] {0:9}
STSSTSN Copy 2nd from top [9,3,0,9] {0:9}
NSSTN Create Label_LOOP_2 [9,3,0,9] {0:9}
SNS Duplicate top (9) [9,3,0,9,9] {0:9}
SSSTN Push 1 [9,3,0,9,9,1] {0:9}
TSST Subtract top two (9-1) [9,3,0,9,8] {0:9}
NTSSSN If 0: Jump to Label_BREAK_2 [9,3,0,9] {0:9}
SNT Swap top two [9,3,9,0] {0:9}
SSSTN Push 1 [9,3,9,0,1] {0:9}
TSSS Add top two (0+1) [9,3,9,1] {0:9}
SNT Swap top two [9,3,1,9] {0:9}
STSSTSN Copy 2nd from top [9,3,1,9,3] {0:9}
TSTS Integer-divide top two (9/3) [9,3,1,3] {0:9}
NSNTN Jump to Label_LOOP_2 [9,3,1,3] {0:9}
SNS Duplicate top (3) [9,3,1,3,3] {0:9}
SSSTN Push 1 [9,3,1,3,3,1] {0:9}
TSST Subtract top two (3-1) [9,3,1,3,2] {0:9}
NTSSSN If 0: Jump to Label_BREAK_2 [9,3,1,3] {0:9}
SNT Swap top two [9,3,3,1] {0:9}
SSSTN Push 1 [9,3,3,1,1] {0:9}
TSSS Add top two (1+1) [9,3,3,2] {0:9}
SNT Swap top two [9,3,2,3] {0:9}
STSSTSN Copy 2nd from top [9,3,2,3,3] {0:9}
TSTS Integer-divide top two (3/3) [9,3,2,1] {0:9}
NSNTN Jump to Label_LOOP_2 [9,3,2,1] {0:9}
SNS Duplicate top (1) [9,3,2,1,1] {0:9}
SSSTN Push 1 [9,3,2,1,1,1] {0:9}
TSST Subtract top two (1-1) [9,3,2,1,0] {0:9}
NTSSSN If 0: Jump to Label_BREAK_2 [9,3,2,1] {0:9}
NSSSSN Create Label_BREAK_2 [9,3,2,1] {0:9}
SNN Discard top [9,3,2] {0:9}
TNST Print as integer [9,3] {0:9} 2
error
```
Program stops with an error: No exit found.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 2 bytes
```
ḋl
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@GO7pz//y3/RwEA "Brachylog – Try It Online")
### Explanation
```
ḋ Prime decomposition
l Length
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~8~~ 2 bytes
```
≢⍭
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/P@1R24RHnYse9a4FshUsudIUDM2AhLGJMZA0MrMwB1KmlgYmlgA "APL (Dyalog Extended) – Try It Online")
`⍭` finds factors, `≢` counts how many of them there are.
[Answer]
# [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 42 bytes
```
D,f,@,bUbU$^=
L,dVfbUG$XGRzGGXzÞ{f}bUbU0$:
```
[Try it online!](https://tio.run/##S0xJKSj4/99FJ03HQScpNClUJc6Wy0cnJSwtKdRdJcI9qMrdPaLq8LzqtFqQrIGK1X@VnMTcpJREBUM7ey7///8NzQA "Add++ – Try It Online")
I don't even know where to begin explaining this mess.
## Explained
```
D,f,@,bUbU$^=
D,f,@, ; a helper function f that given a list [number, [x, y]]
bUbU$^ ; returns whether x ^ y
= ; equals number
L,dVfbUG$XGRzGGXzÞ{f}bUbU0$:
L, ; a lambda that
dV ; places its input into the register
fbU ; and gets the prime factor of the input. This is guaranteed to be a single item because the input is a prime raised to a power.
G$X ; push a list of input copies of that power
GRz ; and zip that with the range [1...input]
GGX ; also, push input copies of the input
z ; and zip that with our big list. I'm calling it a big list because it is what it is.
Þ{f} ; filter that list based on the results of the helper function f
bUbU0$: ; get the power out of the many nested lists returned.
```
[Answer]
# QBasic, ~~51~~ 41 bytes
```
INPUT n
FOR i=2TO n
f=f-(n/i=n\i)
NEXT
?f
```
-10 bytes by copying the approach from [Darren Smith's Nibbles answer](https://codegolf.stackexchange.com/a/240635/16766): For a prime power input, the desired output equals the number of integers between 1 (exclusive) and the input (inclusive) that evenly divide the input.
```
INPUT number
FOR testFactor = 2 TO number
' number is divisible by testFactor if their float division equals
' their int division
isDivisible = (number / testFactor = number \ testFactor)
' Truthy is -1 in QBasic, so we subtract rather than add to the tally
numFactors = numFactors - isDivisible
NEXT testFactor
PRINT numFactors
```
[Answer]
# [HBL](https://github.com/dloscutoff/hbl), 7 bytes
*(or possibly 6.5 depending on how [this meta question](https://codegolf.meta.stackexchange.com/q/24251/16766) shakes out)*
```
+(*'?(*%.(02.
```
[Try it!](https://dloscutoff.github.io/hbl/?f=0&p=KygqJz8oKiUuKC0yMC4_&a=ODE_)
### Explanation
```
+(*'?(*%.(
(0 Inclusive range
2 from 2
. to the argument
(* Map over each value x in that list:
%. Argument mod x
(* Map over each value in that list:
'? Logical negation
The result is a list containing 1 for each number that divides
the argument, 0 otherwise
+ Take its sum
```
[Answer]
# [Risky](https://github.com/Radvylf/risky), 3 bytes
```
!\?___
```
[Try it online!](https://radvylf.github.io/risky?p=WyIhXFw_X19fIiwiWzI1Nl0iLDBd)
---
A basically built-in solution for now, working on a non-trivial version (might not be possible given Risky's heavy investment in specific operators, and generally awful control flow).
```
! Count
\ Prime factors
? Input
___ (Padding)
```
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata), 1 byte
```
ƒ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6FouOTVpSnJRcDOUu2GzJZWjGZWxizGVkZmHOZWppYGIJkQIA)
`ƒ` factorizes the input number, and returns a list of unique prime factors and a list of exponents.
Only the top of the stack will be printed, which is the list of exponents. Since the input is a prime power, this will be a singleton list.
[Answer]
# Java 8, 59 bytes
A lambda from `int` to `int`.
```
x->{int f=1,c=0;while(x%++f>0);for(;x>1;c++)x/=f;return c;}
```
[Try It Online](https://tio.run/##XU7PT4MwFD7DX/EuJiV0FdycYoWjiQdPO5rF1K7FYldIWzYWwt@OnXIyecn73sv3q2Entmo7YZrD99z1n1px4Jo5B29MGRjjaHk6z3xYUhmmoQkq0nuliewN96o15GUBz6/Gi1pYDAuoQEI5D6tqVMaDLHPMy4yev5QWaLhJU1llCZWtRXSocsrTNBluS0mt8L01wOk0RzT@X@PUqgMcQ0O081aZ@n0PzNYuuRaOghmgaxhnTnzAExhxhnAH0lhgyLcY1ps1hrvt4wOG@yLbFNOfMtpdnBdH0vaedMHXa4MkYV2nL@jXLElooE1xmCmefwA)
[Answer]
# J, 4 bytes
```
#@q:
```
`q:` gives the list of prime factors, `#` gives the length of the list.
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/lR0Krf5rcnGlJmfkK6QpWCoYmikYmxgrGJlZmCuYWhqYWHJx/QcA "J – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 37 bytes
```
length(numbers::primeFactors(scan()))
```
[Try it online!](https://tio.run/##K/r/Pyc1L70kQyOvNDcptajYyqqgKDM31S0xuSS/qFijODkxT0NTU/O/oZHFfwA "R – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 3 bytes
```
Yfz
```
[Try it online!](https://tio.run/##y00syfn/PzKt6v9/U0sDE0sA "MATL – Try It Online")
### Explanation:
```
% Implicit input: 59049
Yf % Factorize input [3, 3, 3, 3, 3, 3, 3, 3, 3, 3]
z % Number of non-zero elements: 10
% Implicit output
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~3~~ 2 bytes
```
Æḍ
```
[Try it online!](https://tio.run/##y0rNyan8//9w28Mdvf///ze1NDCxBAA "Jelly – Try It Online")
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `l`, 1 byte
```
ǐ
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=l&code=%C7%90&inputs=9&header=&footer=)
-1 byte thx to @lyxal
Length of the prime factors, the flags are cheaty+awesome
[Answer]
# MS Excel, 33 bytes
An anonymous worksheet function that takes input from cell `A1` and outputs to the calling cell
```
-SUM(-(MOD(A1,SEQUENCE(A1))<1))-1
```
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2) `L`, 1 [byte](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
f
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPWYmZm9vdGVyPSZpbnB1dD01OTA0OSZmbGFncz1M)
Push the prime `f`actors of the input then take the `L`ength of the list.
[Answer]
# [Python 2](https://docs.python.org/2/), 62 bytes
```
def f(n,p=2,i=0):
while n%p:p+=1
while n>p**i:i+=1
return i
```
[Try it online!](https://tio.run/##K6gsycjPM/r/PyU1TSFNI0@nwNZIJ9PWQNOKi7M8IzMnVSFPtcCqQNvWEM63K9DSyrTKBAsVpZaUFuUpZP4vKMrMKwEaYGxirPn/PwA "Python 2 – Try It Online")
Nothing fancy here.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 3 bytes
```
k l
```
[Try it online!](https://tio.run/##y0osKPn/P1sh5/9/U0sDE0sA "Japt – Try It Online")
## Explanation:
```
k l
k Get the prime factors of the input
l Return the length
```
[Answer]
# [Actually](https://github.com/Mego/Seriously), 2 bytes
```
ol
```
[Try it online!](https://tio.run/##S0wuKU3Myan8/z8/5/9/U0sDE0sA "Actually – Try It Online")
] |
[Question]
[
# Task
Given an array of positive integers, replace each element with the parity of the sum of the other elements. The array is guaranteed to have **at least** 2 elements.
# Definition
* Parity: whether a number is odd or even.
# Example
For the array `[1,2,3,1]`:
* Replace `1` with the parity of `2+3+1`, i.e. `even`.
* Replace `2` with the parity of `1+3+1`, i.e. `odd`.
* Replace `3` with the parity of `1+2+1`, i.e. `even`.
* Replace `1` with the parity of `1+2+3`, i.e. `even`.
Output: `[even, odd, even, even]`
# Input
An array of positive integer.
You may take it as a proper array, or as a linefeed-separated string of positive integers.
You may assume that the array and the values inside are within the handling capability of your language.
# Output
An array of **two consistent values**, one representing `odd`, one representing `even`.
You may output it as a linefeed-separated string of the two values.
# Testcases
Inputs:
```
[1, 2, 3, 1]
[1, 2, 3, 2, 1]
[2, 2]
[100, 1001]
```
Outputs:
```
[even, odd, even, even]
[even, odd, even, odd, even]
[even, even]
[odd, even]
```
Note: you may choose other consistent values other than `odd` and `even`.
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in bytes wins.
[Standard loophole](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) applies.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
+SḂ
```
[Try it online!](https://tio.run/nexus/jelly#@68d/HBH0//D7Y@a1rj//x8dbaijYKSjYKyjYBirw6WA4BrBRIAMI4iUgQFQzMDAMDYWAA "Jelly – TIO Nexus")
### How it works
```
+SḂ Main link. Argument: A (array)
S Compute the sum of A.
+ Add the sum to each element of A.
Using _ (subtraction) or ^ (bitwise XOR) would also work.
Ḃ Bit; compute the parity of each resulting integer.
```
[Answer]
# JavaScript (ES6), ~~38 36~~ 32 bytes
```
a=>a.map(b=>eval(a.join`+`)-b&1)
```
Uses `0` for even and `1` for odd.
# Test
```
f=
a=>a.map(b=>eval(a.join`+`)-b&1)
console.log(f([1, 2, 3, 1]))
console.log(f([1, 2, 3, 2, 1]))
console.log(f([100, 1001]))
```
[Answer]
## Haskell, 20 bytes
```
f x=odd.(sum x-)<$>x
```
Uses `True` for odd values and `False`for even values.
[Try it online!](https://tio.run/nexus/haskell#@5@mUGGbn5Kip1FcmqtQoatpo2JX8T83MTNPwVahoCgzr0RBRSFNIdpQx0jHGIgNY/8DAA "Haskell – TIO Nexus")
Subtract each element from the sum of the list and test if it's odd.
`f` turned to pointfree has also 20 bytes: `map=<<(odd.).(-).sum`.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~5~~, 4 bytes
```
ts-o
```
[Try it online!](https://tio.run/nexus/matl#@19SrJv//3@0oY6CkY6CMZg0jAUA "MATL – TIO Nexus")
*One byte saved thanks to Dennis!*
This gives '1' for odd and '0' for even. Explanation:
```
t % Duplicate the input
s % Get the sum of the input
- % Subtract it from the original input
o % Get the parity of each element
```
[Answer]
## [Alice](https://github.com/m-ender/alice), ~~31~~ 28 bytes
```
/O.HQ\d$K@
\i#\ /d2-&+!w?+2%
```
[Try it online!](https://tio.run/nexus/alice#@6/vr@cRGJOi4u3AFZOpHKOgn2Kkq6atWG6vbaT6/78hlxEQGnMZAgA "Alice – TIO Nexus")
The input format doesn't matter as long as the integers are separated. The output format is linefeed-separated.
The layout is probably still not optimal but I haven't found a way to shorten this further yet.
### Explanation
```
/ Reflect to SE. Switch to Ordinal.
i Read all input as a string.
Reflect off bottom boundary. Move to NE.
. Duplicate the input string.
Reflect off top boundary. Move to SE.
\ Reflect to N. Switch to Cardinal.
H Implicitly convert the top copy of the input to the integers it
contains and take the absolute value of the top-most one. (Taking
the absolute value doesn't do anything, but we need the implicit
conversion to integers.)
The IP wraps back to the second line.
\ Reflect to SE. Switch to Ordinal.
Immediately reflect off bottom boundary. Move to NE.
Q Reverse the stack (this converts the integers back to strings but
that's irrelevant). After this, we end up with all the individual
integers on the bottom of the stack in reverse order and the other
copy of the input string with all integers on top.
Reflect off top boundary. Move to SE.
/ Reflect to E. Switch to Cardinal.
d Push the stack depth, which is one more than the number of list
elements (due to the other input string on the stack).
2- Subtract 2.
&+ Run + that many times, which implicitly converts the second string
to the integers it contains and then adds up all the list elements.
! Store the sum on the tape.
w Push the current IP position to the return address stack. This
lets us return here repeatedly to implement a loop.
?+ Retrieve the input sum from the tape and add it to the current
element.
2% Compute its parity. Other ways to do this are 1A and 0x. 2F would
also work but it gives 0/2 instead of 0/1.
The IP wraps the first column of the grid.
\ Reflect to NE. Switch to Ordinal. The IP bounces diaginally up
and down until it hits the next \.
O Implicitly convert the current parity to a string and print it
with a trailing linefeed.
# Skip the next command (the H).
\ Reflect to E. Switch to Cardinal.
d Push the stack depth. This is zero when we're done.
$ Skip the next command if the stack depth is indeed zero, which
exits the loop.
K Jump to the return address on top of the return address stack without
popping it (so that the next K will jump there again).
@ Terminate the program.
```
[Answer]
# Pyth, ~~7~~ 6 bytes
```
mi2-sQ
```
*-1 Byte thanks to @KZhang*
Outputs 1 for odd, 2 for even.
[Try it!](https://pyth.herokuapp.com/?code=mi2-sQ&input=%5B1%2C2%2C3%2C1%5D&test_suite=1&test_suite_input=%5B1%2C+2%2C+3%2C+1%5D%0A%5B1%2C+2%2C+3%2C+2%2C+1%5D%0A%5B2%2C+2%5D%0A%5B100%2C+1001%5D&debug=0)
### Explanation
```
m%-sQd2
m Q # For each element in the (implicit) input list
sQ # Take the sum of all the elements
- d # subtract that element, so that we now have the sum of the other elements
% 2 # modulo 2; 1=off, 0=even
```
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), ~~4~~ 3 bytes
```
O^È
```
[Try it online!](https://tio.run/##MzBNTDJM/f/fP@5wx///0YY6CkY6CsZg0jAWAA "05AB1E (legacy) – Try It Online")
```
O # Sum
^ # XOR with (implicit) input
È # Print 1 for even / 0 for odd
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~33~~ 31 bytes
-2 bytes thanks to Leaky Nun
```
lambda x:[sum(x)-z&1for z in x]
```
[Try it online!](https://tio.run/nexus/python2#S7ON@Z@TmJuUkqhQYRVdXJqrUaGpW6VmmJZfpFClkJmnUBH7H8QuSS0uAXGjow11FIx0FIx1FAxjdRAcIwgfSBmBhA0MgHwDA8PYWCsuhYKizLwSsAk66rrqOmkaIKYm138A "Python 2 – TIO Nexus")
[Answer]
# R, 21 bytes
```
(sum(n<-scan())-n)%%2
```
reads the list from stdin and returns 0 for even, 1 for odd. binds the input to the variable `n` inside the call to `sum` instead of calling it outside, i.e., `n=scan();(sum(n)-n)%%2`
[Try it online!](https://tio.run/nexus/r#@69RXJqrkWOjW5ycmKehqambo6mqavTfUMFIwVjB8D8A)
[Answer]
# [J](http://jsoftware.com/), 6 bytes
```
2|]++/
```
[Try it online!](https://tio.run/nexus/j#@59ma2VUE6utrf8/NTkjXyFNwVDBSMFYwZALhWuEEDBSMILLGRiAMFCqIrNEweA/AA "J – TIO Nexus")
[Answer]
## Mathematica, 13 bytes
```
#+Tr@#&/*OddQ
```
or
```
OddQ[#+Tr@#]&
```
[Answer]
## Clojure, 30 bytes
```
#(for[i %](odd?(apply - i %)))
```
Substracts all values from each value in turn, for example with input `[a b c d]` the 2nd calculated value is `b - a - b - c - d` = `-(a + c + d)`. Output is `false` for even and `true` for odd.
But you might as well use `+` and calculate each subsequent term twice so it doesn't affect the parity.
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 10 bytes
```
{_:+f+1f&}
```
This is an anonymous block (function) that takes the input from the stack and replaces it by the output.
[Try it online!](https://tio.run/nexus/cjam#izZUMFIwVjCM/V8db6Wdpm2Yplb7v67gfzRYPBYA "CJam – TIO Nexus")
### Explanation
Consider input `[1 2 3 1]`.
```
{ e# Begin block
e# STACK: [1 2 3 1]
_ e# Duplicate
e# STACK: [1 2 3 1], [1 2 3 1]
:+ e# Fold addition over the array: compute its sum
e# STACK: [1 2 3 1], 7
f+ e# Map addition over the array with extra parameter
e# STACK: [8 10 11 8]
1 e# Push 1
e# STACK: [8 10 11 8], 1
f& e# Map bit-wise "and" over the array with extra parameter
e# STACK: [0 0 1 0]
} e# End block
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~19~~ 7 bytes
*Golfed 12 bytes thanks to @Adám*
```
2|+/-¨⊢
```
[Try it online!](https://tio.run/nexus/apl-dyalog#@@/0qG2CUY22vu6hFY@6Fv3/76RgqGCkYKxgyAVjGYHZRgpGIBEDAxA2BAA "APL (Dyalog Unicode) – TIO Nexus")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 7 bytes
```
£x +X&1
```
[Try it online!](https://tio.run/nexus/japt#@39ocYWCdoSa4f//0YY6RjrGOoaxAA "Japt – TIO Nexus")
### Explanation
```
£ x +X&1
mX{ x +X&1} // Ungolfed
UmX{Ux +X&1} // Variable introduction
UmX{ } // Replace each item in the input array with
&1 // the parity of
Ux // the sum of the input array
+X // plus X.
// Implicit: output result of last expression
```
[Answer]
# Perl 5, 31 bytes
```
sub{map$x+=$_,@_;map$x-$_&1,@_}
```
Outputs `1` for odd and `0` for even.
[Answer]
# Clojure(Script), 36 bytes
Output is `true` for odd and `false` for even. Both output and input are sequences.
```
(fn[l](map #(odd?(-(apply + l)%))l))
```
[Answer]
# PHP, 50 Bytes
[Online Versions](http://sandbox.onlinephpfunctions.com/code/115c6cae183cf2e67de1c315108e2d99cace708d)
1 for odd , 0 for even
Output as string separated with `_`
```
<?foreach($_GET as$v)echo array_sum($_GET)-$v&1,_;
```
# PHP, 72 Bytes
Output as array use `array_map`
```
<?print_r(array_map(function($v){return array_sum($_GET)-$v&1;},$_GET));
```
[Answer]
# C, ~~68~~ 62 bytes
```
i;s;f(c,l)int*l;{while(i<c)s+=l[i++];while(i)l[--i]=s-l[i]&1;}
```
1 for odd, 0 for even
**Detailed** [*Try Online*](https://tio.run/nexus/c-gcc#nYvLCsIwFAXXzVdcKkpiUzGtu7T@SMxC@qAXYhRTMRDy7TUFwb2LM4s5zLJB25lXP0Dj5h7vh@lMUDo50o4bhnbeGxneE5qBYtMxV7RGYVFo@XXMqLJE3boyeb0TMhJyu6KljASSpR680tBCAMGh4lBzEBAlyR7PdI40D9uew2/xYnPu1VEniBXVilqzlIz0xD37q43L8gE)
```
f(int c, int * l)
{
int i = 0, s = 0;
while(i < c)
{
s = s + l[i];
i = i + 1;
}
// assert(i == c)
while(i > 0)
{
i = i - 1;
l[i] = s - l[i]&1;
}
}
```
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~40~~ 38 bytes
```
\d+
¶$` $'
^¶
\d+
$*
+` |11
%M`1
¶
```
[Try it online!](https://tio.run/nexus/retina#U9VwT/gfk6LNdWibSoKCijpX3KFtXFwgARUtLu0EhRpDQy4uVd8EQ6ACLoX//w0VjBSMFQy5ILQRkGWkYMRlaGCgAMSGAA "Retina – TIO Nexus") Outputs 1 for odd and 0 for even. Explanation: The first two lines duplicate the input once for each number in the input, but without the element itself. This creates an extra blank line which is then deleted. The input is then converted from decimal to unary, the spaces are deleted and the parity computed. Even parity is then converted to zero and the results joined back in to one line. Edit: Saved 2 bytes thanks to @FryAmTheEggman. I tried some other versions which are conceptually more pleasing but which take far too many bytes to express:
```
\d\B
T`2468O`00001
T`d`10`^([^1]*1[^1]*1)*[^1]*1[^1]*$
```
Changes all inputs to their parity, then flips all their parities if the total has odd parity.
```
\d+
$*
^.*
$&¶$&
(?=.*$)
11
\B
0
T`d`10`.*¶1
¶0
```
Sums a duplicate of the input, then takes the parity of everything, then inverts the parities if the sum is odd, then deletes the sum again.
[Answer]
# [Ohm](https://github.com/MiningPotatoes/Ohm), 4 bytes
```
DΣ-é
```
[Try it online!](https://tio.run/nexus/ohm#@@9ybrHu4ZX//wMA "Ohm – TIO Nexus")
Basically a direct port of the [MATL](https://codegolf.stackexchange.com/a/118521/65298) and [05AB1E](https://codegolf.stackexchange.com/a/118510/65298) answers. Uses `true` for even and `false` for odd.
[Answer]
# [Julia 1.0](http://julialang.org/), 17 bytes
```
x->(sum(x).-x).%2
```
[Try it online!](https://tio.run/##ZY1NDoIwFIT3nGJSY0KTYtq6Myl6D@MCQ/kxQAltFU5fi3EjLmbx5n0z8/BdW4g5VOqu63YIc5an1vfpTA9Z1F4GPZTJxTbmhSq9CgbJcGQQN5rUkYJCX4zpkuWLUgJnEFOWBCcQ/dQDYTE0U4odGt2NeoI1aJ2FLuwCZzDpooTxbvSOrUUWYrU/Jd/VerP678rNI97yB@Q8EpxHKLwB "Julia 1.0 – Try It Online")
[Answer]
# k, 9 bytes
```
{2!x-+/x}
```
The output is a `1` for `odd`, and a `0` for even. [Try it online.](http://johnearnest.github.io/ok/?run=%7B2%21x-%2B%2Fx%7D%5B1%202%203%201%5D)
Converted to pseudocode, it would be:
```
for number in x:
yield (number - sum(x)) % 2
```
[Answer]
# [Scala](http://www.scala-lang.org/), 19 bytes
```
x=>x.map(x.sum-_&1)
```
[Try it online!](https://tio.run/nexus/scala#y0/KSk0uUfBNzMxTSK0oSc1LKVZwLChQqOYqS8xRSLNScCwqSqyM9swriVWwtUPhKfyvsLWrUMhNLNCo0CsuzdWNVzPU/F9QlJlXkpOnkaYBVqthqKNgpKNgrKNgqKmpkJsdXAKUT1dQ0lFQ0uSq/Q8A "Scala – TIO Nexus")
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~94~~ ~~68~~ 66 bytes
```
({({}<>)<>})<>{<>(({})<({}<>{}<>(())){({}[()]<([{}])>)}{}>)<>}<>{}
```
[Try it online!](https://tio.run/nexus/brain-flak#HcuxDQAxCAPAVSjtMnol3yAWiTIJYnYCKa6wZSccHmpUi@JqqEx9ZQNI9maDR7E9Do3h8S69yRwy5Cuz/LIu "Brain-Flak – TIO Nexus")
This seems a little long for the task. There might be a more convenient way to do this.
## Explanation
First we calculate the sum of the stack with:
```
({({}<>)<>})
```
The we go through the entire stack adding that result to each element and determine the pairity
```
<>{<>(({})<({}<>{}<>(())){({}[()]<([{}])>)}{}>)<>}<>{}
```
---
This uses a pretty cool mod 2 algorithm I came up with for this challenge.
```
({}(())){({}[()]<([{}]())>)}{}
```
This pushes 1 under the input decrements until the input reaches zero each time performing `1-n` to the 1 we placed earlier, it then removes the input.
[Answer]
# [Wise](https://github.com/Wheatwizard/Wise), ~~54~~ 52 bytes
```
::^:??[:!^:?^:!^:?^?]|!::^??[!:?^:><^!:?^:!^:?^?]!&|
```
[Try it online!](https://tio.run/nexus/wise#@29lFWdlbx9tpQik4iCkfWyNIlAYKKoIErOKq9NVU0SSVVSr@f//v@F/o//GIBIA "Wise – TIO Nexus")
## Explanation
This code would be a lot shorter if it didn't take so many bytes to swap the top two elements. The current record is
```
:?^:!^:?^!
```
This unfortunately constitutes the majority of the code.
---
First we take the XOR sum of the stack
```
::^:??[:!^:?^:!^:?^?]|!
```
We then XOR this with every element and the element with it last bit zeroed
```
::^??[!:?^:><^!:?^:!^:?^?]!&|
```
[Answer]
# [Java](http://openjdk.java.net/), ~~81~~ 78 bytes
3 bytes thanks to Kevin Cruissen
```
void f(int[]a){int s=0,i=a.length;for(int x:a)s+=x;for(;i-->0;a[i]=s-a[i]&1);}
```
[Try it online!](https://tio.run/nexus/java-openjdk#VVAxboQwEKzhFa4iLMAypIvjSHlAqisRxYYA2YgzCJvLnRBvJ2u4Q4pcrD27szPjYfrssGJVB9ayD0Azr5cev1gToXFFCXymyqyWCWoQXW1a962afvRtdn0BbmN93QCFafomFRRYapv68pRxtazDrmAdOCrb8jPpRCc3omlJYmwtn8Ng0ytK5mrrKrC1ZZqZ@pfdcZoI5ixhecKeE5Ytyb93fkB0y@9NKQmVMlvCYFFh8HCNWip8PWQeoTCOvY3dB5D4MUFRiB54M/6HIi6aCLiHTjfr6rPoJycGSuM6E/3ABcTksBPv4wg3K1y/JyWK5ywhnfUP "Java (OpenJDK 8) – TIO Nexus")
Modifies the array in-place.
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 64 bytes
```
{for(i=0;++i<=NF;print s[i]%2)for(j=0;++j<=NF;)if(i!=j)s[i]+=$j}
```
[Try it online!](https://tio.run/nexus/awk#@1@dll@kkWlrYK2tnWlj6@dmXVCUmVeiUBydGatqpAmSzAJLZoElNTPTNDIVbbM0QfLatipZtf//GyoYKRgDsSEXAA "AWK – TIO Nexus")
Outputs a `0` for even sums and `1` for odd sums separated by newlines. The only even slightly out-of-the-box thinking was placing the `print` command inside the `for` "increment" step. I tried a few "clever" ways to print, but they didn't save bytes.
Just for giggles, if you don't want newlines:
```
{for(i=0;++i<=NF;m=m,s[i]%2)for(j=0;++j<=NF;)if(i!=j)s[i]+=$j}1
```
which has the same byte-count as above, but is a bit more obtuse.
[Answer]
# Swift - 55 bytes
*Finally beats C!* Also, 0 for even, 1 for odd
```
func g(a:[Int]){for i in a{print((a.reduce(0,+)-i)%2)}}
```
A function, with usage: `g(a: [1,2,3,2,1] // => 0 1 0 1 0`
**[Check it out!](http://swift.sandbox.bluemix.net/#/repl/5909745bd9945251091fd3f9)**
[Answer]
# Axiom, 45 bytes
```
f(a)==[(reduce(+,a)-a.j)rem 2 for j in 1..#a]
```
no check for input type, possible recalculation of sum "a" each element...tests
```
(27) -> [[a,f(a)] for a in [[1,2,3,1], [1,2,3,2,1], [2,2], [100, 1001] ]]
(27)
[[[1,2,3,1],[0,1,0,0]], [[1,2,3,2,1],[0,1,0,1,0]], [[2,2],[0,0]],
[[100,1001],[1,0]]]
```
] |
[Question]
[
Today's challenge is simple: Without taking any input, output any valid sudoku board.
In case you are unfamiliar with sudoku, [Wikipedia describes what a valid board should look like](https://en.wikipedia.org/wiki/Sudoku):
>
> The objective is to fill a 9×9 grid with digits so that each column, each row, and each of the nine 3×3 subgrids that compose the grid (also called "boxes", "blocks", or "regions") contains all of the digits from 1 to 9.
>
>
>
Now here's the thing... There are [6,670,903,752,021,072,936,960 different valid sudoku boards](https://puzzling.stackexchange.com/questions/2/what-is-the-maximum-number-of-solutions-a-sudoku-puzzle-can-have). Some of them may be very difficult to compress and output in fewer bytes. Others of them may be easier. Part of this challenge is to figure out which boards will be most compressible and could be outputted in the fewest bytes.
Your submission does not necessarily have to output the same board every time. But if multiple outputs are possible, you'll have to prove that every possible output is a valid board.
You can use [this script](https://tio.run/#05ab1e#code=fMKpdnkzw7R9KTPDtMO4dnlKdnnDqn19wq7DuHZ5w6p9wq52ecOqfSnDqsW-aMKmUQ&input=MTIzNDU2Nzg5CjQ1Njc4OTEyMwo3ODkxMjM0NTYKMjMxNTY0ODk3CjU2NDg5NzIzMQo4OTcyMzE1NjQKMzEyNjQ1OTc4CjY0NTk3ODMxMgo5NzgzMTI2NDU) (thanks to Magic Octopus Urn) or [any of these answers](https://codegolf.stackexchange.com/questions/22443/create-a-sudoku-solution-checker) to verify if a particular grid is a valid solution. It will output a `[1]` for a valid board, and anything else for an invalid board.
I'm not too picky about what format you output your answer in, as long as it's clearly 2-dimensional. For example, you could output a 9x9 matrix, nine 3x3 matrices, a string, an array of strings, an array of 9-digit integers, or nine 9-digit numbers with a separator. Outputting 81 digits in 1 dimension would not be permitted. If you would like to know about a particular output format, feel free to ask me in the comments.
As usual, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so write the shortest answer you can come up with in the language(s) of your choosing!
[Answer]
# Pyth, ~~22~~ ~~14~~ ~~12~~ 10 bytes
```
.<LS9%D3 9
```
Saved 2 bytes thanks to Mr. Xcoder.
[Try it here](http://pyth.herokuapp.com/?code=.%3CLS9%25D3+9&debug=0)
```
.<LS9%D3 9
%D3 9 Order the range [0, ..., 8] mod 3.
> For each, ...
.< S9 ... Rotate the list [1, ..., 9] that many times.
```
[Answer]
# [Python 2](https://docs.python.org/2/), 47 bytes
```
l=range(1,10)
for x in l:print(l*9)[x*8/3:][:9]
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P8e2KDEvPVXDUMfQQJMrLb9IoUIhM08hx6qgKDOvRCNHy1IzukLLQt/YKjbayjL2/38A "Python 2 – Try It Online")
[Answer]
# T-SQL, ~~96~~ 89 bytes
Found one shorter than the trivial output!
```
SELECT SUBSTRING('12345678912345678',0+value,9)FROM STRING_SPLIT('1,4,7,2,5,8,3,6,9',',')
```
Extracts 9-character strings starting at different points, as defined by the in-memory table created by `STRING_SPLIT` (which is supported on SQL 2016 and later). The `0+value` was the shortest way I could do an implicit cast to integer.
Original trivial output (96 bytes):
```
PRINT'726493815
315728946
489651237
852147693
673985124
941362758
194836572
567214389
238579461'
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
9Rṙ%3$Þ
```
[Try it online!](https://tio.run/##y0rNyan8/98y6OHOmarGKofn/f8PAA "Jelly – Try It Online")
*And a little bit of [this](https://codegolf.stackexchange.com/a/172475/41024)...*
-1 thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)('s thinking?)
[Answer]
# [Python 2](https://docs.python.org/2/), 53 bytes
```
r=range(9)
for i in r:print[1+(j*10/3+i)%9for j in r]
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v8i2KDEvPVXDUpMrLb9IIVMhM0@hyKqgKDOvJNpQWyNLy9BA31g7U1PVEiSdBZaO/f8fAA "Python 2 – Try It Online")
---
Alternatives:
# [Python 2](https://docs.python.org/2/), 53 bytes
```
i=0;exec"print[1+(i/3+j)%9for j in range(9)];i-=8;"*9
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9PWwDq1IjVZqaAoM68k2lBbI1PfWDtLU9UyLb9IIUshM0@hKDEvPVXDUjPWOlPX1sJaScvy/38A "Python 2 – Try It Online")
# [Python 2](https://docs.python.org/2/), 54 bytes
```
for i in range(81):print(i/9*10/3+i)%9+1,'\n'*(i%9>7),
```
```
i=0;exec"print[1+(i/3+j)%9for j in range(9)];i+=10;"*9
```
```
r=range(9);print[[1+(i*10/3+j)%9for j in r]for i in r]
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 47 bytes
Output as an array of the rows.
```
_=>[...w="147258369"].map(x=>(w+w).substr(x,9))
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/e1i5aT0@v3FbJ0MTcyNTC2MxSKVYvN7FAo8LWTqNcu1xTr7g0qbikSKNCx1JT8791cn5ecX5Oql5OfrpGmgZQBAA "JavaScript (Node.js) – Try It Online")
Generates this:
```
472583691
583691472
691472583
725836914
836914725
914725836
258369147
369147258
147258369
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~58~~ 55 bytes
```
l=*range(10),
for i in b" ":print(l[i:]+l[1:i])
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P8dWqygxLz1Vw9BAU4crLb9IIVMhM08hSYmRhZ2JlYOZjVPJqqAoM69EIyc60ypWOyfa0CozVvP/fwA "Python 3 – Try It Online")
* -3 bytes thanks to Jo King,
The elements of the byte string end up giving the numbers `[1, 4, 7, 2, 5, 8, 3, 6, 9]` which are used to permute the rotations of `[0..9]`. The `0` is removed in `l[1:i]` and there is no need for a null byte which takes two characaters (`\0`) to represent in a bytes object.
**[55 bytes](https://tio.run/##K6gsycjPM/7/P15HK8e2KDEvPVXD0ECTKy2/SCFTITNPIUmJkYWdiZWDmY1TyaqgKDOvRCMnOtMqVjsn2iozVvP/fwA)**
```
_,*l=range(10)
for i in b" ":print(l[i:]+l[:i])
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 bytes
```
9Rṙ`s3ZẎ
```
[Try it online!](https://tio.run/##y0rNyan8/98y6OHOmQnFxlEPd/X9/w8A "Jelly – Try It Online")
```
9Rṙ`s3ZẎ
9R Range(9) -> [1,2,3,4,5,6,7,8,9]
` Use the same argument twice for the dyad:
ṙ Rotate [1..9] each of [1..9] times.
This gives all cyclic rotations of the list [1..9]
s3 Split into three lists.
Z Zip. This puts the first row of each list of three in it's own list,
as well as the the second and third.
Ẏ Dump into a single list of nine arrays.
```
[Answer]
## Batch, 84 bytes
```
@set s=123456789
@for %%a in (0 3 6 1 4 7 2 5 8)do @call echo %%s:~%%a%%%%s:~,%%a%%
```
Uses @Mnemonic's output. `call` is used to interpolate the variable into the slicing operation (normally it only accepts numeric constants).
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~40 32~~ 27 bytes
*-5 bytes thanks to nwellnhof*
```
{[^9+1].rotate($+=3.3)xx 9}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwvzo6zlLbMFavKL8ksSRVQ0Xb1ljPWLOiQsGy9n@ahqZebmKBhpZecWKl5n8A "Perl 6 – Try It Online")
Anonymous code block that returns a 9x9 matrix. Maps each row to a different rotation of the range 1 to 9.
[Answer]
# Java 10, ~~82~~ 75 bytes
```
v->{for(int i=81;i-->0;)System.out.print((i/9*10/3+i)%9+1+(i%9<1?" ":""));}
```
-7 bytes by creating a port of one of [*@TFeld*'s Python 2 answers](https://codegolf.stackexchange.com/a/172526/52210).
[Try it online.](https://tio.run/##LY7PCoJAEIfvPcUgCLuJ/@iSbdoT5EXoEh22VWNMV9FVCPHZt7W8zDC/Yb75Kj5xt8rfWtR8GODKUc47AJSq6EsuCkjXEWBqMQdBbmubKDPZsjNlUFyhgBQkxKAnN5nLtifmGjA@hgxdNwkYzT6DKhqvHZXX9WZJCPrRPgz8g4PUjpzQIWhH5/BigXWyLErZotmK78ZnbfDbl59DYwxJpgzmdX8Ap3896Qkix7rezBb9BQ)
**Explanation:**
```
v->{ // Method with empty unused parameter and no return-type
for(int i=81;i-->0;) // Loop `i` in the range (81, 0]
System.out.print( // Print:
(i/9 // (`i` integer-divided by 9,
*10 // then multiplied by 10,
/3 // then integer-divided by 3,
+i) // and then we add `i`)
%9 // Then take modulo-9 on the sum of that above
+1 // And finally add 1
+(i%9<1? // Then if `i` modulo-9 is 0:
" " // Append a space delimiter
: // Else:
""));} // Append nothing more
```
Outputs the following sudoku (space delimited instead of newlines like below):
```
876543219
543219876
219876543
765432198
432198765
198765432
654321987
321987654
987654321
```
[Answer]
# [J](http://jsoftware.com/), 18 bytes
```
>:(,&|:|."{,)i.3 3
```
[Try it online!](https://tio.run/##y/qvpKegnqZga6WuoKNQa6VgoADE/@2sNHTUaqxq9JSqdTQz9YwVjP9rcqUmZ@QrpP0HAA "J – Try It Online")
### Output
```
1 2 3 4 5 6 7 8 9
4 5 6 7 8 9 1 2 3
7 8 9 1 2 3 4 5 6
2 3 4 5 6 7 8 9 1
5 6 7 8 9 1 2 3 4
8 9 1 2 3 4 5 6 7
3 4 5 6 7 8 9 1 2
6 7 8 9 1 2 3 4 5
9 1 2 3 4 5 6 7 8
```
### How it works
```
>:(,&|:|."{,)i.3 3
i.3 3 The 2D array X = [0 1 2;3 4 5;6 7 8]
,&|:|."{, 3-verb train:
,&|: Transpose and flatten X to get Y = [0 3 6 1 4 7 2 5 8]
, Flatten X to get Z = [0 1 2 3 4 5 6 7 8]
|."{ Get 2D array whose rows are Z rotated Y times
>: Increment
```
## Fancy version, 23 bytes
```
|.&(>:i.3 3)&.>|:{;~i.3
```
[Try it online!](https://tio.run/##y/qvpKegnqZga6WuoKNQa6VgoADE/2v01DTsrDL1jBWMNdX07Gqsqq3rgLz/mlypyRn5Cmn/AQ "J – Try It Online")
Output:
```
┌─────┬─────┬─────┐
│1 2 3│4 5 6│7 8 9│
│4 5 6│7 8 9│1 2 3│
│7 8 9│1 2 3│4 5 6│
├─────┼─────┼─────┤
│2 3 1│5 6 4│8 9 7│
│5 6 4│8 9 7│2 3 1│
│8 9 7│2 3 1│5 6 4│
├─────┼─────┼─────┤
│3 1 2│6 4 5│9 7 8│
│6 4 5│9 7 8│3 1 2│
│9 7 8│3 1 2│6 4 5│
└─────┴─────┴─────┘
```
### How it works
```
|.&(>:i.3 3)&.>|:{;~i.3
i.3 Array [0 1 2]
{;~ Get 2D array of boxed pairs (0 0) to (2 2)
|: Transpose
|.&(>:i.3 3)&.> Change each pair to a Sudoku box:
&.> Unbox
>:i.3 3 2D array X = [1 2 3;4 5 6;7 8 9]
|.& Rotate this 2D array over both axes
e.g. 1 2|.X gives [6 4 5;9 7 8;3 1 2]
&.> Box again so the result looks like the above
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~14~~ 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
8ÝΣ3%}ε9Ls._
```
-2 bytes by creating a port of [*@Mnemonic*'s Pyth answer](https://codegolf.stackexchange.com/a/172475/52210).
[Try it online.](https://tio.run/##yy9OTMpM/f/f4vDcc4uNVWvPbbX0KdaL/@9Ve2j3fwA) (Footer is added to pretty-print it. Actual result is a 9x9 matrix; feel free to remove the footer to see.)
**Explanation:**
```
8Ý # List in the range [0, 8]
Σ } # Sort the integers `i` by
3% # `i` modulo-3
ε # Map each value to:
9L # List in the range [1, 9]
s._ # Rotated towards the left the value amount of times
```
---
**Original 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) solution:**
```
9Lε9LN3*N3÷+._
```
[Try it online.](https://tio.run/##yy9OTMpM/f/f0ufcVksfP2MtP@PD27X14v971R7a/R8A) (Footer is added to pretty-print it. Actual result is a 9x9 matrix; feel free to remove the footer to see.)
**Explanation:**
```
9L # Create a list of size 9
ε # Change each value to:
9L # Create a list in the range [1, 9]
N3*N3÷+ # Calculate N*3 + N//3 (where N is the 0-indexed index,
# and // is integer-division)
._ # Rotate that many times towards the left
```
Both answers result in the Sudoku:
```
123456789
456789123
789123456
234567891
567891234
891234567
345678912
678912345
912345678
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/) & Matlab,50 48 29 bytes
```
mod((1:9)+['furRaghAt']',9)+1
```
[Try it online!](https://tio.run/##y08uSSxL/f8/Nz9FQ8PQylJTO1o9rbQoKDE9w7FEPVZdByhi@P8/AA "Octave – Try It Online")
*-2 thanks to Johnathon frech*
*-14 thanks to Sanchises Broadcast addition suggestion, who also pointed out the non-compatibility.*
*-5 by noticing that the vector can be written in matlab with a char string and transposition.*
Was intuitive, now not so.
Uses broadcast summing to spread 1:9 over 9 rows, spread by values determined by the char string.
Sudoku board produced:
```
5 6 7 8 9 1 2 3 4
2 3 4 5 6 7 8 9 1
8 9 1 2 3 4 5 6 7
3 4 5 6 7 8 9 1 2
9 1 2 3 4 5 6 7 8
6 7 8 9 1 2 3 4 5
7 8 9 1 2 3 4 5 6
4 5 6 7 8 9 1 2 3
1 2 3 4 5 6 7 8 9
```
[Answer]
# [Haskell](https://www.haskell.org/), 41 bytes
```
[[x..9]++[1..x-1]|x<-[1,4,7,2,5,8,3,6,9]]
```
[Try it online!](https://tio.run/##Dca7DoMgGAbQvU/xxTjY8ENC7ybqSzgiA7FNNFUwQFOGvjv2TGcy4f1alpxDq1QSotaMKSlE4lL/UsOVpAvd6URXetCZblRrnVczW7R4ugO2T@yjR4nR2dHEf1azoRo8eIcwuS88GEMx2OKIkHc "Haskell – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 34 bytes
```
(a=*1..9).map{|x|p a.rotate x*3.3}
```
[Try it online!](https://tio.run/##KypNqvz/XyPRVstQT89SUy83saC6pqKmQCFRryi/JLEkVaFCy1jPuPb/fwA "Ruby – Try It Online")
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), ~~16~~ 11 bytes
```
9{9╒♂ï*3/Ä╫
```
[Try it online!](https://tio.run/##ASEA3v9tYXRoZ29sZv//OXs54pWS4pmCw68qMy/DhOKVq/9hbv8 "MathGolf – Try It Online")
Saved 5 bytes thanks to JoKing
[Answer]
# Python - 81 bytes
```
l=list(range(1,10))
for i in range(1,10):print(l);l=l[3+(i%3==0):]+l[:3+(i%3==0)]
```
[Try it Online](https://tio.run/##K6gsycjPM/7/P8c2J7O4RKMoMS89VcNQx9BAU5MrLb9IIVMhM08BSdSqoCgzr0QjR9MaqCPaWFsjU9XY1hYoHqudE22F4Mf@/w8A)
I like having 81 bytes, but after some optimizing :(
# Python 2 - ~~75 68 59~~ 58 bytes
*-7 bytes thanks to @DLosc*
*-9 bytes thanks to @Mnemonic*
*-1 byte thanks to @JoKing*
```
l=range(1,10)
for i in l:print l;j=i%3<1;l=l[3+j:]+l[:3+j]
```
[Try it Online](https://tio.run/##K6gsycjPM/r/P8e2KDEvPVXDUMfQQJMrLb9IIVMhM08hx6qgKDOvRCHHOss2U9XYxtA6xzYn2lg7yypWOyfaCsiI/f8fAA)
[Answer]
[**R**](https://www.r-project.org/)**, 54 bytes**
```
x=1:9;for(y in(x*3)%%10)print(c(x[-(1:y)],x[(1:y)]))
```
**Output:**
```
[1] 4 5 6 7 8 9 1 2 3
[1] 7 8 9 1 2 3 4 5 6
[1] 1 2 3 4 5 6 7 8 9
[1] 3 4 5 6 7 8 9 1 2
[1] 6 7 8 9 1 2 3 4 5
[1] 9 1 2 3 4 5 6 7 8
[1] 2 3 4 5 6 7 8 9 1
[1] 5 6 7 8 9 1 2 3 4
[1] 8 9 1 2 3 4 5 6 7
```
[Try it online!](https://tio.run/##K/r/v8LW0MrSOi2/SKNSITNPo0LLWFNV1dBAs6AoM69EI1mjIlpXw9CqUjNWpyIawtDU/M/1HwA)
[Answer]
Huge Thanks to @Shaggy!
# [JavaScript (Node.js)](https://nodejs.org), 61 bytes
```
t=>[...s='123456789'].map(e=>s.slice(t=e*3.3%9)+s.slice(0,t))
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/E1i5aT0@v2Fbd0MjYxNTM3MJSPVYvN7FAI9XWrlivOCczOVWjxDZVy1jPWNVSUxsmZKBToqn5Pzk/rzg/J1UvJz9dI01DU5PrPwA "JavaScript (Node.js) – Try It Online")
[Answer]
# Python 3, 51 bytes
```
r='147258369';print([(r*4)[int(i):][:9]for i in r])
```
[Answer]
# [Python 2](https://docs.python.org/2/), 48 bytes
```
r='147258369'
for i in r:print(r*4)[int(i):][:9]
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v8hW3dDE3MjUwtjMUp0rLb9IIVMhM0@hyKqgKDOvRKNIy0QzGsTI1LSKjbayjP3/HwA "Python 2 – Try It Online")
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), ~~13~~ 11 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
◂j3[«3[T3[«
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXUyNUMyJXVGRjRBJXVGRjEzJXVGRjNCJUFCJXVGRjEzJXVGRjNCJXVGRjM0JXVGRjEzJXVGRjNCJUFC,v=8)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes
```
E⁹⭆⁹⊕﹪⁺÷×χι³λ⁹
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3sUDDUkchuATIS4dyPPOSi1JzU/NKUlM0fPNTSnPyNQJySos1PPNKXDLLMlNSNUIyc1OLNQwNdBQyNXUUjIE4B4gtNUHA@v///7plOQA "Charcoal – Try It Online") Link is to verbose version of code. Uses @Mnemonic's output. Explanation:
```
E⁹ Map over 9 rows
⭆⁹ Map over 9 columns and join
ι Current row
χ Predefined variable 10
× Multiply
÷ ³ Integer divide by 3
λ Current column
⁺ Add
﹪ ⁹ Modulo 9
⊕ Increment
Implicitly print each row on its own line
```
[Answer]
# [C (clang)](http://clang.llvm.org/), 65 bytes
```
f(i){for(i=0;i<81;)printf("%d%c",(i/9*10/3+i)%9+1,i++%9>7?10:9);}
```
The function is now able to be reused
[Try it online!](https://tio.run/##DctBDoIwEAXQtT0FwTSZsSg0LrQW8SyktfgTbA2iG8LZq2//3N6NfRxyDgReQpoI18aiPWvLrwlxDlRKL11ZEWqz0019VGBplK6glDTd6aabi2G75i2iGz/@XrTv2SMdHp34/@LZI9I3wfMiNoHYijX/AA "C (clang) – Try It Online")
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), 16 bytes
```
1+9!(<9#!3)+\:!9
```
[Try it online!](https://tio.run/##y9bNS8/7/99Q21JRw8ZSWdFYUzvGStHy/38A "K (ngn/k) – Try It Online")
First answer in ngn/k, done with a big help from the man himself, @ngn.
### How:
```
1+9!(<9#!3)+\:!9 // Anonymous fn
!9 // Range [0..8]
( )+\: // Sum (+) that range with each left (\:) argument
!3 // Range [0..2]
9# // Reshaped (#) to 9 elements: (0 1 2 0 1 2 0 1 2)
< // Grade up
9! // Modulo 9
1+ // plus 1
```
[Answer]
# Japt, ~~11~~ 10 bytes
```
9õ ñu3
£éX
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=OfUg8XUzCqPpWA==&input=LVI=) or [verify the output](https://tio.run/##MzBNTDJM/f@/5tDKskrjw1tqNYHE4R1llV5llYdX1dYeWgfiAFmH1oEpzcOrju7LOLQs8P9/I1MLYzNLQxNzLiCGcLggAkAOlwWMyWUOU8hlCVPIBdNqxAXTasgF02oMAA)
---
## Explanation
```
9õ :Range [1,9]
ñ :Sort by
u3 : Mod 3 of each
\n :Assign to variable U
£ :Map each X
éX : U rotated right by X
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 8 bytes
```
ṠmṙÖ%3ḣ9
```
[Try it online!](https://tio.run/##ARcA6P9odXNr///huaBt4bmZw5YlM@G4ozn//w "Husk – Try It Online")
[Answer]
# [Deadfish~](https://github.com/TryItOnline/deadfish-), 344 bytes
```
{iiiii}icicicicicicic{d}iicic{dddd}c{iiii}iiiicicicic{d}iicicicicic{dddd}dddc{iiiii}dddc{d}iicicicicicicicic{dddd}ddddddc{iiii}cicicicicicicic{d}iic{dddd}ic{iiii}iiicicicicic{d}iicicicic{dddd}ddc{iiii}iiiiiicic{d}iicicicicicicic{dddd}dddddc{iiii}dcicicicicicicicic{ddddd}iiic{iiii}iicicicicicic{d}iicicic{dddd}dc{iiii}iiiiicicic{d}iicicicicicic
```
[Try it online!](https://tio.run/##bY5BDoAgDARf5KPMVuOeOZK@vQIFRWwJAcJkZ@XY5WS6NrPMOkrMK4vSzzKK7Ai5/o9XpcpGD2vXD7KAD6uIxM7x9SISj7SpHv/lFm@HBWE3abKRh8jbs2YpIqvZDQ "Deadfish~ – Try It Online")
] |
[Question]
[
# Input
A calendar year from 927 to 2022.
# Output
You can use any three distinguishable outputs. As an example,
“K” (short for King)
or
“Q” (short for Queen)
depending on which of the two England had in that year. If there was both a King and Queen in that year you can output either.
If there was no King or Queen for the whole of that year, your code must output something that is not one of those two messages.
# Dates
Kings: 927-1553, 1603-1649, 1660-1702, 1714-1837, 1901-1952, 2022
Queens: 1553-1603, 1689-1694, 1702-1714, 1837-1901, 1952-2022
Neither: 1650-1659
[Answer]
# [Squire](https://github.com/sampersand/squire), 194 characters
```
d=tally(inquire())i=\(d,s,e)=>s<=d&&d<=e;o=ùîéùî¶ùî´ùî§;if i(d,MDCL,MDCLIX){o=ùîèùî¨ùîØùî° ùîìùîØùî¨ùî±ùî¢ùî†ùî±ùî¨ùîØ}alas if i(d,MCMLII,MMXXII)||i(d,MDCCCXXXVII,MCMI)||i(d,MDCCII,MDCCXIV)||i(d,MDLIII,MDCIII){o=ùîîùî≤ùî¢ùî¢ùî´}proclaim(o)
```
This contest doth be marvelously suited for ye medieval-inspired parlance, [Squire](https://github.com/sampersand/squire). Whilst Squire doth hath a veritable cornucopia of features, lamentably suitability for golfing doth be nary amongst them.
Squire only has roman numeral literals, as well as some fairly length constructs (e.g. `inquire`, `tally`, `proclaim`), so it's not as short as other languages. On the plus side, squire has bare words—however only when the strings are comprised entirely exclusively of the unicode fraktur characters or whitespace.
Unfortunately, [the interpreter](https://github.com/sampersand/squire) is not able to fit onto TIO or anything else, so if you want to test it you'll need to build locally...
Ungolfed, the program is:
```
N.B. Journeys are functions, and you get a reward for returning from them.
journey in(date, start, end) {
reward start <= date && date <= end
}
N.B. `tally` converts to a number, `inquire` reads from stdin.
N.B. In addition to roman numerals, `tally` also reads arabic ones too.
date = tally(inquire())
N.B. Using the fraktur literals, set the default value for `whom`.
N.B. This is sugar for "King".
whom = ùîéùî¶ùî´ùî§; N.B. The `;` is needed here because the parser is bad lol
N.B. Check to see if the date is within Cromwell's time.
if in(date, MDCL, MDCLIX) {
whom = ùîèùî¨ùîØùî° ùîìùîØùî¨ùî±ùî¢ùî†ùî±ùî¨ùîØ
} alas if
in(date, MCMLII, MMXXII)
|| in(date, MDCCCXXXVII, MCMI)
|| in(date, MDCCII, MDCCXIV)
|| in(date, MDLIII, MDCIII)
{
whom = ùîîùî≤ùî¢ùî¢ùî´
}
N.B. The printing press wasn't around way back when. So instead we have
N.B. the town crier proclaim our outputs.
proclaim("The {whom} reigned during the year {date}")
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 50 bytes
Returns \$0\$ for Queen, \$1\$ for King, or \$2\$ for neither.
This code includes some unprintable characters.
```
y=>2132%Buffer(`
2/
+
{@3`).find(c=>(y-=c)<1542)&3
```
[Try it online!](https://tio.run/##bYpNa8JAEEDv2h8xBprMkI82E0WkrpReC0LxKIIh2bUR2ZVxLSz98em2557eg/fO7Vd762S4@tK6Xo9GjUFtuG748e1ujBY8Tvlpkj98vzZHqsxge@zUBkOpOlrXizlT2ozGCQooKOsCQuSKly9R1gr4mTlqntMEQGCm4G80GIggTaFz9uYuurq4E4bKu52XwZ6Qqmvb73wrHudUgPxbOJYEE8hhn33ctbZZAdl7nH651YP/1JId9nKIR0IJjT8 "JavaScript (Node.js) – Try It Online")
### How?
The ASCII codes of the data string are:
```
[ 11, 50, 47, 10, 43, 12, 123, 64, 51 ]
```
They represent the number of years to be added to get the exclusive upper bound of the next interval, starting at \$1542\$.
Once the correct interval has been identified, we apply the following formula to its encoding number \$N\$ to figure out whether it was a King, a Queen or neither:
$$(2132 \bmod N)\bmod 4$$
The last interval is not explicitly encoded. For any input greater than \$1952\$, `find()` returns `undefined` which is turned into `NaN`. But because we use a bitwise AND with \$3\$ rather than an actual modulo \$4\$, it is eventually coerced to \$0\$ -- the expected result for Queen Elizabeth II.
| N | Exclusive upper bound | Interval | 2132 mod N | and 3 | Result |
| --- | --- | --- | --- | --- | --- |
| 11 | 1553 | 927 - 1552 | 9 | 1 | King |
| 50 | 1603 | 1553 - 1602 | 32 | 0 | Queen |
| 47 | 1650 | 1603 - 1649 | 17 | 1 | King |
| 10 | 1660 | 1650 - 1659 | 2 | 2 | Neither |
| 43 | 1703 | 1660 - 1702 | 25 | 1 | King |
| 12 | 1715 | 1703 - 1714 | 8 | 0 | Queen |
| 123 | 1838 | 1715 - 1837 | 41 | 1 | King |
| 64 | 1902 | 1838 - 1901 | 20 | 0 | Queen |
| 51 | 1953 | 1902 - 1952 | 41 | 1 | King |
| undefined | n/a | 1953 - ... | NaN | 0 | Queen |
[Answer]
# [Python 3](https://docs.python.org/3/), 60 bytes
A function that returns `0` for **King**, `1` for **Queen**, and `2` for **Neither**.
```
lambda n:sum(c>n-ord('ؑٱڦޟܭ'[c%5])>0for c in b'2
@I')
```
[Try it online!](https://tio.run/##RY5BTsMwFET3KYf4G2RbtZHt1GldKRVbzhAi5KYEIjVOlKRSOQYnYMeOBbcBhLhK8I/UdmON/sybcfsyPDc@Hsv0fty7ertz4Nf9oabFxoum21Hy9fr9@fP@9/b7QbLi2uRsI8umgwIqD1uiZ7Or2zvCRgcpZFkO6D2g1zn/9Ei11DHLozMhueJ6HU2xHg@Vbw8DZTd9u68GSjgQFmzYc@hCY@1aWvmBQ38KCMJY8JE/Xmam@BzUxILLjjnMUyh4NC37S9DqJYfpUyFZlVBSz8A3AyZc5nPk2y5MhvsYwkIZE3NQiYyFShYWZSKFWkod5FIthFrFoVJZqYSyRk/tWuATISsQRWplg7QLpKQWiAYZWIEoFpgTlZgwkBj7Dw "Python 3 – Try It Online")
[Answer]
# [Knight](https://github.com/knight-lang/knight-lang) (v2.0-alpha), 78 bytes
```
O I|>927=xP?GxF3'165'0I|&<1553x<1603x|&<1702x<1714x|&<1837x<1901x&<1952x<2022x
```
[Try it online!](https://knight-lang.netlify.app/v2#WyJPIEl8PjkyNz14UD9HeEYzJzE2NScwSXwmPDE1NTN4PDE2MDN4fCY8MTcwMng8MTcxNHh8JjwxODM3eDwxOTAxeCY8MTk1Mng8MjAyMngiLCIzIl0=)
Nothing special, just check for ranges with `<` and `>`. Since we have to output just three distinct things, `0` is for when it's neither, `true` for a queen and `false` for a king. Slightly unminified:
```
O I|>927=xP?GxF3'165'0
I|&<1553x<1603x
|&<1702x<1714x
|&<1837x<1901x
&<1952x<2022x
```
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), ~~ 58 ~~ 57 bytes
```
lambda y:9%(6-sum((y:=y-v)<1500for v in b'61/\n+|?4'))%2
```
(Contains an unprintable byte between `+` and `|`.)
An unnamed function that accepts an integer from \$[927,2022]\$ and:
* produces a `ZeroDivisionError` for years when neither a king nor queen reigned;
* returns \$0\$ if a king was on the throne during the year (except Charles III (2022)); or
* returns \$1\$ otherwise (when a queen was on the throne the entire year, or 2022)
**[Try it online!](https://tio.run/##XZDNTsMwEITv5SW2h8q2SEOSQqERERfoBQmJK20PbrppLbVOtHEirNJnD06g4Wcv9o6/mdW6sGaX68ldQU2WLJu9PKw3Emw8G/HpuKwOnNs4seNa3Ic3QZDlBDUoDWs2Da@W@vLi4@GaCTGKmoKwVnlVQgKMDVrQtiBJvUU@i249iIJoIuIBuDJkvy5tkbNk3IpekGWJZJzu/DzwIBQeZGwu1X4I8zYYJcHRniCrdGpU7qagqUjjBo50Yl0OvqdYGHhDyh9VrUpHPRHl9Hds1HVpRYTauH7BnpXeMo@9VojanS@ozA6JrRa06liV9fgwgfPSP6kFKW249c6U@PfCfN9nv8X@174NzSc "Python 3.8 (pre-release) – Try It Online")**
### How?
The byte-string `b'61/\n+|?4'` encodes the integers `[54,49,47,10,43,11,124,63,52]`. The `for` loop subtracts each from the year, `y`, cumulatively by employing the walrus operator, `:=`, and counts, with `sum(...)`, how many are less than `1500` (\$54\$ years before the first lone queen). To force an error for the sixth period (no monarch) and two distinct values otherwise arithmetic is employed:
| years | sum=N | 6-N | 9 mod (6-N) | (9 mod (6-N)) mod 2 | identifies |
| --- | --- | --- | --- | --- | --- |
| 927-1553 | 9 | -3 | 0 | 0 | king |
| 1554-1602 | 8 | -2 | -1 | 1 | queen |
| 1603-1649 | 7 | -1 | 0 | 0 | king |
| 1650-1659 | 6 | 0 | err | err | none |
| 1660-1702 | 5 | 1 | 0 | 0 | king |
| 1703-1713 | 4 | 2 | 1 | 1 | queen |
| 1714-1837 | 3 | 3 | 0 | 0 | king |
| 1738-1900 | 2 | 4 | 1 | 1 | queen |
| 1901-1953 | 1 | 5 | 4 | 0 | king |
| 1954-2022 | 0 | 6 | 3 | 1 | queen |
---
## Non-erroring alternative, 57 bytes
```
lambda y:2**sum((y:=y-v)<1500for v in b'61/\n+|?4')%40%3
```
Returns \$2\$ for King, \$1\$ for Queen, or \$0\$ for neither.
[Try it online!](https://tio.run/##XY9Pb8IwDMXv7EuYA3LCsi5NYX@qVbvtMmnSzsChQAqRIK3ctFLE@Oxd2g00zRfLz79nPVfe7UubPFXUFdmyO@TH9TYHn6rptG6OjPk083ctf4nnUhYlQQvGwhof4vulvb35ep0hn8zkJOkq0q0pmxoyQBz1qO9Ryu1Os2f1KEBJlfB0BKEoUAXzfBjyutbkghZwJkUsFBdQ4FtuDuNAnfyZA2nXkNVbONEZB9emIdLWhUML/NDG7TWhwM9Gaxv6u7E7XC1oNbCmuOLjDC5Jf6L0VZGxjnlxofi/DUZRhH/F66u/hu4b "Python 3.8 (pre-release) – Try It Online")
### How?
Same sum as before with different arithmetic:
| years | sum=N | 2\*\*N | (2\*\*N) mod 40 | ((2\*\*N) mod 40) mod 3 | identifies |
| --- | --- | --- | --- | --- | --- |
| 927-1553 | 9 | 512 | 32 | 2 | king |
| 1554-1602 | 8 | 256 | 16 | 1 | queen |
| 1603-1649 | 7 | 128 | 8 | 2 | king |
| 1650-1659 | 6 | 64 | 24 | 0 | none |
| 1660-1702 | 5 | 32 | 32 | 2 | king |
| 1703-1713 | 4 | 16 | 16 | 1 | queen |
| 1714-1837 | 3 | 8 | 8 | 2 | king |
| 1738-1900 | 2 | 4 | 4 | 1 | queen |
| 1901-1953 | 1 | 2 | 2 | 2 | king |
| 1954-2022 | 0 | 1 | 1 | 1 | queen |
[Answer]
# x86-64 machine code, ~~38~~ ~~32~~ 31 bytes
```
48 B9 64 12 33 20 9F A1 52 B8 31 C0 99 B6 06 88 EA 48 C1 C1 07 14 04 29 D7 99 79 F3 24 05 C3
```
[Try it online!](https://tio.run/##bVLbjtowEH22v2JKhdZmwyqEAFsI/YO@9KkPSJWxncRVcGguNKjsr5eOnbDb7q6U2DMnZ87cIqeZlNfrR2Nl0SoNSd0oUz7kn@l/UGH2r7HK2Mxh1NgGUuZOwTdwKo0CbZUslWZ8Q0V9AAZfR4w@ZEW5FwWkNF1TcihPUMkugNljkjzCBRZhkszwjpdJsnDADIGFR6IkiWOHoDFfeSNGK0RriUY0d@EzDF9S0pUVaIG6eFAi1c8@lcoDWNJKH7VohuyqCEDmlFRl0VeyokQoCQLxmJK63YNWBoXUTeiHraGXQKZVnrlAAd3QoeM15SPArv1QDsLYfi5VJl0uUcFkgs6J09@UuC8dbCEM4OyuTQ8Vom6c283ngXe@142omoGRYnvMRX2KVhsMT7YQhdEczft7TgnKEpN6Rv8BLhdgTj5lHefwYeslkempnvuSw8GEHHGzTcpG49hM8V3D2Ozs6N9aAuimsx7AXjFkqPn87DzX3DnoibrnpruzX4TMjdXgJzZyEq2tTWa1GoZ0xEj2CuMp8n7lptDAjq6RN4RhBxxumWAcRt@w8skRh7N5qQDY2MD@3Oia@87ckjiKTt9Jyn1g2zif3e3snfNx421l3UKe6PX6R6aFyOrr9LCM8cA/fouCuvgL "C (gcc) – Try It Online")
Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes the year number in EDI and returns a value in EAX: 4 for kings, 0 for queens, and 1 for the interregnum.
In assembly:
```
f:
mov rcx, 18<<8 | 50<<1 | 46<<58 | 10<<51 | 42<<44 | 12<<37 | 124<<30 | 64<<23 | 51<<16
# Put this constant in RCX.
xor eax, eax # Set EAX to 0.
cdq # Set EDX to 0 by sign-extending EAX.
mov dh, 6 # Set the second-lowest byte of EDX to 6.
repeat:
mov dl, ch # Set the low byte of EDX to the second-lowest byte of RCX.
rol rcx, 7 # Rotate RCX left by 7 bits.
adc al, 4 # Add 4+CF to AL.
sub edi, edx # Subtract EDX from EDI.
cdq # Set EDX to 0 by sign-extending EAX.
jns repeat # Jump back to repeat if the subtraction's result is nonnegative.
and al, 5 # Keep only the 1s bit and the 4s bit of AL.
ret # Return.
```
The basic way this works is to decrease the given number by 1554, 50, 46, 10, 42, 12, 124, 64, 51, 137, stopping when the result is negative, so that the loop executes a different number of times for each period of constant output.
The years of change were assigned to make all the period lengths even, except the last two. This allows the values to be stored in 7 bits each, so that nine can fit into a 64-bit register, while extracting 8 bits at a time (which includes the previous value's low bit) and still functioning correctly.
The 10th value extracted (for Elizabeth II's reign) entirely overlaps the 1st and 9th values, so we can only control its high bit, by assigning the year 1952. But because only years up to 2022 have to be handled, it is OK for this value to be higher than necessary.
The 1st value, which is 1554, is created by setting the second-lowest byte before the loop and then inserting the low byte within the loop (saving 2 bytes compared to pre-setting the whole thing).
To handle the interregnum, notice that the low bit of RCX ends up being 1 only when the given year is during the interregnum or the king period that follows it, and that is the same bit that gets copied into CF by the `ROL` instruction. An `ADC` instruction adds 4+CF to AL with each iteration, so that the 4s bit alternates between 0 and 1, while the 1s bit stays 0 initially, then becomes 1 for the interregnum and becomes 0 again for the next period, and stays 0 thereafter. At the end, an `AND` instruction picks out those two bits.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~118~~ 117 bytes
```
165.
LP
155[4-9]|15[6-9].|160[0-2]|170[3-9]|171[0-3]|183[89]|18[4-9].|1900|195[3-9]|19[4-9].|20[01].|202[01]
Q
...+
K
```
[Try it online!](https://tio.run/##Lcw5DsJADAXQ3ldBseyZeJYzkAJqK0UKChoKRJm7D/6jNM/W9/J9/d6fYwwtxrQ9SM18Xfp@qnmJyqcWcVlSJFU8z1HVSHI0LXtD0OZN7HaRwK69fsUpPuisCQ09iZlvdB@jWyUVoCCBDFZgoIAKGoiLPw "Retina 0.8.2 – Try It Online") Link includes some test cases. Outputs `K` if there was ever a King in that year, otherwise `Q` if there was ever a Queen in that year, otherwise `LP`, as the Cromwells used the title "Lord Protector" for some of that period. Edit: Saved 1 byte thanks to @pxeger.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~ 25 23 ~~ 22 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
⁽£4;“1/½+¿|?4‘Ä<⁸SḂ⁻¡3
```
A monadic Link that accepts an integer in \$[927,2022]\$ and yields:
* \$0\$ if there was a king on the throne at any point during the year (except for Charles III (2022));
* \$3\$ if neither a king nor queen reigned; or
* \$1\$ otherwise (if a queen and only a queen reigned all year or Charles III succeeded (2022)).
**[Try it online!](https://tio.run/##ATUAyv9qZWxsef//4oG9wqM0O@KAnDEvwr0rwr98PzTigJjDhDzigbhT4biC4oG7wqEz////MTY1MA "Jelly – Try It Online")** Or see [all years](https://tio.run/##AUYAuf9qZWxsef//4oG9wqM0O@KAnDEvwr0rwr98PzTigJjDhDzigbhT4biC4oG7wqEz/yzDhylH//9yYW5nZSg5MjcsIDIwMjMp "Jelly – Try It Online").
### How?
```
⁽£4;“1/½+¿|?4‘Ä<⁸SḂ⁻¡3 - Link: integer, Y
⁽£4 - 1553
“1/½+¿|?4E‘ - code-page indices = [49,47,10,43,11,124,63,52]
; - concatenate -> [1553,49,47,10,43,11,124,63,52]
Ä - accumulate -> [1553,1602,1649,1659,1702,1713,1837,1900,1952]
<⁸ - less than Y? (vectorises)
S - sum -> S
¬° - repeat...
⁻ 3 - ...number of times: not equal to three
(leave as 3 when no monarch)
Ḃ - ...action: mod 2
-> 0 if a king during the year except 2022; or
1 otherwise
```
[Answer]
# [Perl 5](https://www.perl.org/) `-Mutf8 -MList::Util=pairgrep -p`, 67 bytes
```
$_=/^165/?N:pairgrep{$a<$_&&$_<$b}unpack"U*","ؑكڙڞڦڲܭݭޠߦ"
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3lY/ztDMVN/ez6ogMbMovSi1oFol0UYlXk1NJd5GJam2NK8gMTlbKVRLSUfpxsSbzbdm3pp3a9mtTXfW3l17b8H9ZUr//xsZGJn8yy8oyczPK/6v62uqZ2BoAKRLS9IsgJRPZnGJlVVoSWaOLcyG/7oFOQA "Perl 5 – Try It Online")
Outputs `1` for a Queen, `0` for a King, or `N` for none.
[Answer]
# [Zsh](https://www.zsh.org/), 67 bytes
```
>$1<165?&&bye 2
< (1(<553-603>|6<89-94>|7<2-14>|<837-901>)|<1952->)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwe5i20BvP660_CIFQwWNaksjcz09IwMjo1rNao2lpSVpuhY3ne1UDG0MzUzt1dSSKlMVjLhsFDQMNWxMTY11zQyM7WrMbCwsdS1N7GrMbYx0DYG0jYWxua6lgaGdZo2NoaWpka6dJtQoXU01O_2U1DL9vNKcHGsbGxsVQz09vRgFleJoe23DWOuiXAWt2prSvMxCBd00Q4imRdGxCyAsAA)
Outputs via exit code: 0 for queen, 1 for king, and 2 for neither.
Explanation:
* `>$1`: create a file named according to the input
* `<165?`: search for a file beginning with `165` (as there was no monarch during that decade)
+ `&&bye 2`: if one exists, exit early with exit code 2
* `<`: otherwise, search for a file matching the long pattern of periods when there was a queen
+ `<x-y>` is a Zsh pattern searching for a number in the range \$ [x, y] \$
* Zsh will then exit with 1 if no file matches that pattern, and 0 otherwise
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 59 bytes
```
*p;f(y){for(p=L"2/\n+
{@3,//";y>1552;)y-=*p++;y=2704%*p&3;}
```
[Try it online!](https://tio.run/##XU9NS8QwEL0Xf8QYWEmalu5mXRaJEe@K4NnuocS0W9BasvGjlP5146RRVxxImHnz3rwZnTdae5/2sqYDG@sXS3t1S0RRdvxkvF5nRUHkcLXabIRkQ67SnnM5KLFdni/S/mwtJ992Dp6rtqMsGRPA0PvKpuDMh3vYgYIRyE3bNSQDcv9qTBeSO9O6vbEEJjlLwozemjek56sI4SpAAz6YyiJ@IbYy5pcKxFKIWHHOZnq0/plljUMJnoQMJo@tGuhsc6oChf02juoQ35sgQ/7DcXZNyeKxdPM7lOGaYJIFdhaPxmz3x3RK4j8l/lPXT1Vz8Pn7Fw "C (gcc) – Try It Online")
-2 bytes thanks to ceilingcat!!
[Answer]
# [Python 3](https://docs.python.org/3/), 131 bytes
```
a=[1553,1603,1689,1694,1702,1714,1837,1901,1952,2022]
f=lambda x:"AKQ"[any(i for i in range(5)if a[2*i]<x<a[2*i+1])*2or x//10!=165]
```
[Try it online!](https://tio.run/##HYuxDoIwFEV3vuLJ1GIT@ooFSmBwdnJuOtRotYkWQhzK19ficnJucs@yfV9zaFKyk0YpG4Yt39GrDHVi2HGRgdn6pmOoOGZIwQQXwhRuetvP7W4hDuX5ci21DRvx4OYVPPgAqw3PB5HUO7BaVN6McfzLEQ2tRL7FukZ@mLCVJu1Z3DOdJzJAhZyB4MjNUMCy@vAljkRK0w8 "Python 3 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 120 bytes
```
r=lambda s,l:{*range(s,s+l)}
f=lambda y:2*(y in r(1650,10))+(y in r(1553,51)|r(1689,6)|r(1702,13)|r(1837,65)|r(1952,71))
```
[Try it online!](https://tio.run/##TY3LDoIwEEX3fEWXHZhFH5mWkvgxNYqS1EoKm0b99gpNMO7OfeTeOa/3Z9SlpFPwj/PFswXD8GqTj7crX3DpAnya8QjzoFqe2RRZ4tKQQCkAup9DpJEkvPewd2gqWaFQ6oq9tmiooiOFVgKUOU1x5SN3ygI0h9qn/uX2tXW/ "Python 3 – Try It Online")
Interpreting the output: 0 = King, 1 = Queen, 2 = Neither.
Nothing too fancy here. Commented version of `f`:
```
f=lambda y:(
2
# y in r(1650,10) = is neither king nor queen
* (y in r(1650,10))
# y in ... = is queen
+ (y in r(1553,51)|r(1689,6)|r(1702,13)|r(1837,65)|r(1952,71))
)
```
] |
[Question]
[
# Cops' Challenge
[Robbers' challenge here](https://codegolf.stackexchange.com/questions/245702/whats-the-missing-code-robbers).
>
> It has now been four days since the challenge was posted so all new answers should be marked as **non-competing** in the title. These answers can still be cracked by robbers but will not go towards their total, and cannot win this challenge.
>
>
>
In this [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") challenge, you (the cops) must write a program which prints out a certain string (to STDOUT) when run (and does not error or print to STDERR).
Then, **remove a string of consecutive characters** from the code so that it **still runs (without erroring or printing to STDERR)**, but does not give the correct output (or gives no output).
Robbers will try to find the correct characters to add back into the code so that it produces the right (case-sensitive) output (except that there may be an extra trailing newline).
The number of characters they find must be less than or equal to the number of characters removed, so if 4 characters were removed and they find a solution adding in only 3 characters, it is still valid.
In your answer, provide:
1. The language of the code
2. The code with characters removed (remember, the characters must be consecutive: you can't remove characters from several different places in the code)
3. How many characters have been removed
4. The string that the full program outputs (if there is a trailing newline, you may leave that out)
**Remember that your answer is still cracked even if the solution found by the robbers was not intended**. For this reason, make sure it is not possible for the robbers to simply put some code which says
```
Print out the string;
End the program.
```
(In order to stop this happening, try to minimise the number of characters removed while making sure the submission is still challenging. This will also improve your score.)
The score of an answer is equal to:
$$
\operatorname{len}(\text{program with chars removed}) + 2 \times \operatorname{len}(\text{chars removed})
$$
or
$$
\operatorname{len}(\text{program}) + \operatorname{len}(\text{chars removed})
$$
(They both equate to the same thing).
Make sure to edit your answer if it has been cracked, and link the robber's post. If the robber found an unintended solution, then you may keep the intended solution a secret so that people can still try to find it.
## Example submission
>
> # Python, score of 14
>
>
> Code: `print(5*"a")`
>
> Number of characters removed: 1
>
> Target output: `5 a` (currently outputs `aaaaa`)
>
>
>
This would be very easy to crack as the character `,` would just need to be added before the `*`, but it would be valid.
## Scoring
The following scoring criterion will be used in order (if #1 is a tie, then #2 is used to tiebreak, etc.):
1. The cop with the lowest-score uncracked answer after 1 week wins!
2. Out of the tied cops, the one whose lowest-scored uncracked answer has the most upvotes wins
3. Out of the tied cops, the one whose lowest-scored most-upvoted uncracked answer was posted first wins
After 4 days, answers posted to this question will be non-competing (but can still be posted), to stop people posting answers just before the week is over and not giving robbers enough time to crack them.
If it has been four days since this was posted (Saturday 2nd April 2022, after whatever time this was posted in your time zone), please mark your answers as "non-competing" in the title.
Robbers can still crack cops' answers for the remaining 3 days and have those count towards their total; however, cracking non-competing cops' answers does not count towards their total.
Good luck!
[Answer]
# Python 3, score 24, [cracked by xnor](https://codegolf.stackexchange.com/a/245740/48931)
```
print((99,15))
```
* 5 characters removed
* Target output: `(6, 9)`
* Current output: `(99, 15)`
There's a lot of ways to get 6 but (hopefully) only one to get 5.
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 547 + 10 = 557 [Cracked by Kevin Cruijssen](https://codegolf.stackexchange.com/a/245742/52210)
```
import static java.util.stream.Collectors.joining;
import java.util.stream.IntStream;
class Program {
public static void main(String[] args) {
System.out.println(new Program());
}
String getName(int x) {
return x + " " + Integer.toHexString(x);
}
public String toString() {
return IntStream.of(130, 14, 8613, 8784, 150, 151).mapToObj(x -> {
String[] s = getName(x).split(" ");
int n = (x % 13) % 5;
return s[n % s.length];
}).collect(joining(" "));
}
}
```
[Try it online!](https://tio.run/##bZFNSwMxEIbv@ysGQUhoG1xqtVD04kUvKtRb6SHdxjVrNlmS2boi/e3r7Db9QieQhOSZd95JCrmRI1cpW6w/21aXlfMIASXqDAq6EzVqIwJ6JUvx4IxRGTofROG01TafJTHlD/tkcd7vZkmSGRkCvHqXe1nCTwIUVb0yVCOW2ji9hlJqyyiJdBdLkD4PPMJdzL8DqlK4GkVFCBrLrPraqzLOZz26TfplJwO5wmdZKkY8NKdqXmHtLTQwgAsaAyC/KldeoHtUzS6bNeea0XKURhepf2QPzQv3ztLx1RDS6yFMb9IxzbdT2qeT7nCSclHK6s29rArWwOj@ROrYBT1GgLtDLw0XoTIaGRmPBvfRtWkJJa1LSMec5sk5EQ2GhaW7IIyyOX4sj8yWi2z3yyx@cV/m8BDbtv0F "Java (OpenJDK 8) – Try It Online")
I've never done this before and I see my entry is way longer than others. If that's not appropriate let me know and I'll delete it. Of course, Java is infamously verbose. I could also give a hint about what part of my program the characters were deleted from.
* 10 characters removed
* Target output: `BREAK OUT FROM THE GUARDED AREA`
* Current output: `130 e 8613 8784 150 97`
So, can the robbers break out from the guarded area?
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), score = 19
A contiguous string of **seven bytes** was removed from **twelve**, leaving these **five**:
```
49“»V
```
Running this as a full program now outputs `0`, the output of the original program was:
```
Dyesters opposredoundse urosthenicupdrying@uniocular alkie Elgar ontic)0e eyednesses Kangarooed TPN harvestbug_| Enviability gilly ophiolaterDenebWorst horsRockierU Huey: Yelt aBA
```
**[Try it online!](https://tio.run/##y0rNyan8/9/E8lHDnEO7w/7/BwA "Jelly – Try It Online")**
I don't think this will be easy by any stretch of the imagination, but there are some clever people here who might just find one (of the ones?!) that work out of the \$4.3 \times 10^{17}\$ possible programs.
---
### Safe, so how did it work?
I guess this was just a little too much to crack, here's the original program:
>
>
> ```
> 49!’Æfj@⁾“»V - Link:
> 49 - fourty-nine -> 49
> ! - factorial 608281864034267560872252163321295376887552831379210240000000000
> ’ - subtract one 608281864034267560872252163321295376887552831379210239999999999
> Æf - prime decomposition [823,3739397,197653021455862028208110725148879567449727922627417829]
> ⁾“» - list of characters -> ['“', '»']
> @ - with swapped arguments:
> j - join ['“',823,3739397,197653021455862028208110725148879567449727922627417829,'»']
> V - evaluate “82337...829» as Jelly code
> (“...» is Jelly's dictionary-based compression)
>
> ```
>
>
>
>
[Answer]
# Perl 5, score 24, safe
```
print for a..z
```
* 5 characters removed
* Target output: `ABABABABABABABABABABABABAB`
* Current output: `abcdefghijklmnopqrstuvwxyz`
No interpreter flags or trickery involved, this is pure Perl.
## Solution
>
>
> ```
>
> print<\3>^B for a..z
>
> ```
>
>
>
>
>
> The code works as is, but replace `\3` with a literal `\3` character to get the claimed score of 5 characters removed.
>
>
>
[Answer]
# [R](https://www.r-project.org/), score 31, [cracked by Dominic van Essen](https://codegolf.stackexchange.com/a/245718/95126)
```
el(6)
```
[Try it online!](https://tio.run/##K/r/PzVHw0zz/38A "R – Try It Online")
* `13` characters removed
* Target output: `"Infant.Mortality"`
* Current output: `6`
Probably too easy for those familiar with [R](https://www.r-project.org/)...
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 2 + (2 \* 4) = 10, safe!
```
kj
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJraiIsIiIsIiJd)
One last one... Output should be `////\\///\\\//\\\////\\///\\\//\\\////\\///\\\//\\\\///\\///\\\//\\\\///\\///\\\//\\\////\\///\\\//\\\////\\///\\\//\\\////\\///\\\//\\\\///\\///\\\//\\\\///\\///\\\//\\\\///\\///\\\//\\\////\\///\\\//\\\////\\///\\\//\\\\///\\///\\\//\\\\///\\///\\\//\\\\`
>
>
> ```
> k/3(:j
> ```
>
> [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJrLzMoOmoiLCIiLCIiXQ==)
>
> Explanation:
>
> ```
> k/ # "/\"
> 3( # 3 times...
> :j # Join by itself
> ```
>
> Spoilers = pain
>
>
>
[Answer]
# [MATL](https://github.com/lmendo/MATL), score 20. [Cracked by Sanchises](https://codegolf.stackexchange.com/a/245856/36398)
```
'Hey My'
```
[Try it online!](https://tio.run/##y00syfn/X90jtVLBt1L9/38A)
* 6 characters removed.
* Target output: `Hey Hey My My` (displayed with line feed at the end).
* Current output: `Hey My` (displayed with line feed at the end).
[Answer]
## PHP, cracked by [dingledooper](https://codegolf.stackexchange.com/a/245892/88546)
* Score : **45**
* Removed 5 consecutive chars
* Current output is `38416064248`
* Expected output is `612510483624`
```
<?php for($i=7;$i-->2;)print$i<<$i;
```
**Edited** : *removed whitespaces and score was updated in consequence. Also assuming [short\_open\_tag](https://www.php.net/manual/en/ini.core.php#ini.short-open-tag) are disabled.*
[Answer]
# [R](https://www.r-project.org/), score 10 + 2×8 = 26, [cracked](https://codegolf.stackexchange.com/a/245752/86301) by Dominic van Essen
```
print("R")
```
[Try it online!](https://tio.run/##K/r/v6AoM69EQylISfP/fwA "R – Try It Online")
* 8 characters removed
* Current output: `[1] "R"`
* Target output: `[1] R`
I haven't done this in a while; I hope I didn't miss an obvious solution!
[Answer]
# [Python](https://www.python.org), score 36, [cracked by dingledooper](https://codegolf.stackexchange.com/a/245927)
```
"print("")"
print()
""
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhbblAqKMvNKNJSUNJW4IExNLiUliCRUDUwtAA)
Add 7 bytes, and output:
```
print()
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 13+23\*2=59, [Cracked](https://codegolf.stackexchange.com/a/245721/)
```
console.log()
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/OT@vOD8nVS8nP11D8/9/AA "JavaScript (Node.js) – Try It Online")
* Removed 23 characters
* Should output `39iw027a2hnuqi2c1os255jmjsidafs3nx6496n8vl8dak0qc3r15xwheq4vxpb136up7rsmbm8v5slowjwf7mvj0s751b03gxif5`
[Answer]
# C (C99, clang), 34 bytes removed + 666 bytes total = 700 score
[Try it online!](https://tio.run/##bZJfT4MwFMXf@RTXGZeWFjfAocnAhA3cfHASo449kg2QBEuzfz4Yv7p42YwlakJo7@@ec7htWBrLMhF5XZ8WYlnuVim4m@2qqM5frrU2WhciP7BVmhUiBWmCpQoLbFXYQKTJpEUVukDKpKnAABlrVC3moG@ApOW7RPpbdoW4De5n4fRpFjyEweP09uFxgTUGObo0dRyFQSvPbyZzXekoFPXBsQaoVASZHvVVjedBIm2qH922co8g6vn4Db8X/bAxifmCQsxittAXPzggc/5Msdss@pg887nKCckdn1G4YzOmDnZDYoqdmEtLj5V2go2AhGTEfcqJz0eUUq0QW3hNCkGo9q6Vlcjh8ErAg@Yevp@hlriuR@QV/btzmp3u/XObw0N6jlETlPS8fKhl1Zo0sEBoDnFxgeQ9EtmUQrcLyYnXR8pYM43EX2ebkc5ZWcYdfkMSSg8xzTgf2kddfy6zMsk3tTEXlbETu026MvZJuUuPBN1pnq6Nap@us7J6@wI "C (clang) – Try It Online")
```
#include <stdio.h>
#include <string.h>
#define p1 2
#define p2 3
#define p3 (p1+p2)
#define p4 p3+p1
#define p5 p4+p1+p1
#define p6 (p5+p1)
#define p7 p6+p1+p1
#define p8 p7+p1
#define ONEHUNDREDTHIRTYONE (p6*p1*p3 + 1)
#define A (p1<<p6)
#define P0 625*p3
#define P P0*P0
#define P3 (P0*p3)*(p1<<p3)
#define B P/A + A/P
#define C(X,Y) X+X+Y*Y
#define D(W,V) C(W,V)*C(V,W)
#define E(M,N) M+N+1
#define F(X) E(X,p2*X)
#define G F(D(E(B,A),(A,B)))
int main()
{
long long a = p1*p1*p1*p1;
a<<=(p8);
a<<=(p8);
a<<=(p6);
a*=ONEHUNDREDTHIRTYONE;
int g = G;
a/=g;
for(int i = 1; i < (g/(P3)) && a!=0; i++)
{
printf("%llX",F(a));
a/=p1;
}
}
```
Currently outputs `270F665E11387B32F19C3D99794E1ECCBD270F665D1387B32D9C3D9954E1ECC9270F6651387B319C3D994E1ECD270F651387B19C3D94E1ED270F5138799C3D4E1D270D13859C14E12711399D4D251195`
Should output `8300000001418000000120C0000001106000000183000000141800000120C000001106000001830000014180000120C00001106000018300001418000120C0001106000183000141800120C001106001830014180120C01106018301418120C1106183141920D105`
A lot of preprocessor trickery was used to set up the challenge which sadly makes it a little less competetive lengthwise.
Hint:
>
> In the intended solution there is no character from either [0-9] or [+,-] sets
>
>
>
[Answer]
# Python 3, 55 bytes + 3 removed = 58 score CRACKED
```
print("".join(chr(i)for i in b'wZSSP\x1fhPMS[\x1e'))
```
Currently outputs `wZSSPhPMS[` (Plus two unprintables SE markup hates, check [TIO link](https://tio.run/##K6gsycjPM/7/v6AoM69EQ0lJLys/M08jOaNII1MzLb9IIVMhM08hSb08Kjg4IKbCMC0jwDc4GshIVdfU/P8fAA))
Should output `Hello World!`
[Cracked by Sylvester Kruin](https://codegolf.stackexchange.com/a/245708/111305)
[Answer]
# [Lexurgy](https://www.lexurgy.com/sc), Cracked by [Jonathan Allan](https://codegolf.stackexchange.com/a/245709/77309)
# \$7 + 2\times 32=71\$ score
```
a:
*=>w
```
* Characters removed: 32
* Target: `zwq`
* Current: `w`
Original code:
```
a:
*=>aaa
b:
a=>z/$ _
a=>q/_ $
a=>w
```
[Answer]
# [Python](https://www.python.org), 125 + 34 removed = 159 [Cracked](https://codegolf.stackexchange.com/a/245731/110555)
```
import sys
S=sys.stdout
sys.stdout=type('',(),{'write':lambda x,y:'','flush':lambda z:1})()
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3ozNzC_KLShSKK4u5gm2BpF5xSUp-aQkXgmlbUlmQqqGurqOhqVOtXl6UWZKqbpWTmJuUkqhQoVNpBZRRT8spLc6Ai1ZZGdZqamhCrIDaBLMRAA)
Not competitive compared to current Python answers, but I imagine people will find the answer *Pythonic*
Target output:
```
Gur Mra bs Clguba, ol Gvz Crgref
Ornhgvshy vf orggre guna htyl.
Rkcyvpvg vf orggre guna vzcyvpvg.
```
Current output: None
[Answer]
# [Python 3](https://docs.python.org/3/), 23 chars with 4 chars removed = score 27 [CRACKED](https://codegolf.stackexchange.com/a/245768/111305)
```
print(str()[14:18])
```
Currently outputs nothing, should output `Ctrl`
[Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69Eo7ikSEMz2tDEytAiVvP/fwA)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 3 + (2 \* 2) = 7, [Cracked](https://codegolf.stackexchange.com/questions/245702/whats-the-missing-code-robbers/245759#245759) by Jonathan Allan.
```
kay
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJrYXkiLCIiLCIiXQ==)
Should output `acegikmoqsuwy]`. Bonus challenge: `cegikmoqsuwya`.
[Answer]
# [R](https://www.r-project.org/), score 14 + 2×8 = 30, [cracked](https://codegolf.stackexchange.com/a/245830/86301) by Dominic van Essen
```
`?`=print
?"R"
```
[Try it online!](https://tio.run/##K/r/P8E@wbagKDOvhMteKUjp/38A "R – Try It Online")
* 8 characters removed
* Current output: `[1] "R"`
* Target output: `[1] R`
This is my second attempt, after Dominic van Essen found an unintended crack to my [first attempt](https://codegolf.stackexchange.com/a/245750/86301). I hope this one is more robust!
[Answer]
# [R](https://www.r-project.org/), score 24 + 2×8 = 40, [cracked](https://codegolf.stackexchange.com/a/245859/86301) by Dominic van Essen
```
{assign("?",print)}
?"R"
```
[Try it online!](https://tio.run/##K/r/vzqxuDgzPU9DyV5Jp6AoM69Es5bLXilI6f9/AA "R – Try It Online")
* 8 characters removed
* Current output: `[1] "R"`
* Target output: `[1] R`
This is my third and probably last attempt, after Dominic van Essen found an unintended crack to my [first attempt](https://codegolf.stackexchange.com/a/245750/86301) and then to my [second attempt](https://codegolf.stackexchange.com/a/245822/86301). I hope this one is more robust!
[Answer]
# PHP all versions 64 bits, cracked by [dingledooper](https://codegolf.stackexchange.com/a/245891/88546)
* Score : **50**
* Removed : 12 consecutive ascii chars
* Current all PHP versions (64 bits) output : `/* Nothing */`
* Expected all PHP versions (64 bits) output : `687755285922905`
```
<?php echo '';
```
**Info** : The solution may generate a deprecation notice and has possibly no digit.
[Answer]
# [Rust](https://www.rust-lang.org), \$ 26 + (2 \times 12) = 50\$
```
fn main(){print!("{}",81)}
```
[Try it online!](https://tio.run/##KyotLvn/Py1PITcxM09Ds7qgKDOvRFFDqbpWScfCULP2/38A "Rust – Try It Online")
* Characters removed: 12
* Expected output: `0.057987041728136374`
* Currently outputs: `81`
I'm putting the solution here, partly so that I don't forget later ;-), but even though the challenge is over, I encourage you to try to figure it out!
If you *really* want to know the solution, here it is:
>
> `fn main(){print!("{}",8f64.exp()%0.1)}`
>
>
> (added `f64.exp()%0.` between the `8` and the `1`)
>
>
>
>
> The `f64` converts the `8` to a float, and `.exp()`
> [returns `e^(self)` (the exponential function)](https://doc.rust-lang.org/std/primitive.f64.html#method.exp).
>
>
>
>
> Then, the `%0.1` [returns the remainder](https://doc.rust-lang.org/std/ops/trait.Rem.html) from dividing `8f64.exp()` by `0.1`. The resulting number is `0.057987041728136374`.
>
>
>
>
> [Try it online!](https://tio.run/##KyotLvn/Py1PITcxM09Ds7qgKDOvRFFDqbpWSccizcxEL7WiQENT1UDPULP2/38A "Rust – Try It Online")
>
>
>
[Answer]
# [MATL](https://github.com/lmendo/MATL), 11 + 14 = 25 (safe)
```
'tacocat'0y
```
[Try it online!](https://tio.run/##y00syfn/X70kMTk/ObFE3aDy/38A "MATL – Try It Online")
Current output:
```
tacocat
0
tacocat
```
Desired output, adding 7 bytes:
```
taataccocaccoaaat
```
---
## Intended solution
```
'tacocat'0y"@Yfh])
```
[Try it online!](https://tio.run/##y00syfn/X70kMTk/ObFE3aBSySEyLSNW8/9/AA "MATL – Try It Online")
Forgot about this challenge for a while. Explanation:
```
'tacocat' % Push the string 'tacocat'
y" ] % Loop over copy of this string
@Yf % Calculate prime factors of each ASCII code point
0 h % Concatenate factors, with initial zero
) % Index (modularly) into the original string. Implicit display.
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 3 + (11 \* 2) = 25
```
`İy
```
Currently outputs `</li>y`, should output `d xdirf irrwst.mreo3//h.s-ksxdiry`.
A necessary spoiler: This works on MacOS and probably only there, on the offline Vyxal interpreter.
[Answer]
# [Python 3](https://docs.python.org/3/), 20 bytes + 3 removed = 23, [Cracked by des54321](https://codegolf.stackexchange.com/questions/245702/whats-the-missing-code-robbers/245726#245726)
```
print(str()[1:3]*50)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69Eo7ikSEMz2tDKOFbL1EDz/38A "Python 3 – Try It Online")
Currently prints an empty string. Should print 100 lowercase L's like so:
`llllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll`
[Answer]
# [StackCell](https://esolangs.org/wiki/StackCell), 8 + (11 \* 2) = 30 [non-competing, safe]
`"?":[;:]`
Current output: `?`
Correct output: `StackCell`
This should be pretty easy
Solution:
>
> **`"lleCkcatS` [null]** `"?":[;:]`
>
>
>
Explanation:
>
> The first `"` enters string mode.
>
>
>
>
> The bytes 108, 108, 101, 67, 107, 99, 97, 116, 83, and 0 are pushed, in turn (the string `\0Stackcell`, in reverse).
>
>
>
>
> The second `"` exits string mode.
>
>
>
>
> The `?` pops the top element (0) from the stack, and skips the next instruction (`"`)
>
>
>
>
> Then `:[;:]` prints the contents of the stack.
>
> `:` duplicates the top element of the stack to prevent the `[`/`]` from consuming the original, `[`/`]` form a loop as long as the stack contains a non-null item, and `;` pops and prints the top item of the stack as a character
>
>
>
[Answer]
# [Behaviour](https://esolangs.org/wiki/Behaviour), score = 16 + 2 = 18, [cracked](https://codegolf.stackexchange.com/a/245869) by Makonede
```
@(type:type)-0
```
just use a language that nobody knows amiright ;)
* 2 characters removed
* current output: `func`
* desired output: `fun`
hint:
>
> `type` is an embeded function that returns the type of a variable. Using `type` on `type` results in `"cfunc"`
>
>
>
The rest of the technics used are on the [docs](https://github.com/FabricioLince/BehaviourEsolang#readme).
I could have made it smaller but the allure of having the output be `fun` was too great.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 35+23\*2=81 bytes, [safe](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/OT@vOD8nVS8nP10jWk9Pz7GoKLFSwzDVWFMvO7WyWEMzVq84v6hEI8k20dYuyTZJy9DC0Mi8xlBT8/9/AA)
23 hidden chars
```
console.log([...Array(1e3).keys()])
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/OT@vOD8nVS8nP10jWk9Pz7GoKLFSwzDVWFMvO7WyWEMzVvP/fwA "JavaScript (Node.js) – Try It Online")
Current output:
```
[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,280,281,282,283,284,285,286,287,288,289,290,291,292,293,294,295,296,297,298,299,300,301,302,303,304,305,306,307,308,309,310,311,312,313,314,315,316,317,318,319,320,321,322,323,324,325,326,327,328,329,330,331,332,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,362,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,378,379,380,381,382,383,384,385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426,427,428,429,430,431,432,433,434,435,436,437,438,439,440,441,442,443,444,445,446,447,448,449,450,451,452,453,454,455,456,457,458,459,460,461,462,463,464,465,466,467,468,469,470,471,472,473,474,475,476,477,478,479,480,481,482,483,484,485,486,487,488,489,490,491,492,493,494,495,496,497,498,499,500,501,502,503,504,505,506,507,508,509,510,511,512,513,514,515,516,517,518,519,520,521,522,523,524,525,526,527,528,529,530,531,532,533,534,535,536,537,538,539,540,541,542,543,544,545,546,547,548,549,550,551,552,553,554,555,556,557,558,559,560,561,562,563,564,565,566,567,568,569,570,571,572,573,574,575,576,577,578,579,580,581,582,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,611,612,613,614,615,616,617,618,619,620,621,622,623,624,625,626,627,628,629,630,631,632,633,634,635,636,637,638,639,640,641,642,643,644,645,646,647,648,649,650,651,652,653,654,655,656,657,658,659,660,661,662,663,664,665,666,667,668,669,670,671,672,673,674,675,676,677,678,679,680,681,682,683,684,685,686,687,688,689,690,691,692,693,694,695,696,697,698,699,700,701,702,703,704,705,706,707,708,709,710,711,712,713,714,715,716,717,718,719,720,721,722,723,724,725,726,727,728,729,730,731,732,733,734,735,736,737,738,739,740,741,742,743,744,745,746,747,748,749,750,751,752,753,754,755,756,757,758,759,760,761,762,763,764,765,766,767,768,769,770,771,772,773,774,775,776,777,778,779,780,781,782,783,784,785,786,787,788,789,790,791,792,793,794,795,796,797,798,799,800,801,802,803,804,805,806,807,808,809,810,811,812,813,814,815,816,817,818,819,820,821,822,823,824,825,826,827,828,829,830,831,832,833,834,835,836,837,838,839,840,841,842,843,844,845,846,847,848,849,850,851,852,853,854,855,856,857,858,859,860,861,862,863,864,865,866,867,868,869,870,871,872,873,874,875,876,877,878,879,880,881,882,883,884,885,886,887,888,889,890,891,892,893,894,895,896,897,898,899,900,901,902,903,904,905,906,907,908,909,910,911,912,913,914,915,916,917,918,919,920,921,922,923,924,925,926,927,928,929,930,931,932,933,934,935,936,937,938,939,940,941,942,943,944,945,946,947,948,949,950,951,952,953,954,955,956,957,958,959,960,961,962,963,964,965,966,967,968,969,970,971,972,973,974,975,976,977,978,979,980,981,982,983,984,985,986,987,988,989,990,991,992,993,994,995,996,997,998,999]
```
Expected output:
```
[597,123,155,320,156,214,277,194,228,314,42,93,490,67,0,10,441,478,95,99,500,819,15,787,217,815,769,870,476,794,883,907,914,882,916,895,56,887,38,929,934,261,502,248,935,910,467,452,117,572,942,318,347,504,933,635,468,4,621,175,943,674,688,495,888,927,539,413,133,491,187,475,238,754,605,903,742,75,132,96,902,564,163,941,718,596,890,267,400,341,892,728,894,932,535,429,497,921,52,901,33,415,573,19,457,571,659,308,219,264,554,904,378,310,944,394,523,937,908,695,295,136,983,335,143,950,29,897,379,755,968,770,667,297,624,849,842,877,131,130,396,276,594,486,313,565,545,292,380,83,446,484,881,1,256,434,579,372,47,867,797,406,663,966,555,337,66,699,612,119,820,339,342,763,327,807,580,338,220,780,712,330,984,111,913,196,86,311,602,885,824,680,986,557,87,366,442,975,305,506,924,801,221,167,766,930,100,345,684,515,186,302,343,437,730,939,837,765,630,714,611,449,844,758,869,456,39,459,779,733,122,538,460,543,43,878,958,511,383,138,21,312,551,465,254,756,225,548,647,291,293,14,537,393,31,711,114,987,544,852,533,542,768,514,762,397,598,41,408,286,859,333,928,25,374,363,931,418,751,20,124,303,309,948,492,990,868,646,607,862,481,62,344,633,436,956,681,458,772,61,377,202,55,296,271,631,477,721,268,298,142,325,208,180,529,677,190,280,781,431,886,283,599,185,113,876,184,110,84,282,899,76,782,218,864,118,97,144,370,583,284,922,788,289,32,435,235,140,813,11,160,736,253,584,851,559,826,995,588,251,274,546,422,321,692,189,989,628,810,561,216,988,399,148,73,562,211,13,115,725,696,510,785,812,920,536,381,51,911,255,776,450,239,915,655,30,480,805,165,432,193,106,44,272,629,675,616,236,591,918,980,362,455,17,592,290,371,620,60,483,553,149,800,203,428,709,369,893,773,353,811,961,151,367,58,570,840,340,37,328,161,258,505,532,257,525,294,331,299,550,376,8,209,301,761,171,834,909,121,134,375,959,790,359,317,461,789,463,720,723,964,80,777,905,153,414,508,563,199,830,642,448,618,275,26,823,509,795,757,923,182,49,940,556,2,786,835,803,614,260,919,706,679,796,731,306,648,816,582,57,619,191,994,898,125,92,552,601,753,750,304,802,445,657,729,472,300,970,658,22,398,698,936,90,494,68,145,585,604,129,213,12,694,569,352,307,24,671,722,77,799,273,334,744,285,856,141,517,660,644,227,953,818,74,355,558,322,735,575,18,855,205,263,783,798,732,985,108,395,262,451,792,332,889,833,632,474,973,78,288,825,420,139,498,28,603,440,454,178,704,952,405,891,315,192,357,252,79,316,710,863,45,884,996,516,865,319,896,577,210,560,419,587,323,512,411,900,998,198,748,387,649,668,389,269,945,482,425,822,767,101,181,201,368,473,278,27,669,625,578,600,521,946,724,259,234,574,697,775,734,444,102,403,6,373,154,287,741,738,224,265,195,715,808,326,229,726,846,906,827,183,917,639,120,809,595,222,164,829,279,925,266,7,957,392,626,350,240,866,926,382,72,103,549,232,610,976,507,962,804,447,739,687,513,427,568,764,5,832,845,636,982,576,270,749,850,112,135,360,617,716,147,493,471,609,547,615,105,912,168,737,204,960,527,65,430,281,94,173,88,197,817,401,947,606,622,705,623,991,365,70,346,747,608,955,385,821,645,713,530,760,349,354,967,979,82,409,107,848,324,954,329,567,981,470,627,23,519,412,89,485,656,814,59,358,828,351,439,336,35,16,871,853,831,793,581,104,589,526,361,693,176,685,963,839,858,969,464,593,771,40,703,791,348,745,664,977,364,743,759,503,949,854,701,64,541,206,752,179,700,50,740,690,683,689,433,774,391,386,860,972,34,666,638,177,691,843,158,230,661,416,384,53,872,613,993,438,453,63,407,673,522,586,978,424,650,479,590,85,443,116,421,54,717,528,404,152,388,69,524,971,540,651,3,965,518,231,951,874,157,237,207,520,71,784,634,499,534,778,999,841,247,137,170,172,466,708,566,98,838,719,880,702,857,91,682,496,727,672,487,423,410,806,469,662,390,402,417,81,489,128,426,462,250,501,215,169,9,36,245,46,243,109,127,233,166,146,223,686,707,992,641,670,126,746,241,997,678,242,847,188,162,249,653,150,836,200,654,212,244,938,879,159,640,637,643,861,873,226,875,531,174,665,48,246,974,676,488,356,652]
```
>
> Notice that the output is an rearrangement and try `sort`, then there's not large space to test
>
>
>
[Answer]
# C (gcc), 59 bytes + 17 removed = 76 score
```
n=999;main(){for(;printf("%d",n),n*=.9;);}
```
Currently outputs `99989980972865558953047742938634731228025222620318216314613111710594847567605448433834302724211816141210987654321`
Should output `997002512520100`
] |
[Question]
[
Convert a string containing digits as words into an integer, ignoring leading zeros.
# Examples
* `"four two"` -> `42`.
* `"zero zero zero one"` -> `1`.
# Assumptions
Submissions can assume that:
1. The input string is comprised of space-separated digit words.
2. All words are valid (in the range "zero".."nine") and lowercase. Behaviour for empty input is undefined.
3. The input string always represents an unsigned number within the range of `int` and is never an empty string.
# Scoring
Answers will be scored in bytes with fewer bytes being better.
[Answer]
# [PHP](https://php.net/), 74 bytes
```
foreach(explode(' ',$argn)as$w)$n.='793251_8640'[crc32($w)%20%11];echo+$n;
```
[Try it online!](https://tio.run/##RY1LCsIwFAD3PUUoKUnwQz9@ieLOS6hISJ9GkPdCklLx8Na6cjMMzGK888Pu4EfeKICxTsLLP6kFKZiYchPuqEzkveI434v1tqmX1XWzWpTiZINtajmmoi6LqrposI4mHPXwE5afMddZhxGS5Kj0OOgCSz1lbwjE/iCED/n0IIzD7PgF "PHP – Try It Online")
Tried to get a solution which doesn't copy existing answers. I get cyclic redundancy checksum polynomial of 32-bit lengths ([crc32](https://www.php.net/manual/en/function.crc32.php)) for each word and then do a mod 20 and mod 11 on it to get mixed up unique values from 0 to 10 (missing 6) for each digit. Then using that unique value I find the actual digit.
```
| Word | CRC32 | %20 | %11 | Equivalent digit |
|-------|------------|-----|-----|------------------|
| zero | 2883514770 | 10 | 10 | 0 |
| one | 2053932785 | 5 | 5 | 1 |
| two | 298486374 | 14 | 3 | 2 |
| three | 1187371253 | 13 | 2 | 3 |
| four | 2428593789 | 9 | 9 | 4 |
| five | 1018350795 | 15 | 4 | 5 |
| six | 1125590779 | 19 | 8 | 6 |
| seven | 2522131820 | 0 | 0 | 7 |
| eight | 1711947398 | 18 | 7 | 8 |
| nine | 2065529981 | 1 | 1 | 9 |
```
Another 74 bytes CRC32 alternative using `%493%10`: [Try it online!](https://tio.run/##RcxLC4JAFAXgvb/iIiMqPdC0h1i0609UC7GrMxD3DjPjg358pqs2HwfO4Wipp/NVzzZssKplhKN@8wujEMK1qExLcWXFEAvaXsL8dMwO@2KXpOG9NnW2i@YmyIssSJNnibXklaByWgL4D/JLryOLLhIUlxMTghsYnDSI0HBnoFE9glUjWOyRAFUrHZCahx807C3An/ngy9opJjttbj8 "PHP – Try It Online")
Another 74 bytes CRC32 alternative using `%2326%11`: [Try it online!](https://tio.run/##RczdCoJAEAXge59ikBWVfkgtKyy66yUqQmx0F2Jm2V1/6OEzverm48A5HC31eLroyZoNlpWMcNBvfmEUQrgUpWkoLq3oY0Hr8zPJjoftLt9v0ltlqiyNpiJIszQPkuRRYCV5IagY5wD@nfzCa8miiwTFxciE4HoGJw0i1NwaqFWHYNUAFjskQNVIB6Sm4QcNezPwZzr4snaKyY6r6w8 "PHP – Try It Online")
---
# [PHP](https://php.net/), 74 bytes
```
foreach(explode(' ',$argn)as$w)$n.=strpos(d07bfe386c,md5($w)[21]);echo+$n;
```
[Try it online!](https://tio.run/##RY1LCsIwFAD3PUUogSZYxQ9VIYo7L6EuYvJqBH0vJCkVD2@MKzfDwCzGO593B1/YUwBtnICXf5AF0bCm5TrcUOrIR8lxto8peIrCzjfXHlbbtWmfthMlnpaLi1RgHE04qvwTVp@xVtWAEZLgKFUZDIGlkao3BGJ/EMKHfLoTxjw9fgE "PHP – Try It Online")
Another alternative with same length, takes 22nd character in the `md5` of the word (only character which gives a unique value for each word) and then uses that character to map to a digit.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~71~~ 70 bytes
-1 thanks to [ovs](https://codegolf.stackexchange.com/users/64121) (use `find` in place of `index`)
```
lambda s:int(''.join(`'rothuvsein'.find((w*3)[6])`for w in s.split()))
```
**[Try it online!](https://tio.run/##FYtBDgIhDAC/0hvggYMmHkx8iZrsmi1Ss7YEuqB@HvE2mcykj0bhfQ/na1/n132ZoZyI1Rrjn0JsJ5NF41YLEhsfiBdr2@7gLsebm4JkaEAMxZe0klrnXE95/BAscdr@pptAFUGbQMGKI6Y3aMyIEGTLIIyA9IgKTAO/mMX8AA "Python 2 – Try It Online")**
[Answer]
# JavaScript (ES6), ~~70 67 66~~ 62 bytes
*Saved 3 bytes thanks to @ovs*
```
s=>+s.replace(/\w+ ?/g,s=>'2839016547'[parseInt(s,36)%204%13])
```
[Try it online!](https://tio.run/##bY29DoIwFEZ3n@IupG1A/kUd0NlnUIcGb6GGtKStYHz5inEwIS7fcHLynTsfuW2MHNxa6Rt6UXtbH0IbGxx63iBNLlMIx6SNZkzyXbFPs2pTbsl54MbiSTlqo6JiQZ6WQVZcmW@0srrHuNctFZQI/TDgJg1aIbzQaMLYauF8MPxmNv9ISs4HKNvOgcURFVj5BCFHhG@iM4jLkH8D "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~19~~ 17 bytes
```
Ḳµ7ị“*;nÄƲ]³Ṙ»i)Ḍ
```
A monadic Link accepting a list of characters which yields an integer.
**[Try it online!](https://tio.run/##AVsApP9qZWxsef//4biywrU34buL4oCcKjtuw4TGsl3Cs@G5mMK7aSnhuIz///9maXZlIHR3byBzZXZlbiBzaXggdGhyZWUgZm91ciBvbmUgZWlnaHQgbmluZSB6ZXJv "Jelly – Try It Online")**
Pretty much a port of my Python 2 answer.
---
Previous
```
ḲŒ¿€i@€“©¥q£½¤MÆÑ‘Ḍ
```
[Try it online!](https://tio.run/##y0rNyan8///hjk1HJx3a/6hpTaYDkHjUMOfQykNLCw8tPrT30BLfw22HJz5qmPFwR8/////TMstSFUrK8xWKU8tS8xSKMysUSjKKUlMV0vJLixTy81IVUjPTM0oU8jKBzKrUonwA "Jelly – Try It Online")
There is ~~quite possibly~~ a shorter way, but this is a way that first came to mind.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~35~~ 32 bytes
```
{+uniparse 'SP'~S:g/<</,DIGIT /}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Wrs0L7Mgsag4VUE9OEC9LtgqXd/GRl/HxdPdM0RBv/a/NVdxYqWCHlBxWn6RQk5mXmrx/7T80iKFkvJ8rqrUonwFMJGflwoA "Perl 6 – Try It Online")
### Explanation
```
{ } # Anonymous block
S:g/<</,DIGIT / # Insert ",DIGIT " at
# left word boundaries
'SP'~ # Prepend 'SP' for space
uniparse # Parse list of Unicode names into string
+ # Convert to integer
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~18~~ 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
#ε6è}.•ƒ/ÿßÇf•Åβ
```
[Try it online.](https://tio.run/##yy9OTMpM/f9f@dxWs8MravUeNSw6Nkn/8P7D8w@3pwE5h1vPbfr/vyq1KF@hJKMoNVWhOLNCoaQ8X6E4tSw1TyE1Mz2jRCEvMy9VIR@IIUrSMsuARH5pEVgMiAE)
**Explanation:**
```
# # Split the (implicit) input-string on spaces
ε } # Map each string to:
6è # Get the character at 0-based index 6 (with automatic wraparound)
.•ƒ/ÿßÇf• # Push compressed string "rothuvsein"
Åβ # Convert the characters from custom base-"rothuvsein" to an integer
# (after which the top of the stack is output implicitly as result)
```
[See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `.•ƒ/ÿßÇf•` is `"rothuvsein"`.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 89 bytes
```
i,n;f(char*w){for(i=n=0;n=*w%32?n^*w:(i+=n-2)&&!printf(L"8 0 72 3 59641"+n%17),*w++;);}
```
[Try it online!](https://tio.run/##TYrLCoJAFED3fsVtQJnxAT4qq2HoB/qGQGRG76JrjOZE4rdblIs2h8Ph1ElT18uCMUnD67ayoROT6SxHRSqVpELnF/mZrqE7cYwUJbkIgs3dIg2GX9gBUoAyhwJgd9xvMxaRn5UiDl0USSHn5fPBrUICLibPM5y9tO3gi470Twa3lqG1em1fmO5hweCooccn9HrUBBqbdgBC@huZkJ43L28 "C (gcc) – Try It Online")
Thanks to @Ceilingcat smartest tricks :
```
- printf instead of putchar.
- !printf instead of printf()&0.
- And wide char !
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~107~~, ~~91~~, ~~77~~, ~~90~~, 74 bytes
-16 bytes by Sriotchilism O'Zaic
+13 bytes to remove leading zeroes
-16 bytes using `find` and a more clever indexing, but now it's basically a rip-off of the [Python 2 version](https://codegolf.stackexchange.com/a/193364/)...
```
lambda s:int(''.join(str('rothuvsein'.find((w*3)[6]))for w in s.split()))
```
[Try it online!](https://tio.run/##ZY/BDoIwDIbvPEVv3QzhQuKBxCdBDhg6qcGOrAPUl58Ojl7a9MvXv@n8jqOXOrnLNU398zb0oA1LNIjVw7MYjcFg8HFcViUWrBzLYMx2qm177qx1PsAGLKCVzhNHY60tUqaaaYsfCh5LQC@UWx5hL39gN6FE55cAcdu3hIWA@D5GUFrpd4Zf4HglOKwxEGU3px0BXVPAHPILzqi16Qs "Python 3 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~17~~ 16 bytes
```
•D±¾©xWÄ0•I#HèTβ
```
[Try it online!](https://tio.run/##yy9OTMpM/f//UcMil0MbD@07tLIi/HCLAZDrqexxeEXIuU3//1elFuUr5OelKpSU5yuUZBSlpiqk5ZcWKaRllqUqFGdWKBSnlqXmKaRmpmeUKORl5qUCAA "05AB1E – Try It Online")
Perfect tie with [the other 05AB1E answer](https://codegolf.stackexchange.com/questions/193357/convert-a-string-of-digits-from-words-to-an-integer/193395#193395), but using a completely different approach.
```
•D±¾©xWÄ0• # compressed integer 960027003010580400
I# # split the input on spaces
H # convert each word from hex (eg "one" => 6526)
è # index (with wrap-around) into the digits of the large integer
Tβ # convert from base 10 to integer
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~46~~ 45 bytes
```
\w+
¶$&$&$&
%7=T`r\ot\huvs\ein`d`.
\D
^0+\B
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wP6Zcm@vQNhU1EORSNbcNSSiKyS@JySgtK45JzcxLSEnQ44px4eKKM9COceL6/z8tv7RIoaQ8n6sqtShfAUHk56Vy5WXmpSqkZqZnlCgUp5al5ikUZ1YopGWWpSpAdGUUpaaC9IIUg3UBAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
\w+
¶$&$&$&
```
Put each word on its own line and triplicate it.
```
%7=T`r\ot\huvs\ein`d`.
```
Transliterate the 7th character of each line using @UnrelatedString's string.
```
\D
```
Delete all remaining non-digit characters.
```
^0+\B
```
Delete leading zeros (but leave at least one digit).
Previous 46-byte more traditional solution:
```
T`z\wuxg`E
on
1
th
3
fi
5
se
7
ni
9
\D
^0+\B
```
[Try it online!](https://tio.run/##Rcs9CgIxFEXh/q7iNYJgo4iIrShuYMogsbiZvOYFkswPs/noaGFzqvNlVrVX22wfvnV@cdMw9/6OZDigRhwRFCcU4gxTXOBuwHO/c1e0FtKQpU4JC3OSf5LxMxuF2scqhSNNis4SdKT8VMzkatf5q94 "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
T`z\wuxg`E
```
The words `zero`, `two`, `four`, `six` and `eight` uniquely contain the letters `zwuxg`. Transliterate those to the even digits.
```
on
1
th
3
fi
5
se
7
ni
9
```
For the odd digits, just match the first two letters of each word individually.
```
\D
```
Delete all remaining non-digit characters.
```
^0+\B
```
Delete leading zeros (but leave at least one digit).
[Answer]
# x86 machine code, 46 bytes
Hexdump:
```
57 53 33 c0 33 ff f6 01 0f 75 15 6a 0a 5b 99 f7
f3 6b ff 0a 03 fa 33 c0 38 01 75 0f 97 5b 5f c3
69 c0 26 2b aa 6e 32 01 c1 e8 02 41 eb d8
```
It's a `fastcall` function - receives a pointer to the string in `ecx`, and returns the result in `eax`.
The hashing function multiplies by a magic number `1856645926`, does a `XOR` with input byte, and shifts right by 2 bits.
Saving and restoring noclobber registers (`edi` and `ebx`) took 4 bytes, but I didn't find a more efficient way to implement this. Storing the constant 10 in `ebx` was particularly annoying!
Disassembly with corresponding code bytes:
```
57 push edi ; edi = result
53 push ebx ; we use ebx to store the constant 10
33 C0 xor eax,eax
33 FF xor edi,edi
myloop:
F6 01 0F test byte ptr [ecx],0Fh ; check for end of word
75 15 jne myhash
6A 0A push 0Ah
5B pop ebx
99 cdq ; prepare 64-bit dividend in edx:eax
F7 F3 div eax,ebx ; find the remainder of division by 10
6B FF 0A imul edi,edi,0Ah
03 FA add edi,edx ; update the result
33 C0 xor eax,eax ; reset the hash temporary variable
38 01 cmp byte ptr [ecx],al ; check for end of input (here al=0)
75 0F jne mycontinue
97 xchg eax,edi ; set the return register
5B pop ebx ; restore registers
5F pop edi ; restore registers
C3 ret
myhash:
69 C0 26 2B AA 6E imul eax,eax,6EAA2B26h ; hashing...
32 01 xor al,byte ptr [ecx] ; hashing...
C1 E8 02 shr eax,2 ; hashing...
mycontinue:
41 inc ecx ; next input byte
EB D8 jmp myloop
```
Equivalent C code:
```
int doit(const char* s)
{
int result = 0;
unsigned temp = 0;
while (true)
{
int c = *s++;
if ((c & 15) == 0)
{
temp %= 10;
result = result * 10 + temp;
temp = 0;
if (c == 0)
break;
else
continue;
}
temp *= 1856645926;
temp ^= c;
temp >>= 2;
}
return result;
}
```
[Answer]
# ARM Thumb-2 (manual `rothuvsein`, no div, no libc) 70 bytes
Machine code:
```
b5f0 2100 2420 f000 f816 0032 18c5 3b03
bf18 f1c3 0303 5cc4 a004 f000 f80c 240a
fb01 3104 1c68 2a00 d1ec bdf0 6f72 6874
7675 6573 6e69 f07f 0300 1c5b 5cc6 b10e
42a6 d1fa 4770
```
Assembly:
```
.syntax unified
.arch armv6t2
.thumb
.globl _strtoint
.thumb_func
_strtoint:
push {r4-r7, lr}
movs r1, #0
.Lstrtoint_loop:
movs r4, #' '
bl _strfind
movs r2, r6
adds r5, r0, r3
subs r3, #3
it ne
rsbne r3, #3
ldrb r4, [r0, r3]
adr r0, .Lrothuvsein
bl _strfind
movs r4, #10
mla r1, r1, r4, r3
adds r0, r5, #1
cmp r2, #0
bne .Lstrtoint_loop
.Lstrtoint_loop_end:
pop {r4-r7, pc}
@ naturally 4-byte aligned
@ note: this is not null terminated - we blindly assume a match
.Lrothuvsein:
.ascii "rothuvsein"
@ naturally 2-byte aligned
.thumb_func
_strfind:
movs r3, #-1
.Lstrfind_loop:
adds r3, r3, #1
ldrb r6, [r0, r3]
cbz r6, .Lstrfind_loop_end
cmp r6, r4
bne .Lstrfind_loop
.Lstrfind_loop_end:
bx lr
```
### Explanation
Yet another port of the `rothuvsein` method, but this seems to be the first one in assembly. It is also done manually without the support of libc or fancy useless CISC instructions like `repne scasb`. Just plain, barebones RISC. That means that it is longer than other assembly languages.
Unlike my previous entries, I am a little more flexible with the calling convention.
While the input string (null terminated) is in `r0` just like it would be in C, the output is a 32-bit integer in `r1` instead of the traditional `r0`.
It can still be wrapped in C like so, since `r1` is still used for 64-bit integers:
```
extern uint64_t _strtoint(const char *str);
uint32_t strtoint(const char *str)
{
return (uint32_t)(_strtoint(str) >> 32);
}
```
Regardless of whether I care about the calling convention, I am going to have to do something with the link register so I can call my subroutine, so might as well `push` the callee-saved registers and remain mostly in line with the calling convention.
```
.globl _strtoint
.thumb_func
_strtoint:
push {r4-r7, lr}
```
Initialize our accumulator/output variable to 0.
```
movs r1, #0
```
Call our internal subroutine to find the end of the word.
`r3` will have the length of the word, and `r6` will have the last byte read. I will explain `_strfind` later.
```
.Lstrtoint_loop:
movs r4, #' '
bl _strfind
```
We save a copy of the last byte read for later to tell if we reached the null terminator.
```
movs r2, r6
```
Put the pointer to the string (advanced to the space) in `r5`.
```
adds r5, r0, r3
```
Here is the trickiest part: **One does not simply `str+str+str` in assembly.** We need to find the index.
Specifically, if we plot it out:
```
oneoneone
^
fourfourfour
^
sevensevenseven
^
```
We can turn it into this:
```
switch (strlen(str)) {
case 3: return str[0];
case 4: return str[2];
case 5: return str[1];
}
```
It can be done as `6 % strlen(str)`, but that is division. I can do better.
I could do a lookup table, but there is a better solution than that:
Remember that `r3` is essentially `strlen(str)`.
We can do this:
```
subs r3, #3
it ne
rsbne r3, #3 @ note: rsb = Reverse SuBtract
```
The equivalent C:
```
if ((len -= 3) != 0)
{
len = 3 - len;
}
```
This works perfectly:
```
3 - 3 = 0
3 - (4 - 3) = 2
3 - (5 - 3) = 1
```
Now, we load the byte from the string at our offset...
```
ldrb r4, [r0, r3]
```
...then call `_strfind` with the `rothuvsein` lookup table to find it.
```
adr r0, .Lrothuvsein
bl _strfind
```
Now, we add the length to our accumulator times 10;
```
movs r4, #10
mla r1, r1, r4, r3 @ r1 = r1 * 10 + len
```
Take the copy of the string we made in `r5`, advance it past the space, and put it in `r0` for the next iteration.
```
adds r0, r5, #1
```
Then, loop if we are not at a null terminator:
```
cmp r2, #0
bne .Lstrtoint_loop
```
Finally, return in `r1` by popping the link register holding the return address into the program counter (along with restoring the other registers I saved).
```
.Lstrtoint_loop_end:
pop {r4-r7, pc}
```
\_strfind subroutine
`_strfind` is the real workhorse here.
C users will find it similar to `strcspn` or `strchr`.
It is called with the null terminated string to search in `r0` and the byte to find in `r4`.
It will return the index of the match (or null terminator) in `r3` and the last byte read in `r6`.
First, initialize our counter at -1.
```
_strfind:
movs r3, #-1
```
On each iteration, increment the counter..
```
.Lstrfind_loop:
adds r3, r3, #1
```
Then, load `str[counter]` into `r6`
```
ldrb r6, [r0, r3]
```
Then loop unless `r6` is `\0` or if it matches `r4`.
```
cbz r6, .Lstrfind_loop_end
cmp r6, r4
bne .Lstrfind_loop
```
When we find it, return back to `_strtoint`.
```
.Lstrfind_loop_end:
bx lr
```
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), ~~478~~ ~~218~~ 142 bytes
-(a lot) thanks to Jo King
```
int f(string s){char c[]="N02K8>IE;6";int i=0,n=0;while(s[i]){n=n*10-1;while((s[i]^s[i+1])+47!=c[++n%10]);while(s[i++]!=' '&&s[i]);}return n;}
```
[Try it online!](https://tio.run/##RZDBaoRADIbvPkV2S3e17sJYSlsY3VsPpdAXEBdkjBrQKDPjbqn47HYUoZeQfEl@/kT1/blSan4gVs1QIMTUGasxby/eYIgr4LxF0@cKwdhCzsQWSt@NLD0TjKrONag0S/bf4vnr/fL5IV/3cpmiRJw4EfJeU4O@SSkLRk74KRLnaIMrvboQRlkQvrztEpWGIT9GIgv@98Iw2yVHOB4Oq4icNNpBM7CcVjttTuwH3ugBbL4aYpSurNAuqa@ITysMpOew6gYLcezuWNmSIhfNsrFJC@lN8y/qDjpGsPcObK0RoewGDSXd3DPoBwzekAGpqi2wU/oD "C++ (gcc) – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 13 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
¸mg6 ì`Ψuv
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=uG1nNiDsYM6odXagiA&input=Inplcm8gb25lIHR3byB0aHJlZSBmb3VyIGZpdmUgc2l4IHNldmVuIGVpZ2h0IG5pbmUi)
Looks like everyone else beat me to the same idea - could've saved myself the hassle of writing a script to brute force the optimal string for compression, only to find that, up to index `1,000,000` (it was early, I hadn't had my caffeine yet!), "rothuvsein" is the *only* possible string!
```
¸mg6 ì`... :Implicit input of string
¸ :Split on spaces
m :Map
g6 : Character at index 6 (0-based, with wrapping)
ì :Convert from digit array in base
`... : Compressed string "rothuvsein"
```
The compressed string contains the characters at codepoints `206`, `168`, `117`, `118`, `160` & `136`.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~63 bytes~~, ~~52 bytes~~, 50 bytes
```
p $*.map{|d|'rothuvsein'.index (d*3)[6]}.join.to_i
```
-2 thanks to [value ink's](https://codegolf.stackexchange.com/users/52194/value-ink) tip
[Answer]
# T-SQL, 110 bytes
```
SELECT 0+STRING_AGG(CHARINDEX(LEFT(value,2),'_ontwthfofisiseeini')/2,'')
FROM STRING_SPLIT((SELECT*FROM i),' ')
```
Line break is for readability only.
Input is taken via table \$i\$, [per our IO rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341). I could have saved 14 bytes by pre-populating a string variable, but that's only allowed if the language has no other input methods.
Explanation:
1. `STRING_SPLIT` takes the input string and separates it at the spaces
2. `CHARINDEX` takes the first 2 characters and returns the (1-based) position in the string `'_ontwthfofisiseeini'`. `'ze'` for zero is not in the string and returns 0 for "not found". The underscore ensures we only get multiples of two.
3. Divide by 2 to get the final numeral
4. `STRING_AGG` smashes the digits back together with no separator
5. `0+` forces an implicit conversion to INT and drops any leading zeros. `1*` would also work.
[Answer]
# Kotlin, 83 bytes
```
fun String.d()=split(' ').fold(""){a,b->a+"rothuvsein".indexOf((b+b+b)[6])}.toInt()
```
+1 byte if you wanna support longs with `toLong()`
Same rothuvsein trick as the others, saving some precious bytes thanks to kotlin's nice `toInt()` and `fold()`. I just can't shake the feeling that some more bytes can be shaved off though...
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~20~~ ~~18~~ ~~17~~ 16 bytes
```
Ḳ7ị“"c tẠ;Ḅ»iƲ€Ḍ
```
[Try it online!](https://tio.run/##y0rNyan8///hjk3mD3d3P2qYo5SsUPJw1wLrhztaDu3OPLbpUdOahzt6/v//r1SVWpSvUFKer5CWX1qkUJxZoZCamZ5RopCXmZeqUJxalpqnkA9kpWWWpSpA1GYUpaZCSCUA "Jelly – Try It Online")
-2 bytes from running ["rothuvsein"](https://tio.run/##SypKTM6ozMlPN/r/X6kqtShfIT8vVaGkPF@hJKMoNVUhLb@0SCEtsyxVoTizQqE4tSw1TyE1Mz2jRCEvE6jQkSBQeriz/VFTY1Xmo84FpzY83NX5qGvp//8A) through [user202729's string compressor](https://codegolf.stackexchange.com/a/151721/85334).
-1 byte from stealing Jonathan Allan's zero-free enklact string, and putting it in a marginally differently structured program.
-1 byte because I actually kind of understand Jelly's dictionary-based string compression now
```
Ḳ Split the input on spaces,
Ʋ€ for each word
i find the first 1-based index (defaulting to 0)
“"c tẠ;Ḅ» in "othuvseine"
7ị of the element at modular index 7,
Ḍ and convert from decimal digits to integer.
```
I must admit, I'm disappointed I couldn't get a length reduction from `othuvseinfeld`.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 45 bytes
```
+*.words>>.&{+(1...*.uniname.comb(.uc))}.chrs
```
[Try it online!](https://tio.run/##HcsxCoQwEAXQ3lNMJRrhwzbbLHqXbJywgsnIZIOoePYoNq97C@v8LmGj2lNfOoNVdEzDgPromhcAgxynaAPDSfg2yK5tT7ifpvKpkt0I9/SiNE@RU/GSlf6rVDur0INEvgA "Perl 6 – Try It Online")
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 88 bytes
```
import StdEnv,Text
$s=toInt{#i\\n<-split" "s,c<-:"rothuvsein"&i<-['0'..]|c==(n+n+n).[6]}
```
[Try it online!](https://tio.run/##RY07C8IwFEZ3f0WI4gPb4uQgzaaD4CDo1nYIaaqB5N6S3Pr2rxsLDvLBgbOcT1ktITqsO6uZkwaicS16YgeqN3BJjvpGg1EQhFug59CUJeRpaK0hznhIVJ6uuEc6d5egDfCxydNisphkWfVSQkxh3m@WFcvqHQ8k@67oX1o2YgVvsPOMrsgTxh/aI/sDQfMqflRj5SnEdLuL6ztIZ9RP9lZSg959AQ "Clean – Try It Online")
Heavily based on [Jonathan Allan's answer](https://codegolf.stackexchange.com/a/193364/58563).
Uses a comprehension for indexing instead of `indexOf` / `elemIndex`.
[Answer]
# [J](http://jsoftware.com/), 38 bytes
```
('b\e~mjPxw['i.[:u:70+1#.15|3&u:)&>@;:
```
[Try it online!](https://tio.run/##Pcu9CsIwFIbhvVfxodBjUUOLFCGiCIKTg7jWSTkxKZhA@ouItx5tB4d3eeEpw0SQwlaCsEAK@WspcLicjmFGtyt/nuW57woyopCNXKfzbCqy/L2KG5nEu/1GhiSK@K4dFOjF3sFZRt051NozQ7nGQ5mWUZkeFbdsweaha1hjmf50ECMf9ggofAE "J – Try It Online")
[Answer]
# VBA, 160 bytes
```
Function e(s)
s = Split(s, " ")
For i = LBound(s) To UBound(s)
s(i) = Int((InStr("ontwthfofisiseeini", Left(s(i), 2)) + 1) / 2)
Next
e = Val(Join(s, ""))
End Function
```
Matches the first two characters in a string, zero excluded.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes
```
I⍘⭆⪪S §ι⁶rothuvsein
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwymxODW4BMhP14BQvokFGsEFOZklGp55BaUlUDlNHQUlBSUg6VjimZeSWqGRqaNgpgkSLcovySgtK07NzFPS1NS0/v8/Lb@0SKGkPJ/rv25ZDgA "Charcoal – Try It Online") Link is to verbose version of code. Port of @KevinCruijssen's 05AB1E answer. Explanation:
```
S Input string
⪪ Split on spaces
⭆ Map over words and join
ι Current word
§ Cyclically indexed
⁶ Literal `6`
⍘ rothuvsein Custom base conversion
I Cast to string for implicit print
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 48 bytes
```
+-join($args|%{'rothuvsein'.indexof(($_*3)[6])})
```
[Try it online!](https://tio.run/##BcFbCoAgEADAyxhqUT9Bl4mIoDUNcWPVjB5n32YOLEDRgvfMTbujC0ostMW3eiRhsvmM4ILsXFjhQqOUmOtej8OkP83MNxByKsgGM/0 "PowerShell – Try It Online")
Uses the same `rothuvsein` trick as others, thanks to Jonathan Allan. Expects input arguments via splatting, which on TIO manifests as separate command-line arguments.
[Answer]
# [sed -re](https://www.gnu.org/software/sed/), 78 bytes
```
s/three/3/g;s/five/5/g;s/\w\w(\w)\w*/\1/g;s/ //g;y/eouxvgnr/12467890/;s/^0*//
```
[Answer]
## Windows Batch, 169 bytes
```
@setlocal enabledelayedexpansion
@set z=zeontwthfofisiseeini
:a
@set b=%1
@for /l %%c in (0,2,18)do @if "!b:~0,2!"=="!z:~%%c,2!" set/aa=a*10+%%c/2&shift&goto a
@echo %a%
```
[Answer]
# [K (ngn/k)](https://bitbucket.org/ngn/k), 27 bytes
```
10/"rothuvsein"?(*|7#)'" "\
```
[Try it online!](https://tio.run/##XYxBCsIwEEWvMoyLtoJUV4IuvIjbn2YQZiBJo4h3j6ahFNwMw@e99zjopKW4y@k4crDk5xwhyrd@/znvho6J78V1PTubA6Wn8ZXfCEbbMcU6/t7KUPIBoEVxkkFRXhSRoQSZfCKVzWlsJar5T7Vky9XS0rS281C@ "K (ngn/k) – Try It Online")
Another port of [Kevin Cruijssen's 05AB1E answer](https://codegolf.stackexchange.com/a/193395/98547).
* `" "\` split input on spaces
* `(*|7#)'` take the last character of each word (repeated to be of length seven)
* `"rothuvsein"?` find index of character in "rothuvsein" (i.e. the seventh character of "zero" repeated is "r", which is at index 0)
* `10/` convert from a list of digits to a decimal number
[Answer]
# [Scala](http://www.scala-lang.org/), ~~66~~ ~~64~~ 62 bytes
```
_.split(" ").map("rothuvsein"indexOf _.*(3)(6)).mkString.toInt
```
[Try it online!](https://tio.run/##nVFLS8NAEL77Kz6CYCIl1vouVPDoRQXxXLbJJF1Nd9fdSa2Kv73OJq1Q9OQlS@Z77k4oVKPWeuGsZ4T4kzfK1K2qKXc2cKVX9y7g6AjGMjy9ttpTicp6VK0pWFujGs3vA1jTvHfzUgc1a7SpoVCR4tYT3pQ3Mtmzs2cqGHftYkb@QflAHrRiMmXAjXP43AOWqoneYzyyjy6Ta9waxmQ9zYOTrDRBkuUL5dLEW563y0DaJNqUtLqvMM0P05MsPc@E8tI75GzFYA2UVEV3XSqm1HQdwjZmID2cdKNyHOOyMZ6MltSuUl9KFdzKMYnttvKsQ1WQi3C6JUx@vHrYSQA3Jg3Jwf5Gd4BaLylgf6NJC@u9SLIkSr76Z@iLJtYQ@M2C554oGeB4dJLtED7IW/yDJetqZY9SBEGvEGhJBqTrOUO2tTE5PTu/uLzatYooOj/xEtrVcLRLiBEd/vMR1mg4HP6uJMAf0x2h4F/rbw "Scala – Try It Online")
This is the "rothuvsein" approach in Scala. The 7th character of each (repeated) number string is extracted via `(numberString*3)(6)`. The position of this character in "rothuvsein" is then used as the correct numerical digit. The `toInt` conversion does the rest (e.g., dealing with leading zeros).
2 times 2 bytes saved thanks to @user by
1. an even more abused use of syntactic sugar :)
2. simply using `toInt` conversion rather than `BigInt` constructor
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 26 bytes
```
10⊥'rothuvsein'⍳7⊢/⍤⍴¨≠⍛⊆⍨
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkG/w0NHnUtVS/KL8koLStOzcxTf9S72fxR1yL9R71LHvVuObTiUeeCR72zH3W1Pepd8T8NqOdRb9@jruZHvWtA0uuNH7VNBJoWHOQMJEM8PIP/pymo5@elKpSU5yuUZBSlpkJIdS6geFVqUb4CmICqUAcA "APL (Dyalog Extended) – Try It Online")
A simple function which checks the first two letters of each word.
-30 bytes from Adám using Kevin Cruijssen's idea.
## Explanation(old)
```
{⍕2÷⍨1-⍨(2↑⍵)(⍸⍷)'zeontwthfofisiseeinite'} inner fn:
(2↑⍵) take first two letters
(⍸⍷)'zeontwthfofisiseeinite'} find index of the letters in hardcoded string
2÷⍨1-⍨ subtract 1, divide by 2
⍕ stringify
{⍎⊃,/{⍕2÷⍨1-⍨(2↑⍵)(⍸⍷)'zeontwthfofisiseeinite'}¨' '(≠⊆⊢)⍵} ⍵ → input
' '(≠⊆⊢)⍵ split input on spaces
,/ join output of inner fn
⍎⊃ execute it
```
[Answer]
# [Python 3](https://docs.python.org/3/), 85 bytes
I put two versions of my explanation just for fun :)
Split the input **`i`** into words and loop over it using list comprehension.
For all the words find the location of the first 2 letters in a lookup table (*"zeontwthfofisiseeini"*), making sure to divide by two - with **`//`** for floor division, finally use **`"".join(`** to combine into a string and **`int(`** to convert to integer and remove leading zero(s).
```
lambda i:int("".join([str("zeontwthfofisiseeini".find(x[:2])//2)for x in i.split()]))
```
[Try it online!](https://tio.run/##JczBDoIwEIThV9n01F4g0RuJT4IcELYyBndJuwL68gh6meRPJt/0tkHlvHWX6za2z1vfEiqIeeeKh0J8nS1592EVW2yIGpGRmSFwRYT0fq2rUxPK8hSiJloJQijyNMJ8aELYpnRw3WEkpd9EzEyM@2AkECZblDLPLKR7ZawU9ZX@XxsSs9udLw "Python 3 – Try It Online")
* `lambda i:` lambda function instead of using a `def` function
* `[for x in]` use list comprehension to check through the input
* `i.split` split the input at spaces (default delimiter)
* `"zeontwthfofisiseeini".find(x[:2])` find the location of the first two characters of **x** in a lookup list
* `//2` floor divide output of `.find` because it's checking the first 2 chars
* `str()` convert position to string
* `"".join()` combine output of list comprehension to a string
* `int()` convert string to int and remove leading zero(s)
Also, this is accidentally similar to [this](https://codegolf.stackexchange.com/a/193359/100140) answer but I made mine before looking at the other answers.
] |
[Question]
[
Happy Pi Day everyone! For no reason at all, I'm trying to construct a Monte Carlo estimator of Pi that is as short as possible. Can we construct one that can fit in a tweet?
To clarify, what I have in mind is the typical approach of drawing random points from the unit square and calculating the ratio that fall within the unit circle. The number of samples can be hard coded or not. If you hardcode them, you must use at least 1000 samples. The result may be returned or printed as a floating point, fixed point or rational number.
No trig functions or Pi constants, must be a Monte Carlo approach.
This is code golf, so the shortest submission (in bytes) wins.
[Answer]
# 80386 machine code, 40 38 bytes
Hexdump of the code:
```
60 33 db 51 0f c7 f0 f7 e0 52 0f c7 f0 f7 e0 58
03 d0 72 03 83 c3 04 e2 eb 53 db 04 24 58 db 04
24 58 de f9 61 c3
```
How to get this code (from assembly language):
```
// ecx = n (number of iterations)
pushad;
xor ebx, ebx; // counter
push ecx; // save n for later
myloop:
rdrand eax; // make a random number x (range 0...2^32)
mul eax; // calculate x^2 / 2^32
push edx;
rdrand eax; // make another random number y
mul eax; // calculate y^2 / 2^32
pop eax;
add edx, eax; // calculate D = x^2+y^2 / 2^32 (range 0...2^33)
jc skip; // skip the following if outside the circle
add ebx, 4; // accumulate the result multiplied by 4
skip:
loop myloop;
push ebx; // convert the result
fild dword ptr [esp]; // to floating-point
pop eax;
fild dword ptr [esp]; // convert n to floating-point
pop eax;
fdivp st(1), st; // divide
popad;
ret;
```
This is a function using MS `fastcall` calling convention (number of iterations is passed in register `ecx`). It returns the result in the `st` register.
Fun things about this code:
* `rdrand` - just 3 bytes to generate a random number!
* It uses (unsigned) integer arithmetic until the final division.
* The comparison of squared distance (`D`) with squared radius (`2^32`) is performed automatically - the carry flag contains the result.
* To multiply the count by 4, it counts the samples in steps of 4.
[Answer]
# Matlab/Octave, 27 bytes
I know there already is a Matlab/Octave answer, but I tried my own approach. I used the fact that the integral of `4/(1+x^2)` between 0 and 1 is pi.
```
mean(4./(1+rand(1,1e5).^2))
```
[Answer]
# CJam, ~~27 23~~ 22 or 20 bytes
```
4rd__{{1dmr}2*mhi-}*//
```
*2 bytes saved thanks to Runner112, 1 byte saved thanks to Sp3000*
It takes the iteration count from STDIN as an input.
This is as straight forward as it gets. These are the major steps involved:
* Read the input and run the Monte Carlo iterations that many times
* In each iteration, get sum of square of two random floats from 0 to 1 and see if it is less than 1
* Get the ratio of how many times we got less than 1 by total iterations and multiply it by 4 to get PI
**Code expansion**:
```
4rd "Put 4 on stack, read input and convert it to a double";
__{ }* "Take two copies, one of them determines the iteration"
"count for this code block";
{1dmr}2* "Generate 2 random doubles from 0 to 1 and put them on stack";
mh "Take hypot (sqrt(x^2 + y^2)) where x & y are the above two numbers";
i "Convert the hypot to 0 if its less than 1, 1 otherwise";
- "Subtract it from the total sum of input (the first copy of input)";
// "This is essentially taking the ratio of iterations where hypot";
"is less than 1 by total iterations and then multiplying by 4";
```
[Try it online here](http://cjam.aditsu.net/#code=4rd__%7B%7B1dmr%7D2*mhi-%7D*%2F%2F&input=100000)
---
If average value of `1/(1+x^2)` is also considered as Monte Carlo, then this can be done in 20 bytes:
```
Urd:K{4Xdmr_*)/+}*K/
```
[Try it here](http://cjam.aditsu.net/#code=Urd%3AK%7B4Xdmr_*)%2F%2B%7D*K%2F&input=1000000)
[Answer]
# R, 40 (or 28 or 24 using other methods)
```
mean(4*replicate(1e5,sum(runif(2)^2)<1))
mean(4*sqrt(1-runif(1e7)^2))
mean(4/(1+runif(1e7)^2))
```
# Python 2, 56
Another Python one, if numpy is allowed, but pretty similar to Matlab/Octave:
```
import numpy;sum(sum(numpy.random.rand(2,8e5)**2)<1)/2e5
```
[Answer]
# Commodore 64 Basic, 45 bytes
```
1F┌I=1TO1E3:C=C-(R/(1)↑2+R/(1)↑2<1):N─:?C/250
```
PETSCII substitutions: `─` = `SHIFT+E`, `/` = `SHIFT+N`, `┌` = `SHIFT+O`
Generates 1000 points in the first quadrant; for each, adds the truthness of "x^2+y^2<1" to a running count, then divides the count by 250 to get `pi`. (The presence of a minus sign is because on the C64, "true" = -1.)
[Answer]
# Mathematica, ~~42~~ ~~40~~ 39 bytes (or 31/29?)
I've got three solutions all at 42 bytes:
```
4Count[1~RandomReal~{#,2},p_/;Norm@p<1]/#&
4Tr@Ceiling[1-Norm/@1~RandomReal~{#,2}]/#&
4Tr@Round[1.5-Norm/@1~RandomReal~{#,2}]/#&
```
They are all unnamed functions that take the number of samples `n` andd return a rational approximating π. First they all generate `n` points in the unit square in the positive quadrant. Then they determine the number of those samples that lie within the unit circle, and then they divide by the number of samples and multiply by `4`. The only difference is in how they determine the number of sampples inside the unit circle:
* The first one uses `Count` with the condition that `Norm[p] < 1`.
* The second one subtracts the norm of each point from `1` and then rounds up. This turns numbers inside the unit circle to `1` and those outside to `0`. Afterwards I just sum them all up with `Tr`.
* The third one does essentially the same, but subtracts the from `1.5`, so I can use `Round` instead of `Ceiling`.
Aaaaaand *while* writing this up, it occurred to me that there is indeed a shorter solution, if I just subtract from `2` and then use `Floor`:
```
4Tr@Floor[2-Norm/@1~RandomReal~{#,2}]/#&
```
or saving another byte by using the Unicode flooring or ceiling operators:
```
4Tr@⌊2-Norm/@1~RandomReal~{#,2}⌋/#&
4Tr@⌈1-Norm/@1~RandomReal~{#,2}⌉/#&
```
Note that the three rounding-based solutions can also be written with `Mean` instead of `Tr` and without the `/#`, again for the same bytes.
---
If other Monte Carlo based approaches are fine (specifically, the one Peter has chosen), I can do 31 bytes by estimating the integral of `√(1-x2)` or 29 using the integral of `1/(1+x2)`, this time given as a floating point number:
```
4Mean@Sqrt[1-1~RandomReal~#^2]&
Mean[4/(1+1~RandomReal~#^2)]&
```
[Answer]
# Python 2, ~~77~~ 75 bytes
```
from random import*;r=random;a=0;exec"a+=r()**2+r()**2<1;"*4000;print a/1e3
```
Uses 4000 samples to save bytes with `1e3`.
[Answer]
# J, 17 bytes
Computes the mean value of `40000` sample values of the function `4*sqrt(1-sqr(x))` in the range `[0,1]`.
Handily `0 o.x` returns `sqrt(1-sqr(x))`.
```
1e4%~+/0 o.?4e4$0
3.14915
```
[Answer]
## [><> (Fish)](http://esolangs.org/wiki/Fish), 114 bytes
```
:00[2>d1[ 01v
1-:?!vr:@>x| >r
c]~$~< |+!/$2*^.3
.41~/?:-1r
|]:*!r$:*+! \
r+)*: *:*8 8/v?:-1
;n*4, $-{:~ /\r10.
```
Now, ><> doesn't have a built-in random number generator. It does however have a function that sends the pointer in a random direction. The random number generator in my code:
```
______d1[ 01v
1-:?!vr:@>x| >r
_]~$~< |+!/$2*^__
__________
___________ _
_____ ____ _______
_____ ____~ ______
```
It basically generates random bits that make up a binary number and then converts that random binary number to decimal.
The rest is just the regular points in the square approach.
Usage: when you run the code you must make sure to prepopulate the stack (-v in python interpreter) with the number of samples, for example
```
pi.fish -v 1000
```
returns
```
3.164
```
[Answer]
**Matlab or Octave 29 bytes** (thanks to flawr!)
```
mean(sum(rand(2,4e6).^2)<1)*4
```
(I am no quite sure if <1 is OK. I read it should be <=1. But how big is the probability to draw exactly 1...)
**Matlab or Octave 31 bytes**
```
sum(sum(rand(2,4e3).^2)<=1)/1e3
```
[Answer]
# Java, 108 bytes
```
double π(){double π=0,x,i=0;for(;i++<4e5;)π+=(x=Math.random())*x+(x=Math.random())*x<1?1e-5:0;return π;}
```
Four thousand iterations, adding 0.001 each time the point is inside the unit circle. Pretty basic stuff.
*Note:* Yes, I know I can shed four bytes by changing `π` to a single-byte character. I like it this way.
[Answer]
## **Javascript: 62 Bytes**
```
for(r=Math.random,t=c=8e4;t--;c-=r()**2+r()**2|0);alert(c/2e4)
```
I used the previous (now deleted) javascript answer and shaved 5 bytes.
[Answer]
## GolfScript (34 chars)
```
0{^3?^rand.*^.*+/+}2000:^*`1/('.'@
```
[Online demo](http://golfscript.apphb.com/?c=MHteMz9ecmFuZC4qXi4qKy8rfTIwMDA6XipgMS8oJy4nQA%3D%3D)
This uses fixed point because GS doesn't really have floating point. It slightly abuses the use of fixed point, so if you want to change the iteration count make sure that it's twice a power of ten.
Credit to [xnor](https://codegolf.stackexchange.com/users/20260/xnor) for the particular Monte Carlo method employed.
[Answer]
# Python 2, ~~90~~ ~~85~~ 81 bytes
```
from random import*;r=random;print sum(4.for i in[0]*9**7if r()**2+r()**2<1)/9**7
```
returns `3.14120037157` for example. The sample count is 4782969 (9^7). You can get a better pi with 9^9 but you will have to be patient.
[Answer]
# Ruby, 39 bytes
```
p (1..8e5).count{rand**2+rand**2<1}/2e5
```
One of the highlight is that this one is able to use `8e5` notation, which makes it extendable up to ~8e9 samples in the same program byte count.
[Answer]
# [Perl 6](http://perl6.org/), 33 bytes
```
{4*sum((1>rand²+rand²)xx$_)/$_}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/2kSruDRXQ8PQrigxL@XQJm0IpVlRoRKvqa8SX/tfrzixUiEtv0ghTcPQwMBAU6GiQsHQ4D8A "Perl 6 – Try It Online")
This is a function that takes the number of samples as an argument.
[Answer]
# Scala, 87 77 66 bytes
```
def s=math.pow(math.random,2);Seq.fill(1000)(s+s).count(_<1)/250d
```
[Answer]
# Pure Bash, 65 bytes
```
for((;i++<$1*4;a+=RANDOM**2+RANDOM**2<32767**2));{ :;}
echo $a/$1
```
Takes a single command-line parameter which is multiplied by 4 to give the number of samples. Bash arithmetic is integer-only, so a rational is output. This may be piped to `bc -l` for the final division:
```
$ ./montepi.sh 10000
31477/10000
$ ./montepi.sh 10000|bc -l
3.13410000000000000000
$
```
[Answer]
# [Joe](https://github.com/JaniM/Joe), 20 19 bytes
Note: this answer is non-competing, because version 0.1.2, which added randomness, was released after this challenge.
Named function F:
```
:%$,(4*/+1>/+*,?2~;
```
Unnamed function:
```
%$,(4*/+1>/+*,?2~;)
```
These both take the sample count as an argument and return the result. How do they work?
```
%$,(4*/+1>/+*,?2~;)
(4*/+1>/+*,?2~;) defines a chain, where functions are called right-to-left
2~; appends 2 to the argument, giving [x, 2]
? create a table of random values from 0 to 1 with that shape
*, take square of every value
/+ sum rows, giving a list of (x**2+y**2) values
1> check if a value is less than 1, per atom
/+ sum the results
4* multiply by four
%$, divide the result by the original parameter
```
Example runs:
```
:%$,(4*/+1>/+*,?2~;
F400000
3.14154
F400000
3.14302
```
[Answer]
# dc, 59 characters (whitespace is ignored)
```
[? 2^ ? 2^ + 1>i]su
[lx 1+ sx]si
[lu x lm 1+ d sm ln>z]sz
5k
?sn
lzx
lx ln / 4* p
q
```
I tested this on Plan 9 and OpenBSD, so I imagine it will work on Linux (GNU?) `dc`.
## Explanation by line:
1. Stores code to [read and square two floats; execute register `i` if 1 is greater than the sum of their squares] in register `u`.
2. Stores code to [increment register `x` by 1] in register `i`.
3. Stores code to [execute register `u`, increment register `m`, and then execute register `z` if register `m` is greater than register `n`] in register `z`.
4.
5. Set the scale to 5 decimal points.
6. Read the number of points to sample from the first line of input.
7. Execute register `z`.
8. Divide register `x` (the number of hits) by register `n` (the number of points), multiply the result by 4, and print.
9. Quit.
## However, I cheated:
The program needs a supply of random floats between 0 and 1.
```
/* frand.c */
#include <u.h>
#include <libc.h>
void
main(void)
{
srand(time(0));
for(;;)
print("%f\n", frand());
}
```
## Usage:
```
#!/bin/rc
# runpi <number of samples>
{ echo $1; frand } | dc pi.dc
```
## Test run:
```
% runpi 10000
3.14840
```
# Now with less cheating (100 bytes)
Someone pointed out that I could include a simple prng.
<http://en.wikipedia.org/wiki/RANDU>
```
[lrx2^lrx2^+1>i]su[lx1+sx]si[luxlm1+dsmln>z]sz[0kls65539*2 31^%dsslkk2 31^/]sr?sn5dksk1sslzxlxlm/4*p
```
## Ungolfed
```
[
Registers:
u - routine : execute i if sum of squares less than 1
i - routine : increment register x
z - routine : iterator - execute u while n > m++
r - routine : RANDU PRNG
m - variable: number of samples
x - variable: number of samples inside circle
s - variable: seed for r
k - variable: scale for division
n - variable: number of iterations (user input)
]c
[lrx 2^ lrx 2^ + 1>i]su
[lx 1+ sx]si
[lu x lm 1+ d sm ln>z]sz
[0k ls 65539 * 2 31^ % d ss lkk 2 31 ^ /]sr
? sn
5dksk
1 ss
lzx
lx lm / 4*
p
```
## Test run:
```
$ echo 10000 | dc pigolf.dc
3.13640
```
[Answer]
# Pyth, 19
```
c*4sm<sm^OQ2 2*QQQQ
```
Give the desired number of iterations as input.
[Demonstration](https://pyth.herokuapp.com/?code=c*4sm%3Csm%5EOQ2+2*QQQQ&input=10000)
Since Pyth doesn't have a "Random floating number" function, I had to improvise. The program choose two random positive integers less than the input, squares, sums, and compared to the input squared. This performed a number of times equal to the input, then the result is multiplied by 4 and divided by the input.
In related news, I will be adding a random floating point number operation to Pyth shortly. This program does not use that feature, however.
---
If we interpret "The result may be returned or printed as a floating point, fixed point or rational number." liberally, then printing the numerator and denominator of the resulting fraction should be sufficient. In that case:
# Pyth, 18
```
*4sm<sm^OQ2 2*QQQQ
```
This is an identical program, with the floating point division operation (`c`) removed.
[Answer]
# Julia, 37 bytes
```
4mean(1-floor(sum(rand(4^8,2).^2,2)))
```
The number of samples is 65536 (=4^8).
A sligthly longer variant: a function with number of samples `s` as the only argument:
```
s->4mean(1-floor(sum(rand(s,2).^2,2)))
```
[Answer]
# C, 130 bytes
```
#include<stdlib.h>f(){double x,y,c=0;for(int i=0;i<8e6;++i)x=rand(),y=rand(),c+=x*x+y*y<1.0*RAND_MAX*RAND_MAX;printf("%f",c/2e6);}
```
Ungolfed:
```
#include <stdlib.h>
f(){
double x,y,c=0;
for(int i=0; i<8e6; ++i) x=rand(), y=rand(), c+=x*x+y*y<1.0*RAND_MAX*RAND_MAX;
printf("%f",c/2e6);
}
```
[Answer]
## Racket 63 bytes
Using method of R language answer by @Matt :
```
(/(for/sum((i n))(define a(/(random 11)10))(/ 4(+ 1(* a a))))n)
```
Ungolfed:
```
(define(f n)
(/
(for/sum ((i n))
(define a (/(random 11)10))
(/ 4(+ 1(* a a))))
n))
```
Testing:
```
(f 10000)
```
Output (fraction):
```
3 31491308966059784/243801776017028125
```
As decimal:
```
(exact->inexact(f 10000))
3.13583200307849
```
[Answer]
# [Fortran (GFortran)](https://gcc.gnu.org/fortran/), ~~84~~ 83 bytes
```
CALL SRAND(0)
DO I=1,4E3
X=RAND()
Y=RAND()
IF(X*X+Y*Y<1)A=A+1E-3
ENDDO
PRINT*,A
END
```
[Try it online!](https://tio.run/##S8svKilKzNNNT4Mw/v93dvTxUQgOcvRz0TDQ5HLxV/C0NdQxdDXmirAFC2pyRcIYnm4aEVoR2pFakTaGmo62jtqGXK5@Li7@XAFBnn4hWjqO@kamBiCh//8B "Fortran (GFortran) – Try It Online")
This code is very bad wrote. It will fail if gfortran decide to initialize variable `A` with other value then 0 (which occurs 50% of the compilations, approximately) and, if `A` is initialized as 0, it will always generate the same random sequence for the given seed. Then, the same value for Pi is printed always.
This is a much better program:
# [Fortran (GFortran)](https://gcc.gnu.org/fortran/), ~~100~~ 99 bytes
```
A=0
DO I=1,4E3
CALL RANDOM_NUMBER(X)
CALL RANDOM_NUMBER(Y)
IF(X*X+Y*Y<1)A=A+1E-3
ENDDO
PRINT*,A
END
```
[Try it online!](https://tio.run/##S8svKilKzNNNT4Mw/v93tDXgcvFX8LQ11DF0NeZydvTxUQhy9HPx9433C/V1cg3SiNDEJhqpyeXpphGhFaEdqRVpY6jpaOuobcjl6ufi4s8VEOTpF6Kl46hvZGoAEvr/HwA "Fortran (GFortran) – Try It Online")
(One byte saved in each version; thanks Penguino).
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 26 or 18 bytes
```
o r_+ÂMhMr p +Mr p <1Ã*4/U
```
[Try it online!](https://tio.run/##y0osKPn/P1@hKF77cJNvhm@RQoGCNpi0MTzcrGWiH/r/v6EBEAAA)
Analogous to [Optimizer's answer](https://codegolf.stackexchange.com/a/47767/16484), mainly just trying to learn Japt.
Takes the number of iterations to run for as the implicit input `U`.
```
o Take the input and turn it into a range [0, U),
essentially a cheap way to get a large array.
r_ Reduce it with the default initial value of 0.
+Â On each iteration, add one if
MhMr p +Mr p the hypotenuse of a random [0,1)x[0,1) right triangle
<1 is smaller than one.
Ã*4/U Multiply the whole result by four and divide by input.
```
If `1/(1+x^2)` is allowed (instead of two separate randoms), then we can achieve 18 bytes with the same logic.
```
o r_Ä/(1+Mr pÃ*4/U
```
[Answer]
# F#, 149 bytes
```
open System;
let r=new Random()
let q()=
let b=r.NextDouble()
b*b
let m(s:float)=(s-Seq.sumBy(fun x->q()+q()|>Math.Sqrt|>Math.Floor)[1.0..s])*4.0/s
```
[Try it online!](https://tio.run/##VU49a8MwEN39K45AQUqxokCnNvJQ2m5JTD2GDHJzag2WZEvnxIb8d8d1s/Tg4PE@7p2J6ZcPOI6@QQfFEAntS1IjQVAOL/Cp3clbxmeqZVwl8ItKFcQOe3rzXVnjJEO5LGePZfHZ1F4TVyymBbYidvZ1YKZz0KfZdOJx2mu21fQjijbQHX7U3gd@WAspRDzy5ZOQqzgeNu@OwpD7ylF2/CvQlQMdvs9w/wUjVVYT7k1egQILazmPkAk0YQoaB4sHs/hnTECONw)
As far as I can make out, to do this kind of running total in F# it's shorter to create an array of numbers and use the `Seq.sumBy` method than use a `for..to..do` block.
What this code does it that it creates a collection of floating-point numbers from 1 to `s`, performs the function `fun x->...` for the number of elements in the collection, and sums the result. There are `s` elements in the collection, so the random test is done `s` times. The actual numbers in the collection are ignored (`fun x->`, but `x` is not used).
It also means that the application has to first create and fill the array, and then iterate over it. So it's probably twice as slow as a `for..to..do` loop. And with the array creation memory usage is in the region of O(f\*\*k)!
For the actual test itself, instead of using an `if then else` statement what it does is it calculates the distance (`q()+q()|>Math.Sqrt`) and rounds it down with `Math.Floor`. If the distance is within the circle, it'll be rounded down to 0. If the distance is outside the circle it'll be rounded down to 1. The `Seq.sumBy` method will then total these results.
Note then that what `Seq.sumBy` has totalled is not the points *inside* the circle, but the points *outside* it. So for the result it takes `s` (our sample size) and subtracts the total from it.
It also appears that taking a sample size as a parameter is shorter than hard-coding the value. So I am cheating a little bit...
[Answer]
# Haskell, ~~116~~ ~~114~~ ~~110~~ 96 bytes
```
d=8^9
g[a,b]=sum[4|a*a+b*b<d*d]
p n=(sum.take(floor n)$g<$>iterate((\x->mod(9*x+1)d)<$>)[0,6])/n
```
Because dealing with `import System.Random; r=randoms(mkStdGen 2)` would take too many precious bytes, I generate an infinite list of random numbers with the linear congruential generator that some say is almost cryptographically strong: `x↦x*9+1 mod 8^9`, which by the Hull-Dobell Theorem has the full period of `8^9`.
`g` yields `4` if the random number point is inside the circle for pairs of random numbers in `[0..8^9-1]` because this eliminates a multiplication in the formula used.
Usage:
```
> p 100000
3.14208
```
[Try it online!](https://tio.run/##FclLDoIwFEDROat4gw7aggqJMZJQNlJr8ppWJNBPSk0YuPeKd3juG7fFrmspRtyffTVJbLQS28fJ6xc51prrwXCjqghe0MPPGRdLX2sICTwj00DGOduE2VL62E@jC4b2fK87ZtjxmGybm2IXXxzOHgTENPsMBCJ07b/yAw "Haskell – Try It Online")
[Answer]
# Perl 5, 34 bytes
```
$_=$a/map$a+=4/(1+(rand)**2),1..$_
```
The number of samples is taken from stdin. Requires `-p`.
Works because:
[](https://www.wolframalpha.com/input/?i=integral+%7B+1%2F(1%2Bx%5E2)+%7D+for+x+%3D+0..1)
[Try it online!](https://tio.run/##K0gtyjH9/18l3lYlUT83sUAlUdvWRF/DUFujKDEvRVNLy0hTx1BPTyX@/39DAxD4l19QkpmfV/xftwAA "Perl 5 – Try It Online")
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), 11 bytes
```
0♫ô4ƒ²)/+♫/
```
[Try it online!](https://tio.run/##y00syUjPz0n7/9/g0czVh7eYHJt0aJOmvjaQo///PwA "MathGolf – Try It Online")
## Explanation
```
0 Push 0 (used for the sum)
♫ Push 10000
ô Start block of length 6
4 Push 4
ƒ² Push random float in range [0,1) and square
) Increment by 1
/ Divide
+ Add result to the total sum (last instruction of block)
♫/ Divide by 10000
```
I'll add an explanation tomorrow. It performs 10000 iterations using the same integral as many other languages.
Assuming number of iterations as input:
# [MathGolf](https://github.com/maxbergmark/mathgolf), 10 bytes
```
ô4ƒ²)/+\/(
```
[Try it online!](https://tio.run/##y00syUjPz0n7///wFpNjkw5t0tTXjtHX@P/f0MDAAAA "MathGolf – Try It Online")
## Explanation
```
ô Start block of length 6
4 Push 4
ƒ² Push random float in range [0,1) and square
) Increment by 1
/ Divide
+ Add result to the total sum (last instruction of block)
The first iteration, this adds the result to the implicit input, meaning that if the input is 10000 and the result is 3.1, 10003.1 is pushed on the stack. The end result is 10000 too large.
\ Swap the top two elements on the stack (pushes the implicit input to the top)
/ Divide (Since the sum is wonky, this is around 4.14159...)
( Decrement by one, resulting in 3.14159...)
```
] |
[Question]
[
## Description
Given an unsorted array of integers, find the smallest positive integer that does not appear in the array. Your task is to write the shortest code possible to solve this problem.
## Input
A non-empty or empty array of integers, where the integers may be negative, zero, or positive.
## Output
The smallest positive integer that does not appear in the array.
## Test cases
Input: `[1, 2, 3]`
Output: 4
Input: `[3, 4, -1, 1]`
Output: 2
Input: `[7, 8, 9, 11, 12]`
Output: 1
Input: `[-5, -4, -3, -2, -1, 0, 1, 2, 3, 5, 7, 10]`
Output: 4
Input: `[]`
Output: 1
Input: `[-1, -4, -7]`
Output: 1
Scoring criteria: Your score is the number of bytes in your code, as counted by the bytecount tool. The code with the smallest number of bytes wins. In the case of a tie, the earlier submission wins.
```
var QUESTION_ID=258335,OVERRIDE_USER=117038;function answersUrl(e){return"http://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"http://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]
# [Nekomata](https://github.com/AlephAlpha/Nekomata) + `-1`, 4 bytes
```
ŇPᵖf
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFNtJJurpKOgpKuoVLsgqWlJWm6FsuPtgc83DotbUlxUnIxVGzBzZRoQx0FIx0F41iuaGMdBRMdBV2ggCGQZ66jYKGjYAnkgASMgCK6pkBZkAqgQl0jiEoDoBzEAB0FoDRQk6EBUClItSFUtXksxDIA)
The flag `-1` set the interpreter to `FirstValue` mode, which prints the first possible result.
```
Ň Non-deterministically choose an natural number
P that is positive
ᵖ and such that
f the input doesn't contain this number
```
---
## [Nekomata v0.1.0.0](https://github.com/AlephAlpha/Nekomata/tree/v0.1.0.0) + `-1`, 6 bytes
```
ℕPᵖ{-Z
```
This is the original answer in an old version of Nekomata. Some symbols are changed in newer versions.
```
ℕ Non-deterministically choose an natural number
P that is positive
ᵖ{ and such that
-Z it minus the input doesn't contain any zero
```
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), ~~3~~ 2 bytes (4 nibbles)
```
/-,~
```
I somehow didn't expect that `fold`-ing over an infinite list, starting from infinity (the right-hand end) would work, but it does.
```
/-,~ # full function
/-,~$$ # (with implicit arguments shown):
- # remove
$ # elements of the input list
# from
,~ # the infinite list of positive integers
/ # now fold over this infinite list from the right
$ # each time returning the left-hand argument
- # (so, finally, returning the first (left-most) element)
```
[](https://i.stack.imgur.com/cIMnx.png)
[Answer]
# [Zsh](https://www.zsh.org/), 21 bytes
```
seq inf|grep -xvm1 $1
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwXJD24TkxJKEpaUlaboWW4tTCxUy89Jq0otSCxR0K8pyDRVUDCFyC6DUakMuIy5jLjMuQy4TiBAA)
* `seq inf`: list of all positive integers
* `grep`: filter those for
+ `$1`: any of the lines in the input
+ `-v`: inverted match (i.e., it must not match any of the input items)
+ `-x`: match whole lines, not substrings
+ `-m1`: output only the first matching line
[Answer]
# [flax](https://github.com/PyGamer0/flax), 7 bytes
```
∵µḟκ→A∴
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70kLSexYsGCpaUlaboWGx91bD209eGO-ed2PWqb5PioY8uS4qTkYqjshmilaEMdXSAy0tE1jlWKhYoDAA)
[](https://i.stack.imgur.com/N2RUl.png)
## Explained
```
∵µḟκ→A∴
∵ ⊳ min of
κ→A∴ ⊳ range(1, abs(max(input)) + 2)
ḟ ⊳ set diff with input
```
[Answer]
# JavaScript (ES6), 33 bytes
```
a=>a.reduce(m=>m+a.includes(m),1)
```
[Try it online!](https://tio.run/##nZBBDoIwEEX3nmKWbZwCLRh0ARcxXTSlGAylBsTr1yKuSEyJs528/9/MXb3UpMfu8WSDa4xvK6@qWiWjaWZtiK1qe1RJN@h@bsxELEVOvXbD5HqT9O5GWnLlCAIhlxAbSiFNoThs@ByhQGAhhssdvNjyJcIZ4RLwJULICM@3PDuF9sUgiDCxmmQhaT0LIaxDBc/kD//44ZF@/u0v5V98/hHlu//v3w "JavaScript (Node.js) – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~7~~ ~~6~~ 5 bytes
```
ℕ₁≜¬∈
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRuX/eobcOjpqaHuzprH26d8P9Ry9RHTY2POuccWvOoo@P//@hoQx0FIx0F41gdhWhjHQUTHYV4oIghiGuuo2Cho2AJ5IFEjEBC8aZAeZAaoNJ4I4haA6AkxAwdBaA0UJehAUgtWL0hVL15bCwA "Brachylog – Try It Online")
*-1 stealing [Fatalize's solution](https://codegolf.stackexchange.com/revisions/252022/1) to the dupe target--note that my ~~accepted~~ reverted golf suggestion fails on the empty list. Whoops*
Reversed I/O.
```
ℕ₁ The output is a positive integer.
≜ Try every value for it until one
¬∈ isn't in the input.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
1ḟ1#
```
[Try it online!](https://tio.run/##y0rNyan8/9/w4Y75hsr/D7drRv7/H22oo2Cko2Acq6MQbayjYKKjoAsUMQRxzXUULHQULIE8kIgRSEjXFCgPUgNUqmsEUWsAlISYoaMAlAbqMjQAqQWrN4SqN48FAA "Jelly – Try It Online")
```
1# Find the first integer
1 starting from 1
ḟ which is not empty with elements of the list filtered out.
```
[Answer]
# x86-64 machine code, 13 bytes
```
31 C0 FF C0 89 F1 57 F2 AF 5F 74 F6 C3
```
[Try it online!](https://tio.run/##TVJNj5swED3jXzFLlcosQwQkadqk6WXPvfRUKZuD15jgKjEIOy0R4q@XHRMlWiGN5@PNe@PBsmmSo5TjKOwZOPwKOSs3QVe3oESH3rB2E2gjJzc4139BSV@wmgXNxVbQFuS1qjEKrBS2oHTd3LJ/FLS@5lgUQrRlqnOqNRC@hNBr46Dk3j4LBH@aaDsw9om0TpdCwXfrCl3Pqx@MWSeclmBde5EOnLKOhNSNw2ynZrHP8gP134t2f4Ad9KxfYJ9hjothQNYvkeIlJhlmU7zCfo1f8RtmlMmnVJZjn6wwIdQCk9xjU5wYcIVrzNIJlWI/ncROAA9e@3jYMj/MWWjDI9azoKRFcnFxNXx2sHmMbiMWUDVoWoKXPJxp4CHSPtycluHmJqJtBbduT6jpLildFJ52vkpeHBPFBwI700QQ0hfDk/YcYq8PE8sdE72a0CcGFrBH8tX8FLLS9PNkXajNBPCKnVdEuFJY1NDf4TBL898kdN1xfjFWH40qQFaifY7KaN/FMUkO8K/SJwX86sdNu5eFJ30wcLrs25U24edB6Kg4jON/WZ7E0Y7J@cuSDL3GHeHV6R0 "C++ (gcc) – Try It Online")
Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes the address of an array of 32-bit integers in RDI and its length in ESI, and returns a 32-bit integer in EAX.
In assembly:
```
f: xor eax, eax # Set EAX to 0.
r: inc eax # Increase EAX by 1.
mov ecx, esi # Set ECX to the length.
push rdi # Save the value of RDI onto the stack.
repne scasd # Compare EAX and the value at address RDI,
# advancing the pointer and counting down ECX,
# and repeat as long as the result is unequal and ECX≠0.
pop rdi # Restore the value of RDI from the stack.
je r # Jump back if the last comparison result was equal.
ret # Return.
```
[Answer]
# [Python 3](https://docs.python.org/3/), 38 bytes
```
f=lambda a,i=1:i in a and f(a,i+1)or i
```
A recursive function that accepts the list and returns the first missing positive integer.
**[Try it online!](https://tio.run/##PY5BCsIwEEX3nuLvmuAEmlapFupFxEWkBgOalpqNlJ49Tow1iyHz5r9hxne4D76O0XYP87z2BoZcp1sH58GN72EFo62WwwQXLddwe4U0FhvwO2tCRagvlNuasCMopnpFDeFAODJJtFqx2nMuZVlRVXZKDuR9BB6zqcs1//f0z2uYyPYLx8n5IGwxp@MWdCfMVqS/XAoZPw "Python 3 – Try It Online")**
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 3 bytes
```
-#Q
```
[Try it online!](https://tio.run/##K6gsyfj/X1c58P//aF1THQVdEyA2BmIjIDbUUTDQUQCSQA5QDChtDuQaxAIA "Pyth – Try It Online")
This challenge is extremely well-suited for Pyth. Let's go through it step by step:
* `#`: This is the filter function. The predicate function that is used as the filter is `-TQ`, where `T` is the variable representing the values being filtered over. No explicit input is given. When no input is given, `#` outputs the first positive integer for which the predicate function gives a truthy output.
* `-`: This is subtraction function. It is called on `T`, a positive integer, and `Q`, the input list for the program. When `-` is called with an integer followed by a list, it returns a singleton list containing the integer, if the integer is absent from the list, or else an empty list.
Here's an equivalent Python program to the above Pyth program, to hopefully make it clearer what's going on.
```
import ast
Q = ast.literal_eval(input())
T = 1
while True:
subtract_in = [T]
subtract_out = [elem for elem in subtract_in if elem not in Q]
if subtract_out:
print(T)
break
T += 1
```
[Try it online!](https://tio.run/##VY7RCoMgFIbvfYpzWaxGrY3BYA8ReBcRNoxkpmLHjT19OxaMduBX/@8/HnUfHK2plkVNznoEMSOr4R73o1YovdCdfAmdKOMCJmnKOKUle49KS@A@yBsDqjn06MUDO2Uob3j7T23AiKWWEwzWw3qg1v01NWzYWIxRvY0gup@yvRbLeWUw4ekP9F6K5@o4HOiPy9LklwzyM6kinUhlBkUGtJIhRvGVbNF@AQ "Python 3 – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~6 5~~ 4 bytes
```
?F)ṅ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCI/RinhuYUiLCIiLCJbMSwyLDMsNCw1LDYsN10iXQ==)
*-2 thanks to @lyxal*
#### Explanation
```
?F)ṅ # Implicit input
)ṅ # First integer where:
?F # Remove elements from the input which are in this number
# (i.e. is the number not in the input)
```
[Answer]
# [Haskell](https://www.haskell.org) + [hgl](https://gitlab.com/WheatWizard/haskell-golfing-library), 10 bytes
```
he<df[1..]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ0W0km5yQYFS7E3VzNyC_KIShcLSxJzMtMzUFIWAotSc0pRULqhEAFeabczS0pI0XYtVGak2KWnRhnp6sRCBnbmJmXm2mfkqxRk2aTZQjXpFqYkpEPkFN7WidU11FHRNgNgYiI2A2FBHwUBHAUgCOUAxoLQ5kGsANRIA)
My first hgl answer. Returns the first element of the "set" difference of the input from the positive integers.
Potential useful additions (or that I couldn't find):
* a two or three byte alias for `[1..]`
* find the first item in the list matching a predicate (`(hd<)<fl`)
* find the first positive integer matching a predicate (a special-cased combination of the above two; like Jelly's `#`)
* (I didn't use it in the code itself, but in the footer), `read` Maybe there's some fancy equivalent in `P.Parse`, but I couldn't find it
I'd like to set up an instance of [hoogle](https://github.com/ndmitchell/hoogle) for hgl - it would make searching for things easier.
[Answer]
# [Zsh](https://www.zsh.org/), 31 bytes
Unlike [pxeger's answer](https://codegolf.stackexchange.com/a/258341/86147), no external programs, just pure shell constructs.
```
<<<${${${:-{1..1$#}}:|argv}[1]}
```
[Try it online!](https://tio.run/##qyrO@F@cm6mhqfHfxsZGpRoErXSrDfX0DFWUa2utahKL0stqow1ja/9rcnEBVYKwgqGCkYIxmGWkoGuooAvkKRj@BwA "Zsh – Try It Online")
```
${:-{1..1$#}} # List from 1 to a number bigger than the length of the list.
# It's shorter to prepend a "1" than to add 1.
${ :|argv} # :| set difference with the list
<<<${ [1]} # print the first result
```
[Answer]
# [R](https://www.r-project.org), 31 bytes
```
\(x,y=seq(c(1,x)))y[!y%in%x][1]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhb7YzQqdCpti1MLNZI1DHUqNDU1K6MVK1Uz81QrYqMNYyGqbqanaRhaGWsqKCuYcKUBVRrrmOjoGuoYaoKEjMBC5joWOpY6hkBBI7CoIVhU19TKWMdUx1zH0EAToR1ZgaGOLtAsc4gQxLoFCyA0AA)
[Answer]
# [R](https://www.r-project.org), 27 bytes
```
\(x){while(T%in%x)T=T+1;+T}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuha7YzQqNKvLMzJzUjVCVDPzVCs0Q2xDtA2ttUNqISpupqdpGFoZayooK5hwpWkkaxjrmOjoGuoYaoKEjMBC5joWOpY6hkBBI7CoIVhU19TKWMdUx1zH0EAToR1ZgaGOLtAsc4gQxLoFCyA0AA)
Naive approach. For a clever one (and currently longer) see [@Dominic van Essen's answer](https://codegolf.stackexchange.com/a/258369/55372).
[Answer]
# [Haskell](https://www.haskell.org/), 30 bytes
```
f a=filter(`notElem`a)[1..]!!0
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00h0TYtM6cktUgjIS@/xDUnNTchUTPaUE8vVlHR4H9uYmaebUFRZl6JSpoKSNQ49j8A "Haskell – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), 6 bytes
```
ṀŻ‘ḟ³Ṃ
```
[Try it online](https://tio.run/##y0rNyan8///hzoajux81zHi4Y/6hzQ93Nv3//z9a11BHQdcEiM1jAQ)
### Explanation
```
ṀŻ‘ḟ³Ṃ # | [-1, 0, 1, 4]
Ṁ # Maximum | 4
Ż # Range from 0 | [0, 1, 2, 3, 4]
‘ # Increment | [1, 2, 3, 4, 5]
ḟ # Filter out items |
³ # In the input | [2, 3, 5]
Ṃ # Minimum | 2
```
[Answer]
# [Perl 5](https://www.perl.org/) -ap, 20 bytes
```
1while++$i~~@F;$_=$i
```
[Try it online!](https://tio.run/##K0gtyjH9/9@wPCMzJ1VbWyWzrs7BzVol3lYl8/9/XVMFXRMFXWMFXSMFXUMFAwVDBSMFYwVTBXMFQ4N/@QUlmfl5xf91EwsA "Perl 5 – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
@øX}f1
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QPhYfWYx&input=Wy01LCAtNCwgLTMsIC0yLCAtMSwgMCwgMSwgMiwgMywgNSwgNywgMTBd)
```
@øX}f
@ }f # first positive integer where the following is false:
øX # the array contains the integer
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 14 bytes
```
{(~^x?)(1+)/1}
```
[Try it online!](https://ngn.codeberg.page/k#eJxtj7FuwjAQQHd/xVXqAKqNc3aiQDx07tSlG6JqFJzEIsQ0NlUQKt9eG5DSgc137/klrovz7PI5vs5n+DLn+EuIL87P69NlKGoAGNWX3anZV12aTo3qpIb5JjprBAFSpZtwlJACQ0Al4pTDElaAYRYK44JlwIIggYmoJXC9ChnkgMmt8JTcVbyqeZwIJ633B1dwXtmtbmxXL5wvq50eq7bsG72o7J5/H7XzxvaOi2wpZcZdawcfdixeYt6y2vRb5lvN3L7sukj2xjnTN+xgnfHmRzPTe93ogZCPgKEqnXaEvPWHoy9gjRQEBbkh70d/3aQTkxRSGh5FAScuJp5TWFJYBRwVMTk4OSwLhVgJMSZutSTYt89SCDhkMHn4A4+LeC/m//EfdIGGxw==)
Sets up a while-reduce, seeded with `1`, that proceeds to the next iteration (adding one) if the current value is already present in the original input.
[Answer]
# [Desmos](https://www.desmos.com), ~~70~~ 65 bytes
```
j=join(x,0)
l=[isgn(i-j)^2.minfori=[1...j.max+1]]
f(x)=l[l>0].min
```
[Try it on Desmos!](https://www.desmos.com/calculator/h0e9etscpj)
-5 bytes thanks to [Aiden Chow](https://codegolf.stackexchange.com/users/96039/aiden-chow).
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), 22 bytes
```
for(;++$i-in$args){}$i
```
[Try it online!](https://tio.run/##VZBRS8MwFIWfm19xH4JrWAJrp0yRQWDoq@J8E5Eab11HXWaSolD72@stTYe@Jec73wnkaL/Q@R3WtTLWYc/LdduX1qXX8zmvVHXghXv3ou141XeM6ZQlUqc6zSTkEpZCwrmI0ZLOEhSRjOJ8ilcSLiVcUTqQXAw4InVB/cEhVeWjuyA@bksgTHa2@PvKPz@L/mpMBfzArXU3hdmpu9c9mgAtS3hAHzaFRwkcv4@U4husgb8QcuibOtDtjJegpyJLnu63m8YH@zHOPGvaSbaNMej94J52FH5CXKHGYxwYKtMYqL2tDjCTMyo8TO@dnI7Rt/a/ "PowerShell Core – Try It Online")
Takes the input array using splatting, returns an integer
[Answer]
# [Julia 1.0](http://julialang.org/), 26 bytes
```
>(x,i=1)=i∈x ? x>i+1 : i
```
[Try it online!](https://tio.run/##Zc0xDsIwDIXhnVO8EYQj1WlRAcmBeyCGDgxGTJRKmTr3nFwkuA1DpK7@7N/P4aUdx5TCNpIK70S/0xRxQQy6Z5yhaRSEzbXr@8f7g/HGBE@o7xBBU8xrQkNwxryYL6wlHAkno5n94ly4O9jlfG0R53Olss38imBsCa5WT9cl/pfaTOkH "Julia 1.0 – Try It Online")
[Answer]
# [Julia](https://julialang.org), ~~36~~ 33 bytes
```
~x=argmax(!in(x),1:1+max(0,x...))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700qzQnM3HBgqWlJWm6FjcV6ypsE4vScxMrNBQz8zQqNHUMrQy1QVwDnQo9PT1NTajCHQ6JxcWpRSUKddGGOgpGOgrGsQq2tgomXAhxYx0FEx0FXaC0IVjOCEnOXEfBQkfBEigFkjYCyxsiyeuaAnWCdAMN0TWCmGIAVAmxSkcBKA00wtAAw1JMkwyhJplDpCDuh3kYAA)
Returns the first index of range [1,max+1] that isn't in the input. To accommodate the empty list, the input is padded with `0`.
* -3 bytes thanks to MarcMush: replace `findfirst` with `argmax`
* -2 bytes thanks to MarcMush: replace`0∪x...` with `0,x...`
[Answer]
# Excel, 61 bytes
```
=@LET(a,A1#,b,SEQUENCE(MAX(a,-a)+1),SORTBY(b,XMATCH(b,a),-1))
```
Input is spilled array `A1#`.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 6 bytes
```
`@Gm}@
```
Try it at [MATL Online](https://matl.io/?code=%60%40Gm%7D%40&inputs=%5B-1%2C+-4%2C+-7%5D&version=22.7.4)! Or [verify all test cases](https://matl.io/?code=%60%0A%60%40Gm%7D%40%0A%5DDZxT&inputs=%5B1%2C+2%2C+3%5D%0A%5B3%2C+4%2C+-1%2C+1%5D%0A%5B7%2C+8%2C+9%2C+11%2C+12%5D%0A%5B-5%2C+-4%2C+-3%2C+-2%2C+-1%2C+0%2C+1%2C+2%2C+3%2C+5%2C+7%2C+10%5D%0A%5B%5D%0A%5B-1%2C+-4%2C+-7%5D&version=22.7.4).
### Explanation
```
` % Do...while
@ % Push interation index, 1-based
G % Push input
m % Ismember. Gives true or false
} % Finally (i.e. execeute when exiting the loop)
@ % Push iteration index
% End (implicit). A new iteration is run if top of the stack is true
% Display (implicit)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~13~~ 10 bytes
```
I⌊⁻…·¹⊕Lθθ
```
[Try it online!](https://tio.run/##FYq7CoAwEMB@peMV6iC6OToJCuIqDqUetdCe2Nfvn7okEGIuHc2tPfMaHWUYdcqwOHKhhN8lwUTGl@QqbposQqvEVyIGpIwnzEg2X/BIKZX4KQfmfe@U6JVovrk9Dm6qfwE "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Now a port of @GammaFunction's jq answer.
```
…· Inclusive range from
¹ Literal integer `1` to
θ Input list
L Take the length
⊕ Incremented
⁻ Set difference with
θ Input list
⌊ Take the minimum
I Cast to string
Implicitly print
```
Would have been 6 bytes if the input had been guaranteed to be a nonempty list of positive integers:
```
I⌊⁻⊕θθ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzczLzO3NBdElxZreOYlF6XmpuaVpKZoFGrqKBRqAoH1///R0YY6CkY6CsY6CqY6ChY6CobGsbH/dctyAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
θ Input list
⊕ Vectorised increment
⁻ Set difference with
θ Input list
⌊ Take the minimum
I Cast to string
Implicitly print
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~5~~ 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
∞IKн
```
[Try it online!](https://tio.run/##yy9OTMpM/f//Ucc8T@8Le///jzbUUTDSUTCOBQA "05AB1E – Try It Online")
*-1 thanks to @KevinCruijssen*
#### Explanation
```
∞IKн # Implicit input
∞ # Push the infinite list [1, 2, 3, ...]
IK # Remove the elements of the input
н # First item
```
Old:
```
∞å0k> # Implicit input
∞ # For each number in the infinite list [1, 2, 3, ...]
å # Is it in the input?
0k # Get the index of the first 0 (0-indexed)
> # And increment it to make it 1-indexed
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
@øX}f1
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QPhYfWYx&input=Wy01LCAtNCwgLTMsIC0yLCAtMSwgMCwgMSwgMiwgMywgNSwgNywgMTBd)
```
@øX}f1 :Implicit input of array U
@ :Function taking an integer X as argument
øX : Does U contain X
} :End function
f1 :Get the first integer >=1 that returns false
```
[Answer]
# [Python 3](https://docs.python.org/3/) NumPy, 31 bytes
```
lambda a:min({1,*a+(a>0)}-{*a})
```
[Try it online!](https://tio.run/##PY5BDoIwEEX3nuLvbHUwFDSoCVxEXYxRIomUptYFIZwdBxG7mzfvTera8GhsOpT5eXhyfb0x@FhXVnWGVrxWXMS6j7oV93qoatf4APuuXQvwC9YtysYj3F8BlYVaQN7JEBJCeqFpTAlbQiTUzCgj7AkHISNNZhztxBtdSaJkamIRpnsEWUtp4tn/d@bXZUL08Qudr2xQ5bIbP9cjL9CVyroNe8@tGqHW/VIPHw "Python 3 – Try It Online")
Expects a numpy array.
## How?
Returns 1 if that's not in a and otherwise the smallest successor of a positive number in a that's not in a.
] |
[Question]
[
Given a string which is guaranteed to be either `odd`, `even`, `square`, `cube`, `prime` or `composite`, your program or function must return an integer \$100\le N\le 999\$ which meets this description.
## Rules
* Your code must be deterministic.
* The choice of the integers is up to you. However, the six answers **must be distinct**. (For instance, if you return \$113\$ for *odd*, you cannot return \$113\$ for *prime*.)
* You may take the input string in full lower case (`odd`), full upper case (`ODD`) or title case (`Odd`) but it must be consistent.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'").
## Example
Below is an example of valid I/O:
* odd → \$501\$
* even → \$140\$
* square → \$961\$ (\$=31^2\$)
* cube → \$343\$ (\$=7^3\$)
* prime → \$113\$
* composite → \$999\$ (\$=37\times 3\times 3\times 3\$)
## Brownie points
For what it's worth, my own solution in JS is currently 24 bytes. So, brownie points for beating that.
**JavaScript (ES6), 24 bytes**
```
MD5: 562703afc8428c7b0a2c271ee7c22aff
```
***Edit**: I can now unveil it since it was [found by tsh](https://codegolf.stackexchange.com/a/230397/58563) (just with a different parameter name):*
>
>
> ```
> s=>parseInt(s,30)%65+204
> ```
>
>
>
>
[Answer]
# [Python 2](https://docs.python.org/2/), ~~25~~ 22 bytes
```
lambda s:hash(s)%591^1
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHYKiOxOEOjWFPV1NIwzvB/Wn6RQnl@UYpCZp5CtLq/i4u6joK6a5irH4gODgx1DHIFsZxDncB0QJCnL0TA3zfAP9gzxFU91opLQaGgKDOvREFdVdfQoFhB105BNUVdQVVBA2SyjkIamNbU/A8A "Python 2 – Try It Online")
Takes input in upper case and returns the following numbers:
```
ODD -> 263
EVEN -> 554
SQUARE -> 121
CUBE -> 512
PRIME -> 349
COMPOSITE -> 371
```
Generated with this script which searches for formulas following `hash(s)%x?y`, where `?` is any binary operator:
```
from sympy import primerange
# from tqdm.notebook import tqdm
hashes = [
3275334880723988284, -8482906173967949472, -4710393751006474557,
1654718638908055491, -6487253012923789248, 8925015453505786600
]
dyads = {
int.__mul__, int.__mod__, int.__add__,
int.__sub__, int.__rshift__, int.__lshift__,
int.__xor__, int.__or__, int.__and__,
int.__pow__, int.__floordiv__
}
primes = set(primerange(100, 1000))
squares = {x**2 for x in range(10, 32)}
cubes = {x**3 for x in range(5, 10)}
# for x in tqdm(range(6, 1000)):
for x in range(6, 1000):
for y in range(1, 100):
for z in dyads:
a, b, c, d, e, f = r = [z(h%x, y) for h in hashes]
if (
len(set(r)) == 6
and min(r) > 99
and max(r) < 1000
and a%2 == 1
and b%2 == 0
and c in squares
and d in cubes
and e in primes
and f not in primes
):
print(x, y, z)
```
[Try it online!](https://tio.run/##dZPtbpswFIb/@yqONFWCyquMP7AdLbuRqUIkwEALmBqyhVS99sx2ykhT5h/AOc97jj9e009jbTp2uVTWtDBMbT9B0/bGjtDbpi1t3v0sEfoCgY8vRfvUmbHcGfNr1vkkQnU@1OUAW/iBwA1GpWCMK0UkZVopqjiGr4orqkmaSKZTqbnmkroslwlhmkmREJJyyYWQODRJUuGYSpnSRBEhuE6cPOVKUsFIQjVlUmnKFQb3EiQRXDBBhFRpSgh6RqiY8sIv6jX0a7rxKcva4yHL8ByYYgnywgc30uG4W6gd6qYal/gwxzcFJ2MXwe133t217s2fhVYHY2zR/M4y9IZQOHi/6qEco8WFyB0PBvcgcYyGl2Nug@j19PhIoTIWTq4bzFLsLIjf0P64@6di9yrh2zmRt3cm3s3oitN5tg26K5zJJmzIw@lm7gDf2czPngc3lrwfOYYdhj2GAkOJoXJLtf4SnaP64YRhikN17auvN@z5Q3lTQfQh4ceh7CJ/dDaOYbuF9JPAmQFt0zkBfAet13l@8vxb2OiqIn@gvn2yCndXuF6599t5d3BVUHhBsG4Vlx5fb8kqr8D9o//RxJtPJU7VjZE/bQzn@HL5Cw "Python 3 – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 29 bytes
```
n=>121+'qvdou r'.search(n[1])
```
[Try it online!](https://tio.run/##JYyxDsIgFEX3fgUbJSoJrg3d/IqmA8JDMZRHobAYvx1rnc45d7gvVVXWycXtEtBAs7IFOYqrONG1GiwkUZ5BJf3swyRm1oZuomgMPRMak1vgJxqXiNlt/yj3g3ktKh0GFQKducV0U/sPeCJH8u40howeuMdHb/eVsaH7sPYF "JavaScript (Node.js) – Try It Online")
## How?
I found six numbers which were close to 121, then simply placed them strategically.
And also thanks to Arnauld for reminding me of the `search` method.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 10 bytes
Takes in the input in full upper case. Sum of the character code points times 415 mod 998. A sum-less version would multiply the second element with 493, modulo 583.
```
ạ+×₄₁₅%₉₉₈
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@GuhdqHpz9qannU1PioqVX1UVMnGHX8/6/kHOrkqvQ/AgA "Brachylog – Try It Online")
```
┌───┬────┬──────┬────┬─────┬─────────┐
│ODD│EVEN│SQUARE│CUBE│PRIME│COMPOSITE│
├───┼────┼──────┼────┼─────┼─────────┤
│403│580 │361 │343 │431 │339 │
└───┴────┴──────┴────┴─────┴─────────┘
```
Found with this crude J script, typing in the operations manually:
```
NB. returns 1 iff correct solution
test_f =: =@i.@# ([ -: *) [: (1 = 2&|)`(0 = 2&|)`((= <.)@%:)`(3 (= <.)@%: ])`(1&p:)`(1 < #@q:)`:0 [:(**/@~:) (* <&1000 * >&99)"0
NB. try some variants
vars =: ,/ (a=:i.1000)|/ (b=:i.1000)*/ (1#.3&u:)&> ODD`EVEN`SQUARE`CUBE`PRIME`COMPOSITE
NB. show valid solutions
(((,/a,"0/b),.&<"1 [) #~ (test_f :: 0)"1) vars
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~22~~ 21 bytes
```
lambda x:628*x[2]%831
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHCyszIQqsi2ihW1cLY8H9afpFCsUJmnkKSur@Li4JrmKufQnBgqGOQq4JzqJOrQkCQpy@Q6e8b4B/sGeKqrldckJNZoqFpxaUABAVFmXklGsV6KanJ@SmpGpo6Ckq2dko6CmkaxZqa/wE "Python 3 – Try It Online")
Takes input in uppercase as a byte string. Takes the penultimate character's code, and applies some hashing to get:
```
ODD => 323
EVEN => 120
SQUARE => 196
CUBE => 729
PRIME => 139
COMPOSITE => 158
```
Found using this brute-force program:
[Try it online!](https://tio.run/##pZVLbxoxFEb3/AqLKhJU02rGbyOxaBMWWaSkoemGsiAwKSOFRxho1SB@O51jCFHVR6RmFleee@3j77PvwOLHajKfqd3u8ur8otMTbbHJ0iwRWaoIjhCqkPEqeVVUVRxR0ARDzpCzzLOMHCNH1VMNMZALVENVkFmVk1IRHIGc4hWy1FRNDFQhS0vBkXPkIEtPAbJCrgKqkKsyXpGrkKt0DBVAGaqGEUoVShVKFSjlGSFScxAa@zojSF5VDIpATjMCqhGpLVWUasgaqPaMsK8xbThYA9TAM9g3WDXoM1AMAINVg1WDVQPF4NJAsUiz@LVYtVkcUUCf1TFQAGrxa/Fr0Wfxa4Fa/FqkuTSGaoqD4rgPh0uHSwfKcRUOfQ6KQ58D5ZDmODAPwHMBXsagCBS4Wg/Ko8VD8QjyWPVo8dylR5CHF/AWQAUEBQCBawx4C9gKoALnHDimACUACDgKwW1rvY/X7672XS2NhZrSspprTTl8PHhNE3E6ztK88VrjubPCxr6tRkpW8zwFFxtVGr6NlAvWdBInK822dnr9/vAdMUNmLOX8TCbj0m2tdjtfip4oZqJfE9VzUx@tb3JR3q@Hy1wslsU0F6P5dDEvi1Uu5uOxyL/ls/rbcnFXrBrN5LCIjcTeoYhfrzjtXlx2e@efOqJ7diY6nzsffl/ETr39Tpdxp9PjTt1qp86vOw1acR2CiyiYDy4Rb@SgJcQrsZrkVXacj/JSfJ8Uo0mlfj5ej3KxnhX361x8G96t8zIyePCZHIwme6fJk9UEr0k0W51f/6FfDOLOD@zcGxwp5Epyy@Hsa96Iv1Zp2mwdJzxOmj436fEpbsWXPxZ4GqV4HW/hREybVZD/mDucjZ8jRXtHVLst0v/mgYutc7K3um@9l9AOPXjgPX4@LyHu2/kAPPzJvMjvsV1hzuarJ27rrwt5KiGzVeO2XrQ3xVaU7U25FdP2ZroVo2GZtze9fjrY1pu73U8 "Python 3 – Try It Online")
PS: I retract my downvote. Writing and optimising various brute-force programs was actually quite fun. (I don't think it's great to have too many challenges like this, though)
[Answer]
# [Rattle](https://github.com/DRH001/Rattle), ~~21, 20~~ 18 bytes
```
|Ig1n+8s%7[3g+5s]g
```
[Try it Online!](https://www.drh001.com/rattle/?flags=&code=%7CIg1n%2B8s%257%5B3g%2B5s%5Dg&inputs=square)
This is my first ever answer with my own interpreter running on my own website!!!
# Outputs
```
odd: 113
even: 126
square: 121
cube: 125
prime: 127
composite: 119
```
# Explanation
```
| takes the user's input as a string
I splits this string into characters and stores them in consecutive memory
slots
g1 gets the character at index 1 (2nd character, Rattle is 0-indexed)
n converts this character to its ASCII code (int value)
+8 adds 8 to this value
s saves this value to memory at the current pointer
%7 takes mod(7) of the value on top of the stack. This gives three for
inputs of "prime" and "odd" (which are special cases)
[3 .... ] if the value on top of the stack is three, the code in this if statement
executes
g gets the value from memory at the pointer
+5 adds five to this value to fix the special cases
s saves the result to memory
g gets the value saved in memory, prints implicitly
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~8~~ 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 thanks to [the default.](https://codegolf.stackexchange.com/users/36445/the-default) (looked for shorter salt/domain combinations with domains other than the one byte `1000` I'd considered and the different case formats allowed in the OP.)
```
91,651ḥ
```
A monadic Link accepting a list of characters that yields an integer:
```
input output (notes)
odd 897
even 516
square 625 (25²)
cube 125 (5³)
prime 347
composite 752 (2⁴×47)
```
**[Try it online!](https://tio.run/##y0rNyan8//9Rw5xDix7u6H24o@tRw0ydE9sf7lj6/3D7o6Y1//9Hq@enpKjrKKinlqXmgejiwtLEolQQK7k0CUwXFGXmQgTycwvyizNLUtVjAQ "Jelly – Try It Online")**
### How?
```
91,651ḥ - Link: list of characters, S
, ḥ - hash (S) using...
91 - ... salt: literal = 91
651 - ... domain: literal 651 (i.e. a domain of [1..651])
```
The salt for the 8 byte version, using a domain of `[1..1000]` and only the lower-case version of the inputs, was found using this Python code ([Try it online!](https://tio.run/##lVTbjpswEH33V4yQKtlZNgICJF0p@yNRhMhigrVgUtukjap@e@oLyy0Pq/gFPHPOmStcbqpq@eZ@Z82lFQqqXFY1OyFUirYBeWsuN@hdTF4EayhCqKAlNDnjmLwh0KctCgl7kFRhkfMzxWEQ@hAGQeBDRIjF0CvlS1CwBNkAXyhn@mh1dMnUwly2AjgwDgutPiNzWPmVMuYT8xhnnReFdg0eWks6x43Bp1j5q8uFzecvh9UKosdsfNhE5J8roDtNsJslNtF5hz30mtedxR483VLPB890zTxdSPNm5MzTlmANXzl6RytStGY0WU35WVVay3TFNTcXyooPJR5mxTKu1mbq2emmC8Yznzn9aqxllX/SLEpSLOhF4JpJha@ErCn/aAuKvU6VrztPGwp2ptqXhBE5MHgDBi@wO/oPwl7NlKp1MTMPmd1M19jYNd1gLevDbkQd0RR7NVjXTzR6ZV4r0xJ7@V2xmkI4W5h51VXJse2ab5n@vLd6xsREsQOe8XJefMuNLLdfpafZsWW7NX6anLi0h91@WiC0AvaLfpobWK75YwzUx4@TK2xH9apDzXwnQfPPwWIxL2ae7p/0XWy7DxnjBf3TxxRUdYJPxi67Zr4D2GXy/g6M6HzGm17mkBBYue/qMNE@HthxubBpPBYyvv2AcBfH6TaOg@1mG/xMkjAN08G9mhcw2HX4NEZOCiG9tlnG84ZmGez34GWZ5WSeK9H9qNH9/h8 "Python 3 – Try It Online")); it can easily be modified to search other domains and to go through the three allowed case formats:
```
import hashlib
from sympy import isprime
def main():
odds = set(range(101, 1000, 2))
evens = set(range(100, 1000, 2))
primes = set()
composites = set()
for n in range(100, 1000):
if isprime(n):
primes.add(n)
else:
composites.add(n)
squares = {n ** 2 for n in range(10, 32)}
cubes = {n ** 3 for n in range(5, 11)}
values = ["odd", "even", "square", "cube", "prime", "composite"]
domain_length = 1000
parts = [
[
int.from_bytes(
hashlib.shake_256(repr(list(v)).encode("utf-8")).digest(512)[i : i + 8],
"little",
)
for i in range(0, 512, 8)
]
for v in values
]
salt = 1
while 1:
if (
hfn(parts, salt, domain_length, 3) in cubes
and hfn(parts, salt, domain_length, 2) in squares
and hfn(parts, salt, domain_length, 4) in primes
and hfn(parts, salt, domain_length, 5) in composites
and hfn(parts, salt, domain_length, 1) in evens
and hfn(parts, salt, domain_length, 0) in odds
):
print(salt - 1)
break
salt += 1
def hfn(parts, salt, domain_length, value_index):
return (
sum(
((salt >> i) - (salt >> i + 1)) * parts[value_index][i] for i in range(64)
)
% 18446744073709551616
* domain_length
>> 64
)
if __name__ == "__main__":
main()
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 28 bytes
```
n=>122+'vdou r'.search(n[1])
```
[Try it online!](https://tio.run/##JYyxDsIgFEV3voKNEpWkXRu6@RVNB4SHYigPobAYvx1rnc45d7hPVVXWycXtEtBAs7IFOfXDcGLVYKGJiQwq6UcX5n7hbSQzQ2PYmbKY3Ao/0bhGzG77R7kdzK@i0mFQIbBFWExXtf@Ap3Kib6IxZPQgPN47u6@cj@TD2xc "JavaScript (Node.js) – Try It Online")
All credits go to Recursive Co., I would have commented but since It's my first time on posting on stackexchange I don't have the reputation for that.
When search doesn't find anything it return -1, making it possible to remove q and saving one byte.
[Answer]
# JavaScript (ES6), 24 bytes
```
x=>parseInt(x,30)%17^212
```
[Try it online!](https://tio.run/##hVNdb5swFH3nVxxVSWu3HiJEy7Sl9CXKw54SKcpT1SgEzGaUGIYh7Rbx2zODR@pGSENC3I9zry/nXKfhMVRRIfLyk8xifk6C81vwlIeF4t9lSd7Y2KPD0ZeNP/LPUSZVtufuPvtBEnKTxfENpVPnKsyPXPbF1a8qLHhfJqp2vfG8EIf@guyQZ0qUJuksAslfseIl0d7cdla2s7adpe3MbCfJChCBACPPm0LgsTEa6@GB4uQAImnyQ/gINIhi4YZxTIQuvcp5FPNLrrYbm75j3@q6Mkjc4wr9uRvCAq878D3GLTqPvuG/g7eAVAP0ualOC/3pcu@jp/9GN1FgZv1e82gtSiErjjwyodox79L6V@cY7kWsj0oqGZUikyCyOux4oUzjgpdVIfG8YJgzrBjWDEuG2Yur16f4TUjCNA8InpC4P0PVFT@LF0pxe9ue22nWNXaV@MP18AEmegS9F69ZESs9w1ZvKkOzlwxmCxmanWNoN0w73T5tXZXvRUnuGO6oYzTYhYo3nH2dojUfA4wnxv5ArDDE9vBuMT/yJoZ7v4VY9BsBWtpIO7h7CHMSNRRcbmPE2mOpVklgg5TS9@pWmMsl2X68xINTU1fT4eAk6s3glNZ0exG0tlSsnfNf "JavaScript (Node.js) – Try It Online")
Some other 24 bytes
```
x=>parseInt(x,30)%65+204
x=>parseInt(x,33)%37+497
x=>parseInt(x+87,35)%349
```
---
# [JavaScript (Node.js)](https://nodejs.org), 22 bytes
```
x=>Buffer(x)[3]%29^115
```
[Try it online!](https://tio.run/##hVPbbuIwEH3PVxxV0NqtN@KiVtpt04dFPIOEeEIg0sTZdQRJ1klod1G@nU7ihroo0iJFzOXMeHzmOPYPfh5olRXfkjSUp8g7vXnPP8sokpq98dV43R993wyH96cgTfJ0J91d@otF7CoNwyvOH52LsDzIpCue/yl9LbsyQfnSGc@02ncXpPsszVVhks7MS@QrFrJg5E1tZ2E7S9uZ287EdqJUgyl4GA4Gj1B4qo3aurvjODqAiup8HyN4BOKYuX4YMkWlF7kBx/Scq@zGpu94ZHVdGCRucYG@b4ewwMsWfItxg86CH/jv4A0gJgCdG1Na0V@b@xw9/hjdRIGJdb36R7soVFJKZIEJVY755tZdnYO/UyEdFZVJUKg0AUvK/YvUuWmsZVHqBKuZwFRgIbAUmAtM1i7JR/9lLBLEA7xnRO5vP2@LV2rNOa6vm3PbnbWN3Vz9kzS8hwcagXTxmuowpxm2pFSBWpcCRoUCteYEGoWR0@pp6@bZThXsRuCGO2YHlDGU1caTh3FjfeFUGUAH5Rbpw8GDoX3UQCzmDfcNY6yZ2d37GQvq2388w4Cv6Mw1bUdhg5jzz9JmIefHsf3ydHtHqqrW/d5RVZveMa625y1W1uoq5/QO "JavaScript (Node.js) – Try It Online")
Some other 22 bytes
```
x=>Buffer(x)[3]%87^115
x=>Buffer(x)[3]%89^113
x=>Buffer(x)[3]%55^115 // UpperCase
x=>Buffer(x)[3]%57^113 // UpperCase
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), 22 bytes
```
s->150-s.hashCode()%30
```
[Try it online!](https://tio.run/##NY5Ba8MwDIXv@RXCEHCGY1LGLutWKIOdtlN3Gzu4sZM6TWzPkgNl9LdnbrsdhPTQ09M3qFnVgz4udgo@EgxZy0R2lF1yLVnv5N26aEeFCO/KOvgpAELaj7YFJEW5zd5qmPKO7yha139@gYo9VlcrwId/865//Ut7unk20MHzgvVm9dDUKA8KDy9eG16V982yvt51PgKfVQR8BOa1FmY2TuB3UtGINu2NCNFOefSZHC0ZJjGMljgTrPp/DrA7IZlJ@kQy@x11nJWrJmeWunRMAAropAphPG3xAsqxqm4A5@JS5@UX "Java (JDK) – Try It Online")
## Outputs
```
odd: 139
even: 140
square: 169
cube: 125
prime: 149
composite: 155
```
## Alternate
```
s->160-s.hashCode()%50
```
[Try it online!](https://tio.run/##NY5Ba8MwDIXv@RXCEHCGY9LDdli3QhnstJ2629jBjZ3UaWJ7lhwoo789c9vtIKSHnp6@Qc2qHvRxsVPwkWDIWiayo@ySa8l6J@/WRTsqRHhX1sFPARDSfrQtICnKbfZWw5R3fEfRuv7zC1TssbpaAT78m3f961/a082zgQ6eF6w3q4emRnlQeHjx2vCqvG@W9fWu8xH4rCLgIzCvtTCzcQK/k4pGtGlvRIh2yqPP5GjJMIlhtMSZYNX/c4DdCclM0ieS2e@o46xcNTmz1KVjAlBAJ1UI42mLF1COVXUDOBeXOi@/ "Java (JDK) – Try It Online")
## How
Brute-forced with this code:
```
import java.util.*;
class Main {
private static long[] cubes = computeCubes(100, 1000);
private static long[] squares = computeSquares(100, 1000);
private static long[] primes = computePrimes(100, 1000);
public static void main(String[] args) {
for (int o = 0; o <= 1000; o++) {
for (int m = 2; m < 10000; m++) {
if (test(o, m)) {
System.out.printf("o = %d, m = %d%n", o, m);
System.out.printf("odd: %d%n", f("odd", o, m));
System.out.printf("even: %d%n", f("even", o, m));
System.out.printf("square: %d%n", f("square", o, m));
System.out.printf("cube: %d%n", f("cube", o, m));
System.out.printf("prime: %d%n", f("prime", o, m));
System.out.printf("composite: %d%n", f("composite", o, m));
System.out.printf("%n");
}
}
}
}
// static long f(String s, int o, int m) {
// return o + s.hashCode() % m;
// }
static long f(String s, int o, int m) {
return o - s.hashCode() % m;
}
static boolean test(int o, int m) {
var odd = f("odd", o, m);
var even = f("even", o, m);
var square = f("square", o, m);
var cube = f("cube", o, m);
var prime = f("prime", o, m);
var composite = f("composite", o, m);
var values = new long[]{ odd, even, square, cube, prime, composite };
var result = Arrays.stream(values)
.filter(v -> 100 <= v && v < 1000)
.distinct()
.count()
== 6;
result &= odd % 2 == 1;
result &= even % 2 == 0;
result &= Arrays.binarySearch(squares, square) >= 0;
result &= Arrays.binarySearch(cubes, cube) >= 0;
result &= Arrays.binarySearch(primes, prime) >= 0;
result &= Arrays.binarySearch(primes, composite) < 0;
return result;
}
private static long[] computeSquares(int min, int max) {
var minSqrt = (int)Math.sqrt(min); if (minSqrt * minSqrt < min) minSqrt++;
var maxSqrt = (int)Math.sqrt(max);
var squares = new long[maxSqrt - minSqrt + 1];
for (int i = 0; i < squares.length; i++) {
var sqrt = minSqrt + i;
squares[i] = sqrt * sqrt;
}
return squares;
}
private static long[] computeCubes(int min, int max) {
int minCbrt = (int)Math.pow(min, 1/3d); if (minCbrt * minCbrt * minCbrt < min) minCbrt++;
int maxCbrt = (int)Math.pow(max, 1/3d);
var cubes = new long[maxCbrt - minCbrt + 1];
for (int i = 0; i < cubes.length; i++) {
int cbrt = minCbrt + i;
cubes[i] = cbrt * cbrt * cbrt;
}
return cubes;
}
private static long[] computePrimes(int min, int max) {
var composites = new boolean[max];
composites[2] = false;
var primes = new long[max];
var primeCount = 0;
for (int i = 2; i < max; i++) {
if (!composites[i]) {
for (int c = i * i; c < max; c += i) {
composites[c] = true;
}
primes[primeCount++] = i;
}
}
var minPos = Arrays.binarySearch(primes, 0, primeCount, min);
var maxPos = Arrays.binarySearch(primes, 0, primeCount, max);
return Arrays.copyOfRange(primes, minPos < 0 ? ~minPos : minPos, primeCount);
}
}
```
[Try it online!](https://tio.run/##lVZNb9swDL3nV3ADUti146YdsMPcbBh6HjYsxyIHxVYadf7IJDlbMWR/vaM@LMuuk6U5xBb1@ERST5QfyZ7MHvMfz8@s3NVcwiMakkayIrlMJ5OsIELAF8Iq@DOZAOw42xNJQUgiWQZFXT3cryBr1lTAArK63DWS3qlhcD2fx4B/8zA96ih@NoT7rktjOMsZraXv@02Pe67Kt1kX6GNd9zXLocR0gqXkTNMQ/iBCzA7wt6k5BKySUCPtPMXH7UJz4WsUtSgPVyLuJsXHrYYhrvRxAGwDgaRCBnUMZejPACyfhKRlUjcywVwquQneqnWneax5p/m0ehuDdtSpnPLL8w@tgw1RG93QLJ@eZqF7WvVprLEdnsViNtXncUYzPItFaepFLMr4qli0Rno0rdEOz4sFBVYLJjsm39ju0f9Y0NGDHCb@U/0fJpOrK/BFjssYmYKIQcvSPEqlI4UF4FQ2vEKhRiCSLRHbuzqnQQhTKFMNOSjlnMvZY5yNMPb51nVdUFKBFvgY155wQBWimI@LMnVIpbQWOia8DmnUZLBj4uqQSjEe5wsBdUitCgsdE4nH2e48oseEYA@rgu5J0egeVdFftm/9URWJdbKxTSTWYcYmhNjjP5hFHR22xqaQSPeZc/IkEiE5JWVgVgk9@blfsmGFpDzYw@yjalGqoe3h4gL/TMsa98qZkKzKZDA@ndVNNTq3WMB7L2Yb78VCq2AKNwpwnQ7m9L7byflw0ma6ZhXhT0tKeLYN7LXRli@Ej2c66ovKVPt8J3PP2N15vZvbzRArPrfasIfMMLhjdeR27V@N@oCxyp408ts/a2hf/uRKIAoWfiFymwg0BDgRpvoyaiGXDnyr3sJ2GEWd0JH9CB0uOzyNPZW3njO3SgTXq7R/yTJzyTKMwFIkBa0e5BZt/i1q1tBxdGysbaXW9Z6tcF6Y1NQjnXTt1ZbbQk29/1Nu8xFzrNjWfrceVGdX/wo0/vrqXd5VXOMu4eVbV3s1bGtvFxtnJ79b9l6TG5ZfO8/cQqfLrwnGi6@Q2botvuVyxdeOpvSZycx7jOyAxp9Vf/s1d0rt7mS1udv7SKVvk@0g9zcqyA0pBB30/GHlVoP5O9XswJ36Xv1uTP3Qa1g23Pg33ups5X/7OY4MORiWi6X4ankyiNDY/1T0mDKVh@QNffktATah@y7uKFJwt18Hb0tsw/hWCzjdweaxV4hYK7bXI17P4NqHlYX1zerd09fNd1I9UOdqI8TWCZ/grx19sGafNjSyOjw//wM "Java (JDK) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 42 bytes
```
lambda s:sum(s[:-1])-2+6*(81in s)+(77in s)
```
[Try it online!](https://tio.run/##HcbLCoJAFADQfV9xceOdfIAFGYJB5SxcmOajTbXQxiHBF15b9PWTdFZn/M7vod8q6T9UW3aVKIE8@nRId89ynszaGLs17p2mB2IGuu4/Sg4TECyv9DgIgN/4BbJrcUw5nIsThyQNo6VxlMRZmHPdprFtZmTeChbj1PQzki3q1yBqZCZo/kEzQSIxpn4 "Python 3 – Try It Online")
Takes input as `bytes` in uppercase.
Not as short as an [uninteresting clone of the current shortest formula](https://tio.run/##DclBCsMgFEXReVfxcBKlIWA7C6QbaTswVakQ/cavga7e5o4O3PyrX0r37pdX30xcrQHP@qavYj8sNRQx@ZCs5Kd@q@6pgBESBrIW7nAJvDdTHD5tdcglxJMUM3Gobpg4b6FKNV9wdt5UJY8Qy0OM8JKV6n8 "Python 3 – Try It Online"), and can very likely be golfed further, but I wanted to show a different approach.
My first instinct on seeing this challenge was to use `sum`, because you can sum a byte string in Python 3 and it's a useful quick method to do string lookups like this.
Cube numbers were definitely the hardest to get to behave with a sum, because there are only 3 practicable cube numbers in the region of the sums of the strings (\$ 6^3, 7^3, 8^3 \$).
I played around with different slices of the string and different input casings, and I found that `sum(s[:-1])` was promising:
```
ODD => 147
EVEN => 224
SQUARE => 396
CUBE => 218
PRIME => 312
COMPOSITE => 622
```
Subtracting 2 makes `216`, a cube, while keeping the rest. `396` is also very close to `400`, and the rest were pretty easy too.
`81in s` tests for a `Q`, and then `+6*()` adds 6 if there is one (abusing Python's weak interpretation of booleans). Similarly, `+(77in s)` fixes `PRIME` by making `311` instead of `310`. (I'm sure these bits can be golfed somehow.)
[Answer]
# [Python 2](https://docs.python.org/2/), 24 bytes
```
lambda s:hash(s)%853^702
```
An unnamed function accepting a string that returns an integer:
```
odd: 783
even: 832
square: 196
cube: 512
prime: 661
composite: 679
```
**[Try it online!](https://tio.run/##JY3NCsIwEITvPsVeJAkUEYuoAX0SEVKTkoD5aXYriPTZY1Ln8g0zMJM@ZGM4lPF6Ly/lB60ApVVoOYrt@dg/TvtaxgxkkMAF4CxqzTpg5m1CI06zyqa55zysTNn5fxB9iujIMCE3UFWbQMC@8nZZJFT0C9vVda@It4MOxpVClB8 "Python 2 – Try It Online")**
---
...or perhaps 21 in Python 3?
```
lambda b:b[2]**95%547
```
where `b` is `bytes` if that is allowed in place of a string.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~26~~ 25 bytes
```
lambda x:497+int(x,33)%37
```
[Try it online!](https://tio.run/##DYxBCsMgFAX3PcUjUKJUurEQGkhP0o2pSoXot35T0tNbZzUwMPlX35R088uzbSau1uCYb/fpElIVh9JanvXUPBUwQsJI1sJ9XQJ/dlMcXvvqkEuIXSlm4lDdeOW8hSrkfEKn1/5ihWF5DApesJTtDw "Python 3 – Try It Online")
*-1 thanks to ovs*
Converts the string to an integer in base 33, then does a bit of hashing.
Outputs:
```
odd => 509
even => 508
square => 529
cube => 512
prime => 499
composite => 522
```
Found using this brute-force script and a tiny bit of manual filtration:
```
PRIMES = {101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997}
SQUARES = {256, 900, 144, 400, 529, 784, 289, 676, 169, 441, 576, 961, 196, 324, 841, 729, 225, 100, 484, 361, 625}
CUBES = {125, 216, 343, 512, 729}
CUBE, SQUARE, PRIME, EVEN, ODD, COMPOSITE = "cube", "square", "prime", "even", "odd", "composite"
for s in range(800):
for b in range(32, 37):
for m in range(1, 10000):
if \
s + int(CUBE, b) % m in CUBES \
and \
s + int(SQUARE, b) % m in SQUARES \
and \
s + int(PRIME, b) % m in PRIMES \
and \
s + int(COMPOSITE, b) % m not in PRIMES \
and \
(s + int(ODD, b) % m) % 2 \
and \
(s + int(EVEN, b) % m) % 2 == 0:
print(f"{s} + int(x, {b}) % {m}")
```
[Try it online!](https://tio.run/##pZRNb9pAEIbv/hUrpEqg@mDv90bi0CYcckhJQ9JTLxCg5YBNgVStkH873WfNR6RGqkR9GMY7u4/ed2bN6vf2e12p/f7@4fZuMBJ9sSuLMhdloQiOEGIoeZW8KqoqZRQ0wbBmWLPss2SOzFH1VEMKrAWqIRZkGdekVARHYE3xCllqqiYFqpClpeBYc6xBlp4CZIVcBVQhV5W8IlchV@kUIkAZqoYMpQqlCqUKlPJkiNQ0QmNflwTJq0pBEVjTZEA1IrWlilINWQPVngz7GtOGxhqgBp7BvsGqQZ@BYgAYrBqsGqwaKAaXBopFmsWvxaotU0YBfVanQAGoxa/Fr0Wfxa8FavFrkeaKFOIWB8UxD4dLh0sHyjEKhz4HxaHPgXJIczTMA/AMwMsUFIECo/WgPFo8FI8gj1WPFs8sPYI8vIC3ACogKAAIjDHgLWArgAr0OdCmACUACDgKwTXZ6PPTh4f2VktjoRZcWc1YC5qPB6@5RHTHWS5vGmvqOydsurcxUzLu8xRcuqjS8G0UDFhzk@isNE12/fTx8B2xQ5YcpX@mlOlok6UtuWjF5SJ9ebkYfBl8ysXw5iYX18O7@@Ho9nEQMZ3nl8msk4vO5sfLeJ2y1XqxTMns56zit55O@Xmul6t6s9jOOlk2r9diIxaVWI@rb7OuL4reVSbiQ2FyLijJ3T/UjvXluZ7@CorT6dfPYi6@/rXIsxHvI2DbbW1OeuJdS2w78/aZcTX9B@3YrjPvON1LiYfGn4GH/8BLeaexnZhVvf0PbvcITpeiRRLk5aT2kr1G9fuiuHrzEE@8avHUvLPbNAfCr1zsJg1nd8um09vv/wA "Python 3 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
```
HƵ₅%₁+
```
[Try it online!](https://tio.run/##yy9OTMpM/a9cVmlokGWvpKBrp6BkX/nf49jWR02tqo@aGrX/6/zPT0lRSC1LzVMoLixNLEpVSC5NSlUoKMrMBTLzcwvyizNLUgE "05AB1E – Try It Online")
This computes `from_hex(input)%193+256`, found by the same script I used for my Python answer.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes
```
I﹪⁺⁴⁷⁰⍘Sγ⁸⁶⁶
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzc/pTQnXyMgp7RYw8TcQEfBKbE4NbgEqCBdwzOvoLQEytbUUUjXBBIWZmaamprW//8XFGXmpv7XLcsBAA "Charcoal – Try It Online") Link is to verbose version of code. Takes input in lower case. Explanation:
```
S Input string
⍘ γ Converted from base 95
⁺⁴⁷⁰ Plus 470
﹪ ⁸⁶⁶ Modulo 866
I Cast to string
Implicitly print
```
These constants were the only ones I could find that worked with lowercase inputs. There are other constants that work for title or upper case:
```
lower Title UPPER
+ 470 162 710 100 254 588 708
% 866 586 778 840 851 948 972
odd 327 155 401 723 683 671 659
even 206 400 750 278 286 386 470
square 729 169 529 529 361 841 841
cube 343 343 729 729 343 729 729
prime 269 397 457 659 467 919 571
composite 299 511 119 539 495 451 763
```
I also tried base 26 but I didn't find any solutions. I also tried "base 1000" which had one solution for each case: `+499, %837: 819 176 121 512 389 371` (lowercase) `+674, %703: 173 194 225 216 577 512` (title case) `+334, %667: 353 186 625 512 383 372` (upper case).
[Answer]
## Batch, 74 bytes
```
@cmd/cset/aeven=120,square=121,odd=123,cube=125,prime=127,composite=128,%1
```
Case insensitive. Explanation: Sets six variables and evaluates the input.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~24~~ ~~19~~ 18 bytes
```
Hash@#~Mod~619-90&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73yOxOMNBuc43P6XOzNBS19JA7X9AUWZeSbSyrl1atHJsrIKagr6DQrVSfkqKko6CUmpZah6ILi4sTSxKBbGSS5PAdEFRZi5EID@3IL84syRVqfY/AA "Wolfram Language (Mathematica) – Try It Online")
```
Hash@#~Mod~775+35&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73yOxOMNBuc43P6XO3NxU29hU7X9AUWZeSbSyrl1atHJsrIKagr6DQrWSf0qKko6CkmtZah6IDi4sTSxKBbGcS5PANFBbLkQgP7cgvzizJFWp9j8A "Wolfram Language (Mathematica) – Try It Online")
This code was developed on Mathematica `12.3.0 for Mac OS X x86 (64-bit) (May 10, 2021)` and verified on `12.0.1 for Linux x86 (64-bit) (October 16, 2019)`. According to [the documentation](https://reference.wolfram.com/language/ref/Hash.html),
>
> The "Expression" hash code is computed from the internal representation of an expression and may vary between computer systems and from one version of the Wolfram Language to another.
>
>
>
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 23 bytes
```
#define f(n)n[3]%29^115
```
[Try it online!](https://tio.run/##S9ZNT07@/185JTUtMy9VIU0jTzMv2jhW1cgyztDQ9H9uYmaehmY1l0JBUWZeSZqChpJqSkyekk6ahlJ@SoqSpqY1TApJJrUsNQ@HVHFhaWJRKrIkspHJpUmpODQCBXJxySXn5xbkF2eWQORr/wMA "C (gcc) – Try It Online")
* just a port of [tsh answer](https://codegolf.stackexchange.com/a/230397/84844) the difference is : while js had to use buffer() C can access every single character directly.
] |
[Question]
[
This is a version of the recent challenge [Is this number an integer power of -2?](https://codegolf.stackexchange.com/questions/115516/is-this-number-an-exact-power-of-2) with a different set of criteria designed to highlight the interesting nature of the problem and make the challenge more difficult. I put some consideration into it [here](https://codegolf.meta.stackexchange.com/questions/777/are-two-questions-duplicates-if-they-have-different-scoring-rules#comment40233_1876).
The challenge as wonderfully stated by Toby in the linked question, is:
>
> There are clever ways of determining whether an integer is an exact power of 2. That's no longer an interesting problem, so let's determine whether a given integer is an exact power of **-2**. For example:
>
>
>
> ```
> -2 => yes: (-2)¹
> -1 => no
> 0 => no
> 1 => yes: (-2)⁰
> 2 => no
> 3 => no
> 4 => yes: (-2)²
>
> ```
>
>
## Rules:
* An integer is 64 bits, signed, two's complement. This is the *only* data type you may work with.
* **You may only use the following operations. Each of these counts as one operation.**
+ `n << k`, `n >> k`: Left/right shift `n` by `k` bits. Sign bit is extended in right shift.
+ `n >>> k`: Right shift but do not extend sign bit. 0's are shifted in.
+ `a & b`, `a | b`, `a ^ b`: Bitwise AND, OR, XOR.
+ `a + b`, `a - b`, `a * b`: Add, subtract, multiply.
+ `~b`: Bitwise invert.
+ `-b`: Two's complement negation.
+ `a / b`, `a % b`: Divide (integer quotient, rounds towards 0), and modulo.
- Modulo of negative numbers uses the rules [specified in C99](https://stackoverflow.com/a/11720841/616460): `(a/b) * b + a%b` shall equal `a`. So `5 % -3` is `2`, and `-5 % 3` is `-2`:
- `5 / 3` is `1`, `5 % 3` is `2`, as 1 \* 3 + 2 = 5.
- `-5 / 3` is `-1`, `-5 % 3` is `-2`, as -1 \* 3 + -2 = -5.
- `5 / -3` is `-1`, `5 % -3` is `2`, as -1 \* -3 + 2 = 5.
- `-5 / -3` is `1`, `-5 % -3` is `-2`, as 1 \* -3 + -2 = -5.
- Note that Python's `//` floor division operator does not satisfy the "round towards 0" property of division here, and Python's `%` operator does not meet the requirements, either.
+ Assignments do not count as an operation. As in C, assignments evaluate to the value of the left-hand side after the assignment: `a = (b = a + 5)` sets `b` to `a + 5`, then sets `a` to `b`, and counts as one operation.
+ Compound assignments may be used `a += b` means `a = a + b` and count as one operation.
* You may use integer constants, they do not count as anything.
* Parentheses to specify order of operations are acceptable.
* You may declare functions. Function declarations can be in any style that is convenient for you but note that 64 bit integers are the *only* valid data type. Function declarations do not count as operations, but a function *call* counts as one. Also, to be clear: Functions may contain multiple `return` statements and `return`s from any point are allowed. The `return` itself does not count as an operation.
* You may declare variables at no cost.
* You may use `while` loops, but you may not use `if` or `for`. Operators used in the `while` condition count towards your score. `while` loops execute as long as their condition evaluates to a *non-zero* value (a "truthy" 0 in languages that have this concept is not a valid outcome). Since early-return is allowed, you are allowed to use `break` as well
* Overflow/underflow is allowed and no value clamping will be done. It is treated as if the operation actually happened correctly and was then truncated to 64 bits.
## Scoring / Winning Criteria:
Your code must produce a value that is non-zero if the input is a power of -2, and zero otherwise.
This is [atomic-code-golf](/questions/tagged/atomic-code-golf "show questions tagged 'atomic-code-golf'"). Your score is the total number of operations present in your code (as defined above), *not* the total number of operations that are executed at run-time. The following code:
```
function example (a, b) {
return a + ~b;
}
function ispowerofnegtwo (input) {
y = example(input, 9);
y = example(y, 42);
y = example(y, 98);
return y;
}
```
Contains 5 operations: two in the function, and three function calls.
It doesn't matter how you present your result, use whatever is convenient in your language, be it ultimately storing the result in a variable, returning it from a function, or whatever.
The winner is the post that is demonstrably correct (supply a casual or formal proof if necessary) and has the lowest score as described above.
## Bonus *Very* Hard Mode Challenge!
For a chance at winning absolutely nothing except the potential ability to impress people at parties, submit an answer without using `while` loops! If enough of these are submitted I may even consider dividing the winning groups into two categories (with and without loops).
---
Note: If you'd like to provide a solution in a language that only supports 32-bit integers, you may do so, provided that you sufficiently justify that it will still be correct for 64-bit integers in an explanation.
Also: *Certain* language-specific features may be permitted at no-cost *if they do not evade the rules but are necessary to coerce your language into behaving according to the rules above*. For example (contrived), I will permit a free *not equals 0* comparison in `while` loops, when applied to the condition as a whole, as a workaround for a language that has "truthy" 0's. *Clear attempts to take advantage of these types of things are not allowed* -- e.g. the concept of "truthy" 0 or "undefined" values does not exist in the above ruleset, and so they may not be relied on.
[Answer]
# C++, 15 operations
I have no idea why `while` loops are allowed as they destroy the whole challenge. Here is an answer without any:
```
int64_t is_negpow2(int64_t n) {
int64_t neg = uint64_t(n) >> 63; // n >>> 63
n = (n ^ -neg) + neg; // if (n < 0) n = -n;
int64_t evenbits = n & int64_t(0xaaaaaaaaaaaaaaaaull >> neg);
int64_t n1 = n - 1;
int64_t pot = n & n1;
int64_t r = pot | (n1 >> 63) | evenbits;
return ~((r | -r) >> 63); // !r
}
```
[Answer]
# [Python 2](https://docs.python.org/2/), 3 operations
```
def f(n):
while n>>1:
while n&1:return 0
n=n/-2
return n
```
[Try it online!](https://tio.run/nexus/python2#NYwxCoAwEARr84qrJAHFxDKgfxFM9EBWORSfH0/QYmFniilzypQtXDR0r7wlwjgGhZ/qECWdl4C8Sgzo2t7Qp1DyLsTEIJmwJNsG7xud5ip@w@ziIYxTT3kA "Python 2 – TIO Nexus")
The operations are `>>`, `&`, `/`.
The idea is to repeatedly divide by -2. Powers of -2 chain down to 1: `-8 -> 4 -> -2 -> 1`. If we hit a `1`, accept. If we hit an odd number before hitting `1`, reject. We also need to reject `0`, which forever goes to itself.
The `while n>>1:` loops until `n` is 0 or 1. When the loop breaks, `n` itself is returned, and `1` is a Truthy output and `0` a Falsey one. Inside the loop, we reject repeatedly apply `n -> n/-2` and reject any odd `n`.
Since the `/` is only ever used on even values, its rounding behavior never comes into play. So, it doesn't matter that Python rounds differently from the spec.
[Answer]
# Rust, ~~14~~ 12 operations (no loops)
Requires optimization (`-O`) or `-C overflow-checks=no` to enable the overflowing subtraction instead of panic.
```
fn is_power_of_negative_2(input: i64) -> i64 {
let sign = input >> 63;
// 1 op
let abs_input = (input ^ sign) - sign;
// 2 ops
let bad_power_of_two = sign ^ -0x5555_5555_5555_5556; // == 0xaaaa_aaaa_aaaa_aaaa
// 1 op
let is_not_power_of_n2 = abs_input & ((abs_input - 1) | bad_power_of_two);
// 3 ops
let is_not_power_of_n2 = (is_not_power_of_n2 | -is_not_power_of_n2) >> 63;
// 3 ops
input & !is_not_power_of_n2
// 2 ops
}
```
(To clarify: `!x` is [bitwise-NOT](https://stackoverflow.com/questions/38896155/what-is-the-bitwise-not-operator-in-rust) here, not logical-NOT)
Test cases:
```
#[test]
fn test_is_power_of_negative_2() {
let mut value = 1;
for _ in 0 .. 64 {
assert_ne!(0, is_power_of_negative_2(value), "wrong: {} should return nonzero", value);
value *= -2;
}
}
#[test]
fn test_not_power_of_negative_2() {
for i in &[0, -1, 2, 3, -3, -4, 5, -5, 6, -6, 7, -7, 8, 1<<61, -1<<62, 2554790084739629493, -4676986601000636537] {
assert_eq!(0, is_power_of_negative_2(*i), "wrong: {} should return zero", i);
}
}
```
[Try it online!](https://tio.run/nexus/rust#fVLtTuMwEPzfpxg4CSUoBufLaYD0Fe4BEFjhcHuRenEvdik66Ktfbp1A2l5KV7LXcTyzs2O38xqVkSu9UY3Uc1mrRWmrFyUjr6pXa3uDSiQ@2MxlvE1AsVQWplrUKNCdwWwGEd92/66vEUKvhnPlk5H9oQI9Ix47MHF2eYBFBDMD7ql83omyG03wruQjGH9NKeTBJG4dRVGAv5YU8nA6qoy6rrXd6zyiGju5F/C83RdD6ON9pMof1MdOPU6Te0d238HGu/5/ju6Rf4o7G6MOjdxOJt/urTL2YUJX7Bbyi3v29671F5G/lMu1IrlhX3@uG0iqC46rKwyPwEVpjGoscZ15PPjqGXV0foDzTaPrxQ3etjA/9Xr5jEbZdVOj1vUf1ejzoK/84amLXsllARb1m9tjbR3aMO7LNVC5Bi7uSSULA0QBYlq5kQRIKdEQlGhklGhMA4R3dyJ0AMqEiNI0yXLOp0kW5yLKk7zDi0zkUyF4yDkXsUjj7GHskPp9yqHL6pQ9H95U/mBB2/79MV@WC9Oy7y1jzoR/)
---
The idea is to check if |x| is a power of 2 (using `(y & (y - 1)) == 0` as usual). If x is a power of 2, then we further check (1) when `x >= 0`, it should also be an even power of 2, or (2) when `x < 0`, it should be an odd power of 2. We check this by `&`-ing the "`bad_power_of_two`" mask 0x…aaaa when `x >= 0` (produces 0 only when it is an even power), or 0x…5555 when `x < 0`.
[Answer]
# C, 5 operations
```
long long f(long long x){
x=x ^ ((x & 0xaaaaaaaaaaaaaaaa) * 6);
while(x){
while(x&(x-1))
return 0;
return 1;
}
return 0;
}
```
# C, 10 operations, without loops
```
long long f(long long x){
x = x ^ ((x & 0xaaaaaaaaaaaaaaaa) * 6);
long long t = x & (x-1);
return (((t-1) & ~t) >> 63) * x;
}
```
# C, 1 operation
```
long long f(long long x){
long long a0=1, a1=-2, a2=4, a3=-8, a4=16, a5=-32, a6=64, a7=-128, a8=256, a9=-512, a10=1024, a11=-2048, a12=4096, a13=-8192, a14=16384, a15=-32768, a16=65536, a17=-131072, a18=262144, a19=-524288, a20=1048576, a21=-2097152, a22=4194304, a23=-8388608, a24=16777216, a25=-33554432, a26=67108864, a27=-134217728, a28=268435456, a29=-536870912, a30=1073741824, a31=-2147483648, a32=4294967296, a33=-8589934592, a34=17179869184, a35=-34359738368, a36=68719476736, a37=-137438953472, a38=274877906944, a39=-549755813888, a40=1099511627776, a41=-2199023255552, a42=4398046511104, a43=-8796093022208, a44=17592186044416, a45=-35184372088832, a46=70368744177664, a47=-140737488355328, a48=281474976710656, a49=-562949953421312, a50=1125899906842624, a51=-2251799813685248, a52=4503599627370496, a53=-9007199254740992, a54=18014398509481984, a55=-36028797018963968, a56=72057594037927936, a57=-144115188075855872, a58=288230376151711744, a59=-576460752303423488, a60=1152921504606846976, a61=-2305843009213693952, a62=4611686018427387904, a63=-9223372036854775807-1, a64=0;
while(a0){
long long t = x ^ a0;
long long f = 1;
while(t){
f = 0;
t = 0;
}
while(f)
return 1;
a0=a1; a1=a2; a2=a3; a3=a4; a4=a5; a5=a6; a6=a7; a7=a8; a8=a9; a9=a10; a10=a11; a11=a12; a12=a13; a13=a14; a14=a15; a15=a16; a16=a17; a17=a18; a18=a19; a19=a20; a20=a21; a21=a22; a22=a23; a23=a24; a24=a25; a25=a26; a26=a27; a27=a28; a28=a29; a29=a30; a30=a31; a31=a32; a32=a33; a33=a34; a34=a35; a35=a36; a36=a37; a37=a38; a38=a39; a39=a40; a40=a41; a41=a42; a42=a43; a43=a44; a44=a45; a45=a46; a46=a47; a47=a48; a48=a49; a49=a50; a50=a51; a51=a52; a52=a53; a53=a54; a54=a55; a55=a56; a56=a57; a57=a58; a58=a59; a59=a60; a60=a61; a61=a62; a62=a63; a63=a64;
}
return 0;
}
```
[Answer]
# Haskell, 2 3 operations
```
import Data.Bits (.&.)
f 0 = False
f 1 = True
f n | n .&. 1 == 0 = f (n `div` -2)
f n | otherwise = False
```
Defines a recursive function `f(n)`. Operations used are function call (`f`), division (`div`), and bitwise and (`.&.`).
Contains no loops because of the fact that Haskell has no loop statements :-)
[Answer]
# Python 3, ~~10 or 11~~ 9 operations
```
def g(x):
while x:
while 1 - (1 + ~int(x - -2 * int(float(x) / -2))) & 1: x /= -2
break
while int(1-x):
return 0
return 5 # or any other value
```
Returns `5` for powers of `-2`, `0` otherwise
[Answer]
# C, 31 operations
[**Live Demo**](http://ideone.com/6ey9Cw)
My idea is simple, if it's a power of two, then if its log is even then it has to be positive, otherwise its log has to be odd.
```
int isPositive(int x) // 6
{
return ((~x & (~x + 1)) >> 31) & 1;
}
int isPowerOfTwo(int x) // 5
{
return isPositive(x) & ~(x & (x-1));
}
int log2(int x) // 3
{
int i = (-1);
while(isPositive(x))
{
i += 1;
x >>= 1;
}
return i;
}
int isPowerOfNegativeTwo(int x) // 17
{
return ( isPositive(x) & isPowerOfTwo(x) & ~(log2(x) % 2) )
| ( ~isPositive(x) & isPowerOfTwo(-x) & (log2(-x) % 2) );
}
```
[Answer]
# Assembly, 1 operation
```
.data
.space 1 , 1 # (-2)^31
.space 1610612735, 0
.space 1 , 1 # (-2)^29
.space 402653183 , 0
.space 1 , 1 # (-2)^27
.space 100663295 , 0
.space 1 , 1 # (-2)^25
.space 25165823 , 0
.space 1 , 1 # (-2)^23
.space 6291455 , 0
.space 1 , 1 # (-2)^21
.space 1572863 , 0
.space 1 , 1 # (-2)^19
.space 393215 , 0
.space 1 , 1 # (-2)^17
.space 98303 , 0
.space 1 , 1 # (-2)^15
.space 24575 , 0
.space 1 , 1 # (-2)^13
.space 6143 , 0
.space 1 , 1 # (-2)^11
.space 1535 , 0
.space 1 , 1 # (-2)^9
.space 383 , 0
.space 1 , 1 # (-2)^7
.space 95 , 0
.space 1 , 1 # (-2)^5 = -32
.space 23 , 0
.space 1 , 1 # (-2)^3 = -8
.space 5 , 0
.space 1 , 1 # (-2)^1 = -2
.space 1 , 0
dataZero:
.space 1 , 0
.space 1 , 1 # (-2)^0 = 1
.space 2 , 0
.space 1 , 1 # (-2)^2 = 4
.space 11 , 0
.space 1 , 1 # (-2)^4 = 16
.space 47 , 0
.space 1 , 1 # (-2)^6 = 64
.space 191 , 0
.space 1 , 1 # (-2)^8
.space 767 , 0
.space 1 , 1 # (-2)^10
.space 3071 , 0
.space 1 , 1 # (-2)^12
.space 12287 , 0
.space 1 , 1 # (-2)^14
.space 49151 , 0
.space 1 , 1 # (-2)^16
.space 196607 , 0
.space 1 , 1 # (-2)^18
.space 786431 , 0
.space 1 , 1 # (-2)^20
.space 3145727 , 0
.space 1 , 1 # (-2)^22
.space 12582911 , 0
.space 1 , 1 # (-2)^24
.space 50331647 , 0
.space 1 , 1 # (-2)^26
.space 201326591 , 0
.space 1 , 1 # (-2)^28
.space 805306367 , 0
.space 1 , 1 # (-2)^30
.space 3221225471, 0
.space 1 , 1 # (-2)^32
.globl isPowNeg2
isPowNeg2:
movl dataZero(%edi), %eax
ret
```
Uses a huge lookup table to find whether the number is a power of 2. You can expand this to 64 bits, but finding a computer to store that much data is left as an exercise to the reader :-P
[Answer]
# C, 7 operations
```
int64_t is_power_of_neg2(int64_t n)
{
int64_t x = n&-n;
while (x^n) {
while (x^-n)
return 0;
return x & 0xaaaaaaaaaaaaaaaa;
}
return x & 0x5555555555555555;
}
```
or:
# C, 13 operations without loops-as-conditionals
```
int64_t is_power_of_neg2(int64_t n)
{
int64_t s = ~(n>>63);
int64_t a = ((n/2)^s)-s;
int64_t x = n&-(uint64_t)n; // Cast to define - on INT64_MIN.
return ~(a/x >> 63) & x & (0xaaaaaaaaaaaaaaaa^s);
}
```
Explanation:
* `n&-n` yields the lowest set bit of `n`.
* `a` is the negated absolute value of `n/2`, necessarily negative because `/2` precludes overflow of negation.
* `a/x` is zero only if `a` is an exact power of two; otherwise at least one other bit is set, and it's higher than `x`, the lowest bit, yielding a negative result.
* `~(a/x >> 63)` then yields a bitmask that's all-ones if `n` or `-n` is a power of two, otherwise all-zeros.
* `^s` is applied to the mask to check the sign of `n` to see if it's a power of `-2`.
[Answer]
# PHP, 3 operations
ternary and `if` are disallowed; so let´s abuse `while`:
```
function f($n)
{
while ($n>>1) # 1. ">>1"
{
while ($n&1) # 2. "&1"
return 0;
return f($n/-2|0); # 3. "/-2" ("|0" to turn it into integer division)
}
return $n;
}
```
1. `$n>>1`: if number is 0 or 1, return number
2. `$n&1`: if number is odd, return 0
3. else test `$n/-2` (+cast to int)
[Answer]
# JavaScript ES6, 7 operations
```
x=>{
while(x&1^1&x/x){
x/=-2;x=x|0
}
while(x&0xfffffffe)x-=x
return x
}
```
[Try it online!](https://tio.run/nexus/javascript-node#TY3NjsIwDITveQqfUCK2P@HaDS@CWKm0LrWUTSonXYyAZy9FcNjRyIeZT57BLeL2NwVwGcmjlo39sRupxLwyAKlcsWvEyb0GqKqM3Rioa72/goU4wQm7dk4IeaQEqznOoYccLy33CWqgkPGMDD39UaIY1qePf2O1DG@hkcLJ2jDmmQOIeizsDkc1RNbkCls39G1tQ9ut4XKa06jJqOy4/G0nPZgP96J2b0p1MaTosfTxrPlAx6@8HrM8AQ "JavaScript (Node.js) – TIO Nexus")
## Explanation
```
while(x&1^1&x/x)
```
While x!=0 and x%2==0 **4 ops**
x/x is equal to 1 so long as x is not 0 (0/0 gives NaN which is evaluated as false)
& bitwise and
x&1^1 is equal to 1 if x is even (x and 1) xor 1
```
x/=-2;x=x|0
```
This is the form of division defined by the question **1 op**
```
while(x&0xfffffffe)
```
While x!=1 and x!=0 **1 op**
The condition needed to exit when x==0 or x==1 as those two are the return values and entering an infinite loop would not be productive. This could theoretically be extended for greater values by increasing the hexadecimal number. Currently works for up to ±2^32-1
```
x-=x
```
Set x to 0 **1 op**
While I could have used return 0 for 0 ops, I felt that any while loop which is broken by another statement feels too much like cheating.
```
return x
```
returns x (1 if power of -2, 0 otherwise)
] |
[Question]
[
Whoa, whoa, whoa ... stop typing your program. No, I don't mean "print `ABC...`." I'm talking the capitals of the United States.
Specifically, print all the city/state combinations given in the following list
* in any order
* with your choice of delimiters (e.g., `Baton Rouge`LA_Indianapolis`IN_...` is acceptable), so long as it's unambiguous which words are cities, which are states, and which are different entries
* without using any of `ABCDEFGHIJKLMNOPQRSTUVWXYZ` in your source code
Output should be to STDOUT or equivalent.
### EDIT - Whoops!
`<edit>`
While typing up the list from memory (thanks to the Animaniacs, as described below), I apparently neglected Washington, DC, which *isn't* a state capital, but *is* in the song, and is sometimes included in "lists of capitals" (like the Mathematica [answer](https://codegolf.stackexchange.com/a/60664/42963) below). *I had intended to include that city in this list, but missed it, somehow.* As a result, answers that *don't* have that city won't be penalized, and answers that *do* have that city won't be penalized, either. Essentially, it's up to you whether `Washington, DC` is included in your ouput or not. Sorry about that, folks!
`</edit>`
```
Baton Rouge, LA
Indianapolis, IN
Columbus, OH
Montgomery, AL
Helena, MT
Denver, CO
Boise, ID
Austin, TX
Boston, MA
Albany, NY
Tallahassee, FL
Santa Fe, NM
Nashville, TN
Trenton, NJ
Jefferson, MO
Richmond, VA
Pierre, SD
Harrisburg, PA
Augusta, ME
Providence, RI
Dover, DE
Concord, NH
Montpelier, VT
Hartford, CT
Topeka, KS
Saint Paul, MN
Juneau, AK
Lincoln, NE
Raleigh, NC
Madison, WI
Olympia, WA
Phoenix, AZ
Lansing, MI
Honolulu, HI
Jackson, MS
Springfield, IL
Columbia, SC
Annapolis, MD
Cheyenne, WY
Salt Lake City, UT
Atlanta, GA
Bismarck, ND
Frankfort, KY
Salem, OR
Little Rock, AR
Des Moines, IA
Sacramento, CA
Oklahoma City, OK
Charleston, WV
Carson City, NV
```
(h/t to Animaniacs for the list of capitals)
Take a bonus of **-20%** if your submission doesn't explicitly have the numbers `65` through `90` or the number `1` in the code. *Generating* these numbers (e.g., `a=5*13` or `a="123"[0]` or `a=64;a++` or the like) is allowed under this bonus, explicitly having them (e.g., `a=65` or `a="1 23 456"[0]`) is not.
## Leaderboard
```
var QUESTION_ID=60650,OVERRIDE_USER=42963;function answersUrl(e){return"http://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"http://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+(?:[.]\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]
# Mathematica, ~~168~~ ~~153~~ 149 bytes - 20% = 119.2 bytes
```
u="\.55nited\.53tates";\.41dministrative\.44ivision\.44ata[{#,u}&/@\.43ountry\.44ata[u,"\.52egions"],{"\.43apital\.4eame","\.53tate\.41bbreviation"}]
```
Obligatory, but I did not know that any character can be replaced by `\.xx` or `\:xxxx` with the appropriate hex code.
Edit: Cut of 4 more characters by replacing `Thread` with a pure function.
Output:
```
{{Montgomery,AL},{Juneau,AK},{Phoenix,AZ},{Little Rock,AR},{Sacramento,CA},{Denver,CO},{Hartford,CT},{Dover,DE},{Washington,DC},{Tallahassee,FL},{Atlanta,GA},{Honolulu,HI},{Boise,ID},{Springfield,IL},{Indianapolis,IN},{Des Moines,IA},{Topeka,KS},{Frankfort,KY},{Baton Rouge,LA},{Augusta,ME},{Annapolis,MD},{Boston,MA},{Lansing,MI},{Saint Paul,MN},{Jackson,MS},{Jefferson City,MO},{Helena,MT},{Lincoln,NE},{Carson City,NV},{Concord,NH},{Trenton,NJ},{Santa Fe,NM},{Albany,NY},{Raleigh,NC},{Bismarck,ND},{Columbus,OH},{Oklahoma City,OK},{Salem,OR},{Harrisburg,PA},{Providence,RI},{Columbia,SC},{Pierre,SD},{Nashville,TN},{Austin,TX},{Salt Lake City,UT},{Montpelier,VT},{Richmond,VA},{Olympia,WA},{Charleston,WV},{Madison,WI},{Cheyenne,WY}}
```
[Answer]
# R, ~~96 bytes~~ 98 bytes -20% -> 78.4
Thanks to @plasticinsect for the bonus!
```
library(maps);data(us.cities);cat(gsub("()( \\w+)$",",\\2",us.cities$n[us.cities$ca==2]),sep="\n")
```
Previous code at 96 bytes:
```
library(maps);data(us.cities);cat(gsub("( \\w+)$",",\\1",us.cities$n[us.cities$ca==2]),sep="\n")
```
From package `maps`, it loads a dataset of US cities. Column `capital` contains a `2` if it is a state capital. The names of the cities are given is column `name` in the form "City StateAbbreviation" (i. e. `Albany NY`), so one need to add an explicit delimiter in between before output. ~~To do so I eventually use the regex `\1` meaning I can't have the bonus I suppose.~~ To avoid using `\1` in the regex I added an empty group so that I can use `\2`.
Usage:
```
> library(maps);data(us.cities);cat(gsub("()( \\w+)$",",\\2",us.cities$n[us.cities$ca>1]),sep="\n")
Albany, NY
Annapolis, MD
Atlanta, GA
Augusta, ME
Austin, TX
Baton Rouge, LA
Bismarck, ND
Boise, ID
Boston, MA
Carson City, NV
Charleston, WV
Cheyenne, WY
Columbia, SC
Columbus, OH
Concord, NH
Denver, CO
Des Moines, IA
Dover, DE
Frankfort, KY
Harrisburg, PA
Hartford, CT
Helena, MT
Honolulu, HI
Indianapolis, IN
Jackson, MS
Jefferson City, MO
Juneau, AK
Lansing, MI
Lincoln, NE
Little Rock, AR
Madison, WI
Montgomery, AL
Montpelier, VT
Nashville, TN
Oklahoma City, OK
Olympia, WA
Phoenix, AZ
Pierre, SD
Providence, RI
Raleigh, NC
Richmond, VA
Sacramento, CA
Saint Paul, MN
Salem, OR
Salt Lake City, UT
Santa Fe, NM
Springfield, IL
Tallahassee, FL
Topeka, KS
Trenton, NJ
```
[Answer]
# CJam, 312 bytes
```
".ýç9.5i-jæ¤þ¸«Ã«cj|ù;ÎüÄ`ѯÄÿçsøi4ÔÚ0;¾o'ÈàÚãÕ»®¼v{Ðù·*ñfiö\^é]ù¬ðö¸qÚpÿ©a$ÿÆhk¥½éØ×ïÕ{ñ9ÁÛ%Ðø¦ð·âßxâj Ö묯,Ð+?Û¡!ù%Âí©Úfx`¤|}¼>qñµÉÎ4Óæj-wöÄÆ 4,üÖáÌxsÍ·üãýÛêmÁj±æ0?³¢¶§%Û57Ëmc.~`b=´á¥ÉpË,ôb¶ÌsÁì¾*§òÿ_Ö©;<tíèz6ljç¸b§èäø>`ÍÚפÒòÔ§~hÝ®Ú8¼}8Ì7rÿé×ÔÎîæ¡©)Ô@"'[fm256,f=)b27b'`f+'`/{_2>'q/32af.^' *o2<eup}/
```
The code is **390 bytes** long and qualifies for the **20% bonus**.
Note that the code is riddled with unprintable characters. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=%22%06.%C3%BD%C3%A79.%025%C2%86i%C2%97-%C2%95%C2%99j%C3%A6%C2%95%C2%A4%C3%BE%14%C2%92%C2%B8%C2%AB%C2%8D%C3%83%1E%C2%AB%7Fcj%C2%AD%0B%7C%C3%B9%3B%C3%8E%C2%86%C3%BC%C3%84%60%C2%97%C2%AD%C3%91%C2%AF%C3%84%C3%BF%C3%A7%1Ds%1D%C3%B8%1F%C2%90i4%C3%94%C3%9A0%3B%C2%87%C2%BE%19o%C2%9D'%C3%88%C3%A0%16%C2%93%C3%9A%C3%A3%C3%95%C2%98%C2%BB%C2%AE%C2%BC%1Av%7B%C3%90%C3%B9%C2%B7*%C2%95%C3%B1fi%C3%B6%5C%5E%C3%A9%5D%C3%B9%C2%AC%C3%B0%C3%B6%C2%83%C2%B8%17q%C3%9Ap%C3%BF%C2%A9a%C2%99%24%C3%BF%C3%86hk%C2%A5%C2%BD%C3%A9%C3%98%C3%97%C3%AF%C3%95%7B%C3%B19%C3%81%C3%9B%C2%81%25%C3%90%C3%B8%7F%C2%A6%C3%B0%C2%B7%C3%A2%C3%9Fx%C3%A2%7F%C2%81j%09%C3%96%02%C2%86%C3%AB%C2%AC%C2%8E%C2%AD%C2%AF%2C%1B%C3%90%2B%3F%04%C3%9B%C2%A1%C2%87%C2%9A!%C3%B9%25%C3%82%C3%AD%C2%A9%C3%9Afx%60%C2%8B%C2%A4%11%16%16%7C%C2%8E%7D%C2%BC%3Eq%C3%B1%C2%8B%C2%B5%C3%89%C3%8E4%C2%90%10%C3%93%C3%A6j-w%C3%B6%C3%84%C3%86%204%2C%C2%87%C3%BC%C3%96%C2%8F%16%C3%A1%C3%8Cxs%C3%8D%C2%B7%C3%BC%C3%A3%C3%BD%C3%9B%C3%AA%05m%C3%81j%C2%B1%C3%A60%3F%C2%B3%C2%9E%04%C2%A2%C2%95%C2%B6%C2%A7%25%C2%91%C3%9B57%C3%8B%13mc.~%60b%3D%C2%B4%C3%A1%12%C2%A5%C3%89p%C3%8B%0F%1A%2C%C3%B4%C2%89b%C2%85%C2%8E%C2%B6%08%C3%8Cs%C3%81%C3%AC%1A%C2%BE*%C2%A7%C3%B2%C2%95%C3%BF%11%C2%95_%C2%8C%C3%96%C2%A9%1B%3B%3Ct%C3%AD%C3%A8%08z6%C2%8Dlj%C3%A7%01%C2%B8b%C2%A7%C3%A8%C3%A4%C3%B8%3E%60%C3%8D%C3%9A%C2%9D%15%C3%97%1B%04%C2%A4%C3%92%C2%83%C3%B2%C3%94%C2%A7~h%C2%87%C3%9D%C2%AE%C3%9A8%C2%BC%7D8%C3%8C7r%C3%BF%C3%A9%1C%C3%97%C2%91%17%C2%9D%C3%94%C3%8E%C3%AE%C2%82%C3%A6%C2%A1%15%C2%A9)%C3%94%40%22'%5Bfm256%2Cf%3D)b27b'%60f%2B'%60%2F%7B_2%3E'q%2F32af.%5E'%20*o2%3Ceup%7D%2F).
### Idea
We have to encode the output somehow without using uppercase letters or the numbers 1 and 65 to 90 anywhere in the code.
We start by rewriting the desired output as
```
akjuneau`paharrisburg`txaustin`maboston`wvcharleston`azphoenix`kyfrankfort`msjackson`mdannapolis`vtmontpelier`ndbismarck`hihonolulu`meaugusta`nvcarsonqcity`sccolumbia`ohcolumbus`wycheyenne`casacramento`arlittleqrock`nmsantaqfe`mnsaintqpaul`idboise`tnnashville`codenver`nhconcord`almontgomery`inindianapolis`riprovidence`utsaltqlakeqcity`ilspringfield`ncraleigh`labatonqrouge`sdpierre`dedover`orsalem`waolympia`kstopeka`varichmond`cthartford`nyalbany`milansing`njtrenton`mthelena`iadesqmoines`gaatlanta`wimadison`nelincoln`fltallahassee`okoklahomaqcity`mojefferson
```
By subtracting the character ``` from all characters of that string, we obtain an array containing integers from 0 to 26. We can convert this array from base 27 to base 229, yielding an array of integers from 0 to 228.
If we add 91 to each base-229 digit and take the results modulo 256, we map the range **[0, …, 164]** to **[91, … 255]**, and the range **[165, …, 228]** to **[0, …, 63]**. This leaves the characters with code points from **64** (`@`) to **90** (`Z`) unused.
The string to encode is not in the same order as the sample output in the question. I tried several permutation until I found one that contains no null bytes, linefeeds, carriage returns or non-breaking spaces (problematic with the online interpreter), and no double quotes (require escaping).
### Code
```
"…@" e# Push a string of 342 ISO-8859-1 characters.
'[fm e# Subtract the char '[' (code point 91) from each char of the string.
256,f= e# Compute the remainder of the differences divided by 256.
) e# Pop the last integer from the array ('@' -> 27 -> 229).
b27b e# Convert the remaining array from base 229 to base 27.
'`f+ e# Add the character '`' to the resulting digits.
e# This pushes the string from the "Idea" section.
'`/ e# Split the result at backticks.
{ e# For each resulting chunk C:
_2> e# Copy C and remove its first to characters.
'q/ e# Split at occurrences of 'q'.
32a e# Push [32].
f.^ e# Mapped, vectorized XOR; XOR the first character of each chunk
e# with 32. This changes its case.
' * e# Join the resulting chunks, separating by spaces.
o e# Print.
2< e# Reduce the original C to its first two characters.
eu e# Convert to uppercase.
p e# Print, enclosed in double quotes, and followed by a linefeed.
}/ e#
```
[Answer]
# Perl, 605 bytes - 20% = 484
```
$_="baton rouge,laindianapolis,incolumbus,ohmontgomery,alhelena,mtdenver,coboise,idaustin,txboston,maalbany,nytallahassee,flsanta fe,nmnashville,tntrenton,njjefferson,morichmond,vapierre,sdharrisburg,paaugusta,meprovidence,ridover,deconcord,nhmontpelier,vthartford,cttopeka,kssaint paul,mnjuneau,aklincoln,neraleigh,ncmadison,wiolympia,waphoenix,azlansing,mihonolulu,hijackson,msspringfield,ilcolumbia,scannapolis,mdcheyenne,wysalt lake city,utatlanta,gabismarck,ndfrankfort,kysalem,orlittle rock,ardes moines,iasacramento,caoklahoma city,okcharleston,wvcarson city,nv";s/,../uc"$&;"/eg;s/\b./\u$&/g;print
```
My first version was invalid because it used \U to convert to uppercase. This one uses \u on each letter of the state abbreviation. I also had to add a dummy capture group to avoid using $1.
**Edit:** I was able to shave off 8 bytes by using uc() with the e flag. (Thank you Dom Hastings.)
[Answer]
# javascript, ~~727~~ 687 bytes - 20% = 549.6
```
alert('baton rouge;indianapolis;columbus;montgomery;helena;denver;boise;austin;boston;albany;tallahassee;santa fe;nashville;trenton;jefferson;richmond;pierre;harrisburg;augusta;providence;dover;concord;montpelier;hartford;topeka;saint paul;juneau;lincoln;raleigh;madison;olympia;phoenix;lansing;honolulu;jackson;springfield;columbia;annapolis;cheyenne;salt lake city;atlanta;bismarck;frankfort;salem;little rock;des moines;sacramento;oklahoma city;charleston;carson city'.split`;`.map((a,i)=>a.split` `.map(b=>b[0][u='to\x55pper\x43ase']()+b.slice(-~0)).join` `+0+'lainohalmtcoidtxmanyflnmtnnjmovasdpameridenhvtctksmnaknencwiwaazmihimsilscmdwyutgandkyorariacaokwvnv'[u]().substr(i*2,2)))
```
javascript is particularly tough as well, considering their long function names and camelcase. splitting out the states saved a ton on delimiters, and made it easier to work with all around.
@mbomb007 nothing in the post capitalized for a reason ;)
[Answer]
# C, ~~703~~ 700 bytes - 20% = 560 bytes
```
main(){int c=!0;char*p="@baton@rouge[la*indianapolis[in*columbus[oh*montgomery[al*helena[mt*denver[co*boise[id*austin[tx*boston[ma*albany[ny*tallahassee[fl*santa@fe[nm*nashville[tn*trenton[nj*jefferson[mo*richmond[va*pierre[sd*harrisburg[pa*augusta[me*providence[ri*dover[de*concord[nh*montpelier[vt*hartford[ct*topeka[ks*saint@paul[mn*juneau[ak*lincoln[ne*raleigh[nc*madison[wi*olympia[wa*phoenix[az*lansing[mi*honolulu[hi*jackson[ms*springfield[il*columbia[sc*annapolis[md*cheyenne[wy*salt@lake@city[ut*atlanta[ga*bismarck[nd*frankfort[ky*salem[or*little@rock[ar*des@moines[ia*sacramento[ca*oklahoma@city[ok*charleston[wv*carson@city[nv*";while(*++p)c+=*p<97?2+*p/91:0,printf("%c",c?--c,*p-32:*p);}
```
I changed the loop a bit to make it compile with non-C99 compilers. [Online version](http://codepad.org/8pYOWViJ)
[Answer]
# javascript (es6) 516 (645-20%) ~~532 (664-20%)~~
test running the snippet below in any recent browser: the only es6 feature used is `template strings`
```
alert(`
labaton rouge
inindianapolis
ohcolumbus
almontgomery
mthelena
codenver
idboise
txaustin
maboston
nyalbany
fltallahassee
nmsanta fe
tnnashville
njtrenton
mojefferson
varichmond
sdpierre
paharrisburg
meaugusta
riprovidence
dedover
nhconcord
vtmontpelier
cthartford
kstopeka
mnsaint paul
akjuneau
nelincoln
ncraleigh
wimadison
waolympia
azphoenix
milansing
hihonolulu
msjackson
ilspringfield
sccolumbia
mdannapolis
wycheyenne
utsalt lake city
gaatlanta
ndbismarck
kyfrankfort
orsalem
arlittle rock
iades moines
casacramento
okoklahoma city
wvcharleston
nvcarson city
`.replace(/(\n..)(.)| ./g,(w,x,y)=>(y?x+','+y:w)['to\x55pper\x43ase']()))
```
[Answer]
# [Funciton](http://esolangs.org/wiki/Funciton), 5045 − 20% = 4036 bytes
This code contains only one number, and it’s not in the range 65 through 90. Nor is it the number 1. In fact, this number is 4187 decimal digits, which cleanly factorizes into primes 79×53.
As always, get nicer rendering by executing `$('pre').css('line-height',1);` in your browser console.
```
╔═══════════════════════════════════════════════════════════════════════════════╗
║7136715096855386138244201921379984522081157959387689102965666099527710666770872║
║8632405046019650473694855863386057142772501332293800147289916078651647760772443║
║8725652766505885348060772769789231580343563435533130895917300237406562638030980║
║3711194146648873765244744781953334585902685570475123886704870369061449702689564║
║3595572359214492754563209811697465519112054922140302657793458997381684588970868║
║7793823212145990790477442216616349142872430200820970858787998435483524660584416║
║6164882066597488329789212167115912389108306700132767580336075847661452995278441║
║4608506136620095732142590833871485553260077395557115141102093496100483811080395║
║6552804273104384398276311006450509670233242612250087379855689038722276735360412║
║6878753848057526563710344191563893599886868947829201220173418232286377514939888║
║5826479634935379423693839085984565815131964110239432620200938530722481854602826║
║9037704900171802579729347376622932167603510862768435434759967894116610786905139║
║7412487476129828359043674372610945304257752777678880166233522176263310236004692║
║0559345181857154078616512980811741354072155133642234106705715867670036797456411║
║3264775046807948785891163930492821367841190494057926544207551600789781134233199║
║4931373746463823081063091455500394879663289567724955802959562627212816895887920║
║2489552640528826478935177736926106383314641517898028085103843993947923512080284║
║1297634633899484758145253947029431905171166312060063580822580997396575916969283║
║8159188436765390151074141915725490631912068692580040188837785831216953037087556║
║0321645257600479747768084542577912902995339088536912361110657756023624089620615║
║5158613866208649015722071421838484405731207470388752536584022013701916919845375║
║3209922919010373613440766178725948038885270419846274466164969481905438092706837║
║6125745847739006120558864887675350117798119205719776692338137137532239709753293║
║8995102505657504327982204450387974737246780507128822708181598416111438056330283║
║4785530759635414792062372089201435348108257958259667891277855066169836153935818║
║4849044313927545256942990267263122642672090579649898429311837755460330426123991║
║0865666851722460685754104973378688314066186075716326618952555696686125861179585╟
║7767008528632788251800639156553539356488180142086268151130154661765322967918167║
║6359863162328432204277806522752416226370770476079674225817370337594249020946663║
║1822184578010876426310754786368155838502939742370374540683825491575130213369657║
║2120804668997619419445916101731942338784683470192383635854329364775377151471990║
║2655205750667024595911951526939478313795716952326483704217123605616832952264503║
║8356212760984291960912048067411637475389334580447270650407546381067041317195274║
║3658815060537830411410963930585836537141345277217896786840243174681916988181583║
║8390084258839955570465021603546831767108002881554379542200508579678822598563892║
║8621176190864640015677903257299296220003472794175916462345690686103548377723578║
║6760505049046712538526435515066511975271300115330547105472335029933058732991785║
║5589232894601143279598099962031945524489480851133384138840761826907713777131329║
║9653475711559777326388996740771947433446060772704682592783253818915955015393899║
║8513366910314301930539317844646403762279062435716757707854074235922915355490960║
║9007713445763282900095169953058848056683723033266818136479787173846475991012202║
║9462375527766882809250645176534521094942659081258046722219759280486004661723805║
║6786432900677055552677470564184679327084173152258835307889916896828977570843423║
║3265510347632679682249919679555731735198061941806081777484490821424077128775482║
║4866960679621740266038712499696089430677992126743925060145440886995190894304525║
║3469457565680576996559817327023534136403178656947913819462072799063875416015296║
║0646268276069839972076911667210841845209380552353634062961962574981823297845248║
║7817510295701815725710777747052257272070773995280590130309991890195320939352205║
║3629070121725848802522009518874134452415909082137665653417182020188245139223466║
║1804690429428088774753298257855093982064922470661344462996583642233273038068537║
║5899655675409028134860922908216970845189239846431322757349357911553610461726138║
║9065104191927373357937390905721074233359257891159853454407258925428691711525208║
║0898360915775189300266760522953739009955921695946386500512104598494398514200642║
╚═══════════════════════════════════════════════════════════════════════════════╝
```
Edit: Kiri-ban! This answer is codegolf.SE post #61000!
[Answer]
## x86 machine code, 764 bytes
612 if bonus awarded
Totally self-contained program. Only relies upon (a) Bios int 0x10 being available to print each char and (b) DS, ES, SP and SS being initialized before program is called, DOS does this.(and DOS-Box too) Otherwise, the code relies on nothing.
The absolute minimum without any dependencies at all except for the BIOS rom, would be about 2 floppy disk sectors @512 bytes each.
It doesn't seem to exploit any of the standard loop-holes, though while some bytes of the program are 01, these are not numbers in the source. However, since I'd like to submit the binary code as my solution, I imagine that would disallow the 01 bytes.?
Hex-editor view of binary:
```
68 98 01 E8 1D 00 CD 20 B3 62 FE CB 88 DF 80 C7 19 38 D8 72 0D 38 F8 77 09 30 DB FE C3 C0 E3 05 - h˜.è..Í ³bþˈ߀Ç.8Ør.8øw.0ÛþÃÀã.
28 D8 C3 55 89 E5 81 C5 04 00 8B 76 00 89 F7 AC A8 FF 74 3E 80 3E 96 01 00 75 0A E8 CA FF AA A2 - (ØÃU‰å.Å..‹v.‰÷¬¨ÿt>€>–..u.èÊÿª¢
96 01 E9 EA FF 3C 2C 75 18 AA AC E8 BA FF AA AC E8 B5 FF AA AC AA AC E8 AE FF AA A2 96 01 E9 CE - –.éêÿ<,u.ª¬èºÿª¬èµÿª¬ª¬è®ÿª¢–.éÎ
FF 80 3E 96 01 20 75 03 E8 9D FF AA A2 96 01 E9 BD FF 8B 76 00 AC A8 FF 74 1A 3C 2D 75 0F B0 0D - ÿ€>–. u.è.ÿª¢–.é½ÿ‹v.¬¨ÿt.<-u.°.
B4 0E CD 10 B0 0A B4 0E CD 10 E9 E8 FF B4 0E CD 10 E9 E1 FF 5D C3 00 00 62 61 74 6F 6E 72 6F 75 - ´.Í.°.´.Í.éèÿ´.Í.éáÿ]Ã..batonrou
67 65 2C 6C 61 2D 69 6E 64 69 61 6E 61 70 6F 6C 69 73 2C 69 6E 2D 63 6F 6C 75 6D 62 75 73 2C 6F - ge,la-indianapolis,in-columbus,o
68 2D 6D 6F 6E 74 67 6F 6D 65 72 79 2C 61 6C 2D 68 65 6C 65 6E 61 2C 6D 74 2D 64 65 6E 76 65 72 - h-montgomery,al-helena,mt-denver
2C 63 6F 2D 62 6F 69 73 65 2C 69 64 2D 61 75 73 74 69 6E 2C 74 78 2D 62 6F 73 74 6F 6E 2C 6D 61 - ,co-boise,id-austin,tx-boston,ma
2D 61 6C 62 61 6E 79 2C 6E 79 2D 74 61 6C 6C 61 68 61 73 73 65 65 2C 66 6C 2D 73 61 6E 74 61 66 - -albany,ny-tallahassee,fl-santaf
65 2C 6E 6D 2D 6E 61 73 68 76 69 6C 6C 65 2C 74 6E 2D 74 72 65 6E 74 6F 6E 2C 6E 6A 2D 6A 65 66 - e,nm-nashville,tn-trenton,nj-jef
66 65 72 73 6F 6E 2C 6D 6F 2D 72 69 63 68 6D 6F 6E 64 2C 76 61 2D 70 69 65 72 72 65 2C 73 64 2D - ferson,mo-richmond,va-pierre,sd-
68 61 72 72 69 73 62 75 72 67 2C 70 61 2D 61 75 67 75 73 74 61 2C 6D 65 2D 70 72 6F 76 69 64 65 - harrisburg,pa-augusta,me-provide
6E 63 65 2C 72 69 2D 64 6F 76 65 72 2C 64 65 2D 63 6F 6E 63 6F 72 64 2C 6E 68 2D 6D 6F 6E 74 70 - nce,ri-dover,de-concord,nh-montp
65 6C 69 65 72 2C 76 74 2D 68 61 72 74 66 6F 72 64 2C 63 74 2D 74 6F 70 65 6B 61 2C 6B 73 2D 73 - elier,vt-hartford,ct-topeka,ks-s
61 69 6E 74 20 70 61 75 6C 2C 6D 6E 2D 6A 75 6E 65 61 75 2C 61 6B 2D 6C 69 6E 63 6F 6C 6E 2C 6E - aint paul,mn-juneau,ak-lincoln,n
65 2D 72 61 6C 65 69 67 68 2C 6E 63 2D 6D 61 64 69 73 6F 6E 2C 77 69 2D 6F 6C 79 6D 70 69 61 2C - e-raleigh,nc-madison,wi-olympia,
77 61 2D 70 68 6F 65 6E 69 78 2C 61 7A 2D 6C 61 6E 73 69 6E 67 2C 6D 69 2D 68 6F 6E 6F 6C 75 6C - wa-phoenix,az-lansing,mi-honolul
75 2C 68 69 2D 6A 61 63 6B 73 6F 6E 2C 6D 73 2D 73 70 72 69 6E 67 66 69 65 6C 64 2C 69 6C 2D 63 - u,hi-jackson,ms-springfield,il-c
6F 6C 75 6D 62 69 61 2C 73 63 2D 61 6E 6E 61 70 6F 6C 69 73 2C 6D 64 2D 63 68 65 79 65 6E 6E 65 - olumbia,sc-annapolis,md-cheyenne
2C 77 79 2D 73 61 6C 74 20 6C 61 6B 65 20 63 69 74 79 2C 75 74 2D 61 74 6C 61 6E 74 61 2C 67 61 - ,wy-salt lake city,ut-atlanta,ga
2D 62 69 73 6D 61 72 63 6B 2C 6E 64 2D 66 72 61 6E 6B 66 6F 72 74 2C 6B 79 2D 73 61 6C 65 6D 2C - -bismarck,nd-frankfort,ky-salem,
6F 72 2D 6C 69 74 74 6C 65 20 72 6F 63 6B 2C 61 72 2D 64 65 73 20 6D 6F 69 6E 65 73 2C 69 61 2D - or-little rock,ar-des moines,ia-
73 61 63 72 61 6D 65 6E 74 6F 2C 63 61 2D 6F 6B 6C 61 68 6F 6D 61 20 63 69 74 79 2C 6F 6B 2D 63 - sacramento,ca-oklahoma city,ok-c
68 61 72 6C 65 73 74 6F 6E 2C 77 76 2D 63 61 72 73 6F 6E 20 63 69 74 79 2C 6E 76 00 - harleston,wv-carson city,nv.
```
'Un-golfed' version (source - 3126 bytes)
```
[section .text]
[bits 16]
[org 0x100]
entry_point:
push word capital_list
call output_string
int 0x20
; input:
; al = char
; outpt:
; if al if an alpha char, ensures it is in range [capital-a .. capital-z]
toupper:
mov bl, 98
dec bl ; bl = 'a'
mov bh, bl
add bh, 25 ; bh = 'z'
cmp al, bl ;'a'
jb .toupperdone
cmp al, bh
ja .toupperdone
xor bl, bl
inc bl
shl bl, 5 ; bl = 32
sub al, bl ;capital'a' - 'a' (32)
.toupperdone:
ret
;void outputstring(char *str)
outputstring:
push bp
mov bp, sp
add bp, 4
mov si, [bp + 0] ; si --> string
mov di, si
; I run over the text in two passes - because I'm too tired right now to make it
; a tighter, more efficient loop. Perhaps after some sleep.
; In the first pass, I just convert the appropriate chars to upper-case
.get_char_pass_1:
lodsb
test al, 0xff
jz .pass_1_done
cmp [last_char], byte 0
jne .not_first_char
call toupper
stosb
mov [last_char], al
jmp .get_char_pass_1
.not_first_char:
.check_if_sep:
cmp al, ',' ; if this char is a comma, the next 2 need to be uppercase
jne .not_seperator
stosb ; spit out the comma, unchanged
lodsb
call toupper
stosb
lodsb
call toupper
stosb
.gobble_delim:
lodsb ; take care of the '-' delimiter
stosb
.capitalize_first_letter_of_city:
lodsb ; the following char is the first char of the city, capitalize it
call toupper
stosb
mov [last_char], al
jmp .get_char_pass_1 ; go back for more
.not_seperator:
cmp [last_char], byte ' '
jne .output_this_char
call toupper
.output_this_char:
stosb
mov [last_char], al
jmp .get_char_pass_1
.pass_1_done:
; In the second pass, I print the characters, except for the delimiters, which are skipped and
; instead print a CRLF pair so that each city/state pair begins on a new line.
;
pass_2:
mov si, [bp+0] ; point to string again
.pass_2_load_char:
lodsb
test al, 0xff
jz .pass_2_done
cmp al, '-' ; current char is a delimiter, dont print it - instead,
; print a carriage-return/line-feed pair
jne .not_delim_2
mov al, 0xd ; LF
mov ah, 0xe
int 0x10
mov al, 0xa ; CR
mov ah, 0xe
int 0x10
jmp .pass_2_load_char
.not_delim_2:
mov ah, 0xe
int 0x10
jmp .pass_2_load_char
.pass_2_done:
pop bp
ret
last_char db 0
[section .data]
capital_list db 'batonrouge,la-indianapolis,in-columbus,oh-montgomery,al-helena,mt-denver,co-boise,id-'
db 'austin,tx-boston,ma-albany,ny-tallahassee,fl-santafe,nm-nashville,tn-trenton,nj-'
db 'jefferson,mo-richmond,va-pierre,sd-harrisburg,pa-augusta,me-providence,ri-dover,de-'
db 'concord,nh-montpelier,vt-hartford,ct-topeka,ks-saint paul,mn-juneau,ak-lincoln,ne-'
db 'raleigh,nc-madison,wi-olympia,wa-phoenix,az-lansing,mi-honolulu,hi-jackson,ms-'
db 'springfield,il-columbia,sc-annapolis,md-cheyenne,wy-salt lake city,ut-atlanta,ga-'
db 'bismarck,nd-frankfort,ky-salem,or-little rock,ar-des moines,ia-sacramento,ca-'
db 'oklahoma city,ok-charleston,wv-carson city,nv',0
```
Output:
```
Baton Rouge,LA
Indianapolis,IN
Columbus,OH
Montgomery,AL
Helena,MT
Denver,CO
Boise,ID
Austin,TX
Boston,MA
Albany,NY
Tallahassee,FL
Santa Fe,NM
Nashville,TN
Trenton,NJ
Jefferson,MO
Richmond,VA
Pierre,SD
Harrisburg,PA
Augusta,ME
Providence,RI
Dover,DE
Concord,NH
Montpelier,VT
Hartford,CT
Topeka,KS
Saint Paul,MN
Juneau,AK
Lincoln,NE
Raleigh,NC
Madison,WI
Olympia,WA
Phoenix,AZ
Lansing,MI
Honolulu,HI
Jackson,MS
Springfield,IL
Columbia,SC
Annapolis,MD
Cheyenne,WY
Salt Lake City,UT
Atlanta,GA
Bismarck,ND
Frankfort,KY
Salem,OR
Little Rock,AR
Des Moines,IA
Sacramento,CA
Oklahoma City,OK
Charleston,WV
Carson City,NV
```
[Answer]
# Python 3, ~~1416~~ ~~793~~ ~~785~~ ~~779~~ ~~771~~ ~~755~~ 734 characters - 20% = 587.2
No algorithmic cleverness here, I just took the required output, sorted it (this lets zlib do a better job), compressed it (using `zopfli --deflate`), base64-encoded the result, and then changed the encoding around to avoid capital letters.
```
import zlib,base64;print(zlib.decompress(base64.b64decode('>_"@sq*w%>yf^+?!|#-#rii*hezbdf9()#_&m&",s;bb74@n7_93,t>d09rek;+~<l1":+>sr!m~qgv?0[,)z;?>$|p5.i)hegtak<&:db9hg9(xat3yp%x_(j}m]<j7^d?-2$g]5.l:-:g/{da?ow+ykpu}..8g)9"b+h7/[p]ex%x#rp!7u0w3*66|/%:{idbsh|$v/&0^9l!?v8hn-m8%"l^7wx]%_k>h1k(xh~1))h/<x0wdr7")7024.f6~qb;<;$5{tby$>_nid-d!x+,pl0zt[yj5bv"/<+^,$ti>}]3q!gd6>:h/sw}<#x>-lj5#h@w:i01d?m^ks2|,v"^coy^p.l{l{6jxbs,a??m14/h0%/m3j-q_zm@;uu[rgx<(4{{s,en/":1oc|!]fvpsjt$}9z?b&#^;58%@m78i8wf<*u",mizg7;3.3*l7o{0,._oyz0&y5d#afpgc38_-ww_7jx;xd;,:ooaj<u;i5~y]^%u]{.},@_|h[,8^>zt54ohq@y,aw2|20s)$k"|dso*<ra](%%jm<+&upl%[)y/?+{[|<jr8!w=='.translate({ord(x):y+60+5 for x,y in zip('!"#$%&()*,-.:;<>?@[]^_{|}~',range(26))})),-9).decode('u8'))
```
Un-golfed:
```
import zlib, base64
DATA = '>_"@sq*w%>yf^+?!|#-#rii*hezbdf9()#_&m&",s;bb74@n7_93,t>d09rek;+~<l1":+>sr!m~qgv?0[,)z;?>$|p5.i)hegtak<&:db9hg9(xat3yp%x_(j}m]<j7^d?-2$g]5.l:-:g/{da?ow+ykpu}..8g)9"b+h7/[p]ex%x#rp!7u0w3*66|/%:{idbsh|$v/&0^9l!?v8hn-m8%"l^7wx]%_k>h1k(xh~1))h/<x0wdr7")7024.f6~qb;<;$5{tby$>_nid-d!x+,pl0zt[yj5bv"/<+^,$ti>}]3q!gd6>:h/sw}<#x>-lj5#h@w:i01d?m^ks2|,v"^coy^p.l{l{6jxbs,a??m14/h0%/m3j-q_zm@;uu[rgx<(4{{s,en/":1oc|!]fvpsjt$}9z?b&#^;58%@m78i8wf<*u",mizg7;3.3*l7o{0,._oyz0&y5d#afpgc38_-ww_7jx;xd;,:ooaj<u;i5~y]^%u]{.},@_|h[,8^>zt54ohq@y,aw2|20s)$k"|dso*<ra](%%jm<+&upl%[)y/?+{[|<jr8!w=='
TR = { ord(x) : y+60+5
for x,y in zip('!"#$%&()*,-.:;<>?@[]^_{|}~', range(26)) }
print(zlib.decompress(base64.b64decode(DATA.translate(TR)),
-9)
.decode('utf-8'))
```
There is probably more to be squeezed out of this, especially if you can express the argument to `translate()` more compactly. Note that the punctuation in there is carefully chosen to avoid base64's own punctuation (+/=) and anything that would need backwhacking in a string literal.
Fun fact: the bz2 and lzma modules both do *worse* on this input than zlib:
```
>>> z = base64.b64decode('>_"@sq*w%>yf^+?!|#-#rii*hezbdf9()#_&m&",s;bb74@n7_93,t>d09rek;+~<l1":+>sr!m~qgv?0[,)z;?>$|p5.i)hegtak<&:db9hg9(xat3yp%x_(j}m]<j7^d?-2$g]5.l:-:g/{da?ow+ykpu}..8g)9"b+h7/[p]ex%x#rp!7u0w3*66|/%:{idbsh|$v/&0^9l!?v8hn-m8%"l^7wx]%_k>h1k(xh~1))h/<x0wdr7")7024.f6~qb;<;$5{tby$>_nid-d!x+,pl0zt[yj5bv"/<+^,$ti>}]3q!gd6>:h/sw}<#x>-lj5#h@w:i01d?m^ks2|,v"^coy^p.l{l{6jxbs,a??m14/h0%/m3j-q_zm@;uu[rgx<(4{{s,en/":1oc|!]fvpsjt$}9z?b&#^;58%@m78i8wf<*u",mizg7;3.3*l7o{0,._oyz0&y5d#afpgc38_-ww_7jx;xd;,:ooaj<u;i5~y]^%u]{.},@_|h[,8^>zt54ohq@y,aw2|20s)$k"|dso*<ra](%%jm<+&upl%[)y/?+{[|<jr8!w=='.translate({ord(x):ord(y)-32 for x,y in zip('!"#$%&()*,-.:;<>?@[]^_{|}~','abcdefghijklmnopqrstuvwxyz')}))
>>> u = zlib.decompress(x,-9)
>>> len(u)
663
>>> len(z)
427
>>> len(zlib.compress(z))
437
>>> len(bz2.compress(z))
456
>>> len(lzma.compress(z))
620
```
[Answer]
# Pyth, (631 -20%) = 504.8
```
=k!kmrd=k-6kc"baton rouge,la,indianapolis,in,columbus,oh,montgomery,al,helena,mt,denver,co,boise,id,austin,tx,boston,ma,albany,ny,tallahassee,fl,santa fe,nm,nashville,tn,trenton,nj,jefferson,mo,richmond,va,pierre,sd,harrisburg,pa,augusta,me,providence,ri,dover,de,concord,nh,montpelier,vt,hartford,ct,topeka,ks,saint paul,mn,juneau,ak,lincoln,ne,raleigh,nc,madison,wi,olympia,wa,phoenix,az,lansing,mi,honolulu,hi,jackson,ms,springfield,il,columbia,sc,annapolis,md,cheyenne,wy,salt lake city,ut,atlanta,ga,bismarck,nd,frankfort,ky,salem,or,little rock,ar,des moines,ia,sacramento,ca,oklahoma city,ok,charleston,wv,carson city,nv"","
```
### Output:
```
['Baton Rouge', 'LA', 'Indianapolis', 'IN', 'Columbus', 'OH', 'Montgomery', 'AL', 'Helena', 'MT', 'Denver', 'CO', 'Boise', 'ID', 'Austin', 'TX', 'Boston', 'MA', 'Albany', 'NY', 'Tallahassee', 'FL', 'Santa Fe', 'NM', 'Nashville', 'TN', 'Trenton', 'NJ', 'Jefferson', 'MO', 'Richmond', 'VA', 'Pierre', 'SD', 'Harrisburg', 'PA', 'Augusta', 'ME', 'Providence', 'RI', 'Dover', 'DE', 'Concord', 'NH', 'Montpelier', 'VT', 'Hartford', 'CT', 'Topeka', 'KS', 'Saint Paul', 'MN', 'Juneau', 'AK', 'Lincoln', 'NE', 'Raleigh', 'NC', 'Madison', 'WI', 'Olympia', 'WA', 'Phoenix', 'AZ', 'Lansing', 'MI', 'Honolulu', 'HI', 'Jackson', 'MS', 'Springfield', 'IL', 'Columbia', 'SC', 'Annapolis', 'MD', 'Cheyenne', 'WY', 'Salt Lake City', 'UT', 'Atlanta', 'GA', 'Bismarck', 'ND', 'Frankfort', 'KY', 'Salem', 'OR', 'Little Rock', 'AR', 'Des Moines', 'IA', 'Sacramento', 'CA', 'Oklahoma City', 'OK', 'Charleston', 'WV', 'Carson City', 'NV']
```
The second parameter for `r` alternates between 5 (`capwords()`) and 1 (`upper()`)
[Answer]
# PowerShell, ~~1038~~ ~~976~~ ~~925~~ ~~904~~ ~~813~~ ~~768~~ ~~758~~ ~~749~~ 745 -20% = 596
```
"labaton rouge;inindianapolis;ohcolumbus;almontgomery;mthelena;codenver;idboise;txaustin;maboston;nyalbany;fltallahassee;nmsanta fe;tnnashville;njtrenton;mojefferson;varichmond;sdpierre;paharrisburg;meaugusta;riprovidence;dedover;nhconcord;vtmontpelier;cthartford;kstopeka;mnsaint paul;akjuneau;nelincoln;ncraleigh;wimadison;waolympia;azphoenix;milansing;hihonolulu;msjackson;ilspringfield;sccolumbia;mdannapolis;wycheyenne;utsalt lake city;gaatlanta;ndbismarck;kyfrankfort;orsalem;arlittle rock;iades moines;casacramento;okoklahoma city;wvcharleston;nvcarson city"-split";"|%{$a=-split$_;$b={$n,$i=$args;if($a[$n]){" "+(""+$a[$n][$i++]).toupper()+$a[$n].substring($i)}};$(&$b(0)2).trim()+$(&$b(3-2)0)+$(&$b(2)0)+","+$_.substring(0,2).toupper()}
```
**Ungolfed:**
```
"labaton rouge;inindianapolis;ohcolumbus;almontgomery;mthelena;codenver;idboise;txaustin;maboston;nyalbany;fltallahassee;nmsanta fe;tnnashville;njtrenton;mojefferson;varichmond;sdpierre;paharrisburg;meaugusta;riprovidence;dedover;nhconcord;vtmontpelier;cthartford;kstopeka;mnsaint paul;akjuneau;nelincoln;ncraleigh;wimadison;waolympia;azphoenix;milansing;hihonolulu;msjackson;ilspringfield;sccolumbia;mdannapolis;wycheyenne;utsalt lake city;gaatlanta;ndbismarck;kyfrankfort;orsalem;arlittle rock;iades moines;casacramento;okoklahoma city;wvcharleston;nvcarson city"-split";"|%{
$a=-split$_;
$b={
$n,$i=$args;
if($a[$n]){
" "+
(""+$a[$n][$i++]).toupper()+
$a[$n].substring($i)
}
};
$(&$b(0)2).trim()+
$(&$b(3-2)0)+
$(&$b(2)0)+
","+
$_.substring(0,2).toupper()
}
```
[Answer]
## [Minkolang 0.7](https://github.com/elendiastarman/Minkolang), ~~660~~ ~~705~~ 708 \* 0.8 = 566.4
```
99*32-+58*0p467+35*44*55*d8+d5+(99*2-23-r32-p)"baton rouge, laindianapolis, incolumbus, ohmontgomery, alhelena, mtdenver, coboise, idaustin, txboston, maalbany, nytallahassee, flsanta fe, nmnashville, tntrenton, njjefferson, morichmond, vapierre, sdharrisburg, paaugusta, meprovidence, ridover, deconcord, nhmontpelier, vthartford, cttopeka, kssaint paul, mnjuneau, aklincoln, neraleigh, ncmadison, wiolympia, waphoenix, azlansing, mihonolulu, hijackson, msspringfield, ilcolumbia, scannapolis, mdcheyenne, wysalt lake city, utatlanta, gabismarck, ndfrankfort, kysalem, orlittle rock, ardes moines, iasacramento, caoklahoma city, okcharleston, wvcarson city, nv"032-w
48*-o(d","=2&o)oo22$[48*-o]d?.25*o48*-o)
```
Thanks to **Sp3000** for reminding me that I can use `p` to put capital Os in the code!
### Explanation
The bit of the first line before the `"` does nothing but put a `R` (rotate stack) in place of `r` and then replace all of the instances of `o` with `O` on the second line.
After that, it's the list of capitals without newlines and all letters lowercased, which is pushed onto the stack in reverse order by Minkolang. There is a `01w` at the end which is a "wormhole" to the beginning of the second line. All capital letters are outputted by subtracting 32 from the lowercase letter, which is why `48*-` shows up four times.
`48*-O` outputs `B`, then `(` begins a while loop. The top of stack is checked against `,`. If it's not `,`, then `O)` outputs the character and jumps back to the beginning of the loop. If the top of stack *is* `,`, then the program counter jumps over `O)` because of `2&`, a conditional trampoline that jumps two spaces.
Now, I jump when I encounter a `,` because I know the next six characters are `, AB\nC`, which is what the rest of the loop does. There is a check to see if the stack is empty in the middle (after `AB` is printed, before `\nC`): `d?`. If it is, then the conditional trampoline is not taken and the program exits upon hitting the `.`. Otherwise, it's skipped and the loop continues.
[Answer]
# PHP 520 bytes (650 bytes - 20%)
```
foreach(explode(',','baton rouge,indianapolis,columbus,montgomery,helena,denver,boise,austin,boston,albany,tallahassee,santa fe,nashville,trenton,jefferson,richmond,pierre,harrisburg,augusta,providence,dover,concord,montpelier,hartford,topeka,saint paul,juneau,lincoln,raleigh,madison,olympia,phoenix,lansing,honolulu,jackson,springfield,columbia,annapolis,cheyenne,salt lake city,atlanta,bismarck,frankfort,salem,little rock,des moines,sacramento,oklahoma city,charleston,carson city')as$k=>$v)echo ucwords($v).','.strtoupper(substr('lainohalmtcoidtxmanyflnmtnnjmovasdpameridenhvtctksmnaknencwiwaazmihimsilscmdwyutgandkyorariacaokwvnv',$k*2,2)).'_';
```
**Result**
>
> Baton Rouge,LA\_Indianapolis,IN\_ …
>
>
>
**Ungolfed:**
```
$cities = 'baton rouge,indianapolis,columbus,montgomery,helena,denver,boise,austin,boston,albany,tallahassee,santa fe,nashville,trenton,jefferson,richmond,pierre,harrisburg,augusta,providence,dover,concord,montpelier,hartford,topeka,saint paul,juneau,lincoln,raleigh,madison,olympia,phoenix,lansing,honolulu,jackson,springfield,columbia,annapolis,cheyenne,salt lake city,atlanta,bismarck,frankfort,salem,little rock,des moines,sacramento,oklahoma city,charleston,carson city';
$states = 'lainohalmtcoidtxmanyflnmtnnjmovasdpameridenhvtctksmnaknencwiwaazmihimsilscmdwyutgandkyorariacaokwvnv';
foreach(explode(',',$cities) as $k => $v)
echo ucwords($v)
. ','
. strtoupper(
substr($states, $k * 2, 2)
)
. '_';
```
I tried various ways to compress the string, but in the end all solutions were longer than this straight forward approach.
[Answer]
# Python 2, 658 bytes \* 0.8 = 526.4
```
print zip([c.title()for c in"baton rouge.indianapolis.columbus.montgomery.helena.denver.boise.austin.boston.albany.tallahassee.santa fe.nashville.trenton.jefferson.richmond.pierre.harrisburg.augusta.providence.dover.concord.montpelier.hartford.topeka.saint paul.juneau.lincoln.raleigh.madison.olympia.phoenix.lansing.honolulu.jackson.springfield.columbia.annapolis.cheyenne.salt lake city.atlanta.bismarck.frankfurt.salem.little rock.des moines.sacramento.oklahoma city.charleston.carson city".split('.')],[s.upper()for s in map(''.join,zip(*[iter("lainohalmtcoidtxmanyflnmtnnjmovasdpameridenhvtctksmnaknencwiwaazmihimsilscmdwyutgandkyorariacaokwvnv")]*2))])
```
Prints the result as a Python list of Python tuples. They are also enclosed in quotes. This definitely qualifies for the bonus since the only number in the code is 2.
Output:
```
[('Baton Rouge', 'LA'), ('Indianapolis', 'IN'), ('Columbus', 'OH'), ('Montgomery', 'AL'), ('Helena', 'MT'), ('Denver', 'CO'), ('Boise', 'ID'), ('Austin', 'TX'), ('Boston', 'MA'), ('Albany', 'NY'), ('Tallahassee', 'FL'), ('Santa Fe', 'NM'), ('Nashville', 'TN'), ('Trenton', 'NJ'), ('Jefferson', 'MO'), ('Richmond', 'VA'), ('Pierre', 'SD'), ('Harrisburg', 'PA'), ('Augusta', 'ME'), ('Providence', 'RI'), ('Dover', 'DE'), ('Concord', 'NH'), ('Montpelier', 'VT'), ('Hartford', 'CT'), ('Topeka', 'KS'), ('Saint Paul', 'MN'), ('Juneau', 'AK'), ('Lincoln', 'NE'), ('Raleigh', 'NC'), ('Madison', 'WI'), ('Olympia', 'WA'), ('Phoenix', 'AZ'), ('Lansing', 'MI'), ('Honolulu', 'HI'), ('Jackson', 'MS'), ('Springfield', 'IL'), ('Columbia', 'SC'), ('Annapolis', 'MD'), ('Cheyenne', 'WY'), ('Salt Lake City', 'UT'), ('Atlanta', 'GA'), ('Bismarck', 'ND'), ('Frankfurt', 'KY'), ('Salem', 'OR'), ('Little Rock', 'AR'), ('Des Moines', 'IA'), ('Sacramento', 'CA'), ('Oklahoma City', 'OK'), ('Charleston', 'WV'), ('Carson City', 'NV')]
```
I hope this is within the acceptable bounds of formatting.
[Answer]
# Groovy, ~~724~~ 681 - 20% = 545 bytes
```
c={it.capitalize()}
'labaton rouge,inindianapolis,ohcolumbus,almontgomery,mthelena,codenver,idboise,txaustin,maboston,nyalbany,fltallahassee,nmsanta fe,tnnashville,njtrenton,mojefferson,varichmond,sdpierre,paharrisburg,meaugusta,riprovidence,dedover,nhconcord,vtmontpelier,cthartford,kstopeka,mnsaint paul,akjuneau,nelincoln,ncraleigh,wimadison,waolympia,azphoenix,milansing,hihonolulu,msjackson,ilspringfield,sccolumbia,mdannapolis,wycheyenne,utsalt lake city,gaatlanta,ndbismarck,kyfrankfort,orsalem,arlittle rock,iades moines,casacramento,okoklahoma city,wvcharleston,nvcarson city'.split(',').each{it.substring(2).split(' ').each{print c(it) + ' '}println c(it[0])+c(it[3-2])}
```
Inspired by Edc65's clever smushing together of state and city name!
[Answer]
## PowerShell, 627 -20% = 502 bytes
```
[regex]::replace('baton rougela;indianapolisin;columbusoh;montgomeryal;helenamt;denverco;boiseid;austintx;bostonma;albanyny;tallahasseefl;santa fenm;nashvilletn;trentonnj;jeffersonmo;richmondva;pierresd;harrisburgpa;augustame;providenceri;doverde;concordnh;montpeliervt;hartfordct;topekaks;saint paulmn;juneauak;lincolnne;raleighnc;madisonwi;olympiawa;phoenixaz;lansingmi;honoluluhi;jacksonms;springfieldil;columbiasc;annapolismd;cheyennewy;salt lake cityut;atlantaga;bismarcknd;frankfortky;salemor;little rockar;des moinesia;sacramentoca;oklahoma cityok;charlestonwv;carson citynv;','\b\w|..;',{"$args,"[3]+"$args".toupper()})
```
Which is this pattern:
```
[regex]::replace('baton rougela;','\b\w|..;',{"$args,"[3]+"$args".toupper()})
```
Uppercase the single letter after a word boundary, or the double letters before a colon. The `"$args,"[3]` selects either the comma in the case of a double letter state code, or overselects and returns null, and adds the state separators, saving ~50 in separators from the code line.
[Answer]
## Ruby, (925 \* 80%) = 740 bytes
```
require "zlib";eval "puts \x5alib::inflate('789c35925db2da300c85dfb50a16a04d98044a203f0ca450faa64b44e2892333b6c394dd57e1b66fdfb1251fe98c8dfb2279637d0323424fef6cc42a07931c4922fc61c0ccfd1c15ab8d624c56b0fd056b4a5e56273ff78ca581b58d1385fb88750e6b6f2363b140d422ac0c6414a2966736a9d305b28182e3cfe57551fc6611c6eb0d32efe6e9cb129eb37f3c476c76ca72f7a1c37a0739cb8b03668d525c55de0a472c0ce47e39ce37b00d24e3c38784871bec28041bbfe6d0e3d12c2a3d9677b21676ec58742b252f6ae566dc15504867e97f0e450d7bba8f7159e20c7b7e3c387c4403fb59986634072849a2951eab024aab533ac17aa39892630d48333127a8a8b34be7b580ca4beafdc4e18da6fca8273baba35f5aa8290e2feb1c635b43333a1afc44dfb1350768dc7b7a6a365703c7c1b3d83f687ec3517b03e3398763f02fdbb1dc194f059cc8b1ed07ac3338d9fb3079e9f062e04cf740134bf2982dca4a5a1d697658d5aa1c4fd89c1648ab9246fef6fed9ea89fe86d596b1aee0fc0cbaf0c3b2ebb028a125a783528cccb855e99f3c121eced086c546e3d8c35f3dcecbfd'.scan(/.{2}/).map {|i|i.hex.chr}.join)"
```
Oof, this one was hard. This is a Zlib compressed string in hex encoded bytes, which is then decompressed, turned into an array of strings by the scan regex, then each string is converted to a decimal integer, then to a character, and finally this array is joined into a string. I might post a better version later that uses a modified base64 encoding.
Though the encoded string may have some instances of 65-90 or 1's, I don't count those because the string is one huge number in hexadecimal. Thus this qualifies for the 20% bonus.
[Answer]
## Python 2, 639 bytes - 20% = 511.2
```
t="labaton rouge,inindianapolis,ohcolumbus,almontgomery,mthelena,codenver,idboise,txaustin,maboston,nyalbany,fltallahassee,nmsanta fe,tnnashville,njtrenton,mojefferson,varichmond,sdpierre,paharrisburg,meaugusta,riprovidence,dedover,nhconcord,vtmontpelier,cthartford,kstopeka,mnsaint paul,akjuneau,nelincoln,ncraleigh,wimadison,waolympia,azphoenix,milansing,hihonolulu,msjackson,ilspringfield,sccolumbia,mdannapolis,wycheyenne,utsalt lake city,gaatlanta,ndbismarck,kyfrankfurt,orsalem,arlittle rock,iades moines,casacramento,okoklahoma city,wvcharleston,nvcarson city".split(",");print[(t[n][:2].upper(),t[n][2:].title())for n in range(50)]
```
The version bellow (675 bytes) has `''.join([w.capitalize()for w in t[n][2:].split()])` in it, which I just discovered can be replace by `.title()`, and is an anonymous function. In both answers, the state abbreviations are attached to the capitals.
```
lambda t="labaton rouge,inindianapolis,ohcolumbus,almontgomery,mthelena,codenver,idboise,txaustin,maboston,nyalbany,fltallahassee,nmsanta fe,tnnashville,njtrenton,mojefferson,varichmond,sdpierre,paharrisburg,meaugusta,riprovidence,dedover,nhconcord,vtmontpelier,cthartford,kstopeka,mnsaint paul,akjuneau,nelincoln,ncraleigh,wimadison,waolympia,azphoenix,milansing,hihonolulu,msjackson,ilspringfield,sccolumbia,mdannapolis,wycheyenne,utsalt lake city,gaatlanta,ndbismarck,kyfrankfurt,orsalem,arlittle rock,iades moines,casacramento,okoklahoma city,wvcharleston,nvcarson city".split(","):[(t[n][:2].upper(),''.join([w.capitalize()for w in t[n][2:].split()]))for n in range(50)]
```
[Answer]
# x86 machine-code - 585 bytes, 468 with bonus
Dissapointed with how large my last entry was, I decided to try something very different this time. Drawing on `insertusernamehere`'s idea of separating the city names from the state names, thus avoiding unnecessary logic and unneeded terminators, I still thought I've gotta be able to make the program smaller than the raw strings are. UPX wouldn't help me to cheat, complaining that the program was already too small. Thinking about compression, I tried to compress the 662 byte text output with WinRar but still only got 543 bytes - and that was without anything to decompress it with. It still seemed far too large, given that it was just the result, without any code.
Then I realized - I'm only using 26 chars for the letters and another 2 for the spaces and the commas. Hmm, that fits into 32, which needs just 5 bits. So, I wrote a quick javascript program to encode the strings, assigning a-z to 0-25 and space and comma got 26 and 27. To keep things simple, every character is encoded in 5 bits, whether it needs this many or not. From there, I just stuck
all the bits together and broke them back into byte-sized chunks. This allowed me to pack the 563 bytes of strings into 353 bytes - a saving of 37.5% or some 210 bytes. I didn't quite manage to squeeze the program and data into the same space as just the unpacked data, but I came close enough to be happy.
Hxd view of binary:
```
68 3F 00 68 E8 01 68 4F 03 E8 1C 00 68 22 01 68 27 02 68 B3 03 E8 10 00 - h?.hè.hO.è..h".h'.h³.è..
BE 83 05 C6 04 00 68 4F 03 68 B3 03 E8 62 00 C3 55 89 E5 81 C5 04 00 8B - ¾ƒ.Æ..hO.h³.èb.ÃU‰å.Å..‹
76 02 8B 7E 00 B6 05 30 DB AC B2 08 D0 D0 D0 D3 FE CA FE CE 75 1E 80 FB - v.‹~.¶.0Û¬².ÐÐÐÓþÊþÎu.€û
1A 75 05 B3 20 E9 0D 00 80 FB 1B 75 05 B3 2C E9 03 00 80 C3 61 88 1D 47 - .u.³ é..€û.u.³,é..€Ãaˆ.G
B6 05 30 DB 08 D2 75 D4 FF 4E 04 75 CC 5D C2 06 00 53 B3 62 FE CB 88 DF - ¶.0Û.ÒuÔÿN.uÌ]Â..S³bþˈß
80 C7 19 38 D8 72 08 38 F8 77 04 B3 20 28 D8 5B C3 55 89 E5 81 C5 04 00 - €Ç.8Ør.8øw.³ (Ø[ÃU‰å.Å..
8B 76 00 31 C0 88 C2 89 C1 AC A8 FF 74 46 80 FA 20 74 35 08 D2 74 31 3C - ‹v.1ÀˆÂ‰Á¬¨ÿtF€ú t5.Òt1<
2C 75 30 B4 0E CD 10 89 CB 01 DB 03 5E 02 8A 07 E8 B6 FF CD 10 43 8A 07 - ,u0´.Í.‰Ë.Û.^.Š.è¶ÿÍ.CŠ.
E8 AE FF CD 10 B0 0D CD 10 B0 0A CD 10 C6 06 4C 03 00 30 D2 41 E9 C1 FF - è®ÿÍ.°.Í.°.Í.Æ.L..0ÒAéÁÿ
E8 96 FF B4 0E CD 10 88 C2 E9 B5 FF 5D C2 04 00 58 10 D7 1C 0B 64 C4 E4 - è–ÿ´.Í.ˆÂéµÿ]Â..X.×..dÄä
0E 77 60 1B 82 AD AC 9B 5A 96 3A A0 90 DE 06 12 28 19 1A 7A CC 53 54 98 - .w`.‚.¬›Z–: .Þ..(..zÌST˜
D0 29 A4 68 AC 8B 00 19 62 0E 86 49 0B 90 98 3B 62 93 30 1A 35 61 D1 04 - Ð)¤h¬‹..b.†I..˜;b“0.5aÑ.
50 01 01 CA B5 5B 50 08 26 E6 EA 2E A1 89 B4 34 68 03 40 F7 2D 12 D8 9C - P..ʵ[P.&æê.¡‰´4h.@÷-.Øœ
BA 30 34 96 D8 E6 CC CE 61 23 8D 9C 8B 23 41 B1 91 B5 24 76 17 22 44 D8 - º04–ØæÌÎa#.œ‹#A±‘µ$v."DØ
29 29 A1 BB 0B A5 37 37 60 58 40 DC 6E 60 5A C0 70 4A 44 26 E4 06 CC 1A - ))¡».¥77`X@Ün`ZÀpJD&ä.Ì.
29 36 D0 48 F5 42 D6 4D CE 24 6C DC DD A4 85 29 23 27 37 71 40 8E C7 34 - )6ÐHõBÖMÎ$lÜݤ…)#'7q@ŽÇ4
7B 7A 09 18 93 67 04 62 89 06 91 36 C1 43 52 53 06 DF 17 55 03 23 44 4D - {z..“g.b‰.‘6ÁCRS.ß.U.#DM
8D D5 24 76 27 34 4E 88 F6 C7 36 6F 22 D0 48 EC E0 8C CA E8 8F 73 73 C8 - .Õ$v'4NˆöÇ6o"ÐHìàŒÊè.ssÈ
A0 6E 40 43 67 A7 82 8B DA 68 D2 02 9B 5A 1A 27 2D BB 88 16 44 18 FB 60 - n@Cg§‚‹ÚhÒ.›Z.'-»ˆ.D.û`
06 89 39 BB 72 F0 C7 A0 1B 79 DC 46 A2 FB 58 1B 24 34 DB 3B 9A E5 D1 74 - .‰9»rðÇ .yÜF¢ûX.$4Û;šåÑt
DA 40 25 49 CD DC 9F 14 34 C5 41 16 3D 89 CB A3 02 80 6C 0D 68 1E E5 A2 - Ú@%IÍÜŸ.4ÅA.=‰Ë£.€l.h.å¢
5B 11 C9 82 35 A4 DC 80 B9 E9 60 51 34 24 4F 1B 04 D6 06 CC 1B 0A 24 C0 - [.É‚5¤Ü€¹é`Q4$O..Ö.Ì..$À
44 4A D9 62 06 A8 AE 8C F7 20 2C 8C DA D1 39 AC 9A 8B 84 AD 8C 92 D3 1C - DJÙb.¨®Œ÷ ,ŒÚÑ9¬š‹„.Œ’Ó.
86 92 5B 90 05 10 30 8D 9B B6 E5 2C 07 73 01 A1 22 78 D8 8E 08 AC 92 9B - †’[...0.›¶å,.s.¡"xØŽ.¬’›
9B B1 02 32 73 74 24 4F 1B - ›±.2st$O.
```
Source-code:
```
[section .text]
[bits 16]
[org 0x100]
entry_point:
push word 63 ; no of bytes of packed data = (5/8) * unpacked_length - rounded up tp nearest byte
push word states_packed
push word states_unpacked
call unpack_bytes
push word 290 ; no bytes of packed data
push word capitals_packed
push word capitals_unpacked
call unpack_bytes
; ensure there's a terminating null after the capitals
mov si, nullTerminator
mov [si], byte 0
;void outputStrings(char *cities, char *states)
push word states_unpacked
push word capitals_unpacked
call output_strings
; int 0x20
ret
;void unpack_states(char *unpackedDest, char *packedInput, int packed_length)
;unpack_capitals:
unpack_bytes:
push bp
mov bp, sp
add bp, 4
mov si, [bp + 2] ; point to the packed input
mov di, [bp + 0] ; point to the output buffer
mov dh, 5 ; number of bits remaining until we have a full output byte, ready to be translated from [0..25] --> [A..Z] (+65) or 26-->' ' or 27-->','
xor bl, bl ; clear our output accumalator
.unpack_get_byte:
lodsb
mov dl, 8 ; number of bits remaining in this packed byte before we need another one
.unpack_get_next_bit:
rcl al, 1 ; put most significant bit into carry flag
rcl bl, 1 ; and put it into the least significant bit of our accumalator
dec dl ; 1 bit less before we need another packed byte
dec dh ; 1 bit less until this output byte is done
jnz .checkInputBitsRemaining
.transform_output_byte:
cmp bl, 26 ; space is encoded as 26
jne .notSpace
mov bl, ' '
jmp .store_output_byte
.notSpace:
cmp bl, 27 ; comma is encoded as 27
jne .notComma
mov bl, ','
jmp .store_output_byte
.notComma:
.alphaChar:
add bl, 'a' ; change from [0..25] to [A..Z]
.store_output_byte:
mov [di], bl ; store it
inc di ; point to the next output element
mov dh, 5 ; and reset the count of bits till we get here again
xor bl, bl
.checkInputBitsRemaining:
or dl,dl ; see if we've emptied the packed byte yet
jnz .unpack_get_next_bit
dec word [bp + 4] ; decrement the number of bytes of input remaining to be processed
jnz .unpack_get_byte ; if we still have some, go back for more
.unpack_input_processed:
pop bp
ret 6
; input:
; al = char
; outpt:
; if al if an alpha char, ensures it is in range [capital-a .. capital-z]
toupper:
push bx
mov bl, 98
dec bl ; bl = 'a'
mov bh, bl
add bh, 25 ; bh = 'z'
cmp al, bl ;'a'
jb .toupperdone
cmp al, bh
ja .toupperdone
mov bl, 32
sub al, bl ;'A' - 'a'
.toupperdone:
pop bx
ret
;void outputStrings(char *cities, char *states)
output_strings:
push bp
mov bp, sp
add bp, 4
mov si, [bp + 0] ; si --> array of cities
xor ax, ax
; mov [lastChar], al ; last printed char is undefined at this point - we'll use this to know if we're processing the first entry
mov dl, al
; mov [string_index], ax ; zero the string_index too
mov cx, ax ; zero the string_index too
.getOutputChar:
lodsb
test al, 0xff
jz .outputDone ; if we've got a NULL, it's the string terminator so exit
; cmp byte [lastChar], ' ' ; if the last char was a space, we have to capitalize this one
cmp dl, ' ' ; if the last char was a space, we have to capitalize this one
je .make_ucase
; cmp byte [lastChar], 0
or dl, dl ; if this is 0, then it's the first char we've printed, therefore we know it should be capitalized
jz .make_ucase
cmp al, ',' ; if this is a comma, the city is done, so print the comma then do the state and a crlf, finally, increment the string_index
jne .printChar
mov ah, 0xe ; code for print-char, teletype output
int 0x10 ; print the char held in al
; mov bx, [string_index]
mov bx, cx;[string_index]
add bx,bx ; x2 since each state is 2 bytes long
add bx, [bp+2] ; bx --> states_unpacked[string_index]
mov al, [bx] ; get the first char of the state
call toupper ; upper case it
; mov ah, 0xe ;not needed, still set from above
int 0x10 ; and print it
inc bx
mov al, [bx] ; get the 2nd char of the state
call toupper ; uppercase it
; mov ah, 0xe ;not needed, still set from above
int 0x10 ; and print it
mov al, 0x0d ; print a CRLF
int 0x10
mov al, 0x0a
int 0x10
mov byte [lastChar], 0 ; zero this, so that the first letter of the new city will be capitalized, just like the first char in the string was
xor dl, dl ; zero this, so that the first letter of the new city will be capitalized, just like the first char in the string was
; inc word [string_index] ; increment our index, ready for the next city's state
inc cx ;word [string_index] ; increment our index, ready for the next city's state
jmp .getOutputChar ; go back and get the next char of the next city
.make_ucase:
call toupper
.printChar:
mov ah, 0xe
int 0x10
; mov [lastChar], al
mov dl, al
jmp .getOutputChar ; go back and get the next char of the next city
.outputDone:
pop bp
ret 4 ; return and clean-up the two vars from the stack
[section .data]
; 63 packed bytes, 100 unpacked (saved 37)
states_packed:
db 01011000b, 00010000b, 11010111b, 00011100b, 00001011b, 01100100b, 11000100b, 11100100b
db 00001110b, 01110111b, 01100000b, 00011011b, 10000010b, 10101101b, 10101100b, 10011011b
db 01011010b, 10010110b, 00111010b, 10100000b, 10010000b, 11011110b, 00000110b, 00010010b
db 00101000b, 00011001b, 00011010b, 01111010b, 11001100b, 01010011b, 01010100b, 10011000b
db 11010000b, 00101001b, 10100100b, 01101000b, 10101100b, 10001011b, 00000000b, 00011001b
db 01100010b, 00001110b, 10000110b, 01001001b, 00001011b, 10010000b, 10011000b, 00111011b
db 01100010b, 10010011b, 00110000b, 00011010b, 00110101b, 01100001b, 11010001b, 00000100b
db 01010000b, 00000001b, 00000001b, 11001010b, 10110101b, 01011011b, 01010000b
; 290 packed bytes, 463 unpacked (saved 173)
capitals_packed:
db 00001000b, 00100110b, 11100110b, 11101010b, 00101110b, 10100001b, 10001001b, 10110100b, 00110100b, 01101000b, 00000011b, 01000000b, 11110111b, 00101101b
db 00010010b, 11011000b, 10011100b, 10111010b, 00110000b, 00110100b, 10010110b, 11011000b, 11100110b, 11001100b, 11001110b, 01100001b, 00100011b, 10001101b
db 10011100b, 10001011b, 00100011b, 01000001b, 10110001b, 10010001b, 10110101b, 00100100b, 01110110b, 00010111b, 00100010b, 01000100b, 11011000b, 00101001b
db 00101001b, 10100001b, 10111011b, 00001011b, 10100101b, 00110111b, 00110111b, 01100000b, 01011000b, 01000000b, 11011100b, 01101110b, 01100000b, 01011010b
db 11000000b, 01110000b, 01001010b, 01000100b, 00100110b, 11100100b, 00000110b, 11001100b, 00011010b, 00101001b, 00110110b, 11010000b, 01001000b, 11110101b
db 01000010b, 11010110b, 01001101b, 11001110b, 00100100b, 01101100b, 11011100b, 11011101b, 10100100b, 10000101b, 00101001b, 00100011b, 00100111b, 00110111b
db 01110001b, 01000000b, 10001110b, 11000111b, 00110100b, 01111011b, 01111010b, 00001001b, 00011000b, 10010011b, 01100111b, 00000100b, 01100010b, 10001001b
db 00000110b, 10010001b, 00110110b, 11000001b, 01000011b, 01010010b, 01010011b, 00000110b, 11011111b, 00010111b, 01010101b, 00000011b, 00100011b, 01000100b
db 01001101b, 10001101b, 11010101b, 00100100b, 01110110b, 00100111b, 00110100b, 01001110b, 10001000b, 11110110b, 11000111b, 00110110b, 01101111b, 00100010b
db 11010000b, 01001000b, 11101100b, 11100000b, 10001100b, 11001010b, 11101000b, 10001111b, 01110011b, 01110011b, 11001000b, 10100000b, 01101110b, 01000000b
db 01000011b, 01100111b, 10100111b, 10000010b, 10001011b, 11011010b, 01101000b, 11010010b, 00000010b, 10011011b, 01011010b, 00011010b, 00100111b, 00101101b
db 10111011b, 10001000b, 00010110b, 01000100b, 00011000b, 11111011b, 01100000b, 00000110b, 10001001b, 00111001b, 10111011b, 01110010b, 11110000b, 11000111b
db 10100000b, 00011011b, 01111001b, 11011100b, 01000110b, 10100010b, 11111011b, 01011000b, 00011011b, 00100100b, 00110100b, 11011011b, 00111011b, 10011010b
db 11100101b, 11010001b, 01110100b, 11011010b, 01000000b, 00100101b, 01001001b, 11001101b, 11011100b, 10011111b, 00010100b, 00110100b, 11000101b, 01000001b
db 00010110b, 00111101b, 10001001b, 11001011b, 10100011b, 00000010b, 10000000b, 01101100b, 00001101b, 01101000b, 00011110b, 11100101b, 10100010b, 01011011b
db 00010001b, 11001001b, 10000010b, 00110101b, 10100100b, 11011100b, 10000000b, 10111001b, 11101001b, 01100000b, 01010001b, 00110100b, 00100100b, 01001111b
db 00011011b, 00000100b, 11010110b, 00000110b, 11001100b, 00011011b, 00001010b, 00100100b, 11000000b, 01000100b, 01001010b, 11011001b, 01100010b, 00000110b
db 10101000b, 10101110b, 10001100b, 11110111b, 00100000b, 00101100b, 10001100b, 11011010b, 11010001b, 00111001b, 10101100b, 10011010b, 10001011b, 10000100b
db 10101101b, 10001100b, 10010010b, 11010011b, 00011100b, 10000110b, 10010010b, 01011011b, 10010000b, 00000101b, 00010000b, 00110000b, 10001101b, 10011011b
db 10110110b, 11100101b, 00101100b, 00000111b, 01110011b, 00000001b, 10100001b, 00100010b, 01111000b, 11011000b, 10001110b, 00001000b, 10101100b, 10010010b
db 10011011b, 10011011b, 10110001b, 00000010b, 00110010b, 01110011b, 01110100b, 00100100b, 01001111b, 00011011b
[section .bss]
lastChar resb 1 ; last printed char - used to capitalize chars after a space (i.e the 2nd or third word of a city name)
string_index resw 1 ; used to index into the array of states, which are each two bytes
states_unpacked resb 100 ; 50 states, 2 bytes each
capitals_unpacked resb 464
nullTerminator resb 1
```
] |
[Question]
[
Given a nonempty list of positive integers \$(x, y, z, \dots)\$, your job is to determine the number of unique values of \$\pm x \pm y \pm z \pm \dots\$
For example, consider the list \$(1, 2, 2)\$. There are eight possible ways to create sums:
* \$+ 1 + 2 + 2 \to +5\$
* \$+ 1 + 2 − 2 \to +1\$
* \$+ 1 − 2 + 2 \to +1\$
* \$+ 1 − 2 − 2 \to −3\$
* \$− 1 + 2 + 2 \to +3\$
* \$− 1 + 2 − 2 \to −1\$
* \$− 1 − 2 + 2 \to −1\$
* \$− 1 − 2 − 2 \to −5\$
There are six unique sums \$\{5, -5, 1, -1, 3, -3\}\$, so the answer is \$6\$.
## Test Cases
```
[1, 2] => 4
[1, 2, 2] => 6
[s]*n => n+1
[1, 2, 27] => 8
[1, 2, 3, 4, 5, 6, 7] => 29
[3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] => 45
[1, 7, 2, 8, 3, 1, 6, 8, 10, 9] => 56
[93, 28, 92, 100, 43, 66, 2, 98, 2, 52, 57, 75, 39, 77, 45, 15, 13, 82, 81, 20, 68, 14, 5, 3, 72, 56, 57, 1, 23, 25, 76, 59, 60, 71, 71, 24, 1, 3, 72, 84, 72, 28, 83, 62, 66, 45, 21, 28, 49, 57, 70, 3, 44, 47, 1, 54, 53, 56, 36, 20, 99, 9, 89, 74, 1, 14, 68, 47, 99, 61, 46, 26, 69, 21, 20, 82, 23, 39, 50, 58, 24, 22, 48, 32, 30, 11, 11, 48, 90, 44, 47, 90, 61, 86, 72, 20, 56, 6, 55, 59] => 4728
```
[Reference solution](https://tio.run/##lVJNT4NAFLzzK16MhzZdDR/LshjryYuJiQePhAOmaBtxaYQqB/97nXFRE6MNEh67@/bNm5kX1lX3WDfNfr952rbPvVxWfXV6vel6mbnd3TwI6mFbuZWcnUlx5fpSTi4EK5eP8@f90MkgSwFGjmXVipPzEyQD@f0pnCxkUChDVRkEXdu81D9JxuxSmto99Gs5lfu2WTUyUhYhgE/VxhF3dSOzuT8tZbvrb/tnCNm5ZuPqDruiW7evkLhYyJEsL/DB7iM38yzD/C@tfN4AhaGiiJTEpTpU@mWRpf@q/n7/xZAo0UpSJUZJNhGZAxRbJXmsojBEA5wN8OyXW7@mjAw90TrJsWKvsY8YqLe4t5QQTuIUg74RlFIqRWfsbzwHXcfUhLuMOfAZ6MoiH7H2NZ84q6dxspY@Lf3F3iM9xJHP63z0GPreGjx61JNyqonXmJjpPnP0FITlzEbd9E3/7M17g5xmT4TJRz2hnynnwHmnOKd2GifnEwOrwZHwnwA2inwwl4ff3rgnvzV@luSlR/4/acrZl@UB0nK/fwc) (optimizes for speed and not size).
If you can't handle the last case because you use a brute-force method or similar, that's fine.
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid solution (measured in bytes) wins.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 27 bytes
```
Tr[1^Fold[#⋃+##&,{0},#]]&
```
[Try it online!](https://tio.run/##bVLBSsQwEL33KwqBohgxSZNJgih78uzBW6lQVhcXXIWlt9KTR//SH6nzMpVehJ3N9M17My/Tnobx7fU0jMf9sBzuLpanc2efHz7fXzr18/11pVSjJzNr1ffNcnlbPZ6PH2Onru8PO9U3N7upqqrJ6trNWs4t/ee3kVpde10HXZOuI@C2MHz5ZzgXFpWcS2FVxgKngtlS59wa5oOQGXUMZAeQUc8AUdHkVI6A4C4RfXlI5NxzbhHMTmgPi6wm9PZ/FiKUJGoQMIsrERA3IhZEK@HkGqsoeTnhLMGQE1MY66zgPq@2jKyGJV7mBBhoZXRLYiznsqAE/zIKNmEXIlQJuwSbg/I6x8j14BxXD/wckrh1jHusFa@GcWslgGWzGUKO3onWOxlxhiUELGLm72FefgE "Wolfram Language (Mathematica) – Try It Online")
Finding the number of unique sign-swapping sums is equivalent to finding the number of unique subset sums.
A proof would involve adding the sum of the input to each of the sign-swapping sums and dividing by two. Then, there's an obvious bijection.
### Explanation
```
Fold[#⋃+##&,{0},#]
```
Iterate through the input, with the initial value being `{0}`: take the union between `<current value>` and `<current value> + input element` (maps onto lists).
```
Tr[1^ ... ]
```
Golfy version of the `Length` function.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
ŒPS€QL
```
[Try it online!](https://tio.run/##y0rNyan8///opIDgR01rAn3@H24H0pH//0dHG@ooGMXqcCmAGahsYx0FEx0FUx0FMx0Fc7A4UMQQLGgIFrcEKzMDs4FSpjC95mBxC7CgIVgBkG1oANQQyxULAA "Jelly – Try It Online")
### Background
Let **L** be the input list and **{P, N}** a partition into algebraic summands with positive and negative signs. The challenge spec requires calculating **s{P,N} = sum(P) - sum(N)**.
However, since **sum(P) + sum(N) = sum(L)** and **sum(L)** does not depend on the partition, we have **s{P,N} = sum(P) - sum(N) = sum(P) - (sum(L) - sum(P)) = 2sum(P) - sum(L)**.
Thus, each unique value of **sum(P)** corresponds to one unique value of **s{P,N}**.
### How it works
```
ŒPS€QL Main link. Argument: A (array)
ŒP Powerset; generate all subarrays of A.
S€ Take the sum of each.
Q Unique; deduplicate the sums.
L Take the length.
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~11~~ 10 bytes
```
nW:qBGY*un
```
[Try it online!](https://tio.run/##y00syfn/Py/cqtDJPVKrNO///2hDayNro1gA "MATL – Try It Online")
This is a port of Luis Mendo's [Octave/MATLAB](https://codegolf.stackexchange.com/a/164527/31516) answer. I'm still trying to learn MATL, and I figured I'd post it, along with an explanation, since MATL is the language of the month.
### Explanation:
Here's a read-through for anyone unfamiliar with stack based programming in general, and MATL in particular.
The input vector is implicitly placed on the stack. Note that when an operation is performed on an element in the stack, then that element is removed from the stack.
```
% Stack:
% [1, 2, 2]
n % Counts the number of elements of the vector on the top of the stack.
% Stack:
% [3]
W % Raise 2^x, where x is the number above it in the stack
% Stack:
% [8]
: % Range from 1...x, where x is the number above it in the stack. % Stack:
% [1, 2, 3, 4, 5, 6, 7, 8]
q % Decrement. Stack:
% [0, 1, 2, 3, 4, 5, 6, 7]
B % Convert to binary. Stack:
% [0,0,0; 0,0,1; 0,1,0; 0,1,1; 1,0,0; 1,0,1; 1,1,0; 1,1,1]
G % Push input again. Stack:
% [0,0,0; 0,0,1; 0,1,0; 0,1,1; 1,0,0; 1,0,1; 1,1,0; 1,1,1], [1; 2; 2]
Y* % Matrix multiplication of the two elements on the stack.
% Stack:
% [0; 2; 2; 4; 1; 3; 3; 5]
u % Keep only unique elements. Stack:
% [0; 2; 4; 1; 3; 5]
n % Number of elements in the vector. Stack:
% [6]
```
And then it outputs the final element on the stack implicitly.
[Answer]
# [Python 2](https://docs.python.org/2/), 55 bytes
```
s={0}
for n in input():s|={t+n for t in s}
print len(s)
```
[Try it online!](https://tio.run/##TVHBbsIwDD3Tr/CtoPXQhDRNKnFk1112mzhsLBNoqK3SooEY3975xZ02qVbsZz/72e2v46Fr9bTv3gNtKM/zadjcynv20UVq6YivP4/LVTN8b27jQ0tIjEgM96yPx3akU2iXw2pibpZ9HY6nQM/xHJpsMcZrQ@ES9oT22SJc9qEfafv0uI2xiw29xfD6Ob2ogvQuS89/b12QKagqyBZUM8qxSpBKqE9FNvmcqoRXJ9QlSKU0@6rkcs57BjXHXgNj0DBgbaJ4l54Kxk1qdOURNfuGfQXjaofu0Mdsi9bmV0ANphU2CjCLMzUgbmSZUCsxLUvMJGfkhTIHQVpEYaxWghs/yyrlLkwxMqeCgLWMXlsR5n06j4N@GQWZkAsSshaXRDWb9fOcUtaDcqxecVw5UasZN7gq/gvjSokB8@WfIPjo7ey8UynKcIQKh9j9AA "Python 2 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 52 bytes
```
k=1
for n in input():k|=k<<n
print bin(k).count('1')
```
[Try it online!](https://tio.run/##TVHBasMwDD03X6FbWggjdh3HDu2xu@6y2@hhyzwaMpJgUtbC/j3TszI2iLD0pCc9KdN9voyDXtrxPdCR8jxf@qPKPsZIA3X4puu83TX997E/HIZsit0w01s3bPvdQzteh3mbq3y3MDHLvi7dZ6DneA1NtpnjvaFwCy2hd7YJtzZMM52eHk8xjrGhtxhe@@VFFaTPWXr@e/uCTEFVQbagmlGOVYJUQn0qssnnVCW8OqEuQSql2Vcll3PeM6g59hoYg4YBaxPFu/RUMG5SoyuPqNk37CsYVzt0hz5mW7Q2vwJqMK2wUYBZnKkBcSPLhFqJaVliJTkjL5Q5CNIiCmO1Etz4VVYpd2GKkTkVBOxl9N6KMO/TeRz0yyjIhFyQkLW4JKrZrF/nlLIelGP1iuPKiVrNuMFV8V8YV0oMmC//BMFHb2fXnUpRhiNUOMT5Bw "Python 2 – Try It Online")
Uses the binary representation of a number to store the reachable subset sums.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes
```
æOÙg
```
Utilizes the same approach used in [Dennis’ Jelly answer](https://codegolf.stackexchange.com/a/164512/59487).
[Try it online!](https://tio.run/##MzBNTDJM/f//8DL/wzPT//@PNtQx0jGKBQA "05AB1E – Try It Online")
[Answer]
## Haskell, 46 bytes
```
import Data.List
length.nub.map sum.mapM(:[0])
```
[Try it online!](https://tio.run/##TYrRCsIgGEbv9xT/5QY/MrO5Fuyuy3oCkTDYmkxNpnt@Uyro6hzO9y0qrJMxKWnrX1uEi4qKXHWI1TyayT3jQtz@IFZ5CLstvNVn0comWaUdjFDKHWq/aReBwNyAqAAExYPEr/wrwyN2yLH/JIY0B5rTkEeeybD7vfucTlguPJO2OEgJ6Q0 "Haskell – Try It Online")
Instead of summing the subsets of the input list, we make all combinations of either keeping a number or replacing it by `0`, e.g.
```
mapM(:[0])[1,2,3] -> [[1,2,3],[1,2,0],[1,0,3],[1,0,0],[0,2,3],[0,2,0],[0,0,3],[0,0,0]]
```
This is two bytes shorter than `subsequences`.
[Answer]
# R, ~~83~~ 75 bytes
### -8 bytes thanks to JayCe and Giuseppe
Creates a matrix of all possible combinations of (1,-1) for the size of the input vector, multiples this by the original vector to get the sums. Then unique and find the length of the result.
`function(v)nrow(unique(t(t(expand.grid(rep(list(c(1,-1)),sum(v|1)))))%*%v))`
---
### previous version:
`f=function(v)nrow(unique(as.matrix(expand.grid(rep(list(c(1,-1)),length(v))))%*%v))`
### Ungolfed with comments:
```
f=function(vector){
List=rep(list(c(1,-1)),length(vector)) ## Create a list with length(vector) elements, all (1,-1)
Combinations=expand.grid(Length) ## get all combinations of the elements of the list, e.g, 1,-1,1,1,-1,1
Matrix=as.matrix(Combinations) ## convert to matrix
Results=Matrix%*%vector ## multiply the matrix original vector to get a Nx1 matrix
Unique_results=unique(Results) ## unique the results
nrow(Unique_results) ## length = number of rows of unique values
}
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/) / MATLAB, ~~45~~ ~~41~~ 40 bytes
```
@(x)nnz(unique(dec2bin(0:2^nnz(x)-1)*x))
```
Input is a column vector (using `;` as separator).
The code errors for the last test case due to memory restrictions.
This uses an idea from [JungHwan Min's answer](https://codegolf.stackexchange.com/a/164513/36398) (subsets instead of alternating signs) to save a few bytes.
[**Try it online!**](https://tio.run/##y08uSSxL/Z9mq6en999Bo0IzL69KozQvs7A0VSMlNdkoKTNPw8DKKA4kXKGpa6ipVaGp@T9NI9rQWsEoVpMLyDK1VoAiCB8kA5eEcIytFUzASsysFcwhEkAhQ7CoIVjCEqzODMw2RjbKHCxhARY1BKsAsg0NgDpiNf8DAA "Octave – Try It Online")
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 39 bytes
```
a->#[1|n<-Vec(prod(i=1,#a,1+x^a[i])),n]
```
Counts the number of nonzero coefficients of the polynomial \$ \prod\_{i \in a}(1+x^i) \$, where \$a\$ is the input.
[Try it online!](https://tio.run/##RZHdSsQwEIVfJezetJhCJ80vuPsY3pQKQV0pSA3FCwXfvc7JRBYaMvkyZ@ZkWvK@Du/luKnLkYfreabf7XF4envpyv752q0X0ues6eH7Oc/r0vd6W45cysdPl9VwVWVfty8OTzic1K3LnKLmmbQyCwfYW@i1wnenk1ZWK1dxAGZAlVHFqWb5GvOVa8pQcayM6j3HNHI@EhJTwyAZQKaWgfdVk2LdHBZXCajLTQLHlmPC4uyI8rDIao/a9t9CgNKLGgnoxTcBiAt5FgSSZeQZTRSt7HAWYciIKbQ1JNymZmuU0bDESh8HA5O0nrwYS6kOKMK/tIJN2IUItx6zRDamnlqfUZ4H53i647OL4tYwtxgrfg1zIllgabwbQoza0bc3jeIMQ3AYxLL0xx8 "Pari/GP – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 61 bytes
```
f=lambda a,s={0}:a and f(a[1:],s|{u+a[0]for u in s})or len(s)
```
[Try it online!](https://tio.run/##VVLLboMwELzzFXsEdQ82fmBH4ksQB9oEFSmFKCRSqjTfTmcx6UOw2vXsjHcMPn1e3qfRLEtfH7uP131HHc/1XT12qMY99XnX6F3L89f9@tI1qu2nM11pGGl@FCiPhzGfi@Wtmw8z1dRkRHmjuWyZbMHP1br229ryvwed@IdpgDn2XAEvnw3DGrBGI4LikQ07GeF@lBUagYXokbXiiL57zowGuwVMKpm0UlAC8B4gsLAmJ1ExVY7JRORK9gddAuyAftCgQu0h0RZ8UMEUpU9qIcgsdCqBsJGHoNIpSrtSNlGwKYuzIIbKZErGljrhNm621CqzkNg0x4kBk0Ybn4xFsPEG8Z9GiU2xKyLpemBW2AgftzkqHU@cy9Ed1i4ktyVwi9ogG@BapxAsql9DUsvewW9nUsmZfAQnH0J@V1WGImuzTC7RwDTJPVqvzg5/6Vb3@VCgOJ2H8ZLfmG5U1zQVyzc "Python 3 – Try It Online")
Recursive approach, keeping track of unique subset sums.
The real fun is that this beats `itertools` by a big margin:
## 76 bytes
```
lambda a:len({*map(sum,product(*([0,x]for x in a)))})
from itertools import*
```
[Try it online!](https://tio.run/##VY/RCsIwDEXf@xV5bEcenHPVDfYlcw9VNyysS@kqKOK3z1RUlEDCveeGNv4WzzQVy9Dsl9G4w8mAqcd@kvfMGS/ni0Mf6HQ5RpnJdoXXbqAAV7ATGKXUQ4khkAMb@xCJxhms8xRithzN3M/QQCsAZJvjukPYKPyol9ZvvcG/YlL9JAv2StS4ZX/9AQXmbOcMKo5ongWW6Ynyu7llsMMU1DzzFVbMS61EJ0Q6wiJQuuP105qXfLBTlIO0CiF1aBogtTwB "Python 3 – Try It Online")
[Answer]
# [Pyth](https://pyth.readthedocs.io), 5 bytes
```
l{sMy
```
Utilizes the same approach used in [Dennis’ Jelly answer](https://codegolf.stackexchange.com/a/164512/59487).
[Try it here.](http://pyth.herokuapp.com/?code=l%7BsMy&input=%5B1%2C+2%2C+3%2C+4%2C+5%2C+6%2C+7%5D&debug=0)
[Answer]
# [Attache](https://github.com/ConorOBrien-Foxx/Attache), 29 bytes
```
{#Unique[Flat!±_]}@Fold[`±]
```
[Try it online!](https://tio.run/##SywpSUzOSP2fpmBl@79aOTQvs7A0NdotJ7FE8dDG@NhaB7f8nJTohEMbY//7paamFEerFBQkp8dyBRRl5pWEpBaXOCcWpxZHp@koRHMpAEG0oY6CUawOgo3ENdFRQCBUNcZgQVMdBTMdBXOYFFDQECxuCJayBKs0A7OBUqZIJpiDpSzA4oZgNUC2oQFQTyxXbOx/AA "Attache – Try It Online")
This works by folding the `±` operator over the input list, then taking `±` of that list, then counting the unique atoms of the array.
Here's some examples of how the folding works:
```
Fold[`±][ [1,2] ] == 1 ± 2
== [1 + 2, 1 - 2]
== [3, -1]
Fold[`±][ [1,2,2] ] == (1 ± 2) ± 2
== [3, -1] ± 2
== [[3 + 2, 3 - 2], [-1 + 2, -1 - 2]]
== [[5, 1], [1, -3]]
== [5, 1, 1, -3]
Fold[`±][ [4,4,4,4] ] == (4 ± 4) ± 4 ± 4
== [8, 0] ± 4 ± 4
== [[12, 4], [4, -4]] ± 4
== [[[16, 8], [8, 0]], [[8, 0], [0, -8]]]
== [16, 8, 8, 0, 8, 0, 0, -8]
== [16, 8, 0, -8]
```
Then we generate all permutations of the final sign by applying PlusMinus once more.
## A more efficient version, 31 bytes
```
`#@(q:=Unique@Flat@`±)@Fold[q]
```
[Try it online!](https://tio.run/##RVDLasMwELz7KwTtoQUdLOthKRAwFHIsPbQnY4hJlDYQ0rh2P6y/0B9zZ7yGgpddj2Y0s@qnqT985PmkNtt5f9c8DJvt2/U8fOdmd@mnZv/789jsPi/Hdujm55yPY3t/ux3eu@Ll63ydXvM4PfVjHtuTVm3RJqtVFbVKlVamLLVyAEIACCwuzbNqrWqvlU3omB1mwwI74jwaUKEOkBgHPqhgUhlETQK9cFITwkUBgtpIVW6hrKLopDNZZKBKQtG2MoK7tMYqF5mDxImPZwAr1jZIsAQ2vsj8YsWYjEsRTwMwRzYqpNWnlPWYnKt7/PsoaSvgDrNFt8CNkSKWyv9AnHl3DOtOpSTjI3g@RFd03fwH "Attache – Try It Online") This doesn't time out on the final test case, since it doesn't generate unnecessary combinations.
[Answer]
# [R](https://www.r-project.org/), 62 bytes
```
function(V)sum(unique(c(V%*%combn(rep(0:1,L),L<-sum(V|1))))|1)
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNMs7g0V6M0L7OwNFUjWSNMVUs1OT83KU@jKLVAw8DKUMdHU8fHRhekKKzGUBMIgOT/NKBSQx0jHSNNzf8A "R – Try It Online")
Ports Dennis' algorithm. It's closest to the Octave/MATL answers as it uses a similar bitmap and matrix product for inclusion/exclusion of terms.
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), ~~12~~ 11 bytes
-1 thanks to H.PWiz
```
≢⊃(+∪⊢)/⎕,0
```
[Try it online!](https://tio.run/##LVDLTgJBELzvV/RtIEKcmZ2nf7OBQIhEzLIXQzhpENAlJsajBzl61guJP9M/gtWrSc/2THdtVXVXt/Ph@K6aL6bD0bxaLmejMx/eZgvevOiCt4@TM@@OvL/vXfD2k/fH/iXaA31G6zwFiNuD4ecftV6pgUJLTq24/Va83RvevOI9qtVEEbfv1NTVeHJDzYKQigb/rwDl3UeN65Tb05VaXCt@elCTajYHzQntel0YstSQ67LcQtEL3H6lfkOxK5bkyFOgiKbNRUkGBYNSRjMglzhg8EBHlBIJJCAbDUxDPhQVPOSSbKJsUdbkSgoB4Jzw8YhIEUyZYgQTGURJCWRwoCmAy3VKEVBoxqIagBJNkHqKKGUKmqKRsOKvwyYnX8gm6FmRBLk1UnG5E9UynyMXyfxxegiVIlIGkc4ZMyT4Ek6YgBVgUQ1YAxCBQu4YtdiFHczgNfkkLqz943TYCRapyRgJPLP@V8UFTCl0PrXoYhaPcYpKlhpt@gU "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 39 bytes
```
s/^| /{+,-}/g;$_=grep!$s{eval$_}++,glob
```
[Try it online!](https://tio.run/##K0gtyjH9/79YP65GQb9aW0e3Vj/dWiXeNr0otUBRpbg6tSwxRyW@VltbJz0nP@n/f0MFIwVjBRMFUwUzBfN/@QUlmfl5xf91fU31DAwN/usWAAA "Perl 5 – Try It Online")
[Answer]
# JavaScript (ES6), 63 bytes
```
f=([c,...a],s=n=!(o={}))=>c?f(a,s-c)|f(a,s+c)&&n:o[s]=o[s]||++n
```
[Try it online!](https://tio.run/##bY5BCsIwEEX3niJuSkKnqalNaoXoQUoXJVpRSiJG3FjPHuNQEaSb4cN7f2Yu3aPz5na@3jPrDscQek0bA5zzrgWvrV5Sp58vxvTO7Hvagc8MGzGkhiWJ3brGt/ozxjFNbTDOejcc@eBOtKeNAFK0jJE8J@Vihv2wmsdrICUQCUQBqSa1qP/daAkUBbo1VhXmiOT3Azlzo0J3g6LAUsxiFZdMLanCGw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 5 bytes
```
LumΣṖ
```
[Try it online!](https://tio.run/##yygtzv6fq@GlpGBrp6B0aHlqsUbxo6ZGzdyics1D2/77lOaeW/xw57T///8bKhhxATGUNFYwUTBVMFMw5zJWMASyDYE8S6C4GZA2VjAFqjEH8iwUQLJmQNrQQMGSCwA "Husk – Try It Online")
Port of [Dennis' Jelly answer.](https://codegolf.stackexchange.com/a/164512/59487)
### Explanation
```
LumΣṖ [1,2,2]
Ṗ Powerset [[],[1],[2],[1,2],[2],[1,2],[2,2],[1,2,2]]
mΣ Sum each [0,1,2,3,2,3,4,5]
u Remove duplicates [0,1,2,3,4,5]
L Length 6
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 33 bytes
```
{+set ([X](^2 xx$_)XZ*$_,)>>.sum}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Wrs4tURBIzoiViPOSKGiQiVeMyJKSyVeR9POTq@4NLf2f3FipUKaBlBcIS2/iCvaUEfBKFYHQqMwjXUUTHQUTHUUzHQUzEHCQAFDsJghWNgSrMoMzAZKmUJ1moOFLcBihmB5INvQAKg@1vo/AA "Perl 6 – Try It Online")
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + GNU utilities, 49 bytes
```
eval echo "{,-}${@//,/{+,-\}}\;"|bc|sort -u|wc -l
```
[Try it online!](https://tio.run/##TUvNCoJAEL77FMNip2axzdJEii7dOkS3wMu6TiiIhmt5UJ/dpj9oYOb7nVTbfOryoiRoSGcxZLUDPC3Z1mhLW@GeD6fjRbzdW1NU7RXEzILcgQDh/nqf3FILUv7bEz10CWTyGkSPcnT7veeh189RJuOYxGJIzWDrhv/uQ2dAllNWVzQpXDq83@vjCtcYYOj4qJgrVhH7AaOPa@6ErDb4SgNGtcDIeQI "Bash – Try It Online")
Input given as a comma-separated list at the command-line.
### Explanation
```
${@//,/{+,-\}} # Replace commas with {+,-}
"{,-}${@//,/{+,-\}}\;" # Build a brace expansion with {+,-} before every number and ; at the end
eval echo "{,-}${@//,/{+,-\}}\;" # Expand to give every combination expression, separated by ;
|bc # Arithmetically evaluate each line
|sort -u # Remove duplicates
wc -l # Count
```
[Answer]
# x86\_64 machine language for Linux, ~~31~~ 29 bytes
```
0: 31 d2 xor %edx,%edx
2: 6a 01 pushq $0x1
4: 58 pop %rax
5: 8b 0c 97 mov (%rdi,%rdx,4),%ecx
8: 48 89 c3 mov %rax,%rbx
b: ff c2 inc %edx
d: 48 d3 e3 shl %cl,%rbx
10: 48 09 d8 or %rbx,%rax
13: 39 d6 cmp %ese,%edx
15: 7c ee jle 5 <+0x5>
17: f3 48 0f b8 c0 popcnt %rax,%rax
1c: c3 retq
```
[Try it online!](https://tio.run/##jZDdioMwEIWvt08xCIWkpGBM/UP6JMYLjcbtxbqLtRAQn92dxN2LpaypBGcmZ@Z8jurcK7Wu6nO4T6De6xH6sroG0gguTRtJk9TShJjHmTRZg7mSJk@ludg6l0YJabTGGG13Ldad2PIQ9RajwKhRT3G26zD/1XGuwahC6xMUh9swgSb4PtXM5g2dx256jAOxl@REnWYlSntKatbQYlk/6ttA6Hx4@xpR0STQpDzeKwpXOLZyCBgEnEEEOw/2aMcoKzqDrxsWBhBRWviQez7PyF2qRQoPMmdgz4tIX/dLyO27BYMLg5hBwiD1bvl/t0OmHiSOc@fAnUnuPNHKFqjFf5G@bovk3L9l6gYz9mOYuJyH2w982nK32yFDi1zWbw "C (gcc) – Try It Online")
Inspired by @xnor's answer. Requires a machine with the `POPCNT` instruction.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~74~~ 69 bytes
```
f(a,b)int*a;{long k=1;for(;b--;k|=k<<a[b]);a=__builtin_popcountl(k);}
```
[Try it online!](https://tio.run/##jZDfCoIwFIev6ykOQrDFEVr/TJZPYiLTWIg2pfTKfHbbVjcRucYudtjvfN/Ocv@S5@MoicCMFqpdCt5XtbpAGTEu6xvhme/z8hGVx6OIs4RyEaVp1hVVW6i0qZu87lRbkZLyYbyKQhHaz2fNTaMk8SSJF/eEQgSL80l5CB5DWMPE0hlJiO6OE9qDKw0DAqwp5S7lFOdbOWk1yo1DGSKY/afSlf5L@Xr3BmGLsEPYIwTOKX@nrTJwKHU7swRmIaFlapQp9N3uU@lKGyVj7ikD23jAN3Bvz2z1@sCvKSfTVrkyymF8Ag "C (gcc) – Try It Online")
C port of @xnor's answer
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), ~~34~~ ~~33~~ 32 bytes
```
{≢∪⍵+.×⍨↑{,⍵∘.,U}⍣(≢1↓⍵)⊢U←¯1 1}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@/@lHnokcdqx71btXWOzz9Ue@KR20Tq3WA3EcdM/R0Qmsf9S7WACoxfNQ2GSio@ahrUeijtgmH1hsqGNb@dwMyKTGA61HfVCDHTcFQwUjBCMHTUTDSUTDWUTDRUTDVUTDTUTD/DwA "APL (Dyalog Classic) – Try It Online")
Thanks to @ngn for -1 byte!
[Answer]
# [Clean](https://clean.cs.ru.nl), 82 bytes
```
import StdEnv
f[]=length
f[h:t]=f t o foldr(\e l=removeDup[e+h,e-h:l])[]
?l=f l[0]
```
[Try it online!](https://tio.run/##RYw9C8IwFAD3/ooHLooRWgW/ILjUQXBzjBlCmpjAS1LaV8E/b4wubndwnEajYg6pm9BAUD5mH/o0ENyoO8dnZYXkaOKDXEF3JMktECSwCbthfjeAfDAhPU079cIsHTMrd0S5ELI6YWlR1DLfSA1UzQD9SMBBNAx2DNYM9gw2DIpuf9zUDA6yhHaKmnyKJT5V/K/fQX5ri@ox5tXlmttXVMHr8QM "Clean – Try It Online")
Defines the function `? :: [Int] -> Int` using `f :: [Int] -> ([Int] -> Int)` as a helper to reduce over each possible sum after an addition or subtraction.
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 21 bytes
```
⍴∘∪⊢+.×1-2×2(⍴⍨⊤∘⍳*)⍴
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbhEe9Wx51zHjUsepR1yJtvcPTDXWNDk830gAJ96541LUEJNm7WUsTKPD/Ud9UoI40IMWFlfnfUMFIwYgLRBormCiYKpgpmAN55kC@BVDEEMi3UDA0ULAEAA "APL (Dyalog Classic) – Try It Online")
## Explanation
```
2(⍴⍨⊤∘⍳*)⍴
```
A function train equivalent to `{((⍴⍵)⍴2)⊤⍳(⍴⍵)}`, which generates a matrix that has the binary representations of 0 to the length of the input as columns
```
1-2×
```
Maps `1`s to `-1`s and `0`s to `1`s
```
⊢+.×
```
Matrix multiplication with the input, which gives an array of all possible sums
```
⍴∘∪
```
Remove duplicates, then count
[Answer]
# Java 8, ~~207~~ ~~83~~ 44 bytes
```
s->Long.bitCount(s.reduce(1L,(r,c)->r|r<<c))
```
Port of [@xnor's Python 2 answer](https://codegolf.stackexchange.com/a/164577/52210).
-39 bytes thanks to *@Jakob*.
[Try it online](https://tio.run/##hVPBbtswDL33K3i0B8e1HFu2kCyXXb1iQI9FD4qjtE4dObDkDkWXb89I0VsvywqEEUU@8j1R8kG/6sVh93Lpjqdh9HDAfTr5rk@/rADg9hZ@aAwPe/DPBrZv3izaYbL@pu21c/Bdd/b9BqCz3ox73Rq4oy1AP9gnaKOPds6PRh/T@7CsG0xvwMUrBJ/R8Oe89l0Ld2DhK1zcYkOYdNv5b8QXuXQ0u6k1kWiSaEzaeLEZf43rdRvHlxV3OE3bHjvMjV6HbgdH1BchZ2efHh5BxyzOG@cja34CUTw8vmPLvDkHMVeSn@erTwDLJimapGwS2STXsYgSASgCVoVSGfwl/f@HowrYOgBFKEJfZNTkWpVCaI4olRMSoQUGpAyNVB2WkgxbV6QA5VToF@gLMkTXxEknxGpJhMUfsRVVSq4mAHFhpqIQNpJYUAm2nA88F9UFr6SsJkE5iyLaXHC8ULOsjCeLJQXzlCRgydRLycKUCqOsST9TkUySS0WUlTR1QqNJNfNkfDxSTkcvcV/WrDbHeEGzppvFuBBsFFPZhyDyqXct5zNlrIyGUIZBnP/xDYSnGy6LL@rvw71/c94c02Hy6QnftO9tZNOrX1k67CMdxzPB@fIb).
```
s-> // Method with Long-Stream parameter and long return-type
Long.bitCount( // Return the amount of 1s in the binary representation of:
s.reduce(1L, // Result-Long, starting at 1
(r,c)-> // Loop pair-wise (result,current):
r| // Bitwise-OR the result `r` with:
r<<c)) // result `r` bitwise left-shifted by the current `c`
```
[Answer]
# Java 8, 85 bytes
Another Java port of [*xnor*'s answer](https://codegolf.stackexchange.com/a/164577). Like the original answer, this uses an arbitrary-precision bitmap so that there's no upper limit on the size of a subset sum.
It's a lambda from a sequential `java.util.stream.Stream<Integer>` to `int`.
```
s->s.reduce(java.math.BigInteger.ONE,(a,e)->a.or(a.shiftLeft(e)),(u,v)->u).bitCount()
```
[Try It Online](https://tio.run/##XVPbitswEH12vkKPMijCchzZ3kugLS0UennYx2VZtI6cderYwZJTwpJvz85IyropWGh0Zs7MGWm8VQc1367/nPfjS9tUpGqVMeSnajryNosCaKyysNVNp1qyBQYfbdPyeuwq2/Qd/xaMu8ln7KDVjj@47e57Z/VGDytGLhapyf3ZzFeGD3o9Vpo66k7ZV/652YQo/vvXV0YV0/F8pXg/UMXNa1PbH7q2VMcxoyM7gG@M@Utjv/RjZ2l8jm5n/ys/9M2a7KApCoKabvP4RNSwMTH2GIVij0@AVspoQ@5Jp/@Sf3GMi94EI@mJfZjTacnI9F1H5FfHBSOZi5KMXDyACQcL5yldoHT24ipd7jyFg4ULAVskQAkxJThSwMoUcXBkAEjpaGXhtiUuSJRjdiiVg52BLXBBdIEVUCuwJabPLkJyZErPxgCsBZ4cIUgkgZALv1LfTCAVmd9RWYGCUi8Ky6bC41kZZCX@joCS@TpLFLDwpRfSCytLd00F6velUCbKRRJ6Jd4oRsOSZaiT@PZQOba@hPOy8GpTwDO8WXwjwIXwC7EymQShjbkLGXpKvDK8BHx7/xInnMCo7gdCP4bIjdYzufEj5icvejgaq3e8Hy3fw1zatqM1V/t9e6TTr/RpGNTRhD@KujRxHN9inRl8p/M7)
Note that the combiner (the third argument to `reduce`) is unused since the stream is sequential. The function I chose is arbitrary.
[Answer]
# [Julia 0.6](http://julialang.org/), 54 52 bytes
```
V->(~W=W==[]?0:∪([n=W[] -n].+~W[2:end]))(V)|>endof
```
[Try it online!](https://tio.run/##VVFBTsMwELznFT4mwkWxY6/tSim/aA6RD5WgUlEJFYIb6rlP4A08qx8JO95AhaKVx7M7u@PN88fxsKN538/b1aY@D/3Q92N@aNfXy3c9Tv0wZrWa8v3deRjt@ml6zE1Tb5vPDcPX/fyyO9Wnt8P0fpyul6@9VlVdjUYrm7Wc/2G44U4rp5XXirQqdNJ/H66cN6XElKpURFQwp/zSKBQ6Fs6UPGPTcn1pyaxlIlmQzDomiIomxXJ4BHcJ6MtDAmPH2CC4OqI9HLOa0Nv9WghQkqhRgFmcCaC4EbEgGAkrz1hE0ckJZxGGrJjCWGuEd2mx1cqmWOJkjoeBTkZ3JMZSKguK8C@jYBN2IUKWsEtUc1Ba5rTyPDjH0z3ffRS3lnmHteJPMW@MBLjU3gwBo3ek5U2tOMMSPBaRq6aZfwA "Julia 0.6 – Try It Online")
(*-2 bytes by replacing `¬` with `~`, thanks to [Jo King](https://codegolf.stackexchange.com/questions/167872/2d-array-middle-point/167902#comment405656_167902)*)
Works for all test cases. Makes use of broadcast to collect all possible sums, then counts them.
Explanation:
```
function g_(V)
function inner(W) #named ~ in golf version to save bytes
W == [] ? 0 : #return 0 when input empty (base case)
∪( #unique elements of
[n=W[] -n] #take the first element and its negation
.+ #broadcast-add that to each element of
inner([2:end]) #sign-swapping sums of the rest of the array
)
end #returns the list of unique elements out of those sums
return endof(inner(V)) #return the length of that list
end
```
---
Older solution:
# [Julia 0.6](http://julialang.org/), 64 bytes
```
N->endof(∪([2(i&2^~-j>0)-1 for i=0:~-2^(l=endof(N)),j=1:l]*N))
```
[Try it online!](https://tio.run/##VVJLasMwEN3nFFoVucggyfoGnCPkAsGBQGuwcZ0Q2m3WOULP0GPlIu48jUvoYtDzm3kzbyYZv6bhFJa@Xfb17n1@O/fycf@RByuHF3u81eNOV7UR/fkqhlZvb7U9yqnlwn1VqbE126l7Jbh8nC7ych3mz2l@3L97JTZyczBK2E7x@x/GJ26UcEp4JYIShSbCFM4UOpeqUDCl/KqMhU6FMyVP2GiqR0Em1hKRLUhiHREhFE1O5fEI6hLRl4ZEwo6wQVB1QntYJHVAb/dnIUIZWI0CzKJMBEWNAgmi4bC8xipKjl84SzBk2RTGWsO8y6stzachieM5HgYaHt0ENpZzOVCCfx4Fm7ALEbIBt0Q1RcjrHM3rwTlW9/TtE7u1xDucFT8N8cZwgMv6aQgYvVNYd9LsDEfwOES3ob/FLw "Julia 0.6 – Try It Online")
Works for input arrays with length upto 63 (so doesn't work for the last test case, which is fine according to OP).
Explanation:
```
function f_(N)
endof( #length of
∪( #unique elements of
[
(i & 2^(j-1) > 0) #check j'th bit (from right) of i
* 2 - 1 #convert bit value from (0,1)=>(-1,1)
for i = 0:2^endof(N)-1, #where i is numbers 0 to 2^length(N)-1
j = 1:endof(N) #and j is 1 to length(N) (i.e. the bits in i)
] #so we have a matrix [-1 -1 -1;1 -1 -1;1 -1 1;...]
* #matrix multiply that with the input array,
N #thus calculating different combinations of
)) #sign-swapping sums
end
```
[Answer]
# [Desmos](https://www.desmos.com/calculator), ~~90~~ 74 bytes
*-16 bytes thanks to [Aiden Chow](https://codegolf.stackexchange.com/users/96039/aiden-chow)*!
```
f(A)=unique(∑_{j=1}^a(-1)^{floor([0...2^a]2/2^j)}A[j]).length
a=A.length
```
[Try it on Desmos!](https://www.desmos.com/calculator/macn8ggqsp)
Brute-forces all possible sums; then counts the number of distinct sums.
The exact choice of `+` or `-` is encoded in the binary digits of `i`, ignoring the zeroth bit because Desmos arrays are 1-indexed.
[Answer]
# [JavaScript (Babel Node)](https://babeljs.io/), 64 bytes
```
F=([f,...r],s=[0])=>f?F(r,s.flatMap(x=>[x+f,x])):new Set(s).size
```
[Try it online!](https://tio.run/##ZVHLboJAFN33K2YJ6RUZ5sFMG@zOXVddEhZoobEhYoS0pj9Pz2VojDZ6c/E85pzBz/qrHvbnw2lc7epd062O/XszTdsiKltKkuRc0VCUaRUXm/ZlG51pSNquHl/rU3QpNuXlsaVLFcdPx@ZbvDVjNMTJcPhpprEZxn09NKIQUU1ijEWxEfv@OPRdk3T9R7SN6pjx54c/aVRKyioS@h6bUXuDarr5gPf/XAqMIUs52OyWViRBStAeQoutyHC0uTslB@2I5RZbpuShMtxlvRZXoVeIcCiRkZBpioMAWAsQmJuX4clJ5IaE8tg5x0HOA7UD7ySkcFtYpIYeUijZaYObBZwFJmcIB1kYchkm07NkMTkdNjdzXCgLpTg2kwHXfqmVzjYNiw45hguoEK1sKOahxtdx/xDFNbkum5i1wDSrMdYvOWm4Hjfnqxv8Ni60zYBrPCtsBVzKMIz59FqIn/lsZ5c7paEZvwTDL4L/vTxz8fQL "JavaScript (Babel Node) – Try It Online")
This won't work for last testcase.
---
More effective solution (works on last testcase):
# [JavaScript (Babel Node)](https://babeljs.io/), 71 bytes
```
F=([f,...r],s=[0])=>f?F(r,[...new Set(s.flatMap(x=>[x+f,x]))]):s.length
```
[Try it online!](https://tio.run/##ZVFNT4NAEL37K/YIcUpY9oNdDfXWmyePhAOtUDUEmkK0/x7fsBiDBiYD72PmLXzUn/V4ur5fpt2xPjbdrh9em3k@FFHZUpIk14rGokyruNi3T4foSiXAvvkSL80UjUnb1dNzfYluxb683bd0q@K4ih/GpGv68/Q2T804neqxEYWIahJTLIq9OA39OHRN0g3n6BDVMeOPdz/SqJSUVSR0TFtsQe0G1bS5wPt/LgXGkKUcbLalFUmQErSH0KIrMrza/JmSg3bEcosuU/JQmW0WrzDfIUFGQqYppgCwFiAwtzTDlZPIDQnl0XPeBTkX1A68k5DCbWGRGnpIoWSnDW4W8C4wOUMYZGHIZahML5LV5HTonMxxoCyE4rWZDLj2a6x0sWlYdNhjOIAKq5UNwTzUuB3nD6s4JsdlE7MWmGY1yvp1TxqOx8n56AbvxoW0GXCNZ4WugEsZijGf/gbiZ57t7HqmNCTjj2D4Q/CvyzMXz98 "JavaScript (Babel Node) – Try It Online")
---
This won't work in a real browser due to [`Array#smoosh`](https://github.com/tc39/proposal-flatMap/pull/56).
Thanks to Bubbler, `[x+f,x-f]` -> `[x+f,x]` saves 2 bytes.
] |
[Question]
[
# Ultrafactorials
The ultrafactorials are a sequence of numbers which can be generated using the following function:
$$a(n) = n! ^ {n!}$$
The resulting values rise extremely quickly.
*Side note: This is entry [A046882](https://oeis.org/A046882) in the OEIS. Also related are the hyperfactorials, a still quite huge, but a bit smaller sequence: [A002109](https://oeis.org/A002109)*
# Your task
Your task is to implement these numbers into your language. Your program will calculate the **sum of all ultrafactorials** from 0 up to *inclusive* `n`.
## Input
Your program may only take one input: a number, which resembles the last \$a(n)\$ ultrafactorial to be added to the sum. The Input is assured to be positive or 0.
## Output
Your output is all up to you, as long as there's the visible sum of the numbers somewhere.
## Rules
* You can assume all integers, therefore integer input, and using integer counting loops to produce some results.
## Test cases
```
Input: -1
Output: Any kind of error (because -1! is undefined), or no handling at all
Input: 0
Output: 1
Input: 1
Output: 2
Input: 2
Output: 6
Input: 3
Output: 46662
```
# Challenge
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the answer with the least length in bytes wins!
[Answer]
# Mathematica, 19 bytes
```
Sum[n!^n!,{n,0,#}]&
```
Apologies for the extremely clear code ;)
[Answer]
# Jelly, 6 bytes
[Try it online!](http://jelly.tryitonline.net/#code=4oCY4bi2ISpgUw&input=&args=Mw)
```
‘Ḷ!*`S // Main link: Argument n (integer)
‘ // Take n, increment by 1
Ḷ // Range from [0..n]
! // Calculates factorial for each [0..n]
*` // Raises each [0!..n!] to the power of itself
S // Sum the resulting array
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 5 bytes
Code:
```
Ý!DmO
```
Explanation:
```
Ý # Take the range [0, ..., input]
! # Map factorial over each element
Dm # Exponentiate each element to itself
O # Take the sum
```
Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=w50hRG1P&input=Mw)
[Answer]
## R - ~~34~~ 30 bytes
```
x=factorial(0:scan());sum(x^x)
```
vectorizing is nice
**edit:** saved 4 bytes thanks to @MickyT
[Answer]
# J, ~~15~~ 12 bytes
Saved 3 bytes thanks to miles!
```
1#.i.^~@!@,]
```
## Explanation
```
1#.i.^~@!@,] input: y
,] append y to list...
i. [0, y)
!@ factorial each member
^~@ raise each to itself
1#. perform summation
```
## Test cases
```
f =: 1#.i.^~@!@,]
(,. f"0) i.4
0 1
1 2
2 6
3 46662
(,. f"0) i.6
0 1
1 2
2 6
3 46662
4 1.33374e33
5 3.17504e249
echo"1] _90]\":f 6x
190281878633201797429473437859705759836595323046380462211756876146775419721154680216391116
383660154937824558291984804764687140715927099993629348072943551413397410741069111169123658
220861477766905534108349401724389611558474171816216027733366046875815097164882588181826712
426524007417126023680300953790645455254723360874298622143752208989152655091222094594342956
890526202094068774356589887610542642450567071133028553816930267473112879050178461179814798
008667622200592591542432361632955904924276854403585221477449385731481108378608652069211835
448555831555820393949831627809528917004144455150642180845929102272754394116905511650997561
389917179995442329297103257850695109383021080317204810134810158543814178231002423431556657
737982683316707709406053569620116083909440177269311235173671447595521339849978144493268530
780365729831790064477684808893338190825461650933123545889305523546630119181308584140916288
912561260392366609493077363059677222110731132927863243720195975705161197786520981159422881
575250362836779593393897664990291828935858671453835924398316498051705698128484688847592380
831018330553151156822298060174230201841578757499203145955456593022852288527824268115043999
037373974753999860179933517198889966353093307592136928730661270863274130109304971274296438
682725017433937245229524959283895094220677649257613358344409711070780405579776000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
000000003175042373780336892901667920556557182493442088021222004926225128381629943118937129
098831435345716937405655305190657814877412786176000000000000000000000000000000000000000000
000000000000000000000000000000000000000000001333735776850284124449081472890438
```
[Answer]
# [Perl 6](http://perl6.org/), ~~41~~ ~~38~~ 37 bytes
```
{[+] ([**] [*](1..$_)xx 2 for 0..$_)}
```
```
{[+] ([**] ([*] 1..$_)xx 2 for 0..$_)}
```
```
{sum (($_**$_ with [*] 1..$_) for 0..$_)}
```
([Try it online.](https://tio.run/#h2mY0))
### Explanation:
* `for 0 .. $_`: For each integer from 0 to the input,
* `[*](1 .. $_) xx 2`: calculate the factorial twice,
* `[**] ...`: and exponentiate the two identical factorials.
* `[+] ...`: Then sum all results of the loop.
*Thanks to b2gills for 1 byte.*
[Answer]
# [Cheddar](http://cheddar.vihan.org), ~~44~~ 37 bytes
```
n->(0|>n=>(i,a=(1|>i)/(*))->a**a)/(+)
```
Thank goats for reduce operator! I think it would've been good idea to add factorial
[Try it online](http://vihan.org/p/tio/?l=cheddar&p=y0ktUUizVcjTtdMwqLHLs7XTyNRJtNUwrLHL1NTX0NLU1LVL1NJKBLK1Na25uAqKMvOAGjSMgRwY20TT@j8A)
## Ungolfed
```
n -> ( 0|>n => (i, a=(1|>i) / (*)) -> a ** a) / (+)
```
## Explanation
**Note:** A little outdated, will fix
```
n -> // Input
( 0 |> n) => // Run below for each of [0, n]
(
i, // Input
a = // Let's keep n! in this variable `a`
(1 |> i) // Range from [1, n]
/ (*) // Multiply all the items of that range
// `/` is reduce `(*)` is multiplication function
) ->
a ** a // A to the power of A
) / (+) // Sum all results
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 7 bytes
```
Q:Ygt^s
```
[Try it online!](https://tio.run/nexus/matl#@x9oFZleElf8/78xAA "MATL – TIO Nexus")
### Explanation
```
Q % Take input n implicitly. Add 1
: % Range [1 2 ... n+1]
Yg % Gamma function, element-wise. This gives [0! 1! ... n!]
t^ % Rise result to itself, element-wise
s % Sum all values. Implicitly display
```
[Answer]
# PHP, 49 bytes
```
for($f=1;$i<=$argv[1];$f*=++$i)$s+=$f**$f;echo$s;
```
`INF` for `n>5` on a 64 bit system.
**for large numbers, 70 bytes**
```
while($i<=$argv[1])$s=gmp_add($s,gmp_pow($f=gmp_fac($i++),$f));echo$s;
```
requires PHP to be compiled with `--with-gmp`
[Answer]
# Ruby, ~~64~~ 66 bytes
```
->n{(o=(1..n).map{|i|a=(1..i).inject(:*);a**a}.inject(:+))?o+1:1}
```
Added two characters for the off-by-one bugfix (will look into shortening the inject calls later).
[Answer]
# Pyth - ~~9~~ 8 bytes
```
s^Rd.!Mh
```
[Test Suite](http://pyth.herokuapp.com/?code=s%5ERd.%21Mh&test_suite=1&test_suite_input=0%0A1%0A2%0A3&debug=0).
[Answer]
# Haskell, ~~67~~ 56 bytes
Note that this submission was made *before* the rules that banned builtins were removed.
```
p=product
a n=sum[p[x|x<-[p[1..i]],_<-[1..x]]|i<-[0..n]]
```
For example:
```
*Main> a 0
1
*Main> a 1
2
*Main> a 2
6
*Main> a 3
46662
*Main> a 4
1333735776850284124449081472890438
*Main> a 5
3175042373780336892901667920556557182493442088021222004926225128381629943118937129098831435345716937405655305190657814877412786176000000000000000000000000000000000000000000000000000000000000000000000000000000000000001333735776850284124449081472890438
```
[Answer]
# Python 2, ~~73~~ 72 bytes
```
import math
lambda n,f=math.factorial:sum(f(i)**f(i)for i in range(n+1))
```
[Answer]
# [PARI/GP](http://pari.math.u-bordeaux.fr/), 19 bytes
```
n->sum(k=0,n,k!^k!)
```
[Answer]
# GameMaker Language, 97 bytes
Main function (52 bytes)
```
for(a=0;a<=argument0;a++)b+=power(f(a),f(a))return b
```
Function f (45 bytes)
```
a=argument0 if!a return 1else return a*f(a--)
```
[Answer]
# R, 42 ~~35~~ bytes
Now that I've read the question properly, I've put the sum in.
This requires the **gmp** (multiple precision arithmetic) library to be available. This allows for large numbers to be handled. Otherwise anything over 5 returns `INF`.
This is implemented as a unnamed function to avoid the `as.character` that would be required to output to STDOUT through `cat`
```
function(x)sum((i=gmp::factorialZ(0:x))^i)
```
Example run
```
> f <- function(x)sum((i=gmp::factorialZ(0:x))^i)
> f(5)
Big Integer ('bigz') :
[1] 3175042373780336892901667920556557182493442088021222004926225128381629943118937129098831435345716937405655305190657814877412786176000000000000000000000000000000000000000000000000000000000000000000000000000000000000001333735776850284124449081472890438
> f(6)
Big Integer ('bigz') :
[1] 190281878633201797429473437859705759836595323046380462211756876146775419721154680216391116383660154937824558291984804764687140715927099993629348072943551413397410741069111169123658220861477766905534108349401724389611558474171816216027733366046875815097164882588181826712426524007417126023680300953790645455254723360874298622143752208989152655091222094594342956890526202094068774356589887610542642450567071133028553816930267473112879050178461179814798008667622200592591542432361632955904924276854403585221477449385731481108378608652069211835448555831555820393949831627809528917004144455150642180845929102272754394116905511650997561389917179995442329297103257850695109383021080317204810134810158543814178231002423431556657737982683316707709406053569620116083909440177269311235173671447595521339849978144493268530780365729831790064477684808893338190825461650933123545889305523546630119181308584140916288912561260392366609493077363059677222110731132927863243720195975705161197786520981159422881575250362836779593393897664990291828935858671453835924398316498051705698128484688847592380831018330553151156822298060174230201841578757499203145955456593022852288527824268115043999037373974753999860179933517198889966353093307592136928730661270863274130109304971274296438682725017433937245229524959283895094220677649257613358344409711070780405579776000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003175042373780336892901667920556557182493442088021222004926225128381629943118937129098831435345716937405655305190657814877412786176000000000000000000000000000000000000000000000000000000000000000000000000000000000000001333735776850284124449081472890438
```
f(9) will runs pretty well, but fills up a number of pages. A few hundred or so and 2,017,528 digits. f(10) kills the session on my machine.
[Answer]
## JavaScript (ES7), 38 bytes
```
f=(n,a=1,i=0)=>i>n?0:a**a+f(n,a*++i,i)
```
[Answer]
# Dyalog APL, 10 bytes
```
(+/!*!)0,⍳
```
**How?**
`⍳` range of input
`0,` preceded with 0
`!*!` apply `x! ^ x!`
`+/` sum
[Answer]
# [Golfscript](http://www.golfscript.com/golfscript/index.html), 41 bytes
```
{.{,{1+}%{*}*}{;1}if}:f;~.,\+{.f\f?}%{+}*
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPn/v1qvWqfaULtWtVqrVqu22tqwNjOt1irNuk5PJ0a7Wi8tJs0eKKddq/X/vzEA)
[Answer]
# [Thunno](https://github.com/Thunno/Thunno) `+`, \$ 7 \log\_{256}(96) \approx \$ 5.76 bytes
```
RFDz.^S
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_abSStlLsgqWlJWm6FsuD3Fyq9OKCITyo4IKFxhAGAA)
#### Explanation
```
RFDz.^S # implicit input
# + flag adds one
R # range from 0
F # factorial of each
z. # for each number:
D ^ # raise it to the power of itself
S # sum the resulting list
# implicit output
```
[Answer]
# [vemf](https://github.com/selaere/vemf), ~~3~~ 5 bytes
```
▲↕!┴^
```
## Explanation
```
▲↕ ' range [0, α)
┴ ' run this function:
^ ' exponentation
' with this for both inputs:
! ' factorial of each element in range
```
e.g. `3▲↕!┴^+` – [try it online](https://selaere.github.io/vemf/wasm/index.html?code=Mx4SIcFeKw)
[Answer]
# Mathematica, 19 bytes
```
Sum[a!^a!,{a,0,#}]&
```
Anonymous function. Takes a number as input, and returns a number as output.
[Answer]
## Pyke, 11 bytes
```
hFSBD]1*B)s
```
[Try it here!](http://pyke.catbus.co.uk/?code=hFSBD%5D1%2aB%29s&input=3)
```
hF - for i in range (0, input+1)
SB - product(range(1, i+1)
D]1* - [^]*^
B - product(^)
s - sum(^)
```
Fun fact: Pyke doesn't have a factorial built-in because `SB` is only 2 bytes!
[Answer]
## Haskell, 43 bytes
```
b n|f<-product[1..n]=f^f
a n=sum$b<$>[0..n]
```
Usage example: `a 3`-> `46662`.
`b` calculates a single ultrafactorial and `a` sums all ultrafactorials from `0` to `n`.
[Answer]
# JavaScript (ES7), 44 bytes
```
g=n=>n?(f=a=>a?a*f(a-1):1)(n)**f(n)+g(n-1):1
```
[Answer]
# Python 2, 82 Bytes
```
x=input()
s=0
for z in range(x):
t=1
for i in range(z+1):t*=i+1
s+=t**t
print s
```
[Answer]
# [Wonder](https://github.com/wonderlang/wonder), 33 bytes
```
@sum(->@^ f\prod rng1#0f)rng0+1#0
```
Usage:
```
(@sum(->@^ f\prod rng1#0f)rng0+1#0)3
```
# Explanation
```
rng0+1#0
```
Create inclusive range from 0 to input.
```
->@^ f\prod rng1#0f
```
Map over the range with a function that 1) calculates the factorial of the item, 2) stores the result to `f`, and 3) calculates `f^f`.
```
sum
```
Sum.
[Answer]
# TI-Basic, 13 bytes
```
sum(seq(A!^A!,A,0,Ans
```
P.S. You can replace `sum(seq(` with `Σ(` if you have a newer operating system (no size change).
[Answer]
# Ruby 2, 41 bytes
```
->n{(1..n).reduce(s=1){|t,i|t+(s*=i)**s}}
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 7 bytes
```
→ṁo´^Πḣ
```
[Try it online!](https://tio.run/##AS4A0f9odXNr/yBt4oKB/@KGkuG5gW/CtF7OoOG4o////1swLDEsMiwzLDQsNSw2LDdd "Husk – Try It Online")
```
→ One plus
ṁ the sum of
Π x!
^ to the power of
´ itself
ṁo for each x in
ḣ the range from 1 to
the input.
```
It would be slightly more correct to use [`ṁo´^ΠΘḣ`](https://tio.run/##AS0A0v9odXNr/yBt4oKB/@G5gW/CtF7OoM6Y4bij////WzAsMSwyLDMsNCw1LDYsN10), actually adding 0 into the range, but since 0!^0!=1^1=1, this works too.
] |
[Question]
[
This is a Cops and Robbers challenge. This is the robber's thread. The [cop's thread is here](https://codegolf.stackexchange.com/q/188142/31716).
The cops will pick any sequence from the [OEIS](https://oeis.org/), and write a program **p** that prints the first integer from that sequence. They will also find some string **s**. If you insert **s** somewhere into **p**, this program must print the second integer from the sequence. If you insert **s + s** into the same location in **p**, this program must print the third integer from the sequence. **s + s + s** in the same location will print the fourth, and so on and so forth. Here's an example:
>
> # Python 3, sequence [A000027](https://oeis.org/A000027)
>
>
>
> ```
> print(1)
>
> ```
>
> The hidden string is **two bytes**.
>
>
>
The string is `+1`, because the program `print(1+1)` will print the second integer in A000027, the program `print(1+1+1)` will print the third integer, etc.
Cops must reveal the sequence, the original program **p**, and the length of the hidden string **s**. Robbers crack a submission by finding any string *up to* that length and the location to insert it to create the sequence. The string does not need to match the intended solution to be a valid crack, nor does the location it's inserted at.
If you crack one of the cops answers, post your solution (with the hidden string and location revealed) and a link to the answer. Then comment on the cops answer with a link to your crack here.
## Rules
* Your solution must work for any number in the sequence, or at least until a reasonable limit where it fails due to memory restrictions, integer/stack overflow, etc.
* The winning robber is the user who cracks the most submissions, with the tiebreaker being who reached that number of cracks first.
* The winning cop is the cop with the shortest string **s** that isn't cracked. Tiebreaker is the shortest **p**. If there are no uncracked submissions, the cop who had a solution uncracked for longest wins.
* To be declared safe, your solution must stay uncracked for 1 week and then have the hidden string (and location to insert it) revealed.
* **s** may not be nested, it must concatenated end to end. For example, if **s** was `10`, each iteration would go `10, 1010, 101010, 10101010...` rather than `10, 1100, 111000, 11110000...`
* All cryptographic solutions (for example, checking the hash of the substring) are banned.
* If **s** contains any non-ASCII characters, you must also specify the encoding being used.
[Answer]
# [Python 2](https://docs.python.org/2/), sequence [A138147](https://oeis.org/A138147) [by xnor](https://codegolf.stackexchange.com/a/188207)
Original:
```
print 10
```
Cracked:
```
print "1%s0"%10
^^^^^^^
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69EQclQtdhASdXQ4P9/AA "Python 2 – Try It Online")
[Answer]
# [Brain-Flak](https://github.com/Flakheads/BrainHack), [A000984](https://oeis.org/A000984) by [Nitrodon](https://codegolf.stackexchange.com/a/188258/56656)
```
({({}<>({}))<>}<>){({}<>)<>}<>
```
This is only 30 bytes, not sure what Nitrodon had in mind.
[Try it online!](https://tio.run/##SypKzMzLSEzO/v9fQ0NTk0ujWqO61sYOSGhq2tgBWZoQAQiHYunq2lqg3P//AA "Brain-Flak (BrainHack) – Try It Online")
# Explanation
I tried a lot of things but here is what worked. The terms of A000984 are the central elements of Pascal's triangle.
[](https://i.stack.imgur.com/35ndj.png)
Now I figured out that I can get them by adding up the diagonals above them:
For example:
\$1+3+6+10 = 20\$
[](https://i.stack.imgur.com/sUIJg.png)
And since the final action in Nitrodon's program is to sum up everything these seemed like a good candidate (more like I tried a bunch of things but this one ended up working).
So we want a program that takes one partial sum and produces the next. Luckily there is a pretty neat way to get from one of these to the next. Each row is the deltas of the next row. That is the \$n\$th term in a row is the difference between the \$n\$th and \$n-1\$th terms in the next row.
[](https://i.stack.imgur.com/nBjs8.png)
The one problem is that we don't quite have enough of the last row to calculate the row we want. Since each row is one longer than the last if we have a row we can't get the last member of the next row with this method. However here we have another trick, the last member of each row is equal to all previous members of that row!
\$1+3+6=10\$
[](https://i.stack.imgur.com/aIZrZ.png)
And if you are familiar with Brain-Flak that should stick out to you as something that is going to be really easy to do.
Now for the code:
To start we do the next row calculation where each new member is the sum of two adjacent old members. That can be done with:
```
{({}<>({}))<>}<>
```
Which basically moves an element over and adds (without deletion) what ever was already on top to it. However this reverses everything so for the next time we get a row we need to put it back.
```
{({}<>({}))<>}<>{({}<>)<>}<>
```
Now we need to calculate the last member of the row. As I said before this is super easy. Since we had a loop over all the elements of the row we can just take that sum and push it. We push it before the second loop so it ends up on the bottom.
```
({({}<>({}))<>}<>){({}<>)<>}<>
```
And that's it.
[Answer]
# Brain-Flak, [A000290](https://oeis.org/A000290), [by Sriotchilism O'Zaic](https://codegolf.stackexchange.com/a/188151/25180)
Original:
```
((()))({}<>)
```
Cracked:
```
((()))({}([])[]<>)
^^^^^^
```
[Try it online!](https://tio.run/##SypKzMzLSEzO/v9fQ0NDU1NTo7pWIzpWMzrWxk7z/38A "Brain-Flak (BrainHack) – Try It Online")
Alternatively:
```
((())([])[])({}<>)
^^^^^^
```
[Try it online!](https://tio.run/##SypKzMzLSEzO/v9fQ0NDU1MjOlYTiDSqa23sNP//BwA "Brain-Flak (BrainHack) – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), sequence [A005206](http://oeis.org/A005206) by [Luis Mendo](https://codegolf.stackexchange.com/a/188163/12324)
Original:
```
voOdoO
```
[Try it online!](https://tio.run/##y00syfn/vyzfPyXf//9/AA "MATL – Try It Online")
Cracked:
```
voOdoOdNq17L/k
^^^^^^^^
```
I am not a MATL expert, but from what I understand, the original `voOdoO` creates two empty arrays and an array `[0]` on the stack. this `[0]` is what gets printed without brackets as the first element of the sequence. The crack/solution then does the following:
* `d` takes an elements off the stack and (assuming it's a number or an array of size 1) turns it into an empty array. These empty arrays don't get printed, but contribute to the stack size
* `Nq` counts the size of the stack and subtracts one. This is the `n+1` term when evaluating the function (since it starts at 2 and increases by one every iteration because of the `d` adding invisible stuff to the stack)
* `17L` this is the constant `Phi = (1+sqrt(5))/2`
* `/k` this performs `floor((n+1)/Phi)` which is one of the formulas that computes the elements of the sequence. This formula is listed on OEIS as `a(n) = floor(sigma*(n+1)) where sigma = (sqrt(5)-1)/2` except we use the identity `(sqrt(5)-1)/2 = 1/Phi`
[Answer]
# Python 3 -- [A\_\_](https://codegolf.stackexchange.com/a/188152/67312)
```
print(100+-1)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69Ew9DAQFvXUPP/fwA "Python 3 – Try It Online")
100 bottles of beer, add `-1` to get the next number, `99`, etc.
[Answer]
# [Keg](https://esolangs.org/wiki/Keg), sequence [A000045](https://oeis.org/A000045), by [A\_\_](https://codegolf.stackexchange.com/users/85052/a)
Original:
```
0.
```
Cracked:
```
01":&+.
^^^^^
```
Note that the challenge was finding a substring of length <=6, but the found string has length 5.
Definition of the commands for those who are too lazy to look up the Keg specification:
`0` and `1` push the respective number to the stack;
`"` moves the stack top to the stack bottom (roll);
`&` pops the stack top into the register if it's empty, otherwise empties the register onto the stack;
`+` adds the top two stack values.
The initial `1"` just inserts a 1 at the bottom of the stack.
This growing list of 1's only plays a role in the first iteration, where it allows us to assume the stack starts as `1 0` rather than just `0`.
Indeed, the program `10:&+.`, where the `:&+` part is repeated, has the exact same behaviour as the solution above, except that it doesn't have a growing list of 1's at the bottom.
Since `&` is used only once in the repeating part and has alternating behaviour, the behaviour of `1":&+` depends on the parity of the iteration.
Now, this program doesn't really print the sequence Fibonacci sequence starting with 0, 1 from the start; it actually prints the 1, 0 Fibonacci sequence from the second place, i.e. from the 0.
(This results in the same sequence.)
Knowing this, the program is easily analysed:
* In the first, third, ... iteration, the state starts as `[a, b]` and ends as `a+b (&=b)`.
* In the second, fourth, ... iteration, the state starts as `[b] (&=a)` and ends as `[b, b+a]`.
This indeed computes the sequence as required.
[Answer]
# [Pyret](https://code.pyret.org/), sequence [A083420](https://oeis.org/A083420), by [MLavrentyev](https://codegolf.stackexchange.com/a/188204/73884)
```
fold({(b,e):(2 * b) + 1},1,[list: 0,0,])
^^^^
```
[You can run it here, but I've not figured out how to link to the code. You'll have to copy-paste.](https://code.pyret.org/editor)
The function provided ignores its second argument. It doubles its first and adds one, which will generate the necessary `2^n - 1` sequence needed here—all I need do is tell it how many times to perform that operation, done by changing the length of the folded list. Fortunately, Pyret doesn't complain about that trailing comma.
[Answer]
# Java 8+, sequence [A010686](https://oeis.org/A010686) [by Benjamin Urquhart](https://codegolf.stackexchange.com/a/188267/20260)
```
()->System.out.println(1^4);
^^
```
[Answer]
# Brain-Flak, [A000578](http://oeis.org/A000578) [by Sriotchilism O'Zaic](https://codegolf.stackexchange.com/a/188244/71256)
Original:
```
((())<>)
```
[Try it online!](https://tio.run/##SypKzMzLSEzO/v9fQ0NDU9PGTvP/fwA)
Cracked:
```
((())(({})([][][]){})<>)
^^^^^^^^^^^^^^^^
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/X0NDQ1NTQ6O6VlMjOhYENYFMGzvN//8B)
[Answer]
# [AsciiDots](https://github.com/aaronduino/asciidots), sequence [A019523](http://oeis.org/A019523) by [Alion](https://codegolf.stackexchange.com/a/188383/69059)
```
\+++/
//\/\
```
[Once!](https://tio.run/##SyxOzsxMyS8p/v9f385QWUslXjmGSytOt1q7VlNPn6tGP0Y/hitGW1tbn0sfxAbxILTa//8A "AsciiDots – Try It Online")
[Twice!](https://tio.run/##SyxOzsxMyS8p/v9f385QWUslXjmGSytOt1q7VlNPn6tGP0Y/hitGW1tbn0sfnQ3iQWi1//8B "AsciiDots – Try It Online")
[Ten times!](https://tio.run/##SyxOzsxMyS8p/v9f385QWUslXjmGSytOt1q7VlNPn6tGP0Y/hitGW1tbn0uf3mwQD0Kr/f8PAA "AsciiDots – Try It Online")
While trying to figure out how the code/language works, I learned that the first two lines of the existing code does all the work of outputting the Fibonacci sequence infinitely. The code terminates when any dot hits the `&`, so I merely needed to add further delay in the remaining lines to allow for the appropriate number of entries to output.
After some trial, error, and observation, I discovered that the correct delay interval is 16 time units per number. Fitting enough characters in a single row seemed infeasible, so I would need to put the delay in 2 rows, leaving 10 characters for the actual delay. In order for the pattern to match up with itself, both rows had to have 5 characters, and since the middle three characters in a row can be traversed twice, this gives 16 time units as desired.
The requirement to match this up to the `&` in the eighth column seemed to make this impossible, until I realized that I could start with a newline in the interior of the third row. This makes the penultimate row the right length, and removes the now-redundant end of the third line.
[Answer]
# [Python 3](https://docs.python.org/3/), sequence [A268575](http://oeis.org/A268575) by [NieDzejkob](https://codegolf.stackexchange.com/a/188344)
Original:
```
from itertools import product
S,F,D=lambda*x:tuple(map(sum,zip(*x))),lambda f,s:(v for x in s for v in f(x)),lambda s:{(c-48>>4,c&15)for c in map(ord,s)}
W=D("6@AQUVW")
print(len(W))
```
Cracked (100 bytes):
```
from itertools import product
S,F,D=lambda*x:tuple(map(sum,zip(*x))),lambda f,s:(v for x in s for v in f(x)),lambda s:{(c-48>>4,c&15)for c in map(ord,s)}
W=D("6@AQUVW");A=-1,1,0;*X,=F(lambda a:(S(a,x)for x in product(A,A)),W);W={p for p in X if 2<X.count(p)<4+({p}<W)}
print(len(W))
```
[Try it online!](https://tio.run/##RY5bS8NAEIXf@yuWPshMnIrRKJJLMVD6LsVuXmMuuJBkh91NiYb@9pjUom@HmY/zHf5yn7p7nKba6FYoVxmndWOFalkbJ9josi/c6kB72iVN3n6UuTeEruemgjZnsH1L34rBGxCRfgFRkw3hJGptxCBUJ@wlnpZYw/DP2XCEYhO8bLcBFTf@Ey5YsWBLtTYlWTyvZLKD9fNr@vZ@lGuM0mTjk0/3kZdRsodrVR7CAXIa8E96nQ4ppbNRYiSTkS9DeHlnQtXiIc7uCt13Dhjj4BZGPsdyVrJR862pOpCI0/QD "Python 3 – Try It Online")
From what I can gather, the original code is setting up definitions to make the hidden string as abbreviated as possible and then defining the initial Game of Life pattern. The hidden string is then equivalent to writing an iteration of Conway's Game of Life in 102 bytes.
For the purposes of this crack, `S` is a function that sums the elements within its arguments (which are iterables) and `F` applies a function returning an iterable to every element of a list and smashes all the results together.
* `;A=-1,1,0;` ends the preceding statement and abbreviates the tuple (-1,1,0) with A, which is used as `product(A,A)` which gives all the neighbors relative to a given cell as well as the cell itself.
* `*X,=F(lambda a:(S(a,x)for x in product(A,A)),W);` creates a new list `X` holding all the neighbors of cells in `W` and the cells in `W` themselves by adding the relative positions of the neighbors to each cell and smashing them together into a list.
* `W={p for p in X if 2<X.count(p)<4+({p}<W)}` goes through this list `X` and determines whether each cell in `X` belongs in the set of cells in the next iteration. This was taken almost verbatim from [this Game of Life golf](https://codegolf.stackexchange.com/a/3531/88056).
[Answer]
# [Unefunge-98 (PyFunge)](https://pythonhosted.org/PyFunge/), sequence [A000108](http://oeis.org/A000108), by [NieDzejkob](https://codegolf.stackexchange.com/a/188296/73884)
```
1# 2g1+:2p4*6-*2g/.@
^^^^^^^^^^^^^^^^^
```
[Try it online!](https://tio.run/##K81LTSvNS0/VtbTQLagEM///N1RmNEo31LYyKjDRMtPVMkrX13P4/x8A)
[Repeated six times](https://tio.run/##K81LTSvNS0/VtbTQLagEM///N1RmNEo31LYyKjDRMtPVMkrXp4mAnsP//wA)
Two bytes to spare of the nineteen allowed! What appears to be a space there is actually a 0x01 Start Of Header character.
### Explanation:
This challenge is all about generating `a(n)` from `a(n-1)` and perhaps `n`. OEIS provides the explicit formula `a(n) = (2n)!/(n!(n+1)!)`, which is easily enough converted to `a(n) = a(n-1) * (4n-6) / n`. Now to implement this in Funge.
I must be inserting code between the `1` and the `.`. That's half the puzzle done already. All that remains is what code to insert? Funge is notably lacking in stack manipulation tools, so the bottom of the stack is off-limits; I need to track both `n` and `a(n)` without growing the stack. And how better to do that than with Funge space?
That 0x01 character is my counter `n`. I keep `a(n)` on the stack, as it must be on the stack after my bit finishes executing.
```
1# 2g1+:2p4*6-*2g/.@
1 Push 1. This is a(0).
# Skip the next instruction. Without this, I believe the instruction pointer will reverse direction upon encountering 0x01.
2g Push the third character in the source, which starts out as 1.
1+ Increment it...
: ...copy it...
2p ...and put it back. One copy remains atop the stack.
4*6- Multiply by four. Subtract six.
* Multiply by a(n), leaving the result alone on the stack.
2g Push n again...
/ ...and divide our intermediate result by it. Ta-da!
At this point, the stack is the same as at the start of the indented block, except the one item has been advanced one place in the sequence.
The source of the program has changed; the third character holds the number of times this indented block has run.
.@ Print and terminate.
```
[Answer]
## Haskell, [A014675](https://oeis.org/A014675) by [Khuldraeseth na'Barya](https://codegolf.stackexchange.com/a/188351/34531)
Original code
```
main=print$uncurry(!!)([2],0)
```
With substring
```
main=print$uncurry(!!) ([2],0)
$(\(a,n)->(a>>= \e->2:[1|e>1],n+1))
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/PzcxM0/BViEln0tBoaAoM69EpTQvubSoqFJDUVFTgSpAI9ooVsdAE5sFKhoxGok6eZq6dhqJdna2CjGpunZGVtGGNal2hrE6edqGmpo0t4AIJVAL/v8HAA "Haskell – Try It Online")
[Answer]
# [Haskell](https://haskell.org), [A000045 (Fibonacci)](https://oeis.org/A000045), by [Rin's Fourier transform](https://codegolf.stackexchange.com/a/188503/73884)
```
f = head $(flip(:)<*>sum.take 2)[0, 1]
^^^^^^^^^^^^^^^^^^^^^^^
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P03BViEjNTFFQUUjLSezQMNK00bLrrg0V68kMTtVwUgz2kDHMJYrnYAqvJozyNNMjlVZ9LCK5t74n5uYmQf0SUo@l4JCQVFmXolCmgIQ6OoqBKcm5@elKKTmpOam5pXoKBjCVaRDVYRkZBYhKUBSkQFV4ZaZVpKBpMIYriILqsIPyEFWYWT4HwA)
23 bytes exactly.
This one was fun and a bit tricky. The reversed 0 and 1 threw me off for a little bit before I realized that wasn't an issue. The lack of `$` in the original had me trying sketchy stuff like `$...$id` (one byte too long) before it dawned on me that I could just wrap it all in parentheses. All in all, a nice little puzzle.
[H.PWiz](https://codegolf.stackexchange.com/users/71256/h-pwiz) points out that pattern matching could have saved me at least five bytes: `$(\[x,y]->[y,x+y])`. That darn pointfree challenge has me thinking pointfree everywhere.
[Answer]
# Desktop Calculator, [A006125](https://oeis.org/A006125), [by A\_\_](https://codegolf.stackexchange.com/a/188206/25180)
Original:
```
1n
```
Cracked:
```
1 2lx1+dsx^*n
^^^^^^^^^^^
```
[Try it online!](https://tio.run/##S0n@/99QwSinwlA7pbgiTivv/38A "dc – Try It Online")
Straightforward implementation.
[Answer]
# [cQuents](https://github.com/stestoltz/cQuents), sequence [A003617](https://oeis.org/A003617) by [Stephen](https://codegolf.stackexchange.com/a/188233/73884)
```
=10#2:pZ
^
```
[Try it online!](https://tio.run/##Sy4sTc0rKf7/39bQAAiUjawKov7/BwA)
Begin with the lowest n+1-digit number, a one followed by n zeroes. The `#2` specifies that only the second term of the sequence, which is the sequence definition applied once to the seed, will be printed; this sequence definition simply finds and returns the next prime.
[Answer]
# [Python 3](https://docs.python.org/3/) -- [agtoever](https://codegolf.stackexchange.com/a/188308/55934)
```
from sympy import isprime, primerange
from itertools import count
r=1
r+=1
while isprime(r-2)or r&1<1and r>3:r+=1
print(r)
```
[Try it online!](https://tio.run/##NcvBDoIwEATQe79iTwaCHio3A/wL0Sqb0N1musb06ytpwmXmMG9SsU1lrPUNjZRLTIU4JoUR5wSO4UqtsMonuKbYAkx1z6d86lfMYfYOwxG/jfdw3jvc7r2CcPGTX@VFWMZHY8cs1qGv9Q8 "Python 3 – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), sequence [A000796](https://oeis.org/A000796) by [Luis Mendo](https://codegolf.stackexchange.com/a/188284/12324)
Original:
```
'pi'td1_&:_1)Y$J)
```
[Try it online!](https://tio.run/##y00syfn/X70gU70kxTBezSreUDNSxUvz/38A "MATL – Try It Online")
Cracked:
```
'pi'td1_&:|SQ_1)Y$J)
^^^
```
The original author sneakily created the array `[-7:-1]` and then extracted and negated the first element of it to get `7`. He then used that to get the rounded 7'th digit of pi (which is `3`) and presented it as the first digit of pi. Adding in `|SQ` makes the original array all positive, sorts it, and adds one to everything. This means that after everything instead of getting the index `7` it gets the index `-2` after one application, `-3` after two applications, and so on. The `-` is important because it tells the `Y$` function to not round the digits.
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), [A000042](http://oeis.org/A000042), by [NieDzejkob](https://codegolf.stackexchange.com/a/188341/73884)
```
.( 1)1 .
^^^^^
```
[Try it online!](https://tio.run/##S8svKsnQTU8DUf//K@AChgp6XNjE9TQUDDWxSILFsUgixFEl0cThktjE4ZK4ZUcJoghgIP7/DwA)
The trivial 1-byter is simply extending the literal. Problem is, that overflows 64 bits as early as the ninteenth digit. Easy fix is to print the single digit repeatedly, right? Yep, but it's not quite that easy. Though tacking `1 .` onto the end will indeed print the additional digits we require, they'll be separated by spaces. That ain't gonna work.
Now, according to Wikipedia, "`.(` (dot-paren) is an immediate word that parses a parenthesis-delimited string and displays it." Fortunately, that displaying has no other weird characters, so using `.(` to print a single 1 should suffice. And it does. No space is needed after the close-paren, so these five characters (there's a space after the open-paren) can be repeated to our hearts' content. To demonstrate, I've included in TIO an example that would have overflowed a 64-bit int several times over. Works like a charm.
[Answer]
# [Python 3](https://docs.python.org/3/), [A008574 by tsh](https://codegolf.stackexchange.com/a/188373/20260)
```
print(1*2+2)
^^^^
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69Ew1CTC8rQMtI2QuFgFQAL/v8PAA "Python 3 – Try It Online")
[Answer]
# V, [A000290](https://oeis.org/A000290), [by DJMcMayhem](https://codegolf.stackexchange.com/a/188254/41805)
```
é*Ä2é*Ø.
^^^^
```
yields the squares from 1.
[Try it online!](https://tio.run/##K/v///BKrcMtRiByht5/IHeGHgA "V – Try It Online")
The base `é*` inserts `*` and `Ø.` counts the number of non-newline characters in the entire buffer. The insertion `Ä` duplicates the top line to its own line, on which `2é*` inserts `**`. Concatenations of the insertions yield successive odd numbers with the largest at the top. The final `Ø.` in effect sums the first n odd numbers, hence yielding the n-th square .
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), sequence [A114018](https://oeis.org/A114018) by [Unrelated String](https://codegolf.stackexchange.com/a/188479/41723)
Original program:
```
≜ṗ↔ṗb&w
```
String to insert:
```
≜ṗ↔ṗẹbb&w
^^
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1HnnIc7pz9qmwIkH@7amQTDSWrl//8DAA "Brachylog – Try It Online")
### Explanation
Here is first the explanation of the original program (knowing that the sequence used is "least n-digit prime whose digit reversal is also prime")
```
≜ Assign an integer value to a variable named ?
(try 0, then 1, then -1, then 2, etc.)
ṗ ? must be prime
↔ṗ The reverse of ? must be prime
b Remove the first element of ?
& Ignore that we removed that element
w Write ? to STDOUT
```
As you can see, the program is fairly straightforward except for one thing: there is a completely useless `b - behead` predicate call, that removes the first element of the reverse of our number, with which we don't do anything.
This is a definite clue as to how we can find the string. The idea is that, since we want to increase the length of the number by 1 digit each time we add the string, we need a string that "evaluates" the length of that number somehow, using that useless `b`.
The solution is to use `ẹb`: first, `ẹ - elements` will transform the number into a list of digits; then, `b - behead` will remove its first element. The trick is that `b` will fail if the list of digits is empty. So everytime we append a `b`, we will increase the length of the required number by 1 (because it will fail until the assigned value of `?` is high enough to contain sufficiently many digits so that the last `b` is applied on a list of one digit).
Re-appyling `ẹ` each time has no effect because it's already a list of digits. We only need it once at the beginning because if we behead a number like `9001` instead of the list of its digits, we will get `001 = 1` which loses information about the number of digits.
[Answer]
# [VDM-SL](https://github.com/overturetool/documentation/blob/editing/documentation/VDM10LangMan/VDM10_lang_man.pdf), [A000312](https://oeis.org/A000312), [by Expired Data](https://codegolf.stackexchange.com/a/188224/85334)
```
let m={1|->{0}}in hd reverse[let x=x+1 in x**x|x in set m(1)&x<card m(1)]
^^^^^^^^^^^^^
```
Since VDM-SL's `let`-expressions can re-bind variables which are already bound in an enclosing scope, `x**x` can be evaluated arbitrarily deeply nested in scopes in which `x` is one more than in the previous scope, while the original `x` is still less than the cardinality of `m(1)`.
[Answer]
## Haskell, [A083318](https://oeis.org/A083318) by [xnor](https://codegolf.stackexchange.com/a/188536/34531)
```
f=length [2]
$show
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P802JzUvvSQj2iiWKx3KVinOyC8HCWQgC8BFMzFE4VJcuYmZeba5iQW@CgVFmXklCtFpOuk6GTqZsQoKCv//AwA "Haskell – Try It Online")
[Answer]
# Pure [Bash](https://www.gnu.org/software/bash/), sequence [A010888](https://oeis.org/A010888) by [nrgmsbki4spot1](https://codegolf.stackexchange.com/a/235785/78410)
Adds 17 bytes (1 fewer than OP). The added portion is the two lines in the middle, including two newlines.
```
x=
((x%9))||x=
x+=1
echo ${#x}
```
[Try it online!](https://tio.run/##S0oszvj/v8KWS0OjQtVSU7OmBsiu0LY15EpNzshXUKlWrqj9/x8A "Bash – Try It Online") or [check out first 20 iterations](https://tio.run/##S0oszvj/v8KWKy2/SCFTITNPodpQT8/IoNZaISWfS0OjQtVSU7OmBqigQtvWkCs1OSNfQaVauaKWKyU/L/X/fwA).
`x+=1` appends 1 to `x` as a string. Before adding it, `x` is reset to empty if `x` modulo 9 is zero.
[Answer]
# [1+](https://esolangs.org/wiki/1%2B), sequence [A000079](http://oeis.org/A000079), [by HighlyRadioactive](https://codegolf.stackexchange.com/a/209709/86301)
```
1"+:
^^
```
`"` duplicates the (only) number on the stack, and `+` adds the two numbers on the stack, thus doubling repeatedly to give the powers of 2.
[Answer]
# [1+](https://esolangs.org/wiki/1%2B), sequence [A058891](https://oeis.org/A058891) [by HighlyRadioactive](https://codegolf.stackexchange.com/a/209718/86301)
```
1"*"+:
^^^^
```
`"*` duplicates the stack and multiplies, thus squaring. `"+` duplicates the stack and adds, thus doubling.
] |
[Question]
[
Consider an array `x` such as `[1 5 3 4]` and a number `n`, for example `2`. Write all length-`n` sliding subarrays: `[1 5]`, `[5 3]`, `[3 4]`. Let the *minimax* of the array be defined as the minimum of the maxima of the sliding blocks. So in this case it would be the minimum of `5, 5, 4`, which is `4`.
## Challenge
Given an array `x` and a positive integer `n`, output the minimax as defined above.
The array `x` will only contain positive integers. `n` will always be at least `1` and at most the length of `x`.
Computation may be done by any procedure, not necessarily as defined above.
Code golf, fewest bytes wins.
## Test cases
`x`, `n`, result
```
[1 5 3 4], 2 4
[1 2 3 4 5], 3 3
[1 1 1 1 5], 4 1
[5 42 3 23], 3 42
```
[Answer]
# Dyalog APL, 4 bytes
```
⌊/⌈/
```
This is a monadic function train that expects array and integer as right and left arguments, resp.
Try it with [TryAPL](http://tryapl.org/?a=2%20%28%u230A/%u2308/%29%201%205%203%204&run).
### How it works
A train of two functions is an *atop*, meaning that the right one is called first (with both arguments), then the left one is called on top of it (with the result as sole argument).
A monadic `f/` simply reduces its argument by `f`. However, if called dyadically, `f/` is n-wise reduce, and takes the slice size as its left argument.
```
⌊/⌈/ Monadic function. Right argument: A (array). Left argument: n (list)
⌈/ N-wise reduce A by maximum, using slices of length n.
⌊/ Reduce the maxima by minimum.
```
[Answer]
## CJam (11 bytes)
```
{ew::e>:e<}
```
[Online demo](http://cjam.aditsu.net/#code=%5B1%201%201%201%205%5D%204%0A%0A%7Bew%3A%3Ae%3E%3Ae%3C%7D%0A%0A~)
[Answer]
# Ruby 39 bytes
```
->(x,n){x.each_slice(n).map(&:max).min}
```
Where x is the array and n is the number to chunk the array by.
[Answer]
# Oracle SQL 11.2, 261 bytes
```
SELECT MIN(m)FROM(SELECT MAX(a)OVER(ORDER BY i ROWS BETWEEN CURRENT ROW AND :2-1 FOLLOWING)m,SUM(1)OVER(ORDER BY i ROWS BETWEEN CURRENT ROW AND:2-1 FOLLOWING)c FROM(SELECT TRIM(COLUMN_VALUE)a,rownum i FROM XMLTABLE(('"'||REPLACE(:1,' ','","')||'"'))))WHERE:2=c;
```
Un-golfed
```
SELECT MIN(m)
FROM (
SELECT MAX(a)OVER(ORDER BY i ROWS BETWEEN CURRENT ROW AND :2-1 FOLLOWING)m,
SUM(1)OVER(ORDER BY i ROWS BETWEEN CURRENT ROW AND :2-1 FOLLOWING)c
FROM (
SELECT TRIM(COLUMN_VALUE)a,rownum i
FROM XMLTABLE(('"'||REPLACE(:1,' ','","')||'"'))
)
)
WHERE :2=c;
```
[Answer]
## Pyth, 10 bytes
```
hSmeSd.:QE
```
Explanation:
```
- autoassign Q = eval(input())
.:QE - sublists(Q, eval(input())) - all sublists of Q of length num
meSd - [sorted(d)[-1] for d in ^]
hS - sorted(^)[0]
```
Takes input in the form `list newline int`
[Try it here!](http://pyth.herokuapp.com/?code=hSmeSd.%3AQE&input=%5B1%2C+5%2C+3%2C+4%5D%0A2&debug=0)
[Or run a Test Suite!](http://pyth.herokuapp.com/?code=hSmeSd.%3AQE&input=%5B1%2C+5%2C+3%2C+4%5D%0A2&test_suite=1&test_suite_input=%5B5.4%2C+-3.4%2C+6.7%2C+8.8%2C+-1.2%5D%0A3%0A%5B-1%2C+2%2C+-3%2C+4%2C+-5%5D%0A2%0A%5B-1%2C+2%2C+4%2C+-3%2C+-5%5D%0A2%0A%5B0.2%2C+4.5%2C+3.4%2C+2.3%5D%0A4%0A&debug=0&input_size=2)
### Or also 10 bytes
```
hSeCSR.:EE
```
Explanation:
```
.:EE - sublists(Q, eval(input())) - all sublists of Q of length num
SR - map(sorted, ^)
eC - transpose(^)[-1]
hS - sorted(^)[0]
```
[Test Suite here](http://pyth.herokuapp.com/?code=hSeCSR.%3AEE&input=%5B1%2C+5%2C+3%2C+4%5D%0A2&test_suite_input=%5B5.4%2C+-3.4%2C+6.7%2C+8.8%2C+-1.2%5D%0A3%0A%5B-1%2C+2%2C+-3%2C+4%2C+-5%5D%0A2%0A%5B-1%2C+2%2C+4%2C+-3%2C+-5%5D%0A2%0A%5B0.2%2C+4.5%2C+3.4%2C+2.3%5D%0A4%0A&debug=0&input_size=2)
[Answer]
# Jelly, 6 bytes
```
ṡ»/€«/
```
[Try it online!](http://jelly.tryitonline.net/#code=4bmhwrsv4oKswqsv&input=&args=WzEsIDUsIDMsIDRd+Mg)
### How it works
```
ṡ»/€«/ Main link. Left input: A (list). Right input: n (integer)
ṡ Split A into overlapping slices of length n.
»/€ Reduce each slice by maximum.
«/ Reduce the maxima by minimum.
```
[Answer]
# JavaScript (ES6), ~~84~~ ~~83~~ 72 bytes
```
(x,y)=>Math.min(...x.slice(y-1).map((a,i)=>Math.max(...x.slice(i,i+y))))
```
Thanks to user81655 for helping shave off 11 bytes
[Answer]
# [Perl 6](http://perl6.org), 32 bytes
```
{@^a.rotor($^b=>1-$b)».max.min}
```
### Usage:
```
my &minimax = {@^a.rotor($^b=>1-$b)».max.min}
say minimax [1,5,3,4], 2; # 4
say minimax [1,2,3,4,5], 3; # 3
say minimax [1,1,1,1,5], 4; # 1
say minimax [5,42,3,23], 3; # 42
```
[Answer]
# R, ~~41~~ 35 bytes
Requires zoo to be installed.
```
function(x,n)min(zoo::rollmax(x,n))
```
*edit* - 6 bytes by realizing `zoo::rollmax` exists!
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes
```
lvGg
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJsdkdnIiwiIiwiM1xuWzEsIDIsIDMsIDQsIDVdIl0=)
Why reduce by things when you can just vectorise.
## Explained
```
lvGg
l # overlaps of input list of size input integer.
vG # maximum of each window
g # minimum of that
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 4 bytes
```
▼m▲X
```
[Try it online!](https://tio.run/##yygtzv7//9G0PbmPpm2K@P//v/H/aEMdIx1jHRMd01gA "Husk – Try It Online")
### Explanation
```
▼m▲X
X each consecutive slice of length
m▲ maximum of each
▼ minimum
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
ṡṀ€Ṃ
```
[Try it online!](https://tio.run/##y0rNyan8///hzoUPdzY8alrzcGfT/8PLlSL//4821FEw1VEw1lEwidVRAPGMIDygMFQAjsACQMUmECVGxrH/4YqNAQ "Jelly – Try It Online")
Since [Dennis' answer](https://codegolf.stackexchange.com/a/73187/66833), the `Ṁ`aximum and `Ṃ`inimum monadic atoms have been added
[Answer]
# [Julia 0.6](http://julialang.org/), 51 bytes
```
f(x,n)=min([max(x[i-n+1:i]...)for i=n:endof(x)]...)
```
[Try it online!](https://tio.run/##bczBCoMwDAbgu08R8JIyJ9jWHQSfpHjosEJGjVK34dt37bw2uYQ/H//r48k@YlzwbFiMKzGa1Z54GrrzrRtoattWLFsAGnlwPG9Jin8Yc@qJHRBDcHbO94GigjS2ecII7ms97jYcDvNTXL89EL8944JJpSy1RtNBDwr01ICEwtS6SkRmAn1CqkBUJtdmogukq0wPOtdIVWyptfwB "Julia 0.6 – Try It Online")
Nothing too groundbreaking. This is a function that accepts an array and an integer and returns an integer. It just uses the basic algorithm. It would be a whole lot shorter if `min` and `max` didn't require splatting arrays into arguments.
We get each overlapping subarray, take the max, and take the min of the result.
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 6 bytes
```
YCX>X<
```
[**Try it online!**](http://matl.tryitonline.net/#code=WUNYPlg8&input=WzUgNDIgMyAyM10KMw)
```
YC % Implicitly input array and number. Build a matrix with columns formed
% by sliding blocks of the array with size given by the number
X> % Maximum of each column
X< % Minimum of all maxima. Implicitly display
```
[Answer]
# Python 3, 55 bytes.
```
lambda x,n:min(max(x[b:b+n])for b in range(len(x)-n+1))
```
Test cases:
```
assert f([1, 5, 3, 4], 2) == 4
assert f([1, 2, 3, 4, 5], 3) == 3
assert f([1, 1, 1, 1, 5], 4) == 1
assert f([5, 42, 3, 23], 3 ) == 42
```
[Answer]
## Python 2, 50 bytes
```
f=lambda l,n:l[n-1:]and min(max(l[:n]),f(l[1:],n))
```
Recursively computes the minimum of two things: the max of the first `n` entries, and the recursive function on the list with first element removed. For a base case of the list having fewer than `n` elements, gives the empty list, which serves as infinity because Python 2 puts lists as greater than numbers.
[Answer]
# Mathematica, 23 bytes
```
Min@BlockMap[Max,##,1]&
```
**Test case**
```
%[{1,2,3,4,5},3]
(* 3 *)
```
[Answer]
# J, 9 bytes
```
[:<./>./\
```
Similar to the APL answer. `>./\` applies `>./` (maximum) to the (left arg)-subsets of the right arg. Then, `<./` finds the minimum of that, since it's capped with `[:`.
## Test cases
```
f =: [:<./>./\
2 f 1 5 3 4
4
3 f 1 2 3 4 5
3
3 f 1 1 1 1 5
1
3 f 5 42 3 23
42
```
[Answer]
# [Factor](https://factorcode.org/), 34 bytes
```
[ clump [ supremum ] map infimum ]
```
[Try it online!](https://tio.run/##Vc49DsIwDAXgvad4FwCJNl3gAIiFBTFVDFHklojmhzgZUNWzl7RlKH6TP9myW6miC9P9drmej@iCS17bDkzvRFYRQzI7xXhRsNTDB4rx44O2EaeiGArkGnIOqFFBYESJcaPlonX26s/XzC42XkPMC2X1mx@nBqpPxqMBp3zcJIMHjPTQttVLl0f22ZQz3jGt/@5Iquf0BQ "Factor – Try It Online")
## Explanation
```
! { 1 5 3 4 } 2
clump ! { { 1 5 } { 5 3 } { 3 4 } }
[ supremum ] map ! { 5 5 4 }
infimum ! 4
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ŒIù€àß
```
[Try it online](https://tio.run/##yy9OTMpM/f//6CTPwzsfNa05vODw/P//ow11THWMdUxiuYwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVC6P@jkyIO73zUtObwgsPz/@v8j46ONtQx1THWMYnVMYrVUQBxjUBcHdNYHWOoAAQCBUzAAqY6JiAlRsYgFbEA).
**Explanation:**
```
Œ # Get all sublists of the (implicit) input-list
Iù # Only keep those of a size equal to the second input
ۈ # Get the maximum of each inner list
ß # Pop and push the minimum of that
# (after which the result is output implicitly)
```
[Answer]
# Java 8, ~~128~~ ~~126~~ ~~124~~ 105 bytes
```
a->n->{int r=0,m,j,t,i=-1;for(;i++<a.length-n;r=r<1|m<r?m:r)for(m=j=0;j<n;m=t>m?t:m)t=a[i+j++];return r;}
```
[Try it online.](https://tio.run/##lY89b4NADIZ3foVHEMcpH7DkOLJV6tApY8RwTSC5K2fQYVJFKb@dQotaqUMl5MXS68f2Y9RNReb8Npwq1bbwojQ@PICWFOkTmDHlHemKlx2eSNfIn@Ym1UjHnP078oxUXArHYG6yDEqQg4oyjLLHuACcXDHLDCOmZbQWZe18ocMwVbwq8ELXCIWTLl1/2NTt7c4F04SVRq6ESVFYSZnd084GJNVRhyYMc@EK6hyCE/0gvNGl6V6r0WVWutX6DHbU9A/kNF6OOahgUgY43FsqLK874s0YUYV@yVXTVHcfi3f4En6sWcK2LO6DOdkEgVhCbyaaJT/8diH/Xb98vIhPWDw9sNn@vd97/fAJ)
**Explanation:**
```
a->n->{ // Method with Integer-array & Integer as parameters
// and Integer return-type
int r=0, // Result-integer, starting at 0
m, // Max-integer, uninitialized
j,t, // Temp integers
i=-1;for(;i++<a.length-n // Loop `i` in the range (-1,length-n]:
; // After every iteration:
r= // Change the result to:
r<1 // If the result is 0 (first iteration),
|m<r? // or the max is smaller than the result:
m // Change the result to this max
: // Else:
r) // Keep it unchanged
for(m= // Reset the max to 0
j=0;j<n // Inner loop `j` in the range [0,n):
; // After every iteration:
m=t>m?t:m) // Set `m` to the max of `m` and `t`
t=a[i+j++]; // Set `t` to the `i+j`'th item of the array
return r;} // After the nested loops, return the result
```
[Answer]
# [Rust](https://www.rust-lang.org/), 46 bytes
```
|s,n|s.windows(n).map(|a|a.iter().max()).min()
```
[Try it online!](https://tio.run/##bY7LasMwEEX3@ooJCDNDVEP82CSNl9l20aUxRqQKiNhyKsmk1Pa3u1b6WiQSzGU0586V7Z2fTwZaqQ3SAM5Lr49w2J4MRmWfJpXonf5U9FS8XLzuzPOPRMusKGAP8@iEGV181eatuzo0FLfygqMcZay9shj6D6RFQsS8Y6082q62faPcagk@q9or5wfkWHLkctsEm2xoXQlufjtu/99pXwwcpXPK@lq9r/Cw/DVYSdw8JF67VuGtRNwS0Y7W08T@slYDKzeQQwpZJSCBBycLRBIIyBcmvSfSQHzfQGT3xIaVOWRhSZI@3JElbGLT/AU "Rust – Try It Online")
Takes in a `&[u32]` and returns an `Option<Option<&u32>>`. The result will be `Some(Some(&minimax))` so long as valid input is supplied.
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 7 bytes
```
CO)>]<]
```
[Try it online!](https://tio.run/##SyotykktLixN/V9dkPrf2V/TLtYm9n9pQW15TnHG/2pDBVMFYwWTWgUjLiDbCMRWMK1VMAbxIBDIM@GqNlUwAUkaGQPlAA "Burlesque – Try It Online")
```
CO # Sliding window length N
)>] # Map max of block
<] # Min of result
```
[Answer]
# [Julia 1.0](http://julialang.org/), 48 bytes
```
x\n=minimum(n:length(x).|>i->max(x[i-n+1:i]...))
```
[Try it online!](https://tio.run/##bcw7DoMwEATQnlOsRGMrYAlsGiS4QU4AFEY4yUb2BvGJXOTuDhYtM80UT/PeLerCh@B7ahwSut0xqq2h5/Zinotfi3nrtGe@w5xuRY2DEILz8PgsYJEMIMFi9BT3yngCR3Q2QgPmqy27m02LWS@rYVHwE8wL0maJ6X7kiaEpdAVUIEENGZRwkVQlBykjgepA8oLISM5Goi5IkXQVqHhTysuXVJV/ "Julia 1.0 – Try It Online")
based on [Alex A.](https://codegolf.stackexchange.com/users/20469)'s [answer](https://codegolf.stackexchange.com/a/73214/98541)
[Answer]
# JavaScript (ES6), 70 bytes
```
x=>n=>-M(...x.slice(n-1).map((_,i)=>-M(...x.slice(i,i+n)))),M=Math.max
```
Using [currying](https://codegolf.meta.stackexchange.com/a/8427/42091), this function saves 2 bytes from the previous answer.
## Demo
```
f=x=>n=>-M(...x.slice(n-1).map((_,i)=>-M(...x.slice(i,i+n)))),M=Math.max
a=[[[1,5,3,4],2,4],[[1,2,3,4,5],3,3],[[1,1,1,1,5],4,1],[[5,42,3,23],3,42]]
document.write(`<pre>${a.map(r=>`${f(r[0])(r[1])==r[2]?'PASS':'FAIL'} ${r[1]}=>${r[2]}`).join`\n`}`)
```
[Answer]
## Racket 84 bytes
```
(λ(l i)(apply min(for/list((j(-(length l)(- i 1))))(apply max(take(drop l j) i)))))
```
Ungolfed:
```
(define f
(λ (l i)
(apply min (for/list ((j (- (length l)
(- i 1))))
(apply max (take (drop l j) i))
))))
```
Testing:
```
(f '[1 5 3 4] 2)
(f '[1 2 3 4 5] 3)
(f '[5 42 3 23] 3)
```
Output:
```
4
3
42
```
[Answer]
## Clojure, 51 bytes
```
#(apply min(for[p(partition %2 1 %)](apply max p)))
```
[Answer]
# SmileBASIC, 68 bytes
```
M=MAX(X)DIM T[N]FOR I=.TO LEN(X)-N-1COPY T,X,I,N
M=MIN(M,MAX(T))NEXT
```
Nothing special here. Inputs are `X[]` and `N`
[Answer]
# T-SQL, 131 bytes
```
SELECT top 1max(iif(a<c,c,a))FROM x y
CROSS APPLY(SELECT a c FROM x WHERE y.b<b and b<y.b+@)z
GROUP BY b
HAVING-@=~sum(1)ORDER BY 1
```
**[Try it online](https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=0f7bbe3af379290485c5f3281d7532d4)**
[Answer]
# [R](https://www.r-project.org/), 64 bytes
```
function(x,n)min(apply(matrix(x,l<-sum(x|1)+1,n)[n:l-n,],1,max))
```
[Try it online!](https://tio.run/##DcpLCoAgEADQq7ScoXFhn014k2ghgiDoJKYwQXc3t49Xup@M6r6xq@FmEGJMgcHmHF9ItpYgA6NRT0sgn8ZZj3LyERXTRZqSFcTuwYGmnVbakBbsPw "R – Try It Online")
Answer without using `zoo`.
] |
[Question]
[
Print the dates of all the Sundays in 2017 in the following format : `dd.mm.yyyy`.
Expected Output:
```
01.01.2017
08.01.2017
15.01.2017
22.01.2017
29.01.2017
05.02.2017
12.02.2017
19.02.2017
26.02.2017
05.03.2017
12.03.2017
19.03.2017
26.03.2017
02.04.2017
09.04.2017
16.04.2017
23.04.2017
30.04.2017
07.05.2017
14.05.2017
21.05.2017
28.05.2017
04.06.2017
11.06.2017
18.06.2017
25.06.2017
02.07.2017
09.07.2017
16.07.2017
23.07.2017
30.07.2017
06.08.2017
13.08.2017
20.08.2017
27.08.2017
03.09.2017
10.09.2017
17.09.2017
24.09.2017
01.10.2017
08.10.2017
15.10.2017
22.10.2017
29.10.2017
05.11.2017
12.11.2017
19.11.2017
26.11.2017
03.12.2017
10.12.2017
17.12.2017
24.12.2017
31.12.2017
```
[Answer]
# [Python 2](https://docs.python.org/2/), 81 bytes
```
x=0
exec"print'%05.2f.2017'%(x%30.99+1.01);x+=7+'0009ANW'.count(chr(x/7+40));"*53
```
[Try it online!](https://tio.run/nexus/python2#@19ha8CVWpGarFRQlJlXoq5qYKpnlKZnZGBorq6qUaFqbKBnaaltqGdgqGldoW1rrq1uYGBg6egXrq6XnF@aV6KRnFGkUaFvrm1ioKlpraRlavz/PwA "Python 2 – TIO Nexus")
No date libraries, computes the dates directly. The main trick is to treat the `dd.mm` as a decimal value. For example, `16.04.2017` (April 16) corresponds to the number `16.04`. The number is printed formatted as `xx.xx` with `.2017` appended.
The day and month are computed arithmetically. Each week adds 7 days done as `x+=7`. Taking `x` modulo `30.99` handles rollover by subtracting `30.99` whenever the day number gets too big. This combines `-31` to reset the days with `+0.01` to increment the month.
The rollover assumes each month has 31 days. Months with fewer days are adjusted for by nudging `x` upwards on certain week numbers with `+[8,8,8,17,25,38,47].count(x/7)`. These list is of the week numbers ending these short months, with `8` tripled because February is 3 days short of 31.
This list could is compressed into a string by taking ASCII values plus 40. The shift of `+40` could be avoided by using unprintable chars, and could be accessed shorter as a bytes object in Python 3.
[Answer]
# PHP, 48 bytes
```
while($t<53)echo gmdate("d.m.2017
",605e3*$t++);
```
### PHP, 46 bytes (for non-negative UTC offsets)
```
while($t<53)echo date("d.m.2017
",605e3*$t++);
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~90~~ 79 bytes
-5 bytes with the help of xnor (avoid counting the weeks themselves)
-1 byte thanks to xnor (add back in e for 605000 as 605e3)
```
from time import*
i=0
exec"print strftime('%d.%m.2017',gmtime(i));i+=605e3;"*53
```
**[Try it online!](https://tio.run/nexus/python2#@59WlJ@rUJKZm6qQmVuQX1SixZVpa8CVWpGarFRQlJlXolBcUpQGktdQV03RU83VMzIwNFfXSc8Fi2VqalpnatuaGZimGlsraZka//8PAA)**
`0` seconds since epoch is 00:00:00 on the 1st of January 1970, which, like 2017 was not a leap year. `605000` seconds is 1 week, 3 minutes, 20 seconds. Adding 52 of these "weeks" does not take us beyond midnight.
[Answer]
# Bash + coreutils, 44 bytes
```
seq -f@%f 0 605e3 32e6|date -uf- +%d.%m.2017
```
may save 2 bytes `-u` if GMT is assumed
* Thanks [Digital Trauma](https://codegolf.stackexchange.com/users/11259/digital-trauma) point out `-f` paramter for `date` which saves 10 bytes;
* And use 2017 in format string saves more bytes which idea is from [the answer](https://codegolf.stackexchange.com/a/116324/44718) given by [user63956](https://codegolf.stackexchange.com/users/63956/user63956)
---
* `@0` is 1970-1-1
* `605000` is one week (`604800`) plus 200 sec
+ 200 sec. should just work since there are only 52 weeks in a year
* `@32000000` is just a little more than a year
[Answer]
# PowerShell, ~~51~~ 47
```
0..52|%{date((date 2017-1-1)+7.*$_)-u %d.%m.%Y}
```
Fairly straightforward. 2017-01-01 is a Sunday, so is every following seven days. We can save two bytes if we only need the script to be working in my lifetime:
```
0..52|%{date((date 17-1-1)+7.*$_)-u %d.%m.%Y}
```
[Answer]
Excel VBA ~~106~~ ~~91~~ ~~79 bytes~~
```
Sub p()
For i = #1/1/2017# To #12/31/2017#
If Weekday(i) = 1 Then MsgBox i
Next
End Sub
```
saved 15 bytes thanks to @Radhato
Assuming 1/1/2017 is Sunday it will save 12 more bytes.
```
Sub p()
For i = #1/1/2017# To #12/31/2017#
MsgBox i
i = i + 6
Next
End Sub
```
Thanks @Toothbrush **66 bytes**
```
Sub p:For i=#1/1/2017# To #12/31/2017#:MsgBox i:i=i+6:Next:End Sub
```
Edit: (Sub and End Sub is not necessary) **52 bytes**
```
For i=#1/1/2017# To #12/31/2017#:MsgBox i:i=i+6:Next
```
[Answer]
# PHP, 67 bytes
Using the fact the PHP automatically assign value 1 to undeclared loop variables, and using Linux epoch times,
```
<?php for(;54>$t+=1;)echo date("d.m.Y\n",604800*($t)+1482624000);?>
```
[Answer]
# k6, 32 bytes
```
`0:("."/|"."\)'$2017.01.01+7*!53
```
Brief explanation:
```
2017.01.01+7*!53 /add 0, 7, 14, ..., 364 to January 1st
("."/|"."\)'$ /convert to string, turn Y.m.d into d.m.Y
/ split by ".", reverse, join by "."
`0: /output to stdout (or stderr), line by line
```
Alas, this seems to only work in the closed-source, on-request-only interpreter.
[](https://i.stack.imgur.com/Tft4C.png)
[Answer]
# [Pyke](https://github.com/muddyfish/PYKE), ~~26~~ 24 bytes
```
53 Fy17y"RVs6)c"%d.%m.%Y
```
[Try it online!](https://tio.run/nexus/pyke#@29qrOBWaWheqRQUVmymmaykmqKnmqunGvn/PwA "Pyke – TIO Nexus")
```
53 F - for i in range(53):, printing a newline between each
y17y" - Create a time object with the year 2017. (Month and days are initialised to 1.)
RV ) - Repeat i times:
s6 - Add 1 week
c"%d.%m.%Y - Format in "dd.mm.yyyy" time
```
### Or 11 bytes
If allowed to ignore output format
```
y17y"52VDs6
```
[Try it online!](https://tio.run/nexus/pyke#@19paF6pZGoc5qKkmqKnmqunGqmUzOVdbKbp/f8/AA "Pyke – TIO Nexus")
```
y17y" - Create a time object with the year 2017. (Month and days are initialised to 1.)
52V - Repeat 52 times:
D - Duplicate the old time
s6 - Add 1 week
```
[Answer]
## R, ~~79~~ ~~67~~ 58 bytes
```
cat(format(seq(as.Date("2017/01/01"),,7,53),"\n%d.%m.%Y"))
```
First of January being a sunday, this snippet creates a sequence of days, every 7 days starting from the 01-01-2017 to the 31-12-2017, format them to the desired format and print them.
[Answer]
# [Befunge-98 (PyFunge)](https://pythonhosted.org/PyFunge/), ~~99~~ ~~95~~ ~~93~~ 85 bytes, Leaves trailing newline
All the optimizations were made by @JoKing many thanks to them
```
s :1g2/10g\%:d1p10g\`+:b`#@_:1\0d1g#;1+:a/'0+,a%'0+,'.,j;a"7102"4k,d1g7+
>8><><>><><>
```
[Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//8vVrAyTDfSNzRIj1G1SjEsADEStK2SEpQd4q0MYwxSDNOVrQ21rRL11Q20dRJVQaS6nk6WdaKSuaGBkZJJtg5Qibk2l52FnQ0Qgon//wE "Befunge-98 (PyFunge) – Try It Online")
I felt like we were missing out on some esostericity here so I made a solution in my favourite Esosteric language.
**Explanation**:
`>8><><>><><>` Encodes the length of the 12 months
`s` Store the old day in the blank space
[Answer]
## JavaScript, ~~111~~ 106 bytes
```
for(i=14833e8;i<1515e9;i+=605e6)console.log(new Date(i).toJSON().replace(/(....).(..).(..).*/,'$3.$2.$1'))
```
Note: Stack Exchange's console isn't long enough to display the entire list, so here's the first half as a separate snippet:
```
for(i=14833e8;i<15e11;i+=605e6)console.log(new Date(i).toJSON().replace(/(....).(..).(..).*/,'$3.$2.$1'))
```
The custom format costs me 40 bytes...
[Answer]
# [Perl 5](https://www.perl.org/), 64 bytes
```
use POSIX;print strftime"%d.%m.%Y\n",0,0,0,7*$_+1,0,117for 0..52
```
[Try it online!](https://tio.run/nexus/perl5#@19anKoQ4B/sGWFdUJSZV6JQXFKUVpKZm6qkmqKnmqunGhmTp6RjAIbmWirx2oZAhqGheVp@kYKBnp6p0f//AA "Perl 5 – TIO Nexus")
The task given was 2017, not any year, so I hardcoded in:
* 117 (which is perlish for year 2017, 1900+117)
* +1 because 1st of January is a sunday in 2017
* 0..52 because 2017 have 53 sundays
POSIX is a core module and is always installed with Perl5. Doing the same without using modules in 101 bytes, removing whitespace:
```
$$_[5]==117&&printf"%02d.%02d.%d\n",$$_[3],$$_[4]+1,$$_[5]+1900
for map[gmtime(($_*7+3)*86400)],0..1e4
```
[Answer]
# Ruby, 75 bytes
Straightforward solution to figure out the dates with `Time`.
```
t=Time.new 2017
365.times{puts t.strftime("%d.%m.%Y")if t.sunday?
t+=86400}
```
[Answer]
## SAS, ~~52~~ 50 bytes
Saved 2 bytes thanks to @user3490.
```
data;do i=20820to 21184 by 7;put i ddmmyyp10.;end;
```
[Answer]
# Mathematica ~~90~~ 84 bytes
Fairly wordy. numbermaniac and Scott Milner saved 5 and 1 bytes, respectively.
```
Column[#~DateString~{"Day",".","Month",".","Year"}&/@DayRange["2017","2018",Sunday]]
```
[Answer]
# VBA, 81 bytes (maybe 64)
```
Sub p()
For i = 0 To 52
MsgBox format(42736 + i * 7, "dd.mm.yyyy")
Next i
End Sub
```
My first post. Building on newguy's solution by removing the check for weekdays and just specifying every 7th day. Removing the dates saves 12 bytes a piece. 42736 is 1/1/2017.
Output date format depends on system setting. Is that allowed?
If so, it's 64 bytes because you don't need the *format* method.
```
MsgBox #1/1/2017# + i * 7
```
[Answer]
# [AHK](https://autohotkey.com/), 67 bytes
```
d=20170101
Loop,52{
FormatTime,p,%d%,dd.MM.yyyy
Send,%p%`n
d+=7,d
}
```
Nothing magical happens here. I tried to find a shorter means than `FormatTime`
but I failed.
[Answer]
# Java 8+, ~~104~~ ~~100~~ 99 bytes
```
()->{for(int t=0;t<53;)System.out.printf("%1$td.%1$tm.2017%n",new java.util.Date(t++*604800000L));}
```
# Java 5+, ~~109~~ ~~105~~ 104 bytes
```
void f(){for(int t=0;t<53;)System.out.printf("%1$td.%1$tm.2017%n",new java.util.Date(t++*604800000L));}
```
Uses the date-capabilities of the `printf` format.
[Test it yourself!](http://ideone.com/fZxAYV)
## Savings
1. 104 -> 100: changed the loop values and the multiplicand.
2. 100 -> 99: golfed the loop
[Answer]
# T-SQL, 94 Bytes
```
DECLARE @ INT=0,@_ DATETIME='2017'W:SET @+=1SET @_+=7PRINT FORMAT(@_,'dd.MM.yyy')IF @<52GOTO W
```
if you don't like SQL GOTO or WHILE, here is a 122 bytes CTE solution
```
WITH C AS(SELECT CAST('2017'AS DATETIME)x UNION ALL SELECT x+7FROM C WHERE X<'12-31-17')SELECT FORMAT(x,'dd.MM.yyy')FROM C
```
[Answer]
# Ruby, 60+7 = 67 bytes
Uses the `-rdate` flag.
```
(d=Date.new 1).step(d+365,7){|d|puts d.strftime"%d.%m.2017"}
```
[Answer]
# Groovy, ~~81~~ ~~77~~ ~~63~~ ~~60~~ 56 bytes
```
d=new Date(0);53.times{printf('%td.%<tm.2017%n',d);d+=7}
```
The above can be run as groovy script.
My first code golf entry.
Fortunately, the year 1970 was not a leap year, thus can use it as a base.
Thanks to Dennis, here's a:
[Try it online!](https://tio.run/nexus/groovy#@59im5daruCSWJKqYaBpbWqsV5KZm1pcXVCUmVeSpqGuWpKip2pTkqtnZGBorpqnrpOiaZ2ibWte@/8/AA)
[Answer]
# C#, 138 111 102 bytes
*Saved 9 more bytes thanks to [Johan du Toit](https://codegolf.stackexchange.com/users/41374/johan-du-toit)!*
*Saved 27 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)'s suggestions!*
```
()=>{for(int i=0;i<53;)Console.Write(new DateTime(2017,1,1).AddDays(7*i++).ToString("dd.MM.yyyy\n"));}
```
Anonymous function which prints all Sundays in 2017.
Full program with ungolfed method:
```
using System;
class P
{
static void Main()
{
Action f =
()=>
{
for (int i = 0; i < 53; )
Console.Write(new DateTime(2017, 1, 1).AddDays(7 * i++).ToString("dd.MM.yyyy\n"));
};
f();
}
}
```
[Answer]
# C#, ~~110~~ 109 bytes
```
using System;()=>{for(int i=42729;i<43100;Console.Write(DateTime.FromOADate(i+=7).ToString("dd.MM.yyy\n")));}
```
[You can enjoy this program online here](https://dotnetfiddle.net/YVlOls)
In this soluion we :
* Use OLE Automation Date (OADate) to avoid "AddDay()" from datetime.
`FromOADate()` seem big but it's equal to `new DateTime(2017,1,1)`
* Start the loop on the last sunday of 2016. to allow us to increment with operator `+=` only. This operator return the value after the increment is done.
* Increment by 7 days to jump from sunday to sunday before printing the date.
* We stop once the last sunday of 2017 has been hit.
* ~~Use `Debug` instead of `Console` to save two characters~~
* Avoid having explicit variable declaration and assignment
[Answer]
# TSQL, ~~112~~ 105 bytes
```
SELECT CONVERT(VARCHAR,DATEADD(d,number*7,42734),104)FROM master..spt_values WHERE type='p' AND number<53
```
[Demo](http://rextester.com/LSYHK15612)
[T-SQL Convert Syntax](https://technet.microsoft.com/en-us/library/ms187928(v=sql.100).aspx)
[Answer]
# JavaScript (ES6), 123 bytes
It's my first post here, hello!
```
a=x=>`0${x}.`.slice(-3);[].map.call('155274263153',(x,i)=>{for(j=0;j<4+(2633>>i&1);j++)console.log(a(+x+j*7)+a(i+1)+2017)})
```
This solution uses hardcoded data and is designed to work specifically for the year 2017. It relies on no date/time APIs.
As for the digits in the string `155274263153`, each digit is a number of its own and denotes the first Sunday of each consecutive month. Output for the entire year can be generated by successively adding 7 to those.
What about the magic number, `2633`, used in the loop?
Well... `2633` (decimal) is `101001001001` in binary. Now what could those `1`s mean? Starting from the right, the 1st, 4th, 7th, 10th and 12th bit are set. This corresponds to months which happen to have five Sundays, as opposed to those that have only four. Golfed down to this neat expression, it initially looked like this: `for(j=0;j<4+ +[0,3,6,9,11].includes(i);j++)`.
I guess the remaining parts are fairly self-explanatory.
[Answer]
# T-SQL, ~~79~~ 77 Bytes
After helping Salman A improve [his answer](https://codegolf.stackexchange.com/a/116469/45600). I decided to write my own using a loop and `PRINT`.
I ended with this 90 bytes solution.
```
DECLARE @d DATETIME=42734 WHILE @d<43100BEGIN PRINT CONVERT(VARCHAR,@d,104)SET @d=@d+7 END
```
Then I looked at the current leader in T-SQL which was 94 bytes from WORNG ALL with [this answer](https://codegolf.stackexchange.com/a/116409/45600).
This guy had found very good tricks.
1. Name the variable only `@`
2. Loop with `GOTO` instead of actual LOOP
3. Save one character using `FORMAT` instead of `CONVERT`. (SSMS2012+ only)
Using these tricks, this solution was trimmed down to the solution below which is 79 bytes.
```
DECLARE @ DATETIME=42734G:PRINT FORMAT(@,'dd.MM.yyy')SET @+=7IF @<43100GOTO G
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 37 bytes
A lot shorter than all other non-golfing languages, and it's even tied with Jelly! Way to go Octave! :)
```
disp(datestr(367:7:737,'DD.mm.2017'))
```
[Try it online!](https://tio.run/##y08uSSxL/f8/JbO4QCMlsSS1uKRIw9jM3AoIjc111F1c9HJz9YwMDM3VNTX//wcA "Octave – Try It Online")
Luckily, year `2 AD` looks exactly the same as year `2017 AD`. Both starts and ends at a Sunday, and neither is a leap year. This saves a lot of bytes, since `367:7:737` is quite a bit shorter than `736696:7:737060`.
This converts the number of days since `01.01.0001`, to a string on the format `DD.mm`, with a trailing `.2017`.
[Answer]
# [Haskell](https://www.haskell.org/), ~~133~~ 130 bytes
```
import Data.Time.Calendar
((\[f,g,h,i,j]->i:j:'.':f:g:".2017\n").drop 5.show)=<<take 53(iterate(addDays 7)$fromGregorian 2017 1 1)
```
[Try it online!](https://tio.run/##FczRCoIwFADQ977iIoEbrJGFCEN7SegD6i17uODUqdvkbhF9/aLzAWfCsOh1TcnYzVOEFiPKh7FaXnHVrkfahYax7jmIUUzCiPl1uBg1q1zmalCjyuTpWFSdy7jsyW9QyjD5D2/qOuKioTwzEzVh1Az7vsVvgIrvB/L2Rnr0ZNDBP4ACCp4sGtds73iPBCH9AA)
### Without a calendar library, ~~148~~ ~~144~~ 140 bytes
```
(\l->last l!l++length l!l++"2017\n").fst.span(>0).(<$>scanl((+).(+28))0[3,0,3,2,3,2,3,3,2,3,2]).(-)=<<[1,8..365]
a!_=['0'|a<=9]++show a++"."
```
This is funny since using an operator for the padding function saves two bytes even though the second argument is unused, because less parentheses are needed – `p(last l)` is longer than `last l!l`. Works by calculating `day/month` pairs by subtracting the cumulative month start dates from the day of the year. The month start dates are compressed as (`scanl((+).(+28))0[3,0,3,2,3,2,3,3,2,3,2]`). Month number is the number of positive elements and day number is the last positive element.
[Try it online!](https://tio.run/##LY3LCsIwEEX3fkUsQhOShrRFrdD0J1y2RYbShzjG4kTc@O3Ggl0cOIe7uBPQrUcMZJvAG0wqBPIMtygl9m7009@jzKTHxkVCD@Q1zeB4ZYTm5a6iDhxyLpeSWSGEqXNlVK6yldXaZU@ELcs6VYXW@WHfbmB7sXVs4g@U9tRKSdPjzWB501G4w9Uxy@aXP/sno/DtBoSRQtLN8w8)
[Answer]
## C#, 116 114 113 bytes
`for(long i=(long)636188256e9;i<636502857e9;i+=(long)605e10)Out.Write(new DateTime(i).ToString("dd.MM.yyyy\n"));`
Can be run in the interactive windows of Visual Studio (or any other C# REPL based on Roslyn)
Down to 113 bytes: thanks to Kevin Cruijssen.
] |
[Question]
[
A [triangular number](https://en.wikipedia.org/wiki/Triangular_number) is a number that is the sum of `n` natural numbers from 1 to `n`. For example `1 + 2 + 3 + 4 = 10` so `10` is a triangular number.
Given a positive integer (`0 < n <= 10000`) as input (can be taken as an integer, or as a string), return the smallest possible triangular number that can be added to the input to create another triangular number.
For example given input `26`, adding `10` results in `36`, which is also a triangular number. There are no triangular numbers smaller than `10` that can be added to `26` to create another triangular number, so `10` is the correct result in this case.
`0` is a triangular number, therefore if the input is itself a triangular number, the output should be `0`
## Testcases
Cases are given in the format `input -> output (resulting triangular number)`
```
0 -> 0 (0)
4 -> 6 (10)
5 -> 1 (6)
7 -> 3 (10)
8 -> 28 (36)
10 -> 0 (10)
24 -> 21 (45)
25 -> 3 (28)
26 -> 10 (36)
34 -> 21 (55)
10000 -> 153 (10153)
```
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so fewest bytes **in each language** wins!
[Answer]
# Java 8, 58 57 bytes
```
n->{int i=0,m=0;while(n!=0)n+=n<0?++i:--m;return-~i*i/2;}
```
[Online test suite](https://tio.run/##ZZBNU4MwEIbv/RUrJxCofGjtFLE3b556dDyksNS0sHQgRZwO/nVc6Ad0nEkOebJ599lsRSXsfI@0jXdtlIqyhHch6TgBkKSwSESE8NafewJYiVRPc9oAGQHThjevUgklI66EhCCEluzXY1cuQ8fKQif4/pIp6nQXOgaZIb04S9OUC9vOggLVoSD7V97LBy9o2mDCcftCVkLhJbbKZQwKS6V3mbV1Mqn3GCmMDRjs8nWJRYUxKyQ07V3rXhNg9VMqzKb5QU05nVRK@lAdXtNgCVq@02ABunZlGphDgQmaNTTqri4H4/wj3QCHdcriY/@M/1VfKe69@fgEYZys@6m8mQWucxbtietYcAMeLYDZGDwxcMfgmYE/BnMG3nxMPE7xbh75/4jHwf55kKb9Aw)
Thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis) for a 1-byte saving.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~13~~ 12 bytes
*1 byte removed using an idea (set intersection) from [Emigna's 05AB1E answer](https://codegolf.stackexchange.com/a/129043/36398)*
```
Q:qYstG-X&X<
```
[**Try it online!**](https://tio.run/##y00syfn/P9CqMLK4xF03Qi3C5v9/QwMgAAA "MATL – Try It Online")
### Explanation
Let `t(n) = 1 + 2 + ··· + n` denote the `n`-th triangular number.
The code exploits the fact that, given `n`, the solution is upper-bounded by `t(n-1)`. To see this, observe that `t(n-1) + n` equals `t(n)` and so it is a triangular number.
Consider input `8` as an example.
```
Q:q % Input n implicitly. Push [0 1 2 ... n]
% STACK: [0 1 2 3 4 5 6 7 8]
Ys % Cumulative sum
% STACK: [0 1 3 6 10 15 21 28 36]
t % Duplicate
% STACK: [0 1 3 6 10 15 21 28 36], [0 1 3 6 10 15 21 28 36]
G- % Subtract input, element-wise
% STACK: [0 1 3 6 10 15 21 28 36], [-8 -7 -5 -2 2 7 13 20 28]
X& % Set intersection
% STACK: 28
X< % Minimum of array (in case there are several solutions). Implicit display
% STACK: 28
```
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 83 bytes
```
n->{int m=0,a=n,b;for(;a-->0;)for(b=0;b<=n;)m=2*n+b*~b++==a*~a?a*a+a:m;return m/2;}
```
[Try it online!](https://tio.run/##LY9Na4NAEIbv@RVDQHB1tdZqW9xueiv00FOOIYdZP8JaHUXXlCDmr1tNchjmZT7eZ6bEM3pNm1OZ/c7toCqdQlph38MPaoJxA/Co9gbNks6NzqBeevbedJpOhyNgd@rZbRSgXPz8wejKLwZKjW7I/ybz9dBQyJm83ajJQC0DjpK4EkXT2QI9bxcItmolA6E@JAlWy9AhVzlX5bpSonPFT3TQxaQWXW6GjqB@CsU0r2Rx46/7qzslQPkfLPJwHMNX/hzwiMf8jb/zMOIvEQ/jid1PBthfepPXfjMYv11@MoW9teIsAau3aMuBOBQ@tm11sYmxO2farDHN/w "Java (OpenJDK 8) – Try It Online")
## Credits
* -3 bytes thanks to [ceilingcat](https://tio.run/##LY9Na4NAEIbv@RVDQHB1tdZqW9xueiv00FOOIYdZP8JaHUXXlCDmr1tNchjmZT7eZ6bEM3pNm1OZ/c7toCqdQlph38MPaoJxA/Co9gbNks6NzqBeevbedJpOhyNgd@rZbRSgXPz8wejKLwZKjW7I/ybz9dBQyJm83ajJQC0DjpK4EkXT2QI9bxcItmolA6E@JAlWy9AhVzlX5bpSonPFT3TQxaQWXW6GjqB@CsU0r2Rx46/7qzslQPkfLPJwHMNX/hzwiMf8jb/zMOIvEQ/jid1PBthfepPXfjMYv11@MoW9teIsAau3aMuBOBQ@tm11sYmxO2farDHN/w)
[Answer]
# Mathematica, 46 bytes
```
Min[Select[(d=Divisors[2#])-2#/d,OddQ]^2-1]/8&
```
[Answer]
# [Neim](https://github.com/okx-code/Neim), ~~12~~ 9 bytes
```
tSùïäŒõtùïö)0ùïî
```
This takes too long to compute (but works given infinite time and memory), so in the link I only generate the first 143 triangular numbers - using `¬£ùïñ`, which is enough to handle an input of 10,000, but not enough to time out.
Warning: this may not work in future versions. If so, substitute £ for 143
Explanation:
```
t Infinite list of triangular numbers
[ ùïñ] Select the first v numbers
[£ ] 143
Sùïä Subtract the input from each element
Λ ) Only keep elements that are
tùïö triangular
0ùïî Get the value closest to 0 - prioritising the higher number if tie
```
[Try it!](http://178.62.56.56:80/neim?code=t%C2%A3%F0%9D%95%96S%F0%9D%95%8A%CE%9Bt%F0%9D%95%9A)0%F0%9D%95%94&input=10000)
[Answer]
# [PHP](https://php.net/), 45 bytes
```
for(;!$$t;$t+=++$i)${$argn+$t}=~+$t;echo~$$t;
```
[Try it online!](https://tio.run/##K8go@G9jX5BRoMClkliUnmerZGyiZP0/Lb9Iw1pRRaXEWqVE21ZbWyVTU6UarEBbpaTWtg5IWqcmZ@TXgZT8/w8A "PHP – Try It Online")
Is the shorter variant of `for(;!$r[$t];$t+=++$i)$r[$argn+$t]=~+$t;echo~$r[$t];`
Expanded
```
for(;!$$t; # stop if a triangular number exists where input plus triangular number is a triangular number
$t+=++$i) # make the next triangular number
${$argn+$t}=~+$t; # build variable $4,$5,$7,$10,... for input 4
echo~$$t; # Output result
```
# [PHP](https://php.net/), 53 bytes
```
for(;$d=$t<=>$n+$argn;)~$d?$n+=++$k:$t+=++$i;echo+$n;
```
[Try it online!](https://tio.run/##K8go@G9jX5BRoMClkliUnmerZGSiZP0/Lb9Iw1olxValxMbWTiVPGyxnrVmnkmIP5Nlqa6tkW6mUgBmZ1qnJGfnaKnnW//8DAA "PHP – Try It Online")
Use the new [spaceship operator](http://php.net/manual/en/language.operators.comparison.php) in PHP 7
Expanded
```
for(;$d=$t<=>$n+$argn;) # stop if triangular number is equal to input plus triangular number
~$d
?$n+=++$k # raise additional triangular number
:$t+=++$i; # raise triangular number sum
echo+$n; # Output and cast variable to integer in case of zero
```
# [PHP](https://php.net/), 55 bytes
```
for(;fmod(sqrt(8*($t+$argn)+1),2)!=1;)$t+=++$i;echo+$t;
```
[Try it online!](https://tio.run/##K8go@G9jX5BRoMClkliUnmerZGyiZP0/Lb9IwzotNz9Fo7iwqETDQktDpUQbrEBT21BTx0hT0dbQWhMoZqutrZJpnZqcka@tUmL9/z8A "PHP – Try It Online")
[Answer]
# Java 8, ~~110~~ ~~102~~ ~~100~~ ~~93~~ 92 bytes
```
n->{int r=0;for(;t(r)<-t(n+r);r++);return r;}int t(int n){for(int j=0;n>0;n-=++j);return n;}
```
-2 bytes thanks to *@PeterTaylor*.
-7 bytes thanks to *@JollyJoker*.
-1 byte thanks to *@ceilingcat*.
**Explanation:**
[Try it online.](https://tio.run/##hY7NbsMgDIDvfQofQShRl/1KLH2D9tLjtAOjtCJLnIg4raaIZ89MVu2KhA22P6OvMVdT9IPD5vS92NaMI@yNx3kD4JFcOBvr4JDKtQFWpIxScydy8DkAQg0LFrs5zUK91ec@CE0iyPeCBKogdVCKk6MpIAQddSLp/tec8PRseBV3HEWtVPPPo44LwDB9td7CSIb4uvb@BB2biiMFj5ePTzDyTzP5Q8dK6G5rIVZbgOPPSK4r@4nKgXeoRdGVWFpRvcgc8rDNIk9Z4jlLvGaJtyxR5UUe80h1l42buPwC)
```
n->{ // Method with integer as parameter and return-type
int r=0; // Result-integer (starting at 0)
for(;t(r)<-t(n+r); // Loop as long as neither `r` nor `n+r` is a triangular number
r++); // And increase `r` by 1 after every iteration
return r;} // Return the result of the loop
int t(int n){ // Separate method with integer as parameter and return-type
// This method will return 0 if the input is a triangular number
for(int i=0;n>0;) // Loop as long as the input `n` is larger than 0
n-=++j; // Decrease `n` by `j` every iteration, after we've raised `j` by 1
return n;} // Return `n`, which is now either 0 or below 0
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~17~~ 15 bytes
```
⟦{a₀+}ᶠ⊇Ċ-ṅ?∧Ċh
```
[Try it online!](https://tio.run/##AS8A0P9icmFjaHlsb2cy///in6Z7YeKCgCt94bag4oqHxIot4bmFP@KIp8SKaP//MjX/Wg "Brachylog – Try It Online")
### Explanation
```
⟦ [0, …, Input]
{ }ᶠ Find all…
a₀+ …Sums of prefixes (i.e. triangular numbers)
⊇Ċ Take an ordered subset of two elements
-·πÖ? Subtracting those elements results in -(Input)
∧Ċh Output is the first element of that subset
```
[Answer]
# [Python 2](https://docs.python.org/2/), 59 bytes
```
lambda n:min((r-2*n/r)**2/8for r in range(1,2*n,2)if n%r<1)
```
[Try it online!](https://tio.run/##FYpBDsIwDATP8ApfkJJiVGIKVBW8BDgEQUok6laWL7w@OHtZaWaWn35mppKu9/KN0/MVgYcps3Oyo4Zb8U1DbZ9mAYHMIJHHtwtoDsnnBLyRS/ClBlqDW0AghANCh3BEOCP0CGFv1AAZoZPprjLbY1ivFsmsTjE59ajber78AQ "Python 2 – Try It Online")
This uses the following characterization of the triangular numbers `t` than can be added to `n` to get a triangular number:
>
> `8*t+1 = (r-2*s)^2` for divisor pairs `(r,s)` with `r*s==n` and `r` odd.
>
>
>
The code takes the minimum of all such triangular numbers.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
0r+\√∞f_·∏¢
```
[Try it online!](https://tio.run/##y0rNyan8/9@gSDvm8Ia0@Ic7Fv0/uudw@6OmNe7//5voKJjqKJjrKFjoKBga6CgYAQWMgCJGZjoKxiYgMSAAAA "Jelly – Try It Online")
### How it works
```
0r+\√∞f_·∏¢ Main link. Argument: n
0r Build [0, ..., n].
+\ Take the cumulative sum, generating A := [T(0), ..., T(n)].
√∞ Begin a dyadic chain with left argument A and right argument n.
_ Compute A - n, i.e., subtract n from each number in A.
f Filter; keep only numbers of A that appear in A - n.
·∏¢ Head; take the first result.
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~38~~ 36 bytes
*2 bytes off thanks to [@Giuseppe!](https://codegolf.stackexchange.com/users/67312/giuseppe)*
```
@(n)(x=cumsum(0:n))(any(x+n==x'))(1)
```
Anonymous function that uses almost the same approach as my [MATL answer](https://codegolf.stackexchange.com/a/129022/36398).
[**Try it online!**](https://tio.run/##y08uSSxL/f/fQSNPU6PCNrk0t7g0V8PAKk9TUyMxr1KjQjvP1rZCHcgz1PyfpmCrkJhXbM2VpmFkpqmjkKZhaACmTMCkKZg0B5MWYNIIImEMoYxMNf8DAA)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~24~~ ~~23~~ ~~16~~ ~~15~~ 13 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ò å+
m-N √¶@√∏X
```
1 byte saved thanks to [ETH](https://codegolf.stackexchange.com/users/42545/ethproductions).
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=8iDlKwptLU4g5kD4WA&input=MTE3Nw)
```
ò å+\nm-N æ@øX :Implicit input of integer U
ò :Range [0,U]
å+ :Cumulatively reduce by addition
\n :Reassign to U
m- :Map and subtract
N : The array of inputs (i.e., the original value of U)
√¶ :Get the first element that return true when
@ :Passed through the following function as X
√∏X : Does U contain X
```
[Answer]
# [C (GCC)](https://gcc.gnu.org), ~~58 55 54~~ 52 bytes
```
i;s;f(n){for(i=s=0;n;)n+=n<0?++i:--s;return-~i*i/2;}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LY4xDoJAFERr_ilWjWZXRBFBjQtaaesFTIhZQH-CX8NCLIxexIaGa3gPbyOo003mTWaelQoPSpVlVeSJNX-7KLVMOIlbcs44BjqwJUlBZkC-vTJNXFiWllmcFxlZD-zjyJH3fzfsIKm0iGLm6zzC8_C4BEDK2WmPxAW7gdE4kmBcj5jGXKs9JbzdjdoD1iPBWgFbbzeCXbKa-wY7qqPmjpDwnylfNrjgwQzmMLbBccHxwJnCxK1trR_1AQ)
**EDIT**: *-3 bytes* by removing `!=0`
**EDIT**: *-1 byte* by moving variable declarations to a `for`
**EDIT**: *-2 bytes* by moving variable declarations outside the function, thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)
# Explanation
```
i;s;f(n){for(i=s=0;n;)n+=n<0?++i:--s;return-~i*i/2;}­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏⁠‎⁡⁠⁤⁡⁤‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁤⁢‏⁠‎⁡⁠⁤⁣‏⁠‎⁡⁠⁤⁤‏⁠‎⁡⁠⁢⁡⁡‏⁠‎⁡⁠⁢⁡⁢‏⁠‎⁡⁠⁢⁡⁣‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏⁠‎⁡⁠⁢⁡⁤‏⁠‎⁡⁠⁢⁢⁡‏⁠‎⁡⁠⁢⁢⁢‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁢⁢⁣‏⁠‎⁡⁠⁢⁢⁤‏⁠‎⁡⁠⁢⁣⁡‏⁠‎⁡⁠⁢⁣⁢‏⁠‎⁡⁠⁢⁣⁣‏⁠‎⁡⁠⁢⁣⁤‏⁠‎⁡⁠⁢⁤⁡‏⁠‎⁡⁠⁢⁤⁢‏⁠‎⁡⁠⁢⁤⁣‏⁠‎⁡⁠⁢⁤⁤‏⁠‎⁡⁠⁣⁡⁡‏⁠‎⁡⁠⁣⁡⁢‏⁠‎⁡⁠⁣⁡⁣‏⁠‎⁡⁠⁣⁡⁤‏⁠‎⁡⁠⁣⁢⁡‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁣⁢⁢‏⁠‎⁡⁠⁣⁢⁣‏⁠‎⁡⁠⁣⁢⁤‏⁠‎⁡⁠⁣⁣⁡‏⁠‎⁡⁠⁣⁣⁢‏⁠‎⁡⁠⁣⁣⁣‏⁠‎⁡⁠⁣⁣⁤‏⁠‎⁡⁠⁣⁤⁡‏⁠‎⁡⁠⁣⁤⁢‏⁠‎⁡⁠⁣⁤⁣‏⁠‎⁡⁠⁣⁤⁤‏⁠‎⁡⁠⁤⁡⁡‏⁠‎⁡⁠⁤⁡⁢‏⁠‎⁡⁠⁤⁡⁣‏‏​⁡⁠⁡‌­
i;s; // ‎⁡Declare i and s
f(n){ } // ‎⁢Declare function:
i=s=0; // ‎⁣* Set i and s to 0
for( n;) // ‎⁤* While n not 0:
n+=n<0?++i:--s; // ‎⁢⁡* * Increment i and add to n if n < 0
// ‎⁢⁡ Otherwise, decrement s and add to n
return-~i*i/2; // ‎⁢⁢* Return i*(i+1)/2
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes
```
ÝηOãD€Æ¹QϬ¤
```
Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##ASIA3f8wNWFiMWX//8OdzrdPw6NE4oKsw4bCuVHDj8KswqT//zI1 "05AB1E – Try It Online")
[Answer]
# Mathematica, 62 bytes
```
(s=Min@Abs[m/.Solve[2#==(n-m)(n+m+1),{n,m},Integers]])(s+1)/2&
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 [bytes](https://github.com/Adriandmen/05AB1E/blob/master/docs/code-page.md)
```
ÝηODI-Ãн
```
[Try it online!](https://tio.run/##MzBNTDJM/f//8Nxz2/1dPHUPN1/Y@/@/kQkA "05AB1E – Try It Online")
or as a [Test suite](https://tio.run/##ATkAxv8wNWFiMWX/fHZ5/8OdzrdPRHktw4PQvf95IsO/OiDDvyIs/zQKNQo3CjgKMTAKMjQKMjUKMjYKMzQ)
**Explanation**
```
√ù # range [0 ... input]
η # prefixes
O # sum each
D # duplicate
I- # subtract input from each
à # keep only the elements in the first list that also exist in the second list
–Ω # get the first (smallest)
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~78~~ ~~71~~ 70 bytes
Seven bytes saved, thanx to [ovs](https://codegolf.stackexchange.com/users/64121/ovs) and [theespinosa](https://codegolf.stackexchange.com/users/41804/theespinosa)
One more byte saved due to the remark of [neil](https://codegolf.stackexchange.com/users/17602/neil), `x+9` is suffisant and [checked](https://tio.run/##dY6xCsJAEET7@4qxkZwmeHudgfuA@wwLo1u4CUuKkxB/Pd5iIQhOOW8ezPSc76PEbcuUFjl0LznFYVQIWKAXuV2bc41fnbXl21IIgXwPh/xPLEfzoJQeLE2m/cJdgY3YRplWX2n80F9ojIcq75LG3gGTssworVKr9e8b) for all natural numbers `0 <= n <= 10000`. It was also [verified](https://tio.run/##dY6xCsJAEET7@4qxkZwmeHudgfuA@wwLo1u4CUuKkxB/Pe5hIQhOOW8ezPSc76PEbcuUFjl0LznFYVQIWKAXuV2bs8Wvrrbl21IIgXwPh/xPLEcyD0rpwdJk2i/cFdQR11Gm1RuNH/oLK@PB5F3S2DtgUpYZpVVq1f6@AQ) for `x+1` instead of `x+9`, it works also.
```
x=input()
I={n*-~n/2for n in range(x+1)}
print min(I&{i-x for i in I})
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v8I2M6@gtERDk8vTtjpPS7cuT98oLb9IIU8hM0@hKDEvPVWjQttQs5aroCgzr0QhNzNPw1OtOlO3QgGkKhOkyrNW8/9/IzMA "Python 2 – Try It Online")
[Answer]
## JavaScript (ES6), ~~43~~ 42 bytes
```
f=(n,a=s=0)=>n?f(n+=n>0?--s:++a,a):a*++a/2
```
```
<input type=number min=0 value=0 oninput=o.textContent=f(+this.value)><pre id=o>0
```
Edit: Saved 1 byte thanks to @PeterTaylor.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~60~~ 44 bytes
```
f=lambda n,k=1:(8*n+1)**.5%1and f(n+k,k+1)+k
```
*Thanks to @xnor for a suggestion that saved 16 bytes!*
[Try it online!](https://tio.run/##FYxBCoMwFETX9RR/E0z0V0ysrRXsXWytNER/JIkLT5/GgYGZNzDbEX6WmqjXzboA/vBZcuW/wX0/u/Pa0qJXHbisk0Sch2Vc39MIhGaQPe8KKqUoiqplcqQJZk6lQZNYaeJsHRBoghrhhtAiPBA6BJm6SkAlou4ITcqdfKpzSeqzy@Y0BZ6zdofrC1i358CAE57/Qoj4Bw "Python 3 – Try It Online")
### Background
Let **n** be a non-negative integer. If **n** is the **k**th triangular number, we have

which means there will be a natural solution if and only if **1 + 8n** is an odd, perfect square. Clearly, checking the parity of **1 + 8n** is not required.
### How it works
The recursive function **n** accepts a single, non-negative integer as argument. When called with a single argument, **k** defaults to **1**.
First, `(8*n+1)**.5%1` tests if **n** is a triangular number: if (and only if) it is, `(8*n+1)**.5` will yield an integer, so the residue from the division by **1** will yield **0**.
If the modulus is **0**, the `and` condition will fail, causing **f** to return **0**. If this happens in the initial call to **f**, note that this is the correct output since **n** is already triangular.
If the modulus is positive, the `and` condition holds and `f(n+k,k+1)+k` gets executed. This calls **f** again, incrementing **n** by **k** and **k** by **1**, then adds **k** to the result.
When **f(n0, k0)** finally returns **0**, we back out of the recursion. The first argument in the first call was **n**, the second one **n + 1**, the third one **n + 1 + 2**, until finally **n0 = n + 1 + … k0-1**. Note that **n0 - n** is a triangular number.
Likewise, all these integers will be added to the innermost return value (**0**), so the result of the intial call **f(n)** is **n0 - n**, as desired.
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~291~~ 281 bytes
```
class p{static int Main(string[]I){string d="0",s=I[0];int c=1,j,k;for(;;){j=k=0;string[]D=d.Split(' '),S=s.Split(' ');for(;j<D.Length;j++)for(;k<S.Length;k++)if(D[j]==S[k])return int.Parse(D[k]);j=int.Parse(D[0])+c++;d=d.Insert(0,$"{j} ");s=s.Insert(0,$"{j+int.Parse(I[0])} ");}}}
```
[Try it online!](https://tio.run/##VY9Bi8MgEIX/ioSFKtpgz3ZuuQR2YSHH4CEY21WLLY49hfx217SU7c5p5pv34D2De3NNthRzmRDJbcE8ZWeIi5l8TS5SzMnF86h7tjxXMkMjG4HQj1KrTWfgILwI6nRNVCm2eAgg1cvYwdwOt4vLdEd2TAyAb@fT449d@2njOf8ozzl7sHAcXixU5k60G70GGMagWbL5nuIWsv2eEtr6q1R5eCdSM244V3MN0Ee0KVMpPprFr6RhCmuOf5T/ebdm7KFa17WUcpB1fgE "C# (.NET Core) – Try It Online")
Program that takes a string as input and outputs through Exit Code.
Saved 10 Bytes thanks to Kevin Cruijssen
[Answer]
# JavaScript (ES7), ~~46~~ 44 bytes
```
f=(n,x=r=0)=>(8*(n+x)+1)**.5%1?f(n,x+=++r):x
```
---
## Try it
```
o.innerText=(
f=(n,x=r=0)=>(8*(n+x)+1)**.5%1?f(n,x+=++r):x
)(i.value=8);oninput=_=>o.innerText=f(+i.value)
```
```
<input id=i type=number><pre id=o>
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 10 bytes
```
`ḟ∫ΘNo£∫N+
```
[Try it online!](https://tio.run/##yygtzv7/P@HhjvmPOlafm@GXf2gxkOGn/f//f0MDIAAA "Husk – Try It Online")
[Answer]
# Dyalog APL, 19 bytes
*6 bytes saved thanks to @KritixiLithos*
```
{⊃o/⍨o∊⍨⍵+o←0,+\⍳⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbhOpHXc35@o96V@Q/6ugCUo96t2rnA8UNdLRjHvVuBnJrgQoVjMy40hQMDYCECRCbArE5EFsAsRFIwBhEGJkCAA)
**How?**
`o←0,+\⍳⍵` - assign `o` the first `⍵` triangular numbers
`o/‚ç®` - filter `o` by
`o∊⍨⍵+o` - triangular numbers that summed with `⍵` produce triangulars
`⊃` - and take the first
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 54 bytes
```
n->vecmin([y^2-1|y<-[2*n/d-d|d<-divisors(2*n)],y%2])/8
```
[Try it online!](https://tio.run/##FYhRCsIwEAWv8igIiexSG632o/YioUIxVgK6hlQKgd49xo@BmQlT9PwMecYVWXhYH/e3F2XTzXCzpZ6t2Uvt2G2uZ@dXv3ziosrTI6WdGXXd5SmEV1ICHhCil2/R6h8VZiVaE6w5E5oD4URoCRdCRzAljgXTjjr/AA "Pari/GP – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 56 bytes
```
f x|e<-(`elem`scanl1(+)[0..x])=[n|n<-[0..],e n,e$x+n]!!0
```
[Try it online!](https://tio.run/##FcdLCoMwGEXhrfxCB4oa4tw46TIkYGivDxpvxWSQgXtP7YFvcFYXPvA@51nShb4tJ3jsU3g5@q6sq1ErlWxlRl7s2//ZBsIGj1TTFoXOu9soRhbE55cRjEGGwchxboyiZL6dcO/c6bsf "Haskell – Try It Online")
[Answer]
# [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 68 bytes
```
L,RBFEREsECAAx$pBcB_B]VARBFEREsB]GEi$pGBcB*A8*1+.5^1%!!@A!@*b]EZBF#@
```
[Try it online!](https://tio.run/##S0xJKSj4/99HJ8jJzTXItdjV2dGxQqXAKdkp3ik2zBEq6hTr7pqpUuAOFNZytNAy1NYzjTNUVVR0cFR00EqKdY1yclN2@P//vwUA "Add++ – Try It Online"), or see the [test suite](https://tio.run/##S0xJKSj4/99FJ03HwUonyMnNNci12NXZ0bFCpcAp2SneKTbMESrqFOvumqlS4A4U1nK00DLU1jONM1RVVHRwVHTQSop1jXJyU3YIS3ZXUtC1U1BydPD6r5JmZ8AFJExAhCmIMAcRFiDCECxjBJYyAssZmYFIYxOILBD8BwA)!
Even *Java* is beating me. I really need to add some set commands to Add++
## How it works
```
L, - Create a lambda function
- Example argument: 8
R - Range; STACK = [[1 2 3 4 5 6 7 8]]
BF - Flatten; STACK = [1 2 3 4 5 6 7 8]
ER - Range; STACK = [[1] [1 2] ... [1 2 3 4 5 6 7 8]
Es - Sum; STACK = [1 3 6 10 15 21 28 36]
EC - Collect; STACK = [[1 3 6 10 15 21 28 36]]
A - Argument; STACK = [[1 3 6 10 15 21 28 36] 8]
A - Argument; STACK = [[1 3 6 10 15 21 28 36] 8 8]
x - Repeat; STACK = [[1 3 6 10 15 21 28 36] 8 [8 8 8 8 8 8 8 8]]
$p - Remove; STACK = [[1 3 6 10 15 21 28 36] [8 8 8 8 8 8 8 8]]
Bc - Zip; STACK = [[1 8] [3 8] [6 8] [10 8] [15 8] [21 8] [28 8] [36 8]]
B_ - Deltas; STACK = [-7 -5 -2 2 7 13 20 28]
B] - Wrap; STACK = [[-7 -5 -2 2 7 13 20 28]]
V - Save; STACK = []
A - Argument; STACK = [8]
R - Range; STACK = [[1 2 3 4 5 6 7 8]]
BF - Flatten; STACK = [1 2 3 4 5 6 7 8]
ER - Range; STACK = [[1] [1 2] ... [1 2 3 4 5 6 7 8]]
Es - Sum; STACK = [1 3 6 10 15 21 28 36]
B] - Wrap; STACK = [[1 3 6 10 15 21 28 36]]
G - Retrieve; STACK = [[1 3 6 10 15 21 28 36] [-7 -5 -2 2 7 13 20 28]]
Ei - Contains; STACK = [[1 3 6 10 15 21 28 36] [0 0 0 0 0 0 0 1]]
$p - Remove; STACK = [[0 0 0 0 0 0 0 1]]
G - Retrieve; STACK = [[0 0 0 0 0 0 0 1] [-7 -5 -2 2 7 13 20 28]]
Bc - Zip; STACK = [[0 -7] [0 -5] [0 -2] [0 2] [0 7] [0 13] [0 20] [1 28]]
B* - Products; STACK = [0 0 0 0 0 0 0 28]
A - Argument; STACK = [0 0 0 0 0 0 0 28 8]
8* - Times 8; STACK = [0 0 0 0 0 0 0 28 64]
1+ - Increment; STACK = [0 0 0 0 0 0 0 28 65]
.5^ - Root; STACK = [0 0 0 0 0 0 0 28 8.1]
1% - Frac part; STACK = [0 0 0 0 0 0 0 28 0.1]
!! - To bool; STACK = [0 0 0 0 0 0 0 28 1]
@ - Reverse; STACK = [1 28 0 0 0 0 0 0 0]
A - Argument; STACK = [1 28 0 0 0 0 0 0 0 8]
! - Not; STACK = [1 28 0 0 0 0 0 0 0 0]
@ - Reverse; STACK = [0 0 0 0 0 0 0 0 28 1]
* - Multiply; STACK = [0 0 0 0 0 0 0 0 28]
b] - Wrap; STACK = [0 0 0 0 0 0 0 0 [28]]
EZ - Unzero; STACK = [[28]]
BF - Flatten; STACK = [28]
# - Sort; STACK = [28]
@ - Reverse; STACK = [28]
```
[Answer]
# [R](https://www.r-project.org/), ~~46~~ ~~44~~ ~~43~~ 41 bytes
```
function(x,y=cumsum(0:x))y[(x+y)%in%y][1]
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jQqfSNrk0t7g0V8PAqkJTszJao0K7UlM1M0@1MjbaMPZ/moaRieZ/AA "R – Try It Online")
An anonymous function with one mandatory argument, `x`; computes first `x+1` triangular numbers as an optional argument to golf out a few curly braces. I used `choose` before I saw Luis Mendo's [Octave answer](https://codegolf.stackexchange.com/a/129035/67312).
I shaved off a few bytes of Luis Mendo's answer but forgot to use the same idea in my answer.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes
```
0rRS$€ċ
0ð,+Ç€Ạð1#
```
[Try it online!](https://tio.run/##y0rNyan8/9@gKChY5VHTmiPdXAaHN@hoH24Hch7uWnB4g6Hy////DQ0A "Jelly – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~83~~ 81 bytes
* @Felipe Nardi Batista saved 2 bytes.
```
lambda n:min(x for x in i(n)if n+x in i(n))
i=lambda n:[i*-~i/2for i in range(n)]
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZRvzPycxNyklUSHPKjczT6NCIS2/SKFCITNPIVMjTzMzTSFPG87T5Mq0hauOztTSrcvUNwKpzwSpKErMS08Fqor9X1CUmVeikaVhZKap@R8A "Python 2 – Try It Online")
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), ~~16~~ 14 bytes
```
(⊃0∘,∩⊢-≢)+\∘⍳
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbBI1HXc0Gjzpm6DzqWPmoa5Huo85FmtoxQIFHvZv/P@qbClSSBqS4aMT8b2TGZWjAZcJlymXOZcFlZMJlbMJlZAoA "APL (Dyalog Classic) – Try It Online")
] |
[Question]
[
(*Inspired by [this challenge](https://codegolf.stackexchange.com/q/93005/31957)*.)
Let's say we have a string `ABBCBA`. We can say that there is a rise between `A` and `B`, for `B` follows `A`; we can say that there is a run between `B` and `B`, for nothing changes; and finally we can say there is a fall between `C` and `B`. We can draw a graph like this:
```
A B B C B A
Rising: o o
Continuing: o
Falling: o o
```
Without the labels, and minimizing whitespace:
```
o o
o
oo
```
This is the expected output for input `ABBCBA`.
You may use any non-whitespace character to replace `o` in the output. Further, each column may optionally have an extra space between them, like so:
```
o o
o
o o
```
The input will consist of at least three characters. The string will consist entirely of uppercase letters, but you may instead use lowercase letters.
## Test cases
```
TEST CASE
LINE 1
LINE 2
LINE 3
HELLOWORLD
o oo o
o
o o oo
TESTCASE
oo o
o oo o
EXAMINATION
o o o o o
o o o o o
ZSILENTYOUTH
o ooo o
oo o o oo
ABC
oo
ABCBA
oo
oo
```
[Answer]
# Mathematica, ~~93~~ ~~83~~ ~~68~~ 64 bytes
(uses `0`, not `O`)
```
Row[Column@Insert[{,},0,2-#]&/@Sign@Differences@LetterNumber@#]&
```
# Explanation
```
LetterNumber@#
```
Gets the position in the alphabet of each characters of the input.
```
Sign@Differences@
```
Takes the difference between each consecutive elements, and takes the sign (`-1` for negative/falling, `0` for 0/continuing, `1` for positive/rising)
```
Insert[{,},0,2-#]&
```
Inserts a `0` in a list of two `Null`s, in the first position if rising, middle if continuing, and third position if falling.
```
Row[Column@ ... ]
```
Formats the output.
---
If the output could look different from the one in the question, the above code could be shortened to 41 bytes:
```
ListPlot@*Sign@*Differences@*LetterNumber
```
... which creates something like this (for "ABBCBA"):
[](https://i.stack.imgur.com/kkMOs.png)
[Answer]
# [MATL](http://github.com/lmendo/MATL), ~~15~~, 14 bytes
```
dZSqtQtQv~79*c
```
[Try it online!](http://matl.tryitonline.net/#code=ZFpTcXRRdFF2fjc5KmM&input=J0hFTExPV09STEQn)
Explanation:
They say a picture is worth a thousand words, so [here is a beta online interpreter](https://matl.suever.net/?code=dtD1Y.XxZStD1Y.XxqtD1Y.XxttD1Y.XxQtD1Y.XxttD1Y.XxQtD1Y.Xxv~79%2atD1Y.Xxc&inputs=%27HELLOWORLD%27&version=19.2.0) that shows you the value on top of the stack live as it updates. Note that it's still in beta, so you might need to hit run several times.
So first, we call `dZS`. `d` gives us the difference between each consecutive element, and `ZS` gives us the sign (-1, 0, or 1) of each element. So with 'HELLOWORLD' as input, after the first step we'll have:
```
-1 1 0 1 1 -1 1 -1 -1
```
Now, we just use `q` to decrement this and get:
```
-2 0 -1 0 0 -2 0 -2 -2
```
And then two times we duplicate the top of the stack and increment the array (`tQ`) After this we'll have
```
-2 0 -1 0 0 -2 0 -2 -2
-1 1 0 1 1 -1 1 -1 -1
0 2 1 2 2 0 2 0 0
```
Now all of the '0's are where we want to output a character. So, we join these three arrays into a matrix (`v`), and logically negate it (`~`). Then we multiply every value in the matrix by the ASCII value of 'O', (`79*`) and display it as a string with `c`.
[Answer]
# Haskell, 63 bytes
```
f w=[do(e,y)<-zip w$tail w;max" "['o'|b e y]|b<-[(<),(==),(>)]]
```
Returns a list of three strings, representing the lines of output. Contains no subliminal messages.
dianne saved three bytes by using `do` notation and `max` instead of a list comprehension and `last`.
[Answer]
## [CJam](http://sourceforge.net/projects/cjam/), 19 bytes
```
l2ew{:-g)S3*0t}%zN*
```
Uses `0` instead of `o`.
[Try it online!](http://cjam.tryitonline.net/#code=bDJld3s6LWcpUzMqMHR9JXpOKg&input=SEVMTE9XT1JMRA)
### Explanation
```
l e# Read input.
2ew e# Get all pairs of consecutive letters.
{ e# Map this block over the pairs...
:- e# Compute the difference between the two letters.
g e# Signum. Gives -1 for rises, 1 for falls, 0 otherwise.
) e# Increment. Gives 0 for rises, 2 for falls, 1 otherwise. Call this i.
S3* e# Push a string with three spaces.
0t e# Replace the i'th space (zero-based) with a zero.
}%
z e# Transpose.
N* e# Join with linefeeds.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
OIṠ“ o ”ṙZY
```
[Try it online!](http://jelly.tryitonline.net/#code=T0nhuaDigJwgbyDigJ3huZlaWQ&input=&args=QUJCQ0JB) or [verify all test cases](http://jelly.tryitonline.net/#code=T0nhuaDigJwgbyDigJ3huZlaWQrhuLLCtcW8w4figqxZ4oKsauKAnMK2wrY&input=&args=SEVMTE9XT1JMRCBURVNUQ0FTRSBFWEFNSU5BVElPTiBaU0lMRU5UWU9VVEggQUJDIEFCQ0JB).
### How it works
```
OIṠ“ o ”ṙZY Main link. Argument: s (string)
O Ordinal; replace all characters with their code points.
I Increments; compute the differences of consecutive code points.
Ṡ Sign function.
“ o ”ṙ Rotate that string -1, 0, or 1 unit(s) to the left.
Z Zip; transpose rows and columns.
Y Join, separating by linefeeds.
```
[Answer]
# Python 2, ~~76~~ 71 bytes
```
lambda s:[''.join(' o'[cmp(*x)==n]for x in zip(s,s[1:]))for n in-1,0,1]
```
*Thanks to @xnor for notifying me that returning a list of strings is allowed.*
Test it on [Ideone](http://ideone.com/DqNwZ0).
[Answer]
## JavaScript (ES6), ~~96~~ ~~95~~ ~~89~~ ~~87~~ 82 bytes
*2 bytes saved by using `0` instead of `o`, as suggested by Conor O'Brien*
*~~2~~ 6 bytes saved thanks to ETHproductions*
```
let f =
s=>[1,0,-1].map(k=>s.replace(/./g,(c,i)=>i--?(c>s[i])-(c<s[i])-k&&' ':'')).join`
`
console.log(f("HELLOWORLD"));
console.log(f("EXAMINATION"));
```
[Answer]
# Perl, 47 bytes
Includes +1 for `-p`
Give input on STDIN:
```
bumpy.pl <<< ABBCBA
```
`bumpy.pl`:
```
#!/usr/bin/perl -p
$_ x=3;s%.%/\G(.)(.)/?$2cmp$1^$.&&$":--$.>0%eg
```
[Answer]
# MATL, ~~16~~ 14 Bytes
```
dZSqq_tn:79Z?c
```
[Try it online!](http://matl.tryitonline.net/#code=ZFpTcXFfdG46NzlaP2M&input=J0hFTExPV09STEQn)
This grew out of a discussion of [DJMCMahem's answer](https://codegolf.stackexchange.com/a/94440/42247). Even though this answer is ~~2 characters longer~~ the same length, the method is somewhat different so it may be of independent interest.
*Thanks to Luis Mendo for a suggestion saving 2 bytes (see comments)*
**Explanation:**
'dZS' gets a vector where each entry is the sign of the differences between sucessive characters, then 'qq\_' decrements each entry by two and flips the sign, so now if the character increases it is 1, if it stays the same 2, and if it decreases 3. For example,
```
dZSqq_ applied to 'HELLOWORLD' creates the vector [3 1 2 1 1 3 1 3 3]
```
Next, 't' makes a copy of the previous vector on the stack, then 'n:' places the vector [1,2,3,4,...] on the stack as well. Then '79' places the value 79 on the stack. The value 79 is chosen because it is the number for the unicode character 'o', which will be our output later. (Thanks to Luis Mendo for the idea to put the value 79 here rather than later)
```
tn:79 applied to [3 1 2 1 1 3 1 3 3] creates the following items:
[3 1 2 1 1 3 1 3 3] <-- first item on the stack
[1 2 3 4 5 6 7 8 9] <-- second item on the stack
79 <-- third item on the stack
```
At this point we have precisely the row indices, column indices, and nonzero value of a sparse matrix that has the value 79 wherever we want the output character, and 0 wherever we want to output whitespace. We take these three items off the stack and create this sparse matrix with MATL's sparse matrix command 'Z?'. That is,
```
dZSqq_tn:79 Z? applied to 'HELLOWORLD' outputs the following:
[0 79 0 79 79 0 79 0 0 ]
[0 0 79 0 0 0 0 0 0 ] <-- 3-by-n sparse matrix
[79 0 0 0 0 79 0 79 79]
```
All that is left is to convert the matrix from numbers to unicode characters, which is done by the command 'c'. The 79's become 'o', and the 0's become spaces:
```
dZSqq_tn:79Z?c applied to 'HELLOWORLD' outputs:
[ o o o o ]
[ o ] <-- 3-by-n sparse matrix of characters.
[o o o o]
```
The resulting matrix of chars is then implicitly displayed.
[Answer]
# PHP, 95 Bytes
```
for($b[1]=$b[0]=$b[-1]=" ";($s=$argv[1])[++$i];)$b[$s[$i-1]<=>$s[$i]][$i]=8;echo join("\n",$b);
```
1.Create an array of strings with the index -1 to 1 alternative `$b=array_fill(-1,3," ");`
2.Fill the strings dependent by the spaceship operator and position of the input
3.Output join the array with a new line
First Way 111 Bytes
```
for($o=" ";$i<$l=strlen($s=$argv[1])-1;)$o[$l*(1+($s[$i]<=>$s[$i+1]))+$i++]=8;echo join("\n",str_split($o,$l));
```
Use the spaceship operator `<=>` [spaceship operator](http://php.net/manual/en/language.operators.comparison.php)
[Answer]
# JavaScript (ES6), 81 bytes
```
s=>[s,s,s].map(f=([c,...s],n)=>(p=s[0])?((c<p)-(c>p)+n-1&&" ")+f(s,n):"").join`
`
```
Written from scratch, though it was heavily inspired by [@Arnauld's answer](https://codegolf.stackexchange.com/a/94438/42545). Uses recursion to calculate the contents of each row.
[Answer]
# Ruby, ~~66~~ 64 bytes
```
->s{(-1..1).map{|n|s.gsub(/.(?=(.))/){"o "[n+($1<=>$&)]}.chop}}
```
See it on eval.in: <https://eval.in/649503>
[Answer]
# Java 7, ~~158~~ 156 bytes
```
String c(char[]z){String a,b,c=a=b="";for(char i=1,q=z[0],o=79,s=32,x;i<z.length;a+=(x=z[i])>q?o:s,b+=x==q?o:s,c+=x<q?o:s,q=z[i++]);return a+"\n"+b+"\n"+c;}
```
2 bytes saved thanks to *@Frozn*.
**Ungolfed & test cases:**
[Try it here.](https://ideone.com/2ksqN9)
```
class M{
static String c(char[] z){
String a,
b,
c = a = b = "";
for(char i = 1,
q = z[0],
o = 79,
s = 32,
x; i < z.length; a += (x = z[i]) > q
? o
: s,
b += x == q
? o
: s,
c += x < q
? o
: s,
q = z[i++]);
return a + "\n" + b + "\n" + c;
}
public static void main(String[] a){
print("HELLOWORLD");
print("TESTCASE");
print("EXAMINATION");
print("ZSILENTYOUTH");
print("ABC");
print("ABCBA");
print("ABBCBA");
print("UVVWVVUVVWVVUVVW");
}
static void print(String s){
System.out.println(c(s.toCharArray()));
System.out.println("-------------------------");
}
}
```
**Output:**
```
O OO O
O
O O OO
-------------------------
OO O
O OO O
-------------------------
O O O O O
O O O O O
-------------------------
O OOO O
OO O O OO
-------------------------
OO
-------------------------
OO
OO
-------------------------
O O
O
OO
-------------------------
O O O O O O
O O O O O
O O O O
-------------------------
```
[Answer]
# [Clora](https://github.com/opsxcq/cloralang) (20 bytes)
`<IN?o ;=IN?o ;>IN?o`
Explanation:
There are 3 Clora programs, one for each output line.
### First program, `<IN?o`
Check if current input char `I` is smaller `<` than the next char `N`. Save the result in a global flag. Check the flag result `?` and if is true, output `o`, else a blank space (yes, there is a blank space there.
All other programs, follow the same rule and are separated by `;`, every program is executed and receives the input as argument.
You can test it by yourself including clora.js and executing it with
```
(function() {
var x = new Clora('<IN?o ;=IN?o ;>IN?o ');
x.execute('EXAMINATION', function(r) {
console.log(r)
})
})();
```
[Answer]
# Pyth, 21 bytes
```
jCmX*3\ h._d0-M.:CMz2
```
A program that takes input of an unquoted string on STDIN and prints the result.
This uses a similar idea to @MartinEnder's [CJam answer](https://codegolf.stackexchange.com/a/94439/55526).
[Try it online](https://pyth.herokuapp.com/?code=jCmX%2a3%5C+h._d0-M.%3ACMz2&debug=0) or [Verify all test cases](https://pyth.herokuapp.com/?code=zjCmX%2a3%5C+h._d0-M.%3ACMz2&test_suite=1&test_suite_input=HELLOWORLD%0ATESTCASE%0AEXAMINATION%0AZSILENTYOUTH%0AABC%0AABCBA&debug=0).
**How it works**
```
jCmX*3\ h._d0-M.:CMz2 Program. Input: z
CMz Map ordinal over z, yielding the code-points of the characters
.: 2 Yield all length-2 sublists of that
-M Map subtraction over that
m Map the following over that with variable d:
._d Yield the sign of d
h Increment that (i)
*3\ Yield string literal of 3 spaces, " "
X 0 Replace the space at index i with 0
C Transpose that
j Join that on newlines
Implicitly print
```
[Answer]
# PHP 7, ~~81~~ ~~80~~ 77 bytes
Note: uses Windows-1252 encoding
```
for($x=2;~$x--;print~õ)for($a=$argn;$c=$a[$$x+1];)echo$c<=>$a[$$x++]^$x?~ß:o;
```
Run like this:
```
echo HELLOWORLD | php -nR 'for($x=2;~$x--;print"\n")for($a=$argn;$c=$a[$$x+1];)echo$c<=>$a[$$x++]^$x?" ":o;';echo
```
# Explanation
Iterates over lines (numbered `1`, `0`, `-1`). Then iterates over the input string for every line. When the result of spaceship comparison equals the line number, output an `o`, otherwise, output a space. After every line, print a newline.
# Tweaks
* Stop iterating when `$x` is `-1`, which we can find by binary negation (result `0`). Saves a byte compared to adding `1` (or 2 with pre-increment).
* Saved 3 bytes by using `$argn`
[Answer]
**Lua** 326 303 bytes
tl=0 s=io.read() o1,o2,o3="","","" t={} for i=1,#s do t[i]=s:sub(i,i) tl=tl+1 end for v=1,tl-1 do if t[v]t[v+1] then o1=o1.." " o2=o2.." " o3=o3.."o" end end print(o1.."\n"..o2.."\n"..o3)
An ungolfed version
```
tl = 0 --set the tables length to 0
s = io.read() --Get the string from input
o1,o2,o3="","","" --Set the 3 output rows to empty strings
t = {} --Make a table for the string to be sent into
for i = 1, #s do --Loop from 1 to the length of the string
t[i] = s:sub(i, i) --Set the I-th term in the table to the I-th character in the string
tl = tl+1 --Add 1 to the table length
end --End the loop
for v=1,tl-1, 1 do --Loop from 1 to the tables length - 1, incrementing by 1
if t[v] < t[v+1] then --Lua supports greater than less than and equals to with charactes, so this if statement detects if the string is rising
o1=o1.."o" --Adds an o to the end of the first line of output
o2=o2.." " --Adds a space to the second line
o3=o3.." " --Adds a space to the third line
elseif t[v] == t[v+1] then --Detects if the string is continuing
o1=o1.." " --Adds a space to the first line
o2=o2.."o" --Adds an o to the second line
o3=o3.." " --Adds a space to the third line
elseif t[v] > t[v+1] then --Detects if string is falling
o1=o1.." " --Adds a space to the first line
o2=o2.." " --Adds a space to the second line
o3=o3.."o" --Adds an o to the third line
end --Ends the if statement
end --Ends the loop
print(o1.."\n"..o2.."\n"..o3) --Prints the output
```
[Answer]
## R, 114 bytes
A non-competing R answer.
```
v=y=z=rep(" ",length(x<-diff(utf8ToInt(scan(,"")))));v[x>0]="#";y[x==0]="#";z[x<0]="#";cat(v,"\n",y,"\n",z,sep="")
```
### Explanation
1. Read input from command line and convert into ascii decimal vector
2. Take 1st difference and create an 3x vectors of the same length with white spaces
3. Then replace the white space vectors with `#` if the differences are `>0`, `==0` or `<0`.
4. Coerce the vectors and print them separated by newlines
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 13 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Takes input as a character array. The first 3 bytes could be removed by taking input as an array of codepoints. Uses `"` instead of `o`.
```
mc äÎm!éQû3)Õ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&header=cQ&code=bWMg5M5tIelR%2bzMp1Q&input=IkFCQkNCQSI)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes
```
C¯±››×↲§
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJDwq/CseKAuuKAusOX4oaywqciLCIiLCJaU0lMRU5UWU9VVEgiXQ==)
The power of that one built-in I added 3 years ago because I thought it was a good idea to have something to vertically join a list of lists. Can be 7 bytes with the L flag.
## Explained
```
C¯±››×↲§
C¯ # Convert each character to ascii value and get pairwise differences
± # Sign of each
›› # + 2 (the ⇧ element doesn't vectorise it's numeric overload)
×↲ # left adjust the string "*" by each number in ^
§ # "vertical join" - Transpose (filling with spaces) and then join on newlines
```
] |
[Question]
[
This was inspired by [Print a Negative of your Code](https://codegolf.stackexchange.com/q/42017/29611) and [Golf a mutual quine](https://codegolf.stackexchange.com/q/2582/29611).
---
Consider a **rectangle** of characters, that meet the following restrictions:
1. Consists solely of [printable ASCII characters](http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters)
2. Dimensions both greater than 1
3. Each row and each column contains at least one space.
4. Each row and each column contains at least one non-space character.
For example, the following is a valid 6x4 rectangle:
```
%n 2e
1 g 3
&* __
3
```
A **negative** for this rectangle is defined to be a rectangle of equal dimensions, with all spaces replaced by non-space characters, and all non-space characters replaced by spaces. A negative of the above rectangle could be:
```
f ^
33 >
9 $
^ }|Q'
```
Any non-space printable ASCII character may be used to replace a space.
## Task
Your task is to write a program with rectangular source code, that outputs a valid negative to itself. The negative outputted must also be a valid program, in the same language as the original, and it must output the source of the original.
No trailing whitespace may be added or removed, except for a single trailing newline at the end of either output, which is optional.
Neither program is permitted to read the source code of either; nor may REPL environments be assumed.
## Scoring
Your score is the product of the dimensions of your code (i.e. if your source code is in a 12 by 25 rectangle, your score is 12\*15=180). Additionally, for each character used in a comment, your score increases by 2 (If you use `/* .. */` once in your code, and your code is in a 10 by 10 rectangle, your score would be 10\*10+8\*2=116).
The lowest score wins.
If there is a tie, the submission with the least number of spaces in the program (either the original or the negative, whichever has fewer spaces) wins.
If there still remains a tie, the earlier answer shall win.
There is a bonus of **-52%**, if combining the original and the negative together produces a normal quine. For example:
```
Original Negative Combined
A A B B BABA
A A B B ABAB
```
[Answer]
## Python, 97x2 + 2 = 196
Not a great solution to start off, but at least it works (I think).
```
c='o=1-%d;print("%%97s\\n%%97s"%%("#","c=%%r;exec(c%%%%%%d)\\40"%%(c,o),"#")[o:][:2])';exec(c%1)
#
```
Output:
```
#
c='o=1-%d;print("%%97s\\n%%97s"%%("#","c=%%r;exec(c%%%%%%d)\\40"%%(c,o),"#")[o:][:2])';exec(c%0)
```
[Answer]
# CJam, (~~58~~ ~~56~~ ~~54~~ ~~48~~ 46 x 2) \* 48% = 44.16
```
{`"_~"+{_,94\m2/S*a_+\*
N/23f/Wf%N*}_`'"#)!*}_~
```
which prints
```
{`"_~"+{_,94\m2/S*a_+\*
N/23f/Wf%N*}_`'"#)!*}_~
```
The non-space characters in each line remain the same between the two mutual quines.
But now the really sweet part:
```
{`"_~"+{_,94\m2/S*a_+\*{`"_~"+{_,94\m2/S*a_+\*
N/23f/Wf%N*}_`'"#)!*}_~N/23f/Wf%N*}_`'"#)!*}_~
```
is a quine! :)
[Test it here.](http://cjam.aditsu.net/)
## How it works
I recommend you read the explanation on my other submission first, as it explains the basics of quining in CJam in general.
This one is a bit trickier. For the mutual quine, as in the other case, I modify the string representation of the block by adding spaces before or after each line, and swapping a 0 with a 2, so that the resulting program puts the spaces at the opposite end.
Note that the spaces don't affect the mutual quines at all. In the first one, they are in a block, which isn't really used, and in the second they are around the entire code.
To obtain a regular quine when combining both, we need to find a way to avoid doing all that modification. Notice that the structure of the whitespace and code means that by combining both, we insert the entirety of one quine into the other. So if we put the entire modification code in a block, we can run that block depending on its actual contents.
So now I've got this block... for the mutual quines, it only contains the code I actually want to run. For the combined quine, it also contains the entire quine again, in a random position, which doesn't make any sense... but since it's a block, it's not run automatically. So we can determine whether to modify the string based on the contents of that block. That's what `_`'"#)!` is for. It duplicates the block, converts it to a string, searches for the character `"` (which, in the mutual quines, only appears *outside* the block) - the search returns `-1` if the character isn't found and a positive integer otherwise -, increments the result and negates it logically. So if a `"` was found this yields `0` otherwise it yields `1`. Now we just do `*`, which executes the block once, if the result was 1 and not at all otherwise.
Finally, this is how the modifying code works:
```
_,94\m2/S*a_+\*N/23f/Wf%N*
_, "Duplicate the quine string and get its length.";
94\m "Subtract from 94.";
2/ "Divide by two.";
S* "Create a string with that many spaces. This will be
an empty string for the first mutual quine, and contain
23 spaces for the second mutual quine.";
a_+ "Create an array that contains this string twice.";
\* "Join the two copies together with the quine string.";
N/ "Split into lines.";
23f/ "Split each line into halves (23 bytes each).";
Wf% "Reverse the two halves of each line.";
N* "Join with a newline.";
```
# Claiming the Bounty, (12 x 10) \* 48% = 57.6
Turns out that this code can be split over more lines very easily with some modifications. We add 2 characters, to get 48 in a row, which we can then conveniently divide by 8, so that we have 8 lines with 6 characters of code and 6 spaces. To do that we also need to change a few numbers, and to rearrange an operator or two, so they aren't split over both lines. That gives us a working version with size **12 x 8**... one off the requirement. So we just add two lines that don't do anything (push a 1, pop a 1, push a 1, pop a 1...), so get to **12 x 10**:
```
{`"_~"
+{129X
$,m2/S
*a_+\*
N/6f/1
;1;1;1
;1;1;1
;Wf%N*
}_`'"#
)!*}_~
```
As the previous one this produces
```
{`"_~"
+{129X
$,m2/S
*a_+\*
N/6f/1
;1;1;1
;1;1;1
;Wf%N*
}_`'"#
)!*}_~
```
(Side note: there is no need to keep alternating left and right on the intermediate lines, only the position of the first and last line are important. Left and right can be chosen arbitrarily for all other lines.)
And through pure coincidence, the full quine also still works:
```
{`"_~"{`"_~"
+{129X+{129X
$,m2/S$,m2/S
*a_+\**a_+\*
N/6f/1N/6f/1
;1;1;1;1;1;1
;1;1;1;1;1;1
;Wf%N*;Wf%N*
}_`'"#}_`'"#
)!*}_~)!*}_~
```
(I say coincidence, because the part that takes care of not executing the inner code now gets weirdly interspersed with the other quine, but it still happens to work out fine.)
That being said, I could have just added 44 lines of `1;` to my original submission to fulfil the bounty requirement, but `12 x 10` looks a lot neater. ;)
**Edit:** Haha, when I said "pure coincidence" I couldn't have been more spot on. I looked into how the final quine now actually works, and it's absolutely ridiculous. There are three nested blocks (4 actually, but the innermost is irrelevant). The only important part of the innermost of those 3 blocks is that it contains a `"` (and not the one that it did in the original submission, but the very `'"` that is used at the end to check for this same character). So the basic structure of the quine is:
```
{`"_~"{`"_~"+{___'"___}_`'"#)!*}_~)!*}_~
```
Let's dissect that:
```
{`"_~" }_~ "The standard CJam quine.";
{`"_~"+ }_~ "Another CJam quine. Provided it doesn't do
anything in the rest of that block, this
will leave this inner block as a string on
the stack.";
) "Slice the last character off the string.";
! "Negate... this yields 0.";
* "Repeat the string zero times.";
```
So this does indeed do some funny magic, but because the inner block leaves a single string on the stack, `)!*` happens to turn that into an empty string. The only condition is that the stuff in the inner block after `+` doesn't do anything else to the stack, so let's look at that:
```
{___'"___} "Push a block which happens to contain
quotes.";
_`'"#)!* "This is from the original code and just
removes the block if it does contain
quotes.";
```
[Answer]
# CJam, (~~51 49 47 46 45~~ 42 x 2) \* 48% = 40.32
```
{])"_~"+S41*'R+@,[{N@S}{SN@}{W=N]_}]=~}_~
R
```
Running the above code gives this output:
```
R
{])"_~"+S41*'R+@,[{N@S}{SN@}{W=N]_}]=~}_~
```
running which, prints back the original source.
*The source and the output are simply swapped lines.*
**Now comes the magic.**
Overlapping the source and the output results into the following code:
```
{])"_~"+S41*'R+@,[{N@S}{SN@}{W=N]_}]=~}_~R
{])"_~"+S41*'R+@,[{N@S}{SN@}{W=N]_}]=~}_~R
```
which is a perfect quine!
[Try them online here](http://cjam.aditsu.net/)
---
**How it works**
All the printing logic is in the first line itself which handles all three cases explained later.
```
{])"_~"+S41*'R+@,[{N@S}{SN@}{W=N]_}]=~}_~
{ }_~ "Copy this code block and execute the copy";
] "Wrap everything before it in array";
) "Pop the last element out of it";
"_~"+ "Append string '_~' to the copied code block";
S41* "Create a string of 41 spaces";
'R+ "Append character R to it";
@, "Rotate the array to top and get its length";
[{ }{ }{ }]=~ "Get the corresponding element from this"
"array and execute it";
```
The array in the last line above is the array which has code blocks corresponding to all three cases.
**Case 1**
```
{])"_~"+S41*'R+@,[{N@S}{SN@}{W=N]_}]=~}_~
R
```
In this case, the length of remaining stack was 0 as when the block was executed, it only had the copy of the block itself, which was initially popped out in the third step above. So we take the index `0` out of the last array and execute it:
```
{N@S} "Note that at this point, the stack is something like:"
"[[<code block that was copied> '_ '~ ] <41 spaces and R string>]";
N "Add newline to stack";
@ "Rotate the code block to top of stack";
S "Put a trailing space which negates the original R";
```
In this case, the second line is a no-op as far as printing the output is concerned.
**Case 2**
```
R
{])"_~"+S41*'R+@,[{N@S}{SN@}{W=N]_}]=~}_~
```
In this case, the stack already contained an empty string, so when the copied code block was executed, it had 2 elements - an empty string and the code block itself. So we take the index `1` out of the last array and execute it:
```
{SN@} "Note at this point, the stack is same as in case 1";
SN "Push space and newline to stack";
@ "Rotate last three elements to bring the 41 spaces and R string to top";
```
**Case 3**
```
{])"_~"+S41*'R+@,[{N@S}{SN@}{W=N]_}]=~}_~R
{])"_~"+S41*'R+@,[{N@S}{SN@}{W=N]_}]=~}_~R
```
In this case, the stack has 6 elements. So after popping the last code block, remaining array length is 5. We take the index `5` out of the array and execute it. *(Note that in a array of `3` elements, index `5` is index `5%3 = 2`)*
```
{W=N]_} "Note at this point, the stack is same as in case 1";
W= "Take the last character out of the 41 spaces and R string, i.e. R";
N] "Add a new line to stack and wrap the stack in an array";
_ "Copy the array to get back the source of Case 3 itself";
```
[Answer]
# CJam, ~~42~~ ~~37~~ 33 x 2 = 66
```
{`As_W%er"_~"+S 33*F'Lt1{\}*N\}_~
L
```
which prints
```
L
{`As_W%er"_~"+S 33*F'Lt0{\}*N\}_~
```
(The lines are swapped, and a `1` turns into a `0`.)
[Test it here.](http://cjam.aditsu.net/)
## How it works
First, you should understand the basic CJam quine:
```
{"_~"}_~
```
The braces simply define a block of code, like a function, that isn't immediately executed. If an unexecuted block remains on the stack, it's source code (including braces) is printed. `_` duplicates the block, and `~` executes the second copy. The block itself simply pushes the string containing `_~`. So this code, leaves the stack in the following state:
```
Stack: [{"_~"} "_~"]
```
The block and the string are simply printed back-to-back at the end of the program, which makes this a quine.
The beauty of this is that we can do whatever we want in the block, and it remains a quine, because each piece of code will automatically be printed in the block contents. We can also modify the block, by obtaining it's string representation with ``` (which is just a string of the block with braces).
Now let's look at this solution. Notice that either part of the mutual quine contains of the quine-like block with `_~`, and an `L`. The `L` pushes an empty string onto the stack, which doesn't contribute to the output. So here is what the block does:
```
` "Convert block to its string representation.";
As "Push 10 and convert to string.";
_W% "Duplicate and reverse, to get another string 01.";
er "Swap 0s and 1s in the block string.";
"_~"+ "Append _~.";
S 33* "Push a string with 33 spaces.";
F'Lt "Set the character at index 15 to L.";
1{ }* "Repeat this block once.";
\ "Swap the code string and the space string.";
N\ "Push a newline and move it between the two lines.";
```
So this will do the quine part, but exchange a 1 for a 0, and it will also prepend another line with an `L`, where the code above has a space. The catch is that the order of those two lines is determined by the swapping inside `{ }*`. And because the outer part of the mutual quine has the `0` in front of it replaced by a `1`, it never executes this swap, and hence produces the original order again.
[Answer]
# CJam, 27 × 2 = 54
```
{ ` " _ ~ " + N - ) 2 * ' '
> @ t s G B + / N * } _ ~
```
Output:
```
{ ` " _ ~ " + N - ) 2 * '
' > @ t s G B + / N * } _ ~
```
`'A'B>` compares the characters A and B. `' '\n >` returns 1 because 32>10 and `' \n' >` returns 0 because the two spaces are equal.
[Answer]
# CJam, ~~30~~ 29 x 2 = 58
```
{"_~"SN]_,4=S28*'R+\{N@}*}_~
R
```
Outputs:
```
R
{"_~"SN]_,4=S28*'R+\{N@}*}_~
```
which outputs the original source.
This is based on the same principal as my other solution.
[Try it online here](http://cjam.aditsu.net/)
[Answer]
# [Klein](https://github.com/Wheatwizard/Klein), 2\*96 = 192
```
\ 1
< (!.:!.?!|84*:999*+2+$<::::::]]]]]]]77*55+<)!.:!.?!>(84*2+@*77]]]]]]]::::::<$*77:*48+55+2*48 <"
```
[Try it online!](https://tio.run/##y85Jzcz7/18hRoF2wJDLRkFDUc9KUc9escbCRMvK0tJSS9tIW8XGCgxiIcDcXMvUVNtGE6rSTgOo1EjbQcvcHKoAotpGBShipWVioQ1UbQSkFWyU/v//b2Bg8F/XEQA "Klein – Try It Online")
```
< 84*2+55+84*:77*$<::::::]]]]]]]77*@+2*48(>!?.!:.!)<+55*77]]]]]]]::::::<$+2+*999:*48|!?.!:.!( <"
1 1
```
[Try it online!](https://tio.run/##y85Jzcz7/99GwcJEy0jb1FQbSFuZm2up2FiBQSwEAEUctI20TCw07BTt9RSt9BQ1bYCqtczNoQogqm1UtI20tSwtLa2ASmugKjUUbJS4FAwVaAcM////b2Bg8F/XEQA "Klein – Try It Online")
] |
[Question]
[
*This is my first question here, so any suggestions in the comments would be appreciated! Thanks ;)*
# Introduction
One very common strategy for the [2048 game](https://gabrielecirulli.github.io/2048/) is *never ever swiping down*. This positions all the big numbers at the top, and the lower ones in the bottom. So, if you apply this strategy correctly, your board will always match the following pattern:
# The pattern to check for / Your task
Your submission should be either a full program or a function which returns a truthy value if the board can be described like this:
Going down each column of the board, the first number should be the highest of the column, the second number should be less than or equal to the first number, etc. A **good 2048-board** is defined as a board where the highest numbers are all on the top.
This is **code-golf**, so the shortest Code per language (in bytes) wins.
# I/O
The input can be taken in any appropriate way, for example an array of 4 arrays, each containing 4 numbers, or an array of 16 numbers. **In total, it will be always 16 numbers, representing the 4x4 board**
The output should be a truthy value of the input is a "good 2048-board", and a falsy value otherwise.
# Examples
Truthy:
```
|-------------------|
| 16 | | 64 | 8 |
|-------------------|
| 8 | | 32 | 8 |
|-------------------|
| 4 | | 32 | 2 |
|-------------------|
| 2 | | | |
|-------------------|
|-------------------|
| 16 | 128| 64 | 32 |
|-------------------|
| 8 | 128| 32 | 8 |
|-------------------|
| 4 | 16 | 8 | 2 |
|-------------------|
| 4 | | | |
|-------------------|
```
Falsy:
```
|-------------------|
| 16 | | 64 | 8 |
|-------------------|
| 8 | | 32 | 16 |
|-------------------|
| 32 | | 128| 2 |
|-------------------|
| 2 | | | |
|-------------------|
|-------------------|
| 16 | 128| 64 | 32 |
|-------------------|
| 8 | 32| | 8 |
|-------------------|
| 4 | 16 | 8 | 2 |
|-------------------|
| 4 | | | |
|-------------------|
```
# Note
**Look at the 2nd falsy test case: When there is an empty value (or a 0) somewhere and even when it's followed by a value which is higher than the last non-zero number, this should be falsy, because the next value after the zero would be higher than the 0 itself, which makes it invalid.**
Good luck!
[Answer]
# [Haskell](https://www.haskell.org/), 21 bytes
```
all$scanr1 max>>=(==)
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P802MSdHpTg5Ma/IUCE3scLOzlbD1lbzf6JtdLShmY6FjomOSaxOtIEOGAJZIBEIy9gIKA1ixnIl4VZtAFKPqjo3MTNPwVahoCgzr0RBBWhrgUKaQnSiTlLsfwA "Haskell – Try It Online")
Takes a list of columns, with empty spaces as 0.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes
```
€{íQ
```
[Try it online!](https://tio.run/##MzBNTDJM/f//UdOa6sNrA///j442NNOx0DHRMYrViQYiMxMdYyMgAjItgOJGsbEA "05AB1E – Try It Online")
Same as my other two answers. I promise this is my last one until others have answered :)
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), ~~7~~ 4 bytes
Takes 4-by-4 matrix, using 0 for blanks, as argument.
```
⊢≡⌊⍀
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///3z0/P@VR24RHPV2PehsedS581LUIIqjwqG8qUMJEweRR7xZDMwUDBTMTBQsgNFAwNgJSJhAGCBqAIBc2TYZGFiBtYA0gNlQnUMYCqM8Ej05U64ACJNtnDFKIaRsA "APL (Dyalog Unicode) – Try It Online")
`⌊⍀` is the vertical cumulative minimum
`≡` identical to
`⊢` the unmodified argument?
[Answer]
# R (+pryr), 23 bytes
```
pryr::f(all(diff(x))<1)
```
Which evaluates to the function
```
function (x)
all(diff(x)) < 1
```
Which takes a matrix as input:
```
[,1] [,2] [,3] [,4]
[1,] 16 0 64 8
[2,] 8 0 32 8
[3,] 4 0 32 2
[4,] 2 0 0 0
```
When given a matrix, `diff` automatically calculates the differences within rows (surprisingly. I didn't know of this feature until I tried it for this challenge).
```
[,1] [,2] [,3] [,4]
[1,] -8 0 -32 0
[2,] -4 0 0 -6
[3,] -2 0 -32 -2
```
None of these values can be 1 or higher in a good board, so we test for `<1` and see if `all` values of the matrix comply.
```
[,1] [,2] [,3] [,4]
[1,] TRUE TRUE TRUE TRUE
[2,] TRUE TRUE TRUE TRUE
[3,] TRUE TRUE TRUE TRUE
[1] TRUE
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
Ṣ€U⁼
```
[Try it online!](https://tio.run/##y0rNyan8///hzkWPmtaEPmrc8////@hoQzMdCx0THaNYnWggMjPRMTYCIiDTAihuFBsLAA "Jelly – Try It Online")
Input as an array of columns. Works with arbitrary-sized grids.
[Answer]
# [Python 3](https://docs.python.org/3/), 42 bytes
```
lambda l:all(x==sorted(x)[::-1]for x in l)
```
[Try it online!](https://tio.run/##DchBCoAgEEDRq8xSYVqkEiF4EnNhmBRMGubCTm/CW3z@89UzJ9mj2Tr5ew8eSHsi1ox5c6lHYI1brafZxVygwZWAeH/KlSqLzNp5wRUVCod2WBRKMYxcxxfOcd5/ "Python 3 – Try It Online")
Same algorithm as my Jelly answer
[Answer]
# JavaScript, 37 bytes
```
x=>''+x==x.map(v=>v.sort((x,y)=>y-x))
```
Call it like this:
```
|-------------------|
| 16 | | 64 | 8 |
|-------------------|
| 8 | | 32 | 8 |
|-------------------|
| 4 | | 32 | 2 |
|-------------------|
| 2 | | | |
|-------------------|
f([[8,8,2,0],[64,32,32,0],[0,0,0,0],[16,8,4,2]])
```
Tested on Firefox, Chrome, JavaScript Shell, and, Node.js.
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 71 bytes
```
i=>{for(int n=3;++n<i.Length;)if(i[n]>i[n-4])return false;return true;}
```
[Try it online!](https://tio.run/##NY6xasNAEET7/YotJXw2sSyM4Cw1gVROlSKFUHE@r5wFec/cnWKM0LcrspLAsMObLWZsWFvnaeoDywU/HiHSVYOYK4WbsYQygO1MCHgbIEQT2eK34zO@G5YkHeCtF3tgiXWjTs51FcY7SXzkBZYTl9XQOp/Mb5Ryp1crOfDmSHKJXzrlNuFammo@67xJPcXeC7amC6T/IPqe9DhpWArw5Iw/Y4lC97qBAbZ7hS8K97nCQkGxwC5TOOfw9Bm32RxnCn7pKRg1vDoJrqPNp@dIRxZK/lcnS0eaahjHcfoB "C# (.NET Core) – Try It Online")
The BORING way. Expects input flattened into a linear array.
Alternatively the explicitly forbidden way:
```
i=>{for(int n=3;i[++n]<=i[n-4];);}
```
[Try it online!](https://tio.run/##XY3BCsIwEETv@xV7bDGCtkUKaQQ/wJPH0kOMURbspjRRKSHfXrXgRZjLY3gzxq@NG@388MQ3PE0@2F4C6976QRuLHMHctfc4RPBBBzL4dHTBoybO8ggHE8hxQxzabo/hZTlMVY1qJrWPVzdmnwZZlZLa1Yq7RlHL66qTuUyzhEXDs9PjBRWyfbUdRNjuBG4E7iqBtYB6gbL4g0JAscA3kCT8vrNlLpeQUprf "C# (.NET Core) – Try It Online")
Throws an IndexOutOfBoundsException to indicate true, ends normally to indicate false. I tried a version that included conversion from exception/no exception to true/false, but it ended up just as long as the regular version.
[Answer]
# JavaScript, ~~34~~, 32 bytes
```
v=>!v.some((x,i)=>i%4&&x>v[i-1])
```
Call by passing in a single array containing the first column, followed by the 2nd, 3rd, and 4th.
Compares each number to the previous number except for the first number of each column and returns true if all are true.
## Test
```
f=v=>!v.some((x,i)=>i%4&&x>v[i-1])
f([16,8,4,2,0,0,0,0,64,32,32,0,8,8,2,0])
f([16,8,4,4,128,128,16,0,64,32,8,0,32,8,2,0])
f([16,8,32,2,0,0,0,0,64,32,128,0,8,16,2,0])
f([16,8,4,4,128,32,16,0,64,0,8,0,32,8,2,0])
```
Edit: saved 2 bytes thanks to tsh
[Answer]
# [Haskell](https://www.haskell.org/), 28 bytes
```
all$and.(zipWith(>=)=<<tail)
```
There's also
```
all$(==)=<<sort
```
with 15 bytes but it requires `import Data.List` when working with the Prelude only. Alternatively,
```
all$(==)=<<Data.List.sort
```
with 25 bytes works in GHCI.
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), ~~3~~ 6 bytes
+3 bytes because apparently I didn't know how my language worked
```
ọ¦_ẏ⁇!
```
This is a function accepting a list of columns and leaving the result on the stack.
A few other 6 byte solutions exist including `0+¦o¦ẏ` and `ọ¦_ẏ¦ỵ`.
[Try it online!](https://tio.run/##S0/MTPz//@Hu3kPL4h/u6n/U2K74P/VR28T/0dGGZgoWCiYKJrEK0YZGFgrGRgpAEQMgz8xEwQAoBWICBS0UjIDMWAA "Gaia – Try It Online")
### Explanation
```
ọ¦ Deltas of each column
_ Flatten
ẏ⁇ Keep only positive numbers
! Negate (is it empty?)
```
[Answer]
# TI-BASIC, 25 bytes
Takes input as a 4x4 matrix in Ans.
```
For(R,1,3
*row+(-1,Ans,R+1,R
End
Ans=abs(Ans
```
# Explanation
```
For(R,1,3 Loop from row 1 to 3.
*row+(-1,Ans,R+1,R Multiply row R+1 by -1 and add it to row R in-place.
Effectively, this subtracts row R+1 from row R.
End Now the first 3 rows contain the row differences,
and the 4th row is non-negative assuming valid input.
Ans=abs(Ans Check whether every element in the matrix is equal to its
absolute value, or in other words, contains no negative values.
```
[Answer]
# [Haskell](https://www.haskell.org/), 41 bytes
```
f[x]=1>0
f(a:b:c)|a<b=1<0|1>0=f$b:c
all f
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/Py26ItbW0M6AK00j0SrJKlmzJtEmydbQxqAGKGibpgIU@p@bmJlnW1CUmVeikpiTo5AWHW1opmOhY6JjEqsTbaADhkAWSATCMjYCSoOYsf8B "Haskell – Try It Online")
Defines the point-free function `all f`, where `f` determines if a list is sorted.
[Answer]
# JavaScript (ES6), 42 bytes
Takes an array of columns; returns a (truthy) number or `false`.
```
a=>a.every(c=>c.reduce((r,n)=>r&&n<=r&&n))
```
---
# JavaScript (ES6), ~~54~~ 47 bytes
First attempt. Takes an array of columns; returns `true` or `false`.
```
a=>a.every(c=>c.slice(1).every((n,i)=>n<=c[i]))
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 4 bytes
```
SGX=
```
[Try it online!](https://tio.run/##y00syfn/P9g9wvb//@hoIx0DEIy1jjYB0sZGOkZApgWEaQFkGpoB2WYmQHYsAA "MATL – Try It Online")
Input as an array of rows, upside down.
```
S % sort columns
GX= % compare with input
% true if arrays are numerically equal
% (implicit) convert to string and display
```
[Answer]
# [Swift 4](https://swift.org/blog/swift-4-0-release-process/), ~~84~~ 77 bytes
```
func f(l:[[Int]]){print(l.filter{$0.reversed()==$0.sorted()}.count==l.count)}
```
**[Try it online!](http://swift.sandbox.bluemix.net/#/repl/598032d30ad1c117edec888a)**
[Answer]
# Dyalog APL, ~~21~~ ~~19~~ 15 bytes
```
∧/{⍵≡⍵[⍒⍵]}¨↓⍉⎕
```
[Try it online!](http://tryapl.org/?a=%7B%u2227/%7B%u2375%u2261%u2375%5B%u2352%u2375%5D%7D%A8%u2193%u2349%u2375%7D4%204%u237416%200%2064%208%208%200%2032%208%204%200%2032%202%202%200%200%200&run) (modified so it will run in tryapl)
Takes input as a 2D array.
## How?
* `⎕` input
* `⍉` transpose
* `↓` 2D array => 1D vector of 1D vectors
* `{ ... }¨` apply this to each member (argument `⍵`):
+ `⍵[⍒⍵]` `⍵` sorted descending
+ `⍵≡` equality with `⍵`
* `∧/` whether every element is `1`.
[Answer]
# Clojure, 30 bytes
```
(partial every? #(apply >= %))
```
[try it online](https://repl.it/Jypi/1)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~7~~ 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Takes input as a 2D array of columns. Empty cells are `0` or can be omitted if there are no other numbers in the column.
```
eUËnw
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ZVXLbnc&input=W1sxNiw4LDQsMl0sWzAsMCwwLDBdLFs2NCwzMiwzMiwwXSxbOCw4LDJdXQ)
```
eUËnw :Implicit input of 2D array U
e :Test for equality with
UË : Map U
n : Sort each by
w : Maximum
```
[Answer]
# Java 8, 69 bytes
```
b->{for(int[]c:b)for(int i=0,f=1;i<3;)if(c[i]<c[++i])f=0;return f>0;}
```
Well, as of this writing this beats the Swift solution, so there's that! Utterly straightforward. Input is an array of integer arrays, the inner arrays being columns of the board (upper squares first). Cast to `Function<int[][], Boolean>`.
[Answer]
# [MY](https://bitbucket.org/zacharyjtaylor/my-language/src/4b671194ff3f88262c0234b12e2bede1d55086b3/commands.txt?at=master&fileviewer=file-view-default), ~~66~~ ~~62~~ 20 bytes (noncompeting)
```
ω⍉ω⍉A6ǵ'ƒ⇹(E8ǵ'ƒ⇹(Π←
```
[Try it online!](https://tio.run/##y638//9856PeTjDhaHZ8q/qxSY/ad2q4WsCZ5xY8apvw////6GhDMx0DHTMTHYtYnWgLINPYCMw0gTCNgEwjIBMIY2MB)
The reason this is non competing is that I recently implemented `8E (≡)`, which is equivalent to APL `≡`.
## How?
* `ω⍉` The first command line argument transposed
* `ω⍉` The first command line argument transposed
* `A6ǵ'` push `chr(0x6A)` (`⍖` in the codepage, which sorts descending)
* `ƒ` as a function, rather than a string
* `⇹` push a function that maps a popped function over each argument
* `(` apply
* `E8ǵ'ƒ⇹(` the same thing, except with `chr(0x8E)`, which is the match command (`≡`).
* `Π` product
* `←` output with no newline
Yes, a lot of MY's symbols are exactly the same or similar to APL's. The explanation is that they came to mind when I wanted a 1-character command. (I don't know why I didn't use **T** for transpose)
[Answer]
# Mathematica, 27 bytes
`t=Thread;-t[Sort/@-t@#]==#&`
## Explanation:
* `Thread` is a weird general transpose-like operation that [happens to
take the transpose when given a matrix](https://codegolf.stackexchange.com/questions/12900/tips-for-golfing-in-mathematica#comment89659_12922).
* `t=Thread;` lets me use `t` twice instead of `Thread` twice to
save bytes.
* `Sort` sorts a list (in increasing order).
* `Sort\@` maps the `Sort` function to each element of a list individually; when applied to a matrix, it sorts the rows.
* `t@#` applies the transpose function to the input `#` of the main function.
* `-` takes the negative of all of the entries so that sorting the rows of the transposed matrix (the columns of the original) sorts them in the desired way.
* The outer `-t[...]` undoes the negative and the transpose, so all we really did was sort the columns largest-to-smallest.
* `==#` tests to see if this new column-sorted matrix is equal to the original input.
* `&` ends the anonymous function with input `#` we defined.
---
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:
```
t=Thread;-t[Sort/@-t@#]==#&@{{16,128,64,32},{8,32,0,8},{4,16,8,2},{4,0,0,0}}
```
Or for all test cases:
```
t=Thread;-t[Sort/@-t@#]==#&//Map[#,{{{16,0,64,8},{8,0,32,8},{4,0,32,2},{2,0,0,0}},{{16,128,64,32},{8,128,32,8},{4,16,8,2},{4,0,0,0}},{{16,0,64,8},{8,0,32,16},{32,0,128,2},{2,0,0,0}},{{16,128,64,32},{8,32,0,8},{4,16,8,2},{4,0,0,0}}}]&
```
] |
[Question]
[
### Introduction
Let's observe this array: `[3, 2, 4, 1, 1, 5, 1, 2]`.
Each element displays the length of the substring which must be summed up. Let's take a look at the first element of the above array:
```
[3, 2, 4, 1, 1, 5, 1, 2]
^
```
The element at the first index is **3**, so we now take a substring of length three with the same index as the starting position:
```
[3, 2, 4]
```
When summed up, this results into **9**, so the first element of the **substring sum set** is `9`.
We do this for all the elements in the array:
```
3 -> [3, 2, 4]
2 -> [2, 4]
4 -> [4, 1, 1, 5]
1 -> [1]
1 -> [1]
5 -> [5, 1, 2]
1 -> [1]
2 -> [2]
```
You can see that the number **5** is a bit of a weird case. That number exceeds the length of the array:
```
[3, 2, 4, 1, 1, 5, 1, 2]
^ ^ ^ ^ ^
```
We'll ignore everything that exceeds the array, so we just use `[5, 1, 2]`.
The last step is to sum everything up:
```
[3, 2, 4] -> 9
[2, 4] -> 6
[4, 1, 1, 5] -> 11
[1] -> 1
[1] -> 1
[5, 1, 2] -> 8
[1] -> 1
[2] -> 2
```
And that is the array that needs to be outputted:
```
[9, 6, 11, 1, 1, 8, 1, 2]
```
### The Task
Given an non-empty array with positive (non-zero) integers, output the **substring sum set**. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the submission with the smallest number of bytes wins!
### Test cases
```
[1, 2, 3, 4, 5] -> [1, 5, 12, 9, 5]
[3, 3, 3, 3, 3, 3, 3, 3] -> [9, 9, 9, 9, 9, 9, 6, 3]
[5, 1, 2, 4, 1] -> [13, 1, 6, 5, 1]
[1] -> [1]
```
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ṫJḣ"ḅ1
```
[Try it online!](http://jelly.tryitonline.net/#code=4bmrSuG4oyLhuIUx&input=&args=WzMsIDIsIDQsIDEsIDEsIDUsIDEsIDJd) or [verify all test cases](http://jelly.tryitonline.net/#code=4bmrSuG4oyLhuIUxCsOH4oKsRw&input=&args=WzEsIDIsIDMsIDQsIDVdLCBbMywgMywgMywgMywgMywgMywgMywgM10sIFs1LCAxLCAyLCA0LCAxXSwgWzFd).
### How it works
```
ṫJḣ"ḅ1 Main link. Argument: A (array)
J Index; yield the 1-based indices of A.
ṫ Tail; map k to the postfix of A that begins with the k-th element.
ḣ" Vectorized head; for each k in A, truncate the corr. postfix to length k.
ḅ1 Convert the resulting slices from base 1 to integer.
```
[Answer]
# Python, 40 bytes
```
f=lambda x:x and[sum(x[:x[0]])]+f(x[1:])
```
Test it on [Ideone](http://ideone.com/cw3R0H).
[Answer]
# Excel, 21 bytes
`=SUM(OFFSET(A1,,,A1))`
Open a new spreadsheet, put the test values in column A. Enter the formula in B1 and double click the cell handle to ride the range.
[Answer]
## Python 3, 47 bytes
```
lambda X:[sum(X[i:i+k])for i,k in enumerate(X)]
```
Pretty straightforward implementation. Python's default behavior for slices that go past the end of the list was *very* convenient here.
[Answer]
# Haskell, ~~34~~, 33 bytes
```
f l@(x:y)=sum(take x l):f y
f x=x
```
One byte saved by nimi.
[Answer]
# JavaScript ES6, 50 bytes
```
a=>a.map((e,i)=>a.slice(i,i+e).reduce((a,b)=>a+b))
```
Pretty self-explanatory. It `map`s over each element in the array, getting the `slice` from that `i`ndex through the index plus that `e`lement's value, and `reduce`ing by adding.
```
f=
a=>a.map((e,i)=>a.slice(i,i+e).reduce((a,b)=>a+b))
;[
[3, 2, 4, 1, 1, 5, 1, 2],
[1, 2, 3, 4, 5],
[3, 3, 3, 3, 3, 3, 3, 3,],
[5, 1, 2, 4, 1],
[1]
].forEach(function(test){
document.getElementById('p').textContent += test + ' => ' + f(test) + '\n';
});
```
```
<pre id="p"></pre>
```
[Answer]
# J, 11 bytes
```
+/@{."_1]\.
```
### Usage
```
f =: +/@{."_1]\.
f 3 2 4 1 1 5 1 2
9 6 11 1 1 8 1 2
f 1 2 3 4 5
1 5 12 9 5
```
### Explanation
```
+/@{."_1]\. Input: A
]\. Get each suffix of A from longest to shortest
{."_1 For each value in A, take that many values from its corresponding suffix
+/@ Sum that group of values taken from that suffix
Return the sums
```
[Answer]
# JavaScript (ES6), 45
`reduce` beaten again!
```
a=>a.map((v,i)=>eval(a.slice(i,v+i).join`+`))
```
```
F=
a=>a.map((v,i)=>eval(a.slice(i,v+i).join`+`))
;[[3, 2, 4, 1, 1, 5, 1, 2],
[1, 2, 3, 4, 5],
[3, 3, 3, 3, 3, 3, 3, 3,],
[5, 1, 2, 4, 1],
[1]].forEach(t=>console.log(t+' -> '+F(t)))
```
[Answer]
## [Retina](https://github.com/m-ender/retina), 38 bytes
Byte count assumes ISO 8859-1 encoding.
```
\d+
$*
M!&`\b1(1)*(?<-1>,1+)*
M%`1
¶
,
```
Input and output are comma-separated lists.
[Try it online!](http://retina.tryitonline.net/#code=JShHYApcZCsKJCoKTSEmYFxiMSgxKSooPzwtMT4sMSspKgpNJWAxCsK2Ciw&input=MSwyLDMsNCw1CjMsMiw0LDEsMSw1LDEsMgozLDMsMywzLDMsMywzLDMKNSwxLDIsNCwxCjE) (The first line enables a linefeed-separated test suite.)
[Answer]
# Mathematica ~~60~~ 55 bytes
```
Tr@Take[#,UpTo@#&@@#]&/@Drop[#,t-1]~Table~{t,Length@#}&
```
eg
```
f = %; f /@ {{1, 2, 3, 4, 5}, {3, 3, 3, 3, 3, 3, 3, 3}, {5, 1, 2, 4, 1}, {1}}
(* {{1, 5, 12, 9, 5}, {9, 9, 9, 9, 9, 9, 6, 3}, {13, 1, 6, 5, 1}, {1}} *)
```
Thanks @MartinEnder for shaving off 5 bytes :)
[Answer]
## 05AB1E, ~~11~~ 8 bytes
```
[D¬£Oˆ¦Ž
```
**Explanation**
```
[ # infinite loop
D # duplicate current list
¬ # get head of list
£ # get that many elements from list
O # sum
ˆ # add to global array
¦ # remove first element of list
Ž # break if stack is empty
# implicitly push and print global array
```
[Try it online](http://05ab1e.tryitonline.net/#code=W0TCrMKjT8uGwqbFvQ&input=WzMsIDIsIDQsIDEsIDEsIDUsIDEsIDJd)
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 8 bytes
```
.es:Qk+b
```
[Test suite.](http://pyth.herokuapp.com/?code=.es%3AQk%2Bb&test_suite=1&test_suite_input=%5B1%2C2%2C3%2C4%2C5%5D%0A%5B3%2C3%2C3%2C3%2C3%2C3%2C3%2C3%5D%0A%5B5%2C1%2C2%2C4%2C1%5D%0A%5B1%5D&debug=0)
Translation of [El's answer in Python](https://codegolf.stackexchange.com/a/86230/48934).
[Answer]
# Erlang, 69 bytes
```
f(A)->put(1,1),L=lists,[L:sum(L:sublist(A,put(1,get(1)+1),X))||X<-A].
```
Erlang's higher-order functions for lists do not receive the index of the current element. This uses the process dictionary to set the index of the current element.
[Answer]
## Pyke, ~~12~~ 7 bytes
```
FKo>i<s
```
[Try it here!](http://pyke.catbus.co.uk/?code=FKo%3Ei%3Cs&input=%5B3%2C+2%2C+4%2C+1%2C+1%2C+5%2C+1%2C+2%5D)
```
- o = 0
F - for i in input:
o - o+=1
> - input[o:]
i< - ^[:i]
s - sum(^)
```
[Answer]
# VBA, 160 bytes
```
Function e(g())
Dim h()
k=LBound(g)
l=UBound(g)
ReDim h(k To l)
On Error Resume Next
For i=k To l
For j=i To i+g(i)-1
h(i)=h(i)+g(j)
Next
Next
e=h
End Function
```
[Answer]
# [Matricks](https://github.com/jediguy13/Matricks), 25 bytes
Yay, finally a challenge I don't need new features for!
```
md{z:l-g:c;+c;q:c;};:1:l;
```
Run with: `python matricks.py substring.txt [[<input>]] 0`
Explanation:
```
m :1:l; #loop over entire input
#set each value to...
d{ } #the sum of...
z:l-g:c:+c;q:c; #the input cropped to
#the length of the value in the cell
```
[Answer]
# Pyth, 6 bytes
```
ms<~tQ
```
[Test suite](https://pyth.herokuapp.com/?code=ms%3C~tQ&test_suite=1&test_suite_input=%5B3%2C+2%2C+4%2C+1%2C+1%2C+5%2C+1%2C+2%5D%0A%5B1%2C+2%2C+3%2C+4%2C+5%5D%0A%5B3%2C+3%2C+3%2C+3%2C+3%2C+3%2C+3%2C+3%5D%0A%5B5%2C+1%2C+2%2C+4%2C+1%5D%0A%5B1%5D&debug=0)
This is a different solution from any others so far. It loops over the input, slicing an summing the initial values, then removing the first element of the stored input, and repeat.
Explanation:
```
ms<~tQ
ms<~tQdQ Implicit variable introduction
Implicit: Q = eval(input())
m Q Map d over the input, Q
< Qd Take the first d elements of Q
s Sum them
~tQ Afterwards, set Q to the tail of Q, removing the first element.
```
[Answer]
# Julia, 39 bytes
```
!x=x!=[]?[take(x,x[])|>sum;!x[2:end]]:x
```
[Try it online!](http://julia.tryitonline.net/#code=IXg9eCE9W10_W3Rha2UoeCx4W10pfD5zdW07IXhbMjplbmRdXTp4Cgpmb3IgeCBpbiAoWzMsMiw0LDEsMSw1LDEsMl0sIFsxLDIsMyw0LDVdLCBbMywzLDMsMywzLDMsMywzXSwgWzUsMSwyLDQsMV0sIFsxXSkKICAgIEBwcmludGYoIiUtMTdzIC0-ICVzXG4iLCB4LCAheCkKZW5k&input=)
[Answer]
## F#, ~~84~~ 82 bytes
```
let f(A:int[])=[for i in 0..A.Length-1->Seq.skip i A|>Seq.truncate A.[i]|>Seq.sum]
```
[Answer]
# JavaScript (ES6) - 79 Bytes
A recursive solution that does not use any of the Array methods:
```
f=([a,...t],n)=>a&&n?a+f(t,n-1):0;g=([a,...t],r=[])=>a?g(t,[...r,a+f(t,a-1)]):r
```
Testing:
```
f=([a,...t],n)=>a&&n?a+f(t,n-1):0;
g=([a,...t],r=[])=>a?g(t,[...r,a+f(t,a-1)]):r;
[
[3, 2, 4, 1, 1, 5, 1, 2],
[1, 2, 3, 4, 5],
[3, 3, 3, 3, 3, 3, 3, 3,],
[5, 1, 2, 4, 1],
[1]
].forEach(a=>console.log(''+g(a)));
```
[Answer]
## C#, 89 bytes
```
int[]s(List<int>a)=>a.Select((n,i)=>a.GetRange(i,Math.Min(n,a.Count-i)).Sum()).ToArray();
```
**pretty straight forward**
improvement ideas appreciated
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 27 bytes
```
.v|h~l(A:Tc?;A?)b:0&~b.h~+A
```
[Try it online!](http://brachylog.tryitonline.net/#code=LnZ8aH5sKEE6VGM_O0E_KWI6MCZ-Yi5ofitB&input=WzM6Mjo0OjE6MTo1OjE6Ml0&args=Wg) or [verify all test cases](http://brachylog.tryitonline.net/#code=Ons6MiZ3QE53fWEKLnZ8aH5sKEE6VGM_O0E_KWI6MiZ-Yi5ofitB&input=W1szOjI6NDoxOjE6NToxOjJdOlsxOjI6Mzo0OjVdOlszOjM6MzozOjM6MzozOjNdOls1OjE6Mjo0OjFdOlsxXV0).
### Explanation
```
.v Input = Output = []
| Or
h~l A is a list, its length is the value of the first element of the Input
(
A:Tc? The concatenation of A with another list T results in the Input
; Or
A? A = Input
)
b:0& Call recursively on Input minus the first element
~b. Output is the output of that call with an extra element at the beginning
h~+A That extra element is the sum of the elements of A
```
[Answer]
## Dyalog APL, 15 bytes
```
{+/¨⍵↑∘⌽¨⌽,\⌽⍵}
```
or
```
{⌽+/¨(-↑¨,\)⌽⍵}
```
[Answer]
# PHP program, 72 Bytes
```
<?foreach($a=$_GET[a]as$i=>$v)echo array_sum(array_slice($a,$i,$v)),"
";
```
call with `php-cgi -f <filename> 'a[]=3&a[]=2&a[]=4...`
+11 as a function:
```
function f($a){foreach($a as$i=>$v)$r[]=array_sum(array_slice($a,$i,$v));return$r;}
```
+9 without builtins:
```
function p($a){foreach($c=$r=$a as$i=>$v)for($k=$i;$k--;)if(--$a[$k]>0)$r[$k]+=$v;return$r;}
```
($c keeps the original values, $a counts down for each index, $r gets the sums)
-3 as program:
```
<?foreach($a=$r=$c=$_GET[a]as$i=>$v)for($k=$i;$k--;)if(--$c[$k]>0)$r[$k]+=$v;print_r($r);
```
[Answer]
# q (37 bytes)
```
{sum each(til[count x],'x)sublist\:x}
```
Example:
```
q){sum each(til[count x],'x)sublist\:x}3 2 4 1 1 5 1 2
9 6 11 1 1 8 1 2
```
[Answer]
## Javascript (using External Library) (66 bytes)
```
n=>_.From(n).Select((v,i)=>_.From(n).Slice(i,i+v).Sum()).ToArray()
```
Link to lib: <https://github.com/mvegh1/Enumerable>
Code explanation: \_.From is loading the input array into the library, which is basically LINQ for js. Then each item in the array is mapped according to the following predicate: Take the input, and slice it from current item index and take that index plus the current item's value. Then Sum up that subsequence. Convert the result to a native JS array and return it
[](https://i.stack.imgur.com/txiV2.png)
[Answer]
## Clojure, 63 bytes
```
(defn f[[b & r]](concat[(apply + b(take(dec b)r))](if r(f r))))
```
Uses pattern matching to decompose input argument in to the first and the rest of the arguments.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~17~~ ~~14~~ 13 bytes
```
fGy+!-R0<G*!s
```
### Explanation
[Try it online!](https://tio.run/##y00syfn/P829UltRN8jAxl1Lsfj//2hjHQUjHQUTHQVDMDIFk0axAA) Or [verify all test cases](https://tio.run/##y00syfn/PyHCmyvNu1JbUTfIwMZbS7GYyyXk//9oQx0FIx0FYx0FEx0F01iuaGMwBx0BJUx1FCBqgQoNgXzDWAA) (code modified to handle several inputs).
```
f % Take input implicitly. Indices of nonzero elements: this gives [1 2 ... n]
% where n is input size
G % Push input again
y % Push a copy of [1 2 ... n]
+ % Add. Gives [a+1 b+2...] where [a b...] is the input
! % Transpose into a column vector
- % Subtraction with broadcast. Gives 2D array
R % Keep upper triangular part, making the rest of entries 0
0< % True for negative entries. Each row corresponds to a substring sum.
% For each row, this gives true for the entries of the input that make up
% that substring sum. Each row is thus a mask to select entries of the input
G % Push input again
* % Multiply with broadcast. This multiplies the input times each row
!s % Sum of each row. Implicitly display
```
[Answer]
**C#, 94 bytes**
```
Console.Write(String.Join(",",a.Select((v,i)=>a.Skip(i).Take(v).Sum().ToString()).ToArray()));
```
Where a is an int[] that represents the input to be solved.
] |
[Question]
[
# Task
Your task is to convert strings like this:
```
abc^d+ef^g + hijk^l - M^NO^P (Ag^+)
```
To strings like this:
```
d g l N P +
abc +ef + hijk - M O (Ag )
```
Which is an approximation to abcd+efg + hijkl - MNOP (Ag+)
In words, raise the characters directly next to carets to the upper line, one character for one caret.
# Specs
* Extra trailing whitespaces in the output are allowed.
* No chained carets like `m^n^o` will be given as input.
* A caret will not be followed immediately by a space or by another caret.
* A caret will not be preceded immediately by a space.
* All carets will be preceded by at least one character and followed by at least one character.
* The input string will only contain printable ASCII characters (U+0020 - U+007E)
* Instead of two lines of output, you are allowed to output an array of two strings.
To those who speak regex: the input string will match this regex:
```
/^(?!.*(\^.\^|\^\^|\^ | \^))(?!\^)[ -~]*(?<!\^)$/
```
### Leaderboard
```
var QUESTION_ID=86647,OVERRIDE_USER=48934;function answersUrl(e){return"http://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"http://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]
# [V](https://github.com/DJMcMayhem/V), ~~15~~ 14 bytes
```
ÄÒ +òf^xxé kPj
```
[Try it online!](http://v.tryitonline.net/#code=w4TDkiArw7JmXnh4w6kga1Bq&input=YWJjXmQrZWZeZyArIGhpamtebCAtIE1eTk9eUCAoQWdeKyk)
A fairly straightforward solution. The *perfect* challenge for V!
Explanation:
```
Ä "Duplicate this current line
Ò "Replace this line with spaces
+ "Move to the beginning of the next line
ò ò "Recursively (The second ò is implicit):
f^ " Find a caret
xx " Delete two characters. The second will be saved into the main register
é " Insert a space
k " Move up
P " Paste from the main register
j " Move down
```
Conveniently, based on how the recursion works, this will run once for every single caret.
[Answer]
# Cheddar, ~~77~~ ~~72~~ 67 bytes
```
l->l.chars.vfuse.replace("^\n"," ").lines.map(j->"%-2s"%j).turn(3)
```
No regex!
I love this answer as it is a wonderful demonstration of Cheddar's abilities. Mainly thanks to the replace function added by Conor. The PR to dev was never made so the replace function only exists [on this branch](https://github.com/cheddar-lang/Cheddar/tree/string-stdlib) (update: I made the PR and now it's on the latest beta branch which you can install with `npm install -g cheddar-lang`)
I have found a way to golf it but unfortunately an oversight results in this happening when item lengths are not the same:
```
[" denifednud denifednug denifednul denifednuN denifednuP denifednu+ ", "abcdenifednu +efdenifednu + hijkdenifednu - Mdenifednu Odenifednu (Agdenifednu )"]
```
I could have saved a lot of bytes using regex, and in fact I *just* made regexes for Cheddar... the only problem is that there are no regex functions :/
## Explanation
```
l-> // Function take input as `l`
l.chars // Get array of chars in input
.vfuse // Join with newlines
.replace("^\n"," ") // Replace `^\n` with a space globally
.lines // Get the lines (see below for more details on what this returns)
.map(j-> // Loop through each "line" `j` is arg
"%-2s" // C-like printf format.
// think of as: padRight(j, " ", 2)
// see below for more details
% j // Pass j as the string to insert
).turn(3) // Turn the string 270 degrees (see below)
.vfuse // Vertically fuse to get result (this is not needed as we can output an array of the lines)
```
To get a better understanding. This is what `.lines` returns for `1^2`
```
["1", " 2"]
```
the `.turn` with rotate this:
```
1
2
```
into:
```
2
1
```
---
Another example which will make it more clear:
```
1
2
2
2
```
becomes:
```
2 2
1 2
```
### Why format?
What the `%-2s` is doing is pretty simple. `%` specifies we are starting a "format", or that a variable will be inserted into this string at this point. `-` means to right-pad the string, and `2` is the max-length. By default it pads with spaces. `s` just specifies it's a string. To see what it does:
```
"%-2s" % "a" == "a "
"%-2s" % " a" == " a"
```
[Answer]
# Perl, 21 + 1 = 22 bytes
```
say'';s/\^(.)/♥[A\1↓/
```
Run with the `-p` flag. Replace `♥` with a raw `ESC` byte (`0x1b`), and `↓` with a vertical tab (`0x0b`).
The vertical tab is Martin Ender’s idea. It saved two bytes! Thanks.
[Answer]
## JavaScript (ES6), ~~56~~ 55 bytes
```
s=>[/.(\^(.))?/g,/\^.(())/g].map(r=>s.replace(r,' $2'))
```
Regexps to the rescue of course. The first one replaces all characters with spaces, unless it finds a caret, in which case it deletes the caret and keeps the character after it. (These characters are guaranteed to exist.) The second is the obvious one to replace each caret and its following character with a space.
Edit: Saved 1 byte thanks to @Lynn who devised a way to reuse the replacement string for the second replace allowing the replace to be mapped over an array of regexps.
[Answer]
## Python 2, 73 bytes
```
l=['']*2;p=1
for c in input():b=c!='^';l[p]+=c*b;l[~p]+=' '*b;p=b
print l
```
No regex. Remembers if the previous character was `^`, and put the current character in the top or bottom line based on that, and a space in the other one.
[Answer]
# Python 3, ~~157~~ ~~101~~ ~~98~~ ~~85~~ ~~83~~ 74 bytes
This solution keeps track of whether the previous character was `^`, then decides whether to output to the first or second line based on that.
Outputs as an array of `['firstline', 'secondline']`.
```
a=['']*2
l=0
for c in input():x=c=='^';a[l]+=c*x;a[~l]+=' '*x;l=x
print(a)
```
*Saved ~~13~~ 15 bytes thanks to @LeakyNun!*
*Saved 7 bytes thanks to @Joffan!*
[Answer]
# Pyth, 17 bytes
```
CcsmX~Z1j;d;cQ\^2
Q input string
c \^ split on '^'
m map for sections d:
X ; insert a space at index:
~Z1 the old value of Z (initially 0), before setting Z to 1
into:
j;d the section joined on spaces
s concatenate
c 2 chop into groups of 2
C transpose
```
Returns an array of 2 strings. (Prepend `j` to join them with a newline.)
[Try it online](https://pyth.herokuapp.com/?code=CcsmX~Z1j%3Bd%3BcQ%5C%5E2&input=%22abc%5Ed%2Bef%5Eg+%2B+hijk%5El+-+M%5ENO%5EP+%28Ag%5E%2B%29%22).
[Answer]
# [MATL](https://github.com/lmendo/MATL), 18 bytes
```
94=t1YSt~&vG*cw~Z)
```
[**Try it online!**](http://matl.tryitonline.net/#code=OTQ9dDFZU3R-JnZHKmN3flop&input=J2FiY15kK2VmXmcgKyBoaWprXmwgLSBNXk5PXlAgKEFnXispJw)
```
94= % Take input implicitly. Create logical array of the same size that contains
% true for carets, false otherwise
t % Push a copy of this array
1YS % Circularly shift 1 unit to the right. This gives an array that contains true
% for the elements right after a caret (superindices), and false for the rest
t~ % Push a copy and negate
&v % Concatenate vertically. This gives a 2D, 2-row array
G* % Push the input again, multiply with broadcast. This gives a 2D array in
% which the first row contains the superindices (characters after a caret)
% and 0 for the rest; and the second row contains the non-superindices and
% 0 for the superindices
c % Convert to char
w % Swap. Brings to top the array containing true for carets and false otherwise
~ % Negate
Z) % Use as logical index to remove rows that contain carets. Display implicitly
```
[Answer]
# Ruby, 47 + 1 (`-n` flag) = 48 bytes
```
puts$_.gsub(/\^(.)|./){$1||" "},gsub(/\^./," ")
```
Run it like so: `ruby -ne 'puts$_.gsub(/\^(.)|./){$1||" "},gsub(/\^./," ")'`
[Answer]
# Python (2), ~~76~~ ~~68~~ 67 Bytes
*-5 Bytes thanks to @LeakyNun*
*-3 Bytes thanks to @KevinLau-notKenny*
*-1 Byte thanks to @ValueInk*
*-0 bytes thanks to @DrGreenEggsandIronMan*
```
import re
lambda i,s=re.sub:[s("(?<!\^).\^?"," ",i),s("\^."," ",i)]
```
This anonymous Lambda function takes the input string as its only argument and returns the two output lines separated by a newline. To call it give it a name by writing "f=" before it.
Pretty straightforward regex: The first part replaces the following by a space: any character and a ~~carrot~~ caret or only a char, but only if there is no caret before them. The second part replaces any caret in the string and the char after it by a space.
[Answer]
## Convex, 24 bytes
```
®(?<!\^).\^?"SòNê®\^."Sò
```
[Try it online!](http://convex.tryitonline.net/#code=wq4oPzwhXF4pLlxePyJTw7JOw6rCrlxeLiJTw7I&input=YWJjXmQrZWZeZyArIGhpamtebCAtIE1eTk9eUCAoQWdeKyk&args=YWJjXmQrZWZeZyArIGhpamtebCAtIE1eTk9eUCAoQWdeKyk)
[Answer]
# Retina, 16 bytes
```
S`^
\^(.)
♥[A$1↓
```
A port of my Perl answer, pointed out by Martin Ender. Replace `♥` by a raw `ESC` byte (`0x1b`) and `↓` with a vertical tab (`0x0b`).
[Answer]
# shell+TeX+catdvi, ~~51~~ 43 bytes
```
tex '\empty$'$1'$\end'>n;catdvi *i|head -n2
```
Uses `tex` to typeset some beautiful mathematics, and then uses `catdvi` to make a text representation. The head command removes junk (page numbering, trailing newlines) that is otherwise present.
*Edit: Why do the long, proper, thing and redirect to `/dev/null` when you can ignore sideeffects and write to a single letter file?*
---
## Example
Input: `abc^d+ef^g + hijk^l - M^NO^P (Ag^+)`
TeX output (cropped to equation):
[](https://i.stack.imgur.com/C5GnX.png)
Final output:
```
d g l N P +
abc +ef +hijk -M O (Ag )
```
---
Assumptions: Start in empty dir (or specifically a dir with no name ending in "i"). Input is a single argument to the shell script. Input is not an empty string.
Someone tell me if this is rule abuse, especially `catdvi`.
[Answer]
## Haskell, ~~74~~ ~~56~~ 55 bytes
```
g('^':c:r)=(c,' '):g r
g(c:r)=(' ',c):g r
g x=x
unzip.g
```
Returns a pair of strings. Usage example: `unzip.g $ "abc^d+e:qf^g + hijk^l - M^NO^P: (Ag^+)"` -> `(" d g l N P + ","abc +e:qf + hijk - M O : (Ag )")`
`g` makes a list of pairs, where the first element is the char in the upper line and the second element is the char in the lower line. `unzip` turns it into a pair of lists.
Edit: @xnor suggested `unzip` which saves 18 bytes. @Laikoni found one more byte to save. Thanks!
[Answer]
## Perl, 35 bytes
**34 bytes code + 1 for `-p`**
```
$_=s/\^(.)|./$1||$"/ger.s/\^./ /gr
```
### Usage
```
perl -pe '$_=s/\^(.)|./$1||$"/ger.s/\^./ /gr' <<< 'abc^d+ef^g + hijk^l - M^NO^P (Ag^+)'
d g l N P +
abc +ef + hijk - M O (Ag )
```
Note: This is exactly the same as [Value Ink](https://codegolf.stackexchange.com/users/52194/value-ink)'s answer which I spied afterwards. Will remove if needed as this doesn't really add to the Ruby solution.
[Answer]
## Java 8 lambda, ~~132~~ ~~128~~ 112 characters
```
i->{String[]r={"",""};for(char j=0,c;j<i.length();j++){c=i[j];r[0]+=c==94?i[++j]:32;r[1]+=c==94?32:c;}return r;}
```
The ungolfed version looks like this:
```
public class Q86647 {
static String[] printExponents(char[] input) {
String[] result = {"",""};
for (char j = 0, c; j < input.length(); j++) {
c = input[j];
result[0] += c == 94 ? input[++j] : 32;
result[1] += c == 94 ? 32 : c;
}
return result;
}
}
```
Outputs as an array, simply checking whether there is a caret and if so the next character will be put in the upper row, else there will be a space.
---
**Updates**
Replaced characters with their ascii values to save 4 characters.
Thanks to @LeakyLun for pointing out to use a char array as input instead.
Also thanks to @KevinCruijssen for switching the `int` to `char` to save some more characters.
[Answer]
# [Coconut](http://coconut-lang.org/), ~~122 114~~ 96 bytes
Edit: ~~8~~ 26 bytes down with help from Leaky Nun.
```
def e(s,l)=''==l and s or"^"==l[0]and l[1]+e(s+' ',l[2:])or' '+e(s+l[0],l[1:])
f=print..e$('\n')
```
So as I learned today python has a ternary conditional operator, or in fact two of them: `<true_expr> if <condition> else <false_expr>` and `<condition> and <true_expr> or <false_expr>` with last one coming with one char less.
A python conform version can be [ideoned](https://ideone.com/VNmlmT).
---
First attempt:
```
def e(s,l):
case l:
match['^',c]+r:return c+e(s+' ',r)
match[c]+r:return' '+e(s+c,r)
else:return s
f=print..e$('\n')
```
Calling with `f("abc^d+ef^g + hijk^l - M^NO^P (Ag^+)")` prints
```
d g l N P +
abc +ef + hijk - M O (Ag )
```
Anyone tried golfing in coconut yet? It enriches python with more functional programming concepts like the pattern matching and function concatenation (with `..`) used above. As this is my first try at coconut, any tips would be appreciated.
This could definitely be shortened as any valid python code is also valid coconut and shorter python answers have been posted, however I tried to find a purely functional solution.
[Answer]
## Dyalog APL, 34 bytes
```
{(0 1=⊂b/¯1⌽b){⍺\⍺/⍵}¨⊂⍵/⍨b←⍵≠'∧'}
```
It returns a two-element vector with the two lines
Sample run (the uparrow in front is to format the two-el. vector for human consumption):
```
↑{(0 1=⊂b/¯1⌽b){⍺\⍺/⍵}¨⊂⍵/⍨b←⍵≠'∧'}'abc∧d+ef∧g + hijk∧l - M∧NO∧P (Ag∧+)'
d g l N P +
abc +ef + hijk - M O (Ag )
```
[Answer]
## PowerShell v2+, ~~88~~ 83 bytes
```
-join([char[]]$args[0]|%{if($c){$_;$b+=' '}elseif($_-94){$b+=$_;' '}$c=$_-eq94});$b
```
A little longer than the others, but showcases a little PowerShell magic and a little different logic.
Essentially the same concept as the Python answers -- we iterate over the input character-by-character, remember whether the previous one was a caret (`$c`), and put the current character into the appropriate spot. However, the logic and method for determining where to output is handled a little differently, and without a tuple or separate variables -- we test if the previous character was a caret, and if so output the character to the pipeline and concatenate a space onto `$b`. Otherwise we check if the current character is a caret `elseif($_-94)` and so long as it's not, we concatenate the current character onto `$b` and output a space to the pipeline. Finally, we set whether the current character is a caret for the next go-round.
We gather those characters from the pipeline together in parens, encapsulate them in a `-join` which turns them into a string, and leave that along with `$b` on the pipeline. Output at the end is implicit with a newline inbetween.
For comparison, here's a direct port of @xnor's [Python answer](https://codegolf.stackexchange.com/a/86676/42963), at **85 bytes**:
```
$a=,''*2;[char[]]$args[($l=0)]|%{$a[!$l]+="$_"*($c=$_-ne94);$a[$l]+=' '*$c;$l=!$c};$a
```
[Answer]
# Gema, ~~42~~ 41 characters
```
\^?=?@set{s;$s }
?=\ @append{s;?}
\Z=\n$s
```
Gema processes input as stream, so you have to solve it in one pass: first line is written immediately as processed, second line is collected in variable $s, then output at the end.
Sample run:
```
bash-4.3$ gema '\^?=?@set{s;$s };?=\ @append{s;?};\Z=\n$s' <<< 'abc^d+ef^g + hijk^l - M^NO^P (Ag^+)'
d g l N P +
abc +ef + hijk - M O (Ag )
```
[Answer]
# Cinnamon Gum, 21 bytes
```
0000000: 5306 6533 bd92 d1db 8899 8381 a2f8 8f8c S.e3............
0000010: 1230 249e a1 .0$..
```
Non-competing. [Try it online.](http://cinnamon-gum.tryitonline.net/#code=MDAwMDAwMDogNTMwNiA2NTMzIGJkOTIgZDFkYiA4ODk5IDgzODEgYTJmOCA4ZjhjICBTLmUzLi4uLi4uLi4uLi4uCjAwMDAwMTA6IDEyMzAgMjQ5ZSBhMSAgICAgICAgICAgICAgICAgICAgICAgICAgICAgLjAkLi4&input=YWJjXmQrZWZeZyArIGhpamtebCAtIE1eTk9eUCAoQWdeKyk)
## Explanation
I'm not much of a regex golfer so there's probably a better way to do this.
The string decompresses to:
```
S(?<!\^)[^^]& &\^&`S\^.&
```
(note the trailing space)
The first `S` stage receives input and uses a negative lookbehind to replace all characters other than carets with no preceding caret with a space, then deletes all carets. Then it immediately outputs the modified input string with a newline and removes that `S` stage. Since STDIN is now exhausted and the previous stage didn't provide any input, the next `S` stage receives the last line of STDIN again and then replaces all carets followed by any character with a space and outputs that.
In Perl psuedo-code:
```
$first_stage_sub_1 = ($input =~ s/(?<!\^)[^^]/ /gr);
$first_stage_sub_2 = ($first_stage_sub_1 =~ s/\^//gr);
print $first_stage_sub_2, "\n";
$second_stage_sub = ($input =~ s/\^./ /gr);
print $second_stage_sub, "\n";
```
[Answer]
# [J](http://jsoftware.com/), ~~28~~ 27 bytes
```
0|:t#]{."0~_1-_1|.t=.'^'~:]
```
[Try it online!](https://tio.run/##y/r/P81WT8GgxqpEObZaT8mgLt5QN96wRq/EVk89Tr3OKvZ/anJGvkKagnpiUnJcinZqWly6grZCRmZWdlyOgq6Cb5yff1yAgoZjepy2pvp/AA)
```
t=.'^'~:] 0 for ^, 1 for the rest, define t
_1|. Shift right, now zeroes are for superscripts
]{."0~_1- Prepend that many spaces to each character
t# Remove the rows with carets
0|: Transpose
```
There must be a better way...
] |
[Question]
[
# Preface
In the well known carol, [The Twelve Days of Christmas](https://en.wikipedia.org/wiki/The_Twelve_Days_of_Christmas_(song)), the narrator is presented with several gifts each day. The song is *cumulative* - in each verse, a new gift is added, with a quantity one higher than the gift before it. One Partridge, Two Turtle Doves, Three French Hens, and so on.
At any given verse, **N**, we can calculate the cumulative sum of presents so far in the song by finding the **N**th [tetrahedral number](http://oeis.org/A000292), which gives the results:
```
Verse 1: 1
Verse 2: 4
Verse 3: 10
Verse 4: 20
Verse 5: 35
Verse 6: 56
Verse 7: 84
Verse 8: 120
Verse 9: 165
Verse 10: 220
Verse 11: 286
Verse 12: 364
```
For example, after verse 4, we've had **4\*(1 partridge)**, **3\*(2 turtle doves)**, **2\*(3 French hens)** and **1\*(4 calling birds)**. By summing these, we get `4(1) + 3(2) + 2(3) + 1(4) = 20`.
# The Challenge
Your task is to write a program or function which, given a positive integer representing the number of presents **364 ≥ p ≥ 1**, determines which day (verse) of Christmas it is.
For example, if **p = 286**, we are on the 11th day of Christmas. However, if **p = 287**, then the next load of presents has begun, meaning it is the 12th day.
Mathematically, this is finding the next tetrahedral number, and returning its position in the whole sequence of tetrahedral numbers.
**Rules:**
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest solution (in bytes) wins.
* Standard golfing loopholes apply.
* When it comes to days, your program must be 1-indexed.
* Your submission must be a full program or a function - but not a snippet.
# Test Cases
```
1 -> 1
5 -> 3
75 -> 7
100 -> 8
220 -> 10
221 -> 11
364 -> 12
```
[Answer]
# [Python](https://docs.python.org/2/), 27 bytes
```
lambda n:int((n*6)**.33359)
```
[Try it online!](https://tio.run/nexus/python2#Tc29DoIwEADg2T7F6URrNdZajI3dfAQ3dajQkiZymMIAi6@OoME4XC73911hrv3DlvfcAuqATZIgSyljaymlOtDem2nKgxE6MCZX4TjsWMxXL58M7aWghDzjcAyLU/DeRYeZAx@rEqKbyqzKnV4QX0VACAjRYuESwWWqqAYya82AUTLrTPHJwUM7N53@wshb3v2@nF3dQGZrV/@LF8EV3ysuNhu@HWM76rubhskY5f4N)
A direct formula with some curve-fitting, same as [the original one](https://codegolf.stackexchange.com/a/108394/20260) found by Level River St.
The shifted equation `i**3-i==n*6` is close to `i**3==n*6` for large `i`. It solves to `i=(n*6)**(1/3)`. Taking the floor the rounds down as needed, compensating for the off-by-one.
But, there are 6 inputs on boundaries where the error takes it below an integer it should be above. All of these can be fixed by slightly increasing the exponent without introducing further errors.
---
## [Python](https://docs.python.org/2/), 38 bytes
```
f=lambda n,i=1:i**3-i<n*6and-~f(n,i+1)
```
The formula `n=i*(i+1)*(i+2)/6` for tetrahedral numbers can be more nicely written in `i+1` as `n*6=(i+1)**3-(i+1)`. So, we find the lowest `i` for which `i**3-i<n*6`. Each time we increment `i` starting from 1, the recursive calls adds `1` to the output. Starting from `i=1` rather than `i=0` compensates for the shift.
[Answer]
# [J](http://jsoftware.com/), 12 bytes
```
2>.@-~3!inv]
```
There might be a golfier way to do this, but this is a lovely opportunity to use J's built-in function inversion.
[Try it online!](https://tio.run/nexus/j#@5@mYGulYGSn56BbZ6yYmVcW@z81OSNfIU0hNTE5Q8FQwVTB3FTB0MBAwcgIhA0VjM1M/gMA "J – TIO Nexus")
### How it works
```
2>.@-~3!inv] Monadic verb. Argument: n
] Right argument; yield n.
3 Yield 3.
!inv Apply the inverse of the ! verb to n and 3. This yields a real number.
x!y computes Π(y)/(Π(y-x)Π(x)), where Π is the extnsion of the
factorial function to the real numbers. When x and y are non-negative
integers, this equals yCx, the x-combinations of a set of order y.
>.@-~ Combine the ceil verb (>.) atop (@) the subtraction verb (-) with
swapped arguments (~).
2 Call it the combined verbs on the previous result and 2.
```
[Answer]
# [Python](https://docs.python.org/3/), 22 bytes
```
lambda n:n**.3335//.55
```
Heavily inspired by [@xnor's Python answer](https://codegolf.stackexchange.com/a/108400/12012).
[Try it online!](https://tio.run/nexus/python3#TY3BDoIwEETP8BVzIZRaQKjFhIhHv8JLDa0ScDUF4@dj6cnDbnayM28sOlzXST9vvQa1xHkhpVRlWSi19sbiwihr42j0viqOvo9hMhg5l8gx4oQG3Mf8uQt/Z5aPIy9zr2L7ciAMBKfpblglIBu10fQ8G7fAeja6LnT8uTejEjj6qfZ7gboOK8QPW/ztBlpYmsge@RlJ3adIwEgEYJatPw "Python 3 – TIO Nexus")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~7~~ 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 byte thanks to Dennis (use vectorised minimum, `«`, and first index, `i`)
```
R+\⁺«i
```
**[TryItOnline](https://tio.run/nexus/jelly#@x@kHfOocdeh1Zn/j@453P6oaY37///RhjqmOuamOoYGBjpGRiBsqGNsZhILAA)**
### How?
Not all that efficient - calculates the 1st through to nth tetrahedral numbers in order in a list and returns the 1-based index of the first that is equal to or greater.
```
R+\⁺«i - main link: n
R - range [1,2,3,4,...,n]
+\ - cumulative reduce by addition [1,3,6,10,...,sum([1,2,3,4,...n])] i.e. triangle numbers
⁺ - duplicate previous link - another cumulative reduce by addition
[1,4,10,20,...,nth tetrahedral]
« - min(that, n) [1,4,10,20,...,n,n,n]
i - first index of n (e.g. if n=12:[1,4,10,12,12,12,12,12,12,12,12,12] -> 4)
```
---
Previous 7 byters using lowered range `[0,1,2,3,...,n-1]` and counting tetrahedrals less than n:
`Ḷ+\⁺<µS`,
`Ḷ+\⁺<ḅ1`,
`Ḷ+\⁺<ċ1`, and
`Ḷ+\⁺<¹S`
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
R‘c3<¹S
```
[Try it online!](https://tio.run/nexus/jelly#@x/0qGFGsrHNoZ3B/4/uOdz@qGmN@///hjoKpjoK5kBsaGCgo2BkBCaAosZmJgA "Jelly – TIO Nexus")
### How it works
```
R‘c3<¹S Main link. Argument: n
R Range; yield [1, ..., n].
‘ Increment; yield [2, ..., n+1].
c3 Combinations; yield [C(2,3), ..., C(n+1,3)].
<¹ Yield [C(2,3) < n, ..., C(n+1,3) < n].
S Sum; count the non-negative values of k for which C(k+2,3) < n.
```
[Answer]
## JavaScript (ES6), 33 bytes
```
n=>(F=k=>k<n?F(k+3*k/i++):i)(i=1)
```
Based on the recursive formula:
```
a(1) = 1
a(i) = (i + 3) * a(i - 1) / i
```
The second expression can also be written as ...
```
a(i) = a(i - 1) + 3 * a(i - 1) / i
```
... which is the one that we are using here.
`a(i - 1)` is actually stored in the `k` variable and passed to the next iteration until `k >= n`.
### Test cases
```
let f =
n=>(F=k=>k<n?F(k+3*k/i++):i)(i=1)
console.log(f(1)); // -> 1
console.log(f(5)); // -> 3
console.log(f(75)); // -> 7
console.log(f(100)); // -> 8
console.log(f(220)); // -> 10
console.log(f(221)); // -> 11
console.log(f(364)); // -> 12
```
[Answer]
# Ruby, 26 bytes
Edit: alternate version, still 26 bytes
```
->n{(n**0.3333*1.82).to_i}
```
Original version
```
->n{((n*6)**0.33355).to_i}
```
Uses the fact that `T(x) = x(x+1)(x+2)/6 = ((x+1)**3-(x+1))/6` which is very close to `(x+1)**3/6`.
The function simply multiplies by 6, finds a slightly tweaked version of the cube root (yes 5 decimal places are required) and returns the result truncated to an integer.
**Test program and output**
```
f=->n{((n*6)**0.33355).to_i}
[1,4,10,20,35,56,84,120,165,220,286,364].map{|i|p [i,f[i],f[i+1]]}
[1, 1, 2]
[4, 2, 3]
[10, 3, 4]
[20, 4, 5]
[35, 5, 6]
[56, 6, 7]
[84, 7, 8]
[120, 8, 9]
[165, 9, 10]
[220, 10, 11]
[286, 11, 12]
[364, 12, 13]
```
[Answer]
# JavaScript, ~~36~~ 33 bytes
*-3 bytes thanks to Luke (making the function curried)*
```
n=>f=i=>n<=i/6*-~i*(i+2)?i:f(-~i)
```
This is an unnamed lambda function which can be assigned to `func` and called with `func(220)()`, as described in [this meta post](http://meta.codegolf.stackexchange.com/a/11317/60919). My original, non-curried function looks like this:
```
f=(n,i)=>n<=-~i*i/6*(i+2)?i:f(n,-~i)
```
This answer uses the fact that **x**th tetrahedral number can be found with the following function:
\$f(x) = \frac{x}6(x+1)(x+2)\$
The function works by recursively increasing `i`, and finding `tetrahedral(i)`, until it's larger than or equal to `n` (the number of presents given).
When called with one argument as expected, `i = undefined`, and therefore is not larger than `n`. This means `f(n,-~i)` is executed, and `-~undefined` evaluates to `1`, which sets off the recursion.
---
## Test Snippet:
```
func = n=>f=i=>n<=i/6*-~i*(i+2)?i:f(-~i)
var tests = [1, 5, 75, 100, 220, 221, 364];
tests.forEach(n => console.log(n + ' => ' + func(n)()));
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~12~~ 11 bytes
```
`G@H+IXn>}@
```
[Try it online!](https://tio.run/nexus/matl#@5/g7uCh7RmRZ1fr8P@/oYEBAA)
### Explanation
```
` % Do...while
G % Push input, n
@ % Push iteration index (1-based), say m
H % Push 2
+ % Add
I % Push 3
Xn % Binomial coefficient with inputs m+2, 3
> % Is n greater than the binomial coefficient? If so: next iteration
} % Finally (execute after last iteration, before exiting the loop)
@ % Push last iteration index. This is the desired result
% End (implicit)
% Display (implicit)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
```
XµNÌ3c¹‹_½
```
[Try it online!](https://tio.run/nexus/05ab1e#@x9xaKvf4R7j5EM7HzXsjD@09/9/IyNDAA "05AB1E – TIO Nexus")
**Explanation**
```
Xµ # loop until counter equals 1
NÌ3c # binomial_coefficient(iteration_index+2,3)
¹ # push input
‹_ # not less than
½ # if true, increment counter
# output last iteration index
```
[Answer]
## Pyke, 11 bytes
```
#3RL+B6f)lt
```
[Try it here!](http://pyke.catbus.co.uk/?code=%233RL%2BB6f%29lt&input=1)
```
#3RL+B6f) - while rtn <= input as i:
3RL+ - i+j for j in range(3)
B - product(^)
6f - ^/6
lt - len(^)-1
```
[Answer]
# Mathematica, 26 bytes
```
(0//.i_/;i+6#>i^3:>i+1)-1&
```
Unnamed function taking a nonnegative integer argument and returning a nonnegative integer (yeah, it works for day `0` too). We want to find the smallest integer `i` for which the input `#` is at most `i(i+1)(i+2)/6`, which is the formula for the number of gifts given on the first `i` days. Through mild algebraic trickery, the inequality `# ≤ i(i+1)(i+2)/6` is equivalent to `(i+1) + 6# ≤ (i+1)^3`. So the structure `0//.i_/;i+6#>i^3:>i+1` starts with a `0` and keeps adding `1` as long as the test `i+6#>i^3` is satisfied; then `(...)-1&` subtracts `1` at the end (rather than spend bytes with parentheses inside the inequality).
If we let the 12 Days of Christmas continue, we can handle about 65536 days before the built-in recursion limit for `//.` halts the process ... that's about 4.7 \* 10^13 days, or about ten times the age of the universe thus far....
[Answer]
# [J](http://jsoftware.com/), 9 bytes
```
I.~3!2+i.
```
[Try it online!](https://tio.run/nexus/j#@5@mYGul4KlXZ6xopJ2px8WVmpyRr6Cho5emZKCpYKhgqmBuqmBoYKBgZATChgrGZib//wMA "J – TIO Nexus")
This is more inefficient than using the inverse of factorial but happens to be shorter.
For example, if the input integer is *n* = 5, make the range `[2, n+1]`.
```
2 3 4 5 6 choose 3
0 1 4 10 20
```
These are the first 5 tetrahedral numbers. The next step is to determine which interval (day) *n* belongs to. There are *n*+1 = 6 intervals.
```
0 (-∞, 0]
1 (0, 1]
2 (1, 4]
3 (4, 10]
4 (10, 20]
5 (20, ∞)
```
Then *n* = 5 belongs to interval 3 which is `(4, 10]` and the result is 3.
## Explanation
```
I.~3!2+i. Input: integer n
i. Range [0, n)
2+ Add 2 to each
3! Combinations nCr with r = 3
I.~ Interval index of n
```
[Answer]
# Python, 43 bytes
```
f=lambda n,i=0:n*6>-~i*i*(i+2)and-~f(n,i+1)
```
Saved 5 bytes thanks to [@FlipTack](https://codegolf.stackexchange.com/users/60919/fliptack) and another 3 thanks to [@xnor](https://codegolf.stackexchange.com/users/20260/xnor)!
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 12 bytes
```
1n@*6§X³-X}a
```
[Test it online!](http://ethproductions.github.io/japt/?v=1.4.3&code=MW5AKjanWLMtWH1h&input=MjIx) or [Verify all test cases at once](http://ethproductions.github.io/japt/?v=1.4.3&code=Tm1VezFuQCo2p1izLVh9YX0gcVI=&input=MQo1Cjc1CjEwMAoyMjAKMjIxCjM2NA==)
### How it works
```
1n@*6§X³-X}a // Implicit: U = input integer
@ }a // Find the smallest non-negative integer X which satisfies this condition:
X³-X // (X ^ 3) - X
§ // is greater than or equal to
*6 // U * 6.
1n // Subtract 1 from the result.
// Implicit: output result of last expression
```
This is a simplification of the tetrahedral formula several other answers are using:
```
f(x) = (x)(x + 1)(x + 2)/6
```
By substituting `x - 1` for `x`, we can simplify this considerably:
```
f(x) = (x - 1)(x)(x + 1) / 6
f(x) = (x - 1)(x + 1)(x) / 6
f(x) = (x^2 - 1)(x) / 6
f(x) = (x^3 - x) / 6
```
Therefore, the correct result is one less than the smallest integer `x` such that `(x^3 - x) / 6` is greater than or equal to the input.
13-byte solution, inspired by @xnor's [answer](https://codegolf.stackexchange.com/a/108400/61613):
```
p.3335 /.55 f
```
A few more solutions @ETHproductions and I played around with
```
J+@*6§X³-X}a
@*6§X³-X}a -1
@§X/6*°X*°X}a
_³-V /6¨U}a -1
§(°V nV³ /6?´V:ß
§(°VV³-V /6?´V:ß
```
Test it [here](http://ethproductions.github.io/japt/?v=1.4.3&code=QKdYLzYqsFgqsFh9YQ==&input=MzY0).
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 8 bytes
```
+\⍣2∘⍳⍳⊢
```
My first time using APL, thanks to [H.PWiz](https://chat.stackexchange.com/users/289893/h-pwiz) for [shortening it into a train](https://chat.stackexchange.com/transcript/message/52986161#52986161)
Essentially a port of [the Jelly answer](https://codegolf.stackexchange.com/a/108383/87923)
# Explanation
```
+\⍣2∘⍳⍳⊢
∘⍳ Numbers from 1 to input inclusive
+\ Cumulative reduce with addition, gets triangular numbers
⍣2 Repeat (does it again) to get the tetrahedral numbers
⍳⊢ Index of the input in that list
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQb/tWMe9S42etQx41HvZhDqWvQ/DSjxqLfP6FFXM1BdcVEykCzJyCz@n6ZgZGQAAA "APL (Dyalog Classic) – Try It Online")
[Answer]
# SmileBASIC, 43 bytes
```
INPUT X
WHILE X>P
I=I+1
R=R+I
P=P+R
WEND?I
```
`I` is the day, `R` is the `i`th triangular number, and `P` is the `i`th tetrahedral number (number of presents).
I think a similar answer in another language, perhaps:
`x=>{while(x>p)p+=r+=++i;return i}` could be pretty good.
[Answer]
# Python 3, ~~48~~ 46 bytes
```
f=lambda x,i=1:f(x,i+1)if(i+3)*i+2<x/i*6else i
```
[Answer]
# Mathematica, ~~31~~ 25 bytes
```
Floor@Root[x^3-x-6#+6,1]&
```
[Answer]
# Haskell, ~~21~~ 23 bytes
```
floor.(**(1/3)).(*6.03)
```
Edit: As xnor pointed out, the original solution (`floor.(/0.82).(**0.4)`) didn't work between the days of christmas
[Answer]
# [Itr](https://github.com/bsoelch/OneChar.js/blob/main/ItrLang.md), 11 bytes
`#äµS¹µS>S1+`
[online interpreter](https://bsoelch.github.io/OneChar.js/?lang=itr&src=I-S1U7m1Uz5TMSs=&in=MjIw)
# Explanation
```
# ; read a number `n` from standard input
ä ; duplicate that number
µ ; apply for all integers in the range [1,...,n]
S ; replace each element `k` of the range with the sum from 1 to `k`
¹ ; push all no-empty prefixes of that list
µS ; sum up the elements, this will give the list of the first `n` tetrahedral numbers
> ; vectorized comparison
S ; sum up, this will count the number of triangle numbers that are smaller than `n`
1+ ; offset by one to get the right number
```
[Answer]
## Batch, 69 bytes
```
@set/an=d=t=0
:l
@set/at+=d+=n+=1
@if %t% lss %1 goto l
@echo %n%
```
Manually calculates tetrahedronal numbers.
[Answer]
**Pyth 11 bytes**
```
/^Q.3335.55
```
[Try it online!](http://pyth.herokuapp.com/?code=%2F%5EQ.3335.55&input=286%0A%0A287&test_suite=1&test_suite_input=1%0A5%0A75%0A100%0A220%0A221%0A364&debug=0)
pretty much just translated [Dennis' answer](https://codegolf.stackexchange.com/a/108417/56201) into Pyth
[Answer]
**R, 19 characters**
```
floor((n*6)^.33359)
```
based on xnor's answer in `Python`.
[Answer]
## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 19 bytes
This steals @xnor 's formula:
```
:?int((a*6)^.33359)
```
I tried dialing down the resolution to .3336 to save a byte, but that fails on the final testcase.
[Answer]
# Bash + bc, 44 bytes
```
bc -l <<< "f=e(.33359*l($1*6));scale=0;f/1"
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 6 bytes
```
V≥¹∫∫ḣ
```
[Try it online!](https://tio.run/##yygtzv7/P@xR59JDOx91rAaihzsW////39wUAA "Husk – Try It Online") or [Verify all test cases](https://tio.run/##yygtzv5/aFvuo6bG/2GPOpce2vmoYzUQPdyx@P///9GGOqY65qY6hgYGOkZGIGyoY2xmEgsA "Husk – Try It Online")
## Explanation
```
V≥¹∫∫ḣ
ḣ range 1..n
∫∫ cumulative sum, twice
V index of first element that is
≥¹ greater than or equal to the input
```
] |
[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/58150/edit).
Closed 8 years ago.
[Improve this question](/posts/58150/edit)
In modern day standards *Golfing* translates to playing a game of *golf*, while *golf* itself translates to a car manufactured by Volkswagen.
So instead of the usual *golfing of code*, you will today be *coding a golf*.
## Challenge
Write a program (A) in language **A** which will output the source code of another program (B) of language **B**, which in it's turn will output `Vroom vrooom!` when executed.
## Rules
* The source code of program A is formatted into a nice ASCII car (not necessarily a volkswagen).
* Program A must be executable in the format you posted it in.
* Language A is ***NOT*** the same language as language B.
* The output of program B may or may not end with a new line.
* Program A takes no input.
* In non-obvious languages (esoteric) please explain program A.
* You must start your answer with `# Language A, Language B` eg. `# Brainfuck, Python`.
* Valid languages must have either an [English Wikipedia article](https://en.wikipedia.org/wiki/Lists_of_programming_languages), an [esolangs article](http://esolangs.org/wiki/Language_list) or a [Rosetta Code article](http://rosettacode.org/wiki/Category:Programming_Languages) at the time this challenge was posted.
* Be creative :-)
## Scoring
This is a popularity contest. Whichever answer has the most upvotes by Oct 4, will be declared the winner.
## Example
# Brainfuck, Python 2
```
++++++++++[>+++>
++++ ++>+++ ++++
+++< << -]>>>
++++++++++++. ++ .------
---.+++++.++++++.<<++.++.>++++++++++++++
++++++++++++.>--.---..--.<<--.>>+++++++++.
----.---...--.----------------------------
---------------------------------------
\--o--/ \--o--/
\-_./ \+_./
```
This outputs the following code, which can be executed in Python 2;
```
print "Vroom vrooom!"
```
[Answer]
## evil, JavaScript (ES6)
```
aeMeeeDDDeDDDwHwwwwwwDaeeaeae;.
.eu@wa04QMMM4WHHWWM#404HGV#0B4aeee0HeHa
.ewD&M%e aG##a aa a@Q%Bwaaeeuu4.
.uwuwW&u e&M&e H wB0B&uGMVBGuuGu
wuu@M0Bu wW@4Be ueu=w#H00%V%QG@W%eGa
...aa+aeeweWWaee#G&G%V@B@G0@B&00V0V0%4VB4%BQGeewwB%BwwwV0%HMwae
eaeee&BQM%M@4B%Mu%4G@BMwaeeaeeaawwaeeeuuuuwaaaeewwwuueee&QBeweaeMQ4e
,w#QawaHBH4Veaaaawueueeawaaeeeeuuwue&%#eeaeewaaawueewaeaeawueaQBBeeeHVewe.
.eeuu0waaeQMQ%0Waaaawaeaeeee+u<+<=<===->::w~<+<=~-:<><uuwaeeaee&@B&&uuwawaa.
aaaaaweaaQ#@4%@4#Veuuu~><uuw<-ewaaeueeaweeeeueweaeewaaaee-weH#V#%BBQ@0ueeawea
aeewuuu#QB4B4B&0W%QVeuweeeaeM4M%&0W&MG@M0QV%VB0M%W0M&#QQeae4%#G#Q%4#4Q#Vwu>uuw
wQWGuuwMHWVVuue<e%eQ4M4#@0BBWVHVVQ#4HG4%B%#&H@M#BMM0G0MVW0WQ44uwue.eueHGG#waHBe
e&H0ueeV%Heu0wu,GQu0BGWQVH40MM4@0H0BQMMHWW%weueeaawuuuuwuu#@4Hu@&w+MVw@4M%ueeB
%B0V&QW%MaVee>uwH%BW%4aeeeeueeuweaeeeeBMBGM&%H0QG&44#Mwe&#%VaWeeee~&Qw#V%G&wu.
eaeDD&WQ&eGu,.&&0H%04ewaeeaDeB%#HG&#H#BQQ#&#@0Vuw0HBMaD4H#G#eWDee%DaD.Ww
.u%.ue.4aaa.@Mw ,w&wDwwDwwue@a
eeHueMwa@Ge .uV&.eeDw.4u
"ee00V0e' "a@HB4wP
```
For the evil program, I used a similar method as I did for [this answer](https://codegolf.stackexchange.com/a/54833/4020). In summary, I generated an optimally short program (limited to [these four commands](https://codegolf.stackexchange.com/a/55428/4020)) that produced the desired JS, before mixing it with ignored characters to make a [Volkswagen golf](http://static.usnews.rankingsandreviews.com/images/Auto/izmo/369081/2015_volkswagen_golf_sideview.jpg).
It prints out the following JS program, which in turn prints out `Vroom vrooom!` to the console:
```
c=console
o = x=>c
.log(x+"om!");O=o
Q="Vroom\x20vroo";
(O) (Q)
```
[Answer]
# Common Lisp, BASIC (and Python)
I took inspiration from some nice [ASCII cars](http://www.retrojunkie.com/asciiart/vehicles/cars.htm).
Mine is a pickup truck seen from behind:
```
(if'(
(-----------------)
_( _______________ )_
(_( ( ) )_)
( (_______________) )
( )
(=======================)
(( MY OTHER CAR ))
(( IS A CDR ))
(-----------------------)
( ) ( )
(__) (__))
(lambda()(format t"~&PRINT ~S~%""Vroom vroom!")))
```
[Answer]
# CJam, C++
My car is a [1988 Pontiac Trans Am](https://en.wikipedia.org/wiki/Pontiac_Firebird_(third_generation)#1988). (I tried my best. :P)
```
"#"e####===========_
"inclu"+ e#\
"de " + "<iostream>"+e#+--.____ __..
N+N+"using"+" namespace "+"std;"+Ne#---" """"" """"" __'
+N+"int " +"main()"+
N+"{"+N+" "4*+"c" +"out << \"Vr"+e#====================.--"" ""--.=======:
e# [w] : / \ : |========================| : / \ : [w] :
"oom"+" vro"+ "oom!\";"+e#===============| :| |: _-"
N+"}"+e#___: \ / :_|=======================/_____: \ / :__-"
e#--------' ""____"" `-------------------------------' ""____""
```
You can test this [here](http://cjam.aditsu.net/#code=%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22%23%22e%23%23%23%23%23%23%23%23%23%23%23%23%23%23%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22inclu%22%2B%20%20%20%20%20%20%20%20%20%20%20%20%20%20e%23%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22de%20%22%20%20%20%2B%20%20%20%20%20%20%20%20%20%20%20%22%3Ciostream%3E%22%2Be%23%2B--.____%20%20%20%20__..%0A%20%20%20%20%20%20%20%20%20%20%20%20%20N%2BN%2B%22using%22%2B%22%20namespace%20%22%2B%22std%3B%22%2BNe%23---%22%20%22%22%22%22%22%20%20%20%20%20%20%20%22%22%22%22%22%20%20__'%0A%20%20%20%20%20%20%2BN%2B%22int%20%22%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%2B%22main()%22%2B%0A%20N%2B%22%7B%22%2BN%2B%22%20%224*%2B%22c%22%20%20%20%2B%22out%20%3C%3C%20%5C%22Vr%22%2Be%23%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D.--%22%22%20%20%22%22--.%3D%3D%3D%3D%3D%3D%3D%3A%0Ae%23%20%20%20%20%20%20%5Bw%5D%20%3A%20%2F%20%20%20%20%20%20%20%20%5C%20%3A%20%7C%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%7C%20%20%20%20%3A%20%2F%20%20%20%20%20%20%20%20%5C%20%3A%20%20%5Bw%5D%20%3A%0A%22oom%22%2B%22%20vro%22%2B%20%20%20%20%20%20%20%20%20%20%20%20%22oom!%5C%22%3B%22%2Be%23%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%7C%20%20%20%20%3A%7C%20%20%20%20%20%20%20%20%20%20%7C%3A%20%20%20_-%22%0A%20N%2B%22%7D%22%2Be%23___%3A%20%5C%20%20%20%20%20%20%20%20%2F%20%3A_%7C%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%2F_____%3A%20%5C%20%20%20%20%20%20%20%20%2F%20%3A__-%22%0A%20%20e%23--------'%20%20%22%22____%22%22%20%20%60-------------------------------'%20%20%22%22____%22%22).
## CJam
```
"#include <iostream>"N+N+"using namespace std;"+N+N+"int main()"N+"{"+N+" "4*+"cout << \"Vroom vrooom!\";"+N+"}"+
```
And you can test that, [here](http://cjam.aditsu.net/#code=%22%23include%20%3Ciostream%3E%22N%2BN%2B%22using%20namespace%20std%3B%22%2BN%2BN%2B%22int%20main()%22N%2B%22%7B%22%2BN%2B%22%20%224*%2B%22cout%20%3C%3C%20%5C%22Vroom%20vrooom!%5C%22%3B%22%2BN%2B%22%7D%22%2B).
## C++
```
#include <iostream>
using namespace std;
int main()
{
cout << "Vroom vrooom!";
}
```
[Answer]
## BrainFuck, Golf Script, Glee, JQ, Lasso, Lang5 & many more
```
++++++++++
[>+++ >+++++
+++>++ +++++++++<
<<-]>++ + +.>++++++.
<>>>>>>><<<<<<<><><><><><><>
>++++.---..--.<<--.>>+++++++--
++++.----.---...--.<<+.+.-----
-- --
| | | |
-- --
```
Output
>
> "Vroom vrooom!"
>
>
>
Which will be valid syntax for these language which will ouptut "Vroom vroom!"
Golf Script
Glee
J
JQ
Lasso
Lang5
m4
Ml/I
Salmon
TPP & many more
This list came from Rosetta code's Hello World Program
[Answer]
# Java, Python
```
public final class
Car{public static void main
(String ...a ){System
//CCCCC CCCC CCCCCCCC//
.out.println("print(\"Vroom"+
" vroom!\")");}}//HDBSKJBGIWE
///// /////
/// ///
```
(Sorry, the car's really bad)
] |
[Question]
[
# Background
*Person of Interest* is a crime drama on CBS, and my favorite TV show, as of late.
The show is about a man named Harold Finch, a billionaire programmer, and his partner John Reese, a special forces veteran and ex-CIA operative. This programmer created a sentient AI called "The Machine" that predicts violent crimes before they happen. It tracks every person on Earth at all times by monitoring and analyzing all surveillance cameras and electronic communications across the globe.
Harold built The Machine for the United States government to detect terrorist activity before-the-fact. It divides the crimes that it predicts into lists based on whether or not they are relevant to national security. The relevant cases are handled by the government, while the "irrelevant" list is programmed to be deleted daily.
Harold made a small backdoor for himself in hopes to deal with the "irrelevant" list, himself. This backdoor causes The Machine to call the payphone nearest Harold (once every day or so) and read a Social Security number to him. This SSN belongs to someone whose life is in danger as part of a premeditated crime, or of someone who is planning such a crime.
---
# The Challenge
Write a program that takes no input, and outputs 30 random phone numbers & SSNs (see below).
---
# Output
There are two lines of text that will be printed every "day".
1. `Crime predicted: 555-55-5555`
2. `Calling: 1-555-555-5555` followed by a newline
This process should repeat for one "month" (30 "days").
---
# Phone Numbers
Every phone number must have the following elements:
* Must have the United States country code (the first digit).
* Must have a random area code (first set of three digits).
* The first three digits of the phone number itself [should be `555`](https://en.wikipedia.org/wiki/555_(telephone_number)), followed then by 4 random digits.
Here is an annotated example:
```
1-814-555-3857
| | | |
| | | |
| | | +----------> random four digits
| | |
| | +--------------> the set 555
| |
| +------------------> area code
|
+---------------------> country code
```
---
# Social Security Numbers
Every SSN must be 9 random digits in the following format.
```
342-98-1613
```
---
# Example
```
Crime predicted: 234-72-8311
Calling: 1-633-555-0188
Crime predicted: 135-77-0910
Calling: 1-202-555-4719
Crime predicted: 722-90-6653
Calling: 1-466-555-1069
...
```
Continuing for 27 more cycles.
---
# Scoreboard
For your score to appear on the board, it should be in this format:
```
# Language, Bytes
```
Strikethroughs shouldn't cause a problem.
```
function getURL(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){$.ajax({url:getURL(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),useData(answers)}})}function getOwnerName(e){return e.owner.display_name}function useData(e){var s=[];e.forEach(function(e){var a=e.body.replace(/<s>.*<\/s>/,"").replace(/<strike>.*<\/strike>/,"");console.log(a),VALID_HEAD.test(a)&&s.push({user:getOwnerName(e),language:a.match(VALID_HEAD)[1],score:+a.match(VALID_HEAD)[2],link:e.share_link})}),s.sort(function(e,s){var a=e.score,r=s.score;return a-r}),s.forEach(function(e,s){var a=$("#score-template").html();a=a.replace("{{RANK}}",s+1+"").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SCORE}}",e.score),a=$(a),$("#scores").append(a)})}var QUESTION_ID=58199,ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],answer_ids,answers_hash,answer_page=1;getAnswers();var VALID_HEAD=/<h\d>([^\n,]*)[, ]*(\d+).*<\/h\d>/;
```
```
body{text-align:left!important}table thead{font-weight:700}table td{padding:10px 0 0 30px}#scores-cont{padding:10px;width:600px}#scores tr td:first-of-type{padding-left:0}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id="scores-cont"><h2>Scores</h2><table class="score-table"><thead> <tr><td></td><td>User</td><td>Language</td><td>Score</td></tr></thead> <tbody id="scores"></tbody></table></div><table style="display: none"> <tbody id="score-template"><tr><td>{{RANK}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SCORE}}</td></tr></tbody></table>
```
[Answer]
# CJam, ~~68~~ ~~66~~ 64 bytes
Thanks to Dennis for saving 2 bytes!
```
"Crime predicted: --
Calling: 1--555-
"30*{_5<{iAa*:mr}&}/
```
Copypasting won't work since there are a few unprintables (one in place of each random group), so here's an `xxd` dump:
```
00000000: 2243 7269 6d65 2070 7265 6469 6374 6564 "Crime predicted
00000010: 3a20 032d 022d 040a 4361 6c6c 696e 673a : .-.-..Calling:
00000020: 2031 2d03 2d35 3535 2d04 0a0a 2233 302a 1-.-555-..."30*
00000030: 7b5f 353c 7b69 4161 2a3a 6d72 7d26 7d2f {_5<{iAa*:mr}&}/
```
To reverse it, paste it into a file and launch `xxd -r in_file > out_file`. You can also [try it online](http://cjam.aditsu.net/#code=%22Crime%20predicted%3A%20%03-%02-%04%0ACalling%3A%201-%03-555-%04%0A%0A%2230*%7B_5%3C%7BiAa*%3Amr%7D%26%7D%2F).
# Explanation
```
"..."30* Push the string 30 times
{ ... }/ For each character in the string:
_5<{ ... }& If the ASCII code is < 5:
iAa* Push an array of as many 10s as the ASCII code
:mr For each 10, choose a random 0-9 number
```
[Answer]
## Python 2, 129
```
from random import*
print''.join([c,`randint(0,9)`][c>'w']for c in'Crime predicted: xxx-xx-xxxx\nCalling: 1-xxx-555-xxxx\n\n'*30)
```
A naive method. Takes the message
```
Crime predicted: xxx-xx-xxxx
Calling: 1-xxx-555-xxxx
```
and copies it 30 times. Then, replaces each `x` with a random digit `randint(0,9)`, keeping all other characters the same.
[Answer]
# Python 2, 151 bytes
Thank the lord (and @Dennis) for `%0nd` :D
```
from random import randrange as r
for i in[1]*30:print"Crime predicted: %03d-%02d-%04d\nCalling: 1-%03d-555-%04d\n"%(r(1e3),r(100),r(1e4),r(1e3),r(1e4))
```
[Answer]
# Perl, 85 Bytes, thanks to Dennis and grc!
```
$_="Crime Predicted: NNN-NN-NNNN
Calling: 1-NNN-555-NNNN
"x30;s/N/0|rand 10/eg;print
```
# Original Perl, 91 92 Bytes
```
print"Crime Predicted: NNN-NN-NNNN
Calling: 1-NNN-555-NNNN
"=~s/N/int rand 10/egr for 1..30
```
[Answer]
# CJam, ~~73~~ ~~71~~ 70 bytes
```
30{"Crime predicted: x-x-x
Calling: 1-x-555-x
"'x/[ZY4Z4]Aaf*::mr.+N}*
```
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=30%7B%22Crime%20predicted%3A%20x-x-x%0ACalling%3A%201-x-555-x%0A%22'x%2F%5BZY4Z4%5DAaf*%3A%3Amr.%2BN%7D*).
### How it works
```
30{ e# Repeat 30 times:
e# Push the following string:
"Crime predicted: x-x-x
Calling: 1-x-555-x
"
'x/ e# Split at x's.
[ZY4Z4] e# Push the array [3 2 4 3 4].
Aaf* e# For each integer in that array, repeat [10] that many times.
e# This pushes [[10 10 10][10 10][10 10 10 10][10 10 10][10 10 10 10]].
::mr e# For each 10, select a random integer between 0 and 9 (inclusive).
.+ e# Vectorized concatenation.
e# This places the digits at the spots of the x's.
N e# Push a linefeed.
}* e#
```
[Answer]
# ß, ~~121~~ ~~118~~ 112 bytes
```
°/N=1°(30°/M°=ß$-ß$$'Crime predicted: 000-00-0000\nCalling: 1-000-555-0000\n\n'),'',3)µ€(M='0')?ß!G0,9,1):M)°)°)
```
Basically replaces 0 with a random number each and calls itself 30 times.
Test it using the [online terminal](http://run.codegolf.xyz/):
```
sharps:~$ "<ctrl+v the code here>"
Crime predicted: 214-59-4707
Calling: 1-850-555-8529
Crime predicted: 722-97-6832
Calling: 1-864-555-6965
<and so on...>
```
Edit (112B): Using `$$` (something like sprintf) & ternary operator.
[Answer]
# Pyth, 66
```
V30sX"Crime Predicted: v-w-x
Calling: 1-y-555-z
">5GmjkmOTdj32434T
```
Uses `X` to translate the last 5 letters of the alphabet (`>5G == 'vwxyz'`) onto the 5 random numbers. Uses the same RNG as Sok found.
[Try it online here](http://pyth.herokuapp.com/?code=V30sX%22Crime+Predicted%3A+v-w-x%0ACalling%3A+1-y-555-z%0A%22%3E5GmjkmOTdj32434T&debug=0)
[Answer]
# Pyth, 62
An implementation of [Andrea's](https://codegolf.stackexchange.com/a/58211/31625) fantastic CJam answer.
```
sm?<Cd5jkmOTCdd*30"Crime Predicted: --
Calling: 1--555-
"
```
Note that there are several unprintable characters in the source, and there should not be a trailing `"`. That was added for SE so that it seems a bit more readable. I have not been able to get a hexdump yet, but the link below works and you should be able to copy-paste out of it.
[Try it online here](http://pyth.herokuapp.com/?code=sm%3F%3CCd5jkmOTCdd%2a30%22Crime+Predicted%3A+%03-%02-%04%0ACalling%3A+1-%03-555-%04%0A%0A&debug=0)
[Answer]
# CJam, 74 bytes
```
30{[ZY4Z4]{Aa*:mrs}%"Crime predicted: %s-%s-%s
Calling: 1-%s-555-%s
"e%}*
```
Not a winner, but it's at least somewhat close to what Dennis has so far, and it's using a different approach. So I thought it was worth posting anyway.
This uses the CJam `e%` operator, which generates output with a printf style format string.
```
30 Repeat count for whole output.
{ Start loop.
[ZY4Z4] Build list of random number lengths: [3 2 4 3 4].
{ Start loop over all random number lengths.
Aa* Build list of [10 ... ] with the random number length.
E.g. for length 3, this will be [10 10 10].
:mr Apply the random number operator to the list. This will generate
a list of random numbers between 0 and 9, with the given length.
s Convert it to a string.
}% End of loop over random number lengths.
"..." Format string, with a %s for each random number.
e% Apply printf style formatting.
}* End of main repeat loop.
```
[Answer]
## Matlab / Octave, 108 ~~172~~ bytes
```
disp(sprintf('Crime predicted: %i%i%i-%i%i-%i%i%i%i\nCalling: 1-%i%i%i-555-%i%i%i%i\n\n',randi(10,1,480)-1))
```
[Try it online](http://ideone.com/cGmxDh)
[Answer]
# JavaScript (ES6), 142
**Side note** mixmat answer in **ß** shows a so better way to accomplish this task, and could easily implemented in JS giving a better score. I wish I had thought about it.
**Edit** Added the missing text (I misread the challenge)
Test running the snippet below in an EcmaScript 6 compliant browser
```
/* TEST redirect console.log */ console.log=x=>O.innerHTML+=x+'\n'
for(i=30;i--;)console.log(`Crime predicted: ${(R=d=>(1e-9+Math.random()+'').substr(2,d))(3)}-${R(2)}-${R(4)}
Calling: 1-${R(3)}-555-${R(4)}
`)
```
```
<pre id=O></pre>
```
[Answer]
# Fourier, ~~166~~ 142 bytes
```
45~d030(~i67a114a-9a+4a-8a32a112a^^a101ava+5a-6a116a101ava58a32a999roda99roda9999ro10a67a97a108aa-3a+5a-7a58a32a1oda999roda5oooda9999ro10aai^)
```
This has one of the highest byte counts, but I am a huge fan of Fourier and wanted to try my hand at a solution. Not very optimized.
Breaking it down:
```
45~d
```
Sets the variable d to 45, the ASCII code for a hyphen. This character is printed so much that it saves some bytes to declare it here.
```
030(...)
```
Sets the accumulator to zero and loops inside the parentheses until it reaches 30.
```
67a114a-9a+4a-8a32a112a^^a101ava+5a-6a116a101ava58a32a
```
Print "Crime predicted: ".
```
999roda99roda9999ro10a
```
Print a completely random SSN + newline.
```
67a97a108aa-3a+5a-7a58a32a
```
Print "Calling: ".
```
1oda999roda5oooda9999ro
```
Print a phone number that follows the guidelines: 1-xxx-555-xxxx
```
10aa
```
Print two newlines to start over.
[Answer]
# Pyth, 67 bytes
```
V30s.ic"Crime predicted: |-|-|
Calling: 1-|-555-|
"\|mjkmOTdj32434T
```
The newlines are important, and are included in byte count. Try it out [here](https://pyth.herokuapp.com/?code=V30s.ic%22Crime%20predicted%3A%20%7C-%7C-%7C%0ACalling%3A%201-%7C-555-%7C%0A%22%5C%7CmjkmOTdj32434T&debug=0).
```
Implicit: T=10, k=''
"..." The output string
c \| Split on '|' placeholders
j32434T 32434 to base ten -> [3,2,4,3,4]
m Map for d in the above:
mOTd Generate d random numbers from 0-9
jk Concatenate into string (join on empty string)
.i Interleave segments of output string with random strings
s Concatenate and output
V30 Perform the above 30 times
```
[Answer]
# Haskell, 150 bytes
```
import System.Random
p '#'=putChar=<<randomRIO('0','9')
p x=putChar x
main=mapM p$[1..30]>>"Crime predicted: ###-##-####\nCalling: 1-###-555-####\n\n"
```
[Answer]
# JavaScript (ES6), ~~130~~ 123 bytes
Taking minxomat's ß solution a step further, I've replaced the `0`s with the number of `0`s that would have been there. The code uses those numbers to pull the correct number of digits off of `Math.random()`, saving a good bit of bytes in the process.
```
for(i=30;i--;)console.log(`Crime predicted: 3-2-4
Calling: 1-3-555-4
`.replace(/[2-4]/g,x=>`${Math.random()}`.substr(2,x)))
```
Try it out:
```
// redirecting console.log() for this demonstration
console.log=x=>O.innerHTML+=x+'\n';
O.innerHTML='';
for(i=30;i--;)console.log(`Crime predicted: 3-2-4
Calling: 1-3-555-4
`.replace(/[2-4]/g,x=>`${Math.random()}`.substr(2,x)))
```
```
<pre id=O>
```
As always, suggestions welcome!
[Answer]
# Java, 246 bytes
```
import java.util.*;class C{static{Random r=new Random();for(int i=0;i++<30;)System.out.printf("Crime predicted: %s-%s-%s\nCalling: 1-%s-555-%s\n\n",r.nextInt(900)+100,r.nextInt(90)+10,r.nextInt(900)+100,r.nextInt(900)+100,r.nextInt(9000)+1000);}}
```
With line breaks:
```
import java.util.*;
class C{
static{
Random r = new Random();
for(int i = 0; i++<30;)
System.out.printf("Crime predicted: %s-%s-%s\nCalling: 1-%s-555-%s\n\n",r.nextInt(900)+100,r.nextInt(90)+10,r.nextInt(900)+100,r.nextInt(900)+100,r.nextInt(9000)+1000);
}
}
```
It's a start. Instead of producing random digits I used random 3-digit or 4-digit numbers.
[Answer]
# R, ~~151~~ 146 or 144 Bytes
### Code
```
for(l in 1:30)cat(sep="","Crime predicted: ",(i=floor(runif(16,,10)))[1:3],"-",i[4:5],"-",i[6:9],"\nCalling: 1-",i[10:12],"-555-",i[13:16],"\n\n")
```
Test it [online](http://www.r-fiddle.org/#/fiddle?id=8WD2Ldwq&version=1).
### Ungolfed
```
for(l in 1:30) {
i=floor(runif(16,,10))
cat(sep="","Crime predicted: ",
i[1:3],"-",i[4:5],"-",i[6:9],
"\nCalling: 1-",i[10:12],"-555-",
i[13:16],"\n\n")
}
```
I think there is a lot of room to improve but I am no good messing with strings in R.
Edit 1: changed the `runif(16,max=10)` to `runif(16,,10)`.
I've done another code (~~147~~ 144 bytes) with `sprintf` but I don't think it is much a R-like code.
```
for(l in 1:30)cat(do.call(sprintf,as.list(c('Crime predicted: %s%s%s-%s%s-%s%s%s%s\nCalling: 1-%s%s%s-555-%s%s%s%s\n\n',floor(runif(16,,10))))))
```
Another approach (149 bytes):
```
for(p in 1:30)cat(sep="",replace(s<-strsplit("Crime predicted: '''-''-''''\nCalling: 1-'''-555-''''\n\n","")[[1]],which(s<"-"),floor(runif(16,,10))))
```
[Answer]
# [PHP](http://php.net/), 144 143 Bytes
```
<?=preg_replace_callback('/x/',function($x){return chr(rand(48,57));},str_repeat("Crime predicted: xxx-xx-xxxx
Calling: 1-xxx-555-xxxx
",30));
```
[Answer]
# GolfScript, 91 bytes
```
{9rand}+:r;{"Crime Predicted: "{r}3*"-"{r}2*"-"{r}4*"
Calling: 1-"{r}3*"-555-"{r}4*"
"}30*
```
[Try it online.](http://golfscript.apphb.com/?c=ezlyYW5kfSs6cjt7IkNyaW1lIFByZWRpY3RlZDogIntyfTMqIi0ie3J9MioiLSJ7cn00KiIKQ2FsbGluZzogMS0ie3J9MyoiLTU1NS0ie3J9NCoiCgoifTMwKg%3D%3D)
[Answer]
## C#, 280 263 246 bytes
Golfed:
```
using System;class C{static string G(){var r=new Random();var s="";n h=x=>r.Next(x).ToString("D"+x);for(int i=0;i++<30;){s+="Crime predicted: "+h(3)+"-"+h(2)+"-"+h(4)+"\nCalling: 1-"+h(3)+"-555-"+h(4)+"\n\n";}return s;}delegate string n(int x);}
```
Indented:
```
using System;
class C
{
static string G()
{
Random r = new Random();
string s = "";
Func<int, string> f = x => r.Next((int)Math.Pow(10, x)).ToString("D" + x);
for (int i = 0; i++ < 30;)
{
s += "Crime predicted: " + f(3) + "-" + f(2) + "-" + f(4) + "\nCalling: 1-" + f(3) + "-555-" + f(4) + "\n\n";
}
return s;
}
}
```
New on Codegolf, tips are welcome!
[Answer]
# [Hassium](http://hassiumlang.com), 230 Bytes
```
func main(){foreach(x in range(1,31){println("Crime predicted: "+r(3)+"-"+r(2)+"-"+r(4));println("Calling: 1-"+r(3)+"-555-"+r(4)+"\n");}}
func r(l){z=new Random();a="";foreach(y in range(1,l))a+=z.next(0,10).toString();return a;}
```
Expanded:
```
func main () {
foreach (x in range(1, 31) {
println("Crime predicted: " + r(3) + "-" + r(2) + "-" + r(4));
println("Calling: 1-" + r(3) + "-555-" + r(4) + "\n");
}
}
func r (l) {
z = new Random();
a = "";
foreach (y in range(1, l))
a += z.next(0, 10).toString();
return a;
}
```
[Answer]
# Ruby, 98 characters
```
30.times{puts"Crime Predicted: DEF-GH-IJKL
Calling: 1-MNO-555-QRST
".tr"D-OQ-T",rand.to_s[2..-1]}
```
Sample run:
```
bash-4.3$ ruby -e '30.times{puts"Crime Predicted: DEF-GH-IJKL\nCalling: 1-MNO-555-QRST\n\n".tr"D-OQ-T",rand.to_s[2..-1]}' | head
Crime Predicted: 867-29-2637
Calling: 1-278-555-5424
Crime Predicted: 913-31-6306
Calling: 1-744-555-8188
Crime Predicted: 868-36-4612
Calling: 1-926-555-3576
Crime Predicted: 988-06-1643
```
[Answer]
# JavaScript, ~~146~~ 141
```
console.log(Array(30).join("Crime predicted: 3-2-3\nCalling: 1-3-555-4\n\n").replace(/[2-4]/g,function(m){return(m+Math.random()).substr(3,m)}))
```
[Answer]
## pre-ES6 Javascript, 128
```
for(i=30;i--;)console.log('Crime predicted: x-x-x\nCalling: x-555-x\n'.replace(/x/g, function(){return 1e3*Math.random()|0}))
```
I feel like the dashes could be removed somehow, but not sure.
[Answer]
## Pyth, 73 bytes
```
V30FGPc"Crime predicted: xxx-xx-xxxx\nCalling: 1-xxx-555-xxxx"\xpGpOT)pb"
```
[Demo](https://pyth.herokuapp.com/?code=V30FGPc%22Crime+predicted%3A+xxx-xx-xxxx%5CnCalling%3A+1-xxx-555-xxxx%22%5CxpGpOT%29pb%22&debug=0)
[Answer]
# Julia, 120 bytes
```
R(n)=lpad(rand(0:10^n-1),n,0)
for i=1:30 println("Crime Predicted: "R(3)"-"R(2)"-"R(4)"\nCalling: 1-"R(3)"-555-"R(4))end
```
Ungolfed:
```
# Define a function for returning a random number with a
# specified number of digits
function R(n::Int)
lpad(rand(0:10^n-1), n, 0)
end
# Print 30 times
for i = 1:30
println("Crime Predicted: " R(3) "-" R(2) "-" R(4)
"\nCalling: 1-" R(3) "-555-" R(4))
end
```
[Answer]
# Ruby, ~~90~~ 88 bytes
```
30.times{puts"Crime predicted: NNN-NN-NNNN
Calling: 1-NNN-555-NNNN
".gsub(?N){rand 10}}
```
[Try it online.](https://repl.it/BJ6Q/1)
[Answer]
# PowerShell, ~~120~~ ~~108~~ ~~103~~ 102 Bytes
```
0..29|%{("Crime predicted: XXX-XX-XXXX`nCalling: 1-XXX-555-XXX"-split"X"|%{$_+(Random 10)})-join'';""}
```
~~Shortened a few more bytes by setting the split-loop to instead be a code block that outputs to an array `@(..)` and is re-joined.~~
Eliminated the `@` by remembering that `(...)` designates a code block executed before the `-join''` anyway.
This eliminates needing to assign the `$a` variable. Also noticed that due to how the `-split` functionality works, the previous code was spitting out too many digits for the phone number, so got a free byte saving there by shrinking to `1-XXX-555-XXX`. That made up for the erroneous `Random 9` that actually picks random from `0-8`, so we instead need to specify `Random 10.`
*Sooo* dang close to double-digits, but I'm not sure where it's possible to golf off another ~~four~~ 3 bytes ...
---
### Previous, 108
```
0..29|%{$a="";"Crime predicted: XXX-XX-XXXX`nCalling: 1-XXX-555-XXXX"-split"x"|%{$a+="$_$(Random 9)"};$a;""}
```
Shortened the code a couple bytes by instead splitting a string on `X`'s, then re-looping through the resultant array of strings and concatenating each entry with a `Random` digit to build our final output string `$a`. Note that we couldn't do something like `"string".replace("x",$(Random 9))` because then the `Random` would only get called once, so you'd have `1-222-555-2222` for a phone number, for example.
---
### Previous-er, 120
```
0..29|%{"Crime predicted: "+(Random 1e9).ToString("000-00-0000");"Calling: "+(Random 1e7).ToString("1-000-555-0000");""}
```
Pretty dang competitive for a verbose language, thanks to generous output specifications (i.e., `000-00-0001` is treated as a valid SSN) and the really robust `.ToString()` formatting algorithm that PowerShell uses. PowerShell also outputs `\r\n` after every string output, so the requirement for a newline in between iterations is just a simple `""`.
Note that this uses an implied `Get-` in front of `Random`, so this may be *[really slow](https://codegolf.stackexchange.com/a/778/42963)* on some platforms/implementations.
[Answer]
# Befunge-98, 170
I think this can still be golfed down a bit. But at least I beat C#. Tested at [befungius.aurlien.net](http://befungius.aurlien.net/).
```
a3*> 82*v>":detciderp emirC">:#,_$...'-,..'-,....av
>1 -:!#;_v^;v,,,"-555-"...,,,,,,,,,,,"Calling: 1-",<
\ ^v< <2?1v,
+ ^;^3<;<,
^ <0?3vv....<
^;^6<;<>a,v
v_@#:-1<
```
[Answer]
# Python 2, ~~151~~ 150 bytes
```
from random import*
p="Crime predicted: xxx-xx-xxxx\nCalling: 1-xxx-555-xxxx\n\n"*30
while'x'in p:p=p.replace('x',str(randint(0,9)),1)
print p.strip()
```
As golfed as I could get this method.
] |
[Question]
[
# What is the most frequent word?
Given a sentence, your program must make its way through it, counting the frequencies of each word, then output the most used word. Because a sentence has no fixed length, and so can get very long, your code must be as short as possible.
## Rules/Requirements
* Each submission should be either a full program or function. If it is a function, it must be runnable by only needing to add the function call to the bottom of the program. Anything else (e.g. headers in C), must be included.
* There must be a free interpreter/compiler available for your language.
* If it is possible, provide a link to a site where your program can be tested.
* Your program must not write anything to `STDERR`.
* Your program should take input from `STDIN` (or the closest alternative in your language).
* [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* Your program must be case-insensitive (`tHe`, `The` and `the` all contribute to the count of `the`).
* If there is no most frequent word (see test case #3), your program should output nothing.
### Definition of a 'word':
You get the list of words by splitting the input text on spaces. The input will never contain any other type of whitespace than plain spaces (in particular no newlines). However, the final words should only contain alphanumerics (a-z, A-Z, 0-9), hyphens (-) and apostrophes ('). You can make that so by removing all other characters or by replacing them by space before doing the word splitting. To remain compatible with previous versions of the rules, apostrophes are not required to be included.
## Test Cases
```
The man walked down the road.
==> the
-----
Slowly, he ate the pie, savoring each delicious bite. He felt like he was truly happy.
==> he
-----
This sentence has no most frequent word.
==>
-----
"That's... that's... that is just terrible!" he said.
==> that's / thats
-----
The old-fashioned man ate an old-fashioned cake.
==> old-fashioned
-----
IPv6 looks great, much better than IPv4, except for the fact that IPv6 has longer addresses.
==> IPv6
-----
This sentence with words has at most two equal most frequent words.
==>
```
Note: The third and seventh test cases have no output, you may choose either on the fourth.
## Scoring
Programs are scored according to bytes. The usual character set is UTF-8, if you are using another please specify.
When the challenge finishes, the program with the least bytes (it's called [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")), will win.
## Submissions
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
```
## Leaderboard
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.
```
/* Configuration */
var QUESTION_ID = 79576; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 53406; // This should be the user ID of the challenge author.
/* App */
var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;
function answersUrl(index) {
return "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,]*[^\s,]),.*?(\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,
});
});
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;
if (/<a/.test(lang)) lang = jQuery(lang).text();
languages[lang] = languages[lang] || {lang: a.language, 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 > b.lang) return 1;
if (a.lang < b.lang) return -1;
return 0;
});
for (var i = 0; i < langs.length; ++i)
{
var language = jQuery("#language-template").html();
var lang = langs[i];
language = language.replace("{{LANGUAGE}}", lang.lang)
.replace("{{NAME}}", lang.user)
.replace("{{SIZE}}", lang.size)
.replace("{{LINK}}", lang.link);
language = jQuery(language);
jQuery("#languages").append(language);
}
}
```
```
body { text-align: left !important}
#answer-list {
padding: 10px;
width: 290px;
float: left;
}
#language-list {
padding: 10px;
width: 290px;
float: left;
}
table thead {
font-weight: bold;
}
table td {
padding: 5px;
}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="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]
# [Jelly](http://github.com/DennisMitchell/jelly), 25 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ṣ⁶f€ØB;”-¤Œl©Qµ®ċЀĠṪịµẋE
```
[Try it online!](http://jelly.tryitonline.net/#code=4bmj4oG2ZuKCrMOYQjvigJ0twqTFkmzCqVHCtcKuxIvDkOKCrMSg4bmq4buLwrXhuotF&input=&args=JycnVGhhdCdzLi4uIHRoYXQncy4uLiB0aGF0IGlzIGp1c3QgdGVycmlibGUhIiBoZSBzYWlkLicnJw) or [verify all test cases](http://jelly.tryitonline.net/#code=4bmj4oG2ZuKCrMOYQjvigJ0twqTFkmzCqVHCtcKuxIvDkOKCrMSg4bmq4buLwrXhuotFCsOH4oKsauKBtw&input=&args=WycnJ1RoZSBtYW4gd2Fsa2VkIGRvd24gdGhlIHJvYWQuJycnLCAnJydTbG93bHksIGhlIGF0ZSB0aGUgcGllLCBzYXZvcmluZyBlYWNoIGRlbGljaW91cyBiaXRlLiBIZSBmZWx0IGxpa2UgaGUgd2FzIHRydWx5IGhhcHB5LicnJywgJycnVGhpcyBzZW50ZW5jZSBoYXMgbm8gbW9zdCBmcmVxdWVudCB3b3JkLicnJywgJycnVGhhdCdzLi4uIHRoYXQncy4uLiB0aGF0IGlzIGp1c3QgdGVycmlibGUhIiBoZSBzYWlkLicnJywgJycnVGhlIG9sZC1mYXNoaW9uZWQgbWFuIGF0ZSBhbiBvbGQtZmFzaGlvbmVkIGNha2UuJycnLCAnJydJUHY2IGxvb2tzIGdyZWF0LCBtdWNoIGJldHRlciB0aGFuIElQdjQsIGV4Y2VwdCBmb3IgdGhlIGZhY3QgdGhhdCBJUHY2IGhhcyBsb25nZXIgYWRkcmVzc2VzLicnJ10).
[Answer]
# Pyth - ~~23~~ 30 bytes
There has to be a better way to include digits and hyphens, but I just want to fix this right now.
```
Kc@s+++GUTd\-rzZ)I!tJ.M/KZ{KhJ
```
[Test Suite](http://pyth.herokuapp.com/?code=Kc%40s%2B%2B%2BGUTd%5C-rzZ%29I%21tJ.M%2FKZ%7BKhJ&test_suite=1&test_suite_input=The+man+walked+down+the+road.%0ASlowly%2C+he+ate+the+pie%2C+savoring+each+delicious+bite.+He+felt+like+he+was+truly+happy.%0AThis+sentence+has+no+most+frequent+word.%0AIPv6+looks+great%2C+much+better+than+IPv4%2C+except+for+the+fact+that+IPv6+has+longer+addresses.&debug=0).
[Answer]
## Pyke, ~~26~~ 25 bytes
```
l1dcD}jm/D3Sei/1qIi@j@
(;
```
[Try it here!](http://pyke.catbus.co.uk/?code=l1dcD%7Djm%2FD3Sei%2F1qIi%40j%40%0A%28%3B&input=The+man+walked+down+the+road.)
Or ~~23~~ 22 bytes (noncompeting, add node where kills stack if false)
```
l1cD}jm/D3Sei/1q.Ii@j@
```
[Try it here!](http://pyke.catbus.co.uk/?code=l1cD%7Djm%2FD3Sei%2F1q.Ii%40j%40&input=The+man+walked+down+the+road.)
Or with punctuation, 23 bytes (I think this competes? Commit was before the edit)
```
l1.cD}jm/D3Sei/1q.Ii@j@
```
[Try it here!](http://pyke.catbus.co.uk/?code=l1.cD%7Djm%2FD3Sei%2F1q.Ii%40j%40&input=The+man+walked+down+the+road...+road%3F+Road%21)
Or 12 bytes (definitely noncompeting)
```
l1.cj.#jR/)e
```
[Try it here!](http://pyke.catbus.co.uk/?code=l1.cj.%23jR%2F%29e&input=The+man+walked+down+the+road...+road%3F+Road%21&warnings=0)
```
l1 - input.lower()
.c - punc_split(^)
j - j = ^
.# ) - sort(V(i) for i in ^)
jR/ - j.count(i)
e - ^[-1]
```
[Answer]
# Octave, ~~115~~ 94 bytes
```
[a,b,c]=unique(regexp(lower(input('')),'[A-z]*','match'));[~,~,d]=mode(c); try disp(a{d{:}})
```
Accounts for the case with no most frequent word by using `try`. In this case it outputs nothing, and "takes a break" until you catch the exception.
Saved 21(!) bytes thanks to Luis Mendo's suggestion (using the third output from `mode` to get the most common word).
---
The rules have changed quite a bit since I posted my original answer. I'll look into the regex later.
[Answer]
# Perl 6, 80 bytes
```
{$_>1&&.[0].value==.[1].value??""!!.[0].key given .lc.words.Bag.sort:{-.value}}
```
Let's split the answer into two parts...
```
given .lc.words.Bag.sort:{-.value}
```
`given` is a control statement (like `if` or `for`). In Perl 6, they're allowed as postfixes. (`a if 1`, or like here, `foo given 3`). `given` puts its topic (right-hand side) into the special variable `$_` for its left-hand side.
The "topic" itself lowercases (`lc`), splits by word (`words`), puts the values into a Bag (set with number of occurences), then sorts by value (DESC). Since `sort` only knows how to operate on lists, the `Bag` is transformed into a `List` of `Pair`s here.
```
$_>1&&.[0].value==.[1].value??""!!.[0].key
```
a simple conditional (`?? !!` are used in Perl 6, instead of `? :`).
```
$_ > 1
```
Just checks that the list has more than one element.
```
.[0].value==.[1].value
```
Accesses to `$_` can be shortened... By not specifying the variable. `.a` is exactly like `$_.a`. So this is effectively "do both top elements have the same number of occurences" – If so, then we print '' (the empty string).
Otherwise, we print the top element's key (the count): `.[0].key`.
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 30 bytes
Code:
```
lžj¨„ -«Ãð¡©Ùv®yQOˆ}®¯MQÏDg1Q×
```
Uses **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=bMW-asKo4oCeIC3Cq8ODw7DCocKpw5l2wq55UU_Lhn3CrsKvTVHDj0RnMVHDlw&input=VGhlIG1hbiB3YWxrZWQgZG93biB0aGUgcm9hZC4).
[Answer]
## JavaScript (ES6), 155 bytes
```
s=>(m=new Map,s.toLowerCase().replace(/[^- 0-9A-Z]/gi,'').split(/\ +/).map(w=>m.set(w,-~m.get(w))),[[a,b],[c,d]]=[...m].sort(([a,b],[c,d])=>d-b),b==d?'':a)
```
Based on @Blue's Python answer.
[Answer]
# Python 3.5, 142 137 134 112 117 ~~110~~ 127 bytes:
(*+17 bytes, because apparently even if there are words more frequent than the rest, but they have the same frequency, nothing should still be returned.*)
```
def g(u):import re;q=re.findall(r"\b['\-\w]+\b",u.lower());Q=q.count;D=[*map(Q,{*q})];return['',max(q,key=Q)][1in map(D.count,D)]
```
Should now satisfy all conditions. This submission assumes that at least 1 word is input.
[Try It Online! (Ideone)](http://ideone.com/mDHfbA)
Also, if you want one, here is another version of my function devoid of any regular expressions at the cost of about 43 bytes, though this one is non-competitive anyways, so it does not really matter. I just put it here for the heck of it:
```
def g(u):import re;q=''.join([i for i in u.lower()if i in[*map(chr,range(97,123)),*"'- "]]).split();Q=q.count;D=[*map(Q,{*q})];return['',max(q,key=Q)][1in map(D.count,D)]
```
[Try this New Version Online! (Ideone)](http://ideone.com/TiYyKP)
[Answer]
# Ruby, ~~94~~ ~~92~~ 102 bytes
Gotta go fast (FGITW answer). Returns the word in all uppercase, or `nil` if there is no most frequent word.
Now updated to new specs, I think. However, I did manage to golf down a little so the byte count is the same!
```
->s{w=s.upcase.tr("_'",'').scan /[-\w]+/;q=->x{w.count x};(w-[d=w.max_by(&q)]).all?{|e|q[e]<q[d]}?d:p}
```
[Answer]
# Pyth, 32 bytes
```
p?tlJeM.MhZrS@Ls++\-GUTcrz0d8ksJ
```
[Test suite.](http://pyth.herokuapp.com/?code=p%3FtlJeM.MhZrS%40Ls%2B%2B%5C-GUTcrz0d8ksJ&test_suite=1&test_suite_input=The+man+walked+down+the+road.%0ASlowly%2C+he+ate+the+pie%2C+savoring+each+delicious+bite.+He+felt+like+he+was+truly+happy.%0AThis+sentence+has+no+most+frequent+word.%0A%22That%27s...+that%27s...+that+is+just+terrible!%22+he+said.%0AThe+old-fashioned+man+ate+an+old-fashioned+cake.%0AIPv6+looks+great%2C+much+better+than+IPv4%2C+except+for+the+fact+that+IPv6+has+longer+addresses.&debug=0)
[Answer]
# JavaScript (ES6), 99 bytes
```
F=s=>(f={},w=c='',s.toLowerCase().replace(/[\w-']+/g,m=>(f[m]=o=++f[m]||1)-c?o>c?(w=m,c=o):0:w=''),w)
```
```
#input { width: 100%; }
```
```
<textarea id="input" oninput="output.innerHTML=F(this.value)"></textarea>
<div id="output"></div>
```
[Answer]
# Sqlserver 2008, 250 bytes
```
DECLARE @ varchar(max) = 'That''s... that''s... that is just terrible!" he said.';
WITH c as(SELECT
@ p,@ x
UNION ALL
SELECT LEFT(x,k-1),STUFF(x,1,k,'')FROM
c CROSS APPLY(SELECT patindex('%[^a-z''-]%',x+'!')k)k
WHERE''<x)SELECT max(p)FROM(SELECT top 1with ties p
FROM c WHERE p>''GROUP BY p
ORDER BY count(*)DESC
)j HAVING count(*)=1
```
[Try it online!](https://data.stackexchange.com/stackoverflow/query/483878/count-words)
# Sqlserver 2016, 174 bytes
Unable to handle data like this example(counting the equals as 3 words):
```
DECLARE @ varchar(max) = 'That''s... that''s... that is just terrible!" he said. = = ='
SELECT max(v)FROM(SELECT TOP 1WITH TIES value v
FROM STRING_SPLIT(REPLACE(REPLACE(REPLACE(@,'"',''),',',''),'.',''),' ')GROUP
BY value ORDER BY count(*)DESC)x HAVING count(*)=1
```
[Answer]
# PostgreSQL, 246, 245 bytes
```
WITH z AS(SELECT DISTINCT*,COUNT(*)OVER(PARTITION BY t,m)c FROM i,regexp_split_to_table(translate(lower(t),'.,"''',''),E'\\s+')m)
SELECT t,CASE WHEN COUNT(*)>1 THEN '' ELSE MAX(m)END
FROM z WHERE(t,c)IN(SELECT t,MAX(c)FROM z GROUP BY t)
GROUP BY t
```
Output:
[](https://i.stack.imgur.com/TfzXn.png)
Input if anyone is interested:
```
CREATE TABLE i(t TEXT);
INSERT INTO i(t)
VALUES ('The man walked down the road.'), ('Slowly, he ate the pie, savoring each delicious bite. He felt like he was truly happy.'),
('This sentence has no most frequent word.'), ('"That''s... that''s... that is just terrible!" he said. '), ('The old-fashioned man ate an old-fashioned cake.'),
('IPv6 looks great, much better than IPv4, except for the fact that IPv6 has longer addresses.'), ('a a a b b b c');
```
---
Normally I would use `MODE() WITHIN GROUP(...)` and it will be much shorter, but it will violate:
>
> If there is no most frequent word (see test case #3), your program should output nothing.
>
>
>
---
**EDIT:**
Handling `'`:
```
WITH z AS(SELECT DISTINCT*,COUNT(*)OVER(PARTITION BY t,m)c FROM i,regexp_split_to_table(translate(lower(t),'.,"!',''),E'\\s+')m)
SELECT t,CASE WHEN COUNT(*)>1 THEN '' ELSE MAX(m)END
FROM z WHERE(t,c)IN(SELECT t,MAX(c)FROM z GROUP BY t)
GROUP BY t
```
`**[`SqlFiddleDemo`](http://sqlfiddle.com/#!15/7639f/1/0)**`
Output:
```
╔═══════════════════════════════════════════════════════════════════════════════════════════════╦═══════════════╗
║ t ║ max ║
╠═══════════════════════════════════════════════════════════════════════════════════════════════╬═══════════════╣
║ a a a b b b c ║ ║
║ The old-fashioned man ate an old-fashioned cake. ║ old-fashioned ║
║ IPv6 looks great, much better than IPv4, except for the fact that IPv6 has longer addresses. ║ ipv6 ║
║ This sentence has no most frequent word. ║ ║
║ "That's... that's... that is just terrible!" he said. ║ that's ║
║ The man walked down the road. ║ the ║
║ Slowly, he ate the pie, savoring each delicious bite. He felt like he was truly happy. ║ he ║
╚═══════════════════════════════════════════════════════════════════════════════════════════════╩═══════════════╝
```
[Answer]
# R, 115 bytes
```
function(s)if(sum(z<-(y=table(tolower((x=strsplit(s,"[^\\w']",,T)[[1]])[x>""])))==max(y))<2)names(which(z))else NULL
```
This is a function that accepts a string and returns a string if a single word appears more often than others and `NULL` otherwise. To call it, assign it to a variable.
Ungolfed:
```
f <- function(s) {
# Create a vector of words by splitting the input on characters other
# than word characters and apostrophes
v <- (x <- strsplit(s, "[^\\w']", perl = TRUE))[x > ""]
# Count the occurrences of each lowercased word
y <- table(tolower(v))
# Create a logical vector such that elements of `y` which occur most
# often are `TRUE` and the rest are fase
z <- y == max(y)
# If a single word occurs most often, return it, otherwise `NULL`
if (sum(z) < 2) {
names(which(z))
} else {
NULL
}
}
```
[Answer]
# Retina, 97 bytes
The rules keep changing...
```
T`L`l
[^-\w ]
O`[-\w]+
([-\w]+)( \1\b)*
$#2;$1
O#`[-\w;]+
.*\b(\d+);[-\w]+ \1;[-\w]+$
!`[-\w]+$
```
[Try it online!](http://retina.tryitonline.net/#code=VGBMYGwKW14tXHcgXQoKT2BbLVx3XSsKKFstXHddKykoIFwxXGIpKgokIzI7JDEKTyNgWy1cdztdKwouKlxiKFxkKyk7Wy1cd10rIFwxO1stXHddKyQKCiFgWy1cd10rJA&input=cGkgcGllIHBpZQ)
[Test suite.](http://retina.tryitonline.net/#code=JShUYExgbApbXi1cdyBdCgpPYFstXHddKwooWy1cd10rKSggXDFcYikqCiQjMjskMQpPI2BbLVx3O10rCi4qXGIoXGQrKTtbLVx3XSsgXDE7Wy1cd10rJAoKIWBbLVx3XSsk&input=VGhlIG1hbiB3YWxrZWQgZG93biB0aGUgcm9hZC4KU2xvd2x5LCBoZSBhdGUgdGhlIHBpZSwgc2F2b3JpbmcgZWFjaCBkZWxpY2lvdXMgYml0ZS4gSGUgZmVsdCBsaWtlIGhlIHdhcyB0cnVseSBoYXBweS4KVGhpcyBzZW50ZW5jZSBoYXMgbm8gbW9zdCBmcmVxdWVudCB3b3JkLgoiVGhhdCdzLi4uIHRoYXQncy4uLiB0aGF0IGlzIGp1c3QgdGVycmlibGUhIiBoZSBzYWlkLgpUaGUgb2xkLWZhc2hpb25lZCBtYW4gYXRlIGFuIG9sZC1mYXNoaW9uZWQgY2FrZS4KSVB2NiBsb29rcyBncmVhdCwgbXVjaCBiZXR0ZXIgdGhhbiBJUHY0LCBleGNlcHQgZm9yIHRoZSBmYWN0IHRoYXQgSVB2NiBoYXMgbG9uZ2VyIGFkZHJlc3Nlcy4)
[Answer]
# Python, 132 bytes
```
import collections as C,re
def g(s):(a,i),(b,j)=C.Counter(re.sub('[^\w\s-]','',s.lower()).split()).most_common(2);return[a,''][i==j]
```
Above code assumes that input has at least two words.
[Answer]
# PHP, 223 bytes
```
$a=array_count_values(array_map(function($s){return preg_replace('/[^A-Za-z0-9]/','',$s);},explode(' ',strtolower($argv[1]))));arsort($a);$c=count($a);$k=array_keys($a);echo($c>0?($c==1?$k[0]:($a[$k[0]]!=$a[$k[1]]?$k[0]:'')):'');
```
[Answer]
# Python 2, 218 bytes
Assumes more than 2 words. Getting rid of punctuation destroyed me...
```
import string as z
def m(s):a=[w.lower()for w in s.translate(z.maketrans('',''),z.punctuation).split()];a=sorted({w:a.count(w)for w in set(a)}.items(),key=lambda b:b[1],reverse=1);return a[0][0]if a[0][1]>a[1][1]else''
```
[Answer]
## Matlab (225)
* Rules chaneged :/
.
```
function c=f(a),t=@(x)feval(@(y)y(y>32),num2str(lower(x)-0));f=@(x)num2str(nnz(x)+1);e=str2num(regexprep(a,'([\w''-]+)',' ${t($1)} ${f($`)} ${f([$`,$1])}'));[u,r,d]=mode(e);try c=find(e==d{:});c=a((e(c(1)+1)):(e(c(1)+2)));end
```
* Toolbox is necessary to run this.
* How does this work, one of the nicest privileges of regex replace in matlab this it field-executes tokens by calling external-environmental functions parameterized by the tokens caught in the inner environment, so any sequence of `"Word_A Word_B .."` is replaced by integers `"A0 A1 A2 B0 B1 B2 ..."` where the first integer is the numerica ascii signature of the word, the second is the starting index, the third is the ending index, these last two integers dont reduplicate in the whole sequence so i took this advantage to transpose it to an array, then [mode](https://codegolf.stackexchange.com/a/42550/38337) it then search the result in that array, so the starting/ending indices will consequently follow.
* **Edit:** after changing some details, the program is called function by a string parameter.
---
**20** bytes saved thanks to @StewieGriffin, **30** bytes added reproaches to common-agreed loopholes.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~22~~ ~~21~~ 20 bytes
```
žK„- JÃl#{D.MDgiJëõ?
```
Explanation:
```
žK # Push [a-zA-Z0-9]
„- # Push 2-char string containing a hyphen and a space
J # Join the stack into a single element
à # Removes all characters from implicit input except those specified above
l # Converts to lowercase
# # Split string by spaces
{ # Sorts array
D # Duplicates
.M # Finds most common element
Dg # Gets length of string without popping
iJ # If length == 1, then convert the array to a string (otherwise the output would be ['example'] instead of example
ëõ? # Else push an empty string.
```
Note: If you're fine with trailing newlines in the output for when you're not supposed to output anything, remove the `?` at the end to save a byte.
Note #2: The program will not work with a single word, but I doubt this would be a problem. If you want to fix this, replace `#` with `ð¡` for an extra byte.
05AB1E uses CP-1252 as the charset, not UTF-8.
[Try it online!](https://tio.run/nexus/05ab1e#@390n/ejhnm6Cl6Hm3OUq130fF3SDQMzvQ6vPrz1//@M1JycfIXy/KKcFAUw@2tevm5yYnJGKgA)
[Answer]
# Shell, ~~89~~ ~~86~~ 82 bytes
```
grep -Po "[\w'-]+"|sort -f|uniq -ci|sort -nr|awk 'c>$1{print w}c{exit}{c=$1;w=$2}'
```
This lists all words in the input, then sorts them with counts from most common to least common. The `awk` call merely ensures that the #2 word doesn't have the same count as the #1 word.
Unwrapped:
```
grep -Po "[\w'-]+" # get a list of the words, one per line
|sort -f # sort (case insensitive, "folded")
|uniq -ci # count unique entries while still ignoring case
|sort -nr # sort counted data in descending order
|awk '
count > $1 { # if count of most common word exceeds that of this line
print word # print the word saved from it
}
count { # if we have already saved a count (-> we are on line 2)
exit # we always exit on line 2 since we have enough info
}
{ # if true (run on line 1 only due to the above exit)
count = $1 # save the count of the word on this first line
word = $2 # save the word itself
}'
```
`grep -o` is the magic tokenizer here. It takes each word (as defined by a regex accepting word characters (letters, numbers, underscore), apostrophe, or hyphen using PCRE given `-P`) and puts it on its own line. This accepts underscores, as to many other answers here. To disallow underscores, add four characters to turn this portion into `grep -oi "[a-z0-9'-]*"`
`alias cnt='sort -f |uniq -ci |sort -nr'` is an old standby of mine. Without regards to case, it alphabetizes (erm, asciibetizes) the lines of the input counts occurrences of each entry, then reverse-sorts by the numeric occurrences so the most popular is first.
`awk` only looks at the first two lines of that descending ranked list. On line one, `count` is not yet defined, so it is evaluated as zero and therefore the first two stanzas are skipped (zero == false). The third stanza sets `count` and `word`. On the second line, `awk` has a defined and nonzero value for `count`, so it compares that count to the second best count. If it's not tied, the saved `word` is printed. Regardless, the next stanza exits for us.
Test implemented as:
```
for s in "The man walked down the road." "Slowly, he ate the pie, savoring each delicious bite. He felt like he was truly happy." "This sentence has no most frequent word." "\"That's... that's... that is just terrible\!\" he said." "The old-fashioned man ate an old-fashioned cake." "IPv6 looks great, much better than IPv4, except for the fact that IPv6 has longer addresses." "This sentence with words has at most two equal most frequent words."; do printf "%s\n==> " "$s"; echo "$s" |grep -io "[a-z0-9'-]*"|sort -f|uniq -ci|sort -nr|awk 'c>$1{print w}c{exit}{c=$1;w=$2}'; echo; done
```
[Answer]
# Perl, ~~60~~ ~~56~~ ~~55~~ 54 bytes
Includes +3 for `-p`
```
#!/usr/bin/perl -p
s/[\pL\d'-]+/$;[$a{lc$&}++]++or$\=$&/eg}{$\x=2>pop@
```
If a word cannot be just a number you can also drop the `a` for a score of 53.
[Answer]
# [Julia 1.0](http://julialang.org/), ~~140~~ 133 bytes
```
~s=(d=Dict();split(replace(lowercase(s),r"[^\' 0-9a-z-]"=>"")).|>w->d[w]=get(d,w,0)+1;(x,y)=findmax(d);sum(x.==values(d))<2 ? y : "")
```
[Try it online!](https://tio.run/##fZBBb9QwEIXv/IohlzoiiVqEkKBkuXCAGxK9dVtpNp5s3HXs4HHWCUL968skHGCrqqdEnvfevPkeRmvwajqdHrlWuv5imqjyax6siSrQYLEhZX2i0CCT4rwI2e399gIuyw9Y/irvsnqTZXle/d6kcqNv0129p6h0kYrL/M3VtZqKOa9b43SPk9KSPPZqqur6iHYklpf801v4DDN8BMk5DcG4aJ16zG46gh4dJLQH0qB9chDlLXjUVZa/@qf8If3sXIAMMdIqGgwVwHj0ItoDYdOBJmsa40eGnYlUwVeClmwEaw60WBMyxDDaGTochvl8xU1nGJhcJNeIWqTOQ@85Qhvo5ygDSD486bUVG8YLrqpKSv3/B5L2MIo7UghmZ@n1Nls6MBr9dDGBt7pskTvjnYBYmCxnyud80OCBzs3fvh/fg/X@wLAPhLGAfhQSO4qydyniQCTvCqCpoUFu8WGl12IT//ZcE5ZzrXd78aDWgZiJX8KTTOxWHLxaJWYlFZMHYYX2GXBL3ukP "Julia 1.0 – Try It Online")
-7 bytes thanks to MarcMush: replace `count(i->d[i]==x,keys(d))` with `sum(x.==values(d))`
[Answer]
# PowerShell (v4), 117 bytes
```
$y,$z=@($input-replace'[^a-z0-9 \n-]'-split'\s'|group|sort Count)[-2,-1]
($y,($z,'')[$y.Count-eq$z.Count])[!!$z].Name
```
The first part is easy enough:
* `$input` is ~= stdin
* Regex replace irrelevant characters with nothing, keep newlines so we don't mash two words from the end of a line and the beginning of the next line into one by mistake. (Nobody else has discussed multiple lines, could golf -2 if the input is always a single line).
* Regex split, `Group` by frequency (~= Python's collections.Counter), `Sort` to put most frequent words at the end.
* PowerShell is case insensitive by default for everything.
Handling if there isn't a most frequent word:
* Take the last two items [-2,-1] into $y and $z;
* an N-item list, where N>=2, makes $y and $z the last two items
* a 1-item list makes $y the last item and $z null
* an Empty list makes them both null
Use the bool-as-array-index fake-ternary-operator golf `(0,1)[truthyvalue]`, nested, to choose "", $z or $y as output, then take .Name.
```
PS D:\> "The man walked down the road."|.\test.ps1
The
PS D:\> "Slowly, he ate the pie, savoring each delicious bite. He felt like he was truly happy."|.\test.ps1
he
PS D:\> "`"That's... that's... that is just terrible!`" he said."|.\test.ps1
Thats
PS D:\> "The old-fashioned man ate an old-fashioned cake."|.\test.ps1
old-fashioned
PS D:\> "IPv6 looks great, much better than IPv4, except for the fact that IPv6 has longer addresses."|.\test.ps1
IPv6
```
[Answer]
# Lua, ~~232~~ ~~199~~ 175 bytes
```
w,m,o={},0;io.read():lower():gsub("[^-%w%s]",""):gsub("[%w-]+",function(x)w[x]=(w[x]or 0)+1 end)for k,v in pairs(w)do if m==v then o=''end if(v>m)then m,o=v,k end end print(o)
```
[Answer]
# Perl 5, ~~96~~ ~~92~~ 84 + 2 (`-p` flag) = 86 bytes
```
++$h{+lc}for/\w(?:\S*\w)?/g}{$m>$e[1]||$e[1]>$m&&(($_,$m)=@e)||($_="")while@e=each%h
```
Using:
```
> echo "The man walked down the road." | perl -p script.pl
```
[Answer]
# Python, 158 bytes
```
def g(s):import collections as c,re;l=c.Counter(re.sub('[^\w\s-]',"",s.lower()).split());w,f=l.most_common(1)[0];return[w,""][all(f==i[1]for i in l.items())]
```
Takes its input like this:
```
g("Bird is the word")
```
Should match all the requirements, although it does fail on empty strings, is it necessary to check for those? Sorry for the delay.
Advice / feedback / black magic tips for saving bytes are always welcome
[Answer]
# Tcl 8.6, 196 bytes
```
lmap s [join [read stdin] \ ] {dict incr d [regsub -all {[^\w-]} [string tol $s] {}]}
set y [dict fi $d v [lindex [lsort [dict v $d]] end]]
if {[llength $y]!=2} {set y {}}
puts "==> [lindex $y 0]"
```
(Alas, I can't figure out how to get it any smaller than that...)
**Explanation**
It uses several obscure Tcl idioms to do stuff.
* `[join [read stdin] " "]`
— input string→list of whitespace-separated words
* `lmap ...`
— iterate over every element of that list. (Shorter than `foreach` and effectually identical since the result is discarded.)
* `[regsub ... [string tolower ...]]`
— Convert the string to lowercase and strip all characters except for word characters and the hyphen.
* `[dict incr d ...]`
— Create/modify a dictionary/word→count histogram.
* `set y ...`
— Sort the dictionary values, take the largest one, and return all (key,value) pairs corresponding to it.
* `if...`
— There must be exactly two elements: a single (key,value) pair, else there is nothing to print.
* `puts...`
— Print the key in the key value pair, if any. (No word has spaces.)
You can play with it using [CodeChef](https://www.codechef.com/ide).
[Answer]
# Rexx, ~~109~~ ~~128~~ 122 bytes
```
pull s;g.=0;m=0;do i=1 to words(s);w=word(s,i);g.w=g.w+1;if g.w>=m then do;m=g.w;g.m=g.m+1;r=w;end;end;if g.m=1 then say r
```
Pretty printed...
```
pull s
g.=0
m=0
do i=1 to words(s)
w=word(s,i)
g.w=g.w+1
if g.w>=m
then do
m=g.w
g.m=g.m+1
r=w
end
end
if g.m=1 then say r
```
[Answer]
bash, ~~153~~ ~~146~~ ~~131~~ ~~154~~ ~~149~~ ~~137~~ bytes
```
declare -iA F
f(){ (((T=++F[$1])==M))&&I=;((T>M))&&M=$T&&I=$1;}
read L
L=${L,,}
L=${L//[^- a-z0-9]}
printf -vA "f %s;" $L
eval $A;echo $I
```
Operation:
declare an associative array F of integers (declare -iA F)
f is a function that, given a word parameter $1, increments frequency count for this word (T=++F[$1]) and compares to max count so far (M).
If equal, the we have a tie so we will not consider this word to be most frequent (I=)
If greater than max count so far (M), then set max count so far to frequency count of this word so far (M=$T) and remember this word (I=$1)
End function f
Read a line (read L)
Make lowercase (L=${L,,})
Remove any character except a-z, 0-9, dash(-) and space (L=${L//[^- a-z0-9]})
Make a sequence of bash statements that calls f for each word (printf -vA "f %s;" $L). This is saved to variable A.
eval A and print result (eval $a;echo$I)
Output:
```
This quick brown fox jumps over this lazy dog.
-->this
This sentence with the words has at most two equal most frequent the words.
-->
The man walked down the road.
-->the
This sentence has no most frequent word.
-->
Slowly, he ate the pie, savoring each delicious bite. He felt like he was truly happy.
-->he
"That's... that's... that is just terrible!" he said.
-->thats
The old-fashioned man ate an old-fashioned cake.
-->old-fashioned
IPv6 looks great, much better than IPv4, except for the fact that IPv6 has longer addresses.
-->ipv6
```
Bug: FIXED
I have a bug that is not revealed in these test cases.
If input is
```
This sentence with words has at most two equal most frequent words.
```
then my code should output nothing.
~~I have a fix but I seem to have hit a bash bug... I get very odd behaviour is M is not declared an integer: ++F[$1]==M (after a few repeated words) increments both F[$1] and M!!~~ - my mistake.
] |
[Question]
[
I have a simple challenge for you this time. Given an array of positive integers **A** (or the equivalent in your language), replace each entry **Ai** with the sum of the next **Ai** elements of **A**, cycling back from the beginning if there are not enough items.
As usual, you can compete in any [programming language](https://codegolf.meta.stackexchange.com/a/2073/59487) and can take input and provide output through any [standard method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) and in any reasonable format, while taking note that [these loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden by default. You may optionally take the size of **A** as input too. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest submission (in bytes) for *every language* wins.
# Examples / Test Cases
Given `[1,3,4,5]`, your code should output `[3,10,13,14]`, because `1` is replaced by `3`, `3` is replaced by `4+5+1=10` (notice how it wrapped back from the start), `4` by `5+1+3+4=13` and `5` by `1+3+4+5+1=14`.
Given `[3,2,1,9]`, your program should produce `[12,10,9,33]`, because we substitute `3` with `2+1+9=12`, `2` with `1+9=10`, `1` with `9` and `9` with `3+2+1+9+3+2+1+9+3=33` (notice how we wrapped back from the start more than once).
Some more test cases for you to choose from:
```
[4,3,2,1] -> [10,7,5,4]
[3,2,1,9] -> [12,10,9,33]
[1,3,4,5] -> [3,10,13,14]
[4,4,3,2,2] -> [11,11,8,6,8]
[3,5,3,2,1] -> [10,14,6,4,3]
[3,2,4,3,2,1,1] -> [9,7,7,4,2,1,3]
[7,8,6,5,4,3,2,1,5] -> [29,33,20,15,11,8,6,5,30]
[28,2,4,2,3,2,3,4,5,3] -> [137,6,10,5,9,7,12,38,39,34]
[1,2,3,4,5,4,3,2,1,2,3,4,3,2,1] -> [2,7,13,14,12,8,5,3,2,7,9,7,4,2,1]
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~10~~ 9 bytes
```
"G@:X@+)s
```
[Try it online!](https://tio.run/##y00syfn/X8ndwSrCQVuz@P//aEMdYx0THdNYAA "MATL – Try It Online")
```
% implicit input
" % for loop, iterate over the input array
G % push input x
@ % push for loop index, x[i]
: % range, push [1,...,x[i]]
X@ % push for loop index, i
+ % sum, so stack holds [i+1,...,i+x[i]]
) % index, modularly, so gets the cyclic successors
s % sum cyclic successors, leaving the sum on the stack
% implicit end of for loop
% implicit output of stack
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
ṙJṁS¥"
```
[Try it online!](https://tio.run/##y0rNyan8///hzpleD3c2Bh9aqvT/cPvRSQ93zvj/P9pQx0jHWMdExxSIjYFsGB/MjgUA "Jelly – Try It Online")
[Answer]
# [Python](https://docs.python.org), 55 bytes
```
lambda a:[sum((-~v*a)[i:i+v])for i,v in enumerate(a,1)]
```
**[Try it online!](https://tio.run/##VY7BDoIwEETvfsXe2upyoKAiif5I4VBjiU2kECgkXvx1bBc52Ev3zcxOtn/7Z@eypblWy0u394cGXapxajlPPvNeC2VLe5hr0XQDWJzBOjBuas2gveEaU1Ev0fJm9NHjKscMJaY1KvrxEqY0aDkew5Tj6kvyj3/Z3ybxGQs8BX/T4q4sKCRJokLMqHyjLbzyWi3KHYTXD9Z5zgAY0q0IrHLJLVDDIwsSmFi@ "Python 3 – Try It Online")**
[Answer]
# J, 33 bytes
```
[:({.+/@{.}.)"1 i.@#|."{($~>./*#)
```
## ungolfed
```
[: ({. +/@{. }.)"1 i.@# |."0 _ ($~ (>./ * #))
```
## explanation
[](https://i.stack.imgur.com/5lY8N.png)
[Try it online!](https://tio.run/##fZDNasJAFIX3eYpDLJjROmb@nElAEYSuunLrUirVjQ@Qtq@e3jv5MYomJAOB@c797rnUqZyesC4xxTtylPQtJHb7z4/6UGaVnC@3lfyVIlU4y@3kR6ZV9va3kcvZRNQiSb6O31dkJ1gYaCiB58@ihMrh4WB7JAIoxhDNVAFjekgRZuFGIMOMotMO5Bo9LV5OUvwGrBAGfm5sqWYlZYmh9Lut2jKekUQV1IOnO3zjxvk43fXsw4rEaS4Cmma6TpYE8z5Bhzhax4DYEoy49zWeILJ2UYLqNQGGYu2g347tRJr/tgjWYJLrZT60HfkYGHdK6n8 "J – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~86~~ 85 bytes
* Saved a byte thanks to [Jakob](https://codegolf.stackexchange.com/users/44945/jakob).
```
C(y,c,l,i,k)int*y;{for(l=~0;++l<c;printf("%d,",k))for(k=i=0;i++<y[l];k+=y[(l+i)%c]);}
```
[Try it online!](https://tio.run/##jZLbaoQwEIav26dYhIWkzkKOqxLtzT6G60WxbBGtLUtvROyr20k83GwoERVNJt8/88/Up4@6nucLGaCGDhpoadP/vAxmvH3dSVf8MhPHXV6b7zuu30h0fIcIg6jdboumYKaJ43wou8q0cTGUpIsbeqwraqb5863pCR2fn7bDB7zKiJoLIbhQVnTkE3C6w6trn59eDyUH/Lr2GPnfWQUSBCBBeQgMEtCggkAOA5kfhFsMMpAyCMUxJwXai5KWxPGtAstbChQTaE9eHPBO4YxPWI16s0t77cKszk4x1LHVfktMHokZ@p9gjI0IYyauGr1z0cTskStcKwTmqzcDsDAWpCBSl7ZwAq5PIHH@mMcPmSAYXdFgC8EhkClIlFaBU7Dxt2KW/7UB3NMBYWXcbKBYujYrceqLibvuNP8B "C (gcc) – Try It Online")
[Answer]
## Haskell, ~~50~~ ~~47~~ 44 bytes
```
zipWith((sum.).take)<*>scanr(:)[].tail.cycle
```
[Try it online!](https://tio.run/##dY7NDoIwEITvPsUePIBZSSigaMTX8IA9NJWfhoINxYM@vJW0chDicWd2vpma6aaQ0pQZXM1LqIsYas/Tjzbwg4E1hX/anDVnXe8d/ZyOkpABf3JZmJaJDjK43VcAqhfdAGsoIY8xQoIh/VWthoeZGo6/MSZ0TnAMsmAkf9nf1oW3xxR3Y27y510ktWFibTsGo8XIyZkg7nZTzJuXklXabLlSHw "Haskell – Try It Online")
```
-- <*> in function context is Haskell's S combinator, i.e.
-- (zipWith ... <*> scanr ...) arg
-- resovles to
-- zipWith ... arg (scanr ... arg)
zipWith -- so we zip
-- the input list and
scanr(:)[] -- the tails (tails of [1,2,3] are [[1,2,3],[2,3],[3],[]])
tail -- of the tail of
cycle -- and infinite cycle of the input list
-- with the function
(sum.).take -- take that many elements given by the element
-- of the input list from the list given by the inits
-- and sum it
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~8~~ 7 bytes
```
εL¾+èO¼
```
[Try it online!](https://tio.run/##MzBNTDJM/f//3FafQ/u0D6/wP7Tn//9oIwsdIx0TIDYGYxMdUx3jWAA "05AB1E – Try It Online")
**Explanation**
```
ε # apply to each element x of the input
L # push range [1 ... x]
¾+ # add counter to each (initially 0)
è # cyclically index into input with each
O # sum
¼ # increment counter
```
[Answer]
# [K4](http://kx.com/download/) / [K (oK)](https://github.com/JohnEarnest/ok), ~~20~~ 19 bytes
**Solution:**
```
+/'x#'1_(1+2##x)#x:
```
[Try it online!](https://tio.run/##y9bNz/7/X1tfvUJZ3TBew1DbSFm5QlO5wspQwVjBRMH0/38A "K (oK) – Try It Online")
**Examples:**
```
q)k)+/'x#'1_(1+2##x)#x:1 3 4 5
3 10 13 14
q)k)+/'x#'1_(1+2##x)#x:4 3 2 1
10 7 5 4
q)k)+/'x#'1_(1+2##x)#x:3 2 4 3 2 1 1
9 7 7 4 2 1 3
q)k)+/'x#'1_(1+2##x)#x:1 2 3 4 5 4 3 2 1 2 3 4 3 2 1
2 7 13 14 12 8 5 3 2 7 9 7 4 2 1
```
**Explanation:**
Reshape input, drop first, take x length of each, sum up.
```
+/'x#'1_(1+2##x)#x: / the solution
x: / store input as x
# / reshape
( ) / do this together
#x / count x
2# / duplicate (2-take)
1+ / add 1
1_ / 1 drop (_), remove first element
x#' / x take each-both
+/' / sum (+/) each
```
[Answer]
# [R](https://www.r-project.org/), ~~62~~ 58 bytes
```
function(a,l)diag(diffinv(matrix(a,max(a)*l+1,l))[a+2,])-a
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNRJ0czJTMxXSMlMy0tM69MIzexpCizAiiemwgkNbVytA2BSjSjE7WNdGI1dRP/p2kkaxjrGOkY6lhq6pho/gcA "R – Try It Online")
An alternative to the [other R solution](https://codegolf.stackexchange.com/a/166945/67312). In the comments [JayCe made a mention of `cumsum`](https://codegolf.stackexchange.com/questions/166920/replace-me-by-the-sum-of-my-cyclic-successors/166929#comment403701_166945) which triggered something in my brain to use `diffinv` and matrix recycling instead of `rep`.
### Explanation:
Given input array `a`, let `M=max(a)` and `l=length(a)`.
Observe that `M+l` is the maximum possible index we'd need to access, and that `M+l<=M*l+1`, since if `M,l>1`,`M+l<=M*l` (with equality only when `M=l=2`) and if `l==1` or `M==1`, then `M+l==M*l+1`.
By way of example, let `a=c(4,3,2,1)`. Then `M=l=4`.
We construct the `M*l+1 x l` matrix in R by `matrix(a,max(a)*l+1,l)`. Because R recycles `a` in column-major order, we end up with a matrix repeating the elements of `a` as such:
```
[,1] [,2] [,3] [,4]
[1,] 4 3 2 1
[2,] 3 2 1 4
[3,] 2 1 4 3
[4,] 1 4 3 2
[5,] 4 3 2 1
[6,] 3 2 1 4
[7,] 2 1 4 3
[8,] 1 4 3 2
[9,] 4 3 2 1
[10,] 3 2 1 4
[11,] 2 1 4 3
[12,] 1 4 3 2
[13,] 4 3 2 1
[14,] 3 2 1 4
[15,] 2 1 4 3
[16,] 1 4 3 2
[17,] 4 3 2 1
```
Each column is the cyclic successors of each element of `a`, with `a` across the first row; this is due to the way that R recycles its arguments in a matrix.
Next, we take the inverse "derivative" with `diffinv`, essentially the cumulative sum of each column with an additional `0` as the first row, generating the matrix
```
[,1] [,2] [,3] [,4]
[1,] 0 0 0 0
[2,] 4 3 2 1
[3,] 7 5 3 5
[4,] 9 6 7 8
[5,] 10 10 10 10
[6,] 14 13 12 11
[7,] 17 15 13 15
[8,] 19 16 17 18
[9,] 20 20 20 20
[10,] 24 23 22 21
[11,] 27 25 23 25
[12,] 29 26 27 28
[13,] 30 30 30 30
[14,] 34 33 32 31
[15,] 37 35 33 35
[16,] 39 36 37 38
[17,] 40 40 40 40
[18,] 44 43 42 41
```
In the first column, entry `6=4+2` is equal to `14=4 + (3+2+1+4)`, which is the cyclic successor sum (CSS) plus a leading `4`. Similarly, in the second column, entry `5=3+2` is equal to `10=3 + (4+1+2)`, and so forth.
So in column `i`, the `a[i]+2`nd entry is equal to `CSS(i)+a[i]`. Hence, we take rows indexed by `a+2`, yielding a square matrix:
```
[,1] [,2] [,3] [,4]
[1,] 14 13 12 11
[2,] 10 10 10 10
[3,] 9 6 7 8
[4,] 7 5 3 5
```
The entries along the diagonal are equal to the cyclic successor sums plus `a`, so we extract the diagonal and subtract `a`, returning the result as the cyclic successor sums.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
R+"Jị⁸§
```
**[Try it online!](https://tio.run/##y0rNyan8/z9IW8nr4e7uR407Di3///9/tKGOsY6JjmksAA "Jelly – Try It Online")**
[Answer]
# [Attache](https://github.com/ConorOBrien-Foxx/Attache), 26 bytes
```
{Sum=>_[(_2+1:_)%#_]}#Iota
```
[Try it online!](https://tio.run/##SywpSUzOSP2fpmBl@786uDTX1i4@WiPeSNvQKl5TVTk@tlbZM78k8b9fampKcbRKQUFyeixXQFFmXklIanGJc2JxanF0mo5CNJeCgoKJurG6kbqhDogNZqlbgtmGQHETdVMdiBqIKiOoKlM0PVAzoCLm6hbqZkA1MFGIGUYWYIVGYEGw0erGUItgfJgGCB/M5oqN/Q8A "Attache – Try It Online")
## Explanation
This is a fork of two functions:
* `{Sum=>_[(_2+1:_)%#_]}`
* `Iota`
What this means is, the right tine `Iota` is applied to the argument `x` and is passed as the second argument to the center tine (the first function). So this becomes, for input `x`:
```
{Sum=>_[(_2+1:_)%#_]}[x, Iota[x]]
```
Replacing those in for `_` and `_2`:
```
Sum => x[(Iota[x] + 1:x) % #x]
```
`Iota[x]` returns an array of the indices of `x`. It's equivalent to `0...#x`. `#x` is a short way of saying the size of `x`, or `Size[x]`. In essence, this function is mapping the `Sum` function over the second expression:
```
x[(Iota[x] + 1:x) % #x]
```
The outer `x[...]` bit means that `...` will generate a series of indices to be selected from `x`. The most important part of generating the indices is this:
```
Iota[x] + 1:x
```
This expression uses a bit of vectorization. To visualize this, let's suppose the input is `x := [1, 3, 4, 5]`. Then, this expression is equivalent to:
```
Iota[[1, 3, 4, 5]] + 1:[1, 3, 4, 5]
[0, 1, 2, 3] + [1:1, 1:3, 1:4, 1:5]
[0, 1, 2, 3] + [[1], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]]
[0 + [1], 1 + [1, 2, 3], 2 + [1, 2, 3, 4], 3 + [1, 2, 3, 4, 5]]
[[0 + 1], [1 + 1, 1 + 2, 1 + 3], [2 + 1, 2 + 2, 2 + 3, 2 + 4], [3 + 1, 3 + 2, 3 + 3, 3 + 4, 3 + 5]]
[[1], [2, 3, 4], [3, 4, 5, 6], [4, 5, 6, 7, 8]]
```
This is a list of indices which represent the indices next `N` elements in `x` mod `#x`. To make them safe for retrieval, we take this array mod `#x`:
```
(Iota[x] + 1:x) % #x
```
This gives us the proper indices, which are then obtained from `x` and each array is summed, giving the proper results.
## Other attempts
**36 bytes:** `{Sum@_&Get=>((_2+1.._2+_)%#_)}#Iota` - I forgot `x[...]` fully vectorizes, so that becomes:
**30 bytes:** `{Sum=>_[(_2+1.._2+_)%#_]}#Iota` - but then I realized the `_2+` in the inner range could be factored out, which means we could save parentheses by using `:` instead of `..`, giving us the current version.
[Answer]
# [R](https://www.r-project.org/), ~~89~~ 64 bytes
```
j=rep(x<-scan(),max(x));Map(function(u,v)sum(j[v+1:u]),x,seq(x))
```
[Try it online!](https://tio.run/##K/r/P8u2KLVAo8JGtzg5MU9DUyc3sUKjQlPT2jexQCOtNC@5JDM/T6NUp0yzuDRXIyu6TNvQqjRWU6dCpzi1EKTwv7GCkYKhguV/AA "R – Try It Online")
Main idea to to generate a way-long-enough cycling index vector you can use to get the needed elements from the input vector.
Original version:
```
function(x,i=seq(x),j=rep(i,max(x))){for(k in i){T=c(T,sum(x[j[(k+1):(k+x[k])]]))};T[-1]}
```
[Try it online!](https://tio.run/##JcmxCsIwGATg3afo@B/@DrE6qOQtsoUMJTSQhqaaWgiUPntM7XDHfVwqTha3RPv1U6TMXs79hzJ4kKl/k@exy5XA6qZEofGx8ViVtKR4XkbKetAUzgLP2lkHA2OA7aX0RZitOLLU8pUFP4DTLlHV8o3vNcdz@L@B8gM "R – Try It Online")
[Answer]
# Pyth, ~~13~~ 11 bytes
```
.esm@Q+dkSb
```
Saved 2 bytes thanks to Mr. Xcoder.
[Try it here](https://pyth.herokuapp.com/?code=.es%3C%3E%2ahsQQhkb&input=%5B1%2C2%2C3%2C4%2C5%2C4%2C3%2C2%2C1%2C2%2C3%2C4%2C3%2C2%2C1%5D%0A&debug=0)
### Explanation
```
.esm@Q+dkSb
.e Q For each index k and value b in (implicit) input...
Sb ... get the list [1, ..., b]...
m +dk ... add k to each...
@Q ... and index into the input...
s ... then take the sum.
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes
```
IEθΣEι§θ⊕⁺κλ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzexQKNQRyG4NBfMzNRRcCzxzEtJrQCJeuYlF6XmpuaVpKZoBOSUFmtk6yjkaEKB9f//0dHmOhY6ZjqmOiY6xjpGOoY6prGx/3XLcgA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
θ Input array
E Map over elements
ι Current element
E Map over implicit range
λ Inner index
κ Outer index
⁺ Sum
⊕ Increment
θ Input array
§ Cyclically index
Σ Sum
I Cast to string
Implicitly print on separate lines
```
[Answer]
# JavaScript ES6, 65 bytes
```
a=>a.map((x,y)=>{for(s=0,i=y;i<y+x;)s+=a[++i%a.length];return s})
```
Straightforward solution. Ungolfed:
```
a => a.map((x,y) => {
var s = 0;
for (i = y; i < y + x; i++) {
s += a[i % a.length];
}
return s;
});
```
JavaScript's `map()` function is perfect for the job, it runs the given callback against each element and replaced it by the result of the callback. The callback receives two parameters, the first `x` is the value and the second `y` is the index. By taking the modulus `i % a.length` we can easily loop over the array, multiple times if needed.
### Test snippet
(Put the input as JSON notation)
```
let f = a=>a.map((x,y)=>{for(s=0,i=y;i<y+x;)s+=a[++i%a.length];return s})
```
```
<input id=I type="text" size=70 value="[4,3,2,1]"><button onclick="console.log(f(JSON.parse(I.value)))">Run</button>
```
[Answer]
# Java 8, 87 bytes
A curried void lambda taking an `int[]` list and `int` length.
```
l->s->{for(int i=-1,j,t;++i<s;System.out.println(t))for(j=t=0;j++<l[i];)t+=l[(i+j)%s];}
```
[Try It Online](https://tio.run/##rVJLa@MwED7Hv0KXgowdsUmbkx@wLCwUGnahx5CDKstBriIZaZwlBP/2rCzbrdsmFEpPFjPffI/xVPRA57rmqiqez3XzJAVDTFJr0ZoKhU7BbChaoOA@pVBUospNkQaEJGWjGAityO/hkQoFm218CfJLK9vsuUnvFfAdN3mOSpQFZznP7Tw/ldpgN4xENl/EVQxJFInUJo9HC3xPdAOkNq4vFYYw7MBVBtmPpIqiVG7ENgkhyuQGi6gKb@w2ac/BLAmcf6OBM@DFGKGP19N2Aa8h1po9/@0UH8Fw2kMn2NeAD8JC@uepcvUcGc64OLh@hhT/N0H9NIYePTTHYWdsNq72oEWBxmw9D9Jhrzcb@QgtCqzdoKu10@krPpjk1OCR5apZcD5HieSN4GcBeiw0RnU0g6/B26Wbeb9O90MHiXcdT97RvGXxW9q7o8QOJtRus0XU7GyfsCS0ruURd3T@ANHpLka3MVrGaNGGhDLGa8B33rePJKnakQu3NSkNK/QzlwVeNJavGqvv1Fh49luvtJroTesfUi6@bKEN2uD8Hw). Note that I've shadowed `System.out` in this program in order to grab results for prettier printing.
[Answer]
# [Julia 0.6](http://julialang.org/), 63 55 53 bytes
```
A->[sum(repmat(A,v+1)[i+1:i+v])for(i,v)=enumerate(A)]
```
[Try it online!](https://tio.run/##HYjLCsMgEAB/pcdd3BzU9EEhAb9DPCzBgiXaYNTft7aHGZh51z3wrW9LN9Nqzxoh@yNyAUNNSLRByGcQzeHrkyFQw8WnGn3m4sGg65EP4Gk9ckhlT7ABI9IFrCTlyCqSw5I03Un/@kGK5oH@M9N1bMT@BQ "Julia 0.6 – Try It Online")
---
Older solution:
# [Julia 0.6](http://julialang.org/), 65 bytes
```
A->(l=length(A);[sum(A[mod1(j,l)]for j∈i+1:i+A[i])for i∈1:l])
```
[Try it online!](https://tio.run/##LYpLCoQwEESv4rIb20Wb@eGgkHOELILzS0iiOHoHzzkXySTgoop6j3Kbt@aSxj7JZgDf@2d8rx@QeFffLYBUYXowOPKoX9NSud@@25o7W0tlNRZls@LOa0zBzGCaYV5sXH2EEQwiVaCYWhI5TKypUO722IKuJArf8uF0HEVe56wR0x8 "Julia 0.6 – Try It Online")
---
Another solution. Not great by bytecount, but I like it, and it's probably more efficient than the other two, especially if the input has big numbers.
# [Julia 0.6](http://julialang.org/), 69 bytes
```
A->(l=length(A);[sum([A;A][i+1:i+A[i]%l])+A[i]÷l*sum(A)for i∈1:l])
```
[Try it online!](https://tio.run/##yyrNyUw0@59s@99R104jxzYnNS@9JEPDUdM6urg0VyPa0doxNjpT29AqU9sxOjNWNSdWE8w4vD1HC6TAUTMtv0gh81FHh6EVUO5/bmKBRqKuXUFRZl5JTp5GskaipqaOgka0oY6RjjEQG@oYxuqAeEDSCMo21jHXMQbxLYAKTKAKjYEsU6CwpuZ/AA "Julia 0.6 – Try It Online")
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 10 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
²X{x+⁸@]∑]
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JUIyJXVGRjM4JXVGRjVCJXVGRjU4JXVGRjBCJXUyMDc4JXVGRjIwJXVGRjNEJXUyMjExJXVGRjNE,i=JTVCNCUyQzQlMkMzJTJDMiUyQzIlNUQ_,v=3)
Explanation:
```
{ ] map over the items in the input
²X save this loops counter on X (because of a bad design choice..)
{ ] map over 1..current item
x+ add to it X
⁸@ and index in the input using that
∑ sum the map
```
[Answer]
# [QBasic 1.1](http://www.qbasic.net/), 115 bytes
```
INPUT L
DIM A(L)
FOR I=0TO L-1
INPUT C
A(I)=C
NEXT
FOR I=0TO L-1
S=0
FOR C=I+1TO I+A(I)
S=S+A(C MOD L)
NEXT
?S
NEXT
```
First input is the length **L**, then **L** subsequent inputs are the elements in order. **L** outputs represent the resulting array, with the elements in the order they're presented.
[Answer]
# Japt, 7 bytes
```
ËÆg°EÃx
```
[Try it here](https://ethproductions.github.io/japt/?v=1.4.5&code=y8ZnsEXDeA==&input=WzMsMiwxLDld)
[Answer]
# JavaScript, 46 bytes
```
a=>a.map(g=(x,y)=>x--&&a[++y%a.length]+g(x,y))
```
[Try it online](https://tio.run/##HclLCoAgFADA0ySGH6hWLfQi4uJhaoWpZISd3qLZzg43FHNu@WIxLbY50UBI4Adk7AWu9OmFrIwhBIqQpwMebPTXqon/s28mxZKC5SF57LCa6EgHOutvXg)
[Answer]
# APL+WIN, 37 bytes
Prompts for input:
```
+/¨v↑¨⊂[2](⍳⍴v)⌽((⍴v),⍴n)⍴n←(+/v)⍴v←⎕
```
[Try it online! Courtesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/5r6x9aUfaobeKhFY@6mqKNYjUe9W5@1LulTPNRz14NDTBLB0jmaYIIoDYNbf0yEBuoZwLQqP9AQ/6ncRlZKBgpmACxMRibKJgqGHOlcRnCeSZgGRgfzAYA "APL (Dyalog Classic) – Try It Online")
Explanation:
```
n←(+/v)⍴v←⎕ prompts for input and creates a repeating vector of length max v
((⍴v),⍴n)⍴n converts n to a matrix of length v x length n
(⍳⍴v)⌽ rotates each row of n by the size of each element of v
⊂[2] converts each row of m to an element in a nested vector
+/¨v↑¨ selects the number of elements from each element of the nested vector according to v and sums
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 38 bytes
```
->a{w=0;a.map{|x|(a*-~x)[w+=1,x].sum}}
```
[Try it online!](https://tio.run/##VY7NDsIgEITvPgVHf7aNUKo1Bl@EcMBDT23S2DTFAL46ll05eJuZfDO7r@X5Tr1K1cP6VZ3vth7t5IMLe3usPu6g15Pi4Ew9L2OMSWsJDQjgBnYaBdyy5Fsqoc1SAiGCkPaf/9UpuEIHl40oIfZFh5jADFehoRPFFpw8zZv8N/NhCGxivR5MTF8 "Ruby – Try It Online")
[Answer]
# **JavaScript, 65 bytes 3̶0̶0̶ ̶b̶y̶t̶e̶s̶**
golfed
```
n=>n.map((z,x)=>{for(s=0,i=x;i<z+x;)s+=n[++i%n.length];return s})
```
ungolfed
```
f = n=>n.map((z,x)=>{
for(s=0,i=x;i<z+x;)s+=n[++i%n.length];
return s
}
);
console.log(f(process.argv[2].slice(1, -1).split(", ").map(x=>+x)))
```
[Try it online!](https://tio.run/##Hc3RCsIgFADQX5Eg8KKTbU/Bcj8y9iDLLcOu4rUhi77dovcD52F2Q0tyMTcYbrauuqIeUT1N5PyQBfT4XkPipFvpdBnc9RBlABIaJyHcGZW3uOX7PCSbXwkZfaAuASl4q3zY@MpjCoslUiZt@9TPirxbLO8kazpQFL3L/CTZCf5n0aMoAFDr1EvWSvZzl/kL "JavaScript (Node.js) – Try It Online")
(ungolfed version above)
I'm new to this codegolf thing!
---
\*updated! thanks to the useful links provided in comments, I managed to reduce the size to 65 bytes!
[Answer]
## [Perl 5](https://www.perl.org/) with `-M5.010`, 42 bytes
```
say sum+((@F,@F)x$_)[++$-..($-+$_-1)]for@F
```
[Try it online!](https://tio.run/##TY/BbsIwEETv@QqL@pDI65CEuKWgSjnlBEdOCKEgbSWraYLsrYCfr7s1ROKyO7PzPJLP6HoTpP4o1uJFOPRI4nN0gtCT8D@WMPjuxupbpWnTQtNmV3nM9kpJneep1EoedZkd@E3ThjWzs9l/E17JdaK3A4qTw@5LnJAuiEMs9qGGBVRQJnHCe1Kyr8EkNdyTihPzxDx4dm@whFfOpotJqmUEqniINbDgwklP4N1H/TueyY6DD3ro2jnMg96avCgL3hvrabXake1Vyp/O/gA "Perl 5 – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip) `-rn`, 14 bytes
```
$+g@(_+\,B)MEg
```
Takes input numbers on successive lines of stdin; gives output numbers on successive lines of stdout. [Try it online!](https://tio.run/##K8gs@P9fRTvdQSNeO0bHSdPXNf3/f0MuYy4TLtP/ukV5AA "Pip – Try It Online")
### Explanation
```
g List of lines of stdin (from -r flag)
ME Enumerate and map this function to the (index, value) pairs:
\,B One-based range(value)
_+ To each element, add the index of that value
g@( ) Use the resulting range to slice into the original list g
(cyclical indexing is built in)
$+ Sum the numbers in the slice
Output the list of results one per line (from -n flag)
```
Or, using a worked example:
```
g [1 3 4 5]
ME
\,B [(1,2) (1,4) (1,5) (1,6)]
_+ [(1,2) (2,5) (3,7) (4,9)]
g@( ) [[3] [4 5 1] [5 1 3 4] [1 3 4 5 1]]
$+ [3 10 13 14]
```
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 12 bytes
```
+/¨⊢⍴¨⍳∘≢⌽¨⊂
```
[Try it online!](https://tio.run/##fZDNSsNAFIX38xR3l0Updv6ciW8TKpFgINJ2U6SbImKtETeCW7tyr24ENz7KfZF4ZqYRlMYQJpOZ755z7i0u6vHpsqibs/G0Lubzatrx/WPV8PWD7Eqso6OvF77dcfuGb/vKN0@82fHdZzhdd90CyCW377x5nmFbcvtxkjXnGW@vsrKo6gwHuJ6thCFNiiQdfhYkJ@TIkhEJy4dBFdictBYSmgZFQ6gOpMRqYJ8CqCFVGV5Px@SRwP4TNkaVBiQUY9q@NXmAzdGVAxHutXDRwf5U2D@0Cm2Rgr7t4yDKRCgfbVQsSz3rX4m0A4pcNhpiRNqThpjBjPqK3jT9pz0sAx9GFKr8vnMXZWLqbw "APL (Dyalog Classic) – Try It Online")
uses `⎕io←1`
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~50~~ 32 bytes
```
{$_>>.&{.[++$+ ^$^a X%+$_].sum}}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WiXezk5PrVovWltbRVshTiUuUSFCVVslPlavuDS3tva/dXEiSKlGtImOsY6RjmGspjUXTAgsoGOJLGQIVGWiY4osZKID0WqEqtUUu3lQa1AlzHUsdMyAOmCSKOYbWYC1GYHlwLbrGKM6CSYM0w7hw6z/DwA "Perl 6 – Try It Online")
~~I'm new to golfing in Perl 6, so I'm sure this can be shorter.~~ Not new anymore, and back to golf this!
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 6 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
ıRṅ+iS
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVDNCVCMVIlRTElQjklODUlMkJpUyZmb290ZXI9JmlucHV0PSU1QjQlMkMzJTJDMiUyQzElNUQlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAtJTNFJTIwJTVCMTAlMkM3JTJDNSUyQzQlNUQlMEElNUIzJTJDMiUyQzElMkM5JTVEJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwLSUzRSUyMCU1QjEyJTJDMTAlMkM5JTJDMzMlNUQlMEElNUIxJTJDMyUyQzQlMkM1JTVEJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwLSUzRSUyMCU1QjMlMkMxMCUyQzEzJTJDMTQlNUQlMEElNUI0JTJDNCUyQzMlMkMyJTJDMiU1RCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMC0lM0UlMjAlNUIxMSUyQzExJTJDOCUyQzYlMkM4JTVEJTBBJTVCMyUyQzUlMkMzJTJDMiUyQzElNUQlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAtJTNFJTIwJTVCMTAlMkMxNCUyQzYlMkM0JTJDMyU1RCUwQSU1QjMlMkMyJTJDNCUyQzMlMkMyJTJDMSUyQzElNUQlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAtJTNFJTIwJTVCOSUyQzclMkM3JTJDNCUyQzIlMkMxJTJDMyU1RCUwQSU1QjclMkM4JTJDNiUyQzUlMkM0JTJDMyUyQzIlMkMxJTJDNSU1RCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMC0lM0UlMjAlNUIyOSUyQzMzJTJDMjAlMkMxNSUyQzExJTJDOCUyQzYlMkM1JTJDMzAlNUQlMEElNUIyOCUyQzIlMkM0JTJDMiUyQzMlMkMyJTJDMyUyQzQlMkM1JTJDMyU1RCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMC0lM0UlMjAlNUIxMzclMkM2JTJDMTAlMkM1JTJDOSUyQzclMkMxMiUyQzM4JTJDMzklMkMzNCU1RCUwQSU1QjElMkMyJTJDMyUyQzQlMkM1JTJDNCUyQzMlMkMyJTJDMSUyQzIlMkMzJTJDNCUyQzMlMkMyJTJDMSU1RCUyMC0lM0UlMjAlNUIyJTJDNyUyQzEzJTJDMTQlMkMxMiUyQzglMkM1JTJDMyUyQzIlMkM3JTJDOSUyQzclMkM0JTJDMiUyQzElNUQmZmxhZ3M9Qw==)
#### Explanation
```
ıRṅ+iS # Implicit input
ı # Map over the input:
R # [1..item]
ṅ+ # Plus 0-based index
i # Index into input
S # Sum the list
# Implicit output
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 10 bytes
```
ėƛ÷$?$›ǓẎ∑
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJ+UCIsIiIsIsSXxpvDtyQ/JOKAuseT4bqO4oiRIiwiIiwiWzQsMywyLDFdICAgICAgICAgICAgICAgICAgICAgICAtPiBbMTAsNyw1LDRdXG5bMywyLDEsOV0gICAgICAgICAgICAgICAgICAgICAgIC0+IFsxMiwxMCw5LDMzXVxuWzEsMyw0LDVdICAgICAgICAgICAgICAgICAgICAgICAtPiBbMywxMCwxMywxNF1cbls0LDQsMywyLDJdICAgICAgICAgICAgICAgICAgICAgLT4gWzExLDExLDgsNiw4XVxuWzMsNSwzLDIsMV0gICAgICAgICAgICAgICAgICAgICAtPiBbMTAsMTQsNiw0LDNdXG5bMywyLDQsMywyLDEsMV0gICAgICAgICAgICAgICAgIC0+IFs5LDcsNyw0LDIsMSwzXVxuWzcsOCw2LDUsNCwzLDIsMSw1XSAgICAgICAgICAgICAtPiBbMjksMzMsMjAsMTUsMTEsOCw2LDUsMzBdXG5bMjgsMiw0LDIsMywyLDMsNCw1LDNdICAgICAgICAgIC0+IFsxMzcsNiwxMCw1LDksNywxMiwzOCwzOSwzNF1cblsxLDIsMyw0LDUsNCwzLDIsMSwyLDMsNCwzLDIsMV0gLT4gWzIsNywxMywxNCwxMiw4LDUsMywyLDcsOSw3LDQsMiwxXSJd)
#### Explanation
```
ėƛ÷$?$›ǓẎ∑ # Implicit input
ėƛ # Enumerate (index, item) and map over:
÷$ # Dump onto stack and swap
?$›Ǔ # Rotate input left by (index + 1)
Ẏ∑ # Take the first (item) elements and sum
# Implicit output
```
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.