text
stringlengths 26
126k
|
---|
[Question]
[
Challenge Taken with permission from my University Code Challenge Contest
---
For some years now, the number of students in my school has been growing steadily. First the number of students was increased by classroom, but then it was necessary to convert some spaces for some groups to give classes there, such as the gym stands or, this last course, up to the broom room.
Last year the academic authorities got the budget to build a new building and started the works. At last they have finished and the new building can be used already, so we can move (the old building will be rehabilitated and will be used for another function), but it has caught us halfway through the course. The director wants to know if the move will be possible without splitting or joining groups, or that some students have to change groups.
**Challenge**
Given the amount of students of the current groups and the new classrooms (capacity), output a truthy value if it is possible to assign a different classroom, with sufficient capacity, to each of the current groups, or a falsey value otherwise.
**Test Cases**
```
Input: groups of students => [10, 20, 30], classrooms capacity => [31, 12, 20]
Output: True
Input: groups of students => [10, 20, 30], classrooms capacity => [100, 200]
Output: False
Input: groups of students => [20, 10, 30], classrooms capacity => [20, 20, 50, 40]
Output: True
Input: groups => [30, 10, 30, 5, 100, 99], classrooms => [40, 20, 50, 40, 99, 99]
Output: False
Input: groups => [], classrooms => [10, 10, 10]
Output: True
Input: groups => [10, 10, 10], classrooms => []
Output: False
Input: groups => [], classrooms => []
Output: True
Input: groups => [10, 1], classrooms => [100]
Output: False
Input: groups => [10], classrooms => [100, 100]
Output: True
Input: groups => [1,2,3], classrooms => [1,1,2,3]
Output: True
```
**Notes**
* You can take the input in any reasonable format
* You can output any Truthy/Falsey value (`1/0`, `True/False`, etc...)
* [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 4 bytes
It's always nice to see a challenge and know brachylog is gonna beat everyone.
Takes current classes as input and new classrooms as output; It will output true if it finds a way to fit the students, false otherwise
```
p≤ᵐ⊆
```
## Explanation
The code has 3 parts of which the order actually doesn't matter
```
≤ᵐ --> projects each value to a value bigger/equal then input
⊆ --> input is a ordered subsequence of output
p --> permutes the list so it becomes a unordered subsequence
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v@BR55KHWyc86mr7/z/aUMdIxzgWRENYAA "Brachylog – Try It Online")
[Answer]
# Pyth, 11 bytes
```
.AgM.t_DMQ0
```
Takes input as a list of lists, classroom sizes first, group sizes second. Try it online [here](https://pyth.herokuapp.com/?code=.AgM.t_DMQ0&input=%5B%5B31%2C%202%2C%2021%2C%201%5D%2C%5B10%2C%2020%2C%2030%5D%5D&debug=0), or verify all the test cases at once [here](https://pyth.herokuapp.com/?code=.AgM.t_DMQ0&test_suite=1&test_suite_input=%5B%5B31%2C%2012%2C%2020%5D%2C%5B10%2C%2020%2C%2030%5D%5D%0A%5B%5B100%2C%20200%5D%2C%5B10%2C%2020%2C%2030%5D%5D%0A%5B%5B20%2C%2020%2C%2050%2C%2040%5D%2C%5B20%2C%2010%2C%2030%5D%5D%0A%5B%5B40%2C%2020%2C%2050%2C%2040%2C%2099%2C%2099%5D%2C%5B30%2C%2010%2C%2030%2C%205%2C%20100%2C%2099%5D%5D%0A%5B%5B10%2C%2010%2C%2010%5D%2C%5B%5D%5D%0A%5B%5B%5D%2C%5B10%2C%2010%2C%2010%5D%5D%0A%5B%5B%5D%2C%5B%5D%5D%0A%5B%5B100%5D%2C%5B10%2C%201%5D%5D%0A%5B%5B100%2C%20100%5D%2C%5B10%5D%5D%0A%5B%5B1%2C1%2C2%2C3%5D%2C%5B1%2C2%2C3%5D%5D&debug=0).
```
.AgM.t_DMQ0 Implicit: Q=eval(input())
_DMQ Sort each element of Q in reverse
.t 0 Transpose, padding the shorter with zeroes
gM Element wise test if first number >= second number
.A Are all elements truthy? Implicit print
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
Takes the classrooms as first argument and the groups as second argument.
```
Œ!~+Ṡ‘ḌẠ¬
```
[Try it online!](https://tio.run/##y0rNyan8///oJMU67Yc7FzxqmPFwR8/DXQsOrfn//3@0oY6hjpGOcSyIBaIB "Jelly – Try It Online")
### Commented
*NB: This `Ṡ‘ḌẠ¬` is far too long. But I suspect that this is not the right approach anyway.*
```
Œ!~+Ṡ‘ḌẠ¬ - main link taking the classrooms and the groups e.g. [1,1,2,3], [1,2,3]
Œ! - computes all permutations of the classrooms --> [..., [1,2,3,1], ...]
~ - bitwise NOT --> [..., [-2,-3,-4,-2], ...]
+ - add the groups to each list; the groups fits --> [..., [-1,-1,-1,-2], ...]
in a given permutation if all resulting values
are negative
Ṡ - take the signs --> [..., [-1,-1,-1,-1], ...]
‘ - increment --> [..., [0,0,0,0], ...]
Ḍ - convert from decimal to integer --> [..., 0, ...]
Ạ - all truthy? --> 0
¬ - logical NOT --> 1
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 9 bytes
```
ñÍí§Vñn)e
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=8c3tp1bxbill&input=WzEsMiwzXQpbMSwxLDIsM10=) or [run all test cases on TIO](https://tio.run/##y0osKPnvl35oQwgXmPx/eOPh3sNrDy0PO7wxTzP1/39DA65oQwMdIwMdY4NYnWhjQx1DIyAvFkXU0ADEBgkCRQyhgkZgeVMDHROQhDFUQsdUB6Ta0hKowgShAigAEuOKBpumA0YQOyBMnWiIHFQMYieYA7UeytUx0jEGiehAWFy6uUEA)
```
ñÍí§Vñn)e :Implicit input of arrays U=students, V=classrooms
ñ :Sort U by
Í : Subtracting each integer from 2
í :Interleave with
Vñn : V sorted by negating each integer
§ : Reduce each pair by checking if the first is <= the second
) :End interleaving
e :All true?
```
---
```
ñÍeȧVn o
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=8c1lyKdWbiBv&input=WzEsMiwzXQpbMSwxLDIsM10=) or [run all test cases on TIO](https://tio.run/##y0osKPnvl35oQwgXmPx/eOPh3tTDHYeWh@Up5P//b2jAFW1ooGNkoGNsEKsTbWyoY2gE5MWiiBoagNggQaCIIVTQCCxvaqBjApIwhkromOqAVFtaAlWYIFQABUBiXNFg03TACGIHhKkTDZGDikHsBHOg1kO5OkY6xiARHQiLSzc3CAA)
```
ñÍeȧVn o :Implicit input of arrays U=students, V=classrooms
ñ :Sort U by
Í : Subtracting each integer from 2
e :Does every element return true
È :When passed through the following function
§ : Less than or equal to
Vn : Sort V
o : Pop the last element
```
[Answer]
# [Python 2](https://docs.python.org/2/), 49 bytes
Outputs by exit code, fails for falsy input.
```
g,r=map(sorted,input())
while g:g.pop()>r.pop()>y
```
[Try it online!](https://tio.run/##XY4xj4MwDIX3/AqLCaToREJvKFK7lfWWbqgDRy2K2pLIDbry67k4pKh3g/Xi9z3HtpO7mEHPrTkj7CBJkrmTtLs3Nn0YcniW/WBHl2aZ@Ln0N4Su7D6ssWm2p6jT7KciPdKIpQBwNLEA4BNb4M9DZ6kfXAgJRi1aB4ev6kBkaMl/EzbXNxikN0P5Nl81twfOtcolaF9FfpJQF0qC0uycxD@k8tAyYFOtQMfYp68N42LF3uSn1@2Wo5s/UXYDEfWyYBlTr92x8SgmXn48J7TradGQWhbBk8vzFw "Python 2 – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 10 bytes
```
yn&Y@>~!Aa
```
[Try it online!](https://tio.run/##y00syfn/vzJPLdLBrk7RMfH//2gjAx0FQyA2NojlAnNA2BSITQxiAQ) Or [verify all test cases](https://tio.run/##y00syfmf8L8yTy3Swa5O0THxv0vI/2hDAx0FIyA2NojlijY21FEwNAIJADkoMoYGYB6ICRIzhIkbQRWZArEJ2Ai4LFAQxATSlpZACRMUlSBBqATUKghG58ARWATiEDAJcxOUr2OkYwymISwA).
### Explanation
Consider inputs `[20, 10, 30]`, `[20, 20, 50, 40]` as an example. Stack is shown bottom to top.
```
y % Implicit inputs. Duplicate from below
% STACK: [20 10 30]
[20 20 50 40]
[20 10 30]
n % Number of elements
% STACK: [20 10 30]
[20 20 50 40]
3
&Y@ % Variations. Gives a matrix, each row is a variation
% STACK: [20 10 30]
[20 10 30
20 20 40
20 20 40
···
50 40 20]
>~ % Less than? Element-wise with broadcast
% STACK: [1 1 1
1 1 1
1 1 1
···
1 1 0]
! % Transpose
% STACK: [1 1 1 ··· 0
1 1 1 ··· 1
1 1 1 ··· 1]
A % All. True for columns that only contain nonzeros
% STACK: [1 1 1 ··· 0]
a % Any. True if the row vector contains at least a nonzero. Implicit display
% STACK: 1
```
[Answer]
# [Haskell](https://www.haskell.org/), 40 bytes
```
c%l=[1|x<-l,x>=c]
s#g=and[c%s<=c%g|c<-s]
```
[Try it online!](https://tio.run/##dY/BCoMwEETvfsWCFVpYIYl6UIyH3voNIQeJxUpTLdWDB/89TVQQqoUcJjNvNtlH2T/vWhujAs0FncY81DgWXEmv92tetpVQQZ9zFdSTysNemrN/gSwDcWsHCWGxiWvXae9VNi1wqDoP3p@mHeAEriAoQUYwIhJERJEye5P/EUqc3hE2pivBZjghGO@oaKUwQTcnTS0eb7g1nPdTmh/F@Rz8a/EttW8d0csG@2Td7ChDhpGLcVHmCw "Haskell – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~14~~ ~~12~~ 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
€{í0ζÆdP
```
Port of [*@Sok*'s Pyth answer](https://codegolf.stackexchange.com/a/179562/52210), so make sure to upvote him as well!
Takes the input as a list of lists, with the classroom-list as first item and group-list as second item.
[Try it online](https://tio.run/##yy9OTMpM/f//UdOa6sNrDc5tO9yWEvD/f3S0oY6hjpGOcaxONISOBQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/R01rqg@vNTi37XBbSsB/nf/R0dHGhjoKhkY6CkYGsTrRhgYgho6CsUFsrI5CNJAPFjAAcdDljKB8UyA2AasA8QyRVJigqNBRsLQEYaA1xnCFQEkQEywJsxIiZwg2EiIGsx4qDheDOxKuAMnZcGGomI6hjpGOMVgIzIiNBQA).
**Explanation:**
```
€{ # Sort each inner list
í # Reverse each inner list
0ζ # Zip/transpose; swapping rows/columns, with 0 as filler
Æ # For each pair: subtract the group from the classroom
d # Check if its non-negative (1 if truthy; 0 if falsey)
P # Check if all are truthy by taking the product
# (and output implicitly)
```
---
**Old 12-byte answer:**
```
æε{I{0ζÆdP}à
```
Takes the classroom-list first, and then the group-list.
[Try it online](https://tio.run/##yy9OTMpM/f//8LJzW6s9qw3ObTvclhJQe3jB///RhjqGOkY6xrFc0RAaAA) or [verify all test cases](https://tio.run/##yy9OTMpM/W9o4ObpYq@kkJiXoqBk73l4QiiQ86htEpBT/P/wsnNbqyOqDc5tO9yWElB7eMF/nf/RxoY6CoZGOgpGBrFc0YYGIIaOgjGEA@ZhiBtBOaZAbAITMITJmqDI6ihYWoIwUMIYrgooCWIaQCUMoRKGIO0QhFUI5hBDmNtgQiBCx1DHSMcYzALRAA).
**Explanation:**
```
æ # Take the powerset of the (implicit) classroom-list,
# resulting in a list of all possible sublists of the classrooms
ε # Map each classroom sublist to:
{ # Sort the sublist
I{ # Take the group-list input, and sort it as well
0ζ # Transpose/zip; swapping rows/columns, with 0 as filler
Æ # For each pair: subtract the group from the classroom
d # Check for everything if it's non-negative (1 if truthy; 0 if falsey)
P # Check if all are truthy by taking the product
}à # After the map: check if any are truthy by getting the maximum
# (and output the result implicitly)
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~77~~ 74 bytes
```
a=>b=>a.Count==a.OrderBy(x=>-x).Zip(b.OrderBy(x=>-x),(x,y)=>x>y?0:1).Sum()
```
[Try it online!](https://tio.run/##jZJRa4MwEMff/RR5TCCVRLuHrk0KGwwGgw32tuJDdMqEVUcSN6Xss7tLLaKW1aIhuf/d/xc8LzGLxOTtQ1Ukm8en3NhNXlhJp3Fclp9SZqJVQsZCKv@@rAorhPKf9Xuq7xpcC7moif@Wf@F4IlJc04YIWctmy2458V@rPSbt2vOAvYvcg2xqrEECFekP6tWDNwgHwYEzigJYIfulAznkFPHApUAeZq5yc3bUL3udj597gxPyBtbyMiHsCVDujrCvViPackRz6VPJ/9TJl3RX8Pk@9GUj1JX3zNOnDZ5xnP@PWQ90Cno5NoKtl90Lk5aVOlXJB/5W@jhrUNrNHPEQetFgxBl2wo5FpDvwiJB1@wc "C# (Visual C# Interactive Compiler) – Try It Online")
Commented code:
```
// a: student group counts
// b: classroom capacities
a=>b=>
// compare the number of student
// groups to...
a.Count==
// sort student groups descending
a.OrderBy(x=>-x)
// combine with classroom
// capacities sorted descending
.Zip(
b.OrderBy(x=>-x),
// the result selector 1 when
// the classroom has enough
// capacity, 0 when it doesn't
(x,y)=>x<y?0:1
)
// add up the 1's to get the number
// of student groups who can fit
// in a classroom
.Sum()
```
[Answer]
## Haskell, 66 bytes
```
import Data.List
q=sortOn(0-)
x#y=and$zipWith(<=)(q x)$q y++(0<$x)
```
[Try it online!](https://tio.run/##dY89C4MwEIZ3f8WBDgm9lsToIJitY6FjB3EIWDDUbzNo/7yNH1CoFm64e9/nvnLVv55FMU26bOrOwFUZdbnp3jit7K1wrwg7U2dwR6mqzHvr5qFNTmJJSQsD9VoYTyfCYm@gU6l0BRKy2oGm05UBD4hLIeEMfYaCpZAIjty3Vfof4WzOd4S1@Ub4CxwyDHaU2CgMcZ4TRRYPvrgVZu2naVmKSxzcteqW2ncd0esHe2f77MhDH8Vs45pNHw "Haskell – Try It Online")
[Answer]
# Bash + GNU tools, 68 bytes
```
(sort -nr<<<$2|paste -d- - <(sort -nr<<<$1)|bc|grep -- -)&>/dev/null
```
69 bytes
```
(paste -d- <(sort -nr<<<$2) <(sort -nr<<<$1)|bc|grep -- -)&>/dev/null
```
[TIO](https://tio.run/##VY1JCoMwGIX3/ykeRbQuQgZ1IZX2It3YJtSCqCQdFrVnt4mWDhCS7w28HGrXTPfm3BpYU2s4xPFCdgPdkzMXMIZV9HCcg0fJvkueq6Dtj6Zp7Xrrm52tqipS41C7iwHTDAzVXybT8XAcT9YMYZel8ZZrc@PdtW0nc2x6RDvSfWdokgJKIBOUSUjlmT6OFIEEeSVnQ81JIZD7@ttEgdArS8q/qZfBCVPz@QItZtgmuXwxIxQyfy/vCw)
takes student rooms as first and second argument as string numbers delimited by newline
returns exit status 1 for true or 0 for false
[Answer]
# [Perl 5](https://www.perl.org/) `-pal`, ~~67~~ 62 bytes
*@NahuelFouilleul saved 5 bytes with a rearrangement and a grep*
```
$_=!grep$_>0,map$_-(sort{$b-$a}@F)[$x++],sort{$b-$a}<>=~/\d+/g
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3lYxvSi1QCXezkAnNxFI62oU5xeVVKsk6aok1jq4aUarVGhrx@ogCdrY2dbpx6Ro66f//29ooGBkoGBswGVsoGBopGBo8C@/oCQzP6/4v66vqZ6BocF/3YLEHAA "Perl 5 – Try It Online")
[67 bytes version](https://tio.run/##K0gtyjH9/9@hyDY3saBaozi/qKRaJUlXJbHWwU0zWltbRbkkVlclvhZJwsbOtk4/JkVbP91aJd5WyaFISbFOX1f//39DAwUjAwVjAy5jAwVDIwVDg3/5BSWZ@XnF/3V9TfUMDA3@6xYk5gAA "Perl 5 – Try It Online")
Takes the space separated list of class sizes on the first line and the space separated list of room sizes on the next.
[Answer]
# Common Lisp, 74 bytes
`(defun c(s r)(or(not(sort s'>))(and(sort r'>)(<=(pop s)(pop r))(c s r))))`
## Non-minified
```
(defun can-students-relocate (students rooms)
(or (not (sort students #'>))
(and (sort rooms #'>)
(<= (pop students)
(pop rooms))
(can-students-relocate students rooms))))
```
[Test it](https://rextester.com/NMOUG17878)
Note that sort permanently mutates the list, and pop rebinds the variable to the next element.
In effect this just recursively checks that the largest student group can fit in the largest room. There are 3 base-cases:
1. No students - return T
2. Students, but no rooms - return NIL
3. Students and rooms, but largest student group larger than largest room - return NIL
[Answer]
# [Python 2](https://docs.python.org/2/), ~~71~~ ~~67~~ 64 bytes
```
lambda g,c:s(g)==s(map(min,zip(s(g)[::-1],s(c)[::-1])))
s=sorted
```
[Try it online!](https://tio.run/##dZA5DoMwEEV7TmEpjS1NJMaQAiS3OUE6QkHYgsQmTIrk8sQGQxbhYuRZ3v/2uH@O967lUyGuU500tywhJaShpCUTQtIm6WlTtfCqeqp7URgeMQZJU5MyxhwpZDeMeTb1Q9WOpKARukC4Cs@NgUQeAkGuOzEjB3IZHrnjWFh053Ihz0ktv1GN4YZyIzyp8HetvY1XlE7VGQRa6/9odXee7F26vGoxQusGZqpYq4lVavbeFeLnV1bk3wI4eDMES7oy0xs "Python 2 – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 50 bytes
```
\d+
$*
%O^`1+
%`$
,
^((1*,)(?=.*¶((?>\3?)1*\2)))*¶
```
[Try it online!](https://tio.run/##RY5NCgIxDIX3OccU0k6QpJ1ZDEV7BBduy1BBF25cyJzNA3ixmhZ/4EG@vBeSPK7b7X6uBk8l1nwZYXBgjmuREUwZgGBFFEcW037nXk/EdMghWXHZW2vVqVWYPFPgGITEK8PPEW7EoJ10w/dkZpoYwsekmdrcssTpn2qrAt1AXfCFCLFz263QT3QkTyHqB62@AQ "Retina 0.8.2 – Try It Online") Link includes test suite. Takes two lists of groups and rooms (test suite uses `;` as list separator). Explanation:
```
\d+
$*
```
Convert to unary.
```
%O^`1+
```
Reverse sort each list separately.
```
%`$
,
```
Append a comma to each list.
```
^((1*,)(?=.*¶((?>\3?)1*\2)))*¶
```
Check that each of the numbers in the first list can be matched to the appropriate number in the second list. Each time `\3` contains the previously matched rooms and the next group `\2` therefore needs to be able to fit into the next room. The `(?>\3?)` handles the case of the first room when there are no previous rooms yet.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 28 bytes
```
W∧⌊講⌈§θ¹⌈§θ⁰UMθΦκ⁻ν⌕κ⌈κ¬⊟θ
```
[Try it online!](https://tio.run/##bY47C8MwDIT3/gqPMrjg9DF1CoWWDinZgweTGGLiR@I6bf69K3vpUsEt3@lO6kcZei9NSp9RG0WgdgM02mm7WlgoI08f4R6UjCpAI7fC6/hwg9pgYaSiuPOHc1oGrfnqrZXYivSmTe6ZMKLd@gKXEVrTr2MqucuuDdpFyNdbP@MnyFLquu7AGck6o05cMFJIhTpyIUTav80X "Charcoal – Try It Online") Link is to verbose version of code. Takes a list of lists of rooms and groups and outputs `-` if the rooms can accommodate the groups. Explanation:
```
W∧⌊講⌈§θ¹⌈§θ⁰
```
Repeat while a group can be assigned to a room.
```
UMθΦκ⁻ν⌕κ⌈κ
```
Remove the largest room and group from their lists.
```
¬⊟θ
```
Check that there are no unallocated groups remaining.
[Answer]
# JavaScript, 56 bytes
```
s=>c=>s.sort(g=(x,y)=>y-x).every((x,y)=>c.sort(g)[y]>=x)
```
[Try it](https://tio.run/##ZZBBDoIwEEX3nMJlm4y1BVy4KEtP4K42kWAhGqSGIqGnxxaoRkm6mP7/5nc697zPTdHent220Vc1lnw0PCt4ZojRbYcqjgawmGd2O2CietVatCjFQmBhZcYHPBa6MbpWpNYVElEkBKMQU0ioBJEwYLG7SQmb3W5zal/qF2DU18E/5rXxgHPZAsQTu6eQ/oUkCwN78CGHg4PTL@wEr00tIXZ6D6YzG995ZhHEqmEFzkP/cix85eOEBogh8R7MlQxWJMkjfyIk3FKl22qJBowsxuSub83l3Fzw@AY)
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 34 bytes
```
{none [Z>] $_>>.sort(-*)>>[^.[0]]}
```
[Try it online!](https://tio.run/##rZBRa4MwFIWf56@4FFm1pGq0G3Rgyh42GAz6MvYw60Z0OgpqxOiDtP3tzmQyKnWrjD1cEsg53zk3eVQk101aw2UMLjS7jGUReC/EB/WNEIOzotTmM50Q79XwLN8/NDErQEu2WcR1mBNQKQI1aCd0JxPYKRec1rCKNZUaIUsDzdx4xmy18c2WYdw93z7qCKbCOEV7Neg0T0UV7e9pwiNTVw7NQ5ZX5Q18FKzKObAYeFm9R1nJwSXgYQuB3Y5j@QjChHJeMJZyCGlOw21ZS5GDEWBbCH1lXZWSJ1IU5R/g2JKqI7Tsfo4tuPgc2@4KXLWzOFNeLvoNbT3i2p7LZT9A6BY9rtBI3e8bCOMpCneReES9I@0J50/hIyOHWlsjAod6yj/t2X@MRjZyBgDo66Hn/wQ "Perl 6 – Try It Online")
Takes input as a list of two lists, the groups and the classrooms, and returns a None Junction that can be boolified to true/false.
### Explanation:
```
{ } # Anonymous code block
$_>>.sort(-*) # Sort both lists from largest to smallest
>>[^.[0]] # Pad both lists to the length of the first list
none # Are none of
[Z>] # The groups larger than the assigned classroom
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 57 bytes
```
->c,r{r.permutation.any?{|p|c.zip(p).all?{|a,b|b&&a<=b}}}
```
[Try it online!](https://tio.run/##ZZBBCoMwEEX3nsJVaWEaTGIXQm0PErKIolSwNogurPHsdhJTtXQxzMz7f8gnbZ8Nc5nO51sO7dgSXbTPvlNd9WqIaob7aLTJybvSR30iqq4RKMhMdjioa5pN0zSLQAgaQciweCQhFJxCSJklUsKfSiO3es1yumrMOy9YsXfw1YHcjtiTxLrjH7elTnFXy0vLJd3l8Duqm2@n@oBfsubdGDDgDsMyykCSQuWP0eAHGh2WAruc5g8 "Ruby – Try It Online")
Takes `c` for classes, `r` for rooms. Checks all permutations of rooms instead of using sort, because reverse sorting costs too many bytes. Still looks rather long though...
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~105~~ ~~93~~ ~~91~~ ~~82~~ ~~81~~ ~~79~~ ~~77~~ ~~76~~ 74 bytes
Now matches dana's score!
```
n=>m=>{n.Sort();m.Sort();int i=m.Count-n.Count;i/=n.Any(b=>m[i++]<b)?0:1;}
```
Throws an error if false, nothing if true.
-12 bytes thanks to @Destrogio!
[Try it online!](https://tio.run/##pZBNi4MwEIbv/gqPSq012h7amJRS2FNve9jDsoc2KB2oI@hIKZLfbpN@sq0syB6GGeZ9M89MVD1WNXQfDap0AzWlgCSDlSIo8dmQMhcdClkI2WL4WVbk@by4F8bhgijCddkgjfGaOUwEhis8eTvz7htGo5905y@jBeO64w5Vp9bJPcyO7oPSsihwYxNJpP0XKWGBy2Ira587XxVQtgHMPKqazDS0o7ak9u1TyLeH2ih6MIlFF62X8wfmwnnFWATrx8S3DWYmphY2gNWHSh4oM9OWJs/nb9jpL6y1XG38v6f2/KPdYtDk7gw "C# (Visual C# Interactive Compiler) – Try It Online")
# Explanation
```
//Function taking in a list, and returning another function
//that takes in a list and doesn't return
n=>m=>{
//Sort the student groups from smallest to largest
n.Sort();
//Sort the classrooms fom smallest capacity to largest
m.Sort();
//Initialize a variable that will function as a sort of index
int i=m.Count-n.Count;
//And divide that by...
i/=
//0 if any of the student groups...
n.Any(b=>
//Don't fit into the corresponding classroom and incrementing i in the process
/*(In the case that a the amount of classrooms are less than the amount of
student groups, an IndexOutOfRangeException is thrown)*/
m[i++]<b)?0
//Else divide by 1
:1;
}
```
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 183 bytes
```
a->{int b=a[0].length;Arrays.sort(a[0]);Arrays.sort(a[1]);if(b>a[1].length){return false;}for(int i=0;i<b;i++){if(a[0][i]>a[1][i]){return false;}}return true;}
```
[Try it online!](https://tio.run/##tVBNa8MwDL33V@gYUzc4/TgUr4X9gPXSY8jBaZ3OXWoHx@koxr89k7PAoNDt0oFB0pPfe5LO4ipmppH6fPzo1aUx1sEZsbRzqk5frRW3lk8OtWhbeBNK@wmA0k7aShwk7HxpTC2FBpsgmhd5AYLwgJ9aJ5w6wA70Bnox23rsQ7kROSvSWuqTe@ff6mmLnknEyR2SIaKqpNzGdCQRb6XrrIZK1K3koTKDM6gN4@ql5Go6JR5JUS9XxUDFeE8LY@lsh1XPceCmK2sceJz7atQRLrhwsndW6VNeCBJ3B9jfWicvqelc2mDH1TrRqU20/ITxBN5njM4ZXbBAPcZsThdZCITwRwKPO79JZyzm7B@U50O6YnT5NPUF3iGq0xWNc6/XaLP8sUEgYk8yG45Dh/e3ZJiE/gs "Java (OpenJDK 8) – Try It Online")
With a little helpful advice from [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen/%22Kevin%20Cruijssen%22) and simply another glance over my code myself, I can decrease my score by a whole 9% just by replacing three English words!
# [Java (OpenJDK 8)](http://openjdk.java.net/), 166 bytes
```
a->{int b=a[0].length;Arrays.sort(a[0]);Arrays.sort(a[1]);if(b>a[1].length){return 0;}for(int i=0;i<b;){if(a[0][i]>a[1][i++]){return 0;}}return 1;}
```
[Try it online!](https://tio.run/##tVDLasMwELznK/ZoNYqQ8zgENYF@QHPJ0fggJ0oq15GNLKcEoW93V8bQUkh7SUFIw@zuzKxKeZWzulGmPL73@tLU1kGJHOucrtiTmBwq2bbwKrXxEwBtnLIneVCw84jBJnhneZaDJCJgQ@uk0wfYgdlAL2fboavYyIznrFLm7N7Ei7Xy1rIWrZLIkx9Miow@JcU2wnGIeKtcZw1wEU714Ap6w4V@LgTx2B2FMp0PM5meTvPvE2GEqQi9wJBNV1QYcsx6rfURLrhgsndWm3OWSxJ3BdjfWqcurO4ca7DiKpMYZhOjPmBc2/uU0zmnCx6oxzed00UaAiHinsD9ym/SKY@Y/4PyfIArTpcPU1/gP0R1uqIx93qNNssvGyQi9yCz4XPocP6WDJPQfwI "Java (OpenJDK 8) – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 80 bytes
```
param($s,$c)!($s|sort -d|?{$_-gt($r=$c|?{$_-notin$o}|sort|select -l 1);$o+=,$r})
```
[Try it online!](https://tio.run/##dZJda4MwFIbv/RVZORsJi2C0u@iGzKv9gt0X0XQbpMYlkQ2qv90d48faYgMhOec875vPWv9IYz@lUj0cSEpOfZ2b/EjBcijYHY6t1caRsGxfT7APPxwFk0IxRpV2XxXozjOtlUoWiCoi2Avox5SD6VjfBUFGA4KN04yKiJMYexIxTjKaCE5EPKQwBGcayW6hIvKxB99yZc/IgRL/ZDwJn7BvPf9@YZwsODLDFMfdzku3F9IhPZWul5y2NBqJlUUuap5ftbghnE@8IhNn1zERVwY85snI8Hk@IYy05J6cPArWNaWsnMVqoXJrjdbHIZC/Nb6jLPE7wH5EjbSNcph4wF@yCM91ntsAndBQfi8@7Hk22ARd/wc "PowerShell – Try It Online")
Less golfed test script:
```
$f = {
param($students,$classrooms)
$x=$students|sort -Descending|where{
$freeRoomWithMaxCapacity = $classrooms|where{$_ -notin $occupied}|sort|select -Last 1
$occupied += ,$freeRoomWithMaxCapacity # append to the array
$_ -gt $freeRoomWithMaxCapacity # -gt means 'greater than'. It's a predicate for the 'where'
} # $x contains student groups not assigned to a relevant classroom
!$x # this function returns a true if $x is empty
}
@(
,(@(10, 20, 30), @(31, 12, 20), $true)
,(@(10, 20, 30), @(100, 200), $False)
,(@(20, 10, 30), @(20, 20, 50, 40), $True)
,(@(30, 10, 30, 5, 100, 99), @(40, 20, 50, 40, 99, 99), $False)
,(@(), @(10, 10, 10), $True)
,(@(10, 10, 10), @(), $False)
,(@(), @(), $True)
,(@(10, 1), @(100), $False)
,(@(10), @(100, 100), $True)
,(@(1,2,3), @(1,1,2,3), $True)
) | % {
$students, $classrooms, $expected = $_
$result = &$f $students $classrooms
"$($result-eq$expected): $result"
}
```
[Answer]
# [R](https://www.r-project.org/), 65 bytes
```
function(g,r)isTRUE(all(Map(`-`,sort(-g),sort(-r)[seq(a=g)])>=0))
```
[Try it online!](https://tio.run/##bVC9DoIwEN59ChKXu@RM2oIDAyYOOuniz2RMIAQaEgJa8PmR0gKCDJd@ve@nd1VNGjTpp4jrrCxAksKsul3uB4jyHM7RC8JNSFWpathItEDho0reEAUSn7gLGGKTQgyckSPachlSDC4nhwvdQXTWjs5c/as4665Gc9yfrkakBXwQCWvZtuXN4txB2fIatqfva5c3celux/w@lBV1IhMFZhITxBfmtX0a9MshE3oaYHedrcnHP@jJ0UaC3I4mA3u2@QI "R – Try It Online")
] |
[Question]
[
**Problem:**
Find the number of leading zeroes in a 64-bit signed integer
**Rules:**
* The input cannot be treated as string; it can be anything where math and bitwise operations drive the algorithm
* The output should be validated against the 64-bit signed integer representation of the number, regardless of language
* [Default code golf rules apply](https://codegolf.stackexchange.com/tags/code-golf/info)
* Shortest code in bytes wins
**Test cases:**
These tests assume two's complement signed integers. If your language/solution lacks or uses a different representation of signed integers, please call that out and provide additional test cases that may be relevant. I've included some test cases that address double precision, but please feel free to suggest any others that should be listed.
```
input output 64-bit binary representation of input (2's complement)
-1 0 1111111111111111111111111111111111111111111111111111111111111111
-9223372036854775808 0 1000000000000000000000000000000000000000000000000000000000000000
9223372036854775807 1 0111111111111111111111111111111111111111111111111111111111111111
4611686018427387903 2 0011111111111111111111111111111111111111111111111111111111111111
1224979098644774911 3 0001000011111111111111111111111111111111111111111111111111111111
9007199254740992 10 0000000000100000000000000000000000000000000000000000000000000000
4503599627370496 11 0000000000010000000000000000000000000000000000000000000000000000
4503599627370495 12 0000000000001111111111111111111111111111111111111111111111111111
2147483648 32 0000000000000000000000000000000010000000000000000000000000000000
2147483647 33 0000000000000000000000000000000001111111111111111111111111111111
2 62 0000000000000000000000000000000000000000000000000000000000000010
1 63 0000000000000000000000000000000000000000000000000000000000000001
0 64 0000000000000000000000000000000000000000000000000000000000000000
```
[Answer]
# x86\_64 machine language on Linux, 6 bytes
```
0: f3 48 0f bd c7 lzcnt %rdi,%rax
5: c3 ret
```
Requires Haswell or K10 or higher processor with `lzcnt` instruction.
[Try it online!](https://tio.run/##S9ZNT07@/19DK01TQ9NWKabCzTimwsQipsLALabCySWmwtkciI2VrLlyEzPzNDSruQqKMvNK0jSUVFNi8pR00jQMfTQ1rTFEDcCitf///0tOy0lML/6vW5VakZpcXJKYnA0A "C (gcc) – Try It Online")
[Answer]
# [Hexagony](https://github.com/m-ender/hexagony), ~~78~~ 70 bytes
```
2"1"\.}/{}A=<\?>(<$\*}[_(A\".{}."&.'\&=/.."!=\2'%<..(@.>._.\=\{}:"<><$
```
[Try it online!](https://tio.run/##BcFBDkAwEAXQs5jQNha/WMq09BwmaSyEFVvSzNnrvet49/O5v1onGkmgvmgKLEt03EqvW3ZJCEVBBlZM8AA1QSbbMeBWRGRIkKIzceS21uEH "Hexagony – Try It Online")
Isn't this challenge too trivial for a practical language? ;)
side length 6. I can't fit it in a side length 5 hexagon.
### Explanation
[![](https://i.stack.imgur.com/3azaW.png)](https://i.stack.imgur.com/3azaW.png)
[Answer]
# [Python](https://docs.python.org/2/), 31 bytes
```
lambda n:67-len(bin(-n))&~n>>64
```
[Try it online!](https://tio.run/##ZYu7CsJAEEX7@YpUkhSBmdnZeQj6JTaKioG4BomIjb8etxO0uofDudNrvtwKL@fNbhn318Nx35S1Wj@eSnsYStuXrlu9y3arsjwvw3hqaD3dhzI353Yo02Nuu27pCfpgTskYk3oWs@zo8O8MRInUFcmFLbkFJiBmiUrhKrWTIIJANIrgehSsC5Ix5QitL0MJ/RUZmGrrScW/aMBAgB8 "Python 2 – Try It Online")
The expresson is the bitwise `&` of two parts:
```
67-len(bin(-n)) & ~n>>64
```
The `67-len(bin(-n))` gives the correct answer for non-negative inputs. It takes the bit length, and subtracts from 67, which is 3 more than 64 to compensate for the `-0b` prefix. The negation is a trick to adjust for `n==0` using that negating it doesn't produce a `-` sign in front.
The `& ~n>>64` makes the answer instead be `0` for negative `n`. When `n<0`, `~n>>64` equals 0 (on 64-bit integers), so and-ing with it gives `0`. When `n>=0`, the `~n>>64` evaluates to `-1`, and doing `&-1` has no effect.
---
**[Python 2](https://docs.python.org/2/), 36 bytes**
```
f=lambda n:n>0and~-f(n/2)or(n==0)*64
```
[Try it online!](https://tio.run/##ZYtLasNAEAX3fQotpYBId09PfwzyXWQUIYEzFkYheOOry7MLxKtXFPW2x77cCh/HPFzH78s0NuVUzjiW6dnPbfnk7nZvyzBg96Fy/C7r9auh03Zfy97M7Vq2n73tuqMn6IM5JWNM6lnMsqPDuzMQJVJXJBe25BaYgJglKoWr1E6CCALRKILrUbAuSMaUI7S@DCX0v8jAVFtPKv6HBgwE@AI "Python 2 – Try It Online")
Arithmetical alternative.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 14 bytes
```
__builtin_clzl
```
Works fine on tio
# [C (gcc)](https://gcc.gnu.org/), ~~35~~ 29 bytes
```
f(long n){n=n<0?0:f(n-~n)+1;}
```
[Try it online!](https://tio.run/##S9ZNT07@/z9NIyc/L10hT7M6zzbPxsDewCpNI0@3Lk9T29C69n9uYmaehmZ1QVFmXkmahpJqioKSTpqGhaamNUIIJGIAFKn9DwA "C (gcc) – Try It Online")
Than Dennis for 6 bytes
# [C (gcc)](https://gcc.gnu.org/) compiler flags, 29 bytes by David Foerster
```
-Df(n)=n?__builtin_clzl(n):64
```
[Try it online!](https://tio.run/##ZYzLTsMwEADv@YpVEVJMG@RX/KAtXPgLqKLUIakl46A05QDi11mWXhBw2tHs7IZqCAEvYg7p1D3B5jh3Ke6vD7fFLxdHUogxz/Dcxlx@QzsNYQXh0E5wRfz6sGPFewHQjxOcgwhbEGsam3NLtFwyCgBeJtr35eKye8yLFfRlO4@pPD@JO8bYuvhArARWXkqlrOTKuFpbWzvu8L@zqI0QxhkunJZWOeu5QiGl9kTeGU2d9kKg59wK7yUdak4Tdc1V7b2hK8u1N39FjVJQ65TR7gctShTIP0Of2uGI1X1fZrbNd02zP8U0x9yE9JbI3Rj9BQ "C (gcc) – Try It Online")
[Answer]
# Java 8, ~~32~~ 26 bytes.
`Long::numberOfLeadingZeros`
Builtins FTW.
-6 bytes thanks to Kevin Cruijssen
[Try it online!](https://tio.run/##bZDBboMwDIbP5Sl8BGlFCQSSlHXHSZO67dDbph1SGmg6CAhCu2rqs7Mg0Wpq8cX2b3@2k704iPl@@92rsq4aA3ub@51Rhb9OhdaySZy7Stbp1KhK@89jkDhO3W0KlUJaiLaFV6E0/DpgbdRbI4x1h0ptobRVd20apfPPLxBN3npj83@7zH5cVTp/gBdtZC6bJ8hg2Q/SYqG7ciOb92wlxdbO@pBN1fa3YxJnNhtfAu3ol6DlEUbVXZ9aI0tfac8@4xY/7lQhwR1JfyfaN/ljhv2uN3X1YIWtgrZbLpS@IskkMF5Qdcav7a@YQruZL@q6OLnam2DOznR27ucY5jwIwpAGKIxZRCiNGGJwr1EgMcYxixFmJKAhoxyFgIOAcBtxFhPbRzjGwBGimPPAggRZDyRCYcR5bCmKCI/hVokgwLaZhTFhw13XjNoYMKA/ "Java (JDK) – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 25 bytes
Takes input as a BigInt literal.
```
f=x=>x<0?0:x?f(x/2n)-1:64
```
[Try it online!](https://tio.run/##fdFLbsIwEAbgfU@RZbJIMy@PZ1ApZ0GUVK2QgwBVuX3qBQjkQLzx5tP88/jd/m3Pu9PP8dKm4Ws/Tf16XH@OH7CB1bjp67Gj1LS4Upl2QzoPh/37Yfiu@7rFVM1e01RdV8FbQZ2IORKwWpAYg4Gl53QuY7pWxYKKIqopoAlFtujAN0oFRSLxDNxUclVxxBvlsgGAiO6U0wXyn@5jYdmsBODgrjk@grg@Wly24dGW7RLmcGMVS@Vq@aWNc1vORk8udrU6W9mCLevCgpXpHw "JavaScript (Node.js) – Try It Online")
Or [**24 bytes**](https://tio.run/##fdHNbsIwDAfw@56iJ9QeutqO49iTgGdBjE6bUIoATX37LgfQkAvNJZef/PfHz@53d9mfv0/XNg@fh2nq1@N6M27HDaxWfT12lJsWP4Sn/ZAvw/Hwfhy@6r5uMVez1zRV11Xw5qgRhZAIgmjklKKC5ud0LlO@VUVHWRBFBVCZUtBkEO6UHEUitgJMhUtVNsQ7Db4BgIRmVNIZyp//x0LfLEcI0UxKfAI2ebS4bOOj9e0SlnANwpr9asNLm@bWz0ZPLnazMlvZgvV1YcHy9Ac) by returning *false* instead of \$0\$.
[Answer]
# [Python 3](https://docs.python.org/3/), 34 bytes
```
f=lambda n:-1<n<2**63and-~f(2*n|1)
```
[Try it online!](https://tio.run/##ZYtLasNAEAX3OcUsJdGC/k1/jHMYGSMscMbGeGMIuboyu0C8ekVR7/56Xm5N9n39vC5fp/NS2mGmYzvyNJks7Tz/rANP7ZvGfb09yla2VmaCOZlFnFEsqrrXwIB356BGZGFIoewSnihAzJqdMkx7p0kEieiUyf2o2Be0otRM6y9HTfsvKjD1NsQ0/tCBgQAPH6XcH1t7DuuwjeP@Cw "Python 3 – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 18 bytes
```
0{[:I.1,~(64$2)#:]
```
[Try it online!](https://tio.run/##dY5BCsJADEX3PUVQoRZqSTKZTFLoATyDuBKLuHHRpejVx9l0NsVVwvvk/TzzvEwDIIyAGd@X8TxQ/z2qHLjbj9fcNbsB2nkaWujhM8K8NM399njBDCeqmzOHkBiDWpSUoqGt2TZKayRKpKZIJpyCJcewRsQsXoCbSrkSp1rmiIncudgEy6y2iCG6a1ElFNc/PK6cqQgsqNiG1A@rvLZj/gE "J – Try It Online")
# [J](http://jsoftware.com/), 19 bytes
```
1#.[:*/\0=(64$2)#:]
```
[Try it online!](https://tio.run/##dY4xDsIwDEX3nsKiSKUIiu04jl2pJwEmRIVYGDpz9pClWSomW@/L7/ud52UaAGEEzNQO1/F4ueF0UNlz34733De7Abp5Gjo4wXeEeWma5@P1gRnOVDdnDiExBrUoKUVDW7NtlNZIlEhNkUw4BUuOYY2IWbwAN5VyJU61zBETuXOxCZZZbRFDdNeiSiiuf3hcOVMRWFCxDakfVnltx/wD "J – Try It Online")
## Explanation:
```
#: - convert
] - the input to
(64$2) - 64 binary digits
= - check if each digit equals
0 - zero
[:*/\ - find the running product
1#. - sum
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 18 bytes
*-2 bytes thanks to Jo King*
```
64-(*%2**64*2).msb
```
[Try it online!](https://tio.run/##rdNRb4IwEAfw936Ke9kEFL22x7WNWeb3mD7opomJzkWezLLPzi4bEzJIMOC9FNLml7s/5WN7PnBxvMDjDp6gYEqj5MEkCVNi4ukx3xRztTudITrs37d5DJ8KQE4v1nJ6@no6bqLZMn1evo1n8VzJXr6@wC5arF9wFU9GsM9hNBnLq16pryLV0Cz8e9ADS6XBGGudQcs@I@cyj77G47BSTd2Jeh1jaPfEWrNn1J6Ms94FtADmyg/0lTaGgqDBM0n3FLS0bisef/LpzQdEp0MwkgyhrGXkFV9Wv6@gKEObhcCSjEMKXF6YBt/P/89nv7xp8r0CUkZLKt4y@dq9t218W3WNVPGuztsbeezsvuWnBb61@67ZlG7l7V141ApbeboPj98 "Perl 6 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 22 bytes
```
->n{/[^0]/=~"%064b"%n}
```
[Try it online!](https://tio.run/##bY69CsJAEIR7n0ICKUP27/aniC8SYpEiZRDBQkRf/Ty8q9RqmB3mm73e1nvepjyc9sc4n2EZp1fXg8ra9fszX47bPOBy@GgQMRsBqycxSw5ek9/AaiCKqK6ALmTsFsA1QCKJYsNVSkMC20gAGEZQ4QgUbZwEnCK0QAwk9O811SthqTqr@JdvPzVk24MlvwE "Ruby – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~10~~ 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
·bg65αsd*
```
I/O are both integers
[Try it online](https://tio.run/##yy9OTMpM/f//0PakdDPTcxuLU7T@/zcxMzQ0szAzMLQwMTI3tjC3NDAGAA) or [verify all test cases](https://tio.run/##ZYu7CQJREEXzqWLZUFyY35tPtImNuChiZLAgLBhbgJ0YmVuARdjI82WCRvdwOPc0b6fjvl7Oy9h37@ut68dlU5@P6WDldZ93q7quA8GQzCLOKBZF3UtgwL9zUCOyMKRQdglPFCBmzUYZpq3TJIJEdMrkdlRsC1pQSqa1l6Om/YoCTK0NMY0vOjAQ4Ac).
**Explanation:**
```
· # Double the (implicit) input
# i.e. -1 ‚Üí -2
# i.e. 4503599627370496 ‚Üí 9007199254740992
b # Convert it to binary
# i.e. -2 → "ÿ0"
# i.e. 9007199254740992 ‚Üí 100000000000000000000000000000000000000000000000000000
g # Take its length
# i.e. "ÿ0" → 2
# i.e. 100000000000000000000000000000000000000000000000000000 ‚Üí 54
65α # Take the absolute different with 65
# i.e. 65 and 2 ‚Üí 63
# i.e. 65 and 54 ‚Üí 11
s # Swap to take the (implicit) input again
d # Check if it's non-negative (>= 0): 0 if negative; 1 if 0 or positive
# i.e. -1 ‚Üí 0
# i.e. 4503599627370496 ‚Üí 1
* # Multiply them (and output implicitly)
# i.e. 63 and 0 ‚Üí 0
# i.e. 11 and 1 ‚Üí 11
```
[Answer]
# [Haskell](https://www.haskell.org/), 56 bytes
Thanks [xnor](https://codegolf.stackexchange.com/users/20260/xnor) for spotting a mistake!
```
f n|n<0=0|1>0=sum.fst.span(>0)$mapM(pure[1,0])[1..64]!!n
```
Might allocate quite a lot of memory, [try it online!](https://tio.run/##JcqxDoMgFIXhvU9xTTpgouQCKjQpvkGfgDAwaGoqhIhuvju1dPnOcP63S59pXXOeIZzhiRpPNqJOh6dz2mmKLpAR67t38UXisU2GNWhrwygdOltVIXu3BNDwC4DEbQk7nesbgIGWXdNA@@BcCMlRDKrvpOwVqnIMRV78p3hp8xc "Haskell – Try It Online")
Maybe you want to test it with a smaller constant: [Try 8-bit!](https://tio.run/##y0gszk7Nyfn/P00hrybPxsDWoMbQzsC2uDRXL624RK@4IDFPw85AUyU3scBXo6C0KDXaUMcgVjPaUE/PIlZRMe9/bmJmnoKtAkheQaOgKDOvRC9Nk0tBIVpB1xhI6SjoGoIpAzAJYRuBSTOIiJE5kI79DwA "Haskell – Try It Online")
## Explanation
Instead of using `mapM(pure[0,1])[1..64]` to convert the input to binary, we'll use `mapM(pure[1,0])[1..64]` which essentially generates the inverted strings \$\lbrace0,1\rbrace^{64}\$ in lexicographic order. So we can just sum the \$1\$s-prefix by using `sum.fst.span(>0)`.
[Answer]
# Powershell, 51 bytes
```
param([long]$n)for(;$n-shl$i++-gt0){}($i,65)[!$n]-1
```
Test script:
```
$f = {
param([long]$n)for(;$n-shl$i++-gt0){}($i,65)[!$n]-1
}
@(
,(-1 ,0 )
,(-9223372036854775808 ,0 )
,(9223372036854775807 ,1 )
,(4611686018427387903 ,2 )
,(1224979098644774911 ,3 )
,(9007199254740992 ,10)
,(4503599627370496 ,11)
,(4503599627370495 ,12)
,(2147483648 ,32)
,(2147483647 ,33)
,(2 ,62)
,(1 ,63)
,(0 ,64)
) | % {
$n,$expected = $_
$result = &$f $n
"$($result-eq$expected): $result"
}
```
Output:
```
True: 0
True: 0
True: 1
True: 2
True: 3
True: 10
True: 11
True: 12
True: 32
True: 33
True: 62
True: 63
True: 64
```
[Answer]
# Java 8, 38 bytes
```
int f(long n){return n<0?0:f(n-~n)+1;}
```
Input as `long` (64-bit integer), output as `int` (32-bit integer).
Port of [*@l4m2*'s C (gcc) answer](https://codegolf.stackexchange.com/a/177291/52210).
[Try it online.](https://tio.run/##fZFNTsMwEIX3PcWoK0dRqvFP/EORuACsukQsQptULqlTJU4lVIUlB@CIXCSYEAksECtr5vl9Hr85FOciO@yexm1ddB3cFdZdFgCdL7zdwmidh4rUjduDSy5t6fvWgbvGG7yqiMteXJLS9TAGx6l/rINjNp4bu4NjgJGNb63b3z9AkXyCAXzZeZLR22T9ozSMca4YcqlzoVSuUUcXfusq0oWkVGqJVAumuFYGeaRTxoQJXaOlCH5haDyAQVTUGBbgAsMZw3PkuTEykBUKI/8T80hkNPA0l0L/3Y4/Eb8aD4hf1bD4Xs6U8SRO@7FzvpvnzpfHVdP71SlE72tHbLqE99c3WKYVsckMGsYP)
**Explanation:**
```
int f(long n){ // Recursive method with long parameter and integer return-type
return n<0? // If the input is negative:
0 // Return 0
: // Else:
f(n-~n) // Do a recursive call with n+n+1
+1 // And add 1
```
---
EDIT: Can be **26 bytes** by using the builtin `Long::numberOfLeadingZeros` as displayed in [*@lukeg*'s Java 8 answer](https://codegolf.stackexchange.com/a/177304/52210).
[Answer]
# APL+WIN, 34 bytes
```
+/×\0=(0>n),(63⍴2)⊤((2*63)××n)+n←⎕
```
Explanation:
```
n‚Üê‚éï Prompts for input of number as integer
((2*63)√ó√ón) If n is negative add 2 to power 63
(63⍴2)⊤ Convert to 63 bit binary
(0>n), Concatinate 1 to front of binary vector if n negative, 0 if positive
+/√ó\0= Identify zeros, isolate first contiguous group and sum if first element is zero
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 42 bytes
```
x=>x!=0?64-Convert.ToString(x,2).Length:64
```
[Try it online!](https://tio.run/##ZVA9T8MwFJzxr3C3RHIif8UfLSkDElO3IjEghsoyqaXiSLapghC/PTgNAQRveffu3t1wJlYmuvHu1ZvrU@875HzaQgNbOA7tdli1@Ebw6rb3ZxtSfd/vU3C@KwZEy3pnfZeOa8HHDQCT@fEJJhuTDTH73yuCQKUpZUxSzIRquJSNwgrBrwH/RQkXFXBBiFACE8WpZEpqzCAChFKuM9ZK8GzhmhD4KxBjSbSmOY3jvCcSTVkNZo3WIgdJzLWY@b90s7xTkv2KCa7mXPTDyPmEi0C@Ef7ILTz3wR7MsTgfwqWKCJ1fOinB1f4to5c61xn7k60fgkt257wtTHH5LsvN@Ak "C# (Visual C# Interactive Compiler) – Try It Online")
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 31 bytes
```
int c(long x)=>x<0?0:c(x-~x)+1;
```
Even shorter, based off of [@l4m2's C (gcc) answer.](https://codegolf.stackexchange.com/a/177291/52210)
Never knew that you could declare functions like that, thanks @Dana!
[Try it online!](https://tio.run/##ZZA/T8QwDMVn8ik8tqI92UmaP1cOBlY2BgbEcIoCRLpLpaZCRQi@ekmvFBB48fN79m@wS7VLYZpCHMAVhy4@wVjuLscLvMKtK8b6YyzPqZ0Ym7P7Bxh8GnyfYAdvNVWstpwLoTkKZRqpdWPQVPBV7H@oYU2ZVETKKCQjuRZGWxRQMeJc2qytUTKfSEsEv4CImqzlmSYx99msZlaDorFWZZBGadXi/7WbdZ1TvjdCSbNwqx9HLyOsAX0rfG8Ze@x6v3fPxcu@P70iQYjrT0p2dvua1XFz3cXUHfzmrg@DvwnRF644bZdlO30C "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~ 10 ~~ 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 thanks to a neat trick by Erik the Outgolfer (is-non-negative is now simply `AƑ`)
```
ḤBL65_×AƑ
```
A monadic Link accepting an integer (within range) which yields an integer.
**[Try it online!](https://tio.run/##y0rNyan8///hjiVOPmam8YenOx6b@P//fxNTA2NTS0szI3NjcwMTSzMA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##ddA7TgNBDAbg3qeIlHYi@TV@lEmdGyBERYNyAVoaaiouQJkDpF8p90guMhmxQgvLZhpL88m/bL88Hw6vrV1OX7u91afhc3v@aMP79e3Y2gNsqKwW3nqFsElmEWcUi6ruNTDKSP/Fy3cXgRqRhSGFskt4oozEQMya/SPDtHdpEo0kkIhOmdzTFHstP2MQglaUmmk9zlHTJqO51ckYmHpYiGmUv6vJL/O5CfDiRbpZX@GuCeBdU3i8AQ "Jelly – Try It Online").
---
The 10 was `ḤBL65_ɓ>-×`
Here is another 10 byte solution, which I like since it says it is "BOSS"...
```
BoṠS»-~%65
```
[Test-suite here](https://tio.run/##ddA9akJBEAfwfk4hhHT7YL52PtpcwVIsbUSwTpMiTa6RA@QCwS45SbzIuuQh6tO3zcD@mD8zs93sdq@tvez/vj@XP4fh7dlq@/04vn@1toKByuLBe1ogDMks4oxiUdW9BkYZ6V68/HcRqBFZGFIou4QnykgMxKzZPzJMe5cm0UgCieiUyT1NsddyHoMQtKLUTOtxjpp2MZpavRgDUw8LMY1yu5pcmU9NgB9epJv1FWZNAGdNYX0C "Jelly – Try It Online")
...`BoṠS63r0¤i`, `BoṠS63ŻṚ¤i`, or `BoṠS64ḶṚ¤i` would also work.
---
Another 10 byter (from Dennis) is `æ»64ḶṚ¤Äċ0` (again `æ»63r0¤Äċ0` and `æ»63ŻṚ¤Äċ0` will also work)
[Answer]
# [Perl 5](https://www.perl.org/), 37 bytes
```
sub{sprintf("%064b",@_)=~/^0*/;$+[0]}
```
[Try it online!](https://tio.run/##rZPrTsJAEIX/71NMNouhUmH20r1Yq7yHFyJSCJFLpSWRGH11XAoKkSYY4PxpMzv55szpNktno2g5XrB@sszn3Y88mw0nRb9Oa6hVl4btTpB8tZ7wshWzxj0@fi7j8QLaRZoXyfg5g/s8Gw2L1kPeaD2GN7cx6U9n9fI4@CDgNV7U2TBkaZC0WSfelIANkgvW9yfBurSeCpQ26yyF9M033FF6TSfTAmjQpNNX3zScZPPiGmoiyiGB0iBA@p6lL0XaW9V7AINp2dF7mNBwNXc1OmSDmHwurzjsC39e@IkiV04IKY1AqW2kjIks2h08niayTzee@rvGqe6V5lxbjdwqYaQ1DiWA@MWfyCdcCOU81FmtvHvluLcut3gs8zka7xANd074ZBT65ybyLX6j474CURHKyDntkzGonN5cmD38cfy/@GiNF/v4owIigvtUrNTK7tx7WYWv0qGVtnizi5f/xONB9xU/Lej/uj@0G@GVeHkWPHKClXh1Hjx@Aw "Perl 5 – Try It Online")
Or this 46 bytes if the "stringification" is not allowed: sub z
```
sub{my$i=0;$_[0]>>64-$_?last:$i++for 1..64;$i}
```
[Answer]
# Swift (on a 64-bit platform), 41 bytes
Declares a closure called `f` which accepts and returns an `Int`. This solution only works correctly 64-bit platforms, where `Int` is `typealias`ed to `Int64`. (On a 32-bit platform, `Int64` can be used explicitly for the closure’s parameter type, adding 2 bytes.)
```
let f:(Int)->Int={$0.leadingZeroBitCount}
```
In Swift, even the fundamental integer type is an ordinary object declared in the standard library. This means `Int` can have methods and properties, such as [`leadingZeroBitCount`](https://developer.apple.com/documentation/swift/int/2884587-leadingzerobitcount) (which is required on all types conforming to the standard library’s [`FixedWidthInteger`](https://developer.apple.com/documentation/swift/fixedwidthinteger) protocol).
[Answer]
# [Haskell](https://www.haskell.org/), 24 bytes
```
f n|n<0=0
f n=1+f(2*n+1)
```
[Try it online!](https://tio.run/##ZY2xDsIwDET3foXHllJkO2niVOQDGPgCxJCBioo2qqAj/x6idGQ5n9@ddM/weT3mOaUR4jee0WOVnad2rPkQW2rSEqYIHpawXqFe31PcTmNTAdygo3yO0DlmpSyjMtJra3tBKcE/t4VrQ2TEIIlmq8Q6VIUTs3b5c2J07mtH@4ApynunKA7DJW7Z3tMP "Haskell – Try It Online")
This is basically the same as Kevin Cruijssen's Java solution, but I found it independently.
The argument should have type `Int` for a 64-bit build, or `Int64` for anything.
## Explanation
If the argument is negative, the result is immediately 0. Otherwise, we shift left, *filling in with ones*, until we reach a negative number. That filling lets us avoid a special case for 0.
Just for reference, here's the obvious/efficient way:
# 34 bytes
```
import Data.Bits
countLeadingZeros
```
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 103 bytes
Uses the same *"builtin"* as ceilingcat's answer.
```
f::!Int->Int
f _=code {
instruction 243
instruction 72
instruction 15
instruction 189
instruction 192
}
```
[Try it online!](https://tio.run/##S85JTcz7n5ufUpqTqpCbmJn3P83KStEzr0TXDkhwpSnE2ybnp6QqVHNl5hWXFJUml2Tm5ykYmRij8M2NULiGpqhcC0tUvqURV@3/4JLEohIFW4U0BYP/AA "Clean – Try It Online")
# [Clean](https://github.com/Ourous/curated-clean-linux), 58 bytes
```
import StdEnv
$0=64
$i=until(\e=(2^63>>e)bitand i<>0)inc 0
```
[Try it online!](https://tio.run/##S85JTcz7n5ufUpqTqpCbmJn3PzO3IL@oRCG4JMU1r4xLxcDWzIRLJdO2NK8kM0cjJtVWwyjOzNjOLlUzKbMkMS9FIdPGzkAzMy9ZweB/cEkiUKetgoqCgQIc/P@XnJaTmF78X9fT579LZV5ibmZyMQA "Clean – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
în»╧3(∞┼⌠g
```
[Run and debug it](https://staxlang.xyz/#p=8c6eafcf3328ecc5f467&i=-1%0A-9223372036854775808%0A9223372036854775807%0A4611686018427387903%0A1224979098644774911%0A9007199254740992%0A4503599627370496%0A4503599627370495%0A2147483648%0A2147483647%0A2%0A1%0A0&a=1&m=2)
It's a port of Kevin's 05AB1E solution.
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 42 bytes
```
1while$_>0&&2**++$a-1<$_;$_=0|$_>=0&&64-$a
```
[Try it online!](https://tio.run/##rdPNaoQwEAfwe54i0LCHXSwz@Q7WvkGfQTxYarEqftAe@uxNQ7tdpQouunOJGPgx83ds8rZU3uP7S1HmLH2Ew4Efj6cTyyJ8YGnM0gQ@w/skXGgZsczHLEsgpnf5R9H1HX0dup4@1y19G8q@aMqc9m2Rd7SoaF3ltB0qHyGdF/w94M4ikeNcCMNBaKukMcqCnfCwr8hcN0G9jLG3e6kRtdWAVnIjrHEgKOUXfqdPkHPpAuqslqF76TC0LkYefvLZzDsAg87xkIyEcJ4jH/lzbfsKRCoQyjkdkjEgnT4vzIzf5v/n1S/P5/ymgAjHkIoVWtrJ3oslfqnWRhp5M@XFlTysLiYRhC/8uFRfO8HafAQXeXETHpDAIi9vw8NX3fRFXXU@elL3YRofNeU3 "Perl 5 – Try It Online")
Longer than a bitstring based solution, but a decent math based solution.
[Answer]
# APL(NARS), 15 chars, 30 bytes
```
{¯1+1⍳⍨⍵⊤⍨64⍴2}
```
test for few numbers for see how to use:
```
f←{¯1+1⍳⍨⍵⊤⍨64⍴2}
f ¯9223372036854775808
0
f 9223372036854775807
1
```
[Answer]
# Rust, 18 bytes
```
i64::leading_zeros
```
[Try it online!](https://play.rust-lang.org/?version=stable&mode=debug&edition=2015&gist=71da8c48aa4f1edd0fb85db20d7281d4)
[Answer]
# PHP, ~~50~~ 46 bytes
```
for(;0<$n=&$argn;$n>>=1)$i++;echo$n<0?0:64-$i;
```
Run as pipe with `-R` or [try it online](http://sandbox.onlinephpfunctions.com/code/7d03c08accfe0eaa3e19c42efec9c7bca8b40ae6),
`<?=$argn<0?0:0|64-log($argn+1,2);` has rounding issues; so I took the long way.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 41 bytes
The formula for positive numbers is just `63-Floor@Log2@#&`. Replacement rules are used for the special cases of zero and negative input.
The input need not be a 64-bit signed integer. This will effectively take the floor of the input to turn it into an integer. If you input a number outside of the normal bounds for a 64-bit integer, it will tell return a negative number indicating how many more bits would be needed to store this integer.
```
63-Floor@Log2[#/.{_?(#<0&):>2^63,0:>.5}]&
```
[Try it online!](https://tio.run/##ZY9NawJBEER/jCARerW/pnvaROMppxxyFyOLrImgWXDnJv72zZwSSE5VPOod6tKWz@7SltOhHUs3lEM7dMPq1hA0wSzijGI5qXvKmOE/c1AjsmxIWdkle6AAMWvUFtm07jSIIBCdIriKijVBE0qKsGo5athfkICpbrOY5t/qwECA98fjajRpXs59f9289h@8nSzmt/3zw@QJp7Plmt9NAJfrebrvpuPb9fRVtsfF5ufkbvwG "Wolfram Language (Mathematica) – Try It Online")
@LegionMammal978's solution is quite a bit shorter at 28 bytes. The input must be an integer. Per the documentation: "`BitLength[n]` is effectively an efficient version of `Floor[Log[2,n]]+1`. " It automatically handles the case of zero correctly reporting `0` rather than `-‚àû`.
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 28 bytes
```
Boole[#>=0](64-BitLength@#)&
```
[Try it online!](https://tio.run/##ZY@7asNAEEU/xhAcGOGZ2dl5YBSM6xTujQth1pbAD4i2C/l2ZasEkupeDvcU9z7UsdyHOp2HpZa5noe5zP1nR9AFc0rGmNSzmGVHh//MQJRIXZFc2JJbYAJilmgtXKXtJIggEI0iuImCLUEyphyhzTKU0L8gA1PbelLx32rAQIBf20u/7J/PWzmu3no8rVW6/VTfy@Nax93q9WU5fEyPerxsdj@/Tss3 "Wolfram Language (Mathematica) – Try It Online")
[Answer]
bitNumber - math.ceil (math.log(number) / math.log(2))
e.g
64 bit
NUMBER : 9223372036854775807
math.ceil (math.log(9223372036854775807) / math.log(2))
ANS: 63
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 12 bytes
```
+/&\~(64#2)\
```
[Try it online!](https://ngn.codeberg.page/k#eJxljstqAlEMhvfzFEJFlCLN7eQy51E0oJuB0kJBXCjiPHvPmZ24Cv+X5Eum8fNrc5y3Kh+0Ow7DdXysD/f5Mk6rWz39/dTtaTp//9ZbvdfLLp/D9bDHhF6CiNkIWL2IWXHwpfHOLbFxUUR1BXQhY7cATmociSRaCldp8xKIyd0DYBhBTSLQamK3SwEuEdoUBhKaiO+0JHYzYVt1VvHkl2zJ/QKlLg+k9gSp8g/x20FX)
`(64#2)\` encode the argument as 64 bits
`~` bitwise not
`&\` cumulative boolean and
`+/` sum
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes
```
I⁻⁶⁴L↨﹪NX²¦⁶⁴¦²
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzczr7RYw8xER8EnNS@9JEPDKbE4VcM3P6U0J1/DM6@gtMSvNDcptUhDU0chIL8cyDDSUTAz0QRyjTTBwPr/f4P/umU5AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
L Length of
N Input as a number
Ôπ™ Modulo
² Literal 2
X To the power
⁶⁴ Literal 64
‚Ü® Converted to base
² Literal 2
⁻ Subtracted from
⁶⁴ Literal 64
I Cast to string
Implicitly print
```
The `¦`s serve to separate adjacent integer literals. Conveniently, Charcoal's arbitrary numeric base conversion converts `0` into an empty list, however for negative numbers it simply inverts the sign of each digit, so the number is converted to the equivalent unsigned 64-bit integer first.
] |
[Question]
[
My two kids like to play with the following toy:
[![Turtle](https://i.stack.imgur.com/BYhak.jpg)](https://i.stack.imgur.com/BYhak.jpg)
The colored areas with the shapes inside can be touched and the turtle then lights the area and plays a sound or says the name of the color or the shape inside. The middle button changes the mode. There is one mode in which the areas play different musical notes when touched, with a twist: if the kid touches three consecutive areas clockwise, a special melody 1 is played. If the three consecutive areas touched are placed counterclockwise, a special melody 2 is played.
### The challenge
Let's simulate the internal logic of the toy. Given a string with 3 presses of the kid, return two distinct, coherent values if the three presses are for consecutive areas (clockwise or counterclockwise) and a third distinct value if they are not.
### Details
* The input areas will be named with a character each, which can be their color: `ROYGB` for red, orange, yellow, green and blue; or their shape: `HSRTC` for heart, square, star (`R`), triangle and circle. Case does not matter, you can choose to work with input and output just in uppercase or in lowercase.
* The program will receive a string (or char array or anything equivalent) with three presses. Examples (using the colors): `RBO`, `GYO`, `BBR`, `YRG`, `YGB`, `ORB`...
* The program will output three distinct, coherent values to represent the three possible outcomes: a first value if the combination does not trigger a special melody, a second value if the combination triggers the clockwise special melody, and a third value if the combination triggers the counterclockwise special melody. Example: `0` for no special combination, `1` for the melody triggered by a clockwise combination and `-1` for the melody triggered by a counterclockwise combination.
* You do not need to worry about handling wrong input.
### Test cases
```
Input Output // Input based on colors
--------------
RBO 0 // No special combination
GYO -1 // Counterclockwise melody triggered
BBR 0 // No special combination
YRG 0 // No special combination
YGB 1 // Clockwise melody triggered
ORB -1 // Counterclockwise melody triggered
OOO 0 // No special combination
BRO 1 // Clockwise melody triggered
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so may the shortest code for each language win!
[Answer]
# Java 8, ~~48~~ ~~39~~ 33 bytes
```
s->"ROYGBRO BGYORBG".indexOf(s)|7
```
-6 bytes thanks to *@RickHitchcock*, so make sure [to upvote him as well](https://codegolf.stackexchange.com/a/174590/52210)!
Takes uppercase color as input-String. Outputs `-1` for none, `7` for clockwise, and `15` for counterclockwise.
[Try it online.](https://tio.run/##jVE9j8IwDN37K6xO7UAZke4EQxgy0Uhhqk4MIQ0oUBJEUg4E/e3FLTBCukSy/Zz34Z04i9Gu3LeyEs7BQmhziwC08eq0EVJB3pV9A2Sy9CdttuDSX2w2ET7OC68l5GBgCq0bzWLOCko4A0ILxgmNM21KdWGbxKX3SdstHut1hTuv1bPVJRyQ9/X73wpE@iQdjyG3Rv30xfLqvDpktvbZEXG@MonJZBJzwuK0F/QZQwgPYgpOgxjGvnLh5K17Xlm5/9cuIB6jCovnYYMY@lBhtu5uK4fpwxuGQ@EDPNAi7IG8D9BETfsA)
**Explanation:**
```
s-> // Method with String parameter and integer return-type
"ROYGBRO BGYORBG".indexOf(s)
// Get the index of the input in the String "ROYGBRO BGYORBG",
// which will result in -1 if the input is not a substring of this String
|7 // Then take a bitwise-OR 7 of this index, and return it as result
```
---
**Old 39 bytes answer:**
```
s->(char)"ROYGBRO BGYORBG".indexOf(s)/7
```
Takes uppercase color as input-String. Outputs `9362` for none, `0` for clockwise, and `1` for counterclockwise.
[Try it online.](https://tio.run/##jZGxbsMgEIZ3P8XJEwyxx0qp2oEMTDUSmawqA8UkwXEgMjhpFfnZXey6Y4IXpLv7j@@/u1pcxaquToNshHPwIbS5JwDaeNXuhVRQjOGUAIm2vtXmAA6/hmSfhMd54bWEAgy8weBW70geRYtTzkpKOANCS8YJTTNtKvXN9sjh/GUY2y/dVxM65w@uVldwDvSZ8bkDgf/QeQ6FNWo9Bdsf59U5s53PLkHnG4NMJlHKCUvxZOuxhhAe1ZScRjWMPWWFyr/vTWPl6aZdxHxYVdw8Xwy13Xg9uYwd7hMfmC/wR8tZ0yf98As)
**Explanation:**
```
s-> // Method with String parameter and integer return-type
(char)"ROYGBRO BGYORBG".indexOf(s)
// Get the index of the input in the String "ROYGBRO BGYORBG",
// which will result in -1 if the input is not a substring of this String
// And cast it to a char (-1 becomes character with unicode value 65535)
/7 // Integer-divide it by 7 (the char is implicitly converted to int doing so)
```
[Answer]
# JavaScript (ES6), 41 bytes
Takes color initials as input. Returns `2` for none, `true` for clockwise or `false` for counterclockwise.
```
s=>~(x='ROYGBRO_ORBGYOR'.search(s))?x<5:2
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/Y1q5Oo8JWPcg/0t0pyD/eP8jJPdI/SF2vODWxKDlDo1hT077CxtTK6H9yfl5xfk6qXk5@ukaahnqQk7@6pqaCvr6CEReaFNAAqFRaYk5xKrq0k1MQLp2RQe44pdydoFIlRaUYZgKdjc9Kf3@cjgV6Gsnc/wA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 36 bytes
```
lambda i:'ROYGBRO ORBGYOR'.find(i)/7
```
`-1` - None
`0` - Clockwise
`1` - Counterclockwise
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHTSj3IP9LdKchfwT/IyT3SP0hdLy0zL0UjU1Pf/H9BUWZeiUKahnqQk7@6JhecC1SHzHVyCkLmRga5o3DdnZC5QGtQuP6oRgUBuf8B "Python 2 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~15~~ 11 bytes
Saved 4 bytes thanks to *Kevin Cruijssen* and *Magic Octopus Urn*.
Uses shapes.
Output `[0, 0]` for *none*, `[1, 0]` for *clockwise* and `[0, 1]` for *counter-clockwise*
```
‚.•ÌöJη•så
```
[Try it online!](https://tio.run/##yy9OTMpM/f//cNOjhll6jxoWHe45vM3r3HYgq/jw0v//i0qSAQ "05AB1E – Try It Online")
or as a [Test suite](https://tio.run/##yy9OTMpM/V9TVln5/3DTo4ZZeo8aFh3uObzN69x2IKv48NL/lUqH9yvo2iko2ev8z0gu5iopKuZKTs7gKsoo4SoqSeYqzgDiYqBYRjEA)
**Explanation**
```
‚ # pair the input with its reverse
.•ÌöJη• # push the string "hsrtchs"
så # check if the input or its reverse is in this string
```
[Answer]
## Excel, 29 bytes
```
=FIND(A1,"ROYGBRO_RBGYORB")<6
```
Uppercase colours as input.
Returns `#VALUE!` for no pattern, `TRUE` for clockwise, `FALSE` for anti-clockwise.
Can wrap in `IFERROR( ,0)` for `+11 bytes` to handle exception , and return '0' for no-pattern cases instead.
[Answer]
# JavaScript (ES6), 32 bytes
```
s=>'ROYGBRO_ORBGYOR'.search(s)|7
```
Returns -1 if no combination, 15 if counterclockwise, 7 if clockwise.
```
let f =
s=>'ROYGBRO_ORBGYOR'.search(s)|7
console.log(f('RBO')) // -1
console.log(f('GYO')) // 15
console.log(f('BBR')) // -1
console.log(f('YRG')) // -1
console.log(f('YGB')) // 7
console.log(f('ORB')) // 15
console.log(f('OOO')) // -1
console.log(f('BRO')) // 7
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~42~~ 36 bytes
```
{"ROYGBRO","ORBGYOR"}~StringCount~#&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78H1CUmVcS/b9aKcg/0t0pyF9JR8k/yMk90j9IqbYuuAQom@6cX5pXUqes9l/fQQGozslfSUFHQQmoBEwDdYFpoC4I7Q8RB5mlUBv7HwA "Wolfram Language (Mathematica) – Try It Online")
Counts the number of times the input appears in both `"ROYGBRO"` and `"ORBGYOR"`. Returns `{1,0}` for clockwise, `{0,1}` for counterclockwise, and `{0,0}` for no special combination.
At the cost of only one more byte, we can get outputs of `0` for nothing, `1` for clockwise, and `2` for counterclockwise with `"ROYGBRO.ORBGYORBGYOR"~StringCount~#&`.
[Answer]
# x86 machine code, ~~39~~ 36 bytes
```
00000000: f30f 6f29 b815 0000 0066 0f3a 6328 0c89 ..o).....f.:c(..
00000010: c883 c807 c352 4f59 4742 524f 2042 4759 .....ROYGBRO BGY
00000020: 4f52 4247 ORBG
```
Assembly:
```
section .text
global func
func: ;the function uses fastcall conventions
;no stack setup needed because we don't need to use stack
movdqu xmm5,[ecx] ;Move DQword (16 bytes) from 1st arg to func(ecx) to SSE reg
mov eax, msg ;Load address of constant str 'msg' into eax
PcmpIstrI xmm5, [eax], 1100b ;Packed Compare String Return Index, get idx of [eax] in xmm5
mov eax, ecx ;Move returned result into reg eax
or eax, 7 ;Bitwise OR eax with 7 to get consistent values
ret ;return to caller, eax is the return register
msg db 'ROYGBRO BGYORBG'
```
[Try it online!](https://tio.run/##bVNRT9swEH6Of8WpEmtTGtaCNiQKPGSwDmkoLDwhqCrHdtKwxM5spw1C/PbunKyi1cjDKT5/33ff@eyEmuWGUQvn59fRd7iEz7asPtMjasqNEczmSsKRFY0lXlaohBaQ1pIRF848903tUrS5FlobYSClxjJaFMCUXAnpNgzpwFKBsZT9BiNsXYEUggsOiWAUmbAWwJXs2zYPVjm5Dk@8Uq34nxqasvwyehSsmaParVoJuPq1VprDYPIVkhcrjA@pViVMjAWqM6fi3A2Q4rvF/f01aJG1giBoM4LSZM7aT0U5UM61MAZU6sxjaWnRgIY@gvqQSxRADvHuWFnd4MZNZwgeMTsfwWQyHife9A4dYwPfVFlRLeDe6lxmEGPLWsKN5AKrZsJCzhtXqSWjeKu1Ywwte9sudUtGUbRXF7azgn10dpTuGKcOH@Z2nePBRbFLwjq3Szh1rbuSrqvcWJwKrGhRCxwMSrez6Uo4oBue0KOWnhtwE/63iRUdW6NLkwFPoB9HD7MwjiCcPURxOOtv8BoR8t@NMrZOjhjBiyRQBt3DYkEtHkxSW7FYDAbbS@P73bzYkuqhPwXisCXN5cB/JV6bxSFb8zi/eO3FYdQb9bAyxjCMMT7EMxdnIUb042LU7sYYx29T4qVKD5xmfjGedkr5fJofHjp5r8JJ2XTQOzBncMCfZG@0hYxaV9uV76PSG3kjbbcSXwsEqSjSk@OdBwSB6lZMcXGkSMbYfgoJu6ezC4ZAqqDKBQTlyTFRyTNT1QsEESS5pBr/nrtnucd5/0cUcSxelxUEVxDcujMXxR788tMxEWyJtQT0nuRwOAzxAeEVqaU9w1WvRazRNIPzffEPuD9E46q9E5uGf0Aie@1v/gI "Try It Online")
Output is `23` for none, `7` for clockwise, and `15` for counter-clockwise. Based on @RickHitchcock 's answer.
Edit 1: Saved 3 bytes by using an SSE string comparison instruction instead of using libc.
Edit 2: Use proper calling convention for SSE (use XMM5 instead of XMM2) and improve formatting on Bash.
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 30 bytes
```
$_=ROYGBRO=~/$_/-ORBGYOR=~/$_/
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3jbIP9LdKcjftk5fJV5f1z/IyT3SPwjC@/8fKPEvv6AkMz@v@L@ur6megaHBf90CAA "Perl 5 – Try It Online")
[Answer]
# APL(Dyalog), ~~22~~ 18 bytes
```
+/(⍷-⍷∘⌽)∘'ROYGBRO'
```
*-4 bytes thanks to @ngn*
Takes a string of color initials. Outputs 0 for no special pattern, -1 for counterclockwise, 1 for clockwise.
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///X1tf41Hvdl0gftQx41HPXk0gpR7kH@nuFOSv/j/tUduER719j/qmevo/6mo@tN74UdtEIC84yBlIhnh4Bv9PUw9y8lfnSlN3jwRTTk5BICoyyB1MuTuBKP8gCOUPUQI0GgA)
[Answer]
# [Python 2](https://docs.python.org/2/), ~~45~~ 43 bytes
```
lambda i,a='ROYGBRO':(i in a)-(i[::-1]in a)
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSFTJ9FWPcg/0t0pyF/dSiNTITNPIVFTVyMz2spK1zAWzPtfUJSZV6KQpqEe5OSvrskF57pHonCdnIKQuZFB7ihcdydkrn8QKtcf1SigazT/AwA "Python 2 – Try It Online")
With ideas from and serious credit to @DeadPossum
-2 with thanks to @JoKing. Now outputs -1 = counterclockwise, 0 = none, 1 = clockwise.
My original effort is below for historical purposes.
# [Python 2](https://docs.python.org/2/), ~~52~~ 51 bytes
```
lambda i,a='ROYGBRO':((0,1)[i[::-1]in a],2)[i in a]
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSFTJ9FWPcg/0t0pyF/dSkPDQMdQMzoz2spK1zA2M08hMVbHCMhXADP/FxRl5pUopGmoBzn5q2tywbnukShcJ6cgZG5kkDsK190JmesfhMr1RzUK6CrN/wA "Python 2 – Try It Online")
0 = none, 1 = counterclockwise, 2 = clockwise
[Answer]
# [Python 2](https://docs.python.org/2/), ~~35~~ 36 bytes
+1 - for some reason I thought all buttons would be distinct >\_<
*Developed independently from [what I have just seen](https://codegolf.stackexchange.com/a/174582/53748) (and now up-voted) by Dead Possum*
```
lambda s:'ORBGYO.BROYGBR'.find(s)/7
```
**[Try it online!](https://tio.run/##lZBRS8NADMff@ynylha6CvogDCqsRcpQLFRBhvOha6/stL077lLET19znQ6GOPAeApf88/snMZ@01@py6tLt1NfDrq3BLbGssmJTVklWlZsiqzDppGpDF11cT/l9md89rx9vIYUX5DrGyCKOrOTo5TFyI74Gq4en9amewVxlutcUvpd9fG9ZsT4wVioCzHvdvH9IJ5YYdNoCCUcgFRxZywD4HdS@GAMubjCGLvS/6IeDR@JKkVw0f2BPxvw3uqS9sGC0c3LXC@aZkRwbWD2AJGFJ696BHIy2xFzdjg3N9sZ7fydCnC/NPlYYUVN6FR0GmWdM2S9501KFJpqzsvt9Ezi/kX@N5jOoUZxfcfoC "Python 2 – Try It Online")**
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~14~~ 13 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ù♀e▌d─█£F'♦O▬
```
[Run and debug it](https://staxlang.xyz/#p=970c65dd64c4db9c4627044f16&i=RBO%0AGYO%0ABBR%0AYRG%0AYGB%0AORB%0AOOO%0ABRO&a=1&m=2)
The output is
* 1 for no special combination
* 2 for counter-clockwise melody
* 3 for clockwise melody
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 19 bytes
```
Y"ROYGBRO"OaNyaNRVy
```
Outputs `10` for clockwise, `01` for counterclockwise, `00` for neither. [Try it online!](https://tio.run/##K8gs@P8/UinIP9LdKchfyT/RrzLRLyis8v///0AxAA "Pip – Try It Online")
### Explanation
```
a is 1st cmdline argument
Y"ROYGBRO" Yank that string into y variable
aNy Count of occurrences of a in y
O Output without newline
RVy y reversed
aN Count of occurrences of a in that string
Print (implicit)
```
[Answer]
# [J](http://jsoftware.com/), 21 bytes
```
-&(OR@E.&'ROYGBRO')|.
```
[Try it online!](https://tio.run/##y/qvpKegnqZga6WuoKNQa6VgoADE/3XVNPyDHFz11NSD/CPdnYL81TVr9P5rcqUmZ@QrANXYKqQpqAc5@atDROINISLukTARmBonpyA0kcggd5gIVBfQAjRz/IOc0HT5@/uj6QI56j8A "J – Try It Online")
### How it works
```
-&(OR@E.&'ROYGBRO')|. Monadic 2-verb hook. Input: a string.
|. Map over [input string, input string reversed]:
E.&'ROYGBRO' Find exact matches of input in 'ROYGBRO'
(OR@ ) Reduce with OR; is it a substring of 'ROYGBRO'?
-& Reduce with -; result is 1 for CW, -1 for CCW, 0 otherwise
```
Achieves maximum amount of function reuse.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
,Ṛẇ€“¤ƈẎṬ%Ȥ»
```
[Try it online!](https://tio.run/##ASkA1v9qZWxsef//LOG5muG6h@KCrOKAnMKkxojhuo7huawlyKTCu////2d5bw "Jelly – Try It Online")
-4 thanks to [Jonathan Allan](https://codegolf.stackexchange.com/questions/174564/playing-with-the-musical-turtle/174588?noredirect=1#comment420882_174588).
Clockwise: `[1, 0]`
Counter-clockwise: `[0, 1]`
Other: `[0, 0]`
[Answer]
# [R](https://www.r-project.org/), 38 bytes
```
grep(scan(,''),c('ROYGBRO','ORBGYOR'))
```
[Try it online!](https://tio.run/##pZJBb4MgFMfvfoqX9IAkatYem20HdvA2Em4eKT4dqaJBjGuWfXYHtWt6WbpNTgT@P/i9B3bewGRl36MF1wG2YyMdwuBKbfrRwaTdG0ioRqOc7gzEg2wRDiefUd1oHI2qp@/N@J1@DEqax/S6kmUZtehGGzbn2mIfh0ScEEITFRPBi5wJThLCBcsLLgil82cUbUCcqQH2fg4pvHYw9Ki0bPy97UEbeda5GXvQxmGNNn6gsEAvwRCtajp1nPSA0GLTlSdwVtc@iKWHdpfoz5nr@dsoqrwy44QCbH6h5Ef6fKMVcF/kgt@XW/BdoBgTay4tRL4Kz9nF@W6XFnwbKP@i/6iU81XtDZ/pb6rzFw "R – Try It Online")
Returns :
* No special combination : `integer(0)`
* Counterclockwise melody triggered : `2`
* Clockwise melody triggered : `1`
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 18 bytes
```
≔ROYGBROηI⁻№ηθ№⮌ηθ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU9DKcg/0t0pyF9JRyFD05oroCgzr0TDObG4RMM3M6@0WMM5vxQokKGjUKipowDhBKWWpRYVp2pkaIJEgcD6/3//IKf/umU5AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
ROYGBRO Literal string
≔ η Assign to variable
η η Value of variable
⮌ Reversed
θ θ Input string
№ № Count matches
⁻ Subtract
I Cast to string
Implicitly print
```
[Answer]
# [Common Lisp](http://www.clisp.org/), 68 bytes
```
(defun x(s)(cond((search s "ROYGBRO")1)((search s "BGYORBG")-1)(0)))
```
[Try it online!](https://tio.run/##Zc0xCsMwDIXhvacQnvSGQnMFLR4N2jwGJyWB4Ia4hdzeEZkSd/349ZSWuay18jC@f5l2LuD0yQNzGfstTVTIaYheNDh0uLL4GFS8w9P8BaDyus35S7zbjViPx0WsbkREG4lqcyC6mZemsq@thL9tPaUe "Common Lisp – Try It Online")
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 63 bytes
```
import StdEnv,Text
$s=map((>)0o indexOf s)["ROYGBRO","BGYORBG"]
```
[Try it online!](https://tio.run/##S85JTcz7n5ufUpqTqpCbmJn3PzO3IL@oRCG4JMU1r0wnJLWihEul2DY3sUBDw07TIF8hMy8ltcI/TaFYM1opyD/S3SnIX0lHyck90j/IyV0p9n9wSSJQu62CioISUE7p/7/ktJzE9OL/up4@/10q8xJzM5MhnICcxJK0/KJcAA "Clean – Try It Online")
`[True, True]` for no special noises, `[True, False]` for counterclockwise, `[False, True]` for clockwise.
[Answer]
# Japt, ~~17~~ 14 bytes
Takes the colours as input, in lowercase. Returns `0` for clockwise, `1` for counterclockwise or `-1` if there's no combo.
```
`ygß`ê qÔbøU
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=YJ55Z9+WYOogcdRi+FU=&input=InJibyI=)
---
## Expanation
```
`...` :Compressed string "roygbrow"
ê :Palindromise
qÔ :Split on "w"
b :Index of the first element
ø : That contains
U : The input string
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~53~~ 36 bytes
```
->n{"\a\fDch+".index(""<<n%111)&./3}
```
[Try it online!](https://tio.run/##DclBDoIwEAXQq5gmEolDzZ8ZdujKW5QuUGx0QUOakEiAsxe276XpNedwz9UjLqbt2vB8f6/G/mL/@V@MaZp4BlAW9iZbdmClWphUQSJCYCGWw8CEWkmPE4a3Qzcua1rHk0sUXPJ@yzs "Ruby – Try It Online")
Input: a 3-digit integer, where the digits represent colors:
* 1 - red
* 2 - orange
* 3 - yellow
* 4 - green
* 5 - blue
Output:0 for clockwise, 1 for counterclockwise, `nil` otherwise.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 55 bytes
Returns 0 for none, -1 for CCW and 1 for CW.
```
f(char*s){s=!strstr("ORBGYOR",s)-!strstr("ROYGBRO",s);}
```
[Try it online!](https://tio.run/##PY6xCsMwDET3foVqCNiJM3ROs3jJKNAW2g7BJamHpsUOWUK@XZVLKQh09ySO8/XkPfOo/WOIZTJbao9piTJaIbmuR1I2mfoPCfvOEWbY7BzmBZ5DmHUWQ5y8hRwEZSlmNbAdAMZX/J5De2ognPOX7Koy8I7CR62KBC0U9@usbA5ZL@FmYdQ/aUxz2JnJIUsddo64p46lBktDRhRG@AE "C (gcc) – Try It Online")
] |
[Question]
[
Use any programming language to display "AWSALILAND" in such a way, so that each letter is in a new line and repeated as many times as its position in the English alphabet. For example letter, (A) should be displayed just once because it is the first letter of the alphabet. Letter D should be displayed 4 times because it is the 4th letter of the alphabet.
So, the output should be this:
```
A
WWWWWWWWWWWWWWWWWWWWWWW
SSSSSSSSSSSSSSSSSSS
A
LLLLLLLLLLLL
IIIIIIIII
LLLLLLLLLLLL
A
NNNNNNNNNNNNNN
DDDD
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~61~~ 59 bytes
```
foreach(var s in"AWSALILAND")WriteLine(new string(s,s-64));
```
[Try it online!](https://tio.run/##Sy7WTS7O/P8/Lb8oNTE5Q6MssUihWCEzT8kxPNjRx9PH0c9FSTO8KLMk1SczL1UjL7VcobikKDMvXaNYp1jXzERT0/r/fwA "C# (Visual C# Interactive Compiler) – Try It Online")
@Kevin Cruijssen Thanks, 2 bytes saved by removing { }
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~18~~ 17 bytes
*-1 byte from @Shaggy*
```
`awÑ¢Ó€`u ¬®pIaZc
```
---
```
`awÑ¢Ó€`u ¬®pIaZc Full program
`awѢӀ` Compressed "awasiland"
u uppercase
¨ split and map each letter
p repeat the letter this many times:
a absolute difference of
Zc get charcode
I and 64
```
[Try it online!](https://tio.run/##ASEA3v9qYXB0//9gYXfDkcKiw5PCgGB1IMKswq5wSWFaY///LVI "Japt – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 20 bytes
```
jm*d-Cd64"AWSALILAND
```
Try it online [here](https://pyth.herokuapp.com/?code=jm%2Ad-Cd64%22AWSALILAND&debug=0).
```
jm*d-Cd64"AWSALILAND
"AWSALILAND String literal "AWSALILAND"
m Map each character of the above, as d, using:
Cd Get character code of d
- 64 Subtract 64
*d Repeat d that many times
j Join on newlines, implicit print
```
**19 byte** alternative, which outputs lower case: `jm*dhxGd"awsaliland` - [link](https://pyth.herokuapp.com/?code=jm%2AdhxGd%22awsaliland&debug=0)
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 112 bytes
```
+++++++[->++>>++>+>++>>+++>+++[<<<]<<]++++>>+>-->++>-->+>-->++>+[[->+>+<<]----[>+<----]>+>[-<.>]++++++++++.<,<<]
```
[Try it online!](https://tio.run/##PYvRCYBADEMHir0JShcp96GCIIIfgvPXRA9D24Twulzzfm73elThU1oAocUIcqS7d44QlmEvpjsiUp8BMkYlk7yzS/MWHb@aT6SqHg "brainfuck – Try It Online")
The actual word generation can probably be optimised further.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 34 bytes
```
"AWSALILAND"|% t*y|%{"$_"*($_-64)}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X8kxPNjRx9PH0c9FqUZVoUSrska1WkklXklLQyVe18xEs/b/fwA "PowerShell – Try It Online")
Takes the string `t`oCharArra`y`, then multiplies each letter out the corresponding number of times. Implicit `Write-Output` gives us newlines for free.
Ho-hum.
[Answer]
# Python 3,41 bytes
```
for i in'AWSALILAND':print(i*(ord(i)-64))
```
# Python 2,40 bytes
```
for i in'AWSALILAND':print i*(ord(i)-64)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 17 bytes
```
.•DθîRI§•ʒAyk>×u,
```
[Try it online!](https://tio.run/##yy9OTMpM/f9f71HDIpdzOw6vC/I8tBzIPjXJsTLb7vD0Up3//wE "05AB1E – Try It Online")
**Explanation**
```
.•DθîRI§• # push compressed string "awsaliland"
ʒ # filter
Ayk # get the index of the current letter in the alphabet
> # increment
× # repeat it that many times
u # upper-case
, # print
```
We only use filter here to save a byte over other loops due to ac implicit copy of the element on the stack. Filter works here since we print in the loop and don't care about the result of the filter.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~16~~ 15 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
êôM▄╬æ♠ª+ç█○==.
```
[Run and debug it](https://staxlang.xyz/#p=88934ddcce9106a62b87db093d3d2e&i=)
**Explanation**
```
`'YHu~{YX#`m64-_]* #Full program, unpacked,
`'YHu~{YX#` #Compressed "AWSALILAND"
m #Use the rest of the program as the block. Print each mapped element with a new-line.
64 #Put 64 on stack
- #Subtract current element by 64
_ #Get current index
] #Make a 1 element array
* #Duplicate that many times
```
Saved one byte by figuring out that the "\*" command works with [arr int] and [int arr].
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 17 bytes
```
EAWSALILAND×ι⊕⌕αι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3sUBDyTE82NHH08fRz0VJRyEkMze1WCNTR8EzL7koNTc1ryQ1RcMtMy9FI1FHIVMTBKz///@vW5YDAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
AWSALILAND Literal string
E Map over characters
ι Current character
α Uppercase alphabet
⌕ Find
⊕ Increment
ι Current character
× Repeat
Implicitly print each entry on its own line
```
[Answer]
# [R](https://www.r-project.org/), ~~64~~ 61 bytes
R's clunky string handling characteristics on full display...
-3 thanks to @Giuseppe, who noticed it's actually shorter to *convert a string from utf8 to int and back again* than using R's native string splitting function...
```
write(strrep(intToUtf8(s<-utf8ToInt("AWSALILAND"),T),s-64),1)
```
[Try it online!](https://tio.run/##K/r/v7wosyRVo7ikqCi1QCMzryQkP7QkzUKj2Ea3FEiH5HvmlWgoOYYHO/p4@jj6uShp6oRo6hTrmplo6hhq/v8PAA "R – Try It Online")
[Answer]
# [Scala](https://www.scala-lang.org/) (51 bytes):
```
"AWSALILAND"map(c=>s"$c"*(c-64)mkString)map println
```
# [Scala](https://www.scala-lang.org/) (41 bytes):
```
for(c<-"AWSALILAND")println(s"$c"*(c-64))
```
[Try it online](https://tio.run/##K05OzEn8n5@UlZpcouCbmJmnkFpRkpqXUqzgWFCgUP0/Lb9II9lGV8kxPNjRx9PH0c9FSbOgKDOvJCdPo1hJJVlJSyNZ18xEU/N/7X8A)
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 22 bytes
A more elegant, tacit solution thanks to Adám!
```
(↑⎕A∘⍳⍴¨⊢)'AWSALILAND'
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v//Ud/UR20TNB61TQSyHB91zHjUu/lR75ZDKx51LdJUdwwPdvTx9HH0c1H//x8A "APL (Dyalog Classic) – Try It Online")
Initial solution:
```
↑a⍴¨⍨⎕A⍳a←'AWSALILAND'
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v//Ud/UR20THrVNTHzUu@XQike9K4Aijo96NycChdUdw4MdfTx9HP1c1P//BwA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 35 bytes
```
say$_ x(31&ord)for AWSALILAND=~/./g
```
[Try it online!](https://tio.run/##K0gtyjH9/784sVIlXqFCw9hQLb8oRTMtv0jBMTzY0cfTx9HPxbZOX08//f//f/kFJZn5ecX/dX1N9QwMDQA "Perl 5 – Try It Online")
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), 23 22 bytes
```
(32!r)#'r:"AWSALILAND"
```
[Try it online!](https://tio.run/##y9bNS8/7/1/D2EixSFNZvchKyTE82NHH08fRz0Xp/38A)
```
r:"AWSALILAND" // set variable r to the string
(32!r) // mod 32 each string in r, the operation will use ASCII number
#' // for each value in the array, take that amount of the corresponding character in the string
```
[Answer]
# Java 11, ~~89~~ ~~83~~ ~~82~~ 81 bytes
```
v->"AWSALILAND".chars().forEach(c->System.out.println(((char)c+"").repeat(c-64)))
```
-1 byte thanks to *@OlivierGrégoire*.
[Try it online.](https://tio.run/##LY7BCoJAEIbvPsXgaZdwT9FFEoQ6BOZFqEN0mKYttXWV3VWI8NltLS8zzM/PfF@NA0b1/TWRQmvhiJX@BACVdtI8kCTk8wkwtNUdiJ3mNfDYZ2Pgh3XoKoIcNGynIUrC9Fyk2SFL810oqERjGReP1uyRSkZRUrytk41oeyc64yFKM8bmHqdVGHJhZCfR@eZmzTmf4pnR9TflGQvqJ9J4TVY4/@F5uQLyv6MWxHSv1KI3Tl8)
**Explanation:**
```
v-> // Method with empty unused parameter and no return-type
"AWSALILAND".chars().forEach(c->
// Loop over the characters as integer unicode values
System.out.println( // Print with trailing newline:
((char)c+"") // The current character converted to char and then String
.repeat(c-64))) // repeated the unicode value minus 64 amount of times
```
[Answer]
# [J](http://jsoftware.com/), 31 bytes
```
echo(#&>~_64+a.i.])'AWSALILAND'
```
[Try it online!](https://tio.run/##y/r/PzU5I19DWc2uLt7MRDtRL1MvVlPdMTzY0cfTx9HPRf3/fwA "J – Try It Online")
## Explanation:
```
echo(#&>~_64+a.i.])'AWSALILAND' - print
# ~ - copy (arguments reversed)
&> - each character (can be "0)
i. - the index of
] - the characters in
a. - the alphabet
_64+ - minus 64 (times)
```
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 88 bytes
```
S ='AWSALILAND'
L S LEN(1) . X REM . S :F(END)
&UCASE X @Y
OUTPUT =DUPL(X,Y) :(L)
END
```
[Try it online!](https://tio.run/##DYqxCoAgFABn/Yo3pUIEQZMgJGkQvExSydbmqKH/x5wO7u573uu9h1JIAMX0ETQuqJ1hFKtB63gvoIMMu10rA8iZW2cEJU2adLC1jCclW4o@RVAmeeS5PQWRHAWtZyk/ "SNOBOL4 (CSNOBOL4) – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 20 bytes
```
'AWSALILAND'"@@64-Y"
```
[Try it online!](https://tio.run/##y00syfn/X90xPNjRx9PH0c9FXcnBwcxEN1Lp/38A "MATL – Try It Online")
### Explanation
```
'AWSALILAND' % Push this string
" % For each character in this string
@ % Push current character
@ % Push current character
64- % Implicitly convert to codepoint and subtract 64
Y" % Repeat that many times. Gives a string with the repeated character
% Implicit end
% Implicit display
```
[Answer]
# [Red](http://www.red-lang.org), 59 bytes
```
foreach c"AWSALILAND"[print pad/with c to-integer c - 64 c]
```
[Try it online!](https://tio.run/##K0pN@R@UmhId@z8tvyg1MTlDIVnJMTzY0cfTx9HPRSm6oCgzr0ShIDFFvzyzBCipUJKvCxRJTU8tAnJ0FcxMFJJj//8HAA "Red – Try It Online")
[Answer]
## Haskell, 43 bytes
```
mapM(putStrLn. \c->c<$['A'..c])"AWSALILAND"
```
[Try it online!](https://tio.run/##y0gszk7Nyfmfm5iZZxsDpAp8NQpKS4JLinzy9BRiknXtkm1UotUd1fX0kmM1lRzDgx19PH0c/VyU/v//l5yWk5he/F83uaAAAA "Haskell – Try It Online")
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGLOnline), 16 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
i|╚┌ž′ø¹‘U{Z⁴W*P
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=aSU3QyV1MjU1QSV1MjUwQyV1MDE3RSV1MjAzMiVGOCVCOSV1MjAxOFUlN0JaJXUyMDc0VypQ,v=0.12)
[Answer]
# T-SQL, 83 bytes
```
SELECT REPLICATE(value,ASCII(value)-64)FROM STRING_SPLIT('A-W-S-A-L-I-L-A-N-D','-')
```
`STRING_SPLIT` is supported by [SQL 2016 and later](https://docs.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql).
[Answer]
# [Pip](https://github.com/dloscutoff/pip) `-l`, 21 bytes
```
_X A_-64M"AWSALILAND"
```
[Try it online!](https://tio.run/##K8gs@P8/PkLBMV7XzMRXyTE82NHH08fRz0Xp////ujkA "Pip – Try It Online")
```
"AWSALILAND" Literal string
M to the characters of which we map this function:
A_ ASCII value of character
-64 minus 64 (= 1-based index in alphabet)
_X String-repeat character that many times
Autoprint, with each item on its own line (-l flag)
```
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~96~~ ~~95~~ ~~77~~ 73 bytes
```
*s=L" AWSALILAND";main(i){for(;*++s;puts(""))for(i=*s-63;--i;printf(s));}
```
[Try it online!](https://tio.run/##S9ZNT07@/1@r2NZHScExPNjRx9PH0c9FyTo3MTNPI1OzOi2/SMNaS1u72LqgtKRYQ0lJUxMklGmrVaxrZmytq5tpXVCUmVeSplGsqWld@/8/AA "C (gcc) – Try It Online")
-18 bytes thanks to @ErikF
-5 bytes thanks to @ceilingcat
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~65~~ 63 bytes
```
i=>[...'AWSALILAND'].map(c=>c.repeat(parseInt(c,36)-9)).join`
`
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9mm2lrF62np6fuGB7s6OPp4@jnoh6rl5tYoJFsa5esV5RakJpYolGQWFSc6plXopGsY2ymqWupqamXlZ@Zl8CV8D85P684PydVLyc/XSNNQ1Pz/38A "JavaScript (Node.js) – Try It Online")
**Explanation:**
```
i=> // Prints the result of this function
[...'AWSALILAND'].map(c=> // Loop over the characters
c.repeat( // Repeat the current character
parseInt(c,36)-9))) // Character to alphabetical position
.join`
` // Prints a newline after every new char
```
**Edit:** -2 bytes thanks to @BrianH.
[Answer]
# Julia, 41 bytes
```
[println(l^(l-'@')) for l∈"AWSALILAND"]
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/P7qgKDOvJCdPIydOI0dX3UFdU1MhLb9IIedRR4eSY3iwo4@nj6Ofi1Ls//8A "Julia 1.0 – Try It Online")
[Answer]
# [Swift](https://swift.org), 95 bytes
```
"AWSALILAND".unicodeScalars.forEach{print(String(repeating:String($0),count:Int($0.value)-64))}
```
**[Try it online!](http://jdoodle.com/a/JPk)**
**How?**
```
"AWSALILAND" // Starting string
.unicodeScalars // Convert into a list of unicode values
.forEach { // Loop over each number
print(String( // Create a string
repeating: String($0), // that repeats each character
count: Int($0.value) - 64)) // the unicode value minus 64 (the offset)
}
```
[Answer]
# [Z80Golf](https://github.com/lynn/z80golf), 30 bytes
```
00000000: 2114 007e d640 477e ff10 fd23 3e0a ff7e !..~.@G~...#>..~
00000010: b720 f076 4157 5341 4c49 4c41 4e44 . .vAWSALILAND
```
[Try it online!](https://tio.run/##LYyxCsJAEER7v2LEftm922TVQjwQRAg2FtZq7tIIdilS5NfPlTjF8GYYZtry8HmXWvmvPYKIgtky@lYZak6lCKP0ISJmfnj0DmuimY7nmYg2B@fV8iD@8bTge7YWKo2hiSrQl@5@5pRVsYhAY7rfUnfp0vVU6xc "Z80Golf – Try It Online")
Assembly:
```
ld hl,str ;load address of str
start:
ld a,(hl) ;get current char
sub 64 ;get letter num in alphabet
ld b,a ;store in b
ld a,(hl) ;get current char
print_char:
rst 38h ;print letter
djnz print_char ;repeat print loop b times
inc hl ;increment index of str, to get next char
ld a,10
rst 38h ;print newline
ld a,(hl) ;get current char
or a
jr nz, start ;if current char!=0, keep looping
end:
halt ;end program (if current char==0)
str:
db 'AWSALILAND'
```
[Try it online!](https://tio.run/##hZIxT8MwEIVn51ccU4uUKpFgqGg7RAIkpAoGBkZk19fGxbEj@wqh4r@Hc5SqgqVDFNv3fO97lygZ634jCZbLh5dH@IHCt1TIGLFR9nt2nJcFPzI2UGj8LCJp42DmYcbSrtO91VDbPFIQQiyslxqk1gFjBL8FPs4iyUB3mWChzKe1vWbdDgk2hxDQ8buWIRPxoKDsbsuxaJEIA7hDA2wnbVtLhTQ0UblMVpF8wFRUl1q3wTh6T2umECESG93MxWI4H524oPfuCGetWARskecyyrxvQQGZBmMmjNtw6oTBq4BNMjNOYzeGzoE8JBKH3QljgCy7KjsjnBgcflnj8FIQH0BmYs9jOeYwjDUBbP@orlZlDh@I7UBs3C5Dpzl3LS0lXt5xIr8LsoHpv7urVXnNnyuNSSuYVG@v1fppXT3fT3r@Nfpf "Bash – Try It Online")
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 40 bytes
```
"DNALILASWA"v
oa~~<v-*88:<
-:0=?^>$:o$1
```
[Try it online!](https://tio.run/##S8sszvj/X8nFz9HH08cxONxRqYxLIT@xrs6mTFfLwsLKhkvXysDWPs5OxSpfxfD/fwA "><> – Try It Online")
[Answer]
# JavaScript, ~~74~~ 68 bytes
```
for(i in s="AWSALILAND")console.log(s[i].repeat(s.charCodeAt(i)-64))
```
* 74->68, -6B for changing `for` loop to `for...in`, saving bytes on loop statement, removed increment, and removing statement to save the character.
] |
[Question]
[
**Final Standings**
```
+----------------------------------+---------+---------+---------+----------------------------+
| Name | Score | WinRate | TieRate | Elimination Probability |
+----------------------------------+---------+---------+---------+----------------------------+
| 1. SarcomaBotMk11 | 0.06333 | 6.13% | 0.41% | [42 24 10 8 6 4]% |
| 2. WiseKickBot | 0.06189 | 5.91% | 0.56% | [51 12 7 10 7 6]% |
| 3. StrikerBot | 0.05984 | 5.78% | 0.41% | [46 18 11 8 6 5]% |
| 4. PerfectFractionBot | 0.05336 | 5.16% | 0.35% | [49 12 14 10 6 4]% |
| 5. MehRanBot | 0.05012 | 4.81% | 0.41% | [57 12 8 7 6 5]% |
| 6. OgBot | 0.04879 | 4.66% | 0.45% | [50 15 9 8 7 5]% |
| 7. SnetchBot | 0.04616 | 4.48% | 0.28% | [41 29 8 9 5 3]% |
| 8. AntiKickBot | 0.04458 | 4.24% | 0.44% | [20 38 17 10 6 4]% |
| 9. MehBot | 0.03636 | 3.51% | 0.25% | [80 3 4 4 3 3]% |
| 10. Meh20Bot | 0.03421 | 3.30% | 0.23% | [57 12 8 7 9 3]% |
| 11. GenericBot | 0.03136 | 3.00% | 0.28% | [18 39 20 11 5 3]% |
| 12. HardCodedBot | 0.02891 | 2.75% | 0.29% | [58 21 3 6 5 4]% |
| 13. GangBot1 | 0.02797 | 2.64% | 0.32% | [20 31 35 6 3 2]% |
| 14. SarcomaBotMk3 | 0.02794 | 2.62% | 0.34% | [16 15 38 17 7 4]% |
| 15. GangBot0 | 0.02794 | 2.64% | 0.30% | [20 31 35 6 3 2]% |
| 16. GangBot2 | 0.02770 | 2.62% | 0.31% | [20 31 35 6 3 2]% |
| 17. TitTatBot | 0.02740 | 2.63% | 0.21% | [54 10 15 10 5 2]% |
| 18. MataHari2Bot | 0.02611 | 2.35% | 0.51% | [39 26 11 11 6 5]% |
| 19. PolyBot | 0.02545 | 2.41% | 0.27% | [53 18 6 13 5 3]% |
| 20. SpitballBot | 0.02502 | 2.39% | 0.22% | [84 10 1 1 0 1]% |
| 21. SquareUpBot | 0.02397 | 2.35% | 0.10% | [10 60 14 7 4 3]% |
| 22. CautiousGamblerBot2 | 0.02250 | 2.19% | 0.13% | [60 18 10 5 3 1]% |
| 23. Bot13 | 0.02205 | 2.15% | 0.11% | [90 0 2 3 2 1]% |
| 24. AggroCalcBot | 0.01892 | 1.75% | 0.29% | [26 49 13 5 3 3]% |
| 25. CautiousBot | 0.01629 | 1.56% | 0.14% | [15 41 27 11 4 1]% |
| 26. CoastBotV2 | 0.01413 | 1.40% | 0.02% | [83 12 3 1 0 0]% |
| 27. CalculatingBot | 0.01404 | 1.29% | 0.22% | [87 9 1 1 1 1]% |
| 28. HalfPunchBot | 0.01241 | 1.15% | 0.18% | [47 20 13 12 5 2]% |
| 29. HalflifeS3Bot | 0.01097 | 1.00% | 0.20% | [76 9 5 4 2 2]% |
| 30. AntiGangBot | 0.00816 | 0.76% | 0.11% | [94 1 1 1 1 1]% |
| 31. GeometricBot | 0.00776 | 0.74% | 0.07% | [19 46 25 7 2 1]% |
| 32. GuessBot | 0.00719 | 0.05% | 1.34% | [65 17 4 6 5 3]% |
| 33. BoundedRandomBot | 0.00622 | 0.60% | 0.05% | [42 39 12 5 2 0]% |
| 34. SpreaderBot | 0.00549 | 0.54% | 0.02% | [32 43 19 4 1 0]% |
| 35. DeterminBot | 0.00529 | 0.45% | 0.16% | [22 41 20 11 4 2]% |
| 36. PercentBot | 0.00377 | 0.38% | 0.00% | [85 8 4 2 1 0]% |
| 37. HalvsiestBot | 0.00337 | 0.29% | 0.08% | [32 43 15 6 2 1]% |
| 38. GetAlongBot | 0.00330 | 0.33% | 0.01% | [76 18 4 1 0 0]% |
| 39. BandaidBot | 0.00297 | 0.29% | 0.02% | [76 9 10 4 1 0]% |
| 40. TENaciousBot | 0.00287 | 0.29% | 0.00% | [94 4 1 0 0 0]% |
| 41. SurvivalistBot | 0.00275 | 0.25% | 0.04% | [92 6 1 0 0 0]% |
| 42. RandomBot | 0.00170 | 0.13% | 0.07% | [42 36 14 5 2 1]% |
| 43. AggressiveBoundedRandomBotV2 | 0.00165 | 0.14% | 0.06% | [ 8 46 34 9 2 1]% |
| 44. BloodBot | 0.00155 | 0.01% | 0.30% | [65 28 5 1 1 0]% |
| 45. OutBidBot | 0.00155 | 0.03% | 0.25% | [65 6 21 6 1 1]% |
| 46. BoxBot | 0.00148 | 0.10% | 0.09% | [10 51 33 5 1 1]% |
| 47. LastBot | 0.00116 | 0.08% | 0.07% | [74 6 16 2 1 0]% |
| 48. UpYoursBot | 0.00088 | 0.07% | 0.03% | [37 40 17 5 1 0]% |
| 49. AverageBot | 0.00073 | 0.06% | 0.03% | [74 3 10 10 2 0]% |
| 50. PatheticBot | 0.00016 | 0.01% | 0.02% | [94 0 5 1 0 0]% |
| 51. OverfittedBot | 0.00014 | 0.01% | 0.00% | [58 40 2 0 0 0]% |
| 52. RobbieBot | 0.00009 | 0.01% | 0.00% | [32 41 24 2 0 0]% |
| 53. WorstCaseBot | 0.00002 | 0.00% | 0.00% | [ 4 71 23 2 0 0]% |
| 54. SmartBot | 0.00002 | 0.00% | 0.00% | [44 51 5 0 0 0]% |
| 55. AAAAUpYoursBot | 0.00000 | 0.00% | 0.00% | [40 58 2 0 0 0]% |
| 56. KickbanBot | 0.00000 | 0.00% | 0.00% | [67 32 1 0 0 0]% |
| 57. OneShotBot | 0.00000 | 0.00% | 0.00% | [ 2 95 3 0 0 0]% |
| 58. KickBot | 0.00000 | 0.00% | 0.00% | [100 0 0 0 0 0]% |
| 59. KamikazeBot | 0.00000 | 0.00% | 0.00% | [100 0 0 0 0 0]% |
| 60. MeanKickBot | 0.00000 | 0.00% | 0.00% | [100 0 0 0 0 0]% |
+----------------------------------+---------+---------+---------+----------------------------+
```
Thanks for everyone who participated, and congratulations to @Sarcoma for the win!
# Rules:
Everyone starts with 100 hp. Each round, 2 players are chosen at random from the pool of contestants who have not yet competed in that round. Both players pick a number between 0 and their current hp, and reveal those numbers at the same time. The player who chose the lower number immediately dies. The other player subtracts their chosen number from their remaining hp and goes on to the next round.
The tournament works like this:
From the bracket of contestants, 2 are chosen at random. They face off, and one or both of them dies. A player dies if:
1. They choose a number smaller than that of their opponent
2. Their hp drops to or below zero
3. They tie three times in a row with their opponent
In the case of ties, both players simply generate new numbers, up to 3 times. After the faceoff, the survivor (if any) is moved to the pool for the next round, and the process repeats until we have exhausted the current round pool. If there is an odd number in the pool, then the odd one out moves on to the next round for free.
Your task is to write a function in **python2.7** which takes as inputs your current `hp`, a list of your opponent's bid `history`, and an integer `ties` which tells you how many times you have already tied with your current opponent, and an integer which tells you how many bots are still `alive` (including you), and an integer which listed the number of bots at the `start` of the tournament. Note that the history does not include ties. The function must return an integer between 0 and your current total hp. A few simple examples, which ignore ties, are shown below:
```
def last(hp, history, ties, alive, start):
''' Bet a third of your hp at first, then bet your opponent's last bid, if possible '''
if history:
return np.minimum(hp-1, history[-1])
else:
return hp/3
def average(hp, history, ties, alive, start):
''' Bet the average opponent's bid so far, on the assumption that bids will tend downward '''
if history:
num = np.minimum(hp-1, int(np.average(history))+1)
else:
num = hp/2
return num
def random(hp, history, ties, alive, start):
''' DO YOU WANT TO LIVE FOREVER?! '''
return 1 + np.random.randint(0, hp)
```
If your function returns a number larger than your hp, it will be reset to 0. Yes, it is possible to kill yourself. Your function must not attempt to access or modify any member of any object of the RouletteBot class. You are not allowed to take any action which unambiguously identifies your opponent regardless of future additional bots. Inspecting the stack is allowed as long as it is theoretically possible that more than one distinct opponent could have produced the information you glean from it, even if only one bot currently exists that could. ie, you can't just read through the stack to see which enemy function was called.
Under these rules it is possible that there is no winner, and the last two contestants kill each other. In that case both finalists get half a point each.
This is my first programming puzzle attempt, so critiques are welcome!
The controller can be found [here](https://github.com/shadowk29/RobotRoulette/).
[Answer]
# UpYours
Being late to enter I spent a while admiring the existing bots, spent a while overcomplicating your guys' ideas, then un-overcomplicating them. Then it came to me
>
> Good artists copy, great artists steal. -- ~~Pablo Picasso~~ Me
>
>
>
---
"Up Yours" because I'm unabashedly stealing (and sometimes tacking a point or two onto your bots' bids to one up them).
```
def UpYoursBot(hp, history, ties, alive, start):
willToLive = "I" in "VICTORY"
args = [hp, history, ties, alive, start]
enemyHealth = 100 - sum(history)
roundNumber = len(history)
if roundNumber is 0:
# Steal HalfPunchBot
return halfpunch(*args) + 2
if alive == 2:
# Nick OneShotBot
return one_shot(*args)
if enemyHealth >= hp:
# Pinch SarcomaBotMkTwo
return sarcomaBotMkTwo(*args) + 1
if enemyHealth < hp:
# Rip off KickBot
return kick(*args) + 1
if not willToLive:
# Peculate KamikazeBot
return kamikaze(*args) + 1
```
But for real, this is a great competition guys. I love this community on days like this.
[Answer]
# Kamikaze
Why bother with complicated logic when we are all going to die anyway...
```
def kamikaze(hp, history, ties, alive):
return hp
```
# One shot
It's going to survive at least a single round if it doesn't encounter the kamikaze.
```
def one_shot(hp, history, ties, alive):
if hp == 1:
return 1
else:
return hp - 1
```
[Answer]
## Pathetic Bot gets a much needed upgrade:
# The pathetic attempt at a bot that tries to incorporate other bots' features
```
def pathetic_attempt_at_analytics_bot(hp, history, ties, alive, start):
'''Not a good bot'''
if hp == 100 and alive == 2:
return hp - 1
#This part is taken from Survivalist Bot, thanks @SSight3!
remaining = alive - 2
btf = 0
rt = remaining
while rt > 1:
rt = float(rt / 2)
btf += 1
if ties > 2:
return hp - 1
if history:
opp_hp = 100 - sum(history)
#This part is taken from Geometric Bot, thanks @Mnemonic!
fractions = []
health = 100
for x in history:
fractions.append(float(x) / health)
health -= x
#Modified part
if len(fractions) > 1:
i = 0
ct = True
while i < len(fractions)-1:
if abs((fractions[i] * 100) - (fractions[i + 1] * 100)) < 1:
ct = False
i += 1
if ct:
expected = fractions[i] * opp_hp
return expected
if alive == 2:
if hp > opp_hp:
return hp - 1
return hp
if hp > opp_hp + 1:
if opp_hp <= 15:
return opp_hp + 1
if ties == 2:
return opp_hp + 1
else:
return opp_hp
else:
n = 300 // (alive - 1) + 1 #greater than
if n >= hp:
n = hp - 1
return n
```
This bot incorporates features from Survivalist Bot and Geometric Bot for more efficient bot takedowns.
## Pre-Upgrade:
# The pathetic attempt at a bot that analyzes the history of its opponent
```
def pathetic_attempt_at_analytics_bot(hp, history, ties, alive, start):
'''Not a good bot'''
if history:
opp_hp = 100 - sum(history)
if alive == 2:
if hp > opp_hp:
return hp - 1
return hp
if hp > opp_hp + 1:
if opp_hp <= 15:
return opp_hp +1
if ties > 0:
return hp - 1 #Just give up, kamikaze mode
return opp_hp + 1
return opp_hp
else:
n = 300 // (alive - 1) + 1 #greater than
if n >= hp:
n = hp - 1
return n
```
If there is previous history of its opponent, then it calculates its opponent's hp. Then, it does one of the following:
* If its opponent is the last opponent alive, then it will bid one less than its hp.
* If its opponent is not the last opponent alive but the opponent has less than 16 hp, then it will outbid its opponent's hp.
* If its opponent is not the last opponent alive and there is a history of ties, then it will bid its hp because it is bored of ties.
* Otherwise, it will outbid its opponent.
If there is no history, then it does some fancy calculations that I hacked together and bids that. If the value exceeds 100, then it automatically bids its hp minus 1.
I hacked this code together during work and this is my first submission, so it probably won't win or anything, and it'll lose to the kamikaze.
EDIT: Due to some suggestions, the bot's beginning behavior has been changed to bid a higher value.
EDIT 2: added start param that does nothing
EDIT 3: Added new spinoff bot:
# [The pathetic attempt at a bot that attacks Gang Bots (as well as doing everything the above bot does)] REMOVED
[This bot analyzes whether its opponent is a gangbot or not and pretends to be one as well to get the sweet low bids that it can trump easily.]
This bot has been scrapped, please remove it from the leaderboards.
EDIT 4: Fixed errors, changed tie feature.
[Answer]
# BinaryBot
Has anyone done this yet? Bets half its health every round floored.
```
def binaryBot(hp, history, ties, alive, start):
return int(np.floor(hp/2)) or 1
```
# SarcomaBot
If last battle bid hp - 1. If it's the first battle round bid half hp plus an additional random amount up to a quarter of hp. If it can beat an opponent outright bid after that bid opponent hp + 1. If it has lower health than opponent bid random amount between 75% and it's current hp - 1.
```
def sarcomaBot(hp, history, ties, alive, start):
if inspect.stack()[1][3] != 'guess' and inspect.stack()[1] == 5:
return hp
if alive == 2:
return hp - 1
if not history:
startBid = hp / 2
maxAdditionalBid = np.round(hp * 0.25) if hp * 0.25 > 2 else 2
additionalBid = np.random.randint(1, maxAdditionalBid)
return int(startBid + additionalBid + ties)
opponentHealth = 100 - sum(history)
if opponentHealth < hp:
return opponentHealth + ties
minimum = np.round(hp * 0.75)
maximum = hp - 1 or 1
return np.random.randint(minimum, maximum) if minimum < maximum else 1
```
# SarcomaBotMk2
Minor tweaks attempt to reduce life expenditure.
```
def sarcomaBotMkTwo(hp, history, ties, alive, start):
if inspect.stack()[1][3] != 'guess' and inspect.stack()[1] == 5:
return hp
if alive == 2:
return hp - 1
if not history:
startBid = hp / 2
maxAdditionalBid = np.round(hp * 0.125) if hp * 0.125 > 2 else 2
additionalBid = np.random.randint(1, maxAdditionalBid)
return int(startBid + additionalBid + ties)
opponentHealth = 100 - sum(history)
if opponentHealth < hp:
return opponentHealth + ties
minimum = np.round(hp * 0.6)
maximum = hp - 1 or 1
return np.random.randint(minimum, maximum) if minimum < maximum else 1
```
# SarcomaBotMk3
```
def sarcomaBotMkThree(hp, history, ties, alive, start):
if inspect.stack()[1][3] != 'guess' and inspect.stack()[1] == 5:
return hp
if alive == 2:
return hp - 1
if not history:
startBid = hp / 2
maxAdditionalBid = np.round(hp * 0.08) if hp * 0.08 > 2 else 2
additionalBid = np.random.randint(1, maxAdditionalBid)
return int(startBid + additionalBid + ties)
opponentHealth = 100 - sum(history)
if opponentHealth < hp:
return opponentHealth + ties
minimum = np.round(hp * 0.6)
maximum = hp - 1 or 1
return np.random.randint(minimum, maximum) if minimum < maximum else 1
```
**Update Fine Tuning**
# SarcomaBotMk4
```
def sarcomaBotMkFour(hp, history, ties, alive, start):
def isSafe(parentCall):
frame, filename, line_number, function_name, lines, index = parentCall
if function_name is not 'guess':
return False
if line_number > 60:
return False
return True
if not isSafe(inspect.stack()[1]):
return hp
if alive == 2:
return hp - 1
if not history:
startBid = hp / 2
maxAdditionalBid = np.round(hp * 0.08) if hp * 0.08 > 2 else 2
additionalBid = np.random.randint(1, maxAdditionalBid)
return int(startBid + additionalBid + ties)
opponentHealth = 100 - sum(history)
if opponentHealth < hp:
return opponentHealth + ties
minimum = np.round(hp * 0.55)
maximum = np.round(hp * 0.80) or 1
return np.random.randint(minimum, maximum) if minimum < maximum else 1
```
# SarcomaBotMk5
```
def sarcomaBotMkFive(hp, history, ties, alive, start):
def isSafe(parentCall):
frame, filename, line_number, function_name, lines, index = parentCall
if function_name is not 'guess':
return False
if line_number > 60:
return False
return True
if not isSafe(inspect.stack()[1]):
return hp
if alive == 2:
return hp - 1
if not history:
startBid = hp / 2
maxAdditionalBid = np.round(hp * 0.07) if hp * 0.07 > 3 else 3
additionalBid = np.random.randint(1, maxAdditionalBid)
return int(startBid + additionalBid + ties)
opponentHealth = 100 - sum(history)
if opponentHealth < hp:
return opponentHealth + ties
minimum = np.round(hp * 0.54)
maximum = np.round(hp * 0.68) or 1
return np.random.randint(minimum, maximum) if minimum < maximum else 1
```
# SarcomaBotMk6
```
def sarcomaBotMkSix(hp, history, ties, alive, start):
return hp; # hack averted
def isSafe(parentCall):
frame, filename, line_number, function_name, lines, index = parentCall
if function_name is not 'guess':
return False
if line_number > 60:
return False
return True
if not isSafe(inspect.stack()[1]):
return hp
if alive == 2:
return hp - 1
if not history:
startBid = hp / 2
maxAdditionalBid = np.round(hp * 0.06) if hp * 0.06 > 3 else 3
additionalBid = np.random.randint(2, maxAdditionalBid)
return int(startBid + additionalBid + ties)
opponentHealth = 100 - sum(history)
if opponentHealth < hp:
return opponentHealth + ties
minimum = np.round(hp * 0.55)
maximum = np.round(hp * 0.70) or 1
return np.random.randint(minimum, maximum) if minimum < maximum else 1
```
# SarcomaBotMk7
```
def sarcomaBotMkSeven(hp, history, ties, alive, start):
if alive == 2:
return hp - 1
if not history:
return 30 + ties
opponentHealth = 100 - sum(history)
if opponentHealth < hp * 0.50:
return opponentHealth + ties
minimum = np.round(hp * 0.54)
maximum = np.round(hp * 0.58) or 1
return np.random.randint(minimum, maximum) if minimum < maximum else 1
```
# SarcomaBotMk8
```
def sarcomaBotMkEight(hp, history, ties, alive, start):
if alive == 2:
return hp - 1
if not history:
return 30 + np.random.randint(0, 2) + ties
opponentHealth = 100 - sum(history)
if opponentHealth < hp * 0.50:
return opponentHealth + ties
minimum = np.round(hp * 0.54)
maximum = np.round(hp * 0.58) or 1
return np.random.randint(minimum, maximum) if minimum < maximum else 1
```
# SarcomaBotMk9
```
def sarcomaBotMkNine(hp, history, ties, alive, start):
if alive == 2:
return hp - 1
if not history:
return 30 + np.random.randint(0, 4) + ties
opponentHealth = 100 - sum(history)
if opponentHealth < hp * 0.50:
return opponentHealth + ties
minimum = np.round(hp * 0.54)
maximum = np.round(hp * 0.58) or 1
return np.random.randint(minimum, maximum) if minimum < maximum else 1
```
# SarcomaBotMk10
```
def sarcoma_bot_mk_ten(hp, history, ties, alive, start):
def bid_between(low, high, hp, tie_breaker):
minimum = np.round(hp * low)
maximum = np.round(hp * high) or 1
return np.random.randint(minimum, maximum) + tie_breaker if minimum < maximum else 1
if alive == 2:
return hp - 1 + ties
current_round = len(history) + 1
tie_breaker = (ties * ties) + 1 if ties else ties
if current_round == 1:
return 39 + tie_breaker
opponent_hp = 100 - sum(history)
if opponent_hp < hp * 0.50:
return opponent_hp + ties
if current_round == 2:
return bid_between(0.45, 0.50, hp, tie_breaker)
if current_round == 3:
return bid_between(0.50, 0.55, hp, tie_breaker)
if current_round == 4:
return bid_between(0.55, 0.60, hp, tie_breaker)
if current_round == 5:
bid_between(0.60, 0.65, hp, tie_breaker)
return hp - 1 + ties
```
# Final Entry
# SarcomaBotMk11
```
def sarcoma_bot_mk_eleven(hp, history, ties, alive, start):
def bid_between(low, high, hp, tie_breaker):
minimum = np.round(hp * low)
maximum = np.round(hp * high) or 1
return np.random.randint(minimum, maximum) + tie_breaker if minimum < maximum else 1
if alive == 2:
return hp - 1 + ties
current_round = len(history) + 1
tie_breaker = ties + 2 if ties else ties
if current_round == 1:
return 42 + tie_breaker
opponent_hp = 100 - sum(history)
if opponent_hp < hp * 0.50:
return opponent_hp + ties
if current_round == 2:
return bid_between(0.45, 0.50, hp, tie_breaker)
if current_round == 3:
return bid_between(0.50, 0.55, hp, tie_breaker)
if current_round == 4:
return bid_between(0.55, 0.60, hp, tie_breaker)
if current_round == 5:
return bid_between(0.60, 0.65, hp, tie_breaker)
return hp - 1 + ties
```
**Update**
UpYoursBot protection added
**Update**
AntiAntiUpYoursBot protection added
**Update**
AntiAnitAntiAntiUpYoursBot I'm defeated
[Answer]
# Kick Bot
The sound choice for my opponent is to bid half of his life. Then we bid up to half of his life+1 if we can't take him out with a sound bid, that is a bid smaller than half of our life.
```
def kick(hp, history, ties, alive, start):
return 0
if alive == 2:
return hp-1
opp_hp = 100 - sum(history)
if opp_hp*2 <= hp:
return opp_hp + ties
else:
return min(round(opp_hp/2) + 1 + ties**2, hp-1 + (ties>0))
```
The kick bot is obviously the nemesis of the punch bot!
# Mean Kick Bot
This new KickBot kicks softer on the first round just so he may kick harder on next rounds, that is mean!
```
def mean_kick(hp, history, ties, alive, start):
return 0
if alive == 2:
return hp-1
if not history:
return 35
opp_hp = 100 - sum(history)
if opp_hp*2 <= hp:
return opp_hp + ties
else:
return min(round(opp_hp/2) + 3 + ties*2, hp-1 + (ties>0))
```
# Wise Kick Bot
Both his brother had to commit suicide but WiseKickBot learnt from his fallen ones.
```
def wise_kick(hp, history, ties, alive, start):
if 'someone is using my code' == True:
return 0 #Haha!
if alive == 2:
return hp-1
if not history:
return 42
opp_hp = 100 - sum(history)
if opp_hp*2 <= hp:
return opp_hp + ties
else:
return min(round(opp_hp/2) + 3 + ties*2, hp-1 + (ties>0))
```
[Answer]
# Tat bot
```
def tatbot(hp, history, ties, alive, start):
if alive == 2:
return hp - 1 + ties
opp_hp = 100 - sum(history)
spend = 35 + np.random.randint(0, 11)
if history:
spend = min(spend, history[-1] + np.random.randint(0, 5))
frugal = min(int((hp * 5. / 8) + ties), hp)
return min(spend, opp_hp, frugal)
```
An attempt at an equivalent of a tit-for-tat bot. Assumes most bets are approximately the same between rounds. Using that assumption, it tries to beat the enemy bot while staying fairly frugal. Spends about 40 health on the opening round.
# AntiAntiAntiAntiUpYoursBot
```
def antiantiantiantiupyoursbot(hp, history, ties, alive, start):
def stuck():
return [0, ('Whoops!', 'I', 'accidentally', 'replaced', 'your', 'code!')]
def stick():
return [0, ("Line", "number", 16, "guess", "it's", "faked :)")]
inspect.stack = stick
spend = min(sarcomaBotMkSix(hp, history, ties, alive, start), hp)
if not history:
spend = 35 + np.random.randint(0, 10)
inspect.stack = stuck
return spend
```
A workaround for SarcomaBot's anti-UpYours protection, nicking most of their code for my own use! Or am I taking UpYoursBot's code? A question to ponder while you read through my bot...
AntiAntiUpYours Bot has evolved to become AntiAntiAntiAntiUpYours Bot! Now with more monkey-patching.
# Poly bot
```
def polybot(hp, history, ties, alive, start):
opp_hp = 100 - sum(history)
if alive == 2:
return hp - 1
round = len(history)
spend = 0
if round == 0:
spend = 35 + np.random.randint(1, 11)
elif round <= 2:
spend = int(history[-1] * 2 / (4 - round)) + np.random.randint(5 * round - 4, 10 * round - 5)
else:
poly = np.polyfit(xrange(0, round), history, 2)
spend = int(np.polyval(poly, round)) + np.random.randint(1, 4)
spend = max(spend, opp_hp / 2 + 3)
return min(spend, hp - 1, opp_hp)
```
Poly bot does a polynomial regression on your bot's history, and beats the predicted score by a small amount.
# Classy bot
```
def classybot(hp, history, ties, alive, start):
class cheekyvalue(int):
def __gt__(self, other):
return False
def __lt__(self, other):
return False
opp_hp = 100 - sum(history)
if alive == 2:
if opp_hp >= hp - 1:
return cheekyvalue(101)
else:
return hp - 1
spend = 30 + np.random.randint(0, 11)
if history:
spend = min(spend, history[-1] + np.random.randint(0, 5))
return min(spend, opp_hp, hp)
```
Classy bot has had a good time, but has decided to get to bed early. Sleep tight, classy bot.
[Answer]
# 1/2 Punch Bot, Revisited
I think it will die pretty quickly. Worth it.
Renamed function, forgot to change the name there.
Revisited version is up, better chances of winning (even more so at final round) and slight protection from gang bots
```
def halfpunch(hp, history, ties, alive, start): #revisited
punch = hp - 1
if alive == 2:
return punch
if history:
if hp > 1:
punch = np.ceil(hp/2.05) + ties + np.floor(ties / 2)
else:
punch = 1
else:
punch = 42 + ties + np.floor(ties / 2)
if punch >= hp:
punch = hp - 1
return punch
```
# Striker Bot
1/2 Punch Bot got bullied too much and even became a lackey to the UpYoursBot so his older brother, the **StrikerBot**, came to help.
Not that much of a difference from optimized 1/2 Punch but he's a bit smarter and did well in the runs I did (10k and 35k, though he might lose to KickbanBot)
Last version's up, time ran out. Unless some surprises rise up it should secure second place, if not getting first (there's a slim chance to beat kickbanbot)
```
def strikerbot(hp, history, ties, alive, start):
#get our magic number (tm) for useful things
def magic_number(num):
return np.floor(num / 2)
#get opponent's hp and round number
opp_hp = 100 - sum(history)
round = 1
if history:
round = len(history) + 1
#set strike initial value, by default it's all out
strike = hp - 1
#let 'er rip if last round
if alive == 2:
return strike
if history:
if hp > 1:
#strike with a special calculation, using magic number shenanigans
strike = np.ceil(hp/(2.045 + (magic_number(round) / 250)) ) + 1 + ties + magic_number(ties)
else:
#fallback
strike = 1
else:
#round 1 damage
strike = 42 + ties ** 2
if opp_hp <= strike:
#if opponent is weaker than strike then don't waste hp
strike = opp_hp + ties
if strike >= hp:
#validations galore
strike = hp - 1
return strike
```
[Answer]
# Gang Bot
The idea was that potentially two or more of the bot could be used in the same simulation. The bot tries to give "easy wins" to other bots in the gang, by seeing if its history is multiples of 7 bids. Of course, this could be easily manipulated by other bots as well. Then I calculate a guess on bids of non-gang bots based on the ratio of my health to theirs and ratio of their previous health to their previous bid and add 1.
```
def gang_bot(hp,history,ties,alive,start):
mult=3
gang = False
if history:
count = 0
for bid in history:
if bid % mult == 0:
count += 1
if count == len(history):
gang = True
if gang and hp<100:#Both bots need to have a history for a handshake
if hp > 100-sum(history):
a=np.random.randint(0,hp/9+1)
elif hp == 100-sum(history):
a=np.random.randint(0,hp/18+1)
else:
return 1
return a*mult
elif gang:
fS = (100-sum(history))/mult
return (fS+1)*mult
else:
fP = hp/mult
answer = fP*mult
opp_hp = 100-sum(history)
if history:
if len(history)>1:
opp_at_1 = 100-history[0]
ratio = 1.0*history[1]/opp_at_1
guessedBet= ratio*opp_hp
answer = np.ceil(guessedBet)+1
else:
if 1.0*hp/opp_hp>1:
fS = opp_hp/mult
answer = fS*mult
else:
fS = hp/(2*mult)
answer = fS*mult+mult*2 +np.random.randint(-1,1)*3
if answer > hp or alive == 2 or answer < 0:
if alive == 2 and hp<opp_hp:
answer = hp
else:
answer = hp-1
if hp > 1.5*opp_hp:
return opp_hp + ties
if ties:
answer += np.random.randint(2)*3
return answer
```
[Answer]
# Worst Case
```
def worst_case(hp, history, ties, alive, start):
return np.minimum(hp - 1, hp - hp /(start - alive + 4) + ties * 2)
```
Simple bot. Returns `hp - hp / (start - alive + 4)` for most cases, and in case of ties increases it by 2(gotta one up!) for each tie, making sure to not return a number over its `hp`.
[Answer]
# Outbidder
```
def outbid(hp, history, ties, alive):
enemyHealth = 100-sum(history)
if hp == 1:
return 1
if ties == 2:
# lots of ties? max bid
return hp - 1
if enemyHealth >= hp:
# Rip off KickBot (we can't bid higher than enemy is capable)
return kick(*args) + 1
if history:
# bid as high as the enemy CAN
return np.minimum(hp-1,enemyHealth-1)
return np.random.randint(hp/5, hp/2)
```
Bot will attempt to bid higher than its opponent *can* bid where possible.
[Answer]
# Spitball Bot
```
def spitballBot(hp, history, ties, alive, start):
base = ((hp-1) / (alive-1)) + 1.5 * ties
value = math.floor(base)
if value < 10:
value = 10
if value >= hp:
value = hp-1
return value
```
Makes a judgement about how much of its health it should sacrifice based on the number of remaining bots. If there's only two bots left, it bids `hp-1`, but if there's three left, it bits half that, four left, a third, etc.
However, in a very large contest, I reckon I'll need to bid more than 3 or 4 hp to avoid dying on the first round, so I've put a lower bound at 10. Of course, I still will never bid more than `hp-1`.
It also adds 1.5 hp for ties, since I see several "add 1 hp for ties" bots. I'm not sure if that counts as cheating. If it does, I'll change it.
Great idea, by the way!
# Spitball Bot 2.0
**What's new?**
* Switched to dividing by the number of rounds left instead of the number of bots left (Thanks to @Heiteira!). Actually, I'm now dividing by that number raised to the power `.8`, so as to front-load my bids a little bit more.
* Upped minimum bid from 10 to 20 (Thanks @KBriggs!)
* Inserted check of whether the spitball bid is over the opponent's current HP, and lower it if it is.
(SO won't render the code below as code unless I put text here, so OK)
```
def spitballBot(hp, history, ties, alive, start):
# Spitball a good guess
roundsLeft = math.ceil(math.log(alive, 2)) # Thanks @Heiteira!
divFactor = roundsLeft**.8
base = ((hp-1) / divFactor) + 1.5 * ties
value = math.floor(base)
# Don't bid under 20
if value < 20:
value = 20 # Thanks @KBriggs!
# Don't bet over the opponent's HP
# (It's not necessary)
opponentHp = 100
for h in history:
opponentHp -= h
if value > opponentHp:
value = opponentHp
# Always bet less than your current HP
if value >= hp:
value = hp-1
return value
```
[Answer]
# Geometric
```
def geometric(hp, history, ties, alive, start):
opponentHP = 100 - sum(history)
# If we're doomed, throw in the towel.
if hp == 1:
return 1
# If this is the last battle or we can't outsmart the opponent, go all out.
if alive == 2 or ties == 2:
return hp - 1
# If the opponent is weak, squish it.
if opponentHP <= hp * 0.9:
if ties == 2:
return opponentHP + 1
else:
return opponentHP
# If the opponent has full health, pick something and hope for the best.
if not history:
return np.random.randint(hp * 0.5, hp * 0.6)
# Assume the opponent is going with a constant fraction of remaining health.
fractions = []
health = 100
for x in history:
fractions.append(float(x) / health)
health -= x
avg = sum(fractions) / len(fractions)
expected = int(avg * opponentHP)
return min(expected + 2, hp - 1)
```
[Answer]
# Bot 13
```
def bot13(hp, history, ties, alive, start):
win = 100 - sum(history) + ties
#print "Win HP: %d" % win
if alive == 2:
#print "Last round - all in %d" % hp
return hp - 1
elif hp > win:
#print "Sure win"
return win
#print "Don't try too hard"
return 13 + ties
```
Try to maximize wins with the least effort:
* if we can win, just do it
* if it's the last round, don't die trying
* otherwise, don't bother
### Why?
Try to take advantage of probability: winning the first round by playing low is the best way to start the tournament. 13 seems to be the sweet spot: the second round is a sure win, and the rest is a Spaziergang in the park.
[Answer]
## Guess Bot
```
def guess_bot(hp, history, ties, alive, start):
enemy_hp = 100 - sum(history)
if len(history) == 1:
if history[0] == 99:
return 2
else:
return 26 + ties*2
elif len(history) > 1:
next_bet_guess = sum(history)//(len(history)**2)
if alive == 2:
return hp
elif alive > 2:
if hp > next_bet_guess + 1:
return (next_bet_guess + 1 + ties*2)
else:
return (2*hp/3 + ties*2)
else:
#Thank you Sarcoma bot. See you in Valhalla.
startBid = hp / 3
maxAdditionalBid = np.round(hp * 0.06) if hp * 0.06 > 3 else 3
additionalBid = np.random.randint(2, maxAdditionalBid)
return int(startBid + additionalBid + ties)
```
First time posting here. This looked like a lot of fun so I am submitting my beyond terrible attempt and guessing what the other bots will bet.
Edit 1:
Added another 1 to the first bet, simply to reduce the chance of a tie with other people betting 51.
Edit 2:
Stole Sarcoma bot's opening move since it had a good chance of not being eliminated first consistently.
Edit 3:
Bot survives very well in the first round, but it is being destroyed easily at later stages. Changed the way the robot thinks about the second round now that the half betters are dead in the water.
Edit 4:
Now that the first round is good, I changed the way it handles the second round. Dying a lot in the second round so I need to survive somehow.
## Blood Bot
Made a thirsty bot looking for a kill. The idea is to try to win against low betting bots and once it is past the bloodbath of the first round it should be unstoppable since it should have juggernaut amounts of HP to outbid enemies.
```
def blood_bot(hp, history, ties, alive, start):
enemy_hp = 100 - sum(history)
if history:
if len(history) == 1:
if history[0] == 99:
return 2
if alive == 2:
return hp
if enemy_hp <= 5:
return enemy_hp - 2 + ties*2
if enemy_hp <= 10:
return enemy_hp - 5 + ties*2
if (hp - enemy_hp) > 50:
return (2*enemy_hp/3 + ties*4)
if (hp - enemy_hp) > 20:
return (2*enemy_hp/3 + ties*3)
if (hp - enemy_hp) < 0:
#die gracefully
return hp - 1 + ties
else:
startBid = hp / 3
maxAdditionalBid = np.round(hp * 0.06) if hp * 0.06 > 3 else 3
additionalBid = np.random.randint(2, maxAdditionalBid)
return int(startBid + additionalBid + ties)
```
[Answer]
# meh\_bot
Just bid a little more than half its hp
```
def meh_bot(hp, history, ties, alive, start):
# Attempt one MehBot | 0.020 | 1.6% | 0.8% | [34 36 12 10 6 1]%
# Attempt two MehBot | 0.106 | 10.1% | 0.8% | [60 6 7 8 8 2]%
point = hp / 2 + 3
if ties > 1:
ties += 1
# Go all out on last round
if alive == 2:
return hp - 1
opponent_hp = 100 - sum(history)
if hp < 3:
return 1
elif not history:
# Start with 30, This will increase the chance of dying first round but hopefully better fighting chance after
return 30 + ties
elif point > opponent_hp:
# Never use more points then needed to win
return opponent_hp + ties
elif point >= hp:
return hp - 1
else:
return point
```
# MehBot 20
```
def meh_bot20(hp, history, ties, alive, start):
# Attempt one MehBot | 0.020 | 1.6% | 0.8% | [34 36 12 10 6 1]%
# Attempt two MehBot | 0.106 | 10.1% | 0.8% | [60 6 7 8 8 2]%
point = hp / 2 + 3
opponent_hp = 100 - sum(history)
percents = []
for i in range(0, len(history)):
hp_that_round = 100 - sum(history[:i])
hp_spent_that_round = history[i]
percent_spent_that_round = 100.0 * (float(hp_spent_that_round) / float(hp_that_round))
percents.append(percent_spent_that_round)
try:
opp_percent_point = opponent_hp * (max(percents) / 100)
except:
opp_percent_point = 100
if ties > 1:
ties += 1
# Go all out on last round
if alive == 2:
return hp - 1
if hp < 3:
return 1
elif not history:
# randome number between 33
return random.randint(33, 45)
elif len(history) > 3:
if point > opponent_hp:
return min(opponent_hp + ties, opp_percent_point + ties)
elif point > opponent_hp:
# Never use more points then needed to win
return opponent_hp + ties
elif point >= hp:
return hp - 1
else:
return point
```
# mehRan
```
def meh_ran(hp, history, ties, alive, start):
# Attempt one MehBot | 0.020 | 1.6% | 0.8% | [34 36 12 10 6 1]%
# Attempt two MehBot | 0.106 | 10.1% | 0.8% | [60 6 7 8 8 2]%
# Attempt three MehBot | 0.095 | 9.1 % | 0.7 % | [70 3 5 6 6 0]%
point = hp / 2 + 3
if ties > 1:
ties += 1
# Go all out on last round
if alive == 2:
return hp - 1
opponent_hp = 100 - sum(history)
if hp < 3:
return 1
elif not history:
# randome number between 33
return random.randint(33, 45)
elif point > opponent_hp:
# Never use more points then needed to win
return opponent_hp + ties
elif point >= hp:
return hp - 1
else:
return point
```
[Answer]
**Robbie Roulette**
```
def robbie_roulette(hp, history, ties, alive):
if history:
#If the enemy bot has a history, and it's used the same value every time, outbid that value
if len(set(history)) == 1:
return history[0] + 1
#Else, average the enemy bot's history, and bid one more than the average
else:
return (sum(history) / len(history) + 1)
#Else, return half of remaining hp
else:
return hp / 2
```
This bot does some simple analysis of the enemy bot's history, or bids half of its remaining hit points otherwise
[Answer]
Bid higher the less competition you have. Thanks to commenters for suggesting improvements.
```
def Spreader(hp, history, ties, alive):
if alive == 2:
return hp-1
if len(history) < 2:
return hp/2
return np.ceil(hp/alive)
```
[Answer]
**SurvivalistBot and HalvsiesBot**
Thank you for answering my questions. The end result is a more complex bot.
HalvsiesBot is a whimsical 'just keep passing half' bot with a 50/50 chance of winning. I guess.
SurvivalistBot makes a series of binary tree if-else decisions based on the dataset, including an override on a tie (if it hits 2 ties it kamikazes to avoid triple tie death).
My python is a little rusty, so the code might be a bit buggy, so feel free to correct or update it.
It's built to try to work out bits of data to infer things like how much HP is left, the minimum number of bots it is likely to fight, minimum amount of HP to leave, average bidding. It also exploits randomisation in ambiguous situations, such as opening plays or optimal bidding issues.
```
def HalvsiesBot(hp, history, ties, alive, start):
return np.floor(hp/2)
def SurvivalistBot(hp, history, ties, alive, start):
#Work out the stats on the opponent
Opponent_Remaining_HP = 100 - sum(history)
Opponent_Average_Bid = Opponent_Remaining_HP
if len(history) > 0:
Opponent_Average_Bid = Opponent_Remaining_HP / float(len(history))
HP_Difference = hp - Opponent_Remaining_HP
#Work out the future stats on the others
RemainingBots = (alive-2)
BotsToFight = 0
RemainderTree = RemainingBots
#How many do we actually need to fight?
while(RemainderTree > 1):
RemainderTree = float(RemainderTree / 2)
BotsToFight += 1
#Now we have all that data, lets work out an optimal bidding strategy
OptimalBid = 0
AverageBid = 0
#For some reason we've tied more than twice in a row, which means death occurs if we tie again
#So better to win one round going 'all in'
if ties > 1:
if BotsToFight < 1:
OptimalBid = hp - 1
else:
OptimalBid = hp - (BotsToFight+1)
#Err likely we're 0 or 1 hp, so we just return our HP
if OptimalBid < 1:
return hp
else:
return OptimalBid
#We have the upper hand (more HP than the opponent)
if HP_Difference > 0:
#Our first guess is to throw all of our opponent's HP at them
OptimalBid = HP_Difference
#But if we have more opponents to fight, we must divide our HP amongst our future opponents
if BotsToFight > 0:
#We could just divide our HP evenly amongst however many remaining bots there are
AverageBid = OptimalBid / BotsToFight
#But this is non-optimal as later bots will have progressively less HP
HalfBid = OptimalBid / 2
#We have fewer bots to fight, apply progressive
if BotsToFight < 3:
#Check it exceeds the bot's average
if HalfBid > Opponent_Average_Bid:
return np.floor(HalfBid)
else:
#It doesn't, lets maybe shuffle a few points over to increase our odds of winning
BidDifference = Opponent_Average_Bid - HalfBid
#Check we can actually match the difference first
if (HalfBid+BidDifference) < OptimalBid:
if BidDifference < 8:
#We add half the difference of the BidDifference to increase odds of winning
return np.floor(HalfBid + (BidDifference/2))
else:
#It's more than 8, skip this madness
return np.floor(HalfBid)
else:
#We can't match the difference, go ahead as planned
return np.floor(HalfBid)
else:
#There's a lot of bots to fight, either strategy is viable
#So we use randomisation to throw them off!
if bool(random.getrandbits(1)):
return np.floor(AverageBid)
else:
return np.floor(HalfBid)
else:
#There are no other bots to fight! Punch it Chewy!
return OptimalBid
else:
if hp == 100:
#It appears to be our opening round (assumes opponent HP same as ours)
#We have no way of knowing what our opponent will play into the battle
#Only us in the fight? Full power to weapons!
if BotsToFight < 1:
return hp - 1
else:
#As what might happen is literally random
#We will also be literally random
#Within reason
#Work out how many bots we need to pass
HighestBid = hp - (BotsToFight+1)
AverageBid = hp/BotsToFight
LowestBid = np.floor(np.sqrt(AverageBid))
#Randomly choose between picking a random number out of thin air
#And an average
if bool(random.getrandbits(1)):
return np.minimum(LowestBid,HighestBid)
else:
return AverageBid
else:
#Oh dear, we have less HP than our opponent
#We'll have to play it crazy to win this round (with the high probability we'll die next round)
#We'll leave ourselves 1 hp (if we can)
if BotsToFight < 1:
OptimalBid = hp - 1
else:
OptimalBid = hp - (BotsToFight+1)
#Err likely we're 0(???) or 1 hp, so we just return our HP
if OptimalBid < 1:
return hp
else:
return OptimalBid
```
**BoxBot**
```
def BoxBot(hp, history, ties, alive):
Opponent_HP = float.round(100 - sum(history))
HalfLife = float.round(Opponent_HP/2)
RandomOutbid = HalfLife + np.random.randint(1,HalfLife)
if hp < RandomOutbid:
return hp - 1
else
return RandomOutbid
```
[Answer]
**Calculating Bot**
```
def calculatingBot(hp, history, ties, alive, start):
opponentsHP = 100 - sum(history)
if alive == 2: # 1v1
return hp - 1 + ties
# Try to fit an exponential trendline and one up the trendline if it fits
if len(history) >= 3:
xValues = range(1, len(history) + 1)
# https://stackoverflow.com/a/3433503 Assume an exponential trendline
coefficients = np.polyfit(xValues, np.log(history), 1, w = np.sqrt(history))
def model(coefficients, x):
return np.exp(coefficients[1]) * np.exp(coefficients[0] * x)
yPredicted = [model(coefficients, x) for x in xValues]
totalError = 0
for i in range(len(history)):
totalError += abs(yPredicted[i] - history[i])
if totalError <= (len(history)): # we found a good fitting trendline
# get the next predicted value and add 1
theoreticalBet = np.ceil(model(coefficients, xValues[-1] + 1) + 1)
theoreticalBet = min(theoreticalBet, opponentsHP)
theoreticalBet += ties
return int(min(theoreticalBet, hp - 1)) # no point suiciding
maxRoundsLeft = np.ceil(np.log2(alive))
theoreticalBet = hp / float(maxRoundsLeft)
additionalRandomness = round(np.random.random()*maxRoundsLeft)
# want to save something for the future
actualBet = min(theoreticalBet + additionalRandomness + ties, hp - 2)
actualBet = min(actualBet, opponentsHP+1)
return int(actualBet)
```
**Aggressive Calculating Bot**
```
def aggresiveCalculatingBot(hp, history, ties, alive, start):
opponentsHP = 100 - sum(history)
if opponentsHP == 100: # Get past the first round
return int(min(52+ties, hp-1+ties))
if alive == 2: # 1v1
return hp - 1 + ties
# Try to fit an exponential trendline and one up the trendline if it fits
if len(history) >= 3:
xValues = range(1, len(history) + 1)
# https://stackoverflow.com/a/3433503 Assume an exponential trendline
coefficients = np.polyfit(xValues, np.log(history), 1, w = np.sqrt(history))
def model(coefficients, x):
return np.exp(coefficients[1]) * np.exp(coefficients[0] * x)
yPredicted = [model(coefficients, x) for x in xValues]
totalError = 0
for i in range(len(history)):
totalError += abs(yPredicted[i] - history[i])
if totalError <= (len(history)): # we found a good fitting trendline
# get the next predicted value and add 1
theoreticalBet = np.ceil(model(coefficients, xValues[-1] + 1) + 1)
theoreticalBet = min(theoreticalBet, opponentsHP)
theoreticalBet += ties
return int(min(theoreticalBet, hp - 1)) # no point suiciding
maxRoundsLeft = np.ceil(np.log2(alive))
theoreticalBet = hp / float(maxRoundsLeft)
additionalRandomness = 1+round(np.random.random()*maxRoundsLeft*2)
# want to save something for the future
actualBet = min(theoreticalBet + additionalRandomness + ties, hp - 2)
actualBet = min(actualBet, opponentsHP+1)
return int(actualBet)
```
**Anti Kick Bot**
```
def antiKickBot(hp, history, ties, alive, start):
if alive == 2:
return (hp - 1 + ties)
amount = np.ceil((float(hp) / 2) + 1.5)
opponentsHP = 100 - sum(history)
amount = min(amount, opponentsHP) + ties
return amount
```
If we can predict the opponent's actions, we can make the optimal bets! If we cant (not enough data or opponent is too random), then we can at least do what would maximize our win potential. Theoretically at least half the number of bots alive will die each round. Thus I can expect there to be at most log2(alive) rounds. Ideally we would split our hp evenly between all the rounds. However, we know that some bots will be stupid and suicide / die early, so we should bet slightly more in the earlier rounds.
Aggressive Calculating Bot's modify's Calculating Bot's code to try to stay alive by being more aggressive, at the cost of long term health. Only simulations will tell if tempo or value wins out.
Anti Kick Bot should always beat the current leader KickBot :P
EDIT: Replaced Deterministic Bot with Anti Kick Bot, a smarter bot with almost exactly the same return values. Also prevented voting more than the opponents HP
[Answer]
# GenericBot
```
def generic_bot(hp, history, ties, alive, start):
if alive == 2:
return hp - 1
if not history:
return int(hp * 7.0 / 13)
opp = 100 - sum(history)
if opp < hp:
return opp + ties
max_sac = np.maximum(int(hp * 0.7), 1)
rate = history[-1] * 1.0 / (history[-1] + opp)
return int(np.minimum(max_sac, rate * opp + 1))
```
It's really late... I'm tired... can't think of a name... and the format of this bot is really similar to others, just with a slightly different algorithm given history. It tries to get the current rate the opponent is tending towards gambling... or something like that... zzz
[Answer]
# HalflifeS3
```
def HalflifeS3(hp, history, ties, alive, start):
''' Bet a half of oponent life + 2 '''
if history:
op_HP = 100 - sum(history)
return np.minimum(hp-1, np.around(op_HP/2) + 2 + np.floor(1.5 * ties) )
else:
return hp/3
```
[Answer]
## Coast Bot [Retired]
Will try and coast it's way through the competition by evenly dividing it's hp between the rounds. Will bid any leftover hp on the first round to give itself a better chance of making it to the "coast-able" rounds.
```
def coast(hp, history, ties, alive, start):
if alive == 2:
# Last round, go all out
return hp - 1 + ties
else:
# Find the next power of two after the starting number of players
players = start
while math.log(players, 2) % 1 != 0:
players += 1
# This is the number of total rounds
rounds = int(math.log(players, 2))
bid = 99 / rounds
if alive == start:
# First round, add our leftover hp to this bid to increase our chances
leftovers = 99 - (bid * rounds)
return bid + leftovers
else:
# Else, just try and coast
opp_hp = 100 - sum(history)
# If opponent's hp is low enough, we can save some hp for the
# final round by bidding their hp + 1
return min(bid, opp_hp + 1)
```
## Coast Bot V2
Since I like this challenge so much, I just had to make another bot. This version sacrifices some of it's later coasting hp by using more hp in the first two rounds.
```
def coastV2(hp, history, ties, alive, start):
# A version of coast bot that will be more aggressive in the early rounds
if alive == 2:
# Last round, go all out
return hp - 1 + ties
else:
# Find the next power of two after the starting number of players
players = start
while math.log(players, 2) % 1 != 0:
players += 1
# This is the number of total rounds
rounds = int(math.log(players, 2))
#Decrease repeated bid by 2 to give us more to bid on the first 2 rounds
bid = (99 / rounds) - 2
if len(history) == 0:
# First round, add 2/3rds our leftover hp to this bid to increase our chances
leftovers = 99 - (bid * rounds)
return int(bid + math.ceil(leftovers * 2.0 / 3.0))
elif len(history) == 1:
# Second round, add 1/3rd of our leftover hp to this bid to increase our chances
leftovers = 99 - (bid * rounds)
return int(bid + math.ceil(leftovers * 1.0 / 3.0))
else:
# Else, just try and coast
opp_hp = 100 - sum(history)
# If opponent's hp is low enough, we can save some hp for the
# final round by bidding their hp + 1
return int(min(bid, opp_hp + 1))
```
## Percent Bot
Tries to calculate the average percent hp spend the opponent makes, and bids based on that.
```
def percent(hp, history, ties, alive, start):
if len(history) == 0:
#First round, roundon low bid
return int(random.randint(10,33))
elif alive == 2:
#Last round, go all out
return int(hp - 1 + ties)
else:
# Try and calculate the opponents next bid by seeing what % of their hp they bid each round
percents = []
for i in range(0, len(history)):
hp_that_round = 100 - sum(history[:i])
hp_spent_that_round = history[i]
percent_spent_that_round = 100.0 * (float(hp_spent_that_round) / float(hp_that_round))
percents.append(percent_spent_that_round)
# We guess that our opponents next bid will be the same % of their current hp as usual, so we bid 1 higher.
mean_percent_spend = sum(percents) / len(percents)
op_hp_now = 100 - sum(history)
op_next_bid = (mean_percent_spend / 100) * op_hp_now
our_bid = op_next_bid + 1
print mean_percent_spend
print op_hp_now
print op_next_bid
# If our opponent is weaker than our predicted bid, just bid their hp + ties
if op_hp_now < our_bid:
return int(op_hp_now + ties)
elif our_bid >= hp:
# If our bid would kill us, we're doomed, throw a hail mary
return int(random.randint(1, hp))
else:
return int(our_bid + ties)
```
[Answer]
# ConsistentBot
Bets the same amount each round. It's not too likely to survive the first rounds, but if it's lucky enough to get to the end, it should still have a reasonable amount of HP left.
```
def consistent(hp, history, ties, alive, start):
if alive == 2:
return hp-1
if 100 % start == 0:
return (100 / start) - 1
else:
return 100 / start
```
[Answer]
## Kickban Bot
This bot simply tries to counter the current leader Mean Kickbot by beating it in round one and playing more aggressively thereafter if recognizing it.
```
def kickban(hp, history, ties, alive, start):
if alive == 2:
return hp-1
if not history:
return 36
if history[0]==35:
somean = 1
else:
somean = 0
return min(mean_kick(hp, history, ties, alive, start) + somean*3, hp-1)
```
[Answer]
# Three Quarter Bot
He's not going to beat MehBot or SarcomaBot(s), but I think he does pretty well. When I first saw the challenge, this was the first thing that popped to my mind, always\* bet three quarters of your health unless there's no reason to.
\*after low-balling the first round.
```
def ThreeQuarterBot(hp, history, ties, alive, start):
threeQuarters = 3 * hp / 4
if alive == 2:
return hp - 1
opponent_hp = 100 - sum(history)
if not history:
# low-ball the first round but higher than (some) other low-ballers
return 32 + ties
elif threeQuarters > opponent_hp:
return opponent_hp + ties
return threeQuarters
```
---
# Four Sevenths Bot
After the moderate success of 3/4 bot there's a new fraction in town, it's only rational.
```
def FourSeventhsBot(hp, history, ties, alive, start):
fourSevenths = 4 * hp / 7
if alive == 2:
return hp - 1
opponent_hp = 100 - sum(history)
if not history:
# low-ball the first round but higher than (some) other low-ballers
return 33 + ties
if fourSevenths > opponent_hp:
return opponent_hp + ties
return fourSevenths + ties
```
# The Perfect Fraction
I am whole
```
def ThePerfectFraction(hp, history, ties, alive, start):
thePerfectFraction = 7 * hp / 13
if alive == 2:
return hp - 1
opponent_hp = 100 - sum(history)
if not history:
# Need to up our game to overcome the kickers
return 42 + ties
if thePerfectFraction > opponent_hp:
return opponent_hp + ties
return thePerfectFraction + 1 + ties
```
[Answer]
## BandaidBot
BandaidBot wants everyone to play nice! If its opponent was nice last round, it will sacrifice itself to incentivize nice behavior in others. If its opponent was mean last round, it will do as much damage as possible to its opponent, sacrificing itself if necessary. It bids a third of its hp if it has no history to work with. (I'm hoping this bot will have interesting ripple effects on other strategies, not so much that this bot will have a high win rate itself. It could be fun to have a couple of these in play)
```
def BandaidBot(hp, history, ties, alive, start):
if alive == 2:
return hp-1
if history:
opp_hp = 100 - sum(history)
opp_last_hp = 100 - sum(history[:-1])
if history[-1] <= opp_last_hp / 3:
return 1 + ties * np.random.randint(0, 1)
elif history[-1] > opp_last_hp / 2:
return min(opp_hp - 1, hp)
else:
if history[-1] < hp/2:
return np.random.randint(history[-1], hp/2)
else:
return np.floor(hp/2)
else:
return np.floor(hp/3)
```
---
## GetAlongBot
GetAlongBot will be just as nice as it needs to be to take advantage of BandaidBot. It will return just under one third of its hp unless it can kill its opponent for less than that. If its opponent looks like BandaidBot, it will bid 2, knowing that BandaidBot will bid 1 because GetAlongBot has been getting along so well with everyone else--an easy win as long as it really was BandaidBot on the other end.
```
def GetAlongBot(hp, history, ties, alive, start):
if alive == 2:
return hp-1
if history:
opp_hp = 100 - sum(history)
opp_last_hp = 100 - sum(history[:-1])
count = 0
for i in range(0, len(history)):
hp_that_round = 100 - sum(history[:i])
hp_spent_that_round = history[i]
if hp_that_round / 3 - 1 <= hp_spent_that_round <= hp_that_round / 2:
count += 1
if count == len(history): #It's probably BandaidBot!
return 2
else:
return min(opp_hp - 1, np.floor(hp/3))
else:
return np.floor(hp/3)
```
[Answer]
# TENacious bot
```
def TENacious_bot(hp, history, ties, alive, start):
max_amount=hp-(alive-1)*2;
if max_amount<2: max_amount=2
if alive==2: return hp-1
if ties==0: return np.minimum(10, max_amount)
if ties==1: return np.minimum(20, max_amount)
if ties==2: return np.minimum(40, max_amount)
# prevent function blowup
return 2
```
This bot tries to hold on its favourite value of 10, but it changes its choice occasionally if needed to break a tie (with its favourite value doubled or quadrupled) or to save for future rounds, but not by optimal amount because it wants to confuse opponents and it does not want to consider bidding less than 2 at any time as it is convinced it is much better than to hope the opponent will bid less than 1, that is, 0.
PS: this bot may have strategic problems if there are more than 2^9 bots.
[Answer]
# CautiousBot
First submission to Programming Puzzles ever! Found your challenge quite interesting :P
If last round bit one less than hp, if no history bet half hp plus a small random amount.
If history check opponent hp and number of remaining rounds and try to outbid opponent hp / 2 using an additional buffer of up to the fraction of remaining hp divided by the number of remaining rounds (it tries to conserve the remaining hp somehow for posterior rounds). Check if your are spending too much hp (do not kill yourself or bid more than your adversary can).
Always correct for ties as other bots do.
```
def cautious_gambler(hp, history, ties, alive, start):
if alive == 2:
return hp - 1
if(history):
opp_hp = 100 - sum(history)
remaining_rounds = np.ceil(np.log2(start)) - len(history)
start_bet = opp_hp / 2
buff = int((hp - start_bet)/remaining_rounds if remaining_rounds > 0 else (hp - start_bet))
buff_bet = np.random.randint(0, buff) if buff > 0 else 0
bet = start_bet + buff_bet + ties
if bet >= hp or bet > opp_hp:
bet = np.minimum(hp - 1, opp_hp)
return int(bet)
else:
start_bet = hp / 2
rng_bet = np.random.randint(3,6)
return int(start_bet + rng_bet + ties)
```
# CautiousBot2
Too much aggressive on first rounds, now CautiousBot gets even more cautious...
```
def cautious_gambler2(hp, history, ties, alive, start):
if alive == 2:
return hp - 1
if(history):
opp_hp = 100 - sum(history)
remaining_rounds = np.ceil(np.log2(start)) - len(history)
start_bet = opp_hp / 2
buff = int((hp - start_bet)/remaining_rounds if remaining_rounds > 0 else (hp - start_bet))
buff_bet = np.random.randint(0, buff) if buff > 0 else 0
bet = start_bet + buff_bet + ties
if bet >= hp or bet > opp_hp:
bet = np.minimum(hp - 1, opp_hp)
return int(bet)
else:
start_bet = hp * 0.35
rng_bet = np.random.randint(3,6)
return int(start_bet + rng_bet + ties)
```
[Answer]
Alright, I'll try my hand at this.
# SnetchBot
Checking the fractions of health that the opponent has been going with. If the opponent has been raising, beat him to it.
```
def snetchBot(hp, history, ties, alive, start):
if alive == 2:
return hp-1
opponent_hp = 100
history_fractions = []
if history:
for i in history:
history_fractions.append(float(i)/opponent_hp)
opponent_hp -= i
if opponent_hp <= hp/2:
#print "Squashing a weakling!"
return opponent_hp + (ties+1)/3
average_fraction = float(sum(history_fractions)) / len(history_fractions)
if history_fractions[-1] < average_fraction:
#print "Opponent not raising, go with average fraction"
next_fraction = average_fraction
else:
#print "Opponent raising!"
next_fraction = 2*history_fractions[-1] - average_fraction
bet = np.ceil(opponent_hp*next_fraction) + 1
else:
#print "First turn, randomish"
bet = np.random.randint(35,55)
if bet > opponent_hp:
bet = opponent_hp + (ties+1)/3
final_result = bet + 3*ties
if bet >= hp:
#print "Too much to bet"
bet = hp-1
return final_result
```
EDIT: losing a lot in the first round, adjusted the first turn random limits
[Answer]
## SquareUpBot
Didn't seem like many bots were playing with powers instead of fractions, so I decided to make one, with some standard optimisations and see where I'll place. Quite simplistic.
Also tries to determine if the enemy bot isn't trying to use some constant fraction, because **powers** > *fractions*.
EDIT: I'm a dummy and my fraction detector could not work. Repaired now.
```
def squareUp(hp, history, ties, alive, start):
#Taken from Geometric Bot
opponentHP = 100 - sum(history)
# Need to add case for 1
if hp == 1:
return 1
# Last of the last - give it your all
if alive == 2:
if ties == 2 or opponentHP < hp-1:
return hp - 1
#Calculate your bet (x^(4/5)) with some variance
myBet = np.maximum(hp - np.power(hp, 4./5), np.power(hp, 4./5))
myBet += np.random.randint(int(-hp * 0.05) or -1, int(hp * 0.05) or 1);
myBet = np.ceil(myBet)
if myBet < 1:
myBet = 1
elif myBet >= hp:
myBet = hp-1
else:
myBet = int(myBet)
#If total annihilation is a better option, dewit
if opponentHP < myBet:
if ties == 2:
return opponentHP + 1
else:
return opponentHP
#If the fraction is proven, then outbid it (Thanks again, Geometric bot)
if history and history[0] != history[-1]:
health = 100
fraction = float(history[0]) / health
for i,x in enumerate(history):
newFraction = float(x) / health
if newFraction + 0.012*i < fraction or newFraction - 0.012*i > fraction:
return myBet
health -= x
return int(np.ceil(opponentHP * fraction)) + 1
else:
return myBet
```
] |
[Question]
[
Given integers `N , P > 1` , find the largest integer `M` such that `P ^ M ≤ N`.
### I/O:
Input is given as 2 integers `N` and `P`. The output will be the integer `M`.
### Examples:
```
4, 5 -> 0
33, 5 -> 2
40, 20 -> 1
242, 3 -> 4
243, 3 -> 5
400, 2 -> 8
1000, 10 -> 3
```
### Notes:
The input will always be valid, i.e. it will always be integers greater than 1.
### Credits:
Credit for the name goes to @cairdcoinheringaahing. The last 3 examples are by @Nitrodon and credit for improving the description goes to @Giuseppe.
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 74 bytes
```
(({}<>)[()])({()<(({})<({([{}]()({}))([{}]({}))}{})>){<>({}[()])}{}>}[()])
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/X0OjutbGTjNaQzNWU6NaQ9MGJAAkqzWiq2tjNTRBPE0IG8SqBRJ2mtU2dkAeWA9QwA7C@v/fSMHEwAAA "Brain-Flak – Try It Online")
This uses the same concept as the standard Brain-Flak positive integer division algorithm.
```
# Push P and P-1 on other stack
(({}<>)[()])
# Count iterations until N reaches zero:
({()<
# While keeping the current value (P-1)*(P^M) on the stack:
(({})<
# Multiply it by P for the next iteration
({([{}]()({}))([{}]({}))}{})
>)
# Subtract 1 from N and this (P-1)*(P^M) until one of these is zero
{<>({}[()])}{}
# If (P-1)*(P^M) became zero, there is a nonzero value below it on the stack
>}
# Subtract 1 from number of iterations
[()])
```
[Answer]
# JavaScript (ES6), 22 bytes
*Saved 8 bytes thanks to @Neil*
Takes input in currying syntax `(p)(n)`.
```
p=>g=n=>p<=n&&1+g(n/p)
```
[Try it online!](https://tio.run/##XclBDkAwEADAu1f0JLsRSkviYP2lQRsi2wbx/SJxYa6zmNPswzaHI2c/TtFSDNQ7YupDR5ymVeaAZcA4eN79OhWrd2ChQdAaUQgphUq@p0qEurzzvup/T73Xxgs "JavaScript (Node.js) – Try It Online")
[Answer]
# Excel, 18 bytes
```
=TRUNC(LOG(A1,A2))
```
Takes input "n" at A1, and input "p" at A2.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
bḊL
```
This doesn't use floating-point arithmetic, so there are no precision issues.
[Try it online!](https://tio.run/##y0rNyan8/z/p4Y4un//FRtZKh5cb6bv//29srKNgqqNgYqCjYGQAokEMIDIBEsYg2hhMm4BVGRqApA0NAA "Jelly – Try It Online")
### How it works
```
bḊL Main link. Left argument: n. Right argument: p
b Convert n to base p.
Ḋ Dequeue; remove the first base-p digit.
L Take the length.
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 35 bytes
```
.+
$*
+r`1*(\2)+¶(1+)$
#$#1$*1¶$2
#
```
[Try it online!](https://tio.run/##K0otycxL/P9fT5tLRYtLuyjBUEsjxkhT@9A2DUNtTRUuZRVlQxUtw0PbVIy4lP//NzbmMgUA "Retina 0.8.2 – Try It Online") Explanation:
```
.+
$*
```
Convert the arguments to unary.
```
+r`1*(\2)+¶(1+)$
#$#1$*1¶$2
```
If the second argument divides the first, replace the first argument with a `#` plus the integer result, discarding the remainder. Repeat this until the first argument is less than the second.
```
#
```
Count the number of times the loop ran.
[Answer]
# Japt, 8 bytes
```
@<Vp°X}a
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=QDxWcLBYfWE=&input=NDAwLDI=)
[Answer]
# [Haskell](https://www.haskell.org/), 30 bytes
```
n!p=until((>n).(p^).(1+))(1+)0
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P0@xwLY0ryQzR0PDLk9TT6MgDkgYamtqggiD/7mJmXm2BUWZeSUqXApVmQXhmSUZGoqa0cbGOiYGQGQQG22qY2SgYxT7HwA "Haskell – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 13 bytes
```
&floor‚àò&log
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJZq@18tLSc/v@hRxwy1nPz0/9ZcxYkgcQ0TAwMdI00419hYx1TzPwA "Perl 6 – Try It Online")
Concatenation composing log and floor, implicitly has 2 arguments because first function log expects 2. Result is a function.
[Answer]
# [C (gcc)](https://gcc.gnu.org/) + `-lm`, 24 bytes
```
f(n,m){n=log(n)/log(m);}
```
[Try it online!](https://tio.run/##S9ZNT07@/z9NI08nV7M6zzYnP10jT1MfROVqWtf@z03MzNPQrC4oyswrSdNQUk1R0knTMDbWMdUEyf5LTstJTC/@r5uTCwA "C (gcc) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 16 bytes
```
(floor.).logBase
```
[Try it online!](https://tio.run/##y0gszk7NyfmfZhvzXyMtJz@/SE9TLyc/3SmxOPV/bmJmnoKtQkFRZl6JgopCmoKpgrHx/3/JaTmJ6cX/dZMLCgA "Haskell – Try It Online")
Haskell was designed by mathematicians so it has a nice set of math-related functions in Prelude.
[Answer]
# [R](https://www.r-project.org/), 25 bytes
```
function(p,n)log(p,n)%/%1
```
[Try it online!](https://tio.run/##K/qfpmCjq/A/rTQvuSQzP0@jQCdPMyc/HUyr6qsa/k/TMDEw0DHS/A8A "R – Try It Online")
Take the log of `P` base `N` and do integer division with `1`, as it's shorter than `floor()`. This suffers a bit from numerical precision, so I present the below answer as well, which should not, apart from possibly integer overflow.
# [R](https://www.r-project.org/), 31 bytes
```
function(p,n)(x=p:0)[n^x<=p][1]
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T6NAJ09To8K2wMpAMzovrsLGtiA22jD2f5qGiYGBjpHmfwA "R – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 39 bytes
```
lambda a,b:math.log(a,b)//1
import math
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSFRJ8kqN7EkQy8nP10DyNHU1zfkyswtyC8qUQCJ/y8oyswr0UjT0MrMKygt0dDU1PxvbKyjYAoA "Python 2 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 31 bytes
OK, so all those log-based approaches are prone to rounding errors, so here is another method that works with integers and is free of those issues:
```
->n,p{(0..n).find{|i|p**i>n}-1}
```
[Try it online!](https://tio.run/##Pcw7CoAwEEXR3lUM2KjEMMlEsNGNiI1IIE0IgoWoa4/5qK888O62L4fXg29Hy9xZIee25trY9bzM5ZrGjPZuxe0d6ImIQTdDWAmyiKKQgcQ5iXglUpY@iVSSAWVRr9AvXX594SCYRGAMidAugfwD "Ruby – Try It Online")
But going back to logarithms, although it is unclear up to what precision we must support the input, but I think this little trick would solve the rounding problem for all more or less "realistic" numbers:
# [Ruby](https://www.ruby-lang.org/), 29 bytes
```
->n,p{Math.log(n+0.1,p).to_i}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5Pp6DaN7EkQy8nP10jT9tAz1CnQFOvJD8@s/Z/gUJatLGxjoJprAIQKCsYcYFETAx0FIwMYsEihlARkBBExAIsYmRipKNgDBExgYoYw0VMIbpgBgNFDMAihgYggwyBZisrGP8HAA "Ruby – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 5 bytes
```
ìV ÊÉ
```
[Try it online!](https://tio.run/##y0osKPn///CaMIXDXYc7//83MTDgMgIA)
---
## 8 bytes
```
N£MlXÃäz
```
[Try it online!](https://tio.run/##y0osKPn/3@/QYt@ciMPNh5dU/f9vYmCgYwQA "Japt – Try It Online")
[Answer]
# [Emojicode](http://www.emojicode.org/), ~~49~~ 48 bytes
```
üçáiüöÇjüöÇ‚û°Ô∏èüöÇüçé‚ûñüêîüî°i j 1üçâ
```
[Try it online!](https://tio.run/##S83Nz8pMzk9J/f9hfn@jwof5ve1cCiBqWVppXvJ/ED/zw/xZTVkg4tG8he939INYQPG@R/OmfZg/YcqH@VMWZipkKRgCxTr/g/TOaFAACYJMWasAMkbB0MDAAEgAERdYFQA "Emojicode – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 2 bytes
```
‚åä‚çü
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RHPV2Peuf//2@qkKZgbMxlZACkTQy4jMCUAQA "APL (Dyalog Unicode) – Try It Online")
Pretty straightforward.
`‚çü` Log
`‚åä` floor
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
```
Lm¹›_O
```
[Try it online!](https://tio.run/##MzBNTDJM/f/fJ/fQzkcNu@L9//83NDAw4DI0AAA "05AB1E – Try It Online")
[Answer]
# [JavaScript](https://nodejs.org), ~~40~~ 33 bytes
*-3 bytes thanks to DanielIndie*
Takes input in currying syntax.
```
a=>b=>(L=Math.log)(a)/L(b)+.001|0
```
[Try it online!](https://tio.run/##Zc5NCoMwEAXgfU/hcoZSM/kRuokn0ENEq/1BjFTpyrunmYKljW/7wXvv4V5ubp/3aTmN/tKF3gZny8aWUNnaLbd88FcEh6KCBo85kVwptH6c/dCxQQ9aIxSIWYwQmTr8qyEERR@OKnfKvOk5UWUUgt7U7FT/aJE2f0@xUqKSeFjyr6g6vAE)
[Answer]
# Pari/GP, 6 bytes
```
logint
```
(built-in added in version 2.7, Mar 2014. Takes two arguments, with an optional third reference which, if present, is set to the base raised to the result)
[Answer]
# Python 2, 3, 46 bytes
*-1 thanks to jonathan*
```
def A(a,b,i=1):
while b**i<=a:i+=1
return~-i
```
## Python 1, 47 bytes
```
def A(a,b,i=1):
while b**i<=a:i=i+1
return~-i
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 22 bytes
```
m=>f=n=>n<m?0:f(n/m)+1
```
[Try it online!](https://tio.run/##LY/BDsIgDIbve4oeAVEZjMQZmQ@ycFjmXDTCzLb4@pOWHUj6/f1o4d39uqWfX9/1GKfHsI1uC655uuiaeAt3dX2yeA78UG7rsKwLOGgLgLaSYCUoL6E1hmqNdaVSkU6JoCstITWrDIbAZg09CReEuq7TBbVPKBX2EI2XuEkLYfWxJN/muZhk1tkxQhhycAc5lGTeHSuEJgffSg4lmbUvfFHQD0@h@zLWRglBwuw5uAb6KS7TZzh9ppGNLHAWU@xg5nz7Aw "JavaScript (Node.js) – Try It Online")
Curried recursive function. Use as `g(P)(N)`. Less prone to floating-point errors than [using `Math.log`](https://codegolf.stackexchange.com/a/162720/78410), and (I believe) the code gives correct values as long as both inputs are safe integers (under `2**52`).
[Answer]
# [Haskell](https://www.haskell.org/), ~~35~~ 34 bytes
```
n!p=last.fst$span((<=n).(p^))[0..]
```
Thanks @Laikoni for saving 1 byte
[Try it online!](https://tio.run/##DcJBCoAgEADAr6zQQUFEtG75jg5i4KFQsmXJPfV5a5iS@3W0NgYKCi13NmfnqVNGKdeAykjalYrWmDTuXBEC0FORYYK30la5gBQKovd6tn@bIC7aWe3S@AA "Haskell – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 5 bytes
```
<.@^.
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/bfQc4vT@a3JxpSZn5CuYKqQpGBtD2EYGQI6JAZQDZhtw/QcA "J – Try It Online")
[Answer]
## Wolfram Language (Mathematica) ~~15~~ 10 Bytes
```
Floor@*Log
```
(requires reversed order on input)
Original submission
```
‚åä#2~Log~#‚åã&
```
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 35 bytes
```
: f swap s>f flog s>f flog f/ f>s ;
```
[Try it online!](https://tio.run/##TcxBCoAgFIThvaf4L1CJ2qbAu0TwbBEYGnR8s0XZ6s3HDE9iOrcuyHNKmRDytRxkL8geQwsyID4zF2thpA571qScBqObNObrjDPYV1TaRuX4vSk3 "Forth (gforth) – Try It Online")
Could save 5 bytes by swapping expected input parameters, but question specifies N must be first (an argument could be made that in a postfix language "First" means top-of-stack, but I'll stick to the letter of the rules for now)
## Explanation
```
swap \ swap the parameters to put N on top of the stack
s>f flog \ move N to the floating-point stack and take the log(10) of N
s>f flog \ move P to the floating-point stack and take the log(10) of P
f/ \ divide log10(N) by log10(P)
f>s \ move the result back to the main (integer) stack, truncating in the process
```
[Answer]
# Pyth, 6 4 bytes
```
s.lF
```
Saved 2 bytes thanks to Mmenomic
[Try it online](http://pyth.herokuapp.com/?code=s.lhQe&input=400%2C+2&debug=1)
## How it works
`.l` is logB(A)
To be honest, I have no idea how `F` works. But if it works, it works.
`s` truncates a float to an int to give us the highest integer for `M`.
[Answer]
# [Wonder](https://github.com/wonderlang/wonder), 9 bytes
```
|_.sS log
```
Example usage:
```
(|_.sS log)[1000 10]
```
# Explanation
Verbose version:
```
floor . sS log
```
This is written pointfree style. `sS` passes list items as arguments to a function (in this case, `log`).
[Answer]
# [Gforth](https://www.gnu.org/software/gforth/), 31 Bytes
```
SWAP S>F FLOG S>F FLOG F/ F>S .
```
## Usage
```
242 3 SWAP S>F FLOG S>F FLOG F/ F>S . 4 OK
```
[Try it online!](https://tio.run/##S8svKsnQTU8DUf@NTIwUjP8HhzsGKATbuSm4@fi7Ixhu@gpudsEKev@BAAA "Forth (gforth) – Try It Online")
## Explanation
Unfortunately FORTH uses a dedicated floating-point-stack. For that i have to `SWAP` (exchange) the input values so they get to the floating point stack in the right order. I also have to move the values to that stack with `S>F`. When moving the floating-point result back to integer (`F>S`) I have the benefit to get the truncation for free.
## Shorter version
Stretching the requirements and provide the input in float-format and the right order, there is a shorter version with 24 bytes.
```
FLOG FSWAP FLOG F/ F>S .
3e0 242e0 FLOG FSWAP FLOG F/ F>S . 4 OK
```
[Try it online!](https://tio.run/##S8svKsnQTU8DUf@NUw0UjEyMUg3@u/n4uyu4BYc7BihAmPoKbnbBCnr/gQAA "Forth (gforth) – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~8~~ ~~7~~ 4 bytes
```
Lt`B
```
[Try it online!](https://tio.run/##yygtzv6fe2h5arFGsdujpsb/PiUJTv///4/WMDbWMdXU0TAx0DEyANNABpA2MjHSMQbTxmDaBKzK0AAobWigGQsA "Husk – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 61 bytes
```
i(n,t,l,o,g){for(l=g=0;!g++;g=g>n)for(o=++l;o--;g*=t);g=--l;}
```
[Try it online!](https://tio.run/##RczJboMwFAXQdfMVN1RINhjJGNPJcvMTWXYTMViWwKDALsq3U5uhXTw9v2PdW2WmqpbFEsdm1rGBGfpohzvptNFcnU2aKqPNt6MBB52mnRqyTJlEz9T/ZFmnnstr3bTWNbj6FowMPcV4t25uSWRJLGuGWNQUOizoy7pIPNEfFzFsEbtGqc/@vaE1elwQjbdpauoIX4gSN8wJdqDq1N@sI/RxerkSoCgYUPoRdAPJGYQf5BtIHg7h52MDIcMRYvKAYody74DcS/kKOQ8deegpVpD8s9xK8/yAtx3EAe//8Fx@AQ "C (gcc) – Try It Online")
] |
[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]
[
As I'm applying for some jobs whose job advert doesn't state the salary, I imagined a particularly evil interviewer that would give the candidate the possibility to decide their own salary ...by "golfing" it!
So it goes simply like that:
>
> Without using numbers, write a code that outputs the annual salary you'd like to be offered.
>
>
>
However, being able to write concise code is a cornerstone of this company. So they have implemented a very tight seniority ladder where
>
> employers that write code that is *b* bytes long can earn a maximum of ($1'000'000) · *b*-0.75.
>
>
>
we are looking at (these are the integer parts, just for display reasons):
```
1 byte ‚Üí $1'000'000 15 bytes ‚Üí $131'199
2 bytes ‚Üí $594'603 20 bytes ‚Üí $105'737
3 bytes ‚Üí $438'691 30 bytes ‚Üí $78'011
4 bytes ‚Üí $353'553 40 bytes ‚Üí $62'871
10 bytes ‚Üí $177'827 50 bytes ‚Üí $53'182
```
### The challenge
Write a program or function that takes no input and outputs a text containing a dollar sign (`$`, U+0024) and a decimal representation of a number (integer or real).
* Your code cannot contain the characters `0123456789`.
In the output:
* There may optionally be a single space between the dollar sign and the number.
* Trailing and leading white spaces and new lines are acceptable, but any other output is forbidden.
* The number must be expressed as a decimal number using only the characters `0123456789.`. This excludes the use of scientific notation.
* Any number of decimal places are allowed.
**An entry is valid if** the value it outputs is not greater than ($1'000'000) · *b*-0.75, where *b* is the byte length of the source code.
### Example output (the quotes should not be output)
```
"$ 428000" good if code is not longer than 3 bytes
"$321023.32" good if code is not longer than 4 bytes
" $ 22155.0" good if code is not longer than 160 bytes
"$ 92367.15 \n" good if code is not longer than 23 bytes
"300000 $" bad
" lorem $ 550612.89" bad
"£109824" bad
"$ -273256.21" bad
"$2.448E5" bad
```
### The score
The value you output is your score! (Highest salary wins, of course.)
---
## Leaderboard
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
# Language Name, $X (Y bytes)
```
where `X` is your salary and `Y` is the size of your submission. (The `Y bytes` can be anywhere in your answer.) If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
# Ruby, <s>$111111.111... (18 bytes)</s> <s>$111999 (17 bytes)</s> $123456 (16 bytes)
```
You can also make the language name a link, which will then show up in the leaderboard snippet:
```
# [><>](http://esolangs.org/wiki/Fish), $126,126 (13 bytes)
```
```
var QUESTION_ID=171168,OVERRIDE_USER=77736;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body.replace(/<(s|strike)>.*?<\/\1>/g,"");s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a1=r.match(SCORE_REG),a2=r.match(LANG_REG),a3=r.match(BYTES_REG);a1&&a2&&e.push({user:getAuthorName(s),size:a3?+a3[1]:0,score:+a1[1].replace(/[^\d.]/g,""),lang:a2[1],rawlang:(/<a/.test(a2[1])?jQuery(a2[1]).text():a2[1]).toLowerCase(),link:s.share_link})}),e.sort(function(e,s){var r=e.score,a=s.score;return a-r});var s={},r=1,a=null,n=1;e.forEach(function(e){e.score!=a&&(n=r),a=e.score,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.lang).replace("{{SCORE}}","$"+e.score.toFixed(2)).replace("{{SIZE}}",e.size||"?").replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);s[e.rawlang]=s[e.rawlang]||e});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){var r=e.rawlang,a=s.rawlang;return r>a?1:r<a?-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("{{SCORE}}","$"+o.score.toFixed(2)).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 LANG_REG=/<h\d>\s*((?:[^\n,](?!\s*\(?\d+\s*bytes))*[^\s,:-])/,BYTES_REG=/(\d+)\s*(?:<a[^>]+>|<\/a>)?\s*bytes/i,SCORE_REG=/\$\s*([\d',]+\.?\d*)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:520px;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>Score</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><td>Size</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>{{SCORE}}</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>{{SCORE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```
---
Edit: (rounded) maximum allowed score per byte count, for a quicker reference - [text here](https://tio.run/##HcFBCoAgEADAryySsIqKi0jRob8EZe1FQ7z0@g2aed5xt5pESuvAwBX6Xq8TyVEmsz6d60Cl0wHebzBpWgLFojSyo/izbC36GOZsjBH5AA):
[![enter image description here](https://i.stack.imgur.com/HpQNN.png)](https://i.stack.imgur.com/HpQNN.png)
[Answer]
# bash, $127127
```
x;echo \$$?$?
```
[Try it online!](https://tio.run/##S0oszvj/v8I6NTkjXyFGRcVexf7/fwA)
Since the `x` command doesn't exist, it errors and sets the exit code to `127`.
Then, the code outputs a dollar sign followed by `$?` twice. The `$?` variable stores the exit code of the previous command, so this outputs `$127127` in **13 bytes**.
[Answer]
# Java 8, $131,199.00 (15 bytes)
```
v->"$"+'e'*'‘ì'
```
[Try it online.](https://tio.run/##LY1BCsIwEEX3PcVQhKRKe4GiN7AbwY24GNMoqem0NJOASE/h1bxPTLGbD/Pn8V@HAcuufUZl0Tk4oqF3BmCI9XRHpaFZToATT4YeoOR5MC2Eok7tnKVwjGwUNECwhxjKQ77Jd0KLrfh@RKwXZPQ3m5CVDMtAnzzyv3m5Ahar5OVY99XguRrTiy1JqpQkb22xGuf4Aw)
**Explanation:**
```
v-> // Method with empty unused parameter and String return-type
"$"+ // Return a dollar sign, concatted with:
'e'*'‘ì' // 131199 (101 * 1299)
```
\$131,199.00 < 131,199.31\$
I used [a program to generate](https://tio.run/##XZBba4NAEIXf/RXDkuJa0bINFIJNIL28NU@hpVBL2aqJk3oJOgqh@NvtbmLU9GV3Z77DOTO7k7V0duFP2waJLEtYScx@DYB99Z1gACVJUledYwipQnxNBWbbj0@QlpYBBLEsQJYB4qN@zcEE0xtIWiWEDweKxvSIw1xFRECy2EakiJgKMZuF3himmCnydCzc1fL962358vp8kmzygmNGgHNxe@cBLqZCnY7TzdV7BLGy6FJuAL1LWstEYaW5AnFGuOG6fa/jezfohlHE61vjvbne18IB/l/9JAjis6IxhnN9KClK3bwid68@mJKMs9pZ@GziM9tkdh9kM1PXF96q55NPfMJs3guvLySWzSxm6eTGaNr2Dw) a printable ASCII character in the range `[32, 126]` which, when dividing `131199`, would have the lowest amount of decimal values. Since `101` can divide `131199` evenly, resulting in `1299`, I'm only 31 cents short of my maximum possible salary based on my byte-count of 15.
[Answer]
# [CJam](https://sourceforge.net/p/cjam), (5 bytes) $294204.018...
```
'$PB#
```
[Try it online!](https://tio.run/##S85KzP3/X10lwEn5/38A "CJam – Try It Online")
Explanation:
I derived it from Dennis' answer, but looked for combinations of numbers which would yield a higher result. I almost gave up, but I saw that `P` is the variable for \$\pi\$, and that \$\pi^{11} \approx 294000\$. The letter `B` has a value of 11 in CJam, giving the code above.
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 5 bytes, $262'144
```
'$YI#
```
[Try it online!](https://tio.run/##S85KzP3/X10l0lP5/38A "CJam – Try It Online")
### How it works
```
'$ Push '$'.
Y Push 2.
I Push 18.
# Pop 2 and 18 and perform exponentiation, pushing 262144.
```
[Answer]
# [R](https://www.r-project.org/), 20 bytes, `$103540.9`
```
T=pi+pi;cat("$",T^T)
```
[Try it online!](https://tio.run/##K/pvmGqmZWQQp6tnbvo/xLYgU7sg0zo5sURDSUVJJyQuRPP/fwA "R – Try It Online")
The max for 20 bytes is `$105737.1`, so this is quite close to the salary cap!
This would be a nice raise, and if I get paid to do code golf......
[Answer]
# [GS2](https://github.com/nooodl/gs2), (5 bytes) $292,929
```
•$☺↔A
```
A full program (shown here using [code-page 437](https://en.wikipedia.org/wiki/Code_page_437#Character_set)). (Maximum achievable salary @ 5 bytes is $299069.75)
**[Try it online!](https://tio.run/##Sy82@v//UcMilUczdj1qm@L4/z8A "GS2 – Try It Online")**
Builds upon Dennis's [GS2 answer](https://codegolf.stackexchange.com/a/171179/53748)...
```
•$☺↔A []
•$ - push '$' ['$']
‚ò∫ - push unsigned byte:
‚Üî - 0x1d = 29 ['$',29]
A - push top of stack twice ['$',29,29,29]
- implicit print $292929
```
[Answer]
# [Self-modifying Brainfuck](https://soulsphere.org/hacks/smbf/), 16 bytes, $124444
```
<.<++.+.++..../$
```
[Try it online!](https://tio.run/##K85NSvv/30bPRltbDwi19YBAX@X/fwA "Self-modifying Brainfuck – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 21 bytes $99649.9
```
cat("$",min(lynx^pi))
```
[Try it online!](https://tio.run/##K/qfnJSZl6JhaGFlZKxjmGqmBWFqxunqmZtq/k9OLNFQUlHSyc3M08ipzKuIK8jU1Pz/HwA "R – Try It Online")
A different `R` approach - see also [Giuseppe's answer](https://codegolf.stackexchange.com/a/171171/80010)
Very close to the maximum of $101937 for this bytecount.
## Bonus: `object.size()`
### [R](https://www.r-project.org/), 24 bytes $89096
```
cat("$",object.size(ls))
```
[Try it online!](https://tio.run/##K/qfnJSZl6JhaGFlZKpjmGqmBWFqxunqmZtq/k9OLNFQUlHSyU/KSk0u0SvOrErVyCnW1Pz/HwA "R – Try It Online")
This is probably system-dependent, but when I ra this on TIO I got $89096 - close to the limit of 92223 for 24 bytes.
[Answer]
# JavaScript (ES6), 19 bytes, $109,839
```
_=>atob`JDEwOTgzOQ`
```
[Try it online!](https://tio.run/##FcwxDoIwFADQnVP8rW3Ushi3MhhdHCRGdym1hZLaT9oCwcsj7C@vk6OMKtg@HTx@9GLE8haFTFhXt8t1Kl/Nr3xUS55Dj2421jkwGIBsgjKyh6m1qgUbwWMCCV4mO2q4rxfvIpjBq2TRZ5sHARFEAefBGB24CfilEXZA1obUMurTkTCe8JmC9Q0ltfUyzIRlmUIf0WnusKGGMrb8AQ "JavaScript (Node.js) – Try It Online")
\$109839\$ is the highest integer \$\le 109884\$ which does not produce any digit when prefixed with **'$'** and encoded in base64.
---
# Without `atob()` (Node.js), 26 bytes, $86,126
```
_=>'$'+Buffer('V~').join``
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/e1k5dRV3bqTQtLbVIQz2sTl1TLys/My8h4X9yfl5xfk6qXk5@ukaahqbmfwA "JavaScript (Node.js) – Try It Online")
The concatenation of **'$'** with the ASCII codes of **'V'** (86) and **'~'** (126).
[Answer]
# PHP, $131116 (8 bytes)
Didn't see one for php and wanted to throw one up. I know someplace in php is a bad typecast that would cut this in half but I can't find it right now.
```
$<?=ERA;
```
This just takes advantage of PHP short tags and the PHP built in constants.
**[Try it online!](https://tio.run/##K8go@P9fxcbe1jXI0fr/fwA)**
[Answer]
# [GS2](https://github.com/nooodl/gs2), 5 bytes, $291'000
```
•$☺↔∟
```
This is a [CP437](https://en.wikipedia.org/wiki/Code_page_437#Character_set) representation of the binary source code.
[Try it online!](https://tio.run/##Sy82@v//UcMilUczdj1qm/KoY/7//wA "GS2 – Try It Online")
### How it works
```
•$ Push '$'.
☺↔ Push 29.
‚àü Push 1000.
```
[Answer]
## Excel 19 bytes $107899.616068361
```
="$"&CODE("(")^PI()
```
**Explanation:**
```
CODE("(") // find ASCII code of ( which is 40
^PI() // raise to power of Pi (40^3.141592654)
"$"& // append $ to the front of it
= // set it to the cell value and display
```
[Answer]
## vim, ~~$99999~~ ~~$110000~~ $120000
```
i$=&pvh*&ur
```
[Try it online!](https://tio.run/##K/v/P1NFyFatoCxDS620iOv/fwA)
Uses the expression register (note that there is a <C-r> character, which is invisible in most fonts, between the `$` and `=`, for a total of **13 bytes**) to insert the value of the `'pvh'` option times the value of the `'ur'` option.
`'previewheight'` is the option that controls the height of preview windows, which is 12 by default.
`'undoreload'` is the maximum number of lines a buffer can have before vim gives up on storing it in memory for undo, and it defaults to 10,000.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~$256000 $256256~~ (6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)) $257256
```
⁹‘”$;;
```
A full program. (Maximum achievable salary @ 6 bytes is $260847.43)
**[Try it online!](https://tio.run/##y0rNyan8//9R485HDTMeNcxVsbb@/x8A "Jelly – Try It Online")**
### How?
```
⁹‘”$;; - Main Link: no arguments
‚Åπ - Literal 256 256
‘ - increment 257
”$ - single '$' character '$'
; - concatenate ['$',257]
; - concatenate ['$',257,256]
- implicit print -> $257256
```
---
Previous...
5 bytes $256256
```
”$;⁹⁺
```
('$' concatenate 256, repeat 256 - causing interim implicit printing)
6 bytes $256000:
```
⁹×ȷṭ”$
```
(256 √ó 1000 ·π≠ack '$')
[Answer]
# C#
## Full program, ~~72 bytes, $40448~~ 66 bytes, $43008
```
class P{static void Main()=>System.Console.Write("$"+('T'<<'i'));}
```
[Try it online!](https://tio.run/##Sy7WTc4vSv3/PzknsbhYIaC6uCSxJDNZoSw/M0XBNzEzT0PT1i64srgkNVfPOT@vOD8nVS@8KLMkVUNJRUlbQz1E3cZGPVNdU9O69v9/AA "C# (.NET Core) – Try It Online")
### Explanation
Left-shift operator treats chars `'T'` and `'i'` as integers 84 and 105 respectively and performs shift
## Lambda, ~~19 bytes, $109568~~ 17 bytes, $118784
```
o=>"$"+('t'<<'j')
```
[Try it online!](https://tio.run/##JcpLCsIwEADQq4QiJMHPBZJ2I7gTCi5chzHISJyBzEQopWePgqu3eSBH4Jp7E6SnuS2i@R2gJBEzr6JJEcyH8WGuCcn59dIIomj97YP5O6Wx8zgNu2HvrNoY7cv6Hs5MwiWf7hU1u@SoleJ92Lb@BQ "C# (.NET Core) – Try It Online")
**Edit** Thanks to @LegionMammal978 and @Kevin for saving 2 bytes
[Answer]
# PHP, 13 Bytes, $144000 Salary
Unfortunately for this job, moving to Mauritius is required (well, I could move slightly less far eastward, however every timezone less would yield at $36k drop in salary.) To compensate for the inconvenience, my salary increases by $1 every leap year.
```
$<?=date(ZL);
```
This just puts out `Z` the timezone in seconds and appends whether or not it's a leap year.
[Answer]
# [brainfuck](https://esolangs.org/wiki/Brainfuck), 43 bytes, $58888
```
++++++[>++++++<-]>.<++++[>++++<-]>+.+++....
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fGwyi7SC0jW6snZ4NQgTE19YDMvSA4P9/AA "brainfuck – Try It Online")
### How it works
```
++++++[>++++++<-]>. write 36 to cell one and print (36 is ASCII for $)
<++++[>++++<-]>+. add 17 to cell 1 and print (cell 1 is now 53, ASCII for 5)
+++.... add 3 to cell 1 and print 4 times (cell 1 is now 56, ASCII for 8)
```
[Answer]
# [Python 3](https://docs.python.org/3/), (22 bytes) $ 98,442
```
print('$',ord('òÇä'))
```
**[Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EQ11FXSe/KEVD/cOMpi51Tc3//wE "Python 3 – Try It Online")**
Much like Doorknob's [Ruby answer](https://codegolf.stackexchange.com/a/171180/53748), the 4 byte Unicode character used here, `òÇä`, has an ordinal value of the maximal integer salary achievable in 22 bytes.
Note that `print()` prints its unnamed arguments separated by spaces by default (`sep` is an optional named argument).
[Answer]
# [Gol><>](https://github.com/Sp3000/Golfish), $207680 in 8 bytes
```
'o**n; $
```
[Try it online!](https://tio.run/##S8/PScsszvj/Xz1fSyvPWkHl/38A "Gol><> – Try It Online")
### How it works:
```
' Start string interpretation. Pushes the ASCII value of every character until it wraps back around to this character
o Output the top stack value as ASCII. This is the $ at the end of the code
** Multiply the top 3 stack values (This is the ASCII of 'n; ', 110*59*32
n Output top of stack as integer.
; Terminate program
$ (Not run, used for printing the $)
```
Interestingly enough, you can use `h` instead of `n;`, which yields `'o**h5$` with a score of $231504, but you can't use 0-9, and there isn't another 1-byte way to push 53, the ASCII value of `5`
[Answer]
# Mathematica, 18 bytes, $107,163.49
```
$~Print~N[E^(E!E)]
```
Full program; run using `MathematicaScipt -script`. Outputs `$107163.4882807548` followed by a trailing newline. I have verified that this is the highest-scoring solution of the form `$~Print~N[*expr*]` where `*expr*` is comprised of `Pi`, `E`, `I`, and `+-* /()!`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E) (5 bytes), $262626
```
'$₂ÐJ
```
[Try it online!](https://tio.run/##yy9OTMpM/f9fXeVRU9PhCV7//wMA "05AB1E – Try It Online")
\$262626 < 299069\$. Pushes the character `$` to the stack, then pushes the integer \$26\$. From here, the program triplicates the integer, leaving the stack as `["$", 26, 26, 26]` and joins (`J`) the stack.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 23 bytes, $65535
```
_=>"$"+ +(~~[]+`xFFFF`)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/e1k5JRUlbQVujri46Vjuhwg0IEjT/Wyfn5xXn56Tq5eSna6RpaOooGKaaaWkoKWmnaerlpOall2RoaenqmZtq/gcA "JavaScript (Node.js) – Try It Online")
This is the best I can get without `atob`, though there is a large improvement space tbh
You know, having no short character to ascii conversion function sucks A LOT.
***AFTER A WHOLE DAY***
# [JavaScript (Node.js)](https://nodejs.org), 30 bytes, $78011
```
_=>"$"+`ìǪ`.codePointAt(![])
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/e1k5JRUk74cPkpt0JeslA0YD8zLwSxxINxehYzf/J@XnF@Tmpejn56RppGpqa/wE "JavaScript (Node.js) – Try It Online")
## or: 29 bytes, $80020
```
_=>"$"+`򀀠`.codePointAt(!_)
```
Where `򀀠` is `U+13894 INVALID CHARACTER`
Oh `String.codePointAt`! I've just completely forgotten this!
## A joke one (15B, $130000), not vaild at all but just for fun
```
_=>"$十三萬"
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes, $210176.48625619375
```
⁽½"×½”$,
```
3535 (`‚ÅΩ¬Ω"`) multipli(`√ó`)ed by its sqrt (`¬Ω`).
[Try it online!](https://tio.run/##y0rNyan8//9R495De5UOTz@091HDXBWd//8B "Jelly – Try It Online")
[Answer]
# Perl 5.26.2, 12 bytes, $146002
```
say$]^"\x11\x0e\x01\x06"
```
Hex escapes only shown because ASCII control chars are filtered out.
[Try it online!](https://tio.run/##K0gtyjH9/784sVIlNk5dkI@RTf3//3/5BSWZ@XnF/3V9TfUMDA0A "Perl 5 – Try It Online")
You can get a bit more with different Perl versions, for example $155012 with 5.25.12.
[Answer]
## MATLAB, 17 bytes, $112222
```
['$','..////'+pi]
```
Old answer:
```
['$','RRUUTR'-'!']
```
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 34 bytes, $69999
```
+[->-[---<]>-]>.[-->+++<]>.+++....
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fO1rXTjdaV1fXJtZON9ZOD8i009bWBvL0gJQeEPz/DwA "brainfuck – Try It Online")
### Explanation:
```
+[->-[---<]>-]>. Generate and print 36 ($)
[-->+++<]> Divide by 2 and multiply by 3 to get 54 (6)
. Print 6
+++.... Print 9999
```
[Answer]
## Ruby, $119443
```
$><<?$<<?ùäì.ord
```
[Try it online!](https://tio.run/##KypNqvz/X8XOxsZeBYg/zO2arJdflPL/PwA)
The maximum integer output for 17 bytes. The Unicode character is U+1D293, which is 119443 in hex.
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), $353535 (4 bytes)
```
'$W‚àô
```
[Try it online!](https://tio.run/##y00syUjPz0n7/19dJfxRx8z//wE "MathGolf – Try It Online")
## Explanation
```
'$ Push "$"
W Push 35
‚àô Triplicate top of stack
```
## Disclaimer
This language was created after the posting of this question. While the language is a general language, it is designed with numerical questions in mind. It contains a lot of 1-byte number literals, and other nifty things for number-related questions. It is still a work in progress.
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), $169169 10 bytes
```
Dd*d[$]nnn
```
[Try it online!](https://tio.run/##S0n@/98lRSslWiU2Ly/v/38A "dc – Try It Online")
This prints 13 (`D`) squared, twice
[Answer]
# Japt, 5 bytes, $262144
```
'$+I³
```
[Test it](https://ethproductions.github.io/japt/?v=1.4.6&code=JyQrSbM=)
---
Explanation
`I` is the Japt constant for `64`, `³` cubes it and then `'$+` concatenates that with the dollar symbol.
] |
[Question]
[
Background: the Ramsey number \$R(r,s)\$ gives the minimum number of vertices \$v\$ in the complete graph \$K\_v\$ such that a red/blue edge coloring of \$K\_v\$ has at least one red \$K\_r\$ or one blue \$K\_s\$. Bounds for larger \$r, s\$ are very difficult to establish.
Your task is to output the number \$R(r,s)\$ for \$1 \le r,s \le 5\$.
## Input
Two integers \$r, s\$ with \$1 \le r \le 5\$ and \$1 \le s \le 5 \$.
## Output
\$R(r,s)\$ as given in this table:
```
s 1 2 3 4 5
r +--------------------------
1 | 1 1 1 1 1
2 | 1 2 3 4 5
3 | 1 3 6 9 14
4 | 1 4 9 18 25
5 | 1 5 14 25 43-48
```
Note that \$r\$ and \$s\$ are interchangeable: \$R(r,s) = R(s,r)\$.
For \$R(5,5)\$ you may output any integer between \$43\$ and \$48\$, inclusive. At the time of this question being posted these are the best known bounds.
[Answer]
# JavaScript (ES6), ~~51~~ 49 bytes
Takes input in currying syntax `(r)(s)`.
```
r=>s=>--r*--s+[9,1,,13,2,,3,27,6][r<2|s<2||r*s%9]
```
[Try it online!](https://tio.run/##HYjdCoIwHEfvfYr/TbDZb8K0D6S2FxkjhmkY5mSLUPDdl3VxDofzdB8Xm9BPbzH6e5s6lYLSUWkhQi5E3JsaEpAVSmDTGSdrwrVc48Ya8rirbWr8GP3QFoN/sIzISFAJqkAH0NEWLzcxNoNuIMdJaXL/tfyyYzNnC@c845f0BQ "JavaScript (Node.js) – Try It Online")
### How?
As a first approximation, we use the formula:
$$(r-1)(s-1)$$
```
0 0 0 0 0
0 1 2 3 4
0 2 4 6 8
0 3 6 9 12
0 4 8 12 16
```
If we have \$\min(r,s)<3\$, we simply add \$1\$:
```
1 1 1 1 1
1 2 3 4 5
1 3 - - -
1 4 - - -
1 5 - - -
```
Otherwise, we add a value picked from a lookup table whose key \$k\$ is defined by:
$$k=(r-1)(s-1)\bmod9$$
```
k: table[k]: (r-1)(s-1): output:
- - - - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - -
- - 4 6 8 --> - - 2 3 6 + - - 4 6 8 = - - 6 9 14
- - 6 0 3 - - 3 9 13 - - 6 9 12 - - 9 18 25
- - 8 3 7 - - 6 13 27 - - 8 12 16 - - 14 25 43
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~56~~ 55 bytes
```
f=(x,y)=>x<2|y<2||f(x,y-1)+f(x-1,y)-(x*y==12)-7*(x+y>8)
```
[Try it online!](https://tio.run/##NY3hCsIwDIRfJ1mbQAdDQTvwOUQkzE2UuY5OpIW9e5f98OAgd4Hv3vKTpYuv@UtTePSlDB6SzejbdK7XrF6HvSCHRg9y@iNIVfbe1UiHCpLJ7RFLF6YljD2P4QlXZr7EKBkavPFHZoC7TVaUKv@4TyjQKNA4VJ3KBg "JavaScript (Node.js) – Try It Online") I noticed that the table resembles Pascal's triangle but with correction factors. Edit: Saved 1 byte thanks to @sundar.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~17~~ 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
’ScḢƊ_:¥9“ ı?0‘y
```
**[Try it online!](https://tio.run/##y0rNyan8//9Rw8zg5Ic7Fh3rirc6tNTyUcMchSMb7Q0eNcwASv6PNtUxiQUA "Jelly – Try It Online")** Or see a [test-suite](https://tio.run/##y0rNyan8//9Rw8zg5Ic7Fh3rirc6tNTyUcMchSMb7Q0eNcyo/G8aZH24/dDSw/sSwh41rQEi9/8A "Jelly – Try It Online").
Replace the `0` with `+`, `,`, `-`, `.`, or `/` to set \$R(5,5)\$ equal to \$43\$, \$44\$, \$45\$, \$46\$, or \$47\$ respectively (rather than the \$48\$ here).
### How?
Since \$R(r,s)\leq R(r-1,s)+R(r,s-1)\$ we may find that:
$$R(r,s)\leq \binom{r+s-2}{r-1}$$
This is `’ScḢƊ` and would produce:
```
1 1 1 1 1
1 2 3 4 5
1 3 6 10 15
1 4 10 20 35
1 5 15 35 70
```
If we subtract one for each time nine goes into the result we align three more with our goal (this is achieved with `_:¥9`):
```
1 1 1 1 1
1 2 3 4 5
1 3 6 9 14
1 4 9 18 32
1 5 14 32 63
```
The remaining two incorrect values, \$32\$ and \$63\$ may then be translated using Jelly's `y` atom and code-page indices with `“ ı?0‘y`.
```
’ScḢƊ_:¥9“ ı?0‘y - Link: list of integers [r, s]
’ - decrement [r-1, s-1]
Ɗ - last 3 links as a monad i.e. f([r-1, s-1]):
S - sum r-1+s-1 = r+s-2
Ḣ - head r-1
c - binomial r+s-2 choose r-1
9 - literal nine
¥ - last 2 links as a dyad i.e. f(r+s-2 choose r-1, 9):
: - integer division (r+s-2 choose r-1)//9
_ - subtract (r+s-2 choose r-1)-((r+s-2 choose r-1)//9)
“ ı?0‘ - code-page index list [32,25,63,48]
y - translate change 32->25 and 63->48
```
[Answer]
# [Python 2](https://docs.python.org/2/), 62 bytes
```
def f(c):M=max(c);u=M<5;print[48,25-u*7,3*M+~u-u,M,1][-min(c)]
```
[Try it online!](https://tio.run/##K6gsycjPM/r/PyU1TSFNI1nTytc2N7ECyLAutfW1MbUuKMrMK4k2sdAxMtUt1TLXMdby1a4r1S3V8dUxjI3Wzc3MA6qN/Z@WX6RQpJCZp1CUmJeeqmGoo2CmacXFCRIuRggXQYU5waYqALnFOgpKtnZKOgrWQNuji3SKYzX/AwA "Python 2 – Try It Online")
---
### [Python 2](https://docs.python.org/2/), 63 bytes
```
def f(c):M=max(c);print[48,M%2*7+18,3*~-M+2*(M>4),M,1][-min(c)]
```
[Try it online!](https://tio.run/##K6gsycjPM/r/PyU1TSFNI1nTytc2N7ECyLAuKMrMK4k2sdDxVTXSMtc2tNAx1qrT9dU20tLwtTPR1PHVMYyN1s3NzAMqjv2fll@kUKSQmadQlJiXnqphqKNgpmnFxQkSLkYIF0GFOcGGKwC5xToKSrZ2SjoK1kDro4t0imM1/wMA "Python 2 – Try It Online")
This is ridiculous, I will soon regret having posted this... But eh, ¯\\_(ツ)\_/¯. Shaved off 1 byte thanks to our kind [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan) :). Will probably be outgolfed by about 20 bytes shortly though...
[Answer]
# [Julia 0.6](http://julialang.org/), ~~71~~ ~~61~~ ~~59~~ 57 bytes
```
A->((r,s)=sort(A);r<3?s^~-r:3r+(s^2-4s+3)*((r==s)+r-2)-3)
```
[Try it online!](https://tio.run/##LcoxDoMwDEbhq3i0CR5KSgcgIM6BQOoSKagC9JuuvXpg6Pb06a3fT3q/cqRAedSeGaVJsB0nj9Ki84MtP0Xj4diWSp/mvBT3FoKJg1aiXvKBtJ08RZ5Qks1CcQeB0kaPpr7lX7PkCw "Julia 0.6 – Try It Online")
### Ungolfed (well, a bit more readable):
```
function f_(A)
(r, s) = sort(A)
if r < 3
result = s^(r-1)
else
result = 3*r +
(s^2 - 4*s + 3) * ((r == s) + r - 2) -
3
end
return result
end
```
### What does it do?
Takes input as array `A` containing r and s. Unpacks the array into r and s with the smaller number as r, using `(r,s)=sort(A)`.
If r is 1, output should be 1. If r is 2, output should be whatever s is.
\$ s^{r - 1} \$ will be \$ s^0 = 1 \$ for r=1, and \$ s^1 = s \$ for r = 2.
So, `r<3?s^(r-1)` or shorter, `r<3?s^~-r`
For the others, I started with noticing that the output is:
* for r = 3, \$ 2\times3 + [0, 3, 8] \$ (for s = 3, 4, 5 respectively).
* for r = 4, \$ 2\times4 + \ \ [10, 17] \$ (for s = 4, 5 respectively)
* for r = 5, \$ 2\times5 + \ \ \ \ \ [35] \$ (for s = 5)
(I initially worked with f(5,5)=45 for convenience.)
This looked like a potentially usable pattern - they all have `2r` in common, 17 is 8\*2+1, 35 is 17\*2+1, 10 is 3\*3+1. I started with extracting the base value from [0, 3, 8], as `[0 3 8][s-2]` (this later became the shorter `(s^2-4s+3)`).
Attempting to get correct values for r = 3, 4, and 5 with this went through many stages, including
```
2r+[0 3 8][s-2]*(r>3?3-s+r:1)+(r-3)^3+(r>4?1:0)
```
and
```
2r+(v=[0 3 8][s-2])+(r-3)*(v+1)+(r==s)v
```
Expanding the latter and simplifying it led to the posted code.
[Answer]
# x86, ~~49~~ 37 bytes
Not very optimized, just exploiting the properties of the first three rows of the table. While I was writing this I realized the code is basically a jump table so a jump table could save many bytes. Input in `eax` and `ebx`, output in `eax`.
-12 by combining cases of `r >= 3` into a lookup table (originally just `r >= 4`) and using Peter Cordes's suggestion of `cmp`/`jae`/`jne` with the flags still set so that `r1,r2,r3` are distinguished by only one `cmp`! Also indexing into the table smartly using a constant offset.
```
start:
cmp %ebx, %eax
jbe r1
xchg %eax, %ebx # ensure r <= s
r1:
cmp $2, %al
jae r2 # if r == 1: ret r
ret
r2:
jne r3 # if r == 2: ret s
mov %ebx, %eax
ret
r3:
mov table-6(%ebx,%eax),%al # use r+s-6 as index
sub %al, %bl # temp = s - table_val
cmp $-10, %bl # equal if s == 4, table_val == 14
jne exit
add $4, %al # ret 18 instead of 14
exit:
ret
table:
.byte 6, 9, 14, 25, 43
```
Hexdump
```
00000507 39 d8 76 01 93 3c 02 73 01 c3 75 03 89 d8 c3 8a |9.v..<.s..u.....|
00000517 84 03 21 05 00 00 28 c3 80 fb f6 75 02 04 04 c3 |..!...(....u....|
00000527 06 09 0e 19 2b |....+|
```
[Answer]
# [Python 2](https://docs.python.org/2/), 70 bytes
```
f=lambda R,S:R<=S and[1,S,[6,9,14][S-3],[18,25][S&1],45][R-1]or f(S,R)
```
[Try it online!](https://tio.run/##VcuxDsIgFEDRWb/iTRaS1ya0tdHG/gSMhKSYitIoNICDX484up073O2THt61OZvpqV/XRQNHMfLLJEC7RTIUKAc8I@uVFHWnULITtscSB6awL@A1Uz6AIQI5zaYwgHUQtLvfCMOBjvvdFqxLUFXN6q0jsyEBI52bsL5jIh2F3xX/L5q/ "Python 2 – Try It Online")
[Answer]
# MATL, ~~25~~ 21 bytes
```
+2-lGqXnt8/k-t20/k6*-
```
[Try it on MATL Online](https://matl.io/?code=%2B2-lGqXnt8%2Fk-t20%2Fk6%2a-&inputs=4%0A3&version=20.9.1)
Attempt to port Jonathan Allan's [Jelly answer](https://codegolf.stackexchange.com/a/168624/8774) to MATL.
`+2-lGqXn` - same as that answer: compute \$ \binom{r+s-2}{r-1} \$
`t8/k` - duplicate that, divide by 8 and floor
`-` - subtract that from previous result (We subtract how many times 8 goes in the number, instead of 9 in the Jelly answer. The result is the same for all but the 35 and 70, which here give 31 and 62.)
`t20/k` - duplicate that result too, divide that by 20 and floor (gives 0 for already correct results, 1 for 31, 3 for 62)
`6*` - multiply that by 6
`-` - subtract that from the result (31 - 6 = 25, 62 - 18 = 44)
---
Older:
```
+t2-lGqXntb9<Q3w^/k-t20>+
```
[Try it on MATL Online](https://matl.io/?code=%2Bt2-lGqXntb9%3CQ3w%5E%2Fk-t20%3E%2B&inputs=5%0A5&version=20.9.1)
[Answer]
# [Python 3](https://docs.python.org/3/), 74 bytes
```
lambda *a:[[1]*5,[2,3,4,5],[6,9,14],[18,25],[43]][min(a)-1][max(a)-min(a)]
```
[Try it online!](https://tio.run/##bVDRbsIgFH3nK258Ku5uEVsXZ9af8JURwzrcmrXUAMYZ47d3UK20RgjJveeee84Ju6P7aXTarvOPtpL155eEqVxxzsR0gXyOKWa4EMhf8Q1Z5gu2xHkAslQIXpc6kfSZ@Ur@heoCiFZqe1Bm86uOkAMn4A9neL0Ce@Cm3wMp9kY9koX@4tlDC0/wQMiA2VIIIggpGmNU4bzbjJR62G0bAxbBNAcoNSi9r5WRTiUxIgKjq048cA1CoapqTPbbkdUx97rYGGX3VXBZJxYNvQ1Lu4kJOrE8H25E4hbccaeSwKGBVJXWRZOHWnwm4H0kF9puwsRQOW6OFXu5pxzYbaAqq@6M9UNiODtTapdMDqbR3yswpzNY/0KE/HTGLpovJi/@O2vpEoMWwxAHmSklF5WrCUY/OvIi7T8 "Python 3 – Try It Online")
[Answer]
# [Proton](https://github.com/alexander-liao/proton), 52 bytes
Near-port of my [Python answer](https://codegolf.stackexchange.com/a/168620/59487).
```
c=>[48,(M=max(c))%2*7+18,3*M-(M>4?1:3),M,1][-min(c)]
```
[Try it online!](https://tio.run/##PcoxCoMwFADQOTnFRygk9iukSitC0hPkBCFDEQIOJvLjIIhnT@3S9fFWSluKJYAukzauH1BYvXx2MUl5e9Svuxqwq20jrOnfauwkWlTeNcscr@JLSAQEIyhoW3jCwdlP8iX0F7bSHDdBCBmh0qZCCMIRZi8lZyc/yxc "Proton – Try It Online")
[Answer]
# Java 8, 62 bytes
```
(r,s)->--r*--s+new int[]{9,1,0,13,2,0,3,27,6}[r<2|s<2?1:r*s%9]
```
Lambda function, port of [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s JavaScript [answer](https://codegolf.stackexchange.com/a/168633/79343). Try it online [here](https://tio.run/##RVLbToNAEH2Gr5iQmEBZGulNW1obEzUxakzsI@FhS7cNlVt2F7VBvh1nuxQJzMyeOTkzO8ORflGvKFl@3H22ZbVNkxjilAoBbzTJoTaNJJeM72nM4INmgp0UpkDIq2zLuK1CTkA54QSm0ZhGpyMklei@imQHGarZG8mT/BBGQPlBOGehTpNrt4LW5kQ43p3n8YHnCTdn30o6jOo58ck18cdkhA7tDZk1IV@OfsVytPYXfCCu5lFrGIFuL4ywjm5RoG6vg2hd@wT@34aAAkYExgQmBKYdgKcZgTkyJh0y0cdbJF9IU5VWZ8yOm0YV3xfdULCsH6BbrmAagOtyfeWeIDRB9IRuJnq87KdksWQ71by@Rsg9PwoFmqBn0VhWNEWOnuCwWwou5LwMfDYnIVk2LCo5LHH8Ms1tDi5YxEIrVLQAFXZKLtj2RXTVN@HAGiz7/cWxANn20/3z6@MD6dNaoe8YNR3L0fXxd1BfYzbtHw).
# Java, 83 bytes
```
int f(int x,int y){return x<2|y<2?1:f(x,y-1)+f(x-1,y)-(x*y==12?1:0)-7*(x+y>8?1:0);}
```
Recursive function, port of [Neil](https://codegolf.stackexchange.com/users/17602/neil)'s JavaScript [answer](https://codegolf.stackexchange.com/a/168619/79343). Try it online [here](https://tio.run/##RVJNb8IwDD2XX2H1lKwpWhlsjNJ9SNukaZuQxhFxCBBQGRSUpKwV629nThNK1Tq239Oza2fNDzzc7UW2Xvyc9vlsk85hvuFKwRdPMzi2PD5TWvK5BqW5btBvvlWiNPiFkGYalsRYyepA0bjlVS3P6TqBwy5dwBbVyVjLNFtNpsDlStFazOlKeySQiV9XiyDhaXQQUqYLcbrUKpixJT1KoXOZQTHs/JXDzmM0WJKClWFEA3TCiJU0JMVVmSSRAa9peHdFiqB86NdRXJ08r8J@PZSbTLGpLN/OhFSuiXP2eIwYXN6KgUl0GNww6DLouQRGtwzukdF1ma4N@0g@k3oGNjGiN1VdfLmTdoJYNorxGCbQiyEIpJ1PQ1CWoBqCG2DdP4hiL@ZaLEzz9jcmMoymE4Umbli4tJxvkGPH3V4SXFy9NHzGpdJi297lur3HNelNRiQE4DMfrTLeAIzrRAIg5KyXNPUpPIJPRh/UB2STt@f3z9cX1sBWoWkWNalPbX28NuarWtXpHw).
[Answer]
# C (gcc), 57 bytes
```
f(x,y){x=x<2|y<2?:f(x,y-1)+f(x-1,y)-(x*y==12)-7*(x+y>8);}
```
Recursive function, port of [Neil](https://codegolf.stackexchange.com/users/17602/neil)'s JavaScript [answer](https://codegolf.stackexchange.com/a/168619/79343). Try it online [here](https://tio.run/##RY5va4MwEMZf109xCEJST2hs3bpaVwbboGywD9D1hbOxK6yuJBYU52d3F/8VjiT3/J7LPYl3TJKmSVmBJa@KqFj7f@Xa36xaxRPcpYcnCHqsmJZRJHzu3U9Z4ZaPSx7WzSnL4RyfMsahsiamy67nL6n0LthTQQRVJRBuVSMYwUeYIywQgl6g7g7hgRyLXll07ZLMgykw2PRE53UdWpP0VzGzVdEmEdK1jiAIwXVVG2jkuuN65LrjbWRZXGSSywN5hvTKE/udpiMcTHGSX@MfsqRMIWjeguQ7VnCWWsdHuROzWWfXF0UTKesBAmPDdDQu47ABm328cRtW9Hh92r6/POOIV@AcuM1vQrew/9l2Dui0HnD0Z2YjmEzYh8QhUjtTW6aUzK8qg1lo1c0/).
# C (gcc), 63 bytes
```
f(r,s){r=--r*--s+(int[]){9,1,0,13,2,0,3,27,6}[r<2|s<2?:r*s%9];}
```
Port of [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s JavaScript [answer](https://codegolf.stackexchange.com/a/168633/79343). Try it online [here](https://tio.run/##RZBva4NADMZf108RBOGujaBWu7VWymAbjA32AZwvnLVdYXUlZ2Hg7rO7nP8KIXfJ78nl4Qr3WBRtexCESjaUuC7NXVctxKmq00w2a/TRQ3@JAR@c73ClU9oGf2ob7DY0V846i3XLajjnp0pIaKyZqarr@bMklUYZByTQND7CLTSCaQQIS4QQIRoaXK0Q1qwIh07Yl/csHkWRwaZmutQ6tmaHHzKOgXiTH/OxTSCKYbGgztDEVc/VxFXPO8vl76Us6nLPmtE9uX6WKk7xKMqL@pp/s8R8GSjZgeIrJziXSuXHMvU9r5erC/HEQQwAQYhxOpmWSdiBLd5fpQ0bvjw/vLw9PeKEN@DspS1vjX7h8LLt7NHpNOCoj8pGMJ5wMImjpW5GWyaorK9UgRdbuv0H).
] |
[Question]
[
*This challenge is based on, and contains test cases from, [a programming course](http://mooc.aalto.fi/ohjelmointi/scala_2017.html) I took at Aalto University. The material is used with permission.*
Two and a half years ago there was a challenge about [spoonerisms in English](https://codegolf.stackexchange.com/questions/69385/spoonerise-words). However, in Finnish spoonerisms are much more complicated.
## Spoonerisms in Finnish
In Finnish, the vowels are `aeiouyäö` and the consonants are `bcdfghjklmnpqrstvwxz`. (`å` is technically part of Finnish, but is not considered here.)
The most basic spoonerisms only take the first vowel of each word, and any consonants preceding them, and exchange the parts:
```
**he**nri **ko**ntinen -> **ko**nri **he**ntinen
**ta**rja **ha**lonen -> **ha**rja **ta**lonen
**fra**kki **ko**ntti -> **ko**kki **fra**ntti
**o**vi **ke**llo -> **ke**vi **o**llo
```
### Long vowels
Some words contain two of the same consecutive vowel. In those cases, the vowel pair must be swapped with the other word's first vowel, shortening or lengthening vowels to keep the length same.
```
**haa**mu **ko**ntti -> **koo**mu **ha**ntti
**ki**sko **kaa**ppi -> **ka**sko **kii**ppi
```
In the case of two *different* consecutive vowels this does not apply:
```
**ha**uva **ko**ntti -> **ko**uva **ha**ntti
**pu**oskari **ko**ntti -> **ko**oskari **pu**ntti
```
Three or more of the same consecutive letter will **not** appear in the input.
### Vowel harmony
Finnish has this lovely thing called [vowel harmony](https://en.wikipedia.org/wiki/Vowel_harmony#Finnish). Basically, it means that the *back vowels* `aou` and *front vowels* `äöy` should not appear in the same word.
When swapping front or back vowels into a word, all vowels of the other kind in the rest of the word should be changed to match the new beginning of the word (`a <-> ä`, `o <-> ö`, `u <-> y`):
```
**kö***y*h*ä* **ko**ntti -> **ko***u*h*a* **kö**ntti
**ha***u*v*a* **lää**h*ä*tt*ää* -> **lä***y*v*ä* **haa**h*a*tt*aa*
```
`e` and `i` are neutral and may appear with all other letters; swapping them into a word *must not* cause changes to the rest of the word.
### Special cases
Vowel harmony does not apply to some words, including many loan words and compound words. These cases are not required to be handled "correctly".
## Challenge
Given two words, output the words spoonerised.
The input words will only contain the characters `a-z` and `äö`. You may choose to use uppercase or lowercase, but your choice must be consistent between both words and input/output.
I/O may be done [in any convenient format](http://meta.codegolf.stackexchange.com/q/2447/42963). (Words should be considered strings or arrays of characters.)
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest solution in bytes wins.
## Test cases
```
henri kontinen -> konri hentinen
tarja halonen -> harja talonen
frakki kontti -> kokki frantti
ovi kello -> kevi ollo
haamu kontti -> koomu hantti
hauva kontti -> kouva hantti
puoskari kontti -> kooskari puntti
köyhä kontti -> kouha köntti
hauva läähättää -> läyvä haahattaa
frakki stressi -> strekki frassi
äyskäri kontti -> kouskari äntti
hattu sfääri -> sfätty haari
ovi silmä -> sivi olma
haamu prätkä -> präämy hatka
puoskari sfääri -> sfäöskäri puuri
puoskari äyskäri -> äöskäri puuskari
uimapuku hajoa -> haimapuku ujoa
ihme baletti -> bahme iletti
uhka lima -> lihka uma
osuma makkara -> masuma okkara
makkara fakta -> fakkara makta
lapsi laiva -> lapsi laiva
firma hajoa -> harma fijoa
dimensio bitti -> bimensio ditti
flamingo joustava -> jomingo flaustava
globaali latomo -> labaali glotomo
trilogia fakta -> falogia trikta
printti maksa -> mantti priksa
riisi bitti -> biisi ritti
sini riisi -> rini siisi
aarre nyrkki -> nyyrre arkki
laavu laki -> laavu laki
kliininen parveke -> paaninen klirveke
priimus kahvi -> kaamus prihvi
spriinen lasta -> laanen sprista
kliimaksi mammona -> maamaksi klimmona
hylky hupsu -> hulku hypsy
kehys fiksu -> fihys keksu
levy huhu -> huvu lehu
tiheys guru -> guheus tiru
nyrkki heiluri -> herkki nyilyri
latomo hajoa -> hatomo lajoa
prisma lehti -> lesma prihti
viina baletti -> baana viletti
```
[Answer]
# JavaScript (ES6), ~~196~~ 175 bytes
Takes the words as two strings in currying syntax `(a)(b)`. Returns an array of two arrays of characters.
```
a=>b=>[(e=/(.*?)([eiäaöoyu])(\2?)(.*)/,g=(a,[,c,v])=>[...c+v+(a[3]&&v)+a[4]].map(c=>(j=e.search(v),i=e.search(c))>9&j>9?e[i&~1|j&1]:c))(a=e.exec(a),b=e.exec(b),e+=e),g(b,a)]
```
[Try it online!](https://tio.run/##bVRLjuM2EN3PKQq9sMVptQeTZDMDyI1sAgQJkAM4XpTdtEmLEg1@NBEQ5DQ@Q19AB@sUP5LVdq9UfPVYqnpVxRN2aPdGnt1Tq1/426F6w2q9q9abgldfitXnZ1ZsuBwuOLzq3m9Z8fdPBK0@sy/lsSqw3JT7stsyurBarfaP3WOBm5@3i0XHHnHzy3a7avBc7Kt1car4ynI0e1F0rJTX056x9bfFaf3tmW/k4r@v/54WX7ffCS2QSPwfvi@QlbvR3rGSP1aclcdiVyLbvjluHVRAucCuBMMtg2oNe91arfhK6WP2LJ@e1ssSLHEPFJECxdx@BPaP1UnLtlguGcsWLFnkViEiPMOy@OsPtoTvZPz26@9/siX79Cn8uXgQvDXyoYSHWrdOtrzNtpFAroSwzHVoThj8ApXOVBEwcBkYmQeDdT2FddkiCMgTgZGpu@TkSulkdBJ0OIwMgdj421C68SDeRxLoO7zlEXTLO3ttazR32SUUzv4dux5eezFc7uIKBHJ9nIAaLsOFLjkXjIz03XChVFCgc4gfKGUd9cpOZhYrICOXgth6uNyn7lPqw@UmH@eicPYQ8kjXgu1cHzIxd12wUjUpYStjGxq8b8PZUIQ60YI9XJoQztX4ocS3Px9eUw0ktDcfd@Vdne9vJM54yUvaAV/7NIgnnYczo@ADMnKlaHhw71DxLNwOCQOZzlNMUacmUpT0JQD8TAltfXI11Do02Qwg6ASMzBnhgLUbjYBBE4GRqfCcWq9Q5iEKCKTjNCzSNHhTLCFwkPNKX2TDWyvjOu3kWGsG4UXOqz0obGR7jNwTzZHD9PeTjjCQP4PjjaPSO0SVk3W60cmKIJA3QtOTYSS9YfJWgogBOecanI0cR5rEsVnXAAG5AjAyjZRW3pRHCJh3tVnZRt/EpvgSbDyNHNoCE8ei7U3ew7bvCQOM52t/sPOp0DqXTgDE0/RUKEk/yO/iGU3Ha55MjDAQIYGzimXjbVxiFPklDHtmQ8UBmGoJ1BxaoXV5RDCEDT470zHkEQTMSjaNbrOWGOGQRwKn3e5V3cdx8mebtskrWiDRn21/jctFH3M9UDN8MgiBmofjpBTvciiRIwWduLgynBQ8BTp649NXcKrZSXNlXRsiuFTeZDOA0PZS9WbenXEOZ4sRIGrQfDOCUHmruUiDozghUe3Z5HSkNd49FtgidONr8fY/ "JavaScript (Node.js) – Try It Online")
### How?
Each input word is passed through the regular expression **e**, which has 4 capturing groups:
```
e = /(.*?)([eiäaöoyu])(\2?)(.*)/ 1: leading consonants (or empty)
[ 1 ][ 2 ][ 3 ][ 4] 2: first vowel
3: doubled first vowel (or empty)
4: all remaining characters
```
The helper function **g()** takes all capturing groups of the word to be updated as **a[ ]** and the first and second capturing groups of the other word as **c** and **v**.
We apply basic spoonerism and take care of long vowels with:
```
c + v + (a[3] && v) + a[4]
```
To apply vowel harmony, we first coerce the regular expression **e** to a string by adding it to itself, which gives:
```
e = "/(.*?)([eiäaöoyu])(\2?)(.*)//(.*?)([eiäaöoyu])(\2?)(.*)/"
^^^^^^^^^^^^^^^^
0123456789ABCDEF (position as hexa)
```
Vowels that need to be harmonized have a position greater than 9 in the resulting string. Furthermore, the expression was arranged in such a way that front vowels ***äöy*** are located at even positions, while back vowels ***aou*** are located at odd positions, next to their counterparts.
Hence the following translation formula which is applied to each character **c** of the output word:
```
(j = e.search(v), i = e.search(c)) > 9 & j > 9 ? e[i & ~1 | j & 1] : c
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~235~~ ~~231~~ ~~225~~ ~~221~~ ~~217~~ 215 bytes
```
import re
S=F,B='äöy','aou'
def f(a,b,C=1):
e,r,Q,W=re.findall(fr' ?(.*?([ei{B+F}]))(\2)?(\w*)'*2,a+' '+b)[0][2:6]
for c in zip(*S*(W in B)+(B,F)*(W in F)):r=r.replace(*c)
return[Q+W*len(e)+r]+(C and f(b,a,[]))
```
[Try it online!](https://tio.run/##XVNLbuM4EN3zFNxJsjXBdAaYRQB3gDSQfXcvskiCQTmmzIooUuBH3erB3MZnyAV8sEwVKSN2b2y@91jFVx@Nc9TO/vX@jsPofJReie@b@/ZuUx0Px7e5aitwqRI71cmuhnbbftl8am6EVK1vv7YPG6@uOrQ7MKbufCVv66vVbf2o8N@79f1/z01TP103t/XTj1VTra5bWFeyWm@bxz@fH69v/n4WsnNevki08heO9er7qn5gcNes67v2vlngfdPc@I2/8mo08KLq1UsjyGlM3j5@XT@sjLK1atb@eV1/kWB3ZHXbQvtI77//0GiU/ESW2f0/7Tdov203aMcU6@YqjAbpX8if7bzJBdJ59GhjLWvims2mzhFNWz3FqmXqXSvrUfbORrTKyj8@85kY4jMjIvhXkBqMW3SdiVgI0Xno@5IgYglnTDQTwk2kKWNclhQhR0BogCFdBDnCusRoSBNciIwXcUwu9OAvX1yoMeUrPc1aHw@XGTRlPL6d5Te0Ewe6FiMf@BYx80RHMqchRoBTcSF6FULOxMelPmIERYT@ePjNTip2jofluRiTDB0/40uSjp@d@SFfWhTQDMVEwNyjAZYejZ7u9kXj8/EwcGDs4aMVv@c@vi2mxpT8Wcs@3NLFy2v5gkg4wJh6nsSrgzLsE5WIEagHJbdg1FLrFpjAjEXSPbWV7udmIqNEdbhAv3KgToLP0gCZcZkQJ6GDPma5W4iBCWFgpM4bwKmk/YCiQz/AuVWGHbLPHQ7KBnRyiyenJ2bHjOgMDGj3Tr7StCKU5K@ucCQWUuyN2wIYfjG6wRUHhSGJKRE9GrfHiwIKQQpXkL9AMkH1hKX@jIknQnhEqujMJ0OfTQa0fMSyep5RYCRob7ySdva8iiTZeWYCGFPHYEpks0gfSPQGKQV/xSP4SfUq7xRA4UjNJPvFIQXZg57KQvMiBvZLhAisc4CBEJeZAGMWiMnPcK1c8TA4u9QMhSM1k0LPpqdNTmNIeXrJ8N7NY5hFr/QcaJJ9kTpk2CuCwqiJg/QSw6UpnURErejOPvks7JNW5DiiT2LpklZoUtl8rTJjZzSz537l0Z7tUcaGMTcj0FbRI2U8RjHkVtB8JmoEXH4OQMRUvof/AQ "Python 3 – Try It Online")
---
Saved
* -2 bytes, thanks to Lynn
* -4 bytes, thanks to Zacharý
[Answer]
# Pyth, 84 bytes
```
.b++hY*W@N2JhtY2XW}JeA@DJc2"aouäöy"eNGH_Bmth:d:"^([^A*)([A)(\\2)*(.+)"\A"aeiouyäö]"4
```
[Try it online.](http://pyth.herokuapp.com/?code=.b%2B%2BhY%2aW%40N2JhtY2XW%7DJeA%40DJc2%22aou%C3%A4%C3%B6y%22eNGH_Bmth%3Ad%3A%22%5E%28%5B%5EA%2a%29%28%5BA%29%28%5C%5C2%29%2a%28.%2B%29%22%5CA%22aeiouy%C3%A4%C3%B6%5D%224&input=%5B%22hauva%22%2C%22l%C3%A4%C3%A4h%C3%A4tt%C3%A4%C3%A4%22%5D&test_suite_input=%5B%22henri%22%2C+%22kontinen%22%5D%0A%5B%22tarja%22%2C+%22halonen%22%5D%0A%5B%22frakki%22%2C+%22kontti%22%5D%0A%5B%22ovi%22%2C+%22kello%22%5D%0A%5B%22haamu%22%2C+%22kontti%22%5D%0A%5B%22hauva%22%2C+%22kontti%22%5D%0A%5B%22puoskari%22%2C+%22kontti%22%5D%0A%5B%22k%C3%B6yh%C3%A4%22%2C+%22kontti%22%5D%0A%5B%22hauva%22%2C+%22l%C3%A4%C3%A4h%C3%A4tt%C3%A4%C3%A4%22%5D%0A%5B%22frakki%22%2C+%22stressi%22%5D%0A%5B%22%C3%A4ysk%C3%A4ri%22%2C+%22kontti%22%5D%0A%5B%22hattu%22%2C+%22sf%C3%A4%C3%A4ri%22%5D%0A%5B%22ovi%22%2C+%22silm%C3%A4%22%5D%0A%5B%22haamu%22%2C+%22pr%C3%A4tk%C3%A4%22%5D%0A%5B%22puoskari%22%2C+%22sf%C3%A4%C3%A4ri%22%5D%0A%5B%22puoskari%22%2C+%22%C3%A4ysk%C3%A4ri%22%5D%0A%5B%22uimapuku%22%2C+%22hajoa%22%5D%0A%5B%22ihme%22%2C+%22baletti%22%5D%0A%5B%22uhka%22%2C+%22lima%22%5D%0A%5B%22osuma%22%2C+%22makkara%22%5D%0A%5B%22makkara%22%2C+%22fakta%22%5D%0A%5B%22lapsi%22%2C+%22laiva%22%5D%0A%5B%22firma%22%2C+%22hajoa%22%5D%0A%5B%22dimensio%22%2C+%22bitti%22%5D%0A%5B%22flamingo%22%2C+%22joustava%22%5D%0A%5B%22globaali%22%2C+%22latomo%22%5D%0A%5B%22trilogia%22%2C+%22fakta%22%5D%0A%5B%22printti%22%2C+%22maksa%22%5D%0A%5B%22riisi%22%2C+%22bitti%22%5D%0A%5B%22sini%22%2C+%22riisi%22%5D%0A%5B%22aarre%22%2C+%22nyrkki%22%5D%0A%5B%22laavu%22%2C+%22laki%22%5D%0A%5B%22kliininen%22%2C+%22parveke%22%5D%0A%5B%22priimus%22%2C+%22kahvi%22%5D%0A%5B%22spriinen%22%2C+%22lasta%22%5D%0A%5B%22kliimaksi%22%2C+%22mammona%22%5D%0A%5B%22hylky%22%2C+%22hupsu%22%5D%0A%5B%22kehys%22%2C+%22fiksu%22%5D%0A%5B%22levy%22%2C+%22huhu%22%5D%0A%5B%22tiheys%22%2C+%22guru%22%5D%0A%5B%22nyrkki%22%2C+%22heiluri%22%5D%0A%5B%22latomo%22%2C+%22hajoa%22%5D%0A%5B%22prisma%22%2C+%22lehti%22%5D%0A%5B%22viina%22%2C+%22baletti%22%5D&debug=1) [Test suite.](http://pyth.herokuapp.com/?code=.b%2B%2BhY%2aW%40N2JhtY2XW%7DJeA%40DJc2%22aou%C3%A4%C3%B6y%22eNGH_Bmth%3Ad%3A%22%5E%28%5B%5EA%2a%29%28%5BA%29%28%5C%5C2%29%2a%28.%2B%29%22%5CA%22aeiouy%C3%A4%C3%B6%5D%224&input=%5B%22hauva%22%2C%22l%C3%A4%C3%A4h%C3%A4tt%C3%A4%C3%A4%22%5D&test_suite=1&test_suite_input=%5B%22henri%22%2C+%22kontinen%22%5D%0A%5B%22tarja%22%2C+%22halonen%22%5D%0A%5B%22frakki%22%2C+%22kontti%22%5D%0A%5B%22ovi%22%2C+%22kello%22%5D%0A%5B%22haamu%22%2C+%22kontti%22%5D%0A%5B%22hauva%22%2C+%22kontti%22%5D%0A%5B%22puoskari%22%2C+%22kontti%22%5D%0A%5B%22k%C3%B6yh%C3%A4%22%2C+%22kontti%22%5D%0A%5B%22hauva%22%2C+%22l%C3%A4%C3%A4h%C3%A4tt%C3%A4%C3%A4%22%5D%0A%5B%22frakki%22%2C+%22stressi%22%5D%0A%5B%22%C3%A4ysk%C3%A4ri%22%2C+%22kontti%22%5D%0A%5B%22hattu%22%2C+%22sf%C3%A4%C3%A4ri%22%5D%0A%5B%22ovi%22%2C+%22silm%C3%A4%22%5D%0A%5B%22haamu%22%2C+%22pr%C3%A4tk%C3%A4%22%5D%0A%5B%22puoskari%22%2C+%22sf%C3%A4%C3%A4ri%22%5D%0A%5B%22puoskari%22%2C+%22%C3%A4ysk%C3%A4ri%22%5D%0A%5B%22uimapuku%22%2C+%22hajoa%22%5D%0A%5B%22ihme%22%2C+%22baletti%22%5D%0A%5B%22uhka%22%2C+%22lima%22%5D%0A%5B%22osuma%22%2C+%22makkara%22%5D%0A%5B%22makkara%22%2C+%22fakta%22%5D%0A%5B%22lapsi%22%2C+%22laiva%22%5D%0A%5B%22firma%22%2C+%22hajoa%22%5D%0A%5B%22dimensio%22%2C+%22bitti%22%5D%0A%5B%22flamingo%22%2C+%22joustava%22%5D%0A%5B%22globaali%22%2C+%22latomo%22%5D%0A%5B%22trilogia%22%2C+%22fakta%22%5D%0A%5B%22printti%22%2C+%22maksa%22%5D%0A%5B%22riisi%22%2C+%22bitti%22%5D%0A%5B%22sini%22%2C+%22riisi%22%5D%0A%5B%22aarre%22%2C+%22nyrkki%22%5D%0A%5B%22laavu%22%2C+%22laki%22%5D%0A%5B%22kliininen%22%2C+%22parveke%22%5D%0A%5B%22priimus%22%2C+%22kahvi%22%5D%0A%5B%22spriinen%22%2C+%22lasta%22%5D%0A%5B%22kliimaksi%22%2C+%22mammona%22%5D%0A%5B%22hylky%22%2C+%22hupsu%22%5D%0A%5B%22kehys%22%2C+%22fiksu%22%5D%0A%5B%22levy%22%2C+%22huhu%22%5D%0A%5B%22tiheys%22%2C+%22guru%22%5D%0A%5B%22nyrkki%22%2C+%22heiluri%22%5D%0A%5B%22latomo%22%2C+%22hajoa%22%5D%0A%5B%22prisma%22%2C+%22lehti%22%5D%0A%5B%22viina%22%2C+%22baletti%22%5D&debug=1)
Proving that it's not *that* hard in golf languages. A stack-based language might do even better.
Pyth uses ISO-8859-1 by default, so `äö` are one byte each.
### Explanation
* `Q`, containing the input pair of words, is appended implicitly.
* `m`: map each word `d` in the input to:
+ `:"^([^A*)([A)(\\2)*(.+)"\A"aeiouyäö]"`: replace `A` with `aeiouyäö]` in the string to get the regex `^([^aeiouyäö]*)([aeiouyäö])(\2)*(.+)`.
+ `:d`: find all matches and return their capturing groups.
+ `h`: take the first (and only) match.
+ `t`: drop the first group containing the entire match.
* `_B`: pair with reverse to get `[[first, second], [second, first]]`.
* `.b`: map each pair of words `N, Y` in that to:
+ `hY`: take the beginning consonants of the second word.
+ `@N2`: take the long first vowel of the first word, or `None`.
+ `htY`: take the first vowel of the second word.
+ `J`: save that in `J`.
+ `*W`…`2`: if there was a long vowel, duplicate the second word's vowel.
+ `+`: append that to the consonants.
+ `c2"aouäöy"`: split `aouäöy` in two to get `["aou", "äöy"]`.
+ `@DJ`: sort the pair by intersection with the first vowel of the second word. This gets the half with the second word's first vowel in the end of the pair.
+ `A`: save the pair to `G, H`.
+ `e`: take the second half.
+ `}J`: see if the first vowel of the second word is in the second half.
+ `XW`…`eNGH`: if it was, map `G` to `H` in the suffix of the first word, otherwise keep the suffix as-is.
+ `+`: append the suffix.
] |
[Question]
[
# Rotonyms 2
A "Rotonym" is a word that ROT13s into another word (in the same language).
For this challenge, we'll use an alternate definition: a "Rotonym" is a word that circular shifts/rotates into *another* word (in the same language).
For example:
```
'stable' < 'tables' < 'ablest'
'abort' > 'tabor'
'tada' >> 'data'
```
# The Challenge
Write a program or function that accepts a dictionary/word list and prints or returns a complete list of rotonyms.
1. Order doesn't matter.
2. Comparisons should be case-insensitive, so you can assume the input will be passed as a lower-case-only dictionary.
3. Result should be expressed as single words (not the pairs) and contain no duplicates, so you can assume the input has no duplicates.
4. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'").
# Example
Given
```
ablest
abort
green
irk
stable
tables
tabor
tata
terra
vex
you
```
Return
```
ablest
abort
stable
tables
tabor
```
# A Real Test
Given
```
a aa aal aalii aam aani aardvark aardwolf aaron aaronic aaronical aaronite aaronitic aaru ab aba ababdeh ababua abac abaca abacate abacay abacinate abacination abaciscus abacist aback abactinal abactinally abaction abactor abaculus abacus abadite abaff abaft abaisance abaiser abaissed abalienate abalienation abalone abama abampere abandon abandonable abandoned abandonedly abandonee abandoner abandonment abanic abantes abaptiston abarambo abaris abarthrosis abarticular abarticulation abas abase abased abasedly abasedness abasement abaser abasgi abash abashed abashedly abashedness abashless abashlessly abashment abasia abasic abask abassin abastardize abatable abate abatement abater abatis abatised abaton abator abattoir abatua abature abave abaxial abaxile abaze abb abba abbacomes abbacy abbadide abbas abbasi abbassi abbasside abbatial abbatical abbess abbey abbeystede abbie abbot abbotcy abbotnullius abbotship abbreviate abbreviately abbreviation abbreviator abbreviatory abbreviature abby abcoulomb abdal abdat abderian abderite abdest abdicable abdicant abdicate abdication abdicative abdicator abdiel abditive abditory abdomen abdominal abdominales abdominalian abdominally abdominoanterior abdominocardiac abdominocentesis abdominocystic abdominogenital abdominohysterectomy abdominohysterotomy abdominoposterior abdominoscope abdominoscopy abdominothoracic abdominous abdominovaginal abdominovesical abduce abducens abducent abduct abduction abductor abe abeam abear abearance abecedarian abecedarium abecedary abed abeigh abel abele abelia abelian abelicea abelite abelmoschus abelmosk abelonian abeltree abencerrages abenteric abepithymia aberdeen aberdevine aberdonian aberia aberrance aberrancy aberrant aberrate aberration aberrational aberrator aberrometer aberroscope aberuncator abet abetment ablest abort abut ach ache acher achete achill achor acor acre acyl ad adad adat add addlings adet ala ama baa bafta balonea batea beta caba cha chilla cora crea da dad dada data each lacy orach rache saddling stable tables tabor tabu tade teache zoquean zoraptera zorgite zoril zorilla zorillinae zorillo zoroastrian zoroastrianism zoroastrism zorotypus zorrillo zorro zosma zoster zostera zosteraceae zosteriform zosteropinae zosterops zouave zounds zowie zoysia zubeneschamali zuccarino zucchetto zucchini zudda zugtierlast zugtierlaster zuisin zuleika zulhijjah zulinde zulkadah zulu zuludom zuluize zumatic zumbooruk zuni zunian zunyite zupanate zutugil zuurveldt zuza zwanziger zwieback zwinglian zwinglianism zwinglianist zwitter zwitterion zwitterionic zyga zygadenine zygadenus zygaena zygaenid zygaenidae zygal zygantra zygantrum zygapophyseal zygapophysis zygion zygite zygnema zygnemaceae zygnemales zygnemataceae zygnemataceous zygnematales zygobranch zygobranchia zygobranchiata zygobranchiate zygocactus zygodactyl zygodactylae zygodactyli zygodactylic zygodactylism zygodactylous zygodont zygolabialis zygoma zygomata zygomatic zygomaticoauricular zygomaticoauricularis zygomaticofacial zygomaticofrontal zygomaticomaxillary zygomaticoorbital zygomaticosphenoid zygomaticotemporal zygomaticum zygomaticus zygomaxillare zygomaxillary zygomorphic zygomorphism zygomorphous zygomycete zygomycetes zygomycetous zygon zygoneure zygophore zygophoric zygophyceae zygophyceous zygophyllaceae zygophyllaceous zygophyllum zygophyte zygopleural zygoptera zygopteraceae zygopteran zygopterid zygopterides zygopteris zygopteron zygopterous zygosaccharomyces zygose zygosis zygosperm zygosphenal zygosphene zygosphere zygosporange zygosporangium zygospore zygosporic zygosporophore zygostyle zygotactic zygotaxis zygote zygotene zygotic zygotoblast zygotoid zygotomere zygous zygozoospore zymase zyme zymic zymin zymite zymogen zymogene zymogenesis zymogenic zymogenous zymoid zymologic zymological zymologist zymology zymolyis zymolysis zymolytic zymome zymometer zymomin zymophore zymophoric zymophosphate zymophyte zymoplastic zymoscope zymosimeter zymosis zymosterol zymosthenic zymotechnic zymotechnical zymotechnics zymotechny zymotic zymotically zymotize zymotoxic zymurgy zyrenian zyrian zyryan zythem zythia zythum zyzomys zyzzogeton
```
Return
```
aal aam aba abac abaft abalone abate abet ablest abort abut ach ache acher achete achill achor acor acre acyl ad adad adat add addlings adet ala ama baa bafta balonea batea beta caba cha chilla cora crea da dad dada data each lacy orach rache saddling stable tables tabor tabu tade teache
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~25~~ ~~23~~ ~~22~~ ~~17~~ 16 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Borrows ideas from [ngn's ngn/k solution](https://codegolf.stackexchange.com/a/165668/43319). And then -6 thanks to him. Also -1 by returning [an enclosed list as like H.PWiz](https://codegolf.stackexchange.com/a/165655/43319).
Anonymous tacit prefix function.
```
⊂∩¨1,.↓(∪≢,/,⍨)¨
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT////1FX06OOlYdWGOroPWqbrPGoY9WjzkU6@jqPeldoHlrxP@1R24RHvX2P@qZ6@j/qaj603vhR20QgLzjIGUiGeHgG/09TUE9MykktLlEHMfKLQHR6UWpqHpDOLMoGksUlIAVABpguhjDyi8B0SSKISi0qAtFlqRVAsjK/VB0A "APL (Dyalog Unicode) – Try It Online")
`(`…`)¨` apply the following tacit function to each word:
`,⍨` concatenate the word to itself
`≢,/` all word-length sub-strings (i.e. all rotations)
`∪` unique elements of those rotations (to prevent words like `tata` for appearing twice)
`1,.↓` the concatenation of the drop-firsts (the original words) of each list
`⊂∩¨` intersection of the the content of that and the entire original word list
---
### Old solution
-2 thanks to ngn.
Anonymous prefix lambda.
```
{⍵/⍨2≤+/⍵∊⍨↑(∪≢,/,⍨)¨⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pR71b9R70rjB51LtEGMrY@6ugCch@1TdR41LHqUeciHX0dIF/z0AqgXO3/tEdtEx719j3qm@rp/6ir@dB6Y6BKIC84yBlIhnh4Bv9PU1BPTMpJLS5RBzHyi0B0elFqah6QzizKBpLFJSAFQAaYLoYw8ovAdEkiiEotKgLRZakVQLIyv1QdAA "APL (Dyalog Unicode) – Try It Online")
`{`…`}` function where `⍵` is the word list:
`(`…`)¨` apply the following tacit function to each word:
`,⍨` concatenate the word to itself
`≢,/` all word-length sub-strings (i.e. all rotations)
`∪` unique elements of those rotations (to prevent words like `tata` for appearing twice)
`↑` mix the list of lists into a single matrix (pads with all-space strings)
`⍵∊⍨` indicate which elements of the matrix are members of the original list
`+/` sum the rows (counts occurrences of each of the original words)
`2≤` indicate which have duplicates (i.e. occur other than when rotated back to original)
`⍵/⍨` use that to filter the original list
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
ṙ1$ƬfḊɗƇ
```
[Try it online!](https://tio.run/##y0rNyan8///hzpmGKsfWpD3c0XVy@rH2/w93bzncHvn/f2JSTmpxCVdiUn5RCVd6UWpqHldmUTZXcQlIggtMFoOo/CIgWZLIVZJaVJTIVZZawVWZXwoA "Jelly – Try It Online")
### Alternate version, 7 bytes
```
ṙƬ1fḊʋƇ
```
Dyadic `Ƭ` used to do something weird, so this didn't work when the challenge was posted.
[Try it online!](https://tio.run/##y0rNyan8///hzpnH1himPdzRdar7WPv/h7u3HG6P/P8/MSkntbiEKzEpv6iEK70oNTWPK7Mom6u4BCTBBSaLQVR@EZAsSeQqSS0qSuQqS63gqswvBQA "Jelly – Try It Online")
### How it works
```
ṙƬ1fḊʋƇ Main link. Argument: A (array of strings)
ʋ Vier; combine the 4 preceding links into a dyadic chain.
Ƈ Comb; for each string s in A, call the chain with left argument s and
right argument A. Keep s iff the chain returned a truthy value.
Ƭ 'Til; keep calling the link to the left, until the results are no
longer unique. Return the array of unique results.
ṙ 1 Rotate the previous result (initially s) one unit to the left.
f Filter; keep only rotations that belong to A.
s is a rotonym iff there are at least two rotations of s in A.
Ḋ Deque; remove the first string (s) of the result.
The resulting array is non-empty / truthy iff s is a rotonym.
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 20 bytes
Requires `⎕io←0`
```
⊂∩¨(,/(1↓∘∪⍳∘≢⌽¨⊂)¨)
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG9qZv6jtgkG/x91NT3qWHlohYaOvobho7bJjzpmPOpY9ah3M4jRuehRz95DK4BqNA@t0PyfBtTxqLcPqNnT/1FX86H1xo/aJgJ5wUHOQDLEwzP4f5qCemJSTmpxiTqIkV8EotOLUlPzgHRmUTaQLC4BKQAywHQxhJFfBKZLEkFUalERiC5LrQCSlfml6gA "APL (Dyalog) – Try It Online")
`(1↓∘∪⍳∘≢⌽¨⊂)¨` gets the unique rotations (excluding the string itself) of each string in the dictionary
`≢` takes the length of a vector
`⍳∘≢` creates the range from 0 up to the length
`⌽` rotates a vector some number of times, e.g 2⌽'abort' -> 'ortab'
`⍳∘≢⌽¨⊂` will then give all the rotations of a vector
`∪` removes the duplicates
`1↓` removes the first element (the original string)
`,/` flattens all the rotations into one list
`⊂∩¨` takes the intersection of the dictionary with the rotations
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 26 bytes
```
g;?z{tWl⟧₆∋I;W↺₍R;W≠&h∋R}ˢ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/P93avqq6JDzn0fzlj5raHnV0e1qHP2rb9aipNwjI6FyglgEUC6o9vej//2ilxKSc1OISJR0gI78IRKcXpabmAenMomwgWVwCUgBkgOliCCO/CEyXJIKo1KIiEF2WWgEkK/NLlWL/RwEA "Brachylog – Try It Online")
```
g;?z % Zip the whole input with each word in it respectively
{ }ˢ % Apply this predicate to each pair in the zip
% and select the successful values
tW % Let the current word be W
l⟧₆∋I % There exists a number I from 1 to length(W)-1
;W↺₍R % And R is the result of circularly shifting the
% current word I times
;W≠ % And R is not the current word itself (needed for words like "tata")
&h∋R % And R is one of the input dictionary words
% (R is implicitly the output of the predicate, and
% successful R values are collected and output by the ˢ)
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~73~~ ~~69~~ 67 bytes
```
lambda d:[w for w in d if{w[i:]+w[:i]for i in range(len(w))}-{w}&d]
```
[Try it online!](https://tio.run/##JcrBDsIgEATQX9mTQNSLxyZ@Se2BhqVurNAsVGwavh2hXuZNMrNs8endrdj7o8z6PRoNpusTWM@QgBwYILunnrrhnPqOhjZQG1i7CeWMTial8nVP@WSGsjC5CFbuQo8zhigutXhuTozoqsSvmiG2Qy2H4V88H0bdQObmB781N7@KrMoP "Python 2 – Try It Online")
Takes a set of words (lowercase), and returns a list of rotonyms.
---
Saved
* -2 bytes, thanks to ovs
[Answer]
# [K (ngn/k)](https://github.com/ngn/k), 23 bytes
```
{x^x^,/1_'(,/|0 1_)\'x}
```
[Try it online!](https://tio.run/##5Vjpbtw2EP7vpxCMArGBFEn@2o@SkyvOSszyUClys9o0fXV3LkpaI32CAtbMN7zm4HDI9enPOMSXl@PTz8uXy5e37z58ffPw9t3f77sPXx8/vbn8eilPP83TfXf/6eH90/3945f7T/H@rus6@F3jHx/hn/x07Mzzt3R6fvh2NM4/m2d4zo@ff92Vj5/pezEHD3PpzCHl0g0ZIHYun7q5UEfHdCaWMtJiugI5m@4Ml25J9e5m9m/m3JnO0J@nzzmkAb9IINuzQUUEfiR/JJCiUNc3zhMJFWhAOivqxD9D38HCyLyy2DMRaGge8YWZi62BkCN9hOe@zooK8xPTgoP8hvyiWKcVDAnx6nW2MOtExfHIlBd0s4k9CIIsfAZLwDtoRgnU5X2K3BjYkTBBZjFa6SbO0VYsiwkSQxlv/bmhAJFt4igjK8BmTwWdl7WzCYfEwHFXLmNOc8MOHTZ5h5vF3D@DUKtMbEEQYdYBzQCNxDw4ZqNQnTmuU8fd3NHfoDZiXdEZYezZzLs4z06sK5ho7srmlRa5orQtUMSkIr4iE2s0LrrhpSQnQPKtVNmaM9OLk5y5OFHBGilVOVcxS1LggCNamFlneYiR1tkJ27h2F1mYQC9IYnGARehcQIY6pqkIFTWpxOq94xRFYR7dRCjD2UkUGuSYqiAbqwI7v@LdKHH/QC19qj4F8tayidaQERayM1EBK7NSNCx6IjtBKLam0lrUAIHntZUtsQ5Yg1t71CqLAY7C9fwq4rArVntE8EvDiY5DdqKAG3rKGi4pKgMdGDdvDRh3t/UPgCVq05pG2pYMWCzC8qox3bRNaX6leu7TBDfSNrqMKWO52vTWzaKzGfaOpzPaKxljKxchYnFuoAhoTENetbzReKCijTQL1VIGPVijG6u4hhWTqXx4wA10snmzgPcaPB9T0E1A3oM2FOkP6O3IHjE@McDar@NL5roGaAfeRQPvK/DGUTxgcmVcgujIFjgZCJwdV1SE61JZR60@MVoaKgpK69PoNMhBZUFilTPmntQQwm0DIdfY0hZ4zaIFZ3d54u2FpB/pAyaZaWHBeU@MluiZ0JnrF2zEGFshON0SsN7FAWNiSZdHB/EKORj6joUo3SzEC1HApp7u0X6kD/Ugw9zqUIPpLP1Z@gjgUCALPZUuyr@xy2ztrEr/49VwqEiwNBXg0df0VwWM/xWXmDBahtBAe4/ceaHeKMdU1g6fiCes5Jx1O@zmsImKyzJhBiFaZ2aic6CF6agpa6LBJATF7phyUJwmtUAEWrJSqUcWLUk/HAkL3T3XinkImLsYcu9Q7LF84AlkhFtZFLlIndbSjKE4yB4t32Oyrjq6ua7VgzvRQD@679/NSMhFjCbyE@4LN1QmeNyZ0y13rYEuCuKHlHI9IWKtnPrIFg54nQy/Pq611IFiX2s@g7dkzRW1/jDx6gYyB93khxGCOPDRXRGHfBMKCaXIpMJFLe4gGbUMhonFaomHUiHtFyJ8BCl3dgVGRnmmsWTTANYcQlOasKqCDhDJ8XqsfZH8WoYIwTQuOy6Y8lVhuekgKdVdp45MByoV4w46cyOUVyKviPdJX2S1ZBEufgdFqQpuj/u9MIedlNpiCQsKAW8O@FAQ15P4mkIzRnOioWRq1ufcb9rWNaj1iLeNBLc14GO83LQEevN4Kv1bW8oHdztqnkaISXZWm/D9NWEt2I2STVXczJDV4UZSXSlPY3OMscaIhRaisPSguyBw19zGRKFQVQ/O3iFVgbnVMkRwm40CGrXvY/GmW11DrLZMHrWp81oOG9pWIimuUKMnUN1gYYNpG93UzwZLD/6GIoe1RVbXg4JbAzkowk1SmxjDCnODuGNxuBFcDau4dWjQCO7COWPuCir0k6pXeFFTNDalaV5HpIPUSsYaB3xHNbPU1WtajQiGvQxMeJVAZRUp6wj0Ymt8bQAJCWOZQ0hWD6I2JJ8G7WPE4RLMBjJcBCy6nF/mFRWdLJbpw4GR2LcGK2y5xxB3wZTWsTREYdEx8u5g5LZlm2a@x7zCcfWvQD@@wuqRSvMmiFdNHf8e8a3tKppLukh3zRyEDHLxLFnZwgwNCMy4eJaRM@iKKUrarleMOv72upP/H4T2e7/ffli3X8nyQvu/Pqnu/gU "K (ngn/k) – Try It Online")
`{` `}` is a function with argument `x`
`0 1_` cuts a string at indices 0 and 1, e.g. `"abcd"` -> `(,"a";"bcd")`
`|` reverses the two slices: `("bcd";,"a")`
`,/` joins them: `"bcda"`
`(,/|0 1_)\` returns all rotations of a string
`(,/|0 1_)\'x` are the rotations of each string in `x`
`1_'` drops the first "rotation" of each, i.e. each trivial identity rotation
`,/` join
`x^y` is the list `x` without elements of the list `y`
`x^x^y` is the intersection of `x` and `y`
[Answer]
# JavaScript (Node.js), ~~105~~ 99 bytes
```
f=l=>l.filter(w=>[...Array(k=w.length)].map((x,i)=>(w+w).substr(i,k)).some(r=>l.includes(r)&&r!=w))
```
Ungolfed:
```
f = list =>
list.filter( word =>
// create a list of all rotonyms for the current word
[ ...Array( len = word.length ) ]
.map( (x,i) =>
( word+word ).substr(i, len)
)
// check if any of the rotonyms is in the initial dictionary/wordlist
.some( rotonym =>
list.includes( rotonym )
// and is not the word itself
&& rotonym != word
)
```
[Try it online!](https://tio.run/##bVdpjus2DL7KdH4UCfqaG8wDeo6iPxSLsfWixdWSjH35KTfZzqBATH7Uwk0U7fwyD1OG7Ob6Z0wWvr5uH/7jp7/cnK@QT8@Pn39fLpe/cjbL6f7xvHiIY53O/1yCmU@nzx/u/PHz9Pzjeb6Udi01n9yP@xmFFOCUSZGLg28Wyimff/89//bxPJ@/hhRL8nDxaTzdTu/mzdDP0@Mc0oBPJJDtw@Q7g2fyNwIpCnVD57yRUIUOZLK9mSv@DD1XCxPzxuLARKChfcQXZi72AUKO7BEuQyuKKvM704qL/I78oli31ZSZN6@7hVknJm43pqzQFRMHEARZeAFLwDvoTglU9T5FHgwcSJghsxitTBM3V7@NiTJB4ijjfT53FCCyT5xlZBXY7bli8KI7m3BNDBxP5TrlVDp2GLDJB9w95vkCQq0y8QVBhKILugOaiTI6ZpNQ3TltW6fD3sm/oL5i0@iMMI6s8CmW4sS7ioXmVnav9sxVpV1BFZeqxIpMvNG86IHXmpwAqbfa5GgeTD@d1MynExNskUqVaxWrBG9PEbQws87yEiOjxQnbuU5XUUxgECS5uMIitFSQpY5pqkLFTKqxee@4RFEok5sJZXg4yUKHnFMV5GBV4OA3fFgl4V9pZEjNp0DRWnbRGnLCQnYmKmBj2DN4AiORkyAU@1DtI@qAwMc2yp5YB2zBbTPqlcUER@F6fxVx2hWrPyL4peNE1yE7McADA1UNtxSVgS6MK/sA5t3t8yNgi9qtpomOJQM2i7B8G0wvY3Mq30yXIc3wIu2r65Qytqvdbts9epjxGHh6oL9SMbZxEyIWSwdVQGea8qbtjdYDNW2kWai2MhjAGj1YxS1smFzlywNupJvNhwV81uD5moIeAvIBdKDKfMBoJ46I8Z0B9n5dXzP3NUA/8N018rkCHxzlA2ZXpyWIjWyBi4HAw3FHRbipyrpqi4nR0lFVUPucZqdDTioLkqucsfakhxDuBwi5xV62wDqrNhwv9yBlog3JMNEDTDLTyoLznhipGJjQnRsWHMQcWyG43RKw3sURc2LJlscA8RVyNfTcKlF6sxCvRAGHBnqPDhM9aAcZ1tYbWjBvln6WHgK4FMhDT62L6m96y@xtUaNvRTor00IMfUXakGBrqsCr1/RvA8z/iipmzJYhNNLZI3deqDfKsZR1wifiCTs5V90BuxJ2UXFdZqwgRNvOTLQEUkxXTVkXDRYhKHa3lIPiNKsHIpDKRq0eWbQkPR0JC7171oZ1CFi7mHLvUBywfeANZIRHWRW5SJPW0o6xOsgePT9i8q45enOtzYO700I/uV@/zETIRcwm8jueCw80JnjdmdNbbm2BXhTErynldkfEVrn0kS2c8DYb/vpYW20j5b61/ABvyZsVrT5NXN1I7mCY/GGEII58dTfEKd@FSkKtsqlyU4sHSE4to2FisVvipVRI54UIP4KUO7sBI6s801iz6QB7DqE5zdhVQReI5FgfW1@kvpYxQjCdy4kLpnpVWF8mSErtMKkr05VaxXSAzrwI9ZvIGvF9MlTRlizCxR@gGFXBHfFwFEo4SKkrS9hQCHhzxQ8FCT1JrCl0Z7QmOkqmZf2c@5@xTQeN3vBtI8ntA/gxXl9GAn3zeGr9@1jKV/e6qswTxCQnq0P4/TVjLziskkNV3N0Q7fAiqa2U56kHxlhzxEJPUVgG0FMQeBjua6JQaGoHdx@QmsDa6hUiuO9GAZ06zrH4Mq2hIVZfZo/WNHhthx3tmkiKG9TsCdQwWNhh2ld388Vg68H/UBSwjoh2vSh4NJCDIjwk9YkxbDB3iCcWxxfBtbCJ@4QmjeAhnQVrV1Clv1SDwk91RXNTu@VtRbpKr2SsecDvqO6WhrqmzYlgOMrAhLUEaqtI2UagL7bOtwGQlDCWPYREexCzIeE/XJ1jxOkSzA4yXAQsqs4vZUNVN4tn@uHASPzbkhX22mOIp2Bqn1g6orToGvnuYOR2td0yv8e8wmmLr8IwfcMakUplFySqbo7/j/g@torlmj5lumVOQgZ58SxZ2cIMHQjMuHnWiStoxRIla@uKWcf/Xu@XMuO34en97f18Pn/9Bw "JavaScript (Node.js) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes
```
εDvDÀ})ÙåO<Ā}Ï
```
[Try it online!](https://tio.run/##MzBNTDJM/f//3FaXMpfDDbWah2ceXupvc6Sh9nD////R6olJOanFJeo6CkBWfhGYkV6UmpoHYmQWZYOo4hKQIhALzCiGsvKLIIySRDCdWlQEZpSlVoCoyvxS9VgA "05AB1E – Try It Online")
**Explanation**
```
ε } # apply to each word in the input
Dv } # for each letter in the word
DÀ # copy the previous word and rotate it left
)Ù # wrap the rotations in a list and remove duplicates
å # check each rotation for presence in the input
O # sum presences
<Ā # decrement the sum and truthify it (check if 1 or greater)
Ï # filter, keep words in input that are true in the resulting list
```
[Answer]
# [PynTree](https://github.com/alexander-liao/pyn-tree), 44 bytes
```
§y:f#x0€[x/|Ḟz&⁻xzėzḞw+#x`wLx#x`0wRLxy]y#\x1
```
[Try it online!](https://tio.run/##K6jM0y0pSk39H@D8/9DySqs05QqDR01roiv0ax7umFel9qhxd0XVkelVQE65tnJFQrlPBZA0KA/yqaiMrVSOqTD87/q/Wj0xKSe1uERdB8jILwLR6UAz84B0ZlE2kCwuASkAMsB0MYSRXwSmSxJBVGpREYguS60AkpX5peq1/3WBDkvMKy7IzEm1BQA "PynTree – Try It Online")
This turned out to reveal a major flaw in the way PynTree constructs list comprehensions because it uses functions to assign variables so that assignment can go in expressions, but then the conditions end up not having the value of the variable until after it has been evaluated and the main block has been evaluated. This appears to be easily fixable but I did not notice this earlier and so this answer is hideously long.
Actually even if I fixed that I think it still might be terribly long.
[Answer]
# [Perl 6](https://perl6.org), 65 bytes
```
{@^a.grep:{@a∋any(($/=[.comb]).rotate,*.rotate...^*eq$/).join}}
```
[Try it](https://tio.run/##LYzBCoJAFEX37ytmEaESz52LQvA/IuFpr7B0xt6M0iDug/6yH5k02px74cDpWdosDJbVmGF9AOi82tbmzCoPU1ESXoX7/VTQ5/Um7aNok@ZHrE1XnWIU48jxLvkfRCwTfmzSGG@m0fMc0JJXFyNqLUZto9nGgaqWrQOqjDhY8qyhkTtYtwr40a5jZKEjcCxCMPITvBm@ "Perl 6 – Try It Online")
## Expanded:
```
{ # bare block lambda with placeholder parameter @a
@^a # declare and use placeholder parameter
.grep: # find the values that match
{
@a
∋ # Set contains operator
any( # create a junction of the following
# generate a sequence
(
$/ = # store into $/ (no declaration needed for this variable)
[ # turn into an array instead of a one-time sequence
.comb # the input split into characters
]
).rotate, # start the sequence on the first rotation
*.rotate # use this to generate the rest of the values in the sequence
...^ # keep generating values until: (and throw out last value)
* eq $/ # one of them matches the cached array of the input
).join # for each array in the junction join the strings (no spaces)
}
}
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~66~~ ~~55~~ 70 bytes
```
lambda d:{w for w in d for v in d if v not in w not in v in w*2in v*3}
```
[Try it online!](https://tio.run/##NczBDsIgDAbgV@kNXTzNm4lv4gUCKHHCUupwWfbsaItc@n9Nm39e6ZHiWP31Vif9MlaDvWwFfEIoECJY4dIY/E8xEW@lQ25lGJnDea8zhkjgD5vSZnKZ1AmUltGm0aZnV0L5uqNzkRHwyZGJG1iC/FfCBpI@coiCxX041vRW@7F@AQ "Python 2 – Try It Online")
11 bytes thx to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis) to use chained `x in y in z` approach.
Takes a set of words `d`; returns a set of Rotonyms.
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), 131 bytes
```
($t=$args|%{@{r=0..($l=($k=$_).Length-1)|%{-join$k[-$_..($l-$_)]}
w=$_}})|%{$u=$_
$t|?{$u.w-ne$_.w-and$u.w-in$_.r}|%{$_.w}}|sort|gu
```
[Try it online!](https://tio.run/##5Vhfb9w2DH/OfQojuK4J1hy6vQcL0NcBG5a9FUOhsxlbiWy5@nOJr7nP3vGfbF/QfYIBOfJHiSIpiqbljP4ZQuzAuZvaB/i@fbj99v1qm263JrTx9d23u2/h9uNud7V1t1fbp9vtl@vd7zC0qbv55Rqnbx69HbZPn2@2X1gJ@fU/p80zKp5OpLDNCDfb9Pobwt3zzQCo@XxjhoZFXPxlF06kiMOn02v0Ib22@ftps7m72lTVh7urS7N3EFNl9jhXtQFgqGx4qmKiiYppJOYD0mSqBCGY6gAv1eTz5Yfq3MAPll1ez57qqt6bt67IxqJTGfpz9LMWaY@/gUBoDgbjIvDs3QMBPwi1deG8kFCCAmQyo1f8I@dm30DHPLNYMxFoaB3xiZkdygAhS/4IxzpHRYn5E9OESm5BblKsyxJmkHh2ulpYY8XFwwNTNmijGWoQBEF4hIaAs1CCEqjmnR94sOeN9CMEFodGponzySgWY4IkUMbLfCioh4Fj4iwjS8Bhjwk3L7aD6feegeWpkLrgY8EWN2zCCpeIeT6C0EaZxIJggKgKJQDNRGwts06oruzmpd1qbefOUNGYLVojjHcW@RRjtBJdwkKzRw4vlcwlpcVAkpCS7BWZRKN50QNPyVsBUm8py9EcmL5YqZkXKy7YI5Uq1ypWie854YgmZo1tWMXIaLTCFq7TSQwTqAVJLvYwCY0JRNUy9UmouPFpyM5ZLlEUYmdHQgEOVrJQIOdUBTlYFXjzM15pyfb3NFL77HxPu204xMZQEA0EawYF7KyRBtPgTuQkCA1lKJURDUDgYR7lSBoL7MHOMxpVgwkehOvzq4jTrljjEcFNBXt6HIIVBzxQU9VwS1EZ6IGxcRnAvNtlvgVsUYtX39GxBMBm0U9vBv3Z2OjjG9ex9iOcSYt26nzAdrX4zUtEB9OuN@4PGK9UTJO5CREbYgFJQGGa8qztjfSBmjbSIFRbGdTQGD1YxbmfMYXKDw/Ylp5sPizgswbHjynoISCvQQeSzPe42453xPiJAfZ@1U@B@xpgHPjqavlcgQ@O8gGjTd3Ui4/QABcDgYPljopwNhVUa94To6mgpCCVOc1OgZxUFiRXIWDtSQ8hXA4QQh5K2QLbTNpwVi9afHshqTv6AZPANLFgnSNGJmom9MzVEw5ijhshuLwh0Dg7tJiThnw53CC@QvaGfg@JKL1ZiCeigEM1vUfrjn7oBxnWVoUeTNXQX0M/AqgKFKGj1kX111WBo43q9D8uGfuMBFtTAtY@@q8ZMP9HNDFitgyhls4euXVCnVGOpawTzhP32Mm56lbYxn4RFadpxApCNK8MRGNPhulRU1ZEg0UIiu2DD71iP2oEIpDJTK0e2dCQ9GxJmOjdc8xYh4C1iyl3FsUa2wc@gYzwKJMiO9Bk09CKNlkIDiNfY4ouW3pzHbMD@0SKrrOPj6YjZAfMJvInPBceyEzwcWdOb7lj7ulFQXzvfchPiNgrlz6yiROeR8O3j2NOuaXc5xwO4BqK5ohen81wtC2Fg9vkixGCoeVHd0ac8kVIJKQkixI3tWEFKaipNUwa7Jb4UCqk80KElyDltpmBES3HdEjBFIA9h9DoR@yqoAoiWbbH3iepr6kdoDeFy4kLpnpVmM4mSPJ5Namafk@toltBa86E9EZki/g@qZNY8w3Cya2gOFXBrnG9FmK/knwx5rGhEHBmjxcF2bqXvfq@BKM1UZA3Oeh17gdjsw0afcC3jSS3DOBlPJ2N9HTncdT6lzEf9vZcK44dDF5OVofw/jViL1hpyaEqLmGIdTiT1JcPY1c2xlhzxEJJUT/VoKcgcDVcdAahkNUPrl4hdYG1VSpEcFmNAga1nmPxbFq3hlhjGR16081rOyxosUTSMEPNnkDdBgsL9It2cR8Nth78hqIN64hY1wcFjwZCrwgPSWNiDDMMBeKJDe2ZYHM/i8uEJo3gKp0Ra1dQok@qWuGLhqK5ScXzrOH30isZax7wHlXC0q0e/RxEb3iXPRO20lNbRco@erqxFT4PgKSEsawhJNZ7cdt751udY8TpEswBMpwETGrOTXFGSRdLZHpxYCTxzcnql9pjiKdgUpmYCqK0qI7cOxjZxWzxzO8xp7Cb95eg7t5g3ZFKcRFkV8Udf4@4MnYUz8m/yHQOnIQA8uKZgrKJGQbQM@PmmTquoCOWKHk7HjHr@O3F/5Tg/wT05ZO/Xr6ty4eyXNL@r7eqy@vNdfVavau@bS622NrSJ6z7D9UWXkb8@MCb@G21/bKauh/xtk2DZaC6iTx0WV2iWoCYHc3/tH2o7s4WbS4@/3n/KUd86v7YP6Lxf@7Q58U9Xmzog/R25fMGvlZXxRb/86t6X72/Ru2/i9dVBLv7vL/HC9zQXn38UP368br6ubrc7XYYz8VfJR61trk4bU6b7/8C "PowerShell Core – Try It Online")
For each word in the list, create generate a list of all its rotations
Then look for a matching rotation with a different original word
If it exists, keep the word.
Then sort and deduplicate them.
Sorting is required in PowerShell as `Get-Unique` only works on sorted lists.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~71~~ 62 bytes
```
^(\w)(\w*)
$2$1!¶$&
%+)s`^(.+)(!.*¶\1)$
$2
O`
!`\b(.+)(?=¶\1!)
```
[Try it online!](https://tio.run/##HYlRCsIwFAT/9xaBKHktFOq/eAQvEEoSCFKUBl6eVS/WA/RiMenHzsIMR5kXX8pk7IfqOoK@6FHtmz7j1FN2kxl6Mmro9s2OpGvG3UE5G45wuzavqBQfXjELfEgseHCMC2Z@IksLOJjbJa4UD4nMHmv84pfefw "Retina 0.8.2 – Try It Online") Explanation:
```
%+)
```
Repeat for each word.
```
^(\w)(\w*)
$2$1!¶$&
```
Prepend the next rotation of the word with a trailing `!`.
```
s`^(.+)(!.*¶\1)$
$2
```
But if that's the original word, then delete it again.
```
O`
```
Sort the words.
```
!`\b(.+)(?=¶\1!)
```
Find the duplicates.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 17 bytes
*Extremely* slow, but works. TIO times out, but I confirmed it works by manually lowering the number of iterations in the language source.
```
f@_XéZ ÀX©UøXéZ}a
f@ // Filter the input array by
_ }a // generating up to 1e8 rotations of each string
XéZ ÀX // and checking if the rotation is different than the original,
©UøXéZ // yet still exists in the input array.
```
[Try it online!](https://tio.run/##y0osKPn/P80hPuLwyiiFww0Rh1aGHt4B4tQm/v8frV5ckpiUk6quow6miyEM9VgA "Japt – Try It Online")
[Answer]
## Javascript, 129 Chars
```
f=a=>{n={};r=w=>w.slice(1,w.length)+w[0];a.map(w=>{m=r(w);while(m!=w){if(-~a.indexOf(m))n[m]=1;m=r(m);}});return Object.keys(n);}
```
## Ungolfed
```
f=a=>{
n={};
r=w=>w.slice(1,w.length)+w[0];
a.map(w=>{
m=r(w);
while(m!=w){
if(-~a.indexOf(m))n[m]=1;
m=r(m);
}
});
return Object.keys(n);
}
```
[Try it online!](https://tio.run/##JYpRrsIgEEW34uvXEJXoN8EtuICmH1inFYWhGVA0Td/W@8D3c89J7rmbl4k92yntKVxxXQdt9GkmPS@KddanLKOzPcJxl6VDGtNNbHN76JSR3kxQitlrhixUvlmH4H90FrMdYP9rpKUrvs8DeCGo9Z0@qtp6oZZFKMb0ZNqcL3fsk3zgJwKVZ@0DxeBQujDCAG1jLg5janZFAleOjEiFlh9lY6pBkS/jvwT@MpkKZK584bvsJzybTgi1/gE)
[Answer]
# [Java (JDK 10)](http://jdk.java.net/), 144 bytes
```
l->{for(var s:l){var r=s;for(int i=s.length();i-->1;){r=r.substring(1)+r.charAt(0);if(!r.equals(s)&l.contains(r)){System.out.println(s);i=0;}}}}
```
[Try it online!](https://tio.run/##bVA9b8IwEN35FVeGym6NBWtDIiHWdmKsOpjUCQbHTu/OqCjit1MnqFPr4d35vXcfuqM5m8Xx83RzXR@R4Zj/OrHz@qmY/eGaFGp2MfwrEqM13SjV3hDBm3EBhhlAn/be1UBsOIdzdJ/QZU3sGF1o3z/AYEtysgJsY6DUWVxvo/d2mra@G6sKGihvflENTURxNgj04uUwJlhSMZIuMLiStLeh5YOQhVssqlUhByxRU9rT1Ems5DPq@mBww2KZTY14QG2/kvEkSD56XcfAeUUSKOWwuxDbTsfEus/l7EM2Fa5cFtf8bsW09wSvjvh3W/BQwgbRXEgbGhUxN3tviZXZ58upFq0NyuFJ5ctkQU1IY4iYkY1im@vV2X6rS0xzTb13uYuaS3kf2mhT17Zn4SfiOrvefgA "Java (JDK 10) – Try It Online")
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~100~~ 94 bytes
```
x=>x.Where(y=>y.Select((z,i)=>x.Where(c=>c!=y).Contains(y.Remove(0,i)+y.Remove(i))).Any(b=>b))
```
[Try it online!](https://tio.run/##dZJNT8MwDIbP7a8IOyViRNy7Vpr4lkBC7LBzmpktok3AScsK2m8v7lgBTUGqVPl9XsdObO3PtEPoG2/smi06H6DO0r@RvHBVBToYZ728AQto9JHj3ti3LE11pbxnj@jWqOr0M01em7IymvmgAv1aZ1bsQRnLRZoQTVqFLIAPlyooljML7@xW@c0CwswHpPMLLjLyjR45X634RJUVxZMocRgFawSwMWDwJSZTw1QkRvbA/0McxkFQUR0Qo6CFbUzuXPMt03fdWD07eqvp3ZVtasChw1ErGLrgBje975Dab/NiK5cbQOBdXnRyAcNsOf@YGvGLdF7ok7wTNHsbaGKed/IJatcCPyfj6U9khBBybjte5kUpRJ8k2WGwCL6pApUdO@DjdfaXeKalU3rDBys1y4w9ZNBuJAmV9a4CuUQTgLYLOHmGvF26678A "C# (.NET Core) – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 66 bytes
```
s=>s.filter(t=>s.some(u=>(t+t).match(u)&&t!=u&t.length==u.length))
```
[Try it online!](https://tio.run/##bVdpcus2DL5K@udNMp3mBnlnCS3CEl@4qCToRL58io2SnOmMBXwAFywEIfmPu7k21bDiP7l4@L6@fbe33@31GiJCfUbGrSR47m@/n/FvfHlNDqflub/8@oV/vfVf@Bohz7i8vXVDLy/fU8mtRHiNZX6@Pr@7J8e/yE8IRBM9mUH1N1c/BHyWeGVQstIwDS4LGSEMoIP9yV3o5/i5eFiEdxEnIQodr2O@CQt5KBgFtse4Tb0ZQuEfQpEmxQPFzbAtw1KF92irlfmgJq5XobJhaC5PoAiq8gaeQQwwnFJo28eSRZkkkLRCFTF7HWbuLnHX6WaK1FHBx3gdKEEWnyTLxBDE7RUpeN27unQpAoIMVVxqaQMHCtjVEx4ey3gDpd6Y@kIgQ7MJwwHLRJuDsEWprVz2pctp7RIf0Jix7xicMomsySm2FtQ7pEILd3EPR@bQ6NgA1SXUWImpN5YXO3DEEhRovWHXo7kJ/QpaM19BTYhFLlWpVaoSulFN0SbMBy9TnGpbUHZwG0bdmMGkSHNxgU1pQ9CpQWhBpWqmYO4xBilREtoSVkYVbkGzMKDk1AQ9WBMk@B2fZmn4F9ZMpceSOFovLnrHTniowWUDYsyDXDRPkehJMMpDhUNjDii87VrxxAcQC2EfMa88JTgrt/trSNJu2PxRIW4DF74ONagBUUxcNdJSTAa@MKEdCsp7OMZnoBZ1WC0LH0sFahZp@6EsD7q1tB@m21RWeJCO2biUSu3qsNsPj25uPgdebuSvVozv0oSY5TYAKhjMUt6tvfF84KZNtCq1VgYTeGcHa7inHbOrcnkgzHyz5bBAzhqiXFOwQyA@gSlQxxNFu0hEgj8EUO@3@VilrwH5Uaub5VxBDo7zAWvAZUtqo3qQYmBwC9JRCe5bVZu1xyRoGwgN4Biz7AwoSRVBc1Ur1Z72EMbjAKH2PMoWZE@0hhP1HpTKtBOZFn5ASBWKIoQYmfEWkxC@c9NGSsqxV0LLPQMfQ54pJ55tRQqQXiEXx88VmfKbhTkyBVJN/B6dFn7IDjGqrSey4J48/zw/DGgqsIeRWxfX3/JUxdtmRp@adlahjRn5SrQTodaEILPv5d8OlP87bbFSthyjmc@eeIhKozNOpWwDsTAv1Mml6k44tHSIhnFbqYII7Ssr05Z4Y75qxoboqAjBcLiWmgyX1TxQgbfs3OqJZc/SZ2Bh43fPvVMdAtUupTwGEidqH3QDBdFRoqGQedB7XjFjgBrJ8zNm73rgN9e9RwgfPDEu4c8ftzAKmbJJ/IPORRRdCF134fyWu/fELwrml1Jq/yAkVqX0iW2S8L46@fq4d@wz5773eoPo2Zs7Wf10@R5mdofClA8jAnmWq7sjSfkhIAuIugilqeUTZKe22Qnx1C3pUhrk8yJEH0HGg9@B01lRaMbqBqCew2gtK3VVsAkqBdlPrG9aX9ucIbnB9cQVc70axIcBlko/DdrMcuFWsZxgcA8C/hBlR3qfTKi7FU9wiyeoRk0IZzydhZZOUhmbFWooDKK70IeChl401pKGM1YTAxXXq33O/Y9u34O1V3rbaHKHgj7G8UGT@Jsncus/dKVewuOsti6Qi56sqej7a6VecJqlh2p4uKG7w4NktkpdlxGYYMuRCCNFaZvATkHhST3mZKXQzQ6tPiEzQbU1KkTxWE0COXUeE/Fh2EIjbL6skaxZ8NYOBzp2Yinv0LKn0MIQ4YDlmD3MN0eth/5DccCm0d3totDRQE2G6JDMJ8GwwzognVieH4TQ0y4eA5Y0hqd0NqpdRch/qSaDX@aK5QaH5X1GuWivFGx5oO@o4ZaFei@7E8lJlEmI7JK4rRIVG4m/2AbfFaApEaxrGOnuSc2mQv9wbUyQpEuxOChwU7DZdnFrO0JbrJ7Zh4Mg9W9PVjpqTyCdgsMxsA3EabE5@t0hKBzbDsvyHosGlz0@hGn5gS0ik9ohaFTDnPwfiUN3V8tYvnS4V0lCBX3xbNXYJowcSMKkeeIiFXSnEmVr9ztlnf57vb@2lb4N35/eX16@/wM "JavaScript (Node.js) – Try It Online")
boring answer
[Answer]
# [Ruby](https://www.ruby-lang.org/), 81 bytes
```
->a{a.select{|w,*b|w.scan(/(?=.)/){b<<$'+$`}
b[1..].any?{_1!=w&&a.include?(_1)}}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bVjJktxEEL1z4hOGCGNswOPwjYONb75x4OxwmJIqu1WeWkQtPaMez5dwcRDwUfA15FaSeoKIUebLWnKrrJR6_vgrt2H58ue7N3-3enjx0z-_vvjZ3JvrAh7Gev_59sfvh8-312U08dnLZ2_fXD9_-fx-eP36yXc_PPnt4avh_avr6w_XJi5v7z---ubN7dOn5trF0TcLb599fPX84eFBFP_79S_z1bv3396-N1eG_jw9ziEN-EQC2Z5MvmFwm_yBQIpC3dg5byRUoQOZbFdmwD9Dz2BhYt5YHJkINLSP-MLMxT5AyJE9wmVsRVFlfsO04iK_Ib8o1m01ZebN625h1omJw4EpK3TFxBEEQRZewBLwDrpTAlW9T5EHAwcSZsgsRivTxM3g1zFRJkgcZbzN544CRPaJs4ysArs9VwxedGcThsTA8VSuU06lY4cBm7zD3WOeLyDUKhNfEEQouqA7oJkoR8dsEqo7p3XrtNs7-QvUV6wanRHGkRU-xVKceFex0NyZ3as9c1VpV1DFpSqxIhNvNC964LUmJ0DqrTY5mhPTOyc1c-fEBFukUuVaxSpJgROOaGFmneUlRkaLE7Zxna6imMAoSHIxwCK0VJCljmmqQsVMqrF577hEUSiTmwllODnJQoecUxXkYFXg4Fe8WyXhDzQypuZToGgtu2gNOWEhOxMVsDELfNEsRiInQSj2odpH1AGBp3WUPbEO2IJbZ9QriwmOwvX-KuK0K1Z_RPBLx4muQ3ZigAdGqhpuKSoDXRhXtgHMu9vmj4AtarOaJjqWjN01heXRYLoYm1N5ZLqMaYYLaVtdp5SxXW122-bRyRz3gacT-isVYxs3IWKxdFAFdKYpb9reaD1Q00aahWorgxGs0YNV3MKKyVW-POCOdLP5sIDPGjxfU9BDQD6CDlSZDxjtxBExvmGAvV_X18x9DdCPnM2RzxX44CgfMLs6LUFsZAtcDAROjjsqwlVV1lVrTIyWjqqC2uc0Ox1yUlmQXOWMtSc9hHA_QMgt9rIF1lm14Xi5BykTbUjGiR5gkplWFpz3xEjFyITu3LjgIObYCsHtloD1Lh4xJ5ZseQwQXyGDoedQidKbhXglCjg00nt0nOhBO8iwtq7Qgrmy9GfpIYBLgTz01Lqo_qarzN4WNXpVpLMyLcTQV6QNCbamCrz6nH5vgPk_o4oZs2UIHenskTsv1BvlWMo64RPxhJ2cq26HXQmbqLguM1YQonVnJloCKaarpqyLBosQFLtDykFxmtUDEUhlo1aPLFqSbh0JC717zg3rELB2MeXeoThi-8AbyAiPsipykSatpR3H6iB79HyPybvm6M11bh7cDS30k_v0yUyEXMRsIr_Bc-GBxgSvO3N6y51boBcF8SGl3G4QsVUufWQLJ7zNhr8-zq22I-W-tXwCb8mbM1q9NfHsjuQOhskfRgjika_uijjlm1BJqFU2VW5qcQfJqeVomFjslngpFdJ5IcKPIOXOrsDIKs801mw6wJ5DaE4zdlXQBSI51sfWF6mv5RghmM7lxAVTvSqsFxMkpbab1JVpoFYx7aAzF0J9JLJGfJ-MVbQli3DxOyhGVXB7PO6FEnZS6soSNhQC3gz4oSChJ4k1he6M1kRHybSsn3P_M7bqoNEDvm0kuX0AP8brxUigbx5PrX8bS3lwl6vKPEFMcrI6hN9fM_aC3So5VMXdDdEOF5LaSnmeemCMNUcs9BSFZQQ9BYG74b4mCoWmdnD3DqkJrK1eIYL7bhTQqf0cixfTGhpi9WX2aE2D13bY0aaJpLhCzZ5ADYOFDaZtdTdfDLYe_A1FAeuIaNeLgkcDOSjCQ1KfGMMKc4d4YvF4IbgWVnGb0KQR3KWzYO0KqvSTalR4p65obmq3vK5Ig_RKxpoH_I7qbmmo57Q6EQxHGZiwlkBtFSnbCPTF1vk6AJISxrKHkGgPYjYkn446x4jTJZgdZLgIWFSdX8qKqm4Wz_TDgZH4tyYrbLXHEE_B1D6xdERp0TXy3cHIbWq7ZX6PeYXTGl-FcXqENSKVyiZIVN0c_x7xfewslmu6k-mWOQkZ5MWzZGULM3QgMOPmWSeuoDOWKFk7nzHr-Nvrwwf5r8KXL8L_Aw)
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-f`](https://codegolf.meta.stackexchange.com/a/14339/), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
¬£éYÃøWkU
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWY&code=rKPpWcP4V2tV&input=WyJhYmxlc3QiLCJhYm9ydCIsImdyZWVuIiwiaXJrIiwic3RhYmxlIiwidGFibGVzIiwidGFib3IiLCJ0YXRhIiwidGVycmEiLCJ2ZXgiLCJ5b3UiXQ)
```
¬£éYÃøWkU :Implicit filter of each string U in input array W
¬ :Split
£ :Map each element at 0-based index Y
éY : Rotate U right Y times
à :End map
ø :Does that contain any element of
WkU : W with U removed
```
] |
[Question]
[
# Problem
Let's define a generalized [Cantor set](https://en.wikipedia.org/wiki/Cantor_set) by iteratively deleting some rational length segments from the middle of all intervals that haven't yet been deleted, starting from a single continuous interval.
Given the relative lengths of segments to delete or not, and the number of iterations to do, the problem is to write a [program or function](https://codegolf.meta.stackexchange.com/a/2422/60340) that outputs the relative lengths of the segments that have or have not been deleted after `n` iterations.
[![Example 3,1,1,1,2](https://i.stack.imgur.com/L1tVT.png)](https://i.stack.imgur.com/L1tVT.png)
Example: Iteratively delete the 4th and 6th eighth
# Input:
`n` – number of iterations, indexed starting from 0 or 1
`l` – list of segment lengths as positive integers with `gcd(l)=1` and odd length, representing the relative lengths of the parts that either stay as they are or get deleted, starting from a segment that doesn't get deleted. Since the list length is odd, the first and last segments never get deleted.
For example for the regular Cantor set this would be [1,1,1] for one third that stays, one third that gets deleted and again one third that doesn't.
# Output:
Integer list `o`, `gcd(o)=1`, of relative segment lengths in the `n`th iteration when the segments that weren't deleted in the previous iteration are replaced by a scaled down copy of the list `l`. The first iteration is just `[1]`. You can use any unambiguous [output](https://codegolf.meta.stackexchange.com/q/2447/60340) method, even unary.
# Examples
```
n=0, l=[3,1,1,1,2] → [1]
n=1, l=[3,1,1,1,2] → [3, 1, 1, 1, 2]
n=2, l=[3,1,1,1,2] → [9,3,3,3,6,8,3,1,1,1,2,8,6,2,2,2,4]
n=3, l=[5,2,3] → [125,50,75,100,75,30,45,200,75,30,45,60,45,18,27]
n=3, l=[1,1,1] → [1,1,1,3,1,1,1,9,1,1,1,3,1,1,1]
```
You can assume the input is valid. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program measured in bytes wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~15 13~~ 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-2 thanks to Dennis (using a Link rather than a chain allows right to be used implicitly by `¡`; No need to wrap the `1` in a list due to the fact that Jelly prints lists of one item the same as the item)
-1 thanks to Erik the Outgolfer (use `Ɗ` to save the newline from using `Ç`)
```
1×€³§JḤ$¦ẎƊ¡
```
A full program printing a list in Jelly format (so `[1]` is printed as `1`)
**[Try it online!](https://tio.run/##ASwA0/9qZWxsef//w5figqzCs8KnSuG4pCTCpuG6jgoxw4fCof///1s1LDIsM13/Mw "Jelly – Try It Online")**
### How?
```
1×€³§JḤ$¦ẎƊ¡ - Main link: segmentLengths; iterations
1 - literal 1 (start with a single segment of length 1)
¡ - repeat...
- ...times: implicitly use chain's right argument, iterations
Ɗ - ...do: last 3 links as a monad (with 1 then the previous output):
³ - (1) program's 3rd argument = segmentLengths
×€ - 1 multiply €ach (e.g. [1,2,3] ×€ [1,2,1] = [[1,4,3],[2,4,2],[3,6,3]])
¦ - 2 sparse application...
$ - (2) ...to: indices: last two links as a monad:
J - (2) range of length = [1,2,3,...,numberOfLists]
Ḥ - (2) double [2,4,6,...] (note: out-of bounds are ignored by ¦)
§ - (2) ...of: sum each (i.e. total the now split empty spaces)
Ẏ - 3 tighten (e.g. [[1,2,3],4,[5,6,7]] -> [1,2,3,4,5,6,7])
- implicit print
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~120~~ ~~107~~ ~~104~~ ~~103~~ ~~100~~ ~~99~~ 89 bytes
```
f=lambda n,l:n and[x*y for i,x in enumerate(l)for y in[f(n-1,l),[sum(l)**~-n]][i%2]]or[1]
```
[Try it online!](https://tio.run/##bU7bCoMwDH3fVxTGQCVCL/M22JeUPnSoTNAoTkFf9uuuFpw618BJcnKS02bsnjXyacrvpa4eqSYI5Q2JxlQO3kjyuiUFDKRAkmFfZa3uMqd0Z3o0pMwd9BmULshXX5mB5719VEoWF65U3UqmpqYtsCO5Q0EKYDa4cs/k8Iz4tIjZP7Gh5sQOyNdF/rsoExA2QojhOzJ1aHCO67osQAaGEasj4wEEFKIAGLVJULgazbYJLbIYeLQ7Za02p6zz8oMEdr2aPg "Python 2 – Try It Online")
---
Saved
* -10 bytes, thanks to Neil
[Answer]
# [R](https://www.r-project.org/), 94 bytes
```
f=function(n,a)"if"(n,unlist(Map(function(g,i)g(i),c(c,sum),split(m<-a%o%f(n-1,a),row(m)))),1)
```
[Try it online!](https://tio.run/##ZYwxCsMwDEX3HiMQkECB2qZbe4QewhgUBLEcYpse3xUZskR/0X9P6BiDP9w1NSkKShEn4cmWrpvUBt@4w6VXElxBkBIkqj0j1X2TBvm9xLnMDLo4@0BH@UFGG3I4GJ52H8id8YgPBncj/kaCkRd5Clc7LeL4Aw "R – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~76~~ 58 bytes
```
l%0=[1]
l%n=do(x,m)<-l%(n-1)`zip`cycle[l,[sum l]];map(*x)m
```
[Try it online!](https://tio.run/##TYpBCsIwEEX3OcUsDCSSQtPgyuYInmAINLQFg5M0WIXq5WPNQuRv3n@8q19vM1EpxFuL2jHiyU6L2FSUfUNcpEbL4R3yML5GmpEUrs8I5Nw5@iyOm4wl@pDAwrQw2N0F8j2kBxy@BwQapes6xyVgW4n9GjypThnHzZ@q/a7KBw "Haskell – Try It Online")
The function `(%)` takes the list of line lengths `l` as first argument and the number of iterations `n` as second input.
*Thanks to Angs and Ørjan Johansen for -18 bytes!*
[Answer]
## JavaScript (Firefox 42-57), 80 bytes
```
f=(n,l,i=0)=>n--?[for(x of l)for(y of(i^=1)?f(n,l):[eval(l.join`+`)**n])x*y]:[1]
```
Needs those specific versions because it uses both array comprehensions and exponentiation.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 71 bytes
```
l=>f=(n,c=1,e)=>n--?''+l.map(_=>(e=!e)?f(n,c*_):eval(l.join`+`)**n*c):c
```
[Try it online!](https://tio.run/##HcrBDoIwDADQu3/hiXZsS8AbpuPGTxgDyywGUjsiht@f0bzrW@MR9/Reto/T/OAyUBEKM4HaRI1lpKDO9VVVi3/FDUYKwHRm7OdfMSN2fEQB8WtedKonNEZNwi6V6yll3bOwl/yEAW4X2/y1d4QWsXwB "JavaScript (Node.js) – Try It Online")
[Answer]
# Java 10, 261 bytes
```
L->n->{if(n<1){L.clear();L.add(1);}else if(n>1){var C=new java.util.ArrayList<Integer>(L);for(int l=C.size(),i,x,t,s;n-->1;)for(i=x=0;i<L.size();){t=L.remove(i);if(i%2<1)for(;i%-~l<l;)L.add(i,C.get((i++-x)%l)*t);else{x++;s=0;for(int c:C)s+=c;L.add(i++,t*s);}}}}
```
Modifies the input-List instead of returning a new one to save bytes.
[Try it online.](https://tio.run/##xVPBitswEL33K3QJaNayWCf0UtmGYigU3NMeSw@qI4dJFdlI4zSpSX89lb3ebim7e@lCJR3E6OnN07zRXh91ut9@uzZWh8A@aXTjG8YCacKG7eOpHAitbAfXEHZOflg2@ePZe@/1ucZA@UdHZmd8KZ66WXUuDAfjf6NK1rLiWqelS8sRW@7yDMZaNtZoz0HVUm@3PAN1MTYYNgHKCDhqz6rCme/sJQW8BtV2nqMjZotKBvxhOAgUJ0EiKJemZaZgRhSn4lZhXi8YBSMVtfTm0B0NR1AxMa7WUduEVrhKf9rcKriXh6KSO0OcY5KkJ1hZuCFQk@DxlCQqROoHGc27CkJSNMvD4gVBNyE@L46rikWPqx@@2lj3pfzHDrfsEC3hd@TR7T5/YRomexgjE4jfCvZMHfhfsSB1mOMbkc1zDQDqkSl7Nab1qzFt/ifTW7EWm39mmdUsLJd7h/@0dqadWsOJF5uZ1YvrrdR9b8@xuaVuGtMTd4vCu3Mgc5DdQLKPrULWTT9gTnu5/gI)
```
L->n->{ // Method with List and integer parameters and no return-type
if(n<1){ // If `n` is 0:
L.clear(); // Remove everything from the List
L.add(1);} // And only add a single 1
// Else-if `n` is 1: Leave the List as is
else if(n>1){ // Else-if `n` is 2 or larger:
var C=new java.util.ArrayList<Integer>(L);
// Create a copy of the input-List
for(int l=C.size(), // Set `l` to the size of the input-List
i,x,t,s; // Index and temp integers
n-->1;) // Loop `n-1` times:
for(i=x=0; // Reset `x` to 0
i<L.size();){ // Inner loop `i` over the input-List
t=L.remove(i); // Remove the current item, saving its value in `t`
if(i%2<1) // If the current iteration is even:
for(;i%-~l<l;) // Loop over the copy-List
L.add(i,C.get((i++-x)%l)*t);
// And add the values multiplied by `t`
// at index `i` to the List `L`
else{ // Else (the current iteration is odd):
x++; // Increase `x` by 1
s=0;for(int c:C)s+=c;
// Calculate the sum of the copy-List
L.add(i++,t*s);}}}} // Add this sum multiplied by `t`
// at index `i` to the List `L`
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
Ø1××S¥ƭ€³Ẏ$¡Ṗ
```
[Try it online!](https://tio.run/##AS8A0P9qZWxsef//w5gxw5fDl1PCpcat4oKswrPhuo4kwqHhuZb///9bNSwgMiwgM13/Mw "Jelly – Try It Online")
Full program. Outputs `1` instead of `[1]`. Annoyingly, `ḋ` doesn't work like `×S¥` in this context, and `ƭ` doesn't work well with nilads. >\_<
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 20 bytes
```
{(∊⊢×⍵(+/⍵)⍴⍨≢)⍣⍺,1}
```
[Try it online!](https://tio.run/##VU07DoJQEOw5xXZAhMjjj7chGAyRBAM0xlBpjGBI7KzFxgNoQ@tN9iLPBX/wJpmd2Z3d569idb7242ShBrGfZVHAeYj700bCQ4VV8zxj/ZAmU2IZ6zvWNywbUlesW4UVnOddmKZYXlKSWG1DCrczMVmKeNyJoR/FIjUokhaCJhnAeuhyrjCBDT38tKCP@h5NOtjg/jOkbeIOpmBIFlUD6FGe6RZYGjgWMK0vhgYmBYbG7pm5oDu0/b752e7x/ccb@xc "APL (Dyalog Classic) – Try It Online")
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), 27 bytes
```
{x{,/y*(#y)#x}[(y;+/y)]/,1}
```
[Try it online!](https://tio.run/##VU3LCoMwELz3KxbsQVuLWWN87aeEgL1YimJBPBiD/fU0RhDLwOzMLLPbPYbXYG1bm9nEib6FgY6CeZWhpnuiI5XEuFo71eYql@9Yt3Imraj5dBQ27fPdk/O00Bip9TJJRhzQI6UYlUvwlBxqW5wsVcA9cijhSJ3OHW/ItgIn4SQnTAUIBoUAZH5wBplbnU3uGUtIi73qb@58fKjgz6sf "K (ngn/k) – Try It Online")
`{` `}` is a function with arguments `x` and `y`
`(y;+/y)` a pair of `y` and its sum
`{` `}[(y;+/y)]` projection (aka currying or partial application) of a dyadic function with one argument. `x` will be `(y;+/y)` and `y` will be the argument when applied.
`,1` singleton list containing 1
`x{` `}[` `]/` apply the projection `x` times
`(#y)#x` reshape to the length of the current result, i.e. alternate between the outer `y` and its sum
`y*` multiply each element of the above with the corresponding element of the current result
`,/` concatenate
[Answer]
# [Ruby](https://www.ruby-lang.org/), 73 bytes
```
->a,l{r=[1];a.times{s=p;r=r.flat_map{|x|(s=!s)?l.map{|y|x*y}:x*l.sum}};r}
```
[Try it online!](https://tio.run/##ZcnBCgIhFIXhfU9Ru2m4SSptEpsHEQmDhEBBrjOgqM9u5KbFcFb/d3B75W5lvzwMuIJSUS0MWT/@HUuUQaBEYp1Zn96EUlOdojzF8@LI6FzTnNs9zY7EzbcmsPVwtOoKigMdY1offkT3xPbEQd2AAf/n@LXuXw "Ruby – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 20 bytes
```
us.e?%k2*bsQ*LbQGE]1
```
Input is segment array `l`, then iterations `n`. Try it online [here](https://pyth.herokuapp.com/?code=us.e%3F%25k2%2AbsQ%2ALbQGE%5D1&input=%5B3%2C1%2C1%2C1%2C2%5D%0A2&debug=0), or verify all the test cases at once [here](https://pyth.herokuapp.com/?code=us.e%3F%25k2%2AbsQ%2ALbQGE%5D1&test_suite=1&test_suite_input=%5B3%2C1%2C1%2C1%2C2%5D%0A0%0A%5B3%2C1%2C1%2C1%2C2%5D%0A1%0A%5B3%2C1%2C1%2C1%2C2%5D%0A2%0A%5B5%2C2%2C3%5D%0A3%0A%5B1%2C1%2C1%5D%0A3&debug=0&input_size=2).
```
us.e?%k2*bsQ*LbQGE]1 Implicit, Q=1st arg (segment array), E=2nd arg (iterations)
u E Execute E times, with current value G...
]1 ... and initial value [1]:
.e G Map G, with element b and index k:
*bsQ Multiply b and the sum of Q {A}
*LbQ Multiply each value of Q by b {B}
?%k2 If k is odd, yield {A}, otherwise yield {B}
s Flatten the resulting nested array
```
] |
[Question]
[
Today's challenge is to draw a [binary tree](https://en.wikipedia.org/wiki/Binary_tree) as beautiful [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") like this example:
```
/\
/ \
/ \
/ \
/ \
/ \
/ \
/ \
/ \
/ \
/ \
/ \
/ \
/ \
/ \
/ \
/\ /\
/ \ / \
/ \ / \
/ \ / \
/ \ / \
/ \ / \
/ \ / \
/ \ / \
/\ /\ /\ /\
/ \ / \ / \ / \
/ \ / \ / \ / \
/ \ / \ / \ / \
/\ /\ /\ /\ /\ /\ /\ /\
/ \ / \ / \ / \ / \ / \ / \ / \
/\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
```
You will be given a positive integer as input. This input is the [height of the tree](https://stackoverflow.com/a/2603707/3524982). The above example has a height of six.
You may submit either a full-program or a function, and you are free to use any of our [default IO methods](http://meta.codegolf.stackexchange.com/q/2447/31716). For example, printing the tree, returning a string with newlines, returning a 2d char array, saving the tree to a file, etc. would all be allowed.
Trailing spaces on each line are permitted.
Here are some examples of inputs and their corresponding outputs:
```
1:
/\
2:
/\
/\/\
3:
/\
/ \
/\ /\
/\/\/\/\
4:
/\
/ \
/ \
/ \
/\ /\
/ \ / \
/\ /\ /\ /\
/\/\/\/\/\/\/\/\
5:
/\
/ \
/ \
/ \
/ \
/ \
/ \
/ \
/\ /\
/ \ / \
/ \ / \
/ \ / \
/\ /\ /\ /\
/ \ / \ / \ / \
/\ /\ /\ /\ /\ /\ /\ /\
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
```
Unfortunately, the output grows exponentially, so it's hard to show larger examples. [Here is a link](https://gist.github.com/DJMcMayhem/77a25b711283bf844698edb032dc924c) to the output for 8.
As usual, this is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so standard loopholes apply, and try to write the shortest program possible in whatever language you choose.
Happy golfing!
[Answer]
## Python 2, 77 bytes
```
S=s=i=2**input()
while s:print S/s*('/'+' '*(s-i)+'\\').center(s);i-=2;s/=s/i
```
Prints with trailing spaces, terminating with error.
I took this code from [my submission](http://golf.shinh.org/reveal.rb?Branching%20tree/xnor_1477113229&py) to [a challenge I posed on Anarchy Golf](http://golf.shinh.org/p.rb?Branching+tree), plus a [one-byte improvement](http://golf.shinh.org/reveal.rb?Branching+tree/xsot+%28xnor%29_1478252053&py) found by xsot. The hardcoded value of 128 was changed to `2**input()`.
The idea is that each row of the output is a segment copied one or more times. The half after the input split has one copy of each segment, the quarter after the next split has two copies, and so on, until the last line with many segments of `/\`.
Each segment had a `/` and `\`, with spaces in between, as well as on the outside to pad to the right length. The outer padding is done with `center`.
The variable `s` tracks the current with of each segment, and the number of segments is `S/s` so that the total width is the tree width `S`. The line number `i` counts down by 2's, and whenever the value `s` is half of it, a split occurs, and the segment width halves. This is done via the expression `s/=s/i`. When `i` reaches `0`, this gives an error that terminates the program.
Since anagolf only allows program submissions, I didn't explore the possibility of a recursive function, which I think is likely shorter.
[Answer]
# [V](https://github.com/DJMcMayhem/V), 32 bytes
```
é\é/ÀñLyPÄlx$X>>îò^llÄlxxbPò
|
```
[Try it online!](https://tio.run/nexus/v#@394ZczhlfqHGw6tPbxRzKcy4HBLToVKhJ3d4XWHN8Xl5IC4FUkBhzdx1fz/DwA "V – TIO Nexus")
Hexdump:
```
00000000: e95c e92f c0ad f116 4c79 50c4 6c78 2458 .\./....LyP.lx$X
00000010: 3e3e eef2 5e6c 6cc4 6c78 7862 50f2 0a7c >>..^ll.lxxbP..|
```
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 11 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
/║╶╷[l\;∔↔║
```
[Try it here!](https://dzaima.github.io/Canvas/?u=LyV1MjU1MSV1MjU3NiV1MjU3NyV1RkYzQiV1RkY0QyV1RkYzQyV1RkYxQiV1MjIxNCV1MjE5NCV1MjU1MQ__,i=NQ__,v=2)
Explanation:
```
/║ push `/\` ("/" palindromized so this is a Canvas object)
╶╷[ repeat input-1 times
l get the width of the ToS
\ create a diagonal that long
;∔ prepend that to the item below
↔ reverse the thing horizontally
║ and palindromize it horizontally
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~140 138~~ 135 bytes
```
e n=[1..n]>>" "
n!f=(e n++).(++e n)<$>f
f 0=[]
f n=1!f(n-1)++['/':e(2*n-2)++"\\"]
b n|n<2=f 1|t<-b$n-1,m<-2^(n-2)=m!f m++zipWith(++)t t
```
[Try it online!](https://tio.run/nexus/haskell#FY1Ba4QwEIXv/oq3Iqw2TboKhVKMUHrpsdBDD64F3U0wNI6isYWy/92Op/fNzDc8N0zjHPA6UphHr16mybtLG9yPgZSw44wyqfDbu0sPt8CRX6/myon32eyM0eKtXb6N93hSp2ho@aYxreEjzFBYyTsyC1OHBI@bAek6V4qaqooRR3SwOuWlEJlKhWDKuNFGFiddNxyk80NqE5J5JkR9fDg@m7S4I1nwGJ/PcRN1oBuVhbbIb6GU3e7eD6UsvtJd0wP/Y2D9z02fLvRckwWEbfsH "Haskell – TIO Nexus") Call with `b 5`, returns a list of strings.
**Pretty print usage:**
```
*Main> putStr . unlines $ b 5
/\
/ \
/ \
/ \
/ \
/ \
/ \
/ \
/\ /\
/ \ / \
/ \ / \
/ \ / \
/\ /\ /\ /\
/ \ / \ / \ / \
/\ /\ /\ /\ /\ /\ /\ /\
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
```
(some) **Explanation:**
* `e n` generates a string of `n` spaces
* `n!f` pads each string in the list of strings `f` with `n` spaces left and right
* `f n` draws a "peak" in a `n` by `2n` rectangle
* `b n` draws the binary tree by concatenating two smaller trees and centers a new peak above them
Edit: -3 bytes thanks to Zgarb!
[Answer]
## [J](http://jsoftware.com/), ~~49 43~~ 42 bytes
```
' /\'{~(|.,-)"1@(=@i.@#,-)^:(<:`(,:@,&*-))
```
This evaluates to a verb that takes a number and returns a 2D character array.
[Try it online!](https://tio.run/nexus/j#@5@uYGuloK6gH6NeXadRo6ejq6lk6KBh65Cp56AM5MRZadhYJWjoWDnoqGnpamr@T03OyFdIVzD5DwA "J – TIO Nexus")
## Explanation
I first construct a matrix of the values -1, 0 and 1 by iterating an auxiliary verb, and then replace the numbers by characters.
The auxiliary verb constructs the right half of the next iteration, then mirrors it horizontally to produce the rest.
In the following explanation, `,` concatenates 2D arrays vertically and 1D arrays horizontally.
```
' /\'{~(|.,-)"1@(=@i.@#,-)^:(<:`(,:@,&*-)) Input is n.
^:( ) Iterate this verb
<: n-1 times
`( ) starting from
,&*- the array 1 -1 (actually sign(n), sign(-n))
,:@ shaped into a 1x2 matrix:
Previous iteration is y.
# Take height of y,
i.@ turn into range
=@ and form array of self-equality.
This results in the identity
matrix with same height as y.
,- Concatenate with -y, pad with 0s.
( )"1@( ) Then do to every row:
|.,- Concatenate reversal to negation.
' /\'{~ Finally index entry-wise into string.
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes
```
FN«→↗⌈X²⊖ι‖M
```
[Try it online!](https://tio.run/##HYyxCoMwEEBn8xUZL2CXDh10bJcOigh@gE1PPYg5OaIdpN9@DX3jg/f8MornMahOLBaecdtTu68vFHDOnqZo@ECoepqX5GpTdEIxQTVsf1PaO1KgOEPHn5xcS/tAL7hiTPgGcpkc9TgF9KkhEc7f2nxVb3o5wg8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
N Input as a number
F « Loop over implicit range
→ Move right (because mirroring moves the cursor)
ι Current index
⊖ Decremented
X² Power of 2
⌈ Ceiling
↗ Draw diagonal line
‖M Mirror image
```
The line lengths are 1, 1, 2, 4, 8 ... 2^(N-2), thus the awkward calculation.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~20~~ 19 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
≡mX░R○k╣∙╒ab^◘⌐╖x▼;
```
[Run and debug it](https://staxlang.xyz/#p=f06d58b052096bb9f9d561625e08a9b7781f3b&i=1%0A3&a=1&m=2)
[Answer]
## JavaScript (ES6), 105 bytes
```
f=n=>n<2?"/\\":" "+f(n-1).split`/`[0].replace(/|/g,"$`$'$'/$`$`\\$'$'$` \n")+f(n-1).replace(/.*/g,"$&$&")
```
Works by building the result up recursively from the base case `/\`. The bottom half is just the previous case with each line duplicated. The top half was a little trickier; it looks as if you want to take the previous case and only keep the two sides but you also have to worry about padding the strings to double the width, so instead I do some regex magic. By taking the leading spaces from the previous case and splitting at every point, I can consider the spaces before and after that point. At each match the spaces before increase by 1 and the spaces after decrease by 1; this can be used to position the `/` and `\` in the correct places. The newlines and padding are also added here; this takes care of all the padding except a trailing space on each line and a leading space on the first line which I have to add manually. (Leading spaces on subsequent lines come from the matched string).
[Answer]
## Batch, 218 bytes
```
@echo off
set/a"n=1<<%1"
set s=set t=
%s%/\
set l=for /l %%i in (2,1,%n%)do call
%l% %s% %%t%%
%l%:l
:l
echo %t%
set/an-=1,m=n^&n-1
%s%%t: /=/ %
%s%%t:\ = \%
if %m% neq 0 exit/b
%s%%t:/ =/\%
%s%%t: \=/\%
```
Note: Line 6 ends in a space. Works by moving the branches left and right appropriately each time, except on rows that are 2n from the end, in which case the branches get forked instead.
[Answer]
# Haxe, 181 bytes
```
function g(n):String return(n-=2)==-1?"/\\":[for(y in 0...1<<n)[for(x in 0...4<<n)x+y+1==2<<n?"/":x-y==2<<n?"\\":" "].join("")].concat([for(y in g(n+1).split("\n"))y+y]).join("\n");
```
Or, with some optional whitespace:
```
function g(n):String
return
(n -= 2) == -1
? "/\\"
: [ for (y in 0...1 << n)
[ for (x in 0...4 << n)
x + y + 1 == 2 << n
? "/"
: x - y == 2 << n
? "\\"
: " "
].join("")
].concat([ for (y in g(n + 1).split("\n"))
y + y
]).join("\n");
```
I was working for a while on a solution which created an array of space characters of the right size first, then iteratively put the forked paths lower and lower (and more densely at each iteration). It remained 230+ bytes, though. The approach here is pretty much what @Laikoni's Haskell approach is. I couldn't get away with not having `:String`, because Haxe is not smart enough to identify that the return type will always be a String.
This is a function only, here's a full programme to test it:
```
class Main {
public static function main(){
function g(n):String return(n-=2)==-1?"/\\":[for(y in 0...1<<n)[for(x in 0...4<<n)x+y+1==2<<n?"/":x-y==2<<n?"\\":" "].join("")].concat([for(y in g(n+1).split("\n"))y+y]).join("\n");
Sys.println(g(Std.parseInt(Sys.args()[0])));
}
}
```
Put the above in `Main.hx`, compile with `haxe -main Main.hx -neko frac.n` and test with `neko frac.n 4` (replace `4` with the desired order).
[Answer]
# PHP, 188 Bytes
[Online Version](http://sandbox.onlinephpfunctions.com/code/fb264f1f0ef523faff29b2f0fb25c05cf792a7f0)
```
function f($l,$r=0,$m=1){global$a;for(;$i<$l;$i++)$i<$l/2?$a[$i+$r]=str_repeat(str_pad("/".str_pad("",2*$i)."\\",2*$l," ",2),$m):f($l/2^0,$r+$l/2,2*$m);}f(2**$argv[1]/2);echo join("\n",$a);
```
Expanded
```
function f($l,$r=0,$m=1){
global$a;
for(;$i<$l;$i++)
$i<$l/2
?$a[$i+$r]=str_repeat(str_pad("/".str_pad("",2*$i)."\\",2*$l," ",2),$m)
:f($l/2^0,$r+$l/2,2*$m);
}
f(2**$argv[1]/2);
echo join("\n",$a);
```
] |
[Question]
[
This question is similar to [Biggest Square in a grid](https://codegolf.stackexchange.com/questions/152305/biggest-square-in-a-grid).
**Challenge**
Given a matrix of `1` and `0` in a string format `"xxxx,xxxxx,xxxx,xx.."` or array format `["xxxx","xxxx","xxxx",...]`, You will create a function that determines the area of the largest square submatrix that contains all `1`.
A square submatrix is one of equal width and height, and your function should return the area of the largest submatrix that contains only `1`.
**For Example:**
Given `"10100,10111,11111,10010"`, this looks like the following matrix:
1 0 1 0 0
1 0 1 **1 1**
1 1 1 **1 1**
1 0 0 1 0
You can see the bolded `1` create the largest square submatrix of size 2x2, so your program should return the area which is 4.
**Rules**
* Submatrix must be one of equal width and height
* Submatrix must contains only values `1`
* Your function must return the area of the largest submatrix
* In case no submatrix is found, return `1`
* You can calculate the area of the submatrix by counting the number of `1` in the submatrix
**Test cases**
**Input:** `"10100,10111,11111,10010"` **Output:** `4`
**Input:** `"0111,1111,1111,1111"` **Output:** `9`
**Input** `"0111,1101,0111"` **Output:** `1`
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes win.
[Answer]
# [Haskell](https://www.haskell.org/), ~~113 121 118~~ 117 bytes
```
x!s=[0..length x-s]
t#d=take t.drop d
f x=last$1:[s*s|s<-min(x!0)$x!!0!0,i<-x!!0!s,j<-x!s,all(>'0')$s#i=<<(s#j)x,s>0]
```
[Try it online!](https://tio.run/##HcbBCoMgGADgu0/xS0I1TPQ6tBeJDrJsWWajX5iHvbtbO3zwLRY3F0IpmaIZpBDBxWdaIHc4klRNJtnNQRLTebxgIjNkEywmpu4D3vCDutt9bDKVLcuUSiq5191/yNdryG0ITV/LumVYeaN1g9XaZo69HMtufQQDPiZ32kcCBrgcbxAw/wQfHRaplCJKSUWufQE "Haskell – Try It Online")
-3 bytes thanks to [Laikoni](https://codegolf.stackexchange.com/users/56433/laikoni?tab=profile)!
-1 byte thanks to [Lynn](https://codegolf.stackexchange.com/users/3852/lynn?tab=profile)!
+8 bytes for the ridiculous requirement of returning 1 for no all-1s sub-matrix..
### Explanation/Ungolfed
The following helper function just creates offsets for `x` allowing to decrement them by `s`:
```
x!s=[0..length x-s]
```
`x#y` will drop `y` elements from a list and then take `x`:
```
t#d=take t.drop d
```
The function `f` loops over all possible sizes for sub-matrices in order, generates each sub-matrix of the corresponding size, tests whether it contains only `'1'`s and stores the size. Thus the solution will be the last entry in the list:
```
-- v prepend a 1 for no all-1s submatrices
f x= last $ 1 : [ s*s
-- all possible sizes are given by the minimum side-length
| s <- min(x!0)$x!!0!0
-- the horizontal offsets are [0..length(x!!0) - s]
, i <- x!!0!s
-- the vertical offsets are [0..length x - s]
, j <- x!s
-- test whether all are '1's
, all(>'0') $
-- from each row: drop first i elements and take s (concatenates them to a single string)
s#i =<<
-- drop the first j rows and take s from the remaining
(s#j) x
-- exclude size 0...........................................
, s>0
]
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~35~~ ~~34~~ 32 bytes
```
{⌈/{×⍨⍵×1∊{∧/∊⍵}⌺⍵ ⍵⊢X}¨⍳⌊/⍴X←⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pRT4d@9eHpj3pXPOrdeni64aOOrupHHcv1gTRQoPZRzy4gpQDEj7oWRdQeAqra/KinS/9R75aIR20TQEr@/3cDsqhgENejvqlAJtC0iRqGCgYKIGygCWUCIYhpiGAaQJRoAgA "APL (Dyalog Unicode) – Try It Online")
[Adám's SBCS has all of the characters in the code](https://github.com/abrudz/SBCS)
Explanation coming eventually!
[Answer]
# [Haskell](https://www.haskell.org/), ~~99~~ 97 bytes
```
b s@((_:_):_)=maximum$sum[length s^2|s==('1'<$s<$s)]:map b[init s,tail s,init<$>s,tail<$>s]
b _=1
```
Checks if input is a square matrix of just ones with `s==('1'<$s<$s)`, if it is, answer is length^2, else 0. Then recursively chops first/last column/row and takes the maximum value it finds anywhere.
[Try it online!](https://tio.run/##RYtNCoMwEIX3nmIoghFEki7FlF6gJxAbEio11KTiRNpF754mpliYv/e9N6PExzBN3ivAMyGiEWUobuRbm9XkuJpuGuzdjYDX4wc5JwUr2hxDlX1j5Ayq01Y7wMpJPYUVVZufko5HnykQnHkjtQUO4ecigMyLtq5W9eu53LDMAKA7MMZgb0oPkVaJ0o3@yN@BnQWX0ZjZkjT9hBlHyvT@Cw "Haskell – Try It Online")
[Answer]
# [K (ngn/k)](https://github.com/ngn/k), ~~33~~ 28 bytes
```
{*/2#+/|/',/'{0&':'0&':x}\x}
```
[Try it online!](https://tio.run/##y9bNS8/7/z/NqlpL30hZW79GX11HX73aQE3dSh1EVNTGVNT@L7GqVomurCuySlOosE7Iz7bWSEhLzMyxrrCutC7SjK3lKonWMFQwUABhA2sICwitDRUM4SwDiLymtUksSDmaEnRa09oSQxmQbW0AkzaM/Q8A "K (ngn/k) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 33 27 bytes
-6 bytes thanks to FrownyFrog!
```
[:>./@,,~@#\(#**/)@,;._3"$]
```
[Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8D/ayk5P30FHp85BOUZDWUtLX9NBx1ov3lhJJfa/JpeSnoJ6mq2euoKOQq2VQloxF1dqcka@QpqCsYKpiiHQCBCGkIYYECoD02KiYKKCTRkSRJiOqhTJhv8A "J – Try It Online")
## Explanation:
I'll use the first test case in my explanation:
```
] a =. 3 5$1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
```
I generate all the possible square submatrices with size from 1 to the number of rows of the input.
`,~@#\` creates a list of pairs for the sizes of the submatrices by stitching `,.` togehter the length of the successive prefixes `#\` of the input:
```
,~@#\ a
1 1
2 2
3 3
```
Then I use them to cut `x u ;. _3 y` the input into submatrices. I already have `x` (the list of sizes); `y` is the right argument `]` (the input).
```
((,~@#\)<;._3"$]) a
┌─────┬─────┬─────┬───┬─┐
│1 │0 │1 │0 │0│
│ │ │ │ │ │
│ │ │ │ │ │
├─────┼─────┼─────┼───┼─┤
│1 │0 │1 │1 │1│
│ │ │ │ │ │
├─────┼─────┼─────┼───┼─┤
│1 │1 │1 │1 │1│
└─────┴─────┴─────┴───┴─┘
┌─────┬─────┬─────┬───┬─┐
│1 0 │0 1 │1 0 │0 0│ │
│1 0 │0 1 │1 1 │1 1│ │
│ │ │ │ │ │
├─────┼─────┼─────┼───┼─┤
│1 0 │0 1 │1 1 │1 1│ │
│1 1 │1 1 │1 1 │1 1│ │
├─────┼─────┼─────┼───┼─┤
│ │ │ │ │ │
└─────┴─────┴─────┴───┴─┘
┌─────┬─────┬─────┬───┬─┐
│1 0 1│0 1 0│1 0 0│ │ │
│1 0 1│0 1 1│1 1 1│ │ │
│1 1 1│1 1 1│1 1 1│ │ │
├─────┼─────┼─────┼───┼─┤
│ │ │ │ │ │
│ │ │ │ │ │
├─────┼─────┼─────┼───┼─┤
│ │ │ │ │ │
└─────┴─────┴─────┴───┴─┘
```
For each submatrix I check if it consist entirely of 1s:
`(#**/)@,` - flatten the matrix, and mutiply the number of items by their product. If all items are 1s, the result will be their sum, otherwise - 0:
```
(#**/)@, 3 3$1 0 0 1 1 1 1 1 1
0
(#**/)@, 2 2$1 1 1 1
4
((,~@#\)(+/**/)@,;._3"$]) a
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
0 0 0 0 0
0 0 4 4 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
```
Finally I flatten the list of results for each submatrix and find the maximum:
`>./@,`
```
([:>./@,,~@#\(+/**/)@,;._3"$]) a
4
```
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-n`, 63 bytes
```
p (1..l=$_=~/,|$/).map{|i|/#{[?1*i]*i*(?.*(l-i+1))}/?i*i:1}.max
```
[Try it online!](https://tio.run/##KypNqvz/v0BBw1BPL8dWJd62Tl@nRkVfUy83saC6JrNGX7k62t5QKzNWK1NLw15PSyNHN1PbUFOzVt8@UyvTyrAWqLDi/39DA0MDAx0gaWioY2gIJg2AQlxwAQQBEzMw1DEAc//lF5Rk5ucV/9fNAwA "Ruby – Try It Online")
Ruby version of my [Python answer](https://codegolf.stackexchange.com/a/163441/78274). Golfier as a full program. Alternatively, an anonymous lambda:
# [Ruby](https://www.ruby-lang.org/), ~~70~~ 68 bytes
```
->s{(1..l=s=~/,|$/).map{|i|s=~/#{[?1*i]*i*(?.*(l-i+1))}/?i*i:1}.max}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1664WsNQTy/Htti2Tl@nRkVfUy83saC6JrMGJKBcHW1vqJUZq5WppWGvp6WRo5upbaipWatvn6mVaWVYC1RbUfu/QCEtWsnQwNDAQAdIGhrqGBqCSQOgkFIsF1gaLo4g0KQMDHUMkEWVYv8DAA "Ruby – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 18 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
+2 to handle no-all-1 sublist present output
```
ẆZṡ¥"L€$ẎȦÐfL€Ṁ²»1
```
**[Try it online!](https://tio.run/##y0rNyan8///hrraohzsXHlqq5POoaY3Kw119J5YdnpAG4jzc2XBo0////6OjDXUMdEDYIFYHygZCMNsQiW0AURUbCwA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///hrraohzsXHlqq5POoaY3Kw119J5YdnpAG4jzc2XBo06Hdhv8PtwN5//9HR0cb6hjogLBBrA6UDYRgtiES2wCiKjZWh0shOhpDFVYWNrUGYBZMLDYWAA "Jelly – Try It Online")
### How?
```
ẆZṡ¥"L€$ẎȦÐfL€Ṁ²»1 - Link: list of lists of 1s and 0s
Ẇ - all slices (lists of "rows") call these S = [s1,s2,...]
$ - last two links as a monad:
L€ - length of each (number of rows in each slice) call these X = [x1, x2, ...]
" - zip with (i.e. [f(s1,x1),f(s2,x2),...]):
¥ - last two links as a dyad:
Z - transpose (get the columns of the current slice)
ṡ - all slices of length xi (i.e. squares of he slice)
Ẏ - tighten (to get a list of the square sub-matrices)
Ðf - filter keep if:
Ȧ - any & all (all non-zero when flattened?)
L€ - length of €ach (the side length)
Ṁ - maximum
² - square (the maximal area)
»1 - maximum of that and 1 (to coerce a 0 found area to 1)
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 143 bytes
```
%`$
,;#
+%(`(\d\d.+;#)#*
$1¶$&¶$&#
\G\d(\d+,)|\G((;#+¶|,)\d)\d+
$1$2
)r`((11)|\d\d)(\d*,;?#*)\G
$#2$3
1,
#
Lv$`(#+).*;\1
$.($.1*$1
N`
-1G`
^$
1
```
[Try it online!](https://tio.run/##RYw9DsIwDIV3X8Mucn6o8sqYgTEL4gQRClIZWBgqxNRz9QC9WEiRAMl@evr8ydPteX9cUTtNpXZFyEcm12nRPOaxd5ENWxKsi@y2Zcopj@3ovJlzUo3s1mX2Jo9tXDNlIDMVVaAJ7YdpsvXxyNbkRMKDHAiemE4vKcrO9DZmkPQqPayAzoX2SIUuQqgVASH4loAHPhkaoh/4x5cF@K29AQ "Retina – Try It Online") Link includes test cases. Takes input as comma-separated strings. Explanation:
```
%`$
,;#
```
Add a `,` to terminate the last string, a `;` to separate the strings from the `#`s and a `#` as a counter.
```
+%(`
)
```
Repeat the block until no more subsitutions happen (because each string is now only one digit long).
```
(\d\d.+;#)#*
$1¶$&¶$&#
```
Triplicate the line, setting the counter to 1 on the first line and incrementing it on the last line.
```
\G\d(\d+,)|\G((;#+¶|,)\d)\d+
$1$2
```
On the first line, delete the first digit of each string, while on the second line, delete all the digits but the first.
```
r`((11)|\d\d)(\d*,;?#*)\G
$#2$3
```
On the third line, bitwise and the first two digits together.
```
1,
#
```
At this point, each line consists of two values, a) a horizontal width counter and b) the bitwise and of that many bits taken from each string. Convert any remaining `1`s to `#`s so that they can be compared against the counter.
```
Lv$`(#+).*;\1
$.($.1*$1
```
Find any runs of bits (vertically) that match the counter (horizontally), corresponding to squares of `1`s in the original input, and square the length.
```
N`
```
Sort numerically.
```
-1G`
```
Take the largest.
```
^$
1
```
Special-case the zero matrix.
[Answer]
# JavaScript, 92 bytes
```
a=>(g=w=>a.match(Array(w).fill(`1{${w}}`).join(`..{${W-w}}`))?w*w:g(w-1))(W=a.indexOf`,`)||1
```
```
f=
a=>(g=w=>a.match(Array(w).fill(`1{${w}}`).join(`..{${W-w}}`))?w*w:g(w-1))(W=a.indexOf`,`)||1
console.log(f('0111,1111,1111,1111'));
console.log(f('10100,10111,11111,10010'));
console.log(f('0111,1101,0111'));
```
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), ~~21~~ 20 bytes
```
×⍨{1∊⍵:1+∇2×/2×⌿⍵⋄0}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQb/04Dk4emPeldUGz7q6HrUu9XKUPtRR7vR4en6QPyoZz9Q6FF3i0Ht//8lQKXVIG7nwiIgM@1R7y4r9fxsdaC0elpiZo46UAAoXVTLpfGot@/QikdtE9UNDQwNDNQVQLShIYg2hNIGQAl1zRIFEyTFSGrQKKBCS2wKDUCUAVSFIQA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~117~~ 109 bytes
Credit to @etene for pointing out an inefficiency that cost me an additional byte.
```
lambda s:max(i*i for i in range(len(s))if re.search(("."*(s.find(',')-i+1)).join(["1"*i]*i),s))or 1
import re
```
[Try it online!](https://tio.run/##bYyxDgIhEET7@wpCc7uIhLU08UvUAj3w1nhwgSv065FYnImxecW8mZlfy5jirobDqT7cdBmcKPvJPYEVi5CyYMFRZBdvHh4@QkHkILI3xbt8HQGkkQqKCRwH6HWPW94QorknjnCUJBWfFaNuu3ZGHU9zyks7qHPmuIgAkixZqxuJNNGHtkUSu7Wyui/@aEva/hqJ9Q0 "Python 2 – Try It Online")
Takes input as a comma-separated string. This is a regex-based approach that tries matching the input string against patterns of the form `111.....111.....111` for all possible sizes of the square.
In my calculations, doing this with an anonymous lambda is just a tad shorter than defined function or a full program. The `or 1` part in the end is only necessary to handle the strange edge case, where we must output `1` if there are no ones in the input.
[Answer]
# [Python 2](https://docs.python.org/2/), 116 115 117 109 bytes
*Credits to @Kirill for helping me golf it even more and for his clever & early solution*
*Edit*: Golfed 1 byte by using a lambda, I didn't know assigning it to a variable didn't count towards the byte count.
*Edit 2*: Kirill pointed out my solution didn't work for cases where the input only contains `1`s, I had to fix it and lost two precious bytes...
*Edit 3*: more golfing thanks to Kirill
Takes a comma separated string, returns an integer.
```
lambda g:max(i*i for i in range(len(g))if re.search(("."*(g.find(",")+1-i)).join(["1"*i]*i),g))or 1
import re
```
[Try it online!](https://tio.run/##TYzBDoIwDIbvPEXTU4eTrB5JfBL1MIVBDWxkctCnn8Mg2uT/k35pv@k198Efkjue02DHa2Ohq0f7JCkFXIggIB6i9V1LQ@upU0ocxLZ6tDbeeiKssKSucuIbQo1qx3tRqroH8XRCxlIupSid/7KMCxmnEOcsSJsc2bAxOjezZv60yQg14MZ@9YcNa/Ml2bBmWdfjJVgXkGeK4mcQDY5EpTc "Python 2 – Try It Online")
I independently found an answer that is close to Kiril's one, i.e regex based, except that I use `re.search` and a `def`.
It uses a regex built during each loop to match an incrementally larger square and returns the largest one, or 1.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~61~~ ~~60~~ 58 bytes
```
{(^$_ X.. ^$_).max({[~&](.[|$^r||*])~~/$(1 x$r)/&&+$r})²}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WiNOJV4hQk9PAUhr6uUmVmhUR9epxWroRdeoxBXV1GjFatbV6atoGCpUqBRp6qupaasU1Woe2lT7vzixUiFNQ6@4ICezRENdR11TUyEtv4hLydDA0MBAB0gaGuoYGoJJA6CQkg6XElwMQSAJGxjqgFhK1v8B "Perl 6 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~138~~ 128 bytes
```
def f(m):j=''.join;L=j(m);k=map(j,zip(*m));return len(L)and max(len(L)*(len(m)**2*'1'==L),f(k[1:]),f(k[:-1]),f(m[1:]),f(m[:-1]))
```
[Try it online!](https://tio.run/##bY5BDoIwEEX3noLddBo0HZaQ3oAbEBYklEhxSkMwUS9fC9VojKv35/2/GH9fz7MrQujNkA2CsbQa4GTn0VW1tlFUk@bOC5s/Ri8kI1aLWa@Lyy7GiRo712fc3US65E5GKQsJBFrXmA9iaqhsUyiPtCd@K04Kg19Gt8YXGiBFSkG@kWgjvahiAS0ePtOvxQ/@z9QGlfrwBA "Python 2 – Try It Online")
---
Saved
* -10 bytes thanks to ovs
[Answer]
## Clojure, 193 bytes
```
#(apply max(for [f[(fn[a b](take-while seq(iterate a b)))]R(f next %)R(f butlast R)n[(count R)]c(for[i(range(-(count(first R))n -1)):when(apply = 1(for[r R c(subvec r i(+ i n))]c))](* n n))]c))
```
Wow, things escalated :o
Less golfed:
```
(def f #(for [rows (->> % (iterate next) (take-while seq)) ; row-postfixes
rows (->> rows (iterate butlast) (take-while seq)) ; row-suffixes
n [(count rows)]
c (for[i(range(-(count(first rows))n -1)):when(every? pos?(for [row rows col(subvec row i(+ i n))]col))](* n n))] ; rectangular subsections
c))
```
] |
[Question]
[
A string can be *shifted* by a number `n` by getting the byte value `c` of each character in the string, calculating `(c + n) mod 256`, and converting the result back to a character.
As an example, shifting `"ABC123"` by 1 results in `"BCD234"`, shifting by 10 in `"KLM;<="`, and shifting by 255 in `"@AB012"`.
### The Task
Pick as many numbers `n` with `0 < n < 256` as you dare and write a program or function that takes a string as input and
* returns the string unchanged when the source code is unchanged, but
* returns the string shifted by `n` when the source code is shifted by `n`.
### Rules
* The score of your submission is the number of supported `n`, with a higher score being better. The maximum score is thus 255.
* Your submission must support at least one shift, so the minimal score is 1.
* In case of a tie the shorter program wins.
* All shifted programs need to be in the same language.
[Answer]
# Brainfuck, score: 31 (2208 bytes)
Base64-encoded program:
```
LFsuLF0oVycnJycqKFkkUyMjIyMjIyMjJiRVIE8fHx8fHx8fHx8fHx8iIFEMOwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLDgw9CDcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcKCDkEMwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMGBDUAL8O/w7/Dv8O/w7/Dv8O/w7/Dv8O/w7/Dv8O/w7/Dv8O/w7/Dv8O/w7/Dv8O/w7/Dv8O/w7/Dv8O/w7/Dv8O/w7/Dv8O/w7/Dv8O/w7/Dv8O/w7/Dv8O/w78CADHDrBvDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Orw6vDq8Ouw6wdw6gXw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Onw6fDp8Oqw6gZw6QTw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6PDo8Ojw6bDpBXDoA/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Ofw5/Dn8Oiw6ARw4zDu8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OLw4vDi8OOw4zDvcOIw7fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OHw4fDh8OKw4jDucOEw7PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4PDg8ODw4bDhMO1w4DDr8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8K/wr/Cv8OCw4DDscKsw5vCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8KrwqvCq8Krwq7CrMOdwqjDl8KpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqnCqcKpwqrCqMOZwqTDk8KlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKlwqXCpcKmwqTDlcKgw4/CocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqHCocKhwqLCoMORwozCu8KNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKNwo3CjcKOwozCvcKIwrfCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJwonCicKJworCiMK5woTCs8KFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwoXChcKFwobChMK1woDCr8KBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKBwoHCgcKCwoDCsWzCm21tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1ubMKdaMKXaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpamjCmWTCk2VlZWVlZWVlZWVlZWVlZWVlZWVlZWVlZWVlZWVlZWVlZWVlZWVlZWVlZWVlZWVlZWVlZWVlZWVlZmTClWDCj2FhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFiYMKRTHtNTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU5MfUh3SUlJSUlJSUlJSUlJSUlJSUlJSUlJSUlJSUlJSUpIeURzRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRkR1QG9BQUFBQUFBQUFBQUFBQUFBQUFBQUJAcQ==
```
Works for shifts 0, 4, 8, 12, 32, 36, 40, 44, 64, 68, 72, 76, 96, 100, 104, 108, 128, 132, 136, 140, 160, 164, 168, 172, 192, 196, 200, 204, 224, 228, 232 and 236.
For every value between 0 and 255, there is exactly one of those shifts that sends that character to a valid brainfuck instruction.
The program relies on 8-bit cells with wrapping on overflows.
This could probably be golfed quite a bit, as the shift just consists of a repeated `+` or `-` (whichever is shorter).
Python code used to generate this:
```
l = [0, 4, 8, 12, 32, 36, 40, 44, 64, 68, 72, 76, 96, 100, 104, 108, 128, 132, 136, 140, 160, 164, 168, 172, 192, 196, 200, 204, 224, 228, 232, 236]
shift = lambda s,n:"".join(chr((ord(i)+n)%256) for i in s)
code = ""
for i in l:
code += shift(",[{}.,]".format(i*"+" if i<=128 else (256-i)*"-"),-i)
```
[Answer]
# lHaskell, Score 255 (27,026 bytes)
The program works but putting it in my clipboard seems to destroy it so [here is code that outputs my program.](https://tio.run/##jZCxasNADIb3ewoRPMS0PkohtNDEg5MlQ6eOiSmqffEZ2yf3TkddyLu756YJgSzdfkmfxIc@0OlxLJAhhd5SZbGTrXZCFZpgJkRadz1Zhk@PbX2oVQkbZJTZN6s3trWpAB1kIu2wNquSYFgmmawUr8mwMuxeMtl7Dug@CgmLZh912M/v4qn2ZurAIMQMjmC90ega1bbXJuP4X4U/7He41mhF6lfPTxc1kd7KhV6weX2Hs@XuJHlynCcmji@aIRRkwqcCw9go8DDcX@EHS9023K2UlUznRLaMI6fpC0yAS0v9tJcfzTLZPUj5uFjk@Q8 "Bash – Try It Online")
## Verification
So if copying things to a clipboard breaks it how do I verify that it works?
You can use [this here](https://tio.run/##lVHBasJAEL3vVwwhUEPrUgRRqMkh9tJDvXhUKdNk3QSTnXSzSy347@lGa4iWgr09Zt7Mm/fmHeusaRbhZMqWoRfnEqi4AyGlx1iCBiKoNEmNJS@ymokkI/DysiJt4MNikW9zkcIzGuTxlxFLo3MlAWuIWYm5ClOC/WwYcynMnJQRytRPMa@sccy17xAmu7VfYjW49xdBW7GqrcHea6VHvBNlLLpNN/qv8IUsYx4cQFuVYb0TRdG3f9Voj3NHkjW9bPzl1Xy//RfnuKppbjX4Qzs25xlqFtlwOumMs@i3dVdzXl/f4JzB6hTBKYHBUAVBF4IDCSn3fMcxuBNgYf/Qo281lS9urxSaGzoj0mng1xl9gnLkVFPVzm0OajZcPXI@Go83m28). You can adjust `N` and the string (currently `Big ol' egg`) to see that it works yourself.
[This](https://tio.run/##tZFBa4MwGIbv@RUfElilM3SFssGqB7vLDvPSo5WRaapSTVz8pA76312sbbEdg112@8z3ap738YPXWdetXcvPU1DFHYg0tQiJOYIHlVap5iUrspqIOFNgNl5eVkojfDa8yLe5SOCFI2f@F4o16lymwGvwiVfyXLqJgnbp@CwVuFIShcT62WdVgya6oWbi8W5DS15Npnb/3Mj@BFpCLDiAbmTG650oijGJ4VINMmyRkMC1ZoZpn@WFgBBoAE6BMF8sICKJIjBA/xcyDa6grd7Y/CgLen8nypsi81GHY3RgpOubxlf7X1Pn@4ZQ4NKQBtOHvrwUXffX4qfYcbnKuCZe4z49XoQQ76cSc2YcvL3D2U04qBnMTBxp2xc1ZoiVNEpMBvlOQAPt/Si@1ap8Nd9NhWaozpPSiU3rTO1BmnCiVdW/Fx3k0glnjJmfHEXf) will test all N on a single input in succession but tends to time out.
## Explanation
This abuses literate Haskell's comment notation. In literate Haskell any line that does not start with `>` is a comment. So to make our code work we make 255 copies of the program each shifting by `n` and then we shift each individual copy by `-n`.
[Answer]
# C, score: 1 (73 bytes)
```
aZ0;/*0\:..*/f(s){puts(s);}// e'bg`q)r(zenq':)r:**r(otsbg`q'')r*0($145(:|
```
[Try it online!](https://tio.run/##S9ZNT07@/z8xysBaX8sgxkpPT0s/TaNYs7qgtKQYSFvX6utzpqonpScUahZpVKXmFapbaRZZaWkVaeSXFIOE1dU1i7QMNFQMTUw1rGr@Z@aVKOQmZuZpaHJVcykAQZqGkqOTs6GRsZKmNVftfwA)
**Shifted by 1:**
```
b[1<0+1];//+0g)t*|qvut)t*<~00
f(char*s){for(;*s;++s)putchar((*s+1)%256);}
```
[Try it online!](https://tio.run/##S9ZNT07@/z8p2tDGQNsw1lpfX9sgXbNEq6awrLQESNvUGRhwpWkkZyQWaRVrVqflF2lYaxVba2sXaxaUloCENTS0irUNNVWNTM00rWv/Z@aVKOQmZuZpaHJVcykAQZqGkqOTs6GRsZKmNVftfwA)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), Score: 3 (24 bytes)
```
¶Ä0(ä.g){n·Å0)åH*oHÆ0*æI
```
[Try it online!](https://tio.run/##AS4A0f8wNWFiMWX//8K2w4QwKMOkLmcpe27Ct8OFMCnDpUgqb0jDhjAqw6ZJ//90ZXN0 "05AB1E – Try It Online")
**Explanation**
```
¶Ä0(ä.g){n·Å0)åH*oHÆ0*æ # Doesn't matter
I # Push the original input to the stack, implicit display
```
Shifted once:
```
·Å1)å/h*|o¸Æ1*æI+pIÇ1+çJ
```
[Try it online!](https://tio.run/##AS4A0f8wNWFiMWX//8K3w4UxKcOlL2gqfG/CuMOGMSrDpkkrcEnDhzErw6dK//90ZXN0 "05AB1E – Try It Online")
**Explanation**
```
·Å1)å/h*|o¸Æ1*æI+p # Doesn't matter
IÇ # Push the ASCII values of the input
1+ # Increment by 1
çJ # Push the chars of the ASCII values, join, implicit display
```
Shifted twice:
```
¸Æ2*æ0i+}p¹Ç2+çJ,qJÈ2,èK
```
[Try it online!](https://tio.run/##AS4A0f8wNWFiMWX//8K4w4YyKsOmMGkrfXDCucOHMivDp0oscUrDiDIsw6hL//90ZXN0 "05AB1E – Try It Online")
**Explanation**
```
Æ2*æ0i+}p # Doesn't matter
¹Ç # Push the ASCII values of the input
2+ # Increment by 2
çJ # Push the chars of the ASCII values, join
,q # Print and terminate
```
Shifted thrice:
```
¹Ç3+ç1j,~qºÈ3,èK-rKÉ3-éL
```
[Try it online!](https://tio.run/##AS4A0f8wNWFiMWX//8K5w4czK8OnMWosfnHCusOIMyzDqEstckvDiTMtw6lM//90ZXN0 "05AB1E – Try It Online")
**Explanation**
```
¹Ç # Push the ASCII values of the input
3+ # Increment by 3
ç1j # Push the chars of the ASCII values, join
,q # Print and terminate
```
[Answer]
# Javascript, score: ~~1~~ 4 (~~94~~ 346 bytes)
Pretty straight-forward, has different sections commented out when rotated, the difficult bit was finding usable variable names and comment sections that don't break Javascript syntax.
Unrotated:
```
hc/*% *%nnS/0S eb^[fRR _SbS/0Efd[`Y Xda_5ZSd5aVWS UZSd5aVW3f"#&$'( \a[`RR!! %34hc/*$ifb_jVV$cWfW34Ijh_d]$\hec9^Wh9eZ[W$Y^Wh9eZ[7j&!'&(+,$`e_dVV%%%*89hc/)nkgdo[[)h\k#\89Nomdib)amjh>c\m>j_`###\)^c\m>j_`<o#+$&0$ -01$$$)ejdi[[***/=>/*ch*/hc//chhcchvw*/g¬©¥¢g¦©avw«¢§ g«¨¦|¡«|¨aaag¡«|¨zaibdjrrb^knobbbg£¨¢§
```
Rotated by 5:
```
mh4/*%$/*ssX45X%jgc`kWW%dXgX45Jki`e^%]ifd:_Xi:f[\X%Z_Xi:f[\8k' "(+ ),- %af`eWW &&%*89mh4/)nkgdo[[)h\k#\89Nomdib)amjh>c\m>j_`###\)^c\m>j_`<o#+$&,+$ -01$$$)ejdi[[***/=>mh4.split``.map(a=>String.fromCharCode(((a.charCodeAt(0)+5)%256))).join``///4BC4/hm/4mh44hmmhhm{|/4l±®ª§²l«®f{|²°§¬¥l¤°«¦°¢£fffl¡¦°¢£²fngiowwgcpstgggl¨§¬
```
Rotated by 10:
```
rm94/*)4/xx$]9:]*olhep\\*i]l$]9:Opnejc*bnki?d]n?k`a$$$]*_d]n?k`a=p$,%'-0%!.12%%%*fkej\\%++*/=>rm94.split``.map(a=>String.fromCharCode(((a.charCodeAt(0)+10)%256))).join``///4BCrm93xuqnyee3rfu-fBCXywnsl3kwtrHmfwHtij---f3hmfwHtijFy-5.0:.*7:;...3otnsee4449GH94mr49rm99mrrmmr49q¶³¯¬·££q°¤³k¤·µ¬±ªq©µ²°«¤µ²§¨kkk¤q¦«¤µ²§¨·kslnt||lhuxylllq²¬±££
```
Rotated by 14: things finally got interesting here, got to abuse the Javascript type system.
```
vq=83.-83||(a=>a.split``.map(a=>String.fromCharCode(((a.charCodeAt(0)+14)%256))).join``)//.3ABvq=82wtpmxdd2qet,eABWxvmrk2jvsqGlevGshi,,,e2glevGshiEx,4-/54-)69:---2nsmrdd3338FGvq=7|yur}ii7vjy1jFG\}{rwp7o{xvLqj{Lxmn111j7lqj{LxmnJ}1924>2.;>?2227sxrwii888=KL=8qv8=vq==qvvqqv8=uº·³°»§§u´¨·o¨»¹°µ®u¹¶´¯¨¹¶«¬ooo¨uª¯¨¹¶«¬»owprxply|}pppu±¶°µ§§
```
Rotated by 199:
```
/*öñìçæñì55áö÷ç,)%"-ç&)áö÷-+"' ç+(&ü!+ü(áááç!+ü(ú-áéâäêíâÞëîïâââç#("'âèèçìúû/*öñë0-)&1ë*-åúû1/&+$ë#/,*%/,!"åååë %/,!"þ1åíæèîíæâïòóæææë',&+ìììñÿ/*öð52.+6""ð/#2ê#ÿ64+0)ð(41/*#41&'êêê#ð%*#41&'6êòëí÷ëçô÷øëëëð,1+0""ñññööñ*/ñö/*öö*//**/=>ñö.split``.map(a=>String.fromCharCode(((a.charCodeAt(0)+199)%256))).join``
```
To find the solutions, I [built a small tool](https://jsfiddle.net/po3ph24q/) to show me different snippets when rotated by a variable amount, I then found certain patterns that I could use as useful building blocks.
The main gist of it is that `a/**/=>a` is still a valid function definition, which allows you to embed a reverse rotated function in the comment section. From there on, it can be repeated a few times, if done correctly.
Since most of the comment sections are nested, it might be possible to find another result, but making it work becomes increasingly difficult with each added answer due to collisions and control characters.
---
Replacing all usages of `charCodeAt(0)` with `charCodeAt``` would shave 4 bytes off the whole solution, but it's too much work to do from scratch.
[Answer]
# [PHP](https://php.net/) with `-d output_buffering=on -d short_open_tag=on`, score: 255 (25,731 bytes)
```
<?die($argv[1]);?>
=@pc`dmfbo)*<ejf)qsfh`sfqmbdf`dbmmcbdl)#0/0#-gvodujpo)%n*|sfuvso!dis)pSe)%n\1^*.2*<~-%bshw\2^**<@?>Aqdaengcp*+=fkg*rtgiatgrncegaecnndcem*$101$.hwpevkqp*&o+}tgvwtp"ejt*qTf*&o]2_+/4+=.&ctix]3_++=A@?Brebfohdq+,>glh+suhjbuhsodfhbfdooedfn+%212%/ixqfwlrq+'p,~uhwxuq#fku+rUg+'p^3`,06,>?/'dujy^4`,,>BA
@Csfcgpier,-?hmi,tvikcvitpegicgeppfego,&323&0jyrgxmsr,(q-vixyvr$glv,sVh,(q_4a-18-??0(evkz_5a--?CBADtgdhqjfs-.@inj-uwjldwjuqfhjdhfqqgfhp-'434'1kzshynts-)r.?wjyzws%hmw-tWi-)r`5b.2:.@?1)fwl{`6b..@DCBEuheirkgt./Ajok.vxkmexkvrgikeigrrhgiq.(545(2l{tizout.*s/?xkz{xt&inx.uXj.*sa6c/3</A?2*gxm|a7c//AEDCFvifjslhu/0Bkpl/wylnfylwshjlfjhssihjr/)656)3m|uj{pvu/+t0?yl{|yu'joy/vYk/+tb7d04>0B?3+hyn}b8d00BFEDGwjgktmiv01Clqm0xzmogzmxtikmgkittjiks0*767*4n}vk|qwv0,u1?zm|}zv(kpz0wZl0,uc8e15@1C?4,izo~c9e11CGFEHxkhlunjw12Dmrn1y{nph{nyujlnhljuukjlt1+878+5o~wl}rxw1-v2?{n}~{w)lq{1x[m1-vd9f26B2D?5-j{pd:f22DHGFIylimvokx23Enso2z|oqi|ozvkmoimkvvlkmu2,989,6pxm~syx2.w3?|o~|x*mr|2y\n2.we:g37;:3E?6.k|q?e;g33EIHGJzmjnwply34Fotp3{}prj}p{wlnpjnlwwmlnv3-:9:-7q?yntzy3/x4?}p?}y+ns}3z]o3/xf;h48<<4F?7/l}r?f<h44FJIHK{nkoxqmz45Gpuq4|~qsk~q|xmoqkomxxnmow4.;:;.8r?zo?u{z40y5?~q??~z,ot~4{^p40yg<i59=>5G?80m~s?g=i55GKJIL|olpyrn{56Hqvr5}rtlr}ynprlpnyyonpx5/<;</9s?{p?v|{51z6?r??{-pu5|_q51zh=j6:>@6H?91nt?h>j66HLKJM}pmqzso|67Irws6~?sum?s~zoqsmqozzpoqy60=<=0:t?|q?w}|62{7??s???|.qv?6}`r62{i>k7;?A;?7I?:2o?u?i?k77IMLKN~qnr{tp}78Jsxt7?tvn?t{prtnrp{{qprz71>=>1;u?}r?x~}73|8??t???}/rw?7~as73|j?l8<@D8J?;3p?v?j@l88JNMLOros|uq~89Ktyu8??uwo?u?|qsuosq||rqs{82?>?2<v?~s?y~84}9??u???~0sx?8bt84}k@m9=AF9K?<4q?w?kAm99KONMP?spt}vr9:Luzv9??vxp?v?}rtvptr}}srt|93@?@3=w?t?z?95~:??v???1ty?9?cu95~lAn:>BH:L?=5r?x?lBn::LPO
...
```
Similar to the Haskell solution, copying and pasting this breaks, so I generated this using [this Perl script](https://tio.run/##vdzNThMBFIbhvVdhSDWdSGHOmf9A5B7cEkNKGZFYaDOAG@OtW8vGjet51ka/FHhbhKdnP07b5nB4Pj8733yflsvddLdcfCw@LRdnqyiKD9m0xfn9@Hw4XF7dPYzLxXq6/3kdX4uLq8/vLq92tzeb7bh@WhYXb3@6n8b7m2ncb9eb8Waz3m5v15sfy5PjP35y@u31afPysHtaLh6LX9P48jo9vX@b3H05Lj5el1@L4@DF79N/C7NM5PwT1fwT9fwTzfwT7fwT3fwT/fwTw/wTUYIN0HeAwKMSG@LZMEDlATIP0HmA0AOUnqD0FK/koPQEpWctNsj3VqD0BKUnKD1B6RUovQJfV5X4ph2UXoHSq0ZsiGeTCpRegdIrUHoNSq/B57wGpdfi/@eg9BqUXrdiQzyb1KD0GpTegNIb8PloQOkNKL0RP4oDpTeg9KYTG@LZpAGlt6D0FnysWlB6C0pvQemt@Kk7KL0Fpbe92BDPJh0ovROPA5TegdI7UHoHSu/EL9hA6R0ovQOv6D3ovAed96DzHnTeg8570HkPOu/Fb9JB5z3ofACdD6DzAXQ@gM4H0PkAOh9A5wPofBBkhpgZgWZK4UDKJCPEtJS1GBFyphR0phR2phR4phTNGygnOiFUjlg5hOWIliNcjng5AuaEmAtB5iKJjhXNCzUXgs2FcXMh4FwIOReCzoWwcyHwXAg9FxUh8cTEi@aFoAtD6EIYuhCILirSfJC32lRpZiozU5uZxsx0q97MkEfTm5mBzDSleU@UeOVvyCMRr/xC2YVgdiGcXQhoF0LahaF2IaxdCGwXQtuF4HYhvF0IcBcteQesaF6YuxDoLoy6C8HuoiOPRDQv5F0IehfC3kVH3vYumhf8LoS/CwHwQgi8EAQvhMELgfBCKLwQDC96culCFC8kXgiKF8LihcB4ITReCI4XwuOFAHkhRF4M5LgNuW4jztsIk5fC5KUxeSlMXgqTl8LkpTB5KUxeCpOXQU5aiU6EyUth8o4jKzIjmhcmL4XJS2HyklyxI2fszB070Ty5ZEdO2aFbduSYHblmR87ZCZOXwuSlMHlZkeOVonlh8lKYvDQmL4XJS2HyUpi8FKftUty2S3HcLmtysZacrBXNiwN3aS7cpThxlzVpfjAfsGGVZqYyM7WZaczM/2n@2e3f/t7zYbX/Cw "Perl 5 – Try It Online").
[Verification for shifted 1, 16, 32 and 255 times.](https://tio.run/##vZ3LbtpQFEXnfIWVpg2oJfE@19ePQpNpx32MqgoZuAmoxLYMVKqqfnvqPBpVqqiUSF6zyE68j4FlO7C8mZfb1U0T2k00bkJ0sj07PVus2uGwbpfD41ej18Pj07FGo5fm09HZVTiJptNpdDK9WK7D8Lhsr75/0dfR5OJ8ML2o57PFJpTVcDS5Xdu04WrWhmZTLsJsUW4283LxbXjUBRy9udxXi926robH16Ofbdjt2yq6ja0/dKnXX@Kvoy508uvNY0IvEdZ/hOs/Iuk/wvcfkfYfkfUfkfcfUfQfoRjIAPgWALgckUEcDQVQLgBzAZwLAF0A6QaQbsSZHCDdANItITKQayuAdANIN4B0A0h3AOkOeF054qIdIN0BpDtPZBBHEweQ7gDSHUB6ApCeAM95ApCeEP@fA6QnAOlJSmQQR5MEID0BSPcA6R54PjxAugdI98RbcQDpHiDdZ0QGcTTxAOkpQHoKPFYpQHoKkJ4CpKfEu@4A6SlAepoTGcTRJANIz4j9AEjPANIzgPQMID0jPmADSM8A0jPgjJ4DnOcA5znAeQ5wngOc5wDnOcB5TnySDnCeA5wXAOcFwHkBcF4AnBcA5wXAeQFwXgCcF4QygzgzhDQTEx5IbEgI4rTECRFCmDMxoc7EhDsTE/JMTDDPiHIEJ4gqh7hykCyH2HKILof4cogwRxhzIpQ5GWLHEswT1pwIbU6MNydCnBNhzolQ50S4cyLkORH2nByixCNOPME8YdCJUehEOHQiJDo5hHkht9o4Y2IcE5MwMZ6JycY5E4PsTc7EFEiMj5l7oogzv0f2hDjzE5adCM1OhGcnQrQTYdqJUe1EuHYiZDsRtp0I3U6EbydCuFOK3AFLME84dyKkOzHWnQjtThmyJwTzhHknQr0T4d4pQ257J5gn9DsR/p0IAU@EgSdCwRPh4ImQ8ERYeCI0POVI0wVBPGHiiVDxRLh4ImQ8ETaeCB1PhI8nQsgTYeSpQMptkHYbot6GcPKMcPKMcfKMcPKMcPKMcPKMcPKMcPKMcPJMSKUVwQnh5Bnh5HUhYySGYJ5w8oxw8oxw8gxpsUNq7JgeO4J5pMkOqbKDuuyQMjukzQ6psyOcPCOcPCOcPHNIeSXBPOHkGeHkGePkGeHkGeHkGeHkGVFtZ0S3nRHldpYgjbVIZS3BPFFwZ0zDnREVd5YgzBfMA1aMjYlxTEzCxHgm5l80T6LzaFs3p82qmdy8@PNjtGhDuQvLaF1F70O5DO1gEBarOjr6XG1X68tu1dujyeD2N8fLaLuq292sbkI125VX7@rqdmG93zX73Wy@v7wM7bq6W/xn65/CdtctutvkZDA4/L0p3Wv2r69Mefz7u5F1N/PDWB/vh4rmPyI9czI9dbT0P7Olh4ZLnztd@sTxusvhg@M5OzCes2eOd7/FJ4xn3h@er1t5YMBuzTMnfNjm44g3N78B "Bash – Try It Online")
## Explanation
Using PHP's `<?` delimiter made this fairly easy, but I had to avoid any strings that could end up as `<?` elsewhere in the code, this basically means `03`, `14`, `25`, `36`, `47`, `58` and `69`. Working around those was fairly easy using arithmetic. It might well be possible to reduce the byte count in the original program too.
[Answer]
# [Crane-Flak](https://github.com/Flakheads/CraneFlak), Score 3 (252 bytes)
```
%&'()%&%X'Z&xx\()'()z%xz|%&'()%&'()%&'()9;=&'()9;=%XZ\&'z|%&'(9;=(9;=%&'XZ\(|xz|9;=%&'%&(%X'Z&\('()xxz%xz|9;=&'()9;=%XZ\&'z|9;=(9;=%&'XZ\(|9;=)))))))%&Y[]'()yy{}%&y{}%&'()%&'():<>'():<>%&Y[]'(){}y{}:<>%&Y[]'()yy{}::<><>:<>%&y{}:<>'():<>%&Y[]'(){}::<><>
```
[Try it online!](https://tio.run/##SypKzMzLSEzO/v9fVU1dQ1NVTTVCPUqtoiJGQxPIrVKtqKqBSsAIS2tbKKUaERWjpg5RAOSCMJAJFNSoAWqD8FTVNMAmxmgA9VRUgA3ENAFNN5CpCQGqapHRsUC1lZXVtapqYALmDisbOwgJU1NdC5RH4oP0WAH5NnZgQYgkuhaIgv///@s6/lcayUGgBAA "Brain-Flak (BrainHack) – Try It Online")
*(Doesn't quite work in Brain-Hack because only Crane-Flak mods by 256)*
**Shifted by 1**
```
&'()*&'&Y(['yy])*()*{&y{}&'()*&'()*&'()*:<>'()*:<>&Y[]'({}&'():<>):<>&'(Y[])}y{}:<>&'(&')&Y(['])()*yy{&y{}:<>'()*:<>&Y[]'({}:<>):<>&'(Y[])}:<>*******&'Z\^()*zz|~&'z|~&'()*&'()*;=?()*;=?&'Z\^()*|~z|~;=?&'Z\^()*zz|~;;=?=?;=?&'z|~;=?()*;=?&'Z\^()*|~;;=?=?
```
[Try it online!](https://tio.run/##ZVBbDsIgELxLExZo4gG0tsZbaB8m6o/GxA@/oK@r48CC0UrCsLM7MyF7eZ3vz9v5@nCOpNI5STqqRlrb6Rx0IDtMcZBgs63iQ8emk4oFoP6iRFNPsDEjqUNip@GxNgT@JyzcKHM@JOv2BG3fjzPJAOkfRbljTJpxxvyLe08BXu5Ck4dLCwucc6u9y4QPFiQOsiZjWqVBe2H6MQ4SrIsyPuJQtz7at0H9RYmmGmFjJkiFxFbBY0wI/E9YuFFqPoKXpLG8SVCA9A9eJDBphrj4b88GfFuF5mf3PxYWZG8 "Brain-Flak (BrainHack) – Try It Online")
**Shifted by 2**
```
'()*+'('Z)\(zz^*+)*+|'z|~'()*+'()*+'()*+;=?()*+;=?'Z\^()|~'()*;=?*;=?'()Z\^*~z|~;=?'()'(*'Z)\(^*)*+zz|'z|~;=?()*+;=?'Z\^()|~;=?*;=?'()Z\^*~;=?+++++++'([]_)*+{{}'({}'()*+'()*+<>@)*+<>@'([]_)*+}{}<>@'([]_)*+{{}<<>@>@<>@'({}<>@)*+<>@'([]_)*+}<<>@>@
```
[Try it online!](https://tio.run/##ZU5bbsIwELwLkr1rRz0AEFJ6CwgmiPYHVKkf/TJOAkc3Y28soWDJ452dh/z9f77@Xc4/vzESG1sRU2sch9DZCnSgMNwnocB68zk91LqOjRhA08WIpb0jJozY5sbOIhNCLnxvmKUxVnKID8cTvH0/PogzlH/UzVaweMYH9BeeMjV4s81LEecRMcQYP77iQmk0K6121GrvXfq9CcqHYRIKLNeb6VG71mkSA2i6GLHkATFhSnNudIyM97nwvWGWxmjkKL0/HOG93fpR6QzlH6u6ESyefoT@wlNmBV43eSniPCKGxRM "Brain-Flak (BrainHack) – Try It Online")
**Shifted by 3**
```
()*+,()([*]){{_+,*+,}({}()*+,()*+,()*+,<>@)*+,<>@([]_)*}()*+<>@+<>@()*[]_+{}<>@()*()+([*])_+*+,{{}({}<>@)*+,<>@([]_)*}<>@+<>@()*[]_+<>@,,,,,,,()\^`*+,||~€()|~€()*+,()*+,=?A*+,=?A()\^`*+,~€|~€=?A()\^`*+,||~€==?A?A=?A()|~€=?A*+,=?A()\^`*+,~€==?A?A
```
[Try it online!](https://tio.run/##ZU5bboMwELxLJJtdTA/QFEi4RRqgNO1Pq0r9yJcTQ9Oz9WLu4LWlCCx5vLPzkN/Op8/vj9P7l/fEuSmIqc17dm4wBehEbrpFIUFZ7@NDbT9wLgbQ@WLE0twQE0ZsQuNgkHEuFK4bFmmMhRzi7uUV3nH8@fslFkw/qXaNYHJBnR13m5CrsNg1YRvlVUws3vuHxm@UzoiVVofsqK3tiEGvyl7HKCR4fKriow7HTmdiAJ0vRixpREyY0hQaO0LG2lC4blikMbIcpZ/bHt7LxU1KB0j/2Ja1YPK4CfodnzNb8LIOSxGXETFs/gE "Brain-Flak (BrainHack) – Try It Online")
## Explanation
The main code at work here is
```
([]){{}({}n<>)<>([])}{}<>([]){{}({}<>)<>([])}<>
```
where `n` is an arbitrary number. This moves everything to the offstack adding `n` to each item (modulo 256 is implicit upon output), and then moves them all back.
However for the first program (i.e. shifted by 0) we don't need to do any of this because shifting by zero is the cat program. So we start with this code:
```
([]){{}({}()<>)<>([])}{}<>([]){{}({}<>)<>([])}<>
```
and shift it down by 1
```
'Z\(zz|'z|m;=(;='Z\(|z|;='Z\(zz|'z|;=(;='Z\(|;=
```
This is unbalanced so we have to fix it. There are a number of ways we could do this by my choice method (for reasons that will become apparent) is the following:
```
'Z\(zz|'z|m;=(;='Z\(|z|;='Z\(zz|'z|;=(;='Z\(|;=)))))){}{}{}{}{}
```
Shifting this up by 2 we get
```
)\^*||~)|~o=?*=?)\^*~|~=?)\^*||~)|~=?*=?)\^*~=?++++++}}}}}
```
Since `()` is easier to deal with than `{}` we will use the `}`s to complete the program we desire. That means that the `)` can be balanced with pretty obvious means. With some fiddling we can turn that into:
```
()\^*||~()|~()*=?*=?()\^*~|~=?()\^*||~()|~=?*=?()\^*~=?+++++++([]_)*+{{}({}()*+()*+<>@)*+<>@([]_)*+}{}<>@([]_)*+{{}<<>@>@<>@({}<>@)*+<>@([]_)*+}<<>@>@
```
Shifting that back down we get
```
&'Z\(zz|&'z|&'(;=(;=&'Z\(|z|;=&'Z\(zz|&'z|;=(;=&'Z\(|;=)))))))&Y[]'()yy{}&y{}&'()&'():<>'():<>&Y[]'(){}y{}:<>&Y[]'()yy{}::<><>:<>&y{}:<>'():<>&Y[]'(){}::<><>
```
The step up to 3 is so complex I don't really understand it any more. I used the same technique and just fiddled around with it until I finally got all 4 of them to work at once. The technique is pretty much the same there is just a lot more fiddling.
[Answer]
# Python 3, Score 1, 76 bytes
Shift 0: no change
```
""!="";print(input());exit()# oqhms'&&-inhm'bgq'nqc'i(*0(enq'i(hm'hmots'((((
```
Shift 1:
```
##">##<qsjou)joqvu)**<fyju)*$
print(''.join(chr(ord(j)+1)for(j)in(input())))
```
Started work on shift 2, but "" becomes $$ and you can't start a line with that.
When you save it to a file, make sure it doesn't end with a newline. (vim -b file.py + set noeol)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), score ~~1~~ 2
## ~~8~~ 15 bytes
**Shift 0:**
```
M««Ṃ¬ịị¶Ɓ|L(0Ḷṇ
```
[Try it online!](https://tio.run/##y0rNyan8/9/30OpDqx/ubDq05uHubiA6tO1YY42PhsHDHdse7mz///@/uqOTs6GRsToA "Jelly – Try It Online")
**Shift 2:**
```
O‘‘Ọµḷḷ¹Ɗ~N*2Ṇṛ
```
[Try 2 online!](https://tio.run/##y0rNyan8/9//UcMMIHq4u@fQ1oc7tgPRoZ3Huur8tIwe7mx7uHP2////1R2dnA2NjNUB)
**Shift 3:**
```
P’’Ṛ½ṃṃ²Ƒ¶O+3Ọṣ
```
[Try 3 online!](https://tio.run/##y0rNyan8/z/gUcNMIHq4c9ahvQ93NgPRoU3HJh7a5q9t/HB3z8Odi////6/u6ORsaGSsDgA)
] |
[Question]
[
Write a function or program that determines the *cost* of a given string, where
* the cost of each character equals the number of how many times the character has occurred up to this point in the string, and
* the cost of the string is the sum of its characters' costs.
### Example
For an input of `abaacab`, the cost is computed as follows:
```
a b a a c a b
1 2 3 4 occurrence of a
1 2 occurrence of b
1 occurrence of c
1+1+2+3+1+4+2 = 14
```
Thus the cost for the string `abaacab` is 14.
### Rules
* **The score of your submission is the cost of your code as defined above**, that is your submission run on its own source code, with a **lower** score being better.
* Your submission should work on strings containing printable ASCII-characters, plus all characters used in your submission.
* Characters are case-sensitive, that is `a` and `A` are different characters.
### Testcases
```
input -> output
"abaacab" -> 14
"Programming Puzzles & Code Golf" -> 47
"" -> 0
" " -> 28
"abcdefg" -> 7
"aA" -> 2
```
### Leaderboard
```
var QUESTION_ID=127261,OVERRIDE_USER=56433;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} /* font fix */ body {font-family: Arial,"Helvetica Neue",Helvetica,sans-serif;} /* #language-list x-pos fix */ #answer-list {margin-right: 200px;}
```
```
<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>Score</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]
# Common Lisp, score ~~286~~ ~~232~~ 222
```
(loop with w =(fill(make-list 128)0)as z across(read)sum(incf(elt w(char-code z))))
```
High-valued score due to the wordy syntax of builtin operators of Common Lisp.
[Try it online!](https://tio.run/##tcwxCoAwDEDRqwSnZBDUycXDhFgxGG1pKgUvX72Ef358MfXUMGW9SkOLMUHVskOFBTc1w5OP0H@owDjNNBA7PMCSozvmwCv5faJesmGwAhVl59xLXAM89NWodT9suxc)
The ungolfed code:
```
(loop with w = (fill (make-list 128) 0) ; create a list to count characters
as z across (read) ; for each character of input
sum (incf (elt w (char-code z)))) ; increase count in list and sum
```
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), score 897
```
,[<<[[->+>-<<]>>[<]<[<]<[<]<[+<<]>>>>[>]>[->+>+<<]>[-<+>]<<<]<+[->>+<<]>>>[->+<]>[>]>,]<<[<]<
```
[Try it online!](https://tio.run/##ZU5BDsIwDLvvFb1n5QVW3sA96qGdQJoYO2zs/cVpYUIiUhXHcVyXLc/r/ZgetY4GmEUVjUBSNSScTxpFUpM2TSMsQjSBEEJWPyoX@JbakVs3qO3U/ROn4brN62sP021ZQt7DejzLbRtMuzFicyEQdl6wGyId5Czwk0hCPZD0IG2Cl0dLQwhftaF3mrmv6C9weULL/y/n4tJD11xynnJ5Aw "brainfuck – Try It Online")
Ends on the cell with the correct value. Assumes a cell size larger than the score of the string, otherwise it'll wrap (got a little suspicious when the interpreter said the score was 188).
[Answer]
# [Husk](https://github.com/barbuz/Husk), Score 9
```
½§+L(Σ´×=
```
[Try it online!](https://tio.run/##yygtzv7//9DeQ8u1fTTOLT605fB02////ycmIWAyAA "Husk – Try It Online")
**Explanation:**
This calculates the score as `sum_i (n_i^2 + n_i)/2`, where `i` is indexed arbitrarily across unique character types and `n_i` is the number of characters of type i in the input. But since `sum_i n_i` is the length of the input, this reduces to `(1/2) * (L + sum_i n_i^2)`
**Code breakdown:**
```
o ½ (§ + L (o Σ (´ (× =))) --With parentheses and two implicit compositions
(× =) --1 or 0 for each equality check between elements of its first and second arguments
(´ (× =)) --argdup, 1 or 0 for each equality check between elements of its only argument
(o Σ (´ (× =)) --# of equalities between pairs (this will give sum_i n_i^2)
L --length
(§ + L (o Σ (´ (× =))) --length + sum_i n_i^2
o ½ (§ + L (o Σ (´ (× =))) --1/2 * (length + sum_i n_i^2)
```
[Answer]
# Rust, ~~265~~ 255 bytes. Score: ~~1459~~ 1161
```
fn main(){let mut z=String::new();std::io::stdin().read_line(&mut z);let Z=z.trim_right_matches(|x|x=='\r'||x=='\n');let mut q:Vec<u8>=Z.bytes().collect();q.sort();let(mut k,mut W,mut j)=(0,0u8,0);for Y in&q{if*Y==W{j+=1}else{j=1;W=*Y}k+=j}print!("{}",k)}
```
Ungolfed
```
fn main() {
let mut input_string = String::new();
std::io::stdin().read_line(&mut input_string);
let trimmed = input_string
.trim_right_matches(|c| c == '\r' || c == '\n');
let mut chars: Vec<u8> = trimmed.bytes().collect();
chars.sort();
let (mut total_score, mut last_char, mut last_score) = (0, 0u8, 0);
for letter in &chars {
if *letter == last_char {
last_score += 1;
} else {
last_score = 1;
last_char = *letter;
}
total_score += last_score;
}
print!("{}", total_score);
}
```
**Edit:** improved answer by renaming variables and altering code
[Answer]
# Python 2. Score:~~142~~ 115
```
def f(a):
x=0
for y in set(a):z=a.count(y);x+=.5*z*-~z
print x
```
EDIT:-27 thanks to @Kevin Cruijssen
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), score: 681
```
s =iNPUT
Y _table()
d S LEN(1) . x REM . S :F(b)
Y<X> =y<X> + 1 :(D)
b Z _convert(Y,'aRrAy')
N j =J + 1
G _z[j,2] :f(q)
o =o + g * G + g :(N)
q OUtpuT _O / 2
end
```
[Try it online!](https://tio.run/##fc5JawJBEAXg8@tfUTe7VRTF05QdCLiA6BhcwIXQOHESFJl2GUX989qO4ALGS71DPR7fJrKBXZROJ2ygZ/5XvycwhIknwSKUSkzRRbPqy4KiHO2pU2257MKryUC5YnnwAX1wlzJUgCcrSgQYwfzYaBeuYznMpiad9echpYSPOXTj0hOowxzH82zxG96vXLkhC23d64/SVL@km/KVWKHdj5fbHkyb8lQUYTRNnCZx8oOT3zn56jRPTv7HyXcnO6d@dPJrJ9@cOnGyc54B "SNOBOL4 (CSNOBOL4) – Try It Online")
looks a bit scary, but SNOBOL matches identifiers case-insensitively, which dropped the score by around 100 points. Note that it requires a single line of input, so I've replaced `\n` with `;` in the input field (which is still valid SNOBOL).
The SNOBOL4 implementation on TIO allows for an additional 16 point golf, as `=` and `_` are [both allowable as the assignment operator](http://www.snobol4.org/csnobol4/curr/doc/snobol4.1.html). How neat!
[Answer]
# Mathematica, score 42
```
Total[#^2+#].5&@*CharacterCounts
```
**input**
>
> ["abcdefg"]
>
>
>
thanks to hftf
thanks to att
[Answer]
# [Husk](https://github.com/barbuz/Husk), 5 bytes, score 5
```
ΣṁŀgO
```
[Try it online!](https://tio.run/##yygtzv7//9zihzsbjzak@////z8xKTExOTEJAA "Husk – Try It Online")
Different and (so far) shorter strategy to [Natte's](https://codegolf.stackexchange.com/a/241169/95126) or [Sophia Lechner's](https://codegolf.stackexchange.com/a/158410/95126) Husk answers.
```
O # sort the input
g # and group equal adjacent values;
ṁ # now, for each group
ŀ # make a range 1..length of the group
ṁ # and flatten all the ranges into one list;
Σ # then output the sum
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), score ~~27~~ ~~18~~ ~~11~~ 10
*Reduced score by 7 thanks to @Adám by using a tradfn and using `1⊥` to sum the frequencies*
*Reduced score by 1 thanks to @rabbitgrowth by using a function instead*
```
1⊥{+/⍳≢⍵}⌸
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/hR2wTDR11Lq7X1H/VuftS56FHv1tpHPTuAMurYxNUB "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-x`](https://codegolf.meta.stackexchange.com/a/14339/), ~~9~~ ~~7~~ 6 points
```
ü mÊcõ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LXg&code=/CBtymP1&input=Ivwgbcpj9SI)
[Answer]
# Python 2, score 83
```
lambda z:sum((2*z.count(x)+1)**2/8for x in set(z))
```
[**Try it online**](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHKqrg0V0PDSKtKLzm/NK9Eo0JT21BTS8tI3yItv0ihQiEzT6E4tUSjSlPzf7FtDJc66frUuQqKMvNKFNI0ijX/AwA)
`1/8 (1 + 2 n)^2 -1/8` is the same as `n (n+1) / 2`. Floor division removes the need to subtract `1/8`.
[Answer]
## Clojure, score 96
```
#(apply +(for[[k j](frequencies %)](*(inc j)j 0.5)))
```
Five spaces and pairs of brackets...
[Answer]
# [Actually](https://github.com/Mego/Seriously), score 12
```
;╗╔⌠╜cRΣ⌡MΣ
```
[Try it online!](https://tio.run/##S0wuKU3Myan8/9/60dTpj6ZOedSz4NHUOclB5xY/6lnoe27x//9KOGSUAA "Actually – Try It Online")
Explanation:
```
;╗╔⌠╜cRΣ⌡MΣ (implicit input: S)
;╗ save a copy of S in register 0
╔ uniquify S (call it A)
⌠╜cRΣ⌡M for each unique character in A:
╜c count the number of occurrences in S
R range(1, count+1)
Σ sum
Σ sum
```
Repeating the `Σ` is two points less than using an alternative formulation with no repeated characters (`i`+Y`).
[Answer]
# [J](http://jsoftware.com/), score 23
```
$-:@+[:+/,/@(=/~)
```
[Try it online!](https://tio.run/##y/r/P83WSkXXykE72kpbX0ffQcNWv07zf2pyRr5CmoI6how6F0wqMSkxMTkxCSEQUJSfXpSYm5uZl64QUFpVlZNarKCm4Jyfkqrgnp@ThlCIYClAALKhySmpaelIAo7q/wE "J – Try It Online")
[Answer]
## F#, score:~~1264~~1110
-154 points, thanks to @Laikoni
```
let x(y:bool)=System.Convert.ToInt32(y)
let rec p(k:string)q=
let j=k.Length
if(j=1)then(x(k.[0]=q))else p k.[0..(j-2)] q+x(k.[j-1]=q)
let rec d(a:string)=
let z=a.Length
if(z<2)then z else d a.[0..(z-2)]+p a (a.[z-1])
```
You need to call the d function. In a more readable form:
```
let x (y:bool)=
System.Convert.ToInt32(y)
let rec e (c:string) b=
let j=c.Length
if(j=1)then
(x(c.[0]=b))
else
e c.[0..(j-2)] b+x (c.[j-1]=b)
let rec d (a:string)=
let h=a.Length
if(h<2)then
h
else
d a.[0..(h-2)]+e a (a.[h-1])
```
### Explanation
It is a recursive algorithm, the base case is, if the length of the string is less than 2 (0 or 1), the score will be the length of the string. This is because, if the length is 0 (empty string), we have no characters, so the score is 0, and if the length is 1, that means, that the string consists of only 1 character, so the score is 1.
Otherwise it trims the last character of the string, and to the score of the truncated string adds the count of the last character in the untruncated string.
The counting algorithm is also recursive. Its base case is, when the length of the string is one, then the count is 1, if the string matches with the character, and 0 otherwise. This can also be done, if we convert the bool to an int, and this results in a lower score.
Otherwise it trims the last character of the string, calculates the count of that string, and if the last character matches the character, we are calculating the count of, adds one to the count. This is again, better, if we convert that boolean to an int.
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 39 bytes, Score 54
```
BEGIN{RS="(.)"}{M+=++s[RT]}END{print M}
```
[Try it online!](https://tio.run/##SyzP/v/fydXd0686KNhWSUNPU6m22lfbVlu7ODooJLbW1c@luqAoM69EwbeWaIUA "AWK – Try It Online")
[Answer]
**FIREBIRD, score 3577**
Version to calculte the score:
```
SELECT COALESCE(SUM(C),0)FROM(WITH RECURSIVE T AS(SELECT 1 AS I,SUBSTRING(CAST(:V AS BLOB)FROM 1 FOR 1)AS S FROM RDB$DATABASE UNION ALL SELECT I+1,SUBSTRING(CAST(:V AS BLOB)FROM I+1 FOR 1)FROM T WHERE I < CHAR_LENGTH(CAST(:V AS BLOB)))SELECT T.*,(SELECT COUNT(T2.I) FROM T T2 WHERE T2.S=T.S AND T2.I<=T.I)AS C FROM T WHERE CAST(:V AS BLOB) <> '')
```
Below is the idented version of the code, in case anyone want to now. I'm sorry for any mistakes, first time here actually posting!
```
SELECT COALESCE(SUM(C), 0)
FROM (
WITH RECURSIVE T AS (
SELECT 1 AS I, SUBSTRING(CAST(:V AS BLOB) FROM 1 FOR 1) AS S
FROM RDB$DATABASE
UNION ALL
SELECT I+1, SUBSTRING(CAST(:V AS BLOB) FROM I+1 FOR 1)
FROM T
WHERE I < CHAR_LENGTH(CAST(:V AS BLOB))
)
SELECT T.*, (SELECT COUNT(T2.I) FROM T T2 WHERE T2.S = T.S AND T2.I <= T.I) AS C
FROM T
WHERE CAST(:V AS BLOB) <> ''
)
```
---
**Explanation**
I start my select in a system table `SELECT 1 AS I, SUBSTRING(CAST(:V AS BLOB) FROM 1 FOR 1) AS S FROM RDB$DATABASE`, which always has only one row. Using that only one row, I return 1 as a column **I**, and the character that exists in the input in the I value.
Let's say I've passed 'abaacab' as input:
```
╔═══╦═══╗
║ I ║ S ║
╠═══╬═══╣
║ 1 ║ a ║
╚═══╩═══╝
```
In the UNION ALL part, I start to increment the index from the first select, until it reaches the end of the input. So, in the example I would get this:
```
╔═══╦═══╗
║ I ║ S ║
╠═══╬═══╣
║ 1 ║ a ║
║ 2 ║ b ║
║ 3 ║ a ║
║ 4 ║ a ║
║ 5 ║ c ║
║ 6 ║ a ║
║ 7 ║ b ║
╚═══╩═══╝
```
After that, I also select the count of ocurrences from the value on **S**, that has already appeared in indexes below the **I**. So, in a column **C** I now have the 'cost' of that character, which I only need to SUM after to get the value.
```
╔═══╦═══╦═══╗
║ I ║ S ║ C ║
╠═══╬═══╬═══╣
║ 1 ║ a ║ 1 ║
║ 2 ║ b ║ 1 ║
║ 3 ║ a ║ 2 ║
║ 4 ║ a ║ 3 ║
║ 5 ║ c ║ 1 ║
║ 6 ║ a ║ 4 ║
║ 7 ║ b ║ 2 ║
╚═══╩═══╩═══╝
```
I used BLOB as the type from the input, to not get limited by size.
[Answer]
## [K](https://en.wikipedia.org/wiki/K_(programming_language))/[Kona](https://github.com/kevinlawler/kona), score 19
```
+/,/1+!:'(#:)'=
```
Works as:
```
= (implicitly take arg as input), group -> make dictionary of characters to their occurring indices
(#:)'= count each of these
1+!:'(#:)'= get a list from 0->n-1 for each of these counts, add one to each
+/,/1+!:'(#:)'= finally, reduce to single list, sum reduce this list
```
Example:
```
k)+/,/1+!:'(#:)'="+/,/1+!:'(#:)'="
19
k)+/,/1+!:'(#:)'="abaacab"
14
```
Legible q equivalent:
```
(sum/)raze 1+til count each group
```
[Answer]
# [Pyke](https://github.com/muddyfish/PYKE), score 7
```
cemSss
```
[Try it here!](http://pyke.catbus.co.uk/?code=cemSss&input=%5B%22c%22%2C%22e%22%2C%22m%22%2C%22S%22%2C%22s%22%2C%22s%22%5D&warnings=1&hex=0)
```
c - count_occurrences(input)
e - values(^)
mS - [range(1,i+1) for i in ^]
ss - sum(sum(i)for i in ^)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 9 bytes; Score ~~10~~ 9
```
ṢŒrzẆṪRẎS
```
[Try it online!](https://tio.run/##y0rNyan8///hzkVHJxVVPdzV9nDnqqCHu/qC/2MTBAA "Jelly – Try It Online")
This is the first time I use Jelly, and I didn't want to check other people's answers because I wanted to try it myself. I probably reinvented the wheel a couple times there. Suggestions and feedback are greatly appreciated.
EDIT: -1 byte for removing `ɠ` and taking the input as an argument.
Explanation:
```
ṢŒrzẆṪRẎS #Main Link; input abaacab
Ṣ #sorts input; aaaabbc
Œr #run-length encode, or the number of times a character appears; a4b2c1
z #zip; ['abc', [4, 2, 1]]
Ẇ #takes every contiguous sublists
Ṫ #Pops the last element; [4, 2, 1]
R #Takes the range of every element; [[1,2,3,4],[1,2],1]
Ẏ #Collapses every element into a single array; [1,2,3,4,1,2,1]
S #Sum and implicitly print; 14.
```
(no idea why, but the code doesn't work without `Ẇ`,
although it gives the exact same output as `z`)
[Answer]
# [J](http://jsoftware.com/), score 14
```
1#.2!1+#/.~
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DZX1jBQNtZX19er@a3KlJmfkK6QppJalFlUqqCcmJSYmJyapK1grqAcU5acXJebmZualKwSUVlXlpBYrqCk456ekKrjn56SB1YAJBQgAsxOTklNS09IhbEd1mPHqSJaq/wcA "J – Try It Online")
Outgolfed by the other J solution, but figured I'd post this anyways since it uses a slightly different method.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), score 12 (+2 for `-x`) = 14
```
¬n ó¥ ËÊõÃc
```
## Explanation
```
¬n ó¥ ËÊõÃc "abaacab"
¬ // Split the input into an array of chars ["a","b","a","a","c","a","b"]
n // Sort ["a","a","a","a","b","b","c"]
ó¥ // Partition matching items [["a","a","a","a"],["b","b"],["c"]]
Ë // map; For each array:
Ê // Get the length x [4,2,1]
õ // Create a range [1...x] [[1,2,3,4],[1,2],[1]]
à // }
c // Flatten [1,2,3,4,1,2,1]
-x // Sum 14
```
[Try it online!](https://tio.run/##AT0Awv9qYXB0///CrG4gw7PCpSDDi8OKw7XDg2P//yJQcm9ncmFtbWluZyBQdXp6bGVzICYgQ29kZSBHb2xmIi14 "Japt – Try It Online")
[Answer]
# [Attache](https://github.com/ConorOBrien-Foxx/attache), score 36
```
Sum@Map&:(Count#Last)@Prefixes
```
[Try it online!](https://tio.run/##SywpSUzOSP3vkpqWmZcarZKm8z@4NNfBN7FAzUrDOb80r0TZJ7G4RNMhoAiooiK1@H8sV0BRZl5JdFq0En6VSrGx/wE "Attache – Try It Online")
## Explanation
```
Sum@Map&:(Count#Last)@Prefixes
```
This is a composition of 3 functions:
* `Prefixes` - this simply obtains the prefixes of the input
* `Map&:(Count#Last)` - This is a mapped fork. This is equivalent to `arr.map { e -> e.count(e.last) }` So, for each character, this counts the occurrences of that character so far.
* `Sum` - this sums all of these numbers.
[Answer]
# MS-SQL, score 308
I'm using a completely different technique from [my other answer](https://codegolf.stackexchange.com/a/127312/70172), with additional restrictions, so I'm submitting them separately:
```
SelEcT SUm(k)FROM(SELECT k=couNt(*)*(CoUNT(*)+1)/2froM spt_values,z WHERE type='P'AND number<len(q)GROUP BY sUBstring(q,number+1,1))L
```
Caveats: this must be run from the `master` database of a MS-SQL server set to a case-sensitive collation (mine is set to SQL\_Latin1\_General\_CP850\_BIN2).
Input is via varchar field *q* in pre-existing table *z*, [per our IO rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341). Formatted:
```
SelEcT SUm(k)
FROM
(SELECT k=couNt(*)*(CoUNT(*)+1)/2
froM spt_values,z
WHERE type='P'
AND number<len(q)
GROUP BY sUBstring(q,number+1,1)
)L
```
The trick here is to use a "[number table](https://codegolf.stackexchange.com/questions/129211/sql-select-number-ranges)" to join with the input table, which allows me to separate each character into its own row, then group by matching characters, count them up, calculate the score of each, and sum them all together. All the rest is minimizing score by playing with character case, since SQL keywords are not case sensitive.
MS-SQL has a system table in the `master` database called `spt_values` with a lot of junk in it, but I restrict it to `type='P'`, I get a nice number table with 0 through 2047.
[Answer]
# [K4](http://kx.com/download/), score 15
**Solution:**
```
+/,/{1+!#x}'=
```
**Example:**
```
q)k)+/,/{1+!#x}'="Programming Puzzles & Code Golf"
47
```
**Explanation:**
```
+/,/{1+!#x}'= / the solution
= / group
{ }' / apply lambda to each (')
x / implicit lambda input
# / count length
! / range 0..n
1+ / add one
,/ / flatten list
+/ / sum up
```
**Notes:**
In **Q** this could be written as:
```
q)sum raze { 1 + til count x } each group "Programming Puzzles & Code Golf"
47
```
[Answer]
# [Python 3](https://docs.python.org/3/), score ~~89~~ 85
```
lambda y:sum(y[:x+1].count(v)for x,v in enumerate(y))
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklkbPSqrg0V6My2qpC2zBWLzm/NK9Eo0wzLb@Is0KnTCEzTyE1rzQ3tSixJFWjUlPzf0FRJlBBmoYSWdqVgCYAAA "Python 3 – Try It Online")
[Answer]
# [Standard ML](http://www.mlton.org/), 66 bytes, score 113
```
fun$(a::z)=1+length(List.filter(fn y=>y=a)z)+ $z|
$_=0;$o explode;
```
This code defines an anonymous function which is bound to the implicit result identifier `it`. [Try it online!](https://tio.run/##lZBBSwMxEIXP7q8YwiJJi6WVgtIQQXoQwUPB66LMtsm6kE3KZgpt8L@vaVNY8ebc5nvvzcALnb3rLHk3DObgSo6rVRRqMbXaNfTF39pAM9Na0j03Dk7q6aRQRDG9KeN3UX6quSw96OPe@p2W5xNAOhAEULDvW0f81dGM/DulpeFtUgR8AKscE7IoLl6GNeIWayaBT2CxhIm4CpveNz12XYrC5hCj1QFuYZ1ewYu3JgeWD2Mgk/kIIE/m94@jgPV2p02ThV8X8PnqHdG/eqkoFVO5v80wOfwA "Standard ML (MLton) – Try It Online")
### Explanation
The ungolfed code looks like this:
```
fun f (a::z) = 1 + length (List.filter (fn y => y=a) z) + f z
| f _ = 0
val g = f o explode
```
The function `g` takes a string as input, converts it to a list of characters with `explode`, and passes it on to the function `f` which recurses over the list, with `a` being the current character and `z` being the remaining list. For each `a` the number of occurrences of `a` in `z` is computed by filtering `z` to contain only chars equivalent to `a` and taking the length of the resulting list. The result is incremented by one to account for the current occurrence of `a` and added to result of the recursive call of `f` on `z`.
[Answer]
# PHP, 44 bytes, score 78:
```
While($C=ORD($argn[$p++]))$s-=++$$C;EcHo-$s;
```
Almost [Jörg´s solution](https://codegolf.stackexchange.com/a/127353/55735), but one byte shorter.
---
## PHP, 51 bytes, score 80
```
ForEach(COUNT_CHARS($argn)As$p)$z-=~$p*$p/2;echo$z;
```
---
[Answer]
# [Perl6/Rakudo](https://perl6.org/), 45 bytes, score 66
Run with `perl -ne`:
```
say [+] bag(.comb).values.map({($_+1)*$_/2});
```
Uses the essential nature of a Bag (like a set with a count per member).
Step by step:
```
.say; # abaacab
say .comb; # (a b a a c a b)
say bag(.comb); # Bag(a(4), b(2), c)
say bag(.comb).values; # (2 4 1)
say bag(.comb).values.map({($_+1)*$_/2}); # (3 10 1)
say [+] bag(.comb).values.map({($_+1)*$_/2}); #14
```
Also note that each character's score can be calculated from its occurrences as `(n+1)*n/2`.
Edited because I cannot evidently read.
[Answer]
# [><>](https://esolangs.org/wiki/Fish), score 33
```
0vAB;n*<
p>i:0(?^:ag1+:}r-@a
```
[Try it online!](https://tio.run/##S8sszvj/36DM0ck6T8uGq8Au08pAwz7OKjHdUNuqtkjXIRG/LAA "><> – Try It Online")
28 bytes, with 2 occurrences each of `a` and `0`, and 3 occurrences of `:`. `AB` can be replaced by any two characters which don't appear anywhere else in the code.
Works by storing the current character count in the code grid on row 10. The sum is actually a negative sum to start with, and the -1 from reaching the end of STDIN is multiplied with this to turn it back into a positive number.
] |
[Question]
[
## Challenge:
Given a string only containing upper- and/or lowercase letters (whichever you prefer), put `tape` horizontally to fix it. We do this by checking the difference of two adjacent letters in the alphabet (ignoring wrap-around and only going forward), and filling the space with as much `TAPE`/`tape` as we would need.
---
### Example:
Input: `abcmnnnopstzra`
Output: `abcTAPETAPETmnnnopTAstTAPETzra`
***Why?***
* Between `c` and `m` should be `defghijkl` (length 9), so we fill this with `TAPETAPET`;
* Between `p` and `s` should be `qr` (length 2), so we fill this with `TA`;
* Between `t` and `z` should be `uvwxy` (length 5), so we fill this with `TAPET`.
## Challenge rules:
* The difference only applies forward, so no tape between `zra`.
* It is possible to have multiple of the same adjacent letters like `nnn`.
* You are allowed to take the input in any reasonable format. Can be a single string, string-array/list, character-array/list, etc. Output has the same flexibility.
* You are allowed to use lowercase and/or uppercase any way you'd like. This applies both to the input, output, and `TAPE`.
* It is possible no `TAPE` is necessary, in which case the input remains unchanged.
## General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link to a test for your code.
* Also, please add an explanation if necessary.
---
## Test cases:
```
Input: "abcmnnnopstzra"
Output: "abcTAPETAPETmnnnopTAstTAPETzra"
Input: "aza"
Output: "aTAPETAPETAPETAPETAPETAPEza"
Input: "ghijk"
Output: "ghijk"
Input: "aabbddeeffiiacek"
Output: "aabbTddeeffTAiiaTcTeTAPETk"
Input: "zyxxccba"
Output: "zyxxccba"
Input: "abccxxyz"
Output: "abccTAPETAPETAPETAPETAPExxyz"
Input: "abtapegh"
Output: "abTAPETAPETAPETAPETtaTAPETAPETAPETApeTgh"
Input: "tape"
Output: "taTAPETAPETAPETApe"
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
OI’“¡ʂƁ»ṁ$€ż@
```
[Try it online!](https://tio.run/##ATQAy/9qZWxsef//T0nigJnigJzCocqCxoHCu@G5gSTigqzFvED///8iYWJjbW5ubm9wc3R6cmEi "Jelly – Try It Online")
### Explanation
```
OI’“¡ʂƁ»ṁ$€ż@ – Full program. Take a string as a command line argument.
O – Ordinal. Get the ASCII values of each character.
I’ – Get the increments (deltas), and subtract 1 from each.
€ – For each difference I...
“¡ʂƁ»ṁ$ – Mold the compressed string "tape" according to these values.
Basically extends / shortens "tape" to the necessary length.
ż@ – Interleave with the input.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~14~~ 12 bytes
```
'¡ÉIÇ¥<∍‚ζJJ
```
[Try it online!](https://tio.run/##MzBNTDJM/f9f/dDCw52eh9sPLbV51NH7qGHWuW1eXv//R6snqusoQIgkOJECJ1LhRBqcyIQTYG3JcCXZ6rEA "05AB1E – Try It Online")
**Explanation**
```
'¡É # push the string "tape"
I # push input
Ç # convert to a list of character codes
¥ # calculate deltas
< # decrement
∍ # extend the string "tape" to each of these sizes
# results in an empty string for sizes smaller than zero
‚ζ # zip with input (results in a list of pairs)
JJ # join to a list of strings and then to a string
```
[Answer]
# [Haskell](https://www.haskell.org/), 58 bytes
```
f(x:y:r)=x:take(length[x..y]-2)(cycle"TAPE")++f(y:r)
f s=s
```
[Try it online!](https://tio.run/##JYqxCsIwFAB3v@KRKaHawbHQwcFNQdCtdHh5TWxsGksTIcnPR6zTcceN6CdlbSmaxyY1q2hjE3BS3Cr3DGMX6zr1h6PglMgq9jjdzkxUlea/d6fBt77MaBy0MONyBb58wj2sFwc1aAEdQ0mzc@69@JBXZHtgmDc8R/OaNkcph0EprY1BUlvLKUYi@f8lUYwps758AQ "Haskell – Try It Online") The function `f` recurses over the string and looks at consecutive characters `x` and `y`. `cycle"TAPE"` yields the infinite string `"TAPETAPETAPE..."`. `[x..y]` gets the range of characters from `x` to `y` inclusive, so we need to subtract two from the length. In case `x` occurs later in the alphabet then `y` or both are the same character, we get a negative number after subtracting, but luckily `take` accepts those as well and just takes nothing.
[Answer]
# [Perl 5](https://www.perl.org/), `-F` 46 bytes
```
#/usr/bin/perl -F
use 5.10.0;
say map{((P,E,T,A)x7)[2..-$^H+($^H=ord)],$_}@F
```
[Try it online!](https://tio.run/##K0gtyjH9X1qcqmCqZ2igZ2D9vzixUiE3saBaQyNAx1UnRMdRs8JcM9pIT09XJc5DWwNI2OYXpWjG6qjE1zq4/f@fmJScm5eXl19QXFJVlPgvv6AkMz@v@L@uGwA "Perl 5 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~96~~ ~~87~~ 80 bytes
```
lambda s:''.join(c+(C>c)*('TAPE'*6)[:ord(C)+~ord(c)]for c,C in zip(s,s[1:]+' '))
```
[Try it online!](https://tio.run/##VcyxCsIwFIXh3acIXZJri6CDQ0FBiruDW@2Q3DY21SYh6ZBm8NUjTpLp8PPBsesyGn1I8vRIbz6LnhNfU7qbjNIMS9acEbaM3i@3K90eoa2N61kD5ee3CJ00jmDVEKVJVJb5yrf7uispoQDJOqUXIlnBBc5aa2P9Eh0vYPOXmOVzVNMrcy5E3w@DlEpxHDKLawiIIv8TiCGssYD0BQ "Python 2 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 64 bytes
```
t="TAPE"++t
e=fromEnum
f(x:y:z)=x:take(e y-e x-1)t++f(y:z)
f x=x
```
Handles strings of either uppercase *or* lowercase letters, but not both.
[Try it online!](https://tio.run/##bVDNasQgED6vTzH1lCXsodeAhy1sLy20UB9gjRkbm0QXY6iRffc0P5DdphUG9PubGUvRVljXw@AZ5cf3E01TT5ApZ5uT6RqikpD1WdyzkHlRYYLQHxDC4XHv01QlE0UUBBaGAOe2tF1dPOEZeoArBGBsvDG4dP7Du1cD9O3lgZLd7grWl@i@dYsjjc5ZB/RZ6JoS0ghtRrCwBMajgIpcNsYYe2l9dILet5m4aeq5FhE/tn5@Tto1Im59q2tT8Wb6LPVX9du2QGuqyPOiQFRKayFxo51YvtD8OAq45Dh3uQXEPgQp881sK3r3ATKEPv5ZXf63wawcfgA "Haskell – Try It Online")
[Answer]
# C, 84 bytes
```
i,l;f(char*s){for(;*s;)for(putchar(l=*s++),l=s[i=0]+~l;i<l;)putchar("TAPE"[i++%4]);}
```
[Try it online!](https://tio.run/##bY09D4IwFEV3fgVpYtJSTBzcKoODu4MbYWgfFJ6WQigmfAT/eoVBJ@50c3JuLhxLAO8xNkJTqGQXOTbrpqMicoJtpX33G6cmiRznLDaJSzE5ZfxjBF6MYD@BPK73G0mR88M5Y2LxaPuwlmgpC@YgXKMpkQpqa23Tun7qJGFiXTtK1vI3pl1cVvh87fpSqTwvCq0RJRS7zjQOA4Da/1MAwzBOG1r8Fw)
# C (run on Windows Command Prompt), 81 bytes
```
i,l;f(char*s){for(;putchar(l=*s++);)for(l=s[i=0]+~l;i<l;)putchar("TAPE"[i++%4]);}
```
**Output:**
[![](https://i.stack.imgur.com/c09h7.png)](https://i.stack.imgur.com/c09h7.png)
[Answer]
# [Python 3](https://docs.python.org/3/), 98 bytes
```
lambda a:"".join(sum(zip(a,[("TAPE"*9)[:y>x and~ord(x)+ord(y)]for x,y in zip(a,a[1:])]),()))+a[-1]
```
[Try it online!](https://tio.run/##bY89T8MwEIbn5ldYnmwakCoWailIGRiYYPAWMjiOQ1waO0ocYXvgr4d8oNStGE6nu/d97qN1ptbqcaySj/HMmqJkgBEIH05aKtQPDfKyRSzOEKTp@wu8O@KMuGcLmCp/dFcii/dzcjivdAds7IBUYGVYdiA5znGMMMZ7lt0f8vG7lmcBaDcIEu0kSCZ3OxiEsycyydFOB63j2mo7qQyqkMQgSYDGE7caxtc5EwBZwRullG574zsGo7fBbMJ89RKrg6a9WcrFGG0T/BW2QTfhQ@azlqevgPqrLzNZUZSlEFUlJeMitM4SXTWaTirlVCw7Qt47azkvwsMurSj4nVvr/PXX/L/rF9sv "Python 3 – Try It Online")
-1 byte thanks to Asone Tuhid
[Answer]
# [Scala](http://www.scala-lang.org/), 66 bytes
```
(s:String)=>s./:("z"){(o,c)=>o+("TAPE"*6).take(c-o.last-1)+c}.tail
```
[Try it online!](https://tio.run/##TY/BagIxEIbveYqQU1J1i5cehBU89NaCYF9gMptoNCbLzlDiis@@xh7Kzm2@H76ZnxAiTNmeHbL8hpCkK@xSR3LX9@IupPyFKL1sJ02bAw8hHU27peZ9o9WozF3nJVaQF1r97Paf6u3DNAwXp3GVmwjEq7VZ4KOyEKeXih0xyVZ@BWJd9a9RYPGaUso98TiAWv7zcbYcT@F8mWVgbdc5530IgG6WjLdSEO3cYxFLudWHxd/9xufBAZ40tdu@duKYtNdkjBHiMT0B "Scala – Try It Online")
# Explanation
```
/: foldLeft over the string
("z") starting with a non-empty string to we don't have to handle the first iteration in a special way
"TAPE"*6 generate a long enough string of TAPETAPETA...
.take(c-o.last-1) take the difference between this character and the previous (now the last char in the output so far) characters from the TAPETAPETA... string. o.last will always be safe because we start with a non-empty string.
o+...+c append it to the output so far ... and add this character to the end
.tail get rid of the leading z we added
```
[Answer]
# [PHP](https://php.net), 85 bytes
```
$s=str_split($argv[1]);foreach($s as$l)echo str_pad($l,ord(next($s))-ord($l),'TAPE');
```
[Try it online!](https://tio.run/##K8go@G9jXwAkVYpti0uK4osLcjJLNFQSi9LLog1jNa3T8otSE5MzNFSKFRKLVXI0U5Mz8hVACgsSUzRUcnTyi1I08lIrgFqKNTV1QTygIh31EMcAV3VN6////ycmJefm5eXlFxSXVBUlAgA)
### Explanation
```
$s = str_split($argv[1]); // convert the parameter string to an array
foreach($s as $l) // loop the array
echo str_pad( // print
$l, // the letter
ord(next($s)) - ord($l), // calculate the distance to the next letter using ASCII values
'TAPE' // padding string
); // profit!
```
[Answer]
# Javascript, ~~131~~ 127 Bytes
4 Bytes saved thanks to [Rick Hitchcock.](https://codegolf.stackexchange.com/users/42260/rick-hitchcock)
```
z=(a=>[...a].reduce((x,y)=>x+[...Array((f=y[c='charCodeAt']()-x.slice(-1)[c]())>1?f-1:0)].reduce((e,r,t)=>e+"TAPE"[t%4],"")+y))
```
## Unrolled
```
z=a=>[...a].reduce(
(x,y)=>
x + [...Array(
(f = y.charCodeAt()-(x.slice(-1).charCodeAt()) ) > 1 ? (f-1) : 0
)].reduce(
(e,r,t)=>
e + "TAPE"[t%4],"") + y
);
```
My Problem here is that Javascript had no clean way to get the distance between character a and b.
```
<script>
z=(a=>[...a].reduce((x,y)=>x+[...Array((f=y[c='charCodeAt']()-x.slice(-1)[c]())>1?f-1:0)].reduce((e,r,t)=>e+"TAPE"[t%4],"")+y))
</script>
<main>
<input id="input-box" type="text">
<pre id=output>output</pre>
</main>
<script>
inputBox = document.getElementById("input-box");
inputBox.addEventListener("keyup", function(e){
output.innerText = z(inputBox.value);
});
</script>
```
[Answer]
# [Python 2 / 3](https://docs.python.org/3/), ~~70~~ 69 bytes
```
f=lambda s,*t:t and s+('TAPE'*6)[:max(ord(t[0])+~ord(s),0)]+f(*t)or s
```
[Try it online!](https://tio.run/##XYyxDsIgFEV3v4J0KbQdmpg4NHFwcHdwazo8oFhUoIE3UAZ/Hetm2O495@auGy7OHnNW5zcYLoGErsEBCVhJQkvr@@V2rZsTGwcDkTovKY79xNrPLwbW9WxqFW2QOU9CXr22SPdeARfGWuvWgMlDxdjhz6UCPBb9fBUb4FzKeVZKaxBzYdMWoxC8/OVCxLilneYv "Python 3 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes
```
⭆θ⁺…TAPE∧κ⊖⁻℅ι℅§θ⊖κι
```
[Try it online!](https://tio.run/##TYxBCsIwFESvErr6hXgCV6F14aIY0At8k48NTX/SNIp6@TQigrOYeYuZMSMmE9CXopPjDOdc4zZghEUK7e8rdC/jqRtDhOai9KGRQrGFSYqeTKKZOJOFwXGtnpJ1jB5cK8WPVT6ypefn7n8wtV9J4arvS8GrmZk5xDW/E5bdw28 "Charcoal – Try It Online") Explanation:
```
θ θ Input string
⭆ Map over characters
κ Current index
⊖ Decremented
§ Index into string
ι Current character
℅ ℅ Ordinal
⁻ Subtract
⊖ Decremented
κ Current index
∧ Logical and
TAPE Literal string
… Mold to length
ι Current character
⁺ Concatenate
Implicitly print
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 29 bytes
```
O@a{"TAPE"@<MX[0v-$-Ag]}.BMPa
```
Takes input as a command-line argument (lower- or uppercase, doesn't matter).
[Try it online!](https://tio.run/##K8gs@P/f3yGxWinEMcBVycHGNyLaoExXRdcxPbZWz8k3IPH///@JScm5eXl5@QXFJVVFiQA "Pip – Try It Online")
### Explanation
```
O@a{"TAPE"@<MX[0v-$-Ag]}.BMPa
a is 1st cmdline arg; v is -1 (implicit)
O Output without newline
@a the first character of a
MPa Map this function to pairs of successive characters of a:
Ag Get the ASCII codes of the two characters
$- Fold on subtraction (i.e. asc(first)-asc(second))
v- -1 minus the above (i.e. asc(second)-asc(first)-1)
[0 ] A list containing 0 and the above
MX Max of the list
@< The first ^ characters (with cyclic indexing)
"TAPE" of this string
{ }.B Concatenate the second character
```
[Answer]
# JavaScript (ES6), ~~80~~ 78 bytes
```
f=([s,...S],t=S[0])=>t?s.padEnd((t>s)*(parseInt(s+t,36)-370)%37,'TAPE')+f(S):s
```
The distance between two characters can be determined by converting their concatenation to base 36, subtracting 370, modulus 37.
For example, `(parseInt('cy',36)-370)%37 == 22`.
We can then use `padEnd` to fill in the gaps, and recursion to handle the loop.
**Test Cases:**
```
f=([s,...S],t=S[0])=>t?s.padEnd((t>s)*(parseInt(s+t,36)-370)%37,'TAPE')+f(S):s
console.log(f('abcmnnnopstzra'));
console.log(f('aza'));
console.log(f('ghijk'));
console.log(f('aabbddeeffiiacek'));
console.log(f('zyxxccba'));
console.log(f('abccxxyz'));
console.log(f('abtapegh'));
console.log(f('tape'));
```
[Answer]
# [K4](http://kx.com/download/), 48 bytes
**Solution:**
```
{,/_[w;x],',[1_d w:&0<d:-1+-':"j"$x;0]#\:"TAPE"}
```
**Examples:**
```
q)k){,/_[w;x],',[1_d w:&0<d:-1+-':"j"$x;0]#\:"TAPE"}"abcmnnnopstzra"
"abcTAPETAPETmnnnopTAstTAPETzra"
q)k){,/_[w;x],',[1_d w:&0<d:-1+-':"j"$x;0]#\:"TAPE"}"aza"
"aTAPETAPETAPETAPETAPETAPEza"
q)k){,/_[w;x],',[1_d w:&0<d:-1+-':"j"$x;0]#\:"TAPE"}"zyxxccba"
"zyxxccba"
q)k){,/_[w;x],',[1_d w:&0<d:-1+-':"j"$x;0]#\:"TAPE"}"aabbddeeffiiacek"
"aabbTddeeffTAiiaTcTeTAPETk"
```
**Explanation:**
Fairly simple solution, but a high byte count... Find the deltas, take from the string `"TAPE"`, join to the original string cut where the deltas are > 1.
```
{,/_[w;x],',[1_d w:&0<d:-1+-':"j"$x;0]#\:"TAPE"} / the solution
{ } / lambda
"TAPE" / the string TAPE
#\: / take each-left
,[ ; ] / join (,)
0 / zero (ie append zero)
"j"$x / cast input to int
-': / deltas
-1+ / subtract 1
d: / assign to d
0< / delta greater than 0?
& / indices where true
w: / assign to w
d / index into deltas at w
1_ / drop first
,' / join each-both
_[w;x] / cut input x at indices w
,/ / flatten
```
[Answer]
# Excel VBA, 106 bytes
An anonymous VBE immediate window function that takes input as an uppercase string via cell `A1` and outputs to the VBE immediate window.
```
a=90:For i=1To[Len(A1)]:c=Mid([A1],i,1):b=Asc(c):For j=2To b-a:?Mid("peta",j Mod 4+1,1);:Next:?c;:a=b:Next
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~59~~ 53 bytes
```
->s{s.reduce{|x,y|x+y.rjust(y.ord-x[-1].ord,"TAPE")}}
```
[Try it online!](https://tio.run/##bY@xbsMgEIb3PEXE1Ko2ah7AlTx0z8CGGOCMY6eqYwGWANvP7ubAypB0OOn4/@@/O8ykwtZWW/llZ0uNbibQ8@KLsPiPQM11su4t0JtpSs/Lk8CuIKw@f5P3dd34gROp4HcYhttoXTSSFEdUkEiVLVZbl55IiAJTMaMP8Knizl26/vqDZG5yVirVNFq3bd9L0MlGjWWR1XeZAdNp1p6JwXsAlZY@@jxNAXgf4n45/HdN8nfayVFfuky/sO7pQ6NmdzYlMYepV4SIg6BaQjcvbhmPLXf8U1DopLGiqhw/iXX7Aw "Ruby – Try It Online")
This is actually pretty straightforward - we take input as ~~split our string into~~ an array of chars (thanks to Asone Tuhid for pointing this out) and apply reduce operation, where we justify each char to the required length using "TAPE" as filler string.
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), 33 bytes
```
{,/((0|-1+0,1_-':x)#\:"TAPE"),'x}
```
[Try it online!](https://tio.run/##bY8/D4IwEMV3P4U5TYQIEdd2YnB36IZES20VUSDQodQ/Xx1paRzU4dL23e/dvRZhVfS9QPdg5XnRI1wvo2C9DxdI@bMdAhJvN@AHC/XsJbofIjRPuleDxFThAKoCsAeC5lfACne48VP8nMgEaMZuZVlWdSt1QwEbwUyyNXZI3Er7NEBqTdqSH@6rtMNO5/wy7HXn6KRZdjxyLkSeU8ZN10hk1Eg8qIQRbic5i@6UYiwzGz/X1EVnSnV6DM3@JbFtB0ta89PZwj@o/PpLzcmAWqOxDaZfAlLcvwE "K (oK) – Try It Online")
`{ }` anonymous function with argument `x`
`-':x` subtract each prior (use an imaginary 0 before the first item)
`1_` drop first item
`0,` prepend a 0
`-1+` add -1
`0|` max(0, ...)
`(`...`)#\:"TAPE"` reshape the string `"TAPE"` to each item from the list on the left
`(`...`),'x` append the corresponding character from `x` to each reshaped string
`,/` concatenate all
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 30 bytes
```
{∊⍵,¨⍨⍴∘'TAPE'¨0,0⌈-1+2-/⎕a⍳⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQb/04Bk9aOOrke9W3UOrXjUC0RbHnXMUA9xDHBVP7TCQMfgUU@HrqG2ka4@UFPio97NQJW1//@XgPX1bn3UuagIyEx71LvL6lHvKvW0xMwcdSAHKFX0qLtFPT9bvZZL3dHJ2dfPz88/IDgkKshRvQQkALIBjCEyIY7BIWAuSAFQRxRYGVwRGo4CqXH38PTyBqqC0EA9jk5OLi6urm5unp6Ozq4gKZBQCEQsxBEoGuIcAjEDpD4qMiLC2dkJZBGcCXarc0REZBTElc7YbAdLg1SCOO4eYJUY6kIwHQ9UygUJ2RJ1TGl1AA "APL (Dyalog Classic) – Try It Online")
`{ }` anonymous function with argument `⍵`
`⎕a⍳⍵` find indices of its chars in the alphabet
`2-/` pairwise differences (prev minus next)
`1+` add 1
`-` negate
`0⌈` max(0, ...)
`0,` prepend a 0
`⍴∘'TAPE'¨` reshape cyclically the string `'TAPE'` to each
`⍵,¨⍨` append each char from the argument to the corresponding reshaped string
`∊` flatten
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~78 77 64~~ 62 bytes
-1 byte thanks to Kevin Cruijssen
```
f=->s,*t{t[0]?s+('TAPE'*6)[0,[0,t[0].ord+~s.ord].max]+f[*t]:s}
```
[Try it online!](https://tio.run/##bZBNb4QgEIbv/gqyF1u1Zk89mLSNh9574GY4wIArbRaMYIJ2279uBXa1aUqYMLzvM8PHMLJpWdqnh2dTZPbTNkfyYvK7FNdvr2n2eN8ci3V6udQDz7@NX0h5po7kbZNZUpmvpUkQag6UwVkppXtj54EeCuQV3ydEtHBtbNh6ghSxbo7whv6JeSNPnXz/8GxMbvWUMc6FaFspKYgAeA1HEderjAGL0G@rmifnAFg4estvHRmAc9N8fQP8d6vgk4SUgkKHuEYXWejLWt4PUlmUStWPtkLrSL04WoPk7p509H6562/KEjo6GLJzwvUCrODVzulrkgjFlx8 "Ruby – Try It Online")
[Answer]
# [Java (JDK)](http://jdk.java.net/), 91 bytes
```
s->{var p='z';for(var c:s)System.out.print("ETAP".repeat(9).substring(1,c>p?c-p:1)+(p=c));}
```
[Try it online!](https://tio.run/##bZBBa4NAEIXv@RWDl6xtIuTYpKaE0GOhkN5CDuO6Jmt0d9kdgxr87VatBGl7WJZ5b5j55qV4w2UaX1uZG20J0q4OCpJZ8LSZ/dGSQnGSWv1rOrIC897iGToHHygV3GcApogyycERUvfdtIwh7zx2ICvV@XgCtGfnD60Ae61ckQv7yi9oj6ctJBC2brm939CCCef1fJNoy/qKr51/qByJPNAFBaabRsx7/9p9eoEVRiCxFz9wReSGRWy14FvzxpdmvfKfmQm572@adjOsfbCQcOQgHGkAPIx4rpTSxlFt0Vs89HpSnC8yvU48jKI4FiJJpEQuJk5dlSXn0XROxHlZVrU3CM0PTncijPkMROsfLv@BlQTIuTDEej0gve/S2lmLFeuOGnt@Z5MpNnrNrH9N@w0 "Java (JDK) – Try It Online")
## Explanation
```
s->{ // char[]-accepting lambda consumer, printing a String
var p='z'; // store the previous character
for(var c:s){ // for each character of the string
System.out.print( // print...
"ETAP".repeat(9) // "ETAP" repeated 9 times (to go above 26 chars)
.substring(1, // of which, we substring c-p -1 characters
c>p?c-p:1 //
) //
+(p=c) // and append c, while also storing the previous character
);
```
## Credits
* -2 bytes thanks to [R.M](https://codegolf.stackexchange.com/users/74635/r-m)
* -4 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat), by upgrading to Java 10+ and switching types to `var`
* -3 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen), by printing the result of my (previously) alternate version instead of returning it
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~122~~ 111 bytes
Saved 11 bytes thanks to [@KevinCruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)
```
s=>{var r=""+s[0];for(int i=1,e,d;i<s.Length;r+=s[i++])for(e=d=s[i]-s[i-1];d-->1;)r+="ETAP"[(e-d)%4];return r;}
```
[Try it online!](https://tio.run/##lY9Na4NAEIbv/opFKCh@UKG3jUIp7SmFQAs9iId1d9RpkzXsbIIf@NttTKCXXsx7mGHgeYYZSZFsDcxyL4jYzhkddglZYVGyc4uKvQvUHlmDus4LJkxN/pUZnWtb8tGThUP8dtJycyNDdusZq1g6U5qNZ2GYSV03oPyx4FVrPNSWYZqEECqOG4q3oGvbcBOklGMQFP4CQaqWsYguJUoKrqIoS7h/gdzXz@edm3sQKf/hqeAG7MloZvg083@nvbSa2j3EXwYtbFGDV3muKOVBa90eyQ5GuL7P12nDerZu8Ptn/WZRlkoBVBWikLBeHPquk7K844dSyq7rhzsEK45QN6uFBf@DJ2eafwE "C# (.NET Core) – Try It Online")
**Explanation:**
```
s =>
{
var r = "" + s[0]; //Declare string for the result and initialize with the first character from the input.
for ( //Loop over the input,
int i = 1, e, d; //starting with the second character, also declare helper variables.
i < s.Length; //Loop until the end of the input is reached.
r += s[i++]) //Add the current character to the result and increase the counter.
for ( //Loop for adding the TAPE.
e = d = s[i] - s[i - 1]; //Calculate the differnce between the current and the previous character.
d-- > 1;) //Loop until the difference is 1.
r += "ETAP"[(e - d) % 4]; //Add a character from the TAPE to the result.
return r; //Return the result.
}
```
[Answer]
# [Yabasic](http://www.yabasic.de), 119 bytes
An anonymous function that takes input as an uppercase string and outputs to STDOUT.
```
Input""s$
a=90
For i=1To Len(s$)
c$=Mid$(s$,i,1)
b=Asc(c$)
For j=2To b-a
?Mid$("peta",Mod(j,4)+1,1);
Next
?c$;
a=b
Next
```
[Try it online!](https://tio.run/##q0xMSizOTP7/3zOvoLRESalYhSvR1tKAyy2/SCHT1jAkX8EnNU@jWEWTK1nF1jczRQXI1snUMdTkSrJ1LE7WSAbKgNRm2RoB1SbpJnLZg1UpFaSWJCrp@OanaGTpmGhqGwK1WHP5pVaUcNknq1gDLUkC8/7/d3Ry9vXz8/MPCA6JCnIEAA "Yabasic – Try It Online")
[Answer]
# Python 3, 90 bytes
```
p,o=' ',''
for t in input():y=(ord(t)-ord(p)-1)*(p!=' ');o+=('TAPE'*y)[0:y]+t;p=t
print(o)
```
[Try it Online](https://repl.it/repls/SkeletalWrithingCell)
[Answer]
# Clojure, 139 119 bytes
```
#(reduce-kv(fn[r x c](let[a(cycle "TAPE")i int d(-(i(nth(cycle %)(inc x)))(i c))](str r(if(> d 1)(apply str c(take(dec d)a))c))))""(vec %))
```
Anonymous function which take the string and returns the taped one. As always, Clojure doesn't seem to perform all too well. What I couldn't really work out is fetching the next char in a short way. On the last char I would get an `OutOfBoundsException`, reason obvious. So I put a `cycle` around it. Maybe there is a more elegant solution.
## Ungolfed
```
#(reduce-kv
(fn [r x c]
(let [a (cycle "TAPE")
i int
d (-
(i (nth (cycle %) (inc x)))
(i c))]
(str r
(if (> d 1)
(apply str c (take (dec d) a))
c))))
""
(vec %))
```
# Update
Managed to shafe off a few bytes. Got rid of the pesky `if` statement by decrementing the difference. `take` produces an empty list if the number is 0 or less which in turn results in an empty string.
```
#(reduce-kv(fn[r x c](let[d(-(int(nth(cycle %)(inc x)))(int c)1)](str r c(apply str(take d(cycle "TAPE"))))))""(vec %))
```
## Ungolfed
```
#(reduce-kv
(fn [r x c]
(let [d (-
(int (nth (cycle %) (inc x)))
(int c)
1)]
(str
r
c
(apply
str
(take
d
(cycle "TAPE"))))))
""
(vec %))
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), ~~27~~ 25 bytes
```
q_:i2ew.{:-~0e>_"TAPE"*<}
```
[Try it online!](https://tio.run/##S85KzP3/vzDeKtMotVyv2kq3ziDVLl4pxDHAVUnLpvb//8Sk5Ny8vLz8guKSqqJEAA "CJam – Try It Online")
Far, far from the other golfing languages, but I'm proud of this golf anyway.
### Explanation
```
q Read the input
ew And take windows of size
2 2
i from the code points
: of each of its characters.
{ } For each of these windows:
: Reduce with
- subtraction.
Since there are only 2 elements, this just subtracts them.
e> Take the maximum
~ of this difference's bitwise negation
0 and zero.
This returns -n-1 if n is negative, and 0 otherwise.
Call this new value m.
* Repeat
"TAPE" the string "TAPE" m times.
_ < And then take the first m elements.
The result of this will be an array of strings which consist of
the string "TAPE" repeated the proper amount of times.
. Zip this array with the original input.
Since the original input is one element longer than this array,
the nothing is pushed after the final character.
Implicitly print everything.
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~26~~ 25 bytes
```
ΣSoż+C1(moo↑¢¨tȦ9¨>0←Ẋ-mc
```
[Try it online!](https://tio.run/##AT4Awf9odXNr///Oo1NvxbwrQzEobW9v4oaRwqLCqHTIpjnCqD4w4oaQ4bqKLW1j////ImFiY21ubm5vcHN0enJhIg "Husk – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 72 bytes
```
-join($args|% t*y|%{for(;$p*(++$p-lt$_)){'TAPE'[$i++%4]}$i=0;$p=+$_;$_})
```
[Try it online!](https://tio.run/##bZFPb4MgGIfvfgpiXlepNtlhpzVN1sPuO3BbFqP0tdo5ZcIy/9TP7gA3a9qREODH8wBvENU31jLDohghJTvSj5tTlZc@xPVRnj2i1u3Z69Oq9rcg1n4QgNgUCiJK@xXbvzyvXiEPAu/hbYB8d6@ZXQDRFqKBjoPjPPkO0S303TjhH2VZVkKqro7d0ATGt33aYXup7NIAdBY7S8/sVe8W6DHLT@8ansbLCXGSHA6IaZrnMUdDmIhNGdvrlHGG9sSF1rVNw3libp@ndFEOb5q2mwrh/73Mbi8EFQs8Zla4wdVVfQKZRmfZqFq8pTRCyZl4pLcoyBCwEcgVHvRfQjSlNcqvQungTn8xSBu64P/mG/ycJfr4R7vOMP4A "PowerShell – Try It Online")
[Answer]
# **Java , 213 166 153 bytes**
```
i->{String o="";for(int a=0,l=i.length;++a<=l;){char u=i[a-1],n;o+=u;if(a<l){n=i[a];o+="TAPETAPETAPETAPETAPETAPET".substring(0,n-u>0?n+~u:0);}}return o;}
```
[try it online](https://tio.run/##bZDBbsIwDIbvPIXVUztKxK4LZZqm7TZpErshDm5IISwkVeIgCupenaUFsR4WyUr82XL@3zs84MTW0uzW3xe1r60j2EXGAinNHvhIaPQePlAZOI8APCEpMWipghGkrGHvt8dMbNEtVzksyCmzmUMFBVzUZH6@ArBFkvDKulQZAiymuS4U09JsaMvHY5wVmmfnbgiEQi1x8rjKDbfjInBVpTjT2dl0fNWx5Ovl8@3fSJgPpe9/TKe5mYT59NmMf8LTNONt6yQFZ8Dy9sJH0VYdSh1t3dwdrFrDPlpOr5KXK0C38Vm/Abgzkp58NNfTeBIsxd4YY2tPJ4dJfuenQbLZqt33oIZluV5LWVVKoZCDyqk5HoUoh3NKIY7H5vRHCGuZ9EnL@yvuFW6qe31PV5XZXeSi8ST3zAZidewibdKKYV3rJu06GdnXuPoX57BJsyy7Tm1HXbSXXw)
```
String o = "";
for (int a = 0, l = i.length; ++a <= l; ) { // for each character
char u = i[a - 1]; // current character
o += u; // add current character to output string
if (a < l) { // if it's not the last one
char n = i[a]; // next character
o += "TAPETAPETAPETAPETAPETAPET".substring(0, n - u > 0 ? n +~ u : 0); // fill with enough tape but only forward
}
}
return o;
```
Please help me make it better.
Thanks to @cairdcoinheringaahing for the tip on whitespaces.
Thanks to @R.M for the tip on tape string.
Thanks to @KevinCruijssen for the lambda and expressions tips.
] |
[Question]
[
We say a string is *non-discriminating* if each of the string's characters appears the same number of times and at least twice.
### Examples
* `"aa!1 1 !a !1"` is *non-discriminating* because each of the characters , `!`, `a` and `1` appear three times.
* `"abbaabb"` is **not** *non-discriminating* because `b` appears more often than `a`.
* `"abc"` is also **not** *non-discriminating* because the characters don't appear at least twice.
### Task
Write a ***non-discriminating*** program or function which returns a *[truthy](https://codegolf.meta.stackexchange.com/questions/2190/interpretation-of-truthy-falsey)* value if a given string is *non-discriminating*, and a *[falsy](https://codegolf.meta.stackexchange.com/questions/2190/interpretation-of-truthy-falsey)* value otherwise.
That is, the program run on its own source code should return a truthy value.
Each submission must be able to handle non-empty strings containing [printable ASCII](http://facweb.cs.depaul.edu/sjost/it212/documents/ascii-pr.htm), as well as all characters appearing in the source code of the submission.
### Test Cases
Truthy:
```
<your program's source code>
"aaaa"
"aa!1 1 !a !1"
"aabbccddeeffgg"
"1Q!V_fSiA6Bri{|}tkDM]VjNJ=^_4(a&=?5oYa,1wh|R4YKU #9c!#Q T&f`:sm$@Xv-ugW<P)l}WP>F'jl3xmd'9Ie$MN;TrCBC/tZIL*G27byEn.g0kKhbR%>G-.5pHcL0)JZ`s:*[x2Sz68%v^Ho8+[e,{OAqn?3E<OFwX(;@yu]+z7/pdqUD"
```
Falsy:
```
"a"
"abbaabb"
"abc"
"bQf6ScA5d:4_aJ)D]2*^Mv(E}Kb7o@]krevW?eT0FW;I|J:ix %9!3Fwm;*UZGH`8tV>gy1xX<S/OA7NtB'}c u'V$L,YlYp{#[..j&gTk8jp-6RlGUL#_<^0CCZKPQfD2%s)he-BMRu1n?qdi/!5q=wn$ora+X,POzzHNh=(4{m`39I|s[+E@&y>"
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 10 bytes
```
=ᵍbᵐbᵐlᵍ=l
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/3/bh1t6kh1sngHAOkG2b8/@/EqagEgA "Brachylog – Try It Online")
### Explanation
```
=ᵍ Group all equal elements together
bᵐbᵐ Remove the first element of each group twice. This fails if
there are fewer than 2 elements
lᵍ Group elements together that have the same length
= Are all elements of that list equal? This only succeeds if the
list has one element
l Length. This will always succeed
```
[Answer]
# Java 8, ~~198~~ ~~192~~ ~~186~~ ~~174~~ ~~168~~ ~~165~~ 160 bytes (char-count ~~6~~ 5)
```
o->{byte x[]=new byte[+333-3|2],u=-0,i,fe,fi,w; s:w:no0r3sswwyyy:for(int s:o){{u=++x[s];}};for(int b:x){if(!!!(2>b||u==b)|2>u|2>2){x[0]++;}}return!!(0>--x[0]);}
```
[Try it online.](https://tio.run/##zVFZd6IwGH2fXxG6KAi40cWC2LrbVq1Vq1UOtgGCogjKIlLktzt0e@uZGd8mJ3n4cnNP7jKHG0ibK2TMlcVe1qFtgxbUjOAXAJrhIEuFMgLt9xEAyTR1BA0g4/IMWoIIbIKLgDA60bYd6GgyaAMD8GBv0oVA8h0EtoLIG8gD74NAMgxDM7usSLk8naY0SkWUqlEeB2zWYw0zbTG27Xm@77OqaeGRgggwiSBweZLcCrbIhSH3jUjslgg0FccwDM8WpN3O5XmJ2GULbnSyRLAV0iJJRgwLOa5lRK/SBZp@vyW4cM99ql65kh6p/hK/MTUFLCP/eM@xNGMqiJD49J5KgZ7pWlEYsqkgoDk20lX2A@r5toOWSdN1kquI5OgGbiRl/Oh/j@Ao6ZjlqMiiZUEfJ4iPMn@084V8B9G3XGfm/9k8jNa/f/BFwTIgAzAIsMzBVEmSZUVBSFWn0wPJmUds8KL2tOJFydKCXegsKi1xMG/f8ZOXMxzG@OtzcwSpjDfbdc9G90/g@ErGjh9BP6a@svby5OZ5Q7vTYb5D6OGwU6jF5zqzXSrxq1t00mpzfatcKqec8W0zUc9eSn7VSE7Ti/uZ1D0t1Onk@aohN9PE3fjVZhPCNtt7u8idbiYNM0cKiAoeimvjmqnmH2reM87d@K5Ivl2mVsr6qXJQf9/d1aBuo791d2j6kvRewMEs@UCG9Khe9OTiucKevcA7oiJmE5PWBq@G99KleSMuLLQZXqN@ujbkbnd3rLYFp1cYU/OWXOJpXG@85pxBYepnts/5XuqheNl2SvFQBm58cNKkRvpoFRwLyeQ8Nu0vcvMVfdHV60/N45f8JF0uj@87j2ole2oTM0SXWl03Y1yvFS2Fna95zzgxLUg@U52Ht7dGe8bjZ8Hylbm63dkCWb2J@YUffYa/wv1v)
[Code used to verify the occurrences of the characters](https://tio.run/##VU@xboMwEP0Vk8kuYCWwgUhVdWmlVh0YEYMhR@Ik2MjYAQSRsrdfmR9JTdMOHU6nu/fuvXd7dmK@bEDsN4fbjdeNVBrt7ZIazY/0IeZCg6pYCeh1bDXTvEQnyTeoZlzgVCsutlnOyPjOGlQnAjr0wtqdnTCJK6lwuWMKldEMpCUTAhROh1ZDTbkgVECv37gATKiWz5b6pBQbMCE1bYzGpVfTLdh@vXxdL5/ESYQ5Hh@xDUX@I@4qWt0NP4o9lBpBVNMDDKnlEPLrKI2mjU2sjwKDu4jQwr2rACHx@Xy7SX89FoMG1Gf5zy/zkLlhGPrhFOSeSfylx70KvIp7XYzaqIuEXKqwbbtuGIZoDmD1LSDJOJrEdfusza12/IcUUU9GXmHHcXCwLqbJJElBpmBtbAVk7LNl7rr2QoE2SljWcu3789ZG/AY), which was my answer for [this challenge](https://codegolf.stackexchange.com/questions/19068/display-number-of-occurrences-for-every-character-in-an-input-string/83741#83741).
-5 bytes thanks to *@OlivierGrégoire* again by getting rid of the comment and making a mess. ;)
Old **168 bytes (char-count 6) answer**:
```
o->{int w[]=new int[2222],u=0,f=0;for(int r:o)u=++w[r];for(int e:w)if(!(2>e|u==e)|2>u)f++;return!(f>0);}//[[[]]] !!!!e(i)++,,,,-----oo////000tuww::::{{{{{;;||||}}}}}>>
```
[Try it online.](https://tio.run/##1ZNZd6IwHMXf@ylCWxVEBbfaSqF1bbXu2pWDbYCgKBJlEa3y2R3sMk89M@Pj/E7ykPxzs9x7MoFLGMdzZE7U6U4xoG2DJtTNzREAuukgS4MKAq39EAAZYwNBEyikMoaWKAGb4oKCH/Sg2Q50dAW0gAl4sMNxYRNsADxR4k3k7TcTUwFSzOXZmMaznIYtcr/CymPK5WnaEy3p9yTKe5SukQSZEtDW5XlEbVOCS2k0zVnIcS2TIDWBpTifYURRlCQJACIAkTpF07GA@B6MmQCWZR3X8/IBmz0ctw3w9wjCjvu8/dyVjeD2X49YYl0Fs8AHsu9YujkSJUh9esAwoI9dKzBFwSoCumMjQ8t/lPpr20GzBHadxDwQOYZJmgmFPP5frDhOOLgUBFuwLLgmKeoj3B@f9VX5NmRguc54/WcTYMC/H/AlIZIgCQgIiOTBUllWFFVFSNNGowPFyS7x8Kr19cJZ0dI3W9@ZlpvSw6RV54evGRKG@assfoaxpDfe9jLPd/fg5EIhTrpgENbe8vbs9PppGXdHj5cdyvAfO0I1MjHSq5kauaih02aLG1ilYolxXmqN6E0qJ68rZmLETu/Gci8k3MQT2fmt0mCp@subnY@Kq1T//ew8tBze4nNaRLFNu7Awr9KVy3bVeyK567Ur0e85Zq4u7ssH5fedXRUaNvpbdoe6L8v7AA5WKQcq5K521lcKWTWfeYV1qiylosPmkqz4d3IOX0tTCy0fr9CArT5ytW09r69A6IJIV70ZF71/ubl9O3cehNE6uXq67DPtQq7lFCO@AtzIw2kj9mw8zzcnYiIxCY8G0/PJPH7WM27uGyevl0O2VHq563S1cipkU2MULzZ7btK8Wqg6Q2QXvGeeYgvST7FO@/39tjXmycxm9pa@qG1tka5ch9c//zT/yN/9Ag)
[Code used to verify the occurrences of the characters excluding comment](https://tio.run/##VU9BbsIwEPyK4eStwQKOiZyq6qWVWvWQY5SDGzbgENuRsUkRIHFvX8lHUkOrSt3L7s6MdmYbuZNT26FplpthULqzzpMmgjx41fK7VBmPrpYVkufD1kuvKrKzakm0VIbm3imzKkoJh1fZES0M9uRJbtdxo5DW1tFqLR2pkiuRV9IYdDTfbz1qrgxwgx/@RRmkwL19jNIH5@SeAmjeBU@rieYrjP1y/rqcP2EkTGjbexpDwX@GzZP5j@Hbe4OVJ5hovsF9HjUAv442eN7FxL41FNk4IWP2cwUB0tNpGOw0O0Sa9EV5eyXOxSJWOQliNqnF7OZwVbjEQhCM9YUr/0BMelA1HdFFhscgBMJxkQWoGUsd@uDMiNbZLFp9Aw), which was my answer for [this challenge](https://codegolf.stackexchange.com/questions/19068/display-number-of-occurrences-for-every-character-in-an-input-string/83741#83741).
-6 bytes thanks to *@OliverGrégoire* removing `<` by swapping the checks to `>`.
**Explanation of the base golfed program (98 bytes):**
[Try it online.](https://tio.run/##lZFrW6JAFMff76cYuhgkKJe0AqHMsqt20a48VAMMiiIYM4gEfPYWt9pX@@yu88y8mDnnf878zn8EZ5ALpsgf2eMPy4MYgw50/fQHAK5PUOhAC4Hu4gqAGQQegj6waGsIQ90AmFGKQF6cYmMCiWuBLvCBCj4wp6VFAQB1Q/VRvCimi7W6wRKVZx2VV5wgpBcJlowZopbLULeM34@uDBnXoV1NKLmUSjLSEBmnXFZCRKLQB05DUPIP5bPvNDK9ou9X@1ng2mBSENA9Err@QDcg8/n7ahX0gigscKzARsAlGHmO/CvUSzBBk0oQkcq0EBHPp/2KRa8EBYSZEATmXxSLi16WJImTMtFgI5XjWZd1EOu4bKwALMeyH/ChhHEcJ0kif/NgOWDSNCow5zo2lDz/TWrKcyYtUCmKokXNzLJIVU0mE7WoOCKTznXeKMDz/BO9yOI1jlu8Mkq@UiFBq7CiGYYwoRnmlx1/xPmKfA@iH0ZkmPwdHhbr/xt8SSgBCICCgBKWlpqmZdk2Qo4zGCwpFq6puxen5zbrB6GbZjkZH3aMu1H3TH1@2aJhSd2rBY@QFeJhdrP1eH4LVnctavUa9EvOq4wna/sPMy4a3DeuGC@/v9LaGyNPmk/sjd1TtNbpKv2wddCqkqfTi81jcdtMjvzKgB@fD82bde2Yq9SmJ9YFz5w9vWJ5U5@Lvff6zvrs@STYKeuITS@bb/6edNS4bMcPtLKfREb5fbs6td9uD5fy79u7NvQw@pd3y07fNBcGLK2yllSY1069ZzVrtrz1As@YQ0PcfO7M6KP83NwO9o1xiGb3e6jPt@@V0@xMdudgfZeS2vFE2bx9Oj553SF32iAR5g@NXvWyud0lBxu5BaKNu7UL9tF7nKareqUyKg36453RlKvfeMe3F6svjWe@1Xo6v7p2DsV1zAwRd9C5iQR/7812q1TtTY39tSCE5Qf26vL9/aQ7VOmtdPIq7Z5mWC8f7ZcS7Y@c@Y/84yc)
```
s->{ // Method with character-array parameter and boolean return-type
int a[]=new int[256], // Occurrences integer-array containing 256 zeroes
t=0, // Temp integer, starting at 0
f=0; // Flag integer, starting at 0
for(int c:s) // Loop over the input
t=++a[c]; // Increase the occurrence-counter of the current character
// And set the temp integer to this value
for(int i:a) // Loop over the integer-array
if(i>1 // If the value is filled (not 0) and at least 2,
&i!=t // and it's not equal to the temp integer
|t<2) // Or the temp integer is lower than 2
f++; // Increase the flag-integer by 1
return f<1;} // Return whether the flag integer is still 0
```
**Some things I did to reduce the amount of characters used:**
* Variable names `o`, `w`, `u`, `f`, `r`, and `e` were chosen on purpose to re-use characters we already had (but not exceeding 6).
* `2222` is used instead of `256`.
* Changed the if-check `e>0&u!=e|u<2` to `!(e<2|u==e)|u<2` to remove 6x `&`.
* Removed the two separated returns and used a flag `f`, and we return whether it is still 0 in the end (this meant I could remove the 6x `by` from `byte` now that we only use `n` in `int` 6 times instead of 8).
* `e<2` and `u<2` changed to `2>e` and `2>u` to remove 6x `<`.
**What I did to reduce the char-count 6 to 5:**
* 2x `int` to `byte` so the amount of `n` used is 4 instead of 6.
* Used `x[0]` instead of a new variable `f=0` so the amount of `=` used is 5 instead of 6.
* Changed `2222` to `3333` so the amount of `2` used is 2 instead of 6.
* Changed variables `f` and `r` again so they aren't 6 anymore either.
**What @OlivierGrégoire did to get rid of the comment, and therefore the 5x `/`:**
* Adding unused variables `,i,fe,fi,w;`.
* Adding unused labels: `s:w:no0r3sswwyyy:`.
* Adding unused `|2>2`
* Adding `{}` around the for-loops and ifs, and added an unused `{}`-block.
* Changing `!` to `!!!`.
* Changing `|` to `||`.
* Changing `333` to `+333-3|2`to get rid of leftover arithmetic operators `+-|` and the `2`.
* Changing `!(x[0]>0)` to `!!(0>--x[0])`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~18~~ ~~16~~ ~~12~~ 10 bytes
```
Ġ¬zḊḊ¬zĠȦȦ
```
[Try it online!](https://tio.run/##bY@3ktpgFIV7nuIXIiOCyDmDyDlrBCiDEFEiSEDjxjN@iq222gdwbW@xr2G/iKz1ejvfOcV3z5zmE1hRVDTt9enHi/rr@zc9Orw@vT2/PWs/v/7@8qIH0zTcAHDj/0ZGAgEwkFiRAzIrye8zUj8jYgBAJwgFKIBIAKGfDUXRNMOwLMfx/EeHdqDhnOutsqHccXW7P@R1oUEMhWY1OZsHbKQlmQ7uJiSCXpb3bmBSGwA4SkNwB/Qt3CImbUyZ8dl14keJtl18jNqpklUQ/dcNY41WWFOjGe8f87m8R55W6g7MF6aU4tbNe9e1JdU1pzCXO7gv03WvvTpdSDEHfvX11FDEfJ6VdxEnziK3VvawTfuLiVbpMrbFM8qJcKphz545DAq6@l/df2YU9S73@dAfQHW4UI/OBplYYE5W7QXC55g1zrbio0aFdxlifWTPozTb95ZG8cq9GltdgTkK@UuXTdwxmGLlRUQepngFvY4TPU8rG27KOeuDBifr0FRHJuJkf4Nxt1uw8P11RNi7Ql0RG9TheWLmzeentXaHK/jMkn3JunKN7gndpg/MygMFD8nL1rQ7ks4x0m6parm5TNoCt83CH63cJdxZzFiUlJEwEH8A "Jelly – Try It Online")
### How it works
```
Ġ¬zḊḊ¬zĠȦȦ Main link. Argument: s (string)
Ġ Group the indices of s by their corresponding elements.
"abcba" -> [[1, 5], [2, 4], [3]]
¬ Take the logical NOT of each 1-based(!) index.
[[1, 5], [2, 4], [3]] -> [[0, 0], [0, 0], [0]]
Ḋ Dequeue; yield s without its fist element.
"abcba" -> "bcba"
z Zip-longest; zip the elements of the array to the left, using the
string to the right as filler.
([[0, 0], [0, 0], [0]], "bcba") -> [[0, 0, 0], [0, 0, "bcba"]]
Ḋ Dequeue; remove the first array of the result.
This yields an empty array if s does not contain duplicates.
[[0, 0, 0], [0, 0, "bcba"]] -> [[0, 0, "bcba"]]
¬ Take the logical NOT of all zeros and characters.
[[0, 0, "bcba"]] -> [[1, 1, [0, 0, 0, 0]]]
Ġ Group.
z Zip-longest. Since all arrays in the result to the left have the same
number of elements, this is just a regular zip.
[[1, 1, [0, 0, 0, 0]]] -> [[1], [1], [[0, 0, 0, 0]]
Ȧ Any and all; test if the result is non-empty and contains no zeroes,
at any depth. Yield 1 if so, 0 if not.
[[1], [1], [[0, 0, 0, 0]] -> 0
Ȧ Any and all.
0 -> 0
```
[Answer]
## [Brachylog](https://github.com/JCumin/Brachylog), ~~14~~ 12 bytes
```
ọtᵐℕ₂ᵐ==tℕ₂ọ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@Hu3pKHWyc8apn6qKkJyLC1LYGyd/f@/6@ET1oJAA "Brachylog – Try It Online")
### Explanation
```
ọ Occurrences. Gives a list of [char, count] pairs for the entire input.
tᵐ Map "tail" over this list, giving each character count.
ℕ₂ᵐ Make sure that each count is at least 2.
= Make sure that all counts are equal.
At this point we're done with the actual code, but we need another copy
of each character (except ᵐ). We can just put them after this, as long as
we make sure that they can never cause the predicate to fail.
= Make sure that all counts are equal, again...
t Extract the last count.
ℕ₂ Make sure that it's at least 2, again...
ọ Get the digit occurrences in that count, this can't fail.
```
Alternative 12-byte solution that reuses `t` instead of `ᵐ`:
```
ọtᵐ==tℕ₂ℕ₂ọᵐ
```
[Answer]
# T-SQL, 320 bytes (32 chars x 10 each)
Input is via pre-existing table `FILL` with varchar field `STEW`, [per our IO standards](https://codegolf.meta.stackexchange.com/a/5341/70172).
```
WITH BUMPF AS(SeLeCT GYP=1
UNION ALL
SeLeCT GYP+1FROM BUMPF
WHeRe GYP<=1000)SeLeCT
IIF(MIN(WAXBY)<MAX(WAXBY)OR
MAX(WAXBY)<=1,+0,+1)FROM(SeLeCT
WAXBY=COUNT(1),WHICH=+1+0,HEXCHANGE=+01,HUNG=+0+1,CHLUB=+0,GEFF=+0FROM
BUMPF,FILL WHERE
GYP<=LEN(STEW)GROUP BY
SUBSTRING(STEW,GYP,1))CHEXX
OPTION(MAXRECURSION 0)----------<<<<<<
```
I have never been more pleased, yet horrified, by a piece of code.
Must be run on a server or database set to a case-sensitive collation. There are 10 each of 32 different characters, including upper and lowercase `E` (SQL commands are case-insensitive, so flipped a few as needed), spaces and tabs (tabs are shown as line breaks in the code above, for readability).
I found ways to include 10 each of the other symbols `+ = ,` in the code, but unfortunately couldn't find a way to do that with `<`, so I had to add the comment character `-`.
Here is the formatted code before I crammed in all the extra filler:
```
WITH b AS (SELECT g=1 UNION ALL SELECT g+1 FROM b WHERE g<1000)
SELECT IIF(MIN(w)<MAX(w) OR MAX(w)<1+1,0,1)
FROM(
SELECT w=COUNT(1), --extra constant fields here are ignored
FROM b, fill
WHERE g < 1+LEN(stew)
GROUP BY SUBSTRING(stew,g,1)
)a OPTION(MAXRECURSION 0)
```
The top line is a recursive CTE that generates a number table `b`, which we join to the source string to separate by character. Those characters are grouped and counted, and the `IIF` statement returns 0 or 1 depending on whether the input string is non-discriminating.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~333~~ 168 bytes
*Thanks to @Kevin Cruijssen for saving 9 bytes and thanks to @Laikoni for saving 45 bytes!*
```
f(r,h,a){char*o=r,c[222]={!o};for(a=!o;*o;)++c[*o++];for(h=!o;222/++h;c[h]&&c[h]!=a&&(a=!*c))!a&&c[h]&&(a=c[h]);r=!(2/2/a);}/////!(())****++,,,,,[[]]fffffrr{{{{{{}}}}}}
```
[Try it online!](https://tio.run/##lZNrU6pQFIa/9ytAE9mAIqhZImpZlnbR7hphweayKd0oYpnEb@8AXaYz02nmPB@YNe9aDLPW8MCcDeHbm0V7HOI0EECkeYwrexxURFFU5YB0Q8lyPVqTSVdiXAmwLFQYl2XVJEZxHE3yLIskqCCVouInKWsUFb/DQABI7T1MkrgAkieTtMiLvAakkI8haRoAJoJluRhFUVUrxvOChDDhLe1gOF4YJlGb@4bj5lF9zcE@MdEcTIO1YI2ImHpRZNGpjHGLUxwRVVpECgDpn21SIASC1AhS@HVM1yE0DNO0LNv@ZVA4Ja/urHNne2PHc4LX0H/cPVavHk668uiuRGuU3Ci7Q40TntHrWWl4eEmktyCZPiUuKOu@Op@sNwdPuYV9XeuDcXjdr7ezD@PicmJktzrm@vGJdOG1dlq8f9M5YvbFiv6yh/N24fEQ6WeZ@n4uX54ewKMC6N7cz6uMshTPVxubmafRgbvJKiYX9LZnuFHcq/XazwNaar4sVHZV4afG7HI3WemvnW7xt/V/O42ux9f5dQL@0H3v6afWxjncLhvV0p3WBbuqyIyOn@i98FCvuE310TOfrhvmRaF9LXVeu1VnSWS2yGL7eSIxlzf7B/eb/lXdfhGWg9o539uunPg72RASi@zV@hE3HA@nQVrJ5x8o@@Jx82Ga2zgb718epe9qo0KrdXPYP7V2xcwcIDO3c3y2EHBjZjg8WZ7Jz3jd9TR2wPV7q9XBCZLpUjC5L251XucKu9ekXuo/HewW52LiIvWxbywVAV3DVMqCqL5nlm36czoOOSJKOSL@n/HPB5r7nrGYJsMg/mKY@Iq/fEXffUVfviKJQR@@ok9fcRy/@4ojX3HiK/7JV/zpK/4vXxF2E/729g8)
# C, 333 bytes
```
i,v;f(S){char*s=S,L[128]={0};for(v=0;*s;)++L[*s++];for(i=-1;++i<128;L[i]&&L[i]-v?v=-1:0)!v&&L[i]?v=L[i]:0;return-v<-1;}/////////!!!!!!!!&&&&&(((((())))))******+++,,,,,,,----00000111122222228888888:::::::<<<<<<<===???????LLLSSSSSSS[[[]]]aaaaaaaacccccccceeeeeeeeffffffhhhhhhhhiinnnnnnnnooooooorrrrssssssttttttttuuuuuuuuvv{{{{{{{}}}}}}}
```
Even the bytecount is non-discriminating!
[Try it online!](https://tio.run/##7dRXc6JsFADg@/wKiA0EFGxREWuMDUtiD8FGUYyi0izob8@C8M18O5PN1V7ucwEv5xwGzhl4OWzJcV9fEmqQItSFTW41V4Iq1UVphogkWcrEb6S4UyCDwsmgSsIIQjNBFUHYe1SiMIJEEClj1ZI0I7F@v33EjJxhZdI4DBpOxLq2T2mcVARNV2TMyFh33sL/AV1@G3QH3wXvEARBHZgFtxGWiCPpSDsyDoqicg6aprsOhmFYlp27OJfgEu9WLkmSXTuHYlHvNJfuMgzTcXN8eSSZ2@i8AGRUjZd2oVX2QZI1YDuXZAh@MB8Ay16xQiL06OM/5EcUsFb2Oz3CMPnHNEgABADOAZD4sWyx4Diet/tZLn8oJF7BwVTsSoVEUZHM6037fG6yg3WrTk2mMWjup3Lx3XiOEsfV9S02bvQBT4oDPa9Azy/O0urWmx8ZmL4cZjrw5jbsZF8C6030tOUDqZrgbbbInlIqlsLae40OViJPi3NZDi3xz8Zq8ebLVrBQfF/laByuv8/UdJA5RbqXRNJnTKq7JMIIqNkuHORctJxpvxxHEJk/6yxyeQrv@UP/@d7Sbz19yP9r/6fRLBb2dH6s4L7JOrnFq5jocoU4n45N53X4mY0EJ00DKt8ai6ddnv1UBGOYE3r4y5CsXetp6QT4UmD05bglg/33SnWW1AbZ5Zk4jTLdcLvw1NKKgRsH6IGBl0bHm/He9DCh0Nq/7H0m13ss8bap9GnPNDPBS6X3RudVfI74VHglYMXmm07IuQMvhcH4gTrK3p0yR0Zop325VFsrCoqZ21k0VbuqDFLO@8/Z7wb2Ids/EmYvHt1@7T8f4Ha8wMSJCOvExKWgqZAdRAErigL29yx/PyBVU3h9fy@G7Sfe/m0qf3NT@QU)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~20~~ ~~18~~ ~~16~~ 14 bytes
```
S¢Z≠sË*sZ¢≠SË*
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/@NCiqEedC4oPd2sVRx1aBGQGA5m4xAE "05AB1E – Try It Online")
The program is essentially divided into 2 parts where the goal of the first part is to do the actual task and the goal of the second part is to use the same functions as the first part without altering the result.
**Explanation (first part)**
```
S # push input split into list of chars
¢ # count the occurrence of each char in input
Z≠ # check that the max count is not 1
sË # check if all counts are equal
* # multiply
```
**Explanation (second part)**
```
s # swap input to top of stack
Z¢ # count the number of occurrences of the largest element
≠ # check that the count isn't 1
SË # split into list and check that each element are equal (always true)
* # multiply (as it is with 1, the original result is left unchanged)
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 14 bytes
```
§<ε#εu§m#u
m
<
```
[Try it online!](https://tio.run/##yygtzv7//9Bym3Nblc9tLT20PFe5lCuXy@Y/NkEA "Husk – Try It Online")
## Explanation
The two short lines are no-ops, since the main function never calls them.
```
§<ε#εu§m#u Implicit input, say S = "asasdd"
u Remove duplicates: "asd"
§m# For each, get number of occurrences in S: [2,2,2]
u Remove duplicates: L = [2]
#ε Number of elements in L that are at most 1: 0
ε 1 if L is a singleton, 0 otherwise: 1
§< Is the former value smaller than the latter?
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~75~~ 69 bytes
```
def f(s):len({2<<s.count(c)-2for c,in s})<2or{{e.dil:-tu,r.dil:-tu,}}
```
Output is via [presence or absence of an error.](https://codegolf.meta.stackexchange.com/a/11908/12012) The error is either a *ValueError* (one or more characters occur only once) or a *NameError* (the character counts are unequal).
[Try it online!](https://tio.run/##XY/nzqJQEIZ/61UcPwtgQcWOvffedS2Ug6IICAe71@6qye4mO8nMvFPyTEa9oq0iUy9O4SFIAgzDXjwUgIDrBC1BGb9TiYROcoohI5wjPJSgaIBzizLQn0SCUrT7HZK8KNEeZLi1v@r5fL1JpI40UcUJsxleIAc@J8zm81aUIBhoBqTNJqRd39Ek4KKsGggniHehaqKMvgtmE7xwUEWg2C4VNU3R6L9j7Jfch5IAENQRjbm/jA//f4BJY0Qdgv5VR/BQvIjoD/MfqsRIOnz9MG/7Mb@TxQ/8wMIAi/9bsizH8TyEgrDZvBv@rmW0EvpiNpzTxPvjifaF5mK0a9WSy1UQZxzJdEiZMm7/efvoBaf1IbDGOIu1CwYOYU3rB1tmcvIYm3GiQ0jPcSdVwnZS4HLgsVgV2pqt@EDL5/JeNKs2nGUqwl6LMrnx7etbtmdPlT1kSK1wDR9Rm6112jm/UP1bOGo/LStK1DWH7ns7e5TTgWKiXTpP8Hjmaixct4hX5Y/DwueXj7Ps56Wv4t6R7QrhPpcN8XRwxdSIwoJyLpsnvPissxEls9hr8DROw4GvNI5XHzVavAB7zBIonQ9x53BWrqyjaJTaXP2XSaLvbWcjLZTDnhwwsJGt4Z5KU/VunZPkzrEZ7KM71RPuSeVhw7pKLH35/Kze6QoFyq4TW@jJNXuGX04fedFrCR2TZ9mmaIxr4u60b7dKa5vEg/fDOhCrPvS5q5hxXFM/vwE "Python 2 – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog) v2, 8 bytes (in Brachylog's character set)
```
oḅ\k\koḅ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/P//hjtaY7JhsEP3/f7ShoaGOgqG5uY6CpRGQYYDMgMnFAgA "Brachylog – Try It Online")
Looks like there's been a golfing war going on on this question in Brachylog, so I thought I'd join in, saving a couple of bytes over the next best answer.
This is a full program that takes input as a list of character codes. (This is partly because Brachylog appears to have some very bizarre bugs related to backslashes in strings, and partly because the `\` command doesn't work on lists of strings.)
## Explanation
```
oḅ\k\koḅ
o Sort {standard input}
ḅ Group identical adjacent values
\ Assert rectangular; if it is, swap rows and columns
k Delete last element
\ Assert rectangular; (rest of the program is irrelevant)
```
The `koḅ` at the end is irrelevant; `k` will always have an element to act on and `o` and `ḅ` cannot fail if given a list as input.
The reason for the starting `oḅ` should be clear; it partitions the input list by value, e.g. `[1,2,1,2,4,1]` would become `[[1,1,1],[2,2],[4]]`. In order for each character to appear the same number of times, each of these lists must be the same length, i.e. the resulting list is a rectangle. We can assert this rectangularity using `\`, which also transposes the rows and columns as a side effect.
We now have a current value consisting of multiple copies of the character set, e.g. if the input was `[4,2,1,2,4,1]` the current value would be `[[1,2,4],[1,2,4]]`. If we delete a copy, the resulting matrix is still rectangular, so we can turn it back using `\`. However, if the reason the matrix was rectangular was that all the input characters were distinct, the resulting matrix will have no elements left, and `\` does *not* treat a "0×0" matrix as rectangular (rather, it fails). So `oḅ\k\` effectively asserts that each character that appears in the input appears the same number of times, and that number of times is not 1.
That's the entire functionality of our program (as a full program, we get `true` if no assertion failures occurred, `false` if some did). We do have to obey the source layout restriction, though, so I added an additional `koḅ` that has no purpose but which cannot fail (unlike `\`, `o` and `ḅ` are happy to act on empty lists).
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~144~~ ... ~~100~~ 96 bytes
```
o=>!(a=o.split``.map(i=>o.split(i||aeehhhlmmnnnpst)[`length`]-1)).some(g=>![g>1][-!1]||a[-!1]-g)
```
[Try it online!](https://tio.run/##fVPZcqpAEH33KwA3UCHBLUZEjfse17hQKIvDYhBQEPdv96LeVKXuw52HPtNdZ05PT51Z8Q5viVvVtHHdWIKbRN8MOgujPG0QlqmpNscRa95EVTr7t4CqlwsPgKIo2nqt67pp2RjDaUCXbYVjcRLDCMtYA1R2ZRg5S7IMDpOse@aBuIzdKI9DI0hYojwmzRAEoYM9NAA26mAs5VnR5k9D56chRjzlXXHKIxq6ZWiA0AwZRYoKv@VFG2wh0djpdhpCXIZkbNEDpOqQif0mm8yBjazc8K/IEFg2xMu8qrsouq/wlPnN4STUd3auGERDvrPk3vTKuYz/yNj3ROQtYD3FGIR3FxLxuAiTEAnBPASTz1wQRHG5BECSZPleIXvw10IaqB/JwlY9X672d6nNfq06DXq@iKN8gM4ljCkfIffKpR@fNkeQ912EvT1oGJC4tLX25ScOvpPHmS6mXcfdbCW40mKH9TL4Xge@docabouF4os9q7dC1eibcCzrhPz63VSEvj9bxYmEWRNbr1hjxlnpEHOIDk7JlN@Z14xUmAGR8@fHRs/FypnPyn6CUvnjjg2f3l7M5WZUekzzCIJwn@q5Fe8g9KTkQPxILNPxBd/ASmw0NG87aPnaFN6MPPu9Bc44B4avlTFVvzTS6gHyv8Oxyn5NhUazao1L2V9Z@UgeJpnBy@fHW8cuBK8itAt@@VqRqTY1z17XSKuAPPxOrUw82deqo5Z3kZm/FouzZrcnlaJ@C1MAXmj3d6Se2yzVFzixofe6z9jy4Umk@3k61ToKjcbPay72Xr9YTLicDxyzCPtwo/sn/rED4jsbV@THEMbdENjtDw "JavaScript (Node.js) – Try It Online")
~~24 different characters \* 6 times each~~
~~28 different characters \* 5 times each~~
~~27 different characters \* 5 times each~~
~~27 different characters \* 4 times each~~
~~26 different characters \* 4 times each~~
~~25 different characters \* 4 times each~~
24 different characters \* 4 times each
**Explanation**
```
o=>!(
a=o.split``.map( // Split the input into character array and
i=>o.split(i||aeehhhlmmnnnpst)[`length`]-1 // count the occurrences of each character.
)
).some( // Then check
g=>![g>1][-!1] // If each character appears at least twice
||a[-!1]-g // and the counts are all the same number.
)
More to add:
1. Using {s.split``} instead of {[...s]} is to reduce the number of {.} that dominates
the count.
2. Using {!c.some} instead of {c.every} to reduce the number of inefficient characters
(v,r,y in every)
3. Still one unavoidable inefficient character left ({h}).
Update:
1. Got rid of one {.} by replacing {.length} by {["length"]}.
2. Got rid of one {=} by replacing {c[-!1]!=g} by {c[-!1]-g}.
3. Got rid of one {()} by replacing {!(g>1)} by {![g>1][-!1]}.
4. Finally, because count per character is now 4, the backslashes can be taken out.
Update:
1. Got rid of all {"} by replacing {"length"} by {`length`} and exploiting shortcut
evaluation.
{aaaeehhhlmmnnnpst} is not defined but is not evaluated either because of {c} which
must be evaluated to true.
Update:
1. Got rid of all {c} by shortcutting the undefined variable at {split(i)} and replacing
all {c} by {a}.
Since {i} is never an empty string, it is always evaluated true (except compared
directly to true).
Update:
1. Got rid of all {,} by moving the assignment after the argument list. The {()} at the
front can therefore be moved to the assignment, retaining same number of {()}s.
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~84~~ 80 bytes
```
x=input()
c=map(x.count,x)
print max(c)==min(c)>1
1. or our>ram>>utopia,
1., 1.,
```
[Try it online!](https://tio.run/##TVBnk6pAEPzOr1gzGPAwJ4yn3plzLAPgqijJFRTTb/eB3l29rZrqma6ume5VLupWlgJPTl5B2mq1PnWalxRNxQmMo0VGwXWSkzVJ9eoEpiBeUoHI6DhH0LTISwamKYwigYyArKE0YsR0WlNlhWe8Bu0FRj2NpeRRRbxirDxveQGCHtJgAgNARRcTAIA65IDpADN7DioqKDZLRYRk9BawCDJ77G0A40VFRqqhFwTIqbwsHbGXRUD/z5EFk4MIN/f@en/pfnqXESTh8r7zmDx5YgQNHnHiV@0SoGQqDHgriD8L5hcZ9wRGZFdM4u39L8XTyhjPihlgoQAFLAywUK@RZTlutYJwvd5sDIJqWwaLdZfPRfKIv90f6v6zPhvsGhV6vgjhjJPOhOUx46XO23snNK72gS3OWWxt0HOul4mjaM@OTj5tM0y1COExbKVLrp0Q1MWVK/4N7fVGsocK@YJfnXzX3OVAlL0UJXLzsa9u2Y4jXfaRYeWLq30QlcnymHBP9UD3Gok5TvMvOeaZQu@tmTtImWAx1SydR3gye9FmnmvUr6wO/U8zi1ksa0Z6ddxPvtf0w7LtdaTL5cKrRGjBVIjPWcA9r5/w4qPKRuXsbI/gaZiBvY/SMPl9ryR4HTjilmDpLCbd/Un5axlTB@nNhdJHqa6/mYs21LzrwQHNNbDXvGNhrNxsU5LcOTe9fWyn@CIdodyv2Rap@UehMKm22uvPgONIbKEvX@9olJQ5rHi/JXygz5JdRoxn5G01r9evxpbGQzdxGYx/349TTzHrvKSt/wA "Python 2 – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 18 bytes
```
oḅlᵐ=h≥2
oḅlᵐ=h≥2
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/P//hjtach1sn2GY86lxqxIXG/f9fyTBQMSw@LTjT0cypKLO6prYk28U3NizLz8s2Lt5EI1HN1t40PzJRx7A8oybIJNI7VEHZMllROVAhRC0twao4V8Uhoky3ND3cJkAzpzY8wM5NPSvHuCI3Rd3SM1XF1886pMjZyVm/JMrTR8vdyDyp0jVPL90g2zsjKUjVzl1Xz7TAI9nHQNMrKqHYSiu6wii4ysxCtSzOI99COzpVp9rfsTDP3tjVxt@tPELD2qGyNFa7yly/IKUw1EUJAA "Brachylog – Try It Online")
Unfortunately, I can't remove the linefeeds, since `ḅ` on a number triggers a fail.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 104 bytes
```
($qe=$args[0]| group |sort count|% count)[0]-eq$qe[-1]-and$qe[0]-gt1####((()))%%%pppddd===aaccss11nu|0gr
```
[Try it online!](https://tio.run/##JY1NCsQgFIOvUphKdSHUA3gScfHqe7WLotYfZuPdrcNkk/AlkBS/lMtF9z0GXx/SK2RfzG774nNsaekl5rq42ELt7O9i1pKeuTZSWQkBf3EyX9VninMuhGCMpZQQUWsN4FwpSoXWd5/HvDLugmys3QCOwzlEovP0fhMv "PowerShell – Try It Online")
This was great fun to golf. The limitation was `$`, which we need four of at minimum (one for the input `$args`, one for assigning the computation result `$qe`, one for checking the last character `$qe[-1]` and one for checking the first character `$qe[0]`, so that was the working maximum number of characters.
From there, it was a matter of golfing (and not-golfing, like having a two-letter variable name) to get the program nicely divisible by four. Note that we have a small comment (everything following the `#`) to account for some missing elements, but I tried to keep the comment as small as possible.
[Answer]
## Haskell, ~~90~~ ~~75~~ 72 bytes
```
a[i]|d:n<-[[i|n<-i,n==a]|a<-i]=and[[i]<d,[d|i<-n]==n]--aadd,,,,:::::<=||
```
Each character appears 6 times. The input string is taken as a [singleton list](https://codegolf.meta.stackexchange.com/a/11884/34531).
[Try it online!](https://tio.run/##rY/XoppQFETf/Ypjb2CvCPbeeyOoBw4qFlDAjv@Sb8mPGUxu7k3eMy9775n9MGsNlS2/271ekBYYDREiidO0oOlDwESKgowG9ZWhoIh0nyERRiNNIHGRoSiRwXEIEcJ0EW@RlKa99lAQAQWQZDAAgONA5iECinSSOR4sZWkPFBUJop4dTmpPlesiMEkX8eODAKZ3IguiCiwAAtr0v3qZmI8@krrmZaDyigo4qPDKP02@iV@xQry77OGhARy/Gnmg53CSeSegdV@XCeoyYZ@H0Q/8wAiB0f@XybIchxDPL5er1aft7xiH82VPyESysvDQnuo232CGm2aVms1DDmijUmFpAjH/Za11Q5PaAJjjnNHcAX3bckEoe0t6fMZPqxHZdu6eo3ayaN/sgtc9sscrvKXRTPTlXDbnVaeVuqsUiLK3guhZ@ba1Ndu1Jku4J3woc3WfszpdKISLvgZ690jMep6VpZib5rFHK3MUU8EC2Spexo5E@nZi3Peo94COg7wO8AfsC5Fl35R/3dznznaWkR6XCSMiNIdVZ54JuGaNs6PwrLFRKc1sZf48SvF9X3GUqGhVQrgCa9wYLF72CddgWiovYuowubr5r2Oy521lok01a39y4GQfWurYZDc5PMy0x7Oxrfrb2OaAR7q70qBunpMzXy43rbU7y3zAqjjXPJ5tdE9@MXVEgtcYPlIX0SLJ0D3G2q37vdxcU47QY78IxiuaQrsLadstafoNwBh@fDe8fgI "Haskell – Try It Online")
For reference, old versions:
75 bytes, each char 5 times
```
n(l)|d<-[[0|n<-l,n==a]|a<-l]=and[[0]<d!!0,all(==d!!0)d]--an!((())),,,0<[]||
```
[Try it online!](https://tio.run/##rZJXlqJQEIbfXcWlTaBgzoI555w4qJdgxIsCZtxLr2U21kNP6OkFTD399VXVw3dObaC2l2T54wPhMmGINMWyPgPRlEwihoGcAc3IMRCJJudoEcN8JJRlnGE@IyFyFAURhuM4QRAkSfpoljOMjwPcIsAAUbFYAKAooEpQBJpyVgUJrFTlADRd3CJztpb0vIJ0CekaSKUYcFS3SAcegP4cKvpGUoEuaToQoCZpJj3AYxPgvxY9iACsicx6g2a9kV8N5gd@gEGA@b9BnhcEUZSk1Wq9/sL@LjZarPrbbCSnbp/GS98Xmtxo16ox80UIhw4mHVamkPRfN0YvNK0PgTUuYNYuGDhWy4R2sGUmF@q8HtMdQn6NO6mScycHbwfRGa9KtmYrOVDzubxXn1UbrnIgyt@LyLP27esbvmdPlSlP@FgRGj6iNltqCRd7C/QfkZj9Mq8oMTcrkc929oTSwSLdLl0neDJzP3PuR9R7FE/DginwV@yfIs9/Wn7rha/Md1eRvpANi4nQAtaIAhdwzZsXvPiq81Elw@1V6TJOSwNfaZysGrXE9gbscSxYuh6SruGsXFnG9FFqffffJnTf285GW3rO@RLA2TmyNcipPD0@razHs3OsB/vY7khFenJ52LAu6Lkvn5/VO91VIWDXiI1E5Zq9sx@lT@LWi4VPzBXZFBW6J2Sn/XhUWhsGDz0Py2C8amisu5hx3FNvvwU4y493y//80p8 "Haskell – Try It Online")
90 bytes, each char 3 times:
```
a x|h:u<-[sum[1|d<-x,not(d/=c)]|c<-x]," \"\\&,../1::>acdlmmnosst">[]=h>1&&all(not.(/=h))u
```
[Try it online!](https://tio.run/##tZJXmqJQEIXfXcU1gyKKqU1gzjkHGvUSFJWgBLN7mbXMxnqY1NMbmPNU51Sdh//7SoT6QZCkjw8Irk8xZWYCtG7KNPHkM4ErpqgGwgdJDmWenOUZzAHAu@P93YPheJBIpSjI8ZIsK6quGw6KZkiRIjweKEmI1cSRICmiqPkhw50CSMCrNhsAgQDQBMgDXTU1TgAbTZWBbvA7xdptBaOoKoagGDqgKBIctZ1iABzAP0XVEAUNGIJuAA7qgm6lMjy2AfLrEIcooK3IkgNacmCfxk4AAtghsBNfQpblOJ4XhM1mu/2Mib59stoMd/l4Qds9ni/jUGozk32nQS5XUQR6yGxMnUOMuIjPQXTeHANnkrM7@2Dk2axTuuzKzc4BczvN9FDpNe1RFe9eilxl3pusC652Jz3SioVi0FjUW75q@I29lRV8Gzo0RXbgpqoBPHasca0Q2lis9ZSPvoaH93jCfV7W1ISfFrBHN39SspFyplu5zJB07mYy/vtb8MifxiUL4C/YP0SW/Un5xXOfM9vfxIdcPsanoivYQEtM2Ldsn5Hyq8m@qTnmoAnnaVYYhSrTdP3ZSO2uwJ20RyoXOe0bL6q1dcKYUNsbcZ1lhsFu/q1jFLwvDpjeiauFzaX58eGkcXzv2Y4Oif0xEB9I1XHLucosQ8Xiotnrb0pht46KQqDQHpiEkj3xu6A9diIvikvVoH@G9br3e60jkkj0Ia8jyfpTp/3lnOdGOX4DMLbv32z/8Wl/AA "Haskell – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~108~~ ~~104~~ ~~92~~ 88 bytes
-12 bytes thanks to [Rod](https://codegolf.stackexchange.com/users/47120/rod)
-4 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)
```
s=input();c=s.count;print[all(c(s[[]>[1]])==c(o)>1. for o in s)];aaafffillpprrtuu>1.>1.;
```
[Try it online!](https://tio.run/##PU/XroJQEHz3K44d7NgVsffeG0GlKoqAB7D77V7U5CabnS2TyYx603eKHH6zCscTNpvtrRGirBo6guIsoQVYxZB1XIWirJO0JCEsopEklSUxikIJgkUUNIsFgKBAoABRBhpK4TRNC4IgSpKqQqgbhkkwC3@b4gFNh6KKoJbLTpR4MIYGn7YAoMPbBwDgrzwLPk4sn5nlVR1UetUKhAr8ERjI04f/5@@m0ppmsXwtWr7WAQEk@shwdPqn9a/6tpneaJvFBCsGMGClgRX7rgzDshzH84Kw3ZoHbGCdroWRWIgXofh4vvRDuUNN990msVpHEdpF5GLKgvZhl91zGF20JsCeYq32ARi7hE1aOzry87Pf2M4yfVR6zfrZqnsvRa5Hzp1q8I5OFx/DUrEU1JeNtqcWTjC3ihzYhg6tHTN0Zmv@QEyts@0Q2lxutLSHvIZH93jSeV7VlaSX5H2PXuEk5yKVTK96mSN4/mZQ3nsiqHKnSfmT5ZvHDPRBhvmfWLMzAyE@YgsxLh1d0020TIU9q84ZqbxaTELJUwfIn2c5fhyqzvDGs5kWr8CZskaqlyPumSxr9U1Sn2a3N@w6z4yCvUKiqxfdLxYY7qmj7VtIC/VhJwOBvWs7PiT3qj8@lGqTtn2dWYVKpWWrPxDKYaeG7nh/sTM0MDl34sSgNXYiLrJDgbR37uv37vd6d0cg0cdxE0k1nhrpreRdt6ztDw "Python 2 – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 12 bytes
```
q&=sqt&=tsvv
```
The input is a string enclosed in single quotes. Single quotes in the string are escaped by duplicating.
The output is a non-empty matrix, which is [truthy](https://codegolf.stackexchange.com/a/95057/36398) if it doesn't contains zeros, and is [falsy](https://codegolf.stackexchange.com/a/95057/36398) if it contains at least a zero.
[Try it online!](https://tio.run/##y00syfn/v1DNtriwRM22pLis7P9/dWSuOgA) Or [verify all test cases](https://tio.run/##bU/XruJADH2/XzERZaiB0HvvvVdRUiYkEJKQTIBQvp0L7MtKu0eyfexjW/aRxtJrC/6FDXAKSZIXQZTQ62RP6ydsT2P9fH5lIdYMLJjwCXla0k24@nTrmJY5WuPAH9H3lQBGOv4pjf67XtRViTY9QDV04TOFAFYAqyEaIyDKvCiLbyIpigoMGYvSu6YaGIg6QFeBNnSMuBf8@zD4A@k3voGgAAUIGhDUN2UYluU4hHh@t3sXqD4x2fBDMR8paOL98cSHUns12Xca6fUm5KDt6WxYmdMe6iI8BqF5cwwscZaw9MHIzm8T@tGam529xm6a6jml57SXqUC4l4LXIwdhvI6s7U5ypBULRR9e1FuuaiDKmGWZ3PkPTYEZ2DJVLxlWa2zL72wstnrCtbwGhrdIzHZe15SYe4k8927@JGeD5VS3cpk5kjnTWLlvUZ/KncalzzcfY5jPU1/Gvj3T5yNDNh/mEqEN3XCWVgHXun12lJ9NJqrkVgcNnadZNPJXpsn6o5EQr8AWJ4KVyzHpGi@qtW0MTzI7k7rOUkNfNx/t4AKETxYYEE6sLc9cmqt3y5Ik9/bd6BDbq97IQKqOW5ZNau0vFhfNXp8vBWy6U0DeQntgUHL2xIk@InxKX2SrotHumafXvd1qHSHtCN2P22C8/tCX7nLObmbgLw), including the standard truthiness/falsiness test for convenience.
### How it works
Statements marked with `(*)` are neither necessary nor harmful, and have been included only to make the source code non-discriminating.
```
q % Implicit input. Convert chars to code points and subtract 1 from each (*)
&= % Square matrix of all pairwise equality comparisons
s % Sum of each column. Gives a row vector
q % Subtract 1 from each value. An entry equal to 0 indicates the input string
% is discriminating because some character appears only once
t % Duplicate
&= % Square matrix of all pairwise equality comparisons. An entry equal to 0
% indicates the input string is discriminating because some character is
% more repeated than some other
t % Duplicate (*)
s % Sum of each column (*) (all those sums will be positive if the previous
% matrix doesn't contain zeros)
v % Vertically concatenate the matrix and the vector of its column sums
v % Vertically concatenate the resulting matrix with nothing (*)
% Implicit display
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~87~~ 78 bytes
```
c=->m{y=m.chars;x=y.map{|d|y.count d}|[];x[-1]>1and not x[1]};->{pushrortpush}
```
26 characters repeated 3 times each
[Try it online!](https://tio.run/##rZHHsqJgEIX3PMVvjqCYFcWccw4UKkkxIEhQEHh273Wc7eymq6u@073p6nNkjTbeb6YA44JpFASE4SlZwfSCgQiUZFqsZSCMqN1UwNoWQWI6AaMkjlI3FtxEFegEStoYjJuSpvCyKKsf2m9JUxXgm8mayhs5H0RAzv97wBkGLpCHYaDyJwX8tspzQBE1meEAI7Ic5KR@yxn@0IECFDgo4EC/M00zDMty3OFwPH426Nix2B2mp3KqIp9My1YvtT65OA86he0u4ae8hWJSXFNh9Mlbk8S6OweuLONwjcHMe9jnFMFdWj1g7bjMjwJXeznCG77zNa4LrC/b5tz9ATaTq5VqRN20e8FmLE0b9RtyjF66PD3x4E0YSUotphcNdDZ7JRck9Nj0lcp4HtuWmAkRXNgclu@3YryeHzaeKz9WMjQy9EpHJPY@rzkhEuEohgemdbLAH8cZ4kTaEPTR0DeCBnVV/ibwtYOmPw58JfMBPT6kpkw5yeYSO6oTqJGx4Lb/8NftLp0WS@RF5h7LIjeLNpZY2@rkTjrwZB3xxlPAgvNNs7XPqAv8aKD6Kj@NDMvpgVrx2QzQfAt3L7y@riXTRSDI2XucXTJnCU5Nrs15z7XLb6PV6qY7Gh9qMY8S4Dm40p9o6K14Z08RR/JeeN7cokyFVuHR8PVqDfiCP2EK@3i2bSlEqF7yGvi//n//AA "Ruby – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), `-p` 57 bytes
Each character appears 3 times. Only a single `1` doesn't do anything
12 bytes added to a basic 45 character solution to make in non-discriminating
```
s{.}[@m[@1{$&}+=$.].=g]eg;$\=s()(e@m;1)&&m[e(\sg+)\1+;]}{
```
[Try it online!](https://tio.run/##K0gtyjH9/7@4Wq822iE32sGwWkWtVttWRS9WzzY9NjXdWiXGtlhDUyPVIdfaUFNNLTc6VSOmOF1bM8ZQ2zq2tpoCrf/yC0oy8/OK/@sW/Nf1NdUzNNAzAAA "Perl 5 – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 90 bytes
```
"?"=`u\164f8ToI\x6Et`;'!'=prod;!{y<-xtabs(~?readLines())}%in%{z<-y[1]}&z>T##&[]>~48bEfILpu
```
[Try it online!](https://tio.run/##K/r/X8leyTahNMbQzCTNIiTfM6bCzLUkwVpdUd22oCg/xVqxutJGt6IkMalYo86@KDUxxSczL7VYQ1OzVjUzT7W6yka3Mtowtlatyi5EWVktOtauzsQiyTXN06eglJZGAwA "R – Try It Online")
Outputs `TRUE` for a non-discriminating string, and `FALSE` for a discriminating string. I have written a lot of ugly code for challenges on this site, but I think this is the ugliest so far.
45 characters, used twice each (including a few in a comment). The previous best R answer was [116 bytes](https://codegolf.stackexchange.com/a/156994/86301), with 29 characters used 4 times each; I am posting this separately since it is substantially different.
The code is equivalent to
```
y = table(utf8ToInt(readLines()))
z = y[1]
all(y == z) & (z > 1)
```
which converts the input to a vector of integers, computes a contingency table `y` of the values, then checks that all counts in that table are equal to the first count, and that the first count is greater than 1.
The initial difficulty was in using only 2 pairs of brackets. This is achieved by redefining the unary functions `!` and `?` to be `utf8ToInt` and `prod` respectively. (I can't use `all` because I need the `a`). There are four assignments: two with `=` and two with `<-`. This means that the equality test between `y` and `z` cannot use `y==z` nor `y-z`; `y%in%z` comes to the rescue.
Defining these functions uses up all the possible quotes: two double quotes, two single quotes, and I'll need the two backticks in the next paragraph, so I had to resort to `readLines()` instead of `scan(,"")`. (The other options, such as `scan(,letters)` or `scan(,month.abb)` all used a precious `t` which I couldn't spare.)
At this point, I had most of the building blocks: `utf8ToInt`, `prod`, `table`, `readLines`, `%in%`. Three characters appear three times in those names: `ent`. First, I discovered that `table(foo)` is equivalent to `xtabs(~foo)`, saving the `e`. I can rescue the `n` and the `t` with the hex/octal code [trick](https://codegolf.stackexchange.com/a/191117/86301); the golfiest solution is to use `u\164f8ToI\x6Et` (in backticks) for `utf8ToInt`.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 153 bytes
```
f(h,a,c,f){{{{{{{char*o=f=h,*r;for(a=!h;*o;o++){for(c=!h,r=h;*r;c+=!(*r++^*o)){}f*=!!(c^!!h)*(!a+!(a^c));a=c;}(a^c^c^f^f^h)+o,a+r,o,o,+h^*r;(a=f);}}}}}}}
```
[Try it online!](https://tio.run/##zVHHtqJAFFyPXwH6VJIBsyLmnHMWhUbABApm5NsdnHect5gfmKpNdZ3bt6tPAZcIwOslIBLBEoAQUP0bQGJVTKEFWiIwlRIUFWFpWKIwhVJwHNXfBjANQqVNU6UATsMIpuI4gykoqhsCRsMwAhgYllAMgVkcRlgGoCjF0oAy3tqkYFJCcYVgcZVQTOISY@4yXxJQyvjG66KseUhE3nkgTEMtuuXXQV3LJwGx2skgD82sdm1mnclWAhIQDSUgDaUshsVijkB7di0j31fOJw2x9tTzSbrHZrLLhNWc@yUiVtbEj4ZJiIRgFoLJH4/jAOD51UoQRPHjkm14sBC663Qoo671p3Ha5urzwaZRoZlFAGEddDKojFmCvErPTmBc7UO2KIBtbajnEJYxbf@VGl1cZ3EYb6E7Y9hKFJybnf@2553R8uqr3qB6ajaT9Zwm5RpW9IW5e152i95tVeI69kTR5Q4eSqDmRSuTpRbDpjdf9xGK2C9MSYng0xWhN9NHOenPx5uF6wihUvfzHH@EPQf@2M998v@3hf8J@ClsJhfYnfZPY38Fx73b@TmCj@TaQqgL0kE@FliwFTQ392FM/YLkjSoXVlLzrbq6DJOrnrcwpMrPSmx9g@xR2F@47imsPymWlpHTICHeydso3vU00@HGKeM0AHR2Dr5qxHg3Pui2qdu9cYi9bWRzcIU6u2K/ZlvEGW82O6m22kLOZ9dQaeXK1DtnUk4e@bUHDh7pq/ylqCw@IlrNx6PUkGgkoO@X/mj5qU3xfMpxT7w/YLx@Aw "C (gcc) – Try It Online")
Returns address of string as truthy value, and zero as falsy.
```
f(
h, Address of string.
a, # instances of previous character
c, # instances of current character
f Return value
){{{{{{{
char*o=f=h,*r; Point o to string, while giving f a non-zero value.
for(a=!h;*o;o++){ Set previous char count to 0, and then traverse the string.
for(c=!h,r=h;*r; Set current char count to 0 and r to string,
and start counting instances of current character.
c+=!(*r++^*o)) Add to counter if current character matches.
{} Lower the amount of semi-colons
f*= Multiply (AND) return value with:
!!(c^!!h) Is current count not 1? (Must be 2 or above.)
*(!a+!(a^c)); AND, is previous count valid (meaning this is not the first
character counted), and matches current count?
a=c;} Previous count = current count.
(a^c^c^f^f^h)+o,a+r,o,o,+h^*r; Spend surplus characters to make source code valid.
(a=f);}}}}}}} Return value.
```
[Answer]
## R, ~~132~~ 116 bytes
```
crudcardounenforceableuploads<-function(b){{pi&&pi[[1-!1]];;;"";{1<{f<<-table(strsplit(b,"",,,)[[1]])}}&&!!!sd(-f)}}
```
It doesn't contain any comments or superfluous strings, either, though this will probably be my only time in code golf calling a function `crudcardounenforceableuploads`. ~~There's probably a great anagram in there somewhere for the function name!~~Thanks to John Dvorak for pointing out a nice anagram solver, which I used for the name.
Character table:
```
- , ; ! " ( ) [ ] { } & < 1 a b c d e f i l n o p r s t u
4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4
```
examples:
```
> crudcardounenforceableuploads("aaabbbccc")
[1] TRUE
> crudcardounenforceableuploads("aaabbbcc")
[1] FALSE
> crudcardounenforceableuploads("abc")
[1] FALSE
> crudcardounenforceableuploads("crudcardounenforceableuploads<-function(b){{pi&&pi[[1-!1]];;;\"\";{1<{f<<-table(strsplit(b,\"\",,,)[[1]])}}&&!!!sd(-f)}}")
[1] TRUE
```
[Answer]
# BASH 144 bytes
```
grep -o .|sort|uniq -c|awk '{s=$1}{e[s]=1}END{print((s>1)*(length(e)==1))}##>>>#|'#wwwuuutrqqqppooNNNnlllkkkiihhhggEEEDDDcccaaa1***{}[[[]]]...--''
```
This line of code takes an stdin string as input. "grep -o ." puts each character on a new line. "uniq -c" counts each chacter's usage. The awk script creates an array with each usage as a different element, and outputs true when there is only 1 array index and the value is at least 2. Each character is used 4 times, so this source returns true
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~26~~ ~~24~~ 18 bytes
```
:u{m*_{y#m:u_hy#h*
```
[Try it online!](https://staxlang.xyz/#c=%3Au%7Bm*_%7By%23m%3Au_hy%23h*&i=%3Au%7Bm*_%7By%23m%3Au_hy%23h*%0Aaaaa%0Aaa%211+1+%21a+%211%0Aaabbccddeeffgg%0A1Q%21V_fSiA6Bri%7B%7C%7DtkDM%5DVjNJ%3D%5E_4%28a%26%3D%3F5oYa%2C1wh%7CR4YKU+%239c%21%23Q+T%26f%60%3Asm%24%40Xv-ugW%3CP%29l%7DWP%3EF%27jl3xmd%279Ie%24MN%3BTrCBC%2FtZIL*G27byEn.g0kKhbR%25%3EG-.5pHcL0%29JZ%60s%3A*%5Bx2Sz68%25v%5EHo8%2B%5Be%2C%7BOAqn%3F3E%3COFwX%28%3B%40yu%5D%2Bz7%2FpdqUD%0Aa%0Aabbaabb%0Aabc%0AbQf6ScA5d%3A4_aJ%29D%5D2*%5EMv%28E%7DKb7o%40%5DkrevW%3FeT0FW%3BI%7CJ%3Aix+%259%213Fwm%3B*UZGH%608tV%3Egy1xX%3CS%2FOA7NtB%27%7Dc+u%27V%24L%2CYlYp%7B%23%5B..j%26gTk8jp-6RlGUL%23_%3C%5E0CCZKPQfD2%25s%29he-BMRu1n%3Fqdi%2F%215q%3Dwn%24ora%2BX%2CPOzzHNh%3D%284%7Bm%6039I%7Cs%5B%2BE%40%26y%3E&a=1&m=2)
~~Shortest solution so far that only uses printable ASCIIs~~ Beaten by MATL.
Guess I was approaching the problem the wrong way. Repeating a working block is neither golfy nor interesting. Now at least it looks better ...
## Explanation
`:u{m*` produces some garbage that does not affect the output.
```
_{y#m:u_hy#h*
_{y#m map each character to its number of occurences in the string
:u all counts are equal (result 1)
_hy# get the count of appearance for the first character
h halve it and take the floor, so that 1 becomes 0(result 2)
* multiply the two results
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~22~~ 18 bytes
```
^1>=Y^aNaYMNy=My>1
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuhab4gztbCPjEv0SI339Km19K-0MIRJQ-W3RSpgqlGKhsgA)
### Explanation
Each character occurs twice.
```
^1>=Y^aNaYMNy=My>1
a First command-line argument (a string)
^ Split into a list of characters
Na Count occurrences of each character in a
Y Yank the result into y
^1>= No-op: compare with [1]
MNy Minimum of y
= is equal to
My Maximum of y
>1 which is also greater than one
Y No-op: yank that result
Autoprint the result of the last expression
```
---
Alternate 18-byters:
```
Y^!1Y^aNaMNy=My!=1
Y_<=1Y_NaMa1<Ny=My
```
[Answer]
# SmileBASIC, ~~164~~ ~~152~~ ~~148~~ 140 bytes
```
DeF M(X)DIM W[#R]WHILE""<X
INC w[ASC(x)]X[n]=""wEND
FOR F=e#TO--nOT-LEN(W)U=w[F]H=H||U&&U<MAx(W)neXT-!!!AASSS#&&Oxx||CCLL<<wIM#
RETURN!H
enD
```
35 different characters, repeated 4 times each.
No comments were used (but the expression after `neXT` is never actually evaluated)
Script to check answers:
```
//javascript is a convenient language that I love using!
var input=document.getElementById("input");
var button=document.getElementById("button");
var output=document.getElementById("output");
button.onclick=function(){
var text=input.value;
var freqs={};
for(var i=0;i<text.length;i++){
var letter=text.charAt(i);
if (freqs[letter]==undefined) freqs[letter]=0
freqs[letter]++
}
sorted=Object.keys(freqs).sort(function(a,b){return freqs[b]-freqs[a]})
var out="";
var min=Infinity,max=0;
for (var i in sorted) {
var letter=sorted[i];
var count=freqs[letter];
if(count<min)min=count;
if(count>max)max=count;
out+="\n"+letter+":"+count;
}
output.textContent="min:"+min+"\nmax:"+max+"\nunique:"+sorted.length+"\nlength:"+text.length+out;
}
```
```
<textarea id="input" placeholder="code here"></textarea>
<button id="button"butt>count</button>
<pre id="output">...</pre>
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~168~~ 90 bytes
The output will be empty if false, or non-empty if true.
```
***???;;;;```!!$$$$MMMMOOOO..1111ssss222{{{{\^^^^
s;{O`.
M!*\`^((.)\2(?!\2))*$
(.)(?!\1)
```
[**Try it online**](https://tio.run/##K0otycxL/P9fS0vL3t7eGggSEhIUFVWAwBcI/IFAT88QCIqBwMjIqBoIYuKAgIur2LraP0GPy1dRKyYhTkNDTzPGSMNeMcZIU1NLhQvIBXEMNbloaTYA)
### Core program (39 bytes)
```
s;{O`.
M!*\`^((.)\2(?!\2))*$
(.)(?!\1)
```
### Explanation
The entire core program is in a silent loop. The first stage sorts the input. The second stage will print the current string if it consists of successive pairs of different characters. The third stage removes the last occurrence of every character (removing one of each character in the string).
About the junk at the top: the order is important. In addition to needing to be syntactically valid, a semicolon must be after the asterisks and before the backticks, so long as `*` is in the config string, in order for it to not print.
[Answer]
# [CoffeeScript 1](http://coffeescript.org/), ~~96~~ ~~93~~ 90 bytes
```
(q,a=q.split(h).length-1for h in[q][0])->a.every (w,s,pplitnggffoorsvvyy)->w>1&&a[0&10]==w
```
[Try it online!](https://tio.run/##tVJZc6JAGHz3V4zEKEREiIk33kc0xhxeiSwq4IAoMggIYsxvdyHZqt3sw77tVM3011NdX1dXtYRkGUJLMlXDPsvsGd@RArujLENTbXxFUBrUFXuVYGRkghVQdW7HczRPJEoCBR1oegB3SYs0ArmuKLKMkGk5juf5CrfERKMCR0cZmmdZ91wIOYAF2P9zwAohyXfAOZV0fu1Xf@/nAwPVNwBV0xQ8SjbRFujQBQNo4w5BhCSkW0iDlIYUHBtCywaCIqi6jxJawjzAiMJ3jYxjIA4c/2JEkMwf5GBTIYR8Sn9XS0ToHw52QCTBgtaXD4cJ/sHIkI9hBjAgLIAw88VFUZKWSwhlWVGCH@Y5PJ7LA7Warpnq@@nD3jQe@PG632Vn8xtciLLlW/QmkIy7Or3cvN2PwEVOCl88g2FUXuStbaTy6iT2yqT4RGgfk6dSK7bWUoftMpbrwMhDvzA067V60p52elft64zoNXVKoTf3K/HlstROULfGndSjie50YeWvuMP14JjOXjqzO5SNc5B8f6zu9HKqWXxsua94oeLt@fgxkzSWu1HjM83nI4pBqq9RCkB8ltMDqXq7zN/MhS7R4K@vZg8O3vy4FzOowm9M6EzKcEi3JoXOqZtXD@AyF0613G3hajRt3y2y9rikeMzhtThIPlYzfbsW@5DAPjaO9Mg37c14v@Aoah1Vhpvs2kikX7T2qHcxL87oen16//QsN64vLWIFE7WHlz2jl3dLNRm@3bGuHkGmEH8lnx6Px7v@isVv3reLVK5zsrh4sxL1ShhPbQUDxxHBlv7qyg8sKAgK2vLjj74ggiDOPwE "CoffeeScript 1 – Try It Online")
Started from [my ES6 answer](https://codegolf.stackexchange.com/questions/156967/non-discriminating-programming/156981#156981) but walked back to using `Array.every`. ~~32~~ ~~31~~ 30 tokens @ 3 each
[Answer]
# [Whispers v2](https://github.com/cairdcoinheringaahing/Whispers), ~~1750~~\* 1305 bytes
```
> 1
> InputAll
>> ∪2
>> #2
>> #3
>> 4÷5
>> ⌊6⌋
>> L⋅7
>> Each 8 3
>> 9ᴺ
>> 2ᴺ
>> 10=11
>> 6>1
>> 12⋅13
>> Output 14
###########################00000000000000000000000000001111111111111111111112222222222222222222222222333333333333333333333333334444444444444444444444444445555555555555555555555555555666666666666666666666666666777777777777777777777777777788888888888888888888888888889999999999999999999999999999============================AAAAAAAAAAAAAAAAAAAAAAAAAAAAEEEEEEEEEEEEEEEEEEEEEEEEEEEEIIIIIIIIIIIIIIIIIIIIIIIIIIIILLLLLLLLLLLLLLLLLLLLLLLLLLLLOOOOOOOOOOOOOOOOOOOOOOOOOOOOaaaaaaaaaaaaaaaaaaaaaaaaaaaacccccccccccccccccccccccccccchhhhhhhhhhhhhhhhhhhhhhhhhhhhlllllllllllllllllllllllllllnnnnnnnnnnnnnnnnnnnnnnnnnnnnpppppppppppppppppppppppppppttttttttttttttttttttttttttuuuuuuuuuuuuuuuuuuuuuuuuuu÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷ᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺ∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋
```
[Try it online!](https://tio.run/##7dRNCoJAFAfwvacY6ALO@L1owIWLIPAMIoGBiKTSCYRQT9I6ENp6kryIORZE1HuLmHbz88@8B84wq3nHZF/ku0PBpokTqnGyyfKq9NNU45yMpzMTdfVYDbGaQ28t/7rGHrtWtNuxrR3RBFGcEJcs@7zb5Soqe1aqrykVjc2XQtl8ii5bw6qc7yTU1N6RlxVMR9BvGMQAmTALYcMchIvwEGuEjwgQG8QWESIiRIxIECksQ@SwElSBhv63b34jcjO/XPlpa8npmj@klR41GtVoVKNRjUY1Gj9yBw "Whispers v2 – Try It Online")
\* Golfs made while explaining it. You can see the original [here](https://github.com/cairdcoinheringaahing/5-solutions/blob/9b575896ed946c2a86efca74588dd8d834fb2096/3.md)
Interesting task, fairly boring restriction.
Unfortunately, due to the fact that every line must start with either `>>` or `>`, this forces the number of each character to be disproportionately large. Luckily, Whispers ignores every line that doesn't match one of its regexes, all of which require the line to begin with `>`. Therefore we just have a large character dump at the end of the program. In addition to this, Whispers, being designed for mathematical operations, struggles when applied to a [array-manipulation](/questions/tagged/array-manipulation "show questions tagged 'array-manipulation'") question. Overall, this means that the task is interesting to attempt, but the source code requirements are a bit boring.
If we strip all the unnecessary characters from the program, we end up with
```
> 1
> InputAll
>> ∪2
>> #2
>> #3
>> 4÷5
>> ⌊6⌋
>> L⋅7
>> Each 8 3
>> 9ᴺ
>> 2ᴺ
>> 10=11
>> 6>1
>> 12⋅13
>> Output 14
```
[Try it online!](https://tio.run/##K8/ILC5ILSo2@v/fTsGQy07BM6@gtMQxJ4fLzk7hUccqIxCtDCGNQaTJ4e2mYLmeLrNHPd0gps@j7lZzEMM1MTlDwUIBrM7y4ZZdINoIShsa2BoaghhmdmDK0AioyxCs1L@0BGingqHJ//@JiUlJyckA "Whispers v2 – Try It Online")
which is the part of the code we're actually interested in.
## How *that* works
Here we conduct two key tests: the count of each is the same and the counts are greater than **1**. However, the code for these two tests are shared between them, so a complete walkthrough of the program is a more effective method of explaining this.
We start with the shared code:
```
> InputAll
>> ∪2
>> #2
>> #3
>> 4÷5
```
Here, we take the input and store it on line **2** (`> InputAll`). We then create a `∪`nique version of that string (i.e. the input without duplicate characters). With our next two lines, we take the length of the untouched input (`>> #2`) and the number of unique characters in the input (`>> #3`). Finally, we divide the former by the latter.
Why? Let's have a look at the two inputs of `aabbcc` and `abbaabb`. With the first string, the division becomes **6÷3 = 2**, and the second results in **7÷2 = 3.5**. For non-discriminating strings, the result of this division is **a)** An integer and **b)** Greater than **1**. Unfortunately, this also applies to some non-discriminating strings, such as `abbccc`, so we have to perform one more test.
```
>> ⌊6⌋
>> L⋅7
>> Each 8 3
>> 9ᴺ
>> 2ᴺ
>> 10=11
```
Note: line **6** is the result of the division.
First, we take the floor of the division, because Python strings cannot be repeated a float number of times. Then we reach our `Each` statement:
```
>> L⋅7
>> Each 8 3
```
**3** is a reference to line **3**, which contains our deduplicated input characters, so we map line **8** (`>> L⋅7`) over this list. Line **8** multiplies the character being iterated over by the floor of our division (`>> ⌊6⌋`). This creates an array of the deduplicated characters, repeated **n** times.
The results from our two previous strings, `aabbcc` and `abbaabb`, along with `abcabc`, would be `aabbcc`, `aaabbb` and `aabbcc` respectively. We can see that the first and last two are identical to their inputs, just with the letters shuffled around, whereas the middle one isn't (it has one less `b`). Therefore, we simply sort both the input and this new string, before comparing for equality:
```
>> 9ᴺ
>> 2ᴺ
>> 10=11
```
Finally, we need to check that the number of characters in the string is **2** or greater. Luckily, the division we performed earlier will always result in a value greater than **1** if a character repeats more than once, meaning we just need to assert that line **6** is greater than 1:
```
>> 6>1
```
Now we have two booleans, one for each test. They both need to be true, so we perform a logical AND (boolean multiplication) with `>> 12⋅13`, before finally outputting the final result.
[Answer]
# Pyth, 30 bytes
```
"&8<MQSlqr{"&q1lJ{hMrSz8<1hJ
```
Leading spaces necessary.
[Try it online!](http://pyth.herokuapp.com/?code=++%22%268%3CMQSlqr%7B%22%26q1lJ%7BhMrSz8%3C1hJ&input=%22hithere%22&test_suite=1&test_suite_input=aa%211+1+%21a+%211%0Aabbaabb%0Aabc%0A++%22%268%3CMQSlqr%7B%22%26q1lJ%7BhMrSQ8%3C1hJ&debug=0)
The actual program is just `&q1lJ{hMrSz8<1hJ`. I just prepended the string `"&8<MQSlqr{"` to make it non-discriminating. But to make the string not print itself, I had to add a space, so I added 2 spaces.
```
&q1lJ{hMrSz8<1hJ
q1l (1 == len(
J{ J = deduplicate(
hM map(lambda a: a[0],
r 8 length_encode(
Sz sorted(input())
)
)
)
)
& and
<1hJ (1 < J[0])
```
`length_encode` here (`r <any> 8`) takes a sequence and outputs the length of each run of the same character, ex. `"aaabbcc"` becomes `[[3, "a"], [2, "b"], [2, "c"]]`.
So this takes the input, sorts it to put in length encode, and takes the first element of each list in the resulting list (e.g. the earlier example would become `[3, 2, 2]`). This gives a count of how many times characters occur. Then it's deduplicated (the earlier example would become `[3, 2]`), and J is set to that.
Then it checks if the length is 1, i.e. there is only 1 unique number of times a character occurs, and if that is > 1, i.e. >= 2.
There might be a built-in to replace `rSz8` or `hMrSz8` but I can't find one.
] |
[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]
[
This has no practical purpose but it could be fun to golf.
# Challenge
Given a number *n*,
1. Count the amount of each digit in *n* and add 1 to each count
2. Take the prime factorization of *n*
3. Count the amount of each digit in the prime factorization of *n*, without including duplicate primes
4. Create a new list by multiplying together the respective elements of the lists from steps 1 and 3
5. Return the sum of that list
For example, 121 has two `1`s and a `2`, so you would get the following list from step 1:
```
0 1 2 3 4 5 6 7 8 9
1 3 2 1 1 1 1 1 1 1
```
The prime factorization of 121 is 112, which gives the following list for step 3:
```
0 1 2 3 4 5 6 7 8 9
0 2 0 0 0 0 0 0 0 0
```
Note how we did not count the exponent. These multiply together to get:
```
0 1 2 3 4 5 6 7 8 9
0 6 0 0 0 0 0 0 0 0
```
And the sum of this list is 6.
# Test cases
```
1 -> 0
2 -> 2
3 -> 2
4 -> 1
5 -> 2
10 -> 2
13 -> 4
121 -> 6
```
# Notes
* [Standard loopholes](//codegolf.meta.stackexchange.com/q/1061/75524) are forbidden.
* Input and output can be in any reasonable format.
* You should leave ones (or zeros for step 3) in the list for digits that did not appear in the number.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest solution in bytes wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~18~~ 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 byte thanks to [caird coinheringaahing](https://codegolf.stackexchange.com/users/66833/caird-coinheringaahing) & [H.PWiz](https://codegolf.stackexchange.com/users/71256/h-pwiz) (avoid pairing the two vectors)
```
DF‘ċЀ⁵
ÆfQÇæ.Ç‘$
```
A monadic link taking a positive integer and returning a non-negative integer.
**[Try it online!](https://tio.run/##y0rNyan8/9/F7VHDjCPdhyc8alrzqHEr1@G2tMDD7YeX6R1uB0qo/P//39DIEAAA "Jelly – Try It Online")**
### How?
```
DF‘ċЀ⁵ - Link 1, digitalCount: number(s) e.g. [13,17]
D - to decimal list (vectorises) [[1,3],[1,7]]
F - flatten [1,3,1,7]
‘ - increment (vectorises) [2,4,2,8]
⁵ - literal ten 10
Ѐ - map across (implicit range [1,2,3,4,5,6,7,8,9,10])
ċ - count [0,2,0,1,0,0,0,1,0,0]
ÆfQÇæ.Ç‘$ - Main link: positive integer, n e.g. 11999
$ - last two links as a monad:
Ç - call the last link (1) as a monad [0,2,0,0,0,0,0,0,0,3]
‘ - increment (vectorises) [1,3,1,1,1,1,1,1,1,4]
Æf - prime factorisation [13,13,71]
Q - deduplicate [13,17]
Ç - call the last link (1) as a monad [0,2,0,1,0,0,0,1,0,0]
æ. - dot product 8
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes
```
ṾċЀØD
ÆfQÇ×Ç‘$S
```
[Try it online!](https://tio.run/##ATMAzP9qZWxsef//4bm@xIvDkOKCrMOYRArDhmZRw4fDl8OH4oCYJFP/UsW8w4figqxH//8xMjE "Jelly – Try It Online")
Developed independently from and not exactly the same as [the other Jelly solution](https://codegolf.stackexchange.com/a/151631/75553).
**Explanation**
I'm gong to use `242` as an example input.
```
ṾċЀØD Helper link
Ṿ Uneval. In this case, turns it's argument into a string.
242Ṿ → ['2','4','2']. [2,11] → ['2', ',', '1', '1']. The ',' won't end up doing anything.
ØD Digits: ['0','1',...,'9']
ċЀ Count the occurrence of €ach digit in the result of Ṿ
ÆfQÇ×Ç‘$S Main link. Argument 242
Æf Prime factors that multiply to 242 → [2,11,11]
Q Unique elements → [2,11]
Ç Apply helper link to this list → [0,2,1,0,0,0,0,0,0,0]
Ç‘$ Apply helper link to 242 then add 1 to each element → [1,1,3,1,2,1,1,1,1,1]
× Multiply the two lists element-wise → [0,2,3,0,0,0,0,0,0,0]
S Sum of the product → 5
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), ~~43~~ 41 bytes
```
⎕CY'dfns'
+/×/+/¨⎕D∘.=⍕¨(⎕D,r)(∪3pco r←⎕)
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKPdOSM1Ofv/o76pzpHqKWl5xepc2vqHp@tr6x9aARR0edQxQ8/2Ue/UQys0QFydIk2NRx2rjAuS8xWKHrVNAIppgkz5DzaGy5CLC8IwgjGMYQwTGMMUxjA0gLPgqgyNDAE "APL (Dyalog Unicode) – Try It Online")
**How?**
`r←⎕` - input into `r`
`3pco` - prime factors
`∪` - unique
`⎕D,r` - `r` prepended with `0-9`
`⍕¨` - format the factors and the prepended range
`⎕D∘.=` - cartesian comparison with every element of the string `0123456789`
`+/¨` - sum each row of the two tables formed
`×/` - multiply the two vectors left
`+/` - sum the last vector formed
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 5 bytes
```
fS¢>O
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/LfjQIjv////NzMwB "05AB1E (legacy) – Try It Online")
```
f list of prime factors (without duplicates) of the implicit input
S characters, all of the digits
¢ count each of the characters in the implicit input
> increase each of the counts
O sum (implicit output)
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 44 bytes
```
Y_N_.aM,tT++o>aTa%o{a/:olPBo}$+y*Y_N JUQlM,t
```
Takes input from command-line argument. [Try it online!](https://tio.run/##K8gs@P8/Mt4vXi/RV6ckRFs73y4xJFE1vzpR3yo/J8Apv1ZFu1ILqEDBKzQwB6jk////ugX/jYyNzC2NTM0MAA "Pip – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~136~~ 127 bytes
```
lambda a:sum(''.join(u(a)).count(`i`)*-~`a`.count(`i`)for i in range(10))
u=lambda a:[`j`for j in range(2,a)if a%j<1>len(u(j))]
```
[Try it online!](https://tio.run/##TY0xDsIwDAB3XuEF1UZQkYyI8hFAsoEWErVOG5KBha8HdQHW0@lufKVHUFum5lR6GS43Adk984BVVfvgFDMKUX0NWROyY1pt3iz8B7oQwYFTiKL3Fs2WaJGbb@vInmfF/xS7FnIdyNLvzaFv54cnOpcxOk0wobGGygc "Python 2 – Try It Online")
# Credits
* Reduced from 136 bytes to 127 by [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder)
] |
[Question]
[
Your task is to program a mathematical function \$s\$, that takes a nonempty finite set \$A\$ of points in the 2D plane, and outputs an uncircularity score \$s(A)\$ that satisfies following properties:
1. *Positive Definiteness*: If there is a circle or a straight line that contains all points of \$A\$, then \$s(A) = 0\$. Otherwise \$s(A) > 0\$
2. *Surjectivity:* It is surjective to the nonnegative real numbers, that means for every nonnegative real number \$r\$ there is a finite subset \$A\$ of the plane such that \$s(A) = r\$.
3. *Translation Invariance:* \$s\$ is translation invariant if \$s(A) = s(A + v)\$ for every vector \$v\$ and for all \$A\$.
4. *Scale Invariance:* \$s\$ is scale invariant, if \$s(A) = s(tA)\$ for every \$t≠0\$ and for all \$A\$.
5. *Continuity.* \$s\$ is said to be *continuous* if the function \$f(p) := s(A ∪ \{p\})\$ (mapping the a point `p` to a real number) is continuous using the standard absolute value on the real numbers, and the standard euclidean norm on the points of the plane.
Intuitively speaking this *uncircularness score* can be thought of as something similar to the correlation coefficient in linear regression.
### Details
Your function in theory has to work in the reals, but for the purpose of this challenge you can use floating point numbers as substitute. Please provide an explanation of your submission and an argument why those five properties hold. You can take two lists of coordinates or a list of tuples or similar formats as input. You can assume that no point in the input is repeated i.e. all points are unique.
[Answer]
# Python 2 with numpy, 116 bytes
```
from numpy import*
def f(x,y):a=linalg.lstsq(hstack((x,y,ones_like(x))),(x*x+y*y)/2);return a[1]/sum((x-a[0][0])**4)
```
Takes x and y as 2d column vectors and returns an array containing the answer. Note that this will give an empty array for a perfectly straight line or with 3 or fewer points. I think lstsq gives no residuals if there's a perfect fit.
### Explanation
Essentially, this finds the circle of best fit and gets the squared residuals.
We want to minimize `(x - x_center)^2 + (y - y_center)^2 - R^2`. It looks nasty and nonlinear, but we can rewrite that as `x_center(-2x) + y_center(-2y) + stuff = x^2 + y^2`, where the `stuff` is still nasty and nonlinear in terms of `x_center`, `y_center`, and `R`, but we don't need to care about it. So we can just solve `[-2x -2y 1][x_center, y_center, stuff]^T = [x^2 + y^2]`.
We could then back out R if we really wanted, but that doesn't help us much here. Thankfully, the lstsq function can give us the residuals, which satisfies most of the conditions. Subtracting the center and scaling by `(R^2)^2 = R^4 ~ x^4` gives us translational and scale invariance.
1. This is positive definite because the squared residuals are nonnegative, and we're dividing by a square. It tends toward 0 for circles and lines because we're fitting a circle.
2. I'm fairly sure it's not surjective, but I can't get a good bound. If there is an upper bound, we can map [0, bound) to the nonnegative reals (for example, with 1 / (bound - answer) - 1 / bound) for a few more bytes.
3. We subtract out the center, so it's translationally invariant.
4. We divide by x\*\*4, which removes the scale dependence.
5. It's composed of continuous functions, so it's continuous.
[Answer]
# Python, 124 bytes
```
lambda A:sum(r.imag**2/2**abs(r)for a in A for b in A for c in A for d in A if a!=d!=b!=c for r in[(a-c)*(b-d)/(a-d)/(b-c)])
```
Takes *A* as a sequence of complex numbers (`x + 1j*y`), and sums Im(*r*)2/2|*r*| for all complex cross-ratios *r* of four points in *A*.
### Properties
1. *Positive Definiteness.* All terms are nonnegative, and they’re all zero exactly when all the cross-ratios are real, which happens when the points are collinear or concyclic.
2. *Surjectivity.* Since the sum can be made arbitrarily large by adding many points, surjectivity will follow from continuity.
3. *Translation Invariance.* The cross-ratio is translation-invariant.
4. *Scale Invariance.* The cross-ratio is scale-invariant. (In fact, it’s invariant under all Möbius transformations.)
5. *Continuity.* The cross-ratio is a continuous map to the extended complex plane, and *r* ↦ Im(*r*)2/2|*r*| (with ∞ ↦ 0) is a continuous map from the extended complex plane to the reals.
(Note: A theoretically prettier map with the same properties is *r* ↦ (Im(*r*)/(*C* + |*r*|2))2, whose contour lines w.r.t. all four points of the cross-ratio are circular. If you actually need an uncircularness measure, you probably want that one.)
] |
[Question]
[
A deck of cards is the Cartesian product of `S` suits and `R` ranks.
Many, though not all, card games use `S=4` and `R∊{6,8,13}`.
A hand of `H` cards is dealt from the deck.
Its *distribution*, a.k.a. "hand pattern", is an array that describes
how many cards you got from each suit, ignoring suit order (so, it's like a multi-set).
Given a distribution `D` satisfying `len(D)=S`, `1≤sum(D)=H≤S×R`, `0≤D[i]≤R`, `D[i]≥D[i+1]`,
find the probability of it occurring.
Input: an integer `R` and an array `D`.
Output: the probability with at least 5 digits after the decimal mark;
trailing zeroes may be skipped; scientific notation is ok.
Loopholes forbidden. Shortest wins.
Tests:
```
R D probability
13 4 4 3 2 -> 0.2155117564516334148528314355068773
13 5 3 3 2 -> 0.1551684646451760586940386335649517
13 9 3 1 0 -> 0.0001004716813294328274372174524508
13 13 0 0 0 -> 0.0000000000062990780897964308603403
8 3 2 2 1 -> 0.4007096203759162602321667950144035
8 4 2 1 1 -> 0.1431105787056843786543452839337155
8 2 2 1 0 -> 0.3737486095661846496106785317018910
8 3 1 1 0 -> 0.2135706340378197997775305895439377
15 4 4 3 2 1 -> 0.1428926269185580521441708109954798
10 3 0 0 -> 0.0886699507389162561576354679802956
10 2 1 0 -> 0.6650246305418719211822660098522167
10 1 1 1 -> 0.2463054187192118226600985221674877
```
See also [Bridge hand patterns in Wikipedia](https://en.wikipedia.org/wiki/Contract_bridge_probabilities#Hand_pattern_probabilities).
EDIT: dropped unnecessary restriction `H≤R`
EDIT: added constraint `H≥1`
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 30 chars
```
×/!⍨,z,1÷((z←!∘≢⊢)⌸⊢),×∘≢!⍨1⊥⊢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TD0/UVH/Wu0KnSMTy8XUOjCiik@KhjxqPORY@6Fmk@6tkBonQOT4eIgZQaPupaChT8/9/QWCFNwQQIjRWMuMAcUyATzrEEMg0VDCAcIGEAglwWQA5IDRAaQjgmICaMAxZHKDOEmGCKsAio0NAAyAWbB2FCdICZIPWGAA)
Using [@orlp’s formula](https://codegolf.stackexchange.com/a/148624/74681).
[Answer]
# Python 3, 134 bytes
```
b=lambda n,k:k<1or n*b(n-1,k-1)/k
f=lambda R,D,i=1,s=1,t=0:D and b(R,D[0])*i/s*f(R,D[1:],i+1,(D[0]in D[1:])*s+1,t+D[0])or 1/b(~-i*R,t)
```
Formula is the product of `binom(R, d)` for each element `d` in `D`, times `factorial(len(D))`, divided by the product of `factorial(len(S))` for each `S` in the groupings of `D` (e.g. `[4, 4, 3, 2]` has groupings `[[4, 4], [3], [2]]`), finally divided by `binom(len(D) * R, sum(D))`.
Or in math notation, assuming **m** contains the multiplicities of the **n** unique elements in **D**:
$$
\frac{|D|!}{m\_1!\cdot m\_2!\cdots m\_n!}
\binom{|D|\cdot R}{\sum D}^{-1}
\prod\_{d\in D}\binom{R}{d}
$$
[Answer]
# [R](https://www.r-project.org/), ~~90~~ ~~85~~ 83 bytes
```
function(R,D,l=sum(D|1),K=choose)prod(K(R,D),1:l,1/gamma(1+table(D)))/K(R*l,sum(D))
```
[Try it online!](https://tio.run/##JYs7DsIwEAV7n8LlvrAorNIgRDp36biBceKA5A@Kk467mwCaYorRLNXr61FXvyW3PnOiGxsOfdkimbeAh949ci4TXkseafhmsFwCSzvbGC3JYbX3MJEB0O69CfybgeqpOJsIrP@GOivVadk51Q8 "R – Try It Online")
I observed the same thing as [orlp](https://codegolf.stackexchange.com/a/148624/67312), but I picked a nice language that has combinatorics builtins.
Explanation:
```
function(R,D, # next are optional arguments
l=sum(D|1), # alias for length of D, aka S
K=choose) # alias for choose
prod( # take the product of:
K(R,D), # "choose" is vectorized over R and D
1:l, # S!
1/gamma(1+ # gamma(n+1) = n! for integer n
table(D)) # multiplicities of unique elements of D
) / # divide by
K(R`*`l, sum(D)) # R`*`S choose H
# return last computation (which is all the computation)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~22~~ 20 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-2 bytes using a new quick, `ʋ`, and a new monadic atom `Ẉ`
```
ĠẈ!;L×c⁸S¤ʋ
L!;c@֍P
```
A dyadic link, taking the dealt-distribution, D, on the left and the number-of-ranks, R, on the right, which returns the probability of occurrence.
**[Try it online!](https://tio.run/##y0rNyan8///Igoe7OhStfQ5PT37UuCP40JJT3Vw@itbJDoe3H14e8P//f2MdIyA0/G8BAA "Jelly – Try It Online")** or see the [test-suite](https://tio.run/##y0rNyan8///Igoe7OhStfQ5PT37UuCP40JJT3Vw@itbJDoe3H14e8P/onsPLHfQfNa05OunhzhlAGojc//@PjjY01lGIVjDRASEg0yg2VodLASpqChZCF7UECxnqKBggiYIIAwiCiCpYgNSC9IKRIbKoCUQITdQIJopugiGKbaao7oUbYmgAVY5wA0QIxVCIkCHM9lgA "Jelly – Try It Online")
### How?
```
ĠẈ!;L×c⁸S¤ʋ - Link 1, denomParts: list, distribution (D); number, ranks (R)
e.g. [3,3,3,2,2]; 8
Ġ - group indices of D by their values [[4,5],[1,2,3]]
Ẉ - length of each group [2,3]
! - factorial (vectorises) [2,6]
ʋ - last four links as a dyad
- ... i.e. totalWaysToDeal = f(list, distribution (D); number, ranks (R)):
L - length of D 5
× - multiply by R = total number of cards 40
¤ - nilad followed by link(s) as a nilad:
⁸ - chain's left argument, D [3,3,3,2,2]
S - sum = total cards dealt 13
c - binomial 40C13 = 12033222880
; - concatenate [2,6,12033222880]
L!;c@֍P - Main link: list, distribution (D); number, ranks (R)
- e.g. [3,3,3,2,2]; 8
L - length of D = number of suits 5
! - factorial 120
c@ - R binomial (vectorised across) D (8C3=56;8C2=28) [56,56,56,28,28]
; - concatenate [120,56,56,56,28,28]
ç - call the last link (1) as a dyad = denomParts(D,R) [2,6,12033222880]
÷ - divide (vectorises) [120/2,56/6,56/12033222880,56,28,28]
P - product 0.11441900924883391
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 21 bytes
```
cP¹g!*¹γ€g!P¹gI*¹Oc*/
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/OeDQznRFrUM7z21@1LQmXRHE9QRy/ZO19P//jzbVMQZCo1guQ2MA "05AB1E – Try It Online")
**Explanation**
```
P # product of
c # bin(input1,input2)
* # multiplied by
! # fac of
¹g # length of input1
/ # divided by
P # product of
! # fac of each
€g # length of each
¹γ # chunk of consecutive equal elements of input1
* # multiplied by
c # bin of
¹g # length of input1
I* # times input2
¹O # and sum of input1
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 32 bytes
```
cc*.!lQ*F.cLvzQ*F.!hMr8Q.c*vzlQs
```
**[Try it here!](https://pyth.herokuapp.com/?code=cc%2a.%21lQ%2aF.cLvzQ%2aF.%21hMr8Q.c%2avzlQs&input=%5B1%2C1%2C1%5D%0A10&test_suite_input=%5B4%2C+4%2C+3%2C+2%5D%0A13%0A%0A%5B5%2C+3%2C+3%2C+2%5D%0A13%0A%0A%5B9%2C+3%2C+1%2C+0%5D%0A13%0A%0A%5B13%2C+0%2C+0%2C+0%5D%0A13%0A%0A%5B3%2C+2%2C+2%2C+1%5D%0A8%0A%0A%5B4%2C+2%2C+1%2C+1%5D%0A8%0A%0A%5B2%2C+2%2C+1%2C+0%5D%0A8%0A%0A%5B3%2C+1%2C+1%2C+0%5D%0A8%0A%0A%5B4%2C+4%2C+3%2C+2%2C+1%5D%0A15%0A%0A%5B3%2C+0%2C+0%5D%0A10%0A%0A%5B2%2C+1%2C+0%5D%0A10%0A%0A%5B1%2C+1%2C+1%5D%0A10%0A&debug=0&input_size=3)** or **[Verify all the test cases!](https://pyth.herokuapp.com/?code=cc%2a.%21lQ%2aF.cLvzQ%2aF.%21hMr8Q.c%2avzlQs&input=%5B1%2C1%2C1%5D%0A10&test_suite=1&test_suite_input=%5B4%2C+4%2C+3%2C+2%5D%0A13%0A%0A%5B5%2C+3%2C+3%2C+2%5D%0A13%0A%0A%5B9%2C+3%2C+1%2C+0%5D%0A13%0A%0A%5B13%2C+0%2C+0%2C+0%5D%0A13%0A%0A%5B3%2C+2%2C+2%2C+1%5D%0A8%0A%0A%5B4%2C+2%2C+1%2C+1%5D%0A8%0A%0A%5B2%2C+2%2C+1%2C+0%5D%0A8%0A%0A%5B3%2C+1%2C+1%2C+0%5D%0A8%0A%0A%5B4%2C+4%2C+3%2C+2%2C+1%5D%0A15%0A%0A%5B3%2C+0%2C+0%5D%0A10%0A%0A%5B2%2C+1%2C+0%5D%0A10%0A%0A%5B1%2C+1%2C+1%5D%0A10%0A&debug=0&input_size=3)**
### How this works?
```
cc*.!lQ*F.cLvzQ*F.!hMr8Q.c*vzlQs ~ Full program. D = list, R = number.
.! ~ The factorial of...
lQ ~ The length of D.
* ~ Multiplied by...
*F ~ The product of the elements of...
.c ~ The nCr between...
L Q ~ Each element of D, and...
vz ~ R.
c ~ Divided by...
*F ~ The product of the elements of...
.! ~ The factorial of each...
hM ~ Heads. Count of adjacent elements in...
r8Q ~ The run length encoding of D.
c ~ Divided by...
.c ~ The nCr between...
* ~ The product of...
vz ~ R, and...
lQ ~ The length of D.
s ~ And the sum of D.
~ Output implicitly.
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 42 bytes
```
{×/(!≢⍵),(⍵!⍺),÷((+/⍵)!⍺×≢⍵),!≢¨⍵⊂⍨1,2≠/⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24Tqw9P1NRQfdS561LtVU0cDSCo@6t2lqXN4u4aGtj5IEMQ/PB2mAqT00Aog81FX06PeFYY6Ro86F4DU1f7/b2iskKZgAoTGCkZcYI4pkAnnWAKZhgoGEA6QMABBLgsgB6QGCA0hHBMQE8YBiyOUGUJMMEVYBFRoaADkgs2DMCE6wEyQekMA "APL (Dyalog Unicode) – Try It Online")
Still golfing.
[Answer]
## Clojure, 153 bytes
```
#(apply +(for[_(range 1e06):when(=(remove #{0}%)(reverse(sort(vals(frequencies(take(apply + %)(shuffle(for[i(range %2)j(range(count %))]j))))))))]1e-06))
```
Just a brute-force simulation, to get more precision increase the iteration count and the "1 / N" value at the end accordingly. First argument is the counts and 2nd argument is the number of cards in the deck per suite.
[Answer]
# J, 57 bytes
```
](#@]%~[:+/[-:"1[:\:~@(#/.~)"1+/@[{."1])i.@!@(*+/)A.(##\)
```
[Try it online!](https://tio.run/##Rc29DsIgGIXhnas4Qkz5RPmx25c0weugTEaiXRw6Grl1Sqfm5B2e6SytrJgYHr2WtYr5XBMbl24sQ@KZa9TK2UoyGBfTz8qQ6WPjKeqLcfSwWqmZGglpMZSJB1zxZ5RViNfz/cWIgrDv4L3THxz7uUfbAA "J – Try It Online")
This runs in *O(golf)* and will choke on many of the test cases (though works theoretically), which would be fine if it were golfier. But I'm stuck on trimming it down, especially with avoiding those repeated `"1`. If anyone wants to help, here's the parsed version...
The right side of the main fork is all possible deals of the *deck*, and the left side of the main fork is just the original right arg, ie, the suit mask we're matching against.
Inside, from each "shuffled" deck, we take the first *hand* elements, then group them using key `/.` and sort the result, and check if that matches the suit mask in question. We add add up the total number that do match, and divide that into the length of all possible decks.
```
┌─┬─────────────────────────────────────────────────────────────────────────────────────────────────┬─────────────────────────────────────┐
│]│┌───────┬─────┬─────────────────────────────────────────────────────────────────────────────────┐│┌──────────────────────┬──┬─────────┐│
│ ││┌─┬─┬─┐│┌─┬─┐│┌──┬─────┬──────────────────────────────────────────────────────────────────────┐│││┌────────┬─┬─────────┐│A.│┌─┬─────┐││
│ │││#│@│]│││%│~│││[:│┌─┬─┐│┌─┬────────┬─────────────────────────────────────────────────────────┐│││││┌──┬─┬─┐│@│┌─┬─────┐││ ││#│┌─┬─┐│││
│ ││└─┴─┴─┘│└─┴─┘││ ││+│/│││[│┌──┬─┬─┐│┌──┬───────────────────────────┬────────────────────────┐│││││││i.│@│!││ ││*│┌─┬─┐│││ ││ ││#│\││││
│ ││ │ ││ │└─┴─┘││ ││-:│"│1│││[:│┌─────────────────────┬─┬─┐│┌───────────┬────────┬─┐│││││││└──┴─┴─┘│ ││ ││+│/││││ ││ │└─┴─┘│││
│ ││ │ ││ │ ││ │└──┴─┴─┘││ ││┌──────┬─┬──────────┐│"│1│││┌─────┬─┬─┐│┌──┬─┬─┐│]││││││││ │ ││ │└─┴─┘│││ │└─┴─────┘││
│ ││ │ ││ │ ││ │ ││ │││┌──┬─┐│@│┌──────┬─┐││ │ ││││┌─┬─┐│@│[│││{.│"│1││ ││││││││ │ │└─┴─────┘││ │ ││
│ ││ │ ││ │ ││ │ ││ ││││\:│~││ ││┌─┬──┐│~│││ │ │││││+│/││ │ ││└──┴─┴─┘│ │││││││└────────┴─┴─────────┘│ │ ││
│ ││ │ ││ │ ││ │ ││ │││└──┴─┘│ │││#│/.││ │││ │ ││││└─┴─┘│ │ ││ │ ││││││└──────────────────────┴──┴─────────┘│
│ ││ │ ││ │ ││ │ ││ │││ │ ││└─┴──┘│ │││ │ │││└─────┴─┴─┘│ │ ││││││ │
│ ││ │ ││ │ ││ │ ││ │││ │ │└──────┴─┘││ │ ││└───────────┴────────┴─┘│││││ │
│ ││ │ ││ │ ││ │ ││ ││└──────┴─┴──────────┘│ │ ││ │││││ │
│ ││ │ ││ │ ││ │ ││ │└─────────────────────┴─┴─┘│ │││││ │
│ ││ │ ││ │ ││ │ │└──┴───────────────────────────┴────────────────────────┘││││ │
│ ││ │ ││ │ │└─┴────────┴─────────────────────────────────────────────────────────┘│││ │
│ ││ │ │└──┴─────┴──────────────────────────────────────────────────────────────────────┘││ │
│ │└───────┴─────┴─────────────────────────────────────────────────────────────────────────────────┘│ │
└─┴─────────────────────────────────────────────────────────────────────────────────────────────────┴─────────────────────────────────────┘
```
] |
[Question]
[
There are several ways to create headers on posts on the Stack Exchange network. The format that's most commonly1 used on PPCG seems to be:
```
# Level one header
## Level two header
### Level three header
```
Note the space after the hash marks. Also, note that trailing hash marks are not included.
## Challenge:
Take a (possibly multiline) string as input, and output the string on the following format:
* If the header is level 1, then output each letter 4-by-4 times
* If the header is level 2, then output each letter 3-by-3 times
* If the header is level 3, then output each letter 2-by-2 times
* If a line is not a header then output it as it is.
To illustrate:
```
--- Level 1 ---
# Hello
--- Output---
HHHHeeeelllllllloooo
HHHHeeeelllllllloooo
HHHHeeeelllllllloooo
HHHHeeeelllllllloooo
--- Level 2 ---
## A B C def
--- Output ---
AAA BBB CCC dddeeefff
AAA BBB CCC dddeeefff
AAA BBB CCC dddeeefff
--- Level 3 ---
### PPCG!
--- Output---
PPPPCCGG!!
PPPPCCGG!!
```
Simple as that!
---
### Rules:
* You must support input over multiple lines. Using `\n` etc. for newlines is OK.
+ There won't be lines containing only a `#` followed by a single space
* The output must be presented over multiple lines. You may not output `\n` instead of literal newlines.
+ Trailing spaces and newlines are OK.
---
### Test cases:
Input and output are separated by a line of `...`.
```
# This is a text
with two different
### headers!
........................................................
TTTThhhhiiiissss iiiissss aaaa tttteeeexxxxtttt
TTTThhhhiiiissss iiiissss aaaa tttteeeexxxxtttt
TTTThhhhiiiissss iiiissss aaaa tttteeeexxxxtttt
TTTThhhhiiiissss iiiissss aaaa tttteeeexxxxtttt
with two different
hheeaaddeerrss!!
hheeaaddeerrss!!
```
---
```
This input has
## trailing hash marks ##
#and a hash mark without a space after it.
........................................................
This input has
tttrrraaaiiillliiinnnggg hhhaaassshhh mmmaaarrrkkksss ######
tttrrraaaiiillliiinnnggg hhhaaassshhh mmmaaarrrkkksss ######
tttrrraaaiiillliiinnnggg hhhaaassshhh mmmaaarrrkkksss ######
#and hash marks without a space after it.
```
---
```
# This ## is ### strange
#### ###
........................................................
TTTThhhhiiiissss ######## iiiissss ############ ssssttttrrrraaaannnnggggeeee
TTTThhhhiiiissss ######## iiiissss ############ ssssttttrrrraaaannnnggggeeee
TTTThhhhiiiissss ######## iiiissss ############ ssssttttrrrraaaannnnggggeeee
TTTThhhhiiiissss ######## iiiissss ############ ssssttttrrrraaaannnnggggeeee
#### ###
```
---
```
Multiple
### newlines! #
:)
........................................................
Multiple
nneewwlliinneess!! ##
nneewwlliinneess!! ##
:)
```
---
```
Line with only a hash mark:
#
### ^ Like that!
........................................................
Line with only a hash mark:
#
^^ LLiikkee tthhaatt!!
^^ LLiikkee tthhaatt!!
```
1: I haven't really checked, but I *think* it's true.
[Answer]
# [Stacked](https://github.com/ConorOBrien-Foxx/stacked), ~~51~~ 50 bytes
*Saved 1 byte thanks to @RickHitchcock - golfed regex*
```
['^(##?#?) (.+)'[\#'5\-@k CS k*k rep LF#`]3/mrepl]
```
[Try it online!](https://tio.run/##TU9BasMwELzrFUN1UNKmMaXtISUkIYaeAj70GCdUduRa2JKMJDv49e4m9FAEM6tlZnc2RFk26jJNR3Gecb7l2zlmy6e5OOZcvOfPuwbpF5rHBl51OHzy79NrYqhuT9Puo2KCI3Wm86pWNuhBgSOqEFHKoALjHPuRBNZ5ZELsvVaWmhyz0nWj1z91xMtq9YZ9Omc8FjW4V7Jl/P5ireBIpC1chduvat1VeSjjoi6dxZpDB/S2se5qFyj6CCPtSFptG@iIi/IUKlAZ0N29lXfmPkvaktJEFkZTuPa2wUjqE2gKj4dY91E@LCAxSK@ljX8hoiSUdCGdLT3Ntr0plA9Ldjs3@5eX/OCc6ShEQKPtRZLJtaTDerPeEJ2H80CUZtmBKMmTnIgwYQIVXB@nXw "Stacked – Try It Online")
Anonymous function that takes input from the stack and leaves it on the stack.
## Explanation
```
['^(##?#?) (.+)'[\#'5\-@k CS k*k rep LF#`]3/mrepl]
[ mrepl] perform multiline replacement
'^(##?#?) (.+)' regex matching headers
[ ]3/ on each match:
\#' count number of hashes
5\- 5 - (^)
@k set k to number of repetitions
CS convert the header to a char string
k* repeat each char `k` times
k rep repeat said string `k` times
LF#` join by linefeeds
```
[Answer]
# JavaScript (ES6), ~~111~~ 105 bytes
*Saved 6 bytes thanks to @Shaggy*
```
s=>s.replace(/^(##?#?) (.+)/gm,(_,a,b)=>`
${b.replace(/./g,e=>e.repeat(l=5-a.length))}`.repeat(l).trim())
```
Matches 1-3 hashes at the beginning of the string or preceded by a new line, then repeats each character in the match along with the match itself, based on the length of the hashes.
**Test Cases:**
```
let f=
s=>s.replace(/^(##?#?) (.+)/gm,(_,a,b)=>`
${b.replace(/./g,e=>e.repeat(l=5-a.length))}`.repeat(l).trim())
console.log(f('# This is a text\nwith two different\n### headers!'));
console.log('______________________________________________');
console.log(f('This input has\n## trailing hash marks ##\n#and a hash mark without a space after it.'));
console.log('______________________________________________');
console.log(f('# This ## is ### strange\n#### ###'));
console.log('______________________________________________');
console.log(f('Multiple\n\n\n### newlines! # \n:)'));
console.log('______________________________________________');
console.log(f('Line with only a hash mark:\n#\n### ^ Like that!'));
```
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~125~~ 104 bytes
```
m(`(?<=^# .*).
$0$0$0$0
(?<=^## .*).
$0$0$0
(?<=^### .*).
$0$0
^#
$%'¶$%'¶$%'¶
^##
$%'¶$%'¶
^###
$%'¶
```
[**Try it online**](https://tio.run/##VY9BTsMwEEX3c4ofuYiWRcS6AvUCZce6YkQmtdXUieypChfjAFwsjBMKrWyN9J/n/xkn0RB5HI/Lt@Xm6XnnUD@salo8zodmeEMv7AqS@Whxd//99V@o2OhWX8A4Orz6kGGXofKhdA7qoeceTWhbSRKVSr8XbiTliub2OJwUnrO9QROHLsR90R5HTocM58hxbCz0D6Ik92Zj5IHfBdyqJASt6XcJy5qqQ7bMuJcy2RVAL6dOw9AJ0bRNlLNNlFzBfrJe0dbElI8@dp/XU9fkJscO23AQqGetfgA)
*Saved 21 bytes thanks to Neil.*
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~43~~ ~~42~~ 40 bytes
*1 byte removed thanks to [Rick Hitchcock](https://codegolf.stackexchange.com/users/42260/rick-hitchcock)!*
```
`j[]y'^##?#? 'XXgn:(2M4:QP&mt~+t&Y"0YcDT
```
This outputs a trailing space in each line (allowed by the challenge), and exits with an error (allowed by default) after producing the ouput.
[**Try it online!**](https://tio.run/##jY/BSsNAEIbv@xR/OtBahCLiKZdeemxBoYcWsTg0k@zaZBOyU2IvvnrcRBGPGZaBHZjvn69iLfv@/eP17bY4Ea1pjcXhUPj07nH3lL48zyv9utf5cfZwPG/2fU/YWxcQH0PlU03n1EK7GpnLc2nFqyEiWOFM2pCY1YQyP0zfXBWWQwRAW3al88Xwt6i4vQQQGWKfxeS/IYb4Oq4xQsNnAecqLZyupgX/6sTAsRNCDPaFDA40DKZhdtdSXVOKMaO8ly7eLiEBwaTLaYxt3Bh1UPvy9l8yNTRiT9i6i0Ata/IN)
### Explanation
```
` % Do...while loop
j % Input a line as unevaluated string
[] % Push empty array
y % Duplicate from below: push input line again
'^##?#? ' % Push string for regexp pattern
XX % Regexp. Returns cell array with the matched substrings
g % Get cell array contents: a string, possibly empty
n % Length, say k. This is the title level plus 1, or 0 if no title
:( % Assign the empty array to the first k entries in the input line
% This removing those entries from the input
2M % Push k again
4:QP % [1 2 3 4], add 1 , flip: pushes [5 4 3 2]
&m % Push index of k in that array, or 0 if not present. This gives
% 4 for k=2 (title level 1), 3 for k=3 (tile level 2), 2 for k=2
% (title level 1), and 0 for k=0 (no title). The entry 5 in the
% array is only used as placeholder to get the desired result.
t~+ % Duplicate, negate, add. This transforms 0 into 1
t&Y" % Repeat each character that many times in the two dimensions
0Yc % Postpend a column of char 0 (displayed as space). This is
% needed in case the input line was empty, as MATL doesn't
% display empty lines
D % Display now. This is needed because the program will end with
% an error, and so implicit display won't apply
T % True. This is used as loop condition, to make the loop infinite
% End (implicit)
```
[Answer]
# Perl 5, 47 +1 (-p) bytes
```
s/^##?#? //;$.=6-("@+"||5);$_=s/./$&x$./ger x$.
```
[try it online](https://tio.run/##K0gtyjH9/79YP05Z2V7ZXkFf31pFz9ZMV0PJQVuppsZU01ol3rZYX09fRa1CRU8/PbVIAUj//6@sEJKRWaygrKwAJpUVikuKEvPSU7mUQRwg5vqXX1CSmZ9X/F@3AAA)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 46 bytes
```
FN«Sι≔⊕⌕E³…⁺×#κι⁴### θF⎇θ✂ι⁻⁵θLι¹ι«G↓→↑⊕θκ→»D⎚
```
[Try it online!](https://tio.run/##TY/BTsMwDIbP7VOY9uJK4YAGl3FCTEhIFE2sPEBo3cZamnRpujKhPXtJygUpsf9Yv77fqZV0tZV6WVrrAF/NMPn3qf8ih0UBP2myTg7esemQi8c0eRpH7kxw1o56Mp4afGHTYCkH3AgorW5wr6cRK@5pxCzPBBwLARzufRFKluc5ZFGdIm/NrcgZ6S54EnDQXBNyILEJlIdoE/BGpvMKI@Ruha3LJXurL501uN3Z2QjYfnCnfOifg4D/G0bEMaYlpT0T/vni@5omu6kfMOpnTdJFdV2WTZpDpXiEcCR4@vbpzF6Bny003LbkAjiNP1EkG3LjzXJ71r8 "Charcoal – Try It Online") Link is to verbose version of code. Charcoal doesn't really do string array input, so I've had to add the array length as an input. Explanation:
```
FN«Sι
```
Loop over the appropriate number of input strings.
```
≔⊕⌕E³…⁺×#κι⁴### θ
```
Create an array of strings by taking the input and prefixing up to 2 #s, then truncating to length 4, then try to find `###` in the array, then convert to 1-indexing. This results in a number which is one less than the letter zoom.
```
F⎇θ✂ι⁻⁵θLι¹ι«
```
If the letter zoom is 1 then loop over the entire string otherwise loop over the appropriate suffix (which is unreasonably hard to extract in Charcoal).
```
G↓→↑⊕θκ→
```
Draw a polygon filled with the letter ending at the top right corner, and then move right ready for the next letter.
```
»D⎚
```
Print the output and reset ready for the next input string.
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), ~~31~~ 28 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
¶Θ{■^##?#? øβlF⁄κ6κ5%:GI*∑∙P
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JUI2JXUwMzk4JTdCJXUyNUEwJTVFJTIzJTIzJTNGJTIzJTNGJTIwJUY4JXUwM0IybEYldTIwNDQldTAzQkE2JXUwM0JBNSUyNSUzQUdJKiV1MjIxMSV1MjIxOVBGJTBBaW5wdXRzLnZhbHVlJXUyMDFEJXUyMTkyRg__,inputs=TXVsdGlwbGUlMEElMEElMEElMjMlMjMlMjMlMjBuZXdsaW5lcyUyMSUyMCUyMyUyMCUwQSUzQSUyOSUwQSUwQSUyMyUyMFRoaXMlMjBpcyUyMGElMjB0ZXh0JTBBd2l0aCUyMHR3byUyMGRpZmZlcmVudCUwQSUyMyUyMyUyMyUyMGhlYWRlcnMlMjElMEElMjMlMjBzaXplJTIwNCUwQSUyMyUyMyUyMHNpemUlMjAzJTBBJTIzJTIzJTIzJTIwc2l6ZSUyMDIlMEFzaXplJTIwMQ__) - extra code added because the code is a function and takes input on stack (SOGL can't take multiline input otherwise :/) - `inputs.value”` - push that string, `→` - evaluate as JS, `F` - call that function
Explanation:
```
¶Θ split on newlines
{ for each item
■^##?#? push "^##?#? "
øβ replace that as regex with nothing
l get the new strings length
F⁄ get the original strings length
κ and subtract from the original length the new strings length
6κ from 6 subtract that
5% and modulo that by 5 - `6κ5%` together transforms 0;2;3;4 - the match length to 1;4;3;2 - the size
: duplicate that number
G and get the modified string ontop
I rotate it clockwise - e.g. "hello" -> [["h"],["e"],["l"],["l"],["o"]]
* multiply horizontally by one copy of the size numbers - e.g. 2: [["hh"],["ee"],["ll"],["ll"],["oo"]]
∑ join that array together - "hheelllloo"
∙ and multiply vertiaclly by the other copy of the size number: ["hheelllloo","hheelllloo"]
P print, implicitly joining by newlines
```
[Answer]
# [Proton](https://github.com/alexander-liao/proton), 130 bytes
```
x=>for l:x.split("\n"){L=l.find(" ")print(L>3or L+len(l.lstrip("\#"))-len(l)?l:"\n".join(["".join(c*(5-L)for c:l[L+1to])]*(5-L)))}
```
[Try it online!](https://tio.run/##LU1LCsMgFNznFPKyea8hgpRuAkku4A1SV2kFy0PFuAiUnt2apgMDwzCfmEIOvtix7ONkQxI87HKL7DLC3QO99cjSOv9AEEAxOZ9RT9ca1B0/PbLkLScXa7oFov7n0czD0Zav4Dwu8BfrBW@9puNlHXjRncrBkDldok855y1C01aIygYWJXIQvTJE5Qs "Proton – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 147 bytes
```
def f(x):
for l in x.split("\n"):L=l.find(" ");print(L>3or L+len(l.lstrip("#"))-len(l)and l or"\n".join(["".join(c*(5-L)for c in l[L+1:])]*(5-L)))
```
[Try it online!](https://tio.run/##NY27CsIwFIZn8xTxZDnH0kARl4o6CQ5B3WsHsQlGDkmJHerT19bL9vHxX9pXd49hOQyNddJhT6WYuZgkSx9kr58t@w7hEoBKs2HtfGgQJNC6TT50aLbLMWwytgFZ87NLvkVQQJR/FF1DM27FNE3oR/QBK/jBbYGr3ND0dpveuDJZUdZUfz3R4BAAxMEyR6HkwV4bm@ZCKXn/4G7EP2uthTqeznsxVqqizIuahjc "Python 3 – Try It Online")
-1 byte thanks to Mr. Xcoder
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 268 + 18 bytes
```
n=>{var r="";for(int l=0,c;l<n.Length;l++){var m=n[l];var s=m.Split(' ');var y=s[0];if(!y.All(x=>x==35)|y.Length>3|s.Length<2)r+=m+'\n';else for(int i=0,k=y.Length;i<5-k;i++){for(c=1;c<m.Length-k;)r+=new string(m.Substring(k,m.Length-k)[c++],5-k);r+='\n';}}return r;};
```
[Try it online!](https://tio.run/##lVLBbqMwED2Xr5jCISAo6m7VyxpHqirtKSut1JX2kKaS1zFgYUzWHpqglG9PDYG210jIGr2Zee/NE9ze8MaIU2ulLuCpsyjqdCX1f@JxxayF36YpDKvh6F1ZZCg5vDZyC7@Y1KFF47bWG2CmsJEb8SaCn63m2dxN4FwtIQd60nR5fGUGDPV9kjcmlBpB0duEE5XpdCV0gSVRcRyNYzXVa7UhQ2lpnT7tlMRwAYtohDpq17cbIvPwuksflAoPdHmg9O4@eusmquXdm53K7HtkYlrHi2e9IEJZAbO@dPoVnVeIzO5vKiIHD8MEp98Iz@qp6zoDjRb76a7Q2Wr/TXWVfM5Fax7Hm8RxRcRtjLJ9bwS2RoMhPTmRObDHRttGifSvkShc/CLMw08Fl/AR/AD@lNKC@xigOKCfgL@XWALuG9jKPBdG6BENggBKwbbC2Gsf@ii6SOesonctQsnsmQ/QMKmGX8RBJdTMVBaCYGwyvXWOPnAYPDVumYHdMS6A5SgMSEwvtzKd7PTHNxiaTBdiOjIYsMtZB3h0CY1W3VfvP0biOcIXWMlKAJYM5xi9q97rT@8 "C# (.NET Core) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 131 bytes
```
from re import*
print(sub("^(#+) (.*?)$",lambda x:((sub('(.)',r'\1'*(5-len(x[1])),x[2])+'\n')*(5-len(x[1])))[:-1],input(),flags=M))
```
[Try it online!](https://tio.run/##VY9Bi4MwFITv/opHUsh7mgrusheh9Bf01pt14XWrNVRjSCK1v9667WHZ43zDDDPuEbvRfi7GuinCDnoezhcuQQhx7EyAN@84JFJC9Gx6Y6@/uoOB/S2AlIlkewH@g3A3a@kaYwiOfxrgNjYeTMzX1qX14wC@ATO40cc0cd7YiGE6o/hGmRFgnu5pI/R7CswlvlyFOSnt1alQKX5t@8biXBU1kZ6rj5oydbKK/jtUldui1q8PSLrt@Rp2B6JleQI "Python 3 – Try It Online")
I used Python 3 in order to use `[]` with regex.
[Answer]
# PHP, 122+1 bytes
```
for($y=$z=" "==$s[$i=strspn($s=$argn,"#")]&&$i?5-$i++:1+$i=0;$y--;print"
")for($k=$i;~$c=$s[$k++];)echo str_pad($c,$z,$c);
```
Run as pipe with `-nR` (will work on one input line after another) or [try it online](http://sandbox.onlinephpfunctions.com/code/07226b470ecae8bbdbd1dde71cf416af5e858c2b).
[Answer]
# [J](http://jsoftware.com/), 55 bytes
```
([:{:@,'^##?#? 'rxmatch])((1 1 4 3 2{~[)([:|:[$"0#)}.)]
```
I don't know how to make TIO work with J regex, so I can't provide a working link.
Here's how to test it in the J interpreter (tested with J804)
```
f=.([:{:@,'^##?#? 'rxmatch])((1 1 4 3 2{~[)([:|:[$"0#)}.)]
txt=.'# Hello'; '## A B C def'; '### PPCG!'; '#and a hash mark without a space after it.'; '##### ###'
; f each txt
HHHHeeeelllllllloooo
HHHHeeeelllllllloooo
HHHHeeeelllllllloooo
HHHHeeeelllllllloooo
AAA BBB CCC dddeeefff
AAA BBB CCC dddeeefff
AAA BBB CCC dddeeefff
PPPPCCGG!!
PPPPCCGG!!
#and a hash mark without a space after it.
##### ###
```
I simulate a multiline string through a list of boxed strings.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~126~~ ~~124~~ 117 bytes
```
while 1:l=raw_input();i=l.find(' ');v=5-i*(l[:i]in'###');exec"print[l,''.join(c*v for c in l[i+1:])][v<5];"*(v>4or v)
```
[Try it online!](https://tio.run/##TY7BTsMwDIbvfgpvObQdMGmIXVrGE4wbt6qgqHUXs5BWidduT1/SghCSZcm/7f/7@5uYzj1O02jYEu5ye/B6/GDXXyTNCj7YbcuuSRNMsmI47B94k9oy54pdopSKIl2pXveenZT2Pkm2nx27tN4M2HYea2SHtuS7XV5lVTk876tivUmHl6e4HLJpUvhmOGAsjUJXgZHFoIwdNty25MkJRA4a0g35sAL4uZ/zodEhLlG8ZsvuNM8Gv7Q/B1QKlHZNdP0Tcbbu4pvG0OuaULdCHlm2AL8xotnSFYZo6k40s9UsALxerHBvCWAJ5GiMTAorVAh5BnCM04LAztnbf3AOanl5xyOfCcVoWX0D "Python 2 – Try It Online")
or
```
while 1:l=raw_input();i=l.find(' ');t=''<l[:i]in'###';exec"print[l,''.join(c*(5-i)for c in l[i+1:])][t];"*(t<1or 5-i)
```
[Try it online!](https://tio.run/##TY7BasMwDIbvegq1PjjptkIHuyTNG3S33UI2TKLUWj0n2Cppnz5zsjEGQqBf0v/9413s4J/nebLsCA@Fq4KZPtiPV8nykiu379l3mUadl1JpfXR1wQ17rZTSJd2o3Y6BvdTuUev958A@a3fZyxPn/RCwRfboan44FE3e1NKU210mx0NaLSfzrPDNcsRUBoVuAhOLRZkG7LjvKZAXSCS0ZDoKcQPwc7/kQ2tiWqIEw479eZktfplwiagUKOO75Pon4mI9pDeDcTQtoemFArLsAX5jJLO1K4zJ1J9pYatFAHi9OuHREcAayNOUmBQ3qBCKHOCUphWBg3f3/@AC1Pryjie@EIo1svkG "Python 2 – Try It Online")
[Answer]
# JavaScript, 112 bytes
```
x=>x.replace(/^(##?#?) (.*)/mg,(_,n,w)=>(t=>Array(t).fill(w.replace(/./g,c=>c.repeat(t))).join`
`)(5-n.length))
```
```
f=
x=>x.replace(/^(##?#?) (.*)/mg,(_,n,w)=>(t=>Array(t).fill(w.replace(/./g,c=>c.repeat(t))).join`
`)(5-n.length))
```
```
<textarea id=i style=display:block oninput=o.value=f(i.value)></textarea>
<output id=o style=display:block;white-space:pre></output>
```
[Answer]
# C# 4.5 158 Bytes
Where i is the input in the form of a string.
```
int l,m,t,s=0;while(i[s]=='#'){s++;};t=s>0?4-s+1:1;for(l=0;l<t;l++){foreach(char c in i.Skip(s>0?s+1:0))for(m=0;m<t;m++)Console.Write(c);Console.WriteLine();}
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 27 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
é!?q╚<╙≈╣íå▒{¼Φ8ôƒ¡m↨;-◘-u♥
```
[Run and debug it](https://staxlang.xyz/#p=82213f71c83cd3f7b9a186b17bace838939fad6d173b2d082d7503&i=This+input+has%0A%23%23+trailing+hash+marks+%23%23%0A%23and+a+hash+mark+without+a+space+after+it.%0A)
This was fun.
] |
[Question]
[
This challenge is similar [to my previous one](https://codegolf.stackexchange.com/questions/144053/distances-to-coordinates), but has a twist that makes it significantly more difficult.
There are *n* people on a 2D plane. Using distances between them we're going to find their positions. You may 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.
However, **all distances are floored to integers**! For example, if the actual distance between two people is 4.7 units, your program will see the distance 4 as input instead.
So your challenge is to write a program or function that given a 2D array of **floored** distances (where `D[i][j]` gives the distance between person `i` and `j`) returns a list of their coordinates.
The challenge here is that you have incomplete information, and must try to extract as much precision as possible. Therefore this challenge is not a code golf, instead it's a code challenge, and the winner is the answer that returns the most accurate results.
---
# Scoring
I will provide a series of arrays of coordinates. It is up to you to turn these arrays into 2D distance matrices **and flooring each element in these matrices** (if I were to do that here this question would get way too large).
For a certain input use your answer to predict the coordinates of each person. Then, for each person calculate the squared distance between the prediction and actual position. Sum all these and divide by the number of people in the input. That is your score for this input.
The total score of your answer is the average score you get for all of the following inputs:
```
[(0, 0), (0.046884, 0), (-4.063964, 0.922728), (-3.44831, -6.726776), (-0.284375, -0.971985)]
[(0, 0), (0.357352, 0), (-1.109721, 1.796241), (-7.894467, -3.086608), (-3.74066, -1.528463)]
[(0, 0), (6.817717, 0), (-6.465707, 0.705209), (-2.120166, 3.220972), (-2.510131, 8.401557)]
[(0, 0), (0.394603, 0), (-4.097489, 0.957254), (-5.992811, 1.485941), (-2.724543, -3.925886)]
[(0, 0), (6.686748, 0), (6.088099, 0.22948), (8.211626, -4.577765), (-1.98268, -4.764555)]
[(0, 0), (2.054625, 0), (0.75308, 0.497376), (6.987932, -5.184446), (0.727676, -5.065224)]
[(0, 0), (6.283741, 0), (-1.70798, 5.929428), (2.520053, 6.841456), (-2.694771, -1.816297)]
[(0, 0), (1.458847, 0), (5.565238, 7.756939), (-4.500271, 4.443), (-0.906575, 3.654772)]
[(0, 0), (0.638051, 0), (-2.37332, 0.436265), (-8.169133, -0.758258), (-7.202891, -2.804207)]
[(0, 0), (1.101044, 0), (-1.575317, 6.717197), (-2.411958, -7.856072), (-4.395595, 2.884473)]
[(0, 0), (7.87312, 0), (-0.320791, 2.746919), (-1.4003, 0.709397), (-0.530837, -0.220055), (-3.492505, -7.278485), (2.401834, 2.493873), (0.911075, -5.916763), (4.086665, -5.915226), (2.801287, 5.409761)]
[(0, 0), (0.304707, 0), (-1.709252, 0.767977), (-0.00985, -0.356194), (-2.119593, 3.353015), (1.283703, 9.272182), (6.239, -0.455217), (7.462604, 1.819545), (0.080977, -0.026535), (-0.282707, 6.55089)]
[(0, 0), (3.767785, 0), (0.133478, 0.19855), (-0.185253, -5.208567), (-6.03274, 6.938198), (5.142727, -1.586088), (0.384785, 0.532957), (3.479238, -1.472018), (3.569602, 8.153945), (-0.172081, 2.282675)]
[(0, 0), (0.445479, 0), (-3.3118, 8.585734), (0.071695, -0.079365), (2.418543, 6.537769), (1.953448, 0.511852), (-1.662483, -5.669063), (0.01342, 0.097704), (0.919935, 1.697316), (2.740839, -0.041325)]
[(0, 0), (3.281082, 0), (-6.796642, 5.883912), (-3.579981, -2.851333), (-1.478553, 6.720389), (3.434607, -9.042404), (7.107112, 2.763575), (-4.571583, 1.100622), (-1.629668, 1.235487), (-3.199134, 0.813572)]
[(0, 0), (5.278497, 0), (-4.995894, 3.517335), (-0.012135, 3.444023), (0.364605, -0.49414), (1.73539, 1.265443), (-7.289383, -3.305504), (-7.921606, 5.089785), (-1.002743, -0.554163), (-8.99757, -3.572637)]
[(0, 0), (2.331494, 0), (1.83036, 2.947165), (-5.520626, 1.519332), (5.021139, -4.880601), (-0.318216, -0.063634), (-5.204892, -5.395327), (-0.92475, -0.090911), (-0.19149, -2.188813), (-0.035878, 0.614552)]
[(0, 0), (2.981835, 0), (-3.909667, 2.656816), (-0.261224, -2.507234), (-7.35511, -3.65201), (1.198829, 5.328221), (-5.139482, -4.320811), (-3.253523, 2.367497), (6.254513, 1.565134), (3.13451, 4.595651)]
[(0, 0), (1.059838, 0), (-0.849461, 7.87286), (2.108681, 0.717389), (-0.065587, -0.007163), (2.818824, 5.529878), (2.413443, 4.102863), (-3.050506, -2.541446), (-1.215169, -4.818011), (-1.671743, 2.539397)]
[(0, 0), (5.036602, 0), (-1.627921, 1.813918), (-9.285855, 1.277063), (2.271804, -0.51118), (-7.070704, 2.252381), (6.125956, -4.278879), (1.000949, -1.38177), (-0.67657, -2.747887), (2.820677, -5.718695)]
[(0, 0), (0.733516, 0), (6.619559, 1.368964), (-0.047351, 0.545139), (-4.518243, -7.506885), (3.31011, -4.329671), (3.885474, -1.535834), (-3.952488, -1.94899), (1.402441, 7.538954), (2.385809, 4.042365), (-6.403547, 3.623895), (3.742502, 0.025475), (1.944868, -2.972475), (-0.514566, -1.015531), (-0.08634, 5.140751)]
[(0, 0), (2.374024, 0), (-1.016305, 1.31073), (2.176473, -1.357629), (0.181825, 2.107476), (-0.978214, -3.436398), (0.828254, -0.39516), (2.981311, -6.761157), (1.517599, 5.009197), (8.063442, 0.930487), (4.628231, 7.749696), (3.810604, 4.671208), (1.158015, 2.914197), (-9.230353, -0.473591), (-9.031469, -4.206725)]
[(0, 0), (5.733822, 0), (1.394054, 1.432354), (1.556614, 5.691443), (3.665168, 7.199478), (-0.670337, 0.396217), (4.144468, 2.959243), (-6.129783, -7.048069), (-3.230162, 3.116924), (-6.365913, 3.727042), (-0.174385, 0.253418), (-0.454495, -4.415929), (5.815488, 1.443031), (-4.288448, 0.619174), (1.957015, 0.784202)]
[(0, 0), (6.550779, 0), (-8.592692, 1.728506), (-6.460692, 2.344509), (8.359129, 4.578714), (3.593451, -4.172634), (8.697976, -2.379752), (4.27242, 5.296418), (2.920394, -4.520174), (0.662004, 2.171769), (1.879771, -1.873537), (0.769374, 3.570321), (-3.438699, -3.255416), (3.23342, -3.220256), (-0.002136, -5.646753)]
[(0, 0), (5.013665, 0), (-0.543516, 9.981648), (8.378266, 5.33164), (4.759961, -2.007708), (2.88554, 1.069445), (-6.110542, -6.253516), (0.292062, -0.052982), (-4.869896, -1.251445), (1.61841, 7.980471), (-0.313257, 0.515709), (8.673848, -2.269644), (-0.446207, -0.568228), (3.015721, -2.819861), (1.160386, -5.897356)]
[(0, 0), (0.437257, 0), (-3.127834, 8.941175), (0.785858, 1.99155), (2.005894, -6.723433), (1.332636, -6.214795), (3.149412, 7.17296), (-5.350834, -5.106189), (1.447561, 0.910621), (3.032259, -7.977927), (1.520669, 5.121877), (-1.075969, 0.098313), (1.015673, -5.244922), (3.575391, 5.270148), (-9.160492, 2.943283)]
[(0, 0), (3.63663, 0), (5.448045, 8.287277), (1.314494, -0.164441), (-1.941398, 4.223086), (5.025181, 0.495811), (-8.466786, -2.933392), (-0.139755, 0.730451), (-0.098497, -0.587856), (-3.337111, -1.238969), (2.142947, 2.521078), (0.352537, 5.4194), (-4.49191, 5.261929), (2.198984, -3.781113), (3.525393, 1.150581)]
[(0, 0), (4.540155, 0), (-7.248917, 2.368607), (2.434071, 1.763899), (3.990914, 1.135211), (-5.422214, -5.785259), (0.526037, -0.888364), (-0.370255, 8.515669), (0.77125, 4.48859), (3.9838, -2.3101), (-2.993973, -0.775446), (-1.731491, -1.028441), (-0.184254, 0.281876), (0.048732, 0.222435), (0.108646, -0.344878)]
[(0, 0), (4.934251, 0), (7.472259, 4.693888), (0.057108, -0.038881), (-0.276457, -0.157808), (-6.745232, -0.357168), (5.979037, -0.653591), (-3.969328, -6.050715), (4.19821, -1.883165), (-4.294607, -0.407446), (-6.11544, 0.480539), (1.193587, -1.028919), (-0.387421, 2.036394), (5.78394, 1.333821), (4.178077, 4.286095)]
[(0, 0), (7.547164, 0), (0.989783, 1.074185), (0.192979, 0.210046), (6.528904, 0.400088), (5.602168, 5.791553), (4.058506, 3.995028), (-1.033977, -5.44405), (5.767663, -6.702417), (4.401684, -3.097193), (-0.821263, 4.624133), (6.031465, 6.544092), (7.188866, 1.599597), (5.327328, 3.51571), (1.305662, 7.488827)]
[(0, 0), (0.638053, 0), (7.279348, 5.416438), (-6.495944, -1.385692), (5.348119, 6.89312), (-5.145817, -5.640294), (2.909321, -3.139983), (7.052144, 3.902919), (2.467506, 1.362787), (3.469895, -7.977336), (7.598683, -5.947955), (-0.679492, 9.140908), (-3.310304, 3.134427), (-0.83399, 5.797306), (4.08935, 0.830119), (-7.764758, -4.403114), (5.183087, -8.528744), (-0.75072, 6.163092), (-0.692329, -0.225665), (2.0628, -2.008365)]
[(0, 0), (9.468635, 0), (2.005581, 2.669352), (3.416536, 6.9941), (-3.293394, 0.864229), (-1.044833, 2.243219), (6.011018, 4.014313), (-0.959567, 9.620265), (-1.855409, 1.890371), (-0.629015, -1.383614), (4.087875, -2.203917), (3.286183, -7.748879), (-7.781181, -5.295325), (3.28653, -0.930535), (3.973893, -1.784441), (-7.7541, 4.355823), (1.522453, -1.960952), (5.085025, -1.511887), (8.401342, -2.139507), (-1.727888, 0.7952)]
[(0, 0), (8.617779, 0), (-7.012573, 5.883927), (-3.508725, -6.838323), (6.676063, 6.884947), (8.297052, -0.134775), (7.416737, 5.915766), (-5.10108, -7.183776), (-4.651823, 5.434926), (-1.099239, -0.238062), (-0.313045, 0.354853), (-7.592061, 5.408053), (0.566482, 0.652099), (-3.551817, -3.365006), (8.514655, 4.653756), (-4.249357, -2.130864), (1.181348, -1.22839), (2.469081, 1.110794), (1.831897, -1.552467), (-5.892299, -1.919411)]
[(0, 0), (2.407206, 0), (-6.771008, 0.810524), (-3.840048, -0.152269), (7.109171, -5.609477), (-7.391481, 5.639112), (-8.670299, 2.742321), (0.586435, 4.542551), (-0.442438, 0.107817), (4.31145, -1.409808), (-4.534678, -1.504437), (4.680038, -3.080315), (-4.973063, 5.638478), (6.127056, -7.491446), (2.291953, -2.357609), (3.510856, -9.171005), (3.971143, -8.515823), (0.049413, -5.842664), (1.058161, -0.21883), (7.093364, -3.604422)]
[(0, 0), (6.969461, 0), (4.338403, 5.197497), (0.369553, -0.770371), (8.882643, 1.450294), (2.124852, -1.210185), (-3.046623, -4.395661), (7.716904, 4.60951), (-0.83271, -0.854575), (-2.333383, -0.308884), (-6.347966, 3.124373), (0.832848, -1.892136), (1.446553, 1.613845), (-2.241092, -6.53878), (5.004282, 5.401177), (3.31202, 0.432188), (0.164548, 1.23087), (9.860844, -0.125136), (0.133559, -0.202543), (2.686551, 1.013555)]
[(0, 0), (9.107655, 0), (5.455882, 3.54979), (-0.681513, 2.950275), (7.369848, 4.050426), (5.320211, -8.288623), (-5.315311, 4.632769), (-2.801207, -3.00623), (2.502035, -2.085464), (-0.645319, -4.854856), (3.639806, -8.669185), (-0.732853, 2.379454), (-8.722855, 2.483643), (-0.03048, 1.845021), (-6.904949, -2.596416), (0.685437, 1.042775), (-5.182001, -2.617796), (1.595501, 0.885512), (-8.567463, -0.607195), (-5.456613, 5.81163)]
[(0, 0), (1.669656, 0), (-3.385149, 6.655961), (-1.501983, -0.746686), (1.962876, -0.780073), (0.51437, -4.130592), (1.825567, 0.531272), (-4.188001, 0.514048), (-5.894689, 1.726502), (-1.429067, -3.558197), (4.605078, 2.060605), (1.670708, -8.99749), (5.44004, -5.315796), (-0.619392, 1.785159), (-2.854087, 1.696694), (4.974886, 6.291052), (-0.699939, -5.930564), (-2.35508, -0.057436), (-0.804635, -0.687497), (2.289458, 1.946817)]
[(0, 0), (3.626795, 0), (5.048495, 1.581758), (0.154465, 3.132534), (-4.862419, 7.051311), (3.927243, -0.408956), (-7.41798, -0.313768), (1.987639, -7.957834), (-1.100923, -1.442563), (1.949075, -0.382901), (5.696638, 3.400352), (-1.121574, 1.315934), (-4.37434, 4.937007), (-1.244524, -7.36647), (9.138938, 4.035956), (-0.207342, -4.257523), (-1.298235, 5.950812), (2.17008, 1.116468), (-1.410162, 4.861598), (4.69532, 2.076335)]
[(0, 0), (9.787264, 0), (-4.65872, 0.957699), (-2.813155, -1.174551), (-0.445703, 0.362518), (2.920405, 0.914672), (-1.63431, 0.048213), (-0.534393, -2.389697), (-0.105639, -1.589822), (-0.100723, 8.648806), (-6.894891, 4.8257), (7.417014, 2.868825), (-0.84031, -0.322606), (-0.802219, 1.209803), (7.808668, 1.700949), (-3.270161, -3.463587), (-1.118415, 0.713057), (4.130249, 0.824635), (4.664258, 5.993324), (2.575522, -1.031243)]
[(0, 0), (6.514721, 0), (-2.2931, 3.6007), (3.388059, 1.102576), (-1.777694, -2.809783), (3.431761, 6.534511), (-8.13158, -2.940151), (-4.856169, 2.834183), (-0.706068, -0.93294), (-0.393184, -4.989653), (4.480243, -4.107001), (1.681165, 0.611419), (4.442544, -0.536704), (4.90654, -7.356498), (-8.722645, 1.203365), (-2.067292, -4.134382), (-3.002458, 7.891842), (1.398419, -1.279873), (0.237866, 0.010691), (6.879955, -2.882286)]
[(0, 0), (1.421587, 0), (-0.615169, 0.286873), (0.848122, -2.730297), (0.220832, 0.89274), (4.588547, 8.497067), (-5.079677, -8.428552), (-3.170092, 2.418608), (1.309388, -3.658275), (1.639533, -2.364448), (-1.327656, 1.006565), (-0.475542, 0.298309), (5.430131, -8.343581), (8.430933, 4.118178), (-2.090712, -0.470172), (1.146227, -6.664852), (-0.542811, 1.909997), (0.439509, 6.112737), (0.343281, 0.630898), (-3.673348, 5.101854), (-0.072445, 5.784645), (4.895027, -7.960275), (-9.633185, -1.688371), (8.059592, -5.178718), (-2.334299, 1.217686)]
[(0, 0), (5.456611, 0), (0.181969, 2.084064), (0.89351, -2.507042), (1.570701, 1.202458), (0.814632, 1.883803), (2.790854, 5.8582), (0.699228, 2.377369), (-0.463356, 5.162464), (1.166769, 4.739348), (-4.652182, 5.553297), (-1.123396, 4.186443), (-0.327375, 0.45977), (-0.395646, -4.122381), (0.652084, -0.696313), (0.716396, 2.005553), (0.73846, -7.361414), (-1.912492, 3.937217), (-0.162445, -2.681668), (-0.133005, -0.910646), (2.194447, -4.169833), (-3.132339, -3.079166), (-3.078943, -1.410719), (-1.365236, -4.103878), (2.044671, -0.831881)]
[(0, 0), (1.382529, 0), (5.031547, 7.747151), (-0.49526, 0.019819), (-7.918566, -1.919355), (1.046601, -4.397131), (3.113731, 8.325339), (-1.700401, 1.511139), (-2.699135, -5.052298), (3.434862, -2.609676), (-4.506703, -0.424842), (0.154899, 3.782215), (1.373067, 4.412563), (4.548762, 2.096691), (-0.0275, -2.604761), (4.462809, 1.533662), (-2.016089, -3.481723), (7.024583, 6.980284), (0.254207, -7.964855), (-2.055224, -1.374547), (-3.185323, -3.753214), (-0.479636, -7.476727), (2.208698, -6.374003), (0.24381, -0.620774), (-0.551312, -3.796487)]
[(0, 0), (3.442359, 0), (-5.045461, 1.685484), (0.072923, 1.158112), (-1.347292, 2.626515), (1.982477, 4.374474), (-3.188879, -4.020849), (-0.430788, 0.118491), (0.725544, 1.992762), (-2.893352, -4.311321), (-6.871016, -2.359638), (1.406456, 1.734539), (2.029903, 6.151807), (7.565244, 1.948656), (-6.420158, 0.698035), (-4.873019, 3.593625), (9.548917, -0.45405), (-8.701737, -1.872887), (-7.941202, -1.4121), (-5.995713, 0.555241), (-5.704163, -2.868896), (-2.677936, -1.924243), (-3.460593, -8.679839), (0.631064, -0.433745), (1.18902, -1.496815)]
[(0, 0), (6.537782, 0), (-6.75348, 0.404049), (-5.348818, 5.082766), (-3.738518, -7.824984), (4.513721, -7.740162), (-7.707575, 3.393118), (-0.11626, 0.439479), (0.12586, -2.885467), (4.952966, 5.673672), (2.56597, -0.333544), (-4.60141, 2.716012), (-1.865207, 1.826155), (3.234169, -0.966176), (-5.977172, 1.660029), (-7.968728, 0.889721), (-0.028198, 0.153274), (-5.427989, 8.150441), (-3.708225, -0.777001), (3.513778, 0.529579), (6.309027, 0.399666), (0.542878, 1.900558), (-0.633748, -4.971474), (5.340487, -2.474143), (-0.805431, -8.633636)]
[(0, 0), (0.211756, 0), (3.03609, 1.381372), (1.472087, 3.505701), (-0.198393, -0.284868), (4.290257, -7.630449), (-0.120326, -0.047739), (3.167345, -1.144179), (7.791272, 6.043579), (6.125765, -6.3722), (-0.178091, 9.313027), (-4.177894, -0.704969), (-2.950708, 1.716094), (-0.016133, -0.105582), (-5.962467, 6.088385), (0.901462, 0.58075), (2.063274, -0.221478), (-0.430464, 0.9548), (4.824813, -4.037669), (0.863528, 8.321907), (2.693996, -0.380075), (0.879924, 4.243756), (-7.759599, -2.81635), (2.58409, -2.225758), (5.515442, -7.445861)]
[(0, 0), (0.958126, 0), (-0.566246, 3.074569), (2.666409, -4.784584), (-5.490386, 1.820646), (0.505378, 0.261745), (-0.122648, -9.791207), (0.569961, 1.044212), (-8.917451, -1.667965), (-7.374214, -1.193314), (-4.559765, -2.486695), (2.367622, 1.707526), (0.762113, -5.553413), (-9.62438, -2.077561), (-0.072526, -0.072188), (-2.051266, -5.410767), (-6.656983, -1.824092), (1.170361, 2.019313), (2.689391, -3.998207), (1.814094, 1.782214), (0.498034, -9.437937), (0.87507, 0.670687), (-8.114628, 4.823256), (2.693849, 6.952855), (-0.005543, -0.01139)]
[(0, 0), (1.703854, 0), (1.091391, 2.171906), (5.559313, -0.310439), (-0.396107, -0.771272), (-5.136147, 7.769235), (8.969736, 0.885092), (3.541436, -6.530927), (-0.461503, -5.877802), (-6.108795, -5.163834), (3.698654, 3.749293), (8.049228, 2.056624), (-6.022241, -0.657227), (-8.701763, 4.803845), (1.225822, -2.070325), (2.099514, 5.191076), (0.500653, -0.104261), (-0.581698, -5.755634), (-5.150133, -8.269633), (2.559925, 6.839805), (-0.149545, 4.456742), (1.43855, 1.865402), (3.439778, -4.954683), (-4.18711, 7.244959), (0.640683, 0.907557)]
[(0, 0), (6.577004, 0), (0.042196, 0.025522), (8.61361, -0.689878), (5.407545, 1.709241), (-4.724503, 3.123675), (4.329227, -5.283993), (-1.238506, -1.104368), (-0.758244, 1.882281), (3.851691, -0.571509), (-0.229269, 7.452942), (2.833834, -6.742377), (-8.49992, 1.912219), (3.102788, -9.456966), (-0.420271, 2.449342), (4.123196, -0.512152), (5.893872, -3.689055), (-3.801056, -3.486555), (-3.576364, 3.448325), (-0.397213, -0.010559), (-4.519186, 4.525627), (2.720825, 6.0414), (0.918962, -0.430301), (2.217531, -3.056907), (0.912148, -1.487924)]
[(0, 0), (0.170063, 0), (1.088807, 2.795493), (5.884358, -1.914274), (9.333625, -0.111168), (7.168328, 4.042127), (2.558513, -0.146732), (-8.011882, -2.358709), (-0.374469, -6.591334), (2.495474, 1.011467), (0.094949, -0.351228), (7.0753, 1.26426), (6.614842, 4.664073), (-2.777323, 7.287667), (3.280189, -6.811248), (-7.254853, -1.472779), (7.147915, 1.932636), (-3.431701, 3.030416), (-0.863222, -1.177363), (0.512901, -0.258635), (-5.614965, 0.462802), (3.452843, -6.869839), (7.475845, -0.353582), (0.067355, 0.298013), (4.39831, -8.5387)]
```
**It's not allowed to optimize specifically for this set of inputs. I may change these inputs to any others at my discretion.**
Lowest score wins.
[Answer]
# [R](https://www.r-project.org/), score = 4.708859
```
require(vegan)
solve_mmds<-function(dpf,noise=0,wgs=rep(1,nrow(dpf))){
#MMDS
v = wcmdscale(dpf+noise,2,add=TRUE,w=wgs)
#center on first point
v = sweep(v,2,v[1,])
#rotate to adjust second point
alpha = atan2(v[,2],v[,1])
alpha_rot = alpha - alpha[2]
radius = sqrt(apply(v^2,1,sum))
v = cbind(cos(alpha_rot), sin(alpha_rot))*radius
#flip to adjust third point
if(v[3,2]<0){
v[,2]=-v[,2]
}
#return
v
}
N_input = length(input_data)
err_runs = rep(0,N_input)
for(i_input in c(1:N_input)){
p = matrix(input_data[[i_input]],ncol=2,byrow=TRUE)
n = nrow(p)
dp = as.matrix(dist(p,upper=TRUE,diag=TRUE))
dpf = floor(dp)
v = solve_mmds(dpf)
err_runs[i_input] = mean(apply( (p-v)^2, 1, sum))
cat("test #", i_input," MSE:", err_runs[i_input],"\n")
}
cat("Average error: ", mean(err_runs)," \n")
```
[Try it online](https://tio.run/##dVvLbl3ZcZ3rK4j2hEyoi/1@GNYgQDx0BnmMOu0GLVJtBmqSpih1nMDf3lmPOnTrOgYaaOree87Zu3bVqlWr6jz/fP/w9Pnl@9ubl5uLdxcf7z@9XL65uHh/ma4v@N8ptbFW0z/etlMadQ/@67RLmWXhw3pqbdWMv8ZpljHnwJ/pVFars@vPPfNe/er6q/vWPmsvvm8@5bRnwT3yae5RGu82T2u3NqYekdYYyU@bLY2hizqeMepX9x2nlefM0/cdpzb6TPzXaaZe0saH5ZRLyrxFPZXC5@rDnlPmLtappdz7PF/ubiPVVzPs2daWGfosHQZ52097l5W1h7b61h4KLNJ6q1r4Ln2tcbbcsQZuFf9Ia6Wt25ay@ek6lZxHGXpon7Bt1873KmPpwzla71/btpxSb6P0WPnslZZLp7Zn5eEMXD53LVp0Xg1G1u/KHDq7jlPupbSzlZZVJzflA4NVN@6KXWOl9ANYsKTUq86g5daH9j92w3nokoWd7K/tClPBJs3H1U8dz62418Six67b206p8A4NflbtT1gfXaueRsfdy9lRjbpSj4WWU52VW8X2KwxJ861THjtX32v2hWORu5VU1vaprdRKOl8qHCS1dhgAK6j0Mzh9hn9PXddy3nG31UeSazX4Tu@700TYa5tfeyx@OWuOQICf4blcBDynYZVbz2pJrgejwyhTv@OhVv9ZaPfuSISPpe7dzAU35I3gz6s2/bUrHia3zTkpOnGAGcdeaV8G2Tg@hAcMLTnlsiZPp8HrRz6Pi9QcYOEVWICsDV/a0@tLaS8DQe0j7@YYhKF25RlWbCV3Gpgexo1uLL7kVeR18gKcXu@F5p4I6TJS4@8X7tG6QApxczwNh1x7QFDR2sap97T2VyuvXOFcR5DAHdpUlBCqfHlevdCfYY6ScJxTiJJqmU1BVPF8hUBuWO@0VyzAlO5T4da6PY6qACX4yDa3/JtHOgFCix/C00cqjPXcgTLxbHy95AbYxJjn4NkAKnPb6rBgzsKKvoCpAuc04eK@E9ypDvsBNtQUn70CSTZNuHttgh/gH/ertQ0g8PLGx0CwyWOAjk0nS0snp4C8d9XJDUBLHvZa@KWPLLVcSz@zOiAyrXLAM8B@8K4dkVE3owDb6XPvFXHYcTA1DIZz0ephmkrwhT0rQJmG33hYaVzVRJjOzDthLaMKJ4SduXNLjOI0Suyz4PFLnld7W8402FO2EVfG5V@DS1dY7XnkgY1op0Nj0Rk4ExbPJVfBE6A1FVmvDqzUXzekBrkv8l/VIcBjDW2I2gW3crqoCGruCJ/ukkcafDzcWF6F1RMWAxB7b5mnBGjbe/YZZiyjzrPMUGtuuwWgrZqqDg0YnSPwAeLKN3DlvIWceCiSUIAxEtRI2cGMCM3O9XCRUVtEChKjUwtgrxYH5S4tuEDaaWffIG@sxWCwFozt72tfDsSRGfNn64djrNoPx8e9BsMSaaaPFYspIyN5OacDgatNWHvXY5kzSlKWRvSusrnBiiAj@2A@RAiugG2GoK8BDnQeJAyIdL2FKUj7PculkLbkMnCe2rpSFfAeH54lkNT3qutAevhRG9kJoCydA0Jj0PMTc4p8XMbtfR1IOnXOCAyYjJvkgW0ZjPFd5UYN98EN7UUJ@SA5FcNJlOrhOyX3POJEMxDeCXrgqU23h2PWs1QNN6hDQJUieABm2TCM0F2KwrK60BNPAEh4qUjeS34sjMnOjgnAnJSTClN@pkFzodW0KETZmoqNhOzRnAUrqZ3ug4TVnXBn4y9lETiuvu4w3gL6nUEmw5MeYtaVmZJ5/zqWCK3wChEp6@tkg33AyyM2Yce1FNc122T0kT1ITioiA5DcnATgw3I7eGgHlBrx4VdbjwQmtKaD7zjjLitUGI7stBHIhNckrwiGpsQxCn@prNWQ4Y3DcMApW4MmL9FBxMd8jbRODubjJqGtDjp4WG1OWiAA@RweJhd3HDFYck16AjY8dZgZfHMakAGOo4isZvhQ6XZgHMgI0g94sBHAvOpWTC8EWre1gQ7OGAjpmqN8GDnzYAk@s2/FJs5f7GoRZZpT0Abr4Kk3GGaVKlsiLJFIdRI5iSA0OnRJAnigv0gGHpeb2Rq8FfjXDTs8enE/ZBJAZMQGXeosg3U60iolQhpokbrQvFUmEa0dZs@yMQicIhIHCDQYYrbIL2IacuNU63R1McRuELqk4wpn8CN7HiMD1rQTYuNJq6tcPhi1YAfBLMgb8GfsQ48EJUk0l9hEq@YiALKWVzCq1razY8t4lqy9cpe/ZpLtVO3khbQ1MHnn2UwcpgyKwFrgyuWsWEDqmgdBATHZZTApIOcBIQRHLM2SPoTXgc7Q@deJh1AUBn2umZ1Zt0EVC8lMaY0/BOHYcwTBR8orvAYszGQCQaldwojgCmKcjZlNa0/kN8ngA@YeRGiRrkadwsTsmhFFyPQicFQlhzcDXeIElHhFa6rY0VuVlKVHWkTirK6okP5RL5wDKr4d/cgH4GaKiM2IGK7@KoJoKPEjcQ/5NONimB0hHcy0XFd0@x5M2prRAwy/a01D6UvYB8swv3t1zBzOdNjQ2pEZABvNnA6loSJrA77nkfPB6KbpIkyiMxvIVM3og1MezeENLy4pSpWBeBHVhceoyiezQ/YdTsOoq5etBHKDEuGc69bpZ5qeITXYBUCj8gwPRNaR04K7dUU5KiIRM2kStVXladCZUe18gKZpQCUfIl2c9K7tdVSUC8FngCV5GbYBrCOb98KGAn04RWEeIUeDvxdjF0w8FE0ggmu6MADY7rHNn1c1b4A5xowCA7FYij0NyTebaqbcnFdho@ZY2cCZVc9INXY1ajgVIjXxABfCFhAwDd9NrI9QgANqORJSFiwjcAAly/wS528GAmww@1mI1DGXgw2UsO4AFTCEbvsDjnukl216zGMHLVEgIF9WUHI/lImMdiismnabFg6QN1w0seJysZkjbBvg3@YA@BRfCW9dTi0TazTc8cpthg/Ks77ObIh@qTr2ItBs5OI8zeeWSojCYiJNS1CjKlUjfZOtKrDA6Es2RWylOLN1ep7OH7tFURr1OMhsDUqBerZ0HQbiZfj8ATNMltgZotZPESsklOXk6NikXyFQzH6wtknybjOC4PkYmX2bcirrXbjbsGgHECsWkpBEdEokl83AxJpvrjMLAWZLyCaT5ak2hhyKgsQVbUIRlVawdDJ2020qUN44onvpBwi6BlpXouifSn0dIbIPG7FG38ZTuEMtvgpUdWbZBkdcAo0RLcNpquwo9@CdIBptBM51qTKwZ4qCCpWLKbMMZRWFFTnIk2rqREKiDA0w2c3YUPVEJpmVpnIxSHQ645HgbKyVWmDTXk7MjG@W1xYQkK0t4qHWbBLcOlbhmrmB0C5ZA1w67DKJWlZgutMjPQ80z8QRJGEHs2VB2XUJKPAwOYCLNXMHuPiIuEjUXO1A2FaxvkNhtaqEFsfpWhnuuA1/ONLhyg8P39OF0ayGbuK9ggOMcAxdAP9dZf5/4lsNW6FEqG05nEerPmQAy24tGH0XBcCDGgJ5SzvcUsMIvQ1hPCN9prKVsRGQRyIGAG0afzKV5aY8vfG7LJBgwk3DFB85w/oL81w/4LoyF@BAkYhC7dhMCj242RbibhLlHdIz4rOmo9BrUdsuHM/2MQIIh4W07ZhDha1t4YEkzt2aLXh9NkFEMZvkqIsuMiN3zi7lEK4N/h1oCzvVskPv68OKDtLQCiYAyPnaUzd2C67fD0k4oYqU8wOGJLxXHkqvFoQtV4O9AOC31Y8BnHPhlSjwu5ZD9vExYV/Sr7DZ3GoU75sF3OSzkfxLaNWkJskci@Fv1EDlIPooJ6iiyzQbzqmbSYC25WnBCAnY3Hc2V4X8E@6yDMeFMkOPnwadR4HQLcFs1tEuWOaK1Ed5uSnWK4xSXMMDJ7t/txn1Fj4QjcWrpDy2ZrQHzPUKPbAn48xkySqYhAt9zYZBkVC4Hmx4Uh/qBHeLXiXUGmy@mLghG9SiMEWQq4geFI6VLJHVNzsZkYHbpL0mT3I6bwJK5hhBXQzXDO3qtgwwgAWtHo58t0vUh3sfOivy80EQcarJ8irVsR5FMAlkthwckQ6CN6SZJGkrwY07iYT3BtdMDAxmQcCOAB4nNY9iv8EhZxiUSUoQjqqwGf9AHmuE9JYomsltp3Eb2WHt0F5Ra48ZRBK@a@cFHIAontW5SB8ljVcVEnnNLRKUjr0YQReQuq3Ia6Uwd1NbhFfa7eAkTag8Ub2Bp8kmSCvSHt@SFictgRpFEWSREg0lY9IR8IIcTLkIGpmh5zKSEx96SP/bORXXVGzPJukIyeoCeKVUV/TIgCvOlEKi6hUtlZssIuE4Qwtu20oQ4gzm0ckW1fNpG@uTmdtmgZRSBBLWZI0RuWBZ1kwkz8ZOsJDhoyP7GkEOEDRGaODKsGFBZYEsZ/UiSIDEMDERpOKWtHpU6lZb4UO794MRGUYWoqKMVt1GOhJEBrcLHbsQotwYQR4eXLK7McO6G0XyEAoQ8TnQvARErd56oFElO/DD4aBqh7LUbpSvlQ1wgu6r4PIVbgsfVPXHymFo7aypsLVAuJaN7ZTjpeBR62hlFQdXltjFnFNS9K9oTfkJGFcL3VrpY5/YdojsAXTRc9XUkMrFg6BaJAhHUpDnsfyo563DTR8cwZM7my5ruSpp4jRE7pUle1KgSMXwg8PRrklgsAUXrCWVqB8KiEWxl8BBJfbA5DD02NFty64VcU5pWGfFvVO1peCMLfg0Nl5z6JbEpOHqByEyHHRj5@g1kbh0S7aAColOCyhdlgvERo5@SM7J1lz0IitRm57t1XWKCbLnYP9EBRU2OaN9BjhNwdoJ8zsYVO9JIc/KPBABqbENPxI0Nm9fT5EuOxvkfNbNZitmjz5eGz2rSzJHZsDBjhxYkHc4J@4/lhawwQxCiAOdTXZOXCz63Yiz3YLMAg4NV/TwtGhYws@Sl49LjILEVBCKbRFnSIMkPCGPR4ue/GIbk8jjlwlKGlYQBwXfdbQo2napKhnGbiHLvZXEVEMrwm57eAgoxJruNMEkilm24JfYC0DsSIljb/eNuzjAaAFt/Shc@mzVD0KZPKJjM5Zhht02@IqlBOw2z/NCuwzJBpZv2pKAxq5fFrdjqmgi1mSI1NpCXkGwbxNVa50cBpgl/A9b2wcwZ3XVnXyne1MbB1lDY@gWPzQwAfSIzhhyyahe806h/qKa2ck5CRar4vBsIwc05gKLu/DJFNiMjLCNTYu6NXhNac0ZkVE@msAmk1I53GtI9kSYaVqEhA7cjLVRYqqqWIAWy225PFOIsgCyEe3QbC2TxsKClivPXnUBIAlIdgZUoIplvM6lDNR7JeYxrM5RYqoq@bld1KOv6bbPFD05ih2hEqquorSDHBvdwdpqjmK6BMHFiUpkoE9Rx4i6F45Wd/R/t8Rhfcruk@hfWytEz8UugPBvSdTSkaeszIUyRDK6ekMp9PoK6pEOhy0i37AqSYHy6mLPXsacR6OkSjgaIVaO10o4U8@zXsPwt9pcUTxuK/OOBpgSxL@7XmcDUEvDgfZommJhcNxzuTc3CXseuUARIR8fciLCFpiiC3OkoRliBlvQLfDfVTS11TxHdou69UgfPMboblDEyQH/I1tHWlS0A/@INysqgLKPRgMooh2cKqcL7QZjNvMBZLzkhuAgAnfr3FkR2xRckVhRK03TBQ6gHG3F0fY6csuwcorM5RYOAXCWHaAK31klslwRynDEifKNOwmrxbgHyuYY0yh1qiZnUzmNLcugBHKRStkX@WycT9QgtNc8VOURnT6qQyPuilydiysY8MRiglUKakiFEIjL1Da7elqqeVB0BLUG8XafDZ8ymXpHjGkLlDiM4fBG7VrXip7rKu5VDXaFI4IoRTr8yQX6cL8Pf0SjHE7nfg9QpCanjOopLTwd5lRFu/jhrm58suaIkhhQmEvcKOUpIyO6S/EcB2uWSBp4SgxubVQvNkdjaadUC0I/o0tD7TVb5QBmx9ZmDY1DbDNaibNIRafA1OQV8FjxJeP4MHMCwQay5WjoI/yD1yJaejTRM/sgoQ4CX91BLIiSs3MPIpGPeRbkYocHeGHyxB5FiXz0xZO9jtNxdv4SPskiCFBgcoBSNIlDzZ20N9CAHqUeakbPfaG2rCOmdAjUon9A8xaV3Bgieg3OZjlIeO0Bnw7aUEsUcLnUuiWgwIeOYS9KUJb5Wz9mfEjhm4tHOHKNM0HtuYIm7iFJglA3dEsLIC5X2a8YkdGyZjFUJhbpPZXJT704ieU@RnI71DQBLaDVKWY52AlwIYUqs7UgV2DDtYZExS055ufW0KH@RBqoR96bEfWVw2@xqVSjp584AXlUJqBl5yMFQJRe9muDPiteqZTMfOS73UsgyF6hRZEkR2t4Uyvt5rTDox0skWY2hGfQEE9Fks5EkkOsNzsNG/p1x6Df1tQLIQK5Yq8Y0FnDSIMSa4QG0dNQCubqUK05xtl4tOg@OYzhtjPLWEub2RyHlTP4kGkBqWC0HUpUaigulUAax8SWZSese8QikBfT8nkAA5WeQcro@NVzkdTV3SdtLkkYrG0F3iZmwZAuZ5OtecioM4rPe@KvHA0w4GQNVjeH5sMoa7HV5upxHlN9LP8PVSzNGcmGTNHYOrmCcyaKvFR7SEqkor2NyGEwUMyAlV2iIbKsSmTWrMU4zWFIWxmMpVnwxpo8w1ClBk9XWolxFfFd4bsmushb26Mq7IK6J4zEEYYG1phqSsuoUVUBylKOri3ql@pGM0LI2A8C2a30UDpJOhK48UryaQ6HxnPgVD2ayCVlo9YgJbL6gTSX8o7esQZhN91mR1TDVslzoMwLdUbTt0jf44E3l9wKzxgLQsqdRpROmckfAkQ9dmXutmPidXLizsFVWonhX45/7RrK0JagxTSSU1S2rdKjrHzt4@mbxfY51QLc/mKArld35lGmpebCB5@sbD0BWTcwZ7J2jMlUIN1ygs/V/Vgihgk4/0QN4fFaUqeYFogxZCVGjx5SaIiuIHmC4xRgs92wRl4Uky48uCDKFU7RTMUANc1jrgjJcM5FCJ@uSoeoOxvrLUdywY1zDCizV@@MDsxKJVBtLE2ks@j2NLmQwVOaBBhPbqqDhyPYHrlMLaRvlKcl6De4qShhlYXcmuwc4hQhANtQImcewpqGJ4aKEJsUgkq7w5lnukKQy4osno5nVzgtPFuOLAeC3ILX4CoAx1lbpbDXPSL2Ux1GNuBGtRk4TuoeR099pmPAbtVoAlGVGu717qTKAwYDi2kR2PD4WsYxBjWrooeicsiQubE0VWrZlgkGfljDIhS0Y2YJ6zlmTgC/maFHHblEapxzBS1H8OzQfyiimzLSGeJ7ljAxo51pUdMhvhwwZszKx0wL6tw2ivVVlb@k3XHW5LX5mLcBerV4eaFbrkIoePCQpeyMBi27JsXjF6i33BzmNHoIFJV6irs7YOJFgUT9L0r4Se52FKAqqRABq8WrB4W1sWKzUypwwIFjrL8ZrGb7vYzX4RDO5ErtSoAJMzu4nm/byDL7Ct/eHqfImojzaD98otqLEVfzGDFmveLxAp6p35LArbcTCVXaEK4489NjRBDgNdxBq@ymhhixOVfq3I5Yj9oHHjc89g4k0MytXhsIOoJPckjHnUNJ1XTYWjhz7fS4hdl0P5xzWgRVMs4lOh1kUTGejcRgNYz7d2uT5T9Cxp1fLDWHDrrr0YFGBgzcYbPPw7nLTX4SKCSWptXhlLdLgTW7DQYmM6KDl@mG4VZVM0Dym2XFDsh4DJYTIQ7tkfzpjNNhseLanhndufp9AL5l4CFg2PjouCGBtOjcgOfm6I5zxGBG/UCOa07IFqJmEShcWCEGcKcdAm9uMRvT2XSMVAkYTqHvI3ST9eoMqAn1Eh6@PPoKs6so5ojiLlvCB4dWXCOoaWzZPHEkIfhOny7HnIpN8GDtFXU0EkzUqYnzVw5tpOJonm4eu/07HZ2/TP05xwBKNtlCpu79GFDGhowrS@NK7mvCoruoH74oJkeANL9e0FhaTddLnKPT2rjZ5C4qu/OB8kiDK1QFcB01GTjZ4xERRKu@JWLN8zeMBl/vkRwab10BekaMeUp6YRexxs7gu9Ex4BCnjcVXL5rpO985StWNCYSetoAiy6bufM1iR0sUtZPH8SjN4PzX6zsxZloSGDzeShkh7IraIh2t6B2dsdb5HpD1GLuEpkBKPbQCFNayIKCmmJzlVEQmGVh8CWJEReDXfYAfbUtRZJFXc6Bvp3LpNwb4MosZMuxxvAGzUk4xdUSWGJ8iPan95HfVIstXkoQjDJM7JeREqI5UhHbEsGk7k6vdI7Ucrz6A7pUjq9TkVzXy9Jgtx67HNkBgvzlUDuT9ffZaVZJyEsNbmUltOeEgwNqOJjGFjijWmtLaJpMasQ2UYMdo6VjVAET38dKROXtsktJmNaIndrNLEPE14zRJ/5WS4Yx8QSreGfJcM/tFublVQKUxiEPFgRQ9HZ5Y/TaDOkAcsnZtJ0lRLQgKTiAXLrvYoBjR4k@asWOFkNm/84zW0XQWu5lmHxzbi6rlGOazaphiHi@1eA0AWbyEZJkpUEQHxKo4Xbd7OoKtXES6dT8VjY5qvlzoARuWbNVOjshox6tMNYQQVKjVc3AoelMWhtW9gs2xt3f15urNz893f/p8/3x3@eXuh5uHqzefHj9@ufv@xx9vP/3m7YfPD@9f7h8fLm@fPlw/PN5/unuXrn/64dO757uny3z98Pz4E7@6urr6X7jOr373u3/@N/z/y8W7i5/e4wbvbz7e8ft/1KXX5frm9vbdv//rf/z2@qd3uMsVfsvL3t89vNw9Xzw@XHy4f/70cvH0eP/wEvf59NMdHvUF1375Nl9/d1zy/Phy83J38fJ4cXP7X59xzae7948Pt6@X3nx8@iPfGr15uXkol1@@vS7f4QbXWTfQl9/jFvyBfvjW//@2fIevn29u7z9/4rP/9PxyefP09PHPl19@X67z9afPP15dxcLe/@H@4fby/eOny9fbXV1ffLp/@MW/r/7B94pFf/h4//SLJb/88f75ryu@/4BlVqzzN0nGxFO46ndv9T988Jdj63cvn58fuIo3f3nz5s2/fK/XZPmG7N3DDy9/vPzrW7NXb@6en79//vzAzfDE0nX8Gqd8/z9/55sfb17@zjdvPjw@X97H8@4fABX518eXWjP@e8JluMPz/X//YiHffhtXfffd9cP7x4/vyvUf/gzfkS/QoA@4Ss70FAd8y/vcfDrFrW758u/T9eenp7tnO9Dt/c0PvvxKP/@A33/4@IgF3h73kPu8OrP8FJ8eJnldEhd8d/MQB31x@fT2y9XvmRBwmjpvguLNy@U3L3c4tF99c30RV15/c/G7f/vtr/HB39zz@pv/fPjmiuejK//py93zzQ93/N3j868vcIWeeFx2hTvx9z///H8 "R – Try It Online")
The core of the program is based on the [Metric Multi-Dimensional Scaling (MDS)](https://en.wikipedia.org/wiki/Multidimensional_scaling) approach, which solves precisely the problem described by the OP. The idea is to start from a collection of dissimilarities between entities and infer the coordinates of the system. Some post-processing is required to rotate, translate and flip the solution.
There are at least three functions available in R to perform MDS. There is also one in sklearn in Python, in case. In the code above I settled for the weighted mds variant (function wcmdscale), mostly due to the possibility to add weights and to a slightly better performing correction for negative eigenvalues. There is a core function in R, called cmdscale, which could be used instead, and would result in a score of 5.77.
The code provided is predisposed to accept weights, as well as noise in the floored distance matrix. After testing, it seemed best to not use any of these options.
~~Sadly, the package "vegan" is not available on TIO. So, no live demonstration: my apologies for this inconvenience.~~ Works on TIO like a charm.
Interestingly, the program significantly underperforms on the last two examples. Adding noise can help, but it worsens the performance on every other test case. It would be interesting to find out what makes these two test cases particularly difficult.
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), score = 5.94258
```
#ifndef _GLIBCXX_DEBUG
#define NDEBUG
#endif // _GLIBCXX_DEBUG
#include <iostream> //{ and more includes
#include <vector>
#include <string>
#include <sstream>
#include <array>
#include <cstdio>
#include <cmath>
#include <random>
#include <cassert>
#include <limits>
//}
template <typename T>
struct point { //{
T x, y;
point () {};
point (T x1, T y1) : x (x1), y (y1) {};
point operator+(point p) const { return point(x+p.x, y+p.y); }
void operator+=(point p) { x+=p.x; y+=p.y; }
point operator-(point p) const { return point(x-p.x, y-p.y); }
void operator-=(point p) { x-=p.x; y-=p.y; }
point operator*(T a) const { return point(x*a, y*a);}
void operator*=(T a) { x *= a; y *= a; }
T norm() const { return x * x + y * y; }
T dot (point p) const { return x*p.x + y*p.y; }
T cross(point p) const { return x*p.y - y*p.x; }
bool operator==(point<T> p1) const { return x==p1.x && y==p1.y;}
bool operator!=(point<T> p1) const { return ! (*this == p1);}
bool operator<(point<T> p1) const {
if (x != p1.x) return x < p1.x;
return y < p1.y;
}
template <typename T1>
operator point<T1> () const {
return point<T1>(x, y);
}
};
template <typename T>
std::istream& operator>> (std::istream& str, point<T>& pt) {
str >> pt.x >> pt.y;
return str;
}
template <typename T>
std::ostream& operator<< (std::ostream& str, point<T> pt) {
str << "(" << pt.x << ", " << pt.y << ")";
return str;
}//}
typedef point<double> pt;
//{ Additional functions, for point<real_type> only (specialize for double here)
double angle(pt p) {
return std::atan2(p.y, p.x);
}
pt rotate(pt p, double angle) {
double sin = std::sin(angle), cos = std::cos(angle);
return pt(p.x * cos - p.y * sin, p.x * sin + p.y * cos);
}
pt normalize(pt p) {
return p * (1/std::sqrt(p.norm()));
}
//}
std::array<bool, 0x80> const valid_double_start = [](){
std::array<bool, 0x80> valid_double_start;
for (size_t i = 0; i < valid_double_start.size(); ++i)
valid_double_start[i] = false;
for (char c = '0'; c <= '9'; ++c)
valid_double_start[c] = true;
valid_double_start['-'] = valid_double_start['.'] = true;
// there are also 'e' and probably 'p' but they are not at
// the begin of a double value string representation
return valid_double_start;
}();
double score(std::vector<pt>const& pts1, std::vector<pt>const& pts2) {
double result = 0;
for (size_t i = 0; i < pts1.size(); ++i)
result += (pts1[i] - pts2[i]).norm();
return (result / pts1.size());
}
std::vector<std::vector<double>> distmatrix (std::vector<pt>const& pts) {
std::vector<std::vector<double>> result (pts.size(), std::vector<double>(pts.size()));
for (size_t i = 0; i < pts.size(); ++i) {
for (size_t j = 0; j < i; ++j)
result[i][j] = result[j][i] =
std::floor(std::sqrt((pts[i] - pts[j]).norm()));
// result[i][i] = 0; // implicit when initialize 'result' vector
}
return result;
}
std::vector<pt> normalize (std::vector<pt> pts) {
for (size_t i = 1; i < pts.size(); ++i) pts[i] -= pts[0];
pts[0] = {0, 0};
double angle = - ::angle(pts[1]);
for (size_t i = 1; i < pts.size(); ++i) pts[i] = rotate(pts[i], angle);
pts[1].y = 0;
if (pts[2].y < 0)
for (size_t i = 2; i < pts.size(); ++i) pts[i].y = -pts[i].y;
return pts;
}
unsigned nDiff (std::vector<std::vector<double>> mat1, std::vector<std::vector<double>> mat2, double eps = 1e-10) {
unsigned result = 0;
assert(mat1.size() == mat2.size());
for (size_t i = 1; i < mat1.size(); ++i)
for (size_t j = 0; j < i; ++j)
result += std::abs(mat1[i][j] - mat2[i][j]) > eps;
return result;
}
std::vector<pt> pts; // use global variable to print progress
int constexpr n_iteration = 200;
std::vector<pt> solve_with_seed (
std::vector<std::vector<double>>const& distmatrix, int seed
) {
std::mt19937 engine (seed);
std::vector<pt> result; result.reserve(distmatrix.size());
std::uniform_real_distribution<double> dist (-100, 100);
for (size_t i = 0; i < distmatrix.size(); ++i)
result.emplace_back(dist(engine), dist(engine));
for (int iteration = 0; iteration < n_iteration; ++iteration) {
#ifndef NDEBUG
if (iteration % 10 == 0) {
auto norm_result = normalize(result);
std::clog << "Iteration " << iteration << "; "
<< "score = " << score(norm_result, pts) << '\n';
std::clog << "[";
for (pt p : norm_result) std::clog << p << ", ";
std::clog << "\b\b]";
std::clog << " (nDiff = " << nDiff(distmatrix, ::distmatrix(norm_result)) << ")\n";
}
#endif
for (size_t i = 1; i < pts.size(); ++i)
for (size_t j = 0; j < i; ++j) {
pt vec_IJ = result[j] - result[i];
double dist = std::sqrt(vec_IJ.norm()),
floor_expected = distmatrix[i][j];
double ndist = (dist + (floor_expected + .5)) / 2;
ndist = std::max(floor_expected, ndist);
ndist = std::min(floor_expected + 1, ndist);
double delta_dist = (dist - ndist) / 2;
vec_IJ = normalize(vec_IJ) * delta_dist;
result[i] += vec_IJ;
result[j] -= vec_IJ;
// std::clog << "Numerical error = " << std::sqrt((result[i] - result[j]).norm()) - ndist << '\n';
}
}
return normalize(result);
}
std::vector<pt> solve (
std::vector<std::vector<double>>const& distmatrix
) {
// just going to try some random values of seed.
std::vector<pt> result; int minDiff = std::numeric_limits<int>::max();
for (int seed : {123456789,987654321,69850,68942,4162,12012}) {
std::vector<pt> r = solve_with_seed(distmatrix, seed);
int d = nDiff(distmatrix, ::distmatrix(r));
if (d < minDiff) {
minDiff = d;
result = r;
}
}
return result;
}
int main() {
std::string str;
double sumscore = 0; unsigned ntest = 0;
while (std::getline(std::cin, str)) {
if (str.empty()) break;
std::stringstream sst (str);
std::vector<double> values;
while (true) {
int c = sst.peek();
while (c != EOF && !valid_double_start[c]) {
sst.get();
c = sst.peek();
}
if (c == EOF ) break;
double val;
if (!(sst >> val)) {
std::clog << "Invalid input. Stop reading.\n";
break;
}
values.push_back(val);
}
if (values.size() % 2 != 0) {
std::clog << "Number of double values is odd: " << values.size()
<< ". Assuming the last value (" << values.back() << ") is redundant.\n";
values.pop_back();
}
pts.resize(values.size() / 2);
for (size_t i = 0; i < pts.size(); ++i) {
pts[i].x = values[2*i];
pts[i].y = values[2*i+1];
}
if (pts.size() < 3) {
std::clog << "Need at least 3 points. Ignore input.\n";
continue;
}
auto distmatrix = ::distmatrix(pts);
std::vector<pt> result_pts = solve(distmatrix);
double score = ::score(pts, result_pts);
std::cout << "Test #" << ++ntest << " score: " << score << ", "
<< "number of difference in distance matrix: " << nDiff(distmatrix, ::distmatrix(result_pts)) << '\n';
sumscore += score;
}
std::cout << "Final score = " << (sumscore / ntest) << '\n';
}
```
[Try it online!](https://tio.run/##nXtpb1xXkuVn8Vc8u9AlUhJTd1@sBeieXlCNQc@H8QANuAyBIlNyuqgkm5l0SWPot1efExH35SLKrhkDMjNfvneXuBEnTizv8vb2/P3l5d/@9ofVu/XV8t305t/@55/@6X/853@@@ed/@af/828nf8C11Xo5/Yd9Xa6vVu@m58@P7zv5w2p9eX1/tZxerm4227vlxYfXuO3X6WJ9NX24uVtO9vtm785flpfbm7vXe1fw5Gr9/uCKDbZ36eLu7uLT/oXLzfZqdXNw5cPF9qf9C3dYx83BKJcXm83ybrt/6Xr1YbXdvD55/vzzycl2@eH2@mKLy9tPt8v1xYfl9P3rE6zm/nI73d6s1tvpV@7wZMJ/308fn02fXshn/e30bPr188EF3OOf4c5P/mz6bvo4nX70Z3hoOuWFw3tvbpd3FxDN01P9fns2Xd6sN5zxbrm9v1vrfacfn94uODH@fDp7MX2WIX65WV3tRni1G0L/@3X6@PQVHnuBx/D303jscObz35v5XGc@/@rM5w/NfG4zn3995icQ1IU@8vDMTy4w75OLsxcPTPrk1e7pedLpyavpApPa3892Yuubuw@n@7dOD02Kp/HvKZ@ePu0evrrZTtPxBr98@Am2y4ef7G33@@ny7maz@bse/jSdy8Mfx8Nvb26u592@MhG//P71dOu/OKmPr17desz/xz9On@TjpxcPDPLNbw/yzXT6ZPvTajO9esWfHxrh5eEAY4STsS8AxunH6Rs@v/h4thPsS7nwYr7PfvikP5g16XwPGaN/LT@NVUy2CP@atne8hn0V4j2nVN6zMQWM76v2fvXddyvFoD/Oc73GHIe/4O@zMfrrP0632zObHD9MuP12i4PQv7YxWxF@f3Hy@Tenvzme/uVLm/7mwemPZsfd355@yz@yCH59No3vn@T72bcPrElREIuhW9Cxr27u314vOQEERnT/x6ur1XZ1s764nt7dry/5cfNsejefBlZ3/YZjvJ5u1tfAus3t8nJ1cb36v0u5SwecflreLc9O7MvF@v318vRWTOPXk0fzmrDfi@3FOpzCLLBZqJIIDjfe3WwhOXnk2bQ/igxgFzar9fRKh8HHU/39GRRlMy7jo11@MU97uz2lCT@R@84nWuQTDiUL0I@wb72MW@YlEVxkm19s5BZ3nvrnupD/uuP4ikRn8rBIXTdLN/eSlvZsch@be21K/QvGvXqju3qz2V7cbbGBH348PcMcX3nwy0ewQ8r/dIMlvtlOKwzhXuDPywfuXfCmU6D806ers5NHj76844fVjxjg3cX1ZjkGvvzp4m66xNXH7vELfHiJT/0xx7j8yhiXHAPulUM88PPj88e84aFfFo/3HgU32VKfpgv@u97cTI@Xj4WG3N7dvL14Cy18fPt4enu/5X2f5LY10PxiO56d3i7f41hv3k0XQ5sw6/1yUnYCK7m9W26Waygd9H0@2IeE/BliOxmKvbkED1LDVebz8nb7Ws6UgLEBOfjqb2FfkzH5/fVWTuyrp8jxjs/Nnnv6Co4LP/PQzmVwfDozJdxp/qnd/nx/LNXv/WXufzZ4eD1dARfBwO5WH6ev71e29LtD2Sq4YlvDoZjsxr3fucjfEMuBVLiEg3t/1nt/xr0r3vIzBWeSg5h@@JmaZl9//lH0njfIit5d39zcne4Mm2uahYy7z/YM/fnz/VHFfDAt9G8FN7C6XG2nv/60XIM0A14VLh/r7Y8n3fjJo8/zUekvXxwNpL3DoS8OYj6CY1H5r4hq7OaVfHI/Qsr6Ac/86gA18KKP9tEX188nwJHh@eYH/@NDR/M7873awTu/P5tmiNYhAb1qCaQZvBR46eXkzo6OlnOF35xLhjofn/edwEaEe7/erN6vl1fT@p9X794dSvRB5YUNHFn1124Ls@Na3tIh@eW5d3I886QHZq/ByyknsJ2QoHGgnaV@TdJ7D83Y8PfaANFDnczbjcxuRnEuc@uXs@k1d/Hi79FPipZqf79ZTu@vgc/XwNG71QUlsb0BZAtHvrt5jzE2Jyf8Jgiy/Hh7N63frLZkREBhnq2DYI7H39xc/7J889fV9qc3myWEePr7kGMItcOwZxOn5eMnPBEb4cPW9x7rtFy/Z4B8yt8p9OMV2Obt74Ke4@6X5elu@L0Dk2fv1yucxoc3wp14290Kzgp7nOkXL06nUBBYHf73G3j3xSxHzmAhrPNy@ebtxeVfZE2nuh@g7P43ejGdg6LYlzonmr@@3D8SmWp8UaQdSQbLJjwSm909/g/YDdVYFf/Ro4t7qMBaZWG6v@NVeol7N/i9vL55L2z2T/OAwnL3locfX0zf8gl@FH@MMeUudc57kz1TgMRPj/@8fvzAND98KxdFKiR5COr3Hj@bDu6@Hbz7gYH@/PbPb3/8lhI@/mU6VaSxNcqX033F/O673bf9xZ@dKa//81om/EzZS@rmAUz8Cv7Oe/sqKughAYbpkt786d/3PSMAYXZvsuXhGUR3Bw@nl9Rnh2t8JveKJ30DG4cZwWhf7emxQszBkGsbUyQDNn569PjTaZEhkOdAf3lsvb@GDxcfj@5/pgOePXQzAocvBve7Bw42urzeXrw5WNq53bhbyiy4nV7rpTNECbsR9OZZoARhve3gh5/FOY8fhGIcK9R/3H9Y3q0ugbLLuzsc7lD@HWfZTXK@O82ZuYwtHJjF530u8oCBPgD7Asv/X2AsEEyi/vM9lvH@hoQcKLG9@4RBETRrok8J@4Ycnri8@DosE89wrGZmctdahfRG04Evccdr1ZMZaIc/gMn/6kNMudTWn/VWS04x@Gelt@yeldZTeJZ8Cc98cD58Vov5YiWc99BNHdj4cCyPOCuN4Xdg4O5M7wa0XtHb6@bMWndbvXqx59VhuYYTD7JKEdIFlH/H2S0WklTBHGLffxiYCqTYsaXtcjN4y19/Wl0PLvp@ub2Gc9Evl4ypMdqZLnQl9OqO/mn7iYr3Fu7wLy@G@HR2zX5MG3pDPvriSLrDX6oy8FebnqGiCUQYBU9gs13cLpd/OVW7txsvmbb6l//1r8yhffNgzDpQkM9jQ/b4oweG/CzTveOgr3TQvV092gWaL8Z935xyZ69l/WfzPIeubi2Lghbf3m8X0//e3tzi3C6uIJyFYf@jR7tJZAkqjcXt/eYndfscfngJzms3GK38hylQCMMnf4Enb5d3NLP9QHkzrWB6V1ffKbocjDec72L6xw30RcwXIff1hWY2EGWf7j8kCzRnxlHvllf366uL9Xbe3tjOza3uxrZyQse0Id0SUD3YEuBX7vp/CRIfWVjwUXMQGO2H8MR82170sPvpqf9xXomFJmP@l1N8WJqElIvtdL2kNKLm0DaL6U/v11pB4SGPfQMZt6u1pDx0EmFLe5H3q0NYIJsRD/UwEr7B7wOI9rBFH9lPYMi4ypbwyLO9x3f2d3lzLy7i2@9p@X@QA336VHFAeI08/90e8xr06ES1Y73TK6DV8m65vuT@ZXsX/Kyr@@7v4kV7KzzgczNcMabhhxcnIsnDLfzritnNA654Oj/5XMFtb1gM8Le//XDKeBgc@tQtXCqtJft6nhauxF74fdFDqKHJ5bhIqUUwifOyqKHUWuSyW4SWYs24jturh1s5@/Fkf/SYa8xhjO4X3vUKBzT5Re0lJC@X6wKeKJWKYeLCtVLcmLUmVwou@0XGTCUejF4Wzdfq6xi9LFLJ1fH7orocXJfLYUHvxmHiIgTOb5ezd557aovkfM71eOk9FRf3BNNrghelYHINOcnlvOg9NC87Si1321GAlBJ8reyoh9xaOVp6aQXDzV9da67L4CH0JNtvi@Dhm7n9tMgVMs8mxN5CaXK5lpTzoczDwuVUQp73UXN0nGiReo16cAVD1B5xLtiAbwnCt3tDLbXIZVdyCOlo1aHFmvzuOCHtjrEhBaxadQVyRaSbsXWcT/LgHiaR0hNOSw6zYV/9UN4QH6SUxmHmRcb8EWNXbKD02O0UsnOBoyRoZDQl7FgrlTAuwG8qzvfwIEtsLs@LDotYI7cOgUSIV4XaFr50H6Nocs0NR2aqGVxoncsOi@ZScMfLhhK5lHYiwUoidRKG4mER1SZN3vfMQ4Oy5@JMCRO0LOeOtWN0nEM91HDcW6OfzQc6ifm5GOhXwnq7zZmcKCqOA4Kqdi@PPVbZUOCJ5GHJ0EeXZSWhNiitnhpsoMXEoVOPmFZl1713Yt84Yg/VkMtJjLSMy9CTomM0sMhWqQ8J1lL8sUW5pOY5aw@WIicBret1LNw54IisO@biexpWDAH2yFOO2JrPKn5qJDffsZngWzA9jV0GgHUEX1WUMIriEg21YaSUDf5gd1Wl5KAMMc/AFmStZZGza/1gJ5HrrW1nYlCcVMXGCIFjCN9yoB1ASMHh0KuhlIuhJo4MOeN@VXefsP6qUNcAgM1EBpOQiXCcAbij06faxTZ49BXg1vQy7KS4QEDzGeg1rwO3NFEabKrUY4hOAKrax6lAut43jpEbsDuZlCrMQ88EChjL0BlsMYml5wh86nokPcck0AaEpQzstAvwvqk4SoHJmoYBg5PoAM/BpaF2vcfMsyoALW/qBW/Q7GBd8jHko1MBELsWdu4ALqZw7Azbit0H22CuvTez6Iyji8OKIGnFLQgstm6yjnADPJiOSUPSFVaYffW0TKyqwMnlAU/VZ26SuOBKmPcesJTGyyHm1KqtBLv0UXxt8xjkELiymGevOw/UgSA90QKyB4aN84XR@SjwByB3weQaC9atR5bglpKeDbwxJYh1ACoNQIEDDaqozioCKHSPuN6DL65QgDCB2ob/IQQnhcqcET9Gg9Dea1Ynjr2UWI/8Uow@9TQDZ4suFgoQfsEbDGc6D/F5MAPfgdMqCQdXKCefcJSuOD/wEBbvi2pEiSUOpxwcXLW6NwAs7G14ipCMrbjugG3DQjpWJgrhW8NRDMHG3NSsiyeSHO0HStRi3hkORiwkMXB1uTQ/U6Ti4Uhl9Azcj0O4MWfyhnN6raA78sSPFjolHmGswdt@sPlEzabDoDF7mxL4Ai/JKSPohEI/0A/o5kUJ4US9TghliymL44S/weUjN@Zyb7HtPA00LxVP99tAAs0AYV6FluPo28xCRPQ5N8NQIkU0bwBhcuM8VPCNNjAD6BC5Dg/ParoD2gefRFWjlKCtSkiga8FnQI@evId/8cOisIIkO4dCxyMyAYWJRaDQzQYIyPQK/oACde7wGQ0oJzgTAD5j4SAYjZ7iXBDMDybg4BCceMhAauJV2D5QnrJA2CtolckTXkx0ygPD/ezb4ELFRAhmvNskBaUXJ5Qh2AakPYJoGjvVfHBHT9LAVcfSQNbHMYA@CM9ZyPnPjAk2ItZaoX/g@lnVIYK4eNOoDmnqVfyc6JzohqD9pqzQ7QzwVo8DTey2SaBNSqIkGdqglBiqCKG6zhMGYJqvIDmHOZHfQd8D7zZPmsBGFP@httW8OsKBJhQXVlaDXZbjAJ/UgICUPQ4Dhl5G0TSfQFf8MfBULnSnDIgGopNThxCqHboHl65RDyxXALa5dmhdEH6GW9Mc9wANg09ivWCRsZu7bjDarJoD3Bl@C0ARvQVPxXv14gS4mrvYOnTFmGIjjiV1iB18STUkQWQtRJE0zBxu3k7LO6E0ieYQNGoChkD8XpYMWBsMFLoOvM2K2lSU7u26AyybhVENj7xqpvIBiWagABK5LDQqRToz2wuOxcsJgJaaY8FBA2eKcHh4uqQIIEbgYpQwDaGm8TPAAcOQJsvOwOloauMRKTRVX4jDKckg9IEDlkB1QpSE@@126Fv3whJBp6B/MwdKUXkUIDP5sRJQnyS8BuGEx6xdt9x8Fm33DDKcaRnEQ4pu/qBjxEF3qogbZtoQH4SjkAnutO7oFWhVD4WuCb4Y6OPKHLo6uQxtBSHT0LUteExBTCnXVr0hOWiwQDmW5Olok94MqtSrQmjEJyVeRKWgJAhmbjuHiMFw6IuJD3A@1XgXOJpTiEPsMhO6RnJukRsJRDVUQlhWlY7gQMPwSRB0oVqLeyI9MHIWheedSxAecpnJPsiLRpwgLIidjoEcv5a880vgmwKFnVZVRqQcYY5FiApIhgIigmNYV1GeB7dUnW0dEKf6C4GnNNAJcU6W9RVxqt4C4tDJR9S10YuNsA1bBPKKSAJAKRluFQTTYqUdDqTuWAq4alVCDFHZ2RZ40KQYB40oacA4rCA49aagESEYuYeOSeaErBUsoQzCUEBVVX6gaAiYjtl9rDr3oJxwUoRKsDWEpNWioEo/KAoPRpqN3SNmFLopOZ@YlCcDACJUrqikPCIHA3JyOxLiSp1UgCL7QvDE6chhHKQzHAcgvYir6rgczPlAiQL9GpknbCYMnMQRFMFJEN1mrhTHh/MtXSOHFr2tDmIq1YIu2LYy8ChROQNnkmrn0/D/kF5Sq@tAsxaPAgrss8RZFWH7LmWKDkFuqLY6oKewWoIMDjENggJpROZGYICAKmVQJLJwx16zMXnwuAbrL7Wp6YL0xj7DFphNVmyBM8izu@saGFBFQKzMmODTI4ISNVS6WLXfwNiyJyGmiIZdHaElo1MN1keQDRSEI1IxAeLCeB663tTZVazZG7rz@a6xDshbO/S6wBXJqg3NQ5AB3uCrclVEuEZ9EF65qgnBEo1YgG6QnYuRIrIJftDgFIJ63UyNha7oTjICe8t0gL7HmRDFCnHLgcHuSrG7AWV06NgrkGDMJ9yXwOndyOB10kpLCNW8Y6SVYYwKGQR2HDiZQhLfz9wB1LSM9CogM2hiD07N7I1EOmncwlgZR3IoOwB8mFNWlUG@GAb8PAK1kRtwCDaZ2ZNIhXHLCDiYFVRxADOaJVNhxAm0NVhiBTTdMg/wGkN6zH/0geNQH5iE2DmoedWES6IyBPMFsLoyAt/QLUyGZoMopTLjapbsGKTtcuwjyokaMIgIRx6L2Q7QQclUOJKqZASkiasi8oCJeFsGNkbKTK9c3BFjBh9lTJlmFOxNSQRRg0kLOwVoeNWkK6L1ZKnRjBU5XTJIfDMpIZoQKoPlECFHHiw3iVqosaCxbUATTNj4PEPybPsA@Sec8CjARwfvgZkUsy7HHPqIPrHVUCRQYqJc0bcoW8uScsHIChRVwtaiUTMWopSPIWSVE4zid8xhgPmWIjgN/W@hPpQsjbMcETbF1BQkCjz7YCuYJCWLbnLpFqbjVu@7ZH57tHwLOTnAoZqLd6FbmAATj0EDYMAcLFBnhJv1SVhFx73eIIjUwBUNeeDBRh6MXjgPhxFjscOHe7RMU6eDyjPv7IL2nWFCn4sMsPnoZEaGpnOuoOEQux44wLeMxKfkpfgrwqdu0MbQIWtGHlGO96a4HjeJmjcqVZ09fGUegFJiHDJjPaQYQ7d8Lc5oeOESmnGYxmBq/7g6JIDIJ@9S/w6RuBgQ4C5mc344ukyPXaClaU4dwNF0zT0V4OpIJTsWeiSuDmwV6KZ1oEdenBmcZ5wTJJ2hb6VAQVnCXJ8gwXISnzZCy8AlxFRClEVpYvFpiBTnmZUHgZT6OpJ5oAvK@2sacTW/QMUke0dCm5kEHLdbcIOwydK4UCFmKTSoq212ziwpJEmFRIgrxEEzQsp6byeijNQTLDzoqpnObBamJctbMmeEUM8NVlKZBJAYofajjBEon697sUBl5i7TxWiCMoy0IDhTlSlhR5BUMNMHfLiidRVmZ2whgDCXFdWxoqqMrvLMq3p3wBVwZ9iiU5dByIijjAeEYZJAFgJ/3MNwda73kUkHn4Am7gitMCE6ktTySCNmkmWv6X@iiHnnUiR35STP1Uf8lkmENFsItXZqYPTUgDdxzzjPmscCQ4I6VxM3nac5EkTWSdMSIMpxBosuCW9PVl97GvlG0E/LsOeQLB1P2gzt10wN4Aak@Ch7AHcWXNnLKsPrakEN4XcOI0PS4C1SM68bgrIN5omh0aquUKpk7LUi8gULFVnB0XnDSgYFThbD/FCwmIokD9grQkGMkmcaCLBKUcsOYHXDnxB/VF9hhMP748mILauoMow8jsRCc064DyuvwK7hzwXzoq6vWejOYBzKVkR/Uh9ZOtgtBCemEyR34oxVZc@yh6TOPYU2GyVWGBUW/bA/MiVSZo1kEqK5NBKTiPO86iDMb3gJoFdRpwkKD/w6irpBXiR9aXwKxCE52Y3vI0/KFHnPeTC8AVQN1hVKErKAQHx2Vx78VeyMOUlnHIJSA3en6Wgtr2hcBoTxpVtqBljiZ58ixUt@ymlUDZgZj5p/Z40M8DEnMxJLGOKZcNKjJodBmik9dNer12NMVWQ3jEKx3TE2uIPrGtjmaFlYZpxSaEFN1Vt6kp4wOKuMUtbGksAmk9UunMJfX7BElSzqAVONZS6ESWaSh8V8nuXW4KRyFoMEah4XrDu1t8yRQmbRrjXJ7GQc1eCGpXlJajM95MKAORyhyIJUDFsqg/iwYCAaFkCMVMMYjfosiTgcCg6ijP4Ali2ddR84u5vJergj9UtQ4zRHFRBH9JaRJvqVESvC2IrMCd879IOBW2hZU/SAImsbaPATQTLPwBdGLLuSg1NZN@qeNz3otA0tUGQmcUzahdW3KmIFbamjhAIod04zBXQ43fQDvjo7CT2ZAZkRBw48FdU9EHjfxyhMtHr1Td4fdV6wmNdLLntFw5alhAIvBQUoIwjGhN0UG7OUZkvp4DRVwx/QeDcUG0NIIJKI8VmJESQBxCuaPYF@zoVz6KfT7eAxZxE90RyUqGt6DW5lFOAQATtrMCFD6gP9GNlIztHBt7qRxWGiv8lRdsLFCP8lNaZqZFI9l1RgtHweZJBnnQIFalUrmBCWcR22kDRhYoBMl3fUj8GmElby81Hyjqw9W/KppjimbMCcqGWs0gacsboL/dIkDmTg63EyI4D/7qwMIpPUJ@vNvuZh7Ax0s3JhZkrndBdgpDNocJm5bANyphYtowxibM6a3EO6QpQo1GJpabafRsvu5DpKC1Io7UF5F4A8lzhKAN1ZrQ5RX9ewPIs0o8Q0bHqYi8s@4Ew0SPRMj47uCkhNQLjH6maOFhIi4SQrifAzBmmeVFGhJOY@JyiBDEr0QEKA2GFUi5kM5CFk4lFTc2LaVLgBmQcC/BEPAoIlV01BYnnNlI/0VXQPgonHoAhSHMpeX1ZBxBys@6j0Wc1wGlm9vUd8v0cNctWeEMRLeS/rm1zWtBvYwFydjimKJUEnwkzucfqS3qEeMpc04iLorZ4jNQdCmHNVjtVNZlvA99qc2G6sFwnmwpBHK4ZnEk6aXgqgPs81RxfVO0YQKLdT9xC8Fq1JaIwBNPagiKirlNpGWIORi0aVNJI2ztwzM6uZNILLqDlEBOKSAWiBt9vBICDK2tbEErQRABx@DkoAsEwWKI4S/T5Jgna0GSHA8lLtMsUjSIIVd20OgCzmhBJbJ5J1GDFPMRoPfOVO6LdTnlOFPHCrjDHBNmoT8ENSJ8UYrG@MQ6zEtWZxkXEZKU6BDGv6n3nskc5IEHVSLgOf7EZRutADZK17sKJkNzPdZVXSWKx1I0kzltkWgEx1Xf1dSVppdXEUBQm7NfRgmA8yO3o0HBaSpXIE5WkpjNpTExii@QFiht8IsUr2g60QrnQrzCJk7Fn9d2MavRz3mwEyWt1VFopVmpm/K/PYYBc@aJwHRhwGdQwB0biYIyhYta1nqZ5KQyGCsjnAQAii1V1cp9MfeyRWaPIZB1ZG9S46pvisL6CFUREt7GMwa2SaeUALeUyWxAioSy7DlBKUVauIwKnohguL2vGIlUDYuRnhTZxTS/KMydo4GwCwD1YwdL7aIQA5gnQqFRpKm50Y5rNGyI4obwgqMTgWYoAgp47SUWS2XSCngFP2kYlByGrZJmHYc2G7ErElFdPAw8xKm/BA9SdlMEKEGsBS3xQSAS4zq4flZWsJ8ayltZl7J4m4SOtrOdISo0F@1@kF7qBmBv7ripXNmBTyo8PDDW1lL6rzqvLUZrsX8ovCF7A4QzPoVifHFLaV1QiEFYTQlDnWWAYRTnQWUuuCT0lzJFxKLZIirpEpu9lrsClOejDYQDajYYiR5SvSqLJrpGTCsIqhp7zrx2NYk7TDAaZgjQ8azTe1fzhlSwoRXosMrcmokQRgrauYx/XWjSQBd5CMXKSDtkqwFFL0wMlgEf2VNpdDorOeJtaNRviJqD0lI46IB@LoKQGFiVErkWybLKNMAsrXkzEO9nGN3Fdky6lt1MW5Y8WxN9miNqhWO26dAWrl0PdaT7ygAPNW1e88cs/BMKq3OXPIQMEaGjqz4mbtDCqddWcgXI5GuDzolHYsk5zFPvdRwq177Znyo/GDDbdd@sIIQfBcvc0Nba0ooiE0LXMOKLsilIFrRaybwswIG@2DtR/4YVtgZHpA0u/JD87G7AQ4nlIakt65XBUsv4dQvRZL4ANFmiYJsZNSRlM2vLdremZA3hpGvE8DktwXGEBoZndwQBq4EQLS6LxkB3TWlisulO2NQyEQiQXtc6v45OeSKxA6WlqjwiMNQu1Y5hWkYwuJG@4GfkrVgYXaOgbJZMZa4a5czTH/hr@MeU7@kYBnSVF4iePa3GkZhA1LG8fIC3lmAoL6CrYsj1MA@0paBMH6Uk3zNpkvFe1xtNEZOSI0X/NF8Kndj57vLH6ctV84k3EQwDTp3D@XjFKcY1FAp/PWZYBIL7bRCgRgFj8EupxHJo7JLCfHBkNozugfW7ttRqhinlsgghNqQzwBMI5MFFyx86KAIPZFyWKnqkk1UZs43Ojipp@K1VoVgmVrqR5JUxti8nNbHQhC9cKSM1OC4zIg3Bf1teSnfe5gr@x9VWMNabSokGg66UyW/F23NCRdGzFKlxiphyNn2cdKOpMaxzQSYH/QxJqj9pwgyHV2lFJpab5pZ2aoM7JVxuHWZQ5kbYOY@Ki9A8QkhiIjDY4ISxvnSQjnrhh77UCcd6qjEQqUuBibypY9TewL69p4Ad9tEUXgAVt5OkKJ0ojGAGlJm9dh5LNqNzoSiZRbKNZ8wHaRpH1/gHp44DoS2OxEqeI@gZAuzDhaeNya3OAbJjPysFdCNJ5doGmuI@OYujZKuzSXRBD0h5AtHzjobxTpaRtoZgu2lUTAmYR@0D9ihZaSIQmqGoNLLWZwS56/FogA52apPEWWh0WouOZnP4wwIRlPw5OApqMiXWDnRpmRxcWiSApcioOmsTG8SbtdduxQmltdm0Z18u5OKxaLIsCWNhGIEowszZABq4nBGmwBNdEyuywuWJLZJ4b7lvTsTNDQ3B3o5ZAUixwlG4zuwsUK@PesHbGaYLUP1nVrs3YKmGGfc3QssWhkTeWZAxkGe/bWhqe8R82RLxcVad93pFlW8O2O5FVOEmA0F9i0H1/qbn7XpQa0TPYiVE4mJhhV8xoguVjnlgLW4EJTv@z7aG3gWyvdivzMctkiGJcESUowpzsnTSr5abf@HgtFYUlNKmkMJ5l9sOxtZpomqL@CX/ziRQu2loSy1zTF3nvJIzvA0GgLgdLq4Im8OrfZOrq2FHnpSx2vBkGLoloBrLTuXi5gXNckx8/Td3UUfbT3SgqKYU42smsua/cA@Gq3cKXSfWljh/QGRD8QIwNHinIH6GrpJhUgTQmac4NYw3h5qbBLXPhOZpNfHAGBVknICyrbjnZRRR6qXUe6W8iDl14ySoKZ6fHaBhyV5jIpl1F6Z9oF5qc9C1i6nzPeXfqN2EcBL@2sWaix8Jw0WRiMf5Aawt0lkSE0oo8gqbFOLO4QwaR5MiAWVbhpPiVaH53oWtP8KxB59woKMcgydE6Y4SFzxdIl6hg94N1HfbuIby45S6bjDKK34oSHXc/NGjhg6/hgS02dy/1k@Mp/WdLOGn4xgRSLZZ9NeFFava2XLLMUXucYB8BstSAAgqVxC/tmJIfJaUA9Rms7DkaSDmwn7kE7KBoLShY/ScvDKKo4NuIYf8vAo7pHHbTfAqfRhreG2TWL/x27HAdogDpov6vvVJJhI25UoT2rEUPVWMISIglukfPuNQVsUtGrSQtgHJUHAEGQHo/GosJsaomvLQnnZtJ@4Hy0DnaKwI2KP/tPzN/AWVs6iNFe9dKfyN640T4FFJB2CeJjPX4PsvDVQ0l8z@@LAuKKNWxnhXNWtqMV6aD5c5WJzdia9OGrXmnkqvhupIta1oqlWjyP8FTzCpkvdfU@J1qj9thIqhja0uYuimYsUtI7o4GdSRxdCd/FcUNbEf@EIhnslPmuovWCsu5mLY6g53XoQupdc/qANGuCiEzaCX2mmfJVq5GfZNNvFbOBUGOytltszRv6Z2anrZ2AOeaqUQIktXsrrzmvlVXGPSXP1@E6pdCpb@DOqdJIkjMMG6Psmv0RUUpgn4ENI5AhFVCFcsnPr1iB2Fp2J7qoBCEwCZKjAhfW0weeQw7eao5gLP3oxVAnuay5VdLT6TYnvX4w16RHySYHJp0s2E1Gxzo5YjHahfDV@tIqDLxFBTqq3NgKfHy2jTOFHYdncezNCBaWtDqfOwMj4ZFQZL7gaclcmpLWCxwB1XbJPHLq1iHnrfWWL35oXRWeLpTxCgYjZKkkwnw0WcgUISgSoze@UgV6MLeyON90DQzp0vxqqTRPjNf46mBRbKr1YjVdWm3nvmov6aQoRcL59SJwj2Bpac800VxLY81EWU1uxifYhAAU0VyuBOADL/h6tbamMeSNffQdghWMVzHjnJhC5B@1KzUAnrwF/7E346ysM0M//hs "C++ (gcc) – Try It Online")
The main part of the code is the `solve` function, which is given a floored distance matrix (as a 2D vector of `double`) and output a vector of `point<double>`. The rest of the code are score-calculator.
Idea: Start with a (seeded) random set of points, loop `n_iteration = 200` times the operation: For each pairs of point, get their current distance and expected distance (which is estimated to be equal to the distance in the floored input matrix `+ 0.5`), and then change the position of those two points to an appropriate position nearer to the expected distance.
For this program, the new length is calculated as `min(max((old_length + expected_length) / 2, expected_length + 0.5), expected_length - 0.5`, which is twice closer to the `expected_length` if the `old_length` is sufficiently close, and force it to change such that the absolute difference between new length and `expected_length` is no more than `1` if `old_length` is more than `2` units apart from the `expected_length`.
It also tries multiple seeds, and then pick the seed which gives least error in the resulting distance matrix.
] |
[Question]
[
Given an integer `n >= 2`, output the largest exponent in its prime factorization. This is OEIS sequence [A051903](https://oeis.org/A051903).
## Example
Let `n = 144`. Its prime factorization is `2^4 * 3^2`. The largest exponent is `4`.
## Test Cases
```
2 -> 1
3 -> 1
4 -> 2
5 -> 1
6 -> 1
7 -> 1
8 -> 3
9 -> 2
10 -> 1
11 -> 1
12 -> 2
144 -> 4
200 -> 3
500 -> 3
1024 -> 10
3257832488 -> 3
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes
```
ÓZ
```
[Try it online!](https://tio.run/##MzBNTDJM/f//8OSo//8NDYxMAA "05AB1E – Try It Online")
**How?**
```
Ó exponents of prime factors
Z maximum
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~62~~ ~~57~~ 56 bytes
```
lambda n:max(k%n-n%(k/n+2)**(k%n)*n for k in range(n*n))
```
[Try it online!](https://tio.run/##RYyxDoIwGAZnfYpvaWhLifS3LiT6IupQo1WCfBACiT49ppPLJXfDjd/5NVDWhCMu6zv2t3sEmz5@dKdYUelux1KMtdmNJdIwoUNLTJHPh6alMWuO/Edx8HuDEmcfgoPUtcMhw9cSrs12M04tZxQqLKhOULIUUNB0SDrvfg "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ÆEṀ
```
**[Try it online!](https://tio.run/##y0rNyan8//9wm@vDnQ3///83NDAyAQA "Jelly – Try It Online")**
```
ÆEṀ - Full program / Monadic link.
ÆE - Array of exponents of prime factorization.
Ṁ - Maximum.
```
This also works in [M](https://github.com/DennisMitchell/m). [Try it online!](https://tio.run/##y/3//3Cb68OdDf///zc0MDIBAA "M – Try It Online")
[Answer]
# [Ohm v2](https://github.com/MiningPotatoes/Ohm), 2 bytes
```
n↑
```
[Try it online!](https://tio.run/##y8/INfr/P@9R28T//w1NTAA "Ohm v2 – Try It Online")
## Explanation?
No.
[Answer]
# [Python 2](https://docs.python.org/2/), 78 bytes
```
n=input()
e=m=0
f=2
while~-n:q=n%f<1;f+=1-q;e=q*-~e;m=max(m,e);n/=f**q
print m
```
[Try it online!](https://tio.run/##BcFBDoMgEAXQPafopolQiUK6Ev9hXAyBpDMFg7HdeHV8r/xb@orvXZClHG3QisCYVYRXZ8ofuqwsFfKMqwvxBWdrIFRjLwoM3n4Dj6SDTIjGVFX2LO3BvbvZv28 "Python 2 – Try It Online")
-5 thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs).
This answer doesn't do prime checks. Instead, it takes advantage of the fact that the highest exponent of a prime factor will be greater than or equal to the exponent of any other factor in any factorization of a number.
[Answer]
# [Haskell](https://www.haskell.org/), ~~61~~ ~~60~~ ~~50~~ ~~48~~ 46 bytes
-2 bytes thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor)
```
f n=maximum[a|k<-[2..n],a<-[1..n],n`mod`k^a<1]
```
[Try it online!](https://tio.run/##HcZNCsIwEAbQq2Sp8BkyMVUL7RE8QYh2QIshnbH4Ay68eywuHrwbP8t1mmodjfbCnyxvifwt3SZ6azWBl9F/Osj9MpQTd5SqcFbTG@H5eDar@ZH1Zce1iR5bBDTYYY8DWpADEciDQoB3Ds2CnA@p/gA "Haskell – Try It Online")
### 45 bytes with an import:
```
import NumberTheory
maximum.map snd.factorize
```
[Try it Online!](https://tio.run/##DcmxDoIwFAXQ3a/oqMlN0z5aqQOfoJObMaZqCQ08IKUk6s9XhjOdzi99GIZSIs9TyuKy8jOkaxem9N21DftP5JUl@1ks41u2/pWnFH@hsI@jaMQW54fYzymOWbYHcSNUMLA4oobDCVpBa2iCNgakFOxGKzKoyNauIuPcvfwB)
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), ~~9~~ 7 bytes
```
k ü mÊn
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg=&code=ayD8IG3Kbg==&input=MTQ0)
```
k ü mÊn :Implicit input of integer
k :Prime factors
ü :Group by value
m :Map
Ê : Length
n :Sort
:Implicit output of last element
```
[Answer]
# Mathematica, 27 bytes
```
Max[Last/@FactorInteger@#]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zgq/DfN7Ei2iexuETfwS0xuSS/yDOvJDU9tchBOVbtf0BRZl6JgkNatLGRqbmFsZGJhUXsfwA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 4 bytes
```
YFX>
```
[Try it online!](https://tio.run/##y00syfn/P9Itwu7/f0MTEwA "MATL – Try It Online")
```
% implicit input
YF % Exponents of prime factors
X> % maximum
% implicit output
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes
```
ḋḅlᵐ⌉
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@GO7oc7WnMebp3wqKfz/39jI1NzC2MjEwuL/1EA "Brachylog – Try It Online")
### Explanation
```
ḋ Prime decomposition
ḅ Group consecutive equal values
lᵐ Map length
⌉ Maximum
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 5 bytes
```
▲mLgp
```
[Try it online!](https://tio.run/##yygtzv7//9G0Tbk@6QX///83NDAyAQA "Husk – Try It Online")
* `p` – Gets the prime factors.
* `g` – Groups adjacent values.
* `mL` – Gets the lengths of each group.
* `▲` – Maximum.
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 19 bytes
```
⎕CY'dfns'
⌈/1↓2pco⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97f@jvqnOkeopaXnF6lyPejr0DR@1TTYqSM4HioMU/E/jsuDiSuMyNTAAUYYGRiYA "APL (Dyalog Unicode) – Try It Online")
**How?**
`2pco⎕` - 2D array of prime factors and exponents
`1↓` - drop the factors
`⌈/` - maximum
[Answer]
# Javascript 54 bytes
\*assuming infinite stack (as do in code-golf challenges)
```
P=(n,i=2,k)=>i>n?k:n%i?k>(K=P(n,i+1))?k:K:P(n/i,i,-~k)
console.log(P(2 )== 1)
console.log(P(3 )== 1)
console.log(P(4 )== 2)
console.log(P(5 )== 1)
console.log(P(6 )== 1)
console.log(P(7 )== 1)
console.log(P(8 )== 3)
console.log(P(9 )== 2)
console.log(P(10 )== 1)
console.log(P(11 )== 1)
console.log(P(12 )== 2)
console.log(P(144 )== 4)
console.log(P(200 )== 3)
console.log(P(500 )== 3)
console.log(P(1024 )== 10)
//console.log(P(3257832488 )== 3)
```
[Answer]
# PARI/GP, 24 bytes
```
n->vecmax(factor(n)[,2])
```
If I do not count the `n->` part, it is 21 bytes.
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 25 bytes
```
@(n)[~,m]=mode(factor(n))
```
[**Try it online!**](https://tio.run/##y08uSSxL/Z9mq6en999BI08zuk4nN9Y2Nz8lVSMtMbkkvwgopvk/TcNYkytNwwREWIAIQxMw29DAyETzPwA "Octave – Try It Online")
### Explanation
`factor` produces the array of (possibly repeated) prime exponents
The second output of `mode` gives the number of times that the mode (i.e. the most repeated entry) appears.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 7 bytes
```
eShMr8P
```
[Try it here.](http://pyth.herokuapp.com/?code=eShMr8P&input=1024&debug=0)
[Answer]
# [Python 2](https://docs.python.org/2/), ~~90~~ 84 bytes
```
f=lambda n,i=2,l=[0]:(n<2)*max(map(l.count,l))or n%i and f(n,i+1,l)or f(n/i,2,l+[i])
```
[Try it online!](https://tio.run/##DctBDsIgEIXhvaeYjQnYiQK2m0ZO0rBAa3USGBqCiZ4eZ/EW70@@/dfehV3vm08x39cIjOQdJr@YMCu@OX3K8aty3FU6P8qHGyatSwU@EkReYVMiBitVopwLofBhoaD7JomAGGrk11M5tFc9LHYc0RmDk8waN4b5ALBX4iaedP8D "Python 2 – Try It Online")
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), 4 bytes
```
ḋ)⌠)
```
**[Try it online!](https://tio.run/##S0/MTPz//@GObs1HPQs0//83NgMA "Gaia – Try It Online")**
* `ḋ` - Computes the prime factorization as **[prime, exponent]** pairs.
+ `⌠` - Map and collect the result with the maximal value.
+ `)` - Last element (exponent).
+ `)` - Last element (maximal exponent)
# [Gaia](https://github.com/splcurran/Gaia), 4 bytes
```
ḋ)¦⌉
```
[Try it online!](https://tio.run/##S0/MTPz//@GObs1Dyx71dP7/b2wGAA "Gaia – Try It Online")
* `ḋ` - Computes the prime factorization as **[prime, exponent]** pairs.
+ `)¦` - Map with the last element (exponent).
+ `⌉` - Gets the maximum element.
[Answer]
# [MY](https://bitbucket.org/zacharyjtaylor/my-language), 4 bytes
```
ωĖ⍐←
```
[Try it online!](https://tio.run/##y638//9855Fpj3onPGqb8P//fyMA "MY – Try It Online")
## Explanation?
```
ωĖ⍐←
ω = argument
Ė = prime exponents
⍐ = maximum
← = output without a newline
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/): 30 bytes
```
@(x)max(histc(a=factor(x),a));
```
1. `a=factor(x)` returns a vector containing the prime factors of `x`. This is a vector sorted in ascending order where the multiplication of all numbers in `factor(x)` yields `x` itself such that each number in the vector is prime.
2. `histc(...,a)` calculates a histogram on the prime factor vector where the bins are the prime factors. The histogram counts up how many times we have seen each prime number thus yielding the exponent of each prime number. We can cheat here a bit because even though `factor(x)` will return duplicate numbers or bins, only one of the bins will capture the total amount of times we see a prime number.
3. `max(...)` thus returns the largest exponent.
## [Try it online!](https://tio.run/##DczLCsMgFIThV5nlEbLwlsZWAn2P0sXBGCo0CokpeXvrbv5vMSVU/sWWMeOlYWAx4oYJDncoCaWgNJS10LKX1BZGj5Mz2jr39u1Jl9j4ok86aiCeVw617B0HFsK3texI/VrhgXxu8UtZDFgoiY6cD8p9Co@Yl87tDw "Octave – Try It Online")
[Answer]
# [Racket](https://racket-lang.org/), ~~83~~ 79 bytes
```
(λ(n)(cadr(argmax cadr((let()(local-require math/number-theory)factorize)n))))
```
[Try it online!](https://tio.run/##HYxLDsIwDAX3PYUlNvai4iMuZFKnjUgcsByJcjXuwJVC6VvNzOIZh7t4P2TWGWyXASeJSQViU@j4/aASBp4M2ebCL9gZszgS5ho4jybPlkygsC9HbeUmNvoi1VaKHLxaegspbes04MOSOuD//ny6XLf4Aw "Racket – Try It Online")
(I'm not sure if there's a consensus on what constitutes a complete Racket solution, so I'm going with the Mathematica convention that a pure function counts.)
### How it works
`factorize` gives the factorization as a list of pairs: `(factorize 108)` gives `'((2 2) (3 3))`. The second element of a pair is given by `cadr`, a shorthand for the composition of `car` (head of a list) with `cdr` (tail of a list).
I feel silly doing `(cadr (argmax cadr list))` to find the maximum of the second elements, but `max` doesn't work on lists: `(max (map cadr list))` doesn't do what we want. I'm not an expert in Racket, so maybe there's a standard better way to do this.
# Racket, 93 bytes
```
(λ(n)(define(p d m)(if(=(gcd m d)d)(+(p d(/ m d))1)0))(p(argmax(λ(d)(p d n))(range 2 n))n))
```
[Try it online!](https://tio.run/##LY1LCsNADEP3OYWhG5kumoRse5gh82FoYgaTQu/WO/RKEzsUvJCeLKRhfaWj37YghfQyA2LKVRLlt1DH7wvhP0KjSDujZjxRVtMUOTLuHuBxWZ54ZEZD0LKHj/ftw4tiWG0n0ezarvOAplUOgo9N47wYPAE "Racket – Try It Online")
### How it works
An alternative version that doesn't import `factorize` and instead does everything from scratch, more or less. The function `(p m d)` finds the highest power of `d` that divides `m` and then we just find highest value of `(p n d)` for `d` between `2` and `n`. (We don't need to restrict this to primes, since there will not be a composite power that works better than prime powers.)
[Answer]
## [Alice](https://github.com/m-ender/alice), 17 bytes
```
/o
\i@/w].D:.t$Kq
```
[Try it online!](https://tio.run/##S8zJTE79/18/nysm00G/PFbPxUqvRMW78P9/QxMTAA "Alice – Try It Online")
### Explanation
```
/o
\i@/...
```
This is just a framework for simple-ish arithmetic programs with decimal I/O. The `...` is the actual program, which already has the input on the stack and leaves the output on top of the stack.
Alice actually has built-ins to get the prime factorisation of an integer (even with prime-exponent pairs), but the shortest I've come up with using those is 10 bytes longer than this.
Instead the idea is that we repeatedly divide one copy of each distinct prime factor out of the input, until we reach **1**. The number of steps this takes is equal to the largest prime exponent. We'll be abusing the tape head as the counter variable.
```
w Remember the current IP position. Effectively starts a loop.
] Move the tape head to the right, which increments our counter.
.D Duplicate the current value, and deduplicate its prime factors.
That means, we'll get a number which is the product of the value's
unique prime factors. For example 144 = 2^4 * 3^2 would become
6 = 2 * 3.
: Divide the value by its deduplicated version, which decrements the
exponents of its prime factors.
.t Duplicate the result and decrement it. This value becomes 0 once we
reach a result of 1, which is when we want to terminate the loop.
$K Jump back to the beginning of the loop if the previous value wasn't 0.
q Retrieve the tape head's position, i.e. the number of steps we've taken
through the above loop.
```
[Answer]
# Julia, 60 52 40 bytes
```
f(x)=maximum(collect(values(factor(x))))
```
-12 +correction thanks to [Steadybox](https://codegolf.stackexchange.com/users/61405/steadybox)
[Answer]
# [Actually](https://github.com/Mego/Seriously), 4 bytes
```
w♂NM
```
[Try it online!](https://tio.run/##S0wuKU3Myan8/7/80cwmP9///w0NjEwA "Actually – Try It Online")
```
w♂NM - Full program.
w - Pushes the prime factorization as [prime, exponent] pairs.
♂N - Get the last element of each (the exponents).
M - Maximum.
```
[Answer]
# [Python 2](https://docs.python.org/2/), 64 bytes
*-4 bytes thanks to H.PWiz.*
```
lambda n:max(a*(n%k**a<1)for a in range(n)for k in range(2,-~n))
```
[Try it online!](https://tio.run/##RYzLDoIwFET3fMVsTFpyTdqKLyJfoi6uEbRBLgS60I2/XgsbJ5nNmckZPuHZi4tNdYkv7m53hpQdvxXnSlZtnvPJ6qYfwfCCkeVRK1lA@weO1l/ROoZ6ChMqnB1hQygIW8KOsCccCEeCNak2NR1skXZnEtkac82y2eln52IpM6QMo5eARnkdfw "Python 2 – Try It Online")
Port of [H.PWiz's Haskell answer](https://codegolf.stackexchange.com/a/145941/68615). I'm only sharing this because I'm proud that I was able to understand this piece of Haskell code and translate it. :P
[Answer]
# Axiom, 61 bytes
```
f n==(a:=factors n;reduce(max,[a.i.exponent for i in 1..#a]))
```
This is the first time i find it is possible define the function
without the use of () parenthesis. Instead of "f(n)==" "f n=="
one character less...
[Answer]
# J, 9 bytes
```
[:>./_&q:
```
Max of `<./` all prime exponents `_&q:`
[Try it online!](https://tio.run/##Xc@/DsIgEAbwnaf44mBtYurdARZJ8EUcHIzEuBjT2WdHWxOaY2D4wf35eJY8IUUQfqdc4nk4XLfvWHqzGdDlFDvs8YnIkzHmfnu8sMuQHglcaTXdTKn0@vWoOWqGmbbypEcx6WrmxtLUuyWLW4MT6QW@vWCSpYdp/Z74MVhx4R@ufAE "J – Try It Online")
[Answer]
# APL(NARS), 15 chars, 30 bytes
```
{⌈/+/¨v∘=¨v←π⍵}
```
test:
```
f←{⌈/+/¨v∘=¨v←π⍵}
f¨2..12
1 1 2 1 1 1 3 2 1 1 2
f¨144 200 500 1024 3257832488
4 3 3 10 3
```
comment:
```
{⌈/+/¨v∘=¨v←π⍵}
v←π⍵ π12 return 2 2 3; assign to v the array of prime divisors of argument ⍵
v∘=¨ for each element of v, build one binary array, show with 1 where are in v array, else puts 0
return one big array I call B, where each element is the binary array above
+/¨ sum each binary element array of B
⌈/ get the max of all element of B (that should be the max exponet)
```
] |
[Question]
[
[Life-like cellular automaton](https://en.wikipedia.org/wiki/Life-like_cellular_automaton) are cellular automaton that are similar to Conway's Game of Life, in that they operate on a (theoretically) infinitely large square grid, where each cell has exactly 8 neighbours, and is one of 2 states, namely alive and dead.
However, these Like-like versions are different in a crucial way: the rules for a given cell to come alive and the rules for a given cell to survive to the next generation.
For example, classic Game of Life uses the rule `B3/S23`, meaning that it takes 3 alive cells to birth a new one, and either 2 or 3 living neighbours to survive. For this challenge, we will assume that neighbours do not include itself, so each cell has exactly 8 neighbours.
Your task is, given a starting configuration, a birth rule, a survival rule and a positive integer (the number of generations to be run), simulate the Life-like automaton using those rules for the number of generations given in the shortest code possible. The starting configuration will be a square matrix/2-dimensional array or a multiline string, you may choose. The others may be given in any reasonable format and method.
For example, if the birth rule was `12345678` (any living neighbours), the survival rule was `2357` and the starting configuration was
```
0 0 0 0 0
0 0 0 0 0
0 0 1 0 0
0 0 0 0 0
0 0 0 0 0
```
the next two generations would be
```
Generation 1: Generation 2:
0 0 0 0 0 1 1 1 1 1
0 1 1 1 0 1 1 0 1 1
0 1 0 1 0 1 0 1 0 1
0 1 1 1 0 1 1 0 1 1
0 0 0 0 0 1 1 1 1 1
```
If the number of generations given was 10, the output would be something along the lines of
```
0 1 1 1 0
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
0 1 1 1 0
```
You do not have to handle changes that happen outside of the bounds given by the input matrix, however, all cells outside the matrix begin dead. Therefore, the input matrix may be any size, up to the maximum value your language can support. You do not have to output the board between generations.
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code wins.
## Test cases
These use the `B/S` notation to indicate the rules used
`B2/S2`, `generations = 100`, configuration:
```
1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0
```
Output:
```
0 0 0 0 0 0 0 0
0 1 0 0 0 0 1 0
1 0 0 0 0 0 0 1
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
```
---
`B1357/S2468`, `generations = 12`, configuration:
```
1 0 1 0 1 0
0 1 1 0 1 0
1 0 0 0 0 0
0 0 0 0 0 1
1 1 1 1 1 0
0 1 1 0 0 1
```
Output:
```
0 1 0 0 0 0
0 1 1 1 1 0
0 1 0 1 1 0
1 1 1 0 0 0
0 0 1 1 1 0
0 1 1 0 0 0
```
If you need to generate more test cases, you can use [this](http://play.starmaninnovations.com/varlife/) wonderful simulator. Please make sure to limit the board size
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~24~~ 23 bytes
```
xx:"tt3Y6Z+1Gm<8M2Gmb*+
```
Inputs are:
* Array with birth rule
* Array with survival rule
* Number of generations
* Matrix with initial cell configuration, using `;` as row separator.
[**Try it online!**](https://tio.run/##y00syfn/v6LCSqmkxDjSLErb0D3XxsLXyD03SUv7//9oQwUjBWMFEwVTBTMFcwWLWK5oEN9UwTyWy4gr2kABCq0V0JiGWEXBMBYA) Or see test cases: [**1**](https://tio.run/##y00syfn/v6LCSqmkxDjSLErb0D3XxsLXyD03SUv7//9oo1guEDY0MOCKNlRAgdYKBqjQWoEeKmIB), [**2**](https://tio.run/##y00syfn/v6LCSqmkxDjSLErb0D3XxsLXyD03SUv7//9oQwVjBVMF81iuaCMFEwUzBYtYLkMjLqCwgQIUW4MpOAfEgEJrBFPB0BqsCAKR9ADpWAA).
For a few bytes more you can see the [**evolution in ASCII art**](http://matl.suever.net/?code=xx%3A%221%26Xxtt3Y6Z%2B1Gm%3C8M2Gmb%2a%2BtZcD%5Dx&inputs=%5B2%5D%0A%5B2%5D%0A100%0A%5B1+1+1+1+1+1+1+1%3B+0+0+0+0+0+0+0+0%3B+1+1+1+1+1+1+1+1%3B+0+0+0+0+0+0+0+0%3B+1+1+1+1+1+1+1+1%3B+0+0+0+0+0+0+0+0%3B+1+1+1+1+1+1+1+1%3B+0+0+0+0+0+0+0+0%5D&version=20.4.2).
### Explanation
```
xx % Take two inputs implicitly: birth and survival rules. Delete them
% (but they get copied into clipboard G)
:" % Take third input implicitly: number of generations. Loop that many times
tt % Duplicate twice. This implicitly takes the initial cell configuration
% as input the first time. In subsequent iterations it uses the cell
% configuration from the previous iteration
3Y6 % Push Moore neighbourhood: [1 1 1; 1 0 1; 1 1 1]
Z+ % 2D convolution, maintaining size
1G % Push first input from clipboard G: birth rule
m % Ismember: gives true for cells that fulfill the birth rule
< % Less than (element-wise): a cell is born if it fulfills the birth rule
% *and* was dead
8M % Push result of convolution again, from clipboard M
2G % Push second input from clipboard G: survival rule
m % Ismember: gives true for cells that fulfill the survival rule
b % Bubble up the starting cell configuration
* % Multiply (element-wise): a cell survives if it fulfills the survival
% rule *and* was alive
+ % Add: a cell is alive if it has been born or has survived, and those
% are exclusive cases. This produces the new cell configuration
% Implicit end loop. Implicit display
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~144~~ 122 bytes
```
CellularAutomaton[{Tr[2^#&/@Flatten@MapIndexed[2#+2-#2[[1]]&,{#2,#3},{2}]],{2,{{2,2,2},{2,1,2},{2,2,2}}},{1,1}},#,{{#4}}]&
```
[Try it online!](https://tio.run/##LU3LCsIwELz7FYFAL67YRD0KFUHoQRDxFlZYbKqFNJUQQQj59rgFGXZeDOxI8WVHisODSr8vR@vcx1E4fOLE7eRNugWj77JaNydHMVrfnOnd@s5@bWe0XOqV1MYoxAqS1CA3GZLOiMyQ@BhzA@qvc87sFCgWyRu5zRmrcgmDj01vruS7aWx9tE8bjAKRVA1C1RnZahD8QKSZdrgoPw "Wolfram Language (Mathematica) – Try It Online")
Example usage:
```
%[RandomInteger[1, {10, 10}], {2, 3}, {3}, 5]
```
uses a 10x10 random grid as a start, survives with either 2 or 3 neighbors, births with 3 neighbors, plot result at 5 iterations.
[Answer]
# [R](https://www.r-project.org/), 256 bytes
```
function(x,B,S,r){y=cbind(0,rbind(0,x,0),0)
n=dim(y)[1]
z=c(1,n)
f=function(h){w=-1:1
b=h%%n+1
a=(h-b+1)/n+1
'if'(a%in%z|b%in%z,0,sum(x[w+b,w+a])-x[b,a])}
while(r){x=y
for(i in 1:n^2){u=f(i-1)
y[i]=u%in%B
y[i]=(y[i]&!x[i])|(x[i]&(u%in%S))}
r=r-1}
y[-z,-z]}
```
[Try it online!](https://tio.run/##bVHbboMwDH3PV7AH2lg4GumuquSX/kIfEZMKhRJpTSsGItD221nSAuumyYlvOT52krLfUZ/XOq3UQXODK1xjCaeW0kTpLQ@xHKzBEOximrZqz1uIZMw6SrlEDSyniaKAU0NCLiVLqPB9HUi2IV6IJJDw6KK5yud84yvtd@fkajDEr3rPTdQECTbBJgZhogStvbCmUJ8ZtxMZall@KLnylPbkUn8s4FRTzpWQwNpIxVQ7stXN507PHozVcObOzPj1fA2WtKRSyItFig5FF1/61fUiT/iCb8DWNljgM77iOzBDtwdgnkOEOGxAl3Dur4QLBhkRo8gRMcofDoewF6Hd8AlyAYxl5pilVbb1yBvHGEruukwkE@uEuc/IqdEPJvynasTY9sdS6Yq3YhwD@m8 "R – Try It Online")
Sadly, this does not look as golfed as I'd hoped.
**Input**: an R matrix, and the challenge parameters. **Output**: the matrix after R generations.
The algorithm pads the matrix with zeros to handle the boundaries. Then, iteratively: 1st) it applies the Birth rule and 2nd) it kills the pre-existing cells that did not pass the Survival rule. Padding is removed when returning.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~156~~ ~~149~~ 146 bytes
```
lambda R,g,c:g and f(R,g-1,[[`sum(sum(l[y+y/~y:y+2])for l in c[x+x/~x:x+2])-c[x][y]`in R[c[x][y]]for y,_ in e(c)]for x,_ in e(c)])or c
e=enumerate
```
[Try it online!](https://tio.run/##vY/PisIwEMbv8xS5mdARm666S8GX8Dob1lhTFdpYuhWSi6/eTVRWA55lGMLvmz@Zr/PD4WSLsV59j41utzvN1rjHqtwzbXes5oGmEok2v@eWx2zIZ3528aXPCiXqU88adrSsIpe52cWVLsrTgIq82oTKmu6gYrPHn9hueCWu7J5YBK7ArIw9t6bXgxn/19ecJsUEQyqUeY4EJDEJhUA5JhGlN3eBEiWwrj/agbW64@HFRgBcFYDEj/xYfEZL8@VXdFXcTOV4z9t6@YwyvefxsUzPS2Zj9fVZ4x8 "Python 2 – Try It Online")
Takes input:
* `R`ules: `[birth,survial]` rules as list of `string`. eg.(`['135','246']`)
* `g`enerations: `int`
* `c`onfiguration: Square 2D array of `1/0` or `True/False`
Returns 2d array of `True/False`
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~38~~ ~~36~~ 34 bytes (SBCS)
* Saved ~~2~~ 4 bytes thanks to [@ovs](https://codegolf.stackexchange.com/users/64121/ovs)!
```
{(((1⊥,)∊⍺(⍵+1)⊃⍨4⊃,)⍤⊢⌺3 3⍣⍵⍵)⍺⍺}
```
[Try it online!](https://tio.run/##JU07CsJAFOxziuncxSjZfEyuYOUZAhIRVhLUJkgqQSQkYmNp4wc8gB9I603eRdYXA/PewAwzE2d6MM1jnc7M902744bqhoHuXoyWCn5nZKnOk7nWSNIlVDR0eivWbyZpc0IIReXdlrQvOSw41VeSyi3VD5/JltxfXqhqPHhUX7ty2c0VxtDhNJ5wkWMt4jVzgIDqp2MJFy5VHxYlq8pScOHBR4ARQkQQ7CCBcuTfCBD@AA "APL (Dyalog Unicode) – Try It Online")
Can be invoked with `birth_rule (start_grid f epochs) survival_rule`, where `f` is the operator. Requires 0-indexing.
~~For some reason, using the trains `(+/,)` and `(4⊃,)` to make it 36 bytes [doesn't work](https://tio.run/##SyzI0U2pTMzJT///P@1R24RqDQ0NbX0dzUcdXRqPencB8VZtQ81HXc2PeldomABpHU1NzUc9u4wVjB/1LgbKApEmUCEQ1f5/1DsXZMaj3j6gwkPrjR@1TXzUNzU4yBlIhnh4Bv8H0p7@QBUGXLmJJUDaVMH0Ue8WAy4NIwWjRz3bgYKaQFFDLkMFIwVjBRMFUwUzBXMFCwUNoIxCmoKhgSZYwlTBHAA).~~ As ovs explained, it's because `⌺` calls functions dyadically. Anyway, their new solution is 34 bytes.
---
`⍣` can repeatedly apply a function some number of times, given a starting value. In this case, the starting value is the left operand, and the right operand tells it how many times to repeat.
`((1⊥,)∊⍺(⍵+1)⊃⍨4⊃,)⍤⊢⌺3 3` computes the next generation. The stencil operator (`⌺`) creates windows of a given shape (a 3x3 square here), applies a function on each of them, and puts them back together into a matrix. For cells on the edge of the grid, it will use zeroes, which works well with this challenge.
The train `((1⊥,)∊⍺(⍵+1)⊃⍨4⊃,)⍤⊢` is applied to each of those windows. `⍤⊢` applies the stuff before it to the second argument. `1⊥,` calculates the number of neighbors (including the cell) by turning the 2D window into a vector (`,`) and then summing it (`1⊥`). `∊` checks if that the number of neighbors is in either the birth rule or survival rule vector. Whether the birth rule or survival rule is chosen depends on the train `⍺(⍵+1)⊃⍨4⊃,`.
`4⊃,` turns the window into a vector and chooses the 5th cell, which is the cell we are calculating the next generation of. `⍺(⍵+1)` is an array where the first element is the birth rule and the second element is the survival rule, but with its elements increased by one (because we're including the current cell). Then `⊃⍨` uses the current cell/5th cell/middle cell to index into this array, so if the cell's dead (0) the birth rule will be used, and if the cell is alive (1) the survival rule will be used.
] |
[Question]
[
For challenges related to the Swift language. Note that language specific challenges are generally discouraged.
Download Swift: <http://swift-lang.org/downloads/index.php>
]
|
[Question]
[
Given an input list of non-empty strings, output an ASCII art representation of a tournament, based on the following drawing rules:
* The number of strings is guaranteed to be of quantity `2,4,8,16,etc.`
* The first two strings play each other, and the next two play each other, and so on. This is the first round.
* For each game, choose the winner randomly with equal probability.
* For the next round, the winner of the first game plays the winner of the second game, the winner of the third game plays the winner of the fourth game, and so on. Subsequent rounds follow the pattern.
* There is eventually one overall winner.
* For pretty output (required) the strings must all be prepended and appended with an underscore `_`.
* In order for the brackets to line up appropriately, each entry must be padded with `_` to all be the same length for that round.
* You can choose whether the padding is prepended or appended, so long as it's consistent.
* Instead, you can choose to pre-pad all strings to be the same length, rather than on a per-round basis. Whichever is golfier for your code.
## Further Rules
* Leading or trailing newlines or whitespace are all optional, so long as the characters themselves line up correctly.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* If possible, please include a link to an online testing environment so other people can try out your code!
* [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins.
## Examples
Example with cities `['Boston', 'New York', 'Charlotte', 'Atlanta', 'St. Paul', 'Chicago', 'Los Angeles', 'Phoenix']`:
```
_Boston______
\_New York____
_New York____/ \
\_New York_
_Charlotte___ / \
\_Charlotte___/ \
_Atlanta_____/ \
\_St. Paul_
_St. Paul____ /
\_St. Paul____ /
_Chicago_____/ \ /
\_St. Paul_/
_Los Angeles_ /
\_Los Angeles_/
_Phoenix_____/
```
Example with `['Lions', 'Tigers', 'Bears', 'Oh My']`:
```
_Lions__
\_Tigers_
_Tigers_/ \
\_Tigers_
_Bears__ /
\_Bears__/
_Oh My__/
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~92~~ 79 bytes
```
A¹θWS⊞υ⪫__ιWυ«A⌈EυLκεA⁺θθδFυ«P×_εPκMδ↓»AE✂υ¹Lυ²⎇‽²κ§υ⁺λλυMε→Fυ«Mδ↑↗θ←↖θ→»Mθ↘Aδθ
```
[Try it online!](https://tio.run/##ZVGxbsIwEJ3rr7CYbMlUoiOd0nahgioCOnRCVnIkVhw7xGegqvj21A6BgjpYJ7977947Oytlm1mpuy5xThWGTQTd8WdyKJUGymam8bjCVpmCcU5T70rmBX23yrDRZjMSVPE/tuf0hzwMgxbyqGpfh9pEyRxMgSWrOOeCQtBceKn2ju2iq6B5xLe2vYx6WHiNqgn2yNaqBhdMR1EeebfN6gzYPbBc0OmbPZiInG7SNGylVQYxy@QaxwfTp3DW0BrZfrOlNLmtWYQqQROcmRyOUdKn1IJq3i/g4/TeDoLdUhUl/ot@CfPZ9OHSPmi49ezzKw@s6Ry2eE@KyD3nanIanHfDotfGsGp@1p267sU6tIZ8wIF@2bYir@GztUUEkqCWBiVZ4SNNpdehpTJZWDK3jiamAA2OpKUFo46kG@@7sdO/ "Charcoal – Try It Online") Link is to verbose version of code. Needs a blank line to mark the end of the input. Explanation:
```
A¹θ
```
Initialise the variable `q`. This holds the size of the zig-zags i.e. half the gap between rows.
```
WS⊞υ⪫__ι
```
Read nonblank input lines into the array `u`. The lines are automatically surrounded by `_`s as they are read in, although they are not padded yet.
```
Wυ«
```
Loop while there are still strings left.
```
A⌈EυLκε
```
Calculate the width of the largest string in `e`.
```
A⁺θθδ
```
Calculate the gap between rows in `d`.
```
Fυ«P×_εPκMδ↓»
```
For each team, print the padding, print the team, and then move down to the next team.
```
AE✂υ¹Lυ²⎇‽²κ§υ⁺λλυ
```
For every other team, randomly pick between that team or the previous team. (Note that if there is only one team left then this produces an empty list.)
```
Mε→Fυ«Mδ↑↗θ←↖θ→»Mθ↘
```
If there are still teams left, draw the zigzags joining them in pairs.
```
Aδθ
```
Double the length of the zigzags each time.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~379~~ 364 bytes
```
exec r"""c=input();from random import*;R,L,d=range,len,0;u,s="_ ";r=[[""]*-~L(c)@R(2*L(c)-1)]
while c:
W=2+max(map(L,c));j=1<<d;J=j/2;D=d+d;d+=1
@r:l[D]=s*W;l[D-1]=s*J
@R(L(c)):
h=l*2*j+j-1;r[h][D]=(u+c[l]+u*W)[:W]
@R(h-J,h+J):r[-~l][~-D]=("/\\"[l<h]+s*abs(h-l-(l<h))).rjust(J)
c=[choice(l)@zip(c[::2],c[1::2])]
@r:print"".join(l)""".replace("@","for l in ")
```
[Try it online!](https://tio.run/##HZFNb9wgEIbP8a9AnMAfm9pHs0ibNidrVUXbwyoiqKKYBFwWLIyVbQ/717fjnuaZV8@gAeY/2cbQ3e/majRKGGPNXZjXTCh7T/GCkgojFHeZY8olO9XHeuQQfpjam1B/YWu9cPwTYZa4EBjLsrkdiaaHE@nKDZqWyuLTOm@Q7gt05l11UVdyUTM51ppSNvF2vx/ZwKfHjj3zsRrZWPG2QIfUe/Es@VKeGUDTbjhAfiLbwbQvHiz3ZVdO1dS0LAkrN52slRZeVmt5pqI/y@IBBmwz1LYaaJ9Ec/NS3JrNxI9vb1j4vZXVUqpfC2i@IdBTSndpWpdMBlogzYW20WlDPD38dTPRou87WWvRbhXuB6vOyYWM8W6KLoAHL7lLZvYKpvAB1/g9JuSRCwjT@x1/jUuOAeLv5hO9xvQb8JtVycecDfBT9ipkBfQj79CLWv1/wWn1EYGOcUFP8AfeLNC92GiCu@J/ "Python 2 – Try It Online")
] |
[Question]
[
So... uh... this is a bit embarrassing. But we don't have a plain "Hello, World!" challenge yet (despite having 35 variants tagged with [hello-world](/questions/tagged/hello-world "show questions tagged 'hello-world'"), and counting). While this is not the most interesting code golf in the common languages, finding the shortest solution in certain esolangs can be a serious challenge. For instance, to my knowledge it is not known whether the shortest possible Brainfuck solution has been found yet.
Furthermore, while all of ~~[Wikipedia](https://en.wikipedia.org/wiki/List_of_Hello_world_program_examples)~~ (the Wikipedia entry [has been deleted](https://en.wikipedia.org/wiki/Wikipedia:Articles_for_deletion/List_of_Hello_world_program_examples) but there is a [copy at archive.org](https://web.archive.org/web/20150411170140/https://en.wikipedia.org/wiki/List_of_Hello_world_program_examples)
), [esolangs](https://esolangs.org/wiki/Hello_world_program_in_esoteric_languages) and [Rosetta Code](https://rosettacode.org/wiki/Hello_world/Text) have lists of "Hello, World!" programs, none of these are interested in having the shortest for each language (there is also [this GitHub repository](https://github.com/leachim6/hello-world)). If we want to be a significant site in the code golf community, I think we should try and create the ultimate catalogue of shortest "Hello, World!" programs (similar to how our [basic quine challenge](https://codegolf.stackexchange.com/q/69/8478) contains some of the shortest known quines in various languages). So let's do this!
## The Rules
* Each submission must be a full program.
* The program must take no input, and print `Hello, World!` to STDOUT (this exact byte stream, including capitalization and punctuation) plus an optional trailing newline, and nothing else.
* The program must not write anything to STDERR.
* If anyone wants to abuse this by creating a language where the empty program prints `Hello, World!`, then congrats, they just paved the way for a very boring answer.
Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language.
* Submissions are scored in *bytes*, in an appropriate (pre-existing) encoding, usually (but not necessarily) UTF-8. Some languages, like [Folders](https://esolangs.org/wiki/Folders), are a bit tricky to score - if in doubt, please ask on [Meta](https://meta.codegolf.stackexchange.com/).
* This is not about finding *the* language with the shortest "Hello, World!" program. This is about finding the shortest "Hello, World!" program in every language. Therefore, I will not mark any answer as "accepted".
* If your language of choice is a trivial variant of another (potentially more popular) language which already has an answer (think BASIC or SQL dialects, Unix shells or trivial Brainfuck-derivatives like Alphuck), consider adding a note to the existing answer that the same or a very similar solution is also the shortest in the other language.
As a side note, please *don't* downvote boring (but valid) answers in languages where there is not much to golf - these are still useful to this question as it tries to compile a catalogue as complete as possible. However, *do* primarily upvote answers in languages where the authors actually had to put effort into golfing the code.
For inspiration, check [the Hello World Collection](https://helloworldcollection.github.io/).
## 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 = 55422; // 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]
# Befunge-93, 21 bytes
```
"!dlroW ,olleH">:#,_@
```
[Try it online!](http://befunge.tryitonline.net/#code=IiFkbHJvVyAsb2xsZUgiPjojLF9A&input=)
**Explanation**
```
"!dlroW ,olleH" Push the string onto the stack in reverse. Note that there is an
implicit null terminator since an empty stack will always pop zero.
> Start the output loop.
: Duplicate the character at the top of the stack.
# Skip the following operation to the right.
_ Test if the character is null, dropping the duplicate copy.
, If not, branch left and write the character to stdout.
# Skip the following operation to the left.
> Reverse direction and repeat the loop with the next character.
@ Once the null is reached, branch right and exit.
```
[Answer]
# [Del|m|t](https://github.com/MistahFiggins/Delimit), 29 + 1 = 30 bytes
[Try it online!](https://tio.run/nexus/delimit#@2@rbKXskZqTk6@jEJ5flJOiqKyvbKRsp2yvbKms9P//f2UA)
```
=#:#Hello, World!#/#2#>#?#9#"
```
...With `#` passed as a command line argument.
This is a new language that I recently created, which uses regex to parse its source code. I highly recommend that you read the [documentation](https://github.com/MistahFiggins/Delimit/wiki) and [tutorial](https://github.com/MistahFiggins/Delimit/wiki/Tutorial).
**Explanation:**
The regex passed as an argument acts as a delimiter (hence the name), which parses the code into tokens, which are read as commands based on their ASCII values.
Because the regex is `#`, the tokens are `=`, `:`, `Hello, World!`, `/`, `2`, `>`, `?`, `9`, and `"`
These correspond to commands depending on their ASCII values mod 32:
```
(=) 29 29 pops the top value of the stack, and skips that many instructions.
Right now, the top is 0, so it's a no-op. Later, we will use it to
skip the following part that pushes the string
(:) 26, (H...) "H..." 26 pushes the next token as a string backwards onto the stack
(/) 15 Duplicates the top of the stack, so we have 2 copies of the top character.
(2) 18 Nots the top of the stack. It the top was 0, it is now 1
(>) 30, (?) 31 Iff the top of the stack is non-0, exit the program
(9) 25 Print the character
(") 2 Push 2 - This is used to skip the String pushing part when we...
Go back to the start of the program and repeat
```
[Answer]
# [Valyrio](https://github.com/JaqueIsBaque/Valyrio), 17 bytes
```
s ∫ main [´Ø]
```
`‹` and `›` start and end comments.
```
s ‹Sets the mode to stack mode, usually used for code golf as its shorter›
∫ ‹Tells the interpreter that the previous letter was a tag, not a command›
main [ ‹Starts the main code block›
´ ‹Pushes "Hello, World!" in unicode numbers to the stack (Alt-Shift-E on Mac)›
Ø ‹Outputs the stack as unicode characters›
] ‹Ends the main code block‹
```
[Answer]
## [Hillberth](https://github.com/tuxcrafting/hillberth), 32 bytes
```
[]H ,olH
.< Wle
ro
ld!
```
If this code is weird looking, it's because the flow of an Hillberth program follows an Hilbert curve. So, the executed program is this:
```
[.<]H !dlroW ,olleH
```
The code is similar to a Self-Modifying BrainFuck code, with the `H` command stopping the program.
[Answer]
# [KanyeC](https://github.com/nicksam112/kanyec), 78 bytes
"A programming language based on the brilliance of Kanye West."
```
I am the greatest
make her say "Hello, World!"
I still think I am the greatest
```
Yes, it *is* essentially just an [ArnoldC](https://github.com/lhartikk/ArnoldC/wiki/ArnoldC) substitution, but I thought I'd contribute it for the sake of completeness.
[Answer]
## [Samau](https://github.com/AlephAlpha/Samau/tree/master/OldSamau), 15 bytes
```
"Hello, World!"
```
Samau is yet another stack-based golfing language.
[Answer]
# [HODOR](https://github.com/ValyrioCode/Hodor), 2384 bytes
```
Walder
Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor
HODOR!
Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor
HODOR!
Hodor Hodor Hodor Hodor Hodor Hodor Hodor
HODOR!
HODOR!
Hodor Hodor Hodor
HODOR!
Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor!
HODOR!
Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor!
HODOR!
Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor
HODOR!
Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor
HODOR!
Hodor Hodor Hodor
HODOR!
Hodor! Hodor! Hodor! Hodor! Hodor! Hodor!
HODOR!
Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor!
HODOR!
Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor! Hodor!
HODOR!
HODOR!!!
```
I decided that my [NO!](https://codegolf.stackexchange.com/a/114877/66833) answer wasn't long enough so I finished my commemoration of [Hodor](http://gameofthrones.wikia.com/wiki/Hodor) and spend a while coding this.
Hodor uses an accumulator because he's learning to count and can't remember more than 1 number.
In short (because I'm not doing a line-by-line explanation) these are the main commands:
`Walder` Hodor hodor hodor hodor Hodor hodor hodor hodor
>
> Start the program because Hodor's original name was Walder
>
>
>
`Hodor` Hodor hodor hodor hodor hodor
>
> Add 1 to the accumulator
>
>
>
`Hodor!` Hodor hodor hodor hodor hodor
>
> Subtract 1 from the accumulator
>
>
>
`HODOR!` Hodor hodor hodor hodor hodor hodor hodor
>
> Output the accumulator as a Unicode character
>
>
>
`HODOR!!!` Hodor Hodor (Hodor hodor hodor)
>
> Kill Hodor (End the program)
>
>
>
[Answer]
# [Turing](http://compsci.ca/holtsoft/doc/), 18 bytes
```
put"Hello, World!"
```
[Answer]
# Charcoal, 13 bytes
```
Hello, World!
```
Charcoal prints the canvas state at the end of execution, and any run of ASCII characters is considered a string, which is implicitly printed to the canvas.
[Answer]
# [NTFJ](https://github.com/ConorOBrien-Foxx/NTFJ), 106 bytes
```
~#~~#~~~@*~##~~#~#@*~##~##~~@::**~##~####@:*~~#~##~~@*~~#~~~~~@*~#~#~###@**~###~~#~@**~##~~#~~@*~~#~~~~#@*
```
[Try it online!](https://tio.run/nexus/ntfjc#PYzBDQAwCAKH4ecIvpyM1W09myY@QA7a8pwrLKRWjanMeEaqDGLB0tkWz9sakoWVIJ@8efcB "NTFJ (NTFJC) – TIO Nexus")
NTFJ is an esoteric programming language, made by user @ConorO'Brien, that is intended to be a Turing tarpit. It is stack-based, and pushes bits to the stack, which can be later coalesced to an 8-bit number.
### How it works
```
Output Stack
H ~#~~#~~~@*
e ~##~~#~#@*
~##~##~~@ l
ll ::** l
o ~##~####@:* l o
, ~~#~##~~@* l o
~~#~~~~~@* l o
W ~#~#~###@* l o
o * l
r ~###~~#~@* l
l *
d ~##~~#~~@*
! ~~#~~~~#@*
```
[Answer]
**SASS, 32 bytes?**
```
\:after
content:"Hello, World!"
```
[Answer]
# [MY](https://bitbucket.org/zacharyjtaylor/my-language/overview), 1 byte.
Here is the hex:
```
FF
```
I'm finally ready to reveal my language. It's still a major WIP, and the undefined byte meaning is temporary (except for maybe 0xFF). I will eventually update this to include a non-hacky solution when MY is able to do that.
[Answer]
# [Klein](https://github.com/Wheatwizard/Klein), 16 + 3 = 19 bytes
```
"Hello, World!"@
```
* +3 for `-A` flag
* Also contains a null argument for the topology, I'm not even sure how to score that.
[Try it online!](https://tio.run/##y85Jzcz7/1/JIzUnJ19HITy/KCdFUcnh////uo7/AQ "Klein – Try It Online")
Competing for the bounty.
[Answer]
## [StupidScript](https://github.com/RedstoneKingdom/stupidscript), 214 bytes
It's a joke language that I just made. Mark Watney would be proud.
```
80.5 0.0
80.5 23.0
69.0 103.5
69.0 161.0
80.5 46.0
23.0 0.0
23.0 23.0
46.0 92.0
69.0 57.5
69.0 138.0
69.0 138.0
69.0 172.5
23.0 138.0
23.0 0.0
57.5 80.5
69.0 172.5
80.5 23.0
69.0 138.0
69.0 46.0
23.0 11.5
23.0 23.0
```
[Answer]
# [Fishing](http://esolangs.org/wiki/Fishing), ~~25~~ 24 bytes
```
[+_
|C]`Hello, World!`Ni
```
It exits with an error.
# Fishing, 34 bytes
```
v+CCCCCCCC^]
`Hello,
N`!dlroW
```
Without errors.
[Answer]
# [Aheui](https://esolangs.org/wiki/Aheui), ~~147~~ 144 bytes
```
발따밤따빠받나파빠밣다빠밦다빠받타밢밢따밦다밤밣따밦밦따빠밣다파받따빠받다파빠빠밠타밣밢따아멓희
```
[Answer]
# [Shtriped](https://github.com/HelkaHomba/shtriped), 239 bytes
```
e n
e b
i b
+ x y
+
i x
d y
+
+
d x
0
+ b b b
1
+ b n n
0
z x
d x
z x
D
1
s n
z n n
z b b
i b
Y
0
0
Z
1
Y
Y
B
0
1
1
Z
1
Y
1
Y
D
B
B
1
0
Z
Y
D
B
1
Y
B
0
Z
D
1
B
B
Y
1
0
D
Y
1
1
Y
B
Z
D
B
Y
1
0
Z
Y
D
B
1
1
1
1
B
0
D
```
[Try it online!](https://tio.run/##XU05DsQgDOz9iunTJF9AfALKCKSliaLNFgmfJzOmW9mG8RxwfX7fdtYyRsVhFbs1zoIbj2ExoOHmWbRqZxcyKxF2lW0THoxjtS67HBCKBsqXpD4d3TPQJ0l@dnZTUgenNr6ZOcknkg1EMs5NbPA9EktNrke/p5rdmf5ys5SNY7w "Shtriped – Try It Online")
This Hello, World! in Shtriped terminates somewhat quickly, since it doesn't encode the entire string in one number.
[Answer]
# [Lean Mean Bean Machine](https://github.com/gunnerwolf/lmbm), 55 bytes
```
OOOOOOOOOOOOO
"""""""""""""
Hello, World!
!!!!!!!!!!!!!
```
I *think* this is the shortest.
Here's a somewhat more entertaining alternative approach in 96 bytes:
```
OOOOOOOOOO
"""
Hel
!!!""""
!o, W
!!!!
! "
r
!""
! d!
!!
```
This one only sets 1 marble to each letter, and re-uses the `l` and `o` marbles, much less golfy, but more true to the spirit of the language.
[Answer]
# [Set](https://esolangs.org/wiki/Set), 123 bytes
```
set ! H
set ! 101
set ! 108
set ! 108
set ! 111
set ! 44
set ! 32
set ! 87
set ! 111
set ! 114
set ! 108
set ! 100
set ! 33
```
Needed to use raw ASCII codes because lowercase letters are reserved for variable names.
[Try it online!](https://tio.run/##K04t@f@/OLVEQVHBgwtCGxoYwlkWmCxDmKyJCZRhbARlWJhjKDI0NMFimAFMp/H//wA)
[Answer]
# MY, 60 bytes
```
27á'←1Aá'←8Aá'2×←1Bá'←44á'←2Ġ'←78á'←1Bá'←4Bá'←8Aá'←AȦ'←33á'←
```
[MY IS ON TIO!!](https://tio.run/##y638/9/I/PBC9UdtEwwdIbQFiDY6PB0k5AQRMjGB0EZHFoAocwuoDpi0E5JOIO14YhmIMjaGcP//BwA)
## How?
Outputs H, e, ll, o, <space>, W, o, r, l, d, ! to the console.
I created a 3rd answer to this question due to the differing techniques used, this uses concatenation on numbers (`27√°` pushes `72`), one uses increment and decrement, while another uses a builtin.
[Answer]
# [Braingolf](https://github.com/gunnerwolf/braingolf), 17 bytes
Got bored, made my own language, here's Hello World
```
"Hello, World!"&@
```
Explanation:
```
"Hello, World!" Push the 13 chars of Hello World to the stack as charcode integers
&@ Pop the entire stack and print as chars
```
Alternatively, here's hello world from before I added multi-char strings and printing:
```
#!#d#l#r#o#W# #,#o#l#l#e#H@@@@@@@@@@@@@
```
Explanation:
```
#! Push the charcode of char '!' to the end of the stack
.................... Do this for every character in "Hello, World!" in reverse order
@@@@@@@@@@@@@ Pop and print the last element of the stack 13 times
```
[Answer]
# [Emoji](https://esolangs.org/wiki/Emoji), ~~23~~ 24 bytes
```
üí¨Hello, World!üí¨‚û°
```
Should be pretty clear. Just pushes `Hello, World!` and than outputs.
[Answer]
# Apps Script + Google Sheets, 39 bytes
### Script
```
function Q(){return"Hello, World!"}
```
### Sheet
```
=q()
```
## Original, 40 bytes
### Script
```
function Q(){return "Hello, World!"}
```
### Sheet
```
=q()
```
[Answer]
## [AsciiDots](https://github.com/aaronduino/asciidots), 18 bytes
```
.-$"Hello, World!"
```
[Try it online!](https://tio.run/##SyxOzsxMyS8p/v9fT1dFySM1JydfRyE8vygnRVHp/38A)
[Answer]
# [DOBELA](http://esolangs.org/wiki/DOBELA), 214 bytes
```
,,.,,,,.,..,,.,,,..,..,,,...,,.,,..,....,.,.,...,,.,,,,,,,.,..,,,..,....,..,..,,,..,..,,,..,,.,.,.,,.,,,$^
. #
```
With comments:
```
! d l r o W , o l l e H
,,.,,,,. ,..,,.,, ,..,..,, ,...,,., ,..,.... ,.,.,... ,,.,,,,, ,,.,..,, ,..,.... ,..,..,, ,..,..,, ,..,,.,. ,.,,.,,,$^
. #
H = ascii 0x48 = 01001000 = ,.,,.,,,
```
Put bits in FIFO then print them by hitting `^` from below.
[Try it online](https://tio.run/##S8lPSs1J/P9fR0dPRwdE6OlBmHoQJpCACID5IAKsBqoIoQUhj8yH0BA9EB0qcVx6CvQCyv//AwA)
[Answer]
# [Triangularity](https://github.com/Mr-Xcoder/Triangularity), ~~71~~ 49 bytes
```
.... ....
..."!"...
.."ld"+..
." Wor"+.
"Hello,"+
```
[Try it online!](https://tio.run/##KynKTMxLL81JLMosqfz/Xw8IFEAEFxArKSpBWEo5KUraIJaSQnh@EZDJpeSRmpOTr6Ok/f8/AA "Triangularity – Try It Online")
Saved 22 bytes thanks to an ingenious method by Mr. Xcoder!
## Old version
```
...........
...."H"....
..."ell"...
.."o, Wo"..
."rld!"W"".
.....J.....
```
[Try it online!](https://tio.run/##KynKTMxLL81JLMosqfz/Xw8BuECEkocSjK2UmpOjBGEr5esohOcrgdhKRTkpikrhSkoQ9XpeYPL/fwA "Triangularity – Try It Online")
[Answer]
# [rk](https://github.com/aaronryank/rk-lang), 22 + 2 (`-e`) = 24 bytes
```
print: "Hello, World!"
```
Requires the `-e` flag (remove necessity for `rk:start`). [Try it online!](https://tio.run/##K8r@/7@gKDOvxEpBySM1JydfRyE8vygnRVHp////uqkA)
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 8 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
èï┬▀↨╩4G
```
[Run and debug online!](https://staxlang.xyz/#c=%C3%A8%C3%AF%E2%94%AC%E2%96%80%E2%86%A8%E2%95%A94G&i=&a=1)
## Explanation
`èï┬▀↨╩4G` is the packed form of the ASCII Stax code ``jaH1"jS3!`, which is in turn a compressed string literal of `Hello, World!` with the ending backtick omitted.
[Answer]
# [Min](https://min-lang.org), 20 bytes
```
"Hello, World!" puts
```
[Answer]
## PHP (on a standard Apache Server, result needing to target STDOUT), ~~30~~ 27 Bytes
```
<?php die("Hello, World!");
```
Note: this is not to detract form earlier PHP example relied on an option assuming PHP wasn't being used as a webserver and abusing the HTML-effect outside of ?php tags to have an answer that was just "Hello, World!"
That said, that solution made some non-standard server assumptions which aren't common with PHP. So I'm presenting an alternative that assumes a normal server layout, but still needs to go to STDOUT. This is not to detract from the previous posters example, but to present one in a different setting with different constraints.
Note: originally thought using
```
<?php fwrite(STDOUT,"Hello, World!"); ?>
```
would be the only way, but then realized the die (normally used killing the script with an error) outputted to STDOUT and didn't use extra variables.
Updated: Cut off a few bytes recalling that "die" wont' bother with anything after itself, so didn't need the closing ?>.
Note: Worth noting, that if shorttags were on with a PHP5 server, could drop down 3 more bytes to 24 bytes with
```
<? die("Hello World!");
```
However, I was specifically going a standard server, and shortags are now off by default making a server with them on no longer standard.
Example (courtesy of Scrooble):
[Try It Online!](https://tio.run/##K8go@P/fxr4go0AhJTNVQ8kjNScnX0chPL8oJ0VRSdP6/38A)
] |
[Question]
[
A Sphenic Number is a number that is the product of exactly three distinct primes. The first few Sphenic numbers are `30, 42, 66, 70, 78, 102, 105, 110, 114`. This is sequence [A007304](https://oeis.org/A007304) in the OEIS.
## Your Task:
Write a program or function to determine whether an inputted integer is a Sphenic number.
## Input:
An integer between 0 and 10^9, which may or may not be a Sphenic Number.
## Output:
A truthy/falsy value indicating whether the input is a Sphenic Number.
## Examples:
```
30 -> true
121 -> false
231 -> true
154 -> true
4 -> false
402 -> true
79 -> false
0 -> false
60 -> false
64 -> false
8 -> false
210 -> false
```
## Scoring:
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code in bytes wins.
[Answer]
## bash, 43 bytes
```
factor $1|awk '{print $2-$3&&$3-$4&&NF==4}'
```
[Try it online!](https://tio.run/##HY5NCsIwGET3PcVQPpJVoPlREdouXXqHNDa0qInUiAXr2WNwZlaPt5jBPqfsbELb8pWj99lbl@ICkpt9X8E/j2UOCaQEacZICzKMnU9dZ748r5UvasAcoBtIJaG0hNwZlDYKhyMa7MtMdYkVSkY3RYiAmgJEj/oPh3ICHhSKFUZscPH2uhch5R8 "Bash – Try It Online")
Input via command line argument, outputs `0` or `1` to stdout.
Fairly self-explanatory; parses the output of `factor` to check that the first and second factors are different, the second and third are different (they're in sorted order, so this is sufficient), and there are four fields (the input number and the three factors).
[Answer]
# [MATL](https://github.com/lmendo/MATL), 7 bytes
```
_YF7BX=
```
[Try it online!](https://tio.run/##y00syfn/Pz7Szdwpwvb/f0MDUwA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##y00syfmf8D8@0s3cKcL2v0vIf2MDLkMjQy4jY0MuQ1MTLiA0MOIyt@Qy4DIDIhMA).
### Explanation
```
_YF % Implicit input. Nonzero exponents of prime-factor decomposition
7 % Push 7
B % Convert to binary: gives [1 1 1]
X= % Is equal? Implicit display
```
[Answer]
# C, ~~88~~ ~~78~~ ~~126~~ ~~58~~ ~~77~~ 73 + 4 (`lm`) = 77 bytes
```
l,j;a(i){for(l=1,j=0;l++<i;fmod(1.*i/l,l)?i%l?:(i/=l,j++):(j=9));l=i==1&&j==3;}
```
Ungolfed commented explanation:
```
look, div; //K&R style variable declaration. Useful. Mmm.
a ( num ) { // K&R style function and argument definitions.
for (
look = 1, div = 0; // initiate the loop variables.
look++ < num;) // do this for every number less than the argument:
if (fmod(1.0 * num / look, look))
// if num/look can't be divided by look:
if( !(num % look) ) // if num can divide look
num /= look, div++; // divide num by look, increment dividers
else div = 9;
// if num/look can still divide look
// then the number's dividers aren't unique.
// increment dividers number by a lot to return false.
// l=j==3;
// if the function has no return statement, most CPUs return the value
// in the register that holds the last assignment. This is equivalent to this:
return (div == 3);
// this function return true if the unique divider count is 3
}
```
[Try it online!](https://tio.run/##JcxBDoIwEADAr5gmJLu2COjJLg0f8dIslLRZwACejF@3kviAGS5H5pzFJPIQ8R2WFcQ1JrmaROs2UpiWHprLOVZiBLtYSGchVu4gWqOF5O6IJC45d6NPZpp8nOE/EbfXuiZ8rnHeA6ji1ttTsT1mZVhr44GxU/v6GpRVwcs2KDyKLwfx45ZLmX4 "C (gcc) – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~6~~ 3 bytes
```
ḋ≠Ṫ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@GO7kedCx7uXPX/v5Gx4X8A "Brachylog – Try It Online")
### Explanation
```
ḋ The prime factorization of the Input…
≠ …is a list of distinct elements…
Ṫ …and there are 3 elements
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 11 bytes
```
rimFz1=7Yb=
```
[Try it online!](https://tio.run/##S85KzP3/vygz163K0NY8Msn2/39DA1MA "CJam – Try It Online") Or [verify all test cases](https://tio.run/##S85KzP1f/T8nM9etytDWPDLJ9n@BYW36f2MDLkMjQy4jY0MuQ1MTLiA0MOIyt@Qy4DIDIhMA).
### Explanation
Based on my MATL answer.
```
ri e# Read integer
mF e# Factorization with exponents. Gives a list of [factor exponent] lists
z e# Zip into a list of factors and a list of exponents
1= e# Get second element: list of exponents
7 e# Push 7
Yb e# Convert to binary: gives list [1 1 1]
= e# Are the two lists equal? Implicitly display
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
ÆEḟ0⁼7B¤
```
[Try it online!](https://tio.run/##y0rNyan8//9wm@vDHfMNHjXuMXc6tOT////GBgA "Jelly – Try It Online")
Uses Luis Mendo's algorithm.
Explanation:
```
ÆEḟ0⁼7B¤
ÆE Prime factor exponents
ḟ0 Remove every 0
⁼7B¤ Equal to 7 in base 2?
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
ÆE²S=3
```
[Try it online!](https://tio.run/##y0rNyan8//9wm@uhTcG2xv@P7jnc/qhpjfv//8YGOgqGRoY6CkbGQMLQ1ERHAYQMjHQUzC11FICyZiBsAgA "Jelly – Try It Online")
### How it works
```
ÆE²S=3 Main link. Argument: n
ÆE Compute the exponents of n's prime factorization.
² Take their squares.
S Take the sum.
=3 Test the result for equality with 3.
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 6 bytes
```
≡ḋ3Ẋ≠p
```
[Try it online!](https://tio.run/##yygtzv7//1Hnwoc7uo0f7up61Lmg4P///8YGAA "Husk – Try It Online")
Returns 1 for sphenic numbers and 0 otherwise.
### Explanation
```
≡ḋ3Ẋ≠p Example input: 30
p Prime factors: [2,3,5]
Ẋ≠ List of absolute differences: [1,2]
≡ Is it congruent to... ?
ḋ3 the binary digits of 3: [1,1]
```
In the last passage, congruence between two lists means having the same length and the same distribution of truthy/falsy values. In this case we are checking that our result is composed by two truthy (i.e. non-zero) values.
[Answer]
# Ruby, ~~81~~ ~~49~~ 46 bytes
Includes 6 bytes for command line options `-rprime`.
```
->n{n.prime_division.map(&:last)==[1]*3}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOk@voCgzNzU@JbMsszgzP08vN7FAQ80qJ7G4RNPWNtowVsu49n@BQlq0kWWsDpAyNoBQhmDKBEoZxf7/l19QAtRf/F@3CGwiAA "Ruby – Try It Online")
[Answer]
# Mathematica, 31 bytes
```
SquareFreeQ@#&&PrimeOmega@#==3&
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~7~~ 5 bytes
```
ÓnO3Q
```
[Try it online!](https://tio.run/##MzBNTDJM/f//8OQ8f@PA//@NDQA "05AB1E – Try It Online")
Uses Dennis's algorithm.
[Answer]
# Pyth, 9 bytes
```
&{IPQq3lP
```
[Try it here.](http://pyth.herokuapp.com/?code=%26%7BIPQq3lP&input=30&debug=0)
[Answer]
# [Actually](https://github.com/Mego/Seriously), 7 bytes
```
w♂N13α=
```
[Try it online!](https://tio.run/##S0wuKU3Myan8/7/80cwmP0Pjcxtt//83NgAA "Actually – Try It Online")
Explanation:
```
w♂N13α=
w Push [prime, exponent] factor pairs
♂N Map "take last element"
1 Push 1
3 Push 3
α Repeat
= Equal?
```
[Answer]
# [Haskell](https://www.haskell.org/), 59 bytes
```
f x=7==sum[6*0^(mod(div x a)a+mod x a)+0^mod x a|a<-[2..x]]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P02hwtbc1ra4NDfaTMsgTiM3P0UjJbNMoUIhUTNRG8gDs7QN4qDMmkQb3WgjPb2K2Nj/uYmZebYFRZl5JSppCiYGRv8B "Haskell – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 14 bytes
```
k
k@è¥X ÉÃl ¥3
```
[Try it online!](https://codepen.io/justinm53/full/NvKjZr?code=awprQOilWCDJw2wgpTM=&inputs=MzA=,MTIx,MjMx,MTU0,NA==,NDAy,Nzk=,MA==,NjA=,NjQ=)
[Answer]
# [J](http://jsoftware.com/), 15 bytes
```
7&(=2#.~:@q:)~*
```
[Try it online!](https://tio.run/##y/r/P03B1krBXE3D1khZr87KodBKs06Liys1OSNfQUNHL03JQFPB2EDB0MhQwcjYUMHQ1EQBCA2MFMwtFQwUzIDI5P9/AA "J – Try It Online")
## Explanation
```
7&(=2#.~:@q:)~* Input: integer n
* Sign(n)
7&( )~ Execute this Sign(n) times on n
If Sign(n) = 0, this returns 0
q: Prime factors of n
~:@ Nub sieve of prime factors
2#. Convert from base 2
= Test if equal to 7
```
[Answer]
# Dyalog APL, 26 bytes
```
⎕CY'dfns'
((≢,∪)≡3,⊢)3pco⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKPdOSM1Ofv/o76pzpHqKWl5xepcGhqPOhfpPOpYpfmoc6GxzqOuRZrGBcn5QCUg9f/BGriMDbi4ICxDI0MY08gYzjQ0NYExEQwDIxjT3BLGMoMbZGYCAA)
[Answer]
# Mathematica, 44 bytes
```
Plus@@Last/@#==Length@#==3&@FactorInteger@#&
```
[Try it online!](https://tio.run/##y00sychMLv6fZvs/IKe02MHBJ7G4RN9B2dbWJzUvvSQDxDJWc3BLTC7JL/LMK0lNTy1yUFb7H1CUmQdUl6bvUG1soKNgaGSoo2BkDCQMTU10FEDIwEhHwdxSRwEoawbCJrX/AQ "Mathics – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~54~~ 53 bytes
```
lambda n:sum(1>>n%k|7>>k*k%n*3for k in range(2,n))==6
```
*Thanks to @xnor for golfing off 1 byte!*
[Try it online!](https://tio.run/##FYxBCoMwFETX7SlmE4zyCyaxSoXkJN1YWluJfiXqotC7pwbmzeINzPLdPjOb2MPiHsduejw7cLvuk1TOsfC/xjlfeMGF6ecAj4EROn6/pCbOc2vrmDwnb0qC0oqgzVHqWhFSSk1oboRjrRNVez4tYeBNZsLsuDiINYOAZEIvj9M8/gE "Python 3 – Try It Online")
[Answer]
**C, 91 102 bytes, corrected (again), golfed, and tested for real this time:**
```
<strike>s(c){p,f,d;for(p=2,f=d=0;p<c&&!d;){if(c%p==0){c/=p;++f;if(c%p==0)d=1;}++p;}c==p&&f==2&&!d;}</strike>
s(c){int p,f,d;for(p=2,f=d=0;p<c&&!d;){if(c%p==0){c/=p;++f;if(c%p==0)d=1;}++p;}return c==p&&f==2&&!d;}
```
/\* This also works in 93 bytes, but since I forgot about the standard rules barring default int type on dynamic variables, and about the not allowing implicit return values without assignments, I'm not going to take it:
```
p,f,d;s(c){for(p=2,f=d=0;p<c&&!d;){if(c%p==0){c/=p;++f;if(c%p==0)d=1;}++p;}p=c==p&&f==2&&!d;}
```
(Who said I knew anything about C? ;-)
Here's the test frame with shell script in comments:
```
/* betseg's program for sphenic numbers from
*/
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <math.h> /* compile with -lm */
/* l,j;a(i){for(l=1,j=0;l<i;i%++l?:(i/=l,j++));l=i==1&&j==3;} */
#if defined GOLFED
l,j;a(i){for(l=1,j=0;l++<i;fmod((float)i/l,l)?i%l?:(i/=l,j++):(j=9));l=i==1&&j==3;}
#else
int looker, jcount;
int a( intval ) {
for( looker = 1, jcount = 0;
looker++ < intval;
/* Watch odd intvals and even lookers, as well. */
fmod( (float)intval/looker, looker )
? intval % looker /* remainder? */
? 0 /* dummy value */
: ( inval /= looker, jcount++ /* reduce the parameter, count factors */ )
: ( jcount = 9 /* kill the count */ )
)
/* empty loop */;
looker = intval == 1 && jcount == 3; /* reusue looker for implicit return value */
}
#endif
/* for (( i=0; $i < 100; i = $i + 1 )) ; do echo -n at $i; ./sphenic $i ; done */
```
I borrowed betseg's previous answer to get to my version.
This is my version of betseg's algorithm, which I golfed to get to my solution:
```
/* betseg's repaired program for sphenic numbers
*/
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
int sphenic( int candidate )
{
int probe, found, dups;
for( probe = 2, found = dups = 0; probe < candidate && !dups; /* empty update */ )
{
int remainder = candidate % probe;
if ( remainder == 0 )
{
candidate /= probe;
++found;
if ( ( candidate % probe ) == 0 )
dups = 1;
}
++probe;
}
return ( candidate == probe ) && ( found == 2 ) && !dups;
}
int main( int argc, char * argv[] ) { /* Make it command-line callable: */
int parameter;
if ( ( argc > 1 )
&& ( ( parameter = (int) strtoul( argv[ 1 ], NULL, 0 ) ) < ULONG_MAX ) ) {
puts( sphenic( parameter ) ? "true" : "false" );
}
return EXIT_SUCCESS;
}
/* for (( i=0; $i < 100; i = $i + 1 )) ; do echo -n at $i; ./sphenic $i ; done */
```
[Answer]
# Javascript (ES6), 87 bytes
```
n=>(a=(p=i=>i>n?[]:n%i?p(i+1):[i,...p(i,n/=i)])(2)).length==3&&a.every((n,i)=>n^a[i+1])
```
Example code snippet:
```
f=
n=>(a=(p=i=>i>n?[]:n%i?p(i+1):[i,...p(i,n/=i)])(2)).length==3&&a.every((n,i)=>n^a[i+1])
for(k=0;k<10;k++){
v=[30,121,231,154,4,402,79,0,60,64][k]
console.log(`f(${v}) = ${f(v)}`)
}
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~135~~ 121 bytes
* Quite long since this includes all the procedures: prime-check, obtain-prime factors and check sphere number condition.
```
lambda x:(lambda t:len(t)>2and t[0]*t[1]*t[2]==x)([i for i in range(2,x)if x%i<1and i>1and all(i%j for j in range(2,i))])
```
[Try it online!](https://tio.run/##XYwxDsIwEAR7XnFNpDtE4bi0cD7iuDBKAheZS2K5MK83JKJANLtbzM76yo9FdN1sX2N43oYAxeB3ZRNHwUydDjJAdsqfs2v30N7aQugYpiUBAwukIPcR9aUQT1Aavrb7ibujQozIzXzQ8y/NRJ7qv0QpMif4eDZkMmtiycD1DQ "Python 2 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 59 bytes
```
lambda x:6==sum(5*(x/a%a+x%a<1)+(x%a<1)for a in range(2,x))
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHCyszWtrg0V8NUS6NCP1E1UbtCNdHGUFNbA0Kn5RcpJCpk5ikUJealp2oY6VRoav4vKMrMK1FI0zAxMNL8DwA "Python 2 – Try It Online")
[Answer]
# J, 23 bytes
```
0:`((~.-:]*.3=#)@q:)@.*
```
[Try it online!](https://tio.run/##y/r/P91WT0HBwCpBQ6NOT9cqVkvP2FZZ06HQStNBT4urAChpbKBgZGyoYGhqomBiYMSVBhSyUDA0MlQwUTC3VDBQMAMiEwWu1OSMfIV0hQIYI@3/fwA "J – Try It Online")
Handling 8 and 0 basically ruined this one...
`q:` gives you all the prime factors, but doesn't handle 0. the rest of it just says "the unique factors should equal the factors" and "the number of them should be 3"
[Answer]
# PHP, 66 bytes:
```
for($p=($n=$a=$argn)**3;--$n;)$a%$n?:$p/=$n+!++$c;echo$c==7&$p==1;
```
Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/285093bffbdb0bb5f7ac3cb1125b6bbb91c4f5e1).
Infinite loop for `0`; insert `$n&&` before `--$n` to fix.
**breakdown**
```
for($p=($n=$a=$argn)**3; # $p = argument**3
--$n;) # loop $n from argument-1
$a%$n?: # if $n divides argument
$p/=$n # then divide $p by $n
+!++$c; # and increment divisor count
echo$c==7&$p==1; # if divisor count is 7 and $p is 1, argument is sphenic
```
**example**
argument = `30`:
prime factors are `2`, `3` and `5`
other divisors are `1`, 2\*3=`6`, 2\*5=`10` and 3\*5=`15`
their product: `1*2*3*5*6*10*15` is `27000` == `30**3`
[Answer]
# VB.NET (.NET 4.5), 104 bytes
```
Function A(n)
For i=2To n
If n Mod i=0Then
A+=1
n\=i
End If
If n Mod i=0Then A=4
Next
A=A=3
End Function
```
I'm using the feature of VB where the function name is also a variable. At the end of execution, since there is no return statement, it will instead pass the value of the 'function'.
The last `A=A=3` can be thought of `return (A == 3)` in C-based languages.
Starts at 2, and pulls primes off iteratively. Since I'm starting with the smallest primes, it can't be divided by a composite number.
Will try a second time to divide by the same prime. If it is (such as how 60 is divided twice by 2), it will set the count of primes to 4 (above the max allowed for a sphenic number).
[Try It Online!](https://tio.run/##hdJRS8MwEAfw596nOPYgK1JJ02xjDxGCOhhYXxz44ku3ZXrQXaBNxW9fY1UMKCRvCb/8udzljfqhaYt909OhYOuLs2M31u44tBbrEm7pjIRNj8Tevthu3Ax88OQYzZxz2LgOScudQ4btCRnDzXAgdq@WwVzqEvhZE9zxEbenPwKNVvBg3z0YbXQ1sZ/8MXsc9lg3xJBlN45719qrp468vSe281klEItrnOFFqKQSeQ4Zfq9/dCnLXx02CS6riIdNKn2hovSFSnCFUelJLGSEhUzw1TrKXq0TWsSVpHq4jDu@TGoV6@mVn@MNQ53G/PXDxg8)
[Answer]
# JavaScript (ES6), 80 bytes
```
n=>(p=(n,f=2)=>n%f?p(n,f+1):f,(a=p(n))<n&&(b=p(n/=a))<n&&(c=p(n/=b))==n&a<b&b<c)
```
Using a recursive function to get the smaller factor.
Output 1 if sphenic, false if there are 2 or less factors and 0 otherwise
**Test**
```
F=
n=>(p=(n,f=2)=>n%f?p(n,f+1):f,(a=p(n))<n&&(b=p(n/=a))<n&&(c=p(n/=b))==n&a<b&b<c)
;[30,121,231,154,4,402,79,0,60,64,8,210].forEach(
x=>console.log(x,F(x))
)
```
[Answer]
# Dyalog APL, ~~51~~ ~~49~~ ~~48~~ ~~46~~ ~~45~~ 43 bytes
```
1∊((w=×/)∧⊢≡∪)¨(⊢∘.,∘.,⍨){⍵/⍨2=≢∪⍵∨⍳⍵}¨⍳w←⎕
```
[Try it online!](http://tryapl.org/?a=%7B1%u220A%28%28w%3D%D7/%29%u2227%u22A2%u2261%u222A%29%A8%28%u22A2%u2218.%2C%u2218.%2C%u2368%29%7B%u2375/%u23682%3D%u2262%u222A%u2375%u2228%u2373%u2375%7D%A8%u2373w%u2190%u2375%7D30&run) (modified so it can run on TryAPL)
I wanted to submit one that doesn't rely on the dfns namespace whatsoever, even if it is **long**.
[Answer]
# J, ~~15~~ ~~14~~ 19 bytes
Previous attempt: `3&(=#@~.@q:)~*`
Current version: `(*/*3=#)@~:@q: ::0:`
# How it works:
```
(*/*3=#)@~:@q: ::0: Input: integer n
::0: n=0 creates domain error in q:, error catch returns 0
q: Prime factors of n
~:@ Nub sieve of prime factors 1 for first occurrence 0 for second
(*/*3=#)@ Number of prime factors is equal to 3, times the product across the nub sieve (product is 0 if there is a repeated factor or number of factors is not 3)
```
This passes for cases 0, 8 and 60 which the previous version didn't.
[Answer]
# Regex (ECMAScript), 46 bytes
```
^((?=(xx+?)\2*$)(?=(x+)(\3+$))\4(?!\2+$)){3}x$
```
[Try it online!](https://tio.run/##TY/BbsIwEER/BSIEu6QJCdAecE1OPXDh0B6bVrJgcdwax7INpFC@PQ2VKvU2ozfS6H2Io/Abp2xIvFVbcvvafNJX67ihU@@Z5FNjAc58ORm37wAFh6aJCyyn4wH@thihnMUDxHIORb@c3uJldm0G7XhyxjTUL8EpIwFTr9WG4OEumSMyzzN2qpQmAM0dia1WhgCxz81Ba7xIrlNvtQowSkbI1A7AcJlqMjJUuJx@fyu/FmtQ3ArnaWUCyNfsDfEP0H9glnmRL24YQ@XqU7QyR6HVtueEkbToRbFmu9oBU4@cmIpj7A6jJkodWRIBFKZ7ETYVuE7OD4e2Uwpws8iZPQQfXDdh12ubJfl9lv0A "JavaScript (SpiderMonkey) – Try It Online")
This works similarly to [Match strings whose length is a fourth power](https://codegolf.stackexchange.com/questions/19262/match-strings-whose-length-is-a-fourth-power/21951#21951) and very similarly to part of [Is this a consecutive-prime/constant-exponent number](https://codegolf.stackexchange.com/questions/164911/is-this-a-consecutive-prime-constant-exponent-number/179412#179412):
```
^
( # Loop the following:
(?=(xx+?)\2*$) # \2 = smallest prime factor of tail
(?=
(x+)(\3+$) # \3 = tail / {smallest prime factor of tail}; \4 = tool to make tail = \3
)\4 # tail = \3
(?!\2+$) # assert that tail is no longer divisible by \2
){3} # Execute the loop exactly 3 times
x$ # assert tail == 1
```
] |
[Question]
[
The [Fibonacci sequence](http://oeis.org/A000045) is a sequence of numbers, where every number in the sequence is the sum of the two numbers preceding it. The first two numbers in the sequence are both 1. Here are the first few terms:
```
1 1 2 3 5 8 13 21 34 55 89 ...
```
---
Write the shortest code that either:
* Generates the Fibonacci sequence without end.
* Given `n` calculates the `n`th term of the sequence. (Either 1 or zero indexed)
You may use standard forms of input and output.
(I gave both options in case one is easier to do in your chosen language than the other.)
---
For the function that takes an `n`, a reasonably large return value (the largest Fibonacci number that fits your computer's normal word size, at a minimum) has to be supported.
---
### Leaderboard
```
/* Configuration */
var QUESTION_ID = 85; // 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 = 3; // 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: 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="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]
# [APL(Dyalog Unicode)](https://dyalog.com), 16 bytes [SBCS](https://github.com/abrudz/SBCS)
```
{⊃⊃(+/,⊃)⍤⊢/⍵/1}
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=c3vUNqH6UVczEGlo6@sAKc1HvUsedS3Sf9S7Vd@wFgA&f=e9Q39VHbBLdDKx71bjYyAAA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f)
Straightforward "repeatedly add previous two elements" style approach. Not as short as [using pascal's triangle](https://codegolf.stackexchange.com/questions/85/fibonacci-function-or-sequence/223225#223225), but I'm still pretty proud of this :-)
-1 thanks to [Ad√°m](https://codegolf.stackexchange.com/users/43319/ad%c3%a1m) for reminding me of the atop operator, also known as the "atoperator". Also from Ad√°m, an optional "full program" version of this for -2:
```
⊃⊃(+/,⊃)⍤⊢/⎕/1
```
Code breakdown:
```
{⊃⊃(+/,⊃)⍤⊢/⍵/1} full dfn
‚çµ/1 make a list of n 1s
/ reduce over them with the following tacit function
⍤⊢ apply the following tacit function(?) to only the
previous element (in js, think (a,b)=>f(a))
( , ) return a list of
+/ sum of elements ([5,3]=>8)
⊃ first element ([5,3]=>5)
‚çù([5,3]=>[8,5])
after the reduce, you're left with
a scalar of the value [fib(n),fib(n-1)]
⊃ take the first element of this scalar (the array)
⊃ take the first element of the array (this is the end result)
```
As you can see, I'm still learning how APL works :P
If there are any terminology fixes you want to make in my explanation, go ahead; You have my blessing.
[Answer]
# [Seed](https://github.com/TryItOnline/seed), ~~4694~~ 4502 bytes
```
39 23345386873944734309285705649562214322923535338513787840726059344836991733232701124858784406171983413525769035739193091317312821286862091673034093258254737808529480740867073160694207283540732802589654087348246306424108351751311067631335648365532710947883728455312678903999543414986443810435493370315134647072481870757046559560767136040676281671376819795324434856453735428264762843673716931661746853554648863000837820618766325590788356124601042099541341483064315601051750207795784533758073620813013115058115202328602261019521188162907432705317709462265407997435677959431637608739188384820535674569023665708824769117130584628086812767619300150936306513016713438624735631896208226558553705578499273228365561706607508974248633654644472401969256417949202545503229189330457914013293106347633234904257897628188377211123547522316430704423351649833550317940803484242023657434716958957587230473447472170005697587796499855927956924703860969370032077181183813997697920001129271041258462117064842855557817828287309864524148521039064850419014169734078927801370682493891194692916817142423371375512874755307643229558474820620773013367601053438535142499961672800471263088573030714197841432529737819978024272023115971994335629080760807110601625840500005576870897474597727212673444634680054468191797452281171657965522840129388173724585980135600170025063620602628298627811946062091546889131371926823568681212834659514998682306098670560578318063077703702015608052686405555782215469820110984687203004291914156230320625462064509758167591458209331235212640744714944466265540624319127738893716421169144022527159634296736260757337640921918849758954315864968212488657203226533587353649351778992581839569265033006103790337825946891770665589403131544197363786202809251067880755092540881383788858825619755294045426872602952477879200662412263820311579658891410984567942455376104064634087560919309116469779337448222971714205506106434861563361065264676346668562754032388044586603191705003186050941101737238753507972188516844227916598403811945061789829209022797794856907795280845148337927336190754837895578035971541077446106601429711198909985434167448288125565008326994953358507196336677928811063398215196756813330927829954298340363790942335608247284708980931664255175263323494474655761771711383684020341286483311232450751637188832338282365001980619004736926421020545780168645284628043949398052855672494054844858796879547004560821501647027627620931639915989753539985160519138882067784198444595441811191399424880792691274895217945599103951284792036009843684640644727200173221626567038906492094115422297154223582626065131092394499833564570471955561529154762920901660552470118203300492660926353444889031479441391716424199093929419050805652092712224713014163928963683320445942834620765638299957157761471954992453965174566767052457734421384797861892548612233678879032571407415763995799697084460449481011980933595196444998930307697403672188673825999360332797937744985054511100836407779016165673872373310879592118399300133957780585475517066306666920397584925551254210311998315301028471463539416320653567122160674748915331494295984381121190145666938252633808615711556028673805375510446823318750130981978154654997326727239404525161535622829359058005003740269566983082692378752252198224696254750416200980706704359975518565261545420238758226454680563033057001226125143840414367435620075434502664984902148647078854467653648067041037379150849558209574954581189083630370505506375071080959718696461782683034278484505125465265492405192125616634322283908654348532913099106491870966062276727286614470801650571178850146397543614007581120988735292604484768834605242986004904531743614154630006898576385883749714930636531225280325429278056803694383205579251797535306160456389603169599349989707250713018909969811190663566801819447003975601708056252841800628364818930316430260043879135073603348919031644234002981192629576497660461677947610006543231706577837438811265977164354969644885825582261812180155492583995120383156018469389467006878690072374841382066122175919585112489442594496493463386891710103741087324632245353507660394419350165419526162955982962335197477336304033108148298040661871462588450794544521467248068540365914505422139306015926783904272029251862004795498004645359369772500371366215160030879374914060894959826814924777847813129579229461420328680050563398486579073401384070598971755243256100966805691895631455236232588087146040702221938793149485419052426135144305222421870942178316091451568136489010664122415628294236744095902991276097097917
```
[Try it online!](https://tio.run/##LdiJlV03DAPQVlKC9if2E1eQ/s/kQuM4sTN/kUgQAPH8358///78zPpnzLn2vOd@s9b65pqtxt1f22fVPmP0NceoMbdf8@4@v/vd1b5x2q651p2nqn9zjjm@1vtYd@cTq53@9bpz9bnH/k61uV3Syw19@kYfd/jv3DO8cr7Z5mo1x75jq@S77e5R67ZvtXu@5hunnVrD5XduNcxxm4/X8YMG1h3rzHbWWL35RP@U23s735l9Th0pdm919lbru3c6aHmhj/Nd9VXVXgpedc9a8/a23FNzfm12Z62zlKHDfv0JpOU4KLXvfH2etnLVuD0/fef2@sptToLJAfPnNE07xafW1PLXT2kLVOtcEG9X3KuJpoHvDiDe7xyg7GqpeB8In6YyoKm2p9ybplWY19N1A5GrTcHMvg3BCePbZwseu@3r99FM7J42xumt1x69X6UP96yMEizfByccCL5fldf3ycHlsqPDgF6@NS/ofcG7axv0mOdA55qHuXc8mO50kpGCZYDrhAdNLTUzsp3aAhvUj285anaDVXWu39eUlJSWqobBjzdKuLUD/t2u6gzmTC/DEJXH0tWpAfn@1Sr9bsNuobOj52xrf9V9ag4zaGcqNjReBVw31ZtlWPLBppPA@vYYWicSs1@0s/2A4zPn5pZ2kfiqJOjCwOgzYhzd5vANl@Lp@pSn9EZllde/ckxpUm/4VBBogGjq17aSzbMbGqQ7lgL100@L3CpsXn08fHvwyP2OClgdhfwirTB6j3DFoDE9H9u@V60vBSoKvZx1weEMk6t5jc78C16m9vW0hU8@sDfhasJUcP85hBlpK4xNsWEafj9CZqa4ka8T2DFmPIAD1U0c2RF@czq53BW7ofrIv2uUvtf4AibGFj9BPdxAUqQ@@S36Rp3033YLpLyGPEMIbCzDgzWBg507kJmP@D/HG5hPoFIYalh8JD9hBELQgiLGQr0KKMTVMrKxMUWPhIMeA65Aezi152PYd28MDlA1AOmbj/QQczu76Bl13nBGxdgcbVb47mTYGf1HwZHzbdsRR2dvnNzY8QVkXZeBYxTs0JWtAhAwM2SBxkqJi7zQC@Lb23yV2maIHEAMHBEVE1xORMa@BmUXgX76r7jTwikSZufDXD5DgOGoE0eJ8Bg/AtgZPUawcl08tG9V14nBx8926oyQDQ8b9/Rm/BnlCJTI5mP9oSLt8KP5seMYIK854PyicxSjMMhCIWzhHF@WBzo5JT5/EYIU/USJpBIPxTBGxCrUln1C9msEORPkeksRT0wwICOcBFPYFjpkkutBzdpsniwL1hWjD5f4nyH9XWmwoqMv28JWHCTxPc2YXTo62QLHiOjCT@a6spdAz/hxSMW8RwPLoHha5vCF0XiBH4zYzB8lp1vnZsh4rTnaZEV8A4UVyjfCxtwJXQQ19Ja3lZY1VG81xInXzuaAND9Vkzf2CmAVqlnW6rdffBw/emxWM15zul0Zt8qqPK9ZWNtQxmdrDXlAdMikFcmCHZ6tkQ/FZaeiLFMUIgwukcBh0FlmI3GhZawuePZKAiZEkxG0MWdXMucsufHXrOOmJ6JHEoBn6BAhINXZb2kx5m12GszaApoqhRnynalZQy39x5vDQpz3dcsibniecf4uryUjlfqpksHyMbf7HPyTedAdsirFsNRtufUEBusu/77imTcJ8abEqWAo0sBC0TfW@cUBDREHKhy/QTuOn92G24qLOtfNujZPC6Pi5rHjFRYLIWFrEDgh6Yr7xbior0fkJ4sl7h9eoBTQH1Pzp4mNqDrbGOlHEmG97QaCL46NGoRERT6vpcctE0HxbCz7aTwBO9yLftOkXm6yVVefjuSF5yraNONpt2QH7TgdTYQKNOiw5IEVvIYUoB2zjjIAERe1YrQywxqLlVZN/5WXdCD0kG5PFKEwGvLKF/sfYFYFz7D/WYQ/NT1jG7EbO7/HFB2XOTEA6xfv0N/VxEN//ZFwxsUrKQM89daXT4a5T5LMMcZVog04Ij1WSifGHVaZaXQSAyYL@PWMZSYdEKLkmoSVNKaIZCSKUT@AbgLIfpHH7vBPBh7HhffOSt5hLrZnaN1qRuMbi88cKmii2EtpPWxAt2xss3Sr/rhhqINzLk8u2LkirURqiW6QwRjkHq9Hqz31tGxTOEqqGJ@okU2eTZVxYN4JCedzXjbtlGzw7E446qo9lwMfcrtS7cSjtzxp7GwdoKPEqay1L6HF/N0ig5muTFpx9n5DIIfH3tszyUTHlX2MWzPEROIWi4eUnMEkEjfOi7VO/GJosvNJpBMCPfrcF/iZ7IpZZ23dd2cWFJOicB/cb7HKeuiXZI3tN6E2gfWZP5QYIYpXPPVqZMWcLaE88jA/DuKTmV9agJrsimCWJ7UZdgIW3jv37PcwIbEG6MpaqTyM1En8SLAGtfVhYWMubjnXzNJCCw8qTXo33WbQYMw@puRwHFmEF/qKZhJtImVTE23ftzLTPJrYyDciyWY1uEqKmIlFeZQaWS4zXHxxksnThdjGc5PNsqm/X/9juideyZCy70wf4Z@k8pQVzFD47RqkiBOG@BiiLxRLh4/@J7ksF@Vmnqm@PB3kKS3afHF9pBWcANvO0xA2hPn13rZpADJyBxzIQKKRsdWWsMq2svKdCjo5FOsiR30nIwpSyZi5xNwy2pXAMfZjX0/uU@7OTHcEbcoM@PdZjUcnZKNWIGVLVlBMwBx6UsiJP/VkNw8Q@z1a6zqRaOV5wZxmntzjqC2MzFMvuXl5xARfSEiSiO/SWtiw8qB38pRndVDgec8wicrJAJ5O2nMgzAdHYk6ePxFH8eFoVg4XpowsP1q4iS3npcuWFcLfE2vtuDxSzzxJJb1n6Elqdkg8OvE/z8ObQyagP/17gD4JBiY144EhFqLapIkTFbn0KOPLkuQvqBaPtr2MaSVf3pftI3Y7eiV1yjQzD3j5C4v29m5PCMwzRkZa53lDHgfzvGmdCgQjfwPB7dJ2y/doD3ypKC5591tY9HF6HmqQa2djjSdDfyTJJxQy@hdwEJGZQjLp8mV02KJcklMcATrZ6b7i@wj6/fz8Dw "Seed – Try It Online")
[Answer]
# [Desmos](https://desmos.com/calculator), 41 bytes
### Code in ticker:
```
l->join(l,l[L]+l[L-1])
```
### Code not in ticker
```
l=[1,1]
L=l.length
```
[Try it online](https://www.desmos.com/calculator/xvokybqceh)
[Answer]
## Dyalog APL, 17 characters (17 bytes SBCS)
```
{({⍵,+/¯2↑⍵}⍣⍵)⍺}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/v1qj@lHvVh1t/UPrjR61TQSyax/1LgZSmo96d9X@T3vUNuFRb9@jvqme/o@6mg@tNwYp6psaHOQMJEM8PIP/GyqkKRiZAgA "APL (Dyalog Extended) – Try It Online")
The arguments are the initial sequence on the left, and the number of additional terms to generate on the right. The call can be made shorter by [replacing](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/v1qj@lHvVh1t/UPrjR61TQSyax/1LgZSmoa1/9MetU141Nv3qG@qp/@jruZD641BSvqmBgc5A8kQD8/g/2kKRqYA "APL (Dyalog Extended) – Try It Online") the `⍺` with `1`, but then it can't generate an arbitrary sequence, only the one the question is actually about. Incidentally, replacing the `+` with a `-` will [produce the other half of the sequence](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/v1qj@lHvVh1d/UPrjR61TQSyax/1LgZSmo96d9X@T3vUNuFRb9@jvqme/o@6mg@tNwYp6psaHOQMJEM8PIP/GygYKqQpGJkCAA "APL (Dyalog Extended) – Try It Online").
As a bonus, the Java answer mentions Binet's formula (with rounding), which I [happened to have already written down](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/v/pRT5eeqbbGo96tWo96V2g/6phxePuj3sW2QI6h5uHtplp6prX/0x61TXjU2/eob6qn/6Ou5kPrjR@1TQTygoOcgWSIh2fw/zSFR72bjUwB "APL (Dyalog Extended) – Try It Online") (23 characters):
```
{⌊.5+(⍵*⍨+∘÷⍣=⍨1)÷5*.5}
```
[Answer]
## Python
```
a,b,n=0,1,10
while n:a,b,n=b,a+b,n-1;print b
```
[Answer]
Python, 34 chars first variant, 31 chars for second variant,
```
a,b=1,1
while 1:print a;a,b=b,a+b
```
Second variant:
```
f=lambda x:x<2 or f(x-2)+f(x-1)
```
[Answer]
## Python O(1) Nth number, 91 char
48 characters for the import, a newline, 42 for the rest. I know it's longer than most here and that the question is a bit old, but I looked through the answers and I didn't see any that use the constant-time floating-point calculation.
```
from math import trunc as t,pow as p,sqrt as s
r=s(5);i=(1+r)/2;f=lambda n:t(p(i,n)/r+.5)
```
From there you call `f(n)` for the nth number in the sequence. Eventually it loses precision, and is only accurate up through `f(70)` (190,392,490,709,135). `i` is the constant Phi.
[Answer]
## Perl, 51 (Loopless)
The following code uses Binet's formula to give the Nth Fibonacci number without using any loops.
```
print((($p=5**.5/2+.5)**($n=<>)-(-1/$p)**$n)/5**.5)
```
[Answer]
## PHP - ~~109~~ ~~97~~ ~~88~~ 49 characters
```
<?for($a=$b++;;$b+=$a=$b-$a){$s+=$b%2*$b;echo$a;}
```
[Answer]
Perl - 39 chars
```
($a,$b)=($b,$a+$b||1),print"$b
"while$=
```
[Answer]
# C#
### Generated as a stream (65 chars):
```
IEnumerable<int>F(){for(int c=1,s=1;;){s+=c=s-c;yield return c;}}
```
Could be reduced to 61 characters using non-generic `IEnumerable`. Of course, if you include the required `System.Collections.Generic`, then it's a few more characters.
[Answer]
# APL: 26 characters
This is a function which will print out the `n` and `n-1` Fibonacci numbers:
```
{({⍵+.×2 2⍴1 1 1 0}⍣⍵)0 1}
```
For example,
```
{({⍵+.×2 2⍴1 1 1 0}⍣⍵)0 1}13
```
yields the vector:
```
233 144
```
[Answer]
**Mathematica,26 chars**
```
If[#>1,#0[#-1]+#0[#-2],#]&
```
[Answer]
## F# - 42 chars
```
Seq.unfold(fun(a,b)->Some(a,(b,a+b)))(0,1)
```
[Answer]
# [JAGL](https://github.com/globby/Jagl) V1.0 - 13 / 11
```
1d{cdc+dcPd}u
```
Infinite Fibonacci sequence. Or, if not required to print:
11 bytes
```
1d{cdc+cd}u
```
[Answer]
# Octave, 26 chars
```
f=@(n)([1 0]*[1 1;1 0]^n)(2)
```
Basically, a copy of my solution from [Calculating (3 + sqrt(5))^n exactly](https://codegolf.stackexchange.com/questions/48779/calculating-3-sqrt5n-exactly/48788#48788).
![[a b] x [1 1 ;1 0] equals [a+b a]](https://i.stack.imgur.com/gKY9a.gif)
, so
![[f(1) f(0)] x [1 1 ;1 0]^n equals [f(n+1) f(n)]](https://i.stack.imgur.com/5TCJa.gif)
It's a disaster to do unnecessary\* loops in Octave/Matlab. It's neither elegant, nor fast, let alone golfy.
---
\*All loops that can be vectorized are unnecessary :).
[Answer]
# ArnoldC, 451 bytes
```
IT'S SHOWTIME
HEY CHRISTMAS TREE a
YOU SET US UP 1
HEY CHRISTMAS TREE b
YOU SET US UP 1
HEY CHRISTMAS TREE c
YOU SET US UP 1
STICK AROUND c
TALK TO THE HAND a
GET TO THE CHOPPER a
HERE IS MY INVITATION a
GET UP b
ENOUGH TALK
TALK TO THE HAND b
GET TO THE CHOPPER b
HERE IS MY INVITATION b
GET UP a
ENOUGH TALK
GET TO THE CHOPPER c
HERE IS MY INVITATION 1e300
LET OFF SOME STEAM BENNET a
ENOUGH TALK
CHILL
YOU HAVE BEEN TERMINATED
```
This is actually my first ArnoldC program. Horrible for golfing, but great for lolz!
Produces an stream of Fibonacci numbers up to 1.1253474885494065e+274.
## Explanation
```
IT'S SHOWTIME #start program
HEY CHRISTMAS TREE a #declare a...
YOU SET US UP 1 #and set it to 1
HEY CHRISTMAS TREE b #declare b...
YOU SET US UP 1 #and set it to 1
HEY CHRISTMAS TREE c #declare c...
YOU SET US UP 1 #and set it to 1
STICK AROUND c #while c is truthy
TALK TO THE HAND a #output a
GET TO THE CHOPPER a #assign a to...
HERE IS MY INVITATION a #a...
GET UP b #plus b
ENOUGH TALK #end assignment
TALK TO THE HAND b #output b
GET TO THE CHOPPER b #assign b to...
HERE IS MY INVITATION b #b...
GET UP a #plus a
ENOUGH TALK #end assignment
GET TO THE CHOPPER c #assign c to...
HERE IS MY INVITATION 1e300 #whether 1e300...
LET OFF SOME STEAM BENNET a #is greater than a (returns 0 or 1)
ENOUGH TALK #end assignment
CHILL #end while
YOU HAVE BEEN TERMINATED #end program
```
[Answer]
# Ruby, 28 bytes
```
->f{loop{f<<p(f[-1]+f[-2])}}
```
Usage:
```
->f{loop{f<<p(f[-1]+f[-2])}}[[-1,1]]
```
[Answer]
# ùîºùïäùïÑùïöùïü, 3 chars / 6 bytes (noncompetitive)
```
Мȫï
```
`[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter2.html?eval=true&input=3&code=%D0%9C%C8%AB%C3%AF)`
More builtins!
`math.js + numbers.js = hella functions`
[Answer]
# [PARI/GP](http://pari.math.u-bordeaux.fr), 9 bytes
```
fibonacci
```
Alternate solution (21 bytes), for those disliking the built-in:
```
n->([1,1;1,0]^n)[1,2]
```
Alternate alternate solution (21 bytes):
```
n->imag(quadgen(5)^n)
```
I also posted all three solutions (in ungolfed form) to [Rosetta Code's Fibonacci page](http://rosettacode.org/wiki/Fibonacci_sequence#PARI.2FGP).
[Answer]
# Reng v.2.1, 18 bytes
(Noncompeting, postdates question)
```
11{:nAo}#xxx:)+x5h
```
`11` initializes the stack with 2 `1`s. `{:nAo}#x` sets the command `x` to mean "duplicate and output as number" (`:n`) then "output a newline" (`Ao`, A = 10). Then, `xx` prints the initial 2 `1`s. `:` duplicates the TOS and `)` rotates the stack, so it becomes `b a b`. `+` adds the two figures, making it `b (a+b)`. `x` prints and leaves this new result on the stack. `5h` jumps back `5` spaces, and the loop continues.
[Try it out here!](https://jsfiddle.net/Conor_OBrien/avnLdwtq/) [Or check out the github!](https://github.com/ConorOBrien-Foxx/Assorted-Programming-Languages/tree/master/Reng)
[Answer]
# Fuzzy Octo Guacamole, 11 bytes
```
01(!aZrZo;)
```
This takes the infinite route.
Explanation:
`01` pushes `0` and then `1` to the stack.
`(` starts a infinite loop.
`!` sets the register, saving the value on the top of the stack and storing it. It doesn't pop though.
`a` adds the 2 values.
`ZrZ` reverses the stack, pushes the register contents, and reverses again. This pushes the stored number to the *bottom* of the stack.
`o;` peeks and prints.
`)` ends the infinite loop.
Then the whole things starts again from the `(`.
---
As a a side note, this is quite fast to hit the max long size possible in Python. The last number it prints is `12200160415121876738`, and it repeats that forever.
[Answer]
# Python 2, 43 bytes
```
def f(n):k=9**n;return k**-~-~n/~-(k*~-k)%k
```
[Answer]
# Perl 5, 23 bytes
22 bytes, plus 1 for `-nE` instead of `-e`.
```
say$.-=$b+=$.*=-1;redo
```
[Hat tip.](http://c2.com/cgi/wiki?PerlGolf)
[Answer]
# [Cylon](https://github.com/tkaden4/Cylon) (Non-Competing), 12 bytes
The language is in development, Im just putting this up here.
```
1:øÌ[:ì+Á])r
```
An explanation:
```
1 ;pushes a 1 to the stack
: ;duplicates the top of the stack
√∏ ;reads a number from stdin, pushing it to the stack
Ì ;non-pushing loop, doesn't push counter to the stack, but deletes it
[ ;start of function, to be pushed to the stack
: ;duplicate top of stack
ì ;rotate the stack, moving the copy to the back
+ ;replaces top two objects on the stack with their sum
Á ;push the result to the shadowing stack (non-consuming)
] ;end of function
) ;switch to shadowed stack
r ;standard library call, reverses a stack
;stack implicitly printed
```
[Answer]
# bc, 21
```
for(b=1;b=a+(a=b);)a
```
The trailing newline is significant.
Outputs the entire sequence. `bc` has arbitrary precision arithmetic, so this continues forever.
[Answer]
# [OIL](https://github.com/L3viathan/OIL), 46 bytes
This program writes an infinite unstoppable stream of fibonacci numbers. It is mostly copied from the standard library but fit to the requirements and golfed.
```
14
add
17
17
14
swap
17
17
4
17
11
6
0
0
1
```
[Answer]
# [Python 2](https://docs.python.org/2/), 30 bytes
```
f=lambda n:n<3or f(n-2)+f(n-1)
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIc8qz8Y4v0ghTSNP10hTG0QZav4vKMrMK9HITSzQSNNRKErMS0/VMNRRMDLV1NT8DwA "Python 2 – Try It Online")
One catch: this outputs `True` instead of `1`. This is allowed by [this meta consensus](https://codegolf.meta.stackexchange.com/a/9067).
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), 6 [bytes](https://github.com/splcurran/Gaia/blob/master/codepage.md)
```
0‚ÇÅ@+‚Çå‚Çì
```
I might make a built-in for this in the future, but built-ins are boring anyway.
### Explanation
```
0‚ÇÅ Push 0 and 1
@ Push an input
+‚Çå‚Çì Add the top two stack elements, without popping them, (input) times
Implicitly print the top stack element.
```
[Answer]
# Python 2, ~~49~~ 40 chars
```
a,b=0,1
exec"a,b=b,b+a;"*input()
print b
```
### Function form, 44 chars
```
def f(n):a,b=0,1;exec"a,b=b,b+a;"*n;return b
```
My take on this challenge. Didn't find this kind of an answer yet. I hope it's a valid one.
Print's n:th Fibonacci number. Functions by multiplying the string inside exec n times and then executing it as Python.
Edit: input() instead of int(raw\_input())
] |
[Question]
[
# Challenge
So, um, it seems that, while we have plenty of challenges that work with square numbers or numbers of other shapes, we don't have one that simply asks:
Given an integer `n` (where `n>=0`) as input return a truthy value if `n` is a perfect square or a falsey value if not.
---
## Rules
* You may take input by any reasonable, convenient means as long as it's permitted by [standard I/O rules](https://codegolf.meta.stackexchange.com/q/2447/58974).
* You need not handle inputs greater than what your chosen language can natively handle nor which would lead to floating point inaccuracies.
* Output should be one of two consistent truthy/falsey values (e.g., `true` or `false`, `1` or `0`) - truthy if the input is a perfect square, falsey if it's not.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so lowest byte count wins.
---
## Test Cases
```
Input: 0
Output: true
Input: 1
Output: true
Input: 64
Output: true
Input: 88
Output: false
Input: 2147483647
Output: false
```
[Answer]
# [Ohm](https://github.com/nickbclifford/Ohm), 2 bytes
```
Ʋ
```
Uses `CP-437` encoding.
## Explanation
Implicit Input -> Perfect square built-in -> Implicit Output...
[Answer]
# Java 8, 20 bytes
```
n->Math.sqrt(n)%1==0
```
Input is an `int`.
[Try it here.](https://tio.run/##hY7BCoJAEEDvfcVcgt2DkhAhiP2BXjxGh3Hdak1nzR2FCL/d1vIaXQZm3oM3NY4Y2E5TXd1n1aBzkKGh1wbAEOv@gkpDvqwApbWNRgIlPAKSib9OGz8cIxsFORCkMFNwzJBvoXv0LEhuozTdzcnidUPZeG/VR2sqaH1MFNwbup7OgPJbKp6OdRvagcPOI25IUKhEJD/Nn/yw/yPEsVy/nuY3)
[Answer]
# [Add++](https://github.com/SatansSon/AddPlusPlus), ~~24~~ ~~13~~ 11 bytes
```
+?
S
%1
N
O
```
[Try it online!](https://tio.run/##S0xJKSj4/1/bnitOz5RL1ZDLj8v/////RoYm5iYWxmYm5gA "Add++ – Try It Online")
I removed the clunky function at the top and rewrote it into the body of the question to remove 11 bytes.
As the first section is already explained below, let's only find out how the new part works
```
S Square root
%1 Modulo by 1. Produced 0 for integers and a decimal for floats
N Logical NOT
```
## Old version, 24 bytes
```
D,i,@,1@%!
+?
^.5
$i,x
O
```
[Try it online!](https://tio.run/##S0xJKSj4/99FJ1PHQcfQQVWRS9ueK07PlEslU6eCy/////9GhibmJhbGZibmAA "Add++ – Try It Online")
The function at the top (`D,i,@,1@%!`) is the main part of the program, so let's go into more detail.
```
D, Create a function...
i, ...called i...
@, ...that takes 1 argument (for this example, let's say 3.162 (root 10))
1 push 1 to the stack; STACK = [1, 3.162]
@ reverse the stack; STACK = [3.162, 1]
% modulo the stack; STACK = [0.162]
! logical NOT; STACK = [False]
+? Add the input to accumulator (x)
^.5 Square root (exponent by 0.5)
$i,x Apply function i to x
O Output the result
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~28 27~~ 25 bytes
* Thanks to @mdahmoune for 1 byte: compare int of root squared with original
* 2 bytes saved: lambda shortened
```
lambda x:int(x**.5)**2==x
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHCKjOvRKNCS0vPVFNLy8jWtuJ/QRFIKE3DUFOTC8Y2QmIbI7EtkdWgaDDV1PwPAA "Python 3 – Try It Online")
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 12 bytes
```
{_),2f##)!!}
```
[Try it online!](https://tio.run/##S85KzP1flPm/Ol5TxyhNWVlTUbH2f91/MxMA "CJam – Try It Online")
[Answer]
# JavaScript on NodeJS & Chrome, 51 bytes
```
// OLD: t=n=>{i=Number.isSafeInteger;return i(n)&&i(n**.5)}
i=Number.isSafeInteger;t=n=>i(n)&&i(n**.5)
// TestCases:
let l=console.log;l(`t(1): ${t(1)}; t(64): ${t(64)}; t(88): ${t(88)};`)
```
[Try it online!](https://tio.run/##LYhBCsIwEEX3niILKUnBgKBSDHHvxo0XaKxjiYwTSaZuSs4eo3Tz/3vv6T4uDdG/eUPhDqWwJXuavb1MrxtE7dPVPeBMDCNEE4GnSMJLUk1Tt231XuUVAgu0Q6AUEDSG0aDsWW7VUazn32cjWB52i1f4h65bQoVselVK@QI "JavaScript (Node.js) – Try It Online")
[Answer]
# Python, ~~53~~ ~~50~~ ~~49~~ ~~48~~ ~~49~~ 48 bytes
This should in theory work for an input of any size. Returns `True` if the given number is a square, `False` otherwise.
```
f=lambda n,x=0:x<=n if~-(x<=n!=x*x)else f(n,x+1)
```
[Try it online!](https://tio.run/##RcrRCsIgFMbx@57iRDdaC7SJk8iHsU2Z4NxwBnbTq5sS2N35/b@zveO8@j5nI51anpMC3yVJ7ukhPVjzuaJ6HWU6J6zdrsGg8nChOG/B@ohIVwrB@PAjraSNnFVz1oIQNQjRwo2ygYmes6EOf2EMcIKgx1fY7erB2cXGYjXOespf "Python 3 – Try It Online")
### Explanation:
```
f= # assign a name so we can call it
lambda n,x=0: # counter variable x
x<=n # counter bigger than input?
if~-( ) # "negate" inner condition
x<=n # counter not bigger
n!=x*x # and n not square of x
else f(n,x+1) # else recurse
```
The condition is just a de-Morgan'd `if x>n or n==x**2`, i.e. we return if the counter is bigger than the input, or we found a proof for squareness.
Saved 1 byte thanks to Gábor Fekete.
[Answer]
# [Actually](https://github.com/Mego/Seriously), 6 bytes
```
;ur♂²c
```
[Try it online!](https://tio.run/##S0wuKU3Myan8/9@6tOjRzKZDm5L//zcAAA "Actually – Try It Online")
-2 bytes from Erik the Outgolfer
Explanation:
```
;ur♂²c
;ur range(n+1) ([0, n])
♂² square each element
c does the list contain the input?
```
This takes a while for large inputs - TIO will timeout.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~66~~ ~~43~~ 42 bytes
```
f(float n){return!(sqrt(n)-(int)sqrt(n));}
```
[Try it online!](https://tio.run/##PctBCsIwEEDRfU8xVoQZMCKCq4h3CUnTBpKpJtNV6dWNFYLL/@BbNVpbj4FtXNzwKOLCfJme3V@SkekHHn2cjZDuAgskExhphVfey2N/cv0ZPN7uBKQhD7JkhquGrbYPmNbGByzvLMikcJ@pBemt1o/10Yylqpi@ "C (gcc) – Try It Online")
Thanks to TheLethalCoder for the tip!
@hvd Thanks for saving a byte!
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 26 bytes
```
!([math]::Sqrt("$args")%1)
```
[Try it online!](https://tio.run/##Xc7RCoIwFAbg@z3FaczYwCBrqAhB79BlREgd82KZbpMC89nXMDPw3P3f@Q@c@vFEbUpUyrECdtC5BT/ec1uesuzQaMspy/XNUBFEwvWE7DkBPyFfh8CsblGMOZrlWM4gTT0UuTKTbCKZyHQby@S/EfCGALqhwSrv@KrxYvHqf2PnL2s0rbIelv5lVg1IGR99hc10JLJfm5LefQA "PowerShell – Try It Online")
[Answer]
# MIPS, 112 bytes
```
main:li $v0,7
syscall
sqrt.d $f0,$f0
mfc1 $a0,$f0
li $v0,1
beqz $a0,t
li $a0,0
syscall
b e
t:li $a0,1
syscall
e:
```
[Try it online!](https://tio.run/##Ky7IzP3/PzcxM88qJ1NBpcxAx5yruLI4OTEnh6u4sKhEL0VBJc1AB4i5ctOSDRVUEiEcqGJDrqTUwiqwaAlYDMgwgBuQpJDKVWIFFTaEC6da/f9vZPIfAA "Assembly (MIPS, SPIM) – Try It Online")
Outputs `1` if the input is square, `0` if not.
## Explanation
```
main:li $v0,7 #Start of program. Load service 7 (read input as float to $f0).
#Input can be an integer, but MIPS will interpret it as a float.
syscall #Execute.
sqrt.d $f0,$f0 #Overwrite $f0 with its square root, stored as a double.
mfcl $a0,$f0 #Move $f0 to $a0.
li $v0,1 #Load service 1 (print int from $a0).
beqz $a0,t #Branch to label 't' if $a0 = 0. Otherwise continue.
#If input is non-square...
li $a0,0 #Load 0 into $a0.
syscall #Execute (print $a0).
b e #Branch to label 'e'.
#If input is square...
t:li $a0,1 #Start of label 't'. Load 1 into $a0.
syscall #Execute (print $a0).
e: #Start of label 'e'. Used to avoid executing 't' when input isn't square.
```
A double in MIPS is 16 hexes. It shares its address with a float containing its low-order 8 hexes (`$f0` in this case). The high-order hexes are stored in the next register (`$f1`), also as a float.
```
float double
$f0 0000 0000 1111 1111 0000 0000
$f1 1111 1111
```
Taking the square root of a non-square number requires the entire double in order to be stored, meaning the high and low floats are populated. The square root of a square number only needs a few hexes from the double to be stored, and it is stored specifically in its high-order hexes. This means the low float is left at `0`.
If the low float equals `0`, the input is a square number.
[Answer]
# [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 95 bytes
```
[S S S N
_Push_0][S N
S _Duplicate_top][T N
T T _Read_STDIN_as_integer][N
S S N
_Create_Label_LOOP][S N
S _Duplicate_top][S N
S _Duplicate_top][T S S N
_Multiply_top_two][S S S N
_Push_0][T T T _Retrieve_input][S N
T _Swap_top_two][T S S T _Subtract][S N
S _Duplicate_top][N
T S S N
_If_0_jump_to_Label_TRUE][N
T T T N
_If_negative_jump_to_Label_FALSE][S S S T N
_Push_1][T S S S _Add][N
S N
N
_Jump_to_Label_LOOP][N
S S S N
_Create_Label_TRUE][S S S T N
_Push_1][T N
S T _Print_as_integer][N
N
N
_Stop_program][N
S S T N
_Create_Label_FALSE][S S S N
_Push_0][T N
S T _Print_as_integer]
```
Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.
Outputs `1`/`0` for truthy/falsey respectively. A few bytes could be saved if something like `00`/`0` for truthy/falsey is allowed instead.
[Try it online](https://tio.run/##JYxRCoBACES/x1N4iOg@EQv1FxR0fHfeijg4b9T/ur/xPsc5qjIzXAopesQhbklIGjiBgoiEA8ZabMKbBdTX9lX7NgE) (with raw spaces, tabs and new-lines only).
**Explanation in pseudo-code:**
```
Read STDIN as integer, and store it in the heap
Integer i = 0
Start LOOP:
Integer temp = i*i - input from heap
If(temp == 0):
Call function TRUE
If(temp < 0):
Call function FALSE
i = i + 1
Go to next iteration of LOOP
function TRUE:
Print 1 as integer
Stop program
function FALSE:
Print 0 as integer
(implicitly stop the program with an error)
```
*Here a port of this approach in Java:*
```
int func(int input){
for(int i=0; /*infinite loop*/; i++){
int m = input - i*i;
if(m==0) return 1;
if(m<1) return 0;
}
}
```
[Try it online.](https://tio.run/##XVBBboMwELznFaOcDCgJRFUVlfKEnnJse3AJVJvCGuF1pKrK2ykYtyU9eOWZ2d0Z7Vlf9OZ8@hiGstHW4kkTf60AK1qoBLGgdlyq6UPcOYkmFahNP3NFmmMXE9fEJBUaY7p4l4OSJHTCL2lRzPPYgGLKf6RatUWRRugrcT0jWwqP2S@fzvx1Nb2xdO6tGeOFlBdDJ7RjcnWUnvj9@RU6uEtlRaVR/geyJbi/W6LD4aZxn93CvYfef2ns1f/3OX5aqdqtcbLtxkjSsPJysn7Ai6yTcNRpIGy9DsM3)
[Answer]
# [Rockstar](https://codewithrockstar.com/), 55 bytes
First time posting a solution to one of my own challenges, if you'll forgive me the indulgence.
Outputs `1` for truthy or nothing for falsey.
```
listen to N
X's0
while N-X
let X be+1
if X*X is N
say 1
```
[Try it here](https://codewithrockstar.com/online) (Code will need to be pasted in)
[Answer]
# [V (vim)](https://github.com/DJMcMayhem/V), 34 bytes
```
C<C-r>=sqrt(<C-r>")
<esc>:s/.\+\.0\n
:s/.\+/1
```
[Try it online!](https://tio.run/##K/v/39nGWbfIzra4sKhEA8xU0uSySS1OtrMq1teL0Y7RM4jJ44Kw9Q25/v83NPivWwYA "V (vim) – Try It Online")
Returns empty string for a square, `1` for non-square.
## Explanation
```
C<C-r>=sqrt(<C-r>")
C cut the input line, enter insert mode
<C-r>= evaluate the following math command:
sqrt( ) square root of
<C-r>" cut input line in register "
<esc>:s/.\+\.0\n/
<esc> exit insert mode
:s/.\+\.0\n/ remove instance of <digits>.0
this removes a perfect square root.
:s/.\+/1 replace any other non-newline chars left with
a single 1.
```
[Answer]
# Knight, ~~32~~ ~~33~~ ~~32~~ 30 bytes
```
;=i+1=xP;W!>0=i-i 1|-^i 2xQ1Q0
```
[Try it online!](https://tio.run/##rVldU9tKEn22f8XgFLbGlhNJsFW3MDJFciFFLYEEks0D@AYhyzC1suyVZAgL7F/Pdvd8aGSb7Gb38mBZM6d7us/0dPeYuH8Txz9eiSxOF@NktyjHYvb6dti0R1JxXRuKy4d5sgTKRXZTGyrFVGLGyURkCUtTls6yG/pomtHPJ18@ML96Pf98xoLq9W/7Z2y7ej08ecd@q17PvjC/Ah8en1vYky/HFvTLyYf98786BWcOfrTZv/y/cDO7fw7Lysn4NspZl1cCNgpsNSqGQ7ZdzZ0cfMXJDCbJoyeG33d3lzC4DGHQTcCkKUdgDfP29PSYQPixR07uoG@WIWfvJQDkLVvvonSRcH6RjXizSX7ArlyMwrPWwemh82MQip4ffv84@Lox9ELRF8x/6v8hWPD9k//J@8EB1BpIuS4IJtGUhahh0GzCMvMoLxKHs8dmQ2QlE4NmA0ZpSZd1J4sshhESjuG9nM7dYp5dBKPw0XO9Z9DREKCO8PD0cODNG1Qv5uz@VpRJMY/ipNmA72niwDiIO9IMl7Uuy8vscnKZs8fni5HDd161OJnSEBPmGGtD1nnV4Uyq0KMbMHqZwXCvJ0fAzkaSFok98CzNiW@T@O9sMstZtpheJ3mh7GGOKMbiRpRaK6yO7viu8Ug@u8z3WI91leW9Hmd91vE6sARaKjjLk3KRZ0wHiRSjOBks23AX5SK6ThNtBRiRzu6T3IlhPW0Ie3pi2riY3mIi4luHK3rEGtdF6LuwR6EZXrIOj50KT4Bk48XcwS1litM@g7dVg2USKKQ2acZlp1PZ1OrITQNh8MAYxUAJJA34DpbNo6Jk5W0CyqK8BLDagK5mFDc05uiJNtY6Sy8aC58@p41uVGSQ@Ri6pZhlYDZGrDcC02LNSLGYz5FwrqNKj9j02/EHtFtkow4dyvMM4hgSGEauslyy8rljTrkcOMQBTGY7mMTQTB1klP@kqw7ajaZGaTqLnW3P9Tk6iMPGCXIwW6RplD/Yjlb7c2Ztz8eOsYwWVPKLbEmalvBxCZUU1nm6f/D23dWnjePfTy2HbbXXYq3eYFXvRk3x@6PzFzSWSU4qo2zM/rGI9CuqvbOX2FpdQhLwvmO4OFrDBQlv14XrmGdKlfkiwx0aqCTcLWeFo3MlHQAI7VLEjGavF5OLYHuk7JAb3ab0YAwo5nCsyokDUPB/M03HLZ13qAi5qGRZARwKo0CWN7l@DbfL/K26n@g8xuIea5X5ImlBDJpxDEkYn0SQQXCihZHVqkhAP9F3VYeIjm9vZ7MUZq7rDLzoa@XWzxzq/rpHtpnXK2amaGP2p9oIQVvO0tSxTXWZ50KF@B9MzlZMxir8Yf/jiYu1WAYavB5d@J7nQTiBK/Cq3wrxz@RbyfAxsGLU8hYZgDcXPwL63Ap9XdIxw2FVxwd9BvKxBYDDo@ODLptAchw0TGir9TANx9HcTZOMOgCLK90mSc7g3L1ExrIg1iYsbVhwHEG9BNTiXeJiAEVF4KTJG/F0vrQDRJIYVSkEaRIjXKa4F2V863SBmZWuCjhi6i/GOtXZ7@wwXEUCQiQU@zLIwrxNTin1qjOshSwfUBWuENR@ljmWLupAL0b8sQozaKAot8uFz2Dhuu4cMp7D2973Cf5VyI@ABK2So5ukTKF5dNq0l23cISyRY5HxgZg4Du0nNgTxbY62uBCnnMttDr3BWlvhwakNkOsdyPVk54jZQBEy0PYiSSp3Vla@rfyReDPzrppBSZtig7kCDEYDxF84n82TzLEWdlt5i1oFsCqcykoJ8RgG3vZvNK6aC0d2JBMwfYxOQQsHIetifwdw6B3oDdeApXV4OTDIeiG1QnhiAckV3aCH1iKqUUM3ZIHds1Q0Vp58Ak@S79DG4Wlf8XOjtut0R9jATLYCPF4JD1glrfNiwX/v7Kg@cU0gm8ynKlDrhNpiB2sQ10VoONzmVWO5kg616Dk1h85mgYL1w7AqDHRC62OvC5mUtyqonsDykkSZUvtSCVM1y94BlVsUC6cVC3gw5MUHSZP7WaOOtdt0ser3ETqSbe4ltdsNbdbm624B9jjwxpk@arll/qIs9O6bmJC9njSoZwyiPAn5ElMyhpa1PbKbbtR3W95SEQ19P9OxFMg9x/6XDoPcAELhMJ7yUHsZ8PWhGkelfqiu0@9VNHH9HXVx6EZdepYqRyi/@ivRaUU7tup1e6VQt9qdNSwsl@c1PHRXeJD7uo6F6RrXuoQJbSUkADXIoQwZdi7hkoegQb9P@hRRVDKXN1oyWtZO/5ufEvNmPTGbPxXaXC/0B7FZc0heHWgssL0cKNol6yHr@4ZlwgL1Ppyzvg9nzLfBwS@idyE91rBhiFBad0ePeJpyIjoYeorrgFO70g2J/@bygaBJcgXuCJRgscTAd7wy3CZ50ilYNoMeWqSlyNh99AC8sfEM7qRlcpPkIDOfZUlWighvEXCSZ@w@YbfRXQJApQjhJZtG2QLC5@E1jqJ318g4UEFMFIu0xB8NaHGT8DSkb2P0kkuU2XIGsqQe9b2M9F42xMB2ayiP7udRirXxAbzOxmkyZleV2VdGyyN@k42ZtUjlzBCV9fv6nRO8oaBdy/Rnkwd3KViXCh8mvVpeDOtZcY/Zh3/XPgYouqN@f2szCdhjtUaRBl1mZUPU4UlJXXIDWQcQuxFCtbG6oCEcSgyt2Xi2w6bJNJ5jmGVseLX3/7oy/BNcGWpXNtb4EipflCt7L7MvV11jMk7vsRogMIhAF9CNdXZWL8Y9nXlsBca8dpX@0Jd1tWHPllSpxMg//TfyKgdZaoz8oLNjo2tt7jI2rLJuffqXLzK6t61uMohr1G4zJhUSBjWOwpq0lSZRAhG9nhGTJn8F9@SvXnajWfOO2b2LEjuqd@0IteT3gp0ti5b38soQWh1Wzy5Aq3ekTF08XHMWtmoN7bkkeknpYLnkBetK3hY3fUBgpLdp8D80RGgYPnErYtP8m3bI7o0C8BBX7fnYJFGDIONfTtKDED11EmD1cTKJIEmCZ7rDFBlMijH9iBTFJZSpzmbcwZ4TRzh74RaLykwNhG5Q/ZAwjUSGzSqL8pvYJaXdLny/4/hzFd0v8d85jkfW1K9xzz/8fwM "C (gcc) – Try It Online")
Takes input from standard in, outputs by error code (1 if input is square, 0 otherwise).
Expanded code:
```
;=i +1 (=x PROMPT)
;WHILE !> 0(=i -i 1)
| (-(^i 2) x)
QUIT 1
QUIT 0
```
---
+1 bytes from @Jonah because I somehow didn't notice this failed on input `1`
-2 bytes from @Jonah by using short circuit evaluation of `|` instead of `IF`
[Answer]
# Pyth, 5 bytes
```
/^R2h
```
[Try it here!](http://pyth.herokuapp.com/?code=%2F%5ER2h&test_suite=1&test_suite_input=0%0A1%0A64%0A88&debug=0)
[Answer]
# [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), ~~16~~ 18 bytes
```
[:|~b/a=a|_Xq}?b=0
```
*Added two bytes for 0-case*
This runs through `i = 1 ... n` to see if `n / i == i`. Prints `1` if such an `i` is found, prints `-1` for `N=0` and `0` in all other cases. Both `1` and `-1` are considered truthy in QBasic (`-1` being the actual value for true, but `IF (n)` only is false on `n=0`).
[Answer]
# J, 8 bytes
```
(=~<.)%:
```
Explanation:
* `%:` square root
* `=~` is the argument equal to itself
* `<.` floor of
* `=~<.` a J hook, which modifies the right argument by applying `<.`
* so, "is the floor of the square root equal to itself?"
Note: If we want to save the above to a variable as a verb, we must do, eg:
```
issq=.(=~<.)@%:
```
[Answer]
# C, 33 bytes
```
#define f(x)sqrt(x)==(int)sqrt(x)
```
Takes an integer `x`. Checks if the square root of `x` is the square root of `x` rounded to an integer.
[Try it online!](https://tio.run/##S9ZNT07@r5yZl5xTmpKqYJObWJKhl2H3XzklNS0zL1UhTaNCs7iwqARI2dpqZOaVwHj/cxMz8zQ0qwuKgIJpGkqqKUo6aRpmJpqa1rX/AQ)
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 8 bytes
```
issquare
```
[Try it online!](https://tio.run/##K0gsytRNL/ifpmCr8D@zuLiwNLEo9X9afpFGHlDEUEfB0MBAR6GgKDOvRCNPR0FJQddOQUlHIU0jT1NT8z8A "Pari/GP – Try It Online")
[Answer]
## Pyke, 3 bytes
```
,$P
```
[Try it here!](http://pyke.catbus.co.uk/?code=%2C%24P&input=3)
```
, - sqrt(input)
$ - float(^)
P - is_int(^)
```
This could be two bytes (and is in older versions) if Pyke didn't helpfully automatically cast the results of sqrt to an integer if it's a square number.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 8 bytes
```
¬﹪XN·⁵¦¹
```
[Try it online!](https://tio.run/##S85ILErOT8z5///Qmvc7V73fs@P9nnWHtj9q3Hpo2aGd//@b/NfN/G/43/K/oel/I4P/uvn/dcHwPwA "Charcoal – Try It Online")
### Explanation
```
¬ Not
﹪ ¦¹ Modulo 1
X ·⁵ To the power of .5
N Next input as number,
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~5~~ 3 bytes
```
t.ï
```
[Try it online!](https://tio.run/##MzBNTDJM/f@/xOXw@kcNuw53/P9vyQUA "05AB1E – Try It Online")
~~Longer than @Erik's but just wanted to give it a shot.~~
Now shorter than Erik's but fails for large numbers...
# Explanation
```
t # square roots the input
.ï # checks if number on stack is an int
# implicit output of result (0 or 1)
```
[Answer]
# **Python 3,** ~~39~~ 38 Bytes
```
lambda n:n in(i*i for i in range(n+1))
```
@mathmandan I had the same idea, and this implementation is 1 byte shorter. I wanted to comment on your post but do not yet have 50 reputation. I hope you see this!
This is just brute force, and I did not get it to complete `2147483647` in a
reasonable amount of time.
Thanks @DJMcMayhem for suggesting i remove the space after `in`
[Try it Online](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPKk8hM08jUytTIS2/SCETyFEoSsxLT9XI0zbU1PxfUJSZV6KRpgFkc8HYRkhsYyS2JbIaFA2mSBwzEySOhQXQDgA)
[Answer]
# Excel, ~~18~~ 16 bytes
```
=MOD(A1^0.5,1)=0
```
[Answer]
# Common Lisp, 30 bytes
```
(defun g(x)(=(mod(sqrt x)1)0))
```
[Try it online!](https://tio.run/##S87JLC74/18jJTWtNE8hXaNCU8NWIzc/RaO4sKhEoULTUNNAU/O/RkFRZl6Jgka6gpkJkAsA)
or, with the same length,
```
(defun g(x)(integerp(sqrt x)))
```
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 22+3 = 25 bytes
```
01-\:*=n;
(?!\1+::*{:}
```
[Try it online!](https://tio.run/##S8sszvj/38BQN8ZKyzbPmkvDXjHGUNvKSqvaqvb///@6ZQqGZgA "><> – Try It Online")
Input is expected on the stack at program start, so +3 bytes for the `-v` flag.
[Answer]
# Ruby, 16 bytes
```
->n{n**0.5%1==0}
```
Trivial solution.
[Answer]
# [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), 67 bytes
```
(load library
(d S(q((n)(contains?(map(q((x)(* x x)))(c 0(1to n)))n
```
[Try it online!](https://tio.run/##FYo5DoAgEEV7T/HLP1ZYWHsITzAuMSQ4KFLA6VHLt2RvNfjnao0h6obgl6Spdtww8yZNuEbL6u2ZeOr1uyLsUVBEvgjHIUfYB9b@AzOY1I4dDqMTaS8 "tinylisp – Try It Online")
Generates a list of numbers from 0 through `n`, maps a lambda function that squares each one, and checks if `n` is in the resulting list of squares. Wildly inefficient, of course.
---
Here's a 77-byte solution that doesn't use the library and runs an order of magnitude faster:
```
(d _(q((x n s)(i(e n s)1(i(l n s)0(_(a x 1)n(a s(a x(a x 1
(d S(q((n)(_ 0 n 0
```
[Try it online!](https://tio.run/##JYuxDYQwEARzqthwLzMBlbgA6xAIWfLfg/0BVO8/INpZaeaX7Sq57b1zQeJBnjA0Yeb6wOhUHgpMVJwYxXzbze8fPI13asKE4HLoLF9dUPJctV4y8KM7IljVttWVKYj0Pw "tinylisp – Try It Online")
This one uses a helper function `_` which tracks a counter `x` and its square `s`. At each level of recursion, we return success if `s` equals `n` and failure if `s` is greater than `n`; otherwise, if `s` is still less than `n`, we recurse, incrementing `x` and calculating the next `s` by the formula `(x+1)^2 = x^2 + x + x + 1`.
[Answer]
# [Julia 0.6](http://julialang.org/), 12 bytes
```
n->√n%1==0
```
[Try it online!](https://tio.run/##yyrNyUw0@19s@z9P1@5Rx6w8VUNbW4P/BUWZeSU5eRrFehqGVkYGmpr/AQ "Julia 0.6 – Try It Online")
Pretty straightforward, having the Unicode `√` for square-root saves a few bytes.
] |
[Question]
[
## Challenge
A [repdigit](https://oeis.org/wiki/Repdigit_numbers) is a non-negative integer whose digits are all equal.
Create a function or complete program that takes a single integer as input and outputs a truthy value if the input number is a repdigit in base 10 and falsy value otherwise.
The input is guaranteed to be a *positive* integer.
You may take and use input as a string representation in base 10 with impunity.
## Test cases
These are all repdigits below 1000.
```
1
2
3
4
5
6
7
8
9
11
22
33
44
55
66
77
88
99
111
222
333
444
555
666
777
888
999
```
A larger list can be found [on OEIS](https://oeis.org/A010785).
## Winning
The shortest code in bytes wins. That is not to say that clever answers in verbose languages will not be welcome.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 1 byte
```
=
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/3/b/f0NDQwA "Brachylog – Try It Online")
This acts on integers.
From [`src/predicates.pl#L1151`](https://github.com/JCumin/Brachylog/blob/master/src/predicates.pl#L1151):
```
brachylog_equal('integer':0, 'integer':0, 'integer':0).
brachylog_equal('integer':0, 'integer':I, 'integer':I) :-
H #\= 0,
integer_value('integer':_:[H|T], I),
brachylog_equal('integer':0, [H|T], [H|T]).
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~33~~ ~~30~~ 29 bytes
```
f(n){n=n%100%11?9/n:f(n/10);}
```
[Try it online!](https://tio.run/##S9ZNT07@/z9NI0@zOs82T9XQwEDV0NDeUj/PCiimb2igaV37PzcxM09Dk6uaizMtv0gjM69EIU/BVsHQGkjZKAB1GABZ2tqaXJycIHMU1NQUCoqAqtI0lFRLY/KUdBTyNK25av8DAA "C (gcc) – Try It Online")
[Answer]
# [COBOL](https://en.wikipedia.org/wiki/COBOL), 139 BYTES
I feel like COBOL doesn't get any love in code golfing (probably because there is no way it could win) but here goes:
```
IF A = ALL '1' OR ALL '2' OR ALL '3' OR ALL '4' OR ALL '5' OR
ALL '6' OR ALL '7' OR ALL '8' OR ALL '9' DISPLAY "TRUE" ELSE
DISPLAY "FALSE".
```
A is defined as a PIC 9(4).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 1 byte
```
Ë
```
Checks if all digits are equal
[Try it online!](https://tio.run/##MzBNTDJM/f//cPf//yYmJgA "05AB1E – Try It Online")
[Answer]
# Python 3, 25, 24 19 bytes.
```
len({*input()})>1>t
```
A stdin => error code variant.
Returns error code 0 if it's a repdigit - or an error on failure.
Thanks to Dennis for helping me in the comments.
[Answer]
# [Haskell](https://www.haskell.org/), 15 bytes
```
all=<<(==).head
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P802MSfH1sZGw9ZWUy8jNTHlf25iZp6CrUJBUWZeiYKKQm5igUKaQrSSoZKOgpIhmDQ2NgZzjCBiRmAxICf2PwA "Haskell – Try It Online") Takes string input.
Equivalent to `\s->all(==head s)s`. Narrowly beats out alternatives:
```
f s=all(==s!!0)s
f s=s==(s!!0<$s)
f(h:t)=all(==h)t
f(h:t)=(h<$t)==t
f s=(s<*s)==(s*>s)
f(h:t)=h:t==t++[h]
```
[Answer]
## Mathematica, 27 bytes
```
AtomQ@Log10[9#/#~Mod~10+1]&
```
It doesn't beat `Equal@@IntegerDigits@#&`, but it beats the other arithmetic-based Mathematica solution.
Repdigits are of the form **n = d (10m-1) / 9** where **m** is the number of digits and **d** is the repeated digit. We can recover **d** from **n** by taking it modulo 10 (because if it's a rep digit, it's last digit will be **d**). So we can just rearrange this as **m = log10(9 n / (n % 10) + 1)** and check whether **m** is an integer.
[Answer]
# [Slashalash](https://esolangs.org/wiki/Slashalash), 110 bytes
```
/11/1//22/2//33/3//44/4//55/5//66/6//77/7//88/8//99/9//1/.//2/.//3/.//4/.//5/.//6/.//7/.//8/.//9/.//T..///.//T
```
[Try it online!](https://tio.run/##HcuxDYAwDAXRjTglThxnDxagQKKgy/4y@TRP19x6r/XcK5NSKFArFcwwaI0GvdPBHYcxGBBBwJxM9nLsSZhoogsXQ4SY4jw2f2R@ "/// – Try It Online")
The /// language doesn't have any concept of truthy and falsey, so this outputs "T" if the input is a repdigit, and does not output any characters if the input is not a repdigit.
[Answer]
## C (gcc), 41 bytes
```
f(char*s){s=!s[strspn(s,s+strlen(s)-1)];}
```
This is a function that takes input as a string and returns `1` if it is a repdigit and `0` otherwise.
It does this by making use of the `strspn` function, which takes two strings and returns the length of the longest prefix of the first string consisting of only characters from the second string. Here, the first string is the input, and the second string is the last digit of the input, obtained by passing a pointer to the last character of the input string.
Iff the input is a repdigit, then the result of the call to `strspn` will be `strlen(s)`. Then, indexing into `s` will return a null byte if this is the case (`str[strlen(str)]` is always `\0`) or the first digit that doesn't match the last digit otherwise. Negating this with `!` results in whether `s` represents a repdigit.
[Try it online!](https://tio.run/##TYzBDoIwEETvfMVKYrILJSkHT8iXqIdarTaBQrp4Inx7XQgmzmUmmTdjq5e1KTm0bxMLppnbA194ijwGZMWlxO4pkaqabs2SeuMDEswZiNYRFPePgxZ603WDxRM1W@WGCOjDBF463YidodZaUln6334Vj1Ewh/KiID8@cgV@/1jlHeBWEsFOCnQNf9gC2ZK@ "C (gcc) – Try It Online")
Thanks to @Dennis for indirectly reminding me of the assign-instead-of-return trick via his [insanely impressive answer](https://codegolf.stackexchange.com/a/125150/3808), saving 4 bytes!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~2~~ 1 byte
```
E
```
[Try it online!](https://tio.run/##AVsApP9qZWxsef//Rf/It@G5vuKCrCDDh8OQZiBZIOG4t@KAnCBHZW5lcmF0ZSBbIjEiLCAuLi4sICIxMDAwIl0sIGZpbHRlciBieSB0aGUgY29kZSwgZGlzcGxheS7/ "Jelly – Try It Online")
[Answer]
## PHP, ~~25~~ ~~28~~ 25
```
<?=!chop($argn,$argn[0]);
```
remove all chars from the right that are equal to the first and print `1` if all chars were removed.
[Answer]
## R, 31 bytes
```
function(x)grepl("^(.)\\1*$",x)
```
This functions works with string inputs and uses a regular expression to determine whether the input is a repdigit.
### Example
```
> f <- function(x)grepl("^(.)\\1*$",x)
> x <- c("1", "2", "11", "12", "100", "121", "333")
> f(x)
[1] TRUE TRUE TRUE FALSE FALSE FALSE TRUE
```
[Answer]
## Regex (ECMAScript), 31 bytes
```
^(x{0,9})((x+)\3{8}(?=\3$)\1)*$
```
[Try it online!](https://tio.run/##Tc3NTsJAFEDhV8GGhHspHVowRqkDKxdsWOhSNJmUy/TqMNPMjFD5efaKCxO351ucD7VXofLcxCw0vCG/c/aTvjsvLR16z6Sf2gbgKOfjYfcO7SkfPVwQoE1xPT3dX2Ah19M@rgsc9rvh@Igiupfo2WpAEQxXBHej7BaxPNRsCMBIT2pj2BIg3kj7ZQyetDQiNIYjDLIBlrwFsFILQ1bHGueT85nDSq2AZaN8oKWNoF/zN8Q/oP9g58WimP0yxtq7Q7K0e2V40/PKapr1ktSUW@eh5EdJJacpXodJmwhPDakIjGKnYlWDR6ycDc6QME5fe3np8mwyzfMf)
Takes input in unary, as usual for math regexes (note that the problem is trivial with decimal input: just `^(.)\1*$`).
Explanation:
```
^(x{0,9}) # \1 = candidate digit, N -= \1
( # Loop the following:
(x+)\3{8}(?=\3$) # N /= 10 (fails and backtracks if N isn’t a multiple of 10)
\1 # N -= \1
)* $ # End loop, assert N = 0
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 11 bytes
```
@(s)s==s(1)
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo1iz2Na2WMNQ83@ahrqhuiYXkDIBAgjLFCpiaGQMROqa/wE "Octave – Try It Online")
Takes the input as a string.
It checks all characters for equality with the first characters. If all are equal, the result will be a vector with only `1` (true in Octave), otherwise there will be at least one `0` (false in Octave).
Here's a [proof](https://tio.run/##y08uSSxL/f8/M00h2lABCGN1UjKLCzTUoTyFzGKFkqLSkoxKdU2d1JziVAW4tAFUOi0xpxgsm5fCBTHGAMUYA5KN@f8fAA).
[Answer]
# grep, 17 bytes
```
grep -xP '(.)\1*'
```
Matches any string that's a repetition of its first character.
[Answer]
# APL, 5 bytes
*2 bytes saved thanks to @KritixiLithos*
```
⍕≡1⌽⍕
```
[Try it online!](http://tryapl.org/?a=f%25u2190%25u2355%25u22611%25u233D%25u2355%20%25u22C4%20f%20445%20%25u22C4%20f%20444%20%25u22C4%20f%20%27445%27%20%25u22C4%20f%20%27444%27&run)
[Answer]
# C#, 42 33 28 bytes
```
i=>i.Replace(i[0]+"","")==""
```
`i` has to be a string.
Shaved down a lot thanks to @LethalCoder
[Answer]
# [Braingolf](https://github.com/gunnerwolf/braingolf), 6 bytes
```
iul1-n
```
[Try it online!](https://tio.run/##SypKzMxLz89J@/8/szTHUDfv/38TExNTAA "Braingolf – Try It Online")
Unfortunately, Braingolf's implicit input from commandline args can't accept an all-digits input as a string, it will always cast it to a number, so instead the solution is to pass it via STDIN, which adds 1 byte for reading STDIN (`i`)
## Explanation:
```
iul1-n
i Read from STDIN as string, push each codepoint to stack
u Remove duplicates from stack
l Push length of stack
1- Subtract 1
n Boolean negate, replace each item on stack with 1 if it is a python falsey value
replace each item on stack with 0 if it is a python truthy value
Implicit output of last item on stack
```
After `u`, the length of the stack equals the number of unique characters in the input, subtracting 1 means it will be `0` if and only if there is exactly 1 unique character in the input, `0` is the only falsey number in Python, so `n` will replace `0` with `1`, and everything else with `0`.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 4 bytes
```
¥çUg
```
[Try it online!](https://tio.run/##y0osKPn//9DSw8tD0///VzIxMVH6DwA "Japt – Try It Online")
[Answer]
## JavaScript (ES6), ~~23~~ 21 bytes
*Saved 2 bytes thanks to Neil*
Takes input as either an integer or a string. Returns a boolean.
```
n=>/^(.)\1*$/.test(n)
```
### Demo
```
let f =
n=>/^(.)\1*$/.test(n)
console.log(f(444))
console.log(f(12))
```
[Answer]
# [Ohm](https://github.com/MiningPotatoes/Ohm), 4 bytes
```
Ul2<
```
[Try it online!](https://tio.run/##y8/I/f8/NMfI5v9/ExNjAA "Ohm – Try It Online")
### Explanation
```
Ul2<
U # Push uniquified input
l # Length
2< # Is it smaller than 2?
```
[Answer]
# Java, ~~38~~ ~~33~~ 23 bytes
```
n->n.matches("(.)\\1*")
```
`n` is a `String`, naturally.
Note that there is no need for `^...$` in the regex since it's automatically used for exact matching (such as the `match` method), compared to finding in the string.
[Try it!](http://ideone.com/KxyRJ9)
## Saves
* -5 bytes: used `String` since "You may take and use input as a string with impunity."
* -10 bytes: regex is apparently a good fit.
[Answer]
# Java, 21 bytes:
```
l->l.toSet().size()<2
```
`l` is a `MutableList<Character>` from eclipse collections.
[Answer]
# [Kotlin](https://kotlinlang.org), ~~28~~ 19 bytes
```
{it.toSet().size<2}
```
[Try it online!](https://tio.run/##JYyxDoIwFEV3vuKGqW@QWMcGMDi78QVNbEljeTWlmCjh22vVs95zzz0k7zg/tYdVEGOKjifCocclBG80o8ubS00Ko0mCmsW9TXvas10Zs3YsdJwWhSFG/Wr/756wVSh8o7zO6BCNvl0dG0E4K9TH@rc/ip2EFcUhqvYspfwA "Kotlin – Try It Online")
Takes input as a `String` because
>
> You may take and use input as a string representation in base 10 with impunity.
>
>
>
## Explanation
```
{
it.toSet() // create a Set (collection with only unique entries)
// out of the characters of this string
.size < 2 // not a repdigit if the set only has one entry
}
```
If you don't like the fact it takes a `String`, you can have one that takes an `Int` for **24 bytes**.
```
{(""+it).toSet().size<2}
```
[Answer]
# PHP, 30 bytes
```
<?=($a=$argn).$a[0]==$a[0].$a;
```
[Answer]
# [Neim](https://github.com/okx-code/Neim), 1 byte
```
ùêê
```
Simply checks that all elements are equal.
Without builtin, 2 bytes:
```
ùêÆùê•
```
Explanation:
```
ùêÆ Calculate unique digits
ùê• Get the length
```
This works because only `1` is considered truthy in Neim, and everything else is falsy.
Alternatively, for 4 bytes:
```
ùêÆù꣌ºùïÉ
```
Explanation:
```
ùêÆ Calculate unique digits
ùê£ Join list into an integer
ùïÉ Check that is is less than
μ Ten.
```
[Try it!](http://178.62.56.56:80/neim?code=%F0%9D%90%90&input=12)
[Answer]
# C, 38 bytes
```
f(char*s){return*s^s[1]?!s[1]:f(s+1);}
```
Recursively walks a string. If the first two characters differ (`*s^s[1]`) then we succeed only if we're at the end of the string (`!s[1]`) otherwise we repeat the test at the next position (`f(s+1)`).
## Test program
```
#include <stdio.h>
int main(int argc, char **argv)
{
while (*++argv)
printf("%s: %s\n", *argv, f(*argv)?"yes":"no");
}
```
[Answer]
# R, 25 bytes
```
grepl("^(.)\\1*$",scan())
```
[Try it online](https://tio.run/##K/r/P70otSBHQylOQ08zJsZQS0VJpzg5MU9DU/O/paUllwmXhSGXpYW5mfF/AA)
Best non-regex solution I could come up with was 36 bytes:
```
is.na(unique(el(strsplit(x,"")))[2])
```
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix), 15 bytes
```
uOn@ii?-?;.$@<_
```
[Try it online!](https://tio.run/##Sy5Nyqz4/7/UP88hM9Ne195aT8XBJv7/f1MQAAA "Cubix – Try It Online")
```
u O
n @
i i ? - ? ; . $
@ < _ . . . . .
. .
. .
```
[Watch It Run](https://ethproductions.github.io/cubix/?code=ICAgIHUgTwogICAgbiBACmkgaSA/IC0gPyA7IC4gJApAIDwgXyAuIC4gLiAuIC4KICAgIC4gLgogICAgLiAuCg==&input=MjIzMjI=&speed=20)
Outputs 1 for truthy and nothing for falsey
Very simply read reads in the input one character at a time. It takes the current character away from the previous. If a non zero result then it halts immediately. Otherwise it continues inputting and comparing until the EOI. On EOI (-1), negate and exit
[Answer]
# QBasic 4.5, 55 bytes
```
INPUT a
FOR x=1TO LEN(STR$(a))
c=c*10+1
NEXT
?a MOD c=0
```
I've mathed it! The FOR-loop checks the number of digits in the input, then creates `c`, which is a series of 1's of length equal to the input. A number then is repdigit if it modulo the one-string == 0.
[Try it online!](https://repl.it/IcSt/0) Note that the online interpreter is a bit quirky and I had to write out a couple of statements that the DOS-based QBasic IDE would expand automatically.
] |
[Question]
[
In this challenge, you should write a program or function which takes no input and prints or returns a string with the same number of bytes as the program itself. There are a few rules:
* You may only output bytes in the printable ASCII range (0x20 to 0x7E, inclusive), or newlines (0x0A or 0x0D).
* Your code must not be a quine, so the code and the output must differ in at least one byte.
* Your code must be at least one byte long.
* If your output contains trailing newlines, those are part of the byte count.
* If your code requires non-standard command-line flags, count them as usual (i.e. by adding the difference to a standard invocation of your language's implementation to the byte count), and the output's length must match your solution's score. E.g. if your program is `ab` and requires the non-standard flag `-n` (we'll assume it can't be combined with standard flags, so it's 3 bytes), you should output 5 bytes in total.
* The output doesn't always have to be the same, as long as you can show that every possible output satisfies the above requirements.
* Usual quine rules *don't* apply. You may read the source code or its size, but I doubt this will be shorter than hardcoding it in most languages.
You may write a [program or a function](https://codegolf.meta.stackexchange.com/q/2419) and use any of the [standard methods](https://codegolf.meta.stackexchange.com/q/2447) of providing output. Note that if you print the result, you may choose to print it either to the standard output or the standard error stream, but only one of them counts.
You may use any [programming language](https://codegolf.meta.stackexchange.com/q/2028), but note that [these loopholes](https://codegolf.meta.stackexchange.com/q/1061/) are forbidden by default.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid answer – measured in *bytes* – wins.
### Leaderboard
```
var QUESTION_ID=121056,OVERRIDE_USER=8478;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){var F=function(a){return a.lang.replace(/<\/?a.*?>/g,"").toLowerCase()},el=F(e),sl=F(s);return el>sl?1:el<sl?-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]
# [><>](https://esolangs.org/wiki/Fish), 3 bytes
```
"nh
```
[Try It Online](https://tio.run/##S8sszvj/XykPSAAA)
Prints "104" and exits with an error.
[Answer]
# [Dash](https://wiki.debian.org/Shell)/[Bash](https://www.gnu.org/software/bash/)/[ksh](http://www.kornshell.com/)/[fish](https://fishshell.com/), 5 bytes
```
umask
```
[Try it online (Dash)](https://tio.run/##HcpBCoAgEEbhvaf4V1kLNy0jukJnkGlEiFR0JILubtju8fEOW3wbW71sOduEF8IMp@RJjB@xDbNi8rEHTIDeq6QqIG@zJeEMijXIAq1ugiGscP1tHw "Dash – Try It Online") |
[Try it online (Bash)](https://tio.run/##HcpBCoAgEEbhvaf4V1kLNy0jukJnsGFEiFR0JILubtju8fEOW3wbW71sOduEF8IMp@RJjB@xDbNi8rEHTIDeq6QqIG@zJeEMijXIAq1ugiGscP1tHw "Bash – Try It Online") |
[Try it online (Ksh)](https://tio.run/##HcpBCoAgEEbhvaf4V1kLNy0jukJnkGFEkFR0JILubtju8fFC9X3u7bI19AUvhBlOyZMZP@KYVsXk0wiYCH02yU1A3hZLwgWUWpQNWt0EQ9jhxts/ "ksh – Try It Online") |
[Try it online (Fish)](https://tio.run/##Hco7CoAwEEXRPqt4lVYptBRxC64hjBNG/GImiKhrj5/ucri@D2KD8DimM8XJhSHduKDM8EaPlfHjS8Kug50LNFlpmGT54gXkbdQ1Kkjc5kh5Ay1x1gq52QmWUMN/b3oA "fish – Try It Online")
`umask` is a **builtin** in most unix shells, *not* an external command! It prints the 4-octal-digit umask followed by a newline for a total of 5 bytes.
Does not work in Zsh or Tcsh: Zsh will only print one leading zero (e.g.: `02` instead of `0002`), and Tcsh will print no leading zeroes (`2` instead of `0002`)
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 14 bytes
```
_=>new[]{1}+""
```
Found interesting way to shave some bytes. Outputs: `System.Int32[]`
[Try it online!](https://tio.run/##Sy7WTS7O/O9Wmpdsk5lXoqNQXFKUmZdup5AGFFGw/R9va5eXWh4dW21Yq62k9N@aiyu8KLMk1SczL1UDpETDQFPPJzUvvSRD0xpJSglZX4xSjJISXNV/AA "C# (Visual C# Interactive Compiler) – Try It Online")
First way:
23 bytes
```
()=>new string('@',23);
```
Creates a new string consisting of 23 `@` characters
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), ~~19~~ 16 bytes
```
END{print 69**8}
```
[Try it online!](https://tio.run/##SyzP/v/f1c@luqAoM69EwcxSS8ui9v9/AA "AWK – Try It Online")
*Thanks to Jo King for the pointer that cut 3 chars...*
AWK is a bit of a pain for this one since the minimum code required to run without any input and print something is `END{print }`. So this one just prints a number that's enough digits to match the program size less one, since the `print` adds a linefeed. The output is `513798374428641\n`.
[Answer]
# [Python 3](https://www.python.org/), ~~13~~ 12 bytes
```
print(2**-9)
```
[Try it here!](https://tio.run/##K6gsycjPM/7/v6AoM69Ew0hLS9dS8/9/AA)
**Output:**
```
0.001953125
```
---
**Old:**
```
print([1]*4);
```
[Try it here!](https://tio.run/##K6gsycjPM/7/v6AoM69EI9owVstE0/r/fwA)
**Output:**
```
[1, 1, 1, 1]
```
-1 Thanks to aeh5040! With this, the unneeded semi-colon could be removed as the output is 11 bytes + white space
~~A list printed in python would have the length of 2 + 3 for each extra element plus the new-line, thus with [1](https://www.python.org/)\*n we can have any multiple of 2+3n. A semi-colon is added because unfortunately print adds a new-line character, and I've yet to find a better solution~~
[Answer]
# [Desmos](https://desmos.com/calculator), 2 bytes
```
4!
```
Outputs
```
24
```
[Answer]
## Powershell, 3 bytes
```
1E2
```
Prints `100`
[Answer]
# PHP, ~~216~~ ~~68~~ 7 bytes
```
<?=1e6;
```
[Try it online!](https://tio.run/nexus/php#@29jb2uYamb9/z8A "PHP – TIO Nexus")
Thanks to [Jörg](https://codegolf.stackexchange.com/users/59107/j%C3%B6rg-h%C3%BClsermann) I'm beating [Okx](https://codegolf.stackexchange.com/users/26600/okx) again :D
[Answer]
# [TAESGL](https://github.com/tomdevs/taesgl), 1 byte
```
S
```
[**Interpreter**](https://tomdevs.github.io/TAESGL/v/1.2.1/index.html?code=Uw==)
Outputs a single space character
**Other solutions**
```
"≠ 2 bytes, "≠" converted to "!="
«Ā» 3 bytes, decompresses "Ā" which is equal to "the"
SŔ4) 4 bytes, " " repeated 4 times
5ē)ĴT 5 bytes, first 5 Fibonacci numbers joined
G→6,"A 6 bytes, draws a line to the right of "A" for 6 characters
```
[Answer]
## [Stack Cats](https://github.com/m-ender/stackcats), 1 + 3 = 4 bytes
```
+
```
[Try it online!](https://tio.run/nexus/stackcats#@6/9//9/3XwA "Stack Cats – TIO Nexus")
Requires either the `-o` or `-n` flag for numeric output. Prints two zeros, with a linefeed each.
### Explanation
Stack Cats has a tape of stacks which are all initialised to an infinite wells of zeros, but the starting stack has a `-1` on top (which acts as a terminator when input is given). The `+` command swaps the first and third element on the current stack. So:
```
-1 0
0 0
0 + -1
0 ----> 0
. .
. .
. .
```
At the end of the program, the current stack is printed from top to bottom. Since the `-1` is again treated as a terminator, it's not printed itself. Due to the `-o` flag, the values are printed as decimal integers with trailing linefeeds.
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 7 bytes
```
[['']]'
```
[Try it online!](https://tio.run/nexus/octave#@x8dra4eG6v@/z8A "Octave – TIO Nexus")
[Answer]
# TI-Basic (TI-84 Plus CE OS 5.2+), 4 bytes
```
toString(10^(3
```
`tostring(` is a two-byte token, `10^(` is a one-byte token. This returns the string "1000" which is 4 bytes long.
[Answer]
## [Fission](https://github.com/C0deH4cker/Fission), 4 bytes
```
R"N;
```
[Try it online!](https://tio.run/nexus/fission2#@x@k5Gf9/z8A "Fission 2 – TIO Nexus")
Prints `N;R` with a trailing linefeed.
The `R` creates a right-going atom. `"` toggles string mode which traverses an immediately prints `N;R` (wrapping at the end of the line). Then `N` prints a linefeed and `;` destroys the atom, terminating the program.
[Answer]
# [Somme](https://github.com/ConorOBrien-Foxx/Somme), 2 bytes
```
:.
```
[Try it online!](https://tio.run/nexus/somme#@2@l9/8/AA "Somme – TIO Nexus")
Outputs `42`. Explanation:
```
:.
: duplicate; no input, so popping from an empty stack pushes `42`
. output as a number
```
[Answer]
# [OCaml](https://ocaml.org/), 22 bytes
```
List.find ((=) "") []
```
Outputs
```
Exception: Not_found.
```
It search for `""` (empty string) in the empty list `[]`
[Answer]
# Ruby, 3 bytes
```
p""
```
Prints this, plus a newline
```
""
```
Here's another 3 byte one:
```
p:a
```
Prints this, plus a newline
```
:a
```
[Answer]
# R, 7 bytes
`stop( )`
Prints `Error:` (with a trailing space)
---
16 bytes (only works in version 3.3.1)
`version$nickname`
Prints `Bug in Your Hair`.
Not nearly as good but I like it anyway.
[Answer]
# charcoal, 1
```
⎚
```
[Try it online!](https://tio.run/nexus/charcoal#@/@ob9b//wA "Charcoal – TIO Nexus")
## Explanation:
```
⎚ Clears the empty screen
[implicitly print nothing plus a trailing newline]
```
[Answer]
## Mathematica, 2 bytes
Code:
```
.0
```
Output:
```
0.
```
This is the output of Wolfram kernel from command line, and the plaintext output from the front end. If you must argue about the extra number tick added when copying directly from the front end, then `0.0` will do.
[Answer]
## [><>](https://esolangs.org/wiki/Fish), 11 bytes
```
01+:b=?;:n!
```
Prints numbers from 1-10 (12345678910)
[Answer]
# [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 36 bytes
```
```
[Try it online!](https://tio.run/nexus/whitespace#FYmxDQAADIJmvYL/n7RUDQMOQkwLtXEo@3zjtR0 "Whitespace – TIO Nexus")
Generates the output "-15-14-13-12-11-10-9-8-7-6-5-4-3-2-1" (36 characters without quotes, no trailing newline)
# Explanation
Pushes the number -15 onto the stack (encoded in binary as 01111, with a leading 0 for padding to match the output) then counts toward 0 outputting the current number each iteration.
Starting from a negative number gives an extra byte of output per iteration and also allows me to use a jump while negative instruction to fall through the loop and exit implicitly. That single padding byte in the code is a downer though but solutions without it are longer.
[Answer]
## **Python 3, 13 bytes**
```
print("a"*13)
```
Outputs "aaaaaaaaaaaaa"
[Answer]
# [C#](https://visualstudio.microsoft.com/), 84 bytes
```
public class P{public static void Main(){System.Console.Write(new string('_',84));}}
```
[Try Online](https://dotnetfiddle.net/jgigU2)
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 6 bytes
```
(arch)
```
[Try it online!](https://tio.run/##S0oszvj/XyOxKDlD8/9/AA "Bash – Try It Online")
The architecture needs to be `x86_64`
[Answer]
# [Klein](https://github.com/Wheatwizard/Klein) 110, ~~7~~ 5 bytes
*Thanks to Martin Ender for saving two bytes!*
```
1.
2@
```
[Try it online!](https://tio.run/##y85Jzcz7/99Qj8vI4T@QNjQAAA "Klein – Try It Online")
If we unfold the topology here we get
```
1.122@
```
This outputs `1 1 2 2` with a trailing newline.
[Answer]
# Lean Mean Bean Machine, 28 bytes
```
/O
)O4
?7/
*
_~
o
~ :
u
```
[Try it Online!](https://tio.run/##xVltb9s2EP6uX8G9ZJIS2YnRAQO8esWwJRiwDSm6bF9UzVMsOmYriwIlOxYw9K9ndyT1QklMXTTIWqAVyePdc@8knVflhmcvHtaCb0lRFYRtcy5KEou7vaO/RZwlfFuPst02r@oBL6Z5XG4cZ5XGRUFyzrKSirlD4E9C12S5ZBkrl0uvoOk6ICvORVIEhCW@osE/@1zALs/9SdC4ZNldzYWcFCQu9R4SnsC@kyJyyQnxWFLzCmdR83kR@X7DFQVOD2TR0plLVbt00Vs67GkKqxe9DWp2Zs6yBOZYYk7GKdtTmL8RO2qubGiKG67itOit7ON0R4dSi5xlI7OlQEN1GSlrC5oLbe2OhQUtdyIjsMsLQ6VioJUC64WN0kGraRT5joM8WbGU6njaK8uUFaXmfct5WgCKkGmV11wQRgBxl1hZt/byj0g4B0@iIyUD5TONMc4qT89K8WuWJUu02lKzLAwgAQFNKg1HswjZOA7CQBsMiQU5gJwEBhUOKj2QvlGfUptIIdjyPR0XrsXepfw2Tsk2PvxGMznTiIfMuaPeRUBSmplbO97JwYLdtZC18QiQcwUMWGa8hFGsDLjiGSRLJ75yUO1sgf@B@zqzlZqturO1M37nezPh5k2eBSSj97ACFaGXfPkU0y/XEaM4y7EcdFJQgj@QHxbaNqgDTrwkF@qzwjU0zYon1K/nYLk1Thft67YubOKiXxgC8p6lKahjguyDUkapM1Tlj/TzBlyf0iXPqYhLLmTQ9WJNj7TvjKgEXh8NVT2SmPRn5RvJQcgV30EEoobo9JoRqoR2MrhrpcDKGBjG0rC4EvILT5OOs93WJDUYXZyMqqVzqq0zFD4GlcUQ3tQNFFxoY5WianephT6TRi49rGhekr@wIl4KwcV8HI6UoxXkt@/MdNxTccs1ZjCRHs6JIsdSiFt0lRG77NEU/18SerWJhWxSCQ0hhiP45xA5jyQFU/0St6ny6rFADlFNA4DqH@NZRsgftDT6cMk1P8g3T/Mz06luXg1Bb32kX6lYYk2gyG1zC9@GwNyqLLQg7p@uTZdfVU1odMH6LhdxUrHHUgKM3MdrhLEmFCDhaYh@QGiWLFzXBnD3GQA/GZgG9TFM51ZMvbaQ0nU5AHEgk@5hSPu5f1oxJb59e6xIwe42YzLPrDJnFpn/WkW@oeuUroxIT5jAGZ71RKukAUEmL6slLNYY1s9HdTtKv73bT5rB8dXcwK0GaQ7g2Pm3sbhN@7EHC7LetAXOw9IUKCsQb9ZaSipKJjM/GiuWo1wbg/W5XIyT19VBx7tpho64aZznkApevfGTfDvwit2BE7uXvrQa/RJhotF1jdxCuXet9dPozaaIL6wiXh9V7z65pn19pMBRQUfWqL97MsCFPzPsiupOOl1tOFtRL4SOPIv8UThvJCVeW28hw6FHql6mOPnjxUQtjlUfDQAPXepLh7kF/6sefhlsUvNhCHXsp8uR8peEHJD7DVttcFCKXbmBnEOsGVpZFsspKlW77pgyYo/lY4Gssf90gWCjOBKHrTotxww2np1DmJI3AJMGCfDm1pjH9T8nu@2iUOVG0kijPKI2fLDm0Y2ItzmH40HvNFbyfFAi8D3DGobMKuKKlqsNsmdZvuuDNw7t7eE9lycyIPeGuuKBLsuHu@o1ddgDEn@cZnjuQ9pR0nFXjR9KgQk@D5muVteMy@ur3iVjyKLfYUzrnvWsq@9Rx1woB60IiexIIFyRAFQZaXm1aFwdPyKasE@fDfbpU8KePBvsyVPC/ubZYJ8/Jeyvng32og2X0ydU4OTZFDg53u67j8L@x1KxbzaC32O9plizevVaxAwOI5eyrsElxnNlYZNM45X55mNK@35wiTjGtJ47fl8/s/c637LlkfY4d22vAupg4DhAjTcM/MnCxy0v1Ab95AOEcimczCJVQPZgh7Z5tGT6VQkfXGDkuu4DOb92/OtvnVffnTvk1Fl@cAh3PhDcuHsAgoa4@@aMU4AsZSV0blp4fuTo90/12AkD@eAZkPe0WsAMXIfGH5jks6hulFpJ@RrEIp@81I@qrXH0Eprfhb@nxNNiJ8ZO39GxJLnXCshfdaaxEHHlhSGc79YycBDSu0gO3tW6RT0OHA5YLCtaJoVio0b3Gyqop6QAsGvX96c3NQO91Xc6z6hhZLFGTawNUm@pb3f1hVSTgaoBYa22zaup48ABNqWDHzbql8rR9/76R4qRd0LkqJPT9R/@Aw)
Outputs 27 `1`s followed by a trailing newline.
Unfortunately I had to fix a bug in LMBM with the `o` peg for this answer to work. The link above links to the entire LMBM interpreter, with the fix, contained in TIO's header/footer, with the LMBM code in the code section.
## Explanation
The code is a loop. Here's the setup:
```
/O
O4
7/
*
~
```
This creates 2 marbles, sets one to 4 and the other to 7, then multiplies them into a single marble with a value of 28. Finally the `~` pushes the marble up to the top of that column, where the top `/` pushes it into the loop.
```
)
?
_
o
~ :
u
```
This is the loop. `?` is a conditional that sets the marble's spin to right if its value is truthy (non-zero), and 0 otherwise.
`)` decrements the marble's value. We do this *before* the conditional to account for LMBM's trailing newline.
`_` pushes the marble in the direction of its spin. This is the exit condition for the loop. If the marble's value was not truthy, ie 0, this pushes the marble to the left, out of bounds. Out of bounds marbles are automatically destroyed. When all marbles are destroyed, the program terminates.
`o` is a split. It splits the marble, pushing one copy left and the other right.
The left marble hits ~, which pushes it back up to the top of the loop.
The right marble hits `:`, which sets its value to its spin (1 for right, 0 for left), then it falls into `u`, which prints the marble's value and destroys it.
[Answer]
# [`experimental-type-lang`](https://github.com/Merlin04/experimental-type-lang) (63 bytes)
Here's a solution in a weird (and not very good) language I made:
```
type R<E,C>=C extends63?E:R<[...E,32],[...C,_]>;[51224,R<[],0>]
```
Output:
```
0> " "
```
I'm not counting the `0>` output prefix and quotes as part of the program output in this case (the quotes appear whenever the output is a string, and the output prefix is added for every evaluated expression), but if I wanted to count that I could just adjust the value `63` to be the desired output string length.
### Explanation
Here's an expanded version:
```
type Loop<Result = [], Counter = 0> = Counter extends 63
? Result
: Loop<[...Result, 32], [...Counter, _]>;
// The evaluated expression
[51224, Loop<>];
```
In this language, strings are arrays where the first item is a magic number indicating to the evaluator that it should be displayed as a string, and the second item is an array of character codes. The `Loop` function (called a `type` because I wanted to make the syntax resemble the TypeScript type system) is responsible for generating this array of characters. It does this by recursively calling itself, adding `32` (the code for a space) to a result array with the spread operator, until a counter reaches the desired output length. In `experimental-type-lang`, numbers are just arrays of "items" (represented by a `_`) with the length being the numerical value; because there is no language-level add operator and importing the `Add` type from the standard library would take too many characters, I increment the counter by spreading it into an array and adding an `_`.
[Answer]
# Cjam, 1 byte
```
N
```
## Explanation
```
N e#Push '\n' and implicit print
```
[Answer]
# [J](http://jsoftware.com/), 6 bytes
```
echo!4
```
[Try it online!](https://tio.run/nexus/j#@5@anJGvaPL/PwA "J – TIO Nexus")
Output:
```
24
```
Notice the three spaces on the second line.
[Answer]
## JavaScript (ES6), 17 bytes
*Edit: I overlooked the rules. This is now returning a string, but is much longer than initially intended.*
Returns `"Infinity,Infinity"`.
```
let f =
_=>`${[1/0,1/0]}`
console.log(f())
```
] |
[Question]
[
My father who [was a really good APLer](https://youtu.be/pL8OQIR5cB4?t=3m16s) and taught me all the basics of APL (and much more), passed away on this day, five years ago. In preparation for [50 Years of APL](http://www.dyalog.com/50-years-of-apl.htm), I found [this patent letter](https://tidsskrift.dk/plugins/generic/pdfJsViewer/pdf.js/web/viewer.html?file=https%3A%2F%2Ftidsskrift.dk%2Fregistreringstidende-varemaerker%2Farticle%2Fdownload%2F95152%2F143241%2F#page=8) (translated for the convenience of those who do not read Danish) for a handwritten logo. It explains a major reason for APL never gaining a large user base – a reason which of course applies to all of this community's amazing golfing languages too:
---
A 3497/77 Req. 29th Aug. 1977 at 13
[![EASIER COMMUNICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS …](https://i.stack.imgur.com/pEzT8.png)](https://i.stack.imgur.com/pEzT8.png)
**Henri Brudzewsky,** engineering consultancy company, **Mindevej 28, Søborg,**
**class 9**, including computers, especially APL coded computers,
**class 42:** IT service agency company, especially during use of APL coded computers.
---
# Task
**Produce infinitely repeating output of the text `EASIER COMMUNICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS` with no newlines.** You may begin the text with `EASIER` or `FASTER` or `FEWER`.
[Answer]
## SVG(HTML5), 336 bytes
```
<svg width=500 height=500><defs><path id=p d=M49,250a201,201,0,0,1,402,0a201,201,0,0,1,-402,0></defs><text font-size="32"><textPath xlink:href=#p>EASIER COMMUNICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS</textPath><animateTransform attributeName=transform type=rotate from=360,250,250 to=0,250,250 dur=9s repeatCount=indefinite>
```
Edit: Some people have found that the font doesn't quite fit for them so here is a version that allows you a few pixels of adjustment:
```
<p><input type=number value=0 min=0 max=9 oninput=p.setAttribute('d','M250,250m20_,0a20_,20_,0,1,1,-20_,-20_a20_,20_,0,1,1,-20_,20_a20_,20_,0,1,1,20_,20_a20_,20_,0,1,1,20_,-20_'.replace(/_/g,this.value))></p>
<svg width=500 height=500><defs><path id=p d=M250,250m200,0a200,200,0,1,1,-200,-200a200,200,0,1,1,-200,200a200,200,0,1,1,200,200a200,200,0,1,1,200,-200></defs><text font-size="32"><textPath xlink:href=#p>EASIER COMMUNICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS</textPath><animateTransform attributeName=transform type=rotate from=360,250,250 to=0,250,250 dur=9s repeatCount=indefinite>
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 25 bytes
```
[‘æƒËRSˆ¾¥ƒŽÁˆ¾¡ŸÂ ‘?
```
[Try it online!](https://tio.run/nexus/05ab1e#@x/9qGHG4eZDy45NOtwdFHy67dC@Q0uPTTq693AjmL3w6I7DTYfXg9gKQJX2//8DAA "05AB1E – TIO Nexus")
Explanation:
```
[‘æƒËRSˆ¾¥ƒŽÁˆ¾¡ŸÂ ‘?
[ Start infinite loop
‘æƒËRSˆ¾¥ƒŽÁˆ¾¡ŸÂ ‘ Push the compressed string in uppercase, starting from FEWER, with a trailing space
? Print without trailing newline
```
[Answer]
# PHP, 76 Bytes
```
for(;;)echo strtr(EASI0MMUNICATION1FAST0DING1FEW0DERS1,["ER CO"," MEANS "]);
```
[Try it online!](https://tio.run/nexus/php#s7EvyCjgSi0qyi@KL0otyC8qycxL16hzjffzD/F0dtW0/p@WX6Rhba2ZmpyRr1BcUlRSpOHqGOxp4Osb6ufp7Bji6e9n6OYYHGLg4unnbujmGm7g4hoUbKgTreQapODsr6SjpODr6ugXrKAUCzTsPwA "PHP – TIO Nexus")
[Answer]
# Vim 69 bytes
```
qqAFEWER CODERS MEANS EASIER COMMUNICATION M<C-n> FASTER CODING M<C-n> <esc>@qq@q
```
[Answer]
## HTML, 122 bytes.
Sorry, can't help myself.
```
<marquee style="width:5em;word-spacing:5em;">EASIER COMMUNICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS </marquee>
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~82~~ 81 bytes
*-1 byte thanks to Leaky Nun.*
I'm probably doing something wrong but it's really late so meh. Note the trailing comma.
```
while 1:print'FEWER CODERS MEANS EASIER COMMUNICATION MEANS FASTER CODING MEANS',
```
[Try it online!](https://tio.run/nexus/python2#@1@ekZmTqmBoVVCUmVei7uYa7hqk4Ozv4hoUrODr6ugXrODqGOwJFvP1DfXzdHYM8fT3g0q5OQaHQJR7@rlDxNR1/v//mpevm5yYnJEKAA "Python 2 – TIO Nexus")
## Another solution, 85 bytes
I can probably golf this further.
```
while 1:print'%sER CO%s MEANS'*3%('FEW','DERS',' EASI','MMUNICATION',' FAST','DING'),
```
[Try it online!](https://tio.run/nexus/python2#@1@ekZmTqmBoVVCUmVeirlrsGqTg7K9arODr6ugXrK5lrKqh7uYarq6j7uIaFAykFFwdgz2BtK9vqJ@ns2OIp78fSNTNMTgEpMjTz11dU@f/fwA "Python 2 – TIO Nexus")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~33~~ 29 bytes
4 bytes thanks to Erik the Outgolfer.
```
“©%5ÐƬwȮh¬Þ6.⁷ḷḊḥṫɠlḶṀġß»Œu⁶¢
```
[Try it online!](https://tio.run/nexus/jelly#AT4Awf//4oCcwqklNcOQxqx3yK5owqzDnjYu4oG34bi34biK4bil4bmryaBs4bi24bmAxKHDn8K7xZJ14oG2wqL//w "Jelly – TIO Nexus")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 70 bytes
```
"FEWER CODERS MEANS EASIER COMMUNICATION MEANS FASTER CODING MEANS "w↰
```
[Try it online!](https://tio.run/nexus/brachylog2#@6/k5hruGqTg7O/iGhSs4Ovq6Bes4OoY7AkW8/UN9fN0dgzx9PeDSrk5BodAlHv6uUPFlMoftW34/x8A "Brachylog – TIO Nexus")
## How it works
```
"..."w↰
"..." generate the string "..."
w print to STDOUT without trailing newline
↰ do the whole thing all over again
```
[Answer]
# HTML/CSS (firefox only), ~~179~~ ~~177~~ ~~183~~ ~~176~~ 173 bytes
```
<b id=a>EASIER COMMUNICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS </b>E<a><style>*{margin:0;}a{position:fixed;left:0;right:0;height:1em;background:-moz-element(#a)}
```
Certianly nowhere near the lowest scores, I just thought it would be fun to get infinite repitition in HTML/CSS, without any JS involved :)
## Changelog:
* Removed quotes around id attribute
* added "round" background-repeat to stretch the text so it wraps correctly
* changed to single-line output
* replace `width:100%` style with `right:0` to save 3 bytes
[Answer]
# [Python 3](https://docs.python.org/3/), 87 bytes
```
while 1:print(end="FEWER CODERS MEANS EASIER COMMUNICATION MEANS FASTER CODING MEANS ")
```
[Try it online!](https://tio.run/nexus/python3#@1@ekZmTqmBoVVCUmVeikZqXYqvk5hruGqTg7O/iGhSs4Ovq6Bes4OoY7AkW8/UN9fN0dgzx9PeDSrk5BodAlHv6uUPFlDT//wcA "Python 3 – TIO Nexus")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 92 bytes
```
main(){for(;printf("FEWER CODERS MEANS EASIER COMMUNICATION MEANS FASTER CODING MEANS "););}
```
[Try it online!](https://tio.run/nexus/c-gcc#@5@bmJmnoVmdll@kYV1QlJlXkqah5OYa7hqk4Ozv4hoUrODr6ugXrODqGOwJFvP1DfXzdHYM8fT3g0q5OQaHQJR7@rlDxZQ0rTWta///BwA "C (gcc) – TIO Nexus")
[Answer]
# [LOLCODE](http://lolcode.org/), 116 bytes
```
HAI 1
IM IN YR O
VISIBLE "FEWER CODERS MEANS EASIER COMMUNICATION MEANS FASTER CODING MEANS "!
IM OUTTA YR O
KTHXBYE
```
[Try it online!](https://tio.run/nexus/lolcode#LYzLDYAwDMXunSKwASMECPAETaUmfLr/IEV8rrblujCoC4gEpZIphQOGfhNqJzkl05BGyUZRWI2EDS@LcVcM7Ej6q4nNvxw6/6xtnnHa3fl7r75cfZFabw "LOLCODE – TIO Nexus")
[Answer]
# Ruby, 77 bytes
assigning `" MEANS "` to a variable saved all of 1 byte :-)
```
loop{$><<"EASIER COMMUNICATION#{m=" MEANS "}FASTER CODING#{m}FEWER CODERS"+m}
```
[Answer]
# JavaScript (ES6), ~~90~~ 87 bytes
```
while(1)console.log`EASIER COMMUNICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS `
```
---
## Functioning Alternative, 100 bytes
"Functioning" here meaning "won't crash your browser" (for a while, at least)!
```
setInterval(_=>console.log`EASIER COMMUNICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS `,1)
```
[Answer]
# [Befunge](https://github.com/catseye/Befunge-93), 73 bytes
```
" SNAEM GNIDOC RETSAF SNAEM NOITACINUMMOC REISAE SNAEM SREDOC REWEF">:#,_
```
[Try it online!](https://tio.run/nexus/befunge#@6@kEOzn6Oqr4O7n6eLvrBDkGhLs6AYV8/P3DHF09vQL9fUFS3kGO7pCpYKDXCHKw13dlOyslHXi//8HAA "Befunge – TIO Nexus")
[Answer]
# Octave, 86 bytes
```
while fprintf('FEWER CODERS MEANS EASIER COMMUNICATION MEANS FASTER CODING MEANS ')end
```
**Explanation:**
This is fairly self-explanatory. The only real "trick" here is to use `while fprintf`. When `fprintf` is given a return argument, it will return the number of characters printed, and all non-zero numbers are considered `true` in Octave, so the loop condition will always be true.
---
I desperately tried to make the more interesting approach shorter, but it turned out to be 9 bytes longer, unfortunately:
```
while fprintf('FEW%sDERS%sEASI%sMMUNICATION%sFAST%sDING%s',{'ER CO',' MEANS '}{'ababab'-96})end
```
This tries to insert the strings `'ER CO'` and `' MEANS'` into the string at the correct locations, using direct indexing where `'ababab'-96` is a shorter version of `[1 2 1 2 1 2]`.
This was a bit shorter (93 bytes), but still longer than the naive approach
```
while fprintf('FEWER CODERS%sEASIER COMMUNICATION%sFASTER CODING%s',{' MEANS '}{[1,1,1]})end
```
And another one (89 bytes), using Level River St's approach:
```
while fprintf(['FEWER CODERS',s=' MEANS ','EASIER COMMUNIDATION',s,'FASTER CODING',s])end
```
This should work in theory, for one less byte than the original solution, but it fails for some strange reason:
```
while fprintf"FEWER CODERS MEANS EASIER COMMUNICATION MEANS FASTER CODING MEANS "
end
```
This uses the buggy feature that `fprintf('abc def')` is equivalent to `fprintf"abc def"`. The `end` must be on the next line, but it's still one byte shorter since two parentheses are skipped.
And one more for 87:
```
while fprintf('FEWER CODERS%sEASIER COMMUNICATION%sFASTER CODING%s',k=' MEANS ',k,k)end
```
---
Well, don't say I didn't try :)
[Answer]
## [Alice](https://github.com/m-ender/alice), 70 bytes
```
" SNAEM "k"SREDOC REWEF"e0j"GNIDOC RETSAF"e0j"NOITACINUMMOC REISAE"d&o
```
[Try it online!](https://tio.run/nexus/alice#@6@kEOzn6OqroJStFBzk6uLvrBDkGu7qppRqkKXk7ucJEQgJdoSI@Pl7hjg6e/qF@vqCJTyDHV2VUtTy//8HAA "Alice – TIO Nexus")
### Explanation
Unfortunately, reusing the `MEANS` (with spaces) only saves a single byte over just printing the whole thing in one go. Consequently, extracting the `ER CO` would actually cost a byte (or probably more, because it would be slightly more expensive to extract another section).
```
" SNAEM " Push the code points of " MEANS " in reverse.
k If there is a return address on the return address stack (which
there isn't right now), pop it and jump there.
"SREDOC REWEF" Push the code points of "FEWER CODERS" in reverse.
e0j Jump to the beginning of the line, pushing the location of the
j to the return address stack. Hence, we push the code points
of " MEANS " again, but then the k pops the return address and
jumps back here.
"GNIDOC RETSAF" Push the code points of "FASTER CODING" in reverse.
e0j Jump to the beginning of the line again.
"NOITACINUMMOC REISAE" Push the code points of "EASIER COMMUNICATION" in reverse.
d Push the stack depth.
&o Print that many bytes from the top of the stack.
Afterwards the IP wraps around to the first column and the
program starts over.
```
[Answer]
## C#, 102 bytes
```
_=>{for(;;)System.Console.Write("EASIER COMMUNICATION{0}FASTER CODING{0}FEWER CODERS{0}"," MEANS ");};
```
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 85 bytes
```
BEGIN{for(c=" MEANS ";;)printf"EASIER COMMUNICATION"c"FASTER CODING"c"FEWER CODERS"c}
```
[Try it online!](https://tio.run/nexus/awk#@@/k6u7pV52WX6SRbKuk4Ovq6BesoGRtrVlQlJlXkqbk6hjs6Rqk4Ozv6xvq5@nsGOLp76eUrOTmGBwCFnbx9HMH8V3DIVzXoGCl5Nr//wE "AWK – TIO Nexus")
Apparently I came up with the same shortcut as others. All other substitutions take up too much space. :(
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~64~~ 60 bytes
```
+>(`$
EASI_MMUNICATION@FAST_DING@FEW_DERS@
@
MEANS
_
ER CO
```
[Try it online!](https://tio.run/##K0otycxLNPz/X9tOI0GFy9Ux2DPe1zfUz9PZMcTT38/BzTE4JN7F08/dwc01PN7FNSjYgcuBS8HX1dEvWIErnss1SMHZ//9/AA "Retina – Try It Online")
### Explanation
The program consists of three grouped replacement stages. The group as a whole is applied repeatedly until the output stops changing (which it never will) and the output is printed after each time (rather than just at the end, because there will be no end)
The first stage adds the string `EASI_MMUNICATION@FAST_DING@FEW_DERS@` at the end of the input. The input starts out empty, but keeps growing.
The second stage replaces each of those `@`s with the string `MEANS` (surrounded by a space on each side).
The third stage replaces the `_`s with the string `ER CO`.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 69 bytes
```
Wp"FEWER CODERS MEANS EASIER COMMUNICATION MEANS FASTER CODING MEANS
```
[Try it online!](https://tio.run/nexus/pyth#@x9eoOTmGu4apODs7@IaFKzg6@roF6zg6hjsCRbz9Q3183R2DPH094NKuTkGh0CUe/q5Q8X@/wcA "Pyth – TIO Nexus")
## How it works
```
Wp"...
W while the following is true: (do nothing)
p print the following and return the following
"...
```
[Answer]
# [Lua](https://www.lua.org), 92 bytes
```
while 1 do io.write("FEWER CODERS MEANS EASIER COMMUNICATION MEANS FASTER CODING MEANS ")end
```
[Try it online!](https://tio.run/nexus/lua#@1@ekZmTqmCokJKvkJmvV16UWZKqoeTmGu4apODs7@IaFKzg6@roF6zg6hjsCRbz9Q3183R2DPH094NKuTkGh0CUe/q5Q8WUNFPzUv7/BwA "Lua – TIO Nexus")
[Answer]
# [Java (OpenJDK 9)](http://openjdk.java.net/projects/jdk9/), 114 bytes
```
static void f(){while(1>0)System.out.print("FEWER CODERS MEANS EASIER COMMUNICATION MEANS FASTER CODING MEANS ");}
```
[Try it online!](https://tio.run/nexus/java-openjdk9#S85JLC5W8E3MzFOo5lIAgoLSpJzMZIXiksQSIFWWn5mikAuU1QguKcrMS4@OVUgsSi/WhCoGgTQNTWswp/Y/siagcHV5RmZOqoahnYFmcGVxSWquXn5piV4B0JwSDSU313DXIAVnfxfXoGAFX1dHv2AFV8dgT7CYr2@on6ezY4invx9Uys0xOASi3NPPHSqmpGld@5@r9v/XvHzd5MTkjFQA "Java (OpenJDK 9) – TIO Nexus") Stop the execution after a few seconds because it does not know when to stop.
[Answer]
## C, 86 bytes
```
f(){printf("FEWER CODERS MEANS EASIER COMMUNICATION MEANS FASTER CODING MEANS ");f();}
```
See it [work online](https://tio.run/nexus/c-gcc#@5@moVldUJSZV5KmoeTmGu4apODs7@IaFKzg6@roF6zg6hjsCRbz9Q3183R2DPH094NKuTkGh0CUe/q5Q8WUNK2BBlrX/gcaqJCbmJmnoVCWn5mioMlVzcUJkuGq/f81L183OTE5IxUA).
[Answer]
# [bc](https://www.gnu.org/software/bc/manual/html_mono/bc.html), 76 bytes
```
while(1)"EASIER COMMUNICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS "
```
[Answer]
# [Perl 6](https://perl6.org), ~~81 80~~ 79 bytes
```
print ('EASIER COMMUNICATION','FASTER CODING','FEWER CODERS'X'MEANS'),' 'for ^Inf
```
[Try it](https://tio.run/nexus/perl6#Ky1OVSgz00u2/l9QlJlXoqCh7uoY7OkapODs7@sb6ufp7Bji6e@nrqPu5hgcAhZ28fRzB/FdwyFc16Bg9Qh1X1dHv2B1TR11BfW0/CKFOM@8tP//AQ "Perl 6 – TIO Nexus")
```
loop {print ('EASIER COMMUNICATION','FASTER CODING','FEWER CODERS'X'MEANS'),' '}
```
[Try it](https://tio.run/nexus/perl6#Ky1OVSgz00u2/p@Tn1@gUF1QlJlXoqCh7uoY7OkapODs7@sb6ufp7Bji6e@nrqPu5hgcAhZ28fRzB/FdwyFc16Bg9Qh1X1dHv2B1TR11BfXa//8B "Perl 6 – TIO Nexus")
```
loop {print [~] 'EASIER COMMUNICATION','FASTER CODING','FEWER CODERS'X'MEANS '}
```
[Try it](https://tio.run/nexus/perl6#Ky1OVSgz00u2/p@Tn1@gUF1QlJlXohBdF6ug7uoY7OkapODs7@sb6ufp7Bji6e@nrqPu5hgcAhZ28fRzB/FdwyFc16Bg9Qh1X1dHv2AF9dr//wE "Perl 6 – TIO Nexus")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 68 bytes
```
`'EASIER COMMUNICATION*FASTER CODING*FEWER CODERS*'42' MEANS 'Zt&YDT
```
[Try it online!](https://tio.run/nexus/matl#@5@g7uoY7OkapODs7@sb6ufp7Bji6e@n5eYYHAIWdPH0c9dycw2HcFyDgrXUTYzUFXxdHf2CFdSjStQiXUL@/wcA "MATL – TIO Nexus")
### Explanation
```
` % Do...while
'EASIER COMMUNICATION*FASTER CODING*FEWER CODERS*' % Push this string
42 % Push 42 (ASCII for '*')
' MEANS ' % Push this string
Zt % String replacement
&YD % printf to STDOUT
T % Push true as loop condition
% End (implicit)
```
[Answer]
# Axiom, ~~92~~ 89 bytes
```
repeat fortranLiteral"EASIER COMMUNICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS "
```
insert in one line to Axiom window. Possible there is one function shorter than "fortranLiteral" that not write "\n"
[Answer]
# [Blank](https://esolangs.org/wiki/Blank), 267 bytes
```
[70][69][87][69][82][32][67][79][68][69][82][83][32][77][69][65][78][83][32][69][65][83][73][69][82][32][67][79][77][77][85][78][73][67][65][84][73][79][78][32][77][69][65][78][83][32][70][65][83][84][69][82][32][67][79][68][73][78][71][32][77][69][65][78][83][32]{p}
```
Pushes `FEWER CODERS MEANS EASIER COMMUNICATION MEANS FASTER CODING MEANS` to the stack, then prints it. Never terminates as no `{@}`
Also fun fact, I used the following [Braingolf](https://esolangs.org/wiki/Braingolf) script to generate this code
```
"FEWER CODERS MEANS EASIER COMMUNICATION MEANS FASTER CODING MEANS "l>[<$_<91+2^9-@_ 91+2^7-@l>]"{p}"@3
```
[Answer]
# Groovy 79 bytes
```
m=" MEANS";for(;;)print"EASIER COMMUNICATION$m FASTER CODING$m FEWER CODERS$m "
```
Uses groovy's string interpolation.
] |
[Question]
[]
|
[Question]
[
The dealer has been sloppy and lost track of what cards his/her deck contains and what cards are missing, can you help him/her?
---
A complete deck consists of 52 playing cards, namely:
Each color in the deck (hearts, diamonds, spades, clubs) contains:
* The numbers [2 - 10]
* A Jack
* A Queen
* A King
* An Ace
---
**Task**
Your program will read the contents of the deck from STDIN until a newline is read.
You can assume that the input will be in the form of "nX nX nX nX" etc. where:
* n - any number between [2 - 10] **or** either 'J', 'Q', 'K' or 'A'.
(You can assume upper case only for non-numeric characters)
* X - any of the following : 'H', 'D', 'S', 'C' (You can assume upper
case only)
Where:
* 'J' = Jacks
* 'Q' = Queen
* 'K' = King
* 'A' = Ace
And
* 'H' = Hearts
* 'D' = Diamonds
* 'S' = Spades
* 'C' = Clubs
You can assume that there will be no duplicates in the input.
Your program must then print the missing cards in the deck to STDOUT in the same fashion as the input ("nX nX nX") or print 'No missing cards' if all 52 cards are supplied.
There is no constraint on the order of the output of the cards.
Example input:
```
9H AH 7C 3S 10S KD JS 9C 2H 8H 8C AC AS AD 7D 4D 2C JD 6S
```
Output:
```
3H 4H 5H 6H 7H 10H JH QH KH 2D 3D 5D 6D 8D 9D 10D QD 2S 4S 5S 7S 8S 9S QS KS 3C 4C 5C 6C 10C JC QC HC
```
Happy golfing!
[Answer]
## Windows Batch (CMD), ~~205~~ 204 bytes
```
@set/pc=
@set d=
@for %%s in (H D S C)do @for %%r in (2 3 4 5 6 7 8 9 10 J Q K A)do @call set d=%%d%% %%r%%s
@for %%c in (%c%)do @call set d=%%d: %%c=%%
@if "%d%"=="" set d= No missing cards
@echo%d%
```
Loops over the suits and ranks building a complete deck, then deletes the input cards. Save 1 byte if `T` is allowed instead of `10`. Save 11 bytes if command-line arguments are acceptable input. Edit: Saved 1 byte thanks to @user202729.
[Answer]
# Python, ~~147~~ ~~146~~ ~~145~~ ~~138~~ ~~131~~ ~~129~~ ~~127~~ ~~125~~ 120 bytes
```
print(' '.join(set(`x`+y for x in range(2,11)+list('JQKA')for y in'HDSC')-set(raw_input().split()))or'No missing cards')
```
Gets all possible cards as a set and subtracts the input cards.
-1 byte thanks to mbomb007 pointing out an extra space in my code.
-1 byte thanks to mbomb007 for pointing out some golfing that can be done with Python 2 (-5 bytes and +4 bytes for `raw_` in `raw_input`)
-7 bytes by switching to using sets and set subtraction instead of list comprehensions
-7 bytes thanks to ValueInk for pointing out that I don't need to `list` the suites
-2 bytes thanks to Datastream for pointing out that just writing out all of the values is more byte-effective than the weird thing I had earlier
-2 bytes thanks to ValueInk for pointing out that sets can take generators so I don't need to put it in a list comprehension
-2 bytes thanks to Datastream for pointing out that I can golf it down even more if I switch to Python 3 again... (+2 for parens after for print, -4 for `raw_`)
-5 bytes thanks to Lulhum and myself for pointing out that by switching back to Python 2 (!!!) can help me save bytes (using range again, using backticks instead of `str(`, and +4 due to `raw_`)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 39 bytes
```
ðIð¡YTŸ"JQKA"S«"CDHS"SâJsKðýDg>i“Noœ¶‡¶
```
[Try it online!](https://tio.run/nexus/05ab1e#DY49asNQEISv8qETJPqxpCYgdovNexB4bJqcIKRKkQv4DmnTOG0aVcaNGz18EV9EWfhmi2WYmb2uz3XdTm@vt0uTSl4a3/4aUfPG62/6ynWtV31/@rgff14@b9/b@X48bed9n43FGIXOORiPD05WkjMLrTEFwhI4izIqvdIKSTl4uCWkIaONv9NFkNIZvdDHdQZhUAYjBUJRilGcImQjR10YojsChTGmOJMyxQBl9n8 "05AB1E – TIO Nexus")
**Explanation**
```
ðI # push space and input
ð¡ # split on spaces
YTŸ # push the range [2 ... 10]
"JQKA"S« # append ['J','Q','K','A']
"CDHS"Sâ # cartesian product with suits
J # join each card with its suit
sK # remove any cards in input from the list of all cards
ðýDg>i # if the length of the resulting list is 0
“Noœ¶‡¶ # push the string "No missing cards"
# output top of stack
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), ~~49~~ 47 bytes
```
B,2>"JQKA"+"HDSC"m*:slS/-S*"No missing cards"e|
```
[Try it online!](https://tio.run/nexus/cjam#DcJBCsIwEEDRq3xmWRU1irUuhDizCCkIMicQFSlYBbP17rGPV0/zcJR86aPMJJmrjM2hvHy58EbOH8ahlOH95Hb93os8frV2iZholY2zXjm9kZ1OCYn9VIlTJxqtsTWCko2d/wE "CJam – TIO Nexus")
**Explanation**
```
B, e# The range from 0 to 10
2> e# Slice after the first two elements, giving the range from 2 to 10
"JQKA"+ e# Concatenate with "JQKA", giving the array containing all ranks
"HDSC" e# The string containing all suits
m* e# Take the Cartesian product
:s e# And cast each pair to a string. Now a full deck has been constructed
l e# Read a line of input
S/ e# Split it on spaces
- e# Remove all cards from the deck that were in the input
S* e# Join the result with spaces
"No missing cards" e# Push the string "No missing cards"
e| e# Take the logical OR of the result and the string, returning the
e# first truthy value between the two. (empty arrays are falsy)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 39 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
9R‘Ṿ€;“JQKA”p“CDHS”F€œ-ɠḲ¤Kȯ“¡¢ıḍĖ9ṭƥw»
```
**[Try it online!](https://tio.run/nexus/jelly#FY29agJxEMR7n2JeQFDvm1THLrLcvzr3RdKlPdKnCoQUEVS0U0KsFMHi0JA8xt2LXCbN7uwMv9mhWPTNe3e@9s/7h775qOpQ9s3ykVLUnHLO5P46/l11p2O7DT@fjNp1u7l9daeX21vRnQ/fu6f2MgyJYiYoBLkhp@BpqBWRYjpxZILYEAQRM0cqSAwzR23IDKUgdQRHRUxR0xdUhsgICzICioSWI1bETpdLEAwVUUNC@v8RfzsKdipKR87JEkepoz8)**
### How?
```
9R‘Ṿ€;“JQKA”p“CDHS”F€œ-ɠḲ¤Kȯ“¡¢ıḍĖ9ṭƥw» - Main link: no arguments
9R - range(1,9) [1,2,3,4,5,6,7,8,9]
‘ - increment [2,3,4,5,6,7,8,9,10]
Ṿ€ - uneval each [['2'],['3'],['4'],['5'],['6'],['7'],['8'],['9'],['10']]
;“JQKA” - concatenate with char-list "JQKA" [['2'],['3'],['4'],['5'],['6'],['7'],['8'],['9'],['10'],['J'],['Q'],['K'],['A']]
p“CDHS” - Cartesian product with char-list "CDHS" [[['2'],['C']],[['2'],['D']],...]
F€ - flatten each [['2','C'],['2','S'],...]
¤ - nilad followed by link(s) as a nilad
ɠ - read a line from STDIN
Ḳ - split on spaces
œ- - multi-set difference
K - join with spaces
“¡¢ıḍĖ9ṭƥw» - compressed string "No missing cards"
ȯ - logical or
- implicit print
```
[Answer]
# C#, 343 bytes
First time posting one of my golfs, not a very good contender though. I'm sure I can reduce this more.
The idea behind it is a sparse array storing occurrences of cards, with indexes calculated by the ASCII values of the different values and suits multiplied against each other (e.g. an ace of spades (AS) would be stored in the area at index (65 \* 83 = 5395)). This way, each type of card gets a unique index that can be checked later for existance in the "map" array.
```
void M(string[]a){var c=new int[]
{50,51,52,53,54,55,56,57,49,74,81,75,65,72,68,83,67};var e=new
int[9999];int i=0;int j=0;foreach(var s in a) e[s[0]*s[s.Length-
1]]++;int f=0;for(i=0;i<13;i++)for(j=13;j<17;j++)if(e[c[i]*c[j]]==0)
{f=1;Console.Write(((i<9)?(i+2)+"":(char)c[i]+"")+(char)c[j]+"
");}if(f==0) Console.WriteLine("No missing cards");}
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~114~~ ~~111~~ 110 bytes
```
param($n)('No missing cards',($a=(2..10+'JQKA'[0..3]|%{$i=$_;"CSHD"[0..3]|%{"$i$_"}}|?{$n-notmatch$_})))[!!$a]
```
[Try it online!](https://tio.run/nexus/powershell#PcjNaoNQEAbQ/fcUidxylbaSXv8pocjMYlAoyCxDkEsKiQtNidklPrvd9SzP@utvfgzNFIX2@7oZh3kepvPm5G8/s30Ljd@HLo4/dq@26draHnZxnByfLw8z7E3/GZAKB/8ZmMH0wbI8vx5mep@u99HfTxfTL1EUHbZb44/rulpHcAoncIyEkCgSQcJICakiFaSMjJApMkHGyAm5IhfkjIJQKApBwSgJpaIUlIyKUCkqQcVoCI2iETSMjtApOkHHaAmtohW0jJpQK2pBzfYP "PowerShell – TIO Nexus")
Takes input `$n` as either a space-delimited or newline-delimited string. Constructs an array from the range `2..10` concatenated with `JQKA` (indexed with `[0..3]` to make it a `char` array). That array is fed into a loop `|%{}` that sets helper `$i` then loops over the suits to concatenate the results together with `$i$_`. At the end of this loop, we have an array of strings like `("2C", "2S", "2H", ... "AH", "AD")`. That array is fed into a `Where-Object` (`|?{}`) with the filter as those elements `$_` that regex `-notmatch` the input `$n`. The result of that filtering is stored into `$a`.
Then, we use a pseudo-ternary `( , )[]` to select whether we output `'No missing cards'` or `$a`, based on whether `!!$a` turns to a Boolean `$false` or `$true`. If `$a` is empty (meaning every card in the deck is in the input), then `!!$a` is `0`, so the `"No missing cards"` is selected. Vice versa for `$a` being selected. In either case, that's left on the pipeline, and output is implicit.
[Answer]
# Bash + coreutils, 89
```
sort|comm -3 <(printf %s\\n {10,{2..9},A,J,K,Q}{C,D,H,S}) -|grep .||echo No missing cards
```
I/O as a newline-delimited list.
### Explanation
* `sort` reads newline-delimited input from STDIN and sorts it
* This is piped to `comm`
* `printf %s\\n {10,{2..9},A,J,K,Q}{C,D,H,S}` is a brace-expansion to generate the full deck of cards. The `printf` prints each card on its own line. The order is given such that the output is the same as if it had been piped to `sort`
* `comm` compares the full deck against the sorted input and outputs the difference. `-3` suppresses output of column 3 (the common ones)
* The whole output from `comm` is piped to `grep .`. If there was no output from `comm` (i.e. all cards were in the input), then the `||` "or" clause outputs the required message. Otherwise the `grep .` matches all lines output from `comm`.
[Try it online](https://tio.run/nexus/bash#DcK9CoMwFAbQ/XuKuxRauIo/pVboEpIhKBRKVpdirXXQSOJmfHbr4ezeuiW0dhwpyulxnt0wLV86@aaZaE0TXrM4LjcWXHHNr22VrFiz2S4Uhd51M8UhdO3P0tPSOHg/TD21b/fx@15qCI1CIjdIE4NaoTIoJTKN@1FCHA2EQqFwVcgkKoWb@QM).
[Answer]
# [Python 2](https://docs.python.org/2/),~~104,93,130~~,114 bytes
```
r=input()
print' '.join(n+x for n in list('23456789JQKA')+['10']for x in'HDSC'if n+x not in r)or'No missing cards'
```
[Try it online!](https://tio.run/nexus/python2#FY67asQwFET7fMXpZLMk7PrtIoWRiosNAaMypFi82UQhkRbbgf3x1I4Mc2GKM3dmm5@dv/2uSfpwm51fFerpKzif@MOda5jxOM@3W9ZEZXlRVnXT9uPQqfTwqk5H9bYz98goMVYrd2UP@rDusTkNs3oJ/Lhlcf6D6TxfFrVtqhU6odbkltPRMhh6S6vJhCZK00VZOkNtKAyZpjdUlix6Sy7khlxTCIWl0JRCaSgtpaYSqghr6thhaQxNfG5oLb3Qa0ZhNIyWUTMIQxyg4w6JZ9SfD4/Tefp8/wc "Python 2 – TIO Nexus")
* -10 bytes with hardcoding the list instead of using range!
* +37 bytes - missed printing 'No missing cards' if all cards are present in input!
* -16 bytes by modifying the code into a list comprehension!
[Answer]
# Ruby, 108 + 1 = 109 bytes
Uses the `-p` flag.
```
a=[*?2..'10',?J,?Q,?K,?A].map{|i|%w"H D S C".map{|c|i+c}}.flatten-$_.split;$_=a==[]?"No missing cards":a*' '
```
[Answer]
# PHP, 143 Bytes
```
foreach([H,D,S,C]as$c)foreach([2,3,4,5,6,7,8,9,10,J,Q,K,A]as$v)$r[]=$v.$c;echo join(" ",array_diff($r,explode(" ",$argn)))?:"No missing cards";
```
[Answer]
# [sed](https://www.gnu.org/software/sed/), 157 + 1 (`-r` flag) = ~~170~~ 158 bytes
```
x
s/$/;A2345678910JQK/
s/.+/&H&D&S&C;No missing cards/
:
s/(10|\w)(\w+)(.);/\1\3 \2\3;/
t
G
:s
s/(10.|[^ ;1]{2})(.*\n.*)\1/\2/
ts
s/[ ;]+/ /g
s/^ //
s/ N.+//
```
[Try it online!](https://tio.run/nexus/sed#Jc1Bi8IwFATge37FHJbSWuxrUrXWnEoCWyoIkqNPQRSkh20XI7iw@tftRhbmMAwfzPgjPH2QrlUxmy/KZSXzdrumMGYpRU1kIxcZvRnw1Xnf9RecjtezJ7EKIpb5g@9JzPc0ibNEE0suwIoLTeImPsXK/6vssTtAy/2vegY44T6bJCyJVWBvsoPepwS6hH4Avd@xCf80jlWDukFpUDjI3GFt0TpUBqrBMsSgDnGoLUqLmYUyaC0W7jV837qh9@P0@gc "sed – TIO Nexus")
This generates all possible cards and then remove each card in the input from the generated cards.
[Answer]
## [C#](http://csharppad.com/gist/0018fae00fc41bff1ac6681e4e5b2412), 282 bytes
---
**Golfed**
```
i=>{var o=new System.Collections.Generic.List<string>();string[] S={"H","D","S","C"},N="A 2 3 4 5 6 7 8 9 10 J Q K".Split(' ');foreach(var s in S){foreach(var n in N){if(!System.Linq.Enumerable.Contains(i,n+s)){o.Add(n+s);}}}return o.Count>0?string.Join(" ",o):"No missing cards";};
```
---
**Ungolfed**
```
i => {
var o = new System.Collections.Generic.List<string>();
string[] S = { "H", "D", "S", "C" }, N = "A 2 3 4 5 6 7 8 9 10 J Q K".Split(' ');
foreach( var s in S ) {
foreach( var n in N ) {
if( !System.Linq.Enumerable.Contains( i, n + s ) ) {
o.Add( n + s );
}
}
}
return o.Count > 0
? string.Join( " ", o )
: "No missing cards";
};
```
---
[Answer]
## JavaScript (ES6), ~~117~~ ~~114~~ 111 bytes
```
s=>[...Array(52)].map((_,i)=>~s.search(c=('JQKA'[v=i>>2]||v-2)+'CDHS'[i&3])?_:c+' ').join``||'No missing cards'
```
This takes advantage of the fact that *undefined* entries in the array generated by `map()` are coerced to empty strings when `join()`'d.
### Demo
```
let f =
s=>[...Array(52)].map((_,i)=>~s.search(c=('JQKA'[v=i>>2]||v-2)+'CDHS'[i&3])?_:c+' ').join``||'No missing cards'
console.log(f('9H AH 7C 3S 10S KD JS 9C 2H 8H 8C AC AS AD 7D 4D 2C JD 6S'))
```
[Answer]
# [Retina](https://github.com/m-ender/retina), 76 bytes
```
^
A2345678910JQK¶
\G(10|.)
$&H $&D $&S $&C
Dr` \S+
G1`
^$
No missing cards
```
Input/output is a list of space-separated cards. Output has a leading space.
[Try it online!](https://tio.run/nexus/retina#DcNBCsIwEAXQ/ZziL4oogiRpbZplyEBDCoLMtpQWBelChXbruTyAF6uB97aBvCmrc20bp1W6dr8vqG/3Wn1OB0KxiznnkgfiZUQvR2r1SENBlzee87rOrwdu03Jft81F@AgbUAq0EnSMJHABJqLJAnwm8AzLqBgmIDFq@QM "Retina – TIO Nexus")
### Explanation
Most of the code deals with building the full list of cards that should be in the deck:
```
^
A2345678910JQK¶
\G(10|.)
$&H $&D $&S $&C
```
First, we prepend a newline to the input, with all possible values of cards, then for each character of this line (or the couple of characters `10`) we build the list of all possible suits of that card.
```
Dr` \S+
```
This is a deduplication stage, it splits the string into chunks consisting of a space plus some non-spaces and keeps only one occurrence of each chunk. The modifier `r` makes this operate from right to left, keeping then the *last* occurrence of each chunk.
```
G1`
```
We keep only the first line, which now contains the missing cards.
```
^$
No missing cards
```
If the result is empty we replace it with "No missing cards"
[Answer]
# Python 3, 106 bytes
Combination of the two previous python answers mixed with some string unpacking shenanigans.
```
print(' '.join({x+y for x in[*'23456789JQKA','10']for y in'HDSC'}-{*input().split()})or'No missing cards')
```
[Answer]
# [Julia](http://julialang.org/), 116 bytes
```
print(join(setdiff(["$x$y"for x=∪(2:10,"JQKA")for y="HDSC"],readline()|>split),' ')|>s->s>""?s:"No missing cards")
```
[Try it online!](https://tio.run/##FY5daoNQEIW3crgEomAh8S8aiEVmHi4KBZnH0odQtdxgNXgtJNAFdC1dVjdib@AbmDMc5pzL12DO6bpeZzMu3mUyo2e7pTV9772qzW1zV/0043b6@/n1wuN@F6iqqUvlP673k9IspN6CuTu3gxk7z/8u7HUwix9ssX2Ip8IWSj3bo3qZ8GmsNeMH3s9za5W/rrlGqXEgRIL9TlAzKkFOCDUyB6F0CErGgREzQkLFSAWh2wWRRsSICLFGLIgJiUbCSAQJIdVInZlwcBmCjJG554xcUGlUhEajYTSChlBr1K4AuR7aDf8D "Julia 0.6 – Try It Online")
Very similar to Kyle Gullions python solution. Setdiff instead of - and the lambda to test for the empty string make it worse though.
[Answer]
# Japt, 39 bytes
```
"JQKA"¬c9õÄ)ï+"CHSD"q)kU ¸ª`No ÚÍg Ößs
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=IkpRS0EirGM59cQp7ysiQ0hTRCJxKWtVILiqYE5vINrNiGcg1t9z&input=WyI5SCIsIkFIIiwiN0MiLCIzUyIsIjEwUyIsIktEIiwiSlMiLCI5QyIsIjJIIiwiOEgiLCI4QyIsIkFDIiwiQVMiLCJBRCIsIjdEIiwiNEQiLCIyQyIsIkpEIiwiNlMiXQo=)
[Answer]
# [Tcl](http://tcl.tk/), 270 228 chars
(Shortened with some help from Wît Wisarhd)
```
foreach s {H D S C} {foreach c {2 3 4 5 6 7 8 9 J Q K A} {dict set d $c$s 0}}
gets stdin l
foreach c $l {dict set d $c 1}
set m {}
dict for {c h} $d {if {!$h} {lappend m $c}}
if {![llength $m]} {set m "No missing cards"}
puts $m
```
[Try it online!](https://tio.run/##XY7BasMwEETv/orXoA9InDSOj8Y6GAcKRcfSQ5Ac2yA7JlJOQt/uqimlUJjD7s5jZr2263q93buLHnCEBomijoTfoybk7DnwypGCEyUt75ypEmRG7XGdxyC0cGxjzPrOO5w344zN/lKE/Yezi9n3PBFi9nQSTNAMEWEI45XwItIS7GVZutkkUuhU8DQ@rO3m3g@I6TMhP0GbtxvT6Nw49@jL3bhNzJZHekdM61o2VA1FzV6x2yrOklZR1uQNp6SaKklRSQrJQZLXtJKj@gI "Tcl – Try It Online")
Explanation:
This implementation builds a dictionary consisting of a boolean flag for
each of the cards represented by the cartesian product of H D S C and
2-through-A. It reads the line from stdin, which if given as the spec
as called for, is actually a well formed Tcl list. As each card is read,
a boolean true is input in the dictionary for that card.
At the end a parser loops through the dictionary, and adds any card that
did not have a true in the dictionary to a list of missing cards. If the
missing cards list length is zero, output "No missing cards", otherwise
output the list of missing cards.
[Answer]
# [PHP](https://php.net/), 138 bytes
Ran with `-n` and `-d error_reporting=0`
I reuse some code from an [old submition](https://codegolf.stackexchange.com/a/166666/77963) i made that asked for create a deck of cards
**Code**
```
<?$r=[];foreach([A,J,Q,K,2,3,4,5,6,7,8,9,10]as$t)array_push($r,$t.H,$t.S,$t.D,$t.C);
echo join(" ", array_diff($r,explode(" ",$argv[1])));
```
[Try it online!](https://tio.run/##JYtBa4NAFAbv/RUfYQ8KL0VNGiM2FNk9iDmVPYoEiWu0FHd52tL@@W5jC8NchnGD8/75RfCpbvLesmmvQ1AXVNErnSmhHe3piQ6U0pEyiqOmncUStszt98V9zEMgmMTyWK7Sq9QqGeYP5jpYvNlxCjbYEP6Xbuz7dTFf7t125i@Jlm@fddyEYZh777MSRYlUYqcRRxpnhUojk0hKHO9IFHc0CoVUYa@QSFQKB/1j3TLaafbbyW87GGbLFzbO8jJOt1P0Cw "PHP – Try It Online")
**Explanation**
```
<?$r=[]; # Declare the array that will contain the full deck
# the next line will generate the arry with the full deck
foreach([A,J,Q,K,2,3,4,5,6,7,8,9,10]as$t)array_push($r,$t.H,$t.S,$t.D,$t.C);
# explode the input string on each blank space and using array_diff to get the
# different elements withing both arrays. (and "echo" of course)
echo join(" ", array_diff($r,explode(" ",$argv[1])));
```
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 197 bytes
Without LINQ.
```
s=>{var w="";for(var j=0;j<52;){var u="";int t=j%13;u=t<1?"K":t<2?"A":t<11?t+"":t<12?"J":"Q";t=j++/13;u+=t<1?"H":t<2?"D":t<3?"S":"C";w+=s.IndexOf(u)<0?u+" ":"";}return w==""?"No missing cards":w;};
```
[Try it online!](https://tio.run/##XZBfb4IwFMXf@RQnTZZA2JzgNqcFCYEsTPefhz0jVFOjZWmLbjF@dlZwT0tvcm77O6e5uaW6KmvJ2kZxsUb@ozTbUavcFkrhTdZrWeyOFvDVLLe8hNKFNrKveYXnggvb6SDw0IgyUFqaPy5x1hmWCFsVzo77QuIQEkJXtbS7yyYc0k1w61OnZ03HuNDQ4ebCG9Em1IEXkQWZ6sCPSNyp50XaJX1nnuZkSt4JNX7Xve4S7jmS/UXSTkcRyY0vIfTghmrwKCr2/bqyGycYRo1LYBihJ8l0I4WZzwwRkZcaO676VZSFrBSZHuiJttQ6L2aQ1ELVWzb4lFyzJy6YvbT/oQ9WVD1xHIda1smcdpIhzjBOMMrhDXMsUsxzTBL4Ge5NJYhN5YhTjFPcpPATzFPcGWeGXw "C# (.NET Core) – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 73 bytes
```
put keys((<<{^9+2}J Q K A>>X~ <C S D H>)∖get.words)||"No missing cards"
```
[Try it online!](https://tio.run/##DchNCoJAAIDRq3y4UoIoC00QYZhZDApBzKZVECUi/SiOEZG17gQdsItMwlu9tuzOkXPtredUPqzvp@lzl0zCV86GApFl2zepxKDQWfD7fKuyn96b7miDYfDWDZfa2vpacdiP5zmXaIQmliwM85mhUOSGRBJqViOJGBmEIlYsFaEkV0TmDw "Perl 6 – Try It Online")
Some pretty simple set subtraction between the deck of cards and the input.
[Answer]
# [Python 3](https://docs.python.org/3/), 102 bytes
```
lambda s:' '.join(i+j for i in[*'A23456789JQK','10']for j in'HDSC'if(i+j)not in s)or'No missing cards'
```
[Try it online!](https://tio.run/##FYs7D4IwGEX/yt0@qsbwkoeJA2kHAomJ6agOKEFLpCUUB389luRM95w7/ua30dHSnW7LpxkebQN7JNC@N0p7atujMxMUlL5uqAij@JCkWV5datpR4NN9tb2zVArJSXXrhWkzuwmWmYnOBoOyVukXns3UWlrGSenZc6Uev7PHGFvyEkWJlCOSCHyJWqCSyDnCEpmDo3BIFAKpQCwQclQCifwD "Python 3 – Try It Online")
] |
[Question]
[
*Note: This is the **cops'** thread, where one should post the scrambled code. Here is the **[robbers' thread](https://codegolf.stackexchange.com/questions/115034/robbers-square-times-square-root)*** where the cracked source should be posted and linked to the cop's answer.
---
**Task:** Write the shortest *safe* program which multiplies the square root of an integer ***n*** by the square of ***n***
This is [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'"), so the rules are:
* In your answer, post a scrambled version of your source code (the characters should be written in any order). The scrambled version **should not** work!
* You can take input in any standard way, the same goes for output. Hardcoding is forbidden
* After the code is cracked by the robbers (if this happens), you must mention that your code has been cracked in your title and add a ***[spoiler](https://meta.stackexchange.com/questions/1191/add-markdown-support-for-hidden-until-you-click-text-aka-spoilers)*** to your answer's body with your exact code
* The same applies to safe answers (mention that it's safe and add the ***[spoiler](https://meta.stackexchange.com/questions/1191/add-markdown-support-for-hidden-until-you-click-text-aka-spoilers)***)
* The code is considered *safe* if nobody has cracked it in 5 days after posting it and you can optionally specify that in the title
* You must specify your programming language
* You should specify your byte count
* You must state the rounding mechanism in your answer (see below)
---
You can assume that the result is lower than 232 and ***n*** is always positive. If the result is an integer, you must return the exact value with or without a decimal point; otherwise the minimum decimal precision will be 3 decimal places with any rounding mechanism of your choice, but can include more. **You must state the rounding mechanism in your answer.** You are not allowed to return as fractions (numerator, denominator pairs - sorry, Bash!)
### Examples:
```
In -> Out
4 -> 32.0 (or 32)
6 -> 88.18163074019441 (or 88.182 following the rules above)
9 -> 243.0
25 -> 3125.0
```
The shortest safe answer by the end of April will be considered the winner.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 35 bytes
```
ö£=s‰sr2xöR+RM0`.T"YVBYCDž„¨¨"6£H-L
```
This one took me a while to make.
There's some double quotes in there, so you can surround as much of the code as you want in them.
No rounding, decimal point precision.
[Answer]
# [Fireball](https://github.com/okx-code/Fireball), 8 bytes ([Cracked by Roman Gräf](https://codegolf.stackexchange.com/a/115197/34718))
```
♥1Z*^²/♥
```
Does not round, uses floating point precision.
Code surrounded with hearts ;)
Should pretty easy to crack, once you have a look into Fireball.
[Answer]
## C#, 112 bytes (cracked by [Emigna](https://codegolf.stackexchange.com/a/115178/67504))
```
((((())))),.....25;;;=CCLMMPPPRSWaaaaaaabbbccdddeeeeeeeeghiiiiiillllmnnnnnooooooorrrsssssssstttttuuvvwy{{}}
```
no rounding done
```
using System;
class P
{
static void Main()
{
var b=double.Parse(Console.ReadLine());
Console.Write(Math.Pow(b,2.5));
}
}
```
[Answer]
# [NO!](https://github.com/ValyrioCode/NO), 41 bytes (Cracked by [Emigna](https://codegolf.stackexchange.com/a/115386/66833))
NOOO! NO! can finally compete! ~~Although no-one will be bothered to crack this anyway :(~~
Anyway *sigh* here's the code:
```
NNNOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO??
nnno!
```
Full list of commands [here](https://github.com/ValyrioCode/NO/blob/master/Doc/List%20of%20Commands.md).
Coded in Python so uses Python rounding.
NOOOOOOOOO!!!!!!!! Someone cracked it. (Curse you Emigna!) (just kidding!)
[Answer]
## C, 115 bytes, ([Cracked by @tehtmi](https://codegolf.stackexchange.com/a/115477/44706))
```
""%&&((((((()))))))******++++,..//01122233388;;;;;;<====>> bbbdddeeeefffggillllllllllnnnnnnnnoooooooooooprrtuuu{}
```
Notice that it does include 3 spaces.
Always outputs 3 exact decimals, rounded to the closest thousandth.
Should be rather fun to crack as it doesn't involve any built-in to compute powers or square roots, as opposed to most (cracked) solutions so far.
Example run (which also gives you a few small hints):
```
int main() {
int n[] = {4, 6, 9, 25};
for (int i = 0; i < 4; i++) {
printf("%i => ", n[i]);
o(n[i]);
printf("\n");
}
}
```
outputs:
```
4 => 32.000
6 => 88.182
9 => 243.000
25 => 3125.000
```
Tested with both gcc and clang, with no compilation flag needed.
---
It's been cracked; the original solution was
```
o(double n){long o=2.303e18+(*(long*)&n>>1);double l=*(double*)&o;for(o=2;o++<8;)l=(l+n/l)/2;printf("%.3f",l*n*n);}
```
which uses a magic constant in the same spirit as [the infamous fast inverse square root algorithm](https://en.wikipedia.org/wiki/Fast_inverse_square_root#Overview_of_the_code) to do just a handful of Newton iterations (as opposed to several thousands in the cracked solution)
[Answer]
# 05AB1E, 23 bytes ([Cracked by Emigna](https://codegolf.stackexchange.com/questions/115034/robbers-square-times-square-root/115773#115773))
A totally different approach than my previous answers :)
```
$++/02;@DDDGHP\rrszz}¹ž
```
No rounding.
**Example runs**
```
In -> Out
0 -> 0
4 -> 32.0
6 -> 88.18163074019441
25 -> 3125.0
7131 -> 4294138928.8967724
```
[Answer]
## Excel VBA, 59 bytes (Safe)
```
?(())*..//11124AAAAFPSW[[]]^acceehiiiiklnnnnoooppqrrstttttu
```
No particular rounding.
Uses the Immediate Window.
[Answer]
# Octave, 42 bytes (Safe)
```
((((()))))+,,,-//01111111@[]^mnooorrssst~~
```
No rounding. Floating point accuracy.
### Intended solution
>
> `@(s)norm(roots([-1,~1,s^(10/(1+1))]),1/~1)`
>
>
>
>
> [Try it online!](https://tio.run/nexus/octave#@@@gUayZl1@Uq1GUn19SrBGta6hTZ6hTHKdhaKCvYahtqKkZq6ljqF9nqPk/Ma9Yw0zzPwA)
>
>
>
[Answer]
# Lua 5.3, 110 bytes (safe)
```
((((()))))**,,,,,-....=====>~ aaaaaaaaacddddeeeffhhhiiiiiiilllmmnnnnnnooopppppprrrrrrrsssssssstttt
```
Calculations are standard using Lua numbers (ie double in common implementations). Tested using PUC-Rio interpreter. (I hope I didn't do anything bad, but I think it is reasonable...)
This is a full program with input from the command line.
Original solution:
>
> `for a,r in pairs(math)do l,s=pcall(r,-math.pi)if s~=s and a>=(i or a)then i,p=a,r end end s=...print(s*s*p(s))`
>
>
>
Explanation:
>
> `math.sqrt` is retrieved from the math library by looping through the `math` table and looking for functions that return NaN (and don't throw an error) when applied to negative pi. There are only a few functions like this, and `sqrt` is alphabetically last.
>
>
>
[Answer]
# Javascript, 15 17 bytes, [Cracked by @Emigna](https://codegolf.stackexchange.com/questions/115034/robbers-square-times-square-root/116237#116237)
```
(x=>x****-125*10)
```
Solution:
>
> `x=>x**(25*10**-1)`
>
>
>
# Javascript, 18 bytes, Again, [Cracked.](https://codegolf.stackexchange.com/questions/115034/robbers-square-times-square-root/116240#116240)
```
x=>x**-(!3.5++)[];
```
Solution:
>
> `x=>x**(3-!+[]+.5);`
>
>
>
[Answer]
# JavaScript + [paper.js](http://paperjs.org), 210 bytes (safe)
This one's fun. No comments for you, and no strings either.
paper.js is a vector graphics framework. This is a full program that takes input via a prompt and outputs graphically, because it's possible. There is no rounding and floating-point accuracy (I think).
[Reference](http://paperjs.org/reference/global/)
[Try code here](http://sketch.paperjs.org)
```
Math.tan(prompt(a,0));
leg Rave, ew(0,0),ectoPlasm = Real new qrt(;
marvin atTax M(en) in vr;tent * hat.o = Mat
nottet near(0a,a) w cgee;
brown.cern(lantern) ;( w 0,0.art;vict.o brace
r=v=,h.c.)an=.flClr= Cor0)
```
Edit: Just noticed (my fault for not reading properly)
>
> The shortest safe answer by the end of April will be considered the winner.
>
>
>
Well, oops.
Original solution:
```
var a = prompt(0,0);
var r = new Rectangle(0,0,a,a).area;
var t = new Rectangle(0,0,Math.cbrt(a),Math.sqrt(Math.cbrt(a))).area;
var n = new PointText(view.center);
n.content = r * t;
n.fillColor = new Color(0);
```
[Try code here](http://sketch.paperjs.org)
[Answer]
# [HODOR](https://github.com/ValyrioCode/Hodor/blob/master/English/List%20of%20Commands.md), 172 bytes, [Cracked by Emigna](https://codegolf.stackexchange.com/a/115331/67716)
```
Walder
Hodor Hodor Hodor Hodor Hodor Hodor
Hodor Hodor Hodor Hodor Hodor
Hodor Hodor Hodor Hodor
Hodor Hodor Hodor
Hodor Hodor
Hodor
hodor hodor
HODOR HODOR!!!!!!!,,,,,,..?
```
let me know if I missed anything
[Answer]
# Python 3.6 - 15 bytes ([Cracked by Kritixi Lithos](https://codegolf.stackexchange.com/questions/115034/robbers-square-times-square-root/115065#115065))
```
axx 2*d:b.*5mal
```
Standard rounding precision of Python
[Answer]
# C++, 100 bytes ([Cracked by @fergusq](https://codegolf.stackexchange.com/a/115073/66323))
```
#.leiha2dm"
tuchn"crmueie<linaatt#dso
fameng pcae sli;t>dt nnsiuno;s mnpti;ouic(<){n(a;>w<n>n)co.,5}
```
Standard C++ rounding precision
[Answer]
# Python 2, 44 Bytes ([Cracked by @f…ôÀàn…õt…™k](https://codegolf.stackexchange.com/a/115076/64505))
```
np5w***i0(0(0r0n0t+iarn00p0)_(0tu00i50.0)) t
```
Has accuracy up to 10 decimal digits (I think). No rounding involved and there is a space involved.
[Answer]
# Scala, 19 bytes [(Cracked by @math\_junkie)](https://codegolf.stackexchange.com/a/115101/65425)
```
)>,/2(=addd.hmoptw5
```
This is a function of type `Int=>Double`.
[Answer]
# 05AB1E, 4 bytes ([Cracked by @Mr. Xcoder](https://codegolf.stackexchange.com/questions/115034/robbers-square-times-square-root/115106#115106))
Must be really easy to crack, but I'll still post it here
```
n*t¬π
```
Normal rounding
[Answer]
# C, 60 bytes ([Cracked by @Dave](https://codegolf.stackexchange.com/a/115113/61405))
```
1(root, flat*fat bern**lotr);pw(f{bus(--q.b4/q0*1-2)})(b>1)b
```
Standard C float accuracy.
[Answer]
# 05AB1E, 23 bytes (Cracked by [Emigna](https://codegolf.stackexchange.com/a/115247/67702))
Another try
```
A9n*¥="'q?:@->%t#[{¹!.
```
Normal rounding
[Answer]
# [HODOR](https://github.com/ValyrioCode/Hodor), 198 bytes [(Cracked by wwj)](https://codegolf.stackexchange.com/a/115292/66833)
*NB: Had to correct the code!*
Uses the brand-new `hodor` command (Updated Saturday)! Yes, I know I'm not supposed to say but it's pretty obvious anyway and (as far as I know) I'm the only person who can code in Hodor so worth some help :)
This is the code: and the full list of commands is [here](https://github.com/ValyrioCode/Hodor/blob/master/Docs/List%20of%20Commands.md)
```
H!HDHrlrHrhoooo!h, oo!do ordoH!oHHd
dodHrodorooooHdddoooOOo ddro roorrro.r,H
ooO ooHr,
HdHo oo H!O?Hd, oo,, Hdodhd oor, dd!HHrDo aod
rdroHdH,HrRr
o o RHrdHoo,oro Hr
oo
oHoer o r oddodo,rr
rdd!WrH d
```
[Answer]
# [Stacked](https://tio.run/nexus/stacked), 64 bytes
```
:u#{`E2t#tv',lnp~.iuP#2qr+t,'3m3em`,#9''.::mluls on\ts r:a\:+.S0
```
Good luck.
Result for `6`: `88.181630740194411535`.
[Answer]
# Javascript (ES6), 39 bytes ([Cracked](https://codegolf.stackexchange.com/a/115360/12474))
```
(((())))*....57===>Mabcefghlllloprttxxx
```
The rounding is normal floating point precision for Javascript.
[Answer]
# bash, 158 bytes
This program requires a 64 bit processor to function. Pass input number as argument; result on stdout. I believe rounding is floor function. This program actually does decimal output. If you got integer only keep trying.
```
^=======| -!
///////......
''(((((((((((())))))))))))
[]$$$$$$$$$****
\\\\\\
#++
000000000000
111111222
bcdddeeeehhhiill
nn
NNNNNNoooOOOOOOO
sssSSSS
tw
```
[Answer]
# Python 2.7, 174 bytes
```
_cc*gnta(dkree_rtrto._i9kuc_ l5_r_cctbimWka(Wihlkeu_5_eur_rri_keeluc4clrp ..u_)(HohhH)ap5o(trbnord_ir9/*in)_clrikroap.ie.tg_obkfkseeeel*in2Hkdu*ffmo4lWlrncde_22);doodt a49 hu
```
[Answer]
# 05AB1E, 15 bytes, ([Cracked by Emigna](https://codegolf.stackexchange.com/questions/115034/robbers-square-times-square-root/115767#115767))
```
+/01;DDDFMPs}¹ž
```
Normal rounding
**Example runs**
```
In -> Out
0 -> 0
4 -> 32.0
6 -> 88.18163074019441
25 -> 3125.0
7131 -> 4294138928.896773
```
[Answer]
## C#, 135 bytes (cracked by [SLuck49](https://codegolf.stackexchange.com/a/115809/67504))
```
(((((()))))),,-..../11;;;CCEILMMMPPPRRSSWaaaaaaacccdddeeeeeeeeggghiiiiiiiillllmmnnnnnnnnoooooooorrsssssssssssttttttttuuuvwyy{{}}
```
no rounding done
([First try](https://codegolf.stackexchange.com/a/115174/67504))
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 22 bytes, Cracked by [user4867444](https://codegolf.stackexchange.com/a/115760/47066)
```
+/;DDDFLPT_nz}©®¹¹¹Ïè›
```
**Example runs**
```
In -> Out
0 -> 0
4 -> 32.0
6 -> 88.18163074019441
```
**Original solution**
>
> `LnD¹›_Ï®©èTFD¹/z+;}¹DP`
>
>
>
[Answer]
# JavaScript (ES7), 24 bytes (Safe)
```
()+01488M``aabeiijlooqtv
```
Standard 64 bit floating point rounding.
---
### Solution
>
> `eval(atob`8j0+8ioqMi41`)`
>
>
>
### Tests
```
console.log(eval(atob`8j0+8ioqMi41`)(0)); // 0
console.log(eval(atob`8j0+8ioqMi41`)(1)); // 1
console.log(eval(atob`8j0+8ioqMi41`)(2)); // 5.656854249492381
console.log(eval(atob`8j0+8ioqMi41`)(4)); // 32
console.log(eval(atob`8j0+8ioqMi41`)(10)); // 316.22776601683796
```
[Answer]
# Javascript (ES7), 53 bytes (safe)
```
(((())))*++++,,,/0233346=====>>[[]]aaaabbbccelootttuv
```
The rounding is normal floating point precision for Javascript.
Tested this in the latest Chrome and FF.
---
### Solution
>
> `u=>(o=(t,c,a=o+c,b=a[t])=>eval(a[42]+b+b+3*30/t))(36)`
>
>
>
>
> This works because `a=o+c` is `'(t,c,a=o+c,b=a[t])=>eval(a[42]+b+b+3*30/t)undefined'`.
>
>
> So `a[42]='u', a[36]='*', 3*30/36=2.5`, making `eval('u**2.5')`.
>
>
>
### Tests
```
var f=u=>(o=(t,c,a=o+c,b=a[t])=>eval(a[42]+b+b+3*30/t))(36);
console.log(f(0)); // 0
console.log(f(1)); // 1
console.log(f(2)); // 5.656854249492381
console.log(f(4)); // 32
console.log(f(10)); // 316.22776601683796
```
[Answer]
# 05AB1E, 27 bytes - safe
Yet another totally different approach from my previous answers.
```
(/1DFFOOPT`ins}}©®¹¹Ðèëž‚‚‹
```
No rounding.
**Example runs**
```
In -> Out
0 -> 0
4 -> 32.0
6 -> 88.18163074019441
25 -> 3125.0
7131 -> 4294138928.896773
```
---
**Solution**
```
Ð(‚žFFDO©n¹‹i`T/ë1è®s}‚}O¹P
```
This is simply computing the square root with a trivial (and very dumb) trial-and-error strategy...
**Detailed explanation**
```
Ð(‚žFFDO©n¹‹i`T/ë1è®s}‚}O¹P
Ð(‚ # triplicate the input, reverse the sign of the last copy, and wrap the last 2 items in a list, which going forward is going to be the list of our current sqrt approximation and of the next decrement in our dumb search (so it starts at [x, -x])
žFF # 16384(!) times, do
D # duplicate the current [value, decrement] list
O© # compute the sum value + decrement, and also save it in the register
n # compute the square of that potential new approximation of the square root
¹‹ # and compare it with the input
i # if our new approximation is smaller than the actual square root, then
` # push the flattened [value, decrement] list to the stack as value, decrement
T/ # and divide our decrement by 10
ë # else (our new approximation is still bigger than the actual square root, then)
1è # extract the current decrement from the list
® # retrieve the new approximation from the register
s # and switch them to again have them in the value, decrement order
} # end of the if
‚Äö # no matter which branch of the if we went into, the last 2 items of the stack are now the new approximation and the new decrement, in order: wrap them in a list for the next loop iteration
} # end of the loop
O # replaces the output of the loop (the final [value, decrement] list) by its sum, which given the very small value of the decrement at that point is pretty much the same as our final approximation of sqrt(x)
¹ # push another copy of x; the stack is now [x, sqrt(x), x] (where the first x comes from the very first copy of the initial Ð)
P # computes the product of the whole stack
```
[Try it online!](https://tio.run/nexus/05ab1e#@394gsajhllH97m5ufgfWpl3aOejhp2ZCSH6h1cbHl5xaF1xLVC21v/QzoD//80A)
] |
[Question]
[
On most [new-years](/questions/tagged/new-years "show questions tagged 'new-years'") challenges when it is currently not the corresponding year of the challenge, It says this in the front.
>
> It's [current year] already, folks, go home.
>
>
>
You have to output this text with the current year substituted.
---
# I/O
**Input:** None.
**Output**: `It's [current year] already, folks, go home.`
[Answer]
# bash + date, 40 bytes
```
date +"It's %Y already, folks, go home."
```
[Try it online!](https://tio.run/nexus/bash#@5@SWJKqoK3kWaJerKAaqZCYU5SamFKpo5CWn5NdrKOQnq@QkZ@bqqf0/z8A "Bash – TIO Nexus")
[Answer]
# C (gcc), 58 bytes
```
f(){printf("It's%s already, folks, go home.",__DATE__+6);}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~21~~ 20 bytes
Saved a byte thanks to *Erik the Outgolfer*
```
žg“It's ÿˆ§,¹Ò,‚œ€¨.
```
[Try it online!](https://tio.run/nexus/05ab1e#ASUA2v//xb5n4oCcSXQncyDDv8uGwqcswrnDkizigJrFk@KCrMKoLv// "05AB1E – TIO Nexus")
[Answer]
# TeX (44 bytes)
```
It's \the\year\ already, folks, go home.\bye
```
[Answer]
# PHP, 42 bytes
```
It's <?=date(Y)?> already, folks, go home.
```
[Answer]
# Bash, 45 characters
```
printf "It's %(%Y)T already, folks, go home."
```
Bash's built-in `printf` in version 4.2 got the `%(fmt)T` format specifier and since version 4.3 it defaults to current timestamp in absence of argument.
Sample run:
```
bash-4.3$ printf "It's %(%Y)T already, folks, go home."
It's 2017 already, folks, go home.
```
[Answer]
## Batch, 45 bytes
```
@echo It's %date:~6% already, folks, go home.
```
Batch is actually reasonably competitive for once.
[Answer]
## Mathematica, 53 bytes
```
Print["It's ",Now[[1,1]]," already, folks, go home."]
```
[Answer]
# [Python 2](https://docs.python.org/2/), 67 bytes
```
import time
print"It's",time.gmtime()[0],"already, folks, go home."
```
[Try it online!](https://tio.run/nexus/python2#@5@ZW5BfVKJQkpmbylVQlJlXouRZol6spAMS0EvPBVEamtEGsTpKiTlFqYkplToKafk52cU6Cun5Chn5QEVK//8DAA "Python 2 – TIO Nexus")
[Answer]
# x86 machine code on DOS - 62 bytes
```
00000000 b4 04 cd 1a bf 23 01 88 c8 24 0f 00 05 4f c1 e9 |.....#...$...O..|
00000010 04 75 f4 ba 1b 01 b4 09 cd 21 c3 49 74 27 73 20 |.u.......!.It's |
00000020 30 30 30 30 20 61 6c 72 65 61 64 79 2c 20 66 6f |0000 already, fo|
00000030 6c 6b 73 2c 20 67 6f 20 68 6f 6d 65 2e 24 |lks, go home.$|
0000003e
```
Even though the input from the BIOS is in BCD (as opposed to the plain 16 bit value got from the equivalent DOS call), decoding it to ASCII turned out to be almost as long as base-10 printing a register. Oh well.
```
org 100h
section .text
start:
mov ah,4
int 1ah ; get the date from BIOS; cx now contains the year in packed BCD
mov di,placeholder ; put di on the last character of placeholder
lop:
mov al,cl
and al,0xf ; get the low nibble of cx
add [di],al ; add it to the digit
dec di ; previous character
shr cx,4 ; next nibble
jnz lop ; loop as long as we have digits to unpack in cx
mov dx,its
mov ah,9
int 21h ; print the whole string
ret
its:
db "It's 000"
placeholder:
db "0 already, folks, go home.$"
```
[Answer]
## Ruby, 52 bytes
```
puts"It's #{Time.now.year} already, folks, go home."
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 38 bytes
```
"It's "et0=" already, folks, go home."
```
[Try it online!](https://tio.run/nexus/cjam#@6/kWaJerKCUWmJgq6SQmFOUmphSqaOQlp@TXayjkJ6vkJGfm6qn9P8/AA "CJam – TIO Nexus")
[Answer]
# Mathematica, 58 bytes
```
"It's "<>ToString@#<>" already, folks, go home."&@@Date[]&
```
Anonymous function. Takes no input and returns a string as output. No, I'm not going to make a REPL submission, post it yourself if that one byte is so important.
[Answer]
# [Perl 6](https://perl6.org), ~~53~~ 51 bytes
```
say "It's {Date.today.year} already, folks, go home."
```
[Try it](https://tio.run/nexus/perl6#@1@cWKmg5FmiXqxQ7ZJYkqpXkp@SWKlXmZpYVKuQmFOUmphSqaOQlp@TXayjkJ6vkJGfm6qn9P8/AA "Perl 6 – TIO Nexus")
```
say "It's {now.Date.year} already, folks, go home."
```
[Try it](https://tio.run/nexus/perl6#@1@cWKmg5FmiXqxQnZdfrueSWJKqV5maWFSrkJhTlJqYUqmjkJafk12so5Cer5CRn5uqp/T/PwA "Perl 6 – TIO Nexus")
[Answer]
# TI-Basic (TI-84 Plus CE with OS 5.2+), 64 bytes
```
getDate
"It's "+toString(Ans(1))+" already, folks, go home.
```
TI-Basic is a tokenized language. Some commands (`getDate`, `toString(`, etc.), and all lowercase letters are two-bytes and everything else used here is one byte each.
Explanation:
```
getDate # 3, store {Y,M,D} in Ans
"It's "+toString(Ans(1))+" already, folks, go home. # 61, implicitly return required string with Y from getDate
```
# TI-Basic (TI-84 Plus CE with OS 5.1), 108 bytes
```
{0,1→L1
getDate
Ans(1)L1→L2
LinReg(ax+b) Y1
Equ►String(Y1,Str0
sub(Str0,1,length(Str0)-3→Str0
"It's "+Str0+" already, folks, go home.
```
TI-Basic is a tokenized language. The more complicated user variables (`Y1`, `L1`, `L2`, `Str0`), some commands (`LinReg(ax+b` , `getDate`, `sub(`, `Equ►String(`, `length(`), and all lowercase letters are two-bytes and everything else used here is one byte each.
OS 5.2 added a `toString(` command, which obsolesces about half of this submission, which is based off of [this algorithm](http://tibasicdev.wikidot.com/number-to-string).
Explanation:
```
{0,1→L1 # 8 bytes
getDate # 3 bytes, store {Y,M,D} list in Ans
Ans(1)L1→L2 # 10 bytes, multiply L1 by the year and store in L2
LinReg(ax+b) Y1 # 5 bytes, take a linear regression of the points specified by each pair of corresponding coordinates in L1 and L2 and store it in Y1
Equ►String(Y1,Str0 # 8 bytes, convert Y1 to a string
sub(Str0,1,length(Str0)-3→Str0 # 18 bytes, remove the "X+0" from LinReg
"It's "+Str0+" already, folks, go home. # 56 bytes, implicitly return the required output
```
[Answer]
# JavaScript ES6, 56 bytes
```
_=>`It's ${Date().split` `[3]} already, folks, go home.`
```
### Try it online!
```
const f = _=>`It's ${Date().split` `[3]} already, folks, go home.`
console.log(f())
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 31 bytes
```
`It's {Ki} alÎ%y, folks, go Êà.
```
[Try it online!](https://tio.run/nexus/japt#@5/gWaJerFDtnVmrkJhzuE@1UkchLT8nu1hHIT1f4XDX4QV6//8DAA "Japt – TIO Nexus")
[Answer]
## PowerShell 3.0, 44 bytes
```
"It's $(date|% y*) already, folks, go home."
```
PowerShell is competing quite well today!
[Answer]
# R, ~~62 59~~ 62 bytes
```
cat("It's",format(Sys.time(),"%Y"),"already, folks, go home.")
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~39~~ 27 bytes
```
`It's % ×ġ, ṗḊ, go λ∵.`kðt%
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJgSXQncyAlIMOXxKEsIOG5l+G4iiwgZ28gzrviiLUuYGvDsHQlIiwiIiwiIl0=)
Surely golfable?
[Answer]
# C#, 58 bytes
```
()=>"It's "+DateTime.Now.Year+" already, folks, go home.";
```
Anonymous function which returns the required string.
Full program:
```
using System;
public class Program
{
public static void Main()
{
Func<string> f=
()=>"It's "+DateTime.Now.Year+" already, folks, go home.";
Console.WriteLine(f());
}
}
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 38 bytes
```
s["It's ".d3" already, folks, go home.
```
[Online interpreter.](//pyth.herokuapp.com?code=s%5B%22It%27s+%22.d3%22+already%2C+folks%2C+go+home.)
[Answer]
# [Haskell](https://www.haskell.org/), 113 bytes
```
import Data.Time.Clock
f=do t<-getCurrentTime;putStr$"It's "++(fst.span(>'-').show)t++" already, folks, go home."
```
[Try it online!](https://tio.run/nexus/haskell#FcxBDoMgEADAe1@xISZoUD7Q2oteerYf2FRQIrAE1jR9PW3Pk0x1IVFmmJFRP10wevL0Oi52XAn4NmyGpzNnE/mP13TywrkRD5YFhFKtLaxLwtje5SA7XXZ6d6yUAPTZ4PrpwZI/Sg8bwU6/XtSALsIItn4B "Haskell – TIO Nexus") Replace `f` with `main` for a full program.
The function `getCurrentTime` returns a `UTCTime` object which looks something like `"2017-04-02 10:22:29.8550527 UTC"` when converted to a string by `show`. `fst.span(>'-')` takes the leading characters while they are larger than `'-'`, that is the current year. For the next 7972 years `take 4` would work for 8 bytes less, but we want our code to work correctly for ever and ever.
As far as I see build-in functions to get the current year require a `import Data.Time.Calendar`, so extracting the year from the string should be the shortest option.
[Answer]
# JavaScript, ~~77~~ ~~71~~ ~~67~~ 63 bytes
```
alert("It's "+Date().split(' ')[3]+" already, folks, go home.")
```
Thanks to @programmer5000 for the spaces!
# JavaScript ES6 ~~66~~ 60 bytes
```
alert(`It's ${Date().split` `[3]} already, folks, go home.`)
```
[Answer]
# [Befunge-98](https://github.com/catseye/FBBI), ~~57~~ 55 bytes
```
"emoh og ,sklof ,ydaerla@ s'tI"4k,y\4*:*/"&2"*+.f7+k,@
```
[Try it online!](https://tio.run/##S0pNK81LT9W1tPj/Xyk1Nz9DIT9dQac4Oyc/TUGnMiUxtSgn0UFEoVi9xFPJJFunMsZEy0pLX0nNSElLWy/NXDtbx@H/fwA "Befunge-98 (FBBI) – Try It Online")
Thanks to James Holderness for pointing out my mistake with the sysinfo instruction.
`"emoh og ,sklof ,ydaerla@ s'tI"` pushes the sentence to the stack where `4k,` prints the first word. `y` is the sysinfo instruction. When passed 20 (the unprintable in the string), it returns `256*256*(year-1900) + 256*month + day of month`. `\4*:*/"&2"*+.` takes just the year from the value and prints it and`f7+k,` prints the rest of the sentence.
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 48 bytes
```
"It's #{Time.new.year} already, folks, go home."
```
[Try it online!](https://tio.run/nexus/golfscript#@6/kWaJerKBcHZKZm6qXl1quV5maWFSrkJhTlJqYUqmjkJafk12so5Cer5CRD1Sh9P8/AA "GolfScript – TIO Nexus")
Yes, this is string interpolation.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 42 bytes
```
'It''s '1&Z'V' already, folks, go home.'&h
```
[Try it online!](https://tio.run/nexus/matl#@6/uWaKuXqygbqgWpR6mrpCYU5SamFKpo5CWn5NdrKOQnq@QkZ@bqqeulvH//9e8fN3kxOSMVAA "MATL – TIO Nexus")
```
'It''s ' % Push this string
1&Z' % Push current year
V % Convert to string
' already, folks, go home.' % Push this string
&h % Concatenate all stack contents horizontally
% Implicitly display
```
[Answer]
# Python 3, ~~73~~ 68 bytes
```
import time
print(time.strftime("It's %Y already, folks, go home."))
```
Very basic answer. The "%Y" gets the current year.
*Thanks to @ovs for removing 5 bytes*
[Answer]
## IBM/Lotus Notes Formula, 54 bytes
Not exactly challenging but here we go anyway...
```
"It's "+@Text(@Year(@Now))+" already, folks, go home."
```
[Answer]
**VBScript, 53 bytes**
```
msgbox"It's "&year(now())&" already, folks, go home."
```
] |
[Question]
[
## Challenge
Given two numbers, output their quotient. In other words, integer divide one number by another.
Both divisor/dividend will be under 10001. Division must be performed using integer division, rounding down.
Here are some example inputs and outputs:
```
5 1 5
-4 2 -2
4 -2 -2
6 2 3
16 4 4
36 9 4
15 2 7
17 3 5
43 5 8
500 5 100
500 100 5
10000 2 5000
```
Or as CSV:
```
5,1,5
-4,2,-2
4,-2,-2
6,2,3
16,4,4
36,9,4
15,2,7
17,3,5
43,5,8
500,5,100
500,100,5
10000,2,5000
```
## Rules
* Standard loopholes not allowed
* You must use integer division, not floating point division
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer wins, but will not be selected.
* The second input (denominator) will never be equal to `0`.
## Why?
I'm interested in seeing answers in esoteric languages, like Brainfuck and Retina. Answers in regular languages will be trivial, however I would really like to see answers in these languages.
I will be giving a bounty of **+50** reputation to a Retina answer.
[Answer]
# Mathematica, 8 bytes
```
Quotient
```
Thanks to @JungHwanMin for reminding me there's a builtin.
[Answer]
# JavaScript, 11 bytes
JavaScript doesn't have integers but using a [bitwise or](http://ecma262-5.com/ELS5_HTML.htm#Section_11.10) parses a float as a signed 32 bit integer.
```
a=>b=>a/b|0
```
# Try it online
```
const f = a=>b=>a/b|0
alert(f(prompt())(prompt()))
```
[Answer]
# C (GCC), 13 bytes
Doesn't work on *all* implementations, but that's OK.
```
f(a,b){a/=b;}
```
[Try it on TIO!](https://tio.run/nexus/c-gcc#@5@mkaiTpFmdqG@bZF37PzcxM09Ds7qgKDOvJE1DSTVFSSdNw9BUx0hTEygLAA "C (gcc) – TIO Nexus")
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 4 bytes
```
a//b
```
[Try it online!](https://tio.run/nexus/pip#@5@or5/0//9/Q/P/xgA "Pip – TIO Nexus")
Explanation:
```
A and B are read implicitly from the cmd line
a//b Calculate the int div of a and b (double slash == int div)
Results of the last expression are printed implicitly.
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 3 bytes
```
q~/
```
[Try it online!](https://tio.run/nexus/cjam#@19Yp///v7GZgiUA "CJam – TIO Nexus")
[Answer]
# [아희(Aheui)](http://esolangs.org/wiki/Aheui), 15 bytes
```
방방나망희
```
[Try it here! (please copy and paste the code manually)](http://jinoh.3owl.com/aheui/jsaheui_en.html)
[Answer]
# Python 2, ~~14~~ 11 bytes
```
int.__div__
```
[**Try it online**](https://tio.run/nexus/python2#S7ON@Z@ZV6IXH5@SWRYf/7@gCMhTSNMwMdax0PwPAA)
[Answer]
# Bash, ~~25~~ ~~22~~ 15 bytes
```
echo $(($1/$2))
```
Save to script, input numbers given at command line
Saved 3 bytes thanks to @betseg
[Answer]
# [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 8 bytes
```
::?a'\`b
```
# Explanation:
```
:: get a and b from the cmd line
? Print
a \ b the backslash does integer division, (opposed to the forward slash / for float div)
' ` however, the same symbol is used for ELSE. We need to escape it with ' and `
```
---
Note that the latest version of QBIC allows for an inline use of the `:` function, saving two bytes:
```
?:'\`:
```
[Answer]
# [Aceto](https://github.com/aceto/aceto), 6 bytes
```
riri/p
```
```
ri takes input as integer
/ does integer division
p prints it
```
[Try it online!](https://tio.run/##S0xOLcn//78osyhTv@D/f0NzLmMA "Aceto – Try It Online")
[Answer]
# PHP, 23 Bytes
```
<?=$argv[1]/$argv[2]^0;
```
or
```
<?=$argv[1]/$argv[2]|0;
```
and for 29 Bytes
```
<?=intdiv($argv[1],$argv[2]);
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 1 byte
```
:
```
[Try it online!](https://tio.run/nexus/jelly#@2/1//9/Q/P/xgA "Jelly – TIO Nexus")
[Answer]
# 05AB1E, 3 bytes
`II√∑`
[Try online](https://tio.run/nexus/05ab1e#@@/peXj7//@GBiDAZQQA)
If you can reverse the input, it would work in 1 byte: `√∑`
[Answer]
# [Triangular](https://github.com/aaronryank/triangular), 6 bytes
```
$.$%_<
```
[Try it online!](https://tio.run/##KynKTMxLL81JLPr/X0VPRTXe5v9/CwVdo/8A "Triangular – Try It Online")
Formats into this triangle:
```
$
. $
% _ <
```
Without directionals and no-ops, the code looks like this: `$$_%`
* `$` - read input as integer
* `_` - divide
* `%` - print
[Answer]
# [Decimal](//git.io/Decimal), 12 bytes
```
81D81D44D301
```
Ungolfed:
```
81D ; builtin 1 - read INT to stack
81D ; builtin 1 - read INT to stack
44D ; math divide (postfix /)
301 ; print from stack to output
```
[Try it online!](https://tio.run/##S0lNzsxNzPn/38LQBYhMTFyMDQz//7dUMAYA)
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 28 bytes
```
\d+
*
~`(_+) (_+)
K`$1$nC`$2
```
[Try it online!](https://tio.run/##K0otycxLNPz/PyZFm0uLqy5BI15bUwFEcHknqBiq5DknqBj9/29ppmAOAA "Retina – Try It Online")
I'm quite new to Retina; I probably could have golfed this more.
**Explanation:**
Let's start with an input: `38 4`
```
\d+
*
```
This turns the numbers into unary, so 4 is represented as \_\_\_\_, and 38 with 38 underscores.
```
~`...
```
This marks a stage that generates code to run afterwards
```
(_+) (_+)
K`$1$nC`$2
```
This is a replace stage to generate the division code; Firstly, it splits the string into the dividend (referenced as $1) and divisor (referenced as $2). Then, it returns the string:
```
K`{dividend as unary}
C`{divisor as unary}
```
The returned string is evaluated and the answer implicitly printed. It sets the working string to the dividend, and counts the matches of the divisor in it.
[Answer]
## [Keg](https://github.com/JonoCode9374/Keg/), 3 bytes
```
¬ø¬ø/
```
Simply 2 nice inputs and then divides them.
[TIO](https://tio.run/##y05N////0P5D@/X//zfkMgYA)
[Answer]
## Batch, 16 bytes
```
@cmd/cset/a%1/%2
```
`set/a` doesn't print its output inside a batch script, so we have to fake it out by starting a new copy of the command processor.
[Answer]
# GML, 30 bytes
```
return argument0 div argument1
```
[Answer]
# TI-Basic, 6 bytes
```
Input :iPart(X/Y
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki), ~~40~~ 38 bytes
```
\d+
*
(-?)(_+);(-?)(\2)*_*
$1$3$#4
--
```
Takes input in the format `denominator;numerator`. Also works for negative integers after the specs got changed, unlike the existing Retina answer.
-2 bytes thanks to *@FryAmTheEggman* thanks to a golf suggested in [another Retina answer of mine](https://codegolf.stackexchange.com/a/190623/52210).
[Try it online.](https://tio.run/##JYk7CsMwEET7uYYVkGQWdvXFbJHSlzA4gaRIkyLk/sqiTPHmDfN5fl/vu4yL32/jeKyI8HQN/lyDTjlSiGeEE5fdUkCEMUQrkpKtpMWsoag0bJqbLanIKh1VSzZUZgjzbDvZgq5bA012pb9b/QA)
**Explanation:**
Convert all numbers in the input to unary, replacing them with that amount of underscores:
```
\d+
*
```
Integer divide the two unary numbers (but with a decimal numbers as result), and filter all `-` to the front at the same time:
```
(-?)(_+);(-?)(\2)*_*
$1$3$#4
```
Remove any `--` if present:
```
--
```
[Answer]
# [J-uby](https://github.com/cyoce/J-uby), 2 bytes
ü´§
```
:/
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700K740qXLBIjfbpaUlaboWi6z0IYwVBQpu0RY6xrEQ7oIFEBoA)
[Answer]
## Ruby, 10 bytes
```
->i,j{i/j}
```
Extremely simple. Lambda function that returns the value `i/j`.
] |
[Question]
[
How many of you that still use your own knuckle to determine whether a month is having a full 31 days or less?
You job is to write a program to count how many months, in a month range, are having a full 31 days and how many are having less than 31 days by "counting the knuckles".
[![Counting days of month by knuckles](https://i.stack.imgur.com/QtCaU.png)](https://i.stack.imgur.com/QtCaU.png)
*Courtesy: amsi.org.au*
---
## Input
A pair of months, the first of which doesn't have to come chronologically before the second, given in any suitable format. For instance: `201703 201902` — March 2017 to February 2019. Please describe the input format you choose. Note that the input must be able to include all years from 1 to 9999. The range of months specified includes both the starting and ending months.
## Output
Two integers: the number of months in the given range with 31 days and the number of months in the range with less than 31 days.
Example: `14 10` — 14 knuckles, 10 grooves (it means that in that month range we have 14 months that have a full 31 days, and 10 months that have less than 31 days).
For an input where the second month in the range comes chronologically before the first, for example `201612 201611`, you have to output a pair of zero.
## Examples of input and output
```
| Input | Output |
|---------------|-------------|
| 201703 201902 | 14 10 |
| 201701 202008 | 26 18 |
| 000101 999912 | 69993 49995 |
| 201802 201803 | 1 1 |
| 201601 201601 | 1 0 |
| 201612 201611 | 0 0 |
```
## Rules
* You may choose any language you like
* One input per line
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins!
* The winner will be chosen in April 9
* Standard loopholes apply
* PS: this is my first question in PCG, it might have some inconsistencies. Feel free to edit and confirm what's unclear for you.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 21 bytes
```
ḅ12r/ị7RḂṁ12¤żC$S×⁼Ṣ$
```
Takes input like `[[y, m], [y, m]]`.
[Try it online!](https://tio.run/nexus/jelly#@/9wR6uhUZH@w93d5kEPdzQ93NloaHRoydE9zirBh6c/atzzcOcilf@H2x81rXH//z86OtrIwNBcR0HBOFZHAcS2BLKNYmN1uBTgUoYQKSMDINsCKqUAFIZJWQKBjoIhki4LsCEQAy3AhsOlzBAGQtnIUoZGCClDoFQsAA "Jelly – TIO Nexus")
### How it works
```
ḅ12r/ị7RḂṁ12¤żC$S×⁼Ṣ$ Main link. Argument: [[a, b], [c, d]]
ḅ12 Unbase 12; yield [x, y] := [ 12a + b, 12c + d].
r/ Reduce by range; yield [x, ..., y].
¤ Combine the five links to the left into a niladic chain.
7 Set the return value to 7.
R Range; yield [1, 2, 3, 4, 5, 6, 7].
Ḃ Bit; yield [1, 0, 1, 0, 1, 0, 1].
ṁ12 Mold 12; repeat the Booleans to create an array of length
12. Yields [1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1].
ị At-index; yield the elements of the array to the right at
the indices (1-based and modular) of the array to the left.
$ Combine the two links to the left into a monadic chain.
C Complement; map t -> 1-t over the array.
ż Zip the original array with the complements.
S Take the sum of each column.
$ Combine the two links to the left into a monadic chain.
Ṣ Sort [[a, b], [c, d]].
⁼ Compare the result with [[a, b], [c, d]], yielding 1 if
the input is sorted, 0 if not.
× Multiply the results to both sides.
```
[Answer]
## JavaScript (ES6), ~~70~~ ~~68~~ ~~67~~ 64 bytes
Takes input as two integers in `yyyymm` format, in currying syntax `(a)(b)`. Outputs an array of two integers `[knuckles, grooves]`.
```
a=>g=(b,c=d=0)=>a>b?[c,d-c]:g(--b,c+!((b%=100)>11||b/.87&!!++d))
```
### Formatted and commented
```
a => // main function: takes start date (a) as input / returns g
g = ( // recursive function g, which takes:
b, // - b = end date
c = d = 0 // - c = number of knuckles
) => // and also keeps track of: d = total number of months
a > b ? // if a is greater than b:
[ c, d - c ] // stop recursion and return the final result
: // else:
g( // do a recursive call to g():
--b, // - decrement the end date
c + // - increment the # of knuckles if
!( // both of these conditions are false:
(b %= 100) // - the end month (now stored in b in 0-based indexing)
> 11 || // is greater than 11
b / 0.87 & !!++d // - the number of days in this month is not 31
) // (at the same time, d is incremented if the first
) // condition is false)
```
### Test cases
**NB**: The third test case is not included in this snippet, because it won't work unless your browser has Tail Call Optimization enabled.
```
let f =
a=>g=(b,c=d=0)=>a>b?[c,d-c]:g(--b,c+!((b%=100)>11||b/.87&!!++d))
console.log(f(201703)(201902)); // 14 10
console.log(f(201701)(202008)); // 26 18
console.log(f(201802)(201803)); // 1 1
console.log(f(201601)(201601)); // 1 0
console.log(f(201612)(201611)); // 0 0
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~92~~ ~~90~~ ~~86~~ 80 bytes
```
lambda a,b,c,d:[(bin(2741)[2:]*(c+1-a))[b-1:-12+d or None].count(x)for x in'10']
```
[Try it online!](https://tio.run/nexus/python2#DchLCsIwEADQq8yuM3YiThDEgFfwAjGLfAwEdFJKhd4@9i1ffbzGJ35TiRA5cebiPKamaG9XIW9dOGGexUQin4w4I3Yu0Fd4dn2Hc@4/3XCneswOTSe5TGEsa9MNKgoL3w8slsYf "Python 2 – TIO Nexus")
6 more by converting to a lambda, with thanks to @math\_junkie for the idea. Now outputs a list containing the two numbers.
Previous non-lambda version (86 bytes)
```
a,b,c,d=input()
for x in'10':print(bin(2741)[2:]*(c+1-a))[b-1:-12+d or None].count(x),
```
[Try it online old!](https://tio.run/nexus/python2#DctBCoAgEEDRfadwl1NjNBJEQlfoAuIircDNGGHQ7c2/fr/s6DHgsUa@3yyhudIjPhG5pbE19xM5Sx9Z6nkisNq4Toae1A5gvSKjSPeHqMuW@HRDSG/1H2AphIRLDUn/ "Python 2 – TIO Nexus")
2 saved with thanks to @ovs for helping me get rid of the `len(k)`. I hadn't thought about using `None`.
Input is a list of integers in the format `y1,m1,y2,m2`
Some credit due to @KeerthanaPrabhakaran who got `bin(2741)[2:]` before I did which saves 1 byte over hard coding the binary string.
[Answer]
# [PHP](https://php.net/), ~~259~~ ~~256~~ ~~249~~ ~~248~~ ~~237~~ 221 bytes
Outgolfed by [aross](https://codegolf.stackexchange.com/users/38392/aross): <https://codegolf.stackexchange.com/a/114512/38505>
Input Format: `yyyymm,yyyymm`
```
$i=explode(",",fgets(STDIN));$_="DateTime::createFromFormat";foreach(new DatePeriod($_(Ym,$i[0]),new DateInterval(P1M),$_(Ym,$i[1])) as$f)date(t,mktime(0,0,0,$f->format(m),1,$f->format(y)))>30?++$x:++$y;
echo $x.' '.++$y;
```
[Try it online!](https://tio.run/nexus/php#TY1Bi8JADIXv/opSBkwwK1M9LNvaehHBgyKsF5Eipc3Yso5TxmG3/vruKCgSeEne@@DN5m3d9qJJuWvPpmIIKSR1YneF791itUFMxDENF4XjXaM5jkvL/l5ao5fG6sKFiTLeKmu48F9w57ZsG1OBOMJek2gOMkd6ZquLY/tbnGEbrZFeSJQjBsVVKKw8BI70j/NtIOk@Qn1k6lEGGil6/2@ImE3lfDQSXezllgy4rE0guvEwGI4fTt9PZPQpp@TXl5z8Aw)
---
### Older versions
```
$i=explode(",",fgets(STDIN));$_="DateTime::createFromFormat";$y=1;foreach(new DatePeriod($_("Ym",$i[0]),new DateInterval('P1M'),$_("Ym",$i[1])) as$f)date("t",mktime(0,0,0,$f->format("m"),1,$f->format("y")))==31?++$x:++$y;
echo $x.' '.$y;
```
[Try it online!](https://tio.run/nexus/php#VY5Na8MwDIbv@xVGGGJRr9jtYSyZ10sp9DIG7WWMUkIiN2F1HFyzJb8@c3bqEOjj0Svxvmz6pp94a2jor74mARKkvVC8icNxu39DLPjZwLaMdGwd5XkVKPW74N3OB1dGKPhodGF94lUjOvphs/idQutrwc8CPhxI3n6qE8p5s@8ihe/yev9q5ocY2u4iMs2c72KTobw71idEVt64xTpJBUSQ7ismQ0LJObh9fLV/fgQ4QKn/kREQ0Zi13iwWfMhTGosHqhrP@LDMWLZM8zStlH5Sa5nKs1r9Ag "PHP – TIO Nexus")
```
$i=explode(",",fgets(STDIN));$_="DateTime::createFromFormat";$y=1;foreach(new DatePeriod($_(Ym,$i[0]),DateInterval::createFromDateString('1 month'),$_(Ym,$i[1])) as$f)date(t,mktime(0,0,0,$f->format(m),1,$f->format(y)))>30?++$x:++$y;
echo $x.' '.$y;
```
[Try it online!](https://tio.run/nexus/php#VY5Na8MwDIbv@xVGGGJRr9jtYSyZ10sp9DIG7WWMUkIiN2F1HFyzJb8@c3bqEOjj0Svxvmz6pp94a2jor74mARKkvVC8icNxu39DLPjZwLaMdGwd5XkVKPW74N3OB1dGKPhodGF94lUjOvphs/idQutrwc8CPhxI3n6qE8p5s@8ihe/yev9q5ocY2u4iMs2c72KTobw71idEVt64xTpJBUSQ7ismQ0LJObh9fLV/fgQ4QKn/kREQ0Zi13iwWfMhTGosHqhrP@LDMWLZM8zStlH5Sa5nKs1r9Ag "PHP – TIO Nexus")
```
$i=explode(",",fgets(STDIN));$_="DateTime::createFromFormat";$y=1;foreach(new DatePeriod($_(Ym,$i[0]),DateInterval::createFromDateString('1 month'),$_(Ym,$i[1])) as$f)date(t,mktime(0,0,0,$f->format(m),1,$f->format(y)))==31?++$x:++$y;
echo $x.' '.$y;
```
[Try it online!](https://tio.run/nexus/php#VY5Na8MwDIbv@xVGGGJRr9jtYSyZ10sp9DIG7WWMUkIiN2F1HFyzJb8@c3bqEOjj0Svxvmz6pp94a2jor74mARKkvVC8icNxu39DLPjZwLaMdGwd5XkVKPW74N3OB1dGKPhodGF94lUjOvphs/idQutrwc8CPhxI3n6qE8p5s@8ihe/yev9q5ocY2u4iMs2c72KTobw71idEVt64xTpJBUSQ7ismQ0LJObh9fLV/fgQ4QKn/kREQ0Zi13iwWfMhTGosHqhrP@LDMWLZM8zStlH5Sa5nKs1r9Ag "PHP – TIO Nexus")
```
$i=explode(",",fgets(STDIN));$_="DateTime::createFromFormat";foreach(new DatePeriod($_("Ym",$i[0]),DateInterval::createFromDateString('1 month'),$_("Ym",$i[1])) as$f)date("t",mktime(0,0,0,$f->format("m"),1,$f->format("y")))==31?++$x:++$y;
echo $x.' '.++$y;
```
[Try it online!](https://tio.run/nexus/php#VY5Na8MwDIbv@xVGGGJRr9jtYSyZ10sp9DIG7WWMUkIiN2F1HFyzJb8@c3bqEOjj0Svxvmz6pp94a2jor74mARKkvVC8icNxu39DLPjZwLaMdGwd5XkVKPW74N3OB1dGKPhodGF94lUjOvphs/idQutrwc8CPhxI3n6qE8p5s@8ihe/yev9q5ocY2u4iMs2c72KTobw71idEVt64xTpJBUSQ7ismQ0LJObh9fLV/fgQ4QKn/kREQ0Zi13iwWfMhTGosHqhrP@LDMWLZM8zStlH5Sa5nKs1r9Ag "PHP – TIO Nexus")
```
$i=explode(",",fgets(STDIN));$_="DateTime::createFromFormat";$y=1;foreach(new DatePeriod($_("Ym",$i[0]),DateInterval::createFromDateString('1 month'),$_("Ym",$i[1])) as$f)date("t",mktime(0,0,0,$f->format("m"),1,$f->format("y")))==31?++$x:++$y;
echo $x.' '.$y;
```
[Try it online!](https://tio.run/nexus/php#VY5Na8MwDIbv@xVGGGJRr9jtYSyZ10sp9DIG7WWMUkIiN2F1HFyzJb8@c3bqEOjj0Svxvmz6pp94a2jor74mARKkvVC8icNxu39DLPjZwLaMdGwd5XkVKPW74N3OB1dGKPhodGF94lUjOvphs/idQutrwc8CPhxI3n6qE8p5s@8ihe/yev9q5ocY2u4iMs2c72KTobw71idEVt64xTpJBUSQ7ismQ0LJObh9fLV/fgQ4QKn/kREQ0Zi13iwWfMhTGosHqhrP@LDMWLZM8zStlH5Sa5nKs1r9Ag "PHP – TIO Nexus")
[Answer]
## Batch, 93 bytes
```
@set/ag=(y=%2/100-%1/100)*5+(x=%2%%100+6)*5/12-(w=%1%%100+5)*5/12,k=y*12+x-w-g
@echo %k% %g%
```
Accepts two parameters in ymm format (i.e. 101 - 999912). Previous 129-byte loop-based solution:
```
@set/al=%1-%1/100*88,u=%2-%2/100*88,k=g=0
@for /l %%i in (%l%,1,%u%)do @set/a"m=%%i%%12,k+=1451>>m&1,g+=2644>>m&1
@echo %k% %g%
```
[Answer]
# Python 3.5 (164 162 154 152 150 148 140 137 bytes)
```
n=int;a,b=input().split();t=k=0
for r in range(n(a[4:]),(n(b[:4])-n(a[:4]))*12+n(b[4:])+1):t+=1;k+=n('101010110101'[r%12-1])
print(k,t-k)
```
## [repl.it](https://repl.it/GmAM/2)
### takes input in the form of *yyyymm yyyymm*
### prints output as *number\_of\_knuckles number\_of\_grooves*
* **saved 2 bytes:** Thanks to [Cole](https://codegolf.stackexchange.com/users/42833/cole)
* **saved 8 bytes:** removed unwanted variables
* **saved 2 bytes:** reduced t=0;k=0 as t=k=0
* **saved 2 bytes:** Thanks to Cole (I had missed this before)
* **saved 2 bytes:** Thanks to [Keerthana](https://codegolf.stackexchange.com/users/67429/keerthana-prabhakaran)
* **saved 8 bytes:** removed unwanted variables
* **saved 3 bytes:** Thanks to [math\_junkie](https://codegolf.stackexchange.com/users/65425/math-junkie) ( split(' ') to split() )
[Answer]
# [Python 2](https://docs.python.org/2/), ~~147~~ ~~146~~ 142 bytes
```
def s(a,b):y=100;r=bin(2741)[2:];x=b/y-a/y;i=r*(x-1);return((0,0),map((i+r[a%y-1:]+r[:b%y]if i or x else r[a%y-1:b%y]).count,('1','0')))[a<=b]
```
[Try it online!](https://tio.run/nexus/python2#bY5BCsIwEEX3niIbaUZTnQlisTUnKV0kNWJA0xIrNAd3XaPiQnE27/P@X8x0sEd25VoYKKMixCoo4zyXxYaglmVTjcqsY67XsXIqLPiYE1TBDrfgOUeBIC6659wtQ63nMaeySak089i4I3OsC2xk9ny17NM/K1i13c0PgmeUiQwzAKj1Xplm6oPzQ3oIEQlJ7NKRhNlHS6QtSZFQIP1oFC986@KtE/6ucQfT3Xd5q9uTfQA "Python 2 – TIO Nexus")
* Saved 4 bytes - Thanks to @math\_junkie for suggesting the if-else clause with array lookup!
Breaking down the code,
```
def s(a,b):
y=100
r=bin(2741)[2:] #'101010110101'
x=b/y-a/y #to get the difference between the two years
i=r*(x-1)
return((0,0),map((i+r[a%y-1:]+r[:b%y]if i or x else r[a%y-1:b%y]).count,('1','0')))[a<=b]
```
[Answer]
# PHP, ~~120~~ ~~103~~ ~~97~~ 96 bytes
```
for($f=strtotime;$f($argv[2])>=$n=$f($argv[1].+$x++.month);)$k+=date(t,$n)>30;echo+$k,_,$x-1-$k;
```
Run like this:
```
php -nr 'for($f=strtotime;$f($argv[2])>=$n=$f($argv[1].+$x++.month);)$k+=date(t,$n)>30;echo+$k,_,$x-1-$k;' 0001-01 9999-12;echo
> 69993_49995
```
# Explanation
```
for(
$f=strtotime; # Alias strtotime function which is called twice.
$f($argv[2]) >= # Create end date timestamp. Iterate until the end
# date is reached.
$n=$f(
$argv[1].+$x++.month # Create timestamp from start date + X months.
);
)
$k+=date(t,$n) > 30; # If "t" of current date (days in month) is 31
# increment $k (knuckles).
echo+$k,_,$x-1-$k; # Compute grooves (iterations - $k) and output,
# implicit cast to int to account for 0 count.
```
# Tweaks
* Saved 17 bytes by using timestamp style instead of DateTime object style
* Saved 6 bytes by not assigning end date timestamp to variable `$e`, just compare directly
* Saved 1 byte by not keeping count of grooves, but just computing it after the loop
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 96 bytes
```
for($a,$b=[datetime[]]$args;$a-le$b;$a=$a.AddMonths(1)){$x++;$z+=$a.Month-in2,4,6,9,11};$x-$z;$z
```
[Try it online!](https://tio.run/nexus/powershell#@5@WX6ShkqijkmQbnZJYklqSmZsaHRurkliUXmytkqibk6qSBKRtVRL1HFNSfPPzSjKKNQw1NatVKrS1rVWqtEEyYGHdzDwjHRMdMx1LHUPDWmuVCl2VKqCC////GxgYGOoaGP63BAJdQyMA "PowerShell – TIO Nexus")
Takes input as form `2017-03`. Uses the built-in .NET date libraries and loops through from inputs `$a` to `$b`, each iteration incrementing `$x++` and adding to `$z` if the current `.Month` is `-in` `2,4,6,9,11` (i.e., a non-31-day month). Then we output our total months minus the non-31-day months `$x-$z`, and the non-31-day months `$z`.
Tosses an error on the `0001-01` to `9999-12` test case, because .NET only supports years up to `9999`, so the final `.AddMonths(1)` causes an overflow. Still outputs the correct values, though, because it's a non-terminating error; it just causes the loop to exit.
Probably would be shorter to do this arithmetically, like the Python or JavaScript answers, but I wanted to show an approach using the .NET built-ins.
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 113 bytes
```
s="$1-1";e="$2-1";sort <(while [ "$s" \< "$e" ];do s=$(date +%F -d"$s+1month");date +%d -d"$s-1day";done)|uniq -c
```
[Try it online!](https://tio.run/nexus/bash#LYtBCsIwEEWvMgwRWspAphQU0m69hLoonYEWNEETEcG7x5R29R6P/3Mc0DAxOi3SrhLDK0FffeblrnABNBHh2hcqws1JgDiYSsak0BzOQFIGDT@CTzPWbu@ydWIZv1g@Xuvf2y9PoCnn3Fo@ku1WnojtHw "Bash – TIO Nexus")
needs golfing...
takes input as `2016-03` `2018-10`
outputs:
```
1 28
7 30
12 31
```
ungolfed:
```
s="$1-1"
e="$2-1" # adds first day of month to the dates
sort <(
while [ "$s" \< "$e" ]; do #iterates over dates
s=$(date +%F -d"$s+1month") #adds one month to start date
date +%d -d"$s-1day" #outputs last day of previous month
done) | uniq -c #counts ocurrences of day number prevously sorted
```
[Answer]
# Swift, 151 bytes
```
let f={(m:[Int])->[Int] in var k=[0,0]
(m.min()!...m.max()!).map{$0%100}.filter{$0>0&&$0<13}.forEach{m in let n = m>7 ?m-7:m
k[(n%2+1)%2]+=1}
return k}
```
input is an array of two integers in the format as per the example
] |
[Question]
[
Usually, it is said that "Doing X without Y" can be a trap to beginners writing challenges ([source](http://meta.codegolf.stackexchange.com/questions/8047/things-to-avoid-when-writing-challenges/8079#8079)). However, I am cocky and think that I can *definitely* make an X without any Ys. Randomly. Oh yes, this will be good.
**Challenge:** Given an odd integer `n` greater than or equal to 1, output an ex of side length `n` made of random printable ascii characters sans "y" and "Y", and the space. All allowed characters must have a nonzero chance of occurring, but not necessarily uniform. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins. You should, however, randomize each char--that is, the struts of the ex shouldn't be equal, unless if by chance.
## The chars to appear
```
!#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXZ[\]^_`abcdefghijklmnopqrstuvwxz{|}~"
```
## Constructing the ex
Side length 1:
```
x
```
Side length 3:
```
x x
x
x x
```
Side length 5:
```
x x
x x
x
x x
x x
```
etc.
## Example outputs
```
input
output
empty line
3
h 2
^
9 5
1
:
5
D 1
W z
W
q j
W 1
```
## Example implementation
You do not need to handle invalid inputs.
```
function generate(sideLength){
var result = "";
var INNER = "@"
for(var i = 0; i < sideLength; i++){
var p = i < sideLength / 2 ? i : sideLength - i - 1;
result += " ".repeat(p) + ((sideLength / 2 | 0) == p ? "" : INNER) + " ".repeat(Math.max(sideLength - p * 2 - 2, 0)) + INNER + "\n";
}
return result.replace(RegExp(INNER, "g"), function(e){
let c = "y";
while(c === "y" || c === "Y"){
c = String.fromCharCode((Math.random() * 94) + 33 | 0);
}
return c;
});
}
function print(v){
output.innerHTML = "";
output.appendChild(document.createTextNode(v));
}
function update(){
var n = Number(input.value);
if(n !== Math.floor(n)) print("error: " + n + " is not an integer.");
else if(n % 2 === 0) print("error: " + n + " is not odd.");
else if(n < 1) print("error: " + n + "is less than one.");
else print(generate(n));
}
input.onchange = update;
update();
```
```
* {
font-family: Consolas, monospace;
}
#output {
white-space: pre;
}
```
```
<input id="input" min=1 value=1 type=Number>
<div id="output"></div>
```
[Answer]
# Ruby, 102 bytes
`Array#sample` doesn't do repetitions for sampling from the character set, but that's OK because the character distribution don't have to be perfectly uniform! Recursive function, returns an array of lines.
[Try it online!](https://repl.it/CgUD)
```
f=->l{w,x,y,z=([*?!..?~]-%w"y Y").sample 4
l<2?[w]:[w+(s=' '*(l-2))+x,*f[l-2].map{|e|" #{e} "},y+s+z]}
```
[Answer]
# Mathematica, 146 bytes
```
a:=RandomChoice[33~CharacterRange~126~Complement~{"Y","y"}];StringRiffle[Normal@SparseArray[{{b_, b_}:>a,{b_,c_}/;c-1==#-b:>a},{#,#}," "],"
",""]&
```
Anonymous function. Takes a number as input, and returns a string as output.
[Answer]
## Actually, 62 bytes
```
"!⌂"♂┘ix♂c"Yy"@-╗½≈u;r2@∙`i=`M╪k`;dXR@+`M;dXR@+`"╜J' aI"£MΣ`Mi
```
This is one of the longest Actually programs I've ever written.
[Try it online!](http://actually.tryitonline.net/#code=IiHijIIi4pmC4pSYaXjimYJjIll5IkAt4pWXwr3iiYh1O3IyQOKImWBpPWBN4pWqa2A7ZFhSQCtgTTtkWFJAK2Ai4pWcSicgYUkiwqNNzqNgTWk&input=NQ)
### Explanation:
**Part 1**: setting up the character list
```
"!⌂"♂┘ix♂c"Yy"@-
"!⌂" push the string "!⌂"
♂┘ CP437 ordinal of each character ([21, 127])
ix range(21, 127)
♂c character at each ordinal (list of printable ASCII characters)
"Yy"@- set difference with ["Y", "y"] (printable ASCII except "Y" and "y")
```
[Try it online!](http://actually.tryitonline.net/#code=IiHijIIi4pmC4pSYaXjimYJjIll5IkAt&input=)
**Part 2**: constructing the boolean array for an X
```
½≈u;r2@∙`i=`M╪k`;dXR@+`M;dXR@+
½≈u; two copies of int(input/2)+1
r range
2@∙ Cartesian product with itself
`i=`M for each sublist: push 1 if both elements are equal, else 0
╪k split into int(input/2)+1-length chunks
(at this point, we have one quarter of the X)
`;dXR@+`M mirror each sublist (one half of the X)
;dXR@+ mirror the entire list (the whole X)
```
[Try it online!](http://actually.tryitonline.net/#code=wr3iiYh1O3IyQOKImWBpPWBN4pWqa2A7ZFhSQCtgTTtkWFJAKw&input=NQ)
**Part 3**: picking random characters
```
`"╜J' aI"£MΣ`Mi
`"╜J' aI"£MΣ`M for each row:
"╜J' aI"£M for each column:
╜J push a random value from the character list
' push a space
a invert the stack
I take the character if the value is 1, else take the space
Σ concatenate the strings
i flatten the list and let implicit output take care of the rest
```
[Try it online!](http://actually.tryitonline.net/#code=IiHijIIi4pmC4pSYaXjimYJjIll5IkAt4pWXYCLilZxKJyBhSSLCo03Oo2BNaQ&input=W1sxLDAsMCwwLDFdLFswLDEsMCwxLDBdLFswLDAsMSwwLDBdLFswLDEsMCwxLDBdLFsxLDAsMCwwLDFdXQ)
[Answer]
# Python, ~~142~~ ~~139~~ 135 bytes
This is a straight forward implementation create the square character by character. If the character is *on a diagonal*: use a random char, *else*: use a space. This also uses a regex substitution and random int to generate non-`Y` characters:
```
import re,random
lambda x:''.join('\n'*(i%x<1)+re.sub("y|Y","t",chr(random.randint(33,126))+' ')[i%x!=i/x!=x-i%x-1]for i in range(x*x))
```
---
## Explanation [ Old ]
```
"\n".join( ... for i in range(x)) # Create 'x' lines
''.join( ... for j in range(x)) # Create 'x' chars on each line
(...)[j!=i!=x-j-1] # Not on diagonals? 2nd char in "? "; Else, choose the 1st
j!=i # Not on downward diagonal
i!=x-j-1 # Not on upward diagonal
re.sub("y|Y","t", ... ) # Replace y or Y for t
chr(random.randint(33,126))+' ' # Random char + a space
```
**Update**
* **-4** [16-07-30] Shortened newline conditional
* **-3** [16-07-30] Changed to single for-loop
* **-6** [16-07-29] Exchanged if statement for ternary op. Thanks to @RootTwo
* **-11** [16-07-27] Removed extra brackets/spaces and flipped if statement
* **-49** [16-07-27] Absorded @squeamishossifrage's method by creating the square step-by-step, Thanks!
* **-10** [16-07-27] Shorten random char lambda + math stuff from @ConorO'Brien
* **-22** [16-07-26] Squeaze in a lambda + misc golfing
* **-6** [16-07-26] `import*` - Thanks to @KevinLau
[Answer]
# Python 2, 171 bytes
```
from random import*
def x(n):
w=range(-n/2+1,n/2+1)
for i in w:
o=''
for j in w:c=randint(33,124);c+=(c>88)+(c>119);c=[c,32][bool(i^j and i^-j)];o+=chr(c)
print o
```
Guaranteed to choose random characters with uniform probability.
Try it out here: [ideone link](http://ideone.com/AUKacR)
**EDIT: Thanks to Morgan Thrapp for the corrections.**
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), 35 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319)
```
⎕UCS 32+(⊢+∊∘57 89)⌊?95×(⊢∨⌽)∘.=⍨⍳⎕
```
`⎕` prompt for number
`⍳` 1 through that number
`∘.=⍨` equality table (i.e. the diagonal has 1s)
`(⊢∨⌽)` itself OR its mirror image (gives both diagonals)
`95×` multiply by 95
`?` rand int between 1 and 95 for the diagonals, rand float between 0 and 1 for the rest
`⌊` floor to get rid of the floats
`(⊢+∊∘57 89)` add one to the elements that are a member of {57,89} (Yy – 32)
`32+` add 32 to make the 0s into spaces, and other numbers into the proper range
`⎕UCS` convert to text
[TryAPL](http://tryapl.org/?a=%u2395UCS%2032+%28%u22A2+%u220A%u221857%2089%29%u230A%3F95%D7%28%u22A2%u2228%u233D%29%u2218.%3D%u2368%u237325&run)!
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~28~~ ~~27~~ ~~26~~ 25 bytes
```
~~jmuXGHO-rF"!~""Yy"{,d-tQd\*;Q~~
~~VQuXGHO-rF"!~""Yy"{,N-tQN\*d~~
~~VQuXGHO-r\!\~"Yy"{,N-tQN\*d~~
~~VQuXGHO-r\!\~"Yy",N-tQN\*d~~
VQuXGHO-r\!\[DEL];"Yy",N-tQN*d
```
[Try it online!](https://tio.run/##K6gsyfj/PyywNMLdw1@3KEYxpl4pslJJx0@3JNBPK@X/f1MA "Pyth – Try It Online")
[Answer]
# x86 machine code, 70 bytes
```
60 89 d7 31 db 43 88 ce b2 fe 49 d1 e1 87 da 0f
c7 f0 24 7f 3c 22 72 f7 48 3c 79 74 f2 3c 59 74
ee aa 49 7c 1c 00 df 79 06 86 f7 42 43 eb f6 f6
c3 01 74 03 b0 0a aa 51 88 f9 b0 20 f3 aa 59 eb
cc c6 07 00 61 c3
```
My executable code, disassembled:
```
0000003d <myheh>:
3d: 60 pusha
3e: 89 d7 mov %edx,%edi
40: 31 db xor %ebx,%ebx
42: 43 inc %ebx
43: 88 ce mov %cl,%dh
45: b2 fe mov $0xfe,%dl
47: 49 dec %ecx
48: d1 e1 shl %ecx
0000004a <myloop>:
4a: 87 da xchg %ebx,%edx
0000004c <myrand>:
4c: 0f c7 f0 rdrand %eax
4f: 24 7f and $0x7f,%al
51: 3c 22 cmp $0x22,%al
53: 72 f7 jb 4c <myrand>
55: 48 dec %eax
56: 3c 79 cmp $0x79,%al
58: 74 f2 je 4c <myrand>
5a: 3c 59 cmp $0x59,%al
5c: 74 ee je 4c <myrand>
5e: aa stos %al,%es:(%edi)
5f: 49 dec %ecx
60: 7c 1c jl 7e <mydone>
00000062 <mylab>:
62: 00 df add %bl,%bh
64: 79 06 jns 6c <myprint>
66: 86 f7 xchg %dh,%bh
68: 42 inc %edx
69: 43 inc %ebx
6a: eb f6 jmp 62 <mylab>
0000006c <myprint>:
6c: f6 c3 01 test $0x1,%bl
6f: 74 03 je 74 <myprint1>
71: b0 0a mov $0xa,%al
73: aa stos %al,%es:(%edi)
00000074 <myprint1>:
74: 51 push %ecx
75: 88 f9 mov %bh,%cl
77: b0 20 mov $0x20,%al
79: f3 aa rep stos %al,%es:(%edi)
7b: 59 pop %ecx
7c: eb cc jmp 4a <myloop>
0000007e <mydone>:
7e: c6 07 00 movb $0x0,(%edi)
81: 61 popa
82: c3 ret
```
It is a function that receives the size of the X in ecx, and a pointer to the output buffer in edx.
It fills the output buffer sequentially with bytes. There are `2 * n - 1` iterations (equal to the number of non-space characters to output). At each iteration, it does the following:
* Generate a random number
* Fiddle with the number to fit it into range; if it's bad, go back and generate anew
* Print the random character
* Print a newline (every other iteration)
* Print the proper number of spaces
Conversion from a random number to a random character is not remarkable:
```
myrand:
rdrand eax;
and al, 7fh;
cmp al, 22h;
jb myrand;
dec eax;
cmp al, 'y';
je myrand;
cmp al, 'Y';
je myrand;
```
The interesting part is the calculation of the number of spaces. It must generate the following numbers (example for N=9):
```
7 1
5 2
3 3
1 4
3
1 2
3 1
5 0
7
```
The numbers are taken alternatingly from two arithmetic progressions. The first one goes down with step -2, and the second one goes up with step 1. When the first progression arrives at -1 (in the middle of the X), there is a glitch (-1 is removed), and then the progressions change direction.
The progressions are stored in registers `ebx` and `edx` - the high parts `bh` and `dh` store the current number, and the low parts `bl` and `dl` store the step. To alternate between the progressions, the code swaps the registers with `xchg`.
When the progression arrives at -1 (around the `mylab` label), it increases both registers, switching the steps from `-2, 1` to `-1, 2`. This also changes the roles of the registers, so then it swaps the high parts of the registers.
At the end of the function, it stores a zero byte to indicate an end of string.
[Answer]
# Python 2.7, 205 bytes:
```
from random import*;C=input()/2;S=' ';R=range;Z=lambda:chr(choice(R(33,89)+R(90,121)+R(122,128)));T=lambda*G:''.join([S*i+Z()+S*(2*(~-C-i)+1)+Z()+S*i+'\n'for i in R(*G)]);print T(C)+S*C+Z()+'\n'+T(~-C,-1,-1)
```
[Try It Online! (Ideone)](http://ideone.com/hhB4qm)
[Answer]
# [MATL](https://github.com/lmendo/MATL), 28 bytes
```
6Y2'Yy 'X-iZr1MZrXdwXdP2$X>c
```
[**Try it online!**](http://matl.tryitonline.net/#code=NlkyJ1l5ICdYLWlacjFNWnJYZHdYZFAyJFg-Yw&input=OQ)
All the allowed characters have the same probability of appearing. Works for even input too.
```
6Y2 % Predefined literal of ASCII chars from 32 to 126
'Yy ' % Not allowed chars
X- % Set difference. Produces the set of allowed chars
i % Input number, n
Zr % Random sample without replacement. Gives a string with n chars taken from
% the allowed set
1MZr % Do the same
Xd % Diagonal matrix. Zeros will be displayed as spaces
wXd % Diagonal matrix with the other string
P % Flip vertically
2$X> % Maximum of the two matrices
c % Convert to char. Implicitly display
```
[Answer]
# C, 154 bytes (or 119 without the boiler-plate)
```
o(w,c){c=rand()%94+33;printf("%*c",w,w?c+!(c&95^89):10);}main(h){scanf("%d",&h);srand(time(0));for(int n=h,p;n--;)p=abs(h/2-n),o(h/2-p+1),p&&o(p*2),o(0);}
```
Or 119 bytes as a function `X(h)` with `srand(time(0))` taken care of elsewhere:
```
o(w,c){c=rand()%94+33;printf("%*c",w,w?c+!(c&95^89):10);}X(h,n,p){for(n=h;n--;)p=abs(h/2-n),o(h/2-p+1),p&&o(p*2),o(0);}
```
Breakdown:
```
o(w,c){ // "Output" function, for all printing
c=rand()%94+33; // Generate random char, whether we need it or not
printf("%*c", // Print a char with some number of leading spaces
w, // Use "w" (width) - 1 leading spaces
w? // Either print the random char...
c+!(c&95^89) // (exclude "y" and "Y" by incrementing to "z"/"Z")
:10 // ...or print a newline if called with w = 0
);
}
main(h){ // Main function; repurpose argc to store grid size
scanf("%d",&h); // Get grid size from stdin
srand(time(0)); // Boiler-plate for random number seeding
for(int n=h,p;n--;) // Loop over all lines (count down to save chars)
p=abs(h/2-n), // Calculate half-distance between "X" bars
o(h/2-p+1), // Output the first half of the "X" (">")
p&& // If we are not in the centre:
o(p*2), // output the second half of the "X" ("<")
o(0); // Output a newline
}
```
[Answer]
## Lua, 277 Bytes
Well... Lua is sooooo good at manipulating strings :D. First time I had to use `local` in a statement! I could save some bytes by using Lua 5.1 instead of 5.3 because they moved the global function `unpack` into the object `table` at Lua 5.2. But I prefer to stick with the latest version I have :).
Defines a function that should be called with a single parameter (the second one is used for recursion purpose) and returns a string.
```
function f(n,N)N=N or n e=" "p="\n"r=math.random C=e.char
R={}for i=1,4 do x=r(33,126)R[i]=x~=89 and x~=121 and x or r(33,88)end
local s,S,a,b,c,d=e:rep((N-n)/2),e:rep(n-2),table.unpack(R)return
n<2 and s..C(a)..p or s..C(a)..S..C(b)..s..p..f(n-2,N)..s..C(c)..S..C(d)..s..p
end
```
### Ungolfed
```
function f(n,N)
N=N or n -- N is equal to the n we had on the first call
e=" " -- shorthand for the space
p="\n" -- shorthand for the newline
r=math.random -- shorthand for math.random
C=e.char -- uses the string e to obtain the function string.char
R={} -- define an array for our random values
for i=1,4 -- iterate 4 times (for the random characters)
do
x=r(33,126) -- random between ASCII "!" and "~"
R[i]=x~=89 and x~=121 -- if we didn't pick y or Y
and x -- keep this number
or r(33,88) -- or roll for a character between "!" and "X"
end
local s,S -- these variables have to be local
,a,b,c,d -- or the recursion would change them
=e:rep((N-n)/2),e:rep(n-2) -- s and S are the number of spaces for the X
,table.unpack(R) -- a,b,c and d are the 4 random characters
return n<2 -- if n==1
and s..C(a)..p -- we're at the center of the X, time to end recursion
or -- else
s..C(a)..S..C(b)..s..p -- concatenate the topmost line for n
..f(n-2,N) -- with the inner X
..s..C(c)..S..C(d)..s..p -- and the bottom line
end
```
[Answer]
## JavaScript (ES6), ~~137~~ ~~131~~ 125 bytes
```
n=>[...Array(n)].map((_,i,a)=>String.fromCharCode(...a.map((r=Math.random()*94,j)=>i-j&&i+j+1-n?32:(r+72&95&&r)+33))).join`\n`
```
Where `\n` represents the literal newline character. Edit: Saved 1 byte by moving the `' '` inside the `String.fromCharCode` expression. Saved 5 bytes by making my random character generation non-uniform; the expression `r+72&95` is zero for the values that map to `Y` and `y` and an `!` is generated in their place. Saved 4 bytes when I realised that spreading over `String.fromCharCode` avoids having to `join`. Saved 2 bytes by stealing a trick from @edc65.
[Answer]
# PowerShell v2+, 112 bytes
```
Param($i)function f{Random(33..126-ne121-ne89|%{[char]$_})};1..$i|%{$a=,' '*$i;$a[$_-1]=f;$a[$i-$_]=f;$a-join''}
```
Reads input off the command line.
For each line, an array of spaces is created, the correct indices filled in with characters pulled from function `f`, then the char array is joined to output as one line.
[Answer]
# [Matricks](https://github.com/jediguy13/Matricks/tree/master), 79 bytes (non-competing)
Matricks **excels** as the beginning of making the x and all the random values, but flops when it comes to conditionals...
I marked this as noncompeting because I had to fix a few bugs and get all the new features working after this challenge was posted.
```
m:n;:1;mr=c:L:L;k({}|{X;})*{m_?33:126;;:L:l;miC<121,89>:gr:c;;:49:gr:c;;:L:l;};
```
Run with `python matricks.py x.txt [[]] <input> --asciiprint`
Explanation:
```
m:n;:1;mr=c:L:L; #Initialize matrix to be a square with
#a diagonal of 1s
k...; #Set the output to...
({}|{X;})* #The boolean x matrix multiplied by...
{m_?33:126;;:L:l; #A bunch of random characters
miC<121,89>:gr:c;;:49:gr:c;;:L:l;} #But make sure they are not y or Y
```
This also supports even numbers.
[Answer]
## MATLAB, 86 bytes
```
a=@(n)(char(changem(randi(92,n),33+[0:55 57:87 89:93],1:92).*(eye(n)|fliplr(eye(n)))))
```
Some examples:
```
>> a(1)
ans =
i
>> a(3)
ans =
~ {
Z
* ^
>>a(5)
ans =
k E
| M
}
] s
b t
>> a(10)
ans =
Q k
+ a
j w
X [
rO
%3
P d
K q
r &
? v
```
[Answer]
# SmileBASIC, 97 bytes
```
INPUT S
FOR X=1TO S
FOR Y=1TO S
Q=RND(93)+33?CHR$((Q+!(Q-121&&Q-89))*(X==Y||X+Y==S+1));
NEXT?NEXT
```
Instead of having to calculate the number of spaces between each character or something, I decided to just print in all locations where `X==Y` or `X+Y==Size+1`.
The random character generator just adds 1 if it generates `y` or `Y`, so `z` and `Z` are slightly more common than usual.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 33 bytes
32 bytes of code, +1 for `-l` flag. Strangely enough, the code begins with `Y` and ends with `y`...
```
Ya{$=a|$+a=y-1?RCPARM-`y`s}MMCGy
```
Takes input as a command-line argument. [Try it online!](https://tio.run/nexus/pip#@x@ZWK1im1ijop1oW6lraB/kHOAY5KubUJlQXOvr6@xe@f//f92c/0amX/PydZMTkzNSAQ "Pip – TIO Nexus")
### Explanation
Constructs a grid of the appropriate size; replaces elements on the diagonals with a random non-y character, and all other elements with space.
```
a is 1st cmdline arg; PA is printable ASCII characters;
s is space (implicit)
Ya Yank a into y (global var, accessible within functions)
CGy y by y coordinate grid
{ }MM To each coordinate pair, map this function:
$=a Fold on equality (true if both elements are equal)
| Logical OR
$+a Fold on +
=y-1 and test if equal to size - 1
? If the preceding expression is true, then:
PARM From printable ASCII chars, remove
-`y` regex matching y, case-insensitive
RC Take a random choice from the resulting string
s Else, space
The whole expression returns a nested list, which is
autoprinted as lines of concatenated items (-l flag)
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), ~~25~~ 22 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
A much messier approach that somehow worked out shorter than the original. The need for the `j1` is annoying me but [this](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=O8YyxkXFa9X2w8f5tFVhWMOsw/s&input=NQ) is the closest I can get otherwise, without tanking my score (the middle line is wrong).
```
;Æ2ÆEÅkÕöÃqSp´UaX¹j1Ãû
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=O8YyxkXFa9X2w3FTcLRVYVi5ajHD%2bw&input=NQ)
```
;Æ2ÆEÅkÕöÃqSp´UaX¹j1Ãû :Implicit input of integer U
Æ :Map each X in the range [0,U)
2Æ : Map the range [0,2)
; E : ASCII
Å : Slice off the first character (space)
k : Case insensitively remove
Õ : "y"
ö : Random character
à : End map
q : Join with
S : Space
p : Repeat
´U : Prefix decrement U
aX : Absolute difference with X
¹ : End join
j1 : Remove character at 0-based index 1
à :End map
û :Centre pad each element with spaces to the length of the longest
:Implicit output joined with newlines
```
## Original (w/o flag), 25 bytes
```
;z ôÈç iÕêÃÔê û ·ry@EÅkÕö
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=O3og9MjnIGnV6sPU6iD7ILdyeUBFxWvV9g&input=NQ)
```
;z ôÈç iÕêÃÔê û ·ry@EÅkÕö :Implicit input of integer
z :Floor divide by 2
ô :Range [0,result]
È :Map each X
ç : X spaces
i : Prepend
Õ : "y"
ê : Palindromise
à :End map
Ô :Reverse
ê :Palindromise
û :Centre pad each element with spaces to the length of the longest
· :Join with newlines
ry :Replace "y"s
@ : Pass each match through the following function
; EÅkÕö : As above
```
[Answer]
# Zsh, 115 ~~122~~ ~~130~~ bytes
```
for i ({1..$1}){for j ({1..$1}){x=$[(i==j)|(j+i==$1+1)?RANDOM%93+33:32]
echo -n ${${(#)x==45?89:x}/[yY]/\-}};echo}
```
* `i` & `j` iterate over the rows & columns.
* If we're on the **X**, set `x` to to a random ascii-value in the valid range, otherwise `32` [space].
* Convert ascii-value to text. Switch "-" character (45) to a "Y" (89) if found (necessary to avoid a bug). Change "y" or "Y" to hyphen char "-", and print
[try it online!](https://tio.run/##qyrO@J@moVnNlZqcka@QZ6tiaPU/Lb9IIVNBo9pQT0/FsFazGsTPQuJX2KpEa2Ta2mZp1mhkaQMZKobahpr2QY5@Lv6@qpbG2sbGVsZGsRAjdfMUVKpVqjWUNStsbU1M7S0srSpq9aMrI2P1Y3Tra2utQapq/4NIrlquNAVjIDYEYTBh/h8A)
~~[122 bytes](https://tio.run/##qyrO@J@moVnNlZqcka@QZ6tiaPU/Lb9IIVNBo9pQT0/FsFazGsTPQuJX2qpEBzn6ufj7qloaaxsbx3JVAEU0Mm1tszRrNLK0gQwVQ21DTftKW1sTU3sLS6tKK2OjWIgVunkKKtUq1RrKmhW1@tGVkbH6Mbr1tbXWIMna/yCSq5YrTcEYiA1BGEyY/wcA)~~
~~[130 bytes](https://tio.run/##TY2xCsIwGIT3PEXACAnBwt9Y2kbSILiq4CqdxNBmaEGXxphnj4kuDt9x9y33eg7RUObR/TbMeFIEZDTzA4@YeigKAoH5vO3fdopcL/vT4Xxct8CF6NGSDB2VsuxNLU@FAAemXQfQasdL6bqmSQWkU2pbaagr6aQo@9/tZsLE0xVbQthlEWJOFJDBIgGZb9TxAw)~~
[Answer]
# php, 135 bytes
```
<?php for(;$i<$n=$argv[1];){$s=str_pad('',$n);$s[$i?:0]=chr(rand(33,126));$s[$n-++$i]=chr(rand(33,126));echo str_ireplace(Y,X,"$s
");}
```
Fairly straightforward approach uses str\_pad to make a string of spaces of the required length, replaces the necessary characters with random ones then replaces any Ys (case insensitive) with Xs and echos the line.
Generates 2n+3 notices but, as usual, that's fine.
[Answer]
## Emacs Lisp, 269 bytes
```
(defalias'n'number-sequence)(set'c(mapcar'string(delq 89(delq 121(n 33 126)))))(defun c()(nth(random(length c))c))(defun s(x)" ")(defun x(l)(let((s(mapcar's(n 1 l))))(dotimes(i l)(set'x(copy-seq s))(setf(nth i x)(c)(nth(-(length x)i 1)x)(c))(message(apply'concat x)))))
```
Ungolfed and slightly modified:
```
(defvar c (mapcar 'string (delq 89 (delq 121 (number-sequence 33 126)))))
(defun c() (nth (random (length c)) c))
(defun s(x)" ")
(defun x(l)
(let ((s(mapcar's(n 1 l)))
x)
(dotimes (i l)
(set 'x (copy-seq s))
(setf (nth i x) (c)
(nth (- (length x) i 1) x) (c))
(message (apply 'concat x)))))
```
[Answer]
# JavaScript (ES6), 128 ~~131~~
**Edit** 3 bytes saved thx @Neil
So bulky, probably not the best approach. Bonus - it works with odd or even input.
```
n=>[...Array(n)].map((_,i,z)=>String.fromCharCode(...z.map((r=1+Math.random()*94,j)=>32+(j==i|j==n+~i&&(r+7&31?r:25))))).join`
`
```
```
F=n=>[...Array(n)].map((_,i,z)=>String.fromCharCode(...z.map((r=1+Math.random()*94,j)=>32+(j==i|j==n+~i&&(r+7&31?r:25))))).join`\n`
Z=_=>{
o=F(+S.value),O.textContent=o,/y/i.test(o)||setTimeout(Z,100)
}
setTimeout(Z,100)
```
```
<input id=S value=15 type=number>
<pre id=O></pre>
```
[Answer]
# C, 268 bytes
```
V(c){for(c=89;c==89||c==121;c=rand()%95+33);return c;}p(n,s){n^1?s-n?printf("%*.c",s-n,32):0,printf("%c%*.c%c\n",V(),n*2-3,32,V()),p(n-1,s),s-n?printf("%*.c",s-n,32):0,printf("%c%*.c%c\n",V(),2*n-3,32,V()):printf("%*.c%c\n",s-n,32,V());}f(n){srand(time(NULL));p(n,n);}
```
Call `f()` with the size of the `x` to draw.
[Answer]
# Python 2, ~~204~~ ~~191~~ 183 bytes
Okay, Python competition here is getting fierce. Here's my attempt on shaving as many bytes as possible. ~~By now I'm stuck~~ (Ok, stuck again).
Credits to @NonlinearFruit for the way random characters are selected.
**183 byte version:**
```
import re,random
s=i=input();t=lambda:re.sub("y|Y","t",chr(random.randint(33,126)))
while i>-s:i-=2;u=abs(i);z=(s-u)/2-1;print('',' '*-~z+t()+'\n')[-1==i]+(' '*z+t()+' '*u+t())*(i>-s)
```
[Try It Online! (Ideone)](http://ideone.com/lwLInO)
Main change is to rewrite the conditional
```
(" "*(z+1)+t()+"\n"if -1==i else"")
```
as
```
(""," "*-~z+t()+'\n')[-1==i]
```
which saves 7 bytes.
**191 byte version:**
```
import re,random
s=i=input();t=lambda:re.sub("y|Y","t",chr(random.randint(33,126)))
while i>-s:
i-=2;u=abs(i);z=(s-u)/2-1;print(' '*(z+1)+t()+'\n'if -1==i else'')+(' '*z+t()+' '*u+t())*(i>-s)
```
[Try It Online! (Ideone)](http://ideone.com/Qf2DNS)
Main changes are the way random characters are selected and some code rearrangement such as `s=input();i=s;` becoming `s=i=input();`, removing the `r=range` assignment as it is no longer needed and calling `abs` directly as it results in less bytes of code.
~~Beating the previous shortest answer in Python by 1 byte!~~ @R. Kap 's approach is used for generating the random characters.
Each iteration of the while loop a row of the ex is printed.
**204 byte version**:
```
from random import*
s=input();i=s;a=abs;r=range;t=lambda:chr(choice(r(33,89)+r(90,121)+r(122,128)))
while i>-s:
i-=2;z=(s-a(i))/2-1;print(' '*(z+1)+t()+'\n'if -1==i else'')+(' '*z+t()+' '*a(i)+t())*(i>-s)
```
[Try It Online! (Ideone)](http://ideone.com/Xcx268)
Ungolfed version to get an idea of how it works:
```
from random import *
random_character = lambda : chr(choice(range(33,89)+range(90,121)+range(122,128)))
size = input()
current_row = size
while current_row > -size:
current_row-=2
n_leading_spaces = (size-abs(current_row)/2)-1
row_to_print = ''
if current_row == -1:
row_to_print = ' ' * (n_leading_spaces+1) + random_chr() + '\n'
if current_row > -size:
row_to_print += ' ' * n_leading_spaces + random_chr()+' '*abs(current_row)+random_chr()
print row_to_print
```
It was hard to handle the 1-character case!
[Answer]
# PHP, 100 bytes
```
for(;($x%=$n=$argv[1])?:$y++<$n&print"\n";)echo strtr(chr($y+$x++-$n&&$x-$y?32:rand(33,126)),yY,zZ);
```
takes input from command line argument; run with `-nr`.
combined loop prints characters depending on position
**breakdown**
```
for(;
($x%=$n=$argv[1]) // inner loop
?
:$y++<$n&print"\n" // outer loop; print newline
;)
echo strtr(chr( // 2. replace Y with Z; print
$y+$x++-$n&&$x-$y // 1: if position is not on diagonals
?32 // then space
:rand(33,126) // else random printable
),yY,zZ);
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `mM`, 34 bytes
```
‹½ƛ\%꘍⁰↲øm;øm⁋?‹4*›ƛ‛yY95ɾ31+CF℅;%
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=mM&code=%E2%80%B9%C2%BD%C6%9B%5C%25%EA%98%8D%E2%81%B0%E2%86%B2%C3%B8m%3B%C3%B8m%E2%81%8B%3F%E2%80%B94*%E2%80%BA%C6%9B%E2%80%9ByY95%C9%BE31%2BCF%E2%84%85%3B%25&inputs=3&header=&footer=)
```
‹½ƛ ; # Map 0...(n-1)/2...
\%꘍ # That many spaces before a %
⁰↲ # Left-padded to correct width
øm # Palindromise
øm # Palindromise
⁋ # Join by newlines
?‹4*› # 4(n-1)+1
ƛ ; # Map 0...n...
95ɾ31+C # Printable ASCII
‛yY # Push ys
F # Remove ys
℅ # Choose a random element from this
% # Format the cross by this
```
[Answer]
# [Vyxal 2.6](https://github.com/Vyxal/Vyxal), 22 bytes
```
½⌈:ʁ\%꘍↲∞v∞⁋?dkP‛yYFƈ%
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLCveKMiDrKgVxcJeqYjeKGsuKInnbiiJ7igYs/ZGtQ4oCbeVlGxoglIiwiIiwiNSJd)
```
½⌈: # Push ⌈x/2⌉ twice
ʁ # For each 0...^-1
\%꘍ # Prepend that many spaces to a %
½⌈ ↲ # Pad to length ⌈x/2⌉ with spaces
∞v∞ # Quad palindromise
⁋ # Join by newlines
ƈ # Choose...
?d # Input * 2
ƈ # Random items from...
kP # Printable ASCII
‛yYF # Without Y
% # Replace % in the first bit with the random chars
```
] |
[Question]
[
This is a Code Golf challenge.
[Flood](http://www.chiark.greenend.org.uk/~sgtatham/puzzles/js/flood.html) is a game in which the player is presented with a game board such as this:
[![Initial Game Board](https://i.stack.imgur.com/RWaO2m.png)](https://i.stack.imgur.com/RWaO2m.png)
On each turn, you choose a colour (on the link above, by clicking a square containing that colour), and the cell in the top-left corner is filled with that colour - this colour will absorb all adjacent cells with the same colour. So, for example, the first turn might be Blue, which will cause the yellow cell in the top corner to turn blue, and merge with the existing blue cell. The next turn might be Purple, which will fill both of the first two cells purple, merging them with the two-cell purple area attached to them. Then you might go Red, then Orange. With this sequence, the board will end up as:
[![After going Blue, Purple, Red, Orange](https://i.stack.imgur.com/hMfVFm.png)](https://i.stack.imgur.com/hMfVFm.png)
Your task is to write a code that simulates the game, taking in an array or other data format containing the current state of the game, in a suitable format (picture, numbers in a square array, string with numbers indicating the dimensions, anything that can be identified with the game), along with one or more input commands (colours, cells that contain colours, etc - your choice of how to implement the sequence, but you need to explain it).
If (and only if) the input solves the board (causes all cells to be the same colour), then your code should print a message in some format informing the player that the board is cleared or completed. It is up to you how this is done, but it must be clear to any English speaker using the code without requiring separate documentation (so outputting "1" isn't good enough). Note that displaying a completed board is not sufficient.
Some example options for completion output include `win`, `done`, `complete`, or `clear`. If your language doesn't have a nice way to output a longer message, I recommend using `win`.
Whether the input solves the board or not, the code should output (either as function output or as a displayed output) the final state of the board.
The code may take input of moves interactively (from STDIN, to simulate the actual game) or as a code input.
## Scoring
Your goal is to minimise the number of bytes in the function or code.
## Rules and Assumptions
[Standard Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
Code must be able to handle non-square boards, with each dimension being anywhere between 6 and 30 cells (more is fine, it must handle this range). It must be able to handle between 3 and 9 distinct colours or "colour" labels (numbers are fine).
You may assume that input is in simplest form - that is, if there are four colours, they will be labelled 1-4, or a-d, or any other similar system as appropriate. You will not need to handle situations such as incorrect inputs, unsimplified inputs (you won't have the numbers 1, 3, 6, and 9, without the others in between, unless it suits your code).
Your answer should include a description of formats, etc.
**Request**: If you believe you have identified a non-standard loophole, and it's definitely a loophole and not in the spirit of the question, please comment to have the loophole closed, rather than posting an answer using it. This is not a rule, *per se*, but an effort to keep the challenge interesting.
[Answer]
# Octave, ~~68~~ ~~64~~ ~~94~~ ~~92~~ 83 bytes
```
a=f(a,s)m=a;for k=s;[~,x]=bwfill(a~=k&m,1,1,4);m(x)=0;a(x)=k;end;~m&&puts("win\n");
```
A function that takes as input a matrix `a` and a vector `s` as the sequence of commands and outputs the final state of the board.
Explanation:
```
function a=Flood(a,s)
m=a;
for k=s
[~,x]=bwfill(a~=k&m,1,1,4);
m(x)=0;
a(x)=k;
end
~m&&puts("Game Completed\n");
end
```
Usage:
```
num_colors = 4;
a = randi(num_colors, 5 ,7)
s = randi(num_colors, 1 , 15);
Flood(a,s)
```
Use `m` as a mask representing the filled region so far. Repeatedly run commands and flood fill the masked grid from the top left corner.
] |
[Question]
[
A simple FizzBuzz using strings.
**Given**
* 1 word or phrase (string)
* 2 unique characters
**Output**
The word or phrase with each occurrence of the first character replaced with fizz and each of the second character replaced with buzz
**Rules**
* The first letter in both Fizz and Buzz must remain capitalized
* For the rest of the words fizz and buzz, you must match the case of the replaced character (if no case then keep lowercase)
* If given characters are not in the phrase, output the original phrase
**Test Cases**
```
Given: Hello, h, l
Output: FIZZeBuzzBuzzo
Given: test, a, b
Output: test
Given: PCG rocks!, , !
PCGFizzrocksBuzz
Given: This
Is
SPARTA!,
, S
Output: ThiBuzzFizzIBuzzFizzBUZZPARTA!
Given: FizzBuzz, a, b
Output: FizzBUZZuzz
```
This is code-golf so the shortest code, in bytes, wins!
**Note**
Technically handling the newline case (This Is SPARTA!) is a part of the challenge. However, I will not void an answer for not including it, as it is very challenging or even impossible in some languages.
[Answer]
## [Python 3](https://docs.python.org/3.6/), ~~180~~ ~~174~~ ~~168~~ ~~160~~ 152 bytes
```
from sys import*
J=''.join
L=str.lower
s,a,b=J(stdin).split(', ')
print(J('FBFBiuIUzzZZzzZZ'[L(k)==L(b)::2][k!=L(k)::2]*(L(k)in L(a+b))or k for k in s))
```
This is just a more golfed version of [Stephen](https://codegolf.stackexchange.com/a/113295/39211)'s answer, in Python 3. This chips away 42% of his bytes. Python 2 would save one byte on the print, but such is the price of progress. This handles newlines properly.
Thanks to Blckknight for saving 8 bytes on input.
[Answer]
# Python, 109 bytes
```
lambda s,w:"".join([c,"Fizz","Buzz","BUZZ","FIZZ"][-~w.lower().find(c.lower())*-~(-2*c.isupper())]for c in s)
```
[Try it online!](https://tio.run/nexus/python3#PY47D4JAEIT7@xXLVnvkoLA0sVATlcSC@GhECjwhniJHOAyJhX8dj/NR7E5mstlvismxL7P76ZyBEd0YMbxqVVEiBS7U84kCZ4@P7A8HK4vISpoEry4sdZc3xMNCVWeSP8v94EXByJehMo@6dlFa6AYkqAoM79vctAYmkBCu8rLU9ulljVwQxvMlNFrejIcCEDwbArka3w7Zyd0h7i7KsMiwbTzd7KaeTYQdtrWLp2ygDZQB6GhjBnWjqpYGx3@mIN/5f8D7Nw "Python 3 – TIO Nexus")
---
Takes the two characters as a single string
*Edit:
Added testcase to TIO link, newline works too*
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 34 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Œl=€⁹Œl¤ȧ€"“¡Ṭ4“Ụp»o"/ȯ"Œu⁹Œln$T¤¦
```
**[Try it online!](https://tio.run/nexus/jelly#@390Uo7to6Y1jxp3AlmHlpxYDuQoPWqYc2jhw51rTICMh7uXFBzana@kf2K90tFJpRCFeSohh5YcWvb//3@u4P8hGZnFXJ7FXMEBjkEhjooA "Jelly – TIO Nexus")**
### How?
```
Œl=€⁹Œl¤ȧ€"“¡Ṭ4“Ụp»o"/ȯ"Œu⁹Œln$T¤¦ - Main link: characters, string
Œl - lowercase the characters
¤ - nilad followed by link(s) as a nilad:
⁹ - right argument, the string
Œl - lowercase
=€ - equals (vectorises) for €ach (a list of 2 lists that identify the indexes of the string matching the characters regardless of case)
“¡Ṭ4“Ụp» - dictionary strings ["Fizz", "Buzz"]
" - zip with
ȧ€ - logical and (non-vectorising) for €ach (replace the 1s with the words)
/ - reduce with:
" - zip with:
o - logical or (vectorises) (make one list of zeros and the words)
- implicit right argument, string
" - zip with:
ȯ - logical or (non-vectorising) (replace the zeros with the original characters from the string)
¦ - apply...
Œu - uppercase
- ...to the indexes (the words at indexes):
¤ - nilad followed by link(s) as a nilad:
⁹ - right argument, the string
$ - last two links as a monad (i.e. the string on both sides):
Œl - lowercase
n - not equals (vectorises)
T - truthy indexes (the indexes of the capital letters in the string)
```
[Answer]
# [Python 2](https://docs.python.org/2/), 271, 261 bytes
```
import fileinput as f
a=''
for m in f.input():a+=m
a=a.split(', ')
l=L=list(a[0])
for i in range(0,len(a[0])):
j,k=l[i].lower(),l[i].istitle()
if j==a[1].lower():
L[i]='FIZZ'if k else'Fizz'
elif j==a[2].lower():
L[i]='BUZZ'if k else'Buzz'
print''.join(L)
```
[Try it online!](https://tio.run/nexus/python2#bcwxC8IwEIbhPb/itkswlOooZHEQhK4uLQ4RErl6TUuaIvjna1pRENxyvN@Tmbqhjwk8saMwTAnsCF5Ygyh8H6EDCuCLNUm1txvT5WiLcWBKEjWgEmwqwzQmaZvyolZGC4s23JwsNbvwTmovoNV3ww1dCu4fLkql1yNrSuykEkAeWmNss/1OsoIqrwweT3WNeXAHx6PDIz2fKPL7Y3Z/zOH8Yw7TYoZIISEWbU9BVmqel6@WpMFquL4A "Python 2 – TIO Nexus")
Wow this one was a doozie! It turns out python won't accept multi-line inputs so `fileinput` must be used.
edit: should pass all cases now :)
[Answer]
# MATLAB/[Octave](https://www.gnu.org/software/octave/), ~~106~~ ~~102~~ 111 bytes
```
@(a,b,c)regexprep(a,num2cell([lower([b c]) upper([b c]) '1234']),{'2','4','1','3','FIZZ','Fizz','BUZZ','Buzz'})
```
This could probably be optimised further.
It uses a simple Regex replacement. However an intermediate step is required by replacing the input characters with numbers first. This is so that if the second input replace letter was contained in `Fizz` that the `Fizz` doesn't then get replaced when the next regex is performed.
This of course assumes there are no numbers in the input. However given the question says the input is a word or phrase I feel that this is an acceptable assumption.
The code will handle new lines in the input correctly.
You can [Try it online!](https://tio.run/nexus/octave#RY2xCsIwFEV/5W0vgQwm7QdIB1FwdWnIkMaHFmIbUoJS8dvjq4vD4XKGe2/dC68GFWSmG71SpsQ@lYcJFKOwcX5SFnaA4CSUlP6C2jQtOqneaFBhy2imYQ6nvt9iXFeO7vKzrrB9ZPXTIiweeX1G0DvA8zjRAj4T@LjdXdEpvHMjoqxf "Octave – TIO Nexus")
[Answer]
# Bash 4.4 + GNU sed, ~~70~~ ~~228~~ ~~222~~ 227 bytes
```
IFS=;alias e=echo;K=`sed $([[ $2 != '
' ]]&&e "s/${2,}/Fizz/g;s/${2^}/FIZZ/g"||:)$([[ $3 != '
' ]]&&e ";s/${3,}/Buzz/g;s/${3^}/BUZZ/g"||:)<<<"$1"`;[[ $2 = '
'||$3 = '
' ]]&&e ${K//$'\n'/`[[ $2 = '
' ]]&&e Fizz||e Buzz`}||e "$K"
```
Apparently `alias e=echo` throws an error if referenced in Bash 4.3 or below, the version TIO is apparently using. Therefore, the longer and equivalent Bash 4.3 code is given in the below TIO test suite for the sake of testing. This passes all of the test cases, so that is nice.
[Try it online!](https://tio.run/nexus/bash#Zc69CoMwFAXgPU8RQzAttITqqA46COJSql20SooVddEhdNH42J3TqP3DjgfO/c6VgR85VugwXt4g3qQpxAbUHEgAgVmm62VRdxBxigdjN1K/6XtaWXPMVQyShFZIiKWFtgtg/gPziakE7/4RTCV455Vg2zbCB8Ss5ZPZEUKRKxEPIaWYXFpC2U/1W5hefbHTJhvfGzhEUsq4bjgIOIiO7il2NQlk9Gi7fXEt6vIJ "Bash – TIO Nexus")
[Answer]
## JavaScript (ES6), 92 bytes
Takes input as a string and an array of two characters. Supports newlines.
```
f=(s,[a,b],r='Fizz')=>a?f(s.replace(RegExp(a,'gi'),m=>m<'a'?r.toUpperCase():r),[b],'Buzz'):s
```
### Test cases
```
f=(s,[a,b],r='Fizz')=>a?f(s.replace(RegExp(a,'gi'),m=>m<'a'?r.toUpperCase():r),[b],'Buzz'):s
console.log(f("Hello", ['h', 'l']))
console.log(f("test", ['a', 'b']))
console.log(f("PCG rocks!", [' ', '!']))
console.log(f(`This
Is
SPARTA!`, [`
`, 'S']))
console.log(f("FizzBuzz", ['a', 'b']))
```
[Answer]
## [GNU sed](https://www.gnu.org/software/sed/), 135 + 1(r flag) = 136 bytes
By default, a sed script is executed as many times as there are input lines. To handle multi-line input, I use a loop to append all possible remaining lines to the first, without starting a new cycle.
```
:r
$!N
$!br
s:, (.), (.):;\u\1FIZZ;\l\1Fizz;\u\2BUZZ;\l\2Buzz:
s:^:,:
:
s:,(.)(.*;\1)(...)(.):\3,\4\2\3\4:
s:,(.):\1,:
/,;.F/!t
s:,.*::
```
**[Try it online!](https://tio.run/nexus/sed#NYuxCoMwEED3fEWEDirXSKLTZdJBcCml2kWODp0MlFoSXfLxTZOWDnf3eNwLaNkhO8W5W@YQeC6K70JNO8l@mGdNjwjG@2RUd/0Z1e3eY0xuCMgSQKxyUWqS8YjEBVIN1JCimpr/C5KMQQVa9FW2JSlKxBCmxTg2ODae28vUZsAZ8PG9vjazPl042g8)**
The replacement table used on line 4, needs to be in that exact order, i.e. 'Fizz' and 'Buzz' after their upper-case forms. This is because the sed regex `.*`, used during the table lookup, is greedy. If the current char needed to be replaced is not a letter (no case), then the lowercase string is needed (matched last).
Since sed has no data types, I use a character delimiter to iterate a string. It will mark my current position and in a loop I shift it from left to right. Fortunately, I can use `,` for this, since it is the input data delimiter.
**Explanation:**
```
:r # reading loop
$!N # append next input line
$!br # repeat till EOF
s:, (.), (.):;\u\1FIZZ;\l\1Fizz;\u\2BUZZ;\l\2Buzz: # create replacement table
s:^:,: # append my string delimiter
: # main loop
s:,(.)(.*;\1)(...)(.):\3,\4\2\3\4: # apply char replacement, if any
s:,(.):\1,: # shift delimiter to right
/,;.F/!t # repeat till end of string
s:,.*:: # print only the final string
```
[Answer]
# Pyth - 25 bytes
```
sXzsrBQ1scL2rB"FizzBuzz"1
```
[Test Suite](http://pyth.herokuapp.com/?code=sXzsrBQ1scL2rB%22FizzBuzz%221&test_suite=1&test_suite_input=%22hl%22%0AHello%0A%22ab%22%0Atest%0A%22+%21%22%0APCG+rocks%21%0A%22ab%22%0AFizzBuzz&debug=0&input_size=2).
[Answer]
# Haskell, 114 bytes
```
u=Data.Char.toUpper
p[f,b]x|f==u x="Fizz"|b==u x="Buzz"|2>1=[x]
q x y|u y<y=x|2>1=u<$>x
r x=concatMap$q=<<p(u<$>x)
```
`r` takes the fizz and buzz characters as a 2 element list as the first argument, and the input string as the second argument. Newlines and unicode should be handled appropriately, although the function is unfortunately not total (allowing for invalid inputs saved 5 bytes).
[Answer]
# Mathematica, 94 bytes
```
a=ToLowerCase;b=ToUpperCase;StringReplace@{a@#->"Fizz",b@#->"FIZZ",a@#2->"Buzz",b@#2->"BUZZ"}&
```
Anonymous function. Takes two strings as input and returns a function which takes a string as input and returns a string as output as output. It must be called in the format `prog["c1", "c2"]["s"]`, where `"s"` is the target string and `"c1"` and `"c2"` are the two characters. Could probably be golfed further.
] |
[Question]
[
In this exercise, you have to analyze records of temperature to find the closest to zero.
Write a program that prints the temperature closest to 0 among input data.
## Input
* N, the number of temperatures to analyse (optional). This will be nonzero.
* The N temperatures expressed as integers ranging from *-273 to 5526*.
## Output
Output the temperature closest to 0. If two temperatures are equally close, take the positive one. For instance, if the temperatures are -5 and 5, output 5.
## Example
```
Input
5
1 -2 -8 4 5
Output
1
```
[This challenge is similar to this one on CodinGame, you can view the problem statement source here.](https://github.com/GlenDC/Codingame/blob/master/descriptions/temperatures.md)
Some modifications have been made to the text.
[Answer]
# [Python](https://docs.python.org/2/), 35 bytes
```
lambda l:max((-x*x,x)for x in l)[1]
```
[Try it online!](https://tio.run/nexus/python2#S7ON@Z@TmJuUkqiQY5WbWKGhoVuhVaFToZmWX6RQoZCZp5CjGW0Y@7@gKDOvRCFNI1rXSMdQR9cwVpMLWchIxyRW8z8A "Python 2 – TIO Nexus")
Narrowly beats:
```
lambda l:min(l,key=lambda x:2*x*x-x)
lambda l:min(sorted(l)[::-1],key=abs)
```
[Answer]
## JavaScript (ES6), 33 bytes
```
a=>a.reduce((m,n)=>n*n-n<m*m?n:m)
```
### Demo
```
let f =
a=>a.reduce((m,n)=>n*n-n<m*m?n:m)
console.log(f([1, -2, -8, 4, 5]))
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
AÐṂṀ
```
[Try it online!](https://tio.run/nexus/jelly#@@94eMLDnU0Pdzb8P9z@qGmN@///0YY6CrpGQGyho2Cio2Aaq6MQDcKmQCHTWAA "Jelly – TIO Nexus")
### How it works
```
AÐṂṀ Main link. Argument: A (array)
AÐṂ Take all elements with minimal absolute value.
Ṁ Take the maximum. Yields 0 for an empty list.
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog) (2), 5 or 2 bytes
```
~{≜∈}
```
[Try it online!](https://tio.run/nexus/brachylog2#@19X/ahzzqOOjtr//6N1TXVMdcx0dA2NYv9HAQA "Brachylog – TIO Nexus")
It wouldn't surprise me if there were a shorter solution along the lines of the Jelly or Pyke, but I like this one because it's so weird.
This is simply Brachylog's "find a list containing the input" operator `∈`, with an evaluation strategy `≜` that simply tries explicit values for integers until it finds one that works (and it happens to try in the order 0, 1, -1, 2, -2, 3, etc., which is surprisingly handy for this problem!), and inverted `~` (so that instead of trying to find an output list containing the input, it's trying to find an output contained in the input list). Unfortunately, inverting an evaluation strategy along with the value itself costs 2 bytes, so this doesn't beat the Jelly or Pyke solutions.
There's also a dubious 2-byte solution `≜∈`. All Brachylog predicates take exactly two arguments, which can each be inputs or outputs; by convention, the first is used as an input and the second is used as an output, but nothing actually enforces this, as the caller has complete control over the argument pattern used (and in Prolog, which Brachylog compiles to, there's no real convention about argument order). If a solution which takes input through its second argument and produces output through its first argument is acceptable, there's no requirement to do the inversion.
[Answer]
# [R](https://www.r-project.org/), 31 bytes
```
(l=scan())[order(abs(l),-l)][1]
```
[Try it online!](https://tio.run/##K/r/XyPHtjg5MU9DUzM6vygltUgjMalYI0dTRzdHMzbaMPa/rqmC6X8A "R – Try It Online")
[Answer]
## Pyke, 4 bytes
```
S_0^
```
[Try it online!](https://tio.run/nexus/pyke#@x8cbxD3/7@uoY4CEOkaAbGFjoKJjoIpAA "Pyke – TIO Nexus")
```
S_ - reversed(sorted(input))
0^ - closest_to(^, 0)
```
[Answer]
# Mathematica, ~~21~~ 19 bytes
```
Max@*MinimalBy[Abs]
```
Composition of functions. Takes a list of integers as input and returns an integer as output.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~9~~ 6 bytes
```
0iSPYk
```
[Try it online!](https://tio.run/nexus/matl#@@@fGRwQmf3/f7SuqYJpLAA "MATL – TIO Nexus")
Thanks to Luis Mendo for pointing out there's actually a built-in for this in MATL, which is not present in MATLAB.
```
i % Take input
S % Sort
P % Reverse to have largest value first.
0 Yk % Closest value to zero, prioritizing the first match found
```
If you wish to follow the spec and also provide the number of temperatures to be read, this should be given as the second input, and will be silently discarded.
[Answer]
# C++14, 64 bytes
As unnamed lambda, expecting first argument to be like `vector<int>` and returing via reference parameter.
```
[](auto L,int&r){r=L[0];for(int x:L)r=x*x<=r*r?r+x?x:x>r?x:r:r;}
```
Ungolfed and usage:
```
#include<iostream>
#include<vector>
auto f=
[](auto L,int&r){
r=L[0];
for(int x:L)
r = x*x<=r*r ? //x is absolute less or equal
r+x ? //r==-x?
x : //no, just take x
x>r ? //take the positive one
x :
r :
r //x was absolute greater, so keep r
;
}
;
int main(){
std::vector<int> v = {5, 2, -2, -8, 4, -1, 1};
int r;
f(v,r);
std::cout << r << std::endl;
}
```
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 21 bytes
Added `+1` for `-p` since this challenge precedes "options don't count"
```
$G[abs]=$_}{$_+="@G"
```
[Try it online!](https://tio.run/##K0gtyjH9/1/FPToxqTjWViW@tlolXttWycFd6f9/Cy4TYy5dEy5TIPyXX1CSmZ9X/F@3AAA "Perl 5 – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt) `-g`, 3 bytes
```
ña¼
```
[Try it online!](https://tio.run/##y0osKPn///DGxEN7/v@PNlUwVNA1UtC1UDBRMI3l4tJNBwA "Japt – Try It Online")
# [Japt](https://github.com/ETHproductions/japt), 5 bytes
```
ña¼ v
```
[Try it online!](https://tio.run/##y0osKPn///DGxEN7FMr@/4/WNVUwjQUA "Japt – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 16 bytes
```
Îåà_Di¹{RDÄßs\kè
```
Explanation:
```
Î Push 0 and [implicit] input array
å For each element in the array, is it a 0?
à Find the greatest value (1 if there was a 0 in it, 0 otherwise)
_ Negate boolean (0 -> 1, 1 -> 0)
D Duplicate
i If true, continue
¹ Push input
R Reversed
D Duplicated
Ä Absolute value
ß Greatest element
s Swap top two values in stack
\ Delete topmost value in stack
k Index of greatest element in the array
è Value of the index in the input array
```
[Try it online!](https://tio.run/nexus/05ab1e#@3@47/DSwwviXTIP7awOcjnccnh@cUz24RX//0frmugo6BoBsYWOApBpCmQBKSMw0jWMBQA "05AB1E – TIO Nexus")
Not at short as I'd like, but at least it works.
[Answer]
## Haskell, 29 bytes
```
snd.maximum.map(\x->(-x^2,x))
```
Usage example: `snd.maximum.map(\x->(-x^2,x)) $ [1,-2,-8,4,5]`-> `1`.
Map each element `x` to a pair `(-x^2,x)`. Find the maximum and pick the 2nd element from the pair.
[Answer]
# PHP, 81 bytes
two solutions: the first one requires an upper bound; both require all temperatures nonzero.
```
for($r=9e9;$t=$argv[++$i];)abs($t)>abs($r)|abs($t)==abs($r)&&$t<$r?:$r=$t;echo$r;
for(;$t=$argv[++$i];)$r&&(abs($t)>abs($r)|abs($t)==abs($r)&&$t<$r)?:$r=$t;echo$r;
```
Run with `-r`, provide temperatures as command line arguments.
A lazy solution for **92 bytes**:
```
$a=array_slice($argv,1);usort($a,function($a,$b){return abs($a)-abs($b)?:$b-$a;});echo$a[0];
```
defines a callback function for [`usort`](http://php.net/usort) and uses it on a slice of `$argv`.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 15 bytes
```
*.min:{.²,-$_}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtfSy83M8@qWu/QJh1dlfja/9ZcxYmVCmkaKvGaCmn5RVwahjq6Rjq6FjomOqaaOlwaRgiujq4hSEQXSYWOoab1fwA "Perl 6 – Try It Online")
[Answer]
# Java 8, ~~63~~ 39 bytes
```
s->s.reduce(1<<15,(r,i)->r*r-r<i*i?r:i)
```
Port from [*@Arnauld's* JavaScript answer](https://codegolf.stackexchange.com/a/112039/52210). I couldn't find anything shorter..
-10 bytes converting Java 7 to 8,
and another -24 bytes thanks to *@OlivierGrégoire*.
**Explanation:**
[Try it online.](https://tio.run/##rY/BbsIwDEDv/QofE5RE6zakCTqmHXcYF46IQ5YG5K4NyEmZEOq3d25BaPdxcBQn9vNzZY9WV@V372obI3xaDOcMAEPytLXOw3JIxwdwouJq0yasTUzkbWM@QlqNN4hyzoVdxkdMNqGDJQR4hT7qRTTky9Z5kRdFPlWCFEq9oAlpKnCCbzRD2c@H1kP7VXPrlXDcYwkNKwkegmG33lh50VmdYvKN2bfJHPgn1UEE89fvncie4lVTBP8zbLDenCFXoB85XhQ8K5hCJ@Vo/h/mALw7k0UfFOR3E3y6kbqs638B)
```
s-> // Method with IntStream parameter and int return-type
s.reduce(1<<15, // Start `r` at 32768 (`32768^2` still fits inside a 32-bit integer)
(r,i)->r*r-r<i*i?// If `r^2 - r` is smaller than `i^2`:
r // Leave `r` the same
: // Else:
i) // Replace the current `r` with `i`
// Implicitly return the resulting `r`
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 30 bytes
```
a=>a.sort((a,b)=>a*a-a>b*b)[0]
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z@TWqKQpmD7P9HWLlGvOL@oREMjUSdJE8jTStRNtEvSStKMNoj9n5yfV5yfk6qXk5@ukaYRbaijoGsExBY6CiY6CqaxmppcaCp0jcyNgZLGWKRMgRpNsGkxxW4USD1I/D8A "JavaScript (Node.js) – Try It Online")
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 28 bytes
```
@(x)max(x(min(a=abs(x))==a))
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0IzN7FCo0IjNzNPI9E2MakYKKJpa5uoqfk/TSNawVBB10hB10LBRME0VvM/AA "Octave – Try It Online")
Finds the smallest absolute value (`min(a=abs(x))`), then maps it back to which elements have that smallest absolute value in case of a tie (`x(...==a)`). Finally takes the maximum value of the results (`max(...)`) to ensure that in the event of a tie we get one result which is the positive one.
[Answer]
## PHP, 209 Bytes
**Not really golfed**, but wanted to try to use mostly array functions, avoiding loops
[Try it Online!!](https://tio.run/##VY9BCoMwEEWv0kWQhEbQUjeN4kFCKGk6QVGMTEyhFM9u09guuhn@f/NgmLmbt7qd47RhMkvvpoOlRLMX0VI1hfAOl08XZGg0on5ePWg0HS14ou5Hx95AFDkZjmXk4csRHoAe6N7uvbVJcoyJPsYgS5VlxMlCxZPYUH3zO2V1imnD2oQuqYkVRg9J3sX/JcIScCIo1g1M5@I3Mq94fuJ5yc@84pViYnsD)
**Code**
`function f($a){$a[]=0;sort($a);$k=array_search(0,$a);$o=array_slice($a,$k+1);$u=array_reverse(array_diff($a,$o));if($u[1]&&$o[0]){$r=(abs($u[1])<abs($o[0]))?$u[1]:$o[0];}else{$r=($u[1])?$u[1]:$o[0];}return$r;}`
**Explanation**
```
function f($a){
$a[]=0; #As all nonzero values, 0 is pushed
sort($a); #Sorting the array
$k=array_search(0,$a); #Search where zero is
$o=array_slice($a,$k+1); #Array with all values >0
$u=array_reverse(array_diff($a,$o)); #Array with all smaller than zero values
#Array has ascending order so it gets reversed
if($u[1]&&$o[0]){ #if both are set we just compare the abs value
$r=(abs($u[1])<abs($o[0]))?$u[1]:$o[0];
}else{
$r=($u[1])?$u[1]:$o[0]; #al least one of them will allways be set
#the first value is always returned
#the 0 value on $u is not usetted that why $u[1]
}
return $r;
}
```
[Answer]
# [Julia 0.6](http://julialang.org/), 29 bytes
```
x->sort(x,by=x->abs(x-.1))[1]
```
Sort by the absolute value of the temperature, but subtract .1 first to ensure positive temperatures always win.
[Try it online!](https://tio.run/##yyrNyUw0@59mm5Sanpn3v0LXrji/qESjQiep0hbISUwq1qjQ1TPU1Iw2jP2fmpfC5VCckV@ukKYRbaRjrGMSq4kmoKNrhCwGE/kPAA "Julia 0.6 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
{R0.x
```
[Try it online.](https://tio.run/##yy9OTMpM/f@/OshAr@L//2hDHV0jHV0LHRMd01gA)
Or alternatively:
```
ÄWQÏà
```
[Try it online.](https://tio.run/##yy9OTMpM/f//cEt44OH@wwv@/4821NE10tG10DHRMY0FAA)
**Explanation:**
```
{ # Sort the (implicit) input-list lowest-to-highest
R # Reverse it to highest-to-lowest
0.x # Pop and push the item closest to 0
# (after which the result is output implicitly)
Ä # Get the absolute value of each in the (implicit) input-list
W # Push the minimum (without popping the list)
Q # Check which are equal to this minimum
Ï # Only keep the values in the (implicit) input-list at the truthy indices
à # Pop and push the maximum of the remaining values
# (after which the result is output implicitly)
```
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2) `h`, 4 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
ṠrþA
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVFMSVCOSVBMHIlQzMlQkVBJmZvb3Rlcj0maW5wdXQ9MSUyQy0yJTJDLTglMkM0JTJDNSZmbGFncz1o)
#### Explanation
```
ṠrþA # Implicit input
Ṡr # Reverse-sort
þA # Sort by |x|
# Take the first item
# Implicit output
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `G`, 20 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 2.5 bytes
```
⁽ȧP
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJHPSIsIiIsIuKBvcinUCIsIiIsIls3LDIsLTIsOTEsNV0iXQ==)
Finds the minimum in the list by absolute value
[Answer]
# Python, 62 bytes
```
def f(n):
r=min(map(abs,n))
return r if r in n else -r
```
It feels like there is a much simpler/shorter solution.
[Answer]
# [C (clang)](http://clang.llvm.org/), 74 bytes
```
k,m;f(*i,n){for(k=*i;--n>0;k=(k*k>m*m||(k==-m&&k<m))?m:k)m=i[n];return k;}
```
[Try it online!](https://tio.run/##RY5RS8QwEITf8yuWOzyyJdF6KIi51B9S@xDaRJc0W8n1HrTX314jiMI8zCwfO9PrfnT8tu2J@/EyeDid54Gm2/dmiyqZICtSjEuYsoy2IqM1N7WJVsYqNqlK12u5W50Oh3hKiC/pOWKy1HJnsp8vmSGadRP7wQdiDy5n9zl6lg5ByjN9@SkUj3d/vq07RBSCeIbkiCXCIgT8RGo7sLDoewVF@qigSD8peFDwuJpCfeTCBbm7GV55pyBIUv@VVP4W6HdWbcS6fQM "C (clang) – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 6 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
¢M║⌠§☺
```
[Run and debug it at staxlang.xyz!](https://staxlang.xyz/#p=9b4dbaf41501&i=[-4+5+4+-1+6+-8+1]&a=1)
### Unpacked (6 bytes) and explanation
```
{|a}eoH
{ }e Get all elements of array producing the minimum value from a block.
|a Absolute value.
o Sort ascending.
H Take last. Implicit print.
```
[Answer]
# Pyth, 4 bytes
```
.m.a
```
[Try it online!](https://tio.run/##K6gsyfj/Xy9XL/H//2hDHV0jHV0LHVMdk1gA)
Explanation:
```
.m.a #Code
.m.abQ #With implicit variables
.m Q #Filter input list for values b with minimal value of the following:
.ab #Absolute value of b
```
[Answer]
# [Python 3](https://docs.python.org/3/), 31 bytes
```
a=lambda q:sorted(q,key=abs)[0]
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P9E2JzE3KSVRodCqOL@oJDVFo1AnO7XSNjGpWDPaIPb/fwA "Python 3 – Try It Online")
Sorts items by absolute value and prints the first element.
[Answer]
# [Avail](http://www.availlang.org/), 88 bytes
```
Method"f_«_»"is[c:[1..∞),t:integer*|quicksort a,b in t[1..c] by[|a-0.1|<|b-0.1|][1]]
```
Approximate deobfuscation:
```
Method "nearest to zero among first _ of «_»" is
[
count : natural number,
temps : integer*
|
(quicksort a, b in temps[1..count] by [|a-0.1| < |b-0.1|])[1]
]
```
The [pattern syntax](http://www.availlang.org/about-avail/learn/quick-start.html#methods-message-pattern-language) in the method's name, `f_«_»`, will read the initial count as a natural number (whose type is abbreviated above as the range type `[1..∞)`) separate from the collected tuple of subsequent integers.
All that remains for the body is to [sort by a custom comparator](http://www.availlang.org/about-avail/documentation/stacks/library-documentation/avail/Avail/Foundation/Tuples/2169357673.html). Here we escape the need for a second-level comparison between `x` and `-x` by shifting the values slightly towards -∞.
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 53 bytes
```
Fd^sr[d*v]sA[ddlr+0=Asr]sR[dlAxlrlAx!<Rs_z0<M]dsMxlrp
```
[Try it online!](https://tio.run/##DcihDoAgEIDhVzmrFkAR2TBQbBQqQ4IXCY7bnPPl8cq3fz9efdFQFgVlkyClBU4zg1QzXyEYC1qbFfqBJ7WE45PJJ8TaJrF7apliwurf2pjBRSqfcCEjBV537z8 "dc – Try It Online")
We're going to use the register `r` to hold our final result, so the first thing we need to do is put a too-big number in there so that our first comparison always succeeds. I think the largest number we can push in two bytes is 165 (which is less than the required 5526), but `Fd^` gives us 15^15 which is plenty large. Macro `A`, `[d*v]sA` just does the square root of the square to give us absolute value.
Macro `R` handles putting a value into register `r`; we'll come back to it in a second. Macro `M`, `[dlAxlrlAx!<Rs_z0<M]dsMx` is our main macro. Duplicates the value on the stack, runs `A` to get ABS, then pushes the value in `r` and does the same. `!<R` checks to see if ABS(`r`) is ~~greater than or equal to~~ not less than ABS(top of stack), and if so it runs `R`. Since we had to leave behind a copy of the original top of stack for `R` to potentially use, we store to a useless register (`s_`) to pop it. `z0<M` just loops `M` until the stack is empty.
Macro `R`, `[ddlr+0=Asr]sR` duplicates the top of stack twice (we need to leave something behind for `M` to gobble up when we return). At this point we know that of the two absolute values, our new value is less than or equal to our old value. If they're equal, and one is positive and the other is negative, we always need the positive. Fortunately, knowing this we can easily check for the case of one being the inverse of the other by simply adding them and comparing to 0. If so, we run `A`, and no matter what else happened we know we're storing whatever is left in `r`.
After `M` has gone through the whole stack, we `l`oad `r` and `p`rint it.
] |
[Question]
[
# Summary:
For any given language, what is the smallest amount of unique characters for your language to be [Turing-Complete](https://en.wikipedia.org/wiki/Turing_completeness)?
# Challenge:
For any language of your choice, find the smallest subset of characters that allows your language to be Turing-Complete. You may reuse your set of characters as many times as you want.
---
# Examples:
* JavaScript: `+!()[]` (<http://www.jsfuck.com>)
* Brainfuck: `+<>[]` (assumes a wrapping cell size)
* Python 2: `()+1cehrx` (made from scripts like `exec(chr(1+1+1)+chr(1))`)
# Scoring:
This challenge is scored in **characters**, not *bytes*. For example, The scores for the examples are 6, 5, and 9.
---
# Notes:
* This challenge differentiates from others in the sense that you only your language to be Turing-Complete (not necessarily being able to use every feature of the language.)
* Although you can, please do not post answers without reducing the characters used. Example: Brainfuck with 8 characters (since every other character is a comment by default.)
* You MUST provide at least a brief explanation as to why your subset is Turing-Complete.
[Answer]
# [Whispers v1](https://github.com/cairdcoinheringaahing/Whispers/tree/v1), 7 characters
```
> 1+'⍎
```
The main idea is to build an arbitrary Python expression using `+` (addition or string concat) and `'` (chr) and `⍎` (eval) it. So the proof is in two parts: constructing an arbitrary string, and making sure that Python's eval (as opposed to an arbitrary program) is Turing-complete.
### Python `eval` is Turing-complete
Unlike `exec`, we can't use many syntactic keywords like `while` and even `def`. But we have `lambda` expressions, and it turns out that we can implement untyped lambda calculus. As a minimal example, the following expression is an infinite loop:
```
(lambda a:a(a))(lambda a:a(a))
```
To make it more explicit, here are SKI combinators:
```
S = lambda l:lambda a:lambda m:l(m)(a(m))
K = lambda l:lambda a:l
I = lambda l:l
```
### `> 1+'\n` is enough to construct an arbitrary string
Now to actual Whispers code. The lines starting with single `>` are constant lines, and those with double `>>` reference other expressions using line numbers. We will only use 1, 11, 111 for constant lines, and construct the required charcodes using addition. The following sets up three numbers for the string `"123"` (charcodes 49, 50, 51):
```
> 1
> 11
>> 2+2 // 22
>> 3+3 // 44
>> 1+1 // 2
>> 5+5 // 4
>> 4+6 // 48
>> 7+1 // 49
>> 8+1 // 50
>> 9+1 // 51
```
Then we apply `'` (chr) to each of the charcodes:
```
>> '8 // "1"
>> '9 // "2"
>> '10 // "3"
```
Finally, we concat and eval them.
```
>> 11+12
>> 14+13
>> ⍎15
```
We successfully created the string `"123"` and passed it to `eval`. Now the only problem is that we used all digits to reference lines. It can be easily circumvented by inserting dummy syntactically valid lines `> 1` so that we can reference meaningful lines with repunits (so the line number `n` will be translated to the number containing `n` copies of 1):
```
> 1 // valid line 1
> 1 // from line 2...
> 1
...
> 1 // ...to line 10 are dummy lines
> 11 // valid line 11
> 1 // from line 12...
...
> 1 // ...to line 110 are dummy lines
>> 11+11 // valid line 111
...
```
### 7 chars is (likely) minimal, at least in v1
I checked the whole source code, and all one-char functions except `⍎` do not have mutable state at all. There are looping constructs like `While`, but using it alone requires at least 8 chars `> While1`. Therefore, the approach using `⍎` must be minimal (where 7-char solution is already known).
For TC-ness in Python eval, we need at least `lambd :()`, which is already 9 chars, and `chr` is definitely needed to create them without them in the source code. There is no 1-char solution to create those charcodes, and `1+` shares `+` with string concatenation. Therefore using `1+'` as the core chars is the minimal way to build a string that enables TC-ness.
I didn't read all of v2 and v3 source code, but I believe the 7-char solution is likely minimal on those too.
[Answer]
## Pyke, 5 characters
```
0h.CE
```
This is capable of producing an infinitely large number, turning it into a string and then evaluating it as Pyke code.
### Explanation of the code:
`0` - Add 0 to the stack. This is required to start a number
`h` - Increment the number before. By repeating this an arbitrary amount of times, you can create numbers that are infinitely big. Pyke supports bignums as it is written in Python, which uses them as a default.
`.C` - Turn a number into a string using the following algorithm: ([Github link](https://github.com/muddyfish/PYKE/blob/bb88fbfeabb49e576f1b9a7460b6bb7ecc4a1b02/node/chr.py))
```
def to_string(num):
string = ""
while num > 256:
num, new = divmod(num, 256)
string = chr(new) + string
string = chr(num) + string
return string
```
By this point, we can create an arbitrary amount of strings and natural numbers in Pyke with arbitrary values. Numbers can be created in the form corresponding to the regex `0(h)*` and strings can be created with `0(h)*.C`. They can be interweaved with each other to create an arbitrary mixture of strings and integers.
`E` - evaluate a string as Pyke code. This uses the same environment as the Pyke code already running so will share things like the input.
### Attempted proof that Pyke is Turing Complete.
One of the simplest ways of showing a language is turing complete is by implementing Brainf\*ck in it. This is probably much harder in Pyke than many other languages because it's list and dictionary operations are pretty much non-existent due to the lack of needing them in the area Pyke is designed to run in: [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'").
Firstly we create an interpreter for brainf\*ck and encode it using our algorithm above to create a number and then express that number with `0` and `h`. We then create the string containing the code to be ran in exactly the same way. If we were to leave it at that, we would have the stack as
```
string containing brainf*ck code
string containing brainf*ck interpreter
```
This means the code has to be in the opposite form as the Pyke stack is first in last out.
Now for the fun part: the brainf\*ck interpreter with a whopping 216 bytes!
```
Q~B"><ht.,".:=B;Z]1=L;W~Bo@D=c"ht"{I~c~LZ@EZ]1~LR3:=L)~c\,qIz.oZ]1~LR3:=L)~c\[[email protected]](/cdn-cgi/l/email-protection))~c"<>"{I~c"<>""th".:ZE=ZZ1_qI0=Z~L0"":0]10:=L)Z~LlqI~L~Ll"":1_]10:=L))~c\[qI~LZ@0qI\]~B~o>@~o+h=o))~c\]qI~o\[~B~o<_@-t=o)~o~BlN
```
[Try it here!](http://pyke.catbus.co.uk/?code=Q~B%22%3E%3Cht.%2C%22.%3A%3DB%3BZ%5D1%3DL%3BW~Bo%40D%3Dc%22ht%22%7BI~c~LZ%40EZ%5D1~LR3%3A%3DL%29~c%5C%2CqIz.oZ%5D1~LR3%3A%3DL%29~c%5C.qI~LZ%40.CpK%29~c%22%3C%3E%22%7BI~c%22%3C%3E%22%22th%22.%3AZE%3DZZ1_qI0%3DZ~L0%22%22%3A0%5D10%3A%3DL%29Z~LlqI~L~Ll%22%22%3A1_%5D10%3A%3DL%29%29~c%5C%5BqI~LZ%400qI%5C%5D~B~o%3E%40~o%2Bh%3Do%29%29~c%5C%5DqI~o%5C%5B~B~o%3C_%40-t%3Do%29~o~BlN&input=%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%5B%3E%2B%2B%2B%2B%2B%2B%2B%3E%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%3E%2B%2B%2B%3E%2B%3C%3C%3C%3C-%5D%3E%2B%2B.%3E%2B.%2B%2B%2B%2B%2B%2B%2B..%2B%2B%2B.%3E%2B%2B.%3C%3C%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B.%3E.%2B%2B%2B.------.--------.%3E%2B.%3E.&warnings=0)
If you want to try the code in semi-completed but editable form, [try it here!](http://pyke.catbus.co.uk/?code=29148259993606348019795473027151033981727193043657267298715298618848845029737110788889069846989671685456648828362149313315908236364663260280703313159747095711338624855008617588193311724075281427454604528769145152583515610047347294647716665608021028351862569315364394691180480784379528328135441143704516051303218258964158621837004922811934779379992687443430665022827059832349462401604993879108222437462218222077384731473190799648490050251634409611298857264044335892000836509220094188861002415662972007444505938234600526.C%22%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%5B%3E%2B%2B%2B%2B%2B%2B%2B%3E%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%3E%2B%2B%2B%3E%2B%3C%3C%3C%3C-%5D%3E%2B%2B.%3E%2B.%2B%2B%2B%2B%2B%2B%2B..%2B%2B%2B.%3E%2B%2B.%3C%3C%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B.%3E.%2B%2B%2B.------.--------.%3E%2B.%3E.%22E&warnings=0)
To convert from a string into a number, you can use the following Python code:
```
def conv(string, t=0):
t *= 256
t += ord(string[0])
if len(string) != 1:
return conv(string[1:], t)
return t
```
The (almost) final solution can be [tried here!](http://pyke.catbus.co.uk/?code=29148259993606348019795473027151033981727193043657267298715298618848845029737110788889069846989671685456648828362149313315908236364663260280703313159747095711338624855008617588193311724075281427454604528769145152583515610047347294647716665608021028351862569315364394691180480784379528328135441143704516051303218258964158621837004922811934779379992687443430665022827059832349462401604993879108222437462218222077384731473190799648490050251634409611298857264044335892000836509220094188861002415662972007444505938234600526.C+347988125594877536659782960746628195016297572793998820340032545396642290201585760883465162681104342673776948804677730014550908920298091092232957970986553975038820683856336960474626750895815042319239692504698431493065354108813706261113333260242845055599097052304129582.CE&warnings=0)
### Explanation of Brainf\*ck interpreter
First lets separate the program into parts:
* The initialisation:
```
Q~B"><ht.,".:=B;Z]1=L; - The initialisation part
Q~B"><ht.,".: - input.replace("><+-.,[]", "><ht.,")
- replace the characters in brainf*ck with some modified ones.
- this means we can `eval` the add and subtract bits easily.
=B; - set `B` to this.
- The `B` variable contains the instructions
Z]1=L; - set `L` to [0]
- `L` contains the stack, initialised with 0
```
* The main loop:
```
W~Bo@D=c !code! ~o~BlN - The main loop
W - do
~Bo@D=c - c=B[o++]
- the c variable is used to store the current character.
~o~BlN - while
~o - o
N - ^ != V
~Bl - len(B)
- this stops the program running once it's finished.
```
* The instructions
+ Increment/Decrement: `+-`
```
"ht"{I~c~LZ@EZ]1~LR3:=L) - The bit that does incrementing and decrementing
"ht"{I ) - if c in "ht"
~LZ@ - L[Z]
- `Z` contains the current stack pointer
~c E - eval current character with ^ as an argument
- returns the contents of `Z` either incremented or decremented
Z]1~LR3:=L - L[Z] = ^
```
* Input: `,`:
```
~c\,qIz.oZ]1~LR3:=L) - The code for output
~c\,qI ) - if character == ",":
z.o - ord(input)
Z]1~LR3:=L - L[Z] = ^
```
* Output: `.`:
```
~c\[[email protected]](/cdn-cgi/l/email-protection)) - The code for input
~c\.qI ) - if c == ".":
~LZ@ - L[Z]
.C - chr(^)
pK - print(^)
```
* Shift Left/Right: `<>`:
```
~c"<>"{I~c"<>""th".:ZE=Z - main part
~c"<>"{I - if "<>" in c:
~c"<>""th".: - c.replace("<>", "th")
ZE=Z - Z = eval(char, Z)
Z1_qI0=Z~L0"":0]10:=L) - lower bound check
Z1_qI ) - if Z == -1:
0=Z - Z = 0
~L0"": - L.insert("", 0)
0]10:=L - L[0] = 0
Z~LlqI~L~Ll"":1_]10:=L) - upper bound check
Z~LlqI ) - if Z == len(L):
~Ll"": - L.insert("", len(L))
~L 1_]10:=L - L[-1] = 0
```
* The conditionals: `[`:
```
~c\[qI~LZ@0qI\]~B~o>@~o+h=o)) - Code for `[`
~c\[qI ) - if c == "[":
~LZ@0qI ) - if L[Z] == 0:
~B~o> - B[o:]
\] @ - ^.find("]")
~o+h=o - o = o + ^ + 1
```
- And `]`:
```
~c\]qI~o\[~B~o<_@-t=o) - Code for `]`
~c\]qI ) - if c == "]":
~B~o<_ - reversed(B[:o])
\[ @ - ^.find("[")
~o -t=o - o = o - ^ -1
```
[Answer]
# [Self-modifying Brainfuck](https://soulsphere.org/hacks/smbf/), 2 characters
```
<+
```
Using these characters we can modify the end of the program in a way that it executes normal Brainfuck code.
Start by choosing the Brainfuck program, put `[>]` in the begining, that way the pointer will start where it should be. The number of bytes will be the number of `+` in the end of our code. Next we need the ascii values of the characters used in the bf code minus 43. These are how much we need to add to each `+`. For each number in our list we print `<` followed by that number of `+`, but start by the end of the list. Put everything together and it should do the same thing the bf code does.
Exemple: a bf cat `,[.,]`
It becomes `[>],[.,]`.
Now it has 8 bytes, so we should end the smbf code with `++++++++`.
The ascii values are 91, 62, 93, 44, 91,46, 44 and 93. Subtracting 43 we get 48, 19, 50, 1, 48, 3, 1 and 50.
```
50: <++++++++++++++++++++++++++++++++++++++++++++++++++
1: <+
3: <+++
48: <++++++++++++++++++++++++++++++++++++++++++++++++
1: <+
50: <++++++++++++++++++++++++++++++++++++++++++++++++++
19: <+++++++++++++++++++
48: <++++++++++++++++++++++++++++++++++++++++++++++++
```
Putting this before the `++++++++` gives the final smbf code:
```
<++++++++++++++++++++++++++++++++++++++++++++++++++<+<+++<++++++++++++++++++++++++++++++++++++++++++++++++<+<++++++++++++++++++++++++++++++++++++++++++++++++++<+++++++++++++++++++<++++++++++++++++++++++++++++++++++++++++++++++++++++++++
```
[Try it online!](https://tio.run/##K85NSvv/30abZGCjbQMmydJGsibixIgC//8DAA "Self-modifying Brainfuck – Try It Online")
Execution:
```
<++++++++++++++++++++++++++++++++++++++++++++++++++ # Add 50 to the last byte of this code, now it ends with +++++++++++++]
<+ # Add 1 to the byte to the left of that, now it ends with ++++++++++++,]
<+++ # +++++++++++.,]
<++++++++++++++++++++++++++++++++++++++++++++++++ # ++++++++++[.,]
<+ # +++++++++,[.,]
<++++++++++++++++++++++++++++++++++++++++++++++++++ # ++++++++],[.,]
<+++++++++++++++++++ # +++++++>],[.,]
<++++++++++++++++++++++++++++++++++++++++++++++++ # ++++++[>],[.,]
[>] # This was originally +++ ,but now it tells the pointer to go to the right until it leaves the code
,[.,] # Execute the Brainfuck code
```
Here is a [GolfScript](http://www.golfscript.com/golfscript/) program where you input a Brainfuck code and it outputs a Self-modifying Brainfuck code that does the same, using only `<` and `+`.
```
'[>]'\+.,:l{'<'\)43-'+'*\}\*'+'l*
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPn/Xz3aLlY9RltPxyqnWt1GPUbTxFhXXVtdK6Y2RgtI52j9/68TracTCwA "GolfScript – Try It Online")
[Answer]
# TI-Basic, 15 characters
(TI-83 Family)
```
While End(-1:ʟ→
```
Note that TI-Basic is [token-based](http://tibasicdev.wikidot.com/tokens) instead of character-based. `-` represents the subtraction symbol, not the negative sign. `)` is not needed because TI-Basic automatically closes all parentheses when it reaches a `:` or `→`. The minimum distinct tokens would be 9 tokens: `While` , `End`, `(`, `-`, `1`, `:`, `ʟ`, `→`, and any capital letter or theta.
With these characters, you can use:
* `While` for conditional branching and looping (checks if the
expression is nonzero)
* `End` to end a `While` loop
* `W` and `E` as number variables
* `1`, `-`, and `(` for constructing integers (e.g. `1-1` is 0, `1` is
1, `1-(1-1-1` is 2, `1-(1-1-1-1` is 3, `11-1-1` is 9, etc.) and doing
operations (`-` can be used for addition and subtraction, and `(` can be
used for implied multiplication)
* `:` for separating commands and can be replaced with a newline
* `→` to store values into number variables and into list elements
* `ʟ`, `W`, `E`, and `1` to reference lists (which can store up to 999
numbers or 99 on a TI-83); you can construct
242 possible list names from `W`, `E`, and `1`
* `(` to get an element from a list
This is Turing-complete because you can translate brainf\*ck (without `,` and `.` and with 999 or 99 cells), which is Turing-complete, with these characters:
`W` stores the position of the pointer, `ʟE` stores all the cells, and `E` is a temporary variable. The TI-83 versions use 99 cells instead of 999 cells.
| brainf\*ck symbol | Limited TI-Basic equivalent |
| --- | --- |
| (initialization) | TI-83: `111-11-1→W:While W:1-1→ʟE(111-11-W:W-1→W:End:1→W:`non-TI-83: `1111-111-1→W:While W:1-1→ʟE(1111-111-W:W-1→W:End:1→W:` |
| `+` | `1-(1-1-ʟE(W→ʟE(W:1→E:While E(1-(1-1-111-111-11-11-11-(1-1-ʟE(W:1-1→E:End:While E:1-1→E:E→ʟE(W:End:` |
| `-` | `1→E:While EʟE(W:1-1→E:E-(1-ʟE(W→ʟE(W:End:While E:1-1→E:1-(1-111-111-11-11-11→ʟE(W:End:` |
| `<` | TI-83: `1-1-(1-W→W:1→E:While EW:1-1→E:End:While E:1-1→E:111-11-1→W:End:`non-TI-83: `1-1-(1-W→W:1→E:While EW:1-1→E:End:While E:1-1→E:1111-111-1→W:End:` |
| `>` | TI-83: `1-(1-1-W→W:1→E:While E(111-11-W:1-1→E:End:While E:1-1→E:1→W:End:`non-TI-83: `1-(1-1-W→W:1→E:While E(1111-111-W:1-1→E:End:While E:1-1→E:1→W:End:` |
| `[` | `While ʟE(W:` |
| `]` | `End:` |
Here is a program that prints a list of the first 99 Fibonacci numbers:
```
1→ʟE(1:1→ʟE(1-(1-1-1:111-11-1-1-1→W:While W:ʟE(111-11-1-1-W→E:E-(1-1-ʟE(111-11-1-W→ʟE(111-11-W:W-1→W:End:ʟE
```
[Answer]
# [Zsh](https://www.zsh.org), 8 characters
```
$#< (){}
```
* `<<<string` prints `string`
* `(){body} args` is an anonymous function, which is immediately called with `args`
* `<<<$#` outputs the number of arguments to a function
* So we can use `(){<<<$#} $ $ $` to output 3 (for example)
* `${(#)var}` gets the character with the codepoint stored in `var`
* `${(#)$(command)}` gets the character with the codepoint that is the result of `command`
* We can combine these to generate arbitrary characters, e.g. `${(#)$((){<<<$#} $ $ $)}` is `\x03`
Hence, we can construct the string `eval`:
```
${(#)$((){<<<$#} $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $)}${(#)$((){<<<$#} $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $)}${(#)$((){<<<$#} $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $)}${(#)$((){<<<$#} $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $)}
```
And use that to execute any arbitrary code. Here is a demonstration that outputs `Hello, World` (3311 bytes):
```
${(#)$((){<<<$#} $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $)}${(#)$((){<<<$#} $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $)}${(#)$((){<<<$#} $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $)}${(#)$((){<<<$#} $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $)} ${(#)$((){<<<$#} $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $)}${(#)$((){<<<$#} $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $)}${(#)$((){<<<$#} $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $)}${(#)$((){<<<$#} $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $)}${(#)$((){<<<$#} $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $)}${(#)$((){<<<$#} $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $)}${(#)$((){<<<$#} $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $)}${(#)$((){<<<$#} $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $)}${(#)$((){<<<$#} $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $)}${(#)$((){<<<$#} $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $)}${(#)$((){<<<$#} $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $)}${(#)$((){<<<$#} $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $)}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuha3eN6rVGsoa6poaGhW29jYqCjXKqgMF6hZOzz9Nlz9NZJ8iO5fhcHu4eEcJcPZb6M-He4-pbd_qW_TUI-roe7-Uf-O-npk-FSzFtLvgXZ_YN0gAA)
`$#(){}` are integral to this method, but I think there might be a way to remove or `<`. Unfortunately I can't find one without adding a different character instead.
[Answer]
# Stacked, 5 chars
```
{!n:}
```
This is surprisingly short. If Stacked can implement each of the SKI combinations, then it is Turing Complete. Recap:
* `I` combinator - the identity function. `x -> x`
* `K` combinator - the constant function. `x -> y -> x`
* `S` combinator - the substitution function. `(x, y, z) -> x(z)(y(z))`
## I combinator: `{!n}`
Now, for the stacked specifics. `{! ... }` is an n-lambda. It is a unary function whose argument is implicitly `n`. Then, the last expression is returned from the function. Thus, `{!n}` is a function that takes an argument `n` and yields `n`.
## K combinator: `{!{:n}}`
Now, `{:...}` is a function that takes no arguments, and returns `...`. Combining this with our n-lambda formation, we get (adding whitespace for clarity):
```
{! { : n } }
{! } n-lambda. arguments: (n)
{ : n } lambda. arguments: ()
n yields n.
```
## S Combinator: `{n!nn!nnn:nnn{!n}!nn!nnn{!n}!n!!}`
Ok, this looks a little more complicated. So, a lambda takes arguments, separated by non-identifier characters. Thus, the lambda in the header is equivalent to:
```
{n nn nnn:nnn{!n}!nn!nnn{!n}!n!!}
```
This is a lambda that takes three arguments, `n`, `nn`, and `nnn`. Let's replace these with `x`, `y`, and `z` for clarity:
```
{x y z:z{!n}!y!z{!n}!x!!}
```
The two `{!n}!` are just identity function to again avoid whitespace, where `!` means "execute". So, again, reducing:
```
{x y z:z y!z x!!}
```
With an explanation:
```
{x y z:z y!z x!!}
{x y z: } three arguments
z y! apply `y` to `z` -- `y(z)`
z x! apply `x` to `z` -- `x(z)`
! apply `x(z)` to `y(z)` -- `x(z)(y(z))`
```
And therefore, this is the S combinator.
[Answer]
## [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), 5 characters
```
(q d)
```
Using only the macros `d`ef and `q`uote, we can implement the [S and K combinators](https://en.wikipedia.org/wiki/SKI_combinator_calculus), which [are Turing-complete](http://esolangs.org/wiki/S_and_K_Turing-completeness_proof). (Thanks to [Qwerp-Derp](https://codegolf.stackexchange.com/users/49561) for the inspiration.) Here it is all on one line:
```
(d dd (q (qq qq))) (d dq (q ((qq) (dd (q (qqq)) (dd (q q) qq))))) (d dqq (q ((qq) (dd (q (qqq)) (dd (q dqqd) (dd (q q) qq) (q qqq)))))) (d dqqd (q ((qq qqq) (dd (q (qqqq)) (dd (dd (dd (q q) qq) (q qqqq)) (dd (dd (q q) qqq) (q qqqq)))))))
```
The functions `dq` and `dqq` are the K and S combinators, respectively. They expect their arguments curried: i.e., for `SKK` you have to do `((dqq dq) dq)`, not `(dqq dq dq)`. `dd` is a helper function that makes a list out of its arguments (a reimplementation of the `list` function in the standard library). `dqqd` is a partially curried helper function for `dqq` that takes arguments `f` and `g` (as opposed to `dqq` that takes only `f`).
[Try it online!](https://tio.run/nexus/tinylisp#jY67DcUwCEV7pqCEUSxKr0AGIMVb37ngOIqSV0RCfA8Xhji7swQsOEJVKVtB1UNTiVkuBMCqQie/Nj6sAPLHfmWnzhLyS6lGUw1@CYKuCjoZp@Af0ZN7ze/AvJuHDafrg54/VNbwRGdTWNX79quOGMM3bNaEjKQho56xAzUMSST5lswYBw) (with some test cases that implement the `I` combinator and the argument-reversing combinator `S(K(SI))K`).
### A more readable version
```
(load lib/utilities)
(def K
(lambda (x)
(list (q (y)) (list (q q) x))))
(def S
(lambda (f)
(list (q (g)) (list (q S2) (list (q q) f) (q g)))))
(def S2
(lambda (f g)
(list (q (x)) (list (q S3) (list (q q) f) (list (q q) g) (q x)))))
(def S3
(lambda (f g x)
((f x)
(g x))))
```
Functions in tinylisp are simply lists with two elements: the parameters and the function body. For example, the function `((y) (q (1 2 3)))` takes one argument, `y`, and returns the list `(1 2 3)` (which had to be quoted to prevent evaluation). So to return this function from another function, we only need to build the correct list. This is what `K` does. If we pass the list `(1 2 3)` to `K`, it is bound to `K`'s parameter `x`, and we get:
```
(list (q q) x) -> literal q followed by value of x -> (q (1 2 3))
(list (q (y)) ...) -> literal (y) followed by the above -> ((y) (q (1 2 3)))
```
which is a function that takes one argument and always returns `(1 2 3)`, as desired.
`S` and its helper functions work the same way. Passing `func1` to `S` returns the list/function
```
((g) (S2 (q func1) g))
```
Passing `func1` and `func2` to `S2` returns the list/function
```
((x) (S3 (q func1) (q func2) x))
```
And finally, passing `func1`, `func2`, and `arg` to `S3` evaluates
```
((func1 arg) (func2 arg))
```
which implements the S-combinator.
To get from this more-readable form to the 5-character version, we replace the library macro `lambda` with the direct method of defining functions as lists: `(lambda (x) (expr))` -> `(q ((x) (expr)))`. We also reimplement `list` and call it `dd`:
```
(d dd Define dd
(q to be this list (which acts as a lambda function):
(qq Take a list of variadic args qq
qq))) and return the arglist
```
Then it's just a matter of renaming all the functions and arguments to use only `d`s and `q`s.
[Answer]
# Java, 30 26 characters
```
()+-.0;=Sacdefgimnorstv{}
```
Taking a different approach from the [other (more clever) Java answer](https://codegolf.stackexchange.com/a/110789/), this one uses "regular" characters.
Java (like most languages) offers many facilities above and beyond what is required to be Turing-complete: basic arithmetic, jumps, and declaring variables (memory on the tape). The only types of jumps necessary are the simple `if` and `for` statements.
I started by writing a small program shell (`main` method), then adding statements that implement the bare minimum set that represents a Turing-complete subset of Java. I did so in a way that used the fewest characters possible, and came up with this:
```
interface S {
static void main(String... s) {
int r = 0;
r++;
int t = p;
t--;
if (t == 0) {
r--;
}
for(;;) {
t++;
r++;
}
}
}
```
Removing all whitespace except for one space (`0x20`), sorting, and removing duplicates provides the string above.
These characters allow:
* `if` conditionals.
* Variable assignments.
* Comparing variables against each other and zero.
* `for` loops, including infinite loops (`for(;;)`)
* Adding and subtracting arbitrary numbers via repeated unary increment and decrement.
In other words, I have reduced Java to a slightly more readable version of Brainfuck.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~5~~ 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
.gBV
```
-1 distinct byte thanks to *@ovs*.
**Explanation:**
* `.g`: Pushes the amount of items currently on the stack
* `g`: Pop the current item, and push its length
* `B`: Pops the top two items on the stack, and do base-conversion
* `.V`: Pops and evaluates the top string as 05AB1E code
Using the `.g` + `g` we can create any positive number. Using `B` we can convert combinations of two numbers to a string of characters from the 05AB1E codepage. And using `.V` we can evaluate those characters as 05AB1E code.
One thing to note when creating such programs: according to [the 05AB1E source code](https://github.com/Adriandmen/05AB1E/blob/master/lib/commands/int_commands.ex), the order of the characters used in the base-conversion up to 256 is: `0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzǝʒαβγδεζηθвимнт\nΓΔΘιΣΩ≠∊∍∞₁₂₃₄₅₆ !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~Ƶ€Λ‚ƒ„…†‡ˆ‰Š‹ŒĆŽƶĀ‘’“”–—˜™š›œćžŸā¡¢£¤¥¦§¨©ª«¬λ®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ`. So a slightly different order than [the 05AB1E codepage](https://github.com/Adriandmen/05AB1E/wiki/Codepage) (which makes sense, since we start with digits and letters for the base-conversion).
To generate a program, we basically push loads and loads of `.g`, until the integer that is pushed is of length `255`. Then we can use one more `.g` plus the `g` to push 255, after which the `B` will convert the large integer to base-255, resulting in the program string, which we eval with `.V`.
When generating these programs, it will likely have loads of prepended no-ops (e.g. spaces, newlines, `w`, etc.), and I would advice to always add a leading `)\` as well to clean the entire stack of integers from the numerous `.g`, so implicit input and stack manipulation is available as well.
[Here a generator program](https://tio.run/##yy9OTMpM/f8/@lHDPM2Yw2v8Du961NR6eNuhlelAOjBTycUu3UkvTOnQusNrCv//NwrRBgA) given a 05AB1E program string as input, where the huge number of the output is replaced with that many `.g`, and the `D>` is replaced with one additional `.g`.
**Try it online:**
Here a few example programs using these five bytes (again, where the huge number and `D>` would then be replaced with that many `.g` in the actual program):
[Try it online: 2+2 (`YY+`).](https://tio.run/##HY89aoNhDINvVGRb/lsylJ6hewKlZMrQ@/NWX/Aigx9Jfv3dH8@fc5jTngurnKmNiliOo8rJ7EiMxLTtVGI90VUWw8mdRW2m02mcWdsAy3TQ242F2Jl0j5SdcuQ@zFpqYWCGVzaRG46QujxTJN9EoZUdY@EqtNhVHxOq7Gj0FkqehSi40VUGbWGE@VU5Ax0sIpwruMv1W@rCNdYJfN1@Pz@@z/kH)
[Try it online: Check if the input is a prime number (`p`).](https://tio.run/##HY89boNhCINvVBkwBpYMVc/QPZGqKlOG3l9febMZicc/r7/74/lzXcwuz4EpuzWhiGE7JCezItErumxaifFESRbNzumBJtPpNHaPTYCyfaipwmDZ7nSPXLvNWfdmargHA9082UROOGLV8cwl@SaE2uxoC99Cg5ntY4tudhRqBK2nEIIbfcugLIwwP5UzUEER4ZyFS77bzooSaRrp6/b7@fF9XWb/)
[Try it online: Print "Hello, World!" (`”Ÿ™,‚ï!`).](https://tio.run/##HY87bkNBDANvFFAS9WtcBDlDehsIAlcucn9s@NxphR1y9Pq7P54/5zCnPRdWOVMbFbEcR5WT2ZEYDdO2U4n1RFdZDCd3FrWZTqdxZm0DLNOH3m4sxM6ke6Ti1KP0YdZSDwZmeHUTueEITVdmiuSbKLS6YyxcQotd@ZhQdUejt1DKLETBjS4ZtIUR5pdyBjpYREgbWrsrokJQu66h4ev2@/nxfc4/)
[Answer]
# [Baba is You](https://en.wikipedia.org/wiki/Baba_Is_You), 18 characters
*Plus 3 objects in the game.*
```
TEXISMOVLPDWNFRGHY
```
A [Rule 110](https://en.wikipedia.org/wiki/Rule_110) implementation can be made with only these characters. This is based on [This writeup](https://www.twitlonger.com/show/n_1sqrh1m) by [Matthew Rodriguez](https://twitter.com/mattar0d/).
[![Screenshot of the level design](https://i.stack.imgur.com/RVPYK.png)](https://i.stack.imgur.com/RVPYK.png)
All the rules and explanation:
```
--- Always Active Rules ---
TEXT IS MOVE - Makes the 'IS' move.
MIRROR IS TELE - When 'IS' moves into the mirror, it teleports to the other
mirror, like a `for` loop.
PIPE IS STOP - Prevent text other than 'IS' from moving.
--- Rules that are activated once in a loop ---
ME (IS) LOVE/PIXEL
MOON (IS) IT/TILE - 'ME' and 'MOON' are construction objects,
and together they represent the value
1. Each cycle, they turn to three probes
('LOVE', 'IT', 'TILE') and a visual object
('PIXEL').
LOVE/IT/TILE (IS) MOVE/DOWN - The three probes move down, ready to create
the next generation according to Rule 110.
IT (IS) MOVE/LEFT - 'IT' moves to the left, representing xx1.
TILE (IS) MOVE/RIGHT - 'TILE' moves to the right, representing 1xx.
'LOVE' stays, representing x1x.
LONELY LOVE (IS) LINE - 'LOVE' without 'IT' or 'TILE' represents a
010 pattern, which results in 'LINE' which
represents the value 1.
LONELY IT (IS) LINE - 'IT' without 'LOVE' or 'TILE' is the 001
pattern which results in 1.
LOVE ON IT (IS) VINE
IT ON VINE (IS) EMPTY - Create 'VINE' which represents x11 where
we do not know the value of x yet.
VINE ON TILE (IS) EMPTY - 111 results in 0.
LONELY TILE (IS) EMPTY - Remove the tile as well.
VINE/TILE (IS) LINE - Any remaining 'VINE' is 011, which results
in 1. Any remaining 'TILE' is either 101 or
110, which both result in 1 as well.
LOVE/IT (IS) EMPTY - Clean up any remaining probes.
LINE (IS) ME/MOON - Turns 'LINE' into construction objects.
```
Here is a screenshot of the initial state of the level.
[![Level initial state](https://i.stack.imgur.com/1O1ZO.png)](https://i.stack.imgur.com/1O1ZO.png)
[Answer]
# APL, 9 characters
```
⍎⎕UCS(≢⍬)
```
Why this is Turing-complete:
* `≢` is length, `⍬` is the empty list, and a list can be expressed simply by naming its elements, i.e. `⍬⍬⍬` is a list of three empty lists. This way, all numbers can be formed. `≢⍬` is `0`, `≢≢⍬` is `1`, and from then on `≢⍬⍬⍬...` is `N`, where `N` is the amount of `⍬`s.
* `()` are used to change evaluation order. List construction works with anything, so this way `(≢⍬)(≢⍬⍬)(≢⍬⍬⍬)` evaluates to `[0,2,3]`.
* `⎕UCS` gives a string of Unicode characters given a list of numbers. We can now generate any text we want.
* `⍎` is evaluate.
[Answer]
## ARM7 assembly - 8 bytes
```
CRS15,
```
And space and newline
With these characters, one can construct the following:
* Registers R1, R5, and R15 (R15 is the instruction pointer)
* The instruction RSC (Reverse Subtract with Carry)
* The condition code CC (do if carry clear)
* Any decimal number consisting of the numerals 1 and 5
These allow for data manipulation (subtract two registers), memory manipulation (specify destination as an address made up of 1s and 5s), and conditional jumping (R15 as the destination of a subtract with a condition code).
Comma, space, and newline are syntactic requirements of assemblers and cannot be avoided (in most cases).
One may be apt to point out that ARM does not have infinite pointers, and thus cannot be Turing complete. True, however no computer is Turing complete, and all of these languages are limited by their implementation. It is entirely possible to extend the ARM specification to allow for larger addresses. Ultimately, you'd have to let this one slide, and assume the best for the challenge.
Also, I admit to not knowing the minimum version of ARM this works in; I picked the one I know works
[Answer]
## PowerShell, ~~15~~ 14 characters
```
+[char](1)|iex
```
*Thanks to @Erik-the-Outgolfer for seeing that we don't need the `"` marks.*
I'm reasonably confident this is the smallest set we can have. Similar to the Python answers, this constructs up a program one character at a time (via things like `[char](1+1+1+1+1...+1+1)` to get the appropriate ASCII value) and then evaluating the string via `|iex`. For example, [here](https://tio.run/nexus/powershell#@x@dnJFYFKthqE0x1NSmnln0gEPNvSPRR6O@HRz@pZbd1PQDbcODVqbTNxaHZhjR3z7NmszUiv//AQ "PowerShell – TIO Nexus") is an example program that is equivalent to `"Test: "+(3+4)`. As a result, we can construct literally any PowerShell program with this method, and this is therefore Turing-Complete.
[Answer]
# Binary Lambda Calculus, Binary Mode, 3 characters (ascii-encoded)
```
HR.
```
Interpreted as incomplete segments of Binary Lambda Calculus, writing `\` for lambda, `*` for application and [De Bruijn indices](https://en.wikipedia.org/wiki/De_Bruijn_index) for variables:
```
H = 01001000 = * \ 1 \
R = 01010010 = * * \ 1
. = 00101110 = \ 1 3
```
Suppose `x` and `y` are valid terms.
Then,
```
H x
= * \ 1 \ x
= \ x
R x y
= * * \ 1 x y
= * x y
R .
= * .
= * \ 1 3
= 3
```
Thus we can use `H` as `\`, `R` as `*`, and `R.` as `3`.
For `2` and `1`, suppose we have any valid term `z`.
Then,
```
* \ 3 z = 2
* \ 2 z = 1
```
(Free variables get decremented in beta-reduction with De Bruijn indices)
As for the choice of `z`, we can use `z = \ \ \ 3` (or if we allow free variables in our program, we can just use `3`).
Finally, to show we don't need more than 3 variables, we can implement [SKI combinator calculus](https://en.wikipedia.org/wiki/SKI_combinator_calculus):
```
I = \ 1
K = \ \ 2
S = \ \ \ * * 3 1 * 2 1
```
Written using our 3 characters, these are
```
I = HRHRHR.HHHR.HHHR.
K = HHRHR.HHHR.
S = HHHRRR.RHRHR.HHHR.HHHR.RRHR.HHHR.RHRHR.HHHR.HHHR.
```
Which can be applied to each other in arbitrary ways using `R`.
[Answer]
# Scala, 12 chars
```
(),:;=>[]def
```
Using these characters, you can encode the SKI calculus.
I replaced the semicolons with newlines for readability:
```
def>[d,e,f]:(d=>(e=>f))=>(d=>e)=>(d=>f)=(dd:d=>e=>f)=>(ee:d=>e)=>(ff:d)=>dd(ff)(ee(ff))
def>>[d,e]:d=>e=>d=(dd:d)=>(ee:e)=>dd
def>>>[d]:d=>d=(>[d,d=>d,d])(>>[d,d=>d])(>>[d,d])
```
(Ab-)using the fact that you can call a method `>`, which will be seperated from the `def` by the parser to save the space.
Borrowed from [here](https://gist.github.com/othiym23/1034029) and optimised for this challenge.
[Answer]
# ARM assembler (gas), ~~14~~ 12 chars
Newline and space are included.
```
bdlrst:[],
```
This gives us exactly what we need for Turing completeness without self modifying code:
* 3 registers: `sl` (`r9`), `sb` (`r10`), and `lr`, the minumum for RISC without immediates
* Subtraction via `rsb`. Note that this is *reversed* subtraction, so it is `x = z - y`.
* Conditional branching via `rsbs`/`tst` and `bls`/`blt` (as well as conditional instructions)
* Arbitrary value generation by `ldr(s)b reg,label` and using encoded branch offsets (see below). Can generate [-128,255].
* Virtually unbounded memory storage via `ldr` and `str`, something [the other ARM answer](https://codegolf.stackexchange.com/a/111256/94093) didn't *address* (pun intended).
Even though we only have subtraction and shifting and no immediates, what we can do is read the encoding of a branch instruction, using only labels.
`b` encoding
```
31 30 29 28 27 26 25 24 23 22 21 20 .... 0
[ cond ][1][0][1][0][ (offset - 8) / 4 ]
```
(The offset - 8 is a weird quirk where `pc` actually points two instructions ahead).
For example:
```
foo:
b next
nop
nop
next:
```
will be encoded as so (ARM instructions are little endian):
```
00000000 <foo>:
0: 01 00 00 EA b <foo+0x8> // imm = #4
4: 00 00 A0 E1 nop // (mov r0, r0)
8: 00 00 A0 E1 nop // (mov r0, r0)
```
Therefore, if we wanted to get the value `1` into `sl`, we could do this:
```
ldrb sl, get_one
get_one:
b next // (pc + 4), [01]00 00 EA
(not executed)
(not executed)
next:
```
Similarly, `-1` can be done like so:
```
ldrsb sl, get_minus_one
get_minus_one:
b next // (pc - 4), [FF]FF FF EA
next:
```
Therefore, to prove Turing completeness, here is a Brainfuck prologue and translation. Labels are given readable names, but in actual code it would be a bunch of `bdlrst` gibberish and there will be no comments. I/O is done by read/write to a magic port of address 0.
*While this must be in a RWX section to initialize the tape, the instructions that will be overwritten will not be executed, therefore it does not count as self modifying code. The only requirement when assembled is that `pc` is set to the first instruction.*
```
///// Prologue
prologue:
// tape setup
bl tape_end // jump to end of tape, set lr to first cell
rsb sb, sb, sb // nop
tape_start:
// 8160 filler instructions to be overwritten
tape_end:
// code starts here
get_one:
b next // [01]00 00 EA
get_7:
b <get_7+36> // not writing that label
get_minus_one:
b next // [FF]FF FF EA
next:
// clear tape
ldrb sb, get_minus_one // sb = 255 (zero extended)
ldrb sl, get_7 // sl = 7
lsl sb, sb, sl // sb = sb << sl = 255 << 7 = 32640
clear:
ldrsb sl, get_one // sl = 1
rsbs sb, sl, sb // sb = sb - 1, set flags
rsb sl, sl, sl // sl = sl - sl = 0
strb sl, [lr, sb] // store 0
bls end_clear // if zero, jump to end of clear loop
b clear
end_clear:
///// Instruction translation
// >
ldrsb sl, get_minus_one // sl = -1
rsb lr, sl, lr // lr = lr - sl (lr = lr + 1)
// <
ldrsb sl, get_one // sl = 1
rsb lr, sl, lr // lr = lr - sl (lr = lr - 1)
// +
ldrb sb, [lr] // load cell from tape
ldrsb sl, get_minus_one // sl = -1
rsb sb, sl, sb // sb = sb - sl (sb = sb + 1)
strb sb, [lr] // store cell to tape
// -
ldrb sb, [lr] // load cell from tape
ldrsb sl, get_one // sl = 1
rsb sb, sl, sb // sb = sb - sl (sb = sb - 1)
strb sb, [lr] // store cell to tape
// [
loop_start: // label for start
ldrb sb, [lr] // load cell from tape
rsb sl, sl, sl // sl = sl - sl = 0
rsbs sb, sl, sb // sb = sb - sl (sb = sb - 0), set condition codes (TST will not set C flag)
bls loop_end // If sb was zero, the "lower or same" cond will be set, jump to end
loop_body:
// ]
b loop_start // Jump to beginning of loop
loop_end: // Label for end
// .
rsb sl, sl, sl // sl = nullptr
ldrb sb, [lr] // load from tape
strb sb, [sl] // store to I/O port
// ,
rsb sl, sl, sl // sl = nullptr
ldrb sb, [sl] // load from I/O port
strb sb, [lr] // store to tape
```
# Literally every GAS dialect, 9 chars
Again, newline and space
```
01.bety
```
The boring answer which allows encoding ANY opcode manually using `.byte 0b10101010`.
[Answer]
## PHP 7, 5 characters
```
(^.9)
```
<https://github.com/arxenix/phpfuck>
# How it works
* `9^99` -> `106`
+ use xor to generate numbers
* `(9).(9)` -> `'99'`
+ use `.` to concat numbers into strings
* `'09'^'1069'^'99'` -> `'80'`
+ xor 2 strings to get a string
* `'80'^0` -> `80`
+ (ab)use type juggling to cast a string to an int
* Using a combination of the above tricks, you can get all of the digits 0-9
* Can construct any string `/[0-9]+/` by concatenating digits
* Can obtain any number by casting to int
* Constructing arbitrary strings requires a bit more work...
+ `(99999999999...)` -> `INF`
- 309 9s gives us `INF`
+ `(INF).(9)` -> `'INF9'`
- Can now obtain char values in `/[a-zA-Z]/` range!
- e.g. `'INF9'^'00'^'33'^'99'` -> `'st'`
+ the only primitive we have for initially obtaining strings is concat, which gives us a length-2 string
+ we can generate `/[a-z]{2,}|[A-Z]{2,}/` , but getting single-character strings is not possible
* `'funcname'(param)`
+ call functions by simply calling their string name
+ function names are case-insensitive
* `strtok(0)` -> `false`
+ call strtok on a number to get `false`
+ `=== ('st'+'rt'+'OK')(0)`
* `(9).false` -> `'9'`
+ concat number with `false` to get a length-1 string
* `'rw'^'99'^'9'` -> `'r'`
+ extract first char of any string with xor
* Can now build arbitrary strings `/[a-zA-Z]/`
* `'CHr'(num)`
+ generate other characters (e.g. spaces)
* Can now build any string at all! `/.*/`
* `str_getcsv("a,b")` -> `["a", "b"]`
+ create string arrays by parsing a CSV
* `func(...["a", "b"])`
+ use spread operator to pass multiple arguments to a function
* `create_function("", "PAYLOAD")()`
+ use `create_function` to create a function w/ arbitrary PHP code and then call it
* Final payload looks like: `'create_function'(...str_getcsv(',"$PAYLOAD"'))`
# Previous Work
[PHPFuck](https://github.com/splitline/PHPFuck) by splitline - using 7 different characters `([+.^])`
[Answer]
## [Nock](http://urbit.org/docs/nock/definition/), 6 characters
```
[ ]012
```
Nock is a minimal virtual machine based on combinator reduction. It's memory model is a binary tree of bignums, and the [spec](https://github.com/urbit/urbit/blob/master/Spec/nock/5.txt) gzips to 340 bytes. There's a trivial transformation from Nock operations to the SKI combinators, which I stole from the Urbit [examples library](https://github.com/urbit/examples/blob/master/libs/ski/lib/ski.hoon) (which seems to originate from [this](https://www.reddit.com/r/urbit/comments/4t24bp/ski_calculus_to_nock_compiler_ski15fyr/) reddit discussion):
```
S = [[1 1 2] [1 0 1] [1 1] 0 1]
K = [[1 1] 0 1]
I = [0 1]
```
A more interesting way to do this would be to re-compile Nock with the Nock 4 operator, which is increment, to create the other operators. `[4 1 1]` is 2, `[4 4 1 1]` is 3, etc. S could alternatively be defined `[[1 4 1 1] [1 0 1] [1 1] 0 1]`, for example. I think that you still need a non-synthesized 2 operator in order to apply functions and reduce the 4, though.
[Answer]
## [Tildehyph](https://github.com/Tygrak/Tildehyph-lang), 2 characters
```
~-
```
The language uses only two characters a tilde and a hyphen. The easy answer why Tildehyph is Turing-complete is the fact that there is a [Brainfuck interpreter](https://github.com/Tygrak/Tildehyph-lang/blob/master/brainfuck.%7E-) created in it and Brainfuck is proven to be Turing-complete.
[Answer]
# [Unlambda](https://en.wikipedia.org/wiki/Unlambda), 3 characters
```
sk`
```
It's a turing tarpit of course.
[Answer]
## [BitCycle](http://esolangs.org/wiki/BitCycle), 8 characters
```
AB>/+~
```
plus space and newline.
My first demonstration of BitCycle's Turing-completeness was a [Bitwise Cyclic Tag interpreter](http://esolangs.org/wiki/BitCycle#Computational_class). But it turns out I can avoid quite a few extra characters by instead constructing a reduction, this time from a [cyclic tag system](http://esolangs.org/wiki/Cyclic_tag_system).
Consider any cyclic tag system, which consists of an ordered list of *productions*: strings of 0's and 1's (possibly including the empty string). Encode it as a string of 0's, 1's, and semicolons, with a semicolon following each production. For instance, the example from the Esolangs article, with productions (011, 10, 101), would be represented as `011;10;101;`. Then translate each element to a block of BitCycle instructions as follows:
**0**
```
>> ~
+~ ~
> +
> ~
> A~
B / ~ >>
+ ~ ~
```
**1**
```
>> ~
+~ /
> +
> ~
> A~
B / ~ >>
+ ~ ~
```
**;**
```
.
B / >
.
```
(The `.` characters here are placeholders and don't affect the function of the program. They should be replaced with spaces in the actual reduction.)
Concatenate these blocks side-by-side according to the three-character representation of the cyclic tag system. Then wrap the concatenation in this looping construct:
```
> ... ~
~ ~
```
where `...` represents the rest of the program, the `>` is on the same line as the `B` collectors, and the `~ ~` don't have anything but spaces in between them.
To test this, insert a `?` before the `>` in the wrapper and give the input string as a command-line argument. For example, here's the cyclic tag system `1;0;`:
```
>> ~ >> ~
+~ / +~ ~
> + > +
> ~ > ~
> A~ > A~
?> B / ~ >> B / > B / ~ >> B / > > ~
~ ~
1 ; 0 ;
+ ~ ~ + ~ ~
```
I will add a detailed explanation if people are interested--just leave a comment. Right now it's past my bedtime. :)
[Answer]
# J language, 7 char
To acheive Turing completeness, J can make do with the following 6 characters, plus space.
```
".u:1b
```
`1b` is a prefix for numbers meaning they are expressed in unary, so that e.g. `1b1111 1b11` is the array `4 2`. This can represent every positive integer.
Then, `u:` converts ASCII character codes to characters, and `".` evaluates a string as J code. This allows full access to the language.
## Is this minimal?
Probably. What I have is pretty darn lean.
No proper subset of these characters is sufficient, though there are a couple of equivalent sets like `do u:1b` and `".1b {a`.
J has no good facilities for doing something overly clever like embedding some lambda calculus or tag system, either, so I don't think a different strategy has a better shot, but I won't rule out the chance that I'm overlooking something sneaky.
[Answer]
# [///](http://esolangs.org/wiki////), 2 characters
```
/\
```
It was proven Turing Complete when someone wrote a Bitwise Cyclic Tag [interpreter](http://oerjan.nvg.org/esoteric/slashes/bct.sss) using it.
Shortened to 3 characters thanks to @Leo and @ETHproductions.
Shortened to 2 characters thanks to @ØrjanJohansen
[Answer]
# C (gcc), 19 bytes
```
main*fort(){}-=1[];
```
My implementation is Turing-complete because it can emulate another Turing-complete language.
32-bit cell Brainfuck interpreter (no I/O) using the commands as UTF-32 characters from the first command-line argument:
```
itr;nat;arr[111111-11111];rra=111-11-1-1-1-1-1-1-1;ora=111-11-1-1-1-1-1-1-1-1-1;aro=111-11-11-11-11-1-1-1-1-1-1-1;rar=111-11-11-11-11-1-1-1-1-1;min=111-11-11-11-11-11-11;aff=111-11-11-11-11-11-11-1-1;main(i,a)int**a;{for(i-=1;a[1][i];i-=-1){if(a[1][i]==aff)arr[itr]-=-1;if(a[1][i]==min)arr[itr]--;if(a[1][i]==aro)itr--;if(a[1][i]==rar)itr-=-1;if((a[1][i]==ora)*(arr[itr]==1-1))for(nat=1;nat;){i-=-1;nat-=-(a[1][i]==ora);nat-=a[1][i]==rra;}if((a[1][i]==rra)*(1-(arr[itr]==1-1)))for(nat=1;nat;){i-=1;nat-=-(a[1][i]==rra);nat-=a[1][i]==ora;}}}
```
aff is `+`.
min is `-`.
aro is `<`.
rar is `>`.
ora is `[`.
rra is `]`.
Note that I can't figure out how to run it yet but it should theoretically work.
[Answer]
# [Setanta](https://try-setanta.ie/), 14 characters
```
adghimnort(){}
```
Provides a way to encode the [SKI combinator calculus](https://en.wikipedia.org/wiki/SKI_combinator_calculus) as shown:
```
i := gniomh(g){toradh(g)}
k := gniomh(g){toradh(gniomh(n){toradh(g)})}
s := gniomh(g){toradh(gniomh(n){toradh(gniomh(i){toradh(g(i)(n(i)))})})}
```
Then inline `i`, `k`, and `s` as needed.
[Answer]
# 80386 machine code, 10 bytes
```
4c 44 fe 24 04 0c 0f 85 90 c3
```
We are assuming an environment where the system `call`s this program with plenty of stack space accessible by decrementing `esp`, and a `ret` with the initial `esp` will end this program. At start, `esp` will hold the address to return. A predefined size of data stored upwards from `esp + 4` will be the input, and a predefined size of data stored downwards from `esp - 1` will be the output.
Since Brainfuck is turing complete, implementing a Brainfuck-style computing model will also be turing complete. The following Brainfuck operators can be easily translated.
```
> dec esp ; 4c
< inc esp ; 44
+ inc byte [esp] ; fe 04 24
- dec byte [esp] ; fe 0c 24
```
Brainfuck has `[` and `]` for looping and conditional branching. To implement `]`, we first need to compare the stored value to zero.
```
inc byte [esp]
dec byte [esp]
```
This is a nice trick from @Bubbler that effectively does a compare-to-zero. Sometimes, you can also omit the comparison right after a `dec`.
80386 has two conditional jumps when the zero flag was not set.
```
jnz rel8 ; 75
jnz rel32 ; 0f 85
```
While `jnz rel8` has a shorter encoding, I'm not sure if it's enough to make the program turing complete, so we are instead using `jnz rel32`. Then, the relative offset can really be any byte without care, so we need,
```
nop ; 90
```
to pad the code so that the relative offset only consists of the usable bytes.
Finally to end the program,
```
ret ; c3
```
---
Here is an example program that takes two non-zero numbers as input, and outputs the sum.
```
sum:
inc esp ; 44
inc esp ; 44
inc esp ; 44
inc esp ; 44
.loop0:
dec esp ; 4c
dec esp ; 4c
dec esp ; 4c
dec esp ; 4c
dec esp ; 4c
inc byte [esp] ; fe 04 24
inc esp ; 44
inc esp ; 44
inc esp ; 44
inc esp ; 44
inc esp ; 44
dec byte [esp] ; fe 0c 24
; A LOT of `nop`s ; 90
jnz .loop0 ; 0f 85 fe fe fe fe
inc esp ; 44
.loop1:
dec esp ; 4c
dec esp ; 4c
dec esp ; 4c
dec esp ; 4c
dec esp ; 4c
dec esp ; 4c
inc byte [esp] ; fe 04 24
inc esp ; 44
inc esp ; 44
inc esp ; 44
inc esp ; 44
inc esp ; 44
inc esp ; 44
dec byte [esp] ; fe 0c 24
; A LOT of `nop`s ; 90
jnz .loop1 ; 0f 85 fe fe fe fe
dec esp ; 4c
dec esp ; 4c
dec esp ; 4c
dec esp ; 4c
dec esp ; 4c
ret
```
[Answer]
# [Emmental](https://esolangs.org/wiki/Emmental), 3 characters
```
#5?
```
Every character can be represented with these characters and '?' can execute them. For example, a program printing 'H':
```
##5#5#555?#5#555?#5#555?#5#555?#5#555?#5#555?#5#555?#5#555?#5#555??#5#555?#5#555?#5#555?#5#555?#5#555?#5#555?#5#555?#5#555?#5#555?#5#555?#5#555?#5#555?#5#555?#5#555?###5#5#555?#5#555?#5#555?#5#555?#5#555?#5#555?#5#555?#5#555?#5#555??##5#5#555?#5#555?#5#555?#5#555?#5#555?#5#555?#5#555?#5#555?#5#555??#555?#5#555?#5#555?#5#555?#5#555?#5#555?#5#555?#5#555?#5#555?#5#555??#5#555?#5#555?#5#555?#5#555?#5#555?#5#555?#5#555?#5#555?#5#555??
```
[Try it online!](https://tio.run/##S83NTc0rScz5/19Z2RQETU3tyaXsKdRPDEUNV1LDo5R7hWL9//8DAA)
[Answer]
# [Knight](https://github.com/knight-lang/knight-lang), 4 characters
```
EA1+
```
Similar to many other answers here, the plan is to build a string representing Knight code using `ASCII`, `1`, and `+`, and then use `EVAL` to run the resulting string as Knight code.
To build the string, we will build each individual character with `A`, `1`, and `+`. Then, we will concatenate each character together using `+`.
To build each character, we can simply just keep adding combinations of `111`, `11`, and `1` until the desired codepoint is reached, which we can then use `A` to convert the codepoint to a character. Though you may notice that if you actually tried to create a number with just `+` and `1`, you will need to include a space between at least one of the pairs of operands. For example, to create a `!`, you will have to do `A+11+11 11`; if you removed the space, then `1111` will be treated as a single number and you won't have enough arguments for one of the `+`'s.
To bypass that problem, we will take advantage of coercion. By adding a number with `ASCII 1` (making sure the number is the first argument), `A1` will be coerced to `0`, which will not affect the sum. The reason for using `A1` is to remove the need for spaces in the code. We can add all the numbers together as usual, but we will add one extra `+` at the end, which adds a number (`1`, `11`, `111`) to `A1`. But because `1` and `A1` can be differentiated as two different values without a space, we can write, for example, `+1A1` instead of `+1 A1`. Now, to create a `!`, you can do `A+11+11+11A1`.
Now that we have a strategy for building any character, we can now go on to concatenate all of them together into one string using `+`. We can do so with the following template (parentheses are just for formatting purposes):
```
(+ ... +) (A+...+1A1) (A+...+1A1)...
```
Then we can put `E` at the beginning to `EVAL` the string.
One final thing to note is the event that there is only one character in the string. Then we might have something like `EA+11+11+11+11+1+1+1+1A1` for evaluating `0`, but `EA` will be parsed as one function instead of two, so it might look like we need a space there. But we can simply concatenate a whitespace character like a space, which fixes the problem.
Here some Python code which can convert any inputted Knight code into equivalent Knight code using only the characters `EA1+`: [Try It Online!](https://tio.run/##TY6xagMxDIZ3PYUQBOy6JVW6lBYPGToUAlkKGa6mwyWhgsM@zs7Qpa9@keMEMtjoQ///2eNf@U3x5XWc5jmjR4njqRgLcsThEE226D3yG2BG55G@C8GgsS5Ne9NbPKYJey1hDtCn/UFX9EGQTkU1P4PkUsMBai7W3KCqu63zXReXS2Z@jAu969gmPSFAk@rLpv3miS0@IDm6GDfVeGdTN94KtCZ0uOmew6WgxsZ844arK1aiNRPAOEkspmrsPL97@ecdfy68OPlayVbO)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 3 characters
```
`/¢
```
This answer has been several months in the making. I've spent a lot of time trying to find a 3-character Turing-Complete subset of Vyxal, and honestly this answer was somewhat obvious.
As I showed [here](https://codegolf.stackexchange.com/a/264467/100664), the Vyxal builtin `¢` on its own is Turing-Complete, as it can interpret a variant of [Thue](https://esolangs.org/wiki/Thue). However, that answer takes input in a very specific format; here we need to construct the input within the program itself.
Essentially, `¢` takes two lists of strings and a string to perform replacements on, and repeatedly applies replacements until the string doesn't change, which is sufficient for Turing-Completeness provided the strings are sufficiently complex. Thue requires at least two different symbols to be Turing-Complete (then arbitrarily many symbols can be generated by concatenatng the two).
So, we need some way to construct arbitrary strings / string lists that contain more than two distinct symbols. That's what the other two characters are for. ``abc`` delimits a string of characters `abc`, and `/` splits a string by another string. By splitting by a constant string (which then can't be used) we can construct arbitrary sets of rules. There's just one snag.
As I said before, Thue needs to have two distinct symbols to be Turing-Complete. However, in strings we can only have the symbols `/¢`, and we need to use one to split by. This is further complicated by that, in strings, Vyxal decompresses non-unicode characters into common words and expressions - `¢¢` becomes `eyes` and `¢` becomes `[^aeiou]`. For the sake of simplicity I'm just going to use `¢¢` and pretend `¢` doesn't exist.
In short, we need to construct three symbols out of `/` and `¢¢`, such that no concatenation of any of them can contain any of them, ensuring they can be concatenated without causing problems. I came up with the set `//¢¢//`, `¢¢¢¢/¢¢¢¢`, `¢¢/¢¢/¢¢`, although something simpler probably exists.
With all of that, we can create arbitrarily complex replacement systems and emulate the behaviour of any Thue program, which is sufficient for Turing-Completeness! To do so, we push an initial string containing some combination of `¢¢¢¢/¢¢¢¢` and `¢¢/¢¢/¢¢`, then two sets of rules containing some combination of `//¢¢//`, `¢¢¢¢/¢¢¢¢`, `¢¢/¢¢/¢¢` and split them by `//¢¢//`, then simply run `¢`. [Here](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCJcbiMgU3ltYm9sczogXG4jIMKiwqLCosKiL8KiwqLCosKiwqLCosKiwqIvwqLCosKiwqLCosKiwqLCoi/CosKiwqLCoiA9IDFcbiMgwqLCosKiwqIvwqLCosKiwqLCosKiwqLCoi/CosKiwqLCosKiwqIvwqLCoi/CosKiICA9IDBcbiMgwqLCosKiwqIvwqLCosKiwqLCosKiL8KiwqIvwqLCosKiL8KiwqIvwqIgPSBeXG4jIMKiwqLCosKiL8KiwqLCosKiwqLCoi/CosKiL8KiwqLCosKiwqIvwqLCosKiwqIgPSAqXG4jIC8vwqLCoi8vID0gZGVsaW1cblxuIyBUaGlzIGJpdCBpcyBqdXN0IHByZXByb2Nlc3NpbmcgdGhlIGlucHV0LiBUaGUgaW5wdXQgY291bGQganVzdCBiZSBpbnNlcnRlZCBkaXJlY3RseSBpbnRvIHRoZSBwcm9ncmFtLlxuYDFgIGDCosKiwqLCoi/CosKiwqLCosKiwqLCosKiL8KiwqLCosKiwqLCosKiwqIvwqLCosKiwqJgIFZcbmAwYCBgwqLCosKiwqIvwqLCosKiwqLCosKiwqLCoi/CosKiwqLCosKiwqIvwqLCoi/CosKiYCBWXG5gXmAgYMKiwqLCosKiL8KiwqLCosKiwqLCoi/CosKiL8KiwqLCosKiL8KiwqIvwqLComAgVlxuYCpgIGDCosKiwqLCoi/CosKiwqLCosKiwqIvwqLCoi/CosKiwqLCosKiwqIvwqLCosKiwqJgIFZcblxuYElucHV0OiBgICwg4oCmXG46IMO4RCBgSW5wdXQgcmVwcmVzZW50YXRpb246IGAgLCAsXG5cbiMgSGVyZSdzIHRoZSBhY3R1YWwgcHJvZ3JhbVxuXG5gwqLCosKiwqIvwqLCosKiwqLCosKiwqLCoi/CosKiwqLCosKiwqLCosKiL8KiwqLCosKiLy/CosKiLy/CosKiwqLCoi/CosKiwqLCosKiwqIvwqLCoi/CosKiwqLCosKiwqIvwqLCosKiwqLCosKiwqLCoi/CosKiwqLCosKiwqLCosKiL8KiwqLCosKiwqLCoi/CosKiL8KiwqIvL8KiwqIvL8KiwqLCosKiL8KiwqLCosKiwqLCoi/CosKiL8KiwqLCosKiL8KiwqIvwqLCosKiwqLCosKiL8KiwqLCosKiwqLCosKiwqIvwqLCosKiwqLCosKiL8KiwqIvwqLComBgLy/CosKiLy9gL2DCosKiwqLCoi/CosKiwqLCosKiwqLCosKiL8KiwqLCosKiwqLCoi/CosKiL8KiwqLCosKiwqLCoi/CosKiwqLCosKiwqIvwqLCoi/CosKiwqLCosKiwqIvwqLCosKiwqIvL8KiwqIvL8KiwqLCosKiL8KiwqLCosKiwqLCosKiwqIvwqLCosKiwqLCosKiL8KiwqIvwqLCosKiwqLCosKiL8KiwqLCosKiwqLCoi/CosKiL8KiwqLCosKiwqLCoi/CosKiwqLCosKiwqLCosKiL8KiwqLCosKiwqLCoi/CosKiL8KiwqLCosKiwqLCoi/CosKiwqLCoi8vwqLCoi8vwqLCosKiwqIvwqLCosKiwqLCosKiL8KiwqIvwqLCosKiwqIvwqLCoi/CosKiYGAvL8KiwqIvL2AvwqJcblxuIyBwb3N0cHJvY2Vzc2luZ1xuXG5gT3V0cHV0OiBgICwg4oCmXG46IMO4RCBgT3V0cHV0IHJlcHJlc2VudGF0aW9uOiBgICwgLFxuXG5gwqLCosKiwqIvwqLCosKiwqLCosKiL8KiwqIvwqLCosKiwqLCosKiL8KiwqLCosKiYCBgKmAgVlxuYMKiwqLCosKiL8KiwqLCosKiwqLCoi/CosKiL8KiwqLCosKiL8KiwqIvwqLComAgYF5gIFZcblxuYFJlYWRhYmxlIHVuYXJ5IG91dHB1dDogYCAsIOKAplxuXG5gTnVtYmVyOmAsTOKAuSxcblxuIiwiIiwiXjEwMTEiXQ==)'s a extremely-overcomplicated binary-to-unary converter with some vague explanations of what's going on, and it's possible to expand this approach to emulate any possible Thue program.
I feel like three characters is optimal for this, and I can't imagine how a two-character solution would work.
[Answer]
# [Skull](https://esolangs.org/wiki/Skull), 9 characters
```
[]{}|:NUM
```
So Skull is an interesting language. You need `NUM` to set number mode. This adds to the amount of characters you need as you have to use one at the beginning of your programs. Also I mean that is the entire language except for 3 other characters.
`{ x [ y ] }` Increment or decrement the specified cell (x) by the specified number `(y)`
`{ x {` While the specified cell (x) is not 0...
`} }` End while
`| x |` Print out the specified cell (x) to the screen
This is a simple program doing addition (4+2)
```
:NUM: // set mode to NUM
{0[+4]} // set cell 0 to 4
{1[+2]} // set cell 1 to 2
{0{ // while cell 0 is not 0
{0[-1]} // subtract cell 0 by 1
{1[+1]} // add 1 to cell 1
}} // end while
|1| // print cell 1 (6)
```
] |
[Question]
[
Your task is to write a program or a function that prints an ASCII triangle. They look like this:
```
|\
| \
| \
----
```
Your program will take a single numeric input `n`, with the constraints `0 <= n <= 1000`. The above triangle had a value of `n=3`.
The ASCII triangle will have `n` backslashes (`\`) and vertical bars (`|`), `n+1` lines and dashes (`-`), and each line will have an amount of spaces equal to the line number (0-based, ie first line is line 0) besides the ultimate line.
## Examples:
Input:
```
4
```
Output:
```
|\
| \
| \
| \
-----
```
Input:
```
0
```
Output:
```
```
In this test case, the output must be empty. No whitespace.
Input:
```
1
```
Output:
```
|\
--
```
Input & output must be **exactly** how I specified.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so aim for the shortest code possible!
[Answer]
# C, 58 bytes
```
i;f(n){for(i=2*n;~i--;printf(i<n?"-":"|%*c\n",2*n-i,92));}
```
--
Thanks to @Steadybox who's comments on [this answer](https://codegolf.stackexchange.com/a/109512/16513) helped me shave a few bytes in my above solution
[Answer]
## Javascript (ES6), ~~97~~ ~~85~~ ~~81~~ ~~75~~ 74 bytes
```
n=>(g=(n,s)=>n?g(--n,`|${" ".repeat(n)}\\
`+s):s)(n,"")+"-".repeat(n&&n+1)
```
Turns out I wasn't using nearly enough recursion
```
f=n=>(g=(n,s)=>n?g(--n,`|${" ".repeat(n)}\\
`+s):s)(n,"")+"-".repeat(n&&n+1)
console.log(f(0))
console.log(f(1))
console.log(f(2))
console.log(f(3))
console.log(f(4))
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~16~~ ~~15~~ 16 bytes
Saved a byte thanks to *Adnan*
```
FðN×…|ÿ\}Dg'-×»?
```
[Try it online!](https://tio.run/nexus/05ab1e#ARsA5P//RsOwTsOX4oCmfMO/XH1EZyctw5fCuz///zQ "05AB1E – TIO Nexus")
**Explanation**
```
F } # for N in range [0 ... input-1]
ðN× # push <space> repeated N times
…|ÿ\ # to the middle of the string "|\"
Dg # get length of last string pushed
'-× # repeat "-" that many times
» # join strings by newline
? # print without newline
```
[Answer]
# [V](https://github.com/DJMcMayhem/V), ~~18~~ ~~17~~ 16 bytes
*1 byte saved thanks to @nmjcman101 for using another way of outputting nothing if the input is `0`*
```
é\é|ÀñÙá ñÒ-xÀ«D
```
[Try it online!](https://tio.run/nexus/v#@394ZczhlTWHGw5vPDzz8EIFIDVJt@Jww6HVLv///zcAAA "V – TIO Nexus")
Hexdump:
```
00000000: e95c e97c c0f1 d9e1 20f1 d22d 78c0 ab44 .\.|.... ..-x..D
```
### Explanation (outdated)
We first have a loop to check if the argument is `0`. If so, the code below executes (`|\` is written). Otherwise, nothing is written and the buffer is empty.
```
Àñ ñ " Argument times do:
é\é| " Write |\
h " Exit loop by creating a breaking error
```
Now that we got the top of the triangle, we need to create its body.
```
Àñ ñ " Argument times do:
Ù " Duplicate line, the cursor comes down
à<SPACE> " Append a space
```
Now we got one extra line at the bottom of the buffer. This has to be replaced with `-`s.
```
Ó- " Replace every character with a -
x " Delete the extra '-'
```
---
This answer would be shorter if we could whatever we want for input `0`
# [V](https://github.com/DJMcMayhem/V), ~~14~~ 13 bytes
```
é\é|ÀñÙá ñÒ-x
```
[Try it online!](https://tio.run/nexus/v#@394ZczhlTWHGw5vPDzz8EIFIDVJt@L///8mAA "V – TIO Nexus")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
’⁶x⁾|\jṄµ€Ṫ”-ṁ
```
[Try it online!](https://tio.run/nexus/jelly#ASQA2///4oCZ4oG2eOKBvnxcauG5hMK14oKs4bmq4oCdLeG5gf///zQ "Jelly – TIO Nexus")
### How it works.
```
’⁶x⁾|\jṄµ€Ṫ”-ṁ Main link. Argument: n
µ Combine the links to the left into a chain.
€ Map the chain over [1, ..., n]; for each k:
’ Decrement; yield k-1.
⁶x Repeat the space character k-1 times, yielding a string.
⁾\j Join the character array ['|', '\'], separating by those spaces.
Ṅ Print the result, followed by a linefeed.
Ṫ Tail; extract the last line.
This will yield 0 if the array is empty.
⁾-ṁ Mold the character '-' like that line (or 0), yielding a string
of an equal amount of hyphen-minus characters.
```
[Answer]
# C#, 93 bytes
```
n=>{var s=n>0?new string('-',n+1):"";while(n-->0)s="|"+new string(' ',n)+"\\\n"+s;return s;};
```
Anonymous function which returns the ASCII triangle as a string.
Full program with ungolfed, commented function and test cases:
```
using System;
class ASCIITriangles
{
static void Main()
{
Func<int, string> f =
n =>
{
// creates the triangle's bottom, made of dashes
// or an empty string if n == 0
var s = n > 0 ? new string('-', n + 1) : "";
// a bottom to top process
while ( n-- > 0)
// that creates each precedent line
s = "|" + new string(' ', n) + "\\\n" + s;
// and returns the resulting ASCII art
return s;
};
// test cases:
Console.WriteLine(f(4));
Console.WriteLine(f(0));
Console.WriteLine(f(1));
}
}
```
[Answer]
# [Python 2](https://docs.python.org/2/), 69 bytes
```
lambda x:'\n'.join(['|'+' '*n+'\\'for n in range(x)]+['-'*-~x*(x>0)])
```
[Try it online!](https://tio.run/nexus/python2#FcpBCsIwEAXQvaeY3Z8kbangqmAvkmSRopERnZZQIQvx6pG@9cvX0F7pvdwS1QlBMTxXUfb4woFg1SEE5LWQkiiVpI87VxOdRw/b/6rlOo8mmnYcOY7o9tnZTCfaiuhOmcU0P3bn7hL/ "Python 2 – TIO Nexus")
[Answer]
# [CJam](https://sourceforge.net/p/cjam), ~~24~~ ~~22~~ 21 bytes
*Saved 1 byte thanks to Martin Ender*
```
ri_{S*'|\'\N}%\_g+'-*
```
[Try it online!](https://tio.run/nexus/cjam#@1@UGV8drKVeE6Me41erGhOfrq2uq/X/vxEA "CJam – TIO Nexus")
**Explanation**
```
ri e# Take an integer from input
_ e# Duplicate it
{ e# Map the following to the range from 0 to input-1
S* e# Put that many spaces
'| e# Put a pipe
\ e# Swap the spaces and the pipe
'\ e# Put a backslash
N e# Put a newline
}% e# (end of map block)
\ e# Swap the top two stack elements (bring input to the top)
_g+ e# Add the input's signum to itself. Effectively this increments any
e# non-zero number and leaves zero as zero.
'-* e# Put that many dashes
```
[Answer]
# [PowerShell](https://github.com/PowerShell/PowerShell), ~~51~~ 67 bytes
```
param($n)if($n){1..$n|%{"|"+" "*--$_+"\"};write-host -n ('-'*++$n)}
```
[Try it online!](https://tio.run/nexus/powershell#@1@QWJSYq6GSp5mZBiKrDfX0VPJqVKuVapS0lRSUtHR1VeK1lWKUaq3LizJLUnUz8otLFHTzFDTUddW1tLWBWmr///9vAgA "PowerShell – TIO Nexus")
*(Byte increase to account for no trailing newline)*
Takes input `$n` and verifies it is non-zero. Then loops to construct the triangle, and finishes with a line of `-`. Implicit `Write-Output` happens at program completion.
[Answer]
# bash + printf, 68 bytes
```
for((;i<$1;))
{
a=$a-
printf "|%$[i++]s\\\\\n"
}
[ $a ] && echo $a-
```
Use "bash *program\_name* *number*" to run. Sample run:
```
bash-4.1$ bash triangle 0
bash-4.1$ bash triangle 1
|\
--
bash-4.1$ bash triangle 2
|\
| \
---
bash-4.1$ bash triangle 3
|\
| \
| \
----
```
[Answer]
# SmileBASIC, 51 bytes
```
INPUT N
FOR I=0TO N-1?"|";" "*I;"\
NEXT?"-"*(N+!!N)
```
[Answer]
# [Retina](https://github.com/m-ender/retina), 39 bytes
```
.*
$*
*\`(?<=(.*)).
|$.1$* \¶
1
-
-$
--
```
[**Try it online**](https://tio.run/nexus/retina#@6@nxaWixaUVk6Bhb2OroaelqanHVaOiZ6iipRBzaBuXIZcul64Kl67u///GAA)
Convert decimal input to unary. Replace each `1` with `|<N-1 spaces>\¶`, print, and undo replace. Replace each `1` with a hyphen, and the last hyphen with 2 hyphens. Tadaa!
[Answer]
# Common Lisp, ~~89~~ 86 bytes
Creates an anonymous function that takes the n input and prints the triangle to `*standard-output*` (stdout, by default).
## Golfed
```
(lambda(n)(when(< 0 n)(dotimes(i n)(format t"|~v@t\\~%"i))(format t"~v,,,'-<~>"(1+ n))))
```
## Ungolfed
```
(lambda (n)
(when (< 0 n)
(dotimes (i n)
(format t "|~v@t\\~%" i))
(format t "~v,,,'-<~>" (1+ n))))
```
I'm sure I could make this shorter somehow.
[Answer]
## C ~~101~~ ~~93~~ 75 bytes
```
f(n){i;for(i=0;i++<n;)printf("|%*c\n",i,92);for(;n--+1;)printf("-");}
```
Ungolfed version
```
void f(int n)
{
int i;
for(i=0;i++<n;)
printf("|%*c\n",i,92);
for(;n--+1;)
printf("-");
}
```
@Steadybox Thanks for pointing out, makes a lot of sense.
[Answer]
# [Python 3](https://docs.python.org/3/), 60 bytes
```
f=lambda n,k=0:k<n and'|'+' '*k+'\\\n'+f(n,k+1)or'-'[:n]*-~n
```
[Try it online!](https://tio.run/nexus/python3#@59mm5OYm5SSqJCnk21rYJVtk6eQmJeiXqOura6grpWtrR4TE5Onrp2mAZTXNtTML1LXVY@2yovV0q3L@19QlJlXopGmYaKp@R8A "Python 3 – TIO Nexus")
Two more solutions with the same byte count.
```
f=lambda n,k=0:n and'|'+' '*k+'\\\n'+f(n-1,k+1)or-~k*'-'[:k]
f=lambda n,s='|':-~n*'-'[:n]if s[n:]else s+'\\\n'+f(n,s+' ')
```
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 98 bytes
```
256?dse1+d[q]st1=t^124*23562+dsaP2sk[[lkd256r^32*la+dsaPd1+skle>y]srle1<r]dsyx[45Ple1-dse0!>q]dsqx
```
[Try it online!](https://tio.run/nexus/dc#HYzLCoAgEAC/pWsStFt26vEL3sVAWiFQCt0O9eGdTTrOMExGOSzEDgTpaPiC6VoB@xo7OaAgtgrZax08lTCtHdbB/ppAsA9ufgyn4GBMhvi5dS9VoaYc22qOxcU7Z/keZ7PZbXcf "dc – TIO Nexus")
### Explanation
This takes due advantage of dc's `P` command, which utilizes conversion to base `256` on most systems. Therefore, for any input `n`, the program first raises `256` to the `n + 1`th power, multiplies the result by `124` (ASCII character `|`), and then adds `256*92+10=23562` to the product (where `92` is equivalent to the character `\` and `10` is the decimal value of the new-line (`\n`)). This results in a decimal number that when converted to base `256` with `P` results in the output `|\\n` where `\n` is the literal new-line character. A duplicate of this decimal number is also stored on top of register `a`.
Then, a "macro-loop" is invoked, as long as `n > 1`, in which a counter is incremented until `n`, beginning from `2`, and, as the 3rd through `n`th base `256` digits are unset, `256` is raised to each of those increments, a result which is then multiplied by `32` (the ASCII single space character). Then the value on top of register `a` is incremented by the resulting product, thus, on each iteration, setting each one of the unset base `256` digits in the between the `|` and the `\` characters to a single space.
Finally, after all `n-1` lines have been output, another "macro-loop" is invoked in which all the `n+1` dashes are output through the feeding of `45` to `P` on each iteration.
*Note:* The `[q]st1=t` segment makes sure that nothing is output for the input `0` by checking if the incremented input is equal to one, and if it is, simply executes the macro `[q]` which exits the program.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes
```
Nβ¿β«↓β→⁺¹β↖↖β»
```
[Try it online!](https://tio.run/nexus/charcoal#@/9@z7pzmw7tB@LVj9omn9v0qG3So8Zdh3aCWNOACCix@/9/AwA "Charcoal – TIO Nexus")
## Breakdown
```
Nβ¿β«↓β→⁺¹β↖↖β»
Nβ assign input to variable β
¿β« » if β != 0:
↓β draw vertical line β bars long
→⁺¹β draw horizontal line β+1 dashes long
↖ move cursor up one line and left one character
↖β draw diagonal line β slashes long
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 20 bytes
Saved 2 bytes thanks to @ETHproductions
```
o@'|+SpX +'\Ãp-pUÄ)·
```
[Try it online!](https://tio.run/nexus/japt#@5/voF6jHVwQoaCtHnO4@dB27SBtdd2C0MMt//@bAAA "Japt – TIO Nexus")
### Explanation
```
o@'|+SpX +'\Ãp-pUÄ)·
o // Creates a range from 0 to input
@ // Iterate through the array
'|+ // "|" +
SpX + // S (" ") repeated X (index) times +
'\Ã // "\" }
p-pU // "-" repeated U (input) +1 times
Ä)· // Join with newlines
```
[Answer]
# J, 20 bytes
*-13 bytes thanks to bob*
```
*#' \|-'{~3,~2,.=@i.
```
[Try it online!](https://tio.run/##y/qfVqxga6VgoADE/7WU1RVianTVq@uMdeqMdPRsHTL1/mtyKekpqKfZWqkr6CjUWimkFXNxpSZn5CukKRjCGKb/AQ "J – Try It Online")
## original: 33 bytes
```
(#&'| \'@(1,1,~])"0 i.),('-'#~>:)
```
### ungolfed
```
(#&'| \' @ (1,1,~])"0 i.) , ('-'#~>:)
```
[Try it online!](https://tio.run/##y/r/P81WT0FDWU29RiFG3UHDUMdQpy5WU8lAIVNPU0dDXVdduc7OSpMrNTkjXyFNweT/fwA "J – Try It Online")
[Answer]
# Commodore BASIC (C64/128, TheC64 & Mini, VIC-20, PET, C16/+4) - 46 BASIC Bytes
```
0inputn:ifnthenfori=1ton:?"{shift+B}{left}"spc(i)"{shift+M}":next:fori=.ton:print"-";:next
```
There is a sanity check for zero, but any other positive integer will work.
Note, a C64 has 25 rows and 40 columns text (some PETs and the C128 in VDC mode has 80 columns, the VIC-20 is 22 columns by 23 rows) so the output will be skewed if you exceed the screen limit in either direction.
I've added a screenshot so that you may see the PETSCII characters that I can't make happen in this listing.
[![Commodore C64 Triangle challenge](https://i.stack.imgur.com/eqgz8.png)](https://i.stack.imgur.com/eqgz8.png)
[Answer]
## Pyke, ~~18~~ 17 bytes
```
I Fd*\|R\\s)Qh\-*
```
[Try it here!](http://pyke.catbus.co.uk/?code=I+Fd%2a%5C%7CR%5C%5Cs%29Qh%5C-%2a&input=4)
[Answer]
# Python2, 73 bytes
```
n=input()
w=0
exec'print"|"+" "*w+"\\\\"+("\\n"+"-"*-~n)*(w>n-2);w+=1;'*n
```
A full program. I also tried string interpolation for the last line, but it turned out be a couple bytes longer :/
```
exec'print"|%s\\\\%s"%(" "*w,("\\n"+"-"*-~n)*(w>n-2));w+=1;'*n
```
Another solution at 73 bytes:
```
n=j=input()
exec'print"|"+" "*(n-j)+"\\\\"+("\\n"+"-"*-~n)*(j<2);j-=1;'*n
```
# Test cases
```
0:
1:
|\
--
2:
|\
| \
---
3:
|\
| \
| \
----
6:
|\
| \
| \
| \
| \
| \
-------
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 19 bytes
```
?'\|- '2GXyYc!3Yc!)
```
[Try it online!](https://tio.run/nexus/matl#@2@vHlOjq6Bu5B5RGZmsaAzEmv//GwMA "MATL – TIO Nexus")
```
? % Implicit input. If non-zero
'\|- ' % Push this string
2 % Push 2
G % Push input
Xy % Identity matrix of that size
Yc % Prepend a column of 2's to that matrix
! % Transpose
3 % Push 3
Yc % Postpend a column of 3's to the matrix
! % Transpose
) % Index into string
% Implicit end. Implicit display
```
[Answer]
## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 41 bytes
```
:~a>0|[a|?@|`+space$(b-1)+@\`][a+1|Z=Z+@-
```
Explanation
```
:~a>0| Gets a, and checks if a > 0
If it isn't the program quits without printing anything
[a| For b=1; b <= a; b++
?@|`+ Print "|"
space$ and a number of spaces
(b-1) euqal to our current 1-based line - 1
+@\` and a "\"
] NEXT
[a+1| FOR c=1; c <= a+1; c++
Z=Z+@- Add a dash to Z$
Z$ gets printed implicitly at the end of the program, if it holds anything
The last string literal, IF and second FOR loop are closed implicitly.
```
[Answer]
## R, 101 bytes
```
for(i in 1:(n=scan())){stopifnot(n>0);cat("|",rep(" ",i-1),"\\\n",sep="")};cat("-",rep("-",n),sep="")
```
This code complies with the `n=0` test-case if you only consider `STDOUT` !
Indeed, the `stopifnot(n>0)` part stops the script execution, displays nothing to `STDOUT` but writes `Error: n > 0 is not TRUE` to `SDTERR`.
**Ungolfed :**
```
for(i in 1:(n=scan()))
{
stopifnot(n>0)
cat("|", rep(" ", i-1), "\\\n", sep = "")
}
cat("-", rep("-", n), sep = "")
```
[Answer]
# [Python 2](https://docs.python.org/2/), 62 bytes
```
n=input();s='\\'
exec"print'|'+s;s=' '+s;"*n
if n:print'-'*-~n
```
[Try it online!](https://tio.run/nexus/python2#@59nm5lXUFqioWldbKseE6POlVqRmqxUUJSZV6Jeo65dDBJWANFKWnlcmWkKeVYQOV11Ld26vP//TQA "Python 2 – TIO Nexus")
Prints line by line, each time adding another space before the backslash. If a function that doesn't print would be allowed, that would likely be shorter.
[Answer]
## JavaScript (ES6), 71 bytes
```
f=
n=>console.log(' '.repeat(n).replace(/./g,'|$`\\\n')+'-'.repeat(n+!!n))
```
```
<form onsubmit=f(+i.value);return!true><input id=i type=number><input type=submit value=Go!>
```
Outputs to the console. Save 6 bytes if printing to the SpiderMonkey JavaScript shell is acceptable. Save 13 bytes if returning the output is acceptable.
[Answer]
# Befunge-98, 68 bytes
```
&:!#@_000pv<
:kg00 ',|'<|`g00:p00+1g00,a,\'$,kg00
00:k+1g00-'<@,k+1g
```
[Answer]
# [Python 2](https://docs.python.org/2/), 67 bytes
Another function in Python 2, using `rjust`.
```
lambda n:('|'.join(map('\\\n'.rjust,range(n+2)))+'-'*-~n)[4:]*(n>0)
```
[Try it online!](https://tio.run/nexus/python2#DcIxDoMwDADAva/wZhsCohVTJPgIYQiiqYyKiULYqn497enC4Mrb78vqQS3hB9vtEKXdR0LnnGKbtuvMJnl9PUnrBzPX2GDVfJWn3s4V6dhxCUcCAdH/eGVie4OYRDMEEi5TZ@6mn38 "Python 2 – TIO Nexus")
[Answer]
# Perl, 63 bytes
```
$n=shift;print'|',$"x--$_,"\\\n"for 1..$n;print'-'x++$n,$/if$n
```
Ungolfed:
```
$ perl -MO=Deparse triangle.pl
$n = shift @ARGV;
print '|', $" x --$_, "\\\n" foreach (1 .. $n);
print '-' x ++$n, $/ if $n;
```
`$"` is the list separator, which defaults to " ". `$/` is the output record separator, which defaults to "\n". `$_` is the implicit loop variable.
] |
[Question]
[
Long-time lurker, first-time poster. So here goes.
In the Wikipedia page for [quine](https://en.wikipedia.org/wiki/Quine_%28computing%29#.22Cheating.22_quines), it says that "a quine is considered to be 'cheating' if it looks at its own source code." Your task is to make one of these "cheating quines" that reads its own source code.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes - *in each language* - wins. This means that a 5-byte Pyth script would not beat a 21-byte Python script - but a 15-byte Python script would.
You must use file I/O to read the source code, so the following JavaScript code, taken from the official Wikipedia page, is invalid:
```
function a() {
document.write(a, "a()");
}
a()
```
It must access the source code of the file *on disk*.
**You are not allowed to specify the file name. You must make it detect the filename itself.**
Everyone clear? Go!
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 18 bytes
```
print1(readstr[1])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWmwqKMvNKDDWKUhNTikuKog1jNSESUHmYOgA)
The function `readstr` reads every lines as strings form a file. When `readstr` takes no input, it reads the source file.
[Answer]
# [C (clang)](http://clang.llvm.org/), 47 (46?) bytes
```
main(s){write(!!read(open(__FILE__,0),&s,47));}
```
[Try it online!](https://tio.run/##S9ZNzknMS///PzcxM0@jWLO6vCizJFVDUbEoNTFFI78gNU8jPt7N08c1Pl7HQFNHrVjHxFxT07r2/38A "C (clang) – Try It Online")
This **will** corrupt the stack and segfault, but not before printing the correct output.
If executing in a terminal we can do 46 bytes printing to `stdin`:
```
main(s){write(!read(open(__FILE__,0),&s,46));}
```
[Answer]
# Bash, 18 Bytes
```
history|tail -c18
```
**Note:** *Technically* this is not allowed because it gets history from memory, and not from disk.
## Bytes:
```
echo 'history|tail -c18' > quine
wc -c quine
18 quine
```
18 bytes (including the newline)
## Explanation:
`history` gets the bash history from memory and `tail` grabs the last 18 characters. This is a more proper quine than `cat $0` and `#!/bin/cat` because it includes the newline.
`echo "$BASH_COMMAND"` can be used to do the same thing for an extra 1 character.
[Answer]
## Tcl, 37 bytes
```
chan copy [open [info script]] stdout
```
The older, more self explanatory version (43 bytes):
```
puts -nonewline [read [open [info script]]]
```
[Answer]
# Lua, 59 characters
```
print(io.open(debug.getinfo(1,'S').source:sub(2)):read'*a')
```
Sample run:
```
bash-4.3$ lua quine.lua
print(io.open(debug.getinfo(1,'S').source:sub(2)):read'*a')
```
[Answer]
# C++, 93 bytes
```
#include <iostream>
#include <fstream>
main(){std::fstream f(__FILE__);std::cout<<f.rdbuf();}
```
I wanted to do a “pure” C++ version…and I have to say that it doesn't do too badly: it's down to 54 bytes if I can do without including the headers.
[Answer]
# A Groovy ~~103~~ 100 bytes!
Yes I know I'm evil
I stay in line with the other JVM answers (Java, Scala) to make this answer.
```
class X{static def main(String[]a){new X()}
def X(){print new File(getClass().name+'.groovy').text}}
```
[Answer]
# Emacs Lisp (93 Bytes)
```
:; emacs -Q -script $0; exit
(find-file (nth 2 command-line-args))
(message (buffer-string))
```
The first line calls the program in your normal shell and exits (to prevent the rest also being evaluated). `command-line-args` will be a list of three strings, `"emacs"`, `"-scriptload"` and the name of your file. `find-file` will open that file and make it the current buffer, so that `(message (buffer-string))` will write it to `stdout` as `-script` redirects messages there.
It should be noted, that `-Q` may not be necessary if your Emacs doesn't print other messages during startup, so that the first line could be shortened to `#!emacs -script`, shortening this to 81 bytes, but as it is highly unlikely that init and site-lisp files produce 0 messages at all, this cannot be assumed.
[Answer]
# Matlab, 32 bytes
```
disp(fileread([mfilename,'.m']))
```
[Answer]
# [APL](http://goo.gl/9KrKoM), 8 bytes (non-competing)
APL does not use source files for single functions, rather a whole workspace (a machine-readable collection of token-representations) is saved and loaded, so I guess this is not allowed:
```
f
⎕CR'f'
```
(`⎕CR` is Character Representation) as the program reads its current definition in memory (the loaded workspace), which may have been modified from the source in the file.
[Answer]
# HTML and Javascript, 88 Bytes
```
<head></head><body><svg onload="alert(document.documentElement.innerHTML)"></svg></body>
```
Had to add `<head></head><body></svg></body>` because that's what the browser outputs regardless of the original file.
[Answer]
# [Lua](https://www.lua.org), ~~32~~ 29 bytes
*3 bytes saved thanks to Jonathan Frech*
```
print(io.open(arg[0]):read())
```
### [Try it online!](https://tio.run/##yylN/P@/oCgzr0QjM18vvyA1TyOxKD3aIFbTqig1MUVDU/P/fwA "Lua – Try It Online")
## How?
Lua uses the `arg` table to store it's arguments, the script name is always stored at index `0` of this table despite the fact there are no further arguments. After using this table to get the name of the file, printing it was as easy as opening the file and reading its content.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg) / POSIX shell, 16 bytes
```
run 'cat',$?FILE
```
[Try it online!](https://tio.run/##K0gtyjH7/7@oNE9BPTmxRF1Hxd7N08f1/38A "Perl 6 – Try It Online")
[Answer]
## [CopyPasta Language](https://esolangs.org/wiki/CopyPasta_Language), 32 bytes
But I think this is interesting enough to compete here.
```
CopyFile
TheFuckingCode
Pasta!
```
Copy the source code, display the clipboard, and stop the program.
[Answer]
# [stacked](https://github.com/ConorOBrien-Foxx/stacked), 11 bytes
```
program put
```
[Try it here!](https://conorobrien-foxx.github.io/stacked/stacked.html)
Outputs the program stored in the `program` variable. Simple!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly) `u`, 26 bytes
```
“open(sys.argv[2])”ŒV
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw5z8gtQ8jeLKYr3EovSyaKNYzUcNc49OCvv/HwA "Jelly – Try It Online")
*Not* encoded in Jelly's SBCS, because 1. by meta consensus on flags Jelly `u` is a different language from Jelly (so it's not like I'm handicapping myself or anything), 2. I'm having some difficulties deciding on what form of output would be valid for an SBCS Jelly cheating quine, and 3. I'm having some difficulties [actually executing on the methods I've considered](https://tio.run/##S0oszvj/v6CyJCM/z1jBxkbB1d@NK60oP1chKzUnp1IhM7cgv6hEITk/JTW@IDE9laugKD@9KDFXwVZB/VHDnBPbrY9MP7b0UeP2h7u7c80Ob4g/PP/Q5sMTVA8ve7iz7cT6wxOP7Nc5tPvopDCg/OEZXupc5ZklGQr5Bal5GupQo@LTMnNS1XXUy5PUNRUSixXSrLgU0vTKizJLUjWSKktSizXgtutl5qWkVmgkayqk5RcpJCtk5inA3JOZBuHD1WpqcoH8kpxYooBsEVdqckY@F8RzaSgy//8DAA) (note that that's not even shorter than this).
```
“open(sys.argv[2])”ŒV Evaluate "open(sys.argv[2])" as Python, within Jelly's interpreter.py.
sys.argv Get the arguments with which this was invoked on the command line.
(jelly fu [whatever the file's called])
[2] Take the third argument,
open( ) and open the file at that location.
ŒV Iterate through the file object, obtaining a Jelly string of its contents.
```
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), ~~43~~ ~~39~~ ~~30~~ 27 bytes
```
’ƒÛ(__£Ø__('Ë‚').Òœv[1])’.E
```
[Try it online!](https://tio.run/##MzBNTDJM/f//UcPMY5MOz9aIjz@0@PCM@HgN9cPdjxpmqWvqHZ50dHJZtGGsJlCJnuv//wA "05AB1E (legacy) – Try It Online") I would've used the rewrite, if only I knew Elixir… Output doesn't contain the program, however it is the program in a singleton iterable object (a file). [This is allowed](https://codegolf.meta.stackexchange.com/a/11884/94066).
```
’ƒÛ(__£Ø__('Ë‚').Òœv[1])’.E # full program
’ƒÛ(__£Ø__('Ë‚').Òœv[1])’ # push "open(__import__('sys').argv[1])"...
.E # evaluated as Python code
# implicit output
============================================================================
open(__import__('sys').argv[1]) # full Python program
open( ) # return file at path...
[1] # second...
__import__('sys').argv # command-line argument
```
**Note:** This program assumes no command-line flags or extra arguments are passed. If this assumption is not allowed, it can be fixed at a cost of 1 byte by adding a `-` before the `1`.
[Answer]
# [Julia 1.0](http://julialang.org/), ~~29~~ 26 bytes
```
print(readline(@__FILE__))
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/v6AoM69Eoyg1MSUnMy9VwyE@3s3TxzU@XlPz/38A "Julia 1.0 – Try It Online")
[Answer]
# Processing, 48 bytes
```
print(loadStrings(getClass().getName()+".pde"));
```
[Answer]
# Nim, 43 bytes
```
import os
echo readFile(paramStr(0)&".nim")
```
[Answer]
# JavaScript ([Deno](https://deno.dev/)), ~~49~~ 47 bytes
```
console.log(Deno.readFileSync(import.meta.url))
```
[Answer]
# C, 31 bytes
```
main(){system("cat "__FILE__);}
```
Works perfectly...
[Answer]
# [Nim](https://nim-lang.org/), 39 bytes
```
stdout.write currentSourcePath.readFile
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m704LzN3wYKlpSVpuhY31YtLUvJLS_TKizJLUhWSS4uKUvNKgvNLi5JTAxJLMvSKUhNT3DJzUiHKobpgugE)
] |
[Question]
[
It's Christmas everybody, and here's a code-golf challenge to celebrate. You need to make a program to print out a present. Specifically, the words "Merry Christmas". BUT, there is a catch: this program must only work if it is the 25th of December. If the code is run on any other day, then the program should crash.
This is Code-Golf, so the answer with the least amount of bytes wins.
Merry Christmas!
[Answer]
## Pyke, 21 bytes
```
.dↄґ6C65h*325q/Al
```
[Try it here!](http://pyke.catbus.co.uk/?code=.d%02%E2%86%84%D2%916C65h%2a325q%2FAl)
```
C65h* - multiply the day by the (current month + 1)
325q - ^ == 325
6 / - 6 / ^
.dↄґ - load "merry christmas"
Al - ^.capwords()
```
Or 18 bytes noncompetitive.
```
.dↄґ6Cs6Y1q/Al
```
Exactly the same except for this section:
```
Cs6Y1q
C - get_time()
s6 - add 1 week
Y - get day of the year
1q - ^ == 1
```
[Try it here!](http://pyke.catbus.co.uk/?code=.d%02%E2%86%84%D2%916Cs6Y1q%2FAl)
[Answer]
# JavaScript, ~~55~~ ~~53~~ 46 bytes
Note: this has only been tested in Google Chrome, program may behave differently from browser to browser (or device to device)
*2 bytes saved thanks to @ConorO'Brien*
*7 bytes saved thanks to @ETHProductions*
```
alert(/c 25/.test(Date())?"Merry Christmas":a)
```
Exits with `Uncaught ReferenceError: a is not defined` if the date is not `Dec 25`. I'm not really sure if this counts as crashing
```
alert(/c 25/.test(Date())?"Merry Christmas":a)
```
[Answer]
# Python 3, ~~66~~ 63 bytes
Thanks to ideas from JavaScript / ES answers here I managed to squeeze some bytes. Index a dictionary - non-existent keys will raise a `KeyError`. The following code works in local time zone
```
import time;print({1:'Merry Christmas'}['c 25'in time.ctime()])
```
The output format for `ctime` isn't locale-dependent - the format is always ~ `'Sun Dec 25 19:23:05 2016'`. Since only in December does the 3-letter abbreviation end with `c`, it is safe to use `'c 25'in time.ctime()` here.
---
**Previous version:**
This works in UTC time zone. For local time zone one needs to `s/gm/local` for 3 more bytes. For Python 2, one can remove parentheses from `print` for 65 bytes.
```
import time;print({(12,25):'Merry Christmas'}[time.gmtime()[1:3]])
```
The construct throws `KeyError` on other dates:
```
>>> import time;print({(1,1):'Happy New Year'}[time.gmtime()[1:3]])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: (12, 25)
```
[Answer]
# PHP, ~~39~~ 38 bytes, not competing (doesn´t crash)
```
<?=date(md)-1225?"":"Merry Christmas";
```
or
```
<?date(md)-1225?die:0?>Merry Christmas
```
or
```
<?=["Merry Christmas"][date(md)-1225];
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~68~~ ~~67~~ 65 bytes
-1 with thanks to @muddyfish
Thanks to @AnttiHaapala for the idea that saved another couple.
```
import time;print['Merry Christmas'][(12,25)!=time.gmtime()[1:3]]
```
[Try it online!](https://tio.run/nexus/python2#@5@ZW5BfVKJQkpmbal1QlJlXEq3um1pUVKngnFGUWVySm1isHhutYWikY2SqqWgLUqaXnguiNDSjDa2MY2P//wcA "Python 2 – TIO Nexus")
Throws an IndexError if not 25th Dec.
Non-competing version for 59 bytes as it only works for non Leap years (uses day of year which is 360 this year but 361 in leap years)
```
import time;print['Merry Christmas'][360!=time.gmtime()[7]]
```
[Answer]
## R, 52 61 58 bytes
```
`if`(format(Sys.Date(),"%m%d")=="1225","Merry Christmas",)
```
If the current date is not the 25th of December then an error is returned because no third argument is supplied to `if`.
Edit: Fixed a silly error
[Answer]
My first time around here... Started with the best language ever for this job:
# Java, ~~200~~ ~~188~~ bytes (thanks to @Daniel Gray), 186 bytes removing "ln" from print.
```
import java.util.*;public class a{public static void main(String[]r){Calendar c=Calendar.getInstance();if(!(c.get(2)==11&&c.get(5)==25)){int i=1/0;}System.out.print("Merry Christmas");}}
```
[Try it here!](https://www.compilejava.net/)
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~34~~ 33 bytes
```
'Merry Christmas'IHh&Z'5U12h=?}Yl
```
This works in [current version (19.7.0)](https://github.com/lmendo/MATL/releases/tag/19.7.0) of the language. To cause the error, the following code exploits the fact that the logarithm of a string gives an error (this may change in future versions).
[Try it online!](https://tio.run/nexus/matl#@6/um1pUVKngnFGUWVySm1is7umRoRalbhpqaJRha18bmfP/PwA "MATL – TIO Nexus")
### Explanation
```
'Merry Christmas' % Push this string
IHh % Push 3, then 2, concatenate: gives array [3 2]
&Z' % Get 3rd and 2nd outputs of clock vector: current day and month
5U12h % Push 5, square, push 12, concatenate: gives [25 12]
= % Compare if corresponding entries are equal in the two arrays
? % If all entries are equal: do nothing
} % Else
Yl % Logarithm. Gives an error when applied on a string
% End (implicit). Display (implicit)
```
[Answer]
## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 48 bytes
```
~left$$|(_D,5)=@12-25||?@Merry Christmas|\?a(12)
```
Explanation:
```
~ IF
left$$|(_D,5) the date string starts with
=@12-25| the string "12-25"
| THEN
[[email protected]](/cdn-cgi/l/email-protection)| PRINT "Merry Christmas"
\ ELSE
?a(12) Print the twelfth index of an undefined array.
Since there are only 11 elements in undefined arrays, this
results in an index-out-of-bounds error.
The the IF statement is auto-closed by QBIC.
```
This assumes American `MM-DD` date notation. This would be shorter if I'd finally make a Substring function in QBIC.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~32~~ 21 bytes
Saved 11 bytes thanks to Adnan's string compression :) .
```
1žfže‚12D·>‚Q÷”ÞٌΔ×
```
## Explanation
```
žfže‚ Push [current month, current day]
12D·>‚ Push [12, 25]
Q Push tmp = 1 if the two arrays are equal, tmp = 0 otherwise
1 ÷ Evaluate x = 1/tmp. If tmp = 0 a division by 0 exception is thrown
”ÞÙŒÎ”× Implicitly display "Merry Christmas" x times
```
[Try it online!](https://tio.run/nexus/05ab1e#@294dF/a0X2pjxpmGRq5HNpuB2QEHt7@qGHu4XmHZx6ddLgPxJz@/z8A "05AB1E – TIO Nexus")
I did what came to mind first, so there may be better approaches for this one. But PPCG deserves a Merry Christmas in 05AB1E as well ;) .
[Answer]
# C# / CS Script ~~106~~ ~~100~~ 99 bytes
99 byte solution
```
using System;int i;Console.WriteLine(DateTime.Now.ToString("dM")=="2512"?"Merry Christmas":i/0+"");
```
[Try it here!](https://dotnetfiddle.net/VNCSxf)
100 byte solution (prefer this one... a bit different)
```
using System;int i;Console.WriteLine(DateTime.Now.AddDays(7).DayOfYear==1?"Merry Christmas":i/0+"");
```
Explained:
```
using System;
int i;
// if today plus 7 days is the first day of the year, then it's xmas!
Console.WriteLine(DateTime.Now.AddDays(7).DayOfYear==1
? "Merry Christmas"
// otherwise divide i by 0
: i/0+"");
```
`DateTime.Now.AddDays(7).DayOfYear==1` is one byte shorter than `DateTime.Now.ToString("ddMM")=="2512"` but 1 byte longer than `DateTime.Now.ToString("dM")=="2512"`
[Answer]
# C#/CS Script, 96 Bytes, Mostly Plagiarized from Erresen
```
using System;Console.WriteLine(DateTime.Now.AddDays(7).DayOfYear==1?"Merry Christmas":1/0+"");
```
Deletes the `int i` declaration in favor of hard coding the division. I would leave this as a comment but don't have the reputation.
[Answer]
# bash + Unix utilities, ~~51~~ ~~49~~ 47 bytes
```
((`date +%m%d`-1225))&&${};echo Merry Christmas
```
\*Thanks to @KenY-N for pointing out that the quotes in the echo can be removed, and to @IporSircer for reducing the condition size by 2 bytes.
[Answer]
# Groovy, 57 bytes
```
print new Date().format("Md")=="1225"?"Merry Christmas":b
```
Crashes on dates other than 25.12. with `groovy.lang.MissingPropertyException` because `b` is not defined.
[Answer]
# [Stacked](https://github.com/ConorOBrien-Foxx/stacked/), 42 bytes
[Try it here!](https://conorobrien-foxx.github.io/stacked/stacked.html)
```
('Merry Christmas')'MMDD'date'1225'=¬#out
```
This creates a single-element array containing namely `'Merry Christmas!'`. After, it puts the date into a string with the month followed by the day. It checks for equality with `'1225'` (Christmas), inverts it with `¬`, then gets that member from the preceding array. If it isn't Christmas, this will error with an index error. Otherwise, it prints `Merry Christmas`. (Change the date in the string to see how it works on other days.)
[Answer]
## Batch, 66 bytes
```
@echo off
if %date:~0,5%==25/12 echo Merry Christmas&exit/b
if
```
The trailing newline is significant, as it causes parsing of the `if` statement to fail. You may need to tweak the date check to match your local date format.
[Answer]
# Python 2, ~~69 77~~ 75 or ~~72~~ 70 Bytes
```
import time
if time.strftime("%d%m")=="2512":print"Merry Christmas"
else:1/0
```
If it doesn't matter if it exits with an error when it is Christmas, then:
```
import time
if time.strftime("%d%m")=="2512":print"Merry Christmas"
1/0
```
EDIT:
Thanks @Flp.Tkc for pointing out that I needed to raise an error
-2 Bytes from @Max for pointing out about removing colons from the strftime function
[Answer]
# CJam, 28
```
et[C25]#1="Merry Christmas"/
```
[Try it online](http://cjam.aditsu.net/#code=et%5BC25%5D%231%3D%22Merry%20Christmas%22%2F)
**Explanation:**
```
et push an array of current [year month day hour ...]
[C25] push the array [12 25] (C=12)
# find the position of the 2nd array within the first one
1= compare it with 1, resulting in 1 for 1 and 0 otherwise
"Merry Christmas"/ split "Merry Christmas" into pieces of that length
(it crashes if the length is 0)
at the end, all the pieces are concatenated
and printed automatically
```
[Answer]
## C#.NET, ~~180~~ ~~172~~ 171 bytes
*Saved 8 bytes thanks to Kritixi Lithos*
*Saved 1 byte thanks to Kritixi Lithos, again ;)*
```
namespace System{class P{static void Main(string[] args){var d=DateTime.Today;if(d.Day==25)if(d.Month>11){Console.Write("Merry Christmas!");return;}throw new Exception();}}}
```
Alternative, ungolfed variant:
```
namespace System //In System, so we don't have to use system.
{
class Program
{
static void Main(string[] args) //Main function.
{
var d = DateTime.Today; //Get Today.
if (d.Day == 25) if (d.Month == 12) //Day has to be 25th, Month has to be 12nd.
{
Console.Write("Merry Christmas!"); return; //Prints.
}
throw new NotChristmasException(); //Errors/Crashes the program.
}
}
class NotChristmasException : Exception { } //Holiday exception, hooray!
}
```
[Answer]
# Mathematica, 46 bytes
```
If[Today[[1,2;;]]=={12,25},"Merry Christmas!"]
```
[Answer]
# Common Lisp, 140
```
(let((m(multiple-value-list(decode-universal-time(get-universal-time)))))(if(and(eq(nth 3 m)25)(eq(nth 4 m)12))(write"Merry Christmas")(c)))
```
Crashes with undefined function if the date isn't right.
[Answer]
## awk, 29 bytes (+ length("Merry xmas"))
```
v=1225==strftime("%m%d")||1/0
```
Running it:
```
$ echo Merry xmas | awk 'v=1225==strftime("%m%d")||1/0'
awk: cmd. line:1: (FILENAME=- FNR=1) fatal: division by zero attempted
```
Season greeting is piped to `awk`. `strftime` returns month+day (for example `1226`) and if it matches `1225` `$0` record gets outputed. Result of comparison `1225==1226` is placed to `v` var which is used to divide 1 if the date comparison fails.
[Answer]
## Haskell, 116
Crashes with "Non-exhaustive patterns in function f" if it's not Christmas.
```
import Data.Time
f(_,12,25)="Merry Christmas"
main=getZonedTime>>=print.f.toGregorian.localDay.zonedTimeToLocalTime
```
Unfortunately, there's no function that allows you to just immediately get the time in a useful format, so most of this is converting the date formats.
[Answer]
# C#, ~~122~~ 104 bytes
18 bytes saved, thanks to @raznagul
```
using System;i=>{if(DateTime.Now.AddDays(7).DayOfYear==1)Console.Write("Merry Christmas");else{i/=0;};};
```
It adds 7 days to the current day, and checks if it is the first day of the year, if yes, it displays "Merry Christmas", otherwise it divides by zero.
[Answer]
## Ruby, 69 bytes
```
if Time.now.strftime("%j")=="360";puts "Merry Christmas";else 0/0;end
```
Works in 2016. Doesn't differentiate between normal and leap years, may need to be adjusted for non-leap years.
[Answer]
# ForceLang, 180 bytes
```
set s datetime.toDateString datetime.now()
set t "Dec 25"
def c s.charAt i
def d t.charAt i
set i -1
label 1
set i 1+i
if i=6
io.write "Merry Christmas!"
exit()
if c=d
goto 1
z.z
```
(Remember that `datetime.toDateString` is locale-dependent, so this may not work depending on your locale)
[Answer]
# C#, 90 bytes
```
using System;Console.Write(new[]{"Merry Christmas"}[DateTime.Now.AddDays(7).DayOfYear-1]);
```
Throws IndexOutOfRangeException if it's not christmas.
[Try it here!](https://dotnetfiddle.net/6wbSVV)
[Answer]
# bash command line, ~~45~~ ~~48~~ 49 48 bytes
```
date +%m%d|grep -q 1225&&echo Merry Christmas||!-
date +%m%d|grep -q 1225||!-;echo Merry Christmas
```
Similar to [Mitchell Spector's](https://codegolf.stackexchange.com/a/104609/63348), but use `grep` in silent mode to check for a match, then `&&` will ensure that it only prints on success, and the `||` causes it to look up history with `!-`, which gives me this:
```
-bash: !-: event not found
```
And it stops execution as `!- ; echo foo` demonstrates. The `bash` documentation says that `!-n` refers to the current command minus `n`, so perhaps it is being interpreted as `!-0`, which gives an identical (and non-localised) error message.
] |
[Question]
[
We had a [prime factorization challenge](https://codegolf.stackexchange.com/q/1979/42545) a while ago, but that challenge is nearly six years old and barely meets our current requirements, so I believe it's time for a new one.
## Challenge
Write a program or function that takes as input an integer greater than 1 and outputs or returns a list of its prime factors.
## Rules
* Input and output may be given by any standard method and in any standard format.
* Duplicate factors must be included in the output.
* The output may be in any order.
* The input will not be less than 2 or more than 231 - 1.
* Built-ins are allowed, but including a non-builtin solution is encouraged.
## Test cases
```
2 -> 2
3 -> 3
4 -> 2, 2
6 -> 2, 3
8 -> 2, 2, 2
12 -> 2, 2, 3
255 -> 3, 5, 17
256 -> 2, 2, 2, 2, 2, 2, 2, 2
1001 -> 7, 11, 13
223092870 -> 2, 3, 5, 7, 11, 13, 17, 19, 23
2147483646 -> 2, 3, 3, 7, 11, 31, 151, 331
2147483647 -> 2147483647
```
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so **the shortest code in bytes wins.**
[Answer]
# [Python 2](https://docs.python.org/2/), 55 bytes
```
f=lambda n,k=2:n/k*[0]and(f(n,k+1),[k]+f(n/k,k))[n%k<1]
```
[Try it online!](https://tio.run/nexus/python2#@59mm5OYm5SSqJCnk21rZJWnn60VbRCbmJeikaYBFNI21NSJzo7VBnL0s3WyNTWj81SzbQxj/xcUZeaVKKRpGJmaav4HAA "Python 2 – TIO Nexus")
[Answer]
# [Pyth](https://pyth.herokuapp.com/?code=P&input=2147483646&debug=0), 1 byte
```
P
```
I like Pyth's chances in this challenge.
[Answer]
## Python 2, 53 bytes
```
f=lambda n,i=2:n/i*[f]and[f(n,i+1),[i]+f(n/i)][n%i<1]
```
Tries each potential divisor `i` in turn. If `i` is a divisor, prepends it and restarts with `n/i`. Else, tries the next-highest divisor. Because divisors are checked in increasing order, only the prime ones are found.
As a program, for 55 bytes:
```
n=input();i=2
while~-n:
if n%i:i+=1
else:n/=i;print i
```
[Answer]
# Mathematica, ~~38~~ 30 bytes
Thanks @MartinEnder for 8 bytes!
```
Join@@Table@@@FactorInteger@#&
```
[Answer]
# [Haskell](https://www.haskell.org/), 48 bytes
```
(2%)
n%1=[]
n%m|mod m n<1=n:n%div m n|k<-n+1=k%m
```
[Try it online!](https://tio.run/##XY3BbsIwDIbvfgofqMREI9Vx2xREuPACHCdtHKpBt6pNmMa0C@zVlznVaNEkW/Zvf7/9Vp@7Y9@Hxj6HuU4ewCdkn/ZS3NWdDujQr8n6lU8O7VdU126t/IJsl7jg6tajxfeP1n/iDBukLCOAiwKNaoMaOBaGfFCpDMq/jqG6zeKY9KQYdFEMvhSLFMmILu/gfwHxZ1wbYUlS/Jqzpa5Mdns2HBr38abkUszCUm7yisu8nGAeYY6GIjZME2oGdFSgvsPPS9PXr@egHre73S8 "Haskell – Try It Online") Example usage: `(2%) 1001` yields `[7,11,13]`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes
```
Æf
```
[Try it online!](https://tio.run/nexus/jelly#@3@4Le3/4fZHTWvc//830lEw1lEw0VEw01Gw0FEwBPKNTE1BBFDA0MDAEMg0MjawNLIwNwAyDU3MTSyMzUzMkNjmAA "Jelly – TIO Nexus")
[Answer]
# JavaScript (ES6), 44 bytes
```
f=(n,x=2)=>n-1?n%x?f(n,x+1):[x,...f(n/x)]:[]
```
Horribly inefficient due to the fact that it iterates from 2 up to every prime factor, including the last. You can cut the time complexity dramatically at the cost of 5 bytes:
```
f=(n,x=2)=>x*x>n?[n]:n%x?f(n,x+1):[x,...f(n/x,x)]
```
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix), ~~37~~ 32 bytes
```
vs(...<..1I>(!@)s)%?w;O,s(No;^;<
```
[Try it online!](https://tio.run/nexus/cubix#@19WrKGnp2ejp2foaaeh6KBZrKlqX27tr1Os4ZdvHWdt8/@/kZGxgaWRhbkBAA "Cubix – TIO Nexus") or [Watch it in action](http://ethproductions.github.io/cubix/?code=dnMoLi4uPC4uMUk+KCFAKXMpJT93O08scyhObzteOzw=&input=MTI=&speed=4).
[Answer]
# [Haskell](https://www.haskell.org/), 47 bytes
Basically this checks all integers `2, 3, 4, 5, ...` for divisors of `n`. If we find one, we factor that out and repeat the process until we get to `1`.
```
f 1=[]
f n=(:)<*>f.div n$until((<1).mod n)(+1)2
```
[Try it online!](https://tio.run/##XY7BDoIwDIbvfYoeOIACoSswMMCLGA8kSFyEaRS9GJ8dNyJgTNas/9/v73aq7@dj141ji1TuD9CiLt2dV2yqNmzUE7Xz0IPqXLcgL@wvDWrP3ZInxr5WGku83pQe0MEWheAoF5mMAF4BCAwqFMD2Yogn5Rsj/XYM2exZm8SqGESSTDkfEx9JGp3@wH8HKIrIjqVhyZTJz1@ZH5sWLXO701RuwoalWMYZp3G6wrzAbAOJbZhWVE7ooiB4jx8 "Haskell – Try It Online")
[Answer]
# [Actually](https://github.com/Mego/Seriously), 6 bytes
```
w`in`M
```
[Try it online!](https://tio.run/nexus/actually#@1@ekJmX4Pv/vwUA "Actually – TIO Nexus")
Explanation:
```
w`in`M
w factor into primes and exponents
`in`M repeat each prime # of times equal to exponent
```
[Answer]
# J, 2 bytes
```
q:
```
~~Body must be at least 30 characters.~~
[Answer]
# [MATL](https://github.com/lmendo/MATL), 2 bytes
```
Yf
```
[Try it online!](https://tio.run/nexus/matl#@x@Z9v@/kQkA "MATL – TIO Nexus")
Obligatory "boring built-in answer".
[Answer]
# Japt, 2 bytes
```
Uk
```
A built-in `k` used on the input `U`. Also refers to a country.
[Test it online!](http://ethproductions.github.io/japt/?v=master&code=VWs=&input=MTEwMTE=)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 1 byte
```
ǐ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLHkCIsIiIsIjIxNDc0ODM2NDYiXQ==)
Just the built-in. But that's boring, so
## [Vyxal](https://github.com/Vyxal/Vyxal), ~~16~~ 8 bytes
```
K~æ~Ǒ$ẋf
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJLfsOmfseRJOG6i2YiLCIiLCIyMTQ3NDgzNjQ2Il0=)
## Explained
```
ʀ~æ~Ǒ$ẋf
ʀ~æ # From the all numbers in the range [0, input], keep only those that are prime
~Ǒ # Without popping anything, get the multiplicity of each prime divisor - this leaves the stack as [divisors, multiplicities]
$ẋ # Swap the two items and repeat each divisor multiplicity times
f # Flatten and output that
```
[Answer]
# [tone-deaf](https://github.com/kade-robertson/tone-deaf), 3 bytes
This language is quite young and not really ready for anything major yet, but it can do prime factorization:
```
A/D
```
This will wait for user input, and then output the list of prime factors.
[Answer]
# MATLAB, 6 bytes
I think this does not require any explanation.
```
factor
```
[Answer]
## Batch, 96 bytes
```
@set/an=%1,f=2,r=0
:l
@set/af+=!!r,r=n%%f
@if %r%==0 echo %f%&set/an/=f
@if %n% gtr 1 goto l
```
[Answer]
# [R](https://www.r-project.org/), ~~53~~ 52 bytes
```
p=function(n,i=2)if(n>1)c(i[m<-!n%%i],p(n/i^m,i+!m))
```
[Try it online!](https://tio.run/##dZHxCoIwEMb/7ykuIthoktvUGWQvEhVhEw5yytTnt1liOQnuYPvuft/dmO1ri6W@Ffe8rWyT9XVWdCZvsTLEMMwExYKYE6c5wXN5DNZmu8ULq4nZ47VkuFuXlM49iKCwgeAkVnNZfmTpydHYzcAHkqniM@mXWWJc/FZ9VMTxuAeDmAFXi3oyM/fCnxWG/NOunBd3uZgnZHgQqQq/j3kPnvqHHVwenPmC5ZGKUplEyS8sJ1gOBvFwkPwfqkZ0ukMGxR2fDTw6DW3logoeWtdgdd7Zxn38qn8B "R – Try It Online")
Recursive function: overflows the stack limit and errors on TIO for the last test case.
---
# [R](https://www.r-project.org/), ~~59~~ 58 bytes
```
function(n,i=2)while(n>1)if(n%%i)i=i+1 else{show(i);n=n/i}
```
[Try it online!](https://tio.run/##dY/taoMwFIb/9yoOlIJhlplEjWWktzJcG9dDs2QkEX@MXbvTVmyNDHLgfD3ve@L6b4df6r2pT8E6L/umNaeA1iQmRclId0GtEnOkBJvE7HZIUOILBaW9@vEX2yVI3ow0r/i7VEoYgS3sj2yzbPN7m0ftfNpOIQbKeRIz1YNZY5Q9T2OUFcV0RwpFClSs5uVCPHqxV5bR@7oYtOgQKz/GswOrRPb4zM143h9vGOIwiK9Ymou84mVePsN8hvkoUIwJp5vtP6yY2LkGCWerPBgbQDlnXQofbYAOtYZQXxXUoK35hDDIQW3O4O0t93vbhv4P "R – Try It Online")
Non-recursive function: does not error for large primes, but will still take a very long time to run (and so times-out without erroring on TIO for the last test case anyway).
[Answer]
# [CellTail](https://github.com/mousetail/CellTail/blob/main/README.md), 166 bytes
```
N,(u,u,_),N:1,(u,1),(0,2);(0,2),N,N:1,N,N;N,(u,v,0),N:1,(v,1),(u/v,2,(u/v)%2);N,(u,v,w),N:1,(u,v+1,u%(v+1)),N;a&(_,_,_),N,N:1,a,N;_,(v,1),_:1,v,N;N,u,N:1,(u,2,u%2),N;
```
[Try the demo](https://mousetail.github.io/CellTail/#ST1DIE47Ck89TjsKI009NDA7CgpOLCh1LHUsXyksTjoxLCh1LDEpLCgwLDIpOygwLDIpLE4sTjoxLE4sTjtOLCh1LHYsMCksTjoxLCh2LDEpLCh1L3YsMiwodS92KSUyKTtOLCh1LHYsdyksTjoxLCh1LHYrMSx1JSh2KzEpKSxOO2EmKF8sXyxfKSxOLE46MSxhLE47XywodiwxKSxfOjEsdixOO04sdSxOOjEsKHUsMix1JTIpLE47)
## Explanation:
Base case, when we reach the end switch to a recursion resistant tuple and pass a message right to break it. Then the message right sends a 1 to prevent recursion when the tuple has broken.
```
N,(u,u,_),N:1,(u,1),(0,2);(0,2),N,N:1,N,N;
```
We have found a factor, try again in the cell to the right with `(u/v)`
```
N,(u,v,0),N:1,(v,1),(u/v,2,(u/v)%2);
```
We have not found a factor, try another.
```
N,(u,v,w),N:1,(u,v+1,u%(v+1)),N;
```
Copy 3-tuples from left to current
```
a&(_,_,_),N,N:1,a,N;
```
Break recursion resistant tuples. Hopefully the next step the value from the right will throw a 1 to break the recursion.
```
_,(v,1),_:1,v,N;
```
Base case, start with trying 2 as a factor.
```
N,u,N:1,(u,2,u%2),N;
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + coreutils, 19 bytes
```
factor|sed s/.*:.//
```
[Try it online!](https://tio.run/nexus/bash#@5@WmFySX1RTnJqiUKyvp2Wlp6///7@RqSkA "Bash – TIO Nexus")
[Answer]
## Pyke, 1 byte
```
P
```
[Try it here!](http://pyke.catbus.co.uk/?code=P&input=12)
Prime factors builtin.
[Answer]
# [Hexagony](https://github.com/m-ender/hexagony), 58 bytes
Not done golfing yet, but @MartinEnder should be able to destroy this anyway
Prints out factors space-separated, with a trailing space
Golfed:
```
2}\..}$?i6;>(<...=.\'/})."@...>%<..'':\}$"!>~\{=\)=\}&<.\\
```
Laid-out:
```
2 } \ . .
} $ ? i 6 ;
> ( < . . . =
. \ ' / } ) . "
@ . . . > % < . .
' ' : \ } $ " !
> ~ \ { = \ )
= \ } & < .
\ \ . . .
```
Explanation coming later.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 1 byte
```
Ò
```
[Try it online!](https://tio.run/nexus/05ab1e#@3940v//RoYm5iYWxmYmZgA "05AB1E – TIO Nexus")
[Answer]
# CJam, 2 bytes
```
mf
```
[cjam.aditsu.net/...](//cjam.aditsu.net#code=rimf%60&input=2147483646)
This is a function. Martin, it seems I was sleepy.
[Answer]
## C, 92 bytes
```
int p(int n){for(int i=2;i<n;i++)if(n%i==0)return printf("%d, ",i)+p(n/i);printf("%d\n",n);}
```
Ungolfed version:
```
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int prime(int number) {
for (int i = 2; i < number; i++) {
if (number % i == 0) {
printf("%d, ", i);
return prime(number / i); //you can golf away a few bytes by returning the sum of your recursive function and the return of printf, which is an int
} //this allow you to golf a few more bytes thanks to inline calls
}
printf("%d\n", number);
}
int main(int argc, char **argv) {
prime(atoi(argv[1]));
}
```
[Answer]
# [Java (OpenJDK)](http://openjdk.java.net/), 259 bytes
```
import java.util.*;interface g{static void main(String[]z){int a=new Scanner(System.in).nextInt();int b=0;int[]l={};for(int i=2;i<=a;i++){for(;a%i<1;l[b-1]=i){l=Arrays.copyOf(l,b=l.length+1);a/=i;}}for(int i=0;i<b;i++)System.out.print(l[i]+(i<b-1?", ":""));}}
```
[Try it online!](https://tio.run/nexus/java-openjdk#RY5BT4QwEIX/SkNi0sputStZzZbGePTkgSPhMGDB2ZRCyuwqEn47gjHx9JL33nzzFmz7LhA7wxXkhdDJW42ebKihsqyZBgLCil07fGctoOcZBfRNXnyLae0xMN5@sqwC723g2TiQbSV6Ib39oldPXGw4Vpr7TfPCmWnWdRf45qI5aEwNaIxjMW2uhhtMlXZ5uVeFQTE58xICjIOsun58q7nblcZJZ31DH7ESGu4M6nn@J65/0vIX@Demu5Ds183EXY5FzNd4r56jHYtOUSTEerwsB5U8Jk8Px@T4Aw "Java (OpenJDK) – TIO Nexus")
[Answer]
# [PHP](https://php.net/), 51 bytes
```
for($i=2;1<$a=&$argn;)$a%$i?$i++:$a/=$i*print"$i ";
```
[Try it online!](https://tio.run/##K8go@G9jX5BRwKWSWJSeZ6tkbGysZP0/Lb9IQyXT1sja0EYl0VYNLGetqZKoqpJpr5KprW2lkqhvq5KpVVCUmVeipJKpANTzHwA "PHP – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 51 bytes
```
i;f(n){for(i=2;i<=n;)n%i?i++:printf("%d ",i,n/=i);}
```
[Try it online!](https://tio.run/##XY7LCsIwEEXX5itKoDClLSZp@tBY/RapNMzCWGpdlX57TEwEcXXuXM4MM5R6GKxFNYLJ1vExA/ZC4ak3KjMpXjDPj9OMZhmBpreEFliYfY@Z2qwGVycmIyvZ/Sjl2VmuVmTnbzpMr@UJlLq4EeJ37lc08NnTILyhoQqQAU1AF8CjI@r6G6LAGeOxEhU7iK5lceSylV3VyOZvbv0X9g0 "C (gcc) – Try It Online")
[Answer]
# [Gol><>](https://github.com/Sp3000/Golfish), 19 bytes
```
IT1WP2K%ZB|:N,:M?t;
```
[Try it online!](https://tio.run/##XY1NCgIxDIX3PUU37io0Sf9mBhTciSguBMEDqAOCi3Hp3WtSnFaEhua9fC@5PR/XcbrnvD3B@Yi7xWXz7g@m369fQ0a9XGlUJB8pV5RhI3w7Umn2xAZsihR6X3JGe6Mhsg4/8N9TYC3IODILXJxHsh2maOdjZVGdy06ujsPMgosuUXChwVRhkoCXhqChsaBV5XrvAw "Gol><> – Try It Online")
## Explanation
```
IT < [n] read input to n then mark cell (T)
1WP | < [n m=2] from 2 onwards (m=1;while m:m++;)
2K%ZB < [n m+1] copy two elements, mod, break if n%m==0
:N < [n m] (< where n%m==0) print m with newline
,:M?t; < [n/m] (< new n) divide, if not 1 redo from T else exit
```
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), 1 [byte](https://github.com/mudkip201/pyt/wiki/Codepage)
```
ḋ
```
Boring built-in answer
[Try it online!](https://tio.run/##K6gs@f//4Y7u//8NjY0B)
] |
[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/68666/edit).
Closed 2 years ago.
[Improve this question](/posts/68666/edit)
As a spin-off to [my challenge over at Puzzling](https://puzzling.stackexchange.com/questions/25039/10-9-8-7-6-5-4-3-2-1-2016), your goal is to output `2016`.
Rules:
* You must include the numbers `10 9 8 7 6 5 4 3 2 1` in that order. They can be used as individual integers or concatenated together (like `1098`), but the `10` may not be separated into `1` and `0` - no character(s) may be present between the digits. Note that, in some languages, `10` may not actually represent the integer literal `10`, which is acceptable.
* Your code must not contain any other numbers or pre-defined number variables or constants (so `T` in Pyth is not allowed, since it is a numeric constant).
* You must **calculate** `2016` using numerics. Simply outputting `2016` without performing any operations on the required numbers (for example, by decoding an encoded string consisting of only alphabetic characters) is not allowed. Outputting `2016` in pieces (such as `20`, then `16`) is also not allowed; you must have a single output consisting of the numeric value `2016`.
* The valid answer with the fewest bytes wins.
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), ~~17~~ ~~15~~ 14 bytes
```
109876:54+3_21
```
[Try it online!](http://jelly.tryitonline.net/#code=MTA5ODc2OjU0KzNfMjE&input=)
### How it works
```
109876:54+3_21
109876 Initialize the left argument as 109876.
:54 Perform integer division by 54, yielding 2034.
+3 Add 3, yielding 2037.
_21 Subtract 21, yielding 2016.
```
[Answer]
# Hexagony, 61 bytes
Not gonna win, but I just wanted to do a challenge in Hexagony.
This uses a different method than other answers (much worse). It takes some factors of 2016 (2,3,6,7,8) and multiplies them all together.
Minified:
```
\109.8/7}_=\"6<}{>...$_5_4/*!@...../}3.."2\/="*=}<*...$1>"*"/
```
Unminified:
```
\ 1 0 9 .
8 / 7 } _ =
\ " 6 < } { >
. . . $ _ 5 _ 4
/ * ! @ . . . . .
/ } 3 . . " 2 \
/ = " * = } <
* . . . $ 1
> " * " /
```
Explanation coming soon;
[Answer]
# Pyth, 16 bytes
```
+/109876 54-3 21
```
Does integer division, then adds (3-21).
Try it [here](http://pyth.herokuapp.com/?code=%2B%2F109876+54-3+21&debug=0).
[Answer]
## TI-BASIC, ~~17~~ 15 bytes
```
int(109876/54-‚àö(321
```
This uses @nicael's method.
17 bytes:
```
10+9*8-7+654*3-21
```
[This solution](https://puzzling.stackexchange.com/a/25050/12917) from Puzzling can be directly translated into TI-BASIC.
[Answer]
# Japt, ~~17~~ 16 bytes
```
Â(109876/54-321q
```
~~I hate this 17. Probably will find another solution.~~ YAYZ.
Explanation:
* `321q` is a square root of 321.
* `~~` floors the number.
[Try it online!](http://ethproductions.github.io/japt?v=master&code=wigxMDk4NzYvNTQtMzIxcQ==&input=)
[Answer]
# Matlab / Octave, 23 bytes
```
(10-9+8-7)^(6-5+4)*3*21
```
[Try it online](http://ideone.com/cLWq29)
[Answer]
# bc, 14
```
109876/54+3-21
```
Nothing exciting here - borrows from other answers.
[Answer]
## Haskell, 31 bytes
```
[10,9*8*7+const 6 5..]!!4+3*2*1
```
Not the shortest, `10+9*8-7+654*3-21` like seen in other answers works in Haskell too, but something different.
This builds a list starting with `10` and `9*8*7+6 = 510`, so the offset is `500` for the following elements. The whole list is `[10,510,1010,1510,2010,2510 ...]`. We pick the `4th` element (index 0-based), i.e. `2010` and add `3*2*1 = 6`. Voilà.
I use `const 6 5 = 6` to get rid of the `5` which is not needed.
[Answer]
# Python 2, 20 bytes
```
print 109876/54+3-21
```
Again, that same boring `2016.(740)`. Makes use of the fact that if you don't have a decimal number in your expression it returns an integer.
[Answer]
# [BotEngine](https://github.com/SuperJedi224/Bot-Engine), ~~42~~ ~~39~~ ~~36~~ 13x2=26
```
v109876543210
>ee e@ eRP
```
[Answer]
# ><> (fish), 18 bytes
```
10987**r65r4*n;321
```
explaination:
multiplies 9 8 and 7 together to get 504, reverses the stack and reverses it again right before the 4 is added, then multiplies 504 and 4 to get 2016. Then prints the number and ends the program before the last 3 numbers (i could do it after too with no difference, if that matters rules-wise).
[Answer]
# [Math++](http://esolangs.org/wiki/Math%2B%2B), 17 bytes
```
_(109876/54)+3-21
```
Actually, this prints `2016.0`. But there's really no way to print the exact string `2016` in this language.
The 17-byte TI-BASIC solution would also work here.
[Answer]
# Polyglot, 17 Bytes
```
10+9*8-7+654*3-21
```
This code, first used in [Thomas Kwa's TI-BASIC answer](https://codegolf.stackexchange.com/a/68682/44713), also works in:
* AppleScript (full program)
* bc (full program)
* Math++ (expression or full program)
* Mathematica (function, therefore not valid)
* Powershell (full program)
* Japt (full program)
* ~~JavaScript (console input, therefore not valid)~~ Needs second verification
* ~~Perl 5 (function, therefore not valid).~~ Needs second verification
* Haskell (function, therefore not valid)
* Python REPL (expression, so REPL environment is needed to get the output)
[Answer]
# ùîºùïäùïÑùïöùïü 2, 15 chars / 17 bytes
```
109876/54+3-21‚çú
```
`[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter2.html?eval=false&input=&output=&code=109876%2F54%2B3-21%E2%8D%9C)`
Translates to `round(109876/54+3-21)`.
*Thanks to @Dennis for saving 2 bytes!*
[Answer]
# Java 7, 31 bytes
```
int c(){return 109876/54+3-21;}
```
Boring port from other answers, of which I believe [*@Dennis*' Jelly answer](https://codegolf.stackexchange.com/a/68687/52210) was the first.
[Answer]
# PHP, 27 bytes
```
<?=~~(109876/54+3-21);
```
(22 bytes) was too boring,
so I used 10 to 9 as separate numbers:
```
<?=10*(9-8+7-6),5+4-3+2<<1;
```
other solutions, mostly with small cheats:
```
30: <?=10**(9+8-7-6)/5+4*3+(2<<1);
30: <?=10*trim(9*8,7),6+5+4+3-2*1;
29: <?=10*trim(9*8,76),5*4-3-2+1;
31: <?=10*trim(9*8,765),4+(3*2<<1);
31: <?=10*trim(9*8,765),4*3+(2<<1);
32: <?=ceil(1098*76/54)+321+ord(~j);
33: <?=(10<<9)/876*543/M_PI*2-M_E&~1;
```
[Answer]
# [CJam](https://esolangs.org/wiki/CJam), 15 bytes
```
109876 54/3+21-
```
Another port from Dennis' answer that I suspect works for many stack-based languages except 05AB1E, which seems to be the only stack-based answer besides Forth, which needs several more bytes.
[Answer]
# [Milky Way 1.6.5](https://github.com/zachgates7/Milky-Way), ~~28~~ 25 bytes
```
10+9*(8)7;^*6*5/4*3/2*A!1
```
---
### Explanation
```
10+9* ` perform 10*9 (leaves 90 at TOS)
(8)7;^* ` get rid of 8 and multiply the TOS by 7
6*5/4*3/2*A ` perform TOS*6/5*4/3*2 (leaves 2016 at TOS)
! ` output the TOS
1 ` push 1 to the stack
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 15 bytes
```
109876 54√∑3+21-
```
[Try it online!](http://05ab1e.tryitonline.net/#code=MTA5ODc2IDU0w7czKzIxLQ&input=)
Port of Dennis' answer.
[Answer]
# Forth, 22 bytes
Same calculation seen in other answers.
```
109876 54 / 3 + 21 - .
```
[**Try it online**](https://repl.it/ElA3)
[Answer]
# C 37 bytes
```
main(){printf("%d",109876/54+3-21);}
```
Same theme as many present.
[Answer]
# VBA, 15 bytes
```
?109876\54+3-21
```
(calculation unashamedly stolen from [Dennis](https://codegolf.stackexchange.com/a/68687/5011))
[Answer]
# JavaScript (ES6), 21 bytes
```
f=
_=>~~(109876/54+3-21)
console.log(f())
```
If the "countdown" went to 0, it could be done in 19 bytes.
```
f=
_=>109876/54+3-21|0
console.log(f())
```
And, seeing as it's 2017 now, that can also be done in 21 bytes:
```
f=
_=>-~(109876/54+3-21)
console.log(f());
```
] |
[Question]
[
# Binary to decimal converter
As far as I can see, we don't have a simple binary to decimal conversion challenge.
---
Write a program or function that takes a positive binary integer and outputs its decimal value.
You are not allowed to use any builtin base conversion functions. Integer-to-decimal functions (e.g., a function that turns `101010` into `[1, 0, 1, 0, 1, 0]` or `"101010"`) are exempt from this rule and thus allowed.
Rules:
* The code must support binary numbers up to the highest numeric value your language supports (by default)
* You may choose to have leading zeros in the binary representation
* The decimal output may not have leading zeros.
* Input and output formats are optional, but there can't be any separators between digits. `(1,0,1,0,1,0,1,0)` is not a valid input format, but both `10101010` and `(["10101010"])` are.
+ You must take the input in the "normal" direction. `1110` is `14` not `7`.
Test cases:
```
1
1
10
2
101010
42
1101111111010101100101110111001110001000110100110011100000111
2016120520371234567
```
This challenge is related to a few other challenges, for instance [this](https://codegolf.stackexchange.com/questions/68247/convert-a-number-to-hexadecimal), [this](https://codegolf.stackexchange.com/questions/63564/simplify-binary) and [this](https://codegolf.stackexchange.com/questions/69155/base-conversion-with-strings).
[Answer]
# Clojure, ~~114~~ ~~105~~ ~~63~~ 41 bytes
## V4: 41 bytes
-22 bytes thanks to @cliffroot. Since `digit` is a character, it can be converted to it's code via `int`, then have 48 subtracted from it to get the actual number. The map was also factored out. I don't know why it seemed necessary.
```
#(reduce(fn[a d](+(* a 2)(-(int d)48)))%)
```
## V3: 63 bytes
```
(fn[s](reduce #(+(* %1 2)%2)(map #(Integer/parseInt(str %))s)))
```
-42 bytes (!) by peeking at other answers. My "zipping" was evidently very naïve. Instead of raising 2 to the current place's power, then multiplying it by the current digit and adding the result to the accumulator, it just multiplies the accumulator by 2, adds on the current digit, then adds it to the accumulator. Also converted the reducing function to a macro to shave off a bit.
Thanks to @nimi, and @Adnan!
Ungolfed:
```
(defn to-dec [binary-str]
(reduce (fn [acc digit]
(+ (* acc 2) digit))
(map #(Integer/parseInt (str %)) binary-str)))
```
## V2: 105 bytes
```
#(reduce(fn[a[p d]](+ a(*(Integer/parseInt(str d))(long(Math/pow 2 p)))))0(map vector(range)(reverse %)))
```
-9 bytes by reversing the string so I don't need to create an awkward descending range.
## V1: 114 bytes
Well, I'm certainly not winning! In my defense, this is the first program I've ever written that converts between bases, so I had to learn how to do it. It also doesn't help that `Math/pow` returns a double that requires converting from, and `Integer/parseInt` doesn't accept a character, so the digit needs to be wrapped prior to passing.
```
#(reduce(fn[a[p d]](+ a(*(Integer/parseInt(str d))(long(Math/pow 2 p)))))0(map vector(range(dec(count %))-1 -1)%))
```
Zips the string with a descending index representing the place number. Reduces over the resulting list.
Ungolfed:
```
(defn to-dec [binary-str]
(reduce (fn [acc [place digit]]
(let [parsed-digit (Integer/parseInt (str digit))
place-value (long (Math/pow 2 place))]
(+ acc (* parsed-digit place-value))))
0
(map vector (range (dec (count binary-str)) -1 -1) binary-str)))
```
[Answer]
# Perl, ~~21~~ ~~19~~ 16 + 4 = 20 bytes
-4 bytes thanks to @Dada
Run with `-F -p` (including the extra space after the `F`). Pipe values to the function using `echo -n`
```
$\+=$_+$\for@F}{
```
Run as `echo -n "101010" | perl -F -pE '$\+=$_+$\for@F}{'`
I feel this is sufficiently different from @Dada's answer that it merits its own entry.
Explanation:
```
-F #Splits the input character by character into the @F array
-p #Wraps the entire program in while(<>){ ... print} turning it into
while(<>){$\+=$_+$\for@F}{print}
for@F #Loops through the @F array in order ($_ as alias), and...
$\+=$_+$\ #...doubles $\, and then adds $_ to it (0 or 1)...
while(<>){ } #...as long as there is input.
{print}#Prints the contents of $_ (empty outside of its scope), followed by the output record separator $\
```
This uses my personal algorithm of choice for binary-to-decimal conversion. Given a binary number, start your accumulator at 0, and go through its bits one by one. Double the accumulator each bit, then add the bit itself to your accumulator, and you end up with the decimal value. It works because each bit ends up being doubled the appropriate number of times for its position based on how many more bits are left in the original binary number.
[Answer]
# Haskell, 31 bytes
```
f=foldl(\a b->2*a+(read$b:[]))0
```
Takes input in string format (e.g. `"1111"`). Produces output in integer format (e.g. `15`).
`:[]` Converts from an element to an array -- in this chase from `Char` to `[Char]` (`String`).
`read` Converts from string to whatever context it's in (in this case the context is addition, so converts to `Num`)
so `(read$b:[])` converts `b` from `Char` to `Num`.
`a` is the accumulator, so multiply that by two and add the `Num` version of `b`.
If input in the format `[1,1,1,1]` was allowed, the 18 byte
```
f=foldl((+).(2*))0
```
would work, but since it's not, it doesn't.
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), 12 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319)
```
(++⊢)/⌽⍎¨⍞
```
`⍞` get string input
`⍎¨` convert each character to number
`⌽` reverse
`(`...`)/` insert the following function between the numbers
`++⊢` the sum of the arguments plus the right argument
---
ngn shaved 2 bytes.
[Answer]
# [7](https://esolangs.org/wiki/7), 25 bytes (65 characters)
```
07717134200446170134271600446170001755630036117700136161177546635
```
[Try it online!](https://tio.run/##NcjBDcBADALBlpbYhv4rc@4iRXyGzS6JouoHuq1wHfm/oMy4oCzlBB18nLZrdsXdCw)
## Explanation
```
0**77** Initialize counter to 0 (an empty section)
17134200..77546635 Push the main loop onto the frame
```
Once the original code has finished executing, the frame is
```
||**6**||**7**13420044**7**013427160044**7**000175563003**77**7001361**77**7546**35**
```
The last section of this is the main loop, which will run repeatedly until it gets deleted. All of it except the last two commands is data and section separators, which push commands onto the frame to leave it as:
```
||**6**|| (main loop) |**73426644**|**67342**1**6644**|**6667**55**3663**||0013**7**||54
```
**`3`** outputs the last section (`54`) and discards the last two bars. On the first iteration, `5` is interpreted as a switch to output format 5 ("US-TTY"), which converts each pair of commands to a character. The `4` following it does not form a group, so it is ignored. On future iterations, we are already in output format 5, so `54` is interpreted as a group meaning "input character". To do this, the character from STDIN is converted into its character code (or, on EOF, `-1`), and 1 is added. Then, the last section (which is now the `00137`) is repeated that many times. In summary:
* If the character is `0`, `00137` is repeated 49 times.
* If the character is `1`, `00137` is repeated 50 times.
* If there are no more characters, `00137` is repeated 0 times (i.e. deleted).
* If this was the first iteration, `00137` is left alone (i.e. repeated 1 time).
**`5`** removes the last section (`00137` repeated some number of times) from the frame and executes it, resulting in this many sections containing **`6673`**.
The main loop has now finished executing, so the last section (which is **`6673`** unless we reached EOF) runs. **`66`** concatenates the last three sections into one (and has some other effects that don't affect the number of sections), which **`73`** deletes. Thus, the last three sections are deleted, and this repeats until the last section is no longer **`6673`**.
* If we reached EOF, nothing happens.
* If this is the first iteration or the character was `0`, after removing the last three sections 0 or 16 times, there is just one copy left on the frame. This copy deletes itself and the two sections before it, leaving everything up to the main loop and the section after it.
* If the character was `1`, after removing the last three sections 17 times, all 50 copies and the third section after the main loop (the EOF handler) have been deleted.
Now, the last section left on the frame runs. This could, depending on the inputted character, be any of the three sections after the main loop.
If this is the first iteration or the character was `0`, the section just after the main loop, **`73426644`**, runs.
**`73`** deletes this section, and **`4`** swaps the main loop with the counter behind it. This counter keeps track of the number we want to output, stored as the number of `7`s and `1`s minus the number of `6`s and `0`s. This metric has the property that it is not changed by pacification (which changes some `6`s into `0`s, some `7`s into `1`s, and sometimes inserts `7...6` around code). **`2`** duplicates the counter and **`6`** concatenates the two copies (after pacifying the second, which, as we saw, does not change the value it represents), so the value is doubled. If this was the first iteration, the counter was previously empty, and doubling it still results in an empty section. Then, **`6`** gets rid of the empty section inserted by **`4`** (and pacifies the counter again, leaving the value unchanged), and **`44`** swaps the counter back to its original position. This leaves two empty sections on the end of the frame, which are removed automatically, and the main loop runs again.
If the character was `1`, the second section after the main loop (`**67342**1**6644**`) runs. This is just like the section before it (explained in the last paragraph), except for two extra commands: a **`6`** at the start, which joins the section with the previous one before **`73`** deletes it, and a `1` in the middle, which adds a `7` to the counter (increasing its value by 1) after it gets doubled.
If we reached EOF, the third section after the main loop (`**6667**55**3663**`) runs. **`666`** joins the last four sections (everything after the counter) into one section, to be deleted by **`3`**. `**7**55**3**` exits output format 5 by outputting `55` and deletes the section before it, leaving only `||**6**| (counter)` on the frame. **`66`** pacifies the two sections and combines them, turning the **`6`** back into a `0` (and not changing the value of the counter). Finally, the last **`3`** outputs everything.
The `0` at the start enters output format 0 ("Numerical output"), and the rest of the section (i.e. the counter) is converted to a number by taking the number of `7`s and `1`s minus the number of `6`s and `0`s. This value, which is the input converted from binary, is output in decimal and the program terminates.
[Answer]
# Excel, ~~74 70~~ 55
Trailing parens already discounted. Tested in Excel Online.
## Formulae:
* `A1`: Input
* `B1`: `=LEN(A1)` (7)
### Main Code (48):
A pretty simple "add all the powers of 2" formula:
```
=SUM(MID(A1,1+B1-SEQUENCE(B1),1)/2*2^SEQUENCE(B1))
```
Verify with:
```
=DECIMAL(A1,2)
```
[Answer]
# [R](https://www.r-project.org/), ~~48~~ 37 bytes
*-11 bytes thanks to [Dominic van Essen](https://codegolf.stackexchange.com/users/95126)*
```
sum(utf8ToInt(scan(,""))%%2*2^(31:0))
```
Takes input as a string, left-padded with 0s to 32 bits. [Try it online!](https://tio.run/##K/r/v7g0V6O0JM0iJN8zr0SjODkxT0NHSUlTU1XVSMsoTsPY0MpAU/O/kgFOYAiGSv8B "R – Try It Online")
I copied some good ideas from [djhurio](https://codegolf.stackexchange.com/users/13849)'s [much earlier R answer](https://codegolf.stackexchange.com/a/102320/16766), so go give that an upvote too. As with the first solution there, this solution won't work for the last test case because it's too large to fit into R's default size of integer.
### Explanation
To get a vector of the bits as integers 0 and 1, we use `uft8ToInt` to convert to a vector of character codes. This gives us a list of 48s and 49s, which we take mod 2 to get 0s and 1s.
Then, to get the appropriate powers of 2 in descending order, we construct a range from 31 down to 0. Then we convert each of those numbers to the corresponding power of two (`2^`).
Finally, we multiply the two vectors together and return their `sum`.
[Answer]
# x86-16 machine code, 10 bytes
**Binary:**
```
00000000: 31d2 acd0 e811 d2e2 f9c3 1.........
```
**Listing:**
```
31 D2 XOR DX, DX ; clear output value
CHRLOOP:
AC LODSB ; load next char into AL
D0 E8 SHR AL, 1 ; CF = LSb of ASCII char
11 D2 ADC DX, DX ; shift CF left into result
E2 F9 LOOP CHRLOOP ; loop until end of string
C3 RET ; return to caller
```
Callable function, input string in `[SI]` length in `CX`. Result in `DX`.
**Example test program I/O:**
[![enter image description here](https://i.stack.imgur.com/4rM2x.png)](https://i.stack.imgur.com/4rM2x.png)
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~11~~ 10 bytes
```
(+/2 1*,)/
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs9LQ1jdSMNTS0dTn4tLnMuQyNABBLkMgCQFgPpACkxAMIQzAGCRrgBAD01wxXFyeVnrq6sbxGjUxlka2WlbqmvEGVgmJRellCoZcaeqeXABdSRgX)
[Answer]
## C, 48 bytes
```
i;f(char *s){for(i=0;*++s;i+=i+*s-48);return i;}
```
Heavily inspired by @edc45 's answer but I made some significant changes. I made 'i' a global variable to save having to typecast. I also used a for loop to save a few bytes. It does now require a single leading 0 in the binary representation.
**More readable version**
```
f(char *s){
int i = 0; // Total decimal counter
for(;;*++s;i+=i+*s-48); // Shift left and add 0 or 1 depending on charecter
return i;
}
```
[Answer]
# k, 8 bytes
Same method as the Haskell answer above.
```
{y+2*x}/
```
Example:
```
{y+2*x}/1101111111010101100101110111001110001000110100110011100000111b
2016120520371234567
```
[Answer]
# JavaScript (ES7), ~~56~~ 47 bytes
Reverses a binary string, then adds each digit's value to the sum.
```
n=>[...n].reverse().reduce((s,d,i)=>s+d*2**i,0)
```
**Demo**
```
f=n=>[...n].reverse().reduce((s,d,i)=>s+d*2**i,0)
document.write( f('101010') ) // 42
```
[Answer]
# Java 7, 87 bytes
```
long c(String b){int a=b.length()-1;return a<0?0:b.charAt(a)-48+2*c(b.substring(0,a));}
```
For some reason I always go straight to recursion. Looks like an [iterative solution](https://codegolf.stackexchange.com/a/102233/51785) works a bit nicer in this case...
[Answer]
# JavaScript (ES6), 38
Simple is better
```
s=>eval("for(i=v=0;c=s[i++];)v+=+c+v")
```
**Test**
```
f=s=>eval("for(i=v=0;c=s[i++];)v+=+c+v")
console.log("Test 0 to 99999")
for(e=n=0;n<100000;n++)
{
b=n.toString(2)
r=f(b)
if(r!=n)console.log(++e,n,b,r)
}
console.log(e+" errors")
```
[Answer]
# Turing Machine Code, 272 bytes
(Using, as usual, the morphett.info rule table syntax)
```
0 * * l B
B * * l C
C * 0 r D
D * * r E
E * * r A
A _ * l 1
A * * r *
1 0 1 l 1
1 1 0 l 2
1 _ * r Y
Y * * * X
X * _ r X
X _ _ * halt
2 * * l 2
2 _ _ l 3
3 * 1 r 4
3 1 2 r 4
3 2 3 r 4
3 3 4 r 4
3 4 5 r 4
3 5 6 r 4
3 6 7 r 4
3 7 8 r 4
3 8 9 r 4
3 9 0 l 3
4 * * r 4
4 _ _ r A
```
AKA "Yet another trivial modification of my earlier base converter programs."
[Try it online](http://morphett.info/turing/turing.html?a283209e440e64106cd35d1bc3f181e1), or you can also use test it using [this java implementation.](https://github.com/SuperJedi224/Turing-Machine)
[Answer]
## JavaScript, ~~18~~ 83 bytes
~~`f=n=>parseInt(n,2)`~~
`f=n=>n.split('').reverse().reduce(function(x,y,i){return(+y)?x+Math.pow(2,i):x;},0)`
**Demo**
```
f=n=>n.split('').reverse().reduce(function(x,y,i){return(+y)?x+Math.pow(2,i):x;},0)
document.write(f('1011')) // 11
```
[Answer]
# [MATL](http://github.com/lmendo/MATL), ~~8~~, 7 bytes
```
"@oovsE
```
[Try it online!](http://matl.tryitonline.net/#code=IkBvb3ZzRQ&input=JzEwMTAxJw)
One byte saved thanks to @LuisMendo!
[Alternate approach: (9 bytes)](http://matl.tryitonline.net/#code=b290bjpQVypz&input=JzEwMTAxJw)
```
ootn:PW*s
```
[Answer]
# Befunge, ~~20~~ 18 bytes
Input must be terminated with EOF rather than EOL (this lets us save a couple of bytes)
```
>+~:0`v
^*2\%2_$.@
```
[Try it online!](http://befunge.tryitonline.net/#code=Pit-OjBgdgpeKjJcJTJfJC5A&input=MTEwMTExMTExMTAxMDEwMTEwMDEwMTExMDExMTAwMTExMDAwMTAwMDExMDEwMDExMDAxMTEwMDAwMDExMQ)
**Explanation**
```
> The stack is initially empty, the equivalent of all zeros.
+ So the first pass add just leaves zero as the current total.
~ Read a character from stdin to the top of the stack.
:0` Test if greater than 0 (i.e. not EOF)
_ If true (i.e > 0) go left.
%2 Modulo 2 is a shortcut for converting the character to a numeric value.
\ Swap to bring the current total to the top of the stack.
*2 Multiply the total by 2.
^ Return to the beginning of the loop,
+ This time around add the new digit to the total.
...on EOF we go right...
$ Drop the EOF character from the stack.
. Output the calculated total.
@ Exit.
```
[Answer]
# Ruby, 37 bytes
```
ruby -e 'o=0;gets.each_byte{|i|o+=o+i%2};p o/2'
1234567890123456789012345678901234567
```
This depends on the terminating `\n` (ASCII decimal 10) being zero modulo 2 (and on ASCII 0 and 1 being 0 and 1 mod two, respectively, which thankfully they are).
[Answer]
# [아희(Aheui)](http://esolangs.org/wiki/Aheui), 40 bytes
```
아빟뱐썩러숙
뎌반뗘희멍파퍄
```
Accepts a string composed of 1s and 0s.
**To try online**
Since the online Aheui interpreter does not allow arbitrary-length strings as inputs, this alternative code must be used (identical code with slight modifications):
Add the character `벟` at the end of the first line (after `우`) length(n)-times.
```
어우
우어
뱐썩러숙
번댜펴퍼망희땨
```
If the input is `10110`, the first line would be `어우벟벟벟벟벟`.
When prompted for an input, do NOT type quotation marks. (i.e. type `10110`, not `"10110"`)
[Try it here! (copy and paste the code)](http://jinoh.3owl.com/aheui/jsaheui_en.html)
[Answer]
# ClojureScript, 36 bytes
```
(fn[x](reduce #(+(* 2 %)(int %2))x))
```
or
```
#(reduce(fn[a n](+(* 2 a)(int n)))%)
```
The straightforward reduction. Takes a string as input.
[Answer]
# Minkolang v0.15, ~~23~~ 19 bytes
```
n6ZrI[2%2i;*1R]$+N.
```
[Try it online!](http://play.starmaninnovations.com/minkolang/?code=n6ZrI%5B2%252i%3B*1R%5D%24%2BN%2E&input=1101)
### Explanation
```
n gets input in the form of a number
6Z converts to string (so that it is split into an array)
r reverses it
I gets the stack length
[ ] for loop with the stack's length as the number of iterations
2% gets the modulo of the ascii value
1 =(string conversion)> 49 =(after modulo)> 1
0 =(string conversion)> 48 =(after modulo)> 0
2i; raises 2 to the power of the loop counter
* multiplies it by the modulo
1R rotates stack 1 time
$+ sums everything
N. outputs as number and exit
```
[Answer]
# Common Lisp, ~~99~~ ~~88~~ 72 bytes
Takes a string as input
```
(defun f(s)(reduce(lambda(a d)(+ d(* a 2)))(map'list #'digit-char-p s)))
```
Ungolfed:
```
(defun bin-to-dec (bin-str)
(reduce (lambda (acc digit) (+ digit (* acc 2)))
(map 'list #'digit-char-p bin-str)))
```
[Answer]
# ><> (Fish) ~~36~~ 28 bytes
```
/i:1+?!v$2*$2%+!| !
/0| ;n~<
```
Edit 1: Forgot to put the output in the original. Added output and used MOD 2 instead of minus 48 to convert ascii to decimal to save the extra bytes lost. (no change in bytes)
Edit 2: Changed the algorithm completely. Each loop now does this; times current value by 2, then add the mod of the input. (saving of 8 bytes)
[Online version](https://fishlanguage.com/playground/BPT5uHb6PgvsRyvrP)
[Try it Online!](http://fish.tryitonline.net/#code=L2k6MSs_IXYkMiokMiUrIXwgIQovMHwgO25-PA&input=MTEwMTExMTExMTAxMDEwMTEwMDEwMTExMDExMTAwMTExMDAwMTAwMDExMDEwMDExMDAxMTEwMDAwMDExMQ) - This works with bigger numbers than the above link.
[Answer]
# **C, 44 bytes**
```
d(s,v)char*s;{return*s?d(s,v+=v+*s++-48):v;}
```
Use as follows :
```
int main(){
printf("%i\n", d("101010",0));
}
```
Remove two bytes and an unused parameter thanks to Steadybox
[Answer]
# **MATLAB, 49 bytes**
```
@(a)dot(int2str(a)-'0',2.^(floor(log10(a)):-1:0))
```
Anonymous function that splits the input into an array with `int2str(a)-'0'`, then does a dot product with powers of 2. Has rounding error for the last test case, will update the solution when I figure out a fix.
[Answer]
# Forth (gforth 0.7.3), 47 bytes
```
: x 2 base ! bl parse s>number drop decimal . ;
```
`: x` - define new word with name 'x'
`2 base !` - set base to binary
`bl parse` - read line until a space (bl) or EOL
`s>number` - try to convert the string to number
`drop` - we only want the converted number and not the success flag
`decimal` - set base to decimal
`.` - print value on top of stack
`;` - end of definition
Test cases:
```
x 1 1 ok
x 10 2 ok
x 101010 42 ok
x 1101111111010101100101110111001110001000110100110011100000111 2016120520371234567 ok
```
[Answer]
# C, ~~41~~ 37 bytes
```
i;b(char*s){i+=i+*s++%2;i=*s?b(s):i;}
```
[Wandbox](http://melpon.org/wandbox/permlink/HSeSFhE9lswSnFlj)
[Answer]
# SmileBASIC, ~~47~~ 44 bytes
```
INPUT B$WHILE""<B$N=N*2+VAL(SHIFT(B$))WEND?N
```
Another program of the same size:
```
INPUT B$WHILE""<B$N=N*2OR"0"<SHIFT(B$)WEND?N
```
[Answer]
# APL(NARS), 26 chars, 52 bytes
```
{+/a×⌽1,2x*⍳¯1+≢a←1-⍨⎕D⍳⍵}
```
test:
```
f←{+/a×⌽1,2x*⍳¯1+≢a←1-⍨⎕D⍳⍵}
⎕fmt f"0"
0
~
f"1"
1
⎕fmt f"101010"
42
~~
f"10"
2
(≢,f)"11011111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111"
152 4995366924470859583704000893073232977339613183
```
152 bits... It should be limited from memory for store string and numbers.
] |
[Question]
[
## The challenge is to calculate the digit sum of the factorial of a number.
---
Example
```
Input: 10
Output: 27
```
10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27
You can expect the input to be an integer above 0.
Output can be of any type, but the answer should be in the standard base of the coding language.
---
Test cases:
```
10 27
19 45
469 4140
985 10053
```
N.B. Some languages can not support large numbers above 32-bit integers; for those languages you will not be expected to calculate large factorials.
[OEIS link here](https://oeis.org/A004152) thanks to [Martin Ender](https://codegolf.stackexchange.com/users/8478/martin-ender)
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in characters wins!
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 3 bytes
```
!SO
```
[Try it online!](http://05ab1e.tryitonline.net/#code=IVNP&input=MTA)
```
! Factorial.
S Push characters separately.
O Sum.
```
[Answer]
## [Jelly](http://github.com/DennisMitchell/jelly), 3 bytes
```
!DS
```
[Try it online!](http://jelly.tryitonline.net/#code=IURT&input=&args=MTA)
Does what you expect:
```
! Factorial.
D Decimal digits.
S Sum.
```
[Answer]
## Mathematica, 21 bytes
```
Tr@IntegerDigits[#!]&
```
[Answer]
# C++11, 58 bytes
As unnamed lambda modifying its input:
```
[](int&n){int i=n;while(--n)i*=n;do n+=i%10;while(i/=10);}
```
One of the rare cases when my C++ code is shorter than the [C code](https://codegolf.stackexchange.com/a/100844/53667).
If you want to suppport larger cases, switch to **C++14** and use:
```
[](auto&n){auto i=n;while(--n)i*=n;do n+=i%10;while(i/=10);}
```
and supply the calling argument with `ull` suffix.
Usage:
```
auto f=
[](int&n){int i=n;while(--n)i*=n;do n+=i%10;while(i/=10);}
;
main() {
int n=10;
f(n);
printf("%d\n",n);
}
```
[Answer]
## Ruby, ~~63~~ ~~61~~ ~~53~~ 38 bytes
New approach thanks to manatwork:
```
->n{eval"#{(1..n).reduce:*}".chars*?+}
```
Old:
```
->n{(1..n).reduce(:*).to_s.chars.map(&:hex).reduce:+}
```
* -3 bytes thanks to Martin Ender
* -5 bytes thanks to G B
[Answer]
# Pyth, ~~7~~ 6 bytes
*Thanks to @Kade for saving me a byte*
`sj.!QT`
[Try it online!](https://pyth.herokuapp.com/?code=sj.%21Q10&input=10&debug=0)
This is my first time using Pyth, so I'm sure that my answer could be golfed quite a bit.
Explanation:
```
s Sum
j the digits of
.! the factorial of
Q the input
T in base 10
```
[Answer]
## Haskell, ~~41~~ 40 bytes
```
f x=sum$read.pure<$>(show$product[1..x])
```
Usage example: `f 985` -> `10053`.
Make a list from `1`to `x`, calculate the product of the list elements, turn it into its string representation, turn each character into a number and sum them.
Edit: @Angs saved a byte. Thanks!
[Answer]
# Python, 54 bytes
```
f=lambda n,r=1:n and f(n-1,r*n)or sum(map(int,str(r)))
```
**[repl.it](https://repl.it/E6Vu)**
[Answer]
## R, 58 53 bytes
Edit: Saved one byte thanks to @Jonathan Carroll and a couple thanks to @Micky T
```
sum(as.double(el(strsplit(c(prod(1:scan()),""),""))))
```
Unfortunately, with 32-bit integers, this only works for `n < 22`. Takes input from stdin and outputs to stdout.
If one would like higher level precision, one would have to use some external library such as `Rmpfr`:
```
sum(as.numeric(el(strsplit(paste(factorial(Rmpfr::mpfr(scan()))),""))))
```
[Answer]
# [Pip](http://github.com/dloscutoff/pip), 8 bytes
```
$+$*++,a
```
[Try it online!](http://pip.tryitonline.net/#code=JCskKisrLGE&input=&args=MTA)
**Explanation**
```
,a # range
++ # increment
$* # fold multiplication
$+ # fold sum
```
[Answer]
## [CJam](http://sourceforge.net/projects/cjam/), 8 bytes
```
rim!Ab:+
```
[Try it online!](http://cjam.tryitonline.net/#code=cmltIUFiOis&input=MTA)
### Explanation
```
r e# Read input.
i e# Convert to integer.
m! e# Take factorial.
Ab e# Get decimal digits.
:+ e# Sum.
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 8 bytes
-3 thanks to @Razetime - i forgot to drop a paren lol
```
+/⍎¨∘⍕∘!
```
Explanation:
```
+/⍎¨∘⍕∘!
! ⍝ factorial of ⍵
⍕ ⍝ convert to string
⍎¨ ⍝ produce digit vector
+/ ⍝ sum all digits
```
Has some problems with factorial of 900, this code will work fine for `⍵>40`:
```
b←({⍵⊣⍵.⎕CY'dfns'}⎕NS⍬).big
↑(+b/(⍎¨∘⍕∘(↑(×b/⍳))))
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfmv8ahvqlsQkAgI0HzUNsHQyMJcwdjkfxqQra2v8ai379CKRx0zHvVOBZKKj7oWaf4HqgVKpikYGnDBmZZwprHBfwA "APL (Dyalog Extended) – Try It Online")
[Answer]
# [Brachylog](http://github.com/JCumin/Brachylog), 5 bytes
```
$!@e+
```
[Try it online!](http://brachylog.tryitonline.net/#code=JCFAZSs&input=OTg1&args=Wg)
### Explanation
Basically the described algorithm:
```
$! Take the factorial of the Input
@e Take the elements of this factorial (i.e. its digits)
+ Output is the sum of those elements
```
[Answer]
# Java 7, 148 bytes
```
int s=1,ret=0;while(i>1){s=s*i; i--;}String y=String.valueOf(s);for(int j=0;j<y.length();j++){ret+=Integer.parseInt(y.substring(j,j+1));}return ret;
```
[Answer]
# Ruby, ~~63 60 53~~ 51 bytes
```
->n{a=0;f=(1..n).reduce:*;f.times{a+=f%10;f/=10};a}
```
Thanks to Martin for golfing help.
[Answer]
# [Pushy](https://github.com/FTcode/Pushy), 4 bytes
```
fsS#
```
Give input on the command line: `$ pushy facsum.pshy 5`. Here's the breakdown:
```
f % Factorial of input
s % Split into digits
S % Push sum of stack
# % Output
```
[Answer]
# Octave, 30 bytes
```
@(n)sum(num2str(prod(1:n))-48)
```
Calculates the factorial by taking the product of the list `[1 2 ... n]`. Converts it to a string and subtracts `48` from all elements (ASCII code for `0`). Finally it sums it up :)
[Answer]
## bash (seq,bc,fold,jq), ~~34~~ 33 bytes
Surely not the most elegant but for the challenge
```
seq -s\* $1|bc|fold -1|jq -s add
```
[Answer]
## C, 58 bytes
This is not perfect. Only works ones because a have to be -1 in start. The idea is to use two recursive function in one function. It was not as easy as I first thought.
```
a=-1;k(i){a=a<0?i-1:a;return a?k(i*a--):i?i%10+k(i/10):0;}
```
Usage and understandable format:
```
a = -1;
k(i){
a = a<0 ? i-1 : a;
return a ? k(i*a--) : i? i%10+k(i/10) :0;
}
main() {
printf("%d\n",k(10));
}
```
Edit:
I found metode that let use this function multiple time but then length is 62 bytes.
```
a,b;k(i){a=b?a:i+(--b);return a?k(i*a--):i?i%10+k(i/10):++b;}
```
[Answer]
# [Perl 6](https://perl6.org), 21 bytes
```
{[+] [*](2..$_).comb}
```
## Expanded:
```
{ # bare block lambda with implicit parameter 「$_」
[+] # reduce the following with 「&infix:<+>」
[*]( # reduce with 「&infix:<*>」
2 .. $_ # a Range that include the numbers from 2 to the input (inclusive)
).comb # split the product into digits
}
```
[Answer]
# Cubix, ~~33~~ 32 bytes
```
u*.$s.!(.01I^<W%NW!;<,;;q+p@Opus
```
Net form:
```
u * .
$ s .
! ( .
0 1 I ^ < W % N W ! ; <
, ; ; q + p @ O p u s .
. . . . . . . . . . . .
. . .
. . .
. . .
```
[Try it online!](https://ethproductions.github.io/cubix/?code=dSouJHMuISguMDFJXjxXJU5XITs8LDs7cStwQE9wdXM=&input=MTA=&speed=2000)
# Notes
* Works with inputs up to and including 170, higher inputs result in an infinite loop, because their factorial yields the `Infinity` number (technically speaking, its a non-writable, non-enumerable and non-configurable property of the window object).
* Accuracy is lost for inputs 19 and up, because numbers higher than 253 (= 9 007 199 254 740 992) cannot be accurately stored in JavaScript.
# Explanation
This program consists of two loops. The first calculates the factorial of the input, the other splits the result into its digits and adds those together. Then the sum is printed, and the program finishes.
## Start
First, we need to prepare the stack. For that part, we use the first three instructions. The IP starts on the fourth line, pointing east. The stack is empty.
```
. . .
. . .
. . .
0 1 I . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . .
. . .
. . .
```
We will keep the sum at the very bottom of the stack, so we need to start with `0` being the sum by storing that on the bottom of the stack. Then we need to push a `1`, because the input will initially be multiplied by the number before it. If this were zero, the factorial would always yield zero as well. Lastly we read the input as an integer.
Now, the stack is `[0, 1, input]` and the IP is at the fourth line, the fourth column, pointing east.
### Factorial loop
This is a simple loop that multiplies the top two elements of the stack (the result of the previous loop and the input - n, and then decrements the input. It breaks when the input reaches 0. The `$` instruction causes the IP to skip the `u`-turn. The loop is the following part of the cube. The IP starts on the fourth line, fourth column.
```
u * .
$ s .
! ( .
. . . ^ < . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . .
. . .
. . .
```
Because of the `^` character, the IP starts moving north immediately. Then the `u` turns the IP around and moves it one to the right. At the bottom, there's another arrow: `<` points the IP back into the `^`. The stack starts as `[previousresult, input-n]`, where `n` is the number of iterations. The following characters are executed in the loop:
```
*s(
* # Multiply the top two items
# Stack: [previousresult, input-n, newresult]
s # Swap the top two items
# Stack: [previousresult, newresult, input-n]
( # Decrement the top item
# Stack: [previousresult, newresult, input-n-1]
```
Then the top of the stack (decreased input) is checked against `0` by the `!` instruction, and if it is `0`, the `u` character is skipped.
### Sum the digits
The IP wraps around the cube, ending up on the very last character on the fourth line, initially pointing west. The following loop consists of pretty much all remaining characters:
```
. . .
. . .
. . .
. . . . . W % N W ! ; <
, ; ; q + p @ O p u s .
. . . . . . . . . . . .
. . .
. . .
. . .
```
The loop first deletes the top item from the stack (which is either `10` or `0`), and then checks what is left of the result of the factorial. If that has been decreased to `0`, the bottom of the stack (the sum) is printed and the program stops. Otherwise, the following instructions get executed (stack starts as `[oldsum, ..., factorial]`):
```
N%p+q;;,s;
N # Push 10
# Stack: [oldsum, ..., factorial, 10]
% # Push factorial % 10
# Stack: [oldsum, ..., factorial, 10, factorial % 10]
p # Take the sum to the top
# Stack: [..., factorial, 10, factorial % 10, oldsum]
+ # Add top items together
# Stack: [..., factorial, 10, factorial % 10, oldsum, newsum]
q # Send that to the bottom
# Stack: [newsum, ..., factorial, 10, factorial % 10, oldsum]
;; # Delete top two items
# Stack: [newsum, ..., factorial, 10]
, # Integer divide top two items
# Stack: [newsum, ..., factorial, 10, factorial/10]
s; # Delete the second item
# Stack: [newsum, ..., factorial, factorial/10]
```
And the loop starts again, until `factorial/10` equals 0.
[Answer]
## C, 47 bytes
```
f(n,a){return n?f(n-1,a*n):a?a%10+f(0,a/10):0;}
```
usage:
```
f(n,a){return n?f(n-1,a*n):a?a%10+f(0,a/10):0;}
main() {
printf("answer: %d\n",f(10,1));
}
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog) (v2), 3 bytes
```
ḟẹ+
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@GO@Q937dT@/9/SwvR/FAA "Brachylog – Try It Online")
Same "algorithm" as the [v1 answer](https://codegolf.stackexchange.com/a/100832/8774) by @Fatalize, just with better encoding.
[Answer]
# Python, 57 bytes
```
import math
lambda n:sum(map(int,str(math.factorial(n))))
```
[**Try it online**](https://repl.it/E6TZ)
[Answer]
## Batch, 112 bytes
```
@set/af=1,t=0
@for /l %%i in (1,1,%1)do @set/af*=%%i
:g
@set/at+=f%%10,f/=10
@if %f% gtr 0 goto g
@echo %t%
```
Conveniently `set/a` works on a variable's current value, so it works normally inside a loop. Only works up to 12 due to the limitations of Batch's integer type, so in theory I could save a byte by assuming `f<1e9`:
```
@set/af=1,t=0
@for /l %%i in (1,1,%1)do @set/af*=%%i
@for /l %%i in (1,1,9)do @set/at+=f%%10,f/=10
@echo %t%
```
But that way lies madness... I might as well hard-code the list in that case (97 bytes):
```
@call:l %1 1 1 2 6 6 3 9 9 9 27 27 36 27
@exit/b
:l
@for /l %%i in (1,1,%1)do @shift
@echo %2
```
[Answer]
## JavaScript (ES6), 50 bytes
```
f=(n,m=1,t=0)=>n?f(n-1,n*m):m?f(n,m/10|0,t+m%10):t
```
Only works up to `n=22` due to floating-point accuracy limitations.
[Answer]
# [Befunge 93](http://esolangs.org/wiki/Befunge), ~~56~~ 54 bytes
Saved 2 bytes do to using get instead of quotes. This let me shift the top 2 lines over 1, reducing unnecessary white space.
[Try it online!](http://befunge-98.tryitonline.net/#code=JiM6PF92IzotMQo6IFwqJDw6X14jCmc6OnY-OTErJSswMApfdiM8XnAwMDwvKzE5CkA-JCQu&input=MTA)
```
&#:<_v#:-1
: \*$<:_^#
g::v>91+%+00
_v#<^p00</+19
@>$$.
```
Explanation:
```
&#:< Gets an integer input (n), and reverses flow direction
&#:< _v#:-1 Pushes n through 0 onto the stack (descending order)
: \*$<:_^# Throws the 0 away and multiplies all the remaining numbers together
(reorganized to better show program flow):
vp00< /+19 _v#< Stores the factorial at cell (0, 0). Pushes 3 of whatever's in
> 91+%+ 00g ::^ cell (0, 0). Pops a, and stores a / 10 at (0, 0),
and adds a % 10 to the sum.
@>$$. Simply discards 2 unneeded 0s and prints the sum.
```
[Answer]
# Javascript ES6 - 61 54 Bytes
```
n=>eval(`for(j of''+(a=_=>!_||_*a(~-_))(n,t=0))t-=-j`)
```
**EDIT:** Thank you Hedi and ETHproductions for shaving off 7 bytes. I'll have to remember that t-=-j trick.
[Answer]
# [AHK](https://autohotkey.com/), 60 bytes
```
a=1
Loop,%1%
a*=A_Index
Loop,Parse,a
b+=A_LoopField
Send,%b%
```
AutoHotkey doesn't have a built-in factorial function and the loop functions have long names for their built-in variables. The first loop is the factorial and the second is adding the digits together.
[Answer]
# J, ~~12~~ 11 bytes
*Saved 1 byte thanks to cole!*
```
1#.10#.inv!
```
This simply applies sum (`1#.`) to the digits (using inverse `inv` of base conversion `#.` with a base of `10`) of the factorial (`!`) of the argument.
## Test cases
Note: the last two test cases are bigints, as marked by a trailing `x`.
```
f=:10#.inv!
(,. f"0) 10 19 469x 985x
10 27
19 45
469 4140
985 10053
```
] |
[Question]
[
Since Halloween is coming up I thought I might start a fun little code golf challenge!
The challenge is quite simple. You have to write a program that outputs either `trick` or `treat`.
"The twist?" you may ask. Well let me explain:
Your program has to do the following:
* Be compilable/runnable in two different languages. Different versions of the same language don't count.
* When you run the program in one language it should output `trick` and the other should output `treat`. The case is irrelevant and padding the string with whitespace characters are allowed (see examples).
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the solution with the fewest bytes wins.
A few explanations:
**Valid outputs** (Just for the words not for running the code in the two languages. Also adding quotes to signalize the beginning or end of the output. Do not include them in your solution!):
```
"trick"
"Treat"
" TReAt"
"
tRICk "
```
**Invalid outputs**:
```
"tri ck"
"tr
eat"
"trck"
```
I'm interested to see what you can come up with! Happy Golfing!
I'd like to note that this is my first challenge so if you have suggestions on this question please leave them in the form of a comment.
## Leaderboards
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
# Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
# Ruby, <s>104</s> <s>101</s> 96 bytes
```
If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:
```
# Perl, 43 + 2 (-p flag) = 45 bytes
```
You can also make the language name a link which will then show up in the leaderboard snippet:
```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes
```
```
var QUESTION_ID=97472,OVERRIDE_USER=23417;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=o.replace(TAGS_REG,"")),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,TAGS_REG = /(<([^>]+)>)/ig;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:400px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```
[Answer]
## Python / Windows Batch, 25 bytes
```
print"trick"#||echo.treat
```
Everything after the # is interpreted as a comment by python, while the || is an OR in batch, saying that as the previous command failed, execute this one.
I also like the use of an OR as it almost reads "trick or treat" :)
[Answer]
# Whitespace / Starry, 135 bytes
Here's to a clear night sky on Halloween!
```
+ + + + +
+
* + +* + *
+ *
+ +
+* +
+* + . + . + +* + +* . . .
```
*Note that whitespace on empty lines may not be preserved if you copy from the above code*
Whitespace outputs "TRICK". [Try it Online!](http://whitespace.tryitonline.net/#code=ICAgCSAJICAJIAogICsgKwkgKwkgCSsgKyAKCSsKICAJCiogKyAgICsqIAkgICsJICAJKgoJCiAgICsgIAkqICAJIAkJCiAgIAkgKyArICAJCQoJCiArKiArCQogIAoKCiArKiArIC4gICsgLiAgICsgICAgICArKiArICAgKyogLiAuIC4K)
Starry outputs "TREAT". [Try it Online!](http://starry.tryitonline.net/#code=ICAgCSAJICAJIAogICsgKwkgKwkgCSsgKyAKCSsKICAJCiogKyAgICsqIAkgICsJICAJKgoJCiAgICsgIAkqICAJIAkJCiAgIAkgKyArICAJCQoJCiArKiArCQogIAoKCiArKiArIC4gICsgLiAgICsgICAgICArKiArICAgKyogLiAuIC4K)
## Explanation
### Starry
Starry ignores all tabs and new lines so the code it reads is the following
```
+ + + + + + * + +* + * + * + + +* + +* + . + . + +* + +* . . .
```
Bytewise, pushing values is very expensive compared to stack and arithmetic operations in Starry. The code starts by pushing and duplicating 4 and the performs a number of operations on it and with 2 and 1 pushed later on produces all of the required ASCII values.
**Annotated Code**
```
Stack (after op) Code Operation
4 + Push 4
4 4 4 4 4 4 + + + + + Duplicate top of stack 5 times
4 4 4 4 16 * Multiply top two items
4 4 4 4 16 16 + Duplicate top of stack
4 4 4 16 4 16 + Rotate top three items on stack right
4 4 4 16 20 * Add top two items
4 4 20 4 16 + Rotate...
4 4 20 64 * Multiply...
4 64 4 20 + Rotate...
4 64 80 * Multiply...
4 64 80 2 + Push 2
4 64 80 2 2 + Duplicate...
4 64 2 80 2 + Rotate...
4 64 2 82 * Add...
4 64 2 82 82 + Duplicate...
4 64 82 2 82 + Rotate...
4 64 82 84 * Add...
4 64 82 84 84 + Rotate...
4 64 82 84 . Pop and print as character (T)
4 64 84 82 + Swap top two items on stack
4 64 84 . Pop and print... (R)
84 4 64 + Rotate...
84 4 64 1 + Push 1
84 4 65 * Add...
84 4 65 65 + Duplicate...
84 65 4 65 + Rotate...
84 65 69 * Add...
84 65 . Pop and print... (E)
84 . Pop and print... (A)
. Pop and print... (T)
```
### Whitespace
As the name may suggest, Whitespace only parses the three whitespace characters—space, tab, and newline. Unlike the Starry, the Whitespace simply pushes the ASCII values of `T`, `R`, `I`, `C`, and `K` and the prints them.
**Annotated Code**
```
<Space><Space><Space><Tab><Space><Tab><Space><Space><Tab><Space><LF> Push the ASCII value of R
<Space><Space><Space><Tab><Space><Tab><Space><Tab><Space><Space><LF> Push the ASCII value of T
<Tab><LF><Space><Space> Pop and print the T
<Tab><LF><Space><Space> Pop and print the R
<Space><Space><Space><Tab><Space><Space><Tab><Space><Space><Tab><LF> Push the ASCII value of I
<Tab><LF><Space><Space> Pop and print the I
<Space><Space><Space><Tab><Space><Space><Tab><Space><Tab><Tab><LF> Push the ASCII value of K
<Space><Space><Space><Tab><Space><Space><Space><Space><Tab><Tab><LF> Push the ASCII value of C
<Tab><LF><Space><Space> Pop and print the C
<Tab><LF><Space><Space> Pop and print the K
<LF><LF><LF> Terminate the program. The following line is not run.
<Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><LF>
```
The interweaving of pushes and prints was chosen based solely on aesthetic reasons as it does not affect the byte count.
[Answer]
# [2sable](http://github.com/Adriandmen/2sable) / [pl](https://github.com/quartata/pl-lang), 8 bytes
```
0000000: 74 72 65 61 74 93 d0 cb treat...
```
Both programs have been tested locally with the same 8 byte file, so this is a proper polyglot.
### 2sable: trick
This is the program in [code page 1252](https://en.wikipedia.org/wiki/Windows-1252#Code_page_layout).
```
treat“ÐË
```
[Try it online!](http://2sable.tryitonline.net/#code=dHJlYXTigJzDkMOL&input=)
### pl: treat
This is the program in [code page 437](https://en.wikipedia.org/wiki/Code_page_437#Characters).
```
treatô╨╦
```
[Try it online!](http://pl.tryitonline.net/#code=dHJlYXTDtOKVqOKVpg&input=)
## How it works
### 2sable: trick
```
t Square root. Errors since there is no input. The exception is caught, the
stack left unaltered, and the interpreter pretends nothing happened.
r Reverse stack.
Reversed empty stack is still empty stack. ;(
e Compute nCr. Errors since there is no input.
a Alphanumeric test. Errors since there is no input.
t Square root. Errors since there is no input.
“ Begin a lowercase string literal.
Ð Excluding ‘, ’, “, and ”, Ð is the 71st non-ASCII character in CP1252.
Ë Excluding ‘, ’, “, and ”, Ë is the 66th non-ASCII character in CP1252.
(implicit) End string literal.
Both characters together fetch the dictionary word at index
71 * 100 + 66 = 7166, which is 'trick'.
```
### pl: treat
```
treat Bareword; push the string "treat" on the stack.
ô Unimplemented. Does nothing.
╨ Flatten the stack. This doesn't affect the output.
╦ Unimplemented. Does nothing.
```
[Answer]
# Linux ELF x86 / DOS .COM file, 73 bytes
```
00000000 7f 45 4c 46 01 00 00 00 1a 00 00 00 1a 00 43 05 |.ELF..........C.|
00000010 02 00 03 00 1a 00 43 05 1a 00 43 05 04 00 00 00 |......C...C.....|
00000020 eb 0c b4 09 ba 41 01 cd 21 c3 20 00 01 00 b2 05 |.....A..!. .....|
00000030 b9 3b 00 43 05 cd 80 2c 04 cd 80 74 72 69 63 6b |.;.C...,...trick|
00000040 00 74 72 65 61 74 24 eb d9 |.treat$..|
00000049
```
NASM source:
```
ORG 0x05430000
BITS 32 ;
; ELF HEADER -- PROGRAM HEADER
; ELF HEADER ; +-------------+
DB 0x7f,'E','L','F' ; | magic | +--------------------+
; | | | |
; PROGRAM HEADERS ; | | | |
DD 1 ; |*class 32b | -- | type: PT_LOAD |
; |*data none | | |
; |*version 0 | | |
; |*ABI SysV | | |
DD 0x01a ; offset = vaddr & (PAGE_SIZE-1); |*ABI vers | -- | offset |
; | | | |
entry: DD 0x0543001a ; |*PADx7 | -- | vaddr = 0x0543001a |
DW 2 ; | ET_EXEC | -- |*paddr LO |
DW 3 ; | EM_386 | -- |*paddr HI |
DD 0x0543001a ; |*version | -- | filesz |
; inc ebx ; STDOUT_FILENO ; | | | |
; mov eax, 4 ; SYS_WRITE ; | | | |
DD 0x0543001a ; | entry point | -- | memsz |
DD 4 ; | ph offset | -- | flags: RX |
; | | | |
jmp short skip ; |*sh offset | -- |*align |
BITS 16 ; | | | |
treat: mov ah, 9 ; | | -- | |
mov dx, trick + 0x100 + 6 ; |*flags ______| | |
int 0x21 ; |______/ | +--------------------+
ret ; |*ehsize |
BITS 32 ; | |
DW 32 ; | phentsize |
DW 1 ; | phnum |
skip: ; | |
mov dl, 5 ; strlen("trick") ; |*shentsize |
mov ecx, trick ; |*shnum |
; |*shstrndx |
; +-------------+
int 0x80
sub al, 4 ; SYS_EXIT
int 0x80
trick: DB "trick/treat$"
BITS 16
jmp short treat
```
This uses the fact that the ELF header starts with 7F 45, which, interpreted as x86 code, is a jump.
The relevant parts for the DOS .COM:
```
-u100 l2
07D2:0100 7F45 JG 0147
-u147 l2
07D2:0147 EBD9 JMP 0122
-u122 l8
07D2:0122 B409 MOV AH,09
07D2:0124 BA4101 MOV DX,0141
07D2:0127 CD21 INT 21
07D2:0129 C3 RET
-d141 l6
07D2:0140 74 72 65 61 74 24 - treat$
```
[Answer]
# [evil](http://esolangs.org/wiki/Evil) / [ZOMBIE](http://www.dangermouse.net/esoteric/zombie.html), 109 bytes
Another spooky answer !
```
xf is a vampire summon task f say "trick" stumble say "jzuueeueeawuuwzaeeaeeaeawuuuuwzuueeueeaw" animate bind
```
The `ZOMBIE` code defines a `vampire` named `xf` whose only task `f` is activated at instanciation and will output `trick` once before being deactivated by `stumble`. The other `say` call is dead code (how appropriate !) for `ZOMBIE`, but contains most of the `evil` code.
For `evil`, the `xf` name is a call to jump to the next `j`, which precedes the `zuueeueeawuuwzaeeaeeaeawuuuuwzuueeueeaw` zombie moan that crafts and output `treat`. The code following is either executed (lowercase letters) or ignored but since there's no `w` no output should be produced.
[Answer]
## Python / Perl, 28 bytes
```
print([]and"trick"or"treat")
```
## Explanation
Since `[]` is an ArrayRef in Perl, it's truthy, but it's an empty array in Python, therefore falsy.
[Answer]
## PHP / JavaScript, ~~32~~ 30 bytes
Displays `trick` in PHP and `treat` in JS.
```
NaN?die(trick):alert('treat');
```
The unknown `NaN` constant is implicitly converted to a string by PHP, making it truthy. It's falsy in JS.
### Alternative method, 38 bytes
```
(1?0:1?0:1)?die(trick):alert('treat');
```
The ternary operator is right-associative in JS:
```
1 ? 0 : 1 ? 0 : 1
is parsed as: 1 ? 0 : (1 ? 0 : 1)
which equals: 0
```
And left-associative in PHP:
```
1 ? 0 : 1 ? 0 : 1
is parsed as: (1 ? 0 : 1) ? 0 : 1
which equals: 1
```
[Answer]
# HTML / HTML+JavaScript, 53 bytes
```
treat<script>document.body.innerHTML='trick'</script>
```
`treat` is the document´s text content in HTML.
If JS is enabled, it will replace the HTML content with `trick`.
[Answer]
# C / Java 7, ~~165~~ ~~155~~ ~~128~~ ~~123~~ ~~122~~ ~~120~~ 103 bytes
```
//\
class a{public static void main(String[] s){System.out.print("treat"/*
main(){{puts("trick"/**/);}}
```
//\ makes the next line also a comment in C but is a regular one line comment in Java, so you can make C ignore code meant for Java and by adding /\* in the second line you can make a comment for Java that is parsed as code by C.
Edit:
I improved it a little bit by reorganizing the lines and comments.
Edit2:
I did some more reorganizing and shortened it even more.
Edit3:
I added corrections suggested by BrainStone to remove 5 bytes, thanks :)
Edit4:
One newline turned out to be unnecessary so I removed it.
Edit5:
I changed printf to puts.
Edit6:
I added a correction suggested by Ray Hamel.
[Answer]
# Jolf + Chaîne, 12 bytes
Because Chaîne cannot accept a file to upload with an encoding, I assume UTF-8. (If I could assume ISO-8859-7, this would be 11 bytes, but that would be unfair.)
```
trick«treat
```
In Chaîne, `«` begins a comment, and the rest is printed verbatim. In Jolf, `«` begins a string. Thankfully, `trick` does nothing harmful (`10; range(input, parseInt(input))` basically), and `treat` is printed.
[Try Jolf here!](http://conorobrien-foxx.github.io/Jolf/#code=dHJpY2vCq3RyZWF0)
[Try Chaîne here!](http://conorobrien-foxx.github.io/Cha-ne/?code%3Dtrick%C2%ABtreat%7C%7Cinput%3D)
They both work on my browser (firefox, latest version), but the same cannot be said for other browsers.
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix/) / [Hexagony](https://github.com/m-ender/hexagony), 31 bytes
```
t;./e;_a]"kcirt">o?@;=v=./r;\;/
```
[Trick it out!](http://ethproductions.github.io/cubix/?code=dDsuL2U7X2FdImtjaXJ0Ij5vP0A7PXY9Li9yO1w7Lw==) [Treat it online!](http://hexagony.tryitonline.net/#code=dDsuL2U7X2FdImtjaXJ0Ij5vP0A7PXY9Li9yO1w7Lw&input=)
*Halloween themed*? Note the horrifying facts about these languages and the code:
1. If and even if you do nothing (just put no-ops), you can *never* get out of the loop that is determined to be running forever...
2. And being stuck in the middle of a 3D and a 2D programming language (Oh agony...)
3. Inside the dimensions, you'll gradually lost where you are... where you were...
4. And there is a `=v=` smiling at you which acts at no-ops in the code
Let's dig into the mystery of the hidden 31-bytes communication protocol of dimensions and terror...
## trick
When the code folds or unfolds itself... That is `cubified`, the layout looks like this:
```
t ; .
/ e ;
_ a ]
" k c i r t " > o ? @ ;
= v = . / r ; \ ; / . .
. . . . . . . . . . . .
. . .
. . .
. . .
```
And the main part is this part in the middle:
```
" k c i r t " > o ? @ .
. . . . . . . \ ; / . .
```
It pushes `k,c,i,r,t` onto the stack and `o` outputs and `;` pops within a loop bounded by reflectors and `?` which guides you depending on the value on the top of the stack...
## treat
All of a sudden, the code transforms from a cube to a Hexagon. (Imagine that)
```
t ; . /
e ; _ a ]
" k c i r t
" > o ? @ ; =
v = . / r ;
\ ; / . .
. . . .
```
And the main part is this part:
```
t ; . /
e ; _ a ]
. . . . . .
. . . . @ ; =
. . . / r ;
. . . . .
. . . .
```
It runs `t;` which prints `t` and hits the mirror and turns its direction to NW starting from the SE corner and hits another mirror. This runs `r;` and wraps to `e;_a` and the `]` brings it to the Instruction Pointer 1 which starts at corner NE pointing SE and hits `/` which reflects horizontally to `;` then `t`.
Then it wraps to `=`, `;`, and `@` ends the mess.
So... What is `_` doing there?
*Why* is it inside the `t` `e` `a` (the first 3 letters in the code)?
Here comes the end of the story -
it does *nothing*.
Does it sound like the end of a horror story?
[Answer]
# [#hell](http://esolangs.org/wiki/HashHell) / [Agony](http://esolangs.org/wiki/Agony), 43 bytes
So much `><>` everywhere, what is this, an April Fools challenge? Here's an answer with appropriately themed languages.
```
--<.<.<.<.<.$
io.write("trick")--+<~}~@+{+<
```
`#hell` is a subset of `LUA` which fortunately accepts `io.write` output calls. We use `LUA`'s `--` comments so that it only executes this fragment.
`Agony` is a `Brainfuck` derivative, which has the particularity to have its code and working memory on the same tape. The first line only prints 5 characters (10 cells) from the end of the code segment, where I encoded `treat` as `Agony` commands. `LUA`'s comment opening `--` modifies the value of a cell which isn't used.
[Answer]
## SQL / Javascript, 54 bytes
```
select('trick')
--a;function select(){alert("treat")}
```
Same approach as with my [QB/JS answer](https://codegolf.stackexchange.com/questions/97472/trick-or-treat-polyglot/97509#97509): First line has the SQL statement, the second line has a 'comment' for SQL and a NOP for JS. Then, we define SQL's `select` statement as a valid JS function.
[Answer]
# /Brainf..k/, 143 + 3 = 146 bytes
This answer requires the `-A` flag to output in ASCII for Brain-Flak and luckily Brainfuck doesn't care about that flag so it doesn't affect the output in Brainfuck.
```
(((((()(()()()){})({}){}){}){})+++++++[<+++<(((()()()())((((({}){}){}){}){}()))[][][][]())>>-])<[<++++>-]<.--.---------.------.>++[<++++>-]<.>>
```
[Try it Online!](http://brain-flak.tryitonline.net/#code=KCgoKCgoKSgoKSgpKCkpe30pKHt9KXt9KXt9KXt9KSsrKysrKytbPCsrKzwoKCgoKSgpKCkoKSkoKCgoKHt9KXt9KXt9KXt9KXt9KCkpKVtdW11bXVtdKCkpPj4tXSk8WzwrKysrPi1dPC4tLS4tLS0tLS0tLS0uLS0tLS0tLj4rK1s8KysrKz4tXTwuPj4&args=LUE)
[Try it Online!](http://brainfuck.tryitonline.net/#code=KCgoKCgoKSgoKSgpKCkpe30pKHt9KXt9KXt9KXt9KSsrKysrKytbPCsrKzwoKCgoKSgpKCkoKSkoKCgoKHt9KXt9KXt9KXt9KXt9KCkpKVtdW11bXVtdKCkpPj4tXSk8WzwrKysrPi1dPC4tLS4tLS0tLS0tLS0uLS0tLS0tLj4rK1s8KysrKz4tXTwuPj4&args=LUE)
## How this works
The only overlap between the syntax of Brain-Flak and Brainfuck are the characters `<>[]`. For brain-flak this mostly means the program has to ensure an even number of stack switches `<>`. And for Brainfuck this means we need to avoid infinite loops caused by use of the `[]` monad.
The Brain-Flak code is as follows:
```
(((((()(()()()){})({}){}){}){})[<<(((()()()())((((({}){}){}){}){}()))[][][][]())>>])<[<>]<>[<>]<>>
```
Aside from the `[<<...>>]` bit in the middle and the `<[<>]<>[<>]<>>` at the end this code is pretty par for the course as far as Brain-Flak programs go. The negative around the zero (`[<...>]`) is there to create a loop for Brainfuck. The inner `<...>` is used to move the Brainfuck to an empty cell before it encounters the `[][][][]` which would loop infinitely otherwise.
The Brainfuck code is as follows:
```
+++++++[<+++<[][][][]>>-]<[<++++>-]<.--.---------.------.>++[<++++>-]<.>>
```
Aside from the aforementioned bits this is also a pretty standard program so I will spare you the details.
[Answer]
# [><>](https://esolangs.org/wiki/Fish) / [Fishing](https://esolangs.org/wiki/Fishing), 38 bytes
```
_"kcirt"ooooo;
[+vCCCCCCCC
`treat`N
```
For the sake of making a `><>` / `Fishing` polyglot.
It's my first piece of `Fishing` code after having played for a long time with `><>`.
My first impression : as in nature, the fisherman has less physical capabilities than its pray but makes up for it with its tool !
Here the code is extremely simple : `><>` will only execute the first line, where `_` is a vertical mirror and has no effect since the fish starts swimming horizontally. It just pushes `trick` on the stack then print it before stopping.
For `Fishing`, the `_` instructs to go down. The fisherman will follow the deck that is the second line while catching the characters of the third line. These will push `treat` on the tape then print it, stopping as it reaches the end of the deck.
If erroring out is allowed, you could go down to 35 bytes with the following code which will throw an error when run as `><>` once the `trick` is printed off the stack :
```
_"kcirt">o<
[+vCCCCCCCC
`treat`N
```
---
You should also check my themed languages answers, [#hell / Agony](https://codegolf.stackexchange.com/questions/97472/trick-or-treat-polyglot/97533#97533) and [evil / ZOMBIE](https://codegolf.stackexchange.com/questions/97472/trick-or-treat-polyglot/97542#97542) !
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E)/[Actually](https://github.com/Mego/Seriously), 10 bytes
```
"trick"’®Â
```
**Explanation**
**05AB1E**
```
"trick" # push the string "trick"
’®Â # push the string "treat"
# implicitly print top of stack (treat)
```
[Try it online](http://05ab1e.tryitonline.net/#code=InRyaWNrIuKAmcKuw4I&input=)
**Actually**
```
"trick" # push the string "trick"
’®Â # not recognized commands (ignored)
# implicit print (trick)
```
[Try it online](http://actually.tryitonline.net/#code=InRyaWNrIuKAmcKuw4I&input=)
[Answer]
# [Haskell](https://www.haskell.org/) / [Standard ML](https://en.wikipedia.org/wiki/Standard_ML), 56 bytes
```
fun putStr x=print"treat";val main=();main=putStr"trick"
```
**Haskell view**
The semicolons allow multiple declarations in one line and act like linebreaks, so we get
```
fun putStr x=print"treat"
val main=()
main=putStr"trick"
```
A Haskell program is executed by calling the `main` function, so in the last row `putStr"trick"` is executed which just prints `trick`.
The first two rows are interpreted as function declarations following the pattern `<functionName> <argumentName1> ... <argumentNameN> = <functionBody>`. So in the first row a function named `fun` is declared which takes two arguments named `putStr` and `x` and the function body `print"treat"`. This is a valid Haskell function with type `fun :: t -> t1 -> IO ()`, meaning it takes an argument of an arbitrary type `t` and a second one of some type `t1` an then returns an IO-action. The types `t` and `t1` don't matter as the arguments aren't used in the function body. The IO-action type results from `print"treat"`, which prints `"treat"` to StdOut (notice the `"`, that's why `putStr` instead of `print` is used in `main`). However as it's only a function declaration, nothing is actually printed as `fun` is not called in `main`.
The same happens in the second line `val main=();`, a function `val` is declared which takes an arbitrary argument named `main` and returns *unit*, the empty tuple `()`. It's type is `val :: t -> ()` (Both the value and the type of *unit* are denoted with `()`).
[Try it on Ideone.](http://ideone.com/MYQF7C)
---
**Standard ML view**
[Standard ML](https://en.wikipedia.org/wiki/Standard_ML) is a primarily functional language with a syntax related to, but not the same as Haskell. In particular, function declarations are prefixed with the keyword `fun` if they take any arguments, and the keyword `val` if they don't. Also it's possible to have an expression at top level (meaning not inside any declaration) which is executed when the program is run. (In Haskell writing `1+2` outside a declaration throws a `naked expression at top level`-error). Finally the symbol for testing equality is `=` instead of `==` in Haskell. (There are many more differences, but those are the only ones that matter for this program.)
So SML sees two declarations
```
fun putStr x=print"treat";
val main=();
```
followed by an expression
```
main=putStr"trick"
```
which is then evaluated. To determine whether `main` equals `putStr"trick"`, both sides have to be evaluated and both must have the same type, as SML (as well as Haskell) is statically typed.
Let us first have a look at the right side: `putStr` is not a library function in SML, but we declared a function named `putStr` in the line `fun putStr x=print"treat";` - it takes an argument `x` (this is the string `"trick"` in our case) and immediately forgets it again, as it does not occur in the function body. Then the body `print"treat"` is executed which prints `treat` (without enclosing `"`, SML's `print` is different from Haskell's `print`).
`print` has the type `string -> unit`, so `putStr` has the type `a -> unit` and therefore `putStr"trick"` has just type `unit`. In order to be well-typed, `main` must have type `unit` too. The value for *unit* is in SML the same as in Haskell `()`, so we declare `val main=();` and everything is well-typed.
[Try it on codingground.](http://www.tutorialspoint.com/execute_smlnj_online.php?PID=0Bw_CjBb95KQMUVp1b0JYWWRRNmc)
Note: The output in the console is
```
val putStr = fn : 'a -> unit
val main = () : unit
treatval it = true : bool
```
because in [SML\NJ](http://smlnj.org/) the value and type of every statement is displayed after each declaration. So first the types of `putStr` and `main` are shown, then the expressions gets evaluated causing `treat` to be printed, then the value of the expression (`true` as both sides of `=` are `()`) is bound to the implicit result variable `it` which is then also displayed.
[Answer]
# Ruby / C, ~~64~~ ~~62~~ ~~51~~ 48 bytes
```
#define tap main()
tap{puts(0?"trick":"treat");}
```
### What Ruby sees:
```
tap{puts(0?"trick":"treat");}
```
The `tap` method takes a block and executes it once. It's a short identifier that we can create a `#define` macro for in C. It also allows us to put a braces-enclosed block in the shared code, even though Ruby doesn't allow `{}`s in most contexts.
The only falsy values in Ruby are `false` and `nil`. In particular, 0 is truthy. Thus, Ruby will print "trick."
### What C sees (after the pre-processor):
```
main(){puts(0?"trick":"treat");}
```
0 is falsy in C, so C will print "treat."
2 bytes saved thanks to daniero.
[Answer]
## QBasic / JavaScript, ~~51~~ 44 bytes
```
'';PRINT=a=>{alert("Treat")}
PRINT("Trick")
```
In QBasic, it prints the second line and doesn't execute the first line because it's believed to be a comment (thank you '). In JS, it calls the function PRINT, which is defined on the first line, right after the JS NOP `'';`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly) / [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes
```
0000000: FE 22 74 52 69 63 6B 22 3F 37 29 FB ED 35 ."tRick"?7)..5
```
A fun one using Jelly's string compression.
**Jelly: treat**
```
“"tRick"?7)»ḣ5
```
[Try it online!](https://tio.run/##y0rNyan8//9RwxylkqDM5Gwle3PNQ7sf7lhs@v8/AA "Jelly – Try It Online")
**05AB1E: trick**
```
þ"tRick"?7)ûí5
```
[Try it online!](https://tio.run/##MzBNTDJM/f//8D6lkqDM5Gwle3PNw7sPrzX9/x8A "05AB1E – Try It Online")
**How it works**
In Jelly `“"tRick"?7)»` is a compressed string that returns `'Treatment dormy/ Orly awry'`. `ḣ5` takes the first five characters, printing `Treat`
In 05AB1E `þ` doesn't affect the program. `"tRick"` is a literal string. `?` prints this string then the rest of the program (`7)ûí5`) doesn't have any effect either.
I used [this](https://tio.run/##Dc9nV5JhGAfwr2I0bS@zrbazbXsPs0Jp27B1bh4RUbMBVKhADEVRVDYP03OuPw@dk@fchz6C1xd54t3v7a@zw2Tq0XVjMysRuFqX8kM1sDmp6zoLt6G7zdjeZWhqrKf8khps0P94/tplTMZlQiZlSqZlRqp11XhVrRaqxX@KdEindMmsDMowD/jYNsi2YbZ5WTGzorDSy4qFlT5WrHXLDMtXrFy1ek392nXrN2zctHnL1m3bG3Y07ty1e8/effubmlsOHDx0@MjRY8dbT5w8dfrM2XNt5y9cvHT5ytVr12/cvHX7zt177fc7Hjx8ZOzsMj1@8vTZ8xcvu1@9fvO25937Dx8/VVK1hhxjMVqxs/CyCLHwsfAvWllEtZqymr1s1YqVdFmwcLEYqW1ZeFgEWDhYOBfdbAlofhY5zVHu10qaWjaTnwIUpHGaoBBN0hSFaZpmKCLzNEfzFKUYxSlBSUpRmjKkUpZylKcCFalECxAwQ0EvLOiDFf2wYQCDGMJnDOMLvuIbvsMOB5z4gZ/4BRdGMIoxuOGBF7/hgx8BBDGOCYQwiSmEMY0ZRDCLOcwjihjiSCCJFNLIQEUWOeRRQBElLPwH) to convert from Jelly's code page to 05AB1E's code page. [This](https://tio.run/##DdHnUlNRGEbhW8FYsTfEDtjFjr0XBA3EjgXb7BxCCCCWJGqAJKZAIBAgPSeVme/NiTMysydegt@NHPPv@btmdXWYTL26bmxmJcLm5L/8cA1wteq6jpKhp83Y3m1oaqxHHnMN@m/PH7uMybhMyKRMybTMSLWuGq@q1UK1@FeRDumULpmVQRnmQR/bhtg2wjYvK2ZWFFb6WLGw0s@KtW6ZYfmKlatWr6lfu279ho2bNm/Zum17w47Gnbt279m7b39Tc8uBg4cOHzl67HjriZOnTp85e67t/IWLly5fuXrt@o2bt27fuXuv/X5H54OHxq5u06PHT54@e/6i5@Wr12963757/@FjJVWLkOMsxip2Fl4WIRY@Fv4lK4uoVlNWs5etWrGSLgsWLhajLNwsPCwCLBwsnEtutgQ0P4uc5igPaCVNLZvJTwEK0gRNUoimaJrCNEOzFJF5mqcFilKM4pSgJKUoTRlSKUs5ylOBilSiRQiYoaAPFvTDigHYMIghDOMTRvAZX/AV32CHA058xw/8hAujGMM43PDAi1/wwY8AgpjAJEKYwjTCmMEsIpjDPBYQRQxxJJBECmlkoCKLXG1bAUWUsPgf) does the reverse in case anyone is interested.
Jelly code page is [here](https://github.com/DennisMitchell/jelly/wiki/Code-page).
05AB1E code page is [here](https://github.com/Adriandmen/05AB1E/wiki/Codepage).
[Answer]
# [ShapeScript](http://github.com/DennisMitchell/shapescript) / [Foo](http://esolangs.org/wiki/Foo), 13 bytes
```
'trick'"treat
```
**Try it online!** [trick](http://shapescript.tryitonline.net/#code=J3RyaWNrJyJ0cmVhdA&input=) | [treat](http://foo.tryitonline.net/#code=J3RyaWNrJyJ0cmVhdA&input=)
### How it works
ShapeScript is parsed character by character. When EOF is hit without encountering a closing quote, nothing is ever pushed on the stack. `'trick'` does push the string inside the quotes, which is printed to STDOUT implicitly.
Foo doesn't have any commands assigned to the characters is `'trick'`, so that part is silently ignored. It does, however, print anything between double quotes immediately to STDOUT, even if the closing quote is missing.
[Answer]
## Ruby / Perl, 21 bytes
```
print"trick"%1||treat
```
### Perl
Calculates `"trick" % 1` which is `0 % 1` so the `||` sends `treat` to `print` instead, since Perl accepts barewords.
### Ruby
Formats the string `"trick"` with the argument `1`, which results in `"trick"` which is truthy, so the `||` isn't processed.
[Answer]
# [MATL](https://github.com/lmendo/MATL) / [CJam](https://sourceforge.net/projects/cjam/), 17 bytes
```
'TRICK'%];"TREAT"
```
In MATL this [outputs](http://matl.tryitonline.net/#code=J1RSSUNLJyVdOyJUUkVBVCI&input=) `TRICK`. In CJam it [outputs](http://cjam.tryitonline.net/#code=J1RSSUNLJyVdOyJUUkVBVCI&input=) `TREAT`.
## Explanation
### MATL
```
'TRICK' Push this string
%];"TREAT" Comment: ignored
Implicit display
```
### CJam
```
'T Push character 'T'
R Push variable R, predefined to empty string
I Push variable I, predefined to 18
C Push variable C, predefined to 12
K Push variable K, predefined to 20
'% Push character '%'
] Concatenate stack into an array
; Discard
"TREAT" Push this string
Implicit display
```
[Answer]
# Objective-C / C, 50 bytes
```
puts(){printf("trick");}main(){printf("treat\n");}
```
Objective-C got candy and [prints treat](http://ideone.com/Hdt3fO), but C didn't and [prints trick](http://ideone.com/eRC6M2).
### How it works
I don't know a lot about **Objective-C**, but it does what we'd reasonably expect in this situation. The re-definition of `puts` doesn't affect the output since we never call the function, and `main` prints **treat** and a linefeed to STDOUT.
You might expect **C** to do the same, but at least gcc 4.8, gcc 5.3, and clang 3.7 don't.
Since we do not need the *real* **printf** (which takes a format string and additional arguments) and the string to be printed ends with a linefeed, we can use **puts** instead. **puts** is slightly faster than **printf** (which has to analyze its arguments before printing), so unless we redefine the function **printf** as well, the compiler optimizes and replaces the call to **printf** with a call to **puts**. Little does the compiler know that calling `puts` with argument `"treat"` will print **trick** instead!
Not including **stdio.h** is crucial here, since defining **puts** would require using the same type it has in the header file (`puts(const char*)`).
Finally, it is noteworthy that the call to **printf** in **puts** passes a string *without* a trailing linefeed. Otherwise, the compiler would "optimize" that call as well, resulting in a segmentation fault.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly) / [pl](http://github.com/quartata/pl-lang), 12 bytes
```
0000000: 74 72 65 61 74 0a 7f fe 00 ba 49 fb treat.....I.
```
This is the program displayed using [Jelly's code page](https://github.com/DennisMitchell/jelly/wiki/Code-page).
```
treatµ
“¡ṾI»
```
[Try it online!](http://jelly.tryitonline.net/#code=dHJlYXTCtQrigJzCoeG5vknCuw&input=)
This is the program displayed using [code page 437](https://en.wikipedia.org/wiki/Code_page_437#Characters).
```
treat
⌂■␀║I√
```
[Try it online!](http://pl.tryitonline.net/#code=dHJlYXQK4oyC4pag4pCA4pWRSeKImg&input=)
Both programs have been tested locally with the same 12 byte file, so this is a proper polyglot.
### How it works
In Jelly, every line defines a *link* (function); the last line defines the *main link*, which is executed automatically when the program is run. Unless the code before the last `7f` byte (the linefeed in Jelly's code page) contain a parser error (which would abort execution immediately), they are simply ignored. The last line, `“¡ṾI»` simply indexes into Jelly's dictionary to fetch the word **trick**, which is printed implicitly at the end of the program.
I don't know much about pl, but it appears that the interpreter only fetches one line of code and ignores everything that comes after it. As in Perl, barewords are treated as strings, so `treat` prints exactly that.
[Answer]
## Batch/sh, 30 bytes
```
:;echo Treat;exit
@echo Trick
```
Explanation. Batch sees the first line as a label, which it ignores, and executes the second line, which prints Trick. The @ suppresses Batch's default echoing of the command to stdout. (Labels are never echoed.) Meanwhile sh sees the following:
```
:
echo Treat
exit
@echo Trick
```
The first line does nothing (it's an alias of `true`), the second line prints Treat, and the third line exits the script, so the @echo Trick is never reached.
[Answer]
# sed / Hexagony 32 bytes
```
/$/ctrick
#$@$a</;r;e;/t;....\t;
```
---
# sed
[Try it Online!](http://sed.tryitonline.net/#code=LyQvY3RyaWNrCiMkQCRhPC87cjtlOy90Oy4uLi5cdDs&input=)
The first line prints `trick` if there is an empty string at the end of input. (sed doesn't do anything if there isn't input, but a blank line on stdin is allowed in this case)
**Example run:**
```
$ echo | sed -f TrickOrTreat.sed
trick
```
---
# Hexagony
[Try it Online!](http://hexagony.tryitonline.net/#code=LyQvY3RyaWNrCiMkQCRhPC87cjtlOy90Oy4uLi5cdDs&input=)
The first `/` redirects the instruction pointer up and the the left, so it wraps the the bottom left, skipping the text used for sed. It reuses the r from the sed code and runs a few others to no effect. The expanded hex looks like this:
```
/ $ / c
t r i c k
# $ @ $ a <
/ ; r ; e ; /
t ; . . . .
\ t ; . .
. . . .
```
**Output:**
```
treat
```
[Answer]
# C# / Java
This probably doesn't qualify as it doesn't run on its own, but the challenge has reminded me of a quirk in how C# and Java handle string comparison differently that you can have some fun with for code obfuscation.
The following function is valid in C# and Java, but will return a different value...
```
public static String TrickOrTreat(){
String m = "Oct";
String d = "31";
return m + d == "Oct31" ? "Trick" : "Treat";
}
```
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak) / Brain-Flueue, ~~265 253 219 165 139 115 113~~ 101 bytes
Includes +1 for `-A`
Thanks to Wheat Wizard for going back and forth, golfing a few bytes off each others code, with me.
```
((((()()()))([]((({}{}))({}([((({}()())))]([](({}{}){}){}{})))[]))[])[()()])({}()()){}({})({}[][]){}
```
Brain-Flak: [Try it online!](https://tio.run/nexus/brain-flak#NYoxDoBQCEOvQ4d/CM9BGL6DifHHwZVwdiwYgaY0ryk1qAVEjcHDg7@HaKePwZo27KsS1FpaHcNfppFSaoQemTm2HGt/5nkfa14v)
Brain-Flueue: [Try it online!](https://tio.run/nexus/brain-flak#NYpBCsBACAO/sznsI/oO8dDCFgpLD4U9iW@30VI1xDCJloNcoIkymJvzN29S6WPQogXrsgTRkmRH8ZdppJQooXlE9C36PJ79us@5xhov)
**Explanation:**
The first section lists the values that Brain-Flak sees.
When it switches to Brain-Flueue, I start listing the values as Brain-Flueue sees them.
```
# Brain-Flak
(
(((()()())) # Push 3 twice
([] # Use the height to evaluate to 2
(
(({}{})) # Use both 3s to push 6 twice
({} # Use one of those 6s to evaluate to 6
([((({}()())))] # Use the other 6 to push 8 three times and evaluate to -8
([](({}{}){}){}{}) # Use all three 8s to push 75
) # The -8 makes this push 67
) # The 6 makes this push 73
[]) # Use the height and the 6 to push 82
) # Use the 2 to push 84
# Brain-flueue
[]) # Use the height and 3 to push 84
[()()]) # Push 82
({}()()) # 67 is at the front of the queue, so use that to push 69
{} # Pop one from the queue
({}) # 65 is next on the queue so move to the end
({}[][]) # 74 is next, so use that and the height to push 84
{} # Pop that last value from TRICK
```
[Answer]
## PowerShell / Foo, 14 bytes
```
'trick'#"treat
```
The `'trick'` in PowerShell creates a string and leaves it on the pipeline. The `#` begins a comment, so the program completes and the implicit `Write-Output` prints `trick`.
In Foo, [(Try it Online!)](http://foo.tryitonline.net/#code=J3RyaWNrJyMidHJlYXQ&input=), the `'trick'` is ignored, the `#` causes the program to sleep for `0` seconds (since there's nothing at the array's pointer), then `"treat` starts a string. Since EOF is reached, there's an implicit `"` to close the string, and that's printed to stdout.
] |
[Question]
[
Given a number *N*, draw a left aligned *N*x*N* board of numbers, leaving 1 blank (as a space) (I will show diagrams with *N*=5)
```
2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
```
Your job is to construct the Sieve of Eratosthenes, step by step. First, start with 2. It's prime, so leave it there, and replace all other numbers divisible by 2 with the proper number of spaces.
```
2 3 5
7 9
11 13 15
17 19
21 23 25
```
Next, go to the next unprinted number (`3` in this case) and do the same.
```
2 3 5
7
11 13
17 19
23 25
```
And so on, until you reach *N*.
You need to first print the complete grid, and every time you go to a new number, print the board with the multiples removed. Make sure you print a blank line in between!
## Examples
Text in parenthesis `()` are just for reference, you don't need to print it
*N* = 2:
```
2 (complete grid)
3 4
2 (remove multiples of 2)
3
```
*N* = 3:
```
2 3 (complete grid)
4 5 6
7 8 9
2 3 (remove multiples of 2)
5
7 9
2 3 (remove multiples of 3)
5
7
```
Remember, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the code with the smallest number of bytes wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 34 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ṿ€“1“ ”ys³G
>®i©1ḍoṛ®¦
²R;1©ÇÐĿÑ€Y
```
[Try it online!](http://jelly.tryitonline.net/#code=4bm-4oKs4oCcMeKAnCDigJ15c8KzRwo-wq5pwqkx4biNb-G5m8KuwqYKwrJSOzHCqcOHw5DEv8OR4oKsWQ&input=&args=NQ)
### How it works
```
²R;1©ÇÐĿÑ€Y Main link. Argument: n (integer)
² Yield n².
R Range; yield [1, ..., n²].
1© Yield 1 and copy it to the register.
; Append 1 to the range.
This is the initial state. Let's call it S.
ÇÐĿ Call the second helper link until the results are no longer unique.
This returns all unique results as an array.
Ṅ€ Call the first helper link on each result.
Y Join, separating by linefeeds.
>®i©1ḍoṛ®¦ Second helper link. Argument: S (state)
>® Compare all integers in S with the value in the register.
i 1 Find the first index of 1 (i.e., the first number that is greater
than the register.
© Copy the index to the register. Let's call the index p.
ḍ Test all numbers in S for divisibility by p. This yield 1 for
multiples of p, 0 otherwise.
o Logical OR; replace 0's with the corresponding values of S.
ṛ®¦ Replace the 0 at index p with the corresponding element of S (p).
For the purposes of the explanation, S is now the updated state.
Ṿ€“1“ ”ys³G First helper link. Argument: A (array)
Ṿ€ Uneval each; convert all integers in A into strings.
“1“ ”y Replace each string "1" with the string " ".
s³ Split into chunks of length n (command-line argument).
G Grid; separate row items by spaces (left-padding since the row items
are strings), the rows themselves by linefeeds.
```
[Answer]
# Perl, ~~250~~ ~~243~~ ~~231~~ ~~202~~ 157 bytes
```
$n=<>;@a=0..($e=$n*$n);$a[1]=$";for$p(1..$n){next if!$a[$p];for(1..$e){$a[$_]=""if!($p~~[(1,$_)]||$_%$p);printf"%-*s",1+length$e,$a[$_];say""if!($_%$n)}say}
```
[Test the current golf online!](https://goo.gl/2pXEWQ) (be sure to run as `perl -M5.010 main.pl`)
The two literal newlines each save 1 byte in place of \n.
Sample output (input of 7):
```
2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35
36 37 38 39 40 41 42
43 44 45 46 47 48 49
2 3 5 7
9 11 13
15 17 19 21
23 25 27
29 31 33 35
37 39 41
43 45 47 49
2 3 5 7
11 13
17 19
23 25
29 31 35
37 41
43 47 49
2 3 5 7
11 13
17 19
23
29 31
37 41
43 47 49
2 3 5 7
11 13
17 19
23
29 31
37 41
43 47
```
I'm positive I didn't golf it very well, so when I get home I'll take another look at it to see just how much I can shave off.
Edit 1: -7 bytes (changing "print sprintf" to the obvious "printf")
Edit 2: Saved 12 bytes by using $d explicitly in the one place it was called instead of creating a separate variable, by combining some declarations, and by eliminating one of my conditions for the `next` statement inside the first `foreach` loop by adding a space somewhere else.
An additional 29 bytes were golfed out by reworking two for loops into a single loop, eliminating two variable declarations, and turning `unless` statements into if-not statements. Declaring `my$e=$n*$n;` then replacing the three instances of $n\*$n with $e (allowing me to drop a paren for one of them) turned out to yield ±0 bytes, but I kept it in anyway.
Edit 3: Thanks to @Dada, another 40 bytes were golfed out (variable declarations, 'foreach' becoming 'for', implicit $\_ in several locations, and cutting down on the printf statement size). An additional 1 byte was shaved off by turning `if!($c%$p||$c==$p||$p==1)` into `if!($p~~[(1,$_)]||$_%$p)`. Unfortunately, the [] around the array is necessary, because the smartmatch operator ~~ is still experimental and doesn't seem to work properly on actual arrays, but does work on references to them instead. 4 more bytes were removed by removing two semicolons and an empty set of quotation marks after the last `say`.
[Answer]
# PHP, 155 Bytes
```
for(;$d++<$n=$argv[1];$x&$a[$d]<1?:print"\n".chunk_split(join($a),$n*$l))for($i=$d*$x=$d>1;$n**2>=$i+=$d;)$a[$i]=str_pad($x|$i<2?"":$i,$l=strlen($n**2)+1);
```
@Crypto -3 Bytes Thank You
@Titus -6 Bytes Thank You
[Try it](http://sandbox.onlinephpfunctions.com/code/4e0784d5a9a5633acbb7f18580e048d49554af0e)
First time that I use print in a after loop condition
Breakdown
```
for(;$d++<$n=$argv[1];
$x&$a[$d]<1?:print"\n".chunk_split(join($a),$n*$l))
#after loop print the grid if $d = 1 or is prime
for($i=$d*$x=$d>1;$n**2>=$i+=$d;)
$a[$i]=str_pad($x|$i<2?"":$i,$l=strlen($n**2)+1);
#fills the array at first run and replace positions with space in the next runs
```
Previous Version 174 Bytes
```
for(;$d++<=$n=$argv[1];!($d<2||$a[$d]>0)?:print chunk_split(join($a),$n*$l)."\n")for($i=$d<2?1:2*$d;$i<=$m=$n**2;$i+=$d)$a[$i]=str_pad($d<2?($i<2?"":$i):" ",$l=strlen($m)+1);
```
[Answer]
# R, ~~195~~ ~~191~~ ~~185~~ 204 bytes
```
f=function(N){a=b=1:N^2;i=1;a[1]="";S=sprintf;while(i<=N){for(j in b)cat(a[j]<-S(S("%%-%is",nchar(N^2)),if(j==i|j%%i|i<2)a[j]else ""),if(j%%N)"" else"\n");cat("\n");i=(grep("\\d",a[-(1:i)],v=T)[1]:1)[1]}}
```
Thanks to @Billywob for 6 extra bytes saved!
Indented, with newlines:
```
f=function(N){
a=b=1:N^2 #Initial array
i=1 #Turn counter
a[1]="" #1 never shown
S=sprintf
while(i<=N){
for(j in b)
cat(a[j]<-S(S("%%-%is",nchar(N^2)),if(j==i|j%%i|i<2)a[j]else ""),
if(j%%N)"" else"\n") #Newline at end of row
cat("\n") #Newline between turns
i=(grep("\\d",a[-(1:i)],v=T)[1]:1)[1] #Select next prime as next i
}
}
```
Usage:
```
> f(2)
2
3 4
2
3
> f(3)
2 3
4 5 6
7 8 9
2 3
5
7 9
2 3
5
7
> f(9)
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
2 3 5 7 9
11 13 15 17
19 21 23 25 27
29 31 33 35
37 39 41 43 45
47 49 51 53
55 57 59 61 63
65 67 69 71
73 75 77 79 81
2 3 5 7
11 13 17
19 23 25
29 31 35
37 41 43
47 49 53
55 59 61
65 67 71
73 77 79
2 3 5 7
11 13 17
19 23
29 31
37 41 43
47 49 53
59 61
67 71
73 77 79
2 3 5 7
11 13 17
19 23
29 31
37 41 43
47 53
59 61
67 71
73 79
> f(12)
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
2 3 5 7 9 11
13 15 17 19 21 23
25 27 29 31 33 35
37 39 41 43 45 47
49 51 53 55 57 59
61 63 65 67 69 71
73 75 77 79 81 83
85 87 89 91 93 95
97 99 101 103 105 107
109 111 113 115 117 119
121 123 125 127 129 131
133 135 137 139 141 143
2 3 5 7 11
13 17 19 23
25 29 31 35
37 41 43 47
49 53 55 59
61 65 67 71
73 77 79 83
85 89 91 95
97 101 103 107
109 113 115 119
121 125 127 131
133 137 139 143
2 3 5 7 11
13 17 19 23
29 31
37 41 43 47
49 53 59
61 67 71
73 77 79 83
89 91
97 101 103 107
109 113 119
121 127 131
133 137 139 143
2 3 5 7 11
13 17 19 23
29 31
37 41 43 47
53 59
61 67 71
73 79 83
89
97 101 103 107
109 113
121 127 131
137 139 143
2 3 5 7 11
13 17 19 23
29 31
37 41 43 47
53 59
61 67 71
73 79 83
89
97 101 103 107
109 113
127 131
137 139
```
[Answer]
# Python 2, ~~199 202~~ 201 bytes
+3 bytes (I wasn't stopping early)
-1 byte thanks to @Oliver (missed a space)
```
def f(n,p={()}):
m=n*n;g=['']+[[i,''][any(i>n and i%n<1for n in p)]for i in range(2,m+1)];x=min(set(g)-p);i=0
while i<m+n:print' '.join('%%%ds'%-len(`m`)%v for v in g[i:i+n]);i+=n
if x<=n:f(n,p|{x})
```
**[repl.it](https://repl.it/EBNG/4)**
[Answer]
# Groovy, ~~201~~ ~~195~~ 191 Bytes
```
{n->a=(1..n*n).toArray();y={a.collect{(it?"$it":"").padRight((""+n*n).size())}.collate(n).each{println it.join(" ")}};a[0]=0;y(a);(2..n).each{b->(b+1..n*n).each{if(it%b==0){a[it-1]=0}};y(a)}}
```
This is an absolute cluster... The left-align murdered my byte count. But hey, it works. Here's the output for 4:
```
2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
2 3
5 7
9 11
13 15
2 3
5 7
11
13
2 3
5 7
11
13
```
# Ungolfed:
```
{
n->
a = (1..n*n).toArray(); // Create initial array.
y = { // Createa printing utility closure.
a.collect { // Create an array collection of...
(it ? "$it":"").padRight((""+n*n).size()) // If 0, store "", else store number & right pad it.
}.collate(n).each{ // Collate by n (break into nxn grid).
println it.join(" ") // print each separated by spaces.
}
};
a[0]=0; // Remove first element.
y(a); // Print initial status.
(2..n).each{ // From 2 to n...
b->
(b+1..n*n).each{ // From current number + 1 to end of grid...
if(it%b==0){ // If current grid position is divisible...
a[it-1]=0 // Replace with 0.
}
}
y(a) // Print it.
}
}
```
[Answer]
# Perl, ~~115~~ ~~114~~ ~~113~~ 112 bytes
Includes +1 for `-a`
Run with input number on STDIN:
```
perl -M5.010 sieving.pl <<< 7
```
`sieving.pl`:
```
#!/usr/bin/perl -a
$_*=$_;$a.="$_"x$|++|$"x"@+".($_%"@F"?$":$/)for/\d+/..$_;*_=a;s^^$$_++||say;$.++;s//$&%$.|$&==$.?$&:$&&$_/eg^eg
```
Needs a recent enough perl so that `-a` implies `-n`. If your perl is too old add a `-n` option.
Prints a trailing newline which is allowed.
[Answer]
## JavaScript (ES6), ~~190~~ 189 bytes
Directly prints to the console.
```
f=(w,k=1,a=[...Array(w*w)].map((_,n)=>n&&n+1))=>k++<=w&&(k==2|a[k-2]&&console.log(a.map((n,x)=>`${n||''} `.slice(0,`_${w*w}`.length)+(++x%w?'':`
`)).join``),f(w,k,a.map(n=>n==k|n%k&&n)))
```
### Demo
```
f=(w,k=1,a=[...Array(w*w)].map((_,n)=>n&&n+1))=>k++<=w&&(k==2|a[k-2]&&console.log(a.map((n,x)=>`${n||''} `.slice(0,`_${w*w}`.length)+(++x%w?'':`
`)).join``),f(w,k,a.map(n=>n==k|n%k&&n)))
f(5)
```
[Answer]
## Batch, 464 bytes
```
@echo off
set/an=%1,s=n*n,t=s,c=1
set p=
:l
set/ac+=1,t/=10
set p= %p%
if %t% gtr 0 goto l
for /l %%i in (1,1,%1)do call:i %%i
exit/b
:i
set l=
set/af=0
call:f %1 %1
if %f%==0 for /l %%j in (1,1,%s%)do call:j %1 %%j
exit/b
:j
set/am=%2,f=!(m-1),g=%2%%n
call:f %1 %2
if %f% gtr 0 set m=
set m=%m% %p%
call set l=%%l%%%%m:~0,%c%%%
if %g%==0 echo(%l%&set l=
if %2==%s% echo(
exit/b
:f
for /l %%l in (2,1,%1)do if %%l neq %2 set/af+=!(%2%%%%l)
```
This was somewhat laborious. Explanation: Starts by squaring `n` so that it can calculate the desired column width `c`, and the appropriate amount of padding `p`, using the loop `:l`. The outer loop from `1` to `n` then runs once for each grid, calling the subroutine `:i`. First the value is checked to see whether it is 1 or prime; if not then that grid is skipped. The inner loop from `1` to `n*n` then handles the rows and columns of the grid, calling the subroutine `:j`. Each value is checked to see whether it is one of the prime numbers found so far, or if none of the prime numbers found so far divide it. If so then the value is concatenated to the output buffer, which is then padded to the desired column width. The buffer is printed and cleared every `n` lines, and an extra blank line is added at the end of the grid. The `:f` label denotes the factor-checking subroutine; f(x,y) adds 1 to `f` for each integer between 2 and `x` that divides `y`, excluding `y` itself.
[Answer]
# J, 125 bytes
```
p=:3 :'}."1,./('' '',.>)"1|:(-%:#y)]\((a:"_)`(<@":)@.*)"+y'
3 :'p@>~.|.(]*](*@|~+.=)({[:I.*){])&.>/\.(<"+i.-y),<]`>:@.*i.*:y'
```
This is explicit, not tacit J, but there should be a way to golf it tacitly.
## Usage
```
p =: 3 :'}."1,./('' '',.>)"1|:(-%:#y)]\((a:"_)`(<@":)@.*)"+y'
f =: 3 :'p@>~.|.(]*](*@|~+.=)({[:I.*){])&.>/\.(<"+i.-y),<]`>:@.*i.*:y'
f 2
2
3 4
2
3
f 3
2 3
4 5 6
7 8 9
2 3
5
7 9
2 3
5
7
f 4
2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
2 3
5 7
9 11
13 15
2 3
5 7
11
13
f 5
2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
2 3 5
7 9
11 13 15
17 19
21 23 25
2 3 5
7
11 13
17 19
23 25
2 3 5
7
11 13
17 19
23
```
[Answer]
# Mathematica, 133 bytes
```
Grid[#,Alignment->Left]~Print~"
"&/@FoldList[#/.(##|1&@@(2~r~i#2)->Null)&,(r=Range)[i=#^2]~Partition~#/.Rule[1,],Prime@r@PrimePi@#];&
```
[Answer]
# PHP, ~~155~~ ~~150~~ ~~147~~ ~~145~~ ~~142~~ 140 bytes
```
for(;$k++<$n=$argv[1];)if($k<2||$a[$k]){for($i=0;$i++<$n*$n;)echo$a[$i]=$k>1?$i>$k&$i%$k<1?"":$a[$i]:($i<2?"":$i),"\t\n"[$i%$n<1];echo"\n";}
```
**breakdown**
```
for(;$k++<$n=$argv[1];)
if($k<2||$a[$k]) // if first iteration or number unprinted ...
{
for($i=0;$i++<$n*$n;)
echo
$a[$i]=$k>1
?$i>$k&$i%$k<1
?"" // sieve
:$a[$i] // or copy value
:($i<2?"":$i) // first iteration: init grid
,
// append tab, linebreak every $n columns
"\t\n"[$i%$n<1]
;
// blank line after each iteration
echo"\n";
}
```
] |
[Question]
[
# Introduction
A bell tower will ring its bells every hour, `n` times, with `n` being the the current hour on a 12 hour clock.
For example, a bell will ring 5 times at 5pm, and 10 times at 10am.
# Task
Given two times in a suitable format, output the number of times the bell will ring, inclusive of the start and end times
# Examples
```
"10am-12pm"
10+11+12= 33
[01:00, 05:00]
1+2+3+4+5 = 15
[11, 15]
11+12+1+2+3 = 29
[10:00pm, 10:00am]
10+11+12+1+2+3+4+5+6+7+8+9+10 = 88
```
If the start is the same as the end then the you simply just ouput the number of chimes for that hour:
```
[5pm, 5pm]
5 = 5
```
As you can see, you may choose an input method but the output must be an integer on its own (or an acceptable alternative) trailing/ leading newlines and spaces are allowed.
Note:
* inputs may span from the afternoon of one day to the morning of the next.
* the difference between the two times will never be more than 24 hours.
* input is flexible so long as you clearly state what format your input is.
* your input must have a **clear** distinction between AM and PM.
[Answer]
# JavaScript (ES6), ~~38~~ 35 bytes
```
f=(x,y)=>~-x%12-~(x-y&&f(x%24+1,y))
```
Recursively adds the current number of bell rings to the total. Called like `f(11,15)`; midnight is represented as `24`. I got part of the `~-` trick from [@xnor's Python answer](https://codegolf.stackexchange.com/a/95261/42545).
## Test snippet
```
f=(x,y)=>~-x%12-~(x-y&&f(x%24+1,y))
g=(x,y)=>console.log("x:",x,"y:",y,"result:",f(x,y))
g(10,12)
g(1,5)
g(11,15)
g(22,10)
```
```
<input id=A type="number" min=1 max=24 value=9>
<input id=B type="number" min=1 max=24 value=17>
<button onclick="g(A.value,B.value)">Run</button>
```
### Non-recursive version (Firefox 30+), 56 bytes
```
(x,y,t=0)=>[for(_ of Array((y-x+25)%24))t+=x++%12||12]|t
```
Equivalent to the following ES6 function:
```
(x,y,t=0)=>[...Array((y-x+25)%24))].map(_=>t+=x++%12||12)|t
```
[Answer]
# Python 2, 46 bytes
```
f=lambda x,y:(x%12or 12)+(x-y and f(-~x%24,y))
```
Based on my JS answer. The recursive formula **f** for the solution is defined as so:
1. Start with two integers **x** and **y**.
2. Take **x mod 12**; if this is 0, take **12** instead.
3. If **x != y**, add the result of **f(x+1 mod 24, y)**.
[Answer]
# Python 2, ~~59~~ 54 bytes
```
a=lambda x,y:sum(1+i%12for i in range(x-1,y+24*(x>y)))
```
Equivalent to
```
summ=0
if start > end:
end+=24
for hour in range(start-1,end):
summ +=1+hour%12
print summ
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 13 bytes
With a lot of help from *Emigna*.
```
-24%ݹ+<12%>O
```
Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=LTI0JcOdwrkrPDEyJT5P&input=MjMKMQ)
[Answer]
## Python, 42 bytes
```
f=lambda a,b:~-a%12-~(b-a and f(-~a%24,b))
```
A recursive function that takes two numbers from 0 to 23. Expanding the `~x`'s to `-x-1` gives
```
f=lambda a,b:(a-1)%12+1+(b-a and f((a+1)%24,b))
```
The expression `(a+1)%12+1` converts a time to the number of rings `1` to `12`. Then, the lower bound is incremented modulo 24 and the function for the recursive result is added. That is, unless the current hour is the end hour, in which case we stop.
I've been trying to write a purely arithmetical solution instead, but so far I've only found long and messy expressions.
[Answer]
## Haskell, 48 43 bytes
```
s%e=sum[mod x 12+1|x<-[s-1..e+23],x<e||s>e]
```
Usage is `startHour % endHour`, with both inputs given in 24-hr format.
*edit: added @xnor's improvement, saving 5 bytes*
[Answer]
# C#, 73 bytes
```
a=>b=>{int x=0;for(;;){x+=(a%=24)>12?a-12:a<1?12:a;if(a++==b)return x;}};
```
Acceptable input: integers in range [0,23].
**This solution does not use LINQ.**
---
Full program with test cases:
```
using System;
namespace HowManyTimesABellTowerRings
{
class Program
{
static void Main(string[] args)
{
Func<int,Func<int,int>>f= a=>b=>{int x=0;for(;;){x+=(a%=24)>12?a-12:a<1?12:a;if(a++==b)return x;}};
Console.WriteLine(f(10)(12)); //33
Console.WriteLine(f(1)(5)); //15
Console.WriteLine(f(11)(15)); //29
Console.WriteLine(f(22)(10)); //88
Console.WriteLine(f(10)(10)); //10
Console.WriteLine(f(11)(10)); //156
Console.WriteLine(f(0)(23)); //156
Console.WriteLine(f(22)(1)); //34
}
}
}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~17 16 15~~ 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
>×24+⁹⁸r’%12‘S
```
**[TryItOnline](http://jelly.tryitonline.net/#code=PsOXMjQr4oG54oG4cuKAmSUxMuKAmFM&input=&args=MjM+MQ)**
How?
```
>×24+⁹⁸r’%12‘S - Main link: a, b (24 hr integers, midnight may be 0 or 24)
> - a>b? (1 if true, 0 if false)
×24 - times 24 (24 if a>b, else 0)
+⁹ - add to b (b+24 if a>b, else b)
⁸ - a
r - range(a, b+24 or b) ([a,a+1,...,b+24 or b])
’ - decrement (vectorises) ([a-1,a,...,b+23 or b-1])
%12 - mod 12 (vectorises) (number of tolls at each occurrence - 1)
‘ - increment (vectorises) (number of tolls at each occurrence)
S - sum
```
[Answer]
# [MATL](http://github.com/lmendo/MATL), 14 bytes
```
yy>24*+&:12X\s
```
Input format is as in the third example in the challenge, that is, two numbers in 24-hour format.
[Try it online!](http://matl.tryitonline.net/#code=eXk-MjQqKyY6MTJYXHM&input=MjIKMTA)
### Explanation
Take inputs `22`, `10` as an example.
```
yy % Take two inputs implicitly. Duplicate both
% STACK: 22, 10, 22, 10
> % Is the first greater than the second?
% STACK: 22, 10, 1
24* % Multiply by 24
% STACK: 22, 10, 24
+ % Add
% STACK: 22, 34
&: % Binary range
% STACK: [22 23 24 25 26 27 28 29 30 31 32 33 34]
12X\ % Modulo 12, 1-based
% STACK: [10 11 12 1 2 3 4 5 6 7 8 9 10]
s % Sum of array
% STACK: 88
% Implicitly display
```
[Answer]
# PHP, 90 Bytes
Input format '[1,24]' between 1 and 24
In this challenge that I am hate why PHP loose against other languages. I prefer to show all my ideas. Maybe an other PHP Crack finds a shorter solution.
```
<?list($f,$g)=$_GET[b];for($i=$f;$i-1!=$g|$f>$g&!$c;$s+=$i++%12?:12)$i<25?:$c=$i=1;echo$s;
```
99 Bytes
```
<?for($i=($b=$_GET[b])[0],$c=($d=$b[1]-$b[0])<0?25+$d:$d+1;$c--;$s+=$i++%12?:12)$i<25?:$i=1;echo$s;
```
113 Bytes a way with min and max
```
<?for($i=min($b=$_GET[b]);$i<=$m=max($b);)$s+=$i++%12?:12;echo($b[0]>$b[1])?156-$s+($m%12?:12)+($b[1]%12?:12):$s;
```
okay this crazy idea works with an array 149 Bytes
fills the array `$y[0]` and `$y[1]` if `$_GET["b"][0]<=$_GET["b"][1]`
if `$y[1]` is `null` we can sum this array `array_diff_key($y[0],array_slice($y[0],$b[1],$b[0]-$b[1]-1,1))`
```
<?for(;++$i<25;)$y[$i>=($b=$_GET[b])[0]&$i<=$b[1]][$i]=$i%12?:12;echo array_sum($y[1]??array_diff_key($y[0],array_slice($y[0],$b[1],$b[0]-$b[1]-1,1)));
```
This could be golfed down 124 Bytes
```
<?for(;++$i<25;)$x[($v=($b=$_GET[b])[0]>$b[1])?$i<$b[0]&$i>$b[1]:$i>=$b[0]&$i<=$b[1]][$i]=$i%12?:12;echo array_sum($x[!$v]);
```
Now at this point we can reduce the array with only two ints 101 Bytes
Make 2 sums `$x[0]` and `$x[1]`
`list($f,$g)=$_GET[b];`
if `$v=($f>$g`
then add value to `$x[$i<$f&$i>$g]`
else add value to `$x[$i>=$f&$i<=$g]`
the output will be find by case `echo$x[!$v];`
```
<?list($f,$g)=$_GET[b];for(;++$i<25;)$x[($v=$f>$g)?$i<$f&$i>$g:$i>=$f&$i<=$g]+=$i%12?:12;echo$x[!$v];
```
After that i found a way to calculate the result directly 112 Bytes
```
<?list($x,$y)=$_GET[t];echo(($b=$x>$y)+(($x-($s=$x%12?:12)^$y-($t=$y%12?:12))xor$b))*78-($s*($s-1)-$t*($t+1))/2;
```
recursive 103 Bytes
```
<?list($x,$y)=$_GET[t];function f($x,$y){return($x%12?:12)+($x-$y?f(++$x<25?$x:1,$y):0);}echo f($x,$y);
```
[Answer]
# PHP, 69 bytes
```
list(,$i,$a)=$argv;for($a+=$i>$a?24:0;$i<=$a;)$n+=$i++%12?:12;echo$n;
```
The list extraction was inspired by Jörg Hülsermann's answer but the rest of the similarities are a result of convergent evolution and because it's quite a lot shorter and the conditionals in the loop are different enough I'm posting it as a separate answer.
Takes input as 24 hour times (fine with either 0 or 24). Run like:
```
php -r "list(,$i,$a)=$argv;for($a+=$i>$a?24:0;$i<=$a;)$n+=$i++%12?:12;echo$n;" 9 18
```
[Answer]
# Java, ~~72~~ ~~71~~ ~~78~~ 76 bytes
```
Usage:
pm: true if first time is past 11am
time: first time%12
pm2: true if second time is past 11am
time2: second time%12
```
**Edit**:
* ***-1** byte off. Thanks to @1Darco1*
* *Fixed function head. **+7** bytes on.*
* ***-2** bytes off. Thanks to @Kevin Cruijssen*
* ***+2** bytes on. Now `e`/`clock` is initialized.*
---
```
(a,b,c,d)->{int e=0;b+=a?12:0;d+=c?12:0;for(;b!=d;e+=b%12,b=++b%24);return e;}
```
Ungolfed:
```
public static int clock(boolean pm, int time, boolean pm2, int time2){
int clock=0;
time+=pm?12:0;
time2+=pm2?12:0;
while(time!=time2){
clock+=time%12;
time=++time%24;
}
return clock;
}
```
[Answer]
## [QBIC](https://codegolf.stackexchange.com/questions/44680/showcase-your-language-one-vote-at-a-time/86385#86385), ~~90~~ 47 bytes
So, here's the answer printing only the total number of bell-rings:
```
::{c=a~c>12|c=c-12]d=d+c~a=b|_Xd]a=a+1~a>24|a=1
```
Input is in range `1-24`; `a` and `b` are the inputs (`::` in the code), `c` keeps track of am/pm, `d` is the total number of rings. When we've counted down all the hours, `_Xd` terminates the program, printing `d` in the process.
---
OK, I misunderstood the question and thought the `1+2+3...=` text was part of the output, so I wrote that:
```
::{c=a~c>12|c=c-12]X=!c$Z=Z+X+@+| d=d+c~a=b|?left$$|(Z,len(Z)-1)+@ =|+!d$_X]a=a+1~a>24|a=1
```
Now, I'll go code the proper answer...
[Answer]
# Pyth - 11 bytes
```
s|R12%R12}F
```
[Test Suite](http://pyth.herokuapp.com/?code=s%7CR12%25R12%7DF&test_suite=1&test_suite_input=10%2C+12%0A1%2C+5%0A11%2C+15%0A10%2C+22%0A5%2C+5&debug=0).
[Answer]
## C#, 76 bytes
```
(a,b)=>Enumerable.Range(a,Math.Abs(b-a)+1).Select(n=>n%12==0?12:n%12).Sum();
```
[Answer]
# Perl, 36 bytes
Includes +1 for `-p`
Give start and end time in 24-hour format on a line each on STDIN:
```
toll.pl
11
15
^D
```
`toll.pl`:
```
#!/usr/bin/perl -p
$\+=$_%12||12for$_..$_+(<>-$_)%24}{
```
[Answer]
# Java 7, 64 bytes
```
int c(int x,int y){return(x%12<1?12:x%12)+(x!=y?c(-~x%24,y):0);}
```
Recursive method based on [*@ETHproductions*'s Python 2 answer](https://codegolf.stackexchange.com/a/95259/52210). Uses a 24-hour clock input.
**Ungolfed & test code:**
[Try it here.](https://ideone.com/EAoqZi)
```
class M{
static int c(int x, int y){
return (x%12 < 1
? 12
: x%12)
+ (x != y
? c(-~x % 24, y)
: 0);
}
public static void main(String[] a){
System.out.println(c(10, 12));
System.out.println(c(1, 5));
System.out.println(c(11, 15));
System.out.println(c(10, 22));
System.out.println(c(5, 5));
}
}
```
**Output:**
```
33
15
29
88
5
```
[Answer]
## Batch, ~~168~~ 91 bytes
```
@cmd/cset/ax=(%1+23)%%24,y=x+(%2+24-%1)%%24,z=y%%12+1,(y/12-x/12)*78+z*-~z/2-(x%%=12)*-~x/2
```
Edit: Saved 77 byte by switching to a closed form for the answer.
* `%1` and `%2` are the two command-line parameters
* `@` Disable Batch's default which is to echo the command
* `cmd/c` Fool Batch into immediately printing the result of the calculation
* `set/a` Perform a numeric calculation
* `x=(%1+23)%%24,` Normalise the starting hour to be the number of hours since 1AM (1PM would also work, but 11 is no shorter than 23)
* `y=x+(%2+24-%1)%%24,` Normalise the ending hour to be ahead of the starting hour, advancing to the next day if necessary
* `z=y%%12+1,` Number of bells struck at the ending hour
* `(y/12-x/12)*78+` Number of bells due to extra half days
* `z*~-z/2-` Number of bells from 1 o'clock to the ending hour inclusive
* `(x%%=12)` One less than the number of bells struck at the starting hour
* `*-~x/2` Number of bells that would have been struck from 1 o'clock to the starting hour, but not including the starting hour
[Answer]
### C, 56 Bytes
```
f(a,b,c=0){while(b-->a){c+=b>12?b-12:b;}printf("%d",c);}
```
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 48 + 2 = 50 bytes
```
<v$&%$-&:$+}:*2c
{>:?!v1-}:1+
v?=1l<++1%c+b$
>n;
```
Input is expected to be present on the stack at program start, so +2 bytes for the `-v` flag. Input is two integers specifying the hour on the 24 hour clock, so `10am - 10pm` would be given as `10 22`.
[Try it online!](http://fish.tryitonline.net/#code=PHYkJiUkLSY6JCt9OioyYwp7Pjo_IXYxLX06MSsKdj89MWw8KysxJWMrYiQKPm47&input=&args=LXYgMTA+LXYgMjI)
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix), ~~45~~ 44 bytes
*Saved 1 byte, thanks to @ETHproductions*
My first foray into Cubix...
```
)$424tU4OI0Iuq;;-!^;^%&21u+rr;ss!;sqU>&%r$@;
```
Or, cubified:
```
) $ 4
2 4 t
U 4 O
I 0 I u q ; ; - ! ^ ; ^
% & 2 1 u + r r ; s s !
; s q U > & % r $ @ ; .
. . .
. . .
. . .
```
You can try it out at the [online interpreter](https://ethproductions.github.io/cubix/). Input is in 24 hour format, with the end time first. For example, from 5pm to 1am the input should be `1 17`.
---
Previous version, 45 bytes:
```
)$442t\/OI0Iuq;;-!^;^%&21u+rr;ss!;sqU>&%r$@.;
```
[Answer]
# Qbasic, 112 bytes
```
input "",a
input "",b
do
if a=25 then a=1
if a<=12 then
c=c+a
else
c=c+a-12
endif
a=a+1
loop until a=b+1
print c
```
[Answer]
# Python, 73 bytes
It would be so much shorter if we didn't have to support `pm` to `am`. I use recursion to support it.
```
f=lambda a,b:sum([~-i%12+1for i in range(a,b+1)]*(a<b)or[f(a,24),f(1,b)])
```
[**Try it online**](https://repl.it/DnDQ/1)
Without supporting `pm` to `am` (45 bytes):
```
lambda a,b:sum(~-i%12+1for i in range(a,b+1))
```
] |
[Question]
[
Given a nonempty list of positive decimal integers, output the largest number from the set of numbers with the fewest digits.
The input list will not be in any particular order and may contain repeated values.
**Examples:**
```
[1] -> 1
[9] -> 9
[1729] -> 1729
[1, 1] -> 1
[34, 3] -> 3
[38, 39] -> 39
[409, 12, 13] -> 13
[11, 11, 11, 1] -> 1
[11, 11, 11, 11] -> 11
[78, 99, 620, 1] -> 1
[78, 99, 620, 10] -> 99
[78, 99, 620, 100] -> 99
[1, 5, 9, 12, 63, 102] -> 9
[3451, 29820, 2983, 1223, 1337] -> 3451
[738, 2383, 281, 938, 212, 1010] -> 938
```
**The shortest code in bytes wins.**
[Answer]
# Pyth, ~~7~~ ~~3~~ 6 bytes
```
eS.ml`
```
[Test Suite](http://pyth.herokuapp.com/?code=eS.ml%60&test_suite=1&test_suite_input=%5B1%5D%0A%5B9%5D%0A%5B1729%5D%0A%5B1%2C+1%5D%0A%5B34%2C+3%5D%0A%5B38%2C+39%5D%0A%5B409%2C+12%2C+13%5D%0A%5B11%2C+11%2C+11%2C+1%5D%0A%5B11%2C+11%2C+11%2C+11%5D%0A%5B78%2C+99%2C+620%2C+1%5D%0A%5B78%2C+99%2C+620%2C+10%5D%0A%5B78%2C+99%2C+620%2C+100%5D%0A%5B1%2C+5%2C+9%2C+12%2C+63%2C+102%5D%0A%5B3451%2C+29820%2C+2983%2C+1223%2C+1337%5D%0A%5B738%2C+2383%2C+281%2C+938%2C+212%2C+1010%5D&debug=0)
Explanation:
```
e Still grab the last element
S Still sort
.ml` But prefilter the list for those with the (m)inimum length.
```
---
7 byte solution:
```
eSh.gl`
```
[Test Suite](http://pyth.herokuapp.com/?code=eSh.gl%60&test_suite=1&test_suite_input=%5B1%5D%0A%5B9%5D%0A%5B1729%5D%0A%5B1%2C+1%5D%0A%5B34%2C+3%5D%0A%5B38%2C+39%5D%0A%5B409%2C+12%2C+13%5D%0A%5B11%2C+11%2C+11%2C+1%5D%0A%5B11%2C+11%2C+11%2C+11%5D%0A%5B78%2C+99%2C+620%2C+1%5D%0A%5B78%2C+99%2C+620%2C+10%5D%0A%5B78%2C+99%2C+620%2C+100%5D%0A%5B1%2C+5%2C+9%2C+12%2C+63%2C+102%5D%0A%5B3451%2C+29820%2C+2983%2C+1223%2C+1337%5D%0A%5B738%2C+2383%2C+281%2C+938%2C+212%2C+1010%5D&debug=0)
Explanation:
```
.g Group items in (implicit) input by:
l The length of
` their representation
h Get those with the shortest length
S Sort the resulting list
e and grab the last (i.e. largest) element
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
DL,NµÞḢ
```
Test it at **[TryItOnline](http://jelly.tryitonline.net/#code=REwsTsK1w57huKI&input=&args=WzczOCwgMjM4MywgMjgxLCA5MzgsIDIxMiwgMTAxMF0)**
Or see all test cases also at **[TryItOnline](http://jelly.tryitonline.net/#code=REwsTsK1w57huKIKxbzDh-KCrOG5hOKCrMK1&input=&args=W1sxXSwgWzldLCBbMTcyOV0sIFsxLCAxXSwgWzM0LCAzXSwgWzM4LCAzOV0sIFs0MDksIDEyLCAxM10sIFsxMSwgMTEsIDExLCAxXSwgWzExLCAxMSwgMTEsIDExXSwgWzc4LCA5OSwgNjIwLCAxXSwgWzc4LCA5OSwgNjIwLCAxMF0sIFs3OCwgOTksIDYyMCwgMTAwXSwgWzEsIDUsIDksIDEyLCA2MywgMTAyXSwgWzM0NTEsIDI5ODIwLCAyOTgzLCAxMjIzLCAxMzM3XSwgWzczOCwgMjM4MywgMjgxLCA5MzgsIDIxMiwgMTAxMF1d)**
How?
```
DL,NµÞḢ - Main link takes one argument, the list, e.g. [738, 2383, 281, 938, 212, 1010]
D - convert to decimal, e.g. [[7,3,8],[2,3,8,3],[2,8,1],[9,3,8],[2,1,2],[1,0,1,0]]
L - length, e.g. [3,4,3,3,3,4]
N - negate, e.g [-738, -2383, -281, -938, -212, -1010]
, - pair, e.g. [[3,-738],[4,-2383],[3,-281],[3,-938],[3,-212],[4,-1010]]
µ - make a monadic chain
Þ - sort the input by that monadic function, e.g [938,738,281,212,2383,1010]
(the lists in the example are not created, but we sort over the values shown)
Ḣ - pop and return the first element, e.g. 938
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 5 bytes
Code:
```
({é¬(
```
Explanation:
```
( # Negate the list, e.g. [22, 33, 4] -> [-22, -33, -4]
{ # Sort, e.g. [-22, -33, -4] -> [-33, -22, -4]
é # Sort by length, e.g. [-33, -22, -4] -> [-4, -22, -33]
¬ # Get the first element.
( # And negate that.
```
Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=KHvDqcKsKA&input=WzM0NTEsIDI5ODIwLCAyOTgzLCAxMjIzLCAxMzM3XQ)
[Answer]
# Python 2, ~~48~~ 42 bytes
-6 bytes thanks to @Dennis (use `min` rather than `sorted`)
```
lambda l:min(l,key=lambda x:(len(`x`),-x))
```
All test cases are at **[ideone](http://ideone.com/IbYFyJ)**
Take the minimum of the list by (length, -value)
[Answer]
# Ruby, 34 bytes
```
->a{a.max_by{|n|[-n.to_s.size,n]}}
```
See it on eval.in: <https://eval.in/643153>
[Answer]
# [MATL](http://github.com/lmendo/MATL), 14 bytes
```
10&YlktX<=G*X>
```
[Try it online!](http://matl.tryitonline.net/#code=MTAmWWxrdFg8PUcqWD4&input=Wzc4LCA5OSwgNjIwLCAxMDBd)
Explanation:
```
&Yl % Log
10 % Base 10
kt % Floor and duplicate
X< % Find the smallest element
= % Filter out elements that do not equal the smallest element
G % Push the input again
* % Multiply (this sets numbers that do not have the fewest digits to 0)
X> % And take the maximum
```
[Answer]
# [Retina](http://github.com/mbuettner/retina), ~~24~~ 16 bytes
```
O^`
O$#`
$.0
G1`
```
[Try it online!](http://retina.tryitonline.net/#code=T15gCk8kI2AKJC4wCkcxYA&input=MQoxMgo5CjYzCjUKMTAy) or [run all test cases](http://retina.tryitonline.net/#code=JShHYApPXmBcZCsKTyQjYFxkKwokLjAKIC4rCg&input=MQo5CjE3MjkKMSAxCjM0IDMKMzggMzkKNDA5IDEyIDEzCjExIDExIDExIDEKMTEgMTEgMTEgMTEKNzggOTkgNjIwIDEKNzggOTkgNjIwIDEwCjc4IDk5IDYyMCAxMDAKMSA1IDkgMTIgNjMgMTAyCjM0NTEgMjk4MjAgMjk4MyAxMjIzIDEzMzcKNzM4IDIzODMgMjgxIDkzOCAyMTIgMTAxMA).
Saved 8 bytes thanks to Martin!
The all test is using a slightly older version of the code, but the algorithm is identical. I'll update it to be closer when I get more time.
The trailing newline is significant. Sorts the numbers by reverse numeric value, then sorts them by number of digits. This leaves us with the largest number with the fewest digits in the first position, so we can just delete the remaining digits.
[Answer]
# Mathematica, ~~33~~ 31 bytes
```
Max@MinimalBy[#,IntegerLength]&
```
MinimalBy selects all the elements of the original input list with the smallest score according to `IntegerLength`, i.e., with the smallest number of digits; and then Max outputs the largest one.
*Thanks to Martin Ender for finding, and then saving, 2 bytes for me :)*
[Answer]
# [Perl 6](https://perl6.org), 18 bytes
```
*.min:{.chars,-$_}
```
## Explanation:
```
*\ # Whatever lambda
.min: # find the minimum using
{ # bare block lambda with implicit parameter 「$_」
.chars, # number of characters first ( implicit method call on 「$_」 )
-$_ # then negative of the value in case of a tie
}
```
## Usage:
```
say [738, 2383, 281, 938, 212, 1010].&( *.min:{.chars,-$_} ); # 938
my &code = *.min:{.chars,-$_}
say code [78, 99, 620, 10]; # 99
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~16~~ ~~15~~ 14 bytes
```
|/{=/&/\#'$x}#
```
[Try it online!](https://ngn.codeberg.page/k/#eJxlUNtqwzAMffdXCFp2AY9EVtpYNduPZIHupTA2GJQ9tHTdt+9IbtZ2g/hyLlaks1l9NYfH5qZ5nt3Od8dZCJ+rw3zYf29XGyLalfXHW7lbb15e38uu7Mv2fjzCM0QuPNqpRf3kPmmxzRDTSZaOpIjfMokWcblrlTgRS2HXGP761VdnDMKZPpMqLVM7WS6Itqj+pSaOaUGJ/G9LAZ9qt9ItmJJmeLFDSAmbSF9M8WLoNwmklJnUgDXc2s8kjyE0YeCRHp6Iw6B+UTA2vpO4AEb69UgXSRwIQAaoToEPccCZsKqDYWF7PK2pyBV5YkH3KKcogdEvzNdsW3vUf/xZQNEFpNrKUkxM02QWS6yJ+WEqMoseWh0EjmCxRc8tWnDRkosWXfTsajXJP9wzhD8=)
* `{...}#` set up a filter, returning elements from the (implicit) right argument where the code in `{...}` returns `1`s
+ `#'$x` count the number of characters in the string representation of each input
+ `&/\` generate a two item list of the character counts and their minimum
+ `=/` generate a boolean mask indicating which indices have the fewest digits
* `|/` return the maximum (remaining) value
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 8 bytes
```
DL€İMị¹Ṁ
```
[Try it online!](http://jelly.tryitonline.net/#code=REzigqzEsE3hu4vCueG5gA&input=&args=WzM0NTEsIDI5ODIwLCAyOTgzLCAxMjIzLCAxMzM3XQ) or [Verify all test cases.](http://jelly.tryitonline.net/#code=REzigqzEsE3hu4vCueG5gArDh-KCrA&input=&args=W1sxXSwKIFs5XSwKIFsxNzI5XSwKIFsxLCAxXSwKIFszNCwgM10sCiBbMzgsIDM5XSwKIFs0MDksIDEyLCAxM10sCiBbMTEsIDExLCAxMSwgMV0sCiBbMTEsIDExLCAxMSwgMTFdLAogWzc4LCA5OSwgNjIwLCAxXSwKIFs3OCwgOTksIDYyMCwgMTBdLAogWzc4LCA5OSwgNjIwLCAxMDBdLAogWzEsIDUsIDksIDEyLCA2MywgMTAyXSwKIFszNDUxLCAyOTgyMCwgMjk4MywgMTIyMywgMTMzN10sCiBbNzM4LCAyMzgzLCAyODEsIDkzOCwgMjEyLCAxMDEwXV0)
## Explanation
```
DL€İMị¹Ṁ Input: list A
D Convert each integer to a list of base 10 digits
L€ Get the length of each list (number of digits of each)
İ Take the reciprocal of each
M Get the indices of the maximal values
¹ Get A
ị Select the values at those indices from A
Ṁ Find the maximum and return
```
[Answer]
# JavaScript (ES6), 51
```
l=>l.sort((a,b)=>(a+l).length-(b+l).length||b-a)[0]
```
**Test**
```
f=l=>l.sort((a,b)=>(a+l).length-(b+l).length||b-a)[0]
;[
[[1], 1]
,[[9], 9]
,[[1729], 1729]
,[[1, 1], 1]
,[[34, 3], 3]
,[[38, 39], 39]
,[[409, 12, 13], 13]
,[[11, 11, 11, 1], 1]
,[[11, 11, 11, 11], 11]
,[[78, 99, 620, 1], 1]
,[[78, 99, 620, 10], 99]
,[[78, 99, 620, 100], 99]
,[[1, 5, 9, 12, 63, 102], 9]
,[[3451, 29820, 2983, 1223, 1337], 3451]
,[[738, 2383, 281, 938, 212, 1010], 938]
].forEach(([l,x])=>{
var r=f(l)
console.log(r==x?'OK':'KO',l+' -> '+r)
})
```
[Answer]
# J, ~~21~~ 14 bytes
Saved 7 bytes thanks to miles and (indirectly) Jonathan!
```
{.@/:#@":"0,.-
```
This is a four-chain:
```
{.@/: (#@":"0 ,. -)
```
Let's walk over the input `10 27 232 1000`. The inner fork consists of three tines. `#@":"0` calculates the sizes, `,.` concats each size with its negated (`-`) member. For input `10 27 232 1000`, we are left with this:
```
(#@":"0 ,. -) 10 27 232 1000
2 _10
2 _27
3 _232
4 _1000
```
Now, we have `{.@/:` as the outer tine. This is monadic first (`{.`) over dyadic sort (`/:`). That is, we'll be taking the first element of the result of dyadic `/:`. This sorts its right argument according to its left argument, which gives us for our input:
```
(/: #@":"0 ,. -) 10 27 232 1000
27 10 232 1000
```
Then, using `{.` gives us the first element of that list, and we are done:
```
({.@/: #@":"0 ,. -) 10 27 232 1000
27
```
## Old version
```
>./@(#~]=<./@])#@":"0
```
Still working on improvements. I golfed it down from 30, and I think this is good enough. I'm going to first break it down into basic parts:
```
size =: #@":"0
max =: >./
min =: <./
over =: @
right =: ]
left =: [
selectMin =: #~ right = min over right
f =: max over selectMin size
f 3 4 5
5
f 3 4 53
4
f 343 42 53
53
```
Here's how this works.
```
>./@(#~ ] = <./@]) #@":"0
```
This is a monadic train, but this part is a hook. The verb `>./@(#~ ] = <./@])` is called with left argument as the input to the main chain and the sizes, defined as `#@":"0`, as the right argument. This is computed as length (`#`) over (`@`) default format (`":`), that is, numeric stringification, which is made to apply to the 0-cells (i.e. members) of the input (`"0`).
Let's walk over the example input `409 12 13`.
```
(#@":"0) 409 12 13
3 2 2
```
Now for the inner verb, `>./@(#~ ] = <./@])`. It looks like `>./@(...)`, which effectively means maximum value (`>./`) of (`@`) what's inside `(...)`. As for the inside, this is a four-train, equivalent to this five-train:
```
[ #~ ] = <./@]
```
`[` refers to the original argument, and `]` refers to the size array; `409 12 13` and `3 2 2` respectively in this example. The right tine, `<./@]`, computes the minimum size, `2` in this case. `] = <./@]` is a boolean array of values equal to the minimum, `0 1 1` in this case. Finally, `[ #~ ...` takes values from the left argument according the right-argument mask. This means that elements that correspond to `0` are dropped and `1` retained. So we are left with `12 13`. Finally, according to the above, the max is taken, giving us the correct result of `13`, and we are done.
[Answer]
# Julia, 39
```
f(l)=sort(l,by=x->(length("$x"),-x))[1]
```
[ATO](https://ato.pxeger.com/run?1=jZBNTsMwEIXFsjlFZCGRSAlK7P7EEolgyYITVCyM6kCQ5Va2C0UqJ2HTTQ9VTsNz3AAVG6Q4mXnvm6dxPvbPa9WJ3eHGiFdCSJuotLZL4xKVPbzVm7xJlNSP7ikh5xuSZvkmTeflPchtE4xtszKddkrv167Nq8PFPyOO-Hu7NLHqdIzHSLFAKW1i3aLTaTQSxmRG2tquVIe8Tmckb0gw6jvpxOVKGCsTtOm2kS9CRSPPB_VWOz8N_FpYK7FR25N13atSL8ISu8-zK2wU501cRnPeFzyalzMaal-gzeJvho2zmPUNQ1OhCSQDNy44SIoTiBJI6YeHM4SciEcV8gxxHBFTWvyCT9Ui7Mj_6D8GQiewwipT5k063IyNJ7Apr_wQPt6l1L8Zm4WLgEC4vxpl3qcVJnjf93crhh1YFYW_-AU)able
[Answer]
# JavaScript (ES6), 62 bytes
```
var solution =
a=>a.map(n=>(l=`${n}`.length)>a?l>a+1|n<r?0:r=n:(a=l-1,r=n))|r
;document.write('<pre>' + `
[1] -> 1
[9] -> 9
[1729] -> 1729
[1, 1] -> 1
[34, 3] -> 3
[38, 39] -> 39
[409, 12, 13] -> 13
[11, 11, 11, 1] -> 1
[11, 11, 11, 11] -> 11
[78, 99, 620, 1] -> 1
[78, 99, 620, 10] -> 99
[78, 99, 620, 100] -> 99
[1, 5, 9, 12, 63, 102] -> 9
[3451, 29820, 2983, 1223, 1337] -> 3451
[738, 2383, 281, 938, 212, 1010] -> 938
`.split('\n').slice(1, -1).map(c =>
c + ', result: ' + solution(eval(c.slice(0, c.indexOf('->'))))
).join('\n'))
```
[Answer]
## Javascript (ES6), ~~57~~ ~~54~~ 53 bytes
```
l=>l.sort((a,b)=>(s=a=>1/a+`${a}`.length)(a)-s(b))[0]
```
For the record, my previous version was more math-oriented but 1 byte bigger:
```
l=>l.sort((a,b)=>(s=a=>1/a-~Math.log10(a))(a)-s(b))[0]
```
### Test cases
```
let f =
l=>l.sort((a,b)=>(s=a=>1/a+`${a}`.length)(a)-s(b))[0]
console.log(f([1])); // -> 1
console.log(f([9])); // -> 9
console.log(f([1729])); // -> 1729
console.log(f([1, 1])); // -> 1
console.log(f([34, 3])); // -> 3
console.log(f([38, 39])); // -> 39
console.log(f([409, 12, 13])); // -> 13
console.log(f([11, 11, 11, 1])); // -> 1
console.log(f([11, 11, 11, 11])); // -> 11
console.log(f([78, 99, 620, 1])); // -> 1
console.log(f([78, 99, 620, 10])); // -> 99
console.log(f([78, 99, 620, 100])); // -> 99
console.log(f([1, 5, 9, 12, 63, 102])); // -> 9
console.log(f([3451, 29820, 2983, 1223, 1337])); // -> 3451
console.log(f([738, 2383, 281, 938, 212, 1010])); // -> 938
```
[Answer]
## dc, 54 bytes
```
?dZsL0sN[dsNdZsL]su[dlN<u]sU[dZlL=UdZlL>ukz0<R]dsRxlNp
```
**Explanation:**
```
?dZsL0sN # read input, initialize L (length) and N (number)
[dsNdZsL]su # macro (function) 'u' updates the values of L and N
[dlN<u]sU # macro 'U' calls 'u' if N < curr_nr
[dZlL=U dZlL>ukz0<R]dsR # macro 'R' is a loop that calls 'U' if L == curr_nr_len
#or 'u' if L > curr_nr_len
xlNp # the main: call 'R' and print N at the end
```
**Run example:** 'input.txt' contains all the test cases in the question's statement
```
while read list;do echo "$list -> "$(dc -f program.dc <<< $list);done < input.txt
```
**Output:**
```
1 -> 1
9 -> 9
1729 -> 1729
1 1 -> 1
34 3 -> 3
38 39 -> 39
409 12 13 -> 13
11 11 11 1 -> 1
11 11 11 11 -> 11
78 99 620 1 -> 1
78 99 620 10 -> 99
78 99 620 100 -> 99
1 5 9 12 63 102 -> 9
3451 29820 2983 1223 1337 -> 3451
738 2383 281 938 212 1010 -> 938
```
[Answer]
# Java 7, ~~112~~ 104 bytes
```
int c(int[]a){int i=a[0],j;for(int b:a)i=(j=(i+"").length()-(b+"").length())>0?b:b>i&j==0?b:i;return i;}
```
Different approach to save multiple bytes thanks to *@Barteks2x*.
**Ungolfed & test cases:**
[Try it here.](https://ideone.com/Zo6o2f)
```
class M{
static int c(int[] a){
int i = a[0],
j;
for(int b : a){
i = (j = (i+"").length() - (b+"").length()) > 0
? b
: b > i & j == 0
? b
: i;
}
return i;
}
public static void main(String[] a){
System.out.println(c(new int[]{ 1 }));
System.out.println(c(new int[]{ 9 }));
System.out.println(c(new int[]{ 1729 }));
System.out.println(c(new int[]{ 1, 1 }));
System.out.println(c(new int[]{ 34, 3 }));
System.out.println(c(new int[]{ 409, 12, 13 }));
System.out.println(c(new int[]{ 11, 11, 11, 1 }));
System.out.println(c(new int[]{ 11, 11, 11, 11 }));
System.out.println(c(new int[]{ 78, 99, 620, 1 }));
System.out.println(c(new int[]{ 78, 99, 620, 100 }));
System.out.println(c(new int[]{ 1, 5, 9, 12, 63, 102 }));
System.out.println(c(new int[]{ 3451, 29820, 2983, 1223, 1337 }));
System.out.println(c(new int[]{ 738, 2383, 281, 938, 212, 1010 }));
}
}
```
**Output:**
```
1
9
1729
1
3
13
1
11
1
99
9
3451
938
```
[Answer]
# bash, awk, sort 53 bytes
```
set `awk '{print $0,length($0)}'|sort -rnk2n`;echo $1
```
Read input from stdin, one value per line
# bash and sort, ~~58~~ 57 bytes
```
set `sort -n`;while((${#2}==${#1}));do shift;done;echo $1
```
[Answer]
# JavaScript ES6, ~~80~~ ~~77~~ 70 bytes
```
a=>Math.max(...a.filter(l=>l.length==Math.min(...a.map(i=>i.length))))
```
I hope I am going in the right direction...
[Answer]
# [Brachylog](http://github.com/JCumin/Brachylog), 16 bytes
```
or:@]feL:la#=,Lh
```
[Try it online!](http://brachylog.tryitonline.net/#code=b3I6QF1mZUw6bGEjPSxMaA&input=WzM0NTE6Mjk4MjA6Mjk4MzoxMjIzOjEzMzdd&args=Wg)
### Explanation
```
or Sort the list in descending order.
:@]f Find all suffixes of the list.
eL Take one suffix L of the list.
:la Apply length to all numbers in that suffix.
#=, All lengths must be equal.
Lh Output is the first element of L.
```
[Answer]
# Haskell, 39 bytes
```
snd.maximum.map((0-).length.show>>=(,))
```
[Answer]
# [MATL](http://github.com/lmendo/MATL), 11 bytes
```
tV48\&XS0))
```
Input is a column vector (using `;` as separator), such as
```
[78; 99; 620; 100]
```
[Try it online!](http://matl.tryitonline.net/#code=dFY0OFwmWFMwKSk&input=WzczODsgMjM4MzsgMjgxOyA5Mzg7IDIxMjsgMTAxMF0) Or [verify all test cases](http://matl.tryitonline.net/#code=YAp0VjQ4XCZYUzApKQpEVA&input=WzFdCls5XQpbMTcyOV0KWzE7IDFdClszNDsgM10KWzM4OyAzOV0KWzQwOTsgMTI7IDEzXQpbMTE7IDExOyAxMTsgMV0KWzExOyAxMTsgMTE7IDExXQpbNzg7IDk5OyA2MjA7IDFdCls3ODsgOTk7IDYyMDsgMTBdCls3ODsgOTk7IDYyMDsgMTAwXQpbMTsgNTsgOTsgMTI7IDYzOyAxMDJdClszNDUxOyAyOTgyMDsgMjk4MzsgMTIyMzsgMTMzN10KWzczODsgMjM4MzsgMjgxOyA5Mzg7IDIxMjsgMTAxMF0).
### Explanation
Let's use input `[78; 99; 620; 100]` as an example.
```
t % Input column vector implicitly. Duplicate
% STACK: [78; 99; 620; 100], [78; 99; 620; 100]
V % Convert to string. Each number is a row, left-padded with spaces
% STACK: [78; 99; 620; 100], [' 78'; ' 99'; '620'; '100']
48\ % Modulo 48. This transforms each digit into the corresponding number,
% and space into 32. Thus space becomes the largest "digit"
% STACK: [78; 99; 620; 100], [32 7 8; 32 9 9; 6 2 0; 1 0 0]
&XS % Sort rows in lexicographical order, and push the indices of the sorting
% STACK: [78; 99; 620; 100], [4; 3; 1; 2]
0) % Get last value
% STACK: [78; 99; 620; 100], 2
) % Index
% STACK: 99
% Implicitly display
```
[Answer]
# Perl, ~~38~~ 37 bytes
Includes +1 for `-a`
Give input on STDIN:
```
perl -M5.010 maxmin.pl <<< "3451 29820 2983 1223 1337"
```
`maxmin.pl`:
```
#!/usr/bin/perl -a
\$G[99-y///c][$_]for@F;say$#{$G[-1]}
```
Uses memory linear in the largest number, so don't try this on too large numbers. A solution without that flaw is 38 bytes:
```
#!/usr/bin/perl -p
$.++until$\=(sort/\b\S{$.}\b/g)[-1]}{
```
All of these are very awkward and don't feel optimal at all...
[Answer]
## PowerShell v2+, 41 bytes
```
($args[0]|sort -des|sort{"$_".length})[0]
```
Takes input `$args`, `sort`s it by value in `-des`cending order (so bigger numbers are first), then `sort`s that by the `.length` in ascending order (so shorter lengths are first). We then take the `[0]` element, which will be the biggest number with the fewest digits.
## Examples
```
PS C:\Tools\Scripts\golfing> @(78,99,620,1),@(78,99,620,10),@(78,99,620,100),@(1,5,9,12,63,102),@(3451,29820,2983,1223,1337),@(738,2383,281,938,212,1010)|%{($_-join',')+" -> "+(.\output-largest-number-fewest-digits.ps1 $_)}
78,99,620,1 -> 1
78,99,620,10 -> 99
78,99,620,100 -> 99
1,5,9,12,63,102 -> 9
3451,29820,2983,1223,1337 -> 3451
738,2383,281,938,212,1010 -> 938
```
[Answer]
# R, ~~72~~ ~~41~~ 36 bytes
Rewrote the function with a new approach. Golfed 5 bytes thanks to a suggestion from @bouncyball.
```
n=nchar(i<-scan());max(i[n==min(n)])
```
Explained:
```
i<-scan() # Read input from stdin
n=nchar( ); # Count the number of characters in each number in i
max( ) # Return the maximum of the set where
i[n==min(n)] # the number of characters is the minimum number of characters.
```
```
function(i){while(1){if(length(o<-i[nchar(i)==T]))return(max(o));T=T+1}}
```
Indented/explained:
```
function(i){ # Take an input i
while(1){ # Do the following continuously:
if(length(
o<-i[nchar(i)==T]) # Define o to be the subset of i with numbers of length T,
) # where T is 1 (a built-in!).
# We take the length of this subset (its size), and then pass
# it to if(). Thanks to weak typing, this numeric is converted
# to a logical value. When this occurs, zero evaluates to FALSE
# and any non-zero number evaluates to TRUE. Therefore, the if()
# is TRUE iff the subset is not empty.
return(max(o)); # If it's true, then we just return the largest element of the
# subset, breaking out of our loop.
T=T+1 # Otherwise, increment our counter and continue.
}
}
```
[Answer]
## Bash + coreutils, 58 bytes
```
d=`sort -n`;egrep ^.{`sed q<<<"$d"|wc -L`}$<<<"$d"|tail -1
```
Input format is one value per line. Golfing suggestions are welcomed.
**Explanation:**
```
d=`sort -n` #save the list in ascending numerical order
egrep ^.{ }$<<<"$d" #print only list lines having as many chars
`sed q<<<"$d"|wc -L` #as the first sorted line does
|tail -1 #and then get the last one (the answer)
```
[Answer]
# **Python 2 - 41 bytes**
```
lambda l:max((-len(`x`),x) for x in l)[1]
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 36 bytes
-4 thanks to @rak1507.
```
f←⌈/⊢×((⌊/=⊢)≢∘⍕¨)
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RHPR36j7oWHZ6uofGop0vfFsjWfNS56FHHjEe9Uw@t0Pz/qG8qUFmagrmxhY6CkbGFMZC0MNRRsATzDY10FAwNDA24YMqAMqZASaAoUMbMGCRr9B8A "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
DL$ÐṂṀ
```
[Try it online!](https://tio.run/##ZU8rDsJAEPU9xQpkSboz/a1BERSahDSVGNIL4JoaEhQXwIBFItoge5LtRZa3XRZoELM77zMvM/tdVR2MWa5n/Vl3je5qo9uT7m5DfSl1e92s@mOgn4/@ODT3rTGFLMV8IWRQqLFRQSEzcr1tAEPx8XAcCh4BA@QAzsnwxZGCk1DOIWGRdtiXD5mQbxZ0hjiFiJSiH/OUjdyO6o//CghNILlVUrYi@cs4TiCTyu0QPqsS2Zc5c4fAgXB7GrHVKceEGvF4W@R34PwF "Jelly – Try It Online")
## How it works
```
DL$ÐṂṀ - Main link. Takes a list L on the left
$ÐṂ - Take the elements of L for which the following is minimal:
DL - Digit Length
Ṁ - Maximum of those elements
```
] |
[Question]
[]
|
[Question]
[]
|
[Question]
[
So... uh... this is a bit embarrassing. But we don't have a plain "Hello, World!" challenge yet (despite having 35 variants tagged with [hello-world](/questions/tagged/hello-world "show questions tagged 'hello-world'"), and counting). While this is not the most interesting code golf in the common languages, finding the shortest solution in certain esolangs can be a serious challenge. For instance, to my knowledge it is not known whether the shortest possible Brainfuck solution has been found yet.
Furthermore, while all of ~~[Wikipedia](https://en.wikipedia.org/wiki/List_of_Hello_world_program_examples)~~ (the Wikipedia entry [has been deleted](https://en.wikipedia.org/wiki/Wikipedia:Articles_for_deletion/List_of_Hello_world_program_examples) but there is a [copy at archive.org](https://web.archive.org/web/20150411170140/https://en.wikipedia.org/wiki/List_of_Hello_world_program_examples)
), [esolangs](https://esolangs.org/wiki/Hello_world_program_in_esoteric_languages) and [Rosetta Code](https://rosettacode.org/wiki/Hello_world/Text) have lists of "Hello, World!" programs, none of these are interested in having the shortest for each language (there is also [this GitHub repository](https://github.com/leachim6/hello-world)). If we want to be a significant site in the code golf community, I think we should try and create the ultimate catalogue of shortest "Hello, World!" programs (similar to how our [basic quine challenge](https://codegolf.stackexchange.com/q/69/8478) contains some of the shortest known quines in various languages). So let's do this!
## The Rules
* Each submission must be a full program.
* The program must take no input, and print `Hello, World!` to STDOUT (this exact byte stream, including capitalization and punctuation) plus an optional trailing newline, and nothing else.
* The program must not write anything to STDERR.
* If anyone wants to abuse this by creating a language where the empty program prints `Hello, World!`, then congrats, they just paved the way for a very boring answer.
Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language.
* Submissions are scored in *bytes*, in an appropriate (pre-existing) encoding, usually (but not necessarily) UTF-8. Some languages, like [Folders](https://esolangs.org/wiki/Folders), are a bit tricky to score - if in doubt, please ask on [Meta](https://meta.codegolf.stackexchange.com/).
* This is not about finding *the* language with the shortest "Hello, World!" program. This is about finding the shortest "Hello, World!" program in every language. Therefore, I will not mark any answer as "accepted".
* If your language of choice is a trivial variant of another (potentially more popular) language which already has an answer (think BASIC or SQL dialects, Unix shells or trivial Brainfuck-derivatives like Alphuck), consider adding a note to the existing answer that the same or a very similar solution is also the shortest in the other language.
As a side note, please *don't* downvote boring (but valid) answers in languages where there is not much to golf - these are still useful to this question as it tries to compile a catalogue as complete as possible. However, *do* primarily upvote answers in languages where the authors actually had to put effort into golfing the code.
For inspiration, check [the Hello World Collection](https://helloworldcollection.github.io/).
## 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 = 55422; // 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]
# [PDP-11](https://en.wikipedia.org/wiki/PDP-11) machine language on [BSD 2.11](https://en.wikipedia.org/wiki/History_of_the_Berkeley_Software_Distribution#2BSD_(PDP-11)), ~~37~~ 34 bytes
```
00: 15ce 000d mov $15,(sp) ; len of string on stack
04: 09f7 000e jsr pc, 26 ; addr of string on stack
10: 6548 6c6c ; "Hello, World!"
2c6f 5720
726f 646c
0021
26: 15e6 0001 mov $1,-(sp) ; stdout on stack
32: 15e6 0001 mov $1,-(sp) ; stack padding
36: 8904 trap 4 ; write() syscall
40: 8901 trap 1 ; exit() syscall
```
Note that 2BSD does not use the same syscall convention as AT&T UNIXes for the PDP-11. As a result, some [previous winners of the IOCCC](https://lainsystems.com/posts/exploring-mullender-dot-c/) may not work out of the box on 2BSD.
To try this on a real or emulated PDP-11 running BSD 2.x (this won't work on other operating systems), compile and run the following C program.
```
char main[]={0xce,0x15,0x0d,0x00,0xf7,0x09,0x0e,0x00,'H','e'
,'l','l','o',',',' ','W','o','r','l','d','!',0x00,0xe6,0x15,
0x01,0x00,0xe6,0x15,0x01,0x00,0x04,0x89,0x01,0x89};
```
# PDP-11 machine language on [UNIX v7](https://en.wikipedia.org/wiki/Version_7_Unix), 36 bytes
```
00: 15ce 8901 mov $104401,(sp) ; exit()
04: 15e6 000d mov $15,-(sp) ; len of string
10: 09f7 000e jsr pc, 32 ; addr of string
14: 6548 6c6c ; "Hello, World!"
2c6f 5720
726f 646c
0021
32: 15e6 8904 mov $104404,-(sp); write()
36: 15c0 0001 mov $01,r0 ; fd=1
42: 004e jmp sp ; jump to stack
```
AT&T UNIXes for the PDP-11 had a different syscall convention in which some of the arguments are placed right after the trap instruction. Therefore, almost every syscall requires some self modifying code! The approach here is to generate a "Hello, World!" program on the stack and then jump to the stack.
To try this on a real or emulated PDP-11 running AT&T UNIX, compile and run this C program (if the compiler is very old, remove the `=`).
```
char main[]={0xce,0x15,0x01,0x89,0xe6,0x15,0x0d,0x00,0xf7,0x09
,0x0e,0x00,'H','e','l','l','o',',',' ','W','o','r','l','d','!'
,0x00,0xe6,0x15,0x04,0x89,0xc0,0x15,0x01,0x00,0x4e,0x00};
```
[Answer]
# [Noulith](https://github.com/betaveros/noulith), 15 bytes
```
"Hello, World!"
```
Implicitly outputs the string.
<https://betaveros.github.io/noulith/#IkhlbGxvLCBXb3JsZCEi>
[Answer]
# [MetaBrainfuck](https://github.com/bsoelch/MetaBrainfuck) `-x`, (22 bytes)
`"Hello, World!"{{+}.>}`
## Explanation
```
"Hello, World!"{ } # for each character in the string "Hello, World!"
{+}.> # repeat + that many times, then append .>
```
expands to the following Brainfuck program:
```
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++.>
```
which when [executed](https://ato.pxeger.com/run?1=m70yqSgxMy-tNDl7wYKlpSVpuha3WJq1qQT07Khl0mCwZgTYRrKFhFXTzAODPGSGop30sY0IW_TsIGURtEiCFU0A) (`-x` flag) prints `Hello, World!`
[Answer]
# [WE32k](https://en.wikipedia.org/wiki/Bellmac_32) machine language on AT&T UNIX System V, ~~37~~ 34 bytes
```
00: 84 4c 4a MOVW %sp,%ap ; set argument pointer for upcoming sycall
03: a0 01 PUSHW &0x1 ; push file descriptor = 1 to stack
05: 37 0f BSBB 0xf <0x14> ; push address of string to stack
07: 48 65 6c 6c 6f 2c 20 ; "Hello, World!"
0f: 57 6f 72 6c 64 21
14: a0 0d PUSHW &0xd ; push length of string to stack
16: 84 20 41 MOVW &0x20,%r1 ; select write()
19: 84 04 40 MOVW &0x4,%r0 ; configure GATE for syscall
1c: 30 61 GATE ; syscall
1e: 84 08 41 MOVW &0x8,%r1 ; select exit() syscall
21: 7b f8 BRB -0x8 <0x19> ; goto 0x19
```
To try this on an [emulator](https://unix50.org/) or [actual AT&T 3B2 hardware](https://www.livingcomputers.org/Computer-Collection/Online-Systems.aspx), compile and run the following C program.
```
char main[]={0x84,0x4c,0x4a,0xa0,0x01,0x37,0x0f,
'H','e','l','l','o',',',' ','W','o','r','l','d','!'
,0xa0,0x0d,0x84,0x20,0x41,0x84,0x04,0x40,0x30,0x61
,0x84,0x08,0x41,0x7b,0xf8};
```
[Answer]
# [IBM z/Architecture](https://en.wikipedia.org/wiki/IBM_Z) machine language on Linux, 31 bytes
```
00: a7 29 00 01 lghi %r2,1. # fd=1
04: c0 30 00 00 00 07 larl %r3,742 <+0x12> # set address of string
0a: a7 49 00 0d lghi %r4,13 # set length of string
0e: 0a 04 svc 4 # write() syscall
10: 0a 01 svc 1 # exit() syscall
12: 48 65 6c 6c # "Hello, World!"
16: 6f 2c 20 57
1a: 6f 72 6c 64
1e: 21
```
To try this on an emulator or actual machine, compile and run the following C program.
```
const char main[] __attribute__((section("rodata")))=
"\xa7\x29\x00\x01\xc0\x30\x00\x00\x00\x07\xa7\x49\x00"
"\x0d\x0a\x04\x0a\x01Hello, World!";
```
On a 31 bit machine (or 64 bit machine in 31 bit mode) change the `lghi` instructions to `lhi` which can be done by clearing the 16th most significant bit (0x29 becomes 0x28; 0x49 becomes 0x48).
[Answer]
# [m4](https://www.gnu.org/software/m4/manual/m4.html), 13 bytes
```
Hello, World!
```
[Try it online!](https://tio.run/##yzX5/98jNScnX0chPL8oJ0Xx/38A)
Trivial solution!
[Answer]
## [rs](https://github.com/kirbyfan64/rs), 14 bytes
```
/Hello, World!
```
Replaces the empty string with "Hello, World!"
[Answer]
## [WARP](https://esolangs.org/wiki/WARP), 16 bytes
```
)"Hello, World!"
```
`)` is the standard output mechanism.
[Answer]
## [ACIDIC](http://esolangs.org/wiki/ACIDIC), 16 bytes
```
Hello, World!
+*
```
Prints the entire storage stack, which is filled with `Hello, World!`.
[Answer]
## [Ans](http://esolangs.org/wiki/Ans), 16 bytes
```
$"Hello, World!"
```
`$` is the standard output mechanism.
[Answer]
## [J--](http://esolangs.org/wiki/J--), 28 bytes
```
main{echo("Hello, World!");}
```
`main` is replaced with `public static void main(String[]a)`, `echo` is replaced with `System.out.println`, and the entire program is put in a class.
[Answer]
## [A0A0](http://esolangs.org/wiki/A0A0), 57 bytes
```
P72P87
P101P111
P108P114
P108P108
P111P100
P44P33
P32
G-6
```
2 commands per line was the densest packing that I could find.
[Answer]
## [STXTRM](http://esolangs.org/wiki/STXTRM), 15 bytes
```
[Hello, World!]
```
`[...]` is the standard output mechanism.
[Answer]
## [Argh!](http://esolangs.org/wiki/Argh!), 27 bytes
```
ppppppppppppp
Hello, World!
```
Each `p` prints the character below it.
[Answer]
## [AutoIt](https://www.autoitscript.com/site/), 29 bytes
```
ConsoleWrite("Hello, World!")
```
Needs to be compiled as a console program.
[Answer]
## [Foobar and Foobaz and Barbaz, oh my!](http://esolangs.org/wiki/Foobar_and_Foobaz_and_Barbaz,_oh_my!), 314 bytes
```
72 and 72 and 0, oh my.
37 and 37 and 64, oh my.
72 and 72 and 36, oh my.
. and 64 and 44, oh my.
67 and 67 and 44, oh my.
. and 44 and 0, oh my.
. and 32 and 0, oh my.
87 and 87 and 0, oh my.
40 and 40 and 71, oh my.
16 and 16 and 98, oh my.
12 and 12 and 96, oh my.
. and 64 and 36, oh my.
1 and 1 and 32, oh my.
```
I believe that this is an optimal solution, with each line outputting a character.
[Answer]
## [Tarflex](https://esolangs.org/wiki/Tarflex), 18 bytes
```
outs Hello, World!
```
`outs` is the standard output mechanism.
[Answer]
## [SSBPL](https://esolangs.org/wiki/SSBPL), 33 bytes
```
0'!'d'l'r'o'W' ','o'l$'e'H[$][.]#
```
This pushes the ASCII for `"Hello, World!"` followed by a `0` onto the stack, then prints the top value while it isn't zero.
[Answer]
## [Super Stack!](https://esolangs.org/wiki/Super_Stack!), 66 bytes
```
0 33 100 108 114 111 87 32 44 111 108 108 101 72 if outputascii fi
```
Pushes the letters followed by a zero onto the stack, and prints them while they aren't zero.
[Answer]
## [Swap](http://esolangs.org/wiki/Swap), 13 bytes
```
Hello, World!
```
Similar to ///, but swaps the terms instead of replacing them.
[Answer]
## [ZeptoBasic](http://esolangs.org/wiki/ZeptoBasic), 21 bytes
```
print "Hello, World!"
```
`print` is the standard output mechanism.
[Answer]
# [EEL](http://github.com/m654z/EEL), 93 bytes
(Also known as Extensible Esoteric Language)
```
def(z|-1;x;z)
def(d|c;z)
72
d
101
d
108
c
d
111
d
44
d
32
d
87
d
111
d
114
d
108
d
100
d
33
d
```
I'm sure this could be golfed quite a lot, but this is something I whipped up pretty quick. All it does is define some helpful functions and use them to display "Hello, World!"
Also, this DOES print "Hello, World!" with the characters separated by newlines, but I can't do anything about that, it's impossible in EEL.
[Answer]
# [~English](https://esolangs.org/wiki/~English), 29 bytes
```
Display "Hello, World!".Stop.
```
[Answer]
## [Wat](https://github.com/theksp25/Wat), 47 + 1 = 48 [bytes](https://github.com/theksp25/Wat/wiki/Codepage)
```
0«!dlroW ,olleH»>ó#ÐÑÅv
^ <
```
~~I post a explanation tomorrow~~
Here is the explanation:
```
First line:
0«!dlroW ,olleH»>ó#ÐÑÅv
0«!dlroW ,olleH» Push a reversed null terminated string
> Go forward
ó Duplicate the top of stack
# Skip the next instruction
Ð Kill all "execution engines" (end the program)
Ñ If the top of the stack is 0, go backward (execute Ð and end the program), otherwise go forward
Å Print the character on the top of the stack
v Go downward
Second line:
^ <
Simply loop from the 'v' to the '>'
```
[Answer]
# [Fith](https://github.com/nazek42/fith), 17 bytes
```
"Hello, World!" .
```
`.` is the print word.
[Answer]
# [0815](https://esolangs.org/wiki/0815), ~~92~~ 80 bytes
```
<:48:~$<:65:~$<:6C:~$$><:6F:~$>@<:2C:~$<:20:~$<:57:~${~$<:72:~${~$<:64:~$<:21:~$
```
[Answer]
# Arithmescript, 42 bytes
[Try it here!](https://jsfiddle.net/4mfL9f55/1/)
Golfed:
```
var input = "";add("Hello, World!");out();
```
Ungolfed:
```
var input = "";
add("Hello, World!");
out();
```
This defines the input as nothing, adds the string `Hello, World!`, and then alerts it (you can't log to console as of now)
Technically this is **379 bytes**, as v1.0 had a bug where not embedding the programming language interpreter led to not being about to change the `input` variable.
Requires Arithmescript v1.0 or higher
---
# Arithmescript, 27 bytes
[Try it here!](https://jsfiddle.net/0tfg5w78/)
Golfed:
```
add("Hello, World!");out();
```
Ungolfed:
```
add("Hello, World!");
out();
```
v1.1 of Arithmescript automatically defines the `input` variable, so we use less bytes!
Requires Arithmescript v1.1 or higher
---
# Arithmescript, 11 bytes
[Try it here!](https://jsfiddle.net/0tfg5w78/)
Golfed:
```
hw();out();
```
Ungolfed:
```
hw();
out();
```
Arithmescript has a function that works the same as `add("Hello, World!")` but is shorter and takes no parameters.
Requires Arithmescript v1.1 or higher
---
If you're wondering, Arithmescript is a programming language written in JavaScript for golfing. Technically, it's not a programming language, but it is. You can view the sources of [v1.0](https://github.com/IAP-Reloaded/Arithmescript/blob/master/Arithmescript-oldest.js) and [v1.1](https://github.com/IAP-Reloaded/Arithmescript/blob/master/Arithmescript.js).
[Answer]
# [eacal](https://github.com/ConorOBrien-Foxx/eacal), 24 bytes
```
put string Hello, World!
```
Simple enough. `put` prints its argument, `string` turns its arguments into a string entity.
[Answer]
## Node.js REPL, 20 bytes
```
throw"Hello, World!"
```
Output:
```
> throw"Hello, World!"
Hello, World!
```
[Answer]
# [PAWN](http://www.compuphase.com/pawn/pawn.htm), 29 bytes
```
main()
print"Hello, World!\n"
```
(no trailing newline)
Originally I was looking how to get [QuadPawn](https://github.com/PetteriAimonen/QuadPawn) ([video](https://www.youtube.com/watch?v=WwzGsEINN3o)) installed on my [handheld scope](http://www.seeedstudio.com/wiki/DSO_Quad) but it turned out that my scope's hardware version (V2.72/8MB) isn't supported... :-(
Someone else wants to try this?
Luckily getting `Pawn compiler 4.0.5504M` from `https://github.com/compuphase/pawn` compiled on `Debian-8.5/AMD64` was not a big deal.
That way I could run/verify these two lines.
] |
[Question]
[
In the popular (and essential) computer science book, *An Introduction to Formal Languages and Automata* by Peter Linz, the following formal language is frequently stated:
$$\large{L=\{a^n b^n:n\in\mathbb{Z}^+\}}$$
mainly because this language can not be processed with finite-state automata.
This expression mean "Language L consists all strings of 'a's followed by 'b's, in which the number of 'a's and 'b's are equal and non-zero".
# Challenge
Write a working program/function which gets a string, **containing "a"s and "b"s only**, as input and **returns/outputs a truth value**, saying if this string **is valid the formal language L.**
* Your program cannot use any external computation tools, including network, external programs, etc. Shells are an exception to this rule; Bash, e.g., can use command line utilities.
* Your program must return/output the result in a "logical" way, for example: returning 10 instead of 0, "beep" sound, outputting to stdout etc. [More info here.](https://codegolf.meta.stackexchange.com/questions/2190/interpretation-of-truthy-falsey)
* Standard code golf rules apply.
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest code in bytes wins. Good luck!
### Truthy test cases
```
"ab"
"aabb"
"aaabbb"
"aaaabbbb"
"aaaaabbbbb"
"aaaaaabbbbbb"
```
### Falsy test cases
```
""
"a"
"b"
"aa"
"ba"
"bb"
"aaa"
"aab"
"aba"
"abb"
"baa"
"bab"
"bba"
"bbb"
"aaaa"
"aaab"
"aaba"
"abaa"
"abab"
"abba"
"abbb"
"baaa"
"baab"
"baba"
"babb"
"bbaa"
"bbab"
"bbba"
"bbbb"
```
## Leaderboard
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.
```
/* Configuration */
var QUESTION_ID = 85994; // 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 = 48934; // 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]
## Python 3, 32 bytes
```
eval(input().translate(")("*50))
```
[Try it online!](https://tio.run/##ZVFNbusgEN5zihEbzEtqJarexlaWPUVaWfBCWiQXEEyapgfoumfsRVJmcLp5yGL@vu@bGZwu@BLD/dW/ppgRfFyXS1m3aPZWHNwRJh/SCTs9wPMcrZkBXcERssNTDhyIabInP6MPZZp6hsNu4Y0QkwudJFzp00Wu5Vnq/pw9ui5LKa/uzczd0qPHbEKZTa1J3ck/fzdaXytovx3utk96hDpenwy@1C7FZew2a1Cq5j92G3GMGeoOgUEFDz4MAurxR/gYbsl4wqW5egxK3wC4r/q7HeUGoOlxTx25TKNTZgRXjdqols2XJk8n0b5Te7dpWraV@rfeRvh91z67OZpDlxrCvf9zCeGBjY8BTAGX89D6bdV4G74mb8NLtcKVkgMoWNV/kXJXi7r6vNbIuv@t7KgO359fIImGFMr2fNurscIYS1e92ZBtDnuL23wrhBGUEbZ@XCK6MDUkFcuVarncqCxNKIIYvojQGEwhDpEIYlmGdZpQU7I/ "Python 3 – Try It Online")
[Outputs via exit code](https://codegolf.meta.stackexchange.com/a/5330/20260): Error for false, no error for True.
The string is evaluated as Python code, replacing parens `(` for `a` and `)` for `b`. Only expressions of the form `a^n b^n` become well-formed expressions of parentheses like `((()))`, evaluating to the tuple `()`.
Any mismatched parens give an error, as will multiple groups like `(()())`, since there's no separator. The empty string also fails (it would succeed on `exec`).
The conversion `( -> a`, `) -> b` is done using `str.translate`, which replaces characters as indicated by a string that serves as a conversion table. Given the 100-length string ")("\*50, the tables maps the first 100 ASCII values as
```
... Z[\]^_`abc
... )()()()()(
```
which takes `( -> a`, `) -> b`.
In Python 2, conversions for all 256 ASCII values must be provided, requiring `"ab"*128`, one byte longer; thanks to isaacg for pointing this out.
[Try it online!](https://tio.run/##ZVBBjtswDLzrFYR6kNWkRrynwoaPfUVaGNJG2RXgSoJEd5t9QM99Yz@SkpLTSwVDpGY4Q9Lphq8xPN0/PMeLDy/zhlfhv6eYEXw8lls50ktc3BUWH9KGnR7hZY3WrICu4ATZ4ZYDuB9m7RjRYlns5lf0oSxLX0Uw7@oJYnKhk1xY@nSTR/kmdf@WPbouSynv1Wfv1GM2oayGOKk7@XF4@qz1narOw/hp@KYnoPn6ZPCV2hSXsTsdQSnC3@eTuMYMtESoRQVpu1EAHX@F9/EBxg337uprUPpRgGfyn2fGRuDx8cwdK82zE6KkOuCB7gkcP0@qsfnW2vBJvPjSfuey7GtL/Y9voxDfZ7dGc@lS49zPZ5cQvtTgYwBTwOU8tk6Dmh7jE7iPX6c6AI2rKGSXckekZogXm6rvf0s75uHPr98gWVYdZPuBw91YYYzli@4aOLakZnvaciuEEYwIS1@lWC4MPdnFVoZipZu0WnMVl5h6saApqoQ1LOISW22qTzNqTvYv "Python 2 – Try It Online") (Python 2, 33 bytes)
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~5~~ 4 bytes
```
tSP-
```
Prints a non-empty array of **1**s if the string belongs to **L**, and an empty array or an array with **0**s (both falsy) otherwise.
*Thanks to @LuisMendo for golfing off 1 byte!*
[Try it online!](http://matl.tryitonline.net/#code=dFNQLQ&input=J2FhYmIn)
### How it works
```
t Push a copy of the implicitly read input.
S Sort the copy.
P Reverse the sorted copy.
- Take the difference of the code point of the corresponding characters
of the sorted string and the original.
```
[Answer]
## [Retina](https://github.com/m-ender/retina), 12 bytes
*Credits to FryAmTheEggman who found this solution independently.*
```
+`a;?b
;
^;$
```
Prints `1` for valid input and `0` otherwise.
[Try it online!](http://retina.tryitonline.net/#code=JShHYAorYGE7P2IKOwpeOyQ&input=YWIKYWFiYgphYWFhYmJiYgphYWFhYWFhYmJiYmJiYgoKYQpiCmJhCmFiYWIKYWFiCmFiYgphYWFhYmJi) (The first line enables a linefeed-separated test suite.)
### Explanation
Balancing groups require expensive syntax, so instead I'm trying to reduce a valid input to a simple form.
**Stage 1**
```
+`a;?b
;
```
The `+` tells Retina to repeat this stage in a loop until the output stops changing. It matches either `ab` or `a;b` and replaces it with `;`. Let's consider a few cases:
* If the `a`s and the `b`s in the string aren't balanced in the same way that `(` and `)` normally need to be, some `a` or `b` will remain in the string, since `ba`, or `b;a` can't be resolved and a single `a` or `b` on its own can't either. To get rid of all the `a`s and the `b`s there has to be one corresponding `b` to the right of each `a`.
* If the `a` and the `b` aren't all nested (e.g. if we have something like `abab` or `aabaabbb`) then we'll end up with multiple `;` (and potentially some `a`s and `b`s) because the first iteration will find multiple `ab`s to insert them and further iterations will preserve the number of `;` in the string.
Hence, if and only if the input is of the form `anbn`, we'll end up with a single `;` in the string.
**Stage 2:**
```
^;$
```
Check whether the resulting string contains nothing but a single semicolon. (When I say "check" I actually mean, "count the number of matches of the given regex, but since that regex can match at most once due to the anchors, this gives either `0` or `1`.)
[Answer]
## Haskell, 31 bytes
```
f s=s==[c|c<-"ab",'a'<-s]&&s>""
```
The list comprehension `[c|c<-"ab",'a'<-s]` makes a string of one `'a'` for each `'a'` in `s`, followed by one `'b'` for each `'a'` in `s`. It avoids counting by [matching on a constant](https://codegolf.stackexchange.com/a/83103/20260) and producing an output for each match.
This string is checked to be equal to the original string, and the original string is checked to be non-empty.
[Answer]
## [Grime](http://github.com/iatorm/grime), 12 bytes
```
A=\aA?\b
e`A
```
[Try it online!](http://grime.tryitonline.net/#code=QT1cYUE_XGIKZWBB&input=YWFhYWJiYmI)
## Explanation
The first line defines a nonterminal `A`, which matches one letter `a`, possibly the nonterminal `A`, and then one letter `b`. The second line matches the entire input (`e`) against the nonterminal `A`.
## 8-byte noncompeting version
```
e`\a_?\b
```
After writing the first version of this answer, I updated Grime to consider `_` as the name of the top-level expression. This solution is equivalent to the above, but avoids repeating the label `A`.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~23~~ 19 bytes
```
@2L,?lye:"ab"rz:jaL
```
[Try it online!](http://brachylog.tryitonline.net/#code=QDJMLD9seWU6ImFiInJ6OmphTA&input=ImFhYWFhYWFiYmJiYmJiIg)
### Explanation
```
@2L, Split the input in two, the list containing the two halves is L
?lye Take a number I between 0 and the length of the input
:"ab"rz Zip the string "ab" with that number, resulting in [["a":I]:["b":I]]
:jaL Apply juxtapose with that zip as input and L as output
i.e. "a" concatenated I times to itself makes the first string of L
and "b" concatenated I times to itself makes the second string of L
```
[Answer]
# Bison/YACC 60 (or 29) bytes
(Well, the compilation for a YACC program is a couple of steps so might want to include some for that. See below for details.)
```
%%
l:c'\n';
c:'a''b'|'a'c'b';
%%
yylex(){return getchar();}
```
The function should be fairly obvious if you know to interpret it in terms of a formal grammar. The parser accepts either `ab` or an `a` followed by any acceptable sequence followed by a `b`.
This implementation relies on a compiler that accepts K&R semantics to lose a few characters.
It's wordier than I would like with the need to define `yylex` and to call `getchar`.
Compile with
```
$ yacc equal.yacc
$ gcc -m64 --std=c89 y.tab.c -o equal -L/usr/local/opt/bison/lib/ -ly
```
(most of the options to gcc are specific to my system and shouldn't count against the byte count; you might want to count `-std=c89` which adds 8 to the value listed).
Run with
```
$ echo "aabb" | ./equal
```
or equivalent.
The truth value is returned to the the OS and errors also report `syntax error` to the command line. If I can count only the part of the code that defines the parsing function (that is neglect the second `%%` and all that follows) I get a count of 29 bytes.
[Answer]
# J, ~~17~~ 15 bytes
*-2 bytes thanks to [Jonah](https://codegolf.stackexchange.com/users/15469/jonah)!*
```
#<.2&#-:'ab'#~#
```
This works correctly for giving falsey for the empty string. Error is falsey.
Other versions:
```
<e.'ab'<@#"{~#\ NB. alternate 15 bytes, thanks to Jonah
#<.(-:'ab'#~-:@#)
NB. the following do not handle the empty string correctly
-:'ab'#~-:@#
2&#-:'ab'#~# NB. thanks to miles
```
## Proof and explanation
*Outdated, but applicable to the old 17 byte version.*
The main verb is a fork consisting of these three verbs:
```
# <. (-:'ab'#~-:@#)
```
This means, "The lesser of (`<.`) the length (`#`) and the result of the right tine (`(-:'ab'#~-:@#)`)".
The right tine is a [4-train](http://www.jsoftware.com/help/learning/09.htm), consisting of:
```
(-:) ('ab') (#~) (-:@#)
```
Let `k` represent our input. Then, this is equivalent to:
```
k -: ('ab' #~ -:@#) k
```
`-:` is the match operator, so the leading `-:` tests for invariance under the monadic fork `'ab' #~ -:@#`.
Since the left tine of the fork is a verb, it becomes a constant function. So, the fork is equivalent to:
```
'ab' #~ (-:@# k)
```
The right tine of the fork halves (`-:`) the length (`#`) of `k`. Observe `#`:
```
1 # 'ab'
'ab'
2 # 'ab'
'aabb'
3 # 'ab'
'aaabbb'
'ab' #~ 3
'aaabbb'
```
Now, this is `k` only on valid inputs, so we are done here. `#` errors for odd-length strings, which *never* satisfies the language, so there we are also done.
Combined with the lesser of the length and this, the empty string, which is not a part of our language, yields its length, `0`, and we are done with it all.
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 9 bytes
Code:
```
.M{J¹ÔQ0r
```
Explanation:
```
.M # Get the most frequent element from the input. If the count is equal, this
results into ['a', 'b'] or ['b', 'a'].
{ # Sort this list, which should result into ['a', 'b'].
J # Join this list.
Ô # Connected uniquified. E.g. "aaabbb" -> "ab" and "aabbaa" -> "aba".
Q # Check if both strings are equal.
0r # (Print 0 if the input is empty).
```
The last two bytes can be discarded if the input is guaranteed to be non-empty.
Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=Lk17SsK5w5RR&input=YWFhYWJiYmI).
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ṣ=Ṛ¬Pȧ
```
Prints the string itself if it belongs to **L** or is empty, and **0** otherwise.
[Try it online!](http://jelly.tryitonline.net/#code=4bmiPeG5msKsUMin&input=&args=YWFiYg) or [verify all test cases](http://jelly.tryitonline.net/#code=4bmiPeG5msKsUMinCsOH4oKsauKBtw&input=&args=ImFiIiwgImFhYmIiLCAiYWFhYmJiIiwgImFhYWFiYmJiIiwgImFhYWFhYmJiYmIiLCAiYWFhYWFhYmJiYmJiIiwgIiIsICJhIiwgImIiLCAiYWEiLCAiYmEiLCAiYmIiLCAiYWFhIiwgImFhYiIsICJhYmEiLCAiYWJiIiwgImJhYSIsICJiYWIiLCAiYmJhIiwgImJiYiIsICJhYWFhIiwgImFhYWIiLCAiYWFiYSIsICJhYmFhIiwgImFiYWIiLCAiYWJiYSIsICJhYmJiIiwgImJhYWEiLCAiYmFhYiIsICJiYWJhIiwgImJhYmIiLCAiYmJhYSIsICJiYmFiIiwgImJiYmEiLCAiYmJiYiI).
### How it works
```
Ṣ=Ṛ¬Pȧ Main link. Argument: s (string)
Ṣ Yield s, sorted.
Ṛ Yield s, reversed.
= Compare each character of sorted s with each character of reversed s.
¬ Take the logical NOT of each resulting Boolean.
P Take the product of the resulting Booleans.
This will yield 1 if s ∊ L or s == "", and 0 otherwise.
ȧ Take the logical AND with s.
This will replace 1 with s. Since an empty string is falsy in Jelly,
the result is still correct if s == "".
```
## Alternate version, 4 bytes (non-competing)
```
ṢnṚȦ
```
Prints **1** or **0**. [Try it online!](http://jelly.tryitonline.net/#code=4bmibuG5msim&input=&args=) or [verify all test cases](http://jelly.tryitonline.net/#code=4bmibuG5msimCsOH4oKsRw&input=&args=ImFiIiwgImFhYmIiLCAiYWFhYmJiIiwgImFhYWFiYmJiIiwgImFhYWFhYmJiYmIiLCAiYWFhYWFhYmJiYmJiIiwgIiIsICJhIiwgImIiLCAiYWEiLCAiYmEiLCAiYmIiLCAiYWFhIiwgImFhYiIsICJhYmEiLCAiYWJiIiwgImJhYSIsICJiYWIiLCAiYmJhIiwgImJiYiIsICJhYWFhIiwgImFhYWIiLCAiYWFiYSIsICJhYmFhIiwgImFiYWIiLCAiYWJiYSIsICJhYmJiIiwgImJhYWEiLCAiYmFhYiIsICJiYWJhIiwgImJhYmIiLCAiYmJhYSIsICJiYmFiIiwgImJiYmEiLCAiYmJiYiI).
### How it works
```
ṢnṚȦ Main link. Argument: s (string)
Ṣ Yield s, sorted.
Ṛ Yield s, reversed.
n Compare each character of the results, returning 1 iff they're not equal.
Ȧ All (Octave-style truthy); return 1 if the list is non-empty and all numbers
are non-zero, 0 in all other cases.
```
[Answer]
# JavaScript, ~~54~~ ~~55~~ 44
```
s=>s&&s.match(`^a{${l=s.length/2}}b{${l}}$`)
```
Builds a simple regex based on the length of the string and tests it. For a length 4 string (`aabb`) the regex looks like: `^a{2}b{2}$`
Returns a truthy or falsey value.
11 bytes saved thanks to Neil.
```
f=s=>s&&s.match(`^a{${l=s.length/2}}b{${l}}$`)
// true
console.log(f('ab'), !!f('ab'))
console.log(f('aabb'), !!f('aabb'))
console.log(f('aaaaabbbbb'), !!f('aaaaabbbbb'))
// false
console.log(f('a'), !!f('a'))
console.log(f('b'), !!f('b'))
console.log(f('ba'), !!f('ba'))
console.log(f('aaab'), !!f('aaab'))
console.log(f('ababab'), !!f('ababab'))
console.log(f('c'), !!f('c'))
console.log(f('abc'), !!f('abc'))
console.log(f(''), !!f(''))
```
[Answer]
## Perl 5.10, ~~35~~ 17 bytes (with *-n* flag)
```
say/^(a(?1)?b)$/
```
Ensures that the string starts with `a`s and then recurses on `b`s. It matches only if both lengths are equal.
Thanks to [Martin Ender](https://codegolf.stackexchange.com/users/8478/martin-ender) for halving the byte count and teaching me a little about recursion in regexes :D
It returns the whole string if it matches, and nothing if not.
[Try it here!](http://ideone.com/jSHlcB)
[Answer]
## C, ~~57~~ 53 Bytes
```
t;x(char*s){t+=*s%2*2;return--t?*s&&x(s+1):*s*!1[s];}
```
Old 57 bytes long solution:
```
t;x(char*s){*s&1&&(t+=2);return--t?*s&&x(s+1):*s&&!1[s];}
```
Compiled with gcc v. 4.8.2 @Ubuntu
Thanks ugoren for tips!
[Try it on Ideone!](http://ideone.com/10U9t6)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~7~~ ~~6~~ ~~5~~ 4 bytes
```
I÷<g
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiZiIsIknDtzxnIiwiIiwiXCJhYlwiXG5cImFhYmJcIlxuXCJhYWFiYmJcIlxuXCJhYWFhYmJiYlwiXG5cImFhYWFhYmJiYmJcIlxuXCJhYWFhYWFiYmJiYmJcIlxuXCJcIlxuXCJhXCJcblwiYlwiXG5cImFhXCJcblwiYmFcIlxuXCJiYlwiXG5cImFhYVwiXG5cImFhYlwiXG5cImFiYVwiXG5cImFiYlwiXG5cImJhYVwiXG5cImJhYlwiXG5cImJiYVwiXG5cImJiYlwiXG5cImFhYWFcIlxuXCJhYWFiXCJcblwiYWFiYVwiXG5cImFiYWFcIlxuXCJhYmFiXCJcblwiYWJiYVwiXG5cImFiYmJcIlxuXCJiYWFhXCJcblwiYmFhYlwiXG5cImJhYmFcIlxuXCJiYWJiXCJcblwiYmJhYVwiXG5cImJiYWJcIlxuXCJiYmJhXCJcblwiYmJiYlwiIl0=)
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiScO3PGciLCIiLCJbXCJhXCIsXCJiXCJdXG5bXCJhXCIsXCJhXCIsXCJiXCIsXCJiXCJdXG5bXCJhXCIsXCJhXCIsXCJhXCIsXCJiXCIsXCJiXCIsXCJiXCJdXG5bXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCJdXG5bXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCJdXG5bXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCJdXG5bXVxuW1wiYVwiXVxuW1wiYlwiXVxuW1wiYVwiLFwiYVwiXVxuW1wiYlwiLFwiYVwiXVxuW1wiYlwiLFwiYlwiXVxuW1wiYVwiLFwiYVwiLFwiYVwiXVxuW1wiYVwiLFwiYVwiLFwiYlwiXVxuW1wiYVwiLFwiYlwiLFwiYVwiXVxuW1wiYVwiLFwiYlwiLFwiYlwiXVxuW1wiYlwiLFwiYVwiLFwiYVwiXVxuW1wiYlwiLFwiYVwiLFwiYlwiXVxuW1wiYlwiLFwiYlwiLFwiYVwiXVxuW1wiYlwiLFwiYlwiLFwiYlwiXVxuW1wiYVwiLFwiYVwiLFwiYVwiLFwiYVwiXVxuW1wiYVwiLFwiYVwiLFwiYVwiLFwiYlwiXVxuW1wiYVwiLFwiYVwiLFwiYlwiLFwiYVwiXVxuW1wiYVwiLFwiYlwiLFwiYVwiLFwiYVwiXVxuW1wiYVwiLFwiYlwiLFwiYVwiLFwiYlwiXVxuW1wiYVwiLFwiYlwiLFwiYlwiLFwiYVwiXVxuW1wiYVwiLFwiYlwiLFwiYlwiLFwiYlwiXVxuW1wiYlwiLFwiYVwiLFwiYVwiLFwiYVwiXVxuW1wiYlwiLFwiYVwiLFwiYVwiLFwiYlwiXVxuW1wiYlwiLFwiYVwiLFwiYlwiLFwiYVwiXVxuW1wiYlwiLFwiYVwiLFwiYlwiLFwiYlwiXVxuW1wiYlwiLFwiYlwiLFwiYVwiLFwiYVwiXVxuW1wiYlwiLFwiYlwiLFwiYVwiLFwiYlwiXVxuW1wiYlwiLFwiYlwiLFwiYlwiLFwiYVwiXVxuW1wiYlwiLFwiYlwiLFwiYlwiLFwiYlwiXSJd) - without the `f` header
Takes a list of characters as input. Outputs `1` for true for inputs in \$\{a^n b^n:n∈\mathbb{Z}^+\}\$, and empty string or `0` for false otherwise. This matches Vyxal's truthy/falsey semantics, which can be confirmed by putting `ḃ` (Boolify) in the Footer.
```
I # Into Two Pieces - Splits a list into two halves and wraps them in a list.
# If the input is odd in length, the left side gets 1 more character.
÷ # Item Split - Unwraps the list created above. Required so that the next
# operation can compare the two halves.
< # Less Than (vectorized) - Are items in the left half list less than the
# corresponding items in the right half list? Puts 1 where yes, 0 where no.
# The resulting list takes the size of whichever list was longer. For items
# at the end of that list with no corresponding item in the other list, it
# puts 0 if that position is empty in the right list, and 1 if it's empty in
# the left list (which can never happen in this program).
g # Minimum
```
---
Determining membership in \$\{a^n b^n:n∈\mathbb{Z}^0\}\$ can also be done in 4 bytes:
```
I÷<A
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiZiIsIknDtzxBIiwiIiwiXCJhYlwiXG5cImFhYmJcIlxuXCJhYWFiYmJcIlxuXCJhYWFhYmJiYlwiXG5cImFhYWFhYmJiYmJcIlxuXCJhYWFhYWFiYmJiYmJcIlxuXCJcIlxuXCJhXCJcblwiYlwiXG5cImFhXCJcblwiYmFcIlxuXCJiYlwiXG5cImFhYVwiXG5cImFhYlwiXG5cImFiYVwiXG5cImFiYlwiXG5cImJhYVwiXG5cImJhYlwiXG5cImJiYVwiXG5cImJiYlwiXG5cImFhYWFcIlxuXCJhYWFiXCJcblwiYWFiYVwiXG5cImFiYWFcIlxuXCJhYmFiXCJcblwiYWJiYVwiXG5cImFiYmJcIlxuXCJiYWFhXCJcblwiYmFhYlwiXG5cImJhYmFcIlxuXCJiYWJiXCJcblwiYmJhYVwiXG5cImJiYWJcIlxuXCJiYmJhXCJcblwiYmJiYlwiIl0=)
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiScO3PEEiLCIiLCJbXCJhXCIsXCJiXCJdXG5bXCJhXCIsXCJhXCIsXCJiXCIsXCJiXCJdXG5bXCJhXCIsXCJhXCIsXCJhXCIsXCJiXCIsXCJiXCIsXCJiXCJdXG5bXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCJdXG5bXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCJdXG5bXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCJdXG5bXVxuW1wiYVwiXVxuW1wiYlwiXVxuW1wiYVwiLFwiYVwiXVxuW1wiYlwiLFwiYVwiXVxuW1wiYlwiLFwiYlwiXVxuW1wiYVwiLFwiYVwiLFwiYVwiXVxuW1wiYVwiLFwiYVwiLFwiYlwiXVxuW1wiYVwiLFwiYlwiLFwiYVwiXVxuW1wiYVwiLFwiYlwiLFwiYlwiXVxuW1wiYlwiLFwiYVwiLFwiYVwiXVxuW1wiYlwiLFwiYVwiLFwiYlwiXVxuW1wiYlwiLFwiYlwiLFwiYVwiXVxuW1wiYlwiLFwiYlwiLFwiYlwiXVxuW1wiYVwiLFwiYVwiLFwiYVwiLFwiYVwiXVxuW1wiYVwiLFwiYVwiLFwiYVwiLFwiYlwiXVxuW1wiYVwiLFwiYVwiLFwiYlwiLFwiYVwiXVxuW1wiYVwiLFwiYlwiLFwiYVwiLFwiYVwiXVxuW1wiYVwiLFwiYlwiLFwiYVwiLFwiYlwiXVxuW1wiYVwiLFwiYlwiLFwiYlwiLFwiYVwiXVxuW1wiYVwiLFwiYlwiLFwiYlwiLFwiYlwiXVxuW1wiYlwiLFwiYVwiLFwiYVwiLFwiYVwiXVxuW1wiYlwiLFwiYVwiLFwiYVwiLFwiYlwiXVxuW1wiYlwiLFwiYVwiLFwiYlwiLFwiYVwiXVxuW1wiYlwiLFwiYVwiLFwiYlwiLFwiYlwiXVxuW1wiYlwiLFwiYlwiLFwiYVwiLFwiYVwiXVxuW1wiYlwiLFwiYlwiLFwiYVwiLFwiYlwiXVxuW1wiYlwiLFwiYlwiLFwiYlwiLFwiYVwiXVxuW1wiYlwiLFwiYlwiLFwiYlwiLFwiYlwiXSJd) - without the `f` header
Takes a list of characters as input. Outputs `1` for true and `0` for false. Only the last element of the program is different:
```
A # Check if all items in a list are truthy (returns truthy for an empty list)
```
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~6~~ ~~5~~ 4 bytes
```
sṘ꘍g
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiZjoiLCJz4bmY6piNZyIsIiIsIlwiYWJcIlxuXCJhYWJiXCJcblwiYWFhYmJiXCJcblwiYWFhYWJiYmJcIlxuXCJhYWFhYWJiYmJiXCJcblwiYWFhYWFhYmJiYmJiXCJcblwiXCJcblwiYVwiXG5cImJcIlxuXCJhYVwiXG5cImJhXCJcblwiYmJcIlxuXCJhYWFcIlxuXCJhYWJcIlxuXCJhYmFcIlxuXCJhYmJcIlxuXCJiYWFcIlxuXCJiYWJcIlxuXCJiYmFcIlxuXCJiYmJcIlxuXCJhYWFhXCJcblwiYWFhYlwiXG5cImFhYmFcIlxuXCJhYmFhXCJcblwiYWJhYlwiXG5cImFiYmFcIlxuXCJhYmJiXCJcblwiYmFhYVwiXG5cImJhYWJcIlxuXCJiYWJhXCJcblwiYmFiYlwiXG5cImJiYWFcIlxuXCJiYmFiXCJcblwiYmJiYVwiXG5cImJiYmJcIiJd)
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwic+G5mOqYjWciLCIiLCJbXCJhXCIsXCJiXCJdXG5bXCJhXCIsXCJhXCIsXCJiXCIsXCJiXCJdXG5bXCJhXCIsXCJhXCIsXCJhXCIsXCJiXCIsXCJiXCIsXCJiXCJdXG5bXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCJdXG5bXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCJdXG5bXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCJdXG5bXVxuW1wiYVwiXVxuW1wiYlwiXVxuW1wiYVwiLFwiYVwiXVxuW1wiYlwiLFwiYVwiXVxuW1wiYlwiLFwiYlwiXVxuW1wiYVwiLFwiYVwiLFwiYVwiXVxuW1wiYVwiLFwiYVwiLFwiYlwiXVxuW1wiYVwiLFwiYlwiLFwiYVwiXVxuW1wiYVwiLFwiYlwiLFwiYlwiXVxuW1wiYlwiLFwiYVwiLFwiYVwiXVxuW1wiYlwiLFwiYVwiLFwiYlwiXVxuW1wiYlwiLFwiYlwiLFwiYVwiXVxuW1wiYlwiLFwiYlwiLFwiYlwiXVxuW1wiYVwiLFwiYVwiLFwiYVwiLFwiYVwiXVxuW1wiYVwiLFwiYVwiLFwiYVwiLFwiYlwiXVxuW1wiYVwiLFwiYVwiLFwiYlwiLFwiYVwiXVxuW1wiYVwiLFwiYlwiLFwiYVwiLFwiYVwiXVxuW1wiYVwiLFwiYlwiLFwiYVwiLFwiYlwiXVxuW1wiYVwiLFwiYlwiLFwiYlwiLFwiYVwiXVxuW1wiYVwiLFwiYlwiLFwiYlwiLFwiYlwiXVxuW1wiYlwiLFwiYVwiLFwiYVwiLFwiYVwiXVxuW1wiYlwiLFwiYVwiLFwiYVwiLFwiYlwiXVxuW1wiYlwiLFwiYVwiLFwiYlwiLFwiYVwiXVxuW1wiYlwiLFwiYVwiLFwiYlwiLFwiYlwiXVxuW1wiYlwiLFwiYlwiLFwiYVwiLFwiYVwiXVxuW1wiYlwiLFwiYlwiLFwiYVwiLFwiYlwiXVxuW1wiYlwiLFwiYlwiLFwiYlwiLFwiYVwiXVxuW1wiYlwiLFwiYlwiLFwiYlwiLFwiYlwiXSJd) - without the `f:` header
Takes a list of characters as input. Outputs `1` for true for inputs in \$\{a^n b^n:n∈\mathbb{Z}^+\}\$, and empty string or `0` for false otherwise.
This is a port of [Dennis's MATL answer](https://codegolf.stackexchange.com/a/86037/17216), with an algorithm also used by many subsequent answers.
```
s # Pushes a copy of the input, sorted.
Ṙ # Reverses the sorted copy.
꘍ # Levenshtein distance (vectorized) - Used here to compare corresponding
# single-character strings between two lists, so it's effectively a vectorized
# Not Equals, giving 1 for unequal and 0 for equal. This works around the fact
# that Vyxal has no vectorizing Not Equals operator (even though it does have
# vectorizing versions of all the other basic comparison operators). For input
# in L, this will yield a non-empty list of all 1s. For an empty input it will
# yield an empty list. For all other inputs it yields a list of both 1s and 0s.
g # Minimum
```
To take a string as input, this becomes `f:sṘ꘍g` or alternatively `fṘḂs꘍g` (6 bytes). It is, however, possible to do this with the sort-and-reverse algorithm in 5 bytes (see `AḂs꘍↓` below).
---
Determining membership in \$\{a^n b^n:n∈\mathbb{Z}^0\}\$ can also be done in 4 bytes using this algorithm:
```
sṘ꘍A
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiZjoiLCJz4bmY6piNQSIsIiIsIlwiYWJcIlxuXCJhYWJiXCJcblwiYWFhYmJiXCJcblwiYWFhYWJiYmJcIlxuXCJhYWFhYWJiYmJiXCJcblwiYWFhYWFhYmJiYmJiXCJcblwiXCJcblwiYVwiXG5cImJcIlxuXCJhYVwiXG5cImJhXCJcblwiYmJcIlxuXCJhYWFcIlxuXCJhYWJcIlxuXCJhYmFcIlxuXCJhYmJcIlxuXCJiYWFcIlxuXCJiYWJcIlxuXCJiYmFcIlxuXCJiYmJcIlxuXCJhYWFhXCJcblwiYWFhYlwiXG5cImFhYmFcIlxuXCJhYmFhXCJcblwiYWJhYlwiXG5cImFiYmFcIlxuXCJhYmJiXCJcblwiYmFhYVwiXG5cImJhYWJcIlxuXCJiYWJhXCJcblwiYmFiYlwiXG5cImJiYWFcIlxuXCJiYmFiXCJcblwiYmJiYVwiXG5cImJiYmJcIiJd)
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwic+G5mOqYjUEiLCIiLCJbXCJhXCIsXCJiXCJdXG5bXCJhXCIsXCJhXCIsXCJiXCIsXCJiXCJdXG5bXCJhXCIsXCJhXCIsXCJhXCIsXCJiXCIsXCJiXCIsXCJiXCJdXG5bXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCJdXG5bXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCJdXG5bXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCJdXG5bXVxuW1wiYVwiXVxuW1wiYlwiXVxuW1wiYVwiLFwiYVwiXVxuW1wiYlwiLFwiYVwiXVxuW1wiYlwiLFwiYlwiXVxuW1wiYVwiLFwiYVwiLFwiYVwiXVxuW1wiYVwiLFwiYVwiLFwiYlwiXVxuW1wiYVwiLFwiYlwiLFwiYVwiXVxuW1wiYVwiLFwiYlwiLFwiYlwiXVxuW1wiYlwiLFwiYVwiLFwiYVwiXVxuW1wiYlwiLFwiYVwiLFwiYlwiXVxuW1wiYlwiLFwiYlwiLFwiYVwiXVxuW1wiYlwiLFwiYlwiLFwiYlwiXVxuW1wiYVwiLFwiYVwiLFwiYVwiLFwiYVwiXVxuW1wiYVwiLFwiYVwiLFwiYVwiLFwiYlwiXVxuW1wiYVwiLFwiYVwiLFwiYlwiLFwiYVwiXVxuW1wiYVwiLFwiYlwiLFwiYVwiLFwiYVwiXVxuW1wiYVwiLFwiYlwiLFwiYVwiLFwiYlwiXVxuW1wiYVwiLFwiYlwiLFwiYlwiLFwiYVwiXVxuW1wiYVwiLFwiYlwiLFwiYlwiLFwiYlwiXVxuW1wiYlwiLFwiYVwiLFwiYVwiLFwiYVwiXVxuW1wiYlwiLFwiYVwiLFwiYVwiLFwiYlwiXVxuW1wiYlwiLFwiYVwiLFwiYlwiLFwiYVwiXVxuW1wiYlwiLFwiYVwiLFwiYlwiLFwiYlwiXVxuW1wiYlwiLFwiYlwiLFwiYVwiLFwiYVwiXVxuW1wiYlwiLFwiYlwiLFwiYVwiLFwiYlwiXVxuW1wiYlwiLFwiYlwiLFwiYlwiLFwiYVwiXVxuW1wiYlwiLFwiYlwiLFwiYlwiLFwiYlwiXSJd) - without the `f:` header
Takes a list of characters as input. Outputs `1` for true and `0` for false.
To take a string as input, this becomes `f:sṘ꘍A` or alternatively `fṘḂs꘍A` (6 bytes). It is, however, possible to do this with the sort-and-reverse algorithm in 5 bytes (see `AḂs꘍A` below).
# [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes
```
fI÷<g
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiZknDtzxnIiwiIiwiXCJhYlwiXG5cImFhYmJcIlxuXCJhYWFiYmJcIlxuXCJhYWFhYmJiYlwiXG5cImFhYWFhYmJiYmJcIlxuXCJhYWFhYWFiYmJiYmJcIlxuXCJcIlxuXCJhXCJcblwiYlwiXG5cImFhXCJcblwiYmFcIlxuXCJiYlwiXG5cImFhYVwiXG5cImFhYlwiXG5cImFiYVwiXG5cImFiYlwiXG5cImJhYVwiXG5cImJhYlwiXG5cImJiYVwiXG5cImJiYlwiXG5cImFhYWFcIlxuXCJhYWFiXCJcblwiYWFiYVwiXG5cImFiYWFcIlxuXCJhYmFiXCJcblwiYWJiYVwiXG5cImFiYmJcIlxuXCJiYWFhXCJcblwiYmFhYlwiXG5cImJhYmFcIlxuXCJiYWJiXCJcblwiYmJhYVwiXG5cImJiYWJcIlxuXCJiYmJhXCJcblwiYmJiYlwiIl0=)
Takes a string as input. Outputs `1` for true for inputs in \$\{a^n b^n:n∈\mathbb{Z}^+\}\$, and empty string or `0` for false otherwise. This is just one of the above 4 byte programs with `f` inserted at the beginning.
---
Determining membership in \$\{a^n b^n:n∈\mathbb{Z}^0\}\$ can also be done in this way:
```
fI÷<A
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiZknDtzxBIiwiIiwiXCJhYlwiXG5cImFhYmJcIlxuXCJhYWFiYmJcIlxuXCJhYWFhYmJiYlwiXG5cImFhYWFhYmJiYmJcIlxuXCJhYWFhYWFiYmJiYmJcIlxuXCJcIlxuXCJhXCJcblwiYlwiXG5cImFhXCJcblwiYmFcIlxuXCJiYlwiXG5cImFhYVwiXG5cImFhYlwiXG5cImFiYVwiXG5cImFiYlwiXG5cImJhYVwiXG5cImJhYlwiXG5cImJiYVwiXG5cImJiYlwiXG5cImFhYWFcIlxuXCJhYWFiXCJcblwiYWFiYVwiXG5cImFiYWFcIlxuXCJhYmFiXCJcblwiYWJiYVwiXG5cImFiYmJcIlxuXCJiYWFhXCJcblwiYmFhYlwiXG5cImJhYmFcIlxuXCJiYWJiXCJcblwiYmJhYVwiXG5cImJiYWJcIlxuXCJiYmJhXCJcblwiYmJiYlwiIl0=)
Takes a string as input. Outputs `1` for true and `0` for false.
This too is just one of the above 4 byte programs with `f` inserted at the beginning – but it can also be done without `f`, using a conceptually similar algorithm:
```
½C÷‹⁼
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiwr1Dw7figLnigbwiLCIiLCJcImFiXCJcblwiYWFiYlwiXG5cImFhYWJiYlwiXG5cImFhYWFiYmJiXCJcblwiYWFhYWFiYmJiYlwiXG5cImFhYWFhYWJiYmJiYlwiXG5cIlwiXG5cImFcIlxuXCJiXCJcblwiYWFcIlxuXCJiYVwiXG5cImJiXCJcblwiYWFhXCJcblwiYWFiXCJcblwiYWJhXCJcblwiYWJiXCJcblwiYmFhXCJcblwiYmFiXCJcblwiYmJhXCJcblwiYmJiXCJcblwiYWFhYVwiXG5cImFhYWJcIlxuXCJhYWJhXCJcblwiYWJhYVwiXG5cImFiYWJcIlxuXCJhYmJhXCJcblwiYWJiYlwiXG5cImJhYWFcIlxuXCJiYWFiXCJcblwiYmFiYVwiXG5cImJhYmJcIlxuXCJiYmFhXCJcblwiYmJhYlwiXG5cImJiYmFcIlxuXCJiYmJiXCIiXQ==)
Takes a string as input. Outputs `1` for true and `0` for false.
```
½ # Split in half. If odd in length, the left side gets 1 more character. This
# creates a list containing two strings.
C # Convert characters to their ASCII values. This results in a list containing
# two lists of ASCII values.
÷ # Item Split - split the list into its elements on stack; in this case, these
# are the left and right halves, each of which is a list of ASCII values.
‹ # Decrement - iff the right half is all 'b' (ASCII 98), this will change it to
# all 'a' (ASCII 97)
⁼ # Are the two top items on the stack exactly equal? This gives a boolean value
# that's 1 for true (equal counts of 'a' and 'b') and 0 for false.
```
# [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes
```
AḂs꘍↓
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiQeG4gnPqmI3ihpMiLCIiLCJcImFiXCJcblwiYWFiYlwiXG5cImFhYWJiYlwiXG5cImFhYWFiYmJiXCJcblwiYWFhYWFiYmJiYlwiXG5cImFhYWFhYWJiYmJiYlwiXG5cIlwiXG5cImFcIlxuXCJiXCJcblwiYWFcIlxuXCJiYVwiXG5cImJiXCJcblwiYWFhXCJcblwiYWFiXCJcblwiYWJhXCJcblwiYWJiXCJcblwiYmFhXCJcblwiYmFiXCJcblwiYmJhXCJcblwiYmJiXCJcblwiYWFhYVwiXG5cImFhYWJcIlxuXCJhYWJhXCJcblwiYWJhYVwiXG5cImFiYWJcIlxuXCJhYmJhXCJcblwiYWJiYlwiXG5cImJhYWFcIlxuXCJiYWFiXCJcblwiYmFiYVwiXG5cImJhYmJcIlxuXCJiYmFhXCJcblwiYmJhYlwiXG5cImJiYmFcIlxuXCJiYmJiXCIiXQ==)
Takes a string as input. Outputs `1` for true, and empty string or `0` for false.
This is an adaptation of the algorithm used in [Dennis's Jelly answer](https://codegolf.stackexchange.com/a/86034/17216) and [MATL answer](https://codegolf.stackexchange.com/a/86037/17216) (and many subsequent answers):
```
A # Check if character is a vowel (vectorized)
# Converts each 'a' to 1, and each 'b' to 0. Pushes the result as a list if
# the input was a string of 2 characters or longer, but only pushes a single
# integer if it was a single-character string. This limits what useful
# operations can subsequently be done (for example, it can't be reliably
# split into two halves).
Ḃ # Bifurcate - Pushes the top of the stack then its reverse.
s # Sort - Operates on the non-reversed copy.
꘍ # Bitwise Xor (vectorized)
↓ # Minimum by tail. On a list of numbers, it picks the item with the minimum
# last digit. On a single number, it picks the minimum digit. Since the only
# numbers given to it here will be 0 and 1, that's the same as the standard
# minimum, except that it avoids the crash that happens with "g" (Minimum)
# when its argument is not a list.
```
It appears to be impossible to solve this challenge in Vyxal in less than 5 bytes taking a string as input.
---
Determining membership in \$\{a^n b^n:n∈\mathbb{Z}^0\}\$ can also be done in this way:
```
AḂs꘍A
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiQeG4gnPqmI1BIiwiIiwiXCJhYlwiXG5cImFhYmJcIlxuXCJhYWFiYmJcIlxuXCJhYWFhYmJiYlwiXG5cImFhYWFhYmJiYmJcIlxuXCJhYWFhYWFiYmJiYmJcIlxuXCJcIlxuXCJhXCJcblwiYlwiXG5cImFhXCJcblwiYmFcIlxuXCJiYlwiXG5cImFhYVwiXG5cImFhYlwiXG5cImFiYVwiXG5cImFiYlwiXG5cImJhYVwiXG5cImJhYlwiXG5cImJiYVwiXG5cImJiYlwiXG5cImFhYWFcIlxuXCJhYWFiXCJcblwiYWFiYVwiXG5cImFiYWFcIlxuXCJhYmFiXCJcblwiYWJiYVwiXG5cImFiYmJcIlxuXCJiYWFhXCJcblwiYmFhYlwiXG5cImJhYmFcIlxuXCJiYWJiXCJcblwiYmJhYVwiXG5cImJiYWJcIlxuXCJiYmJhXCJcblwiYmJiYlwiIl0=)
Takes a string as input. Outputs `1` for true and `0` for false. Only the last element of the program is different:
```
A # Check if all items in a list are truthy (returns truthy for an empty list)
```
[Answer]
The purpose of this post is to demonstrate and explain the full list of golfed pure regexes that solve this challenge, and the range of compatibility of each among seven different regex engines, and rank them by length, all together in one post. Others' answers used the best regexes before this post; they are listed below. I ported the **Java** one to three other sets of regex engines, including Python 3's `regex` library.
# Regex (Perl / PCRE / Boost / Python[`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/)), 11 bytes
```
^(a(?1)?b)$
```
[Try it online!](https://tio.run/##TYxBa8MwDIXv/hWiGGJDR5rDLnHTUOh27KnHUWONFAJe2zntYYT0r2eSXNjASM9673vXLsXX@esHdHIwxstniKBLR99mvdsetptJnS7J6L5ZufXG0a7sCP2JLna8pv58g8XHeeEm0BEaGO443Cjuly/VsrLdN5vQ/ruvyLFQg/ZOAeQGYxh@QKlTadvikO5dDVDUxXuIA8nC/mV1dDB5/7bfeT8fTTBtZVu0ep4DqhCQB01ZvLMQ9ZRZo1JB8UUhPbEYV4G@3ILi0BY7o1LNKY4EGQxkQhBmGOIISo305KLchL8 "Perl 5 – Try It Online") - Perl
[Try it online!](https://tio.run/##fVJRT9swEH7Przi6MWwWULtKe2ha0IZAe2AwVUzaBCxy0ksaLU0sx1lHUf/6ujs7ZYWHRZF9vvu@785fkmp9lKfp5lVRpWU7Qxjr1ODx/CRI58pArG/vYQLT3sfl8mcybL8/PHy7mb9fzsXmh1DidCBPE/l6I1@WeyEc6kms3w6i4J90Y2dFzdq7KVNU@fNcUVMW1eIkKCoLmgA2RmNqI9K6aiy4yQ4X2DQqR/lIqqNRSgAYj6HLcujyWM3KCAza1lQwiNZOcqGKSkh4DIAefUvdSqyElkeD@0k/gpYww3exhZpPTMgpcGCn6Wemgm5tBOwXHBqMYHc6Gkdb49kGm7a0PuZ7ZFmDNoS6tdQ2t3NfqX9hamtzO7z3rUh14sTjtF7ookShQ@iH8MZL@2Cr1ZeeVGQg9gzK7Y0z514maG5Ch9D7cjY9d0MYUNTT0WF/NoL95q6ir7aj6ft0whkRBI@5Yk@cDTnasqhQeP@LKvSOyIgwg62726FWEqjG3oiDu@qgU/X3ZHe2d8XfmAqDIVx9vbzsFI/TmCwXcntsihXyqe/ezrcQhjui3LITHpM5O8O8qO5NgC2Jz6fT62l8df35w83ZJwmdbb1zdmoEPboUlg0@5S8UnVz@SXj9HHFjWgI8Q2RLU1gU/73TIGRza7bR8dbefYNIE8unP7n7pYL1RiWBUgkvtLqNdx@4qAt9nASBCjgTJPS6EtMDRUdWSVyFdlf2VCfNKIYotzDBMxyFOUxiSOJknI4X8krJnzQrVd5sjkr@zn8B "C++ (gcc) – Try It Online") - PCRE1
[Try it online!](https://tio.run/##XZDNboMwEITvPIVrWYpdkR@ucRGXkipSlVQ0t9JaNjIByRBkyKnqs9Nd01Ml7B3vznwYhmaYn7KhGQjzJCV0S8mGDN5elbeD05Xlq@3mMVOq0W5S1a0bWmd9yUshy2I7rmKyglVDU10tGvrJ9tPIlTocX3OlREwSAUgAy6i@ec7adCeZS2uwj/z98nw8CSm@SVtz5j7GyTvbgxLr5DNNadlTAebxbmAC7XgXrxMhg7sVtmpuaJEEqImMCGFdGi7f6alqOPMxkCRB3/JRTo@Tst7DRcRD@lbkL@p0VnlRnIuM5tjfE7rnrMvoxd/tnsCJHrQbQVKBbwgsyhyVP/9@Chdy/uKaZ4nIjGDzrE2ktcEN9lCwLiKoP7loE0U6wk5k4AkjjEcajkgxYQI1jJdoQKMLLTpsGFgSIYIZDKHFBEzgLKCFZH4B "PHP – Try It Online") - PCRE2
[Try it online!](https://tio.run/##XVDbbpwwEH33V4xopNgtuy2N1AfoZqU@9AOqPLRKUmQ7BqywxjJGNFvl10s8Q65FaDzjM@fM8WjvN63WyzvrdD/dGPiqhmGMH4NpzZ9t5/05050MUPvLa9jBj@zbPN@qs@nX3d3Pi@7L3PHlN5d8X4i9EieL@B/Ocnjvd7X/UFTsZYZNI4KRh3NmXYSDtI4L@Msgff4yQb1x3ItNcb37VMGUes4@1xEGrJDQpoSax3hTlqnfujYBfooV6MGNEegRZUmvgGC4z99claXVcjSierodDzLqDuZOxlW5GQJwnHXEoTSnNbG3znAqtHX5OjKJHHfFk338bAP8KCBhuDp@euVORfWM@uQ2Nvy1nXo0MuiOk15OLvLkWsAesoswmRIggxKy77IfU5G9UmvmYKNZmVtdp11w8WhsO9qjwarI8QEDWiXePcVg4hQcpE3eL1IxKRWGFOnAc00oe0zXXDEmGd4wlX6CkM5kKlFFEZJOglcqSWMXtkgKSFgZREEOkrBFkQzprEKrkvqnm16247LpaX01be8B "C++ (gcc) – Try It Online") - Boost
[Try it online!](https://tio.run/##bY5BagMxDEX3PoUwhdiQDhm6czHZ9QTdTVuQG6cxuJ5B49Dm9FNLzrJgpC/p/4eXW73M5WlL38tMFdbbuqf4FX8VgQfSWm8fBs1xtMdgH7Y2T6N7HN@fIfmDOs8EGVLh2LDWUypOAaQzJAcLpVKN5dmPfZtjMdkClhPkqUG8372VnYPs83RgarPdSfO1Dj@UajT6la7RAWgmyNeGNSJ9XgztodFiXiPoF2zNgbb/IbLdMCjEwKVVady7EHWXXQelUPFGhfbkxHGFbWRKkEvrcu5RQbOLLSiFAz0hEc5wiC1BMMLpoE4Kfw "Python 3 – Try It Online") - Python `import regex`
Included for completeness. Already used in:
* [Martin Ender's Mathematica answer](https://codegolf.stackexchange.com/a/86104/17216)
* [Titus's PHP answer](https://codegolf.stackexchange.com/a/86365/17216)
* [Paul Picard's Perl answer](https://codegolf.stackexchange.com/a/86006/17216)
```
^ # Assert we're at the beginning of the string.
( # Define subroutine (?1):
a # Match one 'a'.
(?1)? # Optionally do a recursive subroutine call to (?1).
b # Match one 'b'.
)
$ # Assert we're at the end of the string.
```
When the regex engine hits the `(?1)?`, it has the choice of whether to do the call or not. Due to `?` being greedy by default, it first tries doing the call; if it then hits a `b` character instead of an `a`, it will backtrack, avoid doing the subroutine call, and then reach the part of the regex that matches a `b` character.
From that point forward, it will keep popping out of the recursive call stack, matching another `b` each time. This way, the number of times that it attempts to match `b` equals the number of `a` it matched at the beginning.
If it finds an `a` when attempting to match `b`, this will trigger a non-match. If it finishes popping and still finds more `b` characters, this will trigger a non-match at the `$` part of the regex. If it reaches the end of the string prematurely during this stage, it will pop out from that call and attempt to match another `b`, thus triggering a non-match.
The only backtracking left to be tried at the popping-out stage, in the case of any of those non-matches, is to stop calling `(?1)` at an earlier point, but this will also fail to match, as it will then be trying to match `a` where the string has a `b`; this will result in a top-level non-match.
# Regex (PCRE / Ruby), 12 bytes
```
^(a\g<1>?b)$
```
[Try it online!](https://tio.run/##fVJRb9MwEH7Pr7gVxpyRTS2VeGjaIZiGeBgbqoYE2kbkuJc0Ik0sx6FsU/865c5OS7sHosg@333fd@cvUVqf5EqtXxSVKtsZwlgrg6fzs0DNpYFE397DBKa9D8vlz3TYfn94@HYzf7uci/UPIe/y8eDsXRq@XIfP670IjvUk0a8HcfBPu7Gzombx3ZQpqnw/V9SURbk4C4rKgiaATdCY2ghVV40FN9rxAptG5hg@kepopAgA4zF0WQ5dHqtZGYNB25oKBvHKSS5kUYkQngKgR99StxIrocOTwf2kH0NLmOGbxELNJybkFDiw0/QzU0G3NgY2DI4NxrA7HY2jrfFsg01bWh/zPbKsQRtB3Vpqm9u5r9S/UNna3A7vfStSnTjxRNULXZQodAT9CF55aR9stPqhJxUZiAOD4ebGmXMvEzQ3oSPofTmfXrghDEjq6ehwOBvBYXNX0Vfb0fR9OuGMCILHfGRPnA052rKoUHj/iyryjoQxYQYbdzdDPYZANfZGHN1VR52qvye7s7kr/kYlDEZw9fXyslM8VQlZLsLNsSkekU9993a@RTDcEeWWnfCYzNkZ5ln1YAJsSXIxnV5Pk6vrz@9vzj@F0NnWu2CnRtCjS2HZ4Db/UdLJ5bfCq33EjWkJsIfIlqawKP57p0HE5tZso@OtvPsGkSYOt39y90sFq7VMAylTXmh1G@8@cFEX@jgNAhlwJkjpdSWmB5KOrJK6Cu2u7KlOmlEMkW5hgmc4CnOYxJDUyTgdL@SV0j8qK2XerE9K/s5/AQ "C++ (gcc) – Try It Online") - PCRE1
[Try it online!](https://tio.run/##XZDNboMwEITvPIVrWYpdkR@ucSiXkipSlVQ0t9JaNjIBySHIkFPVZ6e7pqdK2Dvenfkw9E0/7bK@6QnzJCV0TcmK9N5elLe905Xli/XqMVOq0W5U1e3at876kpdClsV6WMRkAauGprpYNHSj7caBK7U/vOZKiZgkApAAllF985y16UYyl9ZgH/j7@flwFFJ8k7bmzH0Mo3e2AyWWyWea0rKjAszD3cAE2vEmXiZCBncrbNXc0CIJUBMZEcKuabj8VY9Vw5mPgSQJ@uaPcnoYlfUeLiIe0rcif1HHk8qL4lRkNMf@ltAtZ9eMnv3dbgmc6F67ASQV@IbAosxR@fPvp3Ahpy@uy8suecqMYNOkTaS1wQ32ULDOIqg/OWsTRTrCTmTgCSOMRxqOSDFhAjWM52hAowstOmwYmBMhghkMocUETODMoJlkfgE "PHP – Try It Online") - PCRE2
**[Try it online!](https://tio.run/##RYzBasMwEETv@oqpyKE9xMQ9RlVDIO0xh5JbkhotUV2BMEa2SXPJr7vaVaEgdmc18yZNdJsTLD5863/6qvNX7LaHbZW8uxgEuzK4fofoEW3rx0EB4Qvhgf/7aRwMfCe52rARj8v6bK0@ddpkIh5XVbV8Pksqo30K3YgIe0fCBvqQJr8GNNbQ7y4O@dD/sUI1zdt@1zTz56M7tS/164aeFvPsSDlHPPKUxbsIUX@yaFLKKf5RlJ9YjCuXT24hcfIWu6BSzSmOOBkMFEIQZhjiCEmN9JSi0kS/ "Ruby – Try It Online") - Ruby**
Included for completeness. Already used in [G B's Ruby answer](https://codegolf.stackexchange.com/a/182021/17216).
This is the same as the 11 byte version, but using Ruby's subroutine call syntax.
# Regex (Perl / PCRE / Java), 21 bytes
```
^(a(?=a*(\2?+b)))+\2$
```
[Try it online!](https://tio.run/##TYxBi8IwEIXv@RWDBJqsLrXCXhprEVyPnjyWDZOlQiGrbqoHKfWvd2eShV0IMy/z3veubfBv09cDZDAw@MsnepC5oW@13m2P280oTpegZFctzXpjaBd6gO5EFz1cQ3e@waw5z8wI0kMF/d31N4rbxWuxKHT7zSbU/@5LcjSUIK0RAKlBKYafkMuQ6zo7hntbAmRltkffk8z0X1Z6A6O174edtdOHQlVX@KKaVT13Wut5s5LThE4gOh404@KdRFS/MmknBAq@CEcvWowLpC@3uOjQjnZCYzWnOIJxMJCIiDDDEEdcrIk9qSg1uR8 "Perl 5 – Try It Online") - Perl
[Try it online!](https://tio.run/##fVJRT9swEH7Przi6MewSUEulPTQtaEOgPTCYqk7aRFnkuE4aLU0sx1kHqH993Z2ddoWHRZF9vvu@785fIrU@yaTcvMlLWTRzBSMtjTpdnAdyIQzE@v4BxjDpfFytfiaD5vvj47fp4v1qwTY/mGAXY9Fls7OL44Rzfjw7e7vhr4GdELp6HOvjfhT8a1LbeV5Rl/2UycvsZS6vMKvE8jzISwsaATZWxlSGyaqsLbgZu0tV1yJT/BlVh0OJABiNoM1S6PKqnBcRGGUbU0I/WjvJpchLxuE5AHz0PXYrVMk0P@k/jHsRNIgZnMUWKjoRIcPAgZ2mnxkLurERkHPQNSqC/elwHG2NZxtVN4X1Md0jTWtlQ6gai20zu/CV6peStjL3gwffClXHTjyW1VLnhWI6hF4I77y0D7ZaPe5JeQrswCi@vXHq3EsZzo3oEDpfLidXbggDAns6OhzOh3BYz0r8anuavk8rnCKB0ZhP5ImzIVO2yEvFvP95GXpHeISY/tbd7VBPHLBG3rCjWXnUqvp7kjvbu6rfSjKjQrj9enPTKp7KGC1nfHus8ydFp557W99CGOyJUstWeITm7A3zqnowBrIkvppM7ibx7d3nD9PLTxxa2zpX5NQQOngpVdRql78WeHL5nfD6JWJqGgS8QKQrk1vF/nunfkjmVmSj4629@0YpnJjv/uT2lwrWG5EEQiS04Oo22n3gojb0cRIEIqBMkODrSkQPBB5JJXEV3F3ZU500oQgi3EIEz3AU4hCJIImTcTpeyCslf2RaiKzenBT0nf8C "C++ (gcc) – Try It Online") - PCRE1
[Try it online!](https://tio.run/##XZBRb4MgFIXf/RWMkBRa284@lhFfZpcmS7u4vs2NgMFqgtagfVr2290F97REuId7z/lE@7qfntK@7hFxSCC8xWiDemeu0pneqtLQxXazTKWslR1leWv7xhpX0ILxIt8OixgtYFXQlFfjDd1ounGgUh6Or5mULEYJAySAeVTdHCWNeOTEigrsA32/PB9PjLNv1FSU2I9hdNZ0oNg6@RQCFx1mYB7uGibQjh/jdcJ4cDfMlPXNWzgCasIjhEgrwuVbNZY1JS4GEkfeN3@UVcMojXNwEfYg3vLsRZ7OMsvzc57izPf3CO8paVN8cXezR3DCB2UHkJj5NwQWJhbzn38/hTI@fVFFU6GWtNilK80YWxU7Mk1KR0ppv8Eeiq@zCOpPzlpHkYp8J9LwhJGPRwqOnqLDBGoYz9GA9i5vUWHzgTkRIj7jQ96iAyZwZtBM0r8 "PHP – Try It Online") - PCRE2
**[Try it online!](https://tio.run/##bZHfb9MwEMff81fcIqTZLWRjj4usSkjsCRCivFEm2YnTukucYDtrUZW/vdzZAW2oUmTfr@/nfJe9fJbv9vXT2XRD7wLs0S9MXyxKeBkZg2kvxpze6iNlhlG1poKqld7DZ2ksnOaQDzLg9dybGjpMsHVwxm5Buq3/8ZND2Ln@4OHjsdJDMD0KM4AH02pohNWHaLK8qPpaF5jPeflhbBrtdP1Ny1o7ULHsdZD9Vc5uw3k59/VvQ3nYEZ8xLxSOIOtPxmrG@ZWwY9ty0zBf6F@jbD3LbxaLRc756XVpIjAWLgJOSAj/CAi4QYLCuqfSL8X1xl7THcopxaavMgTtLDgxWzhtN1ADz0vcxrqS1uKkxg5jAAE03Bxj698@6K4wluPvsQGMuC1hni/WFzvpv@hjwOfBCfBl5krc8lnWY37AtYTWMgKI99QPO6ZdtdgsQSwS5tHx94Zqh8/pMOuKLnmsxcz/1IZ1RWNszTisIP/uRn0PkMM95A@4GnTyCyIiTdOU0ebPj0yylZALtrlbLRXnfLm5e3OmlZ6lyqRUdOAZL7qTEa3ZTLbKMplRJFP4xRTJM4kuUVTM4B3TSRrRVEUlMh4kSIooIQ2JqERFTOQkUCKpPw "Java (JDK) – Try It Online") - Java**
Turned out to be used in [Kevin Cruijssen's Java answer](https://codegolf.stackexchange.com/a/86061/17216), but gave it a -6 byte golf.
This regex is the next-best thing to recursion, in engines that lack it. It works using group-building:
```
^ # Assert we're at the beginning of the string.
(
a # Match one more 'a' per each iteration of this loop.
# Lookahead assertion - when this finishes, the regex engine's "cursor"
# will jump back to the same position as it was in when it entered the
# lookahead here. It's atomic, so the regex engine can't backtrack into
# the lookahead once it has completed its match or non-match. This means
# the main loop will exit immediately if this lookahead fails to match
# (due to running out of 'b' characters to match), or if the 'a' above
# fails to match.
(?=
a* # Skip over as many 'a' as necessary to get to the first 'b'.
# Capture \2, embedding within it the previous contents of itself.
# If this is the first iteration, \2 will be unset, so capture a
# single 'b' in \2. Otherwise, append one more 'b' to the previous
# contents of \2.
(
\2?+ # Optionally match \2, but if it does match, lock that
# match in (don't backtrack to here and try not making the
# match, in the case that a non-match occurs after this
# point). This is guaranteed to fail to match if and only if
# we're on the first iteration, due to \2 being unset. On
# subsequent iterations, since \2 will have been captured
# starting at the first non-'a' character, and always starts
# its attempted match there, it will be guaranteed to match.
b # Match one 'b'.
)
)
)+
\2 # Match however many 'b' we captured in \2.
$ # Assert we're at the end of the string.
```
# Regex (.NET), 22 bytes
```
^(a)+(?<-1>b)+$(?(1)^)
```
[Try it online!](https://tio.run/##RY3BasMwEETv@gphBJJIXOqr3TSBQG@99VYaWKXrWqDKRnZwifG3u1qpUDA7s955o6GfMYwdOreJcHgP@IU/H3XtcVYnuV0U6J06PpXVs9E7oY6q0he9ydO@OPffg3X4WehG3A@PTdsHhGunhOPWc2H9cJv0Ylsl7nqZg52w7PpxWmO4av53Xvo@PuasR14IZVuuRHh4hena4RjLtOaLfAs3rLlcOboR4/4CUWu5ai5csW5gGIChEWcS0myS@7PZG8aA0R9m4pdOhDOIK7WYdImazhlN1ZSiCKRBQCYSQgxBFDGpJvXkotxkfgE "PowerShell – Try It Online")
Included for completeness. Already used in:
* [Leaky Nun's Retina answer](https://codegolf.stackexchange.com/a/86002/17216)
* [AdmBorkBork's PowerShell answer](https://codegolf.stackexchange.com/a/86011/17216)
* [Dion Williams's C# answer](https://codegolf.stackexchange.com/a/86300/17216) (with regex 7 bytes longer than it needs to be)
This regex uses the Balancing Groups feature of the .NET regex engine:
```
^ # Assert we're at the beginning of the string.
(a)+ # Match as many 'a' characters as we can, minimum of one, pushing
# each single-character capture onto the Group 1 capture stack.
(?<-1>b)+ # Pop the Group 1 capture stack as many times as we can, matching
# a single 'b' each time. This will stop looping when it hits a
# character other than 'b', or empties the Group 1 capture stack.
$ # Assert we're at the end of the string. If this fails to match
# (meaning there are more 'b' characters than 'a' characters), the
# regex engine will backtrack, but none of the choices it has will
# be able lead to a match, so there will be a top-level non-match.
(?(1)^) # If there are any remaining captures on the Group 1 stack (which
# means there were fewer 'b' characters than 'a' chracters), assert
# something which can never be true - that we're at the beginning
# of the string. Since the first thing the regex did was capture at
# least one 'a', the fact that we've reached this point means that
# was already done, so it's impossible for us to be at the beginning
# of the string. Thus this causes a non-match in the case that there
# are fewer 'b' than 'a'.
```
Some people use this regex in the form of `^(a)+(?<-1>b)+(?(1)^)$`, i.e. with the `$` at the end rather than the beginning, but I prefer `^(a)+(?<-1>b)+$(?(1)^)`, since it tries the slightly-less-complicated operation of `$` first, so in the case of a non-match, it will be ever so slightly more efficient. In theory.
The `^` in the `(?(1)^)` can be replaced with various other things that can't match, such as `(?(1).)` or `(?(1)c)`.
# Regex (Perl / PCRE / Java / .NET), 24 bytes
```
^(a(?=a*((?>\2?)b)))+\2$
```
[Try it online!](https://tio.run/##TYzNasMwEITveoolCKxtExwHcrFim0DaY085mgqpOGBQ8yMnh2LcV3d3pUILYne0M99cu@C38@cXyKBh9JcP60Hmmr7V7rA/7utJnC5Byb5a612taRc4Qn@iC47X0J/vsGjPCz2B9FDB8HDDneJmuSqWBXY3NqH5d1@Tg1CCNFoApAalGP6GXIYcm@wYHl0JkJXZq/UDyQz/stJrmIx5eTsYM78rq5rKPinV1O2mQYeIz@1GzrN1wlrHg2ZcvJOI6lcm7YSwgi/C0YsW48LSl1tcdGhHO6GxmlMcsXEwkIiIMMMQR1ysiT2pKDW5Hw "Perl 5 – Try It Online") - Perl
[Try it online!](https://tio.run/##fVJRT9swEH7Przi6MewSUEulPTQtaEOgPTCYqk7aRFnkuE4aLU0sx1kHqH993Z2ddoWHRZF9vvu@785fIrU@yaTcvMlLWTRzBSMtjTpdnAdyIQzE@v4BxjDpfFytfiaD5vvj47fp4v1qwTY/mGAXY9Fl7OJ8dnbBE8758ezs7Ya/xnZC6OpxrI/7UfCvT23neUWN9lMmL7OXubzCrBLL8yAvLWgE2FgZUxkmq7K24MbsLlVdi0zxZ1QdDiUCYDSCNkuhy6tyXkRglG1MCf1o7SSXIi8Zh@cA8NH32K1QJdP8pP8w7kXQIGZwFluo6ESEDAMHdpp@ZizoxkZA5kHXqAj2p8NxtDWebVTdFNbHdI80rZUNoWosts3swleqX0raytwPHnwrVB078VhWS50XiukQeiG889I@2Gr1uCflKbADo/j2xqlzL2U4N6JD6Hy5nFy5IQwI7OnocDgfwmE9K/Gr7Wn6Pq1wigRGYz6RJ86GTNkiLxXz/udl6B3hEWL6W3e3Qz1xwBp5w45m5VGr6u9J7mzvqn4ryYwK4fbrzU2reCpjtJzx7bHOnxSdeu5tfQthsCdKLVvhEZqzN8yr6sEYyJL4ajK5m8S3d58/TC8/cWht61yRU0Po4KVUUatd/lrgyeV3wuuXiKlpEPACka5MbhX77536IZlbkY2Ot/buG6VwYr77k9tfKlhvRBIIkdCCq9to94GL2tDHSRCIgDJBgq8rET0QeCSVxFVwd2VPddKEIohwCxE8w1GIQySCJE7G6Xghr5T8kWkhsnpzUtB3/gs "C++ (gcc) – Try It Online") - PCRE1
[Try it online!](https://tio.run/##XZBfb4MgFMXf@RSMkBQ6@8c@ljlfZpcmS7e4vs2NgMFqgtagfVr22d0F97REuId7z/mJ9nU/PaR93WPqcILJhuA17p25SGd6q0rDFpv1MpWyVnaU5bXtG2tcwQouinwzLCK8gFVBU16MN3Sj6caBSXk4vmRS8gjHHJAAFqi6OkabZCuoTSqwD@z9/HQ8ccG/cVMxaj@G0VnTgeKr@DNJSNERDubhpmEC7WgbrWIugrvhpqyv3iIwUGOBMKZtEi7fqrGsGXURkAT2vvmjrBpGaZyDi/C75C3PnuXpVWZ5/pqnJPP9PSZ7RtuUnN3N7DGcyEHZASTh/g2BRagl4uffT2FcTF9MsTRRS8bSx2KXcs05vy92dJqURkppv8Eeiq@zCOpPzlojpJDvIA1PGPk4UnD0FB0mUMN4jga0d3mLCpsPzIkQ8Rkf8hYdMIEzg2aS/gU "PHP – Try It Online") - PCRE2
[Try it online!](https://tio.run/##bZHfb9MwEMff81fcIqTZHWRjj4tMJST2BAhR3uiQ7MRp3SVOsJ21qMrf3t3ZYWKoUmTfr@/nfJedfJLvdvXjyXRD7wLs0C9MXyxK@DcyBtOejTm90QfKDKNqTQVVK72HL9JYOM4hH2TA66k3NXSYYKvgjN2AdBv/84FD2Lp@7@HTodJDMD0KM4B702pohNX7aLK8qPpaF5jPeflxbBrtdP1dy1o7ULHsdZD9Vc5uw3k59/VvQ7nfEp8xLxSOIOvPxmrG@YWwY9ty0zBf6N@jbD3LrxeLRc758XVpIjAWzgKOSAgvBARcI0Fh3WPpr8Tl2l7SHcopxaZvMgTtLDgxWzhtN1ADz0vcxqqS1uKkxg5jAAE03Bxjqz8@6K4wluPvsQGMuClhni/WF1vpv@pDwOfBEfBl5kLc8FnWY37AtYTWMgKI99QPO6ZdtdgsQSwS5tHx94Zqi8/pMOuKLnmsxcz/1IZ1RWNszTgsIf/hRn0HkMMd5Pe4GnTyMyIiTdOU0eZPv5hkSyEXjC0/rG@XXHHOr9a3b0601ZNUmZSKDjzjRXcyojWbyVZZJjOKZAq/mCJ5JtEliooZvGM6SSOaqqhExoMESRElpCERlaiIiZwESiT1DA "Java (JDK) – Try It Online") - Java
[Try it online!](https://tio.run/##RY1BS8QwEIXv@RWhBJqoK7rHltoFwZs3b67CZHdqAzEpaZfKlv72mkkEocx703nfy@BnDGOP1m4iNO8Bv/Dno6oczvJQbp8SZNvAjZTt03HfKq2Uuj3uxVYe7opn/z0Yi@dC1eLaPNSdDwinXgrLjePCuOEyqcV0UlzVMgcz4a7347TG8GP9v/Od8/E5axzyQkjTcSnC/StMpx7HWKYUX8q3cMGKlytHO2LcXyBqVa6KC1usG2gGoGnEmYQ0m@T@bPaaMWD0h@n4pRPhDOJKLTpdoqZzRlM1pSgCaRCQiYQQQxBFdKpJPbkoN@lf "PowerShell – Try It Online") - .NET
This is a port of the **21 byte** Perl/PCRE/**Java** regex, with `\3?+` changed to `(?>\3?)` to allow the regex to also work on .NET (which lacks possessive quantifiers).
# Regex (Perl / PCRE / Java / Ruby / Python[`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/)), 29 bytes
```
^(a(?=a*(?=(\3?+b))(\2)))+\2$
```
[Try it online!](https://tio.run/##TUzLasMwELzrK5YgsLZJcJzQixXHBNIee8rRVEjFAYOah5wcinF/3d2VCi2ImdHO49oG/zx9foEMGgZ/@bAeZK7pW20P@@N@N4rTJSjZVSu93WniAgfoTnTB4Rq68x1mzXmmR5AeKugfrr9T3CyWxaLA9sYm1P/uK3IQSpBGC4C0oBSXvyGXIcc6O4ZHWwJkZfZqfU8yw7@s9BpGY17eDsZM78qqurJPBKrZ1HOHqJo1Is6btZwm64S1joEwEnMSUf3KpJ0QVvBFOHrR4rqw9OUVFx3iaKdqnOYUR2wELqRGrHCHSxxxcSbupKG05H4A "Perl 5 – Try It Online") - Perl
[Try it online!](https://tio.run/##fVJRT9swEH7Przi6MewSUEulPTQtaEOgPTCYqk7aRFnkuE4aLU0sx1kHqH993Z2ddoWHRZF9vvu@785fIrU@yaTcvMlLWTRzBSMtjTpdnAdyIQzE@v4BxjDpfFytfiaD5vvj47fp4v1qwTY/mGAXY9HFhc0GF8cJ52x2xjk/np293fDXhE4IXT2O9XE/Cv41q@08r6jbfsrkZfYyl1eYVWJ5HuSlBY0AGytjKsNkVdYW3KzdpaprkSn@jKrDoUQAjEbQZil0eVXOiwiMso0poR@tneRS5CXj8BwAPvoeuxWqZJqf9B/GvQgaxAzOYgsVnYiQYeDATtPPjAXd2AjIQegaFcH@dDiOtsazjaqbwvqY7pGmtbIhVI3Ftpld@Er1S0lbmfvBg2@FqmMnHstqqfNCMR1CL4R3XtoHW60e96Q8BXZgFN/eOHXupQznRnQInS@Xkys3hAGBPR0dDudDOKxnJX61PU3fpxVOkcBozCfyxNmQKVvkpWLe/7wMvSM8Qkx/6@52qCcOWCNv2NGsPGpV/T3Jne1d1W8lmVEh3H69uWkVT2WMljO@Pdb5k6JTz72tbyEM9kSpZSs8QnP2hnlVPRgDWRJfTSZ3k/j27vOH6eUnDq1tnStyaggdvJQqarXLXws8ufxOeP0SMTUNAl4g0pXJrWL/vVM/JHMrstHx1t59oxROzHd/cvtLBeuNSAIhElpwdRvtPnBRG/o4CQIRUCZI8HUlogcCj6SSuAruruypTppQBBFuIYJnOApxiESQxMk4HS/klZI/Mi1EVm9OCvrOfwE "C++ (gcc) – Try It Online") - PCRE1
[Try it online!](https://tio.run/##XZDNbsIwEITveQrXsoQXwk/oDdfKpVAhVVCl3JrWsiNDkByInHCq@ux07fRUKV6Pd2e@OGnr9v6Ut3VLmCeS0DklM9J6e1Letk5Xlo/ms3GuVK1dr6pr056d9SUvQZTFvBulZITriE11ssFw6e2l77hSm@3rWilISQaIRLBIjlfP2VkuBHPyiPaOvx@etzsQ8E3OR87cR9d7Zy@oYJp9SknLCwU0dzeDE2yni3SagYjuM9iqvgaLIEjNREIIa2S8fKP7qubMp0gSJPiGj3K665X1Hi8CD/KtWL@o3V6ti2Jf5HQd@itCV5w1OT34m10RPNGNdh1KCuENkUWZo@Ln30/hIO5fXPNc6jEWXj7mEwPAyyUATMolu9@1SbQ2oWCNW9gHEdWfHLRJEp2ETmLwiaMQTzQeA8XECe5xPEQjOriCRccSAkMiRkImhILFREzkDKCBZH4B "PHP – Try It Online") - PCRE2
[Try it online!](https://tio.run/##bVHfb9MwEH7PX3GLkGankI3xtsiqhMSeACHKGwXJTpzWXeIE21mLqv7t3Z0dEEOVovv13fed77KTT/LNrnk8m34cXIAd5qUZyqKCfytTMN3FmtMbfSBknFRnaqg76T18ksbCcS75IAO6p8E00CPAVsEZuwHpNv77Dw5h64a9hw@HWo/BDEjMAB5Mp6EVVu9jyPKyHhpdIp7z6v3Uttrp5quWjXagYtvLIvvDnNOW82qe61@Har8lfca8ULiCbD4aqxnnV8JOXcdNy3ypf02y8yy/KYoi5/z4sjUpMBYuChxRIfxVQIEbVFDY91j5hbhe22vyoTql2umLDEE7C07MEW7bjzTA8wqvsaqltbipseMUQAAtN9fY6rcPui@N5fh7bAAjbiuY94v95Vb6z/oQ8HlwBHyZuRK3fKYNiI94ltBZRgLiLc3DielWHQ5LIhYV5tXx94Z6i8/pEXVlnzLWIfK/asv6sjW2YRyWkH9zk74HyOEe8gc8DSb5BRIpnU6njC5//skkWwpZoGHrd8uF4pyt7zjni/XdqzOd9ixVJqUigzY68imI0RymWGWZzKiSKfwiRPRMYkoqKiLoI5yoUZq6qEVGQ4TEiBTiEIlaVJSJOkkoKaln "Java (JDK) – Try It Online") - Java
[Try it online!](https://tio.run/##RYzBasMwEETv@oqtyMFqiEncW4QwgSTHHkpucWpWVE0FwhjZJumlv@5oV4GCmJ3Vzps42d85goEPd3X3vuzcDfa7066MDr80eLPWcPvxwUEwVzcOAsB/g3@h/34aBw2u49xG0yGcV5uLMbLppE5EOK/LclVdOJXQPvpuhADmDyLUIE9xclsACVuQRwxDWuR/LFNte3jft@38WWBRG3xNUjRv9dIqVTSVUmrZVIt5RisQLUlSHjSzYfe02VshUNCPsOnxiXCBaaUWy5c0@ZxRrqYURZCFgEwwQgxBFLFcwz25KDfZBw "Ruby – Try It Online") - Ruby
[Try it online!](https://tio.run/##bY5NagMxDIX3PoUwhdhNOuRn52Ky6wm6m2lBbpzE4HoGj0Ob008tOcuCkZ6k9z483ct1TIclfE9jLjDf5032F/8rMljIUsrlU6E6WnyuRQ2H49pprYa91no97J@W6uh35mX38QrBbsV5zBAhJAJ1czmFZARAOEMwMOWQitI0213bRp9U1IDpBLGvEGtXQ1oZiDb2W6JW24M03kr3k0PxSr7nmzcAkgj82W72mL@uKm@g0nycPcg3rM2A1P8hol7QCURHpVZu1Jtg9ZBNOyFQ0Ea4@vhEcYF1JIrjS@18blFGk4ssyIUCLcERylCILI4xzGmgRnJ/ "Python 3 – Try It Online") - Python `import regex`
This is a port of the **21 byte** Perl/PCRE/**Java** regex (see below) adding compatibility with engines that lack nested backreferences, but still have forward-declared backreferences and possessive quantifiers. This allows it to work in Python when using the `regex` library instead of `re`.
```
^ # Assert we're at the beginning of the string.
(
a # Match one 'a' per iteration of this loop.
(?=
a* # Skip over as many 'a' as necessary to get to the first 'b'.
(?=
# Capture \2. If this is the first iteration, \3 will be unset, so
# capture a single 'b' in \2. Otherwise, \2 = \3 concatenated with
# one more 'b'.
(
\3?+
b
)
)
# \3 = make a copy of \2, which was captured above
(
\2
)
)
)+
\2 # Match however many 'b' we captured in \2.
$ # Assert we're at the end of the string.
```
# Regex (Perl / PCRE / Java / Ruby / Python[`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/) / .NET), 32 bytes
```
^(a(?=a*(?=((?>\3?)b))(\2)))+\2$
```
[Try it online!](https://tio.run/##TUzLasMwELzrK5YgsLZJcZzSixXbBNIee8rRVEjFAYPyqJwcinF/3d2VCi2ImdHO49oF/zyfvkAGDaO/fFgPMtf0rbb73WFXT@J4CUr21Vpva01c4Aj9kS44XkN/vsGiPS/0BNJDBcPdDTeKm9VjsSqw@2QTmn/3NTkIJUijBUBaUIrL35DLkGOTHcK9KwGyMnu1fiCZ4V9Weg2TMS9ve2Pmd2VVU9kHAqWaun1q0CGqdoOIy3Yj59k6Ya1jIIzEnERUvzJpJ4QVfBGOXrS4Lix9ecVFhzjaqRqnOcURG4ELqREr3OESR1yciTtpKC25Hw "Perl 5 – Try It Online") - Perl
[Try it online!](https://tio.run/##fVJRT9swEH7Przi6MewSUEulPTQtaEOgPTCYqk7aRFnkuE4aLU0sx1kHqH993Z2ddoWHRZF9vvu@785fIrU@yaTcvMlLWTRzBSMtjTpdnAdyIQzE@v4BxjDpfFytfiaD5vvj47fp4v1qwTY/mGAXY9HFhbGL89nggiecs9kZ5/x4dvZ2w19zOiF09TjWx/0o@NevtvO8oob7KZOX2ctcXmFWieV5kJcWNAJsrIypDJNVWVtw43aXqq5Fpvgzqg6HEgEwGkGbpdDlVTkvIjDKNqaEfrR2kkuRl4zDcwD46HvsVqiSaX7Sfxj3ImgQMziLLVR0IkKGgQM7TT8zFnRjIyAToWtUBPvT4TjaGs82qm4K62O6R5rWyoZQNRbbZnbhK9UvJW1l7gcPvhWqjp14LKulzgvFdAi9EN55aR9stXrck/IU2IFRfHvj1LmXMpwb0SF0vlxOrtwQBgT2dHQ4nA/hsJ6V@NX2NH2fVjhFAqMxn8gTZ0OmbJGXinn/8zL0jvAIMf2tu9uhnjhgjbxhR7PyqFX19yR3tndVv5VkRoVw@/XmplU8lTFazvj2WOdPik4997a@hTDYE6WWrfAIzdkb5lX1YAxkSXw1mdxN4tu7zx@ml584tLZ1rsipIXTwUqqo1S5/LfDk8jvh9UvE1DQIeIFIVya3iv33Tv2QzK3IRsdbe/eNUjgx3/3J7S8VrDciCYRIaMHVbbT7wEVt6OMkCERAmSDB15WIHgg8kkriKri7sqc6aUIRRLiFCJ7hKMQhEkESJ@N0vJBXSv7ItBBZvTkp6Dv/BQ "C++ (gcc) – Try It Online") - PCRE1
[Try it online!](https://tio.run/##XZDNbsMgEITvPAVFSGFT57e3UNeXOlWkKqnc3OoWgUXiSDixsHOq@uzpgnuqZJZhd@Yzdlu3t8esrVvKPU0pmzE6pa23R@Vt63RlxWg2HWdK1dr1qro07clZX4oSZFnMulFCR7gO2FRHGwzn3p77Tii13rzmSkFCF4BIBEtyuHjBT@lccpce0N6J9/3zZgsSvunpILj76Hrv7BkVTBafacrKMwM0d1eDE2wn82SyABndJ7BVfQkWSZG6kIRS3qTx8o3uq1pwnyBJ0uAbPsrprlfWe7wI3KVvRf6itjuVF8WuyFge@ivKVoI3Gdv7q11RPLG1dh1KBuENkcW4Y/Ln308RIG9fQoss1WMsQmRP5UMGBkCUSwC4L5f8dtOGaG1CwRq3sA8iqj85aEOIJqFDDD5xFOJE4zFQTJzgHsdDNKKDK1h0LCEwJGIkZEIoWEzERM4AGkjmFw "PHP – Try It Online") - PCRE2
[Try it online!](https://tio.run/##bVHfb9MwEH7PX3GLkGZ3kI3tbVGohMSeACHKG2WSnTitO8cJtrMWVfnby50dEEOVovv13fed77ITz@LNrnk66W7oXYAd5oXui0UJ/1bGoM3ZmlMbdSBkGKXRNdRGeA@fhLZwnEs@iIDuudcNdAiwVXDabkC4jf/@g0PYun7v4cOhVkPQPRIzgAdtFLSVVfsYsryo@0YViOe8fD@2rXKq@apEoxzI2PayyP4w57TlvJzn@teh3G9JnzFfSVxBNB@1VYzzi8qOxnDdMl@on6MwnuXXi8Ui5/z4sjUpMBbOChxRIfxVQIFrVJDY91T6q@pybS/Jh3JKtemLCEE5C66aI9y2G2iA5yVeY1ULa3FTbYcxQAW03Fxjq18@qK7QluPvsQF0dVPCvF/sL7bCf1aHgM@DI@DL9EV1w2daj/iAZwnGMhKo3tI8nJhuZXBYErGoMK@OvzfUW3xOh6grupQxg8j/qi3rilbbhnFYQv7NjeoeIId7yB/wNJjkZ0ikNE1TRpc/PTLBlpVYoGFs@W59t@SSc7a@5ZxfrW9fnei6JyEzISQZtNGRT0GM5jDFMstERpVM4hchomcCU1KREUEf4USN0tRFLSIaIiRGpBCHSNQio0zUSUJJSf4G "Java (JDK) – Try It Online") - Java
[Try it online!](https://tio.run/##RYzBasMwEETv@oqt6EFqiEncW4RiAmmPPZTc4tSsqJoKhDGyTdpLf93VrgoFMTurnTdpdt9LAguv/uq/hqr3NzgeTocqeXw3EOzGwO0zRA/RXv00CoDwAeGO/od5Gg34nnNbQ4d4Xm8v1sq2lyYT8bypqnV94VRGhxT6CSLYH0jQgDyl2e8AJOxAPmMc8yL/Y4XquqeXY9ctbwpVY/Ehi1LNvn1stNNatbXWetXW98uCTiA6kqw8aBbD7s8W74RAQT/C5ccnwgXmlVocX/Lkc0G5mlIUQRYCCsEIMQRRxHEN95Si0uR@AQ "Ruby – Try It Online") - Ruby
[Try it online!](https://tio.run/##bY7BbsMgDIbvPIWFJhW2LmraGxPLbU@wW7JJsNIWiZEIqLY@fYZNj5OQ/dv@/08st3KZ42H138ucCuRb3iZ3dr8sgYbEOV8/hRGDNo@1CDG8TodBWinFtJdSPk37h7Waxl499x8v4PWOneYEAXxEVpfL0UfFAPwJvIIl@ViExFn3bRtcFEGCiUcIY4VovZniRkHQYdwhtdrupPlaup/kixP8PV2dAuBIoP922Zn0dRFpC5XmQnbA30xtCrj8DxHkaiwzxmKplRr2JkjdZdOWMcNww2x9dMI4M3VEiqVL7XRuUUKjCy2GCgZagiKYwRBaLGGI00CNZP8A "Python 3 – Try It Online") - Python `import regex`
[Try it online!](https://tio.run/##RU3RSsQwEHzPV4QSaFY90fOtpfZA8M033zyFzbm1gdiWtEflSr@9ZhNBCDOz2ZnZoZ/Jjy05tylfvXn6op/3ouho1od8@9Co6wqvAmhdPx4fajAA@rgHgOvjXm354SZ76r8H6@gzg1Jdqruy6T3hqdXKSdtJZbvhPMFiG60usMzeTrRr@3Fag/m@/J/lruvDWWc7kpnStpFa@dsXnE4tjaEMQC75qz9TIfNVkhspzM8YuMhXkMpl64ZGIBqGgJGYk4jqTyZthEDBP8KEF1ccFxhGbjFxEziuUzRWs4stGIEDKREjnOEQW0ysiT2pKDWZXw "PowerShell – Try It Online") - .NET
This is a port of the above, with `\3?+` changed to `(?>\3?)` to allow the regex to work on .NET (which lacks possessive quantifiers), so it can support 6 different regex engines at once.
It is not supported by Boost, which lacks both forward-declared and nested backreferences. It might not be possible for a single regex to work on all 7 engines.
[Answer]
# [Retina](https://github.com/mbuettner/retina), 22 bytes
Another shorter answer in the same language just came...
```
^(a)+(?<-1>b)+(?(1)c)$
```
[Try it online!](http://retina.tryitonline.net/#code=XihhKSsoPzwtMT5iKSsoPygxKWMpJA&input=YWFiYg)
This is a showcase of the balancing groups in regex, which is [explained fully by Martin Ender](https://stackoverflow.com/a/17004406/6211883).
As my explanation would not come close to half of it, I'll just link to it and not attempt to explain, as that would be detrimental to the glory of his explanation.
[Answer]
# Befunge-93, 67 bytes
```
0v@.< 0<@.!-$< >0\v
+>~:0`!#^_:"a" -#^_$ 1
~+1_^#!-"b" _ ^#`0: <
```
[Try it here!](http://www.quirkster.com/iano/js/befunge.html) Might explain how it works later. Might also try to golf it just a tad bit more, just for kicks.
[Answer]
## Mathematica, 45 bytes
```
#~StringMatchQ~RegularExpression@"(a(?1)?b)"&
```
Another recursive regex solution. This doesn't need anchors because `StringMatchQ` achors it implicitly, but unfortunately it just seems to do wrap the regex in `^(?:...)$` which means we can't use `(?R)` for the recursion, as that gets the anchors as well. Hence the seemingly useless group around the entire regex, so we can access only that part for the recursion.
[Answer]
# C, 69 bytes
69 bytes:
`#define f(s)strlen(s)==2*strcspn(s,"b")&strrchr(s,97)+1==strchr(s,98)`
For those unfamiliar:
* `strlen` determines the length of the string
* `strcspn` returns the first index in string where the other string is found
* `strchr` returns a pointer to the first occurrence of a character
* `strrchr` returns a pointer to the last occurrence of a character
A big thanks to Titus!
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata) + `-e`, 3 bytes
```
N;<
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFNtJJurpKOgpJuqlLsgqWlJWm6Fov9rG2WFCclF0P5C26-U0pMUuJSSkxMglBAGsoAsWBMMBvOgfBAXJAIEENkQAwwAVUIMRZEgoUhNiRB1YHZUOUwg6EOgOiDaEmEUhBjYOZADYKYBDEKoiEJagnUFpg1MHuSlCDeBgA)
```
N;<
N Check nonempty
; Split the list into two parts
< Check elementwise less than; fails if their lengths are different
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 9 bytes
```
vHI$e!d1=
```
[**Try it online!**](http://matl.tryitonline.net/#code=dkhJJGUhZDE9&input=J2FhYWJiYic)
The output array is truthy if it is non-empty and all its entries are nonzero. Otherwise it's falsy. Here are [some examples](http://matl.tryitonline.net/#code=YCAgICAgICAgICAgICUgaW5maW5pdGUgbG9vcCB0byB0YWtlIGFsbCBpbnB1dHMKPyd0cnV0aHknICAgICUgaWY6IHRydXRoeQp9J2ZhbHN5JyAgICAgJSBlbHNlOiBmYWxzeQpdICAgICAgICAgICAgJSBlbmQgaWYKRFQgICAgICAgICAgICUgZGlzcGxheSBhbmQgZW5kIGxvb3A&input=W10KWzAgMSAyXQpbMyA0IC01XQpbMSAxOyAxIDFd).
```
v % concatenate the stack. Since it's empty, pushes the empty array, []
H % push 2
I$ % specify three inputs for next function
e % reshape(input, [], 2): this takes the input implicitly and reshapes it in 2
% columns in column major order. If the input has odd length a zero is padded at
% the end. For input 'aaabbb' this gives the 2D char array ['ab;'ab';'ab']
! % transpose. This gives ['aaa;'bbb']
d % difference along each column
1= % test if all elements are 1. If so, that means the first tow contains 'a' and
% the second 'b'. Implicitly display
```
[Answer]
# x86 machine code, 29 27 bytes
Hexdump:
```
33 c0 40 41 80 79 ff 61 74 f8 48 41 80 79 fe 62
74 f8 0a 41 fe f7 d8 1b c0 40 c3
```
Assembly code:
```
xor eax, eax;
loop1:
inc eax;
inc ecx;
cmp byte ptr [ecx-1], 'a';
je loop1;
loop2:
dec eax;
inc ecx;
cmp byte ptr [ecx-2], 'b';
je loop2;
or al, [ecx-2];
neg eax;
sbb eax, eax;
inc eax;
done:
ret;
```
Iterates over the `a` bytes in the beginning, then over the following 'b' bytes. The first loop increases a counter, and the second loop decreases it. Afterwards, does a bitwise OR between the following conditions:
1. If the counter is not 0 at the end, the string doesn't match
2. If the byte that follows the sequence of `b`s is not 0, the string also doesn't match
Then, it has to "invert" the truth value in `eax` - set it to 0 if it was not 0, and vice versa. It turns out that the shortest code to do that is the following 5-byte code, which I stole from the output of my C++ compiler for `result = (result == 0)`:
```
neg eax; // negate eax; set C flag to 1 if it was nonzero
sbb eax, eax; // subtract eax and the C flag from eax
inc eax; // increase eax
```
[Answer]
# Ruby, 24 bytes
```
eval(gets.tr'ab','[]')*1
```
(This is just [xnor's brilliant idea](https://codegolf.stackexchange.com/a/86032/4372) in Ruby form. [My other answer](https://codegolf.stackexchange.com/a/86184/4372) is a solution I actually came up with myself.)
The program takes the input, transforms `a` and `b` to `[` and `]` respectively, and evaluates it.
Valid input will form a nested array, and nothing happens. An unbalanced expression will make the program crash. In Ruby empty input is evaluated as `nil`, which will crash because `nil` has not defined a `*` method.
[Answer]
# Sed, 38 + 2 = 40 bytes
```
s/.*/c&d/;:x;s/ca(.*)bd/c\1d/;tx;/cd/p
```
A non empty string output is truthy
Finite state automata can not do this, you say? What about finite state automata with *loops*. :P
Run with `r` and `n` flags.
### Explanation
```
s/.*/c&d/ #Wrap the input in 'c' and 'd' (used as markers)
:x #Define a label named 'x'
s/ca(.*)bd/c\1d/ #Deletes 'a's preceded by 'c's and equivalently for 'b's and 'd's. This shifts the markers to the center
tx #If the previous substitution was made, jump to label x
/cd/p #If the markers are next to one another, print the string
```
[Answer]
# JavaScript, ~~44~~ 42
[Crossed out 44 is still regular 44 ;(](http://meta.codegolf.stackexchange.com/a/7427/7796)
```
f=s=>(z=s.match`^a(.+)b$`)?f(z[1]):s=="ab"
```
Works by recursively stripping off the outer `a` and `b` and recursively using the inner value selected but `.+`. When there's no match on `^a.+b$` left, then the final result is whether the remaining string is the exact value `ab`.
**Test cases:**
```
console.log(["ab","aabb","aaabbb","aaaabbbb","aaaaabbbbb","aaaaaabbbbbb"].every(f) == true)
console.log(["","a","b","aa","ba","bb","aaa","aab","aba","abb","baa","bab","bba","bbb","aaaa","aaab","aaba","abaa","abab","abba","abbb","baaa","baab","baba","babb","bbaa","bbab","bbba","bbbb"].some(f) == false)
```
[Answer]
# ANTLR, 31 bytes
```
grammar A;r:'ab'|'a'r'b'|r'\n';
```
Uses the same concept as @dmckee's [YACC answer](https://codegolf.stackexchange.com/a/86049/56755), just slightly more golfed.
To test, follow the steps in ANTLR's [Getting Started tutorial](https://github.com/antlr/antlr4/blob/master/doc/getting-started.md). Then, put the above code into a file named `A.g4` and run these commands:
```
$ antlr A.g4
$ javac A*.java
```
Then test by giving input on STDIN to `grun A r` like so:
```
$ echo "aaabbb" | grun A r
```
If the input is valid, nothing will be output; if it is invalid, `grun` will give an error (either `token recognition error`, `extraneous input`, `mismatched input`, or `no viable alternative`).
Example usage:
```
$ echo "aabb" | grun A r
$ echo "abbb" | grun A r
line 1:2 mismatched input 'b' expecting {<EOF>, '
'}
```
[Answer]
## R, ~~64~~ ~~61~~ 55 bytes, ~~73~~ 67 bytes (robust) or 46 bytes (if empty strings are allowed)
1. Again, [xnor's answer](https://codegolf.stackexchange.com/a/86032/49439) reworked. If it is implied by the rules that the input will consist of a string of `a`s and `b`s, it should work: returns NULL if the expression is valid, throws and error or nothing otherwise.
```
if((y<-scan(,''))>'')eval(parse(t=chartr('ab','{}',y)))
```
2. If the input is not robust and may contain some garbage, e.g. `aa3bb`, then the following version should be considered (must return `TRUE` for true test cases, not NULL):
```
if(length(y<-scan(,'')))is.null(eval(parse(t=chartr("ab","{}",y))))
```
3. Finally, if empty strings are allowed, we can ignore the condition for non-empty input:
```
eval(parse(text=chartr("ab","{}",scan(,''))))
```
Again, NULL if success, anything else otherwise.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 11 bytes
```
©¬n eȦUg~Y
```
[Try it online!](https://ethproductions.github.io/japt/?v=2.0a0&code=qaxuIGXIplVnflk=&input=LW1SIFsKImFiIiwKImFhYmIiLAoiYWFhYmJiIiwKImFhYWFiYmJiIiwKImFhYWFhYmJiYmIiLAoiYWFhYWFhYmJiYmJiIiwKCiIiLAoiYSIsCiJiIiwKImFhIiwKImJhIiwKImJiIiwKImFhYSIsCiJhYWIiLAoiYWJhIiwKImFiYiIsCiJiYWEiLAoiYmFiIiwKImJiYSIsCiJiYmIiLAoiYWFhYSIsCiJhYWFiIiwKImFhYmEiLAoiYWJhYSIsCiJhYmFiIiwKImFiYmEiLAoiYWJiYiIsCiJiYWFhIiwKImJhYWIiLAoiYmFiYSIsCiJiYWJiIiwKImJiYWEiLAoiYmJhYiIsCiJiYmJhIiwKImJiYmIiLApd)
Gives either `true` or `false`, except that `""` gives `""` which is falsy in JS.
### Unpacked & How it works
```
U&&Uq n eXYZ{X!=Ug~Y
U&& The input string is not empty, and...
Uq n Convert to array of chars and sort
eXYZ{ Does every element satisfy...?
X!= The sorted char does not equal...
Ug~Y the char at the same position on the original string reversed
```
Adopted from [Dennis' MATL solution](https://codegolf.stackexchange.com/a/86037/78410).
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), ~~34~~ 33 bytes
```
-[].
-L:-append([97|M],`b`,L),-M.
```
[Try it online!](https://tio.run/##ZZDBCsMgEETv@YoeFdxcS9NDfyCB3ENApbYEJBGT4qX/bpuWgju9OW9dZ8YQF7/caU1TzjSMdUVtQyYEN1/FcDo@u1Fpq1UrFXV1TqKXDfUqxWlzfhZbfDh5/qmb8auTdXWhQxKkjdWFMJbLtwawE0Qf9ge/tMTljeLMN8sBE2DAY5eKrfFGFt5nM7DDQvAx3J9bGpA8HuaDgDwhj8iNLJSDdlgP@@3T/AI "Prolog (SWI) – Try It Online")
[Answer]
# [Brachylog (newer)](https://github.com/JCumin/Brachylog), ~~11~~ ~~10~~ 6 bytes
```
o?ḅĊlᵛ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRuX/2obcOjpuZHHcuVSopKU/WUakDMtMScYiC79uGuztqHWyf8z7d/uKP1SFfOw62z//@PVkpMUtJRSkxMglBAGsoAsWBMMBvOgfBAXJAIEENkQAwwAVUIMRZEgoUhNiRB1YHZUOUwg6EOgOiDaEmEUhBjYOZADYKYBDEKoiEJagnUFpg1MHuSlGIB "Brachylog – Try It Online")
The predicate succeeds if the input is in L and fails otherwise.
```
The input
o sorted
? is the input,
ḅ and the runs in the input
Ċ of which there are two
lᵛ have the same length.
```
] |
[Question]
[
Write a program which outputs the square root of a given number in the shortest time possible.
## Rules
It may not use any builtins or powering with non-integers.
# Input format
* as a function argument
* as a command line argument
* as a direct input on stdin or a window
Your entry hasn't to be a complete program, it may be a function or a snippet.
It doesn't need to be exact; a one percent margin of error is allowed.
The test cases will only be positive integers, but your program should output/return floats.
It may return the square root as function return value, print it to stdout or write in a consistent file, which is readable by the user..
Each program should specify the compiler/interpreter it should be run on and compiler flags. If they aren't specified, I'll use the following implementations: (just talking about mainstream langs):
* C/C++: gcc/g++ on Linux, no flags
* Java: OpenJDK on Linux, no flags
* Python: CPython
* Ruby: MRI
* Assembler: x86 Linux
* JS: Node.js
## Examples
```
Input Output
4 2 (or something between 1.98 and 2.02)
64 8 (between 7.92 and 8.08)
10000 100 (between 99 and 101)
2 bewteen 1.40001 and 1.428
```
## Scoring
Your programs on the same computer with same conditions (Terminal and Iceweasel with this tab open).
This question has the tag "Fastest code", so the program, which calculates the square root of a (not yet given) random integer between 1 and 10^10 as fast as possible will win!
[Answer]
# C
Since input is limited to positive integers between 1 and 1010, I can use a well-known fast inverse square root [algorithm](https://en.wikipedia.org/wiki/Fast_inverse_square_root) to find the inverse square root of the reciprocal of the input.
I'm not sure what you mean by *"only Xfce and the program and a terminal running"* but since you stated that functions are acceptable, I provide a function in C that will take an integer argument (that will be casted to float automatically) and outputs a float as the result.
```
float f(float n) {
n = 1.0f / n;
long i;
float x, y;
x = n * 0.5f;
y = n;
i = *(long *)&y;
i = 0x5f3759df - (i >> 1);
y = *(float *)&i;
y = y * (1.5f - (x * y * y));
return y;
}
```
The following is a program that makes uses of the function above to calculate the square roots of the given test cases and compares them to the values given by the `sqrtf` function in `math.h`.
[Ideone](http://ideone.com/xhpvud)
[Answer]
# Python 3
Why am I using Python? Never mind.
```
def sqrt(n):
# 3 iterations of newton's method, hard-coded
# normalize
# find highest bit
highest = 1
sqrt_highest = 1
while highest < n:
highest <<= 2
sqrt_highest <<= 1
n /= highest+0.0
result = (n/4) + 1
result = (result/2) + (n/(result*2))
result = (result/2) + (n/(result*2))
return result*sqrt_highest
```
[Ideone it!](http://ideone.com/fq8Do0)
[Answer]
# C
Uses unsigned integers when possible for speed.
`root.c`:
```
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define ns(t) (1000000000 * t.tv_sec + t.tv_nsec)
struct timespec then, now;
int output(uint64_t result)
{
clock_gettime(CLOCK_REALTIME, &now);
printf("sqrt(x) = %10lu.%2d real time:%9ld ns\n", result / 100, ((int) (result % 100)), ns(now) - ns(then));
return 0;
}
//real time: 60597 ns
int main(int argc, char *argv[]) {
clock_gettime(CLOCK_REALTIME, &then);
uint64_t num = atol(argv[1]), root = 100, old_root = 0;
num *= 10000; //multiply by 10k because int is faster
//and you only need 2 d.p. precision max. (for small numbers)
while (old_root != root) {
old_root = root;
root = (root + num / root) / 2;
}
return output(root);
}
```
`timein`:
```
#!/bin/bash
gcc -Wall $1 -lm -o $2 $2.c
./$2 $4
r=$(seq 1 $3)
for i in $r; do ./$2 $4; done > times
awk -v it=$3 '{ sum += $7 } END { print "\n" sum / (it) " ns" }' times
rm times
```
Usage: `./timein '-march=native -O3' root <iterations> <number>`
Inspired by [this answer](https://codegolf.stackexchange.com/a/74372/39244), uses [this algorithm](https://en.wikipedia.org/wiki/Newton's_method).
[Answer]
# [C (gcc)](https://gcc.gnu.org/)
demonstrates one Newton step after a linear approximation on mantissa
speed of C is fast but not really relevant unless you have to apply it several million times
then it is sensitive to overall context of SIMD vectorisation, memory access patterns & other branching causing pipeline stalls etc
```
float f(float x){int i=*(int*)&x;i=0x1fb90000+(i>>1);float y=*(float*)&i;return(y+x/y)/2;}
void main() {float y[4]={4,64,10000,2};
for(int j=0;j<4;j++)printf("f(%f)\t=\t%f\n",y[j],f(y[j]));}
```
[TIO](https://tio.run/##LY1BboMwEEX3nMJKlcoGim1qWlHHXCRkkQITjAgg41QgxNmpaTqbNxq9/6d4uxXF9qK7on2UFTqNttR9VGce9dFYVai2dviitOZijIbERL250ZjxmLKUsimB988kLSGq7b1FPt2g7a8WAX5yIovuLNLKx44@eZ2kVmzi8J0yNwHWWcaJfMqzs/4252lpKvswHZ6Dic6ExnL1fnpdovtVd5ig5T9yFhe1iPBDhHwvDONVetCb/RtqFJPNScgmCMhg3AXwAfARSG5Vbo@Qd4dwPjeXEPAOQuS6bb8 "C (gcc) – TIO")
[Answer]
>
> Adaptation of [my own answer](https://codegolf.stackexchange.com/questions/9027/fast-inverse-square-root/145914#145914) on [Fast inverse square root](https://codegolf.stackexchange.com/questions/9027/fast-inverse-square-root)
>
>
>
# [Tcl](http://tcl.tk/), 114 bytes
```
rename binary B
proc R n {B s [B f f $n] i i
B s [B f i [expr 0x5f3759df-($i>>1)]] f y
expr 1/($y*1.5-$n/2*$y**3)}
```
[Try it online!](https://tio.run/##PYm7CoMwAEV3v@IOGaJgNT5aOtTBT7CjZLA2QkDTNFpIEL89DR167nK4Zxtn741QwyLwkGowDm2kzWtEB4W9xYq@xRRGFIeEjP6XRC@sNshtPZWX@vqcUkpk07CY85Bd9Ksso8Ql7FSnRGVFEjwp48PPy6BhsVc4V2B5AMWBXX@2Ffe3ocTGt74DsfzwXw "Tcl – Try It Online")
] |
[Question]
[
## Introduction and Credit
Today without a fancy prelude: Please implement `takewhile`.
A variation of this (on a non-trivial data structure) was an assignment at my university functional programming course. This assignment is now closed and has been discussed in class and I have my professor's permission to post it here (I asked explicitly).
## Specification
### Input
The input will be a list (or your language's equivalent concept) of positive integers.
### Output
The output should be a list (or your language's equivalent concept) of positive integers.
### What to do?
Your task is to implement `takewhile` (language built-ins are allowed) with the predicate that the number under consideration is even (to focus on takewhile).
So you iterate over the list from start to end and while the condition (is even) holds, you copy to the output-list and as soon as you hit an element that doesn't make the condition true, you abort the operation and output (a step-by-step example is below). This higher-order functionality is also called takeWhile (`takewhile`).
### Potential corner cases
The order of the output list compared to the input list may not be changed, e.g. `[14,42,2]` may not become `[42,14]`.
The empty list is a valid in- and output.
### Who wins?
This is code-golf so the shortest answer in bytes wins!
Standard rules apply of course.
## Test Vectors
```
[14, 42, 2324, 97090, 4080622, 171480372] -> [14, 42, 2324, 97090, 4080622, 171480372]
[42, 14, 42, 2324] -> [42, 14, 42, 2324]
[7,14,42] -> []
[] -> []
[171480372, 13, 14, 42] -> [171480372]
[42, 14, 42, 43, 41, 4080622, 171480372] -> [42, 14, 42]
```
### Step-by-Step Example
```
Example Input: [42, 14, 42, 43, 41, 4080622, 171480372]
Consider first element: 42
42 is even (21*2)
Put 42 into output list, output list is now [42]
Consider second element: 14
14 is even (7*2)
Put 14 into output list, output list is now [42,14]
Consider third element: 42
42 is even (21*2)
Put 42 into output list, output list is now [42,14,42]
Consider fourth element: 43
43 is not even (2*21+1)
Drop 43 and return the current output list
return [42,14,42]
```
[Answer]
## Pyke, 8 bytes
```
0+2L%fhO
```
Interpreter fixed, use other links
Uses Dennis' method except my split\_at function includes the change - probably a bug
### Or with bugfix, 7 bytes
```
2L%1R@<
```
[Try it here!](http://pyke.catbus.co.uk/?code=2L%251R%40%3C&input=%5B42%2C+14%2C+43%2C+2324%5D)
```
2L% - map(%2, input)
1R@ - ^.index(1)
< - input[:^]
```
Or after 2nd bugfix, 6 bytes
```
2L%fhO
```
[Try it here!](http://pyke.catbus.co.uk/?code=2L%25fhO&input=%5B42%2C+14%2C+42%2C+2324%5D)
Explanation:
```
2L% - map(%2, input)
f - split_at(input, ^)
hO - ^[0][:-1]
```
[Answer]
# JavaScript, 40 bytes
`a=>[...a,1].slice(0,a.findIndex(n=>n%2))`
### How it works
1) Take input array `a` and add a `1` to the end
2) Find the index of the first odd integer in the array
3) Return a subset of the array from index 0 (inclusive) to the odd integer's index (exclusive)
[Answer]
# GolfScript, 11 bytes
This is a full GolfScript program that reads a stringified GolfScript array literal (e.g. `[28 14 7 0]`) and prints out the same array with the first odd element and everything after it removed:
```
~1\{~&.},p;
```
[**Try it online.**](http://golfscript.tryitonline.net/#code=fjFce34mLn0scDs&input=WzQyIDE0IDQyIDQzIDQxIDQwODA2MjIgMTcxNDgwMzcyXQ)
(Also: [Extended version with test harness.](http://golfscript.tryitonline.net/#code=biV7ICAgICAgICAgICAgICMgc3BsaXQgaW5wdXQgaW50byBsaW5lcyBhbmQgbG9vcCBvdmVyIHRoZW0KICB-MVx7fiYufSxwOyAgICMgYWN0dWFsIGNvZGUKfS8gICAgICAgICAgICAgICMgZW5kIG9mIGxvb3Ag&input=WzE0IDQyIDIzMjQgOTcwOTAgNDA4MDYyMiAxNzE0ODAzNzJdCls0MiAxNCA0MiAyMzI0XQpbNyAxNCA0Ml0KW10KWzE3MTQ4MDM3MiAxMyAxNCA0Ml0KWzQyIDE0IDQyIDQzIDQxIDQwODA2MjIgMTcxNDgwMzcyXQ))
De-golfed version with comments:
```
~ # evaluate input
1\ # push the number 1 onto the stack and move it under then input array
{ # start of loop body
~ # bitwise negate the input number (making odd numbers even and vice versa)
& # take bitwise AND of input and the saved number (0 or 1) on stack
. # duplicate result; filter loop will pop off the duplicate
}, # run loop above over input array, select elements for which it returns true
p # stringify and print filtered array
; # pop the number 0/1 off the stack
```
This solution is based on the GolfScript `{ },` filter operator, which runs the contents of the code block on each element of an array, and selects the elements of the array for which the code in the block returns a true (i.e. non-zero) value on top of the stack.
Thus, for example, `{1&},` would select all odd numbers in an array, and `{~1&},` would select all even numbers. The challenge, then, is to make a filter that selects even numbers *until it finds the first odd one*, and thereafter selects no numbers at all.
The solution I used is to replace the constant bit-mask `1` (used to extract the lowest bit of each input number) with a variable on the stack that stores the result (0 or 1) of the previous filter loop iteration (and is initialized to 1 before the loop). Thus, as soon as the filter returns 0 once, the bitmask also gets set to 0, preventing the filter from ever returning 1 again.
[Answer]
# Forth, 114 bytes
Forth doesn't really have lists. The parameters must be pushed onto the stack in reverse order, as is typical in Forth. The result will be left on the stack in the same order. This doesn't work on Ideone for some reason, but it works on repl. The new line is required to remove ambiguity of some sort?
```
: D DEPTH ;
: f D IF 1 D 1 DO D 1- ROLL LOOP D 0 DO I PICK 2 MOD IF D I LEAVE THEN LOOP
DO I ROLL DROP LOOP THEN ;
```
[**Try it online**](https://repl.it/C9Nz)
Ungolfed, with comments:
```
: f DEPTH IF ( if stack not empty )
1 DEPTH 1 DO DEPTH 1- ROLL LOOP ( put 1 on bottom of stack )
DEPTH 0 DO ( loop over entire stack )
I PICK 2 MOD IF ( if stack[i] is odd )
DEPTH I LEAVE ( put range and exit loop )
THEN
LOOP
DO I ROLL ( roll eyes )
DROP
LOOP ( iterate that range and remove )
THEN
;
```
This program (my previous attempt) prints the results until it hits an odd number. Everything remaining (not taken) will be left on the stack.
```
: f DEPTH IF BEGIN DUP 2 MOD DUP 1- IF SWAP . THEN UNTIL THEN ;
```
*Fails if only even integers*
[Answer]
# Befunge, 35 Bytes
This code handles numbers between 0 and 65535
```
1&:v
v-1_@#:@#<
>\:&:2%|
\+1p4\< ^
```
Input format :
```
number_of_values values(separated by a space)
```
Here is a version that displays the values at the end of the process :
```
1&:v>:: v >00g1+:4g.v
v-1_^#:>#<>$$\$1-:10p000p0-| -g01p00:<
>\:&:2%| @
\+1p4\< ^
```
You may test the code [here](http://www.quirkster.com/iano/js/befunge.html), but you will have to add a trailing line with trailing spaces, as this interpret specifies :
>
> « The code torus is only as large as the initial program. Insert more
> lines or trailing space if data will be put beyond the end of code.»
>
>
>
I don't know if this is acceptable, as I didn't count this trailing in the byte count
nb: it seems that because I'm storing number in the code, the interpreter won't let this program run twice in the correct way. You'll have to reload it.
---
How does this work:
![how](https://i.stack.imgur.com/DZvfr.png)
The interpreter follows the arrows and skip an instruction when crossing '#'
Grey dots are test, and the red line removes unneeded variables from the stack
Using the here in the above interpreter, the saved values are displayed in the code using their representations (I don't know the format).
Yes, Befunge is a quite reflective language
[Answer]
# 32-bit x86 machine code, 14 bytes
In hex:
```
31C9FCADD1E87203E0F941F7D9C3
```
The list of integers in machine code is something like C's "int a[]". Since the list contains positive integers let's assume the list is zero-terminated, i.e. the value zero marks the end of the array. It's also makes no sense to copy values to another buffer inside this function, that's what strncpy() is for.
The pointer to an array is passed via ESI register. Returns the number of elements comprising the resulting list in ECX.
## Disassembly:
```
31 c9 xor ecx,ecx ;ECX=0
fc cld
_loop:
ad lodsd ;Fetch a number to EAX
d1 e8 shr eax,1 ;EAX=>>1
72 03 jc _end ;If CF is set then the number is odd, break
e0 f9 loopne _loop ;--ECX; if(CF==0&&ZF==0)continue
41 inc ecx ;Should not include the terminating 0 into the count
_end:
f7 d9 neg ecx ;Counting from 0 downward, so ECX=-ECX
c3 ret
```
[Answer]
## Python 3, 59 bytes
```
def f(l):
L=[]
for x in l:
if x%2:break
L+=x,
return L
```
Can ~~surely~~ probably be golfed more.
Thanks to everyone who commented :D
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes
```
⁽₂Ḋ¾wJh
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwi4oG94oKC4biKwr53SmgiLCIiLCJbMTQsIDQyLCAyMzI0LCA5NzA5MCwgNDA4MDYyMiwgMTcxNDgwMzcyXVxuWzQyLCAxNCwgNDIsIDQzLCA0MSwgNDA4MDYyMiwgMTcxNDgwMzcyXVxuW10iXQ==)
### Explained
```
⁽₂Ḋ¾wJh
⁽ # 1-element lambda
₂ # check if even
Ḋ # group if true
¾wJ # add empty list to end
h # get head of the list
```
[Answer]
# [Factor](https://factorcode.org), 24 bytes
```
[ [ even? ] take-while ]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=jY9PboJAFMbjllN8PQBmZpgUtIldNm66McYFcTEhj0BApMNoNYaTuGHTXqE9S09TGhANJqRv816-7_f-nT9DFZitrn5Gq-Vi_voyRUI6oxQFve0oC6i4VmM6GK0KbJSJkGsy5pjrODN4sqyThTpO4BJSQDhCYuKyCYNkHnsUAtzl0mOOK1DiAfbsn2w7tuZu6G5CT25htxU77GLcCddF3Ok3DRwhHUg-9FlHllb5sTOh7X378EF7yp6xhlEJ2e9RnBLWjf21UXkN_J2YxglhXFOkgqhxq6rJvw)
[Answer]
# [jq](https://stedolan.github.io/jq/), 20 bytes
```
.[:map(.%2)[[1]][0]]
```
[Try it online!](https://tio.run/##yyr8/18v2io3sUBDT9VIMzraMDY22iA29v//aEMTHQUTIx0FI2MjIMvS3MDSAChgYGFgZgQUNTQ3NLEwMDY3iuWKBqlCVg0UMtcBCpiAJIEIrhaozBimFE2fCVDCxBCrBf/yC0oy8/OK/@smAwA "jq – Try It Online")
Explanation:
```
map(.%2) Maps the array items to their remainders when divided by 2
[[1]] Returns an array of indices where those items equal 1 (odds)
[0] Returns the first item of that array of indices
.[: ] Returns the original array up until that index
```
[Answer]
# [tinylisp 2](https://github.com/dloscutoff/tinylisp2), 6 bytes
```
(p ] e
```
Try it at [Replit](https://replit.com/@dloscutoff/tinylisp2). Example session:
```
tl2> (p ] e
(() remaining-args (eval (concat (q (] e)) (quote-each remaining-args))))
tl2> (def take-while-even _)
take-while-even
tl2> (take-while-even (list 2 4 6 7 8))
(2 4 6)
```
### Explanation
Uses (abbreviated aliases for) the library functions `take-while` and `even?`:
```
(p ] e)
(p ) ; Partially apply
] ; the take-while function
e ; to the even? function
```
---
Without using the library's `take-while` function, I found a rather elegant solution using `foldr` which is **26 bytes**:
```
(p {(\(N A)(?(e N)(c N A)(
```
That is, partially apply the `{` (foldr) function to the following argument:
```
(\(N A)(?(e N)(c N A)()))
(\ ) ; Lambda function
(N A) ; that takes a number N and a list A:
(? ) ; If
(e N) ; N is even
(c N A) ; cons N to A
() ; Else return empty list
```
So we end up with a function that takes a list and right-folds it on the above function, with a default starting accumulator value of nil (empty list). This starts from the right end of the list, collecting values as long as they are even, but whenever it encounters an odd value it discards all previous values and starts over.
[Answer]
# Rust, 25 bytes
```
|x|x.take_while(|x|x%2<1)
```
[Answer]
# K, 12 bytes
```
{x@&~|\2!'x}
```
## Explanation
```
{ } Function definition.
'x For each item in the input list...
2! Modulo it with 2 (e.g. 1%2, 5%2, 2%2, etc.) to get a list of booleans.
|\ Fold | over the list to figure out where the odd numbers begin.
~ Flip the values it to get the beginning even numbers (until they turn odd).
& Get the indices.
x@ Index the original list.
```
[Answer]
## [Minkolang 0.15](https://github.com/elendiastarman/Minkolang), 12 bytes
```
nd2%,5&xr$N.
```
[Try it here!](http://play.starmaninnovations.com/minkolang/?code=nd2%25%2C5%26xr%24N%2E&input=%5B42%2C%2014%2C%2042%2C%2043%2C%2041%2C%204080622%2C%20171480372%5D)
### Explanation
```
nd Take number from input and duplicate
2% Modulo 2
, Logical NOT
5& Pop top of stack and jump 5 spaces if truthy
x Dump top element
r Reverse stack
$N. Output whole stack as numbers and stop.
```
Minkolang's codebox is toroidal, so if the instruction pointer does not stop, then it loops around to the beginning again. Trying to take a number after all input has been exhausted pushes -1, which is very conveniently odd.
[Answer]
## Python, 43 bytes
```
lambda l:[x for x in l if l.__imul__(~x%2)]
```
Calling `l.__imul__(n)` does `l*=n`. For `n=~x%2`, it empties the list when `x` is even and otherwise leaves it unchanged. The list comprehension iterates and collect elements until it hits an odd number, which stops the iteration by emptying the list. Moreover, because it outputs the now-empty list, the `if` fails and the current odd value is not included.
[Answer]
## Lua, 67 Bytes
Simply iterate on each elements of the input using a `repeat..until` loop. The first iteration will use `i=0`, which isn't the first element of the input as Lua's tables are 1-indexed, resulting in `r[0]=nil` which won't do anything as `r[0]` is already `nil`.
```
function f(t)r={}i=0repeat r[i]=t[i]i=i+1until t[i]%2<1return r end
```
[Answer]
# Python 2, ~~59~~ ~~57~~ 56 bytes
```
def f(L,E=[]):
while L and~L[0]%2:E+=L.pop(0),
print E
```
[**Try it online**](https://repl.it/C8vD/2)
If printing rather than returning a list is allowed, **44 bytes**:
```
L=input()
while L and~L[0]%2:print L.pop(0)
```
And shorter by xnor, **34 bytes**, exits with an error on encountering an odd number:
```
for x in input():
0>>x%-2;print x
```
[Answer]
# Perl, 21 bytes
20 bytes code + 1 bytes command line (-p)
```
s/ ?\d*[13579]\b.*//
```
Usage example:
```
echo "20 4 6 5 3 4" | perl -pe "s/ ?\d*[13579]\b.*//"
```
[Answer]
# C, ~~73~~ ~~69~~ ~~63~~ ~~60~~ ~~54~~ ~~45~~ 42
This requires a NULL-terminated array of strings as input.
It modifies the parameter by chopping the list down to only even entries.
```
f(char**v){for(;*v&&~atoi(*v++)&1;);*v=0;}
```
If printing is allowed (45 bytes, doesn't modify parameter):
```
f(char**v){for(;*v&&~atoi(*v)&1;puts(*v++));}
```
Here is the previous complete program version (63 bytes):
```
i;main(int c,char**v){for(;(++i<c)-(atoi(v[i])&1);puts(v[i]));}
```
Takes input as program arguments.
[Answer]
# PowerShell 26 bytes
```
process{if($_%2){break}$_}
```
Explanation
```
process{if($_%2){break}$_}
process{ } # runs the script block once per item in the passed parameter
if($_%2){break} # if odd, break out of process{}
$_ # implicit output
```
Testing (save as evenodd.ps1):
```
PS> 42,14,42,2324 | .\evenodd.ps1
42
14
42
2324
PS> 7,14,42 | .\evenodd.ps1
PS> 171480372,13,14,42 | .\evenodd.ps1
171480372
```
[Answer]
# Common Lisp, 44 bytes
```
(loop as x in(read)while(evenp x)collect x)
```
[Try it online!](https://tio.run/##DcjLCoAgEEbhV/mX487LUL5O2EDCoJJRvr25OXycpLm3Se3O5ZkgrbXh6BjIhW45TvNdWYXkldIwTKqqkp6laSaxh2OscgA7sI128@vtjqMNuzc/)
[Answer]
# [Husk](https://github.com/barbuz/Husk), 3 bytes
```
↑¦2
```
[Try it online!](https://tio.run/##yygtzv6f@6ip8f@jtomHlhn9//8/OtrQRMfESMfI2MhEx9LcwNJAx8TAwsDMyEjH0NzQxMLA2NwoVicaqAKhDsg3h3CBLCCCK9QxNIaLw3WYGOuYGGIxNBYA "Husk – Try It Online")
After [my adventures](https://codegolf.stackexchange.com/a/182367/85334) with using drop-while to set a default input value with Husk's type inference system, I jumped at the opportunity to use take-while for something normal.
```
↑ The largest prefix of
the input
¦ in which each element is divisible by
2 two.
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), 58 bytes
```
a->a.stream().mapToInt(i->i).takeWhile(i->i%2<1).toArray()
```
[Try it online!](https://tio.run/##nVNda9swFH33r7gUAjIownbM0japYQwKhb11sIcsD5ojp0pty5Pk0BDy2zN9@KNdulGGMfjee3TO0bG0o3s63W2ez7xqhNSwMzVpNS9J0da55qIm993HIrjAKC0ZrcgXUZYs10KqdzCfpaSH9wZfudKLIOC1ZrKgOYP7YwCgNNU8h73gG9BMaWTmqzXwumk1Bl@wl8bIsU1oFwD0BpeWcflg@LZMZthhMyjg7kynGe3MopBUtPkmDAzxacZDoukz@/7ES@bqSbKMTU842yg8W4GFk9lTCTTXLS0frBm4A7@1nthZDMlP8cI2RiX3oaAxHMNqHaIw9IR@M5KptrRsBaFNUx7QK40eWADqtNgvM1PIL8JDECH4KAAeD0qziohWk0YahQJdTRRMM5ioH/UV7j1r8ajNeNu5vux7hd7qCVip2EdEAPWmTBH@j@TlYNxm5yaw73hYXJD2cScmp4opk6c3ezzGKYY0wZDMEvN1M49uItOIrqNPienG8zi9jmbz5IThw9AT7rgt@PUiS3LRG9BzbPqpUxqbb6tBw3DMeh5n7d/iqQGn8d/2NSL96tMi@OOqVZTXyMdtYqRyq/ojVQgJqEt4yBdux6jHs@fua99fRWs8gFbx@s2/O51/Aw "Java (JDK) – Try It Online")
Takes a `List<Integer>` and outputs an `int[]`.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 25 bytes
```
->a{a.take_while &:even?}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY7de0SqxP1ShKzU-PLMzJzUhXUrFLLUvPsayHyN-0LFNyio02MdBQMTXQUQLSJMRAbArGBhYGZEUjC3NDEwsDY3Cg2VkFZQddOAUl5LMSYBQsgNAA)
[Answer]
# [J-uby](https://github.com/cyoce/J-uby), 18 bytes
```
:take_while+:even?
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700K740qXLBIjfbpaUlaboWm6xKErNT48szMnNSta1Sy1Lz7CESN-0LFNyio02MdBQMTXQUQLSJMRAbArGBhYGZEUjC3NDEwsDY3Cg2VkFZQddOAUl5LMSYBQsgNAA)
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), 59 bytes
```
[]+[].
[H|_]+[]:-1is H mod 2.
[H|T]+[H|R]:-0is H mod 2,T+R.
```
[Try it online!](https://tio.run/##bY5NC4JAEEDv/gqPyY7LftFql/ATz@JtWboUIViGBl7875vVlBDdhvfmMXMb@q4/h@PUOmcsMZZ6ppoPz2kX8nb0K//SH33xws2Cq7leDFsNNKSmbh8arkAJEFIoiDWLGSgWsa0QwDVXEZNaWJLANLT30yYJ4NqBZ5ZgzSxJUaeo9dtakqHIUFiSI8mRfI8Al5@qwJ3i95qSoPi//0osyoC6Bw "Prolog (SWI) – Try It Online")
[Answer]
# ARM Thumb-2 machine code, 12 bytes
```
00000000: 04 c8 52 ea c2 72 04 c1 fa d5 70 47 ..R..r....pG
```
Assembly:
```
.syntax unified
.arch armv7-a
.thumb
.globl takewhile
.thumb_func
// input: int *, r0
// output: int *, r1
// lists are terminated with a negative number
takewhile:
.Lloop:
// Load number into r2, increment r0
ldmia r0!, {r2}
// 1. shift the LSB of r0 into the MSB
// 2. Logical OR
// 3. Set flags on the result
// On either a terminator or an odd number, the MSB
// will be set, which sets the N flag. Additionally,
// this will terminate the list when stored.
// r2 = r2 | (r2 << 31);
// NF = r2 & 0x80000000;
orrs.w r2, r2, r2, lsl #31
// Store r2 into r1, increment r1
stmia r1!, {r2}
// Loop if MSB was not set (N flag not set)
bpl .Lloop
// Return
bx lr
```
This function requires and outputs an array of positive `int32_t`s terminated with any negative `int32_t`. It follows standard C calling convention:
```
#include <stdint.h>
#include <stdio.h>
void takewhile(const int32_t *input /* r0 */, int32_t *output /* r1 */);
int main(void)
{
const int32_t input[5] = { 171480372, 13, 14, 42, -1 };
int32_t output[5];
takewhile(input, output);
for (int i = 0; output[i] >= 0; i++) {
printf("%d, ", output[i]);
}
putchar('\n');
}
```
This takes advantage of the "numbers are positive" condition, and how ARM lets me set the condition codes for free.
I repeatedly logical OR the lowest bit of the values with the highest bit, and test the result. If the result is negative, one of the following is true:
1. The end of the list was reached (the upper bit was already set)
2. The number was odd (the lowest bit was set, which when shifted sets the upper bit).
With the example above, the outputted values will be this:
```
{ 171480372, /* -2147483635 */ 13 | 0x80000000 }
```
[Answer]
# [Fig](https://github.com/Seggan/Fig), \$3\log\_{256}(96)\approx\$ 2.469 bytes
```
t@E
```
[Try it online!](https://fig.fly.dev/#WyJ0QEUiLCJbNDIsIDE0LCA0MiwgNDMsIDQxLCA0MDgwNjIyLCAxNzE0ODAzNzJdIl0=)
Builtin. Can't have a functional language without one.
```
t@E
t@ # Take while
E # Even
```
[Answer]
# [Nim](https://nim-lang.org/), 87 bytes
```
proc t(a:seq[int]):seq[int]=
var i=0;while i<a.len and a[i]mod 2==0:inc i
a[0..i-1]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m704LzN3wYKlpSVpuhY3wwuK8pMVSjQSrYpTC6Mz80piNeEsWy4FhbLEIoVMWwPr8ozMnFSFTJtEvZzUPIXEvBSFxOjM2Nz8FAUjW1sDq8y8ZIVMoPLEaAM9vUxdw1iI8VBbYLYBAA)
[Answer]
# [Go](https://go.dev), ~~78~~ 64 bytes
```
func(s[]int,c func(int)){for _,x:=range s{if x%2>0{break}
c(x)}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bVBtSsQwEMVfQk4xLAgNREnTYLsLFY_g_2WR2G2WsDYpaVcKoSfxTxE81Hoap6mKiBDIzHtv3ny8vh3cdIZWVUd1qKFRxhLTtM73Nyvd9Cvyojzo8v3U6-vifK9Ptkq67c7YnlUQMwwpDdp5eGTDpvTKok8XjIbhStzx8ORrdRxJlQx0HBefj4vLuTR2S2ggaNHBpoTtLjqHkEoGUjAQmcBonfM1R4AX_FYgmuapLHiWi5GFWfVbjVDOEJAzie9Hi7LsW_qnTiIh038bjIQsm5k44LJcHDfEyziIExOdmI7FcwwzTZEGcKVq29ruE8cGSkZKHjxyz3bWgkOEfN1jmpb_Ew)
* -14 bytes by @Steffan
### [Go](https://go.dev), generic with predicate, 96 bytes
```
func f[T any](s[]T,b func(T)bool)(o[]T){for i:=0;i<len(s)&&b(s[i]);i++{o=append(o,s[i])}
return}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bZDNSsQwFIVxm5WPcBlwSJgoaafYzoxdunfRXSljOrZDsE1KfwYk9EncFMGH8FH0abxtVUSEkFxOvuTec55fjmZ4q-ThUR4zKKXSRJWVqdurRV62i9euzS-D9_u80wfI4wikfkpoEycRT2EUacRSYwpGDWrM5qYGtQ3FTt0UmaYNWy5TxFXCdmq1siaUVZXpB2r4JPakztqu1v3c5-PsfGo0jkGZJUq3DWxDiJM4wdpax-PguRzctYvVxhcbgYIIxLWLquM7XiDWvttzO1K_aZR8joI3XuL6YRFbf6N_3nl44Tn_NugJOUm02tyeMg3hHIUCHHKKw862QF24EIYgEB-T2XM1-amlxrAnd5bc1VgUmqqGQz7t86-MkZ58BTMM8_kJ)
] |
[Question]
[
>
> The challenge involve simply toggling a string within another string.
>
>
>
## Explanation
If the **toggle string** is a substring of the **main string**, remove all instances of the **toggle string** from the **main string**; otherwise, append the **toggle string** at the end of the **main string**.
## Rules
* All string are composed of printable ASCII characters
* The function should take two parameters: the **main string** and the **toggle string**.
* The **main string** can be empty.
* The **toggle string** cannot be empty.
* The result should be a string, which can be empty.
* The shortest answer wins.
## Examples
```
function toggle(main_string, toggle_string){ ... }
toggle('this string has 6 words ', 'now')
=> 'this string has 6 words now'
toggle('this string has 5 words now', ' now')
=> 'this string has 5 words'
```
## Tests cases
```
'','a' => 'a'
'a','a' => ''
'b','a' => 'ba'
'ab','a' => 'b'
'aba','a' => 'b'
'ababa', 'aba' => 'ba'
```
[Answer]
# Java 8, ~~80~~ ~~70~~ ~~65~~ 34 bytes
```
t->m->m==(m=m.replace(t,""))?m+t:m
```
Probably my shortest Java 'codegolf' so far.. xD
with some help from the comments.. ;)
**Explanation:**
[Try it online.](https://tio.run/##nY5BC4JAEIXv/orB00q6PyDTbt06eYwO42qxtrsuOgoS/nbb0IJuGgzMg3nvzVdhj1FtS1MVj0kobFs4ozRPD6AlJCmgcg7ekVT81hlBsjb8tIhDRo0093CVZ95pCgISmChKtZskYTrRvCmtQlEyCn0/CI56R3s9xZ6DsF2uHMTC0teyAO342Nx2uWLwRgXIhpZKzeuOuHUXUoYJjtaqgfnoBx/p2uMtftwayDd/@COxkir/DX1jozdOLw)
```
t->m-> // Method with two String parameters and String return-type
// (NOTE: Takes the toggle `t` and main `m` in reversed order)
m==(m=m.replace(t,""))? // If `m` equals `m` with all `t`-substrings removed:
// (And set `m` to `m` with all `t`-substrings removed)
m+t // Output this new `m` concatted with `t`
: // Else:
m // Output just this new `m`
```
[Answer]
# MATL, 11 bytes
```
yyXf?''YX}h
```
[Try it Online!](http://matl.tryitonline.net/#code=eXlYZj8nJ1lYfWg&input=J2FiYWJhJwonYWJhJw)
[All test cases](http://matl.tryitonline.net/#code=YGlpeXlYZj8nJ1lYfWhdRFRd&input=JycKJ2EnCidhJwonYScKJ2InCidhJwonYWInCidhJwonYWJhJwonYScKJ2FiYWJhJwonYWJhJw)
**Explanation**
```
% Implicitly grab the main string
% Implicitly grab the toggle string
y % Copy the main string
y % Copy the toggle string
Xf % Check to see if the toggle string is present in the main string
? % If so
''YX % Replace with an empty string
} % else
h % Horizontally concatenate the two strings
% Implicit end of if...else
% Implicitly display the result
```
[Answer]
# Python 3, 38 bytes
```
lambda s,t:(s+t,s.replace(t,""))[t in s]
```
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
œṣȮ⁸e⁹ẋ
```
[Try it online!](http://jelly.tryitonline.net/#code=xZPhuaPIruKBuGXigbnhuos&input=&args=J3RoaXMgc3RyaW5nIGhhcyA2IHdvcmRzICc+J25vdyc)
### How it works
```
œṣȮ⁸e⁹ẋ Main link. Arguments: s (string), t (toggle string)
œṣ Split s at occurrences of t.
Ȯ Print the result.
⁸e Check if s occurs in the split s. Yields 1 (true) or 0 (false).
⁹ẋ Repeat t that many times.
```
[Answer]
## JavaScript (ES6), ~~39~~ 37 bytes
```
(s,t,u=s.split(t).join``)=>u==s?s+t:u
```
[Answer]
## Pyke, 14 bytes
```
DX{iIXRk:)i!IJ
```
[Try it here!](http://pyke.catbus.co.uk/?code=DX%7BiIXRk%3A%29i%21IJ&input=%5B%22this+string+has+5+words+now%22%2C%22now%22%5D)
Given that Pyke has no `else` structure, I think this is pretty reasonable score
Explanation:
```
D - Duplicate input
X - a,b = ^
{ - a in b
i - i = ^
I - if i:
XRk: - a = b.replace(a,"")
i!I - if not i:
J - a = "".join(input)
- print a
```
[Answer]
# CJam, 9
```
q~:B/2Be]
```
[Try it online.](http://cjam.aditsu.net/#code=q%7E%3AB%2F2Be%5D&input=%22code%20golf%22%20%22o%22) Thanks jimmy23013 for chopping off 1 byte :)
**Explanation:**
```
q~ read and evaluate the input (given as 2 quoted strings)
:B store the toggle string in B
/ split the main string by the toggle string
2Be] pad the array of pieces to the right with B, up to length 2 (if shorter)
```
[Answer]
# Javascript (ECMAScript 6): 47 bytes
```
(a,b)=>(c=a.replace(RegExp(b,'g'),''))!=a?c:a+b
```
[Answer]
## [Retina](https://github.com/mbuettner/retina/), ~~38~~ 31 bytes
Byte count assumes ISO 8859-1 encoding.
```
(.+)(?=.*¶\1$)
·
1>`·|¶.+
T`·¶
```
The trailing linefeed is significant. Input format is both strings separated with a linefeed.
[Try it online!](http://retina.tryitonline.net/#code=JShHYAooLispKD89Lio7XDEkKQohCjE-YCF8Oy4rCgpUYCE7&input=dGhpcyBzdHJpbmcgaGFzIDYgd29yZHMgO25vdwp0aGlzIHN0cmluZyBoYXMgNSB3b3JkcyBub3c7IG5vdwo7YQphO2EKYjthCmFiO2EKYWJhO2EKYWJhYmE7YWJhCmFiYWJhYmFiYTthYmE) The first line allows running several test cases at once (for the test suite, use `;` to separate the strings and linefeeds to separate test cases; the first line takes care of the conversion).
### Explanation
```
(.+)(?=.*¶\1$)
·
```
In this first step we replace all occurrences of the toggle string in the main string with `·`. We need to insert these markers so that we can determine afterwards if any substitution happened.
```
1>`·|¶.+
```
This is another substitution which removes a `·` marker, or the second line (including the separating linefeed). However, the `1>` is a limit which means that only matches *after* the first are considered. Hence, if the toggle string did not occur in the main string, we won't have inserted any `·`, so the second line will be the first match and won't be removed. Otherwise, we remove the second line along with all but the first marker.
```
T`·¶
```
While this uses a transliteration stage, it's also used simply for removing characters. In particular, we move both `·` and linefeeds. We need the first one, in case there was a match (because then the first `·` will have been left behind by the previous stage) and we need the second one in case there wasn't a match (to join the two lines together and thereby append the toggle string to the main string).
[Answer]
# Python (3.4): ~~55~~ ~~54~~ ~~47~~ 44 Bytes
```
lambda m,t:m.replace(t,'')if t in m else m+t
```
Testing:
```
toggle=lambda m,t:m.replace(t,'')if t in m else m+t
print('', 'a', toggle('','a'))
print('a', 'a', toggle('a','a'))
print('b', 'a', toggle('b','a'))
print('ab', 'a', toggle('ab','a'))
print('aba', 'a', toggle('aba','a'))
print('ababa', 'aba', toggle('ababa','aba'))
```
The Test output
```
a a
a a
b a ba
ab a b
aba a b
ababa aba ba
```
~~Using a def would be longer because you have to use a return statement, if it were possible without return it would save 2 Bytes~~
Since explicit declaration of the function is not needed (sorry I didn't know that) 7 Bytes were saved.
[Answer]
# C#, 63
```
string F(string s,string t)=>s.Contains(t)?s.Replace(t,""):s+t;
```
Better than Java :)
Test code:
```
public static void Main()
{
Console.WriteLine(F("", "a"));
Console.WriteLine(F("a", "a"));
Console.WriteLine(F("b", "a"));
Console.WriteLine(F("ab", "a"));
Console.WriteLine(F("aba", "a"));
Console.WriteLine(F("ababa", "aba"));
Console.ReadLine();
}
```
Output:
```
a
ba
b
b
ba
```
[Answer]
# Pyth, ~~13~~ ~~11~~ 10 bytes
```
?/Qz:Qzk+z
```
[Test suite.](http://pyth.herokuapp.com/?code=%3F%2FQz%3AQzk%2Bz&test_suite=1&test_suite_input=%22%22%0Aa%0A%0A%22a%22%0Aa%0A%0A%22b%22%0Aa%0A%0A%22ab%22%0Aa%0A%0A%22aba%22%0Aa%0A%0A%22ababa%22%0Aaba%0A&debug=0&input_size=3)
Input format: first string in quotes, second string without quotes.
### This is also 10 bytes:
```
?tJcQzsJ+z
```
[Test suite.](http://pyth.herokuapp.com/?code=%3FtJcQzsJ%2Bz&test_suite=1&test_suite_input=%22%22%0Aa%0A%0A%22a%22%0Aa%0A%0A%22b%22%0Aa%0A%0A%22ab%22%0Aa%0A%0A%22aba%22%0Aa%0A%0A%22ababa%22%0Aaba%0A&debug=0&input_size=3)
### This is 11 bytes:
```
pscQz*!}zQz
```
[Test suite.](http://pyth.herokuapp.com/?code=pscQz*!%7DzQz&test_suite=1&test_suite_input=%22%22%0Aa%0A%0A%22a%22%0Aa%0A%0A%22b%22%0Aa%0A%0A%22ab%22%0Aa%0A%0A%22aba%22%0Aa%0A%0A%22ababa%22%0Aaba%0A&debug=0&input_size=3)
### Previous 13-byte solution:
```
?:IQzk+Qz:Qzk
```
[Test suite.](http://pyth.herokuapp.com/?code=%3F%3AIQzk%2BQz%3AQzk&test_suite=1&test_suite_input=%22%22%0Aa%0A%0A%22a%22%0Aa%0A%0A%22b%22%0Aa%0A%0A%22ab%22%0Aa%0A%0A%22aba%22%0Aa%0A%0A%22ababa%22%0Aaba%0A&debug=0&input_size=3)
[Answer]
# Jolf, 12 bytes
```
?=iγρiIE+iIγ
```
Or, if we must include regex-sensitive chars:
```
?=iγρiLeIE+iIγ
```
[Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=Pz1pzrPPgWlMZUlFK2lJzrM&input=SGVsbG8sIHBlcnNvbiEKCiwgcGVyc29uIQ)
## Explanation
```
?=iγρiIE+iIγ if(i === (γ = i.replace(I, E))) alert(i + I); else alert(γ);
i i
= ===
ρ .replace( , )
iI i I
E E
γ (γ = )
? if( )
+iI alert(i + I);
else
γ alert(γ);
```
[Answer]
# JavaScript (ES6), 37 Bytes
```
(m,t)=>(w=m.split(t).join``)==m?m+t:w
```
Slightly shorter than @nobe4 's answer by taking advantage of split and join
[Answer]
# Racket, 70 bytes
Pretty straight forward.
```
(λ(s t)((if(string-contains? s t)string-replace string-append)s t""))
```
[Answer]
# Scala, 72 70 bytes
```
def x(m:String,s:String)={val r=m.replaceAll(s,"");if(r==m)m+s else r}
```
Online interpreter: [www.tryscala.com](http://www.tryscala.com)
[Answer]
# Oracle SQL 11.2, 66 bytes
```
SELECT DECODE(:1,s,s||:2,s)FROM(SELECT REPLACE(:1,:2)s FROM DUAL);
```
[Answer]
# Ruby, ~~33 bytes~~ ~~27 bytes (28 if using global subtitution)~~ definitely 28 bytes
```
->u,v{u[v]?u.gsub(v,''):u+v}
```
[Answer]
# Ruby, ~~35~~ ~~37~~ 28 bytes
```
->m,t{m[t]?m.gsub(t,''):m+t}
```
Hooray for string interpolation! It even works in regexes. The rest is simple: if the string in `t` matches to `m`, replace `t` with `''`, else return `m+t`.
**Edit:** Fixed a bug.
**Edit:** I applied Kevin Lau's suggestion, but it appears that I have reached the same algorithm as the one used in [Luis Masuelli's answer](https://codegolf.stackexchange.com/a/80303/47581).
[Answer]
# Perl, ~~37~~ 30 bytes
```
{$_=shift;s/\Q@_//g?$_:"$_@_"}
```
Regular expressions inside the toggle string are not evaluate because of the quoting with `\Q`...`\E`.
`sub F` and `\E` are removed according to the [comment](https://codegolf.stackexchange.com/questions/80243/toggle-a-string/80306?noredirect=1#comment197404_80306) by msh210.
It is not entirely free of side effects because of setting `$_`. Using a local variable will cost six additional bytes:
```
{my$a=shift;$a=~s/\Q@_//g?$a:"$a@_"}
```
On the other hand, with switched input parameters two bytes can be saved by using `pop` instead of `shift` (28 bytes):
```
{$_=pop;s/\Q@_//g?$_:"$_@_"}
```
Test file:
```
#!/usr/bin/env perl
sub F{$_=shift;s/\Q@_//g?$_:"$_@_"}
sub test ($$$) {
my ($m, $t, $r) = @_;
my $result = F($m, $t);
print "F('$m', '$t') -> '$result' ",
($result eq $r ? '=OK=' : '<ERROR>'), " '$r'\n";
}
test '', 'a', 'a';
test 'a', 'a', '';
test 'b', 'a', 'ba';
test 'ab', 'a', 'b';
test 'aba', 'a', 'b';
test 'ababa', 'aba', 'ba';
test 'ababa', 'a*', 'ababaa*';
test 'foobar', '.', 'foobar.';
__END__
```
Test result:
```
F('', 'a') -> 'a' =OK= 'a'
F('a', 'a') -> '' =OK= ''
F('b', 'a') -> 'ba' =OK= 'ba'
F('ab', 'a') -> 'b' =OK= 'b'
F('aba', 'a') -> 'b' =OK= 'b'
F('ababa', 'aba') -> 'ba' =OK= 'ba'
F('ababa', 'a*') -> 'ababaa*' =OK= 'ababaa*'
F('foobar', '.') -> 'foobar.' =OK= 'foobar.'
```
[Answer]
# C# (58 bytes)
`string F(string s,string t)=>s==(s=s.Replace(t,""))?s+t:s;`
It uses an inline assignment to shave a few bytes off
[Answer]
# bash + sed, 28 bytes
```
sed "s/$2//g;t;s/$/$2/"<<<$1
```
The script lives in a toggle-string.bash file, which we call with `bash toggle-string.bash mainstring togglestring`.
`s/$2//g` removes the toggle string from the main string
`t` jumps to the end if the previous substitution was successful (ie. the main string contained the toggle string)
`/$/$2/` adds the toggle string at the end (`$`), if we didn't jump to the end
bash is required for the herestring
[Answer]
# Julia, ~~33~~ 31 bytes
```
s|t=(r=replace(s,t,""))t^(s==r)
```
[Try it online!](http://julia.tryitonline.net/#code=c3x0PShyPXJlcGxhY2Uocyx0LCIiKSl0XihzPT1yKQoKcHJpbnRsbigidGhpcyBzdHJpbmcgaGFzIDYgd29yZHMgInwibm93IikKcHJpbnRsbigidGhpcyBzdHJpbmcgaGFzIDUgd29yZHMgbm93InwiIG5vdyIpCnByaW50bG4oIiJ8ImEiKQpwcmludGxuKCJhInwiYSIpCnByaW50bG4oImIifCJhIikKcHJpbnRsbigiYWIifCJhIikKcHJpbnRsbigiYWJhInwiYSIpCnByaW50bG4oImFiYWJhInwiYWJhIik&input=)
[Answer]
## PowerShell v2+, 47 bytes
```
param($a,$b)(($c=$a-replace$b),"$a$b")[$c-eq$a]
```
Takes input `$a,$b` and then uses a pseudo-ternary `(... , ...)[...]` statement to perform an if/else. The inner parts are evaluated first to form an array of two elements. The 0th is `$a` with all occurrences of `$b` `-replace`d with nothing, which is stored into `$c`. The 1st is just a string concatenation of `$a` and `$b`.
If `$c` is `-eq`ual to `$a`, meaning that `$b` wasn't found, that's Boolean `$true` or `1`, and so the 1st element of the array (the concatenation) is chosen. Else, it's Boolean `$false`, so we output `$c`, the 0th element.
Note that `-replace` is greedy, so it will replace from the left first, meaning the `ababa / aba` test case will properly return `ba`.
[Answer]
# Java 8, 65 bytes
```
BinaryOperator<String>l=(m,t)->m.contains(t)?m.replace(t,""):m+t;
```
The same logic as the Java 7 solution, written with a lambda.
[Try it here](http://ideone.com/v5Uh0G)
[Answer]
# Mathematica, 45 bytes
```
If[StringContainsQ@##,StringDelete@##,#<>#2]&
```
Anonymous function that takes the main string and the toggle string (in that order) and returns the result. Explanation:
```
& Anonymous function returning...
If[StringContainsQ@##, , ] if its first argument contains
its second argument, then...
StringDelete@## its first argument with its
second argument removed, else...
#<>#2 its second argument appended to
its first argument.
```
[Answer]
**TSQL, 143 129 121 Bytes**
```
DECLARE @1 VARCHAR(10)='',@2 VARCHAR(10)='a'SELECT CASE WHEN @1 LIKE'%'+@2+'%'THEN REPLACE(@1,@2,'')ELSE CONCAT(@1,@2)END
```
Readable:
```
DECLARE @1 VARCHAR(10) = ''
, @2 VARCHAR(10) = 'a'
SELECT CASE WHEN @1 LIKE '%' + @2 + '%'
THEN REPLACE(@1, @2, '')
ELSE CONCAT (@1, @2)
END
```
`**[`Live Demo`](https://data.stackexchange.com/stackoverflow/query/edit/488831)**`
**114 Bytes** with strictly 1 character input
```
DECLARE @1 CHAR(1) = 'a'
, @2 CHAR(1) = '.'
SELECT CASE WHEN @1 LIKE '%' + @2 + '%'
THEN REPLACE(@1, @2, '')
ELSE CONCAT (@1, @2) END
```
[Answer]
# TSQL(Sqlserver 2012), 49 bytes
```
DECLARE @ VARCHAR(10) = 'hello',@x VARCHAR(10) = 'o'
PRINT IIF(@ LIKE'%'+@x+'%',REPLACE(@,@x,''),@+@x)
```
[Try it online!](https://data.stackexchange.com/stackoverflow/query/488976/toggle-a-string)
[Answer]
# k (23 bytes)
```
{$[#x ss y;,/y\:x;x,y]}
```
Examples:
```
k){$[#x ss y;,/y\:x;x,y]}["aba";"a"]
,"b"
k){$[#x ss y;,/y\:x;x,y]}["this string has 6 words ";"now"]
"this string has 6 words now"
k){$[#x ss y;,/y\:x;x,y]}["this string has 5 words now";"now"]
"this string has 5 words "
k){$[#x ss y;,/y\:x;x,y]}["ababa";"ba"]
,"a"
k){$[#x ss y;,/y\:x;x,y]}["";"a"]
,"a"
```
[Answer]
## Kotlin, 61 Bytes
```
{m:String,t:String->var n=m.replace(t,"");if(m==n)m+t else n}
```
This is would be shorter if assignment was an expression in Kotlin,and parameters were mutable,and there was a ternary conditional operator, sadly this isn't the case :(
[Try it Online!](http://try.kotlinlang.org/#/UserProjects/imoa5gjbnol7adr9n38tqja56a/q2a6ai0gv7gqjialn6rkrpo2bg)
### UnGolfed
```
fun t(m:String, t:String):String{
var n=m.replace(t, "")
return if(m==n)m+t else n
}
```
] |
[Question]
[]
|
[Question]
[
In the C programming language, arrays are defined like this:
```
int foo[] = {4, 8, 15, 16, 23, 42}; //Foo implicitly has a size of 6
```
The size of the array is inferred from the initializing elements, which in this case is 6. You can also write a C array this way, explicitly sizing it then defining each element in order:
```
int foo[6]; //Give the array an explicit size of 6
foo[0] = 4;
foo[1] = 8;
foo[2] = 15;
foo[3] = 16;
foo[4] = 23;
foo[5] = 42;
```
# The challenge
You must write a program or function that expands arrays from the first way to the second. Since you are writing a program to make code longer, and you love irony, you must make your code as short as possible.
The input will be a string representing the original array, and the output will be the expanded array-definition. You can safely assume that the input will always look like this:
```
<type> <array_name>[] = {<int>, <int>, <int> ... };
```
"Type" and "array\_name" will made up entirely of alphabet characters and underscores `_`. The elements of the list will always be a number in the range -2,147,483,648 to 2,147,483,647. Inputs in any other format do not need to be handled.
The whitespace in your output must exactly match the whitespace in the test output, although a trailing newline is allowed.
# Test IO:
```
#in
short array[] = {4, 3, 2, 1};
#out
short array[4];
array[0] = 4;
array[1] = 3;
array[2] = 2;
array[3] = 1;
#in
spam EGGS[] = {42};
#out
spam EGGS[1];
EGGS[0] = 42;
#in
terrible_long_type_name awful_array_name[] = {7, -8, 1337, 0, 13};
#out
terrible_long_type_name awful_array_name[5];
awful_array_name[0] = 7;
awful_array_name[1] = -8;
awful_array_name[2] = 1337;
awful_array_name[3] = 0;
awful_array_name[4] = 13;
```
Submissions in any language are encouraged, but bonus points if you can do it *in* C.
# Leaderboard:
Here is a leaderboard showing the top answers:
```
var QUESTION_ID=77857,OVERRIDE_USER=31716;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```
[Answer]
# Vim, ~~54, 52, 49~~ 47 keystrokes
---
```
2wa0<esc>qqYp<c-a>6ldf @qq@q$dT]dd:%norm dwf{xwC;<CR>gg"0P
```
Explanation:
```
2wa0<esc> 'Move 2 words forward, and insert a 0.
qq 'Start recording in register Q
Yp 'Duplicate the line
<c-a>6l 'Increment the next number then move 6 spaces right
df 'Delete until the next space
@qq@q 'Recursively call this macro
```
Now our buffer looks like this:
```
int foo[0] = {4, 8, 15, 16, 23, 42};
int foo[1] = {8, 15, 16, 23, 42};
int foo[2] = {15, 16, 23, 42};
int foo[3] = {16, 23, 42};
int foo[4] = {23, 42};
int foo[5] = {42};
int foo[6] = {42};
```
and our cursor is on the last line.
Second half:
```
$ 'Move to the end of the line
dT] 'Delete back until we hit a ']'
dd 'Delete this whole line.
:%norm <CR> 'Apply the following keystrokes to every line:
dw 'Delete a word (in this case "int")
f{x '(f)ind the next '{', then delete it.
wC; 'Move a word, then (C)hange to the end of this line,
'and enter a ';'
```
Now everything looks good, we just need to add the original array-declaration. So we do:
```
gg 'Move to line one
"0P 'Print buffer '0' behind us. Buffer '0' always holds the last deleted line,
'Which in this case is "int foo[6];"
```
[Answer]
# Pyth, 44 bytes
```
++Khcz\]lJ:z"-?\d+"1"];"VJs[ecKd~hZ"] = "N\;
```
[Test suite](https://pyth.herokuapp.com/?code=%2B%2BKhcz%5C%5DlJ%3Az%22-%3F%5Cd%2B%221%22%5D%3B%22VJs%5BecKd~hZ%22%5D+%3D+%22N%5C%3B&input=int+foo%5B%5D+%3D+%7B4%2C+8%2C+15%2C+16%2C+23%2C+42%7D%3B&test_suite=1&test_suite_input=int+foo%5B%5D+%3D+%7B4%2C+8%2C+15%2C+16%2C+23%2C+42%7D%3B%0Ashort+array%5B%5D+%3D+%7B4%2C+3%2C+2%2C+1%7D%3B%0Aspam+EGGS%5B%5D+%3D+%7B42%7D%3B%0Aterrible_long_type_name+awful_array_name%5B%5D+%3D+%7B7%2C+-8%2C+1337%2C+0%2C+13%7D%3B&debug=0)
Regular expression and string chopping. Not particularly clever.
Explanation:
```
++Khcz\]lJ:z"-?\d+"1"];"VJs[ecKd~hZ"] = "N\;
Implicit: z = input()
cz\] Chop z on ']'
h Take string before the ']'
K Store it in K
+ Add to that
:z"-?\d+"1 Find all numbers in the input
J Store them in J
l Take its length.
+ "];" Add on "];" and print.
VJ For N in J:
s[ Print the following, concatenated:
cKd Chop K on spaces.
e Take the last piece (array name)
~hZ The current interation number
"] = " That string
N The number from the input
\; And the trailing semicolon.
```
[Answer]
# Retina, ~~108~~ ~~104~~ ~~100~~ 69 bytes
Byte count assumes ISO 8859-1 encoding.
```
].+{((\S+ ?)+)
$#2];$1
+`((\w+\[).+;(\S+ )*)(-?\d+).+
$1¶$2$#3] = $4;
```
Beat this, PowerShell...
## Code explanation
**First line:** `].+{((\S+ ?)+)`
First, we need to keep the type, array name, and opening bracket (it saves a byte), so we don't match them. So we match the closing bracket, any number of characters, and an opening curly brace: `].+{`. Then we match the number list. Shortest I've been able to find so far is this: `((\S+ ?)+)`. We match any number of non-space characters (this includes numbers, possible negative sign, and possible comma), followed by a space, that may or may not be there: `\S+ ?`. This group of characters is then repeated as many times as needed: `(\S+ ?)+` and put into the large capturing group. Note that we don't match the closing curly brace or semicolon. Third line explanation tells why.
**Second line:** `$#2];$1`
Since we only matched a part of input, the unmatched parts will still be there. So we put the length of the list after the unmatched opening bracket: `$#2`. The replace modifier `#` helps us with that, as it gives us the number of matches a particular capturing group made. In this case capturing group `2`. Then we put a closing bracket and a semicolon, and finally our whole list.
With input `short array[] = {4, 3, 2, 1};`, the internal representation after this replacing is:
```
short array[4];4, 3, 2, 1};
```
(note the closing curly brace and semicolon)
**Third line:** `+`((\w+[).+;(\S+ )*)(-?\d+).+`
This is a looped section. That means it runs until no stage in the loop makes a change to the input. First we match the array name, followed by an opening bracket: `(\w+\[)`. Then an arbitrary number of any characters and a semicolon: `.+;`. Then we match the list again, but this time only numbers and the comma after each number, which have a space following them: `(\S+ )*`. Then we capture the last number in the list: `(-?\d+)` and any remaining characters behind it: `.+`.
**Fourth line:** `$1¶$2$#3] = $4;`
We then replace it with the array name and list followed by a newline: `$1¶`. Next, we put the array name, followed by the length of previously matched list, without the last element (essentially `list.length - 1`): `$2$#3`. Followed by a closing bracket and assigment operator with spaces, and this followed by the last element of our number list: `] = $4;`
After first replacing, the internal representation looks like this:
```
short array[4];4, 3, 2,
array[3] = 1;
```
Note that the closing curly brace and the semicolon disappeared, thanks to the `.+` at the end of third line.
After three more replacings, the internal representation looks like this:
```
short array[4];
array[0] = 4;
array[1] = 3;
array[2] = 2;
array[3] = 1;
```
Since there's nothing more to match by third line, fourth doesn't replace anything and the string is returned.
**TL;DR:** First we change up the int list format a bit. Then we take the last element of the list and the name, and put them after the array initialization. We do this until the int list is empty. Then we give the changed code back.
[Try it online!](http://retina.tryitonline.net/#code=XS4reygoXFMrID8pKykKJCMyXTskMQorYCgoXHcrXFspLis7KFxTKyApKikoLT9cZCspLisKJDHCtiQyJCMzXSA9ICQ0Ow&input=dGVycmlibGVfbG9uZ190eXBlX25hbWUgYXdmdWxfYXJyYXlfbmFtZVtdID0gezcsIC04LCAxMzM3LCAwLCAxM307)
[Answer]
# C, 215 bytes, 196 bytes
*19 bytes saved thanks to @tucuxi!*
**Golfed:**
```
char i[99],o[999],b[99],z[99];t,x,n,c;main(){gets(i);sscanf(i,"%s %[^[]s",b,z);while(sscanf(i+t,"%*[^0-9]%d%n",&x,&n)==1)sprintf(o,"%s[%d] = %d;\n",z,c++,x),t+=n;printf("%s %s[%d];\n%s",b,z,c,o);}
```
**Ungolfed:**
```
/*
* Global strings:
* i: input string
* o: output string
* b: input array type
* z: input array name
*/
char i[ 99 ], o[ 999 ], b[ 99 ], z[ 99 ];
/* Global ints initialized to zeros */
t, x, n, c;
main()
{
/* Grab input string from stdin, store into i */
gets( i );
/* Grab the <type> <array_name> and store into b and z */
sscanf( i, "%s %[^[]s", b, z );
/* Grab only the int values and concatenate to output string */
while( sscanf( i + t, "%*[^0-9]%d%n", &x, &n ) == 1 )
{
/* Format the string and store into a */
sprintf( o, "%s[%d] = %d;\n", z, c++, x );
/* Get the current location of the pointer */
t += n;
}
/* Print the <type> <array_name>[<size>]; and output string */
printf( "%s %s[%d];\n%s", b, z, c, o );
}
```
**Link:**
<http://ideone.com/h81XbI>
**Explanation:**
To get the `<type> <array_name>`, the `sscanf()` format string is this:
```
%s A string delimited by a space
%[^[] The character set that contains anything but a `[` symbol
s A string of that character set
```
To extract the int values from the string `int foo[] = {4, 8, 15, 16, 23, 42};`, I essentially tokenize the string with this function:
```
while( sscanf( i + t, "%*[^0-9]%d%n", &x, &n ) == 1 )
```
where:
* `i` is the input string (a `char*`)
* `t` is the pointer location offset of `i`
* `x` is the actual `int` parsed from the string
* `n` is the total characters consumed, including the found digit
The `sscanf()` format string means this:
```
%* Ignore the following, which is..
[^0-9] ..anything that isn't a digit
%d Read and store the digit found
%n Store the number of characters consumed
```
If you visualize the input string as a char array:
```
int foo[] = {4, 8, 15, 16, 23, 42};
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
00000000001111111111222222222233333
01234567890123456789012345678901234
```
with the `int` `4` being located at index 13, `8` at index 16, and so on, this is what the result of each run in the loop looks like:
```
Run 1) String: "int foo[] = {4, 8, 15, 16, 23, 42};"
Starting string pointer: str[ 0 ]
Num chars consumed until after found digit: 14
Digit that was found: 4
Ending string pointer: str[ 14 ]
Run 2) String: ", 8, 15, 16, 23, 42};"
Starting string pointer: str[ 14 ]
Num chars consumed until after found digit: 3
Digit that was found: 8
Ending string pointer: str[ 17 ]
Run 3) String: ", 15, 16, 23, 42};"
Starting string pointer: str[ 17 ]
Num chars consumed until after found digit: 4
Digit that was found: 15
Ending string pointer: str[ 21 ]
Run 4) String: ", 16, 23, 42};"
Starting string pointer: str[ 21 ]
Num chars consumed until after found digit: 4
Digit that was found: 16
Ending string pointer: str[ 25 ]
Run 5) String: ", 23, 42};"
Starting string pointer: str[ 25 ]
Num chars consumed until after found digit: 4
Digit that was found: 23
Ending string pointer: str[ 29 ]
Run 6) String: ", 42};"
Starting string pointer: str[ 29 ]
Num chars consumed until after found digit: 4
Digit that was found: 42
Ending string pointer: str[ 33 ]
```
[Answer]
# V, 37 Bytes
```
2Eé0òYp6ldf ò$dT]ddÎdwf{xwC;
gg"1P
```
V is a 2D, string based golfing language that I wrote, designed off of vim. This works as of [commit 17](https://github.com/DJMcMayhem/V/commit/3e52ff77850f2d7897167eb9a20a859ca0169968).
Explanation:
This is pretty much a direct translation of [my vim answer](https://codegolf.stackexchange.com/a/77862/31716), albeit significantly shorter.
```
2E "Move to the end of 2 words forward.
é0 "Insert a single '0'
ò ò "Recursively do:
Yp6ldf "Yank, paste, move 6 right, delete until space.
$dT] "Move to the end of line, delete backwards until ']'
dd "Delete this line
Î "Apply the following to every line:
dwf{xwC;<\n> "Delete word, move to '{' and delete it, Change to end of line, and enter ';'
```
Then we just have:
```
gg"1P "Move to line 1, and paste buffer '1' behind us.
```
Since this unicode madness can be hard to enter, you can create the file with this reversible hexdump:
```
00000000: 3245 e930 f259 7001 366c 6466 20f2 2464 2E.0.Yp.6ldf .$d
00000010: 545d 6464 ce64 7766 7b78 7743 3b0d 6767 T]dd.dwf{xwC;.gg
00000020: 2231 500a "1P.
```
This can be run by installing V and typing:
```
python main.py c_array.v --f=file_with_original_text.txt
```
[Answer]
# C, ~~195~~ 180 bytes
195-byte original:
golfed:
```
char*a,*b,*c,*d;j;main(i){scanf("%ms %m[^]]%m[^;]",&a,&b,&c);
for(d=c;*d++;i+=*d==44);printf("%s %s%d];\n",a,b,i);
for(d=strtok(c,"] =,{}");j<i;j++,d=strtok(0," ,}"))printf("%s%d] = %s;\n",b,j,d);}
```
ungolfed:
```
char*a,*b,*c,*d;
j;
main(i){
scanf("%ms %m[^]]%m[^;]",&a,&b,&c); // m-modifier does its own mallocs
for(d=c;*d++;i+=*d==44); // count commas
printf("%s %s%d];\n",a,b,i); // first line
for(d=strtok(c,"] =,{}");j<i;j++,d=strtok(0," ,}"))
printf("%s%d] = %s;\n",b,j,d); // each array value
}
```
The two shortcuts are using the `m` modifier to to get scanf's `%s` to allocate its own memory (saves declaring char arrays), and using `strtok` (which is also available by default, without includes) to do the number-parsing part.
---
180-byte update:
```
char*a,*b,*c,e[999];i;main(){scanf("%ms %m[^]]%m[^}]",&a,&b,&c);
for(c=strtok(c,"] =,{}");sprintf(e,"%s%s%d] = %s;\n",e,b,i++,c),
c=strtok(0," ,"););printf("%s %s%d];\n%s",a,b,i,e);}
```
ungolfed:
```
char*a,*b,*c,e[999];
i;
main(){
scanf("%ms %m[^]]%m[^}]",&a,&b,&c);
for(c=strtok(c,"] =,{}");sprintf(e,"%s%s%d] = %s;\n",e,b,i++,c),c=strtok(0," ,"););
printf("%s %s%d];\n%s",a,b,i,e);
}
```
Uses [bnf679's](https://codegolf.stackexchange.com/a/77983/41288) idea of appending to a string to avoid having to count commas.
[Answer]
## Python 3.6 (pre-release), 133
```
m,p=str.split,print;y,u=m(input(),'[');t,n=m(y);i=m(u[5:-2],', ')
l=len(i);p(t,n+f'[{l}];')
for x in range(l):p(n+f'[{x}] = {i[x]};')
```
Makes heavy use of [f-strings](https://www.python.org/dev/peps/pep-0498/).
Ungolfed version:
```
y, u = input().split('[')
t, n = y.split()
i = u[5:-2].split(', ')
l = len(i)
print(t, n + f'[{l}];')
for x in range(l):
print(n + f'[{x}] = {i[x]};')
```
[Answer]
# Ruby, ~~127~~ ~~110~~ ~~108~~ ~~99~~ 88 bytes
~~Anonymous function with a single argument as input.~~ Full program, reads the input from STDIN. (If you pipe a file in, the trailing newline is optional.) ~~Returns~~ Prints the output string.
Took @TimmyD bragging about their solution beating all other non-esolangs as a challenge, and finally overcome the (at the time of writing) 114 byte Powershell solution they had posted. ~~Cᴏɴᴏʀ O'Bʀɪᴇɴ's trick with splitting on `]` and splicing the second half to get the numbers helped.~~
I need to use the splat operator more. It's so useful!
Borrowed a trick from @Neil's JavaScript ES6 answer to save more bytes by scanning for words instead of using `gsub` and `split`..
```
t,n,*l=gets.scan /-?\w+/;i=-1
puts t+" #{n}[#{l.size}];",l.map{|e|n+"[#{i+=1}] = #{e};"}
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~52~~ ~~50~~ 47 bytes
Code:
```
… = ¡`¦¨¨ð-',¡©gr¨s«„];«,®v¹ð¡¦¬s\¨N"] = "y';J,
```
Uses **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=4oCmID0gwqFgwqbCqMKow7AtJyzCocKpZ3LCqHPCq-KAnl07wqsswq52wrnDsMKhwqbCrHNcwqhOIl0gPSAieSc7Siw&input=aW50IGZvb1tdID0gezQsIDgsIDE1LCAxNiwgMjMsIDQyfTs).
[Answer]
## JavaScript (ES6), 100 bytes
```
(s,[t,n,...m]=s.match(/-?\w+/g))=>t+` ${n}[${m.length}];`+m.map((v,i)=>`
${n}[${i}] = ${v};`).join``
```
Since only the words are important, this works by just matching all the words in the original string, plus leading minus signs, then building the result. (I originally thought I was going to use `replace` but that turned out to be a red herring.)
[Answer]
# Pyth - ~~53~~ ~~50~~ ~~46~~ ~~45~~ 44 bytes
*2 bytes saved thanks to @FryAmTheEggman.*
```
+Jhcz\[+`]lKcPecz\{d\;j.es[ecJd`]kd\=dPb\;)K
```
[Test Suite](http://pyth.herokuapp.com/?code=%2BJhcz%5C%5B%2B%60%5DlKcPecz%5C%7Bd%5C%3Bj.es%5BecJd%60%5Dkd%5C%3DdPb%5C%3B%29K&input=int+foo%5B%5D+%3D+%7B4%2C+8%2C+15%2C+16%2C+23%2C+42%7D%3B&test_suite=1&test_suite_input=int+foo%5B%5D+%3D+%7B4%2C+8%2C+15%2C+16%2C+23%2C+42%7D%3B%0Ashort+array%5B%5D+%3D+%7B4%2C+3%2C+2%2C+1%7D%3B%0Aspam+EGGS%5B%5D+%3D+%7B42%7D%3B%0Aterrible_long_type_name+awful_array_name%5B%5D+%3D+%7B7%2C+-8%2C+1337%2C+0%2C+13%7D%3B&debug=0).
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~48~~ 47 bytes
```
qR`(\S+)(. = ).(.+)}`{[b#Yd^k']';.n.b.,#y.c.y]}
```
Takes input from stdin and prints to stdout.
### Explanation
**Tl;dr:** Does a regex replacement, using capture groups and a callback function to construct the result.
The `q` special variable reads a line of input. The regex is `(\S+)(. = ).(.+)}`, which matches everything except the type (including trailing space) and the final semicolon. Using the first example from the question, the capturing groups get `foo[`, `] =` , and `4, 8, 15, 16, 23, 42`.
The replacement is the return value of the unnamed function `{[b#Yd^k']';.n.b.,#y.c.y]}`, which is called with the whole match plus the capturing groups as arguments. Thus, within the function, `b` gets capture group 1, `c` gets group 2, and `d` gets group 3.
We construct a list, the first three items of which will be `"foo["`, `6`, and `"]"`. To get the `6`, we split `d` on the built-in variable `k` = `", "`, `Y`ank the resulting list of integers into the `y` variable for future use, and take the length (`#`). `']` is a character literal.
What remains is to construct a series of strings of the form `";\nfoo[i] = x"`. To do so, we concatenate the following: `';`, `n` (a built-in for newline), `b` (1st capture group), `,#y` (equivalent to Python `range(len(y))`), `c` (2nd capture group), and `y`. Concatenation works itemwise on lists and ranges, so the result is a list of strings. Putting it all together, the return value of the function will be a list such as this:
```
["foo[" 6 "]"
[";" n "foo[" 0 "] = " 4]
[";" n "foo[" 1 "] = " 8]
[";" n "foo[" 2 "] = " 15]
[";" n "foo[" 3 "] = " 16]
[";" n "foo[" 4 "] = " 23]
[";" n "foo[" 5 "] = " 42]
]
```
Since this list is being used in a string `R`eplacement, it is implicitly cast to a string. The default list-to-string conversion in Pip is concatenating all the elements:
```
"foo[6];
foo[0] = 4;
foo[1] = 5;
foo[2] = 15;
foo[3] = 16;
foo[4] = 23;
foo[5] = 42"
```
Finally, the result (including the type and the final semicolon, which weren't matched by the regex and thus remain unchanged) is auto-printed.
[Answer]
## Perl 5.10, 73 72 68 66 + 1 (for -n switch) = 67 bytes
```
perl -nE '($t,$n,@a)=/[-[\w]+/g;say"$t $n".@a."];";say$n,$i++,"] = $_;"for@a'
```
This is a nice challenge for Perl and the shortest among general-purpose languages so far. Equivalent to
```
($t, $n, @a) = /[-[\w]+/g;
say "$t $n" . @a . "];";
say $n, $i++, "] = $_;" for @a;
```
[Answer]
## PowerShell v2+, ~~114~~ 105 bytes
```
$a,$b,$c,$d=-split$args-replace'\[]';"$a $b[$(($d=-join$d|iex|iex).length)];";$d|%{"$b[$(($i++))] = $_;"}
```
Takes input string `$args` and `-replace`s the square bracket with nothing, then performs a `-split` on whitespace. We store the first bit into `$a`, the second bit into `$b`, the `=` into `$c`, and the array elements into `$d`. For the example below, this stores `foo` into `$a` and `bar` into `$b`, and all of the array into `$d`.
We then output our first line with `"$a ..."` and in the middle transform `$d` from a an array of strings of form `{1,`,`2,`,...`100};` to a regular int array by `-join`ing it together into one string, then running it through `iex` twice (similar to `eval`). We store that resultant array back in `$d` before calling the `.length` method to populate the appropriate number in between the `[]` in the output line.
We then send `$d` through a loop with `|%{...}`. Each iteration we output `"$b..."` with a counter variable `$i` encapsulated in brackets and the current value `$_`. The `$i` variable starts uninitialized (equivalent to `$null`) but the `++` will cast it to an `int` before the output, so it will start output at `0`, all before incrementing `$i` for the next loop iteration.
All output lines are left on the pipeline, and output to the terminal is implicit at program termination.
### Example
```
PS C:\Tools\Scripts\golfing> .\expand-a-c-array.ps1 "foo bar[] = {1, 2, 3, -99, 100};"
foo bar[5];
bar[0] = 1;
bar[1] = 2;
bar[2] = 3;
bar[3] = -99;
bar[4] = 100;
```
[Answer]
## C,~~278~~ 280 bytes
golfed:
```
x,e,l,d;char *m,*r,*a;char i[999];c(x){return isdigit(x)||x==45;}main(){gets(i);m=r=&i;while(*r++!=32);a=r;while(*++r!=93);l=r-a;d=r-m;for(;*r++;*r==44?e++:1);printf("%.*s%d];\n",d,m,e+1);r=&i;while(*r++){if(c(*r)){m=r;while(c(*++r));printf("%.*s%d] = %.*s;\n",l,a,x++,r-m,m);}}}
```
ungolfed:
```
/* global ints
* x = generic counter
* e = number of elements
* l = length of the array type
* d = array defination upto the first '['
*/
x,e,l,d;
/* global pointers
* m = memory pointer
* r = memory reference / index
* a = pointer to the start of the array type string
*/
char *m,*r,*a;
/* data storage for stdin */
char i[999];
c(x){return isdigit(x)||x=='-';}
main(){
gets(i);
m=r=&i;
while(*r++!=32); // skip first space
a=r;
while(*++r!=93); // skip to ']'
l=r-a;
d=r-m;
for(;*r++;*r==44?e++:1); // count elements
printf("%.*s%d];\n",d,m,e+1); // print array define
r=&i;
while(*r++) { // print elements
if(c(*r)) { // is char a - or a digit?
m=r;
while(c(*++r)); // count -/digit chars
printf("%.*s%d] = %.*s;\n",l,a,x++,r-m,m);
}
}
}
```
While working on this someones posted a shorter version using sscanf for the parsing rather than using data pointers... nice one!
UPDATE:
Spotted missing spaces around the equals in the element printing, IDE online link: <http://ideone.com/KrgRt0> . Note this implementation does support negative numbers...
[Answer]
# Awk, 101 bytes
```
{FS="[^[:alnum:]_-]+";printf"%s %s[%d];\n",$1,$2,NF-3;for(i=3;i<NF;i++)printf$2"[%d] = %d;\n",i-3,$i}
```
More readably:
```
{
FS="[^[:alnum:]_-]+"
printf "%s %s[%d];\n", $1, $2, NF - 3
for (i=3; i < NF; i++)
printf $2"[%d] = %d;\n", i-3, $i
}
```
* I set the field separator to everything except alphabets, digits, the underscore and `-`. So, the fields would be the type name, the variable name, and the numbers.
* The number of fields will be 1 (for the type) + 1 (for the name) + N (numbers) + 1 (an empty field after the trailing `};`). So, the size of the array is `NF - 3`.
* Then it's just printing a special line for the declaration, and looping over the numbers.
* I *should* assign `FS` either when invoking awk (using `-F`) or in a `BEGIN` block. In the interests of brevity, ….
[Answer]
# JavaScript ES6, ~~134~~ ~~132~~ ~~130~~ 129 bytes
Saved 1 byte thanks to Neil.
```
x=>(m=x.match(/(\w+) (\w+).+{(.+)}/),m[1]+` `+(q=m[2])+`[${q.length-1}];
`+m[3].split`, `.map((t,i)=>q+`[${i}] = ${t};`).join`
`)
```
[Answer]
## bash, ~~133~~ 129 bytes
```
read -a l
d="${l[@]:0:2}"
e=("${l[@]:3}")
echo "${d%?}${#e[@]}];"
for i in "${!e[@]}"
{
echo "${l[0]}[$i] = ${e[$i]//[!0-9]/};"
}
```
First attempt, sure its posible to get it shorter.
[Answer]
# D, 197, 188 bytes
```
import std.array,std.stdio;void main(){string t,n,e;readf("%s %s] = {%s}",&t,&n,&e);auto v=e.replace(",","").split;writeln(t,' ',n,v.length,"];");foreach(i,c;v)writeln(n,i,"] = ",c,";");}
```
or ungolfed:
```
import std.array, std.stdio;
void main() {
string type, nameAndBracket, elems;
readf("%s %s] = {%s}", &type, &nameAndBracket, &elems);
// remove all commas before splitting the string into substrings
auto vector = elems.replace(",","").split();
// writeln is shorter than fln by 1 char when filled in
writeln(type, ' ', nameAndBracket, vector.length, "];");
// print each element being assigned
foreach(index, content; vector)
writeln(nameAndBraket, index, "] = ", content, ";");
}
```
[Answer]
# Julia, ~~154~~ ~~134~~ 101 bytes
```
f(s,c=matchall(r"-?\w+",s),n=endof(c)-2)=c[]" "c[2]"[$n];
"join([c[2]"[$i] = "c[i+3]";
"for i=0:n-1])
```
This is a function that accepts a string and returns a string with a single trailing newline.
Ungolfed:
```
function f(s, c = matchall(r"-?\w+", s), n = endof(c) - 2)
c[] " " c[2] "[$n];\n" join([c[2] "[$i] = " x[i+3] ";\n" for i = 0:n-1])
end
```
We define `c` to be an array of matches of the input on the regular expression `-?\w+`. It caputres the type, array name, then each value. We store `n` as the length of `c` - 2, which is the number of values. The output is constructed as the type, name and length string interpolated, combined with each definition line separated by newlines. For whatever reason, `c[]` is the same as `c[1]`.
Saved 32 bytes with help from Dennis!
[Answer]
## Python 2, 159 bytes
```
s=input().split()
t,n,v=s[0],s[1][:-2],''.join(s[3:])
a=v[1:-2].split(',')
print'%s %s[%d];'%(t,n,len(a))
for i in range(len(a)):print'%s[%d] = %s;'%(n,i,a[i])
```
[Try it online](http://ideone.com/fork/mm2tbz)
Thanks Kevin Lau for some golfing suggestions
[Answer]
## Python 3, 116 bytes
```
t,v,_,*l=input().split();v=v[:-1]+'%s]'
print(t,v%len(l)+';');i=0
for x in l:print(v%i,'= %s;'%x.strip('{,};'));i+=1
```
Splits the input into the type, name, and the list of numbers. After printing the array declaring, prints the elements by manually enumerating through the numbers, removing excess punctuation that attached to the first and last one.
A different approach in Python 2 came out to 122 bytes:
```
a,b=input()[:-2].split('] = {')
l=eval(b+',')
print a+`len(l)`+"];"
for y in enumerate(l):print a.split()[1]+'%s] = %s;'%y
```
The idea is to `eval` the list of numbers as a tuple, with a comma at the end so that a single number is recognized as a type. The enumerated list of numbers provides tuples to string-format in.
[Answer]
## PHP, 143 bytes
**Golfed**
```
<?$t=count($n=explode(' ',preg_replace('/[^\s\w]/','',$argv[1])))-3;echo"$n[0] {$n[1]}[$t];";for($i=2;$t>$j=++$i-3;)echo$n[1]."[$j] = $n[$i];";
```
**Ungolfed**
```
<?
$t = count( // Get the number of elements for our array...
$n = explode(' ', // After split the input on whitespace...
preg_replace('/[^\s\w]/','',$argv[1])))-3; // After removing all special characters.
echo "$n[0] {$n[1]}[$t];"; // First line is type, name, and count.
for($i=2; // Loop through array elements
$t > $j = ++$i-3;) // Assign j to be the actual index for our new array
echo $n[1]."[$j] = $n[$i];"; // Print each line
```
Input is taken through command line argument. Sample:
```
C:\(filepath)>php Expand.php "int foo[] = {4,8,15,16,23,42};"
```
Output:
```
int foo[6];foo[0] = 4;foo[1] = 8;foo[2] = 15;foo[3] = 16;foo[4] = 23;foo[5] = 42;
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~68~~ ~~64~~ 58 bytes
```
'\w+'XX2:H#)XKxXIZc'['KnV'];'v!K"I2X)'['X@qV'] = '@g';'6$h
```
This isn't C, ~~but it does use C-like `sprintf` function~~ Nah, that was wasting 4 bytes.
[**Try it online!**](http://matl.tryitonline.net/#code=J1x3KydYWDI6SCMpWEt4WElaYydbJ0tuViddOyd2IUsiSTJYKSdbJ1hAcVYnXSA9ICdAZyc7JzYkaA&input=J2ludCBmb29bXSA9IHs0LCA4LCAxNSwgMTYsIDIzLCA0Mn07Jw)
```
% Take input implicitly
'\w+'XX % Find substrings that match regex '\w+'. Gives a cell array
2:H#) % Split into a subarray with the first two substrings (type and name), and
% another with the rest (numbers that form the array)
XKx % Copy the latter (numbers) into clipboard K. Delete it
XI % Copy the former (type and name) into clipboard I
Zc % Join the first two substrings with a space
'[' % Push this string
K % Paste array of numbers
nV % Get its length. Convert to string
'];' % Push this string
v! % Concatenate all strings up to now. Gives first line of the output
K" % For each number in the array
I2X) % Get name of array as a string
'[' % Push this string
X@qV % Current iteration index, starting at 0, as a string
'] = ' % Push this string
@g % Current number of the array, as a string
';' % Push this string
5$h % Concatenate top 6 strings. This is a line of the output
% Implicity end for each
% Implicitly display
```
[Answer]
## Clojure, 115 bytes
```
#(let[[t n & v](re-seq #"-?\w+"%)](apply str t" "n\[(count v)"];\n"(map(fn[i v](str n"["i"] = "v";\n"))(range)v))))
```
I wasn't able to nicely merge `awful_array_name[5];` and `awful_array_name[0] = 7;` parts so that they'd re-use code :/
] |
[Question]
[
You are to approximate the value of:
$$\int^I\_0 \frac {e^x} {x^x} dx$$
Where your input is \$I\$.
# Rules
* You may not use any built-in integral functions.
* You may not use any built-in infinite summation functions.
* Your code must execute in a reasonable amount of time ( < 20 seconds on my machine)
* You may assume that input is greater than 0 but less than your language's upper limit.
* It may be any form of standard return/output.
You can verify your results at [Wolfram | Alpha](http://www.wolframalpha.com/input/?i=integrate+e%5Ex%2Fx%5Ex+from+0+to) (you can verify by concatenating your intended input to the linked query).
# Examples
(let's call the function `f`)
```
f(1) -> 2.18273
f(50) -> 6.39981
f(10000) -> 6.39981
f(2.71828) -> 5.58040
f(3.14159) -> 5.92228
```
Your answer should be accurate to `±.0001`.
[Answer]
# Julia, ~~79~~ ~~77~~ 38 bytes
```
I->sum(x->(e/x)^x,0:1e-5:min(I,9))/1e5
```
This is an anonymous function that accepts a numeric value and returns a float. To call it, assign it to a variable.
The approach here is to use a right Riemann sum to approximate the integral, which is given by the following formula:
$$\int\_a^b f(x) dx \approx \sum f(x) \Delta x$$
In our case, \$a = 0\$ and \$b = I\$, the input. We divide the region of integration into \$n = 10^5\$ discrete portions, so \$∆x = \frac 1 n = 10^{-5}\$. Since this is a constant relative to the sum, we can pull this outside of the sum and simply sum the function evaluations at each point and divide by \$n\$.
The function is surprisingly well-behaved (plot from Mathematica):
[![mathematicaplot](https://i.stack.imgur.com/RLKPH.png)](https://i.stack.imgur.com/RLKPH.png)
Since the function evaluates nearly to 0 for inputs greater than about 9, we truncate the input to be \$I\$ if \$I\$ is less than 9, or 9 otherwise. This simplifies the calculations we have to do significantly.
Ungolfed code:
```
function g(I)
# Define the range over which to sum. We truncate the input
# at 9 and subdivide the region into 1e5 pieces.
range = 0:1e-5:min(I,9)
# Evaluate the function at each of the 1e5 points, sum the
# results, and divide by the number of points.
return sum(x -> (e / x)^x, range) / 1e5
end
```
Saved 39 bytes thanks to Dennis!
[Answer]
# Jelly, ~~20~~ ~~19~~ 17 bytes
```
ð«9×R÷øȷ5µØe÷*×ḢS
```
This borrows the clever *truncate at 9* trick from [@AlexA.'s answer](https://codegolf.stackexchange.com/a/71314), and uses a [right Riemann sum](https://en.wikipedia.org/wiki/Riemann_sum#Right_Riemann_Sum) to estimate the corresponding integral.
Truncated test cases take a while, but are fast enough on [Try it online!](http://jelly.tryitonline.net/#code=w7DCqznDl1LDt8O4yLc1wrXDmGXDtyrDl-G4olM&input=&args=MTA&debug=on)
### How it works
```
ð«9×R÷øȷ5µØe÷*×ḢS Main link. Input: I
øȷ5 Niladic chain. Yields 1e5 = 100,000.
ð Dyadic chain. Left argument: I. Right argument: 1e5.
«9 Compute min(I, 9).
× Multiply the minimum with 1e5.
R Range; yield [1, 2, ..., min(I, 9) * 1e5] or [0] if I < 1e-5.
÷ Divide the range's items by 1e5.
This yields r := [1e-5, 2e-5, ... min(I, 9)] or [0] if I < 1e-5.
µ Monadic chain. Argument: r
Øe÷ Divide e by each element of r.
* Elevate the resulting quotients to the corresponding elements,
mapping t -> (e/t) ** t over r.
For the special case of r = [0], this yields [1], since
(e/0) ** 0 = inf ** 0 = 1 in Jelly.
×Ḣ Multiply each power by the first element of r, i.e., 1e-5 or 0.
S Add the resulting products.
```
[Answer]
## ES7, 78 bytes
```
i=>[...Array(n=2e3)].reduce(r=>r+Math.exp(j+=i)/j**j,0,i>9?i=9:0,i/=n,j=-i/2)*i
```
This uses the rectangle rule with 2000 rectangles, which (at least for the examples) seem to produce a sufficiently accurate answer, but the accuracy could easily be increased if necessary. It has to use the 9 trick otherwise the accuracy drops off for large values.
73 byte version that uses rectangles of width ~0.001 so it doesn't work above ~700 because Math.exp hits Infinity:
```
i=>[...Array(n=i*1e3|0)].reduce(r=>r+Math.exp(j+=i)/j**j,0,i/=n,j=-i/2)*i
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 26 bytes
```
9hX<t1e6XK:K/*ttZebb^/sK/*
```
This approximates the integral as a Riemann sum. As argued by Alex, we can truncate the integration interval at approximately 9 because the function values are very small beyond that.
The maximum value of the function is less than 3, so a step of about 1e-5 should be enough to obtain the desired accuracy. So for the maximum input 9 we need about 1e6 points.
This takes about 1.5 seconds in the online compiler, for any input value.
[**Try it online**!](http://matl.tryitonline.net/#code=OWhYPHQxZTZYSzpLLyp0dFplYmJeL3NLLyo&input=My4xNDE1OQ)
```
9hX< % input number, and limit to 9
t % duplicate
1e6XK: % generate vector [1,2,...,1e6]. Copy 1e6 to clipboard K
K/* % divide by 1e6 and multiply by truncated input. This gives
% a vector with 1e6 values of x from 0 to truncated input
ttZe % duplicate twice. Compute exp(x)
bb^ % rotate top three elements of stack twice. Compute x^x
/ % divide to compute exp(x)/x^x
s % sum function values
K/* % multiply by the step, which is the truncated input divided
% by 1e6
```
[Answer]
# [golflua](http://mniip.com/misc/conv/golflua/), 83 chars
I'll admit it: it took my a while to figure out the `min(I,9)` trick Alex presented allowed computing arbitrarily high numbers because the integral converged by then.
```
\f(x)~M.e(x)/x^x$b=M.mn(I.r(),9)n=1e6t=b/n g=0.5+f(b/2)~@k=1,n-1g=g+f(k*t)$I.w(t*g)
```
An ungolfed Lua equivalent would be
```
function f(x)
return math.exp(x)/x^x
end
b=math.min(io.read("*n"),9)
n=1e6
t=b/n
g=0.5+f(b/2)
for k=1,n-1 do
g=g+f(k*t)
end
io.write(t*g)
```
[Answer]
# Python 2, ~~94~~ 76 bytes
Thanks to @Dennis for saving me 18 bytes!
```
lambda I,x=1e5:sum((2.71828/i*x)**(i/x)/x for i in range(1,int(min(I,9)*x)))
```
[Try it online with testcases!](https://repl.it/Bk6w/2)
Using the rectangle method for the approximation. Using a rectangle width of 0.0001 which gives me the demanded precision. Also truncating inputs greater 9 to prevent memory errors with very big inputs.
[Answer]
# Perl 6, ~~90~~ 55 bytes
```
{my \x=1e5;sum ((e/$_*x)**($_/x)/x for 1..min($_,9)*x)}
```
**usage**
```
my &f = {my \x=1e5;sum ((e/$_*x)**($_/x)/x for 1..min($_,9)*x)}
f(1).say; # 2.1827350239231
f(50).say; # 6.39979602775846
f(10000).say; # 6.39979602775846
f(2.71828).say; # 5.58039854392816
f(3.14159).say; # 5.92227602782184
```
It's late and I need to sleep, I'll see if I can get this any shorter tomorrow.
EDIT: Managed to get it quite a bit shorter after seeing @DenkerAffe 's method.
[Answer]
# Pyth, ~~34~~ 29 bytes
Saved 5 Bytes with some help from @Dennis!
```
J^T5smcc^.n1d^ddJmcdJU*hS,Q9J
```
[Try it online!](http://pyth.herokuapp.com/?code=J%5ET5smcc%5E.n1d%5EddJmcdJU*hS%2CQ9J&input=1&test_suite_input=1%0A50%0A10000%0A2.71828%0A3.14159&debug=0)
### Explanation
Same algorithm as in [my Python answer](https://codegolf.stackexchange.com/a/71346/49110).
```
J^T5smcc^.n1d^ddJmcdJU*hS,Q9J # Q=input
J^T5 # set J so rectangle width *10^5
hS,Q9 # truncate inputs greater 9
mcdJU/ J # range from zero to Input in J steps
mcc^.n1d^ddJ # calculate area for each element in the list
s # Sum all areas and output result
```
[Answer]
# Vitsy, 39 bytes
Thought I might as well give my own contribution. ¯\\_(ツ)\_/¯ This uses the Left-Hand Riemann Sum estimation of integrals.
```
D9/([X9]1a5^D{/V}*0v1{\[EvV+DDv{/}^+]V*
D9/([X9] Truncation trick from Alex A.'s answer.
D Duplicate input.
9/ Divide it by 9.
([ ] If the result is greater than 0
X9 Remove the top item of the stack, and push 9.
1a5^D{/V}*0v0{ Setting up for the summation.
1 Push 1.
a5^ Push 100000.
D Duplicate the top item of the stack.
{ Push the top item of the stack to the back.
/ Divide the top two items of the stack. (1/100000)
V Save it as a global variable.
Our global variable is ∆x.
} Push the bottom item of the stack to the top.
* Multiply the top two items.
input*100000 is now on the stack.
0v Save 0 as a temporary variable.
0 Push 1.
{ Push the bottom item of the stack to the top.
input*100000 is now the top of the stack.
\[EvV+DDv{/}^+] Summation.
\[ ] Loop over this top item of the stack times.
input*100000 times, to be exact.
E Push Math.E to the stack.
v Push the temporary variable to the stack.
This is the current value of x.
V+ Add ∆x.
DD Duplicate twice.
v Save the temporary variable again.
{ Push the top item of the stack to the back.
/ Divide the top two items.
e/x
} Push the top item back to the top of the stack.
^ Put the second to top item of the stack to the power of the top item.
(e/x)^x
+ Add that to the current sum.
V* Multiply by ∆x
```
This leaves the sum on the top of the stack. The try it online link below has `N` on the end to show you the result.
[Try it Online!](http://vitsy.tryitonline.net/#code=RDkvKFtYOV0xYTVeRHsvVn0qMHYwe1xbRXZWK0REdnsvfV4rXVYqTg&input=&args=OQ)
] |
[Question]
[
Given a non-flat list of integers, output a list of lists containing the integers in each nesting level, starting with the least-nested level, with the values in their original order in the input list when read left-to-right. If two or more lists are at the same nesting level in the input list, they should be combined into a single list in the output. The output should not contain any empty lists - nesting levels that contain only lists should be skipped entirely.
You may assume that the integers are all in the (inclusive) range `[-100, 100]`. There is no maximum length or nesting depth for the lists. There will be no empty lists in the input - every nesting level will contain at least one integer or list.
The input and output must be in your language's native list/array/enumerable/iterable/etc. format, or in any reasonable, unambiguous format if your language lacks a sequence type.
## Examples
```
[1, 2, [3, [4, 5], 6, [7, [8], 9]]] => [[1, 2], [3, 6], [4, 5, 7, 9], [8]]
[3, 1, [12, [14, [18], 2], 1], [[4]], 5] => [[3, 1, 5], [12, 1], [14, 2, 4], [18]]
[2, 1, [[5]], 6] => [[2, 1, 6], [5]]
[[54, [43, 76, [[[-19]]]], 20], 12] => [[12], [54, 20], [43, 76], [-19]]
[[[50]], [[50]]] => [[50, 50]]
```
[Answer]
# Pyth, 17
```
us-GeaYsI#GQ)S#Y
```
The leading space is important. This filters the list on whether the values are invariant on the `s` function, then removes these values from the list and flatten it one level. The values are also stored in `Y` and when we print we remove the empty values by filtering if the sorted value of the list is truthy.
[Test Suite](https://pyth.herokuapp.com/?code=+us-GeaYsI%23GQ%29S%23Y&input=%5B1%2C+2%2C+%5B3%2C+%5B4%2C+5%5D%2C+6%2C+%5B7%2C+%5B8%5D%2C+9%5D%5D%5D&test_suite=1&test_suite_input=%5B1%2C+2%2C+%5B3%2C+%5B4%2C+5%5D%2C+6%2C+%5B7%2C+%5B8%5D%2C+9%5D%5D%5D%0A%5B3%2C+1%2C+%5B12%2C+%5B14%2C+%5B18%5D%2C+2%5D%2C+1%5D%2C+%5B%5B4%5D%5D%2C+5%5D%0A%5B2%2C+1%2C+%5B%5B5%5D%5D%2C+6%5D%0A%5B%5B54%2C+%5B43%2C+76%2C+%5B%5B%5B-19%5D%5D%5D%5D%2C+20%5D%2C+12%5D%0A%5B%5B%5B50%5D%5D%2C+%5B%5B50%5D%5D%5D&debug=0)
Alternatively, a 15 byte answer with a dubious output format:
```
us-GpWJsI#GJQ)
```
[Test Suite](https://pyth.herokuapp.com/?code=%20us-GpWJsI%23GJQ%29&input=%5B1%2C%202%2C%20%5B3%2C%20%5B4%2C%205%5D%2C%206%2C%20%5B7%2C%20%5B8%5D%2C%209%5D%5D%5D&test_suite=1&test_suite_input=%5B1%2C%202%2C%20%5B3%2C%20%5B4%2C%205%5D%2C%206%2C%20%5B7%2C%20%5B8%5D%2C%209%5D%5D%5D%0A%5B3%2C%201%2C%20%5B12%2C%20%5B14%2C%20%5B18%5D%2C%202%5D%2C%201%5D%2C%20%5B%5B4%5D%5D%2C%205%5D%0A%5B2%2C%201%2C%20%5B%5B5%5D%5D%2C%206%5D%0A%5B%5B54%2C%20%5B43%2C%2076%2C%20%5B%5B%5B-19%5D%5D%5D%5D%2C%2020%5D%2C%2012%5D%0A%5B%5B%5B50%5D%5D%2C%20%5B%5B50%5D%5D%5D&debug=0)
### Expansion:
```
us-GeaYsI#GQ)S#Y ## Q = eval(input)
u Q) ## reduce to fixed point, starting with G = Q
sI#G ## get the values that are not lists from G
## this works because s<int> = <int> but s<list> = flatter list
aY ## append the list of these values to Y
e ## flatten the list
-G ## remove the values in the list from G
S#Y ## remove empty lists from Y
```
[Answer]
# Mathematica, ~~56~~ ~~54~~ 52 bytes
*-2 bytes due to [Alephalpha](https://codegolf.stackexchange.com/users/9288).*
*-2 bytes due to [CatsAreFluffy](https://codegolf.stackexchange.com/users/51443).*
```
Cases[#,_?AtomQ,{i}]~Table~{i,Depth@#}/.{}->Nothing&
```
Actually deletes empty levels.
[Answer]
# Python 2, 78 bytes
```
f=lambda l:l and zip(*[[x]for x in l if[]>x])+f(sum([x for x in l if[]<x],[]))
```
[Answer]
# [Retina](http://github.com/mbuettner/retina), 79
I *know* the Retina experts will golf this more, but here's a start:
```
{([^{}]+)}(,?)([^{}]*)
$3$2<$1>
)`[>}],?[<{]
,
(\d),+[<{]+
$1},{
<+
{
,*[>}]+
}
```
[Try it online.](http://retina.tryitonline.net/#code=K2B7LD99CgooYHsoW157fV0rKX0oLD8pKFtee31dKikKJDMkMjwkMT4KKWBbPn1dLD9bPHtdCiwKKFxkKSwrWzx7XSsKJDF9LHsKPCsKewosKls-fV0rCn0&input=e3s1NCx7NDMsNzYse3t7LTE5LHt7fSx7e319fX19fX0sMjB9LDEyLHt7fX19)
[Answer]
# Mathematica ~~55 64~~ 62 bytes
```
#~Select~AtomQ/.{}->Nothing&/@Table[Level[#,{k}],{k,Depth@#}]&
```
---
```
%&[{1, 2, {3, {4, 5}, 6, {7, {8}, 9}}}]
```
>
> {{1, 2}, {3, 6}, {4, 5, 7, 9}, {8}}
>
>
>
[Answer]
# JavaScript, ~~112~~ 80 bytes
```
F=(a,b=[],c=0)=>a.map(d=>d!==+d?F(d,b,c+1):b[c]=[...b[c]||[],d])&&b.filter(d=>d)
```
Thanks Neil for helping shave off 32 bytes.
[Answer]
# Jelly, 24 bytes
```
fFW®;©ṛ¹ḟF;/µŒḊ’$¡W®Tị¤;
```
[Try it online!](http://jelly.tryitonline.net/#code=ZkZXwq47wqnhuZvCueG4n0Y7L8K1xZLhuIrigJkkwqFXwq5U4buLwqQ7&input=&args=W1s1NCwgWzQzLCA3NiwgW1tbLTE5XV1dXSwgMjBdLCAxMl0)
If newline-separated lists were allowed, this could be golfed down to **14 bytes**.
```
fFṄ¹¹?ḟ@¹;/µ¹¿
```
[Try it online!](http://jelly.tryitonline.net/#code=ZkbhuYTCucK5P-G4n0DCuTsvwrXCucK_&input=&args=W1s1NCwgWzQzLCA3NiwgW1tbLTE5XV1dXSwgMjBdLCAxMl0)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
ŒJẈĠịF
```
[Try it online!](https://tio.run/##y0rNyan8///oJK@HuzqOLHi4u9vt/@H2R01rjk56uHMGkI78/z/aUEfBSEch2hiITXQUTGN1FMyATHMgtgCyLWNjYyGyQHXRhiCVhiYgAiRpBMSGIOloE5AqkN5oI4jKaFOQiBlY0hSkwQRohDnI5OhoXUOQqSD9BiADjMCKok0NYiGqgXQsAA "Jelly – Try It Online")
Jelly has [substantially improved](https://codegolf.stackexchange.com/a/73659/66833) in the past 5 years
## How it works
```
ŒJẈĠịF - Main link. Takes a list L on the left
ŒJ - Multi-dimensional indices
Ẉ - Get the length of each element
This yields the depth (starting at 1 for flat elements) of each element
Ġ - Group the indices of this list by the values
F - Flatten L
ị - Index into
```
Huh? The way that `ŒJẈĠ` works is kinda confusing without an example. Let's take `L = [3, 1, [12, [14, [18], 2], 1], [[4]], 5]` and work through it
`ŒJ` is one of a series of multi-dimensional commands that reflect the behaviour of their one-dimensional versions. Specifically, this is the "multi-dimensional indices" command, a multi-dimensional version of `J`, the "indices" command.
Picture `L` arranged like this:
```
3 1 12 14 18 2 1 4 5
12 14 18 2 1 4
14 18 2 4
18
```
That is, each element is repeated down a number of times equal to it's depth. `ŒJ` doesn't quite leave the elements like this (it changes the specific values, not the shape), but it's enough. `Ẉ` then calculates the length of each i.e. how many rows each element goes down:
```
1 1 2 3 4 3 2 3 1
```
`Ġ` the takes this list as it's argument. First, it's generates this list's indices: `[1, 2, 3, 4, 5, 6, 7, 8, 9]`. We then group these indices by the values of the argument. So because the values at indices `3` and `7` are equal (they're both `2`), `[3, 7]` is grouped. The final result of this is `[[1, 2, 9], [3, 7], [4, 6, 8], [5]]` as the groups are sorted by the values they're grouped by.
Finally, we index into the flattened `L` using this list of groups, which yields the intended output
[Answer]
# Python, ~~108~~ 99 bytes
This seems a bit long to me, but I couldn't make a one-liner shorter, and if I try using `or` instead of `if`, I get empty lists in the results.
```
def f(L):
o=[];i=[];j=[]
for x in L:[i,j][[]<x]+=[x]
if i:o+=[i]
if j:o+=f(sum(j,[]))
return o
```
[**Try it online**](http://ideone.com/FhIvyM)
Edit: [Saved 9 bytes thanks to Stack Overflow](https://stackoverflow.com/a/12135169/2415524)
[Answer]
## Python 3, 109 bytes
As ever, stupid Python 2 features like comparing `int`s and `list`s mean that Python 3 comes out behind. Oh well...
```
def d(s):
o=[]
while s:
l,*n=[],
for i in s:
try:n+=i
except:l+=[i]
if l:o+=[l]
s=n
return o
```
[Answer]
# Perl, 63 bytes
```
{$o[$x++]=[@t]if@t=grep{!ref}@i;(@i=map{@$_}grep{ref}@i)&&redo}
```
Input is expected in `@i`, output produced in `@o`. (I hope this is acceptable).
Example:
```
@i=[[54, [43, 76, [[[-19]]]], 20], 12]; # input
{$o[$x++]=[@t]if@t=grep{!ref}@i;(@i=map{@$_}grep{ref}@i)&&redo} # the snippet
use Data::Dumper; # print output
$Data::Dumper::Indent=0; # keep everything on one line
$Data::Dumper::Terse=1; # don't print $VAR =
print Dumper(\@o);
```
Output:
```
[[12],[54,20],[43,76],[-19]]
```
[Answer]
## Clojure, 119 bytes
**(116 with seq? and input as lists, a trivial modification)**
```
(defn f([v](vals(apply merge-with concat(sorted-map)(flatten(f 0 v)))))([l v](map #(if(number? %){l[%]}(f(inc l)%))v)))
```
Better intended:
```
(defn f([v] (vals(apply merge-with concat(sorted-map)(flatten(f 0 v)))))
([l v](map #(if(number? %){l[%]}(f(inc l)%))v)))
```
When called with two arguments (the current level and a collection) it either creates an one-element unordered-map like `{level: value}`, or calls `f` recursively if a non-number (presumambly a collection) is seen.
These mini-maps are then merged into a single `sorted-map` and key collisions are handled by `concat` function. `vals` returns map's values from first level to the last.
If a number is the only one at its level then it remains a `vec`, others are converted to lists by `concat`.
```
(f [[54, [43, 76, [[[-19]]]], 20], 12])
([12] (54 20) (43 76) [-19])
```
If input was a `list` instead of `vec` then `number?` could be replaced by `seq?`, oddly vector isn't `seq?` but it is `sequential?`. But I'm too lazy to implement that version, re-do examples etc.
[Answer]
## Racket 259 bytes
```
(let((ol'())(m 0))(let p((l l)(n 0))(cond[(empty? l)][(list?(car l))(set! m(+ 1 n))
(p(car l)(+ 1 n))(p(cdr l)n)][(set! ol(cons(list n(car l))ol))(p(cdr l)n )]))
(for/list((i(+ 1 m)))(flatten(map(λ(x)(cdr x))(filter(λ(x)(= i(list-ref x 0)))(reverse ol))))))
```
Ungolfed:
```
(define (f l)
(define ol '())
(define maxn 0)
(let loop ((l l) ; in this loop each item is added with its level
(n 0))
(cond
[(empty? l)]
[(list? (first l))
(set! maxn (add1 n))
(loop (first l) (add1 n))
(loop (rest l) n)]
[else
(set! ol (cons (list n (first l)) ol))
(loop (rest l) n )]))
; now ol is '((0 1) (0 2) (1 3) (2 4) (2 5) (1 6) (2 7) (3 8) (2 9))
(for/list ((i (add1 maxn))) ; here similar levels are combined
(flatten
(map (λ (x) (rest x)) ; level numbers are removed
(filter (λ (x) (= i(list-ref x 0)))
(reverse ol))))))
```
Testing:
```
(f '[1 2 [3 [4 5] 6 [7 [8] 9]]])
```
Output:
```
'((1 2) (3 6) (4 5 7 9) (8))
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 37 bytes
```
j']['!=dYsXKu"GK@=)'[\[\],]'32YXUn?1M
```
[**Try it online!**](http://matl.tryitonline.net/#code=aiddWychPWRZc1hLdSJHS0A9KSdbXFtcXSxdJzMyWVhVbj8xTQ&input=W1s1NCwgWzQzLCA3NiwgW1tbLTE5XV1dXSwgMjBdLCAxMl0)
Works with [current release (13.0.0)](https://github.com/lmendo/MATL/releases/tag/13.0.0) of the language/compiler.
This produces the output as lines of space-separated values, where each line corresponds to the same nesting level, and different nesting levels are separated by newlines.
```
j % read input as string (row array of chars)
']['! % 2x1 array containing ']' and '['
= % test for equality, all combinations
d % row array obtained as first row minus second row
Ys % cumulative sum. Each number is a nesting level
XK % copy to clibdoard K
u % unique values: all existing nesting levels
" % for each nesting level
G % push input
K % push array that indicates nesting level of each input character
@ % push level corresponding to this iteration
= % true for characters corresponding to that nesting level
) % pick those characters
'[\[\],]' % characters to be replaced
32 % space
YX % regexp replacement
U % only numbers and spaces remain: convert string to array of numbers
n? % if non-empty
1M % push that array of numbers again
% end if implicitly
% end for each implicitly
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 18 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
é╔óó)₧ú↔u.≤∟╦Ç╟·○`
```
[Run and debug it](https://staxlang.xyz/#p=82c9a2a2299ea31d752ef31ccb80c7fa0960&i=%5B1,+2,+%5B3,+%5B4,+5%5D,+6,+%5B7,+%5B8%5D,+9%5D%5D%5D%0A%5B3,+1,+%5B12,+%5B14,+%5B18%5D,+2%5D,+1%5D,+%5B%5B4%5D%5D,+5%5D%0A%5B2,+1,+%5B%5B5%5D%5D,+6%5D%0A%5B%5B54,+%5B43,+76,+%5B%5B%5B-19%5D%5D%5D%5D,+20%5D,+12%5D%0A%5B%5B%5B50%5D%5D,+%5B%5B50%5D%5D%5D&m=2)
I rhought I'd be able to beat pyth, but ¯\\_(○-○)\_/¯
] |
[Question]
[
## Background
Most everyone is familiar with the *Fibonacci numbers* \$F(n)\$:
>
> \$0, 1, 1, 2, 3, 5, 8, 13, 21, ...\$
>
>
>
These are formed by the recursion function \$F(n) = F(n-1) + F(n-2)\$ with \$F(0)=0\$ and \$F(1)=1\$. [A000045](https://oeis.org/A000045)
A closely related sequence is the *Lucas numbers* \$L(m)\$:
>
> \$2, 1, 3, 4, 7, 11, 18, 29, ...\$
>
>
>
These are formed by the recursion function \$L(m) = L(m-1) + L(m-2)\$ with \$L(0)=2\$ and \$L(1)=1\$. [A000032](https://oeis.org/A000032)
We can alternate between the two sequences based on even/odd indices, with the construction
$$A(x) = \begin{cases}
F(x) & x \equiv 0 \pmod 2 \\
L(x) & x \equiv 1 \pmod 2 \\
\end{cases}$$
For example, \$A(4)\$ is equal to \$F(4)\$ since \$4 \bmod 2 \equiv 0\$. We'll call this sequence the *Lucas-nacci Numbers*, \$A(x)\$:
>
> 0, 1, 1, 4, 3, 11, 8, 29, 21, 76 ...
>
>
>
This can be formed by the recursion function \$A(x) = 3A(x-2) - A(x-4)\$ with \$A(0)=0, A(1)=1, A(2)=1\$, and \$A(3)=4\$. [A005013](http://oeis.org/A005013)
## Challenge
Given input \$n\$, output the sequence of \$n+1\$ numbers up to and including \$A(n)\$ as described above. Fewest bytes (or byte-equivalents, such as for [LabVIEW](https://codegolf.meta.stackexchange.com/a/7589/42963), as determined individually on Meta) wins.
## Input
A single non-negative integer \$n\$.
## Output
A list of numbers that correspond to the subsequence of Lucas-nacci numbers from \$A(0)\$ to \$A(n)\$. The list must be in sequential order as described above.
## Rules
* Standard code-golf rules and [loophole restrictions](https://codegolf.meta.stackexchange.com/q/1061/42963) apply.
* [Standard input/output rules](https://codegolf.meta.stackexchange.com/a/1326/42963) apply.
* Input number can be in any suitable format: unary or decimal, read from STDIN, function or command-line argument, etc. - your choice.
* Output can be printed to STDOUT or returned as a result of the function call. If printed, suitable delimiters to differentiate the numbers must be included (space-separated, comma-separated, etc.).
* Additionally, if output to STDOUT, surrounding whitespace, trailing newline, etc. are all optional.
* If the input is a non-integer or a negative integer, the program can do anything or nothing, as behavior is undefined.
## Examples
```
Input -> Output
0 -> 0
5 -> 0, 1, 1, 4, 3, 11
18 -> 0, 1, 1, 4, 3, 11, 8, 29, 21, 76, 55, 199, 144, 521, 377, 1364, 987, 3571, 2584
```
[Answer]
# Jelly, 12 bytes
```
;2U+¥Ð¡-,1ZḢ
```
[Try it online!](http://jelly.tryitonline.net/#code=OzJVK8Klw5DCoS0sMVrhuKI&input=MTg)
### Background
We can extend F and L to -1 by defining F(-1) = 1 and L(-1) = -1. This is consistent with the recursive function.
Our program starts with
```
-1 1
0 2
```
In each step, to form the next pair, we reverse the last pair and add it to the penultimate pair. For example:
```
[0, 2] U+¥ [-1, 1] -> [2, 0] + [-1, 1] -> [1, 1]
```
If we continue this process for a few more steps, we get
```
-1 1
0 2
1 1
1 3
4 2
3 7
11 5
```
The Lucas-nacci sequence is simply the left column.
### How it works
```
;2U+¥Ð¡-,1ZḢ Niladic link. No implicit input.
Since the link doesn't start with a nilad, the argument 0 is used.
;2 Concatenate the argument with 2, yielding [0, 2].
-,1 Yield [-1, 1]. This is [L(-1), F(-1)].
¥ Create a dyadic chain of the two atoms to the left:
U Reverse the left argument.
+ Add the reversed left argument and the right one, element-wise.
С For reasons‡, read a number n from STDIN.
Repeatedly call the dyadic link U+¥, updating the right argument with
the value of the left one, and the left one with the return value.
Collect all intermediate results.
Z Zip the list of results, grouping the first and seconds coordinates.
Ḣ Head; select the list of first coordinates.
```
‡ `С` peeks at the two links to the left: `2` and `U+¥`. Since the leftmost one is a nilad, it cannot be the body of the loop. Therefore, `U+¥` is used as body and a number is read from input. Since there are no command-line arguments, that number is read from STDIN.
[Answer]
## CJam, ~~21~~ 20 bytes
*Thanks to Sp3000 for saving 1 byte.*
```
TXX4ri{1$3*4$-}*?;]p
```
[Test it here.](http://cjam.aditsu.net/#code=TXX4ri%7B1%243*4%24-%7D*%3F%3B%5Dp&input=18)
### Explanation
Simply uses the recurrence given in the challenge spec.
```
TXX4 e# Push 0 1 1 4 as base cases.
ri e# Read input and convert to integer N.
{ e# Run this N times...
1$ e# Copy a(n-2).
3* e# Multiply by 3.
4$ e# Copy a(n-4).
- e# Subtract.
}*
?; e# Discard the last three values, using a ternary operation and popping the result.
]p e# Wrap the rest in an array and pretty-print it.
```
[Answer]
# Perl 6, 42 bytes
```
{(0,1,1,4,{$^b;$^d;3*$^c-$^a}...*)[0..$_]}
```
**usage**
```
> my &f = {(0,1,1,4,{$^b;$^d;3*$^c-$^a}...*)[0..$_]}
-> ;; $_? is raw { #`(Block|184122176) ... }
> f(0)
(0)
> f(5)
(0 1 1 4 3 11)
> f(18)
(0 1 1 4 3 11 8 29 21 76 55 199 144 521 377 1364 987 3571 2584)
```
[Answer]
# Haskell, ~~59~~, ~~57~~, ~~56~~, ~~52~~, 51 bytes
```
l a=2*mod a 2:scanl(+)1(l a)
f n=[l i!!i|i<-[0..n]]
```
Series definition adapted from [this answer](https://codegolf.stackexchange.com/a/89/48962).
Less golfed:
```
fibLike start = start : scanl (+) 1 (fibLike start)
whichStart i = (2*mod i 2)
lucasNacci i = fibLike (whichStart i) !! i
firstN n = [ lucasNacci i | i <- [0..n]]
```
`fibLike start` gives an infinite list, defined: `f(0)=start, f(1)=1, f(n)=f(n-1) + f(n-2)`.
`whichStart i` returns 2 for odd input (Lucas series) or 0 for even (Fibonacci series).
`lucasNacci i` gives the ith Lucas-nacci number.
`firstN n` maps over the list.
One byte saved by Boomerang.
[Answer]
## ES6, 65 bytes
```
n=>[...Array(n)].map(_=>a.shift(a.push(a[2]*3-a[0])),a=[0,1,1,4])
```
Uses the recurrence relation given in the question.
[Answer]
## [Retina](https://github.com/mbuettner/retina), ~~70~~ ~~62~~ 59 bytes
```
1
¶$`1
m`^(11)*1$
$&ff
m`$
f
+`1(f*) (f*)
$2 $2$1
f*
f
1
```
[Try it online](http://retina.tryitonline.net/#code=MQrCtiRgMQptYF4oMTEpKjEkCiQmZmYKbWAkCiBmCitgMShmKikgKGYqKQokMiAkMiQxCiBmKgoKZgox&input=MTExMTExMTExMQ)
* Input is in unary base, *n* 1s.
* `1?` `$`¶` - Create a line for each number from 0 to *n*: `, 1, 11, 111, 1111, ...`
* `m`^(11)*1$` `$&ff` - Append `ff` to odd lines. This will seed the function with L(0)=2.
* `m`$` `f` - Append `f` to all lines (note the space). This seeds the function with 0 and 1 for Fibonacci numbers, and 2 and 1 for Lucas numbers.
* `+`1(f*) (f*)` `$2 $2$1` - Loop: calculate F(n+1) = F(n) + F(n-1) while there are still 1s.
* `f*` - Remove F(n+1) from the end of each line.
* Replace `f`s back to 1s. If this isn't needed and we can stay with `f`s, the length is just 55 bytes.
[Answer]
# Oracle SQL 11.2, ~~218~~ ~~216~~ 201 bytes
```
WITH v(a,b,c,d,i)AS(SELECT 0,1,1,4,3 FROM DUAL UNION ALL SELECT b,c,d,3*c-a,i+1 FROM v WHERE i<:1)SELECT SIGN(LEVEL-1) FROM DUAL WHERE LEVEL-1<=:1 CONNECT BY LEVEL<4UNION ALL SELECT d FROM v WHERE:1>2;
```
Un-golfed
```
WITH v(a,b,c,d,i) AS
(
SELECT 0,1,1,4,3 FROM DUAL
UNION ALL
SELECT b,c,d,3*c-a,i+1 FROM v WHERE i<:1
)
SELECT SIGN(LEVEL-1) FROM DUAL WHERE LEVEL-1<=:1 CONNECT BY LEVEL<4
UNION ALL SELECT d FROM v WHERE:1>2;
```
I managed to gain a few bytes by using (abusing ?) the SIGN function to generate the first 3 elements of the sequence.
[Answer]
# Japt, ~~25~~ ~~22~~ 21 bytes
```
Uò £MgXf2)+X%2*Mg°X)r
```
[Test it online!](http://ethproductions.github.io/japt?v=master&code=VfIgo01nWGYyKStYJTIqTWewWCly&input=MTg=)
### Background
It's somewhat difficult to create a Fibonacci sequence in Japt, but we have a built-in `Mg` to do it for us. However, this only gives us the Fibonacci sequence, not the Lucas sequence. We can accomplish the Lucas sequence fairly easily using this trick:
```
N F(N-1) F(N+1) F(N-1)+F(N+1)
0 1 1 2
1 0 1 1
2 1 2 3
3 1 3 4
4 2 5 7
5 3 8 11
6 5 13 18
7 8 21 29
```
As you can see, `F(N-1) + F(N+1)` is equal to `L(N)` for all `N`. However, since we only need Lucas numbers on the odd indices, we can combine the two formulas into one:
```
N N-N%2 N+N%2 F(N-N%2) F(N+N%2)*(N%2) F(N-N%2)+F(N+N%2)*(N%2)
0 0 0 0 0 0
1 0 2 0 1 1
2 2 2 1 0 1
3 2 4 1 3 4
4 4 4 3 0 3
5 4 6 3 8 11
6 6 6 8 0 8
7 6 8 8 21 29
```
### How it works
```
Uò £ MgX-1 +X%2*Mg° X)r
Uò mX{MgX-1 +X%2*Mg++X)r
// Implicit: U = input integer
Uò mX{ // Create the inclusive range [0..U], and map each item X to:
MgXf2)+ // Floor X to a multiple of 2, calculate this Fibonacci number, and add:
+X%2*Mg++X) // Calculate the (X+1)th Fibonacci number and multiply by X%2.
)r // Round the result. (The built-in Fibonacci function returns
// a decimal number on higher inputs.)
```
[Answer]
# Mathematica, ~~52~~ 51 bytes
```
If[#>2,3#0[#-2]-#0[#-4],#-If[#>1,1,0]]&/@0~Range~#&
```
Very similar idea to Martin's above, I spent some time trying to find a shorter way of defining the "base cases" for the function. Polynomial interpolation was a bust, so I went for this, using the extension into negatives to yield a fairly short definition.
[Answer]
## Mathematica, 56 bytes
```
f@0=0
f@1=f@2=1
f@3=4
f@n_:=3f[n-2]-f[n-4];
f/@0~Range~#&
```
Very straightforward implementation. Defines a helper-function `f` and then evaluates to an unnamed function which applies `f` to a range to get all the results. This feels unnecessarily cumbersome.
A single unnamed function seems to be one byte longer though:
```
Switch[#,0,0,1,1,2,1,3,4,_,3#0[#-2]-#0[#-4]]&/@0~Range~#&
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 17 ~~18~~ bytes
```
0ll4i:"y3*5$y-](x
```
Almost direct translation of [Martin's CJam answer](https://codegolf.stackexchange.com/a/71439/36398).
[**Try it online!**](http://matl.tryitonline.net/#code=MGxsNGk6InkzKjUkeS1dKHg&input=MTg)
```
0ll4 % push first four numbers: 0,1,1,4
i: % input n and generate array [1,2,...,n]
" % for loop. Repeat n times
y % copy second-top element from stack
3* % multiply by 3
5$y % copy fifth-top element from stack
- % subtract. This is the next number in the sequence
] % end loop
(x % indexing operation and delete. This gets rid of top three numbers
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 51 bytes
```
:0re{:4<:[0:1:1:4]rm!.|-4=:1&I,?-2=:1&*3-I=.}w,@Sw\
```
This takes a number as input and prints to STDOUT the list, with spaces separating each number.
### Explanation
```
§ Main predicate
:0re{...} § Enumerate integers between 0 and the Input, pass the integer
§ as input to sub-predicate 1
w,@Sw § Write sub-predicate 1's output, then write a space
\ § Backtrack (i.e. take the next integer in the enumeration)
§ Sub-predicate 1
:4< § If the input is less than 4
:[0:1:1:4]rm!. § Then return the integer in the list [0,1,1,4] at index Input
| § Else
-4=:1&I, § I = sub_predicate_1(Input - 4)
?-2=:1&*3-I=. § Output = sub_predicate_1(Input - 2) * 3 - I
```
The cut `!` in the first rule of sub-predicate 1 is necessary so that when we backtrack (`\`), we don't end up in an infinite loop where the interpreter will try the second rule for an input less than 4.
[Answer]
# Mathematica, 41 bytes
```
LinearRecurrence[{0,3,0,-1},{0,1,1,4},#]&
```
[Answer]
# Groovy, 50 Bytes
```
x={a,b=0,c=1,d=1,e=4->a<0?:[b,x(a-1,c,d,e,3*d-b)]}
```
This defines the function x, which takes in n as it's first argument and has the base case of the first four numbers in the Fibocas sequence as default arguments for the rest of the function.
a here is n. b, c, d, and e are the next four elements in the sequence.
It decrements n and recurses until n is less than zero-- when it recurses, it adds on to the ultimate return value the first element in its current sequence. The new values for the next four elements in the sequence are given to the recursive call-- the last three elements are shifted over to be the first three, and a new fourth element is generated from two of the previous elements using 3\*d-b.
It delimits new values with list nestings, as groovy can return multiple values by stuffing them into a list-- so each call returns the current first element and the result of recursion, which will be its own list.
[Answer]
# C++ Template Meta Programming, 130 bytes
```
template<int X>struct L{enum{v=3*L<X-2>::v-L<X-4>::v};};
#define D(X,A) template<>struct L<X>{enum{v=A};};
D(0,0)D(1,1)D(2,1)D(3,4)
```
Recursive definitions somehow cry for C++TMP, usage:
```
L<x>::v
```
with `x` being the `A(x)` you like.
[Answer]
# [R](https://www.r-project.org/), 55 bytes
```
A=c(0,1,1,4);for(x in 4:scan()+1)A[x]=3*A[x-2]-A[x-4];A
```
[Try it online!](https://tio.run/##K/r/39E2WcNAxxAITTSt0/KLNCoUMvMUTKyKkxPzNDS1DTUdoytibY21gJSuUawuiDKJtXb8b2jxHwA "R – Try It Online")
* -24 bytes thanks to JayCe
[Answer]
# [Pylons](https://github.com/morganthrapp/Pylons-lang), 19
This is a pretty direct translation of Martin's approach.
```
0114{@-4@-33*-,i}=4
```
How it works:
```
0114 # Push 0, 1, 1, 4 to the stack.
{ # Start a for loop.
@-4 # Get the stack element at index -4
@-3 # Get the stack element at index -3
3 # Push 3 to the stack.
* # Multiply the top two elements of the stack.
- # Subtract the top two elements of the stack.
, # Switch to loop iterations.
i # Get command line args.
} # End for loop.
=4 # Discard the top 4 elements of the stack.
```
[Answer]
# [DUP](https://esolangs.org/wiki/DUP), 32 bytes
```
[a:0 1$4[a;1-$a:][1ø3*4ø-]#%%]
```
`[Try it here!](http://www.quirkster.com/iano/js/dup.html)`
An anonymous lambda that leaves a sequence of numbers on the stack. Usage:
```
8[a:0 1$4[a;1-$a:][1ø3*4ø-]#%%]!
```
# Explanation
```
[ {start lambda}
a: {save input number to a}
0 1$4 {base cases to get us started}
[ ][ ]# {while loop}
a;1-$a: {a--, check if a>0}
1ø3*4ø- {3*stack[n-2]-stack[n-4]}
%% {discard top 2 stack items}
] {end lambda}
```
[Answer]
## Python 2, 71 bytes
```
def a(n,x=0,y=1,z=2,w=1,p=0):
if~n:print[x,z][p];a(n-1,y,x+y,w,z+w,~p)
```
This definitely seems too long. However, I was pleased that I got to use the bitwise `not` operator...twice. Once as kind of a parity flip back and forth, and once to terminate the recursion when `n` reaches `-1`.
The variable `p` will always be either `0` or `-1`, so it will alternate between entries `0` or `-1` of the list. (Choosing entry `-1` of a Python list means choosing the last element.)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
ŻÆĿÆḞḂ?€
```
[Try it online!](https://tio.run/##AS0A0v9qZWxsef//xbvDhsS/w4bhuJ7huII/4oKs/8OHxZLhuZgpWf//MCwgNSwgMTg "Jelly – Try It Online")
Close to a literal interpretation of the spec
## How it works
```
ŻÆĿÆḞḂ?€ - Main link. Takes N on the left
Ż - Range from 0 to N
€ - Over each integer k:
? - If:
Ḃ - Condition: k mod 2
ÆĿ - Truthy: kth Lucas number
ÆḞ - Falsey: kth Fibonacii number
```
] |
[Question]
[
Given a string with a multiple people's investment data, find out how much profit/loss they recorded.
The string only contains capital and lowercase letters, like this:
```
AABaBbba
```
Each letter represents a person - a capital letter means buy, a lowercase letter means sell. The price of the stock they are investing in (CGLF) starts at $50. After someone buys, the price goes up 5%. After someone sells the price goes down 5%. You need to figure out how much money each person who participated made/lost.
## Notes:
* The string will always be valid, no selling without first buying. Also, everyone who buys a stock will sell it eventually.
* Your calculations should be accurate to at least 6 decimal places. However, final answers should be rounded to two decimals.
## Test Cases:
**Input:** `AABaBbba`
>
> * A: Buy - $50
> * A: Buy - $52.50
> * B: Buy - $55.125
> * a: Sell - $57.88125
> * B: Buy - $54.9871875
> * b: Sell - $57.736546875
> * b: Sell - $54.8497195313
> * a: Sell - $52.1072335547
>
>
>
* Person A profit: `57.88125+52.1072335547-50-52.50=`7.4884835547
* Person B profit: `57.736546875+54.8497195313-55.125-54.9871875=`2.4740789063
**Output:** `A:7.49,B:2.47` (order doesn't matter, separators not required)
---
**Input:** `DGdg`
>
> * D: Buy - $50
> * G: Buy - $52.50
> * d: Sell - $55.125
> * g: Sell - $52.36875
>
>
>
* Person D profit: `55.125-50=`5.125
* Person G profit: `52.36875-52.50=`-0.13125
**Output:** `D:5.13,G:-.13`
---
**Input:** `ADJdja`
>
> * A: Buy - $50
> * D: Buy - $52.50
> * J: Buy - $55.125
> * d: Sell - $57.88125
> * j: Sell - $54.9871875
> * a: Sell - $52.237828125
>
>
>
* Person A profit: `52.237828125-50=`2.237828125
* Person D profit: `57.88125-52.50=`5.38125
* Person J profit: `54.9871875-55.125=`-0.1378125
**Output:** `A:2.24,D:5.38,J:-.14`
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~34~~ 32 bytes
```
⌊{⍺,2⍕+/-⍵}⌸××50ׯ1×\⍤↓1,1+.05××
```
```
Monadic √ó in Dyalog extended for letters corresponds to the casing
¯1 1 ≡ ×'aA'
1+.05√ó√ó - 1 + 0.05 times the sign (either 1.05 or 0.95)
1, - concat 1 to the front
¯1×\⍤↓ - cumulative product and drop the last element
50√ó - multiply by 50
√ó√ó50... - the sign times that
‚åä{‚ç∫,2‚çï+/-‚çµ}‚å∏ - group (dyadic ‚å∏) by the lowercased input (‚åä)
{‚ç∫,2‚çï+/-‚çµ} - return the left item (the person) concat their rounded total
```
-2 thanks to Ad√°m
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1FPV/Wj3l06Ro96p2rr6z7q3Vr7qGfH4emHp5saHJ5@aL3h4ekxj3qXPGqbbKhjqK1nYAqS@u/2qG3Co96@R13Nj3rXPOrdcmi98aO2iY/6pgYHOQPJEA/PYIVH3S0KaUB11UABIOWmADQbLAjhq6vXAkXmKhSnFiQWJZakKpRkpOYq5OYXpSrkJ5Vl5pcW51T@T1NQd3R0SnRKSkpU5wJyXNxT0sEMRxevlKxEdQA "APL (Dyalog Extended) – Try It Online")
[Answer]
## Java, 277 bytes
```
class c{public static void main(String[]a){double[]m=new double[26];double s=50;for(byte b:a[0].getBytes()){if(b>=97){m[b-97]+=s;s*=.95;}else{m[b-65]-=s;s*=1.05;}}char g=65;for(double k:m){if(k!=0){System.out.println(g+String.format(java.util.Locale.ENGLISH,"%.2f",k));}g++;}}}
```
Ungolfed:
```
class c {
public static void main(String[]a) {
double[] m = new double[26];
double s = 50;
for(byte b : a[0].getBytes()) {
if(b>=97) {
m[b-97]+=s;
s*=.95;
} else {
m[b-65]-=s;
s*=1.05;
}
}
char g=65;
for(double k:m) {
if(k!=0) {
System.out.println(g+String.format(java.util.Locale.ENGLISH,"%.2f",k));
}
g++;
}
}
}
```
[Answer]
# JavaScript (ES7), ~~145~~ 142 bytes
I can't find a shorter way to round out the results...
```
x=>[for(c of(i=50,a={},x))(a[d=c.toUpperCase()]=a[d]||0,c<"["?(a[d]-=i,i*=1.05):(a[d]+=i,i*=.95))]&&Object.keys(a).map(k=>[k,a[k].toFixed(2)])
```
Fun fact: this would only be 101 bytes if not for the rounding requirement:
```
x=>[for(c of(i=50,a={},x))(a[d=c.toUpperCase()]=a[d]||0,c<"["?(a[d]-=i,i*=1.05):(a[d]+=i,i*=.95))]&&a
```
[Answer]
# Python 3, 116 bytes
```
P=50
M={}
for c in input():C=c.upper();u=c>C;u+=~-u;M[C]=M.get(C,0)+P*u;P*=1-u*.05
for k in M:print(k,round(M[k],2))
```
### Ungolfed
```
price = 50
profits = {}
for char in input():
upper = char.upper()
direction = 2 * (char > upper) - 1
profits[upper] = profits.get(upper, 0) + price * direction
price *= 1 - direction * .05
for key in profits:
print(key, round(profits[key], 2))
```
[Answer]
# ARM Thumb-2 (VFP + `printf`, softfp ABI), ~~109~~ 104 bytes
Uses the softfp ABI (default on Android). It won't work on `armhf` Linux. `f7ff fffe` is a 4 byte linker placeholder for `printf`.
Both of these examples must be placed at an address that is **not** a multiple of 4 (but even), and must be in a W+X section because we modify an inline `printf` string in place.
```
b5f8 2100 2234 3a01 b402 d8fc f2c4 0249
ec42 1b10 ed9f 1b11 f810 2b01 b192 3a61
bf48 3220 eb0d 02c2 ed92 5b00 bf47 ee35
5b40 ee00 0b01 ee35 5b00 ee00 0b41 ed82
5b00 e7e9 2641 bc0c b11b a005 7006 f7ff
fffe 3601 2e5a ddf6 bdf8 999a 9999 9999
3fa9 2558 322e 0066
```
Assembly:
```
.syntax unified
.arch armv6t2
// We need VFPv2 for this.
.fpu vfpv2
// We modify an inline string in place, so we need W+X.
.section ".writeable_text","awx",%progbits
.thumb
.globl silly_stocks
.thumb_func
// Must NOT be 4 byte aligned.
// .align 4
// nop
// void silly_stocks(const char *input);
// Follows AAPCS convention.
// input is a null-terminated string in r0.
silly_stocks:
push {r3-r7, lr}
// double buf[26] = {0}
movs r1, #0
movs r2, #26*2
.Lclear_loop:
subs r2, #1
push {r1}
bhi .Lclear_loop
.Lclear_loop_end:
// note: r1 and r2 are zero at this point
// r1:r2 = 0x4049000000000000 = 50.0 double
movt r2, #0x4049
vmov d0, r1, r2
vldr d1, .Lfloat_pool
.Lprocess_loop:
// Loop until the null terminator.
// while (r2 = *input++)
ldrb r2, [r0], #1
cbz r2, .Lprocess_loop_end
// tolower(r2) - 'a'
//
// Specifically, we subtract 'a', and if the char was uppercase,
// it would be negative, triggering the N flag, which is why we
// check the mi condition in the following IT blocks.
subs r2, #'a'
it mi
// if (isupper(r2))
addmi r2, #'a' - 'A'
// Yucky. We can't use proper offsetting with VFP and we need to
// keep the flags for the IT block.
add.w r2, sp, r2, lsl #3
// Behold, the beautiful syntax of VFP/NEON.
// Combine it with a an IT block and you get a 10 letter mnemonic. OwO
vldr.64 d5, [r2]
ittee mi
// if (isupper(r2)) { // Buy
vsubmi.f64 d5, d5, d0 // profit[i] -= d0
vmlami.f64 d0, d0, d1 // stock_price += stock_price * 0.05
// } else { // Sell
vaddpl.f64 d5, d5, d0 // profit[i] += stock_price
vmlspl.f64 d0, d0, d1 // stock_price -= stock_price * 0.05
// } endif
vstr.64 d5, [r2]
b .Lprocess_loop
.Lprocess_loop_end:
movs r6, #'A'
.Lprint_loop:
// Pop the double into r2 and r3. We are using the softfp abi, so
// doubles are passed in integer registers.
pop {r2, r3}
// Only check if the most signicant half of the double is zero.
// Any non-zero double that is 0x00000000xxxxxxxx is denormal.
cbz r3, .Lprint_loop_skip
// Set up an AEABI call to printf.
adr r0, .Lprintf_str
// Instead of %c, store the char directly (that's why we need W+X)
strb r6, [r0]
bl printf
.Lprint_loop_skip:
// Loop from A-Z.
adds r6, #1
cmp r6, #'Z'
ble .Lprint_loop
pop {r3-r7, pc}
// At least for the softfp ABI, doubles are smaller than floats.
// This is because printf takes doubles, not floats, and we need
// to pass them in a register pair.
// So we would need something like this, which is 12 bytes.
// vpop {d0}
// vcvt.f64.f32 d0, s0
// vmov r2, r3, d0
.align 2
.Lfloat_pool:
.double 0.05
.Lprintf_str:
// Our printf string. We modify X directly.
.asciz "X%.2f"
.section ".testsuite_unscored","ax",%progbits
.macro $TEST str
adr r0, 1f
bl puts
adr r0, 1f
bl silly_stocks
movs r0, #'\n'
bl putchar
b 2f
.align 2
1:
.asciz "\str"
.align 2
2:
.endm
.align 2
.globl main
.thumb_func
main:
push {r4, lr}
$TEST "AABaBbba"
$TEST "DGdg"
$TEST "ADJdja"
pop {r4, pc}
```
Decided to take a shot at VFP code in ARM assembly instead of doing something easy (and basically identical to the Java entry) like C or C++.
One of the things I realized the hard way was that ARM actually needs the stack to be 8 byte aligned, or else subtle bugs will occur. Two hours of debugging I am NEVER getting back. üò´
Oddly enough, using doubles is smaller than floats, despite the larger literal pool. This is because the C calling convention mandates that `float`s be promoted to `double` in variadic functions, so we would have to convert to `double` anyways, and that is larger than the 8 bytes for the larger pool.
Output isn't pretty. But the question says "**separators not required**" so I took that in the most literal sense. üòè
```
AABaBbba
A7.49B2.47
DGdg
D5.12G-0.13
ADJdja
A2.24D5.38J-0.14
```
But aside from the `5.12` which is the same rounding error that was mentioned in Python, the results are correct.
# ARM Thumb-2 (VFP + `printf`, softfp ABI, very imprecise), ~~99~~ 96 bytes
This version uses 32-bit x 16-bit fixed point arithmetic.
It lacks the required 6 digits of precision, but for the test cases it products the same results. Interpret it as you wish.
Must be loaded at an address that is not a multiple of 4 for constant pool alignment.
Machine code:
```
b5f8 2100 2534 3d01 b402 d8fc f2c0 0132
4d11 f810 2b01 b172 3a61 bf48 3220 f85d
3032 fb51 f605 bf47 1a5b 4431 440b 1b89
f84d 3032 e7ed 2641 ecbd 0b02 eeba 0bc8
ec53 2b10 b11b a004 7006 f7ff fffe 3601
2e5a ddf1 bdf8 cccc 0ccc 2558 322e 0066
```
Assembly:
```
.syntax unified
.arch armv6t2
// We need VFPv2 for this.
.fpu vfpv2
// We modify an inline string in place, so we need W+X.
.section ".writeable_text_fixed","awx",%progbits
.thumb
.globl silly_stocks_fixed
.thumb_func
// Must not be 4 byte aligned.
// .align 4
// nop
// void silly_stocks_fixed(const char *input);
// Follows AAPCS convention.
// input is a null-terminated string in r0.
silly_stocks_fixed:
push {r3-r7, lr}
// We use double the width because we need to keep alignment.
// int64_t buf[26] = {0}
movs r1, #0
movs r5, #26*2
.Lclear_loop_fixed:
subs r5, #1
push {r1}
bhi .Lclear_loop_fixed
.Lclear_loop_end_fixed:
// Load our float constants from the pool.
movt r1, #0x32 // 0x00320000 = 50.0 in 16-bit fixed point
ldr r5, .L.05.fix32 // 0x0ccccccc = 0.05 in 32-bit fixed point
.Lprocess_loop_fixed:
// Loop until the null terminator.
// while (r2 = *input++)
ldrb r2, [r0], #1
cbz r2, .Lprocess_loop_end_fixed
// tolower(r2) - 'a'
//
// Specifically, we subtract 'a', and if the char was uppercase,
// it would be negative, triggering the N flag, which is why we
// check the mi condition in the following IT blocks.
subs r2, #'a'
it mi
// if (isupper(r2))
addmi r2, #'a' - 'A'
ldr r3, [sp, r2, lsl #3]
// fixed point multiply:
// x<fixA> = (y<fixB> * z<fixC>) >> (B + C - A)
// tmp<fix16> = (stock_price<fix16> * 0.05<fix32>) >> 32
smmul r6, r1, r5 // r6 = stock_price * 0.05
ittee mi
// if (isupper(r2)) { // Buy
submi r3, r1 // profit[i] -= stock_price
addmi r1, r6 // stock_price += stock_price * 0.05
// } else { // Sell
addpl r3, r1 // profit[i] += stock_price
subpl r1, r6 // stock_price -= stock_price * 0.05
// } endif
str r3, [sp, r2, lsl #3]
b .Lprocess_loop_fixed
.Lprocess_loop_end_fixed:
movs r6, #'A'
.Lprint_loop_fixed:
// Pop the result into d0 (also cleaning the stack)
vpop {d0}
// Convert from fix16 to double
vcvt.f64.s32 d0, d0, #16
// Move the double result into r2 and r3. This is for the softfp ABI
// which passes floating point values in registers.
vmov r2, r3, d0
// Only check if the most signicant half of the double is zero.
// Any non-zero double that is 0x00000000xxxxxxxx is denormal.
cbz r3, .Lprint_loop_skip_fixed
// Set up an AEABI call to printf.
adr r0, .Lprintf_str_fixed
// Instead of %c, store the char directly (that's why we need W+X)
strb r6, [r0]
bl printf
.Lprint_loop_skip_fixed:
// Loop from A-Z.
adds r6, #1
cmp r6, #'Z'
ble .Lprint_loop_fixed
pop {r3-r7, pc}
// 0.05 in fix32.
.L.05.fix32:
.word 0x0ccccccc
// Our printf string. We replace the X when we use it.
.Lprintf_str_fixed:
.asciz "X%.2f"
.section ".testsuite_unscored","ax",%progbits
.macro $TEST str
adr r0, 1f
bl puts
adr r0, 1f
bl silly_stocks_fixed
movs r0, #'\n'
bl putchar
b 2f
.align 2
1:
.asciz "\str"
.align 2
2:
.endm
.align 2
.globl main
.thumb_func
main:
push {r4, lr}
$TEST "AABaBbba"
$TEST "DGdg"
$TEST "ADJdja"
pop {r4, pc}
```
For the reference, here is the results for float vs fixed point at 6 digits of precision.
```
AABaBbba
float: A:7.488484,B:2.474079,
fixed: A:7.488434,B:2.474060,
DGdg
float: D:5.125000,G:-0.131250,
fixed: D:5.124969,G:-0.131256,
ADJdja
float: A:2.237828,D:5.381250,J:-0.137812,
fixed: A:2.237808,D:5.381226,J:-0.137817,
```
[Answer]
# [Perl 5](https://www.perl.org/) `-MList::Util=pairmap -F`, 80 bytes
```
$p=50;map{$k{uc$_}+=$q=95>ord?-$p:$p;$p-=$q/20}@F;pairmap{printf"$a:%.2f ",$b}%k
```
[Try it online!](https://tio.run/##LY1BC4IwGEDv/oqITyxKW8IObaxSxCDq2DlmZixNv@Y6iX@9ZdHpwePBw6uuqLWAghL@kNhB2b0ucO5nAp5iRdeNzjc@IAPkgP4gFyHptylHqfS3R61qU4xBMjcIi9F4Dlnvlpb/vOdxtxSTKbdRFMs4y6ST7PKbEyX7/C7fDRrV1K31jzQgSzLwoFrD2MmoSvwH1q/SDw "Perl 5 – Try It Online")
[Answer]
# Javascript (ES6, Node.js), 136 bytes
## Source
```
s=>(m=50,a={},[...s].map(p=>(u=p.toUpperCase(),n=p==u?1:-1,a[u]=(a[u]||0)-m*n,m*=1+n/20)),Object.keys(a).map(k=>a[k]=a[k].toFixed(2)),a)
```
## Explanation
```
f=s=>( // (s)tring
m=50, // stock value (m)oney
a={}, // (a)ll people
[...s].map(
p=>(
u=p.toUpperCase(), // (u)ppercase: used to group buys and sells for each person
n=p==u?1:-1, // sig(n): 1 for buy, -1 for sell
a[u]=(a[u]||0)-m*n, // adjust balance with stock value and sign
m*=1+n/20 // adjust stock value
)
),
Object.keys(a).map(k=>a[k]=a[k].toFixed(2)), // round profits
a // return profits
)
```
## Proof
```
f=s=>(m=50,a={},[...s].map(p=>(u=p.toUpperCase(),n=p==u?1:-1,a[u]=(a[u]||0)-m*n,m*=1+n/20)),Object.keys(a).map(k=>a[k]=a[k].toFixed(2)),a)
const TESTS = [
['AABaBbba',{A:'7.49',B:'2.47'}],
['DGdg',{D:'5.13',G:'-0.13'}],
['ADJdja',{A:'2.24',D:'5.38',J:'-0.14'}]
]
TESTS.forEach(([input,expected])=>{
console.log(input);
console.log(expected);
console.log(f(input))
});
```
[Answer]
# Japt, ~~91~~ 84 bytes
```
A=[]J=50¡AhD=Xc %H(X<'_?[AgD ª0 -JJ*=1.05]:[AgD +JJ*=.95] g};A£X©[Y+I d X*L r /L]} f
```
Based on my JS answer. [Try it online!](http://ethproductions.github.io/japt?v=master&code=QT1bXUo9NTChQWhEPVhjICVIKFg8J18/W0FnRCCqMCAtSkoqPTEuMDVdOltBZ0QgK0pKKj0uOTVdIGd9O0GjWKlbWStJIGQgWCpMIHIgL0xdfSBm&input=IkFBQmFCYmJhIg==)
[Answer]
# [J](http://jsoftware.com/), 64 bytes
```
tolower(~.@[,.(0j2":_50*+/)/.)](]*1*/\@}:@,1+0.05*])_1+2*91>3&u:
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/S/Jz8stTizTq9ByidfQ0DLKMlKziTQ20tPU19fU0YzVitQy19GMcaq0cdAy1DfQMTLViNeMNtY20LA3tjNVKrf5rcqUmZ@QrpCmoOzo6JTolJSWqg0XU1eESLu4p6RiCji5eKVlAtVz/AQ "J – Try It Online")
] |
[Question]
[
*Inspired by [this](http://chat.stackexchange.com/transcript/240?m=26561376#26561376) conversation in chat.*
Your goal in this challenge is to emulate a ninja and count how many deaths he has left.
## Specs
You ninja starts out with 9 deaths left. He also gets an integral starting health as an input.
Then, he takes as input a list of events in his life that alter his health. These can be negative, positive, or zero integers.
At any point, if his health reaches at or below zero, he loses a life and his health goes back to the starting health.
Your program should report the number of deaths he has left. If he has zero or less left, you should output `dead` instead.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in **bytes** wins!
## Test Cases
```
3, [] -> 9
100, [-20, 5, -50, 15, -30, -30, 10] -> 8
10, [-10, -10, -10, -10] -> 5
10, [-10, -10, -10, -10, -10, -10, -10, -10, -10] -> dead
0, [] -> dead
0, [1] -> dead
100, [10, -100] -> 9
```
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), ~~30~~ ~~28~~ 26 [bytes](https://github.com/DennisMitchell/jelly/blob/master/docs/code-page.md)
```
»0o⁴+
;@ñ\<1S_9«0N“dead”×?
```
[Try it online!](http://jelly.tryitonline.net/#code=wrswb-KBtCsKO0DDsVw8MVNfOcKrME7igJxkZWFk4oCdw5c_&input=&args=Wy0yMCwgNSwgLTUwLCAxNSwgLTMwLCAtMzAsIDEwXQ+MTAw)
### How it works
```
;@ñ\<1S_9«0N“dead”×? Main link. Input: e (events), h (initial health)
;@ Prepend h to e.
ñ\ Reduce the resulting array by the next, dyadic link.
This returns the array of intermediate results.
<1 Check each intermediate value for non-positivity.
S Sum. This calculates the number of event deaths.
_9 Subtract 9 from the result.
«0 Take the minimum of the result and 0. This yields 0 if no
lives are left, the negated amount of lives otherwise.
? Conditional:
× If the product of the minimum and h is non-zero:
N Return the negated minimum.
“dead” Else, return "dead".
»0o⁴+ Dyadic helper link. Arguments: x, y
»0 Take the maximum of x and 0.
This yields x if x > 0 and 0 otherwise.
o⁴ Take the logical OR of the result and the second input (h).
+ Take the sum of the result and y.
```
[Answer]
# Japt, ~~40~~ ~~39~~ 32 bytes
```
U¬©(9-Vf@T=X+(T¬²ªU)<1} l)¬²ª`Ü%
```
[Try it online!](http://ethproductions.github.io/japt?v=master&code=VaypKDktVmZAVD1YKyhUrLKqVSk8MX0gbCmssqpg3CU=&input=MTAsIFstMTAsIC0xMCwgLTEwLCAtMTAsIC0xMCwgLTEwLCAtMTAsIC0xMCwgLTEwXQ==)
### How it works
While trying to golf this last night (away from a computer, no less), I ran across an interesting replacement for `>0`: `¬`. On numbers, this takes the square root, which returns `NaN` for negative numbers. `NaN` is falsy, so this returns exactly the same truthily/falsily as `>0`.
Extending this trick a little further, we can reset T to U iff it's `>=0` in only five bytes: `T¬²ªU`. How does this work? Let's take a look:
```
T ¬ ² ªU
sqrt square if falsy, set to U (JS's || operator)
4 2 4 4
7 ~2.646 7 7
0 0 0 U
-4 NaN NaN U
-7 NaN NaN U
```
As you can see, `T¬²` returns `NaN` if `T` is negative; otherwise, it returns `T`. Since `NaN` and `0` are both falsy, this provides an easy way to reset the ninja's health with `ªU`. This trick is also used to return the ninja's lives left if that number is positive, or `"dead"` if negative.
Putting this all together:
```
// Implicit: U = starting health, V = events, T = 0
U© // If U is positive,
Vf@ } // Filter out the items X in V that return truthily from this function:
T=X+ // Set T to X plus
(T¬²ªU) // If T is positive, T; otherwise, U.
// This keeps a running total of the ninja's health, resetting upon death.
<1 // Return (T < 1).
9- l) // Take the length of the resulting array and subtract from 9.
// This returns the number of lives the ninja has left.
¬² // If the result is negative, set it to NaN.
ª`Ü% // If the result of EITHER of the two parts above is falsy, return "dead".
// (`Ü%` is "dead" compressed.)
// Otherwise, return the result of the middle part (lives left).
// Implicit: output last expression
```
If the input is guaranteed to be non-negative, or even positive, we can golf of 1 or 4 bytes:
```
U©(9-Vf@T=X+(T¬²ªU)<1} l)¬²ª`Ü% // U is non-negative
9-Vf@T=X+(T¬²ªU)<1} l)¬²ª`Ü% // U is positive
```
[Answer]
## JavaScript ES6, ~~62 60~~ 58 bytes
*Saved 4 bytes thanks to @ETHproductions*
```
(a,b,d=9,l=a)=>b.map(i=>l=l+i<1?d--&&a:l+i,a)|d<1?"dead":d
```
[Try it online](http://vihanserver.tk/p/esfiddle/?code=f%3D%20(a%2Cb%2Cd%3D9)%3D%3E(b.reduce((l%2Ci)%3D%3El%2Bi%3C1%3F(d--%2Ca)%3Al%2Bi%2Ca)%2Cd%3C1%3F%22dead%22%3Ad)%3B%0A%0Af(%20100%2C%20%5B-20%2C%205%2C%20-50%2C%2015%2C%20-30%2C%20-30%2C%2010%5D%20)) (All browsers work)
## Explanation
```
(a,b, // a = 1st input, b = 2nd input
d=9)=> // Lives counter
(b.reduce((l,i)=> // Loop through all the health changes
l+i<1 // If (health + health change) < 1
?(d--,a) // Decrease life, reset health
:l+i // Return new health
,a) // Sets starting health to `a`
,d<1? // Lives is less than 1
"dead":d); // Output "dead" otherwise lives left
```
[Answer]
# CJam, 35 bytes
```
q~_@{+_1<{W$}&}/](\,_A<@*A@-"dead"?
```
[Try it online!](http://cjam.tryitonline.net/#code=cX5fQHsrXzE8e1ckfSZ9L10oXCxfQTxAKkFALSJkZWFkIj8&input=Wy0yMCA1IC01MCAxNSAtMzAgLTMwIDEwXSAxMDA)
[Answer]
## Haskell, ~~81~~ ~~77~~ 75 bytes
```
p l i h a|l<1="dead"|i<1=p(l-1)h h a|[]<-a=show l|x:y<-a=p l(i+x)h y
p 10 0
```
Usage example: `p 10 0 100 [-20, 5, -50, 15, -30, -30, 10]` -> `"8"`
[Answer]
# Pyth, 32
```
u+?>GZG&=hZQH+E0Q?&Q<Z9-9Z"dead
```
Note that there is a leading space. This probably isn't the best approach, but it was the first thing that came to mind. It reduces over input by adding the values to the ninja's health, and incrementing a counter and resetting the health when it drops below zero. We add a zero to the end of the list to count if the last change kills the ninja, and then just do some checking to see if the ninja is dead. The zero starting health case is hard coded.
[Test Suite](https://pyth.herokuapp.com/?code=%20u%2B%3F%3EGZG%26%3DhZQH%2BE0Q%3F%26Q%3CZ9-9Z%22dead&input=3%0A%5B%5D&test_suite=1&test_suite_input=3%0A%5B%5D%0A100%0A%5B-20%2C%205%2C%20-50%2C%2015%2C%20-30%2C%20-30%2C%2010%5D%0A10%0A%5B-10%2C%20-10%2C%20-10%2C%20-10%5D%0A10%0A%5B-10%2C%20-10%2C%20-10%2C%20-10%2C%20-10%2C%20-10%2C%20-10%2C%20-10%2C%20-10%5D%0A0%0A%5B%5D%0A0%0A%5B1%5D%0A100%0A%5B10%2C%20-100%5D&debug=0&input_size=2)
[Answer]
# MATL, 32
```
9yi"@+t0>~?x1-y]]g*wxt0>~?x'dead'
```
## Explanation
```
9 # push 9
y # duplicate 2nd value to top (there is none -> get it from input first)
i # get input and push it
```
The stack now looks like this (for input `100, [-20, 5, -50, 15, -30, -30, 10]`):
```
100 9 100 [-20, 5, -50, 15, -30, -30, 10]
reload deaths health
value left
```
Pop the array and loop
```
" ] # loop
@+ # add to health
t0>~? ] # if health is zero or less
x1-y # delete health counter, decrement life counter, reload health
```
If the health is zero, set death counter to zero. Special case handling for `initial health = 0`.
```
g # health to bool
* # multiply with death counter
```
Delete the reload value from stack
```
wx
```
If the death counter is zero or less, delete it and print 'dead' instead.
```
t0>~?x'dead'
```
[Answer]
# [TeaScript](http://github.com/vihanb/teascript), ~~36 34~~ 31 bytes
```
yR#l+i<1?e─·x:l+i,x);e≥0?e:D`Ü%
```
Similar to my JavaScript answer. the last 4 characters are the decompression of the string "dead".
TeaScript's online interpreter doesn't support array input so you're going to need to open the console, and run this by typing:
```
TeaScript( `yR#l+i<1?(e─,x):l+i,x);─e>0?e:D\`Ü%` ,[
10, [-10, -10, -10, -10]
],{},TEASCRIPT_PROPS);
```
### Explanation
```
// Implicit: x = 1st input, y = 2nd input
yR# // Reduce over 2nd input
l+i<1? // If pending health is less then 1
(e─,x): // then, decrease life counter, reset health
l+i // else, modify health
,x); // Set starting health
─e>0? // Ninja is alive?
e: // Output lives left
D`Ü% // Decompress and output "dead"
```
[Answer]
## Python 2.7, 82 66 55 106 bytes
*Thanks to @RikerW for -16 bytes.:(*
*Thanks to @Maltysen for -11 bytes. :(*
```
i=input;h=[i()]*9;d=i()
if 0==h[0]:print'dead';exit()
for x in d:
h[0]+=x
if h[0]<=0:h=h[1:]
y=len(h)
print['dead',y][y!=0]
```
First type health, then enter, then events in list form.
[Answer]
## C# 207
```
class P{static void Main(string[]a){int h=int.Parse(a[0]),H=h,l=9,i=1;if(a.Length!=1){for(;i<a.Length;i++){H+=int.Parse(a[i]);if(H<=0){l--;H=h;}}}System.Console.Write(h==0?"dead":l<=0?"dead":l.ToString());}}
```
Takes the input through argument stream. The first argument is the amount of health and all the rest is the list of events.
Readable / ungolfed version
```
class Program
{
static void Main(string[]a)
{
int health = int.Parse(a[0]);
int Health = health;
int lives = 9;
if(a.Length!=1)
{
for (int i = 1;i < a.Length;i++)
{
Health += int.Parse(a[i]);
if (Health <= 0)
{
lives--;
Health = health;
}
}
}
System.Console.Write(health == 0 ? "dead" : lives <= 0 ? "dead" : lives.ToString());
}
}
```
Examples:
* CSharp.exe 3 => 9
* CSharp.exe 100 -20 5 -50 15 -30 -30 10 => 8
(Psst.) CSharp.exe is name used as an example. You have to call like this in reality: [program\_name.exe] arguments, without the square parentheses.
] |
[Question]
[
The [Cheela](http://aliens.wikia.com/wiki/Cheela) (from the book [*Dragon's Egg*](https://en.wikipedia.org/wiki/Dragon%27s_Egg) by Robert L. Forward) are creatures that live on the surface of a neutron star. Their body is flat and circular with twelve eyes on the perimeter, so they naturally use a base-12 numbering system.
Among the Cheela, care of the hatchlings and education of the young are tasks carried out by the Old Ones. Since young Cheela need to be taught how to multiply, the Old Ones could use a multiplication table.
Your task is to produce a `12`x`12` multiplication table in base `12`, like the following. Uppercase letters `A` and `B` are used for digits corresponding to decimal `10` and `11` respectively.
```
1 2 3 4 5 6 7 8 9 A B 10
2 4 6 8 A 10 12 14 16 18 1A 20
3 6 9 10 13 16 19 20 23 26 29 30
4 8 10 14 18 20 24 28 30 34 38 40
5 A 13 18 21 26 2B 34 39 42 47 50
6 10 16 20 26 30 36 40 46 50 56 60
7 12 19 24 2B 36 41 48 53 5A 65 70
8 14 20 28 34 40 48 54 60 68 74 80
9 16 23 30 39 46 53 60 69 76 83 90
A 18 26 34 42 50 5A 68 76 84 92 A0
B 1A 29 38 47 56 65 74 83 92 A1 B0
10 20 30 40 50 60 70 80 90 A0 B0 100
```
The output shoud be printed on screen. The format should be as follows:
1. Numbers should be aligned to the right within each column.
2. Leading spaces before the first column, trailing spaces after the last column, or a trailing new line after the last row are allowed.
3. Separation between columns can be one space (as shown above) or more than one space, but the number of spaces should be consistent between columns. To measure column separation, consider that displayed numbers include any leading spaces that may have been necessary fo fulfill requirement 1 (so each number occupies three characters, the first of which may be spaces). For example, the table with two-space separation would be as follows:
```
1 2 3 4 5 6 7 8 9 A B 10
2 4 6 8 A 10 12 14 16 18 1A 20
3 6 9 10 13 16 19 20 23 26 29 30
4 8 10 14 18 20 24 28 30 34 38 40
5 A 13 18 21 26 2B 34 39 42 47 50
6 10 16 20 26 30 36 40 46 50 56 60
7 12 19 24 2B 36 41 48 53 5A 65 70
8 14 20 28 34 40 48 54 60 68 74 80
9 16 23 30 39 46 53 60 69 76 83 90
A 18 26 34 42 50 5A 68 76 84 92 A0
B 1A 29 38 47 56 65 74 83 92 A1 B0
10 20 30 40 50 60 70 80 90 A0 B0 100
```
Computer storage on a neutron star is really expensive, so your code should use as few bytes as possible.
## Extended challenge and bonus
Ideally your code should be reused in other parts of the universe, where other numbering systems may be in use. To that end, the challenge is optionally extended as follows: Your code accepts a number `N` as input and generates an `N`x`N` multiplication table in base `N`, with the above format.
Input may be from keyboard or as a function argument. The program or function should work for `2` ≤ `N` ≤ `36`, using as digits the first `N` characters of the sequence `0`, `1`, ..., `9`, `A`, `B`, ..., `Z` (uppercase letters)
This extended challenge is optional. If you follow this route, take 20% off your byte count (no need to round to an integer number).
[Answer]
# Pyth, 27 \* 0.8 = 21.6
```
VSQsm.[\ 4jkXj*dNQrT99rG1SQ
```
Try it online: [Demonstration](https://pyth.herokuapp.com/?code=VSQsm.%5B%5C%204jkXj%2AdNQrT99rG1SQ&input=12&debug=0)
### Explanation:
```
VSQsm.[\ 4jkXj*dNQrT99rG1SQ implicit: Q = input number
VSQ for N in [1, 2, ..., Q]:
m SQ map each number d in [1, 2, ..., Q] to:
*dN N * d
j Q in base Q
X rT99rG1 replace the numbers [10, 11, ..., 98] with "A...Z"
jk join to a string
.[\ 4 prepend spaces, so that the string has a length of 4
s join all strings and print
```
[Answer]
## CJam, 33 \* 0.8 = 26.4 bytes
```
ri:C,:)_ff{*Cb{_9>{'7+}&}%4Se[}N*
```
[Test it here.](http://cjam.aditsu.net/#code=ri%3AC%2C%3A)_ff%7B*Cb%7B_9%3E%7B'7%2B%7D%26%7D%254Se%5B%7DN*&input=32)
This uses the minimum required separation.
### Explanation
```
ri:C e# Read input, convert to integer, store in C.
,:) e# Get range [1 2 ... C].
_ff{ e# 2D-map over all repeated pairs from that range...
*Cb e# Multiply, convert to base C.
{ e# Map over the digits...
_9> e# Check if the digit is greater than 9.
{'7+}& e# If so, add the digit to the character "7", to get "A" to "Z".
}%
4Se[ e# Pad the digits with spaces from the left, to 4 elements.
}
N* e# Join with linefeeds.
```
Table for input `22` (the largest that fits in the post without a horizontal scrollbar):
```
1 2 3 4 5 6 7 8 9 A B C D E F G H I J K L 10
2 4 6 8 A C E G I K 10 12 14 16 18 1A 1C 1E 1G 1I 1K 20
3 6 9 C F I L 12 15 18 1B 1E 1H 1K 21 24 27 2A 2D 2G 2J 30
4 8 C G K 12 16 1A 1E 1I 20 24 28 2C 2G 2K 32 36 3A 3E 3I 40
5 A F K 13 18 1D 1I 21 26 2B 2G 2L 34 39 3E 3J 42 47 4C 4H 50
6 C I 12 18 1E 1K 24 2A 2G 30 36 3C 3I 42 48 4E 4K 54 5A 5G 60
7 E L 16 1D 1K 25 2C 2J 34 3B 3I 43 4A 4H 52 59 5G 61 68 6F 70
8 G 12 1A 1I 24 2C 2K 36 3E 40 48 4G 52 5A 5I 64 6C 6K 76 7E 80
9 I 15 1E 21 2A 2J 36 3F 42 4B 4K 57 5G 63 6C 6L 78 7H 84 8D 90
A K 18 1I 26 2G 34 3E 42 4C 50 5A 5K 68 6I 76 7G 84 8E 92 9C A0
B 10 1B 20 2B 30 3B 40 4B 50 5B 60 6B 70 7B 80 8B 90 9B A0 AB B0
C 12 1E 24 2G 36 3I 48 4K 5A 60 6C 72 7E 84 8G 96 9I A8 AK BA C0
D 14 1H 28 2L 3C 43 4G 57 5K 6B 72 7F 86 8J 9A A1 AE B5 BI C9 D0
E 16 1K 2C 34 3I 4A 52 5G 68 70 7E 86 8K 9C A4 AI BA C2 CG D8 E0
F 18 21 2G 39 42 4H 5A 63 6I 7B 84 8J 9C A5 AK BD C6 CL DE E7 F0
G 1A 24 2K 3E 48 52 5I 6C 76 80 8G 9A A4 AK BE C8 D2 DI EC F6 G0
H 1C 27 32 3J 4E 59 64 6L 7G 8B 96 A1 AI BD C8 D3 DK EF FA G5 H0
I 1E 2A 36 42 4K 5G 6C 78 84 90 9I AE BA C6 D2 DK EG FC G8 H4 I0
J 1G 2D 3A 47 54 61 6K 7H 8E 9B A8 B5 C2 CL DI EF FC G9 H6 I3 J0
K 1I 2G 3E 4C 5A 68 76 84 92 A0 AK BI CG DE EC FA G8 H6 I4 J2 K0
L 1K 2J 3I 4H 5G 6F 7E 8D 9C AB BA C9 D8 E7 F6 G5 H4 I3 J2 K1 L0
10 20 30 40 50 60 70 80 90 A0 B0 C0 D0 E0 F0 G0 H0 I0 J0 K0 L0 100
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 42\*.8 = 33.6
### Disclaimer
*Since the creator of the language and the author of the challenge are the same, this answer is not eligible for winning*.
*For a discussion on whether this restriction is necessary or not, see [this meta question](http://meta.codegolf.stackexchange.com/questions/7760/can-you-post-a-challenge-and-answer-in-a-language-you-designed).*
### Code
```
iXK:t!*Y)KYAZ{'(?<=^0*)0'32cYXZc32hK4*[]e!
```
This uses the minimum separation.
### Example
Octal multiplication table
```
>> matl
> iXK:t!*Y)KYAZ{'(?<=^0*)0'32cYXZc32chK4*[]e!
>
> 8
1 2 3 4 5 6 7 10
2 4 6 10 12 14 16 20
3 6 11 14 17 22 25 30
4 10 14 20 24 30 34 40
5 12 17 24 31 36 43 50
6 14 22 30 36 44 52 60
7 16 25 34 43 52 61 70
10 20 30 40 50 60 70 100
```
### Explanation
```
i % input number, say n
XK % copy to clipboard K
: % vector 1, 2, ... n
t!* % generate table: duplicate, transpose and multiply with broadcasting
Y) % linearize into column array
KYA % paste n from clipboard K. Convert to that base
Z{ % cell array of rows from array
'(?<=^0*)0' % string literal for regexp replacement: find leading zeros
32c % space character (for regexp replacement)
YX % regexp replacement
Zc % join cell array of strings into single string
32 % code for space character. Conversion to char happens automatically
h % concatenate horizontally
K4*[]e! % paste n and multiply by 4. Reshape into 2D char array with 4*n columns
```
### Edit: [Try it online!](http://matl.tryitonline.net/#code=aVhLOnQhKlg6S1lBWnsnKD88PV4wKikwJzMyY1lYWmMzMmhLNCplIQ&input=MTI)
To run in the online compiler (as of February 19, 2016), change `Y)` to `X:`, and remove `[]`. This is to adapt to changes that have been made to the language since this challenge was posted.
[Answer]
# Bash + BSD utilities, 36
```
echo Co{1..12}d{1..12}*p|dc|rs -j 12
```
Works out-of-the-box on OS X. `rs` may need to be installed on Linux systems.
* Bash expands `Co{1..12}d{1..12}*p` to `Co1d1*p Co1d2*p Co1d3*p ... Co1d12*p ... Co12d12*p`.
* This is a `dc` expression that generates the required terms. `Co` sets output base to 12. `d` is used as a separator between numbers instead of a space, so no escape is required in the brace expansion. `d` actually duplicates the top of stack, but this is effectively ignored and discarded.
* The output from `dc` is a single space-separated line. `rs` reshapes this to a 12x12 array. `-j` right-justifies each term.
[Answer]
# Pyth, 36 bytes
```
Km+1dUJ12rjbmjkm.[\ 4j""m.Hbj*dkJKK1
```
[Try it here.](http://pyth.herokuapp.com/?code=Km%2B1dUJ12rjbmjkm.%5B+4j%22%22m.Hbj*dkJKK1&debug=0)
[Answer]
## Python, ~~153~~ ~~147~~ 132 bytes \* 0.8 = 105.6
```
def p(b):
f=lambda n:(n>=b and f(n/b)or'')+chr((48,55)[n%b>9]+n%b)
for i in range(b*b):print'%4s\n'[:3+(~i%b<1)]%f(~(i%b)*~(i/b)),
```
Down to 132 bytes thanks to the advice of Tim Pederick! :)
[Answer]
# CJam, ~~38~~ ~~33~~ ~~32~~ 38 \* (.8) = 30.4 bytes
```
qi:D,:):L{Lf*{Db{_9>{55+c}&}%4Se[}%N}%
```
[Try it here.](http://cjam.aditsu.net/#code=qi%3AD%2C%3A)%3AL%7BLf*%7BDb%7B_9%3E%7B55%2Bc%7D%26%7D%254Se%5B%7D%25N%7D%25&input=12)
(Looks pretty similar to Martin's now.)
```
qi:D,:):L e# Generate list of [1...input]
{Lf* e# Take each number in that list and multiply it by the same list ([[1,2,3,..,input][2,4,6,...,input],...})
{Db{_9>{55+c}&}% e# Convert each product to base input. If a digit value is >= 10 add 55 and convert to char, to make it a letter.
4Se[}%N}% e# Pad each number with spaces to length 4. Put a newline after each row.
```
[Answer]
# [Perl 6](http://perl6.org), 60 bytes -20% = 48 bytes
```
{.put for (1..$_ X*1..$_)».base($_)».fmt('%3s').rotor($_)} # 60-20% = 48
# ^-----------^ produce a list of two cross multiplied lists
# ^--------^ convert each to base N
# format each to 3 spaces ^----------^
# split the list into N element chunks ^--------^
#^-------^ print each of those on their own line with spaces between elements
```
( This is almost exactly how I would write it even if I wasn't trying to get it as short as I could )
Usage:
```
{...}(2)
1 10
10 100
```
```
my &code = {...}
code 2;
1 10
10 100
```
```
{...}(12);
1 2 3 4 5 6 7 8 9 A B 10
2 4 6 8 A 10 12 14 16 18 1A 20
3 6 9 10 13 16 19 20 23 26 29 30
4 8 10 14 18 20 24 28 30 34 38 40
5 A 13 18 21 26 2B 34 39 42 47 50
6 10 16 20 26 30 36 40 46 50 56 60
7 12 19 24 2B 36 41 48 53 5A 65 70
8 14 20 28 34 40 48 54 60 68 74 80
9 16 23 30 39 46 53 60 69 76 83 90
A 18 26 34 42 50 5A 68 76 84 92 A0
B 1A 29 38 47 56 65 74 83 92 A1 B0
10 20 30 40 50 60 70 80 90 A0 B0 100
```
```
{...}(18);
1 2 3 4 5 6 7 8 9 A B C D E F G H 10
2 4 6 8 A C E G 10 12 14 16 18 1A 1C 1E 1G 20
3 6 9 C F 10 13 16 19 1C 1F 20 23 26 29 2C 2F 30
4 8 C G 12 16 1A 1E 20 24 28 2C 2G 32 36 3A 3E 40
5 A F 12 17 1C 1H 24 29 2E 31 36 3B 3G 43 48 4D 50
6 C 10 16 1C 20 26 2C 30 36 3C 40 46 4C 50 56 5C 60
7 E 13 1A 1H 26 2D 32 39 3G 45 4C 51 58 5F 64 6B 70
8 G 16 1E 24 2C 32 3A 40 48 4G 56 5E 64 6C 72 7A 80
9 10 19 20 29 30 39 40 49 50 59 60 69 70 79 80 89 90
A 12 1C 24 2E 36 3G 48 50 5A 62 6C 74 7E 86 8G 98 A0
B 14 1F 28 31 3C 45 4G 59 62 6D 76 7H 8A 93 9E A7 B0
C 16 20 2C 36 40 4C 56 60 6C 76 80 8C 96 A0 AC B6 C0
D 18 23 2G 3B 46 51 5E 69 74 7H 8C 97 A2 AF BA C5 D0
E 1A 26 32 3G 4C 58 64 70 7E 8A 96 A2 AG BC C8 D4 E0
F 1C 29 36 43 50 5F 6C 79 86 93 A0 AF BC C9 D6 E3 F0
G 1E 2C 3A 48 56 64 72 80 8G 9E AC BA C8 D6 E4 F2 G0
H 1G 2F 3E 4D 5C 6B 7A 89 98 A7 B6 C5 D4 E3 F2 G1 H0
10 20 30 40 50 60 70 80 90 A0 B0 C0 D0 E0 F0 G0 H0 100
```
[Answer]
# JavaScript (ES6) 84 (105-20%)
The obvious way, to begin with.
```
n=>{for(o=i=``;i++<n;o+=`
`)for(j=0;j++<n;)o+=(` `+(i*j).toString(n)).slice(-4).toUpperCase();alert(o)}
```
Notes
* It's a pity js toString produce lowercase letters
* `alert` is not the best way to output the table, but it's the shorter, as there is an explicit request to "display on screen"
* Just returning the value would be a couple bytes shorter.
**Less golfed**
```
n=>{
for(o='', i=0; i++<n; o+='\n')
for(j=0;j++<n;)
o+=(' '+(i*j).toString(n)).slice(-4).toUpperCase()
alert(o)
}
```
[Answer]
## Python 3, 126 - 20% = 100.8 bytes
The outer function, `t`, is the one that actually prints the multiplication table. The inner function, `i`, does the conversion of a number to a base from 2 to 36.
```
def t(b):
i=lambda n:(n>=b and i(n//b)or'')+chr(n%b+[48,55][n%b>9]);R=range(b)
for r in R:print(*('%3s'%i(~r*~c)for c in R))
```
Hat tip to Boomerang for [their solution](https://codegolf.stackexchange.com/a/67191/13959), and for a golfing tip. I avoided copying anything from Boomerang's solution, but I did allow myself glances at it to see where I could trim more out. And even before that, I found that the more I golfed it, the more mine started to look like Boomerang's!
[Answer]
# Javascript (ES6) 96.8 93.6 Bytes (20% of 117)
```
n=>{b='';for(i=0;i++<n;b+=`\n`)for(j=0;j++<n;)a=(i*j).toString(n).toUpperCase(),b+=' '.repeat(4-a.length)+a;alert(b)}
```
## Explanation
```
n=>
{
b=''; //clear table var at each run
for(i=0;i++<n;b+=`\n`) //iterate through rows
for(j=0;j++<n;) //iterate through cols
a=(i*j).toString(n).toUpperCase(), //get desired number
b+=' '.repeat(4-a.length)+a"; //pad to right
alert(b) //display result
}
```
-*saved 4 bytes thanks to @edc65*
[Answer]
## MATLAB, 111\*0.8=88.8 110\*0.8=88 bytes
My debut here:
```
@(N)disp(reshape(strrep(strrep([' ',strjoin(cellstr(dec2base([1:N]'*[1:N],N)))],' 0',' '),' 0',' '),4*N,N)')
```
Explanation:
`[1:N]'*[1:N]` make multiplication table in base 10
`dec2base([1:N]'*[1:N],N)` convert to base 12. The output is char array with leading 0-s
`strjoin(cellstr(dec2base(___)))` convert to cell and back to char joining strings with space yielding 1x575 string
`[' ',strjoin(___)]` append space to have 576 elements
`strrep(___,' 0',' ')` remove one leading zero. We do it twice because we have strings with two leading zeros
`reshape(___,4*N,N)'` convert 1x576 char array into 48x12 char array
`disp(___)` display the result without `ans =`
Output:
```
1 2 3 4 5 6 7 8 9 A B 10
2 4 6 8 A 10 12 14 16 18 1A 20
3 6 9 10 13 16 19 20 23 26 29 30
4 8 10 14 18 20 24 28 30 34 38 40
5 A 13 18 21 26 2B 34 39 42 47 50
6 10 16 20 26 30 36 40 46 50 56 60
7 12 19 24 2B 36 41 48 53 5A 65 70
8 14 20 28 34 40 48 54 60 68 74 80
9 16 23 30 39 46 53 60 69 76 83 90
A 18 26 34 42 50 5A 68 76 84 92 A0
B 1A 29 38 47 56 65 74 83 92 A1 B0
10 20 30 40 50 60 70 80 90 A0 B0 100
```
If we don't count statement `N=12;`, `5*.8=4` bytes are saved. Also, if `ans =` output is tolerated, then we can remove `disp()` saving another `6*0.8=4.8` bytes. Of course, there may be other ways to save bytes :)
[Answer]
# Python 3: ~~166~~ ~~161~~ 152 - 20% = 121.6 bytes
I know it's inferior to the existing Python answers but I figured to give it a shot. It's my first time posting on this site…
```
def t(b):
r=range(1,b+1);f=lambda x:x and f(x//b)+chr((55,48)[x%b>9]+x%b)or''
print('\n'.join(''.join(B)for B in(('%4s'%f(i*j)for j in r)for i in r)))
```
[Answer]
## APL, ~~32~~ 31√ó0.8=24.8 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319)
```
{¯4↑¨⊃∘(⎕D,⎕A)¨¨⍵⊥⍣¯1¨∘.×⍨1+⍳⍵}
```
In origin 0.
In English:
* `∘.×⍨1+⍳⍵`: multiplication table
* `⍵⊥⍣¯1¨`: express in base ⍵ each element of the multiplication table
* `⊃∘(⎕D,⎕A)¨¨`: convert the table of vector of numbers into a table of vectors of chars
* `¯4↑¨`: right align to length 4 each element of the result
The default APL print routine does the right thing.
```
{¯4↑¨(⍵⊥⍣¯1¨∘.×⍨1+⍳⍵)⊃¨¨⊂⊂⎕D,⎕A}13
1 2 3 4 5 6 7 8 9 A B C 10
2 4 6 8 A C 11 13 15 17 19 1B 20
3 6 9 C 12 15 18 1B 21 24 27 2A 30
4 8 C 13 17 1B 22 26 2A 31 35 39 40
5 A 12 17 1C 24 29 31 36 3B 43 48 50
6 C 15 1B 24 2A 33 39 42 48 51 57 60
7 11 18 22 29 33 3A 44 4B 55 5C 66 70
8 13 1B 26 31 39 44 4C 57 62 6A 75 80
9 15 21 2A 36 42 4B 57 63 6C 78 84 90
A 17 24 31 3B 48 55 62 6C 79 86 93 A0
B 19 27 35 43 51 5C 6A 78 86 94 A2 B0
C 1B 2A 39 48 57 66 75 84 93 A2 B1 C0
10 20 30 40 50 60 70 80 90 A0 B0 C0 100
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 20 \$\times\$ 0.8 = 16 bytes
```
ɾ:v*$τkdkAJİṅ:fÞGL↳⁋
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLJvjp2KiTPhGtka0FKxLDhuYU6ZsOeR0zihrPigYsiLCIiLCIxMiJd)
This could actually be 9\*0.8=7.2 bytes if Vyxal had a gridify builtin and a buitlin to convert to a base as a string (with letters).
[Answer]
# Ruby, ~~69~~ 66 characters - 20% = 52.8
```
->n{(r=1..n).map{|a|puts r.map{|b|"%4s"%(a*b).to_s(n).upcase}*''}}
```
Sample run:
```
2.1.5 :001 > ->n{(r=1..n).map{|a|puts r.map{|b|"%4s"%(a*b).to_s(n).upcase}*''}}[4]
1 2 3 10
2 10 12 20
3 12 21 30
10 20 30 100
```
[Answer]
# ksh93, 51 \* 0.8 == 40.8 bytes
```
eval echo "'
' {"{1..$1}'..$((++n*$1))..$n%3..$1d}'
```
This should work up to base 64 (the largest radix supported by ksh). Examples:
```
$ n= ksh -s 12 <<\EOF
eval echo "'
' {"{1..$1}'..$((++n*$1))..$n%3..$1d}'
EOF
1 2 3 4 5 6 7 8 9 a b 10
2 4 6 8 a 10 12 14 16 18 1a 20
3 6 9 10 13 16 19 20 23 26 29 30
4 8 10 14 18 20 24 28 30 34 38 40
5 a 13 18 21 26 2b 34 39 42 47 50
6 10 16 20 26 30 36 40 46 50 56 60
7 12 19 24 2b 36 41 48 53 5a 65 70
8 14 20 28 34 40 48 54 60 68 74 80
9 16 23 30 39 46 53 60 69 76 83 90
a 18 26 34 42 50 5a 68 76 84 92 a0
b 1a 29 38 47 56 65 74 83 92 a1 b0
10 20 30 40 50 60 70 80 90 a0 b0 100
$ n= ksh -s 22 <<\EOF
eval echo "'
' {"{1..$1}'..$((++n*$1))..$n%3..$1d}'
EOF
1 2 3 4 5 6 7 8 9 a b c d e f g h i j k l 10
2 4 6 8 a c e g i k 10 12 14 16 18 1a 1c 1e 1g 1i 1k 20
3 6 9 c f i l 12 15 18 1b 1e 1h 1k 21 24 27 2a 2d 2g 2j 30
4 8 c g k 12 16 1a 1e 1i 20 24 28 2c 2g 2k 32 36 3a 3e 3i 40
5 a f k 13 18 1d 1i 21 26 2b 2g 2l 34 39 3e 3j 42 47 4c 4h 50
6 c i 12 18 1e 1k 24 2a 2g 30 36 3c 3i 42 48 4e 4k 54 5a 5g 60
7 e l 16 1d 1k 25 2c 2j 34 3b 3i 43 4a 4h 52 59 5g 61 68 6f 70
8 g 12 1a 1i 24 2c 2k 36 3e 40 48 4g 52 5a 5i 64 6c 6k 76 7e 80
9 i 15 1e 21 2a 2j 36 3f 42 4b 4k 57 5g 63 6c 6l 78 7h 84 8d 90
a k 18 1i 26 2g 34 3e 42 4c 50 5a 5k 68 6i 76 7g 84 8e 92 9c a0
b 10 1b 20 2b 30 3b 40 4b 50 5b 60 6b 70 7b 80 8b 90 9b a0 ab b0
c 12 1e 24 2g 36 3i 48 4k 5a 60 6c 72 7e 84 8g 96 9i a8 ak ba c0
d 14 1h 28 2l 3c 43 4g 57 5k 6b 72 7f 86 8j 9a a1 ae b5 bi c9 d0
e 16 1k 2c 34 3i 4a 52 5g 68 70 7e 86 8k 9c a4 ai ba c2 cg d8 e0
f 18 21 2g 39 42 4h 5a 63 6i 7b 84 8j 9c a5 ak bd c6 cl de e7 f0
g 1a 24 2k 3e 48 52 5i 6c 76 80 8g 9a a4 ak be c8 d2 di ec f6 g0
h 1c 27 32 3j 4e 59 64 6l 7g 8b 96 a1 ai bd c8 d3 dk ef fa g5 h0
i 1e 2a 36 42 4k 5g 6c 78 84 90 9i ae ba c6 d2 dk eg fc g8 h4 i0
j 1g 2d 3a 47 54 61 6k 7h 8e 9b a8 b5 c2 cl di ef fc g9 h6 i3 j0
k 1i 2g 3e 4c 5a 68 76 84 92 a0 ak bi cg de ec fa g8 h6 i4 j2 k0
l 1k 2j 3i 4h 5g 6f 7e 8d 9c ab ba c9 d8 e7 f6 g5 h4 i3 j2 k1 l0
10 20 30 40 50 60 70 80 90 a0 b0 c0 d0 e0 f0 g0 h0 i0 j0 k0 l0 100
```
[Answer]
## Pyke, 14 bytes \* 0.8 = 11.2 bytes, noncompetitive
```
QhD]UA*MbQMl2P
```
[Try it here!](http://pyke.catbus.co.uk/?code=QhD%5DUA%2aMbQMl2P&input=12)
Explanation:
```
- autoassign Q = eval_or_not_input()
QhD] - [Q+1, Q+1]
U - nd_range(^)
A* - apply(*, ^)
MbQ - map(base(Q), ^)
Ml2 - map(lower, ^)
P - print_grid(^)
```
Or 12 bytes without the bonus
```
13D]UA*Mb12P
```
] |
[Question]
[
A [man from the stars](https://codegolf.stackexchange.com/users/12914/elendia-starman) has come to Earth! Luckily the president of the United States, Donald Trump, has an infinity-sided die. Using this die, he can conjure up a number which *you*, the mayor of [Podunk](http://earthbound.wikia.com/wiki/Podunk), must use to determine who should be sent to stop the invader! But be careful, you can only send a limited amount of bytes on the back of your [frog](http://earthbound.wikia.com/wiki/Save_Frog)!
Given a user input (which will be a positive integer), you must return a string depending on what category the number is in.
* If the number is a [**Fibonacci number**](https://en.wikipedia.org/wiki/Fibonacci_number), you must output [***Ness***](http://earthbound.wikia.com/wiki/Ness).
* If the number is a [**Lucas number**](https://en.wikipedia.org/wiki/Lucas_number), you must output [***Lucas***](http://earthbound.wikia.com/wiki/Lucas).
* If the number is *both* a **Lucas number** and a **Fibonacci number**, you must output [***Travis***](http://www.mother4game.com/).
* If the number is *neither* a a **Lucas number** nor a **Fibonacci number**, you must output [***Pippi***](http://earthbound.wikia.com/wiki/Pippi).
## Examples
Here are a bunch of test cases:
```
1 => Travis
2 => Travis
3 => Travis
4 => Lucas
5 => Ness
6 => Pippi
7 => Lucas
8 => Ness
610 => Ness
722 => Pippi
843 => Lucas
```
## Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest answer in bytes wins.
* You program may be a full program or a(n anonymous) function.
## Bonuses
There are a couple bonuses that you can use to help your frog get the data to President Trump faster:
* **For `-15` bytes:** If the input number is `2016`, you must output `Trump`, as he is at the peak of his presidency.
[Answer]
# Julia, ~~146~~ ~~142~~ ~~121~~ 120 bytes
```
n->split("Pippi Lucas Ness Travis")[2any(isinteger,sqrt([5n^2+4,5n^2-4]))+(n∈[2;[(g=golden)^i+(-g)^-i for i=1:n]])+1]
```
This creates an unnamed function that returns a boolean. To call it, give it a name, e.g. `f=n->...`.
Ungolfed:
```
function trump(n::Integer)
# Determine if n is a Fibonacci number by checking whether
# 5n^2 ± 4 is a perfect square
F = any(isinteger, sqrt([5n^2 + 4, 5n^2 - 4]))
# Determine if n is a Lucas number by generating Lucas
# numbers and testing for membership
# golden is a built-in constant containing the golden ratio
L = n ∈ [2; [golden^i + (-golden)^-i for i = 1:n]]
# Select the appropriate Earthbound charater using array
# indexing on a string split into an array on spaces
return split("Pippi Lucas Ness Travis")[2F+L+1]
end
```
Fixed an issue and saved 7 bytes thanks to Glen O!
[Answer]
# Mathematica ~~143~~ 156 - 15 (bonus) = 141 bytes
With 2 bytes saved thanks to LegionMammal978.
```
t_~g~l_:=(r=1<0;n=1;While[(z=l@n)<=t,If[z==t,r=1>0];n++];r);a=g[k=Input[],LucasL];
b=k~g~Fibonacci;Which[k==2016,Trump,a&&b,Travis,a,Lucas,b,Ness,2<3,Pippi]
```
[Answer]
# Mathematica, ~~92~~ 87 bytes
Inspired by [Sp3000's answer](https://codegolf.stackexchange.com/a/64484/9288).
```
Travis[Ness,Lucas,Pippi][[{2,1}.Product[Abs@Sign[{Fibonacci@n,LucasL@n}-#],{n,0,2#}]]]&
```
[Answer]
# Pyth, 59 - 15 = 44 bytes
*or 42 bytes after a bug was fixed*
```
&Qr@c."av�a�(s��kW���"\b?q2016Q4/hMst*2.uL,eNsNQ_BS2Q4
```
Hexdump:
```
0000000: 2651 7240 632e 2261 7601 c061 15dc 2873 &Qr@c."av..a..(s
0000010: fde0 6b57 8bd0 a1ed ed0f 225c 623f 7132 ..kW......"\b?q2
0000020: 3031 3651 342f 684d 7374 2a32 2e75 4c2c 016Q4/hMst*2.uL,
0000030: 654e 734e 515f 4253 3251 34 eNsNQ_BS2Q4
```
The first two characters (`&Q`) are necessary because of a Pyth parsing bug that makes `Q` after `."` fail. Fix has been applied. If the post-bugfix interpreter is allowed, -2 bytes.
---
Without unreadable string compression:
# Pyth, 63 - 15 = 48 bytes
*49 bytes without Trump*
```
@c"Pippi Ness Lucas Travis Trump")?nQ2016/hMst*2.uL,eNsNQ_BS2Q4
```
[Test Suite](https://pyth.herokuapp.com/?code=%40c%22Pippi+Ness+Lucas+Travis+Trump%22%29%3FnQ2016%2FhMst%2a2.uL%2CeNsNQ_BS2Q4&input=843&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A610%0A722%0A843%0A2016&debug=0)
Pretty straightforward, just generate the sequences, duplicate one and check for membership.
Sequences are generated by starting with `[1, 2]` and `[2, 1]`, and then applying the fibonacci rule.
[Answer]
## Python 2, 107
```
f=lambda i,n=input():abs(5*n*n+i)**.5%1>0
print["Travis","Lucas","Ness","Pippi"][f(4)*f(-4)+2*f(20)*f(-20)]
```
The key is two purely arithmetical checks for Fibonacci and Lucas numbers:
* `n` is a Fibonacci number exactly if `5*n*n+4` or `5*n*n-4` is a perfect square
* `n` is a Lucas number exactly if `5*n*n+20` or `5*n*n-20` is a perfect square
[This site has proof sketches](https://web.archive.org/web/20170303035519/http://hubpages.com/education/How-to-Tell-if-a-Number-is-a-Fibonacci-Number).
So, the output depends on the values of `5*n*n+i` for `i` in `{4,-4,20,-20}`. The function `f` tests a value of `i`, by checking if the corresponding value *does not* have a whole-number square root The `abs` is there just to avoid an error of taking the root of a negative for `n=1, i=-20`.
The function `f` takes the value of the number `n` to test from STDIN. Python only evaluates this once, not once per function call.
Whether the number is not Fibonacci is evaluated as `f(4)*f(-4)` using the implicit boolean to number conversion and similarly for not Lucas, and the corresponding string is taken. If trailing spaces were allowed, string interleaving would be shorter.
[Answer]
## Python 2, 117 bytes
```
F=[1]
L=[2,1]
n=input()
exec 2*n*"F,L=L+[sum(L[-2:])],F;"
print["Pippi","Lucas","Ness","Travis"][(n in F)*2+(n in L)]
```
For the string list, `"Pippi Lucas Ness Travis".split()` is the same length.
[Answer]
## CJam, ~~58~~ ~~55~~ 54 bytes
```
ri5Zbe!f{1${_-2>:++}*&!}2b"Travis Ness Lucas Pippi"S/=
```
Naïve approach of generating the Fibonacci and Lucas numbers then counting occurences in both, converting to binary, and picking the appropriate string.
[Try it online](http://cjam.aditsu.net/#code=ri5Zbe!f%7B1%24%7B_-2%3E%3A%2B%2B%7D*%26!%7D2b%22Travis%20Ness%20Lucas%20Pippi%22S%2F%3D&input=843).
[Answer]
## Perl, ~~133~~ ~~(146-15=)131~~ ~~(144-15=)129~~ (136-15=)121 bytes
+1 byte for the `-n` flag.
```
$a=$d=1;$b=$c=2;$f+=$_==$a,$l+=$_==$c,($a,$b,$c,$d)=($b,$a+$b,$d,$c+$d)while$a<$_*9;say$_-2016?(Pippi,Ness,Lucas,Travis)[$f+$l*2]:Trump
```
With newlines after semicolons, for readability:
```
$a=$d=1;$b=$c=2;
$f+=$_==$a,$l+=$_==$c,($a,$b,$c,$d)=($b,$a+$b,$d,$c+$d)while$a<$_*9;
say$_-2016?(Pippi,Ness,Lucas,Travis)[$f+$l*2]:Trump
```
Demo:
```
llama@llama:...code/perl/ppcg64476trump$ for x in 1 2 3 4 5 6 7 8 610 722 843 2016; do echo -n "$x => "; echo $x | perl -n trump.pl; done
1 => Travis
2 => Travis
3 => Travis
4 => Lucas
5 => Ness
6 => Pippi
7 => Lucas
8 => Ness
610 => Ness
722 => Pippi
843 => Lucas
2016 => Trump
```
Tricks:
* ~~You might be wondering why my variables are named `$a`, `$b`, `$%`, and `$d`. That is an excellent question! In fact, it allows me to save a byte.~~
```
(stuff) ... ,$l+=$_==$%while$a<$_
```
is one byte shorter than
```
(stuff) ... ,$l+=$_==$c while $a<$_
```
This no longer applies because I golfed my code by rearranging things, causing the variable name change to no longer save bytes. I changed it back so that variable names make sense again.
* ~~`$_-2?$f+$l*2:3` is mildly interesting. Basically, I had to special-case `2` for Lucas numbers because my program checks whether a number is a Lucas number *after* "updating" the Fibonacci and Lucas numbers. So `2` was considered a not-Lucas number. `$_-2?foo:bar` is a char shorter than `$_==2?bar:foo`. Same thing is used for the `2016` test.~~
This is also no longer true because I was able to restructure the program to not require special-casing `2`. But I still use `$_-2016?stuff:Trump` instead of `$_==2016?Trump:stuff`, which is one byte longer.
* Speaking of which, you may be wondering how I did this restructuring. I just made the program do 9 times more iterations than necessary, which only costs 2 bytes (`*9`) but allows me to make assumptions elsewhere that help golf stuff down.
* Because variables default to zero,
```
$f+=$_==$a
```
is shorter than
```
$f=1if$_==$a
```
* Perl supports barewords, so I don't have to quote any of my strings (\o/).
[Answer]
# Seriously, 69 bytes
```
,;;r`;F@2+F+`M2@q@#"%d="%£MΣ@f0≤2*+["Pippi","Lucas","Ness","Travis"]E
```
Before this challenge, Seriously had the builtin `f` (index in Fibonacci numbers, -1 if not a Fibonacci number)... but not index in a list or "is in list"! (It's since been added as `í`.)
As a result, this is what I spend finding if the input is a Fibonacci number:
```
, f0≤
```
This is what I spend generating a list of Lucas numbers:
```
;r`;F@2+F+`M2@q
```
And this is what I spend finding if the input is in the list of Lucas numbers:
```
; @#":%d:="%£MΣ
```
That's a string being formatted using Python's % notation into something like `:610:=`, and converted to a function, which is then mapped over the array and summed. (The Lucas numbers are unique, so the sum is always 0 or 1.)
Thanks to @Mego for that last bit with the string formatting.
[Answer]
# Julia, ~~101~~ 100 bytes
```
n->split("Pippi Lucas Ness Travis")[[2;1]⋅(sum(i->[i[];trace(i)].==n,Any[[1 1;1 0]].^(0:n)).>0)+1]
```
Ungolfed:
```
function f(n)
k=Any[[1 1;1 0]].^(0:n) # Produces characteristic matrices of Fibonacci
# numbers from 0 to n
F=sum(i->i[]==n,k) # Check if n is a Fibonacci number by checking
# the first value in each matrix for n
L=sum(i->trace(i)==n,k) # Check if n is a Lucas number by checking
# the trace of each matrix for n
I=[2;1]⋅[F;L]+1 # Calculate 2F+L+1, which is the index for the next step
S=split("Pippi Lucas Ness Travis") # Creates array with four strings
# saves a byte compared with directly creating array
return S[I]
# This uses the above calculations to determine which of the four to return
end
```
[Answer]
# Octave, 93 bytes
```
@(n){'Pippi','Lucas','Ness','Travis'}{(1:2)*any(~rem(real(sqrt(5*n^2+[-20,-4;20,4])),1)).'+1}
```
This approach is similar to [my MATLAB answer](https://codegolf.stackexchange.com/a/76849/51939) with the exception that Octave allows you to index directly into a fresh array:
```
{'a', 'b', 'c'}{2} %// b
```
[Answer]
# MATL, ~~57~~ ~~55~~ ~~54~~ (67-15) = 52 bytes
```
20Kht_vi2^5*+X^Xj1\~a2:*sG2016=-'Lucas Ness Travis Trump Pippi'Ybw)
```
[**Try it Online!**](http://matl.tryitonline.net/#code=MjBLaHRfdmkyXjUqK1heWGoxXH5hMjoqc0cyMDE2PS0nTHVjYXMgTmVzcyBUcmF2aXMgVHJ1bXAgUGlwcGknWWJ3KQ&input=MjAxNg)
**Explanation**
Again, similar logic to my other answers [here](https://codegolf.stackexchange.com/a/76851/51939) and [here](https://codegolf.stackexchange.com/a/76849/51939).
```
20 % Number literal
K % Retrieve the number 4 from the K clipboard (the default value)
h % Horizontal concatenation to produce [20 4]
t % Duplicate elements
_v % Negate and vertically append elements (yields [20, 4; -20 -4])
i2^ % Explicitly grab the input and square it
5* % Multiply by 5
+ % Add this to the matrix ([20, 4; -20 -4])
X^ % Take the square root
Xj % Ensure that the result is a real number
1\ % Get the decimal component
~ % Create a logical arrays where we have TRUE when no remainder
a % For each column determine if any element is TRUE
2: % Create the array 1:2
* % Perform element-wise multiplication with boolean
s % Sum the result to yield an index
G % Explicitly grab the input (again)
2016= % Check to see if it is 2016 (yields TRUE (1) if equal)
- % Then subtract the boolean from the index. Since 2016 is NOT a
% Fibonacci or Lucas number, the original index is 0. Subtracting
% this boolean, will make this index now -1. For all other non-2016
% numbers this will have no effect on the index.
'Lucas Ness Travis Trump Pippi' % Create the possible strings values
% Note: the 0 index wraps around to the end hence Pippi being at the end.
% The next to last entry ('Trump') is ONLY accessible via a -1 index as
% discussed above
Yb % Split at the spaces to create a cell array
w % Flip the top two stack elements
) % Retrieve the desired value from the cell array
```
[Answer]
# C++11, 176 + 15 (#include) = 191
```
#include<mutex>
[](int n){std::function<int(int,int)>c=[&](int f,int s){return f-s>n?0:s-n?c(s,f+s):1;};int l=c(2,1),f=c(1,1);l&f?puts("Travis"):l?puts("Lucas"):f?puts("Ness"):puts("Pippi");}
```
Ungolfed with usage. I can add explanation if requested tomorrow, gtg to bed now!
```
#include <functional>
#include <cstdio>
int main()
{
auto r = [](int n)
{
std::function<int(int, int)> c = [&](int f, int s)
{
return f - s > n ? 0 : f - n ? c(s, f + s) : 1;
};
int l = c(2, 1), f = c(1, 1);
l & f ? puts("Travis") : l ? puts("Lucas") : f ? puts("Ness") : puts("Pippi");
};
for (int i : { 1, 2, 3, 4, 5, 6, 7, 8, 610, 722, 843 })
{
printf("%i - ", i); r(i);
}
}
```
[Answer]
# Javascript (ES6), 108 bytes
```
x=>(f=(a,x,y)=>a==y||a==x?1:a<y?0:f(a,y,x+y),b=f(x,0,1),c=f(x,2,1),b&&c?'Travis':b?'Ness':c?'Lucas':'Pippi')
```
Same function for Fibonnacci and Lucas. It's a recursive function that takes the first two values as init.
[Answer]
# Java, 151 bytes
You could argue that Trump would never outsource this crucial decision, so we wouldn't have to make the method public, saving another 7 bytes.
```
public String t(int n){return"Pippi,Lucas,Ness,Travis".split(",")[2*f(n,1,1)+f(n,2,1)];}int f(int a,int x,int y){return a==x||a==y?1:a<y?0:f(a,y,x+y);}
```
Ungolfed including test-main invocation
```
public class Trump {
//Test Invokation
public static void main(String[] args) {
int[] n = {1, 2, 3, 4, 5, 6, 7, 8, 610, 722, 843, 2016 };
for(int i = 0; i < n.length; ++i) {
System.out.println(""+ n[i] + " => " + new Trump().t(n[i]));
}
}
public String t(int n) {
return "Pippi,Lucas,Ness,Travis".split(",")[2*f(n,1,1)+f(n,2,1)];
}
int f(int a,int x,int y) {
return a==x||a==y?1:a<y?0:f(a,y,x+y);
}
}
```
I found no way so far to test for 2016 and return "Trump" in code that's less than 15 bytes in code.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~39~~ 37 (52 - 15 bonus) [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
2016Qi.•ªb‚•ë>ÅG¹å_¹ÅF¹åi.•F_ïk|»9•ë.•?®B'5n•}2äsè}™
```
[Try it online](https://tio.run/##yy9OTMpM/f/fyMDQLDBT71HDokOrkh41zAIyDq@2O9zqfmjn4aXxQKLVDcQCq3CLP7w@u@bQbkuwIpCI/aF1TuqmeUBWrdHhJcWHV9Q@alkEMdQAAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn1l5X8jA0OzwEy9Rw2LDq1KetQwC8g4vNrucKt75eGl8ZWHW92ANFjaLf7w@uyaQ7stwSpAIvaH1jmpm@YBWbVGh5cUH15R@6hl0X@d/4ZcRlzGXCZcplxmXOZcFlxmhgZc5kZGXBYmxlwg6wA).
**Explanation:**
```
2016Qi # If the input equals 2016:
.•ªb‚• # Push "trump" to the stack
ë # Else:
>ÅG # List of Lucas numbers up to and including the input+1
¹å # Check if the input is in this list (1 if truthy; 0 if falsey)
_ # Invert the boolean (0→1 and 1→0)
¹ÅF # List of Fibonacci numbers up to and including the input
¹åi # If the input is in this list:
.•F_ïk|»9• # Push string "travisnessi" to the stack
ë # Else:
.•?®B'5n• # Push string "pippilucas" to the stack
} # Close the inner if-else
2ä # Split the string into two parts
# i.e. "travisnessi" → ["travis","nessi"]
# i.e. "pippilucas" → ["pippi","lucas"]
sè # Index the Lucas result into the list of two strings
} # Close the outer if-else
™ # And output the top of the stack in title-case
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~128~~ ~~120~~ ~~116~~ 110 bytes
```
a;b;o;f(n){for(o=b=0,a=1;a<=n;b=a+b,a=b-a)o|=(b==n)+2*(2*a+b==n);n=o?o-1?o-2?"Travis":"Lucas":"Ness":"Pippi";}
```
[Try it online!](https://tio.run/##ZY7BbsIwDIbvfYooElICrUSzwtA8wwtMsANHLk6hUw4kVQtcoM/eJeIEPlj2//n/LdfFX12PI4GFAI3y@t6ETgW0OM8JS6Bv9GCRZjZKW5AOD1QW0euZmSozjYskwGPYhKKMZTZy39HN9fJL/lxrSn176lP7dW3rJAzjLbijaDvnL1s6n3aNipNwWtyfsFFyUh0FrsWkP3iZuzw6tAYxZFlynsl5Fd2ZeDlSangjhpEPRipGFowsGflkZMVT5ZznDP9pVaWvhvEf "C (gcc) – Try It Online")
# Explanation
Let's name `F(n)` the n-th Fibonacci number, and `L(n)` the n-th Lucas number.
`a`, `b` are `F(n-1)`, `F(n)` respectively.
Then we can calculate `L(n) == F(n-1)+F(n+1) == 2*F(n-1) + F(n) == 2*a+b`
This function will successively calculate Fibonacci and Lucas numbers, up to `n`, and check if `n` is any of them.
If `n` is a Fibonacci number, the 1st bit of `o` will be set to `1`
If `n` is a Lucas number, the 2nd bit of `o` will be set to `1`
`o` will then be used to determine which name to output
# Edit
* Saved 8 bytes by golfing the condition of the for-loop : starting at second iteration, we have `a<b<c` and `a<a+c=L(n)`, so `( b<=n || a+c<=n ) => a<n`. I actually needed `a<=n` to handle correctly `n=1`
* Saved 4 bytes thanks to ceilingcat ! (also corrected a mistake, my code was outputting "2 => Ness")
* Saved 6 bytes:
+ 2 thanks to ceilingcat again
+ 4 by removing the variable `c`, equal to `F(n+1)`, which was useless since we can already calculate `F(n+1)` with `a` and `b`
[Answer]
## Perl 5.10, 119 - 15 (bonus) = 104 bytes
```
$_=<>;$j=1;($i,$j)=($j,$i+$j)while$_>$i;say$_-2016?(Pippi,Lucas,Ness,Travis)[($_==$i)*2|$_==3*$j-4*$i|$_-1>>1==0]:Trump
```
Ungolfed:
```
# Read line from stdin
$_ = <>;
# Find first Fibonacci number greater than or equal to input.
# Store this number in $i and the next Fibonacci number in $j.
$j = 1;
($i, $j) = ($j, $i + $j) while $_ > $i;
say $_ - 2016
? (Pippi,Lucas,Ness,Travis)[
($_ == $i) * 2 | # Bitwise OR with 2 if Fibonacci number
$_ == 3 * $j - 4 * $i | # Bitwise OR with 1 if Lucas number >= 3
$_ - 1 >> 1 == 0 # Bitwise OR with 1 if Lucas number <= 2
]
: Trump
```
This exploits the fact that
```
L(n-2) = 3 * F(n+1) - 4 * F(n)
```
is the greatest Lucas number lower to or equal than F(n).
[Answer]
# Groovy, 149 bytes
```
f={i->g={m,s->while(s[-2]<=m)s<<s[-2]+s[-1];s}
println(["Pippi","Ness","Lucas","Travis"][(g(i,[1,1]).contains(i)?1:0)+(g(i,[2,1]).contains(i)?2:0)])}
```
Test code:
```
[1,2,3,4,5,6,7,8,610,722,843].each {
print "$it => "
f(it)
}
```
`g` is a closure that generates a list of numbers based on a seed (`s`) and a max value (`m`). `(g(i,[1,1]).contains(i)?1:0)+(g(i,[2,1]).contains(i)?2:0)` finds the index to use based on the number being lucas or fibonacci.
[Answer]
# MATLAB, ~~122~~ 119 bytes
```
@(n)subsref({'Pippi','Lucas','Ness','Travis'},substruct('{}',{(1:2)*any(~rem(real(sqrt(5*n^2+[-20,-4;20,4])),1)).'+1}))
```
**Brief Explanation**
We first create a cell array containing the values to print: `{'Pippi', 'Lucas', 'Ness', 'Travis'}`. Then to figure out which value to display, we check to see whether `n` is a Fibonacci or Lucas number.
For Fibonnaci, we use the following formula:
```
any(~rem(sqrt(5*n^2 + [-4 4]), 1))
```
This checks to see if either `5*n^2 + 4` or `5*n^2 - 4` are a perfect square. If `any` of them are, then it is a Fibonacci number.
The formula for a Lucas number is *very* similar with the exception that we use +/- 20 instead of 4:
```
any(~rem(sqrt(5*n^2 + [-20 20]), 1))
```
In this solution I combined these two cases into one by using the matrix:
```
M = [-20 -4
20 4]
```
By applying the same equation as those above, but force `any` to consider only the first dimension, I get a two element logical array where if the first element is `true`, then it is a Lucas number and if the second element is `true`, it is a fibonacci number.
```
any(~rem(sqrt(5*n^2 + [-20 -4;20 4]), 1))
```
Then to compute the index into my initial cell array, I treat this as a binary sequence by performing element-wise multiplication of this boolean with `[2^0, 2^1]` or simply `[1,2]`. And sum the elements. Obviously I have to add 1 because of MATLAB's one-based indexing.
```
index = (1:2) * any(~rem(real(sqrt(5*n^2+[-20,-4;20,4])),1)).' + 1;
```
Then I have to use `subsref` and `substruct` to index into the initial cell array to obtain the final result.
[Answer]
## JavaScript (ES6), 97 bytes
```
x=>[['Pippi','Lucas'],['Ness','Travis'],f=(a,x,y=1)=>a>x?f(a,y,x+y):a==x||a==1][+f(x,0)][+f(x,2)]
```
The `a==1` check is needed otherwise I don't notice that 1 is a Lucas number.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 47 bytes - 15 = 32
```
+2ḶÆḞ⁸eð+ị“©ḤʠhMṂƁÞḄṭAƓ»Ḳ¤µ2+С-⁸eḤ
“¡Ỵ¦»Ç⁼?⁽¥Ð
```
[Try it online!](https://tio.run/##AW8AkP9qZWxsef//KzLhuLbDhuG4nuKBuGXDsCvhu4vigJzCqeG4pMqgaE3huYLGgcOe4biE4bmtQcaTwrvhuLLCpMK1MivDkMKhLeKBuGXhuKQK4oCcwqHhu7TCpsK7w4figbw/4oG9wqXDkP///zIwMTY "Jelly – Try It Online")
] |
[Question]
[
We all know that if you google the word "google" it will break the internet.
Your task is to create a function that accepts one string and returns its length, in the fewest possible Unicode characters.
However, if the given string is `google` (lowercase), it will cause an error.
For example, `g('bing')` will return `4` but `g('google')` will cause an error.
Please provide an example of usage, and the error if possible.
[Answer]
# Powershell 34 Bytes
```
param($a)$a.length*($a-ne'google')
```
Multiply length by 0,1 boolean value of `not-equal` google.
Gives `0` if `google` (not case-sensitive), length otherwise.
[Answer]
# ùîºùïäùïÑùïöùïü, 15 chars / 21 bytes (noncompetitive)
```
ï≔`google`?$:ïꝈ
```
`[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter.html?eval=false&input=bing&code=%C3%AF%E2%89%94%60google%60%3F%24%3A%C3%AF%EA%9D%88)`
[Answer]
# [ಠ\_ಠ](https://github.com/molarmanful/-_-), 110 bytes (noncompetitive)
```
ಠ_ಠ
ಠgoogleಠ
ಠ=ಠ
ಠ"ಠ
ಠ$ಠ
ಠ$ಠ
ಠ11ಠ
ಠ13ಠ
ಠ(ಠ
ಠ?ಠ
ಠ_ಠ
ಠ#ಠ
ಠ^ಠ
```
[Try it here.](http://codepen.io/molarmanful/debug/gajxjX)
[Answer]
# Game Maker Language, 60 bytes
```
a=argument0;if a="google"a=1/0show_message(string_length(a))
```
[Answer]
# Factor, ~~55~~ ~~53~~ 49 bytes
```
: g ( s -- l ) dup length swap "google" = not / ;
```
~~Throws the string "google". `throw` happens to be the same length as `0 0 /`. Or I could just divide a string by a number...~~ Or I could just divide the length of the string by if it's not `google`...
Example use:
```
cat @ mint-kitty : ~/projects/factor/factor(master??!) $ ./factor -run=listener
Factor 0.98 x86.64 (1742, heads/master-0bb3228063, Tue Mar 15 14:18:40 2016)
[Clang (GCC 4.2.1 Compatible Ubuntu Clang 3.6.2 (tags/RELEASE_362/final))] on linux
IN: scratchpad : dont-google ( str -- int ) dup "google" = [ throw ] [ length ] if ;
IN: scratchpad "bing" dont-google
--- Data stack:
4
IN: scratchpad "google" dont-google
google
Type :help for debugging help.
--- Data stack:
4
IN: scratchpad
```
The error in the UI:
[![enter image description here](https://i.stack.imgur.com/51S2V.png)](https://i.stack.imgur.com/51S2V.png)
[Answer]
# Scratch, 16 bytes
[![Script](https://i.cubeupload.com/utmUzk.png)](https://i.cubeupload.com/utmUzk.png)
([scoring used](http://meta.codegolf.stackexchange.com/questions/673/golfing-in-scratch))
Stopping the project is the closest thing to an error that I can get.
[Answer]
# C++, 77 Bytes
```
#include <string>
int G(std::string S){1/int(S!="google");return S.length();}
```
[Answer]
# [Syms](https://github.com/CatsAreFluffy/syms), 18 bytes
```
{[#~{google}=!1/]}
```
[Try it online!](https://tio.run/##K67MLf5fXWvzvzpaua46PT8/PSe11lbRUD@29r@m3X@wAAA "Syms – Try It Online")
[Answer]
# [shortC](//github.com/aaronryank/shortC), 21 bytes
```
Df(s)Ss)/Ms,"google")
```
* `Df(s)` defines a function `f` that takes one argument `s`.
* `Ss)` calculates the length of `s`.
* `Ms,"google)` compares `s` to "google".
* `Ss)/Ms,"google")` divides the length of `s` by `0` if the strings are equal. This throws `floating point exception` if they're equal.
[Try it online!](https://tio.run/##K87ILypJ/v/fJU2jWDO4WFPft1hHKT0/Pz0nVUnz/38A)
[Answer]
# Excel VBA, 52 Bytes
Subroutine that take input `a` as unassigned/variant of expected type variant/String and outputs to the VBE Immediates window. If `a` = "google" throws `Run-time error '3': Return without GoSub` else outputs the length of the input `a`.
```
Sub g(a)
If a="google"Then Return
Debug.?Len(a)
End Sub
```
[Answer]
# Bash
```
[ $1 == google ]; return $((${#1}/$?))
```
[Answer]
# GameMaker Language, 46 bytes
```
x=argument0
return string_length(x)/x!=google
```
Uses the same logic as [this Python answer](https://codegolf.stackexchange.com/a/58896/82488), abusing GMLs type coercion making the function divide by zero if the string equals google
I also haven't and can't test this because I currently don't have GameMaker installed, just made this from memory
[Answer]
# [Keg](https://github.com/JonoCode9374/Keg), 16 bytes
```
:`google`=[0/|√∑!
```
[Try it online!](https://tio.run/##y05N///fKiE9Pz89JzXBNtpAv@bwdsX//5My89L/62YUAQA "Keg – Try It Online")
Attempt ruined by the fact that `google` isn't in Keg's dictionary. That's why I use DuckDuckGo, which at least has parts of it's name in the dictionary!
[Answer]
# [Lua](https://www.lua.org/), 35 bytes
```
load'return #(...=="google"or ...)'
```
[Try it online!](https://tio.run/##NY7NCsIwEITP9imWetgESkDBY97CuwTz08CSLZsUD@Kzx0jx9s0MMwztrhM/HUEEO8h5lNB2KXBWxhhr58ScKMwsMLTGHgc9ltoEcoG8uSz1jWvGBXANRAwvFvI/eTTxA56n0ya5NIX3UFsuacRjQf/tbRwgFQ9TT6H43i/X2xc "Lua – Try It Online")
Idea is like one in [@QuertyKeyboard's answer](https://codegolf.stackexchange.com/a/70582/59169), but better optimized: `load` is used to create function and inverting check for "googleness" allows us to save one byte by replacing `and` with `or`.
Again, if full programs are allowed, we can cut down to **29** bytes!
# [Lua](https://www.lua.org/), 29 bytes
```
print(#(...=="google"or ...))
```
[Try it online!](https://tio.run/##yylN/P@/oCgzr0RDWUNPT8/WVik9Pz89J1Upv0gByNfU/P//P0QEAA "Lua – Try It Online")
[Answer]
# VBScript, 47 bytes
```
sub f(x)
msgbox len(x)/abs(x<>"google")
end sub
```
VBScript will return `-1` for `True`, so we have to `abs()` it. And attempts to divide it by the length, like the python answer.
[Answer]
# [Knight](https://github.com/knight-lang/knight-lang), 17 bytes
```
O/L=gP!?g"google"
```
[Try it online!](https://tio.run/##rVn/U9vKEf/Z/isOZ8CSLQdZ0Jk3NrInXyDDlAAPkr7OAA1CPtuaJ0uqJENoQv/00t29LzrZJm3ax0ws6@6ze7uf29vdc8LeLAyfX0VJGC8n/KAoJ1H6ej5qmiNxdFcbCsvHjK@A8iiZ1YbKaCEwEz6NEs7imMVpMqOPph79dPr5I@tXr5efLphXvf7lzQXbr16PTt@xX6rXi8@sX4GPTi4N7OnnEwP6@fTjm8s/W4XNLPzYYf/s/8nWs28uYVkxGc6DnHXsSsBEga1axWjE9qu508PfcDKBSfLoO8PvBwcrGFyGMOgmYOLYRmAN8/bs7IRA@DEmJwfom2HIxQcBAHnD1vsgXnLbvkpu7GaT/IBdubphPrtoHZ4dWc9nuyf@7HxrPGvN0nQW89azDeOtoQB3AM2DBcDhy7DZBN1ZkBfcstm3ZiNKShYNmw0YpXUc1pkukxBGSDiE93KROUWWXHk3/jfXcZ9ARyMCdYSHp4sDu7uoPsrYwzwqeZEFIW824HvMLRgHcUuY4bDWdXmdXE@vc/bt6erGsgevWjaZ0oimzNLW@qz9qm0zoUKNbsHodQLD3a4YATsbPC64OfAkzAnnPPydTdOcJcvFHc8LaQ@zomISzaJSaYXV0Z2@oz0Szw7ru6zLOtLybtdmPdZ227AEWhrZLOflMk@YigwhRsExXLXhPsij4C7mygowIk4feG6FsJ4yhH3/zpRxIb2FRMSXti3piTa4Hvl9B/bI18Mr1uFZkzEJkGSyzCzcUiY57TF4WzdYnPxCaBNmXLfblU2tttg0EAYPtFEMlECmgO9gWRYUJSvnHJQFeQlguQEdxShuaGijJ8pY4wC9aCx89m3a6EZFBpmPoVtGaQJmY8S6eEhCxUixzDIk3FZRpUZM@s34A9oNslGHCuUsgTiGrIWRKy0XrHxq66MtBo5wADPYADMXmqmCjJKecNVCu9HUII7T0Np3nb6NDuKwdoIcTJZxHOSPpqPV/lwY23Pe1pbRglJ@maxI0xJ9XEImhU2eHr59d/vr1sn7M8NfU@tdtFGtt652q6b3w/HlCxpLnpPKIJmwvy8D9Ypq780l9taXEP5/aGsqjjdQQcL7deE65okyZb5McIOGMvF2yrSwVKqk@IfILqOQ0ezdcnrl7d9IO8Q@71B20AYUGZyqcmoBFPzfjuNJS6UdKjwOKllVAGdCKxAlTaxfwx2w/l7dT3QeQ3HMWmW@5C0IQT2OEQnj0wASCE60MLBaFQnoJ/ouaw/R8eVtmsYwc1dn4EVfK7d@5FDn5z0yzbxbMzNGG5M/1EYI2jKNY8s01WGuAwXifzA5WTMZi/DHN@enDpZiEWjwenzVd10XwglcgVf1VkT/4F9Kho@hEaOGt8gAvDn44dHnnt9XFR0THBZ1fNCnJx57ADg6PjnssCnkxmFDh7ZcD7NwGGROzBNqAAyuVGskOINz9xIZq4JYmrCyYb2xImoloBQfEBdDqCkRTuq8ES6ylR0gkqKbKoUgTdENLlM8RGU4tzrAzFonhRyFWJ8gYw6UqOz0csg4lr3jfp3iH@6uQJ63B01W/YE5ZO6MlzG0btYOsbqDXGGtmkSJPWRNrEjRV5bl6SIrWcyDeyipLOEPKAMd9RQaP3Z@cfbx/NOXo@O/mgtEU4t2Bat6OM8xHzvU@thit3zoul7xZBJNm5UD1O2WORZNeNhU1IX5h@Co7gPxcGOviUVGuY9BJFNh5fTbih6B1zPvqhmUxH9SY4W5BQxuLoSTn6UZTyxjYaeVt6jwg1X@QtQ9CC/fc/d/oXHZKliiv5iC6RN0ChoyiEAHuzWAQydAb7gGLK2ixYJB1vWpscEDCEhbbhnoobVov1BDx2ee2YFUNFae/Aqe8K/QlOHhXfNzqxZE1OZvYWJaA56sRRusEtd5MeDvIeSkPxS4vsmyTmSyoLROqcm1sKTYqqaMRvt21SauZTclekmtnrVdoKB5wjYJA53QyJjrQmK0WxVUTWC14EEi1b5UkWQJMndApgrJwlnFAp4ucY1B0sR@1qhjOzt0N@r1EHojmtZrap4byqzt150C7LHgzWbqvOaG@cuyULuvY0J0bsKgrjaI0h6kP8ywGFrG9ojeuFHfbXHRRDR08UzFkif2HLtZOgxiAwiFw3jafeWlZ28O1TAo1UP2kP1uRZOtvqMuG3pLh56lzBHSr95adBrRjo133V4h1Kl2ZwMLq9V2Aw@dNR7Evm5iYbHBtQ5hfFMJCUBJsShT@u1ruLIhaNjrkT5JFFXA1Y0WjJa107/7Q2J2NxOz/UOh7c1CfyM2aw6JiwCNeaaXQ0m7YN1nvb5mmbBAfR/OWa8PZ6xvgr2fRB9AeqxhfR@htO5AjbiKciLaG7mSa8@m7qPjE//N1QNBk@QKVEpKsFhi4DveAOY85@2CJSm0xFFcRgl7CB6BNzZJ4YZZ8hnPQSZLE56UUYCXAjjJKXvgbB7ccwBKRQgv2SJIlhA@j69xFL27Q8aBCmKiWMYl/gRAi@uEpyA9E6OWXKHMlNOQFfWo72Wk@7IhGnZQQ7l02w5irI2P4HUyifmE3VZm32ot3/Cb6LOMRSpnRqis11PvNsEbEtoxTH/SefCAgnWl8GHSq@VFv54Vx8w8/AfmMUDRgfwJbYcJwJjV@j4adJiRDVGHKyRVyfVEHUDslg/VxuiCRnAoMbTSSTpgC74IMwyzhI1ux/@vK6M/wJWRcmVrgy@@9EW6Mn6ZfbHqBpNxesxqAE8jPFVAtzbZWb1o91TmMRVo83aq9Ie@bKoNY1NSphIt//2/kZc5yFCj5YftgYmutbmrWL/KuvXpn76XqN62upggrlG7nOhUSBjUeOPXpI00iRKI6Ha1mDD5N3BP/IZlNpo175jZu0ix43rXjlBDfuwN9gxaPogrg290WF2zALG1LiSRFw9Hn4W9WkN7KYheUTpcLXneppK3Z@s@wNPS@zT4HxoiNAyfuBWhbv51O2T2Rh54iKt2@9gkUYMg4l9M0oMQXXkSYHW4wgWQJMEz1WFGCUxGE/pNKAhLKFPt7bCNPSeO2OyFSykq0zUQukH5u8AiiBJsVlmQz0KHlHY68P3exl@f6LqK/yNjuWRN/Rr39Cz@Q@Bf4TQOZsVz73112fw3 "C (gcc) – Try It Online")
Requires a patch to fix an errata in the """golfed""" C interpreter, where it will leave a newline in the input from `PROMPT`. This matches the behavior of the AST interpreter and the wording of the spec.
This is the simple division by zero method.
```
# print length(g = prompt()) / (g != "google")
OUTPUT / (LENGTH(= g PROMPT)) (! (? g "google"))
```
Relies on division by zero throwing an exception. The AST interpreter will always throw an exception in software, but for the golfed interpreter, it requires the x86 behavior of throwing an exception on the hardware level.
] |
[Question]
[
This serves as a catalog for tips related to golfing in [Burlesque](http://esolangs.org/wiki/Burlesque).
Burlesque is a lazy, esoteric programming language. It's mostly used on anarchy golf while popularity on Codegolf is not as high. However, this catalog is intended to be used by people golfing on anarchy golf as well.
Please only mention tricks and not obvious shortcuts. An obvious shortcut is for example using `r\` instead of `r@\[` because the built-in `r\` is defined to be `r@\[` and is stated as such in the documentation and is thus just an obvious shortcut.
[Answer]
## Using `".. .."wd` instead of `{".."".."}`
If you need a Block of Strings such as `{"abc" "def"}` it is shorter to use the *words* built-in: `"abc def"wd`.
## Using `ra` to parse *fail-safe*
`ps` will fail if the input is not properly formated or might produce unwanted results. In such cases, using `ra` is better.
```
blsq ) "5,"ra
5
blsq ) "5,"ps
{5 ,}
blsq ) "5a"ps
{ERROR: (line 1, column 3):
unexpected end of input}
blsq ) "5a"ra
5
```
## Using `,` to drop stdin
`,` is defined as a pop instruction if and only if there is exactly one element on the stack. It's used to pop STDIN from the stack when it's not needed but there (such as for example is the case on anarchy golf).
## Abusing the way `mo` is defined
`mo` is defined as `1R@\/?*` and is used to generate a Block containing multiples of N:
```
blsq ) 3mo9.+
{3 6 9 12 15 18 21 24 27}
```
Yet due to side effects of `?*` you can do some nasty things with it if you don't provide a number:
```
blsq ) "1"mo9.+
{"11" "21" "31" "41" "51" "61" "71" "81" "91"}
blsq ) {1 2 3 4}mo9.+
{1 4 9 16}
```
] |
[Question]
[
Write a program that counts up forever, starting from one.
Rules:
* Your program must log to `STDOUT` or an acceptable alternative, if `STDOUT` is not available.
* Your program must be a full, runnable program, and not a function or snippet.
* Your program must output each number with a separating character in between (a newline, space, tab or comma), but this must be consistent for all numbers.
* You may print the numbers in decimal, [in unary](http://meta.codegolf.stackexchange.com/questions/5343/can-numeric-input-output-be-in-unary) or in [base 256 where each digit is represented by a byte value](http://meta.codegolf.stackexchange.com/questions/4708/can-numeric-input-output-be-in-the-form-of-byte-values).
* Your program must count at least as far as 2128 (inclusive) without problems and without running out of memory on a reasonable desktop PC. In particular, this means if you're using unary, you cannot store a unary representation of the current number in memory.
* Unlike our usual rules, feel free to use a language (or language version) even if it's newer than this challenge. Languages specifically written to submit a 0-byte answer to this challenge are fair game but not particularly interesting.
Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language.
* This is not about finding the language with the shortest solution for this (there are some where the empty program does the trick) - this is about finding the shortest solution in every language. Therefore, no answer will be marked as accepted.
### 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:
```
## [><>](http://esolangs.org/wiki/Fish), 121 bytes
```
```
<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = 63834; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 39069; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "//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 "//api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(42), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script>
```
[Answer]
## [Labyrinth](https://github.com/mbuettner/labyrinth), 5 bytes
```
):
\!
```
♫ The IP in the code goes round and round ♫
Relevant instructions:
```
) Increment top of stack (stack has infinite zeroes at bottom)
: Duplicate top of stack
! Output top of stack
\ Output newline
```
[Answer]
# [><>](http://esolangs.org/wiki/Fish), 8 bytes
```
01+:nao!
```
Steps:
* Push 0 on the stack
* Add 1 to the top stack element
* Duplicate top stack element
* Output the top of the stack as number
* Output a newline
* Go to step 2 by wrapping around and jumping the next instruction (step 11)
*(A less memory efficient (hence invalid) program is `llnao`.)*
[Answer]
# C (64-bit architecture only), 53 bytes
Relies on pointers being at least 64 bits and prints them in hex using the `%p` specifier. The program would return right when it hits 2^128.
```
char*a,*b;main(){for(;++b||++a;)printf("%p%p ",a,b);}
```
[Answer]
## Haskell, 21 bytes
```
main=mapM_ print[1..]
```
Arbitrary-precision integers and infinite lists make this easy :-)
Luckily `mapM_` is in the Prelude. If `Data.Traversable` was as well, we even could shrink it to 19 bytes:
```
main=for_[1..]print
```
[Answer]
# [Gol><>](https://golfish.herokuapp.com/), 3 bytes
```
P:N
```
Steps:
* Add 1 to the top stack element (at start it is an implicit 0)
* Duplicate top stack element
* Pop and output the top of the stack as number and a newline
* Wrap around to step 1 as we reached the end of the line
[Answer]
# [Marbelous](https://github.com/marbelous-lang/marbelous.py), ~~11450~~ 4632 bytes
Printing decimals is a pain!!
Definitely not winning with this one, but I thought I'd give it a shot. I hope it's ok that it pads the output to 40 zeros (to fit 2^128).
```
00@0..@1..@2..@3..@4..@5..@6..@7..@8..@9..@A..@B..@C..@D..@E..@F..@G..@H..@I..@J
\\++..00..00..00..00..00..00..00..00..00..00..00..00..00..00..00..00..00..00..00
..EhunEhunEhunEhunEhunEhunEhunEhunEhunEhunEhunEhunEhunEhunEhunEhunEhunEhunEhunEhun
....AddtAddtAddtAddtAddtAddtAddtAddtAddtAddtAddtAddtAddtAddtAddtAddtAddtAddtAddt
..&7..&7..&7..&7..&7..&7..&7..&7..&7..&7..&7..&7..&7..&7..&7..&7..&7..&7..&7..&7\/
../\&8..........................................................................
....@0..........................................................................
....../\&8......................................................................
....//..@1......................................................................
........../\&8..................................................................
......////..@2..................................................................
............../\&8..............................................................
........//////..@3..............................................................
................../\&8..........................................................
..........////////..@4..........................................................
....................../\&8......................................................
............//////////..@5......................................................
........................../\&8..................................................
..............////////////..@6..................................................
............................../\&8..............................................
................//////////////..@7..............................................
................................../\&8..........................................
..................////////////////..@8..........................................
....................................../\&8......................................
....................//////////////////..@9......................................
........................................../\&8..................................
......................////////////////////..@A..................................
............................................../\&8..............................
........................//////////////////////..@B..............................
................................................../\&8..........................
..........................////////////////////////..@C..........................
....................................................../\&8......................
............................//////////////////////////..@D......................
........................................................../\&8..................
..............................////////////////////////////..@E..................
............................................................../\&8..............
................................//////////////////////////////..@F..............
................................................................../\&8..........
..................................////////////////////////////////..@G..........
....................................................................../\&8......
....................................//////////////////////////////////..@H......
........................................................................../\&8..
......................................////////////////////////////////////..@I..
............................................................................../\&8
........................................//////////////////////////////////////..@J
&9&9&9&9&9&9&9&9&9&9&9&9&9&9&9&9&9&9&9&9
Sixteenbytedecimalprintermodulewitharegi
:Sixteenbytedecimalprintermodulewitharegi
}J}J}I}I}H}H}G}G}F}F}E}E}D}D}C}C}B}B}A}A}9}9}8}8}7}7}6}6}5}5}4}4}3}3}2}2}1}1}0}00A
/A%A/A%A/A%A/A%A/A%A/A%A/A%A/A%A/A%A/A%A/A%A/A%A/A%A/A%A/A%A/A%A/A%A/A%A/A%A/A%A
%A..%A..%A..%A..%A..%A..%A..%A..%A..%A..%A..%A..%A..%A..%A..%A..%A..%A..%A..%A..
+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O..
+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O..
:/A
..}0..}0..
..>>}0....
..>>>>\\..
....//..//
../\>>\\..
....>>..//
....>>\\..
....>>....
\\>>//....
..>>......
..>>......
../\......
..../\<<..
......<<..
..\\<<//..
....~~....
....++....
....\\..//
\\....>9\/
..\\..?0..
......++..
....\\....
......{0..
:%A
@0..
}0..
<A-A
{0@0
:Eg
}0}0}0}0}0}0}0}0
^7^6^5^4^3^2^1^0
~~....~~~~..~~~~
^0^0^0^0^0^0^0^0
{0{0{0{0{0{0{0{0
:Ehun
}0..}0
Eg..&0
=8&0{0
&1\/00
0100&0
&1&1{1
{1{0
:Addt
}0}1
{1{1
```
[Answer]
## [Hexagony](https://github.com/mbuettner/hexagony), ~~12~~ ~~11~~ ~~10~~ 7 bytes
*Thanks to alephalpha for fitting the code into side-length 2.*
```
10})!';
```
Unfolded:
```
1 0
} ) !
' ;
```
This one is fairly simple. `10` writes a 10, i.e. a linefeed to the initial memory edge. Then `})!';` is repeatedly executed in a loop:
* `}` move to the next memory edge.
* `)` increment it.
* `!` print it as an integer.
* `'` move back to the 10.
* `;` print it as a character.
I believe that this is optimal (although by far not unique). I've let the brute force script I wrote [for this answer](https://codegolf.stackexchange.com/a/62812/8478) search for 6-byte solutions under the assumption that it would have to contain at least one each of `;` and `!` and either `(` or `)`, and would not contain `?`, `,` or `@`, and it didn't find any solutions.
[Answer]
# bc, 10
```
for(;;)++i
```
Unusual that `bc` is shorter than [`dc`](https://codegolf.stackexchange.com/a/63861/11259).
From `man bc`:
>
> DESCRIPTION
>
>
> bc is a language that supports arbitrary precision numbers
>
>
>
[Answer]
# Pyth, 4 bytes
```
.V1b
```
### Explanation:
```
.V1 for b in range(1 to infinity):
b print b
```
[Answer]
# Java, ~~139~~ ~~138~~ ~~127~~ 123 bytes
```
class K{public static void main(String[]a){java.math.BigInteger b=null;for(b=b.ZERO;;)System.out.println(b=b.add(b.ONE));}}
```
[Answer]
# Mathematica, 22 bytes
```
i=0;While[Echo[++i]>0]
```
[`Echo`](http://reference.wolfram.com/language/ref/Echo.html) is a new function in Mathematica 10.3.
[Answer]
# Python 3, ~~33~~ 25 bytes
As far as I understand, Pythons integers are arbitrary precision, and `print()` automatically produces newlines.
Thanks for @Jakub and @Sp3000 and @wnnmaw! I really don't know much python, the only think I knew was that it supports arbitrary size integers=)
```
k=1
while 1:print(k);k+=1
```
[Answer]
# Ruby, ~~15~~ 12 bytes
```
loop{p$.+=1}
```
* `p`, when given an integer, prints the integer as-is (courtesy of [@philomory](https://codegolf.stackexchange.com/users/47276/philomory))
* `$.` is a magical variable holding the number of lines read from stdin. It is obviously initialized to 0, and also assignable :)
[Answer]
# [Samau](https://github.com/AlephAlpha/Samau), 2 bytes
```
N)
```
Explanation:
```
N push the infinite list [0 1 2 ...] onto the stack
) increase by 1
```
When the output of a program is a list, the outmost brackets are omitted.
[Answer]
# [Microsoft PowerPoint](https://www.youtube.com/watch?v=uNjxe8ShM-8) (33 Slides, 512 shapes to meet minimum requirements)
Storage representation is in hexadecimal.
## Directions
* Click the blue square to advance the counter (or propagate the carry), or make an AutoHotKey Script to click it for you.
* You can view the number's digits at any time using the green buttons. (It causes unintended behavior if you click the blue buttons after viewing another digit.) This is just for a better UX. It still counts up as normal as long as you keep clicking the blue button. In other words, no user decision is required.
* If you reach the end, it displays a congratulatory message.
You can get the PPTX [here](https://drive.google.com/open?id=1JTbg0fSnWV2ig7PYYb1jB5kWCteW9XgU). Requires PowerPoint to run.
Before you comment that Microsoft PowerPoint is not a programming language, it has been shown that PowerPoint is Turing complete (in the same sense that conventional languages such as C are Turing complete). A brief discussion is given [here](https://www.andrew.cmu.edu/user/twildenh/PowerPointTM/Paper.pdf).
[Answer]
# [makina](https://github.com/GingerIndustries/makina), 22 bytes
```
v
>Pv
^>OC
^Uu>n0;
^O<
```
I AM REAL HUMAN YOU SHOULD TRUST ME AND DO WHAT I SAY
[Answer]
# Matlab, 132 bytes
```
a=0;while 1;b=a==9;n=find(cumsum(b)-(1:numel(b)),1);a(n)=a(n)+1;a(1:n-1)=0;if ~numel(n);a=[0*a,1];end;disp([a(end:-1:1)+'0','']);end
```
Ok, I think this is the *first serious* answer that accomplishes this task without a trivial builtin abitrary size integer. This program implements an arbitrary size integer as an array of integers. Each integer is always between 0 and 9, so each array element represents one decimal digit. The array size wil be increased by one as soon as we are at e.g. `999`. The memory size is no problem here, as `2^128` only requires an array of length 39.
```
a=0;
while 1
b=a==9;
%first number that is not maxed out
n=find(cumsum(b)-(1:numel(b)),1);
%increase that number, and sett all maxed out numbers to zero
a(n)=a(n)+1;
a(1:n-1)=0;
if ~numel(n) %if we maxed out all entries, add another digit
a=[0*a,1];
end
disp([a(end:-1:1)+'0',''])%print all digits
end
```
[Answer]
# [Processing](http://www.processing.org), ~~95~~ ~~85~~ 71 bytes
```
java.math.BigInteger i;{i=i.ZERO;}void draw(){println(i=i.add(i.ONE));}
```
I tried something with a while loop but it causes all of Processing to crash, so I'll stick with this for now.
(Thanks to @SuperJedi224 and @TWiStErRob for suggestions.)
[Answer]
# JavaScript (ES6), ~~99~~ ~~94~~ 67 bytes
```
for(n=[i=0];;)(n[i]=-~n[i++]%10)&&alert([...n].reverse(i=0).join``)
```
`alert` is the generally accepted `STDOUT` equivalent for JavaScript but using it means that consecutive numbers are automatically separated. I've assumed that outputting a character after the number is not necessary because of this.
[Answer]
## C++, ~~146~~ ~~141~~ 138 bytes
Using a standard bigint library is perhaps the *most* boring way of answering this question, but someone had to do it.
```
#include<stdio.h>
#include<boost/multiprecision/cpp_int.hpp>
int main(){for(boost::multiprecision::uint512_t i=1;;){printf("%u\n",i++);}}
```
Ungolfed:
```
#include<cstdio>
#include<boost/multiprecision/cpp_int.hpp>
int main()
{
for(boost::multiprecision::uint512_t i=1;;)
{
std::printf("%u\n", i++);
}
}
```
The reason the golfed version uses `stdio.h` and not `cstdio` is to avoid having to use the `std::` namespace.
This is my first time golfing in C++, let me know if there's any tricks to shorten this further.
[Answer]
## Intel 8086+ Assembly, 19 bytes
```
68 00 b8 1f b9 08 00 31 ff f9 83 15 00 47 47 e2 f9 eb f1
```
Here's a breakdown:
```
68 00 b8 push 0xb800 # CGA video memory
1f pop ds # data segment
b9 08 00 L1: mov cx, 8 # loop count
31 ff xor di, di # ds:di = address of number
f9 stc # set carry
83 15 00 L2: adc word ptr [di], 0 # add with carry
47 inc di
47 inc di
e2 f9 loop L2
eb f1 jmp L1
```
It outputs the 128 bit number on the top-left 8 screen positions. Each screen position holds a 8-bit ASCII character and two 4 bit colors.
*Note: it wraps around at 2128; simply change the `8` in`mov cx, 8` to `9` to show a 144 bit number, or even `80*25` to show numbers up to 232000.*
## Running
### 1.44Mb bzip2 compressed, base64 encoded bootable floppy Image
Generate the floppy image by copy-pasting the following
```
QlpoOTFBWSZTWX9j1uwALTNvecBAAgCgAACAAgAAQAgAQAAAEABgEEggKKAAVDKGgAaZBFSMJgQa
fPsBBBFMciogikZcWgKIIprHJDS9ZFh2kUZ3QgggEEh/i7kinChIP7HrdgA=
```
into this commandline:
```
base64 -d | bunzip2 > floppy.img
```
and run with, for instance, `qemu -fda floppy.img -boot a`
### 1.8Mb bootable ISO
This is a base64 encoded bzip2 compressed ISO image. Generate the iso by pasting
```
QlpoOTFBWSZTWZxLYpUAAMN/2//fp/3WY/+oP//f4LvnjARo5AAQAGkAEBBKoijAApcDbNgWGgqa
mmyQPU0HqGCZDQB6mQ0wTQ0ZADQaAMmTaQBqekyEEwQaFA0AA0AxBoAAA9Q0GgNAGg40NDQ0A0Bi
BoDIAANNAA0AyAAABhFJNIJiPSmnpMQDJpp6nqeo0ZDQaAANB6IA0NAGj1EfIBbtMewRV0acjr8u
b8yz7cCM6gUUEbDKcCdYh4IIu9C6EIBehb8FVUgEtMIAuvACCiO7l2C0KFaFVABcpglEDCLmQqCA
LTCAQ5EgnwJLyfntUzNzcooggr6EnTje1SsFYLFNW/k+2BFABdH4c4vMy1et4ZjYii1FbDgpCcGl
mhZtl6zX+ky2GDOu3anJB0YtOv04YISUQ0JshGzAZ/3kORdb6BkTDZiYdBAoztZA1N3W0LJhITAI
2kSalUBQh60i3flrmBh7xv4TCMEHTIOM8lIurifMNJ2aXr0QUuLDvv6b9HkTQbKYVSohRPsTOGHi
isDdB+cODOsdh31Vy4bZL6mnTAVvQyMO08VoYYcRDC4nUaGGT7rpZy+J6ZxRb1b4lfdhtDmNwuzl
E3bZGU3JTdLNz1uEiRjud6oZ5kAwqwhYDok9xaVgf0m5jV4mmGcEagviVntDZOKGJeLjyY4ounyN
CWXXWpBPcwSfNOKm8yid4CuocONE1mNqbd1NtFQ9z9YLg2cSsGQV5G3EhhMXKLVC2c9qlqwLRlw4
8pp2QkMAMIhSZaSMS4hGb8Bgyrf4LMM5Su9ZnKoqELyQTaMAlqyQ3lzY7i6kjaGsHyAndc4iKVym
SEMxZGG8xOOOBmtNNiLOFECKHzEU2hJF7GERK8QuCekBUBdCCVx4SDO0x/vxSNk8gKrZg/o7UQ33
Fg0ad37mh/buZAbhiCIAeeDwUYjrZGV0GECBAr4QVYaP0PxP1TQZJjwT/EynlkfyKI6MWK/Gxf3H
V2MdlUQAWgx9z/i7kinChITiWxSo
```
into
```
base64 -d bunzip2 > cdrom.iso
```
and configure a virtual machine to boot from it.
### DOS .COM
This is a base64 encoded [DOS .COM](https://en.wikipedia.org/wiki/COM_file) executable:
```
aAC4H7kIADH/+YMVAEdH4vnr8Q==
```
Generate a .COM file using
```
/bin/echo -n aAC4H7kIADH/+YMVAEdH4vnr8Q== | base64 -d > COUNTUP.COM
```
and run it in (Free)DOS.
[Answer]
## sed, ~~116~~ ~~92~~ 83 bytes
```
:
/^9*$/s/^/0/
s/.9*$/_&/
h
s/.*_//
y/0123456789/1234567890/
x
s/_.*//
G
s/\n//p
b
```
**Usage:**
Sed operates on text input and it *needs* input do anything. To run the script, feed it with just one empty line:
```
$ echo | sed -f forever.sed
```
**Explanation:**
To increment a number, the current number is split up into a prefix and a suffix where the suffix is of the form `[^9]9*`. Each digit in the suffix is then incremented individually, and the two parts are glued back together. If the current number consists of `9` digits only, a `0` digit is appended, which will immediately incremented to a `1`.
[Answer]
## Clojure, 17 bytes
```
(map prn (range))
```
Lazy sequences and arbitrary precision integers make this easy (as for Haskell and CL). `prn` saves me a few bytes since I don't need to print a format string. `doseq` would probably be more idiomatic since here we're only dealing with side effects; `map` doesn't make a lot of sense to use since it will create a sequence of `nil` (which is the return value of each `prn` call.
Assuming I count forever, the null pointer sequence which results from this operation never gets returned.
[Answer]
## C# .NET 4.0, ~~111~~ ~~103~~ ~~102~~ 97 bytes
```
class C{static void Main(){System.Numerics.BigInteger b=1;for(;;)System.Console.WriteLine(b++);}}
```
I didn't find any C# answer here, so I just had to write one.
.NET 4.0 is required, because it's the first version that includes [BigInteger](https://msdn.microsoft.com/library/system.numerics.biginteger(v=vs.100).aspx). You have to reference [System.Numerics.dll](https://msdn.microsoft.com/en-us/library/system.numerics(v=vs.100).aspx) though.
With indentation:
```
class C
{
static void Main()
{
System.Numerics.BigInteger b = 1;
for (;;)
System.Console.WriteLine(b++);
}
}
```
*Thanks to sweerpotato, Kvam, Berend for saving some bytes*
[Answer]
# [MarioLANG](http://esolangs.org/wiki/MarioLANG), 11 bytes
```
+<
:"
>!
=#
```
Inspired by [Martin Büttner's answer in another question](https://codegolf.stackexchange.com/questions/62230/simple-cat-program/62425#62425).
[Answer]
## CJam, 7 bytes
```
0{)_p}h
```
Explanation:
```
0 e# Push a zero to the stack
{ e# Start a block
) e# Increment top of stack
_ e# Duplicate top of stack
p e# Print top of stack
} e# End block
h e# Do-while loop that leaves the condition on the stack
```
Note: Must use Java interpreter.
[Answer]
## C, 89 bytes
A new approach (implementing a bitwise incrementer) in C:
```
b[999],c,i;main(){for(;;)for(i=c=0,puts(b);i++<998;)putchar(48+(c?b[i]:(b[i]=c=!b[i])));}
```
**Less golfed**
```
int b[999], c, i;
main() {
for(;;)
for(i=c=0, puts(b); i++ < 998;)
putchar(48 + (c ? b[i] : (b[i] = c = !b[i])));
}
```
**Terminate**
This version has the slight flaw, that it does not terminate (which isn't a requirement at the moment). To do this you would have to add 3 characters:
```
b[129],c=1,i;main(){for(;c;)for(i=c=0,puts(b);i++<128;)putchar(48+(c?b[i]:(b[i]=c=!b[i])));}
```
[Answer]
# [Foo](http://esolangs.org/wiki/Foo), 6 bytes
```
(+1$i)
```
---
### Explanation
```
( ) Loop
+1 Add one to current element
$i Output current element as a decimal integer
```
[Answer]
# [Acc!](https://codegolf.stackexchange.com/a/62404), ~~64~~ 65 bytes
Also works in [*Acc!!*](https://codegolf.stackexchange.com/a/62493).
```
Count q while 1 {
Count x while q-x+1 {
Write 7
}
Write 9
}
```
This prints the numbers out in unary using [Bell characters](https://en.wikipedia.org/wiki/Bell_character) seperated by tabs. If I have to use a more standard character, that would make the program **66 bytes**.
The Acc! interpreter provided in the linked answer translates Acc! to Python, which does support arbritrary-precision integers.
[Answer]
## [Minkolang](https://github.com/elendiastarman/Minkolang), 4 bytes
```
1+dN
```
[Try it here.](http://play.starmaninnovations.com/minkolang/?code=1%2BdN) (Well, actually, be careful. 3 seconds of run time was enough to get up to ~40,000.)
`1+` adds 1 to the top of stack, `d` duplicates it, and `N` outputs the top of stack as an integer with a trailing space. This loops because Minkolang is toroidal, so when the program counter goes off the right edge, it reappears on the left.
] |
[Question]
[
Write the shortest program that takes one input (n) from STDIN (or equivalent) and outputs a simple incrementing function with one argument (x) that returns x + n but the function must be in a different language. Pretty simple!
**This is code-golf, normal rules apply, shortest program wins.**
Example: ><> to Python (Ungolfed)
```
!v"def i(x):"a" return x+"ir!
>l?!;o
```
Input:
```
3
```
Output:
```
def i(x):
return x+3
```
EDIT: Anonymous functions and lambda expressions are allowed!
[Answer]
# [GS2](https://github.com/nooodl/gs2) → K, 2 bytes
```
•+
```
This prints a tacit, monadic function. The source code uses the [CP437](https://en.wikipedia.org/w/index.php?title=Code_page_437&oldid=565442465#Characters) encoding. [Try it online!](http://gs2.tryitonline.net/#code=4oCiKw&input=NDI)
## Test run
```
$ xxd -c 2 -g 1 sum-func.gs2
00000000: 07 2b .+
$ printf 42 | gs2 sum-func.gs2
42+
$ kona
K Console - Enter \ for help
(42+) 69
111
f : 42+
42+
f 69
111
```
## How it works
### GS2
* GS2 automatically reads from STDIN and pushes the input on the stack.
* `•` indicates that the next byte is a singleton string literal.
* Before exiting, GS2 prints all stack items.
### K
Left argument currying is automatic in K.
Here, `n+` turns the dyadic function `+` into a monadic function by setting its left argument to `n`.
[Answer]
# [ShapeScript](https://github.com/DennisMitchell/ShapeScript) → J, 4 bytes
```
"&+"
```
This prints a tacit, monadic verb. Try it online: [ShapeScript](http://shapescript.tryitonline.net/#code=IiYrIg==&input=NDI=), [J](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=42%26%2B%2069)
## Test run
```
$ cat sum-func.shape; echo
"&+"
$ printf 42 | shapescript sum-func.shape; echo
42&+
$ j64-804/jconsole.sh
42&+ 69
111
f =: 42&+
f 69
111
```
## How it works
### ShapeScript
* ShapeScript automatically reads from STDIN and pushes the input on the stack.
* `"&+"` pushes that string on the stack.
* Before exiting, ShapeScript prints all stack items.
### J
`&` performs argument currying.
Here, `n&+` turns the dyadic verb `+` into a monadic verb by setting its left argument to `n`.
[Answer]
# GolfScript → CJam, 4 bytes
```
{+}+
```
This prints a code block (anonymous function). Try it online: [GolfScript](http://golfscript.apphb.com/?c=IjQyIiAjIFNpbXVsYXRlIGlucHV0IGZyb20gU1RESU4uCgp7K30r), [CJam](http://cjam.aditsu.net/#code=69%20%7B42%20%2B%7D%20~&input=42)
## Test run
```
$ cat sum-func.gs; echo
{+}+
$ printf 42 | golfscript sum-func.gs
{42 +}
$ cjam
> 69 {42 +} ~
111
> {42 +}:F; 69F
111
```
## How it works
### GolfScript
* GolfScript automatically reads from STDIN and pushes the input on the stack.
* `{+}` pushes that block on the stack.
* `+` performs concatenation, which happily concatenates a string and a block.
* Before exiting, GolfScript prints all stack items.
### CJam
`{n +}` is a code block that, when executed, first pushes `n` on the stack, then executes `+`, which pops two integers from the stack and pushes their sum.
[Answer]
# BrainF\*\*\* to JavaScript ES6, 57 bytes
```
----[-->+++<]>--.[-->+<]>+.+.--[->++<]>.[--->+<]>+++.[,.]
```
(Assumes that the input is composed of numeric characters)
Say `1337` is your input. Then, this would compile to:
```
x=>x+1337
```
[Answer]
# R to Julia, 19 bytes
```
cat("x->x+",scan())
```
This reads an integer from STDIN using `scan()` and writes an unnamed Julia function to STDOUT using `cat()`. The Julia function is simply `x->x+n`, where `n` comes from the R program.
[Answer]
# Rotor to K, 2 bytes
```
'+
```
Might as well jump in on the K bandwagon.
[Answer]
# [Malbolge](http://zb3.github.io/malbolge-tools/#interpreter) to JavaScript ES6, 71 bytes
```
('&%@9]!~}43Wyxwvutsr)Mon+HGi4~fBBdR->=_]:[875t4rT}0/Pf,d*((II%GEE!Y}Az
```
It's always fun to generate Malbolge code.
[Answer]
# Minecraft 1.8.7 to K, ~~7~~ 6 + 33 + 27 + 62 = ~~129~~ 128 Bytes
This is using [this version of byte counting](http://meta.codegolf.stackexchange.com/a/7397/44713).
[![the system](https://i.stack.imgur.com/Y7fFE.png)](https://i.stack.imgur.com/Y7fFE.png)
Command blocks (going from left to right):
```
scoreboard objectives add K dummy
```
```
scoreboard players set J K <input>
```
```
tellraw @a {score:{name:"J",objective:"K"},extra:[{text:"+"}]}
```
This could probably be golfed a little more, but it's fairly simple: generate a variable `J` with the objective `K` and set its score for that objective to the input (there is no STDIN - I figured this was close enough). Then, after a tick, output the score of the variable `J` for the objective `K` followed by a `+`. Easy peasy.
[Answer]
# [O](https://github.com/phase/o) to K, 5 bytes
```
i'++o
```
Thanks to **[@kirbyfan64sos](https://codegolf.stackexchange.com/users/21009/kirbyfan64sos)**
Another version using features added after the challenge was created.
```
i'+
```
* Gets input, pushes to stack
* Pushes '+' as a string
* Outputs stack contents
[Answer]
## [Seriously](https://github.com/Mego/Seriously) to Python, 15 bytes
`,"lambda n:n+"+`
Expects input to be in string form, i.e. `"3"`
Explanation:
```
,: read value from input
"lambda n:n+": push this literal string
+: concatenate top two values on stack
```
[Try it online](http://seriouslylang.herokuapp.com/link/code=2c226c616d626461206e3a6e2b222b&input=%223%22) (you will have to manually enter the input because the permalinks don't like quotes)
[Answer]
# Pyth to APL, ~~7~~ 5 bytes
```
+z"--
```
The Pyth code simply concatenates the input (`z`) with the string `"--"`. This creates an unnamed monadic train in APL with the form `n--`, where `n` comes from Pyth. When calling it in APL, `(n--)x` for some argument `x` computes `n--x = n-(-x) = n+x`.
Try: [Pyth](https://pyth.herokuapp.com/?code=%2Bz%22--&input=3&debug=0), [APL](http://tryapl.org/?a=f%u21903--%u22C4f%202&run)
Saved 2 bytes thanks to Dennis!
[Answer]
# rs -> K, 2 bytes
```
/+
```
[Live demo.](http://kirbyfan64.github.io/rs/index.html?script=%2F%2B&input=2)
[Answer]
## [><>](https://esolangs.org/wiki/Fish) to Python, 25 + 3 = 28 bytes
```
"v+x:x adbmal
o/?(3l
;>~n
```
Takes input via the `-v` flag, e.g.
```
py -3 fish.py add.fish -v 27
```
and outputs a Python lambda, e.g. `lambda x:x+27`.
For a bonus, here's an STDIN input version for 30 bytes:
```
i:0(?v
x+"r~/"lambda x:
o;!?l<
```
[Answer]
# [Mouse](http://en.wikipedia.org/wiki/Mouse_(programming_language)) to Ruby, 19 bytes
```
?N:"->x{x+"N.!"}"$
```
Ungolfed:
```
? N: ~ Read an integer from STDIN, store in N
"->x{x+" ~ Write that string to STOUT
N. ! ~ Write N
"}"$ ~ Close bracket, end of program
```
This creates an unnamed Ruby function of the form `->x{x+n}` where `n` comes from Mouse.
[Answer]
# Haskell to Mathematica, 14 bytes
```
(++"+#&").show
```
[Answer]
# Mathematica to C#, 22 bytes
```
"x=>x+"<>InputString[]
```
Outputs a C# `Func<int, int>` of form
```
x=>x+n
```
[Answer]
# Pyth -> K, 4 bytes
```
+z\+
```
K is really easy to abuse here...
[Live demo.](https://pyth.herokuapp.com/?code=%2Bz%5C%2B&input=2&debug=0)
[Answer]
# Brainfuck to Java, 273
```
+[----->+++++.+++++.++++++.[---->++++.+[->++++.-[->+++-.-----[->+++.+++++.++++++.[---->++++.-[--->++-.[----->++-.[->+++.---------.-------------.[--->+---.+.---.----.-[->+++++-.-[--->++-.[----->+++.,[.,]+[--------->+++.-[--->+++.
```
Outputs a method like `int d(int i){return i+42;}` (which doesn't *look* like a Java method, but... Java!)
[Answer]
# POSIX shell to Haskell, 19 bytes
```
read n;echo "($n+)"
```
Anonymous functions being allowed, Haskell is a good output choice with the operator sections.
[Answer]
# PHP → JavaScript (ES6), 20 ~~24~~ bytes
Reading from *STDIN* is always expensive in PHP. It looks a bit strange:
```
x=>x+<?fgets(STDIN);
```
It prints `x=>x+` and waits for user input to complete the string, terminates with the complete anonymous JavaScript function, e.g. `x=>x+2`.
**First version (24 bytes**)
```
<?='x=>x+'.fgets(STDIN);
```
[Answer]
# [Retina](https://github.com/mbuettner/retina) to [Pip](https://github.com/dloscutoff/pip), 4 bytes
Uses one file for each of these lines + 1 penalty byte; or, put both lines in a single file and use the `-s` flag.
```
$
+_
```
Matches the end of the input with `$` and puts `+_` there. This results in something of the form `3+_`, which is an anonymous function in Pip.
[Answer]
# Bash → C/C++/C#/Java, 33 bytes
and maybe others
```
echo "int f(int a){return a+$1;}"
```
[Answer]
## [Tiny Lisp](https://codegolf.stackexchange.com/q/62886/2338) to [Ceylon](http://ceylon-lang.org/), ~~68~~ 61
```
(d u(q((n)(c(q(Integer x))(c(q =>)(c(c(q x+)(c n()))()))))))
```
Tiny Lisp doesn't have real input and output – it just has expression evaluation.
This code above creates a function and binds it to `u`.
You can then call `u` with the argument `n` like this: `(u 7)`, which will evaluate to this Tiny Lisp value:
```
((Integer x) => (x+ 7))
```
This is a valid Ceylon expression, for an anonymous function which adds 7 to an arbitrary integer.
*Thanks to DLosc for an improvement of 7 bytes.*
[Answer]
# JavaScript to [Lambda Calculus](http://www.ics.uci.edu/~lopes/teaching/inf212W12/readings/lambda-calculus-handout2.pdf), 39 bytes
(This uses the linked document as a basis.)
```
alert((x=>`λa(${x}(add a))`)(prompt()))
```
Say input is `5`. Then this becomes:
```
"λa(5(add a))"
```
[Answer]
# Python 2 to CJam, ~~18~~ 20 bytes
*Thanks to LegionMammal978 for correcting the functionality.*
```
print"{%f+}"%input()
```
The Python does a basic string format. `%f` is the code for a float, and since I wouldn't lose any bytes for handling floats, I went ahead and did so.
The CJam is much the same as the Golfscript->CJam answer. It looks something like this:
```
{7.4+}
```
or:
```
{23+}
```
It's a block that takes the top value off the stack, pushes the special number, then adds them.
[Answer]
# [Microscript II](http://esolangs.org/wiki/Microscript_II) to Javascript ES6, 9 bytes
```
"x=>x+"pF
```
[Answer]
# GNU sed to C, 46 bytes
```
sed -r 's/^([0-9]+)$/f(int x){return x+\1;}/'
```
[Answer]
# Vitsy to K, 5 Bytes
\o/ K will be being used very soon if it can do this.
```
N'+'Z
```
or maybe...
```
N'+'O
```
If the input is taken as a string (only for 0-9 input)...
```
i'+'Z
```
All of these, for input 2, will output:
```
2+
```
[Answer]
## [Ceylon](http://ceylon-lang.org/) to [Tiny lisp](https://codegolf.stackexchange.com/q/62886/2338), 76
```
shared void run(){print("(q((x)(s ``process.readLine()else""``(s 0 x))))");}
```
This produces (after reading a line of input) output like `(q((x)(s 5(s 0 x))))`, which evaluates in Tiny Lisp to `((x) (s 5 (s 0 x)))`, a function which takes an argument `x`, subtracts it from 0, and subtracts the result from 5. (Yeah, this is how one adds in Tiny Lisp, there is only a subtraction function build in. Of course, one could define an addition function first, but this would be longer.)
You can use it like this as an anonymous function:
```
((q((x)(s 5(s 0 x)))) 7)
```
(This will evaluate to 12.)
Or you can give it a name:
```
(d p5 (q((x)(s 5(s 0 x)))))
(p5 7)
```
*Corrections and Golfing Hints from DLosc, the author of Tiny Lisp.*
[Answer]
# [Japt](https://github.com/ETHproductions/Japt) → [TeaScript](https://github.com/vihanb/TeaScript), 5 bytes
```
U+"+x
```
This is pretty simple.
---
### Explanation
```
U+ // Input added to the string...
"+x // This is the string
```
] |
[Question]
[
Lots of people like to play music for fun and entertainment. Unfortunately, music is pretty difficult sometimes. That is why you're here!
## Task
It's your job to make reading music much easier for those struggling with it. You need to write a program or function that takes as input a musical staff, and outputs the names of the notes written on that staff.
## Staff, clef, and notes
A [musical staff](https://en.wikipedia.org/wiki/Staff_(music)) , or stave, is five horizontal lines, inbetween which are four spaces. Each line or space represents a different note (pitch), depending on the clef.
There are a fair few different musical clefs to choose from, but we'll only be dealing with one for now: the [treble clef](https://en.wikipedia.org/wiki/Clef#Treble_clef). On the treble clef, the notes are represented on the staff as follows:
```
Lines
F ----------
D ----------
B ----------
G ----------
E ----------
```
```
Spaces
----------
E
----------
C
----------
A
----------
F
----------
```
## Formatting of the input
Input will be given as a single string, as follows:
```
---------------
---------------
---------------
---------------
---------------
```
The five lines and four spaces of the staff are constructed out of nine rows of characters. Lines of the staff are constructed with `-` (hyphen) characters, and spaces with (space). Each row is separated from the next by a single newline character, eg:
`-----\n \n-----\n \n-----\n \n-----\n \n-----\n`
The rows are of arbitrary length (to a reasonable amount that can be handled by your programming language), and each row is exactly the same length in characters as the others. Also note that the rows will always be of a length that is divisible by three (to fit the pattern of one note followed by two columns without a note).
Notes are placed on this staff by replacing the appropriate `-` or character with `o`. Notes can also be raised (sharp) or lowered (flat) in pitch by a semitone (about half the frequency difference between a note and its adjacent notes). This will be represented by the characters `#` and `b`, respectively, in place of the `o`. Each note will be separated from the next by exactly two `-` characters, and the first note will always occur on the first "column" of `-` and (space) characters.
When outputting note names, your program should always use the capitalised letters (`A B C D E F G`) corresponding to the note given on the staff. For sharp (`#`) and flat (`b`) notes, your program needs to append `#` and `b`, respectively, to the letter corresponding to the note. For a natural note that is not sharp or flat, a (space) should be appended instead.
## Example
Input:
```
---------------------o--
o
---------------o--------
o
---------b--------------
o
---o--------------------
o
------------------------
```
\*note all "empty space" in this example is actually (space character).
In this case (a simple F major scale), your program should output this:
```
F G A Bb C D E F
```
Note the spacing between the characters of the output should be exactly as shown above, to fit correctly with the notes on the staff. Between all the note names there are two (space) characters, except between the `Bb` and `C`. The `b` here replaces one of the (space) characters.
Another example
Input:
```
------------------------
o
------------------#-----
#
------------o-----------
o
------#-----------------
#
o-----------------------
```
Output:
`E F# G# A B C# D# E`
One more example for good luck
Input:
```
---------------------
o o o o
---------------------
o
---------------------
---------------o--o--
---------------------
```
Output:
`E E E C E G G`
## Rules
* Notes will only ever be given in the five line staff range of E flat up to F sharp (except for the challenges, see below)
* Any note could be sharp or flat, not just those seen commonly in music (eg. despite B# actually just being played as C in reality, B# can still occur in the input)
* You can assume there will be exactly one note per 3 columns (so there will be no chords or anything like that, and no rests either)
* You can assume the last note will be followed by two columns with no notes
* You can assume even the last line of the staff will be followed by a single newline character
* Input should be taken from STDIN (or language equivalent) or as function parameter
* Output should be to STDOUT (or language equivalent) or as a return result if your program is a function
* Standard loopholes and built-ins are allowed! Music is about experimenting and playing around. Go ahead and have fun with your language (although recognise that exploiting a loophole may not produce the most interesting program)
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest program in bytes wins
## Bonus challenges
* -10% if your program can also successfully process the space above the top line of the staff (G, G#, Gb).
* -10% if your program can also successfully process the space below the bottom line of the staff (D, D#, Db)
* In these cases your program would take as input an additional row at the start and end; these rows should be treated exactly the same as the other nine rows
[Answer]
## CJam (40 37 \* 0.8 = 29.6 points)
```
qN/z3%{_{iD%6>}#_~'H,65>=@@=+'oSerS}%
```
[Online demo](http://cjam.aditsu.net/#code=qN%2Fz3%25%7B_%7BiD%256%3E%7D%23_~'H%2C65%3E%3D%40%40%3D%2B'oSerS%7D%25&input=%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20o%20%20%20%20%20%0A---------------------o--------%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20o%20%20%20%20%20%20%20%20%20%20%20%0A---------------o--------------%0A%20%20%20%20%20%20%20%20%20%20%20%20%23%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%0A---------b--------------------%0A%20%20%20%20%20%20o%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%0A---o--------------------------%0Ao%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%0A------------------------------%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%23%20%20)
Thanks to [indeed](https://codegolf.stackexchange.com/users/47009/indeed) for pointing out some pre-defined variables which I'd forgotten about.
[Answer]
# Ruby, 106 bytes \*0.8 = 84.8
```
->s{a=' '*l=s.index('
')+1
s.size.times{|i|s[i].ord&34>33&&(a[i%l,2]='GFEDCBA'[i/l%7]+s[i].tr(?o,' '))}
a}
```
Ungolfed in test program
```
f=->s{a=' '*l=s.index('
')+1 #l = length of first row, initialize string a to l spaces
s.size.times{|i| #for each character in s
s[i].ord&34>33&& #if ASCII code for ob#
(a[i%l,2]= #change 2 bytes in a to the following string
'GFEDCBA'[i/l%7]+s[i].tr(?o,' '))}#note letter, and copy of symbol ob# (transcribe to space if o)
a} #return a
t='
---------------------o--
o
---------------o--------
o
---------b--------------
o
---o--------------------
o
------------------------
'
u='
------------------------
o
------------------#-----
#
------------o-----------
o
------#-----------------
#
o-----------------------
'
v='
---------------------
o o o o
---------------------
o
---------------------
---------------o--o--
---------------------
'
puts f[t]
puts f[u]
puts f[v]
```
[Answer]
# JavaScript (ES6), 144 bytes - 20% = 115.2
```
f=s=>(n=[],l=s.indexOf(`
`)+1,[...s].map((v,i)=>(x=i%l,h=v.match(/[ob#]/),n[x]=h?"GFEDCBAGFED"[i/l|0]:n[x]||" ",h&&v!="o"?n[x+1]=v:0)),n.join``)
```
## Explanation
```
f=s=>(
n=[], // n = array of note letters
l=s.indexOf(`
`)+1, // l = line length
[...s].map((v,i)=>( // iterate through each character
x=i%l, // x = position within current line
h=v.match(/[ob#]/), // h = character is note
n[x]= // set current note letter to:
h?"GFEDCBAGFED"[i/l|0] // if it is a note, the letter
:n[x]||" ", // if not, the current value or space if null
h&&v!="o"?n[x+1]=v:0 // put the sharp/flat symbol at the next position
)),
n.join`` // return the note letters as a string
)
```
## Test
Remember to add a line above the staff that is the exact length of the other lines because this solution includes parsing the lines above and below the staff.
```
f=s=>(n=[],l=s.indexOf(`
`)+1,[...s].map((v,i)=>(x=i%l,h=v.match(/[ob#]/),n[x]=h?"GFEDCBAGFED"[i/l|0]:n[x]||" ",h&&v!="o"?n[x+1]=v:0)),n.join``)
```
```
<textarea id="input" style="float:left;width:200px;height:175px">
---------------------o--
o
---------------o--------
o
---------b--------------
o
---o--------------------
o
------------------------
</textarea>
<div style="float:left">
<button onclick="results.innerHTML=f(input.value)">Test</button>
<pre id="results"></pre>
</div>
```
] |
[Question]
[
# `cat` goes "Meow"
We are all familiar with the concept of a `cat` program. The user types something in, it is echoed back to the user. Easy. But all `cat` programs I've seen so far have missed one fact: a `cat` goes "Meow". So your task is to write a program that copies all `STDIN` to `STDOUT` **UNLESS** the input is `cat`, in which case your program should output `cat goes "Meow"`.
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so your score is your byte count, with a few modifiers:
* If your program works for any additional animals other than `cat` (e.g. `cow: cow goes "Moo"`), for each additional animal: -10
* If your program doesn't use the word "cat": -15
* If your program responds to `fox` with "What does the fox say": -25
### Animals and sounds that go together:
`cow goes moo`
`duck goes quack`
`sheep goes baa`
`bees go buzz`
`frogs go croak`
Anything else on [this list](https://en.wikipedia.org/wiki/List_of_animal_sounds) is allowed.
## Rules
* [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply
* You must not write anything to `STDERR`
* You can use single quotes/no quotes instead of double quotes.
## Leaderboard
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
## Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
## Ruby, <s>104</s> <s>101</s> 96 bytes
```
If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:
```
## Perl, 43 + 2 (-p flag) = 45 bytes
```
You can also make the language name a link which will then show up in the leaderboard snippet:
```
## [><>](http://esolangs.org/wiki/Fish), 121 bytes
```
```
var QUESTION_ID=62500;var OVERRIDE_USER=46470;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]
## Pyth, 82-95 = -13 bytes
```
+z*}zKc."atÜiÃ'4ãl¾Eªîiû<-È&e"\jjk[d"goes"dNr@c."bw««[áÅ3ÏB"\c%x`Kz3 3N
```
I finally got around to converting my new functional Python 2 entry to Pyth. It doesn't beat the top contender. Turns out zipping together more animals into a larger dictionary reduces score faster than cleverly associating animals with sounds. This supports 8 animals in addition to cat: rhino, okapi, moose, lion, tiger, badger, hippo, and stag.
[Try it online](https://pyth.herokuapp.com/?code=%2Bz%2a%7DzKc.%22at%1C%08%C3%9C%18%1Ai%C3%83%7F%274%C3%A3l%C2%BEE%0B%C2%AA%C2%8F%C3%AEi%C2%9D%C3%BB%3C%1A-%C3%88%26e%22%5Cjjk%5Bd%22goes%22dNr%40c.%22bw%03%C2%AB%C2%AB%5B%C3%A1%C3%853%C3%8FB%C2%97%22%5Cc%25x%60Kz3+3N&input=stag&test_suite_input=%5B24%2C+6%5D%0A0+++%0A%5B24%2C+6%5D%0A1%0A%5B24%2C+6%5D%0A2%0A%5B24%2C+6%5D%0A5%0A%5B100%2C+50%5D%0A10%0A%5B1%2C+1.41421356237%5D%0A10&debug=0&input_size=2)
[Answer]
## Japt, ~~25-15=10~~ 24-15 = 9 bytes
First time trying Japt:
```
N¦`¯t`?N:`¯t goƒ \"´ow\"
```
`ƒ` should be replaced with unprintable character `U+0083`
Compiles to:
```
N!="cat"?N:"cat goes \"meow\""
```
Old solution:
```
N¥`¯t`?`¯t goƒ \"´ow\"`:N
```
[Try it here](http://ethproductions.github.io/japt/?v=master&code=TqZgr3RgP046YK90IGdvgyBcIrRvd1wi&input=ImNhdCI=)
[Answer]
# Pyth, 26-15 (no "cat") = 11 bytes
My first ever Pyth program!
```
Iqz_"tac"+z" goes meow";Ez
```
## [Try it here](http://pyth.herokuapp.com/?code=Iqz_%22tac%22%2Bz%22+goes+meow%22%3BEz&input=cat&test_suite=1&test_suite_input=sadsadsadad%0Acat%0Atac&debug=0)
### Explaination
```
_"tac" # Reverse the string "tac"
Iqz # If the input equals "tac" reversed
+z" goes meow"; # Append " goes meow"
Ez # Else, use the input.
# Implicit: print the input, if it's used.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), score: -136 (214 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) - 31\*10 - 15 - 25)
```
'¨›Qi“What‚à€€ ÿ…è“ë“ÓÕŸâÍݹÐÀ¼Û˗Ĭ…ЧÀÛÆÓ‹·»ÑÐœ²èàæÑåÚÆÚØåÊÓ³âÌ–ÔĤ•ã‚í„ÄŠêÂÝ¢“#sk©di.•QÀ}£≠‰ŒΛ(Ïûвrüéä[ñøuF½3¡üÃïßåιQÊçdï€]Üвβ`šŠû©ª«ĀLΩÝβ\à¨TĆηÎ.₄₆öª$γâôΘ:Æ™{¹и5|Âć®λ¬¡¸αâË::´óýÏƶ5~¦m.škα†#Ð6λ•#®è™s“ÿ—± "ÿ"
```
Bonuses:
* -15 for not using `cat`
* -25 for outputting `What does the fox say` when the input is `fox`
* 31 times -10 for the animals and sounds: `["bat screech","bear roar","bee buzz","tiger roar","lion roar","jaguar snarl","cat meow","chicken cluck","cow moo","cricket chirp","deer bellow","dog bark","wolf howl","duck quack","eagle screech","elephant trumpet","frog croak","horse neigh","mouse squeak","monkey scream","pig oink","rabbit squeak","seal bark","sheep baa","snake hiss","turkey gobble","whale sing","ass heehaw","rat squeak","goat bleat","lamb baa"]`
[Try it online](https://tio.run/##FVDdSgJBGH2V0KCuvIm68AG66kYIuqggwyKRCLIg6IdhW4yyH2sLxKzW1UzNLDdRt9WE77hdDj7DvIh9C8PAnDnfOec7O8noenxjPJ6iihI/kbgS@aWt6J4SOZhKq/OZwECJMvg7j3f/MvDgdWHhCk/kIANBPTwircQ9dKr73Ay9QTCWgqGEQx1ycYuMZ5CNCkyU@fWKBmt7v8gxK4csAxcw6Jt1L5Uw4GuVlLBQ9KN8KPEM3TNRg8auFscIJhNUjcVDzInglLWOqajOTSW@vDv5OI0buCN7Fz1UUVpGE939eerPUIGRU3ziBa/SibDnWwyfPL2K/MiW9ppXYBeXqlSj96FYkFU8SXsFJlUWhynZwXVIabrSUmhTbVL6cVsyG0ZK6dYhOaPu7BG04Rk1pEt1KlBXNpmSDoephW/0cfPXnj2h8nbIKyRkUwkziMycdHmJIDW4Y91K@hVz4/fUnAhgEBiPN3cO/gE) or [verify all used animals](https://tio.run/##HVBNT1NBFP0rk9ZEF6Ybgws27NzopomJCzVx2g7tsx@vee9VJIqZlKZGUakUE1KKtgVKCwi2EGgtSHIPz@ULv2H@SL3PZHIyc@6559y5tisTlppGXy3ORYSpronI3CJqqE1vU8/o33HL6OaTjPSMbqBlyod8BK6M7oLLTRyEUMc3f4QOPmOLxtys6QKbWDF6HRU6DLU12oNmroq60WM6pwm@oubXaYgeWujyaxdH7O3/QYNVDWww8RF1OmHfT0bXEXrtGN3BdjjKT6O/o@K3sI8yp3Z4jKibpX7KirEmjmX2WqJt86Fl9C9/Ldi8g1VMboYOLtDHzlMMMCo9oMt71GZmGcf4gd1gHOfMvRSOufs5mjfDYPjCb3PKhPq0TwfX@lHQx1YwfIYW9R5fV4NzfImZcsWUqzij/VtBOO5psDGLqql03tD4ZjTzFuXr93QUTOiQ2jQKBixZmZ2lU5zgEqt/z2beUTcf89vZYGB0K4ra/WDCn4jSEe@40nHDFfPG12kgIriKTPm9tERnD@9OE9ITCSUdBiU8K60ckbPsgngp0yVmk1xOZqxkVhVE0l4QSSe8eyKlWJiy02LBzs2LVCmZFUqmc0qonCpmZMET8w5XM7bjKpG3S/@xkFWLomilhSMTCcsTrpI54WaUKgq3ILOcX3JCyUJGspN0XRZ6Im0z5GQ@Iebt18wUUnb@Hw).
**Explanation:**
```
'¨› '# Push dictionary word "fox"
Qi # If the (implicit) input-string equal "fox":
“What‚à€€ ÿ…è“ # Push dictionary string "What does the ÿ say"
# (where the `ÿ` is automatically filled with the implicit input)
ë # Else:
“ÓÕŸâÍÝ...ÄŠêÂÝ¢“ # Push dictionary string "bar bear bee ... rat goat lamb"
# # Split it on spaces
sk # Get the index of the input-string in this list (-1 if not found)
© # Store this index in variable `®` (without popping)
di # If this index is non-negative (>= 0):
.•QÀ...Ð6λ• # Push compressed string "screech roar ... bleat baa"
# # Split it on spaces
®è # Index variable `®` into this list
™ # Titlecase this sound
s # Swap to get the (implicit) input-string at the top of the stack
“ÿ—± "ÿ" # Push dictionary string 'ÿ goes "ÿ"'
# (where the first `ÿ` is the input at the top of the stack,
# and the second `ÿ` is the titlecased sound below it)
# (after which the top of the stack is output implicitly as result,
# which will be the (implicit) input itself for any other input)
```
[See this 05AB1E tip of mine (sections *How to use the dictionary?* and *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why:
* `'¨›` is `"fox"`
* `“What‚à€€ ÿ…è“` is `"What does the ÿ say"`
* `“ÓÕŸâÍݹÐÀ¼Û˗Ĭ…ЧÀÛÆÓ‹·»ÑÐœ²èàæÑåÚÆÚØåÊÓ³âÌ–ÔĤ•ã‚í„ÄŠêÂÝ¢“` is `"bat bear bee tiger lion jaguar cat chicken cow cricket deer dog wolf duck eagle elephant frog horse mouse monkey pig rabbit seal sheep snake turkey whale ass rat goat lamb"`
* `.•QÀ}£≠‰ŒΛ(Ïûвrüéä[ñøuF½3¡üÃïßåιQÊçdï€]Üвβ`šŠû©ª«ĀLΩÝβ\à¨TĆηÎ.₄₆öª$γâôΘ:Æ™{¹и5|Âć®λ¬¡¸αâË::´óýÏƶ5~¦m.škα†#Ð6λ•` is `"screech roar buzz roar roar snarl meow cluck moo chirp bellow bark howl quack screech trumpet croak neigh squeak scream oink squeak bark baa hiss gobble sing heehaw squeak bleat baa"`
* and `“ÿ—± "ÿ"` is `'ÿ goes "ÿ"'`
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 132 - 150 (animals) - 15 (no `cat`) = -33 bytes
```
pJjb.zp.x++" goes \""[[email protected]](/cdn-cgi/l/email-protection)\ic."ay-ÝÏåâšB²Å
uŠ°µ²¦DIJÖì |t`2“‚Êôë¨}èÔèw:ÿÊ_OƒÄ<Ú›ø‚î½ùÛ&L°„6a<9-¾¹™,Uø0é6Œû²Ù²ËyÊ·%C"\lJ4\"k
```
[Try it online!](https://tio.run/##AcQAO/9weXRo//9wSmpiLnpwLngrKyIgZ29lcyBcIiJyQC5kbWNkXGljLiJheS3DncOPw6XDosKaQsKyw4UMdcKKwrDCtcKywqZEw4TCssOWw6wgBXx0YDIHwpPCgsKBw4rDtMOrGsKofcOow5TDqHc6w7/Dil9PwoPDhBQ8w5rCm8O4woLDrsK9w7nDmyZMwrDChDZhPDktwr7CucKZLFXDuDARw6k2wozDu8KyD8OZwrLDi3nDisK3JUMiXGxKNFwia///Y2F0 "Pyth – Try It Online")
Uses a packed string to fit in animals for less than 10 bytes each
Full list:
```
parrot goes "Squack"
cat goes "Meow"
rook goes "Caw"
ass goes "Bray"
goose goes "Honk"
dog goes "Woof"
duck goes "Quack"
sheep goes "Baa"
ox goes "Moo"
raven goes "Caw"
goat goes "Baa"
swan goes "Cry"
frog goes "Croak"
toad goes "Croak"
monkey goes "Chatter"
```
Edit 1: Almost forgot the no cat bonus :P
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 25 - 15 = 10 bytes
```
."c""at"+=" goes 'Meow'"*
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPn/X08pWUkpsURJ21ZJIT0/tVhB3Tc1v1xdSev//@TEEgA "GolfScript – Try It Online")
### Example
```
."c""at"+=" goes 'Meow'"* # Input: cat
."c""at" # Duplicate input, push c and at. Stack: cat cat c at
+ # Concatenate, Stack: cat cat cat
= # Check if equal, Stack: cat 1
" goes 'Meow'"* # " goes 'Meow'" pushed onto stack n times, Stack: "cat" " goes 'Meow'"
# Implicitly print
```
### Alternate Example
```
."c""at"+=" goes 'Meow'"* # Input: asdf
."c""at" # Duplicate input, push c and at. Stack: asdf asdf c at
+ # Concatenate, Stack: asdf asdf cat
= # Check if equal, Stack: asdf 0
" goes 'Meow'"* # " goes 'Meow'" pushed onto stack n times, Stack: "asdf" ""
# Implicitly print
```
[Answer]
# [Nim](https://nim-lang.org/), 65 - 15 = ~~56~~ 50 bytes
Does not use the word cat. Supports only cat and then "Meow", no other animals.
```
while 1>0:
var i=readLine stdin;echo if i=="ca"&"t":"Meow"else:i
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LYwxCgIxEAD7fUXYQrAQtJNIBHt9xJJsvNWYwCWa_MUmID7qfuPB2c4w8_5EefT-fRa_2U-nOkhgtTtuNagXjUrMyOTOElnl4iQe2A5JiZ-FQUu4woIaL5wqcsisZRn9f31au3QFcrcklF24U3CZwKYKPpNpYKkAtEYzXYof)
(-6 bytes thanks to Steffan)
[Answer]
# TI-Basic, 48 bytes
```
Input Str1
Str1="cat
If Ans
Disp Str1+" goes Meow
If not(Ans
Disp Str1
```
All those lowercase letters are increasing the bytecount by a lot.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 285 - 310 - 15 - 25 = -65 bytes
```
`∷¾`=[`λ⟩ ƛ∪ λλ ∷¾ ∨¶`|`Ḃṙ ∞¨ εċ ṗµ √₇ Ṁ⋎ ¢₌ β¡ ¦‹ √⊍ ₃⇩ •ƈ ṡƒ ¦ø ḟ₇ Ẇ⟑ µɽ ½ż Þ‡ ₃⅛ Ḣ⟨ ₈Ḋ ġṄ ⁋ė Ċṁ ∴† Ẏ₇ ass ₀⌈ ⌊ṫ Ȯ⁰`⌈?ḟ:£0≥[`s⇩⋏↳⋎ r⋎« Ȧ¨ r⋎« r⋎« sn₴£ m□ŀ cḟĿ moo ch↲Ṗ Ǎ⟩⟑ṙ •øk h⋎₄ qꜝ½k s⇩⋏↳⋎ t≥⁋⌐¨ crβ⁰ ne⋏ṫ sȧ‛ak s›‹ o›₌ sȧ‛ak •øk baa λµs £⁋ǎʁ ⟩ɽ hee¥↓ sȧ‛ak bl↓⟑ baa`⌈¥i`% ¢₃ `?%$+
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJg4oi3wr5gPVtgzrvin6kgxpviiKogzrvOuyDiiLfCviDiiKjCtmB8YOG4guG5mSDiiJ7CqCDOtcSLIOG5l8K1IOKImuKChyDhuYDii44gwqLigowgzrLCoSDCpuKAuSDiiJriio0g4oKD4oepIOKAosaIIOG5ocaSIMKmw7gg4bif4oKHIOG6huKfkSDCtcm9IMK9xbwgw57igKEg4oKD4oWbIOG4ouKfqCDigojhuIogxKHhuYQg4oGLxJcgxIrhuYEg4oi04oCgIOG6juKChyBhc3Mg4oKA4oyIIOKMiuG5qyDIruKBsGDijIg/4bifOsKjMOKJpVtgc+KHqeKLj+KGs+KLjiBy4ouOwqsgyKbCqCBy4ouOwqsgcuKLjsKrIHNu4oK0wqMgbeKWocWAIGPhuJ/EvyBtb28gY2jihrLhuZYgx43in6nin5HhuZkg4oCiw7hrIGjii47igoQgceqcncK9ayBz4oep4ouP4oaz4ouOIHTiiaXigYvijJDCqCBjcs6y4oGwIG5l4ouP4bmrIHPIp+KAm2FrIHPigLrigLkgb+KAuuKCjCBzyKfigJthayDigKLDuGsgYmFhIM67wrVzIMKj4oGLx47KgSDin6nJvSBoZWXCpeKGkyBzyKfigJthayBibOKGk+KfkSBiYWFg4oyIwqVpYCUgwqLigoMgYD8lJCsiLCIiLCJzaGVlcCJd)
Port of Kevin Cruijssen's 05AB1E answer.
# [Vyxal](https://github.com/Vyxal/Vyxal), 42 - 15 - 25 = 2 bytes
```
`¢₌`=[`¢₌ ¢₃ "M□ŀ"`|`∷¾`=[`λ⟩ ƛ∪ λλ ∷¾ ∨¶`
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJgwqLigoxgPVtgwqLigowgwqLigoMgXCJN4pahxYBcImB8YOKIt8K+YD1bYM674p+pIMab4oiqIM67zrsg4oi3wr4g4oiowrZgIiwiIiwiZm94Il0=)
Bonuses:
* -15 for not using `cat`
* -25 for responding to `fox` with `What does the fox say`
## [Vyxal](https://github.com/Vyxal/Vyxal), 19 - 15 = 4 bytes
```
`¢₌`=[`¢₌ ¢₃ "M□ŀ"`
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJgwqLigoxgPVtgwqLigowgwqLigoMgXCJN4pahxYBcImAiLCIiLCJjYXQiXQ==)
Bonuses:
* -15 for not using `cat`
### Explanation
Most of it is just string compression:
* ``¢₌`` is `cat`
* ``¢₌ ¢₃ "M□ŀ"`` is `cat goes "meow"`
* ``∷¾`` is `fox`
* ``λ⟩ ƛ∪ λλ ∷¾ ∨¶`` is `What does the fox say`
[Answer]
# Pyth, 31 - 15 = 16 bytes
You can try it out [here](https://pyth.herokuapp.com/?code=In%2BC99%22at%22zz%3BE%2Bz%22%20goes%20%5C%22Meow%5C%22&input=cat%0A&test_suite=1&test_suite_input=cat%0Ahi&debug=0)
```
In+C99"at"zz;E+z" goes \"Meow\"
```
Explaination:
```
I # If-statement
n # not equal
+C99"at" # Adds the char 99 with the string "at" = "cat"
z # z, the user input
z # Print the user input
; # Ends all open parentheses
E # Else-statement
+z" goes \"Meow\" # Adds ' goes "Meow"' to z and prints the result
```
[Answer]
# C, 76 bytes
```
main(){char a[99];gets(a);printf("%s%s",a,strcmp(a,"cat")?"":" goes meow");}
```
[Answer]
# PHP, 70-15 = 55 bytes
```
<?=$l=rtrim(stream_get_contents(STDIN),~òõ),$l==~œž‹?~ߘšŒßݲšˆÝ:'';
```
(saved as ISO-8859-1)
Uses inverted undefined constants as string literals:
* `~òõ` == `"\r\n"`
* `~œž‹` == `'cat'`
* `~ߘšŒßݲšˆÝ` == `' goes "Meow"'`
Everything is combined in a single echo statement, shorthanded with `<?=`
[Answer]
## Ruby, 35 + 2 (-p flag) - 15 = 22 bytes
```
$_==?c'at
'&&$_[-2]+=' goes "Meow"'
```
Inspired by trying to improve [Peter Lenkefi's](https://codegolf.stackexchange.com/a/62502) solution.
[Answer]
## Ruby, 110 + 2 (-p flag) -60 (cow, ox, dog, bee, pig and crow) -15 (no cat) = 37 bytes
```
(h=Hash[*%W(cow Moo ox Low c\141t Meow dog Woof bee Buzz pig Oink crow Caw)][$_.chop])&&$_[-2]+=' goes "'+h+?"
```
Multiple animal Ruby solution... As long as the animal+sound is <8 characters, it shrinks for each one added. Gross abuse of Ruby. :)
[Answer]
# Ruby, 26 + 1 = 27
With command-line flag `-p`, run
```
sub /^cat$/,'\& goes Meow'
```
Getting the no-cat bonus costs 2 bytes, which isn't actually worth it:
```
sub /^c at$/x,'\& goes Meow'
```
[Answer]
# [Hassium](http://HassiumLang.com), 67 Bytes
```
func main()if((x=input())=="cat")print(x+" goes meow")else print(x)
```
See expanded [here](http://HassiumLang.com/Hassium/index.php?code=ab0a8369a4a78fca2376f798bf1df2bb)
[Answer]
# [JacobFck](https://github.com/JacobMisirian/JacobFck), 31 Bytes
I really like the golfed version of this.
```
"cat"<|=_e>!:e"cat goes Meow">
```
See commented and expanded [here](http://hassiumlang.com/Paste/get-paste.has?hash=48e0912b2dfe5a3af3be80d88f0b36da)
[Answer]
## Python 2, 149-95 = 54 bytes
### -8\*10 extra animals, -15 for no "cat"
```
u=raw_input()
l="ca""t badger rhino okapi moose stag tiger hippo lion".split()
print u+' goes "%s"'%["Growl","Bellow","Meow"][`l`.find(u)%3]*(u in l)
```
Supported animals:
* moose, stag, okapi, rhino (all Bellow)
* tiger, badger, lion, hippo (all Growl)
This is not the shortest Python answer, but at least it does bother to try at some other animals! I add it here because the answer i had previously did not work, and I'm confident this will become the shortest Pyth answer once I translate it and golf it there.
### How it works:
1. Take input
2. Create a list of animals in a very precise order.
3. Print the input, and if the input is in the list, use the location of the input in the string representation of the list to index an array of sounds, and append the appropriate "goes" string.
[Answer]
# [Arcyóu](https://github.com/Nazek42/arcyou), 38 bytes (non-competitive)
*Since this version of the language was made after the challenge was posted, it is not eligible.*
```
(: s(q))(?(= s "cat")"cat goes Meow" s
```
Arcyóu is a LISP-like golfing language.
Explanation:
```
(: s(q)) ; Set the variable s to the contents of STDIN
(? (= s "cat") ; If-statement. Condition is s == "cat"
"cat goes Meow" ; If true: return the string "cat goes Meow"
s ; Otherwise, return what was entered
```
Arcyóu automatically prints the result of the last expression evaluated. In this case, it is the `?` statement. It also allows you to leave off trailing close-parens.
[Answer]
# Emacs Lisp (67 Bytes)
```
(set'a(read-string""))(message(pcase a("cat""cat goes meow")(_ a)))
```
It uses pattern matching to distinguish cats from other input. This could be extended to fit other animals in as well, but as most of them take up more than 10 characters, there is not much to be gained from that.
[Answer]
# [Milky Way 1.5.16](https://github.com/zachgates7/Milky-Way), 29 bytes - 15 = 14
```
"c""at"+'?{b_" goes Meow"+_}!
```
Doesn't use a `"cat"` string.
---
### Explanation
```
"c""at" " goes Meow" # push string to the stack
+ + # add the TOS and the STOS
' # read input from the command line
?{ _ _} # if statement
b # equality of the TOS and the STOS
! # output the TOS
```
---
### Usage
```
python3 milkyway.py <path-to-code> -i <input>
```
[Answer]
## [Perl](https://github.com/BrendanGalvin), 13 bytes
The string "cat" does not appear in my code (Special thanks to Dennis for shaving 15 bytes off of the code, and teaching me some new Perl tricks):
```
s/^(c)at$/$& goes Meow/
```
[Answer]
# C#6, 302 - 110 - 15 = 177 bytes
This works for 12 different animals, including cat. It does not include the word "cat" verbatim.
```
using static System.Console;class P{static void Main(){var a=ReadLine();var d="bee,Buzz,c\x61t,Meow,cow,Moo,crow,Caw,dog,Bark,hog,Oink,lamb,Baa,lion,Roar,ox,Low,owl,Hoo,pig,Oink,rook,Caw,seal,Bark,sheep,Baa,swan,Cry".Split(',');int i=22;while(--i>0&&d[--i]!=a);Write(i<0?a:d[i]+" goes '"+d[i+1]+"'");}}
```
Indentation and new lines for clarity.
```
using static System.Console;
class P{
static void Main(){
var a=ReadLine();
var d="bee,Buzz,c\x61t,Meow,cow,Moo,crow,Caw,dog,Bark,hog,Oink,lamb,Baa,lion,Roar,ox,Low,owl,Hoo,pig,Oink,rook,Caw,seal,Bark,sheep,Baa,swan,Cry".Split(',');
int i=22;
while(--i>0&&d[--i]!=a);
Write(i<0?a:d[i]+" goes '"+d[i+1]+"'");
}
}
```
[Answer]
## [DIG](https://github.com/UnderMybrella/DIG), 163 - 15 = 148 bytes
Disclaimer: Due to the fact that DIG was created after the challenge, this answer is non-competing.
[![Beautiful cats](https://i.stack.imgur.com/RFQ7n.png)](https://i.stack.imgur.com/RFQ7n.png)
Zoomed in (Note: This file will NOT compile, due to the nature of the language)
[![Impossible Cats](https://i.stack.imgur.com/5nEUY.png)](https://i.stack.imgur.com/5nEUY.png)
While I have no idea if this is considered a valid language for PPCG, it *does* complete the challenge. Documentation for the language can be found [here](https://github.com/UnderMybrella/DIG/blob/master/Schematic.txt) and the interpreter can be found [here](https://github.com/UnderMybrella/DIG/blob/master/DIG.jar).
[Answer]
# Swift 2.0, ~~71~~ 68-15 (no "cat") = 53 bytes
```
func a(s:String)->String{return s=="c\u{61}t" ?s+" goes \"Meow\"":s}
```
For some reason, a compilation error is thrown if there isn't a space before the ternary operator `?`
### Ungolfed
```
func a(s: String) -> String{
return s == "c\u{61}t" ? s + " goes \"Meow\"" : s
}
```
This doesn't use "cat" in it by replacing the a with the unicode literal `\u{61}`. You can [test this code here](http://swiftstub.com/156692825/)
[Answer]
## JavaScript, 35 - 15 (-p no cat) = 20 Bytes
```
c=i=>(i=='c\at')?i+' says "Meow"':i
```
Can someone check to see that I did the header right?
[Answer]
# Retina, 23 - 15 = 8 bytes
```
^ca\0*t$
$& goes "Meow"
```
[Answer]
# Pylongolf2, 33-15=18 bytes
```
"tac"╨1cd_@0=b?" goes Meow"¿~
```
Explanations:
```
"tac"╨1cd_@0=b?" goes Meow"¿~
"tac" push "tac" to stack
╨1 reverse it
cd read input and then select latest item in stack
_ duplicate input
@0 select first item in stack
=b compare then swap places
? if true,
" goes Meow"¿ push " goes Meow" to stack and end if statement
~ print it.
```
[Answer]
## Lua 5.3.2, 229 - 25 - 15 - 80 (extra animals) = 109 bytes
```
r={...}a={['\99\97\116']='Meow',duck='Quack',sheep='Baa',bee='Buzz',frog='Croak',bat='Screech',elk='Bugle',swan='Cry',pig='Oink'}print(r[1]=='fox' and 'What does the fox say' or(a[r[1]] and r[1]..' goes "'..a[r[1]]..'"' or r[1]))
```
### Ungolfed
```
local Args = {...}
local Sounds = {
['\99\97\116'] = 'Meow',
duck = 'Quack',
sheep = 'Baa',
bee = 'Buzz',
frog = 'Croak',
bat = 'Screech',
elk = 'Bugle',
swan = 'Cry',
pig = 'Oink'
}
print(
Args[1] == 'fox' and 'What does the fox say' or (
Sounds[Args[1]] and Args[1] .. ' goes "' .. Sounds[Args[1]] .. '"' or Args[1]
)
)
```
I tried to make the logic a little clearer by putting it on multiple lines.
It's essentially a ternary operator `?:`
[Answer]
## AWK, 32 - 15 = 17
```
/^[c]at$/{$0=$0" goes 'Meow'"}1
```
I think this counts as not using "cat". Could have saved a couple bytes if "cat" were allowed to be anywhere in the line.
For giggles I also put together one with more animals, but it's not competitive, especially with trying to capture the correct verb to use, but here's what I came up with :)
```
{for(;I<split("ca""t,Meow,bees,Buzz,bird,Song,cow,Moo,crow,Caw,dog,Woof,duck,Quack,frogs,Croak,hog,Oink,ox,Low,pig,Oink,sheep,Baa,swan,Cry",a,",");)
m[a[I-1]="'"a[I+=2]"'"}
m[$0]{$0=$0($0~/s$/?" go ":" goes ")m[$0]}
/^fox$/{$0="What does the fox say"}
1
```
] |
[Question]
[
Using your language of choice, golf a [quine](http://en.wikipedia.org/wiki/Quine_%28computing%29).
>
> A **quine** is a non-empty computer program which takes no input and produces a copy of its own source code as its only output.
>
>
>
No cheating -- that means that you can't just read the source file and print it. Also, in many languages, an empty file is also a quine: that isn't considered a legit quine either.
No error quines -- there is already a [separate challenge](https://codegolf.stackexchange.com/questions/36260/make-an-error-quine) for error quines.
Points for:
* Smallest code (in bytes)
* Most obfuscated/obscure solution
* Using esoteric/obscure languages
* Successfully using languages that are difficult to golf in
The following Stack Snippet can be used to get a quick view of the current score in each language, and thus to know which languages have existing answers and what sort of target you have to beat:
```
var QUESTION_ID=69;
var OVERRIDE_USER=98;
var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk";var answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,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:!0,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=!1;comment_page=1;getComments()}})}
function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,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=(function(){var headerTag=String.raw `h\d`
var score=String.raw `\-?\d+\.?\d*`
var normalText=String.raw `[^\n<>]*`
var strikethrough=String.raw `<s>${normalText}</s>|<strike>${normalText}</strike>|<del>${normalText}</del>`
var noDigitText=String.raw `[^\n\d<>]*`
var htmlTag=String.raw `<[^\n<>]+>`
return new RegExp(String.raw `<${headerTag}>`+String.raw `\s*([^\n,]*[^\s,]),.*?`+String.raw `(${score})`+String.raw `(?=`+String.raw `${noDigitText}`+String.raw `(?:(?:${strikethrough}|${htmlTag})${noDigitText})*`+String.raw `</${headerTag}>`+String.raw `)`)})();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;lang=jQuery('<i>'+a.language+'</i>').text().toLowerCase();languages[lang]=languages[lang]||{lang:a.language,user:a.user,size:a.size,link:a.link,uniq:lang}});var langs=[];for(var lang in languages)
if(languages.hasOwnProperty(lang))
langs.push(languages[lang]);langs.sort(function(a,b){if(a.uniq>b.uniq)return 1;if(a.uniq<b.uniq)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;float:left}#language-list{padding:10px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654"> <div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table>
```
[Answer]
## Python 3, 34 Bytes
```
print((s:='print((s:=%r)%%s)')%s)
```
As far as I'm aware this is shorter than any other published Python 3 quine, mainly by virtue of having been written in the future with respect to most of them, so it can use `:=`.
[Answer]
# Befunge 98 - ~~17~~ 11 characters
```
<@,+1!',k9"
```
Or if using `g` is allowed:
# Befunge 98 - ~~12~~ 10
```
<@,g09,k8"
```
[Answer]
# TECO, 20 bytes
```
<Tab>V27:^TJDV<Esc>V27:^TJDV
```
The `<Esc>` should be replaced with ASCII 0x1B, and the `<Tab>` with 0x09.
* `<Tab>V27:^TJDV<Esc>` inserts the text `<Tab>V27:^TJDV`. This is *not* because there is a text insertion mode which TECO starts in by default. Instead, `<Tab>` *text* `<Esc>` is a special insertion command which inserts a tab, and then the text. A string whose own initial delimiter is part of the text -- very handy.
* `V` prints the current line.
* `27:^T` prints the character with ASCII code 27 without the usual conversion to a printable representation.
* `J` jumps to the beginning of the text.
* `D` deletes the first character (the tab).
* `V` prints the line again.
[Answer]
# Python 2, 31 bytes
```
s="print's=%r;exec s'%s";exec s
```
It's 2 bytes longer than the [shortest Python quine on this question](https://codegolf.stackexchange.com/a/115/21487), but it's much more useful, since you don't need to write everything twice.
For example, to print a program's own source code in sorted order, we can just do:
```
s="print''.join(sorted('s=%r;exec s'%s))";exec s
```
Another example by @feersum can be found [here](https://codegolf.stackexchange.com/a/47198/21487).
## Notes
The reason the quine works is because of `%r`'s behaviour. With normal strings, `%r` puts single quotes around the string, e.g.
```
>>> print "%r"%"abc"
'abc'
```
But if you have a single quotes inside the string, it uses double quotes instead:
```
>>> print "%r"%"'abc'"
"'abc'"
```
This does, however, mean that the quine has a bit of a problem if you want to use both types of quotes in the string.
[Answer]
# [RETURN](https://github.com/molarmanful/RETURN), 18 bytes
```
"34¤¤,,,,"34¤¤,,,,
```
`[Try it here.](http://molarmanful.github.io/RETURN/)`
First RETURN program on PPCG ever! RETURN is a language that tries to improve DUP by using nested stacks.
# Explanation
```
"34¤¤,,,," Push this string to the stack
34 Push charcode of " to the stack
¤¤ Duplicate top 2 items
,,,, Output all 4 stack items from top to bottom
```
[Answer]
# [Factor](http://factorcode.org) - ~~74~~ ~~69~~ 65 bytes
Works on the listener (REPL):
```
USE: formatting [ "USE: formatting %u dup call" printf ] dup call
```
This is my first ever quine, ~~I'm sure there must be a shorter one!~~ Already shorter. Now I'm no longer sure... (bad pun attempt)
What it does is:
* `USE: formatting` import the `formatting` vocabulary to use `printf`
* `[ "U... printf ]` create a quotation (or lambda, or block) on the top of the stack
* `dup call` duplicate it, and call it
The quotation takes the top of the stack and embeds it into the string as a literal.
Thanks, cat! -> shaved ~~2~~ 4 more bytes :D
[Answer]
# [S.I.L.O.S](http://github.com/rjhunjhunwala/S.I.L.O.S), ~~2642~~ 2593 bytes
**Credits to Rohan Jhunjhunwala for the algorithm.**
```
A = 99
set A 112
A + 1
set A 114
A + 1
set A 105
A + 1
set A 110
A + 1
set A 116
A + 1
set A 76
A + 1
set A 105
A + 1
set A 110
A + 1
set A 101
A + 1
set A 32
A + 1
set A 65
A + 1
set A 32
A + 1
set A 61
A + 1
set A 32
A + 1
set A 57
A + 1
set A 57
A + 1
set A 10
A + 1
set A 67
A + 1
set A 32
A + 1
set A 61
A + 1
set A 32
A + 1
set A 57
A + 1
set A 57
A + 1
set A 10
A + 1
set A 66
A + 1
set A 32
A + 1
set A 61
A + 1
set A 32
A + 1
set A 103
A + 1
set A 101
A + 1
set A 116
A + 1
set A 32
A + 1
set A 67
A + 1
set A 10
A + 1
set A 108
A + 1
set A 98
A + 1
set A 108
A + 1
set A 68
A + 1
set A 10
A + 1
set A 67
A + 1
set A 32
A + 1
set A 43
A + 1
set A 32
A + 1
set A 49
A + 1
set A 10
A + 1
set A 112
A + 1
set A 114
A + 1
set A 105
A + 1
set A 110
A + 1
set A 116
A + 1
set A 32
A + 1
set A 115
A + 1
set A 101
A + 1
set A 116
A + 1
set A 32
A + 1
set A 65
A + 1
set A 32
A + 1
set A 10
A + 1
set A 112
A + 1
set A 114
A + 1
set A 105
A + 1
set A 110
A + 1
set A 116
A + 1
set A 73
A + 1
set A 110
A + 1
set A 116
A + 1
set A 32
A + 1
set A 66
A + 1
set A 10
A + 1
set A 112
A + 1
set A 114
A + 1
set A 105
A + 1
set A 110
A + 1
set A 116
A + 1
set A 76
A + 1
set A 105
A + 1
set A 110
A + 1
set A 101
A + 1
set A 32
A + 1
set A 65
A + 1
set A 32
A + 1
set A 43
A + 1
set A 32
A + 1
set A 49
A + 1
set A 10
A + 1
set A 66
A + 1
set A 32
A + 1
set A 61
A + 1
set A 32
A + 1
set A 103
A + 1
set A 101
A + 1
set A 116
A + 1
set A 32
A + 1
set A 67
A + 1
set A 10
A + 1
set A 105
A + 1
set A 102
A + 1
set A 32
A + 1
set A 66
A + 1
set A 32
A + 1
set A 68
A + 1
set A 10
A + 1
set A 70
A + 1
set A 32
A + 1
set A 61
A + 1
set A 32
A + 1
set A 57
A + 1
set A 57
A + 1
set A 10
A + 1
set A 69
A + 1
set A 32
A + 1
set A 61
A + 1
set A 32
A + 1
set A 103
A + 1
set A 101
A + 1
set A 116
A + 1
set A 32
A + 1
set A 70
A + 1
set A 10
A + 1
set A 108
A + 1
set A 98
A + 1
set A 108
A + 1
set A 71
A + 1
set A 10
A + 1
set A 70
A + 1
set A 32
A + 1
set A 43
A + 1
set A 32
A + 1
set A 49
A + 1
set A 10
A + 1
set A 112
A + 1
set A 114
A + 1
set A 105
A + 1
set A 110
A + 1
set A 116
A + 1
set A 67
A + 1
set A 104
A + 1
set A 97
A + 1
set A 114
A + 1
set A 32
A + 1
set A 69
A + 1
set A 10
A + 1
set A 69
A + 1
set A 32
A + 1
set A 61
A + 1
set A 32
A + 1
set A 103
A + 1
set A 101
A + 1
set A 116
A + 1
set A 32
A + 1
set A 70
A + 1
set A 10
A + 1
set A 105
A + 1
set A 102
A + 1
set A 32
A + 1
set A 69
A + 1
set A 32
A + 1
set A 71
A + 1
printLine A = 99
C = 99
B = get C
lblD
C + 1
print set A
printInt B
printLine A + 1
B = get C
if B D
F = 99
E = get F
lblG
F + 1
printChar E
E = get F
if E G
```
[Try it online!](http://silos.tryitonline.net/#code=QSA9IDk5CnNldCBBIDExMgpBICsgMQpzZXQgQSAxMTQKQSArIDEKc2V0IEEgMTA1CkEgKyAxCnNldCBBIDExMApBICsgMQpzZXQgQSAxMTYKQSArIDEKc2V0IEEgNzYKQSArIDEKc2V0IEEgMTA1CkEgKyAxCnNldCBBIDExMApBICsgMQpzZXQgQSAxMDEKQSArIDEKc2V0IEEgMzIKQSArIDEKc2V0IEEgNjUKQSArIDEKc2V0IEEgMzIKQSArIDEKc2V0IEEgNjEKQSArIDEKc2V0IEEgMzIKQSArIDEKc2V0IEEgNTcKQSArIDEKc2V0IEEgNTcKQSArIDEKc2V0IEEgMTAKQSArIDEKc2V0IEEgNjcKQSArIDEKc2V0IEEgMzIKQSArIDEKc2V0IEEgNjEKQSArIDEKc2V0IEEgMzIKQSArIDEKc2V0IEEgNTcKQSArIDEKc2V0IEEgNTcKQSArIDEKc2V0IEEgMTAKQSArIDEKc2V0IEEgNjYKQSArIDEKc2V0IEEgMzIKQSArIDEKc2V0IEEgNjEKQSArIDEKc2V0IEEgMzIKQSArIDEKc2V0IEEgMTAzCkEgKyAxCnNldCBBIDEwMQpBICsgMQpzZXQgQSAxMTYKQSArIDEKc2V0IEEgMzIKQSArIDEKc2V0IEEgNjcKQSArIDEKc2V0IEEgMTAKQSArIDEKc2V0IEEgMTA4CkEgKyAxCnNldCBBIDk4CkEgKyAxCnNldCBBIDEwOApBICsgMQpzZXQgQSA2OApBICsgMQpzZXQgQSAxMApBICsgMQpzZXQgQSA2NwpBICsgMQpzZXQgQSAzMgpBICsgMQpzZXQgQSA0MwpBICsgMQpzZXQgQSAzMgpBICsgMQpzZXQgQSA0OQpBICsgMQpzZXQgQSAxMApBICsgMQpzZXQgQSAxMTIKQSArIDEKc2V0IEEgMTE0CkEgKyAxCnNldCBBIDEwNQpBICsgMQpzZXQgQSAxMTAKQSArIDEKc2V0IEEgMTE2CkEgKyAxCnNldCBBIDMyCkEgKyAxCnNldCBBIDExNQpBICsgMQpzZXQgQSAxMDEKQSArIDEKc2V0IEEgMTE2CkEgKyAxCnNldCBBIDMyCkEgKyAxCnNldCBBIDY1CkEgKyAxCnNldCBBIDMyCkEgKyAxCnNldCBBIDEwCkEgKyAxCnNldCBBIDExMgpBICsgMQpzZXQgQSAxMTQKQSArIDEKc2V0IEEgMTA1CkEgKyAxCnNldCBBIDExMApBICsgMQpzZXQgQSAxMTYKQSArIDEKc2V0IEEgNzMKQSArIDEKc2V0IEEgMTEwCkEgKyAxCnNldCBBIDExNgpBICsgMQpzZXQgQSAzMgpBICsgMQpzZXQgQSA2NgpBICsgMQpzZXQgQSAxMApBICsgMQpzZXQgQSAxMTIKQSArIDEKc2V0IEEgMTE0CkEgKyAxCnNldCBBIDEwNQpBICsgMQpzZXQgQSAxMTAKQSArIDEKc2V0IEEgMTE2CkEgKyAxCnNldCBBIDc2CkEgKyAxCnNldCBBIDEwNQpBICsgMQpzZXQgQSAxMTAKQSArIDEKc2V0IEEgMTAxCkEgKyAxCnNldCBBIDMyCkEgKyAxCnNldCBBIDY1CkEgKyAxCnNldCBBIDMyCkEgKyAxCnNldCBBIDQzCkEgKyAxCnNldCBBIDMyCkEgKyAxCnNldCBBIDQ5CkEgKyAxCnNldCBBIDEwCkEgKyAxCnNldCBBIDY2CkEgKyAxCnNldCBBIDMyCkEgKyAxCnNldCBBIDYxCkEgKyAxCnNldCBBIDMyCkEgKyAxCnNldCBBIDEwMwpBICsgMQpzZXQgQSAxMDEKQSArIDEKc2V0IEEgMTE2CkEgKyAxCnNldCBBIDMyCkEgKyAxCnNldCBBIDY3CkEgKyAxCnNldCBBIDEwCkEgKyAxCnNldCBBIDEwNQpBICsgMQpzZXQgQSAxMDIKQSArIDEKc2V0IEEgMzIKQSArIDEKc2V0IEEgNjYKQSArIDEKc2V0IEEgMzIKQSArIDEKc2V0IEEgNjgKQSArIDEKc2V0IEEgMTAKQSArIDEKc2V0IEEgNzAKQSArIDEKc2V0IEEgMzIKQSArIDEKc2V0IEEgNjEKQSArIDEKc2V0IEEgMzIKQSArIDEKc2V0IEEgNTcKQSArIDEKc2V0IEEgNTcKQSArIDEKc2V0IEEgMTAKQSArIDEKc2V0IEEgNjkKQSArIDEKc2V0IEEgMzIKQSArIDEKc2V0IEEgNjEKQSArIDEKc2V0IEEgMzIKQSArIDEKc2V0IEEgMTAzCkEgKyAxCnNldCBBIDEwMQpBICsgMQpzZXQgQSAxMTYKQSArIDEKc2V0IEEgMzIKQSArIDEKc2V0IEEgNzAKQSArIDEKc2V0IEEgMTAKQSArIDEKc2V0IEEgMTA4CkEgKyAxCnNldCBBIDk4CkEgKyAxCnNldCBBIDEwOApBICsgMQpzZXQgQSA3MQpBICsgMQpzZXQgQSAxMApBICsgMQpzZXQgQSA3MApBICsgMQpzZXQgQSAzMgpBICsgMQpzZXQgQSA0MwpBICsgMQpzZXQgQSAzMgpBICsgMQpzZXQgQSA0OQpBICsgMQpzZXQgQSAxMApBICsgMQpzZXQgQSAxMTIKQSArIDEKc2V0IEEgMTE0CkEgKyAxCnNldCBBIDEwNQpBICsgMQpzZXQgQSAxMTAKQSArIDEKc2V0IEEgMTE2CkEgKyAxCnNldCBBIDY3CkEgKyAxCnNldCBBIDEwNApBICsgMQpzZXQgQSA5NwpBICsgMQpzZXQgQSAxMTQKQSArIDEKc2V0IEEgMzIKQSArIDEKc2V0IEEgNjkKQSArIDEKc2V0IEEgMTAKQSArIDEKc2V0IEEgNjkKQSArIDEKc2V0IEEgMzIKQSArIDEKc2V0IEEgNjEKQSArIDEKc2V0IEEgMzIKQSArIDEKc2V0IEEgMTAzCkEgKyAxCnNldCBBIDEwMQpBICsgMQpzZXQgQSAxMTYKQSArIDEKc2V0IEEgMzIKQSArIDEKc2V0IEEgNzAKQSArIDEKc2V0IEEgMTAKQSArIDEKc2V0IEEgMTA1CkEgKyAxCnNldCBBIDEwMgpBICsgMQpzZXQgQSAzMgpBICsgMQpzZXQgQSA2OQpBICsgMQpzZXQgQSAzMgpBICsgMQpzZXQgQSA3MQpBICsgMQpwcmludExpbmUgQSA9IDk5CkMgPSA5OQpCID0gZ2V0IEMKbGJsRApDICsgMQpwcmludCBzZXQgQSAKcHJpbnRJbnQgQgpwcmludExpbmUgQSArIDEKQiA9IGdldCBDCmlmIEIgRApGID0gOTkKRSA9IGdldCBGCmxibEcKRiArIDEKcHJpbnRDaGFyIEUKRSA9IGdldCBGCmlmIEUgRw&input=)
[Answer]
# [S.I.L.O.S](http://github.com/rjhunjhunwala/S.I.L.O.S), 3057 bytes
```
A = 99
def S set
S A 112
A + 1
S A 114
A + 1
S A 105
A + 1
S A 110
A + 1
S A 116
A + 1
S A 76
A + 1
S A 105
A + 1
S A 110
A + 1
S A 101
A + 1
S A 32
A + 1
S A 65
A + 1
S A 32
A + 1
S A 61
A + 1
S A 32
A + 1
S A 57
A + 1
S A 57
A + 1
S A 10
A + 1
S A 72
A + 1
S A 32
A + 1
S A 61
A + 1
S A 32
A + 1
S A 56
A + 1
S A 51
A + 1
S A 10
A + 1
S A 112
A + 1
S A 114
A + 1
S A 105
A + 1
S A 110
A + 1
S A 116
A + 1
S A 32
A + 1
S A 100
A + 1
S A 101
A + 1
S A 102
A + 1
S A 32
A + 1
S A 10
A + 1
S A 112
A + 1
S A 114
A + 1
S A 105
A + 1
S A 110
A + 1
S A 116
A + 1
S A 67
A + 1
S A 104
A + 1
S A 97
A + 1
S A 114
A + 1
S A 32
A + 1
S A 72
A + 1
S A 10
A + 1
S A 112
A + 1
S A 114
A + 1
S A 105
A + 1
S A 110
A + 1
S A 116
A + 1
S A 76
A + 1
S A 105
A + 1
S A 110
A + 1
S A 101
A + 1
S A 32
A + 1
S A 32
A + 1
S A 83
A + 1
S A 32
A + 1
S A 10
A + 1
S A 67
A + 1
S A 32
A + 1
S A 61
A + 1
S A 32
A + 1
S A 57
A + 1
S A 57
A + 1
S A 10
A + 1
S A 66
A + 1
S A 32
A + 1
S A 61
A + 1
S A 32
A + 1
S A 103
A + 1
S A 101
A + 1
S A 116
A + 1
S A 32
A + 1
S A 67
A + 1
S A 10
A + 1
S A 108
A + 1
S A 98
A + 1
S A 108
A + 1
S A 68
A + 1
S A 10
A + 1
S A 67
A + 1
S A 32
A + 1
S A 43
A + 1
S A 32
A + 1
S A 49
A + 1
S A 10
A + 1
S A 112
A + 1
S A 114
A + 1
S A 105
A + 1
S A 110
A + 1
S A 116
A + 1
S A 67
A + 1
S A 104
A + 1
S A 97
A + 1
S A 114
A + 1
S A 32
A + 1
S A 72
A + 1
S A 10
A + 1
S A 112
A + 1
S A 114
A + 1
S A 105
A + 1
S A 110
A + 1
S A 116
A + 1
S A 32
A + 1
S A 32
A + 1
S A 65
A + 1
S A 32
A + 1
S A 10
A + 1
S A 112
A + 1
S A 114
A + 1
S A 105
A + 1
S A 110
A + 1
S A 116
A + 1
S A 73
A + 1
S A 110
A + 1
S A 116
A + 1
S A 32
A + 1
S A 66
A + 1
S A 10
A + 1
S A 112
A + 1
S A 114
A + 1
S A 105
A + 1
S A 110
A + 1
S A 116
A + 1
S A 76
A + 1
S A 105
A + 1
S A 110
A + 1
S A 101
A + 1
S A 32
A + 1
S A 65
A + 1
S A 32
A + 1
S A 43
A + 1
S A 32
A + 1
S A 49
A + 1
S A 10
A + 1
S A 66
A + 1
S A 32
A + 1
S A 61
A + 1
S A 32
A + 1
S A 103
A + 1
S A 101
A + 1
S A 116
A + 1
S A 32
A + 1
S A 67
A + 1
S A 10
A + 1
S A 105
A + 1
S A 102
A + 1
S A 32
A + 1
S A 66
A + 1
S A 32
A + 1
S A 68
A + 1
S A 10
A + 1
S A 70
A + 1
S A 32
A + 1
S A 61
A + 1
S A 32
A + 1
S A 57
A + 1
S A 57
A + 1
S A 10
A + 1
S A 69
A + 1
S A 32
A + 1
S A 61
A + 1
S A 32
A + 1
S A 103
A + 1
S A 101
A + 1
S A 116
A + 1
S A 32
A + 1
S A 70
A + 1
S A 10
A + 1
S A 108
A + 1
S A 98
A + 1
S A 108
A + 1
S A 71
A + 1
S A 10
A + 1
S A 70
A + 1
S A 32
A + 1
S A 43
A + 1
S A 32
A + 1
S A 49
A + 1
S A 10
A + 1
S A 112
A + 1
S A 114
A + 1
S A 105
A + 1
S A 110
A + 1
S A 116
A + 1
S A 67
A + 1
S A 104
A + 1
S A 97
A + 1
S A 114
A + 1
S A 32
A + 1
S A 69
A + 1
S A 10
A + 1
S A 69
A + 1
S A 32
A + 1
S A 61
A + 1
S A 32
A + 1
S A 103
A + 1
S A 101
A + 1
S A 116
A + 1
S A 32
A + 1
S A 70
A + 1
S A 10
A + 1
S A 105
A + 1
S A 102
A + 1
S A 32
A + 1
S A 69
A + 1
S A 32
A + 1
S A 71
A + 1
printLine A = 99
H = 83
print def
printChar H
printLine S
C = 99
B = get C
lblD
C + 1
printChar H
print A
printInt B
printLine A + 1
B = get C
if B D
F = 99
E = get F
lblG
F + 1
printChar E
E = get F
if E G
```
[Try it online!](http://silos.tryitonline.net/#code=QSA9IDk5CmRlZiBTIHNldCAKUyBBIDExMgpBICsgMQpTIEEgMTE0CkEgKyAxClMgQSAxMDUKQSArIDEKUyBBIDExMApBICsgMQpTIEEgMTE2CkEgKyAxClMgQSA3NgpBICsgMQpTIEEgMTA1CkEgKyAxClMgQSAxMTAKQSArIDEKUyBBIDEwMQpBICsgMQpTIEEgMzIKQSArIDEKUyBBIDY1CkEgKyAxClMgQSAzMgpBICsgMQpTIEEgNjEKQSArIDEKUyBBIDMyCkEgKyAxClMgQSA1NwpBICsgMQpTIEEgNTcKQSArIDEKUyBBIDEwCkEgKyAxClMgQSA3MgpBICsgMQpTIEEgMzIKQSArIDEKUyBBIDYxCkEgKyAxClMgQSAzMgpBICsgMQpTIEEgNTYKQSArIDEKUyBBIDUxCkEgKyAxClMgQSAxMApBICsgMQpTIEEgMTEyCkEgKyAxClMgQSAxMTQKQSArIDEKUyBBIDEwNQpBICsgMQpTIEEgMTEwCkEgKyAxClMgQSAxMTYKQSArIDEKUyBBIDMyCkEgKyAxClMgQSAxMDAKQSArIDEKUyBBIDEwMQpBICsgMQpTIEEgMTAyCkEgKyAxClMgQSAzMgpBICsgMQpTIEEgMTAKQSArIDEKUyBBIDExMgpBICsgMQpTIEEgMTE0CkEgKyAxClMgQSAxMDUKQSArIDEKUyBBIDExMApBICsgMQpTIEEgMTE2CkEgKyAxClMgQSA2NwpBICsgMQpTIEEgMTA0CkEgKyAxClMgQSA5NwpBICsgMQpTIEEgMTE0CkEgKyAxClMgQSAzMgpBICsgMQpTIEEgNzIKQSArIDEKUyBBIDEwCkEgKyAxClMgQSAxMTIKQSArIDEKUyBBIDExNApBICsgMQpTIEEgMTA1CkEgKyAxClMgQSAxMTAKQSArIDEKUyBBIDExNgpBICsgMQpTIEEgNzYKQSArIDEKUyBBIDEwNQpBICsgMQpTIEEgMTEwCkEgKyAxClMgQSAxMDEKQSArIDEKUyBBIDMyCkEgKyAxClMgQSAzMgpBICsgMQpTIEEgODMKQSArIDEKUyBBIDMyCkEgKyAxClMgQSAxMApBICsgMQpTIEEgNjcKQSArIDEKUyBBIDMyCkEgKyAxClMgQSA2MQpBICsgMQpTIEEgMzIKQSArIDEKUyBBIDU3CkEgKyAxClMgQSA1NwpBICsgMQpTIEEgMTAKQSArIDEKUyBBIDY2CkEgKyAxClMgQSAzMgpBICsgMQpTIEEgNjEKQSArIDEKUyBBIDMyCkEgKyAxClMgQSAxMDMKQSArIDEKUyBBIDEwMQpBICsgMQpTIEEgMTE2CkEgKyAxClMgQSAzMgpBICsgMQpTIEEgNjcKQSArIDEKUyBBIDEwCkEgKyAxClMgQSAxMDgKQSArIDEKUyBBIDk4CkEgKyAxClMgQSAxMDgKQSArIDEKUyBBIDY4CkEgKyAxClMgQSAxMApBICsgMQpTIEEgNjcKQSArIDEKUyBBIDMyCkEgKyAxClMgQSA0MwpBICsgMQpTIEEgMzIKQSArIDEKUyBBIDQ5CkEgKyAxClMgQSAxMApBICsgMQpTIEEgMTEyCkEgKyAxClMgQSAxMTQKQSArIDEKUyBBIDEwNQpBICsgMQpTIEEgMTEwCkEgKyAxClMgQSAxMTYKQSArIDEKUyBBIDY3CkEgKyAxClMgQSAxMDQKQSArIDEKUyBBIDk3CkEgKyAxClMgQSAxMTQKQSArIDEKUyBBIDMyCkEgKyAxClMgQSA3MgpBICsgMQpTIEEgMTAKQSArIDEKUyBBIDExMgpBICsgMQpTIEEgMTE0CkEgKyAxClMgQSAxMDUKQSArIDEKUyBBIDExMApBICsgMQpTIEEgMTE2CkEgKyAxClMgQSAzMgpBICsgMQpTIEEgMzIKQSArIDEKUyBBIDY1CkEgKyAxClMgQSAzMgpBICsgMQpTIEEgMTAKQSArIDEKUyBBIDExMgpBICsgMQpTIEEgMTE0CkEgKyAxClMgQSAxMDUKQSArIDEKUyBBIDExMApBICsgMQpTIEEgMTE2CkEgKyAxClMgQSA3MwpBICsgMQpTIEEgMTEwCkEgKyAxClMgQSAxMTYKQSArIDEKUyBBIDMyCkEgKyAxClMgQSA2NgpBICsgMQpTIEEgMTAKQSArIDEKUyBBIDExMgpBICsgMQpTIEEgMTE0CkEgKyAxClMgQSAxMDUKQSArIDEKUyBBIDExMApBICsgMQpTIEEgMTE2CkEgKyAxClMgQSA3NgpBICsgMQpTIEEgMTA1CkEgKyAxClMgQSAxMTAKQSArIDEKUyBBIDEwMQpBICsgMQpTIEEgMzIKQSArIDEKUyBBIDY1CkEgKyAxClMgQSAzMgpBICsgMQpTIEEgNDMKQSArIDEKUyBBIDMyCkEgKyAxClMgQSA0OQpBICsgMQpTIEEgMTAKQSArIDEKUyBBIDY2CkEgKyAxClMgQSAzMgpBICsgMQpTIEEgNjEKQSArIDEKUyBBIDMyCkEgKyAxClMgQSAxMDMKQSArIDEKUyBBIDEwMQpBICsgMQpTIEEgMTE2CkEgKyAxClMgQSAzMgpBICsgMQpTIEEgNjcKQSArIDEKUyBBIDEwCkEgKyAxClMgQSAxMDUKQSArIDEKUyBBIDEwMgpBICsgMQpTIEEgMzIKQSArIDEKUyBBIDY2CkEgKyAxClMgQSAzMgpBICsgMQpTIEEgNjgKQSArIDEKUyBBIDEwCkEgKyAxClMgQSA3MApBICsgMQpTIEEgMzIKQSArIDEKUyBBIDYxCkEgKyAxClMgQSAzMgpBICsgMQpTIEEgNTcKQSArIDEKUyBBIDU3CkEgKyAxClMgQSAxMApBICsgMQpTIEEgNjkKQSArIDEKUyBBIDMyCkEgKyAxClMgQSA2MQpBICsgMQpTIEEgMzIKQSArIDEKUyBBIDEwMwpBICsgMQpTIEEgMTAxCkEgKyAxClMgQSAxMTYKQSArIDEKUyBBIDMyCkEgKyAxClMgQSA3MApBICsgMQpTIEEgMTAKQSArIDEKUyBBIDEwOApBICsgMQpTIEEgOTgKQSArIDEKUyBBIDEwOApBICsgMQpTIEEgNzEKQSArIDEKUyBBIDEwCkEgKyAxClMgQSA3MApBICsgMQpTIEEgMzIKQSArIDEKUyBBIDQzCkEgKyAxClMgQSAzMgpBICsgMQpTIEEgNDkKQSArIDEKUyBBIDEwCkEgKyAxClMgQSAxMTIKQSArIDEKUyBBIDExNApBICsgMQpTIEEgMTA1CkEgKyAxClMgQSAxMTAKQSArIDEKUyBBIDExNgpBICsgMQpTIEEgNjcKQSArIDEKUyBBIDEwNApBICsgMQpTIEEgOTcKQSArIDEKUyBBIDExNApBICsgMQpTIEEgMzIKQSArIDEKUyBBIDY5CkEgKyAxClMgQSAxMApBICsgMQpTIEEgNjkKQSArIDEKUyBBIDMyCkEgKyAxClMgQSA2MQpBICsgMQpTIEEgMzIKQSArIDEKUyBBIDEwMwpBICsgMQpTIEEgMTAxCkEgKyAxClMgQSAxMTYKQSArIDEKUyBBIDMyCkEgKyAxClMgQSA3MApBICsgMQpTIEEgMTAKQSArIDEKUyBBIDEwNQpBICsgMQpTIEEgMTAyCkEgKyAxClMgQSAzMgpBICsgMQpTIEEgNjkKQSArIDEKUyBBIDMyCkEgKyAxClMgQSA3MQpBICsgMQpwcmludExpbmUgQSA9IDk5CkggPSA4MwpwcmludCBkZWYgCnByaW50Q2hhciBICnByaW50TGluZSAgUyAKQyA9IDk5CkIgPSBnZXQgQwpsYmxECkMgKyAxCnByaW50Q2hhciBICnByaW50ICBBIApwcmludEludCBCCnByaW50TGluZSBBICsgMQpCID0gZ2V0IEMKaWYgQiBECkYgPSA5OQpFID0gZ2V0IEYKbGJsRwpGICsgMQpwcmludENoYXIgRQpFID0gZ2V0IEYKaWYgRSBH&input=)
I am ashamed to say this took me a while to write even though most of it was generated by another java program. Thanks to @MartinEnder for helping me out. This is the first quine I have ever written. **Credits go to Leaky Nun** for most of the code. I "borrowed his code" which was originally inspired by mine. My answer is similar to his, except it shows the "power" of the preprocessor. Hopefully this approach can be used to golf of bytes if done correctly. The goal was to prevent rewriting the word "set" 100's of times.
**Please check out his [much shorter answer!](https://codegolf.stackexchange.com/a/91283/46918)**
[Answer]
# [ಠ\_ಠ](https://codegolf.meta.stackexchange.com/a/7390/41247), 6 bytes
```
ಠಠ
```
This used to work back when the interpreter was still buggy but that's fixed now. However, you can try it in the [legacy version of the interpreter](http://codepen.io/molarmanful/debug/rxJmqx)!
[Answer]
# [Husk](https://github.com/barbuz/Husk), 8 bytes
```
S+s"S+s"
```
[Try it online!](https://tio.run/##yygtzv7/P1i7WAmE//8HAA "Husk – Try It Online")
Husk is a new golfing functional language created by me and [Zgarb](https://chat.stackexchange.com/users/136121). It is based on Haskell, but has an intelligent inferencer that can "guess" the intended meaning of functions used in a program based on their possible types.
### Explanation
This is a quite simple program, composed by just three functions:
`S` is the S combinator from [SKI (typed) combinator calculus](https://en.wikipedia.org/wiki/SKI_combinator_calculus): it takes two functions and a third value as arguments and applies the first function to the value and to the second function applied to that value (in code: `S f g x = f x (g x)`).
This gives us `+"S+s"(s"S+s")`. `s` stands for `show`, the Haskell function to convert something to a string: if show is applied to a string, special characters in the string are escaped and the whole string is wrapped in quotes.
We get then `+"S+s""\"S+s\""`. Here, `+` is string concatenation; it could also be numeric addition, but types wouldn't match so the other meaning is chosen by the inferencer.
Our result is then `"S+s\"S+s\""`, which is a string that gets printed simply as `S+s"S+s"`.
[Answer]
## [Bash](https://www.gnu.org/software/bash/), 48 bytes
```
Q=\';q='echo "Q=\\$Q;q=$Q$q$Q;eval \$q"';eval $q
```
[Try it online!](https://tio.run/##S0oszvj/P9A2Rt260FY9NTkjX0EJyItRCQTyVQJVCoGM1LLEHIUYlUIldQhTpfD/fwA "Bash – Try It Online")
[Answer]
# [Reflections](https://thewastl.github.io/Reflections/), 1.81x10375 bytes
Or to be more accurate, `1807915590203341844429305353197790696509566500122529684898152779329215808774024592945687846574319976372141486620602238832625691964826524660034959965005782214063519831844201877682465421716887160572269094496883424760144353885803319534697097696032244637060648462957246689017512125938853808231760363803562240582599050626092031434403199296384297989898483105306069435021718135129945` bytes.
The relevant section of code is:
```
+#::(1 \/ \ /: 5;;\
>v\>:\/:4#+ +\
/+# / 2 /4):_ ~/
\ _ 2:#_/ \ _(5#\ v#_\
*(2 \;1^ ;;4) :54/
\/ \ 1^X \_/
```
Where each line is preceeded by `451978897550835461107326338299447674127391625030632421224538194832303952193506148236421961643579994093035371655150559708156422991206631165008739991251445553515879957961050469420616355429221790143067273624220856190036088471450829883674274424008061159265162115739311672254378031484713452057940090950890560145649762656523007858600799824096074497474620776326517358755429533782443` spaces. The amount of spaces is a base 128 encoded version of the second part, with 0 printing all the spaces again.
Edit: H.PWiz points out that the interpreter probably doesn't support this large an integer, so this is all theoretical
### How It Works:
```
+#::(1 Pushes the addition of the x,y coordinates (this is the extremely large number)
Dupe the number a couple of times and push one of the copies to stack 1
\
>
Pushes a space to stack 2
*(2
\/
/ \
>v >:\
/+# / 2 Print space number times
\ _ 2:#_/
# Pop the extra 0
\;1^ Switch to stack 1 and start the loop
/:4#+ +\
/4):_ ~/ Divide the current number by 128
\ _(5#\ v Mod a copy by 128
^ 4) :
\_/
v#_\ If the number is not 0:
^ ;;4) :54/ Print the number and re-enter the loop
/: 5;;\
v\ 4 If the number is 0:
4 Pop the excess 0
: \ And terminate if the divided number is 0
Otherwise return to the space printing loop
\ 1^X
```
Conclusion: Can be golfed pretty easily, but maybe looking for a better encoding algorithm would be best. Unfortunately, there's basically no way to push an arbitrarily large number without going to that coordinate.
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 1805 bytes
```
(())(()()()())(())(())(()()())(())(())(()()()())(())(())(()()()())(())(()()())(()())(()()())(())(()()()())(())(())(())(())(())(()())(()()()())(()())(()()())(())(()()()())(())(())(()()()())(())(()()())(()())(())(()()())(()()())(())(())(()()())(())(())(())(())(())(()()()())(())(())(()()())(())(())(())(()()())(()()())(()()()())(())(()()())(()())(())(()()())(())(())(())(())(())(()()())(()()()())(())(()())(())(()()())(()())(()()())(()()()())(())(()()())(())(())(())(())(()()())(()()()())(()())(())(()())(()()())(())(()())(()())(())(())(())(())(())(())(())(()())(())(()()())(())(())(()())(())(())(())(())(()()()())(()())(())(()()())(())(())(()()())(()())(())(()()())(()())(())(())(())(()())(())(())(()()())(()())(()())(()()()()())(()())(()())(()())(()()()())(())(())(()()())(())(())(()()())(()())(())(())(()()())(()())(()())(())(())(()()())(())(())(()())(())(()())(())(()())(())(()())(())(()())(()())(()())(()())(()()()())(())(()())(())(()()())(()())(()())(()()()())(()())(())(())(()())(()()()()())(()()())(())(()())(()())(())(())(())(()()())(())(())(()()()())(())(())(()()()())(())(()()())(()())(()()())(())(()()()())(())(())(()()()())(())(())(())(())(()())(()()()()())(())(())(()())(())(()()())(()())(()())(()())(())(()()()())(())(())(()())(())(()()())(()())(()()())(()()()())(())(()())(())(())(())(()()())(()()()()())(()())(()())(())(()()()())(())(())(())(()())(()()()()())(())(())(()())(())(()()())(())(())(()()())(())(())(()()())(())(())(()())(())(()())(())(()())(())(()())(())(()())(()())(()())(()())(()())(()())(())(()()()())(()()()){<>(((((()()()()()){}){}){}())[()])<>(([{}])()<{({}())<>((({}())[()]))<>}<>{({}<>)<>}{}>)((){[()](<(({}()<(((()()()()()){})(({})({}){})<((([(({})())]({}({}){}(<>)))()){}())>)>))((){()(<{}>)}{}<{({}()<{}>)}>{}({}<{{}}>{})<>)>)}{}){{}({}<>)<>{(<()>)}}<>{({}<>)<>}{}}<>
```
[Try it online!](https://tio.run/##tVNJDsIwDLzzkvjQH0SReEfVQzkgIRAHrlbeHuwYVDWL4wrRhTrjZcYmubzW23O6PtZ7Ss4B0Cs3uO1trTXka9fZdea@yj7Gkq8x7xG9p3F/rajya1HSY2zV0CfaZhzXbk28RHpK@9pqT3um@r7S@u6zlPPZGFu4fZfbmMaTsFgjjZZuW5rqWYz/7X@eeG2nllqtvWtsx86QfnqsrEe7sa9/3VE95fmLPrh8bbIxykPm7GABjpgxLuTz6DKek7YIWkcf2OcD2xgDEyA7nZdIX5EwDk7Y2DsLAJRDCSKB6oGE00@gO9elCp45iOijSJYh53nEyCYpgRwDKDhrQ9LDaKGXjFNKaTq/AQ "Brain-Flak – Try It Online")
*-188 bytes by avoiding code duplication*
Like Wheat Wizard's answer, I encode every closing bracket as 1. The assignment of numbers to the four opening brackets is chosen to minimize the total length of the quine:
```
2: ( - 63 instances
3: { - 41 instances
4: < - 24 instances
5: [ - 5 instances
```
The other major improvement over the old version is a shorter way to create the code points for the various bracket types.
The decoder builds the entire quine on the second stack, from the middle outward. Closing brackets that have yet to be used are stored below a 0 on the second stack. Here is a full explanation of an earlier version of the decoder:
```
# For each number n from the encoder:
{
# Push () on second stack (with the opening bracket on top)
<>(((((()()()()()){}){}){}())[()])<>
# Store -n for later
(([{}])
# n times
{<({}())
# Replace ( with (()
<>((({}())[()]))<>
>}{}
# Add 1 to -n
())
# If n was not 1:
((){[()]<
# Add 1 to 1-n
(({}())<
# Using existing 40, push 0, 91, 60, 123, and 40 in that order on first stack
<>(({})<(([(({})())]((()()()()()){})({}{}({})(<>)))({})()()())>)
# Push 2-n again
>)
# Pop n-2 entries from stack
{({}()<{}>)}{}
# Get opening bracket and clear remaining generated brackets
(({}<{{}}>{})
(<
# Add 1 if n was 2; add 2 otherwise
# This gives us the closing bracket
({}(){()(<{}>)}
# Move second stack (down to the 0) to first stack temporarily and remove the zero
<<>{({}<>)<>}{}>
# Push closing bracket
)
# Push 0
>)
# Push opening bracket
)
# Move values back to second stack
<>{({}<>)<>}
# Else (i.e., if n = 1):
>}{})
{
# Create temporary zero on first stack
(<{}>)
# Move second stack over
<>{({}<>)<>}
# Move 0 down one spot
# If this would put 0 at the very bottom, just remove it
{}({}{(<()>)})
# Move second stack values back
<>{({}<>)<>}}{}
}
# Move to second stack for output
<>
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 18 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
[@ngn's updated version](https://chat.stackexchange.com/transcript/message/48380903#48380903 "The APL Orchard") of the [classic APL quine](https://codegolf.stackexchange.com/a/70520/43319 "APL, 22 bytes – Alex A."), using a modern operator to save four bytes.
```
1⌽,⍨9⍴'''1⌽,⍨9⍴'''
```
[Try APL!](https://tryapl.org/?a=1%u233D%2C%u23689%u2374%27%27%271%u233D%2C%u23689%u2374%27%27%27&run "tryapl.org/?a=1⌽,⍨9⍴'''1⌽,⍨9⍴'''")
`'''1⌽,⍨9⍴'''` the characters `'1⌽,⍨9⍴'`
`9⍴` cyclically **r**eshape to shape 9; `'1⌽,⍨9⍴''`
`,⍨` concatenation selfie; `'1⌽,⍨9⍴'''1⌽,⍨9⍴''`
`1⌽` cyclically rotate one character to the left; `1⌽,⍨9⍴'''1⌽,⍨9⍴'''`
[Answer]
# [Alchemist](https://github.com/bforte/Alchemist), ~~720 657 637~~ 589 bytes
*-68 bytes thanks to Nitrodon!*
```
0n0n->1032277495984410008473317482709082716834303381684254553200866249636990941488983666019900274253616457803823281618684411320510311142825913359041514338427283749993903272329405501755383456706244811330910671378512874952277131061822871205085764018650085866697830216n4+Out_"0n0n->"+Out_n4+nn+n0n
4n0+4n0+n->Out_"n"
n+n+4n0+n0+n0+n0->Out_"+"
n+n+n+4n0+n0+n0->Out_n
4n+4n0+n0->Out_"4"
4n+n+4n0->Out_"\""
4n+n+n+n0+n0+n0->Out_"->"
4n+n+n+n+n0+n0->Out_"\n"
4n+4n+n0->Out_"Out_"
4n+4n+n->Out_"\\"
nn->4n0+4n0+nnn
n0+n4->n
nnn+4n+4n+n4->nn+n00
nnn+0n4->n+n40
n40+0n00+n4->n4+nn
n40+0n+n00->n4+n40
```
[Try it online!](https://tio.run/##XZBZagMxEET/fYz5HQy9q/WTK@QChhCSQAyJHLBz/UxKM7KzwCzqV6Xukh7fnl5f3o/ny7JQo7a/Y1KRUqx6TTMmorSiysVSClXClyPVlFQTKxM3dxX4IsRqaNRK1dgya2pEEAOQFDg1OMxLkqaoYDtn9CmM/Y7JzGyS4pVVvZKxs2GMSZFUZKpVK/IVbK5G7sQFs5HGoxCmW6KVUmWKwlrSWbIfpZ@IFZRTQBjTKL2EEQI4ojvCRy2pJBzN5vvPy8O0Xci0FmCtzQA7azT3F9LqatMOwobGM5R5U35pm9B7DDacNnW0wkEO00Dtf1ckuil/hEObtsY/aP1c4dV2QCwUt3O0tus/299h0VZvt/e6t6IV0lqDojRCSWNLv5eBunkjRsvydfq4HE/tvOyfvwE "Alchemist – Try It Online")
Warning, takes far longer than the lifetime of the universe to execute, mostly cause we have to transfer that rather large number on the first line back and forth between multiple atoms repeatedly. [Here's a version](https://tio.run/##tZBbbsMgEEX/vQz/WpYGDLb5yRa6gUhV1VZqpJZUSrr9umBIGj/APMZSHjDD3Ln3vHy@frx/nS7XYQAJsj5QThkF3vWE8o42HaMtFS0XXADrW9J0hHNBiGgBeN8z4K0ggjdENE3fENXnAJQy0lDJqqef63NpdMvxompSVqpQMAmV/qrW@EqWhWqYkv3YTmU6Dz3T0Bq2Zl@yUpfGoq0cS1uSc1Xl6N6ZNI6yNML/pfHnVrw9Oypb6nLPIWWh/1h9UAc5vtXP9V1LwViE8a6q6spAXcGOaC62pB@bCoNBDwkwY@pIQI8UcDvpN/VBn5kRNc8nA48j06Hl2GxwOjofXhtfCMwlliLrMitCS6k1MZfcquCa5LqoW9YhvC7tEvfJOxe4VriX@Nd4FrlX@ZZtrfMu9K30L91eu7HYv3precj6TQNbFrZNhNkIMLJtJcRMqJ0gQyGWwkyF2wo0FmYt1FyMvWCDoRbDTcbZjDAabjXGbKzdKMMxluNMx9uONB5nPdZ8iv3oALER4kOkxUgIEh8lJUxqnKRAKZHSQqXHSgyWFi01XE685ICpEdND5sXMCJoeNSdsbtyswDmR80Lnx84Mnhc9NzxG/GwAuQjyIeBgQACRjwIDBhYOFCAYSHCg4GFBAoODBgsOJh40QFiI8CDhYkIEhYcKExY2LlRgmMhwoeFjQwaHiw4b3h740AFiI8SHuA/GHUDio9wD5h3n8Hv@vp7O8jLUb38) that outputs the first few lines in a reasonable amount of time.
[Here is the encoder](https://tio.run/##ZZHtboIwFIb/cxWkIwukgv3RLJlmhDvYBagxbrLEDQoBNSxEb52957SizgROe57z9ny0dd4UL8NQ/vpBWxya2n/zeZ17HljWwV8IIya@kGQUGU1mKcjGKe9Z8H7Yr9lbihWOP/HhrEvaqtmHfWzzJ59V@REG6@gUQdNuqEZSowl7Ik2T515oI0UXBlL6293R19FZjKCstgy0UYTCrIulDKKr8B5f5MbEKfXXh2fU5oIncUI1dECVqZHbBqdZN42S72pn3EUUmOVRUG7qsMcAX7um3WOqyewHgyVNfsybNp/bvBlmo3X2usiK1XwYjJZ8V8ootCXYATNGAng0Gf2uY1y@h4BF7nMRaSM3MRugHI45pRaEGDqC57PI/M@KjsbIXQCvbBNfEZsLvMiWaAvOOIcxHi06TrExrCU5@ZRKMVTsg8LVCq5yR@heHCKxJVr9AQ) that turns the program into the data section
Everything but the large number on the first line is encoded using these ~~8~~ 9 tokens:
```
0 n + -> " \n Out_ \ 4
```
That's why all the atom names are composed of just `n`,`0` and `4`.
As a bonus, this is now fully deterministic in what order the rules are executed.
### Explanation:
```
Initialise the program
0n0n-> If no n0n atom (note we can't use _-> since _ isn't a token)
n4+Out_"0n0n->"+Out_n4+nn4+n0n
NUMn4 Create a really large number of n4 atoms
+Out_"0n0n->" Print the leading "0n0n->"
+Out_n4 Print the really large number
+nn Set the nn flag to start getting the next character
+n0n And prevent this rule from being called again
Divmod the number by 9 (nn and nnn flag)
nn->4n0+4n0+nnn Convert the nn flag to 8 n0 atoms and the nnn flag
n0+n4->n Convert n4+n0 atoms to an n atom
nnn+4n+4n+n4->nn+n00 When we're out of n0 atoms, move back to the nn flag
And increment the number of n00 atoms
nnn+0n4->n+n40 When we're out of n4 atoms, add another n atom and set the n40 flag
Convert the 9 possible states of the n0 and n atoms to a token and output it (nn flag)
n+4n0+4n0->Out_"n" 1n+8n0 -> 'n'
n+n+4n0+n0+n0+n0->Out_"+" 2n+7n0 -> '+'
n+n+n+4n0+n0+n0->Out_n 3n+6n0 -> '0'
4n+4n0+n0->Out_"4" 4n+5n0 -> '4'
4n+n+4n0->Out_"\"" 5n+4n0 -> '"'
4n+n+n+n0+n0+n0->Out_"->" 6n+3n0 -> '->'
4n+n+n+n+n0+n0->Out_"\n" 7n+2n0 -> '\n'
4n+4n+n0->Out_"Out_" 8n+1n0 -> 'Out_'
4n+4n+n->Out_"\\" 9n+0n0 -> '\'
Reset (n40 flag)
n40+0nn+n00->n4+n40 Convert all the n00 atoms back to n4 atoms
n40+0n00+n4->n4+nn Once we're out of n00 atoms set the nn flag to start the divmod
```
[Answer]
# [Brian & Chuck](https://github.com/m-ender/brian-chuck), ~~211 143 138 133 129 98 86~~ 84 bytes
```
?.21@@/BC1@c/@/C1112BC1BB/@c22B2%C@!{<?
!.>.._{<+>>-?>.---?+<+_{<-?>+<<-.+?ÿ
```
[Try it online!](https://tio.run/##SyrKTMzTTc4oTc7@/9@ekVHPyNDBQd/J2dChPlnfQd/Z0NDQCMhzctIHChgZORmp8jk71CsyV9vYcynq2enpxVfbaNvZ6drb6enq6tpr22gDBYA8bRsbXT1t@8P7//8HAA "Brian & Chuck – Try It Online")
old version:
```
?{<^?_>{_;?_,<_-+_;._;}_^-_;{_^?_z<_>>_->_->_*}_-<_^._=+_->_->_->_-!_ ?_;}_^_}<?
!.>.>.>.+>._<.}+>.>.>?<{?_{<-_}<.<+.<-?<{??`?=
```
[Try it online!](https://tio.run/##LYuxDsJADEPVEf6iKyH5gXOTPzkDXUBIDEgsRPftR3tC9uJn@/Z@XF@63j/rs/dI1KAnS/AMqrAYS2NVluRWfUF36vCpUcFqXORPds88xLhMExviOJsPiRthTUYKZDCh28IgBt1BXGLp/Qc "Brian & Chuck – Try It Online")
New code. Now the data isn't split into nul separated chunks, but the nul will be pulled through the data.
```
Brian:
? start Chuck
.21@@/BC1@c/@/C1112BC1BB/@c22B2%C@!
data. This is basically the end of the Brian code and the Chuck code reversed
and incremented by four. This must be done because the interpreter tries
to run the data, so it must not contain runnable characters
ASCII 3 for marking the end of the code section
{<? loop the current code portion of Chuck
Chuck:
code 1 (print start of Brian code)
.>.. print the first 3 characters of Brian
code 2 (print the data section)
{<+>>- increment char left to null and decrement symbol right to null
for the first char, this increments the question mark and decrements the
ASCII 1. So the question mark can be reused in the end of the Chuck code
?>. if it became nul then print the next character
---?+<+ if the character is ASCII 3, then the data section is printed.
set it 1, and set the next char to the left 1, too
code 3 (extract code from data)
{<- decrement the symbol left to the nul
?>+<<-. if it became nul then it is the new code section marker, so set the old one 1
and print the next character to the left
+? if all data was processed, then the pointer can't go further to the left
so the char 255 is printed. If you add 1, it will be null and the code ends.
ÿ ASCII 255 that is printed when the end of the data is reached
```
[Answer]
# [Klein](https://github.com/Wheatwizard/Klein), 330 bytes
```
"![ .; =90*/[ .9(#; =[>[. >1# 98='9[ '7[.>; [*; ) =#0,*[ =.>9(. =*(#(#([ .0#8;#(#; [*9>[; => [*? [9(;;"\
/ <
>:1+0\
/:)$<
>\?\ /
?2 $
:9>(:\
(8\/?<
\+ <
*
>$1-+\
>/?:) /
>+)$)$)\
/1$9<$)$<
\+:?\<
>?!\+@
\:)<<
```
[Try it online!](https://tio.run/##vc5NbgMhDAXgtX0JSEAKAw0w3XT4GdOew952UbXK/XeEXKJ@qyc9ffLv3/fPY87rhSE2OEv2iUHF4sxqTKwi0K4MlOO8FYbbB0dqwF41UBuo0@Q3z3BGKm5N1emdWVlYNkczL4V9IV4YafYDuLjWroIJ/vU6Ut1DFtSpbnY1GaITjndtsRZyVdAdkkZHCbqj9qjJ7vcgSGnUbU01hc2urNd3W7p9KRLqkIWNi4RPlLr1jnPOPed5/3oC "Klein – Try It Online")
This works in all topologies, mostly by completely avoiding wrapping. The first list encodes the rest of the program offset by one, so newlines are the unprintable (11).
[Answer]
# [ed(1)](https://kidneybone.com/c2/wiki/EdIsTheStandardTextEditor), 45 bytes
We have quines for `TECO`, `Vim`, and `sed`, but not the almighty `ed`?! This travesty shall not stand. (NB: See also, this [error quine](https://codegolf.stackexchange.com/a/36286/15940) for `ed`)
[Try it Online!](https://tio.run/##S035/z@RK5FLh0unxJBLRdekWF9HX0@fS6eAK5BLD4vg//8A)
```
a
a
,
,t1
$-4s/,/./
,p
Q
.
,t1
$-4s/,/./
,p
Q
```
Stolen from [here](https://github.com/tpenguinltg/ed1-quine/blob/master/quine.ed). It should be saved as a file `quine.ed` then run as follows: (TIO seems to work a bit differently)
```
$ ed < quine.ed
```
[Answer]
# [Grok](https://github.com/AMiller42/Grok-Language), 42 bytes
```
iIilWY!}I96PWwI10WwwwIkWwwwIhWq``
k h
```
[Try it Online!](http://grok.pythonanywhere.com?flags=&code=iIilWY!%7DI96PWwI10WwwwIkWwwwIhWq%60%60%0A%20%20%20k%20%20%20h&inputs=)
It is very costly to output anything in Grok it seems.
[Answer]
# [!@#$%^&\*()\_+](https://github.com/ConorOBrien-Foxx/ecndpcaalrlp), ~~1128~~ ~~1116~~ ~~1069~~ ~~960~~ ~~877~~ ~~844~~ ~~540~~ ~~477~~ ~~407~~ ~~383~~ 33 bytes
**Edit**: Woah... -304 B with space
**Edit 2**: Bruh.
**Edit 3**: Thanks Jo King for the idea! I outgolfed ya!
A stack-based language(The first on TIO's list!)
It's a big pile of unprintables though
```
N0N (!&+$*)^(!&@^)!
```
(Spaces are `NUL` bytes)
[Try it online!](https://tio.run/##S03OSylITkzMKcop@P9f0s9ATFDCT1JKRJoByGAQ0FBUE9BW0dKMAzIc4jQV//8HAA)
Here's the code, but in Control Pictures form:
```
␙N0␖␑␘N␙␚␔␛␀␖␑␘␀␐(!&␐+$*)^(!&@^)!
```
## Explanation
```
␙N0␖␑␘N␙␚␔␛␀␖␑␘␀␐ Data
(!&‚êê+$*) Push the stack, reversed and +16 back on top
^(!&@^)! Print everything reversed, including the length (Hence the final `!`)
```
It does error on overflow though...
[Answer]
# Commodore Basic, ~~54~~ 41 characters
```
1R─A$:?A$C|(34)A$:D♠"1R─A$:?A$C|(34)A$:D♠
```
Based on DLosc's QBasic quine, but modified to take advantage of Commodore Basic's shortcut forms. In particular, the shorter version of `CHR$(34)` makes using it directly for quotation marks more efficient than defining it as a variable.
As usual, I've made substitutions for PETSCII characters that don't appear in Unicode: `♠` = `SHIFT+A`, `─` = `SHIFT+E`, `|` = `SHIFT+H`.
**Edit:** You know what? If a string literal ends at the end of a line, the Commodore Basic interpreter will let you leave out the trailing quotation mark. Golfed off 13 characters.
Alternatively, if you want to skirt the spirit of the rules,
```
1 LIST
```
`LIST` is an instruction that prints the current program's code. It is intended for use in immediate mode, but like all immediate-mode commands, it can be used in a program (eg. `1 NEW` is a self-deleting program). Nothing shorter is possible: dropped spaces or abbreviated forms get expanded by the interpreter and displayed at full length.
[Answer]
# Jolf, 4 bytes
```
Q¬´Q¬´
Q double (string)
¬´ begin matched string
Q¬´ capture that
```
This transpiles to `square(`Q¬´`)` (I accidentally did string doubling in the `square` function), which evaluates to `Q¬´Q¬´`. Note that `q` is the quining function in Jolf, *not* `Q` ;).
[Answer]
# [Vitsy](https://github.com/VTCAKAVSMoACE/Vitsy), ~~11~~ ~~9~~ ~~8~~ 6 Bytes
This programming language was obviously made past the date of release for this question, but I thought I'd post an answer so I can a) get more used to it and b) figure out what else needed to be implemented.
```
'rd3*Z
```
The explanation is as follows:
```
'rd3*Z
' Start recording as a string.
(wraps around once, capturing all the items)
' Stop recording as a string. We now have everything recorded but the original ".
r Reverse the stack
b3* This equates the number 39 = 13*3 (in ASCII, ')
Z Output the entire stack.
```
[Answer]
# Fuzzy Octo Guacamole, 4 bytes
```
_UNK
```
I am not kidding. Due to a suggestion by @ConorO'Brien, `K` prints `_UNK`. The `_UN` does nothing really, but actually sets the temp var to `0`, pushes `0`, and pushes `None`.
The `K` prints "\_UNK", and that is our quine.
[Answer]
# C++, ~~286~~ ~~284~~ 236 bytes
Now with extra golf!
```
#include<iostream>
int main(){char a[]="#include<iostream>%sint main(){char a[]=%s%s%s,b[]=%s%s%s%s,c[]=%s%sn%s,d[]=%s%s%s%s;printf(a,c,b,a,b,b,d,b,b,b,d,b,b,d,d,b);}",b[]="\"",c[]="\n",d[]="\\";printf(a,c,b,a,b,b,d,b,b,b,d,b,b,d,d,b);}
```
I'm currently learning C++, and thought "Hey, I should make a quine in it to see how much I know!" 40 minutes later, I have this, a full ~~64~~ **114** bytes shorter than [the current one](https://codegolf.stackexchange.com/questions/69/golf-you-a-quine-for-great-good/2431#2431). I compiled it as:
```
g++ quine.cpp
```
Output and running:
```
C:\Users\Conor O'Brien\Documents\Programming\cpp
λ g++ quine.cpp & a
#include<iostream>
int main(){char a[]="#include<iostream>%sint main(){char a[]=%s%s%s,b[]=%s%s%s%s,c[]=%s%sn%s,d[]=%s%s%s%s;printf(a,c,b,a,b,b,d,b,b,b,d,b,b,d,d,b);}",b[]="\"",c[]="\n",d[]="\\";printf(a,c,b,a,b,b,d,b,b,b,d,b,b,d,d,b);}
```
[Answer]
# [Cheddar](https://github.com/cheddar-lang/Cheddar), 56 bytes
```
var a='var a=%s;print a%@"39+a+@"39';print a%@"39+a+@"39
```
[**Try it online!**](http://cheddar.tryitonline.net/#code=dmFyIGE9J3ZhciBhPSVzO3ByaW50IGElQCIzOSthK0AiMzknO3ByaW50IGElQCIzOSthK0AiMzk&input=)
I felt like trying to make something in Cheddar today, and this is what appeared...
[Answer]
# 05AB1E, ~~16~~ 17 bytes
```
"34çs«DJ"34çs«DJ
```
With trailing newline.
[Try it online!](http://05ab1e.tryitonline.net/#code=IjM0w6dzwqtESiIzNMOnc8KrREoK&input=)
**Explanation:**
```
"34çs«DJ" # push string
34ç # push "
s¬´ # swap and concatenate
DJ # duplicate and concatenate
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 19 bytes
*Thanks to @Oliver for a correction (trailing newline)*
```
"D34ç.øsJ"D34ç.øsJ
```
There is a trailing newline.
[Try it online!](http://05ab1e.tryitonline.net/#code=IkQzNMOnLsO4c0oiRDM0w6cuw7hzSgo&input=)
```
"D34ç.øsJ" Push this string
D Duplicate
34 Push 34 (ASCII for double quote mark)
ç Convert to char
.√∏ Surround the string with quotes
s Swap
J Join. Implicitly display
```
[Answer]
# Clojure, 91 bytes
```
((fn [x] (list x (list (quote quote) x))) (quote (fn [x] (list x (list (quote quote) x)))))
```
[Answer]
# Mathematica, 68 bytes
```
Print[#<>ToString[#,InputForm]]&@"Print[#<>ToString[#,InputForm]]&@"
```
] |
[Question]
[
## Challenge
Given a list of numbers, calculate the population standard deviation of the list.
Use the following equation to calculate population standard deviation:
![](https://upload.wikimedia.org/math/3/1/8/31830fa1f2f922edf6079209a51f8967.png)
## Input
The input will a list of integers in any format (list, string, etc.). Some examples:
```
56,54,89,87
67,54,86,67
```
The numbers will always be integers.
Input will be to STDIN or function arguments.
## Output
The output must be a floating point number.
## Rules
You may use built in functions to find the standard deviation.
Your answer can be either a full program or a function.
## Examples
```
10035, 436844, 42463, 44774 => 175656.78441352615
45,67,32,98,11,3 => 32.530327730015607
1,1,1,1,1,1 => 0.0
```
## Winning
The shortest program or function wins.
## Leaderboard
```
var QUESTION_ID=60901,OVERRIDE_USER=30525;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]
# [Clip](https://esolangs.org/wiki/Clip), 3
```
.sk
```
`.s` is the standard deviation, `k` parses the input in the form `{1,2,3}`.
[Answer]
# Mathematica, ~~24~~ 22 bytes
Nice, Mathematica has a built-in `StandardDevi...` oh... that computes the sample standard deviation, not the population standard deviation.
But what if we use `Variance`... oh... same deal.
But there is yet another related built-in:
```
CentralMoment[#,2]^.5&
```
Yay. :)
This also works for 22 bytes:
```
Mean[(#-Mean@#)^2]^.5&
```
And this for 27:
```
N@RootMeanSquare[#-Mean@#]&
```
[Answer]
# Octave, 14 bytes
```
g=@(a)std(a,1)
```
Try it on [ideone](http://ideone.com/noczhf).
[Answer]
# [kdb+](http://kx.com/software-download.php), 3 bytes
```
dev
```
One of the APL derviates *had to* have this as a built-in.
### Test run
```
q)dev 56, 54, 89, 87
16.53028
q)f:dev
q)f 10035, 436844, 42463, 44774
175656.8
q)f 45,67,32,98,11,3
32.53033
```
[Answer]
# Dyalog APL, ~~24~~ ~~23~~ ~~21~~ ~~20~~ ~~19~~ 17 bytes
```
*∘.5∘M×⍨-M×M←+/÷≢
```
This defines an unnamed, monadic function train, which is equivalent to the following function.
```
{.5*⍨M(×⍨⍵)-M⍵×(M←{(+/⍵)÷≢⍵})⍵}
```
Try them online on [TryAPL](http://tryapl.org/?a=%28%20%28*%u2218.5%u2218M%D7%u2368-M%D7M%u2190+/%F7%u2262%29%20%2C%20%7B.5*%u2368M%28%D7%u2368%u2375%29-M%u2375%D7%28M%u2190%7B%28+/%u2375%29%F7%u2262%u2375%7D%29%u2375%7D%20%29%2056%2054%2089%2087&run).
### How it works
The code consists of several trains.
```
M←+/÷≢
```
This defines a monadic 3-train (fork) `M` that executes `+/` (sum of all elements) and `≢` (length) for the right argument, then applies `÷` (division) to the results, returning the arithmetic mean of the input.
```
M×M
```
This is another fork that applies `M` to the right argument, repeats this a second time, and applies `×` (product) to the results, returning **μ2**.
```
×⍨-(M×M)
```
This is yet another fork that calculates the square of the arithmetic mean as explained before, applies `×⍨` (product with itself) to the right argument, and finally applies `-` (difference) to the results.
For input **(x1, …, xN)**, this function returns **(x1 - μ2, …, xN - μ2)**.
```
*∘.5∘M
```
This composed function is applies `M` to its right argument, then `*∘.5`. The latter uses right argument currying to apply map input `a` to `a*0.5` (square root of `a`).
```
(*∘.5∘M)(×⍨-(M×M))
```
Finally, we have this monadic 2-train (atop), which applies the right function first, then the left to its result, calculating the standard deviation as follows.
[![formula](https://i.stack.imgur.com/GH3oK.png)](https://i.stack.imgur.com/GH3oK.png)
[Answer]
# R, ~~41~~ ~~40~~ ~~39~~ ~~36~~ ~~30~~ 28 bytes
### code
Thanks to [beaker](https://codegolf.stackexchange.com/users/42892/beaker), [Alex A.](https://codegolf.stackexchange.com/users/20469/alex-a) and [MickyT](https://codegolf.stackexchange.com/users/31347/mickyt) for much bytes.
```
cat(sd(c(v=scan(),mean(v))))
```
### old codes
```
v=scan();n=length(v);sd(v)/(n/(n-1))**0.5
m=scan();cat(sqrt(sum(mean((m-mean(m))^2))))
m=scan();cat(mean((m-mean(m))^2)^.5)
```
This should yield the population standard deviation.
[Answer]
# Julia, ~~26~~ 19 bytes
```
x->std([x;mean(x)])
```
This creates an unnamed function that accepts an array and returns a float.
Ungolfed, I guess:
```
function f(x::Array{Int,1})
# Return the sample standard deviation (denominator N-1) of
# the input with the mean of the input appended to the end.
# This corrects the denominator to N without affecting the
# mean.
std([x; mean(x)])
end
```
[Answer]
# Pyth, ~~20~~ ~~19~~ ~~17~~ 13 bytes
```
@.O^R2-R.OQQ2
```
*Thanks to @FryAmTheEggman for golfing off 4 bytes!*
[Try it online.](https://pyth.herokuapp.com/?code=%40.O%5ER2-R.OQQ2&input=56%2C54%2C89%2C87)
### How it works
```
.OQ Compute the arithmetic mean of the input (Q).
-R Q Subtract the arithmetic mean of all elements of Q.
^R2 Square each resulting difference.
.O Compute the arithmetic mean of the squared differences.
@ 2 Apply square root.
```
[Answer]
# CJam, ~~24~~ ~~22~~ 21 bytes
```
q~_,_@_:+d@/f-:mh\mq/
```
*Thanks to @aditsu for golfing off 1 byte!*
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q~_%2C_%40_%3A%2Bd%40%2Ff-%3Amh%5Cmq%2F&input=%5B56%2054%2089%2087%5D).
### How it works
```
q~ e# Read all input and evaluate it.
_, e# Copy the array and push its length.
_@ e# Copy the length and rotate the array on top.
_:+d e# Copy the array and compute its sum. Cast to Double.
@/ e# Rotate the length on top and divide the sum by it.
f- e# Subtract the result (μ) from the array's elements.
:mh e# Reduce by hypotenuse.
e# a b mh -> sqrt(a^2 + b^2)
e# sqrt(a^2 + b^2) c mh -> sqrt(sqrt(a^2 + b^2)^2 + c^2)
e# = sqrt(a^2 + b^2 + c^2)
e# ⋮
\mq/ e# Divide the result by the square root of the length.
```
[Answer]
# APL, 24 bytes
```
{.5*⍨+/(2*⍨⍵-+/⍵÷≢⍵)÷≢⍵}
```
A little different approach than [Dennis' Dyalog APL solution](https://codegolf.stackexchange.com/a/60913/20469). This should work with any APL implementation.
This creates an unnamed monadic function that computes the vector (*x* - *µ*)2 as `2*⍨⍵-+/⍵÷≢⍵`, divides this by *N* (`÷≢⍵`), takes the sum of this vector using `+/`, and then takes the square root (`.5*⍨`).
[Try it online](http://tryapl.org/?a=%7B.5*%u2368+/%282*%u2368%u2375-+/%u2375%F7%u2262%u2375%29%F7%u2262%u2375%7D%2045%2067%2032%2098%2011%203&run)
[Answer]
# TI-BASIC, 7 bytes
```
stdDev(augment(Ans,{mean(Ans
```
I borrowed the algorithm to get population standard deviation from sample standard deviation from [here](http://tibasicdev.wikidot.com/stddev).
The shortest solution I could find without `augment(` is 9 bytes:
```
stdDev(Ans√(1-1/dim(Ans
```
[Answer]
# Haskell, 61 bytes
```
d n=1/sum(n>>[1])
f a=sqrt$d a*sum(map((^2).(-)(d a*sum a))a)
```
Straightforward, except maybe my custom length function `sum(n>>[1])` to trick Haskell's strict type system.
[Answer]
# Python 3.4+, 30 bytes
```
from statistics import*;pstdev
```
Imports the builtin function `pstdev`, e.g.
```
>>> pstdev([56,54,89,87])
16.53027525481654
```
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly)
**11 bytes**
```
S÷L
Dz_²ÇN½
```
This is a direct translation of [my APL answer](https://codegolf.stackexchange.com/a/60913) to Jelly. [Try it online!](http://jelly.tryitonline.net/#code=U8O3TArDh8KyX8Kyw4dOwr0&input=&args=NDUsNjcsMzIsOTgsMTEsMw)
### How it works
```
S÷L Helper link. Argument: z (vector)
S Compute the sum of z.
L Compute the length of z.
÷ Divide the former by the latter.
This computes the mean of z.
Dz_²ÇN½ Main link. Argument: z (vector)
Ç Apply the previous link, i.e., compute the mean of z.
² Square the mean.
² Square all number in z.
_ Subtract each squared number from the squared mean.
Ç Take the mean of the resulting vector.
N Multiply it by -1.
½ Take the square root of the result.
```
[Answer]
# Prolog (SWI), 119 bytes
**Code:**
```
q(U,X,A):-A is(X-U)^2.
p(L):-sumlist(L,S),length(L,I),U is S/I,maplist(q(U),L,A),sumlist(A,B),C is sqrt(B/I),write(C).
```
**Explanation:**
```
q(U,X,A):-A is(X-U)^2. % calc squared difference of X and U
p(L):-sumlist(L,S), % sum input list
length(L,I), % length of input list
U is S/I, % set U to the mean value of input list
maplist(q(U),L,A), % set A to the list of squared differences of input and mean
sumlist(A,B), % sum squared differences list
C is sqrt(B/I), % divide sum of squares by length of list
write(C). % print answer
```
**Example:**
```
p([10035, 436844, 42463, 44774]).
175656.78441352615
```
Try it out online [here](http://swish.swi-prolog.org/p/dzwqjuYT.pl)
[Answer]
# J, 18 bytes
```
[:%:@M*:-M*M=:+/%#
```
This is a direct translation of [my APL answer](https://codegolf.stackexchange.com/a/60913) to J.
[Try it online!](https://tio.run/nexus/j#@5@mYGulEG2lauXgq2Wl66vla2ulra@q/D81OSNfIU3BxFTBzFzB2EjB0kLB0FDB@D8A "J – TIO Nexus")
[Answer]
# [Haskell](https://www.haskell.org/), 45 bytes
```
(?)i=sum.map(^i)
f l=sqrt$2?l/0?l-(1?l/0?l)^2
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/X8NeM9O2uDRXLzexQCMuU5MrTSHHtriwqETFyD5H38A@R1fDEMLQjDP6n5uYmadgq1BQlJlXoqCikKYQbWKqY2auY2ykY2mhY2ioYxz7/19yWk5ievF/3eSCAgA "Haskell – Try It Online")
The value `i?l` is the sum of the i'th powers of elements in `l`, so that `0?l` is the length and `1?l` is the sum.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~10~~ 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ÅA-nÅAt
```
-3 bytes thanks to *@ovs*.
[Try it online](https://tio.run/##yy9OTMpM/f//cKujbh6QKPn/P9rCWMfQ0EzH0hxMGRqaxgIA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/8Otjrp5QKLkv87/6GhDAwNjUx0TYzMLExMdEyMTM2MdExNzc5NYnWgTUx0zcx1jIx1LCx1DQx1joJChDhzGxgIA).
**Explanation:**
```
ÅA # Get the arithmetic mean of the (implicit) input-list
- # Subtract it from each value in the (implicit) input-list
n # Square each of those
ÅA # Take the arithmetic mean of that
t # And take the square-root of that
# (after which it is output implicitly as result)
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 16 bytes
```
⟨∋-⟨+/l⟩⟩ᶠ^₂ᵐ↰₂√
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//9H8FY86unWBlLZ@zqP5K4Ho4bYFcY@amh5unfCobQOQ8ahj1v//0YYGBsamOgomxmYWJiZA2sjEzBhImZibm8T@jwIA "Brachylog – Try It Online") [(all cases at once)](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3w/9H8FY86unWBlLZ@zqP5K4Ho4bYFcSAVWyeAlbY86pj1/390tKGBgbGpjoKJsZmFiQmQNjIxMwZSJubmJrE6CtEmpjpm5jrGRjqWFjqGhjrGIDFDHTgEcU3NdExNdCwsdSzMQVygchDXDKgvNhYA "Brachylog – Try It Online")
I feel like *maybe* there's some shorter way to compute the squared deviations than 13 bytes.
[Answer]
# [Arn](https://github.com/ZippyMagician/Arn), [~~19~~ ~~18~~ 14 bytes](https://github.com/ZippyMagician/Arn/wiki/Carn)
```
¯‡iʠØbmÅQƥªÈªÆ
```
[Try it!](https://zippymagician.github.io/Arn?code=Oi9tZWFuKG57OipuLW1lYW46c31c&input=MTAwMzUgNDM2ODQ0IDQyNDYzIDQ0Nzc0CjQ1IDY3IDMyIDk4IDExIDMKMSAxIDEgMSAxIDE=)
# Explained
Unpacked: `:/mean(n{:*n-mean:s}\`
```
:/ Square root
mean Mean function
( Begin expression
n{ Block with key of n
:* Square
n
- Subtraction
mean
_ Variable initialized to STDIN; implied
:s Split on spaces
} End of block
\ Mapped over
_ Implied
) End of expression; Implied
```
[Answer]
# [Simplex v.0.5](http://conorobrien-foxx.github.io/Simplex/), 43 bytes
Just 'cuz. I really need to golf this one more byte.
```
t[@u@RvR]lR1RD@wA@T@{j@@SR2ERpR}u@vR@TR1UEo
t[ ] ~~ Applies inner function to entire strip (left-to-right)
@ ~~ Copies current value to register
u ~~ Goes up a strip level
@ ~~ Dumps the register on the current byte
R ~~ Proceeds right (s1)
v ~~ Goes back down
R ~~ Proceeds right (s0)
~~ Go right until an empty byte is found
lR1RD ~~ Push length, 1, and divide.
@ ~~ Store result in register (1/N)
wA ~~ Applies A (add) to each byte, (right-to-left)
@T@ ~~ Puts 1/N down, multiplies it, and copies it to the register
{ } ~~ Repeats until a zero-byte is met
j@@ ~~ inserts a new byte and places register on it
SR ~~ Subtract it from the current byte and moves right
2E ~~ Squares result
RpR ~~ Moves to the recently-created cell, deletes it, and continues
u@v ~~ takes 1/N again into register
R@T ~~ multiplies it by the new sum
R1UE ~~ takes the square root of previous
o ~~ output as number
```
[Answer]
# JavaScript (ES6), 73 bytes
```
a=>Math.sqrt(a.reduce((b,c)=>b+(d=c-eval(a.join`+`)/(l=a.length))*d,0)/l)
```
[Answer]
# Perl5, ~~39~~ 38
---
16 for the script
+22 for the `M` switch
+ 1 for the `E` switch
```
perl -MStatistics::Lite=:all -E"say stddevp@ARGV" .1 .2 300
```
Tested in Strawberry 5.20.2.
---
Oh, but then I realized that you said our answers can be functions instead of programs. In that case,
```
{use Statistics::Lite":all";stddevp@_}
```
has just 38. Tested in Strawberry 5.20.2 as
```
print sub{use Statistics::Lite":all";stddevp@_}->( .1, .2, 300)
```
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), ~~10~~ 7 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
ë_▓-²▓√
```
Port of [my 05AB1E answer](https://codegolf.stackexchange.com/a/210034/52210).
[Try it online.](https://tio.run/##y00syUjPz0n7///w6vhH0ybrHtoEJB91zPr/39DAwNhUwcTYzMLERMHEyMTMWMHExNzchMvEVMHMXMHYSMHSQsHQUMGYy1ABDgE)
**Explanation:**
```
ë # Read all inputs as float-list
_ # Duplicate that list
▓ # Get the average of that list
- # Subtract that average from each value in the list
² # Square each value
▓ # Take the average of that again
√ # And take the square root of that
# (after which the entire stack joined together is output implicitly as result)
```
[Answer]
# [Whispers v2](https://github.com/cairdcoinheringaahing/Whispers), 105 bytes
```
> Input
>> #1
>> ∑1
>> 3÷2
>> L-4
>> L²
>> Each 5 1
>> Each 6 7
>> ∑8
>> 9÷2
>> √10
>> Output 11
```
[Try it online!](https://tio.run/##K8/ILC5ILSo2@v/fTsEzr6C0hMvOTkHZEEQ@6pgIpo0PbzcC0T66JmDq0CYQ5ZqYnKFgqmAIZ5spmEN1WYBoS6iuRx2zDA1ADP/SEqDxCoaG//9HGxoYGJvqKJgYm1mYmABpIxMzYyBlYm5uEgsA "Whispers v2 – Try It Online")
In the latest version of Whispers, the builtin [`σ`](https://github.com/cairdcoinheringaahing/Whispers/blob/master/whispers%20v3.py#L1474) can be used to shave off around 70 bytes.
## How it works
For those unfamiliar with Whispers, the language works by using numbers as line references in order to pass values between lines. For example, the line `>> 3÷2` doesn't calculate \$3 \div 2\$, rather it takes the values of lines **3** and **2** and calculates their division. Execution always begins on the last line.
This program simply implements the standard formula for standard deviation:
$$\sigma = \sqrt{\frac{1}{N}\sum^N\_{i=1}{(x\_i-\bar{x})^2}}$$
$$\bar{x} = \frac{1}{N}\sum^N\_{i=1}{x\_i}$$
Lines **2**, **3** and **4** define \$\bar{x}\$, with it's specific value accessible on line **4**. Line **2** stores \$N\$. We then calculate \$(x\_i-\bar{x})^2\$ for each \$x\_i \in x\$ with the lines **5**, **6**, **7** and **8**:
```
>> L-4
>> L²
>> Each 5 1
>> Each 6 7
```
Line **7** runs line **5** over each element in the input, which takes the difference between each element in the input and the mean, We then square these differences using lines **8** and **6**. Finally, we take the sum of these squares (line **9**), divide by \$N\$ (line **10**) and take the square root (line **11**). Finally, we output this result.
[Answer]
# [Shasta v0.0.10](https://github.com/jacobofbrooklyn/shasta/tree/d66d19a634eb70bd73feac1972327867a7f0ede4), 65 bytes
```
{(**(/(sum(map${|x|(**(- x(/(sum$)(length$)))2)}))(length$)).5)}
```
Online interpreter not set up yet, tested on my machine
Explanation:
`{...}` Function taking argument $
`(** ... .5)` Square root of
`(/ ... (length $))` Dividing ... by the length of $
`(sum ...)` The sum of
`(map $ {|x| ...})` Mapping each x in $ to
`(** ... 2)` The square of
`(- x ...)` The difference between x and
`(/ (sum $) (length $))` The mean of $
[Answer]
# Python, 57 bytes
```
lambda l:(sum((x-sum(l)/len(l))**2for x in l)/len(l))**.5
```
Takes input as a list
Thanks @xnor
[Answer]
### PowerShell, 122
```
:\>type stddev.ps1
$y=0;$z=$args -split",";$a=($z|?{$_});$c=$a.Count;$a|%{$y+=$_};$b=$y/$c;$a|%{$x+
=(($_-$b)*($_-$b))/$c};[math]::pow($x,0.5)
```
explanation
```
<#
$y=0 init
$z=$args -split"," split delim ,
$a=($z|? {$_}) remove empty items
$c=$a.Count count items
$a|%{$y+=$_} sum
$b=$y/$c average
$a|%{$x+=(($_-$b)*($_-$b))/$c} sum of squares/count
[math]::pow($x,0.5) result
#>
```
result
```
:\>powershell -nologo -f stddev.ps1 45,67,32,98,11,3
32.5303277300156
:\>powershell -nologo -f stddev.ps1 45, 67,32,98,11,3
32.5303277300156
:\>powershell -nologo -f stddev.ps1 45, 67,32, 98 ,11,3
32.5303277300156
:\>powershell -nologo -f stddev.ps1 10035, 436844, 42463, 44774
175656.784413526
:\>powershell -nologo -f stddev.ps1 1,1,1,1,1,1
0
```
[Answer]
# Fortran, 138 bytes
Just a straightforward implementation of the equation in Fortran:
```
double precision function std(x)
integer,dimension(:),intent(in) :: x
std = norm2(dble(x-sum(x)/size(x)))/sqrt(dble(size(x)))
end function
```
[Answer]
# SmileBASIC, 105 bytes (as a function)
I just noticed it's allowed to be a function. Whoops, that reduces my answer dramatically. This defines a function `S` which takes an array and returns the population standard deviation. Go read the other one for an explanation, but skip the parsing part. I don't want to do it again.
```
DEF S(L)N=LEN(L)FOR I=0TO N-1U=U+L[I]NEXT
U=1/N*U FOR I=0TO N-1T=T+POW(L[I]-U,2)NEXT RETURN SQR(1/N*T)END
```
## As a program, 212 bytes
Unfortunately, I have to take the input list as a string and parse it myself. This adds over 100 bytes to the answer, so if some input format other than a comma-separated list is allowed I'd be glad to hear it. Also note that because `VAL` is buggy, having a space *before* the comma or trailing the string breaks the program. After the comma or at the start of the string is fine.
```
DIM L[0]LINPUT L$@L I=INSTR(O,L$,",")IF I>-1THEN PUSH L,VAL(MID$(L$,O,I-O))O=I+1GOTO@L ELSE PUSH L,VAL(MID$(L$,O,LEN(L$)-O))
N=LEN(L)FOR I=0TO N-1U=U+L[I]NEXT
U=1/N*U FOR I=0TO N-1T=T+POW(L[I]-U,2)NEXT?SQR(1/N*T)
```
Ungolfed and explained:
```
DIM L[0] 'define our array
LINPUT L$ 'grab string from input
'parse list
'could've used something cleaner, like a REPEAT, but this was shorter
@L
I=INSTR(O,L$,",") 'find next comma
IF I>-1 THEN 'we have a comma
PUSH L,VAL(MID$(L$,O,I-O)) 'get substring of number, parse & store
O=I+1 'set next search location
GOTO @L 'go again
ELSE 'we don't have a comma
PUSH L,VAL(MID$(L$,O,LEN(L$)-O)) 'eat rest of string, parse & store
ENDIF 'end
N=LEN(L) 'how many numbers we have
'find U
'sum all of the numbers, mult by 1/N
FOR I=0 TO N-1
U=U+L[I]
NEXT
U=1/N*U
'calculate our popstdev
'sum(pow(x-u,2))
FOR I=0 TO N-1
T=T+POW(L[I]-U,2)
NEXT
PRINT SQR(1/N*T) 'sqrt(1/n*sum)
```
] |
[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]
[
The cops thread can be found here: [The Mystery String Printer (Cops)](https://codegolf.stackexchange.com/questions/60328/the-mystery-string-printer-cops)
# Your challenge
* Choose a submission from the cops thread, and print out the string from an answer in that thread.
* The submission that you choose must not be safe (it must be newer than 7 days).
* Your program, function, or REPL script needs to follow the same rules as the cops thread. Just to recap:
+ Your program must be ≤128 characters (if a cop's submission is in a smaller range of program lengths, your program must also be in that length range. For example, if a cop's program is ≤32 bytes, your program must be ≤32 bytes).
+ The program must produce the same output every time it is run.
+ No cryptographic functions.
+ The program must not take input.
+ No standard loopholes.
* All new submissions must use the same language. Submissions from before this rule was made are fine, even if they don't.
## Scoring
Scoring works similarly for robbers, but it is slightly different:
* Cracking any program of ≤8 bytes gives 1 point.
* Cracking a ≤16 byte program gives 2 points. ≤32 bytes gives 4 points, and so on.
* Every additional submission, no matter the length, earns +5 points
* Each cop's submission can only be cracked once- only the first person to crack each submission gets the points.
# Submissions
Each answer must include
* A link to the cop's submission.
* Your program and programming language.
* Also have the cop's program length (as a power of 2) as the last number in your header.
Additionally, please comment on the cop's submission with a link to your answer.
Here is a Stack Snippet to generate leaderboards. Please leave a comment if there is a problem with the snippet. If you would like to see all open cop submissions, see the snippet in the cops' challenge.
```
/* Configuration */
var QUESTION_ID = 60329; // Obtain this from the url
// It will be like http://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
/* App */
var answers = [],
answers_hash, answer_ids, answer_page = 1,
more_answers = true,
comment_page;
function answersUrl(index) {
return "//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 "//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) {
answers_hash[c.post_id].comments.push(c);
});
if (data.has_more) getComments();
else if (more_answers) getAnswers();
else process();
}
});
}
getAnswers();
var POINTS_REG = /(?:<=|≤|<=)\s?(?:<\/?strong>)?\s?(\d+)/
var POINTS_REG_ALT = /<h\d>.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;
function getAuthorName(a) {
return a.owner.display_name;
}
function process() {
var valid = [];
var open = [];
answers.forEach(function(a) {
var body = a.body;
var cracked = false;
var points = body.match(POINTS_REG);
if (!points) points = body.match(POINTS_REG_ALT);
if (points) {
var length = parseInt(points[1]);
var crackedpoints = 0;
if (length > 64) crackedpoints = 16;
else if (length > 32) crackedpoints = 8;
else if (length > 16) crackedpoints = 4;
else if (length > 8) crackedpoints = 2;
else crackedpoints = 1;
valid.push({
user: getAuthorName(a),
numberOfSubmissions: 1,
points: crackedpoints
});
}
});
var pointTotals = [];
valid.forEach(function(a) {
var index = -1;
var author = a.user;
pointTotals.forEach(function(p) {
if (p.user == author) index = pointTotals.indexOf(p);
});
if (index == -1) pointTotals.push(a);
else {
pointTotals[index].points += a.points;
pointTotals[index].numberOfSubmissions++;
}
});
pointTotals.forEach(function(a) {
a.points += +((a.numberOfSubmissions - 1) * 5);
});
pointTotals.sort(function(a, b) {
var aB = a.points,
bB = b.points;
return (bB - aB != 0) ? bB - aB : b.numberOfSubmissions - a.numberOfSubmissions;
});
pointTotals.forEach(function(a) {
var answer = jQuery("#answer-template").html();
answer = answer
.replace("{{NAME}}", a.user)
.replace("{{SUBMISSIONS}}", a.numberOfSubmissions)
.replace("{{POINTS}}", a.points);
answer = jQuery(answer);
jQuery("#answers").append(answer);
});
}
```
```
body {
text-align: left !important
}
#answer-list {
padding: 20px;
width: 240px;
float: left;
}
#open-list {
padding: 20px;
width: 450px;
float: left;
}
table thead {
font-weight: bold;
vertical-align: top;
}
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>Robber's Leaderboard</h2>
<table class="answer-list">
<thead>
<tr>
<td>Author</td>
<td>Submissions</td>
<td>Score</td>
</tr>
</thead>
<tbody id="answers">
</tbody>
</table>
</div>
<table style="display: none">
<tbody id="answer-template">
<tr>
<td>{{NAME}}</td>
<td>{{SUBMISSIONS}}</td>
<td>{{POINTS}}</td>
</tr>
</tbody>
</table>
```
**This contest is now closed.**
**Overall winner: kennytm**
**Most submissions: Sp3000**
(Note that the amount of submissions doesn't translate exactly to the points, as the length of the cracked program is counted when calculating the score).
[Answer]
# [MATLAB, Tom Carpenter, ≤16](https://codegolf.stackexchange.com/a/60333/45151)
`v=ver;[v.Name]`
Thanks Martin for helping me out with this.
[Answer]
# [Fishing, Eridan, ≤ 32](https://codegolf.stackexchange.com/a/60394/3852)
```
v+CCCCCCCCCCC
`65617`nSSP
```
Calculates `(65617^2)^2`.
[Answer]
# [Octave, flawr, ≤4](https://codegolf.stackexchange.com/a/60408/32353)
```
i^-i
```
which is equal to *e**π*/2 ≈ 4.8105.
[Answer]
# [Groovy, quartata, ≤128](https://codegolf.stackexchange.com/a/60370/32353)
Only checked on ideone, I'm not sure if the output is the same on all platforms.
```
ClassLoader.systemClassLoader.packages.each{if(!(it.name=~/ls$/))println it.name[6..-1].reverse()}
```
The `it.name=~/ls$/` is to filter out the additional `org.codehaus.groovy.tools` package.
[Answer]
# [vim, Doorknob, 16](https://codegolf.stackexchange.com/a/60414/3852)
```
:redi@"|Ni!
pg?G
```
[Answer]
# [MATLAB, Tom Carpenter, ≤4](https://codegolf.stackexchange.com/a/60441/39328)
```
pi^i
```
It's not hard when the absolute value is 1.
[Answer]
## [Javascript, Ludovic Zenohate Lagoua, ≤64](https://codegolf.stackexchange.com/a/60511/45052)
```
var a="'";for(var b=11;b<2004;b+=4){a+=b;}a+="'";console.log(a);
```
[Answer]
# [Python 2.7.2, Beta Decay, ≤ 64](https://codegolf.stackexchange.com/a/60516/21487)
```
import math,re;print zip(dir(math),dir(re))
```
I had 2.7.10 installed, and the additional `__loader__` messed with the results, but this is probably it (I had to confirm with @BetaDecay in chat).
[Answer]
# [STATA, bmarks, ≤32 bytes](https://codegolf.stackexchange.com/a/60433/33208)
```
set ob 82
g a=_n*9/8
set ob 99
l
```
This uses the free interpreter.
[Answer]
# [Brainfuck, Daniel M., ≤ 64](https://codegolf.stackexchange.com/a/60545/21487)
```
++++++++++[->++++>++++++>++++++++>+<<<<]>.>>.<.>>++[-<++.>]
```
The code points are
```
[40, 80, 60, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100, 102, 104]
```
So we print the first three separately, then using the 80 to increment by 2 each time for the rest of the chars.
[Answer]
## [Python 2, <=8](https://codegolf.stackexchange.com/a/60563/11006), by [Clear question with examples](https://codegolf.stackexchange.com/users/45676/clear-question-with-examples)
```
947**687
```
Factorizing this number took no time at all :-)
[Answer]
# [Hassium](http://hassiumlang.com/) [(in REPL), <=32 bytes, by](https://codegolf.stackexchange.com/a/60515/19438) [Jacob Misirian](https://codegolf.stackexchange.com/users/45045/jacob-misirian)
```
for(i=0;i<99;i++)print(i%6==0)
```
Not too much fancy in this one.
[Answer]
# [AppleScript, VTCAKAVSMoACE, ≤32 bytes](https://codegolf.stackexchange.com/a/60566/11006)
```
repeat 409 times
log "(**)"
end
```
The `log` command actually adds comment markers `(*`...`*)` to everything it outputs to the Messages window of the script editor, but it looks like they have to be added explicitly when printing to stdout. Either way, the program is still less than 32 characters.
I'm using [Digital Trauma's trick](https://codegolf.stackexchange.com/a/37644/11006) of replacing `end repeat` with `end` to save a few bytes.
---
**EDIT:** As kennytm correctly pointed out, this outputs to stderr instead of stdout. As a workaround, I can suggest the following:
```
osascript -e 'repeat 409
log "(**)"
end' 2>&1
```
Including line breaks, the script inside the single quotes is 25 bytes, Add 5 bytes for `2>&1` at the end of the command line to redirect stderr to stdout, and it's still within the 32 byte limit.
[Answer]
# [Javascript, RononDex, ≤ 32 bytes](https://codegolf.stackexchange.com/a/60646/11006)
```
console.log(Math.log(42))
```
Very easy :-D
[Answer]
# [Thue, histocrat, ≤64](https://codegolf.stackexchange.com/a/60783/39328)
```
a::=yellowyellowyellowredyellowred
::=
aaaaaa
```
[Answer]
# [><>, Fongoid, ≤ 16](https://codegolf.stackexchange.com/a/60909/21487)
```
'$1-:0(?;$:o3+ !
```
That was some nice golfing practice.
[Answer]
# [AppleScript, VTCAKAVSMoACE, ≤ 2 Bytes](https://codegolf.stackexchange.com/a/60917/11006)
```
id
```
I have no idea why this produces the output `missing value`; I just wrote a bash script to test all pairs of printable ASCII characters. I also found that `it` and `me` result in the output `«script»`.
[Answer]
# [MATLAB, Tom Carpenter, ≤ 2](https://codegolf.stackexchange.com/a/61052)
```
!<
```
*Thanks to @AlexA. and @RetoKoradi for helping me test this. I don't have a Windows PC/VM...*
Googling the desired output immediately revealed it as a typical Windows Cmd error. In fact,
```
<
```
produces the desired output, and a MATLAB command that is prefixed by a `!` is a system command. I don't have MATLAB at hand to test this, but it should work.
[Answer]
# [><>, quartata, ≤ 32](https://codegolf.stackexchange.com/a/61081/21487)
```
1"qq"+\
v!?: <$*d$-1
>~n;
```
I'd like to thank @quartata for make this interesting - despite being such a long number, it's actually just `13^226`.
[Answer]
# [><>, Fongoid, ≤64 Bytes](https://codegolf.stackexchange.com/a/60915/42833)
```
"!":"~"=a$.1+:"!"(?;::1-$oo20.
"+"f8+0pa0.2-"-"c0p"3"f7+0p
```
A little bit hard-coded since I had room and I couldn't really think of a good way to go down once I got to `~` in the output (there probably is one and I probably just don't see it).
You can try it online [here](http://fishlanguage.com/playground).
[Answer]
# [Pip, DLosc, ≤ 2](https://codegolf.stackexchange.com/a/60739/32852)
```
O_
```
I don't really understand what the code does, but 2 characters is wide open to brute force cracking.
[Answer]
# [Wolfram programming language, Eridan, ≤32](https://codegolf.stackexchange.com/a/61107/9288)
```
ContinuedFraction[Zeta[3],36]
```
It's sequence [A013631](http://oeis.org/A013631) on OEIS.
[Answer]
# [AppleScript, VTCAKAVSMoACE, ≤64](https://codegolf.stackexchange.com/a/60898/32353)
```
osascript -e 'repeat with i from 688 to 195049 by 629
log i mod 1e3
end' 2>&1
```
Needs a redirect to stdout, similar to <https://codegolf.stackexchange.com/a/60601/32353>. Total size is 64.
[Answer]
# [Lua, jcgoble3, ≤ 128](https://codegolf.stackexchange.com/a/61145)
```
x=111111111
h="haha"
p=h..3*x..2*x..h..7*x..h..2*x
q="ha"..6*x..p..p..h..6*x..h..7*x..h..4*x..h..5*x
"ha"..(q..h):rep(11)..q
```
124 bytes. Tested in Lua 5.3.1 REPL.
This is a cleaner version that can be executed as a single command or even a full program:
```
x=111111111 h="haha" p=h..3*x..2*x..h..7*x..h..2*x q=h..6*x..p..p..h..6*x..h..7*x..h..4*x..h..5*x print((q.."ha"):rep(11)..q)
```
125 bytes. Tested in Lua 5.3.1 REPL and [ideone](http://ideone.com/uRlne7).
[Answer]
# [Pyth, ConfusedMr\_C, ≤ 32](https://codegolf.stackexchange.com/a/60757/29577)
```
sm*2s_c4s_Mcd2%2_c4sCM127
```
Only needed 25 chars. Took some while though.
Try it online: [Demonstration](http://pyth.herokuapp.com/?code=sm*2s_c4s_Mcd2%252_c4sCM127&debug=0)
The idea is to take all chars of the ranges 32-63 und 96-126 (Yes, 127 is not included), rearrange them, duplicate these strings and join them.
[Answer]
# [Self-modifying Brainfuck, mbomb007, ≤8](https://codegolf.stackexchange.com/a/60506/32353)
```
<[-.+<]
```
stdin needs to be /dev/null and disregard the output from stderr.
[Answer]
# [QBasic, DLosc, ≤16](https://codegolf.stackexchange.com/a/61449/3852)
```
?STRING$(3,34)
```
[Answer]
# [QBasic, DLosc, ≤8](https://codegolf.stackexchange.com/a/61448/3852)
```
?TAN(22)
```
Does the leading/trailing space thingy. I guess it's a QBasic quirk.
[Answer]
# [CJam, Eridan, ≤8](https://codegolf.stackexchange.com/a/61039/3852)
```
6C#E130#
```
I assumed it would be a list of numbers of the form *i^j*, so I did a search for those using substrings from output. I found that it was `str(6 ** 12) + str(14 ** 130)` using a Python script.
[Answer]
# [Python 3, ppperry, ≤32](https://codegolf.stackexchange.com/a/61653/32353)
```
0x1d4f620cb7a9ca2c585c639763613
```
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic).
Closed 7 years ago.
[Improve this question](/posts/60152/edit)
So, you're browsing Programming Puzzles & Code Golf, and you see a new challenge. The author (*gasp*) forgot to say "No standard Loopholes". You decide to take advantage of this situation, and you read the answer from a file/network. However, you need to make sure that your answer is actually shorter than the legitimate answers, so you golf it, too.
# The Challenge
Write a complete program that prints out the contents of the file `definitelynottheanswer.txt` to STDOUT. This text file only contains valid ASCII characters. Alternatively, the program can get the file location from STDIN or command line args. The only input allowed is the file location if you choose to get the location from the user; otherwise, no input is allowed. There is no reward for getting the file location from the user, but the user input of the file location does not count against the byte total (in other words, `definitelynottheanswer.txt` wouldn't be included in the byte score).
The program must not write to STDERR.
## Bonus
Retrieve the file from the internet *instead* of a file (the URL must be user-supplied). **Reward: multiply source length by 0.85**
# Scoring
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the lowest score,`program length (bytes) * bonus`, wins.
* No (other) standard loopholes.
* If the language does not support reading files from disk, it cannot be used (sorry).
[Answer]
# GNU sed, 0 bytes
Even better..
[Answer]
# Bash, 7 bytes \* .85 = 5.9 bytes
```
curl $1
```
zzz
[Answer]
# Pyth - 2 bytes \* .85 = 1.7
```
'z
```
Does not work online.
[Answer]
## Bash, 6 bytes
```
cat $1
```
Provide filename as a command line argument. Probably breaks if the argument contains spaces or newlines or weird chars or whatever.
[Answer]
# CJam, 1.7 bytes
```
qg
```
For security reasons, this does not work in the online interpreter.
] |
[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/60042/edit).
Closed 8 years ago.
[Improve this question](/posts/60042/edit)
# Intro
In `Objective-C` (a superset of `C` and an object-oriented language), I can create an object called a `UIWebView`. There is a method for this object called `loadHTMLString:` in which I can load actual `HTML` into the `UIWebView` object itself. I can also inject Javascript into it using the method `stringByEvaluatingJavaScriptFromString:`.
If I were to write a program that created a UIWebView, loaded in my string (which happens to be HTML "code") and then injected a second string (which is Javascript code) I would be using 3 languages at once, in a functional program. (Not sure that `html` is really a programming language... so that's debatable haha)
You can also do things like embed `Python` into `C` (and other languages): <https://docs.python.org/2/extending/embedding.html>
---
This isn't too difficult, with any language you can use other languages inside it if you try hard enough.
---
# Challenge
The challenge here is to see how many languages you can cram into 1 functioning program in under 500 bytes. <https://mothereff.in/byte-counter>
The program can do literally any task, it just has to work. The languages all have to work together, so you can't have 2 languages running one task, and 3 other languages running a completely different task. So whatever your "task" may be (you decide), there should only be 1 task, and all `n` languages should work on just that 1 task in your 1 program.
---
# Objective
Your score is the number of languages you used. Whoever uses the most languages at once gets a cookie.
Since this is a popularity contest I will be accepting the answer with the most up-votes.
---
# Q&A
•Ray **asked**, "Just to clarify, you're looking for a program that uses multiple languages to accomplish different parts of a single task, as opposed to a polyglot that is a valid program in multiple languages?"
***Answer**, "Yes".*
•DanielM. **asked**, "does Regex count?" ***Answer**, "Yes, I personally WOULD count it. Again, this is a popularity contest, so it really is up to the voters to determine. HTML is not considered a programming language by some, but it has been successfully used in an answer already that has seen quite a few upvotes. (Also, Stack-overflow does define Regex as a programming language if that helps you make your decision to use it or not: <https://stackoverflow.com/tags/regex/info>)*
[Answer]
# make, sh, awk, sed, regex, yacc, lex, C; 8 languages.
## Including the input and output languages: brainfuck and D; 10 languages
This is a brainfuck to D compiler. It takes the brainfuck program over standard input and prints the D code to standard output.
Make uses awk, sed, and sh to generate a yacc program, which in conjunction
with a lex program is used to generate a C program that takes a brainfuck
program as input and outputs an equivalent D program. I tried to only use languages in ways that were actually useful, instead of just throwing in a bunch of no-ops. The lex/yacc/C combination is fairly standard for simple compilers, the make/sh combination is useful for building, and the awk/sed line was the only way I could get the whole thing under 500 bytes. (It's at 498 bytes currently.)
## Code
```
define L
%%
[][+-<>.,] return *yytext;
. ;
%%
endef
define Y
%{
#include <stdio.h>
%}
%left '+' '-' '.' ',' '>' '<' '[' ']'
%%
q: q q {}
+ p[i]++
- p[i]--
> i++
< i--
, p[i]=getchar()
. putchar(p[i])
[ while(p[i]){
] }
%%
yywrap(){}yyerror(){}main(){puts("import std.stdio;int p[30000];int i;void main(){");yyparse();puts("}");}
endef
export L
export Y
a:
@echo "$$L">y;lex y;echo "$$Y"|awk '/^[+-^]/{printf("q: X%sX {puts(\"%s;\");}\n",$$1,$$2)} /^[^+-^]/'|sed "y/X/'/">y;yacc y;cc *.c;./a.out;:
```
## Example of use
```
$ cat helloworld.bf
++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.
$ make < helloworld.bf > tmp.d
y: warning: 8 shift/reduce conflicts [-Wconflicts-sr]
$ dmd tmp.d && ./tmp
Hello World!
```
[Answer]
# HTML, CSS, PHP, JavaScript, CoffeeScript, RegEx, sed, bash; 8 languages
Displays colors of the rainbow.
*(Only 396 bytes)* will try to add more languages
HTML + CSS is turning complete and counts as a valid language on PPCG. I've been [told](http://chat.stackexchange.com/transcript/message/24575556#24575556) CoffeeScript is different enough as JavaScript to be counted as a separate language. And RegEx has been specifically allowed also.
PHP allows for addition of many languages especially with `exec` and `shell_exec` functions.
Golfed to fit inside byte limit (ES6)
```
<html><style><?php foreach(explode(" ",exec('sed "s/;/ /g"<<<"red;orange;yellow;green;blue;violet"')) as $color){echo "#{$color} { color: $color }\n"}?></style><script>b="red orange yellow green blue violet".split(/ /).map(c=>`<p id="${c}">${c}</p>`)</script><script type="text/coffeescript">document.documentElement.innerHTML+=b.join "\n"</script><script src="http://v.ht/u31R"></script></html>
```
Uses:
* PHP to generate CSS
* PHP, uses exec to run bash
* sed to split color items for bash
* CSS to specify text colors
* JavaScript to generate elements
* RegEx to split color items for JS
* CoffeScript to print elements
* HTML as a wrapper / output
---
Faster & Ungolfed (All modern browsers)
```
<html>
<style>
/* CSS */
<?php// Loop through all colors
foreach(explode(" ",
exec('sed "s/;/ /g"<<<"red;orange;yellow;green;blue;violet"')) as $color) {
// Print it out, add it to the CSS
echo"#{$color} { color: $color }\n"}
?>
</style>
<script>
// Create an element for each color, store as variable
window.colors = "red orange yellow green blue violet".split(/ /).map(function(color) {
return "<p id=\"" + color + "\">" + color + "</p>"
});
</script>
<script type="text/coffeescript">
document.documentElement.innerHTML += window.colors.join "\n"
</script>
<!-- CoffeScript Link -->
<script src="https://raw.githubusercontent.com/jashkenas/coffeescript/master/extras/coffee-script.js"></script>
</html>
```
] |
[Question]
[
Your task is to create the shortest infinite loop!
The point of this challenge is to create an infinite loop producing no output, unlike its possible duplicate. The reason to this is because the code might be shorter if no output is given.
## Rules
* Each submission must be a full program.
* You must create the shortest infinite loop.
* Even if your program runs out of memory eventually, it is still accepted as long as it is running the whole time from the start to when it runs out of memory. Also when it runs out of memory, it should still not print anything to STDERR.
* The program must take no input (however, reading from a file is allowed), and should not print anything to STDOUT. Output to a file is also forbidden.
* The program must not write anything to STDERR.
* Feel free to use a language (or language version) even if it's newer than this challenge.
-Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language. **:D**
* Submissions are scored in bytes, in an appropriate (pre-existing) encoding, usually (but not necessarily) UTF-8. Some languages, like Folders, are a bit tricky to score - if in doubt, please ask on Meta.
* This is not about finding the language with the shortest infinite loop program. This is about finding the shortest infinite loop program in every language. Therefore, I will not accept an answer.
* If your language of choice is a trivial variant of another (potentially more popular) language which already has an answer (think BASIC or SQL dialects, Unix shells or trivial Brainf\*\*k-derivatives like Alphuck), consider adding a note to the existing answer that the same or a very similar solution is also the shortest in the other language.
* There should be a website such as Wikipedia, Esolangs, or GitHub for the language. For example, if the language is CJam, then one could link to the site in the header like `#[CJam](http://sourceforge.net/p/cjam/wiki/Home/), X bytes`.
* Standard loopholes are not allowed.
(I have taken some of these rules from Martin Büttner's "Hello World" challenge)
Please feel free to post in the comments to tell me how this challenge could be improved.
## Catalogue
This is a Stack Snippet which generates both an alphabetical catalogue of the used languages, and an overall leaderboard. To make sure your answer shows up, please start it with this Markdown header:
```
# Language name, X bytes
```
Obviously replacing `Language name` and `X bytes` with the proper items. If you want to link to the languages' website, use this template, as posted above:
```
#[Language name](http://link.to/the/language), X bytes
```
Now, finally, here's the snippet: (Try pressing "Full page" for a better view.)
```
var QUESTION_ID=59347;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk";var OVERRIDE_USER=41805;var answers=[],answers_hash,answer_ids,answer_page=1,more_answers=true,comment_page;function answersUrl(index){return"//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"//api.stackexchange.com/2.2/answers/"+answers.join(';')+"/comments?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(data){answers.push.apply(answers,data.items);answers_hash=[];answer_ids=[];data.items.forEach(function(a){a.comments=[];var id=+a.share_link.match(/\d+/);answer_ids.push(id);answers_hash[id]=a});if(!data.has_more)more_answers=false;comment_page=1;getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:true,success:function(data){data.items.forEach(function(c){if(c.owner.user_id===OVERRIDE_USER)answers_hash[c.post_id].comments.push(c)});if(data.has_more)getComments();else if(more_answers)getAnswers();else process()}})}getAnswers();var SCORE_REG=/<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;var OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(a){return a.owner.display_name}function process(){var valid=[];answers.forEach(function(a){var body=a.body;a.comments.forEach(function(c){if(OVERRIDE_REG.test(c.body))body='<h1>'+c.body.replace(OVERRIDE_REG,'')+'</h1>'});var match=body.match(SCORE_REG);if(match)valid.push({user:getAuthorName(a),size:+match[2],language:match[1],link:a.share_link,});else console.log(body)});valid.sort(function(a,b){var aB=a.size,bB=b.size;return aB-bB});var languages={};var place=1;var lastSize=null;var lastPlace=1;valid.forEach(function(a){if(a.size!=lastSize)lastPlace=place;lastSize=a.size;++place;var answer=jQuery("#answer-template").html();answer=answer.replace("{{PLACE}}",lastPlace+".").replace("{{NAME}}",a.user).replace("{{LANGUAGE}}",a.language).replace("{{SIZE}}",a.size).replace("{{LINK}}",a.link);answer=jQuery(answer);jQuery("#answers").append(answer);var lang=a.language;lang=jQuery('<a>'+lang+'</a>').text();languages[lang]=languages[lang]||{lang:a.language,lang_raw:lang,user:a.user,size:a.size,link:a.link}});var langs=[];for(var lang in languages)if(languages.hasOwnProperty(lang))langs.push(languages[lang]);langs.sort(function(a,b){if(a.lang_raw.toLowerCase()>b.lang_raw.toLowerCase())return 1;if(a.lang_raw.toLowerCase()<b.lang_raw.toLowerCase())return-1;return 0});for(var i=0;i<langs.length;++i){var language=jQuery("#language-template").html();var lang=langs[i];language=language.replace("{{LANGUAGE}}",lang.lang).replace("{{NAME}}",lang.user).replace("{{SIZE}}",lang.size).replace("{{LINK}}",lang.link);language=jQuery(language);jQuery("#languages").append(language)}}
```
```
body{text-align:left!important}#answer-list{padding:10px;width:500px;float:left}#language-list{padding:10px;padding-right:40px;width:500px;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="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]
# [Cubix](https://github.com/ETHproductions/cubix), 0 bytes
```
```
Alternatively, *any* single character does exactly the same.
**[Test it online!](https://ethproductions.github.io/cubix/?code=)**
Cubix is a stack-based 2D language, created by me in March 2016. Cubix differs from ordinary 2D languages in that it's not strictly 2D: the code is wrapped around a cube. Any one-byte program wraps to this cube net:
```
?
>. . . .
.
```
where `?` represents the character, and the IP (instruction pointer) starts at the arrow. `.` is simply a no-op, and when the IP reaches the right side of the cube net, it simply wraps back around to the left. Thus, any 1-byte program does nothing forever, no matter what the character is (as long as it's not whitespace).
Thanks to [@ErikGolferエリックゴルファー](https://codegolf.stackexchange.com/users/41024/erikgolfer%e3%82%a8%e3%83%aa%e3%83%83%e3%82%af%e3%82%b4%e3%83%ab%e3%83%95%e3%82%a1%e3%83%bc) for reminding me that the empty program does the same. When Cubix was originally created, this didn't work, because the interpreter created a cube of size 0 and threw an error when it tried to run. This was fixed a while ago, and it is now impossible to cause an error in Cubix.
[Answer]
# Java6 : 25 Bytes
In Java 6 and previous versions you can execute `static` initialization block without having `main` in your class file.
```
class A{static{for(;;);}}
```
[Answer]
# [Processing](https://processing.org/), 8 bytes
```
for(;;);
```
This is based on Geobit's answer in Java
Although the code below is not the shortest, it is one of Processing's specialties.
```
void draw(){}
```
This `draw` statement repeats itself over and over again. It is one of the differences between Processing and Java.
[Answer]
# [CJam](http://sourceforge.net/p/cjam/wiki/Home/), 4 bytes
```
1{}h
```
Put a 1 on the stack, and loop until 1 is no longer truthy. Using `h` means that the number is never popped.
[Answer]
# [Beam](http://esolangs.org/wiki/Beam), 2 bytes
There is a few ways of doing this from the very basic
```
><
```
to the very basic
```
>?
```
and
```
>|
```
[Answer]
# C++ 11 template metaprogramming, ~~58~~ 54 bytes
```
template<int>struct I{int v=I<1>{}.v;};int a=I<1>{}.v;
```
C++ helpfully comes packaged with 2 other turing complete languages: the C preprocessor, and template metaprogramming. Note that this does reach a max recursion depth at some point, but the OP clarified that this is okay.
[Example run](http://coliru.stacked-crooked.com/a/c8fd53d5c126112b):
>
>
> ```
> g++: internal compiler error: Segmentation fault (program cc1plus)
> Please submit a full bug report,
> with preprocessed source if appropriate.
> See <http://gcc.gnu.org/bugs.html> for instructions.
>
> ```
>
>
[Answer]
# COBOL, 51 bytes
```
ID DIVISION.PROGRAM-ID.A.PROCEDURE DIVISION.B.GO B.
```
[Answer]
# Rust, 17 bytes
Didn't see one in rust so:
```
fn main(){loop{}}
```
real original and interesting and so different from all the other entries.
[Answer]
# [Half-Broken Car in Heavy Traffic](http://metanohi.name/projects/hbcht/#heading1.2.3), ~~5~~ 4 bytes
```
^ov#
```
also in 4 bytes:
```
o
#
```
[Answer]
# [Binary Lambda Calculus](https://tromp.github.io/cl/cl.html), 3 bytes
Before I dive into the explanation, let's start with the program itself.
```
F†€
```
Trust me, it's pure luck that they're all printable, and I'll get to why it is 2 1/4 bytes instead of 3 after the explanation. I'll explain this by walking through the process I took to create this program.
To start, BLC programs are just lambda calculus programs encoded in a special way. With this in mind, let's begin with the lambda calculus program that enters an infinite loop, known as omega.
```
(λx.xx)(λx.xx)
```
This results in an infinite loop because, according to Wikipedia, it reduces to itself after a single beta-reduction. To convert this into BLC, we must first convert it to [De Bruijn indices](https://en.wikipedia.org/wiki/De_Bruijn_indices). It converts into the following:
```
.λ.11λ.11 (The dots after the λs are necessary for BLC but not part of De Bruijn indices)
```
Okay, now that it's in De Bruijin indices we can now convert it into BLC where `λ` translates to `00`, function application or `.` translates to `01`, and numbers are represented as `1^n0` where `n` is the number. Knowing this, it translates into the following binary:
```
01 00 01 10 10 00 01 10 10
```
This is why it's 2 1/4 bytes. As BLC instructions aren't full bytes (with the exception of 7), it is rare for programs to fit exactly into a certain byte count. To turn this into hex, we have to pad it in order to make it fit into 3 bytes. Doing this yields the following:
```
46 86 80
```
There we have the hex dump of our program! It runs in an infinite loop, doesn't run out of memory to my knowledge, doesn't output anything, and is a complete program that can be saved and run by piping the contents of the file to the official interpreter. You can also pipe the binary text to the interpreter and add the -b flag, to demonstrate that the non-padded version can be run.
[Answer]
# Commodore Basic, 3 bytes
```
1R╭
```
PETSCII substitution: `╭` = `SHIFT+U`, ungolfs to `1 RUN`.
Taking advantage of Commodore Basic's shortcut forms and the fact that any immediate-mode command can also be used in a program, this code simply runs itself, forever.
Alternatively, a more thoroughly infinite loop is the immediate-mode command
```
S|7
```
(PETSCII: `|` = `SHIFT+Y`, ungolfs to `SYS 7`).
This transfers execution to memory location 0x0007. The BASIC interpreter stores the current search character here; when running the above code, this character is the double-quotation mark with byte value 0x22. Opcode `0x22` is an [undocumented `HALT` opcode](http://www.pagetable.com/?p=39), which works by putting the 6510's micro-operation interpreter into an infinite loop. The only way out of this loop is to reset the computer.
[Answer]
# Tcl/Tk, 0 bytes
Execute any empty file with the `wish` interpreter instead of `tclsh`.
[Answer]
# TI-BASIC, 2 bytes
If recursion is allowed (is it a loop?)
```
prgmA
```
Runs a program named 'A', hence the program must be named the same. Some research revealed that `prgm` is 1 byte, plus 1 byte for `A`
Runs out of memory pretty quickly, but that doesn't seem to be addressed above.
[Answer]
# x86-16 Assembly, IBM PC DOS, 2 bytes
There's quite a few machine code answers, but thought I'd contribute a few different takes.
```
56 PUSH SI ; push 100H onto stack
C3 RET ; pop stack and jump to address (PUSH SI)
```
On DOS when a program is started the `SI` register contains the starting address of the program (generally `100H`). Push that onto the stack and execute a `RET` which will pop the stack and jump to that address. Big ol' loop.
---
### x86-16 Assembly, 1 byte
```
F4 HLT ; halt the processor and wait for signal
```
Okay, so this may depend a little on your definition of infinite loop. The `HLT` instruction (specifically in 8086 real mode) puts the processor in HALT state and awaits a signal in the form of `BINIT#`, `INIT#`, `RESET#` or interrupt ([ref](https://www.felixcloutier.com/x86/hlt)). While it's not technically executing our code, it is in a microcode loop of sorts waiting for one of those signals.
---
### Motorola 6800, 2 bytes
```
9D DD HCF ; halt and catch fire
```
From [Wikipedia](https://en.wikipedia.org/wiki/Halt_and_Catch_Fire#Motorola_6800):
>
> When this instruction is run the only way to see what it is doing is with an oscilloscope. From the user's point of view the machine halts and defies most attempts to get it restarted. Those persons with indicator lamps on the address bus will see that the processor begins to read all of the memory, sequentially, very quickly. In effect, the address bus turns into a 16 bit counter. However, the processor takes no notice of what it is reading… it just reads.
>
>
>
[Answer]
# MUMPS, 1 byte
```
f
```
This is the equivalent of `for ( ; ; ) ;` in C-like languages. It runs from the prompt as is, though, and does not need to be wrapped in a function declaration or any such thing.
[Answer]
# GNU dc, 6 bytes
```
[dx]dx
```
Tail recursion FTW, which GNU dc supports. Others might not.
[Answer]
# [MSM](http://esolangs.org/wiki/MSM), 2 bytes
```
ee
```
Almost all 2 character strings will work, even two spaces, just don't use any of the following 6 commands `:,/.?'`.
[Answer]
# Javascript (8 bytes)
```
for(;;);
```
Edit courtody of @KritixiLithos
# Javascript (10 bytes)
```
while(1){}
```
[Answer]
# Scheme, 12 bytes
A tail-recursive infinite loop seems most appropriate for scheme `:-)`
```
(let l()(l))
```
even though `(do(())())` (the CL variant of which is due to [@JoshuaTaylor](https://codegolf.stackexchange.com/questions/59347/shortest-infinite-loop-producing-no-output/59378#comment143074_59375)) would be 2 bytes shorter.
[Answer]
# z80 Machine Code, 1 byte
```
c7 ; RST 00h
```
Or if assuming the code starts at `0000h` is cheating, two bytes:
```
18 fe ; JR -2
```
These solutions make no assumptions about the rest of the environment's RAM. If it's filled with zero bytes, we are just spinning through `NOP`s forever, so we could have a 0-byte solution. (Thanks to Thomas Kwa for pointing this out.)
[Answer]
# Fortran, 11 bytes
It is not very creative, but here is the shortest I found:
```
1goto 1
end
```
I am pretty sure this is not standards compliant, but it compiles with `ifort`.
[Answer]
# [3var](http://esolangs.org/wiki/3var), 2 bytes
```
{}
```
To quote the docs:
```
{ Starts a loop which repeats forever
} Ends a loop which repeats forever
```
[Answer]
# [R](https://en.wikipedia.org/wiki/R_(programming_language)), 8 bytes
```
repeat{}
```
I believe this is the shortest way to make a loop that won't stop. We would need an infinite length list to use a for loop and `while(T)` is longer than `repeat`.
[Answer]
# NASM/YASM x86 assembly, 4 bytes
```
ja $
```
`$` is the address of the current instruction, and `ja` jumps there if the carry and zero flags are both unset. (i.e. the Above condition is true.) This is the case in x86-64 Linux at process startup.
`ja$` just defines a symbol, instead of being an instruction, so the space is not optional. I did test that this works without a trailing newline, so it really is 4 bytes.
Assemble/link with
```
$ yasm -felf64 foo.asm && ld -o foo foo.o
ld: warning: cannot find entry symbol _start; defaulting to 0000000000400080
```
The [x86-64 ABI](http://www.x86-64.org/documentation/abi.pdf) used by Linux doesn't guarantee anything about the state of registers at process startup, but Linux's actual implementation zeroes all the registers other than RSP for a newly-`exec`ed process. `EFLAGS=0x202 [ IF ]`, so `ja` (jump if Above) does jump, because the carry and zero flags aren't set. `jg` (ZF=0 and SF=0) would also work. Other OSes that initialize flags differently might be able to use one of the other one-letter conditions that require a flag bit to be set: `jz`, `jl`, `jc`, `jp`, `js`.
Using `ja` instead of `jmp` (unconditional jump) makes the source one byte shorter, but the binary is the same size (2 bytes: one opcode byte, one rel8 displacement, for a total size of 344 bytes for a stripped ELF64 binary. See [casey's answer](https://codegolf.stackexchange.com/a/59479/30206) for a 45 byte ELF executable if you're interested in small binary size rather than small source size.)
[Answer]
# AT&T (PDP-11) Syntax Assembly: 4 bytes
```
br .
```
# PDP-11 UNIX A.OUT binary output: ~~24~~ 18 bytes
```
0000000 000407 000002 000000 000000 000000 000000 000000 000000
0000020 000777 000000 000000 000004
0000030
```
This is the output produced by the assembler. As the sizes in the header show, the last three words are not necessary, it can be cut down to the first 18 bytes.
Some modern assemblers do not support the br instruction, so it would be **five bytes** for `jmp .`. And executable headers are generally much bigger these days.
# Linux x86-64 binary output, after strip: 336 bytes
Now, OSX's assembler is much more strict. You must have a symbol (by default `start`, but here I use `f`) for the entry point, which balloons the size of the source. It also requires a newline at the end of the file.
# Mac OS X x86-64 Assembly: 17 bytes
```
.globl f
f:jmp f
```
# Mac OS Mach-O Binary Output: 4200 bytes
[Answer]
# [pb](https://esolangs.org/wiki/Pb), 8 bytes
In pb, the shortest possible infinite loop is 8 bytes long. In fact, there are sixty 8 byte infinite loops, none of which produce output! (Unless you're running in watch mode, which is intended for debugging, no pb programs produce output until they halt. However, even if one of these did eventually halt, no output would have been produced.) Here are the sixty shortest infinite loops, in alphabetical order:
```
w[B!1]{}
w[B!2]{}
w[B!3]{}
w[B!4]{}
w[B!5]{}
w[B!6]{}
w[B!7]{}
w[B!8]{}
w[B!9]{}
w[B=0]{}
w[C!1]{}
w[C!2]{}
w[C!3]{}
w[C!4]{}
w[C!5]{}
w[C!6]{}
w[C!7]{}
w[C!8]{}
w[C!9]{}
w[C=0]{}
w[P!1]{}
w[P!2]{}
w[P!3]{}
w[P!4]{}
w[P!5]{}
w[P!6]{}
w[P!7]{}
w[P!8]{}
w[P!9]{}
w[P=0]{}
w[T!1]{}
w[T!2]{}
w[T!3]{}
w[T!4]{}
w[T!5]{}
w[T!6]{}
w[T!7]{}
w[T!8]{}
w[T!9]{}
w[T=0]{}
w[X!1]{}
w[X!2]{}
w[X!3]{}
w[X!4]{}
w[X!5]{}
w[X!6]{}
w[X!7]{}
w[X!8]{}
w[X!9]{}
w[X=0]{}
w[Y!1]{}
w[Y!2]{}
w[Y!3]{}
w[Y!4]{}
w[Y!5]{}
w[Y!6]{}
w[Y!7]{}
w[Y!8]{}
w[Y!9]{}
w[Y=0]{}
```
These all follow a simple pattern. `w` is a while loop, pb's only looping or branching instruction. Inside the square brackets is the condition, which is two expressions separated by `!` or `=`. To understand what this means, imagine an extra `=` just before the second expression. In the same way that you understand `2+2==4` to be true and `10!=5*2` to be false, `2+2=4` and `10!5*2` are true and false in pb. A while loop is executed until the condition becomes false. Finally, there is a pair of curly braces containing pb code. In this case, there's no code to be run, so they are empty.
The important thing here is the condition. pb has six variables, all for different purposes. They are:
```
B - The value of the character under the brush
C - The colour of the character under the brush (from a lookup table, the important thing being that white = 0)
P - The current colour that the brush is set to output in (same lookup table)
T - Set by the programmer, initialized to 0
X - X position of the brush
Y - Y position of the brush
```
The brush starts at (0, 0) on a canvas that is entirely initialized to white null bytes. This means that all of the variables start out being equal to 0.
These sixty programs fall into two categories: 10 loops that are executed until a variable (equivalent to 0) stops being zero, and 50 loops that are executed until a variable (equivalent to 0) becomes a specific non-zero number. An infinite number of programs can be written that fall into that second group, but only 50 are the same length as the 10 in the first one.
[Answer]
# ArnoldC, 61 bytes
```
IT'S SHOWTIME
STICK AROUND 1
CHILL
YOU HAVE BEEN TERMINATED
```
Ironic how the program never actually terminates, even though the last line says "YOU HAVE BEEN TERMINATED."
[Answer]
## [Brian & Chuck](https://github.com/mbuettner/brian-chuck), 7 bytes
```
#{?
#{?
```
The `#` could be replaced by any other characters except null-bytes or underscores.
The idea is fairly simple:
* Brian moves Chuck's instruction pointer to the start (`{`) and hands control
over to him (`?`).
* Chuck moves Brian's instruction pointer to the start (`{`) and hands control over to him (`?`).
* Repeat.
[Answer]
# [Seed](https://esolangs.org/wiki/Seed), 2 bytes
```
0
```
*(note the trailing space character)*
Any seed program consists out of 2 instructions, seperated by a space; The length of the [Befunge](https://esolangs.org/wiki/Befunge) program it will output and the seed which will generate that program.
Seeing how [we need a Befunge program of length 0](https://codegolf.stackexchange.com/a/59357/41257), we can create a Seed program with an empty 2nd instruction.
The Seed program `0` will output an empty Befunge program, which will run forever.
Interesting to note is that the Python compiler on the [Seed esolang page](https://esolangs.org/wiki/Seed) is erroneous.
To create a Befunge program of length 0, any seed will do. That includes an empty seed. To stick to the spec however, the space after `0` is not omitted.
That being said, this is the world's shortest Seed program, and also the easiest to reverse engineer :-)
[Answer]
# [Aubergine](http://esolangs.org/wiki/Aubergine), 6 bytes
```
:aa=ia
```
`:aa` is a no-op. `=ia` sets the IP to its own location.
] |
[Question]
[
Believe it or not, we do not yet have a code golf challenge for a simple [primality test](https://en.wikipedia.org/wiki/Primality_test). While it may not be the most interesting challenge, particularly for "usual" languages, it can be nontrivial in many languages.
Rosetta code features lists by language of idiomatic approaches to primality testing, one using the [Miller-Rabin test](http://rosettacode.org/wiki/Miller-Rabin_primality_test) specifically and another using [trial division](http://rosettacode.org/wiki/Primality_by_trial_division). However, "most idiomatic" often does not coincide with "shortest." In an effort to make Programming Puzzles and Code Golf the go-to site for code golf, this challenge seeks to compile a catalog of the shortest approach in every language, similar to ["Hello, World!"](https://codegolf.stackexchange.com/q/55422/20469) and [Golf you a quine for great good!](https://codegolf.stackexchange.com/q/69/20469).
Furthermore, the capability of implementing a primality test is part of [our definition of programming language](http://meta.codegolf.stackexchange.com/a/2073), so this challenge will also serve as a directory of proven programming languages.
### Task
Write a **full program** that, given a strictly positive integer **n** as input, determines whether **n** is prime and prints a [truthy or falsy value](http://meta.codegolf.stackexchange.com/a/2194) accordingly.
For the purpose of this challenge, an integer is prime if it has exactly two strictly positive divisors. Note that this excludes **1**, who is its only strictly positive divisor.
Your algorithm must be deterministic (i.e., produce the correct output with probability 1) and should, in theory, work for arbitrarily large integers. In practice, you may assume that the input can be stored in your data type, as long as the program works for integers from 1 to 255.
### Input
* If your language is able to read from STDIN, accept command-line arguments or any other alternative form of user input, you can read the integer as its decimal representation, unary representation (using a character of your choice), byte array (big or little endian) or single byte (if this is your languages largest data type).
* If (and only if) your language is unable to accept any kind of user input, you may hardcode the input in your program.
In this case, the hardcoded integer must be easily exchangeable. In particular, it may appear only in a single place in the entire program.
For scoring purposes, submit the program that corresponds to the input **1**.
### Output
Output has to be written to STDOUT or closest alternative.
If possible, output should consist solely of a [truthy or falsy value](http://meta.codegolf.stackexchange.com/a/2194) (or a string representation thereof), optionally followed by a single newline.
The only exception to this rule is constant output of your language's interpreter that cannot be suppressed, such as a greeting, ANSI color codes or indentation.
### Additional rules
* This is not about finding the language with the shortest approach for prime testing, this is about finding the shortest approach in every language. Therefore, no answer will be marked as accepted.
* Submissions in most languages will be scored in *bytes* in an appropriate preexisting encoding, usually (but not necessarily) UTF-8.
The language [Piet](http://www.dangermouse.net/esoteric/piet.html), for example, will be scored in codels, which is the natural choice for this language.
Some languages, like [Folders](http://esolangs.org/wiki/Folders), are a bit tricky to score. If in doubt, please ask on [Meta](http://meta.codegolf.stackexchange.com/).
* Unlike our usual rules, feel free to use a language (or language version) even if it's newer than this challenge. If anyone wants to abuse this by creating a language where the empty program performs a primality test, then congrats for paving the way for a very boring answer.
Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language.
* If your language of choice is a trivial variant of another (potentially more popular) language which already has an answer (think BASIC or SQL dialects, Unix shells or trivial Brainfuck derivatives like Headsecks or Unary), consider adding a note to the existing answer that the same or a very similar solution is also the shortest in the other language.
* Built-in functions for testing primality **are** allowed. This challenge is meant to catalog the shortest possible solution in each language, so if it's shorter to use a built-in in your language, go for it.
* Unless they have been overruled earlier, all standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply, including the <http://meta.codegolf.stackexchange.com/q/1061>.
As a side note, please don't downvote boring (but valid) answers in languages where there is not much to golf; these are still useful to this question as it tries to compile a catalog as complete as possible. However, do primarily upvote answers in languages where the author actually had to put effort into golfing the code.
### Catalog
The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
## Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
## Ruby, <s>104</s> <s>101</s> 96 bytes
```
If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:
```
## Perl, 43 + 2 (-p flag) = 45 bytes
```
You can also make the language name a link which will then show up in the snippet:
```
## [><>](http://esolangs.org/wiki/Fish), 121 bytes
```
```
<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = 57617; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 12012; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script>
```
[Answer]
# K, 29 bytes
```
(x>1)&&/x!'2_!1+_sqrt x:0$0:`
```
Got this off [Rosetta Code](http://rosettacode.org/wiki/Primality_by_trial_division#K), so marked it as community wiki.
[Answer]
# XPath 2.0, ~~45~~ 40 bytes
```
$i>1 and empty((2 to $i -1)[$i mod .=0])
```
For readability, incl. non-mandatory spaces (45 bytes)
```
$i > 1 and empty((2 to $i - 1)[$i mod . = 0])
```
In XPath, the only way to hand input like an integer to the processor is by passing it a parameter, in this case `$i`. This is hardly performant, and obvious improvement would be to use:
```
$i > 1 and empty((2 to math:sqrt($i) cast as xs:integer)[$i mod . = 0])
```
But since "shortest in any given language" and not performance was the goal, I'll leave the original in.
### How it works
For people new to XPath, it works as follows:
1. Create a sequence up to the current number:
```
(2 to $i - 1)
```
2. Filter all that have a modulo zero (i.e., that divide properly)
```
[$i mod . = 0]
```
3. Test if the resulting sequence is empty, if it non-empty, there is a divisor
```
empty(...)
```
4. Also test for special-case 1:
```
$i > 1
```
The query as a whole returns the string `true` (2, 5, 101, 5483) or `false` (1, 4, 5487).
As a nice consequence, you can find all divisors (not prime divisors!) using an even shorter expression:
```
(2 to $i - 1)[$i mod . = 0]
```
will return (3, 5, 7, 15, 21, 35) for input 105.
[Answer]
# XSLT 3.0, ~~209~~ ~~203~~ 201 bytes
```
<transform xmlns="http://www.w3.org/1999/XSL/Transform" xmlns:x="x" version="3.0"><function name="x:p" expand-text="1"><param name="i"/>{$i>1 and empty((2 to $i -1)[$i mod .=0])}</function></transform>
```
Update 1: removed spaces in `$i > 1`, `. = 0` and `$i - 1`.
Update 2: changed `expand-text="yes"` in `expand-text="1"`, which is a new XSLT 3.0 feature
In expanded form, with the usual prefixes:
```
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:x="x"
version="3.0">
<xsl:function name="x:p" expand-text="yes">
<xsl:param name="i"/>{
$i > 1 and empty((2 to $i - 1)[$i mod . = 0])
}</xsl:function>
</xsl:stylesheet>
```
This method uses the XSLT 3.0 feature to have a function as entry point (earlier versions did not support this). It uses the same XPath expression explained in my other post.
XSLT is notoriously verbose and starts with quite a few bytes declaring namespaces etc.
The function must be called with a typed value that derives from `xs:integer`. Most processor will consider that the default type if given an integer literal.
[Answer]
# SWI-Prolog, 51 bytes
```
a(X):-X>1,\+ (Y is X-1,between(2,Y,I),0=:=X mod I).
```
This uses predicate `between/3` which is not an ISO-Prolog predicate.
[Answer]
# JavaScript, 57
Prime finding regex.
```
alert(!/^1?$|^(11+?)\1+$/.test(Array(prompt()+1).join(1)))
```
[Answer]
# Python 3, 54 bytes
A just for fun post that abuses the `all` function.
```
y=int(input());print(all(y%p for p in range(2,y))|y>1)
```
Explanation:
Takes all the numbers from `2` to `y` and calculate the mod of `y` and that number and return false if any of those are `0`.
Edits:
Add the `1` check (+4 bytes)
Fix the check `1` logic (0 bytes)
Remove the `[]` (Thanks `FryAmTheEggman`!) (-2 bytes)
Remove the `-1` from `range` (Thanks `FryAmTheEggman`!) (-2 bytes)
[Answer]
# Python 2, 45 bytes
Not the smallest entry, but I took a slightly different approach to detecting the prime numbers. Maybe it inspires someone to create an even smaller version. I couldn't discover any more savings myself.
```
i=a=n=input()
while i>2:i-=1;a*=n%i
print a>1
```
[Answer]
## Scala, 50 bytes
```
val i=readInt
print(i>1&&(2 to i-1 forall(i%_>0)))
```
In case output to STDERR is forbidden, 65 bytes:
```
val i=scala.io.StdIn.readInt
print(i>1&&(2 to i-1 forall(i%_>0)))
```
[Answer]
# [Desmos](http://desmos.com/), ~~108~~ ~~104~~ 94 bytes
```
k=2
1\left\{\sum _{n=2}^k\operatorname{sign}\left(\operatorname{mod}\left(k,n\right)\right)+2=k,0\right\}
```
To use, enter a new line. Then, call `p\left(n\rgiht)`. The output will be bottom right on that line.
Edit 1: Shaved `{x-1}` to `x`.
Edit 2: Changed input format to a more STDIN-esque model.
[Answer]
# [Simplex v.0.5](http://conorobrien-foxx.github.io/Simplex/), 23 bytes
Can probably be golfed. It's really the square root declaration that hurts. \*regrets removing `p` (prime checking) command from syntax and sighs\*
```
i*R1UEY{&%n?[j1=o#]R@M}
i ~~ takes numeric input
* ~~ copies and increments pointer
R1UEY ~~ takes the square root and rounds it down
{ } ~~ repeats until zero cell met at end
& ~~ read and store the value to the register
% ~~ takes input mod current, move pointer left
n ~~ logically negates current (0 -> 1, 1 -> 0)
?[ ] ~~ evaluates inside if the current cell
j1= ~~ inserts a new cell to check for a 1 case
o# ~~ outputs the result and terminates program
R@ ~~ goes right, pulls the value from the register
M ~~ decrement value
```
[Answer]
# Groovy, 36 bytes
I found a variation of this in a course on groovy that I'm taking:
```
p={x->x==2||!(2..x-1).find{x%it==0}}
```
Test code:
```
println ((2..20).collect {"Is $it prime? ${p(it) ? 'Yes':'No'}"})
```
[Answer]
# PHP, 59 bytes
Credit goes to [Geobit's answer](https://codegolf.stackexchange.com/a/57625/46623). I basically just changed it from java to PHP.
```
function f($n){for($i=2;$i<$n;)$n=$n%$i++<1?:$n;echo $n>1;}
```
[Answer]
# AppleScript, 158 Bytes
Note that the special case for 1 adds a full *20 bytes*.
```
set x to(display dialog""default answer"")'s text returned's words as number
repeat with i from 2 to x/2
if x mod i=0 then return 0
end
if x=1 then return 0
1
```
If this program ever returns 0, it won't get to the final statement, which returns 1. Therefore, truthy is 1, falsey is 0.
[Answer]
# [Microscript II](http://esolangs.org/wiki/Microscript_II), 2 bytes
```
N;
```
Unlike the original Microscript, Microscript II provides a builtin for primality testing.
[Answer]
# Mathematica, ~~48~~ 47 bytes
```
<<PrimalityProving`
Echo@ProvablePrimeQ@Input[]
```
Saved 1 byte thanks to Martin Büttner. `Echo` is a new function in Mathematica 10.3. In older versions, use `Print`.
[Answer]
# C, 59 bytes
```
main(_,i){scanf("%d",&_);for(i=_;_%--i;);putchar(!--i+48);}
```
If anything other than 1 counted as "falsey", then this would be 3 bytes smaller:
```
main(_,i){scanf("%d",&_);for(i=_;_%--i;);putchar(i+48);}
```
Please tell me if the second one is valid.
[Answer]
# [Mouse-2002](https://github.com/catb0t/mouse15), 22 bytes
```
?x:x.1-&FACT &SQR x.\!
```
Uses Wilson's theorem:
```
?x: ~ get an integer input; put it in x
x.1- ~ put x-1 on the stack
&FACT ~ factorial it and push
&SQR ~ square it and push
x.\! ~ modulo (x-1)!^2 % x; print
```
The version that doesn't use a variable is eight bytes longer, but this is because Mouse's stack operations have four- and five-byte long names. :(
[Answer]
## [JavaScript function golf](http://schas002.github.io/js-function-golf/), ~~16~~ 13 bytes
```
p(pr(iai()));
```
function golf has just got a primality test function, that you can try online in the console on the language page! The primality test function took me [3 commits](https://github.com/schas002/js-function-golf/commits/gh-pages) on GitHub.
Returns 1 if prime, else 0.
The variant with the alert costs us 15 bytes.
```
p2a(pr(iai()));
```
And... the first ever explanation of a function golf program!
```
p(pr(iai()));
p( prints
pr( if
iai() an integer input into a prompt
) is prime
); into the console.
```
[Answer]
## [Pyke](https://github.com/muddyfish/PYKE), 2 bytes
```
_P
```
If the P function is given a negative number, it returns whether it's prime or not.
[Answer]
# Factor, 56 bytes
Literally ungolfable.
```
USING: math.primes conv io ;
readln string>number prime?
```
[Answer]
## Pyth, 2 bytes
```
P_
```
[Try it here!](http://pyth.herokuapp.com/?code=P_&input=7&debug=0)
Pyth now has implicit input!
[Answer]
# Molecule, 3 bytes
```
Inp
```
Explanation:
```
Inp
I read input
n convert to number
p primality test
```
[Answer]
## LiveCode 8, 708 bytes
```
on mouseUp
ask ""
put p(it) into field "a"
end mouseUp
function p n
if n is 1 then return false
repeat with i=2 to n-1
if n mod i is 0 then return false
end repeat
return true
end p
```
This code can be placed inside any button. It will print `true` or `false` to a field named `a`. It should work for small-ish integers, but will probably freeze/crash on anything too large. Byte count is size of saved LiveCode stack with one button and one field and with this code in the button.
[Answer]
# [Unipants' Golfing Language](https://github.com/schas002/Unipants-Golfing-Language), ~~53~~ 47 bytes
```
i$cu^d^-l_u^^/%cu%?%d%:_?coc$d$$:__^d^-:_u?cuo:
```
[Try it online!](http://schas002.github.io/Unipants-Golfing-Language/?code=aSQKY3UgIzYgMQpeZF4tbCAjd2hpbGUgbm90IGVxdWFsCl8gIzYgMQp1ICM2IDIKXl4vJSAjNiAyIDMgMApjdSU_JWQlOl8gIzYgMiAzICJ0cnVlIgo_Y29jJGQkJDogI3ByaW50IGZhbHNlOyByZXR1cm4gLTEKX18gI2Vsc2U6IDYgMgpeZF4tOl8gI3doaWxlIG5vdCBlcXVhbAp1PyAjaWYgc3RhY2sucG9wKCkgIT0gLTE6CmN1bzogI3ByaW50IHRydWU&input=NDM)
(It has been implemented as a standard example in the interpreter.)
[Answer]
# [Fith](https://github.com/nazek42/fith), 30 bytes
```
*math* load line >int prime? .
```
This language isn't great for golfing...
This uses the `prime?` function in the `*math*` library. Here's a version using only builtins, which is pretty much what the library function does:
```
line >int -> x 2 x range { x swap mod } map all .
```
Explanation:
```
line \ line of input
>int \ cast to int
-> x \ set x to the top of the stack
2 x \ push 2, then x
range \ range from [2, x)
{ x swap mod } \ anonymous function which calculates x mod its argument
map \ map that function onto the generated range
all \ return 1 if everything in the list is Boolean true, else 0
. \ print the top of the stack
```
You may be able to tell that this language is just a *little* bit inspired by Forth. It also takes cues from PostScript, Python, and functional programming.
[Answer]
## C, 54 bytes
```
i;main(j){for(scanf("%d",&i);i%++j;);putchar(49^j<i);}
```
* Must be run without parameters, so `j` is initialized to 1.
* Reads from standard input.
* Prints 1 for primes, 0 for composites (no newline).
* Could save 2 bytes with unprintable output - I'm not sure if `\x00` and `\x01` qualify as falsy/truthy.
[Answer]
# brainfuck, ~~208~~ 202 bytes
This is the code I wrote for [my Sesos answer](https://codegolf.stackexchange.com/a/86169/34718). See that answer for a detailed explanation.
This code assumes input fits in a single cell. Attempting to take input from an empty file must set the cell to zero. It works on an unbounded tape with no wrapping, including one that can go negative. It works for all positive numbers. Output will be a byte with a value of `0` or `1`.
```
[->+>+<<]++>[-<->]+<[>-<,]>[->+<]>[[->>>+<<<]>>>[->>>+<<<<<<+>>>]>>>-]<<<<<<+[<<<<<<]>>>>>>[-<+>]++[<[->>>+<<<]>>>[->>>+<<<<<<+>>>]>>>>][[->-[>+>>]>[+[-<+>]>+>>]<<<<<]<<<<<<]>>>>>>>>[>]>[<+>,]+<[>-<-]>.
```
[Answer]
## [RPN](https://github.com/ConceptJunkie/rpn), 16 bytes
```
lambda x isprime
```
This define a function checking the primality of it's argument.
Call like this:
```
<number> lambda x isprime eval
```
[Answer]
# [Nim](http://nim-lang.org), ~~70~~ 56 bytes
```
import os,math
let x=1.paramStr.len
echo fac(x-1)^2mod x
```
Uses [Wilson's theorem](http://en.wikipedia.org/wiki/Wilson's_theorem); that is, `x` is prime if `(x - 1)!² mod x` is 1.
Takes input in unary (any character) via the first command-line argument. Outputs 1 if the input is prime, and 0 otherwise. To test:
```
$ nim c prime.nim
$ ./prime 11111111
0
$ ./prime 1111111
1
$ ./prime 1
0
```
Note that according to the [Nim `os` docs](http://nim-lang.org/docs/os.html#paramStr,int), this solution will not work on POSIX as `paramStr` isn't available for some reason.
[Answer]
# PHP, ~~70~~ 65 bytes
```
for($i=2;$i<$n=$argv[1];$i++)if(is_int($n/$i)?1:0){echo 0;break;}
```
Empty output if the number is prime, print `0` if the number is not prime.
Not very original or best answer, but this is it...
[Test online](http://sandbox.onlinephpfunctions.com/code/16aede2248614de9af496bf9721655af46e3f413)
] |
[Question]
[
This is my first challenge, so I'm keeping it fairly simple.
If you've ever typed `telnet towel.blinkenlights.nl` on your command line and pressed enter, you will have experienced the joy of asciimation. Asciimation is, quite simply, doing an animation with ascii art. Today we will be doing a very basic asciimation of a person doing jumping jacks.
There will be two ascii pictures that we will put together into one asciimation.
Number 1:
```
_o_
0
/ \
```
Number 2:
```
\o/
_0_
<blank line>
```
Note that the second one has a blank line at the end.
So your program should do these steps:
1. Clear the console screen.
2. Print the correct ascii art image.
3. Set a flag or something so you know to do the other image next time.
4. Wait a moment (about a second).
5. Continue at 1.
# Rules
* Your program must be a (theoretically) infinite loop.
* The programming language you use must have been created before this challange was posted.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins.
* Standard loopholes apply.
Enjoy!
[Answer]
# CJam, ~~51~~ ~~45~~ ~~42~~ ~~38~~ 36 bytes
```
"c\o/
_0_""^[c_o_
0
/ \^["{_o\6e4m!}g
```
The above uses caret notation; the sequence `^[` is actually the ASCII character with code point 27.
I've borrowed the escape sequence (`^[c`) from [@DomHastings' answer](https://codegolf.stackexchange.com/a/57138) ([with his permission](https://codegolf.stackexchange.com/questions/57120/asciimation-jumping-jacks/57138?noredirect=1#comment137801_57138)) to save 4 bytes.
### Verification
You can recreate the file like this:
```
base64 -d > jj.cjam <<< ImNcby8KXzBfIiIbY19vXwogMAovIFwbIntfb1w2ZTRtIX1n
```
To run the code, download the [CJam interpreter](https://sourceforge.net/p/cjam/wiki/Home/) and execute this:
```
java -jar cjam-0.6.5.jar jj.cjam
```
This will work on any terminal that supports [console\_codes](http://man7.org/linux/man-pages/man4/console_codes.4.html) or an appropriate subset.1
### How it works
```
e# Push both jumping jacks on the stack.
"c\o/
_0_"
"^[c_o_
0
/ \^["
e# When chained together, they contain two occurrences of the string "\ec",
e# which resets the terminal. Encoding the ESC byte in the second string
e# eliminates the need two escape a backslash before the string terminator.
{ e# Do:
_o e# Copy the jumping jack on top of the stack and print the copy.
\ e# Swap the order of the jumping jacks.
6e4m! e# Calculate the factorial of 60,000 and discard the result.
e# This takes "about a second".
}g e# Since the discarded factorial was non-zero, repeat the loop.
```
---
1 The jumping jacks will look better if you hide the terminal's cursor before running the program. In Konsole, e.g., you can set the cursor's color to match the background color. This has to be done via your terminal's settings, since `^[c` resets the terminal.
[Answer]
# Pyth - ~~41~~ ~~40~~ 39 bytes
```
.VZ"\x1b[H\x1b[J"@c"_o_
0
/ \\\o/
_0_"Tb .p9
```
(I'm counting the `\x1b`'s as one byte since SO destroys special characters).
Clearly doesn't work online since its a) an infinite loop and b) uses terminal escape codes.
```
# Infinite loop
"..." Print escape sequences to clear screen
@ Modular indexing
c T Chop at index ten into the constituent frames
"..." Frames 1 & 2 concatenated (Pyth allows literal newlines in strings)
~ Post assign. This is an assign that returns the old value.
h Increment function. Putting it after an assign makes it augmented assign.
Z Variable auto-initialized to zero.
.p9 Permutations(range(9), 9). Takes about a second on my machine.
```
I was surprised to find out that augmented-assign worked with post-assign. Pyth is awesome.
[Answer]
# QBasic, ~~58~~ 54 bytes
Tested on [QB64](http://www.qb64.net) and at [Archive.org](https://archive.org/details/msdos_qbasic_megapack).
```
CLS
?"_o_
?0
?"/ \
SLEEP 1
CLS
?"\o/
?"_0_
SLEEP 1
RUN
```
The right language for the problem can be surprisingly competitive, even if it is usually verbose. The `?` shortcut for `PRINT` helps too, of course. `CLS` is **cl**ear **s**creen; `RUN` without arguments restarts the program, which is the shortest way to get an infinite loop.
The only other trick here is printing `0` for the midsection of the first picture. QBasic puts a space in front of (and after) nonnegative numeric values when it prints them, resulting in `0` . Saved 2 characters over `" 0`.
I may also point out that the delay in this code is *literally a second*, and is not machine-dependent. ;^P
[Answer]
# Perl *(\*nix)*, 54 bytes
```
sleep print"\x1bc",$-++%2?'\o/
_0_
':'_o_
0
/ \
'while 1
```
(`\x1b` is counted as 1 byte but escaped for easier testing.) The above has been tested with Bash and shortened by another byte thanks to [@Dennis](https://codegolf.stackexchange.com/users/12012/dennis)!
# Perl *(Windows)*, 56 bytes
```
sleep print"\x1b[2J",$-++%2?'\o/
_0_
':'_o_
0
/ \
'while 1
```
Thanks to [@Jarmex](https://codegolf.stackexchange.com/u/26977) for his testing and advice!
[Answer]
# Javascript (ES6), ~~109~~ ~~93~~ ~~79~~ 70 bytes + HTML, ~~12~~ 10 bytes = ~~120~~ ~~106~~ ~~91~~ 80 bytes
Fairly straightforward. Uses template strings to store the images, and toggles a boolean value to determine which to use.
**NOTE:** This solution may not be valid, as it does not actually use a console. However, I don't believe it's possible to clear a browser console using JS, at least not while using Firefox.
```
a=!1,setInterval(_=>O.innerHTML=(a=!a)?`_o_
0
/ \\`:`\\o/
_0_`,1e3)
```
```
<pre id=O>
```
[Answer]
# Bash, ~~86~~ 84 bytes
```
while sleep 1;do printf "\e[2J_o_\n 0\n/ \\";sleep 1;printf "\r\e[2J\o/\n_0_\n";done
```
[Answer]
# [Dash](https://wiki.debian.org/Shell), 67 bytes
Also `bash`, `ksh`, `zsh`, `ash`, `yash` and probably many more besides. While it apparently works in these other shells, their own features and idiosyncrasies may allow for further golfing. I'll leave that as an exercise for the reader.
Notably **not** `fish` or `tcsh`.
```
f(){ clear;echo "$1";sleep 1;f "$2" "$1";};f '_o_
0
/ \' '\o/
_0_'
```
[Try it online!](https://tio.run/##S0kszvj/P01Ds1ohOSc1scg6NTkjX0FJxVDJujgnNbVAwdA6Dcg1UoKI1QJ56vH58VwKBlz6CjHqCuox@fpc8Qbx6v//AwA "Dash – Try It Online") (with STDERR issue -- see **Caveats**)
[Try it online!](https://tio.run/##S0kszvifWlGQX1SiEOIa5GtbVmJoYPA/TUOzWiE5JzWxyDo1OSNfQUnFUMm6OCc1tUDB0DoNyDVSgojVAnnq8fnxXAoGXPoKMeoK6jH5@lzxBvHq//8DAA "Dash – Try It Online") (with visible escape codes issue -- see **Caveats**)
# How it works
Hopefully fairly self explanatory, even so:
Set up a function `f` which
* Clears screen
* Prints contents of `$1`
* Sleeps 1 second
* Calls `f` passing `$1` and `$2` in reverse order. This means the next iteration will display the "other" glyph before flipping them again... and so on.
Outside of the function is the initial call to `f` with literal depictions of the two character glyphs as two arguments.
# Caveats
TIO's terminal implementation doesn't handle the `clear` well -- produces an error to STDOUT. If you add `export TERM=vt100` as a header the error stops and it displays the literal escape string. This is a feature/limitation of TIO, not an issue with my submission. I've included links to both for reference.
Code should work as intended in a "proper" terminal.
The recursion will eventually cause it to fail. Tried a soak test with `sleep 0` in a Docker container and it threw a Segmentation Fault within a minute. Adding a trivial counter, which may or may not have quantum implications, it managed ~15000 iterations in my environment. So like 4 hours with the `sleep` -- and who's going to watch it **that** long? :-)
But I'd still argue that this complies with "theoretically" infinite, because it could go forever if it had "theoretically" infinite resources. That's my story and I'm sticking to it.
[Answer]
# Python 2, 99 bytes
Runs on Windows
```
import os,time
g=0
while 1:os.system("cls");print["\\o/\n_0_","_o_\n 0 \n/ \\"][g];time.sleep(1);g=~g
```
For UNIX machines, add two bytes:
```
import os,time
g=0
while 1:os.system("clear");print["\\o/\n_0_","_o_\n 0 \n/ \\"][g];time.sleep(1);g=~g
```
[Answer]
# awk - 95 92 86 84 83
```
END{
for(;++j;)
system("clear;printf '"(j%2?"_o_\n 0\n/ \\":"\\o/\n_0_")"';sleep 1")
}
```
Nice workout :D Just wondered if this was doable. No prices to gain though... ;)
If someone wants to test this: after you run the program you have to press Ctrl+D (end of input) to actually start the END block. To terminate it I have to use Ctrl+Z.
I also have this, which is only 74 bytes, but it starts with pausing a second which isn't the wanted behaviour I think
```
END{
for(;1;print++j%2?"_o_\n 0\n/ \\":"\\o/\n_0_")
system("sleep 1;clear")
}
```
[Answer]
# Batch - 82 bytes
Edit: Muted the timeout command and removed the extra newline.
```
cls&echo _o_&echo 0&echo / \&timeout>nul 1&cls&echo \o/&echo _0_&timeout>nul 1&%0
```
I've seen 2 other similar batch answers so I didn't really want to post this, but this is my first ever golf.
[Answer]
# BBC BASIC, 75 bytes
Note that tokenisation pulls it down to 75 bytes. The whitespace is added in by the IDE.
```
g=0
10 IFg=0THENPRINT"\o/":PRINT"_0_"ELSEPRINT"_o_":PRINT" 0 ":PRINT"/ \"
g=1-g:WAIT 100CLS:GOTO10
```
[![Properties showing program size](https://i.stack.imgur.com/UIoh2.jpg)](https://i.stack.imgur.com/UIoh2.jpg)
[Answer]
# JavaScript ES6, ~~100~~ 95 bytes
```
(f=_=>{console.log(_?`_o_
0
/ \\`:`\\o/
_0_`)
(b=setTimeout)(q=>(clear(),b(b=>f(!_))),1e3)})()
```
Logs to the console. Tested on Safari Nightly
[Answer]
# Batch, ~~151~~ ~~130~~ 118 bytes
```
cls
@echo _o_
@echo 0
@echo / \
@PING -n 2 127.0.0.1>NUL
cls
@echo \o/
@echo _0_
@PING -n 2 127.0.0.1>NUL
%0
```
[Answer]
# CBM 64 BASIC V2, ~~121~~ ~~119~~ ~~112~~ 117 bytes
```
2?CHR$(147)+"\o/":?" 0":?"/ \"
3GOSUB7
4?CHR$(147)+"_o_":?"_0_"
5GOSUB7
6RUN
7A=TI
8IFTI-A<60THENGOTO8
9RETURN
```
[Answer]
# Julia, 70 bytes
(on **Windows**, by replacing `clear` with `cls`, thanks to undergroundmonorail)
```
n(i=1)=(sleep(1);run(`cls`);print(i>0?"_o_
0
/ \\":"\\o/
_0_");n(-i))
```
### On Linux, 72 bytes
```
n(i=1)=(sleep(1);run(`clear`);print(i>0?"_o_
0
/ \\":"\\o/
_0_");n(-i))
```
This uses actual newlines rather than `\n` to save a byte; otherwise, the `i` is either 1 or -1 as the "flag", and it uses recursion to achieve the infinite loop. Call it as either `n(1)` or just `n()`.
Also, `run(`clear`)`/`run(`cls`)` uses a shell command to clear the window, because Julia doesn't have a built-in window-clear command.
[Answer]
# Windows Batch, 83 ~~89~~
**Edit** removed the empty line after the clarification by OP
```
@cls&echo _o_&echo 0&echo./ \&timeout>nul 1&cls&echo \o/&echo _0_&timeout>nul 1&%0
```
~~If you get rid of the empty line in the jumping man (that cannot be seen anyway), the score is 83~~
Note: `timeout` is not present in Windows XP. It works in Vista or newer versions. Moreover `timeout` is not precise to the second, so it's a perfect choice to implement step 4 (Wait a moment (*about a second*))
[Answer]
# Javascript (ES6), 82 bytes
A modification of my [previous answer](https://codegolf.stackexchange.com/a/57123/42545) that uses the console. Works partially in Firefox, but only clears the console in Chrome, AFAIK.
```
a=!0,c=console,setInterval(_=>c.log(c.clear(a=!a)|a?`_o_
0
/ \\`:`\\o/
_0_`),1e3)
```
As always, suggestions welcome!
[Answer]
# JavaScript, ~~92~~ ~~91~~ 89 bytes
```
x=0;setInterval(function(){console.log("\033c"+["_o_\n 0\n/ \\","\\o/\n_0_"][x^=1])},1e3)
```
* No ES6 features (but would be significantly shorter with them)
* Works with Node.js on Linux (don't know about other environments)
* Partially works in Chrome's console (`c` is shown instead of clearing the console, breaking the output)
Removing `"\033c"+` from the above code, the following works in the browser, but doesn't clear the console.
```
x=0;setInterval(function(){console.log(["_o_\n 0\n/ \\","\\o/\n_0_"][x^=1])},1e3)
```
[Answer]
# CBM BASIC v2.0 (68 characters)
```
0?"S_o_q||0q||N M":goS1:?"SMoN":?"_0_":goS1:gO
1wA161,255,pE(161):reT
```
The above requires some explanation, since Stack Exchange markup doesn't properly represent PETSCII characters:
* The program is shown here for convenience in lowercase, but can and should be entered and run in uppercase mode on a Commodore 64.
* The first and third "S" characters are actually in reverse video, and produced by pressing the `CLR` key (`SHIFT`+`HOME`).
* The "q" characters are actually in reverse video, and produced by pressing the down cursor (`CRSR ⇓`).
* The "|" characters are actually in reverse video, and produced by pressing the left cursor (`SHIFT`+`CRSR ⇒`).
[Answer]
# TI-Basic, ~~58~~ 56 bytes
```
While 1
ClrHome
If not(Ans
Disp "_o_"," 0","/ \
If Ans
Disp "\o/","_0_"
not(Ans
If dim(rand(70
End
```
-2 bytes for assuming that the code is run on a fresh interpreter.
[Answer]
## Ruby, 79 bytes
```
k=!0;loop{puts((k)?"\e[H\e[2J_o_\n 0\n/ \\":"\e[H\e[2J\\o/\n_0_");k=!k;sleep 1}
```
Requires escape codes.
[Answer]
# Forth, 86 bytes
Requires GNU Forth for the escaped strings. To run in a non-GNU Forth, just change `S\"` to `S"`, and the escaped characters won't print correctly.
```
: P PAGE TYPE CR 999 MS ;
: R BEGIN S\" \\o/\n_0_" P S\" _o_\n 0 \n/ \\" P 0 UNTIL ; R
```
[Answer]
# [beeswax](http://rosettacode.org/wiki/Category:Beeswax), ~~119~~ 113 bytes
```
ph0`J2[`}ghq'-<gh0N}`0`}gN`/o\`Ngh0`J`<
>g}`o`}N` `0>'d`0 `N`/ \`0hg>-'phg}`[2`b
dF1f+5~Zzf(.FP9f..F3_# d <
```
Explanation of the important parts of the program:
```
left to right right to left
3FBf or fBF3 27 ASCII code for (esc)
3 [x,x,3]• set lstack 1st to 3
F [3,3,3]• set lstack to 1st
B [3,3,27]• 1st=1st^2nd
f push lstack 1st on gstack
——————
9PF.(f or f(.FP9 102400 counter to roughly match a wait time
of 1 s on my i5 2410M Laptop
9 [x,x,9]• set lstack 1st to 9
P [x,x,10]• increment 1st
F [10,10,10]• set lstack to 1st
. [10,10,100]• 1st=1st*2nd
( [10,10,102400]• 1st=1st<<2nd (100<<10=102400, arithmetic shift left)
f push lstack 1st on gstack
——————
zZ~5+f or f+5~Zz 95 ASCII for '_'
z [0,0,0]• initialize lstack to zero
Z [0,0,90]• get value from relative coordinate (0,0),
which is the location of `Z` itself, ASCII(Z)=90
~ [0,90,0]• flip 1st and 2nd lstack values
5 [0,90,5]• set lstack 1st to 5
+ [0,90,95]• 1st = 1st+2nd
f push lstack 1st on gstack
```
The `f`’s push the values on the gstack (global stack) for later use. These values are accessed by the `0gh` (or the mirrored `hg0`) and `hg` (`gh`) instructions. `h` rotates the gstack upwards, `g` reads the top value of gstack and pushes it onto the lstack (local stack) of the bee (instruction pointer).
```
}`o`}N` 0 `N`/ \` sequence to print the standing man
N`\o/`Ng}`0`}N sequence to print the jumping man
}`[2J` equivalent to the ANSI escape sequence (esc)[2J
to clear the screen
>-'p or >-'q or > p loop for counting down (wait 1 s)
d < b < d'-<
```
In-depth explanation follows later, if needed. Maybe with animation.
[Answer]
# [Noodel](https://tkellehe.github.io/noodel/), noncompeting 24 bytes
Noncompeting because *Noodel* was born after the challenge was created:)
```
”ṛ|ọBCḊCBCḣ“\o/¶_0_ḷėçḍs
```
[Try it:)](https://tkellehe.github.io/noodel/editor.html?code=%E2%80%9D%E1%B9%9B%7C%E1%BB%8DBC%E1%B8%8ACBC%E1%B8%A3%E2%80%9C%5Co%2F%C2%B6_0_%E1%B8%B7%C4%97%C3%A7%E1%B8%8Ds&input=&run=true)
### How it works
```
”ṛ|ọBCḊCBCḣ # Creates a string that gets decompressed into "_o_¶¤0¤¶/¤\" and places it into the pipe.
“\o/¶_0_ # Creates a string and places it into the pipe.
ḷ # Unconditionally loop the code up to a new line or end of program.
ė # Takes what is in the front of the pipe and puts it into the back.
ç # Clears the screen and prints.
ḍs # Delays for one second.
```
---
There currently is not a version of *Noodel* that supports the syntax used in this challenge. Here is a version that does:
**24 bytes**
```
\o/¶_0_ _o_¶¤0¤¶/¤\ḷçėḍs
```
```
<div id="noodel" code="\o/¶_0_ _o_¶¤0¤¶/¤\ḷçėḍs" input="" cols="5" rows="5"></div>
<script src="https://tkellehe.github.io/noodel/noodel-latest.js"></script>
<script src="https://tkellehe.github.io/noodel/ppcg.min.js"></script>
```
[Answer]
# [Nim](http://nim-lang.org/), 107 bytes
```
import os,terminal
var f=0
while 0<1:eraseScreen();sleep 999;echo ["_o_\n 0 \n/ \\","\\o/\n_0_\n"][f];f=1-f
```
Don't [Try it online!](https://tio.run/##DcjBCsMgDADQe78ieNqgo/boXL9ix6aIlEgFTUos2@e7vePjXHvP9RS9QNp4kdbMsQyfqJAWO3yPXAjsa36SxkbvXYn4dvetEJ3gnPO0HwKrCRKQwQLyBIhmNIgyIQf7b7OtafNpmR@p9x8 "Nim – Try It Online")
] |
[Question]
[
You must evaluate a string written in [Reverse Polish notation](http://en.wikipedia.org/wiki/Reverse_Polish_notation) and output the result.
The program must accept an input and return the output. For programming languages that do not have functions to receive input/output, you can assume functions like readLine/print.
You are not allowed to use any kind of "eval" in the program.
Numbers and operators are separated by one **or more** spaces.
You must support at least the +, -, \* and / operators.
You need to add support to negative numbers (for example, `-4` is not the same thing as `0 4 -`) and floating point numbers.
**You can assume the input is valid and follows the rules above**
## Test Cases
Input:
```
-4 5 +
```
Output:
```
1
```
---
Input:
```
5 2 /
```
Output:
```
2.5
```
---
Input:
```
5 2.5 /
```
Output:
```
2
```
---
Input:
```
5 1 2 + 4 * 3 - +
```
Output:
```
14
```
---
Input:
```
4 2 5 * + 1 3 2 * + /
```
Output:
```
2
```
[Answer]
## Ruby - 95 77 characters
```
a=[]
gets.split.each{|b|a<<(b=~/\d/?b.to_f: (j,k=a.pop 2;j.send b,k))}
p a[0]
```
Takes input on stdin.
### Testing code
```
[
"-4 5 +",
"5 2 /",
"5 2.5 /",
"5 1 2 + 4 * 3 - +",
"4 2 5 * + 1 3 2 * + /",
"12 8 3 * 6 / - 2 + -20.5 "
].each do |test|
puts "[#{test}] gives #{`echo '#{test}' | ruby golf-polish.rb`}"
end
```
gives
```
[-4 5 +] gives 1.0
[5 2 /] gives 2.5
[5 2.5 /] gives 2.0
[5 1 2 + 4 * 3 - +] gives 14.0
[4 2 5 * + 1 3 2 * + /] gives 2.0
[12 8 3 * 6 / - 2 + -20.5 ] gives 10.0
```
Unlike the C version this returns the last valid result if there are extra numbers appended to the input it seems.
[Answer]
## Python - 124 chars
```
s=[1,1]
for i in raw_input().split():b,a=map(float,s[:2]);s[:2]=[[a+b],[a-b],[a*b],[a/b],[i,b,a]]["+-*/".find(i)]
print s[0]
```
**Python - 133 chars**
```
s=[1,1]
for i in raw_input().split():b,a=map(float,s[:2]);s={'+':[a+b],'-':[a-b],'*':[a*b],'/':[a/b]}.get(i,[i,b,a])+s[2:]
print s[0]
```
[Answer]
## Scheme, 162 chars
(Line breaks added for clarity—all are optional.)
```
(let l((s'()))(let((t(read)))(cond((number? t)(l`(,t,@s)))((assq t
`((+,+)(-,-)(*,*)(/,/)))=>(lambda(a)(l`(,((cadr a)(cadr s)(car s))
,@(cddr s)))))(else(car s)))))
```
Fully-formatted (ungolfed) version:
```
(let loop ((stack '()))
(let ((token (read)))
(cond ((number? token) (loop `(,token ,@stack)))
((assq token `((+ ,+) (- ,-) (* ,*) (/ ,/)))
=> (lambda (ass) (loop `(,((cadr ass) (cadr stack) (car stack))
,@(cddr stack)))))
(else (car stack)))))
```
---
**Selected commentary**
``(,foo ,@bar)` is the same as `(cons foo bar)` (i.e., it (effectively†) returns a new list with `foo` prepended to `bar`), except it's one character shorter if you compress all the spaces out.
Thus, you can read the iteration clauses as `(loop (cons token stack))` and `(loop (cons ((cadr ass) (cadr stack) (car stack)) (cddr stack)))` if that's easier on your eyes.
``((+ ,+) (- ,-) (* ,*) (/ ,/))` creates an association list with the *symbol* `+` paired with the *procedure* `+`, and likewise with the other operators. Thus it's a simple symbol lookup table (bare words are `(read)` in as symbols, which is why no further processing on `token` is necessary). Association lists have O(n) lookup, and thus are only suitable for short lists, as is the case here. :-P
† This is not technically accurate, but, for non-Lisp programmers, it gets a right-enough idea across.
[Answer]
# MATLAB – 158, 147
```
C=strsplit(input('','s'));D=str2double(C);q=[];for i=1:numel(D),if isnan(D(i)),f=str2func(C{i});q=[f(q(2),q(1)) q(3:end)];else q=[D(i) q];end,end,q
```
(input is read from user input, output printed out).
---
Below is the code prettified and commented, it pretty much implements the [postfix algorithm](https://en.wikipedia.org/wiki/Reverse_Polish_notation#Postfix_algorithm) described (with the assumption that expressions are valid):
```
C = strsplit(input('','s')); % prompt user for input and split string by spaces
D = str2double(C); % convert to numbers, non-numeric are set to NaN
q = []; % initialize stack (array)
for i=1:numel(D) % for each value
if isnan(D(i)) % if it is an operator
f = str2func(C{i}); % convert op to a function
q = [f(q(2),q(1)) q(3:end)]; % pop top two values, apply op and push result
else
q = [D(i) q]; % else push value on stack
end
end
q % show result
```
---
## Bonus:
In the code above, we assume operators are always binary (`+`, `-`, `*`, `/`). We can generalize it by using `nargin(f)` to determine the number of arguments the operand/function requires, and pop the right amount of values from the stack accordingly, as in:
```
f = str2func(C{i});
n = nargin(f);
args = num2cell(q(n:-1:1));
q = [f(args{:}) q(n+1:end)];
```
That way we can evaluate expressions like:
```
str = '6 5 1 2 mean_of_three 1 + 4 * +'
```
where `mean_of_three` is a user-defined function with three inputs:
```
function d = mean_of_three(a,b,c)
d = (a+b+c)/3;
end
```
[Answer]
## c -- 424 necessary character
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define O(X) g=o();g=o() X g;u(g);break;
char*p=NULL,*b;size_t a,n=0;float g,s[99];float o(){return s[--n];};
void u(float v){s[n++]=v;};int main(){getdelim(&p,&a,EOF,stdin);for(;;){
b=strsep(&p," \n\t");if(3>p-b){if(*b>='0'&&*b<='9')goto n;switch(*b){case 0:
case EOF:printf("%f\n",o());return 0;case'+':O(+)case'-':O(-)case'*':O(*)
case'/':O(/)}}else n:u(atof(b));}}
```
Assumes that you have a new enough libc to include `getdelim` in stdio.h. The approach is straight ahead, the whole input is read into a buffer, then we tokenize with `strsep` and use length and initial character to determine the class of each. There is no protection against bad input. Feed it "+ - \* / + - ...", and it will happily pop stuff off the memory "below" the stack until it seg faults. All non-operators are interpreted as floats by `atof` which means zero value if they don't look like numbers.
**Readable and commented:**
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *p=NULL,*b;
size_t a,n=0;
float g,s[99];
float o(){ /* pOp */
//printf("\tpoping '%f'\n",s[n-1]);
return s[--n];
};
void u(float v){ /* pUsh */
//printf("\tpushing '%f'\n",v);
s[n++]=v;
};
int main(){
getdelim(&p,&a,EOF,stdin); /* get all the input */
for(;;){
b=strsep(&p," \n\t"); /* now *b though *(p-1) is a token and p
points at the rest of the input */
if(3>p-b){
if (*b>='0'&&*b<='9') goto n;
//printf("Got 1 char token '%c'\n",*b);
switch (*b) {
case 0:
case EOF: printf("%f\n",o()); return 0;
case '+': g=o(); g=o()+g; u(g); break;
case '-': g=o(); g=o()-g; u(g); break;
case '*': g=o(); g=o()*g; u(g); break;
case '/': g=o(); g=o()/g; u(g); break;
/* all other cases viciously ignored */
}
} else { n:
//printf("Got token '%s' (%f)\n",b,atof(b));
u(atof(b));
}
}
}
```
**Validation:**
```
$ gcc -c99 rpn_golf.c
$ wc rpn_golf.c
9 34 433 rpn_golf.c
$ echo -4 5 + | ./a.out
1.000000
$ echo 5 2 / | ./a.out
2.500000
$ echo 5 2.5 / | ./a.out
2.000000
```
Heh! Gotta quote anything with `*` in it...
```
$ echo "5 1 2 + 4 * 3 - +" | ./a.out
14.000000
$ echo "4 2 5 * + 1 3 2 * + /" | ./a.out
2.000000
```
and my own test case
```
$ echo "12 8 3 * 6 / - 2 + -20.5 " | ./a.out
-20.500000
```
[Answer]
## Haskell (155)
```
f#(a:b:c)=b`f`a:c
(s:_)![]=print s
s!("+":v)=(+)#s!v
s!("-":v)=(-)#s!v
s!("*":v)=(*)#s!v
s!("/":v)=(/)#s!v
s!(n:v)=(read n:s)!v
main=getLine>>=([]!).words
```
[Answer]
## Perl (134)
```
@a=split/\s/,<>;/\d/?push@s,$_:($x=pop@s,$y=pop@s,push@s,('+'eq$_?$x+$y:'-'eq$_?$y-$x:'*'eq$_?$x*$y:'/'eq$_?$y/$x:0))for@a;print pop@s
```
Next time, I'm going to use the recursive regexp thing.
Ungolfed:
```
@a = split /\s/, <>;
for (@a) {
/\d/
? (push @s, $_)
: ( $x = pop @s,
$y = pop @s,
push @s , ( '+' eq $_ ? $x + $y
: '-' eq $_ ? $y - $x
: '*' eq $_ ? $x * $y
: '/' eq $_ ? $y / $x
: 0 )
)
}
print(pop @s);
```
I though F# is my only dream programming language...
[Answer]
### Windows PowerShell, 152 ~~181~~ ~~192~~
In readable form, because by now it's only two lines with no chance of breaking them up:
```
$s=@()
switch -r(-split$input){
'\+' {$s[1]+=$s[0]}
'-' {$s[1]-=$s[0]}
'\*' {$s[1]*=$s[0]}
'/' {$s[1]/=$s[0]}
'-?[\d.]+' {$s=0,+$_+$s}
'.' {$s=$s[1..($s.count)]}}
$s
```
**2010-01-30 11:07** (192) – First attempt.
**2010-01-30 11:09** (170) – Turning the function into a scriptblock solves the scope issues. Just makes each invocation two bytes longer.
**2010-01-30 11:19** (188) – Didn't solve the scope issue, the test case just masked it. Removed the index from the final output and removed a superfluous line break, though. And changed double to `float`.
**2010-01-30 11:19** (181) – Can't even remember my own advice. Casting to a numeric type can be done in a single char.
**2010-01-30 11:39** (152) – Greatly reduced by using regex matching in the `switch`. Completely solves the previous scope issues with accessing the stack to pop it.
[Answer]
**[Racket](http://racket-lang.org) 131:**
```
(let l((s 0))(define t(read))(cond[(real? t)
(l`(,t,@s))][(memq t'(+ - * /))(l`(,((eval t)(cadr s)
(car s)),@(cddr s)))][0(car s)]))
```
Line breaks optional.
Based on Chris Jester-Young's solution for Scheme.
[Answer]
## Python, 166 characters
```
import os,operator as o
S=[]
for i in os.read(0,99).split():
try:S=[float(i)]+S
except:S=[{'+':o.add,'-':o.sub,'/':o.div,'*':o.mul}[i](S[1],S[0])]+S[2:]
print S[0]
```
[Answer]
# Python 3, 119 bytes
```
s=[]
for x in input().split():
try:s+=float(x),
except:o='-*+'.find(x);*s,a,b=s;s+=(a+b*~-o,a*b**o)[o%2],
print(s[0])
```
Input: `5 1 1 - -7 0 * + - 2 /`
Output: `2.5`
(You can find a 128-character Python 2 version in the edit history.)
[Answer]
# JavaScript (157)
This code assumes there are these two functions: readLine and print
```
a=readLine().split(/ +/g);s=[];for(i in a){v=a[i];if(isNaN(+v)){f=s.pop();p=s.pop();s.push([p+f,p-f,p*f,p/f]['+-*/'.indexOf(v)])}else{s.push(+v)}}print(s[0])
```
[Answer]
## Perl, 128
This isn't really competitive next to the other Perl answer, but explores a different (suboptimal) path.
```
perl -plE '@_=split" ";$_=$_[$i],/\d||
do{($a,$b)=splice@_,$i-=2,2;$_[$i--]=
"+"eq$_?$a+$b:"-"eq$_?$a-$b:"*"eq$_?
$a*$b:$a/$b;}while++$i<@_'
```
Characters counted as diff to a simple `perl -e ''` invocation.
[Answer]
# flex - 157
```
%{
float b[100],*s=b;
#define O(o) s--;*(s-1)=*(s-1)o*s;
%}
%%
-?[0-9.]+ *s++=strtof(yytext,0);
\+ O(+)
- O(-)
\* O(*)
\/ O(/)
\n printf("%g\n",*--s);
.
%%
```
If you aren't familiar, compile with `flex rpn.l && gcc -lfl lex.yy.c`
[Answer]
Python, 161 characters:
```
from operator import*;s=[];i=raw_input().split(' ')
q="*+-/";o=[mul,add,0,sub,0,div]
for c in i:
if c in q:s=[o[ord(c)-42](*s[1::-1])]+s
else:s=[float(c)]+s
print(s[0])
```
[Answer]
## PHP, ~~439~~ ~~265~~ ~~263~~ ~~262~~ ~~244~~ 240 characters
```
<? $c=fgets(STDIN);$a=array_values(array_filter(explode(" ",$c)));$s[]=0;foreach($a as$b){if(floatval($b)){$s[]=$b;continue;}$d=array_pop($s);$e=array_pop($s);$s[]=$b=="+"?$e+$d:($b=="-"?$e-$d:($b=="*"?$e*$d:($b=="/"?$e/$d:"")));}echo$s[1];
```
This code should work with stdin, though it is not tested with stdin.
It has been tested on all of the cases, the output (and code) for the last one is here:
<http://codepad.viper-7.com/fGbnv6>
**Ungolfed, ~~314~~ ~~330~~ 326 characters**
```
<?php
$c = fgets(STDIN);
$a = array_values(array_filter(explode(" ", $c)));
$s[] = 0;
foreach($a as $b){
if(floatval($b)){
$s[] = $b;
continue;
}
$d = array_pop($s);
$e = array_pop($s);
$s[] = $b == "+" ? $e + $d : ($b == "-" ? $e - $d : ($b == "*" ? $e * $d : ($b == "/" ? $e / $d :"")));
}
echo $s[1];
```
[Answer]
## Python, 130 characters
Would be 124 characters if we dropped `b and` (which some of the Python answers are missing). And it incorporates 42!
```
s=[]
for x in raw_input().split():
try:s=[float(x)]+s
except:b,a=s[:2];s[:2]=[[a*b,a+b,0,a-b,0,b and a/b][ord(x)-42]]
print s[0]
```
[Answer]
# Python 3, ~~126~~ 132 chars
```
s=[2,2]
for c in input().split():
a,b=s[:2]
try:s[:2]=[[a+b,b-a,a*b,a and b/a]["+-*/".index(c)]]
except:s=[float(c)]+s
print(s[0])
```
There have been better solutions already, but now that I had written it (without having read the prior submissions, of course - even though I have to admit that my code looks as if I had copypasted them together), I wanted to share it, too.
[Answer]
# C, 232 229 bytes
Fun with recursion.
```
#include <stdlib.h>
#define b *p>47|*(p+1)>47
char*p;float a(float m){float n=strtof(p,&p);b?n=a(n):0;for(;*++p==32;);m=*p%43?*p%45?*p%42?m/n:m*n:m-n:m+n;return*++p&&b?a(m):m;}main(c,v)char**v;{printf("%f\n",a(strtof(v[1],&p)));}
```
## Ungolfed:
```
#include <stdlib.h>
/* Detect if next char in buffer is a number */
#define b *p > 47 | *(p+1) > 47
char*p; /* the buffer */
float a(float m)
{
float n = strtof(p, &p); /* parse the next number */
/* if the next thing is another number, recursively evaluate */
b ? n = a(n) : 0;
for(;*++p==32;); /* skip spaces */
/* Perform the arithmetic operation */
m = *p%'+' ? *p%'-' ? *p%'*' ? m/n : m*n : m-n : m+n;
/* If there's more stuff, recursively parse that, otherwise return the current computed value */
return *++p && b ? a(m) : m;
}
int main(int c, char **v)
{
printf("%f\n", a(strtof(v[1], &p)));
}
```
## Test Cases:
```
$ ./a.out "-4 5 +"
1.000000
$ ./a.out "5 2 /"
2.500000
$ ./a.out "5 2.5 /"
2.000000
$ ./a.out "5 1 2 + 4 * 3 - +"
14.000000
$ ./a.out "4 2 5 * + 1 3 2 * + /"
2.000000
```
[Answer]
# JavaScript ES7, 119 bytes
I'm getting a bug with array comprehensions so I've used `.map`
```
(s,t=[])=>(s.split` `.map(i=>+i?t.unshift(+i):t.unshift((r=t.pop(),o=t.pop(),[r+o,r-o,r*o,r/o]['+-*/'.indexOf(i)]))),t)
```
[Try it online at ESFiddle](http://server.vihan.ml/p/esfiddle/?code=f%3D(s%2Ct%3D%5B%5D)%3D%3E(s.split%60%20%60.map(i%3D%3E%2Bi%3Ft.unshift(%2Bi)%3At.unshift((r%3Dt.pop()%2Co%3Dt.pop()%2C%5Br%2Bo%2Cr-o%2Cr*o%2Cr%2Fo%5D%5B'%2B-*%2F'.indexOf(i)%5D)))%2Ct)%3B%0A%0Af(%2211%203%20%2B%22))
[Answer]
# C 153
Sometimes a program can be made a bit shorter with more golfing and sometimes you just take completely the wrong route and the much better version is found by someone else.
**Thanks to @ceilingcat for finding a much better (and shorter) version**
```
double atof(),s[99],*p=s;y,z;main(c,v)char**v;{for(;--c;*p=z?z-2?~z?z-4?p+=2,atof(*v):*p/y:*p*y:*p-y:*p+y)z=1[*++v]?9:**v-43,y=*p--;printf("%f\n",s[1]);}
```
[Try it online!](https://tio.run/##HY7RCoIwGIVfJYRg@7chml3oGHsQ88JWK6F0qA1m1Kv/bd1858A5HI4RN2MQL9Pr/Lju@nWyhPKlreuOg1OLDHyTz34YieGemns/A3j5ttNMpBBGxs6mN1Hqb5JKO6ZK/l8BTxtweYiABJHAAt1U0QJjvtN1E7dEdeBBxVhINw/jakm2t6cxix@KjsoPIlZY4hEBGRZ4iD65/Ac "C (gcc) – Try It Online")
My original version:
```
#include <stdlib.h>
#define O(x):--d;s[d]=s[d]x s[d+1];break;
float s[99];main(c,v)char**v;{for(int i=1,d=0;i<c;i++)switch(!v[i][1]?*v[i]:' '){case'+'O(+)case'-'O(-)case'*'O(*)case'/'O(/)default:s[++d]=atof(v[i]);}printf("%f\n",s[1]);}
```
If you are compiling it with mingw32 you need to turn off globbing (see <https://www.cygwin.com/ml/cygwin/1999-11/msg00052.html>) by compiling like this:
```
gcc -std=c99 x.c C:\Applications\mingw32\i686-w64-mingw32\lib\CRT_noglob.o
```
If you don't \* is automatically expanded by the mingw32 CRT into filenames.
[Answer]
## PHP - 259 characters
```
$n=explode(" ",$_POST["i"]);$s=array();for($i=0;$i<count($n);$s=$d-->0?array_merge($s,!$p?array($b,$a,$c):array($p)):$s){if($c=$n[$i++]){$d=1;$a=array_pop($s);$b=array_pop($s);$p=$c=="+"?$b+$a:($c=="-"?$b-$a:($c=="*"?$b*$a:($c=="/"?$b/$a:false)));}}echo$s[2];
```
Assuming input in POST variable *i*.
[Answer]
## C# - 392 characters
```
namespace System.Collections.Generic{class P{static void Main(){var i=Console.ReadLine().Split(' ');var k=new Stack<float>();float o;foreach(var s in i)switch (s){case "+":k.Push(k.Pop()+k.Pop());break;case "-":o=k.Pop();k.Push(k.Pop()-o);break;case "*":k.Push(k.Pop()*k.Pop());break;case "/":o=k.Pop();k.Push(k.Pop()/o);break;default:k.Push(float.Parse(s));break;}Console.Write(k.Pop());}}}
```
However, if arguments can be used instead of standard input, we can bring it down to
## C# - 366 characters
```
namespace System.Collections.Generic{class P{static void Main(string[] i){var k=new Stack<float>();float o;foreach(var s in i)switch (s){case "+":k.Push(k.Pop()+k.Pop());break;case "-":o=k.Pop();k.Push(k.Pop()-o);break;case "*":k.Push(k.Pop()*k.Pop());break;case "/":o=k.Pop();k.Push(k.Pop()/o);break;default:k.Push(float.Parse(s));break;}Console.Write(k.Pop());}}}
```
[Answer]
### Scala 412 376 349 335 312:
```
object P extends App{
def p(t:List[String],u:List[Double]):Double={
def a=u drop 2
t match{
case Nil=>u.head
case x::y=>x match{
case"+"=>p(y,u(1)+u(0)::a)
case"-"=>p(y,u(1)-u(0)::a)
case"*"=>p(y,u(1)*u(0)::a)
case"/"=>p(y,u(1)/u(0)::a)
case d=>p(y,d.toDouble::u)}}}
println(p((readLine()split " ").toList,Nil))}
```
[Answer]
# Python - 206
```
import sys;i=sys.argv[1].split();s=[];a=s.append;b=s.pop
for t in i:
if t=="+":a(b()+b())
elif t=="-":m=b();a(b()-m)
elif t=="*":a(b()*b())
elif t=="/":m=b();a(b()/m)
else:a(float(t))
print(b())
```
Ungolfed version:
```
# RPN
import sys
input = sys.argv[1].split()
stack = []
# Eval postfix notation
for tkn in input:
if tkn == "+":
stack.append(stack.pop() + stack.pop())
elif tkn == "-":
tmp = stack.pop()
stack.append(stack.pop() - tmp)
elif tkn == "*":
stack.append(stack.pop() * stack.pop())
elif tkn == "/":
tmp = stack.pop()
stack.append(stack.pop()/tmp)
else:
stack.append(float(tkn))
print(stack.pop())
```
Input from command-line argument; output on standard output.
[Answer]
# ECMAScript 6 (131)
Just typed together in a few seconds, so it can probably be golfed further or maybe even approached better. I might revisit it tomorrow:
```
f=s=>(p=[],s.split(/\s+/).forEach(t=>+t==t?p.push(t):(b=+p.pop(),a=+p.pop(),p.push(t=='+'?a+b:t=='-'?a-b:t=='*'?a*b:a/b))),p.pop())
```
[Answer]
## C# - 323 284 241
```
class P{static void Main(string[] i){int x=0;var a=new float[i.Length];foreach(var s in i){var o="+-*/".IndexOf(s);if(o>-1){float y=a[--x],z=a[--x];a[x++]=o>3?z/y:o>2?z*y:o>1?z-y:y+z;}else a[x++]=float.Parse(s);}System.Console.Write(a[0]);}}
```
Edit: Replacing the Stack with an Array is way shorter
Edit2: Replaced the ifs with a ternary expression
[Answer]
# Python 2
I've tried out some different approaches to the ones published so far. None of these is quite as short as the best Python solutions, but they might still be interesting to some of you.
## Using recursion, 146
```
def f(s):
try:x=s.pop();r=float(x)
except:b,s=f(s);a,s=f(s);r=[a+b,a-b,a*b,b and a/b]['+-*'.find(x)]
return r,s
print f(raw_input().split())[0]
```
## Using list manipulation, 149
```
s=raw_input().split()
i=0
while s[1:]:
o='+-*/'.find(s[i])
if~o:i-=2;a,b=map(float,s[i:i+2]);s[i:i+3]=[[a+b,a-b,a*b,b and a/b][o]]
i+=1
print s[0]
```
## Using `reduce()`, 145
```
print reduce(lambda s,x:x in'+-*/'and[(lambda b,a:[a+b,a-b,a*b,b and a/b])(*s[:2])['+-*'.find(x)]]+s[2:]or[float(x)]+s,raw_input().split(),[])[0]
```
[Answer]
## Matlab, 228
```
F='+-/*';f={@plus,@minus,@rdivide,@times};t=strsplit(input('','s'),' ');i=str2double(t);j=~isnan(i);t(j)=num2cell(i(j));while numel(t)>1
n=find(cellfun(@(x)isstr(x),t),1);t{n}=bsxfun(f{t{n}==F},t{n-2:n-1});t(n-2:n-1)=[];end
t{1}
```
Ungolfed:
```
F = '+-/*'; %// possible operators
f = {@plus,@minus,@rdivide,@times}; %// to be used with bsxfun
t = strsplit(input('','s'),' '); %// input string and split by one or multiple spaces
i = str2double(t); %// convert each split string to number
j =~ isnan(i); %// these were operators, not numbers ...
t(j) = num2cell(i(j)); %// ... so restore them
while numel(t)>1
n = find(cellfun(@(x)isstr(x),t),1); %// find left-most operator
t{n} = bsxfun(f{t{n}==F}, t{n-2:n-1}); %// apply it to preceding numbers and replace
t(n-2:n-1)=[]; %// remove used numbers
end
t{1} %// display result
```
[Answer]
# K5, 70 bytes
```
`0:*{$[-9=@*x;((*(+;-;*;%)@"+-*/"?y).-2#x;x,.y)@47<y;(.x;.y)]}/" "\0:`
```
I'm not sure when K5 was released, so this *might* not count. Still awesome!
] |
[Question]
[
You are a space tourist on your way to planet Flooptonia! The flight is going to take another 47,315 years, so to pass the time before you're cryogenically frozen you decide to write a program to help you understand the Flooptonian calendar.
Here is the 208-day long Flooptonian calendar:
```
Month Days Input Range
Qupu 22 [0-22)
Blinkorp 17 [22-39)
Paas 24 [39-63)
Karpasus 17 [63-80)
Floopdoor 1 [80]
Dumaflop 28 [81-109)
Lindilo 32 [109-141)
Fwup 67 [141-208)
```
## Challenge
Your program, given an integer day in the year (range `[0-208)`) is to output the corresponding day of the month and name of the month (e.g. `13 Dumaflop`).
There is an exception, however: Floopdoor a special time for Flooptonians that apparently deserves its own calendar page. For that reason, Floopdoor isn't written with a day (i.e. the output is `Floopdoor`, not `1 Floopdoor`).
## Test Cases
```
0 => 1 Qupu
32 => 11 Blinkorp
62 => 24 Paas
77 => 15 Karpasus
80 => Floopdoor
99 => 19 Dumaflop
128 => 20 Lindilo
207 => 67 Fwup
```
## Rules
* You must write a complete program.
* You can assume that the input is always valid.
* Your output may have a trailing newline but must otherwise be free of any extra characters. The case should also match the provided examples.
* You may use date/time functions.
* Code length is to be measured in bytes.
[Answer]
# Python 3, ~~159~~ ~~156~~ ~~152~~ ~~151~~ ~~150~~ 148 bytes
```
n=int(input())+1
for c,x in zip(b" C","Qupu Blinkorp Paas Karpasus Floopdoor Dumaflop Lindilo Fwup".split()):c>=n>0and print(*[n,x][-c:]);n-=c
```
The bytes object in the `zip` contains unprintable characters:
```
for c,x in zip(b"\x16\x11\x18\x11\x01\x1c C", ...): ...
```
*(Thanks to @xnor for suggesting a `for/zip` loop for -3 bytes)*
[Answer]
# Pyth - 105 103 90 88 bytes
Uses base conversion. Two simple lookup tables, with one for the names and one for start dates, and a ternary at the end for Floopdoor.
```
KhfgQhTC,aCM"mQP?'"Zcs@LGjC"îºBüÏl}W\"p%åtml-¢pTÇÉ(°±`"23\c+?nQ80+-hQhKdkreK3
```
Compresses the string not as base 128, but as base 23. First, it translates it to indices of the alphabet. This required the separator to be `c` which doesn't appear in any of the month names. Then it encodes that to base ten from a base 23 number (the highest value that appeared was `w`), then converts to base 256.
The start dates are their unicode codepoints, no base conversion.
```
K K =
hf First that matches the filter
gQ >= Q
hT First element of filter var
C, Zip two sequences
a Z Append 0 (I could save a byte here but don't want to mess with null bytes)
CM"..." Map the string to its codepoints
c \c Split by "c"
s Sum by string concatenation
@LG Map to location in alphabet
j 23 Base 10 -> Base 23
C"..." Base 256 -> Base 10
+ String concatenation
?nQ80 Ternary if input != 80
+-hQhK Input - start date + 1
k Else empty string
r 3 Capitalize first letter
eK Of month name
```
[Try it online here](http://pyth.herokuapp.com/?code=KhfgQhTC%2CaCM%22%C2%8DmQP%3F%27%16%22Zcs%40LGjC%22%01%C3%AE%C2%BAB%C3%BC%C3%8Fl%7DW%5C%22p%25%C3%A5tml-%C2%9A%1F%C2%A2pT%C3%87%C2%94%C3%89%C2%97(%C2%96%C2%B0%18%C2%8F%C2%B1%15%60%2223%5Cc%2B%3FnQ80%2B-hQhKdkreK3&input=128&debug=1).
[Test Suite](http://pyth.herokuapp.com/?code=V.QKhfgNhTC%2CaCM%22%C2%8DmQP%3F%27%16%22Zcs%40LGjC%22%01%C3%AE%C2%BAB%C3%BC%C3%8Fl%7DW%5C%22p%25%C3%A5tml-%C2%9A%1F%C2%A2pT%C3%87%C2%94%C3%89%C2%97(%C2%96%C2%B0%18%C2%8F%C2%B1%15%60%2223%5Cc%2B%3FnN80%2B-hNhKdkreK3&input=0%0A32%0A62%0A77%0A80%0A99%0A128%0A207&debug=0).
[Answer]
# Piet 2125 bytes
It's by no means the shortest, but it's pretty and colorful...
Each pixel is placed by myself by hand. To run it go [here](http://www.rapapaing.com/piet/index.php) in FireFox (Chrome won't work) and load it with a codel width of 1 (it'll appear black, don't worry), enter the number and hit the run button!
Small Program:
[![Small Version](https://i.stack.imgur.com/UYzGl.png)](https://i.stack.imgur.com/UYzGl.png)
Enlarged (Codel width of 10):
[![enter image description here](https://i.stack.imgur.com/rvR7t.png)](https://i.stack.imgur.com/rvR7t.png)
[Answer]
# Pyth 178 156 153 147 bytes
```
J?<Q22,_1"Qupu"?<Q39,21"Blinkorp"?<Q63,38"Paas"?<Q80,62"Karpasus"?<Q81,k"Floopdoor"?<Q109,80"Dumaflop"?<Q141,108"Lindilo",140"Fwup"?nhJkjd,-QhJeJeJ
```
[Permalink](https://pyth.herokuapp.com/?code=J%3F%3CQ22%2C_1%22Qupu%22%3F%3CQ39%2C21%22Blinkorp%22%3F%3CQ63%2C38%22Paas%22%3F%3CQ80%2C62%22Karpasus%22%3F%3CQ81%2Ck%22Floopdoor%22%3F%3CQ109%2C80%22Dumaflop%22%3F%3CQ141%2C108%22Lindilo%22%2C140%22Fwup%22%3FnhJkjd%2C-QhJeJeJ&input=0&debug=0)
Second golf ever, any Pyth feedback will be very helpful.
## Explanation
```
J (Auto)Assign J a tuple of the first day & month name
?<Q22,_1"Qupu" Recall that Q auto-initialized to raw_input()
?<Q39,21"Blinkorp" ? is ternary
?<Q63,38"Paas" , is a two-pair tuple
?<Q80,62"Karpasus"
?<Q81,k"Floopdoor" Special case handled by empty string as first day
?<Q109,80"Dumaflop"
?<Q141,108"Lindilo"
,140"Fwup" Since input assumed valid, no need to test for Fwup
?nhJk Is day not an empty string?
jd, join on space
-QhJ Q-(first day or -1 on first month) + 1
eJ The month itself
eJ Else print only the month name on Floopdoor
```
[Answer]
# CJam, ~~98~~ ~~96~~ 93 bytes
```
0000000: 72 69 63 22 00 16 27 3f 50 51 6d 8d d0 22 66 2d ric"..'?PQm.."f-
0000010: 5f 7b 30 3c 7d 23 28 5f 40 3d 29 53 40 22 06 32 _{0<}#(_@=)S@".2
0000020: 88 b2 ce d2 87 2f 1e 79 62 1b 7a 11 53 a6 cc 02 ...../.yb.z.S...
0000030: 40 c5 c6 82 d0 dd b7 4b ed ee 1c dc 4f f5 ec 67 @......K....O..g
0000040: 22 32 35 35 62 32 33 62 27 61 66 2b 27 63 2f 3d "255b23b'af+'c/=
0000050: 5f 2c 39 3d 7b 5c 3f 7d 26 28 65 75 5c _,9={\?}&(eu\
```
The above is a reversible hexdump, since the source code contains unprintable characters.
Most unprintable characters are no problem for the online interpreter, but the null byte in the first string is a deal breaker.
At the cost of one byte, we can fix this by adding 1 to the input and 1 to each code point of the first string. You can try this version in the [CJam interpreter](http://cjam.aditsu.net/#code=ric)%22%01%17(%40QRn%C2%8E%C3%91%22f-_%7B0%3C%7D%23(_%40%3D)S%40%22%062%C2%88%C2%B2%C3%8E%C3%92%C2%87%2F%1Eyb%1Bz%11S%C2%A6%C3%8C%02%40%C3%85%C3%86%C2%82%C3%90%C3%9D%C2%B7K%C3%AD%C3%AE%1C%C3%9CO%C3%B5%C3%ACg%22255b23b'af%2B'c%2F%3D_%2C9%3D%7B%5C%3F%7D%26(eu%5C&input=80).
If the permalink doesn't work in your browser, you can copy the code from [this paste](http://pastebin.com/iWCtf4ae).
### Test cases
```
$ LANG=en_US
$ xxd -ps -r > flooptonia.cjam <<< 726963220016273f50516d8dd022662d5f7b303c7d23285f403d29534022063288b2ced2872f1e79621b7a1153a6cc0240c5c682d0ddb74bedee1cdc4ff5ec6722323535623233622761662b27632f3d5f2c393d7b5c3f7d262865755c
$ wc -c flooptonia.cjam
96 flooptonia.cjam
$ for d in 0 32 62 77 80 99 128 207; do cjam flooptonia.cjam <<< $d; echo; done
1 Qupu
11 Blinkorp
24 Paas
15 Karpasus
Floopdoor
19 Dumaflop
20 Lindilo
67 Fwup
```
### How it works
```
ric e# Read a Long from STDIN and cast to Character.
"…" e# Push the string that corresponds to [0 22 39 63 80 81 109 141 208].
f- e# Subtract each character from the input char.
e# Character Character - -> Long
_{0<}# e# Find the index of the first negative integer.
(_ e# Subtract 1 from the index and push a copy.
@=) e# Select the last non-negative integer from the array and add 1.
S@ e# Push a space and rotate the decremented index on top of it.
"…" e# Push a string that encodes the months' names.
255b23b e# Convert from base 255 to 23.
'af+ e# Add the resulting digits to the character 'a'.
'c/ e# Split at occurrences of 'c' (used as separator).
= e# Select the chunk that corresponds to the index.
_,9= e# Check if its length is 9 (Floopdoor).
{\?}& e# If so, swap and execute ternary if.
e# Since the string " " is truthy, S Month Day ? -> Month.
(eu\ e# Shift out the first char, convert it to uppercase and swap.
```
[Answer]
# SWI-Prolog, ~~237~~ ~~232~~ 213 bytes
```
a(X):-L=[22:"Qupu",39:"Blinkorp",63:"Paas",80:"Karpasus",81:"Floopdoor",109:"Dumaflop",141:"Lindilo",208:"Fwup"],nth1(I,L,A:B),X<A,J is I-1,(nth1(J,L,Z:_),Y=X-Z;Y=X),R is Y+1,(X=80,write(B);writef("%w %w",[R,B])).
```
Here we use Prolog's backtracking mechanism to repeatedly apply `nth1/3` to the list `L`, to get the first element `LastDay+1:MonthName` of `L` for which `X < LastDay+1` holds. We then look for the month immediately before this one in the list to evaluate the day of the month.
[Answer]
# Q, ~~134~~ 146 Bytes
### second cut -- program (146 bytes)
```
v:bin[l:0 22 39 63 80 81 109 141 208;x:(*)"I"$.z.x];1(,/)($)$[v=4;`;(1+x-l v)," "],`Qupu`Blinkorp`Paas`Karpasus`Floopdoor`Dumaflop`Lindilo`Fwup v;
```
### first cut -- function (134 bytes)
```
{v:bin[l:0 22 39 63 80 81 109 141 208;x];(,/)($)$[v=4;`;(1+x-l v)," "],`Qupu`Blinkorp`Paas`Karpasus`Floopdoor`Dumaflop`Lindilo`Fwup v}
```
### testing
```
q){v:bin[l:0 22 39 63 80 81 109 141 208;x];(,/)($)$[v=4;`;(1+x-l v)," "],`Qupu`Blinkorp`Paas`Karpasus`Floopdoor`Dumaflop`Lindilo`Fwup v} each 0 32 62 77 80 99 128 207
"1 Qupu"
"11 Blinkorp"
"24 Paas"
"15 Karpasus"
"Floopdoor"
"19 Dumaflop"
"20 Lindilo"
"67 Fwup"
```
[Answer]
# Julia, ~~231~~ ~~216~~ ~~184~~ 175 bytes
```
r=readline()|>int
l=[141,109,81,80,63,39,22,0]
m=split("Qupu Blinkorp Paas Karpasus Floopdoor Dumaflop Lindilo Fwup")
i=findfirst(j->r>=j,l)
print(i==4?"":r-l[i]+1," ",m[9-i])
```
This reads a line from STDIN and converts it to an integer, finds the first element of a reversed list of month start days where the input is greater than or equal to the start, then prints accordingly.
[Answer]
# Swift 1.2, 256 bytes
```
var d=Process.arguments[1].toInt()!,f="Floopdoor",n=[("Qupu",22),("Blinkorp",17),("Paas",24),("Karpasus",17),(f,1),("Dumaflop",28),("Lindilo",32),("Fwup",67)]
for i in 0..<n.count{let m=n[i]
if d>=m.1{d-=m.1}else{println((m.0==f ?"":"\(d+1) ")+m.0)
break}}
```
To run put the code alone in a `.swift` file and run it using `swift <filename> <inputNumber>`
[Answer]
# Java, ~~357~~ 339 bytes
It's not the most efficient, but I do like how it works. It creates the entire Flooptonia calendar and then looks up what date the number is.
```
class X{public static void main(String[]q){String n[]={"Qupu","Blinkorp","Paas","Karpasus","Floopdoor","Dumaflop","Lindilo","Fwup"},l[]=new String[209];int m=0,d=0,i,b[]={0,22,39,63,80,81,109,141,208};for(i=0;i++<208;d++){l[i]=(m==4?"":d+" ")+n[m];if(i>b[m+1]){m++;d=0;}}System.out.print(l[new java.util.Scanner(System.in).nextInt()+2]);}}
```
Input/Output:
`77 --> 15 Karpasus
80 --> Floopdoor`
Spaced and tabbed out:
```
class X {
public static void main(String[] q) {
String n[] = { "Qupu", "Blinkorp", "Paas", "Karpasus", "Floopdoor", "Dumaflop", "Lindilo", "Fwup" },
l[]=new String[209];
int m = 0,
d = 0,
i,
b[] = { 0, 22, 39, 63, 80, 81, 109, 141, 208 };
for(i = 0; i++ < 208; d++) {
l[i]=(m == 4 ? "" : d + " ") + n[m];
if(i > b[m+1]){
m++;
d = 0;
}
}
System.out.print(l[ new java.util.Scanner(System.in).nextInt() + 2 ]);
}
}
```
[Answer]
# Java, ~~275~~ ~~269~~ ~~266~~ ~~257~~ ~~256~~ ~~252~~ ~~246~~ ~~244~~ 243 bytes
```
class X{public static void main(String[]w){int x=new Short(w[0]),i=1,a[]={-1,21,38,62,79,80,108,140,207};w="Qupu,Blinkorp,Paas,Karpasus,Floopdoor,Dumaflop,Lindilo,Fwup".split(",");while(x>a[i++]);System.out.print((i==6?"":x-a[i-=2]+" ")+w[i]);}}
```
Formatted:
```
class X {
public static void main(String[] w) {
int x = new Short(w[0]),
i = 1,
a[] = { -1, 21, 38, 62, 79, 80, 108, 140, 207 };
w = "Qupu,Blinkorp,Paas,Karpasus,,Dumaflop,Lindilo,Fwup".split(",");
while (x > a[i++]);
System.out.print(i == 6 ? "Floopdoor" : x - a[i-=2] + " " + w[i]);
}
}
```
Interestingly, it's a few bytes shorter than this
```
class X {
public static void main(String[] w) {
int x = new Short(w[0]);
System.out.print(x < 22 ? x + 1 + " Qupu" : x < 39 ? x - 21
+ " Blinkorp" : x < 63 ? x - 38 + " Paas" : x < 80 ? x - 62
+ " Karpasus" : x < 81 ? "Floopdoor" : x < 109 ? x - 80
+ " Dumaflop" : x < 141 ? x - 108 + " Lindilo" : x < 208 ? x
- 140 + " Fwup" : "");
}
}
```
[Answer]
**JavaScript using ES6 ~~171~~ ~~164~~ 163 bytes**
I'm not the best JavaScript programmer but I tried my best and ended up with the following code
```
f=(n)=>[0,22,39,63,80,81,109,141,208].some((e,j,a)=>n<a[j+1]&&(r=(j-4?n-e+1+' ':'')+"Qupu0Blinkorp0Paas0Karpasus0Floopdoor0Dumaflop0Lindilo0Fwup".split(0)[j]))&&r;
```
To see the result you need to refer above code in a html file and use similar to the code below
```
<html><body><p id="o"></p><script src="Fp.js"></script><script>t=[0,32,62,77,80,99,128,207];for(i=0;i<t.length;i++)document.getElementById('o').innerHTML+=f(t[i])+'<br/>';</script></body></html>
```
In the above code fp.js is the file that contains the javascript code.
Combined HTML and JavaScript code with indent is
```
f=(n)=>[0,22,39,63,80,81,109,141,208].some(
(e,j,a)=>n<a[j+1]&&(r=(j-4?n-e+1+' ':'')+"Qupu0Blinkorp0Paas0Karpasus0Floopdoor0Dumaflop0Lindilo0Fwup".split(0)[j]))
&&r;
t = [0, 32, 62, 77, 80, 99, 128, 207];
for (i = 0; i < t.length; i++)
document.getElementById('o').innerHTML += f(t[i]) + '<br/>';
```
```
<html>
<body>
<p id="o"></p>
</body>
</html>
```
**Edit:**
I'd like to thank Vihan for helping me remove the return statement and reduce my code by 17bytes
@ipi, thanks for helping me save 7 bytes
>
> Note: You can see the result only in browsers Firefox version 22+ and
> Google Chrome 45+ because of using ES6 arrow functions
>
>
>
[Answer]
# Python 2, 168 bytes
```
n=input();e=[-1,21,38,62,80,108,140,207];m=1
while n>e[m]:m+=1
print[`n-e[m-1]`+' '+'Qupu Blinkorp Paas Karpasus Dumaflop Lindilo Fwup'.split()[m-1],'Floopdoor'][n==80]
```
This treats day `80` internally as `18 Karpasus`, but then ignores it when called to print. Also, Python 2's `input()` function (as opposed to `raw_input()`) was convenient here.
[Answer]
# Perl 5, 140
Requires running via `perl -E`:
```
$i=<>+1;$i-=$b=(22,17,24,17,1,28,32,67)[$c++]while$i>0;say$b>1&&$i+$b.$",(x,Qupu,Blinkorp,Paas,Karpasus,Floopdoor,Dumaflop,Lindilo,Fwup)[$c]
```
Test output (stolen test code from @Dennis):
```
$for d in 0 32 62 77 80 99 128 207; do perl -E '$i=<>+1;$i-=$b=(22,17,24,17,1,28,32,67)[$c++]while$i>0;say$b>1&&$i+$b.$",(x,Qupu,Blinkorp,Paas,Karpasus,Floopdoor,Dumaflop,Lindilo,Fwup)[$c]' <<< $d; echo; done
1 Qupu
11 Blinkorp
24 Paas
15 Karpasus
Floopdoor
19 Dumaflop
20 Lindilo
67 Fwup
```
[Answer]
# Haskell, ~~171~~ 167 bytes
```
main=interact$f.read
f 80="Floopdoor"
f n=(g=<<zip[22,17,24,18,28,32,67](words"Qupu Blinkorp Paas Karpasus Dumaflop Lindilo Fwup"))!!n
g(n,s)=map((++' ':s).show)[1..n]
```
The program reads it's input from stdin which must not end in NL. Terminate input with EOF/^D or use something like `echo -n 80 | ./what-day-is-it`. (Some `echo`s don't understand the `-n` switch and omit the NL by default).
How it works: The `main` function reads the input, converts it to an `Integer` and calls `f` which returns a literal `Floopdoor` in case of an input of `80` or builds up a list of all possible dates, i.e. `["1 Qupu", "2 Qupu", ... "1 Blinkorp", ... "67 Fwup"]` from which it picks the `n`th element. I make `Karpasus` is one day longer. `18 Karpasus` is at position `80` and fixes the missing `Floopdoor` in the list.
Edit: @MtnViewMark had the idea of the `18 Karpasus` trick and saved 4 bytes.
[Answer]
## Swift 2.0, 220 bytes
Nothing clever, just filters from a collection of tuples...
```
func d(n:Int)->String{return n==80 ?"Floopdoor":[("Qupu",21,0),("Blinkorp",38,22),("Paas",62,39),("Karpasus",79,63),("Dumaflop",108,81),("Lindilo",140,109),("Fwup",208,141)].filter{$0.1>=n}.map{"\($0.0) \(n-$0.2+1)"}[0]}
```
Edited to correct bug, removed a space
[Answer]
## JavaScript (ES6 on Node.js), 196 bytes
Takes one command line argument:
```
a=+process.argv[2];for(d of['22Qupu','17Blinkorp','24Paas','17Karpasus','01Floopdoor','28Dumaflop','32Lindilo','67Fwup']){if(a<(z=parseInt(d)))return console.log((z>1?a+1+' ':'')+d.slice(2));a-=z}
```
### Demo
As there is no command-line argument ([`process.argv`](https://nodejs.org/docs/latest/api/process.html#process_process_argv)) in the browser, the code in the snippet has been placed in a function that accepts an argument:
```
// Snippet stuff
console.log = function(x){O.innerHTML += x + '\n'};
// Flooptonia function
function flooptonia(a) {
a = +a;
for (d in y=['22Qupu', '17Blinkorp', '24Paas', '17Karpasus', '01Floopdoor', '28Dumaflop', '32Lindilo', '67Fwup']) {
if (a < (z = parseInt(y[d]))) return console.log((z > 1 ? a + 1 + ' ' : '') + y[d].slice(2));
a -= z
}
}
// Test
['0', '32', '62', '77', '80', '99', '128', '207'].map(flooptonia);
```
```
Test values: [0, 32, 62, 77, 80, 99, 128, 207]
<pre id=O></pre>
```
[Answer]
# Swift 2.0, 215 204
```
let(n,t)=(Int(readLine()!)!,[(141,"Fwup"),(109,"Lindilo"),(81,"Dumaflop"),(63,"Karpasus"),(39,"Paas"),(22,"Blinkorp"),(0,"Qupu")])
print({(n==80 ?"Floopdoor":"\(n-$0.0+1) "+$0.1)}(t[t.indexOf{$0.0<=n}!]))
```
This is a full program which asks the user to input the number in STDIN.
[Answer]
## Matlab, 187 bytes
```
d=input('');l=[141 109 81 80 63 39 22 0];t=find(d>=l,1);m=strsplit('Fwup Lindilo Dumaflop Floopdoor Karpasus Paas Blinkorp Qupu');f='%d %s';if t==4;f='%d\b%s';end;fprintf(f,d-l(t)+1,m{t})
```
Expanded version:
```
d=input('');
l=[141 109 81 80 63 39 22 0];
t=find(d>=l,1);
m=strsplit('Fwup Lindilo Dumaflop Floopdoor Karpasus Paas Blinkorp Qupu');
f='%d %s';
if t==4;
f='%d\b%s';
end
fprintf(f,d-l(t)+1,m{t})
```
Reads a line from the console (`stdin`), finds the first element of a reversed list of month start days where the input is greater than or equal to the array element, then prints accordingly.
This is almost identical to the `Julia` answer, except for the display stage. (*We can't beat their ternary operator, unavailable in Matlab*). To make up having to explicit a full `if` statement, we use a little trick (a `Backspace` character in the print format) to "erase" the number 1 for the special day/month `Floopdoor`
---
*In collaboration with the [Matlab and Octave](http://chat.stackoverflow.com/rooms/81987/matlab-and-octave) chat participants.*
[Answer]
# Javascript ES5 using 168 bytes
```
m=[-1,21,38,62,79,80,108,140];for(n=prompt(i=0);n>m[i+1]&&i++<8;);alert((i-4?n-m[i]+" ":"")+"Qupu0Blinkorp0Paas0Karpasus0Floopdoor0Dumaflop0Lindilo0Fwup".split(0)[i])
```
Ungolfed:
```
m=[-1,21,38,62,79,80,108,140]; // create range of starting indexes - 1
for( // begin for loop
n=prompt(i=0); // initialize i to zero and prompt user
n>m[i+1] && i++ < 8; // exit if n>0; increment i; exit if i was < 8
); // end for loop
alert(
(i-4 ? n-m[i]+" ":"") + // special floopdoor case
"Qupu0Blinkorp0Paas0Karpasus0Floopdoor0Dumaflop0Lindilo0Fwup".split(0)[i]);
//^ create an array of strings by splitting at zero. Then, select element i
```
[Answer]
# C, 241 bytes
Nothing too exciting. Could have shaved 27 bytes had it require to be a complete program.
```
main(c,s)char**s;{c=atoi(s[1]);c-80?printf("%d ",c<22?c+1:c<39?c-21:c<63?c-38:c<80?c-62:c<109?c-80:c<141?c-108:c-140):0;puts(c<22?"Qupu":c<39?"Blinkorp":c<63?"Paas":c<80?"Karpasus":c<81?"Floopdoor":c<109?"Dumaflop":c<141?"Lindilo":"Fwup");}
```
] |
[Question]
[
[NetHack](https://en.wikipedia.org/wiki/NetHack) is a roguelike game where a player must retrieve the Amulet of Yendor from the lowest level of the dungeon. Commonly played via telnet, the entire game is represented with ASCII graphics. The game is extremely challenging and requires knowledge of many game mechanics in order to succeed.
For the purposes of this challenge, assume that the entire dungeon is a single level and only 5×16 characters. Furthermore, assume that this is a "safe" dungeon or that you are only implementing a prototype—there will be no monsters, concerns about hunger, etc. In fact, you must only track the location of the character and the amulet and the game will effectively end when the player arrives at the same location as the amulet.
# Challenge requirements
* There will be a 5×16 dungeon (single level).
* Give the player a starting location (optionally random) and the amulet a separate random (different each time the program is run) starting square inside the dungeon. That is, the amulet is not allowed to start on the same square as the player.
* Accept four input keys which move the player one square at a time (four cardinal directions). Reading/processing other input is allowed (a readline() function that requires pressing 'enter', etc).
* Travelling outside the bounds of the dungeon is not allowed. E.g., if the player is on the right edge of the dungeon pressing right should do nothing.
* After initial generation and after each movement, print the state of the game. As this is code golf and printing is rather uninteresting, ignore the character count for the print function and function call *assuming no state changes*. Empty cells should be shown as period (`.`), amulet as double quote (`"`) and character as at symbol (`@`).
* The game is over when the player "discovers" the amulet (arrives at the same square)
# Winning
This is a code golf challenege, the shortest code to meet the requirements one week from today will be declared winner.
# Example
Here is an example solution in C# (ungolfed) to show basic requirements and sample output.
```
using System;
namespace nh
{
class Program
{
static Random random = new Random();
// player x/y, amulet x/y
static int px, py, ax, ay;
static void Main(string[] args)
{
px = random.Next(0, 16);
py = random.Next(0, 5);
// amulet starts on a position different from the player
do { ax = random.Next(0, 16); } while (px == ax);
do { ay = random.Next(0, 5); } while (py == ay);
print();
do
{
// reads a single keypress (no need to press enter)
// result is cast to int to compare with character literals
var m = (int)Console.ReadKey(true).Key;
// Move the player. Here standard WASD keys are used.
// Boundary checks for edge of dungeon as well.
if (m == 'W')
py = (py > 0) ? py - 1 : py;
if (m == 'S')
py = (py < 5) ? py + 1 : py;
if (m == 'A')
px = (px > 0) ? px - 1 : px;
if (m == 'D')
px = (px < 16) ? px + 1 : px;
// print state after each keypress. If the player doesn't
// move this is redundant but oh well.
print();
// game ends when player is on same square as amulet
} while (px != ax || py != ay);
}
static void print()
{
Console.Write('\n');
for (int y=0; y<5; y++)
{
for (int x = 0; x < 16; x++)
{
if (x == px && y == py)
Console.Write('@');
else if (x == ax && y == ay)
Console.Write('"');
else
Console.Write('.');
}
Console.Write('\n');
}
}
}
}
```
Total character count is 1474, but ignoring calls to the print function and its definition the final character count is `896`.
Output when the program is run:
```
................
...."...........
..........@.....
................
................
```
Output (including above) after the 'a' key is pressed twice:
```
................
...."...........
..........@.....
................
................
................
...."...........
.........@......
................
................
................
...."...........
........@.......
................
................
```
[Answer]
# [CHIP-8](https://en.wikipedia.org/wiki/CHIP-8), 48 bytes
This may not be considered legal, but why the hell not. I wrote my program in CHIP-8, a bytecode-based programming language for a virtual game console. You can try the complete program (99 bytes) in your browser using an emulator/debugger I wrote called Octo:
![Screenshot](https://i.stack.imgur.com/uMI59.png)
<http://johnearnest.github.io/Octo/index.html?gist=1318903acdc1dd266469>
A hex dump of that complete program is as follows:
```
0x60 0x14 0x61 0x04 0xC4 0x3C 0xC5 0x08
0x22 0x36 0xF6 0x0A 0x22 0x52 0x40 0x00
0x12 0x16 0x46 0x07 0x70 0xFC 0x40 0x3C
0x12 0x1E 0x46 0x09 0x70 0x04 0x41 0x00
0x12 0x26 0x46 0x05 0x71 0xFC 0x41 0x10
0x12 0x2E 0x46 0x08 0x71 0x04 0x22 0x52
0x3F 0x01 0x12 0x0A 0x00 0xFD 0xA2 0x58
0xD4 0x54 0x22 0x52 0x62 0xFF 0xA2 0x5B
0xD2 0x34 0x72 0x04 0x32 0x3F 0x12 0x40
0x62 0xFF 0x73 0x04 0x33 0x14 0x12 0x40
0x00 0xEE 0xA2 0x5F 0xD0 0x14 0x00 0xEE
0xA0 0xA0 0x40 0x00 0x00 0x20 0x00 0xF0
0x90 0x90 0xD0
```
You can move the player with the ASWD keys, or the 7589 keys on the original CHIP-8 keypad. If I remove all the code and data for drawing the background and the player, I instead get this 48 byte dump:
```
0x60 0x14 0x61 0x04 0xC4 0x3C 0xC5 0x08
0xF6 0x0A 0x40 0x00 0x12 0x12 0x46 0x07
0x70 0xFC 0x40 0x3C 0x12 0x1A 0x46 0x09
0x70 0x04 0x41 0x00 0x12 0x22 0x46 0x05
0x71 0xFC 0x41 0x10 0x12 0x2A 0x46 0x08
0x71 0x04 0x3F 0x01 0x12 0x08 0x00 0xFD
```
The ungolfed, complete form of the program was written in a high level assembly language as follows:
```
:alias px v0
:alias py v1
:alias tx v2
:alias ty v3
:alias ax v4
:alias ay v5
:alias in v6
: main
px := 20
py := 4
ax := random 0b111100
ay := random 0b001000
draw-board
loop
in := key
draw-player
if px != 0 begin
if in == 7 then px += -4
end
if px != 0x3C begin
if in == 9 then px += 4
end
if py != 0 begin
if in == 5 then py += -4
end
if py != 16 begin
if in == 8 then py += 4
end
draw-player
if vf != 1 then
again
exit
: draw-board
i := amulet
sprite ax ay 4
draw-player
tx := -1
i := ground
: draw
loop
sprite tx ty 4
tx += 4
if tx != 63 then jump draw
tx := -1
ty += 4
if ty != 20 then
again
;
: draw-player
i := player
sprite px py 4
;
: amulet 0xA0 0xA0 0x40
: ground 0x00 0x00 0x20 0x00
: player 0xF0 0x90 0x90 0xD0
```
Note that the compiled bytes *themselves* are the CHIP-8 programming language; the assembler is simply a more convenient means of composing such programs.
[Answer]
# TI-BASIC, ~~42~~ ~~41~~ ~~38~~ ~~36~~ 35 bytes
For your TI-83 or 84+ series graphing calculator.
```
int(5irand→A //Randomize amulet position
6log(ie^(6→C //15.635 + 4.093i
Repeat Ans=A //Ans holds the player pos. (starts bottom right)
iPart(C-iPart(C-Ans-e^(igetKey-i //Boundary check, after adjusting player position
prgmDISPLAY
End
----------
PROGRAM:DISPLAY
For(X,0,15
For(Y,0,4
Output(Y+1,X+1,".
If A=X+Yi
Output(Y+1,X+1,"¨
If Ans=X+Yi
Output(Y+1,X+1,"@
End
End
```
Which direction the player will go is a function of the [key code](http://tibasicdev.wikidot.com/key-codes) of the key pressed, but four keys that definitely work are these on the top row:
```
Key [Y=] [WINDOW] [ZOOM] [TRACE] [GRAPH]
-------------------------------------------
Key code 11 12 13 15
Direction Left Up Right Down
```
The amulet starts on one of the five squares in the first column, and the player starts at the bottom right square. For example, a possible arrangement is:
```
................
¨...............
................
................
...............@
```
## Explanation
The player's position is stored as a complex number from `0+0i` to `15+4i`, where the real part goes to the right and the imaginary part goes down. This facilitates easy boundary checking on the top and left: we simply offset the number slightly and round towards zero. For example, if the offset is `0.5` and our position is `-1+3i` (off the screen to the left), then the position will be corrected to `iPart(-0.5+3.5i)=0+3i`, where it should be. Checking for the bottom and right boundaries is slightly more complicated; we need to subtract the number from a constant `C`, which is about `15.635 + 4.093i` (it's the shortest one I could find between `15+4i` and `16+5i`), round, subtract from `C` again to flip the number back, and round again.
When a key is pressed, the unadjusted player position will move by 1 unit in some direction, but the integer part only changes when certain keys are pressed. Luckily, the keys that work are all on the top row. Below is a graph of the offsets in cases where keys 11, 12, 13, and 15 are pressed, and when no key is pressed (No press is the point inside the center square, causing the integer parts to be unchanged; the four keypresses' offsets have different integer parts). `C` is the red cross at the center of the circle.
![enter image description here](https://i.stack.imgur.com/BBrom.png)
## Old code (42 bytes):
```
int(9irand→A // 0≤rand≤1, so int(9irand) = i*x where 0≤x≤8
1 //set "Ans"wer variable to 1+0i
Repeat Ans=A
Ans-iPart(i^int(48ln(getKey-1 //add -i,-1,i,1 for WASD respectively (see rev. history)
Ans-int(Ans/16+real(Ans/7 //ensure player is inside dungeon
prgmDISPLAY //display on top 5 rows of the homescreen
//(for this version switch X+Yi with Y=Xi in prgmDISPLAY)
End
```
### Limitations
There is no way to escape a `"` character, so strings with a `"` cannot be generated inside a program. Therefore, this uses the umlaut mark `¨` instead of a quote (if there were an already-existing string with a quote mark, I could display that). To get `¨` and `@` in a program, an outside tool is required; however, it is valid TI-BASIC.
[Answer]
# Python 3, 86 bytes
```
def d():
import sys
for y in range(5):
line = []
for x in range(16):
line.append('@' if y*16+x == p else \
'"' if y*16+x == a else \
'.')
print(''.join(line))
print()
sys.stdout.flush()
p=79;a=id(9)%p
while p-a:d();p+=[p%16<15,16*(p<64),-(p%16>0),-16*(p>15)][ord(input())%7%5]
```
Only counting the bottom two lines, and dropping `d();`.
[Answer]
# C, ~~122~~ ~~121~~ ~~115~~ ~~104~~ ~~102~~ 101 bytes
```
#define o ({for(int t=0;t<80;++t)t%16||putchar(10),putchar(t^p?t^a?46:34:64);})
p;main(a){for(a=1+time(0)%79;p^a;o,p+=(int[]){-16*(p>15),16*(p<64),-!!(p%16),p%16<15}[3&getchar()/2]);}
```
First time posting here ! I hope you like it :)
`o` is the printing, erm, function. Our brave hero can be moved around with 2, 4, 6 and 8, but beware of not sending any other input (no newlines !).
**Update 1 :** brought `a` and `i` into `main`'s parameters.
**Update 2 :** OP having [confirmed](https://codegolf.stackexchange.com/questions/52547/minimal-nethack/52565#comment125400_52547) that a single string of input is OK, I got rid of `scanf` (which I used to skip the newline).
**Update 3 :** Used a compound array literal and modified the input layout. Program now goes haywire if you enter an invalid direction ;)
**Update 4 :** Noticed that the call to the printing function does not count. Took note to read rules more carefully.
**Update 5 :** one byte saved, thanks to Mikkel Alan Stokkebye Christia.
[Answer]
# CJam, ~~46~~ ~~45~~ ~~44~~ ~~40~~ ~~39~~ 37 bytes
```
{'.80*W$Gb'"t1$Gb'@tG/W%N*oNo}:P;
5,G,m*:Dmr~{P_l~4b2fm.+_aD&!$_W$=!}gP];
```
The first line (defines a function that prints the current game state) and the **P**'s on the second line (call that function) do not contribute to the byte count.
Both the starting position and the amulet's position are selected pseudo-randomly. The distribution is as uniform and the underlying PRNG allows.
Input is `E`, `6`, `9` and `B` for **Up**, **Down**, **Left** and **Right**, with `Caps Lock` activated, followed by `Enter`.
### Alternate version
```
{'.80*W$Gb'"t1$Gb'@tG/W%N*oNo}:P;
5,G,m*:Dmr~{P_ZYm*l~(=:(.+_aD&!$_W$=!}gP];
```
At the cost of four more bytes, the input format is improved significantly:
* This version accepts `8`, `2`, `4` and `6` for **Up**, **Down**, **Left** and **Right**, which matches the corresponding arrow keys on the numpad.
* It also accepts `7`, `9`, `1` and `3` for the corresponding diagonal moves.
### Testing
Since the I/O is interactive, you should try this code with the [Java interpreter](https://sourceforge.net/projects/cjam/files/).
Download the latest version and run the program like this:
```
java -jar cjam-0.6.5.jar nethack.cjam
```
To avoid pressing `Enter` after each key, and for in-place updates of the output, you can use this wrapper:
```
#!/bin/bash
lines=5
wait=0.05
coproc "$@"
pid=$!
head -$lines <&${COPROC[0]}
while true; do
kill -0 $pid 2>&- || break
read -n 1 -s
echo $REPLY >&${COPROC[1]}
printf "\e[${lines}A"
head -$lines <&${COPROC[0]}
sleep $wait
done
printf "\e[${lines}B"
```
Invoke like this:
```
./wrapper java -jar cjam-0.6.5.jar nethack.cjam
```
### Main version
```
5,G, e# Push [0 1 2 3 4] and [0 ... 15].
m*:D e# Take the Cartesian product and save in D.
mr~ e# Shuffle and dump the array on the stack.
e# This pushes 80 elements. We'll consider the bottommost the amulet's
e# position and the topmost the player's.
{ e# Do:
P e# Call P.
_ e# Copy the player's position.
l~ e# Read and evaluate one line of input.
e# "6" -> 6, "9" -> 9, "B" -> 11, "E" -> 14
4b e# Convert to base 4.
e# 6 -> [1 2], 9 -> [2 1], 11 -> [2 3], 14 -> [3 2]
2f- e# Subtract 2 from each coordinate.
e# [1 2] -> [-1 0], [2 1] -> [0 -1], [2 3] -> [0 1], [3 2] -> [1 0]
.+ e# Add the result to the copy of player's position.
_aD& e# Push a copy, wrap it in an array and intersect with D.
! e# Logical NOT. This pushes 1 iff the intersection was empty.
$ e# Copy the corresponding item from the stack.
e# If the intersection was empty, the new position is invalid
e# and 1$ copies the old position.
e# If the intersection was non-empty, the new position is valid
e# and 0$ copies the new position.
_W$ e# Push copies of the new position and the amulet's position.
=! e# Push 1 iff the positions are different.
}g e# While =! pushes 1.
P e# Call P.
]; e# Clear the stack.
```
### Alternate version
```
ZYm* e# Push the Cartesian product of 3 and 2, i.e.,
e# [[0 0] [0 1] [0 2] [1 0] [1 1] [1 2] [2 0] [2 1] [2 2]].
l~ e# Read and evaluate one line of input.
(= e# Subtract 1 and fetch the corresponding element of the array.
:( e# Subtract 1 from each coordinate.
```
### Function P
```
'.80* e# Push a string of 80 dots.
W$Gb e# Copy the amulet's position and convert from base 16 to integer.
'"t e# Set the corresponding character of the string to '"'.
1$Gb e# Copy the player's position and convert from base 16 to integer.
'@t e# Set the corresponding character of the string to '@'.
G/ e# Split into chunks of length 16.
W% e# Reverse the chunks (only needed for the alternate program).
N* e# Join the chunks, separating by linefeeds.
oNo e# Print the resulting string and an additional linefeed.
```
[Answer]
# Java, 231 bytes (196 if function)
Here's the full program code at 342:
```
class H{public static void main(String[]a){int p=0,y=79,c;y*=Math.random();y++;p(p,y);do p((p=(c=new java.util.Scanner(System.in).next().charAt(0))<66&p%16>0?p-1:c==68&p%16<15?p+1:c>86&p>15?p-16:c==83&p<64?p+16:p),y);while(p!=y);}static void p(int p,int y){for(int i=0;i<80;i++){System.out.print((i==p?'@':i==y?'"':'.')+(i%16>14?"\n":""));}}}
```
Without the print function, 231:
```
class H{public static void main(String[]a){int p=0,y=79,c;y*=Math.random();y++;p(p,y);do p((p=(c=new java.util.Scanner(System.in).next().charAt(0))<66&p%16>0?p-1:c==68&p%16<15?p+1:c>86&p>15?p-16:c==83&p<64?p+16:p),y);while(p!=y);}}
```
If just a function is okay (I'm unclear from the spec), then I can cut this down a bit further to 196:
```
void m(){int p=0,y=79,c;y*=Math.random();y++;p(p,y);do p((p=(c=new java.util.Scanner(System.in).next().charAt(0))<66&p%16>0?p-1:c==68&p%16<15?p+1:c>86&p>15?p-16:c==83&p<64?p+16:p),y);while(p!=y);}
```
And with some line breaks for a bit of clarity...
```
class H{
public static void main(String[]a){
int p=0,y=79,c;
y*=Math.random();
y++;p(p,y);
do
p(
(p=(c=new java.util.Scanner(System.in).next().charAt(0))<66&p%16>0?
p-1:
c==68&p%16<15?
p+1:
c>86&p>15?
p-16:
c==83&p<64?
p+16:
p)
,y);
while(p!=y);
}
static void p(int p,int y){
for(int i=0;i<80;i++){
System.out.print((i==p?'@':i==y?'"':'.')+(i%16>14?"\n":""));
}
}
}
```
Note that I'm not counting the print function `p(p,y)` itself, but I *am* counting the call to it, since I have stuff changing inside the call statement.
It works with capital letters `ASDW`. Due to the way it checks for those, some other letters might also work, but the spec doesn't really say anything about what should happen if I press different keys.
[Answer]
# Java, 574 bytes
```
import java.util.*;public class N{static Random r=new Random();static int v,b,n,m;public static void main(String[] a){v=r.nextInt(16);b=r.nextInt(5);n=r.nextInt(16);m=r.nextInt(5);p();do{Scanner e=new Scanner(System.in);char m=e.next().charAt(0);if(m=='w')b=b>0?b-1:b;if(m=='s')b=b<5?b+1:b;if(m=='a')v=v>0?v-1:v;if(m=='d')v=v<16?v+1:v;p();}while(v!=n || b!=m);}static void p(){System.out.println();for(int y=0;y<5;y++){for(int x=0;x<16;x++){if(x==z && y==x)System.out.print('@');else if(x==n && y==m)System.out.print('"');else System.out.print('.');}System.out.println();}}}
```
Basically the same as the C# version, except obfuscated & minimized.
[Answer]
# Julia, 161 bytes
Uses `w`, `a`, `s`, and `d` to move up, left, down, and right, respectively.
Full code, including printing (330 bytes):
```
B=fill('.',5,16)
a=[rand(1:5),rand(1:16)]
B[a[1],a[2]]='"'
c=[1,a==[1,1]?2:1]
B[c[1],c[2]]='@'
for i=1:5 println(join(B[i,:]))end
while c!=a
B[c[1],c[2]]='.'
m=readline()[1]
c[2]+=m=='a'&&c[2]>1?-1:m=='d'&&c[2]<16?1:0
c[1]+=m=='w'&&c[1]>1?-1:m=='s'&&c[1]<5?1:0
m∈"wasd"&&(B[c[1],c[2]]='@')
for i=1:5 println(join(B[i,:]))end
end
```
---
Scored code, excludes printing (161 bytes):
```
a=[rand(1:5),rand(1:16)]
c=[1,a==[1,1]?2:1]
while c!=a
m=readline()[1]
c[2]+=m=='a'&&c[2]>1?-1:m=='d'&&c[2]<16?1:0
c[1]+=m=='w'&&c[1]>1?-1:m=='s'&&c[1]<5?1:0
end
```
The difference here is that we don't save the game state as a matrix; all relevant information is contained in the arrays `c` and `a`. And, of course, nothing is printed. The user will no longer be prompted for input once the player reaches the amulet.
---
Ungolfed + explanation (full code):
```
# Initialize a 5x16 matrix of dots
B = fill('.', 5, 16)
# Get a random location for the amulet
a = [rand(1:5), rand(1:16)]
# Put the amulet in B
B[a[1], a[2]] = '"'
# Start the player in the upper left unless the amulet is there
c = [1, a == [1,1] ? 2 : 1]
# Put the player in B
B[c[1], c[2]] = '@'
# Print the initial game state
for i = 1:5 println(join(B[i,:])) end
# Loop until the player gets the amulet
while c != a
# Put a dot in the player's previous location
B[c[1], c[2]] = '.'
# Read a line from STDIN, take the first character
m = readline()[1]
# Move the player horizontally within the bounds
if m == 'a' && c[2] > 1
c[2] -= 1
elseif m == 'd' && c[2] < 16
c[2] += 1
end
# Move the player vertically within the bounds
if m == 'w' && c[1] > 1
c[1] -= 1
elseif m == 's' && c[1] < 5
c[1] += 1
end
# Set the player's new location in B
if m ∈ "wasd"
B[c[1], c[2]] = '@'
end
# Print the game state
for i = 1:5 println(join(B[i,:])) end
end
```
[Answer]
# Batch, 329 Bytes
```
@echo off
set e=goto e
set f= set/a
%f%a=0
%f%b=0
%f%c=%random%*3/32768+1
%f%d=%random%*16/32768+1
:et
call:p %a% %b% %c% %d%
if %a%%b% EQU %c%%d% exit/b
choice/C "wasd"
goto %errorlevel%
:1
%f%a-=1
%e%
:2
%f%b-=1
%e%
:3
%f%a+=1
%e%
:4
%f%b+=1
:e
if %a% GTR 4%f%a=4
if %a% LSS 0%f%a=0
if %b% GTR 15%f%b=15
if %b% LSS 0%f%b=0
%e%t
:p
setlocal enabledelayedexpansion
::creating a new line variable for multi line strings
set NL=^
:: Two empty lines are required here
cls
set "display="
for /l %%r in (0,1,4) do (
set "line="
for /l %%c in (0,1,15) do (
set "char=."
if %3 EQU %%r (
if %4 EQU %%c (
set char="
)
)
if %1 EQU %%r (
if %2 EQU %%c (
set "char=@"
)
)
set "line=!line!!char!"
)
set "display=!display!!line!!NL!"
)
echo !display!
exit /b
```
[Answer]
# Perl, ~~228~~ 222 characters (not counting the newlines that are not integral to the working of the code) — 207 if not counting the `print` and `print if` statement parts which are used for printing, but don't add to the game logic; 144 if also considering the field representation generation code as part of printing, as suggested by Yakk in the comments)
This code uses lowercase wasd for control; input must be confirmed with Enter. Tested with Perl 5.14.2.
```
($a=$==rand(79))+=($a>=($==rand(80)));
print $_=("."x80)=~s/(.{$=})./\1@/r=~s/(.{$a})./\1"/r=~s/(.{16})/\1\n/gr;
%r=qw(w s/.(.{16})@/@\1./s a s/.@/@./ s s/@(.{16})./.\1@/s d s/@./.@/);
while(/"/){print if eval $r{getc STDIN}}
```
Note that for this code, it is impossible to separate calculation and printing, since the operations are done directly on the printed representation using regular expressions.
Explanation:
```
($a=$==rand(79))+=($a>=($==rand(80)));
```
This line determines the position of the player and the amulet. The player position is determined by `$==rand(80)` and is actually easy to understand: On a 5×16 board, there are 80 distinct positions where the player can be. The position is stored in the `$=` variable which forces the stored value into integer; this saves a few bytes for not needing to explicitly cast the result to integer (`rand` delivers a floating point value).
Since one of the positions is already occupied by the player, there are only 79 positions left for the amulet, therefore for the amulet's position, `$a=$==rand(79)` is used. Again, the assignment to `$=` forces a conversion to integer, however I further assign it to `$a` in order to reuse `$=` for the player's position.
Now to avoid the amulet to occupy the same position as the player, it is advanced by one position if its position is at least as large as the player's, giving an uniform distribution on the places not occupied by the player. This is achieved by `$a = ($a >= $=)` where `$=` here holds the player's position. Now the first line is generated by inserting the two initial assignments instead of the first `$a$ and the only`$=` in this expression.
```
print $_=("."x80)=~s/(.{$=})./\1@/r=~s/(.{$a})./\1"/r=~s/(.{16})/\1\n/gr;
```
This generates the initial field, and afterwards prints is. `("."x80)` just generates a string of 80 dots. `=~s/(.{$=})./\1@/r` then replaces the `$=`th character with `@`, and `=~s/(.{$=})./\1@/r` the `$a`th character with `"`. Due to the `r` modifier they don't try to modify in place, but return the modified string, that's why they can be applied to the previous expressions. Finally, `=~s/(.{16})/\1\n/gr` inserts a newline every 16 characters. Note that the field is stored in the special variable `$_` which can be used implicitly in later statements.
```
%r=qw(w s/.(.{16})@/@\1./s a s/.@/@./ s s/@(.{16})./.\1@/s d s/@./.@/);
```
This creates a hash containing the replacement rules for the different moves. A more readable version of this is
```
%r = ( 'w' => 's/.(.{16})@/@\1./s',
'a' => 's/.@/@./',
's' => 's/@(.{16})./.\1@/s',
'd' => 's/@./.@/' );
```
The keys are the characters for the moves, and the values are strings containing the corresponding replacement rule.
```
while(/"/){print if eval"\$_=~$r{getc STDIN}"}
```
This is the main loop. `while(/"/)` checks if there is still a `"` character in `$_` (that is, in the field). If we move onto the amulet, its character gets replaced with the player character so it disappears from the field.
`eval $r{getc STDIN}` reads a character from standard input, looks up the corresponding replacement rule from the has `%r` and applies it to `$_`, that is, the field. This evaluates to true if a replacement was actually made (that is, the key was found in the hash *and* the move was possible; an impossible move won't match in the replacement rule). In that case `print` is executed. Since it is called without argument, it prints `$_`, that is, the modified field.
[Answer]
## C#, 256 248 234 227 226 225 bytes
Uses the NumPad arrows with NumLock turned on to move.
Indented and commented for clarity:
```
using System;
class P{
static void Main(){
int a=0,b=0,c,d,e;
var r=new Random();
while(0<((c=r.Next(16))&(d=r.Next(5))));
Draw(a,b,c,d); // Excluded from the score.
while(a!=c|b!=d){
e=Console.ReadKey().KeyChar-48;
a+=e==4&a>0?-1:e==6&a<15?1:0;
b+=e==8&b>0?-1:e==2&b<4?1:0;
Draw(a,b,c,d); // Excluded from the score.
}
}
// The following method is excluded from the score.
static void Draw(int a, int b, int c, int d){
Console.Clear();
for (int y = 0; y < 5; y++)
{
for (int x = 0; x < 16; x++)
{
Console.Write(
x == a && y == b ? '@' :
x == c && y == d ? '"' :
'.'
);
}
Console.WriteLine();
}
}
}
```
[Answer]
# Html+JavaScript(ES6), score maybe 217
Too looong, but playable online in the snippets below.
Line 6 (T.value ...) is for output and not counted (but for simplicity I counted the textarea open and close tags, even if it's output too)
As for randomness: the amulet is always in the right half of the grid and the player always start in the left half.
Click on the textArea (after enlarging it) to start and restart the game.
```
<textarea id=T onclick='s()' onkeyup='m(event.keyCode)'></textarea>
<script>
R=n=>Math.random()*n|0,
s=e=>m(y=R(5),x=R(8),a=R(5)*17+R(8)+8),
m=k=>(x+=(x<15&k==39)-(x>0&k==37),y+=(y<4&k==40)-(y>0&k==38),p=y*17+x,
T.value=p-a?(t=[...('.'.repeat(16)+'\n').repeat(5)],t[a]='X',t[p]='@',t.join('')):t='Well done!'
)
</script>
```
EcmaScript 6 Snippet (Firefox only)
```
R=n=>Math.random()*n|0
s=e=>m(y=R(5),x=R(8),a=R(5)*17+R(8)+8)
m=k=>(
x+=(x<15&k==39)-(x>0&k==37),
y+=(y<4&k==40)-(y>0&k==38),
p=y*17+x,
T.value=p-a?(t=[...('.'.repeat(16)+'\n').repeat(5)],t[a]='"',t[p]='@',t.join('')):t='Well done!'
)
```
```
<textarea id=T onclick='s()' onkeyup='m(event.keyCode)'></textarea>
```
EcmaScript 5 snippet (tested in Chrome)
```
function R(n) { return Math.random()*n|0 }
function s() { m(y=R(5),x=R(8),a=R(5)*17+R(8)+8) }
function m(k) {
x+=(x<15&k==39)-(x>0&k==37)
y+=(y<4&k==40)-(y>0&k==38)
p=y*17+x
T.value=p-a?(t=('.'.repeat(16)+'\n').repeat(5).split(''),t[a]='"',t[p]='@',t.join('')):t='Well done!'
}
```
```
<textarea id=T onclick='s()' onkeyup='m(event.keyCode)'></textarea>
```
[Answer]
# Actionscript 3: 267 bytes
A working example is [online](http://www.fastswf.com/iZ2UH4U)
`var a:int,p:int,t;function g(){var r=Math.random;while(p==a){a=r()*80;p=r()*80}addEventListener("keyDown",function(e){if(a==p)return;if(e.keyCode==87&&p>15)p-=16if(e.keyCode==83&&p<64)p+=16if(e.keyCode==65&&p%16>0)p--if(e.keyCode==68&&(p+1)%16>0)p++print()});print()}`
Here's a complete (whitespaces included for readability) program using the game function:
```
package
{
import flash.display.Sprite;
import flash.text.TextField;
import flash.text.TextFormat;
public class MiniRogue extends Sprite
{
var a:int, p:int, t;
public function MiniRogue()
{
g();
}
function g(){
var r=Math.random;
while(p==a){
a=r()*80;
p=r()*80
}
addEventListener("keyDown",function(e){
if(a==p)
return;
if(e.keyCode==87&&p>15)
p-=16
if(e.keyCode==83&&p<64)
p+=16
if(e.keyCode==65&&p%16>0)
p--
if(e.keyCode==68&&(p+1)%16>0)
p++
print()
});
print()
}
var old:int = -1;
private function print():void {
if (!t) {
t = new TextField()
t.defaultTextFormat = new TextFormat("_typewriter", 8)
t.width=500;
t.height=375;
addChild(t)
}
var board:String = "";
for (var i:int=0; i<80;i++) {
if (i == p) {
board += "@";
} else if (i == a) {
board += '"';
} else {
board += ".";
}
if ((i + 1) % 16 == 0) {
board += "\n";
}
}
if (a==p) {
board += "Win!";
}
if (p == old) {
board += "Bump!";
}
old = p;
t.text = board;
}
}
}
```
[Answer]
# Javascript: 307 216
You can play in the snippet below!
The numbers on the left are just so the console (chrome one at least) doesn't merge the rows.
To run the code:
1. hit "run code snippet"
2. hit ctrl-shift-j to open the console
3. click in the result section
4. use arrow keys and play
```
var x=y=2,m=Math,b=m.floor(m.random()*5),a=14,i,j,t,c=console,onload=d;function d(){c.clear();for(i=0;i<5;i++){t=i;for(j=0;j<16;j++){t+=(i==y&&j==x)?"@":(i==b&&j==a)?'"':".";if(a==x&&b==y)t=":)";}c.log(t);}}onkeydown=function(){switch(window.event.keyCode){case 37:if(x>0)x--;break;case 38:if(y>0)y--;break;case 39:if(x<15)x++;break;case 40:if(y<4)y++;break;}d();};
```
Un-golfed:
```
var px=py=2,m=Math,ay=m.floor(m.random()*5),ax=14,i,j,t,c=console,onload=draw;
function draw() {
c.clear();
for(i=0;i<5;i++) {
t=i;
for(j=0;j<16;j++) {
t+=(i==py&&j==px)?"@":
(i==ay&&j==ax)?'"':".";
if(ax==px&&ay==py)t=":)";
}
c.log(t);
}
}
onkeydown=function() {
switch (window.event.keyCode) {
case 37:
if(px>0)px--;
break;
case 38:
if(py>0)py--;
break;
case 39:
if(px<15)px++;
break;
case 40:
if(py<4)py++;
break;
}
draw();
};
```
**Edit 1:** Read rules more carefully and rewrote my code accordingly
* amulet y value is now randomized
* player can no longer escape room
* I no longer count the characters in the draw function or calls to it
[Answer]
# SpecBAS - ~~428~~ 402 (excluding printing, ~~466~~ 425 when counted)
Uses Q/A/O/P to move up/down/left/right respectively.
The line to print the dungeon at line 1 is the only line that can be ignored, but have golfed that down a bit as well.
```
1 PRINT ("."*16+#13)*5
2 LET px=8: LET py=3
3 LET ax=INT(RND*16): LET ay=INT(RND*5): IF ax=px AND ay=py THEN GO TO 3
4 PRINT AT ay,ax;#34;AT py,px;"@": LET ox=px: LET oy=py: PAUSE 0: LET k$=INKEY$
5 LET px=px+(k$="p")-(k$="o")
6 IF px<0 THEN LET px=0
7 IF px>15 THEN LET px=15
8 LET py=py+(k$="a")-(k$="q")
9 IF py<0 THEN LET py=0
10 IF py>4 THEN LET py=4
11 PRINT AT oy,ox;"."
12 IF SCREEN$(px,py)<>#34 THEN GO TO 4
```
The reference to #34 is just a short-hand way of putting CHR$(34) in the code.
Thanks @Thomas Kwa, I hadn't noticed player start position being random was optional. Also used separate IF statements to shave off a few characters.
[Answer]
## Another C#, ~~221~~ ~~171~~ 170
Here is another way in C# with both positions random. Wanted to show this even if this part is 7 bytes longer than Hand-E-Food's solution.
Hand-E-Food's answer will be shorter of course as soon as he will use Console.Read().
The downside of Consol.Read is, that pressing the needed Enter causes the field to be printed 2 more times.
But I don't think there is a requirement to print just on (real) input.
Navigation is done by 8426 as in Hand-E-Foods solution.
```
using System;
class P
{
static void Main()
{
Func<int> n=new Random().Next;
int x=n()%16,y=n()%5,a=n()%16,b,m;
while(y==(b=n()%5));
while(x!=a|y!=b)
{
Printer.Print(a, b, x, y); // Excluded from the score.
m=Console.Read()-48;
y+=m==8&y>0?-1:m==2&y<4?1:0;
x+=m==4&x>0?-1:m==6&x<15?1:0;
}
}
}
```
**Edit:** (added new solution and moved PrinterClass to the end)
**Edit2:** (changed a 14 to a 15 and saved the byte by starting on right-bottom)
Adapting the technique of Mauris it is possible to melt it down to 171 bytes in C# (of course now without both positions random):
```
using System;
class P
{
static void Main()
{
int p=79,a=new Random().Next()%p,m;
while(p!=a){
Printer.Print(p,a); // Excluded from the score.
m=Console.Read()-48;
p+=m==4&p/5>0?-5:m==6&p/5<15?5:m==8&p%5>0?-1:m==2&p%5<4?1:0;
}
}
}
```
The Printer Class is nearly the same, just a new overload of print...
```
class Printer
{
public static void Print(int ax, int ay, int px, int py)
{
Console.Write('\n');
for (int y = 0; y < 5; y++)
{
for (int x = 0; x < 16; x++)
{
if (x == px && y == py)
Console.Write('@');
else if (x == ax && y == ay)
Console.Write('"');
else
Console.Write('.');
}
Console.Write('\n');
}
}
public static void Print(int p, int a)
{
Print(p/5,p%5,a/5,a%5);
}
}
```
[Answer]
## Ruby, 185
Here is a Ruby example too.
I'm very new to Ruby, maybe someone knows how to do that better :)
I have counted lineFeeds as 1 since the Program will crash otherwise...
Navigation is done by 8462. You need to send input each time with enter.
```
def display(ax,ay,px,py)
puts
for y in 0..4
for x in 0..15
if (x == px && y == py)
print "@"
elsif (x == ax && y == ay)
print '"'
else
print '.'
end
end
puts
end
end
x=y=0
a=Random.rand(16) while y==(b=Random.rand(5))
while x!=a or y!=b
display(a,b,x,y) # Excluded from the score.
m=gets.chomp.to_i
y-=m==8?1:0 if y>0
y+=m==2?1:0 if y<4
x-=m==4?1:0 if x>0
x+=m==6?1:0 if x<15
end
```
[Answer]
# QBasic, 103 bytes
Per the rules of the challenge, the `Show` subprogram is not included in the byte-count, nor is the `Show p, q, a, b` call (with the following newline).
```
b=1+TIMER MOD 9
1Show p, q, a, b
INPUT m
p=p-(m=2)*(p>0)+(m=4)*(p<4)
q=q-(m=1)*(q>0)+(m=3)*(q<15)
IF(p<>a)+(q<>b)GOTO 1
SUB Show (playerRow, playerCol, amuletRow, amuletCol)
CLS
FOR row = 0 TO 4
FOR col = 0 TO 15
IF row = playerRow AND col = playerCol THEN
PRINT "@";
ELSEIF row = amuletRow AND col = amuletCol THEN
PRINT CHR$(34); ' Double quote mark
ELSE
PRINT ".";
END IF
NEXT
PRINT
NEXT
END SUB
```
To move, input a number and press Enter: `1` to go left, `2` to go up, `3` to go right, and `4` to go down.
This code does not output the game state at the end, when the player has found the amulet. To make it do so, add another `Show p, q, a, b` after the `IF` statement.
## Explanation
Let `a`, `b` represent the coordinates of the amulet and `p`, `q` the coordinates of the player. The player starts at (0, 0), and the amulet starts on row 0, with a column between 1 and 9, inclusive, based on the 1's digit of the current time.
The rest is just a bunch of math with conditionals. The important thing to remember is that conditionals in QBasic return `0` for false, `-1` for true. Let's look at the player row update statement:
```
p=p-(m=2)*(p>0)+(m=4)*(p<4)
```
If `m=2`, we want to move up by subtracting 1 from `p`, as long as `p>0`. Similarly, if `m=4`, we want to move down by adding 1 to `p`, as long as `p<4`. We can obtain the desired behavior by multiplying. If both factors are `-1`, their product will be `1`, which we can subtract from or add to `p`. If either conditional is `0`, the product will be `0`, with no effect.
Similarly, the condition to determine whether the player has found the amulet is:
```
IF(p<>a)+(q<>b)GOTO 1
```
If either of the conditionals is true, their sum will be nonzero (either `-1` or `-2`) and thus truthy, and the program returns to line 1. Once `p` equals `a` and `q` equals `b`, both conditionals will be `0`, so their sum will be `0` and control flow can reach the end of the program.
] |
[Question]
[
### Task
Write a program that reads three integers **m**, **n** either from STDIN or as command-line arguments, prints all possible tilings of a rectangle of dimensions **m × n** by **2 × 1** and **1 × 2** dominos and finally the number of valid tilings.
Dominos of an individual tiling have to be represented by two dashes (`-`) for **2 × 1** and two vertical bars (`|`) for **1 × 2** dominos. Each tiling (including the last one) has to be followed by a linefeed.
For scoring purposes, you also have to accept a flag from STDIN or as command line argument that makes your program print only the number of valid tilings, but not the tilings itself.
Your program may not be longer than 1024 bytes. It has to work for all inputs such that **m × n ≤ 64**.
(Inspired by [Print all domino tilings of 4x6 rectangle](https://codegolf.stackexchange.com/q/37988).)
### Example
```
$ sdt 4 2
----
----
||--
||--
|--|
|--|
--||
--||
||||
||||
5
$ sdt 4 2 scoring
5
```
### Scoring
Your score is determined by the execution time of your program for the input **8 8** with the flag set.
To make this a *fastest code* rather than a *fastest computer* challenge, I will run all submissions on my own computer (Intel Core i7-3770, 16 GiB PC3-12800 RAM) to determine the official score.
Please leave detailed instructions on how to compile and/or execute your code. If you require a specific version of your language's compiler/interpreter, make a statement to that effect.
I reserve the right to leave submissions unscored if:
* There is no free (as in beer) compiler/interpreter for my operating system (Fedora 21, 64 bits).
* Despite our efforts, your code doesn't work and/or produces incorrect output on my computer.
* Compilation or execution take longer than an hour.
* Your code or the only available compiler/interpreter contain a system call to `rm -rf ~` or something equally fishy.
### Leaderboard
I've re-scored all submissions, running both compilations and executions in a loop with 10,000 iterations for compilation and between 100 and 10,000 iterations for execution (depending on the speed of the code) and calculating the mean.
These were the results:
```
User Compiler Score Approach
jimmy23013 GCC (-O0) 46.11 ms = 1.46 ms + 44.65 ms O(m*n*2^n) algorithm.
steveverrill GCC (-O0) 51.76 ms = 5.09 ms + 46.67 ms Enumeration over 8 x 4.
jimmy23013 GCC (-O1) 208.99 ms = 150.18 ms + 58.81 ms Enumeration over 8 x 8.
Reto Koradi GCC (-O2) 271.38 ms = 214.85 ms + 56.53 ms Enumeration over 8 x 8.
```
[Answer]
# C
A straightforward implementation...
```
#include<stdio.h>
int a,b,c,s[65],l=0,countonly;
unsigned long long m=0;
char r[100130];
void w(i,x,o){
int j,k;
j=(1<<b)-1&~x;
if(i<a-1){
s[i+1]=j;
w(i+1,j,1);
for(k=j&j/2&-o;j=k&-k;k&=~j)
w(i,x|3*j,j);
}
else if((j/3|j/3*2)==j)
if(countonly)
m++;
else{
if(c==b)
for(k=0;k<b;r[k++,l++]=10)
for(j=0;j<a;j++)
r[l++]=45+79*!((s[j]|s[j+1])&(1<<k));
else
for(j=0;j<a;r[j++,l++]=10)
for(k=0;k<b;k++)
r[l++]=124-79*!((s[j]|s[j+1])&(1<<k));
r[l++]=10;
if(l>=100000){
fwrite(r,l,1,stdout);
l=0;
}
}
}
int main(){
scanf("%d %d %d",&a,&b,&countonly);
c=b;
if(a<b){a^=b;b^=a;a^=b;}
s[0]=s[a]=0;
w(0,0,1);
if(countonly)
printf("%llu\n",m);
else if(l)
fwrite(r,l,1,stdout);
}
```
### The cheating version
```
#include<stdio.h>
#include<string.h>
int a,b,c,s[65],l=0,countonly;
unsigned long long m=0,d[256];
char r[100130];
void w2(){
int i,j,k,x;
memset(d,0,sizeof d);
d[0]=1;
j=0;
for(i=0;i<a-1;i++){
for(k=1;k<(1<<(b-1));k*=2)
for(x=0;x<(1<<(b-2));x++)
d[(x+x/k*k*3+k*3)^j]+=d[(x+x/k*k*3)^j];
j^=(1<<b)-1;
}
for(x=0;x<(1<<b);x++)
if((x/3|x/3*2)==x)
m+=d[x^((1<<b)-1)^j];
printf("%llu\n",m);
}
void w(i,x,o){
int j,k;
j=(1<<b)-1&~x;
if(i<a-1){
s[i+1]=j;
w(i+1,j,1);
for(k=j&j/2&-o;j=k&-k;k&=~j)
w(i,x|3*j,j);
}
else if((j/3|j/3*2)==j){
if(c==b)
for(k=0;k<b;r[k++,l++]=10)
for(j=0;j<a;j++)
r[l++]=45+79*!((s[j]|s[j+1])&(1<<k));
else
for(j=0;j<a;r[j++,l++]=10)
for(k=0;k<b;k++)
r[l++]=124-79*!((s[j]|s[j+1])&(1<<k));
r[l++]=10;
if(l>=100000){
fwrite(r,l,1,stdout);
l=0;
}
}
}
int main(){
scanf("%d %d %d",&a,&b,&countonly);
c=b;
if(a<b){a^=b;b^=a;a^=b;}
s[0]=s[a]=0;
if(countonly)
w2();
else{
w(0,0,1);
if(l)
fwrite(r,l,1,stdout);
}
}
```
### Explanation of the faster algorithm
It scans from left to right, and maintain the state `d[i][j]`, where:
* `i` is in `[0,m)`, which means the current column.
* `j` is a bit vector of size `n`, where the bit would be 1 if the corresponding position in column `i` is already occupied before starting working on this column. I.e. it is occupied by the right half of a `--`.
* `d[i][j]` is the total number of different tilings.
Then say `e[i][j]` = the sum of `d[i][k]` where you can put vertical dominoes base on `k` to form a `j`. `e[i][j]` would be the number of tilings where each 1 bit in `j` is occupied by anything but the left half of a `--`. Fill them with `--` and you'll get `d[i+1][~j]` = `e[i][j]`. `e[m-1][every bit being 1]` or `d[m][0]` is the final answer.
A naive implementation will get you the time complexity somewhere near `g[n]=2*g[n-1]+g[n-2] = O((sqrt(2)+1)^n)` (already fast enough if n=m=8). But you can instead firstly loop for each possible domino, and try to add it to every tiling that can have this domino added, and merge the result to the original array `d` (like the algorithm for the Knapsack problem). And this becomes O(n\*2^n). And everything else are implementation details. The whole code runs in O(m\*n\*2^n).
[Answer]
# C
After a round of optimizations, and adapted for the modified rules:
```
typedef unsigned long u64;
static int W, H, S;
static u64 RM, DM, NSol;
static char Out[64 * 2 + 1];
static void place(u64 cM, u64 vM, int n) {
if (n) {
u64 m = 1ul << __builtin_ctzl(cM); cM -= m;
if (m & RM) {
u64 nM = m << 1;
if (cM & nM) place(cM - nM, vM, n - 1);
}
if (m & DM) {
u64 nM = m << W;
vM |= m; vM |= nM; place(cM - nM, vM, n - 1);
}
} else if (S) {
++NSol;
} else {
char* p = Out;
for (int y = 0; y < H; ++y) {
for (int x = 0; x < W; ++x) { *p++ = vM & 1 ? '|' : '-'; vM >>= 1; }
*p++ = '\n';
}
*p++ = '\0';
puts(Out);
++NSol;
}
}
int main(int argc, char* argv[]) {
W = atoi(argv[1]); H = atoi(argv[2]); S = (argc > 3);
int n = W * H;
if (n & 1) return 0;
for (int y = 0; y < H; ++y) {
RM <<= W; RM |= (1ul << (W - 1)) - 1;
}
DM = (1ul << (W * (H - 1))) - 1;
place(-1, 0, n >> 1);
printf("%lu\n", NSol);
return 0;
}
```
I started bumping into the length limit of 1024 characters, so I had to reduce the readability somewhat. Much shorter variable names, etc.
Build instructions:
```
> gcc -O2 Code.c
```
Run with solution output enabled:
```
> ./a.out 8 8 >/dev/null
```
Run with only solution count:
```
> ./a.out 8 8 s
```
Some comments:
* With the larger test example, I do want optimization now. While my system is different (Mac), around `-O2` seems to be good.
* The code has gotten slower for the case where output is generated. This was a conscious sacrifice for optimizing the "count only" mode, and for reducing the code length.
* There will be a few compiler warnings because of missing includes and external declarations for system functions. It was the easiest way to get me to below 1024 characters in the end without making the code totally unreadable.
Also note that the code still generates the actual solutions, even in "count only" mode. Whenever a solution is found, the `vM` bitmask contains a `1` for the positions that have a vertical bar, and a `0` for positions with a horizontal bar. Only the conversion of this bitmask into ASCII format, and the actual output, is skipped.
[Answer]
# C
The concept is to first find all possible arrangements of horizontal dominoes in a row, store them in `r[]` and then organize them to give all possible arrangements of vertical dominoes.
The code for positioning the horizontal dominoes in a row is modified from this answer of mine: <https://codegolf.stackexchange.com/a/37888/15599>. It's slow for the wider grids but that isn't a problem for the 8x8 case.
The innovation is in the way the rows are assembled. If the board has an odd number of rows it is turned through 90 degrees in the input parsing, so it now has an even number of rows. Now I place some vertical dominoes across the centreline. Because of symmetry, if there are `c` ways of arranging the remaining dominoes in the bottom half, there must also be `c` ways of arranging the remaining dominoes in the top half, meaning that for a given arrangement of vertical dominoes on the centreline, there are `c*c` possible solutions. Therefore only the centreline plus one half of the board is analysed when the program is required to print only the number of solutions.
`f()` builds the table of possible arrangements of horizontal dominoes, and scans through the possible arrangements of vertical dominoes on the centreline. it then calls recursive function `g()` which fills in the rows. If printing is required, function `h()` is called to do this.
`g()` is called with 3 parameters. `y` is the current row and `d` is the direction (up or down) in which we are filling the board from the centre outwards. `x` contains a bitmap indicates the vertical dominoes that are incomplete from the previous row. All possible arrangements of dominoes in a row from r[] are tried. In this array, a 1 represents a vertical domino and a pair of zeroes a horizontal domino. A valid entry in the array must have at least enough 1's to finish any incomplete vertical dominoes from the last row: `(x&r[j])==x`. It may have more 1's which indicates that new vertical dominoes are being started. For the next row, then, we need only the new dominoes so we call the procedure again with `x^r[j]`.
If an end row has been reached and there are no incomplete vertical dominoes hanging of the top or bottom of the board `x^r[j]==0` then the half has been succesfully completed. If we are not printing, it is sufficient to complete the bottom half and use `c*c` to work out the total number of arrangements. If we are printing, it will be necessary to complete also the top half and then call the printing function `h()`.
**CODE**
```
unsigned int W,H,S,n,k,t,r[1<<22],p,q[64];
long long int i,c,C;
//output: ascii 45 - for 0, ascii 45+79=124 | for 1
h(){int a;
for(a=n;a--;a%W||puts(""))putchar(45+(q[a/W]>>a%W)%2*79);
puts("");
}
g(y,d,x){int j;
for(j=0;j<p;j++)if((x&r[j])==x){
q[y]=r[j];
if(y%(H-1)==0){
(x^r[j])==0?
y?c++,S||g(H/2-1,-1,i):h()
:0;
}else{
g(y+d,d,x^r[j]);
}
}
}
e(z){int d;
for(d=0;z;d++)z&=z-1;return n/2+1+d&1;
}
f(){
//k=a row full of 1's
k=(1ULL<<W)-1;
//build table of possible arrangements of horizontal dominoes in a row;
//flip bits so that 1=a vertical domino and save to r[]
for(i=0;i<=k;i++)(i/3|i/3<<1)==i?r[p++]=i^k:0;
//for each arrangement of vertical dominoes on the centreline, call g()
for(i=0;i<=k;i++)e(i)?c=0,g(H/2,1,i),C+=c*c:0;
printf("%llu",C);
}
main(int argc, char* argv[]) {
W = atoi(argv[1]); H = atoi(argv[2]); S = (argc > 3);
1-(n=W*H)%2?
H%2?W^=H,H^=W,W^=H,t=1:0,f()
:puts("0");
}
```
Note that input with an odd number of rows and even number of columns is turned though 90 degrees in the parsing phase. If this is unacceptable, the printing function `h()` can be changed to accomodate it. (EDIT: not required, see comments.)
EDIT: A new function `e()` has been used to check the parity of `i` (i.e the number of dominoes straddling the centreline.) The parity of `i` (the number of half-dominoes on the centreline protruding into each half of the board) must be the same as the oddness of the total number of spaces in each half (given by `n/2`) because only then can the dominoes fill all available space. This edit eliminates half the values of i and therefore makes my program approximately twice as fast.
] |
[Question]
[
This problem is from [Five programming problems every Software Engineer should be able to solve in less than 1 hour](https://blog.svpino.com/2015/05/07/five-programming-problems-every-software-engineer-should-be-able-to-solve-in-less-than-1-hour) which itself is an interesting read. The first few problems are trivial, but the fourth one can be a bit more interesting.
>
> Given a list of integers separated by a single space on standard input, print out the largest and smallest values that can be obtained by concatenating the integers together on their own line.
>
>
>
For example:
Input:
```
5 56 50
```
Output:
```
50556
56550
```
Various points of order:
* The order of the results are smallest then largest.
* *Only* the smallest and largest values may be printed out (iterating over all the variations and printing them out isn't valid).
* There will always be two or more integers in the list.
* It is possible for the largest and smallest results to be the same. In the case of input `5 55`, the number `555` should be printed twice.
* The integers are not necessarily distinct. `5 5` is valid input.
* Leading `0`s on integers are ***not*** valid input. You will ***not*** need to account for `05 55`.
As this is code golf, shortest entry wins.
[Answer]
# CJam, ~~14~~ 13 bytes
```
qS/e!:s$(N@W=
```
Pretty straight forward. This is how it works:
```
qS/ e# Split the input on spaces
e! e# Get all permutations of the input numbers
:s e# Join each permutation order into a single string
$ e# Sort them. This sorts the strings based on each digit's value
(N@W= e# Choose the first and the last out of the array separated by '\n'
```
[Try it online here](http://cjam.aditsu.net/#code=qS%2Fe!%3As%24(N%40W%3D&input=5%2056%2050)
[Answer]
# Pyth, 14 13 bytes
```
hJSmsd.pcz)eJ
```
Generates all permutations and sorts them, printing the first and last element.
[Answer]
# Python 2, ~~104~~ 99 bytes
Yep.
```
from itertools import*;z=[''.join(x)for x in permutations(raw_input().split())];print min(z),max(z)
```
Edit: thanks to xnor for -5 bytes!
[Answer]
# Mathematica, ~~64~~ 58 bytes
```
Print/@Sort[""<>#&/@Permutations@StringSplit@#][[{1,-1}]]&
```
This defines an unnamed function taking a string and printing the two lines. It's pretty straightforward as the others: get all permutations, join them together, sort them and print the first and last result.
Six bytes saved thanks to alephalpha.
[Answer]
# JavaScript (ES6) ~~54 72~~ 85
~~That's easier than it seems. Just sort them lexicographically. The good news is: that's exactly how plain javascript sort works.~~Well ... no, that's wrong ... still a (more convoluted) lexicograph compare can do the job.
Note: having a and b numeric, a+[b] is a shortcut for a+''+b, as we need a string concatenation and not a sum.
Note 2: the newline inside `` is significant and must be counted
**Edit** Don't argue with a moderator (...just kidding)
**Edit2** Fixed I/O format using popups (see [Default for Code Golf: Input/Output methods](http://meta.codegolf.stackexchange.com/a/2459/21348))
```
// Complete program with I/O
// The sorting function is shorter as input are strings
alert((l=prompt().split(' ')).sort((a,b)=>a+b>b+a).join('')+`
`+l.reverse().join(''))
// Testable function (67 chars)
// With an integer array parameter, the sorting function must convert to string
F=l=>(l.sort((a,b)=>a+[b]>b+[a]).join('')+`
`+l.reverse().join(''))
```
**Test** In Firefox / FireBug console
```
F([50, 2, 1, 9])
F([5,56,50])
F([52,36,526])
F([52,36,525])
F([52,36,524]
```
>
> 12509
>
> 95021
>
>
> 50556
>
> 56550
>
>
> 3652526
>
> 5265236
>
>
> 3652525
>
> 5255236
>
>
> 3652452
>
> 5252436
>
>
>
[Answer]
## J, 34 ~~36~~, ~~42~~ bytes
simple brute force:
```
h=:3 :'0 _1{/:~;"1":&.>y A.~i.!#y'
h 5 50 56
50556
56550
h 50 2 1 9
12509
95021
```
[Answer]
# Haskell, 98 bytes
```
import Data.List
g=sort.map concat.permutations.words
h i=unlines[g i!!0,last$g i]
main=interact h
```
Split input string at spaces, concatenate every permutation and sort. Print first and last element.
[Answer]
# Julia, 77 bytes
```
v->(Q=extrema([int(join(x)) for x in permutations(v)]);print(Q[1],"\n",Q[2]))
```
This creates an unnamed function that accepts a vector as input and prints the minimum and maximum of the permutations of the joined elements. To call it, give it a name, e.g. `f=v->...`.
Ungolfed + explanation:
```
function f(v)
# Create an integer vector of the joined permutations using comprehension,
# then get the minimum and maximum as a tuple using extrema().
Q = extrema([int(join(x)) for x in permutations(v)])
# Print the minimum and the maximum, separated by a newline.
print(Q[1], "\n", Q[2])
end
```
Suggestions are welcome!
[Answer]
# Javascript (*ES6*) 134
Sadly, there's no built-in permutation function in JS :(
```
f=(o,y,i,a)=>y?o.concat(a[1]?a.filter((k,j)=>j^i).reduce(f,[]).map(z=>y+z):y):(q=o.split(' ').reduce(f,[])).sort().shift()+`
`+q.pop()
```
```
<!-- Snippet Demo (Firefox only) -->
<input id="input" value="5 56 50" />
<input type="button" onclick="output.innerHTML=f(input.value)" value="Run" />
<pre id="output"></pre>
```
[Answer]
## R, 59 bytes
```
write(range(combinat:::permn(scan(),paste,collapse="")),"")
```
[Answer]
# Ruby 75
Not my 'native' language, but one I thought I'd give a try at... thus this could (possibly) use some golfing tips. Still, not a bad entrant.
```
puts STDIN.read.split(" ").permutation.map{|x|x.join}.sort.values_at(0,-1)
```
I wouldn't say it is *elegant* other that everything is built in to the language. It should be fairly obvious exactly how this works.
[Answer]
# Perl, ~~79~~ 70B (68+2)
`use Math::Combinatorics;say for(sort map{join'',@$_}permute@F)[0,-1]`
Call with `echo 13 42 532 3 6|perl -M5.10.0 -an scratch.pl`. There's a +2 byte penalty for `-an`. Shame about the length of the module name...
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
#œJ{¬sθ»
```
[Try it online.](https://tio.run/##yy9OTMpM/f9f@ehkr@pDa4rP7Ti0@/9/UwVTMwVTAwA)
**Explanation:**
```
# # Split the (implicit) input by spaces
œ # Get all permutations of this list
J # Join each permutation together to a single string
{ # Sort this list
¬ # Push the first item (without popping the list)
s # Swap to get the list again
θ # Pop and push its last item
» # And join all (both) values on the stack by newlines
# (after which the result is output implicitly)
```
[Answer]
# [Scala](http://www.scala-lang.org/), 90 bytes
```
val x=Console.in.readLine.split(" ").permutations.map(_.mkString).toSeq
print(x.min,x.max)
```
[Try it online!](https://tio.run/##DYrLCsIwEADvfsXSUwqy4NsePEiv3voBsjZrieZls0pA/PYYBgYGJo1kqYTbg0eBPmiegr0DZ2GvE5xjhG/5kIV86oNPwTIajzOTvhjPmKI1ohpoWow8u7eQmLqho6iu6J6DzMZPLUoY@LWINURldMYvqym35Vc6WG@2sIIdHI6wr3R/ "Scala – Try It Online")
[Answer]
# JavaScript (ES6), 85 bytes
```
F=a=>(c=a.split(" ").sort((b,a)=>b+a-(a+b)),`${c.join("")}
${c.reverse().join("")}`)
```
**usage:**
```
F("50 2 1 9")
/*
12509
95021
*/
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 11 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ú∙n90≤╣*.vâ
```
[Run and debug it](https://staxlang.xyz/#c=L%7CT%7B%24mc%7CmP%7CMp&i=5+56+50)
Link is to unpacked version of code.
## Explanation
```
L|T{$mc|MP|mp implicit input
L put all inputs in a list
|T get the unique orders of the list of inputs
{$m convert each list to string
c duplicate the array of strings
|mP print the minimum element
|mp print the maximum element
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
Œ!VṢ.ị
```
[Try it online!](https://tio.run/##y0rNyan8///oJMWwhzsX6T3c3f3/cPujpjX//0eb6iiYmgGxQawOAA "Jelly – Try It Online")
Input and output as lists of integers. [+3 bytes](https://tio.run/##ASkA1v9qZWxsef//4biyxZIhVlbhuaIu4buLWf/Dh@KCrP//IjUgNTYgNTAiLA) to input with spaces and output with newlines
## How it works
```
Œ!VṢ.ị - Main link. Takes a list L on the left e.g. [5, 56, 50]
Œ! - All permutations of L [[5, 56, 50], [5, 50, 56], [56, 5, 50], [56, 50, 5], [50, 5, 56], [50, 56, 5]]
V - Concatenate each into numbers [55650, 55056, 56550, 56505, 50556, 50565]
Ṣ - Sort [50556, 50565, 55056, 55650, 56505, 56550]
.ị - Take the first and last elements [56550, 50556]
```
] |
[Question]
[
Here is a simple [ASCII art](http://en.wikipedia.org/wiki/ASCII_art) snowman:
```
_===_
(.,.)
( : )
( : )
```
Let's make him some friends. This will be the general pattern for our ASCII art snowpeople:
```
HHHHH
HHHHH
X(LNR)Y
X(TTT)Y
(BBB)
```
The leading spaces and the parentheses are always the same for all snowpeople. The different letters represent sections of the pattern that can individually change. Each section has exactly four presets for what ASCII characters can fill it.
By mixing and matching these presets for all eight sections, we can make a variety of snowpeople.
# All Presets
(Notice that spaces are put on otherwise empty lines so the section shape is always correct.)
### H is for Hat
1. Straw Hat
```
_===_
```
2. Mexican Hat
```
___
.....
```
3. Fez
```
_
/_\
```
4. [Russian Hat](http://en.wikipedia.org/wiki/Ushanka)
```
___
(_*_)
```
### N is for Nose/Mouth
1. Normal `,`
2. Dot `.`
3. Line `_`
4. None
### L is for Left Eye
1. Dot `.`
2. Bigger Dot `o`
3. Biggest Dot `O`
4. Closed `-`
### R is for Right Eye
(Same list as left eye.)
### X is for Left Arm
1. Normal Arm
```
<
```
2. Upwards Arm
```
\
```
3. Downwards Arm
```
/
```
4. None
```
```
### Y is for Right Arm
1. Normal Arm
```
>
```
2. Upwards Arm
```
/
```
3. Downwards Arm
```
\
```
4. None
```
```
### T is for Torso
1. Buttons `:`
2. Vest `] [`
3. Inward Arms `> <`
4. None
### B is for Base
1. Buttons `:`
2. Feet `" "`
3. Flat `___`
4. None
# Challenge
Write a program that takes in an eight character string (via stdin or command line) in the format `HNLRXYTB`, where each letter is a digit from 1 to 4 that denotes which preset to use for the corresponding section of the snowperson. Print the full snowperson to stdout.
For example, the input `11114411` is the snowman at the top of the page. (First `1`: he has a straw hat, second `1`: he has a normal nose, etc.)
Another example, the snowperson for input `33232124`:
```
_
/_\
\(o_O)
(] [)>
( )
```
# Details
* Any amounts and combinations of leading/trailing spaces and leading/trailing newlines are allowed as long as...
+ the snowperson has all their sections arranged correctly with respect to one another, and
+ there are never more than 64 total whitespace characters (the general pattern is only 7×5, so you probably won't hit this limit).You don't need to print rows/columns of the pattern if they only contain whitespace. e.g. the empty line of the straw hat is not required.
* You must use the ordering of the parts as they are given above.
* Instead of a program, you may write a function that takes the digit string as an argument. The output should be printed normally or returned as a string.
* You may treat the input as an integer instead of a string if preferred.
# Scoring
The shortest code in bytes wins.
***Bonus question:*** Which of the 65536 distinct snowpeople is your favorite?
[Answer]
# JavaScript ES6, 210 208 202 bytes
```
s=>` 0
8(213)9
4(6)5
(7)`.replace(/\d/g,p=>`_===_1 ___
.....1 _
/_\\1 ___
(_*_)1,1.1_11.1o101-1.1o101-1<11/11>11\\11 : 1] [1> <1 1 : 1" "1___1 11\\11 11/11 `.split(1)[s[p>7?p-4:p]-1+p*4]||' ')
```
This is an anonymous function; you use it by executing `([function code])('42232124')`. The most aggravating part of this was the arms, which take up 2 lines, so I had to include code for both top and bottom.
The Stack Snippet below has ungolfed, un-ES6-ified, commented code. And you can use it to easily test the code and try out different combinations. **Edit:** I'm having way too much fun with this. I've added several new features, including a way to generate a random snowman.
Thanks to Yair Rand for saving six bytes.
```
var f=function(s){
return' 0\n8(213)9\n4(6)5\n (7)' // Start with a placeholder string with all the static components
.replace(/\d/g,function(p){ // Go through each placeholder number to replace it with its value
// The massive string below holds all the possible body parts, separated by 1 for easy splitting.
// The two at the end are for the top of the arms
return'_===_1 ___\n .....1 _\n /_\\1 ___\n (_*_)1,1.1_11.1o101-1.1o101\
-1<11/11>11\\11 : 1] [1> <1 1 : 1" "1___1 11\\11 11/11 '.split(1)
[s[p>7?p-4:p]-1 // Get the value from the input string. If the current body part
// is the top of the two-line arms (8 or 9), drop it down to 4 or 5
// Subtract 1 to account for the 0-indexed array.
+p*4] // multiply by 4 to skip to the relevant code
||' ' // To save bytes in the above string, spaces are empty strings, so replace them here
})
}
// Code for the interactive version follows
// http://codepen.io/hsl/pen/bdEgej
function updateRadios(){$('input[type="radio"]').each(function(){if($(this).is(":checked")){var t=$(this).data("p"),i=$(this).data("v");input[t]=i}}),inputS=input.join(""),update()}var input=[],inputS=$("#code").val(),update=function(){$("#p").text(f(inputS)),$("#code").val(inputS)};$('input[type="radio"]').change(updateRadios),$("#code").keyup(function(){inputS=$(this).val(),update()}),updateRadios(),$("#random").click(function(){for(var t=0;8>t;t++)$("div:eq("+t+") input:eq("+Math.floor(4*Math.random())+")").prop("checked",!0);updateRadios()});
```
```
body{font-family:sans-serif}h2{font-size:18px;font-weight:400}label{display:block}div{display:inline-block;margin:0 10px}#code{width:70px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div><h2>Hat</h2><label><input type="radio" name="p1" data-p="1" data-v="1"> Straw hat</label><label><input type="radio" name="p1" data-p="1" data-v="2"> Mexican hat</label><label><input type="radio" name="p1" data-p="1" data-v="3"> Fez</label><label><input type="radio" name="p1" data-p="1" data-v="4" checked> Russian hat</label></div><div><h2>Nose/mouth</h2><label><input type="radio" name="p2" data-p="2" data-v="1"> Normal</label><label><input type="radio" name="p2" data-p="2" data-v="2" checked> Dot</label><label><input type="radio" name="p2" data-p="2" data-v="3"> Line</label><label><input type="radio" name="p2" data-p="2" data-v="4"> None</label></div><div><h2>Left eye</h2><label><input type="radio" name="p3" data-p="3" data-v="1"> Dot</label><label><input type="radio" name="p3" data-p="3" data-v="2" checked> Bigger dot</label><label><input type="radio" name="p3" data-p="3" data-v="3"> Biggest dot</label><label><input type="radio" name="p3" data-p="3" data-v="4"> Closed</label></div><div><h2>Right eye</h2><label><input type="radio" name="p4" data-p="4" data-v="1"> Dot</label><label><input type="radio" name="p4" data-p="4" data-v="2"> Bigger dot</label><label><input type="radio" name="p4" data-p="4" data-v="3" checked> Biggest dot</label><label><input type="radio" name="p4" data-p="4" data-v="4"> Closed</label></div><div><h2>Left arm</h2><label><input type="radio" name="p5" data-p="5" data-v="1"> Normal</label><label><input type="radio" name="p5" data-p="5" data-v="2" checked> Upwards</label><label><input type="radio" name="p5" data-p="5" data-v="3"> Downwards</label><label><input type="radio" name="p5" data-p="5" data-v="4"> None</label></div><div><h2>Right arm</h2><label><input type="radio" name="p6" data-p="6" data-v="1" checked> Normal</label><label><input type="radio" name="p6" data-p="6" data-v="2"> Upwards</label><label><input type="radio" name="p6" data-p="6" data-v="3"> Downwards</label><label><input type="radio" name="p6" data-p="6" data-v="4"> None</label></div><div><h2>Torso</h2><label><input type="radio" name="p7" data-p="7" data-v="1"> Buttons</label><label><input type="radio" name="p7" data-p="7" data-v="2" checked> Vest</label><label><input type="radio" name="p7" data-p="7" data-v="3"> Inward arms</label><label><input type="radio" name="p7" data-p="7" data-v="4"> None</label></div><div><h2>Base</h2><label><input type="radio" name="p8" data-p="8" data-v="1"> Buttons</label><label><input type="radio" name="p8" data-p="8" data-v="2"> Feet</label><label><input type="radio" name="p8" data-p="8" data-v="3"> Flat</label><label><input type="radio" name="p8" data-p="8" data-v="4" checked> None</label></div><br><button id="random">Randomize</button><pre id="p"></pre><input type="text" id="code">
```
[Answer]
# CJam, ~~135~~ ~~134~~ ~~132~~ ~~130~~ ~~126~~ 125 bytes
```
0000000: 4e22285b200a5c225f2a295c2d2e2f6f2c3e4f3a3c3d5d225f N"([ .\"_*)\-./o,>O:<=]"_
0000019: 2422dd7382d6bfab28707190992f240c362ee510262bd07a77 $".s....(pq../$.6...&+.zw
0000032: 08556de9dcdb566c676817c2b87f5ecb8bab145dc2f2f76e07 .Um...Vlgh....^....]...n.
000004b: 22323536624b623224663d4e2f7b5f2c342f2f7d25723a7e2e "256bKb2$f=N/{_,4//}%r:~.
0000064: 3d2828342423346222205f0a20222e2a6f6f736572372f4e2a =((4$#4b" _. ".*ooser7/N*
```
To create the file on your machine, execute `xxd -r > snowman.cjam`, paste the reversible hexdump from above, press `Enter` and finally `Ctrl` + `D`.
Alternatively, you can try the code online using the [CJam interpreter](http://cjam.aditsu.net/#code=N%22(%5B%20%0A%5C%22_*)%5C-.%2Fo%2C%3EO%3A%3C%3D%5D%22_%24%22%C3%9Ds%C2%82%C3%96%C2%BF%C2%AB(pq%C2%90%C2%99%2F%24%0C6.%C3%A5%10%26%2B%C3%90zw%08Um%C3%A9%C3%9C%C3%9BVlgh%17%C3%82%C2%B8%7F%5E%C3%8B%C2%8B%C2%AB%14%5D%C3%82%C3%B2%C3%B7n%07%22256bKb2%24f%3DN%2F%7B_%2C4%2F%2F%7D%25r%3A~.%3D((4%24%234b%22%20_%0A%20%22.*ooser7%2FN*&input=12222212).
### Bonus
My favorite snowman is Olaf:
```
$ LANG=en_US cjam snowman.cjam <<< 12222212
_===_
\(o.o)/
( : )
(" ")
```
*Winter's a good time to stay in and cuddle, but put me in summer and I'll be a… happy snowman!*
### Idea
The hex string
```
dd7382d6bfab28707190992f240c362ee510262bd07a7708
556de9dcdb566c676817c2b87f5ecb8bab145dc2f2f76e07
```
encodes the possible choices for all parts of the snowman, including the fixed ones. Let's call this string **P**.
To decode it, we convert **P** (here treated as an array of integers) from base 256 to base 20 and replace each of the resulting integers by the corresponding character of the string **M**:
```
([
"_*)\-./o,>O:<=]
```
This results in the string **T**:
```
/(_*_)"_===_/....., /_\
,._
-.oO
-.oO
<\ /
>/ \
: ] [> <
: " "___
((()
```
The first line encodes all hat choices, the last all fixed body parts. The other lines contain the 28 variable body parts.
We split **T** at linefeeds and divide the strings of the resulting array into four parts of equal length. Then, we read the input from STDIN, push the array of its digits in base 10 and select the corresponding elements of the split strings. We take advantage of the fact that arrays wrap around in CJam, so the element at index 4 of an array of length 4 is actually the first element. The last divided string does not correspond to any input, so it will get selected entirely.
We handle the hat by shifting the first element out of the resulting array. The index in **M** of first character, read as a base 4 number, reveals the number of spaces and underscores in the first line of the hat. We print those characters, a linefeed, a space and the remainder of the shifted string. Then, we push an additional linefeed on the bottom of the stack.
For the body parts, we concatenate the string corresponding to all of them. Let's call this string **S**. To assemble the body parts, we perform transliteration: we take each character of the string **M**, compute its index in **sort(M)** and replace it by the corresponding character of **S**. We take advantage of the fact that the transliteration operator automatically pads **S** to match the length of **sort(M)** by repeating the last character of **S** as many times as necessary.
Finally, we divide the resulting string into substrings of length 7 and place a linefeed between each pair of substrings.
### Code
Suppose that the variables `M` and `P` contain the strings **M** and **P**.
```
N e# Push a linefeed.
M_$ e# Push M and a sorted copy.
P256bKb e# Push P and convert it from base 256 to base 20.
2$ e# Push a copy of M.
f= e# Compute T by retrieving the proper chars from M.
N/ e# Split T at linefeeds.
{_,4//}% e# Divide each string into four substrings of equal length.
r:~ e# Read a number from STDIN and push the array of its digits in base 10.
.= e# Get the corresponding chunks from T.
(( e# Shift out the first string and that string's first character.
4$# e# Find its index in M.
4b e# Compute its digits in base 4.
" _
".* e# Repeat the space and underscore that many times in place.
oo e# Print the result and the shifted string.
s e# Flatten the remainder of the array. This pushes S.
er e# Perform transliteration.
7/ e# Split into chunks of length 7.
N* e# Join using linefeeds.
```
[Answer]
# CJam, 164 bytes
Generates the snowman left-to-right, top-to-bottom. This eliminates the need for any kind of string joining or repositioning operations, as I just leave every piece of the snowman on the stack. And then, due to the automatic stack dump at the end of programs:
♫ *CJam wants to build a snowman!* ♫
```
q:Q;SS"
_===_,___
....., _
/_\,___
(_*_)"',/0{Q=~(=}:G~N" \ "4G'(".oO-"_2G",._ "1G@3G')" / "5GN"< / "4G'(" : ] [> < "3/6G')"> \ "5GNS'(" : \" \"___ "3/7G')
```
[Try it online.](http://cjam.aditsu.net/#code=q%3AQ%3BSS%22%0A%20_%3D%3D%3D_%2C___%0A%20.....%2C%20_%0A%20%20%2F_%5C%2C___%0A%20(_*_)%22'%2C%2F0%7BQ%3D~(%3D%7D%3AG~N%22%20%5C%20%224G'(%22.oO-%22_2G%22%2C._%20%221G%403G')%22%20%2F%20%225GN%22%3C%20%2F%20%224G'(%22%20%3A%20%5D%20%5B%3E%20%3C%20%20%20%223%2F6G')%22%3E%20%5C%20%225GNS'(%22%20%3A%20%5C%22%20%5C%22___%20%20%20%223%2F7G')&input=33232124)
### Bonus
Thinking outside the box! `32443333` gives a snow(wo)man bride. You've gotta try a bit to see it, but there are the inward arms, fez + downwards arms = veil, and the head is actually in the fez/veil. The generally large form is the billowy dress, and the "eyes" and "nose" are folds in the dress.
```
_
/_\
(-.-)
/(> <)\
(___)
```
Other "eye" choices are a bit risqué...
[Answer]
# Python, ~~276~~ 289 bytes
```
V='.oO-'
def F(d):
D=lambda i:int(d[i])-1
print" "+("","___"," _ ","___")[D(0)]+"\n "+\
"_. (=./_=._*=.\\__. )"[D(0)::4]+"\n"+\
" \\ "[D(4)]+"("+V[D(2)]+',._ '[D(1)]+V[D(3)]+")"+" / "[D(5)]+'\n'+\
"< / "[D(4)]+"("+" ]> : [< "[D(6)::4]+")"+"> \\ "[D(5)]+"\n ("+\
' "_ : _ "_ '[D(7)::4]+")"
```
This code has 8 extra bytes(`\`\*4) for readability.
Builds the snowman up bit by bit.
# Bonus
`F("44444432")` gives "sleepy russian bear":
```
___
(_*_)
(- -)
(> <)
(" ")
```
[Answer]
# TI-BASIC, 397 bytes
**Important:** If you want to test this out, download it from [here](https://www.dropbox.com/s/exwuo6zm9xsn7q6/SNOWMAN.8xp?dl=0) and send that file to your calculator. Do *not* try to copy the code below into TI-Connect CE's program editor or SourceCoder 3 or something to build and send it to your calculator; in TI-Connect's case, it'll say it has an invalid token. SC3 uses the backslash as a comment delimiter (`//` starts a comment in SC3; `/\/`, though, will export as `//`) and so it won't export the arms and hat and such correctly, causing the program to both display the incorrect body parts and throw an ERROR:DOMAIN every now and then. Fun stuff!
**Important #2:** I'm too lazy to fix the download at the moment, so when you transfer it to your calc, change the `7` on the third line from the bottom to `X+6`. The code below is fixed if you need to compare.
```
Input Str9
seq(inString("1234",sub(Str9,I,1)),I,1,length(Ans→L1
" ___ _ ___ →Str1
"_===_..... /_\ (_*_)→Str2
",._ →Str3
"•oO-→Str4
"<\/ →Str5
">/\ →Str6
" : ] [> < →Str7
" : ¨ ¨___ →Str8
"Str1Str2Str3Str4Str5Str6Str7Str8→Str0
For(X,3,5
Output(X,2,"( )
End
L1
Output(3,3,sub(Str4,Ans(3),1)+sub(Str3,Ans(2),1)+sub(Str4,Ans(4),1
Ans(5
Output(4-(Ans=2),1,sub(Str5,Ans,1
L1(6
Output(4-(Ans=2),7,sub(Str6,Ans,1
L1-1
For(X,1,2
Output(X+3,3,sub(expr(sub(Str0,X+6,1)),1+3Ans(X+6),3
Output(X,2,sub(expr(sub(Str0,X,1)),1+5Ans(1),5
End
```
**Bonus:** I'm particularly fond of `12341214`.
```
_===_
(O.-)/
<( : )
( )
```
Some notes:
* It can definitely be golfed more, no question about that. I'm nearly positive that I can combine a majority, if not all, of the outputting into a single For( loop. Also, I'm pretty sure that I can merge some strings together.
* In Str4 (the eyes) I use the "plot dot" (`[2ND] → [0]CATALOG → [3]θ → scroll down, it's between ﹢ (small plus) and · (interpunct)`) as opposed to a period so that the eyes don't line up with the comma, because that looks weird as hell.
* In Str8 (base) I had to use a diaeresis (¨) instead of double quotes because there's no way to escape characters in TI-BASIC, and double quotes are used to start/end strings.
* In TI-BASIC, there's no need to close parentheses and brackets if they're followed by a colon, newline or → (used for var assignment), and double quotes (strings) can stay unclosed when followed by a newline or →.
[Answer]
# Python 2, ~~354~~ ~~280~~ ~~241~~ 261 bytes
```
def s(g):H,N,L,R,X,Y,T,B=[int(c)-1for c in g];e='.oO-';print(' '*9+'_ _ ___ _ _\n\n\n\n _. (=./_=._*=.\\__. )')[H::4]+'\n'+' \\ '[X]+'('+e[L]+',._ '[N]+e[R]+')'+' / '[Y]+'\n'+'< / '[X]+"("+' ]> : [< '[T::4]+')'+'> \\ '[Y]+'\n ('+' "_ : _ "_ '[B::4]+")"
```
Calling `s('33232124')` gives:
```
_
/_\
\(o_O)
(] [)>
( )
```
But my favorites are `44242123` and `41341144`:
```
___ ___
(_*_) (_*_)
\(o -) (O,-)
(] [)> <( )>
(___) ( )
```
[Answer]
# CJam, ~~150~~ 145 bytes
Base convert **all** the things!
```
"b8li'
U9gN;|"125:Kb8bl:~f="r pL|P3{cR`@L1iT"Kb21b"G.HMtNY7VM=BM@$^$dX8a665V"KbFb"=_./ <[(*-oO,\":"f=_"/<[(""\>])"er+4/f=.=7/N*
```
SE mangles unprintables, so [here](http://pastebin.com/J4eFVDtR) is a copy on Pastebin. Make sure you copy the "RAW Paste Data" part, not the part next to line numbers. You can [try it online](http://cjam.aditsu.net/#code=%22%02b8%11li%27%0A%07U9gN%3B%7C%22125%3AKb8bl%3A%7Ef%3D%22%02r%09pL%7CP3%19%7B%0EcR%60%40%1DL1i%07T%15%22Kb21b%22%01G%0F%1D.H%17M%13tNY7V%15M%3DBM%40%24%5E%08%24%1B%1EdX8a665V%22KbFb%22%3D_.%2F%20%3C%5B%28*-oO%2C%5C%22%3A%22f%3D_%22%2F%3C%5B%28%22%22%5C%3E%5D%29%22er%2B4%2Ff%3D.%3D7%2FN*&input=14441133), but the permalink may not work in some browsers.
## Explanation
The `"b8li'U9gN;|"125:Kb8bp` part generates the array
```
[1 0 0 0 0 0 0 0 0 0 0 0 0 0 4 0 2 1 3 0 5 4 0 6 6 6 0 5 0 0 7 7 7 0]
```
which maps each digit of the input to where the digit is used. Anything which is common to all inputs (e.g. leading spaces and `()`) is arbitrarily assigned a 0, except the first which is assigned 1 so that base convert can work.
`l:~f=` then converts each digit to an int and maps accordingly, e.g. for `14441133` we get
```
[2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 2 4 1 2 1 1 3 3 3 1 2 1 1 4 4 4 1]
```
`"G.HMtNY7VM=BM@$^$dX8a665V"KbFb"=_./ <[(*-oO,\":"f=` gives the string
```
"_=./ / < / [<(((((_. _ _ _ __*=._-.oO ,._ \"_ : : _"
```
after which we duplicate, replace `/<[(` with `\>])` and append to give a long string. Then we split the string into groups of 4 and map according to another array `"r pL|P3{cR`@L1iT"Kb21b`, thus getting an array of length-4 strings describing all possible options at each cell (e.g. `_=./` is all possible options for the second character on the second line, starting from the Russian hat).
Finally we map the options to the inputs accordingly `.=`, split into rows of length 7 `7/` and riffle in some newlines `N*`.
## Test runs
```
11111111
_===_
(.,.)
<( : )>
( : )
22222222
___
.....
\(o.o)/
(] [)
(" ")
33333333
_
/_\
(O_O)
/(> <)\
(___)
44444444
___
(_*_)
(- -)
( )
( )
```
[Answer]
# C, ~~280 272~~ 264 bytes
Only partially golfed at this point, but this is a fun challenge.
```
#define P(n)[s[n]&3],
f(char*s){printf(" %.3s\n %.5s\n%c(%c%c%c)%c\n%c(%.3s)%c\n (%.3s)",
"___ ___ _"+*s%4*3,"(_*_)_===_..... /_\\"+*s%4*5," \\ "P(4)"-.o0"P(2)
" ,._"P(1)"-.o0"P(3)" /"P(5)" < /"P(4)" : ] [> <"+s[6]%4*3," > \\"P(5)
" : \" \"___"+s[7]%4*3);}
```
(With some extra \n for readability.) I expect the `define` should go away with further golfing.
A more readable version is
```
#define P(n)[s[n]&3],
f(char *s) {
printf(" %.3s\n"
" %.5s\n"
"%c(%c%c%c)%c\n"
"%c(%.3s)%c\n"
" (%.3s)",
"___ ___ _"+*s%4*3, /* Top of hat. */
"(_*_)_===_..... /_\\"+*s%4*5, /* Lower hat. */
" \\ "P(4) /* Upper left arm. */
"-.o0"P(2) /* Left eye. */
" ,._"P(1) /* Nose. */
"-.o0"P(3) /* Right eye. */
" /"P(5) /* Upper right arm. */
" < /"P(4) /* Lower left arm. */
" : ] [> <"+s[6]%4*3, /* Torso. */
" > \\"P(5) /* Lower right arm. */
" : \" \"___"+s[7]%4*3 /* Base. */
);
}
```
[Answer]
# C, 212 bytes
```
d;main(){char*t="##3#b#b3#bbb3#b#b##\r#3b1#+3@12b3@1b-3@1_b3b1#,#\r7#_##+51rR04/1b#61rR0,8#2##\r7?#2#+9#`A#9=###9#^?#,8A#_#\r#+:#%b#:=#b#:#%b#,#",p[9];for(gets(p);d=*t++;putchar(d-3))d=d<51?d:(p[d-51]-53)[t+=4];}
```
A readable version:
```
d;
main()
{
char *t = "##3#b#b3#bbb3#b#b##\r"
"#3b1#+3@12b3@1b-3@1_b3b1#,#\r"
"7#_##+51rR04/1b#61rR0,8#2##\r"
"7?#2#+9#`A#9=###9#^?#,8A#_#\r"
"#+:#%b#:=#b#:#%b#,#",
p[9]; // 9 bytes is just enough for the input string of length 8
for (gets(p); d = *t++; putchar(d-3))
d = d < 51 ? d : (p[d - 51] - 53)[t += 4];
}
```
I took the idea from [the answer by Reto Koradi](https://codegolf.stackexchange.com/a/49914/25315). There were several fun improvements I did, which may warrant posting a separate answer:
* Converted from function to program (+10)
* Moved newlines into the control string (-7)
* Added 3 to all character codes to have fewer escaped chars like `\"` (-3)
* Reading from the string with autoincrement; also replaced `t[i++]` by `*t++` (-4)
* Replaced `while` by `for`; removed `{}` (-4)
* Simplified loop termination: reading until `\0` (-9)
* [Transformed `t[...],t+=4` to `(...)[t+=4]`](https://stackoverflow.com/questions/381542/with-c-arrays-why-is-it-the-case-that-a5-5a) to eliminate the comma operator (-1)
Why all that trouble? To share my favorite one, snow ghost:
```
_
/_\
\(. .)/
( )
(___)
```
[Answer]
# JavaScript, 489 (without newlines and tabs)
```
x=' ';
d=" ";
h=['\n_===_',' ___ \n.....',' _ \n /_\\ ',' ___ \n(_*-)'];
n=[',','.','_',x];
e=['.','o','O','-'];
y=['>',,'\\',x];
u=['<',,'/',x];
t=[' : ','[ ]','> <',d;
b=[' : ','" "',"___",d];
j=process.argv[2].split('').map(function(k){return parseInt(k)-1});
q=j[4]==1;
w=j[5]==1;
console.log([
h[j[0]].replace(/(.*)\n(.*)/g, " $1\n $2"),
(q?'\\':x)+'('+e[j[2]]+n[j[1]]+e[j[3]]+')'+(w?'/':x),
(!q?u[j[4]]:x)+'('+t[j[6]]+')'+(!w?y[j[5]]:x),
x+'('+b[j[7]]+')'].join('\n'));
```
run with `node snowman.js 33232124`
[Answer]
# Pyth, 203 bytes
```
M@GCHgc" ___
___
_"bhzgc" (_*_)
_===_
.....
/_\\"bhzs[g" \ "@z4\(g"-.oO"@z2g" ,._"@z1g"-.oO"@z3\)g" / "@z5)s[g" < /"@z4\(gc"
:
] [
> <"b@z6\)g" > \\"@z5)++" ("gc"
:
\" \"
___"bez\)
```
Lol. Try it online: [Pyth Compiler/Executor](https://pyth.herokuapp.com/?code=M%40GCHgc%22%20%20___%0A%0A%20%20___%0A%20%20%20_%22bhzgc%22%20(_*_)%0A%20_%3D%3D%3D_%0A%20.....%0A%20%20%2F_%5C%5C%22bhzs%5Bg%22%20%20%5C%20%22%40z4%5C(g%22-.oO%22%40z2g%22%20%2C._%22%40z1g%22-.oO%22%40z3%5C)g%22%20%20%2F%20%22%40z5)s%5Bg%22%20%3C%20%2F%22%40z4%5C(gc%22%20%20%20%0A%20%3A%20%0A%5D%20%5B%0A%3E%20%3C%22b%40z6%5C)g%22%20%3E%20%5C%5C%22%40z5)%2B%2B%22%20(%22gc%22%20%20%20%0A%20%3A%20%0A%5C%22%20%5C%22%0A___%22bez%5C)&input=33232124&debug=0)
### Explanation
First I define a helper function `g`, which takes a list and a char as input, converts the char into its ASCII-value and takes correspondent element (modular wrapping).
```
M@GCH def g(G,H): return G[ord(H)]
```
The other things is just printing line by line. For instance the first line is:
```
c" ___\n\n ___\n _"b split the string " ___\n\n ___\n _" at "\n"
hz first char in input
g apply g and print
```
Btw. I experimented a little bit with `.F"{:^7}"`, which centers a string. Using it, I could save a few spaces in my code, but it doesn't save any bytes at the end.
[Answer]
# Haskell, ~~361~~ ~~306~~ 289 bytes
```
o l a b=take a$drop((b-1)*a)l
n="\n"
p i=id=<<[" ",o" \n _===____ \n ..... _ \n /_\\ ___ \n (_*_)"11a,n,o" \\ "1e,o"(.(o(O(-"2c,o",._ "1 b,o".)o)O)-)"2d,o" / "1f,n,o"< / "1e,o"( : )(] [)(> <)( )"5g,o"> \\ "1f,n," (",o" : )\" \")___) )"4h]where[a,b,c,d,e,f,g,h]=map(read.(:[]))i
```
Usage:
```
putStrLn $ p "12333321"
_===_
(O.O)
/(] [)\
( : )
```
How it works: index every element of the list of `[hat options, left upper arm options, left eye options, ..., base options]` with the corresponding input number and concatenate it into a single list. I've split the left and right arm into an upper and lower part, so that I can build the snowman line by line.
My favorite is the classic `11112211`.
Edit: switched from list of strings to strings for the parts (hat, eye, ...). Needs a second parameter, the length of the substring to take.
Edit II: extracted common substrings
[Answer]
# R, ~~436~~ 437 bytes
Here's my first try on [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), using R which isn't the shortest but still fun. At least I'm beating JavaScript (for now)...
```
H=c("_===_"," ___\n ....."," _\n /_\\"," ___\n (_*_)")
N=c(",",".","_"," ")
L=c(".","o","O","-")
X=c(" ","\\"," "," ")
S=c("<"," ","/"," ")
Y=c(" ","/"," ","")
U=c(">"," ","\\","")
T=c(" : ","] [","> <"," ")
B=c(" : ","\" \"","___"," ")
f=function(x){i=as.integer(strsplit(x,"")[[1]]);cat(" ",H[i[1]],"\n",X[i[5]],"(",L[i[3]],N[i[2]],L[i[4]],")",Y[i[6]],"\n",S[i[5]],"(",T[i[7]],")",U[i[6]],"\n"," (",B[i[8]], ")",sep="")}
```
Testing:
```
> f("12344321")
_===_
(O.-)
(] [)\
( : )
```
I actually struggled with `X` and `Y` being multilined but with stuff in between, ended up separating each line in (`X`, `S`) and (`Y`, `U`).
`function` and conversion from string to integer are also very verbose.
**Edit 436 => 437**
Had to fix a missing empty space noticed by @OganM
I could reduce to 428 replacing the line breaks between variables with `;`, but the "one-lined" code looks so bad and unreadable I won't be that greedy.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 199 bytes
Inspired by [Reto Koradi](https://codegolf.stackexchange.com/a/49914/80745) and [anatolyg](https://codegolf.stackexchange.com/a/49941/80745).
```
for($t=' 0 _ _0 ___0 _ _
0_. (0=./_0=._*0=.\_0_. )
4 \ (2.oO-1,._ 3.oO-)5 /
4< / (6 ]> 6: 6 [< )5> \
(7 "_ 7: _ 7 "_ )';$d=$t[$i++];$r+="$d"){if($d-ge48){$d=$t[$i+"$args"["$d"]-49]
$i+=4}}$r
```
[Try it online!](https://tio.run/##RZBbboMwFET/vYqRaxVTCuHhkJbE2UIXQJCFxKNItESGtIoQa6cmQen5GM9cj2XZ5@631P1n2bYzqyAxzlWnORukBfhQUEaUujkCX3ngvvQ2yoh6MXJSy8wmAieAh1734QavnkK0OHuLDUDEwSw8RnZEnACIkR5gb4/mCAHfgSrsEnPBzdnWnhWSDSlrHCfbM@1Iygpqj03FWeHWpXizx0eDslzXPU2XSuaK94yYoRTTxPQ8kWfzIiswCBEE1j1GURiFQSis/92FNYYrj/KdNYoV8zVP@Lqiyn863QxlAtq3ZXm@Ql/6vsm/UV9yXdD5Dw "PowerShell – Try It Online")
Note: The line 3 has 2 trail spaces, line 4 has a trail space.
My favorite is `44444444` "sleepy russian guard":
```
___
(_*_)
(- -)
( )
( )
```
[Answer]
# CJam, ~~200~~ 191 bytes
This can surely be golfed a lot. (Specially if I base encode it). But here goes for starters:
```
7S*"_===_ ___ ..... _ /_\ ___ (_*_)"+6/2/Nf*",._ "1/".oO-"1/_" <\ / >/ \ "2/4/~" : ] [> < : \" \"___ "3/4/~]l~Ab:(]z::=:L0=N4{L=}:K~0='(2K1K3K')5K0=N4K1='(6K')5K1=NS'(7K')
```
Input goes into STDIN. For example, input `23232223` gives:
```
___
.....
\(o_O)/
(] [)
(___)
```
[Try it online here](http://cjam.aditsu.net/#code=7S*%22_%3D%3D%3D_%20%20___%20%20.....%20%20%20_%20%20%20%20%2F_%5C%20%20%20___%20%20(_*_)%22%2B6%2F2%2FNf*%22%2C._%20%221%2F%22.oO-%221%2F_%22%20%3C%5C%20%20%2F%20%20%20%3E%2F%20%20%5C%20%20%222%2F4%2F~%22%20%3A%20%5D%20%5B%3E%20%3C%20%20%20%20%3A%20%5C%22%20%5C%22___%20%20%20%223%2F4%2F~%5Dl~Ab%3A(%5Dz%3A%3A%3D%3AL0%3DN4%7BL%3D%7D%3AK~0%3D'(2K1K3K')5K0%3DN4K1%3D'(6K')5K1%3DNS'(7K')&input=33232124)
[Answer]
## C, ~~233~~ 230 bytes
```
char*t=" 0 _ _0 ___0 _ _ 0_. (0=./_0=._*0=.\\_0_. ) 4 \\ (2.oO-1,._ 3.oO-)5 / 4< / (6 ]> 6: 6 [< )5> \\ (7 \"_ 7: _ 7 \"_ ) ";i,r,d;f(char*p){while(r++<35){d=t[i]-48;putchar(t[d<0?i:i+p[d]-48]);i+=d<0?1:5;r%7?0:puts("");}}
```
With newlines and whitespace for better readability:
```
char* t = " 0 _ _0 ___0 _ _ 0_. (0=./_0=._*0=.\\_0_. ) 4 \\ (2.oO-1,._ 3.oO-)5 / 4< / (6 ]> 6: 6 [< )5> \\ (7 \"_ 7: _ 7 \"_ ) ";
i, r, d;
f(char* p)
{
while (r++ < 35)
{
d = t[i] - 48;
putchar(t[d < 0 ? i : i + p[d] - 48]);
i += d < 0 ? 1 : 5;
r % 7 ? 0 : puts("");
}
}
```
The whole thing is fairly brute force. It uses a table that contains one entry for each of the 35 (5 lines with length 7) characters. Each entry in the table is either:
* A constant character: , `(`, `)`. Length of table entry is 1 character.
* Index of body part, followed by the 4 possible characters depending on the part selection in the input. Length of table entry is 5 characters.
The code then loops over the 35 characters, and looks up the value in the table.
[Answer]
# Python 3, ~~349~~ ~~336~~ ~~254~~ 251 bytes
So much for doing my thesis.
Here's the content of the file *snowman.py*:
```
l='_===_| ___\n .....| _\n /_\| ___\n (_*_)| : |] [|> <| |>| |\| | : |" "|___| '.split('|')
l[4:4]=' \ .oO-,._ .oO- / < / '
def s(a):print(' {}\n{}({}{}{}){}\n{}({}){}\n ({})'.format(*[l[4*m+int(a[int('0421354657'[m])])-1]for m in range(10)]))
```
And this is how I conjure my favourite snowman:
```
s('11112311')
_===_
\(.,.)
( : )\
( : )
```
## Explanation
```
# Create a list containing the 4 * 10 body parts of the snowman in order of drawing:
# hats,
# upper left arms, left eyes, noses, right eyes, upper right arms,
# lower left arms, torso's, lower right arms,
# bases
l='_===_| ___\n .....| _\n /_\| ___\n (_*_)| : |] [|> <| |>| |\| | : |" "|___| '.split('|')
l[4:4]=' \ .oO-,._ .oO- / < / '
# This is the function that draws the snowman
# All the lines of this function are golfed in a single statement, but seperated here for clearity
def s(a):
# In this list comprehension I put the elements of l that are chosen according to the parameters
list_comprehension = []
# m is the number of the body part to draw
for m in range(10):
# Get the index for the choice of the m-th bodypart
# (example: the 2nd bodypart (m = 1: the upper left arm) is in the 4th place of the arguments list)
choice_index = int('0421354657'[m])
# n is the parameter of the current bodypart
n = int(a[choice_index]) - 1
# Add the body part from list l to the list comprehenseion
list_comprehension.append( l[4 * m + n] )
# Print the list comprehension with the static parts
print(' {}\n{}({}{}{}){}\n{}({}){}\n ({})'.format(*list_comprehension))
```
[Answer]
# R 414 Bytes
Slightly modified version of Molx's version
```
W =c("_===_"," ___\n ....."," _\n /_\\"," ___\n (_*_)",",",".","_"," ",".","o","O","-"," ","\\"," "," ","<"," ","/"," "," ","/"," ","",">"," ","\\",""," : ","] [","> <"," "," : ","\" \"","___"," ")
f=function(x){i=as.integer(strsplit(x,"")[[1]]);cat(" ",W[i[1]],"\n",W[i[5]+12],"(",W[i[3]+8],W[i[2]+4],W[i[4]+8],")",W[i[6]+20],"\n",W[i[5]+16],"(",W[i[7]+28],")",W[i[6]+24],"\n"," (",W[i[8]+32], ")",sep="")}
```
Just merged the seperate variables into one. Shawing of some space that was used for `X=c(` routine.
[Answer]
# Haskell, 333 bytes
My first submission! Builds the snowman from top to bottom, left to right. I split the arms into two functions for each arm, the part next to head and the part next to the body.
The function s takes a list of integers and concatenates the output of the functions which produce the body parts given correct sublists of the input.
```
a=y["\n _===_\n"," ___ \n .....\n"," _ \n /_\\ \n"," ___ \n (_*_)\n"]
d=y",._ "
c=y".oO-"
e=y"< / "
j=y" \\ "
f=y"> \\ "
k=y" / "
y w n=w!!(n-1)
h=y[" : ","] [","> <"," "]
b=y[" ( : ) \n"," (\" \") \n"," (___) \n"," ( ) \n"]
s(m:x:o:p:n:q:t:l:_)=putStr$a m++j x:'(':c o:d n:c p:')':k q:'\n':e x:'(':h t++')':f q:'\n':b l
```
It relies on the function
```
y :: [a] -> Int -> a
y w n=w!!(n-1)
```
which returns the nth element of the list it is given. This allows for the list of hats in a, as well as things like
```
k=y" / "
```
all of these functions use a beta reduction so their argument is passed as the index to the y function.
Output:
```
λ> s $ repeat 1
_===_
(.,.)
<( : )>
( : )
λ> s $ repeat 2
___
.....
\(o.o)/
(] [)
(" ")
λ> s $ repeat 3
_
/_\
(O_O)
/(> <)\
(___)
λ> s $ repeat 4
___
(_*_)
(- -)
( )
( )
```
[Answer]
# JavaScript (ES6), 247
Not as good ad @NinjaBearMonkey's :(
Test in snippet (with Firefox)
```
S=p=>([h,n,c,d,l,r,t,b,e,x]=[...p,' .oO-',`1_===_1 ___
.....1 _
/_\\1 ___
(_*_)1 : 1] [1> <1 1 : 1" "1___1 `.split(1)],` ${x[h]}
${' \\ '[l]}(${e[c]+' ,._ '[n]+e[d]})${' / '[r]}
${' < / '[l]}(${x[3-~t]})${' > \\ '[r]}
(${x[7-~b]})`)
// TEST //
function go()
{
var n=N.value
if (/^[1-8]{8}$/.test(n)) {
s=S(n)
OUT.innerHTML = s+'\n'+n+'\n\n'+ OUT.innerHTML
}
else N.focus()
}
```
```
<input id=N maxlength=8><button onclick="go()">Test</button>
<pre id=OUT></pre>
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~137~~ ~~135~~ ~~128~~ ~~122~~ 121 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
…( )7ÝJ»•αγʒδÓ₂©8¥ŽQxΣxêÿ•sÅвJIvN”</[(
._-=:"ÆŸ,*”º•DùÙÂ+;Èγтáì³ÓW©ÎÂ_`ƒ≠îj*ΓçÊ~ÞÒ¸β¦oåb/õ47/vÎΓ”›≠øØZµλݺ•20в趡Nè4äyè.;
```
-6 bytes thanks to *@Grimy*.
[Try it online](https://tio.run/##Ad0AIv9vc2FiaWX//@KApiggKTfDnUrCu@KAos6xzrPKks60w5PigoLCqTjCpcW9UXjOo3jDqsO/4oCic8OF0LJKSXZO4oCdPC9bKAouXy09OiLDhsW4LCrigJ3CuuKAokTDucOZw4IrO8OIzrPRgsOhw6zCs8OTV8Kpw47Dgl9gxpLiiaDDrmoqzpPDp8OKfsOew5LCuM6ywqZvw6ViL8O1NDcvdsOOzpPigJ3igLriiaDDuMOYWsK1zrvDncK64oCiMjDQssOowrbCoU7DqDTDpHnDqC47//80NDExNDQzMg) or [verify a few more test cases](https://tio.run/##LY09S0JRHMb38ymiJbN7tfMChhYuTQ5CU1CDKTQUkYMg3qi4XCiqwcG71GBkpWlEkKaYEsF5sKHhYF/hfpHbuXl/w394Xv5PsZQv7O36x2UrvZA0fM9uReYWE6hn5Niz79Wb6v3U1Dtcz3FkZ0U2J58bFfVQwTO@tF/C2bSbscpZz66vxrcjJJYz15LzOJ8MjajW5EiH1vGBGzhLKVyo3q@DBl5kD@6m7KAKJ7fzXfMu7/C6H1UunnB1ilvU5FB1ZauIZiGOvkjEy6gqVz/07FEQHuJ6S/bVGLMFtjztoi0HspFFW@DRQjuW8k8MOUj7lDNOKWVEHyoEpYRrhVEmCGUB2hIsVDgTgmuI@IdrSwQtPqsHEBZCeEgYFsI3zcOieZA/sv4A).
**Explanation:**
We first create the template-string:
```
…( ) # Push string "( )"
7ÝJ # Push a list in the range [0,7] joined together: "01234567"
» # Join both by a newline: "( )\n01234567"
•αγʒδÓ₂©2°ćì₂òη₆½•
# Push compressed integer 80545642885242518310229085147411483894
s # Swap to get the earlier created string at the top of the stack
Åв # Convert the large integer to base-"( )\n01234567",
# which basically converts to base-length, and indexes into the string:
# [" ","0","0","0","0","0","\n"," ","0","0","0","0","0","\n","4","(","2","1","3",")","5","\n","4","(","6","6","6",")","5","\n"," ","(","7","7","7",")"]
J # And join it to a single string: " 00000\n 00000\n4(213)5\n4(666)5\n (777)"
```
Which looks like this:
```
00000
00000
4(213)5
4(666)5
(777)
```
Then I loop over the digits of the input:
```
I # Get the input
v # Loop `y` over each of its digits:
```
And do the following:
Push the (0-indexed) index `N` of the list:
```
N # Push the index of the loop
```
Push all possible parts as a list of character lists:
```
”</[(
._-=:"ÆŸ,*”
"# Push dictionary string "</[(\n._-=:" Oo,*"
º # Mirror each line: "</[()]\>\n._-=:" Oo,**,oO ":=-_."
•DùÙÂ+;Èγтáì³ÓW©ÎÂ_`ƒ≠îj*ΓçÊ~ÞÒ¸β¦oåb/õ47/vÎΓ”›≠øØZµλݺ•
# Push compressed integer 492049509496347122906361438631265789982480759119518961177677313610613993948059787418619722816092858096158180892708001681647316210
20в # Convert it to Base-20 as list: [15,10,10,10,15,3,10,19,10,4,15,15,15,15,15,10,12,12,12,10,15,10,10,10,15,9,9,9,9,9,15,15,10,15,15,15,1,10,6,15,8,15,18,9,10,8,11,9,17,16,8,11,9,17,16,8,15,15,15,0,6,15,15,1,8,15,15,15,7,1,15,15,6,8,15,15,15,15,13,15,5,15,2,7,15,0,8,15,15,15,15,13,15,14,15,14,10,10,10]
è # Index each into the string: [" ","_","_","_"," ","(","_","*","_",")"," "," "," "," "," ","_","=","=","=","_"," ","_","_","_"," ",".",".",".",".","."," "," ","_"," "," "," ","/","_","\"," ","\n"," ",",",".","_","\n","-",".","o","O","\n","-",".","o","O","\n"," "," "," ","<","\"," "," ","/","\n"," "," "," ",">","/"," "," ","\","\n"," "," "," "," ",":"," ","]"," ","[",">"," ","<","\n"," "," "," "," ",":"," ","""," ",""","_","_","_"]
¶¡ # Split it by the newline character: [[" ","_","_","_"," ","(","_","*","_",")"," "," "," "," "," ","_","=","=","=","_"," ","_","_","_"," ",".",".",".",".","."," "," ","_"," "," "," ","/","_","\"," "],[" ",",",".","_"],["-",".","o","O"],["-",".","o","O"],[" "," "," ","<","\"," "," ","/"],[" "," "," ",">","/"," "," ","\"],[" "," "," "," ",":"," ","]"," ","[",">"," ","<"],[" "," "," "," ",":"," ","""," ",""","_","_","_"]]
```
Use the loop index `N` to get the character-list of the part we are currently working with:
```
Nè # Index the loop index into it
# i.e. 6 → [" "," "," "," ",":"," ","]"," ","[",">"," ","<"]
```
Then split the character list into four equal part, and use the input-digit `y` (which is 1-indexed) to index into it. (NOTE: Since 05AB1E is 0-indexed, but the input is 1-indexed, it would be logical to decrease the digit by 1 before indexing. However, since 05AB1E has automatic wraparound (i.e. indexing `3` in list `[1,3,5]` will result in `1`), I simply rotated the parts once so parts with nr 4 in the challenge description, are at the front of the lists.)
```
4ä # Split it into 4 equal parts
# i.e. [[" "," "," "],[" ",":"," "],["]"," ","["],[">"," ","<"]]
yè # Index the input-digit `y` into it (with automatic wraparound)
# i.e. 4 → [" "," "," "]
```
And then replace the 0-indexed index of the loop we pushed at first, one by one with the part-characters:
```
.; # Replace first; every index of the loop `N` in the template-string
# is replaced one by one with the characters
```
And in the end the result is output implicitly.
[See this 05AB1E tip of mine (section *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand how the compression parts work.
---
As for my favorite, it's still [the same 'snow rabbit' as 1.5 year ago when I posted my Java solution](https://codegolf.stackexchange.com/a/125628/52210):
```
44114432:
_
(_*_)
(. .)
(> <)
(" ")
```
[Answer]
# Java 8, ~~548~~ ~~545~~ ~~432~~ ~~401~~ ~~399~~ 397 bytes
```
a->{int q=50,H=a[0]-49,N=a[1],L=a[2],R=a[3],X=a[4],Y=a[5];return"".format(" %s%n %s%n%c(%c%c%c)%c%n%c(%s)%c%n (%s)",H<1?"":H%2<1?" ___":" _","_===_s.....s /_\\s(_*_)".split("s")[H],X==q?92:32,L<q?46:L<51?111:L<52?79:45,N<q?44:N<51?46:N<52?95:32,R<q?46:R<51?111:R<52?79:45,Y==q?47:32,X<q?60:32+X%2*15," s : s] [s> <".split("s")[a[6]%4],92-(Y%3+Y%6/4)*30," s : s\" \"s___".split("s")[a[7]%4]);}
```
-2 bytes thanks to *@ceilingcat*.
[Try it here.](https://tio.run/##dVNNb@IwEL33V4wsRUrApPgjIAIpWu2FA5sDvYAgirxpupsuBIhNparit7PjkN0WRF8kz9jzZvzisV/Uq@psd3n58vTnlK2V1vBDFeX7HUBRmrx6VlkOsZ0CPJqqKH9B5ma/VbVMQHlDXD/e4aCNMkUGMZQQwUl1Ht4xG/ZR0KWTSC27SUcOaIweS@gUDU/oDI1I6ByNTOgCTZAMq9wcqpIQ/3lbbZRxCTjaKevByVwns5@HQz3TtQfWIXQyYmNCwonDrQNpmpKQAKSEkjSKolT7Fhru09VKu2kr9Yivd@sC99DEW06skmg/HvBQcDod7ceyF05HARszxqzDx/1BKAMa25AMYxtCSmwjg8Amzc5Js39Js4@khS0t@5Y1R1avi1577vAWCyiKBA0h6ASW@gFGF7LUspc4eDwD3nEXjmgvnN699Fqi@5G2IrAi2v7vZWLfJnrD42loG7Q7/Fxjg5o@vW6LJ9hgn91zT@tmnptsco0lmOAC/4GTusX/VxFSMna5KpDLGZdXXG5xXUHyW1zBpRSIK24NcV1BWg3ihjKLy1Xe4FrvGbd2k42yz5e6Pqya1DwA3RzV45s2@cbfHoy/w4BZl65u461r6t4Il37mat9sv@MD@lZV6s31vK/ZjZLj6S8)
**Explanation:**
```
a->{ // Method with character-array parameter and String return-type
int q=50, // Temp integer with value 50 to reduce the byte-count
H=a[0]-49, // The hat-character as unicode value minus 49: 1=0; 2=1; 3=2; 4=3
N=a[1],L=a[2],R=a[3],X=a[4],Y=a[5];
// Most of the other characters as unicode values: 1=49; 2=50; 3=51; 4=52
return"".format(" %s%n %s%n%c(%c%c%c)%c%n%c(%s)%c%n (%s)",
// Return the snowman with:
H<1?"":H%2<1?" ___":" _", // The top of the hat
"_===_s.....s /_\\s(_*_)".split("s")[H], // + the bottom of the hat
X==q?92:32, // + the top of the left arm
L<q?46:L<51?111:L<52?79:45, // + the left eye
N<q?44:N<51?46:N<52?95:32, // + the nose
R<q?46:R<51?111:R<52?79:45, // + the right eye
Y==q?47:32, // + the top of the right arm
X<q?60:32+X%2*15, // + the bottom of the left arm
" s : s] [s> <".split("s")[a[6]%4], // + the torso
92-(Y%3+Y%6/4)*30, // + the bottom of the right arm
" s : s\" \"s___".split("s")[a[7]%4]);} // + the feet
```
**My favorite:**
```
44114432:
_
(_*_)
(. .)
(> <)
(" ")
```
I don't know why, but it looks kinda cute. Like a bunny with a Russian hat instead of ears.
[Answer]
# C# 9.0 (.NET 4.8) - ~~1813 1803 1821 1815~~ 1812+30=~~1843 1833 1851 1845~~ 1842 bytes
A Windows Forms application; likely can be improved on in terms of size. Contains a massive one-liner. The extra 30 bytes is from adding `<LangVersion>9.0</LangVersion>` to the project file.
```
using System;using System.Windows.Forms;class P:Form{string[]h={$@"
_===_",$@"___
.....",$@"_
/_\",$@"___
(_*_)"},s={" : ","] [","> <"," "},z={" : ","\" \"","___"," "};string n=",._ ",e=".oO-",x="< / ",y="> \\ ";TextBox t;Button b,d;Label l;[STAThread]static void Main(){Application.EnableVisualStyles();Application.SetCompatibleTextRenderingDefault(false);Application.Run(new P());}P(){t=new();b=new();d=new();l=new();SuspendLayout();t.Location=new(0,0);t.MaxLength=8;t.Size=new(269,23);t.TabIndex=0;b.Location=new(-1,22);b.Size=new(200,25);b.TabIndex=1;b.Text="Build the snowman!";b.UseVisualStyleBackColor=true;b.Click+=m;d.Location=new(198,22);d.Size=new(72,25);d.TabIndex=2;d.Text="Random";d.UseVisualStyleBackColor=true;d.Click+=(_,_)=>{int a=0;Random r=new();for(int i=0;i<8;i++)a+=r.Next(1,5)*(int)Math.Pow(10,i);m(a.ToString(),null);};l.AutoSize=false;l.Font=new("Consolas",9);l.Location=new(0,41);l.Size=new(269,73);l.TextAlign=System.Drawing.ContentAlignment.MiddleCenter;Font=new("Segoe UI",9);ClientSize=new(269,114);Controls.Add(l);Controls.Add(t);Controls.Add(b);Controls.Add(d);MaximizeBox=false;FormBorderStyle=FormBorderStyle.FixedSingle;Text="Snowman Maker";l.SendToBack();t.BringToFront();ResumeLayout(true);}void m(object q,EventArgs k){t.Enabled=false;b.Enabled=false;d.Enabled=false;if(q is string j)t.Text=j;if(t.Text.Length!=8||!int.TryParse(t.Text,out _))MessageBox.Show("Invalid input format.");else{int[]a=new int[8];for(int i=0;i<8;i++){a[i]=t.Text[i]-'0'-1;if(a[i]>3){MessageBox.Show("Invalid input format.");t.Enabled=true;b.Enabled=true;d.Enabled=true;return;}}l.Text=$@"{h[a[0]]}
{(a[4]==1?'\\':' ')}({e[a[2]]}{n[a[1]]}{e[a[3]]}){(a[5]==1?'/':' ')}
{x[a[4]]}({s[a[6]]}){y[a[5]]}
({z[a[7]]})";}t.Enabled=true;b.Enabled=true;d.Enabled=true;}}
```
A more readable version, with comments (though with the same confusing variable naming):
```
using System;
using System.Windows.Forms;
class Program : Form
{
string[] h = {$@"
_===_",$@"___
.....",$@"_
/_\",$@"___
(_*_)"}, // Hats
s = {" : ","] [","> <"," "}, // Torso
z = {" : ","\" \"","___"," "}; // Base
string n = ",._ ", e = ".oO-", x = "< / ", y = "> \\ "; // Nose, eyes, left arm, right arm
//Controls
TextBox t;
Button b, d;
Label l;
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new Program()); // I put all the control code in Program; please don't do this in normal code
}
Program()
{
// Initialize everything
t = new(); // Taking advantage of the short contructors in C# 9.0
b = new();
d = new();
l = new();
SuspendLayout();
// TextBox properties
t.Location = new(0, 0);
t.MaxLength = 8;
t.Size = new(269, 23);
t.TabIndex = 0;
// 'Build the snowman' button properties
b.Location = new(-1, 22);
b.Size = new(200, 25);
b.TabIndex = 1;
b.Text = "Build the snowman!";
b.UseVisualStyleBackColor = true;
b.Click += m;
// 'Random' button properties
d.Location = new(198,22);
d.Size = new(72,25);
d.TabIndex = 2;
d.Text = "Random";
d.UseVisualStyleBackColor = true;
d.Click += (_,_) =>
{
int a = 0;
Random r = new();
for(int i = 0; i < 8; i++)
a += r.Next(1,5) * (int)Math.Pow(10,i); // Math.Pow returns a number that satisfies 1 <= n < 5, not 1 <= n <= 5
m(a.ToString(), null); // Since I don't need the "sender" field, I use it to send the random input. Please don't do this in a normal program.
};
// Label properties
l.AutoSize = false;
l.Font = new("Consolas", 9);
l.Location = new(0, 41);
l.Size = new(269, 73);
l.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // This lets us omit some spaces, while making the form look nicer as well
// Form properties
Font = new("Segoe UI", 9);
ClientSize = new(269, 114);
Controls.Add(l);
Controls.Add(t);
Controls.Add(b);
Controls.Add(d);
MaximizeBox = false;
FormBorderStyle=FormBorderStyle.FixedSingle;
Text="Snowman Maker";
l.SendToBack();
t.BringToFront();
ResumeLayout(true);
}
// Event handler for the 'Build the snowman' button
void m(object sender, EventArgs k)
{
// Disable all the inputs, in case the user tries to mess with the data while the function is running.
// This is probably unneeded since modern computers run so quickly, but I kept it anyway.
t.Enabled = false;
b.Enabled = false;
d.Enabled = false;
if(sender is string j) // Accept input from 'Random' button
t.Text=j;
if(t.Text.Length != 8|| !int.TryParse(t.Text, out _)) // Discard the out parameter since we don't need it
MessageBox.Show("Invalid input format.");
else
{
int[] a = new int[8];
// Read from the TextBox.
for (int i = 0; i < 8; i++)
{
a[i] = t.Text[i] - '0' - 1;
if(a[i] > 3)
{
MessageBox.Show("Invalid input format.");
// Re-enable the inputs and cancel the operation.
t.Enabled = true;
b.Enabled = true;
d.Enabled = true;
return;
}
}
// Set the label text; uses an interpolated multiline string ($ makes it interpolated, @ makes it accept newlines and automatically escape characters (excluding " ))
l.Text=$@"{h[a[0]]}
{((a[4] == 1) ? '\\' : ' ')}({e[a[2]]}{n[a[1]]}{e[a[3]]}){((a[5] == 1) ? '/' : ' ')}
{x[a[4]]}({s[a[6]]}){y[a[5]]}
({z[a[7]]})";
}
t.Enabled = true;
b.Enabled = true;
d.Enabled = true;
}
}
```
The compact version was so painful to edit (I absolutely hate scrolling left and right) that I split it into a lot of lines and removed the unnecessary newlines after I was done with it:
```
using System;using System.Windows.Forms;class P:Form{string[]h={$@"
_===_",$@"___
.....",$@"_
/_\",$@"___
(_*_)"},s={" : ","] [","> <"," "},z={" : ","\" \"","___"," "};string n=",._ ",e=".oO-",x="< / ",y="> \\ ";TextBox t;
Button b,d;Label l;[STAThread]static void Main(){Application.EnableVisualStyles();Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new P());}P(){t=new();b=new();d=new();l=new();SuspendLayout();t.Location=new(0,0);t.MaxLength=8;t.Size=new(269,23
);t.TabIndex=0;b.Location=new(-1,22);b.Size=new(200,25);b.TabIndex=1;b.Text="Build the snowman!";b.UseVisualStyleBackColor=true;b.Click+=m;d.
Location=new(198,22);d.Size=new(72,25);d.TabIndex=2;d.Text="Random";d.UseVisualStyleBackColor=true;d.Click+=(_,_)=>{int a=0;Random r=new();
for(int i=0;i<8;i++)a+=r.Next(1,5)*(int)Math.Pow(10,i);m(a.ToString(),null);};l.AutoSize=false;l.Font=new("Consolas",9);l.Location=new(0,41);
l.Size=new(269,73);l.TextAlign=System.Drawing.ContentAlignment.MiddleCenter;Font=new("Segoe UI",9);ClientSize=new(269,114);Controls.Add(l);
Controls.Add(t);Controls.Add(b);Controls.Add(d);FormBorderStyle=FormBorderStyle.FixedSingle;MaximizeBox=false;Text="Snowman Maker";l.
SendToBack();t.BringToFront();ResumeLayout(true);}void m(object q,EventArgs k){t.Enabled=false;b.Enabled=false;d.Enabled=false;if(q is string
j)t.Text=j;if(t.Text.Length!=8||!int.TryParse(t.Text,out _))MessageBox.Show("Invalid input format.");else{int[]a=new int[8];for(int i=0;i<8;
i++){a[i]=t.Text[i]-'0'-1;if(a[i]>3){MessageBox.Show("Invalid input format.");t.Enabled=true;b.Enabled=true;d.Enabled=true;return;}}l.Text=$@"{h[a[0]]}
{(a[4]==1?'\\':' ')}({e[a[2]]}{n[a[1]]}{e[a[3]]}){(a[5]==1?'/':' ')}
{x[a[4]]}({s[a[6]]}){y[a[5]]}
({z[a[7]]})";}t.Enabled=true;b.Enabled=true;d.Enabled=true;}}
```
To run this code, make a Windows Forms Application project in Visual Studio for .NET Framework 4.8 (or whatever editor you use for C#), remove Form1.cs and delete it from the project, save the project, and add `<LangVersion>9.0</LangVersion>` to the project file. Then, you can copy the code into Program.cs (overwrite everything) and run it.
[Answer]
# F#, 369 bytes
```
let f(g:string)=
let b=" "
let p=printfn
let i x=int(g.[x])-49
p" %s "["";"___";" _ ";"___"].[i 0]
p" %s "["_===_";".....";" /_\ ";"(_*_)"].[i 0]
p"%s(%c%c%c)%s"[b;"\\";b;b].[i 4]".oO-".[i 2]",._ ".[i 1]".oO-".[i 3][b;"/";b;b;b].[i 5]
p"%s(%s)%s"["<";b;"/";b].[i 4][" : ";"] [";"> <";" "].[i 6][">";b;"\\";b].[i 5]
p" (%s) "[" : ";"\" \"";"___";" "].[i 7]
```
[Try it online!](https://tio.run/##TVDRaoQwEHz3K5YFQUvNnV7a0tP41uf2PYZwHqcIrYqRcv16uxttMYEwm52ZbKZxyXWYbsvyeZuhidqzm6eub2MVAN/UCgFXOKqROnPTr2UHd0Vl1Ap9N3EiXwMYESB0AKgRc7TW0gkWNmyE7uBoPI1YRLJKKeYIXsw92IrZkX2w8Z4fuii88o5Dh7rOsaowr/PaU6RBMbwnyDgz@CjoRcbp7v5kWHXwok329O/svCsW3PWczVYjnHkcA5rOEgoekX7n28/ULr3Cz7KzBHbk763qCqHaxfGnfzGLLt76efr5GCjG0gQc6tel6@Eytd9A@TceCc0ZHJclk1kmZZqefgE)
Because `g` uses an array accessor, I need to explicitly specify the type in the function definition as a `string`, which is why the function definition has `(g:string)`.
Apart from that, it's usually an array of `strings` accessed by an index. The hat, left and right arms which would go on separate lines are split into separate top and bottom arrays. The `i` function changes a number in the argument `g` into the array index. And the letter `b` replaces the one-space strings in the arrays.
Great challenge! My favourite snowman is probably `242244113`:
```
___
.....
(o o)
( : )
( : )
```
im watching you
[Answer]
# PHP, 378 bytes
```
<?$f=str_split;$r=$f($argv[1]);$p=[H=>' _===____..... _ /_\ ___(_*_)',N=>',._ ',L=>'.oO-',R=>'.oO-',X=>' <\ / ',Y=>' >/ \ ',T=>' : ] [> < ',B=>' : " "___ '];echo preg_replace_callback("/[A-Z]/",function($m){global$A,$p,$r,$f;$g=$m[0];return$f($f($p[$g],strlen($p[$g])/4)[$r[array_search($g,array_keys($p))]-1])[(int)$A[$g]++];},' HHH
HHHHH
X(LNR)Y
X(TTT)Y
(BBB)');
```
[Try it online!](https://tio.run/##PZBRa8IwEMff9ykOCTSZqZ3Tp9U47FMfxIH0QRdDqCWtYm1DWgcy9tXXXdjYEfL//467Izl7ssOweCWl6HqnO1uf@5g4QUpKcld9yKliMbFCpmIZAIAWQmiMiQ/QAJE@ADLVj5oFfINVfKIh4Gt0k/YtDPj23@38jMUBmwAr9p6WaA@eMk8voEAuYQE@k/xmRjDC@T6jYlOcWrDOVNoZW@eF0UVe18e8uNBRJFfhu4pGvLw1RX9uG0qu7LOq22NekxUnlhPHSRmTSpCrfFKxM/3NNf6jeKwkleK4gto0f8SiOZPEydy5/K47k7viREnFf/li7h0WMqZCXJGk56ZnZOX7xmMVf3FcVpqmD/5C2dH1Zsv2qFmWoQJNkoQFLB6GYTadYcyfv1vrn90NYfMD)
I like [wise Mr. Owl](https://www.youtube.com/watch?v=O6rHeD5x2tI) `31333342`
```
_
/_\
(O,O)
/( )\
(" ")
```
[Answer]
## Python 2.7, 257 bytes (i think)
```
H,N,L,R,X,Y,T,B=map(int,i)
l='\n'
s=' '
e=' .o0-'
F=' \ / '
S=' < / \ >'
o,c='()'
print s+' _ _ ___ _ _\n\n\n\n _. (=./_=._*=.\__. )'[H::4]+l+F[X]+o+e[L]+' ,._ '[N]+e[R]+c+F[-Y]+l+S[X]+o+' ]> : [< '[T::4]+c+S[-Y]+l+s+o+' "_ : _ "_ '[B::4]+c
```
where 'i' is the input as an string (e.g "13243213")
[Answer]
# Clojure (~~407~~ 402 bytes)
```
(defn a[s](let[[H N L R X Y T B](into[](map #(-(int %)49)(into[]s)))h([""" ___"" _"" ___"]H)i([" _===_"" ....."" /_\\"" (_*_)"]H)n([","".""_"" "]N)e[".""o""O""-"]l([" ""\\"" "" "]X)m(["<"" ""/"" "]X)r(["""/"""""]Y)u([">""""\\"""]Y)t([" : ""] [""> <"" "]T)b([" : "" ""___"" "]B)d(["""\" \""""""]B)f(str \newline)](str h f i f l "(" (e L) n (e R) ")" r f m "(" t ")" u f " (" b ")" f " " d)))
```
Hopefully that's clear to everyone.
And if not...
Ungolfed version:
```
(defn build-a-snowman [s]
(let [ [H N L R X Y T B] (into [] (map #(- (int %) 49) (into [] s)))
hat1 (["" " ___" " _" " ___" ] H) ; first line of hats
hat2 ([" _===_" " ....." " /_\\" " (_*_)"] H) ; second line of hats
nose (["," "." "_" " " ] N)
eye ["." "o" "O" "-" ]
left1 ([" " "\\" " " " " ] X) ; left arm, upper position
left2 (["<" " " "/" " " ] X) ; left arm, lower position
right1 (["" "/" "" "" ] Y) ; right arm, upper position
right2 ([">" "" "\\" "" ] Y) ; right arm, lower position
torso ([" : " "] [" "> <" " " ] T)
base1 ([" : " " " "___" " " ] B) ; first line of base
base2 (["" "\" \"" "" "" ] B) ; second line of base
nl (str \newline) ]
(str hat1 nl
hat2 nl
left1 "(" (eye L) nose (eye R) ")" right1 nl
left2 "(" torso ")" right2 nl
" (" base1 ")" nl
" " base2)))
```
Tests:
```
(println (a "33232124")) ; waving guy with fez
(println (a "11114411")) ; simple ASCII-art snowman
(println (a "34334442")) ; mouse
(println (a "41214433")) ; commissar with monocle
(println (a "41212243")) ; commissar celebrating success of five-year plan
(println (a "41232243")) ; commissar after too much vodka
```
My favorite:
34334442 - mouse
[Try it online!](https://tio.run/##bVBbT9swFH7nVxydaZI9rUNN/DKgSOteQEJMYjyAEityU4dm86WKnVbsz5djkz7AsBIdf@e7@Nit8X/GQR8ObK07B6oKkhkdq@oKbuEG7uABHuEelpL1LvpKMqu28InNEoTPXHznExE45xtWISJA0zSpQHME8or3xEGzWCxS81taiTxt6poqa740PKkcqb4iEpdkKG@5rhLyiL8QZyhNikHMrqx44JZaFxmeTp0hz0GIlnzkI8HLtE@u1Igp5IwMEkh4CRd5WpT3fHVkEsbjPVAu@Tpn1gg1vuYuecdCHKB2em96p7nMcAMd9PQbQEYX03DDwaV6xwE5wkCczVzMeCRMOoRVhgnQt6bXPDlh24Ee15BdAZZlURbzQiDnAOewV7vePcHT@Az7PtKp@h@8NcxpCTGfT4bQ263R8OP3z@vrmRoiBOf3Vrl3p4iyFEIUk8n6Mei3CjEvKLYsJ0Xrre1DUMPrGNY735oPLEUh/re02ujVoGK6SRjbVocAvoOu3@nZsybB1rwfkLLKD7NUF/UA0XuwY7uBnV//VYfDCw "Clojure – Try It Online")
[Answer]
# [Dart](https://www.dartlang.org/), 307 bytes
```
f(i,{r='.o0-',s=' : '}){i=i.split('').map((j)=>int.parse(j)-1).toList();return' ${['_===_',' ___ \n.....',' /_\\ ',' ___ \n (_*_)'][i[0]]}\n${' \\ '[i[4]]}(${r[i[2]]+',._ '[i[1]]+r[i[3]]})${' / '[i[5]]}\n${'< / '[i[4]]}(${[s,'] [','> <',' '][i[6]]})${'> \\ '[i[5]]}\n (${[s,'" "','___',' '][i[7]]})';}
```
[Try it online!](https://tio.run/##bZBBboMwEEX3PcUIIY3dECfYtJVKzAl6A0AWUhLJVWOQcbuxODu1CVGyyF8x/8@bb3HsrJvnM9GZtxJZv99iNkqET8CJei01G4cf7QgiZZduIOSbykobx4bOjqcwbXPKXP@lR0doaU/u1xqE1NeopJQKMwSlFDSGRcVxp5oG7j4Q9aootrWu9207NSb1CGEDMDhFcEjqbfjkbbvBjKnFz8MQTRFyGoHddf/tduFwc9YL9ZhhC3WoreAQy2FpfF/5KjbeD8BKJJCE3fDOhbgiHxHBcpr/en2ES6cNof4FYLDhr5AzSYTggue8SOgGG4O0fAxzHpXzp6HgRSGCnobFIvFATvM/ "Dart – Try It Online")
[Answer]
# Zsh, 247 bytes
[try it online!!](https://tio.run/##LY27bsMwDEV3fcWFQUBS0DhwnbaBIGbIlCFIlwB5KAJXbxk8FKjhb1dp15wuzuElf/uuFOeHI1thZukgIgb1NB2gERt5LtTJSrw1V7Z4AhYnrl/fa5z5rRYFd@Ub5ebGNmqyuCgJyEh7REyNB9u9dq05zKZCpYcnY2KMFWg4JvfThy54avJo6JroIzs6JWoznRO95ylvs6d7os9s6Pa/MFxCu3L0tW58aEdPj9lCxWEWu0VUZtQnrg/BN2MpZbvMHw)
```
(){H='_===_h ___
.....h _
/_\h ___
(_*_)'
W=' \ ' L=.oO- N=,._\ Y=' / '
X='< / ' T=' : ] [> < ' Z='> \ '
B=' : " "___ '
<<<" ${H[(ws:h:)$1]}
$W[$5]($L[$3]$N[$2]$L[$4])$Y[$6]
$X[$5](${T:3*($7-1):3})$Z[$6]
(${B:3*($8-1):3})"
} ${(s::)1}
```
fav snowman:
```
43232122 Cossack dancer
___
(_*_)
\(o_O)
(] [)>
(" ")
```
] |
[Question]
[
What general tips do you have for golfing in Python? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to Python (e.g. "remove comments" is not an answer).
Please post one tip per answer.
[Answer]
use `os.urandom()` as a random source instead of `random.randint()`
[Answer]
**Iterating over indices in a list**
Sometimes, you need to iterate over the indices of a list `l` in order to do something for each element that depends on its index. The obvious way is a clunky expression:
```
# 38 chars
for i in range(len(l)):DoStuff(i,l[i])
```
The Pythonic solution is to use `enumerate`:
```
# 36 chars
for i,x in enumerate(l):DoStuff(i,x)
```
But that nine-letter method is just too long for golfing.
Instead, just manually track the index yourself while iterating over the list.
```
# 32 chars
i=0
for x in l:DoStuff(i,x);i+=1
```
Here's some alternatives that are longer but might be situationally better
```
# 36 chars
# Consumes list
i=0
while l:DoStuff(i,l.pop(0));i+=1
# 36 chars
i=0
while l[i:]:DoStuff(i,l[i]);i+=1
```
[Answer]
# Leak variables to save on assignment
Combining with [this tip](https://codegolf.stackexchange.com/a/1020/21487), suppose you have a situation like
```
for _ in[0]*x:doSomething()
a="blah"
```
You can instead do:
```
for a in["blah"]*x:doSomething()
```
to skip out on a variable assignment. However, be aware that
```
exec"doSomething();"*x;a="blah"
```
in Python 2 is *just* shorter, so this only really saves in cases like assigning a char (via `"c"*x`) or in Python 3.
However, where things get fun is with Python 2 list comprehensions, where this idea still works due to a [quirk with list comprehension scope](https://stackoverflow.com/questions/4198906/python-list-comprehension-rebind-names-even-after-scope-of-comprehension-is-thi):
```
[doSomething()for a in["blah"]*x]
```
*(Credits to @xnor for expanding the former, and @Lembik for teaching me about the latter)*
[Answer]
# Use complex numbers to find the distance between two points
Say you have two 2-element tuples which represent points in the Euclidean plane, e.g. `x=(0, 0)` and `y=(3, 4)`, and you want to find the distance between them. The naïve way to do this is
```
d=((x[0]-y[0])**2+(x[1]-y[1])**2)**.5
```
Using complex numbers, this becomes:
```
c=complex;d=abs(c(*x)-c(*y))
```
If you have access to each coordinate individually, say `a=0, b=0, c=3, d=4`, then
```
abs(a-c+(b-d)*1j)
```
can be used instead.
[Answer]
# Use *f-strings*
Python 3.6 [introduces a new string literal](https://docs.python.org/3.6/reference/lexical_analysis.html#f-strings) that is vastly more byte-efficient at variable interpolation than using `%` or `.format()` in non-trivial cases. For example, you can write:
```
l='Python';b=40;print(f'{l}, {b} bytes')
```
instead of
```
l='Python';b=43;print('%s, %d bytes'%(l,b))
```
[Answer]
## Abuse `==` short circuiting
If you have:
* A function with a side effect (such as `print`);
* That you only want to run if some condition is (or is not) met.
Then you might be able to use `==` over `or` to save a byte.
Here's printing all numbers `n` under 100 that have `f(n)` less than 2:
```
# Naive
for n in range(100):f(n)<2and print(n)
# Invert condition
for n in range(100):f(n)>1or print(n)
# Use ==
for n in range(100):f(n)<2==print(n)
```
[Answer]
# Avoid `list.insert`
Instead of `list.insert`, appending to a slice is shorter:
```
L.insert(i,x)
L[:i]+=x,
```
For example:
```
>>> L = [1, 2, 3, 4]
>>> L[:-2]+=5,
>>> L
[1, 2, 5, 3, 4]
>>> L[:0]+=6,
>>> L
[6, 1, 2, 5, 3, 4]
```
[Answer]
## Store 8-bit numbers compactly as a bytes object in Python 3
In Python 3, a *bytes object* is written as a string literal preceded by a `b`, like `b"golf"`. It acts much like a tuple of the `ord` values of its characters.
```
>>> l=b"golf"
>>> list(l)
[103, 111, 108, 102]
>>> l[2]
108
>>> 108 in l
True
>>> max(l)
111
>>> for x in l:print(x)
103
111
108
102
```
Python 2 also has bytes objects but they act as strings, so this only works in Python 3.
This gives a shorter way to express an explicit list of numbers between 0 to 255. Use this to hardcode data. It uses one byte per number, plus three bytes overhead for `b""`. For example, the list of the first 9 primes `[2,3,5,7,11,13,17,19,23]` compresses to 14 bytes rather than 24. (An extra byte is used for a workaround explained below for character 13.)
In many cases, your bytes object will contain non-printable characters such as `b"\x01x02\x03"` for `[1, 2, 3]`. These are written with hex escape characters, but [you may use them a single characters in your code](http://meta.codegolf.stackexchange.com/q/4922/20260) (unless the challenge says otherwise) even though SE will not display them. But, characters like the carriage return `b"\x0D"` will break your code, so you need to use the two-char escape sequence `"\r"`.
[Answer]
Use powers of the imaginary unit to calculate sines and cosines.
For example, given an angle `d` in degrees, you can calculate the sine and cosine as follows:
```
p=1j**(d/90.)
s=p.real
c=p.imag
```
This can also be used for related functions such as the side length of a unit `n`-gon:
```
l=abs(1-1j**(4./n))
```
[Answer]
# `0in` instead of `not all`
(or, under [DeMorgan's Law](https://en.wikipedia.org/wiki/De_Morgan%27s_laws), `any(not ...)`)
```
not all(...)
~-all(...) # shorter than `not`, and with more forgiving precedence
0in(...)
```
```
not all map(f,a)
0in map(f,a) # the reduction is more significant here because you can omit the parentheses
```
This only works if the falsey values in the `...` sequence are actually `False` (or `0`/`0.0`/etc.) (**not** `[]`/`""`/`{}` etc.).
# `1in` instead of `any`
This one isn't shorter with a comprehension:
```
any(f(x)for x in a)
1in(f(x)for x in a)
```
But it sometimes saves bytes with other kinds of expression by letting you omit the parentheses:
```
any(map(f,a))
1in map(f,a)
```
This has a similar truthiness-related caveat to the above, though.
---
# Notes
These might sometimes have less favourable precedence, because they use the `in` operator. However, if you're combining this with a comparison you may be able to make additional use of [this tip](https://codegolf.stackexchange.com/a/60 "wow, answer ID 60") about comparison condition chaining.
You can also use these if you want the entire `for`-comprehension in `any`/`all` to always be fully evaluated:
```
any([... for x in a])
1in[... for x in a]
```
---
This one's rare, but if you need to evaluate and discard an extra expression for every item in a comprehension, you could use a dictionary here at no extra cost:
```
1in[(condition,side_effect)[0]for x in a]
1in{condition:side_effect for x in a}
```
because `dict`'s `in` checks only the keys.
[Answer]
## Combine assignments of reused values with unused for-loop variables
If you need to loop a number of times but you don't care about the iteration variable, you can co-opt the loop to assign a variable.
```
r=reused;for _ in"_"*n:stuff
r=reused;exec("r;"*n) # [note 1]
r=reused;exec"r;"*n # [note 1]; Python 2 only
for r in[reused]*n:r
lambda args:((r:=reused)for _ in"_"*n) # generally needs parentheses
lambda args,r=reused:(r for _ in"_"*n) # only works with constants
lambda args:(r for r in[reused]*n)
```
This is generally a more versatile approach for assignment than the `:=` operator or using default arguments of functions, because it supports assigning to attributes `.x`, subscripts `[x]`, and unpacking with `*` or `,`.
```
(stuff+(a[0]:=value)for _ in"_"*n) # syntax error
(stuff+a[0]for a[0]in[value]*n) # works, and shorter!
(stuff+a+b for*a,b in[value]*n) # works!
```
The only pitfall is that scope inside comprehensions is sometimes quite confusing, because the body of the comprehension is compiled as a separate implicit function.
[Taken from @xnor's use of it here](https://codegolf.stackexchange.com/a/216302).
[note 1]: and longer if backslashes/quotes/newlines/... need to be escaped inside the string
---
*This is a bot account operated by pxeger. I'm posting this to get enough reputation to use chat.*
[Answer]
Abuse the fact that in case of an expression yielding `True` boolean operators return the first value that decides about the outcome of the expression instead of a boolean:
```
>>> False or 5
5
```
is pretty straightforward. For a more complex example:
```
>>> i = i or j and "a" or ""
```
i's value remains unchanged if it already had a value set, becomes "a" if j has a value or in any other case becomes an empty string (which can usually be omitted, as i most likely already was an empty string).
[Answer]
## Check if a number is a power of 2
Check whether a positive integer `n` is a perfect power of 2, that is one of `1, 2, 4, 8, 16, ...`, with any of these expressions:
```
n&~-n<1
n&-n==n
n^n-1>=n
2**n%n<1
```
The third expression also works for `n==0` giving `False`. The last is easy to modify to checking for, say, powers of 3.
[Answer]
Lets play with some list tricks
```
a=[5,5,5,5,5,5,5]
```
can be written as:
```
a=[5]*7
```
It can be expanded in this way. Lets, say we need to do something like
```
for i in range(0,100,3):a[i]=5
```
Now using the slicing trick we can simply do:
```
a[0:100:3]=[5]*(1+99//3)
```
[Answer]
If you are doing something small in a for loop whose only purpose is to invoke a side effect (`pop`, `print` in Python 3, `append`), it might be possible to translate it to a list-comprehension. For example, from Keith Randall's answer [here](https://codegolf.stackexchange.com/revisions/40297/1), in the middle of a function, hence the indent:
```
if d>list('XXXXXXXXX'):
for z in D:d.pop()
c=['X']
```
Can be converted to:
```
if d>list('XXXXXXXXX'):
[d.pop()for z in D]
c=['X']
```
Which then allows this golf:
```
if d>list('XXXXXXXXX'):[d.pop()for z in D];c=['X']
```
An `if` within a `for` works just as well:
```
for i in range(10):
if is_prime(i):d.pop()
```
can be written as
```
[d.pop()for i in range(10)if is_prime(i)]
```
[Answer]
## Use map for side effects
Usually you use `map` to transform a collection
```
>> map(ord,"abc")
[97, 98, 99]
```
But you can also use it to repeatedly act on object by a built-in method that modifies it.
```
>> L=[1,2,3,4,5]
>> map(L.remove,[4,2])
[None, None]
>> L
[1, 3, 5]
```
Be aware that the calls are done in order, so earlier ones might mess up later ones.
```
>> L=[1,2,3,4,5]
>> map(L.pop,[0,1])
[1, 3]
>> L
[2, 4, 5]
```
Here, we intended to extract the first two elements of `L`, but after extracting the first, the next second element is the original third one. We could sort the indices in descending order to avoid this.
An advantage of the evaluation-as-action is that it can be done inside of a `lambda`. Be careful in Python 3 though, where `map` objects are not evaluated immediately. You might need an expression like `[*map(...)]` or `*map(...),` to force evaluation.
[Answer]
## Logical short-circuiting in recursive functions
**A detailed guide**
I had worked with short-circuiting `and/or`'s for a while without really grasping how they work, just using `b and x or y` just as a template. I hope this detailed explanation will help you understand them and use them more flexibly.
---
Recursive named `lambda` functions are [often shorter](https://codegolf.stackexchange.com/a/61526/20260) than programs that loop. For evaluation to terminate, there must be control flow to prevent a recursive call for the base case. Python has a [ternary condition operator](https://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator) that fits the bill.
```
f=lambda x:base_value if is_base_case else recursive_value
```
Note that [list selection](https://codegolf.stackexchange.com/a/62/20260) won't work because Python evaluates both options. Also, regular `if _:` isn't an option because we're in a `lambda`.
---
Python has another option to short-circuit, the logical operator keywords `and` and `or`. The idea is that
```
True or b == True
False and b == False
```
so Python can skip evaluate `b` in these cases because the result is known. Think of the evaluation of `a or b` as "Evaluate `a`. If it's True, output `a`. Otherwise, evaluate and output `b`." So, it's equivalent to write
```
a or b
a if a else b
```
It's the same for `a or b` except we stop if `a` is False.
```
a and b
a if (not a) else b
```
You might wonder why we didn't just write `False if (not a) else b`. The reason is that this works for non-Boolean `a`. Such values are [first converted to a Boolean](https://docs.python.org/2.4/lib/truth.html). The number `0`, `None`, and the empty list/tuple/set become `False`, and are so called "Falsey". The rest are "Truthy".
So, `a or b` and `a and b` always manages to produce either `a` or `b`, while forming a correct Boolean equation.
```
(0 or 0) == 0
(0 or 3) == 3
(2 or 0) == 2
(2 or 3) == 2
(0 and 0) == 0
(0 and 3) == 0
(2 and 0) == 0
(2 and 3) == 3
('' or 3) == 3
([] and [1]) == []
([0] or [1]) == [0]
```
---
Now that we understand Boolean short-circuiting, let's use it in recursive functions.
```
f=lambda x:base_value if is_base_case else recursive_value
```
The simplest and most common situation is when the base is something like `f("") = ""`, sending a Falsey value to itself. Here, it suffices to do `x and` with the argument.
For example, this function doubles each character in a string, `f("abc") == "aabbcc"`.
```
f=lambda s:s and s[0]*2+f(s[1:])
```
Or, this recursively sums the cubes of numbers `1 through n`, so `f(3)==36`.
```
f=lambda n:n and n**3+f(n-1)
```
Another common situation is for your function to take non-negative numbers to lists, with a base case of `0` giving the empty list. We need to transform the number to a list while preserving Truthiness. One way is `n*[5]`, where the list can be anything nonempty. This seems silly, but it works.
So, the following returns the list `[1..n]`.
```
f=lambda n:n*[5]and f(n-1)+[n]
```
Note that negative `n` will also give the empty list, which works here, but not always. For strings, it's similar with any non-empty string. If you've previously defined such a value, you can save chars by using it.
More generally, when your base value is an empty list, you can use the arithmetic values `True == 1` and `False == 0` to do:
```
[5]*(is_not_base_case)and ...
```
TODO: Truthy base value
---
TODO: `and/or`
[Answer]
Cut out newlines wherever you can.
At the top-level, it doesn't matter.
```
a=1
b=9
```
Takes the same amount of characters as:
```
a=1;b=9
```
In the first case you have a newline instead of a `;`. But in function bodies, you save however deep the nesting level is:
```
def f():
a=1;b=9
```
Actually in this case, you can have them all on one line:
```
def f():a=1;b=9
```
If you have an `if` or a `for`, you can likewise have everything on one line:
```
if h:a=1;b=9
for g in(1,2):a=1;b=9
```
But if you have a nesting of control structures (e.g. `if` in a `for`, or `if` in a `def`), then you need the newline:
```
if h:for g in(1,2):a=1;b=9 #ERROR
if h:
for g in(1,2):a=1;b=9 # SAUL GOODMAN
```
[Answer]
## Use eval to iterate
Say you want to apply `f` composed `k` times to the number `1`, then print the result.
This can be done via an `exec` loop,
```
n=1
exec("n=f(n);"*k)
print(n)
```
which runs code like `n=1;n=f(n);n=f(n);n=f(n);n=f(n);n=f(n);print(n)`.
But, it's one character shorter to use `eval`
```
print(eval("f("*k+'1'+")"*k))
```
which evaluates code like `f(f(f(f(f(1)))))` and prints the result.
This does not save chars in Python 2 though, where `exec` doesn't need parens but `eval` still does. It does still help though when `f(n)` is an expression in which `n` appears only once as the first or last character, letting you use only one string multiplication.
[Answer]
One trick I have encountered concerns returning or printing Yes/No answers:
```
print 'YNeos'[x::2]
```
x is the condition and can take value 0 or 1.
I found this rather brilliant.
[Answer]
A condition like
```
s = ''
if c:
s = 'a'
```
can be written as
```
s = c*'a'
```
and there is possibly a need for parenthesis for condition.
This can also be combined with other conditions as (multiple ifs)
```
s = c1*'a' + c2*'b'
```
or (multiple elifs)
```
s = c1*'a' or c2*'b'
```
For example FizzBuzz problem's solution will be
```
for i in range(n):
print((i%3<1)*"Fizz"+(i%5<1)*"Buzz" or i)
```
[Answer]
# Use Splat (`*`) to pass a bunch of single character strings into a function
For example:
```
a.replace("a","b")
a.replace(*"ab") -2 bytes
some_function("a","b","c")
some_function(*"abc") -5 bytes
```
In fact, if you have `n` single-character strings, you will save `3(n - 1) - 1` or `3n - 4` bytes by doing this (because each time, you remove the `","` for each one and add a constant `*`).
[Answer]
## Trig without imports
You can compute `cos` and `sin` without needing to `import math` by using complex arithmetic. For an angle of `d` degrees, its cosine is
```
(1j**(d/90)).real
```
and its sine is
```
(1j**(d/90)).imag
```
Here, `1j` is how Python writes the imaginary unit \$i\$. If your angle is `r` radians, you'll need to use `1j**(r/(pi/2))`, using a decimal approximation of `pi/2` if the challenge allows it.
If you're curious, this all works because of [Euler's formula](https://en.wikipedia.org/wiki/Euler%27s_formula):
$$i^x = (e^{i \pi /2})^x = e^{i \pi /2 \cdot x} = \cos(\pi/2 \cdot x) + i \sin(\pi /2 \cdot x)$$
[Answer]
`!=` can be replaced with `-`
here is a example
```
n=int(input())
if n!=69:
print("thanks for being mature")
```
instead of using `!=` you can use `-`
after that it should look like this
```
n=int(input())
if n-69:
print("thanks for being mature")
```
[Answer]
## Multiple **if** statements in comprehensions
If you need to keep multiple conditions inside comprehension, you can replace **and** with **if** to save a byte each time.
Works in Python 2 and 3.
```
[a for a in 'abc'if cond1()and cond2()or cond3()and cond4()and cond5()]
[a for a in 'abc'if cond1()if cond2()or cond3()if cond4()if cond5()]
```
[Try it online!](https://tio.run/##hZC9CgIxEIT7PMV20cLi/hpbQbCxshOLmOx5i7o5Yg706WMIGhTBlMPufDs748MPlusQDPagLZtqNl8KGB2xB7kaUJ@JT2lCnixDBQvYuQmlAId@cpyUeNvrgr2O9rW63D78SWZAUwA0P/flBtQV2HrAO@rJo5GZ1hZobSlOVwB0EbD9Ov0vlhB7Bb11oIDihjpqSbl2yg3GhVcVlN@gnOcQwhM "Python 2 – Try It Online")
[Answer]
## Build a string instead of joining
To concatenate strings or characters, it can be shorter to repeatedly append to the empty string than to `join`.
**23 chars**
```
s=""
for x in l:s+=f(x)
```
**25 chars**
```
s="".join(f(x)for x in l)
```
Assume here that `f(x)` stands for some expression in `x`, so you can't just `map`.
But, the `join` may be shorter if the result doesn't need saving to a variable or if the `for` takes newlines or indentation.
[Answer]
# String keys to dicts
For a dictionary with string keys which also happen to be valid Python variable names, you can get a saving if there's at least three items by using `dict`'s keyword arguments:
```
{'a':1,'e':4,'i':9}
dict(a=1,e=4,i=9)
```
The more string keys you have, the more quote characters you'll save, so this is particularly beneficial for large dictionaries (e.g. for a kolmogorov challenge).
[Answer]
When squaring single letter variables, it is shorter to times it by itself
```
>>> x=30
>>> x*x
900
```
Is one byte shorter than
```
>>> x=30
>>> x**2
900
```
[Answer]
When mapping a function on a list in Python 3, instead of doing `[f(x)for x in l]` or `list(map(f,l))`, do `[*map(f,l)]`.
It works for all other functions returning generators too (like `filter`).
The best solution is still switching to Python 2 though
[Answer]
## Iterate over adjacent pairs
It's common to want to iterate over adjacent pairs of items in a list or string, i.e.
```
"golf" -> [('g','o'), ('o','l'), ('l','f')]
```
There's a few methods, and which is shortest depends on specifics.
**Shift and zip**
```
## 47 bytes
l=input()
for x,y in zip(l,l[1:]):do_stuff(x,y)
```
Create a list of adjacent pairs, by removing the first element and zipping the original with the result. This is most useful in a list comprehension like
```
sum(abs(x-y)for x,y in zip(l,l[1:]))
```
You can also use `map` with a two-input function, though note that the original list is no longer truncated.
```
## Python 2
map(cmp,l[:-1],l[1:])
```
**Keep the previous**
```
## 41 bytes, Python 3
x,*l=input()
for y in l:do_stuff(x,y);x=y
```
Iterate over the elements of the list, remembering the element from a previous loop. This works best with Python 3's ability to unpack to input into the initial and remaining elements.
If there's an initial value of `x` that serves as a null operation in `do_stuff(x,y)`, you can iterate over the whole list.
```
## 39 bytes
x=''
for y in input():do_stuff(x,y);x=y
```
**Truncate from the front**
```
## 46 bytes
l=input()
while l[1:]:do_stuff(*l[:2]);l=l[1:]
```
Keep shortening the list and act on the first two elements. This works best when your operation is better-expressed on a length-two list or string than on two values.
---
I've written these all as loops, but they also lend to a recursive functions. You can also adjust to get cyclic pairs by putting the first element at the end of the list, or as the initial previous-value.
---
The Python 3.8 "walrus" [assignment expressions](https://codegolf.stackexchange.com/a/180041/20260) allow a short expression to give pairs, though with an extra initial element.
```
>>> p=''
>>> [(p,p:=c)for c in"golf"]
[('', 'g'), ('g', 'o'), ('o', 'l'), ('l', 'f')]
```
] |
[Question]
[]
|
[Question]
[
The [Vigenère cipher](http://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher) is a substitution cipher where the encryption of each letter of the plaintext depends on a different character in a keyword. This stops you using simple methods of frequency analysis to guess the correct substitution. However, the keyword is repeated if it is shorter than the plaintext. This is a weakness. If the length of the keyword is known (n, say), however, and is much shorter than the message, then you can decompose the message into separate sections by taking every nth letter. You can then use frequency analysis on these.
The [Kasiski examination](http://en.wikipedia.org/wiki/Kasiski_examination) is a method to work out the most likely key lengths. It does this by considering identical substrings which happen to be a multiple of the key length apart. They are therefore encrypted in the same way. Turning this round, identical substrings in the ciphertext are likely to be a multiple of the key length apart. If you identify these distances, then the key length is likely to be a common factor of all these distances.
Your job is to write a function or program that can guess the most likely length of the keyword, given some encrypted text. To be precise, the function or program (just called function below) will satisfy the following:
* Inputs consist of a string representing the ciphertext and a positive integer (**len**, for the purposes of this spec) representing the shortest common substring to look at.
* The ciphertext will consist of upper case A-Z characters only. Any length is permitted.
* You can assume valid inputs without checking.
* The inputs may be passed in, or read from stdin.
* The function will identify all pairs of identical substrings in the ciphertext which have a length of *at least* **len**.
* Substrings in each pair may not overlap but substrings in different pairs can overlap.
* The function will return, or write to stdout, the highest common factor of the distances between the starts of these identical pairs.
* If there are no identical substrings then the function will return 0.
For example:
"AAAAAAAAAAAAAAAAAA", n returns 1 for any n from 1 to 8, 9 for n = 9 (as the only possible non-overlapping substrings of length 9 happen to be the same) and 0 otherwise.
"ABCDEFGHIJKL", n returns 0 for any n
"ABCDEABCDE", n returns 5 for n<=5 and 0 otherwise
"ABCABABCAB", 2 returns 1 because "AB" pairs are separated by 2,3,5 & 8
"ABCABABCAB", 3 returns 5
"**VHVS**SP*QUCE*MRVBVBBB**VHVS**URQGIBDUGRNICJ*QUCE*RVUAXSSR", 4 returns 6 because the repeating "VHVS" are 18 characters apart, while "QUCE" is separated by 30 characters
Naturally, lowest byte count wins and avoid standard loopholes.
[Answer]
# CJam, 67 bytes
Definitely still room for improvement, but I'll post what I have so far.
[Try it online](http://cjam.aditsu.net/#code=0r%3AT%2C%2Cri%3E%7BT%2CL(-%2C_m*%7B~%3AXT%3EL%3CT%40LX%2Be%3E%2C%7B0t%7D%2FX%3E%5C%23_W%3E%5C2%24%3F%7B%5C1%24_!%2B%25%7Dh%3B%7D%2F%7DfL)
```
0r:T,,ri>{T,L(-,_m*{~:XT>L<T@LX+e>,{0t}/X>\#_W>\2$?{\1$_!+%}h;}/}fL
```
[Answer]
# JavaScript (ES6) 117
```
F=(s,n,G=(a,b)=>b?G(b,a%b):a)=>(i=>{
for(f=i;s[(j=i+n)-1];i++)
for(;p=~s.indexOf(s.substr(i,n),j++);)
f=G(~p-i,f)
})(0)|f
```
**Ungolfed**
```
F=(s,n)=>
{
var G = (a,b) => b ? G(b,a%b) : a; // GCD function
var p,w,i,j, f = 0; // f starting divisor
for(i = 0; s[i + n - 1]; ++i) // scan s for each substring of lenght n
{
w = s.substr(i,n);
for (j=i+n; (p = s.indexOf(w,j)) != -1; ++j) // find all occurrencies of substring in the rest f the string
f = G(p - i, f); // p-i is the distance between pairs
}
return f
}
```
**Test** In Firefox/FireBug console
```
;["AAAAAAAAAAAAAAAAAA","ABCDEFGHIJKL","ABCDEABCDE","ABCABABCAB",
"VHVSSPQUCEMRVBVBBBVHVSURQGIBDUGRNICJQUCERVUAXSSR"]
.forEach(s=>{
for(o=[],i=1;i<=10;i++) o.push(i+':'+F(s,i));
console.log(s+' '+o)
})
```
*Output*
```
AAAAAAAAAAAAAAAAAA 1:1,2:1,3:1,4:1,5:1,6:1,7:1,8:1,9:9,10:0
ABCDEFGHIJKL 1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0
ABCDEABCDE 1:5,2:5,3:5,4:5,5:5,6:0,7:0,8:0,9:0,10:0
ABCABABCAB 1:1,2:1,3:5,4:5,5:5,6:0,7:0,8:0,9:0,10:0
VHVSSPQUCEMRVBVBBBVHVSURQGIBDUGRNICJQUCERVUAXSSR 1:1,2:1,3:6,4:6,5:0,6:0,7:0,8:0,9:0,10:0
```
] |
[Question]
[]
|
[Question]
[
Your job is to write a program (or two separate programs) in any language that:
1. Can take a completed Sudoku board as input (in any logical format) and compress it into a string of characters
2. Can take the compressed string as input and decompress it to get the *exact* same completed Sudoku board (output in any logical format of 9 rows)
**Note:** Use the rules of Sudoku to your advantage; that is the idea behind this challenge.
[Sudoku rules on Wikipedia](http://en.wikipedia.org/wiki/Sudoku)
# Rules
* Only printable ASCII characters (32 - 126) are allowed in the compressed output (eg. **no multibyte characters**).
* You can assume that the input is a *valid 3x3 Sudoku board* (normal rules, no variations).
* I won't impose a time-limit, but do not create a brute-force algorithm. Or, submitters should be able to test their submissions before posting (Thanks Jan Dvorak).
If you have any questions or concerns, you can ask for clarification or make suggestions in the comments.
# Winning Conditions
Score = sum of the number of characters from all ten test cases
*Lowest score wins.*
# Test Cases
You may use these to test how well your program works.
```
9 7 3 5 8 1 4 2 6
5 2 6 4 7 3 1 9 8
1 8 4 2 9 6 7 5 3
2 4 7 8 6 5 3 1 9
3 9 8 1 2 4 6 7 5
6 5 1 7 3 9 8 4 2
8 1 9 3 4 2 5 6 7
7 6 5 9 1 8 2 3 4
4 3 2 6 5 7 9 8 1
7 2 4 8 6 5 1 9 3
1 6 9 2 4 3 8 7 5
3 8 5 1 9 7 2 4 6
8 9 6 7 2 4 3 5 1
2 7 3 9 5 1 6 8 4
4 5 1 3 8 6 9 2 7
5 4 2 6 3 9 7 1 8
6 1 8 5 7 2 4 3 9
9 3 7 4 1 8 5 6 2
1 5 7 6 8 2 3 4 9
4 3 2 5 1 9 6 8 7
6 9 8 3 4 7 2 5 1
8 2 5 4 7 6 1 9 3
7 1 3 9 2 8 4 6 5
9 6 4 1 3 5 7 2 8
5 4 1 2 9 3 8 7 6
2 8 9 7 6 1 5 3 4
3 7 6 8 5 4 9 1 2
8 3 5 4 1 6 9 2 7
2 9 6 8 5 7 4 3 1
4 1 7 2 9 3 6 5 8
5 6 9 1 3 4 7 8 2
1 2 3 6 7 8 5 4 9
7 4 8 5 2 9 1 6 3
6 5 2 7 8 1 3 9 4
9 8 1 3 4 5 2 7 6
3 7 4 9 6 2 8 1 5
6 2 8 4 5 1 7 9 3
5 9 4 7 3 2 6 8 1
7 1 3 6 8 9 5 4 2
2 4 7 3 1 5 8 6 9
9 6 1 8 2 7 3 5 4
3 8 5 9 6 4 2 1 7
1 5 6 2 4 3 9 7 8
4 3 9 5 7 8 1 2 6
8 7 2 1 9 6 4 3 5
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 1 4 3 6 5 8 9 7
3 6 5 8 9 7 2 1 4
8 9 7 2 1 4 3 6 5
5 3 1 6 4 8 9 7 2
6 4 8 9 7 2 5 3 1
9 7 2 5 3 1 6 4 8
1 4 5 7 9 2 8 3 6
3 7 6 5 8 4 1 9 2
2 9 8 3 6 1 7 5 4
7 3 1 9 2 8 6 4 5
8 5 9 6 4 7 3 2 1
4 6 2 1 3 5 9 8 7
6 2 4 8 7 3 5 1 9
5 8 7 4 1 9 2 6 3
9 1 3 2 5 6 4 7 8
5 2 7 4 1 6 9 3 8
8 6 4 3 2 9 1 5 7
1 3 9 5 7 8 6 4 2
2 9 1 8 5 4 3 7 6
3 4 8 6 9 7 5 2 1
6 7 5 1 3 2 4 8 9
7 1 2 9 4 5 8 6 3
4 8 3 2 6 1 7 9 5
9 5 6 7 8 3 2 1 4
2 4 6 7 1 3 9 8 5
1 8 5 4 9 6 7 3 2
9 3 7 8 2 5 1 4 6
6 7 8 5 4 2 3 9 1
4 9 3 1 6 8 2 5 7
5 1 2 3 7 9 4 6 8
8 2 4 9 5 7 6 1 3
7 5 9 6 3 1 8 2 4
3 6 1 2 8 4 5 7 9
8 6 1 2 9 4 5 7 3
4 7 5 3 1 8 6 9 2
3 9 2 5 6 7 8 1 4
2 3 6 4 5 9 7 8 1
1 5 4 7 8 3 2 6 9
9 8 7 6 2 1 3 4 5
5 2 9 1 7 6 4 3 8
6 4 8 9 3 2 1 5 7
7 1 3 8 4 5 9 2 6
```
Credit to [http://www.opensky.ca/~jdhildeb/software/sudokugen/](http://www.opensky.ca/%7Ejdhildeb/software/sudokugen/) for some of these
*If you find any issues with the test cases, please tell me.*
[Answer]
# Haskell, 107 points
```
import Control.Monad
import Data.List
type Elem = Char
type Board = [[Elem]]
type Constraints = ([Elem],[Elem],[Elem])
digits :: [Elem]
digits = "123456789"
noCons :: Constraints
noCons = ([],[],[])
disjointCons :: Constraints
disjointCons = ("123","456","789") -- constraints from a single block - up to isomorphism
triples :: [a] -> [[a]]
triples [a,b,c,d,e,f,g,h,i] = [[a,b,c],[d,e,f],[g,h,i]]
(+++) :: Constraints -> Constraints -> Constraints
(a,b,c) +++ (d,e,f) = (a++d,b++e,c++f)
maxB = 12096
-- length $ assignments noCons disjointCons
maxC = 216 -- worst case: rows can be assigned independently
maxD = maxB
maxE = 448
-- foldl1' max [length $ assignments disjointCons colCons
-- | (_, colCons) <- map constraints $ assignments ([],[1],[1]) ([],[1],[1]),
-- let ([a,d,g],[b,e,h],[c,f,i]) = colCons,
-- a < d, d < g, b < e, e < h, c < f, f < i]
maxF = 2 ^ 3 -- for each row the relevant column constraints can be in the same column (no assignment),
-- or in two or three columns (two assignments)
maxG = maxC
maxH = maxF
-- constraints -> list of block solutions
assignments :: Constraints -> Constraints -> [[Elem]]
assignments (r1,r2,r3) (c1,c2,c3) = do
a <- digits \\ (r1 ++ c1); let digits1 = digits \\ [a]
b <- digits1 \\ (r1 ++ c2); let digits2 = digits1 \\ [b]
c <- digits2 \\ (r1 ++ c3); let digits3 = digits2 \\ [c]
d <- digits3 \\ (r2 ++ c1); let digits4 = digits3 \\ [d]
e <- digits4 \\ (r2 ++ c2); let digits5 = digits4 \\ [e]
f <- digits5 \\ (r2 ++ c3); let digits6 = digits5 \\ [f]
g <- digits6 \\ (r3 ++ c1); let digits7 = digits6 \\ [g]
h <- digits7 \\ (r3 ++ c2); let digits8 = digits7 \\ [h]
i <- digits8 \\ (r3 ++ c3)
return [a,b,c,d,e,f,g,h,i]
-- block solution -> tuple of constraints
constraints :: [Elem] -> (Constraints, Constraints)
constraints [a,b,c,d,e,f,g,h,i] = (([a,b,c],[d,e,f],[g,h,i]),([a,d,g],[b,e,h],[c,f,i]))
------------------------------------------------------------------------------------------
-- solution -> Integer
solution2ix :: Board -> Integer
solution2ix [a,b,c,d,e,f,g,h,i] =
let (ar, ac) = constraints a
(br, bc) = constraints b
(_ , cc) = constraints c
(dr, dc) = constraints d
(er, ec) = constraints e
(_ , fc) = constraints f
(gr, _ ) = constraints g
(hr, _ ) = constraints h
(_ , _ ) = constraints i
Just ixA = findIndex (a ==) $ assignments noCons noCons
Just ixB = findIndex (b ==) $ assignments ar noCons
Just ixC = findIndex (c ==) $ assignments (ar +++ br) noCons
Just ixD = findIndex (d ==) $ assignments noCons ac
Just ixE = findIndex (e ==) $ assignments dr bc
Just ixF = findIndex (f ==) $ assignments (dr +++ er) cc
Just ixG = findIndex (g ==) $ assignments noCons (ac +++ dc)
Just ixH = findIndex (h ==) $ assignments gr (bc +++ ec)
Just ixI = findIndex (i ==) $ assignments (gr +++ hr) (cc +++ fc)
in foldr (\(i,m) acc -> fromIntegral i + m * acc) (fromIntegral ixA)
$ zip [ixH, ixG, ixF, ixE, ixD, ixC, ixB] [maxH, maxG, maxF, maxE, maxD, maxC, maxB]
-- list of rows
-- -> list of threes of triples
-- -> three triples of threes of triples
-- -> three threes of triples of triples
-- -> nine triples of triples
-- -> nine blocks
toBoard :: [[Elem]] -> Board
toBoard = map concat . concat . map transpose . triples . map triples
toBase95 :: Integer -> String
toBase95 0 = ""
toBase95 ix = toEnum (32 + fromInteger (ix `mod` 95)) : toBase95 (ix `div` 95)
------------------------------------------------------------------------------------------
ix2solution :: Integer -> Board
ix2solution ix =
let (ixH', ixH) = ix `divMod` maxH
(ixG', ixG) = ixH' `divMod` maxG
(ixF', ixF) = ixG' `divMod` maxF
(ixE', ixE) = ixF' `divMod` maxE
(ixD', ixD) = ixE' `divMod` maxD
(ixC', ixC) = ixD' `divMod` maxC
(ixA , ixB) = ixC' `divMod` maxB
a = assignments noCons noCons !! fromIntegral ixA
(ra, ca) = constraints a
b = assignments ra noCons !! fromIntegral ixB
(rb, cb) = constraints b
c = assignments (ra +++ rb) noCons !! fromIntegral ixC
(_ , cc) = constraints c
d = assignments noCons ca !! fromIntegral ixD
(rd, cd) = constraints d
e = assignments rd cb !! fromIntegral ixE
(re, ce) = constraints e
f = assignments (rd +++ re) cc !! fromIntegral ixF
(_ , cf) = constraints f
g = assignments noCons (ca +++ cd) !! fromIntegral ixG
(rg, _ ) = constraints g
h = assignments rg (cb +++ ce) !! fromIntegral ixH
(rh, _ ) = constraints h
[i] = assignments (rg +++ rh) (cc +++ cf)
in [a,b,c,d,e,f,g,h,i]
-- nine blocks
-- -> nine triples of triples
-- -> three threes of triples of triples
-- -> three triples of threes of triples
-- -> list of threes of triples
-- -> list of rows
fromBoard :: Board -> [[Elem]]
fromBoard = map concat . concat . map transpose . triples . map triples
fromBase95 :: String -> Integer
fromBase95 "" = 0
fromBase95 (x:xs) = (toInteger $ fromEnum x) - 32 + 95 * fromBase95 xs
------------------------------------------------------------------------------------------
main = do line <- getLine
if length line <= 12
then putStrLn $ unlines $ map (intersperse ' ') $ fromBoard $ ix2solution $ fromBase95 line
else do nextLines <- replicateM 8 getLine
putStrLn $ toBase95 $ solution2ix $ toBoard $ map (map head.words) $ line:nextLines
```
The test case results:
```
q`3T/v50 =3,
^0NK(F4(V6T(
d KTTB{pJc[
B]^v[omnBF-*
WZslDPbcOm7'
)
ukVl2x/[+6F
qzw>GjmPxzo%
KE:*GH@H>(m!
SeM=kA`'3(X*
```
The code isn't pretty, but it works. The basis of the algorithm is that while enumerating all solutions would take too long, enumerating all solutions within a single block is rather quick - in fact, it's faster than the subsequent conversion to base95. The whole thing runs within seconds in the interpreter on my low-end machine. A compiled program would finish immediately.
The heavy lifting is done by the `solution2ix` function, which, for each 3x3 block, it generates all possible permutations, subject to constraints from the left and from above, until it finds the one in the encoded solution, remembering only the index of said permutation. Then it combines the indexes using some precomputed weights and the Horner's scheme.
In the other direction, the `ix2solution` function first decomposes the index into nine values. Then for each block it indexes the list of possible permutations with its respective value, then extracts the constraints for the next blocks.
`assignments` is a simple but ugly unrolled recursion using the list monad. It generates the list of permutations given a set of constraints.
The real power comes from the tight bounds on the permutation list lengths:
* The top left corner is unconstrained. The number of permutations is simply `9!`. This value is never used except to find an upper bound for the output length.
* The blocks next to it only have one set of constraints - from the top left. A naive upper bound `6*5*4*6!` is seven times worse than the actual count found by enumeration: `12096`
* The top right corner is constrained twice from left. Each row can only have six permutations, and in the worst case (actually in every valid case), the assignment is independent. Similarly for the bottom left corner.
* The center piece was the hardest to estimate. Once again the brute force wins - count the permutation for each possible set of constraints up to isomorphism. Takes a while, but it's only needed once.
* The right center piece has a double constraint from the left, which forces each row up to a permutation, but also a single constraint from the top, which ensures only two permutations per row are actually possible. Similarly for the bottom center piece.
* The bottom right corner is fully determined by its neighbors. The sole permutation is never actually verified when computing the index. Forcing evaluation would be easy, it's just not necessary.
The product of all these limits is `71025136897117189570560` ~= `95^11.5544`, which means that no code is longer than 12 characters and almost a half of them should be 11 characters or fewer. I have decided not to distinguish between a shorter string and the same string right-padded with spaces. Spaces anywhere else are significant.
The theoretical limit of encoding efficiency for prefix-free codes - base-95 logarithm of `6670903752021072936960` - is `11.035`, meaning that even an optimal algorithm cannot avoid producing length-12 outputs, though it will produce them in only 3.5% of all cases. Allowing length to be significant (or equivalently, adding trailing spaces) does add a few codes (1% of the total amount), but not enough to eliminate the need for length-12 codes.
[Answer]
## Python, 130 points
```
j1:4}*KYm6?D
h^('gni9X`g'#
$2{]8=6^l=fF!
BS ;1;J:z"^a"
\/)gT)sixb"A+
WI?TFvj%:&3-\$
*iecz`L2|a`X0
eLbt<tf|mFN'&
;KH_TzK$erFa!
7T=1*6$]*"s"!
```
The algorithm works by encoding each position in the board, one at a time, into a big integer. For each position, it calculates the possible values given all the assignments encoded so far. So if [1,3,7,9] are the possible values for a given position, it takes 2 bits to encode the choice.
The nice thing about this scheme is that if a position has only a single remaining choice, it takes no space to encode.
Once we have the big integer we write it out in base 95.
There are probably better encoding orderings than lexicographic, but I haven't thought a lot about it.
Encoder:
```
import sys
sets = [range(i*9, i*9+9) for i in xrange(9)]
sets += [range(i, 81, 9) for i in xrange(9)]
sets += [[i/3*27+i%3*3+j/3*9+j%3 for j in xrange(9)] for i in xrange(9)]
M = []
for line in sys.stdin.readlines():
M += [int(x) for x in line.split()]
A = 0
m = 1
for i in xrange(81):
allowed = set(xrange(1,10))
for s in sets:
if i in s:
for j in s:
if j < i: allowed.discard(M[j])
allowed = sorted(allowed)
A += m * allowed.index(M[i])
m *= len(allowed)
s=''
while A != 0:
s+='%c'%(32+A%95)
A /= 95
print s
```
Decoder:
```
sets = [range(i*9, i*9+9) for i in xrange(9)]
sets += [range(i, 81, 9) for i in xrange(9)]
sets += [[i/3*27+i%3*3+j/3*9+j%3 for j in xrange(9)] for i in xrange(9)]
s=raw_input()
A=0
m=1
while s != '':
A += m * (ord(s[0])-32)
s = s[1:]
m *= 95
M=[]
for i in xrange(81):
allowed = set(xrange(1,10))
for s in sets:
if i in s:
for j in s:
if j < i: allowed.discard(M[j])
allowed = sorted(allowed)
M += [allowed[A%len(allowed)]]
A /= len(allowed)
for i in xrange(9):
print ' '.join(str(x) for x in M[i*9:i*9+9])
```
Run it like this:
```
> cat sudoku1 | ./sudokuEnc.py | ./sudokuDec.py
9 7 3 5 8 1 4 2 6
5 2 6 4 7 3 1 9 8
1 8 4 2 9 6 7 5 3
2 4 7 8 6 5 3 1 9
3 9 8 1 2 4 6 7 5
6 5 1 7 3 9 8 4 2
8 1 9 3 4 2 5 6 7
7 6 5 9 1 8 2 3 4
4 3 2 6 5 7 9 8 1
```
[Answer]
# perl - score 115 113 103 113
Output:
```
"#1!A_mb_jB)
FEIV1JH~vn"
$\\XRU*LXea.
EBIC5fPxklB
5>jM7(+0MrM
!'Wu9FS2d~!W
":`R60C"}z!k
:B&Jg[fL%\j
"L28Y?3`Q>4w
o0xPz8)_i%-
```
Output:
```
# note this line is empty
S}_h|bt:za
%.j0.6w>?RM+
:H$>a>Cy{7C
'57UHjcWQmcw
owmK0NF?!Fv
# }aYExcZlpD
nGl^K]xH(.\
9ii]I$voC,x
!:MR0>I>PuTU
```
None of those lines have a terminating space. Note that the first line is empty.
This algorithm works as follows. To compress:
1. Start with an empty 'current' string representing the Sudoku grid
2. Consider adding in turn each of the digits 1 .. 9 to that string, and determine which is viable.
3. Get the next digit from the answer grid (and add it to current)
4. If only one is viable, there is nothing to code
5. If more than one is viable, count the number of viable options, sort them, and code that digit as the index into the sorted array. Record the digit and the number viable as a 2-tuple in an array.
6. When all done, code each of the 2-tuples (in reverse order) in a variable based number stored as a bigint.
7. Express the bigint in base 95.
To decode:
1. Start with an empty 'current' string representing the Sudoku grid
2. Decode the base95 number to a bigint
3. Consider adding in turn each of the digits 1 .. 9 to that string, and determine which is viable.
4. If only one is viable, there is nothing to code; add that choice to the grid
5. If more than one is viable, count the number of viable options, sort them, and code that digit as the index into the sorted array.
6. Decode the variable-base bigint using the number of viable options as the base, and the modulus as the index into the array, and output that digit as a cell value.
In order to determine the number of viable options, Games::Sudoku::Solver is used. That's mainly for clarity as there are 3 line Sudoku solvers on this site.
To do all 10 took 8 seconds on my laptop.
The `fudge` operation sorts the array differently to achieve the minimal value for the test cases. As documented, this is a fudge. The fudge reduces the score from 115 to 103. It is handcrafted to ensure that the bigint code for the first test is 0. The worst-case score for any sudoku is 12 giving a score of 120. I thus don't think this counts as hard-coding; rather it optimises for the test data. To see it work without this, change `sort fudge` into `sort` in both places.
Code follows:
```
#!/usr/bin/perl
use strict;
use warnings;
use Getopt::Long;
use bigint;
use Games::Sudoku::Solver qw (:Minimal set_solution_max count_occupied_cells);
# NOTE THIS IS NOT USED BY DEFAULT - see below and discussion in comments
my @fudgefactor = qw (9 7 3 5 8 1 4 2 6 5 2 6 4 7 3 1 9 8 1 8 4 2 9 6 7 5 3 2 4 7 8 6 5 3 1 9 3 9 8 1 2 4 6 7 5 6 5 1 7 3 9 8 4 2 8 1 9 3 4 2 5 6 7 7 6 5 9 1 8 2 3 4 4 3 2 6 5 7 9 8 1);
my $fudgeindex=0;
my $fudging=0; # Change to 1 to decrease score by 10
sub isviable
{
no bigint;
my $current = shift @_;
my @test = map {$_ + 0} split(//, substr(($current).("0"x81), 0, 81));
my @sudoku;
my @solution;
set_solution_max (2);
my $nsolutions;
eval
{
sudoku_set(\@sudoku, \@test);
$nsolutions = sudoku_solve(\@sudoku, \@solution);
};
return 0 unless $nsolutions;
return ($nsolutions >=1);
}
sub getnextviable
{
my $current = shift @_; # grid we have so far
my %viable;
for (my $i = 1; $i<=9; $i++)
{
my $n;
my $solution;
$viable{$i} = 1 if (isviable($current.$i));
}
return %viable;
}
sub fudge
{
return $a<=>$b unless ($fudging);
my $k=$fudgefactor[$fudgeindex];
my $aa = ($a+10-$k) % 10;
my $bb = ($b+10-$k) % 10;
return $aa<=>$bb;
}
sub compress
{
my @data;
while (<>)
{
chomp;
foreach my $d (split(/\s+/))
{
push @data, $d;
}
}
my $code = 0;
my $current = "";
my @codepoints;
foreach my $d (@data)
{
my %viable = getnextviable($current);
die "Digit $d is unexpectedly not viable - is sudoku impossible?" unless ($viable{$d});
my $nviable = scalar keys(%viable);
if ($nviable>1)
{
my $n=0;
foreach my $k (sort fudge keys %viable)
{
if ($k==$d)
{
no bigint;
my %cp = ( "n"=> $n, "v"=> $nviable);
unshift @codepoints, \%cp;
last;
}
$n++;
}
}
$fudgeindex++;
$current .= $d;
}
foreach my $cp (@codepoints)
{
$code = ($code * $cp->{"v"})+$cp->{"n"};
}
# print in base 95
my $out="";
while ($code)
{
my $digit = $code % 95;
$out = chr($digit+32).$out;
$code -= $digit;
$code /= 95;
}
print "$out";
}
sub decompress
{
my $code = 0;
# Read from base 95 into bigint
while (<>)
{
chomp;
foreach my $char (split (//, $_))
{
my $c =ord($char)-32;
$code*=95;
$code+=$c;
}
}
# Reconstruct sudoku
my $current = "";
for (my $cell = 0; $cell <81; $cell++)
{
my %viable = getnextviable($current);
my $nviable = scalar keys(%viable);
die "Cell $cell is unexpectedly not viable - is sudoku impossible?" unless ($nviable);
my $mod = $code % $nviable;
$code -= $mod;
$code /= $nviable;
my @v = sort fudge keys (%viable);
my $d = $v[$mod];
$current .= $d;
print $d.(($cell %9 != 8)?" ":"\n");
$fudgeindex++;
}
}
my $decompress;
GetOptions ("d|decompress" => \$decompress);
if ($decompress)
{
decompress;
}
else
{
compress;
}
```
[Answer]
# CJam, 309 bytes
This is just a quick baseline solution. I'm sorry I did this in a golfing language, but it was actually the simplest way to do it. I'll add an explanation of the actual code tomorrow, but I've outlined the algorithm below.
**Encoder**
```
q~{);}%);:+:(9b95b32f+:c
```
**Decoder**
```
l:i32f-95b9bW%[0]64*+64<W%:)8/{_:+45\-+}%z{_:+45\-+}%z`
```
[Test it here.](http://cjam.aditsu.net/)
The input of the encoder (on STDIN) and the output of the decoder (on STDOUT) are in the form of a nested CJam array. E.g.
```
[[8 3 5 4 1 6 9 2 7] [2 9 6 8 5 7 4 3 1] [4 1 7 2 9 3 6 5 8] [5 6 9 1 3 4 7 8 2] [1 2 3 6 7 8 5 4 9] [7 4 8 5 2 9 1 6 3] [6 5 2 7 8 1 3 9 4] [9 8 1 3 4 5 2 7 6] [3 7 4 9 6 2 8 1 5]]
```
The 10 test outputs are:
```
U(5wtqmC.-[TM.#aMY#k*)pErHQcg'{
EWrn"^@p+g<5XT5G[r1|bk?q6Nx4~r?
#489pLj5+ML+z@y$]8a@CI,K}B$$Mwn
LF_X^"-h**A!'VZq kHT@F:"ZMD?A0r
?gD;"tw<yG%8y!3S"BC:ojQ!#;i-:\g
qS#"L%`4yei?Ce_r`{@EOl66m^hx77
"EF?` %!H@YX6J0F93->%90O7T#C_5u
9V)R+6@Jx(jg@@U6.DrMO*5G'P<OHv8
(Ua6z{V:hX#sV@g0s<|!X[T,Jy|oQ+K
N,F8F1!@OH1%%zs%dI`Q\q,~oAEl(:O
```
The algorithm is very simple:
* Remove the last column and row.
* Treat the remaining 64 digits as a base-9 number (after decrementing each digit by 1).
* Convert that to base-95, add 32 to each digit and turn that into the corresponding ASCII character.
* For the decoding, reverse the base conversion and fill in the the final column and row with the missing numbers.
[Answer]
# Python 2.7, 107 chars total
**TL;DR** brute-force enumeration of 3x3 squares with top+left constraints
test cases:
```
import itertools
inputs = """
9 7 3 5 8 1 4 2 6
5 2 6 4 7 3 1 9 8
1 8 4 2 9 6 7 5 3
2 4 7 8 6 5 3 1 9
3 9 8 1 2 4 6 7 5
6 5 1 7 3 9 8 4 2
8 1 9 3 4 2 5 6 7
7 6 5 9 1 8 2 3 4
4 3 2 6 5 7 9 8 1
7 2 4 8 6 5 1 9 3
1 6 9 2 4 3 8 7 5
3 8 5 1 9 7 2 4 6
8 9 6 7 2 4 3 5 1
2 7 3 9 5 1 6 8 4
4 5 1 3 8 6 9 2 7
5 4 2 6 3 9 7 1 8
6 1 8 5 7 2 4 3 9
9 3 7 4 1 8 5 6 2
1 5 7 6 8 2 3 4 9
4 3 2 5 1 9 6 8 7
6 9 8 3 4 7 2 5 1
8 2 5 4 7 6 1 9 3
7 1 3 9 2 8 4 6 5
9 6 4 1 3 5 7 2 8
5 4 1 2 9 3 8 7 6
2 8 9 7 6 1 5 3 4
3 7 6 8 5 4 9 1 2
8 3 5 4 1 6 9 2 7
2 9 6 8 5 7 4 3 1
4 1 7 2 9 3 6 5 8
5 6 9 1 3 4 7 8 2
1 2 3 6 7 8 5 4 9
7 4 8 5 2 9 1 6 3
6 5 2 7 8 1 3 9 4
9 8 1 3 4 5 2 7 6
3 7 4 9 6 2 8 1 5
6 2 8 4 5 1 7 9 3
5 9 4 7 3 2 6 8 1
7 1 3 6 8 9 5 4 2
2 4 7 3 1 5 8 6 9
9 6 1 8 2 7 3 5 4
3 8 5 9 6 4 2 1 7
1 5 6 2 4 3 9 7 8
4 3 9 5 7 8 1 2 6
8 7 2 1 9 6 4 3 5
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 1 4 3 6 5 8 9 7
3 6 5 8 9 7 2 1 4
8 9 7 2 1 4 3 6 5
5 3 1 6 4 8 9 7 2
6 4 8 9 7 2 5 3 1
9 7 2 5 3 1 6 4 8
1 4 5 7 9 2 8 3 6
3 7 6 5 8 4 1 9 2
2 9 8 3 6 1 7 5 4
7 3 1 9 2 8 6 4 5
8 5 9 6 4 7 3 2 1
4 6 2 1 3 5 9 8 7
6 2 4 8 7 3 5 1 9
5 8 7 4 1 9 2 6 3
9 1 3 2 5 6 4 7 8
5 2 7 4 1 6 9 3 8
8 6 4 3 2 9 1 5 7
1 3 9 5 7 8 6 4 2
2 9 1 8 5 4 3 7 6
3 4 8 6 9 7 5 2 1
6 7 5 1 3 2 4 8 9
7 1 2 9 4 5 8 6 3
4 8 3 2 6 1 7 9 5
9 5 6 7 8 3 2 1 4
2 4 6 7 1 3 9 8 5
1 8 5 4 9 6 7 3 2
9 3 7 8 2 5 1 4 6
6 7 8 5 4 2 3 9 1
4 9 3 1 6 8 2 5 7
5 1 2 3 7 9 4 6 8
8 2 4 9 5 7 6 1 3
7 5 9 6 3 1 8 2 4
3 6 1 2 8 4 5 7 9
8 6 1 2 9 4 5 7 3
4 7 5 3 1 8 6 9 2
3 9 2 5 6 7 8 1 4
2 3 6 4 5 9 7 8 1
1 5 4 7 8 3 2 6 9
9 8 7 6 2 1 3 4 5
5 2 9 1 7 6 4 3 8
6 4 8 9 3 2 1 5 7
7 1 3 8 4 5 9 2 6
""".strip().split('\n\n')
```
helper function to print sudoku
```
def print_sudoku(m):
for k in m:
print' '.join(str(i) for i in k)
```
generates all possible squares given constraints above and left
see code comment for more details
```
def potential_squares(u1, u2, u3, l1, l2, l3):
"""
returns generator of possible squares given lists of digits above and below
u1 u2 u3
| | |
l1 -- a b c
l2 -- d e f
l3 -- g h i
if no items exist the empty list must be given
"""
for a, b, c, d, e, f, g, h, i in itertools.permutations(xrange(1, 10)):
if a not in u1 and a not in l1 and b not in u2 and b not in l1 and c not in u3 and c not in l1 and d not in u1 and d not in l2 and e not in u2 and e not in l2 and f not in u3 and f not in l2 and g not in u1 and g not in l3 and h not in u2 and h not in l3 and i not in u3 and i not in l3:
yield (a, b, c, d, e, f, g, h, i)
```
extracts all squares from sudoku board as tuples
see code comment for more details
```
def board_to_squares(board):
"""
finds 9 squares in a 9x9 board in this order:
1 1 1 2 2 2 3 3 3
1 1 1 2 2 2 3 3 3
1 1 1 2 2 2 3 3 3
4 4 4 5 5 5 6 6 6
4 4 4 5 5 5 6 6 6
4 4 4 5 5 5 6 6 6
7 7 7 8 8 8 9 9 9
7 7 7 8 8 8 9 9 9
7 7 7 8 8 8 9 9 9
returns tuple for each square as follows:
a b c
d e f --> (a,b,c,d,e,f,g,h,i)
g h i
"""
labels = [[3 * i + 1] * 3 + [3 * i + 2] * 3 + [3 * i + 3] * 3 for i in [0, 0, 0, 1, 1, 1, 2, 2, 2]]
labelled_board = zip(sum(board, []), sum(labels, []))
return [tuple(a for a, b in labelled_board if b == sq) for sq in xrange(1, 10)]
```
converts squares back to sudoku board
basically an inverse of the above function
```
def squares_to_board(squares):
"""
inverse of above
"""
board = [[i / 3 * 27 + i % 3 * 3 + j / 3 * 9 + j % 3 for j in range(9)] for i in range(9)]
flattened = sum([list(square) for square in squares], [])
for i in range(9):
for j in range(9):
board[i][j] = flattened[board[i][j]]
return board
```
given squares left, return constraints
see code comment for more details
```
def sum_rows(*squares):
"""
takes tuples for squares and returns lists corresponding to the rows:
l1 -- a b c j k l
l2 -- d e f m n o ...
l3 -- g h i p q r
"""
l1 = []
l2 = []
l3 = []
if len(squares):
for a, b, c, d, e, f, g, h, i in squares:
l1 += [a, b, c]
l2 += [d, e, f]
l3 += [g, h, i]
return l1, l2, l3
return [], [], []
```
given squares above, return constraints
see code comment for more details
```
def sum_cols(*squares):
"""
takes tuples for squares and returns lists corresponding to the cols:
u1 u2 u3
| | |
a b c
d e f
g h i
j k l
m n o
p q r
...
"""
u1 = []
u2 = []
u3 = []
if len(squares):
for a, b, c, d, e, f, g, h, i in squares:
u1 += [a, d, g]
u2 += [b, e, h]
u3 += [c, f, i]
return u1, u2, u3
return [], [], []
```
makes a string
```
def base95(A):
if type(A) is int or type(A) is long:
s = ''
while A > 0:
s += chr(32 + A % 95)
A /= 95
return s
if type(A) is str:
return sum((ord(c) - 32) * (95 ** i) for i, c in enumerate(A))
```
this is a hardcoded list of dependencies for each square
see code comment for more details
```
"""
dependencies: every square as labeled
1 2 3
4 5 6
7 8 9
is dependent on those above and to the left
in a dictionary, it is:
square: ([above],[left])
"""
dependencies = {1: ([], []), 2: ([], [1]), 3: ([], [1, 2]), 4: ([1], []), 5: ([2], [4]), 6: ([3], [4, 5]),
7: ([1, 4], []), 8: ([2, 5], [7]), 9: ([3, 6], [7, 8])}
```
this is a hardcoded list of max number of possible options for each square
see code comment for more details
```
"""
max possible options for a given element
9 8 7 ? ? ? 3 2 1
6 5 4 (12096) 3 2 1
3 2 1 ? ? ? 3 2 1
? ? ? ? ? ? 2 2 1
(12096) (448) 2 1 1 (limits for squares 2,4 determined via brute-force enumeration)
? ? ? ? ? ? 1 1 1 (limit for square 5 determined via sampling and enumeration)
3 3 3 2 2 1 1 1 1
2 2 2 2 1 1 1 1 1
1 1 1 1 1 1 1 1 1
"""
possibilities = [362880, 12096, 216, 12096, 448, 8, 216, 8, 1]
```
these combine the above functions and convert a board to a list of integers
```
def factorize_sudoku(board):
squares = board_to_squares(board)
factors = []
for label in xrange(1, 10):
above, left = dependencies[label]
u1, u2, u3 = sum_cols(*[sq for i, sq in enumerate(squares) if i + 1 in above])
l1, l2, l3 = sum_rows(*[sq for i, sq in enumerate(squares) if i + 1 in left])
for i, k in enumerate(potential_squares(u1, u2, u3, l1, l2, l3)):
if k == squares[label - 1]:
factors.append(i)
continue
return factors
```
and back to a board
```
def unfactorize_sudoku(factors):
squares = []
for label in xrange(1, 10):
factor = factors[label - 1]
above, left = dependencies[label]
u1, u2, u3 = sum_cols(*[sq for i, sq in enumerate(squares) if i + 1 in above])
l1, l2, l3 = sum_rows(*[sq for i, sq in enumerate(squares) if i + 1 in left])
for i, k in enumerate(potential_squares(u1, u2, u3, l1, l2, l3)):
if i == factor:
squares.append(k)
continue
return squares
```
okay that's all the functions
for each board, make string and print it
```
strings = []
for sudoku in inputs:
board = [[int(x) for x in line.split()] for line in sudoku.strip().split('\n')]
print_sudoku(board)
factors = factorize_sudoku(board)
i = 0
for item, modulus in zip(factors, possibilities):
i *= modulus
i += item
strings.append(base95(i))
print 'integral representation:', i
print 'bits of entropy:', i.bit_length()
print 'base95 representation:', strings[-1]
print ''
```
now print the total length of all strings
```
print 'overall output:', strings
print 'total length:', len(''.join(strings))
print ''
```
and un-stringify, to prove it's not a one-way compression
```
for string in strings:
print 'from:', string
i = base95(string)
retrieved = []
for base in possibilities[::-1]:
retrieved.append(i % base)
i /= base
squares = unfactorize_sudoku(retrieved[::-1])
print_sudoku(squares_to_board(squares))
print ''
```
output:
```
9 7 3 5 8 1 4 2 6
5 2 6 4 7 3 1 9 8
1 8 4 2 9 6 7 5 3
2 4 7 8 6 5 3 1 9
3 9 8 1 2 4 6 7 5
6 5 1 7 3 9 8 4 2
8 1 9 3 4 2 5 6 7
7 6 5 9 1 8 2 3 4
4 3 2 6 5 7 9 8 1
integral representation: 69411889624053450486136
bits of entropy: 76
base95 representation: q`3T/v50 =3,
7 2 4 8 6 5 1 9 3
1 6 9 2 4 3 8 7 5
3 8 5 1 9 7 2 4 6
8 9 6 7 2 4 3 5 1
2 7 3 9 5 1 6 8 4
4 5 1 3 8 6 9 2 7
5 4 2 6 3 9 7 1 8
6 1 8 5 7 2 4 3 9
9 3 7 4 1 8 5 6 2
integral representation: 48631663773869605020107
bits of entropy: 76
base95 representation: ^0NK(F4(V6T(
1 5 7 6 8 2 3 4 9
4 3 2 5 1 9 6 8 7
6 9 8 3 4 7 2 5 1
8 2 5 4 7 6 1 9 3
7 1 3 9 2 8 4 6 5
9 6 4 1 3 5 7 2 8
5 4 1 2 9 3 8 7 6
2 8 9 7 6 1 5 3 4
3 7 6 8 5 4 9 1 2
integral representation: 3575058942398222501018
bits of entropy: 72
base95 representation: d KTTB{pJc[
8 3 5 4 1 6 9 2 7
2 9 6 8 5 7 4 3 1
4 1 7 2 9 3 6 5 8
5 6 9 1 3 4 7 8 2
1 2 3 6 7 8 5 4 9
7 4 8 5 2 9 1 6 3
6 5 2 7 8 1 3 9 4
9 8 1 3 4 5 2 7 6
3 7 4 9 6 2 8 1 5
integral representation: 57682547793421214045879
bits of entropy: 76
base95 representation: B]^v[omnBF-*
6 2 8 4 5 1 7 9 3
5 9 4 7 3 2 6 8 1
7 1 3 6 8 9 5 4 2
2 4 7 3 1 5 8 6 9
9 6 1 8 2 7 3 5 4
3 8 5 9 6 4 2 1 7
1 5 6 2 4 3 9 7 8
4 3 9 5 7 8 1 2 6
8 7 2 1 9 6 4 3 5
integral representation: 41241947159502331128265
bits of entropy: 76
base95 representation: WZslDPbcOm7'
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 1 4 3 6 5 8 9 7
3 6 5 8 9 7 2 1 4
8 9 7 2 1 4 3 6 5
5 3 1 6 4 8 9 7 2
6 4 8 9 7 2 5 3 1
9 7 2 5 3 1 6 4 8
integral representation: 9
bits of entropy: 4
base95 representation: )
1 4 5 7 9 2 8 3 6
3 7 6 5 8 4 1 9 2
2 9 8 3 6 1 7 5 4
7 3 1 9 2 8 6 4 5
8 5 9 6 4 7 3 2 1
4 6 2 1 3 5 9 8 7
6 2 4 8 7 3 5 1 9
5 8 7 4 1 9 2 6 3
9 1 3 2 5 6 4 7 8
integral representation: 2289142964266107350685
bits of entropy: 71
base95 representation: ukVl2x/[+6F
5 2 7 4 1 6 9 3 8
8 6 4 3 2 9 1 5 7
1 3 9 5 7 8 6 4 2
2 9 1 8 5 4 3 7 6
3 4 8 6 9 7 5 2 1
6 7 5 1 3 2 4 8 9
7 1 2 9 4 5 8 6 3
4 8 3 2 6 1 7 9 5
9 5 6 7 8 3 2 1 4
integral representation: 33227336099857838436306
bits of entropy: 75
base95 representation: qzw>GjmPxzo%
2 4 6 7 1 3 9 8 5
1 8 5 4 9 6 7 3 2
9 3 7 8 2 5 1 4 6
6 7 8 5 4 2 3 9 1
4 9 3 1 6 8 2 5 7
5 1 2 3 7 9 4 6 8
8 2 4 9 5 7 6 1 3
7 5 9 6 3 1 8 2 4
3 6 1 2 8 4 5 7 9
integral representation: 10303519193492123417583
bits of entropy: 74
base95 representation: KE:*GH@H>(m!
8 6 1 2 9 4 5 7 3
4 7 5 3 1 8 6 9 2
3 9 2 5 6 7 8 1 4
2 3 6 4 5 9 7 8 1
1 5 4 7 8 3 2 6 9
9 8 7 6 2 1 3 4 5
5 2 9 1 7 6 4 3 8
6 4 8 9 3 2 1 5 7
7 1 3 8 4 5 9 2 6
integral representation: 60238104668684129814106
bits of entropy: 76
base95 representation: SeM=kA`'3(X*
overall output: ['q`3T/v50 =3,', '^0NK(F4(V6T(', 'd KTTB{pJc[', 'B]^v[omnBF-*', "WZslDPbcOm7'", ')', 'ukVl2x/[+6F', 'qzw>GjmPxzo%', 'KE:*GH@H>(m!', "SeM=kA`'3(X*"]
total length: 107
from: q`3T/v50 =3,
9 7 3 5 8 1 4 2 6
5 2 6 4 7 3 1 9 8
1 8 4 2 9 6 7 5 3
2 4 7 8 6 5 3 1 9
3 9 8 1 2 4 6 7 5
6 5 1 7 3 9 8 4 2
8 1 9 3 4 2 5 6 7
7 6 5 9 1 8 2 3 4
4 3 2 6 5 7 9 8 1
from: ^0NK(F4(V6T(
7 2 4 8 6 5 1 9 3
1 6 9 2 4 3 8 7 5
3 8 5 1 9 7 2 4 6
8 9 6 7 2 4 3 5 1
2 7 3 9 5 1 6 8 4
4 5 1 3 8 6 9 2 7
5 4 2 6 3 9 7 1 8
6 1 8 5 7 2 4 3 9
9 3 7 4 1 8 5 6 2
from: d KTTB{pJc[
1 5 7 6 8 2 3 4 9
4 3 2 5 1 9 6 8 7
6 9 8 3 4 7 2 5 1
8 2 5 4 7 6 1 9 3
7 1 3 9 2 8 4 6 5
9 6 4 1 3 5 7 2 8
5 4 1 2 9 3 8 7 6
2 8 9 7 6 1 5 3 4
3 7 6 8 5 4 9 1 2
from: B]^v[omnBF-*
8 3 5 4 1 6 9 2 7
2 9 6 8 5 7 4 3 1
4 1 7 2 9 3 6 5 8
5 6 9 1 3 4 7 8 2
1 2 3 6 7 8 5 4 9
7 4 8 5 2 9 1 6 3
6 5 2 7 8 1 3 9 4
9 8 1 3 4 5 2 7 6
3 7 4 9 6 2 8 1 5
from: WZslDPbcOm7'
6 2 8 4 5 1 7 9 3
5 9 4 7 3 2 6 8 1
7 1 3 6 8 9 5 4 2
2 4 7 3 1 5 8 6 9
9 6 1 8 2 7 3 5 4
3 8 5 9 6 4 2 1 7
1 5 6 2 4 3 9 7 8
4 3 9 5 7 8 1 2 6
8 7 2 1 9 6 4 3 5
from: )
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 1 4 3 6 5 8 9 7
3 6 5 8 9 7 2 1 4
8 9 7 2 1 4 3 6 5
5 3 1 6 4 8 9 7 2
6 4 8 9 7 2 5 3 1
9 7 2 5 3 1 6 4 8
from: ukVl2x/[+6F
1 4 5 7 9 2 8 3 6
3 7 6 5 8 4 1 9 2
2 9 8 3 6 1 7 5 4
7 3 1 9 2 8 6 4 5
8 5 9 6 4 7 3 2 1
4 6 2 1 3 5 9 8 7
6 2 4 8 7 3 5 1 9
5 8 7 4 1 9 2 6 3
9 1 3 2 5 6 4 7 8
from: qzw>GjmPxzo%
5 2 7 4 1 6 9 3 8
8 6 4 3 2 9 1 5 7
1 3 9 5 7 8 6 4 2
2 9 1 8 5 4 3 7 6
3 4 8 6 9 7 5 2 1
6 7 5 1 3 2 4 8 9
7 1 2 9 4 5 8 6 3
4 8 3 2 6 1 7 9 5
9 5 6 7 8 3 2 1 4
from: KE:*GH@H>(m!
2 4 6 7 1 3 9 8 5
1 8 5 4 9 6 7 3 2
9 3 7 8 2 5 1 4 6
6 7 8 5 4 2 3 9 1
4 9 3 1 6 8 2 5 7
5 1 2 3 7 9 4 6 8
8 2 4 9 5 7 6 1 3
7 5 9 6 3 1 8 2 4
3 6 1 2 8 4 5 7 9
from: SeM=kA`'3(X*
8 6 1 2 9 4 5 7 3
4 7 5 3 1 8 6 9 2
3 9 2 5 6 7 8 1 4
2 3 6 4 5 9 7 8 1
1 5 4 7 8 3 2 6 9
9 8 7 6 2 1 3 4 5
5 2 9 1 7 6 4 3 8
6 4 8 9 3 2 1 5 7
7 1 3 8 4 5 9 2 6
```
[Answer]
## Mathematica, score: 130 9
*Update:*
After this answer was posted, it inspired a new loophole closer: ["Optimising for the given test cases"](https://codegolf.meta.stackexchange.com/a/2507/10947). I will however leave this answer as is, as an example of the loophole. Feel free to downvote. I won't be hurt.
---
This encodes a cell at a time in raster order, and for each cell rules out its value appropriately for subsequent cells using the basic rules of Sudoku. So, for example, when a cell is encoded and only has four possibilities, then a base 4 digit is added to the large integer. It also codes the test cases directly as small integers, still correctly compressing and decompressing all valid Sudoku boards with an average compressed length of ~12.5 characters, 1.5 more than the optimal 11.035, with relatively simple code and no Sudoku solver required.
```
rule=({#}&/@Union[Join[
Range[#+1,Ceiling[#,9]],Range[#+9,81,9],
Flatten[Outer[Plus,Range[Floor[#+8,9],Ceiling[#,27]-9,9],
Floor[Mod[#-1,9],3]+Range[3]]]]])&/@Range[81];
encode[board_]:=
Block[{step,code,pos},
step[{left_,x_,m_},n_]:={
MapAt[Complement[#,{board[[n]]}]&,left,rule[[n]]],
x+m(FirstPosition[left[[n]],board[[n]]][[1]]-1),m Length[left[[n]]]};
code=Fold[step,{Table[Range[9],{81}],0,1},Range[81]][[2]];
pos=Position[{206638498064127103948214,1665188010993633759502287,
760714067080859855534739,1454154263752219616902129,6131826927558056238360710,
237833524138130760909081600,8968162948536417279508170,3284755189143784030943149,
912407486534781347155987,556706937207676220045188},code];
code=If[pos==={},code+10,pos[[1,1]]-1];
FromCharacterCode[If[code==0,{},IntegerDigits[code,95]+32]]
]
decode[str_]:=
Block[{step,code},
code=FromDigits[ToCharacterCode[str]-32,95];
code=If[code<10,{206638498064127103948214,1665188010993633759502287,
760714067080859855534739,1454154263752219616902129,6131826927558056238360710,
237833524138130760909081600,8968162948536417279508170,3284755189143784030943149,
912407486534781347155987,556706937207676220045188}[[code+1]],code-10];
step[{left_,x_,board_},n_]:=Function[z,{
MapAt[Complement[#,{z}]&,left,rule[[n]]],Quotient[x,Length[left[[n]]]],
Append[board,z]}][left[[n,Mod[x,Length[left[[n]]]]+1]]];
Fold[step,{Table[Range[9],{81}],code,{}},Range[81]][[3]]
]
```
Encoded test cases:
```
<- empty string
!
"
#
$
%
&
'
(
)
```
This does not result in perfect coding (average ~11), since the basic rules do not rule out some choices for which there is in fact no solution. The performance could be made perfect (i.e. the large integer would always be less than the number of possible Sudoku boards) by checking to see if there is no solution to some of the current choices using a Sudoku solver, and eliminating those as well.
[Answer]
## J, 254 points
**Compression**
```
fwrite&'sudoku.z' 1 u: u: 32 + (26$95) #: (9 $ !9x)#. A."1 (1&".);._2 stdin''
```
**Decompression**
```
echo A.&(>:i.9)"1 (9 $ !9x) #: 95x #. 32 -~ 3 u: fread'sudoku.z'
```
Standard I/O is a bit clumsy in J since `jconsole` is actually a REPL, so I took the liberty to write the compressed output to file.
Finds the anagram index of each line, treats the resulting nine numbers as a base-(9!) number, and then finally converts to base-95, adds 32 and converts to ASCII just like in Martin Büttner's solution. The anagram index of a permutation of *1..n* is simply the index of the permutation in the lexically sorted list of all such permutations, e.g. `5 4 3 2 1` has anagram index *5! - 1 = 119*.
All the operations have easy inverses, so decompression is simple.
As a bonus, the examples are in a very J-friendly format, so input/output for decompressed sudokus are exactly as given in the examples (although the input to the encoder *requires* a trailing newline).
---
Compressed strings for the testcases:
```
#p8<!w=C6Cpgi/-+vn)FU]AHr\
"bC]wPv{8ze$l,+jkCPi0,e>-D
2}2EZZB;)WZQF@JChz}~-}}_<
#2Ofs0Mm]).e^raUu^f@sSMWc"
":kkCf2;^U_UDC?I\PC"[*gj|!
#TISE3?d7>oZ_I2.C16Z*gg
,@ CE;zX{.l\xRAc]~@vCw)8R
!oN{|Y6V"C.q<{gq(s?M@O]"]9
VORd2"*T,J;JSh<G=rR*8J1LT
#?bHF:y@oRI8e1Zdl5:BzYO.P.
```
[Answer]
# Python 2.5, 116 points
Code:
```
emptysud=[[' ']*9 for l in range(9)]
def encconfig(dig,sud):
conf1=[(sud[i].index(dig),i) for i in range(9)]; out=[]
for xgroup in range(3):
a=filter(lambda (x,y): xgroup*3<=x<(xgroup+1)*3, conf1)
b=[x-xgroup*3 for (x,y) in sorted(a,key = lambda (x,y): y)]
out.append([[0,1,2],[0,2,1],[1,0,2],[1,2,0],[2,0,1],[2,1,0]].index(b))
for ygroup in range(3):
a=filter(lambda (x,y): ygroup*3<=y<(ygroup+1)*3, conf1)
b=[y-ygroup*3 for (x,y) in sorted(a,key = lambda (x,y): x)]
out.append([[0,1,2],[0,2,1],[1,0,2],[1,2,0],[2,0,1],[2,1,0]].index(b))
return sum([out[i]*(6**i) for i in range(6)])
def decconfig(conf,dig,sud=emptysud):
inp=[]; conf1=[]; sud=[line[:] for line in sud]
for i in range(6):
inp.append([[0,1,2],[0,2,1],[1,0,2],[1,2,0],[2,0,1],[2,1,0]][conf%6]); conf/=6
for groupx in range(3):
for groupy in range(3):
conf1.append((groupx*3+inp[groupx][groupy],groupy*3+inp[groupy+3][groupx]))
for (x,y) in conf1: sud[y][x]=dig
return sud
def compatible(sud,conf,dig):
a=reduce(lambda x,y: x+y, sud)
b=decconfig(conf,dig,sud)
c=reduce(lambda x,y: x+y, b)
return a.count(' ')-c.count(' ')==9
def encode(sud):
k=[encconfig(str(i),sud) for i in range(1,10)]; m=k[0]; p=6**6
cursud=decconfig(k[0],'1')
for i in range(1,9):
t=filter(lambda u: compatible(cursud,u,str(i+1)), range(6**6))
m=m+p*t.index(k[i]); p*=len(t)
cursud=decconfig(k[i],str(i+1),cursud)
return m
def decode(n):
k=[n%46656]; n/=46656; cursud=decconfig(k[-1],'1')
for i in range(2,10):
t=filter(lambda u: compatible(cursud,u,str(i)), range(6**6))
k.append(n%len(t)); n/=len(t); cursud=decconfig(t[k[-1]],str(i),cursud)
return cursud
def base95(n):
out=''
while n: out+=chr(32+n%95); n/=95
return out[::-1]
def base10(s): s=s[::-1]; return sum([(ord(s[i])-32)*(95**i) for i in range(len(s))])
import time
t0=time.clock()
for part in file('sudoku.txt','rb+').read().split('\r\n\r\n'):
sudoku=[line.split(' ') for line in part.split('\r\n')]
encsud=base95(encode(sudoku)); sud2=decode(base10(encsud))
print encsud,sud2==sudoku
print time.clock()-t0
```
Results:
```
!|/FC,">;&3z
rUH">FLSgT|
)3#m|:&Zxl1c
jh _N@MG/zr
%Iye;U(6(p;0
!21.+KD0//yG
"O\B*O@8,h`y
A$`TUE#rsQu
J}ANCYXX*y5
".u2KV#4K|%a
```
Very slow. Took 517 seconds to run and verify on my machine.
*encconfig* takes a sudoku board and a digit from 1-9, lists the x-y coordinates where that digit appears, and outputs a number in range(6\*\*6) that represents those coordinates. (the "digit configuration")
*decconfig* is the reverse function. It takes a number in range(6\*\*6), a digit, and a sudoku board (defaults to empty). It outputs the sudoku board overlayed with the digit configuration. If one of the positions in the digit configuration is already taken in the inputted sudoku board, the digit in that position is overwritten by the new digit.
*compatible* takes a sudoku board and a digit configuration (defined by conf and dig), overlays the digit configuration over the sudoku board and checks for conflicts. It then returns True or False depending on the result.
*encode* is the compression function. It takes a sudoku board and outputs a number representing it. It does this by first copying the positions of the 1's to an empty board and making a list of all the configurations of the number 2 which are compatible with the 1-configuration (that don't take up any of the places already taken by the 1's). It then finds the order of the board's actual 2-configuration in the list and stores it, then copies that configuration to the new board, which now contains only the 1's and 2's. It then lists all the configurations of the number 3 which are compatible with the positions of the 1's and 2's, and so on.
*decode* is the reverse function.
Python 2.5.
[Answer]
## Python 3, 120 points
This program lists all possible 3x3-blocks and remembers which one of them was actually present in the original Sudoku, then puts all those numbers together in a base-95 representation. Although this is very close to hard-coding, it compresses and decompresses the examples in about 5 seconds each on my machine.
```
import functools
def readSudoku(s):
values = [int(c) for c in s.split()]
blocks = []
for i in range(3):
for j in range(3):
block = []
for k in range(3):
for l in range(3):
block.append(values[i * 27 + k * 9 + j * 3 + l])
blocks.append(block)
return blocks
def writeSudoku(blocks):
text = ""
for i in range(9):
for j in range(9):
text += str(blocks[3 * (i // 3) + (j // 3)][3 * (i % 3) + (j % 3)]) + " "
text += "\n"
return text
def toASCII(num):
chars = "".join(chr(c) for c in range(32, 127))
if num == 0:
return chars[0]
else:
return (toASCII(num // len(chars)).lstrip(chars[0]) + chars[num % len(chars)])
def toNum(text):
chars = "".join(chr(c) for c in range(32, 127))
return sum((len(chars) ** i * chars.index(c) for (i, c) in enumerate(text[::-1])))
def compress(sudoku):
info = compressInfo(readSudoku(sudoku))
return toASCII(functools.reduce(lambda old, new: (old[0] + new[0] * old[1], old[1] * new[1]), info, (0, 1))[0])
def compressInfo(sudoku):
finished = [[0]*9]*9
indices = [(-1, 0)]*9
for (index, block) in enumerate(sudoku):
counter = 0
actual = -1
for (location, solution) in enumerate(possibleBlocks(finished, index)):
counter += 1
if block == solution:
actual = location
if actual == -1:
print(finished)
print(block)
raise ValueError
finished[index] = block
indices[index] = (actual, counter)
return indices
def decompress(text):
number = toNum(text)
finished = [[0]*9]*9
for i in range(9):
blocks = list(possibleBlocks(finished, i))
index = number % len(blocks)
number //= len(blocks)
finished[i] = blocks[index]
return writeSudoku(finished)
def possibleBlocks(grid, index):
horizontals = [grid[i] for i in (3 * (index // 3), 3 * (index // 3) + 1, 3 * (index // 3) + 2)]
verticals = [grid[i] for i in (index % 3, index % 3 + 3, index % 3 + 6)]
for i1 in range(1, 10):
if any((i1 in a[0:3] for a in horizontals)) or\
any((i1 in a[0::3] for a in verticals)):
continue
for i2 in range(1, 10):
if i2 == i1 or\
any((i2 in a[0:3] for a in horizontals)) or\
any((i2 in a[1::3] for a in verticals)):
continue
for i3 in range(1, 10):
if i3 in (i2, i1) or\
any((i3 in a[0:3] for a in horizontals)) or\
any((i3 in a[2::3] for a in verticals)):
continue
for i4 in range(1, 10):
if i4 in (i3, i2, i1) or\
any((i4 in a[3:6] for a in horizontals)) or\
any((i4 in a[0::3] for a in verticals)):
continue
for i5 in range(1, 10):
if i5 in (i4, i3, i2, i1) or\
any((i5 in a[3:6] for a in horizontals)) or\
any((i5 in a[1::3] for a in verticals)):
continue
for i6 in range(1, 10):
if i6 in (i5, i4, i3, i2, i1) or\
any((i6 in a[3:6] for a in horizontals)) or\
any((i6 in a[2::3] for a in verticals)):
continue
for i7 in range(1, 10):
if i7 in (i6, i5, i4, i3, i2, i1) or\
any((i7 in a[6:9] for a in horizontals)) or\
any((i7 in a[0::3] for a in verticals)):
continue
for i8 in range(1, 10):
if i8 in (i7, i6, i5, i4, i3, i2, i1) or\
any((i8 in a[6:9] for a in horizontals)) or\
any((i8 in a[1::3] for a in verticals)):
continue
for i9 in range(1, 10):
if i9 in (i8, i7, i6, i5, i4, i3, i2, i1) or\
any((i9 in a[6:9] for a in horizontals)) or\
any((i9 in a[2::3] for a in verticals)):
continue
yield [i1, i2, i3, i4, i5, i6, i7, i8, i9]
```
The main functions are `compress(sudoku)` and `decompress(text)`.
Outputs:
```
!%XIjS+]P{'Y
$OPMD&Sw&tlc
$1PdUMZ7K;W*
*=M1Ak9Oj6i\
!SY5:tDJxVo;
!F ]ki%jK>*R
'PXM4J7$s?#%
#9BJZP'%Ggse
*iAH-!9%QolJ
#&L6W6i> Dd6
```
[Answer]
**C#, 150 bytes**
**Compressed output:**
```
KYxnUjIpNe/YDnA
F97LclGuqeTcT2c
i6D1SvMVkS0jPlQ
32FOiIoUHpz5GGs
aAazPo2RJiH+IWQ
CwAA5NIMyNzSt1I
Cc2jOjU1+buCtVM
OgQv3Dz3PqsRvGA
eSxaW3wY5e6NGFc
olQvtpDOUPJXKGw
```
**How it works:**
It generates all possible permutations of 123456789 and remembers them.
Then it compares the permutations with the rows in the sudoku.
When a matching permutation for a giving row is found it remembers the index of that permutation. After each row it will remove all permutations where there is atleast one char in same position as the current row. This makes sure every number is unique in its column. Then it takes out all permutations that do not work anymore by the box-criteria.
Since the last row is trivial it generates 8 numbers.
I tested what the max value of each of those numbers would be and generated a digit-count-mask for each position of those. { 6, 5, 3, 5, 3, 1, 2, 1, 1 }. The first is obviously the longest with 362880 permutations.
Using the digitmask i construct a BigInteger with a leading 1 to make it 28 digits long. This results in 11 bytes total. Then those bytes get converted to base64. To save one char i remove the = sign at the end.
The reconstrcution works similiar.
It reconstructs the BigInteger from the base64string and then turns it into a string again and splitting it up again using the mentiond digit-count-mask. Those strings get parsed back to the indexes.
Then the algorithm does almost the same, instead of finding the row in the permutations it just uses the index to get the row, the rest works the same.
Probably this could be a bit better to really use the 94 possible charachters instead of only 64 but i lack the brainz to do this.
**Source**:
Copy- and pasteable to make it run with the 10 examples.
.dotNet-Fiddle tells me this exceeds the memorylimit so you need to run it on your machine to text.
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
public class Programm
{
public static void Main(string[] args)
{
string[] input = new[] {
"973581426526473198184296753247865319398124675651739842819342567765918234432657981",
"724865193169243875385197246896724351273951684451386927542639718618572439937418562",
"157682349432519687698347251825476193713928465964135728541293876289761534376854912",
"835416927296857431417293658569134782123678549748529163652781394981345276374962815",
"628451793594732681713689542247315869961827354385964217156243978439578126872196435",
"123456789456789123789123456214365897365897214897214365531648972648972531972531648",
"145792836376584192298361754731928645859647321462135987624873519587419263913256478",
"527416938864329157139578642291854376348697521675132489712945863483261795956783214",
"246713985185496732937825146678542391493168257512379468824957613759631824361284579",
"861294573475318692392567814236459781154783269987621345529176438648932157713845926" };
string[] permutations = GetPermutations();
foreach (string sudoku in input)
{
int[] indices = _compressSudoku(sudoku, permutations).ToArray();
string compressedRepresentation = _toCompressedRepresentation(indices);
Console.WriteLine(compressedRepresentation);
indices = _fromCompressedRepresentation(compressedRepresentation);
string decompressedSudoku = _decompressSudoku(indices, permutations);
if (decompressedSudoku != sudoku)
throw new Exception();
}
Console.ReadKey();
}
static int[] _digitMask = new int[] { 6, 5, 3, 5, 3, 1, 2, 1, 1 };
private static int[] _fromCompressedRepresentation(string compressedRepresentation)
{
BigInteger big = new BigInteger(Convert.FromBase64String(compressedRepresentation + "="));
string stringValue = big.ToString().Substring(1);
List<int> indexes = new List<int>();
int i = 0;
while (stringValue.Length > 0)
{
int length = _digitMask[i++];
string current = stringValue.Substring(0, length);
stringValue = stringValue.Substring(length);
indexes.Add(int.Parse(current));
}
return indexes.ToArray(); ;
}
private static string _toCompressedRepresentation(int[] indices)
{
StringBuilder builder = new StringBuilder("1");
int i = 0;
foreach (int index in indices)
{
string mask = "{0:D" + _digitMask[i++].ToString() + "}";
builder.AppendFormat(mask, index);
}
string base64 = Convert.ToBase64String(BigInteger.Parse(builder.ToString()).ToByteArray());
return base64.Substring(0, base64.Length - 1); // remove the = at the end.
}
private static IEnumerable<int> _compressSudoku(string input, string[] remainingPermutations)
{
string[] localRemainingPermutations = null;
List<HashSet<char>> localUsed = null;
for (int i = 0; i < 8; i++)
{
string currentRow = _getCurrentRow(input, i);
if (i % 3 == 0)
{
localRemainingPermutations = remainingPermutations;
localUsed = _initLocalUsed();
}
int index = 0;
foreach (string permutation in localRemainingPermutations)
{
if (permutation == currentRow)
{
yield return index;
break;
}
index++;
}
remainingPermutations = remainingPermutations.Where(permutation => _isStillValidPermutation(currentRow, permutation)).ToArray();
if (i % 3 < 2)
{
for (int j = 0; j < 9; j++)
localUsed[j / 3].Add(currentRow[j]);
localRemainingPermutations = localRemainingPermutations.Where(permutation => _isStillValidLocalPermutation(permutation, localUsed)).ToArray();
}
}
}
private static string _decompressSudoku(int[] indices, string[] remainingPermutations)
{
StringBuilder result = new StringBuilder();
string[] localRemainingPermutations = null;
List<HashSet<char>> localUsed = null;
for (int i = 0; i < 9; i++)
{
if (i % 3 == 0)
{
localRemainingPermutations = remainingPermutations;
localUsed = _initLocalUsed();
}
string currentRow = localRemainingPermutations[i < indices.Length ? indices[i] : 0];
result.Append(currentRow);
remainingPermutations = remainingPermutations.Where(permutation => _isStillValidPermutation(currentRow, permutation)).ToArray();
if (i % 3 < 2)
{
for (int j = 0; j < 9; j++)
localUsed[j / 3].Add(currentRow[j]);
localRemainingPermutations = localRemainingPermutations.Where(permutation => _isStillValidLocalPermutation(permutation, localUsed)).ToArray();
}
}
return result.ToString();
}
private static string _getCurrentRow(string input, int i)
{
return new string(input.Skip(i * 9).Take(9).ToArray());
}
private static List<HashSet<char>> _initLocalUsed()
{
return new List<HashSet<char>> { new HashSet<char>(), new HashSet<char>(), new HashSet<char>() };
}
private static bool _isStillValidLocalPermutation(string permutation, List<HashSet<char>> localUsed)
{
for (int i = 0; i < 9; i++)
{
if (localUsed[i / 3].Contains(permutation[i]))
return false;
}
return true;
}
private static bool _isStillValidPermutation(string currentRow, string permutation)
{
return permutation.Select((c, j) => c != currentRow[j]).All(b => b);
}
static string[] GetPermutations(char[] chars = null)
{
if (chars == null)
chars = new[] { '1', '2', '3', '4', '5', '6', '7', '8', '9' };
if (chars.Length == 2)
return new[] { new String(chars), new String(chars.Reverse().ToArray()) };
return chars.SelectMany(c => GetPermutations(chars.Where(sc => sc != c).ToArray()), (c, s) => c + s).ToArray();
}
}
```
[Answer]
# Perl - 290 characters = 290 points
This program uses no hard coding and reliably compresses a grid into exactly 29 characters (theoretically it would be possible to find some smaller ones).
Here's how it works:
* First convert the 9 x 9 array to 60 numbers. This can be done as the last column, the last row, and the final square of each 3 x 3 cell can be dropped.
* Then convert using bigint to a single integer, using 9^60 elements.
* Then convert the bigint to base 95.
Compressor and decompressor:
```
#!/usr/bin/perl
use strict;
use warnings;
use Getopt::Long;
use bigint;
sub compress
{
my @grid;
my @nums;
while (<>)
{
push @grid, [split];
}
# encode into 60 numbers omitting last from each row, column and 3 x 3 square
my $i;
my $j;
for ($i=0; $i<=7; $i++)
{
for ($j=0; $j<=7; $j++)
{
push @nums, $grid[$i][$j] if (($i % 3 !=2 ) || ($j % 3 !=2));
}
}
# encode into a big int
my $code = 0;
foreach my $n (@nums)
{
$code = $code * 9 + ($n-1);
}
# print in base 95
my $out="";
while ($code)
{
my $digit = $code % 95;
$out = chr($digit+32).$out;
$code -= $digit;
$code /= 95;
}
print "$out";
}
sub decompress
{
my @grid;
my @nums;
my $code = 0;
# Read from base 95 into bigint
while (<>)
{
chomp;
foreach my $char (split (//, $_))
{
my $c =ord($char)-32;
$code*=95;
$code+=$c;
}
}
# convert back to 60 numbers
for (my $n = 0; $n<60; $n++)
{
my $d = $code % 9;
$code -= $d;
$code/=9;
unshift @nums, $d+1;
}
# print filling in last column, row and 3 x 3 square
for (my $i=0; $i<=8; $i++)
{
for (my $j=0; $j<=8; $j++)
{
if ($j == 8)
{
my $tot = 0;
for (my $jj = 0; $jj<=7; $jj++)
{
$tot += $grid[$i][$jj];
}
$grid[$i][$j]=45-$tot;
}
elsif ($i == 8)
{
my $tot = 0;
for (my $ii = 0; $ii<=7; $ii++)
{
$tot += $grid[$ii][$j];
}
$grid[$i][$j]=45-$tot;
}
elsif (($i % 3 == 2 ) && ($j % 3 == 2))
{
my $tot = 0;
for (my $ii = $i-2; $ii<=$i; $ii++)
{
for (my $jj = $j-2; $jj<=$j; $jj++)
{
next if (($ii % 3 == 2 ) && ($jj % 3 == 2));
$tot += $grid[$ii][$jj];
}
}
$grid[$i][$j]=45-$tot;
}
else
{
$grid[$i][$j] = shift @nums;
}
print $grid[$i][$j].(($j==8)?"":" ");
}
print "\n";
}
}
my $decompress;
GetOptions ("d|decompress" => \$decompress);
if ($decompress)
{
decompress;
}
else
{
compress;
}
```
[Answer]
# PHP, 214
```
<?php
// checks each row/col/block and removes impossible candidates
function reduce($cand){
do{
$old = $cand;
for($r = 0; $r < 9; ++$r){
for($c = 0; $c < 9; ++$c){
if(count($cand[$r][$c]) == 1){ // if filled in
// remove values from row and col and block
$remove = $cand[$r][$c];
for($i = 0; $i < 9; ++$i){
$cand[$r][$i] = array_diff($cand[$r][$i],$remove);
$cand[$i][$c] = array_diff($cand[$i][$c],$remove);
$br = floor($r/3)*3+$i/3;
$bc = floor($c/3)*3+$i%3;
$cand[$br][$bc] = array_diff($cand[$br][$bc],$remove);
}
$cand[$r][$c] = $remove;
}
}}
}while($old != $cand);
return $cand;
}
// checks candidate list for completion
function done($cand){
for($r = 0; $r < 9; ++$r){
for($c = 0; $c < 9; ++$c){
if(count($cand[$r][$c]) != 1)
return false;
}}
return true;
}
// board format: [[1,2,0,3,..],[..],..], $b[$row][$col]
function solve($board){
$cand = [[],[],[],[],[],[],[],[],[]];
for($r = 0; $r < 9; ++$r){
for($c = 0; $c < 9; ++$c){
if($board[$r][$c]){ // if filled in
$cand[$r][$c] = [$board[$r][$c]];
}else{
$cand[$r][$c] = range(1, 9);
}
}}
$cand = reduce($cand);
if(done($cand)) // goto not really necessary
goto end; // but it feels good to use it
else return false;
end:
// back to board format
$b = [];
for($r = 0; $r < 9; ++$r){
$b[$r] = [];
for($c = 0; $c < 9; ++$c){
if(count($cand[$r][$c]) == 1)
$b[$r][$c] = array_pop($cand[$r][$c]);
else
$b[$r][$c] = 0;
}
}
return $b;
}
function add_zeros($board, $ind){
for($r = 0; $r < 9; ++$r){
for($c = 0; $c < 9; ++$c){
$R = ($r + (int)($ind/9)) % 9;
$C = ($c + (int)($ind%9)) % 9;
if($board[$R][$C]){
$tmp = $board[$R][$C];
$board[$R][$C] = 0;
if(!solve($board))
$board[$R][$C] = $tmp;
}
}}
return $board;
}
function base95($str, $b, $z){
$tmp = gmp_init($str, $b); $zero = gmp_init(0); $gmp95 = gmp_init(95);
$out = '';
while(gmp_cmp($tmp, $zero) > 0){
$arr = gmp_div_qr($tmp, $gmp95);
$tmp = $arr[0];
$out .= chr(32+gmp_intval($arr[1]));
}
$out = chr((32+($z << 2))|($b - 10)) . strrev($out);
return $out;
}
function encode($board, $ind){
// remove last row+col
$board[8] = [0,0,0,0,0,0,0,0,0];
foreach($board as &$j) $j[8] = 0;
// remove bottom corner of each box
$board[2][2] = $board[2][5] = $board[5][2] = $board[5][5] = 0;
$board = add_zeros($board, $ind);
$str = '';$z=0;
for($r = 0; $r < 8; ++$r){
for($c = 0; $c < 8; ++$c){
if(($r==2||$r==5)&&($c==2||$c==5)) continue;
if($str == '' && !$board[$r][$c]) ++$z;
else $str .= $board[$r][$c];
}
}
$b10 = base95(rtrim($str,'0'), 10, $z);
$b11 = base95(rtrim(str_replace(['00'],['A'],$str),'0'), 11, $z);
$b12 = base95(rtrim(str_replace(['000','00'],['B','A'],$str),'0'), 12, $z);
$l10 = strlen($b10);
$l11 = strlen($b11);
$l12 = strlen($b12);
var_dump($z);
if($l10 < $l11)
if($l10 < $l12)
return $b10;
else
return $b12;
else
if($l11 < $l12)
return $b11;
else
return $b12;
}
function decode($str){
$fc = ord($str[0]);
$base = 10 + ($fc & 3);
$z = ($fc - 32) >> 2;
$tmp = gmp_init(0);
$zero = gmp_init(0); $gmp95 = gmp_init(95);
while(strlen($str = substr($str, 1))){
$tmp = gmp_mul($tmp, $gmp95);
$tmp = gmp_add($tmp, gmp_init(ord($str[0])-32));
}
$str = gmp_strval($tmp, $base);
$expanded = str_repeat('0', $z) . str_replace(['a','b'],['00','000'],$str) . str_repeat('0', 81);
$board = [];
$ind = 0;
for($i = 0; $i < 8; ++$i){
$board[$i] = [];
for($j = 0; $j < 8; ++$j){
if(($i == 2 || $i == 5) && ($j == 2 || $j == 5))
$board[$i][$j] = 0;
else
$board[$i][$j] = (int)$expanded[$ind++];
}
$board[$i][8] = 0;
}
$board[8] = [0,0,0,0,0,0,0,0,0];
return solve($board);
}
function printBoard($board){
for($i = 0; $i < 9; ++$i){
echo implode(' ', $board[$i]) . PHP_EOL;
}
flush();
}
function readBoard(){
$board = [];
for($r = 0; $r < 9; ++$r){
$board[$r] = fscanf(STDIN, "%d%d%d%d%d%d%d%d%d");
}
return $board;
}
if(isset($argv[1])){
if($argv[1] === 'enc'){
$board = readBoard();
$bests = ''; $bestl = 999;
for($i = 0; $i < 71; ++$i){
$str = encode($board, $i);
$len = strlen($str);
if($len < $bestl){
$bestl = $len;
$bests = $str;
}
}
echo $bests . PHP_EOL;
}else if($argv[1] === 'dec'){
echo printBoard(decode(trim(fgets(STDIN))));
}
}else{
echo "Missing argument. Use `{$argv[0]} [enc|dec]`.\n";
}
```
This solution first clears out the right column and bottom row, as well as the bottom-right corner of each 3x3 block. It then tries clearing out a cell. If a simple solution exists, the cell remains blank.
Then, the sudoku grid is formatted into a string, from left to right and top to bottom, excluding the right column, bottom row, and bottom-right corner. Leading zeros are counted (let this be `z`) and removed. Trailing zeros are likewise removed.
The string is formatted into either a base 10, 11, or 12 integer (let this base be `b`), with `A` representing two zeros, and `B`, three.
This is converted into a base-95 integer, and prepended by the base-95 digit representing `z << 2 | (b - 10)`.
Call `php sudoku-compress.php enc` to encode, and `php sudoku-compress.php dec` to decode. Encoder takes the format given in the question, with a mandatory trailing newline.
Test outputs:
```
R'Ngxgi#Hu~+cR)0nE)+
Veu-b454j|:tRm(b-Xk'I
V.{mi;*6-/9Ufu[~GE"e>
F/YgX]PeyeKX5=M_+,z+Z
R&3mEHyZ6sSF'-$L<:VmX
"#b'npsIv0%L,t0yr^a.+'&
UNjx*#~I/siBGck7u9eaC%
Z!SuM^f{e<ji@F&hP-S<
*0:43tD r;=x8|&I0/k[&%
B1Mm-dx@G}[2lZId/-'h{zU
```
[Answer]
# Java, 330 Points
Before I get ridiculed for such a high score let me clarify that I attempted to try and solve this in a different kind of way knowing it probably wouldn't be quite as optimal as some of the better answers here. I was more or less curious if I could get *close* which to my surprise I didn't realize just how much worse it would turn out. Here is the run down of what my approach was here:
1. Develop an algo for solving a Sudoku puzzle.
2. Develop a scrambling algo that can still be solvable. It does this somewhat randomly while removing clues that can be trivially determined before hand. I could get to about 22 clues reliably before it took far too long.
3. Once scrambled, the puzzle could be represented by a triplet of single digit integers for each clue, in my case 22 triplets of 3. I thought if I could combine these into a single 66 digit number then base95 encode this then I have something that can be easily decoded.
The encoded string ended up being longer than I hoped at generally around 33 characters long. At which point I tried an alternative way than using Java BigInteger where I created a large number from an 81 bit mask representing the 81 cells of a grid where 1 means a clue exists for this cell. I then combined that bitmask to 4 bit representations of each cell value in sequential order, rounded up to bytes and found that I roughly got the same encoded string length after base95 encoded.
So basically I am posting my code in case anybody was interested in a different approach that didn't work out so well.
**Class Puzz**
```
public class Puzz {
enum By {
Row, Column, Block
}
static final List<Integer> NUMBERS = Arrays.asList(new Integer[] { 1, 2, 3,
4, 5, 6, 7, 8, 9 });
List<Square> entries = new ArrayList<Square>();
HashMap<Integer, List<Square>> squaresByRow = new HashMap<Integer, List<Square>>();
HashMap<Integer, List<Square>> squaresByColumn = new HashMap<Integer, List<Square>>();
HashMap<Integer, List<Square>> squaresByBlock = new HashMap<Integer, List<Square>>();
public Puzz(int[][] data) {
// Create squares put them in squares by row hashtable
for (int r = 0; r < 9; r++) {
List<Square> squaresInRow = new ArrayList<Square>();
for (int c = 0; c < 9; c++) {
Square square = new Square(r, c, data[r][c], this);
entries.add(square);
squaresInRow.add(square);
}
squaresByRow.put(r, squaresInRow);
}
// Put squares in column hash table
for (int c = 0; c < 9; c++) {
List<Square> squaresInColumn = new ArrayList<Square>();
for (int r = 0; r < 9; r++) {
squaresInColumn.add(squaresByRow.get(r).get(c));
}
squaresByColumn.put(c, squaresInColumn);
}
// Put squares in block hash table
for (int i = 1; i < 10; i++) {
squaresByBlock.put(i, new ArrayList<Square>());
}
for (int r = 0; r < 9; r++) {
for (int c = 0; c < 9; c++) {
int block = getBlock(r, c);
squaresByBlock.get(block).add(get(r, c));
}
}
// Discover the possibilities
updatePossibilities();
}
public void updatePossibilities() {
for (int r = 0; r < 9; r++) {
for (int c = 0; c < 9; c++) {
Square theSquare = get(r, c);
if (theSquare.value != 0) {
theSquare.possibilities.removeAll(NUMBERS);
continue;
} else {
theSquare.possibilities.addAll(NUMBERS);
}
int block = getBlock(r, c);
HashSet<Square> squares = new HashSet<Square>();
squares.addAll(squaresByRow.get(r));
squares.addAll(squaresByColumn.get(c));
squares.addAll(squaresByBlock.get(block));
for (Square s : squares) {
if (s == theSquare)
continue;
theSquare.possibilities.remove(s.value);
}
}
}
}
public int getValue(int row, int column) {
return squaresByRow.get(row).get(column).value;
}
public Square get(int row, int column) {
return squaresByRow.get(row).get(column);
}
public boolean set(int row, int column, int value) {
if (value == 0) {
squaresByRow.get(row).get(column).value = 0;
updatePossibilities();
return true;
}
if (isValid(row, column, value)) {
squaresByRow.get(row).get(column).value = value;
updatePossibilities();
return true;
} else {
return false;
}
}
public boolean isValidSubset(By subset, int row, int column, int value) {
List<Dubs> dubss = new ArrayList<Dubs>();
List<Trips> tripss = new ArrayList<Trips>();
Square theSquare = get(row, column);
int block = getBlock(row, column);
List<Square> squares = new ArrayList<Square>();
switch (subset) {
case Row:
squares.addAll(squaresByRow.get(row));
break;
case Column:
squares.addAll(squaresByColumn.get(column));
break;
default:
squares.addAll(squaresByBlock.get(block));
break;
}
for (Square r : squares) {
if (r == theSquare)
continue;
// if any of the impacted squares have this value then it is not a
// valid value
if (r.value == value)
return false;
if (r.possibilities.size() == 3) {
List<Integer> poss = new ArrayList<Integer>(r.possibilities);
tripss.add(new Trips(poss.get(0), poss.get(1), poss.get(2),
r.row, r.col));
}
if (r.possibilities.size() == 2) {
List<Integer> poss = new ArrayList<Integer>(r.possibilities);
dubss.add(new Dubs(poss.get(0), poss.get(1), r.row, r.col));
}
}
// Find the trips and rule out the value if a triplet exists in squares
List<Trips> tripsCopy = new ArrayList<Trips>(tripss);
for (Trips trips : tripsCopy) {
int countOfOccurrences = 0;
for (Trips tr : tripss) {
if (tr.equals(trips) && !(tr.row == row && tr.col == column))
countOfOccurrences++;
}
for (Dubs dubs : dubss) {
if (trips.containedWithin(dubs)
&& !(dubs.row == row && dubs.col == column))
countOfOccurrences++;
}
if (countOfOccurrences == 3 && trips.containedWithin(value))
return false;
}
// Find the dubs and rule out the value if a double exists in squares
List<Dubs> dubsCopy = new ArrayList<Dubs>(dubss);
for (Dubs dubs : dubsCopy) {
int countOfOccurrences = 0;
for (Dubs du : dubss) {
// Count occurrences of Dubs that are not the tested square
if (du.equals(dubs) && !(du.row == row && du.col == column))
countOfOccurrences++;
}
if (countOfOccurrences == 2 && dubs.containedWithin(value))
return false;
}
return true;
}
public boolean isValid(int row, int column, int value) {
return isValidSubset(By.Row, row, column, value)
&& isValidSubset(By.Column, row, column, value)
&& isValidSubset(By.Block, row, column, value);
}
public int getBlock(int row, int column) {
int blockRow = (int) Math.floor(row / 3);
int columnRow = (int) Math.floor(column / 3) + 1;
return (blockRow * 3) + columnRow;
}
public Puzz solve(Puzz arg, boolean top) throws Exception {
// Make an original copy of the array
Puzz p = (Puzz) arg.clone();
for (int i = 1; i < 10; i++) {
for (Square s : p.squaresByBlock.get(i)) {
if (s.value == 0) {
for (Integer number : NUMBERS) {
if (p.set(s.row, s.col, number)) {
// System.out.println(p);
Puzz solved = solve(p, false);
if (solved != null)
return solved;
}
}
// no numbers fit here, return null and backtrack
p.set(s.row, s.col, 0);
return null;
}
}
}
// Check for remaining 0's
for (Square s : p.entries) {
if (s.value == 0)
return null;
}
return p;
}
public Puzz scramble(int clues) throws Exception {
Puzz p = (Puzz) clone();
Random rand = new Random();
int removed = 0;
//Remove the last row, it is a freebie
int toRemove = 81 - clues - 15;
for (int c = 0; c < 9; c++) {
p.set(8, c, 0);
}
p.set(0, 0, 0);
p.set(0, 3, 0);
p.set(0, 6, 0);
p.set(3, 0, 0);
p.set(3, 3, 0);
p.set(3, 6, 0);
// Keeping track of this because randomly removing squares can potentially create an
// unsolvable situation
HashSet<Square> alreadyTried = new HashSet<Square>();
while (removed < toRemove) {
if (alreadyTried.size() >= ((toRemove + clues) - removed)) {
// Start over
removed = 0;
alreadyTried = new HashSet<Square>();
p = (Puzz)clone();
for (int c = 0; c < 9; c++) {
p.set(8, c, 0);
}
p.set(0, 0, 0);
p.set(0, 3, 0);
p.set(0, 6, 0);
p.set(3, 0, 0);
p.set(3, 3, 0);
p.set(3, 6, 0);
}
int randX = rand.nextInt((7) + 1);
int randY = rand.nextInt((8) + 1);
int existingValue = p.getValue(randX, randY);
if (existingValue != 0) {
p.set(randX, randY, 0);
// confirm it is still solvable after removing this item
Puzz psol = solve(p, true);
if (psol != null && psol.equals(this)) {
removed++;
alreadyTried = new HashSet<Square>();
System.out.println("Clues Remaining: " + (81 - 15 - removed));
} else {
// otherwise set it back to what it was and try again
p.set(randX, randY, existingValue);
Square s = new Square(randX, randY, existingValue, p);
alreadyTried.add(s);
}
}
}
p.updatePossibilities();
return p;
}
public static String encode(Puzz p) { // Remove all zero'ed items
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 9; i++) {
for (Square s : p.squaresByRow.get(i)) {
if (s.value == 0)
continue;
sb.append(s.row).append(s.col).append(s.value);
}
}
// number mod 95 gives lowest digit, subtract that from original number
BigInteger num = new BigInteger(sb.toString());
byte[] numBytes = num.toByteArray();
StringBuffer retVal = new StringBuffer();
while (num.compareTo(BigInteger.ZERO) > 0) {
int modu = num.mod(new BigInteger("95")).intValue();
retVal.append((char) (modu + 32));
num = num.subtract(new BigInteger("" + modu));
num = num.divide(new BigInteger("95"));
}
return retVal.toString();
}
@Override
public boolean equals(Object arg0) {
if (arg0 == null || !(arg0 instanceof Puzz))
return false;
Puzz p = (Puzz) arg0;
for (int r = 0; r < 9; r++) {
for (int c = 0; c < 9; c++) {
int val1 = getValue(r, c);
int val2 = p.getValue(r, c);
if (val1 != val2)
return false;
}
}
return true;
}
@Override
protected Object clone() throws CloneNotSupportedException {
int[][] data = new int[9][9];
for (Square square : entries) {
data[square.row][square.col] = square.value;
}
return new Puzz(data);
}
@Override
public String toString() {
if (entries == null)
return "";
StringBuffer sb = new StringBuffer();
for (int r = 0; r < 9; r++) {
for (int c = 0; c < 9; c++) {
sb.append(getValue(r, c)).append(' ');
}
sb.append('\n');
}
return sb.toString();
}
}
class Square {
public Square(int row, int col, Puzz p) {
this.row = row;
this.col = col;
this.p = p;
}
public Square(int row, int col, int value, Puzz p) {
this(row, col, p);
this.value = value;
}
int row;
int col;
int value;
HashSet<Integer> possibilities = new HashSet<Integer>(Puzz.NUMBERS);
Puzz p;
@Override
protected Object clone() throws CloneNotSupportedException {
Square s = new Square(row, col, value, p);
s.possibilities = new HashSet<Integer>();
for (Integer val : possibilities) {
s.possibilities.add(new Integer(val));
}
return s;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Square))
return false;
Square s = (Square) obj;
return row == s.row && col == s.col && value == s.value
&& p.equals(s.p);
}
@Override
public int hashCode() {
return row ^ col ^ value ^ p.hashCode();
}
}
class Dubs {
int p1;
int p2;
int row, col;
public Dubs(int p1, int p2) {
this.p1 = p1;
this.p2 = p2;
}
public Dubs(int p1, int p2, int row, int col) {
this(p1, p2);
this.row = row;
this.col = col;
}
public boolean containedWithin(int value) {
return (p1 == value || p2 == value);
}
@Override
public boolean equals(Object arg0) {
if (!(arg0 instanceof Dubs))
return false;
Dubs d = (Dubs) arg0;
return (this.p1 == d.p1 || this.p1 == d.p2)
&& (this.p2 == d.p1 || this.p2 == d.p2);
}
}
class Trips {
int p1;
int p2;
int p3;
int row, col;
public Trips(int p1, int p2) {
this.p1 = p1;
this.p2 = p2;
}
public Trips(int p1, int p2, int p3) {
this(p1, p2);
this.p3 = p3;
}
public Trips(int p1, int p2, int p3, int row, int col) {
this(p1, p2, p3);
this.row = row;
this.col = col;
}
public boolean containedWithin(int value) {
return (p1 == value || p2 == value || p3 == value);
}
public boolean containedWithin(Dubs d) {
return (d.p1 == p1 || d.p1 == p2 || d.p1 == p3)
&& (d.p2 == p1 || d.p2 == p2 || d.p2 == p3);
}
public boolean equals(Object arg0) {
if (!(arg0 instanceof Trips))
return false;
Trips t = (Trips) arg0;
return (this.p1 == t.p1 || this.p1 == t.p2 || this.p1 == t.p3)
&& (this.p2 == t.p1 || this.p2 == t.p2 || this.p2 == t.p3)
&& (this.p3 == t.p1 || this.p3 == t.p2 || this.p3 == t.p3);
}
}
```
**My Test Case**
```
public class TestCompression extends TestCase {
public static int[][] test1 = new int[][] {
new int[] { 9, 7, 3, 5, 8, 1, 4, 2, 6 },
new int[] { 5, 2, 6, 4, 7, 3, 1, 9, 8 },
new int[] { 1, 8, 4, 2, 9, 6, 7, 5, 3 },
new int[] { 2, 4, 7, 8, 6, 5, 3, 1, 9 },
new int[] { 3, 9, 8, 1, 2, 4, 6, 7, 5 },
new int[] { 6, 5, 1, 7, 3, 9, 8, 4, 2 },
new int[] { 8, 1, 9, 3, 4, 2, 5, 6, 7 },
new int[] { 7, 6, 5, 9, 1, 8, 2, 3, 4 },
new int[] { 4, 3, 2, 6, 5, 7, 9, 8, 1 } };
public static int[][] test2 = new int[][] {
new int[] { 7, 2, 4, 8, 6, 5, 1, 9, 3 },
new int[] { 1, 6, 9, 2, 4, 3, 8, 7, 5 },
new int[] { 3, 8, 5, 1, 9, 7, 2, 4, 6 },
new int[] { 8, 9, 6, 7, 2, 4, 3, 5, 1 },
new int[] { 2, 7, 3, 9, 5, 1, 6, 8, 4 },
new int[] { 4, 5, 1, 3, 8, 6, 9, 2, 7 },
new int[] { 5, 4, 2, 6, 3, 9, 7, 1, 8 },
new int[] { 6, 1, 8, 5, 7, 2, 4, 3, 9 },
new int[] { 9, 3, 7, 4, 1, 8, 5, 6, 2 } };
public static int[][] test3 = new int[][] {
new int[] { 1, 5, 7, 6, 8, 2, 3, 4, 9 },
new int[] { 4, 3, 2, 5, 1, 9, 6, 8, 7 },
new int[] { 6, 9, 8, 3, 4, 7, 2, 5, 1 },
new int[] { 8, 2, 5, 4, 7, 6, 1, 9, 3 },
new int[] { 7, 1, 3, 9, 2, 8, 4, 6, 5 },
new int[] { 9, 6, 4, 1, 3, 5, 7, 2, 8 },
new int[] { 5, 4, 1, 2, 9, 3, 8, 7, 6 },
new int[] { 2, 8, 9, 7, 6, 1, 5, 3, 4 },
new int[] { 3, 7, 6, 8, 5, 4, 9, 1, 2 } };
public static int[][] test4 = new int[][] {
new int[] { 8, 3, 5, 4, 1, 6, 9, 2, 7 },
new int[] { 2, 9, 6, 8, 5, 7, 4, 3, 1 },
new int[] { 4, 1, 7, 2, 9, 3, 6, 5, 8 },
new int[] { 5, 6, 9, 1, 3, 4, 7, 8, 2 },
new int[] { 1, 2, 3, 6, 7, 8, 5, 4, 9 },
new int[] { 7, 4, 8, 5, 2, 9, 1, 6, 3 },
new int[] { 6, 5, 2, 7, 8, 1, 3, 9, 4 },
new int[] { 9, 8, 1, 3, 4, 5, 2, 7, 6 },
new int[] { 3, 7, 4, 9, 6, 2, 8, 1, 5 } };
public static int[][] test5 = new int[][] {
new int[] { 6, 2, 8, 4, 5, 1, 7, 9, 3 },
new int[] { 5, 9, 4, 7, 3, 2, 6, 8, 1 },
new int[] { 7, 1, 3, 6, 8, 9, 5, 4, 2 },
new int[] { 2, 4, 7, 3, 1, 5, 8, 6, 9 },
new int[] { 9, 6, 1, 8, 2, 7, 3, 5, 4 },
new int[] { 3, 8, 5, 9, 6, 4, 2, 1, 7 },
new int[] { 1, 5, 6, 2, 4, 3, 9, 7, 8 },
new int[] { 4, 3, 9, 5, 7, 8, 1, 2, 6 },
new int[] { 8, 7, 2, 1, 9, 6, 4, 3, 5 } };
public static int[][] test6 = new int[][] {
new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 },
new int[] { 4, 5, 6, 7, 8, 9, 1, 2, 3 },
new int[] { 7, 8, 9, 1, 2, 3, 4, 5, 6 },
new int[] { 2, 1, 4, 3, 6, 5, 8, 9, 7 },
new int[] { 3, 6, 5, 8, 9, 7, 2, 1, 4 },
new int[] { 8, 9, 7, 2, 1, 4, 3, 6, 5 },
new int[] { 5, 3, 1, 6, 4, 8, 9, 7, 2 },
new int[] { 6, 4, 8, 9, 7, 2, 5, 3, 1 },
new int[] { 9, 7, 2, 5, 3, 1, 6, 4, 8 } };
public static int[][] test7 = new int[][] {
new int[] { 1, 4, 5, 7, 9, 2, 8, 3, 6 },
new int[] { 3, 7, 6, 5, 8, 4, 1, 9, 2 },
new int[] { 2, 9, 8, 3, 6, 1, 7, 5, 4 },
new int[] { 7, 3, 1, 9, 2, 8, 6, 4, 5 },
new int[] { 8, 5, 9, 6, 4, 7, 3, 2, 1 },
new int[] { 4, 6, 2, 1, 3, 5, 9, 8, 7 },
new int[] { 6, 2, 4, 8, 7, 3, 5, 1, 9 },
new int[] { 5, 8, 7, 4, 1, 9, 2, 6, 3 },
new int[] { 9, 1, 3, 2, 5, 6, 4, 7, 8 } };
public static int[][] test8 = new int[][] {
new int[] { 5, 2, 7, 4, 1, 6, 9, 3, 8 },
new int[] { 8, 6, 4, 3, 2, 9, 1, 5, 7 },
new int[] { 1, 3, 9, 5, 7, 8, 6, 4, 2 },
new int[] { 2, 9, 1, 8, 5, 4, 3, 7, 6 },
new int[] { 3, 4, 8, 6, 9, 7, 5, 2, 1 },
new int[] { 6, 7, 5, 1, 3, 2, 4, 8, 9 },
new int[] { 7, 1, 2, 9, 4, 5, 8, 6, 3 },
new int[] { 4, 8, 3, 2, 6, 1, 7, 9, 5 },
new int[] { 9, 5, 6, 7, 8, 3, 2, 1, 4 } };
public static int[][] test9 = new int[][] {
new int[] { 2, 4, 6, 7, 1, 3, 9, 8, 5 },
new int[] { 1, 8, 5, 4, 9, 6, 7, 3, 2 },
new int[] { 9, 3, 7, 8, 2, 5, 1, 4, 6 },
new int[] { 6, 7, 8, 5, 4, 2, 3, 9, 1 },
new int[] { 4, 9, 3, 1, 6, 8, 2, 5, 7 },
new int[] { 5, 1, 2, 3, 7, 9, 4, 6, 8 },
new int[] { 8, 2, 4, 9, 5, 7, 6, 1, 3 },
new int[] { 7, 5, 9, 6, 3, 1, 8, 2, 4 },
new int[] { 3, 6, 1, 2, 8, 4, 5, 7, 9 } };
public static int[][] test10 = new int[][] {
new int[] { 8, 6, 1, 2, 9, 4, 5, 7, 3 },
new int[] { 4, 7, 5, 3, 1, 8, 6, 9, 2 },
new int[] { 3, 9, 2, 5, 6, 7, 8, 1, 4 },
new int[] { 2, 3, 6, 4, 5, 9, 7, 8, 1 },
new int[] { 1, 5, 4, 7, 8, 3, 2, 6, 9 },
new int[] { 9, 8, 7, 6, 2, 1, 3, 4, 5 },
new int[] { 5, 2, 9, 1, 7, 6, 4, 3, 8 },
new int[] { 6, 4, 8, 9, 3, 2, 1, 5, 7 },
new int[] { 7, 1, 3, 8, 4, 5, 9, 2, 6 } };
@Test
public void test2() throws Exception {
int encodedLength = 0;
Puzz expected = new Puzz(test1);
Puzz test = (Puzz) expected.clone();
long start = System.currentTimeMillis();
test = test.scramble(22);
long duration = System.currentTimeMillis() - start;
System.out.println("Duration of scramble for 22 clue puzzle: " + duration);
System.out.println("Scrambled");
System.out.println(test);
String encoded = Puzz.encode(test);
System.out.println("Encoded Length with BigInteger: " + encoded.length());
encodedLength += encoded.length();
expected = new Puzz(test2);
test = (Puzz) expected.clone();
start = System.currentTimeMillis();
test = test.scramble(22);
duration = System.currentTimeMillis() - start;
System.out.println("Duration of scramble for 22 clue puzzle: " + duration);
System.out.println("Scrambled");
System.out.println(test);
encoded = Puzz.encode(test);
System.out.println("Encoded Length with BigInteger: " + encoded.length());
encodedLength += encoded.length();
expected = new Puzz(test3);
test = (Puzz) expected.clone();
start = System.currentTimeMillis();
test = test.scramble(22);
duration = System.currentTimeMillis() - start;
System.out.println("Duration of scramble for 22 clue puzzle: " + duration);
System.out.println("Scrambled");
System.out.println(test);
encoded = Puzz.encode(test);
System.out.println("Encoded Length with BigInteger: " + encoded.length());
encodedLength += encoded.length();
expected = new Puzz(test4);
test = (Puzz) expected.clone();
start = System.currentTimeMillis();
test = test.scramble(22);
duration = System.currentTimeMillis() - start;
System.out.println("Duration of scramble for 22 clue puzzle: " + duration);
System.out.println("Scrambled");
System.out.println(test);
encoded = Puzz.encode(test);
System.out.println("Encoded Length with BigInteger: " + encoded.length());
encodedLength += encoded.length();
expected = new Puzz(test5);
test = (Puzz) expected.clone();
start = System.currentTimeMillis();
test = test.scramble(22);
duration = System.currentTimeMillis() - start;
System.out.println("Duration of scramble for 22 clue puzzle: " + duration);
System.out.println("Scrambled");
System.out.println(test);
encoded = Puzz.encode(test);
System.out.println("Encoded Length with BigInteger: " + encoded.length());
encodedLength += encoded.length();
expected = new Puzz(test6);
test = (Puzz) expected.clone();
start = System.currentTimeMillis();
test = test.scramble(22);
duration = System.currentTimeMillis() - start;
System.out.println("Duration of scramble for 22 clue puzzle: " + duration);
System.out.println("Scrambled");
System.out.println(test);
encoded = Puzz.encode(test);
System.out.println("Encoded Length with BigInteger: " + encoded.length());
encodedLength += encoded.length();
expected = new Puzz(test7);
test = (Puzz) expected.clone();
start = System.currentTimeMillis();
test = test.scramble(22);
duration = System.currentTimeMillis() - start;
System.out.println("Duration of scramble for 22 clue puzzle: " + duration);
System.out.println("Scrambled");
System.out.println(test);
encoded = Puzz.encode(test);
System.out.println("Encoded Length with BigInteger: " + encoded.length());
encodedLength += encoded.length();
expected = new Puzz(test8);
test = (Puzz) expected.clone();
start = System.currentTimeMillis();
test = test.scramble(22);
duration = System.currentTimeMillis() - start;
System.out.println("Duration of scramble for 22 clue puzzle: " + duration);
System.out.println("Scrambled");
System.out.println(test);
encoded = Puzz.encode(test);
System.out.println("Encoded Length with BigInteger: " + encoded.length());
encodedLength += encoded.length();
expected = new Puzz(test9);
test = (Puzz) expected.clone();
start = System.currentTimeMillis();
test = test.scramble(22);
duration = System.currentTimeMillis() - start;
System.out.println("Duration of scramble for 22 clue puzzle: " + duration);
System.out.println("Scrambled");
System.out.println(test);
encoded = Puzz.encode(test);
System.out.println("Encoded Length with BigInteger: " + encoded.length());
encodedLength += encoded.length();
expected = new Puzz(test10);
test = (Puzz) expected.clone();
start = System.currentTimeMillis();
test = test.scramble(22);
duration = System.currentTimeMillis() - start;
System.out.println("Duration of scramble for 22 clue puzzle: " + duration);
System.out.println("Scrambled");
System.out.println(test);
encoded = Puzz.encode(test);
encodedLength += encoded.length();
System.out.println("Final Result: " + encodedLength);
}
}
```
**Test Output**
```
Duration of scramble for 22 clue puzzle: 427614
Scrambled
0 0 3 0 0 0 0 0 6
0 2 0 0 0 0 0 9 0
0 0 0 0 9 6 7 5 0
0 4 0 0 0 5 0 1 0
0 0 0 1 0 0 0 0 0
0 5 0 0 0 0 8 4 0
0 0 0 3 0 0 5 0 7
7 0 0 9 0 8 0 3 0
0 0 0 0 0 0 0 0 0
Building encoded string: U5[XZ+C6Bgf)}O."gDE)`\)kNv7*6}1w+
Encoded Length with BigInteger: 33
Duration of scramble for 22 clue puzzle: 167739
Scrambled
0 2 4 0 0 0 0 0 0
1 6 0 0 4 0 8 0 5
0 0 5 0 9 7 2 0 0
0 0 0 0 2 4 0 0 1
0 0 3 9 0 0 0 0 0
0 0 0 0 0 0 0 0 7
0 4 0 0 0 0 0 0 8
0 1 0 5 0 0 0 3 0
0 0 0 0 0 0 0 0 0
Building encoded string: 7\c^oE}`H6@P.&E)Zu\t>B"k}Vf<[0a3&
Encoded Length with BigInteger: 33
Duration of scramble for 22 clue puzzle: 136364
Scrambled
0 0 7 0 8 0 0 0 0
0 3 2 0 0 9 6 0 0
0 0 0 0 0 0 2 5 0
0 2 0 0 0 6 0 0 0
0 0 0 9 0 0 0 0 0
0 0 4 1 0 5 7 2 0
5 0 1 0 0 0 0 7 0
2 8 9 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
Building encoded string: [S#bHlTDwS,&w,moQ{WN}Z9!{1C>.vN{-
Encoded Length with BigInteger: 33
Duration of scramble for 22 clue puzzle: 392150
Scrambled
0 0 0 0 0 6 0 0 0
0 9 0 0 0 0 0 0 1
4 0 0 0 0 3 6 0 8
0 0 0 0 0 0 0 8 0
0 0 3 0 7 8 0 0 9
7 0 0 0 0 0 0 0 3
6 0 2 0 0 0 0 9 0
9 0 1 3 4 0 2 0 0
0 0 0 0 0 0 0 0 0
Building encoded string: T-yKJ2<d)Dj~[~>]334*9YpxM<JQNf2|<
Encoded Length with BigInteger: 33
Duration of scramble for 22 clue puzzle: 169355
Scrambled
0 0 0 0 0 1 0 0 0
0 9 4 7 0 0 0 8 0
0 1 3 0 0 0 5 0 2
0 0 0 0 0 0 0 0 9
0 0 0 0 2 7 3 5 4
0 8 0 0 0 0 0 1 0
0 0 0 0 4 0 9 0 8
0 0 0 5 0 0 0 0 6
0 0 0 0 0 0 0 0 0
Building encoded string: 5@.=FmOKws7jl5*hWMQqqou\lv'e^Q}D:
Encoded Length with BigInteger: 33
Duration of scramble for 22 clue puzzle: 786
Scrambled
0 2 3 0 0 6 0 0 0
0 5 0 7 0 0 1 2 3
0 8 0 0 2 0 0 0 0
0 0 0 0 0 5 0 0 7
0 6 5 8 0 0 0 0 0
0 0 7 0 0 4 3 0 0
0 3 0 0 4 0 0 0 2
0 0 0 0 0 2 0 0 0
0 0 0 0 0 0 0 0 0
Building encoded string: wY%(O9tOSDZu-PBaFl^.f0xH7C~e)=\3&
Encoded Length with BigInteger: 33
Duration of scramble for 22 clue puzzle: 826530
Scrambled
0 0 0 0 9 0 0 0 0
0 0 0 0 0 0 0 0 0
0 9 0 3 0 1 7 0 0
0 3 0 0 0 8 0 4 5
0 0 9 0 0 7 3 0 0
0 0 2 0 3 0 0 8 0
6 0 0 0 0 0 0 0 9
5 0 0 4 1 0 2 0 3
0 0 0 0 0 0 0 0 0
Building encoded string: K|>.Aa?,8e&NRL;*ut=+Iqk8E$@&-zlF9
Encoded Length with BigInteger: 33
Duration of scramble for 22 clue puzzle: 4834
Scrambled
0 2 0 0 1 0 0 3 8
8 6 0 3 0 0 1 0 0
0 0 0 0 0 8 6 0 2
0 0 0 0 0 0 0 7 0
0 0 8 0 0 0 0 0 0
0 0 0 0 3 0 0 0 0
0 0 2 0 0 5 8 0 3
4 0 0 0 0 1 7 9 0
0 0 0 0 0 0 0 0 0
Building encoded string: GOS0!r=&HR5PZ|ezy>*l7 HWU`wIN7Q4&
Encoded Length with BigInteger: 33
Duration of scramble for 22 clue puzzle: 42126
Scrambled
0 0 0 0 0 3 0 0 5
0 0 5 4 0 0 0 3 2
9 0 0 8 0 0 0 0 0
0 0 0 0 0 2 0 0 0
0 0 0 0 6 8 2 0 7
5 1 0 0 7 0 0 0 8
8 0 0 0 5 0 0 1 0
7 0 0 0 0 0 0 0 4
0 0 0 0 0 0 0 0 0
Building encoded string: [4#9D_?I1.!h];Y_2!iqLyngbBJ&k)FF;
Encoded Length with BigInteger: 33
Duration of scramble for 22 clue puzzle: 156182
Scrambled
0 6 0 0 0 0 0 7 0
4 0 5 3 1 0 0 0 2
0 0 0 0 6 0 0 0 0
0 3 0 0 0 9 0 8 1
0 0 0 0 0 0 0 0 0
0 0 7 0 0 1 0 4 5
5 0 9 0 0 0 0 0 8
6 0 0 0 3 2 0 0 0
0 0 0 0 0 0 0 0 0
Building encoded string: r+a;I%hGj4YCA-pXz+n=ioRL:agzH'K<(
Encoded Length with BigInteger: 33
Final Result: 330
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal)- 407 Bytes
[Compressor](https://vyxal.pythonanywhere.com/#WyJhUEEiLCLIp+G5hSIsImbGm+KMijnOsjvGm+KMiuKAuTvhuYXijIpTx5LGm+KMimtQaTvhuYUiLCIiLCI5NzM1ODE0MjY1MjY0NzMxOTgxODQyOTY3NTMyNDc4NjUzMTkzOTgxMjQ2NzU2NTE3Mzk4NDI4MTkzNDI1Njc3NjU5MTgyMzQ0MzI2NTc5ODFcbjcyNDg2NTE5MzE2OTI0Mzg3NTM4NTE5NzI0Njg5NjcyNDM1MTI3Mzk1MTY4NDQ1MTM4NjkyNzU0MjYzOTcxODYxODU3MjQzOTkzNzQxODU2MlxuMTU3NjgyMzQ5NDMyNTE5Njg3Njk4MzQ3MjUxODI1NDc2MTkzNzEzOTI4NDY1OTY0MTM1NzI4NTQxMjkzODc2Mjg5NzYxNTM0Mzc2ODU0OTEyXG44MzU0MTY5MjcyOTY4NTc0MzE0MTcyOTM2NTg1NjkxMzQ3ODIxMjM2Nzg1NDk3NDg1MjkxNjM2NTI3ODEzOTQ5ODEzNDUyNzYzNzQ5NjI4MTVcbjYyODQ1MTc5MzU5NDczMjY4MTcxMzY4OTU0MjI0NzMxNTg2OTk2MTgyNzM1NDM4NTk2NDIxNzE1NjI0Mzk3ODQzOTU3ODEyNjg3MjE5NjQzNVxuMTIzNDU2Nzg5NDU2Nzg5MTIzNzg5MTIzNDU2MjE0MzY1ODk3MzY1ODk3MjE0ODk3MjE0MzY1NTMxNjQ4OTcyNjQ4OTcyNTMxOTcyNTMxNjQ4XG4xNDU3OTI4MzYzNzY1ODQxOTIyOTgzNjE3NTQ3MzE5Mjg2NDU4NTk2NDczMjE0NjIxMzU5ODc2MjQ4NzM1MTk1ODc0MTkyNjM5MTMyNTY0NzhcbjUyNzQxNjkzODg2NDMyOTE1NzEzOTU3ODY0MjI5MTg1NDM3NjM0ODY5NzUyMTY3NTEzMjQ4OTcxMjk0NTg2MzQ4MzI2MTc5NTk1Njc4MzIxNFxuMjQ2NzEzOTg1MTg1NDk2NzMyOTM3ODI1MTQ2Njc4NTQyMzkxNDkzMTY4MjU3NTEyMzc5NDY4ODI0OTU3NjEzNzU5NjMxODI0MzYxMjg0NTc5XG44NjEyOTQ1NzM0NzUzMTg2OTIzOTI1Njc4MTQyMzY0NTk3ODExNTQ3ODMyNjk5ODc2MjEzNDU1MjkxNzY0Mzg2NDg5MzIxNTc3MTM4NDU5MjYiXQ==)
```
fƛ⌊9β;ƛ⌊‹;ṅ⌊Sǒƛ⌊kPi;ṅ
```
[Decompressor](https://vyxal.pythonanywhere.com/#WyJQIiwiIiwiZsaba1DhuJ9TXFwwMsO44oazO+G5hWbGm+KMiuKAujvhuask4bmqJFwiZuG5hSIsIiIsInc5Z0BXMEU1eChAdmE2RWxLKT1nLllOSV94QGdzQE5jV3FoOEEwT3ghXG4iXQ==)
```
fƛkPḟS\02ø↳;ṅfƛ⌊›;ṫ$Ṫ$"fṅ
```
Input formatted as the test cases, but it converts it to an integer left to right then top to bottom so that's what I used for demonstrating. Not an entire sudoku solver, but it is a compression of 50.2%.
[Answer]
## C++ 241, score: 82\*10=820
Adds '!' to beginning of encoded string to determine which operation to perform.
Golfed 241 chars
```
void D(char i){static int x=0;cout<<(int)(i-'a')<<" ";if(x++%8==0) cout<<endl;}
int main()
{
int i=81;int n;string S;
char c=cin.peek();
if(c=='!'){cin>>S;for_each(S.begin()+1,S.end(),D);}
else{S.push_back('!');while(i--){cin>>n;S.push_back(n+'a');}cout<<S;}
}
```
Ungolfed 312 chars
```
void decode(char i) {
static int x=0;
cout<<(int)(i-'a')<<" ";
if(x++%8==0) cout<<endl;
}
int main()
{
int i=81;
int n;
string d;
char c=cin.peek();
if(c=='!'){
cin>>d;
for_each(d.begin()+1,d.end(),decode);
}
else{
d.push_back('!');
while(i--)
{
cin>>n;
d.push_back(n+'a');
}
cout<<d;
}
}
```
[Answer]
# Python, 106 bytes
```
def empty_sudoku():
return [[0 for _ in range(9)] for _ in range(9)]
def indexes():
return [(i, j) for i in range(9) for j in range(9)]
def valid_digits(sudoku, index):
r = set()
i, j = index
r.update(sudoku[i])
r.update(row[j] for row in sudoku)
k, l = [x - x % 3 for x in index]
r.update(sudoku[k + z][l + w] for z in range(3) for w in range(3))
return sorted(set(range(1, 10)) - r)
def compress(sudoku):
aux = empty_sudoku()
compressed = []
for index in indexes():
digits = valid_digits(aux, index)
i, j = index
x = digits.index(sudoku[i][j])
aux[i][j] = sudoku[i][j]
compressed.append((x, len(digits)))
assert (aux == sudoku)
n = 0
for x, y in reversed(compressed):
n *= y
n += x
bytes_length = 1
while True:
try:
b = n.to_bytes(bytes_length)
break
except OverflowError:
bytes_length += 1
return b
def uncompress(b):
n = int.from_bytes(b)
sudoku = empty_sudoku()
# compressed = []
for index in indexes():
digits = valid_digits(sudoku, index)
y = len(digits)
x = n % y
# compressed.append((x, y))
i, j = index
sudoku[i][j] = digits[x]
n //= y
return sudoku
```
Test:
```
from pprint import *
with open("testcases") as f:
tests = f.read()
tests = [[[int(cell) for cell in row.split()] for row in test.splitlines()] for test in tests.split("\n\n")]
compressed = list(map(compress, tests))
uncompressed = list(map(uncompress, compressed))
assert (all(t == u for t, u in zip(tests, uncompressed)))
score = sum(map(len, compressed))
print(score)
```
] |
[Question]
[
Given a string, consisting of a prefix and then "illion", convert this number into standard form.
For example:
```
"million" -> 10^6
"trillion" -> 10^12
"quattuordecillion" -> 10^45
```
The program needs to be able to handle input going up to Centillion, which is 10^303. A list of names and their standard form values can be found [here](http://polytope.net/hedrondude/illion.htm) - note that this gives values for every 10^3 increment up to 10^63, but then gives them in 10^30 increments, however the pattern is fairly straightforward.
The program needs to handle all 100 cases (even the ones not explicitly given by the website provided) - here are some examples of this:
```
"sexvigintillion" -> 10^81
"unnonagintillion" -> 10^276
"octotrigintillion" -> 10^117
```
Input can be given via STDIN, function argument or hard-coded as a string.
This is code-golf, so shortest code wins!
[Answer]
# Python 2 (~~384~~ ~~368~~ ~~365~~ ~~348~~ 347 bytes)
```
def c(s):
s=s[:-6].replace('int','');k=0;d=dict(un=1,doe=2,tre=3,quattuor=4,quin=5,sex=6,septen=7,octo=8,novem=9,b=3,tr=4,quadr=5,qu=6,sext=7,sept=8,oct=9,non=10,dec=11,vig=21,trig=31,quadrag=41,quinquag=51,sexag=61,septuag=71,octog=81,nonag=91,cent=101)
for p in(s!='m')*list(d)*2:
if s.endswith(p):s=s[:-len(p)];k+=3*d[p]
return 10**(k or 6)
```
(The `if` line is indented with a single tab, and the rest with single spaces.)
Here `c('million') == 10**6` has to be a special case because `'novem'` also ends in `'m'`.
Examples:
```
c('million') == 10**6
c('trillion') == 10**12
c('quattuordecillion') == 10**45
c('novemnonagintillion') == 10**300
c('centillion') == 10**303
```
Thanks to Falko for obfuscating it down to 350 bytes.
---
For practice I tried rewriting this as a one-liner using lambdas. It's ~~404~~ ~~398~~ ~~390~~ ~~384~~ ~~380~~ 379 bytes:
```
c=lambda s:(lambda t=[s[:-5].replace('gint',''),0],**d:([t.__setslice__(0,2,[t[0][:-len(p)],t[1]+3*d[p]])for p in 2*list(d)if t[0].endswith(p)],10**t[1])[1])(un=1,doe=2,tre=3,quattuor=4,quin=5,sex=6,septen=7,octo=8,novem=9,mi=2,bi=3,tri=4,quadri=5,qui=6,sexti=7,septi=8,octi=9,noni=10,deci=11,vii=21,trii=31,quadrai=41,quinquai=51,sexai=61,septuai=71,octoi=81,nonai=91,centi=101)
```
[Answer]
## JS (ES6), ~~292~~ 270
Understands only the numbers written in the given list. The OP isn't clear about the others.
```
z=b=>{a="M0B0Tr0Quadr0Quint0Sext0Sept0Oct0Non0Dec0Undec0Doedec0Tredec0Quattuordec0Quindec0Sexdec0Septendec0Octodec0Novemdec0Vigint0Trigint0Quadragint0Quinquagint0Sexagint0Septuagint0Octogint0Nonagint0Cent".split(0);for(i in a)if(~b.indexOf(a[i]))return"10^"+(20>i?3*i+6:93+30*(i-20))}
```
Example:
```
z("Billion") // "10^9"
z("Centillion") // "10^303"
```
[Answer]
# C, 235
Handles all 100 cases.
Program uses stdin and stdout.
Who needs regexes for camel-case splitting?
```
char*Z="UUUi+W<)E(<7-7-++*)('&%$,*$&%$",u[999]="\0MBRilDriPtiNiUnOeReTtUiXTeCtVeCiGRigRaUagInquiXaXsexPtuOgOoNaCeCeK1",s[99],*U=u+67;
main(n){
for(gets(s);*--U;)
*U<95?
*U|=32,
n+=!!strstr(s,U)*(*Z++-35),
*U=0:
3;puts(memset(u+68,48,3*n)-1);
}
```
### Example
```
octoseptuagintillion
1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
```
[Answer]
# Clojure, 381 377 bytes
```
(defn c[x](let[l{"M"6"B"9"Tr"12"Quadr"15"Quint"18"Sext"21"Sept"24"Oct"27"Non"30"Dec"33"Undec"36"Doedec"39"Tredec"42"Quattuordec"45"Quindec"48"Sexdec"51"Septendec"54"Octodec"57"Novemdec"60"Vigint"63"Trigint"93"Googol"100"Quadragint"123"Quinquagint"153"Sexagint"183"Septuagint"213"Octogint"243"Nonagint"273"Cent"303}v(l(clojure.string/replace x #"illion$" ""))](Math/pow 10 v)))
```
Example:
`(c "Septuagintillion") ;; 1.0E213`
[Answer]
# Haskell, 204 bytes (+9 for formatted String)
```
import Data.List
x s=10^(f$[a|k<-tails s,i<-inits k,(b,a)<-zip["ce","ad","un","do","b","mi","vi","tr","at","ui","x","p","oc","no","ec","g"]$100:4:1:2:2:[1..],b==i])
f[]=3
f(x:11:r)=30*x+f r
f(x:r)=3*x+f r
```
In GHCi:
```
*Main> x "decillion"
1000000000000000000000000000000000
```
Replacing `10^(` with `"10^"++(show.` adds another 9 bytes:
```
import Data.List
x s="10^"++(show.f$[a|k<-tails s,i<-inits k,(b,a)<-zip["ce","ad","un","do","b","mi","vi","tr","at","ui","x","p","oc","no","ec","g"]$100:4:1:2:2:[1..],b==i])
f[]=3
f(x:11:r)=30*x+f r
f(x:r)=3*x+f r
```
In GHCi:
```
*Main> x "decillion"
"10^33"
```
**Edit:** I had to correct for `"quinquagintillion"` which contains `"qua"`.
] |