text
stringlengths 180
608k
|
---|
[Question]
[
The quaint hamlet of Кодгольф in the Russian far east has a problem: their population is low (below 66), and no new people have arrived for years. Moreover, after centuries of near-isolation, just about everybody is related to each other.
Mayor Стекобмен has a solution that should keep the morale high: organise a wedding. However, the question is, are there two bachelors in the town that aren't at least cousins of each other?
The mayor fired up his state-of-the-art Microsoft Боб computer to consult the genealogy charts. They had just been updated to the brand-new ASCII format, and look like this:
```
ы┬К
ю
```
And this:
```
А┬д
О┴п┬Щ
Ф
```
And this:
```
з┬Й
Л┬м┴п─┬Ф
Ы┴я┬А ш┬Я
З Е
```
And even this:
```
ю┬────────Й
м┬Е
│ ш
│
│
Щ
```
Here's how it works. Each person is a letter from the [Russian alphabet](https://en.wikipedia.org/wiki/Russian_alphabet). Males are capital letters (any of АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ), females are lowercase letters (any of абвгдеёжзийклмнопрстуфхцчшщъыьэюя).
A '┬' between two people means they are married. Right below that is either another person - their child - or a '┴', meaning that this couple has two children; located to the left and right of the symbol.
Moreover, to the right and left of '┬' and '┴' there can be any number of '─' characters, to extend the lines, as it were. Similarly, there can be any number of '│' characters above a '┴' or below a '┬'.
Lastly, a character without any defined symbol above them is considered a new arrival to the village, and by definition unrelated to anybody.
Also be aware that this is a very conservative village. Nobody marries more than once, and every marriage is heterosexual. Furthermore, assume everybody in the graph is alive, and no two people share the same name: e.g., the same Cyrillic character never occurs more than once.
The two bachelors should be of the opposite gender, and they should not be first cousins or any more closely related. First cousins once removed is okay. In other words: they should not share a parent, or a grandparent, or have one's grandparent be another's parent.
## Challenge
Make the shortest possible program with as input either a string (containing newline characters), or a string array, or a rectangular two-dimensional string or char array (no higher or wider than 100 characters), containing the family tree of the town. Assume the input is a valid family tree. Ignore any character not given an explicit function in the above description.
It's fine to use an encoding other than Unicode for input/output purposes, e.g. [KOI8-R](https://en.wikipedia.org/wiki/KOI8-R#Character_set) as long as it's known and standardised by someone other than yourself. Scoring is done per [this answer](https://codegolf.meta.stackexchange.com/a/5879/81594). If your language handles Cyrillic natively, it's an advantage!
Return a boolean value of true or false (or a bit/int of 1 or 0, or any consistent truthy/falsey value used by the language of your choice) to indicate whether there can be a wedding given the family tree.
## Examples
1.
```
ы┬К
ю
```
FALSE (there's only one bachelor)
2.
```
А┬д
ю┬О┴п┬Щ
Щ ф
```
FALSE (Щ and ф are cousins)
3.
```
з┬Й
Л┬м┴п─┬Ф
Ы┴я┬А ш┬Я
З Е
```
FALSE (З, Е and Ы are all male)
4.
```
з┬Й
Л┬м┴п─┬Ф
ё┴А┬я ш┬Я
З Е
```
TRUE (ё and Е can marry)
5.
```
ю┬────────Й
м┬Е
│ ш
│
│
Щ
```
TRUE (ш is not related to anybody)
6.
```
д┬Ф
ю┬────────Й┴─ё┬З
│ │
│ ш <this person smells bad
│
│
Щ <this person betrayed the Party!
```
FALSE (Щ and ш are cousins)
7.
```
Щ 1234567890 quick brown foxes jumped over the lazy dog ш
```
TRUE (Щ and ш are unrelated)
8.
```
з┬Й
Л┬м┴п─┬Ф
й┬Ы┴я┬А ш┬Я
Э З ю
```
TRUE (ю and З, and also ю and Э)
9.
```
А┬д ф┬Ж
м┴п┬Щ ю┬Я
Ф ц
```
TRUE (ц and Ф)
NOTE: [Here](https://codegolf.stackexchange.com/questions/196035/can-this-scottish-village-have-a-wedding) is an ASCII version of roughly the same challenge.
[Answer]
# [K (ngn/k)](https://bitbucket.org/ngn/k), ~~230 203 200~~ 196 bytes
```
{t:{x*\:x};n:#*x:4(+|0,)/x;p:&2!c:+/"╒ё╡Ё©ъъ"<\:a:,/x;|//(~h=\:h:4!c p)&t[~|/p=/:?,/2#'(p^p^)'g]&3<{&/'x+\:x}/(~=#p)*(#a;1)0|/t'?(+/'p=/:/:g:{?'x,/'x x}/(!#a)+(-e;e,:n;e;n*e:-1 1;())4^"┴┬─│"?a)^0}
```
the input and the k code must be encoded in [koi8-r](https://en.wikipedia.org/wiki/KOI8-R#Character_set). test with (linux only):
```
git clone https://bitbucket.org/ngn/k
cd k/g
../k can-this-village-have-a-wedding.k
```
please make sure your editor handles koi8-r correctly. for instance, if using vim, you can type `:e ++enc=koi8-r` after opening the file or put `set fencs=utf-8,koi8-r` in your `~/.vimrc`
---
k functions are written in `{` `}`, have an implicit argument `x`, and consist of `;`-separated expressions.
the sequence of expressions is evaluated left-to-right but the code within each expression is right-to-left.
`t:{x*\:x}` helper function that creates a multiplication table ([outer product](https://en.wikipedia.org/wiki/Outer_product)) for a list `x`
`x:4(+|0,)/x` surrounds the input `x` with zeroes. literally: 4 times (`4(` `)/`) add zero(-es) on top (`0,`), reverse (`|`), and transpose (`+`).
`n:#*x` let `n` be the width of the input. literally: length (`#`) of the first (`*`)
`a:,/x` let `a` be the flattened input
`c:+/"╒ё╡Ё©ъъ"<\:a` for each character in `a`, count how many of `"╒ё╡Ё©ъъ"`are before it (in koi8-r). this will give odd numbers for russian letters and even for non-letters. also, the remainder mod 4 will indicate the sex - upper/lowercase.
`p:&2!c` take `c` mod 2 (`2!`) and make a list of the indices where (`&`) it's 1. "`p`" for "people".
the rest of the code will build three `p`×`p` matrices that represent conditions for marriage:
* the couple must be >3 steps apart in the graph of relatives. a "step" is a relationship of parent-child or spouse or sibling.
+ `4^"┴┬─│"?a` for each in `a` find its index among `"┴┬─│"` and fill in 4 if not found.
+ `(-e;e,:n;e;n*e:-1 1;())` replace `"┴"` with (-1;1;-n), `"┬"` with (-1;1;n), `"─"` with (-1;1), `"│"` with (-n;n), and others with an empty list
+ `(!#a)+` add `0 1 2`.. thus creating lists of neighbours
+ `g:{?'x,/'x x}/` transitive closure - extend (`,/`) each (`'`) neighbour list (`x`) with the neighbour lists of its neighbours (`x x`) and unique it (`?`), until convergence (`{` `}/`); assign to `g` for "graph"
+ `+/'p=/:/:g` for each of `g`'s neighbour lists build a boolean mask for which people are in it. ignore non-people.
+ `?(` `)^0` remove scalar 0s (`(` `)^0`) as they are a by-product of empty neighbour lists, and make the rest unique (`?`). this gives us a list of families as boolean masks.
+ `t'` build a family matrix for each family
+ `0|/` boolean-or of all family matrices
+ `(#a;1)` replace 0s with "infinity" (the length of `a` is as good as infinity here) and keep 1s as they are - this is a graph of how closely related `p` are. we need to find the shortest paths in it.
+ `(~=#p)*` put 0s on the diagonal. literally: multiply (`*`) by the negation (`~`) of the unit matrix (`=`) of that size (`#p`)
+ `{&/'x+\:+x}/` until convergence, try to improve *dist(i,j)* with *dist(i,k)+dist(k,j)* (similar to the [floyd-warshall algorithm](https://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm))
+ `3<` more distant than first cousins
* they must not be already married
+ `t[~|/p=/:?,/2#'(p^p^)'g]` check which `p` are among the first 2 (`2#`) of the intersection between people (`(p^p^)`) and each (`'`) neighbour list in `g`, and make it a boolean table
* they must be of opposite sexes
+ `(~h=\:h:4!c p)` remember that `c` mod 4 encodes gender information
finally, `|//`...`&`...`&`... and-s the three matrices and tests if there's a truthy element in the result
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~160~~ 159 bytes
```
Ø.UN,ƊAN,Ɗ+Ṫ¥+œị2,5yⱮ$ɼ=5,6⁼Ø.Ɗɗ¡ƬṪ¥ƒ⁸’1¦⁺œị®⁼5ƊпṖṪ+2¦œị®⁻.Ɗ¡ƬṪ¥ⱮØ+$“”¹?
Odȷ%⁴ỊḢịƊ€€H“¥©“©©‘;U¤œṣjƭƒ$€ƬṪ©=.ŒṪ+2¦œị®ɗⱮØ+f2,4ƊÐḟWÇ€Ẏ$Ƭḣ3ẎƲ€Œcf/ÐḟḢ€€ȧœị¥O>⁽¡FIFẸ
```
[Try it online!](https://tio.run/##lVNbTxNREH7vrxiT@tSKUihqKhhfiL6IL8Tnlm6FWii2Ra1PXUKElARqrbR4DUIx1QWiaUpvSnKabujb7k/Y80fqzNm1tgQKnGzOnLl838yZPROUQqF4u93IDUw@dKrJe7Q5jMp3lnc03xq1VZfTHec/9@2t@qjbOcLlOkaqyVaWbamKCFPTXC7zxOYg2@VyVWDYPsa51WQjxY6MygaGOVxst@OqIUEHjtyNnMPOEx954hOr3LVN@I8Pr3K5aNSSRvkrQtQkX1Twu48xLM8KJAokcp5JtoOsle2guqem7RhjkhZGB5rp3qytrJko4HIOU2FG@cvjxjIijOqaHVHl7SE8qb/Q0kxPBa6LCMxvpj7@ZtLkJ8a4/JttjT8YN6rltodKKcG1McDaPUat2Fi220RBXP7DSqwkMgQtpd3WV3lG0d4DgA30NSBpw01LkbkIlp2UzzxT1I7oVCAjkAB9yUJoh@TZBIHQPpBStwAJUnbI/AMt@jqpKdBXSB6AyJal7d3FmfQ3ZKEa9fWzmbqWuIIgOOWjZD3hlFAhls7qZeOZRZN1pZ8XLu0ULf3v63ZqRevu/ZftvJti31BS/xTRq35UJ4s9oV4Egh26E5ueicK8FImG5yA6i7MdBZ/XfxYCLpvifAC2tacInxSLeOOSH2LTEjzyRmLxK91dx/BB19Cwe@Tmrds34NnCzNRT8EXCL@YgEH4pRSG4MDuP4PBzKSIYQt5XcfCHn@BlzV/W84JRPWMaKnQ6fSS0vX9vmWYSWbvmkYaOlA3B3uFVrMdjDuuB9bQ6L0Z/DfAX "Jelly – Try It Online")
A monadic link that takes a list of Jelly strings and returns 1 for true and 0 for false.
I’m sure this could be golfed more. Full explanation to follow.
[Answer]
# Python3, 1001 bytes:
```
m='АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ'
f=m.lower()
def g(t,c,l,w,d,s=[],r=[],o=-1):
k=0
for q,(x,y) in [(0,[0,-1]),(1,[1,0]),(1,[-1,0])]:
if q!=o and len(t[0])>(a:=c[0]+x)>=0 and len(t)>(b:=c[1]+y)>=0 and(a,b)not in r:
if(h:=t[b][a])=='│'or h=='─':k=1;yield from g(t,(a,b),l,q,d,s,r+[(a,b)])
elif h =='┴':k=1;yield from g(t,(a,b),h,q,d,s,r+[(a,b)],o=1)
elif h=='┬':
if q:d.append(s[-1])
else:k=1;yield from g(t,(a,b),h,q,d,s,r+[(a,b)])
elif h in m+f and l in'┬┴':k=1;yield from g(t,(a,b),h,q,d,s+[h],r+[(a,b)])
if not k:yield s
def e(x,y):
return not any((q:=set(a)&set(b)) and any(a.index(i)<3 for i in q) for a in x for b in y)
def a(t):
b,p,z=[*filter(None, t.split('\n'))],{},[]
for x,y in[(x,y)for x in range(len(b[0]))for y in range(len(b))if(l:=b[y][x])in m+f]:
for s in g(b,(x,y),b[y][x],0,z,s=[b[y][x]],r=[(x,y)]):
p[s[0]]=p.get(s[0],[])+[s]
return any(a not in z and b not in z and len(set([a in m, b in m]))==2 and e(p[a],p[b]) for a in p for b in p)
```
The basic idea is to traverse the input graph, building paths between nodes (the genealogy for each node), marking which nodes are already married, and then checking if it is possible for any two resulting nodes to marry (not already married, male and female, not cousins, etc.)
[Try it online!](https://tio.run/##lVTbbttGEH3nV0z8UHGrtSFavqphPqHoO8sH0lpJrCmSIuladFHALYqiQIHEaeOkTtr0ll7cOM2LgaKAgf7C6Bf6I@7skLJo1XEcwhBndnbOnjk866TIB3HU3kjS8/Oh3cADvI9f4df4AA/xE3yIj/AbPMLH@AS/xe/wKX6PP@CP@BP@jM/wF/wVf8Pf8Rj/wOd4gi/wT3zZMHr2cCmMd1VqCqOretA3c7klQ7kruzKzHVem@ie2Fy3RMWDbbhnQi1MYSXMsCwFBBI7Zkk5LLlqukKYlHUu2qmiRQ5f6AIIejG7ZMXhRF0IVmblDpTum17G3KGqOxR27NStSxdcVy20W04rpSV9Eca7PTBmTQM1Bx84d33U8V9h2498HnzaI3YDD/UZn27beKQIVdqGXxkMejmFowJEeUKZNhxdcwYAqJJ4D4PbTa9oH8@2kkFWHYISTRkmTh@90l7wkUTRH5mityooKM/UGx1xiSToMm71SNEr0gTdi3XQG7iVIQtO6bnfKroyNoPgD0wCpynfSiHd4UWGao46dqdz0xFv65QvBDHTJWwqirhqbgbjdZpcEmuNIcOzpeMyhr8Oi9JtHH5sO8WUi92zn7V4Q5uTFd@NISciXsiQMcrPxftQQpPFHH0vHLf1H3AjEYY6csyu8qK9MbSBfu4sLxVxBCDJN2LF9p3CdsStKEUuP6v2Z3t83/dLfstomW3JPX4cq5VvBG1xRfuLEyehI106W@iSKjomqaDqZeyEgKwSVgfdYNP9yqglqTR3WaihLoYY0iW0v8w5lJuR0mZDja6omM1UTcZ5Z9sLCgjH5kvyAjw2Y3AVDL2TLvI4Hev0UwMCnZBf8R6fHoKfAZ9XONvBWamVP7V/5h0ca40y3H8LsMYAuIUeTL@ZX4JULxKCeM4uVkgTgX/qMIy7gEx2fVcT3dUKk8TktTO7p7ICO1e@XPNAj/XNY4a3eFA@MyX29opWa3JsCwv8R1yrEiwdPK4Trn9cqS6fTW7M44ROvg5oXcy69SQt9qdv5IMggUWkWR5ANVRhm4HvdV3XAmx7x@gaywCUSvspTr1BdyAcK3vPSvLg175B1sIE9fQzWcntldW19Y7MFo51gaxv8NN6N6GKMVQYf7AwTAoo/VCmjhd5eAd24T4OXQBsVEH/DmT2Y1tUOwb91dIXvtJlfTJ1Cd6@iulla5eL2seyf6eRheQHOapeRi3dLOChJTT01@Xw6fZIGEf0bNjNLiFmyXE/a9WSlnqzWk7V6sl5PNurJphDn/wE)
] |
[Question]
[
## Description
Imaginary programming language (IPL) uses Polish Reverse Notation. It has the following commands:
* **i** -- input number and push it to the stack
* **o** -- non-destructive output top of the stack (number stays on the stack)
* **d** -- discard top of stack
* **integer number** -- push this number to the stack
* **+-\*** -- pop two numbers from the stack, perform corresponding operation and push back the result. There is no division in IPL.
IPL works only with integers and is used for simple calculations. An IPL program is written on one line and separated by spaces.
Empty string is a valid IPL program.
IPL Program:
```
i i + o
```
Inputs two numbers, adds them together and outputs the result.
Input numbers and integers that can be pushed to stack are in range [-999, 999], however output can be any. If your language do not support big numbers it is okay though.
## Input/output format
You may choose any input/output format as long as it clear to understand and read/write: string, list, tokens etc.
## Task
You are given some IPL program, you need to optimize it (reduce length):
```
i 12 + 3 + o d 2 3 + d
```
After optimization will become
```
i 15 + o
```
You do not have to preserve stack state, but amount of inputs and outputs and their order should match for the original and optimized program.
So IPL program:
```
-40 i * 2 * o i + 3 1 + o i 2 *
```
After optimisation will become
```
i -80 * o i 4 o i
```
or
```
-80 i * o i 4 o i
```
(note that you have to save all inputs, even if they are irrelevant).
There should be no hardcoding for test cases, code should work on any arbitrary IPL program and produce shortest possible IPL program that meets the requirements.
## Scoring
Default code-golf scoring.
UPDATE: changed scoring to pure code golf scoring, as per @Sanchises suggestion.
## Test cases:
Input:
```
(empty string)
```
Possible output:
```
(empty string)
```
Input:
```
i 4 * 2 + 3 * 6 - o
```
Possible output:
```
i 12 * o
```
Input:
```
1 1 + o
```
Possible output:
```
2 o
```
Input:
```
i 2 + 3 + o d 2 3 + d
```
Possible output:
```
i 5 + o
```
Input:
```
-40 i * 2 * o i + 3 1 + o i 2 *
```
Possible output:
```
-80 i * o i 4 o i
```
Input:
```
i i 1 + i 1 + i 1 + i 1 + d d d d o
```
Possible output:
```
i i i i i d d d d o
```
Input:
```
i i i 0 * * * o
```
Possible output:
```
i i i 0 o
```
Input:
```
i i i 1 * * * o
```
Possible output:
```
i i i * * o
```
Input:
```
i 222 + i 222 - + o
```
Possible output:
```
i i + o
```
Input:
```
i 2 + 3 * 2 + 3 * 2 + 3 * i * d i 2 + 3 * i + d i o 2 + 2 - 0 * 1 o
```
Possible output:
```
i i i i i o 1 o
```
Input:
```
i 1 + 2 * 1 + o
```
Possible output:
```
i 2 * 3 + o
```
Input:
```
1 1 + o i 2 + 3 + o d 2 3 + d 4 i * 2 * o i + 3 1 + o i 2 * i i 1 + i 1 + i 1 + i 1 + d d d d o i i i 0 * * * o i i i 1 * * * o i 2 + i 2 - + o i 2 + 3 * 2 + 3 * 2 + 3 * i * d i 2 + 3 * i + d i o 2 + 2 - 0 * 1 o
```
Possible output:
```
2 o i 5 + o 8 i * o i 4 o i i i i i i d d d d o i i i 0 o i i i * * * o i i + o i i i i i o 1 o
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~733~~ ~~728~~ ~~690~~ ~~564~~ ~~516~~ ~~506~~ ~~513~~ 548 bytes
```
j=Integer;f=Flatten;s=SequenceReplace;A=FixedPoint[f@s[#,{{x_j,p,y_j,t}->{y,t,x*y,p},{x_j,y_j,p}->x+y,{x_j,y_j,t}->x*y,{x_j,p,y_j,p}->{x+y,p},{x_j,t,y_j,t}->{x*y,t},{0,p}|{1,t}->{},{0,t}->{d,0}}]//.{a___,Except[i|o]}->{a}&,#]&;B=Expand@Check[f@FoldPairList[f/@Switch[#2,i,{{i},{#,i@c++}},o,{{Last@#},#},d,{{},Most@#},p,{{},{#[[;;-3]],Tr@#[[-2;;]]}},t,{{},{#[[;;-3]],#[[-2]]*Last@#}},_,{{},{##}}]&,c=0;{},#],x]&;F=MinimalBy[w=A@f[#/.m->{-1,t,p}];z=B@w;s[#,{-1,t,p}->m]&/@A/@Select[Permutations@Join[w,Cases[z /.i@_->i,_j,∞]],B@#==z&],Length][[1]]&
```
[Try it online!](https://tio.run/##XVLdbtowFL7nKSwioS04BOi0i0VBLlWpVlGJjd5ZVmQlprhL4iwxIpD6fk@xh9uLsOMERLckir/zne/82c643oqMaxnz0@k1/Jpr8SLKYBMuUq61yIMqXIufO5HH4rsoUh6L4DZcyFokKyVzTTekog5umjp6xQU@wF8bb9YcsMa1e8CFwa3LOgpw1MPDlbBKK3oXbDWNFV0C9TWnlWqgx@B8ayYd2dotSvDYGOb7o4ZHUYTv61gUmso3xayXmwF22CCYh/d1wfOE3G1F/APaX6g0WXFZLmUF0/hkvZc63lJniiWMJSG/gyWJh0NjsAJmyStNHIPhS8A0@El1RNFajUNpEHg3jOHnkoDhTYOAMQjW//tbJ2PuOaPB0VkBmA1wHI4DMB2Ga@h7ET7JXGY8nR/oPrwlG@r4owwG82AjYENYcAznZB@0p3HmvFnGBj65haFEKmJNV6LMdhoOW@UVeYTzo3t8xytR0SPyR5JE3kxi2O4/v35Df3PihOFxwPBS5C96yyidMDY4fXDRvuRFIUq0USWSvrIrXCHkfuw90HXE0JcQrXUp85fzlaFNv@gjb4b6wz5G/azDnsW6w27fMHKOkZtNKkgPXZ5vOyk0WbxjnhUcYimqCgahXdS6SKWmawZzoAbK2KwFtkUsyrAtYZE2rNdblfbqOt7sgcCdQD6BENuMRJ@Qi6ZoiG5g/Yw8pCw9QROgVKfovGCiBLBFSeew7xjC7Kuu1ORfajq1CbrVu2a1BaagelfIm4DMvdo3l3Zkq@z@w0uH6hxqTn8B "Wolfram Language (Mathematica) – Try It Online")
This is a four-step tour-de-force that (1) replaces "-" with "-1 \* +" so that we don't have to deal with subtractions, (2) simplifies the list of commands a bit, (3) makes a list of all permutations of this list of commands and picks out those that give the same result when parsed (executed), and (4) simplifies these lists of commands a bit and picks the shortest, after converting certain operations back to subtractions.
This code is terribly inefficient because it goes through the list of all permutations of the input code. For long input codes I don't recommend running this code; but as I read it there are no runtime or memory restrictions in this challenge.
This code does the optimization step after converting all "-" operations to "+" operations with signs flipped, and only at the end re-introduces the "-" operator when converting code back to strings. This implies for example that "i -1 i \* + o" is correctly optimized to "i i - o".
As the i/o format requirement is quite loose, this code takes and returns code as lists, where the symbols "+", "-", "\*" are represented by p, m, t, tokens respectively. The conversion from and to strings is done in the wrapper function given on TIO:
```
G[S_] := StringReplace[{"p" -> "+", "m" -> "-", "t" -> "*"}]@StringRiffle@
Quiet@F@
ToExpression[StringSplit[S] /. {"+" -> p, "-" -> m, "*" -> t}]
```
Un-golfed version, including the string-format wrapper and minimizing the final code string length instead of the number of tokens, and including a few more transformation niceties:
```
(* convert code string to list of operators *)
inputfilter[s_] := ToExpression[Flatten[StringSplit[s] /.
{"i" -> i, "o" -> o, "d" -> d, "+" -> p, "-" -> {-1, t, p}, "*" -> t}]]
(* convert list of operators to code string *)
outputfilter[s_] := StringReplace[StringRiffle@Flatten@SequenceReplace[s,
{{-1, t, p} -> m, (* convert "-1 t p" back to "-" *)
{x_ /; x < 0, p} -> {-x, m}, (* convert "y x +" to "y -x -" when x<0 *)
{x_ /; x < 0, t, p} -> {-x, t, m}}], (* convert "y x * +" to "y -x * -" when x<0 *)
{"m" -> "-", "p" -> "+", "t" -> "*"}] (* backsubstitution of symbols *)
(* simplify a list of operators somewhat *)
simplifier[s_] := FixedPoint[Flatten@SequenceReplace[#,
{{x_Integer, p, y_Integer, t} -> {y, t, x*y, p}, (* "x + y *" -> "y * (xy) +" *)
{x_Integer, y_Integer, p} -> x + y, (* "x y +" -> "(x+y)" *)
{x_Integer, y_Integer, t} -> x*y, (* "x y *" -> "(xy)" *)
{x_Integer, p, y_Integer, p} -> {x + y, p}, (* "x + y +" -> "(x+y) +" *)
{x_Integer, t, y_Integer, t} -> {x*y, t}, (* "x * y *" -> "(xy) * *)
{0, p} | {1, t} -> {}, (* "0 +" and "1 *" are deleted *)
{x_Integer, i, p} -> {i, x, p}, (* "x i +" -> "i x +" *)
{x_Integer, i, t} -> {i, x, t}, (* "x i *" -> "i x *" *)
{0, t} -> {d, 0}}] //. (* "0 *" -> "d 0" *)
{a___, Except[i | o]} -> {a} &, s] (* delete trailing useless code *)
(* execute a list of operators and return the list of generated outputs *)
parse[s_] := Expand@Quiet@Check[Flatten@FoldPairList[ (* stack faults are caught here *)
Function[{stack, command}, (* function called for every command*)
Flatten /@ Switch[command, (* code interpretation: *)
i, {{i}, {stack, i[inputcounter++]}}, (* output "i" and add input to stack*)
o, {{stack[[-1]]}, stack}, (* output top of stack *)
d, {{}, Most[stack]}, (* delete top of stack *)
p, {{}, {stack[[;; -3]], stack[[-2]] + stack[[-1]]}}, (* add two stack elements *)
t, {{}, {stack[[;; -3]], stack[[-2]]*stack[[-1]]}}, (* multiply two stack elements*)
_, {{}, {stack, command}}]], (* put number onto stack *)
inputcounter = 0; {}, (* start with zero input counter and empty stack*)
s], (* loop over code list *)
x] (* return "x" if an error occurred *)
(* the main function that takes a code string and returns an optimized code string *)
F[s_] := Module[{w, q},
w = simplifier@inputfilter@s; (* convert input to useful form *)
q = parse[w]; (* execute input code *)
MinimalBy[
outputfilter@*simplifier /@ (* simplify and stringify selected codes *)
Select[Permutations[w], (* all permutations of code list *)
parse[#] == q &], (* select only those that give the correct output *)
StringLength] // Union] (* pick shortest solution by length *)
```
Thanks to @redundancy for catching a bug: The parser needs a `Expand` applied to the output in order to handle distributive equivalence. 506→513
### update
Now also optimizes `1 o 1 + o` to `1 o 2 o`. This was a surprisingly difficult case and made the code much slower. 513→548
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 268 bytes
```
r←¯999+⍳1999
{⍺←,⊂(⍵∊,¨'io')/⍵⋄p←⊃⍺⋄≡/{⍺←⍬⍬⋄s o←⍺⋄0=≢⍵:o⋄h←¯2↓s⋄t←¯2↑s⋄u←⊃⍵⋄v←1↓⍵⋄∨/u∊⎕D:(s,⊂,⍎u)o∇v⋄'i'=u:((s,⊂,0)o∇v),¨(s,⊂,1)o∇v⋄0=≢s:.1⋄'o'=u:s(o,¯1↑s)∇v⋄'d'=u:(¯1↓s)o∇v⋄1≥≢s:.1⋄(h,,¨∘.(⍎u)/t)o∇v}¨p⍵:p⋄((1↓⍺),,(⍳≢p)∘.{(⍺↑p),(⊂⍵),⍺↓p}(,¨'d+-×'),('-'@('¯'=⊢)⍕)¨r)∇⍵}
```
[Try it online!](https://tio.run/##fVLBattAEL37K/a2u1iKvU5bsMHQ0kKbQwnUgfZqKlMvDV1h2YEk@JIYx5aRaTAhPbaBgg8FH0wvOSp/Mj@izuxKbiGiSKzmzbw3@3a03fDYD067x@ZTBsubg0OYfq1nA1zTTbPZrEKyVfitnENyj0kP4gsByW@YxV665tpwWSO4mIRYhfiSaIsJzH/UcgUkv@hdTCJmLKR6vQ3zO9S1DIK@3awB01WEaFiga0KjoittcYJAIc0hmK1rI/SBrl@1RETOPEiWI2lgdnWCBK55e9QSeanu8hJt5xm1Y1o7UWtPkcqQKhLGSzeKXMiiXWDb2ewq2mkVzH/@VYu@hxvA7NuesF5qQ0ccp@uQzhsSR7hD3EvPQ9YW1aEkybmwI7sOJebjC@RLz2ZW4VjQuIOq/3DLscp9/lzwdMPbEN9JSG5kuh6QUdSMs6jXHXzs22Ev3T@NL9PNPnZG1Hn3EtejNwedbGg@977osx4yOePoQMD8O8RT6llxV0DZC/C04lqyQsE1e8IeblmDVdk@Bc@Yzwx/RFNMIaOkoHMpFlmAMUUBt5vibSmha9vJrQE@piBvG6Vszerky72lBlzP/3N253scaFoCpv/NVG3C2FQDJ2ItqMKrYmVWfVW0LZ2fySeYvX3x4X2nrV7/AQ "APL (Dyalog Unicode) – Try It Online")
An anonymous function that takes tokenized program as input, and gives the tokenized minimal program as output. Uses `×` instead of `*` for multiplication.
The idea is that each output can only be linearly dependent on each input. This means that if we want to check the equivalence of two programs, it is enough to compute and compare the outputs for each input being 0 or 1 (`2^n` cases if the original program has `n` input commands). We can entirely avoid symbolic computation this way.
Since trying out ~2000 constants takes forever, I put the variable `r` outside of the function so that we can test for small ranges and observe that the code actually solves the challenge.
### Pseudocode
```
Take a tokenized program.
Create the minimal candidate program by removing all commands except I/O.
Create a queue of candidate programs.
While the head of the queue is not equivalent to the original program
Pop the head
For all possible tokens except I/O (Note 1)
For all possible positions in the program (Note 2)
Insert the token at the given position of the program
Push it at the end of the queue
Output the minimal equivalent program
```
Note 1: All possible tokens include `d`, `+-×`, and the numbers -999 to 999 (inclusive).
Note 2: Given a program of length `n`, only the positions 0 to `n-1` need to be considered. The head (position 0) is needed to account for the cases like `1 i - o`. The tail (position `n`) is not needed because it doesn't affect the output(s) in any way.
### Ungolfed with comments
```
⍝ takes tokenized words, 'i' 'o' 'd' '+' '-' '×' or 'num'
⍝ [stk out] runIPL tokens → output
runIPL←{
⍺←⍬⍬ ⍝ Initialize stack and output
stk out←⍺
0=≢⍵:out ⍝ Nothing to process
h←¯2↓stk ⋄ t←¯2↑stk
u←⊃⍵ ⋄ v←1↓⍵
⍝ If the next token is num, push it
∨/u∊⎕D: (stk,⊂,⍎u)out∇v
⍝ If it is 'i', collect the results for 0 and 1
'i'=u: ((stk,⊂,0)out∇v),¨(stk,⊂,1)out∇v
⍝ Stack underflow; break out and output an invalid value
0=≢stk: .1
⍝ Output
'o'=u: stk(out,¯1↑stk)∇v
⍝ Drop
'd'=u: (¯1↓stk)out∇v
1≥≢stk: .1
⍝ Arithmetic
(h,,¨∘.(⍎u)/t)out∇v
}
⍝ strip non-IOs
⍝ takeIO tokens → IO tokens
takeIO←{(⍵∊,¨'io')/⍵}
range←¯1+⍳15
⍝ search for the shortest program whose output exactly matches the original
⍝ should terminate eventually when it meets the original program
⍝ [prog.queue] search tokens → tokens of equivalent program
search←{
⍝ Initialize the queue with single program with only I/O commands
⍺←,⊂takeIO⍵
⍝ List of tokens to try inserting
newToks←(,¨'d+-×'),('-'@('¯'=⊢)⍕)¨range
prog←⊃⍺ ⋄ rest←1↓⍺
⍝ List of indexes to insert the token
idxs←⍳≢prog
⍝ If the program's output matches the original, it is the answer
(runIPL prog)≡runIPL⍵: prog
⍝ Otherwise, add all possible insertions to the queue
(rest,,idxs ∘.{(⍺↑prog),(⊂⍵),⍺↓prog} newToks)∇⍵
}
```
[Try it online!](https://tio.run/##jVTNaxtHFL/vX/Fuu4tWttf9OLgYGggUQVoVEmig5LDRjrWDVjvKzKxlt/jSBsdWUWgaQnIJpIGCDwUfTC4@Kv/J/CPqb2Y/sk4iKNIsM2/e@703v/eRzPJ@epzkYrw2T18Mhub0z521Wb4mnUyYIi0mrOC/sJTmQqYqIp/75AusFKuH1cd6/9InIckvyqnvWeOflZ6QKPUDkmUx@PFOhaPInP5lxbNSe9UF3P3qEZnlNXZm@S/@9vSaBgXXPMnhmpRORhNKirQxJarhnc01zjv75vytWb7bg7Cy/0HojBdjOKaZFCOmFNQyGKwud83pcwtg/nhMupE8gwQapYVc/A4od32IYwx1nD2vDuyAdMaoYEe6ehVxRXh4RLNSZcRteObsYrs0ZwswenuPAkBHZvFbZJZPy9CGffbk8AMa1xYBvEY0EnnORto5kEyVuVZ0AGJ33Otj2EBtvwRki7nTAIbR6qKVxh@5uesoLIuUyYNczL@hh5IljsIOr9gSLw5Bekr4lqwhFqh7tBXXWMMmCSgDGwtuAwBEq8u4ojHsOL4txcyqplXYTseS34kvNuf/fOLkluQ6mzLNRxAEWYTHmbNXW4GjcFu35ieeqzelJZ9RIYr@YKi8pnwHw27dtSevurOlB7x3yBPQfS78cBtHIMqkGDNXGHHPLK/ir2onLJGjzCXEJkhlQmqmtK2vsUymNM@EYg2X7CgZ6fyYpokeZbaRYCEkH/MiySu0TJR5SprJKWSaETtkhS6THEbzzJaVpilj@qZp46zqMnvYelSykj1oous8uN6KA2KPSo6MAr@1r9Tb9rvRcNahQ6U5skAKfZSzD8@0MlEgzMH2ECU7naKEVNvEtv5qgtE0FfYdDpoQRx0RelLLY9SaYlIDHFoFm98TEwX7wCYj7fUxU8IowHj5NvBXl/6@WbwNzfJFuLpw6YGNDahp12vXrugZ3Xbs9UfOOar/yI202rN7pwsJmjw9Um6cXKEWLfLNdq8f76smv5/La1T3spUlhZozaYu3noAWITTnf9dzD7OKOm6GsJFzrlhESZoSqoBmQin@EMTXPImauSY5DhsPjiIbO9n2sPWMHDxzvqIAmYCfMHLC51Z40hBte9Tm52S9rioBUzww52/M4tQS7XP6kt6/pF3q0Rd28zX1SfjeZ3VjiqG26ZbXINCgFHu7S/22xzDwN9lxh1t9U/xE1@pqd7MZx8BEzNV/c1yVh/@h2LLw6YbbT0q8K@k5gXCiXfDmgom74ce0Mfp@3OBvplvUhK@/v3X/p7v78Xf/AQ "APL (Dyalog Unicode) – Try It Online")
] |
[Question]
[
You find yourself on a chessboard, as one does. You can see the exit but it is awfully far away and you would rather not walk all the way. Luckily some locals have offered you a ride. A Knight, a Rook, a Bishop and a King are all willing to take you to your destination, but seeing how this is a chessboard they must each abide by the rules of chess on the way to your destination. You would like to get out of here as soon as possible, whose offer do you accept?
# Task
Given a arbitrarily shaped and sized chessboard and two points on the chess board, output the chess piece that can move between the two locations in as few moves as possible. Boards will not necessarily be continuous meaning that there could be gaps between sections of the board. Each of the four pieces (King, Rook, Knight, and Bishop) can move according to their standard rules in chess. The Queen and pawn pieces have been intentionally left out of this challenge.
# I/O
You may take input in any reasonable format and you may output in whatever format you choose as well. Your input and output must be self-consistent. If multiple pieces can make it to the destination in the same number of moves you must output all of the pieces that can get there in the minimum amount of time. If none of the four pieces can make it to the end you may output anything as long as it is distinct from all other possible outputs. This could include outputting nothing or throwing an error.
# Test Cases
A square indicates the starting point and a circle indicates the ending point.
---
[](https://i.stack.imgur.com/k5xgL.png)
Bishop
---
[](https://i.stack.imgur.com/u40hU.png)
Knight
---
[](https://i.stack.imgur.com/Wx88W.png)
King
---
[](https://i.stack.imgur.com/ioh07.png)
Rook
---
[](https://i.stack.imgur.com/is42i.png)
King, Knight
---
[](https://i.stack.imgur.com/RFFhc.png)
None
[Answer]
# [Haskell](https://www.haskell.org/), ~~447~~ ~~439~~ ~~437~~ 432 bytes
```
t=[1,2]
p=[(+),(-)]
f=filter
a=abs
(#)=elem
x?y=[min x y..max x y]
f&g=(\x->g x>>=f)
(b!1)(c,r)=f(#b)[(c!d,r#s)|(!)<-p,(#)<-p,d<-t,s<-t,d/=s]
(b!2)(c,r)=f(\(d,s)->(c==d&&all(#b)[(c,z)|z<-r?s])||r==s&&all(#b)[(z,r)|z<-c?d])b
(b!3)(c,r)=f(\(d,s)->a(c-d)==a(r-s)&&all(#b)(zip(c?d)$r?s))b
(b!4)(c,r)=f(\(d,s)->a(c-d)<2&&a(r-s)<2)b
(b%p)n s=[s]>>=foldr(&)(:[])(replicate n$b!p)
g b s e=head$f(not.null)[[p|p<-[1..4],e#(b%p)n s]|n<-[0..]]
```
Call using `g <board> <start> <end>` where `<board> :: [(Int, Int)]`, `<start> :: (Int, Int)` and `<end> :: (Int, Int)`. Returns a list containing `1` for Knight, `2` for Rook, `3` for Bishop, and `4` for King. If no solutions are found, it consistently overflows the stack (that counts as throwing an error, right?).
Inspiration taken from LYAH's chapters on Monads—`(%)` is just a generalized and golfed `inMany`, with `(&)` equivalent to `(Control.Monad.<=<)`. Everything else should be more-or-less self-explanatory.
This can probably be golfed a lot more, but I've had enough fun for now.
Ungolfed:
```
data Piece = Knight | Rook | Bishop | King deriving (Show)
type Place = (Int, Int)
type Board = [Place]
x `to` y = [min x y..max x y]
f <=< g = (\x -> g x >>= f)
moves
:: Board -- available spaces
-> Piece -- type of piece
-> Place -- starting place
-> [Place] -- places available in one move
moves b Knight (c,r) =
filter (`elem` b) [(c!d, r#s) |
(!) <- [(+),(-)], (#) <- [(+),(-)],
d <- [1,2], s <- [1,2], d/=s]
moves b Rook (c,r) =
filter (\(d,s) -> (c == d && all (`elem` b) [(c,z) | z <- r `to` s])
|| r == s && all (`elem` b) [(z,r) | z <- c `to` d]) b
moves b Bishop (c,r) =
filter (\(d,s) -> abs(c-d) == abs(r-s)
&& all (`elem` b) (zip (c `to` d) (r `to` s))) b
moves b King (c,r) =
filter (\(d,s) -> abs(c-d) <= 1 && abs(r-s) <= 1) b
canGoIn
:: Board -- available spaces
-> Piece -- type of piece
-> Int -- number of moves
-> Place -- starting place
-> [Place] -- places available in the specified number of moves
canGoIn b p n s =
return s >>= foldr (<=<) return (replicate n (moves b p))
quickestPieces
:: Board -- available spaces
-> Place -- starting place
-> Place -- ending place
-> [Piece] -- quickest pieces
quickestPieces b s e =
head $ filter (not.null)
[[p | p <- [Knight, Rook, Bishop, King], elem e (canGoIn b p n s)] |
n<-[0..]]
```
[Answer]
# Mathematica, ~~326~~ 325 bytes
*Thanks to masterX224 for pointing out a byte savings!*
```
f[g_,w_,x_]:=(c={{1,1},{-1,1}};s=c.c/2;e=#<->#2&@@@#&;j=Join;h=FindShortestPath;t=#~Tuples~2&;a@d_:=e@Select[t@g,#-#2&@@#==d&];y@k=j@@(a/@j[s,c]);y@n=j@@(a/@{{1,2},{2,1},{-2,1},{-1,2}});v=Flatten[e@t@#&/@ConnectedComponents@a@#&/@#]&;y@r=v@s;y@b=v@c;Pick[p={b,k,n,r},z=Length[h[y@#,w,x]/.h@__->0]&/@p,Min[z~Complement~{0}]]);
```
Defines a function `f` taking three arguments: `g` is a list of ordered pairs of integers representing the board, and `w` and `x` ordered pairs representing the start and end squares. The output is the subset of `{b, k, n, r}` (representing bishop, king, knight, and rook, respectively) which have a minimal-moves path between the two squares. For example, the third test case is invoked by `f[{{0, 0}, {1, 1}, {1, 2}, {0, 3}}, {0, 0}, {0, 3}]` and returns `{k}`; the last two test cases return `{k, n}` and `{}`, respectively.
The strategy is to translate the squares of the board into vertices of a graph, where the edges are determined by each piece's moves, and then use built-in graph routines.
More user-friendly version of the code:
```
1 f[g_, w_, x_] := ( c = {{1, 1}, {-1, 1}}; s = c.c/2;
2 e = # <-> #2 & @@@ # &; j = Join; h = FindShortestPath; t = #~Tuples~2 &;
3 a@d_ := e@Select[t@g, # - #2 & @@ # == d &];
4 y@k = j @@ (a /@ j[s, c]);
5 y@n = j @@ (a /@ {{1, 2}, {2, 1}, {-2, 1}, {-1, 2}});
6 v = Flatten[e@t@# & /@
7 ConnectedComponents@a@# & /@ #] &;
8 y@r = v@s; y@b = v@c;
9 Pick[p = {b, k, n, r},
10 z = Length[h[y@#, w, x] /. h@__ -> 0] & /@ p,
11 Min[z~Complement~{0}]]
12 );
```
In line 3, `Select[g~Tuples~2, # - #2 & @@ # == d` finds all ordered pairs of vertices whose difference is the vector `d`; `e` then transforms each such ordered pair into an undirected graph edge. So `a` is a function that creates edges between all vertices that differ by a fixed vector.
That's enough to define, in lines 4 and 5, the king's graph `y@k` (which takes the union of edges generated by the vectors `{1, 1}`, `{-1, 1}`, `{0, 1}`, and `{-1, 0}`) and the knight's graph `y@n` (which does the same with `{1, 2}`, `{2, 1}`, `{-2, 1}`, and `{-1, 2}`).
In line 7, `ConnectedComponents@a@#` takes one of these neighbor graphs and then finds its connected components; this corresponds to grouping all line segments of vertices in the given direction (so that a rook or bishop doesn't have to move through them one by one). Then `e@t@#` on line 6 puts edges between every pair of vertices in the same connected component, which are then `Flatten`ed into a single graph. Thus lines 6 through 8 define the rook's graph `y@r` and the bishop's graph `y@b`.
Finally, lines 9 through 11 choose the elements of `{b, k, n, r}` that yield the shortest path between the two target vertices. `FindShortestPath` will throw an error and return unevaluated if a target vertex doesn't appear in the graph (which will happen if no edges emanate from it), so we use `h@__ -> 0` to return `0` in those cases instead. And the lack of a path between valid vertices returns a list of length `0`, so `Min[z~Complement~{0}]` calculates the length of the smallest path that actually exists, ignoring the bad cases above.
] |
[Question]
[
>
> **Defenestration** is the act of throwing someone or something out of a window.
>
> —[Wikipedia](https://en.wikipedia.org/wiki/Defenestration)
>
>
>
## Input
The input will consist of two parts:
* A floor plan and a person inside the house/building.
+ `v><^` represents a person, pointing in the direction signified by the arrow. The input will contain exactly one person.
+ `-` and `|` represent walls, and `#` represents a window. is empty space.This portion of the input may be taken as either a single string, or an array/list/etc. of lines. There will never be any trailing or leading spaces, and the input will always be a rectangle.
Example:
```
-----###---
| |
| ^ |
-----------
```
* An integer ≥ 1 signifying how far (in characters) the person travels.
## Output
The output should be
* `1` if the person ends up "inside" a window (i.e. after moving forwards the distance specified in the input, the person is on top of a `#`).
* `2` if the person has been defenestrated (come into contact with a `#` and then continued further on).
* `3` if the person has hit a wall (come into contact with a `-` or `|`. Once hitting the wall, the person stops and does not continue through it).
* `0` if none of the above are true (and all the person has done is travel through empty space).
## Assumptions
All of the following can be assumed to be true:
* The person will never travel "out of bounds" of the input area.
* After being defenestrated, the person will never come into contact with another `#` or a `-`/`|` (so you don't have to worry about if `2` *and* `1` or `3` are both true).
## Test cases
For the following "floor plan":
```
-----
| |
|###|
| |
| ^ |
```
```
In Out
1 0
2 1
3 2
```
For this floor plan:
```
> | # |
```
```
In Out
1 0
2-99 3 * that is, any input 2-99 outputs 3
```
For this floor plan:
```
||####|#|#|##|<
```
```
In Out
any 3
```
Final test case:
```
|v|
|#|
| |
| |
| |
| |
```
```
In Out
1 1
2-5 2
```
[Answer]
# JavaScript (ES6), ~~147~~ 146 bytes
```
(p,n)=>eval('l=p.search`\n`+1;m=p.match`[<>v^]`;for(r=d=i=0;i++<n&r<3;r-1?0:d=2)r=(c=p[m.index+i*({v:l,"<":-1,">":1}[m]||-l)])>"#"?3:c>" ";+r||d')
```
*Saved 1 byte thanks to [@NinjaBearMonkey](https://codegolf.stackexchange.com/users/29750/ninjabearmonkey)!*
## Explanation
Takes a floorplan as a string and the number of moves. Returns a number.
```
(p,n)=> // p = floor plan as string, n = number of moves
eval(` // use eval to enable for loop without {} or return
l=p.search\`\n\`+1; // l = line length
m=p.match\`[<>v^]\`; // m = the position and orientation of the person
for(
r= // r = result at the current step
d= // d = 2 if the person has been defenestrated
i=0; // i = current step
i++<n&r<3; // for each step while the person has not hit a wall
r-1?0:d=2 // set d to 2 once the person enters the window
)
r=( // r = 0 if on " ", 1 if on "#" or 3 if on "|" or "-"
c=p[m.index+i* // c = character after current step
({v:l,"<":-1,">":1}[m]||-l) // get the index offset of each step
]
)>"#"?3:c>" ";
+r||d // return the result of the current step or d
`)
```
## Test
```
var solution = (p,n)=>eval('l=p.search`\n`+1;m=p.match`[<>v^]`;for(r=d=i=0;i++<n&r<3;r-1?0:d=2)r=(c=p[m.index+i*({v:l,"<":-1,">":1}[m]||-l)])>"#"?3:c>" ";+r||d')
```
```
<textarea id="floorplan" rows="6" cols="30">-----
| |
|###|
| |
| ^ |</textarea><br />
Moves = <input type="text" id="moves" value="3" />
<button onclick="result.textContent=solution(floorplan.value,moves.value)">Go</button>
<pre id="result"></pre>
```
] |
[Question]
[
# The Challenge
Given a valid regex, output a regex that that matches the same set of strings, but reversed.
# The Task
This challenge uses the most basic regex operations: `^`, `$`, `?`, `+`, `*`, `[]`, `{}`, `|`. There's no such thing as capture groups or any of that complicated stuff. Special characters can be escaped.
# Sample Input/Output
**Note: Invalid input will never be given, and there are generally multiple possible answers for a given input!**
```
Input | Sample Output
-----------|-------------
abc | cba
tuv? | v?ut
a(b|c) | (c|b)a
1[23] | [23]1
a([bc]|cd) | (dc|[bc])a
^a[^bc]d$ | ^d[^bc]a$
x[yz]{1,2} | [yz]{1,2}x
p{2} | p{2}
q{7,} | q{7,}
\[c[de] | [de]c\[
ab[c | <output undefined>
a(?bc) | <output undefined>
a[]]bc | <output undefined>
```
# Demo
[Working demo](http://embed.plnkr.co/k0xr5Y8H1eiUYZF4Xjlc/) that demonstrates correct inputs/outputs. This has some additional logic for validating inputs that isn't necessary in a real answer. Consider invalid inputs to be undefined behavior.
**Specifics**
For simplicity, all special characters either have their special meaning or are escaped; that is, `[[]` isn't a character range for `[`. Length ranges come from standard POSIX EREs; that is, `{n}`, `{n,}`, and `{n,m}` are supported. The character ranges `[]` and `[^]` are supported. Because of these rules, and since no invalid input is given, you really need only copy the contents of these directly to the output. Lastly, greediness doesn't matter, i.e. it doesn't matter if the reversed regex finds a *different* match first, it just needs to find a match for the same set of strings.
# Scoring
Smallest program in bytes (barring cheating such as network requests) wins. Program can either use real IO or simply define a function.
[Answer]
# [Retina](https://github.com/mbuettner/retina), ~~136~~ ~~114~~ 110 bytes
Yo dawg, I heard you like regex...
```
^
;
(T`^$`$^`;.
(.*);(\[(\\.|[^]])*]|\\.|.)([*+?]|{\d+(,|,\d+)?})?
$2$4!$1;
^\(!
)
^\)(.*)!(.+?)
($2$1
;$|!
<empty>
```
Where `<empty>` represents an empty trailing line. Run the code from a single file with the `-s` flag.
...when you wanna reverse regex you should use regex. When you wanna use regex you should use a regex-based programming language.
This code assumes that the input contains neither `;` nor `!` nor spaces. While I agree that that's a pretty strong and potentially invalid assumption, you could replace those three in the code with any three unprintable characters (like null bytes, bell character, `<DEL>` you name it), and it wouldn't affect the code size or functionality at all.
I'll add an explanation when I'm done golfing.
[Answer]
# JavaScript ES6, 574 bytes
I can probably remove a few `var` statements.
```
R=e=>{for(var s=0,c=[],h=/(\?|\+|\{\d*,*\d*\}|\*)(\?*)/,t=0;t<e.length;t++)switch(s){case 0:switch(e[t]){case"\\":t++,c.push("\\"+e[t]);break;case"[":j=t,s=1;break;case"(":k=t,s=2;break;default:var l=e.search(h,t);(l>=t+1||0>l)&&c.push(l==t+1?e[t]+e.slice(t,e.length).match(h)[0]:e[t])}break;case 1:"\\"==e[t]?t++:"]"==e[t]&&(c.push(e.slice(j,t+1)+(e.search(h,t)==t+1?e.slice(t,e.length).match(h)[0]:"")),s=0);break;case 2:"\\"==e[t]?t++:")"==e[t]&&(a=R(e.slice(k+1,t)),c.push("("+a+")"),s=0)}c.reverse(),r=c;var i=c.length-1;return"^"==c[i]&&(r[i]="$"),"$"==c[0]&&(r[0]="^"),r.join``}}
```
## JS ES6, untested, 559 bytes
Will test at home.
```
R=e=>{for(s=0,c=[],h=/(\?|\+|\{\d*,*\d*\}|\*)(\?*)/,t=0;t<e.length;t++)switch(s){case 0:switch(e[t]){case"\\":t++,c.push`\\${e[t]}`;break;case"[":j=t,s=1;break;case"(":k=t,s=2;break;default:l=e.search(h,t);(l>=t+1||0>l)&&c.push(l==t+1?e[t]+e.slice(t,e.length).match(h)[0]:e[t])}break;case 1:"\\"==e[t]?t++:"]"==e[t]&&(c.push(e.slice(j,t+1)+(e.search(h,t)==t+1?e.slice(t,e.length).match(h)[0]:"")),s=0);break;case 2:"\\"==e[t]?t++:")"==e[t]&&(a=R(e.slice(k+1,t)),c.push`(${a})`,s=0)}c.reverse(),r=c;i=c.length-1;return"^"==c[i]&&(r[i]="$"),"$"==c[0]&&(r[0]="^"),r.join``}}
```
# JavaScript ES5, ungolfed, 961 bytes
```
function revRegex(str){
var mode = 0;
var oS = [];
var post = /(\?|\+|\{\d*,*\d*\}|\*)(\?*)/;
for(var i=0;i<str.length;i++){
switch(mode){
case 0: switch(str[i]){
case "\\": i++; oS.push("\\"+str[i]); break;
case "[": j=i; mode = 1; break;
case "(": k=i; mode = 2; break;
default:
var pLoc = str.search(post,i);
if(pLoc>=i+1||pLoc<0){ // current is not pLoc
if(pLoc==i+1){
oS.push(str[i] + str.slice(i,str.length).match(post)[0]);
} else {
oS.push(str[i]);
}
}
}; break;
case 1: if(str[i]=="\\") i++; else if(str[i]=="]"){oS.push
(str.slice(j,i+1)+(str.search(post,i)==i+1?str.slice
(i,str.length).match(post)[0]:""));mode = 0}; break;
case 2: if(str[i]=="\\") i++; else if(str[i]==")")
{a=revRegex(str.slice(k+1,i));oS.push("("+a+")");mode =
0};break;
}
}
oS.reverse();
r=oS;
var l=oS.length-1;
if(oS[l]=="^") r[l]="$";
if(oS[0]=="$") r[0]="^";
return r.join("");
}
```
[Answer]
# JavaScript ES6, 343 bytes
```
t=r=>(u="substr",T="(?:[+?*]|{\\d+(?:,\\d*)?})?)([^]*)",(c=r[0])=="(")?([n,s]=v(r[u](1)),[_,q,s]=s.match("^(\\)"+T),["("+n+q,s]):c==")"||c==null?["",r]:c=="^"?["^",r[u](1)]:c=="$"?["^",r[u](1)]:r.match("^("+/(?:\[(?:[^\]\\]|\\[^])*\]|[^[\\]|\\[^])/.source+T).slice(1);(v=r=>{var o="";do{[n,r]=t(r);o=n+o;}while(n&&r);return[o,r]})(prompt())[0]
```
Original code (the functions, but without `prompt`):
```
function reverse(regex) {
var out = "";
do {
// console.log("calling term");
var [node, regex] = term(regex);
// console.log("reverse: " + [node, regex]);
out = node + out;
} while (node && regex);
return [out, regex];
}
function term(regex) {
switch (regex[0]) {
case "(":
// console.log("calling reverse");
var [node, sequel] = reverse(regex.substr(1));
// console.log("term: " + regex + " / " + [node, sequel]);
var [_, quantifier, sequel] = sequel.match(/^(\)(?:[+?*]|{\d+(?:,\d*)?})?)([^]*)/);
return ["(" + node + quantifier, sequel];
case ")":
case void 0:
return ["", regex];
case "^":
return ["$", regex.substr(1)];
case "$":
return ["^", regex.substr(1)];
default:
return regex.match(/^((?:\[(?:[^\]\\]|\\[^])*\]|[^[\\]|\\[^])(?:[+?*]|{\d+(?:,\d+)?})?)([^]*)/).slice(1);
}
}
reverse("^\\(([The(){}*\\] ]{2,3}world\\\\(begin(ner|ning)?|ends*)+|Con\\|ti\\*n\\)ue...[^%\\[\\]()\\\\])$")[0]
```
The code is implemented as a recursive top-down parser, so it may cause stack overflow on deeply nested input.
The code may cause infinite loop in invalid cases, since I don't test them, taking advantage of the "undefined behavior" clause.
[Answer]
# Python 3, 144 bytes
(This one *does not support qualifiers on a group* like `(a)+(b)*(cde)?`.)
```
import re;f=lambda x:''.join({e:e,'^':'$','$':'^','(':')',')':'('}[e]for e in re.findall(r'(?:\\.|\[(?:\\?.)+?\]|.)(?:[?+*]|\{.+?\})?',x)[::-1])
```
Test cases:
```
test_cases = [
# Provided test cases
r'abc',
r'tuv?',
r'a(b|c)',
r'1[23]',
r'a([bc]|cd)',
r'^a[^bc]d$',
r'x[yz]{1,2}',
r'p{2}',
r'q{7,}',
r'\[c[de]',
# Pathological cases
r'a{3}b',
r'(a)?(b)+', # <-- currently failing!
r'[\[]{5}[^\]]{6}',
r'[\[]\]{7}',
r'[\[\]]{8,9}',
r'\(\)\^\$',
# Undefined cases
r'ab[c',
r'a(?bc)',
r'a[]]bc',
]
for t in test_cases:
print(t, '->', f(t))
```
Result:
```
abc -> cba
tuv? -> v?ut
a(b|c) -> (c|b)a
1[23] -> [23]1
a([bc]|cd) -> (dc|[bc])a
^a[^bc]d$ -> ^d[^bc]a$
x[yz]{1,2} -> [yz]{1,2}x
p{2} -> p{2}
q{7,} -> q{7,}
\[c[de] -> [de]c\[
a{3}b -> ba{3}
(a)?(b)+ -> )+b))?a) # <-- note: wrong
[\[]{5}[^\]]{6} -> [^\]]{6}[\[]{5}
[\[]\]{7} -> \]{7}[\[]
[\[\]]{8,9} -> [\[\]]{8,9}
\(\)\^\$ -> \$\^\)\(
ab[c -> c[ba
a(?bc) -> (cb(?a
a[]]bc -> cb[]]a
```
] |
[Question]
[
*(inspired by [Helka's response](http://chat.stackexchange.com/transcript/message/36343516#36343516) to my random pairing of "chess" and "Fibonacci" tags in chat)*
---
### Fibonacci
The [Fibonacci numbers](https://en.wikipedia.org/wiki/Fibonacci_number) are one of the more well-known sequences in mathematics, where each number is composed by adding the two previous numbers together. Below is a definition of the zero-indexed sequence:
```
f(0) = 0
f(1) = 1
f(n) = f(n-1) + f(n-2)
```
This results in the sequence `0, 1, 1, 2, 3, 5, 8, 13, 21, ...` ([OEIS link](http://oeis.org/A000045)). In this challenge, we'll be focusing on only the strictly-positive values (so `1, 1, 2, 3, ...`), and you can choose zero-indexing or one-indexing, but please state which in your submission.
The Fibonacci numbers can be used for a tiling of the plane, by using squares that are successive `f(n)` in size, and aligning their edges together. The tiling is done in a counter-clockwise fashion, by placing squares in the pattern "right-up-left-down" from the current square. An example of this partial tiling for `f(8)=21`, with the starting square highlighted in blue, is as follows:
[](https://i.stack.imgur.com/cbkJv.png)
You can see the `f(1)=1` as the starting square (highlighted in blue), the `f(2)=1` square placed to the *right* of it, the `f(3)=2` square placed *up* from there, the `f(4)=3` square placed *left* and so on. The next square would be `f(9)=21+13=34` and would be placed to the bottom. This is the partial tiling method we'll be using in this challenge.
---
### The Queens
In the game of [chess](https://en.wikipedia.org/wiki/Chess), the most powerful piece is the [queen](https://en.wikipedia.org/wiki/Queen_(chess)) because it can move any number of spaces horizontally, vertically, or diagonally. In the below board diagram, the squares with a black circle show where the queen can move:
[](https://i.stack.imgur.com/k1qsT.png)
We'll define the term **coverage** as
>
> The percentage of squares that the queen can move to versus the total number of squares, given the queen's particular position on an empty board, and including the queen's own starting position.
>
>
>
For the example moves above, the queen's coverage is `28/64 = 43.75%`. If the queen was in the upper-right `h8` square, the coverage would be `22/64 = 34.375%`. If the queen was in `e7`, the coverage would be `24/64 = 37.5%`.
---
### The Challenge
We're going to use the Fibonacci tiling demonstrated above as our chess board for this challenge. You'll be given two positive integers as input, `n` and `x`:
* The `n` represents how large the tiling is. The example tiling above, with the `21` square on the left, is a board of size `n = 8` since `f(8) = 21` (when zero-indexed).
* The `x` represents which of the Fibonacci squares is used for the queen(s) placement, for calculating the coverage. The queens are placed one-at-a-time on each square in that particular Fibonacci square tile, and the total coverage is the summation of the individual (unique) coverage.
For example, here is an image of `n = 8` (the same tiling as above) and `x = 4` (corresponding to the `f(4) = 3` square, shaded blue). By placing a queen one-at-a-time into each of those nine blue squares, the queens can (combined) cover every square that's shaded orange. The total coverage in this example is therefore `309/714 = 43.28%`.
[](https://i.stack.imgur.com/vfdWB.png)
Quite obviously, any time that `n = x`, the coverage is going to be `100%` (for example, with `n=8` and `x=8`, you can see that every square on the entire board is going to be covered at least once). Conversely, with a suitably large `n` and `x=1` or `x=2`, the coverage is going to approach (but never reach) `0%` (for example, with `n=8` and `x=1`, the coverage is a paltry `88/714 = 12.32%`).
Given two such input numbers, you must output the coverage percentage, accurate to two decimal places. Please specify how your code handles rounding.
---
### Rules
* The input and output can be given [in any convenient format](http://meta.codegolf.stackexchange.com/q/2447/42963), but must be accurate to two decimal places. Please specify how your code handles rounding.
* Assume no other pieces are on the board or otherwise interfere with the moves.
* 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
```
n = 8, x = 4
43.28
n = 8, x = 8
100 or 100.00
n = 8, x = 1
12.32
n = 4, x = 1
66.67
n = 4, x = 2
60 or 60.00
n = 5, x = 3
75 or 75.00
n = 5, x = 1
47.5 or 47.50
```
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 61 bytes [SBCS](https://github.com/abrudz/SBCS)
```
{2⍕100×(+/÷≢)∨⌿⊃∊⍤1⍥{⍉↑(⊢,+/,-/)¨⍸⍵}/1 0⌈{⌽⍉⍺,⍣(≢⍵)⍪⍵}/⌽⍺=⍳⍵}
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=HYyxCoMwGIRfxc0EI3/S3ScTp0KJITd0KN21BXEtYhFEqG9yT9LodHffHZfXF@LhrN2fqpB9Zttp@oFxY7jSB@LliLci2mR5uyuGzhRiStG/4UD4anGZZfQ143ruFkP0Kl0RkybGJI2c5VIRnyPmfw&c=HYyxCsIwAAV/xTGhkSTufllwEiQNeYODuFeF4iqiFESwf3JfYtvxuOPSBp1iCOPZNH580XaW3FO/lD25oGtEt4RaDkdD6Vzj3drbX4/e6LnzcRWoOVE/c6TBoYuZPpO06L40ixy26DHjHw&f=M1FIU7DgMgSTFnC2CZcRmDQGkqZgEVMA&i=AwA&r=tryapl&l=apl-dyalog&m=train&n=f)
A pretty nice challenge for APL. This is an infix function that takes `x` on its left and `n` on its right, and returns the string representation of the rounded percentage. A full program would be 59 bytes (though I don't like using that I/O format because writing tests is cumbersome):
```
2⍕100×(+/÷≢)∨⌿⊃∊⍤1⍥{⍉↑(⊢,+/,-/)¨⍸⍵}/1 0⌈{⌽⍉⍺,⍣(≢⍵)⍪⍵}/⌽⎕=⍳⎕
```
### How it works
Constructs a boolean matrix representing the grid in question where 1 means a queen, and counts all the cells that share their row, column, diagonal, or anti-diagonal with some 1 cell.
```
{⌽⍉⍺,⍣(≢⍵)⍪⍵}/⌽⍺=⍳⍵ Part 1: construct the matrix; ⍺←x, ⍵←n
⌽⍺=⍳⍵ A boolean vector of length n with x-th from the end
marked as 1
{ }/ Reduce from right to left:
⍺,⍣(≢⍵)⍪⍵ Attach a square filled with ⍺ on the left of current matrix ⍵
⌽⍉ Rotate clockwise once
Reduction gives an enclosed matrix
∊⍤1⍥{⍉↑(⊢,+/,-/)¨⍸⍵}/1 0⌈ Part 2: Find possible Queen moves
1 0⌈ Get an all-ones matrix and the original matrix
⍥{ }/ Apply to each matrix:
⍸⍵ Get all coordinates of ones
(⊢,+/,-/)¨ For each coord [r, c], get [r, c, r+c, r-c]
(rownum, colnum, anti-diag-num, diag-num)
⍉↑ Matrixify and transpose
∊⍤1 For each row, convert each number on its left side as 1 if
it appears on the right on the same row
The result is a 4-row matrix with each column representing a cell,
where a 1 means that cell is reachable by moving in specific direction
2⍕100×(+/÷≢)∨⌿⊃ Part 3: Calculate average
⊃ Disclose the enclosed matrix
∨⌿ Boolean OR of each column
(+/÷≢) Average (reachable cells ÷ all cells)
2⍕100× Percentage rounded to 2 decimal places
```
[Answer]
# VB.NET, (.NET 4.5), ~~1238~~ 1229 bytes
*-9 bytes thanks to @totallyhuman*
```
Function A(n,x)
Dim g=New List(Of List(Of Long))
g.Add(New List(Of Long))
g(0).Add(1)
For i=2To n
Dim b=1
If i>2Then
Dim w=0,y=1
b=w+y
For j=3To i
w=y
y=b
b=w+y
Next
End If
Select Case i Mod 4
Case 1
For j=1To b
Dim l=New List(Of Long)
For k=1To b
l.Add(i)
Next
g.Add(l)
Next
Case 2
For Each r In g
For j=1To b
r.Add(i)
Next
Next
Case 3
For j=1To b
g.Insert(0,New List(Of Long))
For k=1To b
g(0).Add(i)
Next
Next
Case 0
For Each r In g
For j=1To b
r.Insert(0,i)
Next
Next
End Select
Next
For i=0To g.Count-1
Dim c=g(i)
For j=0To c.Count-1
Dim e=c(j)
If e=x Then
For k=1To Math.Max(g.Count,g(0).Count)
If j-k>=0AndAlso c(j-k)<>x Then c(j-k)=0
If i-k>=0AndAlso g(i-k)(j)<>x Then g(i-k)(j)=0
If j+k<c.Count AndAlso c(j+k)<>x Then c(j+k)=0
If i+k<g.Count AndAlso g(i+k)(j)<>x Then g(i+k)(j)=0
If i-k>=0AndAlso j-k>=0AndAlso g(i-k)(j-k)<>x Then g(i-k)(j-k)=0
If i-k>=0AndAlso j+k<c.Count AndAlso g(i-k)(j+k)<>x Then g(i-k)(j+k)=0
If i+k<g.Count AndAlso j-k>=0AndAlso g(i+k)(j-k)<>x Then g(i+k)(j-k)=0
If i+k<g.Count AndAlso j+k<c.Count AndAlso g(i+k)(j+k)<>x Then g(i+k)(j+k)=0
Next
End If
Next
Next
Dim hits=0
For Each r In g
For Each c In r
If c=x Or c=0Then hits+=1
Next
Next
Return Math.Round(hits*100/(g.Count*g(0).Count),2)
End Function
```
Simulation of the problem statement. I start by creating the grid, looping through each new fibonacci number to increase the square size. I store the index in each cell, so that it's easy to find where the queens will go in the next step.
Then, I find every cell that should have a queen in it, and mark each threatened square with a zero. I skip the cells where the queens are so that I don't have to worry about backtracking.
At the end, I count up the cells that are cleared, and the cells with queens, and then divide it by the total number of spaces. Multiply by 100 to get the percent, and round to the nearest two decimal places.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~524~~ 499 bytes
```
def Q(n,x):
global w,h,f;f,R,L=0,range,len
for d in R(n):s=x-1==d;f=f or[[s]];w=L(f[0]);W,H=R(w),R(L(f));exec"for j in "+("W:f.append([s]*w)","f:\n\tfor k in H:j.append(s)","W:f.insert(0,[s]*w)","f:\n\tfor k in H:j.insert(0,s)","f:0")[d%4-(d==0)]
w,h=L(f[0]),L(f);l=0,1,-1
for Y in R(h):
for X in R(w):exec("""def F(u,v,x,y):
while(u==v==0)==0<=x<w!=0<=y<h:f[y][x]=1+(f[y][x]!=1);x+=u;y+=v
for s in l:
for t in l:F(s,t,X,Y)""","")[f[Y][X]!=1]
q=w*h;return(q-sum(j.count(0)for j in f))*100./q
```
[Try it online!](https://tio.run/##fVJNc@IwDD2XX@F6hhkZBE1YdqYTo2unh17KpTAhB7axG9isA/kgya@nFml73IOfLfnJ0pN16uuscIvrNTVWvILDTkUj8ZEXf/a5aDFDqy2u8YUCLPfuw2Bu3EjYohSpODixBqeiirpZSJRqS1YUZRxXSaJbegEbB4nSb/hMa2gVrsG7lNKmM@@SnzjyE3IK8i2y8/3pZFwKPnjSKonSRju3q5n2l2nP0fGbUvE1hxxcZcoaAvxf0A@pGgiBVHE6Xs4gJQpUMmKV37UiF6hzLzbEWTjo3A46M9@XO7Y3g92qiHWAlJJb9wQNXrDDntvXZofcQEN04RR@rahbtfe896sssnGfxF1C4RS@jvcUKt1NqdH9lC4jTlNxmjwaaqgH4wkqrHGDW@WzovRCbLxN4g3HeyFnaieZLk3dlA7Os6r5B8f5e9E4r1799Nv/wCQMgvnD@co@/@PeC/CIS4UeH28Yelx@4cLjb/x1w1CxvlN5cLV0gsQ4RdHd9p0bzxd25@SYhwiHUVLXTw "Python 2 – Try It Online")
Defining a function that takes in both the tiling size `n` and the queen's fibonacci square number `x`. The ouput percentage is porperly rounded to two decimal places (in the footer, where all output is taking place).
`f` is a two-dimensional array containing the board information being initiated to `0`. Then, the fibonacci chess board is calculated and populated with queens where queens shall be. Those queens are then moved to every place they can be moved; all positions are counted and printed as a percentage of the entire board.
[Answer]
# Mathematica 11.1, 336 bytes, 1-based
```
R=Rectangle[#,+##]&;f=Fibonacci;o=Join@@Outer[##,1]&;r=RegionUnion;s=RegionMeasure;p[1]={0,0};p[i_]:=p[i-1]+{{-f@i,-f[i-2]},{0,-f@i},{f[i-1],0},{f[i-1]-f@i,f[i-1]}}[[i~Mod~4+1]];t[i_]:=r[R[p@#,f@#]&/@Range@i];k[n_,x_]:=Round[100s@RegionIntersection[r[R[#,f@x]&/@((#+p@x)&/@o[1##&,o[List,{-1,0,1},{-1,0,1}],Range[2f@n]])],t@i]/s@t@i,.01]
```
Usage: `k[n, x]`. Pay attention that the function is 1-based. Rounding is achieved by `Round[100x,0.01]`
Basically, `p[i]` is a function of determining position of each square. And area is calculated by upper-level functions like `RegionIntersection`, `RegionUnion`, `RegionMeasure`
[](https://i.stack.imgur.com/LHySDm.png)
] |
[Question]
[
Write a self-contained program which when given a polynomial and a bound will find all real roots of that polynomial to an absolute error not exceeding the bound.
### Constraints
I know that Mathematica and probably some other languages have a one-symbol solution, and that's boring, so you should stick to primitive operations (addition, subtraction, multiplication, division).
There is certain flexibility on the input and output formats. You may take input via stdin or command-line arguments in any reasonable format. You may allow floating point or require that some representation of rational numbers be used. You may take the bound or the reciprocal of the bound, and if you're using floating point you may assume that the bound will not be less than 2 ulp. The polynomial should be expressed as a list of monomial coefficients, but it may be big- or little-endian.
You must be able to justify why your program will always work (modulo numerical issues), although it's not necessary to supply full proofs inline.
The program must handle polynomials with repeated roots.
### Example
```
x^2 - 2 = 0 (error bound 0.01)
```
Input could be e.g.
```
-2 0 1 0.01
100 1 0 -2
1/100 ; x^2-2
```
Output could be e.g.
```
-1.41 1.42
```
but not
```
-1.40 1.40
```
as that has absolute errors of about 0.014...
### Test cases
Simple:
```
x^2 - 2 = 0 (error bound 0.01)
x^4 + 0.81 x^2 - 0.47 x + 0.06 (error bound 10^-6)
```
Multiple root:
```
x^4 - 8 x^3 + 18 x^2 - 27 (error bound 10^-6)
```
Wilkinson's polynomial:
```
x^20 - 210 x^19 + 20615 x^18 - 1256850 x^17 + 53327946 x^16 -1672280820 x^15 +
40171771630 x^14 - 756111184500 x^13 + 11310276995381 x^12 - 135585182899530 x^11 +
1307535010540395 x^10 - 10142299865511450 x^9 + 63030812099294896 x^8 -
311333643161390640 x^7 + 1206647803780373360 x^6 -3599979517947607200 x^5 +
8037811822645051776 x^4 - 12870931245150988800 x^3 + 13803759753640704000 x^2 -
8752948036761600000 x + 2432902008176640000 (error bound 2^-32)
```
---
*NB This question was in the [Sandbox](http://meta.codegolf.stackexchange.com/questions/530/proposed-questions-sandbox-mk-iv) for approximately 3 months. If you think it needed improving before posting, visit the Sandbox and comment on the other proposed questions* before *they are posted on Main.*
[Answer]
### Mathematica, 223
```
r[p_,t_]:=Module[{l},l=Exponent[p[x],x];Re@Select[NestWhile[Table[#[[i]]-p[#[[i]]]/Product[If[i!=j,#[[i]]-#[[j]],1],{j,l}],{i,l}]&,Table[(0.9+0.1*I)^i,{i,l}],2*Max[Table[Abs[#1[[i]]-#2[[i]]],{i,l}]]>t&,2],Abs[Im[#]]<t^.5&]]
```
This solution implements the Durand–Kerner method for solving polynomials. Note that this is not a complete solution (as will be shown below) because I cannot yet handle Wilkinson's Polynomial to the specified precision. First an explanation of what I'm doing:

`#[[i]]-p[#[[i]]]/Product[If[i!=j,#[[i]]-#[[j]],1],{j,l}]&`:
Thus function computes for each index `i` the next Durand-Kerner approximation. Then this line is encapsulated in a Table and applied using a NestWhile to the input points generated by `Table[(0.9+0.1*I)^i,{i,l}]`. The condition on the NestWhile is that the max change (over all terms) from one iteration to the next is greater than the specified precision. When all terms have changed less than this, the NestWhile ends and `Re@Select` removes the zeros that do not fall on the real line.
Example output:
```
> p[x_] := x^2 - 2
> r[p, .01]
{1.41421, -1.41421}
> p[x_] := x^4 - 8 x^3 + 18 x^2 - 27
> r[p, 10^-6]
{2.99999, 3., 3.00001, -1.}
> p[x_] := x^20 - 210 x^19 + ... + 2432902008176640000 (Wilkinson's)
> Sort[r[p, 2^-32]]
{1., 2., 3., 4., 5., 6., 7.00001, 7.99994, 9.00018, 10.0002, 11.0007, \
11.9809, 13.0043, 14.0227, 14.9878, 16.0158, 16.9959, 17.9992, \
19.0001, 20.}
```
As you can probably see, when the degree grows higher this method begins to bounce around the correct values, never really homing in completely. If I set the stopping condition of my code to be anything stricter than "from one iteration to next the guesses changed by no more than epsilon" then the algorithm never stops. I guess I should just use Durand-Kerner as input to Newton's method?
] |
[Question]
[
Donald Trump is very impressed with the work of the people on this site. He saw how amazing of a job you did [helping Ben Carson](https://codegolf.stackexchange.com/questions/64316/make-american-maps-great-again), so he even hired you to [build his wall](https://codegolf.stackexchange.com/questions/67452/help-trump-build-the-wall). He thinks you're terrific. Now he needs your help again. While he has successfully built his wall, now he needs the Mexican government to pay for it. He wants to charge $1 million a mile, and he has told them that the U.S.-Mexico border is [1,989 miles long](https://help.cbp.gov/app/answers/detail/a_id/578/~/border-in-miles). However they are not quite sure this number is accurate, so they would like a to-scale visual representation as well. That's where you come in. You are to take this map:
[](https://i.stack.imgur.com/6iHXQ.jpg)
and for every *n* (50 <= n <= 500) miles on the border draw a 25 pixel-length line, perpendicular to the slope of the border at that point. Using the scale on the right-hand side of the map, I've determined that **100 miles ~ 50 pixels**. I've drawn a sample of the first 3 lines for n=60, but these are only approximate:
[](https://i.stack.imgur.com/9WLaE.png)
## Notes:
* The only input is *n*. Output should be the map image, with the lines added, drawn to the screen or saved in a raster image file (you can overwrite the original map file).
* You can save the blank map file with whatever file name you want. It is a JPEG, but you can convert it to another common raster format if you prefer. Also, you can reduce the size of the image by up to 50%, as long as you keep the dimensions proportional, and your lines are still to scale.
* Each line should be perpendicular to the slope of the border at that point. The slope should be calculated starting 50 miles before the point and ending 50 miles after the point.
**Accuracy:**
* The slope of each line can have a margin of error of ±5°
* The spacing between each line can have a margin of error of ±20 miles (10 pixels on the regular map).
[Answer]
# [Python 2](https://docs.python.org/2/) + [numpy](http://www.numpy.org/) + [OpenCV](http://www.opencv.org/), 576 bytes

```
from cv2 import*
from numpy import*
n=input()/4
f="m.png"
i=imread(f)
b=array([0]*3)
y=array([165,195,225])
j=inRange(i,b,b+120)
k=inRange(i,y,y+25)
for x,y in zip(*where(j)):j[x,y]=k[x+3,y]-j[x+1,y]>1
j=j[506:732,152:557]
p=[array([11,9])]
for c in sorted(zip(*where(j)),key=lambda c:c[1]):r=range(p[-1][1]+1,c[1]+1);p+=map(array,zip(map(int,interp(r,*zip(p[-1],c)[::-1])),r))
for x,c in enumerate(p[25:-25:n]):s=-1/true_divide(*p[x*n+50]-p[x*n+25]);k=6/(1+s**2)**.5;line(i,*map(tuple,[(c+[int(k*s)+506,int(k)+152])[::-1],(c-[int(k*s)-506,int(k)-152])[::-1],b]))
imwrite(f,i)
```
This program is almost entirely ungolfed, and there are aspects of it that are somewhat inaccurate at the moment, but at least it works for the most part. Additionally, there is a *little* bit of hardcoding, but it's only for an approximate window enclosing the border and the coordinate of the first pixel on the border (the latter of which I will actually most likely remove later).
The image used by the program is halved in area (i.e. 1120 x 865), and so the length of lines drawn and the distance between lines is smaller.
] |
[Question]
[
I love BATCH, despite its shocking lack of functional commands, despite even due to its lack of non-integer support. Why? Because this works:
```
SET var=SET
%var% i=0
```
This would evaluate to:
```
SET var=SET
SET i=0
```
Fantastic, isn't it? I've used this technique in a [BATCH program](https://codegolf.stackexchange.com/questions/63772/determine-the-color-of-a-chess-square/63980#63980) before, because it saves bytes!
Your challenge, should you accept it, would be to "golf" BATCH programs in this way. You are to decrease the byte size of an input BATCH program by including `SET` statements that would evaluate to portions of the program, and in no other way modify the program. (This disallows, say, renaming a variable name to something shorter. Keep in mind that BATCH, asides from variables, is case insensitive.) Your score is calculated as thus:
```
score = # of characters in your program + 5*(net result bytes in test cases below)
```
I reserve the right to add more test cases, so as to discourage working to optimize the program for the test cases.
For the sake of this challenge, your `SET` statements cannot contain control characters (`|`, `<`, `>`, `%`) or linebreaks. You may not modify the code other than to move pieces of code inside a set statement. (That is, you may not remove unnecessary whitespace, replace `EQU` with `==`, etc.) We will assume that the lines end with `\n`.
## Test cases
Each test case is in a separate code block, and each test case is self-contained, meaning you should golf only assuming what's given within it. (I.e., if you `SET d=SET` in one program, that statement will not be automatically given to any other program). Each example result can be found after each test case. There is a line between test cases.
```
@ECHO OFF
SET increment=10
:loop
IF %increment% EQU 0 GOTO end
ECHO %increment%
SET /A %increment%-=1
GOTO loop
:end
EXIT
```
---
```
@ECHO OFF
SET /p INPUT=Enter input here:
SET R=%1
ECHO Last char of input here: %R:~-1%
```
---
```
@ECHO OFF
SET increment=10
:e
GOTO f
ECHO f
:f
GOTO g
ECHO g
:g
GOTO h
ECHO h
:h
GOTO i
ECHO i
:i
GOTO j
ECHO j
:j
IF 3==4 ( ECHO 4 ) ELSE ( ECHO 5 )
IF 5==3 ( GOTO l ) ELSE ( GOTO k )
:k
ECHO Done.
ECHO BATCH OUT!!
EXIT
:l
GOTO g
```
---
```
ECHO Hello, Hello, Hello, hello, hello, Hello, Hello!, hello, ello!, Lello.
```
---
Example outputs:
```
@ECHO OFF
SET increment=10
:loop
IF %increment% EQU 0 GOTO end
ECHO %increment%
SET /A %increment%-=1
GOTO loop
:end
EXIT
```
(0 bytes saved)
```
@ECHO OFF
SET %i%= input here:
SET /p INPUT=Enter%i%
SET R=%1
ECHO Last char of %i%%R:~-1%
```
(3 bytes gained)
```
@ECHO OFF
SET increment=10
SET g=GOTO
SET e=ECHO
:e
%g%f
%e%f
:f
%g%g
%e%g
:g
%g%h
%e%h
:h
%g%i
%e%i
:i
%g%j
%e%j
:j
IF 3==4 ( %e%4 ) ELSE ( %e%5 )
IF 5==3 ( %g%l ) ELSE ( %g%k )
:k
%e%Done.
%e%BATCH OUT!!
EXIT
:l
%g%g
```
(10 chars saved)
```
SET %h%=ello,
ECHO H%h% H%h% H%h% h%h% h%h% H%h% Hello!, h%h% ello!, Lello.
```
(1 character saved)
[Answer]
# [Java 8, Java 10](http://openjdk.java.net/), ~~3884~~ 799/795 program + 484 output = ~~4368~~ 1283/1279 total
There are two limitations of this code:
* It assumes that variables from A to Z are free. (uppercase)
* It assumes that there are no more than 27 substitutions.
* Oh, and because Scanner doesn't quite cut it, empty input dumps out stacktrace.
But hey - there is a pro!
* Outputs best code. Always.
The code manages to perform better than examples provided by challenge author.
This golfed version has been made by [Kevin](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen).
## Java 8
```
c->{List<String>S=new Stack();HashMap<String,Integer>h=new HashMap(),s=new HashMap();int v=65,l=c.length(),b,e;do{for(b=0,l=c.length(),s.clear();b!=l;b++)for(e=b;++e<=l;)S.add(c.substring(b,e));S.removeIf(t->t.length()<5|t.matches(".*[\n|<%>].*"));S.forEach(t->h.merge(t,1,Integer::sum));S.clear();h.entrySet().removeIf(t->t.getValue()==1);String Y=c;int L=l;char V=(char)v;h.forEach((k,x)->{String i=Y,t;for(int j,I,q;i.contains(k);i=t+"%"+V+"%"+i.substring(j+k.length(),i.length())){for(I=-1,t=i.substring(q=0,j=i.indexOf(k));(I=t.indexOf("%",++I))>=0;q++);if(q%2>0)return;}i="SET "+V+"="+k+"\n"+i;if(i.length()<L)s.put(i,L-i.length());});h.clear();v++;c=s.isEmpty()?c:s.entrySet().stream().max((x,y)->x.getValue()>y.getValue()?1:-1).get().getKey();}while(l>c.length());return c;}
```
**[Try it online!](https://tio.run/##pVRdj9o4FH3Pr/BEGsmeBBfaslJjTLcfzA5aWh6go@12@mCMQwyJwyQOBU357bM3McwwK1WV2hfje3zPvcfHuSzFRrSW89W9ztZ5YdESYlpZndILhp49Q0HnFbI5solCs51VLZlXxnoyFWWJPght7jyEtLGqiIVU6GMdIjSxhTYLFOPDRhIG@N6DpbTCaok@IoM4upet/t1Il7bnEvsTbtQ3oAu5woRdiTL5INaHw3AIbRaq6CdN0uEQk7B8GjOQgzb8j26YcklTZRY2gaxZqNg8v4vzAs94@@lZSWWqRAHc2RlP2SwISJ2n@IwFgeoBRCZUzOdY0rKalY0cDAUJYRNaqCzfqGGMbatvH2r2ut8tzYSViSqxTy@@3JjvvfP@V3rhNyyoPxAyqUkJzVSxUNiGneMdo6issibvKCyhythiN1EWk/@1XCh7LdJKYcJ5BzjO889cNk6MQL1MRIGuOa5/yQZqHbvjVbgl8AYHjuafQ8vqq9fMZTgMb5mmMjcWXrrEK/CW28A/94PrZtUndiyD1aOh@mFLSGP5kLc6oeWnhFt4hSUg2szVdhxDdcIgzz4A0CEMgiEhfd5mt/AmTMf49vx5v00KZavCsL3m/mQwRY0e7gerwL8xIKtOfJTQG5GSriuLdThqnShj@9rWo8GbIGCSl1SXg2xtd5i8llF5ajrIViKDTSa2GG/DHRi3PTG/vzsJXneiVofUAG7WvxVUZPtviU4VTvvyRIW7C5Jsf8/qCVlXsxQm5DAom1zPUQb2H2bpy1ckyJMp0wbuBsPUTI4UxqgCT3alVRk4SWhVqvcq1ZmGGcX@zc2/PqFGbUEXc1Vcal5ZuoZ6NjXYf6vgzVSEnEjuo8B1OVH9I@6PT5oKv0L0Wz588WslLO62f9761Bs4PphD458J8N/EYNGTSzv6b93alTj8/@3v/xy8uxqj8eWlV3@32kgYZfjGeKftRcr7azwdo9hrcmIvih2wcMDCixYOSByQeFHiAO0A7UXaAUsHLL1o6Q0v0QvOXyKMGuwlImgwmgyOcReROqXL@QuAGnb6mNLEK0iJVq7k@9wo6rZv30zfXaHxp@nZmTf4Zzj1ovQg@D8 "Java (JDK) – Try It Online")**
## Java 10
```
c->{var S=new Stack<String>();HashMap<String,Integer>h=new HashMap(),s=new HashMap();int v=65,l=c.length(),b,e;do{for(b=0,l=c.length(),s.clear();b!=l;b++)for(e=b;++e<=l;)S.add(c.substring(b,e));S.removeIf(t->t.length()<5|t.matches(".*[\n|<%>].*"));S.forEach(t->h.merge(t,1,(x,y)->x+y));S.clear();h.entrySet().removeIf(t->t.getValue()==1);var Y=c;int L=l;var V=(char)v;h.forEach((k,x)->{String i=Y,t;for(int j,I,q;i.contains(k);i=t+"%"+V+"%"+i.substring(j+k.length(),i.length())){for(I=-1,t=i.substring(q=0,j=i.indexOf(k));(I=t.indexOf("%",++I))>=0;q++);if(q%2>0)return;}i="SET "+V+"="+k+"\n"+i;if(i.length()<L)s.put(i,L-i.length());});h.clear();v++;c=s.isEmpty()?c:s.entrySet().stream().max((x,y)->x.getValue()>y.getValue()?1:-1).get().getKey();}while(l>c.length());return c;}
```
**[Try it online!](https://tio.run/##pVRdb9s2FH3Xr2AEBCAjibXbesBEU10/nMVYWj/YC9Y1faBpyqIsUY5EuzZS//bsSrITZUBRYHsheA/vPffwUFep2IogXawedL4uSotSiOnG6oxeMPTiBfL6vyJbIJsoNN9bFchiY6wjM1FV6KPQ5t5BSBurylhIhT7VIUJTW2qzRDE@biRhgB8cWCorrJboEzKIowcZRPdbUaIpN@oblAm5GrY1ESbsSlTJR7E@Iv4Y2ixVGSVN8vEQE796HjOQg7b8l4GfcUkzZZY2gay5r9iiuI@LEs957/lZRWWmRAm18zOesbnnkTpP8TnzPDUEiEypWCywpNVmXjVyMBASwqa0VHmxVeMY2yCyj5zDwXdLc2Floirs0osvt@b78Dz6Si/cpgr4R0ImdVFCc1UuFbZ@38c7f0@CaOftm6yTrIQqY8v9VFlM/tVwqeyNyDYKE877hNVufuayMeEahNfxDccyESXZAs@pL175O2h0f3whzT/7ltWXrgtTf@zfMU1lYSy8cYVX4Cq3nnvuejfNqjtGpN7qyUr9uCWkMXvMg75vebfgDvxPAdFmoXaTGNgJgzz7CEAH3/PGhES8x@7gNZiO8d35y6hHSmU3pWEHzd3paIYaPdz1Vp57a0BWnfgkYXhNKrreWKz966CjjB1qS0/mbj2PSV5RXY3ytd1j8kaGVddwkK1EDptc7PDphTrGR/tO8KYfBn1SA7hZ/1DAyA7fEp0pnEWyo6K9C5Ls8MDq2Vhv5hnMxnFEtoVeoBzsP07Rl69IkGfzpQ3cDcaomR0pjFElnu4rq3JwktBNpT6oTOcaphO7t7d/u4QatQNdrGVpU4uNpWvgs5nB7jsFb6ZC1IrkLvLaLh3VP6r98UnD8F8K3cCFr32thMWD3s9bd72B46M5NP6ZAPdtDBY9u3Rb/r9u3VIc/3yHh99G768maHJ56dTfrTYSxhi@Md7vOaFyfp/MJih2mpzYCeMWWLbA0gmXLZC0QOKESQvoFtBOqFsgbYHUCVNnfIlecf4aYdRgrxFBo@vp6BQPEKlTBpy/Aqipzp5SmngFKeGqpfxQGEXb7bu3s/dXaPLn7OzMGf01njlhdhT8Dw "Java (JDK) – Try It Online")**.
# Original version
It's not golfed at all, I just wanted to have some fun, not to suffer. If you, dear reader, would like to golf this answer, please do it.
```
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Predicate;
public class Main {
List<String> substrings = new ArrayList<String>();
HashMap<String, Integer> hm = new HashMap<String, Integer>();
HashMap<String, Integer> scores = new HashMap<String, Integer>();
private int v1 = 65;
public static String rfos(String inputString, String stringToReplace,
String stringToReplaceWith) {
int length = stringToReplace.length();
int inputLength = inputString.length();
int startingIndexofTheStringToReplace = inputString.indexOf(stringToReplace);
if(count(inputString.substring(0, startingIndexofTheStringToReplace), "%") % 2 == 1)
return null;
String finalString = inputString.substring(0, startingIndexofTheStringToReplace) + stringToReplaceWith
+ inputString.substring(startingIndexofTheStringToReplace + length, inputLength);
return finalString;
}
public static int count(String text, String find) {
int index = 0, count = 0, length = find.length();
while( (index = text.indexOf(find, index)) != -1 ) {
index += length; count++;
}
return count;
}
private String process(String program) {
int begin = 0, end, il = program.length();
scores.clear();
while(begin != program.length()) {
for(end = begin + 1; end < program.length() + 1; end++)
substrings.add(program.substring(begin, end));
begin++;
}
substrings.removeIf(new Predicate<String>() {
@Override
public boolean test(String arg0) {
return arg0.length() <= 4 || arg0.contains("\n")
|| arg0.contains("|")
|| arg0.contains("<")
|| arg0.contains("%")
|| arg0.contains(">");
}
});
substrings.forEach(new Consumer<String>() {
@Override
public void accept(String t) {
if(hm.containsKey(t)) {
hm.replace(t, hm.get(t) + 1);
} else {
hm.put(t, 1);
}
}
});
substrings.clear();
hm.entrySet().removeIf(new Predicate<Map.Entry<String, Integer>>() {
@Override
public boolean test(Map.Entry<String, Integer> t) {
return t.getValue() == 1;
}
});
hm.forEach(new BiConsumer<String, Integer>() {
@Override
public void accept(String arg0, Integer arg1) {
String iteration = program;
boolean between = false;
while(iteration.contains(arg0)) {
iteration = rfos(iteration, arg0, "%" + Character.toString((char) v1) + "%");
if(iteration == null)
return;
}
iteration = "SET " + Character.toString((char) v1) + "=" + arg0 + "\n" + iteration;
if(iteration.length() < program.length())
scores.put(iteration, program.length() - iteration.length());
}
});
hm.clear();
v1++;
if(scores.isEmpty())
return program;
else
return scores.entrySet().stream().max((entry1, entry2) -> entry1.getValue() > entry2.getValue() ? 1 : -1).get().getKey();
}
public static void main(String[] args) {
Main processor = new Main();
int genid = 0, before = 0, after = 0;
String currentCode = new Scanner(System.in).useDelimiter("\\Z").next();
System.out.println("Calculating first generation...");
do {
String cc = processor.process(currentCode);
before = currentCode.length();
after = cc.length();
currentCode = cc;
if(before > after) {
System.out.println("Generation " + genid++);
System.out.println(before + " -> " + after);
System.out.println("***\n" + cc + "\n***");
} else {
System.out.println("Generation FAIL " + genid++);
System.out.println(before + " -> " + after);
System.out.println("***\n" + cc + "\n***");
}
} while(before > after);
}
}
```
Example output:
```
SET B=GOTO
SET A=ECHO
@%A%OFF
SET increment=10
:e
%B%f
%A%f
:f
%B%g
%A%g
:g
%B%h
%A%h
:h
%B%i
%A%i
:i
%B%j
%A%j
:j
IF 3==4 ( %A%4 ) ELSE ( %A%5 )
IF 5==3 ( %B%l ) ELSE ( %B%k )
:k
%A%Done.
%A%BATCH OUT!!
EXIT
:l
%B%g
```
[**Try it online!**](https://tio.run/##xVdbb9s2FH6WfgVjoIBUu0Kdpnuwo6xt6rRBU3iYvQu27oGRKVupTBkU5SZY89uzc3hISb6l7dMCNKHOjd@5szd8zZ8VKyFvZp8fHrLlqlCa3QAxqnSWR6@V4ndXWamH/g7vPS8XH/lqD@eAwn7hScKlFGoPJ61korNCRm@y80KW1fJxqe@R@UWJWZZwLYa@v6qu8yxhSc7Lkn3kmWT/@h5CP51olcn5GSur69IcSxYzKb6wOhxOJAiHvmcDYWk9dim1mAt1xhZLq3dI4nH1MimUKL/HhO@tVLYGt1gmNVv3Qeenl0QnJ0vNNfwhZabSogzsOZOrSjujlkZOT4tfxSrniej5HrM/@wX@yPQihOiRHELIhZzrBcDYkoyIYUA7WYPgyim08LSEG2nwRGlgXsqZuC3S6UJMNq/YspGh3DgNtoA0NtMgKSqpg7ZSnfjgee/bN4Y91nnSCdkTdszimPVDsuwpoSslmazy3LpLv20Q00zy3J43Mf/g9ay7LyFN0vCne@CCb4eza5PZayeqDp/1seULcu53Sw9zR4G2Lmtxq3utWMywghxcqguABJGBGBhFOtaVhSqtCnGaXxZZLgIWOG28pi4C1OmR4TBkRzF71mdwLdv68bcJZKwb29uHBKjbba69r082IkZi6EJhu9N6u1JFIsq6BeFzrvgS/fc89PxazGEaGXeFAZzDh5VqdxBY9mhIREkuuKqJFAQyc7SrSjd5aaECsA@2SbLL@kO8kJ3uaNS8bjdEVa8ZjRGfzQIn3xSWMWnwhwaVZwgYMg9jYqA3NpRYFmtxmQY46uoh3UxZAvxqvBZKZTOBH7a8rosCXJeQ57IuLa7mz62Ka0IkNd6cxuyEff1K1KSQGqZ/GXQ@yQ5553m7zK@P8E4f4T15hHfWodhgQO7rjDZhgQyNeLIwUXHrbSMoh6KyLrIZ40kiVk2/uYjAxFssaxAfxF2gXUV4HnAUNX4A3Qlfc6GBj/knqN49E3kpWvIwFFC25juHvANObZYqGBBSq7sJ3BMeqgNYfNEIpXbW3@Nh2CiOw0aa2Nhq0ej27zyvBJjHkT7c6xRgb2eoeabs2dJ0wQ/kC0ulNoBffQfSbW4tFMdXTTMcKAPO62uhvwiB7JRDyohJo6HWbYrRNE1dB23j5rlQE3oWGRQ2VMX5giueAC/SBeEKggRoIbxCsGqw/IfWZBq0rMZmL7rWoLi3CmgDQGcymrLvui1GKcSHH9DOuPecoaG/jaI1EHZnJCGz4xVrvBWBnfH4jO0aDQ8WTasD1n0aib5BZm/LytFype8sCFuTrRRjA7Y4VqvVRtBqgi/hsOS3QWAYfZzF8PcYwJ7Rsd@ucks7btN@Zn02gB0ZmilgfuO4CM1a217wpoSXUEq2gP/@BxNRUkWZ57Vde4WyT1okUhRw6c2FzGa09K4FtJWgM08hsHhEOVv5SaUUoD0vZsKasv@JCCZ3pRZL2PdhVJXircizJSYGRvunvzphJOExUE8eK1tUOoL9LHUug845z5Mq55reJKo0sFxio6jjdGcFNYoDlFAPknuR2@8tnG4HWsdanI2F7jl3k2STjv823U6SmgGVYy2fUbzqSbHHxXe1Q6alTNhhqw8PKVjL0E9YOKa/zBUHFTpPnz6l1oOwmDYEglt07eXxDXQXry@v/g@I2KzMvaA2omqTb6r//uHh1ej8/ZiNLy58nE@ZTGB7QX7i/nN/IPx34@mYpb6RSf1BSoQ5Eeb@YE6EBREW/mBBhIwImT/IiHBDhBt/cONfXrAXcXzCAmZoJ/B6HV1NRu77JQtR5GUcvwCS0c4bEfP9GUQGn8nk20KKiI5vXk/P37Pxb9OjI3/05@XUH@QW8H8 "Java (OpenJDK 8) – Try It Online")
] |
[Question]
[
## The Challenge
Write a program that outputs `Hello World, from line X!`, where `X` is the line number, in the source code, of the actual print statement itself.
## The Rules
* In this context, we want **the *first* line number of the statement which outputs the string** to be displayed to `stdout`
* You should **avoid simply searching through your source code as a string** (either file or quine) to find the line number
* If any **additional whitespace or statements** (which do not interrupt the flow of the code) is added to the source code, it should be **reflected at run-time** (after compiling if applicable)
## Recommendations
If provided by the language, you **may** use exceptions/stack traces to accomplish this goal. Try your best to use code that is **portable** across different systems/implementations, but note that this is **not** a requirement. Using defined variables like `__LINE__`, although allowed by the rules, are discouraged.
## The Winner
* This is a **popularity contest** (ended on June 10, 2014), where the **answer voted highest by the community** will be declared the winner based on the current votes at the time
* When voting, please consider the creativity of someone's answer, how elaborate or **interesting** it is. and the difficulties/constraints of the programming language being used
[Answer]
# Sinclair Basic
```
10 PRINT "Hello world, from line ";PEEK 23621;"!"
```
>
> Hello world, from line 10!
>
>
>
This will work for any line by `PEEK`ing at the address storing the current line number, so the following will work as well:
```
341 PRINT "Hello world, from line ";PEEK 23621;"!"
```
>
> Hello world, from line 341!
>
>
>
[Answer]
# BASIC
I think this does everything that was asked for:
```
10 PRINT "Hello World, from line 10!"
```
[Answer]
# Java
```
public class Hello{
public static void main(String[] args) {
System.out.println("Hello World, from line "+new Exception().getStackTrace()[0].getLineNumber()+"!");
}
}
```
[Answer]
## Perl
```
close STDERR;
open FOOBAR,">",\$_;
print!warn,'Hello World, from line ',/(\d+)\.$/,'!';
```
Not quite as short as using `__LINE__`, but perhaps more interesting.
>
> `warn` is a debugging tool, which issues a statement to `STDERR`, indicating in which file, and on which line the warning was issued... *unless* `STDERR` has been previously closed or is otherwise inaccessible, in which case the warning is issued to the most recently opened file handle - this is undocumented behavior. I'm not sure if it would be better classified as a feature or a bug.
>
>
>
> Here, `STDERR` is closed, and a new file handle identified as `FOOBAR` is opened, and routed to the variable `$_`. This is then parsed to retrieve the line number of the warning, which is embedded in the print statement.
>
>
>
[Answer]
## C++
```
#include <iostream>
#include <utility>
#include <type_traits>
#define __(A,B,C,...) B##C##A
#define _(A,...) __(__VA_ARGS__, A)
template<unsigned...Is> struct v;
template<unsigned I0, unsigned... Is> struct v<I0, Is...>:v<I0-1,I0-1, Is...> {};
template<unsigned...Is> struct v<0,Is...>:std::integral_constant<unsigned, sizeof...(Is)> {};
int main() {
std::cout << "Hello world from line " << v<_(EXTRACT,_(Q,_,E,_,$$main$$,),_(@22,,_,_),_(Z,N,L,I,_,,L),__STACK_TRACE__)>::value << "\n";
}
```
[live example](http://ideone.com/8uQ6Cv)
[Answer]
# Lua
```
print("Hello world, from line "..debug.getinfo(1).currentline.."!")
```
[Answer]
# C
```
#include <stdio.h>
main(){
printf("Hello World, from line %d!", __LINE__);
}
```
[Answer]
## C#
C# 5.0's `[CallerLineNumber]` does the trick:
```
using System;
using System.Linq;
using System.Runtime.CompilerServices;
namespace LineNumberConsole
{
class Program
{
public static void Main()
{
Console.WriteLine("Hello World, from line {0}!", ToRoman(GetLineNumber()));
Console.ReadLine();
}
private static int GetLineNumber([CallerLineNumber] int sourceLineNumber = 0)
{
return sourceLineNumber;
}
private static string ToRoman(int number)
{
// TODO: Copy some source code from http://pastebin.com/w0hm9n5W
// Skipped here for brevity
return number.ToString();
}
}
}
```
## Output
```
Hello World, from line X!
```
[Answer]
## Python
Example (10 lines, 213 characters):
```
import sys
import traceback
lineno = None
while True:
try:
print 'Hello World, from line %d!' % lineno
break
except:
lineno = traceback.tb_lineno(sys.exc_info()[2])
continue
```
[Try online here](http://ideone.com/iX6b2g). Non-flow altering code and whitespace can be added and the program will display the updated line count, and likewise, this code snippet can also be used anywhere in an existing program. Expected output:
```
Hello World, from line 6!
```
---
[Another example (try online here)](http://ideone.com/PzzxVn) to show that it works when code/whitespace is added. Expected output:
```
Down we go...
Gotta catch 'em all.
Down we go...
Hello World, from line 11!
Awesome!
```
[Answer]
**Javascript**
```
function getLine(n) {
try {
to
} catch (dat) {
var stack = dat.stack.split('\n');
for (var i = 0; i < stack.length; i++) {
if (~stack[i].indexOf ('getLine')) break;
}
return dat.stack.split ('\n')[i + ~~n].match (/:(\d+)/)[1] - ~~window.hasOwnProperty ('__commandLineAPI')
}
}
//Line 12
console.log ('Hello World, from line ' + getLine(1) + ' !')
```
*Note: Expressions, evaluated from within the chrome dev console will be wrapped in a `with` statement. Thus we need to decrement the line by one if that's the case*
[Answer]
## Python 3
```
import hashlib
with open(__file__) as f:
line_num = 0
for line in f.readlines():
line = line.rstrip() # make it work with or without newline at the end
line_num += 1
if hashlib.sha256(bytes(line, "UTF-8")).hexdigest()[0:6] == 'cc46f7':
print('Hello world, from line {}!'.format(line_num)) # cc46f7
```
>
> Hello world, from line 8!
>
>
>
This self-reading code contains a self-referencing hash. The SHA256 sum of the last line (with the beginning whitespace and without trailing whitespace) [begins with](http://www.convertstring.com/Hash/SHA256) `cc46f7...`. When it hashes the `print` line, it finds that the hash matches the magic value it's searching for.
[Answer]
GNU COBOL
Well, they said it couldn't be done. Actually, it was I who said it couldn't be done. Now it's done, and an obsolete language feature re-implemented using the method applied.
The question states:
>
> If any additional whitespace or statements (which do not interrupt the
> flow of the code) is added to the source code, it should be reflected
> at run-time (after compiling if applicable).
>
>
>
Any amount of stuff can be inserted prior to the three `DISPLAY`s which cause the start of the output, and anything *after* the `DISPLAY`s would "interrupt the flow of the code", so that's OK.
COBOL used to have a `TRACE` verb (statement) which simply listed source line-numbers as they were executed (no access to the line number in the program). Although of limited use, I've included an implementation of TRACE.
```
ID Division.
Program-ID. HIWHERE.
ENVIRONMENT DIVISION.
configuration section.
source-computer. TinkerToy with debugging mode.
Procedure Division.
Declaratives.
Debug-Declaratives Section.
Use For Debugging on a b
.
Debug-Declaratives-Paragraph.
Display Debug-Line "!"
.
End Declaratives
.
Main-Program Section.
DISPLAY "Perform"
Display "Hello World, from line " no advancing Perform b
display "GO TO"
Display "Hello World, from line " no advancing GO TO a
.
a.
dISPLay "Fall through"
Display "Hello World, from line " no advancing. b.
The-Last-bit-OF-the-PROGRAM.
GOBACK
.
```
The output is
```
Perform
Hello World, from line 18!
GO TO
Hello World, from line 20!
Fall through
Hello World, from line 23!
```
As an exhibition of the power and flexibility of writing the language, this example uses mixed-case, entirely lowercase, and entirely uppercase, all at the same time. It does not matter, as when processed, everything is "folded" to UPPERCASE.
The only standard COBOL way to get at a source line-number in the running program, from the running program, is with a `DEBUGGING` `DECLARATIVE`. Within a `SECTION`, strictly within a paragraph within a `SECTION`, of a such a declarative you have access to the special-register `DEBUG-LINE`. This contains the source line-number of the verb (statement) which caused transfer of control to a particular procedure-name (paragraph or `SECTION`).
So, with `PERFORM`, or `GO TO`, or "fall through" the paragraph in the debugging declaratives `SECTION` is executed.
OK, but `DISPLAY` does not cause transfer of control.
No problem. Put it on the *same line* as the transfer of control.
Problem, since if "any additional whitespace or statements (which do not interrupt the flow of the code) is added to the source code, it should be reflected at run-time (after compiling if applicable)".
So, put it on the same line *but in front of* a transfer of control, split the content of the `DISPLAY` into two pieces (remember, "In this context, we want the first line number of the statement which outputs the string to be displayed") and output the first part prior to the transfer of control, and the second part, from the `DEBUG-LINE`, once inside the debugging procedure.
The final tricky bit is for the "fall through" ("procedures" can be `PERFORM`ed, can be the target of a `GO TO`, or can be entered simply by being the next line along). In this instance, put the `DISPLAY` *on the line which defines the procedure, but in front of the definition*.
The names of the "procedures" (`a` and `b`) have been severely shortened to allow them to fit on the same source-line as the `DISPLAY`. Strictly a COBOL procedure-name should start somewhere from column eight to column 11. However, the syntax is, these days, much more relaxed about that. To the extent that I can define a procedure name on the same line as some code. Even embedded in code. Care, and an occasional full-stop, is required.
In the `PROCEDURE DIVISION` each full-stop shown is required, and no more are.
To compile:
```
cobc -x -g hiwhere.cbl
```
To execute (linux):
```
COB_SET_DEBUG=Y ./hiwhere
```
Finally, the return of TRACE (without READY/RESET).
```
ID Division.
Program-ID. tRacE.
ENVIRONMENT DIVISION.
configuration section.
source-computer. TinkerToy with debugging mode.
Procedure Division.
Declaratives.
Debug-Declaratives Section.
Use For Debugging on a
.
Debug-Declaratives-Paragraph.
Display Debug-Line
.
End Declaratives
.
Main-Program Section.
* Just append "perform a" to a single-line statement.
DISPLAY "1" . perform a
Display "2" . perform a
display "3" . perform a
* Or prepend "perform a." for a multi-line statement, or a
* statement which won't "come back".
perform a. GOBACK
.
a.
CONTINUE
.
```
Output is:
```
1
17
2
18
3
19
20
```
Where 1, 2 and 3 are output from the three DISPLAY statements, and 17, 18, 19 and 20 are the line numbers of the "executable" (non-debugging) lines.
[Answer]
# Java
Using the behavior of Exception's stack trace to get current line. as long as Printstatement isn't mangled into multiple lines or classfile gets mangled it should work
```
public class PrittLnbr
{
public static void main(String[] args)
{
System.out.println("Hello World, from line "+new Error().getStackTrace()[0].toString().split(":")[1]+"!");
}
}
```
[Answer]
**Python**
```
import traceback, inspect
frame = inspect.currentframe()
print("Hello World, from line "+traceback.format_stack(frame)[0].split()[3][:-1]+"!")
```
[Answer]
**Befunge**
Done just for fun.
```
>00g1+:00p"v"\10v
v-*45g00p\g <
#v+1_$10g1vv,,,,<
^<p000p01+<#>,,,^
>" enil morf ,oll"v
@.,,,,,,,,,<^,"He"<
```
Conditional: top left of the code has to be 0 < x < 20 and 0 <= y < 62; and the two first cells have to be empty.
example:
```
v
0
0
0
p
0
1
0
p
>00g1+:00p"v"\10v
v-*45g00p\g <
#v+1_$10g1vv,,,,<
^<p000p01+<#>,,,^
>" enil morf ,oll"v
@.,,,,,,,,,<^,"He"<
```
Would output:
Hello, from line 10
[Answer]
# Perl
```
print 'Hello World, from line '.__LINE__.'!';
```
[Answer]
**Java**
```
public class HelloFrom {
public static void main(String[] args) {
System.out.println("Hello World, from line " + Thread.currentThread().getStackTrace()[1].getLineNumber() + "!");
}
}
```
[Answer]
**Python**
```
import inspect
print ("Hello world from line %d!" % (inspect.getlineno(inspect.currentframe())))
```
**Output**
```
Hello World from line 2!
```
[Answer]
# C
By using a variadic macro, we can make a print function which automatically adds the line number to the end of an arbitrary printf statement, and always prints to stdout.
test.c:
```
#include <stdio.h>
#define printfl(format, ...) fprintf(stdout, format " From line %d\n", ##__VA_ARGS__, __LINE__)
int main() {
printfl("Hello World! I have %d argument(s).", 1);
return 0;
}
```
outputs:
```
% ./test
Hello World! I have 1 argument(s). From line 6
```
Note: I deviated from the pattern to demonstrate that printfl is still a valid variadic function; if you *really* care about the format of the output, you can always change the literals I use.
[Answer]
# Bash
```
#
# some comments to fill some lines...
#
echo "Hello World, from line $LINENO!"
```
## Output
```
Hello World, from line 4!
```
[Answer]
## D
```
void main ()
{
import std.stdio;
writefln("Hello World, from line %d", __LINE__);
}
```
[Answer]
# C or C++, and AWK
lineno.c:
```
// code or comments
// ....
#error Hello World, from line
// other code or comments
```
Usage:
```
gcc lineno.c 2>&1 | awk '{ split($0,a,":"); ; printf("%s %s!\n", gensub(".*#error ","",1), a[2]); exit; }'
```
Output:
Hello, World, from line 3
Notes:
* No user written code searches the file.
* g++ will work on a c++ file.
[Answer]
Kind of boring in Ruby:
```
puts "Hello World, from line #{__LINE__}!"
```
This isn't cheating, right?
[Answer]
## Javascript
One line using stack trace.
```
(function (o) { console.log("Hello World, from line " + (Error.captureStackTrace(o) || o.stack.match(/\d+/)[0] - !!__commandLineAPI) + "!"); })({});
```
[Answer]
# Cobra
```
class Program
def main
print 'Hello World, from line [System.Diagnostics.StackFrame(true).getFileLineNumber]!'
```
[Answer]
# Ruby
```
File.write "hello.rb", "x=2\n"+"x+=1\n"*rand(rand(100))+'puts "Hello World, from line #{x}!"'
system "ruby hello.rb"
File.delete "hello.rb"
```
[Answer]
# PowerShell
## Cheap Move
```
Function LemmeGetDatError() {
"Too busy chuggin along"
"Then all of a sudden, I meet a new programmer"
"And he's all like"
Write-Output "$(Try {"Hello World from"; Throw "error" } Catch {$_.ScriptStackTrace.Split(":")[1]})"
}
LemmeGetDatError
```
[Answer]
# Powershell
```
$l=(Get-PSCallStack | ForEach{$_.Location})[0].split(' ')[-1]; "Hello World, from line $l!"
```
And:
```
try{ I AM ERROR. } catch { $l=$error[0].InvocationInfo.ScriptLineNumber; "Hello World, from line $l!" }
```
Both work like this:
```
PS C:\MyFolder> .\helloworld.ps1
Hello World, from line 1!
```
[Answer]
**Python**
```
import traceback
print 'Hello World, from line %i!' % traceback.extract_stack()[0][1]
```
Short and sweet.
[Answer]
# Perl
Another Perl one:
```
use warnings;
$SIG{__WARN__} = sub { ($line = shift) =~ s/\D//g; };
$x=$x+1; print "Hello World, form line $line!\n";
```
] |
[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]
# [Pyth, Dennis, ≤ 8](https://codegolf.stackexchange.com/a/60342/21487)
```
V./Tp*FN
```
Damn that was fun - the hardest part was figuring out how to do it short enough in Pyth.
### Analysis
The `1234` at the start hints that we're probably dealing with a list of numbers, printed without a separator. Let's try and split the numbers up in a way that makes sense:
```
1 2 3 4 4 6 5 8 8 9 6 12 10 12 7 16 16 18 12 15 16 8 24 20 24 14 27 18 20 9 32 32 36 24 30 32 16 36 21 24 25 10
```
There's a few hints that we're on the right track:
* All numbers have prime factors less than 10
* A lot of numbers are pretty close to their index in the list
However, there are a few peculiarities. The number at index 23 is 24, and is the only case where the number at the index is greater than the index itself. However, the bigger clue is that some numbers are clearly smaller than their neighbours, particularly the 7 at index 15, the 8 at index 22 and the 9 at index 30.
Noting that this forms a 7-8-9 pattern, we can also see that the last number is a 10 at index 42. Given @Dennis' recent question on [abelian groups](https://codegolf.stackexchange.com/questions/60288/counting-abelian-groups-of-a-given-size), a quick check on OEIS reveals that `15, 22, 30, 42` is a subsequence of the [partition numbers](https://oeis.org/A000041). Pyth has a builtin for partitions, which gives us two of eight characters: `./`
But note that the last number is 10, which is suspicious because 10 is a preinitialised variable in Pyth, as `T`. `./T` gives a full list of the 42 partitions of the number 10, which looks like it might come in handy.
Now the printing is done without a separator, so this hints at a use of `p`. Perhaps we loop through each partition, do something to it, then print with `p`? This gives us the following template:
```
V./Tp??N
```
where `V` is a for loop which loops over an iterable, storing each element in the variable `N`.
A quick look at the second last partition `(5, 5)` should make it obvious that we want to take a product. The naive way to reduce a list by multiplication is
```
u*GHd1
```
where `d` is the list in question. However, this is far too long.
Unfortunately, this is where I had to pull out a brute forcer. I haven't kept up with Pyth for a while, so I didn't know many of the newer features. There were only two characters left, which looked entirely doable.
The brute forcer then returned:
```
V./Tp*FN
```
where `*F` is fold by `*` (multiplication). No wonder I didn't find it in my search - I was looking up the keyword "reduce" rather than "fold"!
[Answer]
# [><>, VTCAKAVSMoACE, ≤ 64](https://codegolf.stackexchange.com/a/60365/21487)
```
'9?':?!;1-$:'@'+o'3'*'='%$30.
```
Ironically, not only is this much lower the range limit, it's also portable and works with the [online interpreter](http://fishlanguage.com/playground).
### Analysis
Let's start with the target string:
```
yh[cPWNkz^EKLBiQMuSvI`n\Yw|JVXDUbZmfoRC_xrq{TlpHjGt]OadFAsgeyh[
```
><> pushes chars to the stack with `'` or `"` in string mode, but with 63 chars to print and only 64 bytes to work with, the presence of capital letters (invalid instructions in ><>, for the standard looparound trick) make direct printing impossible. Hence, we must be doing something with the code points.
Converting to code points gives (I'm using Python here):
```
>>> L = [ord(c) for c in "yh[cPWNkz^EKLBiQMuSvI`n\Yw|JVXDUbZmfoRC_xrq{TlpHjGt]OadFAsgeyh["]
>>> L
[121, 104, 91, 99, 80, 87, 78, 107, 122, 94, 69, 75, 76, 66, 105, 81, 77, 117, 83, 118, 73, 96, 110, 92, 89, 119, 124, 74, 86, 88, 68, 85, 98, 90, 109, 102, 111, 82, 67, 95, 120, 114, 113, 123, 84, 108, 112, 72, 106, 71, 116, 93, 79, 97, 100, 70, 65, 115, 103, 101, 121, 104, 91]
```
Note that the last three numbers are the same as the first three. This hints at a possible modulo loop going on.
Let's take a look at how many different elements we have:
```
>>> len(set(L))
60
```
We have 63 elements in `L`, the first three of which coincide with the last three. This means that, aside from this collision, all other elements are unique. Now this hints at something like taking powers modulo a prime number. Indeed, `60 + 1 = 61` is prime, which is a good sign.
Let's try finding the smallest element
```
>>> min(L)
65
```
and use that to scale all the elements down so that the min element is 1:
```
>>> M = [x-64 for x in L]
>>> M
[57, 40, 27, 35, 16, 23, 14, 43, 58, 30, 5, 11, 12, 2, 41, 17, 13, 53, 19, 54, 9, 32, 46, 28, 25, 55, 60, 10, 22, 24, 4, 21, 34, 26, 45, 38, 47, 18, 3, 31, 56, 50, 49, 59, 20, 44, 48, 8, 42, 7, 52, 29, 15, 33, 36, 6, 1, 51, 39, 37, 57, 40, 27]
```
Note how the element after `1` is `51`. If there's some sort of powers/multiplication thing going on, this is a good guess for our multiplier.
Let's give it a shot:
```
>>> (57*51)%61
40
>>> (40*51)%61
27
>>> all((x*51)%61 == y for x,y in zip(M, M[1:]))
True
```
Bingo! We can now backtrack, giving the following code:
```
x = 57
for _ in range(63):
print(chr(x + 64), end="")
x = (x*51)%61
```
which was then translated to ><>
[Answer]
# [Mathematica, alphalpha, ≤ 32](https://codegolf.stackexchange.com/a/60577/21487)
```
GroupOrder[MonsterGroupM[]]
```
I hate to say this, but I just recognised the number on the spot.
[Answer]
# [Pyth, Maltysen, ≤4](https://codegolf.stackexchange.com/a/60405/21487)
```
C.ZG
```
Brute force took so long that I did it faster manually.
### Analysis
`C` (convert string to base 256 int) is the easiest way to generate a large number in Pyth, so it's probably the first character. If we convert from base 256, we get:
```
xÚKLJNIMKÏÈÌÊÎÉÍË/(,*.)-+¯¨¬
```
Hmm... not very illuminating.
Now `G` is the alphabet string `"abc...z"`, which looks like it could be a source for a long string to feed into `C`. Looking through the docs I find:
```
.Z Compresses or decompresses a string.
```
If we're dealing with compression here, it wouldn't be surprising to get all sorts of extended ASCII characters. Trying `C.ZG` then gave the answer.
[Answer]
# [Fourier, Beta Decay, ≤ 32](https://codegolf.stackexchange.com/a/60347/21487)
```
2~x1~y20(xoy~z*x~yz~xq^~q)
```
Or alternatively, in CJam:
```
X0I{_2$+}*]2\f#
```
### Analysis
At the start we can see a lot of powers of 2:
```
2
1
2
2
4
8
32
256
8192
2097152
...
```
If we take the log base 2 of these numbers, we get:
```
1 0 1 1 2 3 5 8 13 21 ...
```
which is the Fibonacci series, starting at `1, 0`.
[Answer]
## [Snails, feersum, ≤2 bytes](https://codegolf.stackexchange.com/a/60474)
```
z
```
This is actually 2 bytes; the character `z` followed by a newline `\n`.
I have no idea how it works or what it's doing, but after testing all possible inputs apart from `~+` and `~,`, this was the only 2-byte program that produced `8` as output.
And it took *ages* to get this result. No wonder it's called "Snails" :-D
---
*Note to self: The next time you fuzz test unknown software, do it inside a VM.*
[Answer]
## [Rust, Liam Noronha, ≤128 bytes](https://codegolf.stackexchange.com/a/60359/3808)
```
fn main(){print!("AACAAEGAAACIIMOAAACAAEGQQQSYYDFAAACAAEGAAACIIMOHHHJHHLNXXXAGGKMAAACAAEGAAACIIMOAAACAAEGQQQSYYDFOOO");}
```
Simply printing the string verbatim is 120 bytes...
[Answer]
# [Macaroni 0.0.2, Doorknob, ≤64](https://codegolf.stackexchange.com/a/60378/32353)
```
set x "................................."print x print x print x
```
[Answer]
# [Python 2, Clear question with examples, <=64](https://codegolf.stackexchange.com/a/60489/11006)
One possible solution:
```
print ''.join([" `{.~{{~||"[int(c)] for c in str(3**4278)])
```
(`9**2139`, `27**1426` and `729**713` also give the same result)
[Answer]
# [CoffeeScript, user2428118, ≤64](https://codegolf.stackexchange.com/a/60819/32353)
```
alert 0+(btoa k.substr -2 for k of document.body.style).join ''
```
(works only on Chrome 46.0.2490.71 as described by the Cop.)
---
The output is obviously a concatenation of short base64-encoded strings due to all the "=". After decoding them, we find a list of 2-character strings like
```
['nt', 'ms', 'lf', 'ne', 'll', 'on', 'ay', 'on', …
```
which does not seem to make sense. But I find some odd items in it, like `nX` and `tY`. After filtering these out we get
```
>>> # Python
>>>
>>> [i for i in tt if not re.match('[a-z]{2}$', i)]
['nX', 'nY', 'tX', 'tY', 'wX', 'wY', 'r', 'nX', 'nY', 'tX', 'tY', 'nX', 'nY', 'nX', 'nY', 'nZ', 'x', 'y']
```
These X and Y seem to indicate the original source code used position properties like `offsetX/Y`. A particularly interesting is the `nZ` item. To check my assumption, I searched for all properties that end with "Z":
```
// CoffeeScript
checked = []
f = (o) ->
if !(o in checked)
for k of o
if /Z$/.test(k)
console.log(o, k)
if o[k] instanceof Object
f o[k]
f window
```
which shows tons of `CSSStyleDeclaration, "webkitTransformOriginZ"`. From this we have a strong indication that the list is built up by the last 2 characters of all the keys of a `style` object, which the test above shows indeed is correct.
[Answer]
# [Python 2, histocrat, ≤16](https://codegolf.stackexchange.com/a/60786/32353)
```
[[[51002**3/6]]]
```
---
The biggest hint is the promise that it won't work in Python 3. [What's changed in Python 3](https://docs.python.org/3.0/whatsnew/3.0.html#integers)? The biggest suspect is that the division operator returns a `float` in Python 3.
So I assume the solution is of the form ⌊αβ/n⌋ = c = 22111101102001, as exponentiation is the only short way to create huge numbers.
If {α, β, n} indeed forms a solution, then (cn)1/β ≈ α should be very close to an integer. Therefore I use the following to try to brute-force the {α, β} for each n:
```
(* Mathematica *)
n=2; Sort[Table[{N[Abs[k - Round@k] /. k -> (22111101102001*n)^(1/b), 12], b}, {b, 2, 50}]]
(* Output: {{0.00262542213622, 7}, ...}
The first number is the "quality" of the solution, lower is better.
the second number is β.
Thus α ≈ (nc)^(1/β) = 89
But (89^7)/2 = 22115667447764, which is still far away from the answer.
*)
```
The actual result quickly comes out when n = 6.
[Answer]
# [MATLAB, StewieGriffin, ≤ 16](https://codegolf.stackexchange.com/a/60425/42295)
```
[36;87]*' |'*5
```
Prints:
```
ans =
5760 22320
13920 53940
```
[Answer]
## [Matlab, Luis Mendo, ≤16](https://codegolf.stackexchange.com/a/60417)
I found it, yay!
```
fix(peaks(9).^2)
```
I didn't know that Octave can do this, too.
[Answer]
# [Mathematica, LegionMammal978, ≤64](https://codegolf.stackexchange.com/a/60385/9288)
```
Print@Nest[Compress,ExampleData[{"Text","ToBeOrNotToBe"}],13]
```
[Answer]
# [Python, spacemanjosh, ≤ 64](https://codegolf.stackexchange.com/a/60659/21487)
```
n=0;d=1;L=[]
exec("L+=[10/(100-n)**.5];n+=d;d+=2;"*10)
print(L)
```
Glorious inverse symbolic calculator. Not well golfed, but hey it fits.
**Edit:** I golfed it.
```
print([10/(100-n*n)**.5for n in range(10)])
```
[Answer]
# [JavaScript ES6, Cᴏɴᴏʀ O'Bʀɪᴇɴ, ≤128 bytes](https://codegolf.stackexchange.com/a/60428/32628)
```
var x=122,s='0037122342526683102122';for(var i=23;i<=505;i+=2)s+=(x+=i);s;
```
I doubt this is exactly right since I didn't need anywhere near 128 bytes, but finding a repeating sequence was fun challenge.
[Answer]
# [Thue, ppperry, <=64](https://codegolf.stackexchange.com/a/60704/6828_)
```
0::=11
1::=22
2::=33
3::=44
4::=55
a::=bbb
b::=000
::=
aaaaaaa
```
Decomposes 2016 into its prime factors, essentially. 62 characters, so my guess is this is similar to what you were going for.
[Answer]
# [Python, DLosc, ≤32](https://codegolf.stackexchange.com/a/60603/7313)
(This solution uses Python 2)
```
a=97
while a<4e31:a^=a*2;print a
```
[Answer]
# [><>, Sp3000, <=8](https://codegolf.stackexchange.com/a/60446/7311)
```
'l(?; o>
```
The instruction pointer wraps around and the following steps happen:
* `'l(?; o>'` pushes the ASCII values of `l(?; o>` to the stack
* `l` pushes the size of the stack on the stack
* `(` compare the top two stack elements: `size of stack` and `ord('>')`
* `?;` stops the program if the stack size was bigger
* `o` output the top element of the stack as character (this will be always `o`)
* `>` sets IP direction, here it is no-op
* we go back to the first step
Output is `oooooooooooo`.
We can get a lot of different outputs by changing `[space]` to something which pushes or pops on the stack and using another valid character instead of `>`, which may also push or pop.
[Answer]
# [JavaScript, ev3commander, ≤ 32](https://codegolf.stackexchange.com/a/61036)
```
console.log(0.1411200080598672)
```
OK, that was easy.
[Answer]
# [CJam, Reto Koradi, ≤ 4](https://codegolf.stackexchange.com/a/60867)
```
HJK#
```
Pushes **17**, then **1920 = 37589973457545958193355601**.
[Try it online.](http://cjam.aditsu.net/#code=HJK%23)
There are only so many things you can do in four bytes. An integer this big had to involve powers or factorials somehow, and a factorial would have trailing zeroes.
[Answer]
# [Lua <= 4, Egor Skriptunoff](https://codegolf.stackexchange.com/a/60514/30688)
A lot of users were getting agitated about this answer in chat, so I must relieve them from their misery. I don't know Lua and wasn't able to test it, but I would be very surprised if this doesn't work.
```
4^~9
```
This would be pretty obvious, but probably no one got it because bitwise operators were only added in version 5.3; ideone.com only has version 5.2.
[Answer]
# [Pyth <= 4, Dennis](https://codegolf.stackexchange.com/a/61047/20080)
```
ljyG
```
That's length of join on newlines of all subsets of the alphabet.
Test run:
```
$ pyth -cd 'ljyG'
==================== 4 chars =====================
ljyG
==================================================
imp_print(Plen(join(subsets(G))))
==================================================
939524095
```
I figured out the number was `2^27 * 7 - 1` which is a strong hint that it's based on `yG`, which is `2^26` elements long. I then guessed it had to be converted to a string and its length printed. However, the only way of doing this I could think of for a while was ``, repr. Then I thought of `j`, which fits perfectly.
[Answer]
# [C, tucuxi, ≤64](https://codegolf.stackexchange.com/a/60528/32353)
```
main(i){for(i=0;i<11000;++i)if(!(i&2*i))printf("1%d",!(i&1));}
```
---
The output are all 0 and 1, but C cannot print binary directly, so it's very likely these are boolean results.
There are more 1 than 0s, so I recorded the positions of 0s (`3, 9, 13, 19, …`), which turns out to be OEIS [A075318](http://oeis.org/A075318). This is not useful though, there isn't a simple formula to determine where a number is in this sequence.
But we note that there are all odd numbers, so perhaps `(x-1)/2 = {1, 4, 6, 9, 12, …}` have more useful information. And this is [A003622](http://oeis.org/A003622).
A003622 can be defined as "positions of 1's in [A003849](http://oeis.org/A003849)", which is exactly what we need to crack here. And A003849 is defined as "[A003714](http://oeis.org/A003714) mod 2", where A003714 are simply all integers that `x & (2*x) == 0`. Thus we have got the solution.
OEIS rox.
[Answer]
# [Dyalog APL, Dennis, ≤4](https://codegolf.stackexchange.com/a/61048/3852)
```
*⍨⍟8
```
Computes ln(8)^ln(8). Would StackExchange stop converting my answers? I'll type a bunch of stuff here so it doesn't get turned into a comment.
[Answer]
# [Pyth, xnor, ≤ 4](https://codegolf.stackexchange.com/a/60350/21487)
```
C`CG
```
`CG` (convert the alphabet string `"abc...z"` from base 256) is the typical Pyth way of generating a really large number. After that it's just stringify and convert from base again.
[Answer]
# [Ruby, Doorknob, ≤64](https://codegolf.stackexchange.com/a/60391/32353)
```
'@@'=~/(.)(.)/
p$~
test 0 rescue p"#$!@@".gsub //,$!.inspect+$/
```
[Answer]
# [Matlab/Octave, Wauzl, ≤16](https://codegolf.stackexchange.com/a/60491/32353)
```
"234"'*"567"
```
Using the same idea as [Tom Carpenter's answer](https://codegolf.stackexchange.com/a/60436/32353)
(If it did not work, try this:)
```
[50;51;52]*'567'
```
[Answer]
# [CoffeeScript, J Atkin, ≤ 16](https://codegolf.stackexchange.com/a/60570/21487)
```
Math.PI*Math.LN2
```
Hooray for the inverse symbolic calculator.
[Answer]
# [PARI/GP, alephalpha, ≤ 4](https://codegolf.stackexchange.com/a/60344)
```
9!-9
```
I don't actually know the language, but that *has to* be the right answer.
] |
[Question]
[
A nice simple one
# Input
Given a boolean array (Or an acceptable alternative), you can assume the array will never be more than 32 elements long.
```
[false, false, true, false, false]
```
# Output
Invert every element of the array and output it.
```
[true, true, false, true, true]
```
# Rules
* You can write a full program or just a function
* Standard loopholes apply
* Shortest code in bytes, per language, wins!
# Test cases
```
Input:
[true, false]
Output:
[false, true]
Input: //Example of acceptable alternative
[0,1,1]
Output:
[1,0,0]
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 1 byte
Code:
```
_
```
Explanation:
```
_ # Logical not
```
[Try it online!](http://05ab1e.tryitonline.net/#code=Xw&input=WzEsIDEsIDAsIDEsIDFd)
[Answer]
# Javascript ES6, 15 bytes
```
a=>a.map(b=>!b)
```
Not much explanation needed I guess
```
f=
a=>a.map(b=>!b)
a.innerHTML = `[true, false, 1, 0] => ${ f([true, false, 1, 0]) }`
```
```
<pre id=a>
```
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 1 byte
```
¬
```
[Try it online!](http://jelly.tryitonline.net/#code=wqw&input=&args=MSwxLDAsMCwx)
`¬` is logical NOT (1 if false-y, else 0). `C` (“complement”, **1−z**) also works.
[Answer]
# Matlab, ~~4~~ 1 byte
This should be self explanatory.
```
~
```
Matlab has the one-byte negation operator `~`, if you want a function you can use `@not`.
[Answer]
# Haskell, 7 bytes
```
map not
```
Example:
```
Prelude> (map not) [False, True, True]
[True,False,False]
```
[Answer]
# C, 46 Bytes recursive version
```
f(char*s){*s?putchar(*s&72?*s:*s^1),f(++s):0;}
```
# C, 47 Bytes iterative version
```
f(char*s){for(;*s;putchar(*s&72?*s:*s^1),s++);}
```
Run using this main function
```
main(c,v)char**v;
{
f(v[1]);
}
```
and input like this
```
a.exe [1,0,1,1,0]
[0,1,0,0,1]
```
[Answer]
# R, 1 byte
```
!
```
Example:
```
> !c(TRUE, FALSE)
[1] FALSE TRUE
```
It also works with numerical input:
```
> !c(1, 0)
[1] FALSE TRUE
```
We're not restricted to one-dimensional arrays, either. Let's make a matrix, and randomly populate it with 0s and 1s:
```
> mat = matrix(rbinom(16, 1, .5), ncol=4)
> mat
[,1] [,2] [,3] [,4]
[1,] 0 1 1 1
[2,] 0 1 0 0
[3,] 0 0 0 0
[4,] 1 1 1 0
```
We can invert this just as easily:
```
> !mat
[,1] [,2] [,3] [,4]
[1,] TRUE FALSE FALSE FALSE
[2,] TRUE FALSE TRUE TRUE
[3,] TRUE TRUE TRUE TRUE
[4,] FALSE FALSE FALSE TRUE
```
We can continue to do this for arbitrary numbers of dimensions. Here's an example on a four-dimensional array:
```
> bigarray = array(rbinom(32, 1, 0.5), dim=c(2,2,2,2))
> bigarray
, , 1, 1
[,1] [,2]
[1,] 0 0
[2,] 0 0
, , 2, 1
[,1] [,2]
[1,] 1 0
[2,] 0 0
, , 1, 2
[,1] [,2]
[1,] 0 1
[2,] 0 1
, , 2, 2
[,1] [,2]
[1,] 1 0
[2,] 1 1
> !bigarray
, , 1, 1
[,1] [,2]
[1,] TRUE TRUE
[2,] TRUE TRUE
, , 2, 1
[,1] [,2]
[1,] FALSE TRUE
[2,] TRUE TRUE
, , 1, 2
[,1] [,2]
[1,] TRUE FALSE
[2,] TRUE FALSE
, , 2, 2
[,1] [,2]
[1,] FALSE TRUE
[2,] FALSE FALSE
```
Doesn't work for characters, I'm afraid.
```
> !"Hello world"
Error in !"Hello world" : Invalid argument type.
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 1 byte
```
~
```
[Try it online!](http://matl.tryitonline.net/#code=fg&input=WzAsMSwxLDAsMV0&args=)
`~` is the logical *not* and as many functions, it can also be applied to arrays/matrices.
[Answer]
# [Perl 6](https://perl6.org), 4 bytes
"French"/Unicode version:
```
!«*
```
"Texas"/ASCII version:
```
!<<*
```
Input is a single value which can be treated as a list.
This is a a [Whatever lambda (`*`)](https://docs.perl6.org/type/WhateverCode) with the [logical not prefix operator (`!`)](https://docs.perl6.org/routine/!) combined using [prefix hyper operator (`«`)](https://docs.perl6.org/syntax/$LESS-THAN_SIGN$LESS-THAN_SIGN).
Effectively this is the same as:
```
-> $_ { $_.values.hyper.map: &prefix:<!> }
# ( currently the Rakudo implementation doesn't actually do the 「.hyper」 call,
# but prefix 「«」 is specifically designated for doing things in parallel )
```
## Usage:
```
# pretend it's a method
say (True,False,True,True).&( !«* );
# (False True False False)
say ( !«* )( (False,False,True,False,False) );
# (True True False True True)
# give it a lexical name
my &list-invert = !«*;
# v¯¯ a space is necessary here
say list-invert (True,False);
# (False True)
say (False,True).&list-invert;
# (True False)
```
[Answer]
# [Labyrinth](http://github.com/mbuettner/labyrinth), 9 bytes
```
,$:)%#$.,
```
[Try it online!](http://labyrinth.tryitonline.net/#code=LCQ6KSUjJC4s&input=MQoxCjAKMQowCg) Assumes newline-separated input with a trailing newline. Thanks to @MartinEnder for help with golfing.
This program's a bit weird for a Labyrinth program - it doesn't make use of the 2D nature of the language, and it actually bounces back and forth. On the first forward trip, we have:
```
[Moving rightward]
, Read char c of input
$ XOR c with implicit 0 at bottom of stack
:)% Calculate c % (c+1), erroring out if c == -1 from EOF, otherwise returns c
#$ XOR with (length of stack == 1)
. Output (c^1) as char
, Read newline
[Moving leftward]
. Output newline
$ XOR two implicit 0s, stack [0]
%# Mod with (length of stack == 1), giving stack [0]
$:) Increment, duplicate then XOR, stack still [0]
, Read char c of input
```
The next occurence of `$` then XORs the existing 0 on the stack with `c`, as opposed to an implicit 0 at the bottom of the stack like in the first run. Both situations leave the stack as `[c]`, and the program repeats thereafter.
Alternative 9-bytes:
```
,:):/$.:,
,::)/)$.,
,:):%)$.,
```
[Answer]
## Mathematica, 7 bytes
```
Not/@#&
```
or without letters:
```
!#&/@#&
```
As for the syntactic sugar: `&` marks the right end of an unnamed function and has very low precedence. `#` refers to the first argument of the nearest and enclosing `&`. `!` is the operator for `Not`. So `!#&` is just an unnamed function that negates its argument, in other words its identical to the built-in `Not`. `/@` is the operator for `Map`. So the code would also be equivalent to the somewhat more readable `Map[Not, #]&`.
[Answer]
# J, 2 bytes
```
-.
```
This is the negation verb.
## Test case
```
-. 0 1 0 0 1
1 0 1 1 0
```
[Answer]
# Python, ~~27~~ ~~25~~ 24 bytes
Thanks to Lynn for golfing off two bytes, and xnor and Mego for golfing off another.
```
lambda a:[b^1for b in a]
```
[Answer]
# C#, 19 bytes
as an annonymous function, takes a bool[] and returns an IEnumerable
```
b=>b.Select(x=>!x);
```
or in 36 bytes with
```
dynamic f(bool[]b)=>b.Select(x=>!x);
```
[Answer]
# Swift 3 (7 bytes)
```
.map(!)
```
e.g.
```
[true, false].map(!)
```
## Explanation
Seems pretty obvious. Calls `map` on the array `[true, false]`. The one "gotcha" is that, in Swift, operators are just functions and can be passed around as arguments. This means `map(!)` is passing the "not" function `!` into `map`.
[Answer]
# [Shakespeare Programming Language](http://esolangs.org/wiki/Shakespeare), 240 bytes
```
.
Ajax,.
Puck,.
Act I:.
Scene I:.
[Enter Ajax and Puck]
Puck:
Open your mind.Is hog as big as you?If so, let us return to scene II.You be sum of difference of zero and you and cat.Open thy heart!Let us return to scene I.
Scene II:.
[Exeunt]
```
Takes input as a string of `\0` and `\1` control characters. Outputs as a string of `0` or `1`. If the input must be the same as the output, replace `Open thy heart` with `Speak thy mind` for no change in bytecount. If `\0` and `\1` can't be used, do the above, but also replace `Open your mind` with `Listen to thy heart` for a 5-byte penalty.
Ungolfed:
```
The Invertion of Veronan Arrays.
Romeo, who stores the element.
Juliet, who lectures him.
Act I: In which an array is inverted.
Scene I: A silent entrance.
[Enter Romeo and Juliet]
Scene II: In which Juliet pours out her heart to Romeo.
Juliet:
Open your mind. Is nothing better than thee? If so, let us proceed to scene III.
Thou art as good as the sum of the difference between nothing and thee and my
cat. Open your heart! Let us return to scene II.
Scene III: Finale.
[Exeunt]
```
This roughly translates to the following C pseudocode:
```
int romeo;
Scene1:
romeo = getchar();
if (0 > romeo) goto Scene2;
romeo = 0 - romeo + 1;
printf("%d", romeo);
goto Scene1;
Scene2:;
```
I'm using [this interpreter](http://github.com/drsam94/Spl). Sample run:
```
$ python splc.py invert.spl > invert.c
$ gcc invert.c -o invert.exe
$ echo -ne "\x00\x01\x00" | ./invert
101
```
[Answer]
# IBM/Lotus Notes Formula, 2 bytes
```
!a
```
Usage:
Create a Notes form with two fields named a and b.
a (input) = editable, number, multi-value, comma separated
b (output) = computed, number, multi-value, comma separated
Paste the above formula into b and give a a default value of 0.
Create a new document with the form, enter a binary list in a and press F9 to update the output.
Examples:
[](https://i.stack.imgur.com/17EDw.png)
[](https://i.stack.imgur.com/5p0Nm.png)
[](https://i.stack.imgur.com/E9ZCf.png)
Works because given a list as input, Notes formula will apply whatever specified action to every element in the list.
[Answer]
# [JAISBaL](https://github.com/SocraticPhoenix/JAISBaL), 1 byte
```
!
```
Like all the other 1-byte answers, this is the negation operator, which can operate over an array if needed. This leaves the output on the stack, which is printed at the end of the program.
For two bytes, the array can be explicitly printed:
```
!§
```
Input is in JAISBaL's incredibly odd array format (which I did invent, but I don't like it...).
Test Cases (Output from the Java interpreter, 3.0.5):
```
Enter a value > [true][false]
--------------------
Stack: [[false, true]]
Locals: {}
----------------------------------------
Enter a value > [false][false][true][false][false]
--------------------
Stack: [[true, true, false, true, true]]
Locals: {}
```
[Answer]
## PowerShell, 15 bytes
```
$args[0]|%{!$_}
```
I *think* this may even work in v1, hence I left the version number off the title. Loops through the input `$args` and negates each item in turn. That resulting array is left on the pipeline.
The neat thing, however, is because PowerShell is so loose on its casting requirements, you can do a completely mixed input and get an appropriate Boolean output. For example, here are the literal Boolean values `$false`/`$true`, the numbers `0` `1` and `123456789` as integers, an empty string, a non-empty string, an empty array, and a non-empty array --
```
PS C:\Tools\Scripts\golfing> .\invert-a-boolean-array.ps1 @($false,$true,0,1,123456789,'','foo',@(),@(1,1))
True
False
True
False
False
True
False
True
False
```
[Answer]
# Perl, 7 bytes
Includes +2 for `-lp`
Give each boolean value as 0 or 1 on its own line
```
invert.pl
1
1
0
^D
```
`invert.pl`:
```
#!/us/bin/perl -lp
$_^=1
```
[Answer]
# [Brachylog](http://github.com/JCumin/Brachylog), 7 bytes
```
:{-$_}a
```
[Try it online!](http://brachylog.tryitonline.net/#code=OnstJF99YQ&input=WzE6MDowOjE6MDoxXQ&args=Wg&debug=on)
### Explanation
```
:{ }a Apply this predicate to each element of the Input
- Decrement
$_ Negate
```
[Answer]
# Cheddar, 10 bytes
```
@.map((!))
```
I hope I counted right as I'm writing from phone
[Answer]
# Java, 58 bytes
```
void f(boolean[]a){for(boolean i:a)System.out.print(!i);}
```
[Answer]
# brainfuck (58 Bytes)
```
-[>+<-----]>--->,[<[->->+<<]>[--<]>[>]<[-<+<+>>]<+.[-]<>,]
```
[Try it here](http://brainfuck.tryitonline.net/#code=LVs-KzwtLS0tLV0-LS0tPixbPFstPi0-Kzw8XT5bLS08XT5bPl08Wy08KzwrPj5dPCsuWy1dPD4sXQ&input=MTAwMTExMA)
Ungolfed
```
-[>+<-----]>--- Number 48 (stands for 0)
>, Read in first point
[
<[->->+<<] Subtract 1 from 48 flag, subtract 1 from read data, add 1 for new flag
>
[--<] If sitting on 1 (true) subtract 2 and move left)
>[>]< Move to 48 flag
[-<+<+>>] Add 48 to data point
<+.[-]< Add 1 move print, zero cell, move to new 48 cell
>, Read in next point
] Loop if input remaining
```
Takes an input of undivided 1s or 0s (11001).
[Answer]
# Java, 15 bytes
```
s->s.map(b->!b)
```
Note: `s` is a `java.util.stream.Stream<Boolean>` and the import is not necessary, proof below.
## Testing and ungolfed
**LookMaNoImports.java**
```
class LookMaNoImports {
static Main.F f = s -> // transform a Stream<Boolean>
s.map( // by applying its map method
b -> // which in turns transforms a boolean
!b // by applying its negation.
);
}
```
**Main.java**
```
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
interface F {
Stream<Boolean> f(Stream<Boolean> s);
}
public static void main(String[] args) {
F f=LookMaNoImports.f;
test(f, new Boolean[]{true}, new Boolean[]{false});
test(f, new Boolean[]{false}, new Boolean[]{true});
test(f, new Boolean[]{true, false}, new Boolean[]{false, true});
test(f, new Boolean[]{true, true}, new Boolean[]{false, false});
}
static void test(F f, Boolean[] param, Boolean[] expected) {
List<Boolean> result = f.f(Arrays.stream(param)).collect(Collectors.toList());
if (result.equals(Arrays.asList(expected))) {
System.out.printf("%s: OK%n", Arrays.toString(param));
} else {
System.out.printf("%s: NOT OK, expected %s%n", Arrays.toString(param), Arrays.toString(expected));
}
}
}
```
[Answer]
# [Logicode](https://github.com/LogicodeLang/Logicode), ~~9~~ 8 bytes
```
out!binp
```
Simple, really.
Takes input as a binary string, as Logicode doesn't have support for lists (so `[true, false]` would be `10`).
The `out` outputs the line's result.
The `!` command calculates the NOT of every bit in the string, so something like `!111` would be `000`.
The `binp` is binary input.
1 byte saved thanks to @daHugLenny
[Answer]
# [Binary Lambda Calculus](https://tromp.github.io/cl/cl.html), 64 bits = 8 bytes
```
0001011000000000010111001011111000001000001100101111011010000010
```
[Try it online!](https://tio.run/##S8pJ/v/fwMDA0MDQ0AAOQDxDKAUVh5JwURATJvP/PwA "Binary Lambda Calculus – Try It Online")
*Note: This is a function and its list format is slightly different from the list format used by default in BLC’s I/O, so the TIO link doesn’t really do anything.*
## Explanation
If you don’t know what lambda calculus is, please read [this Wikipedia page](https://en.wikipedia.org/wiki/Lambda_calculus) about it, since Wikipedia explains it better than I can.
My function takes a list of [Church booleans](https://en.wikipedia.org/wiki/Church_encoding#Church_Booleans) as input. The list encoding that it uses is [the one where a list is encoded as its right fold function](https://en.wikipedia.org/wiki/Church_encoding#Represent_the_list_using_right_fold). i.e. The encoding of `list` is `foldr list` (in pseudo-Haskell). An example of this kind of list is `\c n. c (T (c F n))`, where `T` and `F` are the Church booleans for true and false, respectively. This example represents the list `[true, false]`.
Here is the lambda calculus (pseudo-?)code that I used to get my BLC code:
```
\l. l (\a b. \c n. c (a (\x y. y) (\x y. x)) (b c n)) (\c n. n)
```
(`\` is abstraction, `\a b. ...` means `\a. \b. ...`, abstraction extends as far as it can, and application is left-associative.)
I then represented it using [De Bruijin indices](https://en.wikipedia.org/wiki/De_Bruijn_index):
```
\1 (\\\\2 (4 (\\1) (\\2)) (321)) (\\1)
```
Note that `321` means `((3)2)1`, not literally a De Bruijin index using the number 321.
Then I used `@` to represent application (i.e. `@mn` means `m(n)`).
```
\@@1\\\\@@2@@4\\1\\2@@321\\1
```
(Note that I transcribed this “by hand,” so if my answer doesn’t work, then it’s probably a problem with this.)
I then used this to get the BLC code. (See [here](https://tromp.github.io/cl/Binary_lambda_calculus.html) for information about how the encoding works and more information about BLC.)
## The actual explanation is here
So I’m going to explain using a condensed version of the lambda calculus notation.
Note that my vocabulary, specifically “the accumulator’ and “the new element”, is probably wrong. I’m basically trying to paint the image of a for loop initializing the “accumulator” at a value and changing it each time it passes through a “new element” of the list.
```
\l.l(\abcn.c(a(\xy.y)(\xy.x))(bcn))(\cn.n)
\l.l( )( ) Right fold of l.
\cn.n Start the accumulator as the empty list.
\a a is the new element.
b b is the accumulator.
cn.c( Prepend...
a(\xy.y)(\xy.x) the logical negation of a
)(bcn) to the accumulator.
```
(This is a high-level overview and it’s probably possible to explain some of these concepts a better way.)
[Answer]
# [CJam](http://sourceforge.net/projects/cjam/), 4 bytes
```
{:!}
```
Input is a list of `0`s and `1`s.
[Try it online!](http://cjam.tryitonline.net/#code=WzAgMSAxXQoKezohfQoKfnA&input=)
[Answer]
# Japt, 3 bytes
```
¡!X
```
Japt doesn't have boolean input, so input is an array of 0s and 1s. [Test it online!](http://ethproductions.github.io/japt/?v=master&code=oSFY&input=WzEgMCAwIDEgMCAxXQ==)
### How it works
```
¡ // Map each item X in the input to
!X // the boolean NOT of X.
// Implicit output
```
[Answer]
# [Retina](http://github.com/mbuettner/retina), 3 bytes
```
%`0
```
[Try it online!](http://retina.tryitonline.net/#code=JWAw&input=MQoxCjAKMQow)
For each line (`%`), count the number of `0`s.
] |
[Question]
[
Please read the rules, **and the bold areas as well**.
Write a program in any language, so long as it has GUI support for a window system (cannot be text-consoles, etc., and must be a GUI/toolkit/window).
The program must say hello world in any manner (splash image, menu bar, status bar, title, video, message box, other widget stuff, etc.), **so long as a GUI-compliant window appears and shows this text for three seconds**. The person who can code this in the least amount of code used, counted in bytes, will take the cake.
[Answer]
# Unix shell, 31 characters
```
xmessage -timeout 3 hello world
```

This program requires the [xmessage(1)](http://www.openbsd.org/cgi-bin/man.cgi?query=xmessage&apropos=0&sektion=0&manpath=OpenBSD+Current&arch=i386&format=html) utility from X.Org. It uses the traditional black-and-white X Athena Widgets (Xaw).
[Answer]
# Shell and gedit - 27 characters
```
timeout 3 gedit Hello World
```
>
> 
>
>
>
If Hello World needs to be displayed as a single string, then its **28** characters:
```
timeout 3 gedit Hello\ World
```
`timeout` utility runs a command for the duration specified. It ensures that gedit runs for 3 seconds, assuming minimal startup time.
Any editor can be used in place of `gedit`. If a shorter named editor is used like `gvim`, the length can be reduced by 1 or more characters.
Using an editor initially thought of by [user80551](https://codegolf.stackexchange.com/a/28425/8395).
[Answer]
# Applescript, 45 bytes:
Not often Applescript is one of the shorter answers:
```
display alert "hello world" giving up after 3
```
Paste into the Applescript Editor and run, or run using `osascript` at the command line:
```
osascript -e 'display alert "hello world" giving up after 3'
```

[Answer]
# HTML+Javascript, 73 60 characters
```
<script>setTimeout("open('','_self','');close()",3e3)</script>Hello world
```
This works in Chrome, but may not be portable to other browsers.
Suggestions from the comments take this further:
```
<body onload=open('',name=setTimeout(close,3e3))>Hello world
```
[Answer]
## shell script, 31
Not sure whether it qualifies. Requires `notify-send`. Works at least on Ubuntu 12.04.
```
notify-send -t 3000 Hello world
```

[Answer]
## shell + gedit / geany, 34
```
gedit Hello\ World&sleep 3;kill $!
```

This assumes that gedit pops up instantly since the 3 seconds are counted from the start of issuing the command. Could be smaller if there's a GUI text editor shorter than `gedit`.
`geany` works too for the same number of chars, just `s/gedit/geany/g`

EDIT: Using `timeout` is shorter. <https://codegolf.stackexchange.com/a/28477/8766>
EDIT2: Can anyone confirm if this works with `kate` ?
---
## meld , 32
If exactly `Hello World` is not required, then `meld` can be used.
```
meld Hello World&sleep 3;kill $!
```

[Answer]
## VBScript, 58
```
WScript.CreateObject("WScript.Shell").Popup"Hello world",3
```

[Answer]
## Python (pygame), 87
```
import pygame.display as d,time
d.set_mode()
d.set_caption('Hello world')
time.sleep(3)
```

[Answer]
## Tcl - 32 bytes
I noticed that some of these submissions, like the shell or javascript ones, allow you to type the code into the console. If that's the case I can shorten it to:
```
wm ti . hello\ world;af 3000 exi
```
Must be typed into the console **after** running wish. Meaning, run `wish` without arguments which will give you a REPL console and then type the code above. This makes use of the fact that tcl can be lenient and autocomplete command/function names but only in interactive mode. So that `af` actually exectues the `after` command and `exi` executes `exit`. I wanted to use `ex` but my system has the `ex` editor installed.
---
## Original submission - 36 bytes
```
wm ti . hello\ world;after 3000 exit
```
Run using `wish` instead of `tclsh`.
[Answer]
## ~~52~~ 51 chars with Mathematica
(Hope it counts as a GUI-compliant.)
```
NotebookClose/@{CreateDialog@"Hello world",Pause@3}
```

[Answer]
# Java, 136 bytes
```
class F{public static void main(String[]a)throws Exception{new java.awt.Frame("Hello World").show();Thread.sleep(3000);System.exit(0);}}
```
Displays the message `Hello World` as the title of a frame. After `3` seconds, the program closes.
Looks like this:

Drag it bigger:

---
Expanded code (ie readable):
```
class F {
public static void main(String[] a) throws Exception {
new java.awt.Frame("Hello World").show();
Thread.sleep(3000);
System.exit(0);
}
}
```
[Answer]
## R, 44
```
x11(ti="Hello World");Sys.sleep(3);dev.off()
```

[Answer]
## PowerShell - 63 52
```
(new-object -c wscript.shell).popup('Hello World',3)
```
[Answer]
# Visual FoxPro - 23 characters
```
WAIT"hello world"TIME 3
```

This abuses the fact that VFP allows to not to put a space between the string to be printed (which I just discovered) and that it allows to shorten every keyword to up to its first 4 characters.
Ungolfed version:
```
WAIT "hello world" TIMEOUT 3
```
[Answer]
# GTK+, ~~47~~ 45
```
zenity --info --text=Hello\ World --timeout=3
```

---
Old version (score 47):
```
zenity --info --title="Hello World" --timeout=3
```

For some reason, zenity display a text which can be translated as *All update are done*.
[Answer]
## Batch (24)
```
msg/time:3 * hello world
```
Tested on Windows 7, but should work on any NT-based version of Windows, assuming you have MSG.EXE in your System32 folder.
EDIT: Apparently MSG.EXE is not available by default on home versions of Windows. On Windows 7, for example, this is only available in the Ultimate or Business editions. However, you can copy the file over to your System32 folder and get it to work. (You must also copy over the appropriate MSG.EXE.MUI file to get proper error messages, but my "script" works without them.)
You have to install software for most of these other responses to work, too, so I don't think that should be a disqualifier.
[Answer]
## C, 151 characters
```
#include<allegro.h>
main(){textout_ex(screen,font,"Hello World",0,0,7,set_gfx_mode('SAFE',8,8,install_timer(),
allegro_init()));rest(3e3);}END_OF_MAIN()
```
Not the smallest answer. I like it though.
[Answer]
# C# 101 151
This will for sure not be the shortest answer (since there are already other good answers being way shorter) but codegolf.SE needs a lot more C# contributions in my opinion!
```
using t=System.Threading;class P{static void Main(){using(t.Tasks.Task.Run(()=>System.Windows.MessageBox.Show("hello world"))){t.Thread.Sleep(3000);}}}
```
# C# 121
An alternative based on [Bob's answer](https://codegolf.stackexchange.com/a/28480/21478), but with WPF instead of WinForms:
```
class P{static void Main(){new System.Windows.Window(){Title="hello world"}.Show();System.Threading.Thread.Sleep(3000);}}
```
Saves 3 characters thanks to the shorter namespace ...
[Answer]
## bash + ImageMagick (36 bytes)
```
timeout 3 display label:Hello\ world
```
Tested on Ubuntu 14.04 LTS and on Fedora 20.
Nicer-looking, but 10 bytes larger:
```
timeout 3 display -size 800 label:Hello\ world
```
[Answer]
## CMD / Batch - 33 Bytes
I believe the window that the Windows CMD terminal runs in counts as GUI compliant.
```
start "Hello world" cmd /csleep 3
```
If you don't have the `sleep` command on your system - then you can use `timeout` which comes default in Windows 7. For two more bytes.
```
start "Hello world" cmd /ctimeout 3
```
Starts a new CMD window with the title "Hello World" (**NOT** displayed in the terminal itself, but as the title of the GUI window that the terminal runs in), this window will close as soon as all parsed commands have executed - so after `sleep 3` or `timeout 3` has completed.
The window looks like this -

Note; `start` runs the given commands in a new window - not the window that you are running the above commands from.
[Answer]
# [Autohotkey](https://autohotkey.com/), 22 Bytes
```
msgbox,,hello world,,3
```
Ahk's [msgbox](https://autohotkey.com/docs/commands/MsgBox.htm) is pretty powerful and has a built-in timeout option.

[Answer]
# [Red](http://www.red-lang.org), 49 bytes
```
view[text"hello world"rate 0:0:3 on-time[unview]]
```
[Answer]
## APL (40)
```
X.Close⊣⎕DL 3⊣'X'⎕WC'Form' 'Hello World'
```
[Answer]
## Lua + LÖVE, 67 bytes
```
l=love l.window.setTitle"hello world"l.timer.sleep(3)l.event.quit()
```

[Answer]
# Perl on Windows (56)
```
use Win32;fork?kill+sleep+3,$$:Win32'MsgBox"Hello World"
```
[Answer]
## Perl 5, 47
Using [Perl/Tk](http://search.cpan.org/~srezic/Tk-804.032/Tk.pod):
```
perl -MTk -e'alarm 3;tkinit-title,"Hello World!";MainLoop'
# 123 45678901234567890123456789012345678901234567
```
[Answer]
# Rebol View (r3gui), 49
```
view/no-wait[title"hello world"]wait 3 unview/all
```

Ungolfed:
```
view/no-wait [title "hello world"]
wait 3
unview/all
```
[Answer]
# Processing, 77
```
int x=millis();void draw(){text("Hello world",0,9);if(millis()>x+3e3)exit();}
```
Screenshot:

**Edit 1:** Y position of the text can be 9 instead of 10, like noted by @ace.
**Edit 2:** 3000 can be represented as 3e3 to shave one character off, also noted by @ace
[Answer]
### Python with turtle module (69 66 bytes)
```
import turtle as t,time
t.title("Hello World")
t.fd(1)
time.sleep(3)
```
Note that if you run this in an interactive console, you don't need the `t.fd(9)` line. However, for some reason when running this non-interactively, the title doesn't change unless you run the extra line.
### Edit (66 bytes)
```
import turtle as t
t.title("Hello World")
t.ontimer(t.fd(1),3000)
```
[Answer]
# QML - 98 bytes
Here's the code. Works on all supported platforms (including Android and iOS):
```
import QtQuick 1.0;Text{text:"Hello world";Timer{interval:3000;onTriggered:Qt.quit();running:1>0}}
```

] |
[Question]
[
# What?
*Many programming languages, both practical and esoteric, have functions, methods, etc to convert a given string to a decimal number.* This is how the process might work:
* For each character in the given string.
+ Take the character's ASCII value and subtract it by 48.
+ Multiply the output value by 10. (The output at the first iteration is 0)
+ Add the subtracted ASCII value to the output.
Let us do this process for the string `"109"`:
1. The ASCII value of `1` is 49. Subtract it by 48, and we get 1. We multiply the output by 10, we get 0. Finally, we add 1 to 0 and get one.
2. Next, we subtract `0`'s ASCII value (48) by 48, we get 0. We multiply 1 by 10, we get 10. Nothing happens when we add 0.
3. Then we subtract `9`'s ASCII value (57) by 48, we get 9. We multiply 10 by 10 and get 100. We add 9 to 100 and get 109.
There, we successfully converted `"109"` to 109! It is just as simple!
The problem is that most languages do not like it when the converting string has non-digital characters (characters with an ASCII value not in the range 48-57 inclusive). They would most likely throw some nasty errors or exceptions at us.
*How 'bout we ignore that!*
# Task
Given a printable string from STDIN (you can assume that \$1 ‚â§ \text{Input Length} ‚â§ 10\$), implement a program or function to badly convert it to an integer according to the above steps, and output or return it back.
Strings can contain whitespace characters (Spaces, tabs and linefeeds).
For another example string `"Hi!"`:
1. The ASCII value of `H` is 72:
`72 - 48 = 24`
`0 * 10 = 0`
`0 + 24 = 24`
2. The ASCII value of `i` is 105:
`105 - 48 = 57`
`24 * 10 = 240`
`240 + 57 = 297.`
3. The ASCII value of `!` is 33:
`33 - 48 = -15`
`297 * 10 = 2970`
`2970 + -15 = 2955`
This means that `"Hi!"` converted to an integer is 2955!
Standard I/O rules apply.
*Note: if your language does not support input, feel free to tell me in your answers (you can put the "input" strings in your source code)!*
# More test cases
```
STDIN Output
"123456789" -> 123456789
"0123456789" -> 123456789
"-12345" -> -287655
"Lorem" -> 350191
"Ipsum" -> 321451
"AAAAAAAA" -> 188888887
" " -> -177777776
"A" -> 17
" " -> -16
"
" -> -38
```
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply!
[Answer]
# [Shakespeare Programming Language](https://github.com/TryItOnline/spl), ~~258~~ 252 bytes
-6 bytes thanks to [the default](https://codegolf.stackexchange.com/users/36445/the-default).
```
,.Ajax,.Puck,.Act I:.Scene I:.[Exeunt][Enter Ajax and Puck]
Ajax:Open mind.
Puck:Is I nicer zero?If soYou is the sum ofI twice the difference
betweenthe product ofyou the sum ofa cat a big big cat the factorial
ofa big big cat.
If soLet usAct I.Open heart
```
[Try it online!](https://tio.run/##TY9NCgIxDIWv8g4w9ACzERcuCoKCKxEXtZM6VScd2hR/Lj@23egikPfyJbyk@bEsnVrfzKtT@2zvpbcC3auDJabanDYvyizn04aFIioKwwMqfa6q383EmDwP7UKvEzTY2wJ/KIaVdkjhGDJ8goyElCcEpyHPwjRn8M5RJC7yQvIk4urOMQy5hAnuXZZ/mwbWCAwu/tqqqjp1xkqI3jwa8zdVLcGWBDm171RLPJKJsizbEGn6Ag "Shakespeare Programming Language – Try It Online")
The golfiest representation of the integer 48 is as `twice the factorial of a big big cat`, i.e. \$48=2\times (2\times2\times1)!\$.
This corresponds to
```
Ajax = 0
Puck = 0
Begin Act I
Puck = read_input (as ASCII codepoint value)
if(Puck>0){
Ajax = Puck + 2 * (Ajax * (4+1) - 4!)
Go to Act I
}
print(Ajax) (as an integer)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
O_48Ḍ
```
[Try it online!](https://tio.run/##y0rNyan8/98/3sTi4Y6e/4fbHzWt@f9fySNTUUlHQckRCkBsQyNjE1MzcwtLJQA "Jelly – Try It Online")
## How it works
```
O_48Ḍ - Main link. Takes a string s on the left
O - Convert to ordinal code points
_48 - Subtract 48 from each
Ḍ - Convert from base-10
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 8 bytes
As long as we're doing things wrong, why not turn a string into a polynomial?
```
48-[X]ZQ
```
[Try it online!](https://tio.run/##y00syfn/38RCNzoiNirw/391n/yi1Fx1AA "MATL – Try It Online")
Evaluates the polynomial
$$p\_1x^{n-1} + \cdots + p\_{n-1}x^1 + p\_nx^0$$
where \$p\$ is the input string (minus '0') and \$x\$ is 10.
[Answer]
# [Poetic](https://mcaweb.matc.edu/winslojr/vicom128/final), 153 bytes
```
decoding a num got WRONG
I/O digits i get?converting fails,o darn
i am bummed if the I/O fails
i have a number i got based on counting it badly,i suppose
```
[Try it online!](https://mcaweb.matc.edu/winslojr/vicom128/final/tio/index.html?JY07DoMwEER7TjEHQIqSHCBllCZIaVKv8WJWwl7kDxKnJzZpZ968sTyqleBACMXDacb3M7yf3esywIqTnCBwnB@jho1jbuxEsqReYSmGTkAepnjPFjIhz4y2PZlazrTxX244NlV9MJQqrAGjlnAapYV22XtBKuuqiY/r7X7U7Ac)
[Answer]
# [JavaScript (ES6/2015)](http://www.ecma-international.org/ecma-262/6.0/), 43 bytes
```
s=>s.map(c=>r=r*10+c.charCodeAt()-48,r=0)|r
```
```
let f = s=>s.map(c=>r=r*10+c.charCodeAt()-48,r=0)|r
console.log(f([..."123456789" ])) // 123456789
console.log(f([..."0123456789"])) // 123456789
console.log(f([..."Lorem" ])) // 350191
console.log(f([..."Ipsum" ])) // 321451
console.log(f([..."AAAAAAAA" ])) // 188888887
console.log(f([..." " ])) // -177777776
console.log(f([..."A" ])) // 17
console.log(f([..." " ])) // -16
```
[Try it online!](https://tio.run/##jcy9DoIwFIbh3atomIpK4SA/ZSgJcTLxDoxDU8GfgCUtMnnvGAPSRDv4jifP@W6851qoa9t5PR0qNmiWa9LwFguWK6aWEKwEEReutvJUFh12vYiuFQvcpxqEvGtZl6SWZ1zhAyHEgXATxUlKMwcdXRf5PkLzaWHxgXn4y@@lKhsHvfv4TRxABja8a/XjG4cQxVZcTDkGAx1LbR5NGe9BOpZY9@cPs28f/oEeJMML "JavaScript (V8) – Try It Online")
**Edit #1:** -1 byte thanks to [l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)
**Edit #2:** -7 bytes thanks to [EzioMercer](https://codegolf.stackexchange.com/users/116593/eziomercer)
[Answer]
# [R](https://www.r-project.org/), ~~51~~ 48 bytes
*Edit: -3 bytes thanks to Robin Ryder*
```
function(s)(utf8ToInt(s)-48)%*%10^(nchar(s):1-1)
```
[Try it online!](https://tio.run/##hc5dC4IwFAbge3/FMIQtGHj8nEFBl0KXXSdiakJuMZV@vkmalBzpvdt2nr1H99c8q@r0npRK5slTK1nu@6KTWVspSRtGu7YQZxXLdjhwTzBra4F9oTK7pXq42gEHhnxCTXBczw9CEZmMbMgUfiBkfjAwZmPuPzspndffTR/m@jZEgJr40XS4ccDzcXOc8sPe64kxIcqmwaXiEI4J8LLlcnPZSsvKPIfA6F8 "R – Try It Online")
Multiplies Utf8 value of each character minus 48 by powers-of-ten from the length of the string minus one, down to zero, and outputs the sum.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~46~~ ~~45~~ 42 bytes
```
f=lambda s:s>[]and ord(s.pop())-48+10*f(s)
```
[Try it online!](https://tio.run/##VY3BCoJAFEXXzVc8hOHNlIallQkGLYP@oFoYOiSoM/hei77ecnDTXZ17Fve6D79sn4yjKdqye1YlUE6n26PsK7BDpWjtrFNaR2m22sRLo0iPXBMTFKAEbrZJutsfsiOGAuO/Fvk20dUOdTfBxdHbw3nOxDDHey9QaCGMHYCh6cG/5WLhhqZnhfK3SygVBpIClKxDMKptiBVrHVLtCrwz6vEL "Python 3 – Try It Online")
-1 thanks to Sisyphus
-3 taking a list of characters as input thanks to ovs
[Answer]
# [Scala](http://www.scala-lang.org/), 18 bytes
```
_./:(0)(_*10+_-48)
```
[Try it online!](https://tio.run/##K05OzEn8n5@UlZpcouCbmJmnkFpRkpqXUqzgWFBQzVWWmKOQZqUQXFKUmZeuYGun4JlXomD7P15P30rDQFMjXsvQQDte18RC838BUEVJTp5GmoaSR6aikqYmF5KIoZGxiamZuYUlmrhPflFqLpqYAohf@x8A "Scala – Try It Online")
Explanation:
```
_./:(0)(_*10+_-48)
/: Fold left
_ the input string
(0) with an initial value of 0
(_*10+_-48) Multiply the accumulator by 10, and add the next character - 48
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 13 bytes
```
·∫°-‚ÇÑ‚Çà·µê{√ó‚ÇÅ‚ÇÄ ∞+}À°
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3w/@GuhbqPmloeNXUAedWHpz9qanzU1HBqg3bt6YX//0crGRoZm5iamVtYKukoGSBzdMEcIMMnvyg1F0h7FhSXgmhHKAAyFaAAJAriKsUCAA "Brachylog – Try It Online")
For single-"digit" inputs, the output is wrapped in a list, since the fold isn't actually executed. If this isn't acceptable, two 15-byte alternatives exist:
[`·∫°-‚ÇÑ‚Çà·µê,0‚ܪ{√ó‚ÇÅ‚ÇÄ ∞+}À°`](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3w/@GuhbqPmloeNXUAeToGj9p2Vx@e/qip8VFTw6kN2rWnF/7/H61kaGRsYmpmbmGppKNkgMzRBXOADJ/8otRcIO1ZUFwKoh2hAMhUgAKQKIirFAsA)
[`ạ↔-₄₈ᵐ{i×₁₀ⁱ⁾}ᶠ+`](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3w/@GuhY/apug@amp51NQBFKjOPDz9UVPjo6aGR40bHzXuq324bYH2///RSoZGxiamZuYWlko6SgbIHF0wB8jwyS9KzQXSngXFpSDaEQqATAUoAImCuEqxAA)
```
·∫° Convert to codepoints.
-₄₈ᵐ Subtract 48 from each.
{ }ˡ Left fold:
√ó‚ÇÅ‚ÇÄ ∞ multiply the accumulator (initialized to first element) by 10
+ and add it to the next element.
```
Brachylog's base conversion builtin actually disallows values outside the usual range, because it's actually quite useful sometimes on top of preserving proper inverse behavior, so I'm forced to implement the described algorithm directly.
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), ~~35~~ 26 bytes
```
$args|%{$r=$r*10+$_-48}
$r
```
Saved 9 bytes using splatting
[Try it online!](https://tio.run/##K8gvTy0qzkjNydFNzi9K/a@SpmCrUP1fJbEovbhGtVqlyFalSMvQQFslXtfEopZLpeh/LReXShlQkZKhkbGJqZm5haUSlxpQm0MZTMIAp4wuWEZJAQLQJH2A9ufC5NAlPQuKS3FKOkKBEjZJmB50tziiCyBU/AcA "PowerShell Core – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 11 [bytes](https://github.com/abrudz/SBCS)
```
10⊥48-⍨⎕UCS
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R2wRDg0ddS00sdB/1rnjUNzXUOfg/kFIASiikKagbGhmbmJqZW1iqKyg86p2roAAX4EJSZYCkDLcqn/yi1FygOSAAVmVsamBoaYisxLOguBRViZGhiSmKEkcoUIcpMbSAAHNkVQpQAFOla2gOAWYoZsHVwcxCNQRNWtfQ7D8A "APL (Dyalog Unicode) – Try It Online")
`‚éïUCS` converts string to a vector of ASCII values, `48-‚ç®` subtracts 48 from each value and `10‚ä•` converts from base 10.
[Answer]
# Java 8, 46 bytes
```
a->{int r=0;for(var c:a)r=r*10+c-48;return r;}
```
Input as a character-array.
[Try it online.](https://tio.run/##TVDBToNAEL3zFeOeQIRQrVohmDS9aKK99Gg8jNutboWFzC6YhvDtuAvUOIeZ914mb17miC1Gx/33wAvUGl5Rqs4DkMoIOiAXsHV0FID7/Avp7R0wyKzYe7Zpg0Zy2IKCHAaMHju3SXmSHSryWyTgKQaU0@UiCXm0XGUkTEMKKOuHzDnUzUdhHWajtpJ7KG0Kf2dIqs/x2hTBGU4iGKHNBrWAFJT4gfNqx57kBbtii@ub5e3d/erB4uQ/iUZiwUtForTzudaNm@u5LIS5nOoo6wNvUnYnbUQZV42Ja3vQFMo/BwlZCixUMf9TYlNt7LfWRHjyg2D@WD/8Ag)
**Explanation:**
```
a->{ // Method with character-array parameter and integer return-type
int r=0; // Result-integer, starting at 0
for(var c:a) // Loop over the input-characters:
r= // Change the result to:
r*10 // The current result multiplied by 10
+c-48; // And add the codepoint of the current characters minus 48
return r;} // After the loop, return the result
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~45~~ 43 bytes
```
n#(h:t)=(n*10+fromEnum h-48)#t
n#_=n
f=(0#)
```
[Try it online!](https://tio.run/##dYzBjoIwEIbvPsWk7KGztAlFCmi2m@zBg4mePBpjOEjYaAspkOWw744tGA8m/ofJzPf9mapor5fbbRxNQKt1h4qaTxGFpa31xvQaKp7kGHQLE5yVWZSKRgGOuvg1oEAXzf4MTd8dOrszcIQBwhAIqG833Ebbqv6DDyhhwNnwF0OdAlQKLP7TgVn84kdKRLxMZJrlK8KeKzJKoneCTxdhPM6zVEqPdrW9aMKWMhIr4cG2aXsPYpHICfw84n7lczKP4RH3TWRz0qnuenPBmxRPp/EO "Haskell – Try It Online")
```
n#(h:t)= - # -> infix function taking a number and a string(head:tail)
(n*10+fromEnum h-48)#t
- compute first char and call recursively on tail
n#_=n - end condition
f=(0#) - apply 0 to #
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 5 bytes
```
C48-I
```
[Try it Online!](http://lyxal.pythonanywhere.com?s=?flags=&code=C48-I&inputs=Lorem&header=&footer=)
Wow it's actually ASCII.
[Answer]
# [Assembly (NASM, 32-bit, Linux)](https://www.nasm.us/), ~~221~~ ~~185~~ 147 bytes
*Edit: -36 bytes + bugfix*
*Edit: -38 bytes*
```
mov edi,0
push 48
l:imul edi,edi,10
add edi,[esp]
sub edi,48
mov edx,1
mov ecx,esp
mov ebx,0
mov eax,3
int 128
mov ax,[esp]
xor ax,10
jnz l
pop eax
```
[Try it Online!](https://jdoodle.com/a/2rRk)
The result is in `edi`.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 7 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ëk╜ΓOíU
```
[Run and debug it](https://staxlang.xyz/#p=896bbde24fa155&i=%22123456789%22%0A%220123456789%22%0A%22Lorem%22%0A%22Ipsum%22%0A%22AAAAAAAA%22%0A%22++++++++%22%0A%22A%22%0A%22+%22&m=2)
Explanation:
```
{48-mA|E Unpacked source, implicit input
{ m Map over code points of input string
48- Subtract 48 from each
A|E Convert from base 10
```
[Answer]
# [Perl 5](https://www.perl.org/), 40 bytes
```
sub{my$r;map$r=$r.0-48+ord,pop=~/./g;$r}
```
[Try it online!](https://tio.run/##bZBRa4MwFIXf/RVZCEOZtsaaqg0p3dsG3dvexigbjSJME6LCpHR/3Wm0Oteet3vOl3PDlVx9kSarAYpZU1Sfp6xGimYfEimG1MJ1/PBBqKMthWQ/y8UyoUidG2pUBQevvCg3mxehODXahl3Zzsw0QKs3@JTeQTAX2wLgRYS82wODvZVP1kEYwRkz2iPoXpO3wX37mQxebV0RF0d4pJ5lUd2iPOyTiXocBOcUDnsFI3hJ56CDg17rqfH/RYbGP1U3CQdfOixqxEKZ@tTWSVtZbaI0lzbi39JiO3Sggw1QIkp2j2KdW5Od5rFgsDOB42w1Bvs0Lcxu0l225tpnZ@Mocn7oVqZ5Qptf "Perl 5 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~48~~ 44 bytes
Usually using a temporary variable to store the current character is shorter than doing array processing, but not this time!
```
i;f(char*s){for(i=0;*s;i=i*10+*s++-48);s=i;}
```
[Try it online!](https://tio.run/##VU3NTsJAEL7PU4wYwm5LTYuAmHVJvGniGwgHbHdhknaXdIoHSZ@97lYT45y@@X7L7FiWw0DKivJ0aBOWV@tbQTpXCSvSlBR5mnCaZsuNVKxJ9cMtubK@VAafuKvI35228I@q6SNyQK7D5kBOfHqqJF4BMW4gvy9W672C8McthfZoOhY8R6Yv461gGWCodlL9xDBkuGtr44KWFXs92@UzNQrnNsxYMZky6i1Oq52bhPAcY4uMlh764YVuoFjcL1frh80j5H/wzbemgdczXxp4/r2xNh4ECNlohm8 "C (gcc) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 12 bytes
```
10#._48+3&u:
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DQ2U9eJNLLSN1Uqt/mtypSZn5CtoWKdpKqgbGhmbmJqZW1iqI4saYBfWBQujCPnkF6Xmooh4FhSXooo4QgGKoAIUoKpEVaL@HwA "J – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 53 bytes
```
def f(x):
o=0
for i in x:o=o*10+ord(i)-48
return o
```
[Try it online!](https://tio.run/##TY7BDsIgEETvfMXKCdQm1FatTTh408Q/MN4KSqIsAZrUr0fQHpzLzJs97Lh3fKBtUhqUBs0m3hNAKQho9GDAWJh6lLisxQr9wAyv2o6AV3H0FjA9TYjySk9mQde03jTtdrfvDjmLf6i@kMMFvXplP7swFj/OyhFmlbYgvZEyIURv7L3sKK/yOJc5Ms1@B87TBw "Python 3 – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~ 39 ~~ 38 bytes
*Saved 1 byte thanks to @Shaggy*
```
s=>Buffer(s).map(c=>p=p*10+c-48,p=0)|p
```
[Try it online!](https://tio.run/##hcy9CsIwGIXh3asImRI1bb7a3yEF3QRvosRElLYJjXXy3ivSEiEdfMfDw3k0r8bJ4W6frDdXNWkxOVGfRq3VQByNusYSKWor7Bb4TrK03FvB6dtO0vTOtCpqzY1ogiE5pFlelBVGlKI4Rsgvm4Dyn/1HL2ZQHUbfFnrIOFQQurN1Y@ASSLOVOy5h76CcK0KKljxlUMzlq1eP/ev6LjQM8ukD "JavaScript (Node.js) – Try It Online")
[Answer]
# [K (ngn/k)](https://bitbucket.org/ngn/k), 7 bytes
```
10/-48+
```
[Try it online!](https://tio.run/##y9bNS8/7/z/NytBAX9fEQvt/mrqGkqGRsYmpmbmFpZK1gpIBCk8XzAOxfPKLUnNBDM@C4lIwwxEKQGwFKACLgwWUNEH8/wA "K (ngn/k) – Try It Online")
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), ~~43~~ 38 bytes
```
,[<[>++++++++++<-]>+++>+[<->+++++],]<.
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fJ9om2k4bDmx0Y0E8O@1oG12IcKxOrI3e//9mpgA "brainfuck – Try It Online")
Thanks to JosiahRyanW for -5 bytes.
Since by our consensus, [output can be given as character code](https://codegolf.meta.stackexchange.com/questions/4708/can-numeric-input-output-be-in-the-form-of-byte-values/4719#4719), this is pretty straightforward in brainfuck. Note that the brainfuck interpreter on tio.run has 8-bit wrapping cells, so the maximum value is 255.
```
,[ while input
<[>++++++++++<-] add 10 times previous sum to input
>+++>+[<->+++++] add 208 to it (effectively subtracting 48 by 8 bit wrapping)
, read next character
]
<. output
```
[Answer]
# [Befunge-98 (PyFunge)](https://pythonhosted.org/PyFunge/), ~~14~~ 12 bytes
Thanks to [Gegell](https://codegolf.stackexchange.com/users/80503/gegell) for -2 bytes!
```
2j@.~'0-\a*+
```
[Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//83ynLQq1M30I1J1NL@/98nvyg1FwA "Befunge-98 (PyFunge) – Try It Online")
**Explanation**:
Initially the instruction pointer (IP) is moving right and the stack is filled with `0`'s.
`2j` skips the next two instruction (`@.`).
`~` reads one character of input.
`'0-` subtracts 48 from the input.
`\` swaps the two elements at the top of the stack. Now the intermediate result is on the top.
`a*` multiplies the result by 10.
`+` adds the new number.
If there is no input left `~` reflects the IP.
`.` prints the result at the top of the stack, and `@` terminates the program.
Animation of the code with input `Lorem`:
[](https://i.stack.imgur.com/tGGzb.gif)
I'm not sure why there are black bars on two frames, I blame ImageMagick :/
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Ç48-Tβ
```
Similar as some other answers.
[Try it online](https://tio.run/##yy9OTMpM/f//cLuJhW7IuU3//3tkKgIA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/w@0mFroh5zb91/kfreSRqaiko2RoZGxiamZuYQlkGyBzdMEcIMMnvyg1F0h7FhSXgmhHKAAyFaAAJAriKsUCAA).
**Explanation:**
```
Ç # Convert the (implicit) input-string to a list of codepoint integers
48- # Subtract 48 from each value
Tβ # Convert this from a base-10 list to a base-10 integer
# (after which it is output implicitly as result)
```
[Answer]
# [Rust](https://www.rust-lang.org/), 42 bytes
```
|s|s.chars().fold(0,|n,x|n*10+x as i32-48)
```
[Try it online!](https://tio.run/##VcpNCsIwEEDhvacYu5AZTUrS1loVvYoETbBQI2YiFIxnjz8LweV7fOHOMTsPF9N7pAcMNoLbOI8zjoHkvq8r2EFOnLg8nk1gpNJdhxMqkbwYk59rtRjBMLylbDrK24lhtiEe7G2KuqqbZbvq1sJhoX5VEP0xqdsPgO9/5hc "Rust – Try It Online")
Takes input as an &str and outputs the number based on utf-8 codepoints.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 38 bytes
```
->s{s.bytes.inject(0){|a,b|b-48+a*10}}
```
35 bytes with the new Ruby 2.7 syntax:
```
->s{s.bytes.inject(0){_2-48+_1*10}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1664ulgvqbIktVgvMy8rNblEw0CzuiZRJ6kmSdfEQjtRy9CgtvZ/gUJatJKhkbGJqZm5haVSLBdYwABDRBcsAuP55Bel5sI4ngXFpXCOIxTA@ApQAJeHSyjF/gcA "Ruby – Try It Online")
[Answer]
# [><>](http://esolangs.org/wiki/Fish), 15 bytes
```
0l1=?na*{68*-+!
```
[Try it Online!](https://tio.run/##S8sszvj/3yDH0NY@L1Gr2sxCS1db8f///7rFPvlFqbkA)
Explanation
```
0 ! Accumulator initialisation, skipped on subsequent loops
l1=?na* Print-and-terminate condition
a* Decimal shift
{ Next character of input
68*-+ Subtract 48 and add
```
[Answer]
# [Clojure](https://clojure.org/), 41 bytes
```
#(reduce(fn[x y](+(* 10 x)-48(int y)))0%)
```
[Try it online!](https://tio.run/##jZDdCoJAEIXv9ymGjWC2WnDV9Ycg6DLoDcQr3YXC1DRBn94sNUu86FwNcz7ODCdKsmtVqBZjpUG3KyxUXEUKdRrU0IS4xQ0IA2rGbQ8v6QMaxpixZi0jGGelukNQk4AK07Kl43o@3cGgPT8AfPaEGn8w/D1P/shw03MdKQk9Z4W6/fp9iCUN4QtCT3lZLQOmsGUHHAd9M/0bXi@X0HE/Z7hwezldzuzIlPMKoGG4ZHLhEMyLrsckBdRdrYy1Tw "Clojure – Try It Online")
Or alternatively, for the same byte count with a different order of full and shorthand function notation:
```
(fn[x](reduce #(+(* 10%)-48(int %2))0 x))
```
[Try it online!](https://tio.run/##jZDdCoJAEIXv9ymGDWG2WnDV9Ycg6DLoDcQr3YXC1DTBtzdNzRIvOlfDnI8zw4nT/FaXqsVEadAt6ixsIixVUscKNrjDLQjTYNzx8Zo9wbAYM6FhrGUEk7xSDwgbElJh2Y50PT@gexh14EeAz55Q8w@Gv@fZnxhu@Z4rJaGXvFT3X38IsaUpAkHouajqdcASjuyA06hvZnjDH@QROu2XDBfeILfLWRyZc/oAGkVrJhcuwaLsmkwzQN0XydoX "Clojure – Try It Online")
[Answer]
# [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 88 bytes
```
[S S S N
_Push_0][N
S S N
_Create_Label_LOOP][S S S N
_Push_0][S N
S _Duplicate_top][T N
T S _Read_STDIN_as_character][T T T _Retrieve][S N
S _Duplicate][S S S T N
_Push_1][T S S T _Subtract][N
T S S N
_If_0_Jump_to_Label_EXIT][S S S T T S S S S N
_Push_48][T S S T _Subtract][S N
T _Swap_top_two][S S S T S T S N
_Push_10][T S S N
_Multiply][T S S S _Add][N
S N
N
_Jump_to_Label_LOOP][N
S S S N
_Create_Label_EXIT][S N
N
_Discard_top][T N
S T _Print_as_integer]
```
Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.
Since Whitespace inputs one character at a time, the input should contain a trailing ␁ (character with codepoint 1) so it knows when to stop reading characters and the input is done.
[Try it online](https://tio.run/##K8/ILEktLkhMTv3/X0FBgYsLiEE0EHJycSpwcnKC@WAOhABxgaIgRSAhMAmkIAwwB6iZC2oIFyfQnP//dQ2NjE1MGQE) (with raw spaces, tabs and new-lines only).
**Explanation in pseudo-code:**
```
Integer result = 0
Start LOOP:
Integer input = STDIN as character
If(input - 1 == 0):
Jump to Label EXIT
input = input - 48
result = result * 10
result = result + input
Go to the next iteration of LOOP
Label EXIT:
Print result as integer to STDOUT
```
**Example run: [`input = "Hi!"`](https://tio.run/##K8/ILEktLkhMTv3/X0FBgYsLiEE0EHJycSpwcnKC@WAOhABxgaIgRSAhMAmkIAwwB6iZC2oIFyfQnP//PTIVGQE)**
```
Command Explanation Stack Heap STDIN STDOUT STDERR
SSSN Push 0 [0]
NSSN Create Label LOOP [0]
SSSN Push 0 [0,0]
SNS Duplicate top (0) [0,0,0]
TNTS Read STDIN as character [0,0] {0:72} H
TTT Retrieve at address (0) [0,72] {0:72}
SNS Duplicate top (72) [0,72,72] {0:72}
SSSTN Push 1 [0,72,72,1] {0:72}
TSST Subtract top two (72-1) [0,72,71] {0:72}
NTSSN If 0: Jump to Label EXIT [0,72] {0:72}
SSSTTSSSN Push 48 [0,72,48] {0:72}
TSST Subtract top two (72-48) [0,24] {0:72}
SNT Swap top two [24,0] {0:72}
SSSTSTSN Push 10 [24,0,10] {0:72}
TSSN Multiply top two (0*10) [24,0] {0:72}
TSSS Add top two (24+0) [24] {0:72}
NSNN Jump to Label LOOP [24] {0:72}
SSSN Push 0 [24,0] {0:72}
SNS Duplicate top (0) [24,0,0] {0:72}
TNTS Read STDIN as character [24,0] {0:105} i
TTT Retrieve at address (0) [24,105] {0:105}
SNS Duplicate top (105) [24,105,105] {0:105}
SSSTN Push 1 [24,105,105,1] {0:105}
TSST Subtract top two (105-1) [24,105,104] {0:105}
NTSSN If 0: Jump to Label EXIT [24,105] {0:105}
SSSTTSSSN Push 48 [24,105,48] {0:105}
TSST Subtract top two (106-48) [24,57] {0:105}
SNT Swap top two [57,24] {0:105}
SSSTSTSN Push 10 [57,24,10] {0:105}
TSSN Multiply top two (24*10) [57,240] {0:105}
TSSS Add top two (57+240) [297] {0:105}
NSNN Jump to Label LOOP [297] {0:105}
SSSN Push 0 [297,0] {0:105}
SNS Duplicate top (0) [297,0,0] {0:105}
TNTS Read STDIN as character [297,0] {0:33} !
TTT Retrieve at address (0) [297,33] {0:33}
SNS Duplicate top (33) [297,33,33] {0:33}
SSSTN Push 1 [297,33,33,1] {0:33}
TSST Subtract top two (33-1) [297,33,32] {0:33}
NTSSN If 0: Jump to Label EXIT [297,33] {0:33}
SSSTTSSSN Push 48 [297,33,48] {0:33}
TSST Subtract top two (33-48) [297,-15] {0:33}
SNT Swap top two [-15,297] {0:33}
SSSTSTSN Push 10 [-15,297,10] {0:33}
TSSN Multiply top two (297*10) [-15,2970] {0:33}
TSSS Add top two (57+240) [2955] {0:33}
NSNN Jump to Label LOOP [2955] {0:33}
SSSN Push 0 [2955,0] {0:33}
SNS Duplicate top (0) [2955,0,0] {0:33}
TNTS Read STDIN as character [2955,0] {0:1} ␁
TTT Retrieve at address (297) [2955,1] {0:1}
SNS Duplicate top (1) [2955,1,1] {0:1}
SSSTN Push 1 [2955,1,1,1] {0:1}
TSST Subtract top two (1-1) [2955,1,0] {0:1}
NTSSN If 0: Jump to Label EXIT [2955,1] {0:1}
NSSSN Create Label EXIT [2955,1] {0:1}
SNN Discard top [2955] {0:1}
TNST Print as integer [] {0:1} 2955
error
```
The program stops with an error: no exit defined.
] |
[Question]
[
I have a problem at work. I need to compare two numbers that come as strings from two different databases. The numbers may come with leading zeroes and/or leading/trailing spaces. So I may have `"0001 "` from one database and `" 1 "` from the other one.
I solved the problem in C# with the following code:
>
> `Func<string, string, bool> f = (a,b) => int.Parse(a.Trim()) == int.Parse(b.Trim())`
>
>
>
**The challenge**
This is a really simple challenge, suitable for beginners and any kind of esoteric languages. Given two numbers as strings that may come with leading zeroes and/or leading/trailing spaces, write the shortest code that checks if the two strings represent the same number.
* The inputs need to be two strings or the equivalent in your language (a char array is OK), and they will always represent integer values greater than zero.
* The output must be any two consistent values that represent a truthy value and a falsey value.
**Examples**
```
A B Result
----------------------------
"0001" "1 " true
"1450" "1450 " true
"0010001 " " 10001 " true
"0010000" " 10 " false
"101023" "101024" false
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so may the shortest code for each language win!
[Answer]
# [Javascript](https://www.javascript.com/), 11 bytes
```
a=>b=>+a==b
```
Abusing Javascript's casting rules a bit; `+a` coerces `a` into a numeric type.
*-6 bytes* thanks to [Shaggy](https://codegolf.stackexchange.com/questions/152860/compare-two-numbers-given-as-strings/152873?noredirect=1#comment373423_152873) and [Martin Ender♦](https://codegolf.stackexchange.com/questions/152860/compare-two-numbers-given-as-strings/152873?noredirect=1#comment373424_152873)
Also a cool take by [LiefdeWen](https://codegolf.stackexchange.com/questions/152860/compare-two-numbers-given-as-strings/152873?noredirect=1#comment373425_152873):
```
a=>b=>~~a==~~b
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 1 byte
```
Q
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/8P9/AwNDAyBW4FKA0AoA "05AB1E – Try It Online")
**Explanation**
Comparison for equality `Q` will automatically try to evaluate strings as ints before comparing.
[Answer]
# [Operation Flashpoint](https://en.wikipedia.org/wiki/Operation_Flashpoint:_Cold_War_Crisis) scripting language, 33 bytes
```
f={call format(["%1==%2"]+_this)}
```
**Call with:**
```
hint format["%1\n%2\n%3\n%4\n%5",
["0001", "1 "] call f,
["1450", "1450 "] call f,
["0010001 ", " 10001 "] call f,
["0010000", " 10 "] call f,
["101023", "101024"] call f]
```
**Output:**
[](https://i.stack.imgur.com/yx1eJ.jpg)
## Alternative version (41 bytes):
```
f={{t=call _x;r=t==s;s=t}forEach _this;r}
```
Still 5 bytes shorter than the more straightforward `f={t=_this;call(t select 0)==call(t select 1)}`
**39 bytes:**
```
f={{t=call _x;r=t==s;s=t}count _this;r}
```
`count` (which returns the size of an array) works instead of `forEach`, because you can give it a "lambda" that is used as a condition to count only the array elements that meet that condition. The "condition" used in this case is not a valid condition, but it doesn't matter here because it doesn't cause an error and the return value of the `count` is not needed.
[Answer]
# [Taxi](https://bigzaphod.github.io/Taxi/), 488 bytes
```
Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to The Babelfishery.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 l 1 r.Pickup a passenger going to Equal's Corner.Pickup a passenger going to Equal's Corner.Go to Equal's Corner:n 1 l 1 l 1 l.Switch to plan "b" if no one is waiting.'1' is waiting at Writer's Depot.[b]'0' is waiting at Writer's Depot.Go to Writer's Depot:n 1 l 1 r.Pickup a passenger going to Post Office.Go to Post Office:n 1 r 2 r 1 l.
```
[Try it online!](https://tio.run/##lVHLCsIwELz7FYOX3kLrsUcfeFRQ8CAe0rJtF0tSk0j162v6UHyA4sKy7DCZ2TBOXrhplhpOY62twyrLOKW4RoTSt2mnWHN6PFeQqKS1pHIyyDWrvH21LQhTmVCZsS3IXP8j987vcGzv9l/VFqezLAOLmTaK/qL2tq9grAbTrsWmZpcWLa0qpcI4GYMzKA2tCGxRS3ZeXARR8LRCOuwMOzJed06VdmKfHILwB6e/5xV83PP9Z0@pic8cVZfhZMixacIwCn2NgHbC1w0 "Taxi – Try It Online")
Ungolfed:
```
Go to Post Office: west 1st left 1st right 1st left.
Pickup a passenger going to The Babelfishery.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: south 1st left 1st right.
Pickup a passenger going to Equal's Corner.
Pickup a passenger going to Equal's Corner.
Go to Equal's Corner: north 1st left 1st left 1st left.
Switch to plan "b" if no one is waiting.
'1' is waiting at Writer's Depot.
[b]
'0' is waiting at Writer's Depot.
Go to Writer's Depot: north 1st left 1st right.
Pickup a passenger going to Post Office.
Go to Post Office: north 1st right 2nd right 1st left.
```
Taxi is (relatively) well-suited to this challenge because strings are the only input or output type allowed. `The Babelfishery` is what converts strings to number (and vice versa) and it handles stripping all the spaces and leading zeroes. It will also handle negative numbers if the `-` is immediately before the first digit. After that, `Equal's Corner` checks the two values against each other and `Writer's Depot` provides the output in string format. Output is `1` for truthy and `0` for falsey.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 27 bytes
```
f(s,t){s=atoi(s)==atoi(t);}
```
With `-O0` (which is the default setting).
[Try it online!](https://tio.run/##hY5BCoMwEEX3nmIIFDJgIVG7Em/SjUSULExLk5149vgzbts6m3nMPD7f3Rfncp51rBNvcRjTy@vIwwmJ@z37kGgdfdBcbRVh3h@cZq1u0zOomkDGGAtStrwVc//Ds93DiIf9z0NciaTi0onXuiQT9K8uniQV4DatlCjUibrnAw)
# C, 32 bytes
```
f(s,t){return atoi(s)==atoi(t);}
```
[Try it online!](https://tio.run/##hY67CsMwDEX3fIUwFCxIwW7TKeRPugS3KR7qFkeZQr7dvVbXPrToIB0uN@xvIZQy2bkVXvNVlpxolEe0Mw@DgnC/lZiE7mNMlpu1Icwz4zRZs7uck2kJ5JzzIOPr2zD3XzzfnZx62L88xNVIqi698b@uyQT9o4snaQW4h6OWqNSpupUX)
[Answer]
# [J](http://jsoftware.com/), 4 bytes
```
=&do
```
Compare `=` after `&` evaluating `do`. Can also be `=&".`
[Try it online!](https://tio.run/##y/r/P81WT8FWTUnvf2pyRr6CuoGBgaG6AhikAbG6IYgFFuCCKDA0MTVAUQDkoygAGgAyBCQGVqAA4QIZKArAhkAUAFVA7IBZAVRgZKyOsALENwHx/wMA "J – Try It Online")
[Answer]
## [Retina](https://github.com/m-ender/retina), 11 bytes
```
.+
$*
D`
¶$
```
[Try it online!](https://tio.run/##K0otycxL/K@qEZyg819Pm0tFi8slgevQNpX//w0MDAx1DBWAgMvQxNRAB0QocAEFQRIKOgoQGiZioKMAFAGpBXKNjHXAlAkA "Retina – Try It Online")
Input is linefeed separated, but the test suite uses comma separation for convenience. Prints `1` for equality and `0` for inequality.
### Explanation
```
.+
$*
```
Convert each line to unary. This ignores leading zeros and spaces.
```
D`
```
Deduplicate: clear the second line if both are the same.
```
¶$
```
Check that the string now ends in a linefeed.
[Answer]
# [Python 3](https://docs.python.org/3/), 25 bytes
```
lambda a,b:int(a)==int(b)
```
[Try it online!](https://tio.run/##TY49DsMgDIV3TmF5ChWDadIlEiehDKAWNVJLosCS01NMVKlenvW955/tKK81jTWae337T3h48CrMSyqDl8awBlnLM5cMBqxFItKoADW0Qqcs6ulGqLqcoCU4BRyDs/03qPNm/OYbvY59J3cTOidEXHfgq7CkrnkWsO38ThwuDKSsXw "Python 3 – Try It Online")
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 22 bytes
```
(([{}]{})[{(){}}](){})
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/X0Mjuro2trpWM7paQ7O6tjYWRGr@/29gYGgAxFwKYEoBAA "Brain-Flak – Try It Online")
Saved 4 bytes thanks to [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king).
[Answer]
# [Triangularity](https://github.com/Mr-Xcoder/Triangularity), 17 bytes
```
..)..
.Ii).
@Ii=.
```
[Try it online!](https://tio.run/##KynKTMxLL81JLMosqfz/X09PU0@PS88zU1OPy8Ez01bv/38DA0MDIOYCkwA "Triangularity – Try It Online")
Triangularity is, for once, competitive!
### How it works
Triangularity requires the code to have a triangular distribution of the dots. That is, the length of each row must be equal the number of rows multiplied by 2 and decremented, and each row must have (on each side) a number of dots equal to its position in the program (the bottom row is row 0, the one above it is row 1 and so forth). Keeping this in mind, let's analyse how the code works:
```
..).. || Push a 0 onto the stack.
.Ii || Get the 0th input and cast it to an integer.
). || Push another 0 onto the stack.
@I || Increment the ToS => 1. Get the first input.
i=. || Then cast it to an integer and compare their equality.
```
[Answer]
## [Alice](https://github.com/m-ender/alice), 7 bytes
```
X/n
o@i
```
[Try it online!](https://tio.run/##S8zJTE79/z9CP48r3yHz/38DAwNDLkMFIAAA "Alice – Try It Online")
Any non-digit separator works. Prints `1` for equality and `0` otherwise.
### Explanation
```
X XOR, does nothing.
/ Switch to Ordinal mode.
i Read all input as a string.
/ Switch to Cardinal mode.
X XOR. Implicitly finds all integers in the string and pushes them separately
onto the stack. The XOR gives 0 if the values are identical.
n Logical NOT. Gives 1 for equal inputs and 9 otherwise.
/ Switch to Ordinal.
o Print the 0 or 1 as a string.
/ Switch to Cardinal.
@ Terminate the program.
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt/), 3 bytes
```
¥Vn
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=pVZu&input=IjA4IiAKIiA4ICI=)
Converts the second input to an integer and compares equality with the first.
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 4 bytes
*3 bytes saved thanks to @Adám*
```
=/⍎¨
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R2wRb/Ue9fYdWADkK6gYGBobqCuqGCkCgzgUUMDQxNVCHUArqIFEusCpDkEKggLoChAVkICRAGhSAEgpgHWBTgOJGxupQhglIGAA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# jq, 24 characters
```
map(tonumber)|.[0]==.[1]
```
The 2 strings are passed as items of an array.
Sample run:
```
bash-4.4$ jq 'map(tonumber)|.[0]==.[1]' <<< '["0010001 ", " 10001 "]'
true
bash-4.4$ jq 'map(tonumber)|.[0]==.[1]' <<< '["0010000", " 10 "]'
false
```
[Try it online!](https://tio.run/##yyr8/z83sUCjJD@vNDcptUizRi/aINbWVi/aMPb//2glAwNDAyBWUNJRUFKAMBWUYgE "jq – Try It Online") ([All test cases](https://tio.run/##lY7NCsIwEITP9imWPbVQQ6L1UuiTxByqRlD6Z5qCYH11Y7ZFKUUPzSU7y3w7c705x6SCHtDq1oJ/KexDRiLCGNDotivsZNuXeRPauurKgzZRzyRXWcakUINd3xt9tPo02D8iwpVzMqDjjyEGU5DIORdIO48J@kmoyQ3vsqbT8IznqEh2/Iv6eQHqQykYqCyMI@AS1AcT6tmh8Qw950WrfxT26GaLY2Gak39ooF51Yy911bq1eQM "jq – Try It Online"))
[Answer]
# [Husk](https://github.com/barbuz/Husk), 3 bytes
```
¤=r
```
[Try it online!](https://tio.run/##yygtzv6vcGhbrtujpsb/h5bYFv3//z9aQ8nAwMBQSUfJUAEIlDR1NJQMTUwNQAJACiIAVABSpAAUVICwkMVBahWA4jDdQEEjY5B@EMNESTMWAA "Husk – Try It Online")
### Explanation
```
¤ -- combine both arguments of ..
= -- .. equality ..
r -- .. with read
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 20 bytes
```
param($a,$b)+$a-eq$b
```
Similar to the JavaScript answer, just longer because PowerShell doesn't have currying. Uses `+` to cast the first string to integer, and then the `-eq`uals automatically casts the second string to integer. Output is True/False.
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVRRyVJU1slUTe1UCXp////6gYGBobq/9UVDBUU1AE "PowerShell – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
t€⁶V€€ḌE
```
[Try it online!](https://tio.run/##y0rNyan8/7/kUdOaR43bwkBU05qHO3pc////H61kYGBgqKSjoGSoAARKsQA "Jelly – Try It Online") or see the **[test suite](https://tio.run/##y0rNyan8/7/kUdOaR43bwkBU05qHO3pc/x9uB7Ii//@PVjIwMDBU0lFQMlQAAqVYHYVoJUMTUwOwEJCGCgEVgRQqgIQVIEwUGZB6oAxQCm4IUNzIGGwMiGWiFAsA "Jelly – Try It Online")**
35 answers, and no Jelly submission? Takes the argument as a list (`["0001", "1 "]` for the first example)
## How it works
```
t€⁶V€€ḌE - Main link. Argument: list e.g. ["0001", "1 "]
€ - For €ach element... ["0001", "1"]
t - trim from both sides...
⁶ - spaces
€ - For €ach element...
V€ - evaluate €ach character [[0, 0, 0, 1], [1]]
Ḍ - Convert from digits [1, 1]
E - Are they equal? 1
```
[Answer]
# Excel, 8 bytes
```
=A1-B1=0
```
Excel does the string to num conversion for us.
(To input as string, prefix values with `'`.)
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 19 bytes
```
$args-join'-eq'|iex
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/XyWxKL1YNys/M09dN7VQvSYzteL////qCkBgAALmlgrq/9WBpII6AA "PowerShell – Try It Online")
`-join` the argument array (`$args`) with the string representation of the comparison operator (`-eq`) then evaluate the expression with `Invoke-Expression` (`iex`).
[Answer]
# Q (Kdb+), 13 bytes
```
=/["J"$(x;y)]
```
## Explanation
(x;y) : a list of the two inputs.
"J"$ : casting each input to a long (7j) type from string (10c), which can correctly interpret
white space and leading 0s.
=/ : checks equality over elements in a list (each subsequent pair).
As there is only one pair, returns single boolian 0b/1b.
[Answer]
# T-SQL, 35 bytes
[Per our standards](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341), data is input via pre-existing table `t` with `varchar` fields `a` and `b`.
```
SELECT IIF(ABS(a)=ABS(b),1,0)FROM t
```
Returns `1` if they match, `0` if they don't.
A few of SQL's mathematical functions (including `ABS`, `FLOOR` and `CEILING`) will do an implicit conversion to numeric if given string parameters, this is shorter than an explicit `CAST(a AS INT)` or `CONVERT(INT,b)`, and works in this case since we know the input values are always positive.
`IIF` is specific to MS SQL 2012 and above, so no guarantee about other implementations.
[Answer]
# Excel VBA, 27 16 Bytes
-9 Thanks to @Nayrb and @TaylorScott
```
[C1]=[A1]-[B1]=0
```
Where you input the values on the Cells with `'string`.
Where `x` and `y` are the input Strings and `z` is a Boolean output.
If CInt(x)=CInt(y) Then z=1
Using [CInt](https://msdn.microsoft.com/en-us/vba/language-reference-vba/articles/type-conversion-functions)
[Answer]
# [R](https://www.r-project.org/), ~~28~~ 27 bytes
```
!diff(as.double(scan(,'')))
```
Reads numbers as strings, converts them to doubles and checks if their difference is not zero.
[Try it online!](https://tio.run/##K/r/XzElMy1NI7FYLyW/NCknVaM4OTFPQ0ddXVNT87@6goIBEBgZKyioK6gbGav/BwA "R – Try It Online")
*−1 byte thanks to [Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe)*
[Answer]
# [Lua](https://www.lua.org), 20 bytes
```
print(...-arg[2]==0)
```
[Try it online!](https://tio.run/##yylN/P@/oCgzr0RDT09PN7EoPdoo1tbWQPP///8KCgYGpqYK/01NAQ "Lua – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 20 bytes
*-11 bytes thanks to Laikoni. -2 bytes thanks to Zgarb.*
```
a#b=0+read a==read b
```
[Try it online!](https://tio.run/##bY07DoBACER7TzFBOxvWT7mHwWii8Rv1/uuimxg/NDDMY2hl65thcE7iynK6NlJDrD175UbpJljUcwRfy9pNOxIQMxvSDWKQAT1dU5R8u168AX@tCSAFEOY/RGMu5PPD@1lO4YeKgtwB "Haskell – Try It Online")
[Answer]
# [Gema](http://gema.sourceforge.net/), 21 characters
```
*\n*=@cmpn{*;*;0;1;0}
```
No boolean in Gema. As the `@get-switch{}`/`@set-switch{}` functions use 0 and 1 to represent switch statuses, also used 0 and 1.
The 2 strings are passed on separate input lines.
Sample run:
```
bash-4.4$ gema '*\n*=@cmpn{*;*;0;1;0}' <<< $'0010001\n10001 '
1
bash-4.4$ gema '*\n*=@cmpn{*;*;0;1;0}' <<< $'0010000\n 10 '
0
```
[Answer]
# Perl 5, 9 + 1 (`-p`) = 10 bytes
```
$_=$_==<>
```
[try it online](https://tio.run/##K0gtyjH9/18l3haIbG3s/v83MDAwVAABLkMIaWJqoIBgcQGlwUq4FCA0TMSASwEoAlIG5BoZQyiTf/kFJZn5ecX/dQtyAA)
[Answer]
# [Stacked](https://github.com/ConorOBrien-Foxx/stacked), 8 bytes
```
[#~\#~=]
```
[Try it online!](https://tio.run/##VYzRCsIwDEXf@xUXKmQDLaluLwPF/5gDh/ZJxDK71/16TSpDbEo4nOTmncbbI9xz7u1ysctxyOcuGFMZoCJm9gR95Euvi/ZNy6sWXLUsawAk9aX/iWbke/4dEr8/UDmk2Iiv0cusw2YKccJzjKCtxOwVcU4Cu5M0ReccAl5zMoOu5Q8 "Stacked – Try It Online")
## Explanation
```
[#~\#~=] anonymous function
#~ eval TOS
\ swap top two
#~ eval TOS
= push equality of top two
```
[Answer]
# [Attache](https://github.com/ConorOBrien-Foxx/attache), 11 bytes
```
Same@Map&:N
```
[Try it online!](https://tio.run/##SywpSUzOSP3vkpqWmZcarZKm8z84MTfVwTexQM3K738sV0BRZl6JQ5qCrZ1CWDSXApBQMjAwMFTSUVAyVFCK1YEIGZqYGoCFgDRCFKgOpFYBJKMAZaLKGUClkEwCihsZg80CsUyUYrli/wMA "Attache – Try It Online")
This takes an array of strings, such as `V["0001", "1 "]`. Simply stated, `Map&:N` is a function that maps `N` over its argument, and `Same` checks that the array contains only equal members. (Fun fact: this function works for more than 2 string arguments.)
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 42 bytes
```
OUTPUT =EQ(EVAL(INPUT),EVAL(INPUT)) 1
END
```
[Try it online!](https://tio.run/##K87LT8rPMfn/n9M/NCQgNETB1jVQwzXM0UfD0w/I1dRBYmsqGHK5@rn8/29gYGgABFwKCoYGCgoA "SNOBOL4 (CSNOBOL4) – Try It Online")
Outputs 1 for truthy, nothing for falsey. Since (space) is the concatenation operator in SNOBOL, `EVAL`ing a number with leading/trailing spaces yields the number itself, and it also neatly takes care of any leading zeroes. `EQ` tests for numerical equality, conditionally setting `OUTPUT` to 1 on `Success`.
] |
[Question]
[
The challenge is simple: Draw a rainbow in as few bytes as possible
The specs for the rainbow are as follows:
* The figure must be exactly 400 pixels wide and 200 pixels high (optionally 401x201 if you want a single center pixel)
* The red ring should touch all borders of the figure (outer radius = 200 pixels)
* All rings shall have the same width (10 pixels)
+ The violet ring shall have an inner radius of 130 pixels
* The bow should be the upper half of a perfect circle
* The background shall be white (transparent is also accepted)
* The figure shall not have borders, (exception is made if the border can't be suppressed)
* Builtin rainbow making functions are not allowed!
The following colors are to be used in the rainbow:
[](https://i.stack.imgur.com/f4Sm1m.jpg)
This is code golf, so the shortest code in bytes win!
Example:
## [Rainbow](https://i.stack.imgur.com/740pF.png)
[Related, but different!](https://codegolf.stackexchange.com/questions/20379/create-a-seven-color-rainbow-with-animation)
[Answer]
# [Piet](http://www.dangermouse.net/esoteric/piet.html), 838 codels, several thousand pixels
Someone had to do it:
[](https://i.stack.imgur.com/nB1vN.png)
If you save this image you can [try it online](http://www.bertnase.de/npiet/npiet-execute.php)!
The actual Piet program is only the top ~125 pixels, which I created using a Python program I wrote.
Editing this afterwards really hurt my vision, I'll be tripping for days!
This outputs the image in an SVG format, because SVG really is (in my opinion) the simplest way to do this. I shamelessly stole Doorknob's SVG code. Outputs:

well, this really:
```
<svg viewBox='0 0 400 200'><circle cx='200' cy='200' r='200' fill='red'/><circle cx='200' cy='200' r='190' fill='#ff7f00'/><circle cx='200' cy='200' r='180' fill='yellow'/><circle cx='200' cy='200' r='170' fill='lime'/><circle cx='200' cy='200' r='160' fill='blue'/><circle cx='200' cy='200' r='150' fill='indigo'/><circle cx='200' cy='200' r='140' fill='#8f00ff'/><circle cx='200' cy='200' r='130' fill='white'/></svg>
```
Good luck beating this answer, non-Esolang users!
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), ~~107~~ ~~95~~ ~~92~~ ~~87~~ ~~84~~ 83 bytes
```
-200:200 0:200!PYyq10/k12-t8<*t0>*Q7B.561FTh.295Oh.51h4BPFTF6Bl.5hOh4B8$v255*k5M/YG
```
This works in [current release (14.0.0)](https://github.com/lmendo/MATL/releases/tag/14.0.0) of the language/compiler.
*EDIT (July 6, 2017)*: You can try it at [MATL Online!](https://matl.suever.net/?code=-200%3A200+0%3A200%21PYyq10%2Fk12-t8%3C%2at0%3E%2aQ7B.561FTh.295Oh.51h4BPFTF6Bl.5hOh4B8%24v255%2ak5M%2FYG&inputs=&version=14.0.0).
To check that the colors are correct, [remove the last five characters](https://matl.suever.net/?code=-200%3A200%2C0%3A200%21PYyq10%2Fk12-t8%3C%2at0%3E%2aQ7B.561FTh.295Oh.51h4BPFTF6Bl.5hOh4B8%24v255%2ak&inputs=&version=14.0.0) (you need to wait for a few seconds and scroll down to the end of the output).
[](https://i.stack.imgur.com/kAtWE.png)
### Explanation
The code has three main steps:
**Step 1**: Generate a 201x401 matrix with numbers from `1` to `8`. Pixels with value `1` are background (white), pixels with values `2`, ..., `8` represent each band of the rainbow.
Horizontal coordinates range from `-200` to `200` left to right, and vertical coordinates range from `0` to `200` bottom to top. So the origin (0,0) is bottom center, the upper left corner is (-200,200), etc.
The different bands of the rainbow are generated by computing the distance from each pixel to the origin and quantizing in steps of 10 pixels.
**Step 2**: Generate an 8x3 matrix defining the colormap. Each row is one of the necessary colors (white and the seven colors of the rainbow). Each value of the previous 201x401 matrix will be interpreted as an index to a row of this colormap.
We generate the colormap matrix using values between 0 and 1 for each color component, and then multiplying by 255 and rounding down. This way most values are initially 0 and 1, which will later become 0 and 255. Intermediate values are coded as values between 0 and 1 with 2 or 3 decimals, chosen so that when multiplied and rounded give the exact desired value.
**Step 3**: Display the image with that colormap.
```
% STEP 1: CREATE MATRIX DEFINING THE RAINBOW BANDS
-200:200 % row vector [-200, -199, ..., 200]
0:200 % row vector [0, 1, ..., 200]
!P % transpose and flip: convert into column vector [200; 199; ...; 0]
Yy % hypotenuse function with broadcast: distance from each point to (0,0)
q10/k % subtract 1, divide by 10, floor (round down). Gives 20 circular bands
% 10 pixels wide, with values from 0 to 19
12- % subtract 12
t8<* % values larger than 7 are set to 0
t0>* % values less than 0 are set to 0. We now have 7 bands with values
% 1, ..., 7, and the white background with value 0
Q % add 1: white becomes 1, bands become 2, ..., 8
% STEP 2: CREATE MATRIX DEFINING THE COLORMAP
7B % first row: [1 1 1] (7 converted to binary: color white)
.561FTh % second row (light purple)
.295Oh.51h % third row (dark purple)
4BP % fourth row: [0 0 1] (4 converted to binary and flipped: blue)
FTF % fifth row (green)
6B % sixth row: [1 1 0] (6 converted to binary: yellow)
l.5hOh % seventh row: orange
4B % eigth row: [1 0 0] (4 converted to binary: red)
8$v % vertically concatenate the 8 eight rows
255*k % multiply by 255 and round down. Gives exact color values
5M/ % push 255 again and divide. This is needed because colors in MATL are
% defined between 0 and 1, not between 0 and 255
% STEP 3: DISPLAY
YG % display image with that colormap
```
[Answer]
# Minecraft 1.10 (almost), 2677 characters one-command, 868 [blytes](https://codegolf.meta.stackexchange.com/questions/7377/programming-in-minecraft-redstone-how-to-measure-program-size/7397#7397)
Well I sure picked a verbose language.
```
summon FallingSand ~ ~1 ~ {Block:log,Time:1,Passengers:[{id:FallingSand,Block:redstone_block,Time:1,Passengers:[{id:FallingSand,Block:activator_rail,Time:1,Passengers:[{id:MinecartCommandBlock,Command:"summon ArmorStand ~ ~ ~ {Tags:[\"b\"]}"},{id:MinecartCommandBlock,Command:"summon Pig ~ ~ ~ {NoAI:1b}"},{id:MinecartCommandBlock,Command:setblock ~-1 ~-2 ~6 chain_command_block 3 replace {auto:1,Command:"execute @e[tag=b] ~ ~ ~ execute @e[rm=200] ~ ~ ~ tp @e[c=1] ~ -99 ~"}},{id:MinecartCommandBlock,Command:setblock ~-1 ~-2 ~5 chain_command_block 3 replace {auto:1,Command:"execute @e[tag=b] ~ ~ ~ execute @e[rm=190,r=200] ~ ~ ~ setblock ~ ~ ~ wool 14"}},{id:MinecartCommandBlock,Command:setblock ~-1 ~-2 ~4 chain_command_block 3 replace {auto:1,Command:"execute @e[tag=b] ~ ~ ~ execute @e[rm=180,r=190] ~ ~ ~ setblock ~ ~ ~ wool 1"}},{id:MinecartCommandBlock,Command:setblock ~ ~-2 ~4 chain_command_block 4 replace {auto:1,Command:"execute @e[tag=b] ~ ~ ~ execute @e[rm=170,r=180] ~ ~ ~ setblock ~ ~ ~ wool 4"}},{id:MinecartCommandBlock,Command:setblock ~ ~-2 ~5 chain_command_block 2 replace {auto:1,Command:"execute @e[tag=b] ~ ~ ~ execute @e[rm=160,r=170] ~ ~ ~ setblock ~ ~ ~ wool 13"}},{id:MinecartCommandBlock,Command:setblock ~ ~-2 ~6 chain_command_block 2 replace {auto:1,Command:"execute @e[tag=b] ~ ~ ~ execute @e[rm=150,r=160] ~ ~ ~ setblock ~ ~ ~ wool 11"}},{id:MinecartCommandBlock,Command:setblock ~ ~-2 ~7 chain_command_block 2 replace {auto:1,Command:"execute @e[tag=b] ~ ~ ~ execute @e[rm=140,r=150] ~ ~ ~ setblock ~ ~ ~ wool 10"}},{id:MinecartCommandBlock,Command:setblock ~ ~-2 ~8 chain_command_block 2 replace {auto:1,Command:"execute @e[tag=b] ~ ~ ~ execute @e[rm=130,r=140] ~ ~ ~ setblock ~ ~ ~ wool 2"}},{id:MinecartCommandBlock,Command:setblock ~1 ~-2 ~8 chain_command_block 4 replace {auto:1,Command:"tp @e[type=Cow] ~1 ~ ~"}},{id:MinecartCommandBlock,Command:setblock ~1 ~-2 ~7 chain_command_block 3 replace {auto:1,Command:"tp @e[type=Bat] ~-1 ~ ~"}},{id:MinecartCommandBlock,Command:setblock ~1 ~-2 ~6 chain_command_block 3 replace {auto:1,Command:"execute @e[type=Pig] ~ ~ ~ summon Bat ~ ~ ~ {NoAI:1b}"}},{id:MinecartCommandBlock,Command:setblock ~1 ~-2 ~5 chain_command_block 3 replace {auto:1,Command:"execute @e[type=Pig] ~ ~ ~ summon Cow ~ ~ ~ {NoAI:1b}"}},{id:MinecartCommandBlock,Command:setblock ~1 ~-2 ~4 repeating_command_block 3 replace {auto:1,Command:"tp @e[type=Pig] ~ ~1 ~"}},{id:MinecartCommandBlock,Command:setblock ~ ~ ~1 command_block 0 replace {Command:fill ~ ~-3 ~-1 ~ ~ ~ air}},{id:MinecartCommandBlock,Command:setblock ~ ~-1 ~1 redstone_block},{id:MinecartCommandBlock,Command:kill @e[type=MinecartCommandBlock,r=1]}]}]}]}
```
Make a new Superflat world, paste that mess into an Impulse command block, set your render distance fairly high, and run it. Break the armor stand when your computer stops lagging.
The result is 400 blocks across and 200 blocks tall, as requested.
I used [MrGarretto's one command generator](http://mrgarretto.com/cmdcombiner) to pack everything together, and then modified the result of that a little bit to save a couple more bytes. Here's the input to it:
```
INIT:summon ArmorStand ~ ~ ~ {Tags:["b"]}
INIT:summon Pig ~ ~ ~ {NoAI:1b}
tp @e[type=Pig] ~ ~1 ~
execute @e[type=Pig] ~ ~ ~ summon Cow ~ ~ ~ {NoAI:1b}
execute @e[type=Pig] ~ ~ ~ summon Bat ~ ~ ~ {NoAI:1b}
tp @e[type=Bat] ~-1 ~ ~
tp @e[type=Cow] ~1 ~ ~
execute @e[tag=b] ~ ~ ~ execute @e[rm=130,r=140] ~ ~ ~ setblock ~ ~ ~ wool 2
execute @e[tag=b] ~ ~ ~ execute @e[rm=140,r=150] ~ ~ ~ setblock ~ ~ ~ wool 10
execute @e[tag=b] ~ ~ ~ execute @e[rm=150,r=160] ~ ~ ~ setblock ~ ~ ~ wool 11
execute @e[tag=b] ~ ~ ~ execute @e[rm=160,r=170] ~ ~ ~ setblock ~ ~ ~ wool 13
execute @e[tag=b] ~ ~ ~ execute @e[rm=170,r=180] ~ ~ ~ setblock ~ ~ ~ wool 4
execute @e[tag=b] ~ ~ ~ execute @e[rm=180,r=190] ~ ~ ~ setblock ~ ~ ~ wool 1
execute @e[tag=b] ~ ~ ~ execute @e[rm=190,r=200] ~ ~ ~ setblock ~ ~ ~ wool 14
execute @e[tag=b] ~ ~ ~ execute @e[rm=200] ~ ~ ~ tp @e[c=1] ~ -99 ~
```
That's a total of 15 1.9+ command blocks, and 838 bytes, so 15\*2 + 838 = 868 [blytes](https://codegolf.meta.stackexchange.com/questions/7377/programming-in-minecraft-redstone-how-to-measure-program-size/7397#7397).
Here's the (almost) part, it's missing a corner and edge. It logically shouldn't - Minecraft bug? Would be exactly 400x200 blocks if it wasn't for that. Not much I can do.
[](https://i.stack.imgur.com/emrVR.png)
[Answer]
## Pyth, ~~150~~ ~~149~~ 128 bytes
```
"<svg viewBox=0,0,400,200>"V8s["<circle cx=200 cy=200 r="-200*TN" fill="@c"red #ff7f00 #ff0 #0f0 #00f indigo #8f00ff #fff"dN" />
```
Outputs in SVG:
```
<svg viewBox=0,0,400,200>
<circle cx=200 cy=200 r=200 fill=red />
<circle cx=200 cy=200 r=190 fill=#ff7f00 />
<circle cx=200 cy=200 r=180 fill=#ff0 />
<circle cx=200 cy=200 r=170 fill=#0f0 />
<circle cx=200 cy=200 r=160 fill=#00f />
<circle cx=200 cy=200 r=150 fill=indigo />
<circle cx=200 cy=200 r=140 fill=#8f00ff />
<circle cx=200 cy=200 r=130 fill=#fff />
```

Thanks to [@MamaFunRoll](https://codegolf.stackexchange.com/users/41247/mama-fun-roll) for 16 bytes and [@PatrickRoberts](https://codegolf.stackexchange.com/users/42091/patrick-roberts) for 6 more!
[Answer]
# Mathematica ~~152~~ ~~144~~ 126 bytes
```
Graphics@MapIndexed[{#,Disk[{0,0},4-#/5&@@#2,{Pi,0}]}&,RGBColor/@TextWords@"#f00 #ff7f00 #ff0 #0f0 #00f #4b0082 #8f00ff #fff"]
```
[](https://i.stack.imgur.com/EfQEu.png)
Thanks @CatsAreFluffy for shaving off 8 bytes & @njpipeorgan for a further 18 :)
[Answer]
## vim, ~~165~~ ~~142~~ 139
```
i<svg viewBox=0,0,400,200><cr><circle cx=2<C-n> cy=2<C-n> r=2<C-n> fill=red<cr>#ff7f00<cr>#ff0<cr>#0f0<cr>#00f<cr>indigo<cr>#8f00ff<cr>#fff<esc>2Gqq0y4f=jPBB10<C-x>@qq@qV2G:norm A /><cr>
```
Yeesh, this is clunky. There's got to be improvements that can be made.
Outputs as SVG, like [my Pyth answer](https://codegolf.stackexchange.com/a/75397/3808).
Thanks to [@MyHamDJ](https://codegolf.stackexchange.com/users/31716/my-ham-dj) for shaving off 3 bytes!
[Answer]
# HTML+SVG+ES6, 169
```
<svg width=400 viewBox=0,0,40,20 onload="this.innerHTML=`f00
ff7f00
ff0
0f0
00f
4b0082
8f00ff
fff`.replace(/.+/g,c=>`<circle cx=20 cy=20 r=${--r} fill=#${c} />`,r=21)"/>
```
[Answer]
# JavaScript (ES6), ~~171~~ 158 bytes
```
document.write`<svg width=400 height=200>${`f00
ff7f00
ff0
0f0
00f
4b0082
8f00ff
fff`.replace(/.+/g,c=>`<circle cx=200 cy=200 r=${i--}0 fill=#${c} />`,i=20)}`
```
Credit to @edc65 for the idea to convert
```
`[...].map((c,i)=>...)`
```
to
```
`...`.replace(/.+/g,c=>...,i=20)
```
It may look longer but the amount of bytes saved in compressing the array to a string is well worth the conversion. (It saves 13 bytes in this case)
## Demo
```
document.write`<svg width=400 height=200>${`f00
ff7f00
ff0
0f0
00f
4b0082
8f00ff
fff`.replace(/.+/g,c=>`<circle cx=200 cy=200 r=${i--}0 fill=#${c} />`,i=20)}`
```
[Answer]
# Ruby with Shoes, 155 bytes
```
Shoes.app(width:400,height:200){background'fff'
8.times{|i|stroke fill %w{f00 ff7f00 ff0 0f0 00f 4b0082 8f00ff fff}[i]
oval left:i*=10,top:i,radius:200-i}}
```
Sample output:

[Answer]
# HTML (162) + CSS (146)
```
body{height:200px;width:400px}div{height:100%;box-sizing:border-box;border-radius:50% 50% 0 0/100% 100% 0 0;border:solid;border-width:10px 10px 0}
```
```
<div style=color:red><div style=color:#FF7F00><div style=color:#FF0><div style=color:#0F0><div style=color:#00F><div style=color:#4B0082><div style=color:#8F00FF>
```
---
# HTML (224) + CSS (128)
```
body{height:200px;width:400px}div{height:100%;box-sizing:border-box;border-radius:50% 50% 0 0/100% 100% 0 0;padding:10px 10px 0}
```
```
<div style=background:red><div style=background:#FF7F00><div style=background:#FF0><div style=background:#0F0><div style=background:#00F><div style=background:#4B0082><div style=background:#8F00FF><div style=background:#FFF>
```
[Answer]
# LaTeX, 290 bytes
```
\documentclass{proc}\input tikz\begin{document}\def\z#1!#2!#3!#4!{\definecolor{t}{rgb}{#1,#2,#3}\fill[color=t](200pt,0)circle(#4pt);}\tikz{\clip(0,0)rectangle(400pt,200pt);\z1!0!0!200!\z1!.5!0!190!\z1!1!0!180!\z0!1!0!170!\z0!0!1!160!\z.29!0!.51!150!\z.56!0!1!140!\z1!1!1!130!}\end{document}
```
[Try it here](https://www.overleaf.com/4619176dnrxkz#/13963792/).
### Explanations
```
\documentclass{proc}
\input tikz
\begin{document}
%Define macro "\z" with 4 arguments.
% The first 3 arguments are rgb values for the color
% Last argument is the radius in pt that we draw a full circle with
\def\z#1!#2!#3!#4!
{\definecolor{t}{rgb}{#1,#2,#3}
\fill[color=t](200pt,0)circle(#4pt);}
% Start a Tikz figure
\tikz{
% We only draw the top half of the circle
\clip(0,0)rectangle(400pt,200pt);
% Draw each circle from biggest to smallest
\z1!0!0!200!
\z1!.5!0!190!
\z1!1!0!180!
\z0!1!0!170!
\z0!0!1!160!
\z.29!0!.51!150!
\z.56!0!1!140!
% Draw a white circle last
\z1!1!1!130!
}
\end{document}
```
[Answer]
# SpecBAS - ~~318~~ 254 bytes
If we're drawing rainbows, then it seems like a good place to use the successor to ZX Spectrum BASIC.
```
1 p,k=20,x1=0,x2=400,y=200
2 FOR EACH s IN [16711680,16744192,16776960,65280,255,4915330,9371903]: PALETTE p,s: INC p: NEXT s
3 CLS 15: DRAW 0,200 TO 70,200: DRAW 330,200 TO 400,200
4 FOR i=1 TO 7
5 INK k: DRAW x1,y TO x2,y,-PI: DRAW x1+10,y TO x2-10,y,-PI: FILL x1+5,190
6 x1+=10,x2-=10,k+=1
7 NEXT i
```
Line 2 sets up the palette for the specific RGB values needed (and is probably not helping the byte count) as standard Spectrum colours didn't match up.
The `DRAW` command can take an extra parameter which makes it turn through a number of ~~degrees~~ radians between x1,y1 and x2,y2. Finally it finds a gap in the semicircles just drawn and flood fills with the current colour.
[](https://i.stack.imgur.com/ASIMa.png)
[Answer]
# [Tcl/Tk](http://wiki.tcl.tk/), 263 bytes
```
canvas .c -bg #FFF -bo 0 -highlightt 0;pack .c -e 1 -f both;wm ge . 400x200;foreach {r c} {200 #FF0000 190 #FF7F00 180 #FFFF00 170 #00FF00 160 #0000FF 150 #4B0082 140 #8F00FF 130 #FFF} {.c cr o -$r -$r $r $r -outline $c -f $c};after 100 {.c x s -5 u;.c y s -10 u}
```
Alas, this kind of question always favors some esoteric languages...
That said, Tcl/Tk really makes graphics operations all of: easy, short, and *readable*.
That said, I've sacrificed readability to crunch options down to as few characters as possible. I don't imagine crunching the list of colors will help much compared to code to unpack it...
For comparison, here's the uncrunched code (380 bytes):
```
canvas .c -bg #FFF -borderwidth 0 -highlightthickness 0
pack .c -expand yes -fill both
wm geometry . 400x200
foreach {r c} {
200 #FF0000
190 #FF7F00
180 #FFFF00
170 #00FF00
160 #0000FF
150 #4B0082
140 #8F00FF
130 #FFFFFF
} {
.c create arc -$r -$r $r $r -extent 180 -outline $c -fill $c
}
after 100 {
.c xview scroll -5 units
.c yview scroll -10 units
}
```
The `after` command was unfortunately necessary since no scrolling (of the canvas's coordinate origin) can be done before the window is mapped to the screen.
Also, the crunched code actually draws a *full* rainbow (using a circle instead of an arc) and just relies on window clipping...
Anyway, I hope y'all enjoy. :O)
[Answer]
## Java, 354 bytes
```
public void r() throws IOException{BufferedImage i=new BufferedImage(400,200,2);Graphics2D g=i.createGraphics();g.setStroke(new BasicStroke(10));int[]c={0xFF0000,0xFF7F00,0xFFFF00,0xFF00,255,0x4B0082,0x8F00FF};for(int v=0;v<7;v ++){g.setColor(new Color(c[v]));g.drawArc(v*10+5,v*10+5,390-v*20,390-v*20,0,360);}ImageIO.write(i,"PNG",new File("a.png"));}}
```
Just uses the `Graphics2D` class to draw 7 arcs, with an array to store the colors. I'm sure it can be improved further.
Ungolfed code:
```
public void ungolfed() throws IOException {
BufferedImage i = new BufferedImage(400, 200, 2); // 2 is TYPE_INT_ARGB
Graphics2D g = i.createGraphics();
g.setStroke(new BasicStroke(10));
int[] c = {0xFF0000, 0xFF7F00, 0xFFFF00, 0x00FF00, 0x0000FF, 0x4B0082, 0x8F00FF};
for(int v = 0; v < 7; v ++) {
g.setColor(new Color(c[v]));
g.drawArc(v * 10 + 5, v * 10 + 5, 390 - v * 20, 390 - v * 20, 0, 360);
}
ImageIO.write(i, "PNG", new File("a.png"));
}
```
[Answer]
## [Bubblegum](http://esolangs.org/wiki/Bubblegum), ~~139~~ 119 bytes
Hexdump:
```
00000000: b329 2e4b 5728 cb4c 2d77 caaf b035 d031 .).KW(.L-w...5.1
00000010: d031 3130 d031 3230 b0e3 b249 ce2c 4ace .110.120...I.,J.
00000020: 4955 48ae b005 f215 922b c154 1198 4ccb IUH......+.T..L.
00000030: ccc9 b12d 4a4d 51d0 c7ad ced0 12aa 4e39 ...-JMQ.......N9
00000040: 2dcd 3c0d 2884 4fad 0542 2d7e 85e6 3085 -.<.(.O..B-~..0.
00000050: 0604 149a c115 1aa4 e155 680a 5598 9997 .........Uh.U...
00000060: 9299 9e8f 57a9 09cc 4c0b a07f d2f0 1b6b ....W...L......k
00000070: 8cf0 1148 2100 0a ...H!..
```
Sadly, this is shorter than [my Pyth answer](https://codegolf.stackexchange.com/a/75397/3808). :(
Generates the same SVG file.
[Answer]
## CSS, ~~244~~ ~~242~~ 240 bytes
```
body{width:400px;height:200px;background-image:radial-gradient(500px at bottom,#FFF 26%,#8F00FF 26%,#8F00FF 28%,#4B0082 28%,#4B0082 30%,#00F 30%,#00F 32%,#0F0 32%,#0F0 34%,#FF0 34%,#FF0 36%,#FF7F00 36%,#FF7F00 38%,red 38%,red 40%,#FFF 40%)}
```
Edit: Saved 2 bytes by working around a bug in Chrome. Saved a further 2 bytes thanks to @TrangOul.
Note: the snippet uses a `<div>` due to limitations of Stack Snippets.
```
div {
width: 400px;
height: 200px;
background-image: radial-gradient(500px at bottom,
#FFF 26%,
#8F00FF 26%, #8F00FF 28%,
#4B0082 28%, #4B0082 30%,
#00F 30%, #00F 32%,
#0F0 32%, #0F0 34%,
#FF0 34%, #FF0 36%,
#FF7F00 36%, #FF7F00 38%,
red 38%, red 40%,
#FFF 40%);
}
```
```
<div>
```
[Answer]
# JavaScript ~~271~~ 251
```
c=document.body.appendChild(document.createElement('canvas'))
x=c.getContext('2d')
c.width=400
r=c.height=200
for(i=0;i<8;x.beginPath(),x.arc(r,r,r-i*10,0,7),x.fillStyle="#"+"FF0000FF7F00FFFF0000FF000000FF4B00828F00FFFFFFFF".substr(i++*6,6),x.fill());
```
[Answer]
# C, 220 217 213 bytes
```
#define X printf("%c",s<169|s/401?y:s
i=8e4,t,y=255;main(s){for(puts("P6 400 200 255");i--;X/288?y:s<195?143:s<225?75:0),X<256|s/360?0:s/323?127:y),X<225&s/195?130:s<256?y:0))s=i/400,t=i%400-200,s=(s*s+t*t)/100;}
```
Output is PPM (the binary kind).
**Edit:** Saved a couple bytes thanks to @tucuxi.
**Edit 2:** Rearranged code to save even more.
[Answer]
# [Google Blockly](https://developers.google.com/blockly/), 48 blocks, 75 bytes
[](https://i.stack.imgur.com/Pz8Di.png)
Click the gif below to navigate to the solution, where you can get a closer look at how it works.
As for an explanation, I think an image is worth a thousand words, and thus a gif is worth a thousand images.
[link to big readable gif](https://i.stack.imgur.com/NjDAl.gif)
[](https://blockly-games.appspot.com/turtle?lang=en&level=10#c3nukn)
Note: I'm unsure how to count in Blockly, so I counted every block as 1 byte, and every variable the regular way, so that `0` == 1 byte, `530` == 3 bytes, `Arial` == 5 bytes and `bold` == 4 bytes.
I counted the special character I used to cut off the rainbow as 2 bytes.
Please report any mistakes or suggestions of the byte count in the comments
[Answer]
# Postscript (87 bytes)
Hex dump:
```
00000000: 3188 0131 2030 2e35 3631 8800 3120 302e 1..1 0.561..1 0.
00000010: 3237 3888 0030 2e35 3188 0030 8801 3088 278..0.51..0..0.
00000020: 0130 8801 3188 0031 2030 2e35 8800 3188 .0..1..1 0.5..1.
00000030: 0030 87c8 0038 7b34 2031 9287 929d 87c8 .0...8{4 1......
00000040: 0030 2032 9258 3087 b400 9205 9216 9242 .0 2.X0........B
00000050: 880a 92a9 7d92 83 ....}..
```
Output:
[](https://i.stack.imgur.com/YFiwn.png)
[Answer]
# HTML + CSS, ~~310~~ 307 bytes
```
<b style=background:red><b style=background:#ff7f00><b style=background:#ff0><b style=background:lime><b style=background:blue><b style=background:indigo><b style=background:#8f00ff><b style=background:#fff;width:260px;height:130px><style>b{float:left;padding:10px 10px 0 10px;border-radius:300px 300px 0 0}
```
Super-duper invalid markup (may or may not look correct in your browser). Just wanted to see if it was even possible.
[Answer]
## PHP, 285 bytes
```
<?php $a=imagecreate(400,200);define("b",255);$c=array(b,b,b,b,0,0,b,127,0,b,b,0,0,b,0,0,0,b,75,0,130,143,0,b,b,b,b);for($i=0;$i<9;$i++){imagefilledellipse($a,200,200,420-$i*20,420-$i*20,imagecolorallocate($a,$c[$i*3],$c[$i*3+1],$c[$i*3+2]));}header("Content-type:png");imagepng($a);?>
```
Outputs:
[](https://i.stack.imgur.com/MySb0.png)
[Answer]
# Bash + ImageMagick, ~~159~~ 125 characters
```
eval convert -size 401x201 xc: '-fill \#'{f00,ff7f00,ff0,0f0,00f,4b0082,8f00ff,fff}' -draw "circle 200,200 200,$[i++*10]"' x:
```
Sample output:

[Answer]
# Processing, ~~196~~ ~~186~~ ~~181~~ ~~179~~ ~~169~~ 163 bytes
```
int d=400,i=0;size(d,d/2);background(-1);int[]c={-65536,-33024,-256,#00ff00,#0000ff,#4b0082,#8f00ff,-1};for(noStroke();i<8;ellipse(200,200,d,d),d-=20)fill(c[i++]);
```
[](https://i.stack.imgur.com/fUAER.png)
*Saved 10 bytes thanks to Kritixi Lithos*
*... and another 6 bytes thanks to dzaima*
[Answer]
# Excel VBA, ~~213~~ ~~202~~ ~~196~~ ~~192~~ 172 Bytes
### Code
Anonymous VBE immediate window function that takes no input and outputs a rainbow, as a vector image, to the sheets(1) object
```
For i=0To 7:j=400-20*i:Set s=Sheet1.Shapes.AddShape(20,10*i,10*i,j,j):s.Fill.ForeColor.RGB=Array(255,32767,65535,65280,-31*4^8,8519755,&HE1008F,-1)(i):s.Line.Visible=0:Next
```
### Subroutine Version
```
Sub a
For i=0To 7
j=400-20*i
set s=Sheet1.Shapes.AddShape(20,10*i,10*i,j,j)
s.Fill.ForeColor.RGB=Array(255,32767,65535,65280,-31*4^8,8519755,&HE1008F,-1)(i)
s.Line.Visible=0
Next
End Sub
```
-11 bytes for removing `.Adjustments(3)=3/80` call and adding a 8th, white arc
-6 bytes for using `-1` over `&HFFFFFF`
-3 bytes for using `Sheet1` over `Sheets(1)`
-6 bytes for converting `with` statement to `set` statement
-14 bytes for converting from `Sub` to anonymous VBE function
### Output
[](https://i.stack.imgur.com/xSUp3.png)
[Answer]
# R, 184 170 bytes
Making an image with fixed pixel dimensions turns out to be surprisingly tricky with R, whose plotting functions are mostly intended for statisticians. In particular R leaves extra space for labels and coordinate axes unless you explicitly set margins as zero-width by calling `par`.
On the other hand some of the required colours (specifically red, yellow and blue) are found in the default palette, and can be referenced simply by integer indices.
```
png(,400,200)
par(mar=0*1:4)
plot(as.raster(outer(199:0,-199.5:200,function(y,x)c(rep("white",13),"#8F00FF","#4B0082",4,"green",7,"#FF7F00",2)[1+(x^2+y^2)^.5%%200/10])))
```
[Answer]
# Forth Salon Haiku (184 bytes)
I can't satisfy the dimension constraints with this format, but I thought it worth sharing anyway.
```
: ^ 2 ** ;
: b 0.9 * dup x .5 - ^ y 2.01 / ^
+ sqrt dup rot > swap rot .045
+ < * * + ;
0 .56 .2 b .29 .25 b 1 .4 b
1 .45 b 1 .5 b 0 1 .35 b 1 .4 b
0.5 .45 b 0 1 .2 b .51 .25 b
1 .3 b
```
[](https://i.stack.imgur.com/JcuIQ.png)
[Answer]
# DIV Games Studio (184 bytes)
Not the shortest but quite simple. Uses the DIV default palette
```
PROGRAM r;
local
c[]=22,26,235,41,54,82,249,15,15;
BEGIN
set_mode(400200);
for(x=-80;x<80;x+=10)
y=399-x;
draw(5,c[abs(x)/10],15,0,x,x,y,y);
x+=70*(x<0);END
LOOP;FRAME;END
END
```
[](https://i.stack.imgur.com/9DwOt.png)
## Explanation
Define program start (named "r" to save space)
```
PROGRAM r;
```
setup palette lookup
```
local
c[]=22,26,235,41,54,82,249,15,15;
```
BEGIN program code
```
BEGIN
```
Set video mode to 400,200
```
set_mode(400200);
```
loop x (predefined variable) from -80 (which bg hack) to 80 ( 7 colours + white centre)
```
for(x=-80;x<80;x+=10)
```
define elipse constraints
```
y=399-x;
```
draw elipse - on the first iteration this draws a circle larger than the screen in full white (index -8)
draw(type (5=filled elipse), colour, opacity, x0,y0,x1,y1)
```
draw(5,c[abs(x)/10],15,0,x,x,y,y);
```
once first is done, bump x up to zero to start drawing red band
```
x+=70*(x<0);
```
end for loop
```
END
```
infinite loop, drawing screen.
```
LOOP;FRAME;END
```
end (matches BEGIN at top of program)
```
END
```
[Answer]
## Perl, 175 + 1 = 176 bytes
```
perl -MSVG -E '$z=SVG->new(width=>4e2,height=>2e2);@x=qw/#fff #8f00ff indigo #00f #0f0 #ff0 #ff7f00 red/;$z->circle(cx=>200,cy=>200,r=>200-10*$a++,style=>{fill=>pop@x})for 1..8;say$z->xmlify'
```
[](https://i.stack.imgur.com/kbn3G.png)
[Answer]
# PHP, 190 bytes
```
imagefill($a=imagecreatetruecolor($r=400,200),0,0,$w=0xffffff);foreach([255<<16,0xff7f00,$w-255,65280,255,4915330,9371903,$w]as$i)imagefilledellipse($a,200,200,$r,20+$r-=20,$i);imagepng($a);
```
Run it like this:
```
php -r 'imagefill($a=imagecreatetruecolor($r=400,200),0,0,$w=0xffffff);foreach([255<<16,0xff7f00,$w-255,65280,255,4915330,9371903,$w]as$i)imagefilledellipse($a,200,200,$r,20+$r-=20,$i);imagepng($a);' | display
```
[](https://i.stack.imgur.com/53Amf.png)
Also working in theory at 179 bytes (but the image looks a tad messed up, bad GD):
```
php -r '$r=410;imagesetthickness($a=imagecreatetruecolor(400,200),10);foreach([255<<16,0xff7f00,0xffff00,65280,255,4915330,9371903]as$i)imagearc($a,200,200,$r-=20,$r,1,0,$i);imagepng($a);' | display
```
[](https://i.stack.imgur.com/1sSOB.png)
Also not a perfect image, but much better than the above (and @166 bytes):
```
php -d error_reporting=30709 -r '$a=imagecreatetruecolor($r=400,200);foreach([255<<16,0xff7f00,0xffff00,65280,255,4915330,9371903]as$i)for(;++$$i<21;)imageellipse($a,200,200,$r,$r--,$i);imagepng($a);' | display
```
[](https://i.stack.imgur.com/r5sJ5.png)
] |
[Question]
[
# The objective
Given the non-negative integer \$n\$, output the value of the hyperfactorial \$H(n)\$. You don't have to worry about outputs exceeding your language's integer limit.
# Background
The [hyperfactorial](https://mathworld.wolfram.com/Hyperfactorial.html) is a variant of the factorial function. is defined as
$$
H(n) = 1^{1} \cdot 2^{2} \cdot 3^{3} \cdot \: \cdots \: \cdot n^{n}
$$
For example, \$H(4) = 1^{1} \cdot 2^{2} \cdot 3^{3} \cdot 4^{4} = 27648\$.
# Test cases
```
n H(n)
0 1
1 1
2 4
3 108
4 27648
5 86400000
6 4031078400000
7 3319766398771200000
8 55696437941726556979200000
```
# Rules
* The [standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden.
* As this is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
*)P
```
[Try it online!](https://tio.run/##y0rNyan8/19LM@C/zuH2rEcNcxR07RQeNczVjPz/3wIA "Jelly – Try It Online")
## How it works
```
*)P - Main link. Takes n on the left
) - Over each integer 1 ‚â§ i ‚â§ n:
* - Raise i to the power i
P - Product
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 19 bytes
```
Product[n^n,{n,#}]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277P6AoP6U0uSQ6Ly5PpzpPR7k2Vg0olplXoqDvkK7vEJSYl54abaBjEfv/PwA "Wolfram Language (Mathematica) – Try It Online")
also as @att mentioned there is a built-in for this...
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 14 bytes
```
Hyperfactorial
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n27736OyILUoLTG5JL8oMzHnf0BRZl6Jgr5Dur5DUGJeemq0gY5F7P//AA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 5 bytes
```
‚ç≥√ó.*‚ç≥
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v//Ue/mw9P1tIDU/7RHbRMQXK5HfVOBAmkKJv8B "APL (Dyalog Classic) – Try It Online")
Monadic fork train
First it evaluates range of the input, and dots the power and takes the product.
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), 3 bytes
```
*†Π
```
[Try it online!](https://tio.run/##S0/MTPz/X@tRw4JzC/7/NwEA "Gaia – Try It Online")
`†` vectorizes the operator on its left, integer arguments are implicitly cast to ranges. `*` is exponentiation and `Π` the product of a list.
[Answer]
# JavaScript (ES7), 20 bytes
```
f=n=>n?n**n*f(n-1):1
```
[Try it online!](https://tio.run/##DcuxDkAwFEbhV7mDobdC2ARl9RiaUiHyX0Es4tmr01m@s9nHXu5cjzuDTHMI3sB06KE1tFfISq7L4OVUIENFQ6DWUBWbpkxOcMk@57ssahxU8uLjyJI3nvyNHH4 "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 28 bytes
```
f=lambda n:n<1or n**n*f(n-1)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRIc8qz8Ywv0ghT0srTytNI0/XUPN/GoivkJmnUJSYl56qYalppVBQlJlXogGU19T8DwA "Python 3 – Try It Online")
[Answer]
# [Nibbles](http://golfscript.com/nibbles), 2 bytes
```
$*@^
```
Note that this problem influenced how nibbles decides to use implicit args from implicit ops. I'm currently thinking of getting rid of implicit fold since it is uncommonly used though.
```
# implicit fold since accumulator is used
# implicit range from 1 since there's things after an integer
$ # first input integer
* # mult
@ # accumulator from fold
^ # exponentiation
# implicit $ since need another arg to ^
# implicit $ since need another arg to ^
```
[Answer]
# [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), 51 bytes
```
(load library
(d H(q((N)(i N(*(pow N N)(H(dec N)))1
```
[Try it online!](https://tio.run/##DccxDoAgEATA3ldsuWelnU@g4g8oFpegIJIYXn/SzTS9e9K3mDHlEJF0r6H2iRGOD@mFCs@ZJX/wGHWM5zEgshqvUODApWVsIvYD "tinylisp – Try It Online")
## Ungolfed
```
(load library) ; for *, pow, and dec
(def hyper ; name something
(lambda (n) ; a lambda function that takes one parameter n
(if n ; if n...
(* ; ...is non-zero, multiply...
(pow n n) ; ...n raised to itself...
(hyper (dec n))) ; by the hyperfactorial of n-1
1))) ; otherwise if n is zero, return 1
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 5 bytes
```
Πm´^ḣ
```
[Try it online!](https://tio.run/##yygtzv6f@6ip8eGOxf/PLcg9tCUOxPr/3wIA "Husk – Try It Online")
```
Π # product of
m # mapping across all values of
·∏£ # 1..input
´^ # x to the power of x
```
[Answer]
# [R](https://www.r-project.org/), 20 bytes
```
prod((x=1:scan())^x)
```
[Try it online!](https://tio.run/##K/qfpmCjq5BWmpdckpmfp5GpqVCtUJycmIciqpmpoBySWlyiUF6UWFCQWvS/oCg/RUOjwtbQCqRWQ1MzrkLzfy1XWn6RRqZCZp6CgZWppkJBUWZeiUYa0EzN/wA "R – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 20 bytes
```
h 0=1
h n=n^n*h(n-1)
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P0PBwNaQK0MhzzYvLk8rQyNP11Dzf25iZp6CrUJuYoFvvEJBaUlwSZFPnkK0RnFGfrlChaaCtraCkoKtHZAAssCiKgoZIImaChvdaAM9PUOD2Nj//5LTchLTi//rJhcUAAA "Haskell – Try It Online")
[Answer]
# [jq](https://stedolan.github.io/jq/), 42 bytes
```
[range(.+1)]|reduce.[]as$i(1;.*pow($i;$i))
```
[Try it online!](https://tio.run/##yyr8rxcdW/M/uigxLz1VQ0/bUDO2pig1pTQ5FSieWKySqWForadVkF@uoZJprZKpqfn/f7SBjqGOkY6xjomOqY6ZjrmORSwA "jq – Try It Online")
[Answer]
# [Java (JDK)](http://jdk.java.net/), 51 bytes
```
n->{var r=1;for(;n>0;)r*=Math.pow(n,n--);return r;}
```
[Try it online!](https://tio.run/##NY49a8NADIZ3/woRMJwT@0jWXhzo2CF0CJ1KB9Uf6bm27tDJLib4t7uXlA7iQejl0dvhhEVXf6928I4FurjrUWyv25EqsY701iRVjyHAGS3BLQHw42dvKwiCEjE5W8MQb@oibOn6/gHI15A9ogAvJG@EPL/6hlEcQwslrFScbhMycHkwrWNl6LQ3GW/LM8qX9u5HUU5FkRluZGQCNstqHr6YBmVJgKJnbyKOcLhzt/t/CXCZgzSDdqNoHztJqzZp/QRpndImB8qh1eh9Pz@HWE9Rlv25l@Q@y/oL "Java (JDK) – Try It Online")
[Answer]
# TI-Basic, ~~19~~ ~~17~~ 14 bytes
```
prod(seq(I^I,I,1,Ans+not(Ans
```
sadly `0^0` or an empty list errors, so `0` has to be turned into `1`
[Answer]
# [Factor](https://factorcode.org/) + `math.factorials`, 15 bytes
```
hyper-factorial
```
[Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQm1iSoZcGFspMzClWKChKLSmpLCjKzCtRsObisvifUVmQWqQLV/Ff7z8A "Factor – Try It Online")
Built-in.
# [Factor](https://factorcode.org/) + `math.unicode`, ~~33~~ 27 bytes
```
[ [1,b] [ dup ^n ] map Π ]
```
[Try it online!](https://tio.run/##JcvBCQIxEIXh@1bxCpCAR7UA8eJFPIUVxuyshtVJNpkIdmNFthSj3h4/3xvJaUj1eNjtt2vcSa8mkVw4Y@IkfPunsYhTHySbmPyDlJF5LiyuuR8o4l0YGDGx6rMhUWy6bgUflKqFXS7OPSyGEnES9O0V8X6hr9@Rldxk6gc "Factor – Try It Online")
This could have been 26 bytes, but `^` returns NaN for 0^0. Factor is the only language I know of that doesn't just return 1 for that. So I had to use `^n` instead, which is a helper word used to implement `^` that hasn't been 'fixed' yet.
* `[1,b]` A range from 1 to whatever is on top of the data stack, inclusive.
* `dup ^n` Raise an integer to itself.
* `[ ... ] map` Apply a quotation to each element of a sequence, collecting the results in a new sequence of the same length.
* `Π` Product of a sequence.
[Answer]
# [Kotlin](https://kotlinlang.org), 59 bytes
```
fun h(i:Double):Double=if(i<1)1.0 else Math.pow(i,i)*h(i-1)
```
[Try it online!](https://tio.run/##LYyxDsIwDAV/xaONwCIbQu3GykcEKVGfCHZVUnWo@u2hAqZb7u7ptcBay7PRwLjefH6UJH/2yIwuSNAzpfJOdI910NEXxhFy2INTkG/7ijCWNftEDIJRUL3IOk6wWox3U6v/piwi29Y@ "Kotlin – Try It Online")
Longest submission yet, but thought I might as well give Kotlin a shot. Used the `=` format for functions to eliminate 2 brackets as well as the `return`.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 28 bytes
```
H(n){n=n?pow(n,n)*H(--n):1;}
```
[Try it online!](https://tio.run/##XU/daoMwFL7vUxwEIWkTptV23ZzbxRj4DtMLibGTtVGMUJn46suOP5V2B5KTfD8n@QQ/CmFMRBTtVKjeqvJCFFN0HRHOFX12g94UqoFzWihCoVsB1gA0Ujf6M4EQOoeBy2DLwGPgM9j1waKSbSVFI7NJ6I5ClLjOAQ2Pex/bYe87Q80u8ZXWa9yl@Jb1ZLPi9mMbt0/vuHYWg9u7Z82@vKyBDE8WKpMt2pxgPr6ALn5kmZPrZ@jDDKwXJIDNZlRfIy4xcdIUdaST4I7VyEakofeoRHQJ/t9W1SjJiWV7GfBXsDOwdawwVcNAsyW4DEOdzHP7VW9@RX5Kj9rwi@Gn8x8 "C (gcc) – Try It Online")
[Answer]
# [Wren](https://github.com/munificent/wren), 43 bytes
```
var F=Fn.new{|n|n<1?1:n.pow(n)*F.call(n-1)}
```
[Try it online!](https://tio.run/##NcpBCoAgEAXQq8zSCRpyF1G08wKdQEIoqJ@YJJGd3Va99UvBoZTLBjKDgcClJyOj16PuIP5IClwZme22KdSa36IakZbF2XmhJxMo03Sf0e3iw4qo/sxMb/kA "Wren – Try It Online")
Alternate:
# [Wren](https://github.com/munificent/wren), 44 bytes
```
Fn.new{|n|(1..n).reduce(1){|a,b|a*b.pow(b)}}
```
[Try it online!](https://tio.run/##BcExDsIwDAXQq3i0EfqiGwsrF@AETnAFUjFVKERVnLOH92oxHz8tNNNlXB1utYUHT4ALit2/2XiSFnpMoYeE9V05Se@DT8BZYJof1IKcgm77Z7MX1vL0jWdkXRZ2EerjDw "Wren – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes
```
ɾ:eΠ
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%C9%BE%3Ae%CE%A0&inputs=4&header=&footer=)
Obligatory answer
```
…æ # Range
: # Dup
e # Power
Π # Product
```
[Answer]
# dc, 24 bytes
```
?[1+[d1-d1<xr1-d^*]dsxxp
```
### Explanation
This is a complete program, that reads input from stdin and writes the result to stdout.
```
? # input
1+ # avoid H(-1)
[ # function x
d1- #
d1<x # recurse : n n-1 ... i+1 H(i-1)
r1- # : n n-1 ... H(i-1) i
d^* # : n n-1 ... H(i)
]dsxx # define and execute
p # output
```
### Output
H(n) for n = 0..12
```
0
1
4
108
27648
86400000
4031078400000
3319766398771200000
55696437941726556979200000
21577941222941856209168026828800000
215779412229418562091680268288000000000000000
61564384586635053951550731889313964883968000000000000000
548914237009501581804104224704637116078267727827959808000000000000000
```
My machine takes almost 0.7 seconds to compute H(200), but it does produce the correct result:
```
114256002424540571298977792354054343003217988447353197803701128087779\
727310773544883222069862169886712875089569689613436517195625058699339\
831616247967378727547253765461789388643475674400611735920545310021028\
378006078740483920058608872101517118552137511462765664553099379243826\
960171887170750794198373595289872526218671094534622811250467573078955\
097722440499909299236803909456886903559422482755722874996888761181995\
575299415208051459908113833797191408981585936952677202993799475038316\
559629150663378834397372775965856682894873495939410259095804412984759\
376802645433107086846121910224544820403394942396165166503784543183923\
373316267239065885057694972898540625272750046246522113004186914354002\
967536413371473458112220769020094756837578527902012213205896270144393\
863599279497755781359466901673079326909202551645285985747551170700716\
842425698975536766498808553756048408306339794216494138288030784286578\
757511579359563917784149939178533514638276262178221710320662541522716\
166268310550789650887610134719729891484651131282509122835031254510412\
859215509732637002095449585308892098589802359045914197581197309643963\
042570582527203047381981490652454323893038445041694758990588984561508\
024977520153869302479414855203541538559245994267482585355022642863859\
784222422005021616964777696793772349735028255170680455712484791660880\
381133647422166704047722699070109094074510187247343055332257496929374\
982064491045838594959100552218107373079642910265887514107042314387137\
231583168255471546888411138370063211060324585902513206145493958317539\
840648935101056767774783896580016743810934173275647035655085909723344\
400585286826414068777563965071196389690941135698863589037499407785370\
931798703443963281315725441703395909623807818562899480337755459429222\
263976154559801703132418440141220192063353095047779835936440544198953\
496106173470542538936478118001519398934406367850808122800102137273226\
951723289344106737093183594520201847490204826536442751006791251960765\
409736570349501810834880546030444722460505622335562771218876927864732\
533831989277488466279926764165356648286028875357501991394907871736473\
399337480995325006099531629623628775557151039011468601336589825839738\
631718648726576082486937471392562052316112813773965598704019732181766\
979636498126699138316658703065343361486555049963171513229287190102366\
294038070909517003192684859103788524924734600167422726737999487560861\
040910125441478016464932490390352767808126453168977619717961242515337\
678589841167345358713873500430963639031923908700261694508782150681050\
006111529466925629252138641356979249757548377531461415227595617743646\
019706623647306680452085764528828628378729906162793797766057848324098\
880977726680150730390074716141211796155230858668012021940942979991319\
892197094655756666501455192326506825509530719155451676296396102560013\
841584265351485313695020472184192704099107932797640710173835532960606\
518538605516574602321430208034314359982648827905481627199797808702727\
344458806167205608568625797981988480548489292548067131307825217362115\
487277151573038609637079476077578954700658210221211043513144482137132\
113794287001433270940578127570053434695653912547579202493901871464470\
764410974150819235945558607363556467922279391141836922743541233760821\
871365085257243448039467666652724537269128483841450819722610910449669\
667767218934240840176992473839442233550613463850853485560398554469357\
611537501209062167152021399590356213475289096528949653047033419077429\
299028564676171187099901772701404490557158793484243417114875079809449\
627812693323373523747772814832161656651663374496734064538978915783865\
719064174822864696226655708942852177545994665514849721267519945794503\
019098476165255673401283399976325921222555982464845071082560857852257\
814145566478967899059920204170727945409097495154492869672134459786294\
588119159908191561922643839816897827104225462279731830827250471252105\
289727169676968836275320004859466161656331082081074381176816967370602\
357442772694553727911750007625712888624429904817070697897964886832493\
345528030314492840383966128843659735252693645758721744757267671336699\
697149807573431757428427239466529780150411631632066022100098544057533\
387989402082327607683479023952713064900546185006785478600337149539296\
663361814407606344949829339294479920368454331595871231338484805775737\
339268396124977267103545541977669058589689418363091692719790628856414\
752071432633359549389607990792617571221154257026279901828952182073374\
160861868734416746968494659933958156742463652295106500468210780119125\
220209380290875380832470409648848082808663586942813054685601333888677\
903229796350639694587698272283080314334773653111218034106708436851163\
056715554656438061557864316343565021443951504379532417965485201636186\
463813912432724675905548790267512971651098333554063940806626704854532\
678674167073399666603479497096163139406079292169446126287164855437310\
733645103657687054384245612640135453530729419221334723538721255762469\
348656691594173954864816605371367857438364854545334435452281244641153\
702780834293385080202596856941397712010881729069210455124793116543955\
764287224835926198843406678698041913931641907309743017824157088832657\
515931712589921404995250184506019056203133181617154100069201866951525\
300872664323283710970049931600220543834155799207559964184227001086729\
978318247276684554857576596547291291791522751007585853793360225113135\
450501518599762144278325251060114811491521595770223299394208499421070\
133134002376834102080109021979719187115415860089714599508435221834288\
106979134790461271826466644755668937746875390891835581995388195707703\
666919259484508094626586130500902421761233473185812236823727560637765\
353284587005782503482049179577624131003496831794473409129318251405306\
686312023625090599797707676764002997295491901065845799891148513188011\
750255365930732717166438760960930254270355434958193721008813937013342\
442685357933848612269061232591941511207731095268816549202309436856983\
863709498625968309204249579255954213842990272453525630818763597799543\
593087313268427793519216838584166922708627220843209392429847694078662\
627081045478537054881042974186251081449455396030353464966077751989172\
967094495553235926368816821576526232804884953832820814720565106292278\
677023212354425827714341638534116865568614053180685437672841412518894\
098874469347176584909301684501882789675804879960815875737873223894302\
068322229857523890186183543936935430404240034004709340156823935334504\
280773088422757352262015925135936299428100399162508993701323816640249\
317502708643002177380916843121414525377166307214659890456197078789358\
755908958395704605757659385312957851526639927217127812638621838046618\
256249655670855709886714485145533985086443137064765377391996261567764\
614649944571049532129160422595979803302687452962711606329612008212827\
794401494192040770665411078681415279435060816655175330979102977082874\
632330444354061833803759173996116082517816249241467318683953133297949\
696966800597273657946143827878859661836812064102045501830604467916228\
427069899293175548188750078304435399590540700476604483395383697312578\
097710820312329606242276447140831589400706797160881537904137892646388\
261066966454548869342350130453494223912785614903507340787315001904795\
688540272824396638149906352594040357284385938277509795452746883194274\
390009993333838096016899929412160162615538212444522338199878096100853\
638701901085648519985630176886727084180895587065782329076867465210575\
281386375663556976026065633532489743239889186305075304808560243262432\
658085969412020827902073591982408638009516334902222599715386120602437\
678310010096587347186053193158239648969456170841664624039286167247669\
514436308002065354268316000349861095951926759431651589488622884486382\
277854033455441602586071384379537383305706042265499575026224506704860\
688406915452474511683218154440889210555179680616817271305312473155544\
143262273531331795805472254371401019589348634412412286987413907792718\
329915124784729596566415082748529970796499261705982501268401723583887\
701661443797764811659857704733113125011378104100970585073283674392976\
859476816730766230843992524449084734798618995888731548845560723062966\
192859122943220390909175950182057052843622022554828023378885550828117\
382718195394157370910647482474167099695486548360631460470999045477378\
132717331452335714187924997815103638622262298849924210205241176668405\
490741524219253278664341011210099915988552406343854573062664870584245\
103886217277906440977065037168659090059763288778505082007530932618466\
494869181704099810631362022702089755491800061458537467852967380851010\
908862739733011423332473338496528317600181547938903583970178021411350\
504107353290656971578124200774189092891257270280529095290550988723728\
135603533746551804333320307013973767695324099720923379543683864817974\
710553868201698590292895333412491357784173524677821074492989035878523\
065616904294807445990638805797254482102285949882214670841897742949328\
311659987640881568459282440548451135162773664037389258355421285035420\
999699985577663763700005757941427315733197266168699581396576204803981\
473126870934075898120336661598190205939756443947057710182924789850055\
001425654550118743113257624420824183938997656885814673594734917916409\
078995498945642404630814171603046441105445059249548610322842910754951\
846627795460490833776103956049657955540015291032378840531042472594532\
860423319860149058941766354088020712438608204454072807575885575852839\
180700772630347090579280688794361068997524503617691544202365939291565\
645671286667544529026174876789733907296960576178709446195376983454472\
164584703777117244823990537583736958740841562740244004026203727555258\
450538750500484541128688250020648123312909872053878444932137569761105\
646598390520596957373979148797644934213546809772428508682350740007209\
819026797315661258929751889448192710982091237434909749464078055542925\
758110822533573122134535676028907089176208169078890508131338313078120\
366292092748543956445763451239618092200751801948183924253225759130045\
402864771211838018815605401626689028050384789832787839775255721097218\
181110343132212865937413848154233885501099705968645937079387543236067\
419341630111614913910492435024464166688710987099886511583318895948003\
248879615736644901850078099348201377864691386256283320069993735388706\
880978227943386880372348195108338420348643722382324037845214076409223\
421605406326543434017961739452074663199250414741826344527959432512472\
288051981715822955586322044373144003885900746941921709703799672502350\
065363701967267734865903791650802227123544971675955949787985267374530\
847885039570559135088894718198400171730871289918834134265582501872441\
817474408532347174649197682421484732565030830602652775869842343897079\
665618967792517232732353781319861024635289426450784800702094918520783\
421946020173070856497710123531146795959596308032645673704792463483238\
508003336793688645287713354332253474988554262325815954309909567664567\
573258648500395650173170779959337702622396455572300230300768415812431\
943010715240963679596296486831129989681871718230599580037772017117033\
315832399335703122496145800075686154721432794663618613863892627375137\
366428360989986599340414088453536386107561090367699159184439260424635\
745591597059093633912447921539583960069923796416538679234874262062410\
163002664653721804674990501848569881038943775993261621385733027297067\
083554262375476401287244101149052235300084299630703460854961311971283\
087073208822293226528612144677097325474675212863261753395272291201243\
727063158190087578787154328368369458561245784693838304278572756604546\
510952636210910525436103646773871458339800106430023155717178920396687\
520423472846663370278770127553170373437626792023727289514355087037311\
140097772419377161850139650623158006220407602434802036169803932182144\
364560440183502624140166248069772217517658503727605438952409331108997\
938796887451122008271640565975335203086775806001724195485708936422425\
137056283019622940342042757720398404950656311129102072111491775765939\
145688292407278548040314549680511643911856331584703069002009015743434\
987416878546802024548849006779822873402507748917427021579312534569977\
361861231854091421381548376451031427272315824402714317215823133557566\
630570188995812896381696487597394215612003133922998761317879400375340\
125754172678973925934340294567607771195422852830929279465841874639010\
009888808918675285586746078546918806973510720653329464320497985376475\
514652191137288767301110502250694677101081566428326927525440430403867\
468662023769524677616162779798242348230999586692878495342514713764186\
714882538090458901781712475105348027738734745293498558256040405894803\
195991677041814864565397732062450568265762161106477446853681187477778\
726005451422916487453440941705450833165526732124577290035369815857754\
177651321505099564890184890808449589507960017238091650940272579801976\
012553611294392411698525056432475991421017871033115166544672308666931\
153046458808727931683807887236625749116358879625843911889493775696035\
689596716234107636539958765668585942904085430988801703856400119630376\
274574597769512867580730016556216727676744713487993170219184593464999\
311291112749880481896882356531818314812757939997704540854301634559210\
168428005707651884236890080120885190924260622549699781701215291431456\
641474519410935152273699234442085712020314906414846783096378915749837\
313543205699498699058727247319542037049467226655708039331544604104781\
409084183109899592118979816757807977852975258979779416901404268104909\
705348928232083022795123709882664565805802427977177013536930315406074\
119798700228696233155965389441167947547520301277280800708044768115830\
471568118316963537054375894947474149197268583279951389007580911096150\
587642304998165318585620851425172746769477143145386873345481245188537\
754898143742686352644071418948819336880282491363012186422360754575220\
279448092609828602552016180377773970908025714516279864286548174974082\
714686202892658851979133054341592863444445185327463440688040605716405\
067027534367643153032569517666086981280522416245349519983986846967214\
042882273846333605336087299637431797991108127634339718858236191873607\
992145012212007858822784503266193271141131224661074334214839250271667\
726722076785306858810448052589267984702881718156816842983856068663911\
962262395537169886395290931248461646122637458717832878921862044114375\
961223925897580056403294305693475540045578718469567147106404825130645\
182596807474482717319438314466506464297165104699880281509113101964645\
644113558063277536948464800478797709703629400329162780840501627821037\
796082859331312091625314594124914131496550405427389764417029031881865\
161566844591130624668157039150013878652923170474308357677476499519615\
694247353253258416153487129434125741231110906666192911231143233291672\
330355835909139214586207813893211012425324068478627916498679629380977\
726349923696052885626801312565943741488193855513659470521916364497140\
595263059255234991151676056428157949653159230890433842121335826208388\
342905112604728437774206247314145114208160560382868989175460790477221\
890350677890961281703135082791138001520406832403763549570484116412249\
411630340091247083693144122332355091861372457253352008769217588001288\
849717267814951643081139792036726924049299132057170441936528548540420\
064033867805971560358101657671048958681419753322017701206905396234428\
135916258956179250871059395091929250943571633006872870216908850580206\
492968748602862989200240660330463405184596960622742947121148050963122\
321259337631048134291686503286606869138604813871549760164086721913518\
637749340223861847791025891443679650627984525254307030025638348279163\
760184818981923247501359438277271636232964640495952052708147067280051\
510417155618166064646769348176921156031703472238576803756454461973221\
654819493213203649089803381920320331786258749203931226197991150138418\
412665064324591666915076933446777039262089089651109035566583869738578\
597506761075170629480218974597816082666310188595749958551973619906326\
148650712257007357155244818379632436183006582758626649517236510683006\
346083500259745147176189562743231550874298895062648811402347137583548\
675098905750258174262052682531224862649985350791958712521075292922368\
595003093091774703254502960834476169407594973424845628114251412090192\
033055714360450494006595575968666327901355614408397215867467966118019\
576690302025344757113309733262077331055580267485085990493403505787838\
624566370526779488899761016359956759522270200707135958413154679827569\
258052868584822095448301696499657831845970412520110100094933597023662\
316700009222296695302631294120144631256162943881147670342787558109037\
638373998645356492446988510858843413188523534457356161957326654858590\
170373845392894491611342691003506990032562657375834824358150900255718\
212803029008165248772179611829216450388154836261406465215609533903379\
234291823957337623177899123066407939187764831440259804897780532314294\
187768806308300849997380071853436999411397630694458010440206190084920\
364271955929368660748369995712502790615902991832507744246091795838698\
522769638481677935709999820969951468648542838681273677603394509504240\
308953934844440452041183172657724693700991437857142495426882365464490\
656305106674560342135144470557427634289016433075831708395587229518538\
740345784633830858370131443824184367717767852454910547209118651010344\
170278635519515658320221573860591898378883482625668496205501948380927\
655730907380466792089697431597474868907457592287486991817027217936644\
429039036949024880832634934485778971951179199938014320341094585037431\
867897462971290143952624609863752298357851890137576299456918192514413\
801163490330448708940809800295269673370776121695018917895759267103596\
712356385972690041695981952213401668647553788833494484654483704349068\
176379519514076345587421597137517924620994702202104196503077589303867\
675313731830281021790349204147751254681000976845402199926482744440837\
651540373296876407741833859447282118791613435919658716973720823338943\
594717898120853679633629496999886962089450217817683016051641978808086\
090736723556850600235255229245277419993691387427177263341235769365551\
729834695110679831584857749889217164198358411783052421365582162149360\
307993926083432465922185547437809273782150112676800043051133743848179\
507430041789107391336645174236054478492193980551977769361095960852905\
792648589491408260015780133323805313428641785267726788361163481200596\
667926844213028421995386505994266261197953159903842353647124717058462\
606195804456403148297397645768181232545874395373205289680341525417879\
379518455846428797752945668078353519178914505729375052075208668206727\
272592661778659138782753383579531751393302026177424043932380082134112\
304097178637741662710535952129056797743416787671115007825195113544105\
800414762132647003564766945538753743418953135801326760189012574025757\
396710397610011038820702402557513848062197209126418415099387964034761\
398231093033942795839030074337011701661581636846153029980618680958260\
742308998894462132581019648670875157214719847690770798407251574511107\
814179573150171473104112574681707827850658431097893612857747330174826\
263221914068851894736118756496739125630025657215461297066696668503577\
183582733041405309694827396016703300218438917954326780070156715389166\
252811797028538773333761911582321084851330319089805968859787814026573\
646629476563087343556603423340827325523779940913099871860140934516188\
332561209093937145532655355122173625611654611354926043249724145062395\
052073403358582466376317856821760549451408367635975857240939403560193\
544160535875531196735080632931626952143747529382108053685709281128550\
909871592283732369684212053409742502659002594127711109142543712695800\
964668096317273980595863102507908763243035048734467097315273670192716\
453090615295589332917732324135882790481157233370637919417730168802570\
745512158460173430843355794887960375318350278147166774927332518782329\
275386354748592633069853120237345941910229584677639028790677553936767\
813561547451464211027958830776412462906122376937072679758250598400339\
993262606250183184159965386752505918305062458782151287361652904255522\
543747897277759806217530894994343172655413398182581681612121938496736\
246719088985499608274563513876622367779465393373781088492229210720940\
639881067172035481989280366082376941532976834093527635529401514366330\
480920065589598817482347629673178135543148398941148123840436738906568\
689721644562620605431787705716472884630393001383812923459261978914853\
520746731592548434175828751037428755037026486707839111075059327125186\
760809267843888455412978048743136553565305004514936125754311545290038\
133113476411189830181873166563424701146947953889262645190552239014423\
479186724429640510640861075472230063648938881018870060968494482689516\
470150615336695757696184691763777764571491211746536525826581200382784\
605048388142804433635261164053724449418044162892154965646897057026861\
825789232153560082382586610167238788922139435234549283511836608514919\
974792081235167878301494357826304603864897832044708820907368556324046\
004658209312689805738179663008251252674020278832364456345461955022865\
901541110979739876238776312716778351664263063148749685831874832132016\
935035662777717441736545169081531353892410317684943418619599602983211\
424184625311114459460166018052595314630063133375510973311332443179025\
430071437113318883337924946520194725946143840301669209247618491596869\
860173921931370251854462447254511938184185608158210889650209973353848\
709587977807510498484825736181853375451441884380345067688458992092705\
201032496281343674420762320800084135089658792761869184762558806726676\
722458885523590174826474588896231438620097505667947655896718595462296\
073149666204192795203339103128540827107637425053771608250143437698557\
563602741277179793953927426431484612463294041151573622436307805492181\
876291160640064431719636789472314597957573238616645867471630699310482\
878202680466808957828942443566435405022152223504211815437604019790140\
352872467602517381951971882961416597409274884152966514052697974929452\
665027793695015778955965479075442935816241693073367882618572751594589\
233332763571199270073344864323556528614492269184498420264356194305615\
857727851288186636797024506940862150561080428526864057887939002534833\
217825476912788772547258529042674975441187757934184514203802802167837\
147392045462453011001438365392835225710572890221334777983092342949532\
868689408224926079952260855610448736367597882931687183102425507238269\
350671010537707473483269683444914211617226098220802284536428111841021\
355314413825525092408785132949971412943096362996439440725692261405299\
307258200399719962027229993095100541076413611352139497423587018295295\
733263490522360083662929196544565837957602047504540075089561711238004\
034860643130645844174467891334579002129171400079540258966611530625073\
574579537699621459654573062084740258612527512591500081306982149777410\
740290148147295694078336177308080249486577913410339219097486516457786\
845544171494564298759086142864890534059376979463906901088806630448353\
636096572871854504331730452532484411175697139592881541769738473473501\
712004493344258375971665263709468683587321755927947969108354410237014\
622630703966864710147906778218511531246507803307199958593420532473567\
565338941629308172125890217096302195764174165228707151304339280199397\
308288128401592847641643775412416310732509438568791320603475823678213\
022091118173309854694279041928766771888599086244343677301891998549396\
563784328741226437673040978842688696069460803264848555813028336564909\
915911729088504504385439303693869743774004188440858489234825773966439\
034787945703214397718612107720992665600929489208194882429934865386410\
161115173865982683536124076579147099148505092826111112162726946323923\
139510572435234258930966885308790903440842746447356148569569613011866\
216181017947765400323520849488099226865879685849795232175081223157195\
558113479584013517247486158682510281822439736394004394576804296311483\
351867976357203923346203000720371078664247477194715030805264065168164\
569150139879569137943947304661266767151775830577387052301128796128178\
850612741616402622378092347975800584931763715144855238926949360664959\
901934960478488277241384228916947176273846643398938259717770068619213\
014487628266764663292361016953761364719861839113749885418576027074151\
042227017329247056848702075777200168698630056385228682662050087522766\
447910673436514156005878826955500834129864964744197436204252897718702\
140935816928099490760288979327872784783800062445180868891140814201746\
324920232428770583016061424533155666267075515886721407197157139617172\
925490167869130332346357795391916572750248424895052516323326428107724\
137758314910463829058203923431106387112309788487602414624710825158177\
964114057894343181183813244756477920394161657833992924683207226012989\
176214196381796431783415316737367036887146793201669533134930615758349\
947223575783239017366550781734221690665045190947669486016226383725404\
770500226241189927619067594575715556154029052556931773345332242188757\
583235984278742603970474190403890130765749990367903252262002072587910\
429054774362068368774173941070297008442489294012009854536258830415862\
001026233601932344280848478311160293863396081520870580210115748436524\
657593623927560968681489580983408355730739817090564200452344480956466\
381973804084046550012066308187061061100110433589729129116029838272092\
901063648710371584105178456534823033698557959547864668022626855435088\
024359991640953946734473401247145052161022214741899909693164691548573\
821785788946845900456932321418241684343132825893391173058763344836847\
561532940469059613092910143220708525884711120599623251659635879284306\
638801656363654771702535511935418881751805284684639099720239245439664\
571842387562222732097503344638539281322245536316693520241269544702385\
049026321864386637211322748517569828937467849864554760880814644586902\
817967247583917815946609090107550203264295298049898171083475299519485\
282963287445433963699470262712938411098771816976399495400566249571554\
094495292701957093458478414339743747576653696376752337387560862213437\
171824313862829623700800362750977008073325563635225466282360187411791\
004460727184883484132079024845042715007472443596920902083444577226102\
532571137758684844047433693020711502451132357889672168805441775716452\
471223267485604392625754951730382003113622464055081487391284375971238\
853510627596734712602568020285819183336971657562681282095948698659234\
622044625115938725879037169105695234784581029833751973597798676995302\
820884283310795836154247808946969995709972175704217930343337176372368\
862218152343059149076729388531979947396606020581038592064065753946089\
640553006735037214127820206440877419296330789981018521912638631997758\
154425722605472882333085781306809018684379163283706047649566390105938\
809942463192339285589573741721981180866761153351707263614777114324027\
136937248695379341939585067028628395598691094985690489914777669408583\
746705372076602176542601034547167613728331521534397507629206646312256\
534389673241695353105144035296082219501881690212574125509794054226513\
021405438270518614391742936205107159583300586830731485581286071874470\
727979146719804857783111177975437027458797939861069790512476711658674\
604230600339893922108479411334570557026813885541027537801880370343641\
023092718791324902103002359243661089565315113361994869576663697256249\
871813213413860690428249292925393115314038327834441363912113929007244\
105471054120698871274356091169876130969421130575239706338621628737248\
013101040294797899746928168358267493688407646225609161528591367536543\
750216752349842458665061074845656012652829943203210569645609847648814\
464710028370158307713272436594791806761106756447396480204361732530948\
047135168932828677349682361477634216624699993497496226478447072051536\
537255860545682337598542734838920307113252752500355434131067856495860\
013015939155932613207379195719908219623615714946387317825854512782265\
937569392814353157780475720686522817497914676681978626797926015043212\
826447031437776044826145179616020689954105388440566444703570607428452\
666825975085482722275544761731568680350317329391266355823582648567151\
947184773262263887240258693650257727510270752946231093646966589567787\
620541476932789987792695230980505405781968028822750078627313420324636\
601974910918848756407395140464009616507265266662863541465532812264494\
701633405156590660566452973010384370953314634322907040294450198353359\
957924325079183731192016465188487102068495632766765696940620843045103\
075957849189229063712905056032682667355175647119287597317113053888818\
341747269372365744795936558893311837335313287268687137649853296271832\
132369232948513470597966489726144074597206798929415298656496523421111\
438648338467916198955418864697867358689690541049939526892432203616666\
140157354244656146942523547307257405470211487674868073790307956335298\
035604188659325178691582979462715732209779303725246839056014094195154\
353820392910656204599835271073979873482650919077963655893924294796451\
071058930326741588268399079872254763237331178544518654879897999507167\
887498691051777847315585246832306484530047575270468824468839052404478\
471209601574499599308373476806751619934920860932630254791766257400546\
678194740441580832758218048544328980079529926710475069635876888842466\
467601583225867324238379637406226419707584550480244266279922404975917\
076093198953314433166768787654670557582769176583516340512714290053869\
488503951481971926825225950809407051148355971332272041694340467202263\
110935023726355678876173054870475696464256078760528321123516989048437\
905956100976188680575762923547321486475620783046279082273767387016824\
192792115286420878195296354046581539918274861338294922615905787217630\
753697407328812404074746964527035054665330473788617312281599693667903\
884726439880556302179216802454355012570038449126286996206666650775493\
528788476341408273837500438601870416699570809752085526061727790246214\
345643727730520403638924836303813927425447168031067163854295638774643\
166925696428378811144048893909874892635249403446686352691414736194313\
298767484562415849033332860270431449712286909235097808003929552365629\
010360548150077790573248056575513757799999890275575803774798799936015\
705905616634068871497563319841541352544107825662325607124684540278874\
608498624966561241559324542726007033114316454480672240712785896185764\
018459995360582270280586015978104402627028899003008502473747055638994\
967693615667231861323852556312680406367619704217960527830076328909665\
965806712800730336437160882833491675135268112563043378424238104782680\
959602102200424228996956152636857516180424517857400628028239135084923\
094773283114860671676978258922786514794732997721390398253472889571181\
542100313183931206138889694321740603908008622135736073752391733441636\
975148234408515167723600503139787211196698575465893988829247150988295\
132937089264063096302850653741709786986733436740774656976239880063657\
116155268958086159207748442275467563439789929514686396554465496658320\
223447220380884994806499212763873883811980450535445134692803972297225\
867200805366193198427695091115005764789732413669084712930690653442040\
106813786879863642703849455004180398239402073854230429039162641031954\
629435099190465441189701444312997824242458302224265488820857153390295\
433793663904480181503821987893778163121705707885184807286156520157629\
597511728693723440564167397261196843175017576158234990810817702896131\
719777996015606434124732743140927899396903532009620709667134228528325\
848706155364762181691764906498404995473573942979224307302520686325900\
288588511145953186978555460750414834235036978817588590166303626158325\
467769294871096811226986831480934663697186308993101874698672583904437\
163465158962552331778051757595797546950242290952793645521079004895039\
692767591940245446458333450596276630537891924213895070280398426097844\
530715344299379556436113658378942976207843994805006705871918214642436\
109945838548091417431928423665728188757851328090987241230795008197684\
315848649413968970776608596456806202072136369956191814042287222372420\
376209481097924531222327898301388536719301209812529374055978383161560\
402366674953377258306488393460543898212575858060374138609143943928859\
421499452693460735272584637554217829456324966124714620484172913424446\
250636641856678652492289914229876278180893702329869197654678473185792\
094874734672934868913884518473192107135666898214464737134834616023649\
053147415067806966481952994992502849916799522073929134809911363179677\
895671189148802338738965744455969389857438105112202482394405648155050\
107148182005207110004872831031995654451276551356170911494177294990239\
706406481375465466239414677940243242307424235254719725545446624971669\
702152385191708483627545184792059676994807387702668551969466174546191\
070089976167204039385542807339087642680041473305403563782932907930025\
137631116987099138156108731309442818766102387852144495815142081633981\
632881697289008544444602806582589282128339148425329485634849848220805\
882301325917949871098113905536521369117102228224267823573270306372102\
733761111537455389558353499292211244045077468444864626142113431527586\
522286466400715414584503504772063203681892773106418220004132714081774\
597491999689729300930217473244191652387960550998436458561695613745236\
001166814296581318010803425510340274430917394158798175053338323409296\
895304078316728847185492126230467648404918731759558489275204921648189\
641334613191196227133110671760170019469237970548463261174795407272273\
522594027490266679150920541151365410195788704615740727927544780544422\
598110239988012126879177000540770749825882570260436809736803340431649\
136968190510191903550704362810196734029394585868150873111624960230230\
557742069350224866922860141599641459998468635023793968673951162897119\
728086035656539953320600711628909574730519685523709373470327540705653\
335220915475511410416276072511187233012726872585473193916894040338571\
374438826193136849996054292140905498913040046174642438233669539176310\
583789607407253512180368844437606025278249024331609799279741279611616\
861322584297518411616294781785530343484052036928017813197714542874623\
893104213468783249037341094505389577141052425828443310012958430792311\
727117988346582534694572112528868607300926008059143735064550160993534\
371893959294190897252785800898998220518312815414328282874244854542483\
084144884284661147300876442953535032740155789184698983999831384346153\
983006391197340820087681150346256250121310000144506507275816653211852\
630981975984817089090736179427993067512616781166472204275999534793553\
617322021833089272400054973894297458318063353685017787841264474553106\
360829049698395091798134340765126619660886558810014489484062709914663\
708741730650944920828694430958398777612704295668727426847767255490582\
442679545627467864278473335035173682763601472415196578002079707749577\
314107135213271993728277051735738264251975836466432512732611786689972\
608699337829948196681354684107480481385484849536484464106863440975075\
994217657465056219979904595946381966476849760448223076261701459070061\
687625054331070175625148912661262855682533836542470290189307124949454\
672111611301805004282852900469603204454324036160696770568960944006915\
594827374701825793755790511037718231065384570551424914193952437022019\
147130808230140601516999108348126846206887388610494786068336045545230\
386547383991447354800219696499145798056154296637585126096623520286444\
288305461145769481278589644578052606086180987165823906712158053404792\
980245030450164180495915810341531071371713245374578291912729968835571\
659825921274987410512270834924930038942448094826206189084393728747672\
357486250170830682722765817202938882549637223733854649840690650685232\
211002887389219217763704500338914117582617774854375481599185641152046\
183882661395114967337515949838169059628528759746112017143381482333240\
207636582516552896998276786656377571917952133344673723723199179946376\
062254968796003889455221680129540086287321979565069006140531343219593\
747069127462641245536369725942802473102446619255641348424461524297528\
641759974893850890344358331952587334415026185630433554813105770680276\
206280811154949857037528958921963356897630116085109662629658178710778\
798507677725507889134611505315019012251749685690615365792458854857564\
533772662584359952011155264798453844727367592264801349010155252265810\
515246872918204705203793356728720160385276922933864379463998271968011\
571842050057502044481500963066684456034610372353292476835007171599185\
633205112254564334103161056277370091676704684362484674751703624041192\
483451798952663197567989367387817982243873922712260253289081890271484\
747615351738812175971046116046683715704512701857342532265087086607996\
935283737670167056570125886297302351164891412546399612213734288573556\
707802998705475256939453877325826737570250328135497596341563973604069\
510058749824467593715612892797143945980953495801551897876585896910826\
657340220056000137661513683486183600171373811125423027860468400737050\
207216308417605601896328260029394054079292835908268096879154275973758\
803537767265303505542897864749285971624839089144357359776006475483809\
144785869118854493414954429886053110057911071312486249141267331932731\
443170671560086590341048521718826157724599080397854324398250330127048\
599828584475615760524773238222102476324281852003060478889467087936064\
942127015543352629999555455572774241802799902310803374356753670810717\
627142023717059360295954738858332133152053518410378971332898862617963\
385643221635046420724460061022318008822037969715733460287810128018162\
609928288493671713129317148472599626406209968454082954389237826444459\
758905973724812897657188701627543464370788843117544465505781860719350\
587987395303959379133404503898926022219829986363314693902502804136730\
055576160428616527247857010585845882973679162782760983001119225850793\
470860387219780160062333082975943454952693122775459243261504221260853\
490483200000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
000000000000000000000000000000000000000000000000000000000000000000000\
00000000000000000000000000
```
Larger values work fine, but exceed the maximum answer size allowed here.
[Answer]
# [Scala](http://www.scala-lang.org/), 40 38 bytes (supporting Big Integers)
```
1.to(_).map(x=>BigInt(x)pow x).product
```
Provides exact results up to crazy large numbers with several billions of digits, namely up to `Hyperfactorial(2^31-1)`.
Saved 2 bytes thanks to @user.
[Try it online!](https://tio.run/##JcyxDoIwFEbhnaf4x3aQwGqERAeDT2FqKaYGe2/KRWsMz14JbiffcCZrRpPp9nBW0H3YxbOxQtGbES6JC/2EIzO@BfBabZjDHpcgaFqc/H2rXJdC6qrLp2GVmvbvKmmmN5IuOVI/W8nAQBHK47BDDSHUVaW3M8DRBxmDWv/Ka73aUiz5Bw "Scala – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 7 bytes
```
⟦gjz^ᵐ×
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//9H8ZelZVXEPt044PP3/f4v/UQA "Brachylog – Try It Online")
### Explanation
```
⟦ Range: [0, …, Input]
g Nest in a list: [[0, …, Input]]
j Juxtapose: [[0, …, Input], [0, …, Input]]
z Zip: [[0, 0], …, [Input, Input]]
^ᵐ Map power: [1, …, Input^Input]
× Multiply: 1 × … × Input^Input
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 6 bytes
```
*/&!1+
```
[Try it online!](https://ngn.codeberg.page/k#eJxtj01ugzAQhfdzCqpUVdKK+BcbsKJue4coUlwwAQUwBVciitKz105TNYvOYt43b2Yxr8qf0Xm+LB7IC4DLz4/b09eYV1EUzWpvj2q5r3TTqlmd1LjaXfzNFiuy80J+hCoehCmC0wBcUSn4FROVCo5DhUkojhnBMv2zpGKMZFIIlqVSEnpbAILauWHKESpsaQ62rdaT08XRzEWt+4NZF7ZDH59mco3tJ0RZkgmOmm5oTWd6F7vaxPVpMGOlC2fHRrevgz6YDX1y+n3T2bKpGlOWZioW3oidHQB6H/lt2a8AeyBArp36zoEFxilwr9dwkHj6zQYiHN1HA+mdf5JB6v0kEf5ZJjNOJBVhktlt/Q14emba)
* `!1+` generate `0..x` (e.g., with an input of `4`, generate `0 1 2 3 4`)
* `&` take `n` copies of each `n`, e.g. zero copies of `0`, one copy of `1`, two copies of `2`, etc.)
* `*/` calculate (and implicitly return) the product
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 4 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md "Thunno 2 Codepage")
```
RD*p
```
#### Explanation
```
RD*p # Implicit input 6
R # Push the one-range [1, 2, 3, 4, 5, 6]
* # Each to the power of...
D # ...itself [1, 4, 27, 256, 3125, 46656]
p # Product of the list 4031078400000
# Implicit output
```
[Answer]
# [BLC](https://tromp.github.io/cl/Binary_lambda_calculus.html), 8 bytes (61 bit)
```
0000010101110000001011010011100000010111101100111010001100010
```
Works for Church encoded numerals with `1=i`. The code is derived from the common `fac` function. Degolfed to [bruijn](https://bruijn.marvinborner.de):
```
fac [[1 [[id (1 [[2 1 (1 0)]])]] [1] [0]]]
id 0
hyperfac [[1 [[exp (1 [[2 1 (1 0)]])]] [1] [0]]]
exp (0 0)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
LDmP
```
[Try it online](https://tio.run/##yy9OTMpM/f/fxyU34P9/EwA) or [verify all test cases](https://tio.run/##yy9OTMpM/W9xbJKfvZLCo7ZJCkr2fv99XHID/uv8BwA).
**Explanation:**
```
L # Push a list in the range [1, (implicit) input-integer]
# (note: input 0 will create the list [1,0])
D # Duplicate this list
m # Take the exponent of the two lists at the same positions
P # Take the product of this list
# (after which the result is output implicitly)
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 4 bytes
```
:t^p
```
[Try it online!](https://tio.run/##y00syfn/36okruD/fxMA "MATL – Try It Online")
First MATL answer!
Uses the same range-dup-power-product
[Answer]
# [Zsh](https://www.zsh.org), 33 bytes
```
for ((a=1;n++<$1;a*=n**n)):
<<<$a
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuhY3FdPyixQ0NBJtDa3ztLVtVAytE7Vs87S08jQ1rbhsbGxUEiEKoeoXRxvHQpkA)
[Answer]
# Python 3.8 (pre-release), 59 bytes
```
from math import*
lambda n:prod(i**i for i in range(1,n+1))
```
[Try it online!](https://tio.run/##BcE7DoAgDADQ3VN0BHQhLsbb1CDSxH7SsHj6@p59c6jsh3lEd2VgnAOITX2W5UW@GoKc5toSlULQ1YGABBzluVPdZK05R/w)
[Answer]
# [Raku](http://raku.org/), 17 bytes
```
{[*] [\R*] 1..$_}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/OlorViE6JghIGurpqcTX/i9OrFRQUolXsLVTqE5TAIooKaTlFynEGRr8BwA "Perl 6 – Try It Online")
* `1 .. $_` is the sequence of numbers from 1 to the input argument.
* `[\R*]` is the "triangular reduction" (scan) of those numbers with the `R`eversed (and thus right-associative) multiplication operator, producing this list: ùëõ, ùëõ √ó (ùëõ-1), ùëõ √ó (ùëõ-1) √ó (ùëõ-2), ..., ùëõ √ó (ùëõ-1) √ó (ùëõ-2) √ó ... √ó 1.
* `[*]` is the product of those numbers, which contains ùëõ factors of ùëõ, ùëõ-1 factors of ùëõ-1, etc, as required.
If the input argument is zero, `1 .. $_` is an empty range, `[\R*]` applied to that range produces an empty list, and `[*]` applied to that list returns the multiplicative identity element 1.
] |
[Question]
[
Saw this in a PHP challenge. The objective is to make a chessboard with 64 squares (8\*8) with the minimum amount of code.
Simple enough, I made mine in PHP in 356 bytes (not impressive, I know) and I would like to see some other aproaches.
This can be made in a language of your choice, as long as you keep it vanilla, so no imports.
Smallest byte count wins.
The output should look like this:

And my code:
```
<table><?php
$c='black';function p($c,$n){echo'<td style="width:50px;height:50px;background:'.$c.'"></td>';if($n==1){echo"<tr>";}}for($i=1;$i<=64;$i++){if($i%8==0&&$c=="black"){$c="white";$n=1;}elseif($i%8==0&&$c=="white"){$c="black";$n=1;}elseif(isset($n)&&$n==1){$n=0;}elseif($c=="black"){$n=0;$c="white";}elseif($c=="white"){$n=0;$c="black";}p($c,$n);}
```
Or readable:
```
<table><tr>
<?php
$color = 'black';
function printcolor($color, $nl) {
echo '<td style="width:50px; height:50px; background:' . $color . '"></td>';
if ($nl == true) {
echo "</tr><tr>";
}
}
for ($i=1; $i<=64;$i++) {
if ($i % 8 == 0 && $color == "black") {
$color = "white";
$nl = true;
} elseif ($i % 8 == 0 && $color == "white") {
$color = "black";
$nl = true;
} elseif (isset($nl) && $nl == true) {
$nl = false;
} elseif ($color == "black") {
$nl = false;
$color = "white";
}
elseif ($color == "white") {
$nl = false;
$color = "black";
}
printcolor($color, $nl);
}
```
**Edit:**
Sorry I wasn't very specific at first:
* Squares should have 50px \* 50px except for vectorial images.
* Output format or size is not relevant nor it needs to be an image.
* For evaluation purposes the output must be visible such as in an image file or a screenshot
* No libraries written after the challenge was posted
[Answer]
## vim, ~~47~~ ~~46~~ ~~44~~ 43
crossed out 44 is still regular 44...
```
iP1 400 <C-p><cr><esc>50i1<esc>YpVr0yk3PyG49PyG:m$<cr>p2GyG3P
```
```
i enter insert mode
P1 signal to NetPPM that we're using black&white (PBM) format
400 width
<C-p> fancy trick that inserts the other 400 for height
<cr><esc> exit insert mode on the next line
50i1<esc> insert 50 '1's (black)
YpVr0 insert 50 '0's (white) by duplicating the line and replacing all chars
yk copy both lines (yank-up)
3P paste three times; this leaves us on line two
yG copy from line 2 to end of file (this is a full row of pixels now)
49P we need 50 rows of pixels to make a complete "row"; paste 49 times
yG copy the entire row of the checkerboard
:m$<cr> move line 2 (the line we're currently on) to the end of the file
this gives us the "alternating rows" effect
p we're now on the last line: paste the entire row we copied earlier
2G hop back to line 2 (beginning of image data)
yG3P copy the entire image data, paste 3 times
```
Outputs in NetPPM format (PBM):
[](https://i.stack.imgur.com/IZYpi.png)
[Answer]
## CSS, 244 bytes
```
html{background:#fff}body{width:400px;height:400px;background:linear-gradient(45deg,#000 25%,transparent 25%,transparent 75%,#000 75%)0 0/100px 100px,linear-gradient(45deg,#000 25%,transparent 25%,transparent 75%,#000 75%)50px 50px/100px 100px}
```
```
html {
background: white;
}
body {
width: 400px;
height: 400px;
background:
linear-gradient(45deg, black 25%, transparent 25%, transparent 75%, black 75%) 0px 0px / 100px 100px,
linear-gradient(45deg, black 25%, transparent 25%, transparent 75%, black 75%) 50px 50px / 100px 100px
}
```
Explanation: A 100x100px diagonal linear gradient is created with four stops so that most of the gradient is transparent except for two 50px triangular corners. (See below snippet). Adding a second gradient with a 50x50px offset fills in the missing halves of the squares. Increasing the size of the body then allows the resulting pattern to repeat to fill the entire chessboard.
```
html {
background: white;
}
body {
width: 100px;
height: 100px;
background: linear-gradient(45deg, black 25%, transparent 25%, transparent 75%, black 75%) 0px 0px / 100px 100px
}
```
[Answer]
## Mathematica, 34 bytes
```
ArrayPlot@Array[Mod[+##,2]&,{8,8}]
```
The output is a vector image and is surrounded in a frame.
Instead of correctly positioning 32 rectangles, we can just generate a binary matrix and make `ArrayPlot` work for us:
[](https://i.stack.imgur.com/1z6KD.png)
[Answer]
# Octave, ~~20~~ 18 bytes
Thanks to [@Bruno](https://codegolf.stackexchange.com/users/49903/bruno) for shaving off 2 bytes.
```
imshow(invhilb(8))
```
Result:
[](https://i.stack.imgur.com/thVLw.png)
This answer uses a technique found [here](http://matlabtricks.com/post-31/three-ways-to-generate-a-checkerboard-matrix). It also relies on the automatic scaling of images in Octave depending on the size of the figure window.
[Answer]
# Mathematica, ~~81~~ ~~72~~ 55 bytes
```
Graphics[Rectangle/@Select[Range@8~Tuples~2,2∣Tr@#&]]
```

Image is of a previous version's evaluation, but still looks the same.
[Answer]
# Pure Bash (no external utilities), 133
I saw [@Doorknob's comment](https://codegolf.stackexchange.com/questions/71093/build-a-chessboard/71111#comment173980_71093) as a bit of a challenge. Its a bit long, but here goes:
```
echo \# ImageMagick pixel enumeration:400,400,1,rgb
for((;x=p%400,y=p/400,c=1-(x/50^y/50)&1,p++<160000;));{
echo "$x,$y:($c,$c,$c)"
}
```
Output is in [Imagemagick's .txt format](http://www.imagemagick.org/Usage/files/#txt). Note this is pure Bash. Neither Imagemagick nor any other external utilities are spawned to generate this output. However, the output may be redirected to a .txt file and viewed with the ImageMagick `display` utility:
[](https://i.stack.imgur.com/Px4iN.png)
This image format is nice because not only is it pure text, it is little more than a list of all pixels (x, y and colour value), one per line. It is a fairly simple matter to derive all pixel values arithmetically in one big loop.
---
# Previous answer, 167
```
echo "\"400 400 2 1\"
\" c white\"
\"b c black\""
printf -vf %50s
a="$f${f// /b}"
o=("\"$a$a$a$a\"" "\"${f// /b}$a$a$a$f\"")
for i in {0..399};{
echo "${o[i/50%2]}"
}
```
Output is in the [X\_PixMap text image file format](https://en.wikipedia.org/wiki/X_PixMap#XPM2), which may also be viewed with the ImageMagick `display` utility.
Note I've taken as much out of the XPM format as I could such that `display` would still accept it. I was able to take out all the [c](/questions/tagged/c "show questions tagged 'c'") boilerplate with the exception of the `"` double quotes around each line. No idea what other - if any - utilities will accept this.
[Answer]
# Octave, 48 bytes
```
imwrite(kron(mod((t=0:7)+t',2),ones(50)),'.png')
```
This works exactly the same as my [Matlab answer](https://codegolf.stackexchange.com/a/71120/24877), but there is no `spiral` in Octave. Instead we use a feature that Matlab does not have: We can use the assignment of `t` already as an expression, and later use `t` again in the same expression.
(This is the rescaled version, I do not want to clutter the answers here=)

[Answer]
## PowerShell + browser of your choice, ~~149~~ 143 bytes
The inability to use imports is really tough, as all of the GDI calls (i.e., the stuff PowerShell uses to draw) are buried behind imports in .NET ...
```
"<table><tr>"+((1..8|%{$a=$_;-join(1..8|%{'<td style="width:50px;height:50px'+("",";background:#000")[($a+$_)%2]+'"></td>'})})-join'</tr><tr>')
```
Edit - saved six bytes thanks to [@NotThatCharles](https://codegolf.stackexchange.com/users/13950/not-that-charles)
This uses two for-loops from `1..8` to generate a big-ol' HTML string, similar to the PHP example provided, and output it onto the pipeline. Each time through we calculate whether to append `;background:#000` for the black backgrounds by taking our current position on the board modulo 2.
To use, redirect the output into the file of your choice (e.g., with something like `> chessboard.htm`) and then launch that in the browser of your choice. For the screenshot below, I used "c.htm" and Firefox.
[](https://i.stack.imgur.com/fzDsc.png)
[Answer]
# [Python 3](https://python.org), ~~365~~, ~~288~~, ~~270~~, 256 bytes
Thanks @Razetime, @mehbark and @Amazeryogo for the suggestions
```
from turtle import *
B=range
H=Screen()
A=Turtle()
def F():
for C in B(4):A.fd(30);A.lt(90)
A.fd(30)
for D in B(8):
A.up();A.setpos(0,30*D);A.pd()
for G in B(8):
if(D+G)%2==0:E='black'
else:E='white'
A.fillcolor(E);A.begin_fill();F();A.end_fill()
```
[Try it online!](https://repl.it/@IntrstedCoder/chessboard)
Admittedly not good:) first contribution
[](https://i.stack.imgur.com/h7eMx.gif)
[Answer]
# PHP + CSS + HTML, 136 bytes
Taking the table aproach to a higher level:
```
<table><?for(;++$i<9;)echo'<tr>',str_repeat(["<td b><td>","<td><td b>"][$i&1],4);?><style>td{width:50px;height:50px}[b]{background:#000}
```
It generates the following code:
```
<table><tr><td><td b><td><td b><td><td b><td><td b><tr><td b><td><td b><td><td b><td><td b><td><tr><td><td b><td><td b><td><td b><td><td b><tr><td b><td><td b><td><td b><td><td b><td><tr><td><td b><td><td b><td><td b><td><td b><tr><td b><td><td b><td><td b><td><td b><td><tr><td><td b><td><td b><td><td b><td><td b><tr><td b><td><td b><td><td b><td><td b><td><style>td{width:50px;height:50px}[b]{background:#000}
```
It relies heavily on browsers' kindness and CSS.
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 11 (27) bytes
```
8:t!+Q2\TYG
```
This produces the following figure. It doesn't have an intrinsic size; it's automatically scaled depending on the size of the figure window. This seems to be allowed by the challenge.
[](https://i.stack.imgur.com/SROeF.png)
### Explanation
```
8: % row vector [1,2,...8]
t! % duplicate and transpose into column vector
+ % 8x8 matrix with all pairwise additions
Q % add 1
2\ % modulo 2. Gives 8x8 matrix of zeros and ones
TYG % draw image
```
---
If autoscaling is not allowed:
```
'imshow'8:t!+Q2\50t3$Y"0#X$
```
produces the following figure with 50x50-pixel squares
### Explanation
[](https://i.stack.imgur.com/ThxXe.png)
```
'imshow' % name of Matlab function
8:t!+Q2\ % same as above. Produces 8x8 matrix of zeros and ones
50t3$Y" % repeat each element 50 times in each dimension
0#X$ % call imshow function with above matrix as input
```
[Answer]
# Pyth, ~~28~~ 26 bytes
```
J*4+*50]255*50]0.wm_mxkdJJ
```
Explanation
```
J - Autoassign J = V
*50]0 - 50*[0]
*50]255 - 50*[255]
+ - ^^+^
*4 - 4*^
.w - write_greyscale(V)
m J - [V for d in J]
_ - reversed(V)
m J - [V for k in J]
xkd - k^d
```
Python equivalent
```
J = 4*(50*[255]+50*[0])
write_greyscale([[k^d for k in J][::-1] for d in J])
```
[Try it here (just the colour values)](http://pyth.herokuapp.com/?code=J*4%2B*50%5D255*50%5D0jbm_mxkdJJ&debug=0)
Output:
[](https://i.stack.imgur.com/rQz8N.png)
[Answer]
# FFmpeg, 78 ~~82 100~~ bytes
Finally got around to cleaning the board.
```
ffplay -f lavfi color=s=400x400,geq='255*mod(trunc(X/50)+trunc(Y/50)+1,2):128'
```
[](https://i.stack.imgur.com/KqdZ4.png)
---
**Older**:
```
ffmpeg -f lavfi -i "color=tan@0:256x256,format=ya8" -vf "scale=400:-1:alphablend=checkerboard" .jpg
```
Will exit with error, but after producing image below.
[](https://i.stack.imgur.com/PwLjq.jpg)
(board's collected some dust)
[Answer]
# Jelly, 26 bytes
```
400R%2ẋ€50FU;$ẋ4;;;1j⁶;”PU
```
Since Jelly has no support for images built in, we print a PPM image.
[Try it online!](https://tio.run/#jelly#code=NDBSJTLhuovigqw1RlU7JOG6izQ7OzsxauKBtjvigJ1QVQ&input=) (smaller board for speed, raw PPM)
### Results
[](https://i.stack.imgur.com/pWcTv.png)
### How it works
```
400R%2ẋ€50FU;$ẋ4;;;1j⁶;”PU Main link. No arguments.
400 Set the left argument to 400.
R Yield [1, ..., 400].
%2 Compute the parity of each integer.
ẋ€50 Replace each parity by an array of 50 copies of itself.
F Flatten the resulting, nested list.
This creates the first rank of the board.
$ Combine the two atoms to the left:
U Reverse the array of parities.
; Concatenate the reversed array with the original.
This creates the first two ranks of the board.
ẋ4 Repeat the resulting list four times.
This creates all eight ranks of the board.
; Append 400, the link's left argument.
; Append 400, the link's left argument.
;1 Append 1.
j⁶ Join, separating by spaces.
;”P Append the character 'P'.
U Reverse the resulting list.
```
### Non-competing version (24 bytes)
The newest Jelly interpreter that predates this post didn't vectorize `x` properly. With the latest version, 2 additional bytes can be saved.
```
400R%2x50U;$ẋ4;;;1j⁶;”PU
```
The only difference is that `x50` yields a flat list (with every original element repeated 50 times), so `F` is no longer necessary.
[Answer]
# Matlab, 47 (24) bytes
```
imwrite(kron(mod(spiral(8),2),ones(50)),'.png')
```
This works exactly the same as my [Octave answer](https://codegolf.stackexchange.com/a/71118/24877), but I was able to use `spiral` which saved one byte. `spiral(n)` makes an `nxn` matrix and fills it spiraling with the first `n^2` integers.
If vectorgraphics are allowed, we could do it in 24 bytes:
```
imshow(mod(spiral(8),2))
```
(This is the rescaled version, I do not want to clutter the answers here=)

[Answer]
HTML with utf-8 - 66b
```
<div style="font:100 50px/48px serif">▚▚▚▚<br>▚▚▚▚<br>▚▚▚▚<br>▚▚▚▚
```
▚ is short-direct utf for entity **&# 9626 ;**
[Unicode Character 'QUADRANT UPPER LEFT AND LOWER RIGHT' (U+259A)](http://www.fileformat.info/info/unicode/char/259a/index.htm "Unicode Character 'QUADRANT UPPER LEFT AND LOWER RIGHT' (U+259A)")
silly me, was looking for a 1 utf-8 char solution -would have been... 1b!
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~51~~ 30 bytes
```
'P1'
2⍴400
50/50⌿(⍳8)⌽8 8⍴'01'
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKO94L96gKE6l9Gj3i0mBgZcpgb6pgaPevZrPOrdbKH5qGevhYIFUErdwFAdpPp/AQA "APL (Dyalog Extended) – Try It Online")
Outputs a netpbm image. Save the result to a .pbm file and view [here](http://paulcuth.me.uk/netpbm-viewer/).
Since the output is too large for tio, here's the [generated output.](https://raw.githubusercontent.com/razetime/code-golf/master/APL-code/chessboard.ppm)
-21 bytes(!) from Adám.
Here's the output converted to png:
[](https://i.stack.imgur.com/HbHrR.png)
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG9qZv6jtgkG/9UDDNW5jB71bjExMODSMDU4PN3UQP9R72YLzUc9ezWAggpADJTWAMoBKXUDdU0dKNNQXVNT8z/FJgAA "APL (Dyalog Extended) – Try It Online")
[Answer]
# CJam, 27 bytes
```
"P1"400__,2f%50e*_W%+4*~]S*
```
[Try it online!](http://cjam.tryitonline.net/#code=IlAxIjQwX18sMmYlNWUqX1clKzQqfl1TKg&input=) (smaller board for speed, raw PPM)
### Results
[](https://i.stack.imgur.com/yRPnA.png)
### How it works
```
"P1" e# Push that string.
400__ e# Push three copies of 400.
, e# Turn the last one into [0 ... 399].
2f% e# Compute the parity of each integer.
50e* e# Repeat each parity 50 times.
e# This creates the first rank of the board.
_W% e# Create a reversed copy of the resulting array.
+ e# Concatenate the original with the reversed array.
e# This creates the first two ranks of the board.
4* e# Repeat the resulting array four times.
e# This creates all eight ranks of the board.
~ e# Dump all of its items (the pixels) on the stack.
] e# Wrap the entire stack in an array.
S* e# Join that array, separating them by spaces.
```
[Answer]
# [Desmos](https://www.desmos.com/calculator/yl6ahgqphz), 136 bytes
```
ceil(sin(x))\left\{6<x<29\right\}>=ceil(sin(y))\left\{0<y<26\right\}
ceil(sin(x))\left\{3<x<27\right\}<=ceil(sin(y))\left\{0<y<24\right\}
```
[](https://i.stack.imgur.com/2mCca.png)
This was the first thing I thought of when I saw this challenge, hopefully it's not stretching it too far.
[Answer]
## PHP, ~~166~~ ~~158~~ 155 bytes
Works in PHP 7.0.2 (short-tags enabled) and Chrome 48.0.2564.97 m
```
<table><tr><? while(++$i<=8){while(++$j<=8){echo"<td style=background-color:".($i%2==0?($j%2==1?0:""):($j%2==0?0:"")).";padding:9></td>";}echo"<tr>";$j=0;}
```
[Answer]
# Perl 5 - 80
Generates a .PBM file:
```
print 'P1'.' 400'x2 .$".(((0 x50 .1 x50)x4 .$")x50 .((1 x50 .0 x50)x4 .$")x50)x4
```
[Answer]
## PHP >=5.4, ~~175~~ ~~159~~ ~~149~~ 116 Bytes
```
<table><tr><? for(;@++$i<65;)echo'<td width=50 height=50 ',$i+@$m&1?:'bgcolor=0','>',$i%8<1?'<tr '.($m=@!$m).'>':'';
```
```
<table><tr><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><tr 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><tr ><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><tr 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><tr ><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><tr 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><tr ><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><tr 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><tr >
```
## Notes
* Shaved 16 bytes - Thanks @insertusernamehere
* Shaved 10 bytes - Thanks @msh210
* Shaved 30 bytes - Thanks @Ismael Miguel
[Answer]
# GIMP, 539 bytes
```
gimp -i -b '(let* ((i (car (gimp-image-new 400 400 1))) (d (car (gimp-layer-new i 400 400 2 "b" 100 0)))) (gimp-image-insert-layer i d 0 -1) (define (t x y) (gimp-selection-translate i x y)) (define (x) (t 100 0)) (define (X) (t -100 0)) (define (y) (t 50 50)) (define (Y) (t -50 50)) (define (f) (gimp-edit-fill d 1)) (define (r) (f) (x) (f) (x) (f) (x) (f) (y)) (define (R) (f) (X) (f) (X) (f) (X) (f) (Y)) (gimp-image-select-rectangle i 2 0 0 50 50) (r) (R) (r) (R) (r) (R) (r) (R) (gimp-file-save 1 i d "c.png" "c.png") (gimp-quit 0))'
```
Ungolfed Scheme script-fu:
```
(let* ((i (car (gimp-image-new 400 400 GRAY)))
(d (car (gimp-layer-new i 400 400 GRAY-IMAGE "b" 100 NORMAL-MODE))))
(gimp-image-insert-layer i d 0 -1)
(define (t x y) (gimp-selection-translate i x y))
(define (x) (t 100 0))
(define (X) (t -100 0))
(define (y) (t 50 50))
(define (Y) (t -50 50))
(define (f) (gimp-edit-fill d BACKGROUND-FILL))
(define (r) (f) (x) (f) (x) (f) (x) (f) (y))
(define (R) (f) (X) (f) (X) (f) (X) (f) (Y))
(gimp-image-select-rectangle i CHANNEL-OP-REPLACE 0 0 50 50)
(r) (R) (r) (R) (r) (R) (r) (R)
(gimp-file-save RUN-NONINTERACTIVE i d "c.png" "c.png")
(gimp-quit 0))
```
In batch mode, create a blank image, create a 50x50 rectangular selection, fill it, and then repeatedly move it around the image, filling in squares. Then save to `c.png` and exit.
Output:
[](https://i.stack.imgur.com/03o2g.png)
[Answer]
# [R](https://www.r-project.org/), ~~40~~ 38 bytes
*Edit: -2 bytes thanks to Robin Ryder*
```
image(matrix(1:0,9,8)[-1,],c=1:0,ax=F)
```
[Try it at rdrr.io](https://rdrr.io/snippets/embed/?code=image(matrix(1%3A0%2C9%2C8)%5B-1%2C%5D%2Cc%3D1%3A0%2Cax%3DF))
This nicely exploits R's argument-recycling to fill a `matrix()` with dimensions of `9,8` with values of `1:0` recycled to fill it. We then use negative indexing `[-1,]` to chop-off the first row.
The `image()` function converts a matrix directly into a coloured image. Here we specify the `c`olor as `1:0` (black & white), and the `ax`es as `F`ALSE.
[](https://i.stack.imgur.com/obqJk.png)
[Answer]
# AppleSoft Basic, 146 bytes
The best (standard) resolution available on the Apple II is `HGR2` mode, at 280x192 pixels, so the squares are 24x24.
Verified at <https://www.calormen.com/jsbasic/>
```
0HGR2:HCOLOR=3:A=0:B=167:GOSUB8:A=24:B=191:GOSUB8:END
8FORI=A TOB STEP48:FORJ=A TOB STEP48:FORK=0TO23:HPLOTI+K,J TOI+K,J+23:NEXT:NEXT:NEXT:RETURN
```
image credit: [Apple II Basic Bot](https://twitter.com/appleiibot/status/1332146305812992000?s=21) on twitter

If we totally ignore resolution & use `GR` mode, 107 bytes:
```
1GR:COLOR=15:A=0:B=7:GOSUB8:A=1:B=8:GOSUB8:END
8FORI=A TOB STEP2:FORJ=A TOB STEP2:PLOTI,J:NEXT:NEXT:RETURN
```
[Answer]
# [iKe](https://github.com/JohnEarnest/ok/tree/gh-pages/ike), 24 bytes
```
,(;cga;t=\:t:2!-20!!160)
```

The core of the technique is to generate a list of x coordinates, divmod them and then take an equality cross-product to generate an appropriate bitmap. Using smaller examples for illustrative purposes:
```
!8
0 1 2 3 4 5 6 7
-2!!8
0 0 1 1 2 2 3 3
2!-2!!8
0 0 1 1 0 0 1 1
t=\:t:2!-2!!8
(1 1 0 0 1 1 0 0
1 1 0 0 1 1 0 0
0 0 1 1 0 0 1 1
0 0 1 1 0 0 1 1
1 1 0 0 1 1 0 0
1 1 0 0 1 1 0 0
0 0 1 1 0 0 1 1
0 0 1 1 0 0 1 1)
```
[try it here](http://johnearnest.github.io/ok/ike/ike.html?gist=5735a344f4bd5c36868f). Technically iKe works on a logical 160x160 pixel canvas, but in full-screen mode (the default when following a saved link) this is upscaled by 3x. I think this is still following the spirit of the question, as the program could assemble a much larger bitmap with the same character count; it just comes down to an arbitrary display limitation.
## Update:
iKe isn't primarily designed for golf, but livecoding still benefits from brevity and sane defaults. As a result of tinkering with this problem, I've decided to permit it to use a default palette if none is provided. This particular solution could now be expressed with:
```
,(;;t=\:t:2!-20!!160)
```
Saving (an ineligible) 3 bytes.
[Answer]
# JavaScript, 150
This can definitely be golfed. It creates HTML.
```
for(i=0;i<8;)console.log(`<b style=margin-${['lef','righ'][i++%2]}t:50;width:50;height:50;display:inline-block;background:#000></b>`.repeat(4)+'<br>')
```
[Answer]
# Ruby with Shoes, 97 characters
```
Shoes.app(width:400){64.times{|i|stack(width:50,height:50){background [white,black][(i/8+i)%2]}}}
```
Sample output:

[Answer]
# Lua + LÖVE, ~~138~~ ~~113~~ ~~112~~ 106 characters
```
function love.draw()for i=0,31 do
love.graphics.rectangle("fill",i%8*50,(i-i%8)/8*100+i%2*50,50,50)end
end
```
Sample output:

[Answer]
## PowerShell + GDI, 346 bytes
```
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
$f=New-Object Windows.Forms.Form
$f.width=$f.height=450
$g=$f.CreateGraphics()
$f.add_paint({0..7|%{$y=$_;0..7|%{$g.FillRectangle((New-Object Drawing.SolidBrush ("white","black")[($_+$y)%2]),(new-object Drawing.Rectangle ($_*50),($y*50),50,50))}}})
$f.showDialog()
```
(newlines count same as semicolon, so newlines for readability)
As opposed to my other [answer](https://codegolf.stackexchange.com/a/71106/42963), this one uses the .NET assemblies to call [GDI+](https://msdn.microsoft.com/en-us/library/windows/desktop/ms533798(v=vs.85).aspx) function calls. Interestingly, it's about twice the length.
The first two lines load the `System.Windows.Forms` and `System.Drawing` assemblies. The first is used for the literal window and the canvas thereon, the second is used for the drawing object (in this code, a brush) that create the graphics on the canvas.
We then create our form `$f` with the next line, and set its `width` and `height` to be `450`. Note that this isn't `50*8`, since these numbers correspond to the border-to-border edge of the forms window, including titlebar, the close button, etc.
The next line creates our canvas `$g` by calling the empty constructor. This defaults to the upper-left of the non-system area of the form being equal to `0,0` and increasing to the right and downward, perfect for our needs.
The next line is the actual call that draws the graphics, with `$f.add_paint({...})`. We construct the graphics calls by double-for looping from `0..7` and carrying a helper variable `$y` through each outer loop. Each inner loop, we tell our canvas to `.FillRectangle(...,...)` to draw our squares. The first parameter constructs a new `SolidBrush` with a color based on where we're at on the board. Other options here [could be](https://msdn.microsoft.com/en-us/library/system.drawing.brush(v=vs.110).aspx) a hatch, a gradient, etc. The second parameter is a new `Rectangle` object starting at the specified x `$_*50` and `$y*50` coordinates and extending for `50` in each direction. Remember that `0,0` is the top-left.
The final line just displays the output with `.showDialog()`.
[](https://i.stack.imgur.com/FE5IG.png)
Note that since we're creating a *form* object, and PowerShell is all about the pipeline, closing the pop-up form will pass along a `System.Enum.DialogResult` object of `Cancel`, since that's technically what the user did. Since we're not capturing or otherwise doing anything with that result, the word `Cancel` will be displayed to STDOUT when the program concludes, as it was left on the pipeline.
] |
[Question]
[
What are some clever (brief and idiomatic) approaches to taking a list of strings and returning a single properly punctuated string built from the list, with each element quoted.
This came up for me while [experimenting with Groovy](https://stackoverflow.com/q/25793522/656912), for which my too-literal, but illustrative solution is
```
def temp = things.collect({"\'${it}\'"})
switch (things.size()) {
case 1:
result = temp[0]
break
case 2:
result = temp.join(" and ")
break
default:
result = temp.take(temp.size()-1).join(", ") + ", and " + temp[-1]
break
}
```
That is, `['1']` should yield `'1'`, `['1','2']` should yield `'1 and 2'`, [see what I did there?] and `['1','2','3']` should yield `'1, 2, and 3'`.
I have some good answers for Groovy, but I'd like to see what other languages can do.
What are some *compact* clever approaches in various languages that take advantage of the features and idioms of those languages?
[Answer]
# CSS, ~~132~~ ~~116~~ 115 bytes
```
a:not(:last-child):nth-child(n+2):after,a:nth-last-child(n+3):after{content:","}a+:last-child:before{content:"and "
```
```
<p>
<a>one</a>
</p>
<p>
<a>one</a>
<a>two</a>
</p>
<p>
<a>one</a>
<a>two</a>
<a>three</a>
</p>
<p>
<a>one</a>
<a>two</a>
<a>three</a>
<a>four</a>
</p>
```
```
a:not(:last-child):nth-child(n+2):after,a:nth-last-child(n+3):after{content:","}a+:last-child:before{content:"and "
```
CSS is not seen too often in code golf because it can only format text, but it actually works for this challenge and I thought it would be fun to do. See it in action using the snippet above (click "Show code snippet").
List should be in a linked HTML file with each element surrounded by `<a>` tags and separated by line breaks. The list items should be the only elements in their parent element, e.g.
```
<a>one</a>
<a>two</a>
<a>three</a>
```
## Explanation
```
a:not(:last-child):nth-child(n+2)::after,
a:nth-last-child(n+3)::after {
content: ",";
}
a + :last-child::before {
content: "and ";
}
```
Let's consider the ungolfed version above. If you're not familiar with how CSS works, everything outside the curly braces is a selector that determines the set of HTML elements to which the declarations inside the braces apply. Each selector-declaration pair is called a *rule*. (It's more complicated than that but will suffice for this explanation.) Before any styling is applied, the list appears separated by only spaces.
We want to add commas after every word except the last, except for two-word lists, which get no commas. The first selector, `a:not(:last-child):nth-child(n+2):after`, selects all elements except the first and the last. `:nth-child(n+2)` is a shorter way of saying `:not(:first-child)`, and it basically works by selecting elements whose index (starting at 1) is greater than or equal to 2. (Yes, it still confuses me a little. The [MDN docs](https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child) might help.)
Now we just need to select the first element to get a comma *if* there are three or more elements total. `a:nth-last-child(n+3):after` works like `:nth-child`, but counting from the back, so it selects all elements except the last two. The comma takes the union of the two sets, and we use the `:after` [pseudo-element](https://developer.mozilla.org/en-US/docs/Web/CSS/::after) to add `content` immediately after each selected element.
The second rule is easier. We need to add "and" before the last element in the list, unless it is a single element. In other words, we need to select the last element that is preceded by another element. `+` is the [adjacent sibling selector](https://developer.mozilla.org/en-US/docs/Web/CSS/Adjacent_sibling_selectors) in CSS.
[Answer]
# Haskell: ~~81, 77~~ 74 chars
```
f[x]=x
f[x,y]=x++" and "++y
f[x,y,z]=x++", "++f[y++",",z]
f(x:y)=x++", "++f y
```
Haskell features: Pattern matching
[Answer]
## Ruby, 47 bytes
```
q=" and ";p$*[2]?(a=$*.pop;$**", "+?,+q+a):$**q
```
### Explanation
* The input are the command line arguments (`$*`).
* When `$*` has a third element (`$*[2]` does not return nil), take all elements minus the last one and turn them into a comma-separated String using `Array#*`. Finally add an extra comma, the string `" and "` and the last command line argument.
* When `$*` has no third element, two, one, or zero arguments were given. The arguments can safely be joined with the string `" and "` and produce the correct result.
[Answer]
# Python 2 (61)
```
s=input()
d=s.pop()
print", ".join(s)+", and "[8-7*len(s):]+d
```
The main trick is to cut off part of the final joiner `", and "` for one and two elements. For one, all of it is cut out, and for two, the comma is removed. This is done by slicing out `[8-7*len(s):]` (noting that `s` is one shorter after the `pop`).
Unfortunately, `d` cannot just be replaced with its expression or the `pop` would happen too late.
[Answer]
# CSS, ~~62 chars~~ 112 chars
Inspired by the other entries, even shorter. Note that it requires that A elements are not separated by white spaces:
```
a+a:before{content:", "}a+a:last-child:before{content:", and "
```
<http://jsfiddle.net/olvlvl/1Ls79ocb/>
Fix for the "one and two", as pointed at by Dennis:
```
a+a:before{content:", "}a+a:last-child:before{content:", and "}a:first-child+a:last-child:before{content:" and "
```
<http://jsfiddle.net/olvlvl/1Ls79ocb/3/>
[Answer]
# Perl (v 5.10+) - ~~37~~ ~~35~~ ~~34~~ 28
```
@F>2&&s/ /, /g;s/.* \K/and /
```
to be run with `perl -ape`, with the list supplied space separated on `STDIN`.
Output for various inputs:
```
$ perl -ape '@F>2&&s/ /, /g;s/.* \K/and /'
oxford
oxford
oxford cambridge
oxford and cambridge
oxford cambridge comma
oxford, cambridge, and comma
oxford cambridge comma space
oxford, cambridge, comma, and space
```
[Answer]
# Javascript (63)
`l=a.length;l>2&&(a[l-1]='and '+a[l-1]);a.join(l>2?', ':' and ')`
Cases:
* `a = [1]` => `1`
* `a = [1, 2]` => `1 and 2`
* `a = [1, 2, 3]` => `1, 2, and 3`
Caveat: this will modify the last element in an array with length > 2.
[Answer]
# GNU sed - 69 chars including 1 for `-r` flag
```
s/ /, /g
s/( [^ ]+)( [^ ]+)$/\1 and\2/
s/^([^,]+),([^,]+)$/\1 and\2/
```
Takes a space-separated list (fairly idiomatic for shell scripts).
## Example
```
$ sed -r -f oxfordcomma.sed <<< "1"
1
$ sed -r -f oxfordcomma.sed <<< "1 2"
1 and 2
$ sed -r -f oxfordcomma.sed <<< "1 2 3"
1, 2, and 3
$
```
[Answer]
# Python 2 - ~~71, 70~~ 68
```
s=input()
l=len(s)-1
print', '.join(s[:l])+', and '[l<2:]*(l>0)+s[l]
```
Character count including both, `input` and `print`.
[Answer]
## Ruby, 57 bytes
```
f=->l{s=l*', ';s.sub(/,(?!.*,)/,(l.size<3?'':?,)+' and')}
```
I'm joining the string with `,` and then I'm replacing the last comma in the string with an `and` (and optional comma depending on list length).
[Answer]
# Cobra - 60
```
do(l as String[])=l.join(', ',if(l.length<3,'',',')+' and ')
```
Cobra's `List<of T>.join` function lets you specify a different separator for the final two elements of the list, which is what makes this so short.
[Answer]
# Perl - 59
```
sub f{$a=join', ',@_;$#_&&substr$a,(@_>2)-3,@_<3,' and';$a}
```
Joins the list with commas, then if the list has more than one element, either adds `' and'` after the last comma (if length >= 3), or replaces the last comma with it (if length == 2).
[Answer]
# PHP, ~~192~~ ~~167~~ ~~146~~ 136 characters:
```
$n=' and ';$s=count($a);echo ($s<3)?join($n,$a):join(', ',array_merge(array_slice($a,0,$s-2),Array(join(",$n",array_slice($a,-2,2)))));
```
Based on a function I wrote years ago at <http://www.christopherbloom.com/2011/05/21/join-implode-an-array-of-string-values-with-formatting/>
[Answer]
## Batch - 151 Bytes
```
@echo off&set f=for %%a in (%~1)do
%f% set/aa+=1
%f% set/ac+=1&if !c!==1 (set o=%%a)else if !c!==!a! (set o=!o!, and %%a)else set o=!o!, %%a
echo !o!
```
Note; you have to call the script from `cmd` with the `/v` switch set as `on`, this is so I don't have to include the lengthy `setLocal enableDelayedExpansion` in the script. Otherwise add 30 to the byte count, and call the script normally.
```
h:\uprof>cmd /von /c test.bat "1 2 3"
1, 2, and 3
h:\uprof>cmd /von /c test.bat "1 2 3 4 5"
1, 2, 3, 4, and 5
```
[Answer]
## Groovy, ~~47 43~~ 57 characters , JavaScript ES6 56 characters
**Groovy:**
```
(a[1]?a[0..-2].join(", ")+(a[2]?",":"")+" and ":"")+a[-1]
```
Since the array is filled with characters, we can replace `a.size>1` by `a[1]`
**JavaScript, ES6:**
```
a.join(', ').replace(/,([^,]+)$/,`${a[2]?',':''} and$1`)
```
Both cases assume that variable a has the array in question.
[Answer]
# PHP, ~~86~~ 84 chars
```
$a = ['one', 'two', 'three', 'four', 'five'];
```
With the array initialized, we start counting:
```
$L=count($a)-1;$S=', ';$L<2?($S=' and '):($a[$L]='and '.$a[$L]);echo implode($S,$a);
```
Prettified:
```
$last_index = count($a) - 1;
$separator = ', ';
if ($last_index < 2) {
$separator = ' and ';
} else {
$a[$last_index] = 'and '.$a[$last_index];
}
echo implode($separator, $a);
```
The last item in the list is modified. This should be OK because in PHP, array assignment and function calls perform copies.
[Answer]
# CJam, ~~35~~ ~~30~~ ~~28~~ 27 bytes
```
q~)\_"and "L?@+a+_,2=", ">*
```
This is a program that reads from STDIN and prints to STDOUT. [Try it online.](http://cjam.aditsu.net/ "CJam interpreter")
### How it works
```
q~ " Q := eval(input()) ";
) " P := Q.pop() ";
\_"and "L?@+ " P := (Q ? 'and ' : '') + P ";
a+ " Q += [P] ";
_,2=", "> " J := ', '[(len(Q) == 2):] ";
* " R := J.join(Q) ";
" print R (implicit) ";
```
### Example run
```
$ cjam <(echo 'q~)\_"and "L?@+a+_,2=", ">*') <<< '["1"]'; echo
1
$ cjam <(echo 'q~)\_"and "L?@+a+_,2=", ">*') <<< '["1""2"]'; echo
1 and 2
$ cjam <(echo 'q~)\_"and "L?@+a+_,2=", ">*') <<< '["1""2""3"]'; echo
1, 2, and 3
$ cjam <(echo 'q~)\_"and "L?@+a+_,2=", ">*') <<< '["1""2""3""4"]'; echo
1, 2, 3, and 4
```
[Answer]
# Google Sheets, ~~67~~ ~~68~~ ~~67~~ 92 bytes
```
=SUBSTITUTE(JOIN(", ",FILTER(A:A,A:A<>"")),",",IF(COUNTA(A:A)>2,",","")&" and",COUNTA(A:A)-1
```
The input starts at cell `A1` and continuing down for however many entries exist.
`JOIN` merges them all into a string with a comma-space between each.
`FILTER` removes any non-blanks so you don't end up with infinite commas at the end.
`SUBSTITUTE` replaces the last comma (found by `COUNTA` counting the non-blank inputs).
It's not very exciting but it's doable in a single cell.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 27 bytes
```
ṫ$:[`λ¬ `pJ:Ḣ₃[÷ð$Ṡ|‛, j]|_
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%E1%B9%AB%24%3A%5B%60%CE%BB%C2%AC%20%60pJ%3A%E1%B8%A2%E2%82%83%5B%C3%B7%C3%B0%24%E1%B9%A0%7C%E2%80%9B%2C%20j%5D%7C_&inputs=%5B1%5D&header=&footer=)
```
ṫ # Tail extract (x[:-1], x[-1] )
$:[ # If length > 1
`λ¬ `p # Prepend a 'and '
J # Merge
:Ḣ₃[ # If length = 2
÷ð$Ṡ # Add in a space and join
| ] # Else...
‛, j # Join by ', '
|_ # Else pop
```
[Answer]
# JavaScript (ES6) 60
Assuming no empty strings in input array
```
f=(a,b=a.pop())=>a[0]?a.join(', ')+(a[1]?',':'')+' and '+b:b
```
**Test** In FireFox/Firebug console
```
console.log(f(['We invited the stripper','JFK','Stalin']))
```
*Output*
```
We invited the stripper, JFK, and Stalin
```
[Answer]
# JavaScript - ~~60~~ ~~56~~ ~~71~~ ~~67~~ 63
Not exactly an idiomatic approach, but I had fun writing it and I like regex.
Assuming the array is stored in `var a`:
```
a.join((a.length>2?',':'')+' ').replace(/([^,\s])$/,"and $1")
```
Shortened by simply checking for index `[2]`: (yay boolean coercion)
```
a.join((!!a[2]?',':'')+' ').replace(/([^,\s])$/,'and $1')
```
Apparently I suck at testing and skipped a single-entry test. Here's the fixed version:
```
a.join((!!a[2]?',':'')+' ').replace(/([^,\s])$/,(!!a[1]?'and ':'')+'$1')
```
Shaved off 2 chars by inverting my booleans and 3 more by moving the space from the concatenation into the then/else of the first ternary:
```
a.join((!a[2]?' ':', ')).replace(/([^,\s])$/,(!a[1]?'':'and ')+'$1')
```
Thanks to @tomsmeding for reminding me that I don't have to coerce my booleans because JS does that for me. I also realised I forgot to remove the parentheses separating the first ternary from the concatenation inside the `join()`:
```
a.join(a[2]?', ':' ').replace(/([^,\s])$/,(a[1]?'and ':'')+'$1')
```
Did I do that right? Obligatory new golfer apology.
[Answer]
## Golfscript - 31 39 34 30
Hello, World! I am a long time lurker, first time poster. Here is my 30 byte solution in Golfscript (given the array such as [1 2 3] is already on the stack).
```
.,3<" and ":A{~A(;\+]", "}if*
```
The results are proper for all test cases.
EDIT: Take that, CJam!
[Answer]
# Xojo, ~~52~~ ~~71~~ 83 chars
```
dim i as int8=ubound(L)
L(i)=if(i=0,"","and ")+L(i)
Return L.Join(if(i=1," ",", ")
```
Note that UBound is one less than the array length.
[Answer]
# Excel VBA, 108 Bytes
Anonymous VBE immediate window function that takes input as space delimited array from range `A1` and outputs to the VBE immediate window.
```
x=Split([A1]):y=UBound(x):For i=0To y-2:?x(i)", ";:Next:If y>0Then?x(i)IIf(y>1,",","")" and "x(i+1)Else?[A1]
```
[Answer]
# Racket 87
```
(define(f x)(string-join(map ~a x)", "#:before-last(if(= 2(length x))" and "", and ")))
```
[Answer]
# Python 62 chars
Assuming that i is the list of strings:
```
(" and", ", and")[len(i) < 2].join(", ".join(i).rsplit(",",1))
```
[Answer]
**C# 102 Chars**
```
var i=m.Count(),l=i;if(l>2)l--;var r=string.Join(", ",m.Take(l));if(l!=i)r+=" and "+m.Last();return r;
```
[Answer]
# Julia (53)
```
print(join(ARGS,", ",(endof(ARGS)>2?",":"")" and "))
```
Takes args from STDIN and outputs to STDOUT
Solution using Base.join(items, delim[, last])
Edit:
Test cases
```
julia oxfordComma.jl 1
```
1
```
julia oxfordComma.jl 1 2
```
1 and 2
```
julia oxfordComma.jl 1 2 3
```
1, 2, and 3
[Answer]
# Rant (108)
```
[$[l:@b]:[r:each][s:[cmp:[rc];2;[is:different;,]]\s][before:[last:[notfirst:and\s]]][sync:;ordered][arg:b]]
```
Ungolfed:
```
[$[l:@b]:
[r:each] # Repeat for each item
[s:[cmp:[rc];2;[is:different;,]]\s] # Separate by comma if n > 2
[before:[last:[notfirst:and\s]]] # Insert "and" before last item
[sync:;ordered] # Force forward order
[arg:b] # Read list
]
```
Usage:
```
[$l:{A|B|C|D|E}]
```
[Try it online](http://berkin.me/rantbox#6734D3D88CF16B473F6BE7F4CAF8586B36E0AFAE)
[Answer]
# Pyth, 28
```
j>", "qlQ2+_t_Q+?"and "tQkeQ
```
### Examples:
```
$ pyth programs/oxford.pyth <<< "['1']"
1
$ pyth programs/oxford.pyth <<< "['1','2']"
1 and 2
$ pyth programs/oxford.pyth <<< "['1','2','3']"
1, 2, and 3
```
] |
[Question]
[
### Your task
Take a list of strings as the input, and output the maximum average `ord`.
### Example
Given the list `['hello', 'world', 'bye']`:
* The average `ord` of `'hello'` is:
+ (`ord(h)` + `ord(e)` + `ord(l)` + `ord(l)` + `ord(o)`) / `len('hello')`
+ = 106.4
* The average `ord` of `'world'` = 110.4
* The average `ord` of `'bye'` = 106.7
The maximum average `ord` is 110.4. This is your output.
### Test cases
Note: For the last two test cases, I have given the roundings for 1, 2, and 3 decimal places. As mentioned in the rules below, you can round to any number of decimal places.
```
Input Output
['hello', 'world', 'bye'] 110.4
['code', 'golf', 'stack', 'exchange'] 106.8
['!@#', '$%^', '&*('] 55.7 / 55.67 / 55.667 / etc.
['qwertyuiop[', 'asdfghjkl;', 'zxcvbnm,'] 110.9 / 110.91 / 110.909 / etc.
```
### Rules/clarifications
* The output must be only the average `ord`. You may not output anything else.
* It may be rounded (up or down) to any number (\$\ge\$ 1) of decimal places. If your language does not support floating points, you may output the average multiplied by 10.
* [Floating point innacuracies](https://0.30000000000000004.com/) are ok.
* You may assume that the input list will always have a length of 2 or more
* You may assume that the strings will never be empty
* You may assume that the strings will not contain whitespace or non-ASCII characters
* **This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins!**
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 7 bytes
```
eSm.OCM
```
[Test suite](https://pythtemp.herokuapp.com/?code=eSm.OCM&test_suite=1&test_suite_input=%5B%27hello%27%2C+%27world%27%2C+%27bye%27%5D%0A%5B%27code%27%2C+%27golf%27%2C+%27stack%27%2C+%27exchange%27%5D%0A%5B%27%21%40%23%27%2C+%27%24%25%5E%27%2C+%27%26%2a%28%27%5D%0A%5B%27qwertyuiop%5B%27%2C+%27asdfghjkl%3B%27%2C+%27zxcvbnm%2C%27%5D&debug=0)
##### Explanation:
```
eSm.OCM | Full program
eSm.OCMdQ | with implicit variables
----------+-------------------------------
m Q | For each word in the input,
CMd | Get the ord of each character
.O | Get the average
eS | Get the max
```
[Answer]
# [Python](https://www.python.org), 46 bytes
```
lambda l:max(sum(map(ord,s))/len(s)for s in l)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XY5bCsIwEEX_XUXERxOp-iuK4D58QNokbXWS1CTV1q34UxB1Te5GBgXBr3OHcy_M9VE2Ibemvanl5l4FNZ69JsB1IjiBueY19ZWmmpfUOhF7xqYgDfVMWUc8KQwB9l09S1eYQBVdR7kEsFFMorN1IDAkjYy2jHV-ndQKiSazoJA-8PSAQdZpzk323--uemj7gx1iOKJ__niWLjRVYcs1FrgXKsv3B1jgdanTU2J0jJvPu2374Rs)
Unfortunately, the only built-in `mean` function Python has is in the `statistics` module, and that's too expensive to import.
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~18~~ 11 bytes
```
|/{+/x%#x}'
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6rRr9bWr1BVrqhV5+LSV0iLVspIzcnJV4rl4kqL1oByrJXK84tyUoB0UmWqkmYsALq+EBc=)
*Massive -7 bytes golf thanks to Steffan!*
Damn everyone is answering quick. Anyways here's my solution. Takes input as a list of strings.
Explanation:
```
|/{+/x%#x}' Main function. Takes implicit input
' For each string in the input...
{ } Execute a function that...
+/x Takes sum of every character in the string
% And divide it by
#x The length of the string
|/ Get the maximum value
```
[Answer]
# [Wren](https://wren.io/), 68 bytes
```
Fn.new{|x|x.reduce(0){|y,z|y.max(z.bytes.reduce{|a,b|a+b}/z.count)}}
```
[Try it](https://wren.io/try/?code=PTAWFMEMBNwJwFADdJwAQDMC8CEgMYD2sCAYgHYB054A7gN4A+AHi5XONAK77gAUABgCUTAJ4AaAF6NRlALaRmfSZQBGogC7gAzu049wTSONWNIAalUBfYCqJdyGoVau4QGQoS2IA2j4BEEAA2QYT+4v60hHBB0OH+6uD+ALriCGgBRLDxAOaEQRjx2hqQ+ADW8eDM+KCQ5DlJqekBAIQAAgDE8QAkADoApAB64Wj+AGQAVHwpaRn+AI608BqiXACWhAAOARGQ2tAYOaAAVmVBANzxktVIquRyKcmUUDVMrADKosXgcpSbcGtHHwMJR8JAQnxmEJnAggA)
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), ~~14~~ 13 bytes [SBCS](https://github.com/abrudz/SBCS)
*-1 bytes thanks to [Adám](https://codegolf.stackexchange.com/users/43319/ad%c3%a1m)*
```
⌈/+⌿∘⎕UCS¨÷≢¨
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=ARoA5f/ijIgvK@KMv@KImOKOlVVDU8Kow7fiiaLCqA&f=S1PPSM3JyVdXUC/PL8pJAdJJlanqXGnqyfkpqUBeen5OGpAqLklMzgbSqRXJGYl56WAVig7KQBGVOFUgqaalARIqLE8tKqkszcwviAYKJhanpKVnZGXnWAM5VRXJZUl5uTrqXAA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f)
A tacit function which finds the maximum ord. Originally wrote a dfn, but I tried random stuff to convert it to tacit and it somehow worked out.
```
⌈/+⌿∘⎕UCS¨÷≢¨
¨ ⍝ for each element in the input...
⎕UCS ⍝ convert the characters to their ascii values...
+⌿∘ ⍝ and sum the resulting ascii values...
÷ ⍝ divided by...
≢¨ ⍝ the length of each element...
⌈/ ⍝ and take the maximum of that
```
[Answer]
# [><>](https://esolangs.org/wiki/Fish), ~~80~~ ~~51~~ 48 bytes
```
0>0001.
$i:"!"(?v+$1+
(@:{:,$&/
v?(0&~$?/.02
\n;
```
[Animated Version](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiMDAwMDEuXG4kaTpcIiFcIig/diskMStcbjokQDokLCQmLyhAXG52PygwJn4kPy98LiEwMFxuXFxuOyIsImlucHV0IjoiaGVsbG8gd29ybGQgYnllIiwic3RhY2siOiIiLCJtb2RlIjoibnVtYmVycyJ9)
~~Requires a extra space at the end of the input.~~ Also assumes no 2 spaces in a row. (no 0 length words). Anything with ORD of 32 or lower is considered white-space.
## Explanation
[](https://i.stack.imgur.com/cObTg.png)
Top row: Push 3 0s on to the stack. The first is the current best ORD, the second is the length of the current word, and the last is the sum of the ord values of the current word. `01.` is a jump to the next row.
The second row sums a word. If a character is less than "!" (char value 33) go down. Otherwise sum the word and increment the length. `$1+
In the third row, we fist push the last value to the register `&` . We use this to later check if this was the end of the string. Then we divide by the length to get the new ORD value. Then we use the `:{:@` trick to copy the stack if it has only 2 elements (which is always the case) from the stack and compare them. If the new one is better we swap the stack with `$`. In either case we delete the top item.
Lastly, we take the value of the register and check if it is negative, `&0(?`. If so, we print the maximum ord and exit. If not, we jump back to `00`. To get the correct direction we use the `00!.|` trick.
[Answer]
# [><>](https://esolangs.org/wiki/Fish), ~~65~~ ~~45~~ 44 40 bytes
```
000i:"!"(?v+$1+$20.
$~$0(?n00.>@$,:{:@(?
```
[Try it online!](https://tio.run/##S8sszvj/38DAINNKSVFJw75MW8VQW8XIQI9LpU7FQMM@z8BAz85BRceq2spBw/7//4zUnJx8haTKVIXy/KKcFAA "><> – Try It Online")
Takes input as a space separated string.
[Answer]
# [Factor](https://factorcode.org), 24 bytes
```
[ 0 [ mean max ] foldl ]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dVA7TsQwEBVtTjEbLQghYRKBQpZt6BANDaKKFuF1nA_rxFnbYRMQJ6GJhKDgBNQcg9MwickWSEwxb8ae997YL-8JZUaq7nvn7ub68uriDESujYaCmoxoQw12OfvtpYq5wgHDFRUaNF_XvGRcQ6W4MW2l8tLA3HGmTw5guBkXQrrgbqQSMeKy5S4c9wbwNybg-x45sTwmYxx0UykSBNyCrRB5wzJaplsJJkvd87yAhJY3Of96xcHp7i3mvYP9_8ysYRiQUzjqIRhxKLhhxOqtN1yZts5lFaEg1XGSZvcrMcfmsWEPy7LYOtj9Z0gf0B8LbzYqPr_VJjkMPyPwIIKC0xI_tYEFJFLEAhb2-qOgFQwvJvag6yz-AA)
Just fold with the max of the mean.
[Answer]
# [R](https://www.r-project.org), 38 bytes
```
\(x)max(sapply(Map(utf8ToInt,x),mean))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY31WI0KjRzEys0ihMLCnIqNXwTCzSAMhYh-Z55JToVmjq5qYl5mpoQ1bcYBdI0kjXUM1JzcvLVdRTUy_OLclJAjKTKVHVNTWUFLMDQ0EDPhAusLzk_JRWkOj0_Jw1EF5ckJmeDGKkVyRmJeekoZhgamOlZQPQpOiiDVKmoxoEoNS0NXHaBgKmpnrmCPogyg9FgRmpJsh7EuMLy1KKSytLM_IJokHmJxSlp6RlZ2TnWIF5VRXJZUl6uDswKkPMtgdrBtCGMYWAJNRESMAsWQGgA)
```
Map(utf8ToInt,x) # for every string in the input, store the vector of its codepoints in a list
sapply( ,mean) # apply mean to each of the list elements and return a vector
\(x)max( ) # take max
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
OÆmṀ
```
[Try it online!](https://tio.run/##y0rNyan8/9//cFvuw50N////j1bPAArlq@soqJfnF@WkgBhJlanqsQA "Jelly – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~10 9~~ 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ÇÅAà
```
-5 thanks to Sʨɠɠan
[Try it online!](https://tio.run/##yy9OTMpM/f//cPvhVsfDC/7/j1bKSM3JyVfSUVAqzy/KSQExkipTlWIB "05AB1E – Try It Online")
**Explained:**
```
ÇÅAà # Implicit input as a list
# Implicit map over the input:
Ç # Get the ord of each character
ÅA # Get the average of the ords
à # Get the maximum value
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 12 bytes
```
M:$+A*_/#_Mg
```
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJNOiQrQSpfLyNfTWciLCIiLCIiLCItcCBxd2VydHl1aW9wWyBhc2RmZ2hqa2w7IHp4Y3Zibm0sIl0=)
[Answer]
# [Knight](https://github.com/knight-lang/knight-lang) (v2), 56 bytes
```
;=mF;W=pP;=s!=i~1;W>Lp=i+1i=s+*10A Gp iTs&<m=t/sLp=m tOm
```
[Try it online!](https://knight-lang.netlify.app/#WyI7PW1GO1c9cFA7PXMhPWl+MTtXPkxwPWkrMWk9cysqMTBBIEdwIGlUcyY8bT10L3NMcD1tIHRPbSIsImNvZGVcbmdvbGZcbnN0YWNrXG5leGNoYW5nZSIsIjIuMCJd)
Because Knight doesn't support floating point values, it outputs the maximum average ord multiplied by \$10\$, as allowed by the rules:
>
> It may be rounded to any number (\$\ge1\$) of decimal places. If your language does not support floating points, you may output the average multiplied by 10.
>
>
>
[Answer]
# [Julia](https://julialang.org), 34 bytes
```
!a=max(sum.(Int,a)./length.(a)...)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dZBNbsIwEIXFtqdIHIoclA6JBBRUIXXbMwCVjOP8gGPTxCmhV-mGDYeC05AJRMqinc17I837RjO_520pU3Y6nUsTvcwuxGaLjFW0KDOgH8p4zIWRFCo2CdDaA7j3yWuP7vNUGamovSSJkFITzyIHncsQzeYoyNq1_ignCHwYP3XSXIcCM7GWEWphGN-hERVPmIq7JCfwpzDrpu13B2dX_edP1MGQ_rMY05MJvFojq5Zpq40RhkMX-nUQuTmWqd4vEcqKMIqT7U6-YfdT8e-NyrzHnuageQ1pNGiNP39w7w9rX3wD)
[Answer]
# Excel (ms365), 70 bytes
[](https://i.stack.imgur.com/OYTTN.png)
Formula in `F1`:
```
=MAX(MAP(A1:C1,LAMBDA(a,SUM(CODE(MID(a,SEQUENCE(LEN(a)),1)))/LEN(a))))
```
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 4 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
$m▓╙
```
Input as a list of lists of characters.
[Try it online.](https://tio.run/##TY9BDoIwFET33sKI1pjewI33aGoCIqBSUUBRr2E08XpcpE4/s2DxkmGYzwwubou8KjPvI9d/3/3n570xqlBa7UFJKmW1UZ0orWq6qbgJ1FPy1k5wu2MqHTwkcjrhJhOngWpBDEL@JG5ofNAp@PYM8tHXp9AbMJOLCGoOtvK0gFqBJbNX6I5/UrMxLL2BAzddgJHr0NZwd8bWsOIo@4b1a0m@RjvvIOFOBzS6/w)
**Explanation:**
```
$ # Get the codepoint of each inner-most character of the (implicit) input-list
m # Map over each list of integers:
▓ # Pop and push the average of the list
╙ # After the map: pop and push the maximum
# (after which the entire stack is output implicitly as result)
```
[Answer]
# [J](https://www.jsoftware.com), 18 bytes
```
[:>./(1#.3&u:%#)&>
```
Accepts list of boxed strings
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmuxKdrKTk9fw1BZz1it1EpVWVPNDiJxs0eTKzU5I18hTUE9IzUnJ1_dWr08vygnBUgnVaaqwyWT81NSgWLp-TlpQKq4JDE5G0inViRnJOalI6lTdFAGiquoxgFJNS0NhERheWpRSWVpZn5BNFAqsTglLT0jKzvHGsipqkguS8rL1VGHuGnBAggNAA)
```
[:>./(1#.3&u:%#)&>
[: NB. cap, [: f g y -> f (g y)
&> NB. for each input item, result will be unboxed
( ) NB. monadic fork
# NB. length
3&u: NB. convert input to list of char codes
% NB. vectorized division
1#. NB. sum the result to compute average
>./ NB. max item
```
[Answer]
# PHP 8.x, ~~75~~ 73 bytes
Creates an anonymous function that returns the expect values, hopefully.
```
fn($x)=>max(array_map(fn($z)=>array_sum(unpack('C*',$z))/strlen($z),$x));
```
---
-2 bytes thanks to [Sʨɠɠan](https://codegolf.stackexchange.com/users/92689/s%CA%A8%C9%A0%C9%A0an).
## How does it work?
This uses the [`unpack('C*', ...)`](https://www.php.net/manual/en/function.unpack.php) function to convert all characters into an unsigned char (`0`-`255`).
This assumes all characters are part of the ASCII table.
Then it calculates the average using `array_sum([...])/strlen([...])`.
The function [`array_sum()`](https://www.php.net/manual/en/function.array-sum.php) takes an array and returns the sum of all elements, and [`strlen()`](https://www.php.net/manual/en/function.strlen.php) returns the length of the string.
The function [`max()`](https://www.php.net/manual/en/function.max.php) takes the array with the averages and returns the highest value from it.
Anonymous functions implicitly return values.
## Example usage
You need to assign this to a variable, or call with [`call_user_func()`](https://www.php.net/manual/en/function.call-user-func) or [`call_user_func_array()`](https://www.php.net/manual/en/function.call-user-func-array.php):
```
<?php
$fn = fn($x)=>max(array_map(fn($z)=>array_sum(unpack('C*',$z))/strlen($z),$x));
// Should output: float(110.4)
var_dump($fn(['hello', 'world', 'bye']));
```
You can try this here (with test examples): <https://onlinephp.io/c/2a424>
[Answer]
# [MATLAB](https://www.gnu.org/software/octave/), 39 31 bytes
```
@(s)max(cellfun(@(x)mean(x),s))
```
Matlab unfortunately doesn't convert strings ("") directly to ASCII values using the double function, and if converted to char type then a string array will be padded with spaces to make a proper matrix. As a result, the input is a cellstr type, which needs to be looped over using the cellfun function with an anonymous function that takes the average of the unicode values of the strings (''). The output is then the maximum of those values.
[Try it online!](https://tio.run/##y08uSSxL/f/fQaNYMzexQiM5NScnrTRPw0GjQjM3NTEPSOkUa2r@/w8A "Octave – Try It Online")
edit: -8 bytes thanks to Guiseppe
[Answer]
# T-SQL, 125 bytes
```
WITH C as(SELECT len(x)m,0b,*FROM @
UNION ALL SELECT m-1,b+ascii(right(x,m)),x
FROM C WHERE
m>0)SELECT max(b*1./len(x))FROM c
```
**[Try it online](https://dbfiddle.uk/mTX9gZl8)**
[Answer]
# [Raku](https://www.raku.org/), 27 bytes
```
*».&{.ords.sum/.chars}.max
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtf69BuPbVqvfyilGK94tJcfb3kjMSi4lq93MSK/9bFiZUKaRo2Gak5OfkK5flFOSkKSZWpdpr/AQ "Try It Online")
Edit: as per advice from @Steffan
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `G`, 3 bytes
```
Cvṁ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyLhuItHQSIsIiIsIkN24bmBIiwiIiwiWydoZWxsbycsICd3b3JsZCcsICdieWUnXVxuWydjb2RlJywgJ2dvbGYnLCAnc3RhY2snLCAnZXhjaGFuZ2UnXVxuWychQCMnLCAnJCVeJywgJyYqKCddXG5bJ3F3ZXJ0eXVpb3BbJywgJ2FzZGZnaGprbDsnLCAnenhjdmJubSwnXSJd)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 48 bytes
```
->l{l.map{_1.chars.sum(&:ord)/_1.size.to_f}.max}
```
As the division of two integers in ruby gives an integer, and what was expected was a float, it's long :/
And `.fdiv` is one byte longer
[Attempt This Online!](https://ato.pxeger.com/run?1=XY5LDoJAEET3nkLjZ8AA6s5oNN4DPwFmBpCBwfkoSDyJGxL1UN5GOhoTXVV1v6p0X-9C-2V9o4v1QytqT59je8kq5qReXu0mThB5QjpSp8ZgxgU2R81OxmfiKL6jlyZVXD69W66VNKjroogwxpHVRicuGAbjlwRtNmbrGwk4JgBCziioVF6QgCFFczEL_-KdVRdgr78FGQyNX3w4EaFKHfPcBe5JTMNon7A5TOciOPpZakHl_Wpdv_UF)
[Answer]
# [Sequences](https://github.com/nayakrujul/sequences/), \$9 \log\_{256}(96) \approx 7.41\$ bytes
```
[$v$aH]gM
```
### Explanation
```
[$v$aH]gM // Implicit list of string input
[ ] // Loop through the input list:
$v$ // Get a list of ords of each character
aH // Get the average and append to `g`
g // Push the list `g`
M // Get the maximum value
// Implicit output
```
[](https://i.stack.imgur.com/OUb2h.png)
[Answer]
# Mathematica, 29 bytes
```
Max[Mean/@ToCharacterCode@#]&
```
[View it on Wolfram Cloud!](https://www.wolframcloud.com/obj/acdc57e3-3e30-449f-91e1-4fe95d3faafe)
[Answer]
# [Fig](https://github.com/Seggan/Fig), \$6\log\_{256}(96)\approx\$ 4.939 bytes
```
]KemMC
```
[Try it online!](https://fig.fly.dev/#WyJdS2VtTUMiLCJbaGVsbG8sd29ybGQsYnllXSJd)
```
]KemMC
C - Charcodes
emM - Mean of each
K - Sort
] - Last
```
[Answer]
# Java 8, ~~81~~ ~~79~~ 56 bytes
```
a->a.mapToDouble(s->s.chars().average().orElse(0)).max()
```
Input as a `Stream<String>` and output as an `OptionalDouble`.
[Try it online.](https://tio.run/##ZVHLbsIwELzzFa77kF3A6rm0qJXaY@mB3hCVFscEB8dObSeQVnx7uiSgPrh4vJ7Z2dE6gwqGWbJupIEQyAto@9UjRNuo/BKkIpN9SUiGOlFGbcRrEbWzYJ5cuTCKSPZDhegV5GLawh2CtumYAB@hxa6HR4gQtSQTYsl9A8MxiByKN9dZsTAcByFX4APjAirlIVV4c/7ZBMVuOEf1lvFmtLcqsAWtDo6V0wnJMTzrps7mwLvgUYXI6EoZ4@iAbpw3CeKiVrSNdRRIlyh8T51ZIqCrXCOqLcax6T/t2cM5cheX73heXbO/5MdG@ViX2hUzpCEky3SVrc0Ii8@trBY2H9CThbTx2/4uvhDimH9ah6hy4cooCqSisb8W/ug91EFE17Ux4H16S2jfCnmq6n4HNfwwf9d8Aw)
**Explanation:**
```
a-> // Method with String-Stream parameter & OptionalDouble return-type
a.map // Map over the input-Stream
ToDouble(s-> // and convert them to a Stream of Doubles
s.chars() // Convert the String to an IntStream of its codepoint integers
.average() // Then take the average of that IntStream (as OptionalDouble)
.orElse(0)) // And convert the OptionalDouble to double
// (`.orElse(0)` is shorter than `.getAsDouble()`)
.max() // After the map: leave the maximum (again as OptionalDouble)
```
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), ~~13~~ 12 bytes
*-1 byte inspired by [Aiden Chow's APL answer](https://codegolf.stackexchange.com/a/254368/16766)*
```
⌈´+´∘-⟜@¨÷≠¨
```
Anonymous tacit function; takes a list of strings and returns a float. [Try it at BQN online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4oyIwrTCtygrwrTDt+KJoCnCqC3in5xACgpGICJxd2VydHl1aW9wWyLigL8iYXNkZmdoamtsOyLigL8ienhjdmJubSwiCg==)
### Explanation
```
⌈´+´∘-⟜@¨÷≠¨
≠¨ Length of each string
÷ Divide the following by the above:
+´∘ Sum of
-⟜@ Subtract null character from (each character in)
¨ Each string
⌈ Get the maximum of the resulting list of averages
```
[Answer]
# [Go](https://go.dev), ~~132~~ 108 bytes
```
func f(S[]string)(m int){for a,s:=range S{a=0
for _,r:=range s{a+=int(r)}
if a=a*10/len(s);a>m{m=a}}
return}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NZBNTsMwEIXX-BTG_MXFQNmhVkEcAanLqFRuYieh_gm2Q1usnIRNhMQhuAR7boPdpKs38zya-Z4_v0rd_zQ039CSQUlrBWrZaONuEZcOfbeO3zz8Cd6qHPJkkS2tM7UqcSJhrRz2XBtIiZ2lhqqwYOFpOgXRXBFzNK2n12mYTgzuQM0hTenkfnonmEosntNH6WVKuw4Y5lqjuvHm7-FmJEqwB9bCWQqz5RHAe1QxITQiEG21EUUs1nuGOgI9ynXBolFqwaNaFwLGgu3yKjINY6dPZ9E8v3iJcjlJrgb_bcuM27e1brL4QG3By-p1I-ax-9jl72slCQrEQ9AD2hjVQg9OngOhEyEdCX9mMQYdGFP1_aD_)
* -24 bytes by @Sʨɠɠan: return as an int, multiplied by 10
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Takes input as an array of character arrays.
```
®xc /ZlÃñ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&header=bXE&code=rnhjIC9abMPx&input=WyJoZWxsbyIsIndvcmxkIiwiYnllIl0)
```
®xc /ZlÃñ :Implicit input of 2D array of characters
® :Map each sub-array Z
x : Reduce by addition of
c : Codepoints
/ : Divide by
Zl : Length of Z
à :End map
ñ :Sort
:Implicit output of last element
```
] |
[Question]
[
You will be given two arrays of floating-point numbers. Your task is to pair the corresponding elements of the two arrays, and get the maximum of each pair. *However*, if the two corresponding elements are equal, you must take their sum instead.
For example, given the lists `[1, 3, 3.2, 2.3]` and `[3, 1, 3.2, 2.6]`, you must do the following:
* Pair the elements (or zip): `[[1, 3], [3, 1], [3.2, 3.2], [2.3, 2.6]]`.
* Go through each pair and apply the process above: `[3, 3, 6.4, 2.6]`.
---
## Specs
* The arrays / lists will always have equal length. They may however be empty.
* The numbers they contain will always fit your language's capabilities, as long as you do not abuse that. They may be positive, zero or negative, you must handle all types.
* If it helps you reduce your byte count, you *may* also take the length of the lists as input.
## Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
* [Standard input and output rules](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) apply. You may take input (and output) in any reasonable format.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
---
# Test Cases
```
Array_1, Array_2 -> Output
[], [] -> []
[1, 2, 3], [1, 3, 2] -> [2, 3, 3]
[1, 3, 3.2, 2.3], [3, 1, 3.2, 2.6] -> [3, 3, 6.4, 2.6]
[1,2,3,4,5,5,7,8,9,10], [10,9,8,7,6,5,4,3,2,1] -> [10, 9, 8, 7, 6, 10, 7, 8, 9, 10]
[-3.2, -3.2, -2.4, 7, -10.1], [100, -3.2, 2.4, -7, -10.1] -> [100, -6.4, 2.4, 7, -20.2]
```
[Answer]
# [Python 2](https://docs.python.org/2/), 45 bytes
A mix of my initial solution and [@ovs'](https://codegolf.stackexchange.com/a/140754/59487).
```
lambda*a:map(lambda x,y:max(x,y)*-~(x==y),*a)
```
[Try it online!](https://tio.run/##PY3LCoMwEEX3/YrZGWUiSbRqBfsjaRYpRRqoD8SFbvrr6RirBCb33jOPcZ3fQ6982zz8x3bPl01s3dmR7QYWXMkujP444V@2NM0aY2Jj3w4TOHA9aK0NgjZb0RJBIWSbJpmRO3MyWUpQpQGTlWdSHF0KM8zxSq/ECm8oRVglSFYUFQRyalEo9wkeFvyrSnOEkoQUqdznxAED4yc0pr7AOLl@BocRv0fYMqfpmNPSxP4H "Python 2 – Try It Online")
# [Python 2](https://docs.python.org/2/), 49 bytes
```
lambda x,y:[max(a,b)*-~(a==b)for a,b in zip(x,y)]
```
[Try it online!](https://tio.run/##PY3NCoMwEITvfYq9NZaNmMSqFeyLpDlEijRQfxAP2kNf3W5ilcAy883sZlimV9/Jtake69u29dPCjEupWzszi3V04V9mq6qOmn4EAuA6@LiBUSkyq4fOI621QdDGDy0QJILymqQid3AyKqZQxiEmKw6S7S2JClO80suxwBuKJJxKSBaEMgpSqkgU2wYPB/5TxilCTkIksdj2kj0MGT9CY8oTDKPrJnB45vczNsxp@sxpYaL1Bw "Python 2 – Try It Online")
# [Python 2](https://docs.python.org/2/), 46 bytes
[@ovs](https://codegolf.stackexchange.com/users/64121/ovs) suggested this method to save 3 bytes.
```
lambda*x:[max(a,b)*-~(a==b)for a,b in zip(*x)]
```
[Try it online!](https://tio.run/##PY3LCoMwEEX3/YrZNcooeVi1gv2RNItIkQbqA3Fhu@iv20msEhjunDMzGd/zc@jl2tb39WW75mHjpdKdXZjFJoqTL7N13UTtMAEBcD183MjiJTKrZ84TrbVB0MYXLRAkgvKZoqLu4NSolKRMg6ZWHCTfpyQqzPBCr8ASryh4OMUploRyEhmNSBTbRhIO/KtMM4SCguCp2Pb4LoNLDmlMdYJxcv0MDs/J7Ywtc5o@c1qYaP0B "Python 2 – Try It Online")
---
# How?
First off, we pair the corresponding elements, by using either `*` or `zip()`. That allows us to do our further golfing by working either with a map or a list comprehension.
The cool trick in this answer is this part: `max(x,y)*-~(x==y)`. **How does that work?** - Well, as most of you already know, Python auto-converts bool values to integers when they are used in arithmetic operations. Hence, `(x==y)` gets evaluated as `1`, if the condition is met. However, if the two values are not equal, it returns `0` instead. Then, the bitwise operation `-~` increments the value returned from the bool by `1`, giving us either `2` or `1`. `max(a,b)` gives the maximum value of the pair and `*` multiplies it by the value returned above (so it gets multiplied by `2` only if they are equal, in which case `max()` returns the value of both).
This is based on the fact that the sum of two equal numbers is in fact either of them doubled, and kind of "abuses" Python's bool class being a subclass of int.
[Answer]
# Kotlin, ~~78~~ ~~75~~ ~~71~~ ~~66~~ ~~65~~ 59 bytes
It's my first attempt, be cool :D
```
a.zip(b).map{(a,b)->when{b>a->b;a>b->a;else->a*2}}.toList()
```
**TIO doesn't work with this solution (and i don't know why), source code for testing below**
```
fun main(args: Array<String>) {
bestOfTwo(floatArrayOf(), floatArrayOf()).print()
bestOfTwo(floatArrayOf(0F), floatArrayOf(0F)).print()
bestOfTwo(floatArrayOf(1F,2F,3F), floatArrayOf(1F,3F,2F)).print()
bestOfTwo(floatArrayOf(1F,3F,3.2F,2.3F), floatArrayOf(3F,1F,3.2F,2.6F)).print()
bestOfTwo(floatArrayOf(1F,2F,3F,4F,5F,5F,7F,8F,9F,10F), floatArrayOf(10F,9F,8F,7F,6F,5F,4F,3F,2F,1F)).print()
bestOfTwo(floatArrayOf(-3.2F,-3.2F,-2.4F,7F,-10.1F), floatArrayOf(100F,-3.2F,2.4F,-7F,-10.1F)).print()
}
fun bestOfTwo(a :FloatArray, b :FloatArray): List<Float> =
a.zip(b).map{(a,b)->when{b>a->b;a>b->a;else->a*2}}.toList()
fun List<Float>.print() {
this.forEach { print("$it, ") }; println("")
}
```
**EDIT:**
-3 by replace "a+b[i]" by "a\*2"
-4 by replace "mapIndexed" method by "zip" *(Thanks to @AnonymousReality
Swift solution)*
-5 by replace "Math.max" method by when condition
-1 by change when condition order
-6 by change toFloatArray() by toList()
[Answer]
# [Python 3](https://docs.python.org/3/), ~~48~~ ~~46~~ 44 bytes
*-2 bytes thanks to @nwellnhof*
```
lambda*a:map(lambda*x:max(x)*2/len({*x}),*a)
```
[Try it online!](https://tio.run/##PY/dDoIwDIXvfYreuS1l7gdFTfRFcBczSiQBJIQLDOHZZxlKlnTnnK9t0vbTv96NDcXlFipf3x9e@HPtW/YzA5mBDVyYXfVs2CiGiaPwPBTvDjzeoWwgzx3mziEJjWAQ7KxJWnJrTsZKgkZGTFavyeHfZdBiint6GR7xhFrFVYrkkaIDgZRaDOplIokLftXIFCEjoZXUy5z6w8iSFbrzBqDtyqZn23FCGCdIrlS3ku6qfc/oNMxFMf/ccR6@ "Python 3 – Try It Online")
[Answer]
# Jelly, 4 bytes
```
=‘×»
```
[Try it online!](https://tio.run/##y0rNyan8/9/2UcOMw9MP7f7//3@0oY6xjrGekY6RnnHs/2hjHUMozywWAA)
This uses the exact same approach as [my APL answer](https://codegolf.stackexchange.com/a/140820/55550), except Jelly has a builtin for adding one to a number!
[Answer]
# JavaScript (ES6), ~~53~~ ~~49~~ ~~45~~ 43 bytes
```
a=>b=>a.map((x,y)=>(y=b[y])>x?y:y<x?x:x+y)
```
* 4 bytes saved by borrowing a trick from Mr. Xcoder.
* 2 bytes saved thanks to Arnauld.
---
## Try it
```
o.innerText=(f=
a=>b=>a.map((x,y)=>(y=b[y])>x?y:y<x?x:x+y)
)(i.value=[1,3,3.2,2.3])(j.value=[3,1,3.2,2.6]);oninput=_=>o.innerText=f(i.value.split`,`.map(eval))(j.value.split`,`.map(eval))
```
```
<input id=i><input id=j><pre id=o>
```
---
## Explanation
```
a=>b=>
```
Anonymous function taking the 2 arrays as arguments via parameters `a` and `b`, in currying syntax (i.e., call with `f(a)(b)`
```
a.map((x,y)=> )
```
Map over the first array, passing each element through a function where `x` is the current element and `y` is the current index.
```
(y=b[y])
```
Get the element at index `y` in the second array and assign that as the new value of `y`.
```
>x?y
```
Check if `y` is greater than `x` and, if so, return `y`.
```
:y<x?x
```
Else, check if `y` is less than `x` and, if so, return `x`
```
:x+y
```
Else, return the sum of `x` and `y`. (Multiplying `x` or `y` by 2 would also work here, for the same number of bytes.)
[Answer]
# Haskell, 34 bytes
```
x!y|x>y=x|x<y=y|1<2=x+y
zipWith(!)
```
[Try it online.](https://tio.run/##VU7BboJAFLzzFSPpAeJCYLGKxjVpkzYxNfHgoQdDIkQMpFasYISGf6ePFSrsbjbvzcybeZGffoXHY1Xlg6LMF4XIy3xeiKK051zkw0I5iN/4/BlnkTbQqzRKrsf9a4jZDNrbD3yGTZTc4OsQC/gwmm@5hqYrPnbtwA4BSvhCBJBH4HzNNtlldYK6/lAV9E@JJIvCyy1Ow670Cer7y3I1g4rhEFraRFOt4p6EIOySga4o3358IpN9IkMO2Hr162y29VrGZuAMjicrh5q@jkvQ6crr3iScm/UUdfY/MO4PO1I8Nkd37uHBmcNG7JnuhLlsymyrzreocgkZEz4iBWd2348UmDK4DBOypWBLVq5EyaMNMOQ6zc/reFIZtmXaMsZqOUkZD66fVcua3RsHbpncq/4A)
[Answer]
# Dyalog APL, 5 bytes
```
⌈×1+=
```
[Try it online!](http://tryapl.org/?a=1%203%203.2%202.3%20%28%u2308%D71+%3D%29%203%201%203.2%202.6&run)
## How?
* `⌈`, element-wise maximum of the arguments
* `×`, element-wise multiply
* `1+=`, 1 added to the element-wise equality of the arguments
This works because if the numbers are unequal, `1+=` will be `1`, which when multiplied by the maximum, is the maximum. When the numbers are equal, `1+=` will return `2`, when that is multiplied by the maximum, we get twice the maximum, or the maximum added to itself.
[Answer]
# [R](https://www.r-project.org/), ~~31~~ 29 bytes
```
function(a,b)pmax(a,b)+a*!a-b
```
`pmax` takes the parallel maximum of the two (or more) arrays (recycling the shorter as needed).
I was looking at [Luis Mendo's comment](https://codegolf.stackexchange.com/questions/140748/get-the-best-of-two-arrays#comment344950_140758) and obviously I realized the approach could work for R as well. That got me to 30 bytes, but then I started playing around with different ways of getting indices instead to improve my original answer, and stumbled upon `!a-b` as `TRUE` where `a==b` and `FALSE` otherwise, equivalent to `a==b`. However, for whatever reason, R doesn't require parentheses around `!a-b` as it does for `a==b`, which saved me two bytes.
As mentioned by [JDL in the comments](https://codegolf.stackexchange.com/questions/140748/get-the-best-of-two-arrays/140768#comment345380_140768), this works because `!` (negation) has lower precedence than the binary operator `-` in R, which is strange.
[Try it online! (new version)](https://tio.run/##K/qfZvs/rTQvuSQzP08jUSdJsyA3sQLM0E7UUkzUTfqfppFXmptalJmsYaCpg2BqcqVpJGsY6hjpGGvqgBjGOkZwQQVjINIz0lEw0gPLArmGcBEzTc3/AA "R – Try It Online")
[Try it online! (original)](https://tio.run/##RYlBCoAgEEX3ncLlTA2SCu08zCgJLrSQhG5v5cLgL95/r7RgW6jZX/HIwOTwTHx3WHgGttZhC5Br2kv0sCL9iFMAD4o0GaQPDOkhhXknNQkte32vGmZDbA8 "R – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
żSṀE?€
```
A dyadic link taking a list of numbers on each side and returning the resulting list.
**[Try it online!](https://tio.run/##y0rNyan8///onuCHOxtc7R81rfn//3@0oY6CMRDpGekoGOkZx/6PBvIM4QJmsQA "Jelly – Try It Online")** or see a [test-suite](https://tio.run/##y0rNyan8///onuCHOxtc7R81rQGyDy/XBzKOTnq4cwaQBqIsENUwR0HXTuFRw9zI//@jo6NjdRSiY2N1uBSiow11FIx0FIxBIkCmMZCHkADyjPWAskZ6YHkg1xAuYgZXZqRjrGOiYwqE5joWOpY6hgZgwwyATAugkBlQwgSoxEjHEKpFF2wElDTSM9FRMAcyDA30DCEaDWCSYDlduGRsLAA "Jelly – Try It Online")\*.
### How?
```
żSṀE?€ - Link: list of numbers L, list of numbers R e.g. [1,3,3.2,2.3], [3,1,3.2,2.6]
ż - zip - interleave L & R [[1,3],[3,1],[3.2,3.2],[2.3,2.6]]
€ - for each pair:
? - { if:
E - ...condition: equal 0 0 1 0
S - ...then: sum 6.4
Ṁ - ...else: maximum 3 3 2.6
- } ... -> [3 ,3 ,6.4 ,2.6]
```
---
An alternative is [this monadic link](https://tio.run/##y0rNyan8/1/70O5HjXvslfT///8fHW2oo2AMRHpGOgpGesaxOtFAniFcwCw2FgA "Jelly – Try It Online") taking a list of the two lists, also **6 bytes**:
```
+»⁼?"/
```
---
\* I don't think I've ever created a test-suite footer almost three times the byte count of the code before!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
øεMÃO
```
[Try it online!](https://tio.run/##MzBNTDJM/f//8I5zW30PN/v//x8dbaijYAxEekY6CkZ6xrE6CtFAriFcxCw2FgA "05AB1E – Try It Online")
-1 thanks to [Emigna](https://codegolf.stackexchange.com/users/47066/emigna).
[Answer]
# [MATL](https://github.com/lmendo/MATL), 7 bytes
```
X>tG=s*
```
Input is a two-row matrix, where each row is one of the arrays.
[Try it online!](https://tio.run/##y00syfn/P8KuxN22WOv//2hDHQVjINIz0lEw0jO2BnEM4XyzWAA "MATL – Try It Online")
### Explanation
```
X> % Implicit input. Maximum of each column
t % Duplicate
G % Push input
= % Is equal? Element-wise with broadcast. Gives a two-row matrix
s % Sum of each column. Gives a row vector containing 1 and 2
* % Multiply, element-wise. Implicit display
```
[Answer]
# Java 8, ~~80~~ ~~69~~ ~~67~~ ~~66~~ ~~65~~ ~~64~~ 63 bytes
```
(a,b,l)->{for(;l-->0;)if(a[l]>=b[l])b[l]=a[l]*(a[l]>b[l]?1:2);}
```
Modifies the second input-array instead or returning a new float-array to save bytes.
-11 bytes by taking the length as additional integer-input, which is allowed according to the challenge rules.
-5 bytes thanks to *@OliverGrégoire* (one byte at a time.. xD)
-1 byte indirectly thanks to [*@Shaggy*'s JS answer](https://codegolf.stackexchange.com/a/140757/52210), by using `a[l]*2` instead of `a[l]+b[l]`.
**Explanation:**
[Try it here.](https://tio.run/##rZFNb4JAEIbv/Io5QjNs@PCjLdGmadJbvXg0HlaEZu26S2CxMYbfbmdFJU1LD40JDLsz78z7ZNjwHfd1kanN@uMotoUuDWwox2ojJHsuS76vEudHIa9VaoRW7EWrqt5m5V@a1/MhcVLJqwreuFAHB0Aok5U5TzOY2SvATos1pG4uNTeLJXCEy3GFVg3SS0jYOBQqw41IYQYKJnB0Oa5Qev70kOvSTaTvT4PEE7nLF3I5nawoejZM7P2uzdr7U/gYeUlztGPpKeqVpKHn2SecLcG6c1MK9W6RvJb0imgXRAAq@7zkDk1ykiiWut/S2KoRAq9VzPeVybZM14YVNN9I5bYLZ0a3ju6pwzvrT@E3xxAhRoh6jKkakaDzj2/tT@YWgUU5WbFR3g8Sd7I474gGN99IgA94j2Mc4RAHGGOEYS9VRPUB6Yakv6e@MOjIwtv/rCBA8C9bGFD0x/SGAQv7FndWXz5tV9d0hR3@i7VxmuMX)
```
(a,b,l)->{ // Method with 2 float-array and integer parameters and no return-type
for(;l-->0;) // Loop over the array
if(a[l]>=b[l]) // If the current value in `a` is larger or equal to `b`:
b[l]= // Modify the second input-array:
a[l]* // Use `a` multiplied by:
(a[l]>b[l]? // If the current value in `a` is larger than `b`:
1 // Multiply by 1
: // Else (`a` is smaller of equal to `b`):
2) // Multiply by 2
// End of loop (implicit / single-line body)
} // End of method
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 42 bytes
```
->a,b{a.zip(b).map{|x,y|[x+y,x,y][x<=>y]}}
```
[Try it online!](https://tio.run/##TU7dCoMgFL7fUwi7KXYUf1oZrF7EeVEXg10MYjDIVc/ejqYyBP3@zvl8f0a3P7r7TvsBxmVg3@dUjCV7DdOyzuBWM18cILBmvnW9s9u2T@TBCmOBGFueCe3xPR2aACKBKG8hVMhSQgaq/oKeMpQlC3mkIit1GlMhV7PqUPO0BAUVXPE0oKEFwUMnR6hRqtGoMCJBpE3okRaIBtLgQizjAemg4nhcTcMP4i19L4ao4EwcBTyZwaPZzC0@EP8bhyVn0u4/ "Ruby – Try It Online")
The spaceship operator is great.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 11 bytes
```
m*eSdhnd{dC
```
**[Try it here!](https://pyth.herokuapp.com/?code=m%2aeSdhnd%7BdC&input=%5B1%2C+3%2C+3.2%2C+2.3%5D%2C+%5B3%2C+1%2C+3.2%2C+2.6%5D&debug=0)**
# [Pyth](https://github.com/isaacg1/pyth), 12 bytes
```
m*eSdhqhdedC
```
**[Try it here!](https://pyth.herokuapp.com/?code=m%2aeSdhqhdedC&input=%5B1%2C+3%2C+3.2%2C+2.3%5D%2C+%5B3%2C+1%2C+3.2%2C+2.6%5D&debug=0)**
**or**
```
m*eSdh!tl{dC
```
**[Try it here!](https://pyth.herokuapp.com/?code=m%2aeSdh%21tl%7BdC&input=%5B1%2C+3%2C+3.2%2C+2.3%5D%2C+%5B3%2C+1%2C+3.2%2C+2.6%5D&debug=0)**
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~9~~ ~~8~~ 7 bytes
Saved a byte as *Erik the Outgolfer* pointed out that a list of lists is valid input.
```
øεMsËi·
```
[Try it online!](https://tio.run/##MzBNTDJM/f//UcOswzvObfUtPtydeWj7///RusZ6RjoKUNJIz0RHwRzIMDTQM4zlijY0MIDJgaV04XIA "05AB1E – Try It Online")
**Explanation**
```
ø # zip the lists
ε # apply to each pair
M # get max
s # swap the top 2 elements on the stack
Ëi # if all elements are equal
· # double the max
```
[Answer]
# Mathematica, 31 bytes
```
MapThread[If[#==#2,2#,Max@##]&]
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~49~~ ~~46~~ 45 bytes
*3 bytes removed thanks to [@Mr.Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder) (splat instead of two arguments), and 1 byte thanks to [@ovs](https://codegolf.stackexchange.com/users/64121/ovs) (map instead of list comprehension)*
```
lambda*x:map(lambda a,b:a*(a>=b)+b*(b>=a),*x)
```
[Try it online!](https://tio.run/##Pcg9CoAwDEDhq3RMYhC04CDUi9QOCVIU/CnioKevBUF4y/fSc83HbnN0Y15l00no7jdJ8MEIay8EMjjFSgl0cIJMN@Z0LvsFniL4ho0t1S2btraBjS9s/tMFDJhf)
[Answer]
# J, 7 bytes
```
>.`+@.=
```
[Try it online!](https://tio.run/##y/r/P03BVk/BTi9B20HPlosrNTkjX0HDUMFYwVjPSMFIz1hTIU1Bw1jBEMo304QrMQIqMgFLmyqYKZgrWCCkwBAsBWP//w8A)
Takes one list as the left argument and the other as the right.
Luckily, equality is a rank zero operation.
# Explanation
```
>.`+@.=
= Compare equality pairwise
@. If equal
+ Sum
>. (Else) take greater value
```
`@.` isn't *really* an if statement, but in this case it functions as one (it indexes into the gerund `>.`+` based on the result of its right argument and applies that to the input).
[Answer]
# TI-Basic, ~~23~~ 21 bytes
```
Prompt A,B
(ʟA=ʟB)ʟA+max(ʟA,ʟB
```
Too bad lists take up two bytes each...
[Answer]
# [Uiua](https://uiua.org), 6 [bytes](https://www.uiua.org/pad?src=U0JDUyDihpAgK0BcMOKKlwpEZWNvZGUg4oaQIOKHjOKKjy0x4pa9wrEu4o2Y4ouv4oav4oqCwq8x4qe74ouv4qe7LOKHjOKItSjihpjCrzHii68rMjU2KSAtQFwwKzEKJnAg4oqCIjggYml0IGVuY29kaW5nOlx0IiBTQkNTICLih4ziio8tMeKWvcKxLuKNmOKLr-KGr-KKgsKvMeKnu-KLr-Knuyzih4ziiLUo4oaYwq8x4ouvKzI1NikiIOKKgitAXDDih6ExMjkiLiziiLY74oiYwqzCscKv4oy14oia4peL4oyK4oyI4oGFPeKJoDziiaQ-4omlKy3Dl8O34pe_4oG_4oKZ4oan4oal4oig4qe74paz4oeh4oqi4oeM4pmt4ouv4o2J4o2P4o2W4oqa4oqb4oqd4pah4oqU4omF4oqf4oqC4oqP4oqh4oav4oaZ4oaY4oa74per4pa94oyV4oiK4oqXL-KIp1xc4oi14omh4oi64oqe4oqg4o2l4oqV4oqc4oip4oqT4oqD4oqZ4ouF4o2Y4o2c4o2a4qyaJz_ijaPijaQh4o6L4oas4pqCzrfPgM-E4oiefl9bXXt9KCnCr0AkXCLihpB8IyIKJnAg4oqCImRlY29kZWQ6XHQiIERlY29kZSAiwqPCsS0xwrjChy7DjMKlwrPCsMKIMcKfwqXCnyzCo8K_KMK1wogxwqUrMjU2KSIg4oqCK0BcMOKHoTEyOSIuLOKItjviiJjCrMKxwq_ijLXiiJril4vijIrijIjigYU94omgPOKJpD7iiaUrLcOXw7fil7_igb_igpnihqfihqXiiKDip7vilrPih6HiiqLih4zima3ii6_ijYnijY_ijZbiipriipviip3ilqHiipTiiYXiip_iioLiio_iiqHihq_ihpnihpjihrvil6vilr3ijJXiiIriipcv4oinXFziiLXiiaHiiLriip7iiqDijaXiipXiipziiKniipPiioPiipnii4XijZjijZzijZrirJonP-KNo-KNpCHijovihqzimoLOt8-Az4TiiJ5-X1tde30oKcKvQCRcIuKGkHwjIg==)
```
×+1⊃=↥
```
[Try it!](https://uiua.org/pad?src=ZiDihpAgw5crMeKKgz3ihqUKCmYgW10gW10KZiBbMSAyIDNdIFsxIDMgMl0KZiBbMSAzIDMuMiAyLjNdIFszIDEgMy4yIDIuNl0=)
```
×+1⊃=↥
⊃=↥ # elementwise max and equality mask
+1 # increment
× # multiply
```
[Answer]
# Octave, 36 Byte
```
@(a,b)a.*(a>b)+b.*(b>a)+2.*a.*(a==b)
```
[Answer]
# Pyth, 7 bytes
```
ms.MZdC
```
[Try it here.](http://pyth.herokuapp.com/?code=ms.MZdC&input=%5B%5B1%2C+3%2C+3.2%2C+2.3%5D%2C+%5B3%2C+1%2C+3.2%2C+2.6%5D%5D&debug=0)
[Answer]
# Common Lisp, ~~60~~ 59 bytes
```
(mapcar(lambda(x y)(*(max x y)(if(= x y)2 1)))(read)(read))
```
[Try it online!](https://tio.run/##LYjBCoAgEAXvfcUe33YQdKFbH7NpgaAh1sG@3iK8DDPjU7xKR6nxvKkja/FakTRvQdHoYczfbPRrPLD@5sgyM@quYZA7d1gSEuPIGeEJQnbUwi8)
*-1 byte thanks to @Zacharý!*
[Answer]
# Python with numpy, 28 bytes
```
lambda a,b:a*(a>=b)+b*(b>=a)
```
Assumes input is given as two numpy arrays.
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), using Linq 47+18=65 bytes
```
x=>y=>x.Zip(y,(a,b)=>a>b?a:b>a?b:b+a).ToArray()
```
[Try it online!](https://tio.run/##fY5BS8MwFMfP9lM8iocEY2AbeFhthggeRE8TBEsPL1k2AjWZSaorpZ@9RqFOhgjv8H68H@//V@FSOa/HNhi7g3UXon4tst/EH4x9KzLVYAiw77MQMRoFd61VcL1xrWx0VbMvPNK0CLEtx0MpulIc@IvZk44RZJKWAoVc4VIKXMmlvEDKn9yN99gROhZTxLszG3hEY0mIPhWqakC/C7TPzm6dDa7R/NmbqFNBTdbfCr93Sc9ZzrbE6g@YikAPMwaLNHzOYM4XMNBTIV1nP8JVEigt/ko6z6v@/7T@5HliOtR5ejcM4yc "C# (.NET Core) – Try It Online")
# C# (.NET Core), 82 bytes
```
x=>y=>l=>{for(int i=0;i<l;i++)x[i]=x[i]>y[i]?x[i]:y[i]>x[i]?y[i]:y[i]*2;return x;}
```
[Try it online!](https://tio.run/##fY9NS8QwEIbP9lcMxUPjxrLbFQ9mkz0IHkRPe/BQeqjddAl0kzVJtSXkt9dEqIciwjC878zDfDTmtlGaT7I@c3OpGw6H0Vh@zl@E/HBJ09XGwMUlxtZWNPDUywZ2R9W/d7yscLQLJ6TFc4Ux1tJpoGykrKPMtUpnoQ@CronYdUSsVmgoRUVjYmNI@6geomJR7cfZ3hREc9trCQPxE5nv@VTiCK@1kJmxWshTWUGtTwa55OpRSaM6nr9pYXn4hmeHHyR/VgFPcYrbTPIvmI8FBxsM2xB5gaHIt@DREgjdzS9wH4E7hBD5a9l1Wrr/F7rF/OjXCPkqDRO999M3 "C# (.NET Core) – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~34~~ 28 bytes
```
{map {.max*2/set $_},[Z] $_}
```
[Try it online!](https://tio.run/##XYzBDsIgEETvfsUeelCzRRaQ1hh/REIMh3qSpGk9aBq/HRfURg3JMjvzdvpuuNgU71Cd4ZCmGHqYRAy3tdqM3RWq0wPd0ec/jSFTS@cIQSFoj5Cl5s371X7xnbOpBUNKFIxXmh37TyvUaHDLr8EWd0iyVEuWLVuWA8OIQvq9rEvheyphEBoWJAW97uUnLFk9h1ySng "Perl 6 – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~8~~ 7 bytes
```
Zƛ≈[∑|G
```
*-1 byte thanks to [@emanresu A](https://codegolf.stackexchange.com/users/100664/emanresu-a)*
Add the `ḋ` flag if you want to see the numbers in decimal format.
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJaxpviiYhb4oiRfEciLCIiLCJbLTMuMiwgLTMuMiwgLTIuNCwgNywgLTEwLjFdXG5bMTAwLCAtMy4yLCAyLjQsIC03LCAtMTAuMV0iXQ==)
Explanation:
```
Z # Zip
ƛ # On each pair
[ # If
≈ # All are equal
∑ # Sum
| # Otherwise
G # Get the greatest value
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes
```
₌Þ∴=›*
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigozDnuKItD3igLoqIiwiIiwiWzEsIDIsIDNdXG5bMSwgMywgMl0iXQ==)
```
₌ # Do both of these...
Þ∴ # Elementwise maximum
=› # Equality, incremented -> list of 1s where unequal, 2s where equal
* # Multiply by that.
```
[Answer]
# Swift 3, ~~81~~ 79 Bytes
```
func n(a:[Double],b:[Double]){for(x,y)in zip(a,b){print((x==y) ?x+y:max(x,y))}}
```
Swift has an interesting property in that an Int isn't directly castable to a `Double`, so you have to specify any arrays as being arrays of `Double`s before passing them to the function.
(e.g.) `var k:[Double] = [1,2,3,4,5,5,7,8,9,10]`
Edit: -2 bytes thanks to @EriktheOutgolfer
[Answer]
# C, ~~76~~ 75 bytes
*Thanks to @Kevin Cruijssen for saving a byte!*
```
f(a,b,n)float*a,*b;{for(;n--;++a,++b)printf("%f ",*a>*b?*a:*b>*a?*b:*a*2);}
```
[Try it online!](https://tio.run/##dZDdaoNAEEbvfYpFKOyuo7irJmmWJg9SejEbMARaE1J7JT67/Wpi/QFdRmTmzHcWT/H5dOq6UjJ5qlT5eeVaM2nvmvJ6l66KYxdFTFHk1e1@qepShi@lCEnzQfuj5r32B81H7featVWu7QCJL75UUgVNIPD0oYLN@4d4E03rJk2/aEo2hCaJVLnbT/0tw1C5YJpiHwtALIlsHjbOMozHTJD@j17LzKZ7WQLUJovoJ4K5@Uc2owF9j8rXDPlgsJRRTgXOlnb0SiadewYwxWwHZgMyx44lM9py2FBm9ScVj5S4v@jzbROsbPFh0sTMpcUgTQe6h@MlLbmAGVXA13a/)
] |
[Question]
[
Here is another simple one:
# The Challenge
Given two points in an n-dimensional space, output the distance between them, also called the Euclidean distance.
* The coordinates will be rational numbers; the only limits are the restrictions of your language.
* Lowest dimension is 1, highest is whatever your language can handle
* You may assume that the two points are of the same dimension and that there will be no empty input.
* The distance has to be correct to at least 3 decimal places. If your language does not support floating point numbers, output the nearest whole number.
# Rules
* As usual, function or full program allowed.
* Input may be taken from STDIN, command line- or function arguments.
* Input format is up to you, specify which one you used in your answer.
* Output may be provided by printing to stdout or return value.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so lowest byte-count wins! In case of a tie, the earlier answer wins.
# Test cases
Each point is represented by a list of length n.
```
[1], [3] -> 2
[1,1], [1,1] -> 0
[1,2], [3,4] -> 2.82842712475
[1,2,3,4], [5,6,7,8] -> 8
[1.5,2,-5], [-3.45,-13,145] -> 150.829382085
[13.37,2,6,-7], [1.2,3.4,-5.6,7.89] -> 22.5020221314
```
**Happy Coding!**
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 2 bytes
```
ZP
```
[**Try it online**!](http://matl.tryitonline.net/#code=WlA&input=WzEsIDIsIDMsIDRdCls1LCA2LCA3LCA4XQ)
The `ZP` function (corresponding to MATLAB's `pdist2`) computes all pairwise distances between two sets of points, using Euclidean distance by default. Each set of points is a matrix, and each point is a row. In this case it produces a single result, which is the distance between the two points.
[Answer]
# MATL, ~~~~4.0~~~~ 3 bytes
Thanks for -1 by @AndrasDeak!
```
-Zn
```
Reads two vectors (via implicit input that is requested by `-`) then substracts those and calculates the norm of their difference with `Zn`.
[Try it Online!](http://matl.tryitonline.net/#code=LVpu&input=WzEsMiwzLDRdCls1LDYsNyw4XQo)
[Answer]
# Pyth, 2 bytes
```
.a
```
>
> `.a` - L2 norm of vector difference of A[0] and A[1].
>
>
>
Literally a function that does this problem
[Try it here.](http://pyth.herokuapp.com/?code=.a&input=%5B%5B13.37%2C2%2C6%2C-7%5D%2C+%5B1.2%2C3.4%2C-5.6%2C7.89%5D%5D&debug=0)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/blob/master/docs/code-page.md)
```
_²S½
```
[Try it online!](http://jelly.tryitonline.net/#code=X8KyU8K9&input=&args=WzEzLjM3LDIsNiwtN10+WzEuMiwzLjQsLTUuNiw3Ljg5XQ)
### How it works
```
_²S½ Main link. Left input: A (list). Right input: B (list).
_ Subtract B from A, element by element.
² Square all differences.
S Add all squares.
¬Ω Take the square root of the sum.
```
[Answer]
## Mathematica, 11 bytes
```
Norm[#-#2]&
```
Input as two lists, output as a number. If the input is exact (integers, rationals, etc.) the output will be exact as well. If the input contains a floating-point number, the output will be a float as well.
[Answer]
# Octave, 15 bytes
```
@(x,y)norm(x-y)
```
Example:
```
octave:1> d=@(x,y)norm(x-y);
octave:2> d([13.37,2,6,-7], [1.2,3.4,-5.6,7.89])
ans = 22.502
```
[Answer]
## CJam, ~~11~~ 8 bytes
*Thanks to Dennis for saving 3 bytes.*
```
q~.-:mhz
```
[Run all test cases.](http://cjam.aditsu.net/#code=qN%2F%7B%22%20-%3E%20%22%2F0%3D'%2CSer%3AQ%3B%0A%0AQ~.-%3Amhz%0A%0A%5DoNo%7D%2F&input=%5B1%5D%2C%20%5B3%5D%20-%3E%202%0A%5B1%2C1%5D%2C%20%5B1%2C1%5D%20-%3E%200%0A%5B1%2C2%5D%2C%20%5B3%2C4%5D%20-%3E%202.82842712475%0A%5B1%2C2%2C3%2C4%5D%2C%20%5B5%2C6%2C7%2C8%5D%20-%3E%208%0A%5B1.5%2C2%2C-5%5D%2C%20%5B-3.45%2C-13%2C145%5D%20-%3E%20150.829382085%0A%5B13.37%2C2%2C6%2C-7%5D%2C%20%5B1.2%2C3.4%2C-5.6%2C7.89%5D%20-%3E%2022.5020221314)
### Explanation
```
q~ e# Read and evaluate input.
.- e# Vectorised difference.
:mh e# Reduce √(x²+y²) over the list.
z e# Take abs() to handle 1D input.
```
[See this tip for why `:mh` works.](https://codegolf.stackexchange.com/a/61089/8478)
[Answer]
# Haskell, 46 bytes
```
d :: Floating c => [c] -> [c] -> c
d a=sqrt.sum.map((^2).uncurry(flip(-))).zip a
```
# Haskell, 35 bytes (By @nimi)
```
d :: Float c => [c] -> [c] -> c
d a=sqrt.sum.zipWith(((^2).).(-))a
```
# Haskell, 31 bytes
>
> Like [this Scala answer](https://codegolf.stackexchange.com/a/70543/29474), takes input as a sequence of tuples
>
>
>
<hack>
```
d :: Float c => [(c,c)] -> c
d=sqrt.sum.map$(^2).uncurry(-)
```
</hack>
## Examples:
```
Prelude> d [1] [3]
2.0
Prelude> d [1,1] [1,1]
0.0
Prelude> d [1,2,3,4] [5,6,7,8]
8.0
Prelude> d [1.5,2,-5] [-3.45,-13,145]
150.82938208452623
Prelude> d [13.37,2,6,-7] [1.2,3.4,-5.6,7.89]
22.50202213135522
```
[Answer]
# APL, ~~14~~ 11 bytes
```
.5*‚ç®(+/-√ó-)
```
This is dyadic function train that takes the vectors on the left and right and returns the Euclidean norm of their difference.
Explanation:
```
-√ó-) ‚çù Squared differences
(+/ ‚çù Sum them
.5*‚ç® ‚çù Take the square root
```
[Try it here](http://tryapl.org/?a=f%u2190.5*%u2368%28+/-%D7-%29%20%u22C4%2013.37%202%206%20%AF7%20f%201.2%203.4%20%AF5.6%207.89&run)
Saved 3 bytes thanks to Dennis!
[Answer]
# Julia, 16 bytes
```
N(x,y)=norm(x-y)
```
This is a function that accepts two arrays and returns the Euclidean norm of their difference as a float.
You can verify all test cases at once online [here](http://goo.gl/dMBgy0).
[Answer]
# J, 9 bytes
```
+&.*:/-/>
```
This is a function that takes one set of coordinates from the other (`-/>`), and then performs a sum `+` under `&.` square `*:`.
The input should be in the format `x y z;a b c` where `x y z` is your first set of co-ordinates and `a b c` is the other.
[Answer]
# Java, ~~130~~ ~~117~~ ~~114~~ ~~107~~ 105 bytes
This is the obvious solution. I don't usually golf in Java, but I was curious to see if Java could beat the Brainfuck version. Doesn't seem like I did a good job then.. Maybe one could use the new Map/Reduce from Java 8 to save some bytes.
Thanks to @flawr (13 bytes), @KevinCruijssen (9 bytes) and @DarrelHoffman (3 bytes)!
Golfed:
```
double d(float[]a,float[]b){float x=0,s;for(int i=0;i<a.length;x+=s*s)s=a[i]-b[i++];return Math.sqrt(x);}
```
Ungolfed:
```
double d(float[] a, float[] b) {
float x=0,s;
for(int i=0; i<a.length; x+=s*s)
s = a[i] - b[i++];
return Math.sqrt(x);
}
```
[Answer]
# [golflua](http://mniip.com/misc/conv/golflua/), 43 chars
```
\d(x,y)s=0~@i,v i(x)s=s+(v-y[i])^2$~M.q(s)$
```
Works by calling it as
```
> w(d({1,1},{1,1}))
0
> w(d({1,2},{3,4}))
2.82842712475
> w (d({1,2,3,4},{5,6,7,8}))
8
```
A Lua equivalent would be
```
function dist(x, y)
s = 0
for index,value in ipairs(x)
s = s + (value - y[index])^2
end
return math.sqrt(s)
end
```
[Answer]
## Seriously, 12 bytes
```
,iZ`i-ª`MΣ√A
```
[Try it online!](http://seriously.tryitonline.net/#code=LGlaYGktwqpgTc6j4oia&input=WzEzLjM3LDIsNiwtN10sIFsxLjIsMy40LC01LjYsNy44OV0)
Explanation:
```
,iZ`i-ª`MΣ√A
,iZ get input, flatten, zip
` `M map:
i-ª flatten, subtract, square
Σ√A sum, sqrt, abs
```
[Answer]
# Perl 6, ~~30~~ ~~29~~ ~~26~~ 24 bytes
```
{sqrt [+] ([Z-] $_)»²}
```
(Thanks @b2gills for 2 more bytes lost)
**usage**
```
my &f = {sqrt [+] (@^a Z-@^b)»²};
say f([1], [3]); # 2
say f([1,1], [1,1]); # 0
say f([1,2], [3,4]); # 2.82842712474619
say f([1,2,3,4], [5,6,7,8]); # 8
say f([1.5,2,-5], [-3.45,-13,145]); # 150.829382084526
say f([13.37,2,6,-7], [1.2,3.4,-5.6,7.89]); # 22.5020221313552
```
[Answer]
# Python 2, 47 bytes
A straight forward solution. The function expects 2 points as sequences of numbers, and returns the distance between them.
```
lambda a,b:sum((d-e)**2for d,e in zip(a,b))**.5
```
Example:
```
>>> f([13.37, 2, 6, -7], [1.2, 3.4, -5.6, 7.89])
22.50202213135522
```
[Answer]
# Ruby, 52
```
->p,q{t=0;p.size.times{|i|t+=(p[i]-q[i])**2}
t**0.5}
```
**In test program**
```
f=->p,q{t=0;p.size.times{|i|t+=(p[i]-q[i])**2}
t**0.5}
p f[[1], [3]] # 2
p f[[1,1], [1,1]] # 0
p f[[1,2], [3,4]] # 2.82842712475
p f[[1,2,3,4], [5,6,7,8]] # 8
p f[[1.5,2,-5], [-3.45,-13,145]] # 150.829382085
p f[[13.37,2,6,-7], [1.2,3.4,-5.6,7.89]] # 22.5020221314
```
[Answer]
# AppleScript, ~~241~~ 239 bytes
This is golfed code, but I've put comments in in the form `--`.
```
on a() -- Calling for getting input
set v to{1} -- Arbitrary placeholder
repeat until v's item-1="" -- Repeat until no input is gathered
set v to v&(display dialog""default answer"")'s text returned -- Add input to list
end -- End the repeat
end -- End the method
set x to a() -- Set the array inputs
set y to a()
set z to 0 -- Sum placeholder
set r to 2 -- 2 is the first significant array index
repeat(count of items in x)-2 -- Loop through all but first and last of the array
set z to z+(x's item r-y's item r)^2 -- Add the square of the difference
end -- End the repeat
z^.5 -- Return the square root of the sum
```
This uses the same algorithm as most of the other programs here.
[](https://i.stack.imgur.com/3mZqI.gif)
[Answer]
## JavaScript ~~ES7, 45~~ ES6, 37 bytes
```
a=>Math.hypot(...a.map(([b,c])=>b-c))
```
Expects an array of pairs of coordinates, one from each vector, e.g. `[[1, 5], [2, 6], [3, 7], [4, 8]]`. If that is unacceptable, then for 42 bytes:
```
(a,b)=>Math.hypot(...a.map((e,i)=>e-b[i]))
```
Expects two arrays of equal length corresponding to the two N-dimensional vectors, e.g. `[1, 2, 3, 4], [5, 6, 7, 8]`. Edit: Saved 3 bytes thanks to @l4m2. (Also, did nobody notice my typo?)
[Answer]
## Haskell, 32 bytes
```
((sqrt.sum.map(^2)).).zipWith(-)
```
---
```
λ> let d = ((sqrt.sum.map(^2)).).zipWith(-)
λ> d [1] [3]
2.0
λ> d [1,1] [1,1]
0.0
λ> d [1,2] [3,4]
2.8284271247461903
λ> d [1..4] [5..8]
8.0
λ> d [1.5,2,-5] [-3.45,-13,145]
150.82938208452623
λ> d [13.37,2,6,-7] [1.2,3.4,-5.6,7.89]
22.50202213135522
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~79~~ 77 bytes
-2 bytes thanks to ceilingcat.
TIO requires compiler flag `-lm`. GCC of MinGW (that I use) does not.
```
f(p,q,d,s)float*p,*q,s;{for(s=0;d--;)s+=*p++*=*p-=*q++;printf("%f",sqrt(s));}
```
[Try it online!](https://tio.run/##lVHNboMwDD7DU1hIFQESVJLQdmNsD1L1UMFASP2Bhu1S8epjMSWwdpftYiJ/f7bJWJllfV@QmjY0p8orDud969fUb6hKrsX5QlS6THLGEk8FqV8Hga8rS/0mCJL6Up3agjiLwqGqubREeV7S9Z/nKoeSDFbg1xEF8@QUtALy6ujZV9vCd5XYlm3pICDGbut4mgcpLBP9eUG6fgSBZ1vWFBnyYpGBQ6GOttVu4KfIBAYRvIG7c@EZXOp6v/0p/DOB/yHByNgrOGMmwdVxZ9z3RvpoFXEQ72wbtz/uqxMZbnE7Ufuu2khvtNOzXaNw2dGxxW8toVvJTzL/QaYwK7hRTP07mbiTcSwCi5wMhDGIsb/CssayebSSs1U8WrF4spHGholQapxFQ04k40efePIRoViPTkMuW0928bwWx5HlELbC2TZP3XBj2yrJeMbpeDoQf8AN4AbgCPAZEAYQCMgZkAaQCIgZiA0QG0XXf2XFYV@qnh2O3w "C (gcc) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 2 bytes
```
∆d
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLiiIZkIiwiIiwiNywgNCwgM1xuMTcsIDYsIDIiXQ==)
Laughs in built-in. Generalised euclidian distance do be like that sometimes.
[Answer]
# ùîºùïäùïÑùïöùïü, 6 chars / 13 bytes
```
МŰМŷ…ï
```
`[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter2.html?eval=true&input=%5B%5B1%2C1%5D%2C%20%5B1%2C1%5D%5D&code=%D0%9C%C5%B0%D0%9C%C5%B7%E2%80%A6%C3%AF)`
Calculates norm of difference of input arrays.
[Answer]
# Scala, 67 62 bytes
```
def e(a:(Int,Int)*)=math.sqrt(a map(x=>x._2-x._1)map(x=>x*x)sum)
```
Requires input as a sequence/vector of var-arg tuples
Example:
```
scala> e((1, 5), (2, 6), (3, 7), (4, 8))
res1: Double = 8.0
```
[Answer]
# C#, 72 bytes
```
(float[]i,float[]n)=>System.Math.Sqrt(i.Zip(n,(x,y)=>(x-y)*(x-y)).Sum())
```
A simple solution using Linq.
[Answer]
## Sage, 35 bytes
```
lambda a,b,v=vector:norm(v(a)-v(b))
```
This function takes 2 lists as input and returns a symbolic expression. The distance is calculated by performing vector subtraction on the lists and computing the Euclidean norm of the resultant vector.
[Try it online](http://sagecell.sagemath.org/?z=eJwlkdFuhCAQRd9N_IdJ-qA2IxGE1d1k-yObPuDKbklVLKDt_n0BeZlk7pk7XHhcJzkPowSJA-7XXd29sZfF2LncS1nVezlUVZ7lmVfOO7hCURQ3-olwaz-h_gCWZzeKqRFLbDWpxRKD_KBIz3rOOsp4Jw4ZoxYQgSfssE9YHyUigliLqNUt4QJr2iLlIhFUNMHq3Pas6ZNRS9ou8Cesu3QHEowJD_Mk2JL-fKxnRDSsYYy2lIcAxK2T9pNelCtTuIexEAOCXlJ1lzyDcKR9OgSz-RB8lmupdjlhBA6HsojuRXygSK9WLx4e5Xscq465N_BfCqzym13UCGF-U6AdSHCveTCTvoP6W61yTpsFwRkYtQ2fML3gbuZVBssnqJ9NhnUvGI1yS-Hh19jvfyPhd7o=&lang=sage)
[Answer]
## Clojure, 48 bytes
```
#(Math/sqrt(apply +(for[d(map - % %2)](* d d))))
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes
```
-nOt
```
[Try it online!](https://tio.run/nexus/05ab1e#@6@b51/y/3@0obGesbmOkY6Zjq55LFe0oZ6RjrGeiY6uqZ6ZjrmehWUsAA "05AB1E – TIO Nexus")
Negative not y'all!
```
- # a-b
n # (a-b)**2
O # sum((a-b)**2) for all a,b
t # sqrt(sum((a-b)**2) for all a,b)
```
[Answer]
# [Elixir](https://elixir-lang.org/), 74 bytes
```
:math.sqrt Enum.reduce Enum.zip(p,q),0,fn({a,b},c)->:math.pow(a-b,2)+c end
```
[**You can try it online**](http://elixirplayground.com?gist=663568808c8f5eaa09070363516c9e30)
[Answer]
# TI-Basic (TI-84 Plus CE), 15 bytes
```
Prompt A,B
‚àö(sum((LA-LB)2
```
TI-Basic is a [tokenized language](http://tibasicdev.wikidot.com/one-byte-tokens).
Prompts for input as two lists, and returns the Euclidian distance betwrrn them in `Ans`
Explanation:
```
Prompt A,B # 5 bytes, Prompts for two inputs; if the user inputs lists:
# they are stored in LA and LB
‚àö(sum((LA-LB)2 # 10 bytes, Euclidian distance between points
#(square root of (sum of (squares of (differences of coordinates))))
```
] |
[Question]
[
Given two positive integers \$n\$ and \$b\$, such that \$n > 2\$ and \$n > b > 1\$, count the trailing zeros when converting \$n\$ to base \$b\$. Your program should be able to handle any value of \$b\$ within your integer maximum.
The digits of \$n = 18\$, \$b = 3\$ are \$[2,0,0]\$, so the correct output is \$2\$.
The digits of \$n = 107\$, \$b = 43\$ are \$[2, 42]\$, so the correct output is \$0\$
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins
## Test cases
```
n b out
512 2 9
248 2 3
364 265 0
764 2 2
336 284 0
517 422 0
554 37 0
972 3 5
12 6 1
72 2 3
44 2 2
51 16 0
32 2 5
56 7 1
60 2 2
8 3 0
18 3 2
107 43 0
```
---
Credit to [Anush](https://codegolf.stackexchange.com/users/98590/anush) for the [inspiration](https://chat.stackexchange.com/transcript/message/57752871#57752871)
There is a one byte answer in Jelly. Can you find it?
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 1 byte
```
Ǒ
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C7%91&inputs=2%0A512&header=&footer=)
*laughs in stolen jelly built-ins*
[Answer]
# [K (ngn/k)](https://bitbucket.org/ngn/k), ~~11~~ 8 bytes
```
{*&|y\x}
```
[Try it online!](https://tio.run/##RU@7DsIwDNzzFTfxkkCNHScF/woTQxmQygISCPj2YqelDE7O1t35fNn2534YusNrs3g/j4/P0GG3XEkkkFJq7eWcQFm0@K/MGdQmlViQiFQkgYvuC4HVVFmLS5NzJSJmZe8lo2huDLXOq09jDrwegB7ACbjeb8EXA1774OtHzGEKYbgJHmScU5ji1PkUacQWy3JV7NmssZKA6p@tYkCh2R/p7wnLbcGrFvzjmFZ8Vkat3TLz0U7@xo8/TMEPtAt9/gU "K (ngn/k) – Try It Online")
* `|y\x` convert `x` to base `y`, reversing the resulting digits
* `&` use [monadic where](https://github.com/JohnEarnest/ok/blob/gh-pages/docs/Manual.md#where), e.g. convert `0 0 2` into `2 2`
* `*` return the first value
[Answer]
# [Python 2](https://docs.python.org/2/), 31 bytes
Returns `False` for `0`.
```
f=lambda n,b:n%b<1and-~f(n/b,b)
```
[Try it online!](https://tio.run/##RYzNbsIwEITv@xRzQUqkQOP1X0DNs1S2KCJSMBYEoV766uniQDmM9tPszOSf6XhOPM@HfgynuA9ITdylVfxUIe3Xv4cqfcQm1vP9OIzfUDuSAGKD823K6HEKuRrS1OAS7l9DyrepqjfXPA5ya0K@yBMyIp0afV9qs1UM4KEtsemerEk7A3ZWuCUvvPhMWjtwZ4pvlYdhXtiKp33hrS8bIkso@06kCJ7/92Hem7BK3q50oV8Z6dqH55eua995dM99yasXM6lWsqb4fw "Python 2 – Try It Online")
[Answer]
# Jelly, 1 byte
```
ọ
```
[Try it online!](https://tio.run/##y0rNyan8///h7t7///@bm5n8NwIA "Jelly – Try It Online")
Don't know Jelly
[Answer]
# .NET Regex, 35 bytes
```
\G(?=1+,1(1+))(?=(1\1)+,)(?<-2>\1)+
```
[Try it online!](https://tio.run/##HYw5DkIxEEP7OQdICRmkP3uQWEou8QuQoKChQNw/TGjsZ8n25/l9ve9jW27ro8FmN9ZruZyoIRVqtSYXWqk2TDzu@Tx5DCNGBtaeKq7IbhDTQcSRu4JRoDKDmaIEHIJRIFcOMac6u0ZIDjKzOQb4ktRn7y9LPsgP "Retina 0.8.2 – Try It Online") Test suite written using Retina. Takes `n,b` as input in unary as strings of `1`s and outputs the result as the number of successful matches. Explanation:
```
\G
```
Each match must begin at the end of the previous match (with the first match beginning at the start of the string).
```
(?=1+,1(1+))
```
Look ahead to find `b` and capture `b-1` as `\1`.
```
(?=(1\1)+,)
```
Ensure that `1\1`, i.e. `b`, divides `n`.
```
(?<-2>\1)+
```
Subtract `b-1` times the quotient, leaving the quotient, i.e. `n/b`. This value is then the input to the next match.
[Answer]
# [Python 3](http://python.org), ~~83~~ ~~78~~ ~~57~~ ~~47~~ 40 bytes
```
f=lambda n,b:1+f(n/b,b)if n>n%b<=0else 0
```
*Finally figured out how to use a lambda to solve this*
[Answer]
# [JavaScript (V8)](https://v8.dev/), 22 bytes
*-3 thanks to @user*
```
d=>g=x=>x%d?0:g(x/d)+1
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNEts/ifZvs/xdYu3bbC1q5CNcXewCpdo0I/RVPb8H9BUWZeiUaahpGmhrmZiabmfwA "JavaScript (V8) – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~11~~ 8 bytes
```
_YAPf1)q
```
Inputs are in reverse order.
[Try it online!](https://tio.run/##y00syfn/Pz7SMSDNULPw/39jLkMjYyNDAA) Or [verify all test cases](https://tio.run/##HYs7DoNADET7uQkd/i9lpByAgiZVkiZVKJC4/zKLLD@NR8/79/z3T3@/HutPpqM/t64IUXC8QTNg6bxqsDnMEq7DKVghghWWUiTurxpwhyQVRmOFSKacaTauNDg51wU).
### Explanation
Consider inputs `n = 12321`, `b = 3` as an example.
```
_ % Implicit input: b. Negate
% STACK: -3
YA % Implicit input: n. Convert n to specified base. A negative base -b is
% interpreted as digits 0,1,...,b-1, and b can be arbitrarily large.
% (A positive base b is interpreted as chars '0','1',...,'9','A','B',...,
% and then b cannot exceed 36)
% STACK: [1 2 1 2 2 0 1 0 0]
P % Flip
% STACK: [0 0 1 0 2 2 1 2 1]
f % Find: indices of non-zeros
% STACK: [3 5 6 7 8 9]
1) % First entry
% STACK: 3
q % Subtract 1. Implicit display
% STACK: 2
```
[Answer]
# MMIX, 28 bytes (7 instrs)
```
35020001 F7010000
1E000001 E7020001
FE030006 5303FFFD
F8030000
```
# Explanation
```
NEG $2,0,1 // set $2 to -1
PUT rD,0 // clear hidiv register
lop DIVU $0,$0,$1 // set $0 to $0/$1 and rR to $0%$1
INCL $2,1 // increment $2
GET $3,rR // $3 = rR
PBZ $3,lop // if $3, jump back to loop
POP 3,0 // return three registers; $2 goes into lowest slot!
```
The only tricks I used were to start the register at -1 to simplify the logic,
and to use the properties of `POP` to shift the register while returning.
The MMIX register shuffle is useful when golfing.
(It's possible to shave an extra tetra by using `DIV` instead of `DIVU` and omitting the `PUT`, but this changes the semantics to be signed instead of unsigned. For completeness, this leads to the following machine code.)
```
35020001 1C000001 E7020001
FE030006 5303FFFD F8030000
```
[Answer]
# [Raku](http://raku.org/), 22 bytes
```
{($^n,*/$^x.../\./)-2}
```
[Try it online!](https://tio.run/##JchNDoIwEAbQq3whjVGDbZjOtBihJzEQF3blX2ADQc5eU9y9vM99eLj0nLGLaNOyV92rPBrVTVprc9XmcKI1jbcZherRBiwRX9WvBeJ7QCMVgUKJhrj@wzoGOcn0mdtZB6o5UyoPpm1FGNZnnT3Bhkv6AQ "Perl 6 – Try It Online")
`$^n, * / $^x ... /\./` is a sequence starting with `$^n` (the first argument to the function), where each term is obtained by dividing the previous one by `$^x` (the second argument to the function), and ending when a term matches the regex `/\./` (ie, a period). Subtracting 2 from this sequence treats it as a number equal to its length.
[Answer]
# [Risky](https://github.com/Radvylf/risky), 8 bytes
```
0+02?}?0?+1*?:0
```
[Try it online!](https://radvylf.github.io/risky?p=WyIwKzAyP30_MD8rMSo_OjAiLCJbMTgsM10iLDBd)
## Explanation
```
0 0
+ +
0 0
2 prepend to
? first input
} base convert
? second input
0 reduce
? accumulator
+ +
1 1
* ×
? item
: =
0 0
```
This problem translates really nicely to a Risky program. I had to add only two filler characters to make the tree symmetrical.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~38~~ 27 bytes
Saved 11 bytes thanks to [AZTECCO](https://codegolf.stackexchange.com/users/84844/aztecco)!!!
```
f(n,b){n=n%b?0:1+f(n/b,b);}
```
[Try it online!](https://tio.run/##bVLbboMwDH3vV1hIlaBNVSBc2jG2h2lfsaKpSUOHtqUVQRpaxa@POQmgdhpyHOf4@DgX@OrIed@XriTMu8hcztmjfxcsEVgzhLKur2QDn/tKut7sMgP8NNAI1bzKlwJyuMRBSCCMNgRoEhFItaM0IRAHKboYl9sUKZqm5yjSKeRgHCMt8QlgcaCHn3bZbRNmm@gWaEls5w1qRCFGFFtQ1LAwKtgoNZ4ai@iVpmjPgjfiYFW3huAbsj8atggMHl4tw4k2iPG3fb1AL/i7qFENtJ6za5/DXbt9whE7BK7X1Bkqy1MNrt5LJQ@ixTI/G8J7UNW3OJXuuEtvPQCLCclguTRsD@xzjCeTqDQ8i8kX2U2ajWn2b1ph2v4Ft7hAfLqzv4XnGiml68zpAfRYPcAcI7WTeHZJgBFQZLojkeeqGOS7Wdf/8PJjf1T96usX "C (gcc) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 16 12 bytes
```
[:#.~0=#.inv
```
[Try it online!](https://tio.run/##XY8rDwIxEIQ9v2LDiQsJNH1ue02qSFAoLJJwgRPgkPz10mfaQ1TMt9OZ3cVvyTiDszDCHijY8A4EjpfzyV/tQL7UDeT5@vjd5n57vIHDDIrxLCZwayAK4NJkQCNAFZBAWROyR1eQPEZGj8CGJM/RuiGhI1Hln4okgEmXdhYABvC/TZ3XZtkVM0wlLTEaRBeYKnEdgLTbKWjTxlGy7niZANX@Bw "J – Try It Online")
-4 thanks to xash!
* `#.inv` Convert to list of base digits
* `0=` Converts zeroes to ones, everything else to 0.
* `[:#.~` Use that number as a mixed base to convert itself to a number -- effectively zeroes out everything to the left of the rightmost 0, summing all the ones (that were originally trailing zeroes).
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 9 bytes
```
valuation
```
[Try it online!](https://tio.run/##ddDBCsMgDAbg@56khQxMNNEe@jCehjA6Kd1e37kKPcx49eM3f5Ljnu6PXMonPt/xSK@tlLyn7Ziuh4mRgOZ1XebbP5ELJ9merDgg4YqmR//DSqTkrAAFp@cYPTiiAbID63VbPIGtxD3V7aQKKi1ptJwb1mcEFL2Dbd8pFVjA6xXEjAaFcx9lDDZRImjq9VrqCw "Pari/GP – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 15 bytes
```
IntegerExponent
```
[Try it online!](https://tio.run/##PY09C8IwFEX3/IpAwSlC8x0HpYuDm@AoDqGk2qFRSgYhpH89Jo/W7XDfvedNNrzcZMPY2zwc88UH93Tz@ft5e@dDvs6jD/dmfxq6rnnslltv/RJRlJQRzBJBkQmzEleikJKVNTCkXBUyorKkmmDBIJeyNLiueNBFxitVq4L9phebR1KCKdw43EpSxLBX7doxm@YPbX3IE0r5Bw "Wolfram Language (Mathematica) – Try It Online")
Built-in.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 11 bytes
```
IL⊟⪪⭆↨NN¬ι0
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwyc1L70kQyMgv0AjuCAns0QjuAQome6bWKDhlFicquGZV1Ba4leam5RapKGpo4DCBfL98ks0MkEMJQMlTRCw/v/f0tyIy/i/blkOAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
N Input `n`
↨ Converted to base
N Input `b`
⭆ Map over elements and join
ι Current element
¬ Logical Not
⪪ 0 Split string on literal `0`
⊟ Take the last string of `1`s
L Take the length
I Cast to string
Implicitly print
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 34 bytes
```
\d+
$*
+%`^(1+),(\1)+$
¶$1,$#2$*
¶
```
[Try it online!](https://tio.run/##HYtLDsIwDET3vgaplBIv6k/scAIuUaEiwYINC8TZeoBeLDgs5mksv/k8v6/3vU/5uvX1USCdoUzbLVOZMa80lwTHngjTieN17L0zVmJgZG3AVlFM4/LBpihioDwcB3GsVUHw4gyG/5UPqAJZKFGFISyLZkuYLUINNLj4Dw "Retina 0.8.2 – Try It Online") Link includes test cases. Takes input in order `b,n`. Explanation:
```
\d+
$*
```
Convert `b` and `n` to unary.
```
+%`^(1+),(\1)+$
¶$1,$#2$*
```
Repeatedly divide `n` by `b`.
```
¶
```
Count the number of divisions.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 9 bytes
```
ḃ₎,0a₁=kl
```
[Try it online!](https://tio.run/##Pc07CgIxEIDhq4StI@Q1yVqoBwkpVgsFFwSbRWQLIwg24lFsBPE2yUViMmzsPmYmf9bHbrM79YetSOehIbMlaYZVvL2i9@F7H8P7mcLnGv2Dsi76y2Lfp2QtcEGJcJRYodpJUqssDcUGjVOps1pVDNxQogTOAfKFNIVzk2OyqFQ1vq95VTvAKeG4k3UHuYwBzaZJWzt/sPKjdO4H "Brachylog – Try It Online")
```
,0 Append a 0 to
ḃ₎ the digits of n in base b.
a₁ Find the largest suffix
= all elements of which are equal,
k remove its last element,
l and output its length.
```
The shorter `ḃ₎a₁≡ᵛ⁰l` cannot handle cases with no trailing zeroes, since `a₁` cannot generate an empty suffix of a non-empty list, and if it could `≡ᵛ⁰` would fail on it anyhow.
Without utilizing base conversion:
# [Brachylog](https://github.com/JCumin/Brachylog), 11 bytes
```
⟨{f↔∋~^}h⟩t
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3w/9H8FdVpj9qmPOrorourzXg0f2XJ///R0aaGRjoKRrE6CtFGJhZQlrGZCZBlZgpim4PZYFFjMyDLwgTENjU011EwMQKLm5oCVRibg5iW5kDDjEEskKlmYP0w401g5pga6igYguWMYXKmQJPBBpgZQEUsYObAGQYgG41jYwE "Brachylog – Try It Online")
```
∋ An element
f of the list of factors
⟨{ } ⟩ of n
↔ in descending order
~^ h t is b raised to the power of the output.
```
[Answer]
# [R](https://www.r-project.org/), 38 bytes
```
f=function(n,b)`if`(n%%b,0,1+f(n/b,b))
```
[Try it online!](https://tio.run/##jdFdC4IwFAbg@37FgRCUBrlvvfC3@BFag5pgRtSft9kodrPNq8F4eM/Ou2m5jM/61upXPU@tuip9rt/9NPb3ahmq4aFPsxp1qlGXNWpoUp0kHcoRPgypPnbmNvMGpBwTBAAkg705yp0XElY4kPohFQwBEdzC3A/lCv@JJJBIhUksWDSRY4mAERKHfB1NZRSW8lsPtZD7IdgehYU4ACXZ1iOwjfUAxwZiEV0GqDs6tAwXK5TxZUS@8Y1QOD2G3ohdGEjEuflrYL/E5QM "R – Try It Online")
[Answer]
# [Red](http://www.red-lang.org), 48 bytes
```
f: func[n b][either(n % b)> 0[0][1 + f n / b b]]
```
[Try it online!](https://tio.run/##TZDNCoMwEITvPsVcCi09qPm1PfQheg05@JOgUFIR@/x2jWLMIXw7zM7CTK5b3q4zNlv8E/4XWhPQWOOGuXfTNeCC5vZCYQprStzhEZCjIYtd/HdyddsjbsBkoCdLRj@LzER1MFcCTMnImvjQuQKrxL6rIdimS0keriM/9JrJIyPmq411ugWRMimIfLuHnzxSrUsbqyLpqE75ictCUy7PrBmnIcwwY93lH@dn6oDjGJrzsPZDArXzBw "Red – Try It Online")
[Answer]
# [Julia](http://julialang.org/), 18 bytes
```
n*b=n%b<1&&1+n/b*b
```
[Try it online!](https://tio.run/##RZDNbsIwEITv@xRzKYIU0Xj9F6zmSSIfMOUAQqEiQaJPn24cSCytdjye/aT15XE9H9RzGNoi1e1H@larlfpsv1KRhv7U9R1qNGQVAxhrT2yql9aknQE7K7okL3rymbR24Mpk3yoPwzxpK572We99ZkhZQuY7KUXwPPNhFiaskmeXZ6HfGZm1o@enWVcueVQvvuTVWzOpUrJm8iPR7dHLinnVJmxVxK6YbyzvP@fu93r4WzcUWplBSMhtLR@2QTje7vfTsacZEDhiZMoZ265e4DpS3Az/ "Julia 1.0 – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-g`](https://codegolf.meta.stackexchange.com/a/14339/), 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ìV Ôð
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWc&code=7FYg1PA&input=MzY0CjI2NQ)
```
ìV Ôð :Implicit input of integers U=n & V=b
ìV :Convert U to a base-V digit array
Ô :Reverse
ð :0-based indices of truthy (non-zero) elements
:Implicit output of first element
```
[Answer]
# [Emacs Lisp](https://www.gnu.org/software/emacs/manual/eintr.html), 45 bytes
```
(defun f(n b)(if(=(% n b)0)(+(f(/ n b)b)1)0))
```
[Try it online!](https://tio.run/##dY/NCsJADITvPkUuQhYRd7N/LcWHsdqFghax@vxrWihNYXtL8jGTme51u4/nZz@@c8ZHl34DJBygVdgnvOIRplkrPGHCy7y0yvBBZXx/@uELmMAbAgBSCpqGh/qwInKVRFYgGxxQ8AvSAkVGQkVSZQNQ5UoqbyI4oiLybGhjCdVxCm8X5AWCuVdYkJEo0l4vcLvhOSLbhFIMsBvDTQwf@BKLMYLe/QWV7LX5ZTZIqoyOXGBV5T8 "Emacs Lisp – Try It Online")
It seems that recursive functions doesn't work for Emacs Lisp on TIO.
[Answer]
# [Hy](http://hylang.org/), 40 bytes
```
(defn f[n b](if(% n b)0(+(f(/ n b)b)1)))
```
[Try it online!](https://tio.run/##dY@9CsJAEIR7n2IaYQ8L7/b@EvIoYhP00CaI2Pj0cQ2E7MGlG/ZjZmce33mm271MKJcJ45WehY4QZSydqNB50aNxxpiZXu/n9AEVRMcA2BgMg4j@sCEOnUZeIZ8COMUVWYWyIOVi7fIJ3IWWK7qMwNxEUQJ9bqE@/8v7FUWFsOxKK3IaZd7bhbBbXipKTGrVgK8CqxoxySU3ayS7@wud3lX9chXSLmezDNhc8w8 "Hy – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 32 bytes
```
a?b|a`mod`b>0=0|c<-a`div`b=1+c?b
```
[Try it online!](https://tio.run/##TY3LbsIwEEV/xWKVyINqj19BwvADdNUlQsQOlUAlgAotm/x7OuOCxO7c4@s7@3T9@jwexzEt85Da/rxr80JFNXTzaWp3h982Ry27ZR77dDiJKPp0ed@Ky8/t4/a9Oon1dX@@iyTlREykLCFziItnrmi5ZvX2ImLs6qFKkKGr59N15TQCwqyGCm1DZIiMt4DegSIOzIBsjQdsbLFOB7CI/@wsmFBwFmgAHBGtetD8Hx@j9rnjNGhf6obfuO08hNL26lFqaIcrmoGFVnSR3WYz/gE "Haskell – Try It Online")
[Answer]
# [Desmos](https://www.desmos.com/calculator), 64 bytes
```
c=[0...log_bn]
a=n/b^c
f(n,b)=max(c\left\{a=ceil(a):1,0\right\})
```
[Try It On Desmos!](https://www.desmos.com/calculator/nuosdv9lpq)
[Try It On Desmos(Prettified)!](https://www.desmos.com/calculator/lpza3i1nai)
Function to test on: \$f(n,b)\$
It seems like it only works if you copy/paste one expression at a time, instead of copy/pasting it all at once.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 27 bytes
```
f=->n,b{n%b>0?0:1+f[n/b,b]}
```
[Try it online!](https://tio.run/##RYzdasJAEIXv5ynmpqIYk93Zv2hdfQ3BirjRgGC3Ulvw99nTcaP14sDHN2fO9284NU3tB5OYhUt8CxMxFSPZr@exCFlY3JrKj8czMJIQ8Z4hkC4frEBZjWQNswDH3HoCpSxSqZM30qEmatmwUy7x0KUNjgFM@5YjAR3976N@baKRfLbpF9Wzw7/m7lz7a8Wrj@Vjn/vyyQRScFe3fgZQ5btt3Bwu1931mJ2ys6/yQ7WK3eJj3S96@edq3@2Mfr6W2977Hus5dxben2/NHw "Ruby – Try It Online")
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 29 bytes
```
f=(n,b)=>n=n%b>0?0:1+f(n/b,b)
```
[Try it online!](https://tio.run/##XZBNa4NAEIbv/opBWlDcpKvrR740h0ChkHsOaSisbFohjGDsSfLb7btqQomsM7vPvvMctrzOymvVv/9yuam4FXQvRX/OPRbazwvO@VUXcitXYXD2@E2D9msHoeOJ@OtSUU5dEkaConghSKWxoMwWpVJBSZihJDguM0RszPY4tlfIYJ8glkpBGA7tL7PbXa8nvZVjpcnYF5iOI@wU5ArTI8bsuMuGqoYVq4fNTLblcCGHkLwvqMOBR/@O0SMGiXOuG/KgImuRa7TN8ADzveHv9gcgCHxyOofw2RwjZwPH6rR@QA2on6EBNM@wAcSLC9L@CHc1X@uLmR@aqjX7io334nZ8@2w7jTIrqGvQXQrIwyyMtCV3VzeNKUFX5H5wOZ18KG/9Hw "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# Excel, 52 bytes
```
=LET(x,SEQUENCE(LOG(A2,B2)),MAX(x*(MOD(A2,B2^x)=0)))
```
My first attempt below with built-ins was limited because `BASE` only works up to 36. As a bonus the second attempt was shorter. Goes to show, built-ins aren't always the answer.
## Initial Attempt, 70 bytes
```
=LET(x,BASE(A2,B2),q,SEQUENCE(LEN(x)),MAX(q*(RIGHT(x,q)=REPT("0",q))))
```
## Using LAMBDA from Insider Beta, 41 bytes
```
=LAMBDA(n,b,IF(MOD(n,b)=0,f(n/b,b)+1,0))
```
The above is 40 bytes plus 1 byte to set it equal to f in the Name Manager.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
вRĀ1k
```
First input is base \$b\$, second input is \$n\$.
[Try it online](https://tio.run/##yy9OTMpM/f//wqagIw2G2f//G3GZGhoBAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWXC/wubgo40GGb/1/kfHW1qaKRjFKsTbWRiAaaNzUx0jMxMgSxzEAskYmymY2RhAmSZGprrmBiBxExNTXSMzYEMS3MjHWMgDTTFDKQHYpgJRKepoY4hSNQYImpqpgPSYmYA5llA9EEpA6DJxrGxAA).
**Explanation:**
```
в # Convert the (implicit) input `n` to the (implicit) input-base `b` as list
R # Reverse this list
Ā # Truthify each value (0 remains 0; everything else becomes 1)
1k # And get the first (0-based) index of a 1 in this list
# (after which this index is output implicitly as result)
```
] |
[Question]
[
[Sandbox](https://codegolf.meta.stackexchange.com/a/18335/85052)
Given two positive integers a and b, return the smallest multiple of b that is greater than or equal to a.
## Examples
Definitions: `true` = `is a multiple of b`, `false` = `is not a multiple of b`.
* `f(1,3) = 3` because `1` is false, `1+1` is false, but `1+1+1` is true. Therefore `3` is returned.
* `f(5,3) = 6` because `5` is false, but `5+1` is true. Therefore `6` is returned.
* `f(9,3) = 9` because `9` is already a multiple of 3.
* `f(12,5) = 15` because `12` is false, `12+1` is false, `12+2` is false, but `12+3` is true. Therefore `15` is returned.
## Rules
* Input/output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963).
* You can print it to STDOUT or return it as a function result.
* Either a full program or a function are acceptable.
* Any amount of extraneous whitespace is permitted, provided the characters line up appropriately.
* [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.
## 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 = 196683; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 8478; // This should be the user ID of the challenge author.
/* App */
var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;
function answersUrl(index) {
return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}
function commentUrl(index, answers) {
return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}
function getAnswers() {
jQuery.ajax({
url: answersUrl(answer_page++),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
answers.push.apply(answers, data.items);
answers_hash = [];
answer_ids = [];
data.items.forEach(function(a) {
a.comments = [];
var id = +a.share_link.match(/\d+/);
answer_ids.push(id);
answers_hash[id] = a;
});
if (!data.has_more) more_answers = false;
comment_page = 1;
getComments();
}
});
}
function getComments() {
jQuery.ajax({
url: commentUrl(comment_page++, answer_ids),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
data.items.forEach(function(c) {
if (c.owner.user_id === OVERRIDE_USER)
answers_hash[c.post_id].comments.push(c);
});
if (data.has_more) getComments();
else if (more_answers) getAnswers();
else process();
}
});
}
getAnswers();
var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;
var OVERRIDE_REG = /^Override\s*header:\s*/i;
function getAuthorName(a) {
return a.owner.display_name;
}
function process() {
var valid = [];
answers.forEach(function(a) {
var body = a.body;
a.comments.forEach(function(c) {
if(OVERRIDE_REG.test(c.body))
body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
});
var match = body.match(SCORE_REG);
if (match)
valid.push({
user: getAuthorName(a),
size: +match[2],
language: match[1],
link: a.share_link,
});
else console.log(body);
});
valid.sort(function (a, b) {
var aB = a.size,
bB = b.size;
return aB - bB
});
var languages = {};
var place = 1;
var lastSize = null;
var lastPlace = 1;
valid.forEach(function (a) {
if (a.size != lastSize)
lastPlace = place;
lastSize = a.size;
++place;
var answer = jQuery("#answer-template").html();
answer = answer.replace("{{PLACE}}", lastPlace + ".")
.replace("{{NAME}}", a.user)
.replace("{{LANGUAGE}}", a.language)
.replace("{{SIZE}}", a.size)
.replace("{{LINK}}", a.link);
answer = jQuery(answer);
jQuery("#answers").append(answer);
var lang = a.language;
lang = jQuery('<a>'+lang+'</a>').text();
languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link};
});
var langs = [];
for (var lang in languages)
if (languages.hasOwnProperty(lang))
langs.push(languages[lang]);
langs.sort(function (a, b) {
if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1;
return 0;
});
for (var i = 0; i < langs.length; ++i)
{
var language = jQuery("#language-template").html();
var lang = langs[i];
language = language.replace("{{LANGUAGE}}", lang.lang)
.replace("{{NAME}}", lang.user)
.replace("{{SIZE}}", lang.size)
.replace("{{LINK}}", lang.link);
language = jQuery(language);
jQuery("#languages").append(language);
}
}
```
```
body {
text-align: left !important;
display: block !important;
}
#answer-list {
padding: 10px;
width: 290px;
float: left;
}
#language-list {
padding: 10px;
width: 500px;
float: left;
}
table thead {
font-weight: bold;
}
table td {
padding: 5px;
}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/all.css?v=ffb5d0584c5f">
<div id="language-list">
<h2>Shortest Solution by Language</h2>
<table class="language-list">
<thead>
<tr><td>Language</td><td>User</td><td>Score</td></tr>
</thead>
<tbody id="languages">
</tbody>
</table>
</div>
<div id="answer-list">
<h2>Leaderboard</h2>
<table class="answer-list">
<thead>
<tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
</thead>
<tbody id="answers">
</tbody>
</table>
</div>
<table style="display: none">
<tbody id="answer-template">
<tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
</tbody>
</table>
<table style="display: none">
<tbody id="language-template">
<tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
</tbody>
</table>
```
[Answer]
# [Python](https://docs.python.org/2/), 17 bytes
```
lambda a,b:a+-a%b
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSFRJ8kqUVs3UTXpf1p@kUKmQmaeQlFiXnqqhqmmVUFRZl6JQqZOmkamjrHmf0NzHRMA "Python 2 – Try It Online")
Since this doesn't use division, it works for both Python 2 and 3. Note that we can't cut out the `+` sign because `a-a%b` does `a-(a%b)`, whereas we want to do`(-a)%b` and add that to `a`. We could also write it as `-a%b+a`.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 2 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
cV
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Y1Y&input=MTIsNQ)
```
cV :Implicit input of integers U & V
cV :Round U up to the nearest multiple of V
```
With input as an array:
```
rc
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=cmM&input=WzEyLDVd)
```
rc :Implicit input of array
r :Reduce by
c :Rounding the first element up to the nearest multiple of the second
```
## Less Trivial!, 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
_vV}aU
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=X3ZWfWFV&input=MTIsNQ)
```
_vV}aU :Implicit input of integers U & V
_ :Function taking an integer Z as input
vV : Is Z divisible by V?
} :End function
aU :Starting from U, return the first integer that returns true when passed through that function
```
```
ôV ævV
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=9FYg5nZW&input=MTIsNQ)
```
ôV ævV :Implicit input of integers U & V
ôV :Range [U,U+V]
æ :Get first element
vV : Divisible by V
```
[Answer]
## [Intcode (day 5)](https://github.com/tckmn/polyaoc-2019/blob/master/05/rb/05.rb), ~~70~~ ~~66~~ 64 bytes
```
3,0,3,2,102,-1,2,4,1,0,4,0,1,1,8,1,7,9,0,5,5,5,14,2,1,2,0,4,0,99
```
[Try it online!](https://tio.run/##jVNNU4MwEL3zK9ZDbWsjEj5sqTI9edSTN4ZxaEktYwUGwlh0/O24SVosQp0mE9i3ee9l2A15uazqVRox8GBYW8QgFjEJNUxyTTGwCcWUjYvinOGaEheRIye1BReXorhuPdSLbBvz0YKM9fcwg8s5T19iLWJriBMuzwkJhlnJNcAR4rGhHpWZRDEiQ0ZpyZGC0A8kXrLXOJGRGNs0zeCrgWLskDsK/Ti4oYYxHlADcx66wQJCH/MTGgQwBxVBzopVySCJty2T6thk79IyMRsT86TJZ8tEubRMrMbEOmmyCgsmKAEMAG1aex8blgAFLl6/jh6WYALVHRZx4oHdVZh9iqv/FNaxgkqF7JxebOI13@vMrs5WOtVDPSuLDexOsx3F3sGFKtJI3IJqjCUaSYk17mpuDxrvfM207/vvRdMXWM05GKcLMeuT4tFnSF1XaZc5C99a22yLLc4ZL/Ok036WRA3@ltH@njylj4xv0ughz9OcwHOVMRk27D@GByPVC01ALWt@RfEg4FNiBd2s05t1e7PUJE5Q/wA)
Intcode is a programming language invented for [Advent of Code 2019](https://adventofcode.com/2019). It was first introduced on [day 2](https://adventofcode.com/2019/day/2), then further expanded upon on [day 5](https://adventofcode.com/2019/day/5), which is the version used here.
Since on PPCG, languages are defined by their interpreters, I am using the interpreter that I wrote for my day 5 solution (which was written before this challenge).
Explanation:
```
3,0, store first input in cell 0
3,2, store second input in cell 2
(cell 1 is a counter, because it's already initialized to zero)
102,-1,2,4, negate the second input and store in cell 4
(begin loop)
1,0,4,0, subtract the second input from the first input
1,1,8,1, increment the counter (by adding cell 8)
7,9,0,5, if the first input is greater than zero (cell 9)...
5,5,14, ... jump to the beginning of the loop (reusing the cell 8 reference)
2,1,2,0, multiply the counter by the second input
4,0,99 output and quit
```
[Answer]
# x86 Machine Code, 7 bytes
Since x86 integer division instructions do only floor rounding, this uses the formula: `f(a,b) = floor((a+b-1)/b)*b` to accomplish ceiling rounding.
```
02 C3 ADD AL, BL ; a = a + b
48 DEC AX ; a = a - 1
F6 F3 DIV BL ; a = a / b
F6 E3 MUL BL ; a = a * b
```
Input is in `AL` and `BL`, output is `AL`.
**Testing**
Here is output from a test program for PC DOS that takes interactive input.
[](https://i.stack.imgur.com/5Pvvn.png)
Download and test [ROUNDMY.COM](https://stage.stonedrop.com/ppcg/ROUNDMY.COM).
[Answer]
# [MATL](https://github.com/lmendo/MATL), 4 bytes
```
:ien
```
[Try it online!](https://tio.run/##y00syfn/3yozNe//f0MjLlMA "MATL – Try It Online")
### Explanation
Consider inputs `12`, `5`.
```
% Implicit input
: % Range
% STACK: [1 2 3 4 5 6 7 8 9 10 11 12]
i % Input
% STACK: [1 2 3 4 5 6 7 8 9 10 11 12], 5
e % Reshape as a matrix with that number of rows, padding with zeros
% STACK: [1 6 11;
2 7 12;
3 8 0;
4 9 0;
5 10 0]
n % Number of elements
% STACK: 15
% Implicit display
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 17 bytes
Same method as [this JS answer](https://codegolf.stackexchange.com/questions/196683/round-up-my-number/196690#196690):
```
@(a,b)ceil(a/b)*b
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999BI1EnSTM5NTNHI1E/SVMr6X@ahqGOsaaCqoKtgrECV5qGKZhnq2AGZFvCZCyBHEMjHVMIz9CU6z8A "Octave – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~23~~ ~~20~~ 18 bytes
```
lambda a,b:-a/b*-b
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSFRJ8lKN1E/SUs36X9afpFCpkJmnkJRYl56qoapplVBUWZeiUKmTppGpo6x5n9Dcx0TAA "Python 2 – Try It Online")
2 bytes thanks to [tsh](https://codegolf.stackexchange.com/users/44718/tsh)
[Answer]
# [Haskell](https://www.haskell.org/), 14 bytes
```
a%b=a+mod(-a)b
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P1E1yTZROzc/RUM3UTPpf25iZp6CrUJBUWZeiYKKQm5igYKGqrGmQrSBnp6hQez/f8lpOYnpxf91kwsKAA "Haskell – Try It Online")
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), ~~43~~ ~~41~~ ~~40~~ ~~36~~ 25 bytes
```
#define f(a,b)(b-a%b)%b+a
```
[Try it online!](https://tio.run/##hY7NCoJAFIXXzlNcFMEhhSxciNa7zM9VBvQqzswqevapKEkX0Vmdb/FxjprnolcqhERjZwihy0QueSYLkUqeyoMIiSE1eI3Qmsm6BcV4ZcxbQz2QGNHOQiFYpxvGDDkYhaGMsxuL1OQdtC3EXVbmcOZwgfjFKz4rkh4aBp9shGovVKvw26j3Rv13ojzlUG1Pvfk7Ei3o/EJwbNg9PAA "C++ (gcc) – Try It Online")
Saved 4 bytes thanks to @Neil!!!
Saved 11 bytes thanks to @AZTECCO!!!
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 17 bytes
```
a=>b=>a+(b-a%b)%b
```
[Try it online!](https://tio.run/##Nco7DoMwDADQvafwgmSrAQkqhg7O1lNEGeyQ9CNEEIl6/XSh01veR75SwvHea7/lJbbETdgqW7mi9tIpddpqLDVIicDg3Gjg5g24@fR@Ok4GZu8v/zykfDwkvBCdGFBPwBZC3kpe47DmJyYUQiWi9gM "JavaScript (Node.js) – Try It Online")
* -1 byte by [Neil](https://codegolf.stackexchange.com/users/17602/neil)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
÷Ċ×
```
[Try it online!](https://tio.run/##y0rNyan8///w9iNdh6f/97Z@1DBHQddO4VHDXOvDy/W5Drc/aloT@f9/tKGOcaxOtCmYtASThkY6prEA "Jelly – Try It Online")
Simply divide, ceiling, multiply.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~47~~ ~~31~~ 25 bytes
```
f(a,b){a=a%b?f(++a,b):a;}
```
[Try it online!](https://tio.run/##S9ZNT07@r5yZl5xTmpKqYFNckpKZr5dh9z9NI1EnSbM60TZRNck@TUNbG8S1SrSu/Z@ZV6KQm5iZp1GWn5miWc3FWVAEFErTUFJNiclDYCUdhTQNQx1jTRBtCqUtobShkY6ppqY1F2dRaklpUZ6CgTVX7X8A "C (gcc) – Try It Online")
-16 bytes thanks to A̲̲ (forgot that return types and parameters would default to int if not defined, whoops!)
-6 thanks to AZTECCO for using a ternary and making the function recursive
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 7 bytes
```
Ceiling
```
Just pointing out that Mathematica's builtin, which is most commonly called with one argument, actually does exactly the desired operation when called with two arguments.
[Answer]
## Brainfuck, ~~52~~ 49 bytes
Thanks to [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king) for finding a bug, helping fix it with some extra golfing.
```
,>>,<<[>+>->+<[>]>[<+>-]<<[<]>-]>>>[<[-<+>]>,]<<.
```
Input and output is in character codes.
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fx85Ox8Ym2k7bTtdOG0jH2kXbANmxQDGbWCBtZwcUiNYFisXa6QBF9f7/T00EAA)
**Explanation**
```
,>>,<< [>a, 0, b, 0]
[>+>->+<[>]>[<+>-]<<[<]>-] [>0, a, b-a%b, a%b]
>>>[<[-<+>]>,] If a%b is nonzero, add b-a%b to a, and clear a%b
<<. Output a+(b-a%b)
```
Modulus algorithm is straight from [the esolang list of brainfuck algorithms](https://esolangs.org/wiki/Brainfuck_algorithms#Modulus_algorithm).
[Answer]
# [JavaScript (V8)](https://v8.dev/), 22 bytes
This is the function \$(a,b) \mapsto \left\lceil \frac{a}{b} \right\rceil b\$.
```
a=>b=>Math.ceil(a/b)*b
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNEts/ifZvs/0dYuydbON7EkQy85NTNHI1E/SVMr6X9yfl5xfk6qXk5@ukaahqGRpoappuZ/AA "JavaScript (V8) – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 20 bytes
```
function(a,b)a+-a%%b
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNRJ0kzUVs3UVU16X@ahqGOsSZXmoYphLKEUIZGOqaa/wE "R – Try It Online")
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), 8 bytes
```
{x+y!-x}
```
[Try it online!](https://tio.run/##y9bNz/7/P82qukK7UlG3ovZ/mp66hqGCsbUpEFsCsaGRgqnmfwA "K (oK) – Try It Online")
Another port of [xnor's Python answer](https://codegolf.stackexchange.com/a/196700/75681).
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 3 bytes
```
/⌈*
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%2F%E2%8C%88*&inputs=5%0A12&header=&footer=)
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 28 bytes
```
\d+
$*
r`1+(\2*) (1+)
$1$2
1
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPyZFm0tFi6sowVBbI8ZIS1NBw1Bbk0vFUMWIy/D/f0MFYy5TILYEYkMjBVMA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
\d+
$*
```
Convert the inputs to unary.
```
r`
```
Process this stage from right-to-left, so that `\2` gets to match \$ b \$ first, allowing us to refer to it when matching within \$ a \$.
```
1+(\2*) (1+)
```
Match \$ b \$ in `\2`, then as many copies of \$ b \$ as we can, without completely exhausting \$ a \$. `\1` thus matches \$ b \lfloor \frac {a - 1} b \rfloor = b \lceil \frac {a - b} b \rceil \$
```
$1$2
```
Add that to \$ b \$ to give \$ b \lceil \frac a b \rceil \$.
```
1
```
Convert to decimal.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 13 bytes
```
->a,b{-a%b+a}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5RJ6laN1E1STux9n9BUWZeiUKaXnJiTo6GoY6xJldBaUkxF4qwKXZhS@zChkY6ppr/AQ)
[Answer]
# [Red](http://www.red-lang.org), 31 bytes
```
func[a b][round/to/ceiling a b]
```
[Try it online!](https://tio.run/##K0pN@R@UmhIdy5Vm9T@tNC85OlEhKTa6KL80L0W/JF8/OTUzJzMvXQEk@j8tvyg1MTlDAaLGUMFYwRSILYHY0EjBNDa6oCgzrwQoqa6nkKSgrmunkAbWF/sfAA "Red – Try It Online")
Just a built-in `round` with refinements `to`, which scales the first argument according to the second, and `ceiling`, which indicates the direction.
# [Red](http://www.red-lang.org), 25 bytes
```
func[a b][0 - a // b + a]
```
[Try it online!](https://tio.run/##K0pN@R@UmhIdy5Vm9T@tNC85OlEhKTbaQEFXIVFBX18hSUFbITH2f1p@UWpicoYCRNZQwVjBFIgtgdjQSME0NrqgKDOvBCiprgfUoa5rp5CmAFIZ@x8A "Red – Try It Online")
A port of [xnor's Python answer](https://codegolf.stackexchange.com/a/196700/75681). Don't forget to upvote his answer!
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org) + [CLPFD](https://www.swi-prolog.org/man/clpfd.html), 30 bytes
```
f(R,X,Y):-R#=_*Y,R-Y#<X,R#>=X.
```
[Try it online!](https://tio.run/##KyjKz8lP1y0uz/xvpatQWpwan5ufUpqTqpGTmVSUWFSpkZxTkJaiqan3P00jSCdCJ1LTSjdI2TZeK1InSDdS2SZCJ0jZzjZC7z9Y3tBIx1RTj4sLAA "Prolog (SWI) – Try It Online")
```
f(R,X,Y)
```
`f` is a predicate taking in a variable `R`, and two integers `X` and `Y`.
The CLPFD constraints are expressed using the `#`-prefixed operators. `,` means and, so `f` is true iff all these constraints are satisfied, i.e.,
1) `R#=_*Y` R is a multiple of Y `,` and
2) `R-Y#<X` R-Y < X `,` and
3) `R#>=X` R >= X `.`
[Answer]
# [SimpleTemplate](https://github.com/ismael-miguel/SimpleTemplate), 61 bytes
This was quite fun! Sadly, I had to do the dumb way :(
```
{@fn F A,B}{@whileA is notmultipleB}{@incA}{@/}{@returnA}{@/}
```
Creates a function that iterates until it finds a number that's multiple of the 2nd number.
This was actually way smaller than doing it without a function.
---
**Ungolfed:**
```
{@fn F numberA, numberB}
{@while numberA is not multiple of numberB}
{@inc by 1 numberA}
{@/}
{@return numberA}
{@/}
```
Should be mostly straightforward.
You can see it running on <https://ideone.com/MR7t1E> (golfed version only).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 10 bytes
```
≔±NθI×θ÷Nθ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU/DLzU9sSRVwzOvoLTErzQ3KbVIQ1NTR6FQ05oroCgzr0TDObG4RCMkMze1WKNQR8Ezr8QlsywzBU0HSAMQWP//b6pgaPRftywHAA "Charcoal – Try It Online") Link is to verbose version of code. Takes \$ b \$ first and \$ a \$ second. Explanation:
```
≔±Nθ
```
Input \$ b \$, negate it, and save the result.
```
I×θ÷Nθ
```
Input \$ a \$ and compute \$ -b \lfloor \frac a {-b} \rfloor \$, then cast to string for implicit print.
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 6 bytes
```
.~)@%+
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPn/X69O00FV@/9/AA "GolfScript – Try It Online")
Function which consumes A and B from the stack, assuming B is below A.
### Explanation:
```
#Example input: A = 12, B = 5 stack is 5 12
.~) #Duplicate A and negate the duplicate stack is 5 12 -12
@ #Pull 3rd from top to top stack is 12 -12 5
% #Second to top mod top stack is 12 3
+ #Add remaining values stack is 15
```
[Answer]
# Javascript (ES6), 19 bytes
```
a=>b=>a%b?a-a%b+b:a
```
Naive attempt, pretty sure this can be golfed further.
[Answer]
# Java, 99 bytes
```
static int r(int a,int b){int t=a%b<1||b%a<1?a:r(a+1,b);return t;}
```
[Answer]
## JavaScript, 15 bytes
```
a=>b=>--a+b-a%b
```
More expressively, the answer is `a => b => a + b-((a-1)%b) - 1`, but by decrementing `a` we can handle both the "subtract one" steps at once, saving a couple of bytes. Then we just get lucky with operator presidencies.
[Answer]
## Perl 5, (111 bytes with footer) 52 bytes
`sub f{($a,$b)=@_;$c=$b;$c++until!($c%$b)&&$c>=$a;$c}`
[Try it online!](https://tio.run/##K0gtyjH9/7@4NEkhrVpDJVFHJUnT1iHeWiXZViUJSGprl@aVZOYoaqgkqwKl1NRUku1sVRKBMrX/C4oy80oU0jQMdYw1FfQUlHSUgGSahikq1xKVa2ikY6r5HwA "Perl 5 – Try It Online")
Takes `a` and `b` as arguments to a subroutine named `f` and increases `$c` until it is both a multiple of `$b` and greater than or equal to `$a`. Then returns `$c` (the last value evaluated in a subroutine is the return value).
[Answer]
# [Java (JDK)](http://jdk.java.net/), 15 bytes
```
b->a->--a+b-a%b
```
[Try it online!](https://tio.run/##XVBNa4QwFLz7Kx4LgrYx1JY9tFahl0IPpYelp8XDix9LrEZJnoIs/nabVXcPe0gyM5k3Q1LhgEGV/82y6VpNUFnOe5I1L3uVkWwVf4icrEZj4BulgrMD0PWilhkYQrLH0MocGnvnHUhLdTqmgPpk/MUK8KXoc4t6t/hXoR5/ukIjtTqBEuJZBAkGSRDgowjQFXO0zElFx9RmUWHIQLylAZwhZPACE7vx/R1/vePhM4P9VZjW9LLV3oB6SX9bO/xbha0GtJUX@fiUMhBXEqbR5jmMhoqGtz3xzr6aSm@HsZtb77LrwvQ1WeiqHQO0MoOSY9fVoyf8FXwY@x8e@v6aOTmXNc3/ "Java (JDK) – Try It Online")
] |
[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/9266/edit).
Closed 3 years ago.
[Improve this question](/posts/9266/edit)
# Task
The task is to display any of the 128 possible states of a
[7-segment display](http://en.wikipedia.org/wiki/Seven-segment_display).
Your program should accept a string of 7 characters ("bits") that are either `0` or `1`.
First bit of input corresponds to segment A of the following illustration, the
second to B, etc (ignore `dp`):

How you represent the display is up to you -- a single Unicode or ASCII symbol,
[ASCII art](https://codegolf.stackexchange.com/questions/997/render-digital-clock-style-numbers), grafically, or whatever you can come up with. However, each
input must have it's own distinct output. If you come up with something fancy I'm sure you can harvest upvotes by showing off some examples.
All 128 possible states of the display are:

# Rules
* Codegolf
* As I said, any kind of output is allowed, but it would be nice if you specified it.
* Input can be stdin or command line argument.
# Examples
### Input
```
1101101
```
### Output
As ASCII/Unicode:
```
2
```
Different kinds of ASCII art (I'm not too good at this)
```
_ ╺┓ ╒╗ ---
_| ┏┛ ╔╝ |
|_ ┗╸ ╚╛ ---
|
---
```
[Answer]
## C, 106
**Size is 74 chars if allowed to rename program "W00WG5WW1GW66WG4WW2GW33WG"**
```
main(int i,char**s){
for(s[0]="W00WG5WW1GW66WG4WW2GW33WG";i=*s[0]++;putchar(s[1][i&7]-49?i==71?10:32:42));
}
```
running:
```
./a.out 1101101
**
*
**
*
**
```
notes:
'W' and 'G' (0x47 and 0x57) are chosen such that the value & 7 = 7, i.e they safely index the null character that terminates the input string.
[Answer]
## Brainfuck - 224
```
++++++++++[>+>+++<<-]
>>++>,>,>,>,>,>,>,
<<<<<<<.
>[<+.->-]<<.
>>
>>>>>[<<<<<+<+>>>>>>-]<<<<<<.>[<->-]<.>>[<<+.->>-]<<<.>.
>>>>>>>[<<<<<<<+.->>>>>>>-]<<<<<<<<.
>>>>>>[<<<<+<+>>>>>-]<<<<<.>[<->-]<.
>>>[<<<+.->>>-]<<<<.>.
>>>>[<<<<+.>]
```
Prints using Exlamation points:
```
!
! !
!
! !
!
```
Not the most readable, but not too horrible either.
Surprised at how close this is to not being last place.
[Answer]
# Postscript 121 107
```
1 12 moveto{}5 0{0 -5 rmoveto}0 5 0 5 -5 0 0 -5 0 -5 5 0
n{49 eq{rlineto}{rmoveto}ifelse exec}forall stroke
```
requires `n` to be defined as the string to process so invoke like
```
gs -g7x14 -sn=1101101 lcd.ps
```
to get

the complete set is

[Answer]
## Mathematica: ~~135~~ ~~129~~ 118, image display
```
Image[MorphologicalComponents@Import@"http://goo.gl/j3elE" /.
Thread[Range@7 -> IntegerDigits[#, 2, 7][[{7, 2, 6, 1, 3, 5, 4}]]]] &
```
spaces added "for clarity"

**Edit**
For those picky fellow site users: Without using an external mask:
```
Image[MorphologicalComponents[ColorNegate@Rasterize@8, CornerNeighbors -> False] /.
Thread[Range@7 ->IntegerDigits[#, 2, 7][[{7, 2, 6, 1, 3, 5, 4}]]]] &
```
[Answer]
## APL, ~~58~~ 55
```
' _|'[1+3 3⍴0,x[1],0,(x←1 2 2 1 2 2 1×⍞='1')[6 7 2 5 4 3]]
```
Example input:
```
1101101
```
Output:
```
_
_|
|_
```
---
`⍞='1'` takes the input as a character array and converts it to a numeric array.
`1 2 2 1 2 2 1×⍞='1'` converts that array to: `0` for blank, `1` for `_`, `2` for `|`
`(x←1 2 2 1 2 2 1×⍞='1')[6 7 2 5 4 3]` assign that array to variable `x` and reorder to represent segments F, G, B, E, D, C
`0,x[1],0,(x←1 2 2 1 2 2 1×⍞='1')[6 7 2 5 4 3]` concatenates a blank, segment A and another blank to the front
`3 3⍴0,x[1],0,(x←1 2 2 1 2 2 1×⍞='1')[6 7 2 5 4 3]` reshape to a 3x3 matrix
`1+3 3⍴0,x[1],0,(x←1 2 2 1 2 2 1×⍞='1')[6 7 2 5 4 3]` converts to 1-based indexing
Finally uses the string `' _|'` to convert indicies into characters
---
## Edit
```
' _|'[1+3 3⍴(0,1 2 2 1 2 2 1×⍞='1')[1 2 1 7 8 3 6 5 4]]
```
Shaved off 3 chars by concatenating a `0` to front the array and using duplicate indicies, preventing a variable assignment
[Answer]
## PHP 66 bytes
```
<?for(;11>$i;)echo++$i&3?$argv[1][md5(¡æyÚ.$i)%8]?$i&1?~ƒ:_:~ß:~õ;
```
A slight improvement using an `md5` magic formula, but requires 3 additional binary bytes:
`¡`, `æ`, and `Ú` are characters 161, 230, and 218 respectively. It should work as is if copied directly, and saved as an ANSI format.
---
## PHP 73 (70) bytes
```
<?for($s=327638584;3<$s;)echo++$i&3?$argv[1][7&$s/=8]?$i&1?'|':_:' ':'
';
```
If you'll allow me three binary characters, this can be reduced to **70 bytes**:
```
<?for($s=327638584;3<$s;)echo++$i&3?$argv[1][7&$s/=8]?$i&1?~ƒ:_:~ß:~õ;
```
where `ƒ`, `ß`, and `õ` are characters 131, 223, and 245 respectively.
Receives input as a command line argument. Sample usage:
```
$ php seven-seg.php 1101101
_
_|
|_
$ php seven-seg.php 0111011
|_|
_|
```
[Answer]
## JavaScript + jQuery + HTML + CSS (~~210~~ 201)
This solution uses CSS sprites and [the image provided as an example](http://upload.wikimedia.org/wikipedia/commons/thumb/d/d1/7-segment.svg/220px-7-segment.svg.png):
### HTML (3)
```
<a>
```
### CSS (~~82~~ 71)
Thanks to [xem](https://codegolf.stackexchange.com/users/10732/xem) for the "*background:url*" trick:
```
a{background:url(//bit.ly/VesRKL);width:13px;height:23px;display:block}
```
### JavaScript (125 after removing newlines added here for readability)
```
i=prompt();
x=-parseInt(i.substr(0,3),2)*23;
y=-parseInt(i.substr(3),2)*13.75;
$('a').css('background-position',y+'px '+x+'px');
```
---
Online test: <http://jsfiddle.net/zhqJq/3/>
[Answer]
# R (65 chars):
```
plot((3^(1i*1.5:-4.5)*(1:7!=7)),col=strsplit(readline(),'')[[1]])
```
Relies on some loose approximations for some transcendental nuumbers ...
[Answer]
# Python 2 - 65
```
s=raw_input()+'0\n'
for i in`0x623C239E38D2EAA1`:print s[int(i)],
```
Example:
```
echo 1101101|python2 7seg.py
0 1 0
0 0 1
0 1 0
1 0 0
0 1 0
```
[Answer]
## J (51)
```
1 2 1#"1[5 3$' #'{~,|:>0;(88707#:~7#7){>".&.>1!:1[1
```
output:
```
1101101
##
#
##
#
##
```
[Answer]
**PostScript: 53 binary, 87 ASCII 52 binary, 86 ASCII**
Hexdump of the program using binary tokens:
```
$ hexdump -C lcd_binary.ps
00000000 28 34 34 30 34 30 38 30 34 30 34 30 30 30 30 34 |(440408040400004|
00000010 30 34 30 34 34 34 34 34 38 34 38 30 38 29 7b 7d |0404444484808){}|
00000020 92 49 6e 7b 92 70 31 92 04 92 96 92 6b 92 63 92 |.In{.p1.....k.c.|
00000030 a7 7d 92 49 |.}.I|
00000034
```
[Download this file](http://www.mediafire.com/?vs6te3yueiig2r1) to try it out.
Using ASCII tokens:
```
(4404080404000040404444484808){}forall
n{not 1 and setgray moveto lineto stroke}forall
```
First `forall` loop puts all required coordinates on the stack. The coordinates are stored in a string to minimize required space. The coordinates are in reverse order, i.e. the last 4 chars are for segment A. We draw a line from `(0,8)` to `(4,8)` for this segment (actually, we have to add 48 to all coordinates, because `forall` puts all ASCII codes on the stack).
The second `forall` loops through all the `0`s and `1`s in the input string and turns them into a gray value. `0`s are drawn white (gray value 1) and `1`s are drawn black (gray value 0). Then we use the coordinates that the first `forall` loop left on the stack to draw the lines.
Invoke the program using Ghostscript, just like Geoff Reedy's:
```
gs -sn=1101101 lcd.ps
```
This displays: 
[Answer]
## APL ~~101 86 73~~ 69
```
m←45⍴' '⋄m[¯40+⎕av⍳(⍎∊3/' ',¨⍕⍞)/')*+16;EJOQRSAFK-27=>?']←'⎕'⋄9 5⍴m
```
Input is from the screen via ⍞
```
1101101
```
Which produces a 9x5 character matrix composed of blanks and ⎕ as follows:
```
⎕⎕⎕
⎕
⎕
⎕
⎕⎕⎕
⎕
⎕
⎕
⎕⎕⎕
```
The seven digit number is converted into a partition vector to select the ⎕ co-ordinates.
[Answer]
## Mathematica ~~112~~ ~~103~~ ~~100~~ ~~96~~ 88, using Graphs
```
HighlightGraph[z=GridGraph@{3,2},Pick[EdgeList[z][[{3,4,1,2,6,7,5}]],Characters@#,"1"]]&
```

```
Using it to show a calculator display
l = {7-> 7, 1-> 6, 0-> 63, 8-> 127, 9-> 111,3 -> 79, 5-> 109, 2-> 91, 4-> 102, 6-> 125};
GraphicsRow[
HighlightGraph[z = GridGraph[{3,2}, EdgeStyle-> {White}, GraphHighlightStyle-> {"Thick"}],
EdgeList[z][[{3, 4, 1, 2, 6, 7, 5}]][[IntegerDigits[#, 2, 7] Range@7]]] & /@
(IntegerDigits[8736302] /. l)]
```

[Answer]
## Python (107)
Definitely more golfable.
```
a=map(int,raw_input())
for i in(0,6,3):print' .. '*a[i]+('\n'+' .'[a[5-i/6]]+' '+' .'[a[1+i/6]])*(2*(i!=3))
```
Output:
```
1101101
..
.
.
..
.
.
..
```
Explanation:
```
a is a list of booleans extracted from the input.
When you multiply a string with a number, it will return the string repeated (number) times.
If that number happens to be zero, it returns an empty string.
i is iterated through 0 (pos A), 6 (pos G), and 3 (pos D).
' .. ' will print either section A, G, or D, depending on the value of i.
([string here])*(2*(i!=3)) will print [string here] twice only if i!=3.
Breaking down [string here]:
- '\n' will print a newline for each repetition.
- ' ' is the null space between horizontal sections.
- ' .'[(bool)] will return either ' ' if (bool) is 0, and '.' if (bool) is 1.
- 5-i/6 will return 5 if i=0 and 4 if i=6. a[5] is section F and a[4] is section E.
- 1+i/6 will return 1 if i=0 and 2 if i=6. a[1] is section B and a[2] is section C.
```
[Answer]
# Python 2.7 (93 chars):
```
print (' {0}\n{5} {1}\n {6}\n{4} {2}\n {3}').format(*map(lambda x:int(x)and'*'or' ',raw_input()))
```
### Explanation:
With the stdin input, use a makeshift ternary operator to give `*` for true and a space for false. Take those values and plug them into a format statement that's in the format of the 7 digit display. It'd be at most 83 characters if the display worked like this:
```
a
b c
d
e f
g
```
but the ordering makes it longer. Anyone have a way around this?
### Example:
```
$ ./7seg.py
111000
*
*
*
$ ./7seg.py
1111111
*
* *
*
* *
*
```
[Answer]
I thought we needed a lispy answer...
# Clojure, 159 chars
```
(print(apply str(flatten(interpose\newline(partition 3(map(fn[x](if(= x\1)\o" "))(str" "(apply str(interpose" "(map(vec(read-line))[0 5 1 6 4 2 3])))" ")))))))
```
The above will run in the REPL and provide the correct answer. For example:
```
1111111
o
o o
o
o o
o
```
Throwing numbers at it with small modifications:
```
(doseq [i ["1111110" "0110000" "1101101" "1111001" "0110011" "1011011" "1011111" "1110000" "1111111" "1111011"]]
(println (apply str(flatten(interpose\newline(partition 3(map(fn[x](if(= x\1)\o" "))(str" "(apply str(interpose" "(map(vec i)[0 5 1 6 4 2 3])))" ")))))))
(println))
```
yields:
```
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
nil
```
Not easy to read, but they're there!
[Answer]
## Javascript 123
```
s=prompt(i=o='');for(m=' 0516423';i++<15;i%3==0?o+='\n':1)o+=' ─│'[~i%2&(A=+s[+m[~~(i/2)]])+(A&+'110'[i%3])];console.log(o)
```
I can bring the character count lower (101) if we use only one character for the "on" state, but it is less legible:
```
s=prompt(i=o='');for(m=' 0516423';i++<15;i%3==0?o+='\n':1)o+=' ■'[~i%2&s[+m[~~(i/2)]]];console.log(o)
```
[Answer]
# Postscript 136
Not winner, but a different approach.
```
15 string exch{1 and 255 mul}forall
[7 3 9 13 11 5 1]{count 1 sub index 3 1 roll exch put}forall
3 5 8[.02 0 0 .05 0 0]{}image showpage
```
Expects the input string to be on the stack:
```
$ echo '(1101101)'|cat - 7seg.ps |gs -sDEVICE=png16 -sOutputFile=6c.png -
```
This one's even worse. **294** to make a "binary" bitmap. I took me a while to remember that each row is padded to an even byte. So a 3x5 bitmap is five bytes with the 3 msb bits significant.
```
2#1101101
(12345)exch
2 copy 64 and 0 exch put %A
2 copy 2 and 6 bitshift 2 index 32 and or 1 exch put %F B
2 copy 1 and 6 bitshift 2 exch put %G
2 copy 4 and 5 bitshift 2 index 16 and 1 bitshift or 3 exch put %E C
2 copy 8 and 3 bitshift 4 exch put
pop
3 5 1[.02 0 0 .02 0 0]{}image showpage
```
Output is just as ugly as the other one. :(
Alright here's one that looks good. **190**
Edit: It was upside-down and backwards. Fixed now.
```
(1101101)
{neg 49 add 255 mul
1 string dup 0 4 3 roll put}forall
(\377){@/g/f/e/d/c/b/a}{exch def}forall
@ a a @
b @ @ f
b @ @ f
@ g g @
c @ @ e
c @ @ e
@ d d @
4 7 8[.01 0 0 .01 0 0]{}image showpage
```
[Answer]
# Mathematica 264
Getting the output to look right required many bytes, so no cigar this time.
But here's the verbose (264 chars) code anyway.
```
{a, b, c, d, e, g} = {{-1, 5}, {1, 5}, {1, 3}, {1, 1}, {-1, 1}, {-1, 3}};
f@n_ := Graphics[{Yellow, Thickness[.1], CapForm["Round"],
Line /@ {{g, c}, {g, a}, {g, e}, {e, d}, {d, c}, {c, b}, {b, a}}[[Flatten@
Position[IntegerDigits[n, 2, 7], 1]]]},
Background -> Blue, PlotRange -> {{-1, 1}, {1, 5}}, PlotRangePadding -> 1]
```
The complete set of characters:
```
GraphicsGrid[Partition[Table[f[p], {p, 0, 128}], 16]]
```

The digits:
```
{f[63], f[6], f[91], f[79], f[102], f[109], f[125], f[7], f[127], f[111]}
```

[Answer]
**PHP - 155 characters**
```
<?php
$y=array(" \n"," - \n"," \n"," |\n","| \n","| |\n"); $x = $argv[1]; echo $y[$x[0]].$y[2*$x[6]+$x[2]+2].$y[$x[7]].$y[2*$x[5]+$x[3]+2].$y[$x[4]];
```
it would be 150 characters if we use php 5.4 type array declaration, but i dont have that installed on my laptop so couldn't test it.
**Sample out puts.**

**Explanation:**
First i divided the 7 segment display to Five rows and 3 columns. With 1st, 3rd and 5th row havimg '-' in the middle column, and space otherwise.
The 2nd and 4th row has a pipe '|' character in the first and last column. Now the presence of these character should be guided by the input values.
I created a lookup table, which is basically two lookup table. First one for the calculation of values for 1st, 3rd and 5th row. And another one at offset 2 ( 3rd item ) for calculation of rows 2nd and 4th.
[Answer]
# Java - 204 characters
```
class A{public static void main(String[]a){char[]c=new char[7];for(int i=0;i<7;i++)c[i]=a[0].charAt(i)==49?i%3==0?95:'|'):32;System.out.printf(" %c %n%c%c%c%n%c%c%c",c[0],c[5],c[6],c[1],c[4],c[3],c[2]);}}
```
Sample output:
```
_
_|
|_
```
Formatted properly:
```
class A {
public static void main(String[] a) {
char[] c = new char[7];
for (int i = 0; i < 7; i++)
c[i] = a[0].charAt(i) == 49 ? (i % 3 == 0 ? 95 : '|') : 32;
System.out.printf(" %c %n%c%c%c%n%c%c%c", c[0], c[5], c[6], c[1], c[4], c[3], c[2]);
}
}
```
Really wish I could avoid that for loop, but I tried a few other things and they were all longer. There's probably a better way to do this, but this is my first attempt at code golf. (And Java's like the worst language for it, which is why I thought it would be interesting.) Even Brainfuck has me beat, but at least my output looks nicer.
EDIT: can get rid of "public" on class, saves me 7 chars!
And thanks, daniero, for showing me printf! (18 chars saved)
Rewrote the output format, changed character literals to decimal, 12 chars saved.
[Answer]
## VBA - 263
It's ugly but it works, I think. I am having trouble viewing the proper bit order, so I'm inferring from others' answers. Even if that piece is wrong, the code length should remain the same.
```
Sub d(b)
Dim c(1 To 7)
For a=1 To 7
c(a)=Mid(b,a,1)
Next
x=" - "
y="|"
z=" "
w=" "
v=vbCr
MsgBox IIf(c(1)=1,x,w) & v & IIf(c(6)=1,y,z) & z & IIf(c(2)=1,y,z) & v & IIf(c(7)=1,x,w) & v & IIf(c(5)=1,y,z) & z & IIf(c(3)=1,y,z) & v & IIf(c(4)=1,x,w)End Sub
```
[Answer]
**VBScript - 178 characters**
```
m=Split("2 7 11 10 9 5 6")
s=" _ "&vbCr&"|_|"&vbCr&"|_|"
For x=1 To 7
If Mid(WScript.Arguments.Item(0),x,1)=0 Then r=m(x-1):s=Left(s,r-1)&" "&Right(s,Len(s)-r)
Next
MsgBox s
```
[Answer]
# CJam - 29
```
l0N]s7078571876784728737Ab\f=
```
CJam is a new language I am developing, similar to GolfScript - <http://sf.net/p/cjam>. Here is the explanation:
`l` reads a line from the input
`0` is the number 0
`N` is a variable preinitialized to the newline string
`]` gathers the elements on the stack into an array
`s` converts a value (the array) to string, thus appending a zero and a newline to the given input
`7078571876784728737` is a number (the same number I used in python, but it was in hex there)
`A` is a variable preinitialized to 10
`b` does a base conversion, generating the array [7 0 7 8 ... 3 7]
`\` swaps the last two values on the stack
`f=` applies the `=` operator (here, indexed array access) on the input string (plus zero and newline) and each number 7, 0, 7, ...
The index 7 corresponds to the appended zero, and 8 corresponds to the appended newline.
My python solution does exactly the same thing (except the digit separation is done via string conversion)
[Answer]
# VBA, 188 characters
Note that the one has to *type* 188 characters if only including mandatory whitespace -- the IDE expands it out when you copy it into the VBA editor.
```
Sub f(i)
Dim c() As Byte
m=Split("1 6 10 9 8 4 5")
c=StrConv(" _ |_| |_|",128)
c(3)=10
c(7)=10
For x=1 To 7
If Mid(i,x,1) = 0 Then c(m(x-1))=32
Next
MsgBox StrConv(c,64)
End Sub
```
Sadly, VBScript doesn't have a strongly typed Byte array, or that one could be much shorter using this method.
[Answer]
# Javascript (ECMAScript 2016) - 108 bytes
```
console.log(([a,b,c,d,e,f,g]=[...prompt()].map((x,i)=>+x?'_||'[i%3]:' '),` ${a}
${f}${g}${b}
${e}${d}${c}`))
```
This *probably* can be golfed further, but I can't think of anything.
[Answer]
# JavaScript, 148 bytes
```
e=>(e[0]==1?" #\n":"\n")+(e[5]==1?"#":" ")+(e[1]==1?" #\n":"\n")+(e[6]==1?" #\n":"\n")+(e[4]==1?"#":" ")+(e[2]==1?" #\n":"\n")+(e[3]==1?" #\n":"\n")
```
[Try it online!](https://tio.run/##bcvLCsIwEAXQXyntIgnWYH0hhujOn1AXIZ2UlJLUPLoRvz0GumxnceEe7vRiEl46PYatsS2knifgNwzP3Zvz5l4W1cuU1zIH2WQ9zVplKmZpVnfnVT0uvveru8NCE5uEK5TnDj5RO8BIeUSY8tSBaB96yEK1GWOgQVtUoxjUBdUqGpm7wVBL8pXWeDsAHWyHeywJYT/CUjPfHw "JavaScript – Try It Online") (Footer is Node.js to read `.input.tio`)
Accepts input of ABCDEFG in binary flags and returns:
```
#
# #
#
# #
#
```
[Answer]
# SmileBASIC, 136 bytes
```
DIM A[7,2]COPY A,@L@L?DATA.,1,1,3,4,3,6,1,4,0,1,0,3,1INPUT X$FOR I=0TO 6M=I MOD 3GBOX A[I,1],A[I,0],A[I,1]+!M,A[I,0]+!!M,-VAL(X$[I])NEXT
```
Output is graphical.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
C₄+ç
```
[Try it online](https://tio.run/##yy9OTMpM/f/f@VFTi/bh5f//GxoagBAA) or [verify all possible inputs](https://tio.run/##yy9OTMpM/W9oZOHml2SedXiDgZWLvZLCo7ZJCkr2/50fNbVoH17@X@c/AA).
See the *verify all possible inputs* link above to see the mapping used for each input.
**Explanation:**
This abuses the rules where it states:
>
> How you represent the display is up to you -- **a single Unicode or ASCII symbol**, ASCII art, grafically, or whatever you can come up with. However, **each input must have it's own distinct output.**
>
>
>
```
C # Convert the (implicit) input from binary to integer
₄+ # Increase it by 1000
ç # Convert it to a unicode character with this value (and output implicitly)
```
---
Alternative more in the spirit of the challenge using the output-format:
```
-
| |
-
| |
-
```
### 38 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage):
```
Σ•L7וNè}εi" -| | "14∍2ôNèëðº]J24S5∍£»
```
Can definitely be golfed..
[Try it online](https://tio.run/##yy9OTMpM/f//3OJHDYt8zA9PB1J@h1fUntuaqaSgW6NQo6BkaPKoo9fo8Bag8OHVhzcc2hXrZWQSbAoUPLT40O7//w0NDUAIAA) or [verify all possible inputs](https://tio.run/##yy9OTMpM/W9oZOHml2SedXiDgZWLzv9zix81LPIxPzwdSPkdXlF7bmumkoJujUKNgpKhyaOOXqPDW4DCh1cf3nBoV22tl5FJsClQ9NDiQ7v/6/wHAA).
**Explanation:**
```
Σ } # Sort the (implicit) input-digits by:
•L7וNè # The digit at the same index in the compressed integer 1367524
# i.e. "1101101" → ["1","0","1","1","1","0","1"]
ε # Then map each digit to:
i # If it's a 1:
" -| | " # Push string " -| | "
14∍ # Lengthen it to size 14: " -| | -| | -"
2ô # Split it into parts of 2: [" -","| ","| "," -","| ","| "," -"]
Nè # Index into it
ë # Else (it's a 0):
ðº # Push " " (two spaces) instead
] # Close both the if-else and map
# i.e. ["1","0","1","1","1","0","1"]
# → [" -"," ","| "," -","| "," "," -"]
J # Join everything together to a single string
# i.e. [" -"," ","| "," -","| "," "," -"] → " - | -| -"
24S # Push [2,4]
5∍ # Lengthened to size 5: [2,4,2,4,2]
£ # Split the string into parts of that size
# i.e. " - | -| -" → [" -"," | "," -","| "," -"]
» # Join by newlines (and output implicitly)
# i.e. [" -"," | "," -","| "," -"] → " -\n | \n -\n| \n -"
```
[See this 05AB1E tip of mine (*section How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•L7ו` is `1367524`.
[Answer]
# PHP 5.6, 65 bytes plain ASCII
```
for(;$p++<9;)echo$argn[_707561432[$p]]?"||_"[$p%3]:" ","\n"[$p%3];
```
or, without a trailing linebreak, but with some bitwise fun:
```
for(;$p++<11;)echo$argn[_70785618432[$p]]?L|Sx[$p&1]:a^kAAA[$p&3];
```
Run as pipe with `-nR` or [try them online](http://sandbox.onlinephpfunctions.com/code/9b2187c98212f4ce1abd0749028b641b13069546).
**breakdown 1**
```
for(;$p++<9;)echo # loop through positions
$argn[_707561432[$p]] # map position to input bit
?"||_"[$p%3] # if set: underscore in 2nd column, pipe symbol else
:" " # else space
,"\n"[$p%3] # add newline every 3 columns
;
```
**breakdown 2**
```
for(;$p++<11;)echo # loop through positions
$argn[_70785618432[$p]] # map position to input bit (bit 8 for EOL, never set)
?L|Sx[$p&1] # if set: underscore in the middle, pipe symbol else
:a^kAAA[$p&3] # else: newline in 4th column, space else
```
] |
[Question]
[
I was browsing Stack Overflow when I saw [this post in Puzzling](https://puzzling.stackexchange.com/q/112984) in the hot network questions and decided to make a challenge out of it (all credit goes to the creator of the challenge).
## Overview
A Chess Number is a number that, when converted to base 18, results in a valid chess coordinate pair, where the first character is a-h and the second character is 1-8 (inclusive). Your job is to generate the full list of them, ordered. Output may be an array/list, printed individually, as a matrix/grid, or in a string. **The numbers must be in decimal, not base 18.**
## Examples
Here is a Python program to generate the full list:
```
def baseN(num, b, numerals = "0123456789abcdefghijklmnopqrstuvwxyz"):
return ((num == 0) and numerals[0]) or (baseN(num // b, b, numerals).lstrip(numerals[0]) + numerals[num % b])
for i in range(0, 10000):
s = baseN(i, 18)
if len(s) == 2 and s[0].isalpha() and s[1].isdigit() and 0 < int(s[1]) < 9:
print(i, s)
```
[Try it online!](https://tio.run/##VY5RTsMwEET/c4pVJSSviFonUNoicgUugPrhECcxdR1jO0C5fNhtowL7s9aMd974U@oHV05To1uoVdTPwo3HHOocaOugbIQKFrIo7@7XD5vtTtWv9LXrzdvBHt3g30NM48fn1@l7gY8Z0ASdxuBAcBBUFUgE5Zpr3IvcIwwBxJUGqxXz/iBxaWMKxot/R7e/GXx1A/Ues6ylLAPGQVCu00LmUEiauQy3v4AMGVs8i6YFq52IyPXKczsmLE1U1vdK4CwVLDWmM2mWJDwRKQm2kN67C4THBzYIEnGafgA "Python 2 – Try It Online")
The complete list is:
```
181, 182, 183, 184, 185, 186, 187, 188, 199, 200, 201, 202, 203, 204, 205, 206, 217, 218, 219, 220, 221, 222, 223, 224, 235, 236, 237, 238, 239, 240, 241, 242, 253, 254, 255, 256, 257, 258, 259, 260, 271, 272, 273, 274, 275, 276, 277, 278, 289, 290, 291, 292, 293, 294, 295, 296, 307, 308, 309, 310, 311, 312, 313, 314
```
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code in bytes wins
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~8~~ 7 bytes
```
9Ṗ+pṖḅḤ
```
[Try it online!](https://tio.run/##y0rNyan8/9/y4c5p2gVA4uGO1oc7lvz/DwA "Jelly – Try It Online")
-1 byte thanks to [Lynn](https://codegolf.stackexchange.com/users/3852/lynn) by combining our answers, so make sure to upvote [their answer](https://codegolf.stackexchange.com/a/239652/66833) as well!
## How it works
```
9Ṗ+pṖḅḤ - Main link. Takes no arguments
9 - Set the return value to 9, and execute with 9 on the left
Ṗ - Pop, yielding [1,2,3,4,5,6,7,8]
+ - Add 9 to each: [10,11,12,13,14,15,16,17]
Ṗ - Pop, yielding [1,2,3,4,5,6,7,8]
p - Cartesian product: [[10,1],[10,2],...,[17,8]]
Ḥ - Unhalve; Yield 18
ḅ - Unbase; Convert [a, b] to 18a+b
```
[Answer]
# [Python 3](https://docs.python.org/3/), 55 bytes
Edit: Was 56 bytes, now 55. Thanks to Dronir for proposing printing the numbers as a list.
Edit: Was 57 bytes, now 56. Thanks to Neil for proposing the `-~j` modification.
```
print([18*i-~j for i in range(10,18)for j in range(8)])
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EI9rQQitTty5LIS2/SCFTITNPoSgxLz1Vw9BAx9BCEySYhRC00IzV/P8fAA "Python 3 – Try It Online")
# [Python 2](https://docs.python.org/2/), 53 bytes
Thanks to Kevin Cruijssen for propsing switching to Python 2 to save a couple of bytes.
```
print[18*i-~j for i in range(10,18)for j in range(8)]
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM68k2tBCK1O3LkshLb9IIVMhM0@hKDEvPVXD0EDH0EITJJiFELTQjP3/HwA "Python 2 – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~35~~ 17 bytes
```
1:8+18*80:143%/%8
```
[Try it online!](https://tio.run/##K/r/39DKQtvQQsvCwMrQxFhVX9Xi/38A "R – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~37~~ 36 bytes
```
x=64
while x:x-=1;print 314-x-x/8*10
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v8LWzISrPCMzJ1WhwqpC19bQuqAoM69EwdjQRLdCt0LfQsvQ4P9/AA "Python 2 – Try It Online")
1 byte saved thanks to loopy walt
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
18⁵rṖp8ḅ
```
[Try it online!](https://tio.run/##y0rNyan8/9/Q4lHj1qKHO6cVWDzc0fr/PwA "Jelly – Try It Online")
```
18 18
⁵r Range from ⁵=10: [10..18]
Ṗ Remove last element: [10..17] ([a..h])
p8 Cartesian product with [1..8]
ḅ Convert from base 18
```
[Answer]
# [R](https://www.r-project.org/), ~~44~~ ~~25~~ 22 bytes
```
x=180:313;x[x%%18<8]+1
```
[Try it online!](https://tio.run/##K/r/v8LW0MLAytjQ2LoiukJV1dDCxiJW2/D/fwA "R – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~11~~ 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
8Lã18δβƵz+
```
-1 byte thanks to *@ovs*.
[Try it online.](https://tio.run/##yy9OTMpM/f/fwufwYkOLc1vObTq2tUr7/38A)
A port of [*@JosephWalker*'s Python 3 answer](https://codegolf.stackexchange.com/a/238581/52210) is 11 bytes: `7ÝT+18*8LâO` - [Try it online](https://tio.run/##yy9OTMpM/f/f/PDcEG1DCy0Ln8OL/P//BwA).
A port of [*@Arnauld*'s JavaScript first answer](https://codegolf.stackexchange.com/a/238577/52210) is 12 bytes: `ƵΔƵÖŸʒ<18%8‹` - [Try it online](https://tio.run/##AR4A4f9vc2FiaWX//8a1zpTGtcOWxbjKkjwxOCU44oC5//8).
A port of [*@GB*'s Ruby answer](https://codegolf.stackexchange.com/a/238582/52210) is 12 bytes as well: `63ÝD8÷T*ƵΘ++` - [Try it online](https://tio.run/##yy9OTMpM/f/fzPjwXBeLw9tDtI5tPTdDW/v/fwA).
A port of [*@ovs*' APL answer](https://codegolf.stackexchange.com/a/238583/52210) is 13 bytes: `ƵgLD18%9›ÏƵη+` - [Try it online](https://tio.run/##yy9OTMpM/f//2NZ0HxdDC1XLRw27Dvcf23puu/b//wA).
A port of [*@Giuseppe*'s R answer](https://codegolf.stackexchange.com/a/238580/52210) is 14 bytes: `80ƵgŸ8÷18*8LÞ+` - [Try it online](https://tio.run/##yy9OTMpM/f/fwuDY1vSjOywObze00LLwOTxP@/9/AA).
**Explanation:**
```
8L # Push a list in the range [1,8]
ã # Create all possible pairs with the cartesian product
δ # Map over each pair:
18 β # Convert it from a base-18 list to an integer
Ƶz+ # And add 162 to each
# (after which the result is output implicitly)
```
[See this 05AB1E answer of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `Ƶz` is `162`.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 27 bytes
```
64.times{|x|p x+x/8*10+181}
```
[Try it online!](https://tio.run/##KypNqvz/38xEryQzN7W4uqaipkChQrtC30LL0EDb0MKw9v9/AA "Ruby – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 14 [bytes](https://github.com/abrudz/SBCS)
```
171+⍸9<18|⍳143
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97b@huaH2o94dljaGFjWPejcbmhiDxP@nAQA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 16 bytes
```
(181+⊢+18×⊣)⌜˜↕8
```
[Run it online!](https://mlochbaum.github.io/BQN/try.html#code=KDE4MSviiqIrMTjDl+KKoynijJzLnOKGlTg=) Outputs an 8x8 array of numbers.
### Explanation
A port of [my Pip solution](https://codegolf.stackexchange.com/a/238590/16766).
```
(181+⊢+18×⊣)⌜˜↕8
↕8 Range(8)
( )⌜˜ Generate a table, using that range twice, with this function:
18×⊣ 18 times left argument
⊢+ plus right argument
181+ plus 181
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), 35 bytes
Test modulo \$18\$.
```
for(n=180;n<314;)n++%18<8&&print(n)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/Py2/SCPP1tDCwDrPxtjQxFozT1tb1dDCxkJNraAoM69EI0/z/38A "JavaScript (V8) – Try It Online")
---
# [JavaScript (V8)](https://v8.dev/), 36 bytes
Expanding \$[0\dots63]\$ in reverse order to \$[181\dots314]\$.
```
for(n=64;n--;)print(314-(n>>3)*10-n)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/Py2/SCPP1szEOk9X11qzoCgzr0TD2NBEVyPPzs5YU8vQQDdP8/9/AA "JavaScript (V8) – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 12 bytes
```
ṠṪ+mo*18+9ḣ8
```
[Try it online!](https://tio.run/##yygtzv7//@HOBQ93rtLOzdcytNC2fLhjscX//wA "Husk – Try It Online")
```
ḣ8 # get the range from 1..8
Ṡ # Ṡfgx = f(g(x),x)
# so we use the range 1..8 twice
# once directly as an argument to f
# and once after applying g to it
Ṫ+ # f = Ṫ+ = outer product by addition
mo*18+9 # g =
mo # map over each element
+9 # add 9
*18 # and then multiply by 18
```
[Answer]
# [APOL](https://esolangs.org/wiki/APOL), 38 bytes
Port of [Joeph Walker's genius answer](https://codegolf.stackexchange.com/a/238581/66833), all credit goes to him.
`ḟ(10 18 v(0 ∋) ḟ(1 9 p(*(18 +(∋ ⁰)))))`
Sadly, APOL doesn't support nested for counters, so I have to use a clunkier solution. Maybe I'll implement them and come back to this later.
[Answer]
# [Python 3](https://docs.python.org/3/) with NumPy, [62](https://tio.run/##K6gsycjPM/6fZhvzPycxNykl0SqvNLegUq8otTgjsSBVoygxLz1Vw9jIRFNHw9BCx9BCUzPa0MBKx9DKMpYrM7cgv6hEAazjf0FRZl6JRpqGpuZ/AA "Python 3 – Try It Online") [52](https://tio.run/##K6gsycjPM/6fZhvzPycxNykl0aq4NFcjrzS3oFIvN70oMyXa0MLAytjIwMrQQsfQyjJWkysztyC/qEQBrOZ/QVFmXolGmoam5n8A "Python 3 – Try It Online") [46](https://tio.run/##K6gsycjPM/6fZhvzPycxNykl0crQQqsoPtrQAMiI1U4GsqwsY7nSivJzFfJKcwsqFTJzC/KLSrT@FxRl5pVopGloav4HAA "Python 3 – Try It Online") bytes
```
lambda:18*r_[10:18]+c_[1:9]
from numpy import*
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNykl0crQQqsoPtrQAMiI1U4GsqwsY7nSivJzFfJKcwsqFTJzC/KLSrT@FxRl5pVopGloav4HAA "Python 3 – Try It Online")
Utilizing [the option to return output in a 2d array](https://codegolf.stackexchange.com/questions/238575/generate-the-chess-numbers#comment540316_238575). I'm a little fuzzy on how I/O is allowed in python so let me know if this is unacceptable / I need more boilerplate.
Thanks to [loopy wait](https://codegolf.stackexchange.com/users/107561/loopy-walt) for `r_` and `c_`
[Answer]
# APL+WIN, 24 bytes
```
18⊥(∊9+¨8/¨⍳8),[.1]64⍴⍳8
```
[Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3tv6HFo66lGo86uiy1D62w0D@04lHvZgtNnWg9w1gzk0e9W0Dc/0CVXP/TuAA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 12 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
8r♂+G*mÉ8╒+─
```
[Try it online.](https://tio.run/##y00syUjPz0n7/9@i6NHMJm13rdzDnRaPpk7SfjSl4f9/AA)
**Explanation:**
```
8r # Push a list in the range [0,8)
♂+ # Add 10 to each to make the range [10,18)
G* # Multiply each by 18
m # Map over this list,
É # Using 3 characters as inner code-block:
8╒ # Push range [1,8]
+ # Add the map-integer to each
─ # After the map: flatten the list of lists
# (after which the entire stack is output implicitly as result)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes
```
I⁺¹⁸¹E⁶⁴↨¹⁸↨ι⁸
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEIyCntFjD0MJQR8E3sUDDzERHwSmxOBUoAmVk6ihYaIKB9f///3XLcgA "Charcoal – Try It Online") Link is to verbose version of code. I had three 15 byte solutions (including one which generated the range `a1..h8` and converted them from base 18) but I was able to golf one of them down to 14. Explanation:
```
⁶⁴ Literal integer `64`
E Map over implicit range
ι Current integer
↨ ⁸ Divmod by 8 using base conversion
↨¹⁸ Interpret as base 18
⁺¹⁸¹ Vectorised add 181
I Cast to string
Implicitly print
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 13 bytes
```
181+18*_+BMC8
```
Use with some kind of list-formatting flag: `-P` and `-S` work well. [Try it online!](https://tio.run/##K8gs@P/f0MJQ29BCK17bydfZ4v///7oBAA "Pip – Try It Online")
### Explanation
```
181+18*_+BMC8
MC Map the following function to coordinate pairs
8 from an 8x8 grid:
181+ 181 plus
18*_ 18 times the row number
+B plus the column number
```
---
Here's a 16-byte solution that uses base conversion:
```
J_MzH8CP\,8FB:18
z Lowercase alphabet
H8 First 8 characters
CP Cartesian product with
\,8 1-based range up to 8
M To each of the resulting pairs, map:
J_ Join into a single string
FB: Convert from base
18 18
```
You can run it at [Replit](https://replit.com/@dloscutoff/pip), or a 17-byte version on [TIO](https://tio.run/##K8gs@P/fK963ysHGwjkgRsfCzcnK0OL///@6BQA).
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 23 bytes
```
18#+162+#2&~Array~{8,8}
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2P739BCWdvQzEhb2UitzrGoKLGyrtpCx6L2f0BRZl5JdE7sfwA "Wolfram Language (Mathematica) – Try It Online")
Returns a 2d array.
[Answer]
# [Clojure](https://www.clojure.org), 59 45 bytes
`(map read-string(for[x"abcdefgh"y"12345678"](str"18r"x y)))`
`(for[x(range 10 18)y(range 1 9)](+(* 18 x)y))`
[Answer]
# C, ~~[64](https://tio.run/##S9ZNT07@/z/LOjcxM08jU7M6Lb9II9PW0MA6U9fQwjpTW1uzPCMzJ1VDWztL1VKzoCgzryRNQ0k1RUFJJ1PL0AIsal37//@/5LScxPTi/7rlAA)~~, [62](https://tio.run/##S9ZNT07@/z/LOjcxM08jU7M6Lb9II9PW0lpbO1PV0MJaszwjMydVQ1s7S9VSs6AoM68kTUNJNUVBSSdTy9ACLGpd@///v@S0nMT04v@65QA) bytes
Thank you @JustinFinnerty for the improvement
```
j;main(i){for(i=9;++i%18;)while(++j%9)printf("%d ",i*18+j%9);}
```
[Try it here!](https://tio.run/##S9ZNT07@/z/LOjcxM08jU7M6Lb9II9PW0lpbO1PV0MJaszwjMydVQ1s7S9VSs6AoM68kTUNJNUVBSSdTy9ACLGpd@///v@S0nMT04v@65QA)
Less golfed version:
```
i,j;
main(){
for(i=9;++i%18;)
while(++j%9)
printf("%d ",i*18+j%9);
}
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 37 bytes
```
63$*¶
$.`
.+
$*_181$*
_{8}
18$*
%`.
```
[Try it online!](https://tio.run/##K0otycxL/P@fy8xYRevQNi4uFb0ELj1tLhWteEMLQxUtrvhqi1ouQwsgSzVB7/9/AA "Retina 0.8.2 – Try It Online") Explanation:
```
63$*¶
$.`
```
Insert the numbers from `0` to `63`.
```
.+
$*_181$*
```
Convert to unary and add 181.
```
_{8}
18$*
```
Add an extra 10 for each multiple of 8 in the original number.
```
%`.
```
Convert to decimal.
[Answer]
# [Desmos](https://desmos.com/calculator), ~~37~~ 31 bytes
```
[a+bfora=[1...8],b=[10...17]18]
```
[Try It On Desmos!](https://www.desmos.com/calculator/hqzs2shwbp)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/h4qqrmkhpf)
Finally got a chance to utilize the new [list comprehension](https://twitter.com/Desmos/status/1451211022115561476) feature in Desmos!
### Explanation:
```
[ for ] initiate list comprehension for loop
a=[1...8], loop from a=1 to a=8, incrementing by 1
b=[10...17]18 loop from b=10*18 to b=17*18, incrementing by 18
(essentially creates a nested for loop)
a+b calculate a+b
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~11~~ 10 bytes
```
8:Ẋ18vβ⁺=+
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCI4OuG6ijE4ds6y4oG6PSsiLCIiLCIiXQ==)
~~I actually didn't port anything for once lol~~ 05ab1e porting go brrr.
## Explained
```
8:Ẋ18vβ⁺=+
8:Ẋ # The cartesian product of the range(1, 9) and range(1, 9)
18vβ # convert each pair from arbitrary base 18
⁺=+ # add 162 to each (128 + the index of `=` in the vyxal codepage)
```
## 11 bytes
```
8ƛ₀*9ɾM18vβ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCI4xpvigoAqOcm+TTE4ds6yIiwiIiwiIl0=)
```
8ƛ₀*9ɾM18vβ
8ƛ # For each item n in the range [1, 8]:
₀* # Mulitply n by 10
9ɾM # [[n * 10, x] for x in range(1, 10)]
18vβ # and convert each from arbitrary base 18 to base 10
```
[Answer]
# [Scratch](https://scratch.mit.edu), 112 bytes
[Try it online!](https://scratch.mit.edu/projects/612884194/)
Not much room for improvement
```
when gf clicked
set[N v]to(170
delete all of[C v
repeat(8
change[N v]by(10
repeat(8
change[N v]by(1
add(N)to[C v
```
Commentated:
```
when gf clicked Initiates code
set[N v]to(170 Sets N to 98 (in base-18)
delete all of[C v Clears the list
repeat(8 Loops code for each column of the chessboard
change[N v]by(10 Increases the tens digit by 1 and decreases the ones digit by 8
repeat(8 Loops code for each row of the chessboard
change[N v]by(1 Increases the ones digit by 1
add(N)to[C v Adds N to the list
```
[Answer]
# X86-64 Machine Code, Microsoft Calling Convention, 27 bytes
```
33 C0 xor eax,eax
B0 B5 mov al,0B5h
B2 08 mov dl,8
outerLoop:
B6 08 mov dh,8
innerLoop:
89 01 mov dword ptr [rcx],eax
48 83 C1 04 add rcx,4
FF C0 inc eax
FE CE dec dh
75 F4 jne innerLoop
04 0A add al,0Ah
FE CA dec dl
75 EC jne outerLoop
C3 ret
```
Which has the following function signature:
```
extern "C" void chessNumbers(uint32_t* out);
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 14 bytes
```
8⟦₁+₉ᶻ\↔ẋ~ḃ₁₈ᵐ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/3@LR/GWPmhq1HzV1Pty2O@ZR25SHu7rrHu5oBgo@aup4uHXC////owA "Brachylog – Try It Online")
```
8⟦₁ Range [1..8]
+₉ᶻ Add 9 to each element [[1,10],[2,11],..,[8,17]]
\↔ Transpose and swap [[10..17],[1..8]]
ẋ Cartesian product [[10,1],[10,2]..]
~ḃ₁₈ᵐ Convert each element from base 18
```
[Answer]
# [Python 3](https://docs.python.org/3/), 53 bytes
```
b=181
while b<308:[print(b+x)for x in range(8)];b+=18
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P8nW0MKQqzwjMydVIcnG2MDCKrqgKDOvRCNJu0IzLb9IoUIhM0@hKDEvPVXDQjPWOkkbqOH/fwA "Python 3 – Try It Online")
I believe this straightforward solution is currently the shortest vanilla Python 3 solution. :)
[Answer]
# [Perl 5](https://www.perl.org/), 33 bytes
```
map{//;say$_+$'*18for 1..8}10..17
```
[Try it online!](https://tio.run/##K0gtyjH9/z83saBaX9@6OLFSJV5bRV3L0CItv0jBUE/PotbQQE/P0Pz//3/5BSWZ@XnF/3V9TfUMDA0A "Perl 5 – Try It Online")
[Answer]
# [SimpleTemplate](https://github.com/ismael-miguel/SimpleTemplate) 0.84, 163 bytes
This code simply outputs a space separated list of numbers.
```
{@setN 181}{@for to314}{@if_ matches"@18[2-8]|199|2([09][0-6]|3[5-9]|4[012]|5[3-9]|60|7[1-8]|89|9[0-6])|(21|30)[789]|(22|31)[0-4]@"}{@setN N,_}{@/}{@/}{@echoj" "N}
```
It looks yucky, but works!
## How it works?
The code loops from 0 to 314, and then verifies if the number matches the following regular expression:
```
@18[2-8]|199|2([09][0-6]|3[5-9]|4[012]|5[3-9]|60|7[1-8]|89|9[0-6])|(21|30)[789]|(22|31)[0-4]@
```
If it matches, it is added to the array of numbers we need.
The generated array looks like this:
```
[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[181,182],183],184],185],186],187],188],199],200],201],202],203],204],205],206],217],218],219],220],221],222],223],224],235],236],237],238],239],240],241],242],253],254],255],256],257],258],259],260],271],272],273],274],275],276],277],278],289],290],291],292],293],294],295],296],307],308],309],310],311],312],313],314]
```
And this is the final output:
```
181 182 183 184 185 186 187 188 199 200 201 202 203 204 205 206 217 218 219 220 221 222 223 224 235 236 237 238 239 240 241 242 253 254 255 256 257 258 259 260 271 272 273 274 275 276 277 278 289 290 291 292 293 294 295 296 307 308 309 310 311 312 313 314
```
The `{@echo}` will automatically flatten the array internally, before printing it.
---
## Ungolfed:
The code is pretty nasty to look at, so, here's an ungolfed version that does the same:
```
{@set numbers 181}
{@for i from 0 to 314}
{@if i matches "@18[2-8]|199|2([09][0-6]|3[5-9]|4[012]|5[3-9]|60|7[1-8]|89|9[0-6])|(21|30)[789]|(22|31)[0-4]@"}
{@set numbers numbers, i}
{@/}
{@/}
{@echo separator " " numbers}
```
---
## About the language
There are a few things that are important to know to fully understand how it works.
* Almost all whitespace is optional.
* It is required to start with `181` in the variable.
If the variable isn't set to 181, the output will be incorrect, because the first value in the array will be `null`.
* The `{@for to314}` is the same as `{@for i from 0 to 314}`.
The variable is optional, and automatically assigns to `_`.
The `from 0` isn't required, as the loop will automatically start from 0 to the final number.
* Both `{@echo separator " " numbers}` and `{@echoj" "N}` do the same:
Output the variable values separated by `" "`. The `j` stands for "join", in `echoj`.
## Running the code:
You can run the code on: <http://sandbox.onlinephpfunctions.com/code/117ed06567a1d0e710e75b963566b86b510ca7ab>
Please pick a version between 5.6 and 7.4.13. Can't fix the 8.0.0 compatibility issue without invalidating this answer.
] |
[Question]
[
# Background
For this challenge, a 'metasequence' will be defined as a sequence of numbers where not only the numbers themselves will increase, but also the increment, and the increment will increase by an increasing value, etc.
For instance, the tier 3 metasequence would start as:
`1 2 4 8 15 26 42 64 93 130 176`
because:
```
1 2 3 4 5 6 7 8 9 >-|
↓+↑ = 7 | Increases by the amount above each time
1 2 4 7 11 16 22 29 37 46 >-| <-|
| Increases by the amount above each time
1 2 4 8 15 26 42 64 93 130 176 <-|
```
# Challenge
Given a positive integer, output the first twenty terms of the metasequence of that tier.
## Test cases
Input: `3` Output: `[ 1, 2, 4, 8, 15, 26, 42, 64, 93, 130, 176, 232, 299, 378, 470, 576, 697, 834, 988, 1160 ]`
Input: `1` Output: `[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ]`
Input: `5` Output: `[ 1, 2, 4, 8, 16, 32, 63, 120, 219, 382, 638, 1024, 1586, 2380, 3473, 4944, 6885, 9402, 12616, 16664 ]`
Input: `13` Output: `[ 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16383, 32752, 65399, 130238, 258096, 507624 ]`
As you may realise, the first \$t+1\$ items of each sequence of tier \$t\$ are the first \$t+1\$ powers of 2...
# Rules
* Standard loopholes apply
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 34 bytes
```
0~Range~19~Binomial~i~Sum~{i,0,#}&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@9@gLigxLz21ztCyzikzLz83MzGnLrMuuDS3rjpTx0BHuVbtf0BRZl5JtLKCrp1CWrRybKyCmoK@g0K1sY6CoY6CKZA0rv0PAA "Wolfram Language (Mathematica) – Try It Online")
The tier \$n\$ metasequence is the sum of the first \$n+1\$ elements of each row of the Pascal triangle.
[Answer]
# [Haskell](https://www.haskell.org/), 34 bytes
```
(iterate(init.scanl(+)1)[1..20]!!)
```
Uses 0-indexed inputs (`f 4` returns tier 5.)
# [Haskell](https://www.haskell.org/), 36 bytes
```
f 1=[1..20]
f n=init$scanl(+)1$f$n-1
```
[Try it online!](https://tio.run/##BcExCoAwDADA3Vdk6NAiFiM49iXiEIrRYgzF9v3Gu4vafYiYMWDaMMZl3gcGTUVLdy2Tih8DOnY6oT1UFBLUt2gHz7AG@zILnc2mXOsP "Haskell – Try It Online") Uses 1-indexed inputs (`f 5` returns tier 5.)
# Explanation
`scanl (+) 1` is a function that takes partial sums of a list, starting from (and prepending) `1`.
>
> For example: `scanl (+) 1 [20,300,4000]` equals `[1,21,321,4321]`.
>
>
>
It turns out that tier \$n\$ is just this function applied \$ (n-1) \$ times to the list \$[1,2,3,\dots]\$.
(Or equivalently: \$n\$ times to a list of all ones.)
We use either `init` or `[1..20-n]` to account for the list getting longer by \$1\$ every application.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~8~~ 7 bytes
```
20ḶcþŻS
```
[Try it online!](https://tio.run/##y0rNyan8/9/I4OGObcmH9x3dHfz//39TAA "Jelly – Try It Online")
```
cþ Table of binom(x,y) where:
20Ḷ x = [0..19]
Ż y = [0..n] e.g. n=3 → [[1, 1, 1, 1, 1, 1, …]
[0, 1, 2, 3, 4, 5, …]
[0, 0, 1, 3, 6, 10, …]
[0, 0, 0, 1, 4, 10, …]]
S Columnwise sum. → [1, 2, 4, 8, 15, 26, …]
```
This uses @alephalpha’s insight that $$\text{meta-sequence}\_n(i) = \sum\_{k=0}^n \binom ik.$$
[Answer]
# [Brain-Flak](https://github.com/Flakheads/BrainHack), ~~84~~ 82 bytes
```
<>((()()()()()){}){({}[((()))])}{}<>{({}[(())]<<>{({}<>({}))<>}<>{}{({}<>)<>}>)}<>
```
[Try it online!](https://tio.run/##SypKzMzLSEzO/v/fxk5DQ0MTBjWrazWrNapro0GCmpqxmrXVtTZ2UBEg3wbCAWoCKtS0sQNJ1kJEQDw7TSDj////JgA "Brain-Flak (BrainHack) – Try It Online")
## Annotated
```
<> Switch to the off stack
((()()()()()){}) Push 10
{({}[((()))])}{} Make twice that many 1s
<> Switch back
{ While ...
({}[(())]< Subtract one from the input and push 1
<> Switch
{ For every x on the stack
({}<>({}))<> Remove x and add it to a copy of the other TOS
} End loop
<>{} Remove 1 element to keep it 20
{({}<>)<>} Copy everything back to the other stack
>)}<> End scopes and loops
```
[Try it online!](https://tio.run/##dZFBT4QwEIXv/Io50gtxjUfCxejNrHFNPBgPBQbbAC1py66k6W/HtoAJa7ZN5jKd9755LRXlgtGqnee8gP05XbipGBgJhiHIpgFt/MskTVOyXWIdgddRMzjcJTa17jN0Cfkizjp4oS2CufDKV0YN9FRMcNDJLasyyNurHnww3iFkWZYs@l493@bG0ihaGZACoVGyj6hcDKMBKmoYItktv/9Wz1IBnlFN8OMlo9i6s3V54Qshq9Yb9vKM/lmwoXUN3ISkKFRymHxYS2a@KHg/nhJ37fTkxzopB89m981V@QDYYY8iyraIQ3C4X0LOC4@xTT0GwwhtGBffMcS/T4sAywoFcfscAoL2uKjjEoFGz/P88As "Brain-Flak (BrainHack) – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 36 bytes
```
rowSums(outer(0:19,0:scan(),choose))
```
[Try it online!](https://tio.run/##K/r/vyi/PLg0t1gjv7QktUjDwMrQUsfAqjg5MU9DUyc5Iz@/OFVT87/xfwA "R – Try It Online")
Thanks to @Giuseppe for suggesting `outer`.
This is based on the [approach @alephalpha described](https://codegolf.stackexchange.com/a/180863/42248)
[Answer]
# [dzaima/APL](https://github.com/dzaima/APL) REPL, 14 bytes
```
(+\1,19↑)⍣⎕⍳20
```
[Try it online!](https://tio.run/##SyzI0U2pSszMTfwPBBraMYY6hpaP2iZqPupd/Khv6qPezUYGXIZG//ILSjLz84r/6xYDAA "APL (dzaima/APL) – Try It Online")
```
(+\1,19↑)⍣⎕⍳20
( )⍣⎕ repeat the function below input times:
+\ cumulative sum of
1, 1 prepended to
19↑ the first 19 items of the previous iteration
⍳20 starting with the first 20 integers
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~69~~ ~~58~~ 55 bytes
*Saved bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs) and [Jo King](https://tio.run/##K6gsycjPM/r/P9c2JzE3KSVRIc8q2lC7uDRXI1cjT9dQM9oqM1YzLb9IIVMhM0@hKDEvPVWjLk8hMS9FwchAM/Y/SKoEIWWoY6ppxaVQUJSZVwI0oURT8z8A); also, it works in Python 3 now as well.*
```
m=lambda t:[1+sum(m(t-1)[:n])for n in range(~t and 20)]
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9c2JzE3KSVRocQq2lC7uDRXI1ejRNdQM9oqL1YzLb9IIU8hM0@hKDEvPVWjrkQhMS9FwchAM/Y/SKoEIWWoY6ppxaVQUJSZVwIyQVPzPwA "Python 2 – Try It Online")
### The math
Let \$a(t,n)\$ be the \$n^{th}\$ term (0-indexed) of the sequence at tier \$t\$. A little analysis leads to the following recurrence formula:
$$
a(t,n) = 1+\sum\_{i=0}^{n-1}a(t-1,i)
$$
Working backwards, we define \$a(0,n) = 1\$ and \$a(-1,n) = 0\$ for all \$n\$. These definitions will simplify our base case.
### The code
We define a function `m(t)` that returns the first 20 elements of the sequence at tier `t`. If `t` is nonnegative, we use the recursive formula above; if `t` is `-1`, we return an empty list. The empty list works as a base case because the result of each recursive call is sliced (`[:n]`) and then summed. Slicing an empty list gives an empty list, and summing an empty list gives `0`. That's exactly the result we want, since tier \$-1\$ should behave like a constant sequence of all \$0\$'s.
```
m=lambda t: # Define a function m(t):
[ ] # List comprehension
for n in range( ) # for each n from 0 up to but not including...
~n and 20 # 0 if n is -1, else 20:
1+sum( ) # a(t,n) = 1 + sum of
[:n] # the first n elements of
m(t-1) # the previous tier (calculated recursively)
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~34~~ 32 bytes
*-2 bytes thanks to Jo King*
```
{(@,{[\+] 1,|.[^19]}...*)[$_+1]}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WsNBpzo6RjtWwVCnRi86ztAytlZPT09LM1olXtswtvZ/cWKlQpqGSrymQlp@EVCRsY6pjqGx9X8A "Perl 6 – Try It Online")
### Explanation
```
{ } # Anonymous block
, ...* # Construct infinite sequence of sequences
@ # Start with empty array
{ } # Compute next element as
[\+] # cumulative sum of
1, # one followed by
|.[^19] # first 19 elements of previous sequence
( )[$_+1] # Take (n+1)th element
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 62 bytes
```
f=lambda n:[t:=1]+[t:=t+n for n in(n and f(n-1)[:-1]or[0]*19)]
```
[Try it online!](https://tio.run/##FcqxCsMgFAXQvV9xR00M9NWlFfIl4mAJUiG9irjk600yneXUo/8K7bu2MdK6x/93i6Dz3a0S5ps@E6k0EJmKiNyQFBfR3i0SSvPPMMlHh3GnfCWIeRlrxLoHUFtmV0llrccJ "Python 3.8 (pre-release) – Try It Online")
---
## Explanation
```
f=lambda n: # funtion takes a single argument
[t:=1] # This evaluates to [1] and assigns 1 to t
# assignment expressions are a new feature of Python 3.8
+ # concatenated to
[ .... ] # list comprehension
# The list comprehesion works together with the
# assignment expression as a scan function:
[t := t+n for n in it]
# This calculates all partial sums of it
# (plus the initial value of t, which is 1 here)
# The list comprehension iterates
# over the first 19 entries of f(n-1)
# or over a list of zeros for n=0
for n in (n and f(n-1)[:-1] or [0]*19)
```
[Answer]
## R (63 47 bytes)
```
function(n,k=0:19)2^k*pbeta(.5,pmax(k-n,0),n+1)
```
[Online demo](https://tio.run/##K/pfbKP7P600L7kkMz9PI08n29bAytBS0yguW6sgKbUkUUPPVKcgN7FCI1s3T8dAUydP21Dzf7GGqeZ/AA). This uses the [regularised incomplete beta function](https://en.wikipedia.org/wiki/Beta_function#Incomplete_beta_function), which gives the cumulative distribution function of a binomial, and hence just needs a bit of scaling to give partial sums of rows of Pascal's triangle.
## Octave (66 46 bytes)
```
@(n,k=0:19)2.^k.*betainc(.5,max(k-n,1E-9),n+1)
```
[Online demo](https://tio.run/##y08uSSxL/V@sYKugp6f330EjTyfb1sDK0FLTSC8uW08rKbUkMTMvWUPPVCc3sUIjWzdPx9BV11JTJ0/bUPN/sYap5n8A). Exactly the same concept, but slightly uglier because `betainc`, unlike R's `pbeta`, requires the second and third arguments to be greater than zero.
Many thanks to [Giuseppe](/users/67312/giuseppe) for helping me to vectorise these, with significant savings.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 36 bytes
```
n->vector(20,i,i<n+2)*matpascal(19)~
```
[Try it online!](https://tio.run/##K0gsytRNL/ifpmD7P0/Xriw1uSS/SMPIQCdTJ9MmT9tIUys3saQgsTg5MUfD0FKz7n9iQUFOpUaegq6dQkFRZl4JkKkE4igppGnkaWrqKEQb6ygY6iiYAknjWM3/AA "Pari/GP – Try It Online")
A port of my Mathematica answer.
---
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 39 bytes
```
n->Vec(sum(i=1,n+1,(1/x-1)^-i)+O(x^21))
```
[Try it online!](https://tio.run/##K0gsytRNL/ifpmD7P0/XLiw1WaO4NFcj09ZQJ0/bUEfDUL9C11AzTjdTU9tfoyLOyFBT839iQUFOpUaegq6dQkFRZl4JkKkE4igppGnkaWrqKEQb6ygY6iiYAknjWM3/AA "Pari/GP – Try It Online")
---
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 42 bytes
```
Nest[FoldList[Plus,1,#]&,Range[21-#],#-1]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@98vtbgk2i0/J8UnE8gIyCkt1jHUUY5V0wlKzEtPjTYy1FWO1VHWNYxV@x9QlJlXEq2soGunkBatHBuroKag76BQbayjYKijYAokjWv/AwA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 59 bytes
```
.+
19*$(_,
```
Replace the input with 19 `1`s (in unary). (The 20th value is 0 because it always gets deleted by the first pass through the loop.)
```
"$+"{`
)`
```
Repeat the loop the original input number of times.
```
(.+),_*
_,$1
```
Remove the last element and prefix a `1`.
```
_+(?<=((_)|,)+)
$#2*
```
Calculate the cumulative sum.
```
_+
$.&
```
Convert to decimal.
[Try it online!](https://tio.run/##K0otycxLNPz/X0@by9BSS0UjXodLSUVbqTpBQ09bUydeiyteR8WQSzMhXlvD3sZWQyNes0ZHU1uTS0XZCCinzaWip/b/vzEA "Retina – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 58 bytes
```
t=>Array(20).fill(t).map(g=(t,i)=>i--*t?g(t,i)+g(t-1,i):1)
```
[Try it online!](https://tio.run/##TY1BCoMwFESvkoXg/6YJmmXbWHqGXsCgxkbSRGIoFvHsVu2mq5nHPJhevdVYBzNE5nzTrlquUZb3ENQHRI5cG2shIn@pAToJ8WRQloaxLN66g@gWrNjKucBV@0DAEUnyC3HkSsSelCKpvRu9bbn1HVQakhnSlDrkg2oeUYUIAhckyazB/b5gOp52bfrTdhZZZpDb1nXxSQtE3nvjtgGXCi/rFw "JavaScript (Node.js) – Try It Online")
It is trivial to write down following recursive formula based on the description in question
$$ g(t,i)=\begin{cases}
g(t,i-1)+g(t-1,i-1) & \text{if} \quad i\cdot t>0 \\
1 & \text{if} \quad i\cdot t=0 \\
\end{cases} $$
And you just need to generate an Array of 20 elements with \$[g(t,0)\dots g(t,19)]\$
[Answer]
# [Rust](https://www.rust-lang.org/), 135 bytes
```
fn t(m:u64)->Vec<u64>{let f=|y|(1..=y).fold(1,|a,n|a*n);(0..20).map(|i| (0..=u64::min(i,m)).fold(0,|a,x|a+f(i)/f(x)/f(i-x))).collect()}
```
used @alephalpha 's idea, like several others. there is no builtin factorial so that takes up at least 36 bytes, (plus dealing with negatives). no builtin choose, another 16 bytes. iterator->declared vector type, 20 bytes.. etc etc.
[Ungolfed at play.rust-lang.org](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=21078808eeb3a0d8adb8edd8f99110e6)
[Answer]
# [R](https://www.r-project.org/), ~~59~~ 49 bytes
```
f=function(n)`if`(n,Reduce(`+`,f(n-1),1,,T),1:20)
```
[Try it online!](https://tio.run/##K/r/P802rTQvuSQzP08jTzMhMy1BI08nKDWlNDlVI0E7QSdNI0/XUFPHUEcnBEhaGRlo/k/TMNDkStMw0vwPAA "R – Try It Online")
Recursively `Reduce` with `+`, `init=1` and `accumulation=TRUE` to avoid having to subset. Thanks to [Criminally Vulgar](https://codegolf.stackexchange.com/users/72784/criminallyvulgar) for suggesting the recursive approach!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~11~~ ~~9~~ 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
19ÝIÝδcO
```
1-indexed
-1 byte by porting [*@alephalpha*'s Mathematica answer](https://codegolf.stackexchange.com/a/180863/52210), so make sure to upvote him!!
[Try it online](https://tio.run/##yy9OTMpM/f/f0PLwXM/Dc89tSfb//98EAA) or [verify all test cases](https://tio.run/##yy9OTMpM/W9k4Opnr6TwqG2SgpL9f0PLw3P9Ds89tyXZ/7/OfwA).
**Explanation:**
```
19Ý # Push a list in the range [0, 19]
IÝ # Push a list in the range [0, input-integer]
δ # Apply on the two lists double-vectorized (as a table):
c # The binomial coefficient
O # And then sum each inner list
# (after which the resulting list is output implicitly)
```
---
**Old ~~11~~ 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) answer:**
```
20LIF.¥>¨
```
0-indexed
[Try it online](https://tio.run/##yy9OTMpM/f/fyMDH003v0FK7Qyv@/zcBAA) or [verify all test cases](https://tio.run/##yy9OTMpM/W9k4OZnr6TwqG2SgpI9kOfj56Z3aKndoRX/a/UObdX5DwA).
**Explanation:**
```
20L # Create a list in the range [1,20]
IF # Loop the input amount of times:
.¥ # Get the cumulative sum of the current list with 0 prepended automatically
> # Increase each value in this list by 1
¨ # Remove the trailing 21th item from the list
# (after the loop, the result-list is output implicitly)
```
[Answer]
# Ruby, 74 bytes
`a=->b{c=[1];d=0;b==1?c=(1..20).to_a: 19.times{c<<c[d]+(a[b-1])[d];d+=1};c}`
Ungolfed version:
```
def seq num
ary = [1]
index = 0
if num == 1
ary = (1..20).to_a
else
19.times{ary << ary[index]+seq(num-1)[index]; index+=1}
end
return ary
end
```
Quite resource-intensive--the online version can't calculate the 13th metasequence.
[Try it online](https://rextester.com/NGR10964)
[Answer]
# JavaScript (ES6), ~~68~~ 67 bytes
```
f=(n,a=[...f+f])=>n--?f(n,[s=1,...a.map(x=>s-=~--x)]):a.slice(0,20)
```
[Try it online!](https://tio.run/##Dc7LCsIwEIXhvU8xC6EZTIamInghdeUTuCwFh9rUSk1KE6Qg@uo1i58D3@o8@c2hmfoxKufv7bJYI5xkUxGR3dgaTemUOtuEVTBaJmZ68ShmUwZlfkrNWOORKQx904pcFjkup0pL2ErYSdBp9D51kFDkKV2T9dOFm4dwYMoVQONd8ENLg@/ELRmsP46iv8apd53QOdLI92vkKYoCv0e4wQbSH6Sn753IZIa4wuUP "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), 63 bytes
NB: this version works for \$n\le20\$.
```
f=(n,a=[...Array(20-n)])=>n--?f(n,[s=1,...a.map(x=>s+=x||1)]):a
```
[Try it online!](https://tio.run/##DY1BCsIwEADvvmIPQhNMFmPxUknFgy/wWASX1taWuilJkIr69prrzMAM9KJQ@36Kml1zX5bWClZkK0Q8eU9vsdtqlldpS9b62CZZBWtU0oRPmsRsy7Cx8/drUlTQcqiMglzBXoHJr9g6f6b6IRhsuQKoHQc33nF0nbglBusPY3SX6HvuhNlKnKi5RPJR7OSvgBtsID0lDq5nkalMypVc/g "JavaScript (Node.js) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 24 bytes
```
<:(1+/\@,])^:[(1+i.20)"_
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/baw0DLX1Yxx0YjXjrKKB7Ew9IwNNpfj/mlypyRn5CmkKhjCGMVzE@D8A "J – Try It Online")
NOTE: Turns out this is a translation of dzaima's APL answer, though I actually didn't notice it before writing this.
## explanation
```
<: (1 +/\@, ])^:[ (1+i.20)"_
<: NB. input minus 1 (left input)
(1+i.20)"_ NB. 1..20 (right input)
( )^:[ NB. apply verb in parens
NB. "left input" times
(1 , ]) NB. prepend 1 to right input
( +/\@ ) NB. and take scan sum
```
[Answer]
# Ruby, 49 bytes
```
f=->n{n<1?[1]*20:[o=1]+f[n-1][0,19].map{|x|o+=x}}
```
Recursive definition: Tier 0 is `1,1,1,1...` and each subsequent tier is 1 followed by a sequence whose first differences are the previous tier. Annoyingly this would give me 21 values if I didn't explicitly slice out the first 20; seems like there should be a way to shorten this by avoiding that.
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 120 bytes
```
n=>{for(long i=-1,h=0,m=0;++i<20;Print(i<1?1:h))for(m=h=0;m<=n;)h+=f(i)/(f(m)*f(i-m++));long f(long a)=>a>1?a*f(a-1):1;}
```
[Try it online!](https://tio.run/##JY1BDsIgEEWv4pKREqHLDkPjDbwCISKTCE0Ku8azI9XdT97L@6GqULnfQ@OtWC7NtWdt1Au5I267eG/ldWFSZkqkp0wapWQ7a3zsQxZszWqWBHC6mYaD2VJBSJKiYLiJKDJcx1RZSgD89eI/64Gcd2b1g3tlYDH46Xj@i1kD9i8 "C# (Visual C# Interactive Compiler) – Try It Online")
Based off of alephalpha's formula.
[Answer]
# Perl 5, 48 bytes
```
$x=1,@A=(1,map$x+=$_,@A[0..18])for 0..$_;$_="@A"
```
[TIO](https://tio.run/##K0gtyjH9n1vp4Gj9X6XC1lDHwdFWw1AnN7FApULbViUeyI820NMztIjVTMsvUgAyVeKtVeJtlRwclf7/N@Yy5DLlMjT@l19QkpmfV/xftyAHAA)
[Answer]
## R (60 59 bytes)
```
function(n)Reduce(function(p,q)2*p-choose(q-1,n),1:19,1,,1)
```
[Online demo](https://tio.run/##K/pfbKP7P600L7kkMz9PI08zKDWlNDlVAy5SoFOoaaRVoJuckZ9fnKpRqGuok6epY2hlaKljqKNjqPm/WMNU8z8A)
Straightforward implementation of the observation
>
> T(n,k) = 2 T(n-1,k) - binomial(n-1,k). - M. F. Hasler, May 30 2010
>
>
>
from OEIS [A008949](//oeis.org/A008949). The arguments to `Reduce` are the function (obviously), the array over which to map, the starting value, a falsy value (to fold from the left rather than the right), and a truthy value to accumulate the intermediate results in an array.
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), 17 bytes
-1 byte thanks to ngn (switching from 0-indexed to 1-indexed)
```
{x(+\1,19#)/20#1}
```
[Try it online!](https://tio.run/##y9bNz/7/P82qukJDO8ZQx9BSWVPfyEDZsPZ/mrqhtqLpfwA "K (oK) – Try It Online")
1-indexed
# [K (oK)](https://github.com/JohnEarnest/ok), 18 bytes
```
{x(+\1,19#)/1+!20}
```
[Try it online!](https://tio.run/##y9bNz/7/P82qukJDO8ZQx9BSWVPfUFvRyKD2f5q6oul/AA "K (oK) – Try It Online")
0-indexed
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
20RṖ1;ÄƲ⁸¡
```
[Try it online!](https://tio.run/##AR0A4v9qZWxsef//MjBS4bmWMTvDhMay4oG4wqH///8xOQ "Jelly – Try It Online")
0-indexed.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 15 bytes
0-indexed; replace `h` with `p` for 1-indexed.
```
ÈîXi1 å+}gNh20õ
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=yO5YaTEg5St9Z05oMjD1&input=Mg==)
[Answer]
## CJam (20 bytes)
```
1aK*{1\{1$+}/;]}q~*p
```
[Online demo](http://cjam.aditsu.net/#code=1aK*%7B1%5C%7B1%24%2B%7D%2F%3B%5D%7Dq~*p&input=5). This is a program which takes input from stdin and prints to stdout; for the same score an anonymous block (function) can be obtained as
```
{1aK*{1\{1$+}/;]}@*}
```
### Dissection
This applies the definition literally:
```
1aK* e# Start with an array of 20 1s
{ e# Loop:
1\ e# Push a 1 before the current list
{1$+}/ e# Form partial sums (including that bonus 1)
;] e# Ditch the last and gather in an array (of length 20)
}
q~* e# Take input and repeat the loop that many times
p e# Pretty print
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `R`, 7 bytes
```
20⁰(ÞR›
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJSIiwiIiwiMjDigbAow55S4oC6IiwiIiwiNCJd)
0-indexed.
## How?
```
20⁰(ÞR›
20 # Push number 20
⁰( # Loop input times
ÞR # Take the cumulative sum of list (20, R flag makes this a [1, 20] range), remove last item, and prepend 0. Short for ¦Ṫ0p
› # Increment (implicit vectorization)
```
# [Vyxal](https://github.com/Vyxal/Vyxal) `RM`, 7 bytes
```
19ƛ⁰ʀƈ∑
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJSTSIsIiIsIjE5xpvigbDKgMaI4oiRIiwiIiwiNCJd)
1-indexed.
## How?
```
19ƛ⁰ʀƈ∑
19 # Push the number 19
ƛ # Map, R and M flags make this be a [0, 19] range
⁰ʀ # Inclusive zero range of input
ƈ # Binomial coefficient, implicit vectorization
∑ # Sum these binomimal coefficients
```
] |
[Question]
[
**This question already has answers here**:
[Images with all colors](/questions/22144/images-with-all-colors)
(50 answers)
Closed 3 years ago.
Challenge:
Write a program that outputs a graphic file 1920 pixels wide by 1080 pixels high. Every one of the 2,073,600 pixels within the graphic must be a unique colour and no colour values should be repeated. The colours should be specified in RGB and start at 0,0,0 and count upwards in sequence towards 255,255,255. You'll find a 1920 x 1080 pixel image will contain lots of blacks, blues and greens only.
For example, (a smaller cut down version). If the height was set to 5 and the width was set to 5 a 25 pixel square graphic would be output and each pixel would be a unique colour. The RGB colour array would look like this:
```
Array (
[0] => Array
(
[0] => 0
[1] => 0
[2] => 0
)
[1] => Array
(
[0] => 0
[1] => 0
[2] => 1
)
[2] => Array
(
[0] => 0
[1] => 0
[2] => 2
)
[3] => Array
(
[0] => 0
[1] => 0
[2] => 3
)
[4] => Array
(
[0] => 0
[1] => 0
[2] => 4
)
[5] => Array
(
[0] => 0
[1] => 0
[2] => 5
)
[6] => Array
(
[0] => 0
[1] => 0
[2] => 6
)
[7] => Array
(
[0] => 0
[1] => 0
[2] => 7
)
[8] => Array
(
[0] => 0
[1] => 0
[2] => 8
)
[9] => Array
(
[0] => 0
[1] => 0
[2] => 9
)
[10] => Array
(
[0] => 0
[1] => 0
[2] => 10
)
[11] => Array
(
[0] => 0
[1] => 0
[2] => 11
)
[12] => Array
(
[0] => 0
[1] => 0
[2] => 12
)
[13] => Array
(
[0] => 0
[1] => 0
[2] => 13
)
[14] => Array
(
[0] => 0
[1] => 0
[2] => 14
)
[15] => Array
(
[0] => 0
[1] => 0
[2] => 15
)
[16] => Array
(
[0] => 0
[1] => 0
[2] => 16
)
[17] => Array
(
[0] => 0
[1] => 0
[2] => 17
)
[18] => Array
(
[0] => 0
[1] => 0
[2] => 18
)
[19] => Array
(
[0] => 0
[1] => 0
[2] => 19
)
[20] => Array
(
[0] => 0
[1] => 0
[2] => 20
)
[21] => Array
(
[0] => 0
[1] => 0
[2] => 21
)
[22] => Array
(
[0] => 0
[1] => 0
[2] => 22
)
[23] => Array
(
[0] => 0
[1] => 0
[2] => 23
)
[24] => Array
(
[0] => 0
[1] => 0
[2] => 24
)
)
```
Rules:
* Any programming language can be used to generate the image.
* The answer with the most upvotes wins.
* Colours must only be used once.
* Pixel in position 0,0 must start with colour 0,0,0
* Colours must fall within the true color 24 bit range.
* Image must be 1920 x 1080 pixels in size.
* Colours must be in RGB format.
* Using a library to output the image is ok.
* Output must be in the format of a graphic file e.g. output.png
* Output as text which represents the colour values doesn't count, the code must output a graphic file.
* File size of the output image doesn't matter.
* You must be able to view the output by opening it as a graphic in the chrome web browser.
I would be impressed if you mange to do this with really short code, your program also outputs the time in elapsed seconds taken to generate the image embedded within the image itself overlaid on the sequential pixels, your program outputs the image within 10 seconds. I would be really impressed if your program outputs the image within 1 second.
[Answer]
## Python - 660+ bytes
### Incremental Version

Full Size: <http://www.pictureshack.net/images/57626_all_colors.png> (4.52MB)
This is an image based on a [Julia Set](http://en.wikipedia.org/wiki/Julia_set) fractal. Each color is added to the image incrementally, although there is a substantial amount of pre-calculation.
---
### Luminosity Version

Full size: <http://www.pictureshack.net/images/95389_all_colors4.png> (5.24MB)
I've added an option to iterate each color by luminosity, rather than by index. This doesn't qualify as "counting up" from zero, but this seems to be a lax requirement. It's interesting that these two orderings expose completely different structures in the image. To use this, set the `use_luminosity` flag to `True`.
---
### Source
*Requires [PIL](http://www.pythonware.com/products/pil/).*
**Be warned**: this will take several minutes to execute. Using [PyPy](http://pypy.org/download.html) with [Pillow](http://pypi.python.org/pypi/Pillow/) runs in about one fifth the time of CPython with PIL, so I would recommend that, if possible.
```
from PIL import Image, ImageDraw
use_luminosity = True
dim = (1920,1080)
img = Image.new('RGB', dim)
draw = ImageDraw.Draw(img)
xstart = -.776707
ystart = -.134663
a = []
xd = 1.6 / 8192 / dim[0]
yd = 0.9 / 8192 / dim[1]
for x in range(dim[0]):
print x
for y in range(dim[1]):
z = d = complex(xstart + x*xd, ystart + y*yd)
c = 0
while abs(z) < 2 and c < 5000:
z = z*z + d
c += 1
a += [(c, -abs(z), x, y)]
a = a[1:]
a.sort(reverse = True)
t = [(i>>16, 255&i>>8, 255&i) for i in range(1, dim[0]*dim[1])]
if use_luminosity:
t.sort(key = lambda c: c[0]*3 + c[1]*10 + c[2], reverse = True)
r = 0
for c,d,x,y in a:
draw.point((x,y), t[r])
r += 1
img.show()
```
***Edit**: updated so that `#000000` is at the upper-left, as specified.*
***Edit**: added a flag to iterate colors by luminosity.*
***Edit**: switched to native complex calculations, and integer luminosity weights, which are slightly faster.*
---
Solutions I worked on before the primary criterion became [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'")
## PHP - 161 bytes
```
<?header('Content-type: image/bmp');
ob_start();
echo'BM'.pack('I5S2',0,0,26,12,70780800,1,24);
for(;$i=($i-256)%2073601;)echo pack('CS',~$i,~$i>>8);
ob_end_flush();
```
This is going for fastest output possible. No library is used, just a pre-computed header, and direct byte output. Runs in less than 2s on my comp. By incrementing by *256* rather than *1*, it produces a pseudo-gradient effect, with no real computation needed. The only downfall is that (*0, 0*) is not black, but the result looks a lot nicer.
`ob_start();` and `ob_end_flush();` aren't strictly necessary, but buffering the output makes it run a lot faster.

Other interesting increments include:
17: <https://i.stack.imgur.com/ieyyZ.png>
103: <https://i.stack.imgur.com/WD2wa.png>
326: <https://i.stack.imgur.com/c4DSF.png>
557: <https://i.stack.imgur.com/eTTWE.png>
943: <https://i.stack.imgur.com/7rrmR.png>
2125: <https://i.stack.imgur.com/Ct1kM.png>
And many others. Although, most patterns that look like anything resemble stripes of some sort
---
## PHP - 105 bytes
```
<?=BM.pack(I5S2,header('Content-type:'),0,26,12,70780800,1,24);
for(;$i<2073600;)echo pack(CS,$i,$i++>>8);
```
Reckless disregard version.
* Given a broken `Content-type` header, Chrome will do its best to figure out what it was sent. In this case, it correctly identifies it as `image/bmp`. The lastest versions of FireFox and IE are also able to fix the broken header.
* The barewords `BM`, `I5S2`, and `CS` will generate a `NOTICE` error. To prevent corruption of the image, error reporting in `php.ini` will need to be set to prevent this (e.g. `error_reporting = E_ALL & ~E_NOTICE`).
* No output buffering. The image is constructed 3 bytes at a time, which is noticeably slower.
* The point (*0, 0*) is considered to be the lower left, rather than upper left.

---
## PHP-CLI - 83 bytes
```
<?=BM.pack(I5S2,0,0,26,12,70780800,1,24);
for(;$i<2073600;)echo pack(CS,$i,$i++>>8);
```
Run directly from the command line and piped to a file (e.g. `$ php all-colors.php > out.bmp`), no `Content-type` header is necessary. The resulting file is identical to the 105 byte version, and can be viewed in Chrome.
[Answer]
# C with the GD graphics library (err, about 2.5 KB?)
The rules didn't prohibit modifying an existing image. I made a program to replace all of an image's pixels with sequential RGB values from `#000000` to `#1fa3ff`, and I'm quite pleased with the results. Here's what it produced from from [a photo posted to Flickr](http://www.flickr.com/photos/carianoff/4138045089) by Michael Carian ([cc-by-sa 2.0](http://creativecommons.org/licenses/by-sa/2.0/deed.en)):

(The raw output image is [rather large (5.6 MB)](http://www.pictureshack.net/images/33526_test.png))
Here's a close-up of the top left corner (scaled up 400%):

The processing time is about 3 seconds for an image of this size:
```
$ time ./a.out foodface.png outfile.png
File accepted; 1920x1080 pixels
Saving...
Finished
real 0m3.251s
user 0m2.392s
sys 0m0.169s
```
and yes, all the pixels are different colours:
```
$ identify -format %k outfile.png
2073600
```
(`identify` is an ImageMagick utility; the `-format %k` option counts the number of unique colours in an image)
Here's the source code:
```
#include <stdio.h>
#include <stdlib.h>
#include <gd.h>
#define FIRST_PIXEL_MUST_BE_BLACK 1
#define luminance(rgb) (((rgb>>16)&0xff)*77+((rgb>>8)&0xff)*150+(rgb&0xff)*29)
typedef struct { int lum; int rgb; } pal; /* Colour palette */
typedef struct { int lum; int x; int y; } pix; /* Pixel list */
/* Callback function for qsort */
int pcomp(const void *a, const void *b) {
return ((pal *)(a))->lum-((pal *)(b))->lum;
}
int main(int argv, char *argc[]) {
FILE *infile,*outfile;
gdImagePtr img;
int img_width;
int img_height;
int npixels;
int x,y,i;
int rgb,colour_ref,c;
pal *palette;
pix *pixels;
if (argv!=3) return printf("Usage: %s <source> <destination>\n",argc[0]);
if (!(infile=fopen(argc[1],"r"))) {
return printf("Can't open source file <%s>\n",argc[1]);
}
if (!(img=gdImageCreateFromPng(infile))) {
return printf("Bad PNG file <%s>\n",argc[1]);
}
fclose(infile);
img_width=img->sx;
img_height=img->sy;
npixels = img_width * img_height;
printf("File accepted; %dx%d pixels\n",img_width,img_height);
/* Allocate storage for palette and pixel data */
palette = malloc(npixels * sizeof(pal));
if (!palette) return printf("Out of memory\n");
pixels = malloc(npixels * sizeof(pix));
if (!pixels) return printf("Out of memory\n");
/* Create palette and sort by luminance */
for (i=0; i<npixels; i++) {
palette[i].rgb=i;
palette[i].lum=luminance(i);
}
qsort(palette,npixels,sizeof(pal),pcomp);
/* Sort image pixels by luminance */
#if FIRST_PIXEL_MUST_BE_BLACK == 1
colour_ref = gdImageColorAllocate(img,0,0,0);
gdImageSetPixel(img,0,0,colour_ref);
#endif
for (x=y=i=0;i<npixels;i++) {
rgb = gdImageGetTrueColorPixel(img,x,y);
pixels[i].x=x;
pixels[i].y=y;
pixels[i].lum=luminance(rgb);
if (!(x=++x%img_width)) y++;
}
#if FIRST_PIXEL_MUST_BE_BLACK == 1
qsort(pixels+1,npixels-1,sizeof(pix),pcomp);
#else
qsort(pixels,npixels,sizeof(pix),pcomp);
#endif
/* Now use the palette to redraw all the pixels */
for (i=0;i<npixels;i++) {
c = palette[i].rgb;
colour_ref = gdImageColorAllocate(img,c>>16,(c>>8)&0xff,c&0xff);
gdImageSetPixel(img,pixels[i].x,pixels[i].y,colour_ref);
}
printf("Saving...\n");
if (!(outfile=fopen(argc[2],"w"))) {
return printf("Can't open <%s> for writing\n",argc[2]);
}
gdImagePng(img,outfile);
fclose(outfile);
gdImageDestroy(img);
printf("Finished\n");
return 0;
}
```
[Answer]
# C++, 750 bytes

[A Full resolution PNG (5.1MB)](http://lags.leetcode.net/Mandelbrot_HD.png)
The code creates a collection of all integers from 0-1080\*1920, then sorts them by overall brightness. It then creates a Mandelbrot set, and sorts the positions based on their escape iteration and value. Then it walks through both sets, assigning colors in order from dark to bright to the Mandelbrot values smallest to largest. Finally, it writes a 32 bit per pixel BMP image to the output filename specified as a command line parameter.
```
#include <windows.h>
#include <vector>
#include <algorithm>
#define X _complex
#define U int
#define S(j,g)std::sort(j.begin(),j.end(),g);
U w=1920,h=1080;
WORD q[27]={'MB',36918,126,0,0,54,0,40,0,w,0,h,0,1,32,0,0,36864,126};
#define V(a,b)((a>>b)&255)
#define L(z)V(z,16)*.3+V(z,8)*.6+V(z,0)*.1
#define F for(c=0;c<w*h;c++)
U C(U a,U b){return L(a)<L(b);}
U M(X a,X b){return a.x<b.x;}
U main(U c,char**v){
std::vector<U>l;
std::vector<X>D;
F l.push_back(c);
U*i=new U[c];
DWORD p;
F{float r=0,i=0,R;p=0;
for(;p<w&&r*r+i*i<4;p++){R=r*r-i*i;i=2*r*i+(c/w-h/2)/400.;r=R+(c%w-w/2)/400.;}
X d={-p-r*r-i*i,c};
D.push_back(d);}
S(l,C)
S(D,M)
F i[(U)D[c].y]=l[c];
void*f=CreateFileA(v[1],4<<28,0,0,2,0,0);
WriteFile(f,q,54,&p,0);
WriteFile(f,i,w*h*4,&p,0);}
```
The code isn't fully golfed, but it's not going to get too much smaller.
[Answer]
# C - 854 bytes (when squeezed)
I originally had something with cyan, magenta and yellow corners and smooth gradations of colors which looked really nice, but it didn't meet the specs.
The following fulfills the specs: uses the "first" 2,073,600 colors, no repetitions, and black in the top left corner.

How it works is kind of cool. It builds an array with the colors, then sorts vertically and horizontally by different criteria a couple of times. The end result are pleasing transitions between blue & green and between dark & light. It takes about 1.5 seconds to run. Compile using: `gcc -o many many.c -lm` and run using: `./many > many.ppm`
```
#include <stdlib.h>
#include <stdio.h>
#define W 1920
#define H 1080
typedef struct {unsigned char r, g, b;} RGB;
int S1(const void *a, const void *b)
{
const RGB *p = a, *q = b;
int result = 0;
if (!result)
result = (p->b + p->g * 6 + p->r * 3) - (q->b + q->g * 6 + q->r * 3);
return result;
}
int S2(const void *a, const void *b)
{
const RGB *p = a, *q = b;
int result = 0;
if (!result)
result = p->b - q->b;
if (!result)
result = p->g - q->g;
if (!result)
result = q->r - p->r;
return result;
}
int main()
{
int i, j, n;
RGB *rgb = malloc(sizeof(RGB) * W * H);
RGB c[H];
for (i = 0; i < W * H; i++)
{
rgb[i].b = i & 0xff;
rgb[i].g = (i >> 8) & 0xff;
rgb[i].r = (i >> 16) & 0xff;
}
qsort(rgb, H * W, sizeof(RGB), S1);
for (n = 0; n < 2; n++)
{
for (i = 0; i < W; i++)
{
for (j = 0; j < H; j++)
c[j] = rgb[j * W + i];
qsort(c, H, sizeof(RGB), S2);
for (j = 0; j < H; j++)
rgb[j * W + i] = c[j];
}
for (i = 0; i < W * H; i += W)
qsort(rgb + i, W, sizeof(RGB), S1);
}
printf("P6 %d %d 255\n", W, H);
fwrite(rgb, sizeof(RGB), W * H, stdout);
free(rgb);
return 0;
}
```
FYI, this was the original image...

And for those interested in the code used to generate this image:
```
#include <stdio.h>
#include <math.h>
int main(int argc, char **argv)
{
int x, y;
int w = (argc > 1)? atoi(argv[1]): 1920;
int h = (argc > 2)? atoi(argv[2]): 1080;
double l = hypot(w, h);
fprintf(stdout, "P6 %d %d 255\n", w, h);
for (y = 0; y < h; y++)
{
for (x = 0; x < w; x++)
{
unsigned char v[3];
v[0] = floor(256 * hypot(0 - x, h - y) / l);
v[1] = floor(256 * hypot(w - x, h - y) / l);
v[2] = floor(256 * hypot(w - x, 0 - y) / l);
fwrite(v, sizeof(unsigned char), 3, stdout);
}
}
return 0;
}
```
[Answer]
## Ruby, 109
```
require'chunky_png';i=ChunkyPNG::Image.new 1920,1080
i.area.times{|v|i[*(v.divmod(1080))]=v<<8|255};i.save ?i
```
EDIT: I should note that I submitted this when the question was still tagged [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), before it became a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'") so I was going for short code. This is not very imaginative but I believe it to be a valid submission.
Color values range from `00 00 00` to `1f a3 ff`, incrementing by `1`, so the lack of `red` in the result is not surprising.

For the cost of adding 1 character to the source code length (replace `<<8` with `<<11`), the following output can be had. This covers more range of the spectrum at the cost of `blue` resolution. It increments through RGB space at eight times the rate. Color values range from `00 00 00` to `fd 1f f8`.

[Answer]
# Racket
Never used racket object oriented programming before (message passing) so I'm not sure this is optimal, but it seems to get the job done.
```
#lang racket
(require racket/draw)
(let* ((x 1920) (y 1080) (b 256) (bb (* b b)) (pic (make-object bitmap% x y)))
(let loop ((c 0) (v 0))
(when (> (* x y) c)
(send pic set-argb-pixels (modulo c x) ; x
(quotient c x) ; y
1 ; width
1 ; height
(list->bytes
(list 0 ; alpha
(modulo v b) ; red
(quotient v bb) ; green
(modulo (quotient v b) b)))) ; blue
(loop (+ c 1) (+ v 8))))
(send pic save-file "image.png" 'png))
```

By not using the 3 first bits in the red channel I get all three colors in my result image.
# Brainfuck
The code prints out a 24bit BMP image to STDOUT for 8 bit cell BF interpreters. It creates the same image as the Racket version. It's based on the pnm version.
```
>-------->>+>----->-------->+++++++>>---->------>++>--->>++++[-<+++
+>]<[-<+++++<++++<++<+<++++++++<<+++++++++++++<<<<++>>>>>>>>>>>]<<[
.[-]>]++[-<++++>]<[->.<]<<.[-]...<.[-]...<[.[-]<].<.[-].<+[>>>>+<.<
<.>.>++++++++[>-]>[<<+[>>-]>>[<<<+[>>>-]>>>[<<<<->>>>>>>]<]<]<<<<<]
```
Ubuntu ships with `bf` that has 8 bit cells:
```
bf img.bf > image.bmp
```
Old version that violates being able to open from Chrome. It makes a .pnm file that are compatible with most image viewers.
```
>------>+++++>+++++>++>------>>-------->>+>------>>++>------->+>--
---->++++++>>>++++[-<++++>]<[-<+++++<+++<+<+++<++++<+++<+++<+<+++<
+++<++++<+++<+<+++<+++<+++<+>>>>>>>>>>>>>>>>>]<[.[-]<]+[>>>>+<.<<.
>.>++++++++[>-]>[<<+[>>-]>>[<<<+[>>>-]>>>[<<<<->>>>>>>]<]<]<<<<<]
```
[Answer]
Updated, first version did not have all colors unique in 24-bit space:
**Mathematica: 110**
```
x = 1920; y = 1080; Image[
ParallelTable[
List @@ ColorConvert[Hue[h, 1, (b + h)/2], "RGB"], {h, 0, 1 - 1/y,
1/y}, {b, 0, 1 - 1/x, 1/x}]]
```

Rules verification:
```
list = ParallelTable[
List @@ ColorConvert[Hue[h, 1, (b + h)/2], "RGB"], {h, 0, 1 - 1/y,
1/y}, {b, 0, 1 - 1/x, 1/x}]
```
First pixel is black:
```
list[[1, 1]]
```
>
>
> ```
> {0., 0., 0.}
>
> ```
>
>
All colors are unique:
```
id = ImageData[Image[list], "Bit16"]]
Length[DeleteDuplicates[Flatten[id, 1]]] == 1920*1080
```
>
>
> ```
> True
>
> ```
>
>
---
~~**Mathematica: 146**~~
```
x = 1920; Image[
Partition[
ParallelTable[
List @@ ColorConvert[Hue[c, 1, c^.01], "RGB"], {c, 0, 1, 1/(
x*1080)}], x]]
```

Takes 14.778 seconds.
Rules verification:
```
list = Partition[
ParallelTable[
List @@ ColorConvert[Hue[c, 1, c^.01], "RGB"], {c, 0, 1, 1/(
x*1080)}], x];
```
First pixel is black:
```
list[[1, 1]]
```
>
>
> ```
> {0., 0., 0.}
>
> ```
>
>
All colors are unique:
```
Length[DeleteDuplicates[Flatten[list, 1]]] == 1920*1080
```
>
>
> ```
> True
>
> ```
>
>
>
[Answer]
# Python - 104
```
from PIL import Image
a=list(range(2073600))
i=Image.new("RGB",(1920,1080))
i.putdata(a)
i.save("o.png")
```
This is the version, which would have been for the code-golf challenge. As it is just increasing the value from 0 up to 2073599, it contains only unique colors.

## Python - 110
As I didn't like the above version (the colorrange isn't fully used), I tried something like the following:
```
from PIL import Image
a=list(range(0,2073600*8,8))
i=Image.new("RGB",(1920,1080))
i.putdata(a)
i.save("o.png")
```

## Python - 122
Another extension to the above:
```
from PIL import Image
a=[(i<<3,i)[i%2]for i in range(2073600)]
i=Image.new("RGB",(1920,1080))
i.putdata(a)
i.save("o.png")
```

[Answer]
**Processing, 301**
This is not an attempt at the most terse solution, but it maintains all of the control to achieve the desired arrangement of colors. Yes, the colors are not consecutive, but that is no fun.

```
int w = 1920;
int h = 1080;
void setup(){
size(w, h);
int x = 0; int y = 0;
for(int i=0; i<w*h; i++){
stroke(
(i >> 0) & 0xFF,
(i >> 6) & 0xFF,
(i >> 3) & 0xFF
);
if (y % h == 0){
y = 0;
x++;
}
point(x, y);
y++;
}
save("unique.png");
}
```
[Answer]
## Visual Basic .NET, 273 bytes
```
Imports System.Drawing : Module Module1
Sub Main()
Dim b As New Bitmap(1920, 1080) : For i As Integer = 0 To 2073599 : Dim x = 0 : b.SetPixel(Math.DivRem(i, 1080, x), x, Color.FromArgb(i + &HFF000000)) : Next : b.Save("output.png")
End Sub
End Module
```
This outputs a 5.61 MB file:
[](https://web.archive.org/web/20160722043010/https://dl.dropboxusercontent.com/u/59472739/Programming/StackOverflow/Codegolf/Codegolf-2/output.png)
The code above is a compressed version of this more readable code. Spaces were removed to save bytes.
```
Imports System.Drawing
Module Module1
Sub Main()
Dim b As New Bitmap(1920, 1080)
For i As Integer = 0 To 2073599
Dim x = 0
b.SetPixel(Math.DivRem(i, 1080, x), x, Color.FromArgb(i + &HFF000000))
Next
b.Save("output.png")
End Sub
End Module
```
Link to the image: [http://µ.pw/k](http://%C2%B5.pw/k)
[Answer]
**ImageMagick - Convert** 119
Lets use the `convert` from the ImageMagick toolbox to create images. It runs in 0 seconds. It is golfed to 119 characters. I overlay two gradients (red-blue and black-white) convert them to HSL and back to RGB.
```
G=gradient;convert -size 900x900 $G:red-blue \( $G: -rotate 90 \) -compose CopyRed -resize 1920x1080\! -composite o.png
```

Examples of gradient overlay can be found in the [ImageMagick manual pages](http://www.imagemagick.org/Usage/compose/tables/).
[Answer]
**PHP, 507**

You will probably need to increase the amount of memory allocated to PHP in order to run. Uses GD. Takes around 9 seconds to generate the image.
```
$a=microtime(true);$c=1920;$d=1080;$e=$c*$d;$f=@imagecreatetruecolor($c,$d);$h=255;$j=2200000;$k=array();$l=1;for($m=0;$m<=$h;$m++){for($n=0;$n<=$h;$n++){for($o=0;$o<=$h;$o++){if($l<=$j){$k[]=array($m,$n,$o);$l++;}else{break;}}}}while($p<=$e){for($q=0;$q<=$c;$q++){for($s=0;$s<=$d;$s++){$t=imagecolorallocate($f,$k[$p][0],$k[$p][1],$k[$p][2]);imagesetpixel($f,$q,$s,$t);$p++;}}}$u=number_format((microtime(true)-$a),4).' seconds';imagestring($f,6,10,10,$u,$v);header('Content-Type: image/png');imagepng($f);
```
Link to the output image: <https://i.stack.imgur.com/AAKqW.png>
See it running on the web: <http://ben-paton.co.uk/portfolio/pixel.php?w=1920&h=1080>
[Answer]
# DELPHI/PASCAL (Version #1), 361 bytes
```
program P;
{$APPTYPE CONSOLE}
uses
System.SysUtils, Vcl.Imaging.pngimage,System.UITypes;
var a : TPNGObject; h,w: Integer; c : TColor;
begin
a :=TPNGObject.CreateBlank(COLOR_RGB, 16, 1920, 1080);
for h := 0 to 1020 do
for w := 0 to 1920 do
begin
a.Pixels[h,w]:= c ;
inc(c);
end;
a.SaveToFile('e:\t.png');
end.
```
[Answer]
# Tcl/Tk, 149
# ~~150~~
```
set p [image c photo -w 1920 -h 1080]
set y 0
time {set x 0
time {$p p [format #%06x [expr $y*1920+$x]] -t $x $y
incr x} 1920
incr y} 1080
$p w c.png
```
[](https://i.stack.imgur.com/5fkNm.png)
[Answer]
## Java 411 386+24 bytes
## Golfed
```
import java.awt.image.*;()->new BufferedImage(1920,1080,1){{long t=System.currentTimeMillis();int q=-1;for(int i=0;i<getWidth();i++)for(int j=0;j<getHeight();j++)setRGB(i,j,q++);java.io.File f=new java.io.File(System.getProperty("user.home"),"Desktop"+System.getProperty("file.separator")+(System.currentTimeMillis()-t)+".png");javax.imageio.ImageIO.write(this,"png",f);java.awt.Desktop.getDesktop().open(f);}}
```
## Ungolfed
```
import java.awt.image.*;
() -> new BufferedImage(1920, 1080, 1) {
{
long t = System.currentTimeMillis();
int q = -1;
for (int i = 0; i < getWidth(); i++)
for (int j = 0; j < getHeight(); j++)
setRGB(i, j, q++);
java.io.File f = new java.io.File(System.getProperty("user.home"),
"Desktop" + System.getProperty("file.separator")
+ (System.currentTimeMillis() - t) + ".png");
javax.imageio.ImageIO.write(this, "png", f);
java.awt.Desktop.getDesktop().open(f);
}
}
```
## Result

## Explanation
This is not my attempt at the shortest solution, but rather the most portable. Only left import for BufferedImage because the other's didn't save bytes. Rather than loading the Image into a JPanel and writing on it, I saved the time it takes from beginning until writing to disk as the filename. For me, this took this resulted in filenames of about ~110 ms, whereas the time from beginning until end usually took ~500ms. Lastly, it should be platform independent as I tested in both Windows and an Ubuntu VM and it worked (It writes the file to your Desktop). Had to have the return statement due to the Callable syntax garbage. Although I'm working on the work around, I doubt I'll find a better implementation on my own due to the saves from using l and w for my for loops. I'd say half a second for java isn't too bad. My original implementation opened directly to chrome using
```
(System.getProperty("os.name").toLowerCase().contains("win")) { try { Process
* p = Runtime.getRuntime() .exec(new String[] { "cmd", "/c", "start chrome " +
* f }); p.waitFor(); } catch (Exception e) { } } else if
* (System.getProperty("os.name").toLowerCase().contains("ix")) { try { Process
* p = Runtime.getRuntime().exec(new String[] { "google-chrome" + f }); } catch
```
But I believe it's still validated as it can still be opened by chrome, it just automatically opens to your default png viewer (version not tested on Unix based machines).
I'm aware of the byte saves possible but mainly have omitted them to qualify for bonuses. If requested I can upload shorter, platform specific examples. Thank you.
## Edit
Removed Unnecessary Try Catch block and ill formatted return statement to reduce ~30 bytes.
Removed `BufferedImage.TYPE_INT_RGB` because it's literally just 1.
] |
[Question]
[
The alternating factorial is an alternating sum of decreasing factorials. For example, we could calculate the alternating factorial of 4 as follows:
* First, calculate the factorials from 4 down to 1:
$$
4!\quad3!\quad2!\quad1!\quad = \\
4\cdot3\cdot2\cdot1\qquad3\cdot2\cdot1\qquad2\cdot1\qquad1\quad= \\
24\quad6\quad2\quad1
$$
* Next, insert alternating signs between the products, always starting with \$\;-\$.
$$
24-6+2-1 = \\
19
$$
So 19 is the alternating factorial of 4. Mathematically, the alternating factorial is defined as
$$
\large\operatorname{af}(n) = \sum\_{i=1}^n(-1)^{n-i}i!
$$
For example,
$$
\operatorname{af}(4)=(-1)^3\times1!+(-1)^2\times2!+(-1)^1\times3!+(-1)^0\times4!=19
$$
The alternating factorial can also be calculated by the recurrence relation
$$
\operatorname{af}(n) =
\begin{cases}
0, & \text{if $\;n=0$} \\
n!-\operatorname{af}(n-1), & \text{if $\;n>0$}
\end{cases}
$$
The sequence of alternating factorials is [OEIS A005165](https://oeis.org/A005165).
## Task
Given a non-negative integer as input, output its alternating factorial. You don't need to worry about values exceeding your language's integer limit. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the code with the fewest bytes (in each language) wins.
## Test cases
```
n af(n)
0 0
1 1
2 1
3 5
4 19
5 101
6 619
7 4421
8 35899
9 326981
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
R!ḅ-
```
A monadic Link that accepts a non-negative integer, \$n\$, and yields its alternating factorial.
**[Try it online!](https://tio.run/##ASUA2v9qZWxsef//UiHhuIUt/8W7wrUsw4dq4oCcID0@IOKAnSlZ//85 "Jelly – Try It Online")**
### How?
```
R!ḅ- - Link: n
R - range (n) -> [1, ..., n-1, n]
! - factorial -> [1!, ..., (n-1)!, n!]
- - -1
ḅ - convert from base -1 -> n! - (n-1)! + ... [+/-] 1!
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 20 bytes
```
AlternatingFactorial
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2ar8N8xpyS1KA/Iz0t3S0wuyS/KTMz5H1CUmVcSnRZtGRv7HwA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 6 bytes [SBCS](https://github.com/abrudz/SBCS)
```
¯1⊥∘!⍳
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=O7Te8FHX0kcdMxQf9W4GAA&f=Szu04lHvZksA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f)
[Answer]
# [Desmos](https://desmos.com/calculator), 28 bytes
```
f(k)=∑_{n=1}^k(-1)^{k-n}n!
```
[Try It On Desmos!](https://www.desmos.com/calculator/biwt3b1goj)
Yea, I really could not think of any golfier way than to just copy the formula provided in the question. Not the most creative answer out there but at least it's the golfiest in Desmos (at least it better be....).
[Answer]
# [><> (Fish)](https://esolangs.org/wiki/Fish), ~~53~~ 42 bytes
```
i:?vl1=?n-30.
:?v\:1$:@*$1-
1.\6
00.\~~$1-
```
[Try it](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiaTo/dmwxPT9uLTMwLlxuOj92XFw6MSQ6QCokMS1cbjEuXFw2XG4wMC5cXH5+JDEtIiwiaW5wdXQiOiI3Iiwic3RhY2siOiIiLCJzdGFja19mb3JtYXQiOiJudW1iZXJzIiwiaW5wdXRfZm9ybWF0IjoibnVtYmVycyJ9)
The bottom 3 lines calculate the factorial of a number and push it to the stack, the top line just subtracts the top 2 elements from the stack, and prints the top of the stack if there is just one.
After a number is printed, the `-` crashes and the program exits.
[](https://i.stack.imgur.com/b1oHS.png)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 20 bytes
```
Nest[++i!-#&,i=0,#]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73y@1uCRaWztTUVdZTSfT1kBHOVbtf0BRZl5JtLKuXZoDkFsXnJyYVxeUmJeeGm2gYxn7HwA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Python](https://www.python.org), 40 bytes
```
f=lambda n:n>1and~-n*f(n-1)+n*f(n-2)or n
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3NdJscxJzk1ISFfKs8uwME_NS6nTztNI08nQNNbUhDCPN_CKFPKh67TQQRyEzT6EoMS89VcPQQNOqoCgzr0RDSTXFSkE1RUlVI08HqE1TUxOiBWYVAA)
Port of @Arnauld's JS answer.
[Answer]
# JavaScript (ES6), 28 bytes
```
f=n=>n<2?n:n*f(n-2)+--n*f(n)
```
[Try it online!](https://tio.run/##HYsxDoMwEAR7XnEFhQ/LKFAGTL6CBThKhPaQQTSW3@5Aqpli5utOt0/hsx0GMi85ews7oG9feKLyCqZlbcxfOXsJCmTp0RGop@am1kyxIJoEu6xLvcpbjU6VEYmvtIz3mUbuipR/ "JavaScript (Node.js) – Try It Online")
This is based on the recurrence formula given on [OEIS](https://oeis.org/A005165) for \$n > 1\$:
$$a(n) = n\times a(n-2) + (n-1)\times a(n-1)$$
This alternate form accepts either Numbers or Bigints as input:
```
f=n=>n<2?n:n--*f(~-n)+n*f(n)
```
[Try it online!](https://tio.run/##HcsxDoMwEAXRnlNsQeHFMkKhCzi5ChbBCIT@IkBpLOfqhtC9YmZ2X7f327QeBvIZUvIW9oX28cYTxhRe/QxY4wI4edkUyFKFhkAt1Te0ZgoZUS/YZRnKRUbVOZUHRL7iPPzf2HGTxXQC "JavaScript (Node.js) – Try It Online")
[Answer]
# [Curry (PAKCS)](https://www.informatik.uni-kiel.de/%7Epakcs/), 48 bytes
```
f 0=1
f x|x>0=x*f(x-1)
g 0=0
g x|x>0=f(x)-g(x-1)
```
[Try it online!](https://tio.run/##Sy4tKqrULUjMTi7@/z9NwcDWkCtNoaKmws7AtkIrTaNC11CTKx0obAAkIcJAQU3ddLDM/9zEzDwFW4XcxAKFdIVoAwU9PQXL2P8A "Curry (PAKCS) – Try It Online")
My first answer in Curry.
I had to determine the factorial because I couldn’t find it in the standard library
[Answer]
# [R](https://www.r-project.org), ~~29~~ 31 bytes
*Edit: +2 bytes and complete change of approach to fix bug spotted by pajonk*
```
\(x)Reduce(`-`,gamma(x:1+1),,T)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGKxJyStMTkEtulpSVpuhb7YzQqNINSU0qTUzUSdBN00hNzcxM1KqwMtQ01dXRCNCGqthQnFhTkVGoYWhka6EANgEotWAChAQ)
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 6 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md "Thunno 2 Codepage")
```
RR€puḋ
```
(Thunno 2 isn't on ATO yet)
It seems that I forgot to add a "factorial" built-in to Thunno 2...
Port of Jonathan Allan's Jelly answer.
#### Explanation
```
RR€puḋ # Implicit input 5
R # Push the range [1..input] [1, 2, 3, 4, 5]
R # For each number in this, push its range [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]]
€p # Product of each inner list [1, 2, 6, 24, 120]
uḋ # Convert from base -1 101
# Implicit output
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 7 bytes
```
:Yp-1ZQ
```
[Try it online!](https://tio.run/##y00syfn/3yqyQNcwKvD/f1MA "MATL – Try It Online")
[Answer]
# [Oasis](https://github.com/Adriandmen/Oasis), 4 bytes
```
n!-0
```
[Try it online.](https://tio.run/##y08sziz@/z9PUdfg////lgA)
**Explanation:**
```
0 # Start with a(0)=0 (Oasis programs implicitly start with a(0)=1 unfortunately)
# And calculate every following a(n) by:
- # Subtracting
# the implicit previous term a(n-1)
n! # from n!
# (and output the a(implicit input-argument)'th term implicitly as result)
```
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), ~~5.5~~ 5 bytes (10 nibbles)
*Edit: -0.5 bytes (1 nibble) thanks to xigoi*
```
/.\,$`*,$-
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWq_T1YnRUErR0VHQhAlDxBesNuAy5jLiMuUy4TLnMuMwhwgA)
Port of [my R answer](https://codegolf.stackexchange.com/a/260148/95126).
```
/.\,$`/,$*-
. # map over
\ # reverse of
,$ # 1..input:
`* # product of
,$ # 1..each element
# (at this point we have list of
# factorials in reverse order);
/ # now, fold over this from right to left
- # by subtraction
```
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 64 bytes
```
{(({})[()]<({([{}]()({}))([{}]({}))}{}{}([{}])((){}))>)}{}({}<>)
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/v1pDo7pWM1pDM9ZGo1ojuro2VkMTJKIJYYNYtdVACOZqamhogkTsQGJAORs7zf//LQA "Brain-Flak – Try It Online")
This does not compute any factorials as intermediate results. Instead, it multiplies by successively smaller numbers and either adds or subtracts one. Sample calculation for the alternating factorial of 5:
```
0 *6 +1 = 1
1 *5 -1 = 4
4 *4 +1 = 17
17 *3 -1 = 50
50 *2 +1 = 101
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
R!_@ƒ0
```
[Try it online!](https://tio.run/##y0rNyan8/z9IMd7h2CSD/0d36xxuV3nUtMb9/39LAA "Jelly – Try It Online")
## How it works
```
R!_@ƒ0 - Main link. Takes n on the left
R - Range; [1, 2, ..., n]
! - Factorial; [1, 2, 6, ..., n!]
ƒ0 - Reduce by the following, beginning with 0:
_@ - y - x
```
For a list `[a, b, c, d, e]`, `_@ƒ0` calculates
```
((((0 _@ a) _@ b) _@ c) _@ d) _@ e
= e _ (d _ (c _ (b _ (a _ 0))))
= e - d + c - b + a - 0
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes
```
ɾ¡uβ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJ+IiwiIiwiyb7CoXXOsiIsIiIsIiEoXFxkKykgKyhcXGQrKVxuMCAgIDBcbjEgICAxXG4yICAgMVxuMyAgIDVcbjQgICAxOVxuNSAgIDEwMVxuNiAgIDYxOVxuNyAgIDQ0MjFcbjggICAzNTg5OVxuOSAgIDMyNjk4MSJd)
Port of the 4 byte jelly answer
## Explained
```
ɾ¡uβ
ɾ # range [1, n]
¡ # factorial of each
uβ # converted from base -1
```
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), 10 bytes
```
řĐ1~⇹^⇹!·Å
```
[Try it online!](https://tio.run/##K6gs@f//6MwjEwzrHrXvjANixUPbD7f@/28GAA "Pyt – Try It Online")
```
ř implicit input (n); řangify [1,2,...,n]
Đ Đuplicate
1~ -1
⇹ swap top two elements
^ -1^[1,2,3,...,n]
⇹ swap top two elements
! factorial [1!,2!,3!,...,n!]
· dot product
Å Åbsolute value; implicit print
```
Uses that fact that \$\text{af}(n)=\left|\sum\_{i=1}^n(-1)^i i!\right|\$
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 54 bytes
```
~(`.+
.+¶$$.($$'$&*
+`_(_(_+))
$$($.&$*$2$.1$*$1)
__
_
```
[Try it online!](https://tio.run/##DcW7DYAgFAXQ/s5xxQckL4L/CRwDLCxsLIy1YzmAi6E5xTm3az/WUCpZcrklq4f69yFVyJrGweckP28tSKEaOkZq@AsWKSGV0iAgokWHHgNGTJg/ "Retina – Try It Online") Link includes test cases. Explanation: Port of @Arnauld's JavaScript answer.
```
~(`
```
Run the output of the rest of the program on the original input.
```
.+
.+¶$$.($$'$&*
```
Convert the input to unary and replace it with a command that replaces the input with an expression that converts the literal unary string back to decimal. The unary string represents `f(n)` at this point.
```
+`_(_(_+))
$$($.&$*$2$.1$*$1)
```
For `n>2`, repeatedly apply the recurrence relation `f(n)=n*f(n-2)+(n-1)*f(n-1)` to the unary string. `n` and `(n-1)` are represented in decimal while `f(n-2)` and `f(n-1)` remain represented in unary for the next pass.
```
__
_
```
`f(2)=1` while `f(n)=n` for `n<2` which is already correct.
Example: if `n=7`, then the rest of the program produces the following output:
```
.+
$.($'$(7*$(5*$(3*_2*_)4*$(4*_3*$(3*_2*_)))6*$(6*$(4*_3*$(3*_2*_))5*$(5*$(3*_2*_)4*$(4*_3*$(3*_2*_)))))
```
Retina will evaluate the expression using big integers so the limit is the length of the generated expression which has to fit in memory.
Note that there's an extra `$'` in the final expression in case it is empty to work around a Retina bug whereby `$.()` crashes Retina when it has no elements, but it's fine if it has a non-zero number of empty elements.
The recurrence relation is not used for `f(2)` because that would invoke `f(0)` whose representation would be empty, but `*` defaults to a RHS of `_` i.e. `1`. It could be done by representing `f(n)` with `$(n)` except that this triggers the empty length bug, so it needs another 3 bytes for a second copy of the workaround, making it overall a byte longer:
```
.+
.+¶$$.($$'$&*
~)+`_(_(_*))
$.&$*$$($$'$2)$.1$*$$($1)
```
[Answer]
# Excel, 38 bytes
Defined Name `a`:
```
=LAMBDA(n,IF(n,FACT(n)-a(n-1),))
```
After which, within the worksheet:
```
=a(A1)
```
for an input in cell `A1`.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 4 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
õÊìJ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=9crsSg&input=NQ)
```
õÊìJ :Implicit input of integer U
õ :Range [1,U]
Ê :Factorials
ì :Convert from base
J :-1
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 11 bytes
```
0|-₁↰I&ḟ;I-
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/36BG91FT46O2DZ5qD3fMt/bU/f/f8n8UAA "Brachylog – Try It Online")
### Explanation
Uses the recurrence relation.
```
0 af(0) = 0
| Or
-₁↰I I = af(Input - 1)
&ḟ;I- Output = Input! - I
```
[Answer]
# [Julia 0.7](http://julialang.org/), 23 bytes
```
!n=n>0?prod(1:n)-!~-n:0
```
[Try it online!](https://tio.run/##yyrNyUw0//9fMc82z87AvqAoP0XD0CpPU1exTjfPyuC/g55CQVFmXklOnoaihoGVpabmfwA "Julia 0.7 – Try It Online")
Uses the recursive formula.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~17 16~~ 12 bytes
```
$* *\,\,aFDv
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuhZrVLQUtGJ0YnQS3VzKIEJQmcXRFrFQJgA)
Port of Jonathan Allan's Jelly answer.
*-4 thanks to @DLosc*
#### Explanation
```
$* *\,\,aFDv ; Input on command line
\,a ; Range from 1 to input
\, ; Range from 1 to each
$* * ; Product of each inner list
FDv ; From a list of digits in base -1
; Implicit output
```
Old:
```
({$*\,a}M\,a)FDv ; Input on command line
\,a ; Range from 1 to input
{ }M ; Map over this list:
$* ; Product of...
\,a ; ...range from 1 to the number
( )FD ; Convert from a list of digits...
v ; ...in base -1
; Implicit output
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes
```
I↨ENΠ…¹⁺²ι±¹
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iOSOxKDk_MWfBgqWlJWm6FjcDAooy80o0nBOLSzScEotTNXwTCzQ88wpKS_xKc5NSizQ0dRQCivJTSpNLNIIS89JTNQyBAjmlxRpGOgqZmkCgo-CXmp5YApQA8ayXFCclF0NNXx6tpFuWoxS70BzCBwA) Link is to verbose version of code. Explanation:
```
N First input as a number
E Map over implicit range
… Range from
¹ Literal integer `1` to
ι Current value
⁺ Plus
² Literal integer `2`
Π Take the product
↨ ±¹ Interpret as base `-1`
I Cast to string
Implicitly print
```
[Answer]
# [J](https://www.jsoftware.com), 10 bytes
```
_1#.1!@+i.
```
Port of [Jonathan Allan's](https://codegolf.stackexchange.com/users/53748/jonathan-allan) smart Jelly answer.
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmuxKt5QWc9Q0UE7Uw8isFGTKzU5I19JWyFNzU4hU8_QACK-YAGEBgA)
```
_1#.1!@+i.
i. NB. range [0,n)
1 + NB. vectorized increment
!@ NB. factorial of each
_1#. NB. convert from base -1
```
[Answer]
# [minigolf](https://github.com/jfioasd/minigolf), ~~23~~ 22 bytes
```
Ti,n;o,T*:1n,n*_*;+s,_
```
[Attempt This Online!](https://ato.pxeger.com/run?1=3VjJkts2EK3KIQflmB9AOAeTI4oR5W2iqXGVE2df7CSTVZlSYUhIwpgiGQCUR_6VXJxD8gn5GH9NusFdBDm2K6ewVCWS6H69N5r44-90rzZJ_OLlW-_wbZoIReRejopbKtYpFZKNRvpPkLPqlfdQrLMti9UTvWKHTAaCp4on8Zm15TFfJ9HKckZHJGf1aBguacFj31rxiN1yYbXvUvuUgTiphFNKP4CY7ADAxEoD1AKYLakSwZZKZMwyk25YlCLhE8FjRUq1yY4JiRD2KhEk2LDgKY_X5OH5Y5KlIVVMOlavVsF_p9XjTKWZIhGXiiQrEiQhSxNQVBIKP_QNqIWagHgJDIVC-g9Vkjas8RXGTHq7uZaVoqW2tZt6t4ET37BrruwpUCI-irWs0V-ZWk1O_jnnbnyauOfHcz924-Pl8elYust88eW7byOlVDR4ClyLCxAVg7qyesA7G7LJkyrksScYDW1nbP0WW44n0wik6vsROpkTHsNPLuYT_yLXFBSPWGxzhzwg03nlqCATmIdsRyNYq14DNaaMjcsOOdOZM295N9fOo2nK4tBGp9pbmtqJCF0N6jg1GoskG-LW9A2DNVr-VL1e8vAalqajUchWeWxsdPFcJzWZPNBcuRTBZBap3HP4rF0SXru5X1gMySUg7zS_M28azdFW69SakyOgC5fA2dJbsW1a45bXsw3UXyF1AR4n7wGIa8076Viy56RemqS2c0HG-n2LOAKqJlFrsVgonLeISoQDh4MJidowMcBbRFwwlYm4WMsdvIqoUpAv1BlwKXqTzjtJw3XG1OFoyybjswqdD-XIq6q6W8psWymqxL6GKajz9aI8A5aqDkWVvxrMpZC8Gltk4AKwQxO4BBvOrBBUe6Bpp8EHEAdAJlGStGMMuUb4wp-3c0npDNF9oDf03QwsxQK3g9nXFMxosOlmohYjaLxmtg-FAV0MXo19NLxJh1bGSwoywVKg6OY0uoi7OZHTXW0FsWHWgZx8pSDLmRoULKpqc65rM8zSfnb9gHVoRpAaQT6jBgjkcsvb2UUZCbx3awoj7LGG3WYReb_Mb2OIau2aGaI7KLQxI2vHwrJ-mv48cKjWrClwZhCoA49SdyyAbZQ_Zx251CWX7YR0e7NTB7ybnHhV1XLZzSDNVtU5ZCInx4Q6Xex2knQMznseIlR2UUC6HMZBgQ2DgKHHq41Yj3WsYVSBWEO_eJM4H7J19Mrb2v8xwrBd0TcJ7jBLM4ZjYu40jRDGOoQ4ecCgicpjmyQc9lGI6ay_ucRmOK7hBPs9YzBexuxaETvYBxEPnHzYaSHCzixImskNmfh67EAKwiWBXVztvcN80oNbPg6hsOkNnpj4zis4bx0llzQi9XR1U5kg3aImv-iGsDGpwSbvd9dXTRJM1dowc9Iczn4Gz59pz5fpjV8WEAQK8_B-qCz7a2UOTQNWLuuKkR3VKoa8mp_zlKhniX6SRCVr1pm78HrtQmPl9G9wpDaGmowoOwxo5RmdqivVJVdYrEBko149_i_UqGbNK_CRIfBV763d2C95oEcciMv3ArCQHvY-vA5Hhhv3gzKyr7cfnJ3dsCGAOdbUn92-c_fe_ZMPdDbq0gaVUkghvmMk5Guu-nuKtrP1vVQBP_zwo0cff_LpZxrWn0JY_fv9QEAwbvB4K64nZyPy5198-dXX3zx-8u13359r9Ik_A_iJ3w-PFOMDzl4ZWJs_aOCpd7cfExaNrD9q1tnde_2ssGhk_alw1nTIUVMj688F6-zOEO_sjpH5l5x5djLAOzsxsv5aqjysM54r4Lxdf_56gqURDZhtJZYL0_GRdGO5dE-twwKsCZdIOD0djwdojpDG9U-BxmmcegT6ozI_R8nPSyRZiWRrOFTJv9YMH4zaplf_aKzWF9N2y34An2KPup0RJOJ3XDEhQ-F3O9F1_wCjeyLv2YsKTa56NG2J6ByMBBvhXjmGoRYv8w7dAQMMkG7YKEoCPAHyrsD_WmREt5chJcncKl4msOFcH-pgll1DNgDRBnDo4MmOaCpbtoXyWEuMRsWJWUtRSCVXkwB0fhz24s_b-c2_)
## Explanation
```
T Push -1 (b)
i,n; [1..n] range of input
o Reverse it
, Map in [n..1]:
T*: Multiply (b) by -1 (since -1^0 = 1
1 Push 1
n Push curr. item
,n*_ Reduce 1..n by product
* mul. w/ b
; End map
+ sum (works for 0 case since sum of [] is 0)
s,_ drop b
implicit output
```
[Answer]
# [PARI/GP](http://pari.math.u-bordeaux.fr/), ~~40~~ 35 bytes
saved 5 bytes thanks to the comment.
[Try it online!](https://tio.run/##K0gsytRNL/j/P00jT9M2MalYo7g0VyPX1lAnT6egKD9FIxvIzNXRzdbU1PxfUJSZV6KRpmEJZAMA)
```
f(n)=abs(sum(m=1,n,prod(k=1,m,-k)))
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 32 bytes
```
f(n){n=n<2?n:n*f(n-2)+f(--n)*n;}
```
[Try it online!](https://tio.run/##VVDbboMwDH3vV1hIlcJNo1CqMsr2MO0rBg8oJB3aZiqSaWiIXx8zGdA1io@OT2zLJ9w/cz6OkqHdY4an8BHv0aHUD21XMt9H28F0GGvU8FHWyGzoN0BnEkR3EVyL6qWADPrAg525MWFCERA/TGy/D4lG8TGhJAoPyXE3pGYKb1Bp4K9l6xAK/ibav2FW3j2HeZc8UcSWB//zyJq7ZdMCmxapsRIdtQXpTE@g6m/RSLasaN/NgrMqKbiuqV4sLbY0TTIP6Y2sSJZM27eqIHX9B9NVXAsuLZVIZm0r8B@AcKtyJDfaA@WthlWWiWIeOxhshf5skexshvGHy/fyrEb/6xc "C (gcc) – Try It Online")
*Port of [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s [JavaScript answer](https://codegolf.stackexchange.com/a/260122/9481)*
[Answer]
# [FunStack](https://github.com/dloscutoff/funstack) alpha, 39 bytes
```
Minus foldl 0 Product map IFrom1 IFrom1
```
Try it at [Replit](https://replit.com/@dloscutoff/funstack)!
### Worked example
```
4
IFrom1 [1,2,3,4]
IFrom1 [[1],[1,2],[1,2,3],[1,2,3,4]]
Product map [1,2,6,24]
Minus foldl 0 19
```
where the last bit is
```
Minus Subtract first argument from second
foldl Left-fold on that function
0 starting with an accumulator value of 0
```
and so our result is -(-(-(-0+1)+2)+6)+24 = 19.
] |
[Question]
[
Given the output of the cop's program (`o`), the byte-count (`n`) and the number of unique bytes (`c`) used, come up with a corresponding piece of code that is `n` bytes long with `c` unique bytes which matches the cop's output `o`.
---
# This is the ***cops thread***. Post solutions that are to-be-cracked here.
# [The ***robbers thread*** is located here](https://codegolf.stackexchange.com/questions/147637/reversed-engineered-from-uniqueness-robbers-thread).
---
Cops should post solutions like this:
```
#[Language], `n` Bytes, `c` Unique Bytes (c*n points) [Cracked](Link-To-Crack)
[Output]
---
(Optional spoiler)
```
---
# Rules
* You may not take any input for your program.
* The program must use at least 1 byte, but cannot exceed 255 bytes.
* The output itself is also limited to 255 bytes.
* The program must have consistent output results when executed multiple times.
* If your submission is not cracked within 7 days, you may mark it as "safe".
+ When marking it safe, post the intended solution and score it as `c*n`.
+ Only mark an answer as "safe" if you *really* want the +15 for an accepted answer; it's more fun to see how long you can go.
# Winning
* The uncracked post with the lowest `c*n` score, wins the cop's thread.
* This will be decided after 10 safe answers, or a few weeks.
# Caveats
* If you feel cocky, you may tell the user the algorithm using a ***spoiler*** tag.
---
Uncracked Submissions:
```
fetch("https://api.stackexchange.com/2.2/questions/147635/answers?order=desc&sort=activity&site=codegolf&filter=!.Fjs-H6J36vlFcdkRGfButLhYEngU&key=kAc8QIHB*IqJDUFcjEF1KA((&pagesize=100").then(x=>x.json()).then(data=>{var res = data.items.filter(i=>!/^#.*cracked/im.test(i.body_markdown)).map(x=>{const matched = /^ ?#{1,3} ?(?:(?:(?:\[|<a href ?= ?".*?">)([^\]]+)(?:\]|<\/a>)(?:[\(\[][a-z0-9/:\.]+[\]\)])?)|([^, ]+)).*[^\d](\d+) ?\[?(?:.*(?:byte|block|codel)s?)(?:\](?:\(.+\))?)? ?(?:\(?(?!no[nt][ -]competing)\)?)?/gim.exec(x.body_markdown);if(!matched){return;}return {link: x.link, lang: matched[1] || matched[2], owner: x.owner}}).filter(Boolean).reverse().forEach(ans=>{var tr = document.createElement("tr");var add = (lang, link)=>{var td = document.createElement("td");var a = document.createElement("a");a.innerHTML = lang;a.href = link;td.appendChild(a);tr.appendChild(td);};add(ans.lang, ans.link);add(ans.owner.display_name, ans.owner.link);document.querySelector("tbody").appendChild(tr);});});
```
```
<html><body><h1>Uncracked Submissions</h1><table><thead><tr><th>Language</th><th>Author</th></tr></thead><tbody></tbody></table></body></html>
```
[Answer]
# [Haskell](https://www.haskell.org/), 173 bytes, 8 unique, 1384 points, safe
```
"[tag:reverse_engineering]"
```
It looks like this answer wants to provide a relevant tag to the question, while using only 8 different bytes.
As usual, your solution should work by being pasted in the code block on TIO: [Try it online!](https://tio.run/##y0gszk7NyflfXFKUmZeuYKsQ818puiQx3aootSy1qDg1PjUvPTMvNRUkG6v0PzcxMw@oqKC0JLikSAGi6f@/5LScxPTi/7rJBQUA "Haskell – Try It Online")
---
### Solution
```
'[':___':_'':_':':':__':__:__'':__:__':____:__:'_':__:___:_':_'_:___:__:__:__':_'_:___:_':']':[]
_:_:_'':_:_:_:__:_:_':_:_'_:_:_:_:_:___:_:_:_:__':____:___':_:__'':_=['_'..]
```
Yes, this is valid Haskell code: [Try it online!](https://tio.run/##RU9JDoMwDLzzitx8ggdY4hU9ppEVIUoRAUUkfL9uHJdUI9tjeby9fdrmEDjlcz0WM5ongwUkouJADAU1JQl3FIkQhLtEWHt@lJoOWhEcoHVd4TpboWl1hA30Z22XqmrraMveYXC8@/UoZ8crP/Jp9A3@TK/gl8T9FOMX "Haskell – Try It Online")
### How it works
The underscore `_` is used as a wild card in Haskell's pattern matching. `'` is used for characters, e.g. `'a'`. However, both `_` and `'` are also part of the allowed characters for identifier names (Within some restrictions, e.g. `'` cannot occur at the beginning of the name.). Therefore `__`, `_'`, `_'_`, `_''` and so on are all valid identifier names. Using some more descriptive names, the above code becomes
```
'[':t:a:g:':':r:e:v:e:r:s:e:'_':e:n:g:i:n:e:e:r:i:n:g:']':[]
_:_:a:_:_:_:e:_:g:_:i:_:_:_:_:n:_:_:_:r:s:t:_:v:_=['_'..]
```
The first line yields the string `"[tag:reverse_engineering]"` if each variable is assigned to the correct character. This assignment is achieved in the second line: `['_'..]` yields the string `"_`abcdefghijklmnopqrstuvwxyz{|}~ ... "`, witch is matched on the pattern `_:_:a:_:_:_:e:_:g:_:i:_:_:_:_:n:_:_:_:r:s:t:_:v:_` to get the desired assignment `a='a'`, `e='e'` and so on.
[Answer]
# Brain-Flak, 62 total bytes, 6 unique, 372 points, [Cracked](https://codegolf.stackexchange.com/a/149582/56656)
Here is your output:
```
10993592
```
There is something special about this number but [its not on the OEIS](http://oeis.org/search?q=10993592&language=english&go=Search) ;)
In case you are thinking of using a computer tool to solve this, you're out of luck, the integer golfer gets 110 bytes for this number:
```
(((((((((((((((((((((()()()()){}){}){}){({}[()])}{}()()){})){}{}())){}{})){}{}){}){}){}())){}{}){}()){}){}){})
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/XwMr0IRAzepaGNKoro3W0IzVrK2uhckAMYgDoaEkDMGFwUy4xP//AA "Brain-Flak – Try It Online")
You're going to have to do this one by hand.
---
## Tips
Here are some tips, I will reveal more an more helpful tips over time. Good luck!
>
> 10993592 is the 97th term of a sequence on OEIS, but does not appear because only a few terms are included.
>
>
>
---
>
> My solution uses 3 loops, but they are *not* nested 3 levels deep.
>
>
>
---
## My solution
```
((((((()()()){}){}){}){}){}())(({(({})[()])}{}){{({}[()])}{}})
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/XwMCNEFQs7oWGQEFNDSqgahWM1pDM1azFiRaDeTCeLWa//8DAA "Brain-Flak – Try It Online")
This uses one of my favorite tricks, the code
```
(({(({})[()])}{}){{({}[()])}{}})
```
computes the nth term of [A090809](https://oeis.org/A090809). The full submission just pads the code with a 97 to make a large number.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 6 bytes × 3 unique = 18 points. [Cracked](https://codegolf.stackexchange.com/a/147687/36398)
```
1+0i 0+1i -1+0i 0-1i
```
[Answer]
# [Malbolge](https://tio.run/#malbolge), 15 bytes, 13 unique, score 195. Safe!
Outputs:
```
PPCG
```
**Safe!** Intended code:
```
(&a`#""7[}4XE70
```
[Try it online!](https://tio.run/##y03MScrPSU/9/19DLTFBWUnJPLrWJMLV3OD/fwA "Malbolge – Try It Online")
[Answer]
# JavaScript (ES8), 103 bytes, 42 unique (4,326 points) [SAFE]
Output hexdump:
```
3E 6E 6D 08 33 7A 22 7D 6C 37 7B 36 61 7B 65 71 3A 37 26 7E 7B 7B 38 7B 7D 69 6A 2B 3D 70 74 07 6F 6C 66 7E 1A 2A 3C 37 2D 36 31 38 6A 78 33 62 30 1E 34 3D 66 7B 37 10 26 6A 6A 32 27 6F 2E 33 1B 30 1E 76 27 27 7E 18 6F 68 26 2D 76 6A 6D 6D 2F 2E 0A 3F 17 7D 2B 73 7A 17 38 62 3A 29 20 0C 61 24 21 27 10 2B 20 63 71 72 17 5D 5F 12 5B 02 14 59 17 5A 11 1E 1D 10 16 07 5F 5F 58 58 4B 18 48 4B 04 5F 06 12 16 14 4D 45 5D 5D 16 3A 1C 1D 11 16 1F 51 59 4E 4B 4C 3D 16 1C 0F 2E 46 0E 08 4B 4B 13 45 21 10 06 0E 11 3F 51 57 3E 00 54 5F 49 05 0E 07 5A 51 3E 08 01 25 10 0B 51 36 43 0B 34 1A 43 47 04 46 0E 55 05 00 06 01 40 33 0F 00 53 36 42 42 45 5F 3D 3A 38 74 39 74 71 71 2C 7C 60 38 38 76 63 44 7F 64 28 66 3E 24 7A 66 57 79 24 3C 3C 21 6A 36 27 30 77 7E 36 7E 2A 3E 29
```
The score is abnormally big, I know, but anyway I think this one may be interesting to crack. The program is a function which returns a string (just to avoid confusion, this is not REPL).
It shouldn't be too hard, I suppose, everything is about finding the pattern.
### Solution
It seems that it was harded than I had thought, according to the fact that nobody had cracked it. I believed there may be multiple solutions which are easy to craft. Anyways, here is the intended solution:
>
>
> ```
> f=m=>[...m=f+f+f].map((a,p)=>p+1&256?'':String.fromCharCode((p&4?m[p^17]:a).charCodeAt^83^p*.3)).join
> ```
>
>
>
>
For some reason it is not displayed properly as code snippet. Here is the [TIO link](https://tio.run/##LctNCoMwEEDh22imtgPW/iFEKR6hSzEkWGMjJhli6PVTF@UtP96ivmobg6F4cv49paS55U2PiJbrYm9Aq4gxdSTgDRVldr7e2jyvXzEYN6MO3nYfFbp9ZoyyS2t7EuV9qBXg@IdnlFI8KkEHrABw8cZJmUbvNr9OuPqZaQaQfg).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes × 6 unique = 42 points, [cracked](https://codegolf.stackexchange.com/a/147758/41024)
```
843606888284160000
```
[Try it online!](https://tio.run/##y0rNyan8/9/CxNjMwMzCwsLIwsTQzAAI/v8HAA "Jelly – Try It Online")
>
>
> ```
> 8!×16!¤
> ```
>
>
>
>
[Answer]
# Octave, 13 bytes, 5 unique characters, score: 65. Safe!
```
20085918935040000
```
This one shouldn't be too hard. If you don't want to jump in to the most difficult ones straight away it might be a nice first challenge :)
Note: When I read the question, I though it said: Output a number, not output a string. The output looks like this on TIO:
```
ans = 2.0086e+16
```
And will look like this if you have `format long`
```
ans = 20085918935040000
```
or you may print it like this:
```
printf('%i',ans)
20085918935040000
```
### What I had, and explanation:
```
prod prodprod
```
Simple as that. =)
**Explained:**
Normally you'd write this as: `prod('prodprod')`, but Octave treats whatever comes after the function name as a string (array of characters). These are implicitly converted to their ASCII-values, and multiplied together.
[Answer]
# MATL, 11 bytes, 10 unique, 110 points. SAFE!
Output:
```
10803850202590
```
Just to "help" you one the way:
This is the product of:
```
[2, 5, 29, 89, 397, 499, 2113]
```
and it's one less than the `372884884433`rd prime.
---
And here are some real tips. If it's not cracked in a few hours then I'll reveal the solution.
1. >
> - There's a `q` in there
>
>
>
2. >
> - There's a `B` in there
>
>
>
3. >
> - There's a `^` in there
>
>
>
4. >
> - There's a `h` in there
>
>
>
5. >
> - There's a `t` in there
>
>
>
### The real code:
>
> 9K^ZqsBthXB
>
>
>
**Explanation:**
>
> Push two numerals, `9` and `K`, and do exponentiation. Create a list of all primes below that number, and sum them. Convert to binary, duplicate the binary vector and concatenate it with itself. Convert back to decimal and output implicitly.
>
>
>
[Answer]
# MATL, 4 bytes, 4 unique, 16 points. [Cracked](https://codegolf.stackexchange.com/a/147653/36398)
Output:
```
1388289520800
```
**What I had:**
>
> `1X%p`
>
>
> This pushes the number 1, checks which class it is, then multiplies the ASCII-values of the resulting string 'double'.
>
>
>
[Answer]
# Java 8 (full program), 97 total bytes, 34 unique, 3298 points ([Cracked by *@RobertoGraham*](https://codegolf.stackexchange.com/a/147684/52210))
Output:
```
1.4241570377303032
```
NOTE: This is a full program. If functions in the form of `()->` are allowed instead:
# Java 8 (lambda function), 40 total bytes, 18 unique, 720 points ([Cracked by @user202729](https://codegolf.stackexchange.com/questions/147635/reversed-engineered-from-uniqueness-cops-thread/147659?noredirect=1#comment362499_147659))
It's probably quite hard, but whatever.. It's not like Java is going to win anything with this amount of points anyway..
---
**Hints:**
>
> The intended code doesn't contain any single or double quotes. (The function returns a double.)
>
> The intended code doesn't contain any digits (`0-9`).
>
>
>
---
**Intended solution:**
Pretty funny (and impressive) how both given cracks are completely different than what I had in mind, but chapeau to both of the crackers!
>
> Function: [`()->Math.log(Math.hypot(Math.PI,Math.E))`](https://tio.run/##LU7LCoMwELz7FXtMoOYHpL310INS8Cg9bGOqsZoEswpS/PY0Pi67Mwzz6HDG1DpluvobZI/eQ47a/BIAbUiNH5QKio0C1HZ69wok41nkaxKPJyQtoQADVwiMp7ccqRW9bdgO2sVZOuDzcdn/nfOQbV4X06L3jJitrmGI1aykUZumegHyo7dcPKlB2ImEixIxI@KGc8Qa/g)
>
> Full program: [`interface M{static void main(String[]a){System.out.print(Math.log(Math.hypot(Math.PI,Math.E)));}}`](https://tio.run/##y0osS9TNL0jNy0rJ/v8/M68ktSgtMTlVwbe6uCSxJDNZoSw/M0UhNzEzTyO4pCgzLz06NlGzOriyuCQ1Vy@/tESvAChYouGbWJKhl5OfDmFkVBbkQ8UCPHXAtKumpqZ1be3//wA)
>
>
>
[Answer]
# [Haskell](https://www.haskell.org/), 10 bytes, 3 unique, 30 points, [cracked](https://codegolf.stackexchange.com/a/147736/56433)
```
2416508937
```
A nice number which contains every digit, though only 3 unique bytes are used.
The intended solution works by replacing the code part in the following TIO link:
[Try it online!](https://tio.run/##y0gszk7NyfmfqWCrEPPfyMTQzNTAwtLY/H9uYmYeUKygKDOvRCHz/7/ktJzE9OL/uskFBQA "Haskell – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 29 bytes, 15 unique bytes, 435 points, [cracked](https://codegolf.stackexchange.com/a/147884/56433)
```
"33333333333333333333333333333333333333333333334333333333333333333333333333"
```
This is a string containing `3` 73 times, and a single sneaky `4`.
The intended solution works by replacing the code part in the following TIO link: [Try it online!](https://tio.run/##y0gszk7NyflfXFKUmZeuYKsQ81/JmCRggkdO6X9uYmYe0NSC0pLgkiIFiC3//yWn5SSmF//XTS4oAAA "Haskell – Try It Online")
*Edit:* H.PWiz found a valid crack (which could even be golfed to 28 bytes), but not the intended solution.
**Hints:**
>
> No arithmetic needed.
> There exists a single-expression solution.
>
>
>
[Answer]
# Mathematica, 8 bytes, 3 unique, 24 points [Cracked](https://codegolf.stackexchange.com/a/147897/67961)
```
7448503425106854065710345345644475127957406351360000000
```
[Answer]
# [Explode](https://tio.run/#explode), 9 total bytes, 4 unique, 36 points
Output:
```
22k2Dk}D}
```
Note that the documentation does not completely align with the implementation for this language - I wrote this one day and haven't touched it since, so any bugs in implementation that may exist are now definitely features.
Also, I do not think this language is Turing-complete, so you could probably brute force it, but that's boring.
I'll give you a sizable bounty if you can automate reverse-engineering output into optimally short Explode code.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page), 2 unique, 8×2 = 16 points -- Safe!
```
-4.408500694095235e-05
```
(There are only **8,355,840** possible such programs so it should get cracked I guess.)
**[Get going at Try it online!](https://tio.run/##y0rNyan8/1/XQM8ACExMDCxMDQzMLE0MLE2NjE3//wcA)**
### How?
>
> `⁽⁽°°°°°°`
>
> `⁽⁽°` is a base 250 literal yielding `-27221`
>
> `°` converts from radians to degrees. Applying this five times:
>
> `-475.09607568537643`
>
> `-8.291990784013993`
>
> `-0.1447225407260702`
>
> `-0.0025258848375215096`
>
> `-4.408500694095235e-05`
>
>
>
[Answer]
### C (two's complement machine, sizeof(int) = 4), 76 bytes and 35 unique bytes for a score of 2660, Safe
Output:
```
10542949672924294967287429496729029742949672954294967287429496728808914294967289429496728742949672946944294967291429496728742949672914964294967294429496728742949672891980429496728842949672874294967295792
```
which is 203 bytes long.
>
> #include<math.h>
>
> main(){for(int
>
> i=0;i<40;i++)printf("%u",(int)(cos(i)\*10));}
>
>
>
> Without the #include it won't work.
>
>
>
>
[Answer]
# CJam, 15 bytes \* 10 unique = 150 points
```
453630781352162854505467929721140132016201833205823402832306035643819420004950
```
Bad score, but hopefully will be hard to crack.
Note: At the moment I have forgotten what the answer is. As such, I will keep it open until either I or somebody else is able to crack it.
[Answer]
# CJam, 15 bytes \* 10 unique = 150 points
```
355605126761554652609272416635107412217265861355621217687464016216276447790261274709847680
```
Note: At the moment I have forgotten what the answer is. As such, I will keep it open until either I or somebody else is able to crack it.
[Answer]
# Octave, 4 bytes, 3 unique, 12 points: [cracked](https://tio.run/##y08uSSxL/f8/K8486/9/AA)
```
1.6776e-05
```
Lets see how fast this one goes.
[Answer]
# Pyth, 7 bytes, 6 unique, 7\*6=42 total score
```
312069475503262125385169244603150327250717758754411025379995130624544231547913731661607993843298516888546865336571981925596
```
---
Check out the [Pyth tips thread](https://codegolf.stackexchange.com/questions/40039/tips-for-golfing-in-pyth) for inspiration ;)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes × 3 unique = 9 points, [cracked](https://codegolf.stackexchange.com/a/147767/41024)
```
263409560461970212832400
```
[Try it online!](https://tio.run/##y0rNyan8/9/IzNjEwNLUzMDEzNDS3MDI0MjC2MjEwOD/fwA "Jelly – Try It Online")
Another attempt at Jelly, this time more challenging I hope.
>
>
> ```
> ȷc⁵
> ```
>
>
>
>
[Answer]
# [Alice](https://github.com/m-ender/alice), 9 bytes x 8 unique = 72 points [Cracked](https://codegolf.stackexchange.com/a/147892/69059)
```
KMOQSUWY[]_acegikmoqsuwusqomkigecegikmoqsuwy
```
[Try it online!](https://tio.run/##S8zJTE79/9/b1z8wODQ8Mjo2PjE5NT0zOze/sLi0vLS4MD83OzM9FUms8v9/AA "Alice – Try It Online")
This one should be funny to crack
[Answer]
# Excel, 22 bytes, 16 unique, 352 points, [Cracked](https://codegolf.stackexchange.com/questions/147637/reversed-engineered-from-uniqueness-robbers-thread/147860#147860)
```
หนึ่งล้านห้าแสนสามหมื่นสองพันสี่ร้อยเก้าสิบห้าล้านห้าแสนสี่หมื่นแปดร้อยหกสิบห้าล้านแปดแสนเก้าหมื่นล้านล้านล้านล้านล้านล้านบาทถ้วน
```
This might not be very hard to crack but I get to use a function that I otherwise never get to use. Besides, the score won't win anything unless a lot of others get cracked.
[Answer]
# PowerShell, 7 bytes, 5 unique = 35 points [Cracked](https://codegolf.stackexchange.com/a/147830/42963)
Output:
```
1125899906842624
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes \* 6 unique = 48 ([Cracked](https://codegolf.stackexchange.com/a/148082/53748))
```
241975308641975308641975308641975308641975308641926913580246913580246913580246913580246913580246916
```
You can [try to crack it here](https://tio.run/##y0rNyan8DwQA).
>
> **Intended solution:** `7ẋ²Ḍ²ẋ4S`
>
>
>
[Answer]
# [Haskell](https://www.haskell.org/), 30 bytes, 17 unique, 510 points, [cracked](https://codegolf.stackexchange.com/a/148108/56433)
```
"6666666444444455666666666566555533333334333333333"
```
The intended solution works by replacing the code part in the following TIO link: [Try it online!](https://tio.run/##y0gszk7NyflfXFKUmZeuYKsQ81/JDAJMIMDU1AwGgCxTIDCGABNjGFD6n5uYmQfUXFBaElxSpAAx7P@/5LScxPTi/7rJBQUA "Haskell – Try It Online")
This uses the same approach as my [previous answer](https://codegolf.stackexchange.com/a/147876/56433), which was cracked using a different approach.
Some hints:
>
> No arithmetic needed. I have a single-expression solution.
>
>
>
[Answer]
# Javascript, `11` Bytes, `7` Unique Bytes (77 points) [(Cracked)](https://codegolf.stackexchange.com/a/147665/58563)
```
0.022522522522522525
```
---
>
> lambda function declaration included in byte count, function call is not.
>
>
>
This should be really easy.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page), 4 unique, 4 × 4 = 16 points -- Safe!
```
121713205122350539153771498803599196214022517709999123476340843193655114000078051089267404501704293755399249186132786797198080437408108773592830098754467315464894774875031495160099382422748898046431945143395996374011431649446848855993397955116462522798880
```
Note that the output is 255 bytes long, right at the limit.
Yep, same score as [my other (as yet uncracked) Jelly entry](https://codegolf.stackexchange.com/a/147756/53748).
**[Get going at Try it online!](https://tio.run/##FY/BFUNBCAJbEkXRgnLJSwOp/od4ZMeRfb8@n@/zICFURiOzOroOXRJ4u1F9h5sEI7MhxXmQRU0xloWr6YYBj9aa2MsRgx1QMK/Utl7ysONT2tEJt7HBMrnekXwrtyJu1eSo0BzuUaKjKFdqjIGrTWY6XksMuQUbrDr3nb/ShQrDs2iNtXO/6v5Vh5PtdX9w43l@)**
### How?
>
> `7ÆĊ⁺`
>
> `7` is a literal seven
>
> `ÆĊ` gets the **nth** Catalan number
>
> the **7th** Catalan number is **429**
>
> `⁺` repeats the previous atom
>
> the **429th** Catalan number is `121713205122350539153771498803599196214022517709999123476340843193655114000078051089267404501704293755399249186132786797198080437408108773592830098754467315464894774875031495160099382422748898046431945143395996374011431649446848855993397955116462522798880`.
>
>
>
[Answer]
# [Perl 5](https://www.perl.org/), 31 Bytes, 18 Unique Bytes (558 points) -- safe
```
1.76295255109024e+180
```
Intended solution ([Try it online!](https://tio.run/##K0gtyjH9/18l3tbQOi2/SMVWw1BPz9DQULNaJV7LVsW2tqAoM6/k/38A "Perl 5 – Try It Online")):
```
$_=1;for$=(1..111){$_*=$=}print
```
(this calculates the factorial of 111)
[Answer]
# Haskell, 37 bytes, 20 unique, 740 points, safe
The answer is an expression whose result equals the string literal:
```
"4F\\DLE\\C\"S\\T \\\\DC$EO!RUr\\K\\SSS1\\%S\\\\AN\\D&CDI#3SSC\\\\\\E\\C\\YC\\USB2SNN\\ED'\""
```
(That is, when `putStr`’d, you’d get:)
```
4F\DLE\C"S\T \\DC$EO!RUr\K\SSS1\%S\\AN\D&CDI#3SSC\\\E\C\YC\USB2SNN\ED'"
```
>
> **Safe**! Intended expression:
>
>
>
> ```
> [show['\r'..]!!rem(w^7)77|w<-[7..77]]
>
> ```
>
>
] |
[Question]
[
Sometimes, I will think it is one day of the week (e.g Friday) when in reality, it's earlier in the week (e.g Tuesday).
Your challenge is to display the number of days my estimates are off by.
## Challenge
Given a day of the week I think it is, and the day of the week it actually is, output/return the number of days between the two.
## Test Cases
```
Incorrect date, Actual Date -> Days between
Monday, Monday -> 0
Friday, Tuesday -> 3
Saturday, Sunday -> 6
Tuesday, Friday -> 4
Thursday, Wednesday -> 1
Monday, Friday -> 3
```
## Rules
* Dates have to be taken as the actual date name (`Monday`, `Tuesday`, `Wednesday`, `Thursday`, `Friday`, `Saturday` and `Sunday`). This is non-negotiable.
* Date names must be taken as strings or equivalent in your language (ADTs aren't allowed unless they store their values as the allowed strings)
* Input and output can be given/taken in any reasonable format.
* Full program or function - it doesn't matter.
And finally, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the answer in each language with the fewest bytes wins.
[Answer]
# JavaScript (ES6), 48 bytes
Expects `(day1)(day2)`.
```
a=>b=>((g=s=>parseInt(s,34)%72%23)(a)-g(b)+21)%7
```
[Try it online!](https://tio.run/##dc9NC4JAEAbgu79CBGGXMvODOq3HoEMng86jrpshu7LrBv36bRFTM5rTMDy8M/OAJ6hSNl0fcFFRUxMDJCtIhhAjimQdSEXPvEdqm6TYP8Z@nGAEOGCowJs4siNTCq5ES3etYKhG3kXwCl4enjvsDhWG7t5Z4ZNsRnzVVC20xcka59BrOfJcL7ItPqzxlDcvmZLTH3zX8qNvtOLTKRZHzt8Hv4OHm80b "JavaScript (Node.js) – Try It Online")
### How?
We need a hash function \$g\$ that turns a day string into an index. The results of this function are actually quite flexible:
* They can be in ascending or descending order: `0,1,2,3,4,5,6` or `6,5,4,3,2,1,0`. (We'll have to compute either \$g(a)-g(b)\$ or \$g(b)-g(a)\$ accordingly.)
* Day #0 may be any day of the week. For instance, `3,4,5,6,0,1,2` or `4,3,2,1,0,6,5` are also valid.
* The results may be greater than \$6\$ as long as they are correct modulo \$7\$. Because the sign of the modulo is the sign of the dividend in JS, we'll have to do something like `(g(a) - g(b) + k) % 7` anyway, where \$k\$ is a large enough multiple of \$7\$.
The following function was found by brute-force:
```
g = s => parseInt(s, 34) % 72 % 23
```
which gives:
```
day | base34 -> dec | mod 72 | mod 23 | mod 7
-------------+---------------+--------+--------+-------
"Monday" | 30369728 | 56 | 10 | 3
"Tuesday" | 1358300452 | 4 | 4 | 4
"Wednesday" | 1702996445748 | 12 | 12 | 5
"Thursday" | 45612914380 | 52 | 6 | 6
"Friday" | 21127508 | 44 | 21 | 0
"Saturday" | 43748842416 | 24 | 1 | 1
"Sunday" | 38623568 | 32 | 9 | 2
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + GNU utilities, 26
```
date -f- +%u|dc -e??-7+7%p
```
Inputs are read from lines 1 and 2 of STDIN.
[Try it online!](https://tio.run/##TYw9D4JADIb3/op3kERDbmZwYHNzgsS50JIjMZw5uBgD/PbTAwa7tM/70YZHG7vzBXMUnhSmM8izsEgLo2VpirzIXnGlt@2fCq8sYDRXiKOZ8BttrcOJ/@6GVizoSNyg8e4G4Q/2RTffJ6qDjgkrnoJPQhU2@9Cxx6i2wW/8UBn2xvHuCHwB "Bash – Try It Online")
### Explanation
GNU `date` reads a *mostly free format human readable date string*. With `-f` it reads multiple date strings from a file and if the file is `-`, STDIN is read. The *free format* is free enough that a single day of the week will be parsed. The parsed date is then output according to the format string. `%u` simply outputs the {1..7} numerical index of the day of the week, where 1 is "Monday".
This output is piped to a `dc` expression:
```
?? # read the first 2 converted inputted dates
- # find the difference
7+ # add 7
7% # find the modulo-7
p # print the result
```
[Answer]
# [Python 2](https://docs.python.org/2/), 42 bytes
```
lambda a,b:(hash(b*11)%69-hash(a*11)%69)%7
```
[Try it online!](https://tio.run/##RY3BCsIwDIbvfYpcZK1UcSqKg3r05knBiyAZ22hhdqVrGXv6unUbnpL/y5fE9E42eh8q8Q41fvMCAXmeUYmtpPk6TdnqdNnEhHNiq3PopKpLSDMCShsOjXcGBFjsPkP2jrJta2rlaAKbKySMLIbSjo7tQJBDHolZXB5NYwcJKjrOGQgRV8O90QX2HKY6Xt2Rm1WRPX3ZzhAO5IHO28gffnFPZHY4TEsjPJKn9Hair7LQ/yMpWd797cMP "Python 2 – Try It Online")
If we can map both weekdays to their respective values (`Monday -> 0, Tuesday -> 1, ...`), then we can calculate the days in between with \$ (a - b) \bmod 7 \$. To do this, we use the following formula: `hash(s*11)%69%7`.
[Answer]
# [K (ngn/k)](https://bitbucket.org/ngn/k), ~~32~~ 26 bytes
**Solution:**
```
7!-/13 1 0 2 12 7 5?15!+/'
```
[Try it online!](https://tio.run/##y9bNS8/7/z/NylxRV9/QWMFQwUDBSMHQSMFcwdTe0FRRW1/9f5q6hoaSb35eSmKlkjWMoWmtoeRWlAkRCylNLYYJBieWlBZBhINL4UphKqxhmsCCGaVFUNHw1JQ8hBlwy2CKNbn@AwA "K (ngn/k) – Try It Online")
**Explanation:**
Found a slightly better lookup. Sum of ASCII chars modulo 15.
```
7!-/13 1 0 2 12 7 5?15!+/' / the solution
+/' / sum (+/) each (') input string
15! / 15 modulo result
? / lookup this value in left list
13 1 0 2 12 7 5 / precalculated result of summing ASCII weekdays
-/ / subtract to get difference
7! / modulo 7 to account for negatives
```
**Edits:**
* **-6 bytes** Lookup table based on sums of ascii chars, rather than `Mo/Tu/We` etc.
[Answer]
# [Factor](https://factorcode.org/), 35 bytes
```
[ [ day-names index ] bi@ - 7 rem ]
```
Doesn't run on TIO because TIO is missing the `calendar.english` vocabulary which is perfectly extant on a local copy of Factor 0.98. So have a screenshot of running the quotation in the listener:
[](https://i.stack.imgur.com/iPr2w.png)
## Explanation:
It's a quotation (anonymous function) that takes two strings on the data stack as input and leaves an integer on the data stack as output. Assuming `"Tuesday" "Friday"` is on the data stack when this quotation is called...
* `[ day-names index ]` Push a quotation for `bi@` to use later.
**Stack:** `"Tuesday" "Friday" [ day-names index ]`
* `bi@` Apply a quotation to two objects. Inside the quotation now...
**Stack:** `"Tuesday"`
* `day-names` Push a sequence containing the days of the week.
**Stack:** `"Tuesday" { "Sunday" "Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday" }`
* `index` Take an object and a sequence and return the index of that object in the sequence.
**Stack:** `2`
* Now `bi@` will do the same with the other input.
**Stack:** `2 5`
* `-` Subtract.
**Stack:** `-3`
* `7` Push `7` to the stack.
**Stack:** `-3 7`
* `rem` Like `mod`, except the result is always positive.
**Stack:** `4`
[Answer]
# [Emotilang](https://knosmos.github.io/emotilang/), 1,312 bytes
([Github repo](https://github.com/knosmos/emotilang))
Input is from the first and second lines of STDIN.
```
üì¶‚úèÔ∏èüí¨üìúüìú
ü§îüì¶‚öñÔ∏èüìú‚ôèÔ∏èüÖæÔ∏è‚ôëÔ∏è‚Ü©Ô∏èüÖ∞Ô∏èüíπüìú
üì¶‚úèÔ∏èüíØüïõüíØ
ü§îüì¶‚öñÔ∏èüìú‚úùÔ∏è‚õéüìßüí≤‚Ü©Ô∏èüÖ∞Ô∏èüíπüìú
üì¶‚úèÔ∏èüíØüïêüíØ
ü§îüì¶‚öñÔ∏èüìú„Ä∞Ô∏èüì߂ܩÔ∏è‚ôëÔ∏èüìßüí≤‚Ü©Ô∏èüÖ∞Ô∏èüíπüìú
üì¶‚úèÔ∏èüíØüïëüíØ
ü§îüì¶‚öñÔ∏èüìú‚úùÔ∏è‚ôìÔ∏è‚õ鬯Ô∏èüí≤‚Ü©Ô∏èüÖ∞Ô∏èüíπüìú
üì¶‚úèÔ∏èüíØüïíüíØ
ü§îüì¶‚öñÔ∏èüìúüéè¬ÆÔ∏èüïØÔ∏è‚Ü©Ô∏èüÖ∞Ô∏èüíπüìú
üì¶‚úèÔ∏èüíØüïìüíØ
ü§îüì¶‚öñÔ∏èüìúüí≤üÖ∞Ô∏è‚úùÔ∏è‚õ鬯Ô∏è‚Ü©Ô∏èüÖ∞Ô∏èüíπüìú
üì¶‚úèÔ∏èüíØüïîüíØ
ü§îüì¶‚öñÔ∏èüìúüí≤‚õé‚ôëÔ∏è‚Ü©Ô∏èüÖ∞Ô∏èüíπüìú
üì¶‚úèÔ∏èüíØüïïüíØ
‚öóÔ∏è‚úèÔ∏èüí¨üìúüìú
ü§î‚öóÔ∏è‚öñÔ∏èüìú‚ôèÔ∏èüÖæÔ∏è‚ôëÔ∏è‚Ü©Ô∏èüÖ∞Ô∏èüíπüìú
‚öóÔ∏è‚úèÔ∏èüíØüïõüíØ
ü§î‚öóÔ∏è‚öñÔ∏èüìú‚úùÔ∏è‚õéüìßüí≤‚Ü©Ô∏èüÖ∞Ô∏èüíπüìú
‚öóÔ∏è‚úèÔ∏èüíØüïêüíØ
ü§î‚öóÔ∏è‚öñÔ∏èüìú„Ä∞Ô∏èüì߂ܩÔ∏è‚ôëÔ∏èüìßüí≤‚Ü©Ô∏èüÖ∞Ô∏èüíπüìú
‚öóÔ∏è‚úèÔ∏èüíØüïëüíØ
ü§î‚öóÔ∏è‚öñÔ∏èüìú‚úùÔ∏è‚ôìÔ∏è‚õ鬯Ô∏èüí≤‚Ü©Ô∏èüÖ∞Ô∏èüíπüìú
‚öóÔ∏è‚úèÔ∏èüíØüïíüíØ
ü§î‚öóÔ∏è‚öñÔ∏èüìúüéè¬ÆÔ∏èüïØÔ∏è‚Ü©Ô∏èüÖ∞Ô∏èüíπüìú
‚öóÔ∏è‚úèÔ∏èüíØüïìüíØ
ü§î‚öóÔ∏è‚öñÔ∏èüìúüí≤üÖ∞Ô∏è‚úùÔ∏è‚õ鬯Ô∏è‚Ü©Ô∏èüÖ∞Ô∏èüíπüìú
‚öóÔ∏è‚úèÔ∏èüíØüïîüíØ
ü§î‚öóÔ∏è‚öñÔ∏èüìúüí≤‚õé‚ôëÔ∏è‚Ü©Ô∏èüÖ∞Ô∏èüíπüìú
‚öóÔ∏è‚úèÔ∏èüíØüïïüíØ
üß∫‚úèÔ∏èüì¶‚ûñ‚öóÔ∏è
üß∫‚úèÔ∏èüß∫üçáüíØüïñüíØ
üñ®Ô∏èüß∫
```
[Online interpreter](https://knosmos.github.io/emotilang/interpreter.html)
Here is proof that it passes the test cases:
[](https://i.stack.imgur.com/A1KKS.jpg)
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 114 bytes
```
v(s,n)=1+Vecsmall(s)[n]%4;
m=[5,x,x,7;3,2,6,1;x,x,x,x;x,x,x,4];
d(n)=m[v(n,6),v(n,1)];
p(a,b)=print((d(a)-d(b))%7)
```
Explanation:
Pari/GP doesn't have calendar functions or, really, much in the way of string processing. I use the ASCII values of the 1st and 6th characters of the weekday name to index into a 4x4 matrix that encodes the weekday numbers, and then I just print the forward difference. I'm pleased with my solution, but there's probably a shorter formula I didn't think of.
[Try it online!](https://tio.run/##TY29DoJAEIR7HoOEZDcuBYpYXGjtrDBaIMXhoZLAebkDgk@Pp/xotpjdLzOziuvSv6vhFl@GDgxJjIPVqbiamlcVGExl5oXMqeN0S72dHdvQmiIKWP@9@0nDjDkCbLpOO5AUIX0kQIsVcMoxVrqUDYAAjr6AHNHb4aDAPTyl4C@X5gVtwN3rcoTHtjALTXjT6pEn7c88e2iOjfTR6gmfCyH/apaPi314Aw "Pari/GP – Try It Online")
[Answer]
# Ruby, 91 bytes
```
require"date"
w=(0..6).map{|i|Date.jd(i).strftime"%A"}
f=->i,a{(w.index(i)-w.index(a)+7)%7}
```
Testing:
```
p f["Saturday", "Sunday"] #=> 6
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes
```
OP€%647%154%8I%7
```
[Try it online!](https://tio.run/##y0rNyan8/98/4FHTGlUzE3NVQ1MTVQtPVfP/h9uBQv//R0cr@ebnpSRWKukowFixOgrRSm5FmVDRkNLUYrhwcGJJaRFUIrgUoRymCCgM1QkRzigtgomHp6bkIZmEsBamIRYA "Jelly – Try It Online")
-2 bytes thanks to Arnauld via finding the modulo chain to get the right values
Previously:
# [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes
```
OP€%17Ḥị“ØỴ¦’D¤I%7
```
[Try it online!](https://tio.run/##y0rNyan8/98/4FHTGlVD84c7ljzc3f2oYc7hGQ93bzm07FHDTJdDSzxVzf8fbgeq@P8/OlrJNz8vJbFSSUcBxorVUYhWcivKhIqGlKYWw4WDE0tKi6ASwaUI5TBFQGGoTohwRmkRTDw8NSUPySSEtTANsQA "Jelly – Try It Online")
Not convinced this is a good way of doing it, lol.
-2 bytes using integer compressing (thanks Lyxal)
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~43~~ 41 bytes
-2 bytes thanks @Zaelin Goodman
```
$x,$y=$args|%{+[dayofweek]$_}
($x-$y+7)%7
```
[Try it online!](https://tio.run/##XZBdS8MwFIbv8yvORWpb1oGibFeDiSJ4IYoVvBhj1PbMqbWZ@WAtXX97TdN0seYqyfN@HM6eHZCLHeZ5S7ewgLqlZUSrBU34uzh69WSVJRXbHhC/1nTTkICWU1pN5qE3bxtClgGJAv@BFVrlRzDcIILzsCN3/MOSF4XCIrg0LE6k4pbGavDNDBvUGtkIja56tFN8YK@YFS72IhwP45y6MIQjeFAT0IfeFynjHFN5m0iMgF6nUiW5fWC51wQzvQ266fUchcql/jjTSxq7/5qNePUU3ygh2ffj26fWrJd9Z3dilaYoRBdsE6f44wpPOv/UAF2s3xlGpU7ZlzvZv2GM5tl0@a7WoIY07S8 "PowerShell – Try It Online")
[Answer]
# [Java (JDK)](http://jdk.java.net/), 35 bytes
```
i->a->(7+a.ordinal()-i.ordinal())%7
```
[Try it online!](https://tio.run/##fY/BSsRADIbvfYqwUJhqO@hpwWpBEMGDeFjBg3iI7cyS7nSmzKSFIn32Wnfr7oLgJcmffPxJauwxq6vdRE3rPEM9a8nUKHmRR@e9jslI3dmSydmfYWkwBHhGsvAVAbTdp6ESAiPPqXdUQTPPxIY92e37B6DfhmSPAjwuPrcPOLzoN6V26at7svy3XxSg4W6irMCsEOtLlM5XZNGIJKNTncTrKd9ba@dB9OiBbOm8VyXfwNFN9mg6FWZ@OeSMx5I7NP/DAJshsGqk61i282OsxSq@vgqQFXDMVWxX6Wl/ulinoCW2rRnEQScHdR/mx8WRTpJ8WTZGv3GMxukb "Java (JDK) – Try It Online")
Call is done like this:
```
f.apply(MONDAY).applyAsInt(TUESDAY);
```
---
Since the answer above is not of the taste of some, here's a more "Java is verbose" answer that takes strings as input rather than built-in constants:
# [Java (JDK)](http://jdk.java.net/), 113 bytes
```
i->a->(java.util.Comparator.comparing((String s)->java.time.DayOfWeek.valueOf(s.toUpperCase())).compare(a,i)+7)%7
```
[Try it online!](https://tio.run/##XVHLasMwELz7KxZDQGpt0Z4CTWMoKYEeQg5JyaH0sLXlVIktGT1cTPC3u44fSchFO7sz2tmVDlhieEiOjcgLpS0c2pxZkXP2MPNua86KjKVOxlYoeSbjDI2BFQoJJw@gcD@ZiMFYtG0olUggbzmysVrI/dc3oN4b2kkBlkOf154NtupD2rtiFEEK80aEEYYRuc6wUHmBGq3SLO5gqyWDDRgaRtcV3rFapzvOj6zEzPF1Sgyz6rMouF6g4YRSOvTgBANBH6d0Mm1m3YglakiwMjAHyf9gXOPkr5Rs637gbx03PdrxRI54@@v0AJda9GCD1ukBuu523ZukSgM5OwkZK615bF860/GdbhQYW4fZPQ2wqYzlOVPOsqId0abEnzw/GQgjuMRkIv3g6hEMzQJIGRZFVpE@p332ZtrPIBc1pbPBrPbGs/bq5h8 "Java (JDK) – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~10~~ 9 bytes
```
23Y2&md7\
```
Inputs are in reverse order. [Try it online!](https://tio.run/##y00syfn/38g40kgtN8U85v//avWQ0tTilMRKdR0FdbeiTBCrFgA) Or [verify all test cases](https://tio.run/##y00syfmf8N/IONJILTfFPOa/S8j/anXf/LyUxEp1HQUYq5arWj2kNLUYKupWlAkTDS6FKQ1OLCktgglDVQCFYdpAouGpKXlwQ0IySouKMdXDbAQA).
### Explanation
```
% Implicit input: cell array of two strings
23Y2 % Push predefined literal {'Monday', 'Tuesday', 'Wednesday', 'Thursday', ...
% 'Friday', 'Saturday', 'Sunday'}
&m % Indices of membership. Gives a vector of two numbers
d % Consecutive differences. Gives one number
7 % Push 7
\ % Modulus
% Implicit display
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 20 bytes
```
%-Fmx"SMansFr"@d12Q7
```
[Test suite](http://pythtemp.herokuapp.com/?code=%25-Fmx%22SMansFr%22%40d12Q7&test_suite=1&test_suite_input=%22Monday%22%2C+%22Monday%22%0A%22Friday%22%2C+%22Tuesday%22%0A%22Saturday%22%2C+%22Sunday%22%0A%22Tuesday%22%2C+%22Friday%22%0A%22Thursday%22%2C+%22Wednesday%22%0A%22Monday%22%2C+%22Friday%22&debug=0)
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 42 bytes
```
T`aF\hWsMn`d
\w+
$*
,
,7$*
(1*),\1|1{7}
1
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPyQh0S0mI7zYNy8hhSumXJtLRYtLh0vHHEhpGGpp6sQY1hhWm9dycRn@/@@bn5eSWKkDobjcijJBvJDS1GIQNzixpLQIJBBcCpaGiutAlHGFZJQWgfnhqSl5EB1Q4yAKAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
T`aF\hWsMn`d
\w+
$*
```
Convert the day name to a day number. This works as follows: Certain letters in the days are replaced with digits from `0` to `6`. No two digits are adjacent, and the first digit is always the correct digit for the day of the week (but descending, because the inputs are in reverse order). When I ask Retina to convert from decimal to unary, it only sees the first digit, and so gives me the desired result.
```
,
,7$*
```
Add 7 to the second number so that it is always greater than the first.
```
(1*),\1|1{7}
```
Take the difference between the numbers and reduce modulo 7.
```
1
```
Convert to decimal.
Table of day names and their conversions:
```
Sunday Su6d0y 6
Monday 5o6d0y 5
Tuesday Tue4d0y 4
Wednesday 3ed6e4d0y 3
Thursday T2ur4d0y 2
Friday 1rid0y 1
Saturday S0turd0y 0
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~18~~ ~~17~~ ~~15~~ 11 bytes
```
C813%60%Æ7%
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f2cLQWNXMQPVwm7nq///RSuGpKXmpxSmJlUo6CkohGaVFYHYsAA "05AB1E – Try It Online")
[Try all test cases](https://tio.run/##yy9OTMpM/f/f2cLQWNXMQPVwm7nq///R0Uq@@XkpiZVKOgowVqyOQrRSSGlqMVTYrSgTLhxcClMcnFhSWgQXh6oBisM0goXDU1Py4OaEZJQWFWPRAbM2FgA "05AB1E – Try It Online")
Takes input as a list, in order [actual date, incorrect date]
I'm not sure exactly how 05AB1E `C` command works for non binary strings, I just tried some stuff and it worked
uses a hash to map the days to `[4, 3, 2, 1, 0, 6, 5]` (mod 7, since we do mod 7 anyway after the subtraction). The modulos were found by brute-force
```
["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
after C:
[2184, 5008, 18736, 9824, 1968, 9256, 2472]
after 813%:
[558, 130, 37, 68, 342, 313, 33]
after 60%:
[18, 10, 37, 8, 42, 13, 33]
after 7%:
[4, 3, 2, 1, 0, 6, 5]
```
[Answer]
# [J](http://jsoftware.com/), 37 34 bytes
```
7|-&((678 A.i.7)i.7|318+`-/@$3&u:)
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/zWt01TQ0zMwtFBz1MvXMNYG4xtjQQjtBV99BxVit1ErzvyYXV2pyRj5Qk62Cum9@XkpipbpCGpwJkTQGSboVZcIkQ0pTixGyZiDZ4MSS0iKYfHApkmYTkDRMB0gWahBE1hAsm1FaBJcOT03JQzbeGM1lUO3/AQ "J – Try It Online")
* `3&u:` Convert chars to unicode numbers
* `318...$` Reshape cyclically to length 318. I found this by brute forcing a number such that the next step will return unique numbers for each weekday.
* `+`-/` Reduce by placing `+` and `-` alternately between the numbers.
* `7|` Mod 7
* `(678 A.i.7)i.` Find index of above two numbers within `0 6 4 2 1 3 5`, which are the unique numbers the weekdays map to.
* `-&` Subtract after converting both args.
* `7|` Mod 7
## [J](http://jsoftware.com/), staightforward approach, 35 bytes
```
7|-&('MoTuWeThFrSaSu'-:@I.@E.~2&{.)
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/zWt01TTUffNDSsNTQzLcioITg0vVda0cPPUcXPXqjNSq9TT/a3JxpSZn5AN12SoAlealJFaqK6TBmRBJY5CkW1EmTDKkNLUYIWsGkg1OLCktgskHlyJpNgFJw3SAZKEGQWQNwbIZpUVw6fDUlDxk443RXAbV/h8A "J – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
⁽Ae,8ḥ)I%7
```
A monadic Link accepting a list of two lists of characters `[incorrect, actual]` yields an integer in \$[0,6]\$ wrapped in a list.
When run as a full program this accepts a list of two strings and prints the resulting integer (since Jelly's representation of a list containing one element is just the representation of that element).
**[Try it online!](https://tio.run/##y0rNyan8//9R417HVB2LhzuWanqqmv///z9a3a0oMyWxUl1HQT2kNLUYxIwFAA "Jelly – Try It Online")**
### How?
Hashes `"Thursday"` to `1`, `"Wednesday"` to `2`, ..., `"Friday"` to 7, then takes the difference modulo \$7\$.
```
⁽Ae,8ḥ)I%7 - Link: list of lists of characters, [incorrect, actual]
) - for each (day in [incorrect, actual]):
‚ÅΩAe - 17352
8 - eight
, - pair -> [17352, 8]
ḥ - hash (day) using a salt of 17352 and a domain of [1..8]
I - differences
%7 - mod seven -> [(ḥ(incorrect) - ḥ(actual)) mod 7]
- implicit print (of Jelly representation of that)
```
---
### Alternative 10 byter
```
Oḅȷ%⁽€ƈI%7
```
(Same IO as the above.)
[Try it online!](https://tio.run/##y0rNyan8/9//4Y7WE9tVHzXufdS05liHp6r5/8PtQOb//9HR6r75eSmJleo6CjBWLJdOtLpbUSZUNKQ0tRguHJxYUloElQguRSiHKQIKQ3VChDNKi2Di4akpeUgmIayFa4gFAA "Jelly – Try It Online")
Maps `"Thursday"` to `0`, `"Wednesday"` to `1`, ..., `"Friday"` to `6`, then takes the difference modulo \$7\$.
```
Oḅȷ%⁽€ƈI%7 - Link: list of lists of characters, [incorrect, actual]
O - convert to a list of lists of ordinals
»∑ - 1000
·∏Ö - convert from base (1000) to an integer (vectorises)
⁽€ƈ - 4157
% - modulo (4157) (vectorises)
I - differences
%7 - modulo seven
- implicit print (of Jelly representation of that)
```
[Answer]
# [R](https://www.r-project.org/), 78 bytes
```
function(x)diff(which(t(sapply(w,grepl,x))))%%7
w=scan(,'')
M Tu W Th F Sa Su
```
[Try it online!](https://tio.run/##dY@xCoMwGIT3PEVIERPIXii4ujkpOEqMSQ2NiSQG9emtVit16E0f93P3c25p2OwrK2VVz8kig@GDsgZPpFFS4rFVvMUD9qzv9YxH@nSi13Qiq6LoDsbEc2YwjWMCMlgEWMKihSnMGcwD@O3GHKPMmtVBFBVtcH5DQgC4QaY15LarlWHbc/8AoxCvLZxcUkH4nUrRmC@fXRSlTu2QsyG4A8MnTcB3wtFMz6mDJX9v0tmOXFdsFl0zq5Y3 "R – Try It Online")
Well, actually [76 bytes](https://tio.run/##dY89C4MwGIT3/IpgERPIXii4ujkpOEqMSROqieQD9ddbrVbq0Jse7uXu5ezS0tnVRoi6mdNFBM28MhpNuFVCoFEqJpFHjg5DN6ORPC0fOjLhVXF8B2PqGNWIJAkGOSwDrKCEGfSwCOC3GTEU5UavTkSiUgbrNsQYgBukXQeZ6Rul6fbaPcDI@WsLp5dU4G6nirf6y2cXiTKrdiioD/bA8Elj8B1wNJNzqDf4701Y0@Pris0ia2bV8gY) because we could use `M Tu W h F t Su` as a shorter lookup vector, but I feel the obviousness of the code is worth the extra +2.
---
# [R](https://www.r-project.org/), 80 bytes
```
function(a,b,`+`=function(d)sum(utf8ToInt(d)*169^(nchar(d):1-1))%%467)(+a-+b)%%7
```
[Try it online!](https://tio.run/##bY9NC4JAEIbv/goxhJ1cD0JYCV6DDp0SuqWr7qKku7IfhL/etMw8dHueF@adGTmUpFepYCzN@3hghhe6FhwRnOPMy@IlKEGZFhnNDok4cz36NgiPd8SLisjRosAPAFx3F@4BecT38lH263bkXAQf3cHOlWgjJwTL2tikaexCtHnNybRKRdaT0kdc/AZsJzFUzXijJV8kqYz88knWMy39Exv@2aRI1zU9mrrx8pYW8DdnUrSwPl4L/M4Ahhc "R – Try It Online")
Interprets ASCII values in each string as base-169 digits, then evaluates (incorrectly due to floating-point errors, but the incorrectness is taken into account by the program) modulo 467. This converts the days of the week to `5 6 0 1 2 3 4` on the TIO installation of [R](https://www.r-project.org/).
Somehow my own installation of [R](https://www.r-project.org/) evaluates incorrectly differently, requiring interpretation in base-134 and evaluation modulo 978 (to correct the incorrectness), but both programs come out at 80 bytes.
[Answer]
# [Red](http://www.red-lang.org), 70 bytes
```
func[a b][g: func[d][index? find system/locale/days d](g a)-(g b)// 7]
```
[Try it online!](https://tio.run/##TY4/D4IwEMV3PsWlkySSRhcTBt3cXMTEobmh0CuQYDEtTeTTY8P/G@56v77XPktqeJISGOl00N4UQkKOokxhXBSK2ij63UCHCa53HX140xayIa5k70DhoQQZJ6HnMedwwUG3lmRRgQiCE4R2RhFBKPZoTVjZepjo3dYTfXlyG85k5@10kfmdfFGtxhlX3s78TcrsX1q/XQwovrY23ZyQHdmYElhyZaBhi43DHw "Red – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 22 bytes
Going with the numeric modulo would probably be shorter, but I enjoyed this more.
```
£7ÆÐTTX ÅÃb_øX¯3
r- u7
```
Explanation:
```
£7ÆÐTTX ÅÃb_øX¯3
7Æ // Generate the range [0..6] and map it to
ÐTTX // new Date(0, 0, X)
ÅÃ // stringified such as "Sun Dec 31 1899", "Mon Jan 01 1900" etc.
£ // For every input string,
b_ // map to the index of the item that
øX¯3 // contains the first three letters of the input.
r- u7 // Reduce with subtraction, positive modulo 7.
```
[Try it here.](https://ethproductions.github.io/japt/?v=1.4.6&code=ozfG0FRUWCDFw2Jf+FivMwpyLSB1Nw==&input=WyJTYXR1cmRheSIsICJTdW5kYXkiXQ==)
[Answer]
# [R](https://www.r-project.org/), ~~68~~ ~~66~~ 53 bytes
```
function(x)diff(match(x,weekdays(Sys.Date()+0:6)))%%7
```
[Try it online!](https://tio.run/##K/qfkl8en5KZlqZg@z@tNC@5JDM/T6NCEySikZtYkpyhUaFTnpqanZJYWawRXFms55JYkqqhqW1gZaapqamqag43QCNZQ8k3Pw@oUEkHxtDUVFbQtVMw4EJWFFKaWgxR5VaUiaRKwRhFWXAp1KzgxJLSIiR1ZijKoGbowI2FqjJBURWempIHszUko7QIWaWCIXYDUf1g/B8A "R – Try It Online")
Depends on system locale.
*-13 bytes thanks to [@Dominic](https://codegolf.stackexchange.com/users/95126/dominic-van-essen) making it work for edge cases*
[Answer]
# Excel, 69 bytes
```
=LET(s,TEXT(SEQUENCE(7),"dddd"),MOD(MATCH(A1,s,0)-MATCH(B1,s,0)+7,7))
```
Input is in the cells `A1` and `B1`. The formula goes anywhere else.
`LET(s,TEXT(SEQUENCE(7),"dddd")` stores an array of day names so we can reference it using just `s`.
`MATCH(A1,s,0)` & `MATCH(B1,s,0)` finds the input day names in that array.
`MOD(MATCH(~)-MATCH(~)+7,7)` finds the distance from the second day (`B1`) to the first (`A1`).
The `MOD(~+7,7)` is necessary because Mon‚ÜíFri is in the same week but Fri‚ÜíMon spans two weeks.
[](https://i.stack.imgur.com/hUe2F.png)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~28~~ 21 bytes
```
≔⁰ηF²≦⁻﹪⍘Sγ⁸⁴⁹⁰⁷ηI﹪η⁷
```
[Try it online!](https://tio.run/##LYzLCoMwFET3fsXF1Q2kINrqwpUtFIQGCu0PBBNNQBLJo7Rfn4baxTAwhzmT4m6yfE1p8F4vBisKivTFbB1gTYDxbQc3OQdk2kRP4cJ9wCGMRsg3lm11rJvu1JYUmBVxtXjmXuJothgewWmzIKEw59QNIWT33/Me8Cf6nxSFLuM@pWeUXvBPcXU6Vzq81i8 "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 7 bytes thanks to @DominicvanEssen by searching for a suitable base and large modulus which generates descending integers directly instead of needing a look-up table. Explanation:
```
≔⁰η
```
Initialise the accumulator to zero.
```
F²
```
Loop over the two days.
```
≦⁻﹪⍘Sγ⁸⁴⁹⁰⁷η
```
Interpret the day name as a base 95 number (this is the index into printable ASCII). The number is then reduced modulo 84907 and later modulo 7, which was chosen to result in counting downwards from Thursday so that the result is the desired sign. The accumulator is subtracted from this value, so that on the first pass the accumulator becomes the first day and on the second pass it becomes the difference.
```
I﹪η⁷
```
Reduce the difference modulo 7 to account for wrapping past the end of the week.
[Answer]
# [Lua](https://www.lua.org/), 72 bytes
```
a,_,b=io.read(2,"l",2)w="SuMoTuWeThFrSa"print((w:find(a)-w:find(b))/2%7)
```
[Try it online!](https://tio.run/##yylN/P8/USdeJ8k2M1@vKDUxRcNIRylHScdIs9xWKbjUNz@kNDw1JMOtKDhRqaAoM69EQ6PcKi0zL0UjUVMXykrS1NQ3UjXX/P/frSgzJbGSK6Q0tRhIAwA "Lua – Try It Online")
### Explanation
```
a,_,b=io.read(2,"l",2)
```
Take first 2 bytes of each input, discarding rest of first input, and ignoring rest of second. This leaves the remaining input, so running this twice without refreshing the environment (e.g. in a `lua` console) will not work. This could be resolved by adding `,"l"` to the `read` (+4 bytes).
To make this compatible with older Lua versions, change `l` to `*l` (+1 byte).
```
(w:find(a)-w:find(b))/2%7
```
`find` returns the index at which the input was found. `w` being `SuMoTuWeThFrSa`, representing the smallest possible unique letter representation of each day. Find the difference in indexes, divide by two (string length of 14), and modulo by 7.
] |
[Question]
[
# Challenge
Your task is to write a program which, once a second (including immediately when your program is started), prints the elapsed time from the time your program was started.
# Rules
* Time must be printed in `hh:mm:ss` format. (leading zeros for single-digit values)
* The time stamps must be separated by CR, LF, or CRLF. (no leading whitespace)
* A new time must appear every second. (stdout cannot be buffered for a second)
* The behavior of the program if it is run past 23:59:59 is undefined.
* You may use `sleep(1)` even if a specific second may be skipped whenever the overhead to print, calculate, loop, etc. accumulates to a second.
Example output:
```
00:00:00
00:00:01
00:00:02
00:00:04
00:00:05
⋮
```
Note that `00:00:03` is missing here due to processing overhead. The actual skipped values (if any) are of course dependent on implementation and/or system.
Reference implementation in C: (POSIX-compatible systems only)
```
#include <unistd.h> // sleep()
#include <tgmath.h>
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#ifndef __STDC_IEC_559__
#error "unsupported double"
#endif
static_assert(sizeof(double) == 8, "double must have double precision");
#define MAX_PRECISE_DOUBLE ((double)(1ULL << 52))
int main(void) {
time_t start = time(NULL);
if (start == (time_t)-1) return EXIT_FAILURE;
while (1) {
time_t now = time(NULL);
if (now == (time_t)-1) return EXIT_FAILURE;
double diff = difftime(now, start);
if (isnan(diff) || diff < 0) return EXIT_FAILURE;
if (diff > MAX_PRECISE_DOUBLE) return EXIT_FAILURE;
unsigned long long seconds = diff;
unsigned long long h = seconds / 3600;
seconds %= 3600;
unsigned long long m = seconds / 60;
seconds %= 60;
unsigned long long s = seconds;
(void)printf("\r%02llu:%02llu:%02llu", h, m, s);
(void)fflush(stdout);
(void)sleep(1);
}
}
```
# Winning criteria
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code in bytes win!
[Answer]
# [Operation Flashpoint](https://en.wikipedia.org/wiki/Operation_Flashpoint:_Cold_War_Crisis) scripting language, ~~174~~ 171 bytes
```
s=""
#l
t=_time
t=t-t%1
a=t%60
c=(t-a)/60
b=c%60
c=(c-b)/60
d=""
e=d
f=d
?a<10:d=0
?b<10:e=0
?c<10:f=0
s=s+format["%1%2:%3%4:%5%6\n",f,c,e,b,d,a]
hint s
@t+1<_time
goto"l"
```
**In action:**
[](https://i.stack.imgur.com/NzVes.jpg)
[](https://i.stack.imgur.com/H8pIR.gif)
**158 bytes, if the previous time is overwritten by the next time:**
```
#l
t=_time
t=t-t%1
a=t%60
c=(t-a)/60
b=c%60
c=(c-b)/60
d=""
e=d
f=d
?a<10:d=0
?b<10:e=0
?c<10:f=0
hint format["%1%2:%3%4:%5%6",f,c,e,b,d,a]
@t+1<_time
goto"l"
```
Technically, no carriage return is used, so I'm not sure if this version confines to the rules.
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + coreutils, ~~28~~ 26 bytes
```
date -s0|yes date +c%T|sh
```
The unprintable character between `+` and `%` is an *ESC* byte.
**This sets the system time to 00:00:00** and thus requires root privileges. It also assumes that the timezone is UTC and that no other processes will interfere with the system clock.
Each new timing resets the terminal, thus overwriting the previous one.
---
# [Bash](https://www.gnu.org/software/bash/) + coreutils, ~~38~~ 29 bytes
```
date -s0|yes date +%T|sh|uniq
```
The same restrictions as before apply. Each new timing is shown on a new line.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~17~~ 16 bytes
```
`Z`12L/13XOD1Y.T
```
Try it at [**MATL Online!**](http://matl.io/?code=%60Z%6012L%2F13XOD1Y.T&inputs=&version=20.4.2)
### How it works
```
` % Do...while loop
Z` % Push seconds elapsed since start of program
12L % Push 86400 (predefined literal)
/ % Divide. This transforms seconds into days
13XO % Convert to date string with format 13, which is 'HH:MM:SS'
D % Display
1Y. % Pause for 1 second
T % True. Used as loop condition for infinite loop
% End loop (implicit)
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 51 bytes
Full program body.
```
s←⎕AI
1↓∊':'@1∘⍕¨100+3↑0 60 60 1E3⊤3⊃⎕AI-s
⎕DL 1
→2
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM9uCS/oDyxJDnjf/GjtgmP@qY6enIZPmqb/KijS91K3cHwUceMR71TD60wNDDQNn7UNtFAwQyMDF2NH3UtAeJmsB7dYi4g7eKjYMj1qG2SEcjk/3CjAQ "APL (Dyalog Unicode) – Try It Online") (Press Ctrl+Enter to start, and again to stop.)
`⎕AI` **A**ccount **I**nformation (user ID, compute time, connect time, keying time)
`s←` assign to `s` (for **s**tart time)
`⎕AI-s` subtract `s` from `⎕AI`
`3⊃` pick the third element (connect time in milliseconds)
`0 60 60 1E3⊤` convert to this mixed-radix
`3↑` take the first 3 (drops the milliseconds)
`100+` one hundred added to each (to pad zeros)
`':'@1∘⍕¨` amend with a colon at the first character of the string representation of each
`∊` **ϵ**nlist (flatten)
`1↓` drop the first colon (and implicitly print to stdout)
`⎕DL 1` **D**e**l**ay one second
`→2` go to line number two
[Answer]
# [R](https://www.r-project.org/), ~~59~~ 44 bytes
`F` in R defaults to `FALSE`, but it's a regular variable and can be redefined. When used in arithmetic, `FALSE` is coerced to `0`. Asking for `F+1` therefore returns `1`. We assign `F` to be `F+1`, format it nicely, print, and wait for one second. Continues indefinitely.
```
repeat{print(hms::hms(F<-F+1))
Sys.sleep(1)}
```
Doesn't work on TIO (due to lack of the `hms` package), but here's a sample output from my machine:
```
00:00:00
00:00:01
00:00:02
00:00:03
00:00:04
00:00:05
00:00:06
00:00:07
00:00:08
00:00:09
00:00:10
00:00:11
00:00:12
00:00:13
```
[Answer]
# [bash](https://www.gnu.org/software/bash/) + sleep + date, ~~also 50~~ ~~49~~ ~~47~~ ~~46~~ ~~45~~ 41 bytes
```
while date -ud@$[s++] +%T;do sleep 1;done
```
To take a lap time, quickly hit ^C, run this and then rerun the above:
```
laps=("${laps[@]}" $s) ; echo ${laps[-1]}
```
To reset:
```
s=0; unset laps
```
The $[s++] syntax appears to still work, but is no longer (AFAICS) documented in the `bash` man page. And it's still a byte shorter than using the for((...)) loop, once I removed the quotes around it.
[Answer]
# [Swift](https://swift.org), 144 bytes
```
import Foundation
let s=Date()
while 1>0{let d=Int(-s.timeIntervalSinceNow)
print(String(format:"%02d:%02d:%02d",d/3600,d/60%60,d%60))
sleep(1)}
```
## Explanation
```
import Foundation // Import `Date` and `sleep()`
let s = Date() // Get the time at the start of the program
while 1 > 0 { // While 1 > 0 (forever):
let d = Int(-s.timeIntervalSinceNow) // Calculate time difference
print(String(format:"%02d:%02d:%02d", // Print the time
d/3600,d/60%60,d%60))
sleep(1) // Sleep one second
}
```
[Answer]
# JavaScript (ES6), 99 bytes
```
f=_=>console.log(new Date(new Date-d).toUTCString().slice(17,25))
f(d=Date.now(setInterval(f,1e3)))
```
[Answer]
# [Matlab](https://www.mathworks.com/products/matlab.html) (R2016b), 50 bytes
```
t=now;while 1,disp(datestr(now-t,13)),pause(1),end
```
Explanation:
```
t=now; % Stores the current time
while 1 % Loops forever
disp(datestr(now-t,13)) % Computes the difference since the program started
% And prints with format 13 ('HH:MM:SS') - this may change between versions
pause(1) % Waits one second
end
```
Alternate version (50 bytes too :P):
```
now;while 1,disp(datestr(now-ans,13)),pause(1),end
```
[Answer]
# [Julia 0.6](http://julialang.org/), ~~75~~ 68 bytes
```
for h=0:23,m=0:59,s=0:59;@printf "%02i:%02i:%02i
" h m s;sleep(1)end
```
[Try it online!](https://tio.run/##yyrNyUw0@/8/Lb9IIcPWwMrIWCcXSJla6hSDKWuHgqLMvJI0BSVVA6NMKzjBpaSQoZCrUGxdnJOaWqBhqJmal/L/PwA "Julia 0.6 – Try It Online")
With sleep(1) allowed, simple nested for-loops are shorter than using Julias built-in time handling methods.
**Old solution without sleep(1) using DateTime**
```
t=now()-DateTime(0);Timer(x->println(Dates.format(now()-t,"HH:MM:SS")),0,1)
```
`t` is the amount of time passed from 'day 0' to when the program is started.
`now()-t` is a *moment in time*, which is then formatted using `Dates.format()`.
`t0=now(); ...; now()-t0` would yield a *time difference*, that cannot be used with `Dates.format()`.
The timing itself is trivial with the build-in `Timer`.
[Answer]
# [Python 2](https://docs.python.org/2/), 85 bytes
```
import time
t=0
while 1:print(":%02d"*3)[1:]%(t/3600,t/60%60,t%60);time.sleep(1);t+=1
```
# Credits
* Reduced from 89 bytes to 88 by [wnnmaw](https://codegolf.stackexchange.com/users/30170/wnnmaw)
* Reduced from 88 bytes to 85 by [Erik the Outgolfer](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer)
[Answer]
# JavaScript (ES6), 88 bytes
```
f=_=>console.log(new Date(i++*1e3).toUTCString().slice(17,25))
f(i=0,setInterval(f,1e3))
```
Essentially the same approach as [@darrylyeo's answer](https://codegolf.stackexchange.com/a/151800/72685), but works for all timezones and uses a slightly different way to get to 0.
[Edit] Darryl's answer has been fixed. This is still shorter, though.
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 82 + 7 = 89 bytes
```
0\!
:/+1oan~?=3ln?$0(a:o":"n~?=4ln?$0(a:ro":"n~?=5ln?$0(a:,*a6-}:%*a6:,*a6-}:%*a6:
```
[Try it online!](https://tio.run/##S8sszvj/3yBGkctKX9swPzGvzt7WOCfPXsVAI9EqX8lKCSRgAhMogomYwkR0tBLNdGutVIEUCvv///@6JXoGhkamAA "><> – Try It Online")
+7 bytes for using the flag `-t.0125` to make the each instruction take 1/80th of a second. Each loop has 80 instructions, making each loop one second long. Because of computation time, this is actually longer in practice.
I actually had to buffer this all the way up to 100 until I saw @Not A Tree's [answer](https://codegolf.stackexchange.com/a/152144/76162) which had 7 byte better way than mine to generate the hours and minutes, trimming it below 80. They also inspired the use of `\/` which are executed twice per loop.
### How It Works
```
0\...
./...
Initialises the stack with a 0 to represent the time
0\!
:/....................................................,*a6-}:%*a6:,*a6-}:%*a6:
Puts the hours, minutes and seconds in the stack
0\!
:/....n~?=3ln?$0(a:o":"n~?=4ln?$0(a:ro":"n~?=5ln?$0(a:...
Print out the hours, minutes, seconds separated by colons.
If the number is below 0, print a leading 0.
If the number is not, then there is an extra 0 on the stack, which is popped.
0\!
./+1oa...
Print a newline and increment the counter
And restart the loop
```
### Bonus:
A one line version of the same size, 80 + 9 bytes:
```
0::6a*%:}-6a*,:6a*%:}-6a*,:a(0$?nl5=?~n":"or:a(0$?nl4=?~n":"o:a(0$?nl3=?~nao1+>!
```
This uses the `-a` flag to add ticks for skipped instructions.
[Answer]
## PHP 4+, ~~70~~ 64 bytes
```
$x=time();while(1){sleep(1);echo date('H:i:s',time()-$x)."\n";}
```
## PHP 5.3+, ~~69~~ 63 bytes
```
$x=time();a:sleep(1);echo date('H:i:s',time()-$x)."\n";goto a;
```
[Answer]
# [Python 3](https://docs.python.org/3/), 112 bytes
Assuming using 1-second delays is ok, even if it (rarely) might skip a second.
```
from time import*;a=0
while 1:d=divmod;m,s=d(a,60);print(":".join(f"{k:02d}"for k in(*d(m,60),s)));a+=1;sleep(1)
```
[Answer]
# VBA, 90
```
t=0:while(1):?format(t,"hh:mm:ss"):t=t+timeserial(0,0,1):q=timer:while q-timer<1:wend:wend
```
run in immediate window:expected failure point somewhere around 23 million years (floating point resolution fails ~8.5e9 days)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 23 bytes
```
:⁽½c,60;%60d⁵j”:ṄœS1ṛ‘ß
```
[Try it online!](https://tio.run/##AS8A0P9qZWxsef//OuKBvcK9Yyw2MDslNjBk4oG1auKAnTrhuYTFk1Mx4bmb4oCYw5///w "Jelly – Try It Online")
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), ~~110~~ ~~87~~ 86 bytes
```
BEGIN{for(;;i++){printf("%02d:%02d:%02d\n",i/3600%60,i/60%60,i%60);system("sleep 1")}}
```
Does not work in TIO.
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 37 bytes
```
{∇⍵+×⎕DL 1⊣⎕←1↓∊':'@1∘⍕¨100+⍵⊤⍨3⌿60}0
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pRR/uj3q3ah6c/6pvq4qNg@KhrMZD1qG2C4aO2yY86utSt1B0MH3XMeNQ79dAKQwMDbaDqR11LHvWuMH7Us9/MoNbg/38A "APL (Dyalog Unicode) – Try It Online")
Full program.
Pretty similar to Adám's answer, however independently written and uses a non-`⎕AI`-based approach.
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + coreutils + GNU date, 50 bytes
```
o=`date +"%s"`;yes date +%X -ud\"-$o sec\"|sh|uniq
```
Inspired by @Dennis, this solution doesn't require the time to be changed.
It store stores the initial offset from now to the UNIX epoch (1 Jan 1970 00:00:00 UTC), in 'o', and then displays [-ud options] (the current time - offset), in UTC date, but only [+%X option] HH:MM:SS. This should work in countries where the current time-zone isn't UTC.
[Answer]
# [Clean](https://clean.cs.ru.nl), ~~173~~ ~~172~~ 168 bytes
```
import StdEnv,System.Time
$n i#i=(i/60^n)rem 60
=(i/10,i rem 10)
f i w#(Clock j,w)=clock w
#j=j/1000
|j>i=[j:f j w]=f i w
Start w=[($2i,':',$1i,':',$0i,'
')\\i<-f -1 w]
```
This one only works under the Windows Clean bundles.
Add 3 bytes if you want it to work under Linux, as Clean's `CLK_PER_TICK :== 1000000` on \*nix. If you want it to be cross-platform, add 8 bytes instead, as you need to use `CLK_PER_TICK` instead of the value it's set to. (*TIO link is larger due to above*)
[Try it online!](https://tio.run/##LY1Bi8IwFITv@RUPWmgLqaZ78CAbL@pB8LDQvekuZGMiLyaptHGD4G83W8vOZeaDGUZaJXxy3elmFTiBPqG7dn2ANpy2/pe29yEoN/tEp0juATPkJc4X7NtXvXKwYOTFDaMIL25YRTQgxKxc205ewNBYcTnFSDLDzdidRB5mhfxglhoMxC8@rUgbxPgd@aHM35AWy4Lmzb@z0UlRHY/4Xmuom3GU0lNqK85Dqn9Svdunzd0Lh3KY4MOKoLve/QE "Clean – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 69 + 3 (`TZ=`) = 72 bytes
```
from time import*;s=time()
while 1:print ctime(time()-s)[11:19]+'\r',
```
This runs in a continuous loop, without sleeping, updating the time on the same line rather than printing a new line each second. (Still allowed by the rules, I hope.)
This slightly longer version (72+3=75 bytes) prints on a new line every second instead:
```
from time import*;s=time()
while 1:print ctime(time()-s)[11:19];sleep(1)
```
Both of these require you to be in the UTC timezone. On Linux you can achieve this by setting the `TZ` environment variable. E.g. `TZ= python`.
[Answer]
# [><>](https://esolangs.org/wiki/Fish), ~~106 bytes~~ 82 + 9 = 91 bytes
*Thanks to Jo King for suggesting the `-a` flag! Check out [their answer](https://codegolf.stackexchange.com/a/152168/66104) too.*
```
0v+1oan<n0/
:/<</?(a:,*a6-}:%*a6:,*a6-}:%*a6:\\
n<n0/<</?(a:ro":"
":"n<n0/<</?(a:o
```
[Try it online!](https://tio.run/##S8sszvj/36BM2zA/Mc8mz0Cfy0rfxkbfXiPRSkcr0Uy31koVSKGwY2K4wCqhyorylayUuIAYWTD/////uiV6BoZGpv91EwE "><> – Try It Online") (but you'll have to wait for the 60 second timeout).
I got to use a feature of ><> that I've never needed before: this code requires the flag `-t.0125`, which sets the execution speed to 0.0125 seconds per tick, or 80 ticks per second. There's also the `-a` flag, which makes whitespace count as a tick (in some cases — the interpreter is a bit weird about this).
Basically, the code keeps a counter that's incremented each time the fish goes through the loop, and the rest of the loop converts the counter to `hh:mm:ss` format and prints it. The loop takes exactly 80 ticks.
This should work in theory, but in practice, each tick is slightly longer than 0.0125 seconds, because of computation time. Changing the `\\` on the second line to `<<` gives more accurate timings on TIO.
You can also watch the code in action at the [fish playground](https://fishlanguage.com/playground), except that this interpreter treats whitespace slightly differently from the official interpreter. Alternatively, you can remove the flags on TIO to make the code run at top speed, to verify the behaviour for times after one minute.
[Answer]
# Java 8, full program, 150 bytes
```
interface M{static void main(String[]a)throws Exception{for(int i=0;;Thread.sleep(1000))System.out.printf("%02d:%02d:%02d%n",i/3600,i/60%60,i++%60);}}
```
[Try it here (times out after 60 seconds, so I've set the sleep to 1 to see more output).](https://tio.run/##PcyxDoIwFIXhV2lISNqgWDVhkDg6OuFmHBp6kYvSNu0VNYRnr51czjedf1CTWlsHZtCPGNEQ@E61wM5zIEXYssmiZqNCwxvyaO7XmxLUe/sO7PRpwRFaM3fW8/RleJR1fek9KF2GJ4DjWyGabyAYS/ui0qUCdTzL5U4f/pObbIWbfSVlopJ5lSyKhKiXJcYf)
**Explanation:**
```
interface M{ // Program:
static void main(String[]a) // Mandatory main-method
throws Exception{ // Mandatory throws for Thread.sleep
for(int i=0; // Start at 0
; // Loop indefinitely
Thread.sleep(1000)) // After every iteration: Sleep for 1 sec
System.out.printf("%02d:%02d:%02d%n",
// Print in the format "HH:mm:ss\n":
i/3600,i/60%60,i++%60); // The hours, minutes and seconds
// (and increase `i` by 1 afterwards with `i++`)
// End of loop (implicit / single-line body)
} // End of mandatory main-method
} // End of program
```
---
# Java 8, function, 94 bytes
```
v->{for(int i=0;;Thread.sleep(1000))System.out.printf("%02d:%02d:%02d%n",i/3600,i/60%60,i++%60);}
```
[Try it here (times out after 60 seconds, so I've set the sleep to 1 to see more output).](https://tio.run/##ZU89a8MwEN37Kw6DQSKJo7TgISLdOjaLS5bQQZXlRKkiCUl2Gox/u3uuS5fC3T0OHu/jIjqxcl7ZS/05SiNihFehbf8AoG1SoRFSwX56ATqna5DkMEFH0zm4W4SXL6l80s5y5Ay4ODGJpCXswcIOxm713DcuENQDvWOcv52DEnURjVKebCit7jGpa@HaVPiArIZkOXust38nt9lSr59KxhBKlpeIiwUC5cPIZ0/ffhj0/LX@iXrFIqRKKHk6voP4l3huZQtJbGsMnQsM4zc)
**Explanation:**
```
v->{ // Method with empty unused parameter and no return-type
... // Same as the program above
} // End of method
```
Here is a small gif to see it works as intended when 1000 ms are used:
[](https://i.stack.imgur.com/lp5uI.gif)
[Answer]
# PHP, ~~59~~ 48 bytes
```
while(1){sleep(1);echo date('H:i:s',$i++)."\n";}
```
Inspired by [Darren H's answer](https://codegolf.stackexchange.com/questions/151772/implement-a-simple-stopwatch/151805#151805).
*Old version* :
```
<?php while(1){sleep(1);echo date('H:i:s',$i++-3600)."\n";}
```
[Answer]
# [Shell](https://en.wikipedia.org/wiki/Unix_shell), 177 bytes
Notice that this is not entirely POSIX conformant because it uses `date +%s`, which is a common `date` expansion.
```
a=`date +%s`;while true;do b=`date +%s`;s=`expr $b - $a`;h=`expr $s / 3600`;s=`expr $s % 3600`;m=`expr $s / 60`;s=`expr $s % 60`;printf '\r%02d:%02d:%02d' $h $m $s;sleep 1;done
```
[Answer]
# Ruby, ~~192~~ 117 bytes (Credit to Dada)
```
t=Time.now
loop do
m,s=(Time.now-t).to_i.divmod(60)
h,m=m.divmod(60)
printf"%02d:%02d:%02d
",h,m,s
sleep 1
end
```
## How does it work?
Going to use the expanded version (Conversion to a time is given as a separate function and uses a different output format):
```
def format_secs(s) # Converts the value in seconds to the required format
mins, secs = s.divmod(60) # divmod returns the quotient and the remainder of a number
hours, mins = mins.divmod(60)
[hours,mins,secs].map { |e| e.to_s.rjust(2,'0') }.join ':'
=begin
[hours,mins,secs] -Creates a new array using the values allready provided for hours, minutes and seconds
.map { - Creates a new array based on a operation on each of an array's values
.to_s.rjust(2,'0')} - Turns the number into a string, and then adds "0" if needed to make the timer's result at least two digits
.join ':' - Combines the result of the operation into a single string with a ":" in between the two numbers
=end
end
t = Time.now # Saves the time at the program's (Rough) start
loop do
puts format_secs((Time.now - t).to_i) # Returns the result of the "format_secs" operation on the difference between the two times (in seconds) converted to a pure integer
sleep 1 # Waits for one second
end
```
[Answer]
# APL NARS, ~~109 63~~ 57 chars
```
q;t
t←0
{∊⍵,¨':: '}{1<⍴x←⍕⍵:x⋄'0',x}¨(3⍴60)⊤⌊t+←⎕DL 1⋄→2
```
3+3+48+3=57 (seen the others Apl solutions too)
```
{1<⍴x←⍕⍵:x⋄'0',x}
```
convert the INT ⍵ in the string of digits in a way if the lenght of that string is 1 than add one '0' in front of it
```
{∊⍵,¨':: '}
```
combine array in ⍵ with the array ':: '
```
00:00:01
00:00:02
00:00:03
00:00:04
00:00:05
00:00:06
00:00:07
00:00:08
00:00:09
```
[Answer]
# [q/kdb+](http://kx.com/download/), 40 bytes
**Solution:**
```
.z.ts:{-1($)18h$a+:1};a:-1;(.)"\\t 1000"
```
**Example:**
```
q).z.ts:{-1($)18h$a+:1};a:-1;(.)"\\t 1000"
q)00:00:00
00:00:01
00:00:02
00:00:03
00:00:04
00:00:05
```
**Explanation:**
There are three commands being executed here:
1. `.z.ts:{-1($)18h$a+:1}; / override timer function`
2. `a:-1; / initialise variable a to -1`
3. `(.)"\\t 1000" / start the timer with 1000ms precision`
Breakdown of the timer function:
```
.z.ts:{-1 string 18h$a+:1} / ungolfed timer function
{ } / lambda function
a+:1 / add 1 to variable a
18h$ / cast to seconds
string / cast to string
-1 / write to stdout
.z.ts: / assign this function to .z.ts
```
**Bonus:**
Alternative 1 for **41 bytes**:
```
a:.z.t;.z.ts:{-1($)18h$x-a};(.)"\\t 1000"
```
Alternative 2 for **26 + 7 bytes = 33 bytes**
```
.z.ts:{-1($)18h$a+:1};a:-1
```
and adding `-t 1000` as arguments to the q binary.
[Answer]
# Powershell, 52 bytes
Newest (52 Bytes):
```
For($a=0){date -H:0 -Min:0 -S:$a -U:%T;Sleep 1;$a++}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/3y2/SEMl0dZAszolsSRVQdfDykBB1zczD0QFW6kkKuiGWqmGWAfnpKYWKBhaqyRqa9f@/w8A "PowerShell – Try It Online")
It no longer requires admin, the solution is actually much simpler than before.
~~Using .Net (61 Bytes):~~
```
[DateTime]::Now.Date|set-date;For(1){get-date -U %T;Sleep(1)}
```
The .Net version exploits that Now.Date strips out the time, so it outputs 12:00 AM as the time. See: <https://stackoverflow.com/a/9630340/8303961>
~~Using only built-in commandlets (66 Bytes):~~
```
get-date -H:0 -Min:0 -S:0|set-date;For(1){get-date -U %T;Sleep(1)}
```
~~Both versions have to be run in a elevated powershell window due to changing the system time with set-date cmdlet.~~
] |
[Question]
[
**This question already has answers here**:
[Display number of occurrences for every character in an input string](/questions/19068/display-number-of-occurrences-for-every-character-in-an-input-string)
(66 answers)
Closed 4 years ago.
Given a string of printable ASCII, output the frequency of each character in that string.
## The Challenge
* Input is given as a string of printable ASCII characters (decimal `[32-126]` inclusive).
* Output the frequency of each character, in ASCII order.
* The output must have a format similar to `[character][separator][count]`. Provided that there is a single, non-newline separating string between the character and its frequency, it is a valid output.
* Output can be a single string, multiple strings, list of 2-tuples, array of tuples, etc.
* Input and output can be given [using any convenient method.](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods)
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest in bytes wins.
## Sample I/O
```
abcd
//outputs
a: 1
b: 1
c: 1
d: 1
```
```
Over 9001!
//outputs
[ 1
! [ 1
0 [ 2
1 [ 1
9 [ 1
O [ 1
e [ 1
r [ 1
v [ 1
```
```
--<-<<+[+[<+>--->->->-<<<]>]<<--.<++++++.<<-..<<.<+.>>.>>.<<<.+++.>>.>>-.<<<+.
//outputs (as 2-tuples)
(+,14),(-,13),(.,13),(<,21),(>,13),([,2),(],2)
```
```
Su3OH39IguWH
//outputs (as 2d array)
[[3,2],[9,1],[H,2],[I,1],[O,1],[S,1],[W,1],[g,1],[u,2]]
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~50, 43~~, 41 bytes
```
lambda s:{c:s.count(c)for c in sorted(s)}
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHYqjrZqlgvOb80r0QjWTMtv0ghWSEzT6E4v6gkNUWjWLP2f0FRJlAuTUMpMSk5JVFJU/M/AA "Python 3 – Try It Online")
[Answer]
# [Ohm v2](https://github.com/nickbclifford/Ohm), 2 bytes
```
SÖ
```
[Try it online!](https://tio.run/##HYqxDcBADAJ3@daC4mvkJVK@vv8myjZZKIM5tgEhneA594y4vjdiAIJky5bMAXhb0vYtAZS1mMCsZLpX8sMamlBoHD8 "Ohm v2 – Try It Online")
```
implicit input
S sort string
Ö run-length encoding
implicitly print
```
[Answer]
# [Python 3](https://docs.python.org/3/), 41 bytes
```
lambda s:sorted({*zip(s,map(s.count,s))})
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHYqji/qCQ1RaNaqyqzQKNYJzcRSOol55fmlegUa2rWav4vKMrMK9FI01BKTEpOSVTS1PwPAA)
[Answer]
# [J](http://jsoftware.com/), 13 bytes
```
({.;#)/.~@/:~
```
[Try it online!](https://tio.run/##PcqxCsJADAbgvU8RdIgl5q/zmYaC4OTkWjpotYiLDyD01c/cDSb5Ax/JO2/AC/WJmPZ0oBRR0Ol6OefdF8dt22EdurTmtmme8@tDC/HtPj/4L1VTMxllNHFV9dpmNvlkpgqTWgggVhjuZeIH5VClhQLOPw "J – Try It Online")
* `@/:~` sort the input and...
* `/.~` partition it into groups of like items. Apply the following to each group...
* `({.;#)` take the first element `{.` and link it `;` to the number of items in the group `#`
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 2 bytes
```
ọo
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3w/@Hu3vz//6OVEpOSU5R0lPzLUosULA0MDBWBHF1dG10bG@1o7WgbbTtdXV07MLSxsYm1i7Wx0dXVs9EGAz0gRw9IAPl6dnYgBFSjB5IA83RBXG09oIHBpcb@HsaWnuml4R5KsQA "Brachylog – Try It Online")
```
ọ Occurrences,
o sorted.
```
It's essentially the same as using an RLE builtin with the sorting requirement, but if the output could be in any order it would just be `ọ`.
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 5 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Anonymous tacit prefix function, returning a two-column table, which by default prints with space as separator between character and count, and line break after each entry.
```
,∘≢⌸∧
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/X@dRx4xHnYse9ex41LH8f9qjtgmPevse9U319H/U1XxovfGjtolAXnCQM5AM8fAM/p@moJ6YlJyizqWrq8sF5PiXpRYpWBoYGCrChXR1bXRtbLSjtaNttO2AYnZgaGNjE2sXa2Ojq6tnow0GekCOHpAA8vXs7EAIqEYPJAHm6YK42npwY4NLjf09jC0900vDPdQB "APL (Dyalog Extended) – Try It Online")
`,` character followed
`∘` by
`≢` its tally
`⌸` for each unique character
`∧` in ascending order
[Answer]
# [Haskell](https://www.haskell.org/), ~~52~~ 49 bytes
*-3 bytes thanks to cole!*
```
import Data.List
map((,).nub<*>length).group.sort
```
[Try it online!](https://tio.run/##DcqxCoAgEADQ3a@4oqEipMYgmxqDvuECK0lNzrPft978Loy3tjZn48JDDAsyytVEFodyGOq6a6RP@9TOVvuTr0ae9KQg45@zcGg8KAhkPEMFB5TbqwnGvh@KMn8 "Haskell – Try It Online")
I know this is too long (especially that import), but I'm new at Haskell golfing and hoping to get better! Outputs as a list of tuples of `(character, count)` (note the `character` is `String`, not a `Char`).
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 15 bytes
```
*.comb.Bag.sort
```
[Try it online!](https://tio.run/##HYoxC4MwFIT3/Ip0kdbwHhahIL5m6GQnhw4dxCHaKAVTJdaCvz5NcnccfNwt2k4XZ3aeDPzqUuxn0@FNjbjO9utKNr0/ekWjlmOKyYCr2k9Odf2L1T9teZFl5wMDICASjWhISACQ0UTUypYIAElEoQf05RmlDPEfDEMkCCiQPba8rvLiPm7P6g8 "Perl 6 – Try It Online")
Anonymous code block that takes a string and returns a list of pairs, where the key is the character and the value is the number of occurrences.
### Explanation:
```
*.comb # Decompose into characters
.Bag # Group into unordered bag of character => occurrences
.sort # Sort by character
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), ~~8~~ 4 bytes
```
$e`p
```
[Try it online!](https://tio.run/##S85KzP1f9F8lNaHg///EpOSURAA "CJam – Try It Online")
-3 bytes thanks to Jonah, and -1 byte from rule interpretation.
A perfect challenge for CJam. ~~I had hoped that the RLE encode operator would output `[char, count]`, but the order was reversed. Otherwise it would have been a 5-byter.~~ After Jonah's comment, I switched the order of the output. ~~I'm not sure if the first read should be counted, since the standard rules permit input to be on the stack at the start of the program. If that's the case, this answer is one byte shorter.~~ From [this meta discussion](https://codegolf.meta.stackexchange.com/a/8493/79994), I concluded that the read could be placed in the header. Otherwise I could modify the script to be a function without changing the byte count.
## Explanation
```
$ sort string
e` RLE-encode (transforms "aabc" to [[2, "a"], [1, "b"], [1, "c"]]
p print
```
**Open question**: would something [like this](https://tio.run/##S85KzP1fVP1fJTXhf21dwf/EpOSURAA) be allowed if transforming the answer to a function, or should the brackets be included in the byte count?
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 3 bytes
```
r8S
```
[Try it online!](https://tio.run/##K6gsyfj/v8gi@P9/Jf@y1CIFSwMDQ0UlAA "Pyth – Try It Online")
Simply run-length encodes (`r8`) the sorted (`S`) input. Output is a list of tuples of `[frequency, character]`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~6~~ 3 bytes
```
ṢŒr
```
[Try it online!](https://tio.run/##y0rNyan8///hzkVHJxX9P9zu/v9/cKmxv4expWd6abgHAA "Jelly – Try It Online")
A monadic link taking the string as its argument. Returns a list of lists, each one containing the character and count. The footer formats this as a grid.
[Answer]
# [Bash](https://www.gnu.org/software/bash/), ~~27~~ ~~22~~ 20 bytes
```
fold -1|sort|uniq -c
```
[Try it online!](https://tio.run/##Lc3BCsIwDAbg@54ityrlD3j/yYuMHbbOMkEsOj1Zn722ZUlI@Eggy7xvJcrpLN8S030VXPKeXu/8edyeglB@w3ANWxI3L2F1kiUedscECNKPfqQ3ANaT5GQTCSh9D63Q2qrVrFW90bboQqPX/qH8AQ "Bash – Try It Online")
*-5 bytes thanks to Neil*
*-2 bytes thanks to Digital Trauma*
[Answer]
# [PHP](https://php.net/), 57 bytes
```
foreach(count_chars($argn,1)as$a=>$b)echo chr($a)," $b
";
```
[Try it online!](https://tio.run/##NY7BasMwDIbvfgotGNLgyLT0VKK6p0IGgxR22CELxfGy@pQEO9ll7Nkzx9kkIfRJ@oVGOy50Ge3IGJ86P3k4Q80AUt2ajzRfq@qrc3Da7w9PGyMSEola1CQUIqroRNSohghRkogmA8iQAkul1gg7ch1EwhWF3G6@zseqPJ6eH/NbmbKmYOxzcJ02dgd/b2kPXLtHDxl8B0Vn7LA1criVt/u1eimWf40Z5n66G6ud3207h0x7rs@Kt1lUGuvCJMsT4C1LiiU2k/c@KdjP8gs "PHP – Try It Online")
Input via `STDIN`, run with `php -F`:
```
$ echo Su3OH39IguWH|php -F cc.php
3 2
9 1
H 2
I 1
O 1
S 1
W 1
g 1
u 2
```
Fun fact: this challenge is basically the [**Example 1**](https://www.php.net/manual/en/function.count-chars.php#refsect1-function.count-chars-examples) on the PHP docs for [`count_chars()`](https://www.php.net/manual/en/function.count-chars.php#refsect1-function.count-chars-examples).
[Answer]
# T-SQL 2008 query, 130 bytes
```
DECLARE @ varchar(2000)='kabcdda'
SELECT w,sum(1)FROM(SELECT
substring(@,number+1,1)FROM
spt_values WHERE type='P'and
number<len(@))x(w)GROUP BY w
ORDER BY ascii(w)
```
**[Try it online](https://rextester.com/HBX36121)**
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 94 91 bytes
Thanks to Ourous and ceilingcat for their suggestions.
To get the non-newline separator, I'm making use of the fact that negative numbers get a "-" for free! :-)
```
f(char*s){char c[255]={},i=31;for(;*s;)c[*s++]--;for(;++i>0;)c[i]&&printf("%c%d ",i,c[i]);}
```
[Try it online!](https://tio.run/##LY3BboMwDEDv/QoPqVWIcUSHeqiS5tydethhB8SBpUAjbawK0B0Q354ldLaV@D1bsqHOGO9bZm6140M6xx9M@Xo4VKd5yeyp2Mv2xzHJB5makg@IFdFTIVqdR2ur3e7ubD@2LNma7RWSzGZRp3LxQcN3bXsWm9p1JoP1COcBHinMG4Dfm/1qGEf8V9Cy51TCfRoHliShWzZh0zXj5HrI5Wbxvv40V395NA6Oeb5/8USKlMISS4WaiPSaSqlKV0oRCYVriAAiPIGF1rHCjoiDlSgiCv8@FZdzcXzrpo/zHw "C (gcc) – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~27~~ ~~22~~ ~~21~~ 19 bytes
```
$args[0]|sort|group
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/XyWxKL042iC2pji/qKQmvSi/tOD///8a0ckZiUXRsbHqwaXG/h7Glp7ppeEeGeqaAA "PowerShell – Try It Online")
Exactly what it says on the tin. Takes input `$args[0]` via splatting (manifests on TIO as a `[char[]]`), `sort`s it, then `group-object` it into a grouping.
*-8 bytes thanks to mazzy*
[Answer]
# JavaScript, 58 bytes
```
s=>[...s].sort().flatMap(c=>c>p?[p=[c,1]]:p[1]++&&[],p=[])
```
[Try it online!](https://tio.run/##jY3PCsIwDIfvPoV6kJaa4PCkZPWqgu7gwUPpoXZ/mIy1rFPw6We3BxCT8IMv@SBP8zbBdrXvoXV5MZTpEFKpEDFoDK7rGceyMf3FeGZTaaU/KJ8qu0603nuVaCFWK6XXcaf5YF0bXFNg4yp2vmVXDH1Xt1VdfljJluZhc7PknM9@e9m76Oa7zSZZ/CEDEBAJJRQJCQByaiLSUhMBIImpMALGiIxSjhMdHA8TwYgC/3h4e22z43Z3ql7346gPXw "JavaScript (Node.js) – Try It Online")
Thanks Shaggy, -1 byte.
---
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 18 bytes
```
O`.
(.)\1*
$1,$.&¶
```
[Try it online!](https://tio.run/##HYrBCYAwFEPvziGifhPoPfwVHEALevDgxYM4mwO4WG2bhMAjuY/nvPaQ0ryx6TmsYWzaMLXsvjclQJBssUXmALxaUvQoAZRVMQNzZaZ7Sf6wDJVQ0PgD "Retina – Try It Online")
I don't speak Retina. I just translated above JavaScript answer to Retina with some searching.
Thanks to Cows quack, -3 bytes.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 34 bytes
```
KeySortBy[ToCharacterCode]@*Counts
```
[Try it online!](https://tio.run/##PYwxC8IwEIX3/ApNwcF4UXEqnKHYRXFQUXCIGWKNtkMbiKkg4m@vSQffHY/7uLtXa1@aWvuq0N192W3N@2idX73lyealdrrwxuX2ZlQ2zm3b@Gd3aCvjJSF7VzVe0gulKBIUcQBxz/5fzyxRo2n2IVRfixudELp7GTdIZ7P5MBIAAiKTTCITACD6QkQlFCIAR9aLB@DBAnMhYocbHhc9QUTGY@KxXezWi3TzaM9rSr6EqO4H "Wolfram Language (Mathematica) – Try It Online")
Returns an association.
---
```
SortBy[ToCharacterCode@@#&]@*Tally
```
[Try it online!](https://tio.run/##PYwxC8IwEIX3/ApNwcF4sdKpcIagi04qFhxihlijLVQLMRWK@Ntr08F3x@M@7u49jC/sw/gyN91t2R1r51etyup1YZzJvXXr@mqljCZaTjNTVW13aErrFSF7Vz69omdKUUQowgDiJv@PLxnpyVx@CDWX/EpnhO7e1o3SOF6MAwEgIDLFFDIBAGIoRNRCIwJwZIN4D7y3nrkQofsbHhYDQUDGQ@KxSXabJN3em9OGki8huvsB "Wolfram Language (Mathematica) – Try It Online")
Returns a list.
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 63 61 bytes
```
s=>s.OrderBy(c=>c).GroupBy(c=>c).Select(g=>(g.Key,g.Count()))
```
[Try it online!](https://tio.run/##PY7BCsIwDIbvPkXZqaNLXsA0BwUFPXjw4EE9SNeNgnbSdsKevnYTTELg4w9/fhPBRJd3ozcUU3C@b9rJP17OsOiEzlFzxFNobdhM0mg2Ne7DML7/dLZPa5LsNcsej3ZqetwOo0@yruu8Xq0@jyCSjUloUQEQEKmrupJiAOCliejOdyIAJLUUFsCyCiPzPOUGZ2EhmFFhVdwvwSUrf8HxMDgvq5uvGtHJ@WeJsM5f "C# (Visual C# Interactive Compiler) – Try It Online")
Thanks to Expired Data for pointing me towards the C# Interactive Compiler and for showing me the power of dynamics.
[Answer]
# [K4](https://kx.com/download/), 9 bytes
**Solution:**
```
#:'=x@<x:
```
**Example:**
```
q)k)#:'=x@<x:"Over 9001!"
| 1
!| 1
0| 2
1| 1
9| 1
O| 1
e| 1
r| 1
v| 1
```
**Explanation:**
```
#:'=x@<x: / the solution
x: / store input as x
< / indices to sort ascending
x@ / apply (@) to x
= / group same values
#:' / count (#:) each (')
```
[Answer]
# APL(NARS), 26 chars, 52 bytes
```
{m,¨+/¨{w=⍵}¨m←k[⍋k←∪w←⍵]}
```
test:
```
⎕fmt{m,¨+/¨{w=⍵}¨m←k[⍋k←∪w←⍵]}'is, this good or not?'
┌12─────────────────────────────────────────────────────────────────────────────────┐
│┌2───┐ ┌2───┐ ┌2───┐ ┌2───┐ ┌2───┐ ┌2───┐ ┌2───┐ ┌2───┐ ┌2───┐ ┌2───┐ ┌2───┐ ┌2───┐│
││ 4│ │ , 1│ │ ? 1│ │ d 1│ │ g 1│ │ h 1│ │ i 2│ │ n 1│ │ o 4│ │ r 1│ │ s 2│ │ t 2││
│└+───┘ └+───┘ └+───┘ └+───┘ └+───┘ └+───┘ └+───┘ └+───┘ └+───┘ └+───┘ └+───┘ └+───┘2
└∊──────────────────────────────────────────────────────────────────────────────────┘
{m,¨+/¨{w=⍵}¨m←k[⍋k←∪w←⍵]}
k←∪w←⍵ copy the argument in w, k is the argument that has unique elements
m←k[⍋ ] copy k order, in m, (so m is argument unique ordered)
{w=⍵}¨m see each element of m in w, so each element of m generate a len(w) bit list
+/¨ sum each bit list above obtain the number of element of m in w
m,¨ make couples
```
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 128 114 bytes
```
->>,[[-[>>+<<-]>>]>+<+[-<<+]->>,]+[+>[<--.++<<+++++++[>++++++++<-]>++.[-]++++++[>>++++++++<<-]>>.[-].]<[>>+<<-]>>]
```
[Try it online!](https://tio.run/##TYxLCoAwDESv0v2YniAEXHqGkIUWhaJ2UfH81fpBZ/XgzcyQ@5imPcylkEijSioCZjIROwFKzLDqDApRJvI4C7ij8gDqBPBK9ppPXXdVeePffymdW@I8unYdcwx9cuu@xXAA "brainfuck – Try It Online")
How it works:
```
- sets cell 0 to 255, which is used to move back to cell 2 later on
>> moves to cell 2
,[ we load our first input and loop until there are no more characters to load
[-[>>+<<-]>>] keeps moving forward skipping every other cell until it has moved forward the ASCII value of the most recently loaded character
>+< adds one to the next cell for the purpose of later looking at to see how many of that character was entered
+[-<<+]->> goes back to cell 2
,] loads in next character and repeats process if there are remaining characters
+[+>[ checks IF the next cell has a value other than 0
<--. then, if true, it prints the ASCII value of the previous cells contents
++<<+++++++[>++++++++<-]>++. then print ":"
[-]++++++[>>++++++++<<-]>>. then print the number value of the contents of the current cell
[-].] then print a null character and leaves the if statement
<[>>+<<-]>>] continues the same process skipping every other cell, until it repeats 255 times
```
Thanks to Jo King, -14 bytes.
This is my second brainfuck program, first being hello world, and first time golfing, so please let me know what I can do to improve my program and answer!
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 60 bytes
```
import StdEnv
$s=sort[(c,sum[1\\k<-s|k==c])\\c<-removeDup s]
```
[Try it online!](https://tio.run/##HcvBCsMgDAbg@57CQ6EbLsLu0VN3GOzWo3oQ60Zp1VLbwmDPPmebhB8@ktjRmZB97NbREW/6kHs/xXkh7dLdw3aqEk@F8myvafXyptSAkL4D51ZflLIIs/Nxc806kaRzu5jyy0lFZA2AgEgllUgFAIijEVELjQjAkB7FCliJYibEPuWG7YtDsJOyWueffY3mnTI8nrn5BON7m/4 "Clean – Try It Online")
Defines the function `$ :: [Char] -> [(Char, Int)]` giving the result as a list of 2-Tuples.
Uses the element-wise behavior of `<` and thus `sort` on Tuples to ensure codepoint ordering.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 13 bytes
```
EΦγ№θι⁺⁺ι №θι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3sUDDLTOnJLVII11HwTm/FChWqKOQqampoxCQU1qsASYydRSUFJQ0URVoalqDTMlPL0rMzc3MS1cIKK2qykktVlADKktJVXDPz0nj@q9blgMA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
γ Printable ASCII
Φ Filtered where non-zero
№ Count of
ι Current character in
θ Input string
E Map over filtered characters
ι Current character
⁺ Plus a space
⁺ Plus
№ Count of
ι Current character in
θ Input string
Implicitly output on separate lines
```
[Answer]
# JavaScript, 57 bytes
Outputs a 2D-Array. Had to implement a quick & dirty fix for the sorting so I'll need to come back to try to golf that.
```
s=>[...s].map(o=x=>o[x]=-~o[x])&&Object.entries(o).sort()
```
[Try It Online!](https://tio.run/##RY6xjsIwDIb3PgW3oETBFicmTk5mmDrccEOuUkoJqBXEqCmo0716LylC2Jb9f7Jl/V39qGPTt7cBAh/9dNJT1MYiYqzwWt8E61EbtmOl4S8PuVyWh843A/ow9K2PgiVG7gchp4ZD5IvHC5@FLVx9aI5uVbjy4fvFdr3@/MgEQECkrLKkDACYOYmoMhURAJKaAxNgaonRmFzpBvNiJsioMH/8vm/K3Wa7P99/dq542k6mT2KULz1ix21wXwsnn@o3vFXW0z8)
[Answer]
# [Kotlin](https://kotlinlang.org), 75 bytes
```
fun String.c()=toCharArray().sorted().map{Pair(it,count{s->it==s})}.toSet()
```
[Try it online!](https://tio.run/##PY7BCsIwEETP9iuW0kMCth8gtiDiwZugx162TWyDupFkC0rIt8dWwZnLwAyPuVm@G0rpOhGc2Rkaql7Imu1@RLdzDt9CVt461moOD3yGExonDK97OxEHXzaG69pHGSu2Z81CflkPNCTQDX4DX8r2B28khCxbLUV1te6A/XgkpV9aQTBrXTbwnGd8J5FftGcoDJRQ6JZaKoJersWWcgkxy2JK6BV2/Yhdwr9Shx0Os73yatEH "Kotlin – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 7 bytes
```
¬ü ®âZl
```
[Test it online!](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=rPwgruJabA&input=IlN1M09IMzlJZ3VXSCIKLVI)
[Answer]
## Haskell, 46 bytes
```
f x=[(c,sum[1|d<-x,d==c])|c<-[' '..],elem c x]
```
[Try it online!](https://tio.run/##HYrRCsMgFEN/5VIG3dB7Ye/RHxEfirWsTMtYV/Ch/@60SQgckte0v2NKtS5UjLsHvR/ZPc8ZXPRsTPCPM4DdSKOI1zHFTIGKr3laNzL0@a7bj2600MAMBpRTDsoys70MwFsPMAvUJWkgrRqLtT3tI324iDsqGeof "Haskell – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-n`, 43 bytes
```
p$_.chars.uniq.sort.map{|c|[c,$_.count(c)]}
```
[Try it online!](https://tio.run/##HYpLDgIxDEMvwwIUkhNYuUhVoaEbZkFb@lkghqsT2tqWpSe79PvbLJ9uEh5bqdLj/pKaSpPnlj9HOFy4zjH12M7h4r9mzGCAHDmQMrMuA/DqAWYBLckAGTVYVGfGR@awiCeS/FJue4rVOP4B "Ruby – Try It Online")
[Answer]
# [sfk](http://stahlworks.com/dev/swiss-file-knife.html), ~~124~~ ~~87~~ 84 bytes
```
xed -i
+chars
+count -same -case
+xed "_?????*x*[white]?_[parts 6,3,1]_"
+sort -case
```
[Try it online!](https://tio.run/##JYvRCsMgDEXf/QrpY9MExmBPwX6IiEjnaBlbh7Gsf@/U3RsSDvdGHs9SznjXuClY1pCknv14Z40SXlHjEiQqaI3Bz03jOdrvuuXoZm8/IWXRt@k6XZwfFMie8v@nFERGZrBgGQwimm5mdsYxIxJDF1WguiqTMW1qh1rQCRsC/QA "sfk – Try It Online")
Gives output in the form `[character]x[count]` with `count` padded to 5 digits.
] |
[Question]
[
## Rules
Given an ISO3166-1-Alpha-2 country code your task is to decide on the traffic direction for that country:
* Input will be a valid country code (valid as in it's an element of the two lists provided)
* Input may be a list of two characters instead of a string if it helps
* You may choose to take input in lowercase
* You will choose one value, say for *right* (your choice) and will output that value iff the traffic in that country is right-handed and anything else in the other case
* You only have to handle country codes that are contained in one of these lists:
These are all countries where traffic is left-handed:
```
['AI', 'AG', 'AU', 'BS', 'BD', 'BB', 'BM', 'BT', 'BW', 'VG', 'BN', 'KY', 'CX', 'CC', 'CK', 'CY', 'DM', 'FK', 'FJ', 'GD', 'GG', 'GY', 'HK', 'IN', 'ID', 'IE', 'IM', 'JM', 'JP', 'JE', 'KE', 'KI', 'LS', 'MO', 'MW', 'MY', 'MV', 'MT', 'MU', 'MS', 'MZ', 'NA', 'NR', 'NP', 'NZ', 'NU', 'NF', 'PK', 'PG', 'PN', 'SH', 'KN', 'LC', 'VC', 'WS', 'SC', 'SG', 'SB', 'SO', 'ZA', 'GS', 'LK', 'SR', 'SZ', 'TH', 'TL', 'TK', 'TO', 'TT', 'TC', 'TV', 'UG', 'GB', 'TZ', 'VI', 'ZM', 'ZW']
```
And here are all countries where traffic is right-handed:
```
['AF', 'AX', 'AL', 'DZ', 'AS', 'AD', 'AO', 'AQ', 'AR', 'AM', 'AW', 'AT', 'AZ', 'BH', 'BY', 'BE', 'BZ', 'BJ', 'BO', 'BA', 'BV', 'BR', 'IO', 'BG', 'BF', 'BI', 'CV', 'KH', 'CM', 'CA', 'CF', 'TD', 'CL', 'CN', 'CO', 'KM', 'CG', 'CR', 'CI', 'HR', 'CU', 'CW', 'CZ', 'KP', 'CD', 'DK', 'DJ', 'DO', 'EC', 'EG', 'SV', 'GQ', 'ER', 'EE', 'ET', 'FO', 'FI', 'FR', 'GF', 'PF', 'TF', 'GA', 'GM', 'GE', 'DE', 'GH', 'GI', 'GR', 'GL', 'GP', 'GU', 'GT', 'GW', 'GN', 'HT', 'HM', 'VA', 'HN', 'HU', 'IS', 'IR', 'IQ', 'IL', 'IT', 'JO', 'KZ', 'KW', 'KG', 'LA', 'LV', 'LB', 'LR', 'LY', 'LI', 'LT', 'LU', 'MG', 'ML', 'MH', 'MQ', 'MR', 'YT', 'MX', 'FM', 'MC', 'MN', 'ME', 'MA', 'MM', 'NL', 'NC', 'NI', 'NG', 'NE', 'MP', 'NO', 'OM', 'PW', 'PA', 'PY', 'PE', 'PH', 'PL', 'PT', 'PR', 'QA', 'KR', 'MD', 'RE', 'RO', 'RU', 'RW', 'BL', 'MF', 'PM', 'SM', 'ST', 'SA', 'SN', 'RS', 'SL', 'BQ', 'SX', 'SK', 'SI', 'SS', 'ES', 'PS', 'SD', 'SJ', 'SE', 'CH', 'SY', 'TW', 'TJ', 'MK', 'TG', 'TN', 'TR', 'TM', 'UA', 'AE', 'UM', 'US', 'UY', 'UZ', 'VU', 'VE', 'VN', 'WF', 'EH', 'YE']
```
---
For completeness sake, [here](https://pastebin.com/8Gs3ukHr)'s a CSV file that contains all the values along with the country names.
## Testcases
Assuming you chose to output `L` for left-handed traffic, here are some valid test cases:
```
'PY' -> 'python'
'PN' -> 'L'
'CN' -> 33
'GY' -> 'L'
```
**Note:** There is a small chance that I missed a country or that there's a wrong classification and I will not change the specs because that might invalidate answers. If I made a mistake I sincerely apologize, please don't take offense!
[Answer]
# [Python 2](https://docs.python.org/2/), ~~145~~ ~~136~~ ~~112~~ 109 bytes
```
'TTHSZWMSGSONPKNZMWVIDFKELSCYJPNFJMTVCXBNRBWSHKYAUGGYBTLCCKIMVGBSBBMZAINAGDMOBDIEJEMYMUNUPGSRLKTKTOTCTZ'.find
```
[Try it online!](https://tio.run/##VZQ9b9swEIb3/gp1cgK0Bdrdg0hJFMUPMyIlRWo7BAmMBjCcwMjSX@82zw1FlxcCeffec8ezX3@//Xo5f7se9z@uu1L6vC0hm3yIycUtLLNtOtf6rNchxW4IZdb3Ko5qyb1b68mYVRWvtbNhNiorFbbaxto04aAa2w5tWMMUp2Ty6F1x5VB02XZfjs/np@ul2lffd3W3@1Tt6nvUv2uz8Z3RBj2gd@iIBnRBC0qW6tEVbVE5H1B8VI3OKG5Wzg0Kj7LvqolxeGoqanI1MQU2DbOOKD5OInHT@GvcevmeUMg1bC7xjVvjUGgb3FqN4pbhMcyhxa2lx5YJdMR31Oq4NXAmoUUN/AZCQ26DGno05BrJpS8Dm4HZUMVAbui356THbca5l3PiLS9oZcIwWzwtWYPMSiaAp6NHj4@nU69QHDxv6iH0OHiqBLICzoEuArUCWSuRge3q4AzMM8AZ6D1QMXAb8YnERGpF/KNEMo0I@YH4BHnCIUGYiEyQJNwSDAmeOyId34EXH4kf8RzpaMRTSUfygtTKorhlfDJdjMw5E6/oPdNvZpcyXWRiWjRJPNUzm5Zh0DBnuigwFG4DPoU5FCoW@As8EyQ1DpOc4D/hM/G@M33NxMw4LPTVUnFtdz8/nOTPANiaUjVJCjMFrGIdFEUUY1BgzvLDxdhRVjMAzTNq8DXnDbkdJx3NGZwNDoaYnluLm@XWAm7JHURZhIFzJyqLCW3gMQNsAc/AOgdZRllbiWQ8kRFGhhplxeScyCgrAFWCM8GWGZ7j29PpjC7yvHxn@dtgbhmqTf4AiPGyINTNVCx4FlapyLOTVSAveBZ6mWRiOBd5ZCawMZ9t@fukH14vz@e36uF0ujnePN5W@331@Wt1fLlUj9XzubrcVg/np3/XH/@/Pt1e/wA "Python 2 – Try It Online")
Outputs `-1` for right-handed traffic. ~~The string is autogenerated with [this Retina script](https://tio.run/##JZA7DsIwEER7n8JFJPMTEnCCBIgJiUOETQIhQVBQ0FAgSu4O@Ll5snZnZ8f7ur8fz9v3e@7OXa8mvRCXTySkGF/lYDocTEdD6dHNpJDRIppFc/kXqzhTE6liDQ@eiYUrmEADHWw8a/RJ6ZmfPJdHuIQ5pL5iNqWSbj01zhoHjWZDN8Mto5utIbPbwApSzwNJXpDW7CDZDJ6mhmQ2/MsEZetZxnAPcS5DHWWZelakqshZkc1u2Mu74Kc1bHC2vC16y90sqVp2aTQFnpa9lo0OT1dAuo4pR3KHp@Mvh3AxnB2zNRdouU/bqP4H).~~ Thanks to [totallyhuman](https://codegolf.stackexchange.com/users/68615/totallyhuman) for the 9 bytes shorter lookup string. I was able to get 24 bytes more off through [AdmBorkBork](https://codegolf.stackexchange.com/users/42963/admborkbork) suggestion.
Got the lookup string 3 bytes shorter using a python script.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 61 bytes
*Many thanks to [@Mr.Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder) for helping me putting this together*
*Saved 1 byte thanks to [@JonathanAllan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)*
Returns `0` for right-handed or `1` for left-handed.
```
“ŒỴ¬Ʋ>r¤dị|®ædHẇ⁸ɗH^CŒ³ẇPḷgȤƲȥƓƑ®Ƭṅḅ4ṛḟṄ’ḃ⁴+\
Oḅ⁹×6%⁽£€%566e¢
```
[Try it online!](https://tio.run/##AYIAff9qZWxsef//4oCcxZLhu7TCrMayPnLCpGThu4t8wq7DpmRI4bqH4oG4yZdIXkPFksKz4bqHUOG4t2fIpMayyKXGk8aRwq7GrOG5heG4hTThuZvhuJ/huYTigJnhuIPigbQrXApP4biF4oG5w5c2JeKBvcKj4oKsJTU2NmXCov///1RL "Jelly – Try It Online")
### How?
We convert each country code to an integer **N** by parsing it as base-256 and apply the following hash function, which is collision-free for left-handed vs right-handed traffic:
```
((N * 6) MOD 1513) MOD 566
```
This leads to the following list of values for left-handed traffic:
```
[ 8, 14, 27, 37, 52, 60, 62, 68, 71, 84, 85, 88, 103, 105, 114, 119, 135,
166, 167, 180, 187, 190, 195, 196, 202, 207, 208, 211, 214, 225, 226, 229, 232, 255,
256, 262, 285, 301, 302, 303, 304, 309, 322, 325, 327, 337, 357, 369, 370, 381, 393,
401, 408, 413, 420, 430, 453, 467, 473, 478, 492, 503, 509, 513, 516, 527, 528, 541,
546, 547, 556, 562 ] (72 entries)
```
The average difference between two consecutive entries is close to 8. We delta-encode the list with increments in the range [1...16]. It means that whenever an increment is greater than 16, we need to insert an intermediate value on an unused slot (we have to make sure that it's not hit by right-handed traffic). But the hash function was chosen in such a way that we only have to do that for a few positions. This gives:
```
[ 8, 6, 13, 10, 15, 8, 2, 6, 3, 13, 1, 3, 15, 2, 9, 5, 16, 15, 16, 1, 13,
7, 3, 5, 1, 6, 5, 1, 3, 3, 11, 1, 3, 3, 16, 7, 1, 6, 16, 7, 16, 1,
1, 1, 5, 13, 3, 2, 10, 16, 4, 12, 1, 11, 12, 8, 7, 5, 7, 10, 16, 7, 14,
6, 5, 14, 11, 6, 4, 3, 11, 1, 13, 5, 1, 9, 6 ] (77 entries)
```
We convert this list from bijective base-16 to the following integer:
```
274705197430389746738026977757328941544772847257562272094076195694133371689429679543810871702
```
which becomes `“ŒỴ¬Ʋ>r¤dị|®ædHẇ⁸ɗH^CŒ³ẇPḷgȤƲȥƓƑ®Ƭṅḅ4ṛḟṄ’` in Jelly's base-250 encoding.
The first link rebuilds the original list from this integer and the second one tests whether it contains the hash of the input.
```
“ŒỴ¬Ʋ>r¤dị|®ædHẇ⁸ɗH^CŒ³ẇPḷgȤƲȥƓƑ®Ƭṅḅ4ṛḟṄ’ḃ⁴+\ - 1st link: takes no input
“ŒỴ¬Ʋ>r¤dị|®ædHẇ⁸ɗH^CŒ³ẇPḷgȤƲȥƓƑ®Ƭṅḅ4ṛḟṄ’ - our big integer
ḃ⁴ - convert it to bijective base-16
+\ - apply delta-decoding
Oḅ⁹×6%⁽£€%566e¢ - 2nd link: takes the country code -> e.g. 'GB'
O - get ASCII codes -> [71, 66]
ḅ⁹ - convert from base-256 to integer -> 18242
×6 - multiply by 6 -> 109452
%⁽£€ - modulo 1513 -> 516
%566 - modulo 566 -> 516
e - look for it in the decoded list,
¢ - using the first link as a nilad -> 1
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~161~~ 148 bytes
```
"$args"-match'A[GIU]|B[BDMNSTW]|[CFHW][CJKSXY]|DM|G[BDGSY]|[IJ][DEMNP]|K[EINY]|L[CKS]|M[OS-WYZ]|N[AFP-Z]|P[GKN]|S[BCGHORZ]|T[CHKLOTVZ]|UG|V[CGI]|Z.'
```
[Try it online!](https://tio.run/##DclNCoMwEEDhu0ghK3sHjTrGmCiNP9VhFlKkLiwtWuhm7p5m9/He5/1bj3Nb99376LIczzOKX8v3sYkEQfXEKaaZsa4biVEW5UgoK@3uE3FmGMIEF4yqIsxyY1tijbmyodUotSM22Lh4nGZii0nRxgEtgrbEDlMJZXMLpUNZ6rrphuAeeEAJini@Cu@9SED8AQ "PowerShell – Try It Online")
~~Naïve~~ regex pattern matching. Outputs `True` for left-handed and `False` for right-handed.
*Saved 13 bytes thanks to mercator golfing the regex.*
[Answer]
# [Haskell](https://www.haskell.org/), 137 bytes
*-5 bytes thanks to ovs.*
```
import Data.List
(`isInfixOf`"MSOBTVGBSBBMZAINAGDMOAUGGYBDBWSHKYBNRJPNFJMVCKIMTLCCXLSCYFKEVIDIEJELSGSOLKNZMWMYMUPKNPGSRNUTKTOTCTZSZWTTH")
```
[Try it online!](https://tio.run/##ZZVRb5swFIXf9ytQtIdNWvcP@mAbMARMXGxIwzSpqE1W1DStEibt32fNd6u@NFKOkH3vuefca8PjeHra7vfn8/T8@nKck3Scx5/1dJq/7K6/3U2n8rCb/q12dwsXVjr2Vget3aDKRtnUrVRn7Uaneh2KaqObdumbfOl6U5Uu1sbc1sFs8irry7TMllkdbFjVVTO4tdu4zleNt6FtuljFVTRxCMM6xmLx/fw8Tofk@kvy9ttv57f/bk6S6@TXQpWLH8lCWbC7oA5gCmrQgRFcX7AnXjcXrDYXNLegASuQ9ZTcnJV8eUELs4XBElOwW8JWsltmILlLQQ@yXgmivEatW4Foc3C6HkSzw5eTyOGCjQJbEOZG1ols8gt6VHl0erSFgro81zjtwTXMgedAfKBvAVUDtSwxNZyBuoGKEc5Yg@xGsiLKI5wRL510DOZIbk8HBvozrBe/Ge/ld5z@PM4yXqwohqMokpKqkKNotqKgugGRpqBUtFMhRJGlEatpsGYIWtYZrIZHY1cjWcNWyrocGfRohBtiKjgNFQ25hpiINoNmQ8sNPJVEwmbgN7AV8swADcoN2irGa2BLaXCK2hS2jAZnMjT0WPqQwZbhMaMDOfE5tXJ2rRwTUQtaGTUKLbkpaPFoybWSiy@LNotmSxWLcovfgpUCth7mQtaJL5lgKR1GcwlnSdZSeiUdgLPCYw1PjdOao1TDUDPTWq4UDLVcGrIczA4XjlqOrI1cL05Xjk5HPx06Hd4dFR27DTwNMQ21GvgbiZSLiPIV8R7lHgaPQk@kR4mHzaPBo@eGyIpnx8Rb4ls4Wxy1cGpxJBOkVhCELcATcNHK5SZe4z3gN8hVxkUgJgO9xFM9cNICGgyaAy4iGiK7Ti49fYhUjOiP6OlQomDoZAX@Dp5OXgP46onpYVjjK6PiJnt/Mbx9AB5ePl4Rr8fpMCdfk/Hw8IbP42uye/8qXF0l94/b@6dk2iXjfp/Mx7/bT2kvx48sedl8StuN@9P2/B8 "Haskell – Try It Online")
Generated the original string by hand.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~82~~ 68 bytes
Outputs **1** for left-traffic and **0** for right-traffic.
```
.•6uγ)₅₄вwÔívtÎĆ–≠5βI·{!ÅÇΔ›íÕ(1.€ò“Ѧ_£äß₂Ë‹ûÚм2±rrÇQ=ÅÔζ)B†š¢¡ε•så
```
[Try it online!](https://tio.run/##AYkAdv8wNWFiMWX//y7igKI2dc6zKeKCheKChNCyd8OUw612dMOOxIbigJPiiaA1zrJJwrd7IcOFw4fOlOKAusOtw5UoMS7igqzDsuKAnMORwqZfwqPDpMOf4oKCw4vigLnDu8Oa0LwywrFycsOHUT3DhcOUzrYpQuKAoMWhwqLCoc614oCic8Ol//96dw "05AB1E – Try It Online")
or as a [Test Suite](https://tio.run/##JZBPSwJRFMW/irmZhJAMbBG0cDTH0Zlp6j3HmogoaNfKypA2w5BJBEFkmwhS@7PKRUZFf0CYW9vBz/C@yOQ7s/nxuPfcc8@7s9ntncxu1GjuRWnh9ecPw9eU8FvCPxkPj6hDg8YBXfyeCu9KnHWz4VAPPo6nqEXtsCO8LxrQ9XQmLfxnGgrvli6Dp63gnh7oTvg@nQvvk77pZvwzF7zU69ReWZxMdsL3lCq87l8v6Ae98G2ydZ8eo2aSRgsJGiVnog0lpyszCSWngVVJlYEFUAVNkIM1SQd61ZKsrEvm18A8WAFRL2C2iEqxLKnBWYODBk0JXR1uOrr6EojZckwbRL0SE8kNpDWXQWQz4Wk6IDKb@JcZK11JKweugnC24jqUVlHSRiobOW1kYyXsxdvATx2wBmeGN4Oe4W4MqVzs0qAx4Mmwl2Ejhyc3QHQ5pjiSc3hy/KUaXwzOHLMOLuDiPm5N2fwH)
Uses the string generated by [totallyhuman](https://codegolf.stackexchange.com/a/152644/47066) and improved by [ovs](https://codegolf.stackexchange.com/a/152642/47066)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 76 bytes
```
.•B6L>õKвΩ~#ëΓnĀÿι–öß/çĸ’Û´äηÅÚ‚zĨe÷ö#YʒƒʒjªêKΩoúö‰Öe¡₄Æ∞¤iY¥•#vySANèì})åZ
```
[Try it online!](https://tio.run/##AY8AcP8wNWFiMWX//y7igKJCNkw@w7VL0LLOqX4jw6vOk27EgMO/zrnigJPDtsOfL8Onw4TCuOKAmcObwrTDpM63w4XDmuKAmnrDhMKoZcO3w7YjWcqSxpLKkmrCqsOqS86pb8O6w7bigLDDlmXCoeKChMOG4oiewqRpWcKl4oCiI3Z5U0FOw6jDrH0pw6Va//96dw "05AB1E – Try It Online")
---
```
.•B6L>õKвΩ~#ëΓnĀÿι–öß/çĸ’Û´äηÅÚ‚zĨe÷ö#YʒƒʒjªêKΩoúö‰Öe¡₄Æ∞¤iY¥•
```
Outputs the following string:
```
GIU BDMNSTW CKXY M JK BDGSY K DEMN EMP EINY CKS OSTUVWYZA FPRUZ GKN BCGHORZ CHKLOTVZ G CGI S AMW
```
If I split that on spaces, and interleave the alphabet into each string, it results in all the states that drive on the left side.
---
1 for left, 0 for right; Emigna's is better, but this felt different enough to post :).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 69 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ẇ“h¦¤$>Xø3¬I_°Ḷd⁺+ç*p¢7"FU]#x⁹ĿAxḷŻbCȦ]$ḣẒẓST¬ȥ¬ṆṠ®æ÷©#ḄS#MĠỤ4ɱ5’ṃØA¤
```
A monadic link taking a list of characters and returning `1` if left (`0` if right).
**[Try it online!](https://tio.run/##AYQAe/9qZWxsef//4bqH4oCcaMKmwqQkPljDuDPCrElfwrDhuLZk4oG6K8OnKnDCojciRlVdI3jigbnEv0F44bi3xbtiQ8imXSThuKPhupLhupNTVMKsyKXCrOG5huG5oMKuw6bDt8KpI@G4hFMjTcSg4bukNMmxNeKAmeG5g8OYQcKk////R0I "Jelly – Try It Online")**
**How?**
Uses the method as implemented [totallyhuman](https://codegolf.stackexchange.com/a/152644/47066) / [ovs](https://codegolf.stackexchange.com/a/152642/47066).
```
ẇ“ ... ’ṃØA¤ - Link: list of characters
¤ - nilad followed by link(s) as a nilad:
“ ... ’ - base 250 number = 19752831477605543488091668410027486265612829758468833715947215534967455540194888181580207621675010690833131726534873382634884974263558670694315853304
ØA - list of characters = "ABCDEFGHIJKLMNPQRSUVWXZ"
ṃ - base decompress = "MSOBTVGBSBBNZAINAGDMOAUGGYBDBWSHKYBNRJPNFJMVCKIMTLCCXLSCYFKEVIDIEJELSGSOLKOZMWMYMUPKNPGSRNUTKTOTCUZTZWTTH"
ẇ - is a sublist of?
```
---
Also, what I did independently came in at **72 bytes**:
```
“¦w/ḳœBẒḂṡẏ,©ḷĿdẎq⁸4ṙ^|ṂỌʋ:vkɱF#ẊṠµd¤w,ḋhn|ȯ24ɦm|×ỵ’ṃ©ØAO0;I<0œṗ®ṭ€"ØAẎċ
```
Also a monadic link taking a list of characters and returning `1` if left (`0` if right).
**[Try it online!](https://tio.run/##AZEAbv9qZWxsef//4oCcwqZ3L@G4s8WTQuG6kuG4guG5oeG6jyzCqeG4t8S/ZOG6jnHigbg04bmZXnzhuYLhu4zKizp2a8mxRiPhuorhuaDCtWTCpHcs4biLaG58yK8yNMmmbXzDl@G7teKAmeG5g8Kpw5hBTzA7STwwxZPhuZfCruG5reKCrCLDmEHhuo7Ei////0dC "Jelly – Try It Online")**
**How?**
```
“ ... ’ṃ©ØAO0;I<0œṗ®ṭ€"ØAẎċ - Link: list of characters
“ ... ’ - base 250 number = 20449742094039418439524274048234013619715377161457577389098927787850535557806494274193349238496252074719534810320317229
ØA - list of characters = "ABCDEFGHIJKLMNPQRSUVWXZ"
ṃ - base decompress = "GIUBDMNSTWCKXYMKJKBDGSYKDEMNEMPEINYCKSOSTUVXZZAFPRVZHGKNDCBCGHOSZCHKLOTWZGCGIASCBAMW"
© - copy to register
O - cast to ordinals = [71,73,85,66,68,77,78,83,84,87,67,75,88,89,77,75,74,75,66,68,71,83,89,75,68,69,77,78,69,77,80,69,73,78,89,67,75,83,79,83,84,85,86,88,90,90,65,70,80,82,86,90,72,71,75,78,68,67,66,67,71,72,79,83,90,67,72,75,76,79,84,87,90,71,67,71,73,65,83,67,66,65,77,87]
0 - literal zero
; - concatenate = [0,71,73,85,66,68,77,78,83,84,87,67,75,88,89,77,75,74,75,66,68,71,83,89,75,68,69,77,78,69,77,80,69,73,78,89,67,75,83,79,83,84,85,86,88,90,90,65,70,80,82,86,90,72,71,75,78,68,67,66,67,71,72,79,83,90,67,72,75,76,79,84,87,90,71,67,71,73,65,83,67,66,65,77,87]
I - incremental differences = [71,2,12,-19,2,9,1,5,1,3,-20,8,13,1,-12,-2,-1,1,-9,2,3,12,6,-14,-7,1,8,1,-9,8,3,-11,4,5,11,-22,8,8,-4,4,1,1,1,2,2,0,-25,5,10,2,4,4,-18,-1,4,3,-10,-1,-1,1,4,1,7,4,7,-23,5,3,1,3,5,3,3,-19,-4,4,2,-8,18,-16,-1,-1,12,10]
0 - literal zero
< - less than (vectorises) = [0,0,0,1,0,0,0,0,0,0,1,0,0,0,1,1,1,0,1,0,0,0,0,1,1,0,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,0,0,1,1,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,1,0,0,1,0,1,1,1,0,0]
® - recall from register = "GIUBDMNSTWCKXYMKJKBDGSYKDEMNEMPEINYCKSOSTUVXZZAFPRVZHGKNDCBCGHOSZCHKLOTWZGCGIASCBAMW"
œṗ - partition at truthy indexes = ["GIU","BDMNSTW","CKXY","M","K","JK","BDGSY","K","DEMN","EMP","EINY","CKS","OSTUVXZZ","AFPRVZ","H","GKN","D","C","BCGHOSZ","CHKLOTWZ","G","CGI","AS","C","B","AMW"]
ØA - list of characters = "ABCDEFGHIJKLMNPQRSUVWXZ"
" - zip with:
ṭ€ - tack for €ach = [["AG","AI","AU"],["BB","BD","BM","BN","BS","BT","BW"],["CC","CK","CX","CY"],["DM"],["EK"],["FJ","FK"],["GB","GD","GG","GS","GY"],["HK"],["ID","IE","IM","IN"],["JE","JM","JP"],["KE","KI","KN","KY"],["LC","LK","LS"],["MO","MS","MT","MU","MV","MX","MZ","MZ"],["NA","NF","NP","NR","NV","NZ"],["OH"],["PG","PK","PN"],["QD"],["RC"],["SB","SC","SG","SH","SO","SS","SZ"],["TC","TH","TK","TL","TO","TT","TW","TZ"],["UG"],["VC","VG","VI"],["WA","WS"],["XC"],["YB"],["ZA","ZM","ZW"]]
Ẏ - tighten = ["AG","AI","AU","BB","BD","BM","BN","BS","BT","BW","CC","CK","CX","CY","DM","EK","FJ","FK","GB","GD","GG","GS","GY","HK","ID","IE","IM","IN","JE","JM","JP","KE","KI","KN","KY","LC","LK","LS","MO","MS","MT","MU","MV","MX","MZ","MZ","NA","NF","NP","NR","NV","NZ","OH","PG","PK","PN","QD","RC","SB","SC","SG","SH","SO","SS","SZ","TC","TH","TK","TL","TO","TT","TW","TZ","UG","VC","VG","VI","WA","WS","XC","YB","ZA","ZM","ZW"]
- ...this is the left list plus EK, OH, QC, RC, WA, XC, and YB
- (which are not in the right list)
ċ - count
```
[Answer]
# Befunge, ~~155~~ ~~152~~ ~~147~~ 146 bytes
```
~48*%10p~20pv
\"`"`"A"+61p>:2g:48*%10g-!20g61g-!#@*#,_\1+:"O"#@`#._
NzBSgCLVStBGiIJknAVGPSuStAKvfCFHPLttBDIJzBIPkMStJn{NsBLMWgBMtAMnMtBMzcKCGmMNSt
```
[Try it online!](http://befunge.tryitonline.net/#code=fjQ4KiUxMHB+MjBwdgpcImAiYCJBIis2MXA+OjJnOjQ4KiUxMGctITIwZzYxZy0hI0AqIyxfXDErOiJPIiNAYCMuXwpOekJTZ0NMVlN0QkdpSUprbkFWR1BTdVN0QUt2ZkNGSFBMdHRCRElKekJJUGtNU3RKbntOc0JMTVdnQk10QU1uTXRCTXpjS0NHbU1OU3Q&input=Wlc)
Outputs `80` for a right-handed country, and anything else indicates a left-handed country.
**Explanation**
The bottom line of the code contains a representation of all the left-handed countries. This is a list of the first characters of the country codes, grouped by their second character. The end of each group is marked by lowercasing the last character in the group.
So for example the first group, `Nz`, represents `NA` and `ZA`. The second group, `BSg`, represents `BB`, `SB`, and `GB`. There is one group for each letter in the alphabet, except for the letter `Q` (no left-hand country codes end in `Q`). That empty group is represented by the character `{`, since that obviously won't match any valid country code.
To determine whether a given country code matches one of these entries, we iterate through the list checking whether any of the characters in the list match the first character of our input (mod 32 to account for the case), and also that the corresponding group, matches the second character of the input. The group character start as `A`, and is incremented every time we encounter a lowercase letter in the list.
We exit when we find a match, outputting the last character value on the stack (which will be the first character of the country code - possibly lowercase). Otherwise we'll exit when we've iterated through the whole list, in which case we will output the last number on the stack, which is always 80.
[Answer]
# Windows Batch, ~~289~~ ~~279~~ ~~199~~ ~~193~~ ~~181~~ ~~130~~ 118 bytes
```
@echo TTHSZWMSGSONPKNZMWVIDFKELSCYJPNFJMTVCXBNRBWSHKYAUGGYBTLCCKIMVGBSBBMZAINAGDMOBDIEJEMYMUNUPGSRLKTKTOTCTZ|find "%1"
```
Outputs the ovs' string for left-hand traffic, else outputs nothing.
**Note:** I noticed if the input *contains* any country code in the list above, it will still output L. However, this does not violate the challenge rule as OP mentioned only country codes need to be handled.
---
Explanation:
```
@echo TTHSZ...OTCTZ :: List all country code.(compressed by ovs)
| :: Pipe the result to the find command.
find "%1" :: Find the first argument in the country code list,
:: and output the ovs string if found.
:: By default, FIND returns the piped string when
:: a match is found.
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~181~~ ~~169~~ 165 bytes
```
f(x){x=strstr("AIAUBSBDBBMBTBWVGBNKYCXCCKCYDMFKFJGDGGYHKINIDIEIMJMJPJEKELSMOMWMYMVMTMUMZNANRNPNZNUNFPKPGPNSHKNLCVCWSSCSGSOZAGSLKSRSZTHTLTKTOTTCTVUGTZVIZMZW",x)?:82;}
```
[Try it online!](https://tio.run/##fcwxa8MwEAXgPb8iCAI2JEun0lCKJduyLN9Z5M5yJbIUQ0qGmpJmMIT8dtfQuXm84cEHb9h9DsM8n5IpvU2vP9fL0kRkJuskyVxKkCx7ryXaoN6VsirkUNqy1rnWobIGTW4KAzXUri5s0RC00EMADwwdRMzwgA4jdlg667RDqiw2yqueSJGmNmaaGksHilxxw5ZbZsW@0xy9iRB7sZ3St5fnp/19/vo4j0m6uq3WS74v5/F6SsRmOI5iu16WCyJN9/8hPkD1CPXf7X3@BQ "C (gcc) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 144 bytes
```
lambda l:l[1]in'GIU,BDMNSTW,CKXY,M,,JK,BDGSY,K,DEMN,EMP,EINY,CKS,OSTUVWYZ,AFPRUZ,,GKN,,,BCGHORZ,CHKLOTVZ,G,CGI,S,,,AMW'.split(',')[ord(l[0])-65]
```
**[Try it online!](https://tio.run/##VZVBj9owEIXv/IpoL4DkVm2l9lBpD4lJnJDYeGMnLKEcqLaoSBQQSw/99Vv4vIdkD09Zz8yb92accP53/X06fnmrC5X76DFaj@NsLKJx/AxWd5x1PDtwBi7AJ7AGNbgEPUhVkoMrMAXD@RyEJ4nBFoStCOcKRE9S3FGSU8Ip6SipleR4tEk0SwPCU4ZM2CT8ErY8PDcgyiXaSsszbLMSRO0MtlSCsDn0KOaQwpbiMWUCGfkZvTKiCp02qAUV@hUKFbUzUOFRUatCLb4U2hSaFV0UyhV@c05y2FqY83BOfsEGizBhNBdwFlTNw6zCBOAs8VjBU@G0SkAYKnZaobCCoaKLpkrDrHGh6aWpWpGpuV0ZOjXz1OjUeNd01EQNPIYcQy8DvwmZTMOgfEG@RbmFwaLQkmlRYmGzaLDoeSKz5Fmz8Zr8Gs4aRzWcSXAUNkgvFxA2B4/DRc2cHfkJ3h1@HXfJ4cKRk4I25NPdcdMcGiSaHS48GjxRDY9nDp6OHv0ePQ1KYhiacAJ/A0/Dflt8teS0MCzxldJxlY43oyrN3r8H9IlRHd/qRtH73zjhNiToTuiUwJXQL2EuybJfIdmjRL9kJnLVj890/78Mt1nZP1P0VPRUKFN0UwOefFBTkF3gtkBnYfrxOZE5kbntR0oiJd5LvJWDPhV@KvxUrh/R3B@NNh3ufHg7eI8029RsRHf9OsP2DNsw4XazW0O1GeRa/Fu624Ejx5Qc6lz4UoW7hCoHoxtweXI9WT7cL@6vp8LjwKPdD@oa2FvZP2vDWdE/Ww6m0@GyY@Ld8nbbRrvHH2@H7Z@fL9vo8P2w/rzZH29fv0YkM22cXwpZPq@EFmJe3o6UW4lSzFJtRKqtSAuzuiU4sXC@aZerTsSZrZtOCFUaIUQiVb6oOyHzslr4thNKSFUIdwvFt018fD0f9tfJWIyn69PlZXJYf9pMP3z7unnbvr7@ulyj7eEw2U2qabQ7XaIq2h@j@8sxHfXCx9M12k3qkFLfU/hBnY5G58v@eL2V74/nv9fJdDp9e4iLh/8 "Python 2 – Try It Online")**
Prints `True` for left, `False` for right.
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~150~~ 117 bytes
```
$
MSOBTVGBSBBMZAINAGDMOAUGGYBDBWSHKYBNRJPNFJMVCKIMTLCCXLSCYFKEVIDIEJELSGSOLKNZMWMYMUPKNPGSRNUTKTOTCTZSZWTTH
^(..).*\1
```
[Try it online!](https://tio.run/##BcHBDoIwDADQ@75DE/RA4ifQAWVs7RZawC3G6MGDFw/G/5/vfV@/9@dZjw0@6sGQRNANQQCodI477Cl2K2KGHnaZfAZe5sTjTJv1jjRYew1i8@iHzfVumIcgKDF4LrRTpjV5TigLr@o1qtUiZVedzL1p21N7vl1qTdkkNpYN5j8 "Retina – Try It Online")
[Answer]
# Excel VBA, 118 Bytes
Anonymous VBE immediate window function that takes input from cell `[A1]` and outputs `0` if the country is right-handed
```
?InStr(1,"TTHSZWMSGSONPKNZMWVIDFKELSCYJPNFJMTVCXBNRBWSHKYAUGGYBTLCCKIMVGBSBBMZAINAGDMOBDIEJEMYMUNUPGSRLKTKTOTCTZ",[A1])
```
uses [ovs' string](https://codegolf.stackexchange.com/a/152642/61846)
[Answer]
# Japt, ~~126~~ ~~100~~ 97 bytes
Uses ~~totallyhuman's~~ [ovs' lookup string](https://codegolf.stackexchange.com/a/152642/58974). Takes input in lowercase and outputs `false` for RHD or `true` otherwise.
```
`tszwmsgspknzmwvidfkelscyjpnfjmtvcxbnrbw¢kyauggybtlc×Svgbsbbmzaagd¶b¹ejemymunupgsrlktktctz`øU
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=YHSQc3p3bXNnc41wa256bXd2aWRma2Vsc2N5anBuZmptdHZjeGJucmJ3omt5YXVnZ3lidGxj11N2Z2JzYmJtemGIYWdktmK5ZWplbXltdW51cGdzcmxrdGuRdGN0emD4VQ==&input=ImllIg==)
Everything between the backticks is the lookup string lowercased and compressed and `ø` checks if it contains the input, `U`.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~60~~ ~~57~~ ~~55~~ ~~50~~ ~~47~~ ~~46~~ 44 bytes
```
00000000: 736d 406a 4322 579f 235e 804c c3eb 6f49 sm@jC"W.#^.L..oI
00000010: aee5 1f3d be3d 4e13 f326 1934 a181 a210 ...=.=N..&.4....
00000020: 7158 3f94 2232 2f43 5164 5336 qX?."2/CQdS6
```
[Run online](https://pyth.herokuapp.com/?code=sm%40jC%22W%C2%9F%23%5E%C2%80L%C3%83%C3%ABoI%C2%AE%C3%A5%1F%3D%C2%BE%3DN%13%C3%B3%26%194%C2%A1%C2%81%C2%A2%10qX%3F%C2%94%222%2FCQdS6&test_suite=1&test_suite_input=%27AI%27%0A%27AG%27%0A%27AU%27%0A%27BS%27%0A%27BD%27%0A%27BB%27%0A%27AF%27%0A%27AX%27%0A%27AL%27%0A%27DZ%27%0A%27AS%27%0A%27AD%27)
Takes the input as an uppercase quoted string (`'AI'`). Returns `3` for left and non-`3` for right.
### How it works
```
sm@jC"…"2/CQdS6
m S6 map for d in [1, …, 6]:
"…" string literal
C convert to integer from base 256
j 2 digits in base 2
@ wrapping index at:
Q input string
C convert to integer from base 256
/ d integer division by d
s sum
```
### Generating the magic string
```
import binascii
import z3
n, k, c = 239, 6, 3
a = [z3.Bool('a{}'.format(i)) for i in range(n)]
def f(s0, s1):
return z3.Sum([z3.If(a[(ord(s0) * 256 + ord(s1)) // j % n], 1, 0) for j in range(1, k + 1)]) == c
solver = z3.Solver()
solver.add(a[0])
for s0, s1 in ['AI', 'AG', 'AU', 'BS', 'BD', 'BB', 'BM', 'BT', 'BW', 'VG', 'BN', 'KY', 'CX', 'CC', 'CK', 'CY', 'DM', 'FK', 'FJ', 'GD', 'GG', 'GY', 'HK', 'IN', 'ID', 'IE', 'IM', 'JM', 'JP', 'JE', 'KE', 'KI', 'LS', 'MO', 'MW', 'MY', 'MV', 'MT', 'MU', 'MS', 'MZ', 'NA', 'NR', 'NP', 'NZ', 'NU', 'NF', 'PK', 'PG', 'PN', 'SH', 'KN', 'LC', 'VC', 'WS', 'SC', 'SG', 'SB', 'SO', 'ZA', 'GS', 'LK', 'SR', 'SZ', 'TH', 'TL', 'TK', 'TO', 'TT', 'TC', 'TV', 'UG', 'GB', 'TZ', 'VI', 'ZM', 'ZW']:
solver.add(f(s0, s1))
for s0, s1 in ['AF', 'AX', 'AL', 'DZ', 'AS', 'AD', 'AO', 'AQ', 'AR', 'AM', 'AW', 'AT', 'AZ', 'BH', 'BY', 'BE', 'BZ', 'BJ', 'BO', 'BA', 'BV', 'BR', 'IO', 'BG', 'BF', 'BI', 'CV', 'KH', 'CM', 'CA', 'CF', 'TD', 'CL', 'CN', 'CO', 'KM', 'CG', 'CR', 'CI', 'HR', 'CU', 'CW', 'CZ', 'KP', 'CD', 'DK', 'DJ', 'DO', 'EC', 'EG', 'SV', 'GQ', 'ER', 'EE', 'ET', 'FO', 'FI', 'FR', 'GF', 'PF', 'TF', 'GA', 'GM', 'GE', 'DE', 'GH', 'GI', 'GR', 'GL', 'GP', 'GU', 'GT', 'GW', 'GN', 'HT', 'HM', 'VA', 'HN', 'HU', 'IS', 'IR', 'IQ', 'IL', 'IT', 'JO', 'KZ', 'KW', 'KG', 'LA', 'LV', 'LB', 'LR', 'LY', 'LI', 'LT', 'LU', 'MG', 'ML', 'MH', 'MQ', 'MR', 'YT', 'MX', 'FM', 'MC', 'MN', 'ME', 'MA', 'MM', 'NL', 'NC', 'NI', 'NG', 'NE', 'MP', 'NO', 'OM', 'PW', 'PA', 'PY', 'PE', 'PH', 'PL', 'PT', 'PR', 'QA', 'KR', 'MD', 'RE', 'RO', 'RU', 'RW', 'BL', 'MF', 'PM', 'SM', 'ST', 'SA', 'SN', 'RS', 'SL', 'BQ', 'SX', 'SK', 'SI', 'SS', 'ES', 'PS', 'SD', 'SJ', 'SE', 'CH', 'SY', 'TW', 'TJ', 'MK', 'TG', 'TN', 'TR', 'TM', 'UA', 'AE', 'UM', 'US', 'UY', 'UZ', 'VU', 'VE', 'VN', 'WF', 'EH', 'YE']:
solver.add(z3.Not(f(s0, s1)))
res = solver.check()
print(res)
if res == z3.sat:
m = solver.model()
print('n={} k={} c={} a={!r}'.format(n, k, c, binascii.unhexlify('{:0{}x}'.format(
int(''.join('01'[z3.is_true(m[x])] for x in a), 2), n // 8 * 2))))
```
[Answer]
# sed, ~~148+1~~ ~~145+1~~ ~~143+1~~ 142+1 bytes
One extra byte for `-r` flag (POSIX extended regexes).
Outputs empty string for left-handed traffic, original country code for the right-handed traffic.
```
s/A[GIU]|B[BDMNSTW]|C[CXY]|DM|FJ|G[BDGSY]|I[DEMN]|J[^O]|K[EINY]|L[CS]|M[OS-WYZ]|N[AFP-Z]|P[GN]|S[BCGHORZ]|T[CHLOTVZ]|UG|V[CGI]|WS|Z.|[^DMS]K//
```
Example:
```
$ echo -e 'PY\nPN\nCN\nGY' | sed -re 's/A[GIU]|B[BDMNSTW]|C[CXY]|DM|FJ|G[BDGSY]|I[DEMN]|J[^O]|K[EINY]|L[CS]|M[OS-WYZ]|N[AFP-Z]|P[GN]|S[BCGHORZ]|T[CHLOTVZ]|UG|V[CGI]|WS|Z.|[^DMS]K//'
PY
CN
$
```
Explained edit history:
```
148 s/A[GIU]|B[BDMNSTW]|C[CKXY]|DM|F[JK]|G[BDGSY]|HK|I[DEMN]|J[EMP]|K[EINY]|L[CKS]|M[OSTUVWYZ]|N[AFPRUZ]|P[GKN]|S[BCGHORZ]|T[CHKLOTVZ]|UG|V[CGI]|WS|Z.//
naïve regexp; the only optimization here is 'Z.'
145 s/A[GIU]|B[BDMNSTW]|C[CKXY]|DM|F[JK]|G[BDGSY]|HK|I[DEMN]|J[EMP]|K[EINY]|L[CKS]|M[OS-WYZ]|N[AFP-Z]|P[GKN]|S[BCGHORZ]|T[CHKLOTVZ]|UG|V[CGI]|WS|Z.//
M[OSTUVWYZ] → M[OS-WYZ]
N[AFPRUZ] → N[AFP-Z]
the replacements can match inexistent coutries, which is totally fine
143 s/A[GIU]|B[BDMNSTW]|C[CXY]|DM|FJ|G[BDGSY]|I[DEMN]|J[EMP]|K[EINY]|L[CS]|M[OS-WYZ]|N[AFP-Z]|P[GN]|S[BCGHORZ]|T[CHLOTVZ]|UG|V[CGI]|WS|Z.|[^DMS]K//
|[^DMS]K (which also matches impossible country codes) allows these changes:
C[CKXY] → C[CXY]
F[JK] → FJ
|HK → ∅
L[CKS] → L[CS]
P[GKN] → P[GN]
T[CHKLOTVZ] → T[CHLOTVZ]
142 s/A[GIU]|B[BDMNSTW]|C[CXY]|DM|FJ|G[BDGSY]|I[DEMN]|J[^O]|K[EINY]|L[CS]|M[OS-WYZ]|N[AFP-Z]|P[GN]|S[BCGHORZ]|T[CHLOTVZ]|UG|V[CGI]|WS|Z.|[^DMS]K//
J[EMP] → J[^O] (thanks @Neil)
```
## sed, ~~158+1~~ ~~155+1~~ ~~153+1~~ 152+1 bytes, non-empty answer
Slight variation of the previous one. Returns `L` for left-handed traffic.
```
s/[GIU]|B[BDMNSTW]|C[CXY]|DM|FJ|G[BDGSY]|I[DEMN]|J[^O]|K[EINY]|L[CS]|M[OS-WYZ]|N[AFP-Z]|P[GN]|S[BCGHORZ]|T[CHLOTVZ]|UG|V[CGI]|WS|Z.|[^DMS]K/&L/;s/^..//
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 108 bytes
```
1∊⍷∘'TTHSZWMSGSONPKNZMWVIDFKELSCYJPNFJMTVCXBNRBWSHKYAUGGYBTLCCKIMVGBSBBMZAINAGDMOBDIEJEMYMUNUPGSRLKTKTOTCTZ'
```
[Try it online!](https://tio.run/##vZPBbtQwFEX38xXZBaSyYMvOdhInk9jjxk6mk91Q2qpSaRHTLhBiiyqkkdggseEzKv5nfmRozpPgD9hcOfZ99937HG8/3Lx692l7c3d1PL4@PH477H8fHn/mKdVxWrto48qH1k9uPTZF1ZZdNJtl8NXSpdGcad/rdazbjRqs3ejUGdM2brQ6au0m1XhlC7fSRVMuS7dxgx@CjX3XpjatkklTfjwe9r8yt72@zS4fbs/vr@9usxe7h7fvr3e75/XLxeIyO3z9nv1/Z4vF7Cxd7O4vPv71tlhcYefzYf90kr/J8pPD/sfl88eXf/TsfLu72D0zc9XkM1pwmFFHsAA16MAErmcc4Ws/Y7uZ0ZyBBmxB9gtqK3aq5YwWZYuChVNz2qDWcNqUILVLwQCy3wrivMOtW4F4c2i6EcSzI5cT5jSjV2APouxlH6avZgy4CvgMeIs1fVl3JB3BNcqRdYQfmVvE1UQvC6dDM9I30jGhmTqQ00RVwnlCM5FlkImhnKgdmcDEfCayK5wr7kKhWcBUdFfMVqGvTkGcKBSUKNBXUaXxppmnZuZa9rlHjY4mncahRq2RfflD8KPxaeC0aBo6GmoNnIQ3g2fDhA06rTBRM@gb1GpZc18G5wZvLbdpUCuYZ4HbArWSeZZyR/ixzKFErSRjyQQq@BW9Kk6t/BXiFrRyszi01BagJaOl1kotuSzeLJ4tXSzOLXlrdmrURpRr2YffcIONTBjPDZoNVUuZlUwAzZaMHTodSTv@nA6Fjjvt5AWh0Mkbocqh7Ejh6OWo2shr4u@q8OmYp8OnI7ujo@PUo@PheHp59L0w5d3hfAU/4DygEHAYYAacBNQCHgJ@TmG2rB033sPv0exJ1KOpJZHcIL2iIGoRnUiKXt4yfE32SN4oL5cUEU4JBuHTPfKnRTwYPEdSJDwkTp28ceaQ6Jjwn/Az4EShMMgO@gM6g7x6co1wRhTW5CrpuCnzPw "APL (Dyalog Unicode) – Try It Online")
Using the lookup string by ovs.
Left-handed traffic = `1`.
Right-handed traffic = `0`.
[Answer]
# Javascript (ES6), ~~118~~ 116 bytes
Saved 2 bytes thanks to @Craig Ayre
```
s=>"SZAINAGGDMOAUGBBSCCKIMWSHKYLSBMVGSGYBDBTHBWBNRMZMTLCXSRTVCYPNFKNPKEFJMYVIDIEJPGJEMUNZWMSONULKTKTOTTCTZ".match(s)
```
Returns `null` for right-handed traffic
## Test Cases
```
f=s=>"SZAINAGGDMOAUGBBSCCKIMWSHKYLSBMVGSGYBDBTHBWBNRMZMTLCXSRTVCYPNFKNPKEFJMYVIDIEJPGJEMUNZWMSONULKTKTOTTCTZ".match(s)
console.log("AI,AG,AU,BS,BD,BB,BM,BT,BW,VG,BN,KY,CX,CC,CK,CY,DM,FK,FJ,GD,GG,GY,HK,IN,ID,IE,IM,JM,JP,JE,KE,KI,LS,MO,MW,MY,MV,MT,MU,MS,MZ,NA,NR,NP,NZ,NU,NF,PK,PG,PN,SH,KN,LC,VC,WS,SC,SG,SB,SO,ZA,GS,LK,SR,SZ,TH,TL,TK,TO,TT,TC,TV,UG,GB,TZ,VI,ZM,ZW".split`,`.every(s=>f(s)!=null))
console.log("AF,AX,AL,DZ,AS,AD,AO,AQ,AR,AM,AW,AT,AZ,BH,BY,BE,BZ,BJ,BO,BA,BV,BR,IO,BG,BF,BI,CV,KH,CM,CA,CF,TD,CL,CN,CO,KM,CG,CR,CI,HR,CU,CW,CZ,KP,CD,DK,DJ,DO,EC,EG,SV,GQ,ER,EE,ET,FO,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GP,GU,GT,GW,GN,HT,HM,VA,HN,HU,IS,IR,IQ,IL,IT,JO,KZ,KW,KG,LA,LV,LB,LR,LY,LI,LT,LU,MG,ML,MH,MQ,MR,YT,MX,FM,MC,MN,ME,MA,MM,NL,NC,NI,NG,NE,MP,NO,OM,PW,PA,PY,PE,PH,PL,PT,PR,QA,KR,MD,RE,RO,RU,RW,BL,MF,PM,SM,ST,SA,SN,RS,SL,BQ,SX,SK,SI,SS,ES,PS,SD,SJ,SE,CH,SY,TW,TJ,MK,TG,TN,TR,TM,UA,AE,UM,US,UY,UZ,VU,VE,VN,WF,EH,YE".split`,`.every(s=>f(s)==null))
```
[Answer]
**K, 105 bytes**
For information about K/Q languages see code.kx.com
Use: Country-code (2-char string, example "XY") after
```
in[;+\-48+5h$"62<729151368=1>a1A23<6<C181A83?45;488F411112115:235Q43r141738353135247F42Tl<:"]@26/:-65+5h$
```
Generates `1b` (Left-handed traffic) or `0b` (not Left-handed traffic)
Explanation:
* `5h$"XX"` generates ascii codes for each char of the 2-char string (country-code), Example `5h$"TB"` generates 84 66
* `-65+integerList` substract 65 to each integer in the list. Example `-65+5h$"TB"` generates 19 1
* `26/:integerList` computes integer equivalent to that list as digits in 26-base. Example `26/:-65+5h$"TB"` generates 495 (country-code as integer)
* `in[;listOfCountryCodesAsIntegers]@x` returns boolean value (1b = true, 0b = false). True if x is in the list
* `+\-48+5h$"62<729151368=1>a1A23<6<C181A83?45;488F411112115:235Q43r141738353135247F42Tl<:"` calculates list of integers for each country code with Left-handed traffic
+ `"62<729151368=1>a1A23<6<C181A83?45;488F411112115:235Q43r141738353135247F42Tl<:"` is the 'distance string' (distance between each pair of integer-country-codes in ascending order, codified as char). Distance n is codified as ascii char 48+n
+ `-48+5h$".."` calculates ascii value of each char in string ".." and recover original distance as ascii-code - 48. The result is the list of distances
+ `+\integerList` calculates partial summation of items from the list -> absolute integer-country-codes from distances between codes.
NOTES.-
* Returns `0b` for any non-left-handed country-code, including not valid country codes
* We can save a char reformatting the code, but requires to write country-code "XX" inside the code (i don't know if it's valid, but i'm quite sure it's not elegant)
`in[26/:-65+5h$"XX";+\-48+5h$"..."]`
[Answer]
# Vim, ~~117~~ ~~109~~ 108 keystrokes
```
oSZAINAGGDMOAUGBBSCCKIMWSHKYLSBMVGSGYBDBTHBWBNRMZMTLCXSRTVCYPNFKNPKEFJMYVIDIEJPGJEMUNZWMSONULKTKTOTTCTZ␛kg*D
```
[Try it online!](https://tio.run/##PY/BToMwGIDvPMWfhkjign2BuYSW0kFpIWsBIV5wVLfIRkQ2TYzv4N2380Vwp12/7/Dle2rfd7Pd7gZAmiFYwfO@t3fT5@SMtu3AH8HvACGgsFwCy6J50E0Qq4DzUGZBwQnRlIpYVnot6lQTWXLNaxISsyYVURvZSJPSB70xJa1zFQmVCxYlsi7jMGZJzhMmC9VUUmeqSIURJjOGmubv5/f15TacL0mH3iP3i2J8Ydj1Hq33jZzz/gD@CVSmGKDFcRgPbQ8uReAtPt686wXcrAB39oyPp753tu10NfM/) (replace `SE` in the header with the country code)
`␛` is the escape key. The program prints the following text for right-handed traffic:
```
SZAINAGGDMOAUGBBSCCKIMWSHKYLSBMVGSGYBDBTHBWBNRMZMTLCXSRTVCYPNFKNPKEFJMYVIDIEJPGJEMUNZWMSONULKTKTOTTCTZ
```
## Explanation
```
oSZAINA...OTTCTZ␛ Input the lookup-string on a new line
kg*D Delete the everything after the last occurence of the country code
on the same line
```
[Answer]
# [MY-BASIC](https://github.com/paladin-t/my_basic), 162 bytes
Anonymous Function that takes input as an unwrapped string (that is, without parenthesis) and outputs to the console
```
Input"",x$,
For y=0 To 100
z=z+(Mid("TTHSZWMSGSONPKNZMWVIDFKELSCYJPNFJMTVCXBNRBWSHKYAUGGYBTLCCKIMVGBSBBMZAINAGDMOBDIEJEMYMUNUPGSRLKTKTOTCTZ",y,2)=x$)
Next
Print z
```
Returns `0` for right-handed and `1` for left-handed traffic, [try it online!](https://tio.run/##BcFND0MwGADgu1/RNA5kltjuDlpU1Vuyvhi3fR0cxmKW4M/b87zX4/327R/7LofPb6bUW2zPSsaJrIFPcCQn37e2YDs40D8dipiargEjTKFLpTtoahklKs4Nb7NSJxlgza9MX1hjUtWGlRAtw5xzJaEWzDAGXSh1KCIoWCTjLIYWKl2VwlxyhQoL5NhRb/XObrDYrqVfy2yVUz/MZNt3xD8 "MY-BASIC – Try It Online")
[Answer]
# [Yabasic](http://www.yabasic.de), 127 bytes
Anonymous function that takes input as an unwrapped string (no `"..."`) and outputs `0` if the Country is right-handed and `1` if the country is left handed.
```
Input""A$
?InStr("TTHSZWMSGSONPKNZMWVIDFKELSCYJPNFJMTVCXBNRBWSHKYAUGGYBTLCCKIMVGBSBBMZAINAGDMOBDIEJEMYMUNUPGSRLKTKTOTCTZ",A$)>0
```
[Try it online!](https://tio.run/##BcG9DsIgEADg3ccgHTRx8Ak0HLQU6FHSu/7AVp1cGqN18Onx@37rff08H6XY7fXdhZDV4WY32t9HwdxSnpEM9SH6kHGerG583ZFKLobGIU9qgTDATK1PcjQmAXdKeYuTAQLALG2QRmMP2tauxoRjGKOhofPsuWfFWZxldbpeSqH8Bw "Yabasic – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~115~~ 107 bytes
```
f(short*x){x=!wcschr(L"䥁䝁啁卂䑂䉂䵂呂坂䝖乂奋塃䍃䭃奃䵄䭆䩆䑇䝇奇䭈义䑉䕉䵉䵊偊䕊䕋䥋卌位坍奍噍呍啍卍婍䅎剎偎婎啎䙎䭐䝐乐䡓之䍌䍖南䍓䝓䉓体䅚升䭌剓婓䡔䱔䭔佔呔䍔噔䝕䉇婔䥖䵚坚",*x);}
```
[Try it online!](https://tio.run/##dY@xasJQGIX3PoUNFJJin0A6dGkp@AhdSorVobaoUEEcclNNr/oHw72xKNzBIUOGDA4ZMuRtzv8c6YWuFc5wDh@Hw/FvXn2/aXruuP8@mlxPvdn09vLTH/v9kdt1kAUwAacBk0AiIAVKwYlgI2B2qARnaz6GoBBFyFmI8gvFEvkSSQQTcRah@EYlkUikEqXVioMVUqs1bJc2qIkNcUa8J06IU2IizgmLmGXMQcx5zGmMfYxiC7NFtcVRoVrDdmnH9ANSMApSoVZYHJjs6Ial4lzhqHHSKDRqzYkGad5rmBQy4lwj26E8sDk4bXu8M28Gw0nr7XkwdL3ZxcfIpp7rXL08DZ22NXf3jtfyOv@Ax3Pg4Rzo/oF58ws "C (gcc) – Try It Online")
Returns `0` if left handed. -4 thanks to @JonathanFrech
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `r`, 65 bytes
```
⇩«°ǎ+₃∧M⋏⁼•¼¾E⇧M∪∵IḞ½ð∷⅛ḃxṀ⌊ż‹←∵o8ƒ₈£…₌⌈⋏L⟑₇₌±M…uġεƛǏ∆%zKɾ\@(L-«c
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=r&code=%E2%87%A9%C2%AB%C2%B0%C7%8E%2B%E2%82%83%E2%88%A7M%E2%8B%8F%E2%81%BC%E2%80%A2%C2%BC%C2%BEE%E2%87%A7M%E2%88%AA%E2%88%B5I%E1%B8%9E%C2%BD%C3%B0%E2%88%B7%E2%85%9B%E1%B8%83x%E1%B9%80%E2%8C%8A%C5%BC%E2%80%B9%E2%86%90%E2%88%B5o8%C6%92%E2%82%88%C2%A3%E2%80%A6%E2%82%8C%E2%8C%88%E2%8B%8FL%E2%9F%91%E2%82%87%E2%82%8C%C2%B1M%E2%80%A6u%C4%A1%CE%B5%C6%9B%C7%8F%E2%88%86%25zK%C9%BE%5C%40%28L-%C2%ABc&inputs=AU&header=&footer=)
] |
[Question]
[
In [this question](https://codegolf.stackexchange.com/questions/111190/anagram-quines-cops-thread) I asked you to guess an anagram quine based on its output. However it looks like we don't have a question asking to golf an anagram quine yet. So your task will be to make the shortest anagram quine that you can.
### What is an anagram quine?
An anagram quine is a non empty program that prints an anagram of its source code, other than its original source.
Here's an example of an anagram quine in Python 2:
```
print`'`print`*2'*2`
```
You should not read your own source for this challenge.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 2 bytes
```
)(
```
Outputs
```
()
```
[Try it online!](https://tio.run/##K6gsyfj/X1Pj/38A "Pyth – Try It Online")
```
) # Ends statement, does nothing in this program
( # Create an empty tuple
# Implicitly print the empty tuple
```
[Answer]
# [V](https://github.com/DJMcMayhem/V), 4 bytes
```
2ii2
```
Outputs:
```
i2i2
```
[Try it online!](https://tio.run/##K/v/3ygz0@j/fwA "V – Try It Online")
[Answer]
# [><>](https://esolangs.org/wiki/Fish), ~~9~~ ~~8~~ 7 bytes
*Golfed 1 byte thanks to @WheatWizard by using `!` and incrementing it to get `"`*
*Golfed 1 byte thanks to @ConorO'Brien by using `#` instead of `<!`*
```
":1->o#
```
[Try it online!](https://tio.run/##S8sszvj/X8nKUNcuX/n/fwA "><> – Try It Online")
Outputs `"#o>-1:`.
### Explanation
```
":1->o#" Push this string (note that the IP wraps around)
: Duplicate the top value of the stack (35 from the "#")
1- Subtract one from it to get 34 ('"')
>o# Print every character on the stack until the program cannot pop any more and still tries to pop a value from the stack afterwards
The program exits with an error from not being able to pop a value from an empty stack
```
[Answer]
# Brainfuck, 158 bytes
```
>>--<<-[[<+>->+>->+++<<<]>-]<<<<<<[--->>.<<]>>++<<<[->>>.<<<]>>-<<<[--->>>.<<<]>>>--<<<<[++>>>>.<<<<]>>>>+++>--.[---<.>]>+.......++.......<<<>>>>>>>>>-----+++
```
[Try it online!](https://tio.run/##PYxRCoVQCEQXJOMKZDYi96OCIB68j6D1m1q3AcE5jrOey/Hfr@0XQQJmcDch2CNiZoMY1nIApBZinzxt@QL4ApN0X0IRvrBp1eZJK2zKQdFHMpcMcgql/Ii4AQ)
It may not be the shortest version, but at least it works.
*Fun fact*, the output code can actually be executed (and it does terminate).
## Output
```
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>--------------------------++++++++++++++++++<....................[[[[[[[]]]]]]]
```
## Explanation
```
>>--<<-[[<+>->+>->+++<<<]>-] Initializes the tape with the
help of a recurrence relation.
<<<<<<[--->>.<<]>>++<<<[->>>
.<<<]>>-<<<[--->>>.<<<]>>>-- Prints the characters using
<<<<[++>>>>.<<<<]>>>>+++>--. classic loops.
[---<.>]>+.......++.......
<<<>>>>>>>>>-----+++ Junk to complete the anagram.
```
[Answer]
# Python 3, 32 bytes
```
print("""p"r"i"n"t"2(")*"""*2)
```
Prints `p"r"i"n"t"2(")*p"r"i"n"t"2(")*\n`, sorted output: `\n""""""""""""(())**22iinnpprrtt`
[Answer]
# [Ruby](https://www.ruby-lang.org/), 8 bytes
```
p"p*2"*2
```
[Try it online!](https://tio.run/##KypNqvz/v0CpQMtIScvo/38A "Ruby – Try It Online")
This prints
```
"p*2p*2"
```
## Explanation
This works similar to the python answer in the question. It will make the string `p*2p*2` then using Ruby's `p` will print the representation of the string.
[Answer]
## JavaScript (ES6), ~~40~~ 32 bytes
```
f=($=`($)=>{$=$+"${"``"}$"}`)=>$+$
```
No messing around with Function.toString either. As a bonus, the code inside the string almost looks legal. Edit: Saved 8 bytes by using `+` instead of `repeat(2)`.
[Answer]
# [Klein](https://github.com/Wheatwizard/Klein), 7 + 6 = 13 bytes
Here's an answer based on the [><> answer](https://codegolf.stackexchange.com/a/125056/56656).
```
":1+@!
```
[Try it online!](https://tio.run/##y85Jzcz7/1/JylDbQZHr////BgYG/3UdAQ "Klein – Try It Online")
This outputs
```
:1+@!"
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~10~~ 9 bytes
Found a better way :-)
```
Q+2ç"Q+2ç
```
Outputs `"Q+2çQ+2ç`. [Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=USsy5yJRKzLn&input=)
### Explanation
```
Q+2ç"Q+2ç // Implicit: Q = quotation mark
"Q+2ç // Take this string. Q+2ç
2ç // Repeat it twice. Q+2çQ+2ç
Q+ // Prepend a quote. "Q+2çQ+2ç
// Implicit: output result of last expression
```
Could also be `Qi2ç"Qi2ç`, which prints `Qi2çQi2ç"`. This one is closer to the standard Japt quine:
```
"iQ ²"iQ ²
```
But I do not believe there is any easy way to wedge the quotation mark in the middle of the string for a 9-byte quine.
[Answer]
## Ruby, 20 bytes
```
$><<%q($><<%q()*2)*2
```
This outputs
```
$><<%q()*2$><<%q()*2
```
Taking advantage of Ruby's `%q(...)` string syntax, which supports nested parentheses.
[Answer]
## [Retina](https://github.com/m-ender/retina), 8 bytes
```
_
$nn$
```
[Try it online!](https://tio.run/##K0otycxL/P@fK56LSyUvT@X/fwA "Retina – Try It Online")
Prints
```
n$_
n$
```
Both contain one `_`, two `n`, two `$` and three linefeeds.
Note that a linefeed followed by almost any other character is a trivial solution, but it's questionable whether it's valid, because the second character only encodes itself and the linefeed doesn't really encode either output character.
## Explanation
```
_
```
Replace the empty input with a `_`.
```
$nn$
```
Match an empty string, which happens both before or after the `_` and insert a linefeed (`$n`), an `n`, and a `$`. Since we first inserted that `_`, this adds each of those characters twice, so the `n` and `$` account for the `$n`, and we get two of the three linefeeds we need in the output. The third linefeed is printed because Retina prints a trailing linefeed by default.
We could also use `n$n$` in this stage, which would then print:
```
n
$_n
$
```
[Answer]
# Python Repl, 4 bytes
This is my first Code Golf solution, so I hope it meets the rules. In the Python 2 or 3 interactive interpreter:
```
>>> (1),
(1,)
```
The output is an anagram of the input.
---
Another:
```
>>> 2*'2*'
'2*2*'
```
In Python 2:
```
>>> type('rst <>'),
(<type 'str'>,)
```
In Python 3:
```
>> {1, 0}
{0, 1}
```
Update 2017-06-15: Yet another:
```
>>> 01.
1.0
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~38~~ 39 bytes
```
main=print$[0,0]>>"main=print$[0,0]>>"
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/PzcxM8@2oCgzr0Ql2kDHINbOTgmLENf//wA "Haskell – Try It Online") Output:
```
"main=print$[0,0]>>main=print$[0,0]>>"
```
Edit: +1 byte because I previously forgot about the implicit trailing newline of `print`.
---
**Alternative:** (Same byte count but does not contain ASCII-owl)
```
main=print$e++e;e="main=print$e++e;e="
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/PzcxM8@2oCgzr0QlVVs71TrVVgmLENf//wA "Haskell – Try It Online")
Output:
```
"main=print$e++e;e=main=print$e++e;e="
```
[Answer]
# Groovy, ~~24~~ 20 bytes
```
{"""{""*""2""}"""*2}
```
*-4 thanks to CalculatorFeline, the whitespace wasn't needed after all!*
# Output:
```
{""*""2""}{""*""2""}
```
# Explanation:
Anonymous closure that, when called, returns `{""*""2""}` two times (concatenated).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
```
'∞∞''∞'JJ∞
```
[Try it online!](https://tio.run/##MzBNTDJM/f9f/VHHPCBSB9HqXl5A8v9/AA "05AB1E – Try It Online")
# Output:
```
∞∞''JJ''∞∞
```
---
# Explanation:
```
Code | Explanation | Stack
-----------+----------------------------+-------------------
'∞ | Push literal '∞'. | ["∞"]
∞ | Mirror. | ["∞∞"]
'' | Push literal "'". | ["∞∞","'"]
∞ | Mirror. | ["∞∞","''"]
'J | Push literal 'J'. | ["∞∞","''","J"]
J | Join it all together. | ["∞∞''J"]
∞ | Mirror. | ["∞∞''JJ''∞∞"]
-----------+----------------------------+-------------------
| Implicit print. | ∞∞''JJ''∞∞
```
[Answer]
## [CJam](https://sourceforge.net/p/cjam), 6 bytes
```
"_`"_`
```
[Try it online!](https://tio.run/##S85KzP3/Xyk@AYj@/wcA "CJam – Try It Online")
Prints
```
_`"_`"
```
### Explanation
```
"_`" e# Push this string.
_ e# Duplicate.
` e# Stringify it, which wraps it in quotes.
e# Implicitly print stack contents.
```
[Answer]
## Bash, 36 bytes
```
tee f<<<'tee f<<<""cat f'"''"
cat f
```
This outputs
```
tee f<<<""cat f''
tee f<<<""cat f''
```
(and creates the file `f` as a side effect, but that's allowed [per meta](https://codegolf.meta.stackexchange.com/q/8871/3808).)
Both the program and output have a trailing newline.
Thought process: I figured that the easiest way to output a string two times, aside from assigning it to a variable, was to do
```
tee f<<<string
cat f
```
The string needs to be quoted because it will contain spaces and `<` characters, so then I had
```
tee f<<<'tee f<<<cat f'
cat f
```
which almost works, except it doesn't output the quotes. Fortunately, Bash supports string literal concatenation by simply placing them next to each other, so appending `"''"` to the herestring and inserting `""` inside the single quote part yields this solution.
[Answer]
# [PHP](https://php.net/), 44 bytes
```
<?=str_repeat('<?=\str_\repeat(\'\',2);',2);
```
[Try it online!](https://tio.run/##K8go@P/fxt62uKQovii1IDWxREMdyI0B8WOgAjHqMeo6RprWYOL//695@brJickZqQA "PHP – Try It Online")
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 8 bytes
```
"2*`"2*`
```
[Try it online!](https://tio.run/##S85KzP3/X8lIKwGE//8HAA "CJam – Try It Online")
### Explanation
Similar to the Python example in the question
```
"2*`" e# Push the string "2*`"
2* e# Repeat it twice
` e# Get its string representation (wrap in quotes)
```
The output is `"2*`2*`"`.
[Answer]
# Befunge, 11 bytes
```
' 2+">:#,_@
```
Prints:
```
+2 '@_,#:>"
```
Explanation:
```
' 2+" Put a " on the stack (32 + 2)
" Put the rest of the code on stack (wrap-around string)
>:#,_ Print stack
@ End
```
[Answer]
# [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 8 bytes
```
?A+@?A@+
```
I [just figured out](https://codegolf.stackexchange.com/a/125089/44874) how to do a proper quine in QBIC. Making an anagram out of it is done by simply switching around the characters in the string literal. There are 24 possible anagrams this way.
[Answer]
# [Befunge-98](https://github.com/catseye/FBBI), 8 bytes
```
"'$<@,k7
```
[Try it online!](https://tio.run/##S0pNK81LT9W1tPj/X0ldxcZBJ9v8/38A "Befunge-98 – Try It Online")
[Answer]
# [Ohm](https://github.com/MiningPotatoes/Ohm), 14 bytes
```
"æ3M.Cæ"æ3M."C
```
[Try it online!](https://tio.run/##y8/I/f9f6fAyY18958PLIAwl5///AQ "Ohm – Try It Online")
Output:
```
æ3M.CæC.M3æ"""
```
### Explanation
```
"æ3M.Cæ"æ3M."C
"æ3M.Cæ" # Pushes "æ3M.Cæ"
æ # Palindrone of that string
3M # 3 times...
." # Push " on the stack
C # Concatenate with the string above
```
[Answer]
# JavaScript (ES6), 15 bytes
```
f=(s='f=')=>f+s
```
**Outputs:**
```
(s='f=')=>f+sf=
```
**Snippet:**
```
f=(s='f=')=>f+s
console.log(f());
```
[Answer]
# [Fission 2](https://github.com/C0deH4cker/Fission), ~~9 8~~ 6 bytes
```
R"'!+O
```
[Try it online!](https://tio.run/##S8ssLs7MzzP6/z9ISV1R2///fwA "Fission 2 – Try It Online")
# Explanation
An atom is created at `R`, which moves right. This atom then comes across a `"`, which starts printing mode. In printing mode, all characters (until the matching `"`) are printed. This means it prints `'!+OR` in this case. Then, all that is left is printing `"`, which is done by the remaining characters. `'!` sets the atom's mass to the character code of `!`, and `+` increments it to the character code of `"`. Then, the character code is output by `O` and the atom is destroyed, ending the program.
(Actually, this is just a rotation of the shortest quine)
[Answer]
# Mathematica, 2 bytes
```
.0
```
Output:
```
0.
```
A number starting with a decimal point such as `.123` is interpreted as `0.123`, so `.0` is interpreted as `0.0`. Since the part of the number after the decimal point is zero, Mathematica does not print it.
[Answer]
# JavaScript (yet another one), 11 bytes
```
f=_=>'=f'+f
```
Called with `f()`, outputs
```
=f_=>'=f'+f
```
```
f=_=>'=f'+f
console.log(f());
```
[Answer]
Python 3, 31 bytes
```
a='a=%r;pritn(a%%a)';print(a%a)
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~8~~ 4 bytes
```
.S.S
```
[Run and debug online!](https://staxlang.xyz/#c=.S.S&i=&a=1)
A direct port of [this answer](https://codegolf.stackexchange.com/questions/69/golf-you-a-quine-for-great-good/156643#156643).
Old version, 8 bytes
```
..b..LbL
```
[Run and debug online!](https://staxlang.xyz/#c=..b..LbL&a=1)
Alternative version with a pretty cheap trick that can be applied to proper quines in almost any language.
```
"43bL"34bL
```
[Run and debug online!](https://staxlang.xyz/#c=%2243bL%2234bL&a=1)
Because `"34bL"34bL` is a proper quine in Stax.
Yet another version, using only single-char string literals.
```
''c'Lc'cccLcLL
```
[Run and debug online!](https://staxlang.xyz/#c=%27%27c%27Lc%27cccLcLL&i=&a=1)
## Explanation
```
.S.S Generates powerset ["","S","S.","."]
Implicit flatten and output
..b Push string ".b"
..L Push string ".L"
b Duplicate both strings
L Concatenate all 4 strings to a single one.
```
[Answer]
## [W](https://github.com/A-ee/w), 2 bytes
```
1-
```
## Explanation
```
a % (Implicit) argument of the input
% The input is automatically set to 0
% if it isn't specified
1- % Minus 1 over the input (i.e. 0-1 = -1)
```
Output:
```
-1
```
] |
[Question]
[
**This question already has answers here**:
[Stop, stand there where you are!](/questions/55293/stop-stand-there-where-you-are)
(29 answers)
Closed 6 years ago.
I'm currently cooking us some cup noodles, but we're really sleepy at the moment. They'll be finished in 50 seconds from now, can you wake me up then?
## Problem:
Write a program or function that waits 50 seconds of busy waiting (so that you too doesn't sleep) and then outputs at least 1 visible character to wake me up.
## Busy waiting:
You can't use functions like `sleep` or `delay` or `pause` to wait for the 50 seconds, you have to keep checking the elapsed time.
## Rules:
* Your code must be somewhat consistent in time, between runs and between computers. A small error of +- 1 seconds is acceptable.
* You can't output any visible characters between 1 and 50 seconds (let me sleep).
* Whitespace characters (newline, space, tab, ...) are not considered visible characters for this challenge.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins.
[Answer]
# Octave, ~~22~~ 21 bytes
Saved one byte by changing from `while ... end` to `do ... until`.
```
tic;do
until toc>50;1
```
`tic` starts a timer, while `toc` returns the number of decimal seconds since the last call to `tic`. We initiate a **do - until** loop, where we'll loop until `toc>50`, doing nothing inside the loop. The loop stops after 50 seconds, followed by `ans = 1` on the screen.
Try it on [**TIO** (time changed to 5 seconds)](https://tio.run/##y08uSSxL/f@/JDPZOiWfqzSvJDNHoSQ/2c7U2vD/fwA) or paste it into [**Octave Online**](http://octave-online.net/).
[Answer]
# [MATL](https://github.com/lmendo/MATL), 7 bytes
```
1`Z`50<
```
[Try it online!](https://tio.run/nexus/matl#@2@YEJVgaGDz///XvHzd5MTkjFQA "MATL – TIO Nexus") The linked code uses `10` instead of `50`.
### Explanation
```
1 % Push 1
` % Do...while
Z` % Elapsed time since program started
50 % Push 50
< % Less than?
% End (implicit). The loop continues if top of the stack is truthy
% Display (implicit)
```
[Answer]
# [Lua](https://www.lua.org), 35 bytes
```
while os.clock()<50 do end;print'!'
```
odd thing is that it has exactly the same length as:
```
repeat until os.clock()>50;print'!'
```
[Try it online!](https://tio.run/nexus/lua#@1@ekZmTqpBfrJeck5@craFpY2qgkJKvkJqXYl1QlJlXoq6o/v8/AA "Lua – TIO Nexus")
[Answer]
# TI-Basic, ~~14~~ 12 bytes
```
startTmr
While 50>checkTmr(Ans
End
```
(Ab)uses the fact that TI programs output `Done` if nothing is evaluated on the last line.
[Answer]
# **Perl 5.10, 21 bytes**
```
{$^T+50<time?do:redo}
```
Outputs "Null filename used at -e line 1." after [50,51) seconds.
Or **22 bytes** for Perl 5.22:
```
{$^T+50<time?die:redo}
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~57~~ 54 bytes
*-3 bytes thanks to Felipe Nardi Batista.*
```
from time import*
b=time()+50
while time()<b:0
print 1
```
[Try it online!](https://tio.run/nexus/python2#@59WlJ@rUJKZm6qQmVuQX1SixZVkC@JqaGqbGnCVZ2TmpCpA@DZJVgZcBUWZeSUKhv//f83L101OTM5IBQA "Python 2 – TIO Nexus")
## Another solution, 48 bytes
This answer will only work if printing to STDERR is allowed. This will end in a NameError, printing *much* more than one character.
```
from time import*
b=time()+50
while time()<b:0
a
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 21 bytes
-1 thanks to [marinus](https://codegolf.stackexchange.com/users/1426/marinus).
```
{3⊃⍵≥⎕AI:∇⍵⋄1}5e4+⎕AI
```
`⎕AI` **A**ccount **I**nformation (UserID, ComputeTime, ConnectTime, KeyingTime)
`5E4+` add 50000 (milliseconds)
`{` apply the following anonymous function where the argument is represented by *⍵*
[if the]
`3⊃` third item (truth value, i.e that of ConnectTime) of
`⍵≥⎕AI` *⍵* is greater than or equal to **A**ccount **I**nformation
`:` then
`∇⍵` recurse this function on the unmodified argument
`⋄` else
`1` return one
`}` [end of anonymous function]
[Try it online!](https://tio.run/nexus/apl-dyalog#e9TRHpSZl@6b@r/a@FFX86PerY86lz7qm@roafWoox3E7W4xrDVNNdEGC/4HCv6HaAAA "APL (Dyalog Unicode) – TIO Nexus") *Debug* says *Real time: 50.039 s*, or *disable output cache* for real-time effect.
[Answer]
## C, ~~45~~ ~~44~~ 43 bytes
```
i;f(){for(time(&i);time(0)-i<50;);puts(f);}
```
See it [work here](https://tio.run/nexus/c-gcc#@59pnaahWZ2WX6RRkpmbqqGWqWkNZhho6mbamBpYa1oXlJYUa6RpWtf@z8wrUchNzMzTUCjLz0xR0OSq5uIE6law5qr9DwA).
[Answer]
## Bash, 26 bytes
```
f()(((SECONDS<50))&&f);f;.
```
Partially ungolfed:
```
f () (
((SECONDS < 50)) && f
)
f
.
```
[`SECONDS`](https://www.gnu.org/software/bash/manual/bash.html#index-SECONDS) is a magic variable that counts the number of seconds since the shell started. I define a function that recurses until the value is below the threshold. Once the wait is over, run the builtin `.` which prints an error message because it's missing an argument.
Beware that since the function's body is in parentheses, bash forks a new process for each recursive invocation, which may consume a lot of entries in your process table. A loop would keep resource usage down, but it's longer.
```
for((;SECONDS<50;));do :;done;.
```
If you want to have output on standard output rather than to the screen and you're running a sufficiently Unix-like system with at least one user logged in, you can replace the final `.` by `w`. If you want to stick to pure bash then I can't think of a way to produce output in less than **28 bytes**.
```
f()(((SECONDS<50))&&f);f;pwd
```
[Answer]
# Pyth, 9 bytes
```
W>50.d1;G
```
[Try it here.](http://pyth.herokuapp.com/?code=W%3E50.d1;G)
[Answer]
# PHP, ~~42~~ 36 bytes
```
for($t=time();time()-$t<50;);echo 1;
```
* -6 bytes, thanks to @Titus
**How to run**
```
> php -r <code>
```
[Answer]
# Javascript, ~~43~~ ~~39~~ ~~37~~ ~~35~~ ~~34~~ 33 bytes
```
for(t=+new Date;new Date<t+5e4;)1
```
Outputs `1` after 50 seconds.
Open console and run snippet. The snippet only runs for 5 seconds, so your page won't stall for too long :)
```
for(t=+new Date;new Date<t+5e3;)1
```
*Saved **10(!)** bytes thanks to @CraigAyre*:
* 43 : `t=+new Date();while(+new Date()<t+50000)0;x`
* 39 : `t=+new Date;while(+new Date<t+50000)0;x`
* 37 : `t=+new Date;while(+new Date<t+5e4)0;x`
* 35 : `t=+new Date;while(new Date<t+5e4);x`
* 34 : `t=+new Date;while(new Date<t+5e4)1`
* 33 : `for(t=+new Date;new Date<t+5e4;)1`
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~16~~ 14 bytes
```
žc50+60%[DžcQ#
```
[Try it online!](https://tio.run/nexus/05ab1e#@390X7KpgbaZgWq0C5AZqPz//9e8fN3kxOSMVAA)
I'm new to 05AB1E, so any golfing tips would be appreciated.
**Explanation:**
```
žc50+60%[DžcQ#
žc Push current amount of seconds.
50+ Add 50.
60% Modulo 60.
[ Infinite loop.
D Duplicate top of stack
žc Push current seconds.
Q# If current seconds, and start time+50 are the same, break.
Implicit print.
```
The basic idea of this program is to get what the time will be in 50 secs and loop until the current time is equal. So to get the time in 50 seconds, it gets the current time and adds 50. Then, since 05AB1E's clock returns the time since the last minute change, it needs to modulo 60, to get back in the correct range. Then the program loops until the second amount is the same as the desired.
[Answer]
# Processing, 47 bytes
```
void draw(){if(millis()>5e4){print(X);exit();}}
```
After 50 seconds, the program prints `0` and exits.
[Answer]
# PowerShell, 38
```
for($d=(date)+[int]5e8;(date)-lt$d){}1
```
Very trivial; will just wait until the time is 50 seconds later and then prints `1`.
[Answer]
# Java, ~~116~~ ~~114~~ ~~109~~ 105 bytes
* -2 bytes, thanks to @jaxad0127
* -4 bytes, thanks to @KevinCruijssen
[**Try Online**](https://tio.run/nexus/java-openjdk#dY0xC8IwFIRn@ysyJqDFxSm6uzjVTRxiDfWRNCl5LxYJ@e0xFSfBW46Du@9K6a1CZMcmNasp3iz0DElRNevdwIiLFDTF4Fj3QtJj28cQtKMzjPoE1gJyIfPv9unhzua6/UDwUDFrI@cHWM25WeIGxX63rRLyC/aR2imAI27@EUcFjndUS8PlqsKAIi0vkuUmlzc)
```
double t(){return System.nanoTime();}
void w(){for(double s=t();t()-s<5e+10;);System.out.print("\0007!");}
```
**Note** on unix, this should *ring* a beep.
[Answer]
# x86 16 bit machine code on MS-DOS - 21 bytes
```
00000000 53 1f a1 6c 04 05 8e 03 3b 06 6c 04 77 fa b2 6e |S..l....;.l.w..n|
00000010 b4 02 cd 21 c3 |...!.|
00000015
```
Commented assembly:
```
org 100h
section .text
start:
push bx ; notice: bx starts as 0
pop ds ; set the data segment to 0; this allows us to
; read the tick count without segment selectors
mov ax,word [046ch] ; read the low 16 bit of the tick count
add ax,910 ; 910 ticks = 49.98 seconds
; here we used ax because the encoding for both
; the mov and the add is one byte shorter
lop:
cmp ax,word [046ch] ; compare the stop time with the current time
ja lop ; loop if still above
mov dl,'n' ; n is for noodles
mov ah,2
int 21h ; print
ret ; quit
```
This could be shaved down to 16 bytes by replacing the final three instructions with [`int 18h`](https://en.wikipedia.org/wiki/BIOS_interrupt_call#INT_18h:_execute_BASIC), which on ancient machines would invoke the ROM built-in BASIC interpreter and almost everywhere else prints something like "No ROM BASIC" and reboot after a key press, but after discussing this with OP it was decided that this wouldn't be allowed.
### Interrupt + self-modifying code approach - 23 bytes
This is another approach; it turns out to be bigger, but I post it anyway because it is way more fun.
```
00000000 b8 1c 25 ba 12 01 cd 21 b9 8e 03 e2 fb b4 02 cd |..%....!........|
00000010 21 c3 ff 0e 09 01 cf |!......|
00000017
```
```
org 100h
section .text
%define counter lop+1 ; see below
start:
; setup interrupt handler
mov ax,251ch ; function 25h (replace interrupt vector)
; interrupt 1ch (user timer)
mov dx,interrupt_handler ; timer ISR
int 21h
lop:
mov cx,910 ; the 910 immediate value is actually pointed by counter,
; which is decremented in interrupt_handler
loop lop ; decrement and loop as long as cx is nonzero (the decrement is
; not relevant, we are always resetting cx at each iteration)
mov ah,2 ; function 2 (print character); dl is already a printable character
int 21h
ret ; quit
interrupt_handler:
dec word[counter] ; at every tick decrement the counter
iret
```
[Answer]
# PHP, 43 bytes
I think when you´re sleepy, your ears are more alert than your eyes, so:
```
for($t=time();;)echo chr(time()-$t<50?9:7);
```
prints horizontal tabs in the first 50 seconds, BEL codes after that. Run with `-r`.
[Answer]
# C# - 100 bytes
```
using System;
void q(){var t=DateTime.Now.AddSeconds(50);
while(DateTime.Now<t);
Console.Write(t);
}
```
[Answer]
## R, 41 bytes
```
s=Sys.time;x=s();while(s()-x<50){};cat(1)
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 68 43 bytes
```
for((e=`date +%s`+50;`date +%s`<e;)){ :;};w
```
Lists logged in users after 50 seconds.
**Edit:** Thanks a lot, **manatwork**! -25 bytes.
[Try it online!](https://tio.run/nexus/bash#@5@WX6ShkWqbkJJYkqqgrVqcoG1qYI3g2aRaa2pWK1hZ11qX//8PAA "Bash – TIO Nexus")
[Answer]
**C#, 73 bytes**
`var n=DateTime.Now.AddSeconds(50);while(DateTime.Now<n);Console.Write(n);`
[Answer]
# [Aceto](https://github.com/L3viathan/Aceto), 16 bytes
```
6+_p
*-iX
59
Tt<
```
Sets a `T`imer, reads the `t`imer difference and pushes it on the stack. Pushes `9` and `5`, multipl`*`es them, pushes `6`, `+`dds them. We now have a 51 on the stack (on top of the initially small-ish timer number). We substr`-`ct them from each other, getting initially something a little bit bigger than 51. We cast it to an `i`nteger, and mirror (`_`) if the integer is truthy (i.e. not 0). In that case, we go to the left (`<`) and check our timer again, going into a loop. Otherwise, we `p`rint 0 from the empty stack, and e`X`it.
After 50 seconds, the timer will be 50+ε for some small ε, meaning our subtraction yields 50+ε-51 = -ε, since ε is smaller than 1 the corresponding integer will be 0.
[Answer]
## C, ~~41~~ ~~43~~ 39 Bytes
```
a;b(c){time(c?0:&a)-a>50?puts(b):b(1);}
```
[Try it online](https://tio.run/nexus/c-gcc#@59onaSRrFldkpmbqpFsb2Cllqipm2hnamBfUFpSrJGkaZWkYahpXfs/NzEzT0OTq5qLM0nDQNOaq/b/v@S0nMT04v@6/kZf8/J1kxOTM1IB)
[Answer]
## Ruby, ~~36 33~~ 35 bytes
```
t=Time.now;1until Time.now-t>50;p 1
```
Ruby handily supports subtraction of `Time` objects, returning the difference in seconds. Prints the character 1 (being Ruby's internal representation of the entity `1`) when done.
**Edit:** saved 2 bytes by changing to an error message, 1 byte thanks to G B
**Edit:** re-added 2 bytes (stderr doesn't count)
[Answer]
## REXX, 33 bytes
```
do while time(e)<50
nop
end
say a
```
[Answer]
## C#, ~~91~~ 77 bytes
```
n=()=>System.DateTime.Now;_=>{var t=n();while((n()-t).Seconds<50);return t;};
```
[Answer]
# T-SQL, 62 bytes
```
DECLARE @ DATETIME=GETDATE()WHILE DATEDIFF(S,@,GETDATE())<50_:
```
After the execution in SSMS, this will print the message "Command(s) completed successfully." plus a bell sound [bonus :)].
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 48 bytes
```
BEGIN{for($0=systime();systime()-$0<50;)1;print}
```
[Try it online!](https://tio.run/nexus/awk#@@/k6u7pV52WX6ShYmBbXFlckpmbqqFpDWfpqhjYmBpYaxpaFxRl5pXU/v8PAA "AWK – TIO Nexus")
This assumes that input is not allowed.
[Answer]
# Swift - 41 bytes
Just outgolfing @Samira's answer, improving it drastically
```
var d=Date()+50;while Date()<d{};print(d)
```
Prints the date it started running to wake one up, e.g: if it's ran at 12:38 UTC, it outputs `2017-05-12 12:38:51 +0000` after 50 seconds.
] |
[Question]
[
The task is simple. Write an interpreter for the language [\*](https://esolangs.org/wiki/*).
[Here's a bigger link to the wiki.](https://esolangs.org/wiki/*)
There are only three valid \* programs:
* `*` Prints "Hello World"
* `*` Prints a random number between 0 and 2,147,483,647
* `*+*` Runs forever.
The third case must be an infinite loop according to the specifications in [this question](https://codegolf.stackexchange.com/questions/59347/shortest-infinite-loop-producing-no-output)
## Input:
* The input can be taken via any acceptable input method by our standard I/O rules
* It will always be one of the above programs
## Output:
* The first case should print exactly `Hello World`, with or without a trailing line break.
* For the second case, if your language's integer maximum is smaller than 2,147,483,647, use your language's integer maximum
* The first and second cases can print to any acceptable output by our standard I/O rules.
* The third case should not give any output.
## Scoring:
As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest answer, in bytes, wins.
[Answer]
## [\*](https://esolangs.org/wiki/*), 0 bytes
```
```
Since \* has no way of reading input, the default rules allow specifying that [the input must be given by concatenating it onto the program](https://codegolf.meta.stackexchange.com/a/10553/52746).
(... I think. There's an *"at least twice as many upvotes as downvotes"* condition that I don't have the rep to verify).
[Answer]
# [R](https://www.r-project.org/), 69 bytes
```
switch(scan(,""),"*"="Hello, World!"," * "=sample(2^31,1)-1,repeat{})
```
[Try it online!](https://tio.run/##K/r/v7g8syQ5Q6M4OTFPQ0dJSVNHSUvJVskjNScnX0chPL8oJ0VRSUdJQUtBybY4MbcgJ1XDKM7YUMdQU9dQpyi1IDWxpLpW8z9YwX8A "R – Try It Online")
`switch` tries to match the named arguments and if there's no match, selects the first unnamed one after the first, which in this case is the infinite loop `repeat{}`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~21~~ 20 bytes
```
ḊOSØ%HX’¤“½,⁾ẇṭ»¹Ḃ¿?
```
A monadic Link accepting a list of characters.
**[Try it online!](https://tio.run/##ATUAyv9qZWxsef//4biKT1PDmCVIWOKAmcKk4oCcwr0s4oG@4bqH4bmtwrvCueG4gsK/P////yAqIA "Jelly – Try It Online")**
`vL’...` [also works](https://tio.run/##ATUAyv9qZWxsef//dkzigJnDmCVIWOKAmcKk4oCcwr0s4oG@4bqH4bmtwrvCueG4gsK/P////yAqIA "Jelly – Try It Online") (see below).
### How?
```
ḊOSØ%HX’¤“½,⁾ẇṭ»¹Ḃ¿? - Link: list of characters e.g.: "*" or " * " or "*+*"
Ḋ - dequeue "" "* " "+*"
O - to ordinals [] [42,32] [43,42]
S - sum 0 74 85
? - if...
¿ - ...if-condition: while...
Ḃ - ...while-condition: modulo 2 0 0 1
¹ - ...while-true-do: identity 85
- 0 74 (looping)
¤ - ...then: nilad followed by link(s) as a nilad:
Ø% - literal 2^32 2^32
H - half 2^31
X - random integer in [1,n] RND[1,2^31]
’ - decrement RND[0,2^31)
“½,⁾ẇṭ» - ...else: dictionary words "Hello World"
```
---
Alternative
```
vL’... - Link: list of characters e.g.: "*" or " * " or "*+*"
L - length 1 3 3
v - evaluate (left) as Jelly code with input (right)
- 1^1 3^3 (3^3+3)^3
- 1 27 27000
’ - decrement 0 26 26999
... - continue as above "Hello World" RND[0,2^31) (looping)
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 66 63 bytes
Thanks to attinat for the -3 bytes.
I only have to check the second character: if the LSB is set, it's a `+` (thus the program is "`*+*`") and the program loops. After that, if it's a `NUL`, the program was "`*`" and we display `Hello World`; otherwise, it displays a random value ("`*`", the only other option left.)
```
f(char*s){for(s++;*s&1;);printf(*s?"%d":"Hello World",rand());}
```
[Try it online!](https://tio.run/##FYyxDsIgFAB3vuKFRMOjbWJXGVz9AwfjQKBgE4TmUXVo@usibHfJ5czgjSnFCfPUJDNuLpHIXadkPo4K1UJzXJ2Q@cIPlp/5dQohwS1RsLwnHa1AVHupEbz0HEUDTd700IYgZZUPwsYAnGh8Hx@oWFWa1jdFOCm2lyJ/xgXtcxm@fw "C (gcc) – Try It Online")
[Answer]
# [Keg](https://github.com/JonoCode9374/Keg), `-lp`, `-ir` ~~30~~ ~~26~~ ~~25~~ ~~24~~ ~~20~~ 19 bytes
```
!1=[_“H%c¡“| =[~.|{
```
*-1 byte using flags*
[Try it online!](https://tio.run/##y05N//9f0dA2Ov5RwxwP1eRDC4F0jYJtdJ1eTfX//1r/dXMK/utmFgEA "Keg – Try It Online")
## Answer History
```
?!1=[_“H%c¡“| =[~.|{
```
[Try it online!](https://tio.run/##y05N///fXtHQNjr@UcMcD9XkQwuBdI2CbXSdXk31//9aAA "Keg – Try It Online")
Shortened `Hello World` to dictionary string
```
!1=[_Hello World| =[~.|{
```
[Try it online!](https://tio.run/##y05N//9f0dA2Ot4jNScnXyE8vygnpUbBNrpOr6b6/38FLQUA "Keg – Try It Online")
I never ceased to be amazed at the power of Keg. Credits to user EdgyNerd for another byte saved.
## Prior Versions
```
_!0=[Hello World|\*=[~.|{
```
[Try it online!](https://tio.run/##y05N//8/XtHANtojNScnXyE8vygnpSZGyza6Tq@m@v9/BS0FAA "Keg – Try It Online")
Credit to user A\_\_ for the extra byte saved.
## Old version
```
?!1=[_Hello World| =[__~|{
```
Essentially, takes the input program and:
* Checks to see if the input length is 1, printing "Hello World" if true
* Checks to see if the last character is a space, and prints a random number
* Otherwise runs an infinite loop
Then implicitly print the stack.
```
? #Get input from the user
!1= #Compare the stack's length to 1
[_Hello World #Push "Hello, World!" to the stack
| = #See if top item is a space
[__~|{ #If so, generate a random number, otherwise, infinite loop.
```
4 bytes saved due to the fact that hello world doesnt need punctuation.
[Try it online!](https://tio.run/##y05N//9f0dA2Ot4jNScnP0ZHITy/KCclRrFGASgWX1dT/f@/gpYCAA "Keg – Try It Online") Old version
[Try it online!](https://tio.run/##y05N//9f0dA2Ot4jNScnXyE8vygnpUYByI@vq6n@/x8A "Keg – Try It Online") New version
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 22/25 bytes
The first solution is for the original spec which had `*<space>` as the second programme and the other is for the updated spec which arbitrarily changed it to `<space>*</space>`, with thanks to EoI for the suggested "fix".
Both throw an overflow error upon entering the infinite loop of the third programme but, theoretically, with enough memory (which we may assume for the purposes of [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")), would run forever.
```
Å?¢?ß:2pHÉ ö:`HÁM Wld
```
[Try programme 1](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=xT%2biP986MnBIySD2OmBIwU0gV45sZA&input=Iioi)
[Try programme 2](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=xT%2biP986MnBIySD2OmBIwU0gV45sZA&input=IiogIg)
[Try programme 3](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=xT%2biP986MnBIySD2OmBIwU0gV45sZA&input=IiorKiI)
```
Å?UÎ>S?ß:2pHÉ ö:`HÁM Wld
```
[Try programme 1](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=xT9Vzj5TP986MnBIySD2OmBIwU0gV45sZA&input=Iioi)
[Try programme 2](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=xT9Vzj5TP986MnBIySD2OmBIwU0gV45sZA&input=IiAqICI)
[Try programme 3](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=xT9Vzj5TP986MnBIySD2OmBIwU0gV45sZA&input=IiorKiI)
[Answer]
# [Python 2](https://docs.python.org/2/), ~~103~~ ~~93~~ ~~89~~ 87 bytes
I combined my earlier answer with Chas Browns's [answer](https://codegolf.stackexchange.com/a/189620/34718) and got something a few bytes shorter.
The random number will be between 0 and 2\*\*31-1 inclusive.
```
from random import*
i=input()
while'*'<i:1
print["Hello World",randrange(2**31)][i<'!']
```
[**Try it online!**](https://tio.run/##K6gsycjPM/r/P60oP1ehKDEvBUhl5hbkF5VocWXaZuYVlJZoaHKVZ2TmpKprqdtkWhlyFRRl5pVEK3mk5uTkK4TnF@WkKOmAdAJxeqqGkZaWsaFmbHSmjbqieuz//0paSgA "Python 2 – Try It Online")
### Previous versions:
103 bytes
```
from random import*
exec['print"Hello World"','while 1:1','print randint(0,2**31-1)'][cmp(input(),'*')]
```
93 bytes
```
from random import*
i=cmp(input(),'*')
while i>0:1
print["Hello World",randint(0,2**31-1)][i]
```
[Answer]
# JavaScript (ES7), 66 bytes
```
s=>s[1]?s<'!'?Math.random()*2**31|0:eval(`for(;;);`):'Hello World'
```
[Try it online!](https://tio.run/##BcExDsIwDADAr8BkOxIVha2hdGVhZkBItZoEikyM4qoTfw93b17ZpjJ/l13WEGvqq/Vnu7ePwU6wheHKy6spnIN@kNzBuWP723dxZcExaUHvyY/UwSWK6OamRQLUSbOpxEb0iQnBAVH9Aw "JavaScript (Node.js) – Try It Online") (Hello World)
[Try it online!](https://tio.run/##BcE7DsIwDADQq4TJdiQqCltD6dqFmQEhNWoSPjJxFVeduHt47@M3r3N5L@s@S4g19VX7i97bx6Bn2MFw9eurKT4H@SLZo7Wn9nfo4uYZpyQFnSM3UQdjZBZzk8IB6ixZhWPD8sSEYKwBovoH "JavaScript (Node.js) – Try It Online") (random number)
[Try it online!](https://tio.run/##BcE7DsIwDADQq8BkO4iKwtZQurIwMyCkWk3CRyZGcdWJu4f33rywTeX1nbdZQ6ypr9af7NbeBzvCGoYLz8@mcA76QXJ75w7tb9fFhQXHpAW9Jz9SB@cooqurFglQJ82mEhvRByYEt3FAVP8 "JavaScript (Node.js) – Try It Online") (infinite loop)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~23~~ 21 bytes
```
OS¹Ḃ¿ịØ%HX’;““½,⁾ẇṭ»¤
```
[Try it online!](https://tio.run/##ATYAyf9qZWxsef//T1PCueG4gsK/4buLw5glSFjigJk74oCc4oCcwr0s4oG@4bqH4bmtwrvCpP///yo "Jelly – Try It Online")
A monadic link taking a single argument and returning `Hello World`, a random 31 bit integer or looping infinitely as per the spec.
All options: [`*`](https://tio.run/##ATYAyf9qZWxsef//T1PCueG4gsK/4buLw5glSFjigJk74oCc4oCcwr0s4oG@4bqH4bmtwrvCpP///yo "Jelly – Try It Online") [`*`](https://tio.run/##ATgAx/9qZWxsef//T1PCueG4gsK/4buLw5glSFjigJk74oCc4oCcwr0s4oG@4bqH4bmtwrvCpP///yAqIA) [`*+*`](https://tio.run/##ATgAx/9qZWxsef//T1PCueG4gsK/4buLw5glSFjigJk74oCc4oCcwr0s4oG@4bqH4bmtwrvCpP///yorKg)
## Explanation
```
O | Convert to codepoints
S | Sum
¹Ḃ¿ | Loop the identity function while odd
ị ¤ | Index into the following as a nilad:
Ø% | - 2 ** 32
H | - Halved
X | - Random integer in the range 1..2**31
’ | - Decrease by 1
; | - Concatenated to:
““½,⁾ẇṭ» | - "", "Hello World"
```
[Answer]
# [Befunge-93](https://github.com/catseye/Befunge-93), 54 bytes
```
~"*"-_~1+#^_"dlroW olleH">:#,_@.%*2**:*::*88:*`0:?1#+<
```
[Try it online!](https://tio.run/##S0pNK81LT/3/v05JS0k3vs5QWzkuXiklpyg/XCE/JyfVQ8nOSlkn3kFPVctIS8tKy8pKy8LCSivBwMreUFnb5v9/LW0tAA "Befunge-93 – Try It Online")
**Annotated:**
```
~"*"- _ ~1+ #^_ "dlroW olleH">:#,_ @ .%*2**:*::*88: *`0: ?1#+<
Compare first If equal, go right Compare second If equal, Output Exit Modulo by 2^31 If less than Add 1
character to Otherwise, go left character to loop forever "Hello World" and output 0, multiply a random amount
'*' and wrap around -1 (EOF) by 0 of times
```
The randomness is not uniform. At each increment there is a 50% chance to stop incrementing.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~91~~ ~~89~~ 88 bytes
```
from random import*
def f(p):
while'*'<p:p
print['Hello World',getrandbits(31)][p<'!']
```
[Try it online!](https://tio.run/##LY0xDsMgEAR7XnGpziZuknTID8gPUiCKRECMhLnTBSny6zGW3Oxqi5nlrS5U7q1FoRXkXXyvtDJJ1cqHCHHg0Sj4LykH1DizYQUsqVSLz5AzwYske5y@oR74J9Xf8LiNzvKMF3QtkgBDKmA7PiFo6KmvGp05RdCNx8052w4 "Python 2 – Try It Online")
2 bytes thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan); 1 byte thx to [ShadowRanger](https://codegolf.stackexchange.com/users/70305/shadowranger).
[Answer]
# PowerShell, ~~60~~, 56 bytes
```
switch($args){*{'Hello World'}' * '{random}*+*{for(){}}}
```
Pretty dumb version, the only golfing technique here is omitting `Get-` in `Get-Random`.
**UPD.** Stripped down to 56 bytes by removing quotes, thanks to [veskah](https://codegolf.stackexchange.com/users/78849/Veskah)!
* [Try it online!](https://tio.run/##DcgxDoAgDADArzCYFOpH/IEzERSTak0xYWj69uqN9/Co0lslcu/jfLcWpyxHT4oKy98cVhYqYBAwgEq@C1@GM@rOEpOambsDwgc) (Hello World)
* [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/v7g8syQ5Q0MlsSi9WLNaq1rdAyicrxCeX5STol6rrqCloF5dlJiXkp9bq6WtVZ2WX6ShWV1bW/v//3@wJAA) (random number)
* [Try it online!](https://tio.run/##DcgxDoAgDADArzCYFOpH/IEzERQStKaYMDR9e@XGe2lk7iW3ZtZH/Y7il8hXD4IC22xyO3FLoODQgXB8Et2KK8pJ7IOoqpnBDPgB) (infinite loop)
[Answer]
# [///](https://esolangs.org/wiki////), 72 bytes
```
/+*/+*// */a random number between 0 and 0//*/"Hello World"/
```
[Try it online!](https://tio.run/##FchLCoAgEADQqwwuR2H6SHWEbtBacaDFqKBFx58K3up1Cf3krkoWfwRIAVooqWYod47cIPL1MBcY4GuY3OhX57fZLX4lQjI7i1Q4apNkSNGivg "/// – Try It Online")
Here I go again, adding another cheating entry. Was I really going write my own pseudo-random generator just for this though... and in **///**?!
Instead, I interpreted the `Print` instruction very literally, as a good minion should. Everything after `Print` is outputted:
### `*` Prints "Hello World"
>
> `*` → `"Hello World"`, yes, even with the quotation marks. Otherwise, I'd admit to being aware of the quotation-marks-denote-literal-string convention, which wasn't explicitly stated in the question, and doesn't exist in the language with which I'm submitting. And then I wouldn't be able to cheat with the *"Print a random number"* part. So, I'm feigning ignorance... Shhh, don't tell!
>
>
>
### ` * ` Prints a random number between 0 and 2,147,483,647
>
> `*` → `a random number between 0 and 0`. Lucky for me, although they didn't add the whole non-deterministic, different-number-every-time shtick in the rules, they did say *"if our language's integer maximum is smaller than 2,147,483,647"* we can use our language's *"integer maximum"* instead, so I did... There *are* no integer types in **///**, only strings. So the integer maximum is `0`, sort of...
> Well, it shaves off a few bytes!
>
>
>
### `*+*` Runs Forever
>
> `*+*` → . There's no `Print` instruction in this one so I can interpret it like a normal human. Replacing a pattern with itself (or another string containing itself), is the standard way to loop forever, and it's as succinct as it gets!
>
>
>
### Note
To golf it a bit, **///** looks for `+*` & ` *` rather than the whole thing. This works just as well. For the infinite loop, nothing ever prints because the replacing never stops, so you'll never find out that it's prepending an infinitely long list of `*` to the beginning every time it replaces. As for printing 'a random number,' we just don't replace one of the spaces, leaving a trailing space at the end of the output. Luckily, this hurts no one and is not noticeable. Plus, how's an ignoramus like me to know how many of the trailing spaces at the end of the `Print` instruction, until the margin, were on purpose :p
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, ~~43~~ 39 bytes
```
$_=/ /?0|rand~0:/\+/?redo:"Hello World"
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3lZfQd/eoKYoMS@lzsBKP0Zb374oNSXfSskjNScnXyE8vygnRen/fy1trX/5BSWZ@XnF/3ULAA "Perl 5 – Try It Online")
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 71 bytes
```
s=>{for(;s=="*+*";);return"*"==s?"Hello World":new Random().Next()+"";}
```
[Try it online!](https://tio.run/##Xcu7CgIxEIXh3qcIU@Wibm@ctRMLsbDZWrKJBOIEMlkUxGePslZaHfg4v@OV49j2E7kt1xLpuvxOH7Ax9s@Qi7SMCNposMoWX6dCoAGRd3DwKWUx5JJG2JC/i/OFxnyTan3yjyqVAbCvZhdDidUfI3kZ5KdV6p/EbF33q2a@tjc "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-n`, 47 bytes
```
puts~/ /?rand(1<<31):~/\+/?loop{}:"Hello World"
```
[Try it online!](https://tio.run/##KypNqvz/v6C0pLhOX0HfvigxL0XD0MbG2FDTqk4/RlvfPic/v6C61krJIzUnJ18hPL8oJ0Xp/38FLYV/@QUlmfl5xf918wA "Ruby – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 65 bytes
```
#/.{"*"->"Hello World"," * "->RandomInteger[2^31-1],_:>0~Do~∞}&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X1lfr1pJS0nXTskjNScnXyE8vygnRUlHSUFLASgYlJiXkp/rmVeSmp5aFG0UZ2yoaxirE29lZ1Dnkl/3qGNerdr/gKLMvJLoNAegKbH/AQ "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Java (JDK)](http://jdk.java.net/), 83 bytes
```
s->{for(s=s.intern();s=="*+*";);return"*"==s?"Hello World":(-1>>>1)*Math.random();}
```
[Try it online!](https://tio.run/##LU67bsMgFN3zFVdMQGvUrHUhW9Ql6pChQ5SB2DjBxWDBJVIU@dspSTudI53nqK@6Gfuf0jmdEuy09XBfAcz55GwHCTVWuAbbw1Q1usdo/flwBB3PiT2tAGMtERmtE0P2HdrgxfaffPwFXr9Oo@lQwQCypEbdhxBpkklYjyZ6ytokJeEvnLSsjQZz9IQTKdOGfBrnAnyH6HryTpu1UmrN@E7jRUTt@zDV8FLa55H9LaGZRMgo5jqLztNB6Hl2N/r4e3g7MvZwLqulFODwCw "Java (JDK) – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~26~~ 23 bytes
```
l₃∈&hṢ∧2^₃₁-₁ṙw∨Ḥ⊇ᶠ³⁶tw
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/P@dRU/Ojjg61jIc7Fz3qWG4UB@I3NeoC8cOdM8sfdax4uGPJo672h9sWHNr8qHFbSfn//0oKWgpKAA "Brachylog – Try It Online")
Takes the program as a string through the input variable, and ignores the output variable. Heavily exploits the guarantee that the input is only ever one of the three valid programs: any length-three input will behave like either `" * "` or `"*+*"` depending on whether or not the first character is a space, and any other input will behave like `"*"`.
```
l₃ The input has length 3
∈ and is an element of something,
&h and the input's first element
Ṣ is a space
∈ (if not, try some other thing it's an element of),
∧2^₃₁-₁ so take 2,147,483,647 and
ṙw print a random number between 0 and it inclusive.
∨ If the input's length isn't 3,
Ḥ⊇ᶠ³⁶tw print the 36th subsequence of "Hello, World!".
```
[Answer]
# [PHP](https://php.net/), 51 bytes
```
for(;'*'<$l=$argn[1];);echo$l?rand():'Hello World';
```
[Try it online! (Hello World)](https://tio.run/##K8go@G9jXwAk0/KLNKzVtdRtVHJsVRKL0vOiDWOtNa1TkzPyVXLsixLzUjQ0rdQ9UnNy8hXC84tyUtSt///X@pdfUJKZn1f8X9cNAA "PHP – Try It Online")
[Try it online! (Random Number)](https://tio.run/##K8go@G9jXwAk0/KLNKzVtdRtVHJsVRKL0vOiDWOtNa1TkzPyVXLsixLzUjQ0rdQ9UnNy8hXC84tyUtSt//9X0FL4l19QkpmfV/xf1w0A "PHP – Try It Online")
[Try it online! (Infinite Loop)](https://tio.run/##K8go@G9jXwAk0/KLNKzVtdRtVHJsVRKL0vOiDWOtNa1TkzPyVXLsixLzUjQ0rdQ9UnNy8hXC84tyUtSt///X0tb6l19QkpmfV/xf1w0A "PHP – Try It Online")
Takes second character of input which can be `''`, `'*'` or `'+'`. In case of `'+'` the `'*'<'+'` will be true and the loop will be infinite, else, after the loop, "Hello World" or a random number is shown. The `rand()` automatically outputs a number between 0 and `getrandmax()` which uses defined `RAND_MAX` in standard C library and by default is `2147483647` on most platforms/environments, including TIO.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 39 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Anonymous prefix lambda.
```
{'+'∊⍵:∇⍵⋄' '∊⍵:⌊2E31×?0⋄'Hello World'}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/6vVtdUfdXQ96t1q9aijHUg96m5RV4AL9XQZuRobHp5ubwAS90jNyclXCM8vyklRr/2fBjTgUW8fxKyu5kPrjR@1TQTygoOcgWSIh2fw/zQFdS11LiCpoKUAprW0tdQB "APL (Dyalog Unicode) – Try It Online")
`{` "dfn"; `⍵` is the argument:
`'+'∊⍵:` if plus is a member of the argument:
`∇⍵` tail recurse on argument
`' '∊⍵` if space is a member of the argument:
`?0` random float (0–1)
`2E31×` scale to (0–2³¹)
`⌊` floor
`'Hello World'` else return the string
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 21 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
'*KgDi[ë<ižIL<Ω딟™‚ï
```
[Try it online.](https://tio.run/##ASwA0/9vc2FiaWX//ycqS2dEaVvDqzxpxb5JTDzOqcOr4oCdxbjihKLigJrDr///Kg) (NOTE: The random buildin is pretty slow with big lists, so it might take awhile before the result is given.)
**Explanation:**
```
'*K '# Remove all "*" from the (implicit) input
g # Get the length of what's remain (either 0, 1, or 2)
D # Duplicate this length
i # If the length is exactly 1:
[ # Start an infinite loop
ë<i # Else-if the length is 2:
žI # Push builtin 2147483648
L # Create a list in the range [1,2147483648]
< # Decrease each by 1 to make the range [0,2147483647]
Ω # Pop and push a random value from the list
# (after which the top of the stack is output implicitly as result)
ë # Else:
”Ÿ™‚ï # Push dictionary string "Hello World"
# (after which the top of the stack is output implicitly as result)
```
[See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `”Ÿ™‚ï` is `"Hello World"`.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 32 bytes
```
It/Jw\*#;?tlJOhC*4\ÿ"Hello World
```
[Try it online!](https://tio.run/##K6gsyfj/37NE36s8RkvZ2r4kx8s/w1nLJObwfiWP1JycfIXw/KKclP//tQA "Pyth – Try It Online")
## Explanation (Python-ish)
```
I # if
/Jw\* # (J:=input()).count("*"))
t # - 1:
#; # try: while True: pass;except: break;
? # if (ternary)
lJ # len(J):
O # randInt(0, )
C # int( , 256)
*4\ÿ # 4*"ÿ"
h # + 1
"Hello World # else: (implicitly) print "Hello World"
```
[Answer]
# JavaScript, 62 Bytes, no infinite recursive
```
s=>s[1]?eval("while(s>'!');Math.random()*2**31"):'Hello World'
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), 79 bytes
-2 bytes thanks VFDan
```
s=>eval([`"Hello World"`,`Math.random()*2**31|0`,`for(;;);`][s.lastIndexOf`*`])
```
[Try it online!](https://tio.run/##Xcq7DsIgFADQ3a8gnQCV@lhMSJ11MI4OTZNLWvCRK9cAIQ7@O7Zr15PzMtnEPjw/aZ0PxTUlNkebDfIWqpNFJHajgEMFK7iY9FDB@IHeXMidlPvtbzO6o8C1Fhq6Nio0MZ39YL9XBxI6UXrykdAqpDt3fDQhFjNjkk1a1/O7nHb5Aw "JavaScript (V8) – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~39~~ 35 bytes
```
IaQ'*P"Hello World"EIsQ@aPRRmE{T0a}
```
[Try it online!](https://tio.run/##K8gs@P/fMzFQXStAySM1JydfITy/KCdFydWzONAhMSAoKNe1OsQgsfb///8KWgoA "Pip – Try It Online")
Simple if else based program, prints random integer between 0 and 1000.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 16 bytes
```
×=[kh|tð=[k×ʀ℅|{
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=5&code=%C3%97%3D%5Bkh%7Ct%C3%B0%3D%5Bk%C3%97%CA%80%E2%84%85%7C%7B&inputs=*&header=&footer=) The `5` flag is just so that you don't have to wait as long for it to timeout. Even at the default 60 second timeout, this times out on `*` , but you can see that it works by replacing `k×` with a smaller number.
Currently, this beats all other answers.
Explanation:
```
# Implicit input
×=[ # If input = "*":
kh # Push "Hello World"
|tð=[ # Else if last character of input = " ":
k× # Push 2147483648
ʀ # Range [0, 2147483648]
℅ # Random integer from range
| # Else:
{ # While True: (Infinite loop)
# Implicit output
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 30 bytes
```
W№θ*F⁼θ*≔Hello Worldθ∨θI‽X²¦³¹
```
[Try it online!](https://tio.run/##RYsxDsIwDAB3XmFlcqowAGMnVCGxUbEwW22gkUysOC19vqETN57uhol0EGKzdUocATtZ8owlgGuc9/AUBbyUhbj@5bnW9MrorpFZ4CHKowtQfLvrNf3um25tR3XGO@VR3tjLGhWPAU4Hv9GaQQO2//AX "Charcoal – Try It Online") Link is to verbose version of code. Abuses Charcoal's default input format which splits on spaces if there is only one line, thus the random number input actually looks like three inputs. Explanation:
```
W№θ*
```
Repeat while the first input contains a `*`.
```
F⁼θ*
```
If the first input is a `*` only...
```
≔Hello Worldθ
```
... then replace it with `Hello World`, thus causing the loop to terminate. `*+*` doesn't get replaced, resulting in an infinite loop.
```
∨θ
```
If the first input is not empty then output it.
```
I‽X²¦³¹
```
But if it is empty then output a random integer in the desired range.
[Answer]
# [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 78 bytes
```
z:"Hello World"
`y
xR2147483647
x:?
a:"*"
b:" * "
c:"*+*"
Ix=a,Oz
Ix=b,O
Wx=c,
```
[Try it online!](https://tio.run/##S0xJKSj4/7/KSskjNScnXyE8vygnRYkroZKrIsjI0MTcxMLYzMScq8LKnivRSklLiSvJSklBS0GJKxnI0wbyPStsE3X8q0B0ko4/V3iFbbLO////wZIA "Add++ – Try It Online")
## Explanation
```
z:"Hello World" ; Set z = "Hello World"
`y ; Set y as the active variable
xR2147483647 ; Set y to a random number between 0 and 2147483647
x:? ; Set x to the input
a:"*" ; Set a = "*"
b:" * " ; Set b = " * "
c:"*+*" ; Set c = "*+*"
Ix=a, ; If x == a then...
Oz ; ...output z
Ix=b, ; If x == b then...
O ; ...output y
Wx=c, ; While x == c then...
; ...do nothing
```
[Answer]
# Commodore BASIC (VIC-20, C64, TheC64Mini etc) - 170 tokenize BASIC bytes
```
0a%=32767:goS9:b$=leF(b$,len(b$)-1):ifb$="*"tH?"hello world
1ifb$=" * "tH?int(rN(ti)*a%)
2ifb$="*+*"tHfOi=.to1:i=.:nE
3end
9b$="":fOi=.to1:geta$:i=-(a$=cH(13)):b$=b$+a$:?a$;:nE:reT
```
I think to do this more accurately, I'll have to delve into the weird world of 6502 assembly language, but this is a first draft.
First point, the `INPUT` keyword in Commodore BASIC ignores white spaces, so the sub-routine at line `9` is a quick-and-dirty way to accept keyboard entries including spaces.
Second point, Commodore BASIC integers have a range of 16-bit signed, so -32768 to +32767 [source](https://www.c64-wiki.com/wiki/Variable) - so I've kept the random number generated to 0 - 32767 inclusive
] |
[Question]
[
Given a textual representation (case-insensitive full name or 3 character abbreviation) of a month return the number of days in the month.
For example, `december`, `DEC`, and `dec` should all return 31.
February can have either 28 or 29 days.
Assume the input is a month in one of the correct forms.
[Answer]
# JavaScript (ES6), ~~48 47 44 43~~ 42 bytes
```
m=>31^'311'[parseInt(m[1]+m[2],34)*3%49%8]
```
### Demo
```
let f =
m=>31^'311'[parseInt(m[1]+m[2],34)*3%49%8]
;(
'JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC,' +
'JANUARY,FEBRUARY,MARCH,APRIL,MAY,JUNE,JULY,AUGUST,SEPTEMBER,OCTOBER,NOVEMBER,DECEMBER'
).split`,`
.forEach(m => console.log(m, '->', f(m)))
```
### How?
These operations lead to a lookup table of 8 entries, which would not be very interesting if the values were randomly distributed. But any result greater than **2** is mapped to **31** days. Therefore, only the first 3 entries need to be stored explicitly.
```
Month | [1:2] | Base 34 -> dec. | * 3 | % 49 | % 8 | Days
------+-------+-----------------+------+------+-----+-----
JAN | AN | 363 | 1089 | 11 | 3 | 31
FEB | EB | 487 | 1461 | 40 | 0 | 28
MAR | AR | 367 | 1101 | 23 | 7 | 31
APR | PR | 877 | 2631 | 34 | 2 | 30
MAY | AY | 10 | 30 | 30 | 6 | 31
JUN | UN | 1043 | 3129 | 42 | 2 | 30
JUL | UL | 1041 | 3123 | 36 | 4 | 31
AUG | UG | 1036 | 3108 | 21 | 5 | 31
SEP | EP | 501 | 1503 | 33 | 1 | 30
OCT | CT | 437 | 1311 | 37 | 5 | 31
NOV | OV | 847 | 2541 | 42 | 2 | 30
DEC | EC | 488 | 1464 | 43 | 3 | 31
```
[Answer]
# Javascript (ES6), ~~36~~ 33 bytes
-3 bytes thanks to @JustinMariner and @Neil
```
m=>31-new Date(m+31).getDate()%31
```
Sorry @Arnauld, abusing JavaScript weirdness is shorter than your fancy base conversions.
### How it works
For some reason, JavaScript allows entering dates outside of the specified month. The code counts how many days outside the month the date is to determine how many days there are in the month. Examples:
`"FEB31"` → `Thu Mar 02 2000` → `31 - 2 % 31` → `29`
`"October31"` → `Tue Oct 31 2000` → `31 - 31 % 31` → `31`
### Test cases
```
f=m=>31-new Date(m+31).getDate()%31
;(
"JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC,"+
"January,February,Mars,April,May,June,July,August,September,October,November,December"
).split`,`.forEach(s=>console.log(s,"->",f(s)))
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~46~~ ~~45~~ 38 bytes
*-1 byte thanks to @totallyhuman*
```
lambda m:29-int(m[1:3],35)%238%36%-5/2
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHXyshSNzOvRCM32tDKOFbH2FRT1cjYQtXYTFXXVB@oNL9IIVchM08hWt3L0U9dR0HdzdUJRPk6BoEox4AgCC8SRHmF@kEoH7BcqDuICnYNAFH@ziEgys8/DES5uDqrx1pxKSgUFAFtV8jVUUjTyNX8DwA "Python 2 – Try It Online")
[Answer]
# [Proton](https://github.com/alexander-liao/proton), 50 bytes
```
k=>31-((e=k.lower()[1to3])in"eprunov")-3*(e=="eb")
```
[Try it online!](https://tio.run/##XctBC4IwGIDhez9jpy0wEM8LNAYVIrL0ENFB7TPU3CdrM/r1q0ME8/rwvpNGg8q13A18G4UBpcCHzQNfoCm7hAajK@sUgUlbhTNhQbT@FpxATZibdKcMbSnpq6ys5JswtvpbKxJpY332cIxls/ekyvUhXTT@05cZeHC0qV/E9l4@C49OkBsYE5CeYlNgIrRnGc5irBd4g5343e4D "Proton – Try It Online")
-14 bytes thanks to Jonathan Frech
Thirty days hath September, April, June, and November. All the rest had peanut butter. All except my grandmother; she had a little red trike, but I stole it. muahahahahaha
(I've been waiting to tell that joke (source: my math professor) for ages on this site :D :D :D)
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 21 bytes
```
cal $1|xargs|tail -c3
```
[Try it online!](https://tio.run/##S0oszvj/PzkxR0HFsKYisSi9uKYkMTNHQTfZ@P///2mpSQA "Bash – Try It Online")
Takes input as command-line argument and outputs with a trailing newline. The day count for February depends on that of the current year
Requires the **util-linux 2.29** version of `cal`, which is the one [available on TIO](https://tio.run/##S0oszvj/PzcxTyE5Mef/fwA). Also is locale-dependent, so [LC\_TIME must be changed](https://tio.run/##S0oszvj/38c5PsTT19XWWSE5MUdBxbCmIrEovbimJDEzR0E32fj///9pqUkA) on non-English systems (thanks @Dennis for clarification).
Idea of piping through `xargs` to trim `cal`'s output is from [this SO answer](https://stackoverflow.com/a/12973694/8161100).
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), ~~32~~ 27 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?") ([SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set"))
-2 thanks to ngn
Tacit prefix function. Assumes `⎕IO` (**I**ndex **O**rigin) `0`, which is default on many systems.
```
32-1⌈∘⊃'.p|un|no|feb'⎕S 1⍠1
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/42NdA0f9XQ86pjxqKtZXa@gpjSvJi@/Ji01SR2oKFjB8FHvAsP/aUC1j3r7gEoe9a551Lvl0HrjR20TQQqCnIFkiIdn8P80BXWvxDx1LiDt5uoEpnMTi5IzwCzHgCBPH6hYJZj2CvVzBTOySnMgSkrTwXSwa0CIq6@TaxCY559ckp@UWgRm@@WXpebCOCmpyRBVAA "APL (Dyalog Unicode) – Try It Online")
`1⌈∘⊃` and use the maximum of one and the first element of that (0 if none) to pick from
`32-` thirty-two minus
`1⌈∘` the maximum of one and
`⊃` the first element (0 if none) of
`'.p|un|no|f'⎕S` the PCRE \**Search* for any-char,"p" or "un" or "no" or "f"
`1` returning the length of the matches
`⍠1` and done case insensitively
* **Ap**r, S**ep**, J**un**, and **No**v will give 32−2=30
* **Feb** will give 32−3=29 (allowed by OP)
* anything else will give 32−1=31
[Answer]
# [Pyke](https://github.com/muddyfish/PYKE), 9 bytes
```
l4C9@~%R@
```
[Try it here!](https://pyke.catbus.co.uk/?code=l4C9%40~%25R%40&input=December&warnings=1&hex=0)
```
l4 - input.title()
@ - v.index(^)
C9 - ['PADDING', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
@ - v[^]
~%R - ['Padding', 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
```
### Or 15 bytes if all input formats are required
```
l43<C9 3L<@~%R@
```
[Try it here!](https://pyke.catbus.co.uk/?code=l43%3CC9+3L%3C%40~%25R%40&input=Feb&warnings=1&hex=0)
```
l43< - input.title()[:3]
@ - v.index(^)
C9 3L< - ['PAD', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
@ - v[^]
~%R - ['Padding', 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
```
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 52+13=65 38+24=62 bytes
```
m=>D.DaysInMonth(1,D.Parse(1+m).Month)
```
[Try it online!](https://tio.run/##jc5BSwMxEAXgs/kVoacE20DP6xaKoVBxoaAgHsd00JHNRDNZYSn97WvdWq/u8b35eEyQRUgZh06IX/VDLwVjpc7J1@fsPBR8pIiXw299T/xZqdCCiN4dlBQoFPSm43AjJZ/gXBOXlW4SlzcPvehaD7FeefcTtjz2Zjn3bgdZ0Cyvo3VjaYdKXfa@Eu11A8TGqoO6uk0sqUX3lKng6QM0f/Nmdgc8s7b6R23wJXeQ@wk0Qp6g1h@Z2gmuWT9PUO8d48iO6jh8Aw "C# (.NET Core) – Try It Online")
+24 for `using D=System.DateTime;`
### Acknowledgements
-3 bytes thanks to Grzegorz Puławski.
[Answer]
# [Python 3](https://docs.python.org/3/), 60 bytes
```
x=input().lower()[1:3];print(31-(x in"eprunov")-3*(x=="eb"))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v8I2M6@gtERDUy8nvzy1SEMz2tDKONa6oCgzr0TD2FBXo0IhM08ptaCoNC@/TElT11hLo8LWVik1SUlT8/9/r0Q/AA "Python 3 – Try It Online")
Porting my Proton solution
-10 bytes thanks to totallyhuman
[Answer]
## [Shell/GNU Date](https://www.gnu.org/software/coreutils/manual/html_node/Examples-of-date.html), ~~39~~, 26 bytes
```
date -d1$1+1month-1day +%d
```
Where `$1` is the name of the month.
[Try it online!](https://tio.run/##S0oszvj/PyWxJFVBN8VQxVDbMDc/ryRD1zAlsVJBWzXl////aalJAA)
*edit: Thanks [Dennis](https://codegolf.stackexchange.com/users/12012/dennis) for saving many bytes!*
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), ~~45~~ 44 bytes
```
L=tolower($1){$0=L~/v|p|un/?30:L~/f/?28:31}1
```
[Try it online!](https://tio.run/##NYxBDoMgEADv@woOHtoTUi@NifEDfgLp2tYqEAQN0fbrFGh62Z3dZIZvrxC6xqpJbWhOBTvvRdl0H7oe@nCStlVZx2ug7eVaV@zNQhi5hAF7mLkBrk3cnsDoZBoTAe7usKAGJSxItcINBUTFceOTZjJEVzxI0p9R@RcwJ3xuuMWS1LE492hIyqkMsZlfKfyDLw "AWK – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 47 + 1 (`-p`) = 48 bytes
```
$_=substr$_,1,2;$_=31-("eprunov"=~/$_/i)-3*/b/i
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3ra4NKm4pEglXsdQx8gayDc21NVQSi0oKs3LL1OyrdNXidfP1NQ11tJP0s/8/z8rMe9ffkFJZn5e8X9dX1M9A0OD/7oFAA "Perl 5 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~65~~ ~~63~~ 62 bytes
```
f.map((`mod`32).fromEnum)
f(_:b:c:_)|c<3=28|c>13,b>3=30
f _=31
```
[Try it online!](https://tio.run/##dYzBaoNAFEX3fsVFulBoQxM3RWrAJqYgjYakKRQKZhxHk1RnhtFJEfLtsdN0ncV953B53D1pv1ldD1XwNZSjhkjH2TWi2HkTd1Qq0URcN65VOpmf@9TP3DN99oLJ05lOx959PvUC79EqkQXeeGjIgSNAISxIdeAd7mD2UBn@CFW0sOMwwSJ6wTJcI1ytDT8RbxOTN4TbV2yiFdLZO5L0A/NoZt8cOhKOkuWmViBSGfY4am5Sg@gKLZMQtAMXJxSM3h6KCddE9ViwXF1lSRTdIzTvtfEesebMnLpHqCvddtgw2bEmZwop7cQfE3H6L@aMXsUeLrSsSdUOD1TKXw "Haskell – Try It Online")
Pattern matching approach. The first line is to handle the case-insensitivity. Then we return `28` if the third letter is smaller than C (number 3), `30` if the second letter is larger than C and the third one larger than M, or `31` otherwise.
*Edit: -1 byte thanks to Leo*
---
### Alternative (~~65~~ 64 bytes)
```
f s|let i#n=n<mod(fromEnum$s!!i)32=sum$29:[2|2#2]++[-1|2#13,1#3]
```
[Try it online!](https://tio.run/##dYyxbsIwFEX3fsUlYWhFGRKmVs2QQqgUlYCgVKoQg@M4IdSxLTumisS3k7p0ZrjvHF093QMx34zzvi9hzpy1qH0RiZdGFvellk0ibDM0g0H9MAkj4zx8et6F59AP96PRbhw4CyaPgT/Z9w2pBSIU8g5K16LFEA1RKB1/pC4MvDTOME9esYjXiFdrxy@k28zlHfH2DZtkheX0A9nyE7Nk6t0cOhKBkuWu1iBKO3Y4WuHCQWwFwxQkbSHkCQWjt4dSIizRHeYs11dZEE0PiN07d94htYK5wzvEtrKmxYapljU501jSVv4xk6f/YsboVbz@QktOKtOPqVK/ "Haskell – Try It Online")
[Answer]
# q/kdb+, 36 bytes
**Solution:**
```
28 30 31@2^1&(*)"ebeprunov"ss(_)1_3#
```
**Examples:**
```
q)28 30 31@2^1&(*)"ebeprunov"ss(_)1_3#"January"
31
q)28 30 31@2^1&(*)"ebeprunov"ss(_)1_3#"FEB"
28
q)28 30 31@2^1&(*)"ebeprunov"ss(_)1_3#"jun"
30
```
**Explanation:**
There are a million ways to skin a cat. I think is slightly different to the others. Take the 2nd and 3rd letters of the input, lowercase them, then look them up in the string `"ebeprunov"`. If they are at location 0, then this is February, if they are at a location >0 they are a 30-dayer, if they are not in the string, they are a 31-dayer.
```
28 30 31@2^1&first"ebeprunov"ss lower 1_3# / ungolfed solution
3# / take first 3 items from list, January => Jan
1_ / drop the first item from the list, Jan => an
lower / lower-case, an => an
"ebeprunov"ss / string-search in "ebeprunov", an => ,0N (enlisted null)
first / take the first, ,0N => 0N
1& / take max (&) with 1, 0N => 0N
2^ / fill nulls with 2, 0N => 2
@ / index into
28 30 31 / list 28,30,31
```
[Answer]
# Mediawiki Template, 19 bytes
```
{{#time:t|{{{1}}}}}
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 22 bytes
```
14L22Y2c3:Z)Z{kj3:)km)
```
[**Try it online!**](https://tio.run/##y00syfn/39DEx8go0ijZ2CpKM6o6O8vYSjM7V/P///zkEAA "MATL – Try It Online")
### Explanation
```
14L % Push numeric array of month lengths: [31 28 ... 31]
22Y2 % Push cell array of strings with month names: {'January', ..., 'December'}
c % Convert to 2D char array, right-padding with spaces
3:Z) % Keep first 3 columns
Z{ % Split into cell array of strings, one each row
k % Convert to lower case
j % Input string
3:) % Keep first 3 characcters
k % Convert to lower case
m % Ismember: gives a logical index with one match
) % Use that as index into array of month lengths. Implicit display
```
[Answer]
# [Python 3](https://docs.python.org/3/) - ~~93~~ ~~86~~ ~~84~~ 82 bytes
Variants of answer (showing the progression of time, and bytes for each, with TIO links):
[Original Answer](https://tio.run/##LcsxCoQwEEDRq6QRJyCC2ClbbLvFXkAsxhg1YCZhHCGePq6w3ePDj5dsgdqcnY@BRYnztv/b4G5pRlZ4KNMvrx39NKNKnccEpvaBZGOk1UJTPV99CMcHkIauHauymEo9NKPWObIjgQUcxVNA/8oHv@ebrxs) (93 bytes)
[-7 bytes thanks to Jonathan Frech.](https://tio.run/##NcyxCoNADIDhV3EpJnAI4mbp0LVDX8A6xHrWA5M70gjn019x6PbDB386bI3SleX2KhvxNFOVe6YMb9q8zKQNR7FVST4eWmeBffM1TWdAHvpudPVlqnFoR8Rr4BTVqhPdf1CSBjFYIEjaDRCxPOi53/X4AQ) (86 bytes)
[-2 more bytes thanks to my own further testing of the `monthrange` results, with the second value always being the higher value.](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHCKjkxJzUvJbFILzc/rySjKDEvPVXDUKckMzdVr7ikqADE0KiItjKO1VFXTVLXjDaMBWHrzNyC/KISBZC0DsyI/wVFmXklGmkamXkFpSUampqa/91SnYpCixKLKgE) (84 bytes) 1
[-2 more by using `import calendar as c` and referencing it with `c.monthrange`.](https://tio.run/##FclBCoMwEEDRq2RTnEAQxJ2lR@gJrIsxxiZgJsM4gj19ShYfHnz@aSw01v31qQfmdUNzT77PhTQK0jfA4DTl0J8q3AD3PI2L6x5rZ@dhaT1T5iJq2nYej0AbisHT@MqSSGGHRHwpWGvrG8XHPw) (82 bytes, **current revision**)
---
```
lambda x:c.monthrange(1,time.strptime(x[:3],'%b')[1])[1];import time,calendar as c
```
---
Obviously not as nice as [HyperNeutrino's answer](https://codegolf.stackexchange.com/a/146562/4949) which doesn't use built-ins, but this still works.
---
*Footnotes*
1: [Test cases via TIO.run](https://tio.run/##Hc5RC4IwEMDxdz/FEYxtMATxzbeoCIIwqB5CfJhrpqI3mbPo01vn0@/PcRw3fkPjMF2WdhidDxDawSqje4tP7UFPYKLaeUBoEQreaeQKeG0rYtDeNBR69G1PcdYP4nRf17p5HW7nI3E9XIh8dyMwfxN7a3iZRQD/CxjEhk0ZsGkDDATGvftYL6QCEw8OQ@M1vqxIFP0YT8GPFAKLLC0VZxWXRVJKKZflBw) showing the proof for how I'm handling those `monthrange` values, for a varying number of month test cases.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~46~~ 30 bytes
```
#~NextDate~"Month"~DayCount~#&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n5JYWWz7X7nOL7WixCWxJLVOyTc/ryRDqc4lsdI5vzSvpE5Z7X9AUWZeiYNzfk5pbp5bflFudDWXggJIZ7SSV2JeaWJRpVKsDlwoLTUJmZvrWOScgSzgGBCEIp@Iotsr1M9VKZarNvY/AA "Wolfram Language (Mathematica) – Try It Online")
Will give either `28` or `29` for February depending on whether the current year is a leap year.
# How it works
All date commands in Mathematica will interpret input such `April`, `APR`, `ApRiL`, and so on as the first day of the corresponding month in the current year. (As a bonus, input such as `"February 2016"` or `{2016,2}` also works as expected.)
`#~NextDate~"Month"` gives the first day of the month after that, and `DayCount` gives the number of days between its two arguments. The number of days between April 1st and May 1st is 30, the number of days in April.
[Answer]
# [Java 8](http://openjdk.java.net/), 47 bytes
```
m->31-new java.util.Date(m+"31 1").getDate()%31
```
[Try it online!](https://tio.run/##dU/BasMwDL33K4RhkNDGLOS2rj2N3cYOO44dZNfNnDm2seWOMPbtmeMGdtlskB7Se3rSgBdsnFd2OH3MPgmjJUiDMcITagtfm7UWCSmni9MnGHOneqGgbf/6Bhj6WGfikCfxRNrwc7KStLP8cQX3V/LuWQxK0hEWAhzmsTl2bWPVJ/xqH5BUNW5Z10LLat4rKpX6pmvn/ebsAqzOQCoS3AEb0CYME5yVCAWMGOQ7oA/aZDzBkKzKwUyAqU9ZFJUnNQoVwElyS7buci2clCyA8eiNpooBq5fjIL/VF4UIcCj2PCYRS7W63XX1/kqbYp7OXSKeV7BkbFVW3QKD5pjDttzP0XszlVb9v7KY/a1cWovye/nzDw)
Ended up using the same idea as [Herman Lauenstein's JS answer](https://codegolf.stackexchange.com/a/146593/69583), where setting the date to the 31st pushed into the next month. Java does require a year, so that has been set to `1`.
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~32~~ ~~31~~ 28 bytes
```
i`f
28
i`p|v|un
30
\D
^$
31
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPzMhjcvIgiszoaCmrKY0j8vYgCvGhYsrToXL2PD/f6/EvNLEokout9SkIjDDN7EoOYPLsaAoMwfIruTyKs1LBRI5lVyOpemlxSVcwakFJam5SalFXP7JJfkg2i@/DCLgkpoMZgAA "Retina – Try It Online") Edit: Saved 1 byte thanks to @RobertBenson. Saved 3 bytes thanks to @ovs.
[Answer]
# Excel VBA, ~~47~~ 43 Bytes
Anonymous VBE immediate window function that takes input, as month name, abbreviation, or number, from range `[A1]` and outputs the length of that month in the year 2001 to the VBE immediate window function.
```
?31-Day(DateValue("1 "&[A1]&" 1")+30)Mod 31
```
### Old Version
```
d=DateValue(["1 "&A1&" 1"]):?DateAdd("m",1,d)-d
```
[Answer]
# PHP, ~~38~~ ~~33+1~~ 32+1 bytes
*Saved 5 bytes thanks to Titus*
```
<?=date(t,strtotime("$argn 1"));
```
Run as pipe with `-nF`
[Try it online!](https://tio.run/##JcxBCoNADAXQ/ZziI10oVKRrtbPrPaYYNVAzYYz09k1L3T@eruo@xHBJZZFxpmePrgNtxysZoRwiLAvebCuUlZBkQvtAVuMsId7DEMfpR2u77lYsG29UV/8Nt6ppevfPiXdv5Qs)
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 126 bytes
```
s->{for(java.time.Month m:java.time.Month.values())if(m.name().startsWith(s.toUpperCase()))System.out.print(m.length(false));}
```
[Try it online!](https://tio.run/##nY5NS8NAEIbP5lcsOe0K3R9gtGCLgmJPpXgQD9tkkm7cL3ZmA6Xkt8fFVpAePGSO78wz79OrQS18ANc3X5O2wUdifc5kIm1km1xN2jt5W4W0N7pmtVGIbKO0OxVIinK09g6ThXi/pahdt2SNOuKL23hHB/bAJlwsT62P/OctaQvyvLJ3V4kclEmAXAjdciudssCFzC2R8F3TgaMkvwsB4lphXgmxPSKBlT6RDLmbMmXAdfm0VQZBiGqcfs0vtoPXDbPZn591Pz6ZEuxUsMv8kZeqriEQL5@fVqWoipvrOuN4jv8jG6jB7iHOxBHCTPJ19zaTfExdQiovV2MxTt8 "Java (OpenJDK 8) – Try It Online")
[Answer]
# [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), ~~49~~ 35 bytes
```
?31-(instr(@aprjunsepnov feb`,;)%3)
```
Significantly shorter with some trickery.
## Explanation
```
? PRINT
31-( 31 minus
instr( the position of
,; our input string
@aprjunsepnov feb` ) in the string cntaining all non-31 months
%3) modulo 3 (this yields a 1 for each month except feb=2)
```
[Answer]
## [Perl 5](https://www.perl.org/), 24 bytes
**23 bytes code + 1 for `-p`.**
```
$_=31-/p|un|no/i-/f/i*3
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3tbYUFe/oKY0ryYvXz9TVz9NP1PL@P9/r8S80sSiSi631CSu3MSi5AyuxIIiLl/HSC6vUD8ur9KcSi7H0nSu4tSCktTcpNQirvzkEi4//zBXXyfXIC4XV2euf/kFJZn5ecX/dQtyAA "Perl 5 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 45 bytes
```
->m{((Date.parse(m)>>1)-1).day}
require'date'
```
[Try it online!](https://tio.run/##JYxba8JAFITf/RVDXkyQLPjYhwa2JhZCTURrQUopm3isgVy2eyks6m9Pt@nDzHycM4yylRvPj2OcdNcwTIUhJoXSFHZRkiyjeBmxk3D3maJv2yian3xjPgY5L7DOnrDhO/DtzucR@aHwegE/PGOfbVGuXlGUb0izFXLRW6Ec1lSpCTZC1RdwqZrWs0Nue/LWOnD7ZbXBnqShriKFsjbDXxbDz/8hpXqCYMa0bBvDSPitK27d0JvLDdIajYlZTb0hFT5EWCBAnHhb4Pw@PT@YGT417uMv)
Ruby's `Date.parse` accepts a month name on its own. What would normally be a right-shift (`>>`) actually adds to the month of the `Date` object. Subtraction affects the day of the month, which will wrap backwards to the last day of the previous month.
[Answer]
# [Kotlin](https://kotlinlang.org), 92 bytes
```
val d={m:String->arrayOf(0,31,30,30,31,30,31,28,31,0,30)[(m[1].toInt()+m[2].toInt())%32%11]}
```
[Try it online!](https://tio.run/##jVTbjtMwEH3PV4yqRTRQEtKyCCoKQstyeQIJeFrx4MaTxqxjB1@6rVb7L3zL/liZcdrCIh6IqtSe2zlzPM6lDVqZXfkAzhyKgBIa6yC0ykNtJcLK6gbqVmiNZoXzrA2h9/OyZCf7Ch9EfYkbCiF/Uduu/BHRB2WNL6snT09PT7P39go6YbYgxdaDMiCgsya0r7LsnVoj7wNuQhQaHPYOPZoguAKMa@HxkTJk8SpQLDRRazCiQyCaM2bmRB3QgVguHa5VysvBNgcQKhmiM9QSgondkkLJeWDC1hRWZNlbqogb0fUaJ7c/JdbI0bR8c342AWFkMt7@9K2NWgJJcqg9qzgdly4Kt4VaGGgFcUVF5R1MnzHX6fMESoGvvY/En6GV6WMA0vpAlihZg8yQ3bV1DuvAR9JR5oMyy8oSzjc9kaGTWqPzrNIxWmKxP0aiC8I5v4UrIsFZ/@ifTxpF3UJvvVdLzXwkbmAtdMSCk945sUyZHmtrJIvAs@HkH8Lv0RP/SULay91RuWD5hStimpKFlMlVwBdxmTTgjM7KqC3MpuAt8JEfWzqgeJAWvbkfaJAC7RO7VGKfW1VAWPWx@aEThtTWXkLsD1hD5852CYA0EtuCs6@ETxZtr2h8Bw3IIAInaSRgUqHXKjAOB85AqqZBR8NKc/AjKsdHwml0VE00CWmcZJnD5@CUWeWwyICehPqxGT@ezKrJ7HH6Vfv39Bm/2ZZC@ckvhjIX1bci2A8mjPOHg2F6NOT3ZtN7VfUtTcgX7kA6ui8uMemEMmPhVn4Orxn6xUDnZQ7XHP58CsttQJ/tiD7IxXU3HwIevfw/pkzwDrl/ELvZUT8E9gkdj3OSkDADiQUs27CBxVGc0Xdh@D6NJjBq9neL151wdTua7NUZid4pPdiT@3s0OPzrtBdxFX34He@xD@lis9PWwe6Xxq6P5sPdH@WUxbdkzOTS94JJsmxci1nHvqc7sEgOavkrb89ogsd5CiFyJmgzHp2kCi0N2cm1TOXym@GDMPo7cih5CE27O7E3LCOxytKCzzbb/QI "Kotlin – Try It Online")
[Answer]
# [JavaScript (V8)](https://v8.dev/), 100 bytes
```
(z,v=n=e=b=r=y=u=c=0,t=s=a=l=1,f=p=29,m=j=g=o=30,d=31)=>eval([z[0],z[1],z[2]].join`+`.toLowerCase())
```
[Try it online!](https://tio.run/##dY5Pa4QwFMTP3U8RPCU0DbpeWsrbS6@99iTCxuxbV4lJyB9FSz@71S29FHqZ92PeMEwvRxmU71x8Gp/XCVa68BEMIDTgYYYECnIeIYAEDQW/goPjCx@ghxYslDm/QFkwOOEoNa2WKq/5UhW7HOta9LYz58eziPbdTujfZEDK2Jr10iTpZ3LFxt9hkF7diHS@0xvPpE8GN9EzkalNIZKALuLQoCdWRbtfY8cf44LqDpkITneRZiRjYpCOHhBOn4cHZU2wGoW2LUU@UWTs9Y8rQmpC9DTnJdvGfjj3O3bP///dm77Y@g0 "JavaScript (V8) – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Uses [Herman's method](https://codegolf.stackexchange.com/a/146593/58974).
```
´H-ÐU+H f uH
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=tEgt0FUrSCBmIHVI&footer=SLExVQ&input=WyJKYW51YXJ5IiAiRmVicnVhcnkiICJNYXJjaCIgIkFwcmlsIiAiTWF5IiAiSnVuZSIgIkp1bHkiICJBdWd1c3QiICJTZXB0ZW1iZXIiICJPY3RvYmVyIiAiTm92ZW1iZXIiICJEZWNlbWJlciJdLW0) (includes all test cases, footer resets the `H` constant for the next case)
] |
[Question]
[
I thought this would be a fun challenge for everyone and I'm curious to see the solutions people come up with.
Print the "12 Days Of Christmas" lyrics
```
On the first day of Christmas,
my true love gave to me,
A partridge in a pear tree.
On the second day of Christmas,
my true love gave to me,
Two turtle doves,
And a partridge in a pear tree.
...
On the twelfth day of Christmas,
My true love gave to me,
Twelve drummers drumming,
Eleven pipers piping,
Ten lords-a-leaping,
Nine ladies dancing,
Eight maids-a-milking,
Seven swans-a-swimming,
Six geese-a-laying,
Five golden rings,
Four calling birds,
Three french hens,
Two turtle doves,
And a partridge in a pear tree.
```
### Rules
* You don't have to worry about capitalization; the entire text can be case insensitive
* You can sensibly ignore any punctuation: hyphens can be spaces, and commas and periods can be ignored
* There should be a blank line between each verse
* You must ordinalize your numbers: "**first** day of Christmas", "**Four** calling birds", etc
[Answer]
## Brainfuck - 2,974
I am rather proud of this one. That sounds like a pretty big number, but keep in mind, I did not use any external compression libraries, and none of the original text is in my program anywhere. None of the other submissions can say that. This is all hand coded. More naive text generators give over 39k for this text, so I would say this is a significant improvement.
```
>--[<->+++++]<---[>+>+>+>+>+<<<<<-]++++++++++>>[+++++>]<<<[+++++>]<<[+
++++>]<+++++>>++++[<++++++++>-]++++++++++++>+>+>>>>>>>>>>>>>+<<<<<<<<<
<<<<<<[<<<<++.-.->>>.<<++.--<<.<++.-->>>>>.>>>>>>>>>>>>>>[<<<<<<<<<<<<
<<<<++.>.<<<<++.-->>-.+<--.++>>.--<<.>>>>.>>>>>>>>>>>>>>-]<[<<<<<<<<<<
<<<<<<<<++.>>-.<<.>>>>-.+<<<<.-->>++.>++.--<<.>->>>.>>>>>>>>>>>>>>+<-]
<[<<<<<<<<<<<<<<++.<<<++.-->>+.->.--<<.>>>>.>>>>>>>>>>>>>+<-]<[<<<<<<<
<<<<<<<+.<+.>.->++.--<<-.>>>>.>>>>>>>>>>>>+<-]<[<<<<<<<<<<<<<<<++.-->+
.--.+.>>++.--<<.>>>>.>>>>>>>>>>>+<-]<[<<<<<<<<<<<+.<<<++.>>>>-.+<<<<.-
->>+.->+.--<<.>>>>.>>>>>>>>>>+<-]<[<<<<<<<<<<+.<<+.>>>+.-<+.--<<-.>>>>
.>>>>>>>>>+<-]<[<<<<<<<<<<<--.+++.---.>>++.--<<++.>>>>.>>>>>>>>+<-]<[<
<<<<<<<<<--.>++.-->>--.++<.++.--<<++.>>>>.>>>>>>>+<-]<[<<<<<<<++.<<.+.
->>--.<<<+.->>>>>.>>>>>>+<-]<[<<<<<<+.-<<<++.--.>>++.-.-<<+.->>>>>.>>>
>>+<-]<[<<<<<<<--.+++.->>.+.+.-->>.>>>>+<-]<<<<<<<<+.---.>>>>++.>.<<<+
+.<--.>>>>.<<<<<++.>++.>>.<<+.>>+.+.<--.<<--.>>>-.>>.<<<.>>.>.<<+.--.>
----.<<<<++++.>>>>>.<<<-.+++.>>+.<<<<.>>>>>.<<<<--.<----.>>>>.<<<<++++
.>>>>>.<<++.<.>>>.<<<--.<<.>>>>>.<<<<<-->+>>-->+>>>>>>>>>>>>>>>>>>>>>>
>>>>>>[<<<<<<<<<<<<<<<<<<<<<<<<<<<<<++.>.<<<<++.>>-.>>-.<<<<.->>>>>.<<
<<<.>>>--.>-.<<+..<<+.>>>.+.>>.<<<<<-.->>>-.>.<<..<+.>+.-<--.+>>>++>.>
>>>>>>>>>>>>>>>>>>>>>>>>>>-]<[<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<++.>>-.<<
.>>>>-.+<<<<.>>++.>>>.<<--.<<+.>>.<<<.-->>>++.+.>>.<<---.<<.>>.++<<.>.
-<--.+>>>>.>>>>>>>>>>>>>>>>>>>>>>>>>>-]<[<<<<<<<<<<<<<<<<<<<<<<<<<<<++
.<<<++.>>+.>>>.<<<--.+++.>--.<<<-.>>>+.>>.<<<<<---.>>>>>.<<<---.<<++++
.----.++>>>---.++<<+.>++.-<--.+>>>>.>>>>>>>>>>>>>>>>>>>>>>>>>-]<[<<<<<
<<<<<<<<<<<<<<<<<<<<<<+.<+.>.<<++.>>>>>.<<<--.<<----.+++.>.<+.>>>+.->>
.<<<<<-.---.>>++.<<++.>.>.-<--.+>>>>.>>>>>>>>>>>>>>>>>>>>>>>>-]<[<<<<<
<<<<<<<<<<<<<<<<<<<<<<<++.>+.--.+.>>++.>>.<<<.<<----.>+.<+++.>>>-.->>.
<<<<<---.++>>>>>.<<<.<.>-.-.<.>+++.-<--.+>>>>.>>>>>>>>>>>>>>>>>>>>>>>-
]<[<<<<<<<<<<<<<<<<<<<<<<<<+.<<<++.>>>>-.<<<<.>>+.>>>.<<.>+.<<<<----.>
>.>.>>.<<<<<.++>>>>>.<<.->.<<<+.>-..<.>+.-<--.+>>>>.>>>>>>>>>>>>>>>>>>
>>>>-]<[<<<<<<<<<<<<<<<<<<<<<<<+.<<+.>>>+.>.<<<<--.<++..>>>.-<<<.>>>>>
.<<<<<----.>>>>>.<<<-.<<.++>>>>+.--<<<++.>++.-<--.+>>>>.>>>>>>>>>>>>>>
>>>>>>>-]<[<<<<<<<<<<<<<<<<<<<<<<<<--.+++.>>>-.+<<<<++.>>>>>.<<<<--.>+
+.---.<<-.+.-->>++.>>>.<<.<<++.>.-<--.+>>+.->>.>>>>>>>>>>>>>>>>>>>>-]<
[<<<<<<<<<<<<<<<<<<<<<<<--.>++.>>--.++<.>>.<<<<<.--.>>---..<+++.>++.-<
--.>>>>.<<<<<+.>++.->>.<<<++.->>>+.->>.>>>>>>>>>>>>>>>>>>>-]<[<<<<<<<<
<<<<<<<<<<<<++.<<.>>--.<<<++..>>>>>.<<<<--.>>.<<<.>>+.<<--.>++.>>>>.<<
<<.<++.-->>.->+.->>.>>>>>>>>>>>>>>>>>>-]<[<<<<<<<<<<<<<<<<<<<++.>.<<++
.>>>.<<.>--.<--.++.<---.<<++.>>>>>.<<<<<-.>>+++.>>+.<<<<+.>>>-.>>.<<<<
<----.>>-.-<<+++.->>>->+>.>>>>>>>>>>>>>>>>>-]<[<<<<<<<<<<<<<<<<<<<<<--
.>>>>>.<<--.<<<.>>>++.++.--.<<+.<+++.>--.<+.>>>>>.<<<<++.>+.>>>.<<<<<-
---.>>>>>.<<<++.<<++++.----.>>>.>>.<<++.--.<<<++++..>>>>>.<<<<<-->->--
->>>>>>>>>>>>>>>>>>>-]<<<<<<<<<<<<<<<<<<<<<<..>>>>>>>->+[>+>>>>>>>>>>>
>>[>]+[<]<<<<<<<<<<<<<-]>[<+>-]<<]
```
Unfortunately, this is about 600 characters longer than its own output, but whatever.
It keeps the characters c,h,m,r,w in an array, and uses that to print all text. Two arrays to the right of twelve spaces each keep track of which day we are on for the count, and for which items we can output.
I may be able to optimize it a bit by reorganizing the memory map to bring the printing characters in between the two counting arrays to avoid such long chains of `<<<<<<<` and `>>>>>>`, but that would be a lot of work at this point. I could also probably choose some better seed characters with frequency analysis to minimize incrementing / decrementing, but whatever.
This does depend on 8-bit wrapping cells to work properly.
Ungolfed:
```
>--[<->+++++]<---
[>+>+>+>+>+<<<<<-]++++++++++
>>[+++++>]<<<[+++++>]<<[+++++>]<+++++>>
++++[<++++++++>-]
++++++++++++>+>+>>>>>>>>>>>>>+<<<<<<<<<<<<<<<
[
<<<<++o.-n.->>>.<<++t.--<<h.<++e.-->>>>>.
>>>>>>>>>>>>>>
12[<<<<<<<<<<<<<<<<++t.>w.<<<<++e.-->>-l.+<--f.++>>t.--<<h.>>>>.>>>>>>>>>>>>>>-]
11<[<<<<<<<<<<<<<<<<<<++e.>>-l.<<e.>>>>-v.+<<<<e.-->>++n.>++t.--<<h.>->>>.>>>>>>>>>>>>>>+<-]
10<[<<<<<<<<<<<<<<++t.<<<++e.-->>+n.->t.--<<h.>>>>.>>>>>>>>>>>>>+<-]
9<[<<<<<<<<<<<< <<+n.<+i.>n.->++t.--<<-h.>>>> . >>>>>>>>>>>>+<-]
8<[<<<<<<<<<<< <<<<++e.-->+i.--g.+h.>>++t.--<<h.>>>> . >>>>>>>>>>>+<-]
7<[<<<<<<<<<< <+s.<<<++e.>>>>-v.+<<<<e.-->>+n.->+t.--<<h.>>>> . >>>>>>>>>>+<-]
6<[<<<<<<<<< <+s.<<+i.>>>+x.-<+t.--<<-h.>>>> . >>>>>>>>>+<-]
5<[<<<<<<<< <<<--f.+++i.---f.>>++t.--<<++h.>>>>. >>>>>>>>+<-]
4<[<<<<<<< <<<--f.>++o.-->>--u.++<r.++t.--<<++h.>>>> . >>>>>>>+<-]
3<[<<<<<< <++t.<<h.+i.->>--r.<<<+d.->>>>>.>>>>>>+<-]
2<[<<<<<<+s.-<<<++e.--c.>>++o.-n.-<<+d.->>>>>.>>>>>+<-]
1<[<<<<<<<--f.+++i.->>r.+s.+t.-->>.>>>>+<-]
<<<<<<<<+d.---a.>>>>++y.>_.<<<++o.<--f.>>>>_.<<<<<++c.>++h.>>r.<<+i.>>+s.+t.
<--m.<<--a.>>>-s.>>_.<<<m.>>y.>_.<<+t.--r.>----u.<<<<++++e.>>>>>_.
<<<-l.+++o.>>+v.<<<<e.>>>>>_.
<<<<--g.<----a.>>>>v.<<<<++++e.>>>>>.
<<++t.<o.>>>.
<<<--m.<<e.>>>>>.
<<<<<-->+>>-->+
>>>>>>>>>>>>>>>>>>>>>>>>>>>>
12[<<<<<<<<<<<<<<<<<<<<<<<<<<<<<++t.>w.<<<<++e.>>-l.>>-v.<<<<e.->>>>>.
<<<<<d.>>>--r.>-u.<<+m.m.<<+e.>>>r.+s.>>.<<<<<-d.->>>-r.>u.<<m.m.<+i.>+n.-<--g.+>>>++>.
>>>>>>>>>>>>>>>>>>>>>>>>>>>-]
11<[<<<<<<<<<<<<<<<<<<<<<<<<<<< <<<<++e.>>-l.<<e.>>>>-v.+<<<<e.>>++n.>>>.
<<--p.<<+i.>>p.<<<e.-->>>++r.+s.>>.<<---p.<<i.>>p.++<<i.>n.-<--g.+>>>>.>>>>>>>>>>>>>>>>>>>>>>>>>>-]
10<[<<<<<<<<<<<<<<<<<<<<<<<<<< <++t.<<<++e.>>+n.>>> .<<<--
.+++o.>--r.<<<-d.>>>+s.>>.<<<<<---a.>>>>>.<<<---l.<<++++e.----a.++>>>---p.++<<+
i.>++n.-<--g.+>>>> . >>>>>>>>>>>>>>>>>>>>>>>>>-]
9< [<<<<<<<<<<<<<<<<<<<<<<<<< <<+n.<+i.>n.<<++e.>>>>> .<<<--l.<<----a.+++d.>
i.<+e.>>>+s.->> .<<<<<-d.---a.>>++n.<<++c.>i.>n.-<--g.+>>>> . >>>>>>>>>>>>>>>>>>>>>>>>-]
8< [<<<<<<<<<<<<<<<<<<<<<<<< <<<<++e.>+i.--g.+h.>>++t.>> .<<<m.<<----a.>+
i.<+++d.>>>-s.->> .<<<<<---a.++>>>>> .<<<m.<i.>-l.-k.<i.>+++n.-<--g.+>>>> . >>>>>>>>>>>>>>>>>>>>>>>-]
7< [<<<<<<<<<<<<<<<<<<<<<<< <+s.<<<++e.>>>>-v.<<<<e.>>+n.>>> .<<s.>+w.<<<<
----a.>>n.>s.>> .<<<<<a.++>>>>> .<<s.->w.<<<+i.>-m.m.<i.>+n.-<--g.+>>>>. >>>>>>>>>>>>>>>>>>>>>>-]
6< [<<<<<<<<<<<<<<<<<<<<<< <+s.<<+i.>>>+x.> .<<<<--g.<++e.e.>>>s.-<<<e.>>>>>
.<<<<<----a.>>>>> .<<<-l.<<a.++>>>>+y.--<<<++i.>++n.-<--g.+>>>> . >>>>>>>>>>>>>>>>>>>>>-]
5< [<<<<<<<<<<<<<<<<<<<<< <<<--f.+++i.>>>-v.+<<<<++e.>>>>> .<<<<--g.>++o.---
l.<<-d.+e.-->>++n.>>> .<<r.<<++i.>n.-<--g.+>>+s.->> . >>>>>>>>>>>>>>>>>>>>-]
4< [<<<<<<<<<<<<<<<<<<<< <<<--f.>++o.>>--u.++<r.>> .<<<<<c.--a.>>---l.l.<+++
i.>++n.-<--g.>>>> .<<<<<+b.>++i.->>r.<<<++d.->>>+s.->> . >>>>>>>>>>>>>>>>>>>-]
3< [<<<<<<<<<<<<<<<<<<< <++t.<<h.>>--r.<<<++e.e.>>>>> .<<<<--f.>>r.<<<e.>>+
n.<<--c.>++h.>>>> .<<<<h.<++e.-->>n.->+s.->> . >>>>>>>>>>>>>>>>>>-]
2< [<<<<<<<<<<<<<<<<<<<++t.>w.<<++o.>>>.<<t.>--u.<--r.++t.<---l.<<++e.>>>>>.
<<<<<-d.>>+++0.>>+v.<<<<+e.>>>-s.>>.<<<<<----a.>>-n.-<<+++d.->>>->+>.
>>>>>>>>>>>>>>>>>-]
1<[<<<<<<<<<<<<<<<<<<<<<--a.>>>>>.<<p--.<<<a.>>>++r.++t.--r.<<+i.<+++d.>--g.<+
e.>>>>>.<<<<++i.>+n.>>>.<<<<<----a.>>>>>.<<<++p.<<++++e.----a.>>>r.>>.<<++
t.--r.<<<++++e..>>>>>.<<<<<-->->--->>>>>>>>>>>>>>>>>>>-]
<<<<<<<<<<<<<<<<<<<<<<..>>>>>>>->+
[>+>>>>>>>>>>>>>[>]+[<]<<<<<<<<<<<<<-]>[<+>-]<<
]
```
[Answer]
# Common Lisp, 333 ~~363~~
```
(dotimes(n 12)(format t"on-the-~:R-day-of-christmas
my-true-love-gave-to-me
~v*~@{~R-~A
~#[and-~]~}a-PARTRIDGE-IN-A-PEAR-TREE
"(1+ n)(- 22 n n)12'drummers-drumming 11'pipers-piping 10'lords-a-leaping 9'ladies-dancing 8'maids-a-milking 7'swans-a-swimming 6'geese-a-laying 5'golden-rings 4'calling-birds 3'french-hens 2'turtle-doves))
```
The builtin facilities to format ordinals are helpful, but most of the compression comes from being able to use the same argument list over and over, skipping over fewer and fewer arguments at each run.
As proven by [coredump](https://codegolf.stackexchange.com/users/903/coredump) in the comments, the builtin facilities can still be put to good use for the cardinals.
[Answer]
## Perl, ~~438~~ 291 chars
Inspired by [Jeff Burdges's use of DEFLATE compression](https://codegolf.stackexchange.com/a/4197/3191), [Ventero's compressed Ruby code](https://codegolf.stackexchange.com/a/4213/3191) and [J B's use of Lingua::EN::Numbers](https://codegolf.stackexchange.com/a/4209/3191), I managed to compress my entry down to 291 chars (well, bytes) including decompression code. Since the program contains some non-printable characters, I've provided it in [MIME Base64 format](http://en.wikipedia.org/wiki/Base64):
```
dXNlIENvbXByZXNzOjpabGliO2V2YWwgdW5jb21wcmVzcyAneNolkMFqAkEMhu8+RVgELdaIXmXB
S2/FFyhF4k7cHTqTsclMZd++M3pJvo+QH5JiDJ9exkKrj/PqXOKV1bod77qj9b2UeGBZ7w/bpd9s
3rCDruf3uWtwS3qS/vfROy0xsho+oWbB3d+b19YsJHWGhIHp5eQ8GzqSoWkk/xxHH36a24OkuT38
K21kNm77ND81BceCWtlgoBAq4NWrM7gpyzDhxGKQi+bA6NIfG5K4/mg0d0kgTwwdvi67JHVeKKyX
l3acoxnSDYZJveVIBnGGrIUh1BQYqZacIDKc5Gvpt1vEk3wT3EmzejcyeIGqTApZmRftR7BH3B8W
/5Aze7In
```
To unencode the program, you can use the following helper Perl script:
```
use MIME::Base64;
print decode_base64 $_ while <>;
```
Save the output in a file named `12days.pl` and run it with `perl -M5.01 12days.pl`. As noted, you need to have the [Lingua::EN::Numbers](http://search.cpan.org/dist/Lingua-EN-Numbers/) module installed for the code to work.
In case you're wondering, the readable part of the code simply looks like this:
```
use Compress::Zlib;eval uncompress '...'
```
where the `...` stands for 254 bytes of [RFC 1950](https://www.rfc-editor.org/rfc/rfc1950) compressed Perl code. Uncompressed, the code is 361 chars long and looks like this:
```
use Lingua'EN'Numbers"/e/";s==num2en(12-$i++)." "=e,y"." "for@n=qw=drummers.drumming pipers.piping lords.a.leaping ladies.dancing maids.a.milking swans.a.swimming geese.a.laying golden.rings calling.birds french.hens turtle.doves.and=;say"on the ".num2en_ordinal($_)." day of christmas my true love gave to me @n[$i--..@n]a partridge in a pear tree
"for 1..12
```
Writing this code was a weird kind of golfing exercise: it turns out the maximizing repetition and minimizing the number of distinct characters used are much more important than minimizing raw character count when the relevant metric is size *after compression*.
To squeeze out the last few chars, I wrote a simple program to try small variations of this code to find the one that compresses best. For compression, I used Ken Silverman's [KZIP](http://advsys.net/ken/utils.htm) utility, which usually yield better compression rations (at the cost of speed) than standard Zlib even at the maximum compression settings. Of course, since KZIP only creates ZIP archives, I then had to extract the raw DEFLATE stream from the archive and wrap it in a RFC 1950 header and checksum. Here's the code I used for that:
```
use Compress::Zlib;
use 5.010;
@c = qw(e i n s);
@q = qw( " );
@p = qw( = @ ; , );
@n = ('\n',"\n");
$best = 999;
for$A(qw(e n .)){ for$B(@q){ for$C(@q,@p){ for$D(@p){ for$E(@q,@p){ for$F(qw(- _ . N E)){ for$G("-","-"eq$F?():$F){ for$H(@c){ for$I(@c,@p){ for$N(@n){ for$X(11,"\@$I"){ for$Y('$"','" "',$F=~/\w/?$F:()){ for$Z('".num2en_ordinal($_)."'){
$M="Lingua'EN'Numbers";
$code = q!use MB/A/B;sDDnum2en(12-$H++).YDe,yCFC Cfor@I=qwEdrummersFdrumming pipersFpiping lordsGaGleaping ladiesFdancing maidsGaGmilking swansGaGswimming geeseGaGlaying goldenFrings callingFbirds frenchFhens turtleFdovesFandE;say"on the Z day of christmas my true love gave to me @I[$H--..X]a partridge in a pear treeN"for 1..12!.$/;
$code =~ s/[A-Z]/${$&}/g;
open PL, ">12days.pl" and print PL $code and close PL or die $!;
$output = `kzipmix-20091108-linux/kzip -b0 -y 12days.pl.zip 12days.pl`;
($len) = ($output =~ /KSflating\s+(\d\d\d)/) or die $output;
open ZIP, "<12days.pl.zip" and $zip = join("", <ZIP>) and close ZIP or die $!;
($dfl) = ($zip =~ /12days\.pl(.{$len})/s) or die "Z $len: $code";
$dfl = "x\xDA$dfl" . pack N, adler32($code);
$dfl =~ s/\\(?=[\\'])|'/\\$&/g;
next if $best <= length $dfl;
$best = length $dfl;
$bestcode = $code;
warn "$A$B$C$D$E$F$G$H$I $X $Y $best: $bestcode\n";
open PL, ">12days_best.pl" and print PL "use Compress::Zlib;eval uncompress '$dfl'" and close PL or die $!;
}}}}}}
print STDERR "$A$B$C$D$E$F\r";
}}}}}}}
```
If this looks like a horrible kluge, it's because that's exactly what it is.
---
For historical interest, here's my original 438-char solution, which generates nicer output, including line breaks and punctuation:
```
y/_/ /,s/G/ing/for@l=qw(twelve_drummers_drummG eleven_pipers_pipG ten_lords-a-leapG nine_ladies_dancG eight_maids-a-milkG seven_swans-a-swimmG six_geese-a-layG five_golden_rGs four_callG_birds three_french_hens two_turtle_doves);s/e?t? .*/th/,s/vt/ft/for@n=@l;@n[9..11]=qw(third second first);say map("\u$_,\n","\nOn the $n[11-$_] day of Christmas,\nMy true love gave to me",@l[-$_..-1]),$_?"And a":A," partridge in a pear tree."for 0..11
```
Highlights of this version the pair of regexps `s/e?t? .*/th/,s/vt/ft/`, which construct the ordinals for 4 to 12 from the cardinals at the beginning of the gift lines.
This code can, of course, also be compressed using the Zlib trick described above, but it turns out that simply compressing the *output* is more efficient, yielding the following 338-byte program (in Base64 format, again):
```
dXNlIENvbXByZXNzOjpabGliO3NheSB1bmNvbXByZXNzICd42uWTwU7DMAyG730KP8DGOyA0bsCB
vYBp3MYicSo7W9e3xx3ijCIQDHZIUjn683+/k3ZPAjUSDKxWIeACZYC7qGw1o226hwWqHghSORKM
6FMtkGnT3cKEWpXDSMACCBOhQlWim+7jUKO+SGg5dT8XqAetiSD4nrmPBMDPvXywtllF18OgJH2E
SGJfcR+Ky2KL/b0roMeUWEZ4cXb7biQeGol4LZQUSECdyn4A0vjUBvnMXCcYiYy2uE24ONcvgdOR
pBF9lYDNKObwNnPOTnc5kYjH2JZotyogI4c1Ueb06myXH1S48eYeWbyKgclcJr2D/dnwtfXZ7km8
qOeUiXBysP/VEUrt//LurIGJXCdSWxeHu4JW1ZnS0Ph8XOKloIecSe39w/murYdvbRU+Qyc=
```
I also have a 312-byte gzip archive of the lyrics, constructed from the same DEFLATE stream. I suppose you could call it a "zcat script". :)
[Answer]
## Python 2.7 (465)
```
for k in range(12):
print'On the %s day of Christmas\nMy true love gave to me'%'first^second^third^fourth^fifth^sixth^seventh^eighth^ninth^tenth^eleventh^twelfth'.split('^')[k]
print'\n'.join('Twelve drummers drumm*Eleven pipers pip*Ten lords-a-leap*Nine ladies danc*Eight maids-a-milk*Seven swans-a-swimm*Six geese-a-lay*Five golden rings^Four calling birds^Three french hens^Two turtle doves and^a partridge in a pear tree^'.replace('*','ing^').split('^')[11-k:])
```
However, I put the 'and' on the same line as the doves instead of the partridge.
[Answer]
# JavaScript 570
This is my first time golfing. JavaScript 570
```
var l=["first","second","third","fourth","fifth","sixth","seventh","eigth","nineth","tenth","eleventh","twelth","Two turtle doves","Three french hens","Four calling birds","Five golden rings","Six geese-a-laying","Seven swans-a-swimming","Eight maids-a-milking","Nine ladies dancing","Ten lords-a-leaping","Eleven pipers piping","Twelve drummers drumming"];var b = "<br/>";for(var i=0;i<12;i++){var p="On the "+l[i]+"day of Christmas"+b+"My true love gave to me"+b;for(var x=i;x>0;x--)p+=l[13+x]+b;if(i>0)p+="and ";p+="a partridge in a pear tree"+b+b;document.write(p);}
```
[Answer]
# Vim – 578 keystrokes
I decided to try and vim-golf this, since this is the kind of thing that can be vim-golfed.
Start by inserting the framework - the "X day of Christmas" line a total of 12 times (89 keystrokes):
```
KS TL GT
12iOn the X day of Christmas,<Enter> 30 30 30
my true love gave to me,<Enter> 25 55 55
and a partridge in a pear tree.<Enter> 32 87 87
<Enter><Esc> 2 89 89
```
Then, perform a series of macros that will insert the numbers 2 through 12 in the respective places they need to be for the lyrics (172 keystrokes):
```
KS TL GT
42kqmO2<Esc>9/a<Enter>q10@m 17 17 106
dw 2 19 108
6jqm/2<Enter>O3<Esc>jq9@m 14 33 122
/3<Enter>qm/3<Enter>O4<Esc>jq8@m 16 49 138
/4<Enter>qm/4<Enter>O5<Esc>jq7@m 16 65 154
/5<Enter>qm/5<Enter>O6<Esc>jq6@m 16 81 170
/6<Enter>qm/6<Enter>O7<Esc>jq5@m 16 97 186
/7<Enter>qm/7<Enter>O8<Esc>jq4@m 16 113 202
/8<Enter>qm/8<Enter>O9<Esc>jq3@m 16 129 218
/9<Enter>qm/9<Enter>O10<Esc>jq2@m 17 146 235
/10<Enter>qm/10<Enter>O11<Esc>jq@m 18 164 253
?11<Enter>O12<Esc> 8 172 261
```
The "dw" on the second line is to get rid of the first "and", because it doesn't go there.
Then, perform a series of substitutions for the number of things the true love gave (319 keystrokes):
```
KS TL GT
:%s/12/twelve drummers drumming,/g 34 34 295
:%s/11/eleven pipers piping,/g 30 64 325
:%s/10/ten lords-a-leaping,/g 29 93 354
:%s/9/nine ladies dancing,/g 28 117 382
:%s/8/eight maids-a-milking,/g 30 147 412
:%s/7/seven swans-a-swimming,/g 31 178 443
:%s/6/six geese-a-laying,/g 27 205 366
:%s/5/five golden rings,/g 26 231 392
:%s/4/four calling birds,/g 27 268 419
:%s/3/three french hens,/g 26 294 445
:%s/2/two turtle doves,/g 25 319 470
```
And finally, replacing each occurrence of `X` with an ordinal number:
```
KS TL GT
/X<Enter>sfirst<Esc> 10 10 480
nssecond<Esc> 9 18 488
nsthird<Esc> 8 27 497
nsfourth<Esc> 9 36 506
nsfifth<Esc> 8 44 514
nssixth<Esc> 8 52 522
nsseventh<Esc> 10 62 532
nseighth<Esc> 9 71 541
nsninth<Esc> 8 79 549
nstenth<Esc> 8 87 557
nseleventh<Esc> 11 98 568
nstwelfth<Esc> 10 108 578
```
And we're done!
---
I'm sure there are other optimizations I missed, but I think that's pretty good myself.
[Answer]
## Ruby (474)
```
(0..11).each{|i|puts "On the #{"first^second^third^fourth^fifth^sixth^seventh^eighth^ninth^tenth^eleventh^twelfth".split("^")[i]} day of Christmas\nMy true love gave to me";puts "a partridge in a pear tree\n\n^two turtle doves and^three french hens^four calling birds^five golden rings^six geese-a-lay*Seven swans-a-swimm*Eight maids-a-milk*Nine ladies danc*Ten lords-a-leap*Eleven pipers pip*Twelve drummers drumming".gsub('*','ing^').split('^')[0..i].reverse.join("\n")}
```
or in a more readable form (486):
```
(0..11).each do |i|
puts "On the #{"first^second^third^fourth^fifth^sixth^seventh^eighth^ninth^tenth^eleventh^twelfth".split("^")[i]} day of Christmas\nMy true love gave to me"
puts "a partridge in a pear tree\n\n^two turtle doves and^three french hens^four calling birds^five golden rings^six geese-a-lay*Seven swans-a-swimm*Eight maids-a-milk*Nine ladies danc*Ten lords-a-leap*Eleven pipers pip*Twelve drummers drumming".gsub('*','ing^').split('^')[0..i].reverse.join("\n")
end
```
anybody got an idea how to circumvent the .reverse? i could't come up with a solution
[Answer]
## PowerShell, 440
```
-join('On the 1 day of Christmas
my true love gave to me
1a partridge in a pear tree
1first1second1third1fourth1fifth1sixth1seventh1eighth1ninth1tenth1eleventh1twelfth1Twelve drummers drumm7Eleven pipers pip7Ten lords-a-leap7Nine ladies danc7Eight maids-a-milk7Seven swans-a-swimm7Six geese-a-lay7Five golden rings
1Four calling birds
1Three french hens
1Two turtle doves
And '-replace7,'ing
1'-split1)[(26..15|%{0
29-$_
1
$_..26-le25
2})]
```
This prints the lyrics as given in the question with multiple lines per verse. We can save a few characters if that requirement isn't there.
[Answer]
## Perl, 500 485
```
@s=(first,second,third,fourth,fifth,sixth,seventh,eighth,ninth,tenth,eleventh,twelfth);
$;=ing;
@a=(
"Twelve drummers drumm$;",
"Eleven pipers pip$;",
"Ten lords-a-leap$;",
"Nine ladies danc$;",
"Eight maids-a-milk$;",
"Seven swans-a-swimm$;",
"Six geese-a-lay$;",
"Five golden r$;s",
"Four call$; birds",
"Three french hens",
"Two turtle doves\nAnd "
);
for(0..11){
print"\n\nOn the $s[$_] day of Christmas\nMy true love gave to me\n";
$"=$/;
print"@b";
unshift@b,pop@a;
print"A partridge in a pear tree"
}
```
This is my first attempt, and I am sure it could be made a lot shorter. The line breaks are for readability. It has three important arrays, one of which holds the name for each day `@s`, one of which lists off all of the gifts (except for the first one) `@a`, and one that lists off what gifts have already been given `@b`. The main mechanism is that each day, it prints `@b` and then transfers one additional gift from `@a` to `@b`.
Thanks to Andrew for 500->485
[Answer]
# C (644)
Count does not include whitespace used for presentation.
```
#include <stdio.h>
void main() {
char *e = "On the \0 day of Christmas my true love gave to me\0 Twelve drummers drumming Eleven pipers piping Ten lords-a-leaping Nine ladies dancing Eight maids-a-milking Seven swans-a-swimming Six geese-a-laying Five golden rings Four calling birds Three french hens Two turtle doves and A partridge in a pear tree\n\n";
printf("%sfirst%s%s%ssecond%s%s%sthird%s%s%sfourth%s%s%sfifth%s%s%ssixth%s%s%sseventh%s%s%seighth%s%s%sninth%s%s%stenth%s%s%seleventh%s%s%stwelfth%s%s",
e, e+8, e+276, e, e+8, e+255, e, e+8, e+237, e, e+8, e+218, e, e+8, e+200, e, e+8, e+181, e, e+8, e+158, e, e+8, e+136, e, e+8, e+116, e, e+8, e+96, e, e+8, e+75, e, e+8, e+50);
}
```
Output is like:
```
On the first day of Christmas my true love gave to me A partridge in a pear tree
...
On the twelfth day of Christmas my true love gave to me Twelve drummers drumming Eleven pipers piping Ten lords-a-leaping Nine ladies dancing Eight maids-a-milking Seven swans-a-swimming Six geese-a-laying Five golden rings Four calling birds Three french hens Two turtle doves and A partridge in a pear tree
```
[Answer]
## Powershell, 487 453
```
0..11 | % {
'On the {0} day of christmas my true love gave to me {1}`n'-f
(
'first^second^third^fourth^fifth^sixth^seventh^eighth^ninth^tenth^eleventh^twelfth'.Split('^')[$_],
(
'a partridge in a pear tree^two turtle doves and^three french hens^four calling birds^five golden rings^six geese-a-laying^Seven swans-a-swimming^Eight maids-a-milking^Nine ladies dancing^Ten lords-a-leaping^Eleven pipers piping^Twelve drummers drumming'.Split('^')[$_..0]-join' '
)
)
}
```
Thank you to [Daan](https://codegolf.stackexchange.com/a/4205/880) for the idea of splitting a concatenated string.
I had originally included a switching statement to get the "and" on the partridge for all but the first verse. But, because the question absolves us of punctuation, we can just append the "and" to the doves.
This results in line feeds as follows:
```
On the first day of christmas my true love gave to me a partridge in a pear tree
On the second day of christmas my true love gave to me two turtle doves and a partridge in a pear tree
On the third day of christmas my true love gave to me three french hens two turtle doves and a partridge in a pear tree
```
[Answer]
# Perl, 368 ~~389~~ (no unicode/compression)
```
use Lingua::EN::Numbers"/n/";@s=qw(A-partridge-in-a-pear-tree turtle-doves french-hens calling-birds golden-rings geese-a-laying swans-a-swimming maids-a-milking ladies-dancing lords-a-leaping pipers-piping drummers-drumming);$_=$s[0];for$m(1..12){$n=num2en_ordinal$m;say"On the $n day of christmas
my true love gave to me
$_
";s/A/and a/;$_=num2en($m+1)." $s[$m]
$_"}
```
Harnesses [Lingua::EN::Numbers](https://metacpan.org/module/Lingua%3a%3aEN%3a%3aNumbers), though I'm not 100% convinced it's a good idea when I see the module and its identifier names' lengths. Needs Perl 5.10 or later, run from the command line with a `-E` switch.
**Edit:** minor improvements: stop using an array, better use of `$_`, unneeded whitespace.
[Answer]
## C# (528)
```
class P{static void Main(){for(int i=1;i<12;i++){Console.WriteLine("On the "+"^first^second^third^fourth^fifth^sixth^seventh^eighth^ninth^tenth^eleventh^twelfth".Split('^')[i]+" day of christmas my true love gave to me "+"a partridge in a pear tree^two turtle doves and^three french hens^four calling birds^five golden rings^six geese-a-laying^Seven swans-a-swimming^Eight maids-a-milking^Nine ladies dancing^Ten lords-a-leaping^Eleven pipers piping^Twelve drummers drumming".Split('^').Take(i).Aggregate("",(t,s)=>s+' '+t));}}}
```
[Answer]
PHP, 548
```
$n=explode('|','first|second|third|fourth|fifth|sixth|seventh|eighth|ninth|tenth|eleventh|twelfth');$w=explode('|','and a partridge in a pear tree.|two turtle doves|three french hens|four calling birds|five golden rings|six geese a-laying|seven swans a-swimming|eight maids a-milking|nine ladies dancing|ten lords a-leaping|eleven pipers piping|twelve drummers drumming');foreach($n as $i=>$j)echo "on the $n[$i] day of christmas,\nmy true love sent to me\n".str_replace($i?'':'and ','',implode(",\n",array_reverse(array_slice($w,0,$i+1))))."\n\n";
```
Reduced length with compression, 502
```
eval(gzuncompress(base64_decode('eNpVkE1u3DAMhfc+BWEI8AzqDtJtg7QHCYKCsWiLrX4MUjPOAD58KE829UIyP5Hge8/lF/pYY/F0GvZhHGYWrbvSVLLfa2Dx+1yuUsM+82yn8kc76UbZbuIl2JW5FfWB4tdb3SjaxHB+dtv/OzB7QFhRqrBfCDi3klCgCtHFJgtU2xkJfLmRmg7jMAvlKUCgrIcmmDBGzgu8m0pDfCNYSvSUQQxr0woLkRLg94h3Yw/hoBtmNagbp9Tw4QMSsm84cfzXqNkiiOiZFDzmqTEzCbHI0RcJ12P6sAwrryTarqPR7JsgL9eUGj5+7MHymIsQTuHkzLeC45df7u+ZplCgLxlqIHD51fGbLb1DmWEKwloT6tilu2V0NVWWC6jlDLVAoq6/aJU/QmvEiU6Ofw/DzyNni3sYOT3S78euH1EE79Z6M1V0elQauY1t49Po+NuPs32Xvuv650+BSMT/')));
```
[Answer]
# Java, 2062
I know this was posted a while ago, but I thought I would try. I'm a student and still new to this but its seems to work.
```
public class TwelveDaysOfChristmas
{
public static void main(String[] args)
{
String[] days = new String[12];
days[0] = "and a partriage in a pear tree.";
days[1] = "Two turtle doves, ";
days[2] = "Three french hens, ";
days[3] = "Four callings birds, ";
days[4] = "Five diamond rings, ";
days[5] = "Six geese a-laying, ";
days[6] = "Seven swans a-swimming, ";
days[7] = "Eight maids a-milking, ";
days[8] = "Nine ladies dancing, ";
days[9] = "Ten lords a-leaping, ";
days[10] = "Eleven pipers piping, ";
days[11] = "Twelve twelve drummers drumming, ";
System.out.println(chorus(0));
System.out.println("a partriage in a pear tree");
for(int i = 1; i<days.length; i++)
{
System.out.println(chorus(i));
for(int x = i; x>=0; x--)
{
System.out.println(days[x]);
}
System.out.println();
}
}
public static String chorus(int line)
{
String chorus = "On the " + getLine(line) + " day of Christmas my true " +
"love gave to me, ";
return chorus;
}
public static String getLine(int line)
{
int num = line;
String result = "first";
switch (num)
{
case 1: result = "second";
break;
case 2: result = "third";
break;
case 3: result = "fourth";
break;
case 4: result = "fifth";
break;
case 5: result = "sixth";
break;
case 6: result = "seventh";
break;
case 7: result = "eighth";
break;
case 8: result = "ninth";
break;
case 9: result = "tenth";
break;
case 10: result = "eleventh";
break;
case 11: result = "twelfth";
break;
}
return result;
}
}
```
[Answer]
## Swift, 577
```
import UIKit
let f=NSNumberFormatter()
f.numberStyle = .SpellOutStyle
for i in 0...11{
let w = split("first-second-third-four-fif-six-seven-eigh-nin-ten-eleven-twelf"){$0=="-"}[i]+(i<3 ?"":"th")
println("On the \(w) day of Christmas\nmy true love gave to me")
for m in reverse(0...i){
if m==0{break}
let v = split("turtle doves and*french hens*calling birds*golden rings*geese-a-lay*swans-a-swimm*maids-a-milk*ladies danc*lords-a-leap*pipers pip*drummers drumm"){$0=="*"}[m-1]+(m<5 ?"":"ing")
println("\(f.stringFromNumber(m+1)!) \(v)")}
println("a partridge in a pear tree.")}
```
You can paste this in a playground.
I tried moving the `v` into the print command and got:
```
Playground execution failed: <EXPR>:20:1: error: expression was too complex to be solved in reasonable time; consider breaking up the expression into distinct sub-expressions
```
[Answer]
# [///](https://esolangs.org/wiki////), 439 bytes
```
/|/\/\///^/on the |%/ day of christmas
my true love gave to me
|=/-a-|&/ing|*/even|+/th%|:/
^|A/el* pipers pip&
B|B/ten lords=leap&
C|C/nine ladies danc&
D|D/eight maids=milk&
E|E/s* swans=swimm&
F|F/six geese=lay&
G|G/five golden r&s
H|H/four call& birds
I|I/three french hens
J|J/two turtle doves
and K|K/a partridge in a pear tree/^first%K:second%J:+ird%I:four+H:fif+G:six+F:s*+E:eigh+D:nin+C:ten+B:el*+A:twelf+twelve drummers drumm&
A
```
[Try it online!](https://tio.run/##HVDJiiMxDL37K3QpH2Ia3Q05ZN9@oQl4yqoqM7YrWE5nAv73tGoQaEPoLRwdT8SfDzb8lkC845yhTgStQ/DuDfMA/VQC1@RYpTfU8iSI8w/B6CTVGRKptsYv99U0hjy2FdIP5WawTl2zqNS9bZDiCh7hQYWXotW2bbFSlk/F8zqSk92u7TCHLO@dD8QCn3ut9m2PFMapQnJBblOIf7U6tAPyCvjlMq/5FVLS6tiOyOEfjERM6@jeWp3aCYewkJ2jF7iiWZ3bGYf5WaB3MWr4E4SBurSL8C1EMBTK/QQTZVbXdsX6mqE@S40EXmSzctnDrd3QwcOVWoIfCUIGGckV8YcI70MoXLubZern7LurNYLSXeyCa852CIM5WeFqjpZX5mAXgWZvRb3ZWfHFbK04Zja2vigOZskiwpdnSouF/xutNp/PLw "/// – Try It Online")
If trailing newlines are allowed, you can save four bytes:
```
/|/\/\///^/on the |%/ day of christmas
my true love gave to me
|=/-a-|&/ing|*/even|+/th%|A/el* pipers pip&
B|B/ten lords=leap&
C|C/nine ladies danc&
D|D/eight maids=milk&
E|E/s* swans=swimm&
F|F/six geese=lay&
G|G/five golden r&s
H|H/four call& birds
I|I/three french hens
J|J/two turtle doves
and K|K/a partridge in a pear tree
/^first%K^second%J^+ird%I^four+H^fif+G^six+F^s*+E^eigh+D^nin+C^ten+B^el*+A^twelf+twelve drummers drumm&
A
```
[Try it online!](https://tio.run/##HVDJbgMhDL3zFb4Mh6DKX5BD9u0XKiQ6eGZQgYkwaRqJf089FZLxJr@Fo@OJ@P3Ghp/yEC3OGepE0DoE714wD9BPJXBNjlV6QS0Pgjj/EIxOQp0hkWpr/HAfTWPIY1sh/VBuBuvUtQ1SXME93Knw8mm1bVuslOVG8byO5KS3azvMIcth5wOxAOdeq33bI4VxqpBckN0U4rdWh3ZAXgE/XeY1P0NKWh3bETn8wkjEtI7updWpnXAIC805eoErmtW5nXGYHwV6F6OGryAM1KVdhGkhgqFQ7ieYKLO6tivW5wz1UWok8CKYlcsebu2GDu6u1BL8SBAySEmuiDNESqEdQuHa3SxTP2ffXa0RnO5iF2RzlvFgTlbYmqPllTnYRaLZW9FvdlacMVsrnpmNrU@Kg1miyPDlkdJi4n@i1eb9/gM "/// – Try It Online")
### Explanation
/// is a language where the only operation is a self-modifying substitution. In particular, the instruction `/abc/xyz/` replaces all instances of `abc` with `xyz` in the rest of the source code, including other substitutions.. Any other characters are simply output to STDOUT.
While this is enough for Turing-completeness, golfing in /// generally consists of starting with the intended output and identifying repeated substrings that can be replaced with single-character shortcuts.
`\` can be used as an escape character in patterns, replacements, and literal characters to mean a literal `/` or `\`.
---
The first instruction encountered is `/|/\/\//`. This means "replace all `|` with `//` in the rest of the program." This saves a byte for every subsequent substitution in the program.
---
After this, a set of replacements are made to compress the text itself:
* `on the` becomes `^`.
* `day of christmas \n my true love gave to me \n` becomes `%`.
* `-a-` becomes `=`.
* `ing` becomes `&`.
* `even` becomes `*`.
* `th%` becomes `+`.
* `^` preceded by two newlines (which appears in every verse but the first) becomes `:`.
---
Following this, we write the lyrics themselves. This is done using replacements `A` through `K`. Each letter replacement adds a line to the replacement after it. For example, `K` represents `a partridge in a pear tree` and `J` represents `two turtle doves \n and K`.
In this way, each verse of the song is composed of:
* `^` or `:`
* A string representing the correct ordinal (say, `el*th`)
* `%`
* A letter `A` through `K` that represents the correct lyrics.
However, because most of the ordinals end in `th`, we use the substitution `th%` → `+` to save some bytes.
[Answer]
## Ruby 1.9.3, compressed, 321 characters
Since the code contains non-printable characters, I'll post a hexdump of the code instead:
```
0000000: 2363 6f64 696e 673a 6269 6e61 7279 0a72 #coding:binary.r
0000010: 6571 7569 7265 277a 6c69 6227 3b65 7661 equire'zlib';eva
0000020: 6c20 5a6c 6962 2e69 6e66 6c61 7465 2778 l Zlib.inflate'x
0000030: da2d 90db 6ac3 300c 86ef f714 a163 b042 .-..j.0......c.B
0000040: 15e8 5ea7 f442 8be5 58cc 8720 39cd 42db ..^..B..X.. 9.B.
0000050: 3dfb e4a4 3792 f559 c7ff fcd5 574e a4f7 =...7..Y....WN..
0000060: 073f a6b9 eaa1 64a8 81e0 fdfe b17c 7a16 .?....d......|z.
0000070: ad9d d250 b2eb 6a60 719d 2fb3 d4d0 79f6 ...P..j`q./...y.
0000080: 6695 7f9b a51b 65f3 c463 3097 b905 7547 f.....e..c0...uG
0000090: f1f5 5717 8a56 71bc f0f5 090e 5728 1e86 ..W..Vq.....W(..
00000a0: 20ac 35a1 bea5 15aa cc04 b1dc 0846 3453 .5..........F4S
00000b0: 0b24 3a9c 6c87 5669 c0c9 9c12 89ee 0fce .$:.l.Vi........
00000c0: e3ab 374c 3c35 6cae 411b 6b5d c429 2044 ..7L<5l.A.k].) D
00000d0: c28d d942 d61a 1d93 5563 1eb6 e2b6 2b24 ...B....Uc....+$
00000e0: e42d 3371 fc69 74bb 0474 c1dc a82e bc4f .-3q.it..t.....O
00000f0: b233 6124 526a 4d71 6dc8 73db b444 67f9 .3a$RjMqm.s..Dg.
0000100: 6240 3761 60c0 182d 826f 934a 4d31 2102 b@7a`..-.o.JM1!.
0000110: 2f94 8700 81b2 91a5 4035 01a3 1d64 b7da /[[email protected]](/cdn-cgi/l/email-protection)..
0000120: 1413 1661 42a9 c26e 24e0 6c33 2642 3141 ...aB..n$.l3&B1A
0000130: 888e 973f ee7b 385f 4fd3 f31f be35 9d6f ...?.{8_O....5.o
0000140: 27 '
```
To create the actual code from the hexdump, put it in a file and run `xxd -r hexdump > 12days.rb`. Then executing `ruby1.9.3 12.days.rb` will run the code and print the lyrics.
Note that this code requires Ruby 1.9.3 (because it uses `Zlib.inflate`) , so it won't work with Ruby 1.8.x, 1.9.1 and 1.9.2.
The uncompressed code is 425 characters long:
```
12.times{|i|puts"on-the-#{%w(first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth)[i]}-day-of-christmas
my-true-love-gave-to-me",%w(twelve-drummers-drumming eleven-pipers-piping ten-lords-a-leaping nine-ladies-dancing eight-maids-a-milking seven-swans-a-swimming six-geese-a-laying five-golden-rings four-calling-birds three-french-hens two-turtle-doves-and a-partridge-in-a-pear-tree)[~i..-1],p}
```
[Answer]
# Perl, 319/313
Idea : Uncompress and evaluate J B's Lingua::EN::Numbers solution.
First, paste this text block into the command `perl -e 'use MIME::Base64; print decode_base64 $_ while <>;' >12days.pl`. Next, run the command `perl -M5.01 12days.pl`.
```
dXNlIENvbXByZXNzOjpabGliOyRfPSd4nCWOwW7CMAyG730K
q8oBNIUOjq2QxmG3iT3AhJBpTBsRu12cgqpp776UXWx/v63/96QEH166Cev6/VjXx4kvFLWspCqb
N91/P1YHO2JM0buOrBeLdiSMNkUiSFNMgawb7qRwjSRtb3sShRZDyK724qNT6IbgSGzMSgYipewS
cM4M+kDRjPrwzIvA6N0isA+3hQM6T2odSvvEIT7XgXBcePRj/tfmtpCLE/PCzyEr68ac90a/Xk/N
dYiGV9vNZrtb/xjZy8Q7knP284LBcKM4l58CqVwnMAIOZxiu0PbRa2LUgmdIcaL8wZ2gw1zSAEyF
ORdlo9WhQnGA1RL4b70y/LJdb0rI+YZP+bD8Lf4A5ut+sic7ZXZhbCB1bmNvbXByZXNzJF87Cg==
```
The script itself takes the form `use Compress::Zlib;$_='...';eval uncompress$_;` where `...` is J B's 368 char solution after being compressed with this command and escaping a `'`.
```
perl -M5.01 -e 'use Compress::Zlib; $_ .= <> while !eof; say compress($_);' <12days_JB.pl
```
Ilmari's script complains about modifying a read only value without the extra `$_=...;` characters, but presumably he'd make this **313**. You could save several more bytes by tweaking the compression manually like Ilmari did before, maybe achieving **310 or so**, but I didn't bother.
---
**Perl, 376 (cheating off another submission)** [my original submission]
First, create a perl script called `12days.pl` containing :
```
use IO::Uncompress::Inflate qw(inflate);inflate\*DATA=>'-';
__DATA__
```
Next, pipe the output from any other submission into `12days.txt` and execute the command :
```
perl -e 'use IO::Compress::Deflate qw(deflate); deflate "-" => "-";' <12days.txt >>12days.pl
```
Vola `12days.pl` is around 376 bytes and prints the song. ;) Amusingly using rawinflate moves precisely six bytes from the data doc into the code starting from Ilmari's output.
I'd originally set about looking for a Huffman coding module directly, which isn't nearly so dishonest. Yet, sadly CPAN has no modules with English's letter entropy table, which is what you really want when compressing very short strings.
I found that `fortune -m Days\ of\ Christmas` does not work either, regrettably.
[Answer]
# VALA, 584, 574
```
void main(){int i=0;string[] d={"first","second","thrid","fourth","fifth","sixth","seventh","eighth","ninth","tenth","eleventh","twelfth"};string[] p={"Twelve drummers drumming","Eleven pipers piping","Ten lords-a-leaping","Nine ladies dancing","Eight maids-a-milking","Seven swans-a-swimming","Six geese-a-laying","Five golden rings","Four calling birds","Three french hens","Two turtle doves","A"};while(i<12){stdout.printf("On the %s day of Christmas,\nmy true love gave to me,\n%s partridge in a pear tree.\n\n",d[i],string.joinv(",\n",p[11-i:12]));p[11]="And a";i++;}}
```
No more warning at compilation.
[Answer]
# Java, 608
First post on Stack Exchange, second attempt at this problem.
```
class T{public static void main(String[]args){String Z=" partridge in a pear tree.\n";String[] B=(" day of Christmas,\nMy true love gave to me0first0second0third0fourth0fifth0sixth0seventh0eighth0ninth0tenth0eleventh0twelfth0A"+Z+"0Two turtle doves,0Three french hens,0Four calling birds,0Five golden rings,0Six geese-a-laying,0Seven swans-a-swimming,0Eight maids-a-milking,0Nine ladies dancing,0Ten lords-a-leaping,0Eleven pipers piping,0Twelve drummers drumming,").split("0");for(int i=1;i<13;i++){System.out.println("On the "+B[i]+B[0]);for(int j=i+12;j>12;j--)System.out.println(B[j]);B[13]="And a"+Z;}}}
```
Java is a little cumbersome for tasks like this, but using split helped reduce the String overhead.
[Answer]
## Java, 630 bytes
```
public class code{public static void main(String[]a){int x=0;String[]l={"A Partridge in a Pear Tree.\n","Two Turtle Doves, and","Three French Hens,","Four Calling Birds,","Five Gold Rings,","Six Geese-a-Laying,","Seven Swans-a-Swimming,","Eight Maids-a-Milking,","Nine Ladies Dancing,","Ten Lords-a-Leaping,","Eleven Pipers Piping,","Twelve Drummers Drumming,"};for(String d:new String[]{"First","Second","Third","Fourth","Fifth","Sixth","Seventh","Eighth","Ninth","Tenth","Eleventh","Twelfth"}){System.out.println("On the "+d+" day of Christmas\nMy true love sent to me");for(int i=0;i<=x;i++){System.out.println(l[x-i]);}x++;}}}
```
or as clean(ish) code:
```
public class code {
public static void main(String[] a) {
int x = 0;
String[] l = new String[]{"A Partridge in a Pear Tree.\n", "Two Turtle Doves, and", "Three French Hens,", "Four Calling Birds,", "Five Gold Rings,", "Six Geese-a-Laying,", "Seven Swans-a-Swimming,", "Eight Maids-a-Milking,", "Nine Ladies Dancing,", "Ten Lords-a-Leaping,", "Eleven Pipers Piping,", "Twelve Drummers Drumming,"};
for (String d : new String[]{"First", "Second", "Third", "Fourth", "Fifth", "Sixth", "Seventh", "Eighth", "Ninth", "Tenth", "Eleventh", "Twelfth"}) {
System.out.println("On the " + d + " day of Christmas\nMy true love sent to me");
for (int i = 0; i <= x; i++) {
System.out.println(l[x - i]);
}
x++;
}
}
}
```
Example, including validation website: <https://code.golf/12-days-of-christmas#java>
I even got rank #13, I'd really love to get some feedback here. I'm pretty new to this, so would like to know some quick wins here for the Java edition!
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 566 bytes
```
for(d=["First","Second","Third","Fourth","Fifth","Sixth","Seventh","Eighth","Ninth","Tenth","Eleventh","Twelfth"],g=["A Partridge in a Pear Tree.","Two Turtle Doves, and","Three French Hens,","Four Calling Birds,","Five Gold Rings,","Six Geese-a-Laying,","Seven Swans-a-Swimming,","Eight Maids-a-Milking,","Nine Ladies Dancing,","Ten Lords-a-Leaping,","Eleven Pipers Piping,","Twelve Drummers Drumming,"],v=[],i=0;i<12;i++){for(l=["On the "+d[i]+" day of Christmas\nMy true love sent to me"],j=i+1,k=0;j-->0;)l[++k]=g[j];v[i]=l.join("\n")}console.log(v.join("\n\n"))
```
[Try it online!](https://tio.run/##PVLBbsIwDP0VqyeqtmjblXXSNsZ2gA2N3koPETGtS5qgpJShad/O3FA4@em9F8d@SS064TaW9m2ijcTzeWvsSKZ5MCPr2iAOVrgxWjLIKrJ9nZmDbase0NbXFf1cKnaoPXqjsvLgky5EdhXUzZMdUfXni7jk255hKWxrSZYIpEHAEoWFzCKOvddAxrcqhKnp0MUghpHYADOLelPBB2oXD/PBq1CKdAkvPPOFpQ7h3SgJ38x7iueGd0SHiUjm4sR0fN0CVkehHfOrIzXNoPitYCFI9sqC1G4QeEuEuZCEDqZCbwaal4a5sd49R7G/tvEZwJL2aF1frnYOhGec2kPT9IoHXiviLs2LmNK7CT3eP0woisLf/p0UJ/eloa0QgkjmVEQBSHECs4XXypJrG@HWenGC1h4QFEcHjuOH1kCD3LZOKbqPd9y3TpKnu0mo8ijaFWmZ18Wk436pGteG9ChY6yD844/gjMKxMuWouwm9FJ7P/w "JavaScript (Node.js) – Try It Online")
[Answer]
# [Zsh](https://www.zsh.org/) `-y`, 383 bytes
```
for x y (first
two-turtle-doves second
three-french-hens third
`for a b (four call\ -birds
five golden-r\ s
six geese-a-lay
seven swans-a-swimm
eight maids-a-milk
nine ladies-danc
ten lords-a-leap
eleven pipers-pip
twelve drummers-drumm)()(<<<$a-$1ing$2\ ${${a%[et]}/%v/f}th) $b`)<<<"On the $x day of Christmas
my true love gave to me
$1a partridge in a pear tree
"&&1="$y
${1-and }"
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LVFLbsIwEFW3PsUoMogsLJSuuqCrHqAHACSGeJJY9SfyOIEUoR6kG6SqPVRPU0PZzBs9vzf283x-vXP3sy7UVGwv30Nq1NPvw0cTIhxhgkVjIieRDkGlISZLSoeRGJjq4LVIXSRSTSRfd6ojz5A6E7XYXf0I--wPQ4Qard2A2ucjFo0ZCdpgNXkVN8CCzRFaIiaFyuIkmEbywAf0nBk-GOcEmbZL4NDoK-eMfRPeeAKL2hArjb4WKbtsiDeFJewF2duk3vQUWWXIOcjm23UcnLtyt6ZclIvVaiVRycr4Vj5uQJ7kCWdrStvzcjYum3PqSpD7XZl1xavPKQnkETROEBp46aLh5JCFmyDFIT8rXDNiLimAIyErhB5jika3BMbnv-kJYxYTiWI-r54LOQl5qhR6Defifw_3dVzu-Ac)
This may be the first time I've used Zsh's anonymous functions in golf. By combining it with the `-y` option, I can conveniently split `$b` into `$1` and `$2`.
Makes use of some interesting symmetries:
* all the gifts (starting with the fourth) contain `ing`
* fi**ve** -> fi**f**th; twel**ve** -> twel**f**th (that's a mini-etymology lesson for you)
* nin**e** -> ninth; eigh**t** -> eighth
[Answer]
# Java - 1329 chars
```
class x{public static void main(String[] args){for(int i=1;i<=12;i++){System.out.print("On the ");switch(i){case 1:System.out.print("first");break;case 2:System.out.print("second");break;case 3:System.out.print("third");break;case 4:System.out.print("fourth");break;case 5:System.out.print("fifth");break;case 6:System.out.print("sixth");break;case 7:System.out.print("seventh");break;case 8:System.out.print("eighth");break;case 9:System.out.print("ninth");break;case 10:System.out.print("tenth");break;case 11:System.out.print("eleventh");break;case 12:System.out.print("twelfth");break;}System.out.println(" day of Christmas\nmy true love gave to me");switch(i){case 12:System.out.println("Twelve drummers drumming");case 11:System.out.println("Eleven pipers piping");case 10:System.out.println("Ten lords-a-leaping");case 9:System.out.println("Nine ladies dancing");case 8:System.out.println("Eight maids-a-milking");case 7:System.out.println("Seven swans-a-swimming");case 6:System.out.println("Six geese-a-laying");case 5:System.out.println("Five golden rings");case 4:System.out.println("Four calling birds");case 3:System.out.println("Three french hens");default:if(i>=2)System.out.print("Two turtle doves\nAnd a");else System.out.print("A");System.out.println(" partridge in a pear tree");break;}System.out.println();}}}
```
I'm too lazy to ungolf it, but it is here: <http://ideone.com/MU9IcP>.
[Answer]
# Rust 525 chars
Messy:
```
fn main(){for i in 1..13{println!("On the {} day of Christmas,\nmy true love gave to me\n{}\n",["first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth"][i-1],["Twelve Drummers Drumming","Eleven Pipers Piping","Ten Lords a Leaping","Nine Ladies Dancing","Eight Maids a Milking","Seven Swans a Swimming","Six Geese a Laying","Five Golden Rings","Four Calling Birds","Three French Hens","Two Turtle Doves and","a Partridge in a Pear Tree."][(12-i)..12].join("\n"));}}
```
Formatted (haha rustfmt go brrr):
```
fn main() {
for i in 1..13 {
println!(
"On the {} day of Christmas,\nmy true love gave to me\n{}\n",
[
"first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth",
"ninth", "tenth", "eleventh", "twelfth"
][i - 1],
[
"Twelve Drummers Drumming",
"Eleven Pipers Piping",
"Ten Lords a Leaping",
"Nine Ladies Dancing",
"Eight Maids a Milking",
"Seven Swans a Swimming",
"Six Geese a Laying",
"Five Golden Rings",
"Four Calling Birds",
"Three French Hens",
"Two Turtle Doves and",
"a Partridge in a Pear Tree."
][(12 - i)..12]
.join("\n")
);
}
}
```
I love how much this looks like the Python 2 and Ruby solutions (thanks for the inspiration). However, because the string split gives an iterator, I think the `.split('^').collect::<Vec<str>>()` I'd have to write would actually remove all the benefits of having `^`-delimited strings instead of literal lists/arrays. (For the first substitution, I guess there's also `.split('^').nth(i-1).unwrap()`, but that's also a mouthful.)
] |
[Question]
[
Title misspelled on purpose. Read more to find out why.
Your task: given a delimited string or list including the characters `A,B,C,D`, output the indexes of all the adjacent equal characters. Output can be multiple strings/integers on multiple lines, a list/array, or a delimited string.
All output should be in a list or string, or multiple printed lines. Each printed line, if there are multiple, should only contain 1 string or number. Trailing whatevers are okay.
Standard methods of input/output. Standard loopholes apply.
For example, the input `'ABCDDCBA'` should output `3,4` or `4,5`, depending on whether it is 0- to 1- indexed, because those numbers are the indexes of `D` and the `D` next to it.
**Test cases:**
Test cases have input given as a single string, and output as a `,`-delimited string. Outputs are 0-indexed, add 1 to every outputted item to get it to be 1-indexed.
```
Input: 'ABCDCABCD'
Output: ''
Input: 'AABBCCDD'
Output: '0,1,2,3,4,5,6,7'
Input: 'ABCDDDCBA'
Output: '3,4,5'
Input: 'ABBCDD'
Output: '1,2,4,5'
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins!
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~33~~ ~~29~~ 23 bytes
*Saved 6 bytes thanks to Martin Ender*
```
T`L`:`(.)\1+
:
$.`¶
T`L
```
Outputs a linefeed-separated list of indices.
[Try it online!](https://tio.run/nexus/retina#@x@S4JNglaChpxljqM1lxaWil3BoGxdQ8P9/RydnZ2cnFxdXAA "Retina – TIO Nexus")
**Explanation**
```
T`L`:`(.)\1+
```
Transliterate runs of the same character into colons, to mark positions where there are duplicate characters.
```
:
$.`¶
```
Then replace each colon with the length of the text before it, followed by a linefeed.
```
T`L
```
Finally, delete any remaining letters.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
JṁŒgḊÐf
```
1-based; returns a list of lists of the runs of indexes [as allowed](https://codegolf.stackexchange.com/questions/116113/wherre-are-the-adjacent-characters-in-the-title-3-4/116146#comment283578_116113) by the OP.
**[Try it online!](https://tio.run/nexus/jelly#@@/1cGfj0UnpD3d0HZ6Q9v//f3VHRycnZ2cXF3UA "Jelly – TIO Nexus")**
### How?
```
JṁŒgḊÐf - Main link: char-list s e.g. 'DCCABBBACCCD' (which is a python interpreted input of ['D','C','C','A','B','B','B','A','C','C','C','D'])
J - range(length(s)) [1,2,3,4,5,6,7,8,9,10,11,12]
Œg - group-runs(s) [['D'],['C','C'],['A'],['B','B','B'],['A'],['C','C','C'],['D']]
ṁ - mould left like right [[1],[2,3],[4],[5,6,7],[8],[9,10,11],[12]]
Ðf - filter keep items that would be truthy (empty is not truthy) after applying:
Ḋ - dequeue (x[1:]) [ [2,3], [5,6,7], [9,10,11] ]
```
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~57~~ 46 bytes
```
{({}[({})]<(([]<>)[()])>){(<{}{}{}>)}{}<>}<>
```
Includes +2 for `-ar`
Uses 0-based indexing.
[Try it online!](https://tio.run/nexus/brain-flak#@1@tUV0bDcSasTYaGtGxNnaa0RqasZp2mtUaNtW1IGinCSRs7IDo/39HRydnl/@6iUUA "Brain-Flak – TIO Nexus")
```
# While true
{
# Subtract the second value on the stack from the first
({}[({})]
# Push the height of this stack (the main stack) on the other stack
<(([]<>)
# Push the height of the main stack - 1
[()])>
# Push the difference that we calculated a second ago
)
# If they weren't the same character
{
# Pop the difference and the two stack heights
(<{}{}{}>)
# End if
}
# Pop the difference (or the 0 to get out of the if)
{}
# Switch back to the main stack and end while
<>}
# Switch to the stack with the indexes and implicitly print
<>
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~8~~ 7 bytes
```
d~ftQvu
```
Output is 1-based.
[Try it online!](https://tio.run/nexus/matl#@59Sl1YSWFb6/7@6o5Ozi4uLs5OjOgA "MATL – TIO Nexus")
### Explanation with example
Consider input `'ABCDDDCBA'`.
```
d % Implicitly input a string. Consecutive differences
% STACK: [1 1 1 0 0 -1 -1 -1]
~ % Negate. Each character that equals the next gives true
% STACK: [0 0 0 1 1 0 0 0]
f % Find: (1-based) indices of true elements
% STACK: [4 5]
tQ % Duplicate, add 1 element-wise
% STACK: [4 5], [5 6]
v % Concatenate vertically
% STACK: [4 5; 5 6]
u % Unique (remove duplicates). This doesn't automatically sort, but the
% output will be sorted because the input, read in column-major order, is
% Implicitly display
% STACK: [4; 5; 6]
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 19 bytes
```
l⟦k:?z{sĊtᵐ=∧Ċ∋h}ᶠd
```
[Try it online!](https://tio.run/nexus/brachylog2#ASwA0///bOKfpms6P3p7c8SKdOG1kD3iiKfEiuKIi2h94bagZP//IkFCQkNERCL/Wg "Brachylog – TIO Nexus")
### Explanation
Brachylog is usually terrible with indexes, which again shows here.
If `false.` is an acceptable output in cases where there are no adjacent characters, then this would be 1 byte less by replacing `ᶠd` by `ᵘ`.
```
l⟦k The list [0, …, length(Input) - 1]
:?z Zip the Input with this list
{ }ᶠd Find with no duplicates:
∧Ċ∋h The heads of each element of Ċ = [A, B] (i.e. the indexes)…
Ċtᵐ= …where the tails of both A and B are equal (i.e. the letters)…
sĊ …and where Ċ = [A, B] is a substring of the Input
```
[Answer]
## Mathematica, 32 bytes
```
Union@@StringPosition[#,x_~~x_]&
```
Pure function which returns the 1-indexed positions of characters adjacent to an identical character.
## Explanation:
`StringPosition["string","sub"]` gives a list of the starting and ending character positions at which `"sub"` appears as a substring of `"string"`. `x_~~x_` is a `StringExpression` which matches two adjacent, identical characters. For example, `StringPosition["ABCDDDCBA",x_~~x_]` gives `{{4, 5}, {5, 6}}`. Applying `Union` joins the lists, sorts, and deletes duplicates.
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~69, 59~~, 56 bytes
```
{({}[({})]<(())>){((<{}{}>))}{}{([{}]([]<>))(<>)}{}}<>
```
[Try it online!](https://tio.run/nexus/brain-flak#DYixDcAwDMPekYZ@YARI4i8MD32hq@DbXQ8kQLagioFpALkowFSqRY6FUCUibRqjeWWre5/r7vfsft7vBw "Brain-Flak – TIO Nexus")
+2 bytes for the `-ar` flags which enables ASCII input and reverses the stack.
Uses 0-based indexing. Saved 10 bytes by [reducing my push-pop redundancy](https://codegolf.stackexchange.com/a/95404/31716). Saved another 4 bytes by switching from 1 to 0-based indexing.
This is pretty much the only string based challenge that brain-flak is good at. That's because brain-flak is great at comparing consecutive characters, even though it's horrendous at string processing in general. Here is readable version of the code with comments to explain how it works:
```
#While True
{
#Determine if top two are equal
({}[({})]<(())>){((<{}{}>))}{}
#If so
{
#Pop the one, and negate it's value (giving us -1)
([{}]
#Push stack height over
([]<>)
#Then push stack height plus the negated pop (-1)
)
#Push a zero back onto the main stack
(<>)
#Endwhile
}
#Pop the zero
{}
#Endwhile
}
#Toggle back, implicitly display
<>
```
[Answer]
# Cubix, ~~37 32 31 29~~ 28 bytes
*Thanks to ETHProductions for pointing me in the direction of a three-byte saving*
```
$uO@(;Usoi?-!w>;.....S_o\;#O
```
Try it [here](https://ethproductions.github.io/cubix/?code=JHVPQCg7VXNvaT8tIXc+Oy4uLi4uU19vXDsjTw==&input=QUJDQ0Q=)! Note that the output indices are 1-based and not in ascending order.
### Expanded:
```
$ u O
@ ) ;
U s o
i ? - ! w > ; . . . . .
S _ o \ ; # O . . . . .
. . . . . . . . . . . .
. . .
. . .
. . .
```
# Explanation
This works by reading the input character by character. To compare two characters, we simply subtract the their character codes, and if the result is 0, we print the current length of the stack, a space, the current length of the stack - 1 and another space. Then we clean up the stack a bit, and we start with the read loop again. If the end of the input string is reached, the program stops.
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 35 bytes
```
@(s)unique([x=find(~diff(+s)),x+1])
```
[Try it online!](https://tio.run/nexus/octave#@@@gUaxZmpdZWJqqEV1hm5aZl6JRl5KZlqahXaypqVOhbRir@T9NwVYhMa/YmitNQ93RydnFGUSoa@oogPiOTk7Ozi5wLlDGxcXZyVFd8z8A "Octave – TIO Nexus")
Similar to my [MATL answer](https://codegolf.stackexchange.com/a/116123/36398). Here `unique` automatically sorts . The input to `diff` must be converted to `double`, which is done by the unary `+`.
[Answer]
## [C#](http://csharppad.com/gist/bb506264460c250ab6373c7781c4fb87), 115 bytes
---
**Golfed**
```
i=>{var o="";for(int x=1,l=i.Length;x<=l;x++)o+=(x<l&&i[x]==i[x-1])||(x>1&&i[x-1]==i[x-2])?(x-1)+" ":"";return o;};
```
---
**Ungolfed**
```
i => {
var o = "";
for( int x = 1, l = i.Length; x <= l; x++ )
o += ( x < l && i[ x ] == i[ x - 1 ] ) || ( x > 1 && i[ x - 1 ] == i[ x - 2 ] )
? ( x - 1 ) + " "
: "";
return o;
};
```
---
**Ungolfed readable**
```
i => {
// List of positions
var o = "";
// Cycle through the string
for( int x = 1, l = i.Length; x <= l; x++ )
// Check if 'x' is below the string length
// and if the current and previous char are the same...
// ... or if 'x' is beyong the string length
// and the 2 previous chars are the same.
o += ( x < l && i[ x ] == i[ x - 1 ] ) || ( x > 1 && i[ x - 1 ] == i[ x - 2 ] )
// If true, add the index to the list of positions...
? ( x - 1 ) + " "
// ...otherwise add nothing
: "";
// Return the list of positions.
return o;
};
```
---
**Full code**
```
using System;
using System.Collections.Generic;
namespace Namespace {
class Program {
static void Main( String[] args ) {
Func<String, String> f = i => {
// List of positions
var o = "";
// Cycle through the string
for( int x = 1, l = i.Length; x <= l; x++ )
// Check if 'x' is below the string length
// and if the current and previous char are the same...
// ... or if 'x' is beyong the string length
// and the 2 previous chars are the same.
o += ( x < l && i[ x ] == i[ x - 1 ] ) || ( x > 1 && i[ x - 1 ] == i[ x - 2 ] )
// If true, add the index to the list of positions...
? ( x - 1 ) + " "
// ...otherwise add nothing
: "";
// Return the list of positions.
return o;
};
List<String>
testCases = new List<String>() {
"ABCDCABCD",
"AABBCCDD",
"ABCDDDCBA",
"",
"A",
"AA",
"AAA",
};
foreach( String testCase in testCases ) {
Console.WriteLine( $"{testCase}\n{f( testCase )}\n" );
}
Console.ReadLine();
}
}
}
```
---
**Releases**
* **v1.0** - `115 bytes` - Initial solution.
---
**Notes**
Nothing to add
[Answer]
# C, 75 bytes
```
i;f(char*s){for(i=0;*s;++s,++i)if(s[1]==*s|(i&&s[-1]==*s))printf("%d ",i);}
```
Uses spaces as delimiters. (A trailing comma doesn't look too good.)
[Try it online!](https://tio.run/nexus/c-gcc#bYu9CsMwEIP3PIUxJNzZKbSz8eCftwgdQovpDU2DL53SPLvjUOhUDULShwqZBLfHmBXjml4ZyJ6NYqM191oTUgIeLldrFX@Auo6H07chzpmmJYFs70L2hGYrtYvnSBNgszaiqlLnQwyHSTTze2GQNfyg8z6E@J/VT4zBu2Pbyg4)
[Answer]
# JavaScript, 52 bytes
Thanks @Neil for golfing off 1 byte
```
x=>x.map((a,i)=>a==x[++i-2]|a==x[i]&&i).filter(a=>a)
```
Receives input as a 0-indexed array of characters
Returns output as a 1-indexed array
## Explanation
```
x.map()
```
For each character in the string
```
(a,i)=>(a==x[++i-2]|a==x[i])*i
```
If it is equal to the previous character or the next character, return the index+1 otherwise do not return (leaves undefined in the array)
```
.filter(a=>a)
```
Remove all undefined elements from the resulting array
[Try it online!](https://tio.run/nexus/javascript-node#TU3LDsIgEDzrZ/S0ay2J3rc/0pCwsVDWYCHCgYP/jqQXndNM5uWoVZqrenEC4KsgzcBEdRlHme76c3DReBFUTkKx727PjO0R9xyDVSFuAIUcJBq4I6@rc3bz3ktXg8opSDEGUT2j7OZk8PxfLcdzn0wLTzf9S7Uv)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
=2\T’œ|$
```
[Try it online!](https://tio.run/nexus/jelly#@29rFBPyqGHm0ck1Kv8Ptz9qWuP@/7@6o5OzizOIUNdRUHd0dHJydnaBsIFiLi7OTo7qAA "Jelly – TIO Nexus")
[Answer]
# k, 18 bytes
```
{?,/-1 0+/:&:=':x}
```
Examples:
```
k){?,/-1 0+/:&:=':x}"AABCDDDCBAA"
0 1 4 5 6 9 10
k){?,/-1 0+/:&:=':x}"ABCDCBA"
()
```
Translation to `q` is easier to understand:
```
{distinct raze -1 0+/:where not differ x}
```
[Answer]
# Python 2, ~~55~~ 54 bytes
```
m=j=0
for i in input():
if m==i:print~-j,j,
j+=1;m=i
```
[Try it Online!](https://tio.run/nexus/python2#@59rm2VrwJWWX6SQqZCZB0QFpSUamlZcCplpCrm2tplWBUWZeSV1ulk6WTpcClnatobWubaZ//@rOzo6Ojm7uKgDAA)
Outputs indices separated by spaces (note that this displays some indices twice as allowed by OP)
[Answer]
# C#, 89 Bytes
```
using System.Linq;s=>string.Join("",s.Skip(1).Select((a,i)=>a==s[i]?i+" "+(i+1)+" ":""));
```
If there are three or more characters in a row the indexes are repeated. Which @Comrade SparklePony allowed in the comments.
### Ungolfed full program:
```
using System;
using System.Collections.Generic;
using System.Linq;
namespace Namespace
{
class Class1
{
static void Main(string[] args)
{
Func<string, string> f2 =
s => string.Join("" , //Combine the results into one string
s.Skip(1) //Start with the second element
.Select(
(a, i) => // 'a' is the current element, 'i' is the index of the element in the result of 'Skip'
a == s[i] ? // therefore 's[i]' is the previous element; compare it with the current one
i + " " + (i + 1) + " " : //If true, return the indexes
"" //Otherwise an empty string
));
var tests = new string [] {
"ABCDCABCD",
"AABBCCDD",
"ABCDDDCBA",
"ABBCDD"
};
foreach (var test in tests)
{
Console.WriteLine(test);
Console.WriteLine(string.Join("", f2(test)));
Console.WriteLine();
}
Console.ReadLine();
}
}
}
```
[Answer]
## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 42 bytes
```
;[2,_lA||~mid$(A,a-1,1)=mid$(A,a,1)|?a-1,a
```
Sample output:
```
Command line: AADCDBBD
1 2
6 7
```
Explanation:
```
; Get A$ from the cmd line
[2, | FOR a% = 2 TO
_lA| the length of A$
~mid$(A,a-1,1) IF the character at index a%
=mid$(A,a,1) equals the char at index a%-1
| THEN
?a-1,a PRINT both indexes, tab-separated
Any further doubles are printed on a separate line
The IF and FOR are closed implicitly
```
---
EDIT: QBIC now has Substring! This challenge can now be solved in 32 bytes:
```
;[2,_lA||~_sA,a-1|=_sA,a||?a-1,a
```
Where:
```
_s This is the substring function; it takes 1, 2 or 3 arguments.
Arguments are comma-seperated, the list is delimited with |
In this answer we see Substring take 2 arguments:
A, The string to take from
a| Starting position (note:uppercase represents strings, lowercase is for nums)
Any omitted argument (in this case 'length to take') is set to 1.
```
[Answer]
# [Go](https://go.dev), 116 bytes
```
func f(s string)map[int]int{L,l:=make(map[int]int),'0'
for i,r:=range s{if r==l{L[i-1]=i;L[i]=i}else{l=r}}
return L}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TY89asQwEIV7nWIQLGuDNiRdcFDAP6WL9I4JQkhGrCUbSU4jVOcQaUwgh8hRcpvI9hYpZubNFO998_k1TOvPzPiVDQI0UwYpPU_W32GpPf5evLw8_nq5GA4yc-C8VWbINZs7ZXyfKrRkLKhmV5H9u-bkfH9GcrKgiC2oZSbZu6AkWErH0Hbq8tBT9ZREGlGMToSR2hiRFX6xBtp4y_7YszeyLIeAOHPCQUGh6w-WgMuqbuqtYYLLsqrqutllujRNXZW73hYcd6I3wjeDg-nwC-gleXmZ4ZMD-gyn91eDCXCSnuZ5jiK64azrMf8A)
Returns a map where the keys are the 0-based indexes of adjacent characters.
### [Go](https://go.dev), 141 bytes
```
func f(s string)(O[]int){L,l:=make(map[int]int),'0'
for i,r:=range s{if r==l{L[i-1]=i;L[i]=i}else{l=r}}
for k:=range L{O=append(O,k)}
return}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NZDNSsUwEIX3eYoQuNwUckV3UonQn2Wh7muREJMS2qYlSd2ErF35BG6K4EP4KL6NaXvdzJw5MGc-5vOrm9afmfGedQKOTGmgxnky7gbJ0aHvxcnL_e-HXDSHEltonVG6S3DdtEq7xFdkSOnIeoFHNjfR2m1yvj0DORmoiEmpYTpmW68kNJQOvmrU5a6l6iGK2IIYrPADNSHsO_3_RuVryuZZ6Fdckz4JwAi3GB2uUO871IaME-gBZ1ZYmFLYtAekR1lelMVWEEFZludFUe4yOmVZ5NmutwEdl18I3wKO60eeB08xy0mMThbSR3h6e9aIQE7iN3iSgACuOOt69D8)
Returns a slice that is the 0-based indexes of the adjacent characters.
[Answer]
# [Perl 5](https://www.perl.org/), 37 bytes
35 bytes of code + `pl` flags.
```
s/(?<=(.))\1|(.)(?=\2)/print pos/ge
```
[Try it online!](https://tio.run/nexus/perl5#U1YsSC3KUdDNy/lfrK9hb2OroaepGWNYA6Q07G1jjDT1C4oy80oUCvKL9dNT//93dHJ2cXFxdnIEAA "Perl 5 – TIO Nexus")
`(?<=(.))\1|(.)(?=\2)` will match either between two repeted characters (`(?<=(.))\1`), or before a character that is repeated (`(.)(?=\2)`).
Then, `print pos` prints the position of the match. (`pos` contains the index of the current match when used in a regex with `/g` modifier).
[Answer]
# [Perl 6](https://perl6.org), ~~66~~ 57 bytes
```
*.comb.rotor(2=>-1).kv.flatmap({($^a,$a+1)xx[eq] $^b[0,1]}).squish
```
[Try it](https://tio.run/nexus/perl6#TZDfboIwFIfv@xTnAmcrpZluc4kokT@Xu9wd4IJQMzIQtMVoDHuhvcVejLXNXHZz2vR8/fI7pxMcTnOWu6i@wF3eFBxWw4TlTb1lx0Y2Rzxbec6UsI8T21WZrLMWX7G1yaiV2VNyPsf8kIK12cb3dJr2hIlDV4r3wfjWkgsJK6jKPReYMPV5cUUA9ULoA8Balvu2k55i8DL2gzBKPZuY1tjxxuYSr5f83PJc8kJzSWGnExiNYEx1v3dV@bx5qP399Q9nL6WQ1HpDPerUnK8qjYvaKtuDbaK5aNccf1M6HuDEWGhyE9Ck4CInoMOWwik4b6sL6CVhQxIKfyhoFPWDHiLURRmR7wdBGEYRaL1aEJ3RB/pIn@icPiMNRVEY@Lppnn8A "Perl 6 – TIO Nexus")
```
{m:ex/[(.)<($0|(.))>$0]{make $/.from}/».ast.sort.squish}
```
[Try it](https://tio.run/nexus/perl6#TZDLboMwEEX3/opZkALFmPSVSkBQeCy77A5QhcBRUXkVQ5WI0h/qJ3SXH6O221TdzFhzj@7c8cgovG1I7qD6CBd5W1DYLlNt04MVa0R3NWX9zrvuKet0qrMXCopF9n1bz9bpi2RsIKzteXkdS/Y8L9JmN1A2wBaqsqFM00mddfaEAGqbiQaguGXTjYPHGc2N/SCMUs/QpaSaniof8c6lh47mAy0ElxRGegmrFahY6LPDy8fZBxunz384eSjZgJUnNKORn/fI0zioq7IGDBnNQfu2/01peqAl0gUnZwOcFJTlOoiwJTMLSrvqCOJvNEnqPwvgjwfBo3kRl4SicFvk@0EQhlEEYscaX@FrfINv8R3e4HskoCgKA1@IcvwN "Perl 6 – TIO Nexus")
[Answer]
# PHP, 100 Bytes
```
for(;$i<strlen($s=$argn);$i++)$s[$i]==$s[$i+1]||$s[$i]==$s[$i-1]&&$i?$r[$i]=+$i:0;echo join(",",$r);
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 51+1 = 52 bytes
Uses the `-n` flag.
```
i=0;d=[];gsub(/./){$&==$_[i+=1]?d+=[i-1,i]:0};p d&d
```
[Try it online!](https://tio.run/nexus/ruby#U1YsKk2qVNDN@59pa2CdYhsda51eXJqkoa@nr1mtomZrqxIfnaltaxhrn6JtG52pa6iTGWtlUGtdoJCilvL/v6OTs4uLi7OToyMA "Ruby – TIO Nexus")
[Answer]
## Batch, 139 bytes
```
@set/ps=
@set/ai=c=0
:l
@if %s:~,1%==%s:~1,1% set c=2
@if %c% gtr 0 echo %i%
@set/ai+=1,c-=1
@if not "%s:~1%"=="" set s=%s:~1%&goto l
```
Takes input on STDIN. Works by keeping track of how many numbers to print in the `c` variable, which is reset to 2 when a pair is detected. Note: At a cost of 6 bytes, could be hardened to work with most ASCII characters and not just `ABCD`.
[Answer]
# k, 14 bytes
This is a function, it takes in a string, and returns a list of indices.
```
&{x|1_x,0}@=':
```
Explanation:
```
=': /compare each letter to the previous, return binary list
{ }@
1_x,0 /shift left
x| /combine shifted and unshifted with binary or
& /get indices of 1s
```
[Try it online!](http://johnearnest.github.io/ok/?run=%28%26%7Bx%7C1_x%2C0%7D%40%3D%27%3A%29%27%28%22ABCDCABCD%22%3B%22AABBCCDD%22%3B%22ABCDDDCBA%22%3B%22ABBCDD%22%29)
How to use:
```
&{x|1_x,0}@=':"STRINGGOESHERE"
```
[Answer]
# [Julia 1.3](https://julialang.org), 23 bytes
```
!x=findall(r"(.)\1+",x)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700qzQnM3HBgqWlJWm6FtsVK2zTMvNSEnNyNIqUNPQ0Ywy1lXQqNCGyN3XT8osUMhUy8xSKUhNTcjLzUos1NLkUgKCgKDOvJCdPI1PB1k5BMVOTKzUvBaJpwU1lRydnF2cQweXo6OTk7OwCZAB5Li7OTo5cIBEXF4haAA)
in Julia 1.3+, there is a function that does the job for me. The output is a list of ranges, which are equivalent to lists (`4:6 == [4,5,6]`)
[+6 bytes if this format is not accepted](https://ato.pxeger.com/run?1=m700qzQnM3HBgqWlJWm6FnsVK2yj0zLzUhJzcjSKlDT0NGMMtZV0KjT19PSsYyFqbuqm5RcpZCpk5ikUpSam5GTmpRZraHIpAEFBUWZeSU6eRqaCrZ2CYqYmV2peCkTTgpvKjk7OLs4ggsvR0cnJ2dkFyADyXFycnRy5QCIuLhC1AA)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Input as a character array, output as a 2D array.
```
ò¦ m£T°ÃlÉ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=cQ&code=8qYgbaNUsMNsyQ&input=IkFCQkNERCIKLVE)
```
ò¦ m£T°ÃlÉ :Implicit input of array U
ò :Partition on
¦ : Inequality
m :Map
£ : Map
T° : Postfix increment T, initially 0
à :End map
l :Filter by length
É : Minus 1 (0 is falsey)
```
[Answer]
# PHP, 70 bytes
```
for(;a&$c=$argn[$i];)$i++&&$argn[$i-2]==$c||$argn[$i]==$c?print$i._:0;
```
takes input from STDIN; run with `-R`.
[Answer]
# [JavaScript (V8)](https://v8.dev/), 64 bytes
```
x=>x.replace(/(.)\1+/g,f=(s,i,p)=>print(p)+s[i=-~i]&&f(s,i,1+p))
```
[Try it online!](https://tio.run/##HcnBCkBAEADQuw9hpl3kpjQKm5/AYRMaSdOu5OTXV3nXt9vb@tmxXOldhp7CQ/WTuUUOOy@QQ4ZjofJNrwResxakWhyfFwgqPzClL09xvP5ZKEEMVdRD0rSdMaZrmwSr8AE "JavaScript (V8) – Try It Online")
Not that short but fun
# [JavaScript (Node.js)](https://nodejs.org), 45 bytes "by" fəˈnɛtɪk
```
x=>x.flatMap((a,i)=>a==x[++i-2]|a==x[i]?i:[])
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/e9m@7/C1q5CLy0nscQ3sUBDI1EnU9PWLtHWtiJaWztT1yi2BszOjLXPtIqO1fxvzZWcn1ecn5Oql5OfruGmEa2np6fu6OTs4uLi7OSoHqupaf0fAA "JavaScript (Node.js) – Try It Online")
[Answer]
# [><>](https://esolangs.org/wiki/Fish), ~~48~~ 47 bytes
```
0ril3(?;3[$::}@=r$:@e1.
=r{+]?\{1+}20.
}oan:{/1
```
[Try it online!](https://tio.run/##S8sszvj/36AoM8dYw97aOFrFyqrWwbZIxcoh1VCPy7aoWjvWPqbaULvWyECPqzY/Mc@qWt/w////usWOTs4uLi7OTo4A "><> – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes
```
₌ẏĠ•~Ḣ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigozhuo/EoOKAon7huKIiLCIiLCJBQkJCQkNERCJd)
Similar stuff to the other answers but independently derived.
## Explained
```
₌ẏĠ•~Ḣ
₌ẏĠ # range(0, len(input)) and group_consecutive(input)
• # mold the length range to the shape of the consecutive groups
~Ḣ # keep only lists where there's more than one item
```
] |
[Question]
[
Given a list of integers, output a list where the \$ i \$th element of the list equals the first number in the input list which is \$ \ge i \$, until there are no such numbers.
For example, if the input is:
```
2 3 5 7 11
```
then we "expand" the sequence out to show where the gaps are:
```
_ 2 3 _ 5 _ 7 _ _ __ 11 # input
1 4 6 8 9 10 # gaps
```
Now we fill in the blanks with the next number that is in the sequence in each case:
```
2 2 3 5 5 7 7 11 11 11 11
1 4 6 8 9 10
```
This is the output.
## Test cases
```
[1] -> [1]
[3] -> [3, 3, 3]
[1, 2, 3] -> [1, 2, 3]
[1, 3, 4, 9] -> [1, 3, 3, 4, 9, 9, 9, 9, 9]
[2, 3, 5, 7, 11] -> [2, 2, 3, 5, 5, 7, 7, 11, 11, 11, 11]
```
## Rules
* You may assume the input list is non-empty, strictly increasing, and only contains positive integers
* You may use any [standard I/O method](https://codegolf.meta.stackexchange.com/q/2447)
* [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061) are forbidden
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins!
[Answer]
# [R](https://www.r-project.org/), 30 bytes
Or **[R](https://www.r-project.org/)>=4.1, 23 bytes** by replacing the word `function` with a `\`.
```
function(x)rep(x,diff(c(0,x)))
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jQrMotUCjQiclMy1NI1nDQKdCU1PzP4hpqKmprIAKdO0Uog1juUCyxthljXUUQAiixlBHwQjIQVYJNgEiDFcD1GCio2AJVwZVYwyXQUYQXUZgOVMdBXMdBUOIQ0G6jCAmg2UgkmB5ZBz7HwA "R – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 37 bytes (@Jitse)
```
f=lambda l=[],*L:l and[l]*l+f(*L)[l:]
```
[Try it online!](https://tio.run/##JYxBCsMgEEWvMsto/8aaUirkBt5gmIUhSANTI5JNTm@ELj7vvc2v1/k9iu89L5p@65ZIFxbYGJRS2VjF6iNPNhrWID0fjZT2QsxOwH7M4Yk/PWZ8ho3GC284JxKotr2c07hQY/oN "Python 3 – Try It Online")
### Original [Python 3](https://docs.python.org/3/), 38 bytes
```
f=lambda l,*L:(l,)*l+(L and f(*L)[l:])
```
[Try it online!](https://tio.run/##JYxBCsMgEEWvMkvH/o01pUTIDbyBuLCIRJhqCNnk9Fbo4vPe2/zjvvbe7Bhlk/T95EQC7Z0SsJaH8pRapqK05yAu8ij9JKHaKAQTEeycwRN/WixYp83GC28YE6Oj46ztUvNDmMcP "Python 3 – Try It Online")
Takes the splatted input and returns a tuple.
### How?
This is entirely based on the observation that the first original number `k`, say, will occur `k` times in the output. Working back to front we can treat each number `k[n]` as if it were the first and at the next iteration `n-1` replace the `k[n-1]` excess copies of `k[n]` with copies of `k[n-1]`.
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/index.html), 5 bytes
```
+`⁼/⊢
```
[Try it at BQN online REPL](https://mlochbaum.github.io/BQN/try.html#code=RmlsbGludGhlbmV4dCDihpAgK2Digbwv4oqiCkZpbGxpbnRoZW5leHTCqCDin6gg4p+oMeKfqSwg4p+oM+KfqSwg4p+oMSwyLDPin6ksIOKfqDEsMyw0LDnin6ksIOKfqDIsMyw1LDcsMTHin6kg4p+p)
[BQN](https://mlochbaum.github.io/BQN/index.html) has a lovely 'undo' modifier (`⁼`) which calculates the inverse of any function, where this is possible.
Here we use it with cumulative sum (`+`` ) to get the cumulative differences starting from zero.
After that we just need to replicate (`/`) the input values (`⊢`) this number of times.
```
/ # Replicate the elements of
⊢ # the right-hand argument
# by
⁼ # undo the
+` # cumulative sum of
# the right-hand argument
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 36 bytes
```
->l{x=0;l.flat_map{|a|[a]*(-x+x=a)}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6nusLWwDpHLy0nsSQ@N7GguiaxJjoxVktDt0K7wjZRs7b2f4FCWnS0sY6pjmVs7H8A "Ruby – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes
```
ẋ∩vg
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuoviiKl2ZyIsIiIsIlsyLCAzLCA1LCA3XSJd)
```
ẋ # Repeat the numbers by themselves
# [[2, 2], [3, 3, 3], [5, 5, 5, 5, 5]]
∩ # Transpose
# [[2, 3, 5], [2, 3, 5], [3, 5], [5], [5]]
vg # Get the minimum of each
```
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 35 bytes
```
a->vector(a[#a],n,[m|m<-a,m>=n][1])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWN5UTde3KUpNL8os0EqOVE2N18nSic2tybXQTdXLtbPNiow1jNaFKwxMLCnIqNRIVdO0UCooy80qATCUQR0khTSNRU1NHIRqoGkgagwhDHQUjHQUY01hHwURHwRLEMwLzTHUUzHUUDA1jYcYvWAChAQ)
```
a-> Define a function with argument `a`
vector( ) that returns a vector
a[#a], whose length is the last term of `a`
n, and the `n`th term
[m|m<-a, ][1] is the first `m` in `a` such that
m>=n `m` is larger than `n`.
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 40 bytes
```
a=>a.map(g=n=>n>o.push(n)&&g(n),o=[])&&o
```
[Try it online!](https://tio.run/##bY3RCsIwDEXf/Yo8jRbqRjtFRNofGX0oc5vKbIpTf792m0rpFpIQ7j3c3MzbDPXj6p5bi@fGt9IbqUx@N4500kplFebuNVyIpVnWhc1QVjrc6Gu0A/ZN3mNHWlJxDXFReoKigCBvErBcB0sGYy9wzkCMepr7lVfwELNjcNQJXv6duBcBYsL2DA4MONe/ADH/m5zZnPx4tP8A "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 43 bytes
```
f=lambda n,i=2:n and[n[0]]+f(n[[i]>n:],i+1)
```
[Try it online!](https://tio.run/##JYcxCsMwDAC/otEmGqo4oa0h/YjQ4BJMBa5iTJa83jV0OO6uXufnsPCorfe8lfR97wkMdZujQbKdjW8iU3bGrPKyKKgT@Z6PBgXUgJkEOQwIZ/w74ILPUeNxxTsSiUSoTe102RXv@w8 "Python 3.8 (pre-release) – Try It Online")
Thanks @dingledooper for -2 bytes.
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 6 bytes
```
(-':)#
```
[Try it online!](https://ngn.bitbucket.io/k#eJxLs9LQVbfSVObiSlPX0DFUQAVcCjrGGEIahtYKRtYKxppoYsbWCibWCpaacDEjsJiptYK5tYKhoaYmAG7pEFk=)
## Explanation
```
(-':)#
(-':) deltas
# replicate
```
[Answer]
# [Factor](https://factorcode.org/), 44 bytes
```
[ dup last iota [ '[ _ > ] find ] with map ]
```
[Try it online!](https://tio.run/##VU1NC4JAFLz7K@bWLTCLqKBrdOkSnRaJx/qkRV233Sch4m/fFEJoDvPBMExJWlofH/fr7XJExd5yjcDvjq3mgNL3aEhecJ5FeueNFZySZEgwYUCK8eeyxaXY/KUMWxyWPHc77JHO0zEqFJ1DTUFgWiEorBSeOCNHaWwxycdM9w055HHmIKSrNXTN5OMX "Factor – Try It Online")
Let \$L\$ be the last element of the input. Then map \$[0..L)\$ to the first element of the input that is greater.
[Answer]
# APL+WIN, 13 bytes
Prompts for input
```
(-2-/0,v)/v←⎕
```
[Try it online! Thanks to Dyalog APL Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3tv4auka6@gU6Zpn4ZUBAo@R8ozPU/jcuQK43LGIgNFYwUILSxgomCJZAF5CuYKpgrGBoCAA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Halfwit](https://github.com/chunkybanana/halfwit/), 7.5 bytes
```
MZ;RZMR[$
```
[Try It Online!](https://dso.surge.sh/#@WyJoYWxmd2l0IixudWxsLCJNWjtSWk1SWyQiLCIiLCJbWzJuLCAzbiwgNW4sIDduXV0iLCJjcCJd)
I think I made it too minimalistic...
[](https://i.stack.imgur.com/0d7Zt.png)
## Explanation
```
M ; # Map over each value...
Z # Fill an array of length (itself) with (itself)
R # Reduce by (taking two lists)
Z # Zip
M # For each pair...
R # Reduce by...
[ # If the first is truthy (nonzero)...
$ # return it, otherwise return the other value
```
[Answer]
# [Julia 1.0](http://julialang.org/), 29 bytes
```
!x=[fill.(x,diff([0;x]))...;]
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/X7HCNjotMydHT6NCJyUzLU0j2sC6IlZTU09Pzzr2f0FRZl5JTp6GYrSRjoKxjoKpjoK5joKhYazmfwA "Julia 1.0 – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 6 bytes
```
0yhdY"
```
[Try it online!](https://tio.run/##y00syfmfkKlQEuWnYK9QoacQqxDh8d@gMiMlUul/hItCSOz/aMNYrmhjIDbUUTDSUYCyjHUUTHQULIEcIzDHVEfBXEfBEKjWQN8AAA "MATL – Try It Online")
Take a `diff` and `repelem` the input that many times (same as @pajonk's R answer among others).
I thought this sounded ideal for an `interp1` based answer, but that comes out to 16 bytes: `0ihttX>:IG1)5$Yn` [Try it online!](https://tio.run/##y00syfmfkKlQEuWnYK9QoacQqxDhoVDx38Ajo6Qkws7K08NQ01QlMu9/hItCSOz/aMNYrmhjIDbUUTDSUYCyjHUUTHQULIEcIzDHVEfBXEfBEKjWQN8AAA "MATL – Try It Online")
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 26 bytes
```
@(v)repelem(v,diff([0,v]))
```
[Ideone link](https://ideone.com/GqLzwQ) (TIO's version of Octave doesn't seem to have `repelem`.)
This started off as seeing if I'd have better luck with `interp1` on Octave directly ([than via MATL](https://codegolf.stackexchange.com/a/243815/8774)), but it's again longer here, at 45 bytes:
```
@(v,w=[0,v])interp1(w,w,1:max(v),'next',v(1))
```
[Try it online!](https://tio.run/##y08uSSxL/Z@WmZOTl1pRUqxgqxDz30GjTKfcNtpApyxWMzOvJLWowFCjXKdcx9AqN7FCo0xTRx2kVl2nTMNQU/M/F1yzRrRhrCYy1xiVa6ijYKSjgClorKNgoqNgiSpuBBY31VEw11EwBJn7HwA "Octave – Try It Online")
(the `w=[0,v]` is because `interp1` doesn't like operating on single element vectors like the `[3]` testcase, wants at least two elements.)
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~13~~ 11 bytes
*-2 bytes by porting [Neil's Charcoal answer](https://codegolf.stackexchange.com/a/243787/16766) because I was seriously overthinking things*
```
FngT Ui=Pn0
```
Takes input as separate command-line arguments; gives output as lines of stdout. [Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuhar3fLSQxRCM20D8gwgIlCJDdFGOgrGOgqmOgrmOgqGhrFQcQA)
### Explanation
```
FngT Ui=Pn0
; i is 0, g is list of command-line args (implicit)
Fng ; For each n in g:
T ; Till
Ui ; increment i
= ; equals
Pn ; print n:
0 ; No-op
```
[Answer]
# [Desmos](https://desmos.com/calculator), 45 bytes
```
M=l.max
f(l)=[\{l<i:M,l\}.\min\for i=[1...M]]
```
[Try It On Desmos!](https://www.desmos.com/calculator/xpirriwtpc)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/1rndfqr9ze)
I feel like this could be a bit shorter, though I don't see it at the moment. I tried to take out the two uses of `l.max` but the strategies I tried didn't work. Also that piecewise expression is a bit annoying, though I don't see a shorter way (it causes me to add `\`'s everywhere in the list comprehension. Without the `\`'s the code won't work.).
[Answer]
# [HBL](https://github.com/dloscutoff/hbl), 9 bytes
```
-(2*(<1.?)(2-.(10.
```
The online interpreter doesn't support `zip-with` yet, but here's a version with a hacked-together reimplementation of `zip-with` on the first line: [Try it!](https://dloscutoff.github.io/hbl/?f=0&p=PCcoLCgxLikoJzEuKSkoMiwnLCkuCi0oKCkqKDwxLj8pKCgpLS4oMTAu&a=KDEgMiA1IDkp)
### Explanation
```
-(2*(<1.?)(2-.(10.
(2 ) Zip
- with the subtraction function:
. The input list, and
(1 ) Cons
0 0 to
. the input list
Result: pairwise differences
(< ) For each item in
. the input list:
1 cons it to
? nil
Result: input list but with each number in a singleton list
(2 ) Zip those two lists
* with the list-repetition function
Result: for each n in the input list, a length-n list of n's
- Flatten
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~37~~ 34 bytes
```
f l=do(a,b)<-zip(0:l)l;b<$[a+1..b]
```
[Try it online!](https://tio.run/##bY7BDoIwEETvfsUcOEBciG01RgV/hPRQgkRCBaKe/PnatJG06mb3sG8yO3tVj@GitTEddNVOqaImK/NXP6ebo870qSmTWq1ZUTTS3FQ/okI7YYX53o9PJOhQMxmtIl4ZgRN@oSBsCYeYc8d3hD2BMWnsbcSVn12gTfkjCGe3WUtq7Pu8EuZHslh42Nbw9Zg3cH/PcS85NRz5Bg "Haskell – Try It Online")
* Saved 3 Bytes thanks to @Unrelated String suggesting using do notation which reveals how emphatic Haskell is.
[Old version](https://tio.run/##bY7BDoIwEETvfsUcONC4EEs1RkP5EeyhjRKJFYl68udrUyJp1c3uYd9kdvasH5eTtc51sDI/5JoMKxpTZ61e8rI0ism6fvVjvtpbZt1V9wMkjjcsMN774YkMHVquklWkKydUhF8oCGvCLuVV4BvClsC5cv420iqaEOhT/ggi2H3WnJr6Pq/E@YksZh63N3w9Nhmq6V7gkxTUeNQb "Haskell – Try It Online")
```
f l=(\(a,b)->b<$[a+1..b])=<<zip(0:l)l
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
xŻI$
```
A monadic Link that accepts a strictly increasing list of positive integers and yields a non-strictly increasing list of positive integers.
**[Try it online!](https://tio.run/##y0rNyan8/7/i6G5Plf9H9xxuf9S05uikhztnAGkgcv//PzraMJZLJ9oYRBjqKBjpKMCYxjoKJjoKliCeEZhnqqNgrqNgCFQfCwA "Jelly – Try It Online")**
### How?
If the input is `A=[a1, a2, a3, ...]` then the output needs to be `a1` `a1`s followed by `a2-a1` `a2`s then `a3-a2` `a2s` etc.
```
xŻI$ - Link: strictly increasing list of positive integers, A
$ - last two links as a monad - f(A=[a1, a2, a3, ...]):
Ż - prepend a zero -> [0, a1, a2, a3, ...]
I - incremental differences -> [a1, a2-a1, a3-a2, ...]
x - times (vectorises) -> [a1, ..., a1, a2, ..., a2, a3, ...]
```
[Answer]
# [Perl 5](https://www.perl.org/), 39 bytes
```
sub{$l=0;map{($_)x($l+=$r=$_-$l,$r)}@_}
```
[Try it online!](https://tio.run/##bVBda4MwFH3PrziEdCqLsMS60ko23wfry946kX3oKLPq1EKH9Le7RNtqYeEm3HvOuecmKZMq8zuWqq7ev7csU3fB7q1sbRY7B5tlt4pVisUuyzirnGMYH7uApEVlkw2wERGul3oYwIj3vPcf73GYGFWCQw7A1OUCjirdNudYRlcq74JPY@yTPe9zLDiEuZvpk4N7jw9Uz0734OC0xMza/dpsm5ecJYfSUSGLgxOM8KtooHDDUjs0EmdgymqbNymdufc1oOF9s8LMFVJX0B7JR5N8GkQaHtpDF/VrTjk5fwINzTCK5EenWkDxCKv4trCC9bx@wfrJ4kakzSk/q/lJG5BjJ4hHBCTM6WGOJdE5fCz04/4A "Perl 5 – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 41 bytes
```
function(x)x[cumsum(y<-1:rev(x)%in%x)+!y]
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T6NCsyI6uTS3uDRXo9JG19CqKLUMKKaamadaoamtWBn7P00jWcNQU5MLRBtDaUMdIx0E21jHRMcSygOK65jqmOsYArX8BwA "R – Try It Online")
Quite a lot longer than [pajonk's answer](https://codegolf.stackexchange.com/a/243767/67312), but a nice little bit of index calculation all the same.
This ports to other matrix languages such as, for instance, [MATL](https://tio.run/##y00syfn/vyTAyj23pK48slhb8///aCMFYwVTBXMFQ8NYAA), but it's longer than the `diff` approach there as well.
[Answer]
# [Arturo](https://arturo-lang.io), 42 bytes
```
$[a][map 1..max a'x[min select a'y[y>=x]]]
```
[Try it](http://arturo-lang.io/playground?2ytyWY)
```
$[a][ ; a function taking an argument a
map 1..max a'x[ ; map over the range 1..max(a) and assign current value to x
min select a'y[ ; select the smallest number in a that...
y>=x ; is greater than or equal to x
] ; end select
] ; end map
] ; end function
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 38 bytes
```
a=>a.map(g=n=>n>++i?[n,g(n)]:n,i=0)+''
```
[Try it online!](https://tio.run/##bY3LDoIwEEX3fsXsaMMIFjRGTeuHkC4aBILBKRHj71ceahpgMrO59@TM3bxNlz/r9rUleytcKZ2RykQP07JKklSkwrC@ZoQVI67PhLXc8TAIXG6ps00RNbZiJcuEBn84v0AcQx9vZmC6DqYIwy5wgZAM@dz7jVfwXrNHOOkZnv4bfxeCZMQOCEcEIfRPkEz/xmYqx94/7T4 "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
x)o/
```
[Try it online!](https://tio.run/##y0rNyan8/79CM1///@F2b83I//@jDWN1FKKNQYShjpEOlGGsY6JjCWICRXRMdcx1DA1jAQ "Jelly – Try It Online")
Shamelessly sandbox sniped, [but I didn't start it :P](https://chat.stackexchange.com/transcript/240?m=60581858#60581858)
```
) For each element of the input, as a monadic chain:
x repeat it by itself.
o/ Reduce the resulting list of lists by logical OR.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~8~~ ~~7~~ 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Å1*ζ€ß
```
-1 byte porting [*@emanresuA*'s Vyxal answer](https://codegolf.stackexchange.com/a/243766/52210)
[Try it online](https://tio.run/##yy9OTMpM/f//cKuh1rltj5rWHJ7//3@0kY6xjqmOuY6hYSwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/8Othlrntj1qWnN4/n@d/9HRhrE60cZAbKhjpAOhjXVMdCyBLCBfx1THXMfQMDYWAA).
**Original ~~8~~ 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) answer:**
```
0š¥Å1*˜
```
[Try it online](https://tio.run/##yy9OTMpM/f/f4OjCQ0sPtxpqnZ7z/3@0kY6xjqmOuY6hYSwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXLf4OjCw8tPdxqqHV6zn@d/9HRhrE60cZAbKhjpAOhjXVMdCyBLCBfx1THXMfQMDYWAA).
**Explanation:**
```
# e.g. input=[2,3,5]
Å1 # Map each value in the (implicit) input-list to that many 1s
# → [[1,1],[1,1,1],[1,1,1,1,1]]
* # Multiply each to the (implicit) input-list at the same positions
# → [[2,2],[3,3,3],[5,5,5,5,5]]
ζ # Zip/transpose; swapping rows/columns, using " " as filler
# → [[2,3,5],[2,3,5],[" ",3,5],[" "," ",5],[" "," ",5]]
ۧ # Get the minimum of each inner list, ignoring the " "
# → [2,2,3,5,5]
# (after which the resulting list is output implicitly)
0š # Prepend a 0 to the (implicit) input-list
# → [0,2,3,5]
¥ # Pop and push its deltas/forward-differences
# → [2,1,2]
Å1* # Similar as above
# → [[2,2],[3],[5,5]]
˜ # Flatten this list of lists
# → [2,2,3,5,5]
# (after which the resulting list is output implicitly)
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 75 bytes
```
def f(a):
s=[i:=(c:=a[-1])]
while i:=i-1:s=[c:=[c,i][i in a]]+s
print(s)
```
[Try it online!](https://tio.run/##XY/BasMwDIbvfoqfnBKmQJ1sbDO4t73A2M3oEFKHGkoa4pS2T5/ZbpqWgmys//slS8N12h/7@msY53lnO3R5UygBr41TOm@VbkwpuWCB894dLILqSqkCD8y05Ng4uB4N85sXGEbXT7kv5rbx1kPDCBgjmRAuppjUMakJMRZJEqqYRdfyXEGwvRO@F1avwnMs7irBD8InQaY/q1u3JN70hJ5PrGUhuuOIOHPcJc2u7stkf9ZPKqMkmw0XK0C5xc9lsO0Dyxf8a/3pkLDtdzpDFnCX3zvN/w "Python 3.8 (pre-release) – Try It Online")
Ungolfed:
```
def fill_numbers(original):
current_number = last_valid = original[-1]
result = [original[-1]]
while current_number-1 > 0:
current_number -= 1
if current_number in original:
last_valid = current_number
result = [last_valid] + result
print(result)
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 9 bytes
```
hM.Tm*d]d
```
[Try it online!](https://tio.run/##K6gsyfj/P8NXLyRXKyU25f//aCMdBWMdBdNYAA "Pyth – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 9 bytes
```
FAW‹ⅉι⟦Iι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBwzOvoLREQ1NToTwjMydVQcMntbhYI1JDU0chEygYUJSZV6IR7ZxYXKKRqRmraf3/f3S0kY6CsY6CqY6CuY6CoWFs7H/dshwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
FA
```
Loop over the input list.
```
W‹ⅉι
```
Repeat until the appropriate line is reached...
```
⟦Iι
```
... output the current value on its own line.
[Answer]
# PHP, 71 bytes
```
$n=[];for($i=max($a);$i;$i--){$n=[in_array($i,$a)?$h=$i:$h??$i,...$n];}
```
[Try it online!](https://tio.run/##FYpRCsIwEESvsh8LTWAbqCJaY8hBSigLVRKw6RJQFPHsMcLMx7w3EqVevEQBZHAw7Qj2BEeCE8FIMLQ9HFrHYCtmNwV724rC5FZ@KWRtMbX0vf78bcozl8LvdqAmPUaH6YzR@waMMZiD/dYnl3l5rKLSKvdtuaqOOgLMWtv6Aw "PHP – Try It Online")
Ungolfed:
```
$n = [];
for ($i = max($a); $i; $i--) {
$n = [in_array($i, $a) ? $h = $i : $h ?? $i, ...$n];
}
```
] |
[Question]
[
The challenge here is to take a string and output all its rotations, by repeatedly moving the first character to the end, once per character in the string, ending with the original string:
```
john -> ohnj, hnjo, njoh, john
```
You may also cycle in the other direction, moving characters from the end:
```
john -> njoh, hnjo, ohnj, john
```
You should still output one rotation per letter even if the original word is reached before that:
```
heehee -> eeheeh, eheehe, heehee, eeheeh, eheehe, heehee
```
Character arrays are allowed, as long as the result works as shown above.
Shortest answer wins!
[Answer]
## Haskell, 27 bytes
```
scanl(\(a:b)_->b++[a])=<<id
```
[Try it online!](https://tio.run/##BcHRCYAgEADQVQ7pQ5EWCG2RjDgt07JLsvm73kvYzq0UjtZxC0hFOomDV0s/eq0nnJU1Jq98YSawUJ9ML3QQQRx3IsFfiAX3xn2o9Qc "Haskell – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 2 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ṙJ
```
A monadic Link accepting a list of characters which yields a list of lists of characters
**[Try it online!](https://tio.run/##y0rNyan8///hzple/w@3R/7/r@SVn5GnBAA "Jelly – Try It Online")** (footer pretty prints by calling the link and joining with newline characters)
[Answer]
# [Python 2](https://docs.python.org/2/), 38 bytes
```
s=input()
for c in s:s=s[1:]+c;print s
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v9g2M6@gtERDkystv0ghWSEzT6HYqti2ONrQKlY72bqgKDOvRKH4/3@lrPyMPCUA "Python 2 – Try It Online")
[Answer]
# JavaScript (ES6), ~~37~~ 32 bytes
Returns an array of strings.
```
s=>[...s].map(c=>s=s.slice(1)+c)
```
[Try it online!](https://tio.run/##XclBCoAgEEDRfcdwpUQDHUAvEi1kGlMxR5ro@uY6@Kv3s3@94J3as1Q@qAfbxboNAGSHyzeN1okVkJKQ9GpmNB25CheCwqcOWmWOVRkz/TgSjcboHw "JavaScript (Node.js) – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 6 [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")
```
⍳∘≢⌽¨⊂
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT////1Hv5kcdMx51LnrUs/fQikddTf/THrVNeNTb96hvqqf/o67mQ@uNH7VNBPKCg5yBZIiHZ/D/NAX1rPyMPHUA "APL (Dyalog Unicode) – Try It Online")
`⍳` the indices
`∘` of
`≢` the tally
`⌽¨` each rotate (to the left)
`⊂` the entire string
[Answer]
# Japt, ~~5~~ 3 bytes
Takes input as a character array, outputs an array of character arrays
```
£=é
```
[Try it here](https://ethproductions.github.io/japt/?v=1.4.6&code=oz3p&input=WyJqIiwibyIsImgiLCJuIl0KLVE=)
```
£=é :Implicit input of character array U
£ :Map
é : Rotate U one element to the right
= : Reassign to U for next iteration
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), ~~6~~ 5 bytes
```
tf&+)
```
*1 byte saved thanks to @luis!*
Try it at [MATL Online](https://matl.io/?code=tf%26%2B%29&inputs=%27John%27&version=20.10.0)!
**Explanation**:
```
# Implicitly grab input string
t # Duplicate the input
f # Create an array [1, ..., N] where N is the number of characters in the input
&+ # Add the transpose of this array to itself to create a 2D array of indices
#
# + 1 2 3 4
# ----------
# 1 | 2 3 4 5
# 2 | 3 4 5 6
# 3 | 4 5 6 7
# 4 | 5 6 7 8
#
) # Use this 2D array to index into the original string using periodic indexing
# Implicitly display the resulting character array
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes
```
ā._
```
[Try it online!](https://tio.run/##yy9OTMpM/f//SKNe/P//WfkZeQA "05AB1E – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 7 bytes
```
#\|."{]
```
[Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8F85pkZPqTr2vyaXkp6CepqtnrqCjkKtlUJaMRdXanJGvkKagnpWfkaeOoTn4wYXzUhNBSJ1rv8A "J – Try It Online")
## Explanation:
```
|."{ - rotate ( "{ is short for "0 1 - rank 0 1 )
] - the input
#\ - lenght of the successive prefixes of the input
```
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 59 bytes
```
,[>,]<[>>[>]+[<]<[<]>-[[>]>[>]<+[<]<[<]>-]>[.>]>[.>]<[<].<]
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fJ9pOJ9Ym2s4u2i5WO9oGyLSJtdONBvJAIjYIISBfzw5CgAT0bGL//8/Kz8gDAA "brainfuck – Try It Online")
Outputs each string separated by null bytes.
### Explanation:
```
,[>,] # Get input
<[ # Start loop over input
>>[>] # Go to end of the string
+ # Set it to one to mark it
[<]<[<]> # Move to the beginning of input
-[[>]>[>]<+[<]<[<]>-] # Transfer the first character to the end
>[.>]>[.>] # Print the rotated string
<[<]. # Print a nul byte
<] # Repeat loop while input
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~35~~ 26 bytes
```
Partition[#,Tr[1^#],1,-1]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78H1CUmVcS/T8gsagksyQzPy9aWSekKNowTjlWx1BH1zBW7b@Cg4JzRmJRYnJJalFxtFJWfkaeUmzsfwA "Wolfram Language (Mathematica) – Try It Online")
Takes a list of characters as input.
`Partition` (but not its variant `StringPartition`used below) has an optional fourth argument for treating its input as cyclic (and for specifying how exactly to do so), which makes this solution simpler than the string one - in addition to not having any 15-character built-in functions.
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 44 bytes
```
Rest@StringPartition[#<>#,StringLength@#,1]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78H1CUmVcS/T8otbjEIbgEyEkPSCwqySzJzM@LVraxU9aBCPqk5qWXZDgo6xjGqv1XcFBQysrPyFOK/Q8A "Wolfram Language (Mathematica) – Try It Online")
The same, but takes a string as input.
Turns `"john"` into `"johnjohn"`, then takes all the length-`StringLength["john"]` substrings of this string with offset 1, producing `{"john","ohnj","hnjo","njoh","john"}`, then drops the first of these with `Rest`.
[Answer]
# [Attache](https://github.com/ConorOBrien-Foxx/Attache), 13 bytes
```
Rotate#{1:#_}
```
[Try it online!](https://tio.run/##SywpSUzOSP2fpmBl@z8ovySxJFW52tBKOb72v19qakpxtEpBQXJ6LFdAUWZeSUhqcYlzYnFqcXSajkK0UlZ@Rp6SjoJSRmoqEIFYhkbGJiBaz0pRKTb2PwA "Attache – Try It Online")
## Explanation
```
Rotate#{1:#_}
# fork(f, g) = ${ f[x, g[x]] }; this forks:
Rotate rotate's the input by
{1:#_} each number from 1 to the length of the input
```
## Alternatives
**15 bytes**: `{_&Rotate!1:#_}`
**16 bytes**: `{Rotate[_,1:#_]}`
**16 bytes**: `Rotate@Rotations`
**16 bytes**: `Rotate#(1&`:@`#)`
**17 bytes**: `Rotate#{1+Iota@_}`
**18 bytes**: `Rotate#(1&`+@Iota)`
**19 bytes**: `Rotate#(Succ=>Iota)`
[Answer]
# [R](https://www.r-project.org/), 58 bytes
```
function(s,`[`=substring)paste0(s[n<-nchar(s):1],s[1,n-1])
```
[Try it online!](https://tio.run/##DcZBCoAgEADAex/RBYW8Rr5EBEs07bCGq@/fhDlM52w5T4yjNpSkgguW5k2jV3zgu2ikXZLDU2MsV5cEh/GKnFGojQfOUrytoIBtraS0COAf "R – Try It Online")
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 34 bytes
```
x=>x.Select(c=>x=x.Substring(1)+c)
```
[Try it online!](https://tio.run/##Sy7WTS7O/O9WmpdsU1xSlJmXruPpmleam1qUmJSTChWys1NIU7D9X2FrV6EXnJqTmlyikQxk2wJ5pUkQJRqGmtrJmv@tuQKAvBKNNA2lrPyMPCVNvZB8x6KixEoNTU0kuYzUVCBClf0PAA "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 39 bytes
```
->s{a=s.chars.to_a;a.map{a.rotate!*''}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1664OtG2WC85I7GoWK8kPz7ROlEvN7GgOlGvKL8ksSRVUUtdvbb2f4FCWrR6Vn5GnnrsfwA "Ruby – Try It Online")
[Answer]
# C (32-bit), ~~58~~ ~~51~~ 50 bytes
-1 byte for a nice round number thanks to ceilingcat
```
i;f(s){for(i=0;i++<printf("%s%.*s\n",s+i,i,s)-2;);}
```
[Try it online!](https://tio.run/##Jcu7CsIwFIDhV4mFQm4VL@Ohu2/goA4hJs2RNJGk1EH00T1ahH4l892g7VECJ5X8fS5cOw38FYK1b1gmjxv2tquZT2nRleFGnUVIOBFo8HErZ6FDaZIOcNfp4lhvwU2n/ACDJUSni@/EArO/aJbDokOLsbMjrnE6@pjfTRDpe5B3bjffQE "C (gcc) – Try It Online")
## Degolf
```
i; // "Global" i.
f(s){ // s is pointer to string, which conveniently fits in a 32 bit integer.
for(i=0; // Initialize i.
// Increment i and take its complement, and add it to the
// return value of printf(); which just happens to be strlen(s)+1.
// ~i + strlen(s) + 1 == strlen(s) + 1 - i - 1, so the last printed
// string is the original string.
~++i + printf("%s%.*s\n",s+i,i,s);
// The printf prints two strings: first until the terminating \0,
// the second until a \0 or until i chars have been printed. It also
// prints a linefeed.
}
```
[Answer]
# JavaScript, ~~48~~ ~~43~~ 36 bytes
*-5 bytes courtesy of @Bubbler*
\*-7 bytes courtesy of @Shaggy
Input is a character array and output is an array of character arrays.
```
s=>s.map(_=>([a,...b]=s,s=[...b,a]))
```
[Try it online!](https://tio.run/##XcnBDYAgDEDRu2NwgqjdoCxijBYElSg11rg@cjb5p/cTvST@3q@nz7yEErEI2gEAZISTLj2h1QN1FdyI0gk6SLzneW7JmOI5Cx8BDl511CrxlpUxzY@3EGp1lA8)
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 38 bytes
```
,[>>,]<<<+>[[.>>]<<[<<]>-[+>.>-].<<+>]
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fJ9rOTifWxsZG2y46Ws/ODsiMtrGJtdON1rbTs9ON1QPJxP7/n5WfkQcA "brainfuck – Try It Online")
Based on the idea of JoKing to use null-characters as space symbols. This code marks the current letters to print and loops until it reaches the left end.
```
,[>>,]<< input string with empty cells in between
<+> set first marker
[ main loop
[.>>] print remaining characters
<<[<<] return to start
>-[+>.>-] print until marker (remove marker)
. print null
<<+ set new marker
> restart loop with next character to the left
] stop if there's no character to the left
```
[Answer]
# [Fig](https://github.com/Seggan/Fig), \$13\log\_{256}(96)\approx\$ 10.701 bytes
```
$#GLxWxO'+]xq
```
[Try it online!](https://fig.fly.dev/#WyIkI0dMeFd4TycrXXhxIiwiam9obiJd)
This is so long
[Answer]
# [Go](https://go.dev), 105 bytes
```
func f(s[]rune)(o[][]rune){for i:=0;i<len(s);i++{o=append([][]rune{append(s[i:],s[:i]...)},o...)}
return}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RY_BTsQgEIbP8hSEE2Sx8WhY-w7em8ZgF7q4W2hm6In0Sbw0Jj6EV9_Ct5EtrRKSmUn--b_53z_6sHyNurvo3tBBO0_cMAaIFbNDZJ9TtPePP85OvqOWY9PC5I3goWm3NtkA1Kn64eiersZzFEd3OKRQ63E0_sR3YdpmbJxqJTbKtVVViVmGtRAwcQI_b8DvFXjhgH8gjrnHCM73BfoiQdWgfb4bMCHuRERZZBzEvzEhq-UtIRc0EUSqaro7JvYWzp5Jys7G5H_r9Gt3MpbNpMBWfcHl3UTunvNivObEMh9qeTkz58-PzGRLsiyl_gI)
Without the requirement of the original being at the end, this saves 13 bytes:
### 92 bytes
```
func f(s[]rune)(o[][]rune){for i:=0;i<len(s);i++{o=append(o,append(s[i:],s[:i]...))}
return}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TY9BbsMgEEXX5RSIFSjU6rIi9R2yd62KOuDQxGDN4BXySbqxKvUQ3fYWvU2JcaqikfiLmf_-f__ow_I16u6se0MH7TxxwxggVswOkX1O0d4__jzbyXfUcmxamLwRPDTtJpMNQJ2qH_bu6WI8R7F3u10KtR5H4488yE1g41QrsVGurapKiJmAiRP4eWN8r4wzB_zz5pg1RnC-L5wXCaoG7XNUwIR4gyDKssbhnzEhq-W1FBc0EUSqanpzTOwtnDyTlJ2MyXNV-rU7GstmUmDrfsHl20TuDvkwXnJJmYNaXmLmyvmRmWxNlqX8vw)
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 3 bytes
```
:(m
```
[Run and debug it](https://staxlang.xyz/#c=%3A%28m&i=john%0Aheehee&a=1&m=2)
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-nl`, 26 bytes
```
$_.scan(/./){puts$'+$`+$&}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcnm0km5ejlLsgqWlJWm6FrtU4vWKkxPzNPT19DWrC0pLilXUtVUStFXUaiEKoOoWLMnKz8iDsAE)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 3 bytes
```
(Ǔ…
```
### Explanation:
```
( # For each char in the input
Ǔ # Rotate left
… # Print without popping
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIox5PigKYiLCIiLCJqb2huIl0=)
[Answer]
# [Julia 1.0](http://julialang.org/), 31 bytes
```
!s=(r=keys(s)).|>i->(s*s)[i.+r]
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/X7HYVqPINju1slijWFNTr8YuU9dOo1irWDM6U0@7KPa/Q3FGfrmColJWfkaeEheMl5GaCkRK/wE "Julia 1.0 – Try It Online")
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 3 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
ż€Ỵ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728JKM0Ly_faMGCpaUlaboWK47uedS05uHuLUuKk5KLoYILlmWkpgIRhAcA)
#### Explanation
```
ż€Ỵ # Implicit input
ż # Push the length range
€ # For each number in this range:
Ỵ # Rotate the input left that many times
```
[Answer]
# [Arturo](https://arturo-lang.io), 30 bytes
```
$->s[0-1map s=>[rotate s<=1+]]
```
[Try it!](http://arturo-lang.io/playground?rEtDLt)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 41 bytes
Another JS answer, which doesn't beat any of the previous JS ones.
Input is an array of characters (as seen in other answers), and output is an array of strings.
Rotates the string the inverted way, as allowed by OP.
```
s=>[...s].map(_=>[...s]=s.pop()+s.join``)
```
[Try it online!](https://tio.run/##dY5BCsIwEEX3niLMKsGYAwjRvQtduBSxpU5tSk1CJ4oewJ1H0Mt5kRobuxGEgc/Pf/MzdX7OqWiNDxPr9tiVuiM92yilaKuOuee7wWlS3nkuxqRqZ2yWiS4nwjZobqw/BYkXj0XAvWyRTk3Qi/VqqSi0xh5MeeVlwoQQelY4S65B1bgD519c66FgDq/HjcEUXs87AzFOgBiN0n@csc9FULvKwpZJlm3ARgMSqqhRYlBHSUDGmPjZrBDjDLvY28j3r31NyuX/qG/t3g "JavaScript (Node.js) – Try It Online")
---
Different approach that swaps each character with their corresponding one, obtained via calculation of its index (correct rotation direction, **58 bytes**) :
```
s=>s.map((_,i)=>s.map((_,j)=>s[(i+j+1)%s.length]).join``)
```
[Try it online!](https://tio.run/##dY3BasMwDIbvfQojKFjEM@w68HbfoT3sGMoSUiWxyewQuWV7gN32CNvL9UUyJ15hDAZCv3706ZerzzU3kx3jjQ9Hmlszs7ln/VKPUj4ri7@MW0wpbeGKW9yyHsh3sT@gdsH6qsK5ZqYpGmn9eIqKXkdqIh3VRHwaonl82u80x8n6zrZvss0YYkptgucwkB5CJ@UPbsw14AEun@8C7uDy9SEAiwzgZpP/SSFKrTW40Hs4CCWqEtLoQEHqIUnqfZIMVELgn8ueKNX1djULvyotMXmv/l@tqfM3 "JavaScript (Node.js) – Try It Online")
[Answer]
# [ForWhile](https://esolangs.org/wiki/ForWhile) 23 bytes
`{:0$(.0@,0@(.0@,#:)9#)}`
Input: a char array followed by its length (stored on stack)
Output: prints rotations of input separated by tab (newline would need an additional character)
[online interpreter](https://bsoelch.github.io/OneChar.js/?lang=forwhile&src=ezowJCguMEAsMEAoLjBALCM6KTkjKX0KMSQKCiJGb3JXaGlsZSIgMUA_)
# Explanation
```
{ \ define anonymous procedure
:0$ \ store copy of string length at address 0
(. \ start for-loop, ignore loop-counter
0@, \ rotate top (string length) stack elements
0@(.0@,#:) \ print string but keep it on the stack
9# \ print tab
) \ end outer for-loop
} \ end procedure
```
Calling the procedure:
```
{:0$(.0@,0@(.0@,#:)9#)} \ procedure
1$ \ store procedure at address 1
"ForWhile" \ procedure argument
1@? \ call procedure
```
prints:
```
orWhileF rWhileFo WhileFor hileForW ileForWh leForWhi eForWhil ForWhile
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 10 bytes
```
⮌Eθ⭆θ§θ⁻μκ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCMotSy1qDhVwzexQKNQRyG4BCiaDuU4lnjmpaRWgJi@mXmlxRq5OgrZmmBg/f9/Vn5G3n/dshwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
θ Input string
E Map over characters
θ Input string
⭆ Map over characters and join
θ Input string
§ Circularly indexed by
⁻ Difference between
μ Inner index
κ Outer index
⮌ Reversed
Implicitly print each string on its own line
```
To rotate in the opposite direction, replace `Minus` with `Plus`.
[Answer]
# [Red](http://www.red-lang.org), 49 43 bytes
```
func[s][forall s[print move head s tail s]]
```
[Try it online!](https://tio.run/##DcnBCcAgDEDRu1MEx@gYvYYcpEnQoqao7fqp8A8P/hD2Uxgp6OH69gsnodpItcLEZ5S@oNknkCUxTFip7EHkCvG23GPYyCK76D8 "Red – Try It Online")
] |
[Question]
[
Given an integer \$x\_1\$ and some [black box function](https://codegolf.meta.stackexchange.com/a/13706/24877) \$f: ℤ → ℤ\$ find a fixed point of \$f\$ in the sequence defined by \$x\_{k+1} := f(x\_k)\$.
### Details
* A value \$x\$ is said to be a fixed point of \$f\$ if \$x = f(x)\$.
For instance if \$f(x) = \text{round}(\frac{x}{\pi})\$ and we have a starting point \$x\_1 = 10\$ then we get \$x\_2 = f(x\_1) = f(10) = 3\$, then \$x\_3 = f(x\_2) = f(3) = 1\$, then \$x\_4 = f(x\_3) = f(1) = 0\$, and finally \$x\_5 = f(x\_4) = f(0) = 0\$ which means the submission should return \$0\$.
* You can assume that the generated sequence actually contains a fixed point.
* You can use the native type for integers in place of \$ℤ\$.
* You can use any language for which there are defaults for black box functions input in the [standard IO meta post](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). If there are no such default for your language feel free to add one in the sense of the [definition of black box functions](https://codegolf.meta.stackexchange.com/a/13706/24877), and make sure to link your proposals in that definition. Also don't forget to vote on them.
### Examples
```
f(x) = floor(sqrt(abs(x)))
0 -> 0, all other numbers -> 1
f(x) = c(c(c(x))) where c(x) = x/2 if x is even; 3*x+1 otherwise
all positive numbers should result in 1,2 or 4 (Collatz conjecture)
f(x) = -42
all numbers -> -42
f(x) = 2 - x
1 -> 1
```
[Answer]
# [Actually](https://github.com/Mego/Seriously), 1 byte
```
Y
```
[Try it online!](https://tio.run/##S0wuKU3Myan8f2jx/8j//025lBwfdcx61NmhBAA "Actually – Try It Online")
`Y` is the fixed point function in Actually. In the TIO example, the function is shown being taken as a string, and `£` is used to transform it to a function on the stack. It's also possible to just push the function to the stack [like so](https://tio.run/##S0wuKU3Myan8/6hngeOjjlmPOjse9Sz8H/n/vykA). These are the only two ways to get a function input in Actually.
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 2 bytes
```
⍣=
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT/8PBP6P2iY86l1sy1X9qKdLo@ZR71ZNLT3TWn8FQyNjhUe9cxXccvLzizSKC4tKNBKTihUqNDW5qo10gepAahSgAKTQSLeCq1rXxAgobmxohBAHCgEA "APL (Dyalog) – Try It Online")
**NB:** I define `O←⍣=` in the the input section due to a bug in that derived monadic operators can't be defined in the way that TIO likes to define things.
`⍣` Is an operator that can be used like `(function⍣condition) ⍵`
It applies the `function`, `f`, to `⍵` until `(f ⍵) condition ⍵` returns true.
`⍣=` is a derived monadic operator that takes a monadic function, `f`, as its left argument and applies it to its right argument, `⍵`, until `f ⍵ = ⍵`
[Answer]
## Haskell, 17 bytes
```
until=<<((==)=<<)
```
[Try it online!](https://tio.run/##lcs9D4IwGATg3V9xIQ5UA5EPN@pu4ubKgvhWGkuLbVV@vbWOLibmhrvhuaFzV1IqCN6Gu/ZS8aZJU85ZbBbGTmpwnM0CmKzUHksIpEIZY3N3sz4X1ox77elCNu9ODgybP2y1rT/67o/eHjSS5PvbG@080qwuWbQ/ZR7DUJQVngNZQs/RztlOCtCDNGb4IdZZPuIsQcoRqtW8LsKrF6q7uJD10/QG "Haskell – Try It Online")
[Answer]
# [MATLAB](https://matlab.mathworks.com/), 41 bytes
```
function x=g(f,x);while f(x)-x;x=f(x);end
```
There is also [this beauty](https://tio.run/##FclLCoAgGEXh7dwLNqipCG7FHkoQWRmhSGu3v8kZfCdOt3uW1oKxCLTwKrNaMCtJEBIpfOvQoRiPTGMyX1D/r@l5TQfcnmBl@S3GC@m8brgxCZCqJ3X7AA) that does not need function files. Unfortunately it is a little bit longer:
```
i=@(p,c)c{2-p}();g=@(g,f,x)i(f(x)==x,{@()x,@()g(g,f,f(x))});q=@(f,x)g(g,f,x)
```
[Try it online!](https://tio.run/##y08uSSxL/f8/rTQvuSQzP0@hwjZdI02nQtO6PCMzJ1UhTaNCU7fCusIWxLBOzUv5D8TWKZnFBRrpGg5AMSPdCh1DTU3r/wA "Octave – Try It Online")
[Answer]
# Mathematica, 11 bytes
```
#2//.x_:>#&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X9lIX1@vIt7KTlntf0BRZl6JQ1q0W05@flF0cGFRSbRjUrFDRWysjkEsFx5ZE6PY/wA "Wolfram Language (Mathematica) – Try It Online")
# Mathematica, 10 bytes
```
FixedPoint
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73y2zIjUlID8zr@R/QBGQdEiLdsvJzy@KDi4sKol2TCp2UI6NVdMxiOXCJ21iFPsfAA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Standard ML (MLton)](http://www.mlton.org/), 30 bytes
```
fun& $g=if$ =g$then$else&(g$)g
```
[Try it online!](https://tio.run/##bZDNbsMgEITvfopVhCxoFKvGlnqo/AA59JJcq1b4B4KKwbVJxCmvni6oihup4oD2YxhmWEazG4139ibPFlojuq/WhRICNCCNczN9E/5ULN@zp4dBmELObtxbT0W7QGCMZdnfizxd7Ghc8RQyYXvoEtUSt9H1wHF4Bn8aLIJeXxAMZhmgegrb8tGvgk8UX2v@iOtkyHchps6BqEZLAo0i0ZREs5wqwlQqNU2gUT3NGmNj9MK7o8dBIf6AzbvdYImLMOkpmqGe5pjv/hfs9ZfV/B9YVmv5O3xZC6zCNT1jtx8 "Standard ML (MLton) – Try It Online") Use as `& n blackbox`.
The black box functions are defined as following:
```
fun blackbox1 x = floor(Math.sqrt(Real.fromInt(abs x)))
fun blackbox2 x = c(c(c(x)))
and c x = if x mod 2 = 0 then x div 2 else 3*x+1
fun blackbox3 _ = ~42
fun blackbox4 x = 2-x
```
**Ungolfed version:**
```
fun fixpoint n g = if n = g n then n else fixpoint (g n) g
```
[Answer]
# [R](https://www.r-project.org/), ~~36~~ 35 bytes
*thanks to JayCe for golfing down a byte*
```
function(f,x){while(x-(x=f(x)))0;x}
```
[Try it online!](https://tio.run/##hY5NbsIwEIXX4RSvREh2sVUn7a7NCTiFSW1iyYqDbcQIxNlTkqo/WaHZjPS9983E8YAPOdpT32YXemYF8eu5c94wkoway4hzrt7pNh7Yb4p4LUlUHEVRlLjvqwWUb/UdzqwNfcq6z/jBq13zL7l2ds1os6nF6zNtK0EvNZ9b3ut8@Sst9Ds2zfTXfKVEjm7wBnoYvGv1lEKwDyTWhxBZOsbM9D5922SlOIASqQsn/4m9QQUbIghPDZSAQsidiWeXzGPb7Fra1PgF "R – Try It Online")
[Verify the example functions!](https://tio.run/##hY5NbsIwEIXX4RSvREh2sVUn7a7NCTiFSW1iyYqDbcQIxNlTkqo/WaHZjPS9983E8YAPOdpT32YXemYF8eu5c94wkoway4hzrt7pNh7Yb4p4LUlUHEVRlLjvqwWUb/UdzqwNfcq6z/jBq13zL7l2ds1os6nF6zNtK0EvNZ9b3ut8@Sst9Ds2zfTXfKVEjm7wBnoYvGv1lEKwDyTWhxBZOsbM9D5922SlOIASqQsn/4m9QQUbIghPDZSAQsidiWeXzGPb7Fra1PgF)
R port of [flawr's solution.](https://codegolf.stackexchange.com/a/150189/67312)
[Answer]
# [Python 2](https://docs.python.org/2/), ~~39~~ ~~37~~ 33 bytes
thanks to [@Mr.Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder) for -2 bytes
```
s=lambda k:s(f(k))if k-f(k)else k
```
[Try it online!](https://tio.run/##dcrBCsIwDMbx@54iFyGpVNeol@Ieppsrjs5smF18@rqJsCFILh/5/8bXdB@Ec9aqD4/6FiB5xYiJqIuQ7LLaXltIuWiggi8SL0eGWciO4QoOPuZkZO@KuGUNLidEVIzPTiZQdExbo35@Y6gVlYw5XP5C8fbMayzLn8pW1kr5DQ "Python 2 – Try It Online")
assumes the black-box function to be named f
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~25~~ ~~22~~ 21 bytes
thanks [Herman Lauenstein](https://codegolf.stackexchange.com/users/70894/herman-lauenstein) for showing me [this consensus](https://codegolf.meta.stackexchange.com/a/13707/64121)
thanks to [@l4m2](https://codegolf.stackexchange.com/users/76323/l4m2) for -1 byte
Assumes the black-box function to be named `f`.
```
g=k=>f(k)-k?g(f(k)):k
```
[Try it online!](https://tio.run/##JcaxDYAgEADAniks/wsMtibgBA6BCKgQXoG4Pka96g5962LyflaeaLWteRmkchCQh8nDGxxDczJJNeu69S4SZfharlz/6aVAQkRmKBWKto/kgXWdh0EIZNge "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
vÐL
```
[Try it online!](https://tio.run/##y0rNyan8/7/s8ASf////KxnFK/03BAA "Jelly – Try It Online")
Takes the left argument as a string representing a Jelly link (`2_` for instance), and the right argument as an integer
## How it works
```
ÐL - While the output is unique...
v - Evaluate the function with the argument given
```
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 24 bytes
```
(()){{}(({})<>[({})])}{}
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/X0NDU7O6ulZDo7pW04YLyNPQjK6ujdXksosGCcVq1lbX/v9vCAA "Brain-Flak – Try It Online")
(for the black box function `x -> 2-x` in the example below)
The provided black box function should be a program, that given `x` on the top of the stack, pop `x` and push `f(x)` - in other word, it should evaluate the function `f` on the value on the top of the stack.
Equivalent [Mini-Flak](https://codegolf.stackexchange.com/a/110652) is 26 bytes (thanks to Wheat Wizard for saving 2 bytes):
```
(()){{}(({})( )[{}({})])}{}
^ put the function f here
```
(not counting the comments and spaces)
Take the function (inside the `<>`) and a number `x0` from input. (note that Brain-Flak is an esoteric language and can't take functional argument as input)
---
Example blackbox functions:
`x -> 2-x`: [Try it online!](https://tio.run/##SypKzMzTTctJzP7/X0NDU0Mzuro2VvP/fxMA "Brain-Flak – Try It Online")
---
Explanation:
```
(()){{}(({})<f>[({})])}{} Main program.
Implicit input from stdin to stack.
( ) Push
() literal number 1.
Now the content of the stack: [1, x0]
{ } While stack top ≠ 0:
current stack content: [something ≠ 0, x]
{} Pop stack top (something). stack = [x]
( ) Push
({}) Stack top = x. Current stack = [x]
f Evaluate f. Current stack = [f(x)]
< > (suppress the value of f(x), avoid adding it)
[ ] plus the negative of
({}) the top of the stack ( = -f(x) )
In conclusion, this change (x) on the stack to
(f(x)), and then push (x + -f(x))
If it's 0, break loop, else continue.
{} Pop the redundant 0 on the top.
Implicit output stack value to stdout.
```
[Answer]
# [Swift](https://swift.org), ~~47~~ 42 bytes
```
func h(_ n:Int){f(n)==n ?print(n):h(f(n))}
```
Naive approach, assumes that [the black box function is named](https://codegolf.meta.stackexchange.com/a/13707/70894) `f`
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 40 bytes
```
f(n,b)int(*b)(_);{n=n^b(n)?f(b(n),b):n;}
```
[Try it online!](https://tio.run/##ZY/RasMwDEXf@xUiMCqPCJo2ZbDQ7TP2UjYcr24NjtLZDhRKfn2evTG6ZHqR0D2SrhQdlYpRI5etMBzwvhX4Jpor7/i1RRbPGnNK6iM3Y0wIaC8x54uAK7hDGByD/3ABZevxIkQD4yLrXK//cVSvs/ytd9IwJm0BKc5D8FjoNA870LbvHf7dKQrR/HAujWosVkBPcGf2XJSgcVUmU2KG0HbC0HYCDUGdpMPlnpe31s1CMjo/WW02D5ONuVGmL@eH62qC1dUvNMZPpa08@ki2i/TCPZnubI0ygfTAKpie6f2grHQy118 "C (gcc) – Try It Online") Note that the flags are not necessary, they are there to aid with testing the fixpoint function defined above.
This is a function that takes an int `n` and a function pointer `b : int → int`. Abusing the fact that writing to the first variable argument sets the `eax` register, which is equivalent to returning†. Otherwise, this is pretty standard as far as C golf goes. `n^b(n)` checks for the inequality of `n` and the black box applied to `n`. When unequal, it calls the fixpoint function `f` again recursively with the application and black box as arguments. Otherwise, it returns the fixpoint.
†Citation needed, I vaguely remember reading this somewhere and google seems to confirm my suspicions
It declares input with K&R-style parameter typing:
```
f(n, b)
int(*b)(_);
{
n=n^b(n)?f(b(n),b):n;
}
```
The arcane bit on the second line above declares `b` to be a function pointer that takes an integer parameter—the default type of `_` is assumed to be an integer. Similarly, `n` is assumed to be an integer, and `f` is assumed to return an integer. Hooray for implicit typing?
[Answer]
# [Clean](https://clean.cs.ru.nl), 46 bytes
```
import StdEnv
p x=hd[n\\n<-iterate f x|f n==n]
```
Assumes the function is defined as `f :: !Int -> Int`
It takes the head of the infinite list of applications of `f f f ... x` filtered for those elements where `f el == el`.
[Try it online!](https://tio.run/##DcutDsIwFAZQv6f4JBMVoLkOBAlukiJu@gNN2rtmK6QkPPsuHH9cDixaZv/KAYWTaCp1Xhqm5s/yHio6Pf1NrJWjSS0s3AIi@jdCiOSukXa2g3CAQR@HqfE/Eyr2urmY@bGquVz19BEuya0/ "Clean – Try It Online")
If you want to change the function in the TIO, Clean's lambda syntax is:
`\argument = expression`
*(actually it's far more complicated, but thankfully we only need unary functions)*
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 14 bytes
```
{⍵=⍺⍺⍵:⍵⋄∇⍺⍺⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT/@f9qhtQvWjni6Nmke9WzW1Dm83qv2fBxbr3Wr7qHcXGG21AuJH3S2POtrhQrX//6cp5CkYcIFIQzBpCiaNjMGUiRGUMgAA "APL (Dyalog Unicode) – Try It Online")
The function at the header is equivalent to `f(x) = floor(sqrt(abs(x)))`
Thanks @Adám for pointing out that the original answer wasn't valid according to PPCG consensus.
### How it works:
```
{⍵=⍺⍺⍵:⍵⋄∇⍺⍺⍵} ⍝ Main 'function' (this is actually an operator)
: ⍝ if
⍵=⍺⍺⍵ ⍝ the right argument (⍵) = the left function (⍺⍺, which is f) of ⍵
⍵ ⍝ return ⍵
⋄ ⍝ else
∇⍺⍺⍵ ⍝ return this function (∇) with argument f(⍵)
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 37 bytes
```
function x=g(f,x);while x-(x=f(x))end
```
[Try it online!](https://tio.run/##y08uSSxL/f8/rTQvuSQzP0@hwjZdI02nQtO6PCMzJ1WhQlejwjZNo0JTMzUv5T8QW6dkFhdopGs4AMWMdCt0DDU1rf8DAA "Octave – Try It Online")
Octave has inline assignment but MATLAB doesn't, so this is a golfier Octave port of [flawr's solution](https://codegolf.stackexchange.com/a/150189/67312).
It also [ports nicely to R](https://codegolf.stackexchange.com/a/150195/67312).
[Answer]
# [Kotlin](https://kotlinlang.org), 50 bytes
```
{f,k->var a=k;var b=a+1;while(b!=a){b=a;a=f(a)};a}
```
[Try it online!](https://tio.run/##XYm9DsIgFIV3n@K6XWJJ2sapCImjs09wm0glRTSANYbw7AirZzh/3/qM1riykYUwIV5cZFxV76BV4KolyJJ0t3K1kQeSq2g5SzoM4nM39obzXhJL9REkNRLLgnLRbwcPMg7JL2GCs/f0PV2jN25RLO2g6lVHtA4DppGbmDsYGPsn/Dg20PcV5fID "Kotlin – Try It Online")
[Answer]
# [Forth](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/) (gforth), 36 bytes
This version just assumes `f` is predefined. It's not as cool as the solution below it. Both programs exit with a stack overflow if not found, or a stack underflow if found (after printing the result).
[**Try it online**](https://tio.run/##S8svKsnQTU8DUf9jFFJS0zLzUhXSuKwU0hSMFIrLEwsUdBWsubhiFApKizMUKh41NXIZ/rdSSFdIKS0AqskvSy1SsFXwdFPQUwjxcPVTKEpNLi0qTlWw/p/@HwA)
```
: g dup f over = IF . THEN recurse ;
```
---
## Forth (gforth), 52 bytes
This allows a function's execution token to be passed as a parameter, and is definitely the cooler solution.
```
: g 2dup execute rot over = IF . THEN swap recurse ;
```
[**Try it online**](https://tio.run/##PY2xCsIwFEX3fMXdqkMFO7Y4Kro4dewi9r2kCElIXmxW/VR/JFYKTpfDOXDZBTG15t@UASPxZAmsWjAaxPnmUaNTaoBP0SB/3i@1/6OYpa0ismBDme5JJmch7kF2qypwaaHRjMljtYTgBO5JAQdcTtihPx@v601YghAJXdHlCw)
### Explanation:
```
: g \ x1 f Define g. Params on the stack. f is on top
2dup execute \ x1 f x2 duplicate both params, execute f(x1)
rot over \ f x2 x1 x2 move x1 to top and copy x2 to top
= IF . THEN compare, if equal, print
swap recurse ; otherwise, recurse
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~31~~ 28 bytes
```
->x,f{x=f[x]until x==f[x];x}
```
[Try it online!](https://tio.run/##KypNqvyfbvtf165CJ626wjYtuiK2NK8kM0ehwhbMsa6o/V9QWlKskB5tqANUVW2kW1Eby5VsC2JXqBrZ2hrYV@gbWRlrVWgb1nJBlRYl5qVoGBoYGGjqKIAUJkeDYEVsbGxt7H8A "Ruby – Try It Online")
[Answer]
# [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp) repl, 28 bytes
```
(d P(q((x)(i(e(f x)x)x(P(f x
```
Assumes that the function `f` is predefined.
[Try it online!](https://tio.run/##TYxBCoAwDATvecUeNzc9@I9@QdBCoIilHurrY1sUTC6zmyGXHXeycrpzQ2Amq9K4M6JqW4ZOrmNEmhQFzOieADQwgStq0zFPvfviwPI/vj8CFvUH "tinylisp – Try It Online") (The example function is `f(x) = (x*2) mod 10`.)
### Ungolfed
```
(load library)
(def P
(lambda (x)
(if (equal? (f x) x)
x
(P (f x)))))
```
If `f(x)` equals `x`, then `x` is a fixed point; return it. Otherwise, recursively look for a fixed point starting from `f(x)` instead of `x`.
[Answer]
# APL NARS 65 chars
```
r←(f v)n;c
c←0⋄→B
E: r←∞⋄→0
A: n←r
B: r←f n⋄c+←1⋄→E×⍳c>1e3⋄→A×⍳r≠n
```
v operator would return ∞ (or possibly -oo or Nan) for error, else one value x with x=f(x).
In test f=floor(sqrt(abs(x))), f1=2-x, f2=c(c(c(x))) with c=x%2==0?x/2:3\*x+1
```
f←⌊∘√∘|
f v 0
0
f v 9
1
f1←{2-⍵}
f1 v 1
1
f1 v ¯10
∞
f1 v 2
∞
c1←{0=2∣⍵:⍵÷2⋄1+3×⍵}
f2←c1∘c1∘c1
f2 v 1
1
f2 v 2
2
f2 v 7
2
f2 v 82
4
```
[Answer]
## Clojure, ~~45~~ 43 bytes
Well, this is the shortest and ugliest:
```
#(loop[a + b %2](if(= a b)a(recur b(% b))))
```
`+` is there instead of a number so that it is not equal to any value of `x0`.
55 bytes and functional:
```
#(reduce(fn[a b](if(= a b)(reduced a)b))(iterate % %2))
```
Example:
```
(def f #(...))
(defn collaz [x] (if (even? x) (-> x (/ 2)) (-> x (* 3) (+ 1))))
(f (->> collaz (repeat 3) (apply comp)) 125)
; 1
```
[Answer]
# Java 8, 42 bytes
This takes a `Function<Integer, Integer>` or `IntFunction<Integer>` and an `int` or `Integer` (curried) and returns the fixed point.
```
f->i->{while(i!=(i=f.apply(i)));return i;}
```
[Try It Online](https://tio.run/##jU9NS8QwED23v2L2lqINelqwpouXBQ@isHoSD9k2rVPTJCTT1bL0t9eIRVD24GFm3ny/18mDzK1TpqvfZjfsNVZQaRkC3Ek0cEyTpRhIUgwNGqmhi1t8INS8GUxFaA3fLuD6RO/W0E87YtUqX57D6cEnI/1475SXZH0JraItfqj6waIhEHOTl5iXx/dX1IrhSjAUDZfO6ZFhlmWFVzR4A1hMc1Kkf9kfLNbQR2FsRx5N@/wC0rch@9KZ/JM4eNm7R7sGAQh5GZ0QsIZNtKuYnMFlEY/txkCq53Yg7uIn0ob9krJwXm5l3@lNiE/YRZSRJlM6zZ8)
Takes advantage of the fact that Java evaluates subexpressions from left to right (so the old `i` is compared to the new), a property which I was unaware of while writing this!
[Answer]
# x86 opcode, 8 bytes
```
fun:
call edx ; 2B
cmpxchg eax, ecx ; 3B, on 8086 use xchg and cmp instead
jnz fun ; 2B
ret ; 1B
```
Take input: `ecx` (value `x0`), `edx` (function address, take input from `ecx`, write result to `eax` without modifying the value of `ecx` and `edx`)
# 8086 opcode, 7 bytes (but slow)
```
xor cx, cx
call dx
loop $-2
ret
```
If there exists a fixed point, looping 65536 times always drive it there.
Take input: `ax` (initial value `x0`), `dx` (function address, take input from `ax`, write output to `ax` without modifying the value of `cx` and `dx`).
Output the fixed point in register `ax`.
[Answer]
# [J](http://jsoftware.com/), 3 bytes
```
^:_
```
[Try it online!](https://tio.run/##PY9BT4QwEIXv8ysmJKZUgbSFC9U1JCaePHl30RCaXd3IsqwGE@Nfx3mVCAde@948vnldkkKNvPGsMsOeTV7cPT7cL1vfLpooHIbhBPemoGk8nSEvPO1eDgEy9zTj@0T7qf/s36ENb9jxN89EHc6pvSovZ/2Mmab4y0mxhRfrGxRTcLjotr6kUEK2lUsMhQracY6@cz9FAgtQYg5HnD54FN13u4GVV9kPq5DOWihUJjDHfffGX2ugSRXLdeIzxfltVE046sQI5ZrU/12KdOSMf5VSsKZglXatrqXbsjXygH0NdSle8RGwpuSaq7jQ6ueVi5PR4FbGuba1q7DnGom7Ynr5BQ "J – Try It Online")
When a conjunction in J is missing an operand, it becomes an adjective. This program produces an adjective which takes as an argument a verb. `^:` is the *power* or "repeat" verb, and the idiom `f^:_`, that is, `f` repeated infinitely, is J's [*limit application*](https://www.jsoftware.com/help/dictionary/d202n.htm), which exactly solves this challenge:
>
> An infinite power `n` produces the limit of the application of `u` .
>
>
>
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 30 bytes
```
[pq][Smrd3Rd3Rxd3R=mLmlmx]dsmx
```
[Try it online!](https://tio.run/##S0n@Hx1roKCcmZKaV5JZUqmglFaal1ySmZ@npJCYl6JQlVqU/z@6oDA2Oji3KMU4CIgqgNg21yc3J7ciNqU4t@L/fwA "dc – Try It Online")
Takes as input the function in the form of a macro and initial value on the stack(pushed in that order). Prints the fixed point.
[Answer]
# Perl 5, 18 + 1 (`-p`)
```
$_=f$_ while$_^f$_
```
[try it online](https://tio.run/##K0gtyjH97@Tq7ulXXVyapJBWnZlXomeqrRIfbRCrb6xnaFJb@18l3jZNJV6hPCMzJ1UlPg7I/v/f0OBffkFJZn5e8X/dAgA)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 1 byte
```
Ẋ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCLOuzIkLTtcbjEiLCLhuooiLCIiLCIiXQ==)
Builtin lol
[Answer]
# [J-uby](https://github.com/cyoce/J-uby), 3 bytes
J-uby has a built-in operator for this:
```
:!~
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700K740qXLBIjfbpaUlaboWi60U6yCsm1ppCrYKunYV1QoaFfq-iSUZVlYBnpp6RfmleSkKtVxcBQpuehppOgqGBpoQHQsWQGgA)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 14 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
gOvV
¥W?U:ßW
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=CgpnT3ZWCqVXP1U631c&input=MTQyMzU0NgoiQFhhIHEgZn0i)
Japt doesn't have any built-in "repeat until the output is constant" functionality, or the ability to take functions directly as input. This program takes `x` as the first input, and a string defining a Japt function as the second input.
Explanation:
```
/n # Store first input as U
/n # Store second input as V
gOvV
OvV # Interpret V as Japt code
g # Apply that function to U
# Store the result as W
¥W # Check whether U and W are the same
?U # If they are, output U
:ßW # Otherwise repeat the program with W and V as the inputs
```
A [theoretical alternative](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=pWdWID9VOt9VZ1Y&input=MTQyMzU0NgoiQFhhIHEgZn0i) would work if the function were assumed to already be stored in V, but there isn't really a good way to actually accomplish that in Japt so it's not really a reasonable input method.
] |
[Question]
[
**Story:**
Lucy asked George what his Lucky Number was. After some contemplation, George replied that he had several Lucky Numbers. After some brief confusion, Lucy asked George what his first `n` Lucky Numbers are. George then asked you, his buddy, to write him a program to do the work for him.
**The Challenge:**
You will write a program/function that will receive from standard input/function argument a string or integer `n`. The program/function will then return/output the first `n` [Lucky Numbers](http://en.wikipedia.org/wiki/Lucky_number). Lucky numbers are defined via a sieve as follows.
Start with the positive integers:
```
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, ...
```
Now remove every second number:
```
1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, ...
```
The second remaining number is **3**, so remove every third number:
```
1, 3, 7, 9, 13, 15, 19, 21, 25, ...
```
Now the next remaining number is **7**, so remove every seventh number:
```
1, 3, 7, 9, 13, 15, 21, 25, ...
```
Next, remove every ninth number and so on. The resulting sequence are the lucky numbers.
**Winning:**
As usual for codegolf, fewest bytes wins.
As usual, submissions using [standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/32700) are disqualified.
[Answer]
# Python 2, 79
```
n=input()
L=range(1,2**n)
for r in L:r+=r<2;map(L.remove,L[r-1::r])
print L[:n]
```
The magic of iterating over a list as the loop modifies it!
The list `L` starts with all the integers `1` to a sufficiently high value. The code iterates over each element `r` of `L`, taking the sublist of every `r`'th element, and removing each of those values. As a result, the removed values aren't iterated over. At the end, print the first `n` elements.
The expression `map(A.remove,B)` is a trick I've been waiting a long time to use. It calls `A.remove` for each element of `B`, which causes all the elements of `B` to removed from `A`. Effectively, it takes the list difference, though it requires `B` to be a sublist of `A`. It requires Python 2, since Python 3 wouldn't actually evaluate the map.
The first loop needs to be special-cased to convert `r` from `1` to `2`, as `r+=r<2`.
The sufficiently high upper bound of `2**n` makes the program very slow for large values of `n`. Using `n*n+1` suffices, but costs a character. Note that `n*n` doesn't work for `n=1`.
[Answer]
# Haskell, ~~71~~ 69 bytes
```
s(n:k)p=n:s[m|(i,m)<-zip[p..]k,i`mod`n>0](p+1)
f n=take n$1:s[3,5..]3
```
Defines a function `f`. The expression `1:s[3,5..]3` evaluates to the infinite list of lucky numbers, and `f` simply takes the first `n` of them by `take n`.
```
f 20
[1,3,7,9,13,15,21,25,31,33,37,43,49,51,63,67,69,73,75,79]
```
I could shave off 5 bytes from the sieve using a parallel list comprehension
```
s(n:k)p=n:s[m|m<-k|i<-[p..],i`mod`n>0](p+1)
```
but that would require passing the humongous compiler flag `-XParallelListComp` to GHC to enable the extension.
### Explanation of the sieve
```
s(n:k)p= -- Sieving a list with head n and tail k with accumulator p is
n: -- the head n, followed by
s[m| -- the result of sieving the list of numbers m
(i,m)<-zip[p..]k, -- where (i,m) is drawn from [(p,k_0),(p+1,k_1),(p+2,k_2),..] and
i`mod`n>0] -- i does not divide n,
(p+1) -- using p+1 as the accumulator
```
The basic idea is that `s(n:k)p` produces the `(p-1)`th lucky number `n`, drops every `n`th number from the infinite tail `k` (offset by `p` to account for the numbers produced earlier), and recurses to that list with accumulator `(p+1)`. In `f`, we initialize the process with the odd numbers starting from `3`, and tack `1` to the front, obtaining exactly the lucky numbers.
[Answer]
# Python 2, ~~71 69~~ 67
At first, I thought this would be a great challenge for Python's array slicing. However, I encountered a stumbling block when I discovered that slices with a step other than 1 can only have another slice of identical length assigned to them. But after googling "python remove slice", my faith was restored: I found a funky `del` statement that does the trick perfectly.
```
n=input()
l=range(n*n+9)
for v in l:del l[v&~1::v or 2]
print l[:n]
```
**Old version**
```
n=input()
l=range(1,n*n+9)
for v in l:del l[v-1%v::v+1/v]
print l[:n]
```
-2 bytes thanks to Sp3000.
[Answer]
# CJam - 25
```
Lri{1$W%{1$\(1e>/+}/)+}/p
```
[Try it online](http://cjam.aditsu.net/#code=Lri%7B1%24W%25%7B1%24%5C(1e%3E%2F%2B%7D%2F)%2B%7D%2Fp&input=100)
**Explanation:**
This implementation doesn't remove numbers successively from an array, but calculates each number based on how many would have been removed before it.
For each index i (from 0 to n-1) and each previous lucky number l, in reverse order, we increment i by i/(l-1), except for l=1 we use 1 instead of 0, and also add 1 at the end.
E.g. for i=4 we have the first 4 numbers, [1 3 7 9], and calculate:
4 + 4/(9-1) = 4
4 + 4/(7-1) = 4
4 + 4/(3-1) = 6
6 + 6/1 = 12
12 + 1 = 13
```
L empty array - the first 0 lucky numbers :)
ri read and convert to integer (n)
{…}/ for each number (i) from 0 to n-1
1$ copy the previous array
W% reverse the order
{…}/ for each array element (l)
1$ copy i
\( swap with l and decrement l
1e> use 1 if l=1
/+ divide and add to i
)+ increment and add the new lucky number to the array
p pretty print
```
[Answer]
# [><>](http://esolangs.org/wiki/Fish), ~~121~~ ~~114~~ 111 bytes
```
i2+:&:*1\
:})?v:2+>l{
nao2\r~1
)?vv>1+:&:&=?;:[{::nao}]$}l1-[01+}:l3-$%$l1-@@-{$[{~l1
3.\ ff+
!?:<]-1v
~]{43. >
```
I have only a few words to say...
... "Argh my brain hurts."
---
## Explanation
><> is a 2D esoteric programming language and is *definitely* not suited for this task, due to its lack of arrays. In fact, the only data type in ><> is strange mix of int/float/char, and everything happens on a stack of stacks.
Here's the rundown:
```
Line 1: i2+:&:*1\
i2+:& Read a char as input (n) and add 2, copying n+2 into the register
:* Duplicate and multiply, giving (n+2)^2 on the stack
1\ Push 1 and go to the next line
Line 2: >l{:})?v:2+
l{:})?v Go to the next line if the stack's length is greater than (n+2)^2
:2+ Otherwise duplicate the top of the stack and add 2 to it
Line 3: \r~1nao2
r~ Reverse the stack and pop; stack contains the first (n+2)^2 odd integers
1nao Print 1 (special case)
2\ Push 2 (let's call this "i" for "iterations") and go to the next line
Line 4: >1+:&:&=?;:[{::nao}]$}l1-[01+}:l3-$%$l1-@@-{$[{~l1)?vv
1+ Increment i
:&:&=?; If i is equal to n+2 (+2 because we started at 2), halt
:[{::nao}]$} Print the i-th element down (the next lucky number) and also
copy it to the top of the stack, while moving i to the bottom
l1-[ Move everything but i to a new stack
0 Push 0 (let's call this "r" for recursion depth)
Sieve loop:
1+ Increment r
}:l3-$%$l1-@@-{$[ Move everything up to the last element to be sieved out to a new stack
{~ Remove said last element
1)?vv If the length is 1, go to line 6 (sieving complete)
Otherwise go to line 5, which repeats this sieve loop by teleporting
Line 6: :?!v1-]
:?!v1-] Keep unrolling and decrementing r until r is 0
Line 7: >~]{43.
~] Pop r and unroll once more (to the stack where i waits)
43. Loop, performing everything from line 4 all over again
```
Here's a mock example which demonstrates roughly how the sieving works (here `k` is the lucky number which we sieve with):
```
[[15 13 11 9 7 5 3 1 k=3 r=0]] -- move -->
[[15 13] [11 9 7 5 3 1 k=3 r=1]] -- pop -->
[[15 13] [9 7 5 3 1 k=3 r=1]] -- move -->
[[15 13] [9 7] [5 3 1 k=3 r=2]] -- pop -->
[[15 13] [9 7] [3 1 k=3 r=2]] -- move -->
[[15 13] [9 7] [3 1] [k=3 r=3]] -- pop -->
[[15 13] [9 7] [3 1] [r=3]] (now we unroll)
```
[Answer]
# Pyth: ~~23~~ 22 bytes
```
<u-G%@GhH+0GQ%2r1^hQ2Q
```
Try it online: [Pyth Compiler/Executor](https://pyth.herokuapp.com/)
## Explanation:
```
<u-G%@GhH+0GQ%2r1^hQ2Q Q = input()
%2r1^hQ2 create the list [1, 2, ..., (Q+1)^2-1][::2]
u Q%2r1^hQ2 G = [1, 2, ..., (Q+1)^2-1][::2]
modify G for each H in [0, 1, 2, ..., Q]:
-G%:GhH+0G G = G - ([0] + G)[::G[H+1]]
(minus is remove in Pyth)
< Q print the first Q elements of the resulting list
```
The reduce actually calculates more than `Q` lucky numbers (the remove command is called Q+1 times, Q-1 should be enough).
[Answer]
## R, 58 bytes
```
n=scan();s=r=1:n^2;for(j in 1:n)r=r[-max(2,r[j])*s];r[1:n]
```
With line breaks:
```
n=scan() #user input
s=r=1:n^2 #declare r and s simultaneously, both large enough to sieve
for(j in 1:n)
r=r[-max(2,r[j])*s] #iteratively remove elements by position in vector
r[1:n] #print
```
### Previous version, 62 bytes
```
function(n){
s=r=1:n^2 #declare r and s simultaneously, both large enough to sieve
for(j in 1:n)
r=r[-max(2,r[j])*s] #iteratively remove elements by position in vector
r[1:n] #print
}
```
### Previous version, 78 bytes
```
n=as.numeric(readline()) #ask for user input and convert it to numeric
r=1:n^2 #create a large enough vector to sieve
for(j in 1:n){ #loop
r=r[-max(2,r[j])*1:n^2] #iteratively remove elements by position in vector
}
r[1:n] #print
```
[Answer]
# CJam, ~~32~~ 30 bytes
```
3ri:N#,N{0\__I1e>)=%-+}fI(;N<p
```
Takes input from STDIN.
**Code explanation**:
```
3ri:N#, "Read the input in N and get first 3^N whole numbers";
N{0\__I1e>)=%-+}fI "Run the code block N times, storing index in I";
0\__ "Put 0 before the array and take 2 copies";
I1e>)= "Take min(2, I + 1) th index from the copy";
% "Take every array[ min (2, I + 1)] element from the array";
-+ "Remove it from the list and prepend 0 to the list";
(;N<p "Print number index 1 to N";
```
[Try it online here](http://cjam.aditsu.net/#code=3ri%3AN%23%2CN%7B0%5C__I1e%3E)%3D%25-%2B%7DfI(%3BN%3Cp&input=2)
[Answer]
# Python 2, ~~105~~ 101 bytes
```
n=input()
L=range(-1,n*n+9,2)
i=2
while L[i:]:L=sorted(set(L)-set(L[L[i]::L[i]]));i+=1
print L[1:n+1]
```
Just a straightforward implementation.
# Pyth, ~~39~~ ~~36~~ ~~35~~ 32 bytes
```
J%2r1h^Q2VJI>JhN=J-J%@JhN+2J;<JQ
```
Similar to the approach above, but things are 0-indexed rather than 1-indexed. [Try it online](https://pyth.herokuapp.com/).
Thanks to @Jakube for pointing out a byte saving.
[Answer]
# Perl, 86 81 78
86:
```
@a=(1..($k=<>)**2);for$n(@a){$i=1;@a=map{$i++%($n+($n<2))?$_:()}@a;$k-=$k&&print"$n "}
```
UPDATE: obviously, `grep{...}` is better than `map{...?$_:()}`
81:
```
@a=(1..($k=<>)**2);for$n(@a){$i=1;@a=grep{$i++%($n+($n<2))}@a;$k-=$k&&print"$n "}
```
UPDATE: OK, actually a one-liner now. I can stop. (?)
78:
```
@a=(1..($k=<>)**2);for$n(@a){$k-=$i=$k&&print"$n ";@a=grep{$i++%($n+=$n<2)}@a}
```
[Answer]
# Mathematica, 80 bytes
```
(For[l=Range[#^2];i=1,(m=l[[i++]]~Max~2)<=Length@l,l=l~Drop~{m,-1,m}];l[[;;#]])&
```
Straight-forward implementation of the definition. As some other answers, starts with a range from `1` to `n2` and then keeps filtering.
[Answer]
# J, ~~60~~ 52 bytes
```
({.}.@((>:@{.,]#~0<({~{.)|i.@#)@]^:[2,1+2*i.@*:@>:)) 8
1 3 7 9 13 15 21 25
```
Explanation (from right to left):
```
2,1+2*i.@*:@>: generates the list 2 1 3 5 7 9... with (n+1)^2 odd numbers
^:[ repeats n times the following
@] using the list
0<({~{.)|i.@# is the remainder of the indexes of the lists elements with the first element positive (i.e. index divisible by first element)
]#~ keep those elements from the list
>:@{., concatenate a first element with the value of the current one +1
}.@ drop first element
{. take the first n element
```
`2,1+2*i.@*:@>:` seems way too long but I can only shorten it by 1 byte swapping `*:` with `!` making the list grow exponentially.
[Answer]
# JavaScript (ES6) 96 ~~99~~
**Edit** Counting down in first loop - thanks @DocMax
```
F=n=>(i=>{
for(o=[1];--i;)o[i]=i-~i;
for(;++i<n;)o=o.filter((x,j)=>++j%o[i]);
})(n*n)||o.slice(0,n)
```
**Ungolfed**
```
F=n=>{
for (i = n*n, o = [1]; --i;)
o[i] = i+i+1;
for (; ++i < n; )
o = o.filter((x, j) => (j+1) % o[i])
return o.slice(0,n)
}
```
**Test** In Firefox / FireBug console
```
F(57)
```
*Output*
```
[1, 3, 7, 9, 13, 15, 21, 25, 31, 33, 37, 43, 49, 51, 63, 67, 69, 73, 75, 79, 87, 93, 99, 105, 111, 115, 127, 129, 133, 135, 141, 151, 159, 163, 169, 171, 189, 193, 195, 201, 205, 211, 219, 223, 231, 235, 237, 241, 259, 261, 267, 273, 283, 285, 289, 297, 303]
```
[Answer]
# Octave, ~~139~~ ~~83~~ 72
```
function r=l(n)r=1:2:n^2;for(i=2:n)h=r(i);r(h:h:end)=[];end;r=r(1:n);end
```
Ungolfed:
```
function r=l(n)
r=1:2:n^2;
for(i=2:n)
h=r(i);
r(h:h:end)=[];
end
r=r(1:n); # reduce it to only N lucky numbers
end
```
[Answer]
# Matlab, 104 bytes
```
function x=f(n)
k=1;N=n;x=0;while nnz(x)<n
x=1:N;m=1;while m-nnz(x)
m=x(x>m);x(m:m:end)=[];end
N=N+2;end
```
With thanks to @flawr for very appropriate comments and suggestions.
Example from Matlab command prompt:
```
>> f(40)
ans =
Columns 1 through 22
1 3 7 9 13 15 21 25 31 33 37 43 49 51 63 67 69 73 75 79 87 93
Columns 23 through 40
99 105 111 115 127 129 133 135 141 151 159 163 169 171 189 193 195 201
```
[Answer]
# [Julia](http://julialang.org/), 66 bytes
```
x->(l=[1:x^2;];[deleteat!(l,(i+=i<2):i:length(l)) for i=l];l[1:x])
```
[Try it online!](https://tio.run/##TVDRasMwDHzfV3h9splXIjmJE2fZ274iZFBWZ/MwaSkp5O8zXRhsL/LpTjod/r7ndKJ1m/ptfX7VuR8orO/cjd1wjjku8bQ86mx1eurTC5uQQo7z5/KlszFqutxU6vPYZWyNZrve0rzk@aino6bAhTEPv5SedPW/Pbyt1/ixxHM4/JEDWeWs8la1VpEgqqxiIVleB1E4J3IpbykzlXC14Fq4WnqPbZn1ghvYSN/CqxCSiFCA2KPsR3DFgSuhVnuBAFuCJ3lwDRDsqEWmAqGKPR0QicosKiMlw4@Rk8s9PNQaCDkZIbnZC@bgzK0IrnDyhT8 "Julia 1.0 – Try It Online")
[Answer]
# Bash+coreutils, 136
I'd hoped to golf this down more, but oh well. Not every day that you pipe into a recursive function in a shell script:
```
f(){
mapfile -tn$2 a
(($1>$2))&&{
tr \ \\n<<<${a[@]}
sed $[${a[-1]}-$2]~${a[-1]}d
}|f $1 $[$2+1]||echo ${a[@]}
}
yes|sed -n 1~2=|f $1 2
```
### Output:
```
$ ./lucky.sh 23
1 3 7 9 13 15 21 25 31 33 37 43 49 51 63 67 69 73 75 79 87 93 99
$
```
---
# Bash+coreutils, 104
Shorter using a more straightforward implementation:
```
a=(`seq 1 2 $[3+$1**2]`)
for((;i++<$1;));{
a=($(tr \ \\n<<<${a[@]}|sed 0~${a[i]}d))
}
echo ${a[@]:0:$1}
```
[Answer]
# MATLAB, 62 characters
```
n=input('');o=1:2:n^2;for i=2:n;o(o(i):o(i):end)=[];end;o(1:n)
```
I misinterpreted the challenge at first - my revised version is now actually shorter.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~17~~ 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
∞IFD®LKн©ô€¨˜}I£
```
[Try it online.](https://tio.run/##AScA2P9vc2FiaWX//@KInklGRMKuTEvQvcKpw7TigqzCqMucfUnCo///MTU)
**Explanation:**
```
∞ # Push an infinite positive list: [1,2,3,...]
IF # Loop the input amount of times:
D # Duplicate the infinite list
®L # Push a list in the range [1,`®`]
# (`®` is -1 by default, so the list is [1,0,-1] the first iteration)
K # Remove all those values from the duplicated list
н # Pop the list and leave the first (smallest) value
# (this is basically the smallest value above `®`)
© # Store it as new `®` (without popping)
ô # Split the infinite list into parts of size `®`
۬ # Remove the last item of each inner list
˜ # Flatten it back to a single list
}I£ # After the loop: only leave the first input amount of values
# (after which the list is output implicitly as result)
```
[Answer]
# Go, 326
```
package main
import"fmt"
func s(k, p int,in chan int)chan int{
o := make(chan int)
go func(){
for p>0{
o<-<-in;p--
}
for{
<-in
for i:=1;i<k;i++{o<-<-in}
}
}()
return o
}
func main(){
n := 20
fmt.Print(1)
c := make(chan int)
go func(c chan int){
for i:=3;;i+=2{c<-i}
}(c)
for i:=1;i<n;i++{
v := <-c
fmt.Print(" ", v)
c = s(v, v-i-2, c)
}
}
```
Straight forward implementation using goroutine and pipes to make sieves.
[Answer]
## Racket 196 bytes
Produces lucky numbers upto n:
```
(λ(n)(let loop((l(filter odd?(range 1 n)))(i 1))(define x(list-ref l i))(set! l(for/list((j(length l))
#:unless(= 0(modulo(add1 j)x)))(list-ref l j)))(if(>= i(sub1(length l)))l(loop l(add1 i)))))
```
Ungolfed version:
```
(define f
(λ(n)
(let loop ((l (filter odd? (range 1 n))) (i 1))
(define x (list-ref l i))
(set! l (for/list ((j (length l)) #:unless (= 0 (modulo (add1 j) x)))
(list-ref l j)))
(if (>= i (sub1 (length l)))
l
(loop l (add1 i)))))
)
```
Testing:
```
(f 100)
```
Output:
```
'(1 3 7 9 13 15 21 25 31 33 37 43 49 51 63 67 69 73 75 79 87 93 99)
```
] |
[Question]
[
The goal of this code golf is to draw a regular polygon (one with equal side lengths) given the number of sides and radius (distance from center to vertex).
* The number of sides and the radius can be entered via a file, STDIN, or just a plain old variable. Use whatever is shorter in your language.
* -25% of total characters/bytes if the image is actually drawn instead of ASCII art.
[Answer]
**LOGO 37 - 25% = 27.75 (with variables)**
```
REPEAT:S[FD:R*2*sin(180/:S)RT 360/:S]
```
**LOGO 49 - 25% = 36.75 (as a function)**
```
TO P:R:S REPEAT:S[FD:R*2*sin(180/:S)RT 360/:S]END
```
**Triangle**
*Called with variables*
```
Make "R 100
Make "S 3
REPEAT:S[FD:R*2*sin(180/:S)RT 360/:S]
```
*Used as a function* `P 100 3`

**Square**
*Called with variables*
```
Make "R 100
Make "S 4
REPEAT:S[FD:R*2*sin(180/:S)RT 360/:S]
```
*Used as a function* `P 100 4`

**Pentagon**
*Called with variables*
```
Make "R 100
Make "S 5
REPEAT:S[FD:R*2*sin(180/:S)RT 360/:S]
```
*Used as a function* `P 100 5`

**Decagon**
*Called with variables*
```
Make "R 100
Make "S 10
REPEAT:S[FD:R*2*sin(180/:S)RT 360/:S]
```
*Used as a function* `P 100 10`

**Circle**
*Called with variables*
```
Make "R 100
Make "S 360
REPEAT:S[FD:R*2*sin(180/:S)RT 360/:S]
```
*Used as a function* `P 100 360`

[Answer]
## Mathematica, 40 - 25% = 30
```
ListPolarPlot[r&~Array~n]/.PointPolygon
```

[Answer]
## Java 8 : ~~533~~ 322 - 25% = 241.5
Well, it's Java :/ Just draws lines, point to point. Should work for any arbitrarily sized polygon. Cut it down quite a bit from original size. Huge credit to Vulcan (in comments) for the golf lesson.
```
import java.awt.*;class D{public static void main(String[]v){new Frame(){public void paint(Graphics g){int i=0,r=Short.valueOf(v[0]),s=Short.valueOf(v[1]),o=r+30,x[]=new int[s],y[]=x.clone();for(setSize(o*2,o*2);i<s;x[i]=(int)(Math.cos(6.28*i/s)*r+o),y[i]=(int)(Math.sin(6.28*i++/s)*r+o));g.drawPolygon(x,y,s);}}.show();}}
```
Line Breaks:
```
import java.awt.*;
class D{
public static void main(String[]v){
new Frame(){
public void paint(Graphics g){
int i=0,r=Short.valueOf(v[0]),s=Short.valueOf(v[1]),o=r+30,x[]=new int[s],y[]=x.clone();
for(setSize(o*2,o*2);i<s;x[i]=(int)(Math.cos(6.28*i/s)*r+o),y[i]=(int)(Math.sin(6.28*i++/s)*r+o));
g.drawPolygon(x,y,s);
}
}.show();
}
}
```
Input is arguments [radius] [sides]:
```
java D 300 7
```
Output:

[Answer]
# TeX/TikZ (60 – 80.25)
File `polygon.tex`:
```
\input tikz \tikz\draw(0:\r)\foreach\!in{1,...,\n}{--(\!*360/\n:\r)}--cycle;\bye
```
(80 bytes)
The radius and number of sides are provided as variables/macros `\r` and `\n`.
Any TeX unit can be given for the radius. Without unit, the default unit `cm` is used. Examples:
```
\def\r{1}\def\n{5} % pentagon with radius 1cm
\def\r{10mm}\def\n{8} % octagon with radius 10mm
```
(16 bytes without values)
If the page number should be suppressed, then it can be done by
```
\footline{}
```
(11 bytes)
Examples for generating PDF files:
```
pdftex "\def\r{1}\def\n{3}\input polygon"
```
>
> 
>
>
>
```
pdftex "\def\r{1}\def\n{5}\input polygon"
```
>
> 
>
>
>
```
pdftex "\def\r{1}\def\n{8}\input polygon"
```
>
> 
>
>
>
```
pdftex "\def\r{1}\def\n{12}\input polygon"
```
>
> 
>
>
>
**Score:**
It is not clear to, what needs counting. The range for the score would be:
* The base code is 80 bytes minus 25% = **60**
* Or all inclusive (input variable definitions, no page number): (80 + 16 + 11) minus 25% = **80.25**
* If the connection between the first and last point do not need to be smooth, then `--cycle` could be removed, saving 7 bytes.
[Answer]
## [Geogebra](http://www.geogebra.org), 42 – 25% = 31.5 bytes
If you count in characters instead of bytes, this would be 41 – 25% = 30.75 characters.
(That is, if you consider Geogebra a language...)
Assumes the radius is stored in the variable `r` and the number of sides stored in the variable `s`.
```
Polygon[(0,0),(sqrt(2-2cos(2π/s))r,0),s]
```
This uses the cosine theorem *c*2 = *a*2 + *b*2 – 2 *a b* cos *C* to calculate the side length from the given radius.
Sample output for `s`=7, `r`=5

[Answer]
# C, 359 Chars
My first attempt at golfing. At least it beats the Java solution ;-)
```
int r,n,l,g,i,j,x,y;char* b;float a,c,u,z,p,q,s,t;main(int j,char**v){r=atoi(v[1]);b=malloc(g=(l=r*2+1)*r*2+1);memset(b,32,g);for(j=g-2;j>0;j-=l){b[j]='\n';}b[g-1]=0;a=2*3.14/(n=atoi(v[2]));for(;i<=n;i++,p=s,q=t){c=i*a;s=sin(c)*r+r;t=cos(c)*r+r;if(i>0){u=(s-p)/r,z=(t-q)/r;for(j=0;j<r;j++){x=p+u*j;y=q+z*j;if(x>=0&&y>=0&&y<r*2&&x<l-1)b[y*l+x]='#';}}}puts(b);}
```
ungolfed:
```
int r,n,l,g,i,j,x,y;
char* b;
float a,c,u,z,p,q,s,t;
main(int j,char**v){
r=atoi(v[1]);
b=malloc(g=(l=r*2+1)*r*2+1);
memset(b,32,g);
for(j=g-2;j>0;j-=l){b[j]='\n';}
b[g-1]=0;
a=2*3.14/(n=atoi(v[2]));
for(;i<=n;i++,p=s,q=t){
c=i*a;s=sin(c)*r+r;t=cos(c)*r+r;
if(i>0){
u=(s-p)/r,z=(t-q)/r;
for(j=0;j<r;j++){
x=p+u*j;y=q+z*j;
if(x>=0&&y>=0&&y<r*2&&x<l-1)b[y*l+x]='#';
}
}
}
puts(b);
}
```
And it's the only program that outputs the polygon in ASCII instead of drawing it. Because of this and some floating point rounding issues, the output doesn't look particularly pretty (ASCII Chars are not as high as wide).
```
######
### ###
#### ####
### ###
### ####
### ###
# #
# ##
# #
# #
## ##
# #
## ##
# #
# #
## ##
# #
## ##
# #
# #
# #
# #
## ##
# #
## ##
# #
# #
## ##
# #
## ##
# #
# #
# ##
# #
### ###
### ####
### ###
### ####
### ###
######
```
[Answer]
# C: 229 180
```
#include<stdio.h>
#include<math.h>
main(){float n=5,r=10,s=tan(1.57*(1.-(n-2.)/n))*r*2.,i=0,j,x,c,t;int u,v;for(;i<n;i++)for(j=0;j<s;j++)x=i*6.28/n,c=cos(x),t=sin(x),x=j-s/2.,u=c*r+t*x+r*2.,v=-t*r+c*x+r*2,printf("\e[%d;%dH*",v,u);}
```
(r is radius of incircle)
Please run in ANSI terminal
[](https://i.stack.imgur.com/YlVLm.jpg)
### Edit:
* take ace's suggestion
* use old variables (or #define) as input
* use circumcircle radius now
```
u;main(v){float p=3.14,r=R*cos(p/n),s=tan(p/n)*r*2,i=0,j,x,c,t;for(;i++<n;)for(j=0;j<s;)x=i*p/n*2,c=cos(x),t=sin(x),x=j++-s/2,u=c*r+t*x+r*2,v=c*x-t*r+r*2,printf("\e[%d;%dH*",v,u);}
```
compile:
```
gcc -opoly poly.c -Dn=sides -DR=radius -lm
```
[Answer]
## Mathematica, 54 \* 75% = 40.5
```
Graphics@Polygon@Table[r{Cos@t,Sin@t},{t,0,2Pi,2Pi/n}]
```
I don't even think there's a point for an ungolfed version. It would only contain more whitespace.
Expects the radius in variable `r` and number of sides in variable `n`. The radius is a bit meaningless without displaying axes, because Mathematica scales all images to fit.
Example usage:

[Answer]
# HTML/JavaScript : ~~215 - 25% = 161.25~~, 212 - 25% = 159
```
<canvas><script>R=100;i=S=10;c=document.currentScript.parentNode;c.width=c.height=R*2;M=Math;with(c.getContext("2d")){moveTo(R*2,R);for(;i-->0;){a=M.PI*2*(i/S);lineTo(R+M.cos(a)*R,R+M.sin(a)*R)}stroke()}</script>
```
Ungolfed version :
```
<canvas><script>
var RADIUS = 100;
var SIDES_COUNT = 10;
var canvas = document.currentScript.parentNode;
canvas.width = canvas.height = RADIUS * 2;
var context = canvas.getContext("2d");
context.moveTo(RADIUS * 2, RADIUS);
for(i = 1 ; i <= SIDES_COUNT ; i++) {
var angle = Math.PI * 2 * (i / SIDES_COUNT);
context.lineTo(
RADIUS + Math.cos(angle) * RADIUS,
RADIUS + Math.sin(angle) * RADIUS
);
}
context.stroke();
</script>
```
[Answer]
## Postscript 156 - 25% = 117
```
translate exch 1 exch dup dup scale div currentlinewidth mul setlinewidth
1 0 moveto dup{360 1 index div rotate 1 0 lineto}repeat closepath stroke showpage
```
Pass the radius, number of sides, and center point on the command line
```
gs -c "100 9 300 200" -- polyg.ps
```
or prepend to the source
```
echo 100 9 300 200 | cat - polyg.ps | gs -
```
Translate to the center, scale up to the radius, move to (1,0); then repeat n times:
rotate by 360/n, draw line to (1,0); draw final line, stroke and emit the page.
[Answer]
## [Sage](http://www.sagemath.org/), 44 - 25% = 33
Assumes the number of sides is stored in the `s` variable and the radius is stored in the `r` variable.
```
polytopes.regular_polygon(s).show(figsize=r)
```
Sample output:
`s`=5, `r`=3

`s`=5, `r`=6

`s`=12, `r`=5

[Answer]
# bc + ImageMagick + xview + bash, 104.25 (139 bytes - 25%)
This challenge would be incomplete without an ImageMagick answer...
```
convert -size $[$2*2]x$[$2*2] xc: -draw "polygon `bc -l<<Q
for(;i++<$1;){t=6.28*i/$1;print s(t)*$2+$2,",";c(t)*$2+$2}
Q`" png:-|xview stdin
```
For example, `./polygon.sh 8 100` produces this image:

[Answer]
**JavaScript 584 (867 ungolfed)**
This code uses N Complex Roots of unity and translates the angles to X,Y points. Then the origin is moved to centre of the canvas.
*Golfed*
```
function createPolygon(c,r,n){
c.width=3*r;
c.height=3*r;
var t=c.getContext("2d");
var m=c.width/2;
t.beginPath();
t.lineWidth="5";
t.strokeStyle="green";
var q=C(r, n);
var p=pts[0];
var a=p.X+m;
var b=p.Y+m;
t.moveTo(a,b);
for(var i=1;i<q.length;i++)
{
p=q[i];
t.lineTo(p.X+m,p.Y+m);
t.stroke();
}
t.lineTo(a,b);
t.stroke();
}
function P(x,y){
this.X=x;
this.Y=y;
}
function C(r,n){
var p=Math.PI;
var x,y,i;
var z=[];
var k=n;
var a;
for(i=0;i<k;i++)
{
a = 2*i*p/n;
x = r*Math.cos(a);
y = r*Math.sin(a);
z.push(new P(x,y));
}
return z;
}
```
Sample output:

*Ungolfed*
```
function createPolygon(c,r,n) {
c.width = 3*r;
c.height = 3*r;
var ctx=c.getContext("2d");
var mid = c.width/2;
ctx.beginPath();
ctx.lineWidth="5";
ctx.strokeStyle="green";
var pts = ComplexRootsN(r, n);
if(null===pts || pts.length===0)
{
alert("no roots!");
return;
}
var p=pts[0];
var x0 = p.X + mid;
var y0 = p.Y + mid;
ctx.moveTo(x0,y0);
for(var i=1;i<pts.length;i++)
{
p=pts[i];
console.log(p.X +"," + p.Y);
ctx.lineTo(p.X + mid, p.Y + mid);
ctx.stroke();
}
ctx.lineTo(x0,y0);
ctx.stroke();
}
function Point(x,y){
this.X=x;
this.Y=y;
}
function ComplexRootsN(r, n){
var pi = Math.PI;
var x,y,i;
var arr = [];
var k=n;
var theta;
for(i=0;i<k;i++)
{
theta = 2*i*pi/n;
console.log('theta: ' + theta);
x = r*Math.cos(theta);
y = r*Math.sin(theta);
console.log(x+","+y);
arr.push(new Point(x,y));
}
return arr;
}
```
This code requires HTML5 canvas element, c is canvas object, r is radius and n is # of sides.
[Answer]
## PHP 140 - 25% = 105
```
<?
for(;$i++<$p;$a[]=$r-cos($x)*$r)$a[]=$r-sin($x+=2*M_PI/$p)*$r;
imagepolygon($m=imagecreatetruecolor($r*=2,$r),$a,$p,0xFFFFFF);
imagepng($m);
```
Assumes two predefined variables: `$p` the number of points, and `$r` the radius in pixels. Alternatively, one could prepend `list(,$r,$p)=$argv;` and use command line arguments instead. Output will be a png, which should be piped to a file.
---
### Output
`$r=100; $p=5;`

`$r=100; $p=6;`

`$r=100; $p=7;`

`$r=100; $p=50;`

[Answer]
# HTML + JavaScript, 12 + 127 = 139 bytes
```
<canvas id=c
```
```
s=>r=>(g=n=>n?g(n-1,d.lineTo(r+r*M.cos(x=M.PI*2*n/s),r+r*M.sin(x))):d.fill())(s,c.width=c.height=r+r,d=c.getContext`2d`,M=Math)
```
[Try it on Codepen](https://codepen.io/PeterShaggyNoble/pen/rNLMgwN)
# HTML (SVG) + JavaScript, 20 + 140 = 160 bytes
```
<svg id=c><path id=p
```
```
s=>r=>p.setAttribute(`d`,`M${M=Math,v=c.style,v.width=v.height=r+r},`+r+(g=n=>n?`L${r+r*M.cos(x=M.PI*2*n/s)},`+(r+r*M.sin(x))+g(n-1):``)(s))
```
[Try it on Codepen](https://codepen.io/PeterShaggyNoble/pen/ExyNxEo)
[Answer]
# [R](https://www.r-project.org/), 42 bytes -25% = 31.5
```
function(n,r,p=r*1i^(4/n*0:n))plot(p,,"l")
```
[Try it at rdrr.io](https://rdrr.io/snippets/embed/?code=regular_polygon%3D%0Afunction(n%2Cr%2Cp%3Dr*1i%5E(4%2Fn*0%3An))plot(p%2C%2C%22l%22)%0Aregular_polygon(7%2C3))
Calculates coordinates of vertices in the complex plane as `r` times a power-series of the (4/n)th-root of `i`.
Example output of `regular_polygon(7,3)`:
[](https://i.stack.imgur.com/UcuML.png)
[Answer]
# TI-80 BASIC, 25 bytes - 25% = 18.75
```
PARAM
2π/ANS->TSTEP
"COS T->X1ᴛ
"SIN T->Y1ᴛ
DISPGRAPH
```
Assumes all settings are set to the default values.
Run the program like `5:PRGM_POLYGON` (for a pentagon)
It works by drawing a circle with a very low number of steps. For example, a pentagon would have steps of 2π/5 radians.
The window settings are good enough by default, and `TMIN` and `TMAX` are set to `0` and `2π`, so all we need to change is `TSTEP`.
[Answer]
# SmileBASIC 3, 183 159 - 25% = 119.25 bytes
Takes the sides and radius from `INPUT`, calculates and stores the points, and then draws them by using `GLINE`. I feel like this could be shorter but it's like 1 AM, whatever. Assumes a clean and default display env, so you might need to `ACLS` when running it from DIRECT.
```
INPUT S,R
DIM P[S,2]FOR I=0TO S-1
A=RAD(I/S*360)P[I,0]=COS(A)*R+200P[I,1]=SIN(A)*R+120NEXT
FOR I=0TO S-1GLINE P[I,0],P[I,1],P[(I+1)MOD S,0],P[(I+1)MOD S,1]NEXT
```

[Answer]
## OpenSCAD: 31 less 25% = 23.25
```
module p(n,r){circle(r,$fn=n);}
```
First post here! I know I'm late to the party, but this seemed like as good a question as any to start with. Call using `p(n,r)`.
[Answer]
## [APL (dzaima/APL)](https://github.com/dzaima/APL), ~~50 - 12.5 = 37.5~~ 37 - 9.25 = 27.75 bytes
```
P5.draw←{P5.G.ln ↑r+r×2 1○ᑈs÷⍨2×○0…s}
```
Shortened heavily with the help of [The APL Orchard.](https://chat.stackexchange.com/transcript/message/55402353#55402353)
### Explanation:
```
P5.draw←{P5.G.ln ↑r+r×2 1○ᑈs÷⍨2×○0…s}
P5.draw←{ } Draw the following on the canvas every frame:
P5.G.ln Draw a line using array(x1,y1,x2,y2...)
0…s Range from 0 to number of sides
2×○ times 2π
s÷⍨ divided by number of sides
2 1○ᑈ Take cos and sin of each of the values from the left
↑r+r× Multiply the list by r and add r to center it,
then mix the values of the list together
```
Previous version:
```
p←(2×○⍳s+1)÷s
P5.draw←{P5.G.ln r+r×⍉(2○p)↑⍤⍮(1○p)}
```
Takes input as variables `r` and `s`, draws polygon with center at \$(r,r)\$.
Made with the help of the formula used [here.](https://www.openprocessing.org/sketch/738106)
### Outputs:
`100 3`
[](https://i.stack.imgur.com/Tf4Vl.png)
`100 5`
[](https://i.stack.imgur.com/lRpIW.png)
`200 7`
[](https://i.stack.imgur.com/8o1km.png)
To execute the program, use the setup [here,](https://tio.run/##SyzI0U2pSszMTfxf9KhtAlcxiAgw1SvOrEoFMo0e9W4xPjy96H8BkKNhdHj6o@ndj3o3F2sbah7eXgxSmFKUWA6UqwYy3fVy8hSKtIuAqno7NYyASgs0H7VNfNS75FHvOg1DML/2/38A "APL (dzaima/APL) – Try It Online") for a full view of the drawn polygon.
[Answer]
**ActionScript 1, Flash Player 6: 92 - 25% = 69**
```
n=6
r=100
M=Math
P=M.PI*2
lineStyle(1)
moveTo(r,0)
while((t+=P/n)<=P)lineTo(M.cos(t)*r,M.sin(t)*r)
```
[Answer]
## C# in LINQPAD
Credit for the math part goes to Geobits (I hope you don't mind!) with the Java answer. I'm *hopeless* at math :)
I did this in LINQPAD as it's got a built in output window. So essentially you can drag and drop the following in to it and it'll draw the polygon. Just switch it to 'C# Program', and import the System.Drawing lib into the query properties.
```
//using System.Drawing;
void Main()
{
// Usage: (sides, radius)
DrawSomething(4, 50);
}
void DrawSomething(int sides, int radius)
{
var points = new Point[sides];
var bmpSize = radius*sides;
var bmp = new Bitmap(bmpSize,bmpSize);
using (Graphics g = Graphics.FromImage(bmp))
{
var o = radius+30;
for(var i=0; i < points.Length; i++)
{
// math thanks to Geobits
double w = Math.PI*2*i/sides;
points[i].X = (int)(Math.Cos(w)*radius+o);
points[i].Y = (int)(Math.Sin(w)*radius+o);
}
g.DrawPolygon(new Pen(Color.Red), points);
}
Console.Write(bmp);
}
```

[Answer]
# Matlab 58 bytes - 25% = 43.5
Saw no Matlab solution, so here is one which is pretty straightforward:
```
f=@(n,r) plot(r*cos(0:2*pi/n:2*pi),r*sin(0:2*pi/n:2*pi));
```
You can shave off some bytes if **r** and **n** are already in the workspace.
Example call:
```
f(7,8)
```
[](https://i.stack.imgur.com/WMbi1.jpg)
[Answer]
# Python 2, 222 bytes
```
from math import*
def f(s,r):
r*=cos(pi/s)
v,R=2*pi/s,[(2*t)/98.-1for t in range(99)]
print"P1 99 99 "+" ".join(["0","1"][all(w*(w-x)+z*(z-y)>0for w,z in[(r*cos(a*v),r*sin(a*v))for a in range(s)])]for x in R for y in R)
```
Checks if a pixel is on the inner side of all hyperplanes (lines) of the polygon. The radius is touched because actually the apothem is used.
[](https://i.stack.imgur.com/BlSX8.png)
[](https://i.stack.imgur.com/U71Rn.png)
[Answer]
# Mathematica 27 ( = 36 - 25%)
```
Graphics[Polygon[CirclePoints[r, n]]]
```
When we submit Mathematica code we often forget about new functions that keep getting built into the language, with current language vocabulary amassing around [5000 core functions](http://reference.wolfram.com/language/). Large and expanding language vocabulary is btw quite handy for code-golfing. [CirclePoints](http://reference.wolfram.com/language/ref/CirclePoints.html) were introduced in the current version 11.X. A specific example of 7-sided radius 5 is:
[](http://reference.wolfram.com/language/ref/CirclePoints.html)
Also you just need to enter angle parameter to control orientation of your polygon:
```
Graphics[Polygon[CirclePoints[{1, 2}, 5]]]
```
[](https://i.stack.imgur.com/ADqii.png)
[Answer]
# Python 2, 74 bytes - 25% = 55.5
Input is in the variables `r,n`. If included in the count, it would be `r,n=input()`, for 12 bytes more.
```
import math,turtle as t
exec"t.fd(2*r*math.sin(180/n));t.rt(360/n);"*n
```
[**Try it online**](https://trinket.io/python/83cd17e68a) - *(uses different code since `exec` is not implemented in the online interpreter)*
[Answer]
# SmileBASIC, ~~85~~ 75 - 25% = 56.25 bytes
```
FOR I=0TO S
A=I/S*6.28N=X
M=Y
X=R+R*COS(A)Y=R+R*SIN(A)GLINE N,M,X,Y,-I
NEXT
```
Variables S and R are used for input.
Explained:
```
FOR I=0 TO Sides 'Draw n+1 sides (since 0 is skip)
Angle=I/Sides*6.28 'Get angle in radians
OldX=X:OldY=Y 'Store previous x/y values
X=Radius+Radius*COS(A) 'Calculate x and y
Y=Radius+Radius*SIN(A)
GLINE OldX,OldY,X,Y,-I 'Draw line. Skip if I is 0 (since old x and y aren't set then)
NEXT
```
The sides are drawn using the color `-I`, which is usually close to -1 (&HFFFFFFFF white) (except when `I` is 0, when it's transparent).
You can also draw a filled polygon by using `GTRI N,M,X,Y,R,R,-I` instead of `GLINE...`
[Answer]
# Tikz, 199 bytes
```
\documentclass[tikz]{standalone}\usetikzlibrary{shapes.geometric}\begin{document}\tikz{\def\p{regular polygo}\typein[\n]{}\typein[\r]{}\node[draw,minimum size=\r,\p n,\p n sides=\n]{}}\end{document}
```
This solution uses the tikz library `shapes.geometric`.
Here is what a polygon with `5` sides and radius `8in` looks like when viewed in [evince](https://wiki.gnome.org/Apps/Evince).
[](https://i.stack.imgur.com/xxSTf.png)
[Answer]
# MATLAB/Octave, 26.25 bytes (35 bytes-25%)
```
@(n,r)polar((0:n)/n*2*pi,r+(0:n)*0)
```
Can be tested on [octave-online](https://octave-online.net/).
@ptev already posted a MATLAB answer but mine uses far less bytes and isn't distorted.
We can save up another 6 bytes (or 4.5 including bonus) if we assume input can be given as variables `r`&`n` already existing in workspace - then just calling `polar((0:n)/n*2*pi,r+(0:n)*0)` is enough.
Also, example output (`n=5`,`r=3`):
[](https://i.stack.imgur.com/zqECj.png)
] |
[Question]
[
The code has a lot of names, but is very simple:
```
1 2 3 4 5
1 A B C D E
2 F G H I J
3 L M N O P
4 Q R S T U
5 V W X Y Z
```
A letter is coded by its coordinates, with the row first, then the column. Ex:
```
M = 3, 2
V
1 2 3 4 5
1 A B C D E
2 F G H I J
>3 L M N O P
4 Q R S T U
5 V W X Y Z
```
Note the letter 'K' is missing, as a letter needs to be removed to make the alphabet fit in the grid. In some versions, the letter 'J' is removed but K is easier to remove because every line stays in order.
More info [here](https://en.wikipedia.org/wiki/Tap_code) on Wikipedia.
Challenge: Make a program that takes in a message encoded in this way, that outputs the decoded message. Input can be in any reasonable format.
```
23 15 31 31 34 52 34 42 31 14
23153131345234423114
etc
```
Are all reasonable input formats.
Standard loopholes apply.
## Test Cases
```
23 15 31 31 34 52 34 42 31 14 => HELLOWORLD
24 25 31 32 => IJLM
11 22 33 44 55 => AGNTZ
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~40~~ 39 bytes
-1 thanks to kops! (Multiply before integer division)
```
lambda a:[chr(r*16/3+c+59)for r,c in a]
```
An unnamed function accepting an iterable of pairs which returns a list of characters.
**[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHRKjo5o0ijSMvQTN9YO1nb1FIzLb9IoUgnWSEzTyEx9n9BUWZeiYa6ul5WfmaeRppGdLSRjnGsjkK0oY4piDLWMUShTECUqY4REs8ExjOE6DOJjdXU1PwPAA "Python 2 – Try It Online")**
[Answer]
# [J](http://jsoftware.com/), 22 bytes
```
65(u:@+>&74)@+[:5&#.<:
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/zUw1Sq0ctO3UzE00HbSjrUzVlPVsrP5rcpWkFpfY6imkJmfkO@haRVulKcQbxcbEcnGpe7j6@PiH@wf5uKgrgFQpGCkYKygYKpgqAGlDOGGiABQxgrJMICxDkDoTLnVHd7@QKKhuQ5CoEUTeGKQSrNH0PwA "J – Try It Online")
* `[:5&#.<:` Decrement each input value `<:` and interpret every resulting 2-element pair as a base 5 number `5&#.`.
* `65...@+` Add 65 to each (to make it an ascii value), and...
* `u:@+>&74` Add 1 more to each number greater than 74 `+>&74` to adjust for the missing K. Finally, convert the result to a character `u:@`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
ḅ5<⁴ạƊ+60Ọ
```
[Try it online!](https://tio.run/##y0rNyan8///hjlZTm0eNWx7uWnisS9vM4OHunv///0dHG@kYx@ooRBvqmIIoYx1DFMoERJnqGCHxTGA8Q4g@k9hYAA "Jelly – Try It Online")
A completely different approach.
## Explanation
```
ḅ5<⁴ạƊ+60Ọ Main monadic link
All following operations are automatically vectorized.
ḅ5 Convert from base 5
ạƊ Absolute difference with
<⁴ 1 if it's less than 16, else 0
+60 Add 60
Ọ Convert to character
```
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 85 bytes
```
,[>++++++++[<------>-],<[>+++++>>[>]+[<]<<-]>+++++++++++>>>>[<<<<+>>>>-]<<<<.>>>>>>,]
```
[Try it online!](https://tio.run/##PYpBCoBACEUPlAbOODvxIoOLCoIIWgSd30yG3t98fX@9l@Pan@10h67ToAsmigYy3qpdLYyJoP3LFKEkyIb21VkTMPdSqVWKcCuVOU7iFw "brainfuck – Try It Online")
## Explanation
```
, Read a character
[ While not at the end of input
>++++++++[<------>-] Subtract 48 to get the actual number
, Read another character
<[>+++++>>[>]+[<]<<-] Add 5 times the number to the character and also expand the number into a group of 1s
>+++++++++++ Add 11 to the character to turn it into a letter
>>>> Go to the third item in the group of 1s
[<<<<+>>>>-] If it's a 1 then add 1 to the character
<<<<. Print the character
>>>>>> Skip past the dirty memory cells
, Read a new character
]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
ØAḟ”Ks5⁸œị
```
[Try it online!](https://tio.run/##y0rNyan8///wDMeHO@Y/apjrXWz6qHHH0ckPd3f/f7h7y8Mdmx41rQkDYpfD7UAy8v9/I2MFQ1MFY0MwMlEwNQKRJkYgrqEJl5GJghFE1ojL0FDBCChurGACVGYKAA "Jelly – Try It Online")
-1 byte thanks to Jonathan Allan!
## How it works
```
ØAḟ”Ks5⁸œị - Main link. Takes a list of pairs P on the left
ØA - Yield the uppercase alphabet
ḟ”K - Filter out "K"
s5 - Split into a 5x5 matrix, S
⁸ - Yield P
œị - For each pair [A, B] in P,
get the B'th element of the A'th row of S
```
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 78 bytes
```
,[<<-[----->+>-<<]>>+>,<[>+>]<<[<]>>+[>+>]<<[<]>[--->>+<<]>[->+++++<]>--.>>>,]
```
[Try it online!](https://tio.run/##TYpLCoAwDEQP1EbIp7uQi4QuVBBEcCF4/ph25Sxm3gvZnvW8j3e/IqqrgsOIFQPVbrlVPbur@vSfjNe86EQrI4kAi5nVHiFCjE1QGgkyUmoiM2Eufw "brainfuck – Try It Online")
Takes input for each letter as 2 ascii encoded digits.
**Explanation**
Essentially the formula is
`65+[Row ASCII - 49]*5+[Column ASCII -49]+[1 if row >2]` .
The row ASCII value is reduced by 49, but the column ASCII offset is calculated as
```
65-49 = 16 = 17-2+1 plus an additional 1 if in row 3 onwards.
```
The approach is quite different to the existing brainfuck answer.
```
,[<< Take an input for row value into cell 0 to get started then move to cell minus 2
-[----->+>-<<] make cell minus 1 equal 255/5=51 and also subtract this number from input
>>+>,< add 1 to row value in cell 0 and input column value into cell 1
[>+>]<<[<] if cell 0 not 0 row input was not 2 so add 1 to column value
>>+ add 1 to row value in cell 0 so now it is 49 minus the input / note ASCII 49 is 1
[>+>]<<[<] if cell 0 not 0 row input was not 1 so add 1 to column value
>[--->>+<<] add 51/3=17 to column value
>[->+++++<] add 5 times row value to column value
>--. subtract 2 from column value and output letter
>>>,] skip 3 dirty cells and take next row input
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~39~~ 37 bytes
```
map(\(r,c)->[';'..]!!(r*5+c+r`div`3))
```
[Try it online!](https://tio.run/##y0gszk7NyfmfbhvzPzexQCNGo0gnWVPXLlrdWl1PL1ZRUaNIy1Q7WbsoISWzLMFYUxOoKjNPwVahoCgzr0RBRSE9WsNIx1hTR0HDUMcURBnrGKJQJiDKVMcIiWcC4xlC9Jloxv7/l5yWk5he/F83uaAAAA "Haskell – Try It Online")
* saved 2 thanks to @cole
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 42 bytes
```
a=>Buffer(a.map(([y,x])=>+x+y*16/3+59))+''
```
[Try it online!](https://tio.run/##dZBtS8MwEMff91PcCyGJndU@CTpSUXymOlBBcA5WunREuqSmqW6MfvaZrJvzjRBC7u73/9/lPrKvrM4Vr/SBkBO2yqWoNdSybDSXAugqo8lFUxRM4cybZRXGw0VvPiI0cefuYt8/Pgzd@IQQF6GNNs9qVgMFxT4brhhGRY2Ip1g2ueYle16IHB8RT8tnrbiYYuLVVck1Ru/CYLZDyQUDmsDSAegsh1xUje4Bm1cs12wyMvaW2kppgkjf0IrpRokN7hn/2c4eENkZbGqjvtMaYSEV4P86yaL7Efkzj2J1U2ozxHZPeC1bz2AJWTKvlFM83lt2aAt4@wRK6a89nAHKpVImQHAK6FtJMUUtGRurdhWE4McQ@usTQRzYOwps6Ed2Q7dXaTp4HTyll04QQdCxga3c3acPju9DYOgQIiOObfr85vHl7Qc "JavaScript (Node.js) – Try It Online")
Takes an array of strings.
[Answer]
# [convey](http://xn--wxa.land/convey/), 568 bytes
```
{:v
1v
v#< 0
v^<<<<(<
v9 ^9
v+2v'A'^+2
"=>!} ^*5v'Z'
v9 "=>!}
v+3v'B'^9
"=>!} ^*6v'Y'
v9 "=>!}
v+4v'C'^9
"=>!} ^*6
v9 ^-1v'X'
v+5v'D'"=>!}
"=>!} ^9
v9 ^+4
v+6v'E'^*4v'W'
"=>!} "=>!}
v7 ^9
v*3v'F'^+8
"=>!} ^*3v'V'
v9 "=>!}
v+2 ^9
v*2v'G'^*5v'U'
"=>!} "=>!}
v9 ^9
v+9 ^+2
v+5v'H'^*4v'T'
"=>!} "=>!}
v6 ^9
v*4v'I'^*4
"=>!} ^+7v'S'
v5 "=>!}
v*5v'J'^7
"=>!} ^*6v'R'
v9 "=>!}
v*3 ^9
v+4v'L'^*4
"=>!} ^+5v'Q'
v8 "=>!}
v*4v'M'^5
"=>!} ^*7v'P'
v9 "=>!}
v+2 ^9
v*3v'N'^+8
"=>!} ^*2v'O'
>>>>>>>"=>!}
```
And here's a picture of the factory (the gif thing kept crashing):
[](https://i.stack.imgur.com/HfwNk.png)
The basic idea is that there is a massive loop which lets one value through at a time. It goes through every letter. Note: Some things which appear to be golfable aren't due to interpreter glitches.
[Try it online!](https://xn--wxa.land/convey/run.html#eyJjIjoiezp2XG4gMXZcbnYjPCAgIDBcbnZePDw8PCg8XG52OSAgICAgXjlcbnYrMnYnQSdeKzJcblwiPT4hfSAgXio1didaJ1xudjkgICAgIFwiPT4hfVxudiszdidCJ145XG5cIj0+IX0gIF4qNnYnWSdcbnY5ICAgICBcIj0+IX1cbnYrNHYnQydeOVxuXCI9PiF9ICBeKjZcbnY5ICAgICBeLTF2J1gnXG52KzV2J0QnXCI9PiF9XG5cIj0+IX0gIF45XG52OSAgICAgXis0XG52KzZ2J0UnXio0didXJ1xuXCI9PiF9ICBcIj0+IX1cbnY3ICAgICBeOVxudiozdidGJ14rOFxuXCI9PiF9ICBeKjN2J1YnXG52OSAgICAgXCI9PiF9XG52KzIgICAgXjlcbnYqMnYnRydeKjV2J1UnXG5cIj0+IX0gIFwiPT4hfVxudjkgICAgIF45XG52KzkgICAgXisyXG52KzV2J0gnXio0didUJ1xuXCI9PiF9ICBcIj0+IX1cbnY2ICAgICBeOVxudio0didJJ14qNFxuXCI9PiF9ICBeKzd2J1MnXG52NSAgICAgXCI9PiF9XG52KjV2J0onXjdcblwiPT4hfSAgXio2didSJ1xudjkgICAgIFwiPT4hfVxudiozICAgIF45XG52KzR2J0wnXio0XG5cIj0+IX0gIF4rNXYnUSdcbnY4ICAgICBcIj0+IX1cbnYqNHYnTSdeNVxuXCI9PiF9ICBeKjd2J1AnXG52OSAgICAgXCI9PiF9XG52KzIgICAgXjlcbnYqM3YnTideKzhcblwiPT4hfSAgXioydidPJ1xuPj4+Pj4+PlwiPT4hfSIsInYiOjEsImkiOiIyMyAxNSAzMSAzMSAzNCA1MiAzNCA0MiAzMSAxNCJ9)
I can't believe Brainfuck is beating this :( - Convey has terrible string handling, so this is the only answer where it implicitly checks every single letter...
[Answer]
# [Scala](http://www.scala-lang.org/), ~~37~~ 36 bytes
Saved 1 byte thanks to @xigoi, who suggested applying @kops's suggestion to Jonathan Allan's answer.
```
_.map{case(r,c)=>r*16/3+c+59 toChar}
```
[Try it online!](https://tio.run/##NU3BSsQwFLz3K4aeErdbTZrKutAF8SToyaPIErNpjXbT0AQRSr@9JnaFxzAzzJvxSvZyGd4/tQp4lsZC/wRtTx73zmHKgG/Zo93jyfjwSh5tKBCBvqE5rN7DhxyjWo7lWbpJSa/JWCjaHMYrdntdbdSmvkMYUmxegNh40i064vd4CaOxHUUDF0noLWmJL73rTSA5clqGIU2kYkwwaZIYckOxhdgVMIStlGKm5fnrUpfFiY7kvAKrUbG/E6h5QsGTZCKnl5AAX0P832IMPKYqiPhURzebl18 "Scala – Try It Online")
Now simply a port of [Jonathan Allan's Python answer](https://codegolf.stackexchange.com/a/222464/95792), which you should upvote!
Outputs a list of characters.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~13~~ 12 bytes
```
<ε5β}Au'Kмsè
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f5txW03Obah1L1b0v7Ck@vOL//@hoIx0F41gdhWhDHQVTEG2so2CIRpuAaFMdBSNkvgmCbwjVbxIbCwA "05AB1E – Try It Online")
-1 byte thanks to [Makonede](https://codegolf.stackexchange.com/users/94066/makonede). Outputs as a list of characters
## How it works
```
<ε5β}Au'Kмsè - Program. Takes an input of a list of pairs P
< - Decrement to use 0-indexing
ε } - Over each pair [A, B]:
5β - Convert from base 5, yielding 5A+B
Au - Push the uppercase alphabet
'K - Push "K"
м - Remove "K" from the alphabet
sè - Index into this modified alphabet
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes
```
⭆⪪⭆S⊖ι²§⁻αK⍘ι⁵
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCO4BEil@yYWaAQX5GQi8z3zCkpLIFwNTR0Fl9TkotTc1LyS1BSNTE2ggBEQO5Z45qWkVmj4ZuaVFmsk6igoeSsBhZ0Si1OhOjN1FEw1gcD6/38jY0NTY0MgNDE1MjYxAXINTf7rluUAAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
S Input string
⭆ Map over characters and join
ι Current character
⊖ Decremented
⪪ ² Split into pairs of digits
⭆ Map over pairs and join
ι Current pair
⍘ ⁵ Convert from base 5
§ Index into
α Predefined variable uppercase alphabet
⁻ Minus
K Literal string `K`
Implicitly print
```
[Answer]
# [K (ngn/k)](https://bitbucket.org/ngn/k), 20 bytes
```
`c${x+74<x}65+5/'-1+
```
[Try it online!](https://tio.run/##y9bNS8/7/z/NKiFZpbpC29zEpqLWzFTbVF9d11D7f4mVhpGCsYKhgimYhGATIM8ITJsoQGQNFUysgUwQF6bQyBosbgRWAVFrqmCqyZVuZeCnYKTMVZ2mkK5QUate8h8A "K (ngn/k) – Try It Online")
Uses [@Jonah](https://codegolf.stackexchange.com/a/222469/75681)'s method - don't forget to upvote him!
[Answer]
# [Jelly (fork)](https://github.com/cairdcoinheringaahing/jellylanguage), 10 bytes
```
’ḅ5ịØȦḟ”K¤
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw8yHO1pNH@7uPjzjxLKHO@Y/apjrfWjJ////o6ONdBSMY3UUog11FExBtLGOgiEabQKiTXUUjJD5Jgi@IVS/SWwsAA "Jelly – Try It Online") (or rather, don't)
## How it works
```
’ḅ5ịØȦḟ”K¤ - Main link. Takes a list of pairs P on the left
’ - Decrement each integer to use 0-indexing
ḅ5 - For each pair [A, B], yield 5A+B (convert from base 5)
¤ - Group the previous links into a nilad:
ØȦ - Shifted alphabet; Yield "BCDE...XYZA"
ḟ”K - Filter out "K"
ị - Index into this modified alphabet
```
[Answer]
# Excel, 42 bytes
```
=CONCAT(REPT(CHAR(A:A*16/3+B:B+59),A:A>0))
```
Another port of [Johnathan Allan's Python Answer](https://codegolf.stackexchange.com/a/222464)
Input is 2 columns of cells.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
▄πKñ╜╓♥F⌂F
```
[Run and debug it](https://staxlang.xyz/#p=dce34ba4bdd603467f46&i=%5B%5B3,+2%5D,+%5B5,+1%5D,+%5B1,+3%5D,+%5B1,+3%5D,+%5B4,+3%5D,+%5B2,+5%5D,+%5B4,+3%5D,+%5B2,+4%5D,+%5B1,+3%5D,+%5B4,+1%5D%5D%0A%0A%5B%5B4,+2%5D,+%5B5,+2%5D,+%5B1,+3%5D,+%5B2,+3%5D%5D%0A%0A%5B%5B1,+1%5D,+%5B2,+2%5D,+%5B3,+3%5D,+%5B4,+4%5D,+%5B5,+5%5D%5D&m=1)
takes inputs as `[column, row]`. Based on Jonathan Allan's answer.
[Answer]
# [Befunge-93](https://github.com/catseye/Befunge-93), 31 bytes
```
~:1+!#@_"0"-:2`\5*+~"0"-+";"+,~
```
[Try it online!](https://tio.run/##S0pNK81LT/3/v87KUFtR2SFeyUBJ18ooIcZUS7sOxNZWslbS1qn7/9/QSMHYCAA "Befunge-93 – Try It Online")
### Explanation
```
~ Get a char
:1+!#@_ If at the end of the string, stop the execution (see if the char is -1)
"0"- Get the row number
:2`\ If greater than 2, push a 1, otherwise a zero, swap the top two in the stack
5*+ Multiply by 5 and sum the 0/1
~"0"-+ Get the col number and sum everything
";"+, Sum 59 to get the ASCII value of the char
~ Remove the space
```
[Answer]
# [R](https://www.r-project.org/), 37 bytes
```
function(a)intToUtf8(a$x*16/3+a$y+59)
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jUTMzryQkP7QkzUIjUaVCy9BM31g7UaVS29RS83@aRkpiSaJeWlFibqpGhW2yhpGOkY6xjrGmjkIlkGeiY6pjqGOkqanJhUWlIUglEJoCsQkQG0J1GYN1GQLFjMAYyAKa8B8A "R – Try It Online")
Port of [Jonathan Allan's Python answer](https://codegolf.stackexchange.com/a/222464/95792).
Takes input as a data frame with first digit in first column and second digit in second column.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 34 bytes (31 bytes with Ruby 2.7)
```
->x{x.map{|i,j|(i*16/3+j+59).chr}}
```
A direct port of Johnathan Allan's Python answer.
This lambda accepts an array of pairs and returns an array of characters.
[Try it online!](https://tio.run/##XY5LCsIwAET3OcUsWxsjaRLBhV4kZlH7oSmooVqoND17bERQuhge82Bg@uHyCs3xHLancRrZtXCTt7Tzid3w/U5kXaYOKSvbfp6DQ6O1zimEodCcQkUKCr6ijFQU@X@Xv86/e2mMIQlnTKWsLsoW1R3eegKsZRcl4Ibn43NiuRi3QH2ryJLwBg "Ruby – Try It Online")
`->x{x.map{(_1*16/3+_2+59).chr}}` is written in 31 bytes and also works fine, but it requires Ruby 2.7 (not yet supported by TIO).
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell) 5+, 47 bytes
Tribute to [Metal gear 2: Solid Snake](https://metalgear.fandom.com/wiki/Tap_code#)
```
-join($args|%{(';'..'_'-ne'K')[5*$_[0]+$_[1]]})
```
[Try it online!](https://tio.run/##bY9dT4MwFIbv@yt60VmqZZGvK7MEo8YvJmYzMRkhhEE3tyBMGJmR8duxQHFM7QWH9jzvc9pNsmNp9saiqEKLUVHJ62QVS8hPl9l@UEj4Ag@H2MNyzPAjJo5xijzn3D3jX8V1S1KVAJgSAFTCdzeWZb/aE@saUyipFGqEV4VCo64ahcqvqtfVoFDt7/XDXhF5nZDaf/9gjYW5IdW/ZrUlL2@fXma4DSsC7aSaGNINN9rIzI@/VnM/tfw4xE3HID1BFxTHKtXbrtqH/rn6UVg8BRC4hwNYAMgXYp8bFmxZSPlvHCQhC8csy/wlgyOIvJZJWZZHW35wghbQPMYawnmeXuXZNnm352tuc81WXq9pHgScrG1CI7OPw9gfbtLNEFjTKEFZVd8 "PowerShell – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 34 bytes
```
s/(.)(.)/(A..J,L..Z)[5*$1-6+$2]/ge
```
[Try it online!](https://tio.run/##K0gtyjH9/79YX0NPE4j0NRz19Lx0fPT0ojSjTbVUDHXNtFWMYvXTU///NzI2NDU2BEITUyNjExMg19DkX35BSWZ@XvF/XV9TPQNDg/@6BQA "Perl 5 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 75 bytes
```
main(int a,char**b){for(b++;**b;++*b)putchar(16+(a=**b-49)*5+(a>1)+*++*b);}
```
[Try it online!](https://tio.run/##HYpBDkAwEEWvYtl2WEw7lUjDXaoJulAirMTZx5C/eu/91MwpMa8xF5XLWcU6LfEwZtT3tB1qBAgCAUDMfp1fVNiCir3ohjptvMCAGsz/CQ8zW4feoYy8dUSCSC8 "C (gcc) – Try It Online")
In the end, this is pretty straightforward and just uses C's willingness to be fluid about treating characters as integers. It runs through the characters in the first commandline argument, then uses a golfed version of this logic to map each one to the desired character.
```
'A' + (char1-'1')*5 + (char1-'1'>1) + (char2-'1')
```
The only trickery here is using the using the storage provided by the arguments to the `main()` call to avoid having to declare local variables. And the operator precedence in C means this jumble of punctuation,
```
+*++*b
```
does a number of things with just a few characters. That fragment, increments the pointer to the "current character" `*b`, then dereferences that location as a single character, implicitly converts it to an integer and adds it to the rest of the expression. The fact that `+*++*`, which looks more like Morse Code than C code, does something useful is pretty much why I decided to post this entry. :)
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~33~~ 15 bytes
Saved 18 bytes thanks to Razetime! (they also pointed out the answer was invalid)
```
⌷∘(5 5⍴⎕A~'K')¨
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RHPdsfdczQMFUwfdS75VHfVMc6dW91zUMr/qcDJdM0NB71dB0GqTA00NQxNKh51LUILKlgZKxgaKpgbAhGJgqmRiDSxAjENTThAsqbKBhB5I2APENDBSOgnLGCCVCpKQA "APL (Dyalog Unicode) – Try It Online")
Takes a vector of pairs of numbers.
```
⌷∘(5 5⍴⎕A~'K')¨
¨ ⍝ For each pair in the input
⌷ ⍝ Index into:
⎕A ⍝ Capital letters
~'K' ⍝ Without 'K'
5 5⍴ ⍝ Reshaped into a 5x5 matrix
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 37 bytes
```
T` d`__9\EKPU` |\b\d
+T`dL`__1-7L`.\d
```
[Try it online!](https://tio.run/##K0otycxL/P8/JEEhJSE@3jLG1TsgNEGhJiYpJoVLOyQhxQcoaqhr7pOgF5Py/7@RsYKhqYKxIRiZKJgagUgTIxDX0ITLyETBCCJrxGVoqGAEFDdWMAEqMwUA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
T` d`__9\EKPU` |\b\d
```
This does two things; it deletes all the spaces, and it replaces the first of each pair of digits with the characters `9EKPU` respectively, these being the characters in the translation string below that precede the letters from the first column of the code.
```
+T`dL`__1-7L`.\d
```
Repeatedly decrement the remaining digits and increment the preceding letter until the digits become zero, at which point they are deleted. Note that on the first pass the "letter" might actually be a `9`, but this works because on the first pass of this loop all the "letters" will be paired with a digit.
[Answer]
# [R](https://www.r-project.org/), 62 bytes
```
function(x)for(i in x)cat(letters[(y=(i-1)%*%c(5,1)+1)+(y>9)])
```
[Try it online!](https://tio.run/##TY5BCoMwEEX3PYUb4U@bLqLJogt7EemijBECkkAcQU@fGqUgDPN48Gf4KQ@O4@C6PC6BxceAlcaY4CsfqpX4K5iciEtzj62Df2qq7zXDKk2PfbC9X/ShfDyZ/CxgNKolxdDKFrR78gpTYFVzMfM3fd4ZotvZC2VR/gE "R – Try It Online")
Aaargh! I clicked submit and then saw [pajonk's much shorter answer](https://codegolf.stackexchange.com/a/222505/95126) waiting for me! Upvote that one (and [Jonathan Allan's one](https://codegolf.stackexchange.com/a/222464/95126) that it's based-on)!
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 22 bytes
```
~]2/{~\16*3/+59+}/]''+
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPn/vy7WSL@6LsbQTMtYX9vUUrtWP1ZdXfv/fyMFYwUFQwVTBSBtCCdMFIAiRlCWCYRlCFJnAgA "GolfScript – Try It Online")
Another port of @Jonathan Allen’s answer, and my first time trying out GolfScript. Input is just a series of numbers, separated by spaces, but you can separate number pairs with extra spaces for readability.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 60 bytes
```
($a|%{[char][int][math]::floor($_[0]*16/3+$_[1]+59)})-join''
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvkmjroKFhpGOsqaOgYahjCqKMdQxRKBMQZapjhMQzgfEMIfpMNDX/a6gk1qhWRydnJBbFRmfmlcRG5yaWZMRaWaXl5OcXaajERxvEahma6RtrA5mGsdqmlpq1mrpZ@Zl56ur//wMA "PowerShell – Try It Online")
Thanks to @JonathanAllan
] |
[Question]
[
### Your task
Given a string, output the range of ASCII values.
### Example
Let's say we have the string `Hello`.
We get the ASCII values:
* `H` = 72
* `e` = 101
* `l` = 108
* `l` = 108
* `o` = 111
Now, we get the range (`max - min`):
* 111 - 72 = 39
Our answer is 39.
### Test cases
```
Input Output
Hello, World! 82
aaaaa 0
Code Golf 79
Stack Exchange 88
ASCII 18
```
### Scoring
For scoring, we will get the range of ASCII/Unicode values of your program source code, and add that to the length of your code in bytes.
For example, with the program `abc`, the score would be:
* 3 (the length of the program) + 2 (the ASCII range of the program) = 5
You can use [this TIO link](https://tio.run/##RYyxCoMwFEX3fMXbTKh16SZ0KJ2Ebu3S8dVEDSR54SUF/XobKeh2OefeG5c8Ubisq/WROENakmC4gkP/0QiuBY@zdArO4G0oQdBhUwvOpiw9Rkmsa0hKieHwcwssSc6F2kLLd5OytqFhg1oqgQUO0irhto0JW4xsQ5bV7XnvOmAMo2mrGnAXDxPGPG3M7exFGR2knvhfPjm1rm/6MvSkDYxkEkyGzQ8) to get your score.
### Clarifications
* There will be no non-ASCII characters in the input (but your program source code may contain non-ASCII characters)
* There will be no newline characters in the input (but your program source code may include newlines)
* **Lowest score wins**
[Answer]
# [MATL](https://github.com/lmendo/MATL), score 37 (length 7, range 30)
```
X>GX<ZP
```
[Try it online!](https://tio.run/##y00syfn/P8LOPcImKuD/f3WP1JycfHUA "MATL – Try It Online") Or [verify](https://tio.run/##y00syfmf8D/Czj3CJirgv0tURch/dY/UnJx8HYXw/KKcFEV1LvVEEADSzvkpqQru@TlpQHZwSWJytoJrRXJGYl56KlDAMdjZ0xNIQ41SBwA) all test cases and source code.
```
X> % Implicit input. Maximum
G % Push input again
X< % Minimum
ZP % Distance (of code points). Implicit display
```
[Answer]
# [C (clang)](http://clang.llvm.org/), 79 bytes + 28 = ~~145 138 129 112 111~~ 107
*-7 score thanks to [@Digital Trauma](https://codegolf.stackexchange.com/users/11259/digital-trauma)
~~-9~~ -10 score thanks to [@jdt](https://codegolf.stackexchange.com/users/41374/jdt)*
```
A,B;D(*C)??<*C<A?A=*C:*C>B?B=*C:0;*++C?D(C):0;??>C(*C)??<A=B=*C;D(C);*C=B-A;??>
```
[Try it online!](https://tio.run/##jVBNT4QwED3TXzGSbAIFshyNXWiga3STve1hDysHLB9LrNAAuhrDXxdbRA/Egz29eTNvOu9xj4u0LscxcmOytTCzKd1gtoloFGB2g1kY01gjn2DHYXRrMVthSkM2D0eB7hPdIJgFsRfp7ljVPXpOq9p6barMRh/IUAzgPu/6UwIBKMLYm/e5EI0Lx6YV2ZXpTlyq34xZk@Vw14hirg99yp/g9o2f1dH5TEYHttv94F8bpqrXGBzAa9ib/zK1kMwWl4v@MrxUTtf4yBhcwFi68PhSnK79xIU27wlCRtG0YEkVg86DAJYEHEfaUyoX3nH5bimJEkubKIrpakKyVTEWlrkSHXghrLKH2tRj31/4iR4a0DB@8kKkZTd6fVuVbSrPCl6@AA "C (clang) – Try It Online")
## Explanation
`??<` and `??>` are trigraphs for `{` and `}` respectively
```
A,B; // A will track the minimum, B will track the maximum
D(*C){ // D() will traverse C updating the values of A and B
*C<A? // if current character < A
A=*C // update A with it's value
:*C>B? // else if current character > B
B=*C // update B with it's value
:0; // else, do nothing
*++C? // if we're not at the end of the string
D(C) // call D recursively with the next character
:0; // else, do nothing
} // end D()
C(*C){ // C() takes the string, which is also where we'll store the output
A=B=*C; // initialize A and B with the first character in C
D(C); // call D
*C=B-A; // store the range (max - min) in the out argument
} // end C()
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + GNU utilities, 52 bytes + 92 range = 144
```
od -An -w1 -td1 -v|sort -n|sed -n '1p;$p'|dc -e??r-p
```
[Try it online!](https://tio.run/##nY2xDoIwFAD3fsWTYLrYgZmBEEKUxMHIYBwr7yHEpq9piTj03yv@gjfccsM9dJjSOs2GwJPGEpCF87NdRpD7ICHLr@3lfM8gJkZQtQW1FqAW3PSOgf0CysZAW7MgC1fmTkYcQFFVeeUSsqV0ImP4ADf2BndC/xANI8GRzSj6RQ8vaD/DpO2TRN03XSf@mYkv "Bash – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 13 bytes + 39 = 52
```
a:A^aMXaADMNa
```
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJhOkFeYU1YYUFETU5hIiwiIiwiIiwiXCJIZWxsbywgV29ybGQhXCIiXQ==)
### Explanation
A straight code-golf solution to the challenge might look like this:
```
A*:a;Ma-Na
a First command-line argument
A* Get ASCII value of each character
: and assign that list of integers back to a
; Statement separator
Na Minimum of a
a- Subtract that from each element in a
M and take the maximum of the resulting list
```
This gets a score of 65. The `a` for getting the command-line argument and `A` for taking ASCII values are both necessary, so to improve the score we'll need to look at the characters with ASCII values less than `A`.
The smallest character is `*`, which we can get rid of by splitting the string into a list of characters with `^` and passing that list to `A` directly:
```
A*:a
->
a:A^a
```
The next-smallest character is `-`, which we can get rid of by using the absolute difference operator `AD` instead. Then we have to rearrange a bit more to avoid needing a space; we'll use the old `MX` and `MN` operators for max and min instead of the newer `M` and `N`.
```
Ma-Na
->
MXaADMNa
```
(We could also keep using `M`, but since it also requires a semicolon to parse correctly, the score is the same if we replace it with `MX` which doesn't need the semicolon.)
[Answer]
# [Alumin](https://github.com/ConorOBrien-Foxx/Alumin), ~~36~~ 19 bytes + ~~22~~ 20 = ~~58~~ 39
```
idiqdhhhwrvsruripkc
```
[Try it online!](https://tio.run/##S8wpzc3M@/8/MyWzMCUjI6O8qKy4qLQosyA7GasgAA "Alumin – Try It Online")
Both the right language for the job~~, and horribly inefficient at it!~~ Turns out, I'm just an inefficient thinker!
## Explanation
```
idiqdhhhwrvsruripkc
explanation | stack
id take input, duplicate | MAX MIN
iq ip while input > 0 | MAX MIN in
d duplicate | MAX MIN in in
hhhw grab top 3 | MAX [ MIN in in ]
r reverse stack | MAX [ in in MIN ]
v get lesser of two | MAX [ in MIN' ]
s ungrab | MAX in MIN'
r reverse stack | MIN' in MAX
u get greater of two | MIN' MAX'
r reverse stack | MAX' MIN'
(this gives us a better score than using `y` to swap 2)
loop finishes | MAX MIN -1
k discard eof | MAX MIN
c subtract | MAX-MIN
```
## Explanation (Old)
```
hqidrlhcwrspkrklhhgwfufsykrlhcwfvfsc
h push 1 (to start loop)
q p input loop
id take input, duplicate
r reverse stack
lhc stack length - 1
wrs reverse that many elements off the stack
this has the effect of pushing two copies of the input
krk pop trailing EOF twice
lhhg stack length / 2
w grab that many elements into a new stack
fuf fold over maximum
sykr place on bottom stack, remove initial 1
lhc stack length - 1
w grab that many elements as before
fvf fold over minimum
sc push and subtract
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), score 56 (length 6, range 50)
```
@range
```
[Try it online!](https://tio.run/##y08uSSxL/f/foSgxLz31f5qCrUJiXrE1V5qGukdqTk6@jkJ4flFOiqK6JkgoEQQgTOf8lFQF9/ycNAg3uCQxOVvBtSI5A2QORMwx2NnTE8KEGK@u@R8A "Octave – Try It Online")
[Answer]
# [Terse](https://gymhgy.github.io/TerseLang/), 7 bytes + 6769 = 6776
```
找没最手样找到
```
[Try it here](https://gymhgy.github.io/TerseLang/?code=wGm9voTAag&in=IuaJvuayoeacgOaJi-agt-aJvuWIsCI)
Could be worse.
```
找 Char codes
没 Maximum, after
最手 Squaring and then square root (identity)
样 Subtract
找到 Minimum
```
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), ~~9~~ 12 bytes + ~~56~~ ~~49~~ 38 = 50
```
;*;-;o;/;\;`<@@o;/_$;`$$
```
This corresponds to the [Nibbles](http://golfscript.com/nibbles/index.html) program with nibbles:
```
6 a 6 9 6 e 6 a 6 b 6 e 4 d 4 e 6 a 5 3 6 d 7 3
```
Which, paired-up into bytes, gives
```
6a 69 6e 6a 6b 6e 4d 4e 6a 53 6d 73
```
which can be read-out as a string (with the same ASCII values)
```
jinjknMNjSms
```
with ASCII range 115 (`73`) - 77 (`4d`) = 38.
---
**How?**
We start from a straightforward code-golf solution to the question: `-o/\;`<$$o/` (5.5 bytes, 11 nibbles):
```
-o/\;`<$@o/
- # subtract
o # character value of
/ # fold over
\ # reverse of
; # (save)
`< # sorted
@ # input
$ # returning left element each time
# (so the fold returns the first element)
# from
o # character value of
/ # fold over
# (implicit) saved sorted input
# (implicit) returning left element each time
```
The nibbles are slightly re-arranged in the final program, since the 2-nibble 'sort' function ( ``<`) wraps around its argument (here `$`). Thus, the paired-up nibbles from this are:
```
-o /\ ;` @< $o / # program code (in final order)
9e ab 6e 4d 3e a # nibbles
```
We can reduce the range of bytes by inserting 'save' operators (`;`, nibble `6`) to shift high-valued nibbles into the least-significant-nibble position of each byte.
This doesn't affect the output, but we need to override the final implicit variable to account for the saved (but ignored) values. Hence:
```
;- ;o ;/ ;\ ;` @< $o ;/ ;$ # program code (in final order), with final variable changed to ;$
69 6e 6a 6b 6e 4d 3e 6a 63 # nibbles
```
Modifying both folds (so returning right element `@` instead of left element `$`) avoids the lowest byte `3e`, but unfortunately outputs a negated value.
So we multiply (and save: `;*`) the negated value by its own sign (also saved: `;`$`): this corrects the output, introducing a new highest byte of `73`, but the overall score is still reduced.
[](https://i.stack.imgur.com/KOztR.png)
[Answer]
# [Julia](https://julialang.org), 22 bytes + 80 = 102
```
+s=-(-(extrema(s)...))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700qzQnM3HBgqWlJWm6Ftu0i211NXQ1UitKilJzEzWKNfX09DQ1IZI3G6OVPFJzcvJ1FMLzi3JSFJV0lBUULIy4lBJBAMyDAwMuJef8lFQF9_ycNISMuSWXUnBJYnK2gmtFckZiXnoqxAwLLiXHYGdPTyVkIxQMLbhi9WrsCooy80py8h51zNCGOATmWgA)
[Answer]
# Java 8, score: 134 (54 bytes)
```
s->s.chars().max().orElse(0)-s.chars().min().orElse(0)
```
[**Try it online**](https://tio.run/##dVLBTuMwEL33KwafbKU1e0IrKlaCqLAcFlYExIFFq8FxGhfXruxpAaF@e7GT0q1WIpEmmTfjN@@NPMMVjmb180ZZjBF@oXHvAwDjSIcGlYarnHYAKF5RMG4KUYwTuB6kEAnJKLgCByebOPoRpWoxRC7kHF9T9GFio@bfxGivYtx@ZTPORIvlk01EW76VNzXMk5jtyIdHFNQG/xJh8qr0gox3vbDGB77CAKQjlRj1sdMv8Hnonf3U1voh3Ptg6wM2ZJif9C19reHC2yb9V4TqOfO26KY6AadVeXnJ1qIbAFC9RdJz6ZckF4mXrOOf0wp2DKxwUu0QITo7AFmUylNO4J8kPkv7ls542Rir5XkKUQaN9am1Z2@J47@G30it9A1n8lBmMpmMMyGGsGvrlqpJJhOuxlCXfR7l3e353@9CxoU1xNkfx8TD0eN48IWh3FDkCWK8Ux90XFrK@pO/vVq@C1a7KbWp1qnqMy6@pq/K65tJ3hXvWYv@iCgYcFZsMZbeHi@YYNtLtt58AA) (also contains code to extract the lambda function from the code-block and calculate its score: `(max_codepoint - min_codepoint) + length`).
Not too much too improve unfortunately.
* We could change the `x` to `\u0078`, but unfortunately the next highest codepoint then becomes `u` which isn't too much lower than `x`, so the +5 in byte-count is higher than the -3 in codepoint, giving a +2 in score instead of decrease: [Try it online](https://tio.run/##dVLBThsxEL3nK6Y@2drE5NQiIirRVaAcSiu2iAOgyvV6sw6OHdmTUITy7el4N4QIiV3J9rwZv/dm5Llaq9G8ftxqp1KCH8r6lwGA9Whio7SBqxx2AGheYbR@BklMCNwMaEmo0Gq4Ag@n2zT6mqRuVUxcyIW6X43HX47pGOLUJcPHYnSQtv4ws51ktuXqryO2Hek62BoW5Gine/egBLYxPCWY/tNmiTb43l0TIl@rCGgSliqZE2@e4PXSC/tunAtDuA3R1Z/YkKn80V6G2sBFcA2dK1T6MfO2ys8MAWdVeXnJNqITAKieE5qFDCuUS@JF5/mrWsFOgBVe6j0iRNcOQDals8opvFnicxq69DbIxjojz2lJMhpVnzn37Zk43hX8UtjK0HAmj2Qmk9Q4E2II@7JuqAYlNeFrFeuyj5O8@X3@51jItHQWObv3TNx9fpgMPmgoFxRZQUz27qNJK4fZP/V3kMsPwhk/w5Zynas@4uJj@qr8eT3Ns@I9a9FfEQUDzoodxujv8YIJtntpm@1/).
* Using a regular for-loop requires both `{}` and a space, so the difference of the max-min codepoints would widen on both ends. And in addition it's longer anyway: [Try it online](https://tio.run/##dVLBjtMwEL33KwafbKU1nBBtNotKtAt7yIIIKw6lQsZxmnQdu7KnXaqq317spFsE0iaS7Xl6897M2GuxE5N19XiSWngPhWjNYQTQGlSuFlLBfQx7ACSVjXCLpWdpwI6jsHgU2Eq4BwPZyU@uD5HXZdPpdFxkb9LaOtpnzjw7dJm86t7LWZcWmbwuwqlIj07h1hkoJl16PKVRcrP9pYPkWXln2wq6UBUt0bVmtVgKho2zTx5ufku1wdaaocLotRMOUHnMhVczo57gOelAPimt7Ri@W6erV2RMRPzCnttKwUer63AuUcjHqNsIs1IBmJf53R05st4AoNx7VB23W@SboIva0Ge3hMyAJIbLC8LR5mFcc@fEnjLG@uYAYokyembwt0C6DtfATWt53WrFb8PiuVOimmv9YR8U/yN8EdhwW1PCX/MoxsMYCGNjuNDiTXmFPLRkKuGqfIg9f/h2@/Md436jW6TkhyFs8XaZjl5oLxKS6MDSS/VO@a3GWH/odnD/p9P08mC0MitsArNnDRFlL5uV@eevN3GOdPBIhhSWEKAkOWMk/AOeEEbOT/F4@gM).
**Explanation:**
```
s-> // Method with String parameter and integer return-type
s.chars() // Convert the String to an IntStream of codepoint integers
.max() // Get the maximum of these codepoints
.orElse(0) // Convert the OptionalInt to an int
// (`.orElse(0)` is 1 byte shorter than `.getAsInt()`)
- // And subtract
s.chars().min().orElse(0)
// The same to get the minimum codepoint
```
[Answer]
# [Excel](https://www.microsoft.com/en-us/microsoft-365/excel), score = ~~103~~ 94 (length 46, range 48)
-9 score thanks to [Engineer Toast](https://codegolf.stackexchange.com/users/38183/engineer-toast)
```
=LET(A,CODE(RIGHT(A1,ROW(A:A))),MAX(A)-MIN(A))
```
[](https://i.stack.imgur.com/SzCp3.png)
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~12 bytes + 86 = 98~~ 13 bytes + 56 = 69
h/t @isaacg
```
+/1_-':@/1<:\
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs9LWN4zXVbdy0De0sYrh4srPSbHS1deo0bdW09d0iLHi4gqx0lDySM3JyVcIzy/KSVFU4lJQUFBKBAIIyzk/JVXBPT8nDcINLklMzlZwrUjOSMxLT4WIOQY7e3pCmEhmx1hBhFBcEKOkycWVph7CBQBShCQG)
[Answer]
# [MATL](https://github.com/lmendo/MATL), 3 bytes + 32 = 35
```
Sds
```
### Explanation
```
Sds
S % Sort implicit input
d % Difference between adjacent elements
s % Sum the values
```
[Try it online!](https://tio.run/##y00syfn/Pzil@P9/dY/UnJx8HYXw/KKcFEV1AA "MATL – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) + 149 = 154
I think this is about as good as it's going to get in Jelly due to the distance between `O` (unavoidable as it's the only way to get the ordinals of the input string) and the large ordinals of Unicode characters representing the bytes for mapping and getting maximums and minimums, index into a list etc.
```
OÞOIS
```
A monadic Link that accepts a list of characters and yields the range size as an integer.
**[Try it online!](https://tio.run/##y0rNyan8/9//8Dx/z@D///@rewAF8nUUwvOLclIU1QE "Jelly – Try It Online")**
### How?
```
OÞOIS - Link: list of characters (ordinal)
Þ - sort by: (222)
O - ordinal value (79)
O - ordinal values (79)
I - forward differences (73)
S - sum (83)
----
222
- 73
====
149
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 11 bytes + [63](https://tio.run/##RYy9CsIwGEX3PMW3NcHaxS2iUAShIDjUxfGz6U8gfyQZWl8@pgjtdjnn3uuWOFlzSklqZ32EsATi4QIK9UcgKA4aZ6oYHEFLkwOxuw0clAyRanTUelFCYIwMu585eGrpnKnMNH9XIQppKt@joIxghgOVjKh105s1Oi9NpEXd3poGPJqx50UJuIlHb8Y4rUxt7GUjKgid9f/yQbGU6vZ7tef7@6m7Hw) = 74
```
ASz>o;FYOmc
```
[Try it online!](https://tio.run/##yygtzv7/3zG4yi7f2i3SPzf5////Hqk5Ofk6CuH5RTkpigA "Husk – Try It Online")
```
ASz>o;FYOmc
m # map over input
c # getting character values
O # and sort into ascending order;
z # now, zip together
> # getting differences
S # the sorted list itself
# and
o; # the single-element list of
F # fold over the sorted list
Y # getting pairwise maxima
A # finally, get the average
# of the resulting single-element list.
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 42 bytes + 80 = 122
```
s=>Math.max(...b=Buffer(s))-Math.min(...b)
```
[Try it online!](https://tio.run/##Xc/BbsIwDAbgO0/hRRwSAWHbhW5SkQChwWGnHnYlhKQthBiSDDFNffauHSBV8dH@7F/ei4vw0pWnMLK4U7VOa59OP0Uo@FFcKed8m86/tVaOesZGt0Fp/weslmg9GsUN5nSTSXTqHfq/FlLQPGAWXGlzyrhRNg9FBdufoDwMGnJuCe0iVjWtdncA52rDer3ubU3JShmDQ/hCZ3ZPBBiD8RiS15iJtgg86saeY7VoXoUPNJp01OQtZlkQ8gDLqyyEzRW5ZyYxm2WL9TrOfEnqPw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Ly](https://github.com/LyricLy/Ly), 8 bytes + 70 = 78
```
ia0I-s>l
```
[Try it online!](https://tio.run/##y6n8/z8z0cBTt9gu5///4JLE5GwF14rkjMS89FQA "Ly – Try It Online")
I found a shorter program, but the character range of the code was big enough that it had a higher total score.
```
ia - read STDIN onto stack as codepoints, sort the stack
0I - copy the bottom of the stack to the top
- - subtract to get the range
s>l - save result, switch to clean stack, load result
```
[Answer]
# [Raku](https://www.raku.org/), 25 bytes
ASCII range: 88
Length: 25
Total score: 113
```
[-] @_.ords.minmax[*-1,0]
```
[Try it online!](https://tio.run/##K0gtyjH7X1yapJCmUP0/WjdWwSFeL78opVgvNzMvN7EiWkvXUMcg9n@ttUJBUWZeCVCZukdqTk6@jkJ4flFOiqL6fwA "Perl 6 – Try It Online")
[Answer]
# [J](http://jsoftware.com/), score 70 (16 bytes, range 54)
```
[:+/2-/\a.I.]\:]
```
[Try it online!](https://tio.run/##y/r/P03B1koh2kpb30hXPyZRz1MvNsYq9n9qcka@QpqCukdqTk6@jkJ4flFOiqL6fwA "J – Try It Online")
* `]` `\:` `]`: Pass the input (using the identity function [`]`](https://www.jsoftware.com/help/dictionary/d500.htm)) on both sides of [`\:`](https://www.jsoftware.com/help/dictionary/d431.htm) to sort it in descending order.
* `a.` `I.`: For each character of the sorted input, find its index in the ["alphabet"](https://www.jsoftware.com/help/dictionary/dadot.htm); at least on TIO's setup, this contains all of [ISO-8859-1](https://en.wikipedia.org/wiki/ISO-8859-1) in order, which includes ASCII. Thus, this produces the ASCII values of the characters, while keeping the highest used character lower than the straightforward method of `3` [`u:`](https://www.jsoftware.com/help/dictionary/duco.htm) would.
([`I.`](https://www.jsoftware.com/help/dictionary/dicapdot.htm) would also take the following index if a character is not found, but that never happens; it was chosen over [`i.`](https://www.jsoftware.com/help/dictionary/didot.htm) to reduce the highest used character.)
* `2-/\`: For each length-2 subarray (from the `2` and [`\`](https://www.jsoftware.com/help/dictionary/d430.htm)), subtract the second value from the first ([`-`](https://www.jsoftware.com/help/dictionary/d120.htm) [`/`](https://www.jsoftware.com/help/dictionary/d420.htm)).
* `[:` `+/`: Take the sum ([`+`](https://www.jsoftware.com/help/dictionary/d100.htm) [`/`](https://www.jsoftware.com/help/dictionary/d420.htm)) of the values, using [`[:`](https://www.jsoftware.com/help/dictionary/d502.htm) to do so monadically.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal) -v, 35 bytes, score 61
```
castminusordceilceil[q]ordminmin[q]
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z85sbgkNzOvtDi/KCU5NTMHhKMLY4E8oCgQAdnEKdItywEA "Charcoal – Try It Online") Abusing Charcoal's verbose parser again. In order for it to recognise `q` as a variable name I can't follow it with a letter, so the next nearest suitable characters are the list delimiters. I've also used `ceil` instead of `max` to avoid using an `x`; this costs 2 bytes but overall saves 1 from my score. Normally the program would be written like this:
```
Print(Cast(Minus(Ordinal(Maximum(q)), Ordinal(Minimum(q)))));
```
The best I could do in succinct Charcoal was a score of 10135:
```
⭆ψ⁻℅⌈θ℅⌊θ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCO4BEil@yYWaFTqKPhm5pUWa/gXpWTmJeZo@CZWZOaW5moUamrqKMAFM/NggkBg/f//o7Vt5zseNe5@1NL6qKfj3A4w3XVux3/dshwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: The limiting factors here are the Greek letter `θ` needed for the two occurrences of the input variable (the only other input method uses `S` which has a ridiculously high Unicode code point of 65531) and the `⭆` used to stringify the result (again, `I` would have had far too high a code point).
```
ψ Predefined string null character
⭆ Map over characters and join
θ Input string
⌈ Maximium
℅ Ordinal
⁻ Minus
θ Input string
⌊ Minimum
℅ Ordinal
Implicitly print
```
If using bytes from Charcoal's code page was allowed, its score would "only" be 210:
```
SαI⁻℅⌈α℅⌊α
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0JLikKDMvXSNR05orAMgq0XBOLC7R8M3MKy3W8C9KycxLzNHwTazIzC3NBSrS1FGAC2bmwQSBwPr//8NTDy883Hlo7aFmqcMLDzVLHl74X7csBwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: The limiting factors here are that `⌊` (`Minimum`) is byte index 25 while `α` (variable `a`) is byte index 225, although I did reduce my score by 14 by taking the input into `α` rather than the default input of `θ` (variable `q`, byte index 241).
```
S Input as a string
α Store in variable `a`
α Input string
⌈ Maximum
℅ Ordinal
⁻ Subtract
α Input string
⌊ Minimum
℅ Ordinal
I Cast to string
Implicitly print
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 8 bytes + 34 = 42
```
+F.+CDCM
```
[Try it online!](https://tio.run/##K6gsyfj/X9tNT9vZxdn3/38lGFMJAA "Pyth – Try It Online")
* `CM`: Map to ASCII value
* `CD`: Sort (equivalent to `S`)
* `.+`: Deltas (Differences between consecutive elements, all nonegative because of sort)
* `+F`: Sum (equivalent to `s`)
Using `.+` is golfier than `h` and `e`, and also stays within the established ASCII value range.
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 12 bytes + 52 = 64
```
)**J>]\/<].-
```
[Try it online!](https://tio.run/##SyotykktLixN/V/9X1NLy8suNkbfJlZP939teM5/j9ScnHwuZGEA "Burlesque – Try It Online")
```
)** # Map to char code
J # Duplicate
>] # Maximum
\/ # Swap
<] # Minimum
.- # Difference
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 98 score (18 bytes)
ASCII range: 80
Length: 18
```
s=>s.Max()-s.Min()
```
[Try it online!](https://tio.run/##ZY7LCsIwEEX3/Yoxq4Q@EJdqC1J8FCoIFVyHJG2DJZEmlYL47bUPoYizGc6Zy3CZ8ZmR3aFRbGtsLVXhgVQ2ghzCzoSRCc60xcTvt1SYdBvnKozF6CSqSiPygx7cdF3xxazpMDPGmgs46iqfVWYpu8O@ZSVVhZj9LouTZMAv/1cZj08tOYyJqXzf/dFY8nIAbrW0IpVK4NG5aI1chIIL5anILV4t/dEHqVCFLYmbTznSv313Hw "C# (Visual C# Interactive Compiler) – Try It Online")
* -27 score thanks to Kevin Cruijssen for the tip to use C# Interactive
---
# [C# (Visual C# Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 125 score (36 bytes)
ASCII range: 89
Length: 36
Total score: 125
```
s=>s.Max()-s.Min()
```
If we're going traditional through the compiler then we have to include an extra 18 bytes for `using System.Linq;`
[Try it online!](https://tio.run/##jc1LCoMwEIDhfU8xdZWAegGrUKQPoULBhesQow1NE@rEYimePY3FvZ3NwPD9DMeII3cDSt1B9UYrHvFF6mcCXDFEuMIH0DIrObyMbKBkUhPqj4s9Dprv0PY@D0Fqm0ELKThMM4xLNhIa@T0nLtksSW40GiXiupdW@F@CtCQ4C6VMQOkfKoTa9KrZrmo2z6rKTSPgZFS7KivL@B0OI78x3YlVvq/yovipCSb3BQ "C# (Visual C# Compiler) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes + 67 = score 73
```
C:G$g-
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiQzpHJGctIiwiIiwiXCJIZWxsbywgV29ybGQhXCJcblwiQzpHJGctXCJcblwiYVwiIl0=)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 31 bytes + 85 = 116
```
ToCharacterCode@s//Max@#-Min@#&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n1icnJkZlJiXnhpdHB9cUpSZlx6rYGX7PyTfOSOxKDG5JLXIOT8l1aFYX983scJBWdc3M89BWQ1Zn5JHak5Ovo5CeH5RToqiUqy@fgDQmBIuZCWJIIBdCmS8gnt@Thp26eCSxORsBdeK5AwQH7sax2BnT0@41H8A)
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2) `GB`, 2 + 24 = 26
```
G_
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPUdfJmZvb3Rlcj0maW5wdXQ9SGVsbG8mZmxhZ3M9R0I=)
Port of lyxal's Vyxal answer.
#### Explanation
```
G_ # Implicit input
# Convert to codepoints
G # Maximum codepoint
_ # Subtract each input codepoint
# Find the maximum
# Implicit output
```
[Answer]
# [Sequences](https://github.com/nayakrujul/sequences), score = 73 + 4.12 = 77.12
(Sequences uses the 96 printable ASCII characters as its codepage, so the byte count of this program is \$5\log\_{256}(96) \approx 4.12\$)
```
`vMm-
```
### Explanation
```
`vMm- # Implicit input as a string
`v # Get the ASCII values of the input string in a list
M # Get the maximum value of that list
m # Get the minimum value of that list
- # And subtract to find the range
# (implicit output)
```
[Answer]
# [Python](https://www.python.org), 39 + 80 = 119
```
print(ord(max(s:=input()))-ord(min(s)))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dY8xTgMxEEV7n2JwE1vZTUGFVtoCRQhSb5HarG1i4R1btoOSs6RJA1yDa-Q2zO6SdEz3x-9__zl9xWPZBTx_W2iBc_65L7Z-uCxiclhESFoM6iBy0zqM-yKklPW0dCgyiT_8h5yrXJKLQjI2e3nXh2QaXoE3KKysgC9JXCOtlFDDNYsUvbc3GJYg_iUl_eGGGFKBfMyM2ZDAOzTgcFxQEe2wYUAztabLvBpetWom7FZ0BMyH8pQ533G-3L8Y70MF25C8vmNqHLYO2sBz8JZ1RfXv8HTodwrfDHvs1pvNbP0F)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 26 bytes + 80 = 106
-2 bytes thanks to [Steffan](https://codegolf.stackexchange.com/users/92689/steffan)
```
->s{y=s.bytes;y.max-y.min}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuha7dO2Kqytti_WSKktSi60r9XITK3SBZGZeLUTBlgIFt2glj9ScnHwdhfD8opwURaVYiNSCBRAaAA)
[Answer]
# [Haskell](https://www.haskell.org), 27 bytes + 84 = score 111
```
_?s=(maximum$s)-(minimum$s)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8FN7dzEzDzbgqLMvBIFFQUNe00FA4VoQwNDHQUoYaGjYG4EZBgaxi4tLUnTtdgdb19sq5GbWJGZW5qrUqypq5GbmQdlQ1QsgFJQGgA)
] |
[Question]
[
# Challenge:
Given a list of integer, sort descending by their single largest digit(s). The order for numbers with the same largest digit are then sorted by second largest digit, etc.
We ignore duplicated digits in numbers. And if all digits in a number are the same, the order of those numbers in the list can be in any way you'd like.
**Example:**
```
Input: [123, 478, -904, 62778, 0, -73, 8491, 3120, 6458, -7738, 373]
Possible outputs: [8491, -904, 62778, 478, -7738, 6458, 373, -73, 3120, 123, 0]
[8491, -904, 62778, 478, -7738, 6458, -73, 373, 3120, 123, 0]
```
Why? Here are the relevant digits the numbers were sorted on:
```
Output:
[8491, -904, 62778, 478, -7738, 6458, 373, -73, 3120, 123, 0 ]
Relevant digits they were sorted on:
[[9,8], [9,4], [8,7,6], [8,7,4], [8,7,3], [8,6], [7,3], [7,3], [3,2,1,0], [3,2,1], [0]]
```
## Challenge rules:
* We ignore duplicated digits, so `478` and `-7738` will be ordered as `478, -7738`, because the largest digits are `[8,7,4]` and `[8,7,3]`, and not `[8,7,4]` and `[8,7,7,3]`.
* If multiple numbers have the same digits, the order of those can be either way. So `373` and `-73` can be sorted as both `373, -73` or `-73, 373` (digits are `[7,3]` for both of these numbers).
* If a number contains no more digits to check, it will be placed at the back of the relevant numbers. So `123` and `3120` will be sorted as `3120, 123`, because the largest digits `[3,2,1]` are the same, but `0` comes before *`none`*.
* You can assume all numbers in the input are in the range `[-999999,999999]`.
* Just one of the possible outputs is enough as result, but you are allowed to output all possible outputs where sublists can be in any permutation if you want (although I doubt it would save bytes in any language).
## General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code (i.e. [TIO](https://tio.run/#)).
* Also, adding an explanation for your answer is highly recommended.
## Test cases:
```
Input: [123, 478, -904, 62778, 0, -73, 8491, 3120, 6458, -7738, 373]
Possible outputs: [8491, -904, 62778, 478, -7738, 6458, 373, -73, 3120, 123, 0]
[8491, -904, 62778, 478, -7738, 6458, -73, 373, 3120, 123, 0]
Input: [11, -312, 902, 23, 321, 2132, 34202, -34, -382]
Possible outputs: [902, -382, 34202, -34, -312, 321, 2132, 23, 11]
[902, -382, 34202, -34, 2132, -312, 321, 23, 11]
etc. The sublist [-312, 321, 2132] can be in any permutation
Input: [9, 44, 2212, 4, 6, 6, 1, 2, 192, 21, 29384, 0]
Possible outputs: [29384, 192, 9, 6, 6, 4, 44, 2212, 21, 2, 1, 0]
[29384, 192, 9, 6, 6, 44, 4, 2212, 21, 2, 1, 0]
etc. The sublists [4, 44] and [2212, 21] can be in any permutation
Input: [44, -88, 9, 233, -3, 14, 101, 77, 555, 67]
Output: [9, -88, 67, 77, 555, 14, 44, 233, -3, 101]
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
ΣêR}R
```
[Try it online!](https://tio.run/##yy9OTMpM/f//3OLDq4Jqg/7/jzYx0VHQtbDQUbDUUTAyNgZygNgQKGhoYKijYG6uo2BqaqqjYGYeCwA "05AB1E – Try It Online")
or as a [Test suite](https://tio.run/##HU09CkIxDN49RXBuoU3Sl3bxLeIBHgjC4w0KDk4Ozp7GzQN4AN29Uv0ilDTfb6634@ly7rrb7vv38XlO96kfxjXFDa3H8H6Nfc4sgdRqoNiSBhrYHCRgg1K15UCSGcSgxW1mgk9MltWcIUaogVrC8C5hcJwFUJSdjaI@KiPQcAyI2TN@7v88gdm8wvcmFVqC382x4l7zdvEeGEHmBKNZoFIKOmz5AQ)
**Explanation**
```
Σ } # sort input by
ê # its sorted unique characters
R # reversed (to sort descending)
R # reverse the result (to sort descending)
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 9 bytes
```
{ȧdṫo₁}ᵒ¹
```
Note: due to how ordering works in brachylog, it does not work on number correctly. This is fixed by casting the number to a string (`ṫ`) at the cost of 1 byte.
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v/rE8pSHO1fnP2pqrH24ddKhnf//RxsaGesomJhb6CjEWxqY6CiYGZmDOAZAvjlQxsLE0lBHwdjQCChgZmIKUmZubgykjM2NY/9HAQA "Brachylog – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~97~~ 95 bytes
```
function(x)x[rev(order(sapply(Map(sort,Map(unique,strsplit(paste(x),"")),T),Reduce,f=paste0)))]
```
[Try it online!](https://tio.run/##LU3LasQwDLz3K8yeLFDAsZy1fdhP6KX0VnoIWQcCS@LaTtl@fSqFBTOWRvMox3w75n2d2rKt@gnPr5J@9Vbuqeg65vz40@9j1nUrDWXY1@VnT1hbqfmxNJ3H2hL78HIBwE/Aj3Tfp4Tz7bwYAPg@Zj3p3hIq5wOqLhqH6mq9LIZ3z5fgYo@KesvE1Q0i8574I08Ab2cCCzpWoIqGQfLIMmd74pWcFbYjJxDsyxS5lBlrxSe15xMXY5QYmSMFvpmXRwxd4O4oLSR5LGayNyz2HtUwDJzjAY5/ "R – Try It Online")
This challenge seems to have been pessimized for R. Explanation of the original version (start at 1. and work up):
```
f <- function(x) {
x[ # 8. Input vector in
rev( # 7. Reversed
order( # 6. Lexicographical order
sapply( # 5. Paste....
Map(sort, # 4. Sort each using...
Map(unique, # 3. Deduplicate each
strsplit( # 2. Split each string into characters
paste(x), # 1. Coerce each number to string
"")),
T), # 4. ...descending sort.
paste,collapse="") # 5. ...back into strings
)
)
]
}
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~36~~ ~~34~~ ~~33~~ 31 bytes
*-1 byte thanks to Jo King*
*-2 bytes thanks to Phil H*
```
*.sort:{sort 1,|set -<<m:g/\d/}
```
[Try it online!](https://tio.run/##HU1LCsIwEN17ilmIqCSazKSdxM9JVESwdaMorRtRz17fCOU17zuPprvWw@1Fk5a2w3zR37vn6m1I0X365kl@s7mtLsv9efkd1qP@9KJ2Oj7OqL13o11kcZQ0O/IlJEc1q5EArnByKtGRRIZQp8piqoKfqBwc6nA9bEclAGxMGBpHAZXEpnpJBpmtUXAOlNlKdvD/WQVYbMPeRTK8YAVL@4yTxfbFlpCEGAOSqo6qqsKIHoYf "Perl 6 – Try It Online")
### Explanation
```
{ } # Map each number, e.g. -373
m:g/\d/ # Extract digits: (3, 7, 3)
-<< # Negate each digit: (-3, -7, -3)
set # Convert to set to remove duplicates
| # Pass as list of pairs: (-3 => True, -7 => True)
1, # Prepend 1 for "none": (1, -3 => True, -7 => True)
sort # Sort (compares 1 and pair by string value): (-7 => True, -3 => True, 1)
*.sort: # Sort lexicographically
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~58~~ 60 bytes
`lambda a:sorted(a,key=lambda x:sorted(set(`x`))[::-1])[::-1]`
[Try it online!](https://tio.run/##VY7dCsIwDIXvfYpebtBCm3SmHfgkKmziRPFvzF3o088TmYhQ8nOS7zT9azzebzQdVpvp0l53@9a09eM@jN2@aO25e61m9flVH91YNM@mLNd17cJ2TlM/nG5jcSjWgdiaKMkal320ZkmijUcvmKSYgzUcCMIyVromwkgsvC3Lxc8Haw571mSPoK5M0CgwWo6kquOoIdEfmnEAdCKl9YTPUxYxq5nWmRNm/o9UzCVck/VHVm8gEIMHImJNVVVwE1DTGw)
[Answer]
# Pyth, ~~7~~ 6 bytes
*-1 byte by [@Sok](https://codegolf.stackexchange.com/users/41020/sok)*
```
_o_{S`
```
Pyth, which uses only printable ASCII, is at a bit of a disadvantage here. Optimally encoded this would be `6*log(95)/log(256) = 4.927` bytes, beating 05AB1E.
Explained:
```
o Sort the implicit input by lambda N:
_ reversed
{ uniquified
S sorted
' string representation [of N]
_ then reverse the result.
```
Try it [here](http://pyth.herokuapp.com/?code=_o_%7BS%60&input=%5B123%2C+478%2C+-904%2C+62778%2C+0%2C+-73%2C+8491%2C+3120%2C+6458%2C+-7738%2C+373%5D&test_suite=1&test_suite_input=%5B123%2C+478%2C+-904%2C+62778%2C+0%2C+-73%2C+8491%2C+3120%2C+6458%2C+-7738%2C+373%5D%0A%5B11%2C+-312%2C+902%2C+23%2C+321%2C+2132%2C+34202%2C+-34%2C+-382%5D%0A%5B9%2C+44%2C+2212%2C+4%2C+6%2C+6%2C+1%2C+2%2C+192%2C+21%2C+29384%2C+0%5D%0A%5B44%2C+-88%2C+9%2C+233%2C+-3%2C+14%2C+101%2C+77%2C+555%2C+67%5D&debug=0).
[Answer]
# [Python 2](https://docs.python.org/2/), ~~60~~ ~~55~~ 54 bytes
-1 byte thanks to [Jonas Ausevicius](https://codegolf.stackexchange.com/users/83921/jonas-ausevicius).
```
def f(l):l.sort(cmp,lambda n:sorted(set(`n`))[::-1],1)
```
[Try it online!](https://tio.run/##bY7BisMwDETv@QodE7AXW3IqO7BfUgrtblJ2wU1Dm0u/PjtqTwsFI1sjzfMsj/XnOvO2jdOZzm3thvpxv97W9vuyuHq6fI0nmgdTprG9T2t7nI9dtx8GHw8udlulT9pHFkdJsyNfQnK0Y7UmoFdMcirRkUSGsEu9rakKLlE5NPZps9x@55Vq07x4WPfYd1QCitGFoXEUtJLYVC/JSua3iIJAmDMbxSI9jzFQi0HtXSRjFt4SzO4zUhZLIPYXrBBjgFXVUd/3oOp/9/YH "Python 2 – Try It Online")
---
## Ungolfed
```
def f(l):
l.sort( # Sort the list in place
cmp = cmp, # ... compare with the builtin function cmp
key = k, # ... on the function k
reverse = 1 # ... in reverse
) # As the arguments are used in the right order, no names are necessary.
k = lambda n:sorted( # sort
set(`n`) # ... the set of digits
)[::-1] # reverse the result
# As '-' is smaller than the digits,
# it will be sorted to the back and ignored for sorting
```
[Try it online!](https://tio.run/##dVLBbqswELzzFSv10EQyCGxSINI7vG/osapUBwyxMDayTat8fboLaaVIqYWMd3dmdhYzX@LZWX69dqqHfmf2xwTAZMH5uIPbeoJXDCGeFRgdImgLs5GtSqjYTjP8o52tyCzLoHXTLL2CLx3PK@u0aBOR1S@2jdpZgq/kUV2QPLJbGyJjlSi/0HEFevWpfFAILn6AqHfLImIPd@sJ/odVRvphmZSNAcjQElRHPKp4PZwjON8pz8A6sHJSG8qqVoUg/SVLkhE7GjmdOgn2SB9FdTtUpxMA9g0q7j7sx/6uN7mjFlgE10OnBx0DmXw7HtPi/d7oz2SrJxUWExN4tNaRntNn0AHCJI1RHjlyG2Zrwf5i6oh3YQycFGwzQHTbxch2BGnxowzWecz3zq8QbYerwdnfCi4YlFXNIG3yksELryjIMa6wUpdNwUAUHBMv5YFgVSXwJSrxntD/lMxe2wgmSTY9hKeIZ9DkuJG64JjjhcBQlJyyqShpq/lDiQYNYZ1zUiFL60MauDckSudG1FjLHyoQPa3RZUMOBPVCKiaLHKlVxeBwOKBqdc@@fgM "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
ADṢUQµÞU
```
[Try it online!](https://tio.run/##HU27DcIwEO2ZwgPYkn3n5OwSiQUoUkUpaVAWoIsQEkPwKahpU6RNJkkWMe@QrPO9751PfX8pZX9Yp09znMfl3ZTlvk63edyu33V6bMNzG16ltG0gtiZKssZlH62pSRR4YIGSYg7WcCAQdazUJsL4WLizuzZAdZCtyR5Dy5jAUWBAjqSs46gjkSYyzgESaUgP/p9GMLN26J45QfMaULdLOJm1n7UJTpDBwyliTVVVKJGu@wE "Jelly – Try It Online")
### How it works
```
ADṢUQµÞU Main link (monad). Input: integer list
µÞU Sort by (reversed):
AD Absolute value converted to decimal digits
ṢUQ Sort, reverse, take unique values
```
[Answer]
# [Julia 1.0](http://julialang.org/), ~~50~~ 47 bytes
```
x->sort(x,by=y->sort(∪([digits(-abs(y));1])))
```
[Try it online!](https://tio.run/##XY5BasMwEEX3PYWWEkggzcgZiZJcJGRhExIcQhpsF@wb5Cw9Vi/i/CldhIAY6f@Z9zWX72vfpnk9bdc57MavYbKz75bt8i9@Hz92f@zP/TTa0HajXZz7TAfn3Hof@tt0vdmT3Sdib7IUb0KN2ZsNiYoILeiUXJM3nAjGJjc6JsK4WBhRH69JGAyY9KZGFM1lgkeJITmTuoGzlkJvcMUS6BApr2v8HaVRq8bpu3JBL76xCoaCnar@ypoPCGaKgES8aZoGeQJufQI "Julia 1.0 – Try It Online")
-3 bytes by Ashlin Harris.
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), ~~7~~ 6 bytes
```
áÉ░▀zx
```
[Try it online!](https://tio.run/##y00syUjPz0n7///wwsOdj6ZNfDStoari//9oQyNjHRNzCx1dSwMTHTMjcyDTQEfX3FjHwsTSUMfY0MhAx8zEFChvbm5soWNsbhwLAA "MathGolf – Try It Online") or as a [test suite](https://tio.run/##VY5NSgNBEIX3niLM@g10/cxU98KtF3A5zCKE@AORiDEghoBbl26y9ySCuUkuMlZ3R1CGge73vq@6HubPd7fr1c00HT@P76fDx@nw9voyrS@/v3bN9XaxWG42zX7XXM3vV9unZbN/nAZigVpEm4KiZ/NjQGuCqIkgxAG9dt6bSYSYjLOhVH@E4pf@jEoGq5znh/FiIDc8QAoMj4QJTMIQZU9aUf8j@/BUrvF/42KlsyYg8okJqmD2yvfwzxtQyiA4SVR/djbUU45TgbRIVD3ny24etTE6wSL@GMiNQDBD13XoLW9ViN5@Q6qDznyg8Qc "MathGolf – Try It Online").
## Explanation
After looking at Emigna's 05AB1E solution, I found that I didn't need the absolute operator (and my previous answer was actually incorrect because of that operator). Now the main difference is that I convert to string and get unique characters instead of using the 1-byte operator in 05AB1E.
```
áÉ Sort by the value generated from mapping each element using the next 3 instructions
░ Convert to string
▀ Get unique characters
z Sort reversed (last instruction of block)
x Reverse list (needed because I don't have a sort-reversed by mapping)
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 12 bytes
```
ñ_a ì â ñnÃw
```
[All test cases](https://ethproductions.github.io/japt/?v=1.4.6&code=8V9hIOwg4iDxbsN3&input=W1sxMjMsIDQ3OCwgLTkwNCwgNjI3NzgsIDAsIC03MywgODQ5MSwgMzEyMCwgNjQ1OCwgLTc3MzgsIDM3M10KWzExLCAtMzEyLCA5MDIsIDIzLCAzMjEsIDIxMzIsIDM0MjAyLCAtMzQsIC0zODJdCls5LCA0NCwgMjIxMiwgNCwgNiwgNiwgMSwgMiwgMTkyLCAyMSwgMjkzODQsIDBdCls0NCwgLTg4LCA5LCAyMzMsIC0zLCAxNCwgMTAxLCA3NywgNTU1LCA2N11dCi1tUg==)
Explanation:
```
ñ_ Ãw :Sort Descending by:
a : Get the absolute value
ì : Get the digits
â : Remove duplicates
ñn : Sort the digits in descending order
```
[Answer]
# [Haskell](https://www.haskell.org/), 54 52 bytes
```
import Data.List
f=r.sortOn(r.sort.nub.show);r=reverse
```
[Try it online!](https://tio.run/##ZU7LbsIwELzzFXskkhPZXoe1VeXWI1I/AHFI1SAiIEF2Wj4/naW3Yln7mNmZ3XNfLsP1uq7j7T7nhd77pW/2Y1k2py43BdDHtP0rmun7synn@VG95S4PP0Muw3rrx4k6@po3hHfP47TQ9kQH59lQkGioTjYY2nnRxqIXMDEkZ4idB7ALrY6JMBILH6v/XhitMWsoWQR1Zg/MO0bLwStac9AQ/Ys84RBw3quDnvL8qkdMaqh14gjOvqhVWkdclnQz6w7IADoLmYihtm3hKMdq/QU "Haskell – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~6~~ 7 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
èó≥ü≤♥¥
```
[Run and debug it](https://staxlang.xyz/#p=8aa2f281f3039d&i=[%22123%22,+%22478%22,+%22-904%22,+%2262778%22,+%220%22,+%22-73%22,+%228491%22,+%223120%22,+%226458%22,+%22-7738%22,+%22373%22]&a=1&m=2)
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 19 bytes
```
{⍵[⍒∪¨(∨'¯'~⍨⍕)¨⍵]}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/v/pR79boR72THnWsOrRC41HHCvVD69XrHvWueNQ7VfMQkNwaW/s/7VHbBGIUcj3qmwpUmqZgaGSso2BibqGjcGi9pYGJjoKZkTmIZwASMAfKWZhYGuooGBsaAUXMTEzBCs3NjYG0sbnxfwA "APL (Dyalog Extended) – Try It Online")
Fixed at a cost of +2 bytes thanks to OP.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~114~~ ~~111~~ 109 bytes
```
a;v(n){n=n<0?-n:n;for(a=0;n;n/=10)a|=1<<n%10;n=a;}c(int*a,int*b){a=v(*a)<v(*b);}f(a,n)int*a;{qsort(a,n,4,c);}
```
[Try it online!](https://tio.run/##lZTtbpswFIb/cxVHmSrZrVGN7dRQg3YhaTS5lEyWWmejtNLGuPbsHNK08CNKEkXHPh/vwxtbpE5/1vVu5907i7yPVSzl9zTeR7fZtsxX0kUXb6tMcv@vysoyXmVYqrwbahZid@0FxUfe@@qdXXteYnzkbtgwLyIfJ1z/@3XbdlQQRtTY3P1qsfPDt63/QxRADNBac@gTwA8lwY3bcXbDFqsF3xfIWIAKpIMAJdS43NwchFMFXD3BQoBfhfWHdJgR10QckuTbU7MJsYHRz3MTmefA2Gv422zxZ3B@@7lfyTXnPEnI3osPkU39dnW2WqOvPlNagLG5gLSQRsCdspRIzC12clNkAnSmsHBnljRmrcZFWz24CU594HA6xXEBhcRAcK2wpjKNqTaKqqk2FHI1I@g9oUA72FaKIGRo/BICY0FM2hc6x56cAcweQOo0R4sFPV/Tk1CJxUyi0loBy@USoRbFsyMO8R4O9za9dDwr8XXemPHD5R5vHZgPcfvWXYj90j5EEp5pUs1oamrySOsskye1F5nUM5qemjzSOsvkSe1FJs2MZqYmj7TOMnlSuzcJkJDRtune2oh/HPjW7/4D "C (gcc) – Try It Online")
Explanation:
f() uses qsort() to sort provided array in place. Using comparison function c() to compare numbers which evaluates numbers using v().
v() calculates a higher number if bigger digits are present in parameter.
[Edit 1]
Improved by 3 bytes. 2 byte credits to Kevin. Thanks
[Edit 2] 2 more bytes improved. Credits to gastropner. Thanks
[Answer]
# [J](http://jsoftware.com/), 17 bytes
```
{~[:\:~.@\:~@":@|
```
[Try it online!](https://tio.run/##PY27agNBDEX7/YqDGxMIy@ixq5kBw/6HDVOELCFNCpdJ/OsbNQ5C4iKde/V57PfLTKFTju/Htd/6Y95ybKe@/Rwv02nmvF/mM6/8dvb7NMH0/vbxxY6o4VEZrTirRsrCCKN6E0y0sPqS9wirWNi/URh5phUlM0wFFVPMNTfDPLvqk264o5p8fslKGGnpTNGsOuVJJjdqTYOaZQTiSBEiWJaFNeD4Aw "J – Try It Online")
## Explanation:
```
@| - find the absolute value and
@": - convert to string and
@\:~ - sort down and
~. - keep only the unique symbols
\: - grade down the entire list of strings
[: - function composition
{~ - use the graded-down list to index into the input
```
[Answer]
# [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 68 bytes
Thanks for @Arnauld for reminding me again that SpiderMonkey uses stable sort, so -4 bytes for removing `||-1`.
```
A=>A.sort((x,y,F=n=>[...new Set(""+n)].sort().reverse())=>F(x)<F(y))
```
[Try it online!](https://tio.run/##JYxBDoIwFESv0rD6jbUBihSiJWHDBVwSFgQ/BsWWtATh9FjiavJmXubVLq3r7DDNZzcND7Qfo9@47b3aS1WU3Bk7A6xsY5XSqqg55xq/5I4zBMFJ0@ZvUG5xQesQKFVFBSu9VbBRul87o50ZkY/mCT3UUSwYSWTGyDkPE0bSWB4QepZ@yZI8YkREsS/S5HJoUgofQorG3/0A "JavaScript (SpiderMonkey) – Try It Online")
# [JavaScript (Node.js)](https://nodejs.org), 72 bytes
```
A=>A.sort((x,y,F=n=>[...new Set(""+n)].sort().reverse())=>F(x)<F(y)||-1)
```
[Try it online!](https://tio.run/##JYrRCoMgGEZfRbryZyaZbhabQTe9wC6ji2g2NkKHRivo3Z2xq4/znfPul94P7vWZU2MfOowq1KqqqbduxnglG2mUUVVLKTX6i@56xklyMtD9C6BOL9p5jQFU1eAVbg3eYN9TBuE6WOPtpOlkn3jELcs5QUIWBKVlJgi65PKALLKMphAlI4izPB4XcT4yKXkcLnkHEH4 "JavaScript (Node.js) – Try It Online")
[Answer]
# [Java (JDK)](http://jdk.java.net/), 98 bytes
```
l->l.sort((a,b)->{int r=0,i=58;for(;r==0&i-->48;)r=(b.indexOf(i)>>9)-(a.indexOf(i)>>9);return r;})
```
[Try it online!](https://tio.run/##bVLBbpwwEL3vV4xyqOwWI8AQoASkKtdWPeQY5eBlIfIWMLJNlGjFt29ndjfpqq0EHubNvDejh/fqRYn97tdRj7OxHvaYh4vXQ/i52vyD9cvUem2m/xadt50aqdQOyjn4ofR02ADMy3bQLTivPIYXo3cwYok9eKun58cnUPbZcaBWgHszuWXs7N137fzduaVpoIf6OIgGh@BMxlSw5aI56MmDraNA11lR9cayytZ19EkL0aRFxW3NtqGedt3rz55p3jQlF0z9hVS284udwFYrP1anHVD28Qn38p3zDurLZgAHiBMZQJoXAYgySgO4TXJKIsxzrBRpGQcg4wSB2zSjtjyXGGQuYQ3@yGCXwLYAyggPEpUJYkksMZVpQqiQKR1Fcs0scTzCSUJkWuD0EBXPkrTou5QF1qJrIrFEgauUNE@SMjIQjCNk5HkAWZahWP5OWs9ekKsnP05ufD17wj8suf5LMGCCdn2zVr25y3VgRODh1rx2O8bDUc1Mi@bm5ovmYWuGoWs9uz9HY13oDSkyzqvLgD5UbdvNnpH4B/rw5nw3hmbx4Yyz/TBd19cNvevxNw "Java (JDK) – Try It Online")
## Explanation
```
l-> // Consumer<List<String>>
l.sort( // Use the incorporated sort method which uses a...
(a,b)->{ // Comparator of Strings
int r=0, // define r as the result, initiated to 0
i=58; // i as the codepoint to test for.
for(;r==0&i-->48;) // for each digit codepoint from '9' to '0',
// and while no difference was found.
r= // set r as the difference between
(b.indexOf(i)>>9)- // was the digit found in b? then 0 else -1 using the bit-shift operator
(a.indexOf(i)>>9); // and was the digit found in a? then 0 else -1.
return r; // return the comparison result.
}
)
```
**Note:**
I needed a way to map numbers to either `0/1` or `0/-1`.
`indexOf` has the nice property that it's consistently returning `-1` for characters not found. `-1` right-shifted by any number is always `-1`. Any positive number right-shifted by a big enough number will always produce `0`.
So here we are:
```
input input.indexOf('9') input.indexOf('9')>>9
"999" 0 0
"111119" 5 0
"123456" -1 -1
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 55 bytes
```
->a{a.sort_by{|x|x.abs.digits.sort.reverse|[]}.reverse}
```
[Try it online!](https://tio.run/##NU1bCsIwEPz3FDlAUpLd1E0@9CIlSItV/FLaKor17HVWKYTJ7uw8hnv3Wk67xe3bd1uN12E6dK/3/JyfVduN1fFyvkzjj6@G/tEPYz835bPOn@VmTk0TiK2Jkqxx2UdrtiS6eOyCS4o5WMOBQGxjrTIRxsfCpWz@EVA4SKzJHqCBTOAoMFaOpKzjqJBodWXUgiJSoxb/ntqAWXN0zpxw86tJHS6hPmsPayLUIIOHWsSauq4RJKUsXw "Ruby – Try It Online")
[Answer]
# APL(NARS), 366 chars, 732 bytes
```
_gb←⍬
∇a _s w;t
t←_gb[a]⋄_gb[a]←_gb[w]⋄_gb[w]←t
∇
∇(_f _q)w;l;r;ls;i
(l r)←w⋄→0×⍳l≥r⋄l _s⌊2÷⍨l+r⋄ls←i←l⋄→3
→3×⍳∼0<_gb[i]_f _gb[l]⋄ls+←1⋄ls _s i
→2×⍳r≥i+←1
l _s ls⋄_f _q l(ls-1)⋄_f _q(ls+1)r
∇
∇r←(a qsort)w
r←¯1⋄→0×⍳1≠⍴⍴w⋄_gb←w⋄a _q 1(↑⍴w)⋄r←_gb
∇
f←{∪t[⍒t←⍎¨⍕∣⍵]}
∇r←a c b;x;y;i;m
x←f a⋄y←f b⋄r←i←0⋄m←(↑⍴x)⌊(↑⍴y)⋄→3
→0×⍳x[i]<y[i]⋄→3×⍳∼x[i]>y[i]⋄r←1⋄→0
→2×⍳m≥i+←1⋄r←(↑⍴x)>(↑⍴y)
∇
```
For the qsort operator, it is one traslation in APL of algo page 139 K&R Linguaggio C.
I think in it there is using data as C with pointers...
Test
```
c qsort 123, 478, ¯904, 62778, 0, ¯73, 8491, 3120, 6458, ¯7738, 373
8491 ¯904 62778 478 ¯7738 6458 ¯73 373 3120 123 0
c qsort 11, ¯312, 902, 23, 321, 2132, 34202, ¯34, ¯382
902 ¯382 34202 ¯34 321 ¯312 2132 23 11
c qsort 9, 44, 2212, 4, 6, 6, 1, 2, 192, 21, 29384, 0
29384 192 9 6 6 4 44 2212 21 2 1 0
c qsort 44, ¯88, 9, 233, ¯3, 14, 101, 77, 555, 67
9 ¯88 67 77 555 14 44 233 ¯3 101
```
[Answer]
# Powershell, 44 bytes
```
$args|sort{$_-split'(.)'-ne'-'|sort -u -d}-d
```
Test script:
```
$f = {
$args|sort{$_-split'(.)'-ne'-'|sort -u -d}-d
}
@(
,( (123, 478, -904, 62778, 0, -73, 8491, 3120, 6458, -7738, 373),
(8491, -904, 62778, 478, -7738, 6458, 373, -73, 3120, 123, 0),
(8491, -904, 62778, 478, -7738, 6458, -73, 373, 3120, 123, 0) )
,( (11, -312, 902, 23, 321, 2132, 34202, -34, -382),
(902, -382, 34202, -34, -312, 321, 2132, 23, 11),
(902, -382, 34202, -34, 2132, -312, 321, 23, 11) )
,( (9, 44, 2212, 4, 6, 6, 1, 2, 192, 21, 29384, 0),
(29384, 192, 9, 6, 6, 4, 44, 2212, 21, 2, 1, 0),
(29384, 192, 9, 6, 6, 44, 4, 2212, 21, 2, 1, 0),
(29384, 192, 9, 6, 6, 44, 4, 21, 2212, 2, 1, 0) )
,( (44, -88, 9, 233, -3, 14, 101, 77, 555, 67),
,(9, -88, 67, 77, 555, 14, 44, 233, -3, 101) )
) | % {
$a, $expected = $_
$result = &$f @a
$true-in($expected|%{"$result"-eq"$_"})
"$result"
}
```
Output:
```
True
8491 -904 62778 478 -7738 6458 -73 373 3120 123 0
True
902 -382 34202 -34 2132 -312 321 23 11
True
29384 192 9 6 6 44 4 21 2212 2 1 0
True
9 -88 67 77 555 14 44 233 -3 101
```
[Answer]
# PHP, ~~87 86~~ 84 bytes
```
while(--$argc)$a[_.strrev(count_chars($n=$argv[++$i],3))]=$n;krsort($a);print_r($a);
```
Run with `-nr` or [try it online](http://sandbox.onlinephpfunctions.com/code/49f5b36a7bfa67b8f2a306b1c198753486ef2d3b).
Replace `++$i` with `$argc` (+1 byte) to suppress the Notice (and render `-n` obosolete).
**breakdown**
```
while(--$argc) # loop through command line arguments
$a[ # key=
_. # 3. prepend non-numeric char for non-numeric sort
strrev( # 2. reverse =^= sort descending
count_chars($n=$argv[++$i],3) # 1. get characters used in argument
)
]=$n; # value=argument
krsort($a); # sort by key descending
print_r($a); # print
```
`-` is "smaller" than the digits, so it has no affect on the sorting.
[Answer]
# Common Lisp, 88 bytes
```
(sort(read)'string> :key(lambda(x)(sort(remove-duplicates(format()"~d"(abs x)))'char>)))
```
[Try it online!](https://tio.run/##NcpBDsIgEEDRq0y66cyiiQhIddG7TAG1ESwBNHXj1bEbdz8v34alpIYpL88KDcuaK2bPjvpSd7tNcHn4DwaOs2Pc6H/E9e0H90phsVx9weuaI1ek7us65LnARkS9vXOe9mjUUCkYxhHOcJQSBglCgTgIMAa01nAy9AM)
Good old verbose Common Lisp!
Explanation:
```
(sort ; sort
(read) ; what to sort: a list of numbers, read on input stream
'string> ; comparison predicate (remember: this is a typed language!)
:key (lambda (x) ; how to get an element to sort; get a number
(sort (remove-duplicates ; then sort the unique digits (characters)
(format() "~d" (abs x))) ; from its string representation
'char>))) ; with the appropriate comparison operator for characters
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~75~~ 74 bytes
-1 thanks @ASCII-only
```
x=>x.OrderByDescending(y=>String.Concat((y+"").Distinct().OrderBy(z=>-z)))
```
[Try it online!](https://tio.run/##rZBRS8MwEMff@ylCnxJMS5ukS8PWPugUFGEPPvggPswsk8BMoc1wnfjZ653oi4ggDMLl7n@X@93FDpkd/HS1D3ZxfRn2L65fP@3cwofY8p9CS7akmQ5Ne8hX/cb15@PSDdaFjQ/PdGzau9iDl190wa4jpeNZmrJ86Yfog42UfT@ix6bNjoyxaZ4kUDx0O5ff9z66Wx8c/epy0/lAU5JysqXBvT48krekFJITpWtOMlMoTmZCY1BArCFTK1NyIksBwkxVWKa1hEtqmbwDcP4Ljv17CGBkAOHEFGBwJClAE6WEUCqBaiYVmlqcjmtgdWgqBKJx@c@DYLAGJ0HfyBpyxemwyMxq@ESDu0rcCngglgXwtOakqioYRf@BnD4A "C# (Visual C# Interactive Compiler) – Try It Online")
In C#, strings are considered "enumerables" of characters. I use this to my advantage by first converting each number to a string. LINQ is then leveraged to get the unique characters (digits) sorted in reverse order. I convert each sorted character array back into a string and use that as the sort key to order the whole list.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 7 bytes
```
↔Öö↔Oda
```
[Try it online!](https://tio.run/##yygtzv7//1HblMPTDm8DUv4pif///482NDLWMTG30NG1NDDRMTMyBzINdHTNjXUsTCwNdYwNjQx0zExMgfLm5sYWOsbmxrEA "Husk – Try It Online")
[Answer]
# [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3), 6 bytes
```
µᵛfG]Ṛ
```
[Try it Online!](https://vyxal.github.io/latest.html#WyIiLCIiLCLCteG1m2ZHXeG5miIsIiIsIlsxMjMsIDQ3OCwgLTkwNCwgNjI3NzgsIDAsIC03MywgODQ5MSwgMzEyMCwgNjQ1OCwgLTc3MzgsIDM3M10iLCIzLjQuMSJd)
need two bytes to reverse the end result otherwise i might have a 4 byter lol
[Answer]
# [Perl 5](https://www.perl.org/) `-nl`, 68 bytes
```
$a{eval"9876543210=~y/$_//dcr"}=$_}{say$a{$_}for reverse sort keys%a
```
[Try it online!](https://tio.run/##DcrRCoMgFIDh@/MUEu3SpR7t2EWPsGcI2RyMSYZGEFGPPufdB/@/@BRMKa07/OZCM1jqjUYlxXjtXTt13euZmnNsp/PIbq9b1TsmlvzmU/Ysx7Syr9/zzZUiFYImC3wQGnpFlQI4IVg9SECpBPTa1E6EFpDwF5f1E@dc@MPchRSFh/kP "Perl 5 – Try It Online")
] |
[Question]
[
In my room, I have this geeky clock (click for full size):
[](https://i.stack.imgur.com/lx2F2.jpg)
Most of these are not difficult to figure out, but the one for 4-o-clock is particularly tricky:
[](https://i.stack.imgur.com/Pa22c.gif)
Normally, a fraction like 1/2 doesn't make sense in modular arithmetic since only integers are involved. The correct way, then, is to see this as the *inverse* of 2, or to put it another way, [](https://i.stack.imgur.com/Pkoal.gif) is that number [](https://i.stack.imgur.com/Lzrio.gif) where [](https://i.stack.imgur.com/sIc0U.gif). Put this way, a moment's thought will reveal that [](https://i.stack.imgur.com/DlQvi.gif) because [](https://i.stack.imgur.com/ZOSq0.gif).
However, simply finding the *multiplicative* inverse would be far too easy as a challenge. So let's bump up the difficulty to exponentiation, or in other words, finding the modular logarithm or discrete logarithm of 2. In this case, 3 is the modular logarithm of 2 with respect to 7. For those of you with number theory/abstract algebra background, this means calculating the multiplicative order of 2 modulo n.
## The Challenge
Given a positive **odd** integer `n` greater than 1, output the smallest positive integer `x` where [](https://i.stack.imgur.com/0a9rg.gif).
## Examples
```
n x
3 2
5 4
7 3
9 6
11 10
13 12
15 4
17 8
19 18
21 6
23 11
25 20
27 18
29 28
31 5
33 10
35 12
37 36
39 12
41 20
43 14
45 12
47 23
49 21
51 8
53 52
55 20
57 18
59 58
61 60
63 6
65 12
67 66
69 22
71 35
73 9
75 20
77 30
79 39
81 54
83 82
85 8
87 28
89 11
91 12
93 10
95 36
97 48
99 30
101 100
103 51
105 12
107 106
109 36
111 36
113 28
115 44
117 12
119 24
121 110
123 20
125 100
127 7
129 14
131 130
133 18
135 36
137 68
139 138
141 46
143 60
145 28
147 42
149 148
151 15
153 24
155 20
157 52
159 52
161 33
163 162
165 20
167 83
169 156
171 18
173 172
175 60
177 58
179 178
181 180
183 60
185 36
187 40
189 18
191 95
193 96
195 12
197 196
199 99
201 66
```
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 6 bytes
```
R2*%i1
```
[Try it online!](http://jelly.tryitonline.net/#code=UjIqJWkx&input=&args=MjAx)
### How it works
```
R2*%i1 Input: n
R Range; yield [1, ..., n].
2* Compute [2**1, ..., 2**n].
% Hook; take all powers modulo n.
i1 Get the index of the first 1.
Indices are 1-based, so index k corresponds to the natural number k.
```
[Answer]
# Pyth - ~~9~~ 8 bytes
```
f!t.^2TQ
```
[Test Suite](http://pyth.herokuapp.com/?code=f%21t.%5E2TQ&test_suite=1&test_suite_input=3%0A5%0A7%0A9%0A11%0A13%0A15%0A17%0A19%0A21%0A23%0A25%0A197%0A201&debug=0).
`f`ilters from default of 1 till it finds some x such that modular exponentiation with 2 and the input equals 1.
[Answer]
## Python, 32 bytes
```
f=lambda n,t=2:t<2or-~f(n,2*t%n)
```
Starting with 2, doubles modulo n until the result is 1, recursively incrementing each time, and ending with a count of 1 for the initial value of 2.
[Answer]
## Mathematica, 24 bytes
```
2~MultiplicativeOrder~#&
```
I just used a built-in for this.
[Answer]
# APL, 8 bytes
```
1⍳⍨⊢|2*⍳
```
This is a monadic function train that accepts an integer on the right and returns an integer. To call it, assign it to a variable.
Explanation (calling the input `x`):
```
2*⍳ ⍝ Compute 2^i for each i from 1 to x
⊢| ⍝ Get each element of the resulting array modulo x
1⍳⍨ ⍝ Find the index of the first 1 in this array
```
Note that the result may be incorrect for large inputs since the exponential gets rounded.
[Answer]
# Pyth, 14 bytes
```
VQIq%^2hNQ1hNB
```
Explanation:
```
VQIq%^2hNQ1hNB
# Implicit, Q = input
VQ # For N in range(0, Q)
Iq 1 # If equals 1
%^2hNQ # 2^(N + 1) % Q
hN # Print (N + 1)
B # Break
```
Try it [here](https://pyth.herokuapp.com/?code=VQIq%25%5E2hNQ1hNB&input=201&debug=0)
[Answer]
# JavaScript (ES6), 28 bytes
```
f=(n,t=2)=>t<2||-~f(n,2*t%n)
```
Based on @xnor's brilliant recursive approach.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes
Code:
```
DUG2NmX%iNq
```
Explanation:
```
DUG2NmX%iNq
D # Duplicates the stack, or input when empty
U # Assign X to last item of the stack
G # For N in range(1, input)
2Nm # Calculates 2 ** N
X # Pushes X
% # Calculates the modulo of the last two items in the stack
i # If equals 1 or true, do { Nq }
N # Pushes N on top of the stack
q # Terminates the program
# Implicit, nothing has printed, so we print the last item in the stack
```
[Answer]
# Julia, ~~25~~ 24 bytes
```
n->endof(1∪2.^(1:n)%n)
```
This is simple - `2.^(1:n)%n` finds the powers of 2 within the set, `∪` is `union`, but serves as `unique` and returns only one of each unique power (and because it's an infix operator, I can union with 1 to save a byte over the `∪(2.^(1:n)%n)` approach). Then `endof` counts the number of unique powers, because once it hits 1, it'll just repeat the existing powers, so there'll be as many unique values as the power that produces 1.
[Answer]
## Seriously, 14 bytes
```
1,;╗R`╙╜@%`Míu
```
Hex Dump:
```
312c3bbb5260d3bd4025604da175
```
[Try It Online](http://seriouslylang.herokuapp.com/link/code=312c3bbb5260d3bd4025604da175&input=175)
Explanation:
```
,;╗ Make 2 copies of input, put 1 in reg0
R push [0,1,...,n-1]
` `M map the quoted function over the range
╙ do 2^n
╜@% modulo the value in reg0
1 íu Find the 1-index of 1 in the list.
```
[Answer]
## Haskell, 30 bytes
```
n%1=1
n%t=1+n%(2*t`mod`n)
(%2)
```
Helper argument `t` is doubled modulo `n` each step until it equals 1.
[Answer]
# Japt, 17 bytes
```
1oU f@2pX %U¥1} g
```
[Try it online!](http://ethproductions.github.io/japt?v=master&code=MW9VIGZAMnBYICVVpTF9IGc=&input=OQ==)
This would be three bytes shorter if Japt had a "find the first item that matches this condition" function. *Starts work on one*
### How it works
```
1oU f@2pX %U¥1} g // Implicit: U = input number
1oU // Generate a range of numbers from 1 to U.
// "Uo" is one byte shorter, but the result would always be 0.
f@ } // Filter: keep only the items X that satisfy this condition:
2pX %U¥1 // 2 to the power of X, mod U, is equal to 1.
g // Get the first item in the resulting list.
// Implicit: output last expression
```
[Answer]
# PARI/GP, 20 bytes
```
n->znorder(Mod(2,n))
```
[Answer]
# Julia, ~~33~~ 26 bytes
```
n->findfirst(2.^(1:n)%n,1)
```
This is a lambda function that accepts an integer and returns an integer. To call it, assign it to a variable.
We construct an array as 2 raised to each integer power from 1 to `n`, then we find the index of the first 1 in this array.
Saved 7 bytes thanks to Glen O!
[Answer]
## Perl 5, 29 bytes
```
$n=<>;{2**++$_%$n-1?redo:say}
```
[Hat tip.](/a/68033)
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 13 bytes
```
it:Hw^w\1=f1)
```
Runs on Octave with the [current GitHub commit](https://github.com/lmendo/MATL/commit/77a5eba228ccedec8ac0d58d0f1842aba03858cc) of the compiler.
Works for input up to `51` (due to limitations of the `double` data type).
### Example
```
>> matl it:Hw^w\1=f1)
> 17
8
```
### Explanation
```
i % input, "N"
t: % vector from 1 to N
Hw^ % 2 raised to that vector, element-wise
w\ % modulo N
1= % true if it equals 1, element-wise
f1) % index of first "true" value
```
[Answer]
# [Unicorn](https://github.com/vihanb/Unicorn), ~~1307 1062~~ 976 bytes
```
( ✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨ 🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄 ( 🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐 🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈 🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈 🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄 2 ) 🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄 🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐 🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈 ✨✨✨✨✨✨✨✨✨✨ 2 🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈 🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈 🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤 ✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨ ✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨ ( 🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐 🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈 2 ✨✨✨✨✨✨✨ 🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈 🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄 🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐🐐 ) ) ( 🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈 ✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨ 🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤🌤 🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄🦄 🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈 🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈 ( ) )
```
I'm attempting to make unicorn a serious golfing language but that's a bit difficult...
Hopefully I'll find a way to retain the "unicorn-ness" of the language while making *much* less bytes
---
Picture:
## [enter image description here](https://i.stack.imgur.com/RS3ot.png)
Uses a [custom](https://github.com/vihanb/Unicorn/blob/master/encoding.txt) encoding.
This answer is non-competing because it uses a version of Unicorn made after this language
[Answer]
# 𝔼𝕊𝕄𝕚𝕟, 11 chars / 22 bytes
```
↻2ⁿḁ%ï>1)⧺ḁ
```
`[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter.html?eval=true&input=25&code=%E2%86%BB2%E2%81%BF%E1%B8%81%25%C3%AF%3E1%29%E2%A7%BA%E1%B8%81)`
Uses a while loop. This is one of the few times a while loop is better than mapping over a range.
# Explanation
```
// implicit: ï = input, ḁ = 1
↻2ⁿḁ%ï>1) // while 2 to the power of ḁ mod input is greater than 1
⧺ḁ // increment ḁ
// implicit output
```
[Answer]
# CJam, 15 bytes
```
2qi,:)f#_,f%1#)
```
Peter Taylor saved a byte. Neat!
[Answer]
# Prolog, 55 bytes
**Code:**
```
N*X:-powm(2,X,N)=:=1,write(X);Z is X+1,N*Z.
p(N):-N*1.
```
**Explained:**
```
N*X:-powm(2,X,N)=:=1, % IF 2^X mod N == 1
write(X) % Print X
;Z is X+1, % ELSE increase exponent X
N*Z. % Recurse
p(N):-N*1. % Start testing with 2^1
```
**Example:**
```
p(195).
12
```
Try it online [here](http://swish.swi-prolog.org/p/wbJDbkIG.pl)
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-æ`](https://codegolf.meta.stackexchange.com/a/14339/), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
©2pU %N¶1
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LeY&code=qTJwVSAlTrYx&input=MjAx)
[Answer]
# [Python 3](https://docs.python.org/3/), 37 bytes
```
f=lambda n,x=1:2**x%n==1or 1+f(n,x+1)
```
[Try it online!](https://tio.run/##RVPBatwwEL3rK6aGwDoJYceSLCngY3vuqadCcbN2anC9i@2Ay7Lfvn0zMgSMx5p5evP0xrr8W/@cJ3u/983Y/v19aml63hp@rR4ft4epafg8Ez/1B2SfuLyv3bL@emuXbqGGiqKwVJHx5MgEsmQS1WSYiY8IlhhF1ioHingnYoSKBVahzgieKqCrkEuJKgTL5PG2SmS9Ell0wDabdOVYtzlAQO8yxAUCq3EgAbNn6ektedGY2/jcxifyCDWEIFlb0VNnjjpQLStwYBWY0N4ESwnvzBEgREIiaDERUqEgWorARy89Y9BTxKQnTKzEKZ8meT1GCuQASUm5@Cie6QfkssSsho8QfBRTj0n3MRhztNqDxV8xGA7rBnhcyRoOsI4BjlQa/d4CVgcJSa1jeM2qQewWRpsVMgyvdQ2glQ947qQA08U2husqAbY7ae2EURI4AWQh2qxlN5/hvtdfIuUI/9EUEZ1rTexADCFqAYxeWmIOqg2D4CBIzEI1YBheC0AG@YiClErcVcb9OBiK03X@CRljSSISc0lST7vjmAznRCI8psJs6hr/ujE9LoPcABom@rwJL8tlHNZD8XMqyldDuEC04XYIYC@VkkVqmNbDJIteAMs6H3CxSkkMveS@NLQJA9HcDktHP9rxo/s6z2cAi2/tMHan3F/60nW6PVO3Xbq3FfnrdqN2OtH7eaVrv92K0nTj0gndZZbGxfd2WQBsx/GTZHkpyvt/ "Python 3 – Try It Online")
Thanks Maria Miller for saving me 1 byte.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 35 bytes
```
i;f(n){for(i=1;(1<<i++)%n-1;);--i;}
```
Gives accurate results up to \$x=31\$, otherwise the result is 32.
[Try it online!](https://tio.run/##DcixCoAgEADQ3a@QQLjDHGw9@5OWUIwbOkOiRfx2840vuivGMZgyCLZcKvDuCXwIbC0acZ6QnGPqg@XV98kCX@GEqik9PXV2hsWkQ5ZVZ9g8Iqk@fg "C (gcc) – Try It Online")
] |
[Question]
[
Given a list of positive integers that contains at least 3 distinct entries, output a permutation of that list that isn't sorted in ascending or descending order.
### Examples
```
1,2,3 -> 2,1,3 or 3,1,2 or 1,3,2 or 2,3,1
1,2,3,3 -> 2,1,3,3 or 3,1,2,3 or 1,3,2,3 etc..
```
Thanks @Arnauld and @NoOneIsHere for the title!
[Answer]
# JavaScript (ES6), ~~39~~ 34 bytes
```
a=>[a.sort((x,y)=>x-y).pop(),...a]
```
Sort the array in ascending order, pop the last element and use it as the first element of a new array. Then destructure the remaining elements of the original array into the new array (In JS, both `sort` and `pop` modify the original array).
---
## Test it
```
o.innerText=(f=
a=>[a.sort((x,y)=>x-y).pop(),...a]
)(i.value=[1,2,3]);oninput=_=>o.innerText=f(i.value.split`,`)
```
```
<input id=i><pre id=o>
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 2 bytes
```
o↻
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/P/9R2@7//6MNdYx0jHWMY//7AwA "Brachylog – Try It Online")
or
```
o↺
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/P/9R267//6MNdYx0jHWMY//7AwA "Brachylog – Try It Online")
Sorts then rotates the list
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
Ṣṙ1
```
[Try it online!](https://tio.run/##y0rNyan8///hzkUPd840/P//f7ShjoKRjoJxLAA "Jelly – Try It Online")
[Answer]
# [Ohm](https://github.com/MiningPotatoes/Ohm), 2 bytes
```
S╙
```
[Try it online!](https://tio.run/##y8/I/f8/@NHUmf//RxvqKBjpKBjHAgA "Ohm – Try It Online")
Sort and rotate to the right.
[Answer]
# [Japt](https://github.com/ETHproductions/japt/), 3 bytes
```
n é
```
[Test it](http://ethproductions.github.io/japt/?v=2.0a0&code=biDp&input=WzIsMSwzXQ==)
Sorts (`n`) the array and rotates it (`é`) one element to the right.
[Answer]
# [Python 3](https://docs.python.org/3/), 31 bytes
```
lambda a:sorted(a)[1:]+[min(a)]
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHRqji/qCQ1RSNRM9rQKlY7OjczD8iO/V9QlJlXopGmEW2oY6RjrGOiYxqrqfkfAA "Python 3 – Try It Online")
-1 byte thanks to xnor
[Answer]
# APL, 9 bytes
```
{1⌽⍵[⍋⍵]}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT/8PBNWGj3r2PurdGv2otxtIxdYqGCoYKRgrGHNhypgAxS0UTBXMwSosgXxTIMsSyDZSMAEA)
**How?**
`⍵[⍋⍵]` - sort the list
`1⌽` - rotate by 1
[Answer]
# TI-Basic (TI-84 Plus CE), 31 bytes
```
Prompt A
SortA(LA
max(LA→B
dim(LA)-1→dim(LA
augment({B},LA
```
Prompts for input in the format `{1,2,3,4}`.
TI-Basic is a [tokenized language](http://tibasicdev.wikidot.com/one-byte-tokens), all tokens used here are one-byte.
Explanation:
```
Prompt A # 3 bytes, store user input in LA
SortA(LA # 4 bytes, sort LA ascending
max(LA→B # 6 bytes, save the last value in the sorted list to B
dim(LA)-1→dim(LA # 11 bytes, remove the last value from LA
augment({B},LA # 7 bytes, prepend B to LA and implicitly print the result
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~7~~ ~~5~~ 4 bytes
```
.P1S
```
[Try it online!](https://tio.run/##K6gsyfj/Xy/AMPj//2hDHQUjHQXjWAA "Pyth – Try It Online")
*-1 byte thanks to FryAmTheEggman*
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes
```
{Á
```
[Try it online!](https://tio.run/##MzBNTDJM/f@/@nDj///RhjogaKRjomMcCwA "05AB1E – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes
```
{À
```
[Try it online!](https://tio.run/##MzBNTDJM/f@/@nDD///RRjoKJjoKxjoKpjoKhjoKRmC2SSwA "05AB1E – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina), 21 bytes
```
O#`
s`(.*)¶(.*)
$2¶$1
```
[Try it online!](https://tio.run/##K0otycxL/P/fXzmBqzhBQ09L89A2EMmlYnRom4rh///GXMZcRlyGAA "Retina – Try It Online") Sort and rotate as per usual. At least there's no unary conversion this time.
[Answer]
# Java 8, ~~68~~ 37 bytes
```
l->{l.sort(null);l.add(l.remove(0));}
```
-31 bytes thanks to *@Nevay* (forgot Java 8 had a `List#sort(Comparator)` method..)
Modifies the input-`ArrayList`, instead of returning a new one.
**Explanation:**
[Try it here.](https://tio.run/##nU7LasMwELz7K@Yol1jp42hS6L0NhRxLDxtZaeXKkpHWLib4213ZDjTHUlgtzKzmUVNPhW@1q6uvyTStD4w6cbJjY@VNCWC7xSsl2p/AnxrHgXWhfOc4U5ZixAsZd84A41iHEymN/QyB3psKSjyFQMOziQybl0iXMb00kYmNwh4OO0y2eDxbGVO@cJ1NP62kqhJWBt34XovbPC/HqVylbXe0SXpxWHKa1EIcOBj38fYOytcKV9nz2sHp719yrRYlxQXdbe43DylmUTqpxKy5wMMQWTfSdyzblMHWXV//av4v@zEbpx8)
```
l->{ // Method with ArrayList parameter and no return-type
l.sort(null); // Sort the input-list (no need for a Comparator, thus null)
l.add(l.remove(0)); // Remove the first element, and add it last
} // End of method
```
[Answer]
# Haskell, ~~36~~ 37 bytes
```
import Data.List
f(a:b)=b++[a];f.sort
```
~~Use view patterns to match on the head of a sorted version of the input list, then append the first item of the list to the tail of the remaining list.~~
View patterns aren't worth it. Sort the list, take the head off, append it to the end. In this case, it turns out that the naive solution typed out compactly is the best.
[Answer]
# [Perl 6](https://perl6.org), ~~43~~ 19 bytes
```
{first {&&![>=] $_},.permutations}
```
[Try it](https://tio.run/##K0gtyjH7X1qcqlBmppdszZVbqaCWl1@iW5xfVKJg@786LbOouEShWjHaxjZWQyVeU01NMdrONlZBJb5WR68gtSi3tCSxJDM/r7j2f3FipQJcq4ahjpGOseZ/AA "Perl 6 – Try It Online")
```
*.sort[1..*,0].flat
```
[Try it](https://tio.run/##K0gtyjH7X1qcqlBmppdszZVbqaCWl1@iW5xfVKJg@19LD8SINtTT09IxiNVLy0ks@W/NVZxYqQBXpGGoY6RjrPkfAA "Perl 6 – Try It Online")
Note that `[1..*,0]` would result in `((2,3),1)`, so `.flat` is there to turn it into `(2,3,1)`
[Answer]
# Mathematica, 18 bytes
```
RotateLeft@Sort@#&
```
[Try it online!](https://tio.run/##y00sychMLv6fZvs/KL8ksSTVJzWtxCE4v6jEQVntf0BRZl6JgkNadLWhjpGOcW3sfwA "Mathics – Try It Online")
[Answer]
# [Ly](https://esolangs.org/wiki/Ly), 7 bytes
```
&nasprl
```
[Try it online!](https://tio.run/##y6n8/18tL7G4oCjn/39DBWMIBAA "Ly – Try It Online")
Ugh, ruining the sort is so expensive!
Explanation:
```
&nasprl
&n # take input as a list of numbers
a # sort
sp # save top of stack and pop
r # reverse stack
l # load saved item
```
[Answer]
# R, ~~33~~ ~~32~~ 29 bytes
Takes input from stdin. Sorts the list and then moves the first element to the end, ensuring that it is no longer sorted. Saved three bytes due to Giuseppe.
```
c(sort(x<-scan())[-1],min(x))
```
Another implementation, same byte count:
```
c((x<-sort(scan()))[-1],x[1])
```
[Answer]
# [Ohm](https://github.com/MiningPotatoes/Ohm), 2 bytes
```
S╜
```
[Try it online!](https://tio.run/##y8/I/f8/@NHUOf//RxvqKBjpKBjHAgA "Ohm – Try It Online")
I think this is dissimilar enough from totallyhuman's post to post a new answer; I hope you don't mind :P **EDIT**: DAMMIT YOU NINJA'D ME
[Answer]
# Python, 31 bytes
```
def f(a):a[1:]=a[a.sort():0:-1]
```
Yet another Python solution.
Sadly, this one has the same length to [HyperNeutrino's answer](https://codegolf.stackexchange.com/a/138846/44718).
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), 3 bytes
```
ȯ1«
```
[Try it online!](https://tio.run/##S0/MTPz//8R6w0Or/6c@apv4P9pIwVDBOBYA "Gaia – Try It Online")
Same as other answers: sort `ȯ` and rotate left once `1«`.
[Answer]
# [Retina](https://github.com/m-ender/retina), 10 bytes
```
O#`
O^#-2`
```
[Try it online!](https://tio.run/##K0otycxL/P/fXzmByz9OWdco4f9/Yy5jLiMuQwA "Retina – Try It Online")
```
O#` Sort the list
O^#-2` Reverse sort the list other than the last element
```
This leaves the list with the 2nd highest element first and the highest element last which is never correctly sorted
[Answer]
# Ruby, 18 bytes
Submitted on mobile. Please don't kill me for problems.
```
->a{a.sort.rotate}
```
[Answer]
# Pyth, 5 bytes
```
.>SQ1
```
# Explanation
`SQ` - sort input list
`.>SQ1` - rotate input list cyclicaly by 1
[Answer]
# [Proton](https://github.com/alexander-liao/proton), 19 bytes
```
a=>sorted(a)[1to,0]
```
[Try it online!](https://tio.run/##KyjKL8nP@@@QZvs/0dauOL@oJDVFI1Ez2rAkX8cg9n9BUWZeiUaaRrShjoKRjoKpjoKJjoJxrKbmfwA "Proton – Try It Online")
-2 bytes indirectly thanks to xnor
~~Not yet working on TIO; waiting for a pull.~~
[Answer]
# [Python 3](https://docs.python.org/3/), 28 bytes
```
lambda a:a[1:a.sort()]+a[:1]
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHRKjHa0CpRrzi/qERDM1Y7MdrKMPZ/QVFmXolGmka0sY6RjqGOSaym5n8A "Python 3 – Try It Online")
`a.sort()` sorts `a` in place and returns `None`. `None` can be used as a slicing index and is the same as omitting that index.
[Answer]
# [Python 3](https://docs.python.org/3/), 31 bytes
```
lambda a:a.sort()or[a.pop(),*a]
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHRKlGvOL@oREMzvyg6Ua8gv0BDU0crMfZ/QVFmXolGmka0oY6RjqmOsY5JrKbmfwA "Python 3 – Try It Online") or [Verify all test cases.](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHRKlGvOL@oREMzvyg6Ua8gv0BDU0crMfZ/QVFmXomGeppGtKGOkY5xrKaCra26jgKCr8mFpgRTEVjZfwA "Python 3 – Try It Online")
Inspired by Shaggy's [JS answer](https://codegolf.stackexchange.com/a/138858/66459).
[Answer]
# [RProgN 2](https://github.com/TehFlaminTaco/RProgN-2), 2 bytes
```
§›
```
[Try it online!](https://tio.run/##Kyooyk/P0zX6r2GoYKpgrGCkYKj5/9DyRw27/v8HAA "RProgN 2 – Try It Online")
[Answer]
# PHP, 44 bytes
requires PHP 5.4 or later for short array syntax.
```
sort($a=&$argv);print_r([array_pop($a)]+$a);
```
sort arguments, replace 0-th argument with removed last argument, print.
Run with `-nr` or [try it online](http://sandbox.onlinephpfunctions.com/code/61de8dc832ad8353be98057afb38130261abb47a).
---
The 0-th argument is the script file name, `"-"` if you call PHP with `-r`. `"-"` is compared to the other arguments as a string, and since `ord("-")==45`, it is smaller than any number. The numbers themselves, although strings, are compared as numbers: `"12" > "2"`.
`php -nr '<code>' 3 4 2 5 1` and `sort($a=&$argv)` lead to `$a=["-","1","2","3","4","5"]` →
`[array_pop($a)]+$a` is `[0=>"5"]+[0=>"-",1=>"1",2=>"2",3=>"3",4=>"4"]`,
which results in `[0=>"5",1=>"1",2=>"2",3=>"3",4=>"4"]`.
[Answer]
# Julia, 23 bytes
```
f(x)=sort(x)[[2:end;1]]
```
Slightly shorter than, but equivalent to `f(x)=circshift(sort(x),1)`.
I wish I could makeamethod based on `select` that was more, compact but I can not
] |
[Question]
[
**This question already has answers here**:
[Output the Hebrew alphabet](/questions/96950/output-the-hebrew-alphabet)
(27 answers)
[Print the Greek alphabet!](/questions/97049/print-the-greek-alphabet)
(48 answers)
Closed 6 years ago.
[Apparently](https://codegolf.stackexchange.com/questions/96950/output-the-hebrew-alphabet), we [really like](https://codegolf.stackexchange.com/questions/97049/print-the-greek-alphabet) printing [the alphabet](https://codegolf.stackexchange.com/questions/67357/output-the-alphabet-the-alphabet-or-just-a-character) in different languages.
How about the Russian Cyrillic alphabet?
Print/output/return this exact text (trailing whitespace is permitted)
```
АаБбВвГгДдЕеЁёЖжЗзИиЙйКкЛлМмНнОоПпРрСсТтУуФфХхЦцЧчШшЩщЪъЫыЬьЭэЮюЯя
```
This is the Russian Cyrillic alphabet with upper and lower case interleaved (eg `AaBbCc...`)
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so crunch those bytes folks!
[Answer]
# [Рапира](https://en.wikipedia.org/wiki/Rapira) (Rapira), ~~172~~ 142 bytes
```
ВЫВОД: "АаБбВвГгДдЕеЁёЖжЗзИиЙйКкЛлМмНнОоПпСсТтУуФфХхЦцЧчШшЩщЪъЫыЬьЭэЮюЯя"
```
[Try it online!](https://tio.run/##DczFEcIAAAXRVpiUQTc5cmPoILhDILgNLsHdaWF/RSGHvbzDRsxwKGJ6HhVcvz5OMGBQZo/NwYcjVU44nKlxwZJNnSsNbjS50@JBmycdXnR50@PjL74M@DGUxUhRxooxUZypEsyUZK4UC6VZKsNKWVzlWCvPRgW2KrJTyfC8Pw "Rapira – Try It Online")
Just for fun, given the challenge. It may not be golfed; I'm not really familiar with the language.
[Answer]
# Mathematica, ~~43~~ 42 bytes
`Alphabet` is a built-in function.
-1 byte from Martin.
```
ToUpperCase@#<>#&/@Alphabet@"Russian"<>""&
```
This may not work on some older versions of Mathematica, but it does work on [Wolfram sandbox](https://sandbox.open.wolframcloud.com "Wolfram sandbox") and [Try it online!](https://tio.run/##RY7BasMwEETv@opFgdAG4/5AGlxKDz30kjYnY8hGXtUCeyWkdeN8vWs50F7nDW9mQOloQHEGZ/s8f/lTCBRfMVG12R8226fqpQ8dXkgqfRxTcsh6f9B6Oz/s1LuFK0HrIhnpbxCiY0mwCMF4FmIBb8HWDWAChCQL/y7g438Srq7vFSWDgcAJiIcTO@PbbGiphE@fFzr8ocxoCj7KOnCX5RDBup4Khdxmwvcba0loErjcII7MuX02KOdS7R6VeltVtRYaQimT6CIfbdRx5FovNfgDzfwL "Wolfram Language (Mathematica) – Try It Online").
---
Another version without builtin `Alphabet` or `ToUpperCase`:
# Mathematica, ~~82~~ 66 bytes (64 chars)
```
Insert[FromCharacterCode@{#,#+32}&/@(1039+Range@32),"Ёё",6]<>""&
```
or
```
Insert[FromCharacterCode@{#,#+32}&/@1040~Range~1071,"Ёё",6]<>""&
```
Unfortunately Martin's trick (use `a<>b` instead of `{a,b}`) doesn't work here.
[Try it online!](https://tio.run/##jc3NasJAFIbh/VzF4QjiT7CJKRXFSIpYcFfcpllM05NJwMzI5PhTpIKX4J3pFaXBumhddfvB872F5IwKyXkiqzSo5roky9GLNcU0k1YmTHZqPijcN5xG1@9/NR/Cluf6w@5CakWh3287eD5eTug8xeMJYrNqdeB5WTNdn24INmTL3GjY5pxBKQuC90@mxKw1j6DTFkIF4j9Vz310D9fowXMH3l1ViFebaw7xTadRDAGgmO1Wpj7FtMc7RgfqPRaLtY4wkQw/a/zLqTunbk79cermqm8 "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 18 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
40r71s6j25Q+ȷỌżŒl$
```
A full program. Pretty similar in nature to an [existing answer by Erik the Outgolfer](https://codegolf.stackexchange.com/a/127683/53748), but I *think* it's different enough.
**[Try it online!](https://tio.run/##y0rNyan8/9/EoMjcsNgsy8g0UPvE9oe7e47uOTopR@X/fwA "Jelly – Try It Online")**
### How?
```
40r71s6j25Q+ȷỌżŒl$ Main link: no arguments
40r71 inclusive range from 40 to 71: [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]
s6 split into sixes: [[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]]
j25 join with 25s: [40,41,42,43,44,45,25,46,47,48,49,50,51,25,52,53,54,55,56,57,25,58,59,60,61,62,63,25,64,65,66,67,68,69,25,70,71]
Q de-duplicate: [40,41,42,43,44,45,25,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]
ȷ literal 1000
+ addition: [1040,1041,1042,1043,1044,1045,1025,1046,1047,1048,1049,1050,1051,1052,1053,1054,1055,1056,1057,1058,1059,1060,1061,1062,1063,1064,1065,1066,1067,1068,1069,1070,1071]
Ọ cast to characters: "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ"
$ last two links as a monad:
Œl lowercase: "абвгдеёжзийклмнопрстуфхцчшщъыьэюя"
ż zip: ["Аа","Бб","Вв","Гг","Дд","Ее","Ёё","Жж","Зз","Ии","Йй","Кк","Лл","Мм","Нн","Оо","Пп","Рр","Сс","Тт","Уу","Фф","Хх","Цц","Чч","Шш","Щщ","Ъъ","Ыы","Ьь","Ээ","Юю","Яя"]
implicit print: АаБбВвГгДдЕеЁёЖжЗзИиЙйКкЛлМмНнОоПпРрСсТтУуФфХхЦцЧчШшЩщЪъЫыЬьЭэЮюЯя
```
[Answer]
# C#, Java, Javascript 137 bytes
Note: Java is only valid if you replace `=>` with `->`
```
s=>"АаБбВвГгДдЕеЁёЖжЗзИиЙйКкЛлМмНнОоПпРрСсТтУуФфХхЦцЧчШшЩщЪъЫыЬьЭэЮюЯя"
```
Ahhhh!!! Found a shorter way for
# C#, 102 99 bytes
```
a=>string.Concat(new string[32].Select((x,i)=>(x=(char)(i+1040)+"")+x.ToLower())).Insert(12,"Ёё")
```
Shortened it by using a different approach
[Try it Online!](https://tio.run/##Sy7WTS7O/K@g4Faal2xTXFKUmZeuowCh7RTSgIIKtgr/E23tIEJ6zvl5yYklGnmp5VBF0cZGsXrBqTmpySUaGhU6mZq2dhoVthrJGYlFmhqZ2oYGJgaa2kpKmtoVeiH5PvnlqUUampqaep55xalFJRqGRjpKFxovTlTS/G/NFV6UWZKqAbJTA6hB0/o/AA)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~75~~ ~~38~~ ~~32~~ ~~24~~ ~~23~~ 22 bytes
```
;Bi";<=>?@," c+981 ®+v
```
[Test it](https://ethproductions.github.io/japt/?v=1.4.5&code=O0JpIjs8PT4/QCwiIGMrOTgxIK4rdg==&input=)
* 1 byte saved thanks to ETHproductions.
---
## Explanation
```
;B :The uppercase alphabet
i :Prepend ...
";<=>?@," : this string
c :Map over the charcodes of each character in the string...
+981 : and increment them by 981
® :Map over each character in the string, replacing them with themselves...
+Zv : and their lowercase selfs
:Implicit output of resulting string
```
---
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~20~~ 19 bytes
```
71r40s26j25+ȷṚỌżŒl$
```
[Try it online!](https://tio.run/##ASMA3P9qZWxsef//NzFyNDBzMjZqMjUryLfhuZrhu4zFvMWSbCT//w "Jelly – Try It Online")
Thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan) for posting his [answer](https://codegolf.stackexchange.com/a/127694/41024) (even though he outgolfs me) for -1 :)
[Answer]
## PHP, ~~68~~ 66
```
for(;$i++<33;)echo$c=ڀ^"
".chr($i-7?16+$j++:1),mb_strtolower($c);
```
slight improvement over the previous attempt by xoring instead of appending.
`ڀ^"\n"` constructs the necessary `"\0xd0\128"` and xors in the lower 7 bit.
[Answer]
## JavaScript (ES6), 106 bytes
```
f=
_=>"АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ".replace(/./g,c=>c+c.toLowerCase())
console.log(f())
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 22 [bytes](https://github.com/Adriandmen/05AB1E/blob/master/docs/code-page.md)
```
žv47ŸžB+çJ6т‚£'ЁýDløJ
```
[Try it online!](https://tio.run/##ASoA1f8wNWFiMWX//8W@djQ3xbjFvkIrw6dKNtGC4oCawqMn0IHDvURsw7hK//8 "05AB1E – Try It Online")
**Explanation**
```
žv47Ÿ # push range [16 ... 47]
žB+ # add 1024 to each
çJ # convert to a string of characters with those code points
6т‚£ # split into 2 pieces, the first being 6 chars long
'Ёý # merge the 2 strings on "Ё"
Dlø # zip with a lower case copy
J # join to a string
```
[Answer]
# Pyth, 26 bytes
```
X12ssmCM+B+1040d32U32"Ёё
```
```
U32 generate the range [0, 1, 2, ..., 30, 31]
m d for each element in the range,
+1040 add 1040, giving the uppercase cyrillic letter
+B 32 bifurcate over adding 32, giving [upper, lower]
CM convert each into a character
ss join into a single string
X12 "Ёё insert this string at index 12
```
[Try it here](http://pyth.herokuapp.com/?code=X12ssmCM%2BB%2B1040d32U32%22%D0%81%D1%91&debug=0).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 20 bytes = 18 bytes + 2 UTF-8 bytes
```
T„(GÇ«ŸçJ„ЁЖ6ǝDløJ
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/5FHDPA33w@2HVh/dcXi5F5B3ofHCNLPjc11yDu/w@v8fAA "05AB1E – Try It Online")
---
Credit to Emigna for the `lowercase` trick and for `3°` isntead of `3Tm`.
---
# How?
```
T # Push 10. | [10]
„(G # Push "(G" | [10, "(G"]
Ç # Convert to ASCII. | [10, [40, 71]]
« # Concatenate. | [[1040, 1071]]
Ÿ # Range. | [[1040, ..., 1071]
çJ # Convert to char, join. | ["А..Я"]
„ЁЖ # Push "ЁЖ" | ["А..Я", "ЁЖ"]
6ǝ # Replace "Ж" w/ "ЁЖ" | ["А.Ё.Я"]
Dl # Duplicate, lowercase. | ["А..Ё..Я", "а..ё..я"]
øJ # Zip together and join. | ["АаБбВвГгДдЕеЁёЖжЗзИиЙйКкЛлМмНнОоПпРрСсТтУуФфХхЦцЧчШшЩщЪъЫыЬьЭэЮюЯя"]
```
---
Alternate 20 byte version (no UTF-8): `T„(GÇŸ„.Ç6ǝ˜«çJDløJ`
Even more random 20 byte nonsense: `T„(GÇŸ„.Ç6ǝ˜«vyçDlJ`
(The key takeaway is that I don't think I'm getting below 20 here).
[Answer]
# [Braingolf](https://github.com/gunnerwolf/braingolf), 58 bytes
```
"ABCDEF2GHIJKLMNOPQRSTUVWXYZ[\\]^_`"{#Ϗ+..#Ёe#P:# |+}>&@
```
[Try it online!](https://tio.run/##SypKzMxLz89J@/9fydHJ2cXVzcjdw9PL28fXzz8gMCg4JDQsPCIyKjomJjYuPkGpWvl8v7aenvKFxlTlACtlhRrtWjs1h///AQ "Braingolf – Try It Online")
Woo!
## Explanation
Adds `Ϗ` (975) to each character in ABCDEF2GHIJKLMNOPQRSTUVWXYZ[\]^\_`
Then duplicates and adds space (32), unless the character is `Ё`, in which case it adds P (80)
[Answer]
# Java, 93 bytes
```
s->"АаБбВвГгДдЕеЁёЖжЗзИиЙйКкЛлМмНнОоПпРрСсТтУуФфХхЦцЧчШшЩщЪъЫыЬьЭэЮюЯя"
```
Source file should be saved in `Windows-1251` encoding so the source makes for 71 bytes, plus flag to compiler `-encoding WINDOWS-1251` for 22 bytes more.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~69~~ 66 bytes
-3 bytes using the form (using `'%c'` to directly apply `chr()`) from [totallyhuman's answer](https://codegolf.stackexchange.com/a/127719/53748), do go give some credit!
```
v=32
while v:print('Ёё'*(v==26),end='%c%c'%(1072-v,1104-v));v-=1
```
A full program (two double-byte characters used, `Ё` and `ё`).
**[Try it online!](https://tio.run/##K6gsycjPM/7/v8zW2IirPCMzJ1WhzKqgKDOvREP9QuPFiepaGmW2tkZmmjqpeSm26qrJqsnqqhqGBuZGumU6hoYGJrplmprWZbq2hv//AwA "Python 3 – Try It Online")**
[Answer]
# Dyalog APL, ~~55~~ 47 bytes
*8 bytes saved thanks to @Zacharý*
```
⎕UCS 66⍴⍉2 33⍴1025+(14+⍳6),0,(20+⍳32),80,52+⍳26
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT////1Hf1EdtE4BkqHOwgpnZo94tj3o7jRSMjYEsQwMjU20NQxPtR72bzTR1DHQ0jAxAbGMjTR0LAx1TIxDHyOz/fwA)
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 71 bytes
```
."Ёё kdâ¿Ããä©ÃòçÅD´fjÃØÜr
ÔE®8CðÒº[£÷6ÓþC0"
```
[Try it online!](http://pyth.herokuapp.com/?code=.%22%D0%81%D1%91%01%09kd%C2%92%C3%A2%C2%BF%C3%83%C3%A3%C3%A4%C2%A9%C3%83%C3%B2%C3%A7%C2%93%C3%85D%01%C2%B4f%C2%8Fj%C3%83%C3%98%C3%9Cr%C2%96%0A%03%C3%94E%C2%AE%C2%888C%C3%B0%C3%92%C2%BA%5B%C2%A3%06%03%07%14%C3%B7%C2%9D%C2%8E6%C3%93%C3%BEC%C2%840%22&debug=0)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~64~~ ~~47~~ 46 bytes
```
5ÝD1040+s1072+‚øžB>D80+‚«25ÝD1046+s1078+‚ø)˜çJ
```
[Try it online!](https://tio.run/##MzBNTDJM/f/f9PBcF0MDEwPtYkMDcyPtRw2zDu84us/JzsXCAMQ5tNoIqsIMrMICokLz9JzDy73@/wcA "05AB1E – Try It Online")
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 94 93 90 bytes
```
_=>{var r="";for(var i='А';i<='Я';)r+=""+i+(char)(i+32)+(i++=='Е'?"Ёё":"");return r;}
```
[Try it online!](https://tio.run/##bY6xasMwEIZ3P8WhxRJKMqRbFDlDoFMLhQ4dg1Dl5MCR4KQEivHQN0iHPEdexXkiR04hXfoP993d/x@cjVMbyA2QZRsTI7xR2JLZF@OmvddRMZmEFo4BP@HVoOfiYf2FRr1/xeT2s@eDt8uYCP12Ar@soAZdDBtdtUdDQJoxVQfi44C67E@lwmXmpVSCZHYlSm53hgRH@TQXMkPqHDiXK9Z/X3/YgjGhyKUDeSDVDar475V18DE0bvZBmNwLesdrng@FeoS7e9cNNw "C# (.NET Core) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~96~~ 92 bytes
* *@Mayube suggested this to save 2 bytes, and succeeded to golf it down by 1 byte by declaring `chr(i)`.*
* *@Rod golfed 4 bytes by removing `chr(i)`.*
```
for i in[chr(ord(i)+975)for i in"ABCDEF2GHIJKLMNOPQRSTUVWXYZ[\\]^_`"]:print(end=i+i.lower())
```
[Try it online!](https://tio.run/##K6gsycjPM/7/Py2/SCFTITMvOjmjSCO/KEUjU1Pb0txUEyau5Ojk7OLqZuTu4enl7ePr5x8QGBQcEhoWHhEZFR0TExsXn6AUa1VQlJlXopGal2KbqZ2pl5Nfnlqkoan5/z8A)
---
# [Python 3](https://docs.python.org/3/), ~~104~~ 99 bytes
Any suggestions are welcome.
```
for i in"АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ":print(end=i+i.lower())
```
[Try it online!](https://tio.run/##BcFLCoJQGIDRrYgjJXDSLGg3Gf4Q98pFiIbtINPKSns/NEu38u3odk68SCKthtZOtXHEEeWyImVNRs6GJVt2FOw5cKSk4sSZC1du3Hnw5MWbmoYPLV9@dPTuKDaiEi9Uk7EMJJjpeWg837f2Dw)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 29 bytes
```
1040ÐU5+ŸžB>X6+D25+Ÿ)˜çDl)ø˜J
```
[Try it online!](https://tio.run/##MzBNTDJM/f/f0MDE4PCEUFPtozuO7nOyizDTdjECcTRPzzm83CVH8/CO03O8/v8HAA "05AB1E – Try It Online")
Uses the lowercase / uppercase trick from the python answer
### Explanation
```
1040ÐU5+ŸžB>X6+D25+Ÿ)˜çDl)ø˜J
1040 # Push 1040
Ð # Triplicate top of stack
U # Saves top of stack in X
5+Ÿ # Push range [1040, ..., 1045]
žB> # Push 1025
X # Push X (1040)
6+D25+Ÿ # Push range [1046, ..., 1071]
) # Wrap stack to array
˜ # Flatten array
ç # Convert to character
Dl # Create a lowercase copy
)ø # Zip both together
˜J # Flatten and join
# Implicit output
```
[Answer]
# [Python 3](https://docs.python.org/3/), 66 bytes
```
for i in range(32):print(end='%c%c'%(i+1040,i+1072)+'Ёё'*(i==5))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/Py2/SCFTITNPoSgxLz1Vw9hI06qgKDOvRCM1L8VWXTVZNVldVSNT29DAxEAHRJkbaWqrX2i8OFFdSyPT1tZUU/P/fwA "Python 3 – Try It Online")
[Answer]
# PHP>=7.0, 77 Bytes
```
for($t=IntlChar;$i++<33;)echo$c=$t::chr($i-7?1040+$j++:1025),$t::tolower($c);
```
[IntlChar Class](http://php.net/manual/de/class.intlchar.php)
# PHP, 136 Bytes
```
for(;$i<mb_strlen($r=АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ);)echo$m=mb_substr($r,$i++,1),mb_strtolower($m);
```
[PHP Sandbox Online](http://sandbox.onlinephpfunctions.com/code/e4111a0343b19b6b93f81ed6eb93ba76a60e5cdd)
# [PHP](https://php.net/), 136 bytes
```
<?=АаБбВвГгДдЕеЁёЖжЗзИиЙйКкЛлМмНнОоПпРрСсТтУуФфХхЦцЧчШшЩщЪъЫыЬьЭэЮюЯя;
```
[Try it online!](https://tio.run/##BcHFDUIBAETBiqgACLUQQsIJKAF3d3d3d2nhbTGcPzNel9cwLDYrOXbk2VPgQJEjJU6UOeNXngoXqlypcaPOnQYPmjxp8aLNmw4funzpyUdffgYKMFSQkUKMFWaiCFNFmSnGXHEWSrBUkpVSrJVmowxbZc2G8XN7TA67w@X8Aw "PHP – Try It Online")
[Answer]
# Bash+coreutils, ~~101~~ ~~100~~ ~~93~~ ~~92~~ 74 bytes
```
printf %b\\n \\u04{51,{3,4}{{0..9},{a..f}}}|sort|sed 's/./\u&&/'|tr -d \\n
```
This requires a UTF-8 locale such as `ru_RU.utf8` (English UTF-8 locales also sort correctly). I've not added any score for this, as per the [consensus on meta](//codegolf.meta.stackexchange.com/q/7881).
[Answer]
# Ruby, 60 bytes
```
u=?Џ
l=?Я
32.times{$><<u.next!+l.next!+(l==?е?"Ёё":"")}
```
(Just a demonstration of [`String#next!`](http://ruby-doc.org/core-2.4.1/String.html#method-i-next-21), the multibyte literals ruin the 55 characters score.)
Sample run:
```
bash-4.4$ ruby -e 'u=?Џ;l=?Я;32.times{$><<u.next!+l.next!+(l==?е?"Ёё":"")}'
АаБбВвГгДдЕеЁёЖжЗзИиЙйКкЛлМмНнОоПпРрСсТтУуФфХхЦцЧчШшЩщЪъЫыЬьЭэЮюЯя
```
[Try it online!](https://tio.run/##KypNqvz/v9TW/kI/Vw6QXM9lbKRXkpmbWlytYmdjU6qXl1pRoqidA6U1cmyBirbaK11ovDhRyUpJSbP2/38A "Ruby – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~59 56 55 54~~ 51 bytes
```
32.times{|x|$><<((x==6?"Ёё":"")<<x+1040<<x+1072)}
```
Thanks to manatwork for at least 4 bytes.
[Try it online!](https://tio.run/##KypNqvz/39hIryQzN7W4uqaiRsXOxkZDo8LW1sxe6ULjxYlKVkpKmjY2FdqGBiYGENrcSLP2/38A "Ruby – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~26~~ 24 bytes
22 bytes of code (encoded in UTF-8), +2 for the `-P` flag.
```
#h0o#k2_dÃi'Ё6
®+Zv
```
Similar to the below method, except instead of pairing two arrays, I join each capital letter with itself, lower-cased.
[Try it Online!](https://tio.run/##y0osKPn/XznDIF852yg@5XBzpvqFRjOuQ@u0o8r@/9cNAAA)
## 26 byte solution:
I had some help from @Shaggy, who discovered that `Ё` wasn't in the `[1040...1071]` char range.
```
#h0o#k2_dÃi'Ё6
íUmv)c
```
## Explanation:
```
#h0o#k2_dÃi'Ё6
íUmv)c
// Implicit U =
o // Range
#h0 // [1040...
#k2 // 1071]
_ // Map; At each char,
d // Get the char-code
à // End mapping;
i'Ё6 // Insert "Ё" into index 6;
í // U paired with:
Um // U, where each char:
v // Converted to lowercase
c // Flatten
-P // Join into a string
```
[Try it online!](https://tio.run/##y0osKPn/XznDIF852yg@5XBzpvqFRjOuw2tDc8s0k///1w0AAA "Japt – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~45~~ ~~44~~ 26 bytes
```
FE⮌⪫⪪…⮌…γ⁷²¦³²Lαi℅⁺℅ιφ⁺↥ιι
```
[Try it online!](https://tio.run/##RY3BCsIwEER/JfS0gXqpBw8ecxPFovgBS9y2C0sStrHg18cED53DDLx3GL@g@ohSyhTVwA0TPGgjXQkukQM8k3AG9/VCbom73Mncm9NgbW@OQ60rhTkvgA103LVx9QJ9JoVRPivc9c0BBbiqydaYUTnkv3ylROqxHjTN1p5LKYdNfg "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
FE⮌⪫⪪…⮌…γ⁷²¦³²Lαi
```
Take the first 72 printable ASCII characters, reverse them, then take the first 32 of those (this is actually shorter than slicing and reversing, although slicing didn't exist at original time of posting anyway), then insert the `i` after the `N`, then reverse again. The resulting characters happen to have ASCII codes that are exactly 1000 less than the desired Russian lower case letters.
```
℅⁺℅ιφ
```
Calculate the Russian lower case letter by adding the predefined variable `φ` (`f`) which has the value 1000.
```
⁺↥ιι
```
Print the upper and lower case letters. (`«↥ιι` would probably also work.)
[Answer]
## [Alice](https://github.com/m-ender/alice), 31 bytes
```
gr'v6R,' &w'ѷ~-.O' +'С'ёSOk@
```
[Try it online!](https://tio.run/##S8zJTE79/z@9SL3MLEhHXUGtXP3i9jpdPX91BW31CwvVL04M9s92@P8fAA "Alice – Try It Online")
### Explanation
```
g Read the first character of the source code. That's g itself, with
code point 103, so this pushes 103. The exact value is irrelevant
but we need something greater than 31.
r Range. Turns 103 into 0, 1, 2, ..., 103.
'v Push 118.
6R, Move it down the stack by 6 elements, so the top of the stack is
..., 96, 97, 118, 98, 99, 100, 101, 102, 103.
' &w Push the current IP address to the return address stack 32 times,
which will cause the following part to be executed 33 times.
'ѷ~- Subtract the value on top of the stack from 1143, which gives the
33 code points of the upper case letters.
.O Print a copy of this value as a character.
' + Add 32. This turns the upper case letters in the main range to their
lower case counterparts. However, this doesn't work for Ё/ё, where
we obtain C instead.
'C'ёS Replace the divisor 1057 with 1105. The only value among the 33 which
is divisible by 1057 is 1057 (C) itself, so that it simply gets turned into
1105 (ё).
O Output the lower case character.
k Jump back to the w as long as there's a copy on the return address stack.
@ Terminate the program.
```
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), ~~91~~ 88 bytes
```
()->{String s="";for(char i=0,u=1039,l=1071;i<33;)s=i++==6?s+"Ёё":s+ ++u+ ++l;return s;}
```
[Try it online!](https://tio.run/##bVBbT9RgEH3fXzH2qU2hgWyCwVL8AUZ92EfjQ13a5VtLW/t9H4aQTQBRuSty98ZF8H5Hbir6F878orVlN/GFh5lJzpyZc2bq/rDfmaRBXB@43Uz1rUhUqRr5UtJVX8Q0WiJqo1L5Ki/DiRigobxnVlQm4tqNm@RnNWmdUYnq@T5HKxE5oY6rSiSxU9FpGokg62sN9FNIXtO0OvtHWwBJzzDcMMnM6qCfkfC6OrTX3VXu7YjycrHbFX3lsmtJT9i25/VclraBcV40LkmbbFsXKXKzQOksJuk2moUNt3TmpjIiVTDkJFo5aS6lotiMg7vU0jVDpxYo07KsNluEZF4w8BhfsYhveILvWMI@lvEDKzgoNLGKQ6zhCOs4xgZO8BQ/8Qy/8By/8QKneIk/2MRfbPEYtnkcOzyBV3wPuzyJPb6P1/wAb/gh3vIU3vE03vMMPvAsPvIcPvE8PvMCvvAjwwnuaD@S/y2233vuSca1RNH1K0Z@R8FolIpoNP8B "Java (OpenJDK 8) – Try It Online")
Encoded in Windows-1251. Must use a default Russian Windows installation.
[Answer]
## [Alice](https://github.com/m-ender/alice), 33 bytes
```
/ZАе"е"ёяSr@
\"'Я"rЁа""o/
```
[Try it online!](https://tio.run/##S8zJTE79/18/6sKEC1uVgOjixIv9wUUOXDFK6hfWKxVdaLywQUkpX///fwA "Alice – Try It Online")
My other Alice solution was entirely in Cardinal mode, this one is entirely in Ordinal mode. It's conceptually much simpler, but unfortunately two byte longer.
### Explanation
Ignoring the Ordinal template, the program is entirely linear:
```
"АЯ"r"ая"rZ'е"еЁё"So@
```
Alice does have a built-in to convert between lower and upper case, but unfortunately in the Ruby interpreter it only works on ASCII letters, so we still have to get both ranges separately.
```
"АЯ"r Push "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ".
"ая"r Push "абвгдежзийклмнопрстуфхцчшщъыьэюя".
Z Zip. Interleave the two strings.
'е"еЁё"S Replace "е" with "еЁё".
o@ Print the result and terminate the program.
```
] |
[Question]
[
Simple challenge inspired by the popularity of my previous [print invisible text](https://codegolf.stackexchange.com/questions/122703) and [print real invisible text](https://codegolf.stackexchange.com/questions/123447) challenges, and the [same length different string](https://codegolf.stackexchange.com/questions/123539) challenge.
Given a string consisting of only printable characters (`0x20 to 0x7E`), print every printable character not present in the string.
## Input
A string, or array of characters, consisting of only printable ASCII characters
## Output
Every printable ASCII character not present in the input string, in any order.
## Testcases
```
Input: "Hello, World!"
Output: ""#$%&'()*+-./0123456789:;<=>?@ABCDEFGIJKLMNOPQRSTUVXYZ[\]^_`abcfghijkmnpqstuvwxyz{|}~"
========
Input: "Hi!"
Output: " "#$%&'()*+,-./0123456789:;<=>?@ABCDEFGIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghjklmnopqrstuvwxyz{|}~"
========
Input: ""
Output: " !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
========
Input: " !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
Output: ""
```
## Scoring
This is code-golf so fewest bytes **in each language** wins
[Answer]
# [GS2](https://github.com/nooodl/gs2), 2 bytes
```
ç7
```
[Try it online!](https://tio.run/nexus/gs2#@394ufn//x6pOTn5Ogrh@UU5KYoA "GS2 – TIO Nexus")
### How it works
```
(implicit) Push the sting of all characters in STDIN on the stack.
ç Push the string of all printable ASCII characters.
7 Perform symmetric set difference.
(implicit) Print the result to STDOUT.
```
[Answer]
# [Python 3.5](https://docs.python.org/3/), 39 bytes
```
lambda n:{*map(chr,range(32,127))}-{*n}
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPqlorN7FAIzmjSKcoMS89VcPYSMfQyFxTs1a3Wiuv9n9BUWZeiUaahpJHak5Ovo5CeH5RToqikqbmfwA "Python 3 – Try It Online")
Turns input into a set, and remove it from the set containing all ascii characters
[Answer]
# [Perl 6](https://perl6.org), 29 bytes
```
{[~] keys (' '..'~')∖.comb}
```
Note that the result is random because [Set](https://docs.perl6.org/language/setbagmix)s are unordered.
[Test it](https://tio.run/nexus/perl6#tc9LWtswEAfwvU4xGIrtYMu8W2KcUt60pVCebfNoHVsEJ7YlJBkIabLmBD0AnIPLcAFWrFPHhI/syAbt5pu/5jeTCALn89izUdSEcY/6BJxuq9gpQ4M0BWgqqBirHVW/v/6HPRpV2900uCSJkOBAGMREaDquccI0q1JZNItOuWDpmFNJuTatY58QFrks30IA@2kC0ohSLuTg4e5Gebi7tSwskqqQXJs0cuaUjtooSVc6SOfbiIVuDBMZZqMTyvuuWQCtFMQskUaJXDLiSeLr0BPS1UqciCTsLZcdk8XstOUHbg2eer0yEP0iOwoLyiWu0yA24Hmi8fQXM8JD1O5u9Yo8gLJJwpAacEx56I8oaCeRWUNRRsfejauanpswsTU5NT0zOzf//sNC3l50Ch@XPi2vrK6tb2x9/vJ1@9vO7ve9/YPDox8/fxVL5crvP27VO6mdBvVGFLMzIZPzi8vmVetvu6Mgp//QywLBIAsvrjE0fDwo@yS1640wiik746/pg/TIcPbma3gwtP625MBtHeUxpqbneqfkPw "Perl 6 – TIO Nexus")
## Expanded:
```
{
[~] # reduce using string concatenation
# (shorter than 「join '',」)
keys # get the keys from the Set object resulting from the following
(' '..'~') # Range of printable characters
∖ # Set minus (this is not \ )
.comb # split the input into individual characters
}
```
There is also an ASCII version of `∖` `(-)`, but it would require a space before it so that it isn't parsed as a subroutine call.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 14 bytes
```
Ho#_dÃf@bX ¥J
```
[Try it online!](https://tio.run/nexus/japt#@@@Rr1wfn3K4Oc0hKULh0FKv//@VPFJzcvJ1FMLzi3JSFJUA "Japt – TIO Nexus")
Saved 4 bytes thanks to Shaggy and obarakon
[Answer]
## Haskell, 32 bytes
```
f x=[y|y<-[' '..'~'],all(/=y)x]
```
[Try it online!](https://tio.run/nexus/haskell#@5@mUGEbXVlTaaMbra6grqenXqceq5OYk6Ohb1upWRGr8D83MTNPwVahoLQkuKTIJ09BRSFNQckjU1HpPwA "Haskell – TIO Nexus")
Boring library function for set difference:
### Haskell, 31 bytes
```
import Data.List
([' '..'~']\\)
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 5 bytes
```
6Y2X~
```
[Try it online!](https://tio.run/nexus/matl#@28WaRRR9/@/ukdqTk6@OgA "MATL – TIO Nexus")
Thanks to Luis Mendo for [golfing 8 bytes off!](http://chat.stackexchange.com/transcript/message/37783520#37783520)
Explanation:
```
X~ % The symmetric set difference
6Y2 % Between all printable ASCII
% And the input string (implicit)
% Implicitly display
```
*Symmetric set difference* will give every element that is present in exactly one of the two input sets. (but not both) This will always give the right answer, since the input set will always be a subset of the second set (all printable ASCII).
Original version:
```
32:126tGom~)c
```
Explanation:
```
32:126 % Push the range 32-126
t % Duplicate it on the stack
G % Push the input
o % Convert it to character points
m % Is member (0 for each char that isn't in input, 1 for each char that is)
~ % Logical NOT
) % Take the truthy elements of this array from the previous array (All Printable ASCII)
c % Display as a string
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes
```
ẹ;Ṭ↔x
```
[Try it online!](https://tio.run/nexus/brachylog2#@/9w107rhzvXPGqbUvH/v5JHak5Ovo5CeH5RToqi0v8oAA "Brachylog – TIO Nexus")
### Explanation
```
ẹ Split the input string into a list of chars
;Ṭ↔x Exterminate the chars from the string Ṭ of printable ASCII chars
```
[Answer]
## Perl, 39 bytes
```
s!.*!"pack(c95,32..126)=~y/$_//dr"!ee
```
Run with `perl -pe`.
[Answer]
# JavaScript (ES6), 74 bytes
I'm sure there's a shorter way to do this!
```
s=>[...Array(95)].map((_,y)=>s.includes(c=String.fromCharCode(y+32))?"":c)
```
---
## Try it
```
let f=
s=>[...Array(95)].map((_,y)=>s.includes(c=String.fromCharCode(y+32))?"":c)
oninput=_=>o.innerText=f(i.value).join``
o.innerText=f(i.value="Hello, World!").join``
```
```
<input id=i><pre id=o>
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/), ~~47 43~~ 40 bytes
```
printf %x {32..126}|xxd -r -p|tr -d "$1"
```
[Try it online!](https://tio.run/nexus/bash#@19QlJlXkqagWqFQbWykp2doZFZbU1GRoqBbpKBbUFMCJFMUlFQMlf7//w8A "Bash – TIO Nexus")
Generates hexa range, inverts hex dump to char an removes characters present in first parameter.
[Answer]
# Octave, ~~22~~ 20 bytes
Thanks to @Luis Mendo saved 2 bytes.
```
@(s)setxor(32:'~',s)
```
[Try it online!](https://tio.run/nexus/octave#@@@gUaxZnFpSkV@kYWxkpV6nrlOs@T8xr1hDySM1JydfRyE8vygnRVFJ8z8A "Octave – TIO Nexus")
Other answer:
```
@(s)setdiff(' ':'~',s)
```
[Try it online!](https://tio.run/nexus/octave#@@@gUaxZnFqSkpmWpqGuoG6lXqeuU6z5PzGvWEPJIzUnJ19HITy/KCdFUUnzPwA "Octave – TIO Nexus")
[Answer]
# APL, 13 bytes
```
⍞~⍨⎕UCS31+⍳95
```
Straightforward:
```
31+⍳95 ⍝ A vector 32 .. 126
⎕UCS ⍝ as characters
~⍨ ⍝ without
⍞ ⍝ those read from character input.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes
```
žQsм
```
[Try it online!](https://tio.run/##yy9OTMpM/f//6L7A4gt7/v/3SM3JyddRCM8vyklRBAA "05AB1E – Try It Online")
```
žQsм # full program
м # remove...
s # implicit input...
м # from...
žQ # all ASCII characters
# implicit output
```
[Answer]
# PHP, 42 Bytes
Input as array
Output as string
```
<?=join(array_diff(range(" ","~"),$_GET));
```
[Try it online!](https://tio.run/nexus/php#s7EvyCjgUol3dw2xjVbyUNJRSgXiHCjOB2IQVADicCi/CCqXAsSKSrHWXPZ2/23sbbPyM/M0EouKEivjUzLT0jSKEvPSUzXAOuuUNHXANmhqWv//DwA "PHP – TIO Nexus")
# PHP, 53 Bytes
Input as string
Output as string
```
<?=join(array_diff(range(" ","~"),str_split($argn)));
```
replace `<?=join` with `print_r` for an output as array
[Try it online!](https://tio.run/nexus/php#s7EvyCjgUkksSs@zVfJIzcnJ11EIzy/KSVFUsuayt/tvY2@blZ@Zp5FYVJRYGZ@SmZamUZSYl56qoaSgpKNUp6SpU1xSFF9ckJNZogE2RVNT0/r/fwA "PHP – TIO Nexus")
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 8 bytes
```
'␡,32>q^
```
Where `␡` is a literal delete character.
[Try it online!](https://tio.run/nexus/cjam#@69er2NsZFcY9/@/R2pOTr6OQnh@UU6KIgA "CJam – TIO Nexus")
```
'␡, e# The range of all characters up to ~.
32> e# Slice it to be the range of all characters from space to ~.
q^ e# Symmetric set difference with the input.
```
[Answer]
# [brainfuck](https://github.com/TryItOnline/tio-transpilers), 120 bytes
```
+[+[>+<+<]>]>-[[>>]+[<<]>>-],[<+++++[>------<-]>-[>[>>]+[<<]>-]>[>>]<[-]<[-<<]>,]++++++++[->++++<]>[>[-<.>]<[->>+<<]>>+]
```
[Try it online!](https://tio.run/nexus/brainfuck#RY0xCoBADAS/onUuviBs7Q8slnTaHRz4fzizIjgQwiZDMo1GWFgkEk4CaYxK8GwME4S/hEvB71RWCLpKk5b2QYdaSKnd9mqoV7ptOed@9T7acoy7n@sD "brainfuck – TIO Nexus")
Wrapped:
```
+[+[>+<+<]>]>-[[>>]+[<<]>>-],[<+++++[>--
----<-]>-[>[>>]+[<<]>-]>[>>]<[-]<[-<<]>,
]++++++++[->++++<]>[>[-<.>]<[->>+<<]>>+]
```
Explained:
```
+[+[>+<+<]>]>- initialize what we will now consider cell 0 to 95
[[>>]+[<<]>>-] initialize cells 2 4 etc 95*2 to 1; end on cell 0 at 0
,[ main input loop (for each char of input)
<+++++[>------<-]>- subtract 31 from the input
[>[>>]+[<<]>-] lay a trail of (input minus 31) ones in the empty spaces
>[>>]<[-]<[-<<]> use the trail to clear the appropriate "print" flag
,] keep reading input until it ends
++++++++[->++++<]> initialize the cell directly before flag 1 to 32
[ we'll let the accumulator overflow; no harm done
>[-<.>] print the accumulator if the flag is still set
<[->>+<<]>>+ shift over the accumulator and increment it
]
```
[Answer]
# [Ohm](https://github.com/MiningPotatoes/Ohm), 3 bytes
```
α@─
```
[Try it online!](https://tio.run/nexus/ohm#@39uo8OjKQ3//0ere6jrqKcCcQ4U5wOxAhCXQ9lFUPEU9dj/AA "Ohm – TIO Nexus")
Note: you can also enter your input as a string ([example](https://tio.run/nexus/ohm#@39uo8OjKQ3//3uk5uTkK4TnF@WkKP4HAA "Ohm – TIO Nexus")), but it fails for the empty input case.
[Answer]
# Ruby, 23 18 17 bytes
```
->s{[*' '..?~]-s}
```
Uses a lambda function as per @sethrin's comments.
Previous versions:
```
[*' '..?~]-s.chars
(' '..'~').to_a-s.chars
```
[Answer]
## [Julia](https://julialang.org/), 21 bytes
```
s->setdiff(' ':'~',s)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
*Really, 8 bytes? Please, tell me I missed something!*
```
32r126Ọḟ
```
**[Try it online!](https://tio.run/nexus/jelly#@29sVGRoZPZwd8/DHfP///@vFJKRqlBYmpmcrZBUlF@ep5CWX6GQVZpbkJqikF@WWqRQApTPSayqVEjJTy/WUwIA "Jelly – TIO Nexus")**
### How?
```
32r126Ọḟ - Main link: list of characters s
32r126 - inclusive range from 32 to 126 = [32,33,...,125,126]
Ọ - cast ordinals to characters = list of printable characters
ḟ - filter discard if in s
```
---
Alternatively
```
“ ~‘r/Ọḟ - Main link
“ ~‘ - code-page indexes = [32,126]
r/ - reduce by inclusive range = [32,33,...,125,126]
Ọ - cast from ordinals to characters = list of printable characters
ḟ - filter discard if in s
```
---
Since this challenge a new atom which yields all printable ASCII characters, `ØṖ`, has been introduced making the following work for 3 bytes:
```
ØṖḟ
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 5 bytes
```
PADCa
```
Removes all chacracters in the input from a predefined variable.
[Try it online!](https://tio.run/##K8gs@P8/wNHFOfH///8eqTk5@YoA "Pip – Try It Online")
# [Pip](https://github.com/dloscutoff/pip), 9 bytes
```
PARM(X^a)
```
Converts the characters of the input to regex, and removes the characters from the printable ASCII builtin.
[Try it online!](https://tio.run/##K8gs@P8/wDHIVyMiLlHz////Hqk5OfmKAA "Pip – Try It Online")
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~14~~ 10 bytes
```
⍞~⍨' '…'~'
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKM97f@j3nl1j3pXqCuoP2pYpl6nDhL9rwAEaVzqjk7OLq7qAA "APL (Dyalog Extended) – Try It Online")
-4 bytes from Adám!(inclusive range)
## Explanation
```
' '…'~' range of chars in visible ASCII range
⍨ flip the arguments of the function on the left
⍞~ Get all characters not in input
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 7 6 bytes
```
`.-srd\`
-srd\
```
`.-` `-` Subtract the second string from the first:
1. `srd\` Create a range from space char to the delete char
2. *implicitly read input*
[Try it online!](https://tio.run/##K6gsyfj/X0@3uCglpv7/fyWP1JycfIXw/KKcFEUlAA "Pyth – Try It Online")
[Answer]
# MUMPS, 35 bytes
```
r r,! f i=32:1:126 w:r'[$c(i) $c(i)
```
**Explanation**
* Assign input to `r` and write a newline (`!`)
* Loop from 32 to 126 and if r doesn't contain (`'[`) the character representation of the ASCII value (`$char()`, can be shortened to `$c()`), write the that character representation.
* You can attach conditionals to commands with a colon. So `w:1>0 "True"` is the same as `if 1>0 write "True"`
[Try the code here](https://tio.run/##yy3NLSj@/18BCMqLMktSFZQ8UnNy8nUUwvOLclIUlf7/BwA)
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), ~~39~~ 32 bytes
```
$a=$args
' '..'~'|?{$_-cnotin$a}
```
Added splatting and case sensitivity
[Try it online!](https://tio.run/##DczNCkBAEADg@z7F0GQveANx9ADu2jTslnY0SPLz6sP961v4IFk9zXMxsJDiCBVciq5CJ9NqLNiytK@96wv7Yoi8hYju0ccYDPG3aRug8ySUg@cDnBCcvCd1arL/akJU/QA "PowerShell Core – Try It Online")
Inspired by `colsw`'s answer
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 3 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
kcḍ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728JKM0Ly_faMGCpaUlaboWS7OTH-7oXVKclFwMFVmw1iM1JydfRyE8vygnRREiCAA)
#### Explanation
```
kcḍ # Implicit input
ḍ # Symmetric set difference with...
kc # ...all printable ASCII characters
# Implicit output
```
[Answer]
# [Factor](https://factorcode.org/), ~~26~~ 25 bytes
-1 byte by using `∖` from `math.unicode` instead of `diff`, as suggested by @chunes
```
[ 32 126 [a,b] swap ∖ ]
```
[Try it online!](https://tio.run/##JYxZVsIwGIXfu4qfOIFSlKKo4DwBDjggorZVQxtoIE1K2oKK@OwK3IRL8M2luJFa4eUO3z3ntrAVCBnVa5VqqQBdIjlh4JNeSLhFfHBx4GRCTi1hk0mRmLfjgQogfcygqCiM8hggBB1B@ZgmQVX/TyAV6ZDTIKvlQcfppgn@AHvw@/EJZuTGSQf084Vi@Ubgh1KKkNvgScoDMIFgy4mGCgAqE8ZEGhpCMjuBxoROfCyQMNDU9MzsXDI1v5BWM4tLWS23vJJfXVsvFDc2t7Z3dvf2Dw6PSuXK8cnpWfX84vKqdl2/adze3euGYT48PuGmZZNW26GdLnO58HrSD8L@4Pnldfg2ekfK6A8 "Factor – Try It Online")
TIO uses an old build of Factor; on the latest version, `[a,b]` from `math.ranges` has moved to `[a..b]` from `ranges`.
### Explanation
| Code | Explanation | Stack |
| --- | --- | --- |
| `[ ... ]` | Quotation (anonymous function) | `"Hello!"` |
| `32 126 [a,b]` | Inclusive range from 32 to 126 | `"Hello!" T{ range f 32 95 1 }` |
| `swap` | Swap so range is below input | `T{ range f 32 95 1 } "Hello!"` |
| `∖` | Set difference | `" \"#$%&'()*+,-./012..."` |
This works because in Factor, a string is basically a list of codepoints, and all sequences are `set`s.
[Answer]
# [R](https://www.r-project.org/), 50 bytes
```
function(s)intToUtf8(setdiff(32:126,utf8ToInt(s)))
```
returns an anonymous function. Converts the input string to integers, computes the set difference between the printable range and the input values, and then converts them back to a string and returns it.
[Try it online!](https://tio.run/nexus/r#S7P9n1aal1ySmZ@nUayZmVcSkh9akmahUZxakpKZlqZhbGRlaGSmUwoUC8n3zCsBKtLU/J@moe6RmpOTr6MQnl@Uk6KorvkfAA "R – TIO Nexus")
[Answer]
# PHP, 53 bytes
```
for($k=31;$k++<126;)~strstr($argn,$k)?:print chr($k);
# or
for($k=31;$k++<126;)echo~strstr($argn,$k)?"":chr($k);
```
Run as pipe with `-r`.
[Answer]
# C#, ~~74~~ 71 bytes
```
using System.Linq;s=>new int[95].Select((n,i)=>(char)(i+32)).Except(s);
```
Old version with creating a range for 74 bytes:
```
using System.Linq;s=>Enumerable.Range(32,95).Select(n=>(char)n).Except(s);
```
] |
[Question]
[
There’s a [famous tricky algorithm for counting the number of set bits](https://en.wikipedia.org/wiki/Hamming_weight#Efficient_implementation) in a 32-bit unsigned integer:
```
int popcount(unsigned x) {
x = (x & 0x55555555) + ((x >> 1) & 0x55555555);
x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
x = (x & 0x0F0F0F0F) + ((x >> 4) & 0x0F0F0F0F);
x = (x & 0x00FF00FF) + ((x >> 8) & 0x00FF00FF);
x = (x & 0x0000FFFF) + ((x >>16) & 0x0000FFFF);
return x;
}
```
I won’t explain it here. But imagine similar code for 512-bit integers! The hexadecimal constants would be huge, and form a pretty pattern. Your task is simply to **print this exact output**:
```
0x55555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555
0x33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333
0x0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f
0x00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff
0x0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff
0x00000000ffffffff00000000ffffffff00000000ffffffff00000000ffffffff00000000ffffffff00000000ffffffff00000000ffffffff00000000ffffffff
0x0000000000000000ffffffffffffffff0000000000000000ffffffffffffffff0000000000000000ffffffffffffffff0000000000000000ffffffffffffffff
0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff00000000000000000000000000000000ffffffffffffffffffffffffffffffff
0x0000000000000000000000000000000000000000000000000000000000000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
```
No trailing spaces, please — though a single trailing newline is optional.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer (in bytes) wins.
[Answer]
# Python 2, 52 49 46 bytes
The kth number is given by `2**512/(2**2**k + 1)`. This is for a 512 bit number, so it's trivial to extend the pattern to different widths.
```
l=2;exec"print'0x%0128x'%(2**512/-~l);l*=l;"*9
```
3 bytes saved thanks to Dennis.
3 bytes saved thanks to xnor.
[Answer]
# PHP, ~~111~~ ~~110~~ 108 bytes
One byte saved thanks to @user59178.
```
<?=($p=str_pad)("0x",130,5).$p($s="\n0x",131,3);for($x=1;$x<65;$x*=2)echo($p($s,131,$p(0,$x,0).$p(f,$x,f)));
```
What´s the pattern for 1024 bits? :D
[Answer]
# Vim, 32 bytes
`i5<CR>3<Esc>qqYpVrf$<C-V>{yPG1vr0q6@q<C-V>{I0x<Esc>`
I only need to manually write the first `5` and `3`, and the macro takes care of the rest, "doubling the bit count" each time it runs. The order of the steps in the macro is a bit weird (make a new `f` line, block-wise copy, reuse the visual block size to put `0`s in the `f` line), but it's the fastest variant I've found.
[Answer]
## [Retina](http://github.com/mbuettner/retina), 43 bytes
```
:`
0x128$*5
:`5
3
;{:`33
0f
0(f+)(0+)
0$2$1
```
[Try it online!](http://retina.tryitonline.net/#code=OmAKMHgxMjgkKjUKOmA1CjMKO3s6YDMzCjBmCjAoZispKDArKQowJDIkMQ&input=)
### Explanation
This makes a lot of use of the generally underused `:` option which lets you print intermediate results, because it's a lot shorter to modify a single line than to build up the whole output.
```
:`
0x128$*5
```
This replaces the empty input with `0x` followed by 128 `5`s and prints it to generate the first line.
```
:`5
3
```
This one replaces the `5`s with `3`s to generate the second line and prints it as well.
```
;{:`33
0f
```
This is the last special-cased line and it turns every two `3`s into `0f` to generate the third line. This also starts a loop through the last two stages (`{`). However, this stage won't do anything after the first iteration except print the current state. The `;` suppresses the output at the very end of the program to avoid duplicating the last line.
```
0(f+)(0+)
0$2$1
```
This substitution now transforms each line into the next, by swapping every other pair of `f`s and `0`s. The "every other pair" condition is enforced by matching a zero in front of the `f`, which makes it impossible to match consecutive pairs since matches cannot overlap.
[Answer]
# J, ~~46~~ 34 bytes
~~I'm working on golfing this, but this baby likes to stay at 46 bytes...~~ Not anymore! -12 bytes thanks to miles!
```
'0x',"1'5','3','0f'(128$#)"{~2^i.7
```
[Try it online! :D](https://tio.run/nexus/j#S7S1MlCwUjD4r25Qoa6jZKhuqq6jbgzEBmnqGoZGFirKmkrVdUZxmXrm/zW5UpMz8hWU9BJ19XzcdJyD/gMA "J – TIO Nexus")
## Result
```
'0x',"1'5','3','0f'(128$#)"{~2^i.7
0x55555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555
0x33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333
0x0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f
0x00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff
0x0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff
0x00000000ffffffff00000000ffffffff00000000ffffffff00000000ffffffff00000000ffffffff00000000ffffffff00000000ffffffff00000000ffffffff
0x0000000000000000ffffffffffffffff0000000000000000ffffffffffffffff0000000000000000ffffffffffffffff0000000000000000ffffffffffffffff
0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff00000000000000000000000000000000ffffffffffffffffffffffffffffffff
0x0000000000000000000000000000000000000000000000000000000000000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
```
---
For this answer, I needed (ideally) a verb with rank `0 1` so as to use it in the `u"v` definition of rank; however, miles observed that `0 _` was sufficient for the task at hand.
```
┌──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬──┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┐
│= │< │<.│<:│> │>.│>:│+ │+.│+:│* │*.│*:│_ 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│0 _ _│0 _ _│0 0 0│2 _ 2│0 0 0│0 0 0│0 0 0│_ 1 _│_ _ _│_ _ _│_ 0 0│_ 0 0│
├──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤
│| │|.│, │,.│,:│; │;:│# │#.│#:│! │/:│\:│0 0 0│_ 1 _│_ _ _│_ _ _│_ _ _│_ _ _│1 _ _│_ 1 _│1 1 1│_ 1 0│0 0 0│_ _ _│_ _ _│
├──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤
│[ │[:│] │{ │{.│{:│}.│}:│".│":│? │?.│a │_ _ _│_ _ _│_ _ _│1 0 _│_ 1 _│_ 0 0│_ 1 _│_ 0 0│1 _ _│_ 1 _│0 0 0│_ 0 0│_ _ _│
├──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤
│A │A.│b │C │C.│d │D │e │e.│E │E.│f │H │_ _ _│1 0 _│_ _ _│_ _ _│1 1 _│_ _ _│_ _ _│_ _ _│_ _ _│_ _ _│0 _ _│_ _ _│_ _ _│
├──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤
│i │i.│i:│I │I.│j │j.│L │L.│M │o │o.│p │_ _ _│1 _ _│0 _ _│_ _ _│1 _ _│_ _ _│0 0 0│_ _ _│_ 0 0│_ _ _│_ _ _│0 0 0│_ _ _│
├──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼──┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤
│p.│p:│q │q:│r │r.│s │s:│S │t │T │u:│x:│1 1 0│0 _ _│_ _ _│0 0 0│_ _ _│0 0 0│_ _ _│_ _ _│_ _ _│_ _ _│_ _ _│_ _ _│_ _ _│
└──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┘
```
Here you see a bunch of verbs' string representations with their respective ranks. [This is the script I used to generate it.](https://tio.run/nexus/j#TY5LT4NAFIX38yuOUF46jhh304IYNdFEV7rDijymdkwDFbBp08pfxxlMq8ld3Mf5zj19KRcIOCTz4ZMmnYlErNJhdQGuVmjrDYPBsEGetvmcQROiLBjxyErUWaO1Y06dYBImJ8en1uuo2zFOx@bR2Us83X4bb5F9mV5l18WNuJ3dyfuPh8dq@Vk3T@3z19qhzPBx7oBxh2RpI3PtF3P8ZaG2g4z5DlGDLJLDU/e3Mzu4ExXKQ8cx9TCY2CzEcCaLqnwXTTsAynarNBrxEcCMYuw6zUgWhap4ZPHIJMulVo867Fl66KwOJhH5vIJLma2E@28e/qXr@x8 "J – TIO Nexus")
[Answer]
# Pyth, 26 bytes
```
V9%"0x%0128x"/^2 512h^2^2N
```
Port of my Python answer.
[Answer]
# [Actually](http://github.com/Mego/Seriously), 25 bytes
```
9r`‚ïô‚ïôu9‚ïô‚ïô\#"0x%0128x"%`Mi
```
[Try it online!](http://actually.tryitonline.net/#code=OXJg4pWZ4pWZdTnilZnilZlcIyIweCUwMTI4eCIlYE1p&input=)
This solution uses the fact that `f(n) = 2**512//(2**2**n + 1)` (where `//` is floored division) to compure the values.
Explanation:
```
9r`‚ïô‚ïôu9‚ïô‚ïô\#"0x%0128x"%`Mi
9r`‚ïô‚ïôu9‚ïô‚ïô\#"0x%0128x"%`M for n in range(1, 10):
9‚ïô‚ïô\ 2**2**9//
‚ïô‚ïôu (2**2**n + 1)
#"0x%0128x"% pad with zeroes to 128 digits, prefix with "0x"
i flatten and implicitly print
```
[Answer]
# JavaScript (Firefox 30+), ~~139~~ ~~113~~ ~~112~~ ~~92~~ ~~83~~ 80 bytes
```
_=>[for(x of"970123456")(f=y=>y--?f(y)+(x>6?x-4:y>>x&1&&'f'):'0x')(128)].join`
`
```
Finally hit the recursive sweet spot :-) Uses a handy-dandy string comprehension to save 3 bytes over `.map`:
```
_=>[..."970123456"].map(x=>(f=y=>y--?f(y)+(x>6?x-4:y>>x&1&&'f'):'0x')(128)).join`
`
```
`.replace` is also 83 bytes:
```
_=>"970123456".replace(/./g,x=>(f=y=>y--?f(y)+(x>6?x-4:y>>x&1&&'f'):'0x')(128)+`
`)
```
If a leading newline were allowed, this would also be 80 bytes:
```
_=>"970123456".replace(/./g,x=>(f=y=>y--?f(y)+(x>6?x-4:y>>x&1&&'f'):`
0x`)(128))
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~26~~ ~~22~~ 21 bytes
05AB1E uses the [CP-1252](http://www.cp1252.com) encoding.
```
9F„0x0NÍo×9ooNoo>÷hJ,
```
[Try it online!](http://05ab1e.tryitonline.net/#code=OUbigJ4weDBOw41vw5c5b29Ob28-w7doSiw&input=)
**Explanation**
```
9F # for N in [0 ... 8]
„0x # push the string "0x"
0NÍo× # push 2**(N-2) zeroes
9oo # 2**2**9
√∑ # //
Noo> # (2**2**N+1)
h # converted to base-16
J # join everything to string
, # print with a newline
```
**Other versions that might be improved**
```
9F9ooNoo>÷h¾6o×J7o£R…0xÿ,
9F9ooNoo>÷h0žy×ìR7o£R…0xÿ,
9FX0No×1No×JCh7o×1K7o£…0xÿ,
8ÝovX0y×1y×JCh7o×1K7o£…0xÿ,
9F1NoÅ0D>)˜JCh1K7o×7o£…0xÿ,
```
[Answer]
# [Python 2](https://docs.python.org/2/), 60 bytes
```
k=1
exec"print'0x%0128x'%int(256/k*('0'*k+'1'*k),2);k*=2;"*9
```
[Try it online!](https://tio.run/nexus/python2#@59ta8iVWpGarFRQlJlXom5QoWpgaGRRoa4K5GkYmZrpZ2tpqBuoa2VrqxsCSU0dI03rbC1bI2slLcv//wE "Python 2 – TIO Nexus")
[Answer]
# [Bubblegum](http://esolangs.org/wiki/Bubblegum), 65 bytes
```
00000000: c5cb 4501 0441 1043 d17b d4fc 254b d110 ..E..A.C.{..%K..
00000010: f7cb 9761 9e7a 8d45 e451 4ce4 564c 04d7 ...a.z.E.QL.VL..
00000020: 2e11 b02b 8f08 80df aa5e 11fe fc77 762c ...+.....^...wv,
00000030: 428b 5b8e ae8b 30c1 13b6 ce8b b091 377a B.[...0.......7z
00000040: 01 .
```
Obligatory Bubblegum answer.
[Answer]
# Haskell, ~~84~~ 72 bytes
Porting @orlp's answer:
```
import Text.Printf
mapM(\n->printf"0x%0128x\n"$div(2^2^9)$2^2^n+1)[0..8]
```
94 byte alternatives without the power of `Text.Printf`:
```
import Data.List
mapM(putStrLn.("0x"++))$transpose$("53"++).reverse<$>sequence(["0f"]<*[1..7])
r=[0..127]
mapM(putStrLn.("0x"++))$('5'<$r):('3'<$r):[["0f"!!mod(div x(2^y))2|x<-r]|y<-[0..6]]
```
[Answer]
## Batch, 216 bytes
```
@echo off
set s=5
call:c
set s=3
call:c
set a=0
set b=f
for /l %%i in (1,1,7)do call:l %%i
exit/b
:l
set s=%a%%b%
:c
for /l %%j in (0%1,1,6)do call set s=%%s%%%%s%%
echo 0x%s%
set a=%a%%a%
set b=%b%%b%
```
[Answer]
## PowerShell v2+, 68 bytes
```
5,3|%{"0x"+"$_"*128}
($a=1)..7|%{"0x"+('0'*$a+'f'*$a)*(128/($a*=2))}
```
PowerShell doesn't have arbitrary precision integers without using `[bigint]` calls, and those can't be easily converted to hexadecimal, so we're instead treating this as a string-based challenge.
The first line handles the repeating `5` and `3` by just doing a string multiplication out to `128` characters and tacking a `0x` on the front.
The next line loops from `$a=1` to `7`, each iteration outputting another string. Again we have the `0x` tacked onto the front, and we're doing string multiplication in the middle to construct the appropriate number of `0` and `f` concatenated together, and then doing string multiplication of *that* out to the appropriate number of characters. Note we're using variable `$a` here, and not the loop counter `$_`, so we can properly scale (otherwise we'd need to loop like `1,2,4,8,16,32,64|%{...}`, which is longer).
The resulting strings are left on the pipeline, and output via implicit `Write-Output` happens at program completion, with a newline between elements.
[Answer]
# [V](http://github.com/DJMcMayhem/V), 43 bytes
```
64i0fòYpÓ¨¨0«©¨f«©©û2}/²²³³òdd{3ÄÒ5jÒ3Îi0x
```
[Try it online!](http://v.tryitonline.net/#code=NjRpMGYbw7JZcMOTwqjCqDDCq8KpwqhmwqvCqcKpw7syfS_CssKywrPCs8OyZGR7M8OEw5I1asOSM8OOaTB4&input=)
This uses one of the longest compressed regexes I've ever needed in a V answer. Here is the more readable version, where I added a byte for readable regexes, and changed the unprintable escape character to `<esc>`
```
64i0f<esc>òYpÓö((0+)(f+)){2}/²²³³òdd{3ÄÒ5jÒ3Îi0x
```
Explanation (using the readable version):
```
64i0f<esc> " Insert 64 "0f"s and escape to normal mode
ò ò " Recursively:
Yp " Duplicate this line
Ó " Substitute:
ö " (Optionally Turn the readable version on)
((0+)(f+)) " One or more '0's followed by one or more 'f's
{2} " Repeated twice
/ " With:
²² " The second capture group twice (the '0's)
³³ " Followed by the third capture group twice (the 'f's)
" Once the search is not found, the loop will break
dd " Delete a line (because we have one too many)
{ " Move to the first line
3Ä " Make three copies of this line
Ò5 " Replace the first one with '5's
jÒ3 " Move down a line and replace the second with '3's
Î " On every line:
i0x " Insert a '0x'
```
[Answer]
## JavaScript (ES6), ~~74~~ ~~72~~ 70 bytes
Includes the optional trailing newline.
```
f=(i=1152)=>i--?f(i)+(i&127?'':`
0x`)+('53'[y=i>>7]||i&1<<y-2&&'f'):''
```
```
f=(i=1152)=>i--?f(i)+(i&127?'':`
0x`)+('53'[y=i>>7]||i&1<<y-2&&'f'):''
console.log(f())
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~66 60~~ 45 bytes
```
x=2;9.times{puts"0x%0128x"%(2**512/-~x);x*=x}
```
[Try it online!](https://tio.run/##KypNqvz/v8LWyNpSryQzN7W4uqC0pFjJoELVwNDIokJJVcNIS8vU0Ehft65C07pCy7ai9v9/AA "Ruby – Try It Online")
Idea stolen from [orlp](https://codegolf.stackexchange.com/a/101710/18535)
[Answer]
# Pyth - ~~31~~ 30 bytes
To get pattern except for the `3`'s and `5`'s it cumulative reduces, each time doubling the chunks.
```
jm+"0x".[dd128+`3+`5.u.iNN6"0f
```
[Try it online here](http://pyth.herokuapp.com/?code=jm%2B%220x%22.%5Bdd128%2B%603%2B%605.u.iNN6%220f&debug=0).
[Answer]
# Vim 72 bytes
```
i0x128a5Ypll128r3o0x64a0fa0Ypqqffdt0fft0p@qq@qqwYp@qq@w@w@w@w:%s/0$
```
[TryItOnline!](http://v.tryitonline.net/#code=aTB4GzEyOGE1G1lwbGwxMjhyM28weBs2NGEwZhthMBtZcHFxZmZkdDBmZnQwcEBxcUBxcXdZcEBxcUB3QHdAd0B3OiVzLzAk&input=)
Unprintables:
```
i0x^[128a5^[Ypll128r3o0x^[64a0f^[a0^[Ypqqffdt0fft0p@qq@qqwYp@qq@w@w@w@w:%s/0$
```
The 4 `@w`s at the end are bugging me, but because I was relying on the `@q` to fail out at the end of a line, it fails out the @w as well. I might try just running q 32 times and seeing if it messes up the later lines.
[Answer]
# C, 146 bytes
```
#define F for(i=0;++i<129;)s[i+1]=
#define P ;puts(s);
i,j;f(){char s[131]={'0','x'};F'5'P F'3'P for(j=1;(j*=2)<129;){F(i-1)%j<j/2?'0':'f'P}}
```
Ungolfed:
```
#define F for(i=0;++i<129;)s[i+1]=
#define P ;puts(s);
i,j;f(){
char s[131]={'0','x'};
F'5'P
F'3'P
for(j=1;(j*=2)<129;){
F(i-1)%j<j/2?'0':'f'P
}
}
```
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 211 bytes
```
+++++++>++>>-[>>>>+<<++<+<-----]>--->>++++++++++>++<<<<<<[->----[>+++<--]>-->.<.++++++++[->>>>.<<<<]>>>.>--[<]<<]+<[->>----[>+++<--]>-->.<.++++++++[<<[>+>->.<<<-]>[<+>>->>.<<<-]>]>>>.<<<<[-<+>]<[->++<]>[-<+>]<<]
```
[Try it online!](https://tio.run/##fU5bCoAwDDtQ6U4QepHSDxUEEfwQPH9NN@anYYymedD1Xo5rf7YzUwaMz9SNEEAEAi2E8ePuA0d0uJbECJcYRmto00eZaOWMGig7gkQq@R9luYlpT1N11G02acxeVwpRdayhbVBE5gs "brainfuck – Try It Online")
[Answer]
# [GNU sed 4.2.2](https://www.gnu.org/software/sed/), 77
```
s/^/0x5/
:
s/x5{,127}$/&5/
t
p
y/5/3/
p
s/33/0f/gp
:a
s/(f+)(0+f+)/\2\1/gp
ta
```
[Try it online.](https://tio.run/##FYjRCkAwGEbv/@eQCH2btdSeRUoxuWH5d0Hy6n5zczrn8DyJMAao04IcMU5717rtngx5OpECXbAwSMIwBspjCeTGVIWvykJViejbXv8/jiLvHuK6byzNdnw)
[Answer]
# C#, 168 bytes
```
()={string R="",o="0",f="f";for(int i=0,j;i<9;i++){R+="0x";if(i>2){o+=o;f+=f;}for(j=0;j<128;){R+=i<1?"5":i<2?"3":o+f;j+=i>1?(int)Math.Pow(2,i-1):1;}R+="\n";}return R;};
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 19 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
⌡hÅék╝94"ºé♪╛#V┐5í╒
```
[Run and debug it](https://staxlang.xyz/#p=f5688f826bbc393422a7820dbe2356bf35a1d5&i=&a=1)
Unpacked, ungolfed, and commented, it looks like this.
```
512r [0..511]
{:Brm convert each to bits and reverse each
M transpose matrix, filling missing elements in rectangle with zero
m map over each element of array, using the rest of the program. outputs implicitly.
4/ split bits into groups of 4
{:b|Hm convert each 4-bit binary number to single digit hex string
.0xp print "0x" without newline
```
[Run this one](https://staxlang.xyz/#c=512r++++%09[0..511]%0A%7B%3ABrm+++%09convert+each+to+bits+and+reverse+each%0AM+++++++%09transpose+matrix,+filling+missing+elements+in+rectangle+with+zero%0Am+++++++%09map+over+each+element+of+array,+using+the+rest+of+the+program.++outputs+implicitly.%0A++4%2F++++%09split+bits+into+groups+of+4%0A++%7B%3Ab%7CHm%09convert+each+4-bit+binary+number+to+single+digit+hex+string%0A++.0xp++%09print+%220x%22+without+newline&i=)
[Answer]
# [///](https://esolangs.org/wiki////), 193 bytes
```
/*/\/\///X/
0x*F/5555*G/FFFF*T/3333*U/TTTT*o/0f0f*1/oooo*t/00ff*2/tttt*g/0000*h/ffff*4/ghgh*6/gghh*7/gggg*8/hhhh*9/7788/0xGGGGGGGGXUUUUUUUUX11111111X22222222X44444444X66666666X78787878X99X77988
```
[Try it online!](https://tio.run/##LccxDoMwEETRPkeZZhZCsH0BuECQtkiTIt4tIlFAwe2dleL3i9Ec3/fhn6M1gq@IVN7kwsJHwMol4Ml7wMZnwE6pUjFwDzgpUitGngEWTwTOGjDR3BwzzdyRYsyQ6QGFKeVMudZOt06HTsdOp07nTlP@p6VoSiXn1n4 "/// – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 72 bytes
```
n=1n<<512n;f=(i=2n)=>i-n?`
0x`+(n/-~i+n).toString(16).slice(1)+f(i*i):''
```
[Try it online!](https://tio.run/##BcFBDsIgEAXQvRfpjASUJrrQoofwAm0QmjHkjynEuPLq@N5r@Sw1bvJuFvpMvSN4TNPJj7jmQBJGcLiJxX3eHb@zIRzsTwzYNX20TbCSP7OrRWIizyaT7IUvw9CjompJruhKmZj7Hw "JavaScript (Node.js) – Try It Online")
# [JavaScript (Node.js)](https://nodejs.org), 69 bytes from Arnauld's
```
f=(i=4608)=>i?f(i-=4)+(i&508?'':`
0x`)+('53'[y=i>>9]||i&1<<y&&'f'):''
```
[Try it online!](https://tio.run/##DchRCoMwDADQ/x2kSRClYzpUTD2IDBS1I1KsqMgE7975Pt/UHd3Wr7Ls8eyHMQTLKJy@dU5spLYoMacUoahM5zVA2T70r70Dshc0J4sxxee6RD2r6lQKLFAJEHo/b96NifNftEgU/g "JavaScript (Node.js) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `j`, 136 [bitsv1](https://github.com/Vyxal/Vyncode/blob/main/README.md), 17 bytes
```
‚Äõ0x53f‚Äõ0f6 ÄE‚Ä¢J‚Çáv·∫é+
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyJqPSIsIiIsIuKAmzB4NTNm4oCbMGY2yoBF4oCiSuKCh3bhuo4rIiwiIiwiIl0=)
Math? No we don't do that here. We do string manipulation instead.
## Explained
```
‚Äõ0x53f‚Äõ0f6 ÄE‚Ä¢J‚Çáv·∫é+¬≠‚Ű‚Äã‚Äé‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å¢‚Å£‚Å™‚Äè‚ņ‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å¢‚ŧ‚Å™‚Äè‚ņ‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å£‚Ű‚Å™‚Äè‚Äè‚Äã‚Ű‚ņ‚Ű‚Äå‚Å¢‚Äã‚Äé‚Å™‚Å™‚ņ‚Å™‚Å™‚ņ‚Å™‚Å™‚ņ‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚ŧ‚Ű‚Å™‚Äè‚Äè‚Äã‚Ű‚ņ‚Ű‚Äå‚Å£‚Äã‚Äé‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å£‚Å¢‚Å™‚Äè‚ņ‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å£‚Å£‚Å™‚Äè‚ņ‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å£‚ŧ‚Å™‚Äè‚Äè‚Äã‚Ű‚ņ‚Ű‚Äå‚ŧ‚Äã‚Äé‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚ŧ‚Å¢‚Å™‚Äè‚Äè‚Äã‚Ű‚ņ‚Ű‚Äå‚Å¢‚Ű‚Äã‚Äé‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚ŧ‚Å™‚Äè‚ņ‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å¢‚Ű‚Å™‚Äè‚ņ‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å¢‚Å¢‚Å™‚Äè‚Äè‚Äã‚Ű‚ņ‚Ű‚Äå‚Å¢‚Å¢‚Äã‚Äé‚Äè‚Äã‚Å¢‚ņ‚Ű‚Äå‚Å¢‚Å£‚Äã‚Äé‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚ŧ‚Å£‚Å™‚Äè‚ņ‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚ŧ‚ŧ‚Å™‚Äè‚ņ‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å¢‚Ű‚Ű‚Å™‚Äè‚Äè‚Äã‚Ű‚ņ‚Ű‚Äå‚Å¢‚ŧ‚Äã‚Äé‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Ű‚Å™‚Äè‚ņ‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å¢‚Å™‚Äè‚ņ‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å£‚Å™‚Äè‚ņ‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å¢‚Ű‚Å¢‚Å™‚Äè‚Äè‚Äã‚Ű‚ņ‚Ű‚Äå‚Å£‚Ű‚Äã‚Äé‚Äè‚Äã‚Å¢‚ņ‚Ű‚Äå¬≠
‛0f # ‎⁡The string "0f"...
• # ‎⁢with each character repeated n times...
6 ÄE # ‚Äé‚Å£for each n in [2**x for x in range(0, 7)].
J # ‎⁤Appended to...
53f # ‎⁢⁡the list [5, 3].
# ‎⁢⁢The top of the stack is [5, 3, "0f", "00ff", "0000ffff", ...]
₇vẎ # ‎⁢⁣Take the first 128 items of each item.
# ‎⁢⁣This reuses previous digit/chars if the item isn't long enough
‛0x + # ‎⁢⁤Add the string "0x" to each item
# ‎⁣⁡The j flag joins on newlines before printing
üíé Created with the help of Luminespire at https://vyxal.github.io/Luminespire
```
] |
[Question]
[
### Display the remaining battery charge, as a percentage of maximum charge
Remember if you can't run your code on a phone, calculator, etc, you can probably install your environment on a laptop at least. If you absolutely can't run on a device that has a battery, then unfortunately your language isn't eligible since you have no useful value to print.
You must display the results on the screen. This is theoretically supposed to be a handy utility for the user to check the battery. Writing battery percent to a file is too clunky, requiring the user to then check the file. Displaying on-screen is therefore a part of the specification that can't be overridden by default IO. That said, you can assume nothing is preventing things like STDOUT from being displayed on screen in the usual way.
If the battery percent is already displayed on screen all the time by the OS, like on many phones, that does not mean you've got a zero-byte solution. You must assume that built-in display doesn't exist, and display the battery percent again somewhere else.
Edit: The output format is being opened up. You are free to display as little as just the digits of the percent, or the digits with some extra output as well.
Edit2: The digits representing the percent must appear in a known location within the output, not more than 50 lines from the end of the output, and that location shouldn't change between invocations. The digits representing the percent must be separated from other output by at least one non-digit character on each side.
For reference here is the old output format from before the change:
`Remaining battery is ddd%`
or
`Remaining battery is ddd percent`
[Answer]
# Bash, ~~70~~ ~~67~~ ~~50~~ ~~46~~ ~~43~~ 16 bytes
```
`</*/*/*/B*/c*y`
```
Outputs: `<battery 0-100>: command not found`
Reads the file `/sys/class/power_supply/BAT1/capacity`.
Tested using Ubuntu 18.04 on a LENOVO ideapad 500.
Takes a while (since it searches the entire filesystem) - but it saves a byte!
### Old answer:
```
echo Remaining battery is `</*/*/*/B*/c*y`%
```
[Answer]
# JavaScript (browser), ~~78~~ ~~77~~ 50 bytes
(-1 byte thanks to [Benoit Esnard](https://codegolf.stackexchange.com/users/38454/benoit-esnard))
(-27 bytes since the output format is flexible now)
```
navigator.getBattery().then(b=>alert(b.level*100))
```
# JavaScript (browser), 46 bytes, by returning a promise
(Suggested by [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy), requires a header and footer)
```
f=
_=>navigator.getBattery().then(b=>b.level*100)
f().then(alert)
```
---
**Note:** Only works on Google Chrome >= 38 (desktop and Android) or any other browser that supports [Battery API](https://developer.mozilla.org/en-US/docs/Web/API/Battery_Status_API). FireFox has removed this API due to privacy concerns.
**Example on Android (old output format):**
[](https://i.stack.imgur.com/jN9Zi.png)
**Example on a Windows laptop (old output format):**
[](https://i.stack.imgur.com/7jdq6.png)
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 28 bytes
-26 (!) thanks to AdmBorkBork. Previous version -3 thanks to colsw.
```
((gwmi win32_battery)|% e*g)
```
[](https://i.stack.imgur.com/Haocv.png)
`gwmi` is short for `Get-WmiObject`
`|%` takes the pattern `e*g` and finds the only matching property; `estimatedChargeRemaining`
[Answer]
# Bash+acpi, ~~43~~ 4 bytes
## New rules
```
acpi
```
output on form
```
Battery 0: Charging, 92%, 00:05:37 until charged
```
not sure if the rule change makes things more interesting, couldn't you dump any text that contains all strings 0 to 100 which would be valid output? Seems to lose the original intent if so.
## Old rules
```
set `acpi`;echo Remaining battery is ${4%,}
```
output on form
```
Remaining battery is 92%
```
Don't ask me why set works like this, but it does.
[Answer]
# [Python 3.6](https://docs.python.org/3/) + [`psutil`](https://pypi.org/project/psutil/), 80 bytes
```
import psutil
print(f"Remaining battery is {psutil.sensors_battery().percent}%")
```
[Try it online!](https://tio.run/##LcoxCoAwDADA3VcUQWiXLv7ED0iVqAGbhiQORXx7HXS@42pHobE1zFzEHOtleHYsSOa3foKckJB2tyQzkOpQ3f2lqEBaROeffIgMsgLZM/ShtRc "Python 3 – Try It Online")
If the machine has no battery (like on TIO), the program will throw an error, because `psutil.sensors_battery()` returns `None`.
This requires Python 3.6 for [string interpolation](https://www.python.org/dev/peps/pep-0498/).
[Answer]
# C (win32, gcc i686-w64-mingw32), 78 bytes
```
#include<windows.h>
main(s){GetSystemPowerStatus(&s);printf("%hhu",s>>16);}
```
Abuses the win32 API by letting `GetSystemPowerStatus()` write "somewhere" on the stack, the interesting member is in the third byte, according to the [`SYSTEM_POWER_STATUS` struct](https://docs.microsoft.com/de-de/windows/desktop/api/winbase/ns-winbase-_system_power_status).
Unfortunately, the `#include` seems to be needed, probably because of calling conventions.
Example output:
```
> bat.exe
90
```
Displays `255` on systems without a battery.
[Answer]
# Excel VBA, 150 bytes
Restricted to 32-Bit Windows Installs of office, because the windows Kernel32 call is not 64-bit pointer safe.
Outputs to the cell `A1` on the ActiveSheet.
```
Declare Sub GetSystemPowerStatus Lib"kernel32"(f As t)
Type t
i As Integer
b As Byte
End Type
Sub d
Dim e As t
GetSystemPowerStatus e
[A1]=e.b
End Sub
```
-26 bytes thanks to flexible output
-7 bytes thanks to [@Neil](https://codegolf.stackexchange.com/users/17602/neil) for using an Int instead of 2 bytes
[Answer]
# [QPython for Android](http://www.qpython.org/index.html), 133 bytes
```
from androidhelper import*
d=Android()
d.batteryStartMonitoring()
d.dialogCreateAlert(str(d.batteryGetLevel()[1])+"%")
d.dialogShow()
```
[](https://i.stack.imgur.com/Oxy2E.png)
[](https://i.stack.imgur.com/AK1BG.png)
The `+"%"` isn't strictly necessary since it uses the newer more flexible output format anyway, but it makes for slightly nicer output at just +4 bytes.
[Answer]
# Emacs Lisp, 9 bytes
```
(battery)
```
Shows current battery status in mini-buffer at the bottom (or to stdout when using `--batch`) in format such as: `Power N/A, battery Unknown (99.1% load, remaining time N/A)`.
Should work on Windows, OSX, BSD , and Linux.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 60 bytes
```
Ox`nàÀÓ&.getBÂjry().È(x=>O.q("Rà@°á ßMy "+L*x.¤vel+"%"))
```
[Test it](https://ethproductions.github.io/japt/?v=1.4.5&code=T3hgbuDA0yYuZ2V0QsJqcnkoKS7IASh4PT5PLnEoIlLgQLDhIN9NgHkgiSAiK0wqeC6kdmVsKyIlIikp&input=)
[Answer]
# Java, 546 bytes (Windows XP or Higher)
The powercfg utility came into play for WindowsXP, I have no idea what utilities were available prior to this. I must also be run as administrator. This is god-awful and I didn't make an extreme golfing attempt...
```
import java.io.*;import java.util.Scanner;public class J {public static void main(String[] args)throws Exception{Process p=Runtime.getRuntime().exec("powercfg energy");p.waitFor();Scanner s=new Scanner(new File("C:\\windows\\system32\\energy-report.html"));String x;double a=0,b=0;while(s.hasNextLine()){x=s.nextLine();if(x.contains("Design Capacity")){s.nextLine();b=Integer.parseInt(s.nextLine().replaceAll("\\D+",""));}else if(x.contains("Last Full Charge")){s.nextLine();a=Integer.parseInt(s.nextLine().replaceAll("\\D+",""));}}System.out.print(a/b*100);}}
```
Formatted / commented...
```
import java.io.*;
import java.util.Scanner;
public class J {
public static void main(String[] args) throws Exception {
Process p = Runtime.getRuntime().exec("powercfg energy"); // Run CMD sys32 app.
p.waitFor(); // Wait for it.
Scanner s = new Scanner(new File(
"C:\\windows\\system32\\energy-report.html")); // Read output.
String x;
double a = 0, b = 0;
while (s.hasNextLine()) {
x = s.nextLine();
if (x.contains("Design Capacity")) { // Find max capacity.
s.nextLine();
b = Integer.parseInt(s.nextLine().replaceAll("\\D+", ""));
} else if (x.contains("Last Full Charge")) { // Find current capacity.
s.nextLine();
a = Integer.parseInt(s.nextLine().replaceAll("\\D+", ""));
}
}
System.out.print(a / b * 100); // Calculate %.
}
}
```
Honestly I was more interested to see if it was even possible in Java.
] |
[Question]
[
When Alice was touch typing on her QWERTY keyboard (Figure 1), she accidentally shifted both of her hands rightwards by one key, so `q` became `w`, `w` became `e`, etc. (`p` became `[`). Spaces were not affected because the space bar was quite big.
Your task is to help her fix her message using the shortest number of bytes, i.e. undo the shifting of her hand positions. More precisely, you will be given a string consisting of spaces as well as characters from `wertyuiop[sdfghjkl;xcvbnm,` and you need to map the characters to `qwertyuiopasdfghjklzxcvbnm` and leave spaces untouched.
Here are some testcases for you to test your program:
```
input output
----------------------
s[[;r apple
s gom a fin
werty qwert
uiop[ yuiop
sdfgh asdfg
jkl; hjkl
xcvb zxcv
nm, bnm
;p;;o[p[ lollipop
[2 spaces] [2 spaces]
```
(the `lollipop` testcase starts with a space)
Figure 1: Alice's QWERTY keyboard

This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in bytes wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes
```
ØqḊ€ż“[;,”F,Fyɠ
```
[Try it online!](https://tio.run/##ASwA0/9qZWxsef//w5hx4biK4oKsxbzigJxbOyzigJ1GLEZ5yaD//yA7cDs7b1twWw "Jelly – Try It Online")
Takes input via STDIN
## How it works
```
ØqḊ€ż“[;,”F,Fyɠ - Main link. Takes no arguments
Øq - Set the return value to ['qwertyuiop', 'asdfghjkl', 'zxcvbnm']
Ḋ€ - Dequeue each; ['wertyuiop', 'sdfghjkl', 'xcvbnm']
ż“[;,” - Zip with "[;,"; [['wertyuiop', '['], ['sdfghjkl', ';'], ['xcvbnm', ',']]
F - Flatten; "wertyuiop[sdfghjkl;xcvbnm,"
F - Flatten the return value; "qwertyuiopasdfghjklzxcvbnm"
, - Pair; ['wertyuiop[sdfghjkl;xcvbnm,', 'qwertyuiopasdfghjklzxcvbnm']
ɠ - Read a line from STDIN
y - Translate. Map w -> q, e -> w, etc.
```
[Answer]
# [J](http://jsoftware.com/), 43 bytes
```
'qwertyuiop[asdfghjkl;zxcvbnm, '(<:@i:{[)]
```
[Try it online!](https://tio.run/##TZA7C8IwFIV3f8XBJRba4pwoCIKTk2twqLVP0ya2vv3xMQkkFZLlfnDPd26r5ykpsaYgiLEENT9JsT3sd5pcn8Vwe98bqXg2nsuqbi@CfV7549R3MUAWK7pp6JdHRx3NiryWIJlSoiBIKEqQkXM2EHiEsukDQiW7gFyQRy40IBfvkVOZFlqnsND6BWRNPbHSAVh7D2yRAEwlPzflwhhCCtGoSQFMMSb5n4Y5hGfm6R8 "J – Try It Online")
* `'qwertyuiop[asdfghjkl;zxcvbnm, '` The full keyboard, including the shifted away left-most chars and the extra chars `[;,`, as well as two extra spaces at the end.
* `<:@i:` Find the index of the input within that, searching from the right, and substract one.
* `{[` Pull those shifted indexes from the string in step 1.
[Answer]
# C++ (Windows MSVC), 92 bytes
```
#include<Windows.h>
void f(PCH s){for(;*s;)*s++=MapVirtualKey(OemKeyScan(*s)-(*s>32),1)|32;}
```
Take input as a `char*` (`PCH` is typedef of `char*`), output by modify the string in-place.
Trying to make use of some built-ins. But seems not quite short. Maybe some one may take this idea and make a shorter one in other languages.
`OemKeyScan` convert key to its scancode, `'q' -> 16`, `'w' -> 17`, `'e' -> 18`, ..., `'p' -> 25`, `'a' -> 30`, ..., `'l' -> 38`, `'z' -> 44`, ..., `'m' -> 50`. `MapVirtualKey` convert scancode back to (uppercase) character.
Saved 1 byte by ErikF.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), ~~16 13~~ 12 bytes
```
k•`[;,`Y∑:ǔĿ
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=k%E2%80%A2%60%5B%3B%2C%60Y%E2%88%91%3A%C7%94%C4%BF&inputs=s%5B%5B%3Br&header=&footer=)
```
k• # Qwerty keyboard (array of rows)
`[;,`Y # Interleave with `[;,`
∑ # Concatenate all of that
:ǔĿ # Shift each character 1 right relative to this in the input.
```
[Answer]
# [Python 3](https://docs.python.org/3/), 61 bytes
```
lambda s:s.translate('p?ml ??'*14+'vxswdfguhjknbio?earycqzt')
```
[Try it online!](https://tio.run/##JY7BbsMgEETvfMXegDaNFLWnIMcf4l5wgmOSBTaA4zg/74J7e08zGg0teQz@ex2a3xW16y8a0jHtc9Q@oc5GcGodQtvyj8PPJ3@@0nwZrtN4u/vehtbouJwf78zlOo8WDRyODKynHYQpEzSVpyzkPhHaLDh8nYBLBhStz2IQJZbQNFtbrqnrVKwVTYSGJbgGtykM1rPZxLxUfVRikw3UVV0qsVRujVu5ErvdUVUrR5G9zs@@yrsA825XufeOgSKlQvc/AxgQLZUpgM3hDw "Python 3 – Try It Online")
### Explanation
A naive implementation with `str.translate` would use the following translation table:
```
???????????????????????????????? ???????????m??????????????l???????????????????????????????p??????vxswdfguhjknbio?earycqzt
```
To optimize for size, notice that the characters `' mlp'` all have different positions, modulo 7. As such, we can replace the first 98 characters of the table with `'p?ml ??'*14`. The rest of the table is the same.
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 34 bytes
```
tr snvfrghjokl\;,mp[wtdyibecux a-z
```
[Try it online!](https://tio.run/##DcnJEYAgDADAf6pIAVpBSokf8OBQhCGoYPPoflcrsb2XjHLeWzbWx/2YaAiJn7I0p9f5qqjGt3dhpgyCJgZ41lwaXC4mBlk2Y8HvB0Gdbw1nGAApEUX@F/ED "Bash – Try It Online") Using `bash` because I don't know how to score this as a `tr` answer.
[Answer]
# [Haskell](https://www.haskell.org/), 65 bytes
```
a#(c:d)|a==c=d!!0|1>0=a#d
map(#",mnbvcxz;lkjhgfdsa[poiuytrewq ")
```
[Try it online!](https://tio.run/##BcHBEoIgEADQe1@B0EFnOtg1ZvuRPW0gSQKuYFqN/07vjVSmIYRaSbXmZruDAAzYpumP670HUvbkIBK3Sl5iemzm89Nheo1PZwshz/79XfOwL0LIrkbyCTj7tJ6dLIg6C81az8go6x8 "Haskell – Try It Online")
`(#)` takes a character and a string and returns the character after the first match in the string. Our implementation then just maps this across the string with `,mnbvcxz;lkjhgfdsa[poiuytrewq` as the preset string.
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 64 bytes
```
x=>x.Select(t=>" mlpvxswdfguhjknbio?earycqzt"[t%94%88%57%43%32])
```
[Try it online!](https://tio.run/##jdE9a8MwEAbgvb9CCAw2pA40KU1R7A6lhUK3Dh1MB1mVbSX6iiQndv68azUQYk/S@Irn7rgj9p5YNry3kmytM0zWC/DxJltBDS453ZIGmzyvsqHL8i79opwSF7ssh0Bwfezs6beq22a3lyVTLxSbnhzODhYuel5Hm030@BStV9Hq4ScZ0N2rklZxmn4b5ugnkzS@dEzHD4JdXMXQFgUyMEkSBP7fcgmw1pwGWVArMbOgYjLEnqhx/dQefBZiW6Z0MbW9z4JmHtfXzGb2WYjd7Tm6od6Oh@AhtCPHckbPYxZCpVjcSk9LKUIkQBohVVx3NUoIuOKcaaVhUAUwaX2pAODwBw "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# JavaScript (ES6), 66 bytes
I/O format: array of characters.
```
a=>a.map(c=>(S=" ,mnbvcxz;lkjhgfdsa[poiuytrewq")[S.indexOf(c)+1])
```
[Try it online!](https://tio.run/##Tc2xjoQgEIDh3qcgVpDz2FxNtLt6iy2JBSIoLgIrrqv78p7j5S5MqL4/zAxiEVFOJsyfzrdq1@UuykrQUQQsywrfyhyhYnTNItc3s/eh73QbBQ/ePLd5Uq9HTviNGteq9aqxJB9fNdkZzxDKI@dsygt0zuWCRAhWnQF1fkwD0sZBeKlp3pLwAIDwND7wJGwA56pWd326CgDCcLfszyH0B4CvcmlSfx8A7sbin8EbNwIjFhjz/Pf4wTmy3loTfMjPDC/5BZDVGdV@@hayxxGVFZLeRW8Vtb7DGnNKaawJIfsP "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), 57 bytes
If taking an array of ASCII codes as input and returning an array of characters is acceptable, we can do:
```
b=>b.map(c=>"rjbwgtvacnofh_spzleykidumx_q "[c*19%116%30])
```
[Try it online!](https://tio.run/##TdDRasMgFIDh@zyFCIV0dHZhMBiSwBh7CgnFmBiTGrWapk1fPstJ2VC8@n48wun5xIPwnRtfja2bReZLlRcVGbhLRV5g31e3dpy4MFaqU3AP3cznrr4O99MFYSZess9dln3s3t/K/UJZghAOjFGPD2g7xyPizulmC6i1QxyQ7AyEW@PHOQoXAAjXzjoWhRlgG1XLVsWjACD0Z03/HIJaAfwupir2xwrgZjj8M3hlBmBEHaWWPT9fGSNtte6cdXjLcKNXAEmZEGn9DxcqDSgvkLAmWN0QbdtUpowQEsrnXrdKhOL@e93515ju4Sy/ "JavaScript (Node.js) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/) -p, 40+1 bytes
```
$_.tr!"snvfrghjokl;,mp[wtdyibecux","a-z"
```
[Try it online!](https://tio.run/##KypNqvz/XyVer6RIUak4ryytKD0jKz87x1ontyC6vCSlMjMpNbm0QklHKVG3Sun//@LoaOuif/kFJZn5ecX/dQsA "Ruby – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 79 bytes
I combined the source and destination strings so that I can take the character after the match. By inverting the list of characters, I could avoid -1 indexes and having to special-case spaces.
```
f(char*s){for(;*s;putchar(strchr(",mnbvcxz;lkjhgfdsa[poiuytrewq ",*s++)[1]));}
```
[Try it online!](https://tio.run/##VZDBboMwDIbvPIXFNClJ2aSdPfoEVW87ZRxoaCAtJCwJtF3Fs7PAlk27fZ9t/XEsnmoh5lkS0ZSWOXqXxhJkDvvBLyXivBWNJWnW6cMorp/Ynk9NLStX8t6o4ebt8fIBkGbMbTaUvxSU4jQ/KC3aoTrCq/OVMs/NNkmU9tCVSpPRqIrCPQFYXgDmeJEvFlIc52jT7EegNl2Uy9H6W5RBmZ7/jlWybqKczi1GvorxEFl3WUTAHtHwv4Bl@5X2b7tdgCkDxjwmAZdr@NwhBP9eGaC34SeSpPzRFZBvIeSENsW1KQnz4Q74b7J41@lampJp/gI "C (gcc) – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 36 bytes
```
T`snvfrg\hj\ok\l;,m\p[\wt\dyibecux`l
```
[Try it online!](https://tio.run/##Dcm5FYAgDADQPlMwgBtkDbukwAMB5XoEr@nR3/5qmk9T76OWdG3Vsts5HxxwiFyI78br62eznI8OvQsRVhBlc4Tb1PbC6XMhkHWzDvYjIDzLNUOKAygsiJn@VeoD "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: Simply a transliteration, although Retina's built-in classes need to be escaped on the source string (obviously the built-in class `l` is desired on the target string).
Alternative solution, also 36 bytes:
```
T`\wertyuio-p[as\df-hj-l;zxcvbnm,`qo
```
[Try it online!](https://tio.run/##Hcq3AYAgEADA/qdgAJng17B7CwyIqAQB4/KI1ndBJm3bnGvRnDKke9eOe2pjM4x8mvmKz9UfnTWV2FzOkQgDRKacgb9D@Z4gDqOaYF5WhK9D@cDQIzoqytgL "Retina 0.8.2 – Try It Online") Link includes test cases. Transliterates the letters in keyboard order. This costs bytes because `a` and `z` have to be included in the source list and `q` in the destination list but then bytes can be saved by using character ranges to avoid quoting the `o`, `p`, `h` and `l` character classes.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-m`](https://codegolf.meta.stackexchange.com/a/14339/), 29 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
;D+S ·¬v gD·mÅí"[;,"¬'+ ¬v bU
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW0&code=O0QrUyC3rHYgZ0S3bcXtIls7LCKsJysgrHYgYlU&input=InMgZ29tIgoid2VydHl1aW9wW3NkZmdoamtsO3hjdmJubSwi)
```
; -> use second set of predef. Vars
-m flag -> map input by the program (U)->
g - take from
D+S·¬v [ QWERTY +' ' split on (\n),rejoined, to lowercase ]
Dxxx bU - at index of input in[WERTY..]
D· - QWERTY split on \n
mÅ - remove 1st char on each
í - pair with :
"[;,"¬ - ..splitted
'+ - and join
¬v - join all and to lowercase
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 36 bytes
```
≔”⧴3�⁷Rrηs⟲θ]⁺L÷↗¹T“[~↓TφF”η⭆S§η⊕⌕ηι
```
[Try it online!](https://tio.run/##JYixDsIgFAD3fsVLJ0jwC5i6mDCYmDgyISCg9IFAa/Xn0cZbLnfaq6KTir1PtQaHZARgM15XvX14fNy9u5mqZE5hebdiX8@Rgad8OJeAjVzaT@6kMhGYl/ZPQhlMTaCxG/EMBOpiZ4vNGnIMaPYX6A7vHXjmPMksh35Y4xc "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of @ErikF's C answer, except putting the spaces at the beginning because that compresses better.
```
≔”⧴3�⁷Rrηs⟲θ]⁺L÷↗¹T“[~↓TφF”η
```
Assign the compressed string `,mnbvcxz;lkjhgfdsa[poiuytrewq` to a variable.
```
⭆S§η⊕⌕ηι
```
Find each input character in the string and print the character that follows it.
[Answer]
# [Perl 5](https://www.perl.org/), 57 bytes
```
s/./",mnbvcxz;lkjhgfdsa[poiuytrewq "=~m|\Q$&\E(.)|;$1/ge
```
[Try it online!](https://tio.run/##Dcu7DoIwFADQ/X5FQ4jRBGkcnG4c@QDnsgiUUqAP2/IyxE@3Mp8cy914j9HTnCaZ0tVcrx8ch74TbeNfzBo5bcHx5U1I8viqvXymp7I455cd0xsV/KiMoQNPhFGwcBc2mKSxDHzTig76YURY67kCrTIgaBENO5SQn7FBGu3j1f4B "Perl 5 – Try It Online")
```
s/. #replace one char at a time from input
/
",mnbvcxz;lkjhgfdsa[poiuytrewq " #...with its next char in this string
=~ m| \Q$&\E (.)|x; #found by searching for current char in $&
#which must be escaped by \Q and \E
#since [ has a special meaning in regexes.
$1 #Return next char captured into $1 by (.)
/gex #g = global search: all chars
#e = treat replacement string as eval code
#x = allow white-space, improve readability
```
[Answer]
# [R](https://www.r-project.org/), ~~68~~ 55 bytes
```
function(x)chartr("snvfrghjokl;,mp[wtdyibecux","a-z",x)
```
[Try it online!](https://tio.run/##Rc5LDoMgEIDhfU9B6EYSegLSk7BSFMHyKkVFL08Zmyor/i9khljks8jZiaS9azIRqo0pNvjjFhlHNfmXYdQGvqZ@090g5owpbh87ppkUWd9xziImN7ii0VtM7ug4LZLaAa9DTNvJb0jgWfvAT94gjyG9HNU1BBJ4qt84FamaoFks3aV7TVBn6YWocxYQscCY5/@Vxhujw28lQpiULw "R – Try It Online")
Abusing laconic `Ranges are supported in the specifications` in `chartr` [documentation](https://stat.ethz.ch/R-manual/R-devel/library/base/html/chartr.html) (forced to work by try and error).
Inspired by [@Neil's answer](https://codegolf.stackexchange.com/a/230882/55372).
[Answer]
# [Haskell](https://www.haskell.org/), 59 bytes
```
mapM(`lookup`(zip<*>tail)",mnbvcxz;lkjhgfdsa[poiuytrewq ")
```
[Try it online!](https://tio.run/##Xc9dbsIwDMDx953CivYAEztBKAdA4gTZA@lH2lAnMU0KtIdfabQJJPvxr59ludOxbxAXU/wsTtNpc8YQ@pHOm9nS/uuQtMWt2Dlf3qrHLLG/dK2po1YU7DiloblfAcR23bW@qMMHAA3WJ/gEAyIqJQcBeYoCjmNMIDQRNoI5aIPjDoz1zN2bIU3MXXNkbrSBFHNTjvxubdqO382RuUuP8o@9XbdGxh7VreRsXiNj3u3@1ZuV3jEFkqQMKv/xUoAB0VL@Y/mtDOo2Lt8V0RM "Haskell – Try It Online")
A function `String -> Maybe String`; it maps `"s gom"` to `Just "a fin"`.
[Answer]
# [Common Lisp](http://www.clisp.org/), 102 bytes
```
(defun f(i &aux(s",mnbvcxz;lkjhgfdsa[poiuytrewq "))(map'string(lambda(c)(elt s(1+(position c s))))i))
```
[Try it online!](https://tio.run/##jZKxbsIwEIbn5ilOrihnSocidSHqUCEqIXUq6hR1MIkDBjs2sQMJQ16d2oBCK1VVvfj03W//9t2lUlhzPGLG86qAHAXcsapGS4aqWOzS@hDLzXq1zDPLEqNF1biS77cAhFJUzPStK0WxRMnUImOYUuTSgcXHezTaCid0ASlY6peg9GRjWMkUd7yEgePWPaTMcjuIAPqIxCZJXBIgzBjJCfUUwFNYahUo5KLo6J6XrvF0G4KOVkKbxNMmBNcbsny5CjeEoKPrjYw9XPm9Y3W6W3h28HvHCjX0aFGojkBs4lgnJyeQWkphvrn58gA51YhG0aW03V8BRWEqB7w2PHU8e9CVS7Xi4TDmulTMgQMyC6JxO3pyrW1704sYLuIu8c5tJa@6dpy8vsze2nj@MZlM5/P2sx31SHQD8LupdzxnKOC5lc9/aOjpjf/SRWi8ygHyHS8buO1fRgSw9lahvQFei1JT@mMe/LB8AQ "Common Lisp – Try It Online")
Test cases included in TIO.
[Answer]
# Excel, 93 bytes
```
=CONCAT(IFERROR(CHAR(FIND(MID(A1,SEQUENCE(LEN(A1)),1),"snvfrghjokl;,mp[wtdyibecux")+96)," "))
```
[Link to Spreadsheet](https://1drv.ms/x/s!AkqhtBc2XEHJnEGX_Z79laPncjcs?e=u9gVvb)
[Answer]
# [PHP](https://php.net/), 80 bytes
```
str_replace($a=str_split('wertyuiop[asdfghjkl;yxcvbnm,'),[-1=>'q']+$a,$argv[1]);
```
Avoids string repetition and double str\_split().
[Try it online!](https://tio.run/##FcdBDoIwEADAr/TQpBDqgXMtPGRDzIoVkALLtqK8fo1zGxpJrq2XlPnGgSL2odDo/00Up1yYT@B8vqeNANPjOYyvObrz2x/3dbGmtHCpfWN201UarUYeDqi70omISgCOlVI/ "PHP – Try It Online")
[Answer]
## PHP, 186 114 Bytes
```
$W=str_split(",mnbvcxz;lkjhgfdsa[poiuytrewq");for(;$c=$argv[1][$p++];)echo($c!==" ")?$W[array_flip($W)[$c]+1]:" ";
```
[Try it online!](https://tio.run/##Dck7EsIgEADQqyCzBQw2aUUmx6DYYTKI@Wk06xKj8fKY5jWPBirnmnbBu7xwk2kaFyWPj@dlTd@fne63oe@uOSLN43tbuP28pLbdzMpCchC5X7EKCGRMsLpNw6wgHZyTQuoaPEbmuDXdNJICrxFSMFU47WtLKSIjWhZC/AE)
Definitely not the shortest answer on here, but I'm not sure how I could handle this in PHP without using a big array. Any input would be greatly appreciated!
-72 bytes by changing a large keyed array into one small one. Just iterates over every character, find it in the array, then prints the next element in the array.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~45~~ 35 bytes
```
.rQ"[poiuytrewq;lkjhgfdsa,mnbvcxz
```
[Try it online!](https://tio.run/##K6gsyfj/X68oUCm6ID@ztLKkKLW80DonOysjPS2lOFEnNy@pLLmiSkHh/38lBesCa@v86IJoJQA "Pyth – Try It Online")
~~```
sm?gJtxK.",zcVÖzùwÔ\"Ã?4‰ØÝ”gR¹³3"dZ@KJ\ Q
```~~
[Try it online!](https://tio.run/##AUsAtP9weXRo//9zbT9nSnR4Sy4iLHpjVsOWesO5d8OUXCIBw4M/NMKJwo3DmMOdwpRnUsK5wrMRMyJkWkBLSlwgUf//IiA7cDs7b1twWyI "Pyth – Try It Online")
\***Edit:**
Improved solution is rather boring...
`"[poiuytrewq;lkjhgfdsa,mnbvcxz` is a string of every possible char followed by the char it's meant to be (i.e. ytrewq) with two spaces on the end (space is meant to be space);
This is all surrounded with `.r` which will translate each element of `Q`(Input) into the next element.
**Previous solution**
Haven't golfed in a while so this feels pretttty rusty...
Maps through qwerty string, shifting char to the left unless it's a space.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
žV€¦…[;,øSžW‡
```
[Try it online.](https://tio.run/##yy9OTMpM/f//6L6wR01rDi171LAs2lrn8I7go/vCHzUs/P9fSUmpODrauoirWCE9P5erPLWopJKrNDO/IJqrOCUtPYMrKzvHmqsiuSyJKy9Xh0vBusDaOj8aKKugANQKAA)
**Explanation:**
```
žV # Push builtin ["qwertyuiop","asdfghjkl","zxcvbnm"]
€¦ # Remove the first character from each: ["wertyuiop","sdfghjkl","xcvbnm"]
…[;,ø # Zip/transpose with string "[;,":
# [["wertyuiop","["],["sdfghjkl",";"],["xcvbnm",","]]
S # Convert it to a flattened list of characters:
# ["w","e","r","t","y","u","i","o","p","[","s","d","f","g","h","j","k",
# "l",";","x","c","v","b","n","m",","]
žW # Push builtin "qwertyuiopasdfghjklzxcvbnm"
‡ # Transliterate all characters in the (implicit) input
# (after which the result is output implicitly)
```
] |
[Question]
[
# Challenge
Given a positive integer, return the product of its divisors, including itself.
This is [sequence A007955 in the OEIS](http://oeis.org/A007955).
# Test Cases
```
1: 1
2: 2
3: 3
4: 8
5: 5
6: 36
7: 7
8: 64
9: 27
10: 100
12: 1728
14: 196
24: 331776
25: 125
28: 21952
30: 810000
```
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in each language wins!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes
```
ÑP
```
[Try it online!](https://tio.run/##MzBNTDJM/f//8MSA//@NTAA "05AB1E – Try It Online")
**Explanation**
```
Ñ # divisors
P # product
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt/), 3 bytes
```
√¢ √ó
```
[Try it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=4iDX&input=MjQ=)
## Explanation
```
√¢ √ó // implicit integer input
√¢ // get integer divisors
√ó // get product of array
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~42~~ 41 bytes
Saved 1 byte thanks to Leaky Nun!
```
f=lambda i,k=1:k>i or k**(i%k<1)*f(i,k+1)
```
[Try it online!](https://tio.run/##DYxBCoMwEADvfcVeCrtxD93YQhH1I6WHiE27RKPEXHx9GpjTDMx@5t8W21L8sLh1mh0oh0G6MCpsCYIxqNfQCxmPtTRCxVevoBEWPTImF78fFBYhal5iWe5sKw@2T25v7@4CsCeNGeuAqPwB "Python 3 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
ÆDP
```
[Try it online!](https://tio.run/##y0rNyan8//9wm0vA////jUwA "Jelly – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 3 bytes
```
Z\p
```
[Try it online!](https://tio.run/##y00syfn/Pyqm4P9/MwA "MATL – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 35 34 bytes
*-1 thanks to ovs*
```
f n=product[x|x<-[2..n],n`mod`x<1]
```
[Try it online!](https://tio.run/##DcLRCoIwFAbgVzmXCr/ijloG2hv4BGvkyCTJzWEK56J3X318L/t5P5clxol8F7Z1PB67lq@0meY89wZ@cOs4SKtMdHb21JGzob9TchPKrhS22e@UCGgiSVPSCowSFWqccEaDC1QBxVAV@L8GNygLE38 "Haskell – Try It Online")
[Answer]
## [Alice](https://github.com/m-ender/alice), 12 bytes
```
/o
\i@/Bdt&*
```
[Try it online!](https://tio.run/##S8zJTE79/18/nysm00HfKaVETev/fyMTAA "Alice – Try It Online")
### Explanation
This is just the regular framework for decimal I/O:
```
/o
\i@/...
```
Then the program is:
```
B Get all divisors of the input.
dt Get the stack depth minus 1.
&* Multiply the top two stack elements that many times, folding multiplication
over the stack.
```
[Answer]
# [Factor](https://factorcode.org/), 43 bytes
```
[ dup [1,b] [ dupd divisor? ] count 2 / ^ ]
```
[Try it online!](https://tio.run/##NY09C8IwGIT3/opzl2pi6@fgKC4u4lQqxDRqsE1i8kYQ8bfXUhWO4zk4eM5CkvXtYb/dbZa4KW9UjUbQta/UC3NR4cvnaCRpa36z1qcGziuip/PaEIK6R2Vkd18l290SQXpB8pokA5AKBG1cpJC8wMAxQYYcU8wwxwJsDMbBMvAuOfgckzHebYEqOhRseCrRc4VKP3Swfo0S0sbOyjHCEWXbCPcX2Ui9KYWslfDtBw "Factor – Try It Online")
Uses the formula `n^((number of divisors of n)/2)`.
Usually `mod 0 =` (7 bytes) is shorter than `divisor?` (8 bytes), but the latter is used here to auto-load `math.functions` to disambiguate `^` (which happens to appear in a regex lib). Auto-use is weird. The unambiguous alternative to `^` exists (`fpow`), but it's longer.
```
[ ! anonymous lambda
dup [1,b] ! ( n {1..n} )
[ ... ] count ! count the elements that satisfy the predicate...
dupd ! ( n i -- n n i )
divisor? ! ( n ? ) tests if i is a divisor of n
2 / ^ ! halve the divisor count and raise n to the power
]
```
---
# [Factor](https://factorcode.org/), 45 bytes
```
USE: math.primes.factors
[ divisors product ]
```
[Try it online!](https://tio.run/##NY7LCsIwEEX3@YrrD5Q@rI@6FnHTjbgSFzFObbBNazIRRPz2GlqFy@UODJxTScWdHY6HfbkrcCdrqEEruR4rstLcyE278kax7szvbPSlRW@J@dVbbRiOHp6MCu8bsS8LOGUlq1qIGZgcQ5vesxNvJEiRYY4cCyyxwhpJjCRFMkcakiNdIYvxCVbbYoIFQksuqkZbJ0646qd2YQaD7uoV4zy0sv@jOs8jK4JqSNrhCw "Factor – Try It Online")
Uses `divisors` built-in, but obviously the library import is expensive.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 6 bytes
```
*Fs{yP
```
[Test suite](http://pyth.herokuapp.com/?code=%2aFs%7ByP&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A12%0A14%0A24%0A25%0A28%0A30&debug=0).
[Answer]
# [Neim](https://github.com/okx-code/Neim), 2 bytes
```
ùêÖùê©
```
[Try it online!](https://tio.run/##y0vNzP3//8PcCa1AvPL/f2MDAA "Neim – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 28 bytes
```
v=scan():1;prod(v[!v[1]%%v])
```
[Try it online!](https://tio.run/##K/r/v8y2ODkxT0PTytC6oCg/RaMsWrEs2jBWVbUsVvO/2X8A "R – Try It Online")
[Answer]
# x86-64 Machine Code, 26 bytes
```
31 C9 8D 71 01 89 F8 FF C1 99 F7 F9 85 D2 75 03 0F AF F1 39 F9 7C EE 89 F0 C3
```
The above code defines a function that takes a single parameter (the input value, a positive integer) in `EDI` (following the [System V AMD64 calling convention](https://en.wikipedia.org/wiki/X86_calling_conventions#System_V_AMD64_ABI) used on Gnu/Unix), and returns a single result (the product of divisors) in `EAX`.
Internally, it computes the product of divisors using an (extremely inefficient) iterative algorithm, similar to [pizzapants184's C submission](https://codegolf.stackexchange.com/a/130466/58518). Basically, it uses a counter to loop through *all* of the values between 1 and the input value, checking to see if the current counter value is a divisor of the input. If so, it multiplies that into the running total product.
**Ungolfed assembly language mnemonics:**
```
; Parameter is passed in EDI (a positive integer)
ComputeProductOfDivisors:
xor ecx, ecx ; ECX <= 0 (our counter)
lea esi, [rcx + 1] ; ESI <= 1 (our running total)
.CheckCounter:
mov eax, edi ; put input value (parameter) in EAX
inc ecx ; increment counter
cdq ; sign-extend EAX to EDX:EAX
idiv ecx ; divide EDX:EAX by ECX
test edx, edx ; check the remainder to see if divided evenly
jnz .SkipThisOne ; if remainder!=0, skip the next instruction
imul esi, ecx ; if remainder==0, multiply running total by counter
.SkipThisOne:
cmp ecx, edi ; are we done yet? compare counter to input value
jl .CheckCounter ; if counter hasn't yet reached input value, keep looping
mov eax, esi ; put our running total in EAX so it gets returned
ret
```
The fact that the `IDIV` instruction uses hard-coded operands for the dividend cramps my style a bit, but I think this is pretty good for a language that has no built-ins but basic arithmetic and conditional branches!
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 2 bytes
```
KΠ
```
Explanation:
```
K # Gets the divisors of a number
Π # Product of array
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJLzqAiLCIiLCIzMCJd)
[Answer]
# TI-Basic (TI-84 Plus CE), 24 bytes
```
Prompt X
1
For(A,1,X
If not(remainder(X,A
AAns
End
```
Full program: prompts user for input; returns output in `Ans`, a [special variable](http://tibasicdev.wikidot.com/ans) that (basically) stores the value of the latest value calculated.
Explanation:
```
Prompt X # 3 bytes, Prompt user for input, store in X
1 # 2 bytes, store 1 in Ans for use later
For(A,1,X # 7 bytes, for each value of A from 1 to X
If not(remainder(X,A # 8 bytes, If X is divisible by A...
AAns # 3 bytes, ...store (A * Ans) in Ans
End # 1 byte, end For( loop
```
[Answer]
# C (gcc), ~~52~~ 48 bytes
```
p,a;f(x){for(p=1,a=x;a;a--)p*=x%a?1:a;return p;}
```
-4 bytes thanks to Cody Gray
A function that takes in an integer and returns the product of it's divisors.
[Try it online!](https://tio.run/##HYxBCsMgEEXXeoohENBGF2mhi0ylF@lmSGqZRY1IWoTg2a3p6sHn/Tfb1zzXGg2hV1nvfk0qutGQy0hI1up4crmn@zgRpuf2SQEilsphgzdxUN@VFw27FMfCKMVRYHAwIjDc4NI4DPxXREzN8qrrz8sE/XV5hM4AG/CKtW7fIkv9AQ)
Ungolfed:
```
int proddiv(int input) {
int total = 1, loopvar;
for(loopvar = input; loopvar > 0; --loopvar) {
// for loopvar from input down to 1...
total *= (input % loopvar) ? 1 : loopvar;
// ...If the loopvar is a divisor of the input, multiply the total by loopvar;
}
return total;
}
```
[Answer]
# [Shakespeare Programming Language](http://esolangs.org/wiki/Shakespeare), 353 bytes
```
.
Ajax,.
Puck,.
Page,.
Act I:.
Scene I:.
[Enter Ajax and Puck]
Ajax:
You cat
Puck:
Listen to thy heart
[Exit Ajax]
[Enter Page]
Scene II:.
Puck:
You sum you cat
Page:
Is Ajax nicer I?If so, is remainder of the quotient Ajax I nicer zero?If not, you product you I.Is Ajax nicer I?If so, let us return to scene II
Scene III:.
Page:
Open thy heart
[Exeunt]
```
Ungolfed version:
```
The Tragedy of the Product of a Moor's Factors in Venice.
Othello, a numerical man.
Desdemona, a product of his imagination.
Brabantio, a senator, possibly in charge of one Othello's factories.
Act I: In which tragedy occurs.
Scene I: Wherein Othello and Desdemona have an enlightened discussion.
[Enter Othello and Desdemona]
Othello:
Thou art an angel!
Desdemona:
Listen to thy heart.
[Exit Othello]
[Enter Brabantio]
Scene II: Wherein Brabantio expresses his internal monologue to Desdemona.
Desdemona:
Thou art the sum of thyself and the wind!
Brabantio:
Is Othello jollier than me?
If so, is the remainder of the quotient of Othello and I better than nothing?
If not, thou art the product of thyself and me.
IS Othello jollier than me?
If so, let us return to scene II!
Scene III: An Epilogue.
Brabantio:
Open thy heart!
[Exeunt]
```
I'm using [this SPL compiler](https://github.com/drsam94/Spl) to run the program.
Run with:
```
$ python splc.py product-of-divisors.spl > product-of-divisors.c
$ gcc product-of-divisors.c -o pod.exe
$ echo 30 | ./pod
810000
```
[Answer]
# JavaScript (ES7), 32 bytes
```
n=>g=(i=n)=>i?i**!(n%i)*g(i-1):1
```
Saved a couple of bytes by borrowing Leaky's tip on [musicman's Python solution](https://codegolf.stackexchange.com/a/130458/58974).
---
## Try it
```
o.innerText=(f=
n=>g=(i=n)=>i?i**!(n%i)*g(i-1):1
)(i.value=1)();oninput=_=>o.innerText=f(+i.value)()
```
```
<input id=i type=number><pre id=o>
```
---
## Alternative (ES6), 32 bytes
```
n=>g=(i=n)=>i?(n%i?1:i)*g(i-1):1
```
[Answer]
# TI-Basic, ~~24~~ ~~14~~ 13 bytes
Saved 1 byte thanks to lirtosiast
```
:‚àö(Ans^sum(not(fPart(Ans/randIntNoRep(1,Ans
```
[Answer]
# [RProgN 2](https://github.com/TehFlaminTaco/RProgN-2), 2 bytes
```
ƒ*
```
Another language with built ins for `divisors` and `product`.
[Try it online!](https://tio.run/##Kyooyk/P0zX6///YJK3///8bmQAA "RProgN 2 – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 7 bytes
-1 byte thanks to @rak1507.
```
f←×/∘∪⊢∨⍳
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TD0/Ufdcx41LHqUdeiRx0rHvVu/v@obypQIk3B0OQ/AA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Go](https://go.dev), ~~65~~ 64 bytes
```
func p(n int)int{p,i:=1,1
for;i<=n;i++{if n%i<1{p*=i}}
return p}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LY1BCsIwEEXXzSmGgtCYKAY30jbgwgN4hVKaMminIaSrkJO4KYKH8CjexlS7GN5i-O89nv04v23T3pq-g6FBYjjY0XnIzeDz1-TN7vQ5m4lasAUBkufpgpVYaiUVM6OrsNZUoRABDdAGaxXsVmOMzHV-cgQ2rp7Lz7NUCg6BZWkMCKUGVSXWcDwkCrG8spTfX11q3alAmeLIOcsiW13z_OcX)
### Ungolfed
* -1 swapping `==0` for `<1` (@Steffan)
```
func product(s []int) int {
p := 1
for _,e := range s {
p *= e
}
return p
}
func divisors(n int) (d []int) {
for i := 1; i <= n; i++ {
if n % i == 0 {
d = append(d, i)
}
}
return d
}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bZBBSgQxEEXXySk-A0LitDLiRpzJHVy4E5HQSYZi7CSk026GPombRvAQXsA7eBvTmXF04aY-9Qver6rXt22YPqJud3pr0WnynLoYUsbCdXnxPmR3cfP16QbfIqZghjaLHg-P5LNEKdhzFnGrcMWZCwlPjZ27pH3B9fO0jM8VLGcjZ8nmIXlEPvJKNPRCfUi98KhAYX7Q-wOOKnpddKPgiy6XlUkOHmfFVgqr6jADBR2j9UaYBiSLN_4NNXw8XnNfs-dbxX9BuF79BpUnXN6lstKzF9ScXnBanKSUc8qRPU0H_QY)
[Answer]
# [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 22 bytes
```
[:|~b/a=b'\`a|q=q*a}?q
```
## Explanation
```
[:| FOR a = 1; a <= input (b); a++
b/a=b'\`a 'a' is a proper divisor if integer division == float division
~ | IF that's true
q=q*a THEN multiply running total q (starts as 1) by that divsor
} NEXT
?q Print q
```
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 18 bytes
```
n->n^(numdiv(n)/2)
```
[Try it online!](https://tio.run/##K0gsytRNL/ifpmCr8D9P1y4vTiOvNDcls0wjT1PfSPN/Wn6RRh5QzlBHwdhAR6GgKDOvBCigpKBrByTSgKo0Nf8DAA "Pari/GP – Try It Online")
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 27 bytes
```
@(n)prod(find(~mod(n,1:n)))
```
This defines an anonymous function.
[Try it online!](https://tio.run/##y08uSSxL/f/fQSNPs6AoP0UjLTMvRaMuF8jK0zG0ytPU1PyfmFesYWyg@R8A "Octave – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~52~~ 50 bytes
* Thanks @ovs for 2 bytes: `m*=n%i>0 or i`
```
i=n=input()
m=1
while i:m*=n%i>0 or i;i-=1
print m
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9M2zzYzr6C0REOTK9fWkKs8IzMnVSHTKlfLNk81085AIb9IIdM6UxcoVVCUmVeikPv/v7EBAA "Python 2 – Try It Online")
[Answer]
# [PHP](https://php.net/), 45 bytes
```
for($p=1;$d++<$argn;)$argn%$d?:$p*=$d;echo$p;
```
[Try it online!](https://tio.run/##K8go@G9jX5BRwKWSWJSeZ6tkZKJk/T8tv0hDpcDW0FolRVvbBixjrQmmVFVS7K1UCrRsVVKsU5Mz8lUKrP//BwA "PHP – Try It Online")
[Answer]
# Mathematica, 17 bytes
for those who can't view deleted answers (DavidC's answer), this is the code in Mathematica with the help of @MartinEnder
```
1##&@@Divisors@#&
```
[Answer]
## Python 3, 45 bytes
`lambda _:_**(sum(_%-~i<1for i in range(_))/2)`
Let `x` be a number. Both `y` and `z` will be divisors of `x` if `y * z = x`. Therefore, `y = x / z`. Let's say a number `d` has 6 divisiors, due to this observation the divisors will be `a`, `b`, `c`, `d / a`, `d / b`, `d / b`. If we multiply all these numbers (the point of the puzzle), we obtain `d * d * d = d ^ 3`. In general, for `e` with a number of `f` divisors, the product of said divisors will be `e ^ (f / 2)`, which is what the lambda does.
[Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRId4qXktLo7g0VyNeVbcu08YwLb9IIVMhM0@hKDEvPVUjXlNT30jzP1w0J7O4RAMiZahjaKipqR1taKRjaKJjBESmOkYWOsYGsVZcCgoFRZl5JRppGpmamv8B "Python 3 – Try It Online")
[Answer]
# [MY](https://bitbucket.org/zacharyjtaylor/my-language/src/5ebf758a930fa4f4140d49db53b3ce8359aa1b65?at=master), 4 bytes
Hex:
```
1A 3A 54 27
```
Explanation:
```
1A - Input as an integer
3A - Factors
54 - Product
27 - Output (with newline)
```
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), ~~52~~ 51 bytes
```
n->{int r=n,d=0;for(;++d<n;)r*=n%d<1?d:1;return r;}
```
[Try it online!](https://tio.run/##NY5Ba8MwDIXv/RWiEEiW1DT0VscrPe4wdig7jR28OC7OUtnISiGU/PbM7baDeEJ6evp6fdUbHzrszfcSxq/BtdAOOkZ41Q7htgL4m0bWnOTqnYFL2uUnJofnj0/QdI7FwwrQpzwxshuEHbFl51G8IL@jpuktdKTZE1i14Ob55pCBFFZGbaX1lMuyNA3Kgp4UZqapD2ZfS@p4JASS8yIfD5IT8vspgoJaJmkU7LapKct/CIDTFLm7CD@yCImSbb7OdmYPmclwXQFWYIUOYZiOMeHlWBS/6fPqXvPyAw "Java (OpenJDK 8) – Try It Online")
Thanks LeakyNun for saving 1 byte!
] |
[Question]
[
I read [this](https://stackoverflow.com/q/43593278/5401763) question and thought it would make a nice challenge.
## Task
Give an input `0<n<10` generate a random number with
* exactly n digits
* the first not a `0`
+ so `f(n)>10**(n-1)-1`
* distinct digits
## Winning criteria
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code wins.
## Random
I mean evenly distributed random. So from the view of the program each possible number has the same chance. If the language you're writing in has a weird random number generator, it's okay to use that one.
## Example
The list of values to randomly select from for `n=2` is:
```
[10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98]
```
[Answer]
# [Python 2](https://docs.python.org/2/), 77 bytes
```
from random import*
r=range(10)
while[1]>r:shuffle(r)
print`r`[1:input()*3:3]
```
[Try it online!](https://tio.run/nexus/python2#DcgxCoAgFADQ3VM0qhBkbUJdRASjvimYyk/p5M3m9OA1i@kecI9nx985YeEE1x4XUDEx8jofQAm9oXxctTYARUYy@lgMGiWkj7kWyvgiF93a/MU0Hvvh4Ac "Python 2 – TIO Nexus")
Shuffles the list of 10 digits until it doesn't start with 0, then makes a number with the first `n` digits listed.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~9~~ 10 bytes
```
{~lℕ₁≜≠}ᶠṛ
```
[Try it online!](https://tio.run/nexus/brachylog2#ASUA2v//e35s4oSV4oKB4omc4omgfeG2oOG5m///M/9a9W5vLWNhY2hl "Brachylog – TIO Nexus")
As usual for Brachylog, this is a function submission. The TIO link above has been given a command-line argument to make the function into a full program.
I had to add an extra byte from the first version of this, changing `ℕ` to `ℕ₁`, to disallow the output 0 (something that's now been clarified).
## Explanation
```
{~lℕ₁≜≠}ᶠṛ
{ }ᶠṛ Pick a random value with these properties:
~l it has length equal to the input;
ℕ₁ it's a positive integer;
≜ it's a specific value (not a constraint);
≠ all its elements (digits in this case) are different.
```
Fairly inefficient, because the interpreter generates a list of all possible values and then picks one at random (that's what `ᶠṛ` means; Brachylog didn't have a "pick a random solution" option at the time this question was asked).
Some comments on the labelization here: if the `≜` is omitted, the section within the braces only produces one value, a constraint representing numbers with the property we want; picking a random result therefore gives us the constraint, and the interpreter outputs the minimum absolute value that meets the constraint (1, 10, 102, 1023, 10234, etc.), which is not what we want. We thus have to force it to construct the list via an explicit labelization.
Most Prolog implementations I've seen have a builtin to find a random result matching a constraint, but typically not with uniform probability; Brachylog didn't have one, though (one got added in response to this challenge, but obviously I can't use it due to loophole rules). If it did, and if it happened to give uniform probability on this problem, this program would just be `~lℕ₁≠` followed by that builtin, for a likely length of 6 bytes.
# [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes, in collaboration with @Fatalize
```
~lℕ₁≠≜ᶠṛ
```
[Try it online!](https://tio.run/nexus/brachylog2#ASAA3///fmzihJXiiaDiiZzhtqDhuZv//zT/WvVuby1jYWNoZQ "Brachylog – TIO Nexus")
This is the sort of genius low-level trick that only makes sense with the way Prolog does things, and doesn't make much sense when described mathematically.
As before, `~lℕ₁≠` builds up a value that describes a constraint ("length equal to the input, natural number, all elements different"). Then `≜ᶠ` generates all possible values that meet the constraint. The point here is that with Brachylog's evaluation sequence, no actual choices are made until the `≜` appears, so the "find all solutions" operation `ᶠ` need apply to nothing but the "specific value that fulfils a constraint" operation `≜`. That means there's no need for a `{…}` to select its scope, saving 2 bytes.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
⁵*ṖQL$€MX
```
**[Try it online!](https://tio.run/nexus/jelly#@/@ocavWw53TAn1UHjWt8Y34//@/8de8fN3kxOSMVAA "Jelly – TIO Nexus")** (won't work at TIO for **n > 6** due to the inefficiency of the implementation)
or an alternative implementation of the same thing:
```
⁵*ṖQL$ÐṀX
```
### How?
This is pretty sneaky, and very inefficient! Jelly does some useful things implicitly when an atom expects a list but receives an integer (this is by design).
This code uses a couple of these useful implicit actions:
* The monadic atom `Ṗ`, "pop", when called with an integer input implicitly makes a range from which to pop, so an input of **n** first makes **[1, 2, ..., n]**, then pops, yielding **[1, 2, ..., n-1]**.
* The monadic atom `Q`, "de-duplicate" or "unique", when called with an integer input implicitly makes a decimal list to de-duplicate, so an input of **n** where:
**n = dk-1×10k-1 + dk-2×10k-2 + ... + d1×10 + d0**
first makes
**[dk-1, dk-2, ... ,d1, d0]**
and then yields the unique values by first appearance.
So, for example, **n = 5835518** would yield **[5, 8, 3, 1]**.
Furthermore the monadic atom `M`, "maximal element indexes", returns the indexes of the maximal items from a list, this saves **two** bytes over the far more obvious alternative of testing for equality with the input and finding truthy indexes, `⁵*ṖQL$€=⁸TX`, or `⁵*ṖðQL⁼ð€TX`
```
⁵*ṖQL$€MX - Main link: n e.g. 2
⁵ - literal 10
* - exponentiate: 10^n 100
Ṗ - pop (make range 1 to 10^n, then pop) [1 ,2 ,...,21 ,22 ,23 ,...,97 ,98 ,99]
$€ - last two links as a monad for €ach:
Q - unique (makes a decimal list first) [[1],[2],...,[2,1],[2],[2,3],...,[9,7],[9,8],[9]]
L - length [1 ,1 ,...,2 ,1 ,2 ,...,2 ,2 ,1 ]
M - indexes of maximal elements [ ...,21 ,23, ...,97 ,98 ]
- - i.e. all n-digit numbers with n-distinct digits.
X - pick a random element from that list
```
This is all quite quite inefficient, both in time and memory: first a list of **10n** integers is made and one is discarded, then for each of these a list of **n** integers (not some fancy 4-bit object or enum) is made and then de-duplicated. This de-duplication has a completely list-based implementation (no sets, sorted-sets, or dictionaries are involved under-the-hood, each digit is checked for existence in the list that eventually gets output).
Offline **n = 7** uses ~0.5GB and takes ~25 seconds, while **n = 8** uses ~4GB and takes ~5 minutes - I have not bothered running **n = 9** as I only have 16GB ram (I guess it would take ~45 minutes).
The alternative implementation just uses the built-in `ÐṀ` quick to filter-keep minimal (which here just adds a little overhead in management for the same byte-count).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
9Xœ|⁵ḶẊ¤ḣ¹Ḍ
```
[Try it online!](https://tio.run/nexus/jelly#ASYA2f//OVjFk3zigbXhuLbhuorCpOG4o8K54biM////M/Vuby1jYWNoZQ "Jelly – TIO Nexus")
### How it works
```
9Xœ|⁵ḶẊ¤ḣ¹Ḍ Main link. Argument: n
9 Set the return value to 9.
X Pick; pseudo-randomly select an integer from [1, ..., 9].
¤ Combine the three preceding links into a niladic chain.
⁵ Yield 10.
Ḷ Unlength; yield [0, ..., 9].
Ẋ Shuffle; pseudo-randomly select a permutation of [0, ..., 9].
œ| Multiset OR; prepend the selected integer to the selected permutation
and remove the second occurrence of the first element.
¹ Identity; yield n.
ḣ Head; keep the first n digits of the permutation.
Ḍ Undecimal; convert from base 10 to integer.
```
[Answer]
## JavaScript (ES6), ~~72~~ ~~71~~ ~~70~~ 69 bytes
```
f=(x,y="")=>x?!y.match(z=Math.random()*10|0)&&y|z?f(x-1,y+z):f(x,y):y
```
This is a recursive function that takes in the number of digits **x**. The second parameter **y**, initially set to the empty string, keeps track of the number as we generate it digit by digit.
First we generate a random digit **z** with `Math.random()*10|0`. Now, we want to check that the **y** does not contain **z**, and that **y** and **z** are not both **0**.
We can calculate the first condition with `!y.match(z)`. `y.match(z)` returns an array (always truthy) if **y** contains **z**, **null** (falsy) otherwise; the `!` converts this to a boolean and inverts it.
The second condition is checked with `y|z`. Although **y** is a string, JS implicitly converts it to an integer when using `|`. This is a positive integer if **y** already contains digits, **0** otherwise. The net result is that `y|z` returns **0** iff **y** is empty and **z** is **0**, or a positive integer otherwise.
If both of these conditions are true, then we append the digit to **y**, decrement **x**, and start the process over again. Otherwise, we simply return to the beginning and hope that the next random digit works. When **x** reaches **0**, we simply return the empty string to end the recursion.
---
Previous version:
```
f=(x,y)=>x?~y>>(z=Math.random()*10|0)&1&&y|z?z+f(x-1,y|1<<z):f(x,y):""
```
This is a recursive function that takes in the number of digits. The initially undefined second parameter, **y**, is a 10-bit lookup table telling us which digits we already have, conveniently stored as an integer.
First we generate a random digit **z** with `Math.random()*10|0`. Now, we want to check that the **z**'th least significant bit of **y** is not set, and that **y** and **z** are not both **0**.
We can calculate the first condition with `~y>>z&1`; invert **y**, shift it **z** bits to the right, and take only the least significant bit. This gives **1** if we have not yet generated the digit in question, or **0** otherwise.
The second condition was initially pretty difficult to figure out (I tried using `y/z` at first to generate `NaN` if they're both 0), but at some point I realized that simply `y|z` would do the trick. The result is **0** iff both **y** and **z** are **0**; a positive integer otherwise.
If both of these conditions are true (`~y>>z&1&&y|z`), then we generate the rest of the number and prepend **z**. The rest of the number is generated by calling the function again with `x-1` and `y|1<<z` (**y**, but with the bit at index **z** set to **1**). When **x** reaches **0**, we simply return the empty string to end the recursion.
[Answer]
# ClojureScript, ~~81~~ 79 bytes
```
#(let[a(subvec(shuffle(range 10))0 %)](if(=(a 0)0)(recur %)(int(apply str a))))
```
This is an anonymous function, so you have to use it like this:
```
(#(...) {arguments})
```
Where you replace `{arguments}` with your arguments.
You can try the code [here](http://clojurescript.io) (ClojureScript REPL).
Thanks `@cliffroot` for shaving off 2 bytes!
---
## Expanded code:
```
(defn random-digits [n]
(let [num-vector
(subvec
(shuffle (range 10))
0 n)]
(if (= (num-vector 0) 0)
(recur n)
(int (apply str num-vector)))))
```
---
## Explanation:
I'm going to go through the lines one by one, using an example input of `8`.
---
```
(defn random-digits [n] ...)
```
Pretty simple, this defines the function `random-digits` with one argument, called `n`. In my answer I used an anonymous function (`#(...)`), to save bytes.
---
```
(let [num-vector ...] ...)
```
Let's examine inside the `let`, from inside out:
```
(shuffle (range 10))
```
In ClojureScript (and Clojure), `(range n)` is similar to Python's `range(n)`: it gives you a list with every number from `0` to `n - 1` (`9` in this case).
`shuffle` takes a list, and returns a vector (which is slightly different from a list) with all of its elements shuffled. So, using our example, we get something like this:
```
[1 0 8 3 6 7 9 2 4 5]
```
---
```
(subvec {see above} 0 n)
```
`(subvec vector start end)` takes a vector (only a vector), and returns a vector which has all the elements from index `start` to `end`. In this case, we're taking elements from the `0`th element to the argument given to `random-digits`. If we apply that to our example, we get:
```
[1 0 8 3 6 7 9 2]
```
---
```
(if (= (num-vector 0) 0)
(recur n)
(int (apply str num-vector)))
```
This `if` statement checks if the first element of `num-vector` is a `0`.
If it is `0`, then we call the function again, with the argument `n`, using `recur`.
If it isn't `0`:
---
```
(int (apply str num-vector))
```
`(apply function list)` takes a list, and spits them into the function as arguments. For example:
```
(apply + [2 3 4])
```
Turns into:
```
(+ 2 3 4)
```
Which equals `9`.
`(str items)` turns every item in `items` into a string, and then concatenates them. `int` converts anything to an integer. So if we apply this to our example, we get:
```
(int (apply str [1 0 8 3 6 7 9 2]))
=> (int (str 1 0 8 3 6 7 9 2))
=> (int "10836792")
=> 10836792
```
Which is our final answer.
[Answer]
# Python 2, ~~89~~ ~~81~~ 80 bytes
```
from random import*
lambda n:choice([i for i in range(10**n)if`set(`i`)`[5*n:]])
```
[**Try it online**](https://tio.run/nexus/python2#FcoxCsMwDADAva/QKBkKzZAl0JeEgF3HagS1ZFT36Z3ddLrlBrtV8KT7idRm3sOF769UH3sCXfJhkguuAmwOAqL//Cw43UJQEo7v0jFKpLjOQZdto9FctAOjaPt0JBrzV@2aUz7KDw)
[Answer]
# R, 45 Bytes
```
k=0
i=scan()
while(!k[1])k=sample(0:9)[1:i]
k
```
[Answer]
# Bash + GNU utils, 46
```
seq 1e$[$1-1] 1e$1|egrep -v '(.).*\1'|shuf -n1
```
[Try it online](https://tio.run/nexus/bash#Fca9DkAwFAbQ3VN8QxM/yW1yF4tHwSB10aVFseCxzcWZzuBXWFiHk7Uu7wq9T/AJsoEIysYgC1hUrZi4/ceXjKvMoANppnNdNJxeYdoHkOPYeyfxcZ5MZyZ5AQ).
This takes a long time for larger *n* - about 30s for n=7, and increasing 10 times for each increment, so probably 8-9 hours for n=10.
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), ~~27~~ ~~19~~ 17 bytes
Requires `⎕IO←0` which is default on many systems.
```
10⊥⊢↑{?⍨10}⍣{×⊃⍺}
```
[Try it online!](https://tio.run/nexus/apl-dyalog#U9Z71DfV0/9R2wQDLmUQO8gHyH7Uu@Z/GpA2NHjUtfRR16JHbROr7R/1rjA0qH3Uu7j68PRHXc2PenfV/v@fdmiFoYKRgrGCiYKpgpmCuYKFgqWCocHXvHzd5MTkjFQA "APL (Dyalog Unicode) – TIO Nexus")
Shuffles the digits until valid:
`10⊥` decode from base-10 digits to regular number,
`⊢` the n
`↑` first elements of
`{`…`}⍣{`…`}` repeating the function…
`?⍨10` shuffle the first ten positive integers
until…
`⊃⍺` the first digit of the last attempt
`×` is positive
[Answer]
# Java 10, ~~150~~ ~~147~~ ~~145~~ ~~134~~ ~~132~~ 110 bytes
```
n->{var r="";for(int l,x;(l=r.length())<n;x*=Math.random(),r+=(l<1?x>0:!r.contains(""+x))?x:"")x=10;return r;}
```
-2 bytes thanks to *@TheLethalCoder*
-2 bytes thanks to *@ceilingcat*.
[Try it online.](https://tio.run/##NZDBboMwDIbvfQovp2RpI7gSUp6gvew47ZABbdMFU5mAMlU8Owttd7Fk//6t7/fVTnZ3bX6W2tthgIN1eN8AOAwtnWzdwnFtAT4COTxDzZMCKHQazptUhmCDq@EICAYW3O3vkyUgw5g@9fTY9tuouTekfIvncOFClKjjuznYcFFksek7LrYkDfdlXsV9VryRqnsMiWXgjMkoRBULxkQ0eaapDSMhkJ4XvRLcxm@fCF4gU@8a6JKTP4k/v8CKZ4R/HmdyDa5cb4GTUjzElPB3CG2n@jGoW3IGj9xJVgCT3JV5VjFgK4NElZ4gXh@Ylz8)
**Explanation:**
```
n->{ // Method with integer parameter and String return-type
var r=""; // Result-String, starting empty
for(int l,x; // Temp integers
(l=r.length())<n // Loop until the length of the String is equal to the input:
; // After every iteration:
x*=Math.random(),// Pick a random digit
r+= // Append to the result-String:
(l<1? // If the String is empty:
x>0 // Make sure the first random digit is not 0
: // Else (the String is not empty):
!r.contains(""+x))
// Check that the String doesn't contain this digit yet
? // And if that's truthy:
x // Append the random digit
: // Else:
"") // Leave the String the same by appending an empty String
x=10; // (Re)set `x` to 10 for the next random digit
return r;} // Return the result-String
```
[Answer]
# [Perl 6](https://perl6.org), 44 bytes
```
{(->{+[~] (^10).pick($_)}...*>9 x$_-1).tail}
```
[Try it](https://tio.run/nexus/perl6#Ky1OVSgz00u25sqtVFBLzk9JVbD9X62ha1etHV0Xq6ARZ2igqVeQmZytoRKvWaunp6dlZ6lQoRKva6ipV5KYmVP7Py2/SMFAIU5PL07B0EChmktBoTixUgFkEkgLV@3/r3n5usmJyRmpAA "Perl 6 – TIO Nexus")
## Expanded:
```
{ # bare block with implicit parameter 「$_」
(
->{ # pointy block lambda with no parameters
+ # turn the following into a numeric
[~] # concatenate the following
(^10).pick($_) # grab $_ digits at random from 0..9
}
... # keep doing that until
* > 9 x $_-1 # one of them is big enough
).tail # return the last one (only valid one)
}
```
[Answer]
# PHP, 67 Bytes
[Online Version](http://sandbox.onlinephpfunctions.com/code/436bda2f3f91d9e62bfdfd8cde7f061500948509)
All versions based of shuffle the digits from 0-9
```
for($a=range(0,9);!$a[0];)shuffle($a);for(;$i<$argn;)echo$a[+$i++];
```
71 Bytes
```
for($s="0123456789";!$s[0];)$s=str_shuffle($s);echo substr($s,0,$argn);
```
73 Bytes
```
for($a=range(0,9);!$a[0];)shuffle($a);echo join(array_slice($a,0,$argn));
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
9×!X+!Œ?’ḣƓḌ
```
Currently one byte behind my other Jelly answer, but I really like this one.
[Try it online!](https://tio.run/nexus/jelly#ASIA3f//OcOXIVgrIcWSP@KAmeG4o8aT4biM//8z9W5vLWNhY2hl "Jelly – TIO Nexus")
### How it works
```
9×!X+!Œ?’ḣƓḌ Main link. No arguments.
9 Set the argument and the return value to 9.
! Yield 9!
× Compute 9 × 9!.
X Pick; pseudo-randomly select an integer j from [1, ..., 9 × 9!].
! Yield 9!
+ Compute k := j + 9!.
The result will belong to [9! + 1, 10!].
Œ? Get the permutation P of R := [1, ..., r], with minimal r, such that
P is the lexicographically k-th permutation of R.
Since k belongs to [9! + 1, 10!], r = 10 and this generates a per-
mutation between [2,1,3,4,5,6,7,8,9,10] and [10,9,8,7,6,5,4,3,2,1].
’ Subtract 1 from all integers in P.
Ɠ Read an integer n from STDIN and yield it.
ḣ Head; keep the first n digits of the permutation.
Ḍ Undecimal; convert from base 10 to integer.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~9~~ ~~7~~ ~~10~~ 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
°L¨ʒÙgQ}Ω
```
Very slow for larger \$n\$.
[Try it online](https://tio.run/##yy9OTMpM/f//0AafQytOTTo8Mz2w9tzK//9NAA) or [verify some more test cases](https://tio.run/##ATkAxv9vc2FiaWX/NEUibj0iP07CqT8iIOKGkiAiP1RGwq7/wrBMwqjKksOZZ8KuUX3Oqf8/w7A/fcK2P/8).
~~+3~~ +2 bytes because I missed the requirement of an evenly distribution..
**Original invalid 7 byter solution:**
(can output all random outputs, but not evenly distributed)
```
žh.rïI£
```
[Try it online](https://tio.run/##yy9OTMpM/f//6L4MvaLD6z0PLf7/3xQA) or [verify some more test cases](https://tio.run/##ATQAy/9vc2FiaWX/OUUibj0iP07CqT8iIOKGkiAiP1RGwq7/xb5oLnLDr8KuwqP/P8OwP33Ctj//).
**Explanation:**
```
° # Push 10 to the power of the (implicit) input-integer
L # Push a list in the range [1, 10**input]
¨ # Remove the last value to make the range [1, 10**input)
ʒ # Filter this list by:
g # Where the amount
Ù # of the unique digits
Q # is equal to the (implicit) input-integer
}Ω # After the filter: pop and push a random element of the list
# (after which it is output implicitly as result)
žh # Push the builtin string "0123456789"
.r # Randomly shuffle it
ï # Cast it to an integer to remove any potentially leading 0s
I£ # Only leave the first input amount of digits
# (after which it is output implicitly as result)
```
[Answer]
# [W](https://github.com/A-ee/w), 6 [bytes](https://github.com/A-ee/w/wiki/Code-Page)
To make this work, you need an extra operand (e.g. `""`). After providing it, this W script would ignore this operand.
```
"▬←l╟B
```
Uncompressed:
```
U=a^(Xg
```
## Explanation
```
a % Take a single input
^ % 10 ** input
( % Decrement by 1 so that special cases like 100 would be avoided
X % Filter out all items in the implicit range 1 to operand
U % Uniquify (the current item)
% This also implicitly converts the current item to a string
= % Check whether (the length of) the current item is equal to (the input)
g % *Evenly* Pick a random number in the list.
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 15 bytes
```
`4Y2GZr1)48=]8M
```
Try it at [MATL Online!](https://matl.io/?code=%604Y2GZr1%2948%3D%5D8M&inputs=3&version=19.10.0)
### Explanation
```
` % Do...while
4Y2 % Push predefined literal '0123456789'
G % Push input n
Zr % Random sample of n unique characters from that string
1) % Pick the first
48= % Is it 48? This is the loop condition
] % End. If top of the stack evaluates to true: next iteration
8M % Push the latest random sample. Implicitly display
```
[Answer]
## [Python 2](https://docs.python.org/2/), ~~100~~ ~~93~~ ~~92~~ 90 bytes
*Thanks to @mbomb007 for shaving off 2 bytes*
```
from random import*
def f(n):k=randint(10**~-n,10**n-1);return(n==len(set(`k`)))*k or f(n)
```
Tries numbers in the required until one is found with unique digits. I'll bet there's a much cleaner way to do this, but none's coming to mind.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 11 bytes
```
jk<{+OS9.ST
jk<{+OS9.STQ implicit Q
9 9
S [1,2,3,4,5,6,7,8,9]
O random element
T 10
.S random permutation of [0,1,2,3,4,5,6,7,8,9]
+ add the results from the previous two paragraphs together
{ deduplicate
< Q first (input) elements
jk join by empty string
```
Uses the same algorithm as [Dennis' answer](https://codegolf.stackexchange.com/a/117519/48934).
[Try it online!](http://pyth.herokuapp.com/?code=jk%3C%7B%2BOS9.ST&input=6&debug=0)
[Answer]
# Perl, 48 bytes
```
1until$_=1+int rand 10**$n-1,/.{$n}/&&!/(.).*\1/
```
## Explanation:
Repeatedly generate random integers from 1 to 10\*\*$n-1, rejecting them until there is one of the correct length (so at least 10\*\*($n-1)) with no repeated digits.
[Answer]
## Batch, 156 bytes
```
@set/af=9,r=x=0
@for /l %%i in (1,1,%1)do @call:c
@echo %r%
@exit/b
:c
@set/a"d=9-%random%%%f,e=x>>d&1
@if %e%==1 goto c
@set/a"r=r*10+d,f=10,x|=1<<d
```
`x` maintains a bitmask of used digits. `f` indicates the number of available digits (counting down from 9). Random digits are generated until an unused digit is found. `n=10` could be supported for 165 bytes:
```
@set/af=9,r=x=0
@for /l %%i in (1,1,%1)do @call:c
@echo %r:~1%
@exit/b
:c
@set/a"d=9-%random%%%f,e=x>>d&1
@if %e%==1 goto c
@set r=%r%%d%
@set/a"f=10,x|=1<<d
```
(`r` contains an extra leading zero because it's golfier that way.) Previous approach for 165 bytes special-cased the first digit, and also happened to work with `n=10` (the numeric version actually took 166 bytes!):
```
@set/ar=%random%%%9+1,x=0
@for /l %%i in (2,1,%1)do @set/a"x|=1<<d"&call:c
@echo %r%
@exit/b
:c
@set/a"d=%random%%%10,e=x>>d&1
@if %e%==1 goto c
@set r=%r%%d%
```
Original approach for 170 bytes also worked for `n=10`:
```
@set/ar=%random%%%9+1
@for /l %%i in (2,1,%1)do @call:c
@echo %r%
@exit/b
:c
@set/ad=%random%%%10
@call set s=%%r:%d%=%%
@if not "%s%"=="%r%" goto c
@set r=%r%%d%
```
Uses string manipulation to detect duplicate digits.
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 66 bytes
```
a=0;while [[ $a == 0* ]];do a=`shuf -i0-9 -n$1|xargs`;done;echo $a
```
[Try it online!](https://tio.run/nexus/bash#FYvBCsIwEAXvfsU75CRsSY8l5EtKoUu6NQuShUZRUD/bc4xzG4bZ7YBCC17jMEyfgM1O6FS5gQhOG0cfHlmvgnmGY8QIf8ayhM3Aca35voPU0wQqbnw/@bjUtcciQVK2vrS/tG8xSpyy/AA "Bash – TIO Nexus")
Straight forward, usues shuf, xargs is used to join lines and continues to try while the combination starts with 0.
Cant beat 46 char from other answer but thus is fast!
[Answer]
# Pyth, ~~15~~ 28 bytes
```
=+YhO9VtQ#KOTI!hxYK=+YKB;jkY
```
[Try it here](http://pyth.herokuapp.com/?code=%3D%2BYhO9VtQ%23KOTI%21hxYK%3D%2BYKB%3BjkY&input=8&debug=0)
[Answer]
## C#, ~~127~~ ~~132~~ ~~128~~ ~~126~~ 125 bytes
```
n=>{var s="";for(int l,r;(l=s.Length)<n;)if((l<1&(r=new System.Random().Next(10))>0)|(l>0&!s.Contains(r+"")))s+=r;return s;};
```
[Try It Online!](http://rextester.com/MCE85919)
Borrowed the idea from [@KevinCruijssen's answer](https://codegolf.stackexchange.com/a/117574/38550) to initialise the random, `r`, in the `if` statement to save 2 bytes.
Pretty sure this can be golfed further but I don't have time at the moment.
---
Old version using a `while` loop:
```
n=>{var s="";while(s.Length<n){int r=new System.Random().Next(10);if(s.Length<1&r>0)s+=r;else if(!s.Contains(r+""))s+=r;}return s;};
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~123~~ ~~122~~ ~~100~~ ~~95~~ ~~104~~ ~~103~~ ~~99~~ 97 bytes
This one generating an actual random number
```
j;f(n){for(int i,k=n,s[10]={j=0};n;s[i+=i?0:k==n]=!s[i]?j+=i*pow(10,--n):1)i=rand()%10;return j;}
```
[Try it online!](https://tio.run/nexus/c-gcc#bczLCoMwFATQvV9hhUIuKsQ@rSH4IeIi@KgX9VqM7Ub87G5rVboqmd0chplLRjCWXc@QBhu9WpKnk4CncuSTIKETdCXGPKqlpFTulp7Gvk/e4zlklerZKXQRogBQ9opyBvuAi2m21rdWIbFXhzlYo2Uv0dtkwLZgHEBsVrIAxHKmmeOAWOXHBzMfzXwy89nMFzNfzRya@fbP0/zJykbd9ew37Zs6P1NZVXwB "C (gcc) – TIO Nexus")
# [C (gcc)](https://gcc.gnu.org/), ~~87~~ 85 bytes
Here it is printing a string of digits.
```
f(n){for(int i,k=n,s[10]={0};n;s[i+=i?0:k==n]=!s[i]?--n,putchar(48+i):1)i=rand()%10;}
```
[Try it online!](https://tio.run/nexus/c-gcc#bczLCoMwFATQvV9hhUIuKsQ@rSH4IeIi@KgX9VqM7Ub87G5rVboqmd0chplLRjCWXc@QBhu9WpKnk4CncuSTIKETdCXGPKqlpFTulp7Gvk/e4zlklerZKXQRogBQ9opyBvuAi2m21rdWIbFXhzlYo2Uv0dtkwLZgHEBsVrIAxHKmmeOAWOXHBzMfzXwy89nMFzNfzRya@fbP0/zJykbd9ew37Zs6P1NZVXwB "C (gcc) – TIO Nexus")
[Answer]
# PHP, ~~65~~ 63 bytes
```
while(count(count_chars($x=rand(1,10**$argn),1))<$argn);echo$x;
```
takes input from STDIN; run with `-nR`.
create random number between `1` and `10^N` inclusive;
repeat while count of distinct characters is < `N`.
[Answer]
# [Jellyfish](https://github.com/iatorm/jellyfish), 17 bytes
```
p
d^u ?
j?r10
10
```
[Try it online!](https://tio.run/nexus/jellyfish#@1/AlRJXqmDPpZBlX2RowGVo8P@/6de8fN3kxOSMVAA "Jellyfish – TIO Nexus")
Fork of [Dennis' Jelly answer](https://codegolf.stackexchange.com/a/117519/48934).
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), ~~10~~ 11 bytes
```
úr╞gÆ░▀£k=w
```
[Try it online!](https://tio.run/##ASoA1f9tYXRoZ29sZv//w7py4pWeZ8OG4paR4paAwqNrPXf//zEKMgozCjQKNf8 "MathGolf – Try It Online")
## Explanation
```
úr push [0, ..., (10**input)-1]
╞ discard the first item of the list (0)
gÆ filter by block of 5 operators
░ convert to string (needed for "unique elements" operator
ߜ number of unique characters in string
k= is equal to input?
end of block
w random item from the filtered list
```
[Answer]
## Mathematica ~~65~~ 60 Bytes
```
0For[a=11,Max@DigitCount@a>1,a=RandomInteger[10^{#-1,#}]]+a&
```
Here is a faster version but adds 9 bytes:
```
FromDigits@Join[f=(s=RandomSample)[r=Range@9,1],s[r/.f[[1]]->0,#-1]]&
```
[Answer]
# Java 9 JShell, 86 bytes
```
n->new Random().longs(0,10).limit(n-1).reduce(new Random().nextInt(9)+1,(a,b)->a*10+b)
```
[Try it online!](https://tio.run/nexus/java-openjdk9#bU9Nb8IwDL33V/iYjDZq940YHCdN2nYYx4mDCaF4Sp2qSWFo4mfvzMIojE3zIbH83rPfo6p2TYA3XKJqA1n1gjxz1SChv8BYI7Np/kHmLetAjtV91wySpG6nljRoi97DExLDRwKxurkPGOK3dDSDKqJiHBri8nUC2JReduRddWchbhgCm9VhIMZrH0yliOXgSD4YuHvgYErTpPDouBzBHIZbzkY7@T6fkMpGxIs8LfLYU0VBcFZI1ZhZq434RWXzHuJG0Ze9IhWYTmU2wrMi703l9nD6x8RqQdaAIFYL9M@dVJ5m@s61t@/aoOoYPVgWc4V1bdc7JR9lJ@k2yf7dbAs4hwu4hCu4hhu4hT4U@Se7TKNemC8 "Java (OpenJDK 9) – TIO Nexus")
Note: I'm not counting the imports as those packages are imported by default in JShell, but there's no Try-it-online link that I know of for JShell, so I've provided one for Java 9 with header and footer code to make it work in that context. In JShell you can just do:
```
jshell> Function<Integer,Long> f =
...> n->new Random().longs(0,10).limit(n-1).reduce(new Random().nextInt(9)+1,(a,b)->a*10+b)
f ==> $Lambda$27/633070006@5702b3b1
```
And then:
```
jshell> f.apply(6)
$26 ==> 746202
```
### How it works:
We define a function from Integer to Long and create an infinite stream of random longs in the range from 0-9, limit it to the first n-1 items, then reduce it with a random int from 1-9 as the initial value and a function that multiplies the value by 10 and adds the next value from the stream.
I used longs so this should work for up to about 18 digits (n = 18).
] |
[Question]
[
# Challenge
Create the image of a pride flag (rainbow flag), i.e. a six coloured striped flag (from top to bottom): red, orange, yellow, green, blue, and violet.
# Output
[](https://i.stack.imgur.com/BPJiB.png)
# Example (R)
```
barplot(rep(1, 6), horiz = TRUE, axes = FALSE, space = 0, border = NA, col = c("darkviolet", "blue", "darkgreen", "yellow", "orange", "red"))
```
# Rules
* The algo should actually create the image, not just load an existing one.
* You may use any colors reasonably recognizable as "red", "orange", "yellow, "green", "blue", and "violet".
* The flag may either be scalable (such as an SVG, or output that scales to window size) or at least size 200px by 300px.
* All coloured areas should be of the same size.
Every answer must include the resulting picture!
Credits: this post was inspired by the following post: [Draw the flag of Tennessee](https://codegolf.stackexchange.com/q/194299/448).
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `sḢ`, 36 bytes
```
`<p «⟇=øḢ-÷¥:#%7;₃ṁ:0>.`»‡Ė\Tµi»Hǒv%
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJz4biiIiwiIiwiYDxwIMKr4p+HPcO44biiLcO3wqU6IyU3O+KCg+G5gTowPi5gwrvigKHEllxcVMK1acK7SMeSdiUiLCIiLCIiXQ==)
Stuff Vyxal isn't meant to do! This took far too long. The `Ḣ` flag renders stdout as HTML.
[](https://i.stack.imgur.com/78C7M.png)
```
v # Over each element of...
»‡Ė\Tµi» # A compressed integer
Hǒ # Split into chunks of two...
% # Insert that into...
`...` # Compresssed string `<p style=background-color:#%7;margin:0>.`
# (s flag) turn the result into something HTML understands
# (Ḣ flag) render the output as HTML
```
For compression purposes, all the character codes end in 7.
[Answer]
# [Red](http://www.red-lang.org), 73 bytes
```
view/tight[style s: box 315x35 below s red s#fa0 s#ff0 s#0f0 s#00f s#808]
```
[](https://i.stack.imgur.com/OKyL2.png)
Works in Red console. To run as a standalone program, we must add in front:
```
Red[needs view]
```
I don't know, whether this has to be counted.
[Answer]
# DOS 80186 .COM executable, ~~31~~ 30 bytes
xxd:
```
00000000: b0 13 cd 10 68 00 a0 07 31 ff be 18 01 ac b9 80 ....h...1.......
00000010: 2a f3 aa 3c 05 75 f6 c3 28 2a 2c 02 20 05 *..<.u..(*,. .
```
Commented assembly:
```
; NASM syntax
[cpu 186]
[org 0x100]
start:
; Set DOS to mode 13h for 320x200, 256 colors
; Since we know the DOS startup state, we can just set AL.
mov al, 0x13 ; 0x0013
int 0x10
; Set ES to point to the video ram segment
push 0xa000
pop es
; Set DI to point to the start of video ram
xor di, di
; Set SI to our lookup table
mov si, colors
.loop:
; Load color from lookup table
lodsb
; Roughly 1/6 of the screen
; ceil(200 / 6) * 320
mov cx, 10880
; For all CX iterations, store byte to video ram
rep stosb
; Check for last byte in lut and loop if it is not
; that.
cmp al, 5
jnz .loop
.ret:
; Return to DOS, leaving a pretty but annoying flag on
; the screen that requires a manual mode reset.
ret
; Lookup table for the default 256 color palette.
colors:
; R O Y G B P
db 40, 42, 44, 2, 32, 5
```
I'm not sure if this is valid, as the last stripe is technically a bit shorter than the others, but 200 is not a multiple of 6 so it is unavoidable at this size.
Screenshot (the `C:\CODE>` part is simply the DOS prompt overwriting it after exiting)
[](https://i.stack.imgur.com/L9aDM.png)
* 1 byte: `stosb` already stores to the `es` segment. What a dummy.
[Answer]
## Postscript, 42 bytes
Hand tokenised (42 bytes including showpage, 40 bytes without).
```
00000000: 36 88 09 32 5b 30 20 2e 31 92 38 30 88 f7 88 f7 6..2[0 .1.80....
00000010: 5d 7b 8e 05 88 33 3c e3 00 7d 8d 00 33 20 63 6f ]{...3<..}..3 co
00000020: 6c 6f 72 69 6d 61 67 65 92 a1 lorimage..
```
No tokenisation (62 bytes including showpage, 53 bytes without):
```
6 9 2[0 .1 .1 0 -9 -9]{<88333ce30>}false 3 colorimage
showpage
```
This renders to about 3.2 by 2.1 cm (0.8" by 1.25"). The size is limited by the constants '.1'. Making the flag bigger requires a smaller number which will need one extra byte (two bytes in the untokenised version).
The tokenised version is the same as the untokenised version except the ".1 .1" is encoded as ".1 dup" to save a byte.
[](https://i.stack.imgur.com/XGOJ6.png)
[Answer]
# [QBasic](https://en.wikipedia.org/wiki/QBasic), 78 bytes
```
SCREEN 9
FOR i=0TO 5
READ c
LINE(0,i*40)-(400,239),c,BF
NEXT
DATA 4,6,14,2,9,5
```
The orange looks more like brown, in my opinion, but it's the closest QBasic has (it's the dark version of yellow). Here's the output when run on DOSBox at [Archive.org](https://archive.org/details/msdos_qbasic_megapack):
[](https://i.stack.imgur.com/8cAPQ.png)
[Answer]
# ~~SVG, 254 bytes~~ HTML, ~~181~~ ~~173~~ 165 bytes
By moving from SVG to HTML, I can get away with not specifying a bunch of things and leaving some tags open.
* Saved ~ 70 bytes thanks to Wheat Wizard.
* Saved 8 + 8 bytes thanks to pxeger.
```
<svg><rect y=0 fill=red /><rect y=1 fill=#fa0 /><rect y=2 fill=#ff0 /><rect y=3 fill=#4f0 /><rect y=4 fill=blue /><rect y=5 fill=#808><style>rect{width:8px;height:1px
```
After zooming in a lot, you can see
[](https://i.stack.imgur.com/yfm9E.png)
[Answer]
# C, 69 bytes
I don't have comment privileges yet, so I'm adding this as another answer. This is an improvement on @weirdsmiley's [answer](https://codegolf.stackexchange.com/a/230635/103498).
```
#define p(s)puts("\e["#s"m█");
main(){p(91)p(31)p(93)p(32)p(34)p(35)}
```
[Try it on godbolt](https://godbolt.org/z/Tj1bbvece)
I added the the `\e[` and `m` to the `p` macro because it was used 6 times in each macro invocation. Also the `\e[0m` (which resets the color) can be removed because the color is overwritten again before each `puts`.
If there was a way to make the `91` and `93` start with a `3`, then it might save a few bytes by being able to remove the `3` from the 30s.
I'm new to codegolf, so I'm sure if this is 69 or more bytes (because of the `█` character).
[Answer]
# Python 3 with `pygame`, 166 152 bytes
I wrote this before realizing there was another pygame answer here, but I'm still posting it because I wrote it independently, and it does use a rather different method for getting the colors.
```
from pygame import*
d=display
s=d.set_mode()
for i in range(6):
draw.rect(s,("red","orange","yellow","green","blue","purple")[i],(0,i*3,32,3))
d.flip()
```
Edit -14 bytes: Some golfing I did on [another pygame answer I just posted](https://codegolf.stackexchange.com/a/245337/111305) helped me golf this one too.
New output:
[](https://i.stack.imgur.com/pJDQx.png)
As the size makes this almost illegible, here's a scaled up version (from the older code, hence the window bar at the top) for better viewing:
[](https://i.stack.imgur.com/WebAb.png)
[Answer]
# [Desmos](https://desmos.com/calculator), 75 bytes
```
k=255
C=rgb([k,k,k,0,0,75],[0,165,k,k,0,0],[0,0,0,0,k,k])
[5...0]<y<[6...1]
```
Result:
[](https://i.stack.imgur.com/oU2yp.png)
Technically, each colored bar has the same area of infinity, but if that's not allowed, then you can simply add a domain restriction at the end of the inequality with the cost of some additional bytes.
[Try It On Desmos!](https://www.desmos.com/calculator/wzrjggyt5s)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/egir8k9sqz)
There must be some way to golf that huge `rgb()` expression, but I don't see a way at the moment...
---
## Bonus Answer, 5 bytes
```
pride
```
If you paste `pride` into an empty expression, Desmos will automatically redirect you to a graph of the pride flag.
You have a chance of getting this graph:
[](https://i.stack.imgur.com/kPRnK.png)
Or this graph:
[](https://i.stack.imgur.com/vXTYY.png)
[Answer]
# Nim, 862 274 246 bytes
```
var
y=33.0
m=newImage(297,198)
c=newContext(m)
r=y/2
for i in 0..5:c.strokeStyle="#FF5C00#FF8C00#FFE900#006400#00008B#4B0082"[i*7..i*7+6];c.lineWidth=y;c.strokeSegment(segment(vec2(0,r),vec2(y*9,r)));r+=y;m.writeFile("l.png")
```
Using the Nim library pixie. If you have Nim and Nimble installed, a quick `nimble install pixie` should let you run it perfectly! It outputs to l.png. I am inexperienced with Pixie and Nim, so if I did anything wrong, please let me know. This answer has gone through a lot of revisions, from totally un-golfy to fairly golfed. Bytes were counted using `wc -c`.
[](https://i.stack.imgur.com/OFLkq.png)
[Answer]
# TikZ, 164 bytes
```
\documentclass[tikz]{standalone}\begin{document}\tikz{\foreach\u\c in{1/purple,2/blue,3/green,4/yellow,5/orange,6/red}{\fill[\c](,\u)rectangle(9,7);}}\end{document}
```
Pretty simple.
```
\documentclass[tikz]{standalone}\begin{document}\tikz{ % boilerplate
% For every color and index ascending from the bottom.
\foreach\u\c in{1/purple,2/blue,3/green,4/yellow,5/orange,6/red}{
% Draw a filled rectangle in that color from (0,u) to the upper right corner
\fill[\c](,\u)rectangle(9,7);
}
}\end{document} %boilerplate
```
[](https://i.stack.imgur.com/EdDii.png)
[Answer]
# Python 3 + Turtle, 183 bytes
```
from turtle import*
for x in "red orange yellow green blue violet".split():fillcolor(x);begin_fill();exec("fd(200);lt(90);fd(20);lt(90);"*2);end_fill();rt(90);fd(20);lt(90)
mainloop()
```
[](https://i.stack.imgur.com/JH6Zo.png)
The turtle pointer by default starts at cartesian coordinates (0,0) so the image is in the 4th quadrant.
[Answer]
# [K (oK) + `iKe`](https://github.com/JohnEarnest/ok), 79 bytes
```
w:300
h:200
{(0,x*34;,("red";"#fa0";"#ff0";"#0f0";"#00f";"#808")x;(34;w)#0)}'!6
```
[Try it online!](https://johnearnest.github.io/ok/ike/ike.html?key=CPMZdZ5W)
Draws a static bitmap with 300x200px area.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/mathematica/), ~~142~~ 139 bytes
```
BarChart[1~Table~6,BarOrigin->Left,ChartStyle->{Purple,Blue,Green,Yellow,Orange,Red},BarSpacing->0,Axes->0>1,ChartBaseStyle->EdgeForm@None]
```
`ChartBaseStyle->EdgeForm@None` removes the faint black lines that would normally separate each bar.
-3 bytes thanks to att.
[](https://i.stack.imgur.com/gcOlW.png)
[Answer]
# [Python 3](https://docs.python.org/3/), ~~108~~ ~~89~~ ~~85~~ 80 bytes
```
print("P3 300 204 9")
for x in range(6):print(*"900960990070009707"[x::6]*10200)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EQynAWMHYwEDByMBEwVJJkystv0ihQiEzT6EoMS89VcNM0wqiTkvJ0sDA0szAEkiZGwCZ5gbmStEVVlZmsVqGBkYGBpr//wMA "Python 3 – Try It Online")
*Huge change (-22 chars) thanks to ovs, and -5 more from Wheat Wizard!*
The output is an ASCII PPM image file, which is easy to generate but incredibly inefficient space-wise. So even at 300x204 pixels it's too larger for TIO, so it's truncated if you run the code there.
Here's an explanation.
```
print("P3 300 204 9") # Print the PPM header (1)
for x in range(6): ... # For each distinct color
... print(*"900960990070009707"[x::6]*10200) # Print 10200 copies of the RGB value (2)
```
(1) - `P3` means it's an RGB image, `300 204` are the dimensions and the last number if the max RGB value `9` in this case so that we can use single digit values.
(2) - The RGB values are single byte since the color depth in the header is given as `9`. The string `900960990070009707` holds the 3 digit RGB values for each of the 6 rows.
The image uploader won't accept a PPM file so I loaded it into GIMP and exported it as a PNG to include it.
[](https://i.stack.imgur.com/mLFCU.png)
[Answer]
# JavaScript - 165 bytes
The snippet works in the console.
```
console.log(...["red","orange","#ff0","green","#00f","violet"].reduce((a,c)=>{a[0]=a[0]+'%c0';return [...a,`background:${c};color:${c};padding:35px 400px;`];},['']))
```
[](https://i.stack.imgur.com/ruXch.png)
### EDIT:
Used Chrome Version 91.0.4472.114 (Official Build) (x86\_64) for creating the image.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~91~~ 57 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
The latest entry in my series of making Japt do things it shouldn't be able to do!
```
Ol"%c "²³$,...$`fÇÛÆèÆÇ¾b`roT ò3 Ëi`padÜA:2%26%;baå®":#
```
[Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=JGNvbnNvbGUuY2xlYXIoJA&code=T2wiJWMgIrKzJCwuLi4kYGbH28boxsePvmJgcm9UIPIzIMtpYHBhZNxBOjIlMjYlO2Jh5a4iEDoj) (Open your browser's console. Only tested in Chrome.)
## Original solution
```
$flags$
`fÇÛÆèÆÇ¾b`roT ò3 £$V.before(V.cloneNode(),V.style.border=V.style.background='#'+X
```
[Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=JGZsYWdzLnBhcmVudE5vZGUuY2xhc3NMaXN0LnJlbW92ZSgiY29sbGFwc2VkIikk&code=JGZsYWdzJApgZsfbxujGx4%2b%2bYmByb1Qg8jMgoyRWLmJlZm9yZShWLmNsb25lTm9kZSgpLFYuc3R5bGUuYm9yZGVyPVYuc3R5bGUuYmFja2dyb3VuZD0nIycrWA)
[Answer]
# Swift + UIKit, 216 bytes
A function that returns a `UIView`.
```
func f()->UIView{let v=UIStackView(arrangedSubviews:[UIColor]([.red,.orange,.yellow,.green,.blue,.purple]).map{let v=UIView()
v.backgroundColor=$0
return v})
v.axis = .vertical
v.distribution = .fillEqually
return v}
```
You can't remove the whitespace around the last two `=` operators.
Result when displayed at full screen on iPhone Xʀ:

# Swift + SwiftUI, 90 bytes
A `View`. Not a function that returns one -- you could say `let prideFlag = /* the answer */`, or include the answer directly in a ViewBuilder.
```
VStack(spacing:0){Color.red
Color.orange
Color.yellow
Color.green
Color.blue
Color.purple}
```
*This is why everyone prefers SwiftUI.*
The colors are slightly different, and it doesn't let itself extend into the margins at the top/bottom of the screen, but the result is very similar:

[Answer]
# Pygame, 171 bytes
```
from pygame import*
d=display
e=99
s=d.set_mode((e*9,e*6))
m=[255]
l=[0]
i=0
for c in[m+l*2,m+[e]+l,m*2+l,l+m+l,l+l+m,[e,0,e]]:draw.rect(s,c,(0,i*e,e*9,e));i+=1
d.update()
```
Here's the flag generated:
[](https://i.stack.imgur.com/M37h3.png)
[Answer]
# C, ~~171 bytes~~ ~~118 bytes~~ 100 bytes
EDIT: Saved 53 bytes thanks to [Wheat Wizard](https://codegolf.stackexchange.com/users/56656/wheat-wizard) and 14 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)
```
#define p(s) printf(#s"█\e[0m\n");
main(){p(\e[91m)p(\e[31m)p(\e[93m)p(\e[32m)p(\e[34m)p(\e[35m)}
```
Try on [godbolt](https://godbolt.org/z/PnGbGzcrx)!
NOTE: Output differs a little according to Godbolt's UI.
Here is the output from my native machine.
[](https://i.stack.imgur.com/JzRw4.png)
[Answer]
# R + ggplot2,150 bytes - <https://cran.r-project.org/web/packages/ggplot2/index.html>
```
library(ggplot2);ggplot(data.frame(y=1:6),aes(y=y))+theme_void()+geom_bar(fill=c("#9400D3","#0000FF","#006400","#FFFF00","#FFA500","#FF0000"),width=1)
```
the output image
[](https://i.stack.imgur.com/h2m50.png)
[Answer]
# JavaScript, 107 bytes
```
console.log(`%c `.repeat(6),...`f00fa0ff00f000fb0b`.match(/.../g).map(c=>`background:#${c};padding:2%26%`))
```
Open your browser's console and run the snippet below.
```
console.clear()
console.log(`%c `.repeat(6),...`f00fa0ff00f000fb0b`.match(/.../g).map(c=>`background:#${c};padding:2%26%`))
```
[Answer]
# [Big Unicorn](https://www.theedkins.co.uk/jo/games/unicorn/bigunicorn/index.htm), 54 bytes
```
C1P9T1P2T1C7P9T3P2C2T3P9T1P2T1C9P9T3P2T3C3P9T1P2T1C8P9
```
Unicorns sure do love rainbows...
[](https://i.stack.imgur.com/lunGn.jpg)
[Answer]
# [`dc`](https://en.wikipedia.org/wiki/Dc_(computer_program) "Wikipedia") + [QOI](https://qoiformat.org/), 116 bytes
```
16i[qoif]P0dPP1P32P0ddPPPCCP3P0P5AP[A7[FDP1-d0<R]dsRxF0Pk]ddddddxFEPFFP80P0PxFEPFFdPP0Px7APx6DPx5APx0ddddddPPPPPPP1P
```
Outputs a 306x204 image to stdout in the [Quite OK Image Format](https://qoiformat.org) (shown here converted to png):
[](https://i.stack.imgur.com/7pNPr.png)
QOI images can be viewed with ImageMagick, among other software:
```
dc -e"16i[qoif]P0dPP1P32P0ddPPPCCP3P0P5AP[A7[FDP1-d0<R]dsRxF0Pk]ddddddxFEPFFP80P0PxFEPFFdPP0Px7APx6DPx5APx0ddddddPPPPPPP1P" | magick display
```
[Answer]
# [Uiua](https://www.uiua.org/), 52 bytes
```
⍉⍉↯400⍉⬚50▽[]÷4[4_0_0 4_2_0 4_4_0 0_4_0 0_0_4 3_0_4]
```
[Try it online!](https://www.uiua.org/pad?src=4o2J4o2J4oavNDAw4o2J4qyaNTDilr1bXcO3NFs0XzBfMCA0XzJfMCA0XzRfMCAwXzRfMCAwXzBfNCAzXzBfNF0=)
```
÷4[4_0_0 4_2_0 4_4_0 0_4_0 0_0_4 3_0_4] # Set up the colours
(RGB values between 0 and 1)
⬚50▽[] # Make an array of 50 of each RGB value
⍉ # Transpose the array
↯400 # Repeat each element 400 times
⍉⍉ # Transpose to the correct format
(300x400x3)
```
[](https://i.stack.imgur.com/wsQOZ.png)
A couple of bytes can be saved by making the image 40px by 30px. This can be done by removing a zero from each of "400" and "50" in the code above.
However, the result is not great:
[](https://i.stack.imgur.com/NsGDc.png)
[Answer]
# HTML, ~~330~~ 245 bytes
Saved 7 bytes thanks to Wheat Wizard!
Saved 78 bytes thanks to Recursive Co.!
```
<div style="background:red"> </div><div style="background:#F60"> </div><div style="background:#CF0"> </div><div style="background:#0F0"> </div><div style="background:blue"> </div><div style="background:#C0F"> </div>
```
[Answer]
# [ConTeXt](https://wiki.contextgarden.net/Main_Page), 112 bytes
It produces PDF, hence scalable, output:
```
\startMPpage for i=0upto5:draw(0,-i)--(5,-i)withcolor hsvtorgb(i*(25+6i),1,1)withpen pensquare;endfor\stopMPpage
```
[](https://i.stack.imgur.com/YbKCQ.png)
[Answer]
# HTML & CSS — 207 bytes
[](https://i.stack.imgur.com/TigNq.png)
```
hr{height:30px;margin:0;border:0}hr{background:red}*+hr{background:orange}*+*+hr{background:yellow}*+*+*+hr{background:green}*+*+*+*+hr{background:blue}*+*+*+*+*+hr{background:violet}
```
```
<hr><hr><hr><hr><hr><hr>
```
[Answer]
# [R](https://www.r-project.org/), ~~80~~ ~~65~~ 45 bytes
```
image(t(1:6),c=rainbow(12)[c(10,8,4:1)],ax=F)
```
[Try it at rdrr.io!](https://rdrr.io/snippets/embed/?code=image(t(1%3A6)%2Cc%3Drainbow(12)%5Bc(10%2C8%2C4%3A1)%5D%2Cax%3DF))
**Original 80-byte version**
```
plot(0,,,1:2,c(1,7),,,,"","",,F);rect(1,7:2,2,6:1,,,rainbow(12)[c(1:4,8,10)],NA)
```
[Try it at rdrr.io!](https://rdrr.io/snippets/embed/?code=plot(0%2C%2C%2C1%3A2%2Cc(1%2C7)%2C%2C%2C%2C%22%22%2C%22%22%2C%2CF)%3Brect(1%2C7%3A2%2C2%2C6%3A1%2C%2C%2Crainbow(12)%5Bc(1%3A4%2C8%2C10)%5D%2CNA)%0A)
[](https://i.stack.imgur.com/wp6Gx.png)
[Answer]
# [Scratch](https://scratch.mit.edu), 289 bytes
```
when gf clicked
add(16753920)to[l v
add(16776960)to[l v
add(65280)to[l v
add(255)to[l v
add(8388736) to [l v
set pen color to(()+(16711680
set pen size to(800
pen down
repeat(5
change[a v] by (1
go to x:(-240)y:((150)-((60)*(a
set pen size to(60
set pen color to(item(a)of[l v
set x to(240
```

[Try it online!](https://scratch.mit.edu/projects/710926486/) | [Test it on Scratchblocks!](http://scratchblocks.github.io/#?style=scratch3&script=when%20gf%20clicked%0Aadd(16753920)to%5Bl%20v%0Aadd(16776960)to%5Bl%20v%0Aadd(65280)to%5Bl%20v%0Aadd(255)to%5Bl%20v%0Aadd(8388736)%20to%20%5Bl%20v%0Aset%20pen%20color%20to(()%2B(16711680%0Aset%20pen%20size%20to(800%0Apen%20down%0Arepeat(5%0Achange%5Ba%20v%5D%20by%20(1%0Ago%20to%20x%3A(-240)y%3A((150)-((60)*(a%0Aset%20pen%20size%20to(60%0Aset%20pen%20color%20to(item(a)of%5Bl%20v%0Aset%20x%20to(240)
] |
[Question]
[
I'd like you to build me a clock that displays time in this format:
```
18 ----------
19 --------------------------------------------------
```
This displays '18:10'. The current hour and the next hour are shown at the front of the line, followed by a space and a number of dashes: on the first line the number of minutes that have passed in this hour, and the second line shows how many more minutes to go in this hour.
# To clarify
* The clock should display the system's time. If fetching the time from another source is more convenient, that's fine too. It *may not* be supplied as input.
* At `18:00`, the top line is just `18` (Trailing spaces allowed but not required)
* At `18:59`, the bottom line is `19 -`
* The hours < 10 are either pre-padded with a `0` (`01 -----`) or right-aligned ( `1 -----`). A left-aligned single digit is not allowed, not even if the dashes start at the right place (`1 -----` is invalid).
* The clock should display the hours in a 24h-format.
* Although it's called the 24h format, there is not actually a `24` on it. During the 23rd hour, the second line starts with `00` or `0`.
* The display needs to be updated at least once a minute, but that doesn't have to happen at exactly `00` seconds. You may update more frequently / continuously if that is more convenient, but the result must of course still be legible - not one smear all over the screen.
# Input
None.
# Output
* As described above. Trailing spaces to pad the clock to 60-ish positions is allowed on both lines, a trailing newline is also allowed.
* The screen needs to be cleared when displaying the next minute: either with a clear-screen command or by adding no less than 30 newlines.
# Additional rules
* [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden
* [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest answer in bytes wins.
[Answer]
# TI-Basic, 94 bytes
```
"
Repeat 99<length(Ans
Ans+"-
End
Ans→Str1
Repeat 0
getTime
ClrDraw
Ans{Ans(1)≠24,1,1
Text(0,0,Ans(1),sub(Str1,1,1+Ans(2
Text(6,0,Ans(1)+1,sub(Str1,1,61-Ans(2
End
```
Relatively straightforward. That's a string with one space at the beginning. The hours are right-aligned. This only works on TI-84+ calculators since the TI-83 does not have an internal clock.
Edit: Thanks @kundor for noticing that I didn't close the last loop. Fixed now (+2 bytes).
Edit #2: First hour should be zero, not twenty-four. Corrected at a cost of +14 bytes.
[Answer]
## Batch, 197 bytes
```
@echo off
set/ah=100+%time:~0,2%,m=1%time:~3,2%
cls
call:l
set/ah=(h-3)%%24+100,m=260-m
call:l
timeout/t>nul 60
%0
:l
set s=%h:~1%
for /l %%i in (101,1,%m%)do call set s=%%s%%-
echo %s%
```
Note: 10th line has a trailing space. For me, `%time%` formats hours with a leading space but minutes with a leading zero. I decided a leading zero was an easier output format, since all I have to do for that is to add 100 hours and remove the first digit. Minutes are trickier as `08` or `09` will cause octal parse errors, so I prefix a `1` effectively adding 100 minutes, adjusting for this by offsetting the loop appropriately, which is a byte shorter than subtracting the 100.
[Answer]
## Python 3.6, ~~110~~ ~~114~~ 112 bytes
```
from time import*
while[sleep(9)]:h,m=localtime()[3:5];print('\n'*50+'%2d '%h+'-'*m+f'\n{-~h%24:2} '+'-'*(60-m))
```
This uses the new f-string formatting to save one byte (`f'\n{h+1:2} '` vs `'\n%2d '%(h+1)`.) You can change `[sleep(9)]` to `1` to save 8 bytes, but then it just spams the screen.
Saved one byte changing `while 1:...;sleep 60` to `while[sleep(60)]:...`, thanks to TuukkaX.
I had to use 5 more bytes to get the next hour displayed after 23 to be 0, instead of 24, as OP just commented. :-(
Recovered one byte by only sleeping 9 seconds instead of 60.
Saved two bytes using a bit-fiddling to shorten `(h+1)%24`, borrowed from [Value Ink's Ruby answer](https://codegolf.stackexchange.com/a/107148/18314).
[Answer]
# Ruby, ~~98~~ ~~95~~ 91 bytes
Updates every 5 seconds. Only works in Unix-style terminals.
```
loop{t=Time.now;puts`clear`+"%02d %s
%02d "%[h=t.hour,?-*m=t.min,-~h%24]+?-*(60-m);sleep 5}
```
Windows command prompt version, ~~95~~ 92 bytes:
```
loop{t=Time.now;puts"\e[H\e[2J%02d %s
%02d "%[h=t.hour,?-*m=t.min,-~h%24]+?-*(60-m);sleep 5}
```
[Answer]
# [Perl 6](https://perl6.org), 113 bytes
```
loop {$_=DateTime.now;.put for |('' xx 30),|([\+](.hour,1)».fmt('%2s')Z('-' Xx[\-](.minute,60)».abs));sleep 60}
```
[Try it once](https://tio.run/nexus/perl6#FcrLCoJAFADQX7lQMTOkgxW4SNr1AS1aRBphccWBecg8aEL9snb9mNnmrM7JGiUccqHphnHfot5Dj1H4ERYg0YPwYIMGo@V75omTNKaDfnk/HGuPZ6GQa/MqeBc8NMbCQAmBGGGXsWSgZbW@Ud6aYJMN@354ozwlq60j7EpJSuASyyqdhxI6eEzy7J/qh2OscBKxgzwbp@kH "Perl 6 – TIO Nexus") with a one second timeout.
[Or try an altered version](https://tio.run/nexus/perl6#hZDBSsQwEIbvfYofdiUJdktXYQ8uvfkIHsRdWdLt1BabpDSpLbg@mTdfrKYtgrKKA7n8M/PN/2dYHpDgVjq6KxVF2nRbfKsF0obkM0oH0/qXwxWEypga1qAjHKX2TWo8IAgm/TUIxr3lIfmDusDRKEXaUTZBPcgV0o03RtqxkPqJkJLriL7gpdF25Ea1X8hNgxNnDH2P61iEJ77bXz7yqDBtE67Fx3uUK8fZxZVl4oGzFcN9v9uv/IQqdeso3MTjkEytENvZra2IamxinNU/br00WlKmIbzIqqXJpv/UKEHl8zccN/NVvhYQE1BmGSRm9QdvSm5/jf42DJ8 "Perl 6 – TIO Nexus") that outputs the result of running for several hours.
## Expanded:
```
loop { # keep repeating forever
$_ = DateTime.now; # assign an object representing the current time
.put # print with trailing newline
# ( adds a space between numbers and dashes )
for # for each of the following
|( # make it a slip so that it is all part of one list
'' xx 30 # 30 empty strings (30 empty lines)
),
|(
[\+]( # triangle produce
.hour, # the hour
1 # the hour plus one
)».fmt( '%2s' ) # both formatted to two element string ( space padded )
Z # zipped with
(
'-' # a dash
Xx # cross (X) using string repeat (x) operator
[\-]( # triangle produce
.minute, # the minute
60 # the minute minus 60
)».abs # absolute value of both
)
);
sleep 60 # wait until the next minute
}
```
[Answer]
# QBasic, ~~120~~ ~~127~~ 121 bytes
~~Don't run this for very long or your laptop will catch fire.~~ Now 99.several9s% more CPU-efficient.
```
CLS
m=TIMER\60
h=m\60
m=m MOD 60
FOR i=1TO 2
?USING"## ";h MOD 24;
FOR j=1TO m
?"-";
NEXT
?
h=h+1
m=60-m
NEXT
SLEEP 1
RUN
```
### Ungolfed and explanation
```
DO
CLS
totalMinutes = TIMER \ 60
hour = totalMinutes \ 60
minute = totalMinutes MOD 60
FOR row = 1 TO 2
PRINT USING "## "; hour MOD 24;
FOR j = 1 TO minute
PRINT "-";
NEXT j
PRINT
hour = hour + 1
minute = 60 - minute
NEXT row
SLEEP 1
LOOP
```
We start by clearing the screen, then get the current hours and minutes from `TIMER`, which returns the number of seconds since midnight.
This is the first time I've tried `PRINT USING`, so I was delighted to discover that it doesn't suffer from the usual QBasic quirk that positive numbers are printed with a leading space. `##` as the format specifier ensures that single-digit numbers are right-aligned and padded with a space, as required. We have to use a loop for the hyphens, unfortunately, since QBasic does not have a string repetition function. (If I'm mistaken, please let me know!)
All the `PRINT` statements end with `;` to suppress the newline; but after the hyphens, we need a newline; thus, the solitary `?` after the inner `FOR` loop.
The `SLEEP 1` is now necessary. Without it, the screen gets cleared so quickly after printing that it's just a flickering mess. (I used `LOCATE 1` instead of `CLS` at first for that reason, until I realized that `CLS` with `SLEEP` is shorter anyway.) `RUN` restarts the program from the top--the shortest way to get an infinite loop.
[Answer]
## Java 8, 313 300 299 bytes
```
import java.time.*;()->{for(int c=0,h=LocalDateTime.now().getHour(),m=LocalDateTime.now().getMinute(),i;;)if(c>30){c=0;String l="",u,d;for(i=0;i++<60;)l+="-";u=l.substring(0,m);d=l.substring(m);System.out.println((h<10?"0":"")+h+" "+u+"\n"+(h<9?"0":"")+(h+1)+" "+d);}else{c++;System.out.println();}}
```
This only updates every 30 iterations of the while loop. The other 29 iterations just print new lines.
**Updated**
Saved 13 14 bytes due to Kevin Cruijssen's help! Thanks!
[Answer]
## C, ~~176~~ ~~162~~ ~~161~~ ~~160~~ 156 bytes
This is a **gross** abuse of pointers but compiles and runs as specified. Be sure to compile without optimization otherwise you are likely to hit a segfault.
```
main(){int*localtime(),b[9],*t;memset(b,45,60);for(;;)time(&t),t=localtime(&t),usleep(printf("\e[2J%.2d %.*s\n%.2d %.*s\n",t[2],t[1],b,t[2]+1,60-t[1],b));}
```
### Ungolfed:
```
#import<time.h>
main()
{
int *t,b[60];
memset(b,45,60);
for(;;) {
time(&t);
t=localtime(&t);
usleep(printf("\e[2J%.2d %.*s\n%.2d %.*s\n",t[2],t[1],b,t[2]+1,60-t[1],b));
}
}
```
[Answer]
# JavaScript (ES6), 162 bytes
Updates once per second
```
setInterval(c=>{c.clear(d=new Date,m=d.getMinutes(),h=d.getHours(),H=_=>`0${h++}`.slice(-2)),c.log(H()+` ${'-'.repeat(m)}
${H()} `+'-'.repeat(60-m))},1e3,console)
```
[Answer]
## Python 2, ~~131~~ ~~129~~ 127 bytes
```
from time import*
while[sleep(9)]:exec(strftime("a='%H';b=int('%M')"));print "\n"*30+a+" "+"-"*b+"\n"+`int(a)+1`+" "+"-"*(60-b)
```
saved a byte thanks to @TuukkaX
[Answer]
## C ~~251~~ ~~267~~ 251 bytes
```
#include<time.h>f(){time_t t;struct tm *t1;h,m,i;while(1){time(&t);t1=localtime(&t);h=t1->tm_hour;m=t1->tm_min;printf("%d ",h);for(i=1;i<=m;i++)printf("-");puts("");printf("%d ",h+1);for(i=0;i<=59-m;i++)printf("-");puts("");sleep(1);system("clear");}}
```
Ungolfed version
```
#include<time.h>
void f()
{
time_t t;
struct tm *t1;
int h,m,i;
while(1)
{
time(&t);
t1=localtime(&t);
h=t1->tm_hour;
m=t1->tm_min;
printf("%d ",h);
for(i=1;i<=m;i++)
printf("-");
puts("");
printf("%d ",h+1);
for(i=0;i<=59-m;i++)
printf("-");
puts("");
sleep(1);
system("clear");
}
}
```
Gets the work done! Can definitely be shortened in some way.
Assume `unistd.h` file is included.
@Neil Thanks for the info.
@Seth Thanks, for saving 8 bytes.
[Answer]
First time golfing...
# Powershell, 116 bytes (was 122)
```
while($d=date){$f="{0:D2}";$h=$d.Hour;$m=$d.Minute;cls;"$($f-f$h)$("-"*$m)`n$($f-f(++$h%24))$("-"*(60-$m))";Sleep 9}
```
Edit: From @AdmBorkBork's advice, changed Get-Date to date, and Clear to cls, for a saving of 6 bytes.
[Answer]
# PHP, ~~104~~ 105 bytes
```
<? for(;;sleep(6))printf("%'
99s%2d %'-".($m=date(i))."s
%2d %'-".(60-$m).s,"",$h=date(H),"",++$h%24,"");
```
showcase for `printf`´s custom padding characters:
`"%'-Ns"`=left pad string with `-` to `N` characters.
will print 99 newlines (every 6 seconds) instead of clearing the screen.
First newline must be a single character. So, on Windows, it must be replaced with `\n`.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 41 bytes
*Thanks to @Kundor for noticing a mistake, now corrected*
```
`XxFT"4&Z'@+24\OH&YAO'-'60@*5&Z'-|Y"hhD]T
```
Try it at [MATL online!](https://matl.io/?code=%60XxFT%224%26Z%27%40%2B24%5COH%26YAO%27-%2760%40%2a5%26Z%27-%7CY%22hhD%5DT&inputs=&version=19.7.1) But note that the program is killed after 30 seconds, so it's difficult to catch any changes in the output.
### How it works
```
` % Do...while
Xx % Clear screen
FT % Push [0 1]
" % For each k in [0 1]
4&Z' % Push current hour
@+ % Add k
24\ % Modulo 24. This transforms 24 into 0
OH&YA % Convert to base-10 string with 2 digits
O % Push 0. Concatenating with chars will convert this to char,
% and char(0) will be displayed as a space
'-' % Push '-'
60@* % Push 60*k
5&Z' % Push current minute
-| % Absolute difference. This gives current minute for k==0,
% or 60 minus that for k==1
Y" % Repeat '-' that many times
hh % Concatenate the top three elements into a string
D % Display
] % End
T % Push true
% End (implicit). Since the top of the stack contains true, this
% gives an infinite loop
```
[Answer]
# GameMaker Language, 134 bytes
```
s=" "while 1{s+="-"a=current_hour b=current_minute draw_text(0,0,string(a)+string_copy(s,1,b+1)+"#"+string(a+1)+string_copy(s,0,61-b)}
```
In the settings, you must be ignoring non-fatal errors in order for this to work. Also, in GML, `#` is equivalent to `\n` in most languages.
[Answer]
## AWK, 190 bytes
```
#!/bin/awk -f
func p(x,y,c){printf("%2s ",x)
for(j=0;j<y;j++)printf(c)
print}BEGIN{for(;;){split(strftime("%H %M"),t)
m=t[2]
if(o!=m){p(a,30,"\n")
p(t[1],m,"-")
p((t[1]+1)%24,60-m,"-")}o=m}}
```
Since `AWK` doesn't have a built-in `sleep` function, I simply have it continually check the clock to see if the minute has changed yet. The key thing is that it works... right? :)
[Answer]
## Python 3.5, ~~127~~ 120 ~~117~~ bytes
```
from time import*
while[sleep(9)]:h,m=localtime()[3:5];print('\n'*88,*['%2d '%x+'-'*y+'\n'for x,y in[(h,m),(h+1,60-m)]])
```
[Answer]
# Python, ~~115~~ 113 bytes
saved a couple of bytes thanks to @kundor and @Phlarx
```
import time
while 1:h,m=time.localtime()[3:5];print("\x1b[0;H{:02} {}\n{:02} {} ".format(h,"-"*m,h+1,"-"*(60-m)))
```
[Answer]
## C# *Interactive* (138 Bytes)
```
while(true){var d=DateTime.Now;Console.WriteLine($"{d.Hour:00} {new string('-',d.Minute)}\n{d.Hour+1:00} {new string('-',60-d.Minute)}");}
```
[Answer]
# PHP, ~~112~~ 120 bytes
```
for(;;sleep(9))echo($s=str_pad)($h=date(H),99,"\n",0).$s(" ",1+$m=date(i),"-")."\n".$s(++$h%24,2,0,0).$s(" ",61-$m,"-");
```
As there's no way to clear the screen (that I can find) I had to go with a pile of newlines. Also the question being updated to "at least" once a minute saves a byte with `9` instead of `60`.
edit: @Titus noticed a bug in the padding of the second hour. Fixing it cost 8 bytes.
[Answer]
# Bash (3 and 4): 90 bytes
```
d=(`sed s/./-/g<$0`);let `date +h=%H,m=%M`;echo $h ${d:0:m}'
'$[++h%24] ${d:m}
sleep 5
$0
```
Due to the use of `$0`, this script must be put into a file, not pasted into an interactive bash shell.
The first command sets `$d` to 60 hyphens; it relies on the fact that the first line of this script is 60 characters long. This is three characters shorter than the next best thing I could come up with:
```
d=`printf %060d|tr 0 -`
```
If you don't want this to run your box out of PIDs or memory eventually, you can add `eval` to the beginning of the last line, which would make this 95 bytes.
[Answer]
# BASH, 165 141 155 bytes
```
while :
do
clear
m=`date +%-M`
a=`printf %${m}s`
b=`printf %$((60-m))s`
h=`date +%H`
echo $h ${a// /-}
printf "%02d %s" $((10#$h+1)) ${b// /-}
sleep 9
done
```
[Answer]
# [Raku](https://raku.org/) (aka Perl 6), 104 bytes
```
DateTime.now.&{"\ec{.hour.fmt: '%2s'} {'-'x.minute}\n{(.hour+1).fmt: '%2s'} {'-'x 60-.minute}"}.say xx*
```
Needs to be run on a [ANSI compatible terminal](https://graphcomp.com/info/specs/ansi_col.html) so that the control sequence for resetting the terminal works.
Pretty basic (because the more obfuscated approaches I tried turned out longer):
* `DateTime.now.&{" "}.say xx*`: Transform the current time into a string (see below) and say it, and repeat all of that an infinite number of times. The string is built like this:
* `\ec`: ANSI control code `<ESC>c` for resetting the terminal, which clears the screen.
* `{.hour.fmt: '%2s'}`: hour, right-aligned to 2 columns
* : space
* `{'-'x.minute}`: dash repeated times the minute
* `\n`: newline
* `{(.hour+1).fmt: '%2s'}`: next hour, right-aligned to 2 columns
* : space
* `{'-'x 60-.minute}`: dash repeated times 60 minus the minute
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), 154 bytes
```
S+N:-get_time(A),format_time(atom(O),S,A),atom_number(O,N).
:-repeat,"%H"+H,"%M"+M,format("~t~d~2+ ~|~45t~*+
~|~t~d~2+ ~|~45t~*+
",[H,H,M,M]),\+sleep(60).
```
[Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/P1jbz0o3PbUkviQzN1XDUVMnLb8oNxHKTSzJz9Xw19QJ1gFKgDjxeaW5SalFGv46fpp6XFa6RakFqYklOkqqHkraHkDKV0nbF2qChlJdSV1KnZG2Ql1NnYlpSZ2WNheQhSGmpBPtoeOh46vjG6upE6NdnJOaWqBhZqCp9/8/AA "Prolog (SWI) – Try It Online")
Welp, what a mess.
[Answer]
# [Gura](https://github.com/gura-lang/gura), 138 bytes
```
k(a,b)={if(a<10){a="0"+a;}println(a," ","-"*b)};repeat{t=datetime.now();k(t.hour,t.min);k(t.hour+1,60-t.min);os.sleep(60);print("\n"*30);}
```
Pretty short and straightforward :)
[Answer]
Ok, haven't done a code golf in a while, so here goes my sad attempt :)
# Unix Korn Shell: ~~177~~ ~~171~~ 170 bytes
```
while :
do
clear
h=`date +%H`
m=`date +%M`
d=-----
d=$d$d$d$d
d=$d$d$d
a=`echo $d|cut -b-$m`
let m=60-$m
b=`echo $d|cut -b-$m`
let i=h+1
echo "$h $a\n$i $b"
sleep 9
done
```
[Answer]
# Mathematica, 235 bytes
```
d=UpdateInterval;e=Dynamic;f=Refresh;g=AbsoluteTime;Grid[Partition[Riffle[e[f[Floor@Mod[g[]/3600+#,24],d->1]]&/@{0,1},With[{t=#},e[f[""<>Array["-"&,If[t==60,60-#,#]]&@Setting@Floor@Mod[g[]/60+#,60],d->1]]]&/@{0,60}],2],Alignment->Left]
```
[Answer]
# Processing, ~~204~~ ~~200~~ ~~198~~ 197 bytes
*5 bytes saved thanks to @L. Serné by using smarter ternaries*
```
void draw(){int i;String s=((i=hour())>9?i:" "+i)+" ";for(i=0;i<minute();i++)s+="-";s+="\n"+((i=hour()+1)>9?i>23?" 0":i:" "+i)+" ";for(i=0;i<60-minute();i++)s+="-";print(s);for(;i++<99;)println();}
```
This outputs 30+ newlines for each update (which takes place when the frame gets updated)
### Ungolfed
```
void draw(){
int i;
String s=((i=hour())>9?i:" "+i)+" ";
for(i=0;i<minute();i++)
s+="-";
s+="\n"+((i=hour()+1)>9?i>23?" 0":i:" "+i)+" ";
for(i=0;i<60-minute();i++)
s+="-";print(s);
for(;i++<99;)
println();
}
```
[Answer]
# C, 239 bytes
```
#include<time.h>
#include<unistd.h>
#define F printf(
void d(n,p){for(;n--;F"%c",p));}int main(){time_t*t;for(;;){d(30,10);time(t);int*m=localtime(t);F"%2d ",m[2]);d(m[1],45);F"\n%2d ",(m[2]+1)%24);d(60-m[1],45);F"\n");sleep(1);}return 0;}
```
Inspired by Seth's and Abel's entries, this will output 0 instead of 24 for the next hour, as required, and will use 30 lines to clear the screen.
[Answer]
# SmileBASIC, 55 bytes
```
TMREAD OUT H,M,
CLS?H,"-"*M?(H+1)MOD 24,"-"*(60-M)EXEC.
```
Explanation:
```
TMREAD OUT HOUR,MINUTE,
CLS
PRINT HOUR,"-"*MINUTE
PRINT (HOUR+1) MOD 24,"-"*(60-MINUTE)
EXEC 0 'runs the code stored in slot 0 (the default)
```
Note: SmileBASIC only has 50 columns of text, so it won't look good...
] |
[Question]
[
*(Inspired by [ASCII's 95 Characters...95 Movie Quotes](https://codegolf.stackexchange.com/q/40562/42963))*
## The Challenge
Given input `n`, output the `nth` [Fibonacci number](https://oeis.org/A000045). You can use either `0` or `1` indexing, please state which in your submission. Simple, yeah? The catch is you must take the character set of the immediate previous answer, remove two characters from it, and add a separate character. The separate character must
* *not* be from the immediate previous answer's character set
* be from the set of (printable ASCII, space, newline, horizontal tab)
and thus your total character set size will be *exactly* one smaller than the immediate previous answer's set.
## The initial answer
The first submission must contain a subset of (all printable ASCII, space, newline, and horizontal tab) with two characters removed. Every submission thereafter must restrict their answers to this original ASCII-only format (meaning you can't add a Unicode or extended-ASCII character ... sorry Jelly, APL, et al.).
## Examples and Clarifications
* Suppose the first answer is in C and contains (almost all printable ASCII, newline, and horizontal tab), and omits the `%` and `^` from its character set. The second submission, then, must remove two characters from the previous (almost all printable ASCII, newline, and horizontal tab) character set and add in either the `%` or `^`. Perhaps it's a one-liner PowerShell answer that omits the newline. And so on.
* If the previous answer had `print(){}!*+` as its character set (12 characters), your submission could have `print(){}!` (10 characters) and one additional character, `print(){!+` (10 characters) and one additional character, etc.
* If the previous answer had `print(){}!*+` as its character set (12 characters), your submission could *not* have `print()` and `&` (8 characters) as its character set, since `12 - 8 > 1`.
* If the previous answer had `print(){}!*+` as its character set (12 characters), your submission could *not* have `print(){}!` (10 characters) plus additional character `*` as its character set, since even though that's 11 characters, the `*` is included in the previous set.
* Not every character in your character set must do something useful for your submission. For example, if the previous answer had `print(){}!*+` as its character set, and your language has a built-in `!` that calculates the Fibonacci sequence and `#` that starts a comment, your submission could be `!#print(){}` and still be valid.
* You can use the same character from your character set multiple times. For example, suppose your character set was `!*#_`, your answer could be `!!!**#**#_!!` and would be acceptable.
* In addition to your code (and an explanation is nice, too!) please also explicitly list your character set, to make it easier for future submissions.
## Winning
The winner of the challenge will be the person who posted the *second* most-recent submission (i.e., not the person who posted last, since they broke the chain).
### Final Rules
Usual [answer-chaining](/questions/tagged/answer-chaining "show questions tagged 'answer-chaining'") rules apply:
* The same person can't post twice in a row
* If an answer is deemed invalid (for example, it used a forbidden character, or doesn't calculate correctly), it needs to be deleted (and any subsequent answers that chain off of it also)
* Two users who post "at the same time" will have to let the earlier submission stand
* The same language cannot be posted twice in a row. For the purposes of this rule, languages of the same family (e.g., Python 2 and Python 3) count as "the same language."
---
Final things:
* This post works best if you sort by "Oldest" so that the answers are in proper order.
* Kyle Gullion constructed a code checker in Python [here](https://gist.github.com/kgullion/8d591bc76d3e18e00e31ae64fab32178) to verify if you're missing or using wrong characters.
[Answer]
# 1. C
Contains no `{` or `}`.
```
#if 1
#define Q !"$&'",./=@[]^_\`|*
int WERTYUIOPASDFGHJKLZXCVBNM34567890(qwrtyuopasghjklzxcvbm)<%
return qwrtyuopasghjklzxcvbm<2?1:WERTYUIOPASDFGHJKLZXCVBNM34567890(~-qwrtyuopasghjklzxcvbm)+WERTYUIOPASDFGHJKLZXCVBNM34567890(qwrtyuopasghjklzxcvbm-2);
%>
#endif
```
[Try it online!](https://tio.run/nexus/c-gcc#@6@cmaZgyKWckpqWmZeqEKigqKSipq6ko6dv6xAdGxcfk1CjxZWZV6IQ7hoUEhnq6R/gGOzi5u7h5e0TFeEc5uTna2xiamZuYWmgUVheVFJZml@QWJyekZWdU1WRXJaUq2mjysVZlFpSWpSngFWBjZG9oRVhw@t0sRuvTaa7dI00rblU7biUU/NSMtP@5yZm5mloVhcUAb2apqGkmqKkQ9hgM01N69r/AA "C (gcc) – TIO Nexus")
I hope I did this right.
[Answer]
# 8. [Octave](https://www.gnu.org/software/octave/)
Added `U` and removed `+` and `-`. Solution contains no `+-`01AEI` or tab character.
```
% !"#$&\'*./256789:<>?BCDFGHJKLMNOPQRSTUVWXYZ\\_abceghijklnpqrstuvwyz{|}~
f=@(x)([mod(4,3) mod(4,3);mod(4,3) mod(4,4)]^x)(3)
```
Based on the [Fibonacci Matrix](http://mathworld.wolfram.com/FibonacciQ-Matrix.html).
[Answer]
## 33, [MATL](https://github.com/lmendo/MATL)
Added `-`, removed `()`. Solution doesn't contain `!&'()/\01?AEIKLMNPSTWZ`dmwz{}|~`, tab, space, or newline.
```
5X^Hq+G^Hq5X^-G^-HG^5X^*Hqqq^*Yo%"#$,.2346789:;<=>@BCDFJOQRUV[]_abcefghijklnprstuvxy
```
[Try it at MATL Online](https://matl.io/?code=5X%5EHq%2BG%5EHq5X%5E-G%5E-HG%5E5X%5E%2aHqqq%5E%2aYo%25%22%23%24%2C.2346789%3A%3B%3C%3D%3E%40BCDFJOQRUV%5B%5D_abcefghijklnprstuvxy&inputs=10&version=19.9.0)
Fixed mistake: `0`, `1`, and `\` were accidentally left in the comment (after the `%`) at the end. Their removal does not break the functionality. Moved this answer from 32 to 33 in an attempt to keep it valid. If it needs to be deleted, please let me know and I'll do just that.
[Answer]
# 2. Mathematica
Contains no `}`, `Z`, or horizontal tab. (Reincluded `{`.)
```
(* !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXY
[\]^_`\abcdefghijklmnopqrstuvwxyz{|~ *)
Fibonacci
```
The two first lines are just a comment; the last line is the builtin function, using the Only True Super Cosmically Ordained Indexing where inputs 0 and 1 yield outputs 0 and 1 respectively (I have no idea whether to call this 0-indexed or 1-indexed).
[Answer]
# 36. Java
Added `\`. Removed `qx`. Doesn't use `!&'()/1?AEIKLMNPSTWZ`dmnqtwxz{}|~[]`, tab, or space.
```
\u002f\u002f"#$%*:>@BCGHJOQRUVXY^_jk
class
Fibo\u006eacci\u007b
i\u006e\u0074
fib\u0028i\u006e\u0074
\u006e\u0029\u007b
i\u006e\u0074
lo\u0077=0,high=3-2,\u0074e\u006Dp;
for\u0028i\u006e\u0074
i=3-2;i<\u006e;i++\u0029\u007b
\u0074e\u006Dp=lo\u0077;
lo\u0077=high;
high=high+\u0074e\u006Dp;
\u007D
re\u0074ur\u006e
lo\u0077;
\u007D
public
s\u0074a\u0074ic
voi\u0064
\u006Dai\u006e\u0028\u0053\u0074ri\u006eg\u005b\u005Db\u0029\u007b
Fibo\u006eacci
a=\u006ee\u0077
Fibo\u006eacci\u0028\u0029;
for\u0028i\u006e\u0074
i=3-2;i<=20;i++\u0029\u007b
\u0053ys\u0074e\u006D.ou\u0074.pri\u006e\u0074l\u006e\u0028a.fib\u0028i\u0029\u0029;
\u007D
\u007D
\u007D
```
I know I probably could have waited longer but I wanted to make sure to get this out before it was too late. Not only does this class define a function which takes an integer `n` and return that Fibonacci number, but it also prints the first 20 for you just for fun. I tried to do my due diligence by writing this in plain old java with no sneaky golfing and then I removed illegal characters 1 by 1 until we got to the creature you see before you now.
[Try it online!](https://tio.run/nexus/java-openjdk#hVJNS8QwEL3Pz/DjYtdSUrvdNUZEi8peREFRECUpdne00JJSwV9fTSbSHSl4mWQmL@/NvGR47pNEVBR3dvf2D45Pz84vrq5XN7d39w@PTy@v7x9Q1rrr4BJN44DzN12W6Ha5AaSKz46gQuOpFrw8JmI5ea/2xHmuktkG1xuVHooZHXnEvGglVI2d4kYHlnhCRYlRxHQ4i/oVkqOkE5TgZV2I/ur6vAAbBHtLSjBSBUTbmxpL6AinafkpfDbUcfCh0FsDiIWLWUpgG07WvuitzArD5uGPAFpRQs3lE29ECmL5r4FKJJPuZelXxzyJm57yuLWMqt6eS8f8MxCn6yPYxZZh@AY "Java (OpenJDK 8) – TIO Nexus")
[Answer]
# 37. Python 2
Readded `x`. Doesn't use `!&'()/1?AEIMNPSTWZdmnqtwz{}|~[]`, space, tab or `. Removed K and L.
```
f=u"\u0074"
b=u"\u006D"
i=u"\u0028"
j=u"\u0029"
h=u"\u006e"
r=2.2360679775
s=u"\u002F"
exec"p="+i+"3-2+r"+j+s+"2"
exec"g=i"+h+"pu"+f+i+j
exec"pri"+h+f+i+"i"+h+f+i+i+"p**g-"+i+"-p"+j+"**-g"+j+s+"r"+j+j
#$%´:;<=>@BCGHJOQRUVXY^agklopvy
```
With comments:
```
f=u"\u0074" #t
b=u"\u006D" #m
i=u"\u0028" #(
j=u"\u0029" #)
h=u"\u006e" #n
r=2.2360679775 #sqrt(5)
s=u"\u002F" #/
exec"p="+i+"3-2+r"+j+s+"2" #p=(3-2+r)/2 = (1+sqrt(5))/2 = phi
exec"g=i"+h+"pu"+f+i+j #g=input()
exec"pri"+h+f+i+"i"+h+f+i+i+"p**g-"+i+"-p"+j+"**-g"+j+s+"r"+j+j #print(int((p**g-(-p)**-g)/r))
```
This approach uses the fibonacci series' general term.
[Answer]
# 3. [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak)
Contains no `Z`, `~`, `A`, or horizontal tab. (Re-included `}`)
```
({}<(())>){({}<(({})<>)<>({}{}<<>({}<>)>)>[()])}{}{}
# !"$%&'*+,-./0123456789:;=?@BCDEFGHIJKLMNOPQRSTUVWXY\^_`abcdefghijklmnopqrstuvwxyz|
```
[Try it online!](https://tio.run/nexus/brain-flak#@69RXWujoaGpaadZDWFW12ra2AERkAHkg2kgHwijNTRjNWtBolzKCopKKqpq6lraOrp6@gaGRsYmpmbmFpZW1rb2Dk7OLq5u7h6eXt4@vn7@AYFBwSGhYeERkTFx8QmJSckpqWnpGZlZ2Tm5efkFhUXFJaVl5RWVVTX//5sDAA "Brain-Flak – TIO Nexus")
[Answer]
# 5, [Haskell](https://www.haskell.org/)
Removed `AEIOU` and tab, added `Z`
```
-- #!"$%&'*./23456789;:<>?@BCDFGHJKLMNPQRSTVWXYZ[\]^`abcdeghijklmopqrstuvwxyz{|}~,_
f 0 = 1
f 1 = 1
f n = f (n-1) + f (n-2)
```
[Try it online!](https://tio.run/nexus/haskell#@6@rq6CsqKSiqqaupadvZGxiamZuYWltZWNn7@Dk7OLm7uHl7ePrFxAYFBwSFh4RGRUdExuXkJiUnJKanpGZlZ2Tm19QWFRcUlpWXlFZVV1TW6cTz5WmYKBgq2AIpA2hdB6QTlPQyNM11FTQhrCMNP/nJmbm2RYUZeaVKKgABc3@AwA "Haskell – TIO Nexus")
[Answer]
## 12. Python 3
added `:` removed `{;` doesn't contain `{};`01AEIPQx` or tab character.
```
#!"#$%&\',./23456789?@BCDFGHJKLMNORSTUVWXYZ[\]^_abcdgjkmopqrvwyz|~:
def fib(n,a=3-2,b=3-2):
if n==2-2:
return a
a, b = b, a + b
return fib(n-1,a,b)
```
[Answer]
# 6. [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak)
```
({}<(())>){({}<(({})<>)<>({}{}<<>({}<>)>)>[()])}{}{}
# !"$%&'*+,-./0123456789:;=?@BCDFGHJKLMNOPQRSTVWXY\^bcdfghjklmnopqrstvwxyz|
```
[Try it online!](https://tio.run/nexus/brain-flak#@69RXWujoaGpaadZDWFW12ra2AERkAHkg2kgHwijNTRjNWtBolzKCopKKqpq6lraOrp6@gaGRsYmpmbmFpZW1rb2Dk7OLm7uHl7ePr5@/gGBQcEhYeERkTFxSckpaekZWdk5uXn5BYVFxSVl5RWVVTX//5sDAA "Brain-Flak – TIO Nexus")
Doesn't use `*tab*AEIU`_`, and added back `O`
[Answer]
# 26. [Prolog (SWI)](http://www.swi-prolog.org)
Added `%`. Removed `NK`. Doesn't use `&*01AEIKLMNPSTWZ`dmrwz{}]`, tab or newline.
```
a(X,B):-X<3,B is 4-3;C is X-4-(-3),D is X-2,a(C,G),a(D,F),B is G-(-F).%!"#$'/56789=>?@HJOQRUVY[\^_bcefghjklnopqtuvxy|~
```
[Try it online!](https://tio.run/nexus/prolog-swi#@5@oEaHjpGmlG2FjrOOkkFmsYKJrbO0MYkTomuhq6Bpr6rhAeEY6iRrOOu6aQMpFx00TotodqMRNU09VUUlZRV3f1MzcwtLWzt7Bw8s/MCg0LDI6Ji4@KTk1LT0jKzsnL7@gsKS0rKKypu7//0QNQwOdCE09AA "Prolog (SWI) – TIO Nexus")
[Answer]
# 34. [brainfuck](https://github.com/TryItOnline/tio-transpilers)
Added newline, removed `n` and `t`. Doesn't use `!&'()/\01?AEIKLMNPSTWZ`dmntwz{}|~`, tab, or space. (maybe we can get some 2D languages now)
0-indexed. Input/output is by byte values.
```
,[->]+>+<<[->>[->+<]<[->+<]>>[-<+<+>>]<<<]>>.
"#$%*23456789:;=@BCDFGHJOQRUVXY^_abcefghijklopqrsuvxy
```
[Try it online!](https://tio.run/nexus/brainfuck#@68TrWsXq22nbWMDZNgBsbZNrA2EAnFttG207exibWxAXD0uJWUVVS0DQyNjE1MzcwtLK2tbBydnFzd3Dy//wKDQsIjImLj4xKTk1LT0jMys7Jy8/ILCouKS0rKKyv//WQE "brainfuck – TIO Nexus")
[Answer]
# 4, [Python 2](https://docs.python.org/2/)
Removed `AEIZ`, tab added `~`
```
# !"$%&'*-./23456789;<>?@BCDFGHJKLMNOPQRSTUVWXY[\]^`chjklmpqsvwxyz{|}
def f(x):
a=0
b=1
for _ in range(x):
a,b = a+b,a
return a
```
[Try it online!](https://tio.run/nexus/python2#JcznDsFAAADg33dPcbZStPYqgth7i3mlrRqHU3u8ekn8/pJPNyGD0WS2WG12xuFkXW4Px3t9/kAwFI5EY3EhkUylM9lcvlAslSvVWr3RbLU73V5/MByNJ9PZHIuLpSQrK3W92e7I/nCkJ@18ud7uj@fr/YHwh0i235goBFjgIBAFHgJ5T9EMqQRRTBTprwCzIhIQdooshoBK2pkShPUDVYn2G3iO0b8 "Python 2 – TIO Nexus")
[Answer]
## 11. [Standard ML (mosml)](http://mosml.org)
Added `+`. Removed `:}`. Doesn't contain `:}0`1AEIPQx` or tab character.
```
(* !"#$%&\',./23456789;<>?@BCDFGHJKLMNORSTUVWXYZ[\]^_abcdgjkmopqrvwyz{|~ *)
fun f s = if s = 2-2 then 2-2 else if s = 3-2 then 3-2 else f (s-4+2) + f (s-3+2)
```
SML isn't on TIO, and I used the moscow ml variety, but there's an online SMLNJ interpreter [here](https://www.tutorialspoint.com/execute_smlnj_online.php).
[Answer]
# 10. C
Added `m`, removed `PQ`. Doesn't contain `+`01AEIPQx` or tab character.
Compiler flag: `-lm`
```
//!"#$%&'*346789:<=>?@BCDFGHJKLMNORSTUVWXYZ[\]^_acfghkmvyz|.
double fib(i){
double j = -(-~-2-sqrt(5))/2;
return floor((pow(j,i)-pow(-j,-i))/sqrt(5));
}
```
[Try it online!](https://tio.run/nexus/c-gcc#@6@vr6ikrKKqpq5lbGJmbmFpZWNrZ@/g5Ozi5u7h5e3j6@cfFBwSGhYeERkVHRMbF5@ckp6RnVtWWVWjx8WVkl@alJOqkJaZpJGpWc2lAARQoSwFWwVdDd06XSPd4sKiEg1TTU19I2uwiqLUktKiPAWNgvxyjSydTE1dEEM3S0c3E6gGqtiaq/Z/Zl6JQm5iZp4G1GQQPxNiRFp@kUamrYG1QqaNoSGQ1NbWBIuDQEERUGGahpKqUYqCqpGeQVpMnpJOpg7EjWCD/yWn5SSmF//XzckFAA "C (gcc) – TIO Nexus")
[Answer]
# 9. Python 2
Added `-`, removed `m` and `x`. Contains no `+`01AEImx` or tab character.
```
# --!"$%&'*./29;:<>?@[\]^345678BCDFGHJKLMNOPQRSTUVWXYZabcdeghijklopqrstuvwyz{|}~,_
def fibonacci(n):
elif n==(2/2):
return 2-2
elif n==2:
return 2/2
else:
return fibonacci(n-2/2)-(-(fibonacci(n-2)))
```
Recursive Python function! Adds all Fibonacci numbers *backwards* until `n` is 1.
[Answer]
# 18. [Octave](https://www.gnu.org/software/octave/)
Added `;` and removed `f` and space. Solution contains no `{}:`*%01AEIPQfrd`, no tab, no newline, and no space characters.
```
g=@(x)([4-3,4-3;4-3,4-4]^x)(3)#!"$&'+./256789<>?BCDFGHJKLMNORSTUVWXYZ\_abcehijklmnopqstuvwyz|~
```
Identical to [answer 8](https://codegolf.stackexchange.com/a/115638/32604), just with more SML hate :P
[Answer]
# 23. Standard ML (mosml)
There we go again. Added `Q`, removed `}` and `]`. Doesn't use `%&*+01:AEILMPZ`dmrzM{}]`, tab, or linefeed
```
fun f x = #2("!#$\\',.23456789<>?@BCDFGHJKNOQRSTUVWXY[/;^_abcgjkopqvwxy|~", if x = 2-2 then 2-2 else if x = 3-2 then 3-2 else f (~(~(x-4)-2)) + f (x-(~3-2)))
```
[Answer]
# 25. [CJam](https://sourceforge.net/p/cjam)
Added `+` back, removed `S` and `T`. Doesn't use `%&*01AEILMPSTZ`dmrz{}]Ww`, tab, or linefeed.
Basically a port of my older answer, but this one uses some eval trickery to circumvent the lack of braces.
```
q~"XX"a:~'|("_(j\((j+"'|)'j+++~e# !$,-./23456789;<=>?@BCDFGHJKNOQRUVY[^bcfghiklnopstuvxy
```
0-indexed.
[Try it online!](https://tio.run/nexus/cjam#@19YpxQRoZRoVadeo6EUr5EVo6GRpa2kXqOpnqWtrV2XqqygqKKjq6dvZGxiamZuYWltY2tn7@Dk7OLm7uHl7ecfGBQaFhkdl5Sclp6RmZ2Tl19QXFJaVlH5/7/5f1U1LQNDR1dPH9@A4JCohJTcoirf6trY8HJOLgA "CJam – TIO Nexus")
[Answer]
# 27. JavaScript
Added `*`, removed `"` and `'`. Doesn't use `"&'01AEIKLMNPSTZ`dmrz{}]Ww`, tab, or linefeed.
```
f=a=>a<2?3-2:f(a-3+2)+f(a-4+2)/* !#$,.56789;%@BCDFGHJOQRUVXY[\^_bceghijklnopqstuvxy|~*/
```
[Answer]
# 28. [Haskell](https://www.haskell.org/)
```
f=length"":scanl(+)(length"f")f;g=const(f!!)"#$%*,./23456789<>?@BCDFGHJOQRUVXY[\\^_bijkpquvxy|~"
```
[Try it online!](https://tio.run/nexus/haskell#@59mm5Oal16SoaRkVZycmJejoa2pARVJU9JMs063Tc7PKy7RSFNU1FRSVlHV0tHTNzI2MTUzt7C0sbN3cHJ2cXP38PIPDAoNi4iMjomJi0/KzMouKCwtq6isqVP6n5uYmadgq1BQlJlXoqCikJtYoJCuEG2gp2doEPsfAA "Haskell – TIO Nexus") Usage: `g 3` gives `2`.
Added `"`, removed `<space>` and `-`. Does not use `&'-01AEIKLMNPSTZ`dmrz{}]Ww` or any white spcae.
[Answer]
# 30. [Standard ML](https://en.wikipedia.org/wiki/Standard_ML)
Added `:`, removed `+` and `?`. Does not contain `!&'+-01?AEIKLMNPSTWZ`dmrwz{}` or any white space.
```
fun$(a,b,x)n=if(length(x)=n)then(length(a))else$(b,a@b,()::x)n;("#%*./23456789<>BCDFGHJOQRUVXY\\^_cjkopqvy|~";$([],[()],[]))
```
The first part `fun$(a,b,x)n=if(length(x)=n)then(length(a))else$(b,a@b,()::x)n` defines a function `$` which computes the `n`th fibonacci number itereatively using an unary list encoding. The length of argument `x` indicates the current number and `a` and `b` are lists of length `fib(length(x)-1)` and `fib(length(x))`. If `n` equals `length(x)` we return `length(b)`, otherwise recursively add `a` and `b` via list concatenation and increment `x` by adding an element `()` to it.
The second part `("#%*./23456789<>BCDFGHJOQRUVXY\\^_cjkopqvy|~";$([],[()],[]))` is a sequence where the string is discarded and `$([],[()],[])` is the initialisation of the function `$` with `a = 0`, `b = 1` and `x = 0`, resulting in an anonymous function which computes the nth fibonacci number.
[Answer]
# 32, Python 3
```
exec(chr(2**2+2**5+2**6)+chr((3^2)+2**2+2**5+2**6)+chr(2+2**2+2**5+2**6)+chr(2**5)+chr(2+2**2+2**5+2**6)+chr(2**3+2**5)+chr(2**3+2**4+2**5+2**6)+chr((3^2)+2**3+2**5)+chr(2+2**3+2**4+2**5)+chr(2+2**3)+chr(2**5)+chr((3^2)+2**5+2**6)+chr((3^2)+2**2+2**3+2**4+2**5)+chr(2**4+2**5)+chr(2+2**3)+chr(2**5)+chr(2+2**5+2**6)+chr((3^2)+2**2+2**3+2**4+2**5)+chr((3^2)+2**4+2**5)+chr(2+2**3)+chr(2**5)+chr(2+2**2+2**5+2**6)+chr((3^2)+2+2**2+2**3+2**5+2**6)+chr(2+2**4+2**5+2**6)+chr(2**5)+chr((3^2)+2+2**2+2**3+2**4+2**6)+chr(2**5)+chr((3^2)+2**3+2**5+2**6)+chr(2+2**2+2**3+2**5+2**6)+chr(2**5)+chr(2+2**4+2**5+2**6)+chr((3^2)+2**5+2**6)+chr(2+2**2+2**3+2**5+2**6)+chr((3^2)+2+2**2+2**5+2**6)+chr((3^2)+2**2+2**5+2**6)+chr(2**3+2**5)+chr(2**3+2**4+2**5+2**6)+chr((3^2)+2**3+2**5)+chr(2+2**3+2**4+2**5)+chr(2+2**3)+chr(2**5)+chr(2**5)+chr((3^2)+2**5+2**6)+chr(2**2+2**3+2**5)+chr(2+2**5+2**6)+chr(2**5)+chr((3^2)+2**2+2**3+2**4+2**5)+chr(2**5)+chr((3^2)+2**5+2**6)+chr((3^2)+2+2**3+2**5)+chr(2+2**5+2**6)+chr(2**2+2**3+2**5)+chr((3^2)+2**5+2**6)+chr(2+2**3)+chr(2**5)+chr(2+2**4+2**5+2**6)+chr((3^2)+2**2+2**5+2**6)+chr(2**2+2**4+2**5+2**6)+chr((3^2)+2**2+2**4+2**5+2**6)+chr(2+2**4+2**5+2**6)+chr(2+2**2+2**3+2**5+2**6)+chr(2**5)+chr((3^2)+2**5+2**6))#"$%,.789:;<=>@BCDFGHJOQRUVXY[]_abfgijklnopqstuvy
```
Added `r` and removed `|~`. Solution contains no `!&'/\-01?AEIKLMNPSTWZ`dmrwz{}|~`, no tab, no newline, and no space characters.
[Answer]
# 39. [Python 2](https://docs.python.org/2/)
Added `0`. Removed `@^`. Doesn't use `!^&'()/1?@AEIMNPSTWZdmntwz{}|~[] ``, tab or newline.
```
C=u"f=la\u006Db\u0064a\u0020X:3-2if\u0020X<2else\u0020f\u0028X-3+2\u0029+f\u0028X-2\u0029";exec""+C#$%*,.57>BFGHJKLOQRUVY_ghjkopqrvy
```
Argument to exec without escape sequences:
```
f=lambda X:3-2if X<2else f(X-3+2)+f(X-2)
```
[Try it online!](https://tio.run/##K6gsycjPM/r/39m2VCnNNicxptTAwMwlCUyZgHlGBhFWxrpGmWlQjo1Rak5xKoQDEbOI0DXWNgIzLbXhQlABJevUitRkJSVtZ2UVVS0dPVNzOyc3dw8vbx//wKDQsMj49Iys7PyCwqKyyv8FRZl5JQppGoYGmv8B "Python 2 – Try It Online")
[Answer]
# 38. Matl
Added `q`. Removed `0 <newline>`. Doesn't use `!&'()/1?AEIKLM0NPSTW{Z`dmntwxz}|~[]`, tab, newline, or space.
```
5X^Hq+G^Hq5X^-G^-HG^5X^*Hqqq^*Yo%"#$,.2346789:;<=>@BCDFJORUV_abcefghijklprsuvy
```
[Try it online](https://matl.suever.net/?code=5X%5EHq%2BG%5EHq5X%5E-G%5E-HG%5E5X%5E%2aHqqq%5E%2aYo%25%22%23%24%2C.2346789%3A%3B%3C%3D%3E%40BCDFJORUV_abcefghijklprsuvy%0A&inputs=10&version=19.9.0)
[Answer]
# 7, [Python 2](https://docs.python.org/2/)
Re-included `_`.
Removed characters: *tab* and `AEIU``, and (just to get a little nasty) `0` and `1`. Otherwise, just a copy of [Wheat Wizard's answer](https://codegolf.stackexchange.com/a/115604/56178) (hence the community wiki).
```
# !"$%&'*./456789;<>?@BCDFGHJKLMNOPQRSTVWXY[\]^chjklmpqsvwxyz{|}
def f(x):
a=2-2
b=3-2
for _ in range(x):
a,b = a+b,a
return a
```
[Try it online!](https://tio.run/nexus/python2#@6@soKikoqqmrqWnb2JqZm5haW1jZ@/g5Ozi5u7h5e3j6@cfEBgUHBIWHhEZHRMbl5yRlZ2TW1BYXFZeUVlVXVPLxZWSmqaQplGhacWlkGhrpGvEpZBkawyi0vKLFOIVMvMUihLz0lMhKhQSdZIUbBUStZN0ErkUilJLSovyFBL/FxRl5pUATTE00vwPAA "Python 2 – TIO Nexus")
[Answer]
## 13. [Standard ML (mosml)](http://mosml.org)
Added `x`. Removed `:r`. Doesn't contain `:;{}0`1AEIPQr` or tab character.
```
(* !"#$%&\',./23456789<>?@BCDFGHJKLMNORSTUVWXYZ[\]^_abcdgjkmopqvwxyz|~ *)
fun f s = if s = 2-2 then 2-2 else if s = 3-2 then 3-2 else f (s-4+2) + f (s-3+2)
```
After we've pretty much excluded C-style languages, let's go after Python. This answer is pretty much identical to answer 11.
[Answer]
# 14. [Octave](https://www.gnu.org/software/octave/)
Added `r` and removed newline and space. Solution contains no `{}:;`01AEIPQ`, no tab, no newline, and no space characters.
```
f=@(n)round(((2/2+sqrt(5))/2)^n/sqrt(5))%!"#$&'*-,.346789<>?BCDFGHJKLMNORSTUVWXYZ[\]_abceghijklmpvwyz|~
```
Based on a closed form formula [(7)](http://mathworld.wolfram.com/FibonacciQ-Matrix.html).
[Answer]
# 16. [Octave](https://www.gnu.org/software/octave/)
Added `/` and removed \* and space. Solution contains no `{}:;`*%01AEIPQ`, no tab, no newline, and no space characters.
```
f=@(n)round(((2/2+sqrt(5))/2)^n/sqrt(5))#!"$&'-,.346789<>?BCDFGHJKLMNORSTUVWXYZ[\]_abceghijklmpvwyz|~
```
Identical to [answer 14](https://codegolf.stackexchange.com/a/115695/32604), just a straight up attack on SML and Python :P
[Answer]
# 15. Standard ML (mosml)
Added space and removed `%/`. Doesn't contain `{}:;`01AEIPQ`, tab, or newline.
```
fun f s = if s = 2-2 then 2-2 else if s = 3-2 then 3-2 else f (s-4+2) + f (s-3+2) (* !"#$&\',.23456789<>?@BCDFGHJKLMNORSTUVWXYZ[\]^_abcdgjkmopqrvwxyz|~ *)
```
] |
[Question]
[
*[Cross posted from my anagolf post (note: may contain spoilers, post mortem).](http://golf.shinh.org/p.rb?ASCII+Pylon)*
Output the following text exactly.
* You may have additional trailing whitespace on each line, and trailing newlines as well.
* Shortest code, in bytes, wins.
```
!"!
"#$#"
#$%&%$#
$%&'('&%$
%&'()*)('&%
&'()*+,+*)('&
'()*+,-.-,+*)('
()*+,-./0/.-,+*)(
)*+,-./01210/.-,+*)
*+,-./012343210/.-,+*
+,-./0123456543210/.-,+
,-./01234567876543210/.-,
-./0123456789:9876543210/.-
./0123456789:;<;:9876543210/.
/0123456789:;<=>=<;:9876543210/
0123456789:;<=>?@?>=<;:9876543210
123456789:;<=>?@ABA@?>=<;:987654321
23456789:;<=>?@ABCDCBA@?>=<;:98765432
3456789:;<=>?@ABCDEFEDCBA@?>=<;:9876543
456789:;<=>?@ABCDEFGHGFEDCBA@?>=<;:987654
56789:;<=>?@ABCDEFGHIJIHGFEDCBA@?>=<;:98765
6789:;<=>?@ABCDEFGHIJKLKJIHGFEDCBA@?>=<;:9876
789:;<=>?@ABCDEFGHIJKLMNMLKJIHGFEDCBA@?>=<;:987
89:;<=>?@ABCDEFGHIJKLMNOPONMLKJIHGFEDCBA@?>=<;:98
9:;<=>?@ABCDEFGHIJKLMNOPQRQPONMLKJIHGFEDCBA@?>=<;:9
:;<=>?@ABCDEFGHIJKLMNOPQRSTSRQPONMLKJIHGFEDCBA@?>=<;:
;<=>?@ABCDEFGHIJKLMNOPQRSTUVUTSRQPONMLKJIHGFEDCBA@?>=<;
<=>?@ABCDEFGHIJKLMNOPQRSTUVWXWVUTSRQPONMLKJIHGFEDCBA@?>=<
=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZYXWVUTSRQPONMLKJIHGFEDCBA@?>=
>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\[ZYXWVUTSRQPONMLKJIHGFEDCBA@?>
?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^]\[ZYXWVUTSRQPONMLKJIHGFEDCBA@?
@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`_^]\[ZYXWVUTSRQPONMLKJIHGFEDCBA@
ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`aba`_^]\[ZYXWVUTSRQPONMLKJIHGFEDCBA
BCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdcba`_^]\[ZYXWVUTSRQPONMLKJIHGFEDCB
CDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefedcba`_^]\[ZYXWVUTSRQPONMLKJIHGFEDC
DEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghgfedcba`_^]\[ZYXWVUTSRQPONMLKJIHGFED
EFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijihgfedcba`_^]\[ZYXWVUTSRQPONMLKJIHGFE
FGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklkjihgfedcba`_^]\[ZYXWVUTSRQPONMLKJIHGF
GHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnmlkjihgfedcba`_^]\[ZYXWVUTSRQPONMLKJIHG
HIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnoponmlkjihgfedcba`_^]\[ZYXWVUTSRQPONMLKJIH
IJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrqponmlkjihgfedcba`_^]\[ZYXWVUTSRQPONMLKJI
JKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstsrqponmlkjihgfedcba`_^]\[ZYXWVUTSRQPONMLKJ
KLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvutsrqponmlkjihgfedcba`_^]\[ZYXWVUTSRQPONMLK
LMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxwvutsrqponmlkjihgfedcba`_^]\[ZYXWVUTSRQPONML
MNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba`_^]\[ZYXWVUTSRQPONM
NOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|{zyxwvutsrqponmlkjihgfedcba`_^]\[ZYXWVUTSRQPON
OPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~}|{zyxwvutsrqponmlkjihgfedcba`_^]\[ZYXWVUTSRQPO
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 73 bytes
```
' '*48;46..0|%{" "*$_+-join[char[]](($x=79-$_)..($y=$x+$j++)+(++$y)..$x)}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X11BXcvEwtrETE/PoEa1WklBSUslXls3Kz8zLzo5I7EoOjZWQ0OlwtbcUlclXlNPT0Ol0lalQlslS1tbU1tDW1ulEiioUqFZ@/8/AA "PowerShell – Try It Online")
Outputs the first whitespace-only line, then loops from `46` to `0`. Each iteration, outputs the corresponding number of spaces and then a `-join`ed together `char`-array of the appropriate symbols, via some calculations.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 13 bytes
```
E⁴⁸⮌✂γι⊕⊗ι‖O←
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3sUDDxEJHISi1LLWoOFUjOCczOVUjXUchU0fBMy@5KDU3Na8kNUXDJb80KQdIZ2qCgDVXUGpaTmpyiT9QVw7QCCuf1LQSTev////rluUAAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
⁴⁸ Literal 48
E Map over implicit range
ι ι Current index
⊗ Doubled
⊕ Incremented
γ Printable ASCII
✂ Slice
⮌ Reverse
Implicitly print each slice on separate lines
‖O← Reflect with overlap
```
[Answer]
# [Python 2](https://docs.python.org/2/), 73 bytes
```
i=48
while i:i-=1;r=range(79-i,127-i*2);print' '*i+bytearray(r+r[-2::-1])
```
[Try it online!](https://tio.run/##BcFLCoAgEADQfadw56dmoQSW4kmihYHkQJgMQnh6e6/2lt9ixsCwbtOX8UkMHULQngLFcidhd8BFGwuojPSVsDTOuML56i1FotgFzXSAcQ70Kcf4AQ "Python 2 – Try It Online") Crossposted from anarchy golf (see [my submission](http://golf.shinh.org/reveal.rb?ASCII+Pylon/lynn_1523517333&py)).
Quick post-mortem analysis: xnor and dianne discovered the [exact](http://golf.shinh.org/reveal.rb?ASCII+Pylon/xnor_1523583184&py) same [solution](http://golf.shinh.org/reveal.rb?ASCII+Pylon/dianne_1523778547&py). ebicochneal submitted a [71 byte solution](http://golf.shinh.org/reveal.rb?ASCII+Pylon/ebicochineal_1523764377&py) which mitchs improved to [70 bytes](http://golf.shinh.org/reveal.rb?ASCII+Pylon/mitchs_1524714112&py). They avoid dealing with `bytearray` (which is long) or `''.join(map(chr,…))` (which is even longer) entirely, by keeping a "current line" variable and cleverly updating it.
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), ~~15~~ 14 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
0c[C²[j}¹m]/││
```
[Try it here!](https://dzaima.github.io/Canvas/?u=MCV1RkY0MyV1RkYzQiV1RkYyMyVCMiV1RkYzQiV1RkY0QSV1RkY1RCVCOSV1RkY0RCV1RkYzRCV1RkYwRiV1MjUwMiV1MjUwMg__,v=2)
Note that while making this I added a couple built-ins (`c` & `C`) as Canvas somehow didn't have any built-ins for ASCII/unicode before...
Explanation (some characters have been replaced to look monospace):
```
0c push the charcode of "0" - 48
{ ] map over 1..48
C push the ASCII characters
²[ ] repeat by the counter (0-indexed)
j remove the last character
¹m mold to the length of the counter
/ pad each line with spaces so it looks like a diagonal
││ palindromize the whole thing horizontally
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes
```
48ḶḤr$z0ZUŒB+32ỌY
```
[Try it online!](https://tio.run/##y0rNyan8/9/E4uGObQ93LClSqTKICj06yUnb2Ojh7p7I//8B "Jelly – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 16 bytes
```
48FžQNÝûN+èJ}).C
```
[Try it online!](https://tio.run/##MzBNTDJM/f/fxMLt6L5Av8NzD@/20z68wqtWU8/5/38A "05AB1E – Try It Online")
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGLOnline), ~~16~~ 15 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
'½{ ~Δf⌡kFm}⁰¼╥
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JTI3JUJEJTdCJTIwJTdFJXUwMzk0ZiV1MjMyMWtGbSU3RCV1MjA3MCVCQyV1MjU2NQ__,v=0.12)
[Answer]
# VBA, 71 bytes
An anonymous VBE immediate window function that takes no input and outputs to the console.
```
For i=0To 47:?Spc(47-i);:For j=-i To i:?Chr(32-Abs(j)+2*i);:Next:?:Next
```
[Answer]
# [Common Lisp](http://www.clisp.org/), 110 bytes
```
(dotimes(i 48)(dotimes(j 96)(princ(if(>(abs(- j 48))i)" "(code-char(+(-(* i 2)(abs(- j 48)))32)))))(princ"
"))
```
[Try it online!](https://tio.run/##VYzNCkBAFEb3nuI2q@@j2SCx8S5jkCt/Ge8/klLO7tTp@EXDESP6/dJ1CFApa342S1MRx6mbh45o4boAK/MTUWnEwO/9YP3kTmSwSEUl5y9jkfPh3ZjEkDHe "Common Lisp – Try It Online")
### Explanation
```
(dotimes(i 48) ;; for i from 0 up to 47
(dotimes(j 96) ;; for j from 0 up to 95
(princ ;; print
(if(>(abs(- j 48))i) ;; if abs(j - 48) > i
" " ;; print " "
(code-char(+(-(* i 2)(abs(- j 48)))32)) ;; else print appropriate character
)
)
)(princ"
") ;; print newline
)
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 70 bytes
```
s=[*?\s..?~]*'';48.times{|i|puts s[i,i+1].rjust(48)+s.reverse[-2*i,i]}
```
[Try it online!](https://tio.run/##KypNqvz/v9g2Wss@plhPz74uVktd3drEQq8kMze1uLoms6agtKRYoTg6UydT2zBWryirtLhEw8RCU7tYryi1LLWoODVa10gLKBtb@/8/AA "Ruby – Try It Online")
Constructs the full printable ASCII string and then prints the required number of forward (padded with spaces) + backward slices of it.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 24 bytes
```
48RrḤ’$$ịØṖŒBṭ"48RU⁶ẋ$¤Y
```
[Try it online!](https://tio.run/##ATIAzf9qZWxsef//NDhScuG4pOKAmSQk4buLw5jhuZbFkkLhua0iNDhSVeKBtuG6iyTCpFn//w "Jelly – Try It Online")
[Answer]
# C (gcc), 117 bytes
```
c;i;main(){for(i=0;i<48;++i){for(c=2*i-15;c<32+2*i;++c)putchar(c>31+i?c:32);for(;c>31+i;--c)putchar(c);putchar(10);}}
```
[Try it online!](https://tio.run/##TYrbCsIwEAV/J2sINImCeJL2W8oBdR@8IPpU@u3blFLwbZgZhhtpRigeoz6dTNfXx2ntoOV4hve6GdZ00BBPYMnJN26J8v59eR9b7XP0OvCSk2DdsRmE8DcJdoydYJ7NFg "C (gcc) – Try It Online")
Ungolfed:
```
int ch;
int row;
int main(void) {
for (row = 0; row < 48; ++row) {
for (ch = 2*row-15; ch < 32 + 2*row; ++ch) {
// The first character in the row is 2*row - 15 (row is zero-indexed)
if (ch > 31+row)
putchar(ch);
else
// If the current character is not in the pyramid, mask it with a space
putchar(' ');
}
for (; ch > 31+row; --ch) {
// Finish the other side of the pyramid
putchar(ch);
}
putchar('\n');
}
}
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~114~~ ~~113~~ 107 bytes
```
#define _(_)for(k=32;k<j;)putchar(j+_++);
f(j,k){for(j=31;++j<80;){printf("\n%*c",80-j,j);_(-31+k)_(j+~k)}}
```
[Try it online!](https://tio.run/##FcxBCsIwEADAu6@QirDrJtCaS2HbnwihxEazwVhCPZX49Vjvwzj9cK7W0332Ic1HCxb9O0MczZXjIIzLZ3XPKYOQJUI@eBAVcfsjGU3HRDL0LeO25JBWD80tnS@uUX2rRQmyBW06imj34RuxlPqaQoJ9AORSfw "C (gcc) – Try It Online")
*[101 bytes](https://tio.run/##Fc1BCsIwEADAvxSEXTeB1lwK29x8hhBCILUbjaWtpxKfbqwfmAl6DKHWCKIS7vG1gFjTMZEMfcu4z8uUtwjNLZ/OoVF9q0UJsgNtOkroQOiTsJT69FOGQwDkUr8hPvy4Vn21Dhz@2WTNhdMgjPN7C3d/ROSIkH8) are possible using a compiler flag.*
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~55~~ 53 bytes
```
say ' 'x 47-$_,chrs 32+2*$_ X-(-$_..$_)>>.abs for ^48
```
[Try it online!](https://tio.run/##K0gtyjH7/784sVJBXUG9QsHEXFclXic5o6hYwdhI20hLJV4hQlcDKKanpxKvaWenl5hUrJCWX6QQZ2Lx/z8A "Perl 6 – Try It Online")
[Answer]
# T-SQL, 153 bytes
```
DECLARE @ INT=33,@t CHAR(95)=''a:PRINT @t;
SET @t=LEFT(STUFF(STUFF(@t,63-@/2,2,''),46,0,CHAR(@-1)+CHAR(@)+CHAR(@+1)+CHAR(@)),33+@/2)
SET @+=2IF @<128GOTO a
```
Returns are for display only.
I tried several ideas, including a loop to preconstruct the full string (163 characters), and a nested loop to build it on the fly (168 characters), but this ended up being the shortest.
Basically, each loop I'm *cramming 4 new characters* into the center of the string, then trimming off the extras from both ends, using the [SQL `STUFF()` function](https://docs.microsoft.com/en-us/sql/t-sql/functions/stuff-transact-sql?view=sql-server-2017).
Formatted and explained:
```
DECLARE @ INT=33, --Using a single counter for both rows and CHAR
@t CHAR(95)='' --a non-null CHAR field will pre-fill with spaces
a: --GOTO loop, shorter than a WHILE
PRINT @t --duh
SET @t = LEFT( --lops off the character at the end
STUFF( --crams 4 new characters in the middle
STUFF(@t, 63-@/2, 2, '') --snips out a space and the leading character
,46, 0, CHAR(@-1) + CHAR(@) + CHAR(@+1) + CHAR(@))
,33 + @/2) --rest of the LEFT()
SET @+=2
IF @<128 GOTO a
```
[Answer]
# [J](http://jsoftware.com/), 47 44 bytes
```
(,.~}:@|."1)(1+i.48)([|.@{.}.)"0 1 u:31+i.96
```
[Try it online!](https://tio.run/##y/pflFiuYGulYKAAwrp6Cs5BPm7/NXT06mqtHGr0lAw1NQy1M/VMLDQ1omv0HKr1avU0lQwUDBVKrYxBEpZm/zW5UpMz8hWU9IBG/QcA "J – Try It Online")
Thanks to Conor O'Brien for the template!
Thanks to FrownyFrog for indicating the invalid solution.
[Answer]
# Ruby, 59 bytes
```
48.times{|i|-47.upto(i){|c|putc~c<i ?32-c.abs+2*i:32};puts}
```
Cross-posted from my answer on anagol.
[Answer]
# Japt `-R`, ~~18~~ 15 bytes
[14 bytes](https://ethproductions.github.io/japt/?v=1.4.5&code=IzHHb2RIK1rJIKzqw/s=&input=LVI=) if an additional leading newline is allowed.
```
#0õ_odH+ZÉ ¬êÃû
```
[Test it](https://ethproductions.github.io/japt/?v=1.4.5&code=IzD1X29kSCtaySCs6sP7&input=LVI=)
---
## Explanation
```
#0 :48
õ :Range [1,48]
_ Ã :Pass each Z through a function
o : Range [0,Z)
H+ZÉ : To each add 32+Z-1
d : Get the character at that codepoint
¬ : Join to a string
ê : Palinrdomise
û :Centre pad each element to the length of the longest element
:Implicitly join with newlines and output
```
[Answer]
# [J](http://jsoftware.com/), ~~40 37~~32 bytes
40 expression `u:30+2>.(+:@i.@(2&+)(-*(>+:))"0 _|@i:)47` thanks to +Galen Ivanov & +Conor O'Brien for the ideas in their solutions
37 included **echo** `echo u:32+|.(~.(>:*+:@[-])"0 _])|i:47`
```
echo u:32+|.(~.(>:*[+-)"{])|i:47
```
incorporating @FrownyFrog tips from comments
[TIO](https://tio.run/##y/rv56SnkJdfopCYk6OQW6mQX56nUJ5flK2jkJmXnF9UkF@UWJJarFCSWVCskFaUn6vg4FYEVFMJJNP/pyZn5CuUWhkbadfoadTpadhZaUVr62oqVcdq1mRamZj//w8A "TIO")
[Answer]
# [Perl 5](https://www.perl.org/), ~~77~~ ~~75~~ 69 bytes
```
map{say$"x(47-$_),(@a=map chr$_+32,$_..$_*2),reverse@a[0..@a-2]}0..47
```
[Try it online!](https://tio.run/##K0gtyjH9/z83saC6OLFSRalCw8RcVyVeU0fDIdEWKKqQnFGkEq9tbKSjEq@npxKvZaSpU5RallpUnOqQGG2gp@eQqGsUWwtkmJj///8vv6AkMz@v@L@ur6megaEBAA "Perl 5 – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 95 bytes
```
f=(x=y=0)=>y<48?[`
`[x]]+Buffer([x<48-y|x>48+y?32:x<48?x+y*2-16:80-x+y*2])+f(++x%96?x:+!++y):''
```
[Try it online!](https://tio.run/##HcjdCoIwFADg@96ii3DrsDATmaM56DXGQLFNCnGiFedA775@7j6@e/fq1n65zQ8xxatPKWiGmnTOdUPnUhrbblqLzsHlGYJfmMXvCnpjU0ogcyrULwwC7QtxrJTMxd@OQ2AAuKsrgwq2AMRVlqU@Tmsc/WGMAwuM8/QB "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~98~~ 88 bytes
-1 byte thanks to @Mr.Xcoder
```
i=32
exec"print''.join(chr(i+i-32-abs(j))for j in range(32-i,i-31)).center(95);i+=1;"*48
```
[Try it online!](https://tio.run/##TYlNDoMgGAX3noKwEepPorZJG@NJGheIgB8mYAGT9vQUuuri5U1mjk/YrOljhGnoC/EWHB8OTCjLVlswhG@OQAXN0Dds8URTKq1DGoFBjhklSApQp95R2nJhgnDkcaMjVFM34sv1HuMTs4WvuEZYwO7y21NqPBcpvJwP2Zw7E5BBSmvtr6nNrzIt20QqTf6xwvMX "Python 2 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 78 bytes
```
s=*32;48.times{puts (s.map(&:chr)*'').center 95;c=*s[0]+1;s=c+s.map{|x|x+2}+c}
```
[Try it online!](https://tio.run/##KypNqvz/v9hWy9jI2sRCryQzN7W4uqC0pFhBo1gvN7FAQ80qOaNIU0tdXVMvOTWvJLVIwdLUOtlWqzjaIFbb0LrYNlkbrLC6pqKmQtuoVju59v9/AA "Ruby – Try It Online")
Full program. Ungolfed:
```
s=*32; # s is an array of integers
48.times{ # Repeat 48 times:
puts (s.map(&:chr)*'').center 95; # Turn each int to a char, join, center, and print
c = *s[0] + 1; # c is a singleton array. It will bookend the next line
s = c + s.map{|x|x+2} + c # Add 2 to each element of s before adding the bookends
}
```
[Answer]
# [Yabasic](http://www.yabasic.de), 80 bytes
An anonymous [yabasic](/questions/tagged/yabasic "show questions tagged 'yabasic'") function that takes no input and outputs to the console
```
For i=0To 47
For j=i To 47?" ";Next
For j=-i To i?Chr$(32-Abs(j)+2*i);Next
?Next
```
[Try it online!](https://tio.run/##q0xMSizOTP7/3y2/SCHT1iAkX8HEnAvEybLNVADz7JUUlKz9UitKoMK6YPFMe@eMIhUNYyNdx6RijSxNbSOtTE2IMnsQ@f8/AA "Yabasic – Try It Online")
[Answer]
# [uBASIC](https://github.com/EtchedPixels/ubasic), 95 bytes
```
0ForI=0To47
1ForJ=ITo47:?" ";:NextJ
2ForK=-1*IToI:?Left$(Chr$(32-Abs(K)+2*I),1);:NextK
3?:NextI
```
[Try it online!](https://tio.run/##K01KLM5M/v/fwC2/yNPWICTfxJzLEMj2svUEsa3slRSUrK38UitKvLiMgOLetrqGWkApTyt7n9S0EhUN54wiFQ1jI13HpGINb01tIy1PTR1DTYgWby5jezDD8/9/AA "uBASIC – Try It Online")
[Answer]
# [MY-BASIC](https://github.com/paladin-t/my_basic), 97 bytes
An anonymous MY-BASIC response that takes no input and outputs to the Console
```
For i=0 To 47
For j=i To 47
Print" "
Next
For j=-i To i
Print Chr(32-Abs(j)+2*i)
Next
Print;
Next
```
[Try it online!](https://tio.run/##y63UTUoszkz@/98tv0gh09ZAISRfwcScC8TLss2E8gKKMvNKFJQUlLj8UitKoJK6YNlMqKRzRpGGsZGuY1KxRpamtpFWpiZELVjWGsz@/x8A "MY-BASIC – Try It Online")
-1 byte thanks to [Jonathan Frech](https://codegolf.stackexchange.com/users/73111/jonathan-frech)
[Answer]
# [MATL](https://github.com/lmendo/MATL), 18 bytes
```
48:"@@Zv30++Xhc3Zu
```
[Try it online!](https://tio.run/##y00syfn/38TCSsnBIarM2EBbOyIj2Tiq9P9/AA "MATL – Try It Online")
[Answer]
# [Gol><>](https://github.com/Sp3000/Golfish), 29 bytes
```
`0FaLssLF:P|LF:M|`/L-R` lRo|;
```
[Try it online!](https://tio.run/##S8/PScsszvj/P8HALdGnuNjHzSqgBkj41iTo@@gGJSjkBOXXWP//DwA "Gol><> – Try It Online")
### How it works
```
`0FaLssLF:P|LF:M|`/L-R` lRo|;
`0F |; Repeat the following 48 times and halt...
a Push 10 (\n)
Lss Push L(loop counter) + 32
LF:P| Repeat "Clone the top and increment" L times
LF:M| Repeat "Clone the top and decrement" L times
`/L-R` Push 32 (space) 47-L times (space is significant)
lRo Print everything as char, from the top,
until the stack is empty
```
[Answer]
# [Tcl](http://tcl.tk/), ~~129~~ ~~122~~ ~~118~~ 117 bytes
```
time {incr i;set j -48;set a {};time {set a $a[format %c [expr abs([incr j])>=$i?32:$i*2-abs($j)+30]]} 96;puts $a} 48
```
[Try it online!](https://tio.run/##K0nO@f@/JDM3VaE6My@5SCHTuji1RCFLQdfEAsxKVKiutYbIQ7gqidFp@UW5iSUKqskK0akVBUUKiUnFGtFg3Vmxmna2Kpn2xkZWKplaRrogGZUsTW1jg9jYWgVLM@uC0pJioBG1CiYW//8DAA "Tcl – Try It Online")
### Explanation
```
time { # for i from 0 up to 47
incr i
set j -48
set a {}
time { # for j from -48 up to 47
# add next character to a
set a $a[format %c [expr abs([incr j])>$i?32:$i*2-abs($j)+32]]
} 96
puts $a # print a
} 48
```
[Answer]
### C (gcc) 199 bytes
```
#include<stdio.h>
int i,j=32,k=32,l=49;int main(){while(k<127){for(i=0;i<l;++i)printf(" ");for(i=j;i<k;++i)printf("%c",i);printf("%c",k);for(i=k-1;i>=j;--i)printf("%c",i);printf("\n");j++;k+=2;l--;}}
```
[Try it online!](https://tio.run/##dYxBCsIwFET3nqJEhIQkYmtB5Cc9iRtJW/uTmEqtuCg9e0wRQRduBmbezBh5MSbGNQbjH3Wj7mON/barVhjGDIXV@0K4Rbwuj7CE1zMGyqZnh76hTuXFgU1tP1DUO0DlgXNktyE1W0oywuDNbGLuh20MEcjg27pP28kcsEojKf8OTiGdW87BcV2AlxLmOcYX)
Thanks to Picard and PunPun1000 for all of the help
] |
[Question]
[
The objective of this challenge is to take an array of positive integers, and enumerate its indices, grouping like elements.
An enumeration without any duplicates is done by just outputting an array of pairs `(value, index)`, for example, `[3, 4, 13, 9, 2]` => `[[3,1],[4,2],[13,3],[9,4],[2,5]]`.
However, if a given element appears a second time, it isn't given its own pair, but is instead added to the group of its first occurrence. If in our above example we replaced the 9 with 3, then in the output we would remove `[9,4]` and replace `[3,1]` with `[3,1,4]`.
In the output, groups must be ordered by their first occurrence, and indices must be in ascending order. The element must be first in a group, before its indices. Output may be 0 or 1 indexed. You may assume the array has at least one element.
Test cases:
```
Input | Output (One-indexed)
[3, 2, 2, 3] | [[3, 1, 4], [2, 2, 3]]
[17] | [[17, 1]]
[1, 1] | [[1, 1, 2]]
[1, 1, 2] | [[1, 1, 2], [2, 3]]
[1, 2, 3, 4] | [[1, 1], [2, 2], [3, 3], [4, 4]]
[1, 1, 1, 1] | [[1, 1, 2, 3, 4]]
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), fewest bytes wins!
[Answer]
# Dyalog APL, 5 bytes
```
(⊂,)⌸
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R2wSNR11NOpqPenYAuQrGCkZAaMyVpvCoo8vQHEgbKhhCSAUjMA2UVTCBigAhAA "APL (Dyalog Unicode) – Try It Online")
[`,⌸`](https://tio.run/##SyzI0U2pTMzJT///P@1R2wSdRz07gCwFYwUjIDTmSlN41NFlaA6kDRUMIaSCEZgGyiqYQEWAEAA) for 2 bytes *almost* works, but has trailing zeroes :/
[Answer]
# [J](http://jsoftware.com/), 12 bytes
```
~.,&.><@I.@=
```
Zero-indexed.
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/6/R01PTsbBw89Rxs/2typSZn5CukKRgrGAGhMYxraA5nKRgiMRWMEBygcgUTZDkg/A8A "J – Try It Online")
If you can remove all of the work I'm doing with boxes, you can probably reduce the bytecount by quite a bit. I'm going to see if I can figure that out.
# Explanation
This is probably too early to be explaining (there ought to be more golfs).
```
~. ,&.> <@I.@=
= Self-classify (comparison of each unique element to array)
@ Composed with
I. Indices of ones (where it's equal)
@ Composed with
< Boxed (how we deal with arrays of unequal length)
,&.> Joined with
> Unbox each
, Concatenate
&. Box again
~. Unique elements
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
```
ÙεDIQƶ0K)˜
```
[Try it online!](https://tio.run/##MzBNTDJM/f//8MxzW108A49tM/DWPD3n//9oYx0FIzAyjgUA "05AB1E – Try It Online")
**Explanation**
```
Ù # remove duplicates
ε # apply to each element
D # duplicate
IQ # compare for equality with input
ƶ # multiply each element by its index (1-based)
0K # remove zeroes
)˜ # wrap in a flattened list
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~83~~ 82 bytes
-1 byte thanks to Mego
```
lambda x:[[n]+[j for j,m in enumerate(x)if m==n]for n in sorted({*x},key=x.index)]
```
[Try it online!](https://tio.run/##FclBCsMgEADAr@xR26WQJqeCL7EeDK7EtK7BWthQ8nZL5jrb3pbCY4/m2d8@z8GDPKxld7UrxFJhxQyJgfibqfpGSnSKkI1hdzaf@Sm1UVC/ixz4ot3ILXEg0a5vNXFTUdkB7zjigJPTuv8B "Python 3 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 48 bytes
```
import Data.List
f l=nub[k:elemIndices k l|k<-l]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/PzO3IL@oRMElsSRRzyezuIQrTSHHNq80KTrbKjUnNdczLyUzObVYIVshpybbRjcn9n9uYmaegq1CbmKBr4JGQVFmXomCnkKaJpcCEEQrRBvrKBiBkXEsWEhHIdrQHMHUUTBE4QCVIvNB@nQUTNCUgHUpxP4HAA "Haskell – Try It Online")
[Answer]
# [Attache](https://github.com/ConorOBrien-Foxx/attache), 15 bytes
```
Flat=>Positions
```
[Try it online!](https://tio.run/##SywpSUzOSP3vkpqWmZcarZKm898tJ7HE1i4gvzizJDM/r/h/LBdXdUBRZl5JdLyOgpKtnZKOQlp0fGxsrYKtnUJYNJcCkDDWUTACI@NYHbCAoTmMoaNgiMQEKkLwQOp1FExQpMHquWL/AwA "Attache – Try It Online")
This is an interesting case of `=>`, the operator form of `Map`. When given two functional arguments `f` and `g`, `Map` returns a function `f => g[x]` over `x`. That is, the RHS is applied to the input, then the LHS is mapped.
The builtin `Positions` generates an array representing the grouping of entries by indices. By default, when not supplied with a second argument, `Positions` will use the first argument. `Flat` is then mapped over each item, as that is what the question requires.
## Alternative solutions
**31 bytes**
```
MapArgs[Concat#~Indices,Unique]
```
[Try it online!](https://tio.run/##SywpSUzOSP3vkpqWmZcarZKm8983scCxKL042jk/LzmxRLnOMy8lMzm1WCc0L7OwNDX2fywXV3VAUWZeSXS8joKSrZ2SjkJadHxsbK2CrZ1CWDSXApAw1lEwAiPjWB2wgKE5jKGjYIjEBCpC8EDqdRRMUKTB6rli/wMA "Attache – Try It Online")
A pretty short, builtin-less alternative. `MapArgs` is a function like `Map`, except you can feed extra arguments into it. For example, `MapArgs[{_1 + _2}, 1..3, 3]` is `[4, 5, 6]`. Like `Map`, it becomes curried when supplied with two functional arguments. The function be mapped is `Concat#~Indices`, which is a fork. This fork is applied to the `Unique` items of the input and the input itself. This translates to `Concat[_, Indices[_2, _]]` (with the arguments of `Indices` swapped through `~`), which pairs the element being mapped (`_`) with the indices of said element `_` in the input array, which is `_2` (as ffed through `MapArgs`).
**43 bytes**
```
{Flat=>Zip[Unique[_],Indices[_,Unique[_]]]}
```
[Try it online!](https://tio.run/##SywpSUzOSP3vkpqWmZcarZKm87/aLSexxNYuKrMgOjQvs7A0NTo@VsczLyUzObU4Ol4HLhYbW/s/lourOqAoM68EKKGgZGunpKOQBpKqVbC1UwiL5lIAEsY6CkZgZByrAxYwNIcxdBQMkZhARQgeSL2OggmKNFg9V@x/AA "Attache – Try It Online")
This is really just a more verbose (yet a tad more readable) combination of solutions #1 and #2.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
Q;"ĠṢ$
```
[Try it online!](https://tio.run/##y0rNyan8/z/QWunIgoc7F6n8P9x@dNLDnTP@/4821lEwAiPjWAA "Jelly – Try It Online")
Explanation:
```
Q;"ĠṢ$
Q Keep the first occurrence of each element
$ Last two links as a monad
Ġ Group indices of equal elements, then sort the resulting list of groups by the element they point to
Ṣ Sort; used to re-order the list of groups based on first occurrence instead
" Vectorize link between two arguments (the first occurrences and the group list)
; Concatenate
```
[Answer]
# [Pyth](https://pyth.readthedocs.io), 7 bytes
0-indexed.
```
{+VQxRQ
```
[Try it here!](https://pyth.herokuapp.com/?code=%7B%2BVQxRQ&input=%5B3%2C2%2C2%2C3%5D&debug=0) [Alternative.](https://pyth.herokuapp.com/?code=%7Bm%2BdxdQ&input=%5B3%2C2%2C2%2C3%5D&debug=0)
### How?
```
{+VQxRQ – Full program.
RQ – For each element...
x – Get all its indices.
+V – And apply vectorised concatenation.
Q – With the input.
{ – Deduplicate.
```
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), 10 bytes
**Solution:**
```
(!x),'.x:=
```
[Try it online!](https://tio.run/##y9bNz/7/X0OxQlNHXa/CytZYwQgIjf//BwA "K (oK) – Try It Online")
**Examples:**
```
(!x),'.x:=,17
,17 0
(!x),'.x:=1 1
,1 1 2
(!x),'.x:=1 0 1
(1 1 2
2 3)
(!x),'.x:=1 2 3 4
(1 0
2 1
3 2
4 3)
```
**Explanation:**
Evaluation is performed right-to-left. I still think this is golf-able further...
```
(!x),'.x:= / the solution
= / group input into dictionary, item!indices
x: / save as variable x
. / value of x (the indices)
,' / concatenate (,) each-both (') with
( ) / do this together
!x / the key of x (i.e. the items)
```
**Notes:**
* **14 bytes** without declaring `x`, `(,/)'+(!;.)@'=`, gave up with this approach...
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 8 bytes
```
u"@tG=fh
```
Try it at [MATL Online](https://matl.io/?code=u%22%40tG%3Dfh&inputs=%5B3%2C2%2C2%2C3%5D&version=20.6.0)
**Explanation**
```
# Implicitly get the input
u # Compute the unique values
" # For each unique value, N
@ # Push the value N to the stack
t # Duplicate N
G # Grab the input
=f # Get the 1-based indices of the elements that equal N
h # Horizontally concatenate N with the indices
# Implicitly display the result
```
[Answer]
# [Actually](https://github.com/Mego/Seriously), 24 bytes
```
;;╗⌠╝╜r⌠╜E╛=⌡░⌡M@Z⌠♂i⌡M╔
```
[Try it online!](https://tio.run/##S0wuKU3Myan8/9/a@tHU6Y96FjyaOvfR1DlFYNYc10dTZ9s@6ln4aNpEIOnrEAUSntmUCeI8mjrl//9oQx0FIDKKBQA "Actually – Try It Online")
Explanation:
```
;;╗⌠╝╜r⌠╜E╛=⌡░⌡M@Z⌠♂i⌡M╔
;; make two copies of input
╗ save a copy to register 0
⌠╝╜r⌠╜E╛=⌡░⌡M map over input:
╝ save the element in register 1
╜r indices for input
⌠╜E╛=⌡░ filter:
╜E element in input at index
╛= equals element for outer map (from register 1)
@Z swap, zip input with map result
⌠♂i⌡M flatten each element in zipped list
╔ uniquify
```
[Answer]
# [Julia 0.6](http://julialang.org/), 37 bytes
Thanks to Pavel for 1 byte off.
```
y->[[x;findin(y,[x])]for x=unique(y)]
```
[Try it online!](https://tio.run/##yyrNyUw0@59mm5Sanpn3v1LXLjq6wjotMy8lM0@jUie6IlYzNi2/SKHCtjQvs7A0VaNSM/Z/al4Kl0NxRn65QppGtLGOghEYGcdqIkQNzVF4OoaoXAUgMkIVMtIx1jHBVAVCsZr/AQ "Julia 0.6 – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 56 bytes
```
function(x)lapply(unique(x),function(y)c(y,which(x==y)))
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T6NCMyexoCCnUqM0L7OwNBXI14HLVWoma1TqlGdkJmdoVNjaVmpqav4vKMrMK9FIA/KTNQx1DHWMdIxBwgA "R – Try It Online")
---
This is my first attempt at codegolf, so any feedback is welcome!
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 40 bytes
Saved a byte thanks to Martin Ender.
```
KeyValueMap[{#,##&@@#2}&]@*PositionIndex
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zgq/DfO7UyLDGnNNU3sSC6WllHWVnNwUHZqFYt1kErIL84syQzP88zLyW14n9AUWZeSbSyjoKSgq6dgpKOQlq0cmysmoK@g0J1tbGOghEYGdfqKFQbmoNJHQVDGA2UgzJBanQUTBASYGW1/wE "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# JavaScript (ES6), 64 bytes
0 indexed
```
a=>a.map((v,i)=>a[-v]?a[-v].push(i):a[-v]=[v,i]).filter(x=>x[0])
```
Note, this assume input numbers being positive, so v > 0
**Test** slightly modified (1 indexed) to match the test cases
```
var F=
a=>a.map((v,i)=>a[-v]?a[-v].push(i+1):a[-v]=[v,i+1]).filter(x=>x[0])
test = [ // output 1 indexed
[3, 2, 2, 3],// | [[3, 1, 4], [2, 2, 3]]
[17], // | [[17, 1]]
[1, 1], // | [[1, 1, 2]]
[1, 1, 2], // | [[1, 1, 2], [2, 3]]
[1, 2, 3, 4], // | [[1, 1], [2, 2], [3, 3], [4, 4]]
[1, 1, 1, 1] // | [[1, 1, 2, 3, 4]]
]
test.forEach(t => {
x = F(t)
console.log(JSON.stringify(t)+ ' -> ' + JSON.stringify(x))
})
```
[Answer]
# APL NARS, 24 bytes, 12 chars
```
{∪⍵,¨⍸¨⍵=⊂⍵}
```
-4 bytes thanks to Adam
test:
```
f←{∪⍵,¨⍸¨⍵=⊂⍵}
⎕fmt f 3 2 2 3
┌2────────────────┐
│┌3─────┐ ┌3─────┐│
││ 3 1 4│ │ 2 2 3││
│└~─────┘ └~─────┘2
└∊────────────────┘
⎕fmt f 17
┌1──────┐
│┌2────┐│
││ 17 1││
│└~────┘2
└∊──────┘
⎕fmt f 1 1
┌1───────┐
│┌3─────┐│
││ 1 1 2││
│└~─────┘2
└∊───────┘
⎕fmt f 1 2 3 4
┌4──────────────────────────┐
│┌2───┐ ┌2───┐ ┌2───┐ ┌2───┐│
││ 1 1│ │ 2 2│ │ 3 3│ │ 4 4││
│└~───┘ └~───┘ └~───┘ └~───┘2
└∊──────────────────────────┘
⎕fmt f 1 1 1 1
┌1───────────┐
│┌5─────────┐│
││ 1 1 2 3 4││
│└~─────────┘2
└∊───────────┘
```
[Answer]
# [SWI-Prolog](http://www.swi-prolog.org), ~~165~~ 117 bytes
*-48 bytes thanks to [Prolog golfing tips](https://codegolf.stackexchange.com/questions/67023/tips-for-golfing-in-prolog).*
```
h(I):-I+[]-1.
[H|T]+R-N:-(select([H|A],R,[H|L],S),!,append(A,[N],L);append(R,[[H,N]],S)),O is N+1,(T+S-O,!;write(S)).
```
[Try it online!](https://tio.run/##PU3LCoMwELz7FektwYlgLRT05E1BFNSDEHKQNlTBVjEBL/13Gx8Ulp3ZmWF2msdhfHG99Ova0ZSFPHWF5L7niORbS7fkecipVoN6GGqlWKKExUyiYrignSb1edIYIpfIWHTeNiMS5HJLMRSk1yR3fdDarXiBS7TMvVHUet5qlDaaChGAXPcJJIR/3xaIf4I1Drb5ILe/vGck85yQO4QcXQ2D5e92GnptaAfS2Dc/ "Prolog (SWI) – Try It Online")
## Explanation
```
% The predicate that prints the grouped duplicates. It's a wrapper because we
% need some extra arguments to keep state:
enumerate_duplicates(Input) :- enumerate(Input, [], 1).
% In the golfed code, operators are used to represent this predicate.
% See https://codegolf.stackexchange.com/a/153160
% Go through the input, build up the result on the way and print it.
enumerate([Head|Tail], Result, Index) :-
(
% If our current Result already contains a list that starts with the
% current first element in our input, Head, NewIndexes will become the
% new "tail" of that list in our next result list:
select([Head|OldIndexes], Result, [Head|NewIndexes], NextResult),
% Don't backtrack before this if goals below this fail:
!,
% The as-yet-unknown NewIndexes above should in fact be the same as
% OldIndexes with our current Index appended:
append(OldIndexes, [Index], NewIndexes)
% Use ; instead of separate predicate rules.
% See https://codegolf.stackexchange.com/a/67032
;
% If our current Result did not already contain Head, append a new list
% for it with the current index:
append(Result, [[Head, Index]], NextResult)
),
% Increment our index counter:
NextIndex is Index + 1,
(
% And continue with the rest of our input:
enumerate(Tail, NextResult, NextIndex),
% Don't backtrack if the above succeeded:
!
;
% If Tail is no longer a multi-element list, we're done. Print:
write(NextResult)
).
```
[Answer]
# JavaScript (ES6), 68 bytes
0-indexed.
```
a=>a.map(p=(x,i)=>1/p[x]?b[p[x]].push(i):b.push([x,p[x]=i]),b=[])&&b
```
### Test cases
```
let f =
a=>a.map(p=(x,i)=>1/p[x]?b[p[x]].push(i):b.push([x,p[x]=i]),b=[])&&b
console.log(JSON.stringify(f([3, 4, 13, 9, 2]))) // [[3,0],[4,1],[13,2],[9,3],[2,4]]
console.log(JSON.stringify(f([3, 4, 13, 3, 2]))) // [[3,0,3],[4,1],[13,2],[2,4]]
console.log(JSON.stringify(f([3, 2, 2, 3] ))) // [[3,0,3],[2,1,2]]
console.log(JSON.stringify(f([17] ))) // [[17,0]]
console.log(JSON.stringify(f([1, 1] ))) // [[1,0,1]]
console.log(JSON.stringify(f([1, 1, 2] ))) // [[1,0,1],[2,2]]
console.log(JSON.stringify(f([1, 2, 3, 4] ))) // [[1,0],[2,1],[3,2],[4,3]]
console.log(JSON.stringify(f([1, 1, 1, 1] ))) // [[1,0,1,2,3]]
```
[Answer]
# PHP 4.1, 88 bytes
Yeah, it is pretty long.
This assumes a **default** `php.ini` file (`short_open_tag = On` and `register_globals = On`).
```
<?foreach($A as$k=>$v){!$b[$v]&&$b[$v]=array($v);$b[$v][]=$k;}print_r(array_values($b));
```
This presents the array in an human-readable way.
The values can be passed by POST, GET and COOKIE, inside the key "A".
---
For a modern version, one can use (90 bytes):
```
<?foreach($_GET[A]as$k=>$v){if(!$b[$v])$b[$v]=[$v];$b[$v][]=$k;}print_r(array_values($b));
```
The result is the same, except all values have to be passed over GET parameters inside the key "A".
[Answer]
# [Perl 6](https://perl6.org), ~~63~~ 61 bytes
```
*.pairs.classify(*.value).map({.key,|.value».key}).sort(*.[1])
```
[Test it](https://tio.run/##bVLLboMwELzzFXuoIpMaSyRRIhWl4gN67C3l4ICjWuVhYROVJHxZbvkx6jUJolUtC3tnx7PD2krU@bpvtIDjmqWRV7QwS6tMwLafM8VlrVmac63loSVzduR5I3xWcEXO7Eu09DJAtytGnc90VRvL24WJ3zux2AhtYAvEA9gtKSzcXCZgB4UdQiGFVWL3j1RCkRtuHOcxkBtuLDmh9zzu/@Sd1mLKwPA/hqs2lhoKo40p8eEJ1yWy7bpC0lR@tDGRv2uhDT/ydLOHtCqKqpQnAQQ@UvDhDKnt2ZvUxn2g8/AK3m2vIk/lvITnoXGZPMIi8g5Vfe9k8AqxLFVjaCy@lUiNyOBs7WCrT6Kugj3XFtrCmMbbesFz5OlT8IzOY8NljhaG@ELAIXC7BrcrhNZdZwWlDjIhVN4CPgcyFHVmfTYb/4dOq/7GhwPKvq/I6/of "Perl 6 – Try It Online") (0-based)
```
{sort *.[1],map {.key,|.value».key},classify *.value,.pairs}
```
[Test it](https://tio.run/##bVLRboIwFH3nK87DYtAVEtRoMuLCB@xxb46HCjVrBtJQMEPky3zzx1hvUcOWNQ3tPff03MNtlSizVV9rgePKT0InbzBJilRg07e6KCvM/G0Qs5wrtP6XaNjZP/KsFtcLRR1LMq613DeGZ3HmKy5L3fVWKqqErrCB6wDbBcPczkUMMxi2BAUMy9js76mYETdYW859EDdYG3LMbnna/8lbrfmYQeF/DFvtUWooTDbGxLsnWhfENuuSSGP5h42R/E2LbExDR9c7JEWeFwd5EnDxkWCKFonp35vUlf2gc@gC3k2vQkdl/IDnoXGpPGIeOvuivHXSe0UkD6quWCS@lUgqkaI1dqjVJ1EW3o5rA23wSPvm5l7onPv0KXjKZlHFZUYWhvjswiK4XrzrBYFx1xlBqb1UCJU1oMfgDkWt2ak/efwPG1f9jQ8HlHldodP1Pw "Perl 6 – Try It Online") (0-based same algorithm)
## Expanded:
```
# WhateverCode lambda (this is the parameter)
*\ # [3,2,2,3]
# get a list of Pairs (zero based index => value)
.pairs # (0=>3,1=>2,2=>2,3=>3)
# classify based on the values (unordered result)
.classify(*.value) # {2=>[1=>2,2=>2],3=>[0=>3,3=>3]}
# simplify the structure
.map({
.key, # the value
|.value».key # slip in the indexes
}) # ((3,0,3),(2,1,2))
# sort based on first index
.sort(*.[1])
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt/), ~~14~~ 9 bytes
0-indexed.
```
â £ð¶X iX
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=4iCj8LZYIGlY&input=WzEsIDEsIDEsIDFdCi1R)
```
â £ð¶X iX
â :Deduplicate
£ :Map each X
ð : Get 0-based indices of elements in the input
¶X : That are equal to X
iX : Prepend X
```
[Answer]
# [PHP 7.4+](https://www.php.net/), 71 bytes
\*73 bytes to quote the `$_GET` key and avoid Warnings.
Snippet: ([Demo](https://3v4l.org/UHQWO))
```
<?foreach($_GET[A]as$k=>$v){$b[$v][0]=$v;$b[$v][]=$k;}print_r([...$b]);
```
Based on rep, I assume [IsmaelMiguel](https://codegolf.stackexchange.com/users/14732/ismael-miguel) knows the best way to post php code in this community so I am building from [his foundation](https://codegolf.stackexchange.com/a/153621/88960). It is not clear to me [if `<?` is to be included/counted in my snippet](https://codegolf.meta.stackexchange.com/q/2424/88960). As this is my maiden post, I am happy for anyone to explain if there is any unnecessary syntax. p.s. I also read [Tips for golfing in PHP](https://codegolf.stackexchange.com/q/2913/88960) which [seems to me like a terrific candidate for migration to Meta](https://codegolf.meta.stackexchange.com/q/18047/88960).
The improvements made to Ismael's snippet are:
1. Unconditional assignment of the first element in each subarray (value overwriting)
2. [Splatpacking instead of `array_values()`](https://stackoverflow.com/q/57725811/2943403) to reindex the output.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 6 bytes
```
mS:¥¹u
```
[Try it online!](https://tio.run/##yygtzv6fm18erPOoqfF/brDVoaWHdpb@//8/OtpYxwgIjWN1og3NQYSOIYTUMQLTQCkdE6gISC4WAA "Husk – Try It Online")
[Answer]
# [Clean](https://clean.cs.ru.nl), ~~61~~ 60 bytes
```
import StdEnv,StdLib
$l=removeDup[[e:elemIndices e l]\\e<-l]
```
[Try it online!](https://tio.run/##TU7BCoMwFDvbr3gwj/XgHAzGvLmD4M1j7aGrb6PQ1qJV2M@v63Qbg0ASEkKkRmGDGfpZIxihbFDGDaOH1vcXu9BIjbqSVJcjmmHBanaM4Qk1mtr2SuIECJp3HZ4zzUPrxejJDpR1s5@gBEYSVlDYryg4jTY/bkQh/4kYf/W7R@HwF61NknBSxocO0s96eMqbFvcpZHUTqocVRsnNbKdf "Clean – Try It Online")
Output is 0-indexed
[Answer]
# [Kotlin](https://kotlinlang.org), 83 bytes
```
{it.mapIndexed{i,c->c to i}.groupBy({(a,b)->a},{(a,b)->b}).map{(a,b)->listOf(a)+b}}
```
## Beautified
```
{
it.mapIndexed { i, c -> c to i }
.groupBy({ (a, b) -> a }, { (a, b) -> b })
.map { (a, b) -> listOf(a) + b }
}
```
## Test
```
var f: (List<Int>) -> List<List<Int>> =
{it.mapIndexed{i,c->c to i}.groupBy({(a,b)->a},{(a,b)->b}).map{(a,b)->listOf(a)+b}}
data class Test(val input: List<Int>, val output: List<List<Int>>)
val tests = listOf(
Test(listOf(3, 2, 2, 3), listOf(listOf(3, 0, 3), listOf(2, 1, 2))),
Test(listOf(17), listOf(listOf(17, 0))),
Test(listOf(1, 1), listOf(listOf(1, 0, 1))),
Test(listOf(1, 1, 2), listOf(listOf(1, 0, 1), listOf(2, 2))),
Test(listOf(1, 2, 3, 4), listOf(listOf(1, 0), listOf(2, 1), listOf(3, 2), listOf(4, 3))),
Test(listOf(1, 1, 1, 1), listOf(listOf(1, 0, 1, 2, 3)))
)
fun main(args: Array<String>) {
for (c in tests) {
val o = f(c.input)
if (o != c.output) {
throw AssertionError("${c.input} -> $o != ${c.output}")
}
}
}
```
## TIO
[TryItOnline](https://tio.run/##fVJRa8IwEH7vr7iJDwmLZVVBEC042IMw2MP2B2JtXVhNJEndpOS3d0naWkXtUUruy33f3eXuR+ic8So4UgnZHNA7U3qx5jrGMIrBe2cohmVVMh3u6WHNt+lfui0ZSUZxAloAM+FOiuLwekIlomSDRzE1pD1uDHa01s2t5EeGKH7eGFMFW6opJDlVCr5SpdGR5sD4odBzOCcn4FBR6A7uCsNB4G61JStYQiMfQGNetAEnBMb+m2DSBnZXL1e4jYpsLMaY3NWKZjca0cyKPCZYwVuKTxv1klwVj3iX5Y77VFzTBKZ3ha6b7rzJVeape57+OvtabN4d48AOLCs47CnjiMqdmsNKSnpafGrJ+M4uX+lTZEICSuwu1KNtYWd+G+ysM5SEflfw+YplgAQ8LSEJ63255DnT31L8wkqpVGom+JuUQqLBsGyUjFv9oVdwWK1hBl0CE9R/U/0D)
[Answer]
# [Swift 4, 107 bytes](https://repl.it/@alexandermomchilov/Enumerate-an-array-grouping-duplicates)
... Yikes.
```
{a in Dictionary(grouping:a.enumerated()){$0.1}.sorted{$0.1.first!.0<$1.1.first!.0}.map{[$0]+$1.flatMap{$0.0}}}
```
Ungolfed:
```
let f = { (input: [Int]) -> [[Int]] in
return Dictionary(grouping: input.enumerated(), by: { $0.element })
.sorted { pairA, pairB in // Sort by order of first appearence (lowest offset)
return pairA.value.first!.offset < pairB.value.first!.offset
}.map { element, pairs in
return [element] + pairs.map{ $0.offset /* +1 */} // add 1 here for 1 based indexing
}
}
```
It's too bad that dictionary loses ordering, forcing me to waste so many characters on sorting back again. This sort of abuse of implicit closure arguments (`$0`, `$1`, ...) and implicit tuple members (`.0`, `.1`, ...) is uhhhhh not pretty.
[Answer]
# [Perl 5](https://www.perl.org/), 63 + 1 (`-a`) = 64 bytes
```
map$k{$_}.=$".++$i,@F;say$_.$k{$_}for sort{$k{$a}-$k{$b}}keys%k
```
[Try it online!](https://tio.run/##K0gtyjH9/z83sUAlu1olvlbPVkVJT1tbJVPHwc26OLFSJV4PIpGWX6RQnF9UUg3iJtbqgqik2trs1Mpi1ez//w0VDBWM/uUXlGTm5xX/1/U11TMwNPivmwgA "Perl 5 – Try It Online")
[Answer]
# [Ruby](http://www.ruby-lang.org), ~~54~~ 52 bytes
```
->a{a.map{|i|[i]+(0..a.size).select{|j|a[j]==i}}|[]}
```
This version allows nil (53 bytes):
```
->a{a.map{|i|[i]+(0...a.size).select{|j|a[j]==i}}|[]}
```
[Try it online!](https://tio.run/##dZHbCsIwDIbv9xS5U7GWVQVBmC8Sc1G1asXDcBPUdc8@m7nNTTEUQvL3aw693laPYhsti9FCZ1qedJw569DSsB9KqWVin2YgE3M06zRzB6fxQFFk89wh5QUGCDgRMC7PhAAEAHIm5FAA@rTyInmpMRKMqVkrV2Jq5rnOzY5VmH@QulhZTf0DPxj38Yu9mxx/4w3GgwmYUgurB2PP07Of8sDUqVa12q5W7emnVQpIGr3eA28/AIhvaQI9e/Z@3uMYLIbUCLtLnd4iCx/F3GP/U2bTUKrWgrx4AQ)
[Answer]
# [Factor](https://factorcode.org/), 56 bytes
```
[ dup members swap '[ _ dupd indices swap prefix ] map ]
```
[Try it online!](https://tio.run/##PU47CsJAFOxziunsAkZR0AOIjY1YhSBr8iKL2Y9vN2gUzx5f4ocp5sMMTK3K6Lg/7Le7zQoXYksNAsWAmjsR15ZsSQGeKcbOs7YRZ7LEqtEPFbWzAeskeWKGTDDDS/R0@SHBj7OvGirzfzo2@hxV62HInIgDwk15THIch7SCtpUeDoyxvKj1HQWMmEKGaZqKK53xLhAWsMr7puvf "Factor – Try It Online")
[Answer]
# [jq](https://stedolan.github.io/jq/), 31 bytes
```
[unique[]as$b|[$b]+indices($b)]
```
This really just uses a `jq` variable to allow the `indices()` function to reference data that's not readily available otherwise.
```
[ ] - makes the output valid JSON
unique[]as$b - stores each unique number in var "$b"
|[$b] - convert number to an array
indices($b) - get all matching positions in an array
+ - combined the arrays
```
[Try it online!](https://tio.run/##yyr8/z@6NC@zsDQ1OjaxWCWpJlolKVY7My8lMzm1WEMlSTMWqMBQRwGIjGIB "jq – Try It Online")
] |
[Question]
[
Using the following table ([source](http://theplanets.org/distances-between-planets/)) write some code that takes the names of two planets and returns the distance between them:
```
+-------------------+---------------+
| Planets | Distance (km) |
+-------------------+---------------+
| Mercury -> Venus | 50290000 |
| Venus -> Earth | 41400000 |
| Earth -> Mars | 78340000 |
| Mars -> Jupiter | 550390000 |
| Jupiter -> Saturn | 646270000 |
| Saturn -> Uranus | 1448950000 |
| Uranus -> Neptune | 1627450000 |
| Neptune -> Pluto | 1405380000 |
+-------------------+---------------+
```
Examples, input then output:
```
Mercury, Mars
170030000
```
```
Neptune, Jupiter
-3722670000
```
```
Earth, Earth
0
```
Note the negative sign there, as Jupiter comes before Neptune. They are also all integers.
Pluto doesn't have to be included (mostly because of a weird orbit which makes it hard to work out the distance - that distance given is my own calculation, but as Pluto is all famous now...).
By distances between planets I'm meaning orbits - I don't expect a date and working out where they are.
This is code golf, shortest code wins.
[Answer]
# CJam, ~~54~~ ~~51~~ 44 bytes
```
2{"X84VT:Z/3KD'Y->>6\ Ta "3/r26b93%=70be4}*-
```
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=2%7B%22X84VT%3AZ%2F3KD'Y-%3E%3E6%5C%20Ta%20%223%2Fr26b93%25%3D70be4%7D*-&input=Mercury%20Mars).
### Idea
We use a simple hashing function to identify all eight planets. By considering each name as the array of its code points, converting them from base 26 to integer and taking the result modulo 93 then modulo 8, **Mercury**, **Venus**, **Earth**, etc. map to **2**, **4**, **0**, **1**, **3**, **5**, **6** and **7**.
Now, we choose a point that lies 320,000 km behind Neptune and calculate the distances of all eight planets to that point. After dropping four trailing zeroes and reordering the planets so that they fit the 8 indexes from above, we obtain the array
```
[435172 427338 444341 372299 439312 307672 162777 32]
```
which, if we encode each integer in base 70, yields the following:
```
[
[1 18 56 52] [1 17 14 58] [1 20 47 51] [1 5 68 39]
[1 19 45 62] [ 62 55 22] [ 33 15 27] [ 32]
]
```
Remembering that two adjacent digits `(A B)` can be replaced with `((A-1) (B+70))`, we can modify the array from above so that all integers can be encoded as printable ASCII characters:
```
["X84" "VT:" "Z/3" "KD'" "Y->" ">6\\" " Ta" " "]
```
### Code
```
2{ e# Do twice:
"X84VT:Z/3KD'Y->>6\ Ta " e# Push that string.
3/ e# Chop it into chunks of length 3.
r e# Read a token from STDIN.
26b e# Convert from base 26 to integer.
93% e# Take the result modulo 93.
= e# Retrieve the chunk at that index.
70b e# Convert from base 70 to integer.
e4 e# Multiply by 10,000.
}* e#
- e# Subtract the two results.
```
[Answer]
# Python 2, ~~149~~ ~~147~~ ~~142~~ ~~138~~ ~~128~~ ~~123~~ 119 Bytes
Just uses a simple lookup to figure out which distances to use :) This defines an anonymous function, so to use it you'll need to give it a name.
*Thanks to Sp3000 for ideas that saved a bunch of bytes!*
```
lambda*x:int.__sub__(*[[0,5029,9169,17003,72042,136669,281564,444309]['MeVeEaMaJuSaUr'.find(k[:2])/2]for k in x])*~9999
```
Indented properly and ungolfed slightly for readability:
```
def f(*x):
d=0,5029,9169,17003,72042,136669,281564,444309
a,b=[d['MeVeEaMaJuSaUr'.find(k[:2])/2]for k in x]
print(b-a)*10000
```
Call like so:
```
f("Mercury","Mars") -> 170030000
f("Neptune","Jupiter") -> -3722670000L
```
[Answer]
# Prolog, ~~190~~ ~~174~~ 151 bytes
Thanks to Fatalize for guidance.
```
g(A,X):-sub_atom(A,2,2,_,B),member(B:X,[rc:0,nu:5029,rt:9169,rs:17003,pi:72042,tu:136669,an:281564,pt:444309]).
s(A,B,R):-g(A,X),g(B,Y),R is(Y-X)*10^4.
```
---
```
$ gprolog --consult-file src.pro
| ?- s('Mercury','Mars',R).
R = 170030000 ?
yes
| ?- s('Neptune','Jupiter',R).
R = -3722670000 ?
yes
| ?- s('Earth','Earth',R).
R = 0 ?
yes
```
[Answer]
# JavaScript (ES6), ~~115~~ 110 bytes
```
(x,y,g=k=>"Me0Ve5029Ea9169Ma17003Ju72042Sa136669Ur281564Ne444309".match(k[0]+k[1]+"(\\d*)")[1]*1e4)=>g(y)-g(x)
```
This is an anonymous function, so you will need to store it in a variable (`f=...; f("Earth", "Mercury")`) or use it as a parenthesised expression (`(...)("Earth", "Mercury")`.
That messy string is the first two letters of each planet, followed by that planet's distance from Mercury (divided by 10000, to save space). The inner function `g` does the following:
1. takes a name (`k`),
2. reduces it to the first two letters (`k[0]+k[1]`),
3. uses a regex match to find the corresponding distance from Mercury, divided by 10000 (e.g., the "Earth" regex looks like `Ea(\d*)`),
4. multiplies the value by 10000 (`1e4`) and returns the result.
By subtracting one Mercury-distance from the other, we get the distance between the planets.
[Answer]
# Java, ~~274~~ ~~272~~ 264 bytes (includes Pluto!)
```
void p(String p,String l){String q="MeVeEaMaJuSaUrNePl";int w=q.indexOf(p.substring(0,2))/2,e=q.indexOf(l.substring(0,2))/2,m=1,t=e,d[]={5029,4140,7834,55039,64627,144895,162745,140538};long h=0;if(w>e){e=w;w=t;m=-1;}for(;e-->w;)h+=d[e]*1e4;System.out.print(h*m);}
```
Input/Output:
```
p("Mercury","Mars") --> 170030000
p("Mars","Mercury") --> -170030000
p("Earth","Earth") --> 0
```
Spaced and tabbed:
```
void p(String p,String l){
String q="MeVeEaMaJuSaUrNePl";
int w=q.indexOf(p.substring(0,2))/2,
e=q.indexOf(l.substring(0,2))/2,
m=1,
t=e,
d[]={5029,4140,7834,55039,64627,144895,162745,140538};
long h=0;
if(w>e){
e=w;
w=t;
m=-1;
}
for(;e-->w;)
h+=d[e]*1e4;
System.out.print(h*m);
}
```
[Answer]
# Python, 118 bytes
```
n=lambda x:(5029,9169,17003,72042,136669,281564,444309,0)["VeEaMaJuSaUrNe".find(x[:2])/2]*10000
f=lambda a,b:n(b)-n(a)
```
`n` is a function that returns distance from Mercury.
The string `"VeEaMaJuSaUrNe"` is the first two characters of all planet names *except Mercury*. `find` cannot find Mercury so will return -1. -1/2 is still -1 so this is the last element in the tuple, which is 0.
Simple test code:
```
test = (
("Mercury","Venus",50290000),
("Venus","Earth",41400000),
("Earth","Mars",78340000),
("Mars","Jupiter",550390000),
("Jupiter","Saturn",646270000),
("Saturn","Uranus",1448950000),
("Uranus","Neptune",1627450000),
#("Neptune","Pluto",1405380000),
("Mercury","Mars",170030000),
("Neptune","Jupiter",-3722670000),
("Earth","Earth",0))
for a, b, expect in test:
print a, "->", b, "=", expect
assert f(a, b) == expect, f(a, b)
```
[Answer]
# APL, ~~97~~ ~~95~~ 85 bytes
```
{1E4×-/(0 5029 9169 17003 72042 136669 281564 444309[{⍵≡'Mars':4⋄'MVEmJSUN'⍳⊃⍵}¨⍵⍺])}
```
This creates an unnamed dyadic function that takes the origin planet as the left argument and the destination planet as the right.
You can [try it online](http://tryapl.org/?a=f%u2190%7B1E4%D7-/%280%205029%209169%2017003%2072042%20136669%20281564%20444309%5B%7B%u2375%u2261%27Mars%27%3A4%u22C4%27MVEmJSUN%27%u2373%u2283%u2375%7D%A8%u2375%u237A%5D%29%7D%u22C4%27Mercury%27f%27Mars%27&run)!
[Answer]
# [J--](http://esolangs.org/wiki/J--), 226 bytes
```
main{str q="MeVeEaMaJuSaUrNePl";int w=q.indexOf(a[0].subs(0,2))/2,e=q.indexOf(a[1].subs(0,2))/2,m=1,t=e,d[]={5029,4140,7834,55039,64627,144895,162745,140538};lg h = 0;@i(w>e){e=w;w=t;m=-1;}@f(;e--^^w;)h+=d[e]*10000;echo(h*m);}
```
I don't think this counts as I was making the language while the question was out, but it was mostly a test of how small I could compress Java code. This is *totally* and *completely* based off [DeadChex's answer](https://codegolf.stackexchange.com/a/53163/41711).
Here's how to use it:
```
$ j-- planets.j-- Mercury Mars
170030000
```
[Answer]
# Pyth - 59 53 bytes
Encodes the distance in unicode codepoints.
```
-Fm*^T4s<CM"·é•·Ä¨·∫öÌõøÔ±≥£óøßÆπ"x"MshrJtaN"@d14_Q
```
The name lookup is kinda cool because it loops around. Thanks to @Dennis for suggesting index 14 as a collision free lookup!
[Try it here online](http://pyth.herokuapp.com/?code=-Fm*%5ET4s%3CCM%22%E1%8E%A5%E1%80%AC%E1%BA%9A%ED%9B%BF%EF%B1%B3%F0%A3%97%BF%F0%A7%AE%B9%22x%22MshrJtaN%22%40d14_Q&input=%22Neptune%22%2C+%22Jupiter%22&debug=1).
[Answer]
# Bash, 140 bytes
```
bc<<<"(-`sed -e 's/,/+/;s/[abd-z]//g;s/Mc/0/g;s/V/5029/g;s/E/9169/g;s/M/17003/g;s/J/72042/g;s/S/136669/g;s/U/281564/g;s/N/444309/g'`)*10^4"
```
---
```
$ bash script.sh
Mercury, Mars
170030000
$ bash script.sh
Neptune, Jupiter
-3722670000
$ bash script.sh
Earth, Earth
0
```
[Answer]
## CoffeeScript, ~~183~~ 180 bytes
```
f=(a,b)->t=[d=0,5029,4140,7834,55039,64627,144895,162745];n='MeVeEaMaJuSaUrNe';t=(x=n[q='indexOf'](a[..1])/2)<(y=n[q](b[..1])/2)&&t[x+1..y]||t[y+1..x];d+=c*1e4for c in t;x>y&&-d||d
```
Unminified:
```
f = (a,b) ->
t = [d = 0, 5029, 4140, 7834, 55039, 64627, 144895, 162745]
n = 'MeVeEaMaJuSaUrNe'
t = if (x = n[q='indexOf'](a[..1]) / 2) < (y = n[q](b[..1]) / 2) then t[x+1..y] else t[y+1..x];
d += c * 1e4 for c in t
if x > y then -d else d
```
[Answer]
# Ruby, 168 bytes
```
a=ARGV.map{|e|e=='Mars'?3:%w(M V E m J S U N P).index(e[0])}
p 10000*(a[1]<=>a[0])*[5029,4140,7834,55039,64627,144895,162745,140538][a.min..a.max-1].inject(0){|r,e|r+e}
```
It's designed as a script to be run from command line, thus uses `ARGV`.
Run as
```
$ ruby planets.rb Mercury Mars
170030000
$ ruby planets.rb Neptune Jupiter
-3722670000
$ ruby planets.rb Earth Earth
0
$ ruby planets.rb Mercury Venus
50290000
$ ruby planets.rb Venus Earth
41400000
$ ruby planets.rb Mercury Mercury
0
$ ruby planets.rb Pluto Pluto
0
$ ruby planets.rb Mercury Pluto
5848470000
$ ruby planets.rb Pluto Mercury
-5848470000
```
[Answer]
# Haskell, ~~160~~ ~~158~~ 157 bytes
```
data P=Mercury|Venus|Earth|Mars|Jupiter|Saturn|Uranus|Neptune deriving Enum
d x=[0,5029,9169,17003,72042,136669,281564,444309]!!fromEnum x
x#y=(d y-d x)*10^4
```
Usage example:
```
*Main> Neptune # Jupiter
-3722670000
*Main> Mercury # Mars
170030000
```
How it works: I define a new data type `P` where the constructor names are the names of the planets. I also put it in the `Enum` class, i.e. I get a mapping to integers via `fromEnum` (in order of definition, starting with `Mercury` -> `0`). This integer can be used as a index for the distance list.
Edit: @Kritzefitz found two bytes to save and @Alchymist another one. Thanks!
[Answer]
# Julia, ~~206~~ ~~203~~ 190 bytes
```
(f,t)->t==f?0:(M(p)=p=="Mars"?4:findin("MVEmJSUN",p[1])[1];T=M(t);F=M(f);(T>F?1:-1)*sum([get(Dict(zip(1:8,[5029,4140,7834,55039,64627,144895,162745,0])),i,0)for i=T>F?(F:T-1):(T:F+1)])*1000)
```
This creates an unnamed function that accepts two strings and returns an integer. To call it, give it a name.
Ungolfed + explanation:
```
function planet_distance(p_from, p_to)
if p_from == p_to
# Return 0 right away if we aren't going anywhere
0
else
# Define a function to get the planet's order in the solar system
M(p) = p == "Mars" ? 4 : findin("MVEmJSUN", p[1])[1]
# Get indices for origin and destination
ind_from = M(p_from)
ind_to = M(p_to)
# Define a dictionary to look up distances by index
D = Dict(zip(1:8,[5029,4140,7834,55039,64627,144895,162745,0])
# Determine whether the distance will be positive or negative
# and the range over which we'll sum distances
if ind_to > ind_from
coef = 1
range = ind_from:ind_to-1
else
coef = -1
range = ind_to:ind_from+1
end
# Sum the distances between points
coef * sum([get(D, i, 0) for i in range]) * 1000
end
end
```
[Answer]
# Java, ~~257~~ 228 bytes
```
enum Z{Mercury(0),Venus(5029),Earth(9169),Mars(17003),Jupiter(72042),Saturn(136669),Uranus(281564),Neptune(444309),Pluto(584847);long r;Z(long x){r=x*10000;}static long d(String...s){return Z.valueOf(s[1]).r-Z.valueOf(s[0]).r;}}
```
`static long d(String...s){...}` solves the challenge. Input requires names of planets to match the enum's constants' names exactly. I love how java provides a string to enum conversion method for me <3
Usage:
`Z.d("Mercury","Pluto")` returns `5848470000`
`Z.d("Pluto","Mercury")` returns `-5848470000`
`Z.d("Uranus","Neptune")` returns `1627450000`
`Z.d("Mars","Pluto")` returns `5678440000`
[Answer]
# [C (gcc)](https://gcc.gnu.org/) pre-processor macro, 146 bytes
```
char*p="(3$,?2'+";D[]={0,5029,9169,17003,72042,136669,281564,444309,584847};
#define E(x)D[strchr(p,*x^x[1])-p]
#define f(s,t)(E(t)-E(s))*10000LL
```
[Try it online!](https://tio.run/##PY5ha4MwEIY/118R0pUl7hxRo624dl/ql9HuD4gDiakKnYQkQkfpb3exZTsO7njuvfdOBK0Q07IfxHlsJHozVvdD@9rtJtHV2ldbTOIneI@eX3C@L6vtlUHCogyyMM0gXDMWwzpiPIIwTlOHok2YpBw45zHLINnwDV/f8oW3bOSpHyQqyIXuS3dFdJoo8C9flzKsaKCqf8mJGLCUFMTSoCCGUj9kLg6HqSXzU8g3gB6Npd7VWyj3sj0RvDLIZbBDq/O5wYCczMLdDllKc6RGawjGNPdunudW0HfdD@Ru0RJ8lFqM@gcDPtbazKqZfkplx0E6@jGq3kr9NyhqbTuHH3X2nH4B "C (gcc) – Try It Online")
Another version, courtesy of ceilingcat, using Unicode, which seems to make TiO count weirdly:
# [C (gcc)](https://gcc.gnu.org/), 119 bytes
```
char*p="(3$,?2'+";
#define E(x)L"\0·é•‚èë‰â´ë•™°óùÒÑØúÒ¨ûïÚé≤è"[index(p,*x^x[1])-p]
#define f(s,t)(E(t)-E(s))*10000LL
```
[Try it online!](https://tio.run/##PY7BSgMxEIbP5ilCanGyZqXV42o97UW2vkCtsGSz28AaQpKFFfHmxUtLD@JFBQ@9qCD4RooP0PoCa7ZFh4EZ/vnnm@FhwXnTkYqXVSbwoXVGqmJvMmj4JDWBPiJwsM2O93d2SYQ6mcilEjiGmibkrPc5XXzN5t@3r8v54mX5fP@4unl/WL093f1MP2ZkJFUmatAsqM/rUX9MQz3@R@RgmaMQg6NhDJbSoN/zkSRNAe1lHFiGN42j6Aptaf@Xy4F0LfYZDnC3LDPCsLc5tsZhR2mEdeUsEEIjdI2QX8EXqVSwRhRAhsLwylwSRoapsa2rVU@FdpUSXj2ptHTC/A3i1LiJlze1ZTa/ "C (gcc) – Try It Online")
] |
[Question]
[
A [regular dodecahedron](https://mathworld.wolfram.com/RegularDodecahedron.html) is one of the five [Platonic solids](https://mathworld.wolfram.com/PlatonicSolid.html). It has 12 pentagonal faces, 20 vertices, and 30 edges.
[](https://i.stack.imgur.com/vx9WU.png)
Your task is to output the vertex coordinates of a regular dodecahedron. The size, orientation, and position of the dodecahedron are up to you, as long as it is regular.
You may output the coordinates in any order, and in any reasonable format.
If the edge length of your dodecahedron is \$a\$, then the coordinates should be accurate to at least \$a/1000\$.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
## Example output
This is one possible output. Your output does not have to match this.
```
{-1.37638,0.,0.262866}
{1.37638,0.,-0.262866}
{-0.425325,-1.30902,0.262866}
{-0.425325,1.30902,0.262866}
{1.11352,-0.809017,0.262866}
{1.11352,0.809017,0.262866}
{-0.262866,-0.809017,1.11352}
{-0.262866,0.809017,1.11352}
{-0.688191,-0.5,-1.11352}
{-0.688191,0.5,-1.11352}
{0.688191,-0.5,1.11352}
{0.688191,0.5,1.11352}
{0.850651,0.,-1.11352}
{-1.11352,-0.809017,-0.262866}
{-1.11352,0.809017,-0.262866}
{-0.850651,0.,1.11352}
{0.262866,-0.809017,-1.11352}
{0.262866,0.809017,-1.11352}
{0.425325,-1.30902,-0.262866}
{0.425325,1.30902,-0.262866}
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 15 bytes
```
SpherePoints@20
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P7ggI7UoNSA/M6@k2MHI4H9AEZDlEFwCpNKDUgtyEpNTo0PyIXwH96LMFIc0HSUuLiVdOyUupdj/AA "Wolfram Language (Mathematica) – Try It Online")
20 evenly spaced points on the surface of a unit sphere.
[![ConvexHullMesh[SpherePoints@20, MeshCellStyle -> Opacity@0.75, ViewPoint -> {2, 2, 2}]](https://i.stack.imgur.com/dfk2C.png)](https://i.stack.imgur.com/dfk2C.png)
The more obvious `PolyhedronCoordinates@Dodecahedron[]` is a little bit longer.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~31~~ 25 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
®X‚D3ãsãvy5t<;D>‚*¾š2Ý._«
```
Uses \$\sqrt{3}\$ as the distance of each vector from the origin \$\{0,0\}\$. Will output the following 20 vertex-coordinates:
$$[\{-1,-1,-1\},\{-1,-1,1\},\{-1,1,-1\},\{-1,1,1\},\{1,-1,-1\},\{1,-1,1\},\{1,1,-1\},\{1,1,1\},\{0,-\phi,-\phi-1\},\{-\phi,-\phi-1,0\},\{-\phi-1,0,-\phi\},\{0,-\phi,\phi+1\},\{-\phi,\phi+1,0\},\{\phi+1,0,-\phi\},\{0,\phi,-\phi-1\},\{\phi,-\phi-1,0\},\{-\phi-1,0,\phi\},\{0,\phi,\phi+1\},\{\phi,\phi+1,0\},\{\phi+1,0,\phi\}]$$
[Try it online.](https://tio.run/##yy9OTMpM/f//0LqIRw2zXIwPLy4@vLis0rTExtrFDiiidWjf0YVGh@fqxR9a/f8/AA)
**Explanation:**
```
®X‚ # Push pair [-1,1]
D # Duplicate it
3ã # Get all possible triplets using the cartesian power of 3
s # Swap so the [-1,1] pair is at the top again
ã # Also get all possible pairs using the cartesian power of 2
vy # Loop over each pair of [±1,±1]:
5t<; # Push the golden ratio: (sqrt(5)-1)/2
D # Duplicate it
> # Increase the copy by 1
‚ # Pair it together with the (sqrt(5)-1)/2
y * # Multiply the values in the pair to pair [±1,±1] at the same positions
¾š # Prepend a 0 to this pair
2Ý # Push list [0,1,2]
._ # Rotate the triplet that many times to the left
« # Merge it to the original list of [-1,1]-triplets
# (after which the list of 20 triplets is output implicitly as result)
```
---
I started with a port of [this SO C# answer](https://stackoverflow.com/a/10462220/1682559), but noticed (for \$r=\sqrt{3}\$ at least):
* \$±\frac{1}{\sqrt{3}}\times\phi\times\sqrt{3}\$ is simply \$±\phi\$
* \$±\frac{\frac{1}{\sqrt{3}}}{\phi}\times\sqrt{3}\$ is simply \$±(\phi+1)\$
[Try it online.](https://tio.run/##yy9OTMpM/W9aYmMd@t@4pCpCy7hES4crQoeLC8TTh/DsdP7/BwA)
[Answer]
# [Python](https://www.python.org), 73 bytes
```
x={3*(55,),(89,34,0)}
for s in(-1,1)*3:x|={(s*y,*z)for*z,y in x}
print(x)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3PStsq421NExNdTR1NCwsdYxNdAw0a7nS8osUihUy8zR0DXUMNbWMrSpqbKs1irUqdbSqNIGSWlU6lUBphYparoKizLwSjQpNiIFQc2HmAwA)
Same approach as @xnor (I think), i.e. flip signs and rotate coordinates random-ish-ly. Only, I'm being more simple-minded about it ;-)
#### Retired [Python](https://www.python.org), 103 bytes
```
*x,x[7],x[2]=6*[-55,55]
*y,y[11],_,_,y[2]=3*[-34,0,-89,34,0,89]
for a in x,y:*map(print,a,a[1:],a[2:]),
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY307UqdCqizWOBhFGsrZlWtK6pqY6paSyXVqVOZbShYaxOPBBWgiSNgZLGJjoGOroWljpghoVlLFdafpFCokJmnkKFTqWVVm5igUZBUWZeiU6iTmK0oVUskDSyitXUgVgHtRVmOwA)
Integer coordinates from @alephalpha / @xnor via @Arnauld.
[Answer]
# JavaScript (ES6), 88 bytes
Returns a set of strings, where each string is a triplet `x,y,z`.
This version takes inspiration from [xnor's approach](https://codegolf.stackexchange.com/a/262078/58563).
```
_=>(g=(s,x,y=x,z=x,k=y)=>k--?g(s.add(x+[,y,z]),k%4?z:-z,x,y,k):s)(g(new Set,55),0,34,89)
```
[Try it online!](https://tio.run/##FcpBCsIwEADAr3gRdnFTBFvQwraP8CgioUmDpiTiFk3y@aiHuc1Dv7VMr/tzVSEaW2euNx7AMQglypyo/HjOyINXanQgjTYG0u5CmcoVyW/bsfSq/Dt57AXBQbCfzdmu1HVIezq0dDxhnWKQuNhmiQ5mQKxf "JavaScript (Node.js) – Try It Online")
### Commented
```
_ => ( // main function ignoring its argument
g = ( // g is a helper function taking:
s, // s = output set
x, // x = 1st coordinate
y = x, // y = 2nd coordinate, or x by default
z = x, // z = 3rd coordinate, or x by default
k = y // k = counter, initialized to y
) => //
k-- ? // if k is not 0 (decrement afterwards):
g( // do a recursive call:
s.add( // add to the set:
x + [, y, z] // a stringified version of the triplet
), //
k % 4 ? z // rotate by putting z at the beginning
: - z, // or -z if k is a multiple of 4
x, y, // followed by x and y
k // pass the updated counter
) // end of recursive call
: // else:
s // stop and return the set
)( //
g(new Set, 55), // first call with x = y = z = 55
0, 34, 89 // second call with (x, y, z) = (0, 34, 89)
) //
```
---
# [JavaScript (V8)](https://v8.dev/), 108 bytes
*-5 bytes by using \$\phi\approx 89/55\$, as suggested by [alephalpha](https://codegolf.stackexchange.com/users/9288/alephalpha)*
*-3 bytes by scaling everything up (x55), as suggested by [xnor](https://codegolf.stackexchange.com/users/20260/xnor)*
A full program printing 20 triplets `x,y,z`.
```
[344,900,564,228].map(g=n=>n--&15&&g(n,j=0,print([4,6,8].map(i=>[0,55,89,34][v=n>>i&3]*(v&&n>>j++&1||-1)))))
```
[Try it online!](https://tio.run/##LYtBCsMgEAB/s9hmDRo1mMP6EfEgPQSFLpIGT/m7TaFzmsNMzT1/Xkdpp@x@jGisxU0pdKvFZfFpfucmdmIKLCVoB7ALxkoK21H4FNHiiv@sUIj36dBvaGyKnTiEAiY9RQe4vU4T6OuS@vFjjC8 "JavaScript (V8) – Try It Online")
## Encoding
We use the Cartesian coordinates based on the golden ration [as described on Wikipedia](https://en.wikipedia.org/wiki/Regular_dodecahedron#Cartesian_coordinates), but with a different scale.
Each triplet pattern is encoded with the following bit mask:
```
ZZ YY XX NNNN
| | | \__/
| | | |
| | | +--> number of triplets
| | +------> x
| +---------> y
+------------> z
```
where \$x\$, \$y\$ and \$z\$ are indices in the lookup array \$[0,1,\phi,\frac{1}{\phi}]\$.
This gives:
| Triplet pattern | x | y | z | N | Bit mask | As decimal |
| --- | --- | --- | --- | --- | --- | --- |
| \$(\pm 1,\pm 1,\pm 1)\$ | 1 | 1 | 1 | 8 | 01 01 01 1000 | 344 |
| \$(0,\pm\phi,\pm\frac{1}{\phi})\$ | 0 | 2 | 3 | 4 | 11 10 00 0100 | 900 |
| \$(\pm\frac{1}{\phi},0,\pm\phi)\$ | 3 | 0 | 2 | 4 | 10 00 11 0100 | 564 |
| \$(\pm\phi,\pm\frac{1}{\phi},0)\$ | 2 | 3 | 0 | 4 | 00 11 10 0100 | 228 |
[Answer]
# [Haskell](https://www.haskell.org/), 33 bytes
```
k=[0..19]
```
```
[[0^(x-y)^2|x<-k]|y<-k]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P9s22kBPz9AylivNNjraIE6jQrdSM86opsJGNzu2phJE/s9NzMxTsFXITSzwjVcoKMrMK1FI@w8A "Haskell – Try It Online")
## Explanation
So this answer uses a trick, which some may consider a loophole. Actually uses *two tricks*. So I'm going to explain how it works.
If the OP wants to patch this approach out of the challenge, I will delete my answer.
### Skew polyhedra
The exact definition of a polyhedron varies from person to person. Some circumstances require that a polyhedron be finite and not self intersect, this gives 5 regular polyhedra, some allow self intersection but still require finiteness, this gives 9 regular polyhedra, some times Euclidean tilings are considered as well giving 12.
However in the beginning of the 20th century Petrie and Coxeter discovered 3 regular polyhedra that hadn't been considered before. These were infinite polyhedra with flat non-intersecting faces, however they didn't have insides, so they hadn't been considered before. Pictured below is a section of the mucube, one of the three:
[](https://i.stack.imgur.com/jGQW4.jpg)
This discovery lead to a new definition of polytope (and by extension a new definition of polyhedron). This definition was first given by Branko Grünbaum in the paper *Regular polyhedra - old and new*, but has been used pretty extensively. Under this definition vertices (and edges) have exact locations, but the higher dimensional elements no longer needed to have exact interiors. A polygon is just a sequence of vertices pairwise connected by edges, such that you can reach any vertex from any other by following edges. A polyhedron is shape made out of polygons with exactly two meeting at every edge.
For example, classically a polygon needs to be "flat" meaning all of its vertices lie in a plane. However skew polygons can have vertices which lie in higher dimensional space. For example here's a 4-dimensional regular polygon:
[](https://i.stack.imgur.com/DSOQ0.gif)
*Image by Plasmath see [this page](https://polytope.miraheze.org/wiki/File:Pentagon-pentagram_coil.gif) for liscensing*
(We will come back to this particular polygon later)
The same can also be done with polyhedra. Instead of requiring that the vertices of a polyhedron lie strictly in 3D space with each face lying on a plane, you can have polyhedra whose vertices span 4 or greater dimensions, and whose faces are non-planar.
Lots of great work would be done with this definition. I'd especially like to point out the work of McMullen and Schulte. The have a paper classifying all the regular polyhedra in 3-space, which has been summarized in this excellent youtube video:
jan Misali, [there are 48 regular polyhedra](https://www.youtube.com/watch?v=_hjRvZYkAgA)
This definition is the one I am using in this answer.
Now the challenge says:
>
> Your task is to output the vertex coordinates of a regular dodecahedron. The size, orientation, and position of the dodecahedron are up to you, as long as it is regular.
>
>
>
So I just need to choose *a* regular dodecahedron. It turns out there are 28 distinct ways to realize the regular dodecahedron {5,3} in Euclidean space. The dodecahedron I chose is the its "Simplex realization". In general you can take any regular polyhedron with \$n\$ vertices and create an fully symmetric realization of it on a \$(n-1)\$-simplex. This is because all the symmetries of a polyhedron are permutations of its vertices. The symmetries of a simplex are *all* the permutations of its vertices. So when we place the vertices of a polyhedron on the vertices of a simplex every symmetry is possible. So this realization is always fully regular with maximum symmetry.
The dodecahedron has 20 vertices so that means the vertices of its simplex realization are the vertices of the 19-simplex. At first glance I've just made my problem much harder. The vertices of the 19-simplex centered at the origin are *nasty*, way worse than the vertices of the convex regular dodecahedron.
So here's where the second trick comes in. The vertices of a regular \$n\$-simplex are actually really simple if you express them in \$n+1\$ dimensions. If you place each vertex on an axis, all at the same distance from the origin, then permuting the axes is exactly the same as permuting the vertices. So this is fully regular, in fact its the same simplex its just lying on a weird hyperplane.
For example you can give the vertices of the triangle as:
$$
(1,0,0) \\
(0,1,0) \\
(0,0,1) \\
$$
This is a regular 2D triangle. This same trick comes up if you want to represent triangular (or hexagonal) coordinates. Instead of using 2D space and complicated square roots, you can represent them in 3D space as triplets of integers.
So returning to the problem at hand, the 19 simplex can be given in 20 dimensions as all permutations of \$(1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)\$. Its symmetries being all permutations of of the coordinate axes.
So in summary, I am giving the vertices for a 19-dimensional dodecahedron in 20 dimensional space.
I can't exactly render this in any way that is helpful. But its faces I can say its faces are the regular 4D pentagon shown earlier. If you want to try to imagine 12 of those in 20 dimensional space.
[Answer]
# [Python 3](https://docs.python.org/3.8/), 86 bytes
```
r=[]
for l in[[55]*3,[0,89,34]]*99:l+=(len(r)%11%-2|1)*l.pop(0),;r+=(*l,),
print({*r})
```
[Try it online!](https://tio.run/##JYtBCoMwEADvvsKLkN1ui2kqmBZfEnK0VFiSZfEi6tujbW8zDCPL/MnJ9aKl6BBi9c5acz2lELouoqPQUu/JPWJE7598GQyPySg01jbX@2YB@SZZTAv00rMiE1AlOqXZrKg7lD9/r59DOQA "Python 3.8 (pre-release) – Try It Online")
Outputs the golden-ratio vertices everyone is using, scaled up by 55, from the approximation of \$ \phi \approx 89/55\$ suggested by alephalpha.
The idea is to take the two vertices \$(1,1,1)\$ and \$(0,\phi,1/\phi)\$ and "randomly" negate entries and take cyclic permutations to reach all 20 vertices, then de-duplicate using sets. Each loop alternates between the two vertices, mutating it by moving the first entry to the back, and possibly negating that entry. Whether to negate is given by `i%11%2` on the `i`'th loop, which happens to hit all 20 vertices in not too many loops. The index `i` is actually tracked by the length of the list `l` of vertices we've generated so far.
---
# [Python 3](https://docs.python.org/3.8/), 82 bytes
```
*l,k=0,34,89,718230
while k:k-175or(l:=[55]*3);l+=l.pop(0)*(-1)**k,;k>>=1;print(l)
```
[Try it online!](https://tio.run/##BcFBCoUgEADQfadoqdMUmkmW2EWi5YdihhwkiH96e0/@z5lvF6TUCoyUDLoJw4KzDaMzzXte/Gtppd7OPhfFa9q9P8DpyF3iQbIoo0H1VgMQRtq2ZKOU634U61o/ "Python 3.8 (pre-release) – Try It Online")
To be golfed...
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), 130 bytes
```
A+B:-A=B;A is-B.
A*B*C*G*I*P:-A+P,B+P,C+P;A=0,B+G,C+I;B=0,A+I,C+G;C=0,A+G,B+I.
:-bagof([A,B,C],A*B*C*89*34*55,R),maplist(write,R).
```
[Try it online!](https://tio.run/##JcwxC8IwEAXgvb/CsV4uQdCCNnS4yxCyBVdxqKAl0JLSFvrz46HDg4/34M1LHvOg1z2VQopbTR1bOqRVs6kIGBx4CBBlUBFZ4lS01J3EXhwsi0kFsbfuZy9bMFWrX/2QP/WDkNE98f92vcH5Ak2D9yNO/Tymdav3JW1vKUwpXw "Prolog (SWI) – Try It Online")
Uses the approximation \$\phi \approx 89/55\$ then scaling the vertices by 55.
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata), 16 bytes
```
7Ƃ89\55:ŗÐçxŘ~?ŋ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHHBgqWlJWm6FtvMjzVZWMaYmlodnX54wuHlFUdn1Nkf7V5SnJRcDFUCUwoA)
```
7Ƃ89\55:ŗÐçxŘ~?ŋ
7Ƃ Push the list [1,1,1]
89\55 Push the number 89/55
:ŗÐ Pair with its reciprocal ([89/55,55/89])
ç Prepend zero ([0,89/55,55/89])
xŘ~ Non-deterministic rotation ([0,89/55,55/89],[89/55,55/89,0],[55/89,0,89/55])
? Non-deterministic choice ([1,1,1],[0,89/55,55/89],[89/55,55/89,0],[55/89,0,89/55])
ŋ Optionally negate each element
```
[Answer]
# Perl, 167 bytes
```
sub f{print"@_
"}sub g{$a=shift;map{$_[$_]*(!($a&1<<$_)*2-1)}0..~~@_-1}$p=.5+sqrt 5/4;f g $_,1,1,1 for 0..7;do{@v=((g $_,$p,1/$p,0)x2);f @v[$_..$_+2] for 0..2}for 0..3
```
[Try it online!](https://tio.run/##NU3dCoIwGL3vKZZ8hPNntpV0ocLeI2QYNRMq1zQJxnz1NaM4cDicH4666Fvu3PA6IWmU7h5jwMUqsIvRGmiq4drJsbg3yoA4gqijcB1Cs6FlCQJHLKXYbgmZZy5SakFVJI@Hpx5Rnu0LiVoEIqELkOw18s1Dce4Nn6ow/GagEpp52uI3w37AJ39CCIiY1f8Jsz@xc@4D)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~18~~ 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
...or 15 with repeats - remove `µQ`.
```
Ø+ṗ3µØpİƬŻṙJ×€jµQ
```
A niladic Link that yields a list of triples.
**[Try it online!](https://tio.run/##ASgA1/9qZWxsef//w5gr4bmXM8K1w5hwxLDGrMW74bmZSsOX4oKsasK1Uf// "Jelly – Try It Online")**
### How?
Produces the twenty triples as shown on [Wikipedia](https://en.wikipedia.org/wiki/Regular_dodecahedron#Cartesian_coordinates "Regular dodecahedron - Cartesian coordinates"):
$$(\pm 1, \pm 1, \pm 1)$$
$$(0, \pm \phi, \pm \phi^{-1})$$
$$(\pm \phi^{-1}, 0, \pm \phi)$$
$$(\pm \phi, \pm \phi^{-1}, 0)$$
```
Ø+ṗ3µØpİƬŻṙJ×€jµQ - Link: no arguments
Ø+ - [1, -1]
3 - three
ṗ - Cartesian power -> (+/-1, +/-1, +/-1) "CubePoints"
µ µ - monadic chain - f(CubePoints):
Øp - phi
Ƭ - collect up while distinct under:
İ - inverse
Ż - prefix with zero -> [0, phi, 1/phi]
J - range of length {CubePoints} -> [1, 2, 3, 4, 5, 6, 7, 8]
ṙ - rotate {[0, phi, 1/phi]} left by (vectorises) {that}
-> [[phi, 1/phi, 0], [1/phi, 0, phi], [0, phi, 1/phi], ...(8)]
€ - for each (rotation):
× - multiply by {CubePoints} (vectorises)
j - join {that list of lists of triples} with {CubePoints}
Q - deduplicate
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~53~~ 44 bytes
```
≔E²E³∨ι∧⊖λ⊘⁺⊖λ₂⁵υFυFE²⊞OΦιν×⊖⊗κ§ι⁰F¬№υκ⊞υκIυ
```
[Try it online!](https://tio.run/##ZY09DsIwDIV3TpHRkYKEQEydqiIEA7QCLhBaQ6OmSclPxe1D0rIgvDzbz35f3XJTay5DyK0VTwUnPsCakSQbRkoDgpFcNbDD2mCPymEDkjJy4HKMbSW9/fOuL88NXrR2sKVzMeJptnhoQ8BTMumXVHnblgMa7rSBvZAOJ6aKLzfR42/6Tvu7jNqlxNwdVYPvdL2aIHPuOWIL7ZUDz0iX1gkxD9miMiI6BbfRpjQLISxH@QE "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Uses the formula from [this Math.SE answer](https://math.stackexchange.com/a/141653/30622).
```
≔E²E³∨ι∧⊖λ⊘⁺⊖λ₂⁵υ
```
Get the points `[1/ϕ, 0, ϕ]` and `[1, 1, 1]`.
```
FυFE²⊞OΦιν×⊖⊗κ§ι⁰F¬№υκ⊞υκIυ
```
For each point, rotate it around the axis `x=y=z`, and also reflect the rotated point in the `xy` plane, and save and process any new points thus found.
```
Iυ
```
Output the final dodecahedron.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 55 bytes
```
20.times{|j|p ~0**j*(1.309-k=j/10),1.618**k*1i**j*=0.4}
```
[Try it online!](https://tio.run/##dY/dboMgAIXvfQrSq40AAk5Ks/gkxgu0LtHW6vxZ7Gr36g7dZv1hMSYkH@ecj7IJr33PKamTLK5uXdoV4ItCmMInRhx6wCcvtRl9RowIJiE8QZYM1KPk5d4XTV2BnWVFeVaoMgZVpM7xEXyocxNX4K3MM/CuT3WSXxCo8rLWMLyCTxDleXlMLqqOd1aru7jgUgg4jlDHgdzyfb2/F45ElFCE/64EyPL1NHcd7qLRkPIlxYww5rhc56SmbP8PxmY@lWNjO0X6Gw6blcXIRnGl8HiZOYZNua250YwSISU7ME2H/THz2/5z@@G8pNKlwmWjlTGGTblpDa/mZj6zYryIrn3wcnf2DjPBa2RwnbAVkEwVty7pFApR5CWvBfBxZLdI6T@02@DefwM "Ruby – Try It Online")
Golfed version using decimal approximations instead of exact formulas (I can't use fractions as Ruby would interpret using integer arithmetic.) Dimensions are now half the ones given in the wolfram page, instead of double, to avoid `j/10*4`. The polar vertices are now listed before the equatorial vertices, to enable the distance from the `z` axis to be calculated as `1.618**k` (1 or 1.618)
I also deleted the `[]` to save 2 bytes, although this impacts readability of the output.
# [Ruby](https://www.ruby-lang.org/), ~~85~~ 63 bytes
```
20.times{|j|p [~0**j*z=5**0.5-1+j/10*4,[8/z,4].max*1i**j*=0.4]}
```
[Try it online!](https://tio.run/##dZLdboIwFMfveYrGy64t5xRbaxafhHhRkCUYEQa4oLK9uituU8EuTZMmv/P/aHLqQ3K8XCSINi@y5txv@4rEX0Dplp5WilIQiuPLNkSgcxab8MTma1HYjmI@zKxAzNefl@rQNmQWBGlZVLbOSJPaXbYhH3Z3yBryVpcFeXevNi/3jDRl3TqYHMmJpGVZb/K9bbNZ0DkzqaXRmqLQaCCKQhnEMYpooSPDQADjfyNrFsQuW6pIKuYmYAlyTDkKxEhJpzOO4uIfzP38Zs697sDcGR5PKaOQp4qTCvef@WXcp3tu7m0GQhuDS3R0yL9qft1/pu@dx9Qo0Aqvrbwy7tPd0vgk7qHPgzEfSad9@Dj34R9@wqfI0/WGg2GBq3Of95YlLF3lr27leRp2zLqbhJ1b6G8 "Ruby – Try It Online")
The coordinates given in the question are `x,y,z` with the dodecahedron's 5-fold rotational symmetry axis aligned with the `z` axis (It's actually a 10-fold axis for the rotate-and-flip operation.). This program outputs the same coordinates as the ones in the question, but in the format `[z,x+yi]` and scaled. First all the equatorial vertices are output, and then the polar vertices.
`~0**j` alternates the sign of the `z` coordinate as the `x` and `y` coordinates cycle through the 1/10th of a circle rotations. (`-1**j` would not work because unary minus has lower priority than raising to a power in Ruby.)
Exact coordinates in terms of the golden ratio are given at [the wolfram page](https://mathworld.wolfram.com/RegularDodecahedron.html) in formulas 1 and 2. The alternate coordinate system used in other answers is given a little below them on the same page, as well as in wikipedia. This code uses double the scale used in the Wolfram page, to avoid the division by 2 required to calculate the golden ratio. The footer in TIO link scales the coordinates given in the question and moves the `z` coordinate to the beginning for comparison. You still have to squint a bit because I've sorted the coordinates given in the question by `z` value, whereas the above code generates the vertices in an intercalated order with alternating sign of the `z` value.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 24 bytes
```
{+K^_BT3*VM*K.<L+tB.n3Z3
```
[Try it online!](https://tio.run/##K6gsyfj/v1rbOy7eKcRYK8xXy1vPxke7xEkvzzjK@P9/AA "Pyth – Try It Online")
Uses the same \$\varphi\$ based coordinates that everybody else is using, just multiplied by 10, that is, \$[\pm 10,\pm 10,\pm 10], [\pm 10\varphi, \pm \frac{10}{\varphi}, 0], [0, \pm 10\varphi, \pm \frac{10}{\varphi}], [\pm \frac{10}{\varphi}, 0, \pm 10\varphi]\$.
But there's a really neat simplification here, which is that after I had the integer coordinates, I could use them as the signs for the other coordinates, just adding the need to deduplicate at the end since \$0=-0\$.
### Explanation
```
_BT # bifurcate 10 on negation (gives us [1,-1])
^ 3 # get all possible triplets
K # assign this list to K
.n3 # phi
tB # bifurcated on subtracting 1
+ Z # append 0 to the pair
.<L 3 # map [0,1,2] to cyclic rotation on this list
*K # get the cartesian product of these rotations with K
*VM # map over vectorized multiplication
+K # add K to this list
{ # deduplicate to eliminate repeat coordinates
```
[Answer]
# [Scala](https://www.scala-lang.org/), 226 bytes
Golfed version. [Try it online!](https://tio.run/##XU/BasMwDL3nK3SUmsRLCru0yaAf0FOPYxTFcVN3Sew6ZlBCvj2zyxhsOoj3xNN70iS551UP1jgPUyRiYH8V58Q0NyU9HFmPMCcArbrAEAiy66bdwTl@vJ@802P3QTXM6xf3YOuTumNeZiUlkXc1Tnfn8ZXykl62ECtBvBg3c5XbfRObDG15aNW3ELc5azJJlKZPma3yf/q/UqJwr50lT@p3VL890abLmg12aUm0RBEWokh3Z6K9rvICvIHtj5cVrTMWdQi1wvOnCjAYh1jF8oo2POn7kVaAJVnWbw)
```
val p=Seq(-1,1)
val g=(sqrt(5)-1)/2
((for{a<-p;b<-p;c<-p}yield Seq(a,b,c))++(for{p<-((for{a<-p;b<-p}yield Seq(a,b)).map{case Seq(a,b)=>Seq(a*g,b*(g+1))}.map(0.0+:_));i<-0 to 2}yield p.drop(i)++p.take(i))).foreach(println)
```
Ungolfed version. [Try it online!](https://tio.run/##lVJLT8MwDL73V/iYsq1sSFwqhsSdSYjHCaHJa7MukCUhMUgT6m8vblf64HHg@MX@HnYcMtRYVWrvrCcINUr2SLtkHUV28ywzghUqAx8RQC63sGcg0BchhSvv8fB4R16Z4ilO4cEogmXTCfCOGhwqzw/XKpCYLaawiLsSk5yWFLi8tb7lACBczBpaizffcDbCJRyU1PnRAKewmUIWj9z/p/9DrxcrrM6luUVSliVFePUkzmOY8UxwCme/9a3eNPGQSuY3bZImEW/XdXkyDHJgB8vLFsHJUIpr/CCGISbsfIxX9hN76aTJe8O/09QpxDyZQ5rCuh/TW0Lq@cPVNZ9Zb2tk0hZVXZkD2XYVX5usSUnurRMqhsnkiAlfJOPOdKsM6vv@ILrbYMIwUEMYNSccUGK2E45vkLSpNcuojKrqEw)
```
import scala.math._
object Main {
def main(args: Array[String]): Unit = {
val pair = List(-1, 1)
val triplets = for {
a <- pair
b <- pair
c <- pair
} yield List(a, b, c)
val pairs = for {
a <- pair
b <- pair
} yield List(a, b)
val goldenRatio = (sqrt(5) - 1) / 2
val goldenRatioMultipliedPairs = pairs.map {
case List(a, b) => List(a * goldenRatio, b * (goldenRatio + 1))
}
val prependedPairs = goldenRatioMultipliedPairs.map(0.0 :: _)
val rotatedPairs = for {
pair <- prependedPairs
i <- 0 to 2
} yield pair.drop(i) ++ pair.take(i)
val finalTriplets = triplets ++ rotatedPairs
finalTriplets.foreach(println)
}
}
```
[Answer]
# Perl, ~~139~~ ~~137~~ 135 bytes
```
sub p{print"@_
"}sub g{($x)=@_;map{$_[$_]*(1-(4*$x>>$_&2))}1..3}p g$_,(55)x3 for 0..7;map{@v=(g$_,89,34,0)x2;p@v[$_..$_+2]for 0..2}0..3
```
[try it online](https://tio.run/##K0gtyjH9/7@4NEmhoLqgKDOvRMkhnkupFiSQXq2hUqFp6xBvnZtYUK0SH60SH6ulYairYaKlUmFnpxKvZqSpWWuop2dcW6CQrhKvo2FqqllhrJCWX6RgoKdnDtbmUGarAZKzsNQxNtEx0Kwwsi5wKAMapaenEq9tFAtVbFQLJIz//wcA)
] |
[Question]
[
A good resolution for 2015 is to live more sustainably. We'll start by recycling. Recycling code, that is!
Your task is to print the number `2015` to STDOUT, with or without trailing newline (and *only* that). However, you have to do so by *recycling* some old code from PPCG. Here is how that works:
* Pick any *answer* posted on CodeGolf.SE before 2014-12-16 00:00:00Z (the day I posted this in the sandbox). *Exception:* You may not use any answers from [last year's New Year's challenge](https://codegolf.stackexchange.com/q/17005/8478).
* Choose *one* code block from that answer (not an inline code snippet, it has to be a on its own paragraph). This block must be advertised as actual code, e.g. you cannot use test cases or example output which happen to use monospace formatting.
* Rearrange the *characters* in that code block to form your submission for this challenge. You may only change the order, not add or remove any characters. This includes newlines.
* You must be able to show that the original source block is syntactically valid in your language. In the best case you can do this by showing that it runs without compile-time or run-time errors. So while the original code may have been Java, you could use it for a Whitespace answer (as every file is valid in Whitespace), but probably can't use it for a Python answer (as the original won't be valid Python syntax).
Note that your answer must ignore all input and external state (including the actual current date). It *may* read from STDIN, say, as long as it doesn't crash if it's empty, and produces the same output for all possible contents of the stream.
Your resulting code has to be a full program (not a function, nor a snippet which assumes a REPL environment).
This is code golf, so the shortest answer (in *bytes*) wins.
# Leaderboards
I'm sure this will play out very differently in different languages. So the following Stack Snippet generates 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
```
```
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 getAnswers(){$.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(e){answers.push.apply(answers,e.items);if(e.has_more)getAnswers();else process()}})}function shouldHaveHeading(e){var t=false;var n=e.body_markdown.split("\n");try{t|=/^#/.test(e.body_markdown);t|=["-","="].indexOf(n[1][0])>-1;t&=LANGUAGE_REG.test(e.body_markdown)}catch(r){}return t}function shouldHaveScore(e){var t=false;try{t|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(n){}return t}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading);answers.sort(function(e,t){var n=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0],r=+(t.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0];return n-r});var e={};var t=1;answers.forEach(function(n){var r=n.body_markdown.split("\n")[0];var i=$("#answer-template").html();var s=r.match(NUMBER_REG)[0];var o=(r.match(SIZE_REG)||[0])[0];var u=r.match(LANGUAGE_REG)[1];var a=getAuthorName(n);i=i.replace("{{PLACE}}",t++ +".").replace("{{NAME}}",a).replace("{{LANGUAGE}}",u).replace("{{SIZE}}",o).replace("{{LINK}}",n.share_link);i=$(i);$("#answers").append(i);e[u]=e[u]||{lang:u,user:a,size:o,link:n.share_link}});var n=[];for(var r in e)if(e.hasOwnProperty(r))n.push(e[r]);n.sort(function(e,t){if(e.lang>t.lang)return 1;if(e.lang<t.lang)return-1;return 0});for(var i=0;i<n.length;++i){var s=$("#language-template").html();var r=n[i];s=s.replace("{{LANGUAGE}}",r.lang).replace("{{NAME}}",r.user).replace("{{SIZE}}",r.size).replace("{{LINK}}",r.link);s=$(s);$("#languages").append(s)}}var QUESTION_ID=43048;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/;var NUMBER_REG=/\d+/;var LANGUAGE_REG=/^#*\s*([^,]+)/
```
```
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>Language<td>Size<tbody id=answers></table></div><div id=language-list><h2>Winners by Language</h2><table class=language-list><thead><tr><td>Language<td>User<td>Score<tbody id=languages></table></div><table style=display:none><tbody id=answer-template><tr><td>{{PLACE}}</td><td>{{NAME}}<td>{{LANGUAGE}}<td>{{SIZE}}<td><a href={{LINK}}>Link</a></table><table style=display:none><tbody id=language-template><tr><td>{{LANGUAGE}}<td>{{NAME}}<td>{{SIZE}}<td><a href={{LINK}}>Link</a></table>
```
[Answer]
# GolfScript, 9 bytes
The [original answer](https://codegolf.stackexchange.com/a/31718/30688) (dibs!) is also in GolfScript, which is how I know it is syntactically valid. I tested on <http://golfscript.apphb.com/> .
```
2015}{.**
```
I despise the use of languages designed for golfing, but I had to win this challenge, so I betrayed my values by posting this answer. I don't know what most of the characters do in this language, but I once inadvertently learned, while skimming a GolfScript answer, that an unmatched `}` comments out the rest of the program. This allowed me to ignore the rest of the characters.
[Answer]
# Befunge-93, 2085 bytes
I thought I'd have fun and go meta by [recycling the best of the recycled](https://codegolf.stackexchange.com/a/26880/21487). Not going for any awards for brevity here.
```
+2012+1+1e1 or b+bbv+b+NN
"a"""""
p((('?'.ord-' '.ord )/(1.0/'A'.ord)).to_i)
<<id
1
!
_" fabaaaca"-.-.-.-.+"O"2::++p
aa
AaAAaAAaAAaAAaA
eEe ddd OoOOoOOoOOoOOoOOoOOoOOoOOoOOoO ddD Ccc eEE
ccc LLl
SssSss LLl
SsS LLl
SsSSsSSsSSsS LLl
cccccc
mMm
+ + a pppp pppp y y n n eeeee + + y y eeeee a rrr "
+ + a a p p p p y y nn n e + + + y y e a a r r "
+++++ aaaaa pppp pppp y n n n eee + + + y eee aaaaa rrr "
+ + a a p p y n nn e + + y e a a r r
+ + a a p p y n n eeeee + + y eeeee a a r r "
Hope to see another round of awesome programming puzzles and code golf challenges
===============================
"" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" " ' ' ' ' '
Big char dump below (will clean up if there's more languages to squeeze in):
$$$$$$$()++++++++++++++++++++++++++++--------------------------/////:::;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;<>>>>>??AAACCDDEEEFHHLLMMMMM
NOOOOOOOOOOORRRRRRRRRSSSUUUUV[\]___aaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
bbbbbbbbbbbbbbbbbbbbbbbcccccccccccccddddddddddddddddddddddddddddddddddddddd
ddddddddddddddddddddddddddddddddddddddddddddddddddeeeeeeeeeeeeeeeeeeeeeeeee
eeeeeeeeeeeeeeeeeeffffffffffghhhhhhiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiilll
llllllllllmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnnnnnnnnnnnnnnnnn
nnnnnnnnnnnnnoooooooooooooooooooooooooooooooooooooooooooooooooppppppppppppp
ppppppppppppprrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrsssssss
ssssssssssssssssssssssssstttttttttttttttttttttttttttttttttttttttttttttttttt
ttttttttttttttttttttttttttttttttttttttttttuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
uuuuuuuuuuuuvvvvvvvvwwxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
yyyyyyyyyyzz{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}
"""
one=1
print(int(ord('A')/(one/(ord(' ')-one))))
id
"mOO"
```
This is actually also a polyglot for 5 languages: [Befunge-93](http://www.bedroomlan.org/tools/befunge-93-playground), [oOo Code](http://esolangs.org/wiki/OOo_CODE), [Pyth](https://github.com/isaacg1/pyth), Python 3 and Ruby. However, since the original code is only syntactically valid for Befunge-93, I'm only counting that.
Unfortunately the original code had only one pair of `[]` and too many `.`s, so I wasn't able to actually fit Brainfuck in (hence the oOo Code).
---
# Notes
This turned out to be surprisingly restrictive, because:
* The full set of digits available is `001111111222`, requiring the use of `ord` for Ruby and Python. In particular there's no `5`, which turned out to be a pain for Pyth.
* The lack of `@` meant that `p` needed to be used to place an `@` for Befunge.
* The lack of `*` meant that we had to multiply by dividing by the inverse of a number. Fun.
## Befunge-93
The Befunge program is
```
v
1
!
_" fabaaaca"-.-.-.-.+"O"2::++p
```
where we've skipped the useless instructions. We encode each digit as the difference in ASCII values between chars, specifically `cabf` vs. `a`.
## oOo Code
The corresponding BF is
```
>><->>->>>><>+++++[>++++++++++<-]>.--.+.++++.>>[>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>->>>>>>>>>>>>>>>>>>>>>>->>>>>>>>>>>>>>>>>><;;;;;;;;;;;;;;;;>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>->>>]
```
, of which the only relevant part is
```
+++++[>++++++++++<-]>.--.+.++++.
```
## Pyth
Pyth only executes the first line, so
```
+2012+1+1e1 or b+bbv+b+NN
```
Note that Pyth uses an prefix notation, so the first part of the line is actually
```
2012 + (1 + (1 + (1 % 10)))
```
(*Note: `e` means `%10`*)
Due to the nature of Pyth, this is automatically printed. The rest of the line is valid Pyth, but the preceeding space before the `o` suppresses the automatic printing.
## Python 3
The majority of the Python code is commented out using strings, especially a large triple-quoted string in the middle. Ignoring a few stray strings, we have:
```
+2012+1+1e1 or b+bbv+b+NN
"""
...
"""
one=1
print(int(ord('A')/(one/(ord(' ')-one))))
id
```
The first and last lines are syntactically valid, but do nothing. The middle two lines print what we need.
## Ruby
The Ruby code is similar, but we're using a heredoc instead of a triple quoted string to comment out most of the program. Ignoring some stray strings, we have:
```
+2012+1+1e1 or b+bbv+b+NN
p((('?'.ord-' '.ord )/(1.0/'A'.ord)).to_i)
<<id
...
id
```
Once again, the first line is syntactically valid, but does nothing. The second line prints what we need.
[Answer]
# CJam, 12 bytes
```
T~mp[]!_1+oE^
```
The [Unscramble the Code](https://codegolf.stackexchange.com/questions/40935/unscramble-the-source-code-robber-thread-for-cracking-attempts/41002#41002) topic is a really good source for random number printing. This one was quite fun to piece together :)
```
T~ bitwise not of 0 is -1 [-1]
mp replace with 0 as -1 is not prime [0]
[]! not of an empty array (falsy) is 1 [0, 1]
_ copy that 1 [0, 1, 1]
1+ add 1 [0, 1, 2]
o output top of stack [0, 1] 2
E push 14 [0, 1, 14] 2
^ bitwise xor [0, 15] 2
(CJam implicitly prints stack afterwards) [] 2015
```
---
## Bonus answers
[14 bytes:](https://codegolf.stackexchange.com/questions/40932/unscramble-the-source-code/41682#41682)
```
36.e8 .79e2%15
```
[19 bytes:](https://codegolf.stackexchange.com/questions/40932/unscramble-the-source-code/41624#41624)
```
0_*1_)@@{_%\_)*\};5
```
[Answer]
# Ostrich, 198
I'm excited to get an Ostrich answer out; I don't care how long it is. :P (this is [version 0.5.0](https://github.com/KeyboardFire/ostrich-lang/releases/tag/v0.5.0-alpha), by the way)
```
{: rotate ( circ n -- )
neg swap change-circular-start
IN: 1 9 [a,b] <circular> dup 6 rotate >array .
{ 4 5 6 7 8 9 1 2 3 }
IN: 1 9 [a,b] <circular> dup 3 rotate >array .
7 8 9 3 4 6 };2 n15
```
[Original](https://codegolf.stackexchange.com/a/18567/3808):
```
: rotate ( circ n -- )
neg swap change-circular-start ;
IN: 1 9 [a,b] <circular> dup 6 rotate >array .
{ 4 5 6 7 8 9 1 2 3 }
IN: 1 9 [a,b] <circular> dup 3 rotate >array .
{ 7 8 9 1 2 3 4 5 6 }
```
All I changed was the following:
* Wrapped everything other than `2 n15` in a block (`{}`) that is immediately popped (`;`).
* Stuck `2 n15` at the end. `2` pushes a `2`, `n` pushes a `0`, and `15` pushes `15`, which ultimately becomes `2015` when output.
This actually helped me find a bug: `2n15` doesn't work for some reason (it prints `215`), but both `2 n15` and `2n 15` work. I'll have to figure out why that is....
Here's the search query I used to find this perfect code sample:
>
> created:..2014-12-16 is:answer code:"2" code:"0" code:"1" code:"5" code:"]" code:";"
>
>
>
[This answer](https://codegolf.stackexchange.com/a/6703/3808) would work for 140, but I'm going to see if I can go smaller....
[Answer]
# JavaScript, 26 bytes
[Original](https://codegolf.stackexchange.com/a/40972/4020):
```
alert(998|(103>8>0&41>-0))
```
Recycled:
```
alert(4030>>(998>1|8&1-0))
```
It just shifts 4030 one bit to the right.
[Answer]
# CJam, 14 bytes
This one is a bit tricky, so I had to post it even though its a bit long. [Original answer](https://codegolf.stackexchange.com/questions/40935/unscramble-the-source-code-robber-thread-for-cracking-attempts/41885#41885) is also in CJam, so its valid.
Original answer:
```
92e8.17 5e6.3%
```
Recycled 2015:
```
9.68e3 .7e2%15
```
**How it works**
```
9.68e3 is 9680
.7e2 is 70
9680 70% is 9680%70 = 20
15 is 15
```
So the stack contains `20` and `15` which are printed one after another, printing 2015
[Try it online here](http://cjam.aditsu.net/)
[Answer]
# Marbelous, 54 bytes
### Boring answer (54 bytes)
```
32303135
:R
:Q
++003333333567QQRR}0
```
(followed by a ton of trailing newlines to equal 54 bytes)
[Original Answer](https://codegolf.stackexchange.com/a/37509/29611)
The main board simply drops marbles representing each of character of `2015`. `R` and `Q` boards are defined, but never used.
### Alternative answer (92 bytes)
```
3W!!?0]]>W/\&0&1@1@0@0
]]>W/\&0&1@1@0@0
@1 @0
03 02
\\ //
32+A
Dp
```
[Original Answer](https://codegolf.stackexchange.com/a/42334/29611)
Spaces as blank cells should be checked. This first prints `2` (0x32), then prints `0x03+0x02+0x0A=0x0F=15` as a three digit decimal (`015`). The first three lines do nothing.
[Test answers here.](https://codegolf.stackexchange.com/a/40808/29611)
[Answer]
## Pyth, 25
<https://github.com/isaacg1/pyth>
```
J6ifqT++2010/JJ4U*2^TJ^TT
```
[Here](https://codegolf.stackexchange.com/a/42314/31625) is the original answer (also written in pyth). I know that this is not a very competitive answer (there is python answer of length 26), but I really enjoyed coming up with this, and I think it comes out into a rather humourous answer.
Explanation:
```
J6 : J=6
i ^TT : convert_to_base(..., 10 BILLION)
fqT U*2^TJ : filter(lambda T: T==..., range(2*10^6)
++2010/JJ4 : 2010 + J/J + 4
```
Basically this is filtering a list of the first two million numbers for being equal to 2015. Then, it treats this list of numbers as the digits of a base 10 BILLION number. Thankfully, there is only one number equal to 2015 in the range, so you get 2015\*10000000000^0, which is just 2015. This takes a couple seconds to run.
[Answer]
# Perl, 48 bytes
```
\d>\fDg;print ord($:)*($_=$=+/~?/)+$_|//<<(\n>n)
```
[Original Answer](https://codegolf.stackexchange.com/a/37112/29990)
[Answer]
# Python 2, 26 bytes
```
iiiceex=";;+=*";print 2015
```
Taken from the [Smallest python script to print even numbers 0 to 100](https://codegolf.stackexchange.com/a/36077/21487) thread. This is probably the solution @FryAmTheEggman was alluding to.
[Answer]
# Mathematica, 60 bytes
```
⌊DF@IM~RS~ad~ee~ee~ggggiiimmnnoorrrstt~.22346⌋Print@2015
```
[Source](https://codegolf.stackexchange.com/a/25239/8478)
The part in the `Floor` brackets is just a series of function applications of non-existing functions (which Mathematica doesn't have a problem with, because of its symbolic computation model). Likewise, just writing the flooring and `Print@2015` is multiplication, which Mathematica also doesn't complain about. Without the syntactic sugar, it would be
```
Floor[ggggiiimmnnoorrrstt[ee[RS[DF[IM], ad], ee], 0.22346]] * Print[2015]
```
Since we're not assuming a REPL environment, the evaluated result of this is never printed (which would be `Null Floor[ggggiiimmnnoorrrstt[ee[RS[DF[IM], ad], ee], 0.22346]]`), but only the side effect of the `Print` actually goes to STDOUT.
Thanks to Sp3000 for turning up the source to this.
[Answer]
# ><>, 57 bytes
**Original C++ code, from the [RadioASCII challenge](https://codegolf.stackexchange.com/a/40844/21487):**
```
#include <cstdio>
int main(){int x;printf("Lawrencium");}
```
**Recycled [><> (Fish)](http://esolangs.org/wiki/Fish) code:**
```
eclne)nfn;
""#(();<>Laaccddiiiiiiimmnnnoprrsttttuuwx{}
```
Like Befunge, ><> is a stack-based 2D language. Execution starts from the top left and is initially rightward. Only the first line of the program is executed, in the following manner:
```
e Push 14 [14]
c Push 12 [14, 12]
l Push the length of the stack [14, 12, 2]
n Output as num [14, 12] 2
e Push 14 [14, 12, 14] 2
) Push 1 if greater than else 0 [14, 0] 2
n Output as num [14] 20
f Push 15 [14, 15] 20
n Output as num [14] 2015
; Terminate [14] 2015
```
Now the big question is — why is the C++ code valid ><>? In ><> there are ways to change the direction of program flow (it's a 2D language, after all):
```
^>v< Arrows which direct program flow a certain direction
_/|\ Mirrors which reflect the direction of program flow
# Four-way mirror, reflect from all directions
```
When the C++ code is executed, the initial `#` reflects program flow leftward. But ><> is toroidal, so the instruction pointer wraps around, appearing from the end of the line, meeting the `>` which directs program flow rightward again. The pointer then wraps back to the `#`, bounces back to the `>`... and thus an infinite loop occurs and an error is never thrown.
[Answer]
# Python 3, 1878 bytes
Very long, but wanted to share anyway:
```
import sys,re,zlib as z,base64
print(2015)#,PIL.Image as ire.search(str(z.adler3(i.open(sys.argv[1]).tobytes()[2::6])%203)+'(\\D+',z.decompress(base64.b8decode(b'c${Tc%XZ>86NyfdNqBH<%b?iLI_EpFkwO-GfQC$tcfjoB$+h*^;0s?o$g*?uzgjxs%~BKif!C3zALZEU!&?wJd#-mqgS@p<P&+)AsV|c*52*C>U&(_4w^urvvWJU8Bj;bvv4ia;eiJLu+bsXLru`DjH|W<`|;xLq++kv5k8VWZgQe*`_u+opEF8>A6qjM%k#skzbiuJ7dL_*><K@9l6!M*H(|w)PZJ2`RYy7K2VVrv+zc)&2Fc?wvh|^#ksyymE?D!Q$3!LbFX%h%vT%1#lr486Iybw?0!`H)ZlZ#XIao2uXTr}(IBl@wRWHa#})bgV);O3HoW7+T*!5M3=^mu6Ri$`7L;uUWj~gsqR6gQR9h7^nKdBIgy>ats36%|M|8p1x;32(ZfK9R5_xK5ts=Sz70c%SIK&g3N1E|sg{n3>JSbKwwhssGcb$8uMNw=Nv;f_;rj?}kz(3-&#FQw@O;q(8nGHjbrTC(NQv=ckXT|eHr|amahCq(7T6<LBTr5Gj>fHV~3DcYINN!Qr`6Dl?jT>!4u5~bb%Zi6VTax;%vg*m325J_$nEC%yqbbYeEp!K_K7k)W-XCP`6+}N7tktMVX+{@c2L&kLAc&IvspGrzZ$F`uOBg}fA3W2neAU}tg~<+iCN=<sR^Zke+9WNhnCyy6!8nfa>33&OWiPt2s=OMTrUgilSYQxrG!gziB!Aj83zX&6S|yjIQkA?iF0n%?<+B=%_D11aoCv?@Q&eei{sqNkr7RG`#*xyzSUE6BUNnZK)3|3Wls}K$qaKv;jOO#!{3Ms)4CQ?shafnAF^zVq(`K9o2xL5JoQoGea+W1$+xmw&8OMOtN1Pid6UAcd+*_bB6IY$KjrO=ac^tPv3(8O`&(agOBbT{Va6s}Rm9&`I#yivC;MhW8=n+^^&Reho;~!~W<xgH6bVq3^=H7)sUXV2nv~DP4`CY`f55i&qH)DvPMQy>)y*Z=|68w@v=#oo5^RSh5R2F%1-vt>h=|+1n0pE^Yq-72!)1+o{hD_3<Cyxpyr6r%cei-AFQ*h1seM$MP>ovLS2k#Ci$to#do$s3MXu2lZsw~9HkbjVWM@1!{w>}LWVj#j2qC(+*Okc>=<qcV}*}+U_QK+(ZZ(x>ZMdDDWtgHiBK+7p6aHHI`u-h6z7|Xm`>D1t4uEp271y7oCI^{1^H~O7QRxTA_U&92Q8z$J2O|5Lbeg_0umd^pSU<%-ki7LtDvo&AgIt0h~6(y@Hr+kyLJ$<B#07KdGob0EW$7@f{GszaUv#tkpSyk759Khmvq-aiyM-_&x_VCTx$Vy<;$<k{T$-@{Mhc<<%KD1AHK^MKkg%pYIW}SxhV?&a{o9=rs@*+hqyoioE=TF>9S<KxY+^69^OA0jkS#0!w@kw4}KTcP9#+PVW+qB|7B`Y?eRs+7}8RSAs?i?-Cz#Wp(Iihd`nI!Q_i%R^o_;fvDQ5|{Cr;yWeirL>_l#(wn)$QenJkK6Sgw)5NleBzvo&G#@>X`7Ib*aS4LHx9epI%BXXV&y7LJ&54g}D25-Q8>DZQ5hGKyIeJkQQu08%j|<x~)q(AOVw9P~Z*c0Z@VM6n#<}tBT6+T%4mZ9f*y76xlEFM~o$xr9*SZHd^6D-C!pkkp3m(-~W3&>KY@106L+;I><MJ^Dz`f{(I3i?u`2pWjUjlwZx`B1JB#h#u3xTH*b1K?TG40|4lxF1$_Pw+t?h2')).decode()).group(1))
```
Taken from [KennyTM's answer](https://codegolf.stackexchange.com/a/42245/9275).
I saw that 2, 0, 1 and 5 and # could be found in the code, so I moved some chars to make `print(2015)` and could comment out the rest. I also put the PIL import into the comment so it doesn't require that library.
[Answer]
# PHP, 21 bytes
```
<?=65*4*31*2/8;//7**9
```
Let's try this again. Taken from [another PHP answer](https://codegolf.stackexchange.com/a/41166/29750) from Unscramble the Source Code. It's pretty basic, but so far it's the shortest program in a non-golfing language. You can verify it at <http://codepad.org/15EjIYAU>. The original code is as follows:
```
<?=9*8*7*6*5*4/3/2/1;
```
] |
[Question]
[
# Challenge
Write a function/program that outputs either the `n`'th element, or the first `n` elements, in the well known number sequence:
```
1, 2, 4, 8, 16 ...
```
Oh, wait... I forgot the first few numbers:
```
1, 1, 1, 1, 2, 4, 8, 16 ...
```
Heck, I'll add a few more for good measure:
```
1, 1, 1, 1, 2, 4, 8, 16, 33, 69, 146, 312, 673, 1463, 3202, 7050, 15605, 34705 ...
```
---
The numbers are Generalized Catalan numbers given by the (zero-indexed) formula:
$$a(n+1)= a(n) + \sum\_{k=2}^{n-1} a(k)\cdot a(n-1-k)$$
where
$$a(0)= a(1)= a(2)= a(3) = 1$$
This is [OEIS A004149](http://oeis.org/A004149).
You may choose if you want to have the sequence zero- or one-indexed. The sequence must of course be the same, so you must rewrite the formula if you have it one-indexed.
[Answer]
# [Python](https://docs.python.org/2/), 51 bytes
```
f=lambda n,k=2:n<3or k<n and f(k)*f(n-k-2)+f(n,k+1)
```
[Try it online!](https://tio.run/##FcwxDoAgEAXR3lNsyYoWYmfgMBhFyeqHEBtPj9hN8TL5fc4EU2twl7/XzRMGcWaBnVMhsSCPjYIS7oPCKKNh3WIQPXENjYAiqHgcuzITLx3lEvG0C/2O6wc "Python 2 – Try It Online")
Simplifies the formula a bit:
$$a(n) = \sum\_{k=2}^{n-1} a(k)\cdot a(n-2-k)$$
$$ a(-1) = a(0)= a(1)= a(2) = 1$$
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~14~~ ~~13~~ 11 bytes
```
$ƒˆ¯Âø¨¨¨PO
```
[Try it online!](https://tio.run/##yy9OTMpM/f9f5dik022H1h9uOrQCBA/vCPD//9/QAAA "05AB1E – Try It Online")
Outputs the nth element, 0-indexed.
```
$ # push 1 and the input
ƒ # repeat (input+1) times
ˆ # add the top of the stack (initially 1) to the global array
¯ # push the global array
 # and a reversed copy of it
ø # zip the two together, giving a list of pairs
¨¨¨ # drop the last 3 pairs
P # take the product of each pair (or 1 if the list is empty)
O # take the sum of those products
# after the last iteration, this is implicitly output;
# otherwise, it's added to the global array by the next iteration
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 44 bytes
```
{1,1,1,1,{sum @_[2..*]Z*@_[@_-4...0,0]}...*}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv9pQBwKri0tzFRzio4309LRio7SALId4XRM9PT0DHYPYWiCtVfu/OLFSIU1DMzrOyCD2PwA "Perl 6 – Try It Online")
Anonymous code block that returns a lazy infinite sequence of values. This pretty much implements the sequence as described, with the shortcut that it zip multiplies all the elements so far after the second element with the reverse of the list starting from the fourth element and adding an extra `1` at the end.
### Explanation:
```
{ } # Anonymous code block
...* # Create an infinite sequence
1,1,1,1, # Starting with four 1s
{ } # Where each new element is:
sum # The sum of
@_[2..*] # The second element onwards
Z* # Zip multiplied with
@_[@_-4...0 ] # The fourth last element backwards
,0 # And 1
```
[Answer]
# JavaScript (ES6), 42 bytes
A port of [xnor's solution](https://codegolf.stackexchange.com/a/193186/58563).
0-indexed.
```
f=(n,k=2)=>n<3||k<n&&f(k)*f(n+~++k)+f(n,k)
```
[Try it online!](https://tio.run/##FctBDoIwEEDRPaeYBSEzDhqDS1rOQoPUaMkMAeOm1KtXu/qb91/u4/Zpe67vs@h9ztlblDbYjuwg5nYcwUjTeAx08ij8ZQ7EvhDKXjcUsHDtQcBAV8pMECuASWXXZb4s@sDRYR0l0Z/WscyURuqrlH8 "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), ~~83~~ 75 bytes
A faster, less recursive, but significantly longer solution.
0-indexed.
```
f=(n,i,a=[p=1])=>a[n]||f(n,-~i,[...a,p+=(h=k=>k<i&&a[k]*a[i-++k]+h(k))(2)])
```
[Try it online!](https://tio.run/##FY1BCoMwEADvfcUeRLJNDK1XXT8SAi5WaxpJREsvar@e2tPAMDAv/vDaLW5@FyE@@pQGEkE5xWRmulukhk2w@z6ctvg6ZbTWrGZJYiRPja9dnrPx9srGFVJ6K0fhEUWJFtMQFxGA4FZBgBrKP6VE2C4AXQxrnHo9xadoWWRbOPBMs@084dFidTnSDw "JavaScript (Node.js) – Try It Online")
[Answer]
## Haskell, ~~49~~ ~~43~~ 39 bytes
```
a n=max(sum[a k*a(n-2-k)|k<-[2..n-1]])1
```
[Try it online!](https://tio.run/##BcExDoAgDADAr3RwEJMSYXGRlxCGDiaS0oaIJg7@vd6dNPhozYxAk9A7j0cyAS80K0Zk9/GOOXqvGEpxwYSqQoJ@Vb1hAqEOBHn1PmzFfg "Haskell – Try It Online")
For `n<3` the `sum` is 0, so `max ... 1` raises it to `1`.
Edit: -6 bytes thanks to @Jo King.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 36 bytes
```
Sum[#0@i#0[#-i-1],{i,3,#-1}]/. 0->1&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P7g0N1rZwCFT2SBaWTdT1zBWpzpTx1hHWdewNlZfT8FA185Q7X9AUWZeCVDeLs1BOVZN3yEoMS891cHQ9D8A "Wolfram Language (Mathematica) – Try It Online")
1-indexed.
The 2-indexed sequence is 4 bytes shorter: `Sum[#0@i#0[#-i],{i,#-4}]/. 0->1&`.
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P7g0N1rZwCFT2SBaWTczVqc6U0dZ16Q2Vl9PwUDXzlDtf0BRZl4JUM4uzUE5Vk3fISgxLz3VwdD0PwA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~17~~ 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
4Å1λ£₁λ¨Â¦¦s¦¦*O+
```
Not shorter than [the existing 05AB1E answer](https://codegolf.stackexchange.com/a/193183/52210), but I wanted to try the recursive functionality of the new 05AB1E version as practice for myself. ~~Could perhaps be golfed by a few bytes.~~ EDIT: And it indeed can, see the recursive version of *@Grimy*'s 05AB1E answer below, which is **13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)**.
Outputs the first \$n\$ items: [Try it online](https://tio.run/##yy9OTMpM/f/f5HCr4bndhxY/amoEUisONx1admhZMYjQ8tf@/9/IAAA).
Could be changed to the 0-based \$n\$'th item when replacing `£` with `è`: [Try it online](https://tio.run/##yy9OTMpM/f/f5HCr4bndh1c8amo8t/vQisNNh5YdWlYMIrT8tf//N7QEAA);
or an infinite list by removing `£`: [Try it online](https://tio.run/##yy9OTMpM/f/f5HCr4bndj5oaz@0@tOJw06Flh5YVgwgtf@3//w0tAQ).
**Explanation:**
This implements the formula used in the challenge description like this:
\$a(n)= a(n-1) + \sum\_{k=2}^{n-1}(a(k)\cdot a(n-1-k))\$
\$a(0)=a(1)=a(2)=a(3)=1\$
```
λ # Create a recursive environment,
£ # to output the first (implicit) input amount of results after we're done
4Å1 # Start this recursive list with [1,1,1,1], thus a(0)=a(1)=a(2)=a(3)=1
# Within the recursive environment, do the following:
λ # Push the list of values in the range [a(0),a(n)]
¨ # Remove the last one to make the range [a(0),a(n-1)]
 # Bifurcate this list (short for Duplicate & Reverse copy)
¦¦ # Remove the first two items of the reversed list,
# so we'll have a list with the values in the range [a(n-3),a(0)]
s # Swap to get the [a(0),a(n-1)] list again
¦¦ # Remove the first two items of this list as well,
# so we'll have a list with the values in the range [a(2),a(n-1)]
* # Multiply the values at the same indices in both lists,
# so we'll have a list with the values [a(n-3)*a(2),...,a(0)*a(n-1)]
O # Take the sum of this list
₁ + # And add it to the a(n-1)'th value
# (afterwards the resulting list is output implicitly)
```
---
**13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) version of *@Grimy* (make sure to upvote [his answer](https://codegolf.stackexchange.com/a/193183/52210) if you haven't yet!):**
```
1λ£λ1šÂ¨¨¨øPO
```
Outputs the first \$n\$ items: [Try it online.](https://tio.run/##yy9OTMpM/f/f8NzuQ4vP7TY8uvBw06EVIHh4R4D///9GBgA)
Can again be changed to 0-based indexing or an infinite list instead:
- (0-based) indexing `1λèλ1šÂ¨¨¨øPO`: [Try it online](https://tio.run/##yy9OTMpM/f/f8NzuwyvO7TY8uvBw06EVIHh4R4A/UNwSAA);
- Infinite list `λλ1šÂ¨¨¨øPO`: [Try it online](https://tio.run/##yy9OTMpM/f//3O5zuw2PLjzcdGgFCB7eEeD//z8A). (Note that 2 bytes are saved here instead of 1, because the recursive environment starts with \$a(0)=1\$ by default.)
**Explanation:**
This instead implements the formula found by [*@xnor* for his Python answer](https://codegolf.stackexchange.com/a/193186/52210) like this:
\$a(n) = \sum\_{k=2}^{n-1}(a(k)\cdot a(n-2-k))\$
\$a(-1) = a(0) = a(1) = a(2) = 1\$
```
λ # Create a recursive environment,
£ # to output the first (implicit) input amount of results after we're done
1 # Start this recursive list with 1, thus a(0)=1
# Within the recursive environment, do the following:
λ # Push the list of values in the range [a(0),a(n)]
1š # Prepend 1 in front of this list
 # Bifurcate the list (short for Duplicate & Reverse copy)
¨¨¨ # Remove (up to) the last three value in this reversed list
ø # Create pairs with the list we bifurcated earlier
# (which will automatically remove any trailing items of the longer list)
P # Get the product of each pair (which will result in 1 for an empty list)
O # And sum the entire list
# (afterwards the resulting list is output implicitly)
```
[Answer]
# [Python 3](https://docs.python.org/3/), 59 bytes
really inefficient, `a(13)` doesn't finish on TIO.
```
a=lambda n,k=2:n<4or(n-k<2)*a(n-1)or a(k)*a(n-k-2)+a(n,k+1)
```
[Try it online!](https://tio.run/##JYo7DoAgEAWvsiWrWABWBk9iLNb4zepiCI2nR4zNZObl3U/ag7icqT/pmmYC0dzbTnwbopKGvcWKihgMEUjxX9xYrItorg3mOx6S1PChbIiwlq/AIRBJtkUZhyPmFw "Python 3 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes
```
1WṪ;+¥×Uṫ3SƲ;@Ʋ⁸¡
```
[Try it online!](https://tio.run/##AScA2P9qZWxsef//MVfhuao7K8Klw5dV4bmrM1PGsjtAxrLigbjCof///zU "Jelly – Try It Online")
A monadic link taking the zero-indexed \$n\$ and returning the list of generalized Catalan numbers from \$0\$ to \$n\$.
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 34 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
-2 thanks to dzaima.
Anonymous prefix lambda.
```
{⍵≤3:1⋄+/(∇⍵-1),⍵(-×⍥∇¯2+⊢)¨4…⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/v/pR79ZHnUuMrQwfdbdo62s86mgHiugaauoAKQ3dw9Mf9S4Fih1ab6T9qGuR5qEVJo8algGlav@nPWqb8Ki371HfVE//R13Nh9YbP2qbCOQFBzkDyRAPz@D/aYdWPOrdbGgOAA "APL (Dyalog Extended) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 76 bytes
```
1:1:1:f[1,1,1]
f(x:z)|y<-x+sum(zipWith(*)(init$init z)$reverse z)=y:f(y:x:z)
```
[Try it online!](https://tio.run/##FYuxDsIgFAB3v@INDKA2sY5EJn@gmybq8GLAvpSSBtAU4reLkEsut9yIYdLWFlT30suGufX7ymNj@Cqz@KZTt@7Ce@aZlgvFkW8FJ0eRNUEWzOuP9kHXVEkanmTbyozkQMHiyUVgEHHScDzUwvJ7GouvULrreRj@ "Haskell – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~19~~ ~~17~~ 16 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Outputs the `n`th term, 1-indexed.
```
@Zí*Zz2)Ťx}g4Æ1
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QFrtKlp6MinFpHh9ZzTGMQ&input=OA)
```
@Zí*Zz2)Ťx}g4Æ1 :Implicit input of integer U
@ :Function taking an array as an argument via parameter Z
Zí : Interleave Z with
Zz2 : Z rotated clockwise by 180 degrees (simply reversing would be a bye shorter but would modify the original array)
* : Reduce each pair by multiplcation
) : End interleave
Å : Slice off the first element
¤ : Slice off the first 2 elements
x : Reduce by addition
} :End function
g :Pass the following as Z, push the result back to it and repeat until it has length U
4Æ1 :Map the range [0,4) to 1s
:Implicit output of the last element
```
[Answer]
# [Haskell](https://www.haskell.org/), 65 bytes
```
f a|a<4=1|z<-g[2..a]=sum$zipWith(*)z$reverse(1:g[0..a-4])
g=map f
```
[Try it online!](https://tio.run/##FcoxCoAgFADQvVP8wcGCRKMp8hwN4fAHNSlDtBrEu1u9@W2Ydn0ctRrAgvMoRclzb9eBMVQy3Z5kFxZ3bbRrM4n60TFpKia78m/0o2obKz0GMNWjO0FCiO68gICFvwxc1Rc "Haskell – Try It Online")
You can use either `f` to get a single element of a sequence, or pass a list of values to `g` and get all the indexes for that list.
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 99 81 bytes
```
: f recursive dup 4 > if 0 over 3 do over 1- i - f i f * + loop else 1 then nip ;
```
[Try it online!](https://tio.run/##JYtLCgIxFASvUsxSTTDoQhS8SMjKvDgPhknIfK4fM7houguqU67raL7pqNaeJKp8trroLsStcOeNJq7kXSo3Yv4vZ1BM17XnxJkp54JMi@BYR5mZtfBq7tHZxxzwGrrqsBU7cGHAH59AVxK2/QA "Forth (gforth) – Try It Online")
Output is nth term and input is 1-indexed
Edit: Saved 17 bytes by switching to xnor's formula. Saved another 1 byte by using 1-indexed
### Code Explanation
```
: f \ start a new word definition
recursive \ mark that this word will be recursive
dup 4 > \ duplicate the input and check if it is greater than 4
if \ if it is:
0 over \ create an accumulator and copy n to top of stack
3 do \ start counted loop from 3 to n-1
over 1- i - f \ recursively calculate f(n-1-i)
i f \ recursively calculate f(i)
* + \ multiply results and add to accumulator
loop \ end the counted loop
else \ otherwise, if n < 5
1 \ put 1 on the stack
then \ end the if block
nip \ drop n from the stack
; \ end the word definition
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 26 bytes
```
F⁵⊞υ¹FN⊞υΣ✂E⮌υ×κ§υλ³→I§υ±⁴
```
[Try it online!](https://tio.run/##TcqxDoIwFIXhnafoeG9SB6MmRibjxCAh4AvUeoXGtpC2l/j2FVx0OcP5Pz2ooEdlc36OQcABRcNxAJZii2Xx/So/carZ3SkA/nrHDjprNMFVTdDSTCESMEpxM44ivKQ4p8o/6L1qi7iU3bJl0QTjE5xa0w9JiouKCf5kTb1KBHtcbc7HvJntBw "Charcoal – Try It Online") Link is to verbose version of code. Prints the 0-indexed nth number, although it calculates using 1-indexing internally. Explanation:
```
F⁵⊞υ¹
```
Start with `a[0] = a[1] = a[2] = a[3] = a[4] = 1`. Yes, this is 1-indexed, but then with an extra zeroth value. That's code golf for you.
```
FN
```
Calculate an additional `n` terms. This is overkill, but it makes finding the desired term easier when `n<5`.
```
⊞υΣ✂E⮌υ×κ§υλ³
```
For each term, compute the next term as the sum of the terms so far termwise multiplied by the reverse of the terms so far, excluding three terms.
```
→
```
This is a no-op used to trick Charcoal into parsing the 2-argument form of `Slice`, otherwise I would have to use a less golfy way of removing three terms.
```
I§υ±⁴
```
Output the 4th last term.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 30 bytes
```
J*4]1VQ=+J+eJsPP*M.t,PJ_PJ0;<J
```
[Try it online!](https://tio.run/##K6gsyfj/30vLJNYwLNBW20s71as4IEDLV69EJ8ArPsDLwNrG6/9/SwA "Pyth – Try It Online")
Returns the first \$n\$ elements of the sequence.
```
J*4]1VQ=+J+eJsPP*M.t,PJ_PJ0;<JQ # Full program, last Q = input (implicitly added)
J*4]1 # J = 4 * [1] (=[1,1,1,1])
VQ # for N in range(Q):
=+J # J +=
+eJ # J[-1] +
s # sum( )
*M # map(__operator_mul, )
.t 0 # transpose( , pad=0)
, # [ , ]
PJ # J[:-1]
_PJ # J[1::-1]
<JQ # J[::Q]
```
Alternative: Replace `<` with `@` to return the \$n\$-th element of the sequence, 0-indexed.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~42~~ 41 bytes
```
f=->n{n<4?1:(4..n).sum{|i|f[i-1]*f[n-i]}}
```
[Try it online!](https://tio.run/##BcFBCoAgEADAr4SninbJ8BRlD7E9lCB4UKT0EOrbbeZJ99ea2UH67Ddx8LUXiH7AN7lcbDHKAqfRKA@Wam0hxbfrOeIyD@iukIsuSk9GaaKRnRFAnpHV9gM "Ruby – Try It Online")
1-indexed (to save 1 byte)
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 73 bytes
```
g=(1:4).^0;for(i=3:(n=input('')))g(i+2)=g(4:i+1)*g(i-(2:i-1))';end;g(end)
```
[Try it online!](https://tio.run/##DcdRCoAgEAXA47gvMdKEQPEqQZTJ/miEdf2tn4Fpe9/eLFIS2eAxrlM8202c5kA1cb2eTkoBKMTaIRXygbXF8N@QC2wsoGKuRyz0C5HlAw "Octave – Try It Online")
-2 bytes thanks to Stewie Griffin. Once more, the imperative approach wins over the functional recursive approach. That one is shown below.
### [Octave](https://www.gnu.org/software/octave/), 75 bytes
```
f(f=@(a)@(n){@()sum(arrayfun(@(k)a(a)(k)*a(a)(n-2-k),2:n-1)),1}{2-(n>3)}())
```
[Try it online!](https://tio.run/##HclLCoAgFAXQ7dwbKmSDICjcyiNyIr2wH0S0dotGZ3CWcZdzKrl3zpWI2AcIA5R3ALdjhqyrXPFQBCTKlx/Vr1pvE43v1NakqZ/bW@jQ8AFZMlqWFw "Octave – Try It Online")
Captcha wanted to verify I was a human when posting this. To be honest, [I'm not so sure](https://xkcd.com/329/).
[Answer]
# [Perl 5](https://www.perl.org/) `-MList::Util=sum`, 61 bytes
```
sub a{my$b=-2+pop;$b<2||sum a($b+1),map{a($_)*a($b-$_)}2..$b}
```
[Try it online!](https://tio.run/##K0gtyjH9/7@4NEkhsTq3UiXJVtdIuyC/wFolycaopqa4NFchUUMlSdtQUyc3saAayI7X1AKJ6AIZtUZ6eipJtf@LEysVwDIKaflFCoZ6ekYG///lF5Rk5ucV/9f19cksLrGyCi3JzLEFmgcUMNUzMDQAAA "Perl 5 – Try It Online")
[Answer]
# [C/C++](http://www.cplusplus.com/doc/tutorial/), ~~70~~ ~~69~~ 67 bytes
-1 bytes thanks to Jonathan.
```
int a(int n){int k=2,s=0;while(++k<n)s+=a(k)*a(n+~k);return s?s:1;}
```
[Try it online!](https://onlinegdb.com/r1lN1BjmvH)
] |
[Question]
[
# Task description
Given an integer, swap its **(2k–1)**-th and **2k**-th least significant bits for all integers **k > 0**. This is sequence [A057300](https://oeis.org/A057300) in the OEIS.
(The number is assumed to have “infinitely many” leading zeroes. In practice, this simply means prepending a single 0 bit to odd-length numbers.)
[](https://i.stack.imgur.com/j6sll.jpg)
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code (in bytes) wins.
# Test cases
```
0 -> 0
1 -> 2
9 -> 6
85 -> 170
220 -> 236
1827 -> 2835
47525 -> 30298
```
[Answer]
## Python 2, 26 bytes
```
lambda n:2*n-3*(4**n/3&n/2)
```
Bit tricks!
Say `n` has form `...ghfedcba` in binary. Then, we can split it into every other bit as
```
n = o + 2*e
n = ...hgfedcba
o = ...0g0e0c0a
2*e = ...h0f0d0b0
```
Then, the bit-switched result `s` can be expressed as `s=2*o+e`.
```
s = 2*o + e
s = ...ghefcdab
2*o = ...g0e0c0a0
e = ...0h0f0d0b
```
We'd rather compute only one of `e` and `o`, so we express `o=n-2*e` and substitute
```
s=2*(n-2*e)+e = 2*n-3*e
```
So, now it remains to express `e` in terms of `n`. The number `M=4**n/3` has form `...10101010101` in binary, which serves as a mask for the odd digits. The exponent `n` ensures that `M` is long enough. Taking the bitwise `and` of `n/2` and this value gives `e` as desired.
```
n/2 = ...hgfedcb
M = ...1010101
n/2 & M = ...h0f0d0b = e
```
We can instead express `e` in terms of `o` `e=(n-o)/2`, which gives `s=(n+o*3)/2`, which saves a byte thanks to an optimization from xsot.
```
lambda n:n+(n&4**n/3)*3>>1
```
[Answer]
# C function, 38
Bit-twiddling:
```
f(x){return(x&~0U/3*2)/2+(x&~0U/3)*2;}
```
[Ideone.](https://ideone.com/5HOmv7)
---
Or for the fun of it:
# C recursive function, 43
As per the [OEIS formula](https://oeis.org/A057300), `a(4n+k) = 4a(n) + a(k), 0 <= k <= 3`
```
f(x){return x>3?4*f(x/4)+f(x%4):x%3?3-x:x;}
```
or
```
f(x){return x>3?4*f(x/4)+f(x%4):x%2*2+x/2;}
```
[Ideone.](https://ideone.com/plkr0v)
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), ~~10~~ ~~9~~ 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
b4d2UFḄ
```
[Try it online!](http://jelly.tryitonline.net/#code=YjRkMlVG4biE&input=&args=NDc1MjU) or [verify all test cases](http://jelly.tryitonline.net/#code=YjRkMlVG4biECsOH4oKs&input=&args=WzAsIDEsIDksIDg1LCAyMjAsIDE4MjcsIDQ3NTI1XQ).
### How it works
```
b4d2UFḄ Main link. Argument: n (integer)
b4 Convert n to base 4.
d2 Divmod each quaternary digit x by 2, yielding [x : 2, x % 2].
U Upend; reverse each pair, yielding [x % 2, x : 2].
F Flatten the 2D list of binary digits.
Ḅ Convert from binary to integer.
```
[Answer]
## CJam, ~~16~~ ~~14~~ 13 bytes
```
ri4b4e!2=f=4b
```
[Test it here.](http://cjam.aditsu.net/#code=ri4b4e!2%3Df%3D4b&input=181)
### Explanation
```
ri e# Read input and convert to integer.
4b e# Get base-4 digits.
4e! e# Push all permutations of [0 1 2 3].
2= e# Select the third one which happens to be [0 2 1 3].
f= e# For each base-4 digit select the value at that position in the previous
e# list, which swaps 1s and 2s.
4b e# Convert back from base 4.
```
[Answer]
# Pyth, 9 bytes
```
iXjQ4S2)4
```
Try it in the [Pyth Compiler](https://pyth.herokuapp.com/?code=iXjQ4S2%294&input=1&test_suite=1&test_suite_input=9%0A85%0A220%0A1827%0A47525&debug=0).
### How it works
```
jQ4 Convert the input (Q) to base 4.
X S2) Translate [1, 2] to [2, 1].
i 4 COnvert from base 4 to integer.
```
[Answer]
## JavaScript (ES6), ~~32~~ 30 bytes
```
(n,m=0x55555555)=>n*2&~m|n/2&m
```
Only works up to 1073741823 due to the limitations of JavaScript's integers. ~~38~~ 36 bytes works up to 4294967295:
```
(n,m=0x55555555)=>(n*2&~m|n/2&m)>>>0
```
Edit: Saved 2 bytes thanks to @user81655.
51 bytes works up to 4503599627370495:
```
n=>parseInt(n.toString(4).replace(/1|2/g,n=>3-n),4)
```
[Answer]
# x86 asm function: 14 bytes of machine code
## uint64\_t version: 24 bytes
x86-64 SysV calling convention (`x` in `edi`), but this same machine code will also work in 32bit mode. (Where the `lea` will decode as `lea eax, [edi + eax*2]`, [which gives identical results](https://stackoverflow.com/questions/34377711/which-2s-complement-integer-operations-can-be-used-without-zeroing-high-bits-in)).
```
0000000000000040 <onemask_even>:
40: 89 f8 mov eax,edi
42: 25 55 55 55 55 and eax,0x55555555
47: 29 c7 sub edi,eax
49: d1 ef shr edi,1
4b: 8d 04 47 lea eax,[rdi+rax*2]
4e: c3 ret
4f: <end>
```
`0x4f - 0x40` = 14 bytes
This is [compiler output](http://gcc.godbolt.org/#compilers:!((compiler:g6,options:'-xc+-std%3Dgnu99+-O3+-Wno-all+-Wno-extra+-fno-verbose-asm',sourcez:PQKgBAIglg5lAuBDANmAKgJ0QVwLaIHIBnMAYTADcBTDIqAewDswRgAoAMwAoAPASgDeGKvGwZGvAGQA/AAwBVYAGYQAJj7BVAailzFSvmoDcAXzZtQYGPWQcqAEzKUadJmHocwPRvQzF3jFT4RADWYAAOAJ7wABZuHNiMAMbwDMysbDC8gsKi4mCqIDwAtCq8mvIyCsp8pmwx2UIiYsyFJWU8VfpqGqqmYGDAwGBEiNRgsVRg8uZsAMRQnrJsiXQwgY7ITDBgHABsACxcq7AbYFuMO/wCbAO5LWC6CgAyz8o9mmBaj516rzXGNhmNhQRjwXZrDZcUHg673cRPbrqTQ6X7VAzGMwndYOXb0ehgAC8YD0yiM8yojHsi1mlg4GHouC8Pj8JCisTciEYRAA7jQADRgABG2HB9HC4XodHgUxlGFwoJs9BgkQAXMKELIwFASFRqOl2NizkwgohQgB9XywY7c064/hgG4DI24vWU4JhYmkpTk522nGOehChAkYlcXhgAB8kbAAEY%2BGBJGA3YwPbVbmB4a0imBimAVEGQ%2BTgSt/cbAh7zZXJoxzUQYot4DbIfaE06wC7Ax6iST0SwCr6O2XcfRVD2I0nGWaQum/S3A8H4KH3GPo3HB1mCjm8wXF0Ri%2BZQLdmMTCgTvlRbsvClNvvRzMme8w82eBm/xzxE735G8DLcCWGz7Jr075hp%2BSZcH8NQADzQfGUaRrGtxXj2N5fI8jDFFQvTIWAKGniAXBAWeCZ3qhIDPgcIDnu45FAQWtwZBY4DwBgkQTDEUz0JMGBgDyiCRIKZpgIgERSnQQrIFMPAABx7CJRBMlyvI0CwhrDoGFbTuaKbNnajgOu2nbJt2XrooOxlTGBX6mqEs6Zs0%2BRUGo6Hhp%2BebYQhcbpsCCzJMg2D2FM0FEPA1JggAdDEkYrDChzmmKWkWimhzHHFBwJV4bYZtg6WZbZnrfr%2BFl5eCVk/DZaYbo5zDOWO3xubmwFefGB4WMMPBENx/hUDw4TCEQriMBFAwQPQVBEIwBDgjyvghBF7VgAA4o0m48KiXQAko0axnUQAA%3D)),filterAsm:(binary:!t,commentOnly:!t,directives:!t,intel:!t,labels:!t),version:3) from using xnor's excellent mask-once idea the opposite way. (And opposite terminology: the low bit is bit 0, which is even, not odd.)
```
unsigned onemask_even(unsigned x) {
unsigned emask = ~0U/3;
unsigned e = (x & emask);
return e*2 + ((x - e) >> 1);
}
```
I didn't find any improvements over what the compiler does. I might have written it as `mov eax, 0x555...` / `and eax, edi`, but that's the same length.
---
The same function for 64bit integers takes 24 bytes (see the godbolt link). I don't see any way shorter than 10-byte `movabs rax, 0x55...` to generate the mask in a register. (x86's `div` instruction is clunky, so unsigned division of all-ones by 3 doesn't help.)
I did come up with a loop to generate the mask in rax, but it's 10 bytes (exactly the same length as the `mov imm64`).
```
# since 0x55 has its low bit set, shifting it out the top of RAX will set CF
0000000000000000 <swap_bitpairs64>:
0: 31 c0 xor eax,eax ; old garbage in rax could end the loop early
0000000000000002 <swap_bitpairs64.loop>:
2: 48 c1 e0 08 shl rax,0x8
6: b0 55 mov al,0x55 ; set the low byte
8: 73 f8 jnc 2 <swap_bitpairs64.loop> ; loop until CF is set
000000000000000a <swap_bitpairs64.rest_of_function_as_normal>:
# 10 bytes, same as mov rax, 0x5555555555555555
# rax = 0x5555...
a: 48 21 f8 and rax,rdi
...
```
If we knew that none of the existing bytes in `rax` has their low bit set, we could skip the `xor`, and this would be 8 bytes long.
A previous version of this answer had a 10 byte loop using the [`loop`](http://www.felixcloutier.com/x86/LOOP:LOOPcc.html) insn, but it had a worst-case run-time of `0xFFFFFFFFFFFFFF08` iterations, because I only set `cl`.
[Answer]
# [Oasis](http://github.com/Adriandmen/Oasis), 17 bytes (non-competing)
```
n4÷axxn4÷xxe+3120
```
[Try it online!](http://oasis.tryitonline.net/#code=bjTDt2F4eG40w7d4eGUrMzEyMA&input=&args=NDc1MjU)
Oasis is a language designed by [Adnan](https://codegolf.stackexchange.com/users/34388/adnan) which is specialized in sequences.
Currently, this language can do recursion and closed form.
We use this formula: `a(4n+k) = 4a(n) + a(k), 0 <= k <= 3`
To specify the base case is simple: the `3120` at the end simply means that `a(0)=0, a(1)=2, a(2)=1, a(3)=3`.
```
n4÷axxn4÷xxe+3120
0 a(0) = 0
2 a(1) = 2
1 a(2) = 1
3 a(3) = 3
n push n (input)
4÷ integer-divide by 4
a a(n/4)
xx double twice; multiply by 4
now we have 4a(n/4)
n push n (input)
4÷xx integer-divide by 4 and then multiply by 4
since there is no modulo currently, n%4
is built as n-(n/4*4)
e we should have done a(n-(n/4*4)), but this
is a shortcut for a(n-x) where x is the top
of stack. Therefore, we now have a(n-n/4*4)
which is a(n%4).
+ add.
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 10 bytes
```
BP2eP1ePXB
```
[Try it online!](http://matl.tryitonline.net/#code=QlAyZVAxZVBYQg&input=Ng)
[Modified version](http://matl.tryitonline.net/#code=OnEiQApCUDJlUDFlUFhC&input=MTA) to generate the first terms of the sequence ([OEIS A057300](https://oeis.org/A057300)).
### Explanation
```
B % Take input implicitly. Convert to binary array
P % Flip
2e % Convert to two-row 2D array, padding with a trailing zero if needed.
% Because of the previous flip, this really corresponds to a leading zero
P % Flip each column. This corresponds to swapping the bits
1e % Reshape into a row
P % Flip, to undo the initial flipping
XB % Convert from binary array to number. Display implicitly
```
[Answer]
## zsh, 28 bytes
```
<<<$[`tr 12 21<<<$[[#4]$1]`]
```
Takes input as a command line argument, outputs on STDOUT.
It's not Bash-compatible because it uses zsh-specific base conversion syntax.
```
$1 input (first command line argument)
$[ ] arithmetic expansion
[#4] output in base 4
<<< pass the result of this to...
tr the `tr' command
12 21 and replace 1s with 2s, 2s with 1s
` ` evaluate the result...
$[ ] in another arithmetic expansion, to convert back
to base 10
<<< output the result on STDOUT
```
[Answer]
# Retina, 70 bytes
```
.+
$*
+`(1+)\1
$1x
x1
1
^
x
r`(.)(.)
$2$1
1
x@
+`@x
x@@
x*(@*)
$.1
0$
```
[Test suite.](http://retina.tryitonline.net/#code=JShgLisKJCoKK2AoMSspXDEKJDF4CngxCjEKXgp4CnJgKC4pKC4pCiQyJDEKMQp4QAorYEB4CnhAQAp4KihAKikKJC4xCjAkCg&input=MAoxCjkKODUKMjIw) (Slightly modified.)
### Well, just for fun: 7 bytes
```
T`12`21
```
Takes base-4 as input, and outputs as base-4.
[Try it online!](http://retina.tryitonline.net/#code=VGAxMmAyMQ&input=MzAxMg)
[Answer]
# 05AB1E, 8 bytes
```
4B12‡4ö
```
Thanks to @Adnan for -5 bytes!
**Uses CP-1252 encoding.**
[Try It Online!](http://05ab1e.tryitonline.net/#code=NEIxMsOC4oChNMO2&input=)
Explanation:
```
4B - Take input and convert to base 4.
12Â - Push 12 bifurcated.
‡ - Transliterate [1, 2] to [2, 1].
4ö - Convert to base 10.
```
[Answer]
# C, ~~32~~ ~~30~~ 29 bytes
```
f(x){return(x&~0U/3)*3+x>>1;} // 30 bit version, see below
// less golfed:
f(x){return ((x & 0x55555555)*3 + x) >>1;} // >> is lower precedence than +
```
Algorithm [copied from xsot's comment on xnor's Python answer](https://codegolf.stackexchange.com/a/81226/30206). Instead of masking both ways, mask one way and combine.
This [compiles to the same asm as the last version I tested](http://gcc.godbolt.org/#compilers:!((compiler:g6,options:'-xc+-std%3Dgnu99+-O3+-Wno-all+-Wno-extra+-fno-verbose-asm',sourcez:PQKgBAIglg5lAuBDANmAKgJ0QVwLaIHIBnMAYTADcBTDIqAewDswRgAoAMwAoAPASgDeGKvGwZGvAGQA/AAwBVYAGYQAJj7BVAailzFSvmoDcAXzZtQYGPWQcqAEzKUadJmHocwPRvQzF3jFT4RADWYAAOAJ7wABZuHNiMAMbwDMysbDC8gsKi4mCqIDwAtCq8mvIyCsp8pmwx2UIiYsyFJWU8VfpqGqqmYGDAwGBEiNRgsVRg8uZDXkT08P5RsW5UPOHCRK6MAHRsAOKNuS1eOp16NSBKAHw3AIx1ABLHzeK8511XBpr9g8N3MBQEjIegAdxoEWESQcVGSU1iiGYWgANCN6BMYsCgSQwTFEPAwAccWB7PQoIwYGwAJKvPISC7VAzXLQ8O6PEwDf5gJJiYSMQnUWhpABcI0QuCmiCIuDA0qJ2TljEcL34YDxUCSMXVNARVCI8AcbAAUnSWlxdEzDEpWb06mwAMRQTyyNiJOgwQKOUGUsAcABsABYuO7YF6wD6YF5BGwBid8pb5AAZJPKHqaMBaMCJlNXPpsMxsCmEjger1cYvRpr0xNp9SaT6XZl9Myhz0OP30DEAXjATaMjrh9md5gs4A4GHosu8vmW0TizCRRAhGDRACNsIT6OFwvQ6IaJjRcBSbPQYJExWuELISVRqOl2G3w0wgtKQgB9XywEOMMsdtUCLGYBPh2d5wsEYS9v2QEgY49BXvAJC9haPBgIC9x8GAkhgGBjAQbUQHxq0RRgMUYAqPBCBEAOhZur%2BYYdi%2BEHvsxkyMO%2BRBYhw8A/n%2BjgATB9HtnBEFgFBTIsAUA4DLB7iqGJ2aodhU5vgRMlCc%2BCFIXJaE3GAjyEW8xGoWRFFaTRswgLGzC9oUGJZlQsbaYUUxZvQ5g4QpzBkXZXJcshSl9goqYGLGPbZt5OG9H5AVYdmeghXwAA8SUYbp9yxk5CkuZmEXFFQvSZWAWW2SAXCRXZmFudlIDeYGID2e4NWRRRsYZGOEwYJEmJTIsMSQmCiCRGi8qIBEe50GuyBTDwAAc/pyjKSrLpCGSyUxb7vrhvEMfxmGAepfE4aJ4n6NJwEaaBCm8HFr6hGpYBEThai5ShpFRbp%2BkEYWTrJMg2D2FMSUGsOAq7DENxusWQbvlugTMbhQYhtDgaw9GYAHcBKNo3dkFBcmyjndg2OElMsXYbjD1PVQL1Zm9ZEFZ9GEWUAAA%3D)),filterAsm:(binary:!t,commentOnly:!t,directives:!t,intel:!t,labels:!t),version:3), and it works (for x up to `0x3FFFFFFF`, and for x above that as long as bit 30 isn't set, see below). In machine code, it's the same length as my existing asm answer.
---
**The above version always clears the high bit of the result**. The best safe version is 32 bytes:
```
g(x){return 2*x-3*(x/2U&~0U/3);} // safe 32bit version, works for all x
```
The Python version doesn't have this problem, because [python uses arbitrary-precision integer types when needed](https://docs.python.org/2/library/stdtypes.html), instead of truncating to a fixed upper limit.
[Answer]
# Javascript (ES6), ~~113~~ 109 bytes
Saved 4 bytes thanks to [Upgoat](https://codegolf.stackexchange.com/users/40695/upgoat)
```
n=>+('0b'+/(..)+$/.exec('0'+n.toString`2`)[0].split``.reduce((p,c)=>p.length-1?[p.join(c)]:[p[0],c],[''])[0],2)
```
### How it works
```
n=>+('0b'+ //parse as binary literal
/(..)+$/.exec('0'+n.toString`2`)[0] //convert to binary string with an even number of digits
.split`` //convert to array
.reduce((p,c)=>p.length-1?[p.join(c)]:[p[0],c],[''])
//swap all numbers
)
```
[Answer]
# J, 20 bytes
```
4#.0 2 1 3{~4#.^:_1]
```
### Usage
```
>> f =: 4#.0 2 1 3{~4#.^:_1]
>> f 85
<< 170
```
Where `>>` is STDIN and `<<` is STDOUT.
### Ungolfed
```
to_base =: 4 #.^:_1 ]
transpose =: 0 2 1 3 {~ to_base
from_base =: 4 #. transpose
```
Three forks.
### Sidenote
In the official interpreter, `^:_1` can be replaced by `inv`, saving 1 byte.
However, none of the online interpreters implement this.
[Answer]
# C#, 44 bytes
Based on the [C implementation](https://codegolf.stackexchange.com/a/81228/54201)
`int f(int n)=>n>3?4*f(n/4)+f(n%4):n%2*2+n/2;`
Try it here: [C# pad](http://csharppad.com/gist/6a4c768f58bf8f4bc2e21c93c34920d4)
[Answer]
# [INTERCAL](http://www.catb.org/~esr/intercal/), 60 bytes
```
DOWRITEIN.1PLEASE.1<-!1~#21845'$.1~#43690DOREADOUT.1DOGIVEUP
```
[Try it online!](https://tio.run/##y8wrSS1KTsz5/9/FPzzIM8TV00/PMMDH1THYVc/QRlfRsE7ZyNDCxFRdRQ/INDE2szRw8Q9ydXTxDw3RM3Txd/cMcw0N@P/fzT80SCHYNczVT8ENKKQQEu4PZnABAA "INTERCAL – Try It Online")
Works for 16-bit integers, with I/O done in the most natural format for INTERCAL: the input is a series of decimal digits spelled out in one of several natural or constructed languages, and the output is in "butchered Roman numerals".
This is one of those rare challenges where INTERCAL's binary operators can actually be used at all intuitively, since repositioning bits is what they're all about. Select (`~`) takes the bits from its first argument corresponding to ones in its second argument and pads them to the right with zeroes, and mingle (`$`) interleaves the bits from its arguments such that the bits from the first argument are more significant. So the straightforward solution is to select out the less significant alternating bits (`.1~#21845`), select out the more significant alternating bits (`.1~#43690`), and interleave them back together in the opposite order. Fortunately for byte count, although INTERCAL's operators have no defined precedence (as the language's goal is to have no precedents), it turns out that the C-INTERCAL on TIO doesn't require much grouping for this particular expression, costing only one byte since `'.` can be abbreviated `!`.
With support for 32-bit integers:
# [INTERCAL](http://www.catb.org/~esr/intercal/), 67 bytes
```
DOWRITEIN:1PLEASE:1<-':1~#0$#65535'$:1~#65535$#0DOREADOUT:1DOGIVEUP
```
[Try it online!](https://tio.run/##y8wrSS1KTsz5/9/FPzzIM8TV08/KMMDH1THY1crQRlfdyrBO2UBF2czU1NhUXQXEAzNVlA1c/INcHV38Q0OsDF383T3DXEMD/v938w8NUgh2DXP1U3ADCimEhPuDGVwA "INTERCAL – Try It Online")
INTERCAL doesn't allow 32-bit literals, which actually makes this a bit *easier* to read, since it means the magic constants for selecting alternating bits have to be constructed by mingling two 16-bit literals together, where one's all zeroes and the other's all ones. (Actually, even if there were 32-bit literals, this would still be shorter. `#0$#65535` is two bytes off `#1431655765`, and the same goes for the other one.) This communicates the whole process unnaturally well for INTERCAL.
An alternate approach with clumsy use of *operand overloading*:
# [INTERCAL](http://www.catb.org/~esr/intercal/), 71 bytes
```
DO:1<-:1/.2$.3PLEASEWRITEIN:2DO:1<-:2PLEASE:2<-.3$.2DOREADOUT:2DOGIVEUP
```
[Try it online!](https://tio.run/##y8wrSS1KTsz5/9/F38rQRtfKUF/PSEXPOMDH1THYNTzIM8TV08/KCCppBBG2MrLR1TNW0QMKB7k6uviHhoBUuHuGuYYG/P/v5h8apBDsGubqp@AGFFIICfcHM7gA "INTERCAL – Try It Online")
This does away with selecting altogether by declaring that `:1` is `.2` mingled with `.3`, setting `:1` to the input, then outputting `.3` mingled with `.2`. Since `:1` was overloaded as `.2$.3`, `DO :1 <- :2` assigns values to `.2` and `.3` such that `:1` acquires the value of `:2`, which results in `.2` containing the more significant alternating bits from `:2` and `.3` containing the less significant alternating bits. This would be the shorter of the two 32-bit solutions by four bytes if `PLEASE WRITE IN :1` could replace `PLEASE WRITE IN :2 DO :1 <- :2` with overloaded `:1`, but `CALCULATING` turns out to be necessary for using overloading. I also feel like there might be some shorter way to carry out the overloading itself than starting the program with `DO:1<-:1/.2$.3`, but since this is INTERCAL I also also feel like there can't be.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 8 bytes
```
ḋṁo↔‰2B4
```
[Try it online!](https://tio.run/##yygtzv7//@GO7oc7G/MftU151LDByMnk////JuamRqYA "Husk – Try It Online")
Same as the Jelly solution.
# [Husk](https://github.com/barbuz/Husk), ~~9~~ 8 bytes
```
ḋṁ↔C_2Θḋ
```
[Try it online!](https://tio.run/##yygtzv7//@GO7oc7Gx@1TXGON7IyAPL@//9vYm5qZAoA "Husk – Try It Online")
General method.
-1 byte from Jo King. (using `Θ`)
[Answer]
## Mathematica, 44 bytes
```
Fold[3#+##&,#~IntegerDigits~4/.{1->2,2->1}]&
```
Same approach as my CJam answer: convert to base-4, swap 1s and 2s, convert back. It also uses alephalpha's trick to replace `FromDigits` with a `Fold` operation to save one byte.
[Answer]
## Actually, 16 bytes
```
4@¡"21""12"(t4@¿
```
[Try it online!](http://actually.tryitonline.net/#code=NEDCoSIyMSIiMTIiKHQ0QMK_&input=MjIw)
Explanation:
```
4@¡"21""12"(t4@¿
4@¡ base 4 representation of n
"21""12"(t translate (swap 1s and 2s)
4@¿ base 4 to decimal
```
[Answer]
# J, 22 bytes
```
([:,_2|.\,&0)&.(|.@#:)
```
Alternative approach based on array manipulation instead of the base 4 trick.
## Usage
```
f =: ([:,_2|.\,&0)&.(|.@#:)
(,.f"0) 0 1 9 85 220 1827 47525
0 0
1 2
9 6
85 170
220 236
1827 2835
47525 30298
```
## Explanation
```
([:,_2|.\,&0)&.(|.@#:) Input: n
#: Get the value as a list of base 2 digits
|.@ Reverse it
( )&. Apply to the list of base 2 digits
,&0 Append a zero to the end of the list
_2 \ Split the list into nonoverlapping sublists of size 2
|. Reverse each sublist
[:, Flatten the list of sublists into a list
&.( ) Apply the inverse of (reversed base 2 digits)
to convert back to a number and return it
```
[Answer]
## REXX, 88 bytes
```
n=x2b(d2x(arg(1)))
o=0
do while n>''
parse var n a+1 b+1 n
o=o||b||a
end
say x2d(b2x(o))
```
[Answer]
## x86 machine code - 19 bytes
Callable function, input in `ebx` output in `eax`.
Lisitng :
```
16 global tukar_bits
17 tukar_bits:
18
19 00000016 89DA mov edx, ebx
20 00000018 8D0412 lea eax, [edx + edx]
21 0000001B D1EA shr edx, 1
22 0000001D 81E255555555 and edx, 0x55555555
23 00000023 8D1452 lea edx, [edx + edx * 2]
24 00000026 29D0 sub eax, edx
25 00000028 C3 ret
```
[Try it online!](https://tio.run/##XY/RbsMgDEWfw1dYlfaydqirFm3qr3RRZQLJ0AipwJ3o12eEspDODwhfXx/b6L0ahLm99G07cW1JmbO/WcIAdrw41enAuAqknIWLi/WOcYmErBvoCNxT1HrYPMlPu2GconOxI42a8d6MwsCA2rL5OTKIMYw/4KTewcl5vf1oqqS2aEzqgqpabOBE2IHDsPLQ9RvdWWjyf06jEDIxLtbMEqwQXicEwP8CRva@gO8XPkxPDrgrTtGUDyorsPItx4GSsU@JULZTM@kUddjO1SZV/JfL3teUo5U534c6xwohHxDwDIeMuYo8IMrLqmya3t7rQ/0L), using x86-64 caller.
---
## x86 machine code - 21 bytes
Callable function, input in `ebx`output in `eax`.
Listing :
```
1 global tukar_bits
2 tukar_bits:
3
4 00000000 89D8 mov eax, ebx
5 00000002 89C2 mov edx, eax
6 00000004 2555555555 and eax, 0x55555555
7 00000009 D1EA shr edx, 1
8 0000000B 81E255555555 and edx, 0x55555555
9 00000011 8D0442 lea eax, [edx + eax * 2]
10 00000014 C3 ret
```
[Try it online!](https://tio.run/##ZY/RbsMgDEWfw1dYlfaydqirFm3qr7RR5QSSoRJSgVfRr8@AsCTb/ICs6@OLLzon@1o/XrqmGbkyJPXFPQyhBzPcrGyVZ1x6ktbAzYZ5y7hAQtb2dATuKGgdbJ7E2WwYp0DOONKgGO/0UGvoURkWnyODUP1wByvUDk7Wqe1HVSS1Qa3TFhTFjIGt/Q4s@hVDX1e0l1qR@yG1RMiO4bAqSrCycCpZAPwdYPDeL8ZTwl@/JwImxUoac6DlBLa0SziQcU/WfqWIqOCkoBGZ2fsyVxq4T5vR1xUo/oMpcXI4hTFsYw/PcKjmS9k4vr2Xh/Ib), using x86-64 caller.
] |
[Question]
[
*We seem to [never](https://codegolf.stackexchange.com/questions/89283/print-an-alphabet-wave/89306#comment217718_89283) get [tired](https://codegolf.stackexchange.com/questions/89283/print-an-alphabet-wave/89306#comment217928_89283) of alphabet-related challenges...*
---
# The recipe
Given
* a string of letters `S`, and
* two positive integers `M`, `N`,
produce an alphabet soup with the letters of `S` occupying **random positions** in a **rectangular bowl** of size `M`×`N`, **framed** by a non-alphabetic, non-space character to represent the rim of the bowl.
Positions not used by letters should be displayed as spaces. See the **examples below**.
# Aditional rules
* The size `M`×`N` refers to the **interior** of the bowl. The size including the rim is `M+2`×`N+2`.
* Each character from `S` should appear *once* in the bowl, in a **different position**; that is, one character cannot overwrite another.
* `S` **may contain duplicates**. For instance, if `S` is the string `'abcc'`, the soup must contain one `a`, one `b`, and two `c` (all in different positions).
* The inputs will satisfy the **restrictions** `M >= 1`, `N >= 1`, `1 <= length(S) <= M*N`.
* The rim of the bowl can be **any non-alphabetic, non-space character**, consistent across program runs and input values.
* Letter positions in the bowl are random, so the result may differ every time the program is run with the same inputs.
* Given the input, every possible set of letter positions should have a **non-zero probability**. Since this cannot be checked from a few realizations of the program, please explain how your code fulfills this.
* Leading or trailing **whitespace** around the rim is allowed.
* `S` will contain are **only uppercase** letters. If wou wish, you can choose to take **only lowercase** letters.
* Input and output are [flexible](https://codegolf.meta.stackexchange.com/q/2447/36398) as usual. For example, the output can be a string with newlines, a 2D character array, or a list of lines.
* [Programs or functions](http://meta.codegolf.stackexchange.com/a/2422/36398) are allowed, in any [programming language](https://codegolf.meta.stackexchange.com/questions/2028/what-are-programming-languages/2073#2073). [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* The shortest code in bytes wins.
# Examples
Inputs are shown as `S, [M N]`, where `M` is number of rows and `N` is number of columns. The character `#` is used for the rim.
```
'O', [1 1]:
###
#O#
###
'HEY', [1 3]:
#####
#YHE#
#####
'HELLO', [4 11]:
#############
# O #
# H #
# LE #
# L #
#############
'ADVNJSGHETILMVXERTYIOJKCVNCSF', [8 12]:
##############
#K V L S #
# A V X H #
#T M C #
# I O N#
# YC #
# G I R SE#
# J F #
#JT D V EN #
##############
'OOOOOOOOOOXXXXX', [13 31]:
#################################
# X #
# O #
# #
# X #
# O #
# X O #
# O #
# X #
# O #
# X #
# O #
# O O O #
# O #
#################################
'ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ', [11 41]
###########################################
# JU#
# Q C M G R T U Y H #
# KI E H M YO #
# V BW I JC #
# SV D P B U #
# A F RF J KP E #
# E N TH Z #
# N BM O Q I AS N WX #
# S O K G L P Q #
#Z L T R L A F DD#
# V Y WX C G XZ #
###########################################
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~20~~ ~~18~~ ~~16~~ ~~15~~ 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
*j.rS²ô2Føε8.ø
```
Takes three inputs in the order: height, width, string. Output as a 2D list of characters.
Uses `8` as border, but could be any digit.
-1 byte thanks to *@Grimy*.
[Try it online](https://tio.run/##AUMAvP9vc2FiaWX//ypqLnJTwrLDtDJGw7jOtTguw7j/XUrCu/84CjEyCkFEVk5KU0dIRVRJTE1WWEVSVFlJT0pLQ1ZOQ1NG) or [verify all test cases](https://tio.run/##yy9OTMpM/W/m5unpeWjlf60svaLgQ@sObzFyO7zj3FYLvcM7/tfWeh3arXNom/1/fy5DIPRwjQSSxkDax8efy4TL0JDL0SXMzyvY3cM1xNPHNyzCNSgk0tPfy9s5zM852I3LgsvQiMsfDiJAgMvQmMsYqNHJ2cXVzd3D08vbx9fPPyAwKDgkNCw8IjKKHBmQU0wMAQ). (TIO contains `}}J»` in the footer to pretty-print the result; feel free to remove it to see the actual output 2D list of characters instead.)
**Explanation:**
```
* # Multiply the (implicit) width and height inputs
j # Pad the (implicit) input-string with up to that amount of leading spaces,
# so the total string-length is equal to that value
.r # Shuffle the characters in the string
S # Convert the string to a list of characters
# (edge-case for the zip below with strings of size 1 with 1x1 dimensions)
² # Push the width input again
ô # Split the list of characters into parts of that size
2F # Loop 2 times:
ø # Zip/transpose the 2D list; swapping rows/columns
ε # Inner map over each line:
8.ø # And surround this line-list with a leading/trailing "8"
# (after the loop, the result is output implicitly)
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 25 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
```
'#',∘⌽∘⍉⍣4{⍵⍴⊃¨↓∘⍺¨?⍨×/⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///X11ZXedRx4xHPXtBZG/no97FJtWPerc@6t3yqKv50IpHbZPBErsOrbB/1Lvi8HR9oGTt/7RHbRMe9fY96pvq6Q9St974UdtEIC84yBlIhnh4Bv8H0kBF6o4uYX5ewe4eriGePr5hEa5BIZGe/l7ezmF@zsFu6gppChYKhkYA "APL (Dyalog Unicode) – Try It Online")
-22 thanks to @ngn, -7 thanks to @ngn and @Adám
Explanation:
```
'#',∘⌽∘⍉⍣4{⍵⍴⊃¨↓∘⍺¨?⍨×/⍵}
{ ⍵} ⍝ Function that generates the content
⍝ argument: ⍵ (width and height), ⍺ (string)
×/ ⍝ get the product
?⍨ ⍝ For each randomized elements
↓∘⍺¨ ⍝ take the character in ⍺
⍵⍴⊃¨ ⍝ turn it back into a matrix of shape ⍵
∘ ∘ ⍣4 ⍝ Then, 4 times, do these 3 things:
'#', ⍝ - prepend a # to the axis
⌽ ⍝ - reverse the columns
⍉ ⍝ - swap columns and lines
```
# ~~[APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 21 [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")~~
**The rim's angles are different characters**
```
{⌂disp⊂⍵⍴⊃¨↓∘⍺¨?⍨×/⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG9qsKteqLOvi3pSfoVCfp76o67FGkBRv@BHvWs09TRS8xKTclKDHX1CgBJAcedI9eLEnBJ1zf/Vj3qaUjKLCx51NT3q3fqod8ujruZDKx61TX7UMeNR765DK@wf9a44PF0fKFn7P@1R24RHvX1AAzz9QerWGz9qmwiyPMgZSIZ4eAaDnAJUpO7oEubnFezu4Rri6eMbFuEaFBLp6e/l7Rzm5xzspq6QpmChYGgEAA "APL (Dyalog Extended) – Try It Online")
Using the dfn to display the box.
[Answer]
# [Python 3](https://docs.python.org/3/), 110 bytes
```
lambda s,m,n,r=['#']:[r+(n*r+[i for i,j in{*zip(s+m*n*' ',range(m*n))}]+n*r)[k*n:-~k*n]+r for k in range(m+2)]
```
[Try it online!](https://tio.run/##nY1NT4NAGITv/RWbeFgWXg@UHkyTHpTSAqVFC2IrErMK2LWwJUsv1ehfx8VvOTqHTXZmnneqw36z40aTj26agpZ3KUU1lMBBjGJ8hJNhLDSFq0KLGcp3AjF4RIw/q0@sUmqtVLmKEQZB@UOmyB8hL4km6yTeqnx4/CrfRBPv5FZy6LOo9UnSpFmOUlZXBT0o9xsqbqkQ9ECGPSTVEgXjWQv9hB9Zq0owvlfUtgKozqoRxqTX@zqXK9jHoINOyG/Pttata3Rdz5PtAeid@uk4WrjB1LZCx5tHK2sZrh3fnZnRwgwmGE5A7/8F/G@tWsktA4zu0TNzbE2mtuPOvPnCP79YBuFldLVaX/8nkRM6DORE8wY "Python 3 – Try It Online")
Randomizes by using a `set` comprehension and returns a 2D character array.
[Answer]
# Bash + coreutils, ~~139~~ 125 characters
```
r=`printf %$3s@@|tr \ @`
echo $r
printf %$[$2*$3]s $1|fold -1|shuf|tr -d \\n|fold -$3|paste -d@ <(:) - <(:)|head -$2
echo $r
```
Sample run:
```
bash-5.0$ bash soup.sh HELLO 4 11
@@@@@@@@@@@@@
@ H @
@ OE @
@ L @
@ L@
@@@@@@@@@@@@@
```
[Try it online!](https://tio.run/##S0oszvj/v8g2oaAoM68kTUFVxbjYwaGmpEghRkHBIYErNTkjX0GliAsuHa1ipKViHFusoGJYk5afk6Kga1hTnFGaBtKim6IQE5MHFVYxrilILC5JBYo6KNhoWGkq6IKpmozURJC0Eczs////Ozo5u7i6uXt4enn7@Pr5BwQGBYeEhoVHREaRI/Pf0PC/iSEA "Bash – Try It Online")
### Bash + coreutils + boxes, 97 characters
```
printf %$[$2*$3]s $1|fold -1|shuf|tr -d \\n|fold -$3|boxes -dsimple -s$[$3+2]x$[$2+2] -pa0 -itext
```
Sample run:
```
bash-5.0$ set -- HELLO 4 11
bash-5.0$ printf %$[$2*$3]s $1|fold -1|shuf|tr -d \\n|fold -$3|boxes -dsimple -s$[$3+2]x$[$2+2] -pa0 -itext
*************
* O L E *
* H *
* *
* L *
*************
```
[Try it online!](https://tio.run/##S0oszviflF@RWqyhqVCtkJxYYq1Q@7@gKDOvJE1BVSVaxUhLxTi2WEHFsCYtPydFQdewpjijNK2mpEhBN0UhJiYPKqxiXAM2BShanJlbkJOqoFsM1G2sbRRbATIFSCvoFiQaKOhmlqRWlPz//9/RydnF1c3dw9PL28fXzz8gMCg4JDQsPCIyihyZ/4aG/00MAQ "Bash – Try It Online") (Partially, as `boxes` is not installed on TIO.)
[Answer]
# [J](http://jsoftware.com/), ~~30~~ 29 bytes
-1 byte thanks to Jonah
```
'#'|.@|:@,^:4[$*/@[(?~@[{{.)]
```
[Try it online!](https://tio.run/##nY7BCoJQEEX3fcVYwVSY9VIiH0SaaWovLTXTpDaRRJs@wOjXTTOCXHaHWcw9d4a55TJHyXHMURmx0RQwhSkFBB6GQIvuC6B5zMixhQ9BeVCFP1EpafcGStKZPZUky4TuMe82LufrHUhRKaCLUM3FxY8vlr6px/gLRJAqwJhbQxMgo5Kpi9Cx/aWpBxZbh5HuBbHl2istdDTfqO0QEcTqg6@iUvUYAekdU@faQjeWpmWv2NpxN1vPD3bhPooP/xDMXw "J – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~163~~ ~~111~~ 93 bytes
```
param($w,$h,$s)'#'*$w+-join($s|% *ht($w*$h)|% t*y|sort{Random})+'#'*$w-replace".{$w}",'#$0#
'
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQ6VcRyVDR6VYU11ZXUulXFs3Kz8zT0OluEZVQSujBCitpZKhCeSUaFXWFOcXlVQHJeal5OfWampDNOgWpRbkJCanKulVq5TXKumoK6sYKHOp////38Twv6Hhf3VHJ2cXVzd3D08vbx9fP/@AwKDgkNCw8IjIKHJk1AE "PowerShell – Try It Online")
Takes input as `$w`idth, `$h`eight, `$s`tring.
Constructs a string of `#` of the appropriate `$w`idth, string-joins that with some computation, and then that same `#` string again. The computation starts with taking the input `$s`tring, and doing a .padRig`ht` up to the `$w`idth by `$h`eight length (i.e., make a string long enough to completely take up the rectangular space. We then convert that string `t`oCharArra`y`, and `sort` it `Random`ly. That gives us the mixed-up middle portion. Finally, we `-replace` it into chunks of equal `$w`idth, and surround those chunks with `#`s.
*-52 thanks to inspiration from AZTECCO*
*-18 bytes thanks to mazzy*
[Answer]
# JavaScript (ES7), 125 bytes
Returns a string. Uses `0` as the frame character.
```
(s,h,w)=>(a=[...s.padEnd(w++*h++)].sort(_=>Math.random()-.5),g=x=>y+~h?(x%w&&y%h&&a.pop())+[`
`[x-w]]+g(x<w?x+1:!++y):a)(y=0)
```
[Try it online!](https://tio.run/##bctNT8JAFIXhPb9CF5R7ve1E/EgMcUoMVgELJEIaSdPIhEJHg52m0zDTjX@91rgzJGf3nudTHIXelh9F5eUq3TV73oB2pWuQ@yB4zBjTrBBpkKdgiC4kESZMq7KCd@7PRCVZKfJUfQF67BbdjFvu1/Qth2C7xnHqrnQcwQpVACLFm84mtp5JEsrA3puhpf7gnKjGgUCo@SU2W5Vrddixg8pgD71Fzz3rt0Ps/CvjYP3Xrk@1MPyVN@3hBH14jObT5fM4WE3CWfQWvK7Wk8X0ZRTNR8unlt217Aqx@QE "JavaScript (Node.js) – Try It Online")
### Commented
```
(s, h, w) => ( // s = string; h = height; w = width
a = // build an array a[] consisting of:
[...s.padEnd(w++ * h++)] // all original characters in s padded with spaces for a
.sort(_ => // total length of w * h, in a random order
Math.random() - .5 // (this is not guaranteed to be uniform, but it is not
), // required to be)
g = x => // g is a recursive function taking x:
y + ~h ? // if we haven't reached the end of the grid:
( x % w && // if we're not located on a vertical border
y % h && // nor on a horizontal border,
a.pop() // extract the last character from a[]
) + // (otherwise, append '0')
[`\n`[x - w]] + // if we've reached the end of the row, append a linefeed
g( // append the result of a recursive call:
x < w ? x + 1 : !++y // using either (x+1, y) or (0, y+1)
) // end of recursive call
: // else (end of grid):
a // a[] is now empty and can be used as an empty string
)(y = 0) // initial call to g with x = y = 0
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 23 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Anonymous tacit infix function. Takes `[M,N]` as left argument and `S` as right argument.
```
'#',∘⌽∘⍉⍣4⊣⍴×/⍛(?⍨⍤⊣⊇↑)
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/X11ZXedRx4xHPXtBZG/no97FJo@6Fj/q3XJ4uv6j3tka9o96VzzqXQIS62p/1DZR83/ao7YJj3r7HvVN9fR/1NV8aL0xUBjICw5yBpIhHp7B/w0VDBXSFNT91bkMFYxBLA/XSHUuEwVDQwjHxwcoZaFgaATiOrqE@XkFu3u4hnj6@IZFuAaFRHr6e3k7h/k5B7sBTTBWMIaYBgcRIACUMVQwAcs4Ojm7uLq5e3h6efv4@vkHBAYFh4SGhUdERpEjow4A "APL (Dyalog Extended) – Try It Online")
`×/⍛(`…`)` apply the following function between the arguments, replacing the left argument with its product:
`↑` take `M`×`N` characters from `S`, padding with spaces on the right
`⊇` reorder that to the following order:
`?⍨⍤` the shuffled indices 1 through…
`⊣` the left argument (`M`×`N`)
`⍴` **r**eshape that to the following shape:
`⊣` the left argument (i.e. `M` rows and `N` columns)
`'#'`…`⍣4` apply the following function four times, each time with the hash character as left argument:
`∘⍉` transpose the right argument
`∘⌽` mirror the right argument
`,` concatenate a column of hashes to the left side of that
[Answer]
# PHP 7.4, ~~107~~ ~~99~~ 94 characters
```
fn($s,$r,$c)=>_.chunk_split(($b=str_pad(_,$c,_)).str_shuffle(str_pad($s,$r*$c)),$c,"_
_").$b._
```
Thanks to:
* [Ismael Miguel](https://codegolf.stackexchange.com/users/14732/ismael-miguel) for reminding me about PHP 7.4's arrow functions (-10 characters)
* [Night2](https://codegolf.stackexchange.com/users/81663/night2) for
efficiently reversing the concatenations and the `join()` (-8 characters)
* [Night2](https://codegolf.stackexchange.com/users/81663/night2) for showing how to use `chunk_split()`'s `$end` parameter (-5 characters)
[Try it online!](https://tio.run/##nY9Rb4IwFIXf@ysIaWJrGpJNH0wUzYYoIIIKMjAmzWSSLhpsrPx@bDUz84EXb/rU851z7uWM14MRZxwAKE4V18y6KBEUBJ4JzLE5pEbOqvJABT/@XhCCO1NczpR//yAqAUIxNtSHYFVRHPfoT7wltGUCVpROAdWxAXcGrfsA7HN20m51qBW2iPYmHyaavi23pd5/kh07uwOdRsD3VUZXUk0hH@Mk8KKpY8euP09SexVnbujNrCSwoon09qT3vcEbPiZVo5bpyG0aqz6tsT2ZOq438@dBuFiuonidfKXZ5hVFtcnbu//a6is "PHP – Try It Online")
### PHP 7.3, ~~117~~ ~~112~~ 108 characters
```
function s($s,$r,$c){echo _.chunk_split(($b=str_pad(_,$c,_)).str_shuffle(str_pad($s,$r*$c)),$c,"_
_").$b._;}
```
Thanks to:
* [Night2](https://codegolf.stackexchange.com/users/81663/night2) for efficiently reversing the concatenations and the `join()` (-5 characters)
* [Night2](https://codegolf.stackexchange.com/users/81663/night2) for showing how to use `chunk_split()`'s `$end` parameter (-4 characters)
Sample run:
```
php > function s($s,$r,$c){echo _.chunk_split(($b=str_pad(_,$c,_)).str_shuffle(str_pad($s,$r*$c)),$c,"_
php " _").$b._;}
php > s('HELLO', 4, 11);
_____________
_ L _
_ L _
_E _
_ OH _
_____________
```
[Try it online!](https://tio.run/##K8go@G9jXwAk00rzkksy8/MUijVUinVUinRUkjWrU5Mz8hXi9ZIzSvOy44sLcjJLNDRUkmyLS4riCxJTNOKBinTiNTX1QALFGaVpaTmpGjBJsClaQFM0QaqU4rnilTT1VJL04q1r/xdrqDs6Obu4url7eHp5@/j6@QcEBgWHhIaFR0RGkSOjrqNgaKijYGKoaf0fAA "PHP – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~22~~ 19 bytes
```
tZ"ibpyn&Z@(TT35&Ya
```
[Try it online!](https://tio.run/##y00syfn/vyRKKTOpoDJPLcpBIyTE2FQtMvH//2gTBdNYLvXEpOSUVHUA "MATL – Try It Online")
Thanks @LuisMendo for saving 3 bytes, so now it has the same bytecount as @flawr's [answer](https://codegolf.stackexchange.com/a/193908/32352), but sufficiently different to post anyway. High-level agorithm overview:
```
Z" % Create n x m matrix of spaces
( % Index into this matrix:
i % The alphabet vermicelli (explicit input)
&Z@ % at a random locations (randperm), which are
yn % length(S) numbers, ranging
t bp % from 1 to n*m
TT35&Ya % And finally add a border
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 121 bytes
Creates the bowl, queries the indices of all spaces within the bowl, samples a number of spaces equal to the size of the string, and fills them in. `sample` does not return a sorted list, so there is no need to shuffle. Searching indices up to `9*m*n` (which almost certainly goes out of range) will still get all spaces and is 1 byte shorter than `r.size`.
```
->s,m,n{r=[t=?@*(n+2),*["@#{' '*n}@"]*m,t]*$/;i=-1;(0..9*m*n).select{|j|r[j]==' '}.sample(s.size).map{|j|r[j]=s[i+=1]};r}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf165YJ1cnr7rINrrE1t5BSyNP20hTRytayUG5Wl1BXSuv1kEpVitXpyRWS0XfOtNW19Baw0BPz1IrVytPU684NSc1uaS6JqumKDor1tYWqKNWrzgxtyAnVaNYrzizKlVTLzexAK6gODpT29Ywtta6qPZ/QWlJsUJatLq/uo6CIRDFcsFEPFwjIWLGyGI@PiCVJkAJJKWOLmF@XsHuHq4hnj6@YRGuQSGRnv5e3s5hfs7BbkDlFkDlRkjKnZxdXN3cPTy9vH18/fwDAoOCQ0LDwiMio8iRATkS6EoTw9j/AA "Ruby – Try It Online")
[Answer]
# [Red](http://www.red-lang.org), ~~120~~ ~~116~~ ~~114~~ 112 bytes
-2 bytes thanks to @Kevin Cruijssen!
```
func[s m n][random pad s m * n insert/dup t: copy"00"0 n
print t loop m[print rejoin[0 take/part s n 0]]print t]
```
[Try it online!](https://tio.run/##nY/BToNAGITP8BSTPXopSA@mN21pgVJQWhHc7GFll1i1u2ShMT49hWJ8AOc0/z@TLxkjRZ9JQZltuBL6NGulFFD6264X6OuzqmiLExSjU46GC4yfGygcVStNNxPnBt0ClW5@iOMQB8puzFF16PCldYMTnU4jP/RRUQcd/5SzhptuICk4jP3WWV9rI3n1DsrxhopRkhK4cG3LIoFfjt6bfBwPyRzuNbpf5Um03wT@IYx3eeFnhzJMo@0yT5b7NcEd3Nuxlv6pGDXQPHgT4GG58tebIIy28S5JH5@y/eE5fynK1/8kA9jF3GW2RWtch2AaSAjrLw "Red – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~74~~ 67 bytes
*-5 bytes thanks to Jo King*
```
{0 X~0 x$^n,|comb($n,[~] $^s.comb[pick *,^$^m*$n]X//' '),0 x$n X~0}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/2kAhos5AoUIlLk@nJjk/N0lDJU8nui5WQSWuWA/Ejy7ITM5W0NKJU4nL1VLJi43Q11dXUNfUAenJA@mt/V@cWKmQpmGio2BoqKOg7uHq4@OvrqmXlZ@Zp6EUk6ekaf0fAA "Perl 6 – Try It Online")
### Explanation
```
{ }
^$^m*$n # Range 0 .. M*N-1
pick *, # Shuffle
$^s.comb # Split S into chars
[ ] # Pick shuffled elements
X//' ' # undef to space
[~] # Join
# Split into n-character strings
comb($n, )
| # Flatten
# Add top and bottom of bowl
0 x$^n, ,0 x$n
# Add left and right of bowl
0 X~ X~0
```
[Answer]
# T-SQL 2017, 232 bytes
Testing this online is an older version of sql-server costing another character. I posted the shorter version.
**Golfed:**
```
DECLARE @ varchar(max)=''SELECT top 999 @+=substring(@i,number+1,1)FROM spt_values
WHERE type='P'and number<@a*@b
ORDER BY newid()WHILE-@b<1SELECT @=stuff(@+' ',@b*@a+1,0,'#
#'),@b-=1PRINT stuff(replicate('#',2+2*@a),2+@a,0,trim(@))
```
**[Try it online](https://data.stackexchange.com/stackoverflow/query/1120256)**
**Ungolfed:**
```
DECLARE @ varchar(max)=''
SELECT top 999 @+=substring(@i,number+1,1)
FROM spt_values
WHERE type='P'and number<@a*@b
ORDER BY newid()
WHILE-@b<1
SELECT @=stuff(@+' ',@b*@a+1,0,'#
#'),@b-=1
PRINT stuff(replicate('#',2+2*@a),2+@a,0,trim(@))
```
[Answer]
# [Perl 5](https://www.perl.org/) `-lF`, ~~99~~ 97 bytes
*-2 bytes courtesy of @NahuelFouilleul*
```
%k=map{$_=>$F[$_]||$"}0..($m=<>)*($n=<>)-1;say+($p='#'x($n+1)),map"#
#"x!($i++%$n).$_,values%k,$p
```
[Try it online!](https://tio.run/##FcvBDoIgHIDxO28R/J0QyqDmqfDorSdojVF5cCKyqGbLXj2y07f9ti@0N1ellPV6sOENRtfQHMGc5hnwRwpBYdD7mq0p@H9LtYv2xSkEnZN8WpQrxorlxQQRPK0odJxn4JkAUzyte7Qx6wsIKdnz5Yq2aPMdw70bfUzloRJSyVS65gc "Perl 5 – Try It Online")
[Answer]
# k4, ~~32~~ 28 bytes
```
{4{|+x,'"#"}/y#a?(a:-*/y)$x}
```
edit: -4 thanks to Galen Ivanov!
called like
```
f["hey";3 3]
```
---
explanation:
```
(a:-*/y) / neg product of y and assign to a
$x / left pad x so we have char vector the length of the inner area
a? / take `a` random drawings. if a is negative, draw with no duplicates/replacements
y# / reshape to y's dimensions
4{ }/ / do {} 4 times
|+x,'"#" / append "#" along right-side of x then transpose (+) and reverse (|)
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), ~~180~~ 178 bytes
Not a single extra import:
```
(y,m,n)->{for(m*=n;y.length()<m;y+=" ");var s="";for(;m-->0;y=s)for(var c:y.split(s=""))s=Math.random()<.5?s+c:c+s;s="#".repeat(n);return(s+y+s).replaceAll(".{"+n+"}","\n#$0#");}
```
[Try it online!](https://tio.run/##zVNdb9owFH1OfsWV2YNNTAoVlSrcsDFGv0ZbqVTVpm0PbgiQznEi22kVIX47syGMautDH/awJ1/fc3xz78m5j/yJtx6nP9dpVuTKwKO9h6VJRdhk/l@5WSljk@byVVAblfDsT4g/G5fyP5zWb7m4kCZRMx4nfrqL4E6lO8LJgMJHCkMKt31Y@t4t8KIQFR4AtwA8WAhiwvyVHwuuNVzxVDpeUT6INAZtuLHHU55OIbMQnhiVyvm3H8DVXBPH9F5@bQtTcF3NE/Ui2CJ9MFs2RN4aVzSjkrT6y1mucNaMJKtCkci5WWBykrEqiBAgwp64Ah0hxByNZa1Wv82qSBN3dVjcq0JdiNRgxyJER1fcLELF5TTPbKXw6L0O4l4caGYJDRSqpEi4wZIwlZhSSayDKtDE5YXVbyAERuESBTJAK0TRd9l4127YRlZrz2N24kmlTZKFeWnCwk5lhMT1WOFWXVRKvShnM5FMrYRucEShS@GIkLe9byPaoZ23ss9H4/ENol3aefOTwaf768vJ2fno7mJ8df9ldHv39eLm8vPw/no4OUX0mHYO/02pndjdZpfQ46bt8dBGrvTK9w4OoCqzLE209VMCFYMMoggWSTpfGAbSXZ7TqVn43saCOi@Lw9qDUFGw/UC2PSRZOi@ISCbPMFCKV@NUm5M@3u/UJqtDrh2CcRVYd@3ay5qyBXv3EVI7yvmJsGEuRLJxuA7rH4vFb2O@cFTQIbVL@1GbiZBPp9gatikpalgb2WJ1sk1B7@JNYF@NeLzAe717vY3ghL3yC6wXfd@rhXCq7EXZalJL8h8uFt5tFqlXq7NZLd9frX8B "Java (JDK) – Try It Online")
It was quite the struggle to get this golfed down. In particular, the imports involved with Collections.shuffle()/Arrays methods were too much to accept, so I had to create my own String shuffling algorithm (probably neither efficient nor uniformly distributed). Massive thanks to Steven for [proving any set of positions can be generated](https://cs.stackexchange.com/a/115439/110322) from the algorithm.
Formatted (with explanation):
```
(y, m, n) -> // y = yummies in the soup,
{ // m = height, n = width
for (m *= n; y.length() < m; y += " ") // set m to m*n and
; // add spaces to y to fill up
var s = ""; // the rest of the soup
for (; m-- > 0; y = s) // for m*n iterations, scramble y
for (var c : y.split(s = "")) // with random appends
s = Math.random() < .5 ? s + c : c + s;
s = "#".repeat(n); // create the top/bottom of the rim
return (s + y + s).replaceAll(".{" + n + "}", "\n#$0#"); // add all sides of the rim
};
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 27 bytes
```
NθNη↖B⁺²θ⁺²η#FS«W℅KKJ‽θ‽ηPι
```
[Try it online!](https://tio.run/##TYxNCsIwGAXX7SlC3XyBuqi40p0gqLS2@HOA2KYmmCZpTKognj1GUXA3w3tMzYipFRHer6V2duu6EzXQ43n87yx4oQYKs6POaWuDLtQdKuGuMElRj1P0YxY4GSXh0SqD4FPZW8PlGTBGjzi6MS4ogtI0XBIBFaWXsGC0cZ0@KNgR2agO3skvMhxiUeGE5Tp0LPDgT@@zLJ7Gq2Wel348iBc "Charcoal – Try It Online") Link is to verbose version of code. Takes input in the order width, height, string. Explanation:
```
NθNη
```
Input the width and height.
```
↖B⁺²θ⁺²η#
```
Frame the bowl.
```
FS«
```
Loop over the characters in the string.
```
W℅KKJ‽θ‽η
```
Jump to a random position in the bowl until an empty spot is found.
```
Pι
```
Print the current character without moving the cursor.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), ~~21~~ 18 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
úV*W ö¬òW ²Ô²û2W+2
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=%2blYqVyD2rPJXILLUsvsyVysy&input=IkhFTExPIgo0CjEx)
```
úV*W ö¬òW ²Ô²û2W+2 :Implicit input of string U=S and integers V=M & W=N
úV*W :Right pad U with spaces to length V*W
ö¬ :Random permutation
òW :Split to array of strings of length W
² :Push 2
Ô :Reverse
² :Push 2
û2W+2 :Centre pad each element with "2" to length W+2
:Implicit output, joined with newlines
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~29 27~~ 19 bytes
```
pZ@iy~hw)1GeTT35&Ya
```
[Try it online!](https://tio.run/##y00syfn/vyDKIbOyLqNc09A9NSTE2FQtMvH//2hDYx1jw1gudX84iAABdQA "MATL – Try It Online")
Thanks @LuisMendo for -8 bytes!
Explanation: `p` computes the number of soup-pixels. Then `Z@` produces a random permutation of size of number of soup pixels. We will use this as indices to `iy~h` which is the input string with enough spaces added. `w)` swaps the two and indexes one with the other. We then reshape `1Ge` the shape into the desired rectangle and `#`-pad it using `TT35&Ya`.
[Answer]
# [Icon](https://github.com/gtownsend/icon), ~~136~~ ~~133~~ ~~131~~ 118 bytes
```
procedure f(s,n,m)
s||:=repl(" ",m*n-*s)
!s:=:?s&\z
write(t:=repl(0,m+2))
write(0,s[1+(0to n)*m+:m],0)&\z
write(t)
end
```
[Try it online!](https://tio.run/##nZBfa4MwFMXf8ykyH0aiGWjbh@Eoo7O2alvdqnO6Pw@lpiAzsRjLoPS7uxSlG8ynHe5L8rvnntzk25I3zb4qtzQ7VBTukCCcMAzE6WSOK7ovkAIVwlR@owoMroQ5Nu/F9fsRfFV5TVHdNemEaQOMu1udiDdDQ3pdQo5Vppnsg@j4lwsDyrOmyPknrDY8Kxn4eQLb5BxhAKValh9pd94hZaIQaMjCd7CddSGOnbZs2MNoUZSSjmRDj3UyjX0vnDt25C5XcWKvo9QNvIUV@1Y4k7ZbaRv8tQUXJWed04cyvi/gwZras7njeovlyg8en9Zh9By/JOnrf8g5SO45Mtpv/AY "Icon – Try It Online")
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~169~~ ~~...~~ 156 bytes
```
i,b;f(n,m,s)char*s;{char o[b=i=-~++n*(m+=3)],*a=o;for(srand(&a);--i;)*a++=i%m?-~i%m<3|i<m|i>m*n?35:32:10;for(*a=0;*s;*a=*a-32?*a:*s++)a=o+rand()%b;puts(o);}
```
[Try it online!](https://tio.run/##nU/JbsIwFLznK6JIVN4iYUylCpMiCmEN0AJNocDBbK2lxkFJOLH8euqkiA/oHN7zeDzz/Db25keorzSVZM33QJGAxHDzLSIU81PWzXCxdqRjXzFWCATYYXBFkHBCvg8jEEdCbcGDgNy2JYdIYOzIQlCzr7pW2VlWg7N8DpCqsccKK1VoMbdpf5HrCbojYbNSDYkKijGGOhfnkbCw5odjEoMQ8ksqVWIGQioAzZNh5N@Kk2ixcqz6S6Ppttqdbq/vDYaj17fxZPruf8zmn/9RLG7sQZlQSqyO63kjC2YXlGh@P7NMm/@xJ0JLxKo3/WFv0u6406438GfueDrvjnr9hj9sTFo3GyMsC7ljluGmUVKmRO@jmUa@tbVUS7VT2@yFqRHtkmOkzCI3Lukv "C (clang) – Try It Online")
Saved 7 @ceilingcat suggestion to use -~variable and auto storage for string o plus many improvements.
Saved 4 again from @ceilingcat
Degolf :
```
char*a,// pointer for set operations
*o=malloc(b=i=(m+=3)*(n+=2)); => o[b=i=(m+=3)*-~++n]
// before allocating for the whole bowl as a char array
// increments m by 3 (2 for rims and 1 for '\n') and n by one but allocates for 2(rims)
// and assigns bowl size to i and b.
srand(time(0));// seeds rand function
for(// loop to make empty bowl
a=o;// using pointer as iterator
--i ;)// i decremented as a counter
*a=// sets every char to..
i%m?// if(not) over right side of bowl (m+3)
-~i%m<3|i<m|i>m*n-m?35// if on rim '#'//-~i == (i+1)
:32 // else ' '
:10;// i%m==0
for(*a=0;// before loop terminates bowl with \0
*s;// for every letters(exit on '\n')
*a=*a-32?*a:*s++)
// puts letter if bowl at a is a space and
// go to next letter
a=o+rand()%b;
// sets a to o offsetted by random
puts(o);// prints bowl
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
P⁶ẋaẊs⁸ṪṾ€«”~ZƊ⁺
```
A dyadic Link accepting a list of integers, `[M, N]`, on the left and a list of characters, `S`, on the right which yields a list of lists of characters, the lines. Uses the tilde character, `~`, as the border.
**[Try it online!](https://tio.run/##AT8AwP9qZWxsef//UOKBtuG6i2Hhuopz4oG44bmq4bm@4oKswqvigJ1@WsaK4oG6/8OnWf//WzQsMTFd/ydIRUxMTyc "Jelly – Try It Online")**
All possible outputs have a non-zero chance of being yielded since we shuffle (`Ẋ`) a list of the characters of `S` along with the appropriate number of spaces.
The code `Ṿ€«”~ZƊ⁺` saves the byte which I imagine would be required to join with newlines that full programs using an integer such as zero would need to employ (e.g. `P⁶ẋaẊs⁸Ṫ;€0ZUƊ4¡Y` or `P⁶ẋaẊs⁸Ṫj@€Ø0Z$⁺Y`). Maybe there's a way to save more...?
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 274 bytes
[Without LINQ]
Embarrassing number of bytes, but, this is what I got.
```
(x,y,z)=>{var f=new string('#',x+2)+'\n';char[] b=new string(' ',y*x).ToCharArray();Random r=new Random();while(z.Length>0){var d=r.Next(0,y*x);if(b[d]==' '){b[d]=z[0];z=z.Substring(1);}}z=f;for(var j=1;j<y*x+1;)z+=(j%x==1?"#":"")+b[j-1]+(j++%(x)==0?"#\n":"");return(z+=f);}
```
[Try it online!](https://tio.run/##fZHLauswEIb3eQrhUizVrrFDF6WqckgD4RR64yTQRZqFL3IsV5GMJCeOQ549R7a76aJFCM3o/@cbMUr1dSoVPdeaiQ1YHLShWzxKeaw1eFNyo@LtcQRAVSecpUCb2NhjJ1kGnmMmIOpEAOa1SO@ZMH63tVGW9XVMwCcgZ9j4B79FZHLcxQrkRNA9GHToXrh@442R534IF6dFrFZrkHxzANc/XDUoWMqZladKxQeI8L9YZHILVG8dEnu7LxinsA2eqNiYYhKivmNGVPBCGwPDnoRZDpNVtibEstGxD9tVuMYtaYNFnXw1jhA@nVqS41wq2GFKEuHy3hK8CKPWI7C8bAiJ/jgXzp3jIC9ZldfR2oOl513CBhESWulD9CJW1NRKQFuWW@4Zj4ZhBzMptOQ0eFfMUPgJb/0o9J2/lHP5LhXPHIR@9Ea3/tialwVV9FFP5/bDHoXNFrKufqsbD03eaEWfaFc1rSold1QvC6YXjHMmqNYPtXmRxuKGYb7mNpzJjP5GvvFvuvcwPbcUi6MPcs/7gpNd5/8 "C# (.NET Core) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~105~~ 78 bytes
Takes an array of characters and two integers; returns a string.
```
->s,h,w{((e=?#*w)+(s+[" "]*(h*w-s.size)).shuffle*""+e).gsub /.{#{w}}/,'#\&#
'}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3_XTtinUydMqrNTRSbe2Vtco1tTWKtaOVFJRitTQytMp1i_WKM6tSNTX1ijNK09JyUrWUlLRTNfXSi0uTFPT1qpWry2tr9XXUlWPUlLnUayGm7ikoLSlWcItWLY_2UHBV8AFC_1gdBRMdBUPDWIiSBQsgNAA)
] |
[Question]
[
Write a program or function that given *n ≥ 1* returns the number of solutions to ±1 ± 2 ± 3 ± ... ± n = 0.
For n = 6 there are no solutions, so the answer is 0. For n = 4 there are two solutions, so the answer is 2 (the two solutions are 1 - 2 - 3 + 4 = -1 + 2 + 3 - 4 = 0).
This is OEIS sequence [A063865](http://oeis.org/A063865). Some example input/outpus are:
```
n a(n)
1 0
2 0
3 2
4 2
5 0
6 0
7 8
8 14
9 0
10 0
11 70
12 124
13 0
14 0
15 722
16 1314
```
---
Shortest code in bytes wins.
[Answer]
# JavaScript (ES6), 35 bytes
*Saved 1 byte thanks to @tsh*
```
f=(n,s)=>n--?f(n,n-~s)+f(n,n+~s):!s
```
[Try it online!](https://tio.run/##HcsxDkBAEEDR3ilGt5O1Eo0Cy1kEK0RmxIhGuPqaqP5r/tpfvQzHsp@OeJxiDN5QJuhbcq4LanKvoP1lVVUqMfBhCDwUNRA02lJhLcKdAAxMwtuUbzzrAzoiJk/8AA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 33 bytes
```
Count[{1,-1}~Tuples~#.Range@#,0]&
```
Counts the `n`-tuples of 1 and -1 whose dot product with `Range[n]` is 0.
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zgq/DfOb80ryS62lBH17C2LqS0ICe1uE5ZLygxLz3VQVnHIFbtv0t@dEBRJlBRno6CkoKunYKSjkJadF5srI5CNVDI0Kw29j8A "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 42 bytes
```
f n=sum[1|0<-sum<$>mapM(\x->[x,-x])[1..n]]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00hz7a4NDfasMbARhfIsFGxy00s8NWIqdC1i67Q0a2I1Yw21NPLi439n5uYmWcLkczTtSsoLQkuKfLJ0yjOyC9XyNPWVlLQtVNQ0tYG8TWAxmpqgnUamsX@BwA "Haskell – Try It Online")
This is ~~2~~ 1 byte shorter than any recursive function that I could write.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
```
X®‚sã€ƶO_O
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/4tC6Rw2zig8vftS05tg2/3j///8tAA "05AB1E – Try It Online")
**Explanation**
```
X®‚ # push [1,-1]
sã # cartesian product with input
€ƶ # multiply each element in each list with its 1-based index
O # sum each list
_ # logical negation of each sum
O # sum
```
[Answer]
# C (gcc), ~~45~~ ~~62~~ ~~52~~ 50 bytes
```
f(n,r){n=n?f(n-1,r+n)+f(n-1,r-n):!r;}F(n){f(n,0);}
```
Port of Kevin Cruijssen's Java 8 [answer](https://codegolf.stackexchange.com/a/161131/79343).
Try it online [here](https://tio.run/##LYqxCgIxEAXr5CvWA2GXJHBnaTzs7itsJBJJ4VOW60K@PUawmoGZFJ4p9Z4ZXqVixXVoWLw6iPtrgJwPGtvGkPo7Z4mtv@4FLFStyW/lgp0KrbTEgQud5kHnxBrz0dEyT8fHDZOnjYtItK1/AQ).
Note that due to the improvements suggested in the comments, the code produces undefined behaviour to the point of not working when compiled with clang.
Thanks to [etene](https://codegolf.stackexchange.com/users/79471/etene) for golfing 3 bytes.
Thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) for golfing 10 more bytes.
Thanks to [Christoph](https://codegolf.stackexchange.com/users/29637/christoph) for golfing another 2 bytes.
Ungolfed version:
```
f(n, r) { // recursive function - return type and parameter type are omitted, they default to int
n = // instead of returning, we set n - dirty trick
n ? // if n is not 0, recurse
f(n-1,r+n) // +n
+f(n-1,r-n) // -n
!r; // else if r != 0 return 0 else return 1
}
F(n) { // function to start the recursion; again implicitly int(int)
n = f(n, 0); // call the recursive function; this time we simply don't return
}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~9~~ 8 bytes
Thanks to **Emigna** for saving a byte!
### Code:
```
LæO·sLO¢
```
Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##MzBNTDJM/f/f5/Ay/0Pbi338Dy36/98CAA "05AB1E – Try It Online")
### Explanation
```
L # Create the list [1, 2, .., input]
æ # Compute the powerset of this list
O # Sum each list
· # Double each element
sLO # Compute the sum of [1, 2, .., input]
¢ # Count the number of occurrences
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~14~~ 13 bytes
```
[la]Z^G:!Y*~s
```
*Thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe) for saving 1 byte!*
[Try it online!](https://tio.run/##y00syfn/PzonMTYqzt1KMVKrrvj/f0MzAA) Or [verify all test cases](https://tio.run/##y00syfmv5PA/OicxNirOwUoxUquu@P9/QytDMwA).
### Explanation
Consider `n = 3` as an example. Stack is shown upside down, that is, newest appears below.
```
[la] % Push array [1 -1]
% STACK: [1 -1]
Z^ % Cartesian power with inplicit input n
% STACK: [ 1 1 1
1 1 -1
1 -1 1
1 -1 -1
-1 1 1
-1 1 -1
-1 -1 1
-1 -1 -1]
G: % Push n, range: gives [1 2 ... n]
% STACK: [ 1 1 1
1 1 -1
1 -1 1
1 -1 -1
-1 1 1
-1 1 -1
-1 -1 1
-1 -1 -1],
[1 2 3]
! % Transpose
% STACK: [ 1 1 1
1 1 -1
1 -1 1
1 -1 -1
-1 1 1
-1 1 -1
-1 -1 1
-1 -1 -1],
[1
2
3]
Y* % Matrix multiplication
% STACK: [6
0
2
-4
4
-2
0
-6]
~ % Logical negation
% STACK: [0
1
0
0
0
0
1
0]
s % Sum of vector. Implicit display
% STACK: 2
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
ŒPS€ċÆṁ$
```
[Try it online!](https://tio.run/##y0rNyan8///opIDgR01rjnQfbnu4s1Hlf9DRPYfbgQLu//8bmgEA "Jelly – Try It Online")
### How it works
```
ŒPS€ċÆṁ$ Main link. Argument: n
ŒP Take the powerset of [1, ..., n].
S€ Take the sum of each subset.
$ Combine the two links to the left into a monadic chain.
Æṁ Compute the median of the sums, i.e, (1 + ... + n)/2.
ċ Count the occurrences of the median.
```
[Answer]
# Python 2, 74 bytes
```
def f(n):l=k=1;exec"l+=l<<n*k;k+=1;"*n;return(l>>n*n*-~n/4)%2**n*(~-n%4>1)
```
More of a fun submission, direct generating function computation.
[Answer]
# [Octave](https://www.gnu.org/software/octave/) (with Communications Package), 39 bytes
```
@(n)sum((2*de2bi(0:2^n-1)-1)*(1:n)'==0)
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999BI0@zuDRXQ8NIKyXVKClTw8DKKC5P11ATiLQ0DK3yNNVtbQ00/ycWFSVWppXmaaTpGFpZav4HAA "Octave – Try It Online")
### Explanation:
Take a range **0 ... n^2-1** and convert it to binary. This gives a matrix with all combinations of **0** and **1**. Multiply by **2** and subtract **1** to get a matrix with all combinations of **-1** and **+1**.
Take the dot-product with a range **1 ... n** to get all combinations of **±1 ± 2 ... ±n**. Count how many are zero.
Basically the same thing, same byte count:
```
@(n)nnz(~((2*de2bi(0:2^n-1)-1)*(1:n)'))
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), ~~31~~ 22 bytes
*9 bytes saved thanks to @H.PWiz*
```
1⊥0=⊂∘⍳+.ר∘,3-2×∘⍳⍴∘2
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R2wTDR11LDWwfdTU96pjxqHeztt7h6YdWANk6xrpGh6dDBB/1bgEyjIAaFIByvZsNDQA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# Python 2 and 3, 50 bytes
Recursive approach like most of the answers:
```
f=lambda n,r=0:f(n-1,r+n)+f(n-1,r-n)if n else r==0
```
[Try it online](https://tio.run/##LcZBCsIwEAXQq3y6ytApNLgQCrmJm4gZHai/ZczG08eNb/XOb38dvIxhZa/v@6OCGmXdLHHJGjNl/nehuIFo@6chSlmHHQGHE1H5bCkr8lU2nOHsyXW69UlhyUXGDw "Python 3 – Try It Online")
The double recursive call takes too much bytes... There's probably a way to simplify it.
[Answer]
# Java 8, ~~72~~ ~~71~~ 70 bytes
```
n->f(0,n)int f(int r,int n){return n>0?f(r+n,--n)+f(r+~n,n):r==0?1:0;}
```
Port of [*@Arnauld*'s JavaScript (ES6) answer](https://codegolf.stackexchange.com/a/161125/52210).
-2 bytes thanks to *@OlivierGrégoire*.
[Try it online.](https://tio.run/##LU9Nb4MwDL3vVzz1lCiA4LIDLO0vWC89djtkNExpwVQhdKoq9teZk07yt5/t57O5mfx8uqxtb6YJ78bR4wVwFKzvTGuxj2kqoBXRkmy4srCy7EHQWCnfdqLMuBURXcL57Il@eBtmT6BtueuEV5TlOUkVw1/ikdprXe6qumyWFbjOX71rMQUT2N1Gd8LAnMQheEffx08jn3wiUQx8m@xPSkSiBXSjT@edrhq4N129slNKpiZwuE/BDsU4h@LKG0NPwqlN/RE2aiio4Bfl/3/L@gc)
**Explanation:**
```
n-> // Method with integer parameter and integer return-type
f(0,n) // Call the recursive method with 0 and this parameter
int f(int r,int n){ // Recursive method with integer as both two parameters and return-type
return n>0? // If `n` is not 0 yet:
f(r+n,--n) // Recursive call with `r+n` (and `n` lowered by 1 first with `--n`)
+f(r+~n,n) // + Recursive call with `r-n` (and `n` also lowered by 1)
:r==0? // Else-if `r` is 0
1 // Return 1
: // Else:
0;} // Return 0
```
[Answer]
# [Haskell](https://www.haskell.org/), 55 bytes
A straightforward approach of computing all those sums and checking how many are zero.
```
f 0=[0]
f n=[(n+),(n-)]>>=(<$>f(n-1))
g x=sum[1|0<-f x]
```
[Try it online!](https://tio.run/##Dco7DoAgDADQ3VN0cICopDhbLkIYHCwaoTF@Egbvjo4veet87UtKtTIgeQwNg5BX0uleyaCDc6Sm1vEPq3UTodD1ZG9fnAaGEmqeNwGC49zkhhbin701ZsRQPw "Haskell – Try It Online")
EDIT: @H.PWiz has a shorter and way more elegant solution using [`mapM`](https://codegolf.stackexchange.com/a/161132/24877)!
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + GNU utilities, 63 bytes
Bash can probably do better than this with recursive functions, but I can't resist this sort of `eval`/escape/expansion monstrosity:
```
p=eval\ printf\ %s
$p\\\\n \$[$($p \\\{+,-}{1..$1})]|grep -c ^0
```
[Try it online!](https://tio.run/##S0oszvifll@kUJJaXJKcWJyqkJmnUG2op2doVmutkJLPVZxaoqCrq6ACk/9fYJtalpgTo1BQlJlXkhajoFrMpVIQAwR5CjEq0SoaKgUKQE61to5uLcgcFcNazdia9KLUAgXdZIU4g/8p@Xmp/wE "Bash – Try It Online")
---
Update: I don't think bash can do better with recursive functions. [This is the best I could do for a score of 90](https://tio.run/##NYwxCsMwDAB3vUIFESTchCpDl5J@pGRIE5t0saD2luTtbl3odHAH95zSWoK9MfuU5yl5fEXctOv0etxwMUg@Y9si/TtwiQMpBJYNmEnvUaRpmJMbTtSfVWTf69DqyWELi2FAepA6HSt7MtLxq6OHAwIqXsDPqyGlIj9dPg). `eval` hell it is then.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 12 bytes
```
⟦₁{{ṅ|}ᵐ+0}ᶜ
```
[Try it online!](https://tio.run/##ASgA1/9icmFjaHlsb2cy///in6bigoF7e@G5hXx94bWQKzB94bac//8xNv9a "Brachylog – Try It Online")
### Explanation
```
⟦₁ The range [1, …, Input]
{ }ᶜ Count the number of times the following predicate succeeds on that range:
{ }ᵐ Map for each element of the range:
ṅ Negate
| Or do nothing
+0 The sum of the elements after the map is 0
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 42 bytes
```
@(n)sum((dec2bin(0:2^n-1)*2-97)*(1:n)'==0)
```
[Try it online!](https://tio.run/##FchBCoAgEADAe6/w1q4UqIciQ@gfUWBl4KEtUoNebzTHOddoH5fzAIQhHQCbW9XiCYRWM9USuaq7FjlITVgaIzBHFyIzTGrZ9MXmwwXjXz2z923fPRFYChX7D6cS8wc "Octave – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 32 bytes
```
1#.0=1#.1+i.*"1[:<:@+:@#:[:i.2^]
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DZX1DGyBhKF2pp6WkmG0lY2Vg7aVg7JVtFWmnlFc7H9NLq7U5Ix8hTQFQxjDCMYwhjFMYAxTGMMMxjCHMSxgDEu4gQZwFtxsQ7jhhnCzDOGGGRlw/QcA "J – Try It Online")
There is certainly much room for golfing. Exlpanation will follow.
[Answer]
# [Haskell](https://www.haskell.org/), 41 bytes
```
(%0)
n%k|n<1=0^k^2|m<-n-1=m%(k+n)+m%(k-n)
```
[Try it online!](https://tio.run/##FcVLCoAgFADAfadwoaCEkUE77SJ9QCRL1Idky87ei2Yzp61xTwm9WZCzXjTA4gNamX6L2/BkLUEqkxmPLYj2X4LAbAMQQ8oV4CaUeE2nWXWdGld8nU/2qChdKR8 "Haskell – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
RżN$ŒpS€ċ0
```
[Try it online!](https://tio.run/##y0rNyan8/z/o6B4/laOTCoIfNa050m3w/1Hj1sPtQPZ/AA "Jelly – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), `-p` 35 bytes
```
#!/usr/bin/perl -p
$_=grep!eval,glob join"{+,-}",0..$_
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3ja9KLVAMbUsMUcnPSc/SSErPzNPqVpbR7dWScdAT08l/v9/i3/5BSWZ@XnF/3UL/uv6muoZGugZAgA "Perl 5 – Try It Online")
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 30 bytes
```
n->Pol(prod(i=1,n,x^i+x^-i))%x
```
[Try it online!](https://tio.run/##DcgxCoAwDADArwRBSDAZuri1b/AFBUEqAUlDcejvo8sN5@dQuT0a5DApR3/QR79Qc2LjWXWbVZRondH6QIMMiSHtDD7U3j8WkPLT0IgoPg "Pari/GP – Try It Online")
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), 99 bytes
```
p(0,0,1).
p(0,_,0).
p(X,Y,Z):-A is X-1,B is Y+X,p(A,B,C),D is Y-X,p(A,D,E),Z is C+E.
X*Y:-p(X,0,Y).
```
[Try it online!](https://tio.run/##Jcw7DoAgEEXRnlVQOviGgKUdfvYw2FgaExOJFC4fA3Y3p7jpua/74PyepaTOwcGTVbV2uFaCiI1GDvrMWthjqhF7QeoCJsyEpQn/smAlbFXmfrVKTBy5Xhwi2VL8YMR@ "Prolog (SWI) – Try It Online")
[Answer]
# Pyth, ~~14~~ 13 bytes
```
lf!s.nT*F_BRS
```
[Try it here](http://pyth.herokuapp.com/?code=lf%21s.nT%2aF_BRS&input=12&debug=0)
### Explanation
```
lf!s.nT*F_BRS
SQ Take the list [1, ..., <implicit input>].
_BR Get the pairs [[1, -1], [2, -2], ...].
*F Take the Cartesian product.
f!s.nT Find the ones where the flattened sum is 0.
l Take the length.
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 25 bytes
```
ri,:)_Wf*:a.+:m*:e_1fb0e=
```
[Try it online!](https://tio.run/##S85KzP3/vyhTx0ozPjxNyypRT9sqV8sqNd4wLckg1fb/f0NTAA "CJam – Try It Online")
This is a fairly direct translation of @emigna's 05AB1E solution. It's certainly golfable.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 9 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
è%é┐╬@₧╠¬
```
[Run and debug it](https://staxlang.xyz/#p=8a2582bfce409eccaa&i=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12%0A13%0A14%0A15%0A16&a=1&m=2)
~~One of the shortest answers so far~~ defeated by Jelly.
I feel that checking explicitly which signs sum to zero is not very golfy, so instead I take the powerset and check how many sets in the powerset have the sum of half the nth triangular number. This method is, not surprisingly, of the same time complexity as checking which signs sum to zero.
ASCII equivalent:
```
RS{|+Hmx|+#
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 10 bytes
```
/mysdySQsS
```
[Try it online.](http://pyth.herokuapp.com/?code=%2FmysdySQsS&input=8&debug=0) Alternatively, [verify all test cases at once](http://pyth.herokuapp.com/?code=Q%0A%2FmysdySQsS&input=8&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12%0A13%0A14%0A15%0A16&debug=0).
Explaination:
```
/mysdySQsS Implicit: Q=input()
SQ Generate range [1...Q]
y Generate powerset of above
m Map d in the above over...
ysd ... double the sum of d
sS Sum of range [1...Q] (final Q is implicit)
/ Count the matches (implicit output)
```
[Answer]
# [J](http://jsoftware.com/), 28 bytes
```
(*>:){1j3#1+//.@(*/)/@,.=@i.
```
Uses the other definition from OEIS where `a(n) = coefficient of x^(n(n+1)/4) in Product_{k=1..n} (1+x^k) if n = 0 or 3 mod 4 else a(n) = 0`.
[Try it online!](https://tio.run/##FcqxCoAgFAXQ3a@41KDP5KkEDYLiv0SSLg2O0bdbDWc7bZSOGODwGUqnQLdv6@wXazkrbclmwzFXHiQmhiz/ljB4AkoX4tjPC8pwmRwhBVSG38YL "J – Try It Online")
## Explanation
```
(*>:){1j3#1+//.@(*/)/@,.=@i. Input: n
i. Range [0, n)
= Self-Classify. Forms an identity matrix of order n
1 ,. Stitch. Prepend 1 to each row
/ Reduce using
Convolution
*/ Product table
+//. Sum along anti-diagonals
1j3# Copy each once, padding with 3 zeroes after
{ Index at n*(n+1)
>: Increment n
* Times n
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 9 bytes
```
#½Σḣ¹mΣṖḣ
```
[Try it online!](https://tio.run/##yygtzv7/X/nQ3nOLH@5YfGhnLpDeOQ3I/P//v6EZAA "Husk – Try It Online")
### Explanation
```
#½Σḣ¹mΣṖḣ Implicit input
ḣ [1..input]
Ṗ Powerset
mΣ Sum each list
# Count occurrence of
ḣ¹ [1..input]
½Σ Half of sum
```
[Answer]
# [Gol><>](https://github.com/Sp3000/Golfish), 26 bytes
```
:IFPlMF2K+}:@-}||0lMF$z+|h
```
[Try it online!](https://tio.run/##S8/PScsszvj/38rTLSDH183IW7vWykG3tqbGAMhTqdKuAcoZmgIA "Gol><> – Try It Online") or [Run test cases from 1 to 16!](https://tio.run/##S8/PScsszvhv6BipEIkGrLmsPN0CcnzdjLy1a60cdGtragyAPJUq7Ro/p/845TL@/zfkMuIy5jLhMuUy4zLnsuCy5DI04DI05DI04jI05jI04TI05TI0AwA "Gol><> – Try It Online")
### How it works
```
:IFPlMF2K+}:@-}||0lMF$z+|h
Main outer loop
:IFPlMF ...... ||
: Duplicate top; effectively generate two explicit zeroes
Top is the loop counter `i`;
the rest is the generated 2**i sums
I Take input as number
F ........... | Pop n and loop n times
P i++
lM Push stack length - 1, which is 2**(i-1)
F ...... | Loop 2**(i-1) times
Main inner loop: generate +i and -i from 2**(i-1) previous sums
2K+}:@-}
Stack: [... x i]
2K [... x i x i] Copy top two
+} [x+i ... x i] Add top two and move to the bottom
:@ [x+i ... i i x] Duplicate top and rotate top 3
-} [i-x x+i ... i] Subtract and move to the bottom
Counting zeroes
0lMF$z+|h
0lM Push zero (zero count) and 2**n (loop count)
F...| Loop 2**n times
$z+ Swap top two; Take logical not; add to the count
h Print top as number and halt
```
] |
[Question]
[
Given a number N, the challenge is to get the sum of the pyramid of N primes. To clarify things, here is an example:
```
Input: 4
```
We will list the first `4` primes, and then compute the sum of them. After that, we will compute the sums of the sums, and so on:
```
2
> 5
3 > 13
> 8 > 33
5 > 20
> 12
7
```
You can see that the final result is **33**. Here is another example, with N = 8:
```
2
> 5
3 > 13
> 8 > 33
5 > 20 > 83
> 12 > 50 > 205
7 > 30 > 122 > 495
> 18 > 72 > 290 > 1169
11 > 42 > 168 > 674
> 24 > 96 > 384
13 > 54 > 216
> 30 > 120
17 > 66
> 36
19
```
You can see that the final result is **1169**.
Here is another example with an odd N, N = 3:
```
2
> 5
3 > 13
> 8
5
```
This gives us **13** as the result
Your task is to write a program or a function, that takes an integer greater than 0, and output the final result.
Here are some test results:
```
1: 2
2: 5
3: 13
4: 33
5: 83
6: 205
7: 495
8: 1169
9: 2707
10: 6169
11: 13889
12: 30993
13: 68701
14: 151469
15: 332349
16: 725837
17: 1577751
18: 3413221
19: 7349029
20: 15751187
21: 33616925
22: 71475193
23: 151466705
24: 320072415
25: 674721797
26: 1419327223
27: 2979993519
28: 6245693407
29: 13068049163
30: 27297614797
31: 56929779663
32: 118543624847
33: 246475746269
34: 511766428817
35: 1061264813321
36: 2198298700845
37: 4548996804811
38: 9405003164065
39: 19429190057417
40: 40107799133677
41: 82736199371081
42: 170553108953473
43: 351333736092089
44: 723224546040181
45: 1487710742395387
46: 3058157261678325
47: 6282142186547177
48: 12896743408107403
49: 26460652594917673
50: 54262186256186881
51: 111224391050741687
52: 227896496141836195
53: 466805185374509003
54: 955904519939662217
55: 1956988697590280537
56: 4005572366722212927
57: 8196803221276230093
58: 16769645303734608963
59: 34300013739423719561
60: 70136585692535099353
61: 143371352962891226373
62: 292978031452308375001
63: 598482012866917021541
64: 1222083126601616763473
65: 2494459637841415902073
66: 5089478703050176444803
67: 10379794709536133386939
68: 21160351440305258275579
69: 43119914481530819445497
70: 87833066190052490228187
71: 178841897161848754603319
72: 364014682565128163812791
73: 740654046243174781813209
74: 1506496270380756958474835
75: 3063280375436290387756263
76: 6227039507615221644290617
77: 12655020557561801933128885
78: 25712267089927372837530869
79: 52230425385198423845305957
80: 106076955379202815098486497
81: 215397386589448754140867649
82: 437308717912632286770415395
83: 887706233370396897803709611
84: 1801721089699452657985592689
85: 3656329898231436156162865559
86: 7418972676822310377574227797
87: 15051599987013574096449515927
88: 30532404546282900804722616529
89: 61926565462373271494414919017
90: 125582269494835615524470915169
91: 254631689768733901573206365479
92: 516210444730946464864091626473
93: 1046330617753410129672316234861
94: 2120493010460433691014704829565
95: 4296639990460140795780826898943
96: 8704509990931940668688755806845
97: 17631229933967301681217551193565
98: 35706243541395815998303171050377
99: 72298621492552303967009812018997
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest amount of bytes wins!
[Answer]
# J, 15 bytes
```
p:@i.+/ .*i.!<:
```
Explanation:
Basically the same as [my Mathematica answer](https://codegolf.stackexchange.com/a/65826/9288).
```
p:@i.+/ .*i.!<:
i.!<: binomial coefficients
p:@i. first n primes
+/ .* dot product
```
[Answer]
# Mathematica, ~~38~~ ~~36~~ 35 bytes
```
Prime[r=Range@#].Binomial[#-1,r-1]&
```
[Answer]
## [Minkolang 0.14](https://github.com/elendiastarman/Minkolang), 17 bytes
```
n[i3M$i1-i6M*+]N.
```
[Try it here](http://play.starmaninnovations.com/minkolang/?code=n%5Bi3M%24i1-i6M*%2B%5DN%2E&input=8) and [check all test cases here](http://play.starmaninnovations.com/minkolang/?code=%28ndN%5Bi3M%24i1-i6M*%2B%5Dn%3DNlO%24I%29%2E&input=1%3A%20%202%0A2%3A%20%205%0A3%3A%20%2013%0A4%3A%20%2033%0A5%3A%20%2083%0A6%3A%20%20205%0A7%3A%20%20495%0A8%3A%20%201169%0A9%3A%20%202707%0A10%3A%206169%0A11%3A%2013889%0A12%3A%2030993%0A13%3A%2068701%0A14%3A%20151469%0A15%3A%20332349%0A16%3A%20725837%0A17%3A%201577751%0A18%3A%203413221%0A19%3A%207349029%0A20%3A%2015751187%0A21%3A%2033616925%0A22%3A%2071475193%0A23%3A%20151466705%0A24%3A%20320072415%0A25%3A%20674721797%0A26%3A%201419327223%0A27%3A%202979993519%0A28%3A%206245693407%0A29%3A%2013068049163%0A30%3A%2027297614797%0A31%3A%2056929779663%0A32%3A%20118543624847%0A33%3A%20246475746269%0A34%3A%20511766428817%0A35%3A%201061264813321%0A36%3A%202198298700845%0A37%3A%204548996804811%0A38%3A%209405003164065%0A39%3A%2019429190057417%0A40%3A%2040107799133677%0A41%3A%2082736199371081%0A42%3A%20170553108953473%0A43%3A%20351333736092089%0A44%3A%20723224546040181%0A45%3A%201487710742395387%0A46%3A%203058157261678325%0A47%3A%206282142186547177%0A48%3A%2012896743408107403%0A49%3A%2026460652594917673%0A50%3A%2054262186256186881%0A51%3A%20111224391050741687%0A52%3A%20227896496141836195%0A53%3A%20466805185374509003%0A54%3A%20955904519939662217%0A55%3A%201956988697590280537%0A56%3A%204005572366722212927%0A57%3A%208196803221276230093%0A58%3A%2016769645303734608963%0A59%3A%2034300013739423719561%0A60%3A%2070136585692535099353%0A61%3A%20143371352962891226373%0A62%3A%20292978031452308375001%0A63%3A%20598482012866917021541%0A64%3A%201222083126601616763473%0A65%3A%202494459637841415902073%0A66%3A%205089478703050176444803%0A67%3A%2010379794709536133386939%0A68%3A%2021160351440305258275579%0A69%3A%2043119914481530819445497%0A70%3A%2087833066190052490228187%0A71%3A%20178841897161848754603319%0A72%3A%20364014682565128163812791%0A73%3A%20740654046243174781813209%0A74%3A%201506496270380756958474835%0A75%3A%203063280375436290387756263%0A76%3A%206227039507615221644290617%0A77%3A%2012655020557561801933128885%0A78%3A%2025712267089927372837530869%0A79%3A%2052230425385198423845305957%0A80%3A%20106076955379202815098486497%0A81%3A%20215397386589448754140867649%0A82%3A%20437308717912632286770415395%0A83%3A%20887706233370396897803709611%0A84%3A%201801721089699452657985592689%0A85%3A%203656329898231436156162865559%0A86%3A%207418972676822310377574227797%0A87%3A%2015051599987013574096449515927%0A88%3A%2030532404546282900804722616529%0A89%3A%2061926565462373271494414919017%0A90%3A%20125582269494835615524470915169%0A91%3A%20254631689768733901573206365479%0A92%3A%20516210444730946464864091626473%0A93%3A%201046330617753410129672316234861%0A94%3A%202120493010460433691014704829565%0A95%3A%204296639990460140795780826898943%0A96%3A%208704509990931940668688755806845%0A97%3A%2017631229933967301681217551193565%0A98%3A%2035706243541395815998303171050377%0A99%3A%2072298621492552303967009812018997).
### Explanation
```
n Take number from input (N)
[ Open for loop that repeats N times
i Loop counter (n)
3M Pop n and push nth prime (where 2 is the 0th prime)
$i1- Max iterations - 1 (which is N-1)
i Loop counter (n)
6M Pop n,k and push kCn (binomial)
*+ Multiply and add
] Close for loop
N. Output as number and stop.
```
I use basically the same algorithm as several of the earlier answers that use binomial coefficients. Whenever you see such a pyramid of numbers being added, Pascal's triangle should be the first thing to come to mind. I don't see that any of the other answers have *explained* why this works, so I'll do that.
## MORE explanation
```
2
> [2,3]
3 > [2,3,3,5]
> [3,5] > [2,3,3,3,5,5,5,7]
5 > [3,5,5,7]
> [5,7]
7
```
As you can see, the primes `2,3,5,7` appear `1,3,3,1` times in the final result. Lemme change the layout a bit.
```
_ _ _ 7
_ _ 5
_ 3
2
```
The number of times that the `3` will contribute to the final result is the same as the number of paths from the `3` to the upper-left corner, **moving only up and left**. Here, there are three such paths for the `3`:
```
_ _ _ _
_ _ _ _
_ 3 3 3
```
Note that I can reverse the direction without loss of generality. So I want to know how many paths there are from the upper-left corner to each position along the jagged edge. I can count them like so...
```
1 1 1 1 1 . . .
1 2 3 4
1 3 6
1 4 .
1 .
. .
.
.
```
For every number in this triangle, if it is X units from the left and Y units from the top, then the number at that position is
[](https://i.stack.imgur.com/seIXi.gif)
The way I use it, though, `X+Y = N` is constant and `X` ranges from 0 to `N`, which goes along one diagonal. I multiply each coefficient with the corresponding prime number and then add it all up.
See [the Wikipedia article on Pascal's triangle](https://en.wikipedia.org/wiki/Pascal%27s_triangle) for more on this.
[Answer]
# JavaScript ES7 107
Abusing the fixed limit at 27 - how boring is actually finding the primes.
```
n=>eval("t=2;for(p=[for(v of'012242424626424662642646842')t-=-v];--n;)p=p.slice(0,n).map((v,i)=>v+p[i+1])")
```
Test snippet (using array comprehension it will work only in Firefox)
```
F=n=>eval("t=2;for(p=[for(v of'012242424626424662642646842')t-=-v];--n;)p=p.slice(0,n).map((v,i)=>v+p[i+1])")
// Less golfed
Q=n=>{
t=2;
// Note: the golfed version will return the last computed value, that is p if the loop is entered, else t=2
p=[for(v of '012242424626424662642646842') t-=-v] // build the array of first 27 primes in p
while(--n) p = p.slice(0,n).map((v,i)=>v+p[i+1])
return p
}
//TEST
console.log=x=>O.innerHTML+=x+'\n'
for(i=1;i<28;i++)console.log(i+' : '+F(i))
```
```
<pre id=O></pre>
```
[Answer]
# Pyth, 16 bytes
```
s*V.cLtQQ.f}ZPZQ
```
Very simple actually:
```
s*V ; Dot product of
.cLtQQ ; the binomial coefficients for n
.f}ZPZQ ; and the first n prime numbers.
```
[Answer]
# Pyth - ~~16~~ 15 bytes
Uses reduce and `first_n` filter.
```
u+VGtGtQ.f}ZPZQ
```
[Test Suite](http://pyth.herokuapp.com/?code=u%2BVGtGtQ.f%7DZPZQ&input=8&test_suite=1&test_suite_input=4%0A8%0A26&debug=0).
[Answer]
# Pyth, 18 bytes
```
husM.:G2tQ.f}ZPZQ0
```
Try it online: [Demonstration](http://pyth.herokuapp.com/?input=4&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12%0A13%0A14%0A15%0A16%0A17%0A18%0A19%0A20%0A21%0A22%0A23%0A24%0A25%0A26%0A27%0A28%0A29%0A30%0A31%0A32%0A33%0A34%0A35%0A36%0A37%0A38%0A39%0A40%0A41%0A42%0A43%0A44%0A45%0A46%0A47%0A48%0A49%0A50%0A51%0A52%0A53%0A54%0A55%0A56%0A57%0A58%0A59%0A60%0A61%0A62%0A63%0A64%0A65%0A66%0A67%0A68%0A69%0A70%0A71%0A72%0A73%0A74%0A75%0A76%0A77%0A78%0A79%0A80%0A81%0A82%0A83%0A84%0A85%0A86%0A87%0A88%0A89%0A90%0A91%0A92%0A93%0A94%0A95%0A96%0A97%0A98%0A99&code=husM.%3AG2tQ.f%7DZPZQ0&test_suite=0)
### Explanation:
```
husM.:G2tQ.f}ZPZQ0 implicit: Q = input number
.f Q0 find the first Q numbers Z >= 0, which satisfy
}ZPZ Z appears in the prime factorization of Z
this gives the first Q prime numbers
u tQ assign this list to G and repeat the following Q-1 times:
.:G2 create all subarrays of length 2
sM sum them up and update G
h take the first element (=result) and print
```
[Answer]
## Haskell, 74 bytes
```
import Data.Numbers.Primes
f n=([]:iterate(zipWith(+)=<<tail)primes)!!n!!0
```
Usage example:
```
*Main> map f [1..12]
[2,5,13,33,83,205,495,1169,2707,6169,13889,30993]
```
How it works: repeatedly calculate the neighbor sums of all primes. Take the head of the `n`th iteration.
```
[2,3,5,7,11,13,17,19,23,29,...] -- plain primes (and 1st iteration)
[5,8,12,18,24,30,36,42,52,60,...] -- 2nd iteration of neighbor sums
[13,20,30,42,54,66,78,94,112,128,...] -- 3rd iteration
[33,50,72,96,120,144,172,206,240,274,...]
...
```
As the index operator `!!` is zero based, I'm prepending an empty list to avoid having to use `!!(n-1)`.
[Answer]
# Matlab, 76 bytes
Thanks to David for saving a lot of bytes!
```
n=input('');x=primes(103);
for s=2:n,x=conv(x,[1 1]);end
disp(num2str(x(n)))
```
**Old version, 98 bytes**
```
n=input('');m=1;x=[];while nnz(x)<n
m=m+1;x=primes(m);end
for s=2:n,x=conv(x,[1 1]);end
disp(x(n))
```
[Answer]
# Shell + GNU and BSD utilities, 92
```
echo `primes 1|sed $1q`|sed -r ':
s/(\w+) (\w+)/$((\1+\2)) \2/
t
s/ \w+$//
s/^/echo /e
/ /b'
```
[Answer]
# JavaScript (ES6), 121 bytes
```
n=>eval(`for(p=[],c=0,x=1;c<n;s?p[c++]=x:0)for(s=i=++x;--i>1;)x%i?0:s=0;for(;--c;p=s)for(i=c,s=[];i;)s[c-i]=p[i]+p[--i]`)
```
## Explanation
Most of the size comes from finding the prime numbers.
```
n=>
eval(` // eval used to enable for loops without {} or return
// Get primes up to n
for( // loop from range 2 to n
p=[], // p = primes
c=0, // c = count of primes
x=1; // x = current number to check for primality
c<n;
s?p[c++]=x:0 // add the number to the primes if it has no divisors
)
for( // loop from range 2 to x to check for divisors
s= // s = true if x is a prime
i=++x;
--i>1;
)
x%i?0:s=0; // check if x has a divisor
// Sum primes
for(;--c;p=s) // while the new pyramid has pairs to sum
for(i=c,s=[];i;) // loop through each pair of the pyramid
s[c-i]=p[i]+p[--i] // push the sum of the pair to the new pyramid s
`) // implicit: return the final sum
```
## Test
```
<input type="number" id="input" value="0" oninput="result.textContent=(
n=>eval(`for(p=[],c=0,x=1;c<n;s?p[c++]=x:0)for(s=i=++x;--i>1;)x%i?0:s=0;for(;--c;p=s)for(i=c,s=[];i;)s[c-i]=p[i]+p[--i]`)
)(+this.value)" />
<pre id="result"></pre>
```
[Answer]
## Seriously, 23 bytes
```
,r`P`M;lD`;pX@dXZ'Σ£M`n
```
Outputs the result as a list of length 1: `8 -> [1169]`
[Try it online](http://seriouslylang.herokuapp.com/link/code=2c726050604d3b6c44603b70584064585a27e49c4d606e&input=8)
Explanation:
```
,r`P`M push the first n primes as a list
;lD push 1 minus the length of the list (we'll call this k) ([2,3,5,7],3)
`...`n call the following function k times:
;pX duplicate the list, pop and discard the first element
@dX swap, pop and discard the last element
Z zip the two lists
'Σ£ push the string "Σ" and convert to function
M map the function over the list
```
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-rprime`, ~~66~~ 62 bytes
-4 bytes thanks to [south](https://codegolf.stackexchange.com/users/110888/south)
```
->n{a=Prime.take n
(eval"a=a.each_cons(2).map &:sum;"*~-n)[0]}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcnW0km5RQVFmbqpS7CI326WlJWm6FjftdO3yqhNtA0DieiWJ2akKeVwaqWWJOUqJtol6qYnJGfHJ-XnFGkaaermJBQpqVsWludZKWnW6eZrRBrG1EFOWFyi4RVtaxkJ4CxZAaAA)
[Answer]
# [Fig](https://github.com/Seggan/Fig), \$18\log\_{256}(96)\approx\$ 14.816 bytes
```
tF@pmC
?!{Lx[xoX+p
```
*-6.585 bytes thanks to @Seggan*
[Try it online!](https://fig.fly.dev/#WyJ0RkBwbUNcbj8he0x4W3hvWCtwIiwiNyJd)
Explanation:
```
tF@pmC #
t # Take the first n from
mC # all positive integers
F # filtered by
@p # is prime.
?!{Lx[xoX+p #
? # If
! # not
L # length of
x # the list
{ # decremented,
[ # return the first item
x # from the list
o # otherwise call
X # the current function
+ # the list plus
p # the list with the first removed
```
[Answer]
# Mathematica 73 bytes
```
NestWhile[Plus@@@Partition[#,2,1]&,Prime@n~Table~{n,#},Length@#>1&][[1]]&
```
---
**How it works**
`Prime@n~Table~{n,#}&` gives a list of the first `#` primes.
`Partition[#,2,1]&` rearranges a list of numbers, `{a, b, c, d ...}` as
`{{a,b}, {b,c}, {c,d}...}}`.
`Plus@@@` then returns `{a+b, b+c, c+d...}`.
`NestWhile` begins with the list of `#` primes and repeatedly applies `Plus@@@Partition...` as long as there is more than one number in the list.
---
```
NestWhile[Plus@@@Partition[#,2,1]&,Prime@n~Table~{n,#},Length@#>1&][[1]]&[4]
```
>
> 33
>
>
>
---
```
NestWhile[Plus @@@ Partition[#, 2, 1] &, Prime@n~Table~{n, #}, Length@# > 1 &][[1]] &[5]
```
>
> 83
>
>
>
---
It takes about 1/5 sec to solve for the first 1000 primes.
```
NestWhile[Plus @@@ Partition[#, 2, 1] &, Prime@n~Table~{n, #},
Length@# > 1 &][[1]] &[10^3] // AbsoluteTiming
```
>
> {0.185611,
> 1917231113909474354152581359443368948301825453723617274940459548079399
> 7849439430405641625002631859205971635284844253657654843025188471660669
> 0868945436580032828177831204066809442374364181056590286849530757875874
> 9185665854180901580438781223737728559484382552514103542932932981340942
> 3918431043908415228663677}
>
>
>
[Answer]
# Python 2, 159 bytes
```
m=int(input())
q=[]
x=2
while len(q)<m:
if not any([x%g<1 for g in q]):q+=[x]
x+=1
for i in range(m-1):
for p in q:q+=[q[1]+q[0]];q.pop(0)
print(q.pop())
print q
```
[Answer]
# [Milky Way 1.4.8](https://github.com/zachgates7/Milky-Way), ~~26~~ 25 bytes
This answer is not competing. Some of the operations were created after this question was posted (but not necessarily for this challenge).
```
'E&{~F§{G}:y1ba?{_^_}};!
```
I was able to remove a byte after reading through the comments. Output is a single-element list.
---
### Explanation
```
' # read input from the command line
E # push a list of the first N primes
&{~ } # while loop
F # push the sum of TOS elements i.e. [A, B, C] => [[A,B], [B,C]]
§{ } # mapping
G # sum i.e. [1, 2, 3] => 6
: # duplicate the TOS
y # push the length of the TOS to the stack
1 # push 1 to the stack
b # evaluate equality of the TOS and STOS
a # logical not
?{_ _} # if-else statement
^ # pop the TOS
; # swap the TOS and STOS
# dump the TOS to the stack
! # output the TOS
```
---
### Usage
```
python3 milkyway.py <path-to-code> -i <input-integer>
```
[Answer]
## Ceylon, 169 bytes
```
alias I=>Integer;I s(I*l)=>l.size<2then(l[0]else 0)else s(*l.paired.map((I[2]i)=>i[0]+i[1]));I p(I n)=>s(*loop(2)(1.plus).filter((c)=>!(2:c-2).any((d)=>c%d<1)).take(n));
```
This defines two functions – `s` calculates the pyramid sum of a sequence of integers, while `p` calls this on the sequence of the first `n` primes.
Looks like about half the size is finding the first `n` primes, other half is calculating the pyramid sum.
Here is a formatted/commented version:
```
// Sum pyramid of primes
//
// Question: http://codegolf.stackexchange.com/q/65822/2338
// My answer: http://codegolf.stackexchange.com/a/65879/2338
alias I => Integer;
// Calculate the pyramid sum of some sequence.
I s(I* l) =>
// If less than two elements ...
l.size < 2
// then use the first (only element), or 0 if no such.
then (l[0] else 0)
// otherwise,
else s(*
// take the iterable of pairs of consecutive elements,
l.paired
// and add each of them together.
.map((I[2] i) => i[0] + i[1])
// then apply s (recursively) on the result.
);
// Calculate the pyramid sum of the first n primes.
I p(I n) => s(*
// the infinite sequence of integers, starting with 2.
loop(2)(1.plus)
// filter by primality (using trial division)
.filter((c) => !(2 : c-2)
.any((d) => c%d < 1))
// then take the first n elements
.take(n)
// then apply s on the result.
);
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
ÆN€+ƝƬṀ
```
[Try it online!](https://tio.run/##y0rNyan8//9wm9@jpjXax@YeW/NwZ8N/I/Ogw@1Agf8A "Jelly – Try It Online")
Originally I wrote a Brachylog answer, [`1<|~lṗᵐ≠≜{s₂ᶠ+ᵐ}ⁱ~g`](https://tio.run/##SypKTM6ozMlPN/r/qGXqo6bGR51zqsuVFHTtFJTK7R@1bXjU1PRwV6di7aOupf8NbWrqch7unP5w64RHnQtAKotB0tsWaANFah81bqxL//8fAA), but when it came out to 19 bytes I decided that I should probably try a different language.
```
Ṁ The largest value from
Ƭ every stage of repeatedly
+ adding
Ɲ adjacent values, starting with
ÆN nth prime
€ mapped over the input.
```
Apparently, mapping over a number treats it as a range from 1 to itself inclusive, and integers sort as greater than lists or whatever `''` is.
[Answer]
# APL(NARS), 41 chars, 82 bytes
```
{1=≢⍵:↑⍵⋄∇+/¨¯1↓⍵,¨1⌽⍵}∘{⍵↑v/⍨0πv←⍳1+⍵×⍵}
```
In input if one want to use big number has to enter the type number\_x as 47x.
There could be something not ok: i here write that n primes are in the set 1..n^2
Test:
```
h←{1=≢⍵:↑⍵⋄∇+/¨¯1↓⍵,¨1⌽⍵}∘{⍵↑v/⍨0πv←⍳1+⍵×⍵}
h 1
2
h 2
5
h 9
2707
h 24
320072415
h 47x
6282142186547177
h 99x
72298621492552303967009812018997
h 200x
433205808657246411262213593770934980590715995899633306941417373
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 52 bytes
```
{grep(&is-prime,1..*)[^$_],{[|$_]Z+.skip}...1& &say}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwvzq9KLVAQy2zWLegKDM3VcdQT09LMzpOJT5Wpzq6BkhFaesVZ2cW1Orp6RmqKagVJ1bW/tcD6k3LL1IAKjYy/w8A "Perl 6 – Try It Online")
Anonymous code block that takes an argument and prints out a one element list containing the result.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 7 bytes
```
ΩεẊ+↑İp
```
[Try it online!](https://tio.run/##ARgA5/9odXNr///Oqc614bqKK@KGkcSwcP///zQ "Husk – Try It Online")
Pretty straighforward.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
_j}jU
Å£=ä+
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=X2p9alUKxaM95Cs&input=NA)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `G`, 7 bytes
```
ʁǎ≬2lṠ↔
```
*-1 byte thanks to [Steffan](https://codegolf.stackexchange.com/users/92689/steffan)*
[Try it online](https://vyxal.pythonanywhere.com/#WyJHIiwiIiwiyoHHjuKJrDJs4bmg4oaUIiwiIiwiNCJd), see a [flagless version](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLKgceOP+KAuSgybOG5oCIsIiIsIjQiXQ==), or [verify more test cases](https://vyxal.pythonanywhere.com/#WyJHQSIsIiIsIsqBx47iiawybOG5oOKGlCIsIiIsIjFcbjJcbjNcbjRcbjVcbjZcbjdcbjhcbjkiXQ==).
Explanation:
```
ʁ # Range from 0 to n
ǎ # Nth prime (vectorising)
≬ # Three element lambda that:
2l # Gets overlapping groups of 2
Ṡ # And sums each of them
↔ # Apply that function until no change and collect intermediate results
# Get the maximum item of of those results with the G flag
```
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), 10 bytes
```
Đ`ŕʁ+ĐŁ⁻łŕ
```
[Try it online!](https://tio.run/##ASMA3P9weXT//8SQYMWVyoErxJDFgeKBu8WCxZX//1syLDMsNSw3XQ "Pyt – Try It Online")
```
Đ Implicit input; duplicate list
` ł Do... while top of stack is not 0
ŕ Remove top of stack
ʁ+ Reduce by addition
ĐŁ⁻ Get the length of the resultant array and subtract 1
ŕ Remove the pesky 0; implicit print
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 13 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ä/($◘é∟o¶Vƒm^
```
[Run and debug it](https://staxlang.xyz/#p=842f282408821c6f14569f6d5e&i=3%0A4%0A8%0A27%0A&a=1&m=2)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ÅpIGü+
```
Outputs the result wrapped in a list.
[Try it online](https://tio.run/##yy9OTMpM/f//cGuBp/vhPdr//5sAAA) or [verify all test cases](https://tio.run/##yy9OTMpM/W9p6epnr6TwqG2SgpK93//DrQV@7of3aP@v1fkPAA).
**Explanation:**
```
Åp # Push a list of the first (implicit) input amount of primes
IG # Loop the input-1 amount of times:
ü # For each overlapping pair of integers in the list:
+ # Add them together
# (after which the result is output implicitly)
```
] |
[Question]
[
Do you recognize the PPCG logo?
it looks like this, when you do an ascii art of it.
```
+---+
|PCG|
+---+
v
```
Now, In this Code Golf, You will make a code, that makes logos for other sites, similar to the PPCG logo.
# What You should do
The "Shortened" string will be the string, with all upper case letters and numbers in the input string.(Which would be `PPCG` when the input string is `Programming Puzzles & Code Golf`)
The "Box" (
```
+---+
| |
+---+
v
```
)
should fit the Shortened string perfectly.(No bigger or smaller)
Also the `v` part should be exactly 1 down and 1 left to the down right `+`.
Then output the box which has the shortened string in it.
# Example
`Stack Overflow`:
```
+--+
|SO|
+--+
v
```
`Area 51`:
```
+---+
|A51|
+---+
v
```
# Rules
You may assume that the input contains at least one digit or upper case letter.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply.
[Answer]
# Vim, 42 strokes
```
:s/[^A-Z0-9]//g
YPVr-i+<DOWN><LEFT>|<ESC><C-V>ky$pYjppVr $xrv
```
Replace `<DOWN>` with `↓`, `<LEFT>` with `←`, `<ESC>` with `esc` and `<C-V>` with `CTRL`+`V`.
Here's an animation of this script running (old version which uses a `V` instead of a `v`):
[](https://i.stack.imgur.com/wrpAG.gif)
Explanation of the script:
```
:s/[^A-Z0-9]//g # Remove all the characters that are not uppercase or numbers using a Regex.
YPVr- # Duplicate the current, and replace all the characters of the upper one with dashes.
i+<DOWN><LEFT>|<ESC> # Insert a + on the upper line, and a | on the second line.
<C-V>ky$p # Copy the + and | to the end of both lines.
Yjpp # Copy the upper line to the bottom two times.
Vr $ # Replace the bottom most line with spaces and put the cursor on the last character.
xrv # Remove the last character and replace the second last character with a v.
```
[Answer]
# [V](https://github.com/DJMcMayhem/V) 34 bytes
```
Ó[^A-Z0-9]
ys$|ÄVr-r+$.YLppVr x$rv
```
Note that this worked in an older version, but doesn't work in the current version on try it online. I changed `Ä` to `YP` which is functionally equivalent.
[Try it online!](http://v.tryitonline.net/#code=w5NbXkEtWjAtOV0KeXMkfFlQVnItciskLllMcHBWciB4JHJ2&input=UHJvZ3JhbW1pbmcgUHV6emxlcyAmIENvZGUgR29sZg)
Explanation:
```
Ó[^A-Z0-9]
```
Remove everything except for digits and uppercase characters.
```
ys$| "Surround this line with '|' characters.
Ä "Duplicate this line
Vr- "Replace this whole duplicated line with '-' characters
r+ "replace the first character with '+'
$ "Move to the end of the line, and
. "Repeat our last command. This is the same as 'r+'
Y "Yank the current line
pp "and paste it twice
L "At the end of our text
```
Now, the buffer looks like this:
```
+---+
|A51|
+---+
+---+
```
And our cursor is at the first column of the last line.
```
Vr "Change the whole last line to spaces
x "Delete a character
$rv "And change the last character to a 'v'
```
[Non-competing version: (31 bytes)](http://v.tryitonline.net/#code=w5PChEEtWjAtOV0KeXMkfFlQw5ItciskLllMcHDDkiB4JHJ2&input=UHJvZ3JhbW1pbmcgUHV6emxlcyAmIENvZGUgR29sZg)
[Answer]
# 16-bit x86 machine code, 72 bytes
In hex:
```
565789F731C9FCAC84C074143C5A77F73C4173083C3977EF3C3072EBAA41EBE75F5EE81500B07CAA51F3A4AB59E80A00B020F3AAB076AA91AAC351B02BAAB02DF3AAB82B10AB59C3
```
Parameters: `SI` = input string, `DI` - output buffer.
Outputs a NULL-terminated string with lines delimited by newline.
Uses input string as a temporary buffer.
```
56 push si
57 push di
89 f7 mov di,si ;Using source string as a buffer
31 c9 xor cx,cx ;Counter
fc cld
_loop:
ac lodsb
84 c0 test al,al ;Test for NULL
74 14 jz _draw ;Break
3c 5a cmp al,'z' ;\
77 f7 ja _loop ; |
3c 41 cmp al,'a' ; \
73 08 jae _stor ; >[A-Z0-9]?
3c 39 cmp al,'9' ; /
77 ef ja _loop ; |
3c 30 cmp al,'0' ;/
72 eb jb _loop
_stor:
aa stosb ;Store char in the source buffer
41 inc cx
eb e7 jmp _loop
_draw:
5f pop di
5e pop si
e8 15 00 call _line ;Output the first line
b0 7c mov al,'|' ;This proc upon return leaves '\n' in AH
aa stosb ;First char of the second line
51 push cx
f3 a4 rep movsb ;Copy CX logo characters from the source buffer
ab stosw ;Outputs "|\n", which is still in AX
59 pop cx
e8 0a 00 call _line ;Output the third line
b0 20 mov al,0x20 ;Space
f3 aa rep stosb ;Output it CX times
b0 76 mov al,'v'
aa stosb ;Output the final 'v'
91 xchg cx,ax ;CX == 0
aa stosb ;NULL-terminate the string
c3 retn ;Return to caller
_line:
51 push cx
b0 2b mov al,'+'
aa stosb
b0 2d mov al,'-'
f3 aa rep stosb ;'-'*CX
b8 2b 10 mov ax,0x102b ;"+\n"
ab stosw
59 pop cx
c3 retn
```
[Answer]
# [Retina](https://github.com/m-ender/retina), 43 bytes
```
[^A-Z\d]
.+
+$.&$*-+¶|$&|¶+$.&$*-+¶$.&$* V
```
[Try it online!](http://retina.tryitonline.net/#code=W15BLVpcZF0KCi4rCiskLiYkKi0rwrZ8JCZ8wrYrJC4mJCotK8K2JC4mJCogVg&input=QXJlYSA1MQ)
This is the perfect challenge to demonstrate Retina, Martin Ender's golfing language.
This solution is divided into two steps (what we call stages), both stages being a replacement stage.
The first stage:
```
[^A-Z\d]
```
This matches the substrings which match `[^A-Z\d]`, which is the characters that are not uppercase and not digits, and then substitute them by nothing, meaning deleting them.
The second stage:
```
.+
+$.&$*-+¶|$&|¶+$.&$*-+¶$.&$* V
```
The `.+` matches the whole result, and then substitutes it with the second line.
In the second line:
* `$&` refers to the whole match
* `$.&` refers to the length of the whole match
* `$*` means take the previous integer, repeat the next character that many times. Here `$.&$*-` means to repeat `-` however long the match is.
* `¶` refers to a new-line.
[Answer]
## C#, 183 177 165 bytes
```
string h(string s){s=string.Concat(s.Where(n=>n>47&n<58|n>64 &n<91));int m=s.Length;var x=new string('-',m);return$"+{x}+\n|{s}|\n+{x}+\n{new string(' ', m + 1)}v";}
```
multiplying chars is terrible in C#.
suggestions appreciated
thanks alot to aloisdg for -18 bytes
[Answer]
# Excel VBA, ~~375~~ ~~359~~ 358 bytes:
It works, I give up on trying to make it shorter...
Edit: Switched to case statement from if statements, -16 bytes
Edit2: Got rid of u and replaced with Len(b), -1 byte
```
Function b(x)
For i = 1 To Len(x)
a = Mid(x, i, 1)
e = Asc(a)
If e > 64 And e < 91 Or e > 47 And e < 58 Then b = b & a
Next i
For Z = 1 To 4
y = ""
Select Case Z
Case 2
y = "|" & b & "|"
Case 4
For i = 1 To Len(b)
y = y & " "
Next i
y = y & "v"
Case Else
y = "+"
For i = 1 To Len(b)
y = y & "-"
Next i
y = y & "+"
End Select
Debug.Print y
Next Z
End Function
```
[Answer]
## Lua, ~~145~~ 99 Bytes
Not much to say, manipulating strings is always wordy in lua :). Takes a command-line argument and output via STDOUT
**Thanks to @LeakyNun for saving me 45 Bytes !**
```
n=(...):gsub("[^%u%d]","")s="+"..("-"):rep(#n).."+\n"return s.."|"..n.."|\n"..s..(" "):rep(#n).."V"
```
**100 Bytes proposed by @LeakyNun**
```
n=(...):gsub("[^A-Z%d]","")s="+"..("-"):rep(#n).."+\n"return s.."|"..n.."|\n"..s..(" "):rep(#n).."V"
```
**OLD 145 Bytes**
```
g="|"..(...):gsub("%a+",function(w)return w:sub(1,1)end):gsub("%s",'').."|"S="+"..g.rep("-",#g-2).."+"p=print
p(S)p(g)p(S)p(g.rep(" ",#g-2).."v")
```
### Ungolfed
```
g="|" -- g is the second, and starts with a |
..(...):gsub("%a+", -- append the string resulting of the iteration on each word
function(w) -- in the input, applying an anonymous function
return w:sub(1,1) -- that return the first character of the word
end):gsub("%s",'') -- then remove all spaces
.."|" -- and append a |
S="+"..g.rep("-",#g-2).."+" -- construct the top and bot of the box
p=print -- alias for print
p(S)p(g)p(S) -- output the box
p(g.rep(" ",#g-2).."v") -- output #g-2 spaces (size of the shortened name), then v
```
[Answer]
# [2sable](http://github.com/Adriandmen/2sable), ~~36~~ ~~34~~ ~~33~~ ~~32~~ 31 bytes
Presenting **2sable** :). Although it has a lot in common with 05AB1E, this one actually auto joins the stack rather than outputting the top of the stack. Code:
```
žKA-ég'-×'+DŠJDU„
|®sX¶®gð×'v
```
Uses the **CP-1252** encoding.
[Answer]
## JavaScript (ES6), 99 bytes
```
(s,t=s.replace(/[^0-9A-Z]/g,``),g=c=>t.replace(/./g,c))=>`${s=`+${g(`-`)}+
`}|${t}|
${s}${g(` `))v`
```
[Answer]
# Haskell, 107 Bytes
This answer is heavily based on the answer by *Zylviij* and the comments by *nimi*. I would have added more comments to that answer, but alas, I don't have enough rep.
```
o n=t++'|':f++"|\n"++t++(f>>" ")++"v"where f=[c|c<-n,any(==c)$['0'..'9']++['A'..'Z']];t='+':(f>>"-")++"+\n"
```
Additional tricks used:
* Replaced `intersect` by its implementation so the import can be dropped. (Side note: the implementation is nearly verbatim the library one, I couldn't find a shorter version.)
* Moved the helper functions into the `where` clause so functions can use the `n` parameter internally.
* After that, `(#)` was short enough to be inlined.
* Put everything on one line to limit extra whitespace.
[Answer]
# Python 3.5, ~~114~~ ~~93~~ 112 bytes:
```
import re;Y=re.findall('[A-Z0-9]',input());I='+'+'-'*len(Y)+'+\n|';print(I+''.join(Y)+I[::-1]+'\n'+' '*len(Y)+'v')
```
A full program. Basically uses a regular expression to match all occurrences of uppercase letters and numbers, then creates the box of the exact size based on the length of the list of matches, and finally puts the joined list of matches "inside" it.
[Try It Online! (Ideone)](http://ideone.com/3b6z1g)
[Answer]
# Python 3, ~~121~~ 124 bytes
Fixed stupid mistake
```
s=''
for i in input():_=ord(i);s+=("",i)[91>_>64or 47<_<58]
x=len(s)
c='+'+"-"*x+'+'
print(c+"\n|"+s+"|\n"+c+"\n"+" "*x+"v")
```
does not import libraries like other python answer.
[Answer]
# Java 8, 149 bytes
```
s->{s=s.replaceAll("[^A-Z0-9]","");String t="+",r;int l=s.length(),i=l;for(;i-->0;t+="-");for(r=(t+="+\n")+"|"+s+"|\n"+t;++i<l;r+=" ");return r+"v";}
```
[Try it online.](https://tio.run/##jVA9b8IwEN35FScPVSKTiA4dkBsk6NCpgMRWSiUTHGpwbGRfUhWa355e2kidKirZ1n28d37vDrKWyWF3bHMjQ4Anqe1lAKAtKl/IXMG8SwFW6LXdQx71QYgF1Ru6dAJK1DnMwUIGbUgml5CF1KuToQlTYyK2fp0mz6NkvGFDxmLRD8GMcTb0gn4DQwyj7B7fonioMyMK5yOhk2QyEsgzlhCtK/ks6lL@YlnM2SfjgV5KOArO9b0RnrpAYK@w8hY8ZzUTTSt@pJ6qrSGpveLa6R2U5Lm3td6AjHvDHwFVmboK0xO10NjIpnnElt7tvSzLTv@yOp@NCnADD26n4NGZgsXfi/mbv0KZH2FR03qNe78Kn3ol4e72Km48hq1D7NS4ArZK@f9QZj1lUcDsl9IMmvYL)
**Explanation:**
```
s->{ // Method with String as both parameter and return-type
s=s.replaceAll("[^A-Z0-9]","");
// Leave only the uppercase letters and digits
String t="+", // Temp-String, starting at "+"
r; // Result-String
int l=s.length(), // Amount of uppercase letters and digits `l`
i=l;for(;i-->0;t+="-");// Loop and append `l` amount of "-" to the temp-String
for(r=(t+="+\n") // Append "+" and a new-line to the temp-String
+"|"+s+"|\n"+t; // Set the result to `t`, "|", modified input, "|", new-line, `t`
// all appended to each other
++i<l;r+=" "); // Loop and append `l` amount of spaces to the result
return r+"v";} // Return the result-String with appended "v"
```
[Answer]
## Pyke, 39 bytes
```
cFDh~u{!Ih(sil\-*\+R\+sj\|i\|++jild*\v+
```
[Try it here!](http://pyke.catbus.co.uk/?code=cFDh%7Eu%7B%21Ih%28sil%5C-%2a%5C%2BR%5C%2Bsj%5C%7Ci%5C%7C%2B%2Bjild%2a%5Cv%2B&input=Area+51&warnings=0)
12 bytes of mini-string creation, 20 bytes of formatting. Joy!
[Answer]
# Pyth, ~~38~~ 37 bytes
```
Jj*\-lK@jrG1UTz"++"jK"||"JtXJ"-+"" v
```
[Try it online.](http://pyth.herokuapp.com/?code=%0A%0AJj%2a%5C-lK%40jrG1UTz%22%2B%2B%22jK%22%7C%7C%22JtXJ%22-%2B%22%22+v&input=99+Bottles+Of+Beer&debug=0)
Note the newline in the start.
[Answer]
## Python 2, 113 bytes
```
def f(n):c=filter(lambda x:x.isupper()^x.isdigit(),n);L=len(c);h='+'+L*'-'+'+\n';return h+'|'+c+'|\n'+h+' '*L+'v'
```
[Answer]
# Jolf, 35 bytes
```
Ά+,Alγ/x"[^A-Z0-9]"1'+'-'|γS*lγ" 'v
```
I need a shorter way to remove all but caps & numbers...
[Answer]
# C, ~~171~~ 163
Function `f()` modifies its input and prints out the result.
```
l;f(char*n){char*p=n,*s=n,c[99];for(;*n;++n)isupper(*n)+isdigit(*n)?*p++=*n:0;*p=0;memset(c,45,l=strlen(s));c[l]=0;printf("+%s+\n|%s|\n+%s+\n%*.cv\n",c,s,c,l,32);}
```
## Test Program
Requires one parameter, the string to use in the favicon:
```
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc, const char **argv)
{
char *input=malloc(strlen(argv[1])+1);
strcpy(input,argv[1]);
f(input);
free(input);
return 0;
}
```
[Answer]
# Haskell, 161
```
import Data.List
r=replicate
l=length
f n=intersect n$['0'..'9']++['A'..'Z']
t n='+':(r(l$f n)'-')++"+\n"
o n=(t n)++"|"++(f n)++"|\n"++(t n)++(r(l$f n)' ')++"V"
```
### Usage
```
o"Stack Overflow"
+--+
|SO|
+--+
V
o"Area 51"
+---+
|A51|
+---+
V
```
[Answer]
# Bash, ~~99~~ 74 bytes
```
s=$(sed s/[^A-Z0-9]//g);a=${s//?/-};echo -e "+$a+\n|$s|\n+$a+\n${s//?/ }v"
```
Usage: Run the above command, type the site name, press enter and then `Ctrl` + `D` (send 'end of file').
[Answer]
# CJam, 41
```
"||"q_'[,65>A,s+--*__"+-"er_@\_,((S*]N*'v
```
[Try it online](http://cjam.aditsu.net/#code=%22%7C%7C%22q_'%5B%2C65%3EA%2Cs%2B--*__%22%2B-%22er_%40%5C_%2C((S*%5DN*'v&input=Programming%20Puzzles%20%26%20Code%20Golf)
[Answer]
# R, 108 bytes
```
cat(x<-gsub("(.*)","+\\1+\n",gsub(".","-",y<-gsub("[^A-Z0-9]","",s))),"|",y,"|\n",x,gsub("."," ",y),"v",sep="")
```
## Explanation
Going from the inside out (because who doesn't love assigning global variables from inside a regex), assuming `s` is our input string:
`y<-gsub("[^A-Z0-9]","",s)` keeps capitals and numbers, assigns the resulting value to y.
`gsub(".","-",y<-...)` replaces all characters with hyphens in the above.
`x<-gsub("(.*)","+\\1+\n",gsub(...))` chucks a `+` on either end of the row of hyphens, and a newline, and we store that as x.
The rest is pretty straightforward, output in the appropriate order, and use the fact that the number of spaces before the `v` will be the same as the length of y.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog/tree/45273ddf926eb9cb054f17a113540959cf32face), 61 bytes
Linked to the repository at Jul 7 to ensure backward compatibility.
```
lybL:{,."-"}ac:"+"c:"+"rcAw@NNw"|"Bw?wBwNwAwNwL:{," "w}a,"v"w
```
### Non-competing, 53 bytes
```
lL:"-"rjb:"+"c:"+"rcAw@NNw"|"Bw?wBwNwAwNw" ":Ljbw"v"w
```
[Try it online!](http://brachylog.tryitonline.net/#code=bEw6Ii0icmpiOiIrImM6IisicmNBd0BOTncifCJCdz93QndOd0F3TnciICI6TGpidyJ2Inc&input=IkJyYWNoeWxvZyI)
[Answer]
## APL, 52 49 bytes
```
{x⍪2⌽'v'↑⍨≢⍉x←⍉z⍪⍨(z←'+|+')⍪'-','-',⍨⍪⍵/⍨⍵∊⎕D,⎕A}
```
(down to 49 thanks to the comment).
[Answer]
## Perl, 57 bytes
**56 bytes code + 1 for `-p`.**
```
y/a-z //d;$d="-"x y///c;$_="+$d+
|$_|
+$d+
".$"x y///c.v
```
I originally tried to make this only using regexes, but it was much larger than I'd hoped, so I've used some string repetition instead.
[Try it online!](https://tio.run/##K0gtyjH9/79SP1G3SkFfP8VaJcVWSVepQqFSX18/2Vol3lZJWyVFm6tGJb6GC8xS0lOBSeuV/f8fUJSfXpSYm5uZl64QUFpVlZNarJCYl6LgnJ@SquCen5P2L7@gJDM/r/i/bgEA "Perl 5 – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 34 bytes
```
t1Y24Y2hm)T45&Ya'+|+'!wy&h10M~'v'h
```
[**Try it online!**](http://matl.tryitonline.net/#code=dDFZMjRZMmhtKVQ0NSZZYScrfCsnIXd5JmgxME1-J3YnaA&input=J0FyZWEgNTEn)
```
t % Implicit input. Duplicate
1Y2 % Uppercase letters
4Y2 % Digit characters
h % Concatenate horizontally: string with uppercase letters and digits
m % True for input chars that are uppercase letters or digits
) % Keep only those
T45&Ya % Pad up and down with character 45, which is '-'. Gives three-row char array
'+|+'! % Push this string and transpose into a column vector
wy % Swap, duplicate the second array from the top. This places one copy of the
% column vector below and one above the three-row char array
&h % Contatenate all stack arrays horizontally. This gives the box with the text
10M % Retrieve the string with selected letters
~ % Logical negate. Gives zeros, which will be displayes as spaces
'v' % Push this character
h % Concatenate horizontally with the zeros.
% Implicitly display the box with the text followed by the string containing
% the zero character repeated and the 'v'
```
[Answer]
## JavaScript (ES6), 119 bytes
```
h=a=>"+"+"-".repeat(a.length)+"+\n";j=a=>(a=a.replace(/[^A-Z0-9]/g,""),h(a)+"|"+a+"|\n"+h(a)+" ".repeat(a.length)+"v");
```
[Answer]
# [J](http://jsoftware.com/), 52 bytes
```
'v'(<3 _2)}4{.1":]<@#~2|'/9@Z'&I.[9!:7@'+++++++++|-'
```
[Try it online!](https://tio.run/##y/r/P81WT0G9TF3Dxlgh3kiz1qRaz1DJKtbGQbnOqEZd39IhSl3NUy/aUtHK3EFdGwZqdNX/pyZn5CukKag7FqUmKpgaqv8HAA)
```
[9!:7@'+++++++++|-' Set the box drawing characters.
'/9@Z'&I. Interval index, 1 for numbers, 3 for
uppercase letters.
] #~2| Mod 2, and filter
the characters that correspond to 1s.
<@ Put them in a box.
1": Convert to a character matrix, so we can do stuff to it.
4{. Add a 4th line filled with spaces
'v'(<3 _2)} Insert a “v” at 3,−2
```
[Answer]
# Ruby, 81 bytes (78 + `-p` flag)
```
gsub(/[^A-Z\d]/,'')
gsub(/.+/){"+#{k=?-*s=$&.size}+
|#{$&}|
+#{k}+
#{' '*s}v"}
```
[Answer]
## Common Lisp (Lispworks), 159 bytes bytes
```
(defun f(s)(labels((p(c l)(dotimes(i l)(format t"~A"c))))(let((l(length s)))#1=(p"+"1)#2=(p"-"l)#3=(format t"+~%")(format t"|~A|~%"s)#1##2##3#(p" "l)(p"v"1))))
```
ungolfed:
```
(defun f (s)
(labels ((p (c l)
(dotimes (i l)
(format t "~A" c))))
(let ((l (length s)))
#1=(p "+" 1)
#2=(p "-" l)
#3=(format t "+~%")
(format t "|~A|~%" s)
#1#
#2#
#3#
(p " " l)
(p "v" 1))))
```
Usage:
```
CL-USER 2 > (f "so")
+--+
|so|
+--+
v
NIL
CL-USER 3 > (f "pcg")
+---+
|pcg|
+---+
v
NIL
```
] |
[Question]
[
# Challenge
Find an expression, at most 100 bytes long, with the longest type signature.
# Rules
* Any statically typed language with type inference is allowed
* The type must be non-ambiguous, but otherwise may include types without defined instances. For example `Num [a]` and `Eq [a]` are allowed, even without a defined instance
* No imports other than the minimum required to compile a program with STDIN/STDOUT
* Infinite types are not allowed
* If an answer has more than one expression, only one may contribute to the score. For example, although the type signature of composition is `(.) :: (b -> c) -> (a -> b) -> a -> c`, having a score of 20, the answer with 25 copies of `(.)\n` would have a score of 20, not 500
* The expression must be, at most, 100 bytes
* The score is the number of characters in the type signature, excluding the name of the function and any whitespace. For example, `f :: (a -> b) -> a -> b` would have a score of 12
* The highest score wins!
# Examples
Although other languages are allowed, the following examples are in Haskell:
```
Score: 112
map.map.map.map.map.map.map.map.map.map.map.map.map.map.map.map.map.map.map.map.map.map.map.map.map
f :: (a -> b)
-> [[[[[[[[[[[[[[[[[[[[[[[[[a]]]]]]]]]]]]]]]]]]]]]]]]]
-> [[[[[[[[[[[[[[[[[[[[[[[[[b]]]]]]]]]]]]]]]]]]]]]]]]]
Score: 240
(.).(.).(.).(.).(.).(.).(.).(.).(.).(.).(.).(.).(.).(.).(.).(.).(.).(.).(.).(.).(.).(.).(.).(.).(.)
f :: (b->c)->(a->a1->a2->a3->a4->a5->a6->a7->a8->a9->a10->a11->a12->a13->a14->a15->a16->a17->a18->a19->a20->a21->a22->a23->a24->b)->a1->a2->a3->a4->a5->a6->a7->a8->a9->a10->a11->a12->a13->a14->a15->a16->a17->a18->a19->a20->a21->a22->a23->a24->c
Score: 313
foldl$foldl$foldl$foldl$foldl$foldl$foldl$foldl$foldl$foldl$foldl$foldl$foldl$foldl$foldl$foldl(.)
f :: (Foldable t, Foldable t1, Foldable t2, Foldable t3, Foldable t4,
Foldable t5, Foldable t6, Foldable t7, Foldable t8, Foldable t9,
Foldable t10, Foldable t11, Foldable t12, Foldable t13,
Foldable t14, Foldable t15) =>
(b -> c)
-> t (t1 (t2 (t3 (t4 (t5 (t6 (t7 (t8 (t9 (t10 (t11 (t12 (t13 (t14 (t15 (b
-> b))))))))))))))))
-> b
-> c
Score: 538
lex.show.foldl1.mapM.traverse.sum.mapM.sum.traverse.(.).mapM.scanl.zipWith3((.traverse).(.traverse))
(Num
(a -> ([[c]] -> t3 [[a1 -> f b]]) -> [[c]] -> t3 [[a1 -> f b]]),
Num
(([[c]] -> t3 [[a1 -> f b]])
-> t1 (t2 ([[c]] -> t3 [[a1 -> f b]]))
-> [[c]]
-> t3 [[a1 -> f b]]),
Show
(t (t1 (t2 ([[c]] -> t3 [[a1 -> f b]])))
-> t1 (t2 ([[c]] -> t3 [[a1 -> f b]]))),
Applicative f, Foldable t,
Foldable ((->) (t1 (t2 ([[c]] -> t3 [[a1 -> f b]])) -> a)),
Foldable
((->) (([[c]] -> t3 [[a1 -> f b]]) -> a -> t3 [a1 -> f b])),
Traversable t1, Traversable t2, Traversable t3, Traversable t4,
Traversable t5,
Traversable ((->) (t1 (t2 ([[c]] -> t3 [[a1 -> f b]])))),
Traversable ((->) ([[c]] -> t3 [[a1 -> f b]]))) =>
[(t5 (t4 a1) -> f (t5 (t4 b))) -> c -> a1 -> f b]
-> [(String, String)]
```
[Answer]
## Haskell, ~2^(2^18)
```
f x=(x,x)
g=f.f.f.f
h=g.g.g.g
i=h.h.h.h
j=i.i.i.i
k=j.j.j.j
l=k.k.k.k
m=l.l.l.l
n=m.m.m.m
n.n.n.n$0
```
Each application of `f` roughly double the type signature by transforming the type signature `T` to `(T,T)`. For example, the fourfold composition `f.f.f.f$0` has type
```
Num a => ((((a, a), (a, a)), ((a, a), (a, a))), (((a, a), (a, a)), ((a, a), (a, a))))
```
Each line quadraples the number of applications of `f`, giving `4^9 = 2^18` at the end. So, the type signature has size of the order of `2^(2^18)`.
[Answer]
# [Haskell](https://www.haskell.org/) with extensions, \$\ggg A(A(A(A(220,0),0),0),0)\$
```
Z::Z#Z#Z#Z#Z#Z#Z#Z#Z?Z
data a?b=Z|S(a?b)
type family m#n where Z#n=S n;S m#Z=m#S m;S m#S n=m#(S m#n)
```
[Try it online!](https://tio.run/##XY1Ba8MwDIXv@RUCXxJo/kCH6WFjMHpYICsDs4uaqK6ZrYbIpQvb/vo8db0NHd73nsTTEeWdYiyfrYGI7M/oCbpTXLaBR1k9YMYbvSwTPWIKMdDNPE80Yz7NstrxSEMYcR/piSUjD3py33Vg2u/qw8Jbceu1M/9m46pR2wE3e@u@@lq1qbIWw@H6ZoFkGC5HmgmcYdsD3/WaOZuM6h9rpq6@IjclYWA7nWeqm/IzHCJ6Ke1rCiKBfSvBM2bdyi8)
Requires `-XDataKinds`, `-XPolyKinds`, `-XTypeOperators`, `-XUndecidableInstances`, and `-XTypeFamilies`.
Many thanks to Ørjan Johansen, who realized that making the natural number constructor infix and building the arguments a bit differently saved two bytes, making just enough room for another iteration of `#`.
Obviously, the type checker will give up trying to check this program. To get a general sense of what the signature would look like (if it were small enough to fit in the observable universe), try the much smaller
```
Z::S(S Z)#Z?Z
```
## Explanation
The `#` type family is closely related the [Ackermann–Péter function](https://en.m.wikipedia.org/wiki/Ackermann_function), commonly written \$A\$, but `#` grows faster. The Ackermann–Péter function is defined
>
> \$A(0,n)=n+1\$
>
>
> \$A(m,0)=A(m-1,1)\$ when \$m > 0\$
>
>
> \$A(m,n)=A(m-1, A(m, n-1))\$ when \$ m, n > 0 \$
>
>
>
`#`, on the other hand, we can call \$B\$, and write
>
> \$B(0,n)=n+1\$
>
>
> \$B(m,0)=B(m-1,m)\$ when \$m > 0\$
>
>
> \$B(m,n)=B(m-1, B(m, n-1))\$ when \$m,n > 0\$
>
>
>
Only the second case is different. The termination proof is identical to the standard one for \$A\$, and it should be clear that \$B(m,n) \ge A(m,n)\$ for all \$m\$ and \$n\$.
Here we calculate a unary representation of
>
> \$r = B(B(B(B(B(B(B(B(0,0),0),0),0),0),0),0),0) \$
>
>
>
By direct calculation, \$B(B(B(B(0,0),0),0),0)=220\$, so
>
> \$r = B(B(B(B(220,0),0),0),0)\$.
>
>
>
Note that \$A(A(A(A(0,0),0),0),0)\$ is only \$5\$, so we've bumped things up a good bit to start out. I don't have a very clear sense of just how much faster \$B\$ grows than \$A\$, but considering how the calculation proceeds, it seems likely to grow quite a lot faster.
The number of digits in even \$A(6,0)\$ is too large to express practically in decimal, so this is ... rather ridiculously large.
The definition of the natural numbers, `(?)`, is a bit non-standard. To save space, we use `(?)` as both a natural number type (at the type level) and a proxy type (at the term level).
I believe that either `TypeFamilies` or (more verbosely and obfuscatedly) `FunctionalDependencies` are necessary to get the type-level computation required to reach truly large types. `UndecidableInstances` is needed to work around Haskell's very primitive termination checking. The other extensions are only needed to compress the code into the small available space.
[Answer]
# Java, score 17301488
Requires the method `<T>java.util.Map<T,T>f(T t){return null;}`, which has been counted towards the 100-byte limit.
`f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(1)))))))))))))))))))`
The compile-time type signature of this should match [this.](https://drive.google.com/file/d/0B66Q2_YrkhNnQTJkX1ZZb3RjNU0/view?usp=sharing)
[Answer]
# Haskell, 9·2663552 − 3 (≈ 1.02·10199750)
A small (“small”) improvement over [xnor’s 5⋅2262144 + 5](https://codegolf.stackexchange.com/questions/71797/make-a-long-type-signature/71800#71800). This is 99 bytes.
```
f=(:).(:)
g=f.f.f.f
h=g.g.g.g
i=h.h.h.h
j=i.i.i.i
k=j.j.j.j
l=k.k.k.k
m=l.l.l
n=m.m.m
o=n.n.n
o.o.o
```
### How it works
We have
```
(:) :: a -> [a] -> [a]
(:).(:) :: a -> [[a] -> [a]] -> [[a] -> [a]]
(:).(:).(:) :: a -> [[[a] -> [a]] -> [[a] -> [a]]] -> [[[a] -> [a]] -> [[a] -> [a]]]
```
and so on, with the length roughly doubling for each `(:)`. The given expression `o.o.o` works out to `(:).(:).(:).….(:)` with 2·46·34 = 663552 copies of `(:)`.
# Haskell with `FlexibleContexts` and `NoMonomorphismRestriction`, (200·4331776 + 75·331776 + 16)/9 ≈ 2.53·10199750
A small improvement over [Bubbler’s 12·2663552 + 9·663552 − 4 ≈ 1.36·10199750](https://codegolf.stackexchange.com/questions/71797/make-a-long-type-signature/178294#178294), which also relies on these extensions. The wording of the challenge sort of suggests it might be okay to rely on them (“For example `Num [a]` and `Eq [a]` are allowed, even without a defined instance”); I’m not sure. This is 100 bytes.
```
f=(/).(:)
g=f.f.f.f
h=g.g.g.g
i=h.h.h.h
j=i.i.i.i
k=j.j.j.j
l=k.k.k.k
m=l.l.l
n=m.m.m
o=n.n.n
-o.o.o
```
### How it works
We have
```
-(/).(:) :: (Fractional ([a] -> [a]), Num (a -> ([a] -> [a]) -> [a] -> [a])) => a -> ([a] -> [a]) -> [a] -> [a]
-(/).(:).(/).(:) :: (Fractional ([a] -> [a]), Fractional ([([a] -> [a]) -> [a] -> [a]] -> [([a] -> [a]) -> [a] -> [a]]), Num (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]]
-(/).(:).(/).(:).(/).(:) :: (Fractional ([a] -> [a]), Fractional ([([a] -> [a]) -> [a] -> [a]] -> [([a] -> [a]) -> [a] -> [a]]), Fractional ([([([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]]]), Num (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] -> [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]) -> [a] -> [a]]) -> [([a] -> [a]) -> [a] -> [a]] -> [([a] -> [a]) -> [a] -> [a]]]
```
and so on, with the length roughly quadrupling for each `(/).(:)`. The given expression `-o.o.o` works out to `-(/).(:).(/).(:).….(/).(:)` with 46·34 = 331776 copies of `(/).(:)`.
[Answer]
# Haskell, 12·2663552 + 9·663552 - 4
Yet another small improvement over [Anders Kaseorg's answer](https://codegolf.stackexchange.com/a/170171/78410).
```
f=(/).(/)
g=f.f.f.f
h=g.g.g.g
i=h.h.h.h
j=i.i.i.i
k=j.j.j.j
l=k.k.k.k
m=l.l.l
n=m.m.m
o=n.n.n
o.o.o
```
### How it works
```
(/) -- score 27
:: Fractional a => a -> a -> a
(/).(/) -- score 62
:: (Fractional a, Fractional (a -> a)) => a -> (a -> a) -> a -> a
(/).(/).(/) -- score 119
:: (Fractional a, Fractional (a -> a), Fractional ((a -> a) -> a -> a)) =>
a -> ((a -> a) -> a -> a) -> (a -> a) -> a -> a
(/).(/).(/).(/) -- score 224
:: (Fractional a, Fractional (a -> a),
Fractional ((a -> a) -> a -> a),
Fractional (((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
```
Just changed function composition `(.)` to fractional division `(/)`. The `Fractional x` part in the function signature explodes along with the main part, giving slightly higher constant multiplier.
[Answer]
# C, 979
```
#define a int,int,int
#define b a,a,a,a
#define c b,b,b
#define d c,c,c
#define e d,d,d
int(*f)(e);
```
`f` has the signature:
```
int(*)(int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int)
```
[Answer]
# Idris, >hyper(hyper(hyper(hyper(999999999, 99, 99), 99,99),99,99),99,99)
```
f:Nat->Type
f Z=()
f(S n)=hyper n n n~=~f n
the$f$hyper(hyper(hyper(hyper 999999999 9 9) 9 9)9 9)9 9
```
## Explanation:
We're defining a function f, computing a type f(0) is just the unit type, while f(S(n)) computes to the equality type applied to the function argument "hypered" by itself and to f applied to n. The last line basically is a function expecting a value of a type like (27 = (4 = (2 = (1 = ()))))) (for n=4).
# Simple Example
```
f 3 = (27 = (4 = (2 = (1 = ()))))
```
[Answer]
# C#, 363
Expression:
```
new{a=new{a=new{a=new{a=new{a=new{a=new{a=new{a=new{a=new{a=new{a=new{a=new{a=new{a=""}}}}}}}}}}}}}}
```
Type signature:
```
<>f__AnonymousType0#1`1[<>f__AnonymousType0#1`1[<>f__AnonymousType0#1`1[<>f__AnonymousType0#1`1[<>f__AnonymousType0#1`1[<>f__AnonymousType0#1`1[<>f__AnonymousType0#1`1[<>f__AnonymousType0#1`1[<>f__AnonymousType0#1`1[<>f__AnonymousType0#1`1[<>f__AnonymousType0#1`1[<>f__AnonymousType0#1`1[<>f__AnonymousType0#1`1[<>f__AnonymousType0#1`1[System.String]]]]]]]]]]]]]]
```
[Try it online!](http://csharppad.com/gist/487852bf2e208a896377)
[Answer]
# Go 1.0 without `reflect`, 98
Go 1.x types are statically defined. Here is my first try:
```
[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]string{}
```
[On the Go playground](https://play.golang.org/p/MC8pTVC1K6D):
```
package main;import "fmt"
func main() {
x := [][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]string{}
fmt.Printf("%d %T\n", len(fmt.Sprintf("%T", x)), x)
}
```
# Go 1.9 using type aliases, 2389
```
type(I=interface{f();g()};S=struct{p,q,r,s,t,u,v,w,x,y,z I});map[S]map[S]map[S]map[S]map[S]map[S]S{}
```
[On the Go playground](https://play.golang.org/p/K6H6WqF04fI):
```
package main;import("fmt";"strings")
func main() {
type(I=interface{f();g()};S=struct{p,q,r,s,t,u,v,w,x,y,z I});x:=map[S]map[S]map[S]map[S]map[S]map[S]S{}
fmt.Printf("%d %T\n", len(strings.Replace(fmt.Sprintf("%T", x), " ", "", -1)), x)
}
```
Result:
```
2389 map[struct { p interface { main.f(); main.g() }; q interface { main.f(); main.g() }; r interface { main.f(); main.g() }; s interface { main.f(); main.g() }; t interface { main.f(); main.g() }; u interface { main.f(); main.g() }; v interface { main.f(); main.g() }; w interface { main.f(); main.g() }; x interface { main.f(); main.g() }; y interface { main.f(); main.g() }; z interface { main.f(); main.g() } }]map[struct { p interface { main.f(); main.g() }; q interface { main.f(); main.g() }; r interface { main.f(); main.g() }; s interface { main.f(); main.g() }; t interface { main.f(); main.g() }; u interface { main.f(); main.g() }; v interface { main.f(); main.g() }; w interface { main.f(); main.g() }; x interface { main.f(); main.g() }; y interface { main.f(); main.g() }; z interface { main.f(); main.g() } }]map[struct { p interface { main.f(); main.g() }; q interface { main.f(); main.g() }; r interface { main.f(); main.g() }; s interface { main.f(); main.g() }; t interface { main.f(); main.g() }; u interface { main.f(); main.g() }; v interface { main.f(); main.g() }; w interface { main.f(); main.g() }; x interface { main.f(); main.g() }; y interface { main.f(); main.g() }; z interface { main.f(); main.g() } }]map[struct { p interface { main.f(); main.g() }; q interface { main.f(); main.g() }; r interface { main.f(); main.g() }; s interface { main.f(); main.g() }; t interface { main.f(); main.g() }; u interface { main.f(); main.g() }; v interface { main.f(); main.g() }; w interface { main.f(); main.g() }; x interface { main.f(); main.g() }; y interface { main.f(); main.g() }; z interface { main.f(); main.g() } }]map[struct { p interface { main.f(); main.g() }; q interface { main.f(); main.g() }; r interface { main.f(); main.g() }; s interface { main.f(); main.g() }; t interface { main.f(); main.g() }; u interface { main.f(); main.g() }; v interface { main.f(); main.g() }; w interface { main.f(); main.g() }; x interface { main.f(); main.g() }; y interface { main.f(); main.g() }; z interface { main.f(); main.g() } }]map[struct { p interface { main.f(); main.g() }; q interface { main.f(); main.g() }; r interface { main.f(); main.g() }; s interface { main.f(); main.g() }; t interface { main.f(); main.g() }; u interface { main.f(); main.g() }; v interface { main.f(); main.g() }; w interface { main.f(); main.g() }; x interface { main.f(); main.g() }; y interface { main.f(); main.g() }; z interface { main.f(); main.g() } }]struct { p interface { main.f(); main.g() }; q interface { main.f(); main.g() }; r interface { main.f(); main.g() }; s interface { main.f(); main.g() }; t interface { main.f(); main.g() }; u interface { main.f(); main.g() }; v interface { main.f(); main.g() }; w interface { main.f(); main.g() }; x interface { main.f(); main.g() }; y interface { main.f(); main.g() }; z interface { main.f(); main.g() } }
```
# Go 1 using [`reflect`](https://golang.org/pkg/reflect/), 65532
There is [a limit in package `reflect`](https://github.com/golang/go/blob/ed15e82413c7b16e21a493f5a647f68b46e965ee/src/reflect/type.go#L533) on the length of type names: `len(name) <= 1<<16-1`
I've been able to reach a type name of 65532 bytes so far with this block:
```
t:=reflect.TypeOf(0);u:=t;for i:=0;i<8191;i++{t=reflect.MapOf(u,t)};reflect.New(t).Interface()
```
[Full code on the Go playground](https://play.golang.org/p/gr7ayLr2M9P):
```
package main;import("fmt";"reflect")
func main() {
t:=reflect.TypeOf(0);u:=t;for i:=0;i<8191;i++{t=reflect.MapOf(u,t)};x:=reflect.New(t).Interface()
fmt.Printf("%d %T\n", len(fmt.Sprintf("%T", x)), x)
}
```
---
Notes: `x:=` is never counted.
[Answer]
# [C#](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 100 bytes, score = \$3.7996944224×10^{21}\$
```
class X<A,B,C,D,E,F,G>{class Y:X<Y,Y,Y,Y,Y,Y,Y>{Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y.Y y;}}
```
---
Solution inspired by [this answer](https://codegolf.stackexchange.com/a/69200/113454).
There are two variables that contribute to the length of the type signature of the variable `y`: the number of generic type arguments on `X` and the number of nested class accesses in `Y`.
The following formula represents the length of the generated type signature not counting whitespace:
\$ L\ =\ \frac{x^{y}\cdot((x-1)(2x^{2}+5x+4)+x+4)-(x+4)}{(x-1)} \$
where `x` is the number of generic type arguments on `X` (e.g. for `X<A,B,C,D>`, `x = 4`) and `y` is the number of `.Y`s
Using Desmos and trial and error, I found the maximum length value where `x` and `y` would fit in 100 bytes was at `x=7` `y=23`.
[Try it online!](https://tio.run/##Sy7WTS7O/P8/OSexuFghwsZRx0nHWcdFx1XHTcfdrhoiHGkVYROpgwTtqiP1SIIKlda1tf//AwA "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# Rust, 100 bytes, Score \$\approx 2.22128\times 10^{78}\$
The score is \$8+\underbrace{6\times(6\times(\cdots(6\times2+7)\cdots)+7)+7}\_{100 \text{ levels}}=\$ `2221283319900241080728746908337396589826288615608046563246444685656290281023085`.
The type is `Option<((...(u8,u8,u8,u8,u8,u8),...))>`, with 100 levels of nested tuples, where each tuple contains 6 identical items.
```
type A<T>=(T,T,T,T,T,T);type B<T>=A<A<A<A<A<T>>>>>;type C<T>=B<B<B<B<B<T>>>>>;None::<C<C<C<C<u8>>>>>
```
[Answer]
# [Rust](https://www.rust-lang.org), 99 bytes, score=46,137,336
```
fn b<T>(a:T)->Result<T,T>{Ok(a)}b(b(b(b(b(b(b(b(b(b(b(b(b(b(b(b(b(b(b(b(b(b(0))))))))))))))))))))))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=jZLfToMwFMYT7-QpKhdLm7FF3c3Skb7ATExM423DsGw4KKQ9aCbhEXwCb3ahD6VPY8fAMLZknl7A-cP361f68akLA9ufi3fQQQyIb3J5J9USVqh0kI1IoaUEkdQ1TNCIocLEb3LmVI4Tp3nic9r5ypt3M9bVizKNHqQpEvC5N2dn9FE5RUPEKT3oDtH8sFK12-iT4sntOUDd3oWWUGiFJrO6Up12duRlwM9a6BOO7dx0mFYn17ECARYksqjHxyIGmVLLJVb5sh5N1BV2y8r1-tJjyIQBO7LEpCaMAyMWG5CmzXW4KtTa4Emby5e2lQY5NvBEqVWgNNJZKgqIpk03zJJEhkCp3_zNRxn6AzvKPCQYa0UK9aqtTpM9Z7HCrucSMmuspoGtkOaMDnzjQflleaPpd2jnFj5nOKCcjNjf7eGsvF_jgFQL_P91TU7GHvVV7Ta2f99u989f)
[Answer]
# Ceylon, 38843546786070481 (~ 4·1016)
```
[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]
```
This are 49 nested one-tuples, with an empty tuple innermost.
The short name of this type is actually the same as the value in this case, but the fully expanded name is much longer.
The Ceylon compiler is working forever when trying to compile this (The compiler was still running after 180 minutes) – I'll have to try calculating the theoretical type length.
The problem here is that a one-element-tuple type `[X]` is actually represented in Ceylon's type system as `Tuple<X, X, []>` (first parameter is a supertype for all element types, second is the type of the first element, and third the type of all except the first elements, which is here an empty tuple (the `empty` object, the single instance satisfying the interface `Empty`)).
So `[]` is `empty`, `[[]]` is `Tuple<[], [], []>` = `Tuple<empty, empty, empty>`, `[[[]]]` is `Tuple<[[]], [[]], []>` = `Tuple<Tuple<[], [], []>, Tuple<[], [], []>, []>`. And the full name includes the package names, so we have actually `ceylon.language::Tuple<ceylon.language::Tuple<ceylon.language::empty, ceylon.language::empty, ceylon.language::empty>, ceylon.language::Tuple<ceylon.language::empty, ceylon.language::empty, ceylon.language::empty>, ceylon.language::empty>` just for three levels. And we want to go to 50.
As `ceylon.language::empty` is 22 characters long, and each `ceylon.language::Tuple<?,?,ceylon.language::empty>` adds 47 to twice the result from the previous step, we get `f(1) = 22`, and `f(n) = 2 · f(n-1) + 47`. This simplifies to `f(n) = 69 · 2^(n - 1) - 47`, and entering 50 gives us 38843546786070481. Of course, this is much larger than what would fit in the memory of my computer (8·109 bytes).
Of course, the compiler could be smart and not try to have the whole type name in memory until its name is requested.
Here is the full program trying to print the type:
```
import ceylon.language.meta {
type
}
"Run the module `codegolf.signature71797`."
shared void run() {
value x = [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]];
print(type(x));
}
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 99 bytes, Score 841
```
(1,(1,(1,(1,(1,(1,(1,(1,(1,(1,(1,(1,(1,(1,(1,(1,(1,(1,(1,(1,(1,(1,(1,(1,1,1))))))))))))))))))))))))
```
[Try it online!](https://tio.run/##Sy7WTS7O/F@WWKSQbqvxX8NQhyoICDVxgP@aeu6pJSGVBakamtZc4UWZJak@mXmpGumoPL2Q/OCSosy8dA1NPZ/UvPSSDAVtBSWF5IzEomKFnPy8dCVN6/8A "C# (Visual C# Interactive Compiler) – Try It Online")
Outputs
```
System.ValueTuple`2[System.Int32,System.ValueTuple`2[System.Int32,System.ValueTuple`2[System.Int32,System.ValueTuple`2[System.Int32,System.ValueTuple`2[System.Int32,System.ValueTuple`2[System.Int32,System.ValueTuple`2[System.Int32,System.ValueTuple`2[System.Int32,System.ValueTuple`2[System.Int32,System.ValueTuple`2[System.Int32,System.ValueTuple`2[System.Int32,System.ValueTuple`2[System.Int32,System.ValueTuple`2[System.Int32,System.ValueTuple`2[System.Int32,System.ValueTuple`2[System.Int32,System.ValueTuple`2[System.Int32,System.ValueTuple`2[System.Int32,System.ValueTuple`2[System.Int32,System.ValueTuple`2[System.Int32,System.ValueTuple`2[System.Int32,System.ValueTuple`2[System.Int32,System.ValueTuple`2[System.Int32,System.ValueTuple`2[System.Int32,System.ValueTuple`3[System.Int32,System.Int32,System.Int32]]]]]]]]]]]]]]]]]]]]]]]]
```
[Answer]
# Haskell, 782
Expression:
```
sum.sum.sum.sum.sum.sum.sum.sum.sum.sum.sum.sum.sum.sum.sum.sum.sum.sum.sum.sum.sum.sum.sum.sum.sum
```
Type signature:
```
:: (Num [[[[[[[[[[[[[[[[[[[[[[[[c]]]]]]]]]]]]]]]]]]]]]]]], Num [[[[[[[[[[[[[[[[[[[[[[[c]]]]]]]]]]]]]]]]]]]]]]], Num [[[[[[[[[[[[[[[[[[[[[[c]]]]]]]]]]]]]]]]]]]]]], Num [[[[[[[[[[[[[[[[[[[[[c]]]]]]]]]]]]]]]]]]]]], Num [[[[[[[[[[[[[[[[[[[[c]]]]]]]]]]]]]]]]]]]], Num [[[[[[[[[[[[[[[[[[[c]]]]]]]]]]]]]]]]]]], Num [[[[[[[[[[[[[[[[[[c]]]]]]]]]]]]]]]]]], Num [[[[[[[[[[[[[[[[[c]]]]]]]]]]]]]]]]], Num [[[[[[[[[[[[[[[[c]]]]]]]]]]]]]]]], Num [[[[[[[[[[[[[[[c]]]]]]]]]]]]]]], Num [[[[[[[[[[[[[[c]]]]]]]]]]]]]], Num [[[[[[[[[[[[[c]]]]]]]]]]]]], Num [[[[[[[[[[[[c]]]]]]]]]]]], Num [[[[[[[[[[[c]]]]]]]]]]], Num [[[[[[[[[[c]]]]]]]]]], Num [[[[[[[[[c]]]]]]]]], Num [[[[[[[[c]]]]]]]], Num [[[[[[[c]]]]]]], Num [[[[[[c]]]]]], Num [[[[[c]]]]], Num [[[[c]]]], Num [[[c]]], Num [[c]], Num [c], Num c) => [[[[[[[[[[[[[[[[[[[[[[[[[c]]]]]]]]]]]]]]]]]]]]]]]]] -> c
```
] |
[Question]
[
[Brain-flak](https://github.com/DJMcMayhem/Brain-Flak) is a stack-based turing-tarpit language, written collaboratively between me, [DJMcMayhem](https://codegolf.stackexchange.com/users/31716/djmcmayhem), and [1000000000](https://codegolf.stackexchange.com/users/20059/1000000000).
Some users are very experienced in the mysterious ways of Brain-Flak. So I thought it a good idea to set up this question as a way for us, and hopefully others too, to share our knowledge with the community and lower the bar of entry to this language "designed to be painful to use". And perhaps even teach those of us with more experience some new tricks.
So what tips do you have for golfing in brain-flak? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to brain-flak (e.g. "remove comments" is not an answer).
Please post one tip per answer.
[Answer]
# Use the Third Stack
If you have read the title you might be a bit confused. Surely there are only two stacks in Brain-Flak? However I assure you that it exists and it is one of the most powerful if not the most powerful tool in writing and golfing Brain-Flak.
---
## What is the "Third Stack"?
Every Brain-Flak program uses the third stack in one way or another but most of the use goes on behind the scenes and it is often useful to simply ignore the fact that it exists. Each parenthesis in the program either adds or removes one item from the stack. Three of the open braces `([<` all add an item to the stack while their three conjugates `)]>` all remove an item from the stack. The value of the item on the stack is the value of the current scope of the program and using nilads will modify this value in certain ways. The close parenthesis `)` has the unique function of moving an element from the Third Stack to the current stack; a push.
Hopefully this is becoming clear to you. The Third Stack is some sort of stack that remembers the return values of code that has already been executed. Let's walk through an example of a simple program keeping track of the two normal stacks and the Third Stack.
### Example
We will walk through the following program. This program pushes `-3, 1, -2` to the stack.
```
(([()()()])(()))
```
We start with three open braces, which all push a zero to the third stack.
Our stacks now look like this, the Third Stack is the one on the right and the active stack has a `^` under it:
```
0
0
0 0 0
^
(([()()()])(()))
^
```
Now we have three `()` nilads. These do not do anything to the normal two stacks, however they do each add one to the top of the Third Stack making our stacks look like:
```
3
0
0 0 0
^
(([()()()])(()))
^
```
Now we encounter a `]` as stated before close braces remove an item from the Third Stack, but `]` has the function of subtracting the element it removes from the top of the stack. Thus our new stacks will look like:
```
-3
0 0 0
^
(([()()()])(()))
^
```
This makes sense; `[...]` does negation so `]` should subtract downwards.
Now we must execute a `)`. As you likely recall `)` is the place in the program where stuff gets pushed to the stack so we will be moving the top of the Third Stack to the current stack, in addition we will be adding the `-3` to the next element in the third stack.
```
-3 0 -3
^
(([()()()])(()))
^
```
Once again we encounter one of our three open braces so we will add another element to our Third Stack.
```
0
-3 0 -3
^
(([()()()])(()))
^
```
As we said earlier `()` will increment the top of our third stack by one.
```
1
-3 0 -3
^
(([()()()])(()))
^
```
And `)` will move the top of the Third Stack onto the active stack and add downwards
```
1
-3 0 -2
^
(([()()()])(()))
^
```
The last `)` moves the Third Stack onto the active stack and since there are no elements left on the Third Stack for it to add, does nothing else.
```
-2
1
-3 0
^
(([()()()])(()))
^
```
The program is over so we terminate and output.
---
This example is intended to give you a feel for what the Third Stack is and does. It does not include all of the operations, but hopefully you can figure out what each of them does on its own. If you are still struggling I have included a "cheatsheet" at the bottom of this answer to help you along.
## Ok, So what?
Ok, now you understand the Third Stack, but "So what"? You were already using it even if you didn't call it the "Third Stack", how does thinking in terms of the Third Stack help you golf?
Lets look at a problem. You want to take the [Triangle of a number](https://en.wikipedia.org/wiki/Triangular_number). This is the sum of all numbers less than n.
One approach might be to create an accumulator on the offstack and add to it as you count down. This creates code that looks like this:
```
(<>)<>{(({}[()])()<>{})<>}{}<>({}<>)
```
[Try it Online!](https://tio.run/nexus/brain-flak#@69hY6dpY1etoVFdG62hGaupAeLVAona6lobOw0Qofn/v6GREQA)
This code is pretty compact and one might think that it can't get much smaller. However if we approach it from a third stack point of view it become clear that this is grossly inefficient. Instead of putting our accumulator on the offstack we can put it on the third stack with a `(` and retrieve it at the end we use `)`. We will once again loop through all the numbers, but this time we don't have to do much of anything to increment our Third Stack, the program does it for us. This looks like:
```
({()({}[()])}{})
```
[Try it Online](https://tio.run/nexus/brain-flak#@69RraGpUV0braEZq1lbXav5/7@hkREA)
This code is less than half the size of the pretty well golfed version we made before. In fact a computer search has proven that this program is the shortest possible program that can perform this task. This program can be explained using the "sum of all runs" approach, but I think it is a lot more intuitive and clear when explained using a Third Stack approach.
## When do I use the Third Stack?
Ideally whenever you begin work on a new problem in Brain-Flak you should think to yourself how would I do this with the Third Stack in mind. However as a general rule of thumb whenever you have to keep track of some type of accumulator or have a running total it is a good idea to try putting that on your third stack instead of the two real stacks.
Another time that it might be a good idea to consider using your third stack is when you don't have any space to store some value on the other two stacks. This can be particularly useful when you are doing manipulations on two existing stacks and you want to save a value for later use without having to keep track of where it is.
## Limitations of the Third Stack
The Third Stack is very powerful in a lot of ways but it comes with its own limitations and drawbacks.
Firstly, the maximum stack height for the Third Stack at any given point is determined at compile time. This means that if you want to use an amount of space on the stack you have to allocate that space when you are writing the program.
Secondly the Third Stack is not Random Access. This means that you cannot perform any operations on any value but the top most value. In addition you cannot move values around on the stack (say swap the first two elements).
## Conclusion
The Third Stack is a powerful tool and I would consider it essential to every Brain-Flak user. It takes some getting used to and requires a shift in the way your think about programming in Brain-Flak, but when used properly it makes all the difference between a decent and an amazing when it comes to golfing.
## Cheatsheet
Here is a list of operations and how they affect the Third Stack
```
Operation | Action
====================================================
(,[,< | Put a zero on top of the Third Stack
----------------------------------------------------
) | Add the top of the Third Stack to the
| second element and move it to the
| active stack
----------------------------------------------------
] | Subtract the top of the Third Stack
| from the second element and pop it
----------------------------------------------------
> | Pop the top of the Third Stack
----------------------------------------------------
() | Add one to the top of the Third Stack
----------------------------------------------------
{} | Pop the top of the active stack and
| add it to the top of the Third Stack
----------------------------------------------------
[] | Add the stack height to the Third
| Stack
----------------------------------------------------
<>,{,} | Nothing
```
[Answer]
## Finding modulus/remainder
Finding *n* modulo *m* is one of the basic arithmetic operations, important for many challenges. For cases *m > 0* and *n >= 0*, the following 46-byte snippet may be used. It assumes that *n* is on top of the active stack with *m* the next one down, and replaces them with *n* mod *m*. It leaves the rest of the stacks intact.
```
({}(<>))<>{(({})){({}[()])<>}{}}{}<>([{}()]{})
```
This annotated version shows the stack contents at some points in the program. `;` separates the two stacks and `.` marks the active stack.
```
. n m;
({}(<>))<>
{ . m; r 0 (r = n - km)
(({}))
. m m; r 0
{({}[()])<>}
{}
}
m-n%m-1 m; . 0
{}<>([{}()]{})
. n%m;
```
[Answer]
# Push-Pop Redundancy
This is a big one. It is also a little bit of a nuanced one.
The idea is that if you push something and then pop it without doing anything you should not have pushed it at all.
For example, if you want to move something to the offstack and then add one to it you might write the following code:
```
({}<>)({}())
```
This can be simpler like this:
```
({}<>())
```
The first program picks up the item moves it, picks it up again and adds one, while the second one does both in one fell swoop.
That example was simple however it can get a lot more complex. Take for instance:
```
({}<({}<>)><>)(<((()()()){}[((){}{})])>)
```
The reduction is less clear here but the 4th pop in the program can be reduced with the 2nd push, like so:
```
(<((()()()){}[((){}<({}<>)><>{})])>)
```
This is the most powerful tool in my golfing repertoire but it takes some practice to get good at it. Once you have been doing these for a while you will be able to spot these almost instantly.
[Answer]
## Optimise your integers
Integers are tedious to represent in Brain-Flak. Fortunately we have a question that will help [Golf a Brain-Flak Integer](https://codegolf.stackexchange.com/questions/89726/golf-a-brain-flak-integer?s=1|3.2002) for you. (Note that the question is designed to push the integer to the stack, so push-pop redundancy probably applies to more realistic programs.)
[Answer]
# Push extra loop counters
Frequently, you'll want to do something like
>
> Perform **X** operation on every element in the stack
>
>
>
or
>
> Perform **X** operation on every pair of adjacent elements in the stack
>
>
>
When the input may contain '0's, or the result of operation **X** may give a 0, this is really inconvenient. Because you'll need to do:
```
([])
{
{}
({}...<>)
([])
}
```
To do **X** to each element, and then later
```
<>
([])
{
{}
({}<>)
<>
([])
}
<>
```
To reverse the array again.
Even worse, if we're operatiing on pairs of adjacent elements, we'll need to do `([][()])` in place of `([])`. This is really inconvenient. Here's the trick: While you're doing **X** to each element, push a **1** over onto the alternate stack right above the `X(element)`. Then, while you're reversing it, you can simply do
```
<>
{
{}
({}<>)
<>
}
<>
```
This is 8 bytes shorter, so when you factor in the extra code to push 1, you'll end up saving 4-6 bytes. For a more concrete example, compare the task of getting deltas of an array. Without this trick, you'd need:
```
([][()]){
{}
([{}]({})<>)<>
([][()])
}{}{}<>
([])
{{}({}<>)<>([])}<>
```
For 62. With this trick, you'll have
```
([][()]){
{}
([{}]({})<>)(())<>
([][()])
}{}{}<>
{{}({}<>)<>}<>
```
For 58. If used the right way (for example, reversing first, and removing two `([][()])` from later), this could save even more in speficic scenarios.
[Answer]
# Take advantage of the 'Stack-Height' nilad
Especially in [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'") challenges, or challenges where you always know the size of the input, you can take advantage of the 'Stack-Height' nilad `[]` to create integers.
Let's work through this with a hypothetical challenge: output `CAT`. The non-golfy way is to use the [online integer golfer](https://brain-flak.github.io/integer/) to push 67, 65, and 84. This gives:
```
(((((()()()()){}){}){}()){}())
(((((()()()()){}){}){}){}())
((((((()()()){}()){}){})){}{})
```
(Newlines for clarity). This is 88 bytes, and not that great. If we instead push the consecutive differences between values, we can save a lot. So we wrap the first number in a *push* call, and subtract 2:
```
( (((((()()()()){}){}){}()){}()) [()()] )
```
Then, we take this code, wrap it in a *push* call, and add 19 to the end:
```
( ((((((()()()()){}){}){}()){}())[()()]) ((((()()()){})){}{}()) )
```
This is 62 bytes, for a whopping 26 byte golf!
Now *here* is where we get to take advantage of the stack-height nilad. By the time we start pushing 19, we know that there are already 2 items on the stack, so `[]` will evaluate to `2`. We can use this to create a 19 in fewer bytes. The obvious way is to change the inner `()()()` to `()[]`. This only saves two bytes though. With some more tinkering, it turns out we can push 19 with
```
((([][]){})[]{})
```
This saves us 6 bytes. Now we are down to 56.
You can see this tip being used very effectively on these answers:
* [Hello World](https://codegolf.stackexchange.com/a/91500/31716) V1
* [Hello World](https://codegolf.stackexchange.com/a/92975/31716) V2
* [Magic The Gathering, Friend or Foe](https://codegolf.stackexchange.com/a/112790/31716)
* [Output The Missing Integer](https://codegolf.stackexchange.com/a/114063/31716)
* [Diagonal Alphabet](https://codegolf.stackexchange.com/a/142417/31716) (my personal favorite)
[Answer]
# Use the wiki
We have a [wiki](https://github.com/DJMcMayhem/Brain-Flak/wiki)! It has some short comings, but it is helpful resource. It has lists of useful, well golfed, stack clean programs that you can paste into your code. If you want to do something you think someone might have done before there is a good chance it is on the wiki.
[Answer]
# Better looping
Here's an easy one:
A fairly common construct is:
```
(({})<{({}[()]<...>)}{}>)
```
Where you want to loop n times but still keep the n. However this can be written as:
```
({<({}[()]<...>)>()}{})
```
to save 2 bytes.
Another fairly common paradigm is
```
([])({<{}>...<([])>}{})
```
Which will loop and accumulate the entire stack. Due to some fancy maths this is the same as:
```
(([]){[{}]...([])}{})
```
[Answer]
# Check your negatives
Sometimes you can golf a few bytes by strategically choosing what to negate with the `[...]` monad.
A simple example is in nested `[...]`s. For example `[()()()[()()]]` could just be `[()()()]()()`
Say you want to check whether a value is any of the start brackets `(<{[`. The initial attempt is to push the difference between each character and loop over subtracting it
```
({}<((((( #Push the differences between start bracket characters
(((()()()()){}){}){}) #Push 32
[()]) #Push 31
[((()()())()){}{}]) #Push 20
){})><>) #Push 40
<>({<(([{}]<>{}))>(){[()](<{}>)}<>})
```
However, you can save 4bytes by pushing the negative versions of the differences instead!
```
({}<((((( #Push the differences between start bracket characters
((([()()()()]){}){}){}) #Push -32
()) #Push -31
((()()())()){}{}) #Push -20
){})><>) #Push -40
<>({<(({}<>{}))>(){[()](<{}>)}<>})
```
Generally, this doesn't save you very much, but it also costs very little effort to change around what the `[...]` is surrounding. Be on the lookout for situations where you can push the negative of a counter instead of the positive to save on incrementing multiple times instead of decrementing later. Or swapping out `(a[b])` with `([a]b)` to make the difference between two numbers negative instead of positive.
] |
[Question]
[
[Ash](https://github.com/Radvylf/ash) has a bit of an interesting float division algorithm. It's designed to never return `NaN`, and things like signed zero and infinity need to be handled.
**How it works:**
Assume the inputs are positive for the rules below. One input being negative will always result in the output being negative, and both being negative will result in a positive output.
* Zero divided by anything is `0`
* Anything other than `0` divided by `0` is `Infinity`
* Anything other than `Infinity` divided by `Infinity` is `0`
* `Infinity` divided by anything other than `Infinity` is `Infinity`
* `Infinity` divided by `Infinity` is `1`
* All other division works as normal
**I/O:**
For languages with floats that support signed zero and positive/negative infinity, floats are an accepted I/O format. For others, using a string is allowed. You can use any reasonable format in this string, and you can represent the infinities with anything that can't be confused with another number (such as `I`, `∞`, `inf`, or `:(`).
Input will always be two floats in your chosen representation, and output will be a single one. Floating point errors and large numbers being represented as `Infinity` are allowed.
**Test cases:**
```
0 / 0 0
0 / 1 0
0 / 8 0
0 / Infinity 0
0 / -0 -0
0 / -1 -0
0 / -8 -0
0 / -Infinity -0
-0 / 0 -0
-0 / 1 -0
-0 / 8 -0
-0 / Infinity -0
-0 / -0 0
-0 / -1 0
-0 / -8 0
-0 / -Infinity 0
1 / 0 Infinity
8 / 0 Infinity
Infinity / 0 Infinity
1 / -0 -Infinity
8 / -0 -Infinity
Infinity / -8 -Infinity
-1 / 0 -Infinity
-8 / 0 -Infinity
-Infinity / 0 -Infinity
-1 / -0 Infinity
-8 / -0 Infinity
-Infinity / -0 Infinity
Infinity / 1 Infinity
Infinity / 8 Infinity
Infinity / -1 -Infinity
Infinity / -8 -Infinity
-Infinity / 1 -Infinity
-Infinity / 8 -Infinity
-Infinity / -1 Infinity
-Infinity / -8 Infinity
Infinity / Infinity 1
Infinity / -Infinity -1
-Infinity / Infinity -1
-Infinity / -Infinity 1
1 / 1 1
1 / 8 0.125
1 / Infinity 0
1 / -1 -1
1 / -8 -0.125
1 / -Infinity -0
-1 / 1 -1
-1 / 8 -0.125
-1 / Infinity -0
-1 / -1 1
-1 / -8 0.125
-1 / -Infinity 0
8 / 1 8
8 / 8 1
8 / Infinity 0
8 / -1 -8
8 / -8 -1
8 / -Infinity -0
-8 / 1 -8
-8 / 8 -1
-8 / Infinity -0
-8 / -1 8
-8 / -8 1
-8 / -Infinity 0
1 / 0.125 8
0.1 / 0.2 0.5
10 / -3 -3.333333
1 / 0.0000000000000001 10000000000000000
```
**Other:**
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes (per language) wins!
[Answer]
# [Haskell](https://www.haskell.org/), 35 bytes
```
x?y|isNaN$x/y=tanh x*tanh y|0<1=x/y
```
[Try it online!](https://tio.run/##lVRda8IwFH3vrwgifqxGG2UQxLqXMRiIL9vb2EOHUcNqKm1FK/53l6ZVW3uvZXkpzTk599ybcNZe9Ct8/3w@vCQnGc29efMwSNzYU2tyeDKf5ORMmKt3zxtPKncRWOTr0Et6x@8J3XjbTii8xXj8EYdSrej0Ndj9@KLb3wfhIuovpR@LsDNw24N2d9KcrkQ8k0pYRC6Jrui6x1Yrkiu123T0b9d1sx9yJPFaKLLVmjH5DHf6hPAjQba7WBeaqWbjzdP/Y9Kw7Wgd7M1p2270LhvkaJHU7tkhA@KQ6nKsFGEowlHkXS2lknFSRWi1EM0RhiIcRaqFNELhhi4IQxGOIngdoKELwlCEo0i1kGMx5H4uXIvXEa6qd7wrgSFXUyrxkFAoUWzvRqBwGwUCryPAbdyVAFyWSzwkFNtwHk@S1Y2a1xGKL@Q/k4RNwIRahaIJmMAfd1F6sqxkvwBRVhLFkeIhZh4mlEAZAiZQnw2fDQqnEEOyJlMEs@aqiOQNbDLtiyGpYhQpQ5MFMZkrQvlxUwQzhCNz5Abh4IQ5OkOOzDBTg2aYqSHzg81pNQqbSyfL0dkh5nI1wFyuhmdvOtuKmt412LByE/qtmCwfVY2P@iOzcl2nvLRpdrfl/AE "Haskell – Try It Online")
The relevant function is `(?)`, which takes two `Double`s as input and returns a `Double` as output.
## How?
The hyperbolic tangent is an amazing function (two bytes shorter than `signum`!).
| `x` | `tanh x` |
| --- | --- |
| `0.0` | `0.0` |
| `-0.0` | `-0.0` |
| `Infinity` | `1.0` |
| `-Infinity` | `-1.0` |
# [Haskell](https://www.haskell.org/), ~~30~~ 29 bytes
```
x?y|x/y<=1/0=x/y|0<1=tanh$x*y
```
[Try it online!](https://tio.run/##lVRda8IwFH3vrwgiU6exucogiNlexmCwt@1t7KHDqGU1SlvRyv67Sz/U1t5rWZ7anJNzzz0Jd@lFPzoIjsf9U/K7d5OpAlco@/ErpqBizyzb@/vkuPJ8o2Zrh33uB8ng8DXlK2/TDbU3m0ze49A3C/74vN5@B7o33K3DWTSc@0Gsw66rOm6nN20/LnT85hvtMH/ObC2lDnd3kb8w21XX/vaUyn/YgcVLbdjGasbsI9zaEzqINNtsY1vozbRbL579n7BWvx8t17vsdL/fGpw22MFhqd2jYC4TrL6EkyJAIpJEXs3cN36c1BFeL8QLBEhEkki9kEU43tAJARKRJELXQRo6IUAikkTqhYQDxP2cuI5sIpxVr3hnAhBXUylxk1AqUW7vQuB4GyWCbCLgbVyVQFxWS9wklNsQt5OEpqhlE6H8Qv6TJG4CJzQqlE3gBHm7i8qThYr9EsShIkoj5UOQPUxsAuUIOoGGMHrIUHwKATFrckV01pwViXmDm0z7AmKqZIocyMlCmCwUsflxUURniCRylBki0YQlmaEkMszVsAxzNSI/3JxV47i5NFlJZkeYK9QQc4UaPXvTbGtqdjfDRrWbsG8lm@XjuvHxcJytQldUlzUNV1viDw "Haskell – Try It Online")
Using [MarcMush](https://codegolf.stackexchange.com/a/223173/82619)'s amazing trick, which relies on the well-known formula1
$$
\tanh(x\cdot y)=\tanh(x)\cdot\tanh(y).
$$
---
1 I know, I know, maths.
[Answer]
# JavaScript (ES6), 45 bytes
Expects `(a)(b)`, as Numbers. Returns a Number.
```
a=>b=>a/b||+(b?1/a?a/b:a*b>0||-1:1/a/b<0&&-0)
```
[Try it online!](https://tio.run/##lVTNbtpAGLzzFKsc8G6C7d2gSCtaw6mVemgvHEsVrc2auCI2tZ2qUekbVOolx/Y9@jx5gT4CWf8ANv4@rPoAyc4w33zj1XxWX1UWpNEmt@NkqXeht1Pe1PemyvW32yvqz4SrZuafibr0p3y7tcXEnLj@az4c2pztUv3lIUo1tcLMYk6q1fJttNbzxzignDl5Ms/TKF5R5mSbdZTTi0V8wZwwSd@o4I5mxJuS7wNCPt6OiBoRf0T0t40Ocr0kn4hHMude5Ybn0sX8ipGFS6o/Lssvlxl4Qz883Ps6Za@MTKqNIgmpYtQvD4IkzpK1dtbJilb6hjKqeN5x1nBI3qv8zsmiVUwFcQsCKxjt0z2fkRmx/v399fz7yXxaZEKs5z8/LTPxB9txQ@Sk@/BBgQgUkSjyLg6jOMofu4jdHWTXiEARiSLdQQax4YX2iEARiSL4HGChPSJQRKJIdxAfCOT97LkD2Uc4qJ7wDgSBvJrWiLOExojmekeCDa/RIMg@ArzGyQjAZXvEWUJzDX4@SdEXtewjNG/I/yQJm4AJvQpNEzBBnt@idWVFy34DskVLFEeaPxLlxYQaqELABnLE9U2Jwi0kkK6pFMGuOSgifQObLPYSSKuUirZAmwUxWStC/XFUBDtEIjnKEpFgwhLNUCIZVmpQhpUakh9szqjZsLkiWYlmh5ir1QBztRrevUW2HTVzWmLXnTdh7krZ5eOu8bEzbj839QTefox9cXLEXwA "JavaScript (Node.js) – Try It Online")
## How?
Let \$\mathbb{R}^\*\$ be \$\{x\in\mathbb{R}\mid x\neq0\}\$.
### Direct answers when `a/b` is truthy
Whenever \$a/b\$ is neither `NaN` nor \$0\$, we know for sure that it is the expected answer. The cases that are covered that way are:
* \$a\in\mathbb{R}^\*\$, \$b\in\mathbb{R}^\*\$ : standard division of non-zero, non-infinite floats
* \$a\in\mathbb{R}^\*\$, \$b=\pm0\$ : resulting in either \$+\infty\$ or \$-\infty\$
* \$a=\pm\infty\$, \$b\in\mathbb{R}^\*\$ : resulting in either \$+\infty\$ or \$-\infty\$
* \$a=\pm\infty\$, \$b=\pm0\$ : resulting in either \$+\infty\$ or \$-\infty\$
### Other cases
If \$a/b\$ is zero'ish, we test \$b\$:
* If \$b\neq\pm0\$:
+ If \$1/a\neq\pm0\$, \$a/b\$ is also the correct answer, which is either \$0\$ or \$-0\$
+ If \$1/a=\pm0\$ (i.e. \$a=\pm\infty\$), we also have \$b=\pm\infty\$ and the answer is either \$1\$ or \$-1\$ depending on the sign of \$a\times b\$ (we do `a*b>0||-1`)
* If \$b=\pm0\$, we also have \$a=\pm0\$ and the answer is either \$0\$ or \$-0\$ depending on the signs of \$a\$ and \$b\$ (we do `1/a/b<0&&-0`)
---
# JavaScript (ES6), ~~42~~ 33 bytes
Using [MarcMush's improvement](https://codegolf.stackexchange.com/a/223173/58563) of [Delfad0r's excellent trick with **tanh**](https://codegolf.stackexchange.com/a/223169/58563) saves ~~3~~ 12 bytes.
```
a=>b=>a/b<=1/0?a/b:Math.tanh(a*b)
```
[Try it online!](https://tio.run/##lVTLbtNAFN3nK666qGdK/JhGlUalTlcgsYBNlg1CY2ecGKV2aruICvEHSGxYwn/0e/oDfEIYP5LY8b2x8CKJ5pyce@7x6HxWX1QeZvGmsJN0obeRv1X@NPCnyg1ufOF6t@bH9XtVrJxCJSumLgK@zfTDY5xpZkW5xZ1Mq8XbeK1nT0nIPO4U6azI4mTJuJNv1nHBzubJGXeiNHujwhXLwZ/CtxHA3acxqDEEY9BfNzos9AI@gg@5c68Kw3PZfPaKw9yF@sdF9eVyA2/Yh8f7QGf8tZHJtFGEiCnOguogTJM8XWtnnS5ZrW8o45rnH2adn0O1Vh4vEybALQm8ZHRPd3wOt2D9ff758vuX@bTgGqyXPz8sM/E733qG6EH/8UYlIkhEksi7JIqTuHjqI3Z/kN0ggkQkifQHGcTGF9ohgkQkidBzkIV2iCARSSL9Qd5IEO9nxx3JIcJe9Yi3Jwji1XRGnCS0RrTXOxBsfI0WQQ4R8DWORiAuuyNOEtpreKeTFENRyyFC@4b8T5K4CZwwqNA2gRPk6S06V1Z07LcgW3REaaT9J1FdTKyBagRtIEdcXlUo3kKC6JpaEe2avSLRN7jJci9BtEqlaAuyWQiTjSLWHwdFtEMkkaOsEIkmLMkMJZFhrYZlWKsR@eHmjJqNmyuTlWR2hLlGDTHXqNHdW2bbUzOnFXbZexPmrlRdPukbnziT7nPVTPC6j7Evjo68fw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Julia 0.7](http://julialang.org/), 26 bytes
imaginary brownie points for using `tanh` instead of `sign` (thanks [Delfad0r](https://codegolf.stackexchange.com/a/223169/98541))
```
a$b=a/b<=Inf?a/b:tanh(a*b)
```
[Try it online!](https://tio.run/##lVbLTsMwELznK6yIg4OS1NvysBAVNyS@ARByRCqCIrdqzIE/gN/kR4LjpMWpdxORSyPPdHZ2bY3z/lFX6rpt1VmxVovidv2gN3f25cYo/cbVeZG0pmxMw9YsjuNIsAUTLHyEQ4BEJInYepWuzGeIZGGhbECARCSJhIUskuENHRAgEUkidB2koQMCJCJJJCwkIiD258CN5BzhqHrCOxKA2JpRiUmCV8Jv74@Q4W14BDlHwNs4KYG4HJeYJPhtiOlJwtyo5RzBPyH/mSRuAifMKvgmcIKc7mJ0ZGFk34MyGInSiP8ncAcTS6AeQRMoh@WlQ/EUAiJrekU0a46KRN7gJru@gEgVp5gBmSyEyUERy48/RTRDJDFH6RCJTliSM5TEDHs1bIa9GjE/3JxVy3Bz3WQlOTvC3KCGmBvU6OztZhuo2VWHLYOdsGfFZfkqNL7KV/4zyIvxY73DyZLo7ulos90zrtKXtEjLhFWaNbu6Mjl3P9xd6SmLn3ScJJGrpzqmveV3at@UOb@vt8pcXaTs0QHPA2u3r7SpNeduNWX2syFl5c/3l32xSqV@bX8B "Julia 0.7 – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~98~~ ~~95~~ ~~89~~ 88 bytes
-6 bytes thanks to Giuseppe
```
function(x,y=abs(scan(t=x)))cat("-"[!!sd(grepl("-",x))],c(z<-y[1]/y[2],!!y)[1+is.na(z)])
```
[Try it online!](https://tio.run/##bcxBDsIgEAXQvacos5qJoNaViXKAngFZIIppYkZTaFJ6eSxdGjfz8/PyZyhBlzCyT/2bcZJZu1vE6B1j0hMReZcQFBgh4h2fw@PzqlUuZKXH@aKyae0@m6OVQmQy7baPO3Y4k6US0CMcQDbLITo367MrA21WUR2HijX@8Kma@l2WLw "R – Try It Online")
Expects a vector of strings, as R cannot handle signed 0. Infinity will be input and output as `Inf`.
* `x` contains the input as 2 strings, and `y` is the conversion to numeric in absolute value.
* First, call `grepl("-",x)`, giving a vector of two booleans. We need to output a `-` sign iff the two booleans are different, ie if the standard deviation is non-0.
* Second, compute the division of the two values. R's division agrees with Ash's in most cases, but will give `NaN` for the two cases which are ambiguous: `0/0` and `Inf/Inf`. If the quotient is not NaN, we output it; otherwise, we compute the boolean `!!y[1]`, convert to integer, and output that.
Note that we can use `is.na` instead of `is.nan`, as `is.na(NaN)` returns `TRUE`. (The two functions are nonetheless not equivalent; `is.nan(NA)` returns `FALSE`.)
[Answer]
# [Scratch](https://scratch.mit.edu/), 310 bytes
[Try it online!](https://scratch.mit.edu/projects/513598083/)
In scratchblocks4:
```
when gf clicked
ask()and wait
set[N v]to(answer
ask()and wait
set[D v]to(answer
set[Q v]to((N)/(D
if<(Q)=[NaN]>then
if<(A)contains(0)?>then
set[Q v]to(0
else
set[Q v]to(1
end
end
if<<(join(N)(D))contains(-)?>and<not<<(N)contains(-)?>and<(D)contains(-)?>>>>then
if<(Q)contains(-)?>then
else
set[Q v]to(join(-)(Q
```
Alternatively, 37 blocks. No picture this time!
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 32 bytes
```
a=>b=>a/b+b/a?a/b:Math.sign(a*b)
```
[Try it online!](https://tio.run/##lVVdb4IwFH3nV/TNdkChmiXNDO5pD3tY9gPmMgtDxSAYIUuWZb@dlQ8V7L2SNTGYnsO59542h536UkV0TA6lm@WfcbUOKhUswmChvNAOPfWonw8vqtzyItlkVN2FrCrjoiQBWVk@8YhPzOU3iEARiSLP2TrJkvLbRFyzkNshAkUkipiFNOLCA50QgSISRfA6wEAnRKCIRBGzkG8J5HxOXEuOEc6qV7wzQSBHMyhxk9Ar0R/vQnDhMXoEOUaAx7gqAXQ5LHGT0B/Dv@2kGLNajhH6N@Q/TsJNwIRRhX4TMEHenmJwZcWg/R7kioEojvRfEs3FhBKoRcAE4mJ636BwCgkka1pFMGvOikjewE3WcwkkVRpFV6DJgjTZKUL5cVEEM0QiPsoGkaDDEvVQIh62apCHrRriH9ycVnPh5mpnJeod0lynBjTXqeHZW3trqOndBpsaJ6HvSpPlM7PxGZ8Zq6vhD5ceQFxt@daKl8dkTxkvDmlS0skymzC@VweakmBB0m7bWxa2x9jcqr/wfJ0fn1S0pfRNOR9O6MTvrCb/WITk@vO/prZi1A41nZAoz4o8jXmab@hruIujkicFtWOH5MwhttK/UP/Xj1jzf9m8@gM "JavaScript (Node.js) – Try It Online")
| Rule | JavaScript (IEEE 754) |
| --- | --- |
| Zero divided by anything is `0` | 0/0 is NaN;Same results for other values |
| Anything other than `0` divided by `0` is `Infinity` | Same Results |
| Anything other than `Infinity` divided by `Infinity` is `0` | Same Results |
| `Infinity` divided by anything other than `Infinity` is `Infinity` | Same Results |
| `Infinity` divided by `Infinity` is `1` | Infinity/Infinity=NaN |
| All other division works as normal | Same Results |
From above comparsion, we can see that, we only need to handle values when `a/b` is NaN. And whenever `a/b` is NaN, `Math.sign(a*b)` is what we want here.
So we use `a/b+b/a` to test `NaN` here. As long as `a/b` is not `NaN`, `a/b`, `b/a` have same signs. And adding them would always yield non-zero value. We know only `0`, `-0`, `NaN` is falsy. And the value here is non-zero. So we can ensure the result is `NaN` if `a/b+b/a` is falsy.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~169~~ 157 bytes
Thanks to @ceilingcat for the -12.
`tanh` seems like the way to go if you want to win this one, so I decided to try this without using any intrinsics, looking at the sign and exponents instead. `NaN` and denormals are not handled.
Annotated version:
```
*i,*j,w,x,t,u,v; char*z;
float f(a,b) float a,b; {
i=&a; j=&b; // Get the integer representations of the floats
w=*i*2; x=*j*2; // Move the exponents into the MSB of a copy
t=*j; // Save the original value that will be clobbered
u=3[z=&w]; v=3[z=&x]; // Get the exponents
b=v?
~v? // x/!0
~u?
j=0,a/b: // !INF/!(0,INF)=a/b (indicate normal division)
1/0.: // INF/!(0,INF)=INF
!~u: // INF/INF=1 or !INF/INF=0
u? // x/0
1/0.: // !0/0=INF
0; // 0/0=0
// Adjust the sign if normal division not used
// (if one value is negative, it will flip the sign)
j?*j^=(*i^t)&1<<31:0;
a=b; // Store the result in the return
}
```
```
*i,*j,w,x,t,u,v;char*z;float f(a,b)float a,b;{i=&a;j=&b;w=*i*2;x=*j*2;t=*j;u=3[z=&w];v=3[z=&x];b=v?~v?~u?j=0,a/b:1/0.:!~u:u?1/0.:0;j?*j^=(*i^t)&1<<31:0;a=b;}
```
[Try it online!](https://tio.run/##bVDRboIwFH3nKzqXEahVC2aJsXS8LfHFp70sDpOCMtsoLAzQaNyvs9uqQ80IOff0nHMvlya9zyRpGiwJVmRLdqQkFalZshIF3rN0nYsSpY4gsXviwNhBclswxe2YbTmW2Gc7jhWUEgqr@HC25/Y2YvWJ7SIW8zr8gbcKFadEDOKxN6D98cNPNa5CQylTIVZz7mA5L13bC4KhB6LgMTs2jzJL1tViiYLvciHz/urFaqWNKFdasWRWoo2QmVPncuGig4XQeedZxA@0TwnqGfQMNTgy1OBk@jqZTt7e4XyhR2bpIXnh6NmSU4ZkMALodl0wWktpS2lLXSyEvgqwUqfzlKIBAuAAH1mHwD4y0qgA4W7/Tq5rvnfpgwWhkfY9/7ntTR2zt1F1vo2DZOL@dRhEHfZvox41o3tDKNeTT3cE6l38vAi9fbx/trqPnH@pWJZVkSHKrGPzCw "C (gcc) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 48 bytes
```
ẸṂ=?
ñç÷?
÷×¹?
®+©ṛ
”-eÇ
Ḋ⁸Ç?
ɠÇŒV
-1*®
7£2ŀ7£×¢
```
Takes input as newline-separated strings in STDIN, zero is `0.0`, and infinity is `inf`.
[Try it online!](https://tio.run/##AVwAo/9qZWxsef//4bq4MD0/CsOxw6fDtz8Kw7cwwrk/CsKuK8Kp4bmbCuKAnS1lw4cK4biK4oG4w4c/Csmgw4fFklYKLTEqwq4KN8KjMsWAN8Kjw5fCov//LWluZgotMw "Jelly – Try It Online")
### How?
```
ẸṂ=? - 1: λxλy: any(x, y) if x == y else min(x, y)
ñç÷? - 2: λxλy: line3(x, y) if x÷y else line1(x, y)
÷×¹? - 3: λxλy: x÷y if x else x×y
®+©ṛ - 4: λx: add x to register; return x
”-eÇ - 5: λx: link4("-" in x)
Ḋ⁸Ç? - 6: λx: x[1:] if link5(x) else x
ɠÇŒV - 7: eval(link6(read from stdin))
-1*® - 8: (-1)^register
7£2ŀ7£×¢ - main: link2(link7, link7) * link8
```
] |
[Question]
[
I'm surprised this hasn't come up in a challenge yet.
Output the IP address of the machine you're running on. You are required to output both the local and external IP addresses.
Local IP address, ie along the default format of 192.168.x.x
Public IP address can be verified by using google <https://www.google.co.uk/search?source=hp&q=whats+my+ip>
Output can be in any format. IPv4 or IPv6 or any mix of each is allowed, however they must be the only output. Code can be a full program or a function.
[code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply so shortest code wins.
[Standard Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
**EDIT:**
As per @Peter Taylor's comment, in the case where multiple of either type of address are present, you can choose to either output the first one, or as many as you can access. So long as at least one local and one public are present.
[Answer]
# Bash + [curl](https://curl.haxx.se/) + [iproute2](https://wiki.linuxfoundation.org/networking/iproute2), ~~54 50 49 48~~ 33 bytes
```
ip r g 1|awk '$0=$7'
curl eth0.me
```
Thanks @DomHastings for golfing off 1 byte!
Thanks @Sisyphus for coming up with a shorter URL!
Thanks @zeppelin for golfing off 9 bytes!
[Answer]
# Bash 37 31 27 bytes
This is inspired by the [answer](https://codegolf.stackexchange.com/a/139538/21461) by [Bruce Forte](https://codegolf.stackexchange.com/users/48198/bruce-forte). That answer only works with IPv4 which means it doesn't work for me. I have rewritten it into a version that (only) works with IPv6:
```
ip r g b::|awk '$0=$9" "$9'
```
This is tested on Ubuntu 14.04.5 connected through PPPoE and since IPv6 is designed to be used without any NAT it will output the same IP address twice.
-6 bytes thanks to [zeppelin](https://codegolf.stackexchange.com/users/61904/zeppelin),
-2 bytes thanks to [Ferrybig](https://codegolf.stackexchange.com/users/10621/ferrybig),
-2 bytes thanks to [Markasoftware](https://codegolf.stackexchange.com/users/10973/markasoftware).
[Answer]
# AutoIt, ~~56~~ 53 bytes
```
#include<Inet.au3>
ConsoleWrite(@IPAddress1&_GetIP())
```
[`@IPAddress1`](https://www.autoitscript.com/autoit3/docs/macros.htm) is a macro that returns
>
> IP address of first network adapter
>
>
>
[`_GetIP()`](https://www.autoitscript.com/autoit3/docs/libfunctions/_GetIP.htm) returns
>
> the public IP address.
>
>
>
---
-3 bytes thanks to @mınxomaτ
[Answer]
# Mathematica, 17 bytes
~~Mathematica has a builtin for everything~~
```
$MachineAddresses
```
[As described in the documentation](http://reference.wolfram.com/language/ref/$MachineAddresses.html), this builtin command lists all IP addresses (both local and external) associated with your device.
[Answer]
# C#, ~~196~~ ~~194~~ ~~188~~ 163 bytes
```
namespace System.Net.Sockets{using Linq;_=>Dns.GetHostEntry("").AddressList.First(i=>(int)i.AddressFamily==2)+" "+new WebClient().DownloadString("http://eth0.me")}
```
*Saved 2 bytes thanks to @Xynos.*
*Saved 25 bytes thanks to @Nick.*
Full/Formatted Version:
```
namespace System.Net.Sockets
{
using Linq;
class P
{
static void Main()
{
Func<object, string> f = _ =>
Dns.GetHostEntry(Dns.GetHostName())
.AddressList
.First(i => (int)i.AddressFamily == 2) + " " + new WebClient().DownloadString("http://eth0.me");
Console.WriteLine(f(null));
Console.ReadLine();
}
}
}
```
[Answer]
## PowerShell v4+, 40 36 bytes
```
NetIPAddress|% IPA*
iwr eth0.me|% C*
```
*(Only works on Server 2012 R2 or above, or Windows 8.1 or above. Doesn't work on TIO.)*
Does exactly what it says on the tin. Gets the local network IP addresses and selects just the `IPA`ddress portion thereof (e.g., filters out the subnet mask, the gateway, etc.).
The second is a `Invoke-WebRequest` to `http://eth0.me` which simply gets the `C`ontent thereof; i.e., just the public IP address.
---
Ungolfed version:
```
(Get-NetIPAddress).IPAddress
(Invoke-WebRequest eth0.me).content
```
[Answer]
#Unix Shell + [stunclient](http://manpages.ubuntu.com/manpages/zesty/man1/stunclient.1.html), 40 bytes
```
stunclient stun.vo.lu|cut -d: -f2|sed 1d
```
Makes use of a [STUN protocol](https://www.rfc-editor.org/rfc/rfc5389):
>
> Session Traversal Utilities for NAT (STUN) is a protocol that serves
> as a tool for other protocols in dealing with Network Address
> Translator (NAT) traversal. It can be used by an endpoint to
> determine the IP address and port allocated to it by a NAT
>
>
>
The STUN server name is from the [Public STUN server list](https://gist.github.com/mondain/b0ec1cf5f60ae726202e).
The output format is:
```
LOCAL IPV4 ADDRESS
PUBLIC IPV4 ADDRESS
```
Note that both lines will be indented with a single space, but I believe this does not break the output rules as written.
Sample output:
```
192.168.1.100
209.85.233.147
```
[Answer]
# curl (bash one-liner): 27 bytes
```
curl -w%{local_ip} eth0.me
```
The result is printed on `stdout` and looks like this:
```
1.2.3.4
192.168.0.10
# no trailing newline, use "curl -w%{local_ip}\\n eth0.me" for it
```
`curl` should be at least of version 7.29.0 (from Feb 6, 2013).
The answer is based on <https://codegolf.stackexchange.com/a/139538/66016>.
[Answer]
## Go, MacOS only, 10 bytes
In macOS this [killswitch](https://vpn-kill-switch.com/) could be used, it can print current private active IP and public IP:
```
$ killswitch
Interface MAC address IP
en1 bc:34:36:d2:81:ba 192.168.2.10
Public IP address: 179.43.176.99
No VPN interface found, verify VPN is connected
```
This is not a built-in tool but tries to simplify the process of finding the proper IP's.
The output could get by using commands like:
```
$ route get 0.0.0.0
$ ifconfig | pcregrep -M -o '^[^\t:]+:([^\n]|\n\t)*status: active'
$ networksetup -listnetworkserviceorder
$ scutil --dns
```
Public IP:
```
$ dig o-o.myaddr.l.google.com @ns.google.com txt +short
```
[Answer]
**Python 3, 124 133 bytes**
```
from urllib2 import urlopen
import socket
a=urlopen('http://eth0.me').read()
b=socket.gethostbyname(socket.gethostname())
print a,b
```
[Answer]
**PowerShell v3+ (alternative answer for windows 7+)**
```
((ipconfig) -match "v4").split(":")[1]
Invoke-RestMethod eth0.me
```
[Answer]
# Bash + Awk + Curl, 43 bytes
using only built in tools for Mac and Linux
```
ifconfig|awk '/bro/{print $2}';curl eth0.me
```
[Answer]
## Node.js (JavaScript) ~~224~~ ~~223~~ ~~194~~ ~~175~~ ~~173~~ 130 bytes
```
r=require,l=console.log,r('dns').lookup(r('os').hostname(),(a,b)=>l(b));r('http').get('http://eth0.me',a=>a.on('data',c=>l(c+"")))
```
Ungolfed version:
```
require('dns').lookup(require('os').hostname(), (err, loc, fam) => console.log(loc));
require('http').get('http://eth0.me', res => {
res.on('data', chunk => console.log(chunk + ""));
});
```
---
* *Saved 1 byte* (due to unnecessary semicolon).
* *Saved 29 bytes thanks to @AndrewLi* (used arrow functions for shorter code).
* *Saved 19 bytes thanks to @MiniGod* (used `.get()` instead of `.request()` - `.end();` removed).
* *Saved 2 bytes thanks to @Zacharý* (parentheses not needed around a lone parameter of an arrow function).
* *Saved 43 bytes thanks to @Birjolaxew* (stored `require` and `console.log` in single-letter variables, passed url directly to `require('http').get`, logged output directly from `data` event).
[Answer]
**Python 2.7.13 128 bytes**
```
print __import__("urllib").urlopen("http://eth0.me").read(),__import__("socket").gethostbyname(__import__("socket").getfqdn())
```
[Answer]
# [Windows' Batch File](https://en.wikipedia.org/wiki/Batch_file), 116 bytes
```
@for /f "tokens=1-2 delims=:" %%a in ('ipconfig^|find "v4"')do @echo%%b
@powershell -Command "(iwr eth0.me).content"
```
The first line iterates through the results of running `ipconfig` and gets your local IPv4 address.
For the public IP part, I had to steal a bit from the marvelous [Powershell answer](https://codegolf.stackexchange.com/a/139556/66000) because, as far as I know, there is no way to get the machine's public IP using solely batch scripting.
We start with an `@` sign, to suppress echoing the prompt (`C:\...\path>`), then run the Powershell command `Invoke-WebRequest` (with its alias, `iwr`) and extract the `content` part of that.
I experimented with *not* using `(...).content` and, instead, only running the command and extracting the actual information from the complete output, using batch. But that proved to be way longer than this solution, so I kept it.
Tested on Windows 10.0.15063.
[Answer]
## R, ~~142~~, ~~140~~, 137 bytes
```
library(magrittr);system("ipconfig",int=T)%>%regmatches(.,regexpr("v4.+",.))%>%{a=nchar(.);substr(.,a-14,a)};readLines("http://eth0.me")
```
Tested on win10 and R (3.4.1).
Thanks for @Bruce-Forte for short URL.
Ungolfed version:
```
library(magrittr)
system("ipconfig",int=T) %>%
regmatches(.,regexpr("v4.+",.)) %>%
{a <- nchar(.)
substr(., a - 14, a)}
readLines("http://eth0.me")
```
[Answer]
# Bash + Curl, 24 bytes
```
hostname -i;curl eth0.me
```
[Answer]
# MS-SQL, 59 bytes
```
SELECT TOP 1 local_net_address
FROM sys.dm_exec_connections
```
Returns the client-facing IP address of the SQL instance executing the query.
[Answer]
# VBA, 58 Bytes
***Whoops, does not handle local address - fix in progress***
>
> ***Note:***
> Uses reference to
>
>
> `Microsoft Internet Controls`
>
>
>
Anonymous VBE immediate window function that takes no input and outputs the user's IP address via an Internet Explorer window
```
Set i=New InternetExplorer:i.Visible=1:i.Navigate"eth0.me"
```
[Answer]
# Bash — 29 bytes (linux)
```
curl ipinfo.io/ip
hostname -i
```
[Answer]
# [Python 3](https://docs.python.org/3/), 97 bytes
```
from socket import*
from requests import*
gethostbyname(gethostname()),get('http://eth0.me').text
```
returns tuple with `('LOCAL_IP', 'PUBLIC_IP')`, as apparently
```
x = 2,3
type(x)
>>> tuple
```
# [Python 3](https://docs.python.org/3/), 103 bytes
```
from socket import*
from requests import*
gethostbyname(gethostname()),get('http://api.ipify.org').text
```
ditto, read below.
---
# [Python 3](https://docs.python.org/3/), 107 bytes
First solution
```
from socket import*
from requests import*
gethostbyname(gethostname())+" "+get('http://api.ipify.org').text
```
The `+" "+` part is for joining strings together.
If you leave just the `+` sign, 103 bytes are possible, but would yield the strings without spaces which could lead to results like this `"5.5.5.111222.222.222.222"` and they should still be readable, as there are only 3 digits at max in every ip part.
But there are edge cases like `"5.5.5.11111.222.222.222"` where it would be impossible to distinguish the local vs public part.
Other possible savings are in the public ip grabber tool. I used this site, as it was the first thing I found on the Internet and it returns html with just text in it, which is super nice. I saw other people using `http://eth0.me`, but it doesn't load for me on my machine and my antivirus has it blacklisted, thus Python raises a `ConnectionError`. It loads through Tor though, so I don't know whether I should use it.
# [Python 3](https://docs.python.org/3/), 101 bytes
```
from socket import*
from requests import*
gethostbyname(gethostname())+" "+get('http://eth0.me').text
```
] |
[Question]
[
Print or return the following text:
```
Hello world! The quick brown fox jumps over a lazy dog.
```
However, your submission will not be scored in bytes. Instead, primarily it will be scored by the width in pixels of the program when written in Arial in a 12pt font. In particular, the score is:
$$ (\text{visual width in px}) + \frac{1}{1000}(\text{length in characters})$$
Since there might be slight differences based on platform, OS etc the following program will be used to judge your score:
[Try it online!](https://tio.run/##Vc7NToQwEADgO08xnqDRbQsmevLAxUiyB2O8GWO6MEC1MLWUZdmXx8IaEy@Tycw3P3b2LfW3S/5S5Ht4gFiQ9aJGo0/C6MNvtsVdJtM7Lu95mu1cmYqhVQ4viHo/iNxpZbj3dbzUjjp4LvagO0vOQ9GpBh@DilYazvwVuHcj@tlisn1wA2nGopIqDIgs9olk3KGqEhYd9TAq8zHpyrehu27iDfpBnzFZJ9ibfI@s071P/tFrMGHPJkBAKqXkki3LRcZPaAzBRM5UV/DaInyPuvyCg6OpDzdO8Dl2dgA6ogMFRp1nqKjhMfsB "Python 3 – Try It Online")
### Rules
* Standard I/O rules apply.
* A single trailing newline is optionally permitted in the output. No other variation is permitted.
* Lowest score as calculated by the above program wins.
* Note that the measure of visual width used ignores newlines. As far as I can tell, you can never reduce the score of your program by adding characters.
[Answer]
# [Zalgo](https://esolangs.org/wiki/Zalgo), score ~~5.221~~ 0.222
```
̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̝̐̈̄̐̅̆̐̌̆̐̌̆̐̏̆̐̀̂̐̇̇̐̏̆̐̂̇̐̌̆̐̄̆̐́̂̐̀̂̐̄̅̐̈̆̐̅̆̐̀̂̐́̇̐̅̇̐̉̆̐̃̆̐̋̆̐̀̂̐̂̆̐̂̇̐̏̆̐̇̇̐̎̆̐̀̂̐̆̆̐̏̆̐̈̇̐̀̂̐̊̆̐̅̇̐̍̆̐̀̇̐̃̇̐̀̂̐̏̆̐̆̇̐̅̆̐̂̇̐̀̂̐́̆̐̀̂̐̌̆̐́̆̐̊̇̐̉̇̐̀̂̐̄̆̐̏̆̐̇̆̐̎̂
```
[Score this online!](https://tio.run/##vZHBTsIwHMbve4re2KJ0HSZ68rCLCQkH49UYM6FAk7EuXVHxBBMKCqIv4BvtKXyR2f07WH0B0@RL8@@v3/c1TWdyzJOzMrzphj10iVo@T6U/pDF79mP2UO9A2x0SnGNygYNOW/QDPxtHghqIJzLzQ8GiGEs5bJVDwSfouttDbJJyIVF3Eo3olaacCtUxxwGWYkrlLKUuNDhFQcdz@nxANcRTmrjEw4JGA9dzHlk2jeL7JzaQY31aOeERlRl7oW51w7sld04qWCLdP@gJirUPEMhHASEEE68sf@bb4vtf11exKZZaV4XSurP0E3Re5FrXeh0mOewNswRdAGPIpXaqPNXR08wXcGsF@gbzV9CtxeSWv8kyuXuLUVa3DZya@XudWE0@an4NKQ1jbqm6SZN1aNik7Op3KXA2ndfWG5XVUEHDXH/dLw)
I think I found the ~~perfect~~ **uberperfect** language! Tested with the [official interpreter](https://github.com/shortc1rcuit/zalgo) locally. Now also uses dingledooper's observation that zalgo surrounded by two `\u200b`s has width zero. Luckily (and surprisingly) `\u200b` is not considered as a whitespace in the interpreter (which uses Rust's `char.is_whitespace`).
Script to generate the source:
```
s = 'Hello world! The quick brown fox jumps over a lazy dog.'
ans = '\u200b'
ans += '\u031d' * len(s)
for c in s:
d = ord(c)
ans += '\u0310' + chr(0x300 + d % 16) + chr(0x300 + d // 16)
print(ans + '\u200b', end='')
```
[Try it online!](https://tio.run/##ZY5BDoIwFET3nGJcmIIYKZK4MGHvAVy6AVoErf3YgoCXR6yJifGv5k3yJr8Z24p0Mk0WKdhBKkXoySixwLGSuHd1cUVuqNcoacCluzUW9JAGGVT2HCHovGFepp1/6rac5x8MHfMkFgwrKKl9G3glGRSoNezew3xitsgIvwgc/nicIURRGZ8PCedzFlgi3gV/bRS9a68xtW59N/H9ZA2pRcpYME0v "Python 3 – Try It Online")
[Answer]
# [Python](https://www.python.org), 125.833 score
```
ᵉᵛªˡ(ᵇʸᵗᵉſ(ᵐªᵖ(ˡᵉⁿ,''.ſᵖˡᵢᵗ(''))))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=7dyhDoJQFIDhxwE3NRl8AJ_FmdSgwabJOQ0mCBRw00C_m42NjSJvYLs8idepb-DwnOvv_iIF-A7jJm5yma8Wk9k0Tc_Lxbg3vI8G1uysScq8zkJrtrerNbE7VBXu37HMrYnCOnMHmk3RDZr1nr7a4dcX4GvAoickMH3lbe3UHj9CHt8aYpKDEUaBteDJyNoJZzxVBCyMvnKxnnL7YoNOoBhDQVVjCKOHlZZYyOQEFLAqwhNndbHSyQw0PJXGK0V-ACKsJSQhVRTLn7rwBFlgiOmFZXZClBgEjCj5GuCeaTNQuPBUlyi3v_jyN-hXhTXRc_-PkzVxGLjLCTru99o85L2HyGcvkQc) *or* [Score this online!](https://tio.run/##7dw/T8JAGMfxnVdxW9sI/YOJTg4sJiQMxtUYU@GAJqVt2kPFSSdjZHCCwQlH9yZuJCQs8irKG8EDjYm7C/IlvxC4Pi3t52l7U0kGqhtH@6vaab3WEEfCcOJEOW0ZBjdOGFx@f9q8V6qud2C7h7ZXraRNz8m6fiq/iuJIZU4tDfzQVqptrNpp3BMn9YYIekmcKlHv@R15rKtK61L9Mz8Dtkr7Ug0SaW72oCy8qlVqxi2pi@JERqZr2an0W6ZVugqyvh9eXAct1dVL11uyO1Jlwa0012tYZ@55KUmDSJm/SvdEqLezqRCO8FzXtV1rtSryxyJ/mb0tJmaRP3y8F/lYD82n@tvz7K3IR@ZiogeW99Oysbx7In@aIQjAogcm2ULeIacQh4YYjDCS7fGkZVwaeBJgYfz3XMynHD50iNEUTnWECXpYMZERoIDFk@DMTEdfCJ5Q000AEUaSQMr0hzOeICNGuEXTCBoBI0qAE27XdITguctuO/Hkr2HPp0U@Wv//x2uRj01D745h6dcn)
### Explanation
Through some experimentation, I found that `\u200a` (zero width space) takes up **zero** pixels. In addition, as kindly pointed out by [Mukundan314](https://codegolf.stackexchange.com/users/91267/mukundan314), `\u200c` seems to use up zero pixels as well, though only when surrounded by `\u200a`. Using this fact, I created an algorithm to encode any string using only the characters `\u200c` and `\u200a`. The algorithm works by encoding each character as a string of `\u200c`s whose size is the value of its unicode codepoint. Then, they are joined together by `\u200a`.
Then, decoding it is simply a matter of splitting the string by the `\u200c` delimiter, mapping each element to its length, and converting it back into a string using the `bytes` builtin:
```
bytes(map(len,'...'.split('\u200c')))
```
In the implementation, the strange-looking unicode characters are converted to ASCII due to Python's [implicit NFKC normalization of identifiers](https://docs.python.org/3/reference/lexical_analysis.html), which help slightly shorten the pixel width.
# [Python](https://www.python.org), 139.097 score
*-0.002 score thanks to @Neil, who noticed that the `\u200b`s are apparently unnecessary here.*
```
ᵉᵛªˡ(ᵇʸᵗᵉſ(ºʳᵈ(ˡ)%126for ˡ in'ֲًٌٍٍِّّ֑᷿͈ۘۚ︠̔ۘ̔̔ۛٓ̔̕ﱢٍَْ᷿ۘ̔ͬ̔ۛۙ̔᷾ۘ̔ﱡ̔ﱡٌُ֑۠۟̔︡'))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3zz3c2vlw6-xDq04v1Hi4tf3UjodbpwOFju7XOLTr1OaHWzs0Ti_UVDU0MkvLL1I4vVAhM0_9UeO62zNuTnzUuOb2rPc7FlybeG3Tzd5HjavAaO2ZKQ-37wfSt2cA-Td7zkw9M-Vsx80JN3vPTHnUuP727JsTb3bfnHxmyvuNi0BK1oJVrzkz5WYfkHMWxJh0e_ajxtUgW2aC9ABV7LvZe3sGSMtCkMAqIH17we35QKU9QOmb_Y8a1lyb-H7HQnVNTYivoJ6DeRIA)
An alternative solution, which although longer, may port better to other languages. The idea here is that any string of accent characters embedded between two `\u200b`s has a pixel width of zero.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), score ~~49.089~~ ~~27.235~~ 27.107
```
⍘⍘̔̆́̐̐̑̊̓̇̂̐̇̋̒́̒̎̏̌́̄̐́̉̌̇̀̍̌̌̓̒̊̋̎́̄̎̅̍̃̂̒̃̂̉̏̑̈̋̄̎̋̂̂̃̋̋̍̎̀̈̍̀̆̇̐́̐̒́̑̄̑̎̒̌̎̑̐̔̄¦̀́̂̃̄̅̆̇̈̉̊̋̌̍̎̏̐̑̒̓̔γ
```
[Try it online!](https://tio.run/##HY5LDsIgEIbP2nTjwsTEE7QV@xBoAbvwBF7AG7j@00N4EfwgkGH4XzPtqbm2l@ac88@/uNo1qlfgRD301KSBfpJVAk9atcnRGdBeC/2kTp7XoU54LJrCr7qD3/CnWhecUTN84SzIAG45nn8H46kjeaFuUOZFtBE2kb7SBfYz3ze6vroNM4pjJr1MdjVrq9sn9tmPT85/ "Charcoal – Try It Online") No verbose version because the deverbosifier extraneously quotes the strings, which is longer than using the `¦` separator. Explanation: Converts a string from base `\u0300-\u0314` and then into base `-~` (printable ASCII).
```
̔̆́̐̐̑̊̓̇̂̐̇̋̒́̒̎̏̌́̄̐́̉̌̇̀̍̌̌̓̒̊̋̎́̄̎̅̍̃̂̒̃̂̉̏̑̈̋̄̎̋̂̂̃̋̋̍̎̀̈̍̀̆̇̐́̐̒́̑̄̑̎̒̌̎̑̐̔̄ Literal string of \u0300-\u0314 characters
⍘ Convert from base
̀́̂̃̄̅̆̇̈̉̊̋̌̍̎̏̐̑̒̓̔ Literal string `\u0300-\u0314`
⍘ Convert to base
γ Predefined variable printable ASCII
Implicitly print
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), score 64.584
```
`0:`c$#'""\""
```
[Try it online!](https://ngn.codeberg.page/k#eJzt2MEJwkAQhtFeVsGrZ2vxELAR70mVVqIlKMSZyc6Dh0cXv/0JxOV6Wx7n02W8ntu4fz7XnWz7fRV1Os99XMqJhyNRn/Ipdz39Q4aGvpmZKWYlUj6M1DoXIVGf5pHnxpxlvZHUlqiCDq/kWT8T5QUvKCxRqwed4UlEHR1ejcHeCGZyxLO6golcCikMb+LOLlci0tlYtURuhH+zMfFpyPYkogL/4zErS+MH4w2v5O4F) or [Score this online!](https://tio.run/##7ZhBS8MwHEfv/RRhCmvRpekEBcHDLsJgB/Gq4uqWbYGuKWmmzpN3@yn9IrXbRDx4ksFkPniEkv6TlJdfc0ix9DObn9S9635vIC5EO7aFjyc6M89xZh4@n9Ztp6uSU6nOZNLtuFESl7PU6U2RzX0Z95xJM@n9pF1PnJ2Lq/5AmHlhnRf9eTrVl01VsCptlvnqkN4ttF8WOlx/wbFIulEwsmPdFNlC56GKpNPpOIyCR1Mu0uz@yYz9rHm7mklOtS/Niw5XI6IbdRcUzuQ@/F4a/dAnjkTWzL0eJWKRKKWkiup6qM6Ho8ODduv9tWrdNu3blqi2NxX8Hc/7vRy5RRHmd77XFXmGf/nzEsVdKcI85y2eUQT76rzau7VIL2cFipDMzQNgHuEo4qAjeCgCwkbIgZwDEDkgdShiU4DTAM9sLvkHMoYidgSINCAfyB6KALjHAyBp8HtaHw)
A port of dingledooper's answer to K. Uses `\u200b` as the "word" character and `\u200c` as the separator. The only difference is that "length" `#` counts each "space" character as 3 bytes, so I had to do a little calculation so that `(word length in characters) * 3 % 256 == output character`.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `s`, Score 41.09
```
``\/vLC
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJzIiwiIiwiYOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAjOKAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi+KAi2BcXOKAjC92TEMiLCIiLCIiXQ==)
Port of dingledooper's answer.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), score: 494.078 (78 bytes)
```
"He
llo
wo
rld
! T
he
qui
ck
bro
wn
fox
ju
mps
ov
er
a l
azy
do
g.
"ṇc
```
[Try it online!](https://tio.run/##BcHBGcFAFIXR/V/FlQIsVKEAK7vJZCTi8RhfRDSgJuWo5OWctqY8LOb9LqLZF8wczU61jo0ODEU8pjP5ItrqzDdx8jcaJ673J/IXpYokI30W1Dn9lub/@@aIOK4 "Brachylog – Try It Online")
Not as competitive as the rest, but the program contains the expected string with no specific encoding.
### Explanation
`"ṇc` ends a string, splits it on linebreaks into a list of strings, and then concatenates it back into a single string with no linebreaks.
We then split the string into chunks of at most 3 chars with linebreaks, as Brachylog supports inline multi-line strings.
[Answer]
# Mathematica, score 261.096
```
FromCharacterCode[ToCharacterCode@"̨͌͌ͅ͏̀͗͏̴͈͕͉͒͌̈́́̀̀͑̓͋̀͂͒ͅ͏͎͗̀͆͏͕͍͓̀͊͐̀͘͏͖͚͙͒̀́̀͌́̀̈́ͅ͏͇̎"-736]
```
[View it on Wolfram Cloud!](https://www.wolframcloud.com/obj/3eca615e-a692-4acf-a5dd-4f7636397a8f)
[Score it online!](https://tio.run/##VY/fSsMwFMbv@xRhN2vRpWkH25XgGAwKuxDxbgypa7YFuqakmTqvNt3876oT/z6BD@Bj9DxTPasijEDyy/m@8@UknuihjKp5Y99rtMkOKdsy1nafh@LUDsXRHxV7xWVOjbI6ddyK6jl2MvQV/zXJSCd2Qwk/pFr3y3lfyRHZ89pEjGKpNPFG/oC30GWsrfjMf4FqNeZ6EnOzmGCbOK5l9GTA0SRjHpnMoor7gWkZxyIZ@@HhiQj0ENV1Eh1wnYgzbq47rA7rGrESkTY3rFskxJzCQWziMMYos/K8hTM28Qt@T3PVRLVzIDfuu6XsCxZwjyvNpvAGKayQ59ksm2bfcA0LrD7BC9zABdwhn6Oeom@JfIn0juct6g/wCM/IKbxi3goJEzBpBp/wgTRH5Spblir1aq37Aw)
[Answer]
## Pascal, 495.092
```
program i(output);begin write('Hello world! The quick brown fox jumps over a lazy dog.')end.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), score 40.062
```
’̨͌͌ͅ͏̀͗͏̴͈͕͉͒͌̈́́̀̀͑̓͋̀͂͒ͅ͏͎͗̀͆͏͕͍͓̀͊͐̀͘͏͖͚͙͒̀́̀͌́̀̈́ͅ͏͇̎’ÇŽ2ã-
```
[Try it online!](https://tio.run/##Dc0xDoJAEIXhE9F4I0wsrCi8wCIgKsoKBhRbGg5ga0Xs5l2Ciyx/tpgv8yZvk0O83e9CWNxgkwrdeN6cXvJqcW6pOfvqrIJto04XZarwkdxzV@MTejOv5Hc99MRePX0tooGmVB8NKCcprebDufz/NvMYhbAC "05AB1E – Try It Online") Outputs as a list of byte values.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), score ~~30.062~~ [29.061](https://tio.run/##VY7LSgMxFIb38xShLjqDNsmMoCsX3QiFLsStiIxtpg1MJyGTqnXVauvdjla8rlz6AL6FOc80nlYRJJB8nP/Ln@iB7apstaxvN@pNskGqTGnLEpHKI5bK/V9a7LWIh2uUr9MwqplWyPJubMSPpDKbs7qRcUqtTaplYlSPbDWaRPa0MpY0enFHbKLlzVV85m9ArekLO9DCX/xghYRR4LVUW6CktMh8HlAj4rYfeAcy78fp3qFs2y6m8ybaETaXx8Kf3wh2@K6njcys/09dJin2LAzCSMg5pzwoy4r7gAnc4CrcEJ6hgBny2I3c0H3CBUxweg@PcAmncI18gnmB3hT5DOkFzyvMb@EOHpALeMK@GRI2YNMI3uAVaYzJuZtWWrWlr/dv)
```
"̨͌͌ͅ͏̀͗͏̴͈͕͉͒͌̈́́̀̀͑̓͋̀͂͒ͅ͏͎͗̀͆͏͕͍͓̀͊͐̀͘͏͖͚͙͒̀́̀͌́̀̈́ͅ͏͇̎"c-#ˠ
```
[Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Ilx1MDMyOFx1MDM0NVx1MDM0Y1x1MDM0Y1x1MDM0Zlx1MDMwMFx1MDM1N1x1MDM0Zlx1MDM1Mlx1MDM0Y1x1MDM0NFx1MDMwMVx1MDMwMFx1MDMzNFx1MDM0OFx1MDM0NVx1MDMwMFx1MDM1MVx1MDM1NVx1MDM0OVx1MDM0M1x1MDM0Ylx1MDMwMFx1MDM0Mlx1MDM1Mlx1MDM0Zlx1MDM1N1x1MDM0ZVx1MDMwMFx1MDM0Nlx1MDM0Zlx1MDM1OFx1MDMwMFx1MDM0YVx1MDM1NVx1MDM0ZFx1MDM1MFx1MDM1M1x1MDMwMFx1MDM0Zlx1MDM1Nlx1MDM0NVx1MDM1Mlx1MDMwMFx1MDM0MVx1MDMwMFx1MDM0Y1x1MDM0MVx1MDM1YVx1MDM1OVx1MDMwMFx1MDM0NFx1MDM0Zlx1MDM0N1x1MDMwZSJjLSNcdTAyZTA)
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), score 58.092
```
smCldc""\
```
[Try it here!](https://pythtemp.herokuapp.com/?code=smCldc%22%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8C%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%22%5C%E2%80%8C&debug=0)
[Score it online!](https://tio.run/##7dVPS4RAGMfxu69i2MsqteNoUKcOSxAIe4iuFWHruDugjoyz1XbqXq@yN2JqEfQOYvvCDxF9/DOfR2favd/a5qRfXmfLlTgX89i2Pi51ZZ7jyjx8703bRaqSU6nOZJIu3DqJu23u9FeRbXwXL53JK@l9Oe9LZ2txla2EqVvrvMjqfKMvh6pgLB0e83NAerfTft/qcHqDY5GkUbC2hR6KbKubUEXS6bwIo@DRdLu8un8yhd8OZ8c7yY32nXnR4XhFdKPugtaZxoe/So9ENdxnqhCxSJRSUkV939UXVbGefby@HWjeD3doiMEII/lrnrSMXwNPAiyMB8/FesrwoUOMpvCpI0zQw4qFjAAFLJ4EZ1Y6@kLwhJpuAogwkgRSlj@c8QQZMcIUTSNoBIwoAU6YrukIwfP/us1uh9f5BA)
Near literal translation of [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)'s [Python answer](https://codegolf.stackexchange.com/a/251553/78186).
] |
[Question]
[
In this code golf challenge, you will verify hashtags!
# #What\_your\_code\_should\_do
Input is a string. Output a truthy value if it is a valid hashtag, and a falsy value otherwise.
We define a string as a valid Hashtag if ...
* It starts with a hash (`#`).
* It doesn't have a number right after the hashtag (e.g. `#2016USElection` isn't a valid hashtag).
* It doesn't have any "special characters" (i.e. any character that isn't an alphabet, underscore (`_`) or a number).
You can assume that the input only contains ASCII characters. (It would be unfair if we did Unicode too.)
# #Rules
Basic [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply.
# #Examples
Truthy:
```
#
#e
#_ABC
#thisisanunexpectedlylongstringxoxoxoxo
#USElection2016
```
Falsy:
```
Hello, World!
#12thBday
#not-valid
#alsoNotValid!
#!not_a_hash
```
[Answer]
## [Retina](https://github.com/m-ender/retina), 12 bytes
```
^#(?!\d)\w*$
```
Prints `1` for hashtags and `0` otherwise.
[Try it online!](http://retina.tryitonline.net/#code=JShHYApeIyg_IVxkKVx3KiQ&input=I1VTRWxlY3Rpb24yMDE2CiMKI3RoaXNpc2FudW5leHBlY3RlZGx5bG9uZ3N0cmluZ3hveG94b3hvCiNIYXNodGFnX29yX25vdAojX2hhc2gKIzEydGhCZGF5CkhlbGxvLCBXb3JsZCEKIzIwMTZVU0VsZWN0aW9uCiMj) (The first line enables a linefeed-separated test suite.)
Not much to explain here, this is quite a literal implementation of the definition: `^` and `$` are just anchors ensuring that the match covers the entire string, `#` checks that the string starts with a `#`, `(?!\d)` ensures that the next character *isn't* a digit (without advancing the regex engine's position), `\w*` checks that we can reach the end of the string with zero or more letters, digits or underscores.
By default, Retina counts the number of matches of the given regex, which is why this gives `1` for valid hash tags and `0` otherwise.
[Answer]
## Perl, 22 bytes
**21 bytes code +1 for `-p`**
```
$_=/^#([a-z_]\w*)?$/i
```
Prints 1 if it's a valid hashtag, empty string otherwise.
### Usage
```
perl -pe '$_=/^#([a-z_]\w*)?$/i' <<< '#'
1
perl -pe '$_=/^#([a-z_]\w*)?$/i' <<< '#_test'
1
perl -pe '$_=/^#([a-z_]\w*)?$/i' <<< '#1test'
```
Saved 2 bytes thanks for [Martin Ender](https://codegolf.stackexchange.com/users/8478/martin-ender) (and another 4 using his [lookaround method](https://codegolf.stackexchange.com/q/85621))
---
## Perl, 18 bytes
**17 bytes code +1 for `-p`**
Using Martin's lookaround this can be much shorter!
```
$_=/^#(?!\d)\w*$/
```
[Answer]
# JavaScript (ES6), 25 bytes
```
s=>/^#(?!\d)\w*$/.test(s)
```
```
F = s => /^#(?!\d)\w*$/.test(s)
input.oninput = () => result.innerHTML = input.value ? F(input.value) ? '\ud83d\udc8e' : '\ud83d\udca9' : '\ud83d\udcad';
```
```
#input, #result {
vertical-align: middle;
display: inline-block;
}
#input {
line-height: 2em;
}
#result {
font-size: 2em;
}
```
```
<input id="input" type="text"/> <span id="result">💭</span>
```
[Answer]
# C, 80 bytes
Function `f()` takes the string as an argument and modifies `int *b` to either 1 or 0 to indicate truthy/falsy.
```
f(char*p,int*b){for(*b=(*p==35)&&!isdigit(p[1]);*p;++p)*b&=isalnum(*p)||*p==95;}
```
If the string always has at least one character (i.e. never an empty string), a byte can be shaved off for 79 bytes:
```
f(char*p,int*b){for(*b=(*p==35)&&!isdigit(p[1]);*++p;)*b&=isalnum(*p)||*p==95;}
```
[Answer]
# Python 3, 41 bytes
```
import re
re.compile('#(?!\d)\w*$').match
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 55 bytes
```
"#"|h"#",?b@lL'(eE,@A:"1234567890":"_"c'eE),@A:"_"ce~hL
```
This uses no regex.
### Explanation
```
Main predicate, Input (?) is a string
"#" ? = "#"
| Or
h"#", First character of ? is "#"
?b@lL L is the rest of the chars of ? lowercased
'( It is not possible for any char of L that...
eE, Call this char E
@A:"1234567890":"_"c Concatenate the lowercase alphabet with the digits and "_"
'eE E is not a member of that concatenated string
),
@A:"_"c Concatenate the lowercase alphabet with "_"
e~hL One char of that concatenated string is the first char of L
```
[Answer]
## Python 3, ~~103~~ 93 bytes
```
all((c=='_'or c.isalpha()*i>0)^(i<1and'#'==c)^(c.isdigit()*i>1)for i,c in enumerate(input()))
```
The `#` being `True` killed me here, I had to enumerate the string to avoid an index error on the single character input.
[Answer]
## PowerShell v2+, 25 bytes
```
$args-match'^#(?!\d)\w*$'
```
Using [Martin's regex](https://codegolf.stackexchange.com/a/85621/42963), just wrapped up in PowerShell's `-match` operator coupled with the input `$args`. For truthy/falsey values, this will return the string itself on a match (a truthy value) or nothing on a non-match (a falsey value). This is because when a comparison operator is applied against an array, it [returns anything](https://codegolf.stackexchange.com/a/745/42963) that satisfies that operator.
A couple examples (wrapped in a `[bool]` cast to make the output more clear):
```
PS C:\Tools\Scripts\golfing> [bool](.\hashtag-or-not.ps1 '#2016Election')
False
PS C:\Tools\Scripts\golfing> [bool](.\hashtag-or-not.ps1 'Hello, World!')
False
PS C:\Tools\Scripts\golfing> [bool](.\hashtag-or-not.ps1 '#')
True
PS C:\Tools\Scripts\golfing> [bool](.\hashtag-or-not.ps1 '')
False
PS C:\Tools\Scripts\golfing> [bool](.\hashtag-or-not.ps1 '#USElection2016')
True
```
[Answer]
# Mathematica, ~~52~~ ~~46~~ 43 bytes
Saved ~~6~~ 9 bytes due to [@MartinEnder](http://ppcg.lol/users/8478).
```
StringMatchQ@RegularExpression@"#(?!\d)\w*"
```
Function. Takes a string as input, and returns `True` or `False` as output. Pretty simple, just matches against the regex `/#(?!\d)\w*/`.
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), ~~22~~ 20 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319)
Without RegEx:
```
{0≤⎕NC 1↓⍵,⎕A}∧'#'=⊃
```
-2 thanks to ngn
[Answer]
# Python 2, 79 bytes
```
lambda x:x=='#'or(1>x[1].isdigit())&x[1:].replace('_','').isalnum()&('#'==x[0])
```
First golfing attempt. Ungolfed version:
```
def f(x):
if x == '#':
return True
else:
return x[0]=='#' and x[1:].replace('_','').isalnum() and not x[1].isdigit()
```
[Answer]
# Octave, ~~37~~ ~~56~~ ~~54~~ 43 bytes
Thanks to @LuisMendo for removing 8 bytes!
```
@(s)s(1)==35&(isvarname(s(2:end))|nnz(s)<2)
```
Not very golfy, but very built-inny.
Edit: The original code accepted strings with no leading '#'. I guess I should have stuck with regex.
Test suite on [ideone](http://ideone.com/ihx7a5).
[Answer]
## Python3 - 156 128 bytes
```
lambda n:n=="#"or(n[0]=="#")*all(any([47<ord(c)<58,64<ord(c)<91,ord(c)==95,96<ord(c)<123])for c in n[1:]+"0")*~(47<ord(n[1])<58)
```
A solution that doesn't use regex. 0 is falsey and every other value is truthy.
Thanks to @LeakyNun for saving bytes!
[Answer]
# Lua, ~~59~~ ~~55~~ 54 bytes
## Code
```
s=arg[1]print(load(s:sub(2).."=0")and s:sub(1,1)=="#")
```
## How it works:
1. Check if the rest of the characters can be a valud Lua identifier (identifiers in Lua follow the same rules as hashtags.)
2. Check if the first character is a `#`.
Takes input from the command line. Prints `true` if the string is a valid hashtag, otherwise, it prints `nil`.
[Answer]
# Google Sheets, 30 bytes
An anonymous worksheet function that takes input from the cell `A1` checks it against the RE2 expression and outputs the result to the calling cell.
```
=RegexMatch(A1,"^#([a-z_]\w*)?
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 18 bytes
Code:
```
¬'#Qs¦A«¬d_sDžjKQP
```
Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=wqwnI1FzwqZBwqvCrGRfc0TFvmpLUVA&input=I1Byb2dyYW1taW5nX1B1enpsZXNfYW5kX0NvZGVfR29sZg).
[Answer]
# Sed 19 + 2 = 21 bytes
```
/^#([a-z_]\w*)?$/Ip
```
This filters out all non-hashtags and outputs valid hashtags.
Run as `sed -rn "/^#$|^#[a-z]\w*$/Ip"`. Quit with `Ctrl` + `D` (send EOF).
[Answer]
# GNU grep, 15 + 2 = 17 bytes
```
grep -Ei '^#([a-z_]\w*)?$'
```
### Test:
```
$ echo '#
#e
#_ABC
#thisisanunexpectedlylongstringxoxoxoxo
#USElection2016
Hello, World!
#12thBday
#not-valid
#alsoNotValid!' | grep -Ei '^#([a-z_][a-z0-9_]*)?$'
```
Output:
```
#
#e
#_ABC
#thisisanunexpectedlylongstringxoxoxoxo
#USElection2016
```
[Answer]
# Python 3, 97 Bytes 70 Bytes 56 Bytes
```
lambda x:s=x[2:];b=x[1];all(x!="#",[x[0]=="#",any[b.isalpha(),"_"in b],any[s.isalnum(),"_"in s]])
```
(Code changed) Human readable
```
x=input()
if x[0]=="#" and x[1].isalpha() and str(x)[2:].isalnum():
print(True)
else:
print(False)
```
[Answer]
## Pyke, 19 bytes
```
\#.^It,!It\_D-PRkq|
```
[Try it here!](http://pyke.catbus.co.uk/?code=%5C%23.%5EIt%2C%21It%5C_D-PRkq%7C&input=%23)
Quick fix for tonight
[Answer]
# Ruby, 16 + ~~3~~ 1 (`n` flag) = ~~19~~ 17 bytes
Uses `0` as truthy and `nil` as falsy.
```
p~/^#(?!\d)\w*$/
```
Run it as `ruby -ne 'p~/^#(?!\d)\w*$/'`. Thanks to @manatwork for fixing the bash error when running the program.
[Answer]
# [Standard ML](http://www.mlton.org/), ~~121~~ ~~118~~ 107 bytes
```
(fn#"#"::a=>(fn x::r=>x> #"@"andalso List.all(fn#"_"=>1=1|c=>Char.isAlphaNum c)a|e=>1=1)a|e=>1=0)o explode;
```
[Try it online!](https://tio.run/##TVDLasMwEDzXX6EolxiSEOfQg41M41DooeQS2h76MIutxoK11lhKcSD/7kpWCkVI2h3NaKQxLa5atKTHcfGt53zO0xRE7mo2pGkv8iFnc/7AQdeAhtizMnYNiBO55CJPRHKtRL5voF8rs8OugcO5ZVUMVzmd/hWbmJgcOqRaZuMPILPSWCZYCx1bdL3SlhHzvkbk5ot/aB47oCDCtaWjdYST65WNs8ir3VS1k79Hd@7RS7/KsJW7Yh8q2yijDOizdsaysrLGC5I@mem2gcII3JfjIzqKIr3dJPf8M7go/d/nSSLSkr1Rj/UsyJKtbYoaLqHTZFeTILQ@sQPZV4/c@DNHKaFswDTeY8pgUmRRyMB//IbfzLPxFw "Standard ML (MLton) – Try It Online")
Functional solution without using regex. Declares an anonymous function which is bond to the implicit result identifier `it`.
```
> val it = fn : string -> bool
- it "#valid_hash";
> val it = true : bool
```
[Answer]
# Excel VBA, 54 bytes
Anonymous VBE immediate window function that takes input from cell `[A1]`, checks if the value of the cell matches the `Like` pattern, and outputs as `Boolean` to the VBE immediate window
```
?Not[Left(A1,2)]Like"[#]#"And[A1]Like"[#][_a-zA-z0-9]*
```
[Answer]
# [Haskell](https://www.haskell.org/), 79 bytes
```
import Data.Char
f(a:r)=a=='#'&&r==""||r!!0>'@'&&all(\c->c=='_'||isAlphaNum c)r
```
[Try it online!](https://tio.run/##bY9Ba8IwFMfPzadII9gWrKiHHQaRqRvssHkRt8OU8mirCUuTkKRDod@9S42HHfYC7@U9fv9/XhjY71qIvueNVsbhZ3Aw3TAw6JTCo8koUJqMkvHYUEpI15k4ni2TJz8AIdJDmS9LDxRJ13G7EprBtm1wmZn@BwSvMMVfKCIjMhlyHUqxWm/CzTFuuQXZyvqi69LVlbgKJc/WGS7PFxVOYPe7F@ERruRiNn8gR8Tl3yde/SfUBH8qI6o4KOYLx9YVXEMnlctvgtCCsGqr3McwufOxRwooGFjm7VEDXHrzSqGoAf2OU@2XcniKTxm@GaFIt27nzJsk@RDkH/C@ZP8L "Haskell – Try It Online")
[Answer]
# C#, 92 bytes
```
s=>s[0]=='#'&s.Length>1&&(s[1]<48|s[1]>57)&s.Skip(1).All(x=>char.IsLetterOrDigit(x)|x=='_');
```
C# lambda (`Predicate`) where input is a `string` and output is a `bool`.
[Try it online!](https://dotnetfiddle.net/3DxbYm)
[Answer]
## Lua, 39 bytes
```
print(arg[1]:match("^#[%a_][%a_%d]*$"))
```
Straightforward copypasta of match description. Outputs falsy `nil` if not hashtag, outputs truthly hashtag back otherwise.
Can be shortened for one more byte by using `find` if outputing list of two values (which is truthly) doesn't break rules.
[Answer]
## Clojure, ~~130~~ ~~135~~ 132 bytes
* +5 bytes to deal with an NPE that happened when the string consisted of only a hashtag.
* -2 bytes by using `Character/isLetterOrDigit`.
```
(fn[s](let[[h & r]s n(map int r)](and(= h\#)(not(<= 48(or(first n)0)57))(every? #(or(Character/isLetterOrDigit^long %)(= 95 %))n))))
```
Ungolfed:
```
(defn hashtag? [s]
(let [[h & r] s
codes (map int r)]
(and (= h \#)
(not (<= 48 (or (first codes) 0) 57))
(every?
#(or (Character/isLetterOrDigit ^long %)
(= 95 %))
codes))))
```
[Answer]
# Java 8, ~~57~~ ~~54~~ 28 bytes
```
s->s.matches("#(?!\\d)\\w*")
```
Port of [Martin Ender's Retina answer](https://codegolf.stackexchange.com/a/85621/52210) to save a few bytes and match added test cases.
Not that [`String#matches`](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#matches(java.lang.String)) always matches the entire String, so no need for `^...$`.
[Try it here.](https://tio.run/##hY4xT8NADIX3/go3XRJEI9qBpQJEERILXSrEQBBy70xz5eKLck5phPLbw9FkRZHtwfL3nt8Bjzh3JfFBf3XKovfwjIZ/JgCGhapPVASbvxVg55wlZFDxVirDe/DJKhzaMKG9oBgFG2C4gc7Pb31aoKicfBzN4rtplukky74voqRb9Yqy3tmgGIRHZzQU4ffg/vYOmPSPt40XKlJXS1qGk1iOOVVx9ETWukt4dZXV0yg5p/mfnr1sHy0pMY6XV4vrcV5y441HrplOZRCSto11vPfnfCfX17jPYin5WmMzTo4TNI583K8fBqqdtN0v)
] |
[Question]
[
### Task
Write a program or function that takes as input a time in UTC, and outputs the equivalent time in **5 different cities** around the world. The cities displayed are up to the programmer, but the **time must be different** in each city.
To prevent golfers from using overly obscure city names, the city names used must appear on this list: [World Cities](https://pastebin.com/xmRiwZiQ)\*, which corresponds to the list of cities and times found [here](https://www.timeanddate.com/worldclock/).
As usual, [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default/1062#1062) are forbidden, including fetching data from an external source.
\*The times provided in the pastebin use daylight time and assume that the time is 0:30 UTC.
### Example
Given as input 12:30AM, your output might be:
```
Athens: 3:30AM
London: 1:30AM
New York: 8:30PM
Seoul: 9:30AM
Beijing: 8:30AM
```
### Input
You may take input in any reasonable format. You can choose to take the time as 24-hour time, or 12-hour time with `AM` and `PM`. Specify the input format in your answer.
### Output
Output may also be in either 12-hour or 24-hour time. The city-time pairs may be in any order and any reasonable format, so long as it is possible to associate each city with the corresponding time.
Daylight Savings Time can safely be ignored (ie. you can either use the offsets from the pastebin above, or you can assume that all times are in daylight time, or alternatively all in standard time)
### Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Happy golfing!
[Answer]
# [Python 2](https://docs.python.org/2/), ~~80~~ ~~79~~ 77 bytes
-1 byte thanks to [Surculose Sputum](https://codegolf.stackexchange.com/users/92237/surculose-sputum).
24-hour time, input as `hours, minutes`.
```
h,m=input();i=h
exec"print'ALCADcaamucgimbroraaasoni'[i-h::5],i%24,m;i+=1;"*5
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P0Mn1zYzr6C0REPTOtM2gyu1IjVZqaAoM69E3dHH2dElOTExtzQ5PTM3qSi/KDExsTg/L1M9OlM3w8rKNFYnU9XIRCfXOlPb1tBaScv0/38DHQVjAwA "Python 2 – Try It Online")
Example output for `0, 30` (12:30AM):
```
Accra 0 30
Lagos 1 30
Cairo 2 30
Amman 3 30
Dubai 4 30
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~71~~ 65 bytes
*Save 2 bytes using @dingle dooper's printing through `input()` trick!*
```
t=input('Accra Lagos Rome Kyiv Dubai ')
exec"print t%24,;t+=1;"*5
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v8Q2M6@gtERD3TE5uShRwScxPb9YISg/N1XBuzKzTMGlNCkxU0Fdkyu1IjVZqaAoM69EoUTVyETHukTb1tBaScv0/38jI21D0ywA "Python 2 – Try It Online")
Takes input as a complex number (e.g `01:30` is inputted as \$1+30i\$), and prints out the list of cities, then the corresponding times. Uses 24-hour time.
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + Core utilities, ~~79~~ ~~78~~ 72 bytes
```
for c in Amman Dubai Kabul Dhaka Seoul;{ TZ=Asia/$c date +$c\ %R -d$1Z;}
```
[Try it online!](https://tio.run/##S0oszvj/Py2/SCFZITNPwTE3NzFPwaU0KTFTwTsxqTRHwSUjMTtRITg1vzTHulohJMrWsTgzUV8lWSElsSRVQVslOUZBNUhBN0XFMMq69v///4aWViamAA "Bash – Try It Online")
Input is passed as an argument, and output is on stdout. Both are in 24-hour time.
[Answer]
# Google Sheets, ~~82~~ ~~77~~ 80 bytes
*Saved 5 bytes by finding a shorter list of city names that are all off by 1 hour.*
*Added 3 bytes thanks to Surculose Sputum pointing out that I was referencing the wrong list.*
```
=ArrayFormula(Split("Lagos,Rome,Kyiv,Dubai,Kabul",",")&Mod(A1+Column(A:E),24)&B1
```
Sheets will automatically add the trailing parentheses. Hours are input in `A1` and minutes in `B1`.
`Split(~)` gives us the list of city names.
`A1+Column(A:E)` iterates the input time by ones.
`Mod(~,24)` accounts for when the clock rolls to the next day.
`Split(~)&Mod(~)&B1` tacks on the minutes.
`ArrayFormula(~)` makes the whole thing work on arrays instead of just the first value.
[](https://i.stack.imgur.com/lToyu.png)
There aren't any delimiters between the city name and the time because pretty costs bytes. It's fairly easy to distinguish between the end of the name and the start of the time, though, since none of the city names have numbers in them.
[Answer]
# Befunge-93, 238 bytes
```
&&\" arccA",,,,,,:.\:.\" nammA",,,,,,3+:345*+`!v v <
> v v `+*543:+3,,,,,,"Dhaka "\.:\.:_#<83*-^
^-*38>#_ :.\:.\" luoeS",,,,,,3+:345*+`!v v <
> v v `+*543:+3 ,,,,,"Suva " \.:\.:_#<83*-^
^-*38>#_:.\:.@
```
[Try it online!](https://tio.run/##S0pNK81LT/3/X00tRkkhsSg52VFJBwys9GKASEkhLzE3FyZmrG1lbGKqpZ2gWKZQpgAENlx2IArKg4AEbS1TE2MrbWOIHiWXjMTsRAWlGD0rIIpXtrEw1tKN44rT1TK2sFOOh2uD2ZdTmp8aTJZ9ChD7gkvLgNYp4LAPbI3D//@GllxG5gA "Befunge-93 – Try It Online")
Reads the hour and minutes from the input. For each city, except the first, it adds 3 to the hour, then checks whether it exceeds 23. If it does, it makes a small loop to subtract 24. The rest is just printing strings, moving the PC around and swapping the hours/minute to/from the top of the stack.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 25 bytes
Thanks to Kevin Cruijssen for shaving off 7 bytes.
```
”Accra‡¸«ÄçªâÈ”#ε¹N+24%²»
```
[Try it online!](https://tio.run/##ATkAxv9vc2FiaWX//@KAnUFjY3Jh4oChwrjCq8OEw6fCqsOiw4jigJ0jzrXCuU4rMjQlwrLCu///MjEKMDA "05AB1E – Try It Online")
# [05AB1E](https://github.com/Adriandmen/05AB1E), 32 bytes
Just another port of Surculose Sputum's answer. It produces quite an ugly output, due to joining by newlines.
```
”Accra Lagos«Ä KyivâÈ”#ε¹N+24%²»
```
[Try it online!](https://tio.run/##yy9OTMpM/f//UcNcx@TkokQFn8T0/OJDqw@3KHhXZpYdXnS4AyilfG7roZ1@2kYmqoc2Hdr9/7@RIZeBAQA "05AB1E – Try It Online")
# Explanation (for both)
```
”...” Compressed string with the cities
# Space-split
ε Map:
Implicit current city pushed
¹ First input:
N+ Add by the iteration counter
24% Modulo by 24
² Append the second input
» Join the whole stack by newlines.
```
[Answer]
# [q](http://kx.com/download), 43 40 bytes
```
{`Accra`Cork`Rome`Doha`Dubai!x+60*til 5}
```
No Tio unfortunately for q
q has built in time types that you can perform arithmetic with, so simple enough
```
Example:
q){`Accra`Cork`Rome`Doha`Dubai!x+60*til 5}00:30
Accra| 00:30
Cork | 01:30
Rome | 02:30
Doha | 03:30
Dubai| 04:30
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 26 bytes
```
5ɾ+₆+24%$S+`∴∷₇›†↵ƈ…±↑`5/Y
```
[Try It Online!](https://vyxapedia.hyper-neutrino.xyz/tio#WyIiLCI1yb4r4oKGKzI0JSRTK2DiiLTiiLfigofigLrigKDihrXGiOKApsKx4oaRYDUvWSIsIiIsIiIsIjBcbjMwIl0=)
Takes in `<hour>` `<minute>`, outputs an interleaved list of `<time>|<city>`.
My first Vyxal answer... it took me an embarrassingly long time to figure out how to properly deal with input.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 92 bytes
```
i;f(h,m){for(i=0;i<5;)printf("%s %d:%d;","AccraLagosRome.Kyiv.Dubai"+6*i++,(h+i)%24,m);}
```
[Try it online!](https://tio.run/##S9ZNT07@/z/TOk0jQydXszotv0gj09bAOtPG1FqzoCgzryRNQ0m1WEE1xUo1xVpJR8kxObkokcEnMT2/mCEoPzeVQc@7MrOMQc@lNCkxU0nbTCtTW1tHI0M7U1PVyARoonXt/9zEzDwNoNEaBjrGBiABAA "C (gcc) – Try It Online")
Port of Bash, didn't check map
# [C (gcc)](https://gcc.gnu.org/), 94 bytes
```
i;f(h,m){for(i=0;i<15;i+=3)printf("%s %d:%d;","AccraAmmanDhakaSeoulSuva"+2*i,(h+i)%24,m);}
```
[Try it online!](https://tio.run/##FcxBDsIgEABAnmJISBbBBFu9iD008Qd9wWYrsqlQg9aL8e1Yr3MY2t2IamUfINqkP2EuwJ3zfN4fPZuu1Y/C@RVAqudGjSc1emllT1RQ9ClhFpeIE4rhOi93MSxvlKbZsoVoWKvmsJ7@WxNyhjUHZ1v3hx8 "C (gcc) – Try It Online")
Port of Python solution, didn't check map
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 23 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
+Ɱ5%24;€⁹“F=ẓŒMdƲEṢ$Ṛ.»
```
A full program accepting two arguments, hours then minutes, which prints in an ugly format. Uses `Algiers Amsterdam Amman Dubai Islamabad` since they are the alphabetically earliest allowed cities with DST offsets of `1-5` hours from UTC.
**[Try it online!](https://tio.run/##ATcAyP9qZWxsef//K@KxrjUlMjQ74oKs4oG54oCcRj3hupPFkk1kxrJF4bmiJOG5mi7Cu////zIy/zQ1 "Jelly – Try It Online")**
### How?
```
+Ɱ5%24;€⁹“F=ẓŒMdƲEṢ$Ṛ.» - Main Link: hour, H; minute M
Ɱ5 - map across [1..5] with:
+ - addittion (to H)
%24 - modulo by 24
⁹ - chain's right argument, M
;€ - concatenate to each
“F=ẓŒMdƲEṢ$Ṛ.» - compressed string "Algiers Amsterdam Amman Dubai Islamabad"
- (this new niladic chain forces the previous result to be printed)
- implicit print
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/), ~~118~~ \$\cdots\$ ~~76~~ 75 bytes
Saved a byte thanks to [Duncan](https://codegolf.stackexchange.com/users/72002/duncan)!!!
Saved a whopping ~~18~~ ~~39~~ ~~41~~ 42 bytes thanks to [David G.](https://codegolf.stackexchange.com/users/90945/david-g)!!!
```
for d in Accra Lagos Rome Kyiv Dubai;do date -d$1Z+$((i++))hour +$d%R;done&
```
[Try it online!](https://tio.run/##bcqxCsIwFAXQvV9xhyoJoZAqLjoJbjp1dEuTFxPQPGkbQcRvj/kAz3xGM4fic7JL5AQvJD7F8wSHmHC0djK4mBvPGPhBOL/jC6c8mnhwDGcWQufa/qpaIaJSUgbOE1TrVkMNidbl23j0m/1WN/Od6IldQzYwuv9q1rrm8gM "Bash – Try It Online")
Input passed as command line argument.
Outputs to stdout.
Uses 24-hour time format.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 38 bytes
```
E⪪”↶+∧e-|GT⊘"↘w⌊⎇*↔JAN·”⁵⪫⟦ι﹪⁺Iθκ²⁴η⟧
```
[Try it online!](https://tio.run/##Dck9C8IwEIDhv3JkukCEUnVyEjuVFguO4nBGMMGjV/Ph3z8zvM/y@kDJC7HqkuJacKYNbxvHgubsfaKJ3pKvmQUGCQRDfVI0Do7WwShxxXt0MMursuDCNeOFcsFvu59Wf2iEhwMDxlp7Uu1g3@nux38 "Charcoal – Try It Online") Link is to verbose version of code. Port of @SurculoseSputum's Python answer. Takes input as separate hours and minutes and uses the 24 hour clock. Explanation:
```
... Compressed string of five cities
⪪ ⁵ Split into substrings of length 5
E Map over each substring
ι Current substring
Iθ Input hours as a number
⁺ κ Plus current index
﹪ ²⁴ Modulo literal 24
η Input minutes
⪫⟦ ⟧ Joined with spaces
Implicitly print on separate lines
```
[Answer]
# [JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide), 98 bytes
```
((h,m)=>['Accra','Lagos','Rome','Kyiv','Dubai'].map((e,i)=>console.log(e+' '+(h+i)%24+':'+m+';')))
```
[Try it online!](https://jsfiddle.net/8zofL7g9/ "Javascript – Try It Online")
Get the original idea from the C and so the Python guys.
[Answer]
# PHP 5.4+, 96 bytes
Yes, it's a fat boy :(
But was fun to write it!
```
foreach([Accra,Lagos,Cairo,Doha,Dubai]as$k=>$v)echo"\n$v ",date(H_i,strtotime("$argn {$k}hour"));
```
Run this with `php -r` (produces warnings).
The input format is flexible, as long as it can be interpreted by [`strtotime()`](https://www.php.net/manual/en/function.strtotime.php).
You can input hours in 12-hour or 24-hour formats, being displayed in 24-hour format.
The cities chosen were picked because they are NOT in DST at the time of this answer:
[](https://i.stack.imgur.com/Aegch.png)
[Answer]
# [JavaScript (V8)](https://v8.dev/), 81 bytes
```
(h,m)=>'Accra-Lagos-Rome-Kyiv-Dubai'.split`-`.map(e=>console.log(e,h++%24+':'+m))
```
[Try it online!](https://tio.run/##BcHRCoMgFADQrxkqeiVqD2NgMNjbeuoLuhMrh@5KltDX2zk/LJjt5tMO5VFnU/mqojA9e1m7IQy4UIaRooPP6Qu8jy96pnMKfp9g0hETd6a39M8UnA60cKdWKW/tXbInk1GIOvO2U10j6gU "JavaScript (V8) – Try It Online")
[Answer]
# JavaScript, 65 bytes
Input `f(h)(m)`. Outputs an array of arrays: `[[City, mm, ss], ...]`.
```
h=>m=>`Accra
Lagos
Rome
Kyiv
Dubai`.split`
`.map(c=>[c,h++%24,m])
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNEts/ifZvs/w9Yu19YuwTE5uSiRyycxPb@YKyg/N5XLuzKzjMulNCkxM0GvuCAnsySBK0EvN7FAI9nWLjpZJ0NbW9XIRCc3VvN/cn5ecX5Oql5OfroGF2eahpGxpoaxgSaX5n8A)
---
# JavaScript, 66 bytes
Prettier. Outputs a string with `City,mm,ss` separated by newlines.
```
h=>m=>`Accra
Lagos
Rome
Kyiv
Dubai`.replace(/.+/g,M=>[M,h++%24,m])
```
[Try it online!](https://tio.run/##BcFBC8IgFADgc@9/BIrmYuvQRSHoVrt0jWAvcc7Q3tAS@vX2fS@sWGwO62dXj23WbdEmaTOdrM0IV/RU4EbJweUXKpy/TwyTym6NaB3rlOh8kqM291EuQmz7g0wP3iy9C0WnInkGm5n1A2fDngNvfw)
---
# JavaScript, 64 bytes
Uglier. Outputs a string without delimiters: `Citymm,ssCitymm,ss...`.
```
h=>m=>`Accra Lagos Rome Kyiv Dubai `.replace(/ /g,_=>[h++%24,m])
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNEts/ifZvs/w9Yu19YuwTE5uShRwScxPb9YISg/N1XBuzKzTMGlNCkxUyFBryi1ICcxOVVDX0E/XSfe1i46Q1tb1chEJzdW839yfl5xfk6qXk5@ugYXZ5qGkbGmhrGBJpfmfwA)
[Answer]
# [W](https://github.com/A-ee/w), 33 [bytes](https://github.com/A-ee/w/wiki/Code-Page)
Just realized that my language is such a bad language. It doesn't even support dumping the stack...
```
☻|▓■°u:"≡∟◘Σ≡☺╖ⁿ╩]┼ε╝╣╗à_∙▬Cô\K←û
```
Uncompressed:
```
"3@374Ry<+o;<r>YwI+eA78P`5a(c0[+24mc1[{M
```
## Explanation
```
"3@374Ry<+o;<r>YwI+eA78P` % Compressed string containing the cities
5 M % In the range 1..5:
a % The current counter,
( % Decremented,
c0[+ % Is added to the hours
24m % And modulo'd by 24
c1[ % Push the minutes
{ % Pair the two items
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 119 bytes
Input: `hh:mm`
Output: `h:mm`
```
t=>String.Concat("Accra,Lagos,Rome,Kyiv,Dubai".Split(',').Select((c,i)=>c+$":{(int.Parse(t[0..2])+i)%24}:{t[3..5]}\n"))
```
[Try it online!](https://tio.run/##JY7BSsNAFEXXzlc8B6Xv0XEYEguamIAobuxCmoWL2sU4TuuDOJHMVJGQb0@x3dzDOavr4pWLPD3tg7uLqeewU3BiDVuoplTVzVH1QxecTSjvneutWtpdF9Wq@/Lq@Y9/1OP@3bLUzXfLCWdqRrrxrXcJ0SmmqnbzC1kMyCHpF9tHj2lttM42NGe6zK7HYkjrXOvFZnwLkmgqhTjdgFiK309uPSBGqGDl7ceSg0ciOK9ASoJBnL32nPwxbzESlWKcjClyI8zN/2Z5sbgVBw "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 548 bytes
Golfed vesrion, [try it online!](https://tio.run/##bVBRS8MwGPwrn6VbUoxs7SZoQ4X6bEXwSRiO0qU22qa1SRlj1r9ek2zaDXxJvgt3912uYW15PQydZCBVyzNFzbhNW8HFm6TVDiaKV2xd57lkSkIEGMWqYEIiiO5gQdA94@@aa@ENQQ@12NTCIp@gR7aFl7r9sPhqSdAzq7vSolvPuLtcNJ3StsgPwsUc4gSZZ@wWddcScCsuOsX0kFZN5Wner@AbZq94tdn7JOi90Ez6BhwnX0@J584oz7WJEQH7BPSUIJhOwbrCRQR@4MH@gC4Noj2wUp5r4lNNdKaJYE57003G1W5tCpJ0W/CSAbbhzbPOfCjNpGZpVpw3qb3M98s6S8v10RQfE43KCQRL6o5b9nbuNVc2LRcqx85kHmxCczjk1O6vO4/2/0QzbmOwcYGOZY3BsczwwFwJh/bD8AM)
```
use strict;use warnings;my %time_offsets = ('Athens' => 3,'Beijing' => 8,'London' => 1,'New York' => -4,'Seoul' => 9);my $input = '12:30 AM';my ($hour, $minute, $ampm) = $input =~ /^(\d{1,2}):(\d{2}) (AM|PM)$/;if ($ampm eq 'PM' && $hour != 12) {$hour += 12;} elsif ($ampm eq 'AM' && $hour == 12) {$hour = 0;}my %city_times;while (my ($city, $offset) = each %time_offsets) {my $local_hour = ($hour + $offset) % 24;$city_times{$city} = sprintf("%02d:%02d", $local_hour, $minute);}while (my ($city, $time) = each %city_times) {print "$city: $time\n";}
```
Ungolfed vesrion
```
use strict;
use warnings;
my %time_offsets = (
'Athens' => 3,
'Beijing' => 8,
'London' => 1,
'New York' => -4,
'Seoul' => 9,
);
my $input = '12:30 AM'; # Replace with input from user
# Extract hour, minute, and AM/PM from input
my ($hour, $minute, $ampm) = $input =~ /^(\d{1,2}):(\d{2}) (AM|PM)$/;
# Convert 12-hour time to 24-hour time
if ($ampm eq 'PM' && $hour != 12) {
$hour += 12;
} elsif ($ampm eq 'AM' && $hour == 12) {
$hour = 0;
}
# Calculate time in each city
my %city_times;
while (my ($city, $offset) = each %time_offsets) {
my $local_hour = ($hour + $offset) % 24;
$city_times{$city} = sprintf("%02d:%02d", $local_hour, $minute);
}
# Output city times
while (my ($city, $time) = each %city_times) {
print "$city: $time\n";
}
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 123 bytes
Input can be in 12 or 24 hour format `i.e. hh:mm OR hh:mm AM/PM`
```
param($i)0..4|%{"{0}: {1}"-f("Accra","Lagos","Cairo","Amman","Dubai")[$_],([datetime]$i).AddHours($_).ToString("hh:mm tt")}
```
[Try it online!](https://tio.run/##DczBCsIgGADgVxk/CxSWuOi0m9ShQ53qNsb422wKcw7n6GA@u3n6bt9qv9JtSs5zSis6NKTUlDN2/h0CBB6bItQRjh8CYhgcQgV3nOyWvaB2NiuMwSV73d@ogbZl31WkHdFLr43scsfEON7s7jZS9pS97NM7vUwElGqMKbwHGlNKNW9OvBCPPw "PowerShell – Try It Online")
] |
[Question]
[
Given list of integers `{0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4}`.
For those who interested these numbers are used in weekday calculation.
Weekday = `(m[n] + d + y + y>>2 + y/400 - y/100) % 7;`, where `m[n]` - expression I'm searching, `d` - day of month, `y` - `year - (month <= 2)`.
Construct expression consisting of arithmetic, logic and bitwise operators, which will output for positive integer `n` integer `m` so that `m % 7` equals n-th number in the list.
Branches, ternary operators, table lookups and pointers are not allowed.
**Score:**
1 - for `| & ^ ~ >> <<` operators
1.1 - for `+ - < > <= >= == != ! && ||` operators
1.2 - for `*` operator
1.4 - for `/ %` operators
Answer with lowest score wins.
Personally I have found:
>
> `(41*n)>>4+((n+61)>>4)<<2` with score 6.4.
> I thought this will be hard to find so provided own expression to start with.
>
>
>
[Answer]
# 2 2.2
I love arbitrary precision arithmetic.
```
0x4126030156610>>(n<<2)
```
Or, if you don't like hex,
```
1146104239711760>>(n<<2)
```
Test:
```
print([(0x4126030156610>>(n<<2))%7 for n in range(1,13)])
[0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4]
```
[Answer]
## 2.0
```
(127004 >> i) ^ 60233
```
or (score 2.2) :
```
(i * 3246) ^ 130159
```
All found with brute force :-)
[Answer]
## 35.3
I suspect this may be the least efficient method to create the list:
```
1.7801122128869781e+003 * n -
1.7215267321373362e+003 * n ^ 2 +
8.3107487075415247e+002 * n ^ 3 -
2.0576746235987866e+002 * n ^ 4 +
1.7702949291688071e+001 * n ^ 5 +
3.7551387326116981e+000 * n ^ 6 -
1.3296432299817251e+000 * n ^ 7 +
1.8138635864087030e-001 * n ^ 8 -
1.3366764519057219e-002 * n ^ 9 +
5.2402527302299116e-004 * n ^ 10 -
8.5946393615396631e-006 * n ^ 11 -
7.0418841304671321e+002
```
I just calculated the polynomial regression. I'm tempted to see what other terrible method could be attempted.
Notably, I could save 3.3 points if the result was rounded. At this point, I don't think that matters.
[Answer]
## 3.2
Zero based solution:
```
7 & (37383146136 >> (i*3))
```
One based solution:
```
7 & (299065169088 >> (i*3))
```
I initially thought that the `%7` operation would be counted as well and `%` being an expensive operation here, I tried to solve it without it.
I came to a result of 3.2 like this:
```
// Construction of the number
// Use 3 bits per entry and shift to correct place
long c = 0;
int[] nums = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4};
for (int i = nums.Length - 1; i >= 0; i--)
{
c <<= 3;
c += nums[i];
}
// c = 37383146136
// Actual challenge
for (int i = 0; i < 13; i++)
{
Console.Write("{0} ",7 & 37383146136 >> i*3);
}
```
I'd be interested in optimizations using this approach (without `%`). Thanks.
[Answer]
# Python (3)
Since there are quite a few of these questions these days, I decided to make a program to automatically solve them in 3 (or 2) tokens. Here's the result for this challenge:
```
G:\Users\Synthetica\Anaconda\python.exe "C:/Users/Synthetica/PycharmProjects/PCCG/Atomic golfer.py"
Input sequence: 0 3 2 5 0 3 5 1 4 6 2 4
f = lambda n: (72997619651120 >> (n << 2)) & 15
f = lambda n: (0x426415305230L >> (n << 2)) & 15
f = lambda n: (0b10000100110010000010101001100000101001000110000 >> (n << 2)) & 15
Process finished with exit code 0
```
Proof that this works:
```
f = lambda n: (72997619651120 >> (n << 2)) & 15
for i in range(12):
print i, f(i)
0 0
1 3
2 2
3 5
4 0
5 3
6 5
7 1
8 4
9 6
10 2
11 4
```
] |
[Question]
[
Given string `s` of even length as input, randomly capitalize exactly half of the letters.
* You can assume the input will always be a non-zero, even length
* You can assume the input will consist of only lowercase letters (`[a-z]`)
* Exactly half of the letters should be capitalized in the output
* Every permutation that has exactly half of the characters capitalized should have an equal probability of being output
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so fewest bytes **in each language** wins!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes
### Code
Uses the [05AB1E codepage](https://github.com/Adriandmen/05AB1E/blob/master/docs/code-page.md).
```
ā.rÈÅÏu
```
[Try it online!](https://tio.run/##yy9OTMpM/f//SKNe0eGOw62H@0v//09MSk5JTUvPAAA "05AB1E – Try It Online")
### Explanation
```
# *example input: "**abcdefgh**"*
ā # Indices of the input -> ex. [1, 2, 3, 4, 5, 6, 7, 8]
.r # Randomly shuffle this list -> ex. [5, 4, 6, 3, 2, 8, 1, 7]
È # Map (x % 2 == 0) on each element -> ex. [0, 1, 1, 0, 1, 1, 0, 0]
ÅÏ # Apply the following on truthy indices:
u # Convert to uppercase -> ex. "aBCdEFgh"
```
[Answer]
# [R](https://www.r-project.org/), ~~52~~ ~~51~~ 33 bytes
Or **[R](https://www.r-project.org/)>=4.1, 25 bytes** by replacing the word `function` with `\`.
```
function(s)s-sample(seq(s))%%2*32
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jWLNYtzgxtyAnVaM4tRDI1VRVNdIyNvqfmVcSkh9akmahkaZRCqRC8j3zSjSUEpOUNDU1uciUTU5JTUvPAKv5DwA "R – Try It Online")
Inputs and outputs through vector of character codes.
Inspired by [@Adnan's solution](https://codegolf.stackexchange.com/a/237903/55372).
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~57~~ 56 bytes
```
i,r;f(*s,z){for(i=z;s[r=rand()%z]>96?s[r]-=32,i-=2:i;);}
```
[Try it online!](https://tio.run/##HcrRCsIgFADQ931FCINrKKwFQYn1A/3B2INsWhechgqBY99urtfDmfhklXuVgiwIA8fIMl2ND4AyizgEGZSbgbZ5vF8vjwojl@eeIZf9DQUVW1kUOqBrE/8z4aKho1Q06NIh6ZiGUT7JW1vrvz7YmYjGwO7s1NX1CfUZIK2NhO1cbSs/ "C (clang) – Try It Online")
* takes a pointer to a widechar string and modifies it.
[Answer]
# [Python](https://www.python.org), 86 bytes
```
lambda s:bytes(map(int.__xor__,s,sample(len(s)//2*[0,32],len(s))))
from random import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LYxLCsIwFEXnrqLg5KXEVOpEhG7DiUpImhcsNB-SFOxanBTE7sndGEjv5H64nPfq5_R0dvno7v6dkj6cf9dRGKlEFS9yThjBCA-DTYzzlwuc00ijMH5EGNFCJE3T1rcjPbUPWoasnQ7OVEFYlW0w3oVUb_S9DxkGOiP9lIAwtL1TCIQwhVsq12UVsleoS_sD)
Uses [Rɪᴋᴇʀ's idea](https://chat.stackexchange.com/transcript/message/59760574) to toggle case using `^32`, but taken a bit further.
-1 byte thanks to @ovs.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), 8 bytes
```
ŒuJḂẊTƲ¦
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700KzUnp3LBgqWlJWm6FuuPTir1erij6eGurpBjmw4tW1KclFwMlVsVrZSYlJySmqYUCxUBAA)
Using the mod-2 trick from [Adnan's 05AB1E answer](https://codegolf.stackexchange.com/a/237903/97857).
Explanation:
```
ŒuJḂẊTƲ¦
Œu TƲ¦ uppercase at truthy indices:
J range [1..length(input()]
Ḃ each modulo 2
Ẋ random permutation
```
`JḂ` essentially creates `[0, 1, 0, 1, ..., 0, 1]` up to the length of the input.
# [Jelly](https://github.com/DennisMitchell/jellylanguage), 9 bytes
```
ŒuJẊŒHḢƲ¦
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700KzUnp3LBgqWlJWm6FhuPTir1erir6-gkj4c7Fh3bdGjZkuKk5GKo7KpopcSk5JTUNKVYqAgA)
Explanation:
```
ŒuJẊŒHḢƲ¦
Œu Ʋ¦ uppercase at indices:
JẊ random permutation of [1..length(input)]
ŒH split that list into two halves
Ḣ take the first of those two halves
```
I think there ought to be a shorter way of doing the `JẊŒHḢ`, ~~perhaps by picking a random combination~~[nope](https://ato.pxeger.com/run?1=m700KzUnp3LBgqWlJWm6FuuPTir1Ojo52cdDJeLYpkPLlhQnJRdD5VZFKyUmJaekpinFQkUA). Or, at least, a shorter version of `ŒHḢ`.
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~14~~ 9 bytes
−5 bytes thanks to ovs.
Anonymous tacit prefix function
```
⌈@(2|≢?≢)
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1FPh4OGUc2jzkX2QKz5P@1R24RHvX2Pupof9a551Lvl0HrjR20TH/VNDQ5yBpIhHp7B/9PUM1JzcvLL84tyUtQB "APL (Dyalog Extended) – Try It Online")
`⌈` uppercase
`@(`…`)` at the positions indicated by the following mask:
`≢?≢` shuffle the indices 1 through the tally of elements in the argument (lit. take n random elements from 1…n, without replacement)
`2|` division remainders when divided by 2
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 76 bytes
```
f=s=>(S=Buffer(s).map(c=>c^=Math.random(n++)<.5?32:--n-n--,n=0),n?f(s):S)+''
```
[Try it online!](https://tio.run/##DcvBCoMwDADQf/FiQm0ZG7vIorD7Tt4HpbabQxNp1N/v5J3fzx9eQ57WzbKMsZRESh0M9NxTihkU3eJXCNSFN7389nXZ8ygLsDH4cPf@dm2t5ZNtmC7YcJ/O1A5o6roEYZU5ulk@kKDaeTpi1lghlj8 "JavaScript (Node.js) – Try It Online")
### Commented
```
f = s => // s = input string
( S = // S = output
Buffer(s) // turn s into a buffer
.map(c => // for each ASCII code c in s:
c ^= // update c:
Math.random(n++) // increment n
< .5 ? // with 1/2 probability:
32 // turn c into uppercase
: // or:
--n - n--, // leave c unchanged and decrement n twice
n = 0 // start with n = 0
), // end of map()
n ? f(s) // try again if we haven't capitalized exactly
// half of the letters
: S // otherwise, stop and return S
) //
+ '' // coerce the output buffer back to a string
```
[Answer]
# [J](http://jsoftware.com/), 21 bytes
```
toupper@{~`]`[}-:@#?#
```
[Try it online!](https://tio.run/##y/pvqWhlGGumaGWprs6lpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/S/JLCwpSixyq6xJiE6Jrda0clO2V/2typSZn5CukKagnJiWnpKalZ6iTJ/IfAA "J – Try It Online")
* `-:@#?#` Randomly "Deal" `?` half-the-length `-:@#` number of indices from all possible indices.
* `toupper@{~`]`[}` And Amend `}` just those indices with their uppercased versions `toupper@{~`.
[Answer]
# JavaScript (ES6), 154 bytes
*-1 thanks to emanresu A, with their `v<{}` trick*
```
s=>(t=(f=x=>x?f(x.slice(1)).flatMap(y=>[x[0]+y,x[0].toUpperCase()+y]):[""])(s).filter(w=>![...w].reduce((u,v)=>u+(v<{})*2-1,0)))[Math.random()*t.length|0]
```
**Explanation:**
* `(f=x=>x?f(x.slice(1)).flatMap(y=>[x[0]+y,x[0].toUpperCase()+y]):[""])(s)`: Recursively finds all ways to capitalize the string
* `.filter(w=>![...w].reduce((u,v)=>u+(v<{})*2-1,0))`: Filters out items which don't have the correct number of capitalized letters, by checking if the sum of `-1` (for capitalized) and `1` (for lowercase) is `0`
* `[Math.random()*t.length|0]`: Choose a random item
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), 8 bytes
```
JẊị"żŒu$
```
[Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCJK4bqK4buLXCLFvMWSdSQiLCIiLCIiLFsiaGVsbG93b3JsZCJdXQ==)
-2 bytes thanks to a clever trick from Adnan using cyclical indexing, thus tying pxeger's answer
```
JẊị"żŒu$ Main Link
J [1, 2, ..., len(input)]
Ẋ random permutation of that
ị" vectorize - index (half of them are even, half are odd, and it wraps)
żŒu$ the input zipped with itself capitalized
```
[Answer]
# [Factor](https://factorcode.org/) + `sequences.repeating`, ~~43~~ 39 bytes
```
[ "\0 "over length cycle randomize v- ]
```
[Try it online!](https://tio.run/##Rcw7CgIxFAXQflZxSe9grQsQGxuxUosYr0kwn5mXTEA3HxEE@8N5aFOz9NNxf9ht8KQkBhTOC5Nhgeh0zxFRVzc2fmmBz38wCifq6pPFdhiU0/G2iKUU1c9QlzVUbhQEJlsdzMsE/k7/JtoK1250CJjEp9o/ "Factor – Try It Online")
```
! "hamburgers"
"\0 " ! "hamburgers" "\0 "
over ! "hamburgers" "\0 " "hamburgers"
length ! "hamburgers" "\0 " 10
cycle ! "hamburgers" "\0 \0 \0 \0 \0 "
randomize ! "hamburgers" "\0\0\0 \0 \0"
v- ! "hamBURGeRs"
```
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~58~~ 51 bytes
-1 thanks to [AZTECCO](https://codegolf.stackexchange.com/questions/237895/randomly-capitalize-half-of-a-string/237931?noredirect=1#comment539485_237931)
-6 with wide string and clang
```
i;f(*s,l){for(i=l/2;rand()%l--<i?s[l]^=32,--i:i;);}
```
[Try it online!](https://tio.run/##TY1LjsIwEETX@BTGEsgmtiYEVjgWF@AGmYwUmQS15HSQnfmIiLOHJqtZdavqVZU3PjR4m2ewndwlHdTUDVGCCx@FjQ1epdoEY0o4pyrUX@5QaGPgBFbZ59w3gFJNDHDkgFXNHb@IxrfQ4xDT98/v30PYxQ0tcnL3R8tYWmpH6FuZK2VZJwH1m6D/HonupNiE9IlCw1tbCvxI8ZzgIXK57LnccigpRifLFFsRkjm@JreCenso/tddhfYjCc/5BQ "C (clang) – Try It Online")
Outputs by modifying the input string.
Each letter has a \$\frac in\$ chance of being capitalized, where \$i\$ is the number of remaining capital letters and \$n\$ is the number of remaining letters (including this one).
[Answer]
# [Julia 1.0](http://julialang.org/), 73 bytes
```
!s=(E=length(s);v=rand(E);prod(i->s[i]-32*(i∈sortperm(v)[1:E÷2]),1:E))
```
[Try it online!](https://tio.run/##RY5BDoIwFET3nKKw@t8AQnUlqTtOQdA0UrUGCukvxCNwIw/gTbwIQkh09SaZvMw8@lrL9DlNPgnIRa3Mzd2BMBuElaaCHLPOthXo6EiFLqMd34D@jCO11nXKNjBgkR7y94uXGM4BcXKK3PkiSRETrAhkcOIhW7BfkSYreVJ63rW1jJg27G95ndXG1Qaob0BT3807SxFD4VMcxyUiE4L9rm45espU0xc "Julia 1.0 – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 81 bytes
```
/^((?<-2>[a-z])|(?<-3>[A-Z])|([A-Z])|([a-z]))*(?(2)^)(?(3)^)$/^+/./_?(T`l`L
T`L`l
```
[Try it online!](https://tio.run/##K0otycxLNPyvquGe8F8/TkPD3kbXyC46UbcqVrMGxDG2i3bUjQJx4DRYUlNLw17DSDNOE0gZAykV/ThtfT39eHuNkIScBB@ukASfhJz//5MTCzJLEnMyi1O5ihLzUvJzcyoB "Retina – Try It Online") Explanation:
```
/^((?<-2>[a-z])|(?<-3>[A-Z])|([A-Z])|([a-z]))*(?(2)^)(?(3)^)$/
```
Check whether the input contains equal numbers of lower and upper case letters. Groups `2` and `3` contain any excess upper and lower case letters respectively; if they are non-empty then the letter of the opposite case decrements the group, otherwise the letter increments the group appropriately. At the end both groups are required to be empty.
```
^+
```
Repeat while it does not.
```
/./_
```
Loop over each letter.
```
?(
```
Random choice between one of the following.
```
T`l`L
```
Uppercase.
```
T`L`l
```
Lowercase.
[Answer]
# [Perl 5](https://www.perl.org/) `-F`, 49 bytes
```
@k{0..$#F}=1;map$_=uc,@F[(keys%k)[1..@F/2]];say@F
```
[Try it online!](https://tio.run/##K0gtyjH9/98hu9pAT09F2a3W1tA6N7FAJd62NFnHwS1aIzu1slg1WzPaUE/PwU3fKDbWujix0sHt///EpOSUf/kFJZn5ecX/dX1N9QwMDf7rugEA "Perl 5 – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 52 bytes
```
MapAt[Capitalize,#,RandomSample[i=0;{++i}&/@#,i/2]]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773zexwLEk2jmxILMkMSezKlVHWScoMS8lPzc4MbcgJzU609bAulpbO7NWTd9BWSdT3yg2Vu1/QFFmXomDVnAJkE73ys/MU3BId3DOSCxKTC5JLSqOVioCG1EMlleK/f8fAA "Wolfram Language (Mathematica) – Try It Online")
-16 bytes thanks to @att
[Answer]
# [Ruby](https://www.ruby-lang.org/), 59 bytes
```
->s{[*0...q=s.size].sample(q/2).map{|w|s[w]=s[w].upcase};s}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1664OlrLQE9Pr9C2WK84syo1Vq84MbcgJ1WjUN9IUy83saC6prymOLo81hZE6JUWJCcWp9ZaF9f@L1BIi1YqSS0uUYr9DwA "Ruby – Try It Online")
[Answer]
# [C#](https://docs.microsoft.com/en-us/dotnet/csharp/%3E!), 145 bytes
Hey! I'm completely new to this and my answer will make that apparent. I thought I'd post so that I can refer back to later to see my progress. Let me know if I anything is incorrect involving my answer.
didn't include logging, output is the t string
```
string t="";int p=0;while(p!=s.Length/2){t="";p=0;foreach(char c in s){char l=c;if(new Random().Next(2)==0){l=char.ToUpper(l);p++;}t=$"{t}{l}";}}
```
[Try it online!](https://tio.run/##VY7BSgMxGITP3af4DR4Sirul15CTLHiotrRZVMRDSNPdQDZZkmiVkGdf03rRuc3MNzAy3Enn1Tx/BG17OHyHqEZaSSNCgJ13vRcjpGoRoohawqfTR3gU2uIQfRm8vYPwfSAXBIp@UwjAAA3KGEShaXYdh9dttwfevnB4aPct8G0xB/5vFBlCVNsIE1vR86CNwtMNC/VG2T4OzZqkK3FpT@WykAOWg/AgQVsIJF2NYZLqE7bqDHthj27EpH5SXxGvCWMrkkpfsJq7bpqUx4bQabmkObJblGJOJiOacwV/dO9scEbVz15HtdFW4UhotchVnucf)
[Answer]
# [Python 2](https://docs.python.org/2/),127 119 bytes
Not super happy with this, I'll probably come back to it after class (or not, we'll see). Takes input from stdin using Python 2 `input()` rules - aka `"test"` rather than `test`.
Requires Python 2 for `range` returning a list, since that would require `*x,` instead of `x` otherwise, and would lose a byte on the print statement and I don't think you can gain more than 2 from inline variable assignments.
Using `chr`/`ord` is shorter than `[s[i],s[i].upper()][i in x[::2]]`, I think that's optimal as well.
Thanks to enzo for -8, from switching from using a while loop to just `str.join`.
```
from random import*
s=input()
n=len(s)
r=range(n)
x=sample(r,n)
print''.join(chr(ord(s[i])-32*(i in x[::2]))for i in r)
```
[Try it online!](https://tio.run/##HYpBCoMwEADveUXw4q60PaQ3IS8RD1Jj3WJ2wyaCfX0aehpmmPQtu7CrdVOJVhdeGygm0TKY7InTWQAN@yMwZDTq2/MOwGgun5eYjgB6a5aUuPT94yPE8NoVRFfIE814f7oByBLbaxpHNyNuovYfFGvtSsil@wE "Python 2 – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes
```
ẏṖ℅Ih⁽N¨M
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuo/huZbihIVJaOKBvU7CqE0iLCIiLCJzdHJpbmciXQ==)
Explanation:
```
ẏ # List of [0..len(input))
Ṗ℅ # Random permutation
Ih # First half of the list
⁽N¨M # Toggle case of the indexes in the list
```
There is actually a dedicated builtin for `Random Permutation`, which is faster, but there is a bug in it, so we have to get every permutation and choose a random one.
[Answer]
# [Python 3](https://docs.python.org/3/), 105 bytes
```
lambda s:''.join([x,x.upper()][y%2]for x,y in zip(s,sample([*range(len(s))],len(s))))
from random import*
```
[Try it online!](https://tio.run/##LYpBDsIgEADvvoKL6dKQHvRm4ktqDxjAYmB3s9BI/Tz24GkmmeG9roTXHu6Pnmx@OqvKbRimN0WEuZk2bcxeQC/zfr4sgUQ1s6uI6hsZiik2c/Iwj2Lx5SF5hKL1Yv6i9SkIZXVUdyBmJqljZ4lYIUBE3iocV199SvQhSa7/AA "Python 3 – Try It Online")
[Answer]
# Excel, 89 bytes
```
=LET(x,LEN(A1),y,RANDARRAY(x),CONCAT(CHAR(CODE(MID(A1,SEQUENCE(x),1))-(y>MEDIAN(y))*32)))
```
This breaks the string into an array of characters. Then generates an array of random numbers of the same length. For each number in the random array that is greater that the median of the array, the corresponding letter is changed to upper case (ASCII value reduced by 32). Then all of the characters are concatenated.
[Answer]
# [Perl 5](https://www.perl.org/) `-pF`, 43 bytes
1 byte saved thanks to [@Kjetil S](https://codegolf.stackexchange.com/users/64733/kjetil-s)!
```
$F[rand@F]&=_,$_=join"",@F
while@F/2>y;A-Z;
```
[Try it online!](https://tio.run/##K0gtyjH9/1/FLbooMS/FwS1WzTZeRyXeNis/M09JScfBjas8IzMn1cFN38iu0tpRN8r6///EpOSU1LT0jH/5BSWZ@XnF/3UL3AA "Perl 5 – Try It Online")
---
# [Perl 5](https://www.perl.org/) + `-pa`, 38 bytes
-5 bytes using a space separates string (Thanks [@Kjetil S](https://codegolf.stackexchange.com/users/64733/kjetil-s)!)
```
$F[rand@F]&=_,$_="@F"
while@F/2>y;A-Z;
```
[Try it online!](https://tio.run/##K0gtyjH9/1/FLbooMS/FwS1WzTZeRyXeVsnBTYmrPCMzJ9XBTd/IrtLaUTfK@v//RIUkhWSFFIVUhTSFdIWMf/kFJZn5ecX/dQsSAQ "Perl 5 – Try It Online")
[Answer]
# [ayr](https://github.com/ZippyMagician/ayr), 13 bytes
```
(];-){:2|#?.#
```
[Try it!](https://zippymagician.github.io/ayr#Zjo@/KF07LSl7OjJ8Iz8uIw@@/Oz5mIjEwJEAuMCBfMV0nYWJjZGVmZ2gn//)
# Explained
```
#?.# Roll N-sided die N times, where N is len of y
2| Convert this to a length-N boolean vector (half 1s, half 0s)
{: Use this to catalogue..
];- A matrix of the string and the string with inverted caps
```
[Answer]
# [Raku](http://raku.org/), 41 bytes
```
{[~] {@_[pick @_/2,^@_]».=uc;@_}(.comb)}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/OrouVqHaIT66IDM5W8EhXt9IJ84hPvbQbj3b0mRrh/haDb3k/Nwkzdr/xYmVCmka6mn5@UmJReqaCmn5RQpxhgb/AQ "Perl 6 – Try It Online")
* `.comb` splits the input string into a list of characters, which is then fed to the brace-delimited anonymous function, which takes the list in the `@_` array. This is just a short way to get an array with writeable elements without having to declare one explicitly.
* `pick @_ / 2, ^@_` randomly selects half of the indices in the character array.
* `@_[...]».=uc` slices into the array of characters with the random selection of indices, and uppercases the characters at those indices. The original array is then returned.
* `[~]` concatenates the characters into a single string.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes
```
W⁻⊗LΦKA№ακLθP⭆θ‽⁺κ↥κ
```
[Try it online!](https://tio.run/##LY1BCsIwEEWvMsspxBO4EsWVgaL0AGM6tEPGJE0TPX4M4t88Pjz@dytlF0lb@6yiDGgl1B0vsT6VZ7xxWMqKV9HCGUdmf1LFwcA51lCQDPihx8Bf3HoBW7VIytKFR@lYLCXcDNwpzPGFo/YDb2BKibOjnfG3MRxbc5SkkMrO7fDWLw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
W⁻⊗LΦKA№ακLθ
```
Repeat until uppercase letters make up exactly half of the canvas...
```
P⭆θ‽⁺κ↥κ
```
... output the input string but randomly uppercase each letter.
[Answer]
# APL+WIN, 37 bytes
Prompts for string
```
s[i]←s[i←(.5×⍴s)?⍴s←⎕av⍳⎕]+48⋄⎕av[s]
```
[Try it online!Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3tf3F0ZiyQB6SApIae6eHpj3q3FGvag0igCFB1Ytmj3s1AOlbbxOJRdwtYJLo4lus/UD/X/zQu9cSk5JTUNHUA "APL (Dyalog Classic) – Try It Online")
[Answer]
# Python 3, 124 bytes:
```
import random as r
j=range
f=lambda s:(lambda v:''.join(chr(ord(s[i])-32*(i in v))for i in j(l)))(r.sample(j(l:=len(s)),l//2))
```
[Answer]
`(new Array(s.length)).fill(0).map((i,j)=> j % 2).sort(() => Math.random() - 0.5).map((i, j) => (i ? s[j].toUpperCase() : s[j])).join("")`
[Answer]
# [Ly](https://github.com/LyricLy/Ly), 44 bytes
```
irysp>l[0f1f,,]p<[>sprl0y?[,sprl]psp<l' *-o]
```
[Try it online!](https://tio.run/##y6n8/z@zqLK4wC4n2iDNME1HJ7bAJtquuKAox6DSPloHxIgtKC6wyVFX0NLNj/3/vzg/N7UkIzMvPbM4I7GgIDUPyAQA "Ly – Try It Online")
This one works by generating a list of `0 1` pairs on a list the size of the input string. Then for each input character it reverses the list of `0 1` pairs a random number of times, then pops the top off the resulting stack. That value is used to decide whether or not to capitalize the character before printing it out.
1. Prep the input strings
```
ir - read input codepoints into the stack, reverse the stack
ysp - save the number of char, delete that from the stack
> - switch to an empty stack
```
2. Generate a list of `0 1` pairs
```
l[0f1f,,]p
l[ ,,]p - loop "n/2" times adding "0,1" pairs to the stack
0f - add a "0" to the stack, pull the iterating var forward
1f - add a "1" to the stack and pull the iterator forward again
```
3. Process each of the input chars on the input stack
```
<[ ] - loop until the input stack is empty
*3.1* - get a random 0/1 from the boolean stack
<l - back to input stack, load boolean 0/1 capitalization choice
' * - multiple " " by the boolean
- - subtract to capitalize (of boolean was true)
o - print the current input char
```
3.1 Pull a random boolean off the list
```
> - switch to the boolean stack
sprl - disrupt pattern on list, move top entry to the bottom
0y? - pick a random number between 0 and the stack size
[,sp l]p - loop that number of time, using backup cell for iterator val
r - reverse the stack
sp - save the random boolean to the backup cell
```
] |
[Question]
[
#### Task
[FizzBuzz](https://codegolf.stackexchange.com/questions/58615/1-2-fizz-4-buzz), but instead of 3 and 5, you'll take the numbers and corresponding strings as input.
You can assume all inputted numbers are coprime (and \$\ge 2\$). You'll receive one or more numbers, and a string to print with each of them. The normal FizzBuzz would be something like `[[3, "Fizz"], [5, "Buzz"]]`, but you could also receive something like `[[2, "Quux"]]` or `[[2, "a"], [5, "b"], [7, "c"], [33, "d"], [529, "e"]]`.
For output, you'll have two options:
* Print this modified FizzBuzz infinitely
* Take a number as input, and return the first \$n\$ lines
You *must* return output with newline separators. An array of lines is not acceptable.
#### Details
To clarify exactly what this should look like, this is the process to determine what the \$n\$th line should look like (first line is always \$1\$):
1. For each of the inputted numbers \$n\$ is divisble by, append the corresponding string to the output (for example, \$15\$ would result in `"Fizz" + "Buzz" = "FizzBuzz"` for normal FizzBuzz)
2. If \$n\$ is not divisble by any of the numbers (i.e., the line is still empty), default to \$n\$
For example, the first 100 lines of the sample input `[[4, "Foo"], [7, "Bar"], [9, "Baz"]]` are:
```
1
2
3
Foo
5
6
Bar
Foo
Baz
10
11
Foo
13
Bar
15
Foo
17
Baz
19
Foo
Bar
22
23
Foo
25
26
Baz
FooBar
29
30
31
Foo
33
34
Bar
FooBaz
37
38
39
Foo
41
Bar
43
Foo
Baz
46
47
Foo
Bar
50
51
Foo
53
Baz
55
FooBar
57
58
59
Foo
61
62
BarBaz
Foo
65
66
67
Foo
69
Bar
71
FooBaz
73
74
75
Foo
Bar
78
79
Foo
Baz
82
83
FooBar
85
86
87
Foo
89
Baz
Bar
Foo
93
94
95
Foo
97
Bar
Baz
Foo
```
#### I/O
You can take input in any reasonable format. This includes dicts of numbers and their strings, a single list of pairs (like in the examples), two lists (one with numbers and ones with pairs), or similar.
For instances where there's two strings being appended, such as `FooBar` in the example above, any order is acceptable (`BarFoo` is also fine).
#### Other
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes (per language) wins!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
⁴ḍTị⁵ȯ)Y
```
[Try it online!](https://tio.run/##y0rNyan8//9R45aHO3pDHu7uftS49cR6zcj///8bGvyPNtYx1THXMTTUMTSO/R@t5JZZVaWko@RUCqbc8vNBnMQiMFmlFAsA "Jelly – Try It Online")
Full program that takes \$n\$, the list of numbers \$L\$ and the list of strings \$S\$ as command line argument, and returns a newline separated string
## How it works
```
⁴ḍTị⁵ȯ)Y - Main link. Takes n on the left, L as ⁴ and S as ⁵
) - Over each integer 1 ≤ i ≤ n:
⁴ḍ - Map each element in L to 1 if i is divisible by it, else 0
T - Indices of 1s
ị⁵ - Select the elements of S at those indices
ȯ - If this is the empty list, replace it with i
Y - Join on newlines
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 29 bytes
```
{{$[a:&~x!'y;,/a;y]}[x]'1+!y}
```
[Try it online!](https://ngn.bitbucket.io/k#eJxLs6quVolOtFKrq1BUr7TW0U+0roytja6IVTfUVqys5eJKi9ZQcsusqlKyVnIqBVKaisYKptaGprEQmfx8kERiEZgEyZoomCtYWhsaGMRycQEA7pwYsQ==)
Takes a dict with (string, number) pairs.
## Explanation
```
{{$[a:&~x!'y;,/a;y]}[x]'1+!y}
1+!y range 1..y
' for each number
[x] with x as constant first argument:
{$[ ]} if:
x!'y the values of x mod y
~ logical NOTed
& filter out keys which have truthy values
a: store in a
;,/a return a if non-empty
;y otherwise return number y
```
[Answer]
# [Haskell](https://www.haskell.org/), 69 bytes
```
[]%n=show n
x%_=x>>=id
f a=unlines[[y|(x,y)<-a,mod i x<1]%i|i<-[1..]]
```
[Try it online!](https://tio.run/##LcfBCoMgGADge0/xExMSLBZjByE77LAX2FFkCBn9ZDpmMYve3TXY7fsGHUZjbUpSESfC4D/gskieIratwC7rQYvFWXQmSLnuRWQrbUrNJt8BQmxqRXDHppR1VSmVJo0OBLyW@TG/4QSzHg1wzg/2IIsLg/yO25ZTBsX1yG35pz7/5v2UU5W@ "Haskell – Try It Online")
`f [(3, "Fizz"), (5, "Buzz"), (10, "Boom")]` is an infinite string with newlines in it.
[Answer]
# [JavaScript (V8)](https://v8.dev/), 59 bytes
Prints the sequence forever.
```
a=>{for(k=0;++k;)print(a.map(([m,s])=>k%m?'':s).join``||k)}
```
[Try it online!](https://tio.run/##HcbdCsIgGADQVxlCzI@ZdBH0M1zQRS8hwmRkOKef6NhFrWe32Lk6o150HpKN8345FyOKFt3HYKJOHNqmcS3EZMNMNfc6Uio9ywpE53b@VtfXDHxEG/p@XR18y4Ah4/TkE76ooVIeWUUeiESxSp7@v@u0/bL9TZQCKD8 "JavaScript (V8) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes
```
ƛ¹Ḋ⁰*∑∴,
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%C6%9B%C2%B9%E1%B8%8A%E2%81%B0*%E2%88%91%E2%88%B4%2C&inputs=100%0A%5B3%2C%205%2C%207%5D%0A%5B%22Fizz%22%2C%20%22Buzz%22%2C%20%22Joe%22%5D&header=&footer=)
Since y'all complaining about flags, I'll give you a tie with jelly.
Expects `L`imit, `D`ivisors, `S`trings
## Explained
```
ƛ¹Ḋ⁰*∑∴,
ƛ # for each n in the range [1, L]:
¹Ḋ # Push n % D == 0 (epicly vectorised)
⁰* # Push ^ * S (which is vectorised python string multiplication)
∑∴ # Push max(sum(^), n)
, # and print ^ with a newline
```
This would be 7 with the `j` flag
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 14 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
õ@VËÌpXvDÎìªX
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=9UBWy8xwWHZEzsOsqlg&input=MTAwCltbNCwgIkZvbyJdLCBbNywgIkJhciJdLCBbOSwgIkJheiJdXQ)
```
õ@VËÌpXvDÎìªX :Implicit input of integer U & array V
õ :Range [1,U]
@ :Map each X
VË : Map each D in V
Ì : Last element
p : Repeat
Xv : Is X divisible by
DÎ : First element of D
à : End map
¬ : Join
ªX : Logical OR with X
:Implicit output joined with newlines
```
[Answer]
# [Perl 5](https://www.perl.org/), 56 bytes
```
sub{say join('',map$.%$$\_[0]?'':$$_[1],@_)||$.while++$.}
```
[Try it online!](https://tio.run/##K0gtyjH9r5Jm@7@4NKm6OLFSISs/M09DXV0nN7FARU9VRSU@2iDWXl3dCsQyjNVxiNesqVHRK8/IzEnV1lbRq/1vzaWmkqYRbayj7pZZVaUeqxNtqqPuVApialr//5dfUJKZn1f8X9e3zFTP0AAA "Perl 5 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes
```
Eθ∨⭆η⎇﹪⊕ι§λ⁰ω§λ¹I⊕ι
```
[Try it online!](https://tio.run/##XYu9CsIwFEZf5ZLpBiK0IIg4qSB0KAq6hQwhCbaQJnqNvy8f0276Tecc@EynyUTtcz5QHxK2@oJXAXvCYyrhPHon4OQoaHpjG@3dR2yCITe4kJzFngtYpyZY90IvoCr6/Ck156Vt9S39/catcpZ1VQmQci6A7WJkqsii8EbTxMuJP0wplWcP/wU "Charcoal – Try It Online") Link is to verbose version of code. Prints the first `n` terms. Explanation:
```
θ Input `n`
E Map over implicit range
η Input list of pairs
⭆ Map over pairs and join
ι Outer index
⊕ Incremented
﹪ Modulo
§λ⁰ First element of pair
⎇ If non-zero then
ω Empty string
§λ¹ Else second element of pair
∨ Logical Or
ι Current index
⊕ Incremented
I Cast to string
Implicitly print on separate lines
```
Note: Using trunk Charcoal (not available on TIO) this would be only 15 bytes:
```
Eθ∨⭆η⎇﹪⊕ιμωλI⊕ι
```
Explanation: Takes the input as a dict, which means that iterating over it populates the loop variables directly without having to index into the pairs.
[Answer]
# [R](https://www.r-project.org/), ~~76~~ 64 bytes
*-12 bytes thanks to [@Dominic](https://codegolf.stackexchange.com/users/95126/dominic-van-essen)*
```
function(N,S)repeat{F=F+1;cat(F[all(k<-F%%N)],S[!k],"
",sep="")}
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0/DTydYsyi1IDWxpNrN1k3b0Do5sUTDLToxJ0cj20bXTVXVTzNWJzhaMTtWR4lLSac4tcBWSUmz9n@aRrKGiY65jqWmTrKGklt@vpKOklNiEZisUtLU/A8A "R – Try It Online")
Takes vectors of `N`umbers and corresponding `S`trings.
Outputs infinitely.
[Answer]
# Python 2, 63 bytes
```
def f(k,i=1):
print''.join(y*(i%x<1)for x,y in k)or i;f(k,i+1)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728oLIkIz_PaMGCpaUlaboWN-1TUtMU0jSydTJtDTWtuBQKijLzStTV9bLyM_M0KrU0MlUrbAw10_KLFCp0KhUy8xSyNYHsTGuwFm1DTYgxq9I0MvMKSks0NKECC26aRkcb6SgoJSrF6ihEmwJZSWCWOZCVDGYZGwOZKRBpI0sgO1UpNhaiGwA)
-1 bytes thanks to @dingledooper
-3 bytes thanks to @pxeger
[Answer]
# [Java (JDK)](http://jdk.java.net/), 109 bytes
```
l->{for(int i=1;;i++){var s="";for(var e:l)if(i%e.getKey()<1)s+=e.getValue();System.out.println(s==""?i:s);}}
```
[Try it online!](https://tio.run/##ZY9BS8NAEIXv@RVDQNi17UJBELtJBEVBtKeCl@JhTTdh4mY37E4CteS3xyQVLHh833vzZqZSnVpVh68B68Z5gmrUoiU04lpG/1jR2pzQ2QszkCLMLzJb1QhtyR9llBsVAmwVWjhFAE37acbo70Tn8AD16LEdebTl/gOULwOfowCPzoa21j55w0DJVPo0lSYvlnSp/fI8lGUZFOlgVtmpcJ6hJcB0LSUuFvzUKQ8hjWM5WZPQG8OxYHilRanpVR8ZT9Y8LNJZvyvTasbl7hhI18K1JJpxBxnLQjrW3OMmcNn3g5wPLITKc90Qmw4UrmDz0@xmCfGzczFfwhncjuBB@T9wN4PvmHM@NfVRP/wA "Java (JDK) – Try It Online")
## Notes
The `s==""` works here because of the constants pool: the two references to the empty string are actually one reference and have the same address in memory. `s==new String("")` wouldn't have worked for instance.
## Credits
* 3 bytes saved thanks to [AZTECCO](https://codegolf.stackexchange.com/users/84844/aztecco)
[Answer]
# [Julia 0.7](http://julialang.org/), 59 bytes
```
N\d=1:N.|>n->println((a=prod(p->p[2]^(n%p[1]<1),d))>""?a:n)
```
[Try it online!](https://tio.run/##yyrNyUw0///fLybF1tDKT6/GLk/XrqAoM68kJ09DI9G2oCg/RaMAKBRtFBunkadaEG0Ya2OoqZOiqWmnpGSfaJWn@V/DRMtcy1LbUFMhRiHaxNZOyS0/X0nHHMhwSixS0rEEM6qUYv8DAA "Julia 0.7 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 65 bytes
```
f=lambda a,n=1:print(''.join(j*(n%i<1)for i,j in a)or n)+f(a,n+1)
```
[Try it online!](https://tio.run/##HcvBCsIwDADQXwkFWeKKUBTE4S4e/InSQ0SKKZqMsov@fC27vctbvuvL9Nhant/8eTwZ2OscpqWKrjgMh2KiWPaoO7kGylZBfAFRYOpWGjP2MQZqGWM8eXB3M5c8xHP3jevmy@afS4naHw "Python 3 – Try It Online")
-1 byte thanks to MarcMush
[Answer]
# [J](http://jsoftware.com/), 48 bytes
```
1 :'(|:@([:(,0=+/)0=u|/]);@#"1(,"#:<@":"+))1+i.'
```
[Try it online!](https://tio.run/##VcsxC8IwEAXgvb/iTMHL0ZgmllK8WgkVnMTBtUQRsahLQXCR4l@PbTeH9@Dx@J5hNeOsAA8GzmMiobGFigFBDZuHLDRsj/tdsMAoe3ayYalMlaRkqnefeipdLKxUIua1EywSIps8NAaKDrWGiW3Y@eYferpd750bsFSjIzqxtDnNLUbjA8vcgMwghwJa@gLuug5LrC@vqT8Yfg "J – Try It Online")
This was bizarrely difficult to golf in J.
[Answer]
# [Bash](https://www.gnu.org/software/bash/), ~~100~~ ~~80~~ 75 bytes
*-20 bytes thanks to [@Dude coinheringaahing](https://codegolf.stackexchange.com/users/66833/dude-coinheringaahing)*
*-5 bytes and extra readability thanks to [@Jonah](https://codegolf.stackexchange.com/users/15469/jonah)*
```
for((i=1;;i++));{
o=
for a;{((0==i%${a% *}))&&o=$o${a#* };}
echo ${o:-$i}
}
```
[Try it online!](https://tio.run/##DchBCoQwDEDRfU8RmCqtIuiMbibkMK1MMauA4saSs2e6@ryf03WYFTlDYFoQeRxjxOqEXJuQsIYwE3Hna@pg0Bj7XshL42sARXW//RDwVb6TZ3VqZh8o/Dy2Qb5blhmKiK1vyOn8Aw "Bash – Try It Online")
Takes arguments as strings in the form '$num $str' and uses variable expansion to split them out into their component parts. Outputs infinitely.
I'm pretty sure this one has lots of potential for further golfing, but I'll take an even 100 for my first submission.
[Answer]
# [Scala](http://www.scala-lang.org/), 94 bytes
```
b=>1 to _ map(x=>println(Seq(b.collect{case(k,s)if x%k<1=>s},Seq(x))maxBy(_.size)mkString ""))
```
[Try it online!](https://tio.run/##LY5NCwIhFEX38yseA4GCDQ0EUaTQLIIWraJVRDiTEzaOWkpY0W83@1jd87gH7nMNVzya@iwaD2suNYjghT46WFgLz@zGFbSz1NjdSnsCG3@V@rQHyiDdn9hqmTLWlJXgDRyg5xYFymwSvdJoIy6oLhqjVJp4NtwJ1BGHZQth0M1LytyLfJyAcc9DdUeHwsmHwH3324I8xzhmLUo/oDEMGeRLY3ICky9X/Jp4@udHclE5GuHsFd8 "Scala – Try It Online")
Outputs the first n lines of the sequence.
```
b => //A Map with the keys being divisors (4, 7, 9) and the values being strings ("Foo", "Fizz", etc.)
1 to _ //Make a range to n
map(x=> //For each x in the range, output either "x" or a string made from its divisors
println( //Print with newline
Seq( //Make a Seq with the two alternatives ^
b.collect{ //The Fizz, Buzz, FizzBuzz alternative
case(k,s) //For every divisor k and its accompanying string s,
if x%k<1 //If k divides x
=>s}, //Add s to this alternative
Seq(x) //The second alternative is just the number itself
) maxBy(_.size) //Find the alternative with more elements (if both have 1, the first is chosen)
mkString "" //Join into a single string
)
)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
∞ε¹ÖÏJy‚õKн,
```
Integers and strings as two separated input-lists.
Outputs the infinite sequence.
[Try it online.](https://tio.run/##yy9OTMpM/f//Uce8c1sP7Tw87XC/V@WjhlmHt3pf2Kvz/3@0iY65jmUsV7SSW36@ko6SU2IRmKxSiv2vq5uXr5uTWFUJAA)
**Explanation:**
```
∞ # Push an infinite positive list: [1,2,3,...]
ε # Foreach `y` over these integers:
¹Ö # Check for each integer in the first input-list whether it divides the
# current integer
Ï # Get the strings of the second (implicit) input-list at the truthy indices
J # Join this list of strings (it's now "" if none were divisible)
y‚ # Pair it with the current integer `y`
õK # Remove empty strings from this pair
н # Pop and leave the first item
, # And print it with trailing newline
```
[Answer]
# [CSASM v2.5.1](https://github.com/absoluteAquarian/CSASM/releases/tag/v2.5.1), 317 bytes
```
func a:
.local a : i32
push 1
add
pop $3
pop $2
dup
len
pop $4
pop $1
lda 1
.lbl a
push 0
pop a
push -1
pop $5
push $a
push 1
sub
brfalse c
.lbl b
inc $5
push $5
push $4
sub
brfalse c
push $a
push $1
ldelem $5
rem
brtrue b
push 1
pop a
push $2
ldelem $5
print
br b
.lbl c
push a
brtrue d
push $a
print
.lbl d
push '\n'
print
inc $a
push $a
push $3
sub
brtrue a
ret
end
```
A function named `a` which expects an `~arr:i32` for the values, an `~arr:str` for the names and an `i32` representing \$n\$ on the stack, pushed in that order specifically.
**Explanation:**
```
func a:
; Used as the flag for if a string was printed
.local a : i32
; stack: [ values array, strings array, amount to print ]
push 1
add
pop $3
pop $2
; Duplicate "values array", get its length and store it into $4
dup
len
pop $4
pop $1
; $1 = values, $2 = strings, $3 = final number
; Initialize $a to 1
lda 1
.lbl a
; Reset the "string printed" flag
push 0
pop a
; Reset the "numbers array" iteration
push -1
pop $5
; If $a == 1, skip to the end
push $a
push 1
sub
brfalse c
.lbl b
inc $5
push $5
push $4
sub
brfalse c
; Loop through each value in the numbers array and check if a$ % them is zero
; If they are, print that string
push $a
push $1
ldelem $5
rem
brtrue b
; Modulo was zero
push 1
pop a
push $2
ldelem $5
print
br b
.lbl c
push a
brtrue d
; Print the current number
push $a
print
.lbl d
; Print the newline
push '\n'
print
; Loop while $a != $3
inc $a
push $a
push $3
sub
brtrue a
ret
end
```
---
**Sample Program:**
```
func main:
push $i32:[3,5]
push 2
newarr str
pop $a
push $a
push "Fizz"
stelem 0
push $a
push "Buzz"
stelem 1
push $a
push 30
call a
ret
end
; "func a" would be defined here
```
[Answer]
# [Python 3](https://docs.python.org/3/), 122 bytes
```
exec("g="+input())
n=1
while 1:
b=1
for k,v in g:
if n%k<1:
print(v,end='')
b=0
print(n)if b else print()
n+=1
```
Input:
```
((4, "Foo"), (7, "Bar"), (9, "Baz"))
```
[Try it online!](https://tio.run/##LYrLDoIwFAX3/YqTJobe0IWNJkZjNy78D9ECDeSWYMXHz9dC2M2ZM8M3toF3KbmPuyvZWFl6Hl5REQm2Rrxb3zuYk0CVF@owotMTPKPJDr4Gb7rz/APD6DmqSTt@2KKgWVV2K1bPlOMKrn@61eSCS2tSUmqvIa8hSNJQh8yX27jwceGfJPoD "Python 3 – Try It Online")
Fairly obvious way of going about the challenge. Using a tuple of tuples saves 1 byte over a dict. Looking at the other python submissions, I realize I missed a lot of optimizations. Lessons to bring to the next code golf, I hope.
[Answer]
# [CJam](http://sourceforge.net/projects/cjam/), ~~36~~ 35 bytes
```
q~{)1${\_@~;%!},_@aa?{1=}%:+oNo}%];
```
[Try it online!](http://cjam.aditsu.net/#code=q%7E%7B%291%24%7B%5C_%40%7E%3B%25!%7D%2C_%40aa%3F%7B1%3D%7D%25%3A%2BoNo%7D%25%5D%3B&input=%5B%5B4%20%22Foo%22%5D%20%5B7%20%22Bar%22%5D%20%5B9%20%22Baz%22%5D%5D%20100)
**Explanation**
```
q~ read the factor array and upper bound in one go
{) }% for each i from 1 to n
1${ }, get all the input factors i contains
\_@~;%! by checking i mod f = 0 for each input factor f
_@aa? if there *are* factors in i,
keep the relevant factors [[f, "Foo"], ...]
otherwise keep the number in the form [[i]]
{1=}% keep the 2nd element in each subarray
this is the texts ["Foo","Bar","Baz",...]
or just [i] if there were no input factors
:+ sum them all (concatenating texts together)
oNo print in the required format
]; clean up
```
**(-1 byte)** *dropping `,`: CJam automatically turns a number `n` into `[0, n)` when you map using `%`*
---
**Possible Changes**
**(-2 bytes)** *using `p` instead of `oNo` but this prints `"Foo"`/`"BarBaz"` instead of `Foo`/`BarBaz`*
**(-2 bytes)** *using `n` instead of `oNo` but this feature isn't in any releases (and most likely will never be)*
] |
[Question]
[
Your challenge is to generate this string:
```
011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000
```
or split into lines with length of 80:
```
01101011010110100110101101011010110101101011010011010110101101001101011010110101
10101101011010011010110101101001101011010110101101011010110100110101101011010000
11010110101101001101011010110101101011010110100110101101011010011010110101101011
01011010110100110101101011010011010110101101011010110101101001101011010110100001
10101101011010011010110101101011010110101101001101011010110100110101101011010110
10110101101001101011010110100110101101011010110101101011010011010110101101000110
10110101101001101011010110101101011010110100110101101011010011010110101101011010
11010110100110101101011010011010110101101011010110101101001101011010110100001101
01101011010011010110101101011010110101101001101011010110100110101101011010110101
10101101001101011010110100110101101011010110101101011010011010110101101000011010
11010110100110101101011010110101101011010011010110101101001101011010110101101011
01011010011010110101101001101011010110101101011010110100110101101011010001101011
01011010011010110101101011010110101101001101011010110100110101101011010110101101
01101001101011010110100110101101011010110101101011010011010110101101000011010110
10110100110101101011010110101101011010011010110101101001101011010110101101011010
11010011010110101101001101011010110101101011010110100110101101011010000011010110
10110100110101101011010110101101011010011010110101101001101011010110101101011010
11010011010110101101001101011010110101101011010110100110101101011010001101011010
11010011010110101101011010110101101001101011010110100110101101011010110101101011
01001101011010110100110101101011010110101101011010011010110101101000011010110101
10100110101101011010110101101011010011010110101101001101011010110101101011010110
10011010110101101001101011010110101101011010110100110101101011010000110101101011
01001101011010110101101011010110100110101101011010011010110101101011010110101101
00110101101011010011010110101101011010110101101001101011010110100011010110101101
00110101101011010110101101011010011010110101101001101011010110101101011010110100
11010110101101001101011010110101101011010110100110101101011010000110101101011010
01101011010110101101011010110100110101101011010011010110101101011010110101101001
10101101011010011010110101101011010110101101001101011010110100001101011010110100
11010110101101011010110101101001101011010110100110101101011010110101101011010011
01011010110100110101101011010110101101011010011010110101101000110101101011010011
01011010110101101011010110100110101101011010011010110101101011010110101101001101
01101011010011010110101101011010110101101001101011010110100001101011010110100110
10110101101011010110101101001101011010110100110101101011010110101101011010011010
11010110100110101101011010110101101011010011010110101101000001101011010110100110
10110101101011010110101101001101011010110100110101101011010110101101011010011010
11010110100110101101011010110101101011010011010110101101000110101101011010011010
11010110101101011010110100110101101011010011010110101101011010110101101001101011
01011010011010110101101011010110101101001101011010110100001101011010110100110101
10101101011010110101101001101011010110100110101101011010110101101011010011010110
10110100110101101011010110101101011010011010110101101000011010110101101001101011
01011010110101101011010011010110101101001101011010110101101011010110100110101101
01101001101011010110101101011010110100110101101011010001101011010110100110101101
01101011010110101101001101011010110100110101101011010110101101011010011010110101
10100110101101011010110101101011010011010110101101000011010110101101001101011010
11010110101101011010011010110101101001101011010110101101011010110100110101101011
01001101011010110101101011010110100110101101011010000110101101011010011010110101
10101101011010110100110101101011010011010110101101011010110101101001101011010110
10011010110101101011010110101101001101011010110100011010110101101001101011010110
10110101101011010011010110101101001101011010110101101011010110100110101101011010
01101011010110101101011010110100110101101011010000110101101011010011010110101101
01101011010110100110101101011010011010110101101011010110101101001101011010110100
11010110101101011010110101101001101011010110100001101011010110100110101101011010
11010110101101001101011010110100110101101011010110101101011010011010110101101001
10101101011010110101101011010011010110101101000110101101011010011010110101101011
01011010110100110101101011010011010110101101011010110101101001101011010110100110
10110101101011010110101101001101011010110100001101011010110100110101101011010110
10110101101001101011010110100110101101011010110101101011010011010110101101001101
01101011010110101101011010011010110101101000011010110101101001101011010110101101
01101011010011010110101101001101011010110101101011010110100110101101011010011010
11010110101101011010110100110101101011010001101011010110100110101101011010110101
10101101001101011010110100110101101011010110101101011010011010110101101001101011
01011010110101101011010011010110101101000011010110101101001101011010110101101011
01011010011010110101101001101011010110101101011010110100110101101011010011010110
10110101101011010110100110101101011010000110101101011010011010110101101011010110
10110100110101101011010011010110101101011010110101101001101011010110100110101101
01101011010110101101001101011010110100011010110101101001101011010110101101011010
11010011010110101101001101011010110101101011010110100110101101011010011010110101
10101101011010110100110101101011010000110101101011010011010110101101011010110101
10100110101101011010011010110101101011010110101101001101011010110100110101101011
01011010110101101001101011010110100000110101101011010011010110101101011010110101
10100110101101011010011010110101101011010110101101001101011010110100110101101011
01011010110101101001101011010110100011010110101101001101011010110101101011010110
10011010110101101001101011010110101101011010110100110101101011010011010110101101
01101011010110100110101101011010000110101101011010011010110101101011010110101101
00110101101011010011010110101101011010110101101001101011010110100110101101011010
11010110101101001101011010110100001101011010110100110101101011010110101101011010
01101011010110100110101101011010110101101011010011010110101101001101011010110101
10101101011010011010110101101000110101101011010011010110101101011010110101101001
10101101011010011010110101101011010110101101001101011010110100110101101011010110
10110101101001101011010110100001101011010110100110101101011010110101101011010011
01011010110100110101101011010110101101011010011010110101101001101011010110101101
01101011010011010110101101000011010110101101001101011010110101101011010110100110
10110101101001101011010110101101011010110100110101101011010011010110101101011010
11010110100110101101011010001101011010110100110101101011010110101101011010011010
11010110100110101101011010110101101011010011010110101101001101011010110101101011
01011010011010110101101000011010110101101001101011010110101101011010110100110101
10101101001101011010110101101011010110100110101101011010011010110101101011010110
10110100110101101011010000011010110101101001101011010110101101011010110100110101
10101101001101011010110101101011010110100110101101011010011010110101101011010110
10110100110101101011010001101011010110100110101101011010110101101011010011010110
10110100110101101011010110101101011010011010110101101001101011010110101101011010
11010011010110101101000011010110101101001101011010110101101011010110100110101101
01101001101011010110101101011010110100110101101011010011010110101101011010110101
10100110101101011010000110101101011010011010110101101011010110101101001101011010
11010011010110101101011010110101101001101011010110100110101101011010110101101011
01001101011010110100011010110101101001101011010110101101011010110100110101101011
01001101011010110101101011010110100110101101011010011010110101101011010110101101
00110101101011010000110101101011010011010110101101011010110101101001101011010110
10011010110101101011010110101101001101011010110100110101101011010110101101011010
01101011010110100001101011010110100110101101011010110101101011010011010110101101
00110101101011010110101101011010011010110101101001101011010110101101011010110100
11010110101101000110101101011010011010110101101011010110101101001101011010110100
11010110101101011010110101101001101011010110100110101101011010110101101011010011
01011010110100001101011010110100110101101011010110101101011010011010110101101001
10101101011010110101101011010011010110101101001101011010110101101011010110100110
10110101101000011010110101101001101011010110101101011010110100110101101011010011
01011010110101101011010110100110101101011010011010110101101011010110101101001101
01101011010001101011010110100110101101011010110101101011010011010110101101001101
01101011010110101101011010011010110101101001101011010110101101011010110100110101
10101101000011010110101101001101011010110101101011010110100110101101011010011010
11010110101101011010110100110101101011010011010110101101011010110101101001101011
01011010000110101101011010011010110101101011010110101101001101011010110100110101
10101101011010110101101001101011010110100110101101011010110101101011010011010110
10110100011010110101101001101011010110101101011010110100110101101011010011010110
10110101101011010110100110101101011010011010110101101011010110101101001101011010
11010000110101101011010011010110101101011010110101101001101011010110100110101101
01101011010110101101001101011010110100110101101011010110101101011010011010110101
10100001101011010110100110101101011010110101101011010011010110101101001101011010
11010110101101011010011010110101101001101011010110101101011010110100110101101011
01000110101101011010011010110101101011010110101101001101011010110100110101101011
01011010110101101001101011010110100110101101011010110101101011010011010110101101
00001101011010110100110101101011010110101101011010011010110101101001101011010110
10110101101011010011010110101101001101011010110101101011010110100110101101011010
00001101011010110100110101101011010110101101011010011010110101101001101011010110
10110101101011010011010110101101001101011010110101101011010110100110101101011010
00110101101011010011010110101101011010110101101001101011010110100110101101011010
11010110101101001101011010110100110101101011010110101101011010011010110101101000
01101011010110100110101101011010110101101011010011010110101101001101011010110101
10101101011010011010110101101001101011010110101101011010110100110101101011010000
11010110101101001101011010110101101011010110100110101101011010011010110101101011
01011010110100110101101011010011010110101101011010110101101001101011010110100011
01011010110100110101101011010110101101011010011010110101101001101011010110101101
01101011010011010110101101001101011010110101101011010110100110101101011010000110
10110101101001101011010110101101011010110100110101101011010011010110101101011010
11010110100110101101011010011010110101101011010110101101001101011010110100001101
01101011010011010110101101011010110101101001101011010110100110101101011010110101
10101101001101011010110100110101101011010110101101011010011010110101101000110101
10101101001101011010110101101011010110100110101101011010011010110101101011010110
10110100110101101011010011010110101101011010110101101001101011010110100001101011
01011010011010110101101011010110101101001101011010110100110101101011010110101101
01101001101011010110100110101101011010110101101011010011010110101101000001101011
01011010011010110101101011010110101101001101011010110100110101101011010110101101
01101001101011010110100110101101011010110101101011010011010110101101000110101101
01101001101011010110101101011010110100110101101011010011010110101101011010110101
10100110101101011010011010110101101011010110101101001101011010110100001101011010
11010011010110101101011010110101101001101011010110100110101101011010110101101011
01001101011010110100110101101011010110101101011010011010110101101000011010110101
10100110101101011010110101101011010011010110101101001101011010110101101011010110
10011010110101101001101011010110101101011010110100110101101011010001101011010110
10011010110101101011010110101101001101011010110100110101101011010110101101011010
01101011010110100110101101011010110101101011010011010110101101000011010110101101
00110101101011010110101101011010011010110101101001101011010110101101011010110100
11010110101101001101011010110101101011010110100110101101011010000110101101011010
01101011010110101101011010110100110101101011010011010110101101011010110101101001
10101101011010011010110101101011010110101101001101011010110100011010110101101001
10101101011010110101101011010011010110101101001101011010110101101011010110100110
10110101101001101011010110101101011010110100110101101011010000110101101011010011
01011010110101101011010110100110101101011010011010110101101011010110101101001101
01101011010011010110101101011010110101101001101011010110100001101011010110100110
10110101101011010110101101001101011010110100110101101011010110101101011010011010
11010110100110101101011010110101101011010011010110101101000110101101011010011010
11010110101101011010110100110101101011010011010110101101011010110101101001101011
01011010011010110101101011010110101101001101011010110100001101011010110100110101
10101101011010110101101001101011010110100110101101011010110101101011010011010110
10110100110101101011010110101101011010011010110101101000011010110101101001101011
01011010110101101011010011010110101101001101011010110101101011010110100110101101
01101001101011010110101101011010110100110101101011010001101011010110100110101101
01101011010110101101001101011010110100110101101011010110101101011010011010110101
10100110101101011010110101101011010011010110101101000011010110101101001101011010
11010110101101011010011010110101101001101011010110101101011010110100110101101011
01001101011010110101101011010110100110101101011010000110101101011010011010110101
10101101011010110100110101101011010011010110101101011010110101101001101011010110
10011010110101101011010110101101001101011010110100011010110101101001101011010110
10110101101011010011010110101101001101011010110101101011010110100110101101011010
01101011010110101101011010110100110101101011010000110101101011010011010110101101
01101011010110100110101101011010011010110101101011010110101101001101011010110100
11010110101101011010110101101001101011010110100000110101101011010011010110101101
01101011010110100110101101011010011010110101101011010110101101001101011010110100
11010110101101011010110101101001101011010110100011010110101101001101011010110101
10101101011010011010110101101001101011010110101101011010110100110101101011010011
01011010110101101011010110100110101101011010000110101101011010011010110101101011
01011010110100110101101011010011010110101101011010110101101001101011010110100110
10110101101011010110101101001101011010110100001101011010110100110101101011010110
10110101101001101011010110100110101101011010110101101011010011010110101101001101
01101011010110101101011010011010110101101000110101101011010011010110101101011010
11010110100110101101011010011010110101101011010110101101001101011010110100110101
10101101011010110101101001101011010110100001101011010110100110101101011010110101
10101101001101011010110100110101101011010110101101011010011010110101101001101011
01011010110101101011010011010110101101000011010110101101001101011010110101101011
01011010011010110101101001101011010110101101011010110100110101101011010011010110
10110101101011010110100110101101011010001101011010110100110101101011010110101101
01101001101011010110100110101101011010110101101011010011010110101101001101011010
11010110101101011010011010110101101000011010110101101001101011010110101101011010
11010011010110101101001101011010110101101011010110100110101101011010011010110101
10101101011010110100110101101011010000
```
## Notes:
* You may return an array of the characters (or digits) of the string
* You may use characters other than 0 and 1 if you want.
* You can have other characters in the output, as long as, if filtered for your two chosen characters, would result in this pattern.
* This string is generatable in way better ways than just hardcoding the whole string. A big part of the challenge is to find the shortest way to generate it. I've made a 16-byte SOGL answer that *should* be a language-agnostic algorithm (an old SOGL version specific 15-byte answer is what inspired the challenge), trough I'm not gonna post it (until someone finds that algorithm) to make the challenge more interesting for others.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer (per language) wins!
### Snippet to check the validness of an answer:
```
function check() {
if (chr0.value == "") chr0.value = "0"
if (chr1.value == "") chr1.value = "1"
inp.value = inp.value.replace(new RegExp("[^"+JSON.stringify(chr0.value+chr1.value)+"]", "g"), "")
if (inp.value == correct)
output.innerHTML = "Matches"
else
output.innerHTML = "Doesn't match"
}
correct = "011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000"
```
```
<input id="inp" placeholder="input your result here"/><br>
<input id="chr0" placeholder="character for 0 (def=0)"/>
<input id="chr1" placeholder="character for 1 (def=1)"/><br>
<button id="chk" onclick="check()">check</button>
<div id=output></div>
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~35~~ ~~33~~ ~~29~~ ~~26~~ ~~25~~ 24 bytes
```
'1
#˜5s £=r1,26¤²²sX
s#ž
```
[Try it online!](https://tio.run/##ASYA2f9qYXB0//8nMQojwpg1cyDCoz1yMSwyNsKkwrLCsnNYCnMjwp7//w "Japt – Try It Online")
### Explanation
```
'1 First line: Set variable U to this value.
'1 Yield the string "1". (This part gets simpler every time I golf this answer...)
1525s £=r1,26¤²²sX Second line: Set variable V to this value (though that's not important).
1525s Yield the string "1525".
£ For each char X in this string:
26¤ Yield the binary representation of 26. "11010"
²² Double it twice. "11010110101101011010"
sX Slice off the first X chars. This gives "1010110101101011010",
"110101101011010", "010110101101011010", and "110101101011010".
= Set U to
r1, U with each instance of 1 replaced with the string calculated above.
s158 Last line: output the result of this line.
s158 Take U and slice off the first 158 characters.
```
Here's how I got this. Start with the original sequence:
```
01101011010110100110101101011010110101101011010011010110101101001101011010110101101011...
```
After some messing around, I realized that the sequence consisted entirely of copies of `0` and `11010`. Replacing each instance of `11010` with `2` gave this:
```
02220222222022202222220222022222202220002220222222022202222220222022222202220002220222...
```
Oh hey, now it's entirely made of `0` and `222`. Let's change each `222` to a single `2`:
```
02022020220202202000202202022020220200020220202202022020020220202202022020002022020220...
```
This sequence looks an awful lot like the original. There seems to be a lot of `22020`s in this, so I replaced each with `3` and got this:
```
02033300203330020333020333002033300203330203330020333000203330203330020333002033302033...
```
Now each instance of `3` is contained in a `020333`. Replacing each of these again with a single `3` gives this:
```
30303303033030033030330303303003303033030330303303033030330300330303303033030033030330...
```
...and we're back to the original pattern again. One more time, replacing `33030` with `4`:
```
30304404440444444044404444440444044444404440
```
Uh-oh, there's some stray chars at the beginning. We can fix this by adding an extra `3` at the beginning before condensing (this is where the 158 extra chars at the end comes from). Then we condense each run of 3 `4`s into a single `4`, as before:
```
4040440404404044040
```
Aaaaand yet again, we're back to the original pattern. One last time, let's condense copies of `44040` to `5`:
```
4040555
```
Hopefully this final step isn't too hard to understand. It's like the step where we compressed the `020333`s into `3`s, except this time, we're compressing `4040555`s into `5`s:
```
5
```
And there you have the fully compressed string. The code simply reverses the repeated compression to get back the original string. Since all compression iterations were nearly identical, it doesn't take much to reorganize the string properly.
[Answer]
## JavaScript (ES6), 130 bytes
Multicolor nonlinear pulse compression by consecutive optical parametric amplification in quasi-phase matched structures.
OK, not quite. Just substitutions.
```
f=(n=0,s='pqh0f9bc9bc9bc900')=>n<20?f(n+1,s.split((n+9).toString(36)).join('cb0dgfgnjkkoppo0qs10'[n]+'adcdef0hi0klmnqpqrs1'[n])):s
```
### Demo
```
f=(n=0,s='pqh0f9bc9bc9bc900')=>n<20?f(n+1,s.split((n+9).toString(36)).join('cb0dgfgnjkkoppo0qs10'[n]+'adcdef0hi0klmnqpqrs1'[n])):s
o.innerHTML = f()
```
```
<pre id=o></pre>
```
### How?
This is definitely not the best way to compress this string, but I thought I'd post it anyway since I went to the trouble of optimizing it (slightly) with a recursive function.
We start with the string `s="pqh0f9bc9bc9bc900"` and successively apply the following 20 substitutions:
```
9 | a | b | c | d | e | f | g | h | i | j | k | l | m | n | o | p | q | r | s
----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----
ca | bd | 0c | dd | ge | ff | g0 | nh | ji | k0 | kk | ol | pm | pn | oq | 0p | qq | sr | 1s | 01
```
For instance, a *"9"* will expand to *"ca"*, *"cbd"*, *"c0cd"*, *"dd0ddd"*, ..., and ultimately a 2381-character string of 0's and 1's.
[Answer]
# Mathematica, 128 bytes
```
Fold[StringReplace,"AAAY0PY0",{{"A"->"Y0PY0PYP"},{"Y"->"P0P0PP0P0PP0P0"},{"P"->"QQQXXX00"},{"Q"->"XXX0XXXXXX0"},{"X"->"01101"}}]
```
[Try it online!](https://tio.run/##y00sychMLv6fZvvfLT8nJTq4pCgzLz0otSAnMTlVR8nR0THSICDSQEmnulrJUUnXTgnMDYgMUKrVqVaKBIkEGAAhnACLB4DEAwMDIyIiDCAigSAREDcCDCCCESBBA0NDA0Ol2trY/wFAq0sUHNL@AwA "Mathics – Try It Online")
[Answer]
## JavaScript (ES6), ~~85~~ 80 bytes
```
[j="1",5,2,5].map(x=>j=j.replace(/1/g,"11010".repeat(4).slice(x)))&&j.slice(158)
```
Somewhat of a port of my Japt answer. An explanation of the pattern can be found over there.
### Test snippet
```
var q = [j="1",5,2,5].map(x=>j=j.replace(/1/g,"11010".repeat(4).slice(x)))&&j.slice(158);
var o = "011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000011010110101101001101011010110101101011010110100110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000110101101011010011010110101101011010110101101001101011010110100110101101011010110101101011010011010110101101001101011010110101101011010110100110101101011010000";
console.log(q === o);
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~28~~ ~~22~~ 20 bytes
```
⁽.⁷Dð26Bẋ4ṫȧ€Ẏð/ṫ159
```
[Try it online!](https://tio.run/##y0rNyan8//9R4169R43bXQ5vMDJzerir2@ThztUnlj9qWvNwV9/hDfpAnqGp5f//AA "Jelly – Try It Online")
-3 thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan).
(Somewhat) port of [ETHproductions](https://codegolf.stackexchange.com/users/42545/ethproductions)'s excellent Japt [answer](https://codegolf.stackexchange.com/a/135517/41024).
Still not efficient as [dzaima's](https://codegolf.stackexchange.com/questions/135486/repeat-repetitive-repetitions/135650#comment331265_135486) (old SOGL version)!
This returns an array of digits.
[Answer]
# Retina, ~~69~~ ~~66~~ 65 bytes
Port of @ETHproduction's JavaScript (ES6) answer: [Try it online!](https://tio.run/##K0otycxL/P@fy/DQNkMDQwMrKzDBVZ1gqGFvq6d1aJtGTIqWppUml4phVFQUVxSXIUgZV61hAlDciosrTq/a0NSitubQNq7//wE "Retina – Try It Online") N.B. Somewhat slow.
```
1¶1010::010::
{`1(?=.*¶(\d*):)
$1ZZZ
Z
11010
}1`\d*:
^.{158}|¶
```
A port of @Jenny\_mathy's Mathematica answer was ~~82~~ 66 bytes: [Try it online!](https://tio.run/##HcWhEYBQDERB/6q5X0I6SKISHAKBQTD0Hxhmxd7Hc177DGbW8hbGv7fTbP5hw@XCiYiUCFKZIqkqCq2lNfMC "Retina – Try It Online")
```
AAAY0PY0
A
Y0PY0PYP
Y
ZPZPZ
Z
P0P0
P
QQQR00
Q
R0RR0
R
XXX
X
01101
```
A port of @ETHproduction's Japt explanation was 69 bytes: [Try it online!](https://tio.run/##HYYxCoBADAT7fYxssnvgawQLCxsLuU58ewwyDDP3Mc9rr8LwDwZME4bdQqIIgUlJPZm9yG6LCAaxLU@M9UXVBw "Retina – Try It Online")
```
5454545
5
4040
4
444
4
33030
3
020333
3
22020
2
222
2
11010
^.{158}
```
A port of @ETHproduction's previous Japt explanation was also 69 bytes: [Try it online!](https://tio.run/##K0otycxL/P@fKz4@3tDAkCueC0gCaSA0hJBALpAGSxtApMECyNJxetWGpua1XP//AwA "Retina – Try It Online")
```
___101
_
10101
1
111
1
11010
1
___100
_
10110
1
111
1
11010
^.{157}
```
A port of @RickHitchcock's JavaScript answer was 74 bytes: [Try it online!](https://tio.run/##PcU7DoBADAPRfk7jHAkpv20oEPcPLAV@kueKe53HDCu3LrHoLppSUqRe/5GENneXCHb9G47MZDMP "Retina – Try It Online")
```
ifififhg0
i
hhg
h
g0f
g
f0f0ff0f0ff0f0
f
e0e0e0ddd00
e
ddd0dddddd
d
01101
```
A port of @Arnauld's JavaScript answer was 85 bytes: [Try it online!](https://tio.run/##LcpBCsAgDADB@74mPfqcqiWWgCS1/089FBbmss/13vPMxGOISqntT4RCq52KNBq901HdD8ocDMxMMMTdJ3MbOBEE61gs5Mj8AA "Retina – Try It Online")
```
pqh0g09bc9bc9bc900
9
cbd
b
0c
c
dd
d
gg0g0
g
nh
h
kkk0
k
0pppn
n
0pq
p
qq
q
s1s
s
01
```
[Answer]
# JavaScript (ES6), ~~158~~ ~~143~~ 139 bytes
*(Saved some bytes thanks to @DanTheMan.)*
```
'ifififhg0'[r='replace'](/i/g,'hhg')[r](/h/g,'g0f')[r](/g/g,'f0f0ff0f0ff0f0')[r](/f/g,'e0e0e0ddd00')[r](/e/g,'ddd0dddddd')[r](/d/g,'01101')
```
```
console.log('ifififhg0'[r='replace'](/i/g,'hhg')[r](/h/g,'g0f')[r](/g/g,'f0f0ff0f0ff0f0')[r](/f/g,'e0e0e0ddd00')[r](/e/g,'ddd0dddddd')[r](/d/g,'01101'));
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 20 bytes
```
1Ž5ûv1₂b4×y.$.:]Ƶv.$
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f8Ohe08O7ywwfNTUlmRyeXqmnomcVe2xrmZ7K////dXXz8nVzEqsqAQ "05AB1E – Try It Online")
Port of [ETHProductions's JAPT answer](https://codegolf.stackexchange.com/a/135517/6484).
[Answer]
# [K (ngn/k)](https://github.com/ngn/k), 86 bytes
```
@[&15558;+\(,/(,/(,/(1 5,,/(1_,/(11#5 6 6),\:5 5),\:4 5),\:9#3 2 3),\:2 2),\:1 2);:;1]
```
[Try it online!](https://tio.run/##y9bNS8/7/98hWs3Q1NTUwlo7RkNHH4oMFUx1QFQ8iDBUNlUwUzDT1ImxMlUwBVEmEMpS2VjBSMEYxDRSMAJRhkDK2sraMPb/fwA "K (ngn/k) – Try It Online")
] |
[Question]
[
The [Home Prime](https://en.wikipedia.org/wiki/Home_prime) of an integer \$n\$ is the value obtained by repeatedly factoring and concatenating \$n\$'s prime factors (in ascending order, including repeats) until reaching a fixed point (a prime). For example, the Home Prime (\$\text{HP}(n)\$) of \$10\$ is \$773\$ as:
$$\begin{align}
10 & = 2 \times 5 \to 25 \\
25 & = 5 \times 5 \to 55 \\
55 & = 5 \times 11 \to 511 \\
511 & = 7 \times 73 \to 773 \\
\end{align}$$
There are two equivalent ways to consider when the sequence ends:
* It ends at a prime
* It reaches a fixed point, as the prime factors of a prime \$p\$ is just \$p\$
Note that the Home Prime of some numbers is currently unknown (e.g. \$49\$ or \$77\$).
---
You are to take a positive integer \$n \ge 2\$ as input through any [convenient method or format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) and output the Home Prime of \$n\$. You may assume that you don't have to handle any input that would exceed the integer limit in your language at any step, and you may assume that the input will already have a known Home Prime (so 49 won't be an input).
Make sure you program handles all inputs correctly, not just those that are only semiprimes:
$$\begin{align}
\text{HP}(24) = 331319 :\\
24 & = 2 \times 2 \times 2 \times 3 \to 2223 \\
2223 & = 3 \times 3 \times 13 \times 19 \to 331319
\end{align}$$
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins!
## Test cases
These are the results for each \$2 \le n \le 100\$, excluding \$n = 49,77,80,96\$ which don't terminate on TIO in my example program.
```
2 2
3 3
4 211
5 5
6 23
7 7
8 3331113965338635107
9 311
10 773
11 11
12 223
13 13
14 13367
15 1129
16 31636373
17 17
18 233
19 19
20 3318308475676071413
21 37
22 211
23 23
24 331319
25 773
26 3251
27 13367
28 227
29 29
30 547
31 31
32 241271
33 311
34 31397
35 1129
36 71129
37 37
38 373
39 313
40 3314192745739
41 41
42 379
43 43
44 22815088913
45 3411949
46 223
47 47
48 6161791591356884791277
50 3517
51 317
52 2213
53 53
54 2333
55 773
56 37463
57 1129
58 229
59 59
60 35149
61 61
62 31237
63 337
64 1272505013723
65 1381321118321175157763339900357651
66 2311
67 67
68 3739
69 33191
70 257
71 71
72 1119179
73 73
74 379
75 571
76 333271
78 3129706267
79 79
81 193089459713411
82 241
83 83
84 2237
85 3137
86 6012903280474189529884459
87 41431881512748629379008933
88 719167
89 89
90 71171
91 236122171
92 331319
93 331
94 1319
95 36389
97 97
98 277
99 71143
100 317047
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes
```
ΔÒJ
```
[Try it online!](https://tio.run/##HZA7DgIxDAWvYm0dpI0dO0nD9lwBUYBEQUWBhETBJRA3oudKy4TCzZt5zud6O54u5/X@WCbZbGVaHuv3/Xnt1mda95rEkpQkniSS1CQ9SZ6ZzEAzOMMzQgbnxuAoXOEKV7jClQ2KoziKY@wxPBun4Bme4Rme4Rme4RWcglPGVWAF5nSd3Mmd3Mcd6TrcB6frdAMv8AIv8AIe8IAHvMIrvMIqOyo76ngprNFp5I28kTc6jbzT6bAO67AO6@Nr4P3/P/PhBw "05AB1E – Try It Online")
`Δ` run until the output doesn't change:
`Ò` prime factors including duplicates
`J` join into an integer
[Answer]
# JavaScript (ES6), ~~58~~ 55 bytes
```
f=n=>n-(g=d=>q=n>1?n%d?g(d+1):d+g(d,n/=d):'')(2)?f(q):q
```
[Try it online!](https://tio.run/##PVE7bttAFOxzim2C3YVsyvvjkjJWqpIyjcvEBUMuZRrSUiJpw0GQGwRIkzK5R87jC@QIyntPoVQIwzdv5s2Qj9VzNdZDd5iuU9/E06kNKazTtdiGJqyPIa3VJr1tNlvRLJRcNQsAV2kZGrniXAotN604ytXxNMTjUzdEwduRy2yIVfO@28W7L6kWNzKb@rtp6NJWyGw87LpJ8E8J1tp@eFfVD2JkYc2@vmHsY7pi8eUQ6yk29yywMQPZ/qJassVSZvvqID487T/HQd6Cpu7T2O9ituu3AvVDBDu2aEWS/x/CxZNtGP/758frr5/wz9mK8dff3/l99th3CTJNXILlN3liTDP8afA3hAwgixOlADmaOUA5rSHraeYBlbiPe@oGJx5YpZCkGTprVChyVogccroERC4KXFRBxsiWNANWk4sBVus5izZzAu3maxpSGe2QJReNCnLBGwZTOQszc/aDPWPmzOaSxfj5mikIgLM5dwNkSWtBYTWxoLCUxSKbzy0tueA1B3eNw25OkQsijWvo50jrEFkqjujSyPk5lTs3QkSNHKCcsuSQJacemDnP0QUb5ZQgx1lBNUDh8R1oBzNPWg97nhLgNW/nRh4TOGLpGs4KevfYvCBFAYrCUl3wKxy9IESkKEBRnlOBorT4xfFblpSqhL2SGnn/Dw "JavaScript (Node.js) – Try It Online")
### Commented
```
f = n => // f is a recursive function taking the input n
n - ( // subtract from n the result of a call to ...
g = d => // ... g: a recursive function taking a divisor d
q = // save in q:
n > 1 ? // if n is greater than 1:
n % d ? // if d is not a divisor of n:
g(d + 1) // increment d until it is
: // else:
d + // append d
g(d, // append the result of a recursive call
n /= d) // with n divided by d
: // else:
'' // stop and force coercion to a string
)(2) // initial call to g with d = 2
? // if it's not equal to n:
f(q) // recursive call to f with n = q
: // else:
q // we're done: return q
```
[Answer]
# [APL(Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 12 bytes [SBCS](https://github.com/abrudz/SBCS)
```
{⍎⊃,/⍕¨⍭⍵}⍣=
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=q37U2/eoq1lH/1Hv1EMrHvWufdS7tfZR72JbAA&f=AwA&i=S1MwNOBKUzACYmMgNgFiUyA2A2JzAA&r=tio&l=apl-dyalog-extended&m=dfn&n=f)
A dfn submission which takes a single argument.
[Answer]
# [Bash](https://www.gnu.org/software/bash/), ~~84~~ ~~82~~ 71 bytes
Saved 11 bytes thanks to [caird coinheringaahing](https://codegolf.stackexchange.com/users/66833/caird-coinheringaahing)!!!
```
for((;$1-${2-0};)){ set - `factor $1|sed 's/.*://;s/ //g'` $1;};echo $1
```
[Try it online!](https://tio.run/##TZTdaiNHEIXv9RQnYmA1AUddVd1dXREKgZCnsA27kUdrs2AvHl0YFD27c3rkLCsYadT1c0593TP/fJkf34@b8fx@fHndbHaD3AxnvUmX3TieMU8n3ODz8cvh9PKKQf6dpwd8mre//fr7drubt9huv376zMDuspsOjy@8e7@sVqdpPs37DRSGjIIKR0NAEkQgCjFIhhRIhTikQQKaoAJVqEEztEAr1KENGrAEExhbGizDCqzCHNZggZyQBVmRqZiRC3JFduSGklAERVEMhW4KSkVxFIYCNaEKqqIaakal2YrqqA014AkucIUbPMMLnLM0eKAJmqIZWkYraBWNQza0QCSEIBRhiIwoCEcQQCeQxtX09n06nKaHD0JKJqUPzWHMRMSiFrNWrUjiGsNOfelsbEFnRocinYpUq9aj5EQyxMgWzVLLXqrX5JJZQU5dheWMGpN6Q1NyufbSjjmIp8sRvijH7sLMjg8pvwoyo9fK0ipLqOfifQeYTCzkr9qkpNai52SRyLE4Z/MqVTykMFRqo8egEjsW6cLdB2u4TxzFrh49V7vqazcYPZf9arem3Qwv9tCSShLzBVAT47SkwG8vUtwr@0WkZMVr6Rw4Wl0mWXhxt5QngjOzLOgQizT1OgazKw0NT1VZxoAEEUcu4dJH7Mj6WdDFEn3wXDE/mbaUPUuLosF5WUBQmTtERLSdW9WgUGKzPjHF2b8tsL37rEIki4ll2/iD6021ftBIzLtvtuz8qDWuDo/T4dv0ut@s797@1ru3@ItXWePnv7YeV3ze8YSnZwznX/4/kbd/3l92q4eXFfg57Yfz8iTfDk/3l2Vp3g@bI35eHpf1iak/evzI/v769Hw6Yj3wJfIHhpmFH@Zuh81mmPf7YRrH@8vd85qaz9P7fw "Bash – Try It Online")
Returns the home prime of \$n\$ *quickly* (performs all testcase in less than 2 seconds on TIO).
[Answer]
# [Haskell](https://www.haskell.org/), 79 bytes
```
until((==)<*>g)g
g=read.f
f 1=""
f n=[show p++f(div n p)|p<-[2..],mod n p<1]!!0
```
[Try it online!](https://tio.run/##jVbLbuJAELzzFZMoB0gC8nTPU7LzBfsHLAcU87AWbAvY5JJvX7bbyjk1XJBQubururrMcXv9szud7sfm9/1vf@tO83nTLOrnt8PiMDs0l922Xe1ne2Obx0f56pv19Th8mvHlZT9vuw/Tm3HxNdbLNa1Wm9fz0Oovtd08PFT387brm3aYGbPuXodNvTxvRzNV/Bwu7bV@ejvsbr@6fieI8dL1t6ej6ZpGH9BH78aQgR8SNGMYC8zBWtYKzONqXmABj6ZNI64WBZYhAZ3NVrBWlKbWwp5TNSgvKQWL5bUKcwjDQZhaDyejLDCsm9VqCS9BZ8u4mjQlrBtLU6IiIxEXOYR@1o3Z8jSbL1o9IVsyeZ0tFi2LsLykMCyv7pShe72TalywBaHAP2@BnKWoMC66LHYIxFlnK3Mvgy3Eb1gs8hsnjJLVc0GGCMxheZ0I4gg3FQoOm9xp01AUNQ4Log7xyEjsNRy8xYIojOBoqpvHTL3CHA4khZWdsw9oBy4oLBbZ0hecs8LwOXuBhQouwSkM@y2I3wKhVZHeQsDnPMEC3IJefcB@0xgMCd@fMs1oMpulaYQxSF6aRqyb5lvEtlQjRVd0zhHa0k9NAyDKU/ZGbCRtmvD7VBMpYaZJmCaHk0bkTR6HpcIS2EC26pCEmSZhmiv4XlDdMhX9JcgFt6DVkCDf1YAgHHiigE9GX5QZR01UWIaCyOvDVhWK8crFf@/70/ZwvS/fx/E/ "Haskell – Try It Online")
The relevant function is `until((==)<*>g)g`, which takes as input a number `n` and returns its Home prime.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 6 bytes
```
ω(rṁsp
```
[Try it online!](https://tio.run/##yygtzv6f@6ip8eGOxeb/z3dqFD3c2Vhc8P8/AA "Husk – Try It Online")
```
ω( # iterate until reaching a fixed point:
p # get the prime factors
ṁs # convert each to a string & concatenate
r # convert the string to a value
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), ~~5~~ 4 bytes
```
‡ǐṅẊ
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%80%A1%C7%90%E1%B9%85%E1%BA%8A&inputs=6&header=&footer=)
Jelly really do be getting rekt by stack languages though :p
~~This isn't 4 bytes because strings and integers aren't interchangeable like 05ab1e (and by extension Ohm), but that's okay.~~ I added better type cohesion.
## Explained
```
‡ǐṅẊ
‡ǐṅ # lambda x: "".join(prime_factorisation(x))
Ẋ # repeat the above on the input until it doesn't change.
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 14 bytes
```
W!P_Q=QsjkPQ;Q
```
[Try it online!](https://tio.run/##K6gsyfj/P1wxID7QNrA4Kzsg0Drw/38LAA "Pyth – Try It Online")
# Explanation
```
Q # integer input
W!P_Q # While Q is not prime
=Q # Set Q to
PQ # Returns prime factors of Q in increasing order.
k # Empty string
jk # Join them
s # Convert to integer
; # End of loop
Q # Print the final value of Q
```
[Answer]
# [Ohm v2](https://github.com/nickbclifford/Ohm), 4 bytes
```
·ΘoJ
```
[Try it online!](https://tio.run/##y8/INfr//9D2czPyvf7/NzECAA "Ohm v2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
ÆfV$ÐL
```
[Try it online!](https://tio.run/##y0rNyan8//9wW1qYyuEJPv///zc0AAA "Jelly – Try It Online")
This seems oddly long, but the prime factorize built-in is two bytes, I don't think there's a way to bypass needing the `$`, and the loop-until-not-unique built-in is only one byte long for the accumulator version.
[Answer]
# [R](https://www.r-project.org/) + `numbers`, ~~74~~ 73 bytes
```
n=scan();while(F<-el(Reduce(paste0,numbers::primeFactors(n)):0)-n)n=n+F;n
```
[Try it online!](https://tio.run/##BcFbCoAgEADA6@xSgkRfmr8eoBuYLSToJj7o@NtME2HXY2BA@z0pE/hDUYaT7hkJauiD9MqzXNS6MbWlQj7E8bYOjGg0KkZ2vHjLsu3yAw "R – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
@=k ¬n)j}a;U
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QD1rIKxuKWp9YTtV&input=WzEwLDExLDEyLDEzLDE0LDE1LDE2LDI0XS1t)
```
@...}a - first number to return a truthy value when passed trough:
@= > ignore input and assign 1st input U : *
k ¬n) * prime factors of U joined and converted to a number
j > return(is prime?)
;U - print U
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 11 bytes
```
j ?U:ßUk ¬n
j ? // If the input is prime
U // we're done, return the input.
: // Otherwise,
ß // recursively rerun
Uk // with the input's prime factors
¬n // joined together as a string and parsed to a number.
```
[Try it here.](https://ethproductions.github.io/japt/?v=1.4.6&code=aiA/VTrfVWsgrG4=&input=MTA=)
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 37 bytes
```
{`.+
$*_
+`(__+?)(\1)*$
$.1_$#2$*_
_
```
[Try it online!](https://tio.run/##HY0xTsVADAX7uQZByv@Rvtb22t6tKLkEUkJBQUOB6Dh8cOie5mk03x8/n1/v5/P6epy/x2Njue9sx7rv28ttfZPbfWF5yL486fXsnKdidJwgYSINEUQRQzriIIkMZIIKqqjVcjTQRAc6sYYJmGEdK8cSG1g5XehKL4ce9IrgDRdcccOr7XjgiQ98Eo0QQonLiSCSGMQkG1mVNLKTValdBYYyjNEZ/2xcjGnMziwykzngDw "Retina 0.8.2 – Try It Online") Somewhat slow, so link only includes faster test cases. Explanation:
```
{`
```
Repeat until the fixed point.
```
.+
$*_
```
Convert to unary.
```
+`
```
Repeat until all prime factors have been found.
```
(__+?)(\1)*$
```
Find the lowest factor of the remainder.
```
$.1_$#2$*_
```
Prefix the decimal of the factor to the quotient, thus concatenating it to the factors found so far.
```
_
```
Delete the trailing unary `1`.
[Answer]
# [Python 3](https://docs.python.org/3/), 109 bytes
```
def f(n,m=0):
while n-m:
l=m=n;n=0
for i in range(2,l+1):
while l%i<1:n=int(f'{n}{i}');l/=i
return n
```
[Try it online!](https://tio.run/##RZTdbtswDIXv8xS6GRJjLiaKkii1c19k28WQOaux1A0cF/sJ8uzZIe1uFzac8CN5eCjo9Ht@ehn5dvvWH9xhN7bPnW/uN@7n03Ds3Xj3jG937J678WHsPL4PL5Mb3DC66ev4vd@F9vieNMGtKcd3w0e6H7thnHeH7WW8Xobrtnk4fuiGjZv6@XUa3Xib@/N8dp1DvuPWxdal1uXWSetK62rryOMhPAAIBAEhMASIQBEwAhfABXABXAAXwAVwAVwAF8AFcAyOwbE2BMfgGByDY3AMjsFFcBFcBBdVGbgILoKL4CK4BCaBSWASmKTywSQwCUxSBrUyuAwug8vgMrisc4LL4DK4DE7ACTgBJ@AEnIATNQSMgCmIF8QL4gXxgnhBvKhjYAqYijoVXAVXwVVwFVwFU9VW89U3m/7Xqd/P/bf/CwjqdVosVDeYiYhrTswlcyKvfyojKpDMcF43w6zDEJnNlDmzMWq@Oq1bQrnCvkRJWbIXipqotltfrQSClbT6HNTetXCwNVa1WZYdhkhB/TJByKv/2suqQkErREvpSDVITGIb1iS1VNcbQqHkS6kGRqIa6zqbdsuUSSolhFMu0F/RWYsnMi0mT1P1GGBafhtAYuY3UcHEV8vS6tlUBxOpL5QMySdPLIunhRi@wDG8JVESyShdq/ecJCdzTEfPy5iLv7r4oKdPnUF2JZ1xEaP9zTDm1bhQxeegBTRIFcupMVUh9cAcXo5aWGSSvrNHmudQfJRIpaZQYUlM5mnEhmElZoklh4qeHiXNEEjRRmXZj5j8TPBtkbTsndk2bp@Z7TSruWIDUbRdCho3m/1Tv//RT3p2t59f0W@/bZ19EW@bjd5Pc9vrDfVnOO3somnd24lfbio3HNyxH3fnedr1TfMo9/uXcR7G196iejEddnNjP07TepPNV3f36C7nq7usEj71XXf@gtvt9hc "Python 3 – Try It Online")
*Quite* verbose, returns the home prime of \$n\$.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 60 bytes
```
#//.x_:>FromDigits[ToString/@(""<>Table@@@FactorInteger@x)]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277X1lfX68i3srOrSg/1yUzPbOkODokP7ikKDMvXd9BQ0nJxi4kMSkn1cHBwS0xuSS/yDOvJDU9tcihQjNW7X9gaWZqiUMAUHGJgkN6tIV57P//AA "Wolfram Language (Mathematica) – Try It Online")
-14 bytes from @att
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 5 bytes
```
usjkP
```
[Try it online!](https://tio.run/##K6gsyfj/v7Q4Kzvg/38zUwA "Pyth – Try It Online")
Pyth could tie 05AB1E if it had a "join into integer" byte, or Ohm if it could take the primes factors of a string. Beats Jelly even without them, which surprises me.
[Answer]
# [Arturo](https://arturo-lang.io), 49 bytes
```
$->n[until->prime? n[n:do join factors.prime n]n]
```
[Try it](http://arturo-lang.io/playground?NGHXtI)
Really useful:
* `join [12, 3, 45]` -> `"12345"`
* `do "12345"` -> `12345`
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 88 bytes
```
param($n)while($n-ne$m){$m=$n;$n=[int](((factor $m)-replace"^\d+: ").split()-join"")};$n
```
[Try it online!](https://tio.run/##Dcs9CsMwDEDhqwSjQaI4Q7em5CT9AZOqxEGWjWPIUHJ21duDj1fywXVfWcSshBoSgtKxRuEeXhkS/SDNoHfQ@RG1vRDxG5aW69DNVy4SFnbv5@cyDY7GvUhsSH7LUZ2js39mdrv@AQ "PowerShell – Try It Online")
Well, I'm lazy, just ported @Noodle9
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 203 bytes
```
param($k)$s='$f;$n/=$f';function F($n){$m=[math]::sqrt($n);$f=2;while(!($n%$f)){iex $s};$f=3;while($f-le$m-and$n-ge$m){while(!($n%$f)){iex $s};$f+=2};$n};while($k-ne$g){$g=$k;$k=[int]((F($g))-join'')};$k
```
[Try it online!](https://tio.run/##dY7RCsIgGIVfZcEfKiHBuirxtpcYu5DSzdR/axoLxp7dHNRlV@dwPj444zDrKfba@5xHNalAwTGIkoARgEcJhgjzwluyA1ZXCsgWCLIJKvXt5RKfU9o2AUbWYu6t13RXhj0Yxhar3xXEdYOnLwTDvYbAFd4BeVcqW/5rB1mXwPUnO44auvKgk@AEONlYTC2l5VfHGH8MFglhRXE553P9AQ "PowerShell – Try It Online")
This one has some thought put into it...
`F()` is a function that returns the prime factors of a number, it works like
1. Handle 2 as a prime
2. Then brute force odd numbers
3. Stop when the factor to test exceeds the square root of the number, or the remaining quotient is less than the square root of the number
[Answer]
# [Scratch](https://scratch.mit.edu), 320 bytes
[Try it online!](https://scratch.mit.edu/projects/515528202)
Numbers that use values greater than 1 sextillion break because Scratch automatically converts them to scientific notation. Alternatively, 38 blocks.
```
when gf clicked
delete all of[P v
ask()and wait
set[N v]to(answer
repeat until<(length of[P v])=(1
repeat(length of[P v
set[N v]to(join(item(length of[P v])of[P v])(N
delete(length of[P v])of[P v
end
repeat until<(N)=(1
set[F v]to(2
repeat until<((N)/(F))=(round((N)/(F
change[F v]by(1
end
set[N v]to((N)/(F
add(F)to[P v
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
@j}a@=k ¬n
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QGp9YUA9ayCsbg&input=MjQ)
# [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Assumes that it takes no more than `n` iterations to reach `p`.
```
Æ=k ¬n
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=xj1rIKxu&input=MjQ)
[Answer]
# [Scala](http://www.scala-lang.org/), ~~233~~ 212 bytes
saved 21 bytes thanks to the comment of @The Thonnu
Golfed version, [try it online!](https://tio.run/##ZZHRatswGIXv/RQ/JgMJFM@ylrhxqrJRejFwctPuauxC9RRXQ5GCJTo6kzfY3W63l@uLZL8cug1mEBKH8x3J5w@dsurk77/oLsJGGQfjKT4dNLSy9a7PPusd7IhrWrZvWlnSJqlyfBsSVyjnfFTReFdEZeygO0hA/wKgXRrEpdxTB9oGPT6qATbSrdO@lWU7HazcrHd@IOZyXkH0YIvo37tIvz4Yq4l9ZSRePW7lFvXbOBjXF513nYrE/FEontLj1va1NMd1T7ZsQ9Pu2J4eT@lde/w/ooY@NO@GQT19PIOfaPPBmSjH7FFZuJOtCZFUDASDNwwWDJYMagYXDFYMeImL40IDRwdHC1/QCb35F62SC@FKTLQQgnMuVsuFEBdLseBl3aKaTHUtzplV8k6hQizrpFWrc/L1OTl//vU9Z5A///yR0wwLA0IiA03hcg53xTdzIDeUwphh5/pvVVa7Pj5ccawwO6ASrSMhn0WYX2HZHu5Nj3HHaTzTdQEkDj3S/9yzALPxmpgdEC1loMCnoUJJjykBv9Nv)
```
type L=Long
def f(n:L,m:L=0):Long={@scala.annotation.tailrec def g(n:L,m:L):L=if(n==m)n else{var M=n;var N=0L;var l=M;for(i<-2 to l.toInt)while(l%i==0){N=N.toString.concat(i.toString).toLong;l/=i};g(N,M)};g(n,m)}
```
Ungolfed version
```
import scala.annotation.tailrec
object Main {
def f(n: Long, m: Long = 0): Long = {
@tailrec
def innerF(n: Long, m: Long): Long = {
if (n == m) n
else {
var newM = n
var newN = 0L
var l = newM
for (i <- 2 to l.toInt) {
while (l % i == 0) {
newN = newN.toString.concat(i.toString).toLong
l /= i
}
}
innerF(newN, newM)
}
}
innerF(n, m)
}
def main(args: Array[String]): Unit = {
val tests = List(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)
val expected = List(2, 3, 211, 5, 23, 7, 3331113965338635107L, 311, 773, 11, 223, 13, 13367, 1129, 31636373, 17, 233, 19, 3318308475676071413L)
val checker = List("❌", "✓")
for ((t, e) <- tests.zip(expected)) {
if (e.toString.length > 10) {
println(s"$t -> too big")
} else {
val s = f(t)
println(s"$t -> $s ${checker(if (e == s) 1 else 0)}")
}
}
}
}
```
] |
[Question]
[
We all know `true` and `false`, but what do speakers around the globe say?
```
+----------------------+------------+------------+
| **Language** | **True** | **False** |
+----------------------+------------+------------+
| Arabic | sahih | zaif |
| Armenian | irakan | kelc |
| Assamese | asol | misa |
| Breton | gwir | gaou |
| Bulgarian | veren | neveren |
| Catalan | veritable | fals |
| Cornish | gwir | gaw |
| Czech | pravdivy | nepravdivy |
| Danish | sand | falsk |
| Dutch | waar | onwaar |
| English | true | false |
| Esperanto | vera | malvera |
| Finnish | tosi | epatosi |
| French | vrai | faux |
| Galician, Portuguese | verdadeiro | falso |
| Georgian | namdvili | cru |
| German | wahr | falsch |
| Greek | alithis | psevdis |
| Hebrew | hiyuvi | shikri |
| Hindi, Urdu | thik | jhutha |
| Hungarian | igaz | hamis |
| Icelandic | sannur | rangur |
| Indonesian, Malay | benar | salah |
| Irish | fior | breagach |
| Italian | vero | falso |
| Japanese | shin | nise |
| Korean | cham | geojit |
| Latin | verus | falsus |
| Latvian | patiess | nepareizs |
| Mandarin Chinese | zhen | jia |
| Maori | pono | pate |
| Persian | dorost | galat |
| Polish | prawdziwy | falszywy |
| Romanian | adevarat | fals |
| Russian | vernyj | falsivyj |
| Sardinian | beru | falsu |
| Scottish Gaelic | fior | breugach |
| Spanish | verdadero | falso |
| Swedish | sann | falskt |
| Sylheti | hasa | misa |
| Turkish | dogru | yanlis |
| Volapuk | veratik | dobik |
| Welsh | gwir | anwir |
+----------------------+------------+------------+
```
All words ASCIIfied from Wiktionary: [true](https://en.wiktionary.org/wiki/true#Translations), [false](https://en.wiktionary.org/wiki/false#Translations). Preference given to first entry under 'A state in Boolean logic that indicates an affirmative or positive result'/'state in Boolean logic that indicates a negative result', then first entry under 'concurring with a given set of facts'/'untrue, not factual, wrong'. I apologise if your favourite language is not included or the word choice for your language is not optimal - go edit Wiktionary!
Write a program or function that takes one word from the table above as input and outputs a consistent truthy value if the word means 'true' and a consistent falsy value otherwise. Your code must produce the correct output for all 79 possible inputs. Shortest code (in bytes) in each language wins.
Sorted list of unique words meaning 'true':
```
adevarat,alithis,asol,benar,beru,cham,dogru,dorost,fior,gwir,hasa,hiyuvi,igaz,irakan,namdvili,patiess,pono,pravdivy,prawdziwy,sahih,sand,sann,sannur,shin,thik,tosi,true,vera,veratik,verdadeiro,verdadero,veren,veritable,vernyj,vero,verus,vrai,waar,wahr,zhen
```
Sorted list of unique words meaning 'false':
```
anwir,breagach,breugach,cru,dobik,epatosi,fals,falsch,false,falsivyj,falsk,falskt,falso,falsu,falsus,falszywy,faux,galat,gaou,gaw,geojit,hamis,jhutha,jia,kelc,malvera,misa,nepareizs,nepravdivy,neveren,nise,onwaar,pate,psevdis,rangur,salah,shikri,yanlis,zaif
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~56~~ 48 bytes
thanks to [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper) for -8 bytes!
```
lambda s:0x420AF14A5F8266>>hash(s)%3317%890%57&1
```
[Try it online!](https://tio.run/##XVLLjtswDLzvV/iSJgGIIsm@C@wCe9mv6IWOZYu2TBmUbK/98ykldw/tZTgwSXlmpGGJ1vPlVr/9vjnsywqL8Ov09XA5fXyeHz4eP18uT0/v7xaDPYTj7v7@/Lx7eT3tHp9/nG9RxmhD8VbssTITCkZAR9FSAAzeQWkYRVFGuFrsofKN0sqLDxFq8gLNTAJ6OIKlZZwIqMEVSLBDBsa@msgRDBjJhACDZw@D4FTRtCQyVyvNCwS0ZBW5SsAZRoFgiUHVdBB9IFC1BiYjmCHqZ62VKifx33RjhhNSxNLlDV7aVHJvDDAJEsyo1ma0Aqs1vP8ZBnV@2MP@eHdXowtmy4WTwVIMNni1iYyZXHMOpWowai6pSzsZtJv3M6rPNpNuw5iLzzhuuG2ti@ZQ4/gFDTq9hwb9qDBDY3xLUTPu9VZaqxeG0BJCZ9wVenQ5EO0hsEoRQ2tI7DtkNlseTKrIc3atig0MwehEAEFuUtb6V5sS74RgQXbaWpHqf4MZhDgW6Nyh1tdU1F6KUBAX20M6/u2z1xle/pvZQj3e/gA "Python 2 – Try It Online")
All these answers do the same thing:
1. Convert the string into an unique integer.
2. Makes these integers smaller by repeated modulo operations.
These operations are bruteforced to make the numbers as small as possible while not mixing up the two classes.
3. Index into a binary lookup table.
---
# [Python 3](https://docs.python.org/3/), ~~59~~ 58 bytes
```
lambda s:0x48A2D06199310566F06>>int(s[:4],36)%542%400%78&1
```
[Try it online!](https://tio.run/##XVLLbtwwDLznK3zZ7hogCm924zyABAgQ9CfaHrhr2aItU4Yk27F/fkvJzaG9DAcmCc8MNSxBWz7d6tdfN4P9pcLMvxSf56f3@4@iPD4/n47FQ1n@KMq3N@Jw8D9fzr/hVOa7h/P97lwUu8enb8dbcGPQPnvN9lipCR0GQENBkwf01sBFMTpBN8JVYw@VbYRW1lkfoCbroJnJgUaPoGkZJwJqcAVy2CEDY19NZAgGDKS8h8GyhcHhVNG0RDJXK80LeNSkBbmKwAlGB14Tg6jpIFhPIGoVTMphgiCfpVainJz9ohtTHJECXkza4KWNJfVGD5NDghnF2ozawaoV77/7QZwf9rDP7@5qNF5tuXA0eHEKG7zqSMZErimHi2hQYi6qizsJpJv2E4rPNpFuw5CKTThuuG2ti@RQ4/gJDRq5Q4N2FJihUbalIBn3cpVWy8EQWkLolLlCjyYFIj0EFilO0eoj@wqZ1ZYHkyiynFyLYgWDVzLhwSE3MWv5q46Jd45gQTbSWpHqf4MZXHxNaMyhPvg8q63LfEacbQ8pz/8OsA0Z8vLf0JZqnt/@AA "Python 3 – Try It Online")
```
lambda s:0x453CCA1066840810431C1>>int(s,36)%2387%1770%86&1
```
[Try it online!](https://tio.run/##XVLBjqMwDL3PV3DptkjWCpZuW400I436G3MxJRC3wUFJgIGf7zph57B7eX7CtnjvOcMStOXq2b59Pg32dYOZfy2@jr@r6/WjLE6ny7G4lMWxKq/l@ztxOHioTvnuV3U578rzudhdTj/KZ3Bj0D57y/bYqAkdBkBDQZMH9NZArRidoBvhprGHxnZCG@usD9CSddDN5ECjR9C0jBMBdbgCOXwgA2PfTGQIBgykvIfBsoXB4dTQtEQyNyvNC3jUpAW5icAJRgdeE4OoeUCwnkDUKpiUwwRBPkttRDk5@003pjgiBaxN2uDlHkvqjR4mhwQzirUZtYNVK97/9IM4P@xhn7@8tGi82nLhaLB2Cju86UjGRG4ph1o0KDEX1cWdBNJN@wnF5z2Rx4YhFZtw3HDbWhfJocXxCzo0cocO7SgwQ6fsnYJk3MtV7loOhnAnhIcyN@jRpECkh8AixSlafWTfIbPa8mASRZaTa1GsYPBKJjw45C5mLX/VMfGHI1iQjbRWpPbfYAYX3xIac2gPPs9a6zKfEWfbQ8rzvwNsQ4a8/De0pZrnzz8 "Python 3 – Try It Online")
```
lambda s:0x42744262AEA01A914800A12C>>int(s,36)%155687%95&1
```
[Try it online!](https://tio.run/##XVJdj6MwDHzfX8HLXotknUq37X5Iu1K1un9xL6YEYggOSgIs/PmeE24f7l7GI2yLmXGGJWjLT/f6/ffdYF9WmPm3w9fp@Hw6HS/H66/robi@FqeXw@FaHD8/PojD3sPTJX8szufLy/Pj6/lHcQ9uDNpn79kOKzWhwwBoKGjygN4aKBWjE3Qj3DT2UNlGaGWd9QFqsg6amRxo9AialnEioAZXIIcdMjD21USGYMBAynsYLFsYHE4VTUskc7XSvIBHTVqQqwicYHTgNTGImg6C9QSiVsGkHCYI8llqJcrJ2W@6McURKWBp0gYvbSypN3qYHBLMKNZm1A5WrXj30w/ifL@DXf7wUKPxasuFo8HSKWzwpiMZE7mlHErRoMRcVBd3Ekg37ScUn20i3YYhFZtw3HDbWhfJocbxCxo0cocG7SgwQ6NsS0Ey7uUqrZaDIbSE0Clzgx5NCkR6CCxSnKLVR/YdMqstDyZRZDm5FsUKBq9kwoNDbmLW8lcdE@8cwYJspLUi1f8GM7j4kNCYfb33eVZbl/mMONseUp7/HWAbMuTlv6Et1Ty//wE "Python 3 – Try It Online")
---
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~30~~ ~~29~~ 28 bytes
```
4öŽ3¹%Ƶ™%84%o•1±87÷Јù³Í:•&Ā
```
[Try it online!](https://tio.run/##TZJLTsMwEIavgiqVFRsEEhVXQSwmjRtP4tqVHwmJhNQFYofEGXoDhArqgk0DbJA4RC9SnLEdsfo@O@PH/I4ykCE7/m6Pl/3b18fFfjf93h4eNtPZ5VQd1pvz/cvsqn/vn38e@93@tX@69pOnn@vj/fFmAjmrQYOdnJ1MQKDlaEiNEgMzJkEH0W7gnMNyYK6KMJErrQwtX6Ci0qJBIgcDRGxdjYNhAR1RQwVyMAnLvEZBX1dgkRk6fqWkImqoc6zb6E3eYUMDAxx5EJlHykRHxxuONONbqojK0DFWOzawZhoSbSjxmvtAUKt/o3HAZBS0kIm0h2zLaKnOUQu1BjqugRBgA5zY8bAPyBhTphkUMOfRXfJ5yjcLl2M@n9jCAoRJDMWDsSQ@sDJ5NYpNppK4UcbdujbkuwB3R28JIvwbBSgX2BCYKtGGV16GX6bkznJKtERCxcR84BJEytqXEqVvRjPsTBz8e2bJxqglhp6UTCH6CGhmZZhfQKs1yCI@uL8rjy9faQqqBSlCWQe4mNz@AQ "05AB1E – Try It Online")
```
6öŽ9{%521%76%o•B&¦¿³ʒв F6•&Ā
```
[Try it online!](https://tio.run/##TZJLTsMwEIavUlVqV2xAoogtCy6BWEwSN57EsSs/EhKE1DNwBBYcAAQ7hFRgwwJxBi5SnLEddfV9dsaP@R1lIEO2/3nZrz5ev97ObxenJ8eLs9VC/W0fLpa7x9377vn7/vdpdrnyM8vP7f5ufzWHgrWgwc6PZnMQaDkaUqPEyIxJ0EG0G5lzaEYWqgwThdLK0PI1KiotOyRyMEDE3rU4GpYwEDXUIEeT0BQtCvq6AYvM0PEbJRVRQ1tg20fvigE7GhjgyIPIIlImOjrecKQZ31JNVIaOsdqxkS3TkGhDidfCB4JaHYymAZNR0EIm0h6yr6KlOkcttBrouA5CgB1w4sDDPiBjTJlmUELOo7vkeco3C5djPp/YwhqESQzFo7EkPrAqeT2JTaaSuEmm3YY@5LsGd0NvCSL8GyUoF9gRmKrQhlduwi9TcWc5JVohoWYiH9mASFn7UqL0zWiGg4mDg2eWbIpaYuhJyRSij4BmNob5BbRagyzjg/u78vjytaagepAilA2A6/n1Pw "05AB1E – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-n`, ~~54~~ ~~49~~ 47 bytes
```
p !/^[fgmryz]a|[ncks][erw]|[bjm][hir]|ep|la|te/
```
[Try it online! - truthy](https://tio.run/##NY9bboQwDEX/7yraBVSzIEQlM8kQD@BEzktBrL00UPXn3CNblq41T@08w8fn43t4zZu2faRjkOcSx8FqHY9hem/j4FjHw4ZjpSPZx3mSsYWUEmjl5DiCol8xWSHt1Iynow3Gz12NVx8TXuwVc2WFo0hw3HJh8Ew7WGkhgdBmCq@MQIltjAhePIJSMVzaJdXsXBsiOXadYi7IjayIjgW9zYLkIyNptihW6Ubq456mN2f1//pnVi5yomm9L6S9r7h3OaIoMSr11yo5xe6s/PiQ2Es8v@QX "Ruby – Try It Online")
[Try it online! - falsy](https://tio.run/##JY5BboQwDEX3PkV7gGoOhKhkGENMQoKcBBrE2Sc1YfP8pG/LX/JQat2@vl@/3TSvUs4er86PNvYdydFf3bCsfWdY@ou2y@GV6FUr@oMFBiGccTS35CajZHiHgS3QhilEhgldbND0HtTIe1ma2IepjdCYHz5XZzmKSv6DGR0mZciKA2YKCycwuHKExeRkEBZGsORGWNHtJAiaIXitIsRnvE1wf@tzVV0gD561UfAHooA2Jtgi6UYEQT9ngahfDUTDVhgKeqfRiTx9wpY4@Fh//D8 "Ruby – Try It Online")
Thanks to Dingus for a byte saved and Value Ink for inspiring another -2.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~68~~ ~~67~~ ~~60~~ 58 bytes
```
^(n?a[^n]|be|ch|gw|p[or]|sa[hn]|h?[itvw]|zh)|as|ss|in|og?r
```
[Try it online!](https://tio.run/##DchBCsIwEAXQfe4h1KUnyNJDhJR@dWwCZSozsQH5d499y2fSquI2LtN9GfOkEWnWzIfwWbh2ftJumY5Uzi0x1Xb0zF@5Ek53VuW@Rhuj2VfCG5tLwEsOGFqA9mp/ "Retina – Try It Online")
Regex that matches all truthy values and none of the falsey ones.
[Verify all truthy inputs](https://tio.run/##NY9BboQwDEX3vkel6bInYNlDIEb9TFLiDuMgOyQC5e40UHXz/tO3LNnqEws@jrfb59dxv0mH/i5DHX19hDqVuvRRh2roQ2tD13PKZah7eK@walZZapw6PQ44n6FIhJlTYCNYnGn0Am3UlR4BL3JxauqiRkv0zVFpKqwUYKDA25qZeMJOrHhCSPBymWemBYm9GS1RIi2K7DhvpxS3c9nIEDg0ijshF1YlCyzUrnlSisaUdPWUveJCanVL1y5njf/6Z15OcsI4Xxuy/ZxxzVajrGAqaK8VBKU9ePkF "Retina – Try It Online")
[Verify all falsey inputs](https://tio.run/##JY5BjoMwDEX3vsdIneWcgOUcAlGNS93EQBNkJ1BQ7s6YsHl@ynfkL5Q44M/xdfv9O@630GB7D115UOl9cWuZ2yhdUWy9vfqm5bSsXdn9d0EtqoVDia6R48CwssBDCB32/pRcpZcMz/jgEWjGFJXhhZNWWHoOquRlG6qMF1MdsTJfvH7t27qZ5A84nDAZYzas4CgOnMDjmxUGn5NHGBhhpKmHN04LCYJlCMGqCPGupwkuTztuagsUILA1imFFFLDGBLOSbSgIBpcF1K56UM@jMGwYJot25Nc/ "Retina – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~55~~ 52 bytes
*-3 bytes thanks to @G. Sliepen*
```
f(s){s=0x4240165C085F34>>a64l(s)%19537U%11702%56&1;}
```
[Try it online!](https://tio.run/##fVPBjpswEL3nK6xIqUi3lWBDso3S3Uul/kFPqz1MwMAkYCPbwEKUb0/tsZON2qqn8cwbv/GbB9nXMssulyLSy5N@jt/TxzRONusf8bf1z1X68gKbtLbYItmuV0@/FknyFD8u1ptPye58ySpQn9k@eU3jN/bMTnMNFVbzL2yOCo4g3Am0rF0sB1Qu9lxxEQ5oYF/ze7RV0OfYj@6sQeQuDgCEGdXxcBEolxopV4ChnkPOUUmXCWjyHmv0DBUxQI2mQu2OFY5dT6CtHOnJJUxhrOiofc@Fn1ygvL6duHWFJMHqb0K9I9YWDHJNx6nyMlsp6E4uldQmaBzyCQcSaR/cgwITaMR48JNV98dgJy1Mtw8kCaDBM5e@2y3GeDG0z/NuFhyKX1db79AEWLiGI68zFxv0JCVI4hD8ZlABtfbQ4JF7cxxIk6S4@uNKZFAD9dUjbjcSbCqge7@2kY4saLR5Rh9Nq7nl12HDR0XXDlVnKvB6Gw8qEKV3SEMNdHWvOJTgaW4DBPr3lFwe0Fwh75RVA4rjRMkBIbjn@y3rrX0ah/F@Gy7aHRxudGF899d4WpG5X/IIovYScrn3RoEITs1QGNYAimjJTjNWSMUiV0JrW7yz4TtLXXx4IJy1yqJFNF90zPIUkf0L8W253M3YedZ2RkfzuUv@xbPa/o8n/uA5X34D "C (gcc) – Try It Online")
The strategy used is the same as in [@ovs's answer](https://codegolf.stackexchange.com/a/205466/88546). We brute-force values corresponding to each string, making sure that no two `truthy` and `falsey` words share the same value. The answer is then extracted from a binary lookup table.
Here, the `a64l()` function converts a given string into a 32-bit signed integer.
[Answer]
# x86-64 machine code, 27 bytes
Hexdump:
```
6b 01 35 c1 e8 06 6b c8 d3 d1 c1 48 ba 4e 88 00
02 c3 45 88 8b 48 d3 e2 1a c0 c3
```
A function which receives a pointer to the string in `rcx`, and returns the result in `al`.
−1 means `true`, and 0 means `false`.
Assembly source code, using `ml64` (MASM) syntax:
```
.CODE
my PROC
imul eax, dword ptr[rcx], 53
shr eax, 6
imul ecx, eax, -45
rol ecx, 1;
mov rdx, 8b8845c30200884eh;
shl rdx, cl;
sbb al, al;
ret;
my ENDP
end
```
Disassembly, while stopped on a breakpoint at the start of the function:
```
00007FF73978F4A0 6B 01 35 imul eax,dword ptr [rcx],35h
00007FF73978F4A3 C1 E8 06 shr eax,6
00007FF73978F4A6 6B C8 D3 imul ecx,eax,0FFFFFFD3h
00007FF73978F4A9 D1 C1 rol ecx,1
00007FF73978F4AB 48 BA 4E 88 00 02 C3 45 88 8B mov rdx,8B8845C30200884Eh
00007FF73978F4B5 48 D3 E2 shl rdx,cl
00007FF73978F4B8 1A C0 sbb al,al
00007FF73978F4BA C3 ret
```
It uses hashing, like many other answers. The hash function uses the first 4 bytes of the string - by luck, all strings are at least 4 bytes long (including terminating zero byte). It does the following:
* Multiply by 53, ignoring overflow
* Shift right by 6 bits
* Multiply by -45, ignoring overflow
* Rotate left by 1 bit
* Access the 64-bit hash table, using 6 LSB of the result
Found by brute-force search. The search space was 8 + 5 + 8 + 5 = 26 bits. The "rotate left" bit count is 1 by luck, which reduces code size by 1 byte, compared to the general "rotate left" case.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 70 bytes
```
¬{~ṇ"pate
shik
dob
sal
ham"∧"nezabrcrpsangagenifa"ġ₂;?,"yeojrkm"∋∋~a₀}
```
[Try it online!](https://tio.run/##TZKxbtswEIZ3P4XBOcnQNUDyIEWHk0SJJ9GkQYpSJMNG4QJtiix9hU7t0KFLh3Ys@iLWi7jkkRQCCPh@Ukce778rDJRikrp5cz2MbHv7sGXj4@G0fPy5nD8sz99Ybxy/Y3fL83dWg7ReHy9/Ph8vv75c//44nC6/P7E99HxjBXabShcbC3IjYMfCYcVnKExp9hZUAw1XWAP793U5n@8fb9jEdWu6EPnivxMs5/fH6/Utg4oPYKBnN1sGEnuBlqTVMrDgCkwUxgWWIZ1npZu4UWmjLR2vUVNoMyJRgAUiTm7AoLCBmWigAxWUgl01oKS/vjTkltLvtdJEA0OFw5T0WM040sKCQBGFqhJVpqP03iTa8SV1RG0pTTA5cOAGMvsY4mXlDUGjX63WBVdJYA@FzHeoqU0qxzkqYTBA6UaIBo4giLOI94BKNhWGQ@MHI2mXdZn9LeLjuPcnlRCGIzMG07hk4Q1rs@5W0Wels3CrWG@bp@hvDe6JegkyzkYD2kWOBD9O2Mcu7@LItML1ghxtkdBxWQbuQGavfShR@WIMx9mmxas2K75arTDWpFU2MUw/0XJ/gE4bP@2p4f6tInW@M2TUBErGsBmwZu/@Aw "Brachylog – Try It Online")
Takes input through the output variable and outputs through success or failure.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 41 bytes
```
¬∨⁼θgaw⊙⪪”&⌈→⊖L↓&s⦃R⁹CV÷⊕O⸿↔Vf‴λ⌕9↶7”²№θι
```
[Try it online!](https://tio.run/##FcxBDoIwEEDRqzRdDUnduHVljFs18QRDM8BAaWFoJXj5sf79f35A8QmD6ks4ZnikDE@B@1owbLA6Y3vcbePMNR7wXgJnsC234oWWDvsyDiNPNEnAGWeOFPdUNsp04BetM@d63lKpcKW4@XdR7apNevqEHw "Charcoal – Try It Online") Link is to verbose version of code. Output is a Charcoal boolean, i.e. `-` for true, nothing for false. Explanation:
```
θ Input string
⁼ Equals
gaw Literal string `gaw`
∨ Boolean Or
”...” Compressed string `bibrcrepfagujhjikekrlamaminenwouseteyaza`
⪪ ² Split into substrings of length 2
⊙ Where any is nonzero
№ Count of
ι Current substring in
θ Input string
¬ Boolean Not
Implicitly print
```
[Answer]
# JavaScript (ES6), ~~63 62~~ 60 bytes
*Saved 2 bytes thanks to @Neil*
A regular expression that matches all falsy words and none of the truthy ones.
```
s=>!/ao|mi|ob|w$|[gnst]e|[bck]r|[flz]a|^[ejkmry]|nw/.test(s)
```
[Try it online!](https://tio.run/##bVJNi9wwDL3Pr3ChkBmqZu8t2bLQXShdKLTb0zALSuLEyocdbCdpQv77VHa6h8Jcnh6WLT89qcEJXWFp8B@1KeW1yq4uu393h2braTP5Nr/fzrV2/iK3c160F7udq2694PZ6lk3b2@Wy6fku9dL5oztdX37@fhSZSLCUE1r0gB15RQ7QmQ5yqdEy2hEKhT2UpmZaGmuch4qMhXomCwodgqJlnAioxhXIYosaNPblRB3BgJ6kczAYbWCwOJU0LYHM5UrzAg4VKUZdBtARRgtOkQZW04I3jsDbUcIkLUbwfMyxZOVkzRvdmdQByWPexRd6aUKIudHBZJFgRm5tRmVhVVInqRu482MCyenz4fD08Pxr90WHBnMrscZCBTJGUkQfctYgubmgrsLOReBsCDIi99lE0u7oYzARxx33V@vCPlQ4/oEaO55DjWZkmKGWpiHPHvc8lUaNXiE0hNDKroAeu2gI5xA0S7GSVhfYm8la7n5oYkVGx65ZsYTBSb7hwKKug9f8qwqOt5ZgQd1xakWqkvTwnzOF0bwZMu1MfUxeeItI1yJu0SeRiA/iGHgaPl2OTmT3ouI1E1mWiTC@k/gikh/fk3D56eHb8@PX5HS6XTOO4F/NyG8WjU7frHr9Cw "JavaScript (Node.js) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~41~~ 39 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
.•6ðó_ ï²£Ëý¾Sð7§Ê³®6´¡Žmã•2ôåàI…gawQ~≠
```
-2 bytes by using a shorter compressed string from [*@Neil*'s Charcoal answer](https://codegolf.stackexchange.com/a/205470/52210), who apparently uses the exact same approach.
[Try it online](https://tio.run/##AVAAr/9vc2FiaWX//y7igKI2w7DDs18gw6/CssKjw4vDvcK@U8OwN8Knw4rCs8KuNsK0wqHFvW3Do@KAojLDtMOlw6BJ4oCmZ2F3UX7iiaD//2dhdw) or [verify all test cases](https://tio.run/##RZG/jtQwEMZfZZX6REFxlPcMiBIhNNl440kce@U/CUmBrkICOp7g4AR0cOKuPYpYvMi@yDJjO7rGv2/kGc/4G@OgRnEe56tqd/rwZVddzednp@tvl/Eu3r/dxd/rn/U2fo6P699X8e7F@jN@Wu/XX5frw/r13@MQbyn3eXyI3@PNfLr@0cL08v3p48354vy6gkaMYMFXFxUo9BIdK2cUoRYabKINhL2EgdCYNoWNscZx3QENZ7UTMiQ4YOAcRiSBLSwMCz1oEhqGZkTFV0fwKBw3PBptGBbGBsc5y6lZcGLtQKJM1E2GLgjc0UnkmGbvGcbx294GQRiFhQKfrkk19Ge05inYtNCZ6KFWpVrPXRYlJ/C4owXuMUGyZwLJWGSqB519qK2AFvYyy1DkvlhXp2EEOZDHPYByBSmPhSgkQ7oi@42@CFMYNm6vLHOy7gDhHe8GVFpxCyYkTHwK06FPKxvS2jsZvGS7OuSzF2pPGEAVFymLoWlsK3BxWT/tTIvNRI1peqOLRfRPjo9OUC7XWdBtXh5NJvMSe8tOzKBVSlkAD9Wb/w).
**Explanation:**
```
.•6ðó_ ï²£Ëý¾Sð7§Ê³®6´¡Žmã•
# Push compressed string "bibrcrepfagujhjikekrlamaminenwouseteyaza"
2ô # Split it into parts of size 2
å # Check for each whether it's a substring of the (implicit) input-string
à # And check if any is truthy
I # Push the input again
…gawQ # Check that it's equal to string "gaw"
~ # Check if either of the two is truthy by using a bitwise-OR
≠ # And invert the boolean (!= 1)
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `.•6ðó_ ï²£Ëý¾Sð7§Ê³®6´¡Žmã•` is `"bibrcrepfagujhjikekrlamaminenwouseteyaza"`.
[Answer]
# [Io](http://iolanguage.org/), 109 bytes
-10 bytes thanks to Neil.
```
method(x,"bi br cr ep fa gu jh ji ke kr la ma mi ne nw ou se te ya za gaw"split select(i,x findSeq(i))size<1)
```
[Try it online!](https://tio.run/##hVK7jtwwDOz3KwhXuwCbtIdcez@QlGlom7Zoy5Kjh732z28o7d4BaRLBGA5E0hqOJP4xwNs7/HosnIzvr3dsWoE2QBeAVxgIxgyTgUlgZpgDWIJFPwHH4HbwGSJDYjgITi2mvYmrlaS7lrt0FbzDIK7/wb@vcrtFOfn7t9vjZ8jJHOXkhnreKFBC0jYjESl6iy07CoohY2dowd6PSnsffEw4iA847hLQUCQ0cuRNUEY6UQLN5NDR0m9iBVdKwjHi6p3HNdDWy3YUsven7AdGMmIUXV/AVcgBoxGHqmbG5KNgCplx40AVkm5r7FW5BP9Jn4xdQUnU2trhjqmEmssRt0CCO@loO5mAp2HXQDXs2mBzu1w@yMaXL64M2AamkTpTSK6kqz60qoF1uKJu0J4Kmi2BK@qcUyXzE1MNvmJ@4rPrPNSHgfIdR7J6DyP5rLDjyH6SpB4veiuT0RsjnIRwZtvhQrYaojlCp1ICyxkL@zTZ8dMPJ6rIuzq1KmZcI2tFxEBuLF7rqaY4PgfBg5zV1Eky/G3M68UMXg3pjL7TC@garvcbrEFcsu6iVc37/1fz1fBy@5//fPwB "Io – Try It Online")
# [Io](http://iolanguage.org/), 119 bytes
Searches for prefixes of existing values.
```
method(x,"dob fa ga ham an br cr e pate ge j k ma mi ne ni on ps sal shik ra ya za"split select(i,x findSeq(i)==0)size)
```
[Try it online!](https://tio.run/##hVKxrtswDNzzFYSnBODQuUDW/kA7dmFs2qItU64k27F/PqWU9wp0aTUcD6YoH4@U8Orh6x1@vmbOLnTXJzZdeEBPMBA4moEUHhHaCAwLZYaBYYQJZoJZQBlUICgsCRJ5SE4miAQHwUlNWrxkSOy5zVfBJ/Si3Xf@dZXb/f7lluTk2@tHXLM7ioaGOt4oUkayOicJKQWPD1aKhnHF1gRhFwajXYghZewlRBx2iegoETo51k1QBjpRIk2kqDR3m3hBUy@cEi5BAy6Rtk62o5C9O2U/MJETZ6hdAa2wRrSWFE3NhDkkwRxXxo0jVcj22WJnyiWGT/pmrAUl08PXCj3GEmpuTbhFEtzJWtvJRTwdawPVsWuDze1y@UY@ffiipcFHZBqodYWslbTVh4dpYGuuqOutpoJlS@CK1udYyfTGXEOouL7xXXUe5kNP6xMH8jaHgcJqsOPAYZRsHs82ldHZxAhHIZzYtziTr4ZYjlBNSmQ5U2GfJiu//VAxRUFr12WZcElsNxJG0qF4bX91xfEpCh6k3lInSf@3MR8b0wczpHW2sRew01@fN1iiaPZ6sVvN/f@n@VPw4fY/33z9Bg "Io – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~125~~ \$\cdots\$ ~~101~~ 95 bytes
Saved a byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
```
#define f(s)!index(" %&(-.049;ADHJQRSYZis",*s**s*s[l=strlen(s)-1]*s[l-1]%3519%163%108%92+32)
l;
```
[Try it online!](https://tio.run/##pVPfj9MwDH6/vyIUFbX7AdsNENM4JCQeEG/AE9ztwWvT1luWTEm7Xnva3z4SJ9sNEDxAVclxbH/2ZzvZuMyy4/FpzguUnBWJSZ@gzPl9ErH4WTJ@Pnk5X7z/8PHT5y9fv31HE40GZmB/cytuTK0FlzZiPF26Cyvi2avpPJ6@nsXTyZt4fj2cXadXYnHcAsokZQ9XzH5ZBXpQ64ab2yW7YQ@RgQqraMQi1LAB6U5glHCybFE7ueeay3DAGlaCX1p3GvY57jt3NiBzJ1sAsrlEIRBIVwZJ14DhPoeco1ZOk7DN9yjQI1SEAALrylFnUYVdsyejvdlQySX0Ia1syH3Fpc9coDrVTtimQqJg@W/DfUOoO6iRGzr2lae5U5JicqWVqQPHNu@xJZK24D1oqAOM7NY@s25@Seyohey2QKIABjxy6b1dY2pPhvp5WDxOqQBh3JjclHrAwjltuMic3KIHKkERjuTnIbkwb2q95XJAzkjZlDzNiNIQJojTnLjtShhVAc39yY24ZIGn1TNanJ3hFt@ELm80ha2rpq7Ac956owZZ@ikZEEChK82hBA9zTiDR11Nytcb6ZPLTsmxAc@xJWSOECXp/i3p277u2u@yGk7YH6zNcSN/8lp5aVF82uQMpPIVcrfywQF5Ma6dR1kUSjX/6mFt@Nv7Ddyej1EcXSrPEAjC073GysOItM9hzVST0TtMXQaOlSBdsOMTTa77MHhs2fsfi/M5tgX/huByxgGLPaUh4@FvRtA3sf4r2a/tPVYeN92Wflce6D8cf "C (gcc) – Try It Online")
Inputs a string and returns \$1\$ for words meaning 'true' and \$0\$ for words meaning 'false'.
**How?**
The first, second to last, and last characters of all the word strings form a unique triplet of characters across all words. Multiplying the ASCII values of first character squared and the other two together yields unique 32-bit integers across all words. These numbers modulus values found by a Python script yield a distinct set of integers for all 'false' words in the range \$(0,96)\$. These numbers can then be transformed back to printable ASCII characters by adding \$32\$ to them. Then it's simply a test if a string put through these calculations yields a character that can be found in a given string (also generated by the Python script).
] |
[Question]
[
I like to think of a 10-adic number as a number that goes infinitely to the left, or an integer modulo a very very large power of 10.
Things carry infinitely to the left and vanish. To see what I mean, note that `...6667 * 3 = 1` in the 10-adic land, since the "2" that carries to the left goes to infinity.
Addition and multiplication make sense for 10-adic numbers, since the last `n` digits of the sum/product only depend on the last `n` digits of the summands/multiplicands.
---
Given `n`, you need to print the last `n` digits of the 10-adic cube root of 3, i.e. `x` satisfiying `x*x*x = 3`.
It ends:
```
...878683312291648481630318492665160423850087895134587
```
---
**Your code must terminate for `n=1000` before submission.**
Let's say that if the number you need to print begins with zero, then you don't need to print the leading zeroes, since it isn't actually the point to print extra zeroes.
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in bytes wins.
[Answer]
# [Python 2](https://docs.python.org/2/), 33 bytes
```
lambda k:pow(3,10**k*2/3+1,10**k)
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHbqiC/XMNYx9BASytby0jfWNsQwtb8n21raGBgwFVQlJlXopCmka0JYUIFQNpAgjrGMPUA "Python 2 – Try It Online")
The `pow` function efficiently computes the modular exponent `3**(10**k*2/3+1)%10**k`.
We're asked to find a solution to `r**3 = 3 (mod 10**k)`. We want to find an exponent `e` for which the map `x -> x**e` is inverse to cubing `x -> x**3` working mod `10**k`, just as the decryption and encryption exponents in RSA cancel to produce the original value. This means that `(x**3)**e = x (mod 10**k)` for all `x`. (We'll assume throughout that `gcd(x,10) = 1`.) Then, we can recover `r` by inverting the cubing to get `r = 3**e (mod 10**k)`.
Expanding out `(r**3)**e = r (mod 10**k)`, we get
```
r**(3*e-1) = 1 (mod 10**k)
```
We're looking for an exponent `3*e-1` that guarantees that multiplying that many copies gives us `1`.
Multiplication modulo `10**k` forms a group for invertible numbers, that is those with `gcd(x,10) = 1`. By Lagrange's Theorem, `x**c = 1` where `c` is the count of elements in the group. For the group modulo `N`, that count is the Euler totient value `φ(N)`, the number of values from `1` to `N` that are relatively prime to `N`. So, we have `r**φ(10**k) = 1 (mod 10**k)`. Therefore, its suffices for `3*e-1` to be a multiple of `φ(10**k)`.
We compute
```
φ(10**k) = φ(5**k) φ(2**k)= 4 * 5**(k-1) * 2**(k-1) = 4 * 10**(k-1)`
```
So, we want `3*e-1` to be a multiple of `4 * 10**(k-1)`
```
3*e - 1 = r * 4 * 10**(k-1)
e = (4r * 10**(k-1) + 1)/3
```
Many choices are possible for `r`, but `r=5` gives the short expression
```
e = (2 * 10**k + 1)/3
```
with `e` a whole number. A little golfing using floor-division shortens `e` to `10**k*2/3+1`, and expressing `r = 3**e (mod 10**k)` gives the desired result `r`.
[Answer]
# [Python 2 (PyPy)](http://pypy.org/), ~~55~~ 50 bytes
-5 bytes thanks to [@H.P. Wiz](https://codegolf.stackexchange.com/users/71256/h-pwiz)!
```
n=p=1;exec"p*=10;n+=3*(3-n**3)%p;"*input();print n
```
[Try it online!](https://tio.run/##BcHRCoAgDAXQXwkh0IUw83Hsa0LQl3UJg/z6dQ7W7LedGQvL3RRapH3tCiAtLHZopVizEdW0QwINwztjEjzD5mbuhZl/ "Python 2 (PyPy) – Try It Online")
Calculates (non-bruteforcing) digit by digit, so it's faster than brute force.
[Version without exec](https://tio.run/##BcE7CsAgEAXA3lNsE9AVYY2kCeQwKfKxeS5iQE9vZnS0t2ANOnTMiSOau1TqlEH1xHPZDP2adT66Hf5IbFMAc3JLFOZutGY0wpybiPw)
### Explanation
(Thanks [@Leaky Nun](https://codegolf.stackexchange.com/users/48934/leaky-nun) and [@user202729](https://codegolf.stackexchange.com/users/69850/user202729) for figuring this out)
First, observe that \$n^3\$ is an involution modulo 10 (i.e. if the function is called \$f\$, then \$f(f(n)) = n\$). This can be confirmed using an exhaustive search.
We can use mathematical induction to find the next digit.
Let \$d\_n\$ be the \$n\$th digit of the number (from the right).
$$
\begin{align\*}
d\_1^3 &\equiv 3 &&\pmod{10} \\
d\_1 &\equiv 3^3 &&\pmod{10} \\
&\equiv 27 &&\pmod{10} \\
&\equiv 7 &&\pmod{10} \\
\end{align\*}
$$
Now, assume we know the number up to the \$k\$th digit, \$x\$
$$
\begin{align\*}
x^3 &\equiv 3 &&\pmod{10} \\
(d\_{k+1} \cdot 10^k + x)^3 &\equiv 3 &&\pmod{10} \\
m \cdot 10^{2k} + 3 \cdot d\_{k+1} x^2 \cdot 10^k + x^3 &\equiv 3 &&\pmod{10^{k+1}} \;\textrm{(for some } m \textrm{)} \\
3 \cdot d\_{k+1} x^2 \cdot 10^k + x^3 &\equiv 3 &&\pmod{10^{k+1}} \\
\end{align\*}
$$
We know that:
$$
\begin{align\*}
x &\equiv 7 &&\pmod{10} \\
x^2 &\equiv 49 &&\pmod{10} \\
&\equiv 9 &&\pmod{10} \\
x^2 \cdot 10^k &\equiv 9 \cdot 10^k &&\pmod{10^{k+1}} \\
3 \cdot x^2 \cdot 10^k &\equiv 27 \cdot 10^k &&\pmod{10^{k+1}} \\
&\equiv 7 \cdot 10^k &&\pmod{10^{k+1}} \\
\end{align\*}
$$
Substituting this in:
$$
\begin{align\*}
3 \cdot d\_{k+1} x^2 \cdot 10^k + x^3 &\equiv 3 &&\pmod{10^{k+1}} \\
7 \cdot d\_{k+1} \cdot 10k + x^3 &\equiv 3 &&\pmod{10^{k+1}} \\
d\_{k+1} &\equiv \frac{3 - x3}{7 \cdot 10^k} &&\pmod{10} \\
\therefore d\_{k+1} &\equiv \frac{3 \cdot \left(3 - x^3\right)}{10^k} &&\pmod{10} \; (7^{-1} \equiv 3 \pmod{10})
\end{align\*}
$$
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 21 bytes
```
PowerMod[3,1/3,10^#]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zgq/A/IL88tcg3PyXaWMdQH4gN4pRj1f4HFGXmlUSnRRsaGBjExv4HAA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~17~~ 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
7IGD3mN°÷7*θì
```
Port of [*@ASCII-only*'s Python 2 (PyPy) answer](https://codegolf.stackexchange.com/a/166418/52210).
-4 bytes AND bug-fixed for outputs with leading zeros thanks to *@Emigna*, by replacing `T%N°*+` with `θì`.
[Try it online.](https://tio.run/##MzBNTDJM/f/f3NPdxTjX79CGw9vNtc7tOLzm/39Lc3MA)
**Explanation:**
```
7 # Start result-string `r` at '7'
IG # Loop `N` in the range [1, input)
D3m # `r` to the power 3
÷ # Integer-divided with
N° # 10 to the power `N`
7* # Multiplied by 7
θì # Then take the last digit of this, and prepend it to the result `r`
# Implicitly output result `r` after the loop
```
[Answer]
# Java 8, ~~158~~ ~~156~~ ~~141~~ ~~136~~ 135 bytes
```
n->{var t=n.valueOf(3);var r=n.ONE;for(int i=0;i++<n.intValue();)r=r.add(t.subtract(r.pow(3)).multiply(t).mod(n.TEN.pow(i)));return r;}
```
Port of [*@ASCII-only*'s Python 2 (PyPy) answer](https://codegolf.stackexchange.com/a/166418/52210).
-2 bytes thanks to *@Neil*.
-20 bytes thanks to *@ASCII-only*.
NOTE: There is already a [much shorter Java answer by *@OlivierGrégoire*](https://codegolf.stackexchange.com/a/166422/52210) using an algorithmic approach utilizing `modPow`.
[Try it online.](https://tio.run/##pVCxTsMwEN3zFTfaqmoFMZowIHVgIB2KWBDDNXFTB8eJLpegqsq3h0sBiaETLJbvvXvP77nGEdd1@T4XAfsentDHcwLgIzs6YOEgX0aAWvZMg3w0D756FLZyBIW6CkdtRTMlcvSM7AvIIUIGc1zfn0ck4CyaEcPgtgd1q@0CkUDbfGMPLSl5HHyWWr9a3UUj08uyq7TVlJHBslRs@mHPhAUrMl37IS7aNENg34WTYrm3pYrmeZNfWK@1tuR4oAhkp9ku0bphHyTad8Kx9SU00l7tmHysXt8A9Vf13aln15h2YNMJxSGK9fXqv1rpyyf8TX2T/lOe/hhMyTR/Ag)
**Explanation:**
```
n->{ // Method with BigInteger as both parameter and return-type
var t=n.valueOf(3); // Temp BigInteger with value 3
var r=n.ONE; // Result-BigInteger, starting at 1
for(int i=0;i++<n.intValue();)// Loop `i` in the range [1, n]
r=r.add( // Add to the result-BigDecimal:
t.subtract(r.pow(3)) // `t` subtracted with `r` to the power 3
.multiply(t) // Multiplied by 3
.mod(n.TEN.pow(i))); // Modulo by 10 to the power `i`
return r;} // Return the result-BigInteger
```
[Answer]
# [Java (JDK 10)](http://jdk.java.net/), 106 bytes
```
n->n.valueOf(3).modPow(n.valueOf(2).multiply(n=n.TEN.pow(n.intValue())).divide(n.valueOf(3)).add(n.ONE),n)
```
[Try it online!](https://tio.run/##bY@xTsNADIb3PIXHO9RaAcbSDkhFYqBFKmJBDEcuCQ4X3ynxBVWozx4uEQKGTpY///psN2Ywy8Z@jNQG3wk0qcco5LCKXAh5xotVVjjT9/BgiOErAwjxzVEBvRhJZfBkoU0zdZCOuH55BdPVvZ6jAHc/nptZ3Rp5x1uq71nKuuwW5@AGKljDyMsN42BcLPeVutbYevvoP9Ufu0osOqHgjorXjE/bHYY5QSzPU0hprdHSQLZU/10ajbWJ7HdbvWA9ruZLD8deyhZ9FAzpEXGsKjRh0p8789d3med5WjRJTtlp/AY "Java (JDK 10) – Try It Online")
## Credits
* Port of [xnor's Python 2 answer](https://codegolf.stackexchange.com/a/166446/16236).
* -6 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)
[Answer]
# [Haskell](https://www.haskell.org/), 37 bytes
1 byte saved thanks to ASCII-only!
```
(10!1!!)
n!x=x:(n*10)!mod(9-3*x^3+x)n
```
[Try it online!](https://tio.run/##y0gszk7NyfmfZhvzX8PQQNFQUVGTK0@xwrbCSiNPy9BAUzE3P0XDUtdYqyLOWLtCM@9/bmJmnm1BUWZeiUqagqGBgcH/f8lpOYnpxf91kwsKAA "Haskell – Try It Online")
I use a similar approach to ASCII-only, but I avoid using division
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 15
```
3?Ar^d2*3/1+r|p
```
Uses modular exponentiation, like [@xnor's answer](https://codegolf.stackexchange.com/a/166446/11259).
[Try it online!](https://tio.run/##S0n@/9/Y3rEoLsVIy1jfULuopuD/f1NDAA "dc – Try It Online")
TIO calculates input=1000 in 21s.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 12
```
.^3h/y^TQ3^T
```
[Try it online!](https://tio.run/##K6gsyfj/Xy/OOEO/Mi4k0Dgu5P9/U0MA "Pyth – Try It Online")
Again, using modular exponentiation, like [@xnor's answer](https://codegolf.stackexchange.com/a/166446/11259).
[Answer]
# [Pyth](https://pyth.readthedocs.io), 23 bytes
Of course, this uses ASCII-only's approach.
```
K7em=+K*%*7/^K3J^TdTJtU
```
[Try it here!](https://pyth.herokuapp.com/?code=K7em%3D%2BK%2a%25%2a7%2F%5EK3J%5ETdTJtU&input=1000&debug=0)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~26~~ 22 bytes
```
≔⁷ηFN≧⁺﹪׳⁻³Xη³Xχ⊕ιηIη
```
[Try it online!](https://tio.run/##NY3NCsIwEITvPkWOuxBBycFDT@Kph0oQXyCmsVlINyU/@vixVrzNx3zDWG@SjSa0ds6ZJoaTFB673TMmAT0vtVzr/HAJEMVglp90o8kX0KFmKYY41hDhTrPLoFYmrlvQ8b3OvBQKEf94PEjRs01udlzcCLR130OdiAtcTC7gEbvWVNu/wgc "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⁷η
```
Initialise the result to 7. (Doesn't have to be 7, but 0 doesn't work.)
```
FN
```
Loop over the number of required digits.
```
η Current result.
X ³ Take the cube.
⁻³ Subtract from 3.
׳ Multiply by 3.
⊕ι Increment the loop index.
Xχ Get that power of 10.
﹪ Modulo
≧⁺ η Add to the result.
```
Now uses @H.P.Wiz's approach to save 4 bytes.
```
Iη
```
Print the result.
Here's a 28-byte brute-force version that takes cube roots of arbitrary values:
```
FN⊞υ⊟Φχ¬﹪⁻XI⁺κ⭆⮌υμ³IηXχ⊕ι↓Iυ
```
[Try it online!](https://tio.run/##LUxLCsIwEN33FFlOIILSnS4VoYuWoCeINdpgminJTHv8mFYH3sD79oOJPRqf8wujgCZMTB2PDxtBSqE5DcBKaJzg6jwV9bBXokOCFp/sEVoXOIHGpVhnkwi0L/yjxJ2iC@/WTHCzs43JAkslRinLrwu28LCyX3ndbUIf7WgD2Sc4ud2p0mWH4HjBJfxbXOSc66rOu9l/AQ "Charcoal – Try It Online") Link is to verbose version of code. First input is number of digits, second is value to root.
[Answer]
# [J](http://jsoftware.com/), 33 bytes
```
f=:3 :'((10x^y)|]+3*3-^&3)^:y 1x'
```
[TIO](https://tio.run/##y/r/P83WyljBSl1Dw9CgIq5SsyZW21jLWDdOzVgzzqpSwbBCHahEwdDAwAAA "J – TIO")
port of @ASCII-only's [answer](https://codegolf.stackexchange.com/a/166418/80062) but using fixed modulo 10^n throughout
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~23~~ ~~18~~ 17 bytes
```
*3:×7DṪ×+⁸
R⁵*çƒ7
```
[Try it online!](https://tio.run/##AScA2P9qZWxsef//KjM6w5c3ROG5qsOXK@KBuApS4oG1KsOnxpI3////MTA "Jelly – Try It Online")
I know `ƒ` will be useful.
] |
[Question]
[
# End the tabs versus space war
So, there has been a great deal of debate of whether to use tabs or spaces to indent/format code. Can you help the university settle the dispute, by going to an incredibly ~~crazy~~ unique method of formatting.
---
Your job is to write a full program or function which expands all tabs into four spaces. And then replaces a run of n leading spaces with "/(n - two stars here)/". You will receive input over multiple lines in any reasonable format (single string array of strings for each new line. Columnar array etc.)
---
Sample input [shamelessly stolen](https://esolangs.org/wiki/Brainfuck). Note that since tabs get automagically expanded to four spaces on SE I represent it as the "^" character, but you must handle tabs (codepoint 0x09) as well. **All "^" characters represent a tabulation.**
```
Calculate the value 256 and test if it's zero
If the interpreter errors on overflow this is where it'll happen
++++++++[>++++++++<-]>[<++++>-]
+<[>-<
Not zero so multiply by 256 again to get 65536
[>++++<-]>[<++++++++>-]<[>++++++++<-]
+>[>
# Print "32"
++++++++++[>+++++<-]>+.-.[-]<
<[-]<->] <[>>
# Print "16"
+++++++[>+++++++<-]>.+++++.[-]<
<<-]] >[>
# Print "8"
++++++++[>+++++++<-]>.[-]<
<-]<
# Print " bit cells\n"
+++++++++++[>+++>+++++++++>+++++++++>+<<<<-]>-.>-.+++++++.+++++++++++.<.
>>.++.+++++++..<-.>>-
Clean up used cells.
[[-]<]l
^this is preceded by a tab
^^two tabs
^^^three tabs etcetera!
```
Sample output
```
Calculate the value 256 and test if it's zero
If the interpreter errors on overflow this is where it'll happen
++++++++[>++++++++<-]>[<++++>-]
+<[>-<
/**/Not zero so multiply by 256 again to get 65536
/**/[>++++<-]>[<++++++++>-]<[>++++++++<-]
/**/+>[>
/******/# Print "32"
/******/++++++++++[>+++++<-]>+.-.[-]<
/**/<[-]<->] <[>>
/******/# Print "16"
/******/+++++++[>+++++++<-]>.+++++.[-]<
<<-]] >[>
/**/# Print "8"
/**/++++++++[>+++++++<-]>.[-]<
<-]<
# Print " bit cells\n"
+++++++++++[>+++>+++++++++>+++++++++>+<<<<-]>-.>-.+++++++.+++++++++++.<.
>>.++.+++++++..<-.>>-
Clean up used cells.
[[-]<]l
/**/this is preceded by a tab
/******/two tabs
/**********/three tabs etcetera!
```
---
Because the university needs space to download both Vim and Emacs, you are allowed very little storage for your code. Therefore this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") and the shortest code wins. You may assume that input is well formed and lines with less than four spaces (after replacement of tabs) may result in undefined behavior.
### Disclaimer
This "excellent" formatting strategy came courtesy of Geobits, and is reproduced with his permission. No programmers were harmed during the production of this challenge.
[Answer]
# Vim, ~~37, 34, 33,~~ 32 bytes
```
:%s/\t/ /g|%norm ^hr/hv0r*r/
```
[Try it online!](http://v.tryitonline.net/#code=OiVzL1x0LyAgICAvZ3wlbm9ybSBeaHIvaHYwcipyLwo&input=U2FtcGxlIGlucHV0IHNoYW1lbGVzc2x5IHN0b2xlbi4gTm90ZSB0aGF0IHRhYnMgZ2V0IGF1dG9tYWdpY2FsbHkgZXhwYW5kZWQgdG8gZm91ciBzcGFjZXMgb24gU0UsIGJ1dCB5b3UgbXVzdCBoYW5kbGUgdGFicyBhcyB3ZWxsLgpDYWxjdWxhdGUgdGhlIHZhbHVlIDI1NiBhbmQgdGVzdCBpZiBpdCdzIHplcm8KSWYgdGhlIGludGVycHJldGVyIGVycm9ycyBvbiBvdmVyZmxvdyB0aGlzIGlzIHdoZXJlIGl0J2xsIGhhcHBlbgorKysrKysrK1s-KysrKysrKys8LV0-WzwrKysrPi1dCis8Wz4tPAoJTm90IHplcm8gc28gbXVsdGlwbHkgYnkgMjU2IGFnYWluIHRvIGdldCA2NTUzNgoJWz4rKysrPC1dPls8KysrKysrKys-LV08Wz4rKysrKysrKzwtXQoJKz5bPgoJCSMgUHJpbnQgIjMyIgoJCSsrKysrKysrKytbPisrKysrPC1dPisuLS5bLV08Cgk8Wy1dPC0-XSA8Wz4-CgkJIyBQcmludCAiMTYiCgkJKysrKysrK1s-KysrKysrKzwtXT4uKysrKysuWy1dPAo8PC1dXSA-Wz4KCSMgUHJpbnQgIjgiCgkrKysrKysrK1s-KysrKysrKzwtXT4uWy1dPAo8LV08CiMgUHJpbnQgIiBiaXQgY2VsbHNcbiIKKysrKysrKysrKytbPisrKz4rKysrKysrKys-KysrKysrKysrPis8PDw8LV0-LS4-LS4rKysrKysrLisrKysrKysrKysrLjwuCj4-LisrLisrKysrKysuLjwtLj4-LQpDbGVhbiB1cCB1c2VkIGNlbGxzLgpbWy1dPF1sCgl0aGlzIGlzIHByZWNlZGVkIGJ5IGEgdGFiCgkJdHdvIHRhYnMKCQkJdGhyZWUgdGFicyBldGNldGVyYSE)
Note that this requires a trailing carriage return (enter) in vim, although not in the online interpreter.
This uses the V interpreter because it's backwards compatible. A very straightforward solution.
Here's a gif that lets you see the solution happen in real time. This uses a slightly older version, and I added some extra keystrokes to make it run slower so you can see what happens:
[](https://i.stack.imgur.com/OUizf.gif)
And here is the explanation of how it works:
```
:%s/\t/ /g "Replace every tab with 4 spaces
| "AND
%norm "On every line:
^ " Move to the first non-whitespace char
h " Move one character to the left. If there is none, the command will end here.
r/ " Replace it with a slash
h " Move to the left
v0 " Visually select everything until the first column
r* " Replace this selection with asterisks
r/ " Replace the first character with a slash
```
[Answer]
# Perl, 41 bytes
```
s,␉, ,g;s,^ ( +),/@{[$1=~y| |*|r]}/,
```
Run with the `-p` flag, like so:
```
perl -pe 's,␉, ,g;s,^ ( +),/@{[$1=~y| |*|r]}/,'
# ↑ └───────────────────┬───────────────────┘
# 1 byte 40 bytes
```
Replace `␉` by a tab (in Bash, try typing `Control-V` `Tab`.)
[Answer]
# [Cheddar](http://cheddar.vihan.org), ~~60~~ ~~57~~ 56 bytes
*Saved 3 bytes thanks to @Conor O'Brien*
```
@.sub(/\t/g," "*4).sub(/^ +/gm,i->"/"+"*"*(i.len-2)+"/")
```
I wish Cheddar had better string formatting.
[Try it online!](http://cheddar.tryitonline.net/#code=QC5zdWIoL1x0L2csIiAiKjQpLnN1YigvXiArL2dtLCBpLT4iLyIrIioiKihpLmxlbi0yKSsiLyIp&input=ICAgIGZvdXIgc3BhY2VzCiAgICAgICAgZWlnaHQgc3BhY2VzCgl0YWIgY2hhcmFjdGVyIHdoaWNoIGlzIGhvcGVmdWxseSBwcmVzZXJ2ZWQ)
## Explanation
This is a function. `@` is a represents functionized property (e.g. ruby's `&:`) letting you do things like: `ar.map(@.head(-1))
```
@ // Input
.sub( /\t/g, " "*4) // Replace tabs with four spaces
.sub(
/^ +/gm, // Regex matches leading spaces
i -> // i is the matched leading spaces
"/"+ // The / at the beginning
"*"*(i.len-2)+ // Repeat *s i-2 times
"/" // The / at the end
)
```
If you aren't familiar with regex the:
```
/^ +/gm
```
this basically matched one or more (`+`) spaces () at the beginning (`^`) of every (`g`) line (`m`).
[Answer]
# Mathematica, 97 bytes
```
a=StringReplace;a[a[#,"\t"->" "],StartOfLine~~b:" "..:>"/"<>Table["*",StringLength@b-2]<>"/"]&
```
Anonymous function. Takes a string as input and returns a string as output.
[Answer]
# Python 3, 124 bytes
Uses good ol' regex.
```
import re
lambda I:re.sub('^\s*(?m)',lambda m:'/'+'*'*len(m.group()[:-2])+'/',re.sub('\t+',lambda g:' '*4*len(g.group()),I))
```
[**Ideone it!**](http://ideone.com/1w8qim)
[Answer]
# Java ~~210~~ 207 bytes
This is the reference solution which implements it naively.
```
void a(String[]a){for(String s:a){s=s.replaceAll("\t", " ");String x,y="";int j,i=s.length()-(x=s.replaceAll("^\\s+", "")).length();if(i>3){y="/";for(j=0;j++<i-1;)y+="*";y+="/";}System.out.println(y+x);}}
```
[Answer]
# JavaScript ES6, 75 bytes
```
s=>s.replace(/\t/g," ").replace(/^ +/gm,k=>`/${"*".repeat(k.length-2)}/`)
```
Replace `\t` with a literal tab in your code.
[Answer]
# Java, ~~185~~ ~~184~~ ~~167~~ 152 bytes
```
S->S.map(s->{s=s.replace("\t"," ");String t=s.replaceAll("^ +","");int n=s.length()-t.length();if(n>3){s="/";for(;n-->2;)s+="*";s+="/"+t;}return s;})
```
Given the very loose definition of string array given in the initial post, I've used `Stream<String>` which allows for some consequent byte savings.
I used different techniques than the RI to achieve the same goal. The algorithm itself is rather the same.
**Testing and ungolfed**:
```
import java.util.Arrays;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
StringStreamTransformer sst = lines -> lines.map(line -> {
line = line.replace("\t"," ");
String trimmed = line.replaceAll("^ +", "");
int startingSpaces = line.length() - trimmed.length();
if (startingSpaces > 3) {
line = "/";
for(;startingSpaces > 2; startingSpaces--) {
line += "*";
}
line += "/" + trimmed;
}
return line;
});
Stream<String> lines = Arrays.stream(new String[]{
"lots of spaces and tabs after\t\t \t\t \t\t\t\t\t",
"no space",
" 1 space",
" 2 spaces",
" 3 spaces",
" 4 spaces",
" 5 spaces",
" 6 spaces",
" 7 spaces",
" 8 spaces",
"\t1 tab",
"\t\t2 tabs",
"\t\t\t3 tabs"
});
sst.map(lines).map(s -> s.replace(" ", ".").replace("\t","-")).forEach(System.out::println);
}
}
```
[Answer]
# [V](http://github.com/DJMcMayhem/V), ~~21~~, 20 bytes
```
Íô/
Î^hr/hv0r*r/
```
[Try it online!](http://v.tryitonline.net/#code=w43DtC8gICAgCsOOXmhyL2h2MHIqci8&input=U2FtcGxlIGlucHV0IHNoYW1lbGVzc2x5IHN0b2xlbi4gTm90ZSB0aGF0IHRhYnMgZ2V0IGF1dG9tYWdpY2FsbHkgZXhwYW5kZWQgdG8gZm91ciBzcGFjZXMgb24gU0UsIGJ1dCB5b3UgbXVzdCBoYW5kbGUgdGFicyBhcyB3ZWxsLgpDYWxjdWxhdGUgdGhlIHZhbHVlIDI1NiBhbmQgdGVzdCBpZiBpdCdzIHplcm8KSWYgdGhlIGludGVycHJldGVyIGVycm9ycyBvbiBvdmVyZmxvdyB0aGlzIGlzIHdoZXJlIGl0J2xsIGhhcHBlbgorKysrKysrK1s-KysrKysrKys8LV0-WzwrKysrPi1dCis8Wz4tPAoJTm90IHplcm8gc28gbXVsdGlwbHkgYnkgMjU2IGFnYWluIHRvIGdldCA2NTUzNgoJWz4rKysrPC1dPls8KysrKysrKys-LV08Wz4rKysrKysrKzwtXQoJKz5bPgoJCSMgUHJpbnQgIjMyIgoJCSsrKysrKysrKytbPisrKysrPC1dPisuLS5bLV08Cgk8Wy1dPC0-XSA8Wz4-CgkJIyBQcmludCAiMTYiCgkJKysrKysrK1s-KysrKysrKzwtXT4uKysrKysuWy1dPAo8PC1dXSA-Wz4KCSMgUHJpbnQgIjgiCgkrKysrKysrK1s-KysrKysrKzwtXT4uWy1dPAo8LV08CiMgUHJpbnQgIiBiaXQgY2VsbHNcbiIKKysrKysrKysrKytbPisrKz4rKysrKysrKys-KysrKysrKysrPis8PDw8LV0-LS4-LS4rKysrKysrLisrKysrKysrKysrLjwuCj4-LisrLisrKysrKysuLjwtLj4-LQpDbGVhbiB1cCB1c2VkIGNlbGxzLgpbWy1dPF1sCgl0aGlzIGlzIHByZWNlZGVkIGJ5IGEgdGFiCgkJdHdvIHRhYnMKCQkJdGhyZWUgdGFicyBldGNldGVyYSE)
This is literally just a direct port of my vim answer. The notable differences:
* The `Í` command (Global substitute) automatically fills in the `/g` flag, which saves two bytes
* `ô` is identical to `\t`
* `Î` Is a mnemonic for `:%norm`, and it also fills in the necessary space between `:%norm` and the set of keystrokes.
* The trailing carriage return at the end is implicitly added.
[Answer]
# [Retina](http://github.com/mbuettner/retina), 25 bytes
The `\t` should be replaced with an actual tab character (0x09).
```
\t
4$*
%`^ ( +)
/$.1$**/
```
[Try it online!](http://retina.tryitonline.net/#code=CQo0JCogCiVgXiAgKCArKQovJC4xJCoqLw&input=Q2FsY3VsYXRlIHRoZSB2YWx1ZSAyNTYgYW5kIHRlc3QgaWYgaXQncyB6ZXJvCklmIHRoZSBpbnRlcnByZXRlciBlcnJvcnMgb24gb3ZlcmZsb3cgdGhpcyBpcyB3aGVyZSBpdCdsbCBoYXBwZW4KKysrKysrKytbPisrKysrKysrPC1dPls8KysrKz4tXQorPFs-LTwKICAgIE5vdCB6ZXJvIHNvIG11bHRpcGx5IGJ5IDI1NiBhZ2FpbiB0byBnZXQgNjU1MzYKICAgIFs-KysrKzwtXT5bPCsrKysrKysrPi1dPFs-KysrKysrKys8LV0KICAgICs-Wz4KICAgICAgICAjIFByaW50ICIzMiIKICAgICAgICArKysrKysrKysrWz4rKysrKzwtXT4rLi0uWy1dPAogICAgPFstXTwtPl0gPFs-PgogICAgICAgICMgUHJpbnQgIjE2IgogICAgICAgICsrKysrKytbPisrKysrKys8LV0-LisrKysrLlstXTwKPDwtXV0gPls-CiAgICAjIFByaW50ICI4IgogICAgKysrKysrKytbPisrKysrKys8LV0-LlstXTwKPC1dPAojIFByaW50ICIgYml0IGNlbGxzXG4iCisrKysrKysrKysrWz4rKys-KysrKysrKysrPisrKysrKysrKz4rPDw8PC1dPi0uPi0uKysrKysrKy4rKysrKysrKysrKy48Lgo-Pi4rKy4rKysrKysrLi48LS4-Pi0KQ2xlYW4gdXAgdXNlZCBjZWxscy4KW1stXTxdbAoJdGhpcyBpcyBwcmVjZWRlZCBieSBhIHRhYgoJCXR3byB0YWJzCgkJCXRocmVlIHRhYnMgZXRjZXRlcmEhIA)
### Explanation
```
\t
4$*
```
Replace each tab with four spaces.
```
%`^ ( +)
/$.1$**/
```
Transform each line separately (`%`) by matching `2+N` spaces at the beginning of the line and replacing it with `/.../` where `...` is `N` copies of `*`.
[Answer]
# Python, ~~125~~ 111 bytes
```
lambda s:'\n'.join(('/'+(len(L.replace('\t',' '*4))-len(L.strip())-2)*'*'+'/'+L.strip(),L)[L[0]>' ']for L in s)
```
<https://repl.it/DGyh/2>
[Answer]
# SED (56 + 1 for -r) 57
```
s/⇥/ /g;tr;:r;s,^ ( *) ,/\1/,;T;:l;s,^(/\**) ,\1*,;tl
```
Where `⇥` is a tab
1. replaces tabs with spaces.
2. replaces the first and last leading space with `/`.
3. replaces the first space after `/` and 0+ `*`s with a `*` until there isn't a match.
[Answer]
The university should consider allowing a bit more space for programs in Emacs Lisp (or default to `tabify` and `untabify` alone), as they get even more verbose than Java. It should also pay close attention to students (or teachers) whose identation size is smaller than four or who happen to code in some non-C-like language.
The following solution has **206 bytes**
```
(lambda (b e)(let((tab-width 4))(untabify b e)(goto-char b)(while(re-search-forward"^ +"e t)(replace-match(format"/%s/"(apply'concat(mapcar(lambda(x)"*")(number-sequence 1(-(length(match-string 0))2)))))))))
```
Assuming that `tab-width` needs not to be explicitly set, we can save 20 of them.
```
(lambda(b e)(untabify b e)(goto-char b)(while(re-search-forward"^ +"e t)(replace-match(format"/%s/"(apply'concat(mapcar(lambda(x)"*")(number-sequence 1(-(length(match-string 0))2))))))))
```
And ungolfed version would look like this
```
(defun end-tab-war (beg end)
(let ((tab-width 4))
(untabify beg end)
(goto-char beg)
(while (re-search-forward "^ +" end t)
(replace-match
(format
"/%s/"
(apply 'concat
(mapcar (lambda(x) "*")
(number-sequence 1
(- (length (match-string 0))
2)))))))))
```
We first `untabify` the region before jumping to its start. Then, while we see whitespace at the beginning of a line, we replace it with a comment that is as long as said whitespace. To be exact, the comment to be inserted is constructed by
```
(format"/%s/"(apply'concat(mapcar(lambda(x)"*")(number-sequence 1(-(length(match-string 0))2)))))
```
which itself takes up 97 bytes. A shorter solution to copy some string n times is highly appreciated.
[Answer]
# Ruby, ~~52~~ 47 + 1 (p flag) = 48 bytes
**Edit**: saved whole 5 bytes, thanks to Value Ink
```
ruby -pe 'gsub ?\t," "*4;sub(/^ +/){?/+?**($&.size-2)+?/}'
```
[Answer]
## GNU sed, ~~66~~ 64 + 1(r flag) = 65 bytes
**Edit:** 1 byte less thanks to [Riley](/users/57100/riley)'s suggestion.
```
s/\t/ /g
s,^ ( *) ,/\1\n,
:
s,^(/\**) ( *\n),\1*\2,
t
s,\n,/,
```
**Run:** sed -rf formatter.sed input\_file
The reason for separating with a `\n` the leading spaces from the rest of the text on that line, is because otherwise a C++ line starting with a comment like this `/* */` would be turn into `/*****/` by a simpler line 4 like `s,^(/\**) ,\1*,` or even `s,^(/\**) ( */),\1*\2,`. Since sed executes the script for each input line, no `\n` is introduced in the pattern space on reading.
] |
[Question]
[
## Input
Your input is a list of single-digit numbers in any reasonable format, including a string of digits.
The input will not be empty.
## Output
Your output shall be the input list, but with each maximal run of nonzero digits being reversed.
## Example
Consider the input
```
95883007414830
<---> <---->
```
where the nonzero runs have been marked with arrows.
Reversing each of these runs, we obtain the output
```
38859003841470
```
## Rules and scoring
You can write a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.
[This challenge](https://codegolf.stackexchange.com/questions/11142/reverse-each-word-in-a-line-of-text-while-keeping-the-order-of-the-words-and-ca) is related, but much more complex, since it includes additional string processing.
## Test cases
```
4 -> 4
00 -> 00
123 -> 321
0010 -> 0010
12000345 -> 21000543
18161604 -> 61618104
95883007414830 -> 38859003841470
010230456078912 -> 010320654021987
357509902003550 -> 575309902005530
2492882377675046 -> 5767732882942064
03026302053000357099 -> 03036202035000753099
```
## Leaderboard
Here's a Stack Snippet to generate a leaderboard and list of winners by language.
To make sure your answer shows up, start it with a header of the form
```
## Language, N bytes
```
You can keep old scores in the header by using the strikethrough tags: `<s>57</s>` will appear as ~~57~~.
```
/* Configuration */
var QUESTION_ID = 78510; // 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 = 32014; // 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 = '<i>' + lang + '</i>';
lang = jQuery(lang).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;
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/Sites/codegolf/all.css?v=617d0685f6f3">
<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><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]
# Pyth, 8
```
j0_Mcz\0
```
Split on zeros, reverse and join back on zeros.
[Test Suite](http://pyth.herokuapp.com/?code=j0_Mcz%5C0&input=12300312&test_suite=1&test_suite_input=4%0A00%0A123%0A0010%0A12000345%0A18161604%0A95883007414830%0A010230456078912%0A357509902003550%0A2492882377675046%0A03026302053000357099&debug=0)
[Answer]
# [IPOS](https://github.com/DenkerAffe/IPOS), 5 bytes
```
'0!r%
```
`%` splits the input string on zeroes, applies the command `r` (reverse) to every substring and joins the result back on zeroes.
[Answer]
## [Retina](https://github.com/mbuettner/retina), 15 bytes
```
S`0
O%^$`.
¶
0
```
[Try it online!](http://retina.tryitonline.net/#code=JShHYApTYDAKTyVeJGAuCgrCtgow&input=NAowMAoxMjMKMDAxMAoxMjAwMDM0NQoxODE2MTYwNAo5NTg4MzAwNzQxNDgzMAowMTAyMzA0NTYwNzg5MTIKMzU3NTA5OTAyMDAzNTUwCjI0OTI4ODIzNzc2NzUwNDYKMDMwMjYzMDIwNTMwMDAzNTcwOTk) (Slightly modified to run all test cases at once.)
### Explanation
```
S`0
```
Split the input around `0`s that is, put each (possibly empty) run of non-zero digits on its own line.
```
O%^$`.
```
This reverses each line, by:
* Applying the stage to each line individually with `%`.
* Matching each character individually with `.`.
* Sorting it by the result of the substitution (`$`) with the empty string (the empty second line). I.e. it doesn't sort at all, since all sort values are identical.
* Then reverses the order of the sorted characters.
Finally:
```
¶
0
```
Turn the linefeeds back into `0`s.
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 6 bytes
Code:
```
0¡€R0ý
```
Explanation:
```
0¡ # Split on zeros
€R # For each item in the array, reverse it
0ý # Join by zeros
```
Uses **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=MMKh4oKsUjDDvQ&input=MDMwMjYzMDIwNTMwMDAzNTcwOTk).
[Answer]
# Julia, 30 bytes
```
s->replace(s,r"[^0]+",reverse)
```
This is an anonymous function that accepts a string and returns a string. To call it, assign it to a variable.
The `replace` function provides the ability to replace matches of a regular expression with the result of a function applied to each match. In this case we can get nonzeros using `[^0]+` and replace those runs with the result of the `reverse` function applied to the matched text.
[Verify all test cases online!](http://julia.tryitonline.net/#code=Zj1zLT5yZXBsYWNlKHMsciJbXjBdKyIscmV2ZXJzZSkKCmZvciBjYXNlIGluIFsoIjQiLCAiNCIpLAogICAgICAgICAgICAgKCIwMCIsICIwMCIpLAogICAgICAgICAgICAgKCIxMjMiLCAiMzIxIiksCiAgICAgICAgICAgICAoIjAwMTAiLCAiMDAxMCIpLAogICAgICAgICAgICAgKCIxMjAwMDM0NSIsICIyMTAwMDU0MyIpLAogICAgICAgICAgICAgKCIxODE2MTYwNCIsICI2MTYxODEwNCIpLAogICAgICAgICAgICAgKCI5NTg4MzAwNzQxNDgzMCIsICIzODg1OTAwMzg0MTQ3MCIpLAogICAgICAgICAgICAgKCIwMTAyMzA0NTYwNzg5MTIiLCAiMDEwMzIwNjU0MDIxOTg3IiksCiAgICAgICAgICAgICAoIjM1NzUwOTkwMjAwMzU1MCIsICI1NzUzMDk5MDIwMDU1MzAiKSwKICAgICAgICAgICAgICgiMjQ5Mjg4MjM3NzY3NTA0NiIsICI1NzY3NzMyODgyOTQyMDY0IiksCiAgICAgICAgICAgICAoIjAzMDI2MzAyMDUzMDAwMzU3MDk5IiwgIjAzMDM2MjAyMDM1MDAwNzUzMDk5IildCiAgICBwcmludGxuKGYoY2FzZVsxXSkgPT0gY2FzZVsyXSkKZW5k&input=)
[Answer]
# Retina, ~~25~~ 24
```
O^$#`[^0](?=(.*?0)*)
$#1
```
[Try it online](http://retina.tryitonline.net/#code=T14kI2BbXjBdKD89KC4qPzApKikKJCMx&input=MDMwMjYzMDIwNTMwMDAzNTcwOTk)
Saved 1 byte thanks to Martin!
Sort the nonzero digits by the number of zeros that follow the digit, in reverse order.
See [Martin's solution](https://codegolf.stackexchange.com/a/78528/31625) for a clever use of per-line mode to get a shorter program!
[Answer]
# Jolf, 8 bytes
```
RΜGi0λ_0
```
[Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=Us6cR2kwzrtfMA&input=MTIzMDQ1NjAzMjQyMzQyMDEyMw)
## Explanation
```
RΜGi0λ_0
Gi0 split input on zeroes
Μ λ_ map over reversal as a lambda
R 0 join by zeroes
```
The code explanation looks sort of like a lambda if you squint.
An equivalent 8-byte answer:
```
RΜGi0΅O0
```
Same thing, but it uses `΅O` (string mirror lambda) instead.
[Answer]
## Ruby, 29 bytes
```
->x{x.gsub /[^0]*/,&:reverse}
```
[Answer]
# Jelly, 5 bytes
```
ṣ0Uj0
```
[Try it online!](http://jelly.tryitonline.net/#code=4bmjMFVqMA&input=&args=WzEsOCwxLDYsMSw2LDAsNF0)
[Answer]
# Python, ~~58~~ 50 bytes
```
lambda x:"0".join([n[::-1] for n in x.split("0")])
```
Takes in a string x and splits on the zeros and reverses each element in the split and adds a zero and returns the this minus last zero.
[Answer]
# Mathematica, 30 bytes
```
Join@@Reverse/@#~SplitBy~Sign&
```
e.g. `Join@@Reverse/@#~SplitBy~Sign&[{1,2,3,0,0,5,9,0}]` = `{3, 2, 1, 0, 0, 9, 5, 0}`
[Answer]
## PowerShell v2+, 45 bytes
```
($args-split0|%{-join$_[$_.length..0]})-join0
```
Abusing the implicit casting like there's no tomorrow. Likely can't get much shorter, as there's no builtin for reverse that's shorter than this indexing trick.
### Explanation
An example of how this works -- suppose `123045` was the input `$args`. After the `-split` on `0`, the pipeline would contain an array `(123,45)`. The first loop with `|%{...}` has the current element `$_` equal to `123`, which is then implicitly cast as a string, then reversed with the `[]` indexing. That makes it `('3','2','1')` as a char-array. The loop's `-join` puts that back into a string `"321"` and leaves it on the pipeline. The next (last) loop iteration reverses the input to `"54"`. So now our pipeline is `"321"`, `"54"`. That's encapsulated in parens `()` so it's reformed into an array, and re`-join`ed back together with zeros to produce the resultant output string `"321054"`. That's left on the pipeline and output to the console is implicit.
If there are subsequent zeros in the original input, the array would be populated with null elements, so there are the correct number of zeros on the output. For example, `1230045-split0` turns into `(123,,45)` and things continue as above.
[Answer]
# Factor, 35 bytes
Beating Pyfon and Clojure, booyah!
```
[ "0"split [ reverse ] map "0"join ]
```
This anonymous function is a literal translation of [this Python answer](https://codegolf.stackexchange.com/a/78538/46231).
It's quite simple, just split the string on zeroes, reverse every element of the resulting array, and join all the elements (including zero-length strings) with `"0"`.
Here's an example of it running on all test cases:
```
IN: scratchpad auto-use {
"4"
"00"
"123"
"0010"
"12000345"
"18161604"
"95883007414830"
"010230456078912"
"357509902003550"
"2492882377675046"
"03026302053000357099"
}
[
"0" split [ reverse ] map "0" join
]
map .
{
"4"
"00"
"321"
"0010"
"21000543"
"61618104"
"38859003841470"
"010320654021987"
"575309902005530"
"5767732882942064"
"03036202035000753099"
}
```
`"00120"` -> `{ "" "" "12" "" }` -> `{ "" "" "21" "" }` -> `"00210"`
[Answer]
## Haskell, 45 bytes
```
r%(0:t)=r++0:[]%t
r%(h:t)=(h:r)%t
r%_=r
([]%)
```
Recursively accumulates the reversed chunk so far in `r`, prepending it when a `0` is reached. When the remaining string is empty, it also discharges `r`.
The first two repeat some code, but I didn't find a shorter way to combine them (45 and 47 bytes):
```
r%(h:t)|h<1=r++h:[]%t|1>0=(h:r)%t
r%_=r
([]%)
r%l|0:t<-l=r++0:[]%t|h:t<-l=(h:r)%t
r%_=r
([]%)
```
[Answer]
## Pyke, 8 bytes
```
\0cm_\0J
```
Explanation:
```
\0c - input().split("0")
m_ - map(reversed, ^)
\0J - "0".join(^)
```
[Try it here!](http://pyke.catbus.co.uk/?code=%5C0cm_%5C0J&input=%2212000345%22)
[Answer]
# JavaScript (ES6), ~~50~~ 49 bytes
String version:
```
s=>s.replace(/[^0]+/g,r=>[...r].reverse().join``)
```
*Saved a byte thanks to @Kevin Lau!*
Array version (60 bytes):
```
a=>a.map((n,i)=>n?a[z-i+[...a,0].indexOf(0,i)]:(z=i,0),z=-1)
```
[Answer]
# J, ~~20~~ 18 bytes
```
0}:@;@(<@|.;.1)@,]
```
Thanks to Zgarb for helping with this! Takes a space-separated list as a right argument.
-2 bytes thanks to Zgarb!
[Answer]
# Clojure/ClojureScript, 44 chars
```
#(flatten(map reverse(partition-by pos? %)))
```
Same solution as others, just more verbose thanks to long function names. Wasn't going to post it because of that, but it beats some other answers so why not?
Works on any sequence type. In ClojureScript, this also works on strings since strings are processable as lists of characters, which are really just 1-length strings, which coerce to numbers for things like `pos?`.
[Answer]
## Haskell, 46 bytes
```
import Data.Lists
(reverse=<<).split(oneOf"0")
```
Usage example: `(reverse=<<).split(oneOf"0") $ "0123004500678090"`-> `"0321005400876090"`.
Sadly the `split` function requires the expensive import. Split the input list at every `0`, e.g. `split(oneOf"0") "0120030"` -> `["","0","12","0","","0","3","0",""]`, reverse each chunk and concatenate into a single string.
[Answer]
# F#, 103 bytes
```
let f x=x="";x.Split '0'|>Array.map(fun s->System.String(s|>Seq.toArray|>Array.rev))|>String.concat "0"
```
[Answer]
# Java, 179 bytes(with import)
```
import java.util.*;static void r(String s){StringJoiner x= new StringJoiner("0");for(String a:s.split("0",s.length())){x.add(new StringBuilder(a).reverse());}System.out.print(x);}
```
Takes in a string input and splits the characters by zero then adds them back by calling the add method on the StringJoiner class.
[Answer]
# Oracle SQL 11.2, ~~131~~ 123 bytes
Abusing XML functions.
```
SELECT LISTAGG(REVERSE(COLUMN_VALUE||''))WITHIN GROUP(ORDER BY rownum)FROM XMLTABLE(('"'||REPLACE(:1,'0','","0","')||'"'));
```
[Answer]
# Perl, 22 bytes
Including +1 for `-p` option:
```
s/[^0]+/reverse$&/eg
```
This is a pretty trivial substitution - sorry to be so boring. Note that if your input is newline-terminated (e.g. using `perl -pe 's/[^0]+/reverse$&/eg' <<<21000543` in Bash), it will catch the newline with the digits - use `echo -n` or `printf` to avoid that. Alternatively, for a cost of one additional byte, change the character class to `[1-9]`, and you can provide many inputs, one per line.
[Answer]
## C, 105 bytes
```
#define x(o)for(p=s;*s&&'0'o*s;++s);for(r=s;r-->p;putchar(*r));
f(s,p,r)char*s,*p,*r;{x(^)x(==)*s&&f(s);}
```
Call `f` with the list of digits as a nul-terminated string, and it will print the correct output.
**Ungolfed and explained:**
```
f(s,p,r)
char*s,*p,*r; // K&R style to avoid repeating `char`
{
// x(^)x(==) expands to...
// Find the next zero digit
for(p = s; *s && '0' ^ *s; ++s)
;
// Print that run backwards
for(r = s; r-- > p; putchar(*r))
;
// Find the next non-zero digit
for(p = s; *s && '0' == *s; ++s)
;
// Print that run backwards (no difference, it's all zeros)
for(r = s; r-- > p; putchar(*r))
;
// If there's more string, recurse
*s && f(s);
}
```
[See it live on Coliru](http://coliru.stacked-crooked.com/a/97f6d4a5e3fa4c17)
[Answer]
# [Husk](https://github.com/barbuz/Husk), 4 bytes
```
ṁ↔ġ¬
```
[Try it online!](https://tio.run/##yygtzv7//@HOxkdtU44sPLTm////0ZY6pjoWQGisYwCE5jomOoZADObHAgA "Husk – Try It Online") or [verify all test cases](https://tio.run/##JY27DQJBDER72YiAYPzfrQWRg9BFJwo4AiqgAXIaIEU0wjWyeCGw/caekQ/n@dSnzee5zOtlmY49ab3e3vfXo/e@K1q2BchGLD@kvwAgagMrOTmGr1mtAoSS5hxuAgvUHFEbcW7EwtAaMi9mw8PauFaWCM@T@ogJ2LNgMt5YZKLsvw)
Input is a list of digits.
`ġ`roups all adjacent runs of nonzero (`¬`=NOT) digits, then `ṁ`aps the 'reverse a list' (`↔`=REV) function across all groups, concatenating the result.
[Answer]
# [K (ngn/k)](https://bitbucket.org/ngn/k), 10 bytes
```
"0"/|'"0"\
```
[Try it online!](https://tio.run/##JY1LDgJBCETvwmY00Vh8m9aruB4XJnMC796CLigKeBXe1@N1rLXfCXT7bKXPtW@nCxk9CChh0Z/l/wBAzdsmBweam56pwDC26k0zRGEeGDlZaqM@HHOi8urejNiUTNExok4WHVNIVMG13/ioBJ3XFw "K (ngn/k) – Try It Online")
Similar to many of the other approaches; takes (implicit) input as a string of digits:
* `"0"\` split input on `0`s
* `|'` reverse each chunk
* `"0"/` join with `0`s
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes
```
0ẆRṅ
```
Takes input as a string instead. If that's not allowed then the `Ṡ` flag can be added.
[Try it online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiMOG6hlLhuYUiLCIiLCJcIjRcIlxuXCIwMFwiXG5cIjEyM1wiXG5cIjAwMTBcIlxuXCIxMjAwMDM0NVwiXG5cIjE4MTYxNjA0XCJcblwiOTU4ODMwMDc0MTQ4MzBcIlxuXCIwMTAyMzA0NTYwNzg5MTJcIlxuXCIzNTc1MDk5MDIwMDM1NTBcIlxuXCIyNDkyODgyMzc3Njc1MDQ2XCJcblwiMDMwMjYzMDIwNTMwMDAzNTcwOTlcIiJd)
Explanation:
```
0 # Push the literal digit 0
Ẇ # Split and keep delimiter
R # Reverse each one
ṅ # Join by nothing
```
[Answer]
# Perl 5, 52 bytes
A subroutine:
```
{$_=pop;y/0/ /;map$i.=reverse,split/\b/;$i=~y/ /0/r}
```
[Answer]
## Actually, 22 bytes
```
k"a%sa"%'0@s♂R'0j#pXdX
```
This actually made me notice that there's a bug in the split command - it doesn't preserve empty splits. As a workaround, I surround the input string with `a`s before doing the split, reverse, and join, then remove the `a`s at the end. Input is taken as a string, output is a list of single-character strings.
[Try it online](http://actually.tryitonline.net/#code=ayJhJXNhIiUnMEBz4pmCUicwaiNwWGRY&input=IjAzMDI2MzAyMDUzMDAwMzU3MDk5MCI)
Explanation:
```
k"a%sa"%'0@s♂R'0j#pXdX
k"a%sa"% surround input with "a" characters
'0@s split on 0
♂R reverse each piece
'0j join on 0
#pXdX listify, remove first and last element (the "a"s)
```
[Answer]
## C#, 131 bytes ##
solution flawed!
```
string j(string i){foreach(var s in i.Split('0'))if(s!="")i=i.Replace(s,new string(s.ToCharArray().Reverse().ToArray()));return i;}
```
ungolfed:
```
string j(string input)
{
string[] a = input.Split('0');
foreach (string s in a)
{
if (s!="")
input=input.Replace(s, new string(s.ToCharArray().Reverse().ToArray()));
}
return input;
}
```
] |
[Question]
[
# Task
Given a positive integer return the geologic era and period it was that many million years ago.
## Input/output
The input is a string or integer; the output is a string. Eras and periods are separated by slashes (`/`). Input will always be between `0` and `542` inclusive
# Data
The possible outputs for eras and periods and their corresponding time periods (in millions of years) are:
* **Cenozoic** 0 - 66
+ **Quaternary** 0 - 3
+ **Neogene** 4 - 23
+ **Paleogene** 24 - 66
* **Mesozoic** 67 - 252
+ **Cretaceous** 67 - 145
+ **Jurassic** 146 - 201
+ **Triassic** 202 - 252
* **Paleozoic** 253 - 542
+ **Permian** 253 - 299
+ **Carboniferous** 300 - 359
+ **Devonian** 360 - 419
+ **Silurian** 420 - 444
+ **Ordovician** 445 - 485
+ **Cambrian** 486 - 542
Submissions will be scored by byte count. Lowest byte count wins.
# Test cases
```
314 -> Paleozoic/Carboniferous
0 -> Cenozoic/Quaternary
542 -> Paleozoic/Cambrian
100 -> Mesozoic/Cretaceous
```
[Answer]
# [Befunge-93](https://github.com/catseye/Befunge-93), 537 bytes
```
&:"C"`#v_"neC">,,,"/ciozo",,,,,,:4`#v_"auQ",,,"yranret">,,,,,,,@
*54+65:< > ^"Mes"_v#!`*+3 >#># ^#
"leogene"<^"ale","P"< v_v#`*64:<> "enegoeN"^
,,,"Cre"< ^ ,,"Pa"_v#!`"C":< > ^^"taceous"
`*2"e":_^#`*+*5545:<v_v#
,"T"_v#!`*+*543+65:< >"J","cissaru" ^"riassic"
*"d"3:<v_v#!`
"rmian"< >:"x"3*`!#v_:"F"6*`#v_"D",v ^"Pe"
"ous",,,,,,"Carbon"< : ^"ifer"
"enovian" < ^
"brian","C"_v#`*"Q"6_v#`*"Y"5< ^"am"
"an",,,"Ord"< >"S","nairuli" ^"ovici"
```
[Try it online!](https://tio.run/##dVBNS8MwGL7nV2RPwUNXcNiPQyhBqHgQ1A29eMmaddkIbC2ka1H/fH3Tus2Lzynkfb7ed2N2Xb03w3AjUKAM@jVqU0BGUYTbyjbfDaIRIhmHulv5D3w5XTtzGoke9yxMk3mWipxzLjlXeDYt1n0wK8N5zC@QgQz4X6iAcRxMsze1Qa6gDwYRlsjHaU8OZZglIpdnAYi4b8wLFPNFCkcyrjg9l3oKpEWoxlmgFE66Mk3XgpXhHQzEWpHpPEzThPr6CMYjvJ/b0iLxtInEE3WpbNtq18Ev5axuW1uBhdginsSzksEdra6phxT4RByWM7qVwCOycLzaA6Ley5cGDL7JdDQU2m2a@ndXD3E5C@zOOGKbuum9N/8XpFYMG@dZZInxZFghmx4fSPOrqz6SpydS@qvbXqMl3khda@u6g8XIpeDKYhjSxeIH "Befunge-93 – Try It Online")
This is basically a giant `if/elsif/if` chain (or rather, two of them), one for the era, and one for the period.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~74~~ 73 bytes
```
“¥Þ+O83/<<ı)‘Ä>⁸Sµ:3»1;ị"“¥nq9r&t\“¥Ḅr¶4ḍẏżæœġẓÆ$Ụ>¬ḞḂṂĊƁÄ`zṚƥṀȯ4N»Ḳ€¤j”/
```
A monadic Link accepting number in \$[0,542]\$ which yields a list of characters (or a full program which prints the result).
**[Try it online!](https://tio.run/##AZIAbf9qZWxsef//4oCcwqXDnitPODMvPDzEsSnigJjDhD7igbhTwrU6M8K7MTvhu4si4oCcwqVucTlyJnRc4oCcwqXhuIRywrY04biN4bqPxbzDpsWTxKHhupPDhiThu6Q@wqzhuJ7huILhuYLEisaBw4RgeuG5msal4bmAyK80TsK74biy4oKswqRq4oCdL////zEwMA "Jelly – Try It Online")**
### How?
```
“...‘Ä>⁸Sµ:3»1;ị"“...“...»Ḳ€¤j”/ - Link: integer, N e.g. 100
“...‘ - list of code page indices [4,20,43,79,56,51,47,60,60,25,41]
Ä - cumulative sums [4,24,67,146,202,253,300,360,420,445,486]
>⁸ - greater than N? [0,0,0,1,1,1,1,1,1,1,1]
S - sum 8
µ - start a new monadic chain, call that X
:3 - integer divide (X) by 3 2
»1 - maximum of that and 1 2
; - concatenate with X [2,8]
¤ - nilad followed by link(s) as a nilad:
“...“...» - list of compressed strings ["Paleozoic Mesozoic Cenozoic","Ordovician Silurian Devonian Carboniferous Permian Triassic Jurassic Cretaceous Paleogene Neogene Quaternary Cambrian"]
Ḳ€ - split each at spaces [["Paleozoic","Mesozoic","Cenozoic"],["Ordovician","Silurian","Devonian","Carboniferous","Permian","Triassic","Jurassic","Cretaceous","Paleogene","Neogene","Quaternary","Cambrian"]
" - zip with:
ị - index into (modular) ["Mesozoic","Cretaceous"]
j”/ - join with a '/' "Mesozoic/Cretaceous"
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), 260 bytes
```
n->(n<67?"Cen":n<253?"Mes":"Pale")+"ozoic/"+"QuaternaryNeogenePaleogeneCretaceousJurassicTriassicPermianCarboniferousDevonianSilurianOrdovicianCambrian".split("(?=[A-Z])")[(n=java.util.Arrays.binarySearch("B‘ÉüīŧƣƼǥȞ".toCharArray(),(char)n))<0?~n:n]
```
[Try it online!](https://tio.run/##VZDBbhMxEIYP3PICXEeWItk0MWnTgrRJGpUgpCKVFoUTUQ6TjTd12B2vbO9KC2rvHHkBLghx4BV6olB4q8W7jYQ4WDNjf2P9@rZYYn@7flfrLDfWwzbMsvA6lUlBsdeG5KNRJ07ROThDTfChA5AXq1TH4Dz6UEqj15CFNz73VtNmsQS0GydaFOCU/IvdV@N74BgSmEBN/WNO4ydPp2ymiEU0PjgaTtmZcixiF5gqJvaYeW90/JjtsdcFemUJbfVKmY0i1RBtM7PKY6xM4V4WNsTU8Rur23qhbKaRZmhXhnSibGCeqzL0SHOdFgGjc7s2pY5bLFs1N0y6PNWeMz6dLE76b5eCiQWnyT8zJ9Zi5eRKN3HmCm18ydmDh89@fLr9eHvz8/uvb3df7m5@f/3zmUlvZpdo2w0uejwOgyAhxoPpNUW0rEeto8RY4CVa8Mr56D99AJo8VEFYEKk2ysoS00KdJ7xhxWgHzSvnVSZN4WUeHPuEs@5wHUHXdYn1oOpBIjHP04rfZ6jEbvWq05yruh7uH9aD@ujwoN4fDP4C "Java (JDK) – Try It Online")
* Contains invisible characters. The binary search String is actually: `"\u0003\u0017\u0042\u0091\u00c9\u00fc\u012b\u0167\u01a3\u01bc\u01e5\u021e"`.
[Answer]
# [J](http://jsoftware.com/), 195 bytes
Assumes that input is 0-542, otherwise ~+7 bytes.
```
(Cen`Mes`Pale{~66 252&I.);@,'ozoic/';Quaternary`Neogene`Paleogene`Cretaceous`Jurassic`Triassic`Permian`Carboniferous`Devonian`Silurian`Ordovician`Cambrian{~(+/\3 20 43 79 56 51 47 60 60 25 41)I.]
```
[Try it online!](https://tio.run/##JYpda8JAEEXf@yuGPjQGNW42uxEVoZBSsLR@P1bYNU5ki@7CxAit4F9PNwbmDudezk/9HAUFTMcQQA8YjH36EWTrz/e6k6FVX1iqpT7h7Z6mwCV/mUXh5LUXuD9n8kEwWVX6gmQ1/ao5uiNafOgtZYQXnaOrSvVRkS5Lk6stmRaWSGejrco07Z01BVLjveHVFz9vzKmiBhZ0cFeTt@p532y3e6c7@E6AMxAJDEcgU5AxiCGkrDkuQcThLNrVYV1AEounApiPFNz/mLF/ "J – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~273~~ 264 bytes
```
lambda y:(['Cen']*67+['Mes']*186+['Pale']*290)[y]+'ozoic/'+(['Quaternary']*4+['Neogene']*20+['Paleogene']*43+['Cretaceous']*79+['Jurassic']*56+['Triassic']*51+['Permian']*47+['Carboniferous']*60+['Devonian']*60+['Silurian']*25+['Ordovician']*41+['Cambrian']*57)[y]
```
[Try it online!](https://tio.run/##PY9Pb4MwDMXv@xTcAoNqBAKslbYLO03aP3U31kOgposESWVCJfblmUPZfPLv6fnZPk/22@h0bh@@5k729VF6086vWAmaHW7zIqzYCwzU8vuc@nfZAUGyjYNqOoTM/BjV3LGQJj5GaQG1xIkMgryvYE6gF3u8jv4JIiWhRLCyATO6@GJLyvOIchhUQ5y5bZ@o/pm7CMBeSXeYcIeVEmujVQt4zcjdmie4kLaYFt6rbsQrJxnxGx7NRTVrDF9i@np1ZIV7a24NetZT2vNTLqI4ykQS8TgOdjce1RmVtr6N2OaRRa1vg2D@BQ "Python 3 – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~226~~ 221 bytes
```
n=>(Buffer('!%5LpYTP]]:JZ').some(c=>(n-=c-34)<j++,j=1),a='CenMesPaleQuaternaryNeogenePaleogeneCretaceousJurassicTriassicPermianCarboniferousDevonianSilurianOrdovicianCambrian'.match(/.[a-z]+/g))[j>8?2:j/6|0]+'ozoic/'+a[j]
```
[Try it online!](https://tio.run/##HY3BTsJAFEX3fMW4MJ3J0BYRjAEGE@uKiGJko6SLx/Bap2nfkJm2iajfXgure3JykltAC147c6xDsgfsMtWRWvLHJsvQ8eDqevp8/Nhu0nS2@gxE5G2FXPcBhUqHtxOxKKQcFupGDEEFCdIa/QZKfGugRkfgvl/Q5kh4lhdIHNag0TZ@1Tjw3uitM5fdoKsMUAJub8n0933zhG3PQO@mbPqMXt3BtkZfsmp/NkFUQa2/eBztIDylMs6F2BXL@4fxrIjvfkepDOzJGh0HEnZF2mXWcWKKjeaM2EKx6WTck5SC/QwY05a8LTEqbc5pyDJOQswHf90/ "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 148 bytes
```
Nθ§⪪Cen Mes Pale¦ ⁺‹θ⁶⁷‹θ²⁵³ozoic§⪪”↶0s⟧↶'⪪Q⟧⪪⪫(cI‹qκyQυ⌕↖↙″⁼R¤´⁵σι↙¡Z⟧+]IΦc№M⁰$✂%¹νν⬤~[Z⊕←⊘↖τF¤H>¹Sk◨ⅈγδ;§⟦⬤▶%↨Φ;{θi∕Nβ” LΦI⪪”)¶5″⁶vρ⁶S⊘l²Kκ~y”³‹ιθ
```
[Try it online!](https://tio.run/##dU/LTsMwELzzFZZPjhSkvCHihIKQikoJKj/guEtrybGbtR0BPx@chnDrnmZGo9kZceIoDFfTtNFn73a@7wDZED3ctCi1Y49uow/wxfZnJR2jDWjyCpa0XAGNCSU0ikmrvGVbsJYNManugrKSrMyjcGsYNT9GCnot/N1zB6g5fpMdmCNouPxZUIPguADjLXnxyK2VgnygXEAL2EuuScOxM1p@As6@JxgDCfJeKo8zeMODGaVYrH03a/8rtqCP7sSepQolWMOtW3slSZ5keVJVaVFmSZqVWVbXeVkXaV2Euy9DRtj5N1vGZLiMnqY8LabbUf0C "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ
```
Input the year.
```
§⪪Cen Mes Pale¦ ⁺‹θ⁶⁷‹θ²⁵³
```
Print one of the three era prefixes depending on the year.
```
ozoic
```
Print the era suffix.
```
§⪪”...” LΦI⪪”...”³‹ιθ
```
Extract the years that the periods end from a compressed list of padded years and count how many periods have ended before the input year and index into a compressed list of names of periods to print the current period. (Padding the years to three digits saves 4 bytes overall due to not needing any separators.)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~127~~ ~~125~~ 124 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
.•TćFh/>ytTOb•#櫕͇,®ǝ₁êË2•80в.¥I›©₆12ªèOè.•Hα^B·´‘›∞ÕΣHı[šyZÙΣpK5|´Ø·ëu"dw$мïjéåpºöÒ@’»©\I›¼ä^и9Σ߃ôƶI<Ægª6XyrмÏ•#®Oè'/ý™
```
[Try it online](https://tio.run/##yy9OTMpM/f9f71HDopAj7W4Z@naVJSH@SUCu8pH2Q6uB9OHeRw0LdQ6tOz73UVPj4VWHu42AghYGFzbpHVrq@ahh16GVj5raDI0OrTq8wv/wCpBBHuc2xjkd2n5oy6OGGUAFjzrmHZ56brHH4ZZDG6OPLqyMOjzz3OICb9OaQ1sOzzi0/fDqUqWUcpULew6vzzq88vDSgkO7Dm87PMnhUcPMQ7sPrYwB27Hn8JK4Czsszy0@PP/YpMNbjm3ztDncln5olVlEZRFQZz/IvYfWAe1X1z@891HLov//DQ0MAA) or [verify all test cases](https://tio.run/##AfUACv9vc2FiaWX/dnk/IiDihpIgIj//LuKAolTEh0ZoLz55dFRPYuKAoiPEh8Kr4oCiw43igKEswq7HneKCgcOqw4sy4oCiODDQsi7CpXnigLrCqeKChjEywqrDqE/DqC7igKJIzrFeQsK3wrTigJjigLriiJ7Dlc6jSMOEwrFbxaF5WsOZzqNwSzV8wrTDmMK3w6t1ImR3JNC8w69qw6nDpXDCusO2w5JA4oCZwrvCqVxJ4oC6wrzDpF7QuDnOo8OfxpLDtMa2STzDhmfCqjZYeXLQvMOP4oCiI8KuT8OoJy/DveKEov8s/1szMTQsMCw1NDIsMTAwXQ).
**Explanation:**
```
.•TćFh/>ytTOb• # Push compressed string "ozoic cen pale mes"
# # Split it on spaces: ["ozoic","cen","pale","mes"]
ć # Extract head; pop and push remainder-list and first item separated
« # Append this head to each item in the list:
# ["cenozoic","paleozoic","mesozoic"]
•͇,®ǝ₁êË2• # Push compressed integer 3656627291841362083337
80в # Convert it to base-80 as list: [4,20,43,79,56,51,47,60,60,25,41,57]
.¥ # Undelta this list: [0,4,24,67,146,202,253,300,360,420,445,486,543]
I› # Check for each whether it's larger than the input-integer
# (1 if truthy; 0 if falsey)
© # Store this list of checks in variable `®` (without popping)
₆ # Push builtin 36
12ª # Convert it to a list of digits, and append 12: [3,6,12]
è # Index those into the checks (to get those for [67,253,543])
O # Sum those checks to get the amount of truthy values
è # Index it into the string-list (modulair 0-based,
# so 3 indexes into "cenozoic")
.•Hα^B·´‘›∞ÕΣHı[šyZÙΣpK5|´Ø·ëu"dw$мïjéåpºöÒ@’»©\I›¼ä^и9Σ߃ôƶI<Ægª6XyrмÏ•
"# Push compressed string "quaternary cambrian ordevician silurian devonian carboniferous permian triassic jurassic cretaceous paleogene neogene"
# # Split it on spaces: ["quaternary","cambrian","ordevician","silurian","devonian","carboniferous","permian","triassic","jurassic","cretaceous","paleogene","neogene"]
® # Push the list of checks from variable `®`
Oè # Do the same as we did earlier
'/ý '# Join the two words on the stack with "/" delimiter
™ # And titlecase both words in this string
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (sections *How to compress strings not part of the dictionary?*, *How to compress large integers?*, and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand how the compression works.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/) 18.0, 213 bytes
```
(0 4 24 67 146 202 253 300 360 420 445 486 543⍸⎕)⊃⊃,/1(⌷,¨↓)¨(9⍴4↑1)⊂(∊∘⎕A⊂⊢)'Cenozoic/QuaternaryNeogenePaleogeneMesozoic/CretaceousJurassicTriassicPaleozoic/PermianCarboniferousDevonianSilurianOrdovicianCambrian'
```
[Try it online!](https://tio.run/##NY/PSsNAEMbvfYq5NYFK82c36lHiSVAr@gLb7VoW0t2waQr1qBBjMEWRQs895QEEPfdR5kXiNsFhhvmY@Q0fw9LkZLZmiZ63HIsPLD6xbrDc4dseq2es9gMsXyFtHQ8IBASiU/BJBIEXQEBDCD0PwsjuAluEAjmLgJIQ61/cbF2sXmyOxr6D7z@jQ4PFl3tonHOsv4l18l3uYFkd3Tbbi97OHcZC6Sct@fguZ0thFDPrG6HnQokJS3pxLbIeiY1YMi50nl3lhmWZ5A9Gdr1jO2YizEIyFTMz1Uo@CmPpS7Gymql7meT2QN2amV5J3mGL6XEybO3fLXSRDkKfDP41pfQP "APL (Dyalog Unicode) – Try It Online") (uses `c` as a polyfill for `⊂` since TIO has not upgraded to 18.0 yet)
[Answer]
# perl -pl, 270 251 bytes
```
@a=((Cenozoic)x67,(Mesozoic)x186,(Paleozoic)x290);@b=((Quaternary)x4,(Neogene)x20,(Paleogene)x43,(Cretaceous)x79,(Jurassic)x56,(Triassic)x51,(Permian)x47,(Carboniferous)x60,(Devonian)x60,(Silurian)x25,(Ordovician)x41,(Cambrian)x57);$_=$a[$_].$".$b[$_]
```
[Try it online!](https://tio.run/##NY7LasMwEEX3/oyihQRqkBzLbgiBgLsq9EW7KyXI7iQIHMmM7OD246tKsbubM3PPZXrAToWw1ztKa7Dux5mWTWXF6SP4heRdyemL7mDhfCPYdt9E43XUA6DV@M2mgtMncCewEBNiEWYs1pzWCINuwY2eTdWG04cRtfepTsX2dzT/JKMKeDbaRjH@UWtsnDVHwKtbxup7uMRNCiR6M92IV8oVp8/45S6mnXWZ9HMzX1XFtuSwI/qDHD5X5GZFmjSFsJZFJjJV5JkU4tf1g3HWh9u@@wM "Perl 5 – Try It Online")
This creates two arrays with 543 elements each. Finding the era and period is then just a matter of indexing in the arrays.
Edit: The challenge was changed; we can now assume the input is between 0 and 542 inclusive. So we don't need to test the input anymore. And we don't require a slash between era and period either.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 339 bytes
```
f=(a)=>{g=(b,q,w)=>{for(i=0;;i++){if(a<q[i])return w[i]}}
x=[67,253,543]
y=['Cenozoic/','Mesozoic/','Paleozoic/']
n=[4,24,67,146,202,253,300,360,420,445,486,543]
m=['Quaternary','Neogene','Paleogene','Cretaceous','Jurassic','Triassic','Permian','Carboniferous','Devonian','Silurian','Ordovician','Cambrian']
console.log(g(a,x,y)+g(a,n,m))}
```
[Try it online!](https://tio.run/##PY5NT8JAEIbv/RXe2E1HLe22muB6wZOJisFb08NSps2adlemH4CE314XCh4med75eDLfqldNTvqnvTV2jcNQSKa4fD6Ukq1gA9sTF5aYlsFspn2fH3TB1NMm1RknbDsyN1vHx6O3k2nyAGEcQSyizNvLdDJHY3@tzu8nMHnD5p8XqsJLyDwjUwGhAHc8FQmEQXiWREEAURKACF2JGMRjMoprJ/7sVItkFO2d7R1tiQav3gvP3XcqR9s1Lrx2pJpG5w6/SF9xgVRrZU7LilbW6AJp3H/B3sXzaKmrjkb8oLXtdX49qVfnfubl1jS2wrvKlqxkCnaw5/4JDNScH4eCTfnwBw "JavaScript (Node.js) – Try It Online")
simplest solution to start golfing
[Answer]
# [Whitespace](https://esolangs.org/wiki/Whitespace), ~~1841~~ ~~1830~~ 1819 bytes
```
```
[Try it online!](https://tio.run/##nVVBTgMxDDzbr5gnwIX/IFQJbkgg8fxlYyf2JPFWhbZatY7jGU/G6c/7x/ft6/P17XYcgIgC0PMtKu2F9htijzMEj1tUPIGittkfLdA2Kdc4M6SFRj68Tovaj1zoNGBLgYcsj0hKAA9yHbFWosxMVkYTthwL4sB9ESBwSUrBIyh1iZpyGqmmpPT2E4K6Q5biRglAhBKy545Ool1VxSafsw2uxCfEX3svWE4JktsKQIsSNulU0vYtmZTOYl91U2E6PS4HWe3Sj3v7CrCfggwVnixZiOSdpaaLizYd8jiX8945XYsa4LP5phPNUxLWF6yvzbx9Hhy7aQhKIywe82H4gya1u0LZlQvNJulXWvVqYgWXCjCtYkr7fGelvVdUve6GcuuTix7wc9277Og@4K2w0t0rcq88ty7Ykca8aIfRbozx96HQAToMc@e6iyPRYeR6jOabAtMO@cc96Dd176WVsoGI4YAex/PL0y8 "Whitespace – Try It Online")
For some reason it doesn't work quite right on TIO, try it using the IDE I wrote it in, [Whitelips](http://vii5ard.github.io/whitespace/)
## Explanation
Since the only conditionals in whitespace are `jump-if-negative` and `jump-if-zero`, I figure out if the inputed number minus the number for the era plus one is negative, then jump to the respective label and push the era onto the stack. I then jump into a loop that prints the entire stack. (loops until it reaches a `-1`, which I push at the very start of the program.) I save repetive bytes by pushing "ogene" and then "Ne" or "Pale", "ozoic/" and then "Mes" or "Cen", etc.
[Answer]
# [FEU](https://github.com/TryItOnline/feu), 268 bytes
```
u/x
m/x{486}x*/"Cambr#/x{445}x*/"Ordov%#/x{420}x*/"Silur#/x{360}x*/"Devon#/x{300}x*/"Carbonifer&/x{253}x*/"Perm#/x{202}x*/'Tri,/x{146}x*/'Jur,/x{67}x*/'Cretace&/x{24}x*/- 0/x{4}x*/-N0/x*/-Quaternary/0/eogene/-/Cen!/,/ass%/'/Mes!/&/ous/#/ian/"/ e!/!/ozo%\//%/ic/ /Pal/g
```
[Try it online!](https://tio.run/##Lc5Ni8IwEAbgu7@iVWphUd5Ya3fv3ZPgF3rcS3RHCdgEpkaq4m@vzegp8z7MZOZIvm09ml6F5pH/FM/mC/1SV3seBMhnAiv@d9dEJFMiW3P20jIt3vBLV2cFlPp8wntnzZF42Gk2m4quiavQlaks5HTHZtTFSS6b07nnEItvSSXTRR9I5vMg40iFG6RcdmX3bLy@EFvNNyiQO5EljFGSjTGCrusEKRZUxxjC@RoDGG3RR0QxYri7S/6ABOaACGt9xqltXw "FEU – Try It Online")
Basically just compression.
[Answer]
# [Io](http://iolanguage.org/), 417 bytes
Port of Noodle9's Python answer.
```
method(y,("Pale "repeated(67).."Mes "repeated(186).."Pale "repeated(290))split at(y).."ozoic/"..("Quaternary "repeated(4).."Neogene "repeated(20).."Paleogene "repeated(43).."Cretaceous "repeated(79).."Jurassic "repeated(56).."Triassic "repeated(51).."Permian "repeated(47).."Carboniferous "repeated(60).."Devonian "repeated(60).."Silurian "repeated(25).."Ordovician "repeated(41).."Cambrian "repeated(57))split at(y))
```
[Try it online!](https://tio.run/##ZZDBbsIwEER/xfLJlqqQUJIAUk/0VKktqBy5mGQDKyV2tHGQ0p9PcVAlO1z3zezMLpqxYts3dhobsFdTiuFF8L2qgXGCFpSFUmS5jCL@CZ03S9aZG86Uy00sZdfWaJmyYnAK82uwWPAoEvzQ30WkFQ2eZeVEX2AuoINN8f/6OVm9OrIjsKoA0/ul8o1DHz2prsPCA@lU9kj4BJIpBqhBpf2Q6eSdorPRWAGFOdlU7h1udxjYHuAH655CsEwd@KbS3LCYRSWPqOY886R58Es5ViKJY8laQm1rPf4B "Io – Try It Online")
[Answer]
# [PHP](https://php.net) [with -r](https://codegolf.meta.stackexchange.com/a/2428/58556), 261 bytes
Lots of ternary operators is the shortest solution I've found. Then golfed for some redundant suffixes. Only twice the amount of bytes needed to spell out each era uncompressed.
```
$a=$argv[1];echo($a<67?Cen:($a<253?Mes:Pale)).'ozoic/'.($a<4?Quarternary:($a<24?Neogene:($a<67?Paleogene:($a<146?Cretaceous:($a<202?Jurassic:($a<253?Triassic:($a<300?Permian:($a<360?Carboniferous:($a<420?Devon:($a<445?Silur:($a<486?Ordovic:Cambr))).ian))))))));
```
[Try it online!](https://tio.run/##RY9NT8MwDIb/yg6VRg@MrE0L6jb5UE5IwBC7IYS8zrSRtjhyPyT48YRWGcwn@/Xrx7ZrnPdrcI2bRbiJUOrhbfm@oqrhqwjX@S2UZIspTbIUHqkttnikOF7M@ZtNdTNfTD0NLz1KR2JRvoJbwxNxTZaKM2eauwhLnUMp1GFF3LdhRCXw0Au2ran@N@7EXIRUKdiSnAyGk9JcQYmyZ2s@Sf44OlFwTwMHj9YZvJpjL6G6y@FZDjyMxBJPe4nHV0ZcfI6V9z5T6oddZ9i2/vowIxGWDyHH0hlbb9Qv "PHP – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 317 bytes
```
->a{a<31?"Cenozoic/"+(a<4?"Quaternary":(a<24?"Neogene":(a<67?"Paleogene":""))):a<253?"Mesozoic/"+(a<146?"Cretaceous":(a<202?"Jurassic":(a<253?"Triassic":""))):a<543?"Paleozoic/"+(a<300===a ?"Permian":(a<360 ?"Carboniferous":(a<420?"Devonian":(a<445===a ?"Silurian":(a<486 ?"Ordovician": (a<543?"Cambrian":"")))))):""}
```
[Try it online!](https://tio.run/##TY5NT4QwEIbv/goypyXGWGhBs1nsAU8mfkVvZg8DDqbJLjUD3WQ1/nbsQkFv06fvPPOyq45DUwwXN/iNG5loKKm1X9bUl3C@wo3S8OywJ26Rj7D2JPXogewHtTS@8ysNT7ibCUAcx2sfy6SGe@r@uRKVez1TjzVZ1002kWq4c4xdZ@qJnBZf2QQy@zIlw50/oRSiKAqM/Afx3mA7CmQuPCmRK9uahng@pVKh4ZYOnoakUlnYfzE7xwu@zj165Hd7MPUIo1UoUOK@mnJjr1M1gJ/h0/Vd1LzJRG3PwiyWKVPpMidCbIdf "Ruby – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 235 bytes
```
67‹i’¦ì€¸zo¾ã/’™?¹4‹i’QuâìÒÇry’?ë¹₂Í‹i’ÖÌž¹’™?ë’æ§ož¹’™?}}ë¹253‹i’€á€Êzo¾ã/’™?¹145‹i’±ƒˆÆÁàÔºs’™?ë¹т·Ì‹i’JҢ턾ã’?ë’Æ×턾㒙?}}ë’æ§¢äo¾ã/’™?¹3т*‹i’„œéên’™?ë¹₆T*‹i’®´€¬²¡Ôºs’™?ë¹420‹i’Ùç·‹’™?ë¹445‹i’¯ë„¹´€¤’™?ë¹486‹i’€—€·É²·‹’™?뒧袰’™?
```
[Try it online!](https://tio.run/##XVC7SgNBFP0fG012E@3S2wn@gAGLNC4YLBQC4yArSmzWoKRZzBqyatYnwjoWKe4hNqnyC/Mj6ww7Y8ZtBu655zU36O61O/tF0dyUTHQkG9IEmeQZfZ0ENMP9uoLkWdIi4RvCzhESZIhwfnisxhamJCTnuDJ73KA/nymsFGKqsQmlgQP2elpVb3hGowIx0s9lNbXmN2yx959oESLEKe4woO/uXwCJJaccfUPcRkQJniWLtVVZUXcIceuitoeppyTjSra35Gu2IIvn13jE04GTKnm4awn0Qp/6bBl90Khaz69v2OMMkVKuBne7@uKrrhOTKL3GLmmrubqVZAO9z3Gh0v65aZMUD5TQm8GKwqv5vw "05AB1E – Try It Online")
```
i # if
# implicit input
67‹ # is less than 67
? # then output without trailing newline
’¦ì€¸zo¾ã/’™ # "Cenozoic/"
i # if
¹ # first item from input history
4‹ # is less than 4
? # then output without trailing newline
’QuâìÒÇry’ # "Quaternary"
ë i # elif
¹ # first item from input history
‹ # is less than
₂ # 26
Í # - 2 = 24
? # then output without trailing newline
’ÖÌž¹’™ # "Neogene"
ë # else
? # output without trailing newline
’æ§ož¹’™ # "Paleogene"
}} # end if statement (2x)
ë i # elif
¹ # first item from input history
253‹ # is less than 253
? # then output without trailing newline
’€á€Êzo¾ã/’™ # "Mesozoic/"
i # if
¹ # first item from input history
145‹ # is less than 145
? # then output without trailing newline
’±ƒˆÆÁàÔºs’™ # "Cretaceous"
ë i # elif
¹ # first item from input history
‹ # is less than
т # 100
· # * 2 = 200
Ì # + 2 = 202
? # then output without trailing newline
’JҢ턾㒠# "Jurassic"
ë # else
? # output without trailing newline
’Æ×턾㒙 # "Triassic"
}} # end if statement (2x)
ë # else
? # output without trailing newline
’æ§¢äo¾ã/’™ # "Paleozoic"
i # if
¹ # first item from input history
‹ # is less than
3т* # 3 * 100 = 300
? # then output without trailing newline
’„œéên’™ # "Permian"
ë i # elif
¹ # first item from input history
‹ # is less than
₆ # 36
T* # * 10 = 360
?# then output without trailing newline
’®´€¬²¡Ôºs’™ # "Carboniferous"
ë i # elif
¹ # first item from input history
420‹ # is less than 420
? # then output without trailing newline
’Ùç·‹’™ # "Devonian"
ë i # elif
¹ # first item from input history
445‹ # is less than 445
? # then output without trailing newline
’¯ë„¹´€¤’™ # "Silurian"
ë i # elif
¹ # first item from input history
486‹ # is less than 486
? # then output without trailing newline
’€—€·É²·‹’™ # "Ordovician"
ë # else
?# output without trailing newline
’§è¢°’™ # "Cambrian"
# implicit end if statement (5x)
```
] |
[Question]
[
This is a CMC (chat mini challenge) that I posted in our chatroom, [The Ninteenth Byte](http://chat.stackexchange.com/rooms/240/the-nineteenth-byte), a bit ago.
### The Challenge
Given a positive integer `x`, depending on the last 2 bits of `x`, do the following:
```
x & 3 == 0: 0
x & 3 == 1: x + x
x & 3 == 2: x * x
x & 3 == 3: x ^ x (exponentiation)
```
### Input/Output
```
Single Integer -> Single Integer
```
A trailing newline is permitted in the output. No other whitespace is permitted.
### Testcases
```
input output
1 2
2 4
3 27
4 0
5 10
6 36
7 823543
8 0
9 18
10 100
11 285311670611
12 0
```
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so the shortest code wins!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
ị“+×*_”v
```
[Try it online!](https://tio.run/nexus/jelly#@/9wd/ejhjnah6drxT9qmFv239AoSOdwu8qjpjXu/wE "Jelly – TIO Nexus")
## How it works
Firstly, notice that `x&3` is equivalent to `x%4`, where `%` is modulo. Then, since Jelly uses modular indexing (`a[n] == a[n+len(a)]`), so we don't even need to deal with that.
Then:
* If `x%4==0`, return `x_x` (subtraction) (for consistency);
* If `x%4==1`, return `x+x`;
* If `x%4==2`, return `x×x`(multiplication);
* If `x%4==3`, return `x*x`(exponentiation)
Note that Jelly uses 1-indexing, so the subtraction `"_"` is moved to the end.
```
ị“+×*_”v example input: 10
ị“+×*_” index 10 of the string “+×*_”, which gives "×"
v evaluate the above as a Jelly expression,
with 10 as the argument, meaning "10×" is the
expression evaluated. The dyad "×" takes the
second argument from the only argument, effectively
performing the function to itself.
```
[Answer]
# [Python](https://docs.python.org/), 30 bytes
```
lambda x:[0,x+x,x*x,x**x][x%4]
```
[Try it online!](https://tio.run/nexus/python3#S7ON@Z@TmJuUkqhQYRVtoFOhXaFToQXCWhWx0RWqJrH/C4oy80o00jRAZGZeQWmJhiYQ/DcGAA "Python 3 – TIO Nexus")
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 12 bytes
```
ri__"-+*#"=~
```
[Try it online!](https://tio.run/nexus/cjam#@1@UGR@vpKutpaxkW/f/vwUA "CJam – TIO Nexus")
### Explanation
```
ri e# Read an int from input (call it x).
__ e# Duplicate x twice.
"-+*#" e# Push this string.
= e# Get the character from the string at index x (mod 4).
~ e# Eval that char, using the two copies of x from before.
```
Runs one of the following operations depending on `x`'s value mod 4 (mod 4 is equivalent to AND 3).
```
0: - Subtraction
1: + Addition
2: * Multiplication
3: # Exponentiation
```
[Answer]
## Mathematica 25 Bytes
```
0[2#,#*#,#^#][[#~Mod~4]]&
```
Saved 4 Bytes thanks to @MartinEnder
[Answer]
# Pyth, 8 bytes
```
.v@"0y*^
```
[Interpreter](//pyth.herokuapp.com?code=.v%40%220y%2a%5E&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 26 bytes
```
->x{x*[0,2,x,x**~-x][x%4]}
```
[Try it online!](https://tio.run/nexus/ruby#S7P9r2tXUV2hFW2gY6RToVOhpVWnWxEbXaFqElv7X8NQT8/QSFMvN7GguqaipkAhLboCKAwA "Ruby – TIO Nexus")
[Answer]
# PHP, 37 Bytes
```
<?=[0,2*$x=$argn,$x*$x,$x**$x][$x&3];
```
[Online Version](http://sandbox.onlinephpfunctions.com/code/992a252296d9bddff362ea213f918c004681c1dc)
# PHP, 47 Bytes
```
<?=(bc.[sub,add,mul,pow][($x=$argn)&3])($x,$x);
```
[Online Version](http://sandbox.onlinephpfunctions.com/code/29748e1a3da588d1988e55ed9d82273b2a6969e5)
[BC Math functions](http://php.net/manual/en/ref.bc.php)
[Answer]
## Haskell, ~~28~~ 27 bytes
```
f x=cycle[0,x+x,x*x,x^x]!!x
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P02hwja5MjknNdpAp0K7QqdCC4jjKmIVFSv@5yZm5inYKhQUZeaVKKgo5CYWKKQpRBvq6Rkaxf4HAA "Haskell – Try It Online")
Edit: Thanks to @Ørjan Johansen for 1 byte.
[Answer]
# JavaScript, 24 bytes
```
a=>[0,a+a,a*a,a**a][a%4]
```
[Try it online!](https://tio.run/nexus/javascript-node#S7P9n2hrF22gk6idqJOoBcJaibHRiaomsf@T8/OK83NS9XLy0zXSNCw0Na25UIUsMYUMDbCIGQLF/gMA "JavaScript (Node.js) – TIO Nexus")
[Answer]
# C, 63 or 62 bytes
```
#include<math.h>
f(x){return(int[]){0,x+x,x*x,pow(x,x)}[x&3];}
```
-1 byte if macros are allowed, assuming `x` is not an expression like `3+5` (since that'd mess up the precedence):
```
#include<math.h>
#define f(x)(int[]){0,x+x,x*x,pow(x,x)}[x&3]
```
[Answer]
# Java 7, 75 bytes
```
long c(int n){int x=n%4;return x<1?0:x<2?n+n:x<3?n*n:(long)Math.pow(n,n);}
```
Even though it is valid according to the rules, `long` is 64-bits, so it fails for the exponentiation test cases of `19^19` and above. To fix that we can use a `BigDecimal` approach:
**~~148~~ 146 bytes**
```
import java.math.*;BigDecimal c(int n){int x=n%4;BigDecimal m=new BigDecimal(n);return x<1?m.subtract(m):x<2?m.add(m):x<3?m.multiply(m):m.pow(n);}
```
**Explanation (of BigDecimal approach):**
```
import java.math.*; // Import required for BigDecimal
BigDecimal c(int n){ // Method with integer parameter and BigDecimal return-type
int x=n%4; // Input modulo-4
BigDecimal m=new BigDecimal(n); // Convert input integer to BigDecimal
return x<1? // If the input mod-4 is 0:
m.subtract(m) // Return input - input (shorter than BigDecimal.ZERO)
:x<2? // Else if the input mod-4 is 1:
m.add(m) // Return input + input
:x<3? // Else if the input mod-4 is 2:
m.multiply(m) // Return input * input
: // Else:
m.pow(n); // Return input ^ input
} // End of method
```
**Test code:**
[Try it here.](https://tio.run/nexus/java-openjdk#TU9BasMwELz7FUOgINUgSNpeKptC6bWnHEsPiuwmKl5ZyKvEIfjtrpwU2sMyO7PDMOso9JHxbY5GkeGDuteF7cww4P1SAAMbdhbzq9u/tdaR6WCF8wwvLwuMtb971P@uVPv2hD9BeKljyyl6jNX6hdSQdhyNZUHyeaw2WTFNcyMPmVDq2IXuvCikQn9aAqYZCGnX5Sa/hY69a0DGebHl6Pz@4xNGLoWBrz7iWtGhxlpnqGpsnvJSlhI3D7A9D9yS6hOrkANY5LckSqw0VlJfTVOxzDT/AA)
```
import java.math.*;
class M{
static BigDecimal c(int n){int x=n%4;BigDecimal m=new BigDecimal(n);return x<1?m.subtract(m):x<2?m.add(m):x<3?m.multiply(m):m.pow(n);}
public static void main(String[] a){
for (int i = 1; i <= 25; i++) {
System.out.print(c(i) + "; ");
}
}
}
```
**Output:**
```
2; 4; 27; 0; 10; 36; 823543; 0; 18; 100; 285311670611; 0; 26; 196; 437893890380859375; 0; 34; 324; 1978419655660313589123979; 0; 42; 484; 20880467999847912034355032910567; 0; 50;
```
[Answer]
## x86 Assembler, Intel syntax, 192 bytes
```
.data
f dw @q,@w,@e,@r
.code
mov ecx, eax
and ecx, 3
mov edx,dword ptr f[ecx*4]
call [edx]
ret
q:
xor eax,eax
ret
w:
add eax,eax
ret
e:
mul eax,eax
ret
r:
mov ecx,eax
t:
mul eax,eax
loop t
ret
```
Example pretends for fastest working speed. Is is a program or program part, which uses fastcall convention. It assumes input variable `x` in register `eax`, and returns result also in `eax`. Basic idea is stay away from using conditional jumps, as in some examples here. Also, it is not to evaluate everything (as in C example with arrays) but to use array of pointers to functons and make faster unconditional jumps (jmp/call) as an optimized "C language switch()-case.." analog. This technique could be also useful in kinds of finita automata - like processor emulators, executors and so on.
Upd: for x64 use "r" in register names, instead of "e" (e.g. `rax` instead of `eax`, `rcx` instead of `ecx`). Size will not be changed, and it will use 64-bit unsigned words.
[Answer]
# C#, 39 bytes
```
x=>new[]{0,2,x,Math.Pow(x,x-1)}[x&3]*x;
```
### Explanation
Observe that:
(x-x, x+x, x\*x, x^x) == (0, 2, x, x^(x-1)) \* x
The solution creates an array, indexes into it and then multiplies the result by `x`:
```
x => new[] { 0, 2, x, Math.Pow(x,x-1) }[x&3] * x;
```
### Alternative versions:
```
x=>new[]{0,x+x,x*x,Math.Pow(x,x)}[x%4];
```
(39B, all multiplication done in the array, `x%4` replaces `x&3`)
```
x=>x%4<2?x%2*2*x:Math.Pow(x,x%4<3?2:x);
```
(39B, same as @MetaColon's answer but `x%2*2*x` replacing `x*x%4<1?0:2`)
[Answer]
# [Actually](https://github.com/Mego/Seriously), 12 bytes
```
;;3&"-+*ⁿ"Eƒ
```
[Try it online!](https://tio.run/nexus/actually#@29tbaympKut9ahxv5LrsUn//xsDAA "Actually – TIO Nexus")
Explanation:
```
;;3&"-+*ⁿ"Eƒ
;; two copies of input (so 3 total)
3& bitwise AND with 3
"-+*ⁿ"E index into this string
ƒ call the respective function
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
```
Ð"-+*m"è.V
```
Uses the **05AB1E** encoding. [Try it online!](https://tio.run/nexus/05ab1e#@394gpKutlau0uEVemH//5sCAA "05AB1E – TIO Nexus")
[Answer]
# [J](http://jsoftware.com/), 14 bytes
```
4&|{0,+:,*:,^~
```
[Try it online!](https://tio.run/nexus/j#@59ma2WiVlNtoKNtpaNlpRNX9z81OSNfIU3JQMHOyiFTT8HQqIIrtSKz5D8A "J – TIO Nexus")
[Answer]
# [Oasis](https://github.com/Adriandmen/Oasis), 25 bytes
```
mn4%3Q*nkn4%2Q*nxn4%1Q*++
```
[Try it online!](https://tio.run/nexus/oasis#@5@bZ6JqHKiVlw2kjYB0BZA2DNTS1v7//7@hIQA "Oasis – TIO Nexus")
## How it works
Notice that `x&3` is equivalent to `x%4`, where `%` is modulo.
```
mn4%3Q*nkn4%2Q*nxn4%1Q*++ input is n
mn4%3Q* (n**n)*((n%4)==3)
nkn4%2Q* (n**2)*((n%4)==2)
nxn4%1Q* (n*2)*((n%4)==1)
+ add the above two
+ add the above two
```
Oasis is a stack-based language where every character is a command.
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix), 29 bytes
```
.;[[email protected]](/cdn-cgi/l/email-protection):4%!^s;((?u.^P;<^*;
```
[Try it online!](https://tio.run/nexus/cubix#@69nreev7aAX6u9pZaKqGFdsraFhX6oXF2BtE6dl/f@/OQA "Cubix – TIO Nexus")
Explanation will be added soon...
[Answer]
# C#, 42 Bytes
```
x=>x%4<2?x*x%4<1?0:2:Math.Pow(x,x%4<3?2:x)
```
Actually it's normal C#, but as you can't run it as a whole program and you have to type it into the interactive, I guess you may call it *C# interactive*.
**Explanation**:
```
x => (x % 4) < 2 //If the bits are smaller than 2 (1 or 0)
? x * //multiply x with
(x % 4) < 1 //if the bits are 0
? 0 //0 (results in 0)
: 2 //or else with 2 (results in 2*x or x+x)
: Math.Pow(x, //otherwise power x by
(x % 4) < 3 //if the bits are 2
? 2 //2 (results in x^2 or x*x)
: x); //or else x (results in x^x)
```
I can't tell wether it's the shortest variant, any suggestions are appreciated.
[Answer]
# PHP, 36 bytes
```
<?=[0,2,$x=$argn,$x**~-$x][$x&3]*$x;
```
[Answer]
# dc, 27
I've never had the occasion to use arrays in dc before:
```
[+]1:r[*]2:r[^]3:r?dd4%;rxp
```
[Try it online](https://tio.run/nexus/bash#S8svUihJLS5JTixOVcjMU6g21NMzNKq1VkjJ51IAguLUEgVdXQUVmBqwYEFRZl5JmoK6arGCrp2COppsanJGPkJIoUYhJVlBN1VB6X@0dqyhVVG0VqwRkIyLNbYqsk9JMVG1Lqoo@K/ElZKfl/ofAA).
[Answer]
# Groovy, 26 bytes
```
{x->[0,x+x,x*x,x**x][x%4]}
```
[Try it online!](https://tio.run/nexus/groovy#q1CwVQiuLC5JzdXLzNPLSy0PSk1MSS3S0NQrAjJ8MvNSNTQVEosVMvNKuFJS0xTSFGz/V1fo2kUb6FRoV@hUaIGwVkVsdIWqSWzt/4IioMKcPI00jQpNzf/mAA "Groovy – TIO Nexus")
[Answer]
## C, 115 bytes
```
#include<math.h>
#define D(K,L)K(x){return L;}
D(q,0)D(w,x+x)D(e,x*x)D(r,pow(x,x))(*g[])()={q,w,e,r};D(f,g[x%4](x))
```
Example is a function `int f(int x)`
It pretends for fastest working speed as it keeps CPU away from using conditional jumps. And this is only correct speed-optimisation way for this task. Also, it tries not to evaluate everything, as in array C example `return(int[]){0,x+x,x*x,pow(x,x)}[x%4];` But but to wisely use array of pointers to functons, in order to make much faster unconditional jumps (jmp/call) with much faster address arithmetics, as an optimized version of "switch()-case..". This technique could be also useful in several kinds of finita automata - like processor emulators, executors, command stream parsers, and so on - where speed matters and code like `switch(x%4) case(0):... case(1):...` is unsuitable because it produces multiple cmp/jnz instructions; and these are [costly operations for CPU](https://en.wikipedia.org/wiki/Branch_predictor)
Simpliest and shortest test program (in default conditions) for the case will be as follows:
```
D(main,f(x))
```
It will add just 12 bytes of payload and will total our size to 127 bytes;
But you should better tell the linker to use `f` function as an entry point, instead of `main`. That is the way, if we aim to get fastest possible working binary for this task from shortest code ;-) This happens because C library adds extra init/shutdown code before calling your main() function.
Code compiles on MSVS Community 2015 without any tricks and issues and produces correct results. I haven't tested it with gcc, but i'm sure it will work fine as well.
[Answer]
# R, ~~47~~ 42 bytes
```
x=scan();c(`-`,`+`,`*`,`^`)[[x%%4+1]](x,x)
```
Applies the function `-`, `+`, `*`, or `^` based on the modulus of `x` to `x` and `x`.
`-` is the only (somewhat) smart thing, since `x-x` is always 0.
# R, 33 bytes
```
pryr::f(c(0,2*x,x^2,x^x)[x%%4+1])
```
Same method as other people use. Though it is shorter, I don't like it nearly as much.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 12 bytes
```
.vjd,+@"-+*^
```
[Try it online!](http://pyth.herokuapp.com/?code=.vjd%2C%2B%40%22-%2B%2a%5E&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12&debug=0)
## How it works
Firstly, notice that `x&3` is equivalent to `x%4`, where `%` is modulo. Then, since Pyth uses modular indexing (`a[n] == a[n+len(a)]`), so we don't even need to deal with that.
Then:
* If `x%4==0`, return `x-x` (for consistency);
* If `x%4==1`, return `x+x`;
* If `x%4==2`, return `x*x`;
* If `x%4==3`, return `x^x`.
---
```
.vjd,+@"-+*^ example input: 10
@"-+*^ "-+*^"[10], which is "*"
+ "*10"
, ["*10","10"]
jd "*10 10"
.v evaluate as Pyth expression
(Pyth uses Polish notation)
```
More about Polish notation: [Wikipedia](https://en.wikipedia.org/wiki/Polish_notation) (too bad if you are in Turkey).
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 13 bytes
```
Ov"^+*p"gU +U
```
[Try it online!](https://tio.run/nexus/japt#@@9fphSnrVWglB6qoB36/7@hIQA "Japt – TIO Nexus")
This uses the same method as the other eval answers, except the program `-U` just negates `U`, so we use `^` (bitwise XOR) instead.
[Answer]
## Vim, 50 bytes
```
y$o^R"A-+*^^V^[0^R"lx0"_Dp^[0D@"kJ0"ad$:r!echo ^R"^R0|bc^<Enter>
```
Here, `^V` represents a `Ctrl+V`, `^R` represents `Ctrl-R` and `^[` represents the `esc` key
Works by first building up the expression and then letting `bc` evaluate it. Expects the input on the first line in an otherwise empty buffer.
Explanation:
```
y$o^R" Copies the input into register " and pastes it on the second line
A-+*^^V^[0^R"lx0"_Dp Enters that text after the input on the second line
^[0D@" Executes the second line as a Vim command.
For example, if the input is 12, the second line would be 12A-+*^^[012lx0"_Dp, which means:
12A-+*^^[ Insert the text -+*^ 12 times
012lx0"_Dp Go 12 chars to the right and remove everything except for that.
If effect, this basically just selects the appropriate operation.
kJ0"ad$ Put the operator after the number, cut it into register a
:r! Execute the following shell command and put the result into the buffer:
echo ^R"^R0|bc<Enter> The shell command "echo [contents of register a][contents of registers 0]|bc. As said above, register a contains the input and the operator, and register 0 contains the input. The <enter> then executes this command.
```
[Answer]
# Pyth, 9 bytes
```
@[0yQ*QQ^
```
[Test suite](https://pyth.herokuapp.com/?code=%40%5B0yQ%2aQQ%5E&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12&debug=0)
Nothing fancy going on here, just calculate the four values, and select one with modular indexing.
```
@[0yQ*QQ^
@[0yQ*QQ^QQ)Q Implicit variable introduction
@ Q Modularly index into the following list
[0 ) 0
yQ Q*2
*QQ Q*Q
^QQ Q^Q
```
[Answer]
## Batch, 135 bytes
```
@set/an=%1*2^&6
@goto %n%
:6
@set n=1
@for /l %%i in (1,1,%1)do @set/an*=%1
@goto 0
:4
@set n=%1
:2
@set/an*=%1
:0
@echo %n%
```
I was hoping to create the exponentiation by building up and evaluating a string of the form `[0+...+0, 2+...+2, x+...+x, x*...*x]` depending on the last two bits of `x` but unfortunately the code to select the operation took too long to express because I couldn't use `*` as a `for` parameter, but I was at least able to use some fall-though trickery to golf away some bytes.
[Answer]
# [Retina](https://github.com/m-ender/retina), 87 bytes
```
.+
$*1;$&$*
;((1111)*)(1?)$
;$3$3
1(?=1.*;((1111)*111)$)
$1;
+`\G1(?=.*;(1*))|;1*$
$1
1
```
[Try it online!](https://tio.run/nexus/retina#PckxEkBAEETRvM/R1MyoUtoimVJClxA4iLsvm/jBT15n513HAQwlewbSTF8ebjqcSBYWyI5dY/zYRgeVGO7rbNxU4f6kgp9AtU4QZhQsWLG9 "Retina – TIO Nexus") (Link includes test suite.)
Explanation: The first two lines convert the input into unary and duplicate it (so we now have `x;x`). The next two lines look for an `x&3` of either `0` or `1` and change `x;x` into `x;0` or `x;2` appropriately. The next two lines look for `x&3==3` and change `x;x` into `x;x;x;...;x;1;x` (`x` `x`s). This means that we have either `x;0`, `x;2`, `x;x`, or `x;...;x` and it remains to multiply everything together and convert back to decimal. (The multiplication code is based on that in the Retina wiki but amended to handle multiplication by zero.)
] |
[Question]
[
Given a string, character list, byte stream, sequence… which is both valid UTF-8 and valid Windows-1252 (most languages will probably want to take a normal UTF-8 string), [convert it](https://en.wikipedia.org/wiki/Mojibake "Mojibake - Wikipedia") from (that is, *pretend* it is) [Windows-1252](https://en.wikipedia.org/wiki/Windows-1252 "Windows-1252 - Wikipedia") to [UTF-8](https://en.wikipedia.org/wiki/UTF-8 "UTF-8 - Wikipedia").
### Walked-through example
The UTF-8 string
`I` `♥` `U` `T` `F` `-` `8`
is represented as the bytes
`49` `20` `E2 99 A5` `20` `55` `54` `46` `2D` `38`
these byte values in [the Windows-1252 table](https://en.wikipedia.org/wiki/Windows-1252#Character_set) gives us the Unicode equivalents
`49` `20` `E2 2122 A5` `20` `55` `54` `46` `2D` `38`
which render as
`I` `â` `™` `¥` `U` `T` `F` `-` `8`
### Examples
`£` → `£`
`£` → `£`
`£` → `£`
`I ♥ UTF-8` → `I ♥ UTF-8`
`árvíztűrő tükörfúrógép` → `árvÃztűrÅ‘ tükörfúrógép`
[Answer]
## bash, 14 bytes
```
iconv -fCP1252
```
[Try it online!](https://tio.run/##S0oszvj/PzM5P69MQTfNOcDQyNTo//9Di7kON4GI5kcNs8AsT4VHM5cqhIa46VpwHV5YVHZ4bVXJ0Y1FRycqlBzek314W1Ha4V1FhzenH15ZAAA)
[Answer]
# Java 8, ~~72~~ ~~66~~ ~~36~~ 25 bytes
```
s->new String(s,"cp1252")
```
[Try it online.](https://tio.run/##lY8xS8NAFMf3fIpHpgTsgQVBCDoIFRzsop3E4Xq5xkvTu@PuJbVKQPQTOOom4uDQQQQHcfLoF@kXiVfMJghZHjz4/X/v/3Ja0V6eThtWUGvhmAp5HQAIidxMKOMw3KwAJ2iEzIBF4wXys3OwMeCFUXMLuTcQochI2lJrZZCnA8lU6vHBJeMahZKJd9SBHxYpCgZDkLAHje3tSz5v3ZHdCpne7u/0w7hJNrAux4WH20ylRAoz3y/65X0J2qlE@8jCIp8RVSLRXoOFjCRhUfj9HJKM44F/z0ZxHCf/0u62I3@3vnnsGjqC9cMLjE4Pe7udbj2Zyi2vcPVmVveA7mvqPszEfRr3nrlX/VdVB3XzAw)
```
s-> // Method with byte-array (UTF-8 by default) as parameter and String return-type
new String(s,"cp1252")
// Pretend this UTF-8 input is (and convert it to) Windows-1252,
// and return it as UTF-8 String (by default) as well
```
`cp1252` is an alias for `Windows-1252`. This alias `cp1252` is the Canonical Name for the `java.io` and `java.lang` APIs, while the full name `Windows-1252` is the Canonical Name for the `java.nio` API. [See here for a full list of supported Java encodings](https://docs.oracle.com/javase/8/docs/technotes/guides/intl/encoding.doc.html), where we'd always want to use the shortest of the two for codegolfing.
[Answer]
# [R](https://www.r-project.org/) 3.5.0 or higher, ~~32~~ 20 bytes
```
scan(,"",e="latin1")
```
[Try it online!](https://tio.run/##AToAxf9y//9zY2FuKCwiIixlPSJsYXRpbjEiKf8iw6FydsOtenTFsXLFkSB0w7xrw7ZyZsO6csOzZ8OpcCL/ "R – Try It Online")
Oddly short for a [string](/questions/tagged/string "show questions tagged 'string'") challenge in R... *thanks to JayCe for golfing down 12 more bytes!*
`scan` optionally takes an `encoding` argument to set the encoding of the input string. `latin1` corresponds to, according to the documentation of [`Encoding`](https://stat.ethz.ch/R-manual/R-devel/library/base/html/Encoding.html)
>
> There is some ambiguity as to what is meant by a ‘Latin-1’ locale, since some OSes (notably Windows) make use of character positions used for control characters in the ISO 8859-1 character set. How such characters are interpreted is system-dependent but as from R 3.5.0 they are if possible interpreted as per Windows codepage 1252 (which Microsoft calls ‘Windows Latin 1 (ANSI)’) when converting to e.g. UTF-8.
>
>
>
[Answer]
# [Python 2](https://docs.python.org/2/), ~~40~~ 38 bytes
-2 bytes thanks to [Erik the Outgolfer](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer).
```
lambda s:s.decode('1252').encode('u8')
```
[Try it online!](https://tio.run/##K6gsycjPM/qvnJyfkpmXblVqwZVmG/M/JzE3KSVRodiqWC8lFSiVqqFuaGRqpK6pl5oH4ZZaqGv@T8svUihWyMxTUD@0WF1HQf1wE5RuftQwC8bxVHg0c6lCaIibrgVYbmFR2eG1VSVHNxYdnahQcnhP9uFtRWmHdxUd3px@eGWBuhWXgkJBUWZeiUIxUPWjtklATWkaxZr/AQ "Python 2 – Try It Online")
u8 is an alias for `utf-8`.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 31 bytes
```
->s{s.encode("UTF-8","CP1252")}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1664ulgvNS85PyVVQyk0xE3XQklHyTnA0MjUSEmz9n9BaUmxQrTSocVKOlxKh5ugdPOjhlkwjqfCo5lLFaA6gXILi8oOr60qObqx6OhEhZLDe7IPbytKO7yr6PDm9MMrC5Ri9XITC6primvSootja7WUYvKU/iMZAQA "Ruby – Try It Online")
Tests cases are included in the TIO
[Answer]
# [Python 3](https://docs.python.org/3/), ~~38 36~~ 34 bytes
```
lambda s:s.encode().decode('1252')
```
[Try it online!](https://tio.run/##K6gsycjPM/6vnJyfkpmXblVqwZVmG/M/JzE3KSVRodiqWC81DyiVqqGpl5IKZqgbGpkaqWv@T8svUihWyMxTiFY/tFhdR0H9cBOUbn7UMAvG8VR4NHOpQmiIm64FWG5hUdnhtVUlRzcWHZ2oUHJ4T/bhbUVph3cVHd6cfnhlgXqsFZcCEBQUZeaVaBQDNTxqmwTUl6ZRrKn5HwA "Python 3 – Try It Online")
*note: After I had a working function I used [ovs's python2 answer](https://codegolf.stackexchange.com/a/167246/79918) answer to learn about the header and footer fields for tio, so the header and footer are the same*
*edit: Trimmed it a little thanks to python3 defaulting to utf8 and a tip from ovs's submission :)*
[Answer]
# C#, 81 bytes
```
using e=System.Text.Encoding;s=>e.GetEncoding(1252).GetString(e.UTF8.GetBytes(s))
```
[Try it online!](https://tio.run/##hU29SgNBEO73KYZUe0UWEhAC4Sz8RdAqEevzbu5YsrcbdibBKHkIS0sLCwsLESzEbsmL5EXOPXOxdZqZ72e@L6d@7axrmgVpW8FkRYz1WOwQpjuspnjH6tTmroj0WIgCDVYZIxD71niCRnYnJVGfL26NziE3GRHUmbbwICBOxxNnHNfS6QKuoiqTTm8nZkEJKVB6iOoceV8rB8ODYdIyk98miep6ejZqiaMVI0lKYvU@5dhZcgbVjdeMl9qiLGXvArZPLxC/@qPev@bw7Jfh7Z43737zCBy@Z@HTl@HLh48qvM7/AtZi3TQ/ "C# (Mono C# compiler) – Try It Online")
Thanks to Schmalls for 3 bytes
[Answer]
# 180 bytes, machine code (16-bit x86)
I noticed most answers use builtin encode/decode (which I believe is perfectly fine), but I thought I'll continue [my 16-bit quest](https://codegolf.stackexchange.com/a/180194/74387).
As with previous ones, this was done **without compiler** using mostly [HT hexeditor](http://hte.sourceforge.net) and [ICY's hexplorer](https://sourceforge.net/projects/hexplorer/).
```
00000000: eb40 ac20 0000 1a20 9201 1e20 2620 2020 .@. ... ... &
00000010: 2120 c602 3020 6001 3920 5201 0000 7d01 ! ..0 `.9 R...}.
00000020: 0000 0000 1820 1920 1c20 1d20 2220 1320 ..... . . . " .
00000030: 1420 dc02 2221 6101 3a20 5301 0000 7e01 . .."!a.: S...~.
00000040: 7801 89f7 4646 89fa 89d9 4143 4bb4 3fcd x...FF....ACK.?.
00000050: 2185 c074 288a 053c 8073 05e8 1700 ebec !..t(..<.s......
00000060: 3ca0 721a d440 0d80 c050 86c4 e806 0058 <[[email protected]](/cdn-cgi/l/email-protection)
00000070: e802 00eb d7b4 4088 05b3 01cd 21c3 2c80 ......@.....!.,.
00000080: d0e0 89c3 8b00 89cb 85c0 74c0 3dff 0773 ..........t.=..s
00000090: 08c1 c002 c0e8 02eb cd50 c1e8 0c0c e0e8 .........P......
000000a0: d3ff 5825 ff0f c1c0 02c0 e802 0d80 8050 ..X%...........P
000000b0: 86c4 ebb8 ....
```
[](https://i.stack.imgur.com/wOX9W.png)
## Dissection
Implementation is pretty straight-forward, although I haven't given much thought to flow upfront so there is SOME spaghetti there.
I'll mix order a bit, to make it easier to follow...
```
0000 eb40 jmp 0x42
```
Skip over table that maps chars >= 0x80 < 0xa0, to unicode codes.
```
data db ACh,20h, 00h,00h, 1Ah,20h, ...
```
Invalid ones are encoded as 0, they are not mapped to anything
```
0075 b440 mov ah, 0x40
0077 8805 mov [di], al
0079 b301 mov bl, 0x1
007b cd21 int 0x21
007d c3 ret
```
Helper function used to print char in `al`, will be called few times.
```
0042 89f7 mov di, si
0044 46 inc si
0045 46 inc si
0046 89fa mov dx, di
0048 89d9 mov cx, bx
004a 41 inc cx
004b 43 inc bx
```
Prepare registers. Data will be read into 0x100, let `si` point into translation table above.
```
004c 4b dec bx
004d b43f mov ah, 0x3f
004f cd21 int 0x21
0051 85c0 test ax, ax
0053 7428 jz 0x7d
```
Read char from stdin, jump to 0x7d if EOF.
Sidenote: This actually is a small (but pretty well known) trick, 0x7d contains `ret`,
this will cause `pop sp`, `sp` at start points to end of a segment, there's `00 00` there, and `cs:0` in DOS contains `CD 20`, which causes application to exit.
```
0055 8a05 mov al, [di]
0057 3c80 cmp al, 0x80
0059 7305 jnc 0x60
005b e81700 call 0x75
005e ebec jmp 0x4c
```
If char is < 0x80, just print it out, and go to beginning of loop
(because helper function is setting BX to 1 - stdout, jumps will go to `dec bx`)
```
0060 3ca0 cmp al, 0xa0
0062 721a jc 0x7e
0064 d440 aam 0x40
0066 0d80c0 or ax, c080
0069 50 push ax
006a 86c4 xchg ah, al
006c e80600 call 0x75
006f 58 pop ax
0070 e80200 call 0x75
0073 ebd7 jmp 0x4c
```
This part deals with chars >= 0xa0, splits ascii code into "high" two bits and "low" 6 bits and applies utf-8 mask c080 for two bytes, then prints both of them
```
007e 2c80 sub al, 0x80
0080 d0e0 shl al, 0x1
0082 89c3 mov bx, ax
0084 8b00 mov ax, [bx+si]
0086 89cb mov bx, cx
0088 85c0 test ax, ax
008a 74c0 jz 0x4c
008c 3dff07 cmp ax, 07ff
008f 7308 jnc 0x99
0091 c1c002 rol ax, 0x2
0094 c0e802 shr al, 0x2
0097 ebcd jmp 0x66
```
This part deals with chars >= 0x80 < 0xa0, it finds proper utf-8 code in the table at the top, if code equals 0, just skip to beginning, if it's below 0x7ff (ergo: fits on two UTF-8 bytes), just adjust the value and re-use previous code at 0x166.
```
0099 50 push ax
009a c1e80c shr ax, 0xc
009d 0ce0 or al, e0
009f e8d3ff call 0x75
00a2 58 pop ax
00a3 25ff0f and ax, 0fff
00a6 c1c002 rol ax, 0x2
00a9 c0e802 shr al, 0x2
00ac 0d8080 or ax, 8080
00af 50 push ax
00b0 86c4 xchg ah, al
00b2 ebb8 jmp 0x6c
```
Final part, deals with codes that are above 0x7FF, drop low 12 bits,
apply 0xE0 (see [UTF-8 encoding description](https://en.wikipedia.org/wiki/UTF-8#Description) for reference) and print it out,
adjust lower 12 bits and apply 8080 mask and again reuse part that spits out two chars.
[Answer]
# JavaScript, 64 bytes
```
x=>new TextDecoder('cp1252').decode(new TextEncoder().encode(x))
```
```
f =
x=>new TextDecoder('cp1252').decode(new TextEncoder().encode(x))
```
```
<p><input id=i oninput="o.value=f(i.value)" style="width:100%" /></p>
<p><output id=o></output></p>
```
Even longer than Java answer. So sad. :(
[Answer]
## [PHP](http://php.net/)+[mbstring](http://php.net/manual/en/book.mbstring.php), ~~63~~ 49 bytes
`<?=mb_convert_encoding($argv[1],'UTF8','CP1252');`
It doesn't work on TIO due to the lack of mbstring.
The third parameter force mbstring to interpret the string as Windows-1252 encoded
-14 bytes thanks to Ismael Miguel
[Answer]
# [C (gcc)](https://gcc.gnu.org/) + [`libiconv`](https://www.gnu.org/software/libiconv/), 119 117 bytes
```
*f(s,t,u)void*s,*t,*u;{long i=strlen(s),j=i*4;u=t=malloc(j);iconv(iconv_open("UTF8","CP1252"),&s,&i,&u,&j);return t;}
```
[Try it online!](https://tio.run/##XY1NasMwEIX3PsXggpHEpODQQkB1NoFAd1mkqxKCKzvOBEUK@vEm5CA9QC/Wi6iKV203j/e@ebxRs0Gp9EBG6dj18OJDR/bxuCx@I0dm@M86TR9/GSlrxoySODCPASMfLXXCowgoorxqawagJs/p3jDP8dSQeJKxCc251doqduJyGmGT7u0l98q37XpRYrna1PPnecmx8lgRVhGrXHd9iM5AkLdEJsC5JcPupnWDQnVsHQiR/cjhWgDQgd0Py5rDJQbPpji@1zvOZXFL6RW@P78gP5wtfgA "C (gcc) – Try It Online")
[Answer]
# Scala 3, 18 bytes
Simply a port of [Kevin Cruijssen's Java answer](https://codegolf.stackexchange.com/a/167239/95792)
```
String(_,"cp1252")
```
[Try it in Scastie!](https://scastie.scala-lang.org/gGDVsWJ4RICsWZt8LY1QuQ)
Ordinarily, I wouldn't post such a trivial answer, but this demonstrates Scala 3's universal apply methods, which let you omit `new`.
] |
[Question]
[
### Introduction
It's 2600 BC and people are building pyramids now. They already made the basis of the pyramid but don't know how to continue. So, they called you for help.
The rules of making a pyramid is quite simple. For the layer above the previous layer, all you need to do is follow this step-by-step hand guide:
1. Cut the edges off the previous layer.
2. Above the `/` character, there must be a `\` character and vice versa. This applies to every character **except** the edges.
3. The leftmost character is always a `/` and the rightmost character is always `\`.
Let's take an example of a basis for a pyramid:
```
//\/\/\\
```
We cut off the edges, leaving:
```
/\/\/\
```
We change the forward slashes with backward slashes and vice versa:
```
\/\/\/
```
The leftmost character is always a `/` and the rightmost character is always a `\`, so we change that:
```
//\/\\
```
We place this layer on the previous layer:
```
//\/\\
//\/\/\\
```
We continue until the top is reached (which looks like `/\`). So, eventually we get:
```
/\
//\\
//\/\\
//\/\/\\
```
This is what you need to output.
### The task
Given the basis of a pyramid (with a length greater than 3), output the full pyramid. You can safely assume that the leftmost character is `/` and the rightmost character is a `\`. You can also assume that the length of the basis is always **even**. The use of **trailing spaces** is allowed. The use of **leading spaces** is also allowed, as long as the pyramid stays in place. The use of 1 **trailing** and 1 **leading** newlines is allowed.
### Test cases
```
Input: /\\\
Output:
/\
/\\\
Input: //\\///\/\
Output:
/\
/\\\
/\///\
///\\\/\
//\\///\/\
Input: /////////////\
Output:
/\
/\\\
/////\
/\\\\\\\
/////////\
/\\\\\\\\\\\
/////////////\
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the submission with the least amount of bytes wins!
[Answer]
# [Retina](http://github.com/mbuettner/retina), ~~59~~ ~~56~~ ~~54~~ 52 bytes
```
{`^( *)/.(.*)..
$1 /$2\¶$0
T`/\\`Ro`(?<=^ +/).+(?=.)
```
[Try it online!](http://retina.tryitonline.net/#code=e2BeKCAqKS8uKC4qKS4uCiQxIC8kMlzCtiQwClRgL1xcYFJvYCg_PD1eICsvKS4rKD89Lik&input=Ly9cXC8vL1wvXA)
## Sample output
```
/\
/\\\
/\///\
///\\\/\
//\\///\/\
```
[Answer]
# Pyth - ~~27~~ 26 bytes
Reduces by the operation given in the OP until it repeats, which is the case for the blank line.
```
j_.e+*kdb.ujXtPtPNK"\/")_K
```
[Test Suite](http://pyth.herokuapp.com/?code=j_.e%2B%2akdb.ujXtPtPNK%22%5C%2F%22%29_K&test_suite=1&test_suite_input=%22%2F%2F%5C%5C%2F%5C%5C%2F%5C%5C%5C%5C%22%0A%22%2F%5C%5C%5C%5C%5C%5C%22%0A%22%2F%2F%5C%5C%5C%5C%2F%2F%2F%5C%5C%2F%5C%5C%22%0A%22%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%5C%5C%22&debug=0).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~28 26 25~~ 24 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
QṚ,QyḊḊṖṖj@QµÐĿµJ’⁶ẋ⁸żYṚ
```
-4 bytes thanks to Dennis
Recipe:
```
QṚ,QyḊḊṖṖj@QµÐĿµJ’⁶ẋ⁸żYṚ - one argument: input()
Q Q Q - set of Left=input(): "/\"
Ṛ - reverse Left: "\/"
, - Left-pair-Right: ["\/","/\"]
ḊḊṖṖ - dequeue Left twice, then pop twice: input()[2:-2]
y - translate Right with mapping in Left: swaps internal slashes
j@ - join Right with separator Left (@ swaps operands)
µ µ - chain separators to form a 1,1,1 chain of chains
ÐĿ - loop while results are unique and collect them
J - yield [1,...,len(Left=input())]
’ - decrement: [0,....len(input())-1]
⁶ - " "
ẋ - repeat Left Right times: ["", " ", ...]
⁸ż - zip Right and Left (⁸ is the link's Left argument):
...pads the loop results
Y - joins Left with line-feeds
Ṛ - reverse Left
```
*(serve with lemonade, those pyramids make for thirsty workers)*
Cook up your own slash pyramid at [**TryItOnline**](http://jelly.tryitonline.net/#code=UeG5mixReeG4iuG4iuG5luG5lmpAUcK1w5DEv8K1SuKAmeKBtuG6i-KBuMW8WeG5mg&input=&args=L1xcLy9cL1xcL1xcLy9cLy8vXC8vL1wvXC9cXFwvXFxcL1wvL1xcL1wvL1wvXFwvL1w), or try out all the [OP's suggested tasters](http://jelly.tryitonline.net/#code=UeG5mixReeG4iuG4iuG5luG5lmpAUcK1w5DEv8K1SuKAmeKBtuG6i-KBuMW8WeG5mgrhuaPigJ18w4figqxZ&input=&args=L1xcXHwvL1wvXC9cXHwvL1xcLy8vXC9cfC8vLy8vLy8vLy8vLy9c)
[Answer]
## Python 2, 78 bytes
```
f=lambda s,p='\n':(s[2:]and f('/%s\\'%s.translate('/\\'*128)[2:-2],p+' '))+p+s
```
A recursive function that outputs a string. Each layer of the pyramid is appended to the recursive call with the layer above it. The prefix `p`, which starts as a newline character gains one more space to make the triangle. The next layer is produced by swapping slashes, cutting off the first and last two symbols, and sandwiching it inside a left and right slash.
Python 3 can save a byte by doing `*99` in the `translate`, as the length-256 requirement was dropped.
[Answer]
## Haskell, ~~98~~ ~~94~~ ~~90~~ 85 bytes
```
q=init.tail
s '/'='\\'
s _='/'
t#""=t++"\\\n"
t#l=(' ':t)#(s<$>q l)++t++l#""
("/"#).q
```
Usage example (note: in Haskell backslashes within literal strings have to be escaped `\\`):
```
*Main> putStr $ (("/"#).q) "//\\\\///\\/\\"
/\
/\\\
/\///\
///\\\/\
//\\///\/\
```
Simple recurse approach: `#` does the work by mapping `s`, which flips the `/` and `\`, on the inner elements. The additional parameter `t` keeps track of the indention level and is expanded by a space on each recursive call.
Note: the second recursive call of `#` (-> `l#""`) jumps directly to the base case and is just a short way to add `l`, `\` and a newline, i.e. it replaces `++l++"\\\n"`.
Edit: @xnor saved 5 bytes. Thanks!
[Answer]
# Python 3, ~~108 104 101 94 91 89~~ 88 bytes
```
b,f='\/';p=lambda t,n='\n':(t[2:]and p(f+''.join(map({f:b,b:f}.get,t[2:-2]))+b,n+' '))+n+t
```
-7 bytes thanks to xnor (letting me know we don't have to print!)
-3 bytes thanks to xnor (taking declaration outside of function declaration [d'oh])
-1 byte thanks to Dennis (replace `f,b='/\\'` with `b,f='\/'`)
Test it on [**ideone**](http://ideone.com/144ywY). Note: input adjusted for double backslash (even raw strings won't work if they end in an odd number of backslashes).
[Answer]
## JavaScript (ES6), ~~91~~ 86 bytes
```
f=
(s,t=`
`)=>s[2]?f(`/${s.slice(2,-2).replace(/./g,c=>c>`/`?`/`:`\\`)}\\`,t+` `)+t+s:t+s
;
```
```
<input placeholder=Basis oninput=o.textContent=f(this.value)><pre id=o>
```
Output includes a leading newline character.
[Answer]
# Ruby, 80 bytes
```
f=->s{s[-3]>?!&&f[" "+s.gsub(/^( *\/).|.(.$)?/){$1||$2||($&>?/??/:?\\)}]
puts s}
```
## Ungolfed
```
f = ->s{
s[-3] > ?! &&
f[" " + s.gsub(/^( *\/).|.(.$)?/) {
$1 || $2 || ($& > ?/ ? ?/ : ?\\)
}]
puts s
}
```
See it on ideone: <http://ideone.com/HN0l0Y>
[Answer]
## Batch, 137 bytes
```
@echo off
if %1==/\ goto g
set s=%1
set s=\%s:~2,-2%/
set s=%s:/=-%
set s=%s:\=/%
set s=%s:-=\%
call %0 %s% "%~2 "
:g
echo %~2%1
```
Conveniently my use of`%~2` and `%1` means that I avoid having to spend bytes on `setlocal`. Explanation: Since Batch won't perform replacements on the empty string, we have to set up the next layer with the "wrong" edges, which will then be corrected as part of the string replacements.
[Answer]
# BASH (sed + sort) 71 66 Bytes
```
~~sed -rne':l;p;y|\\|1|;y|/|\\|;y|1|/|;th;:h;s|\\.(.\*)./| /\1\\|;tl'|sort~~
sed -rne':l;p;y|\\/|1\\|;y|1|/|;th;:h;s|\\.(.*)./| /\1\\|;tl'|sort
```
input comes from stdin.
Example:
```
echo '//\\' |sed -rne':l;p;y|\\|1|;y|/|\\|;y|1|/|;th;:h;s|\\.(.*)./| /\1\\|;tl'|sort
/\
/\\\
```
Explanation:
`-n` - suppress auto print
`:l` - and `tl` branch back to the beginning if this line was something other than `/\`
`p` - print this line
`y|\\/|1\\|;y|1|/|` - replace `\` with `1`, `/` with `\`, and then `1` with `/`
`th;:h` - test and jump the the same place, so that only the next substitution gets tested later
`s|\\.(.*)./| /\1\\|` - replace the outside two slashed on each side with `{space}/` and `\`
`sort` - `space` comes before `/` so this puts everything in the right order
[Answer]
# 05AB1E, ~~42~~ ~~38~~ 36 bytes
```
Dg;<FÐgÍ©£R®ÍN-£„/\‡'/ðN>׫«R'\«}r»
```
[Try it online!](http://05ab1e.tryitonline.net/#code=RGc7PEbDkGfDjcKpwqNSwq7DjU4twqPigJ4vXMOC4oChJy_DsE4-w5fCq8KrUidcwqt9csK2w70&input=Ly8vLy8vLy8vLy8vL1w)
Explanation:
```
# Read the input to the stack, loop for 0 .. len(input) / 2 - 1
Dg;<F
# Save the layer by pushing a copy on the stack, then push
# len(layer) - 2 to both the top of the stack and register_c
ÐgÍ©
# a = pop(); b = pop(); push(b[0:a].reverse())
# This removes the last 2 characters and reverses
£R
# push(register_c - 2 - N)
®ÍN-
# a = pop(); b = pop(); push(b[0:a])
# This removes the leading spaces and the first two slashes
£
# Push "/\" and "\/" to the stack.
„/\Â
# Transliterate the slashes
‡
# Add N+1 spaces and a / to the end of the (reversed) current layer
'/ðN>׫«
# Reverse the layer and add a \ to the end.
R'\«
# End the loop
}
# Reverse the stack and join it with newlines. It is implicitly printed.
r»
```
(Thanks to [Emigna](https://codegolf.stackexchange.com/users/47066/emigna) for pointing out that `DD -> Ð` and `DR -> Â`).
[Answer]
# Go, ~~300~~ 276 bytes
```
package main
import(."regexp";."os")
func p(b string)string{
s:=MustCompile(`((\s*.)(\S*)(\S))`).FindStringSubmatch(b)
if s[3]!=""{r:=""
for _,c:=range s[3][1:len(s[3])-1]{r+=`\/`[c/64:c/46]}
return p(" "+s[2]+r+`\`)+s[1]+"\n"}
return s[1]+"\n"}
func main(){print(p(Args[1]))}
```
Long version:
```
package main
import (
"regexp"
"os"
)
func pyramid(base string) string {
m := regexp.MustCompile(`^((\s*\S)(\S*)(\S))\s*`).FindStringSubmatch(base)
if len(m[3]) > 0 {
reversed := ""
for _, c := range m[3][1:len(m[3]) - 1] {
if c == '/' {
reversed += `\`
} else {
reversed += `/`
}
}
return pyramid(" " + m[2] + reversed + m[4]) + m[1] + "\n"
}
return m[1] + "\n"
}
func main() {
print(pyramid(os.Args[1]))
}
```
[Answer]
# Perl, ~~53~~ 52 bytes
Includes +1 for `-p`
Run with the input on STDIN, e.g.
```
./pyramid.pl <<< '//\\///\/\'
```
`pyramid.pl`:
```
#!/usr/bin/perl -p
s%^( *)/.(.*)..%"$1 \\$2/
"=~y|\\/|/\\|r.$&%e&&redo
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 31 bytes
```
Dg;GDðK¦¦¨¨„/\‡'\«R'/«ðN׫R}r»
```
**Explanation**
```
Dg;G } # for N in [1..len(input)/2-1]
D # make a copy of previous layer
ðK # remove all spaces
¦¦¨¨ # remove first 2 and last 2 chars
„/\‡ # replace '/' with '\' and vice versa
'\« # add a backslash at the end
R # reverse
'/« # ad a slash at the end
ðN׫ # add N spaces
R # reverse back
r» # reverse stack and join on newline
# implicitly print
```
[Try it online](http://05ab1e.tryitonline.net/#code=RGc7R0TDsEvCpsKmwqjCqOKAni9cw4LigKEnXMKrUicvwqvDsE7Dl8KrUn1ywrbDvQ&input=Ly8vLy8vLy8vLy8vL1w)
[Answer]
## [><>](http://esolangs.org/wiki/Fish), ~~186~~ ~~179~~ ~~175~~ 171 bytes
```
0&v &+1&<
>i:0)?^~&2,:&v
v'/'~v?:-1< }0<
o >84*o^-$;?=@:&:&}:~<
\&::&{:@+$}1+[{l1-$-2*:&1+{
>}1-:?!v$:l2%?!vo
^o'/'v?~e (*5a<
^o'\'< & >~]a'\'oo{1+:^
{$1- >:?!^
```
oooh man this is definitely my largest ><> answer yet.
There's still probably some golfing left to be done (the bottom area is pretty wasteful)
[Try it online](https://fishlanguage.com/playground/dzyWS8NjBH8zcFgBF)
[Answer]
## Powershell, 142 bytes
```
function s($s){if($s.Trim()-eq'/\'){return $s}
$n=$s-replace'\\','#'-replace'/','\'-replace'#','/'-replace'\\.(.*)./',' /$1\'
(s($n))+"`n$s"
}
```
[Answer]
## C#, 250 bytes
```
s=>{int j=s.Length/2,i=0;var l=new string[j];l[j-1]=s;while(++i<j){var n=l[j-i].Trim().Substring(1,l[j-i].Trim().Length-2);l[j-i-1]=new string(' ',i)+"/"+n.Replace("/","#").Replace(@"\","/").Replace("#",@"\").Substring(1,n.Length-2)+@"\";}return l;};
```
Can definitely be golfed further but my brain went dead so I decided to leave it as it is for the moment.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 22 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
à╝á■╬h½₧£Hδuóß►Δ䣃┐#R
```
[Run and debug it](https://staxlang.xyz/#p=85bca0fece68ab9e9c48eb75a2e110ffeb9c9fbf2352&i=%2F%5C%5C%5C%0A%2F%2F%5C%5C%2F%2F%2F%5C%2F%5C%0A%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%5C&m=2)
] |
[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]
[
## Challenge
Given a positive integer \$N\$, repeat each of its digits \$d\_1, d\_2, d\_3, \cdots, d\_n\$ a number of times corresponding to its position in \$N\$. In other words, each digit \$d\_k\$ should be repeated \$k\$ times (for each \$1\le k\le n\$, 1-indexed), thus creating the new number:
$$\overline{d\_1d\_2d\_2d\_3d\_3d\_3\cdots\underbrace{d\_nd\_nd\_n\cdots d\_n}\_{n\text { times}}}$$
Then, write it down both horizontally and vertically and fill in the blanks with copies of the digit that corresponds to the greater index between the column index and the row index of the blank space. The final output should look like this:
$$\begin{bmatrix}
\color{red}{d\_1} \color{green}{d\_2 d\_2} \color{blue}{d\_3 d\_3 d\_3} \cdots \\
\color{green}{d\_2 d\_2 d\_2} \color{blue}{d\_3 d\_3 d\_3} \cdots \\
\color{green}{d\_2 d\_2 d\_2} \color{blue}{d\_3 d\_3 d\_3} \cdots \\
\color{blue}{d\_3 d\_3 d\_3 d\_3 d\_3 d\_3} \cdots \\
\color{blue}{d\_3 d\_3 d\_3 d\_3 d\_3 d\_3} \cdots \\
\color{blue}{d\_3 d\_3 d\_3 d\_3 d\_3 d\_3} \cdots \\
\vdots
\end{bmatrix}$$
---
## Specs
You may take \$N\$ as an integer, a string, a list of digits or a list of characters representing the digits. The output can be a newline-separated string, a list of strings / integers or a list of lists of characters / digits, but please include a pretty-print version too, if possible. If the output is a newline-separated string, it is also acceptable to:
* have leading / trailing whitespace, as long as the visual appearance of the output doesn't change
* separate the columns using a consistent amount spaces or the rows with a consistent (non-zero) amount of newlines
You can take input and provide output through any [standard method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), while taking note that [these loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden by default. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so try to complete the task in the least bytes you can manage in your [language](https://codegolf.meta.stackexchange.com/a/2073/59487) of choice.
## Test cases
```
65:
655
555
555
---------------
203:
200333
000333
000333
333333
333333
333333
--------------
233:
233333
333333
333333
333333
333333
333333
---------------
5202:
5220002222
2220002222
2220002222
0000002222
0000002222
0000002222
2222222222
2222222222
2222222222
2222222222
---------------
12345:
122333444455555
222333444455555
222333444455555
333333444455555
333333444455555
333333444455555
444444444455555
444444444455555
444444444455555
444444444455555
555555555555555
555555555555555
555555555555555
555555555555555
555555555555555
```
[Answer]
# JavaScript (ES7), 70 bytes
Takes input as a string. Returns a string with a trailing linefeed.
```
s=>(g=x=>(c=s[(x>y?x:y)**.5-1>>1])?c+g(x+8):x>y?`
`+g(1,y+=8):'')(y=1)
```
[Try it online!](https://tio.run/##bcxBCoMwFATQvRfJ/6aKiU0pwo8HKQUl1VARU5pSktOncVvcDMwbmGX8jt68n69PtbnHlGZKnjRYCjkN@RsEHfvQRSzLWlVCa3HH3nALgV@x28ehGHIVp8gpC2MIkQQm4zbv1qlenYUZ2EUxxOIPZdMeqJKNPGAh2/N@kn4 "JavaScript (Node.js) – Try It Online")
## How?
### Method
We build the output character by character by walking through a square matrix and converting each cell into an index \$i\_{x,y}\$ into the input string.
### Coordinates to string index
The upper bound \$u\_{n}\$ of the \$n^{th}\$ digit area (0-indexed) along each axis is given by [A000096](https://oeis.org/A000096):
$$u\_{n} = \frac{n(n+3)}{2}$$
$$u\_{0}=0,u\_{1}=2,u\_{2}=5,u\_{3}=9,u\_{4}=14,u\_{5}=20,\dots$$
Given an integer \$k\$, we can find out in which area \$n=\lfloor{x}\rfloor+1\$ it is located by solving:
$$x²+3x-2k=0$$
Leading to:
$$x = \frac{\sqrt{1+8k}-3}{2}$$
$$n = \left\lfloor\frac{\sqrt{1+8k}-3}{2}\right\rfloor+1=\left\lfloor\frac{\sqrt{1+8k}-1}{2}\right\rfloor$$
For each cell \$(x, y)\$, we define:
$$v\_{x,y} = \max(1+8x,1+8y)$$
These values \$v\_{x,y}\$ are converted into indices \$i\_{x,y}\$ into the input string by doing:
$$i\_{x,y} = \left\lfloor\frac{\sqrt{v\_{x,y}}-1}{2}\right\rfloor$$
```
v(x,y) | 0 1 2 3 4 5 6 7 8 9 i(x,y) | 0 1 2 3 4 5 6 7 8 9
--------+------------------------------- --------+-------------------------------
0 | 1 9 17 25 33 41 49 57 65 73 0 | 0 1 1 2 2 2 3 3 3 3
1 | 9 9 17 25 33 41 49 57 65 73 1 | 1 1 1 2 2 2 3 3 3 3
2 | 17 17 17 25 33 41 49 57 65 73 2 | 1 1 1 2 2 2 3 3 3 3
3 | 25 25 25 25 33 41 49 57 65 73 3 | 2 2 2 2 2 2 3 3 3 3
4 | 33 33 33 33 33 41 49 57 65 73 --> 4 | 2 2 2 2 2 2 3 3 3 3
5 | 41 41 41 41 41 41 49 57 65 73 5 | 2 2 2 2 2 2 3 3 3 3
6 | 49 49 49 49 49 49 49 57 65 73 6 | 3 3 3 3 3 3 3 3 3 3
7 | 57 57 57 57 57 57 57 57 65 73 7 | 3 3 3 3 3 3 3 3 3 3
8 | 65 65 65 65 65 65 65 65 65 73 8 | 3 3 3 3 3 3 3 3 3 3
9 | 73 73 73 73 73 73 73 73 73 73 9 | 3 3 3 3 3 3 3 3 3 3
```
### Halting conditions
We know that we've reached:
* the right boundary of the matrix when the character at \$i\_{x,y}\$ does not exist and we have \$x > y\$
* the bottom boundary of the matrix when the character does not exist and we have \$x \le y\$
[Answer]
# [J](http://jsoftware.com/), 16 15 bytes
-1 byte thanks to FrownyFrog!
```
{~#\<:@>./~@##\
```
[Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8L@6TjnGxsrBTk@/zkFZOea/JpeSnoJ6mq2euoKOQq2VQloxF1dqcka@QpqCupmpOoStrg4XMzIwxhQ0NTIwwhQ1NDI2MVX/DwA "J – Try It Online")
Takes `N` as a string.
## Explanation of th initial solution:
```
#\ finds the length of the successive prefixes of the input (1 2 3...)
#~ copies each digit as many times (1 2 2 3 3 3...)
>./~@ and creates a table of the max of the row/col numbers
[:<:@ then subtract 1 from each element (for indexing)
{~ select the corresponding digit from the input
```
Test session with input `203`:
```
#\ '203'
1 2 3
#~#\ '203'
1 2 2 3 3 3
>./~@#~#\ '203'
1 2 2 3 3 3
2 2 2 3 3 3
2 2 2 3 3 3
3 3 3 3 3 3
3 3 3 3 3 3
3 3 3 3 3 3
<:@>./~@#~#\ '203'
0 1 1 2 2 2
1 1 1 2 2 2
1 1 1 2 2 2
2 2 2 2 2 2
2 2 2 2 2 2
2 2 2 2 2 2
({~[:<:@>./~@#~#\) '203'
200333
000333
000333
333333
333333
333333
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
Jx`»þ`ị
```
[Try it online!](https://tio.run/##y0rNyan8/9@rIuHQ7sP7Eh7u7v7//3@0qY6CkY6CAZCMBQA "Jelly – Try It Online")
[Clarified output.](https://tio.run/##y0rNyan8/9@rIuHQ7sP7Eh7u7v5/uN39//9oUx0FIx0FAyAZCwA)
[Answer]
# [Haskell](https://www.haskell.org/), ~~60~~ ~~59~~ 58 bytes
```
f x|s<-do(n,_)<-zip[0..]x;n<$[0..n]=[(x!!).max a<$>s|a<-s]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P02hoqbYRjclXyNPJ17TRrcqsyDaQE8vtsI6z0YFxMqLtY3WqFBU1NTLTaxQSLRRsSuuSbTRLY79n5uYmadgq5CbWOCrUFBaElxS5JOnoKKQpqBkbGRooPQfAA "Haskell – Try It Online")
---
### Point-free version (68 bytes)
```
(map=<<(.((snd.).max)).flip map).((\t@(n,c)->t<$[1..n])=<<).zip[1..]
```
[Try it online!](https://tio.run/##y0gszk7NyfmfZhvzXyM3scDWxkZDT0OjOC9FT1MvN7FCU1MvLSezQAEopQkUjylx0MjTSdbUtSuxUYk21NPLi9UEatHUq8osAHFj/@cmZuYp2ILU@yoUlJYElxT55CmoKKQpKBkbGRoo/f@XnJaTmF78XzfCOSAAAA "Haskell – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 71 bytes
```
i=j=0;r=''
for x in input():i+=1;r+=x*i
for c in r:print j*c+r[j:];j+=1
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9M2y9bAushWXZ0rLb9IoUIhMw@ICkpLNDStMrVtDa2LtG0rtDLBkskgySKrgqLMvBKFLK1k7aLoLKtY6yygsv//1ROTklMS1QE "Python 2 – Try It Online")
First generates the first row `r`, then iterates over `r` to print each line.
[Answer]
# [R](https://www.r-project.org/), 59 bytes
```
function(a){m=outer(x<-rep(g<-seq(a),g),x,pmax);m[]=a[m];m}
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jUbM61za/tCS1SKPCRrcotUAj3Ua3OLUQKKGTrqlToVOQm1ihaZ0bHWubGJ0ba51b@z9NI1lD3UhdR90EiA2A2FxdU5MrTUPdUB1EQSVBEsZAif8A "R – Try It Online")
* I noticed that taking a vector of digits is acceptable, and this allowed me to save 21 bytes :)
* -2 bytes thanks to @Giuseppe suggestion to accept only character vector
* -2 bytes assigning in arguments definition
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 16 bytes
```
{⍵[∘.⌈⍨(/⍨⍳⍴⍵)]}
```
I'm separating this solution from the post with my J answer, as suggested by Jo King
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbhOpHvVujH3XM0HvU0/God4WGPpB41Lv5Ue8WoIRmbC1QlYK6mak6FxeQNjIwhjAMjYxN1LkA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~14~~ ~~11~~ 10 bytes
Saved 1 byte thanks to *Magic Octopus Urn* / *Adnan*
```
ƶJDv¬N×?=¦
```
[Try it online!](https://tio.run/##MzBNTDJM/f//2DYvl7JDa/wOT7e3PbTs/38DQzNDcwA "05AB1E – Try It Online")
**Explanation**
```
ƶ # repeat each element its index (1-based) times
J # join to string
Dv # for N in [0 ... len(string)-1] do
¬N× # push the head repeated N times
? # print without newline
= # print the rest of the string without popping
¦ # remove the head
```
[Answer]
# [Python 2](https://docs.python.org/2/), 74 bytes
```
i=1;a=[]
for c in input():exec"a=zip(*a+[c*-~len(a)]);"*i;i+=2+i%2
print a
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9PW0DrRNjqWKy2/SCFZITMPiApKSzQ0rVIrUpOVEm2rMgs0tBK1o5O1dOtyUvM0EjVjNa2VtDKtM7VtjbQzVY24Cooy80oUEv//Vzc3MzVRBwA "Python 2 – Try It Online")
[Answer]
# Excel VBA, 95 bytes
An anonymous VBE immediate window funtion that takes input from `[A1]` and outputs to the console
```
n=[len(A1)]:For y=1To n:For l=1To y:?:For x=1To n:?String(x,Mid([A1],IIf(x>y,x,y)));:Next x,l,y
```
### Ungolfed and commented
```
n=[len(A1)] '' Get Length
For y=1To n '' Iterate down input
For l=1To y '' Iterate down repeat lines
? '' Print Newline
For x=1To n '' Iterate accross input
?String(x,Mid([A1],IIf(x>y,x,y))); '' Print x of the `max(x,y)`th digit in input
Next x,r,y '' Loop, Loop, Loop
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~15~~ 12 bytes
```
tftY"t!2$X>)
```
[Try it online!](https://tio.run/##y00syfn/vyStJFKpRNFIJcJO8/9/dTNTdQA "MATL – Try It Online")
I suspect this can be shortened, but it's not so bad...
```
% implicit input, '230'
t % duplicate input. Stack: ['230','230']
f % indices of nonzero values. Stack: ['230',[1,2,3]]
t % duplicate. Stack: ['230',[1,2,3],[1,2,3]]
Y" % run-length decoding. Stack: ['230',[1,2,2,3,3,3]]
t % duplicate. Stack: ['230',[1,2,2,3,3,3],[1,2,2,3,3,3]]
! % transpose. Stack: ['230',[1,2,2,3,3,3],[1;2;2;3;3;3]]
2$X> % elementwise maximum of 2 inputs, with broadcast.
% Stack:
% ['230',
% [1, 2, 2, 3, 3, 3;
% 2, 2, 2, 3, 3, 3;
% 2, 2, 2, 3, 3, 3;
% 3, 3, 3, 3, 3, 3;
% 3, 3, 3, 3, 3, 3;
% 3, 3, 3, 3, 3, 3]]
) % index into G
% implicit end, display stack contents
```
[Answer]
# [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 35 bytes
```
L,bLRdBcB]£X¦Ω+d‽b>1€Ω_A€Ω:AbLR¦+$T
```
[Try it online!](https://tio.run/##S0xJKSj4/99HJ8knKMUp2Sn20OKIQ8vOrdROedSwN8nO8FHTmnMr4x3BlJUjUNGhZdoqIf9ddLLyM/N0HOp0uDi9uLhcdAqKUktKKguKMvNKdBysgKJOLtU5iblJKYkKhrVcnClOGVycBs4gEmhUNUgzUDQpNA8kYmjgrGRra6sEpLW1ubhUkMyyMzNF5RsZGKMKmBoZGKGKGBoZm5j@BwA "Add++ – Try It Online")
## How it works
We take input as a list of digits, while prevents us from a) having to cast to digits with `BD`, and also from having to save the digits, which would take two bytes.
First, we generate a range from **[1 ... len(input)]** with `bLR`, then we repeat each element \$n\$ in the range \$n\$ times. As automatic vectorisation doesn't exist in Add++, we zip it with itself, `dBcB]`, to create a list of pairs \$[[1, 1], [2, 2] ... [n, n]]\$. We then apply *[starmap](https://docs.python.org/3/library/itertools.html#itertools.starmap)*, coupled with repetition over the pairs: `£X` before concatenating them into one flat array (`¦Ω+`).
Next, we duplicate this array and table it by maximum, `d‽b>`. I.e. each element in the array is paired with each other element from the second array and the *dyadic maximum* command is run over the pair. For an example input of **[6 5]**, this creates the array **[1 2 2 2 2 2 2 2 2]**, which is a flattened version of the mosaic, as the indexes for the array. Unfortunately, Add++ uses 0-indexed arrays, so we need to decrement each element: `1€Ω_`.
Then, we index into the input list, by pushing the input again (`A`), which again saves bytes by taking input as a list. Index into the list with `€Ω:` before chopping the array into the appropriately lengthed pieces. If the number of digits in the input is denoted by \$x\$, then the piece size is
$$\frac{x(x - 1)}{2}$$
or the \$x^{th}\$ [triangular number](https://en.wikipedia.org/wiki/Triangular_number). We generate that by pushing the input's length, calculating the range from **1** to that value, then taking the sum with `AbLR¦+`. Now, the stack, for an input of **[6 5]**, looks like **[[6 5 5 5 5 5 5 5 5] 3]**. `T` chops the array into pieces of size \$n\$, but the arguments are currently in the wrong order, so we swap them with `$` before chopping and returning with `T`.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 17 bytes
```
F⮌…LθUO⊕⊘×ι⁺³ι§θι
```
[Try it online!](https://tio.run/##HYrBCsIwEAV/ZY8rRJCKJ0/eLAhK8Qdi@kwD2w1NYvDvY3AuA8O4xSYXrbT2jol4QkXK4MmqB9@gviy87Tp0f0lUz6O6hBVaMPPVSu16hhWZg6GHfDIfDYX@G7qUUWd8efuHc2un4TC0fZUf "Charcoal – Try It Online") Explanation:
```
F⮌…Lθ
```
Loop over the indices of the characters in reverse order.
```
⊕⊘×ι⁺³ι
```
Calculate the size of the square.
```
UO...§θι
```
Draw the square using the current character.
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 12 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
ø╶{;l└²+:*;n
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JUY4JXUyNTc2JXVGRjVCJXVGRjFCJXVGRjRDJXUyNTE0JUIyJXVGRjBCJXVGRjFBJXVGRjBBJXVGRjFCJXVGRjRF,i=JTIyNTIwMiUyMg__,v=3)
[Answer]
# [Python 2](https://docs.python.org/2/), ~~76~~ 73 bytes
-3 bytes thanks to [Lynn](https://codegolf.stackexchange.com/users/3852/lynn).
```
l=0;m=[]
for k in input():l+=1;m=[r+l*k for r in m]+l*[l*-~l/2*k]
print m
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P8fWwDrXNjqWKy2/SCFbITMPiApKSzQ0rXK0bQ1BUkXaOVrZCiDpIpB0biyQH52jpVuXo2@klR3LVVCUmVeikPv/v7qRgbE6AA "Python 2 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 14 [bytes](https://github.com/somebody1234/Charcoal/wiki/Code-page)
```
E⭆θ×⊕κι×⊕κι‖O↗
```
**[Try it online!](https://tio.run/##S85ILErOT8z5///9nqWP1rad23F4@qOuqed2ndsJZzxqmPZ@z/pHbdP//zc1MjD6r5sPAA "Charcoal – Try It Online")**
### How?
```
E⭆θ×⊕κι×⊕κι‖O↗ - implicitly print the result of...
E - map:
⭆ - over: string map:
θ - over: first input
× - using: repeat
ι - what: ι (loop value)
⊕κ - by: incremented κ (loop counter)
× - using: repeat
ι - what: ι (loop value)
⊕κ - by: incremented κ (loop counter)
‖O - Reflect with overlap:
↗ - direction: up-right
```
...can this method be golfed?
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 12 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ü°√¿«│⌠º₧@\τ
```
[Run and debug it](https://staxlang.xyz/#p=81f8fba8aeb3f4a79e405ce7&i=%2265%22%0A%22203%22%0A%225202%22%0A%2212345%22&a=1&m=2)
Using [this algorithm](https://codegolf.stackexchange.com/a/167358/78123).
Explanation:
```
c%R:BXm]i*xit+ Full program, implicit input
c% Length of input
R 1-based range
:B Repeat each element according to the range ("123" -> "122333")
X Save to X register
m Map:
] Character -> string
i* Repeat by iteration index
xit Trim first <iteration index> elements from X
+ Concatenate
Implicit output with newline
```
### [Stax](https://github.com/tomtheisen/stax), ~~20~~ ~~19~~ ~~18~~ 16 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ù↔‼i,ÑΓæ☺=╘‼æ↕4╝
```
[Run and debug it](https://staxlang.xyz/#p=81c3141c192d5b6a76a66a474d2b4a015e29&i=%2265%22%0A%22203%22%0A%225202%22%0A%2212345%22&a=1&m=2)
Explanation:
```
c%R:BX%mYx%{y|Mvx@m Full program, implicit input
c% Length of input
R 1-based range
:B Repeat each element according to the range ("123" -> "122333")
X Save to X register
% Length
m Map over 1-based range:
Y Save index to Y register
x% Push length of X register
{ m Map over 1-based range:
y|M Maximum of both indices
v 1-based -> 0-based (decrement)
x@ Index into X register
Implicit output with newline
```
[Answer]
# [Attache](https://github.com/ConorOBrien-Foxx/Attache), 34 bytes
```
{_[Table[Max,Flat!{_&_}=>1:#_]-1]}
```
[Try it online!](https://tio.run/##SywpSUzOSP2fpmBl@786PjokMSknNdo3sULHLSexRLE6Xi2@1tbO0Eo5PlbXMLb2v19qakpxtEpBQXJ6LBeXS2ZxQU5iZUhqcYlzYnFqcXSag0tmemZJsY5CtJmpjoKRgbGOgqmRgZGOgqGRsYlpbOx/AA "Attache – Try It Online")
## Explanation
Works similarly to [Galen Ivanov's J answer](https://codegolf.stackexchange.com/a/167338/31957).
```
{_[Table[Max,Flat!{_&_}=>1:#_]-1]}
{ } anonymous function: _ is input, array of digits
example: _ := [2, 0, 3]
1:#_ the range 1 to Size[_]
> e.g.: [1, 2, 3]
{ }=> over each number N:
_&_ map to N repeated N times
> e.g.: [[1], [2, 2], [3, 3, 3]]
Flat! flatten it
> e.g.: [1, 2, 2, 3, 3, 3]
Table[Max, ] create a "max" table with it
> e.g.:
1 2 2 3 3 3
2 2 2 3 3 3
2 2 2 3 3 3
3 3 3 3 3 3
3 3 3 3 3 3
3 3 3 3 3 3
-1 subtract 1 from each
> e.g.:
0 1 1 2 2 2
1 1 1 2 2 2
1 1 1 2 2 2
2 2 2 2 2 2
2 2 2 2 2 2
2 2 2 2 2 2
_[ ] index the original array with this matrix
> e.g.:
2 0 0 3 3 3
0 0 0 3 3 3
0 0 0 3 3 3
3 3 3 3 3 3
3 3 3 3 3 3
3 3 3 3 3 3
```
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), 16 bytes
```
{x@i|\:i:&1+!#x}
```
[Try it online!](https://tio.run/##y9bNS8/7/z/NqrrCIbMmxirTSs1QW1G5ovZ/mpKZqRJXmpKRgTGIMjUyMALRhkbGJkr/AQ "K (ngn/k) – Try It Online")
[Answer]
# [QBasic 1.1](http://www.qbasic.net), 127 bytes
```
INPUT S$
FOR X=1TO LEN(S$)
K=K+X
R$=R$+STRING$(X,MID$(S$,X,1))
NEXT
FOR C=1TO K
?STRING$(C-1,MID$(R$,C,1))RIGHT$(R$,K-C+1)
NEXT
```
-4 thanks to [DLosc](https://codegolf.stackexchange.com/questions/167337/lets-design-a-digit-mosaic/167356?noredirect=1#comment404548_167356).
Uses a modified version of [xnor's Python 2 algorithm](https://codegolf.stackexchange.com/a/167358/41024).
Input is an unquoted string. Output is `\n`-separated without extra spaces or `\n`s.
[Answer]
# [QBasic](https://archive.org/details/msdos_qbasic_megapack), 111 bytes
An anonymous function that prompts for input and outputs to the console.
```
INPUT s$
n=LEN(s$)
FOR y=1TO n
FOR l=1TO y
?
FOR x=1TO n
z=x
IF y>x THEN z=y
?STRING$(x,MID$(s$,z));
NEXT x,l,y
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~130~~ 126 bytes
-4 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)
Who needs fancy maths when you can bruteforce?
```
n,l;R(n,c){for(;n--;)putchar(c);}f(s){for(char*p=s,*q;*p++;)for(n=l=p-s;l--;R(1,10))for(R(n*-~n/2,p[-1]),q=p;*q;)R(++q-s,*q);}
```
[Try it online!](https://tio.run/##NU5Nj4IwED3bX0FITGZKm4Wqe9gJf4Lr6sHUgCQ4FuruxeBfZ6dsPM2b95Xnbef9srAZqAE2Hp/tfQJiawnDz8NfzxN4pLmF@C8lRoc6Gj2SDkVBmFiuhzrYSIPkGqhMVeLKS6e2L/5wJnzb6oRmrANJEhsoitGmFilffu/9JevW7kxHVE@1CVPPjxbybfw68pFzk0UktUk75Mi0CLnQ8sxKiTW7nXuGNdpB/nlISkKu3L3hwZXujSu326@eefkD "C (gcc) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 13 bytes
```
Þżṅ:ẏ(:hnẋ₴…Ḣ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLDnsW84bmFOuG6jyg6aG7huovigrTigKbhuKIiLCIiLCIwMTYxNyJd)
## How?
```
Þżṅ:ẏ(:hnẋ₴…Ḣ
Þż # Repeat each character in the (implicit) input its 1-based index amount of times
ṅ # Join by nothing
: # Duplicate
ẏ( # Loop over [0...length), where the current iteration = n
:h # Duplicate and get the first character
nẋ # Repeat it n amount of times
₴ # Print without a trailing newline
… # Print without popping with a trailing newline
Ḣ # Remove the first item
```
[Answer]
# [Php 7.1](http://www.php.net), 163 bytes
Via CLI providing the number as an argument:
```
<?foreach(str_split($argv[1])as$k=>$d)$a[]=array_fill(0,$s+=$k+1,array_fill(0,$s,$d));foreach(array_replace_recursive(...array_reverse($a))as$v)echo join($v)."\n";
```
Not so golfed:
```
$n = 123;
foreach(str_split($n) as $k => $d) {
$s += $k + 1;
$a[] = array_fill(0, $s, array_fill(0, $s, $d));
}
foreach(array_replace_recursive(...array_reverse($a)) as $v)
echo implode('', $v) . "\n";
```
Output:
```
122333
222333
222333
333333
333333
333333
```
Method:
Basically build multi-dimensional array squares consisting of the digit, and then superimpose all of them (array\_replace\_recursive).
(Yes, I know this is embarrassingly long.)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 80 bytes
```
->n{s=(1..n.size).map{|i|n[i-1]*i}*"";(0...s.size).map{|i|s[i]*i+s[i..-1]}*"\n"}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vuthWw1BPL0@vOLMqVVMvN7GguiazJi86U9cwViuzVktJyVrDQE9PrxhVQXF0JlBaG0jp6QFVAtXF5CnV/o9WMjNV0lFQMjIwBlGmRgZGINrQyNjEVCkWojmvRqGgtKRYIS06L7b2PwA "Ruby – Try It Online")
Similar to [ovs answer](https://codegolf.stackexchange.com/a/167344/81225)
[Answer]
# Japt, 12 bytes
Takes input as a string, outputs an array of strings.
```
Ë+pE
¬£h°YçX
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=yytwRQqso2iwWedY&input=IjEyMzQiCi1S)
---
## Explanation
```
:Implicit input of string U
Ë :Map each character D at 0-based index E
pE : Repeat D E times
+ : Append to D
\n :Reassign to U
¬ :Split to character array
£ :Map each element X at 0-based index Y
°Y : Increment Y
çX : Repeat X Y times
h : Replace the first Y characters in U with that
```
[Answer]
# [uBASIC](https://github.com/EtchedPixels/ubasic), 120 bytes
An anonymous function that takes input foprm STDIN and outputs to STDOUT
```
0Input"",S$:N=Len(S$):ForY=1ToN:ForL=1ToY:ForX=1ToN:ForC=1ToX:Z=X:IfY>XThenZ=Y
1?Mid$(s$,z,1);:NextC:NextX:?:NextL:NextY
```
[Try it online!](https://tio.run/##K01KLM5M/v/fwDOvoLRESUknWMXKz9YnNU8jWEXTyi2/KNLWMCTfD8TyAbEiQawIuJgziBVhFWUbYeWZFmkXEZKRmhdlG8llaO@bmaKiUayiU6VjqGlt5ZdaUeIMJiOs7MG0D5iM/P/f0MjYBAA "uBASIC – Try It Online")
[Answer]
# [Visual Basic .NET (VBC)](http://www.mono-project.com/docs/about-mono/releases/5.12.0/#vbnet-compiler), 198 bytes
A `Sub`routine that takes input from STDIN and outputs to STDOUT.
Couldn't seem to get StrDup to work :/
```
Module M
Sub Main
Dim c,s,n,l,x,y
s=Console.readLine()
n=Len(s)
For y=1To n
For l=1To y
For x=1To n
For c=1To x
Console.Write(Mid(s,IIf(x>y,x,y),1)&IIf(c=n,vbLf,""))
Next c,x,l,y
End Sub
End Module
```
[Try it online!](https://tio.run/##TY49C8IwFEX3/IrgIAm8ClXXuPgBhdZFwblJUwjEF2jakvz62EYEp3feHe49s/FTawvZeqMK1GMxS5VS47rJatqQxyRp0xokF/OmCjwgWAgQiRdnh95ZvRt029UGNeMERa2ReU5ubqBRlE9HMbPNHDOHv1xlDuTX9RrMqFljOuahqnoWTnFd41Dy7forgTDLuofNhnNy12FcpMKiFCm5YkcX3Xy//imV@8PxAw "Visual Basic .NET (VBC) – Try It Online")
[Answer]
# Lua, 149 140 bytes
Function which accepts a list of digit strings and prints the result to stdout. This is my first attempt at code golf (and the language choice isn't helping either) so bear with me :)
[Try it online!](https://tio.run/##VYzBCgIhGIRfRf4uiiJrp9r4r@5D1B60dWEhNHQl2OjZTSOCDjMMzDdzy6YMWObsr@sSPDVMi4SdAJhDJBaV2BkyBZIwSWnOduyju1PLnJ9O/8QS5CMuq6O0knDxwL5ofdxQcyvqnKsxRICE26fUTMrUp2yp5qp9kqoykCccQBBQzfbNul86wqu8AQ "Lua – Try It Online")
```
function(a)F,s=0,""for b=1,#a do s=s..a[b]:rep(b)end;for b=1,#a do io.write((s.."\n"):rep(b))F,z=F+b,a[b+1]or""s=z:rep(F)..s:sub(F+1)end end
```
Ungolfed:
```
G = function(p)
F,s = 0,""
for i=1,#p do
s=s..p[i]:rep(i)
end
for i=1, #p do
io.write((s.."\n"):rep(i))
F,z = F+i, p[i+1]or""
s = z:rep(F)..s:sub(F+1)
end
end
-- allows to pass the argument list from stdin
-- example: {"1", "2", "3", "4", "5"}
G(load("return " .. io.read())())
```
[Answer]
## [Perl 5](https://www.perl.org/) + `-nalF -M5.010`, 67 bytes
```
s/./$&x++$-/ge;eval'eval"say;"x++$i;$x+=$i;s/.{$x}/$F[$i]x$x/e;'x@F
```
[Try it online!](https://tio.run/##K0gtyjH9/79YX09fRa1CW1tFVz891Tq1LDFHHUQoFSdWWiuBxDOtVSq0bYEUUGm1SkWtvopbtEpmbIVKhX6qtXqFg9v//4YGYPgvv6AkMz@v@L9uXmKO239dX1M9oDAA "Perl 5 – Try It Online")
] |
[Question]
[
Although [related](https://codegolf.stackexchange.com/questions/2958/check-if-number-is-a-sum-of-consecutive-numbers-or-not) [challenges](https://codegolf.stackexchange.com/questions/66193/sums-of-consecutive-integers) have been asked, this one is different to warrant its own question.
---
# Challenge
Given a positive integer, return the longest sequence of consecutive positive odd integers whose sum is the given integer. If no such sequence exists, you may report an error in whatever way makes sense for your language, including returning a falsy value or throwing an exception.
# Test Cases
```
1 -> [1]
2 -> []
3 -> [3]
4 -> [1, 3]
5 -> [5]
6 -> []
9 -> [1, 3, 5] (note that [9] is not a valid answer)
15 -> [3, 5, 7]
104 -> [23, 25, 27, 29] (note that [51, 53] is not a valid answer)
```
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in each language wins.
[Answer]
# Haskell, ~~67~~ ~~65~~ ~~63~~ ~~62~~ 58 bytes
Saved 4 bytes thanks to Julian Wolf
```
f x=[[2*n+1,2*n+3..2*m]|n<-[0..x],m<-[n..x],m^2-n^2==x]!!0
```
[Try it online!](https://tio.run/##bU/RCsIwDHx2X5GBD3Nmpe22h4L1R2oHAx0O2ypOoQ/@e@0Q1EEDOe6OXELO/XQ5GRPCAF4qxUu3ZThjTQgvrX65XaUoIV6jjcx9WMcr13Epvc5zGmw/OpBwvMLtProHrGEAlsG3fm6drf6lWMo2mREiaTNKl2lGm/QgT/m9MVAcPFR7mJ62iN9vQMoZFcMaBbYoBMYjsRuMO3R4Aw)
I check if the number can be expressed as he difference of two squares: `m^2-n^2`. I can then construct the list of consecutive odd numbers: `[2n+1,2n+3...2m-1]`. Note that because the minimum `n` is chosen, the longest list will be output
[Answer]
# [Python 2](https://docs.python.org/2/), ~~66~~ 62 bytes
```
f=lambda n,k=0,*r:n-sum(r)and f(n,k+1,*range(k%n|1,k/n,2))or r
```
Exits with a *RuntimeError* (maximum recursion depth exceeded) if there's no solution.
[Try it online!](https://tio.run/##RY1BDoIwFETXcIq/IbRSlKLGaKI7L@DWuEAo2kB/yW9JJPHuWOPCSWYWLzOZYfJPi@WszWDJg5tcHLx0ypOqR3LaYq@N9kwWQXxuj31l7k0FKLpjIRZ0wNyNhhGvsIGWBZzJgCt8KNYl@JaiW6EoObcENLchETTCryAF7DhkcN0LkNvgYnM7xJGnKWQ0kEYPabIeIT@lkITP7wOPI/Wq1eDhMqLXRp2JLP0HjM8f "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 byte thanks to Dennis (use the implicit range building of `Ẇ` - replace `Rm2Ẇ` with `ẆḤ’`)
```
ẆḤ’S_¥Ðḟ⁸Ṫ
```
A monadic link returning a list of the summands if possible, or `0` if not.
**[Try it online!](https://tio.run/##ASUA2v9qZWxsef//4bqG4bik4oCZU1/CpcOQ4bif4oG44bmq////MTA0 "Jelly – Try It Online")**
### How?
```
ẆḤ’S_¥Ðḟ⁸Ṫ - Link: number, n
Ẇ - all sublists (implicit range of input) note: ordered by increasing length
- i.e. [[1], [2], [3], ..., [1,2], [2,3], ..., [1,2,3], ...]]
Ḥ - double [[2], [4], [6], ..., [2,4], [4,6], ..., [2,4,6], ...]]
’ - decrement [[1], [3], [5], ..., [1,3], [3,5], ..., [1,2,5], ...]]
⁸ - link's left argument, n
Ðḟ - filter out items for which the following yields a truthy value:
¥ - last two links as a dyad:
S - sum
_ - subtract the right from the left = sum - n
Ṫ - tail (last and hence longest such run)
```
[Answer]
## JavaScript (ES7), ~~87~~ ~~86~~ ~~85~~ 81 bytes
Returns a comma-delimited list of integers, or `0` if no solution exists.
```
n=>(g=(s,k,x=n+s)=>(x**.5|0)**2-x?k>n?0:g(s+k,k+2):(n-=k)?k+','+g(-n,k+2):k)(0,1)
```
### How?
We first look for the smallest perfect square ***s*** such that ***x = n + s*** is another perfect square.
If ***s*** exists, ***n*** is the difference ***x - s*** of 2 perfect squares, which can be written as the difference of 2 sequences of consecutive odd numbers. We then build the resulting list.
Example:
For ***n = 104***:
We find ***s = 11² = 121*** which satisfies ***x = n + s = 225 = 15²***
Then:
***15² = 1 + 3 + 5 + 7 + 9 + 11 + 13 + 15 + 17 + 19 + 21 + 23 + 25 + 27 + 29***
***11² = 1 + 3 + 5 + 7 + 9 + 11 + 13 + 15 + 17 + 19 + 21***
***104 = 15² - 11² = 23 + 25 + 27 + 29***
```
let f =
n=>(g=(s,k,x=n+s)=>(x**.5|0)**2-x?k>n?0:g(s+k,k+2):(n-=k)?k+','+g(-n,k+2):k)(0,1)
console.log(f(1)) // -> 1
console.log(f(2)) // -> 0
console.log(f(3)) // -> 3
console.log(f(4)) // -> 1,3
console.log(f(5)) // -> 5
console.log(f(6)) // -> 0
console.log(f(9)) // -> 1,3,5
console.log(f(15)) // -> 3,5,7
console.log(f(104)) // -> 23,25,27,29
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~9~~ 8 bytes
-1 byte thanks to Emigna
```
ÅÉŒʒOQ}н
```
Explanation:
```
ÅÉ Generate a list of odd numbers up to, and including, the input
Œ Substrings
ʒ Only keep values
O where the sum
Q equals the input
} End
For 9, the result would look like this:
[[1, 3, 5], [9]]
н Get the first value
```
On invalid input, outputs nothing.
[Try it online!](https://tio.run/##MzBNTDJM/f//cOvhzqOTXPwP7Qw83H9h7///lgA "05AB1E – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~61~~ 60 bytes
*Thanks to @maple\_shaft for shaving off 1 byte*
```
f n=[k|r<-[1,3..],s<-[r,r+2..n],k<-[[r,r+2..s]],sum k==n]!!0
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00hzzY6u6bIRjfaUMdYTy9WpxjILNIp0jbS08uL1ckG8mDc4ligbGmuQratbV6soqLB/9zEzDwFW4WUfIWCosy8EgUVhTQFQy4FOECIGnNxInMtUbmmWPUYmqKqMjQw@Q8A "Haskell – Try It Online")
Uses the fact that the longest run will always be the run that starts with the lowest number.
I wanted to do something with arithmetic in stead of brute-forcing `k`, but `fromInteger` seems to kill it.
[Answer]
# [Python](https://docs.python.org/3/), 67 bytes
```
f=lambda n,R=[1]:n-sum(R)and f(n,[R+[R[-1]+2],R[1:]][sum(R)>n])or R
```
[Try it online!](https://tio.run/##dY2xCoMwFABn/Yq3iAlGaGpLqaBbh65ZHxnSqq2gT4kR9OvTlM4d7qaDm3f3nqjwvqsGMz4aAyRUhVKXlC/ryBQ31EDHSKDKUGEudXbUQqEstcZfUZPmkwXlu2CCnmDoF8esoVfLpIAL55ABXgXIc@Bw0mUcObsHR7PtybE0KVbI6xSSsP/eOI@jdnu2s4M7Ne12s3ay/3rU3H8A "Python 3 – Try It Online")
I copied [my answer from the previous consecutive sum challenge](https://codegolf.stackexchange.com/a/66229/20260) and changed the `+1` to `+2`. Who knew that golfed code could be so modular?
An oddly straightforward strategy: search for the interval `R` with the desired sum.
* If the sum is too small, shift the right endpoint of the interval up
2 by appending the next number 2 above it.
* If the sum is too large, shift up the left endpoint by removing the smallest element
* If the sum is correct, output `R`.
Since the bottom end of the interval only increases, longer intervals are found before shorter ones. If no possible interval can be found, terminates with IndexError.
[Answer]
# JavaScript (ES6), ~~65~~ 64 bytes
```
f=(a,i=1)=>a>i?(c=f(a-i,i+=2))[0]==i?[i-2,...c]:f(a,i):a<i?0:[i]
```
Returns an array if there's a solution, or 0 for no solution.
This is a highly inefficient yet *golfy* solution to the problem.
It searches for the first solution using `a-i` and `i=1`, even if it doesn't work up the recursive stack. If that solution doesn't begin with `i+2`, then we recursively search for the first solution using `a` and `i+2`.
**Ungolfed**
```
f=(a,i=1)=>
a > i ?
(c = f(a - i, i += 2))[0] == i ?
[i-2, ...c] :
f(a, i) :
a < i ?
0 :
[i]
```
**Test cases:**
```
f=(a,i=1)=>a>i?(c=f(a-i,i+=2))[0]==i?[i-2,...c]:f(a,i):a<i?0:[i]
console.log(JSON.stringify(f(1))); //[1]
console.log(JSON.stringify(f(3))); //[3]
console.log(JSON.stringify(f(4))); //[1, 3]
console.log(JSON.stringify(f(5))); //[5]
console.log(JSON.stringify(f(6))); //[0]
console.log(JSON.stringify(f(9))); //[1, 3, 5]
console.log(JSON.stringify(f(15))); //[3, 5, 7]
console.log(JSON.stringify(f(104))); //[23, 25, 27, 29]
```
For an idea of how inefficient this is, the solution to `f(104)` requires 69,535 recursive calls. The stack is never more than 51 levels deep, so no problem with stack overflow.
The solution to `f(200)` requires 8.6 *million* recursive calls, with a stack 99 levels deep. (Its solution is `[11,13,15,17,19,21,23,25,27,29]`.)
Here's a visual representation of the program running:
```
r=0;
output=o=>setTimeout(_=>O.textContent += o + '\n', r++ * 20);
f=(a,i=1,s='',o = s + 'a=' + a + '; i=' + i + ';')=>
(
output(o),
a > i ?
(c = f(a - i, i += 2, s + ' '))[0] == i ? (
output(o + ' a > i; [i-2, ...c] = [' + [i-2, ...c] + '];'),
[i-2, ...c]
) : (
output(o + ' a > i; c=[' + c + ']; ' + 'c[0]+2 != i ... dead end\n' + s + 'trying a, i+2:'),
f(a, i, s)
) :
a < i ? (
output(o + ' a < i ... dead end'),
0
) : (
output(o + ' a == i;'),
[i]
)
)
f(21); //[5, 7, 9]
```
```
<pre id=O></pre>
```
[Answer]
# Python 2.7, 109 108 97 bytes
11 bytes down, Thanks to Erik the Outgolfer.
This is my first code golf!
```
def f(N):
for n in range(N):
x=(n*n+N)**.5-n
if x%1==0:return[2*(k+n)+1for k in range(int(x))]
```
## How it works
I used the well known identity that `1 + 3 + 5 + ... + (2n - 1) = n²`
Take the case of `15`
```
15 = 3 + 5 + 7 = (1 + 2) + (3 + 2) + (5 + 2) = (1 + 3 + 5) + 3×2 = 3² + 3×2
```
In general, if there are *x* terms starting from `2n + 1`, like
```
(2n + 1) + (2n + 3) + (2n + 5) ... (2n + (2x-1))
```
It is equal to `2nx + x²`
If `N` is the input integer, the problem reduces to finding maximum `x` such that
```
x² + 2nx - N = 0
```
It is a quadratic equation with solution
```
x = sqrt(n² + N) - n
```
The longest sequence is one with largest `x`. The program iterates `n` from `0` to `N` and when it find that `x` is an integer, it creates a list of `(2n + 1) + (2n + 3) + (2n + 5) ... (2n + (2x-1))` and returns it.
[Answer]
# Python 3, 190 81 Bytes
```
def c(q,l,i):
if sum(l)0:
l.append(i)
return c(q,l,i+2)
elif sum(l)>q:
l.pop(0)
return c(q,l,i)
else:
print(l)
c(q,[1],1)
```
```
c=lambda q,l=[1]:c(q,l+[l[-1]+2])if(sum(l)<q)*l else c(q,l[1:])if sum(l)>q else l
```
Thanks to @ovs and @musicman523
[Answer]
# [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 47 bytes
```
{_Cg=q┘q=q+2~g>:|_Xp\?g,[q,a,2|?b,┘g=g+b~g=a|_X
```
This tries to count all the odd numbers from one until its sum is `n`. If it passes `n`, reset the loop, increase 1 to 3 and try again. Quit, printing 0, if at the start of the loop our number `> n`.
## Explanation
```
{ Do infinitely
_C Clear the screen (we basically print every run of odd numbers, but clear out everything that doesn't sum up to n)
g=q Set g to the first num of this cycle (q starts as 1 in QBIC)
┘ (Syntatcic linebreak)
q=q+2 Raise q to the next odd number, this sets up both the next outer loop as well as a coming FOR loop
~g>:| If we start out with a number > n (read as 'a' from the cmd line)
_Xp THEN quit, printing 0 (the value of the number var 'p')
\ ELSE
[q,a,2| FOR b = q, b <= n, b+=2
?b,┘ PRINT b followed by a tab
g=g+b Add 'b' to running total 'g'
~g=a| and if that lands us on 'n'
_X QUIT (printing nothing: everything is already printed)
```
[Answer]
# [R](https://www.r-project.org/), 90 bytes
```
f=function(x,y=1)'if'(length(w<-which(cumsum(r<-y:x*2-1)==x)),r[1:w],'if'(y>x,0,f(x,y+1)))
```
[Try it online!](https://tio.run/##HcxBCsIwEIXhvRfpjCbQqVWwNF6kdBUcE7ARYkOS00emmw/@xXuxNTacgt39N0BR1RB2njv4vMJ7d5BnnZ23DmzafmmDOOs6lfOgCY0piCouNOVVHZv6LKpXLDcXQsTGQHhiGISrMAo34S48BDqa@hHbHw "R – Try It Online")
Uses a recursive function that test sequence cumulative sum of y:x converted to an odd number sequence. y is incremented on each recursion until it exceeds x. The first sequence which sums to the target will be returned.
[Answer]
# [Python 2](https://docs.python.org/2/), 89 bytes
```
lambda n,r=range:[v for v in[r(1,n+1,2)[i:j]for i in r(n)for j in r(n+1)]if sum(v)==n][0]
```
An unnamed function taking a positive integer, `n`, and returning the result if it exists and raising an `IndexError` otherwise.
**[Try it online!](https://tio.run/##RYxBCsIwEEXX6SlmmdAsmiIuCrmCF4hZVE10ip2WaQz29LEFxc2H9/i8eU2PidoS7bk8@/Fy64E0W@7pHjqXIU4MGZAcS6OpNrpVDrvB7x43DyxJ7TB8oTbKY4TlNcqsrCXvGl/@7727lcxRQQ3ONAffVSLxuq3IYCFKVJUI72uY08@dJgqVmBkpAWrI5QM "Python 2 – Try It Online")**
Creates a list of all the relevant odd numbers with `r(1,n+1,2)` which is `range(start=1, stop=n+1, step=2)`; creates all the relevant sub-slices (plus some empty ones) by slicing that from `i` inclusive to `j` exclusive with `[i:j]` across `i` in **[0,n)** using `r(n)` and `j` in **[0,n]** using `r(n+1)` (the empty ones when `i>=j` or `i` is out of bounds); filters for those with the correct sum with `if sum(v)==n`; returns the first (and hence longest) such slice using `[0]`.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~91~~ 90 bytes
*-1 byte thanks to @CMcAvoy*
```
lambda n,r=range:[r(i,j+1,2)for i in r(1,n+1,2)for j in r(i,n+1,2)if(i+j)*(2+j-i)==4*n][0]
```
[Try it online!](https://tio.run/##TczBDoIwDAbgu0@xGxvUhCGYSLKjZxOuyAEVtIuWpdlBnn7OqMRb/6/962Z/m6gIozmGe/84XXpBwIZ7ug51yxLBZhoKNU4sUCAJlhpoIfsh/BKOEjOrUllkdo3KmDKlrs27sNTjFWyghAq2sANdgc7LeiWEYyQvEOLoeX7Lz@JLFePwPA/O/y@SfdMcmiS8AA "Python 2 – Try It Online")
[Answer]
# Pyth, 11 bytes
```
efqsTQ.:%2S
```
[Try it here.](http://pyth.herokuapp.com/?code=efqsTQ.%3A%252S&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A9%0A15%0A104&debug=0)
[Answer]
# [PHP](https://php.net/), 73 bytes
no solution is a infinite loop
```
for($e=-1;$s-$i=$argn;)$s+=$s<$i?$n[]=$e+=2:-array_shift($n);print_r($n);
```
[Try it online!](https://tio.run/##HcmxCoAgFAXQvc@IOyghVDRlDz8kIhw0XezxbOnrDdoOHE7cNseJO3i5CvXTuPS2xVsUApnJohpk@tNq1IFQN2SHsh@EMNC8Gi/i37OmHB@Foi1LLs8pv1v7AA "PHP – Try It Online")
# [PHP](https://php.net/), 83 bytes
prints nothing for no solution
every input mod 4 == 2 has no solution
```
for($e=-1;($i=$argn)%4-2&&$s-$i;)$s+=$s<$i?$n[]=$e+=2:-array_shift($n);print_r($n);
```
[Try it online!](https://tio.run/##HcmxCsMgEAbgvY8R/ogSHBpKh@qRBwlFHJJ6iz3OLHl6A9k@@KRIj4sUeSDrr9LwHkLf/2qxkX8GC6Y73PjyszFoHhwc2kRoEbygrl/CNtH88Vk1n6kV3g@L6oIo1yPp7d4v "PHP – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~122~~ ~~121~~ ~~119~~ 115 bytes
*-1 byte thanks to musicman523. -4 bytes thanks to Step Hen. haha*
```
def f(n,R=range):r=R(1,n,2);print[i for w in R(1,len(r)+1)for i in[r[j:j+w]for j in R(len(r)-w+1)]if sum(i)==n][-1]
```
[Try it online!](https://tio.run/##XY@xTsMwEIb3PMXRpbHqSjikSAR5Qgxdu1oegNrlovYSnY3SPn1wbGDgls/@7vfpPN7i50DNPB@dB1@TPGh@o5MTHetDrSTJRjyPjBQNgh8YJkCCpXN2VLPYKLFYTNaw6bt@M9lF9CVWQtspxSx6CF@XGoXWZM1W2Tm6EANoMBWkUjKjKXgoaAt2BY8FTwXqx6r7trJV9bsH5LFdbkW@lcNS@RuA8k/4tEy@uOuHGyPs6eiur8wD/3@0elmnoYCXcQgB38/ubjW33w "Python 2 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 93 bytes
```
lambda n,r=range:[[*r(s,e+1,2)]for s in r(1,n+1,2)for e in r(s,n+1,2)if(s+e)*(2+e-s)==4*n][0]
```
[Try it online!](https://tio.run/##dYtBDoIwFET3nuKnqxY@CQU0kaRepHaB2moTLKTtQk5fKbh1VpM3b@YlvibXJiOuaRzet8cADr3wg3vqXsrC04C65NgwZSYPAawDTzm6jWWkdxR@yBoaSs0K2pS6CkyIrnBK1ipl12Z3fUOD0CJ0CEeEE8IZga@N1x3rD7Am@mUvObO3LlKLpLoQBEMtY9umP3c9x38ekYqw9AU "Python 3 – Try It Online")
Only thing special I did was noting that `(s+e)*(2+e-s)==4*n` is equivalent to `sum(range(s,e+1,2))==n`, and though they're the same size when `r=range`, the former can be placed closer to the `if` statement.
[Answer]
# [Python 3](https://docs.python.org/3/), 185 bytes
```
def f(s):
d={k:v for k,v in{a:(1-a+((a-1)**2+4*s)**(.5))/2 for a in range(1,s,2)}.items()if int(v)==v};m=max(d.keys(), key=(lambda k: d[k]));return list(range(int(m),int(m+2*d[m]),2))
```
[Try it online!](https://tio.run/##RY@xDsIwDER3vsKj3YZCCh1olS9BDEFJoAopVRIqEOLbi4GB6el857M8PvL5Omzm2VgHDhO1CwCjnr6dwF0jeDFBPzx1i3KpS0S9lFQUdbktEhOrhmhVf5OacxD1cLIoRRI1vao@25CQesdWxomUml5dUEHf0VTePtgTwFR40eFoNPgWzN4fiLpo8y0OcOlTxl/ppyKQ@KKsC7MPB@IrNI/xM9sJhzuixU/JhqVs/nq9Ffwegxfe "Python 3 – Try It Online")
---
As for how this works, I tried to go for a bit more elegant solution than a simple brute force search. I rearranged the formula for the [sum of an arithmetic sequence](https://en.wikipedia.org/wiki/Arithmetic_progression#Sum) and applied the quadratic formula to get the expression `(1-a+((a-1)**2+4*s)**(.5))/2`, which appears in the code. What the expression calculates is, given a desired sum `s` and a first term for of arithmetic sequence `a`, the length of the sequence. These lengths are stored in a dictionary as values to the first terms as keys.
Next, all non-integer values are removed from the dictionary, as those represent invalid sequences. From there, the largest value is identified with `max(d.keys(), key=(lambda k: d[k]))` and the sequence of odd numbers at that position and at that length is made with `list(range(int(m),int(m+2*d[m]),2))`.
---
I'm looking for help golfing this if you see anything. I was more interested in seeing how well I could do with a non-trivial algorithm; my answer is nearly twice as long as the best Python solution.
[Answer]
# Mathematica, 56 bytes
```
Last@Cases[Subsequences@Table[n,{n,1,#,2}],x_/;Tr@x==#]&
```
`Function` with first argument `#`. `Table[n,{n,1,#,2}]` computes the list of positive odd numbers less than or equal to `#`. `Subsequences` returns all subsequences of that list ordered by increasing length. We then take the `Cases` which match `x_/;Tr@x==#`, that is, sequences `x` such that their sum `Tr@x` is equal to the input `#`. We then take the `Last` such sequence.
[Answer]
## JavaScript (ES6), 72 bytes
```
n=>(g=s=>s?s>0?g(s-(u+=2)):g(s+l,l+=2):u-l?l+' '+g(s,l+=2):u)(n-1,l=u=1)
```
Returns a space-separated string of odd numbers or throws on invalid input. 84 byte version that returns an (empty when appropriate) array:
```
n=>n%4-2?(g=s=>s?s>0?g(s-(u+=2)):g(s+l,l+=2):u-l?[l,...g(s,l+=2)]:[u])(n-1,l=u=1):[]
```
Explanation: Loosely based on @Cabbie407's awk solution to [Sums of Consecutive Integers](https://codegolf.stackexchange.com/questions/66193/) except I was able to save some bytes by using recursion.
[Answer]
# PHP, 78 bytes
```
for($b=-1;$s-$argn;)for($n=[$s=$x=$b+=2];$s<$argn;)$s+=$n[]=$x+=2;print_r($n);
```
infinite loop if no solution. insert `?$b>$argn+2?$n=[]:1:0` after `$s-$argn` to print empty array instead.
Run with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/942003d4780086b421fda6de4b5a3e1db34f082d).
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 129 bytes
```
(i)=>{int s,j,b=1,e=3;for(;;){var o="";s=0;for(j=b;j<e;j+=2){s+=j;o+=j+" ";}if(s==i)return o;s=s<i?e+=2:b+=2;if(b==e)return"";}};
```
Outputs numbers in a string, space delimited (any other character would just require changing the `" "`). Input with no solution returns an empty string (though if running forever without error is a valid way to indicate no solution then 17 bytes could be saved by removing `if(b==e)return"";`).
Algorithm is:
1. Start with [1]
2. If the sum is equal to the target, return the list
3. If the sum is less than the target, add the next odd number
4. If the sum is greater than the target, remove the first item
5. If the list is empty, return it
6. Repeat from 2
[Answer]
## C++, 157 -> 147 Bytes
---
**-10 Bytes thanks to DJMcMayhem**
will return 0 if there's no answer, 1 otherwise
the last line it prints is the answer
```
int f(int n){for(int i=1;;i+=2){int v=0;for(int k=i;;k+=2){v+=k;std::cout<<k<<" ";if(v==n)return 1;if(v>n)break;}if(i>n)return 0;std::cout<<"\n";}}
```
ungolfed:
```
int f(int n)
{
for (int i = 1;; i += 2)
{
int v = 0;
for (int k = i;; k += 2)
{
v += k;
std::cout << k << " ";
if (v == n)
return 1;
if (v > n)
break;
}
if (i > n)
return 0;
std::cout << "\n";
}
}
```
this is my first code golf ^^
[Answer]
# Kotlin, 152 bytes
```
fun f(a:Double){var n=Math.sqrt(a).toInt()+1;var x=0;while(n-->0){if(((a/n)-n)%2==0.0){x=((a/n)-n).toInt()+1;while(n-->0){println(x.toString());x+=2}}}}
```
[Try it online](https://tio.run/##VY5BC4JAEIXP@Su8BDuItkonbYWgS4dOHaPDBqlLNta61ob427cxIWqO33vf8C6NqRU6V3ToX6VCJnXZpv5aa/la7Y1WWObQe7PiExz4MTLNpulO9ZkBeIPnjSKF6QShf0jto9hJU0XtXRsmgYwtGgZBnI2hFTx7VooeYBjmHHpVMMbkAiFEmCdC8IigFV/24/95NxpnamSWCtNSmpTZQCQDnXMu5ss3) (Wait 4-5 seconds, compiler is slow)
Ungolfed
```
fun f(a: Double){
var n=Math.sqrt(a).toInt()+1;
var x=0;
while(n-->0){
if(((a/n)-n)%2==0.0){
x=((a/n)-n).toInt()+1;
while(n-->0){
println(x.toString());
x+=2;
}
}
}
}
```
[Answer]
# Excel VBA, 139 Bytes
`Sub`routine that takes input `n` of expected type integer and reports the longest sequence of consecutive odd numbers to cell `[A1]`
```
Sub a(n)
For i=1To n Step 2
s=0
For j=i To n Step 2
s=s+j
If s=n Then:For k=i To j-1 Step 2:r=r &k &"+":Next:[A1]=r &j:End
Next j,i
End Sub
```
] |
[Question]
[
[3var](http://esolangs.org/wiki/3var) is a variant of [deadfish](http://esolangs.org/wiki/deadfish) which uses three variables called A, B and R.
A and B are accumulators, while R is used as a result variable.
In this [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, you need to make an interpreter for a stripped-down version of this language.
### Required Commands:
```
i Increments A
d Decrements A
s Squares A
p Prints A
P Prints the ASCII character of A
> Sets A to R
a Increments B
k Decrements B
m Squares B
o Prints B
O Prints the ASCII character of B
< Sets B to R
+ Adds A and B, stores in R
- Subtracts B from A, stores in R
* Multiplies A and B, stores in R
/ Divides A by B, stores in R
w Prints R
@ Resets A to 0
# Resets B to 0
e Resets R to 0
```
Everything else (including whitespaces) is ignored.
### Clarifications
* `o` and `p` should output without anything after it.
* Division is integer division.
* Numbers above 255 and numbers below 0 are supported.
* 'w' should output a space or a newline after R
* Division by 0 halts without errors. (No output to STDERR)
* A, B and R are initially 0
### Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest answer wins.
* In the event of a tie, the oldest answer wins.
* The file will be provided through command line arguments or STDIN.
* Any language is allowed.
* Eval is allowed.
### Test Cases
`Hello world!` (taken from Esolangs)
```
iisssaa/>e
maa->e#
aamam->e#
dddddddddddddddddddddddddPiiiiiiiiiiiiiiiiiiiiiiiii
iiiiPiiiiiiiPPiiiP
@#e
iis
aamaaaa
*>P
@#e
iisssaa/>e
maa->e#
aamam->e#
iiiiiiiiiiiiiiiiiiiiiiP
ddddddddP
iiiP
ddddddP
ddddddddP
@#e
iiss
aa*>
iP
```
Outputs `20spooky22me`:
```
iipois+iis<-<aaaO<OkOOkkkkOP@#iippisa+<m+>PaO
```
Outputs `9P-1420 100 3Q-1 162 0`:
```
iiispsdPkokmo/w<+w#aaaommO-w@ii*wew
```
## 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=63008,OVERRIDE_USER=45220;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.0.3/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]
# JavaScript (ES7) 208 ~~213 223 237 241 311~~
**Edit3** Copying each other, I and Dendrobium are collapsing together.
**Edit2** Using EcmaScript 7 to save just 2 bytes, joined together handling of A and B
**Edit** Following the changes of the rules.
~~Note, I added the `r` command that is not required in the question, just to run the **old** example *Hello world*~~
```
V=p=>(o='',[for(c of'@#e'+p)eval('++x,--x,x*=x,x=R,x=0,o+=x,o+=String.fromCharCode(x),R=A+B,R=A-B,R=A*B,R=A/B|0,R=0,o+=R+` `'.replace(/x/g,(k='ids>@pP+-*/ewakm<#oO'.indexOf(c))<13?'A':'B').split`,`[k%13])],o)
// More readable
U=p=>(
o='',
[for(c of'@#e'+p)
eval(
'++x,--x,x*=x,x=R,x=0,o+=x,o+=String.fromCharCode(x),R=A+B,R=A-B,R=A*B,R=A/B|0,R=0,o+=R+` `'
.replace(/x/g,(k='ids>@pP+-*/ewakm<#oO'.indexOf(c))<13?'A':'B')
.split`,`[k%13])]
,o
)
// ES6, no array comprehension, 2 bytes more
W=p=>
[...'@#e'+p].map(c=>
eval(
'++x,--x,x*=x,x=R,x=0,o+=x,o+=String.fromCharCode(x),R=A+B,R=A-B,R=A*B,R=A/B|0,R=0,o+=R+` `'
.replace(/x/g,(k='ids>@pP+-*/ewakm<#oO'.indexOf(c))<13?'A':'B')
.split`,`[k%13]),
o=''
)&&o
// Test
function test()
{
OUT.innerHTML = V(I.value)
}
test()
```
```
textarea { width: 75%; height: 8em }
```
```
Test program <button onclick="test()">Run</button><br><textarea id=I>
iisssaa/>e
maa->e#
aamam->e#
dddddddddddddddddddddddddPiiiiiiiiiiiiiiiiiiiiiiiii
iiiiPiiiiiiiPPiiiP
@#e
iis
aamaaaa
*>P
@#e
iisssaa/>e
maa->e#
aamam->e#
iiiiiiiiiiiiiiiiiiiiiiP
ddddddddP
iiiP
ddddddP
ddddddddP
@#e
iiss
aa*>
iP
</textarea><br>Output<pre id=OUT></pre>
```
[Answer]
# GNU Sed (with eval option to evaluate `dc` expression), 254
Deadfish maps fairly nicely to a subset of `dc`. So we use sed to do that mapping:
```
s/^/@#e/
s/\+/AB+r/g
s/-/AB-r/g
s/\*/AB*r/g
s|/|AB/r|g
s/a/B1+b/g
s/i/A1+a/g
s/d/A1-a/g
s/s/Ad*a/g
s/p/An/g
s/P/AP/g
s/>/Ra/g
s/k/B1-b/g
s/m/Bd*b/g
s/o/Bn/g
s/O/BP/g
s/</Rb/g
s/w/Rn/g
s/@/0a/g
s/#/0b/g
s/e/0r/g
s/[ABR]/l&/g
s/[abr]/s\u&/g
s/.*/dc -e'&'/e
```
[Try it online!](https://tio.run/##Jc7RCsIgFAbg@54iGBQo9m/3EtMXUHbbClxKyFqNSXSzd1/m8eo7/p4fU/DblnBDWwXsEnoOpfmCR7bIFMSeZbPiFavSWNb/tYNu@FBeRKiGu0KfKYgJyjPiDPUqsFC24IyOojHXCKqZoD0jvqFpwUDTgkRH0RcdRS1qqqhQUxRQ05cvSndXPA80uGG5IvUfGk8M/r4X4Xg4ImxbjPM7Jh5jkkI654w0ozFjPsa2VU7nmByXEz9bZ34 "sed 4.2.2 – Try It Online")
[Answer]
# Javascript ~~ES6~~ ES7, ~~217~~ ~~215~~ ~~213~~ 208 bytes
```
f=s=>(O='',[for(c of'@#e'+s)eval('v=0,++v,--v,v*=v,O+=v,O+=String.fromCharCode(v),v=R,R=0,R=A+B,R=A-B,R=A*B,R=A/B|0,O+=R+" "'.replace(/v/g,'AB'[(x='@idspP>e+-*/w#akmoO<'.indexOf(c))/13|0]).split`,`[x%13])],O)
```
Ungolfed
```
f=s=>(
O='', // initialize output to empty string
[for(c of'@#e'+s)eval( // initialize A, B, and R, loop over all chars in input, eval returned function string
'v=0,++v,--v,v*=v,O+=v,O+=String.fromCharCode(v),v=R,R=0,R=A+B,R=A-B,R=A*B,R=A/B|0,O+=R+" "' // operation list
.replace(/v/g,'AB'[(x='@idspP>e+-*/w#akmoO<'.indexOf(c))/13|0]) // replace all instances of v with either A or B
.split`,`[x%13])], // split ops list, select corresponding function string
O) // return output string
```
[Answer]
# CJam, 112
```
q{"+-*/dspP>@ikmoO<#awe"_@#\4<"X2 U|{TU :V;}P?"S/f*'T"( _*T cT;V;0)"2/f+":T;"f+_'Tf/'Uf*+"VS 0:V; "S/++=~}%Pa/0=
```
[Try it online](http://cjam.aditsu.net/#code=q%7B%22%2B-*%2FdspP%3E%40ikmoO%3C%23awe%22_%40%23%5C4%3C%22X2%20U%7C%7BTU%20%3AV%3B%7DP%3F%22S%2Ff*%27T%22(%20_*T%20cT%3BV%3B0)%222%2Ff%2B%22%3AT%3B%22f%2B_%27Tf%2F%27Uf*%2B%22VS%200%3AV%3B%20%22S%2F%2B%2B%3D%7E%7D%25Pa%2F0%3D&input=iisssaa%2F%3Ee%0Amaa-%3Ee%23%0Aaamam-%3Ee%23%0AdddddddddddddddddddddddddPiiiiiiiiiiiiiiiiiiiiiiiii%0AiiiiPiiiiiiiPPiiiP%0A%40%23e%0Aiis%0Aaamaaaa%0A*%3EP%0A%40%23e%0Aiisssaa%2F%3Ee%0Amaa-%3Ee%23%0Aaamam-%3Ee%23%0AiiiiiiiiiiiiiiiiiiiiiiP%0AddddddddP%0AiiiP%0AddddddP%0AddddddddP%0A%40%23e%0Aiiss%0Aaa*%3E%0AiP)
**Explanation:**
The program builds an array of pieces of code to be executed, and executes the corresponding piece for each character. Dealing with the division by zero is more difficult, because CJam doesn't yet have a "break" operator. Instead, the program pushes π as a marker (since no floating point number can appear otherwise), and at the end it keeps only the output before the first π.
Also, the program uses variables T, U and V instead of A, B and R, because they are preinitialized with 0 in CJam.
```
q read the input
{…}% transform each character
"…" push a string with all the 3var commands, in a convenient order
_@ duplicate the string and bring the current character to the top
# find the index of the character in the string (or -1 if not found)
\ swap with the other string copy
4< keep only the first 4 characters ("+-*/")
"…" push a string that will be used for implementing those operators
S/ split by space into ["X2" "U|{TU" ":V;}P?"]
f* join with each of '+', '-', '*', '/' -> 4 strings
'T push the 'T' character
"…" push a string with implementations of commands involving A
2/ split into pieces of length 2
f+ prepend 'T' to each piece
":T;"f+ append ":T;"to each piece
_ duplicate the array (containing full A-command implementations)
'Tf/ split each piece by the 'T' character
'Uf* join each split piece using the 'U' character
practically replacing 'T' with 'U'
to obtain B-command implementations
+ concatenate the 2 arrays
"…" push a string containing implementations for "w" and "e",
separated by space; the string also ends with a space
S/ split by space, obtaining the implementations for "w" and "e"
and an empty string, for handling unrecognized characters
++ concatenate with the A and B command and +-*/ implementations
= get the corresponding string implementing the current command
if the character was not found, -1 will get the empty string (no-op)
~ execute it
Pa/ split the array of results by the π separator
0= get the first piece (before the first π, if any)
```
The actual command implementations (constructed by the program):
```
+: X2+U|{TU+:V;}P? if (1+2)|U != 0, set V=T+U, else push π
-: X2-U|{TU-:V;}P? if (1-2)|U != 0, set V=T-U, else push π
*: X2*U|{TU*:V;}P? if (1*2)|U != 0, set V=T*U, else push π
/: X2/U|{TU/:V;}P? if (1/2)|U != 0, set V=T/U, else push π
d: T( :T; set T=T-1
s: T_*:T; set T=T*T
p: TT :T; push T and set T=T (no-op)
P: TcT:T; push T converted to character and set T=T (no-op)
>: T;V:T; push and pop T (no-op) and set T=V
@: T;0:T; push and pop T (no-op) and set T=0
i: T):T; set T=T+1
k: U( :U; set U=U-1
m: U_*:U; set U=U*U
o: UU :U; push U and set U=U (no-op)
O: UcU:U; push U converted to character and set U=U (no-op)
<: U;V:U; push and pop U (no-op) and set U=V
#: U;0:U; push and pop U (no-op) and set U=0
a: U):U; set U=U+1
w: VS push V and a space
e: 0:V; set V=0
(default): (empty) no-op
```
[Answer]
# APL, 191
```
{0::→⋄A B R←0⋄{⍵∊G←'aikdms<>':⍎'AB'[1+2|G⍳⍵],'+-*∘'[M],'←','112R'[M←⌈2÷⍨G⍳⍵]⋄⍵∊G←'PpOo':⍞←⎕UCS⍣(2|G⍳⍵)⊢A B[⌈2÷⍨G⍳⍵]⋄⍵∊G←'+-*/':R∘←⌊A(⍎'+-×÷'[G⍳⍵])B⋄⍵∊G←'@#e':⍎'ABR'[G⍳⍵],'∘←0'⋄⍵='w':⍞←R}¨⍵}
```
This is a function that takes the program as an argument, e.g:
```
∆3var←{0::→⋄A B R←0⋄{⍵∊G←'aikdms<>':⍎'AB'[1+2|G⍳⍵],'+-*∘'[M],'←','112R'[M←⌈2÷⍨G⍳⍵]⋄⍵∊G←'PpOo':⍞←⎕UCS⍣(2|G⍳⍵)⊢A B[⌈2÷⍨G⍳⍵]⋄⍵∊G←'+-*/':R∘←⌊A(⍎'+-×÷'[G⍳⍵])B⋄⍵∊G←'@#e':⍎'ABR'[G⍳⍵],'∘←0'⋄⍵='w':⍞←R}¨⍵}
∆3var 'iipois+iis<-<aaaO<OkOOkkkkOP@#iippisa+<m+>PaO'
20spooky22me
```
It can be used as an anonymous function, I just gave it a name for clarity.
Explanation:
* `0::→`: if an error occurs (say, division by zero), halt without printing the error message
* `A B R←0`: initialize variables
* `{`...`}¨⍵`: for each command:
+ `⍵∊G←'aikdms<>'`: If the command is one of the type *var ← fn(var, x)*, find the proper *fn* and *x*, substitute them in and then evaluate it:
- `⍎`: evaluate
- `'AB'[1+2|G⍳⍵`: `A` if the position of `⍵` in `'aikdms<>'` is even, `B` otherwise.
- `'+-*∘'[M]`: add, subtract, power, or nothing, depending on `M` (defined later)
- `'←'`: assign
- `'112R'[M←⌈2÷⍨G⍳⍵]`: `1` (for adding and subtracting), `2` (for power), and `R` (for nothing, i.e. it just sets the variable to `R`), depending on `M`, which is whether the command belongs to the first, second, third or fourth pair.
+ `⍵∊G←'PpOo'`: output:
- `⍞←`: output
- `⎕UCS⍣(2|G⍳⍵)`: ASCII (well, Unicode) or number depending on whether the command was on an odd or even position in `PpOo`,
- `⊢A B[⌈2÷⍨G⍳⍵]`: `A` or `B`, depending on whether the command was in the first or second half.
+ `⍵∊G←'+-*/`: math:
- `R∘←⌊A(⍎'+-×÷'[G⍳⍵])B`: set `R` to the result of applying the given operator to `A` and `B`.
+ `⍵∊G←'@#e':` reset:
- `⍎`: evaluate
- `'ABR'[G⍳⍵]`: select the right variable
- `'∘←0`': set to zero
+ `⍵='w':⍞←R`: if the command is `w`, output `R`.
[Answer]
# C, 253 241 bytes
```
#define _ c--?c--?c--
k="id@s>ak#m<e+-*/wpoPO",*p;main(c,a,b,r){for(a=b=r=0;~c;c=getchar())c=strchr(k,c),c&&(c-=k,p=&a+c/5,*p=_?_?_?_?_?printf(c?c<3?"%d":"%c":"%d ",c?c%2?a:b:r):a/(b?b:exit()):a*b:a-b:a+b:0:r:b*b:0:b-1:b+1:r:a*a:0:a-1:a+1);}
```
This code uses the string `id@s>ak#m<e+-*/wpoPO` as a table of commands. The string is arranged according to the destination of the calculated expression. It just so happens that there are 5 commands that update each of the variables:
* `id@s>` - update `a`
* `ak#m<` - update `b`
* `e+-*/` - update `r`
* `wpoPO` - update... the memory location after `a`, `b` and `r`. I hope it's not too important :)
So after locating the input character in the string of commands, its index is repeatedly decreased, and depending on when it reaches 0, an expression is chosen.
If it doesn't reach 0 after 15 subtractions, it's a `printf` with some properly chosen arguments.
Also, when dividing, it avoids division by 0 by calling `exit()`.
This code should be compiled without optimizations, because it assumes that `a`, `b` and `r` are located at adjacent addresses on stack (not in CPU registers).
Also, it should be compiled in 32-bit mode, because it converts pointers to integers and vice-versa.
[Answer]
# VBA, ~~484, 453~~ 380 Bytes
To long to win but A super Simple way of doings things, Nothing Fancy just good old `Select Case`
~~Adding in Integer Division and Div 0 Error Handling Ate a lot of Bytes~~
Removed Error Handling as it seems the normal error handling results in the same functionality.
Fixed Int Division to work as expected. Was also shorter.
```
Function Y(x)
For Z=1 To Len(x)
w=Mid(x,Z,1)
Select Case w
Case"i":A=A+1
Case"d":A=A-1
Case"s":A=A^2
Case"p":Y=Y &A
Case"P":Y=Y &Chr(A)
Case">":A=R
Case"a":B=B+1
Case"k":B=B-1
Case"m":B=B^2
Case"o":Y=Y &B
Case"O":Y=Y &Chr(B)
Case"<":B=R
Case"+":R=A+B
Case"-":R=A-B
Case"*":R=A*B
Case"/":R=A\B
Case"w":Y=Y &R &vbCrLf
Case"@":A=0
Case"#":B=0
Case"e":R=0
End Select
Next
End Function
```
>
> Thanks to Henrik Ilgen for saving ~~31~~ 104 bytes
>
>
>
[Answer]
# PHP, 310 bytes
First time in my life using ~~[`eval`](http://php.net/manual/en/function.eval.php)~~:
```
for($A=$B=$R=0;$c=$argv[1][$i++];)eval([i=>'++$A',d=>'--$A',s=>'$A*=$A',p=>'echo$A',P=>'echo chr($A)','>'=>'$A=$R',a=>'++$B',k=>'--$B',m=>'$B*=$B',o=>'echo$B',O=>'echo chr($B)','<'=>'$B=$R','+'=>'$R=$A+$B','-'=>'$R=$A-$B','*'=>'$R=$A*$B','/'=>'$R=$A/$B',w=>'echo$R','@'=>'$A=0','#'=>'$B=0',e=>'$R=0'][$c].';');
```
Takes the first command line input:
```
php 3var.php "iipois+iis<-<aaaO<OkOOkkkkOP@#iippisa+<m+>PaO"
```
---
Output from the examples:
>
> Hello world!
>
> 20spooky22me
>
>
>
[Answer]
# C, 357
Macros FTW!
(Who am I kidding - c will never win this one)
```
#define X(p,e) case p:e;break;
#define Y(p,a,b,c,d,e,f) X(a,p++)X(b,p--)X(c,p*=p)X(d,printf("%d",p))X(e,printf("%c",p%256))X(f,p=R)
A,B,R;main(int C,char**V){for(;*V[1];)switch(*V[1]++){Y(A,'i','d','s','p','P','>')Y(B,'a','k','m','o','O','<')X('+',R=A+B)X('-',R=A-B)X('*',R=A*B)X('/',R=A/(B?B:exit(0),1))X('w',printf("%d",R))X('@',A=0)X('#',B=0)X('e',R=0)}}
```
[Answer]
# JavaScript (ES6), 293 262 bytes
```
f=x=>(o="",a=b=r=0,p=String.fromCharCode,[...x].map(c=>{if(eval(`m={i_a++,d_a--,s_a*=a,p_o+=a,P_o+=p(a),">"_a=r,a_b++,k_b--,m_b*=b,o_o+=b,O_o+=p(b),"<"_b=r,"+"_r=a+b,"-"_r=a-b,"*"_r=a*b,"/"_r=a/b|0,w_o+=r,"@"_a=0,"#"_b=0,e_r=0}[c]`.replace(/_/g,":_=>")))m()}),o)
```
## Usage
```
f(`iisssaa/>e
maa->e#
aamam->e#
dddddddddddddddddddddddddPiiiiiiiiiiiiiiiiiiiiiiiii
iiiiPiiiiiiiPPiiiP
@#e
iis
aamaaaa
*>P
@#e
iisssaa/>e
maa->e#
aamam->e#
iiiiiiiiiiiiiiiiiiiiiiP
ddddddddP
iiiP
ddddddP
ddddddddP
@#e
iiss
aa*>
iP`)
=> "Hello world!"
```
## Explanation
There are a few details of the language that I'm unsure about (integer sizes, handling unrecognised characters, etc) but this solution seems to work sufficiently and ignores whitespace characters like the new-lines in the test case.
```
f=x=>(
o="", // o = output string
a=b=r=0,
p=String.fromCharCode,
[...x].map(c=>{ // iterate through each character
if( // if used for NOP characters (whitespace)
// Functions:
eval(`m={
i_a++,
d_a--,
s_a*=a,
p_o+=a,
P_o+=p(a),
">"_a=r,
a_b++,
k_b--,
m_b*=b,
o_o+=b,
O_o+=p(b),
"<"_b=r,
"+"_r=a+b,
"-"_r=a-b,
"*"_r=a*b,
"/"_r=a/b|0,
w_o+=r,
"@"_a=0,
"#"_b=0,
e_r=0
}[c]`.replace(/_/g,":_=>")) // dynamically add common characters
)m() // execute the function
}),
o // return the output string
)
```
[Answer]
# [Simplex v.0.8](http://conorobrien-foxx.github.io/Simplex/), 211 bytes
(UTF-8 encoded.)
```
h@u]u2ƒ§I]ƒ§M]ƒ§^O]ƒ§o]ƒ§s]ƒ§@]ƒ§Ah]ƒ§Sh]ƒ§Mh]ƒ§Vh]ƒ§&oh]ƒðI]ƒðM]ƒð^O]ƒðo]ƒðs]ƒð@]ƒðAh]ƒðSh]ƒðMh]ƒðVh]ƒð&oh]ƒ§z]ƒðz]ƒuz@]{"idspP>akmoO<+-*/w@#e"RlyG^u·u†vøÏ}
```
## Explanation
Since this is *the longest* simplex program I have thus far written, I will generally explain how this works in bullet points.
* `h@u]` - defines macro 0. This macro simply writes to the register and makes a lambda return nothing.
* `u2` - goes to the above strip and sets the current byte to 2; this defines the arity of the lambdas to be defined.
* `ƒ` - begin lambda expression; once completed by `]`, will push lambda function to the lambda stack. It acts by taking (arity) cells from the pointer into its local strip, and, after completion, will set its local strip to the taken cells, unless the current byte is unwritten. The pointer is not affected. Macro 0 allows for a function to return without modifying anything in the strip.
* `§` - moves to the first written cell in the current strip i.e. `A`.
* `ð` - moves to the last written cell in the current strip i.e. `B`.
* … `{"idspP>akmoO<+-*/w@#e"RlyG^u·u†vøÏ}`
+ `{...Ï}` repeat until the input stack is empty
+ `"idspP>akmoO<+-*/w@#e"` - the commands
+ `Rly` - put the strip into a tuple
+ `G^u` - the index of the input in the tuple
+ `·` - load the current byteth into the lambda evaluator
+ `uRL` - goes to the strip holding `A` and `B` (writes `A` and `B` if they don't exist)
+ `†` - executes lambda (this is the lambda evaluator)
+ `vø` - resets below strip
*phew* I'm impressed. It's long for Simplex, but short for everything else. `;)`
[Answer]
## [Minkolang 0.11](https://github.com/elendiastarman/Minkolang), 222 bytes
I'm sure this can be golfed further, but it was fun. Also, first Minkolang interpreter of another language!
```
>I3&000V$Vod?.45*[di1q=5&]x00wx1i2+kw
idspP>akmoO<+-*/w@#e
vr1+r
vr1-r
vr2;r
v0c1$((dl%"0"+$rl:d)$Ok
v0cO
vrx0cr
v1g1+1G
v1g1-1G
v1g2;1G
v1c1$((dl%"0"+$rl:d)$Ok
v1cO
v1gxd1G
vx$d+
vx$d-
vx$d*
vx$dd?.:
vdN
vrx0r
v1gx01G
vx0
```
[Try it here.](http://play.starmaninnovations.com/minkolang/old?code=%3EI3%26000V%24Vod%3F%2E45%2A%5Bdi1q%3D5%26%5Dx00wx1i2%2Bkw%0AidspP%3EakmoO%3C%2B-%2A%2Fw%40%23e%0Avr1%2Br%0Avr1-r%0Avr2%3Br%0Av0c1%24%28%28dl%25%220%22%2B%24rl%3Ad%29%24Ok%0Av0cO%0Avrx0cr%0Av1g1%2B1G%0Av1g1-1G%0Av1g2%3B1G%0Av1c1%24%28%28dl%25%220%22%2B%24rl%3Ad%29%24Ok%0Av1cO%0Av1gxd1G%0Avx%24d%2B%0Avx%24d-%0Avx%24d%2A%0Avx%24dd%3F%2E%3A%0AvdN%0Avrx0r%0Av1gx01G%0Avx0&input=iisssaa%2F%3Ee%0Amaa-%3Ee%23%0Aaamam-%3Ee%23%0AdddddddddddddddddddddddddPiiiiiiiiiiiiiiiiiiiiiiiii%0AiiiiPiiiiiiiPPiiiP%0A%40%23e%0Aiis%0Aaamaaaa%0A%2A%3EP%0A%40%23e%0Aiisssaa%2F%3Ee%0Amaa-%3Ee%23%0Aaamam-%3Ee%23%0AiiiiiiiiiiiiiiiiiiiiiiP%0AddddddddP%0AiiiP%0AddddddP%0AddddddddP%0A%40%23e%0Aiiss%0Aaa%2A%3E%0AiP)
### Explanation
```
>I3&000 Initializes A, B, and R if they don't already exist.
V$V An idiom that ensures no time-travel.
od?. Reads in a character and halts if input is empty.
45*[di1q=5&] Looks through the second row for a matching character.
x00w Jumps back to beginning if no match.
x1i2+kw Jumps to corresponding line upon match.
```
The rest of the lines are pretty simple, perhaps with the exception of those with `1$((dl%"0"+$rl:d)$Ok`, which is an idiom that prints a number without a trailing space. (I haven't yet implemented the convert-this-number-to-a-string functionality, which will be `1Z`.) Oh, yes, they all have a `v` at the beginning, which takes it back to the beginning.
[Answer]
# GNU Sed (with eval option to evaluate dc expression), 289
Inspired by Digital Trauma who sadly failed to realize, that a) illegal characters need to be ignored, b) dc needs the entire converted program in one argument and c) division by 0 must terminate the program without error.
If all these rules wouldn't apply, my solution would only be 235 bytes long ;)
```
H
$!d
x
s/^/@#e/
s:[^-a><de/+i*k@w#opsmOP]::g
s:[e@#]:0&:g
s:[-*+/pPid]:Q&:g
s:[-kaoO*+/]:H&:g
s:[><w]:Z&:g
s:[diak]:1&:g
s:s:Q2^>:g
s:m:H2^<:g
s:[-+*/]:&e:g
s:[ia]:+&:g
s:[dk]:-&:g
y:Oop:Pnn:
s:w:n32P:g
s:[id>@]:sq:g
s:e:sz:g
s:[#<ka]:sh:g
s:[QHZ]:l\l&:g
s:/:d0=t/:g
s/.*/dc -e'[q]st&'/e
```
[Answer]
# AWK, ~~311~~ 309
```
func p(z,f,x){if(c~z)printf"%"f,x}BEGIN{FS=z}{for(i=0;++i<=NF;){c=$i;A=c~/i/?A+1:c~/d/?A-1:c~/s/?A*A:c~/@/?0:c~/>/?R:A;p("p","d",A);p("P","c",A);B=c~/a/?B+1:c~/k/?B-1:c~/m/?B*B:c~/#/?0:c~/</?R:B;p("o","d",B);p("O","c",B);R=c~/+/?A+B:c~/-/?A-B:c~/*/?A*B:c~/e/?0:R;if(c~"/")if(B)R=A/B;else exit;p("w","d ",R)}}
```
TIL parenthesis were not needed around printf. 2 bytes saved!
### Ungolfed version for easier reading:
```
func p(z,f,x) {
if(c~z) printf "%"f,x
}
BEGIN {
FS=z
}
{
for(i=0;++i<=NF;){
c=$i;
A=c~/i/?A+1:c~/d/?A-1:c~/s/?A*A:c~/@/?0:c~/>/?R:A;
p("p","d",A);
p("P","c",A);
B=c~/a/?B+1:c~/k/?B-1:c~/m/?B*B:c~/#/?0:c~/</?R:B;
p("o","d",B);
p("O","c",B);
R=c~/+/?A+B:c~/-/?A-B:c~/*/?A*B:c~/e/?0:R;
if(c~"/")if(B)R=A/B;else exit;
p("w","d ",R)
}
}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~104~~ ~~103~~ 102 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
0©U0Vv“ìÉP@p>akmO#o<+-*/ew“ykDdi…><nS'Xì'U«"Xç?0UX?®U"4ä«Dε„XU„YV‡}«"+-*÷"S„XYì0ª„©\«„®,ª«sè.Vy'/Q®+iq
```
[Try it online](https://tio.run/##yy9OTMpM/f/f4NDKUIOwskcNcw6vOdwZ4FBgl5id66@cb6Otq6WfWg4Ur8x2Scl81LDMziYvWD3i8Br10EOrlSIOL7c3CI2wP7QuVMnk8JJDq13ObX3UMC8iFEhEhj1qWFgLVAQ04vB2pWCQeOThNQaHVgFZh1bGHFoNotfpHFp1aHXx4RV6YZXq@oGH1mlnFv7/r6SklJlZXFycmKhvl8qVm5ioa5eqzJWYmJuYC2al4AIBmbgAF4iASQeAGAFcDsqpQOFisMFAwKVlBxfDbTd24wPgbgrgQuIiC8NMBpqlZceVGQD0JAA) or [verify all test cases](https://tio.run/##fU8xS8NAGN39FeUyFJLGZHCSkGbo4nQnJSXFOJwkwxHuErm2IUMgq/9BBEHUNqWbOgp3uz8ifyReWqwK1jd893jv@973XcrxFYnbRQHOWDafnfbk@xGcz7YUDIvWFkvfniya6lau5Q3yMhcnFGqpY5i6FedKL5JRRJrq0XXYuB/Idd8XNQjk09D2g6HY@OBEPoh69PHSVHeBr8p00lT3pWpSEfINjDt9Kte2WCkmlqGou3czECtRc/l8PCn61rnYGOS6LctSvA7aC0AI5xxjy41DRjE23VgLGcYU0x2NDgGRQwhZV7981BEUMk@LO4Pv0hVCprs/9H@v@HsR@j4PbXv2wm9nv6LL1F3FERj01NezlHBDGY7pqIOgAxMIEwWIPE25GeHYcKjhIgx3A4RnPEJJmtDUyh0j19RYSik0c48QPY9zcPkJ).
**Explanation:**
```
0©U0V # Set variables `X` (A), `Y` (B) and `®` (R) to 0
# (they are 1, 2, and -1 respectively by default)
v # Loop over each character `y` of the (implicit) input-string:
“ìÉP@p>akmO#o<+-*/ew“
# Push dictionary string "idsP@p>akmO#o<+-*/ew"
yk # Get the index of `y` in this string
D # Duplicate it
di # If the index is not -1 (thus it's a valid character):
…><n # Push string "><n"
S # Convert it to a list of characters: [">","<","n"]
'Xì '# Prepend an "X" in front of each item: ["X>","X<","Xn"]
'U« '# Append an "U" after each item: ["X>U","X<U","XnU"]
"Xç?0UX?®U" # Push string "Xç?0UX?®U"
4ä # Try to split it into 4 equal-sized parts: ["Xç?","0U","X?","®U"]
« # Merge these two lists together:
# ["X>U","X<U","XnU","Xç?","0U","X?","®U"]
D # Duplicate the list
ε } # Map over each inner string:
„XU„YV‡ # And transliterate all "X" to "Y" and all "U" to "V"
« # Merge the lists together:
# ["X>U","X<U","XnU","Xç?","0U","X?","®U",
# "Y>V","Y<V","YnV","Yç?","0V","Y?","®V"]
"+-*÷" # Push string "+-*÷"
S # Convert it to a list of characters: ["+","-","*","÷"]
„XYì # Prepend "XY" in front of each item: ["XY+","XY-","XY*","XY÷"]
0ª # Append a 0: ["XY+","XY-","XY*","XY÷",0]
„©\« # Append "®\" after each item:
# ["XY+©\","XY-©\","XY*©\","XY÷©\","0©\"]
„®,ª # Append string "®," to this list:
# ["XY+©\","XY-©\","XY*©\","XY÷©\","XY0©\","®,"]
« # Merge the two lists together:
# ["X>U","X<U","XnU","Xç?","0U","X?","®U",
# "Y>V","Y<V","YnV","Yç?","0V","Y?","®V",
# "XY+©\","XY-©\","XY*©\","XY÷©\","XY0©\","®,"]
s # Swap to get the duplicated index
è # Use it to index into this list of strings
.V # And evaluate/execute it as 05AB1E code
y'/Q '# Check if the current character equals "/"
®+ # Add the value of `®` to it
i # If this is now 1:
# (thus the current character is "/" and the value of `®` is 0):
q # Stop the program
```
Here an overview of all characters translated to 05AB1E code:
```
i X>U # Push `X`; increase it by 1; pop and store it as new `X`
d X<U # Push `X`; decrease it by 1; pop and store it as new `X`
s XnU # Push `X`; square it; pop and store it as new `X`
P Xç? # Push `X`; convert it to a character; pop and print it (without newline)
@ 0U # Push 0; pop and store 0 as new `X`
p X? # Push `X`; pop and print it (without newline)
> ®U # Push `®`; pop and store `®` as new `X`
a Y>V # Push `Y`; increase it by 1; pop and store it as new `Y`
k Y<V # Push `Y`; decrease it by 1; pop and store it as new `Y`
m YnV # Push `Y`; square it; pop and store it as new `Y`
O Yç? # Push `Y`; convert it to a character; pop and print it (without newline)
# 0V # Push 0; pop and store 0 as new `Y`
o Y? # Push `Y`; pop and print it (without newline)
< ®V # Push `®`; pop and store `®` as new `Y`
+ XY+©\ # Push `X` and `Y`; add them together; store it in `®` (without popping);
# and discard it from the stack
- XY-©\ # Push `X` and `Y`; subtract them from one another; store it in `®`
# (without popping); and discard it from the stack
* XY*©\ # Push `X` and `Y`; multiply them together; store it in `®` (without
# popping); and discard it from the stack
/ XY÷©\ # Push `X` and `Y`; integer-divide them from one another; store it in `®`
# (without popping); and discard it from the stack
e 0©\ # Push 0; store 0 in `®` (without popping); and discard it from the stack
w ®, # Push `®`; pop and print it with trailing newline
```
[See this 05AB1E tip (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `“ìÉP@p>akmO#o<+-*/ew“` is `"idsP@p>akmO#o<+-*/ew"`.
[Answer]
# Python 2, 272
```
import sys;a,b,r=0,0,0;exec';'.join(filter(None,map(dict(x.split(':')for x in"a:b+=1|@:a=0|#:b=0|/:r=a/b|d:a-=1|PXchr(a)|i:a+=1|-:r=a-b|k:b-=1|*:r=a*b|m:b*=b|oXb|pXa|s:a*=a|OXchr(b)|wXr|+:r=a+b|e:r=0|<:b=r|>:a=r".replace('X',':print ').split('|')).get,sys.stdin.read())))
```
[Answer]
# Ruby, 199 bytes
```
a=b=r=0
$<.read.chars{|c|eval %w{a+=1
a-=1
a*=a
$><<a
$><<a.chr
a=r
b+=1
b-=1
b*=b
$><<b
$><<b.chr
b=r
r=a+b
r=a-b
r=a*b
b==0&&exit||r=a/b
puts\ r
a=0
b=0
r=0
p}["idspP>akmoO<+-*/w@#e".index(c)||-1]}
```
5 bytes can be saved by removing `.read` from the second line if you can tolerate a warning being printed to stderr on newer version of Ruby.
[Answer]
# Python, 244
```
import sys;P=sys.stdout.write;A=B=R=0;exec';'.join(filter(None,map(dict(zip('idspP>akmoO<+-*/w@#e','A+=1 A-=1 A**=2 P(`A`) P(chr(A)) A=R B+=1 B-=1 B**=2 P(`B`) P(chr(B)) B=R R=A+B R=A-B R=A*B R=A/B print(R) A=0 B=0 R=0'.split())).get,input())))
```
Bit late but I wanted to have a go.
[Answer]
# Prolog, 759 bytes
Not the shortest program, but at least it's structured and readable.
```
q(A,B,R,i,X,B,R):-X is A+1.
q(A,B,R,d,X,B,R):-X is A-1.
q(A,B,R,s,X,B,R):-X is A*A.
q(_,B,R,>,R,B,R).
q(A,B,R,a,A,X,R):-X is B+1.
q(A,B,R,k,A,X,R):-X is B-1.
q(A,B,R,m,A,X,R):-X is B*B.
q(A,_,R,<,A,R,R).
q(A,B,_,+,A,B,X):-X is A+B.
q(A,B,_,-,A,B,X):-X is A-B.
q(A,B,_,*,A,B,X):-X is A*B.
q(_,0,_,/,_,_,_):-!,1=2.
q(A,B,_,/,A,B,X):-B>0,X is A/B.
q(_,B,R,@,0,B,R).
q(A,_,R,#,A,0,R).
q(A,B,_,e,A,B,0).
q(A,B,R,p,A,B,R):-write(A).
q(A,B,R,'P',A,B,R):-A>0,format('~c',A).
q(A,B,R,'P',A,B,R):-write(A).
q(A,B,R,o,A,B,R):-write(B).
q(A,B,R,'O',A,B,R):-format('~c',B).
q(A,B,R,'O',A,B,R):-write(B).
q(A,B,R,w,A,B,R):-write(R),nl.
q(A,B,R,_,A,B,R).
f([],_,_,_).
f([H|T],A,B,R):-q(A,B,R,H,X,Y,Z),f(T,X,Y,Z),!.
p(X):-atom_chars(X,Y),f(Y,0,0,0).
```
**Example input**
```
p('iipois+iis<-<aaaO<OkOOkkkkOP@#iippisa+<m+>PaO').
```
Try it out online [here](http://swish.swi-prolog.org/)
[Answer]
# [Perl 5](https://www.perl.org/) `-Minteger -n0`, 274 bytes
```
s//;/g;s/e/R=0/g;s/\+/R=A+B/g;s/-/R=A-B/g;s/\*/R=A*B/g;s/i/A++/g;s/d/A--/g;s/s/A*=A/g;s/p/printA|0/g;s/P/print chrA/g;s/>/A=R/g;s/a/B++/g;s/k/B--/g;s/m/B*=B/g;s/o/printB|0/g;s/O/print chrB/g;s/</B=R/g;s,/,B||exit;R=A/B,g;s/w/sayR|0/g;s/\@/A=0/g;s/#/B=0/g;s/[ARB]/\$$&/g;eval
```
[Try it online!](https://tio.run/##dZA9T8MwEIZ3/wqkVAxOzIWhU0hUe6@wshIGi1rFovlQHBWQ8tsxti8tHcgN0fPe6Z6zMujxtHXOAhRwLCxoqMs8UpN65KmIgQVmyA0NgWIwwNM00gE4Y5EscFryiAMMo@kmPqNTYrx7ex9xXgEv60gKxCL6ALGIWhC0xDs9bopF9PwnwvkTCBRlkIl51l9mKvwrQWRh@glWfdfLbrPzRxETv4X0wmvxCs1mc@@jPquTc8ZYa5WCSpNWKVbphCjVqjbSYa2kWSsSPpexDCDJLtG@baPYF6HVtbd@@3@9vL5Jkpt4276YvYtWxMiffphM31nH9v5n6qMePW0f8sfcsS7/BQ "Perl 5 – Try It Online")
] |
[Question]
[
You will be given a string `s`. It is guaranteed that the string has equal and at least one `[`s and `]`s. It is also guaranteed that the brackets are balanced. The string can also have other characters.
The objective is to output/return a list of tuples or a list of lists containing indices of each `[` and `]` pair.
### note: The string is zero-indexed.
Example:
`!^45sdfd[hello world[[djfut]%%357]sr[jf]s][srtdg][]` should return
`[(8, 41), (20, 33), (21, 27), (36, 39), (42, 48), (49, 50)]` or something equivalent to this. Tuples are not necessary. Lists can also be used.
Test cases:
```
input:[[asdf][][td([)ty54g% ]hg[[f]u][f[[jhg][gfd]sdf]sdfs]ghd]fr43f]
output:[(0, 62),(1, 6), (7, 8), (9, 56), (13, 22), (25, 30), (26, 28), (31, 52), (33, 47), (34, 38), (39, 43)]
input:[[][][][]][[][][][[[[(]]]]]))
output:[(0, 9), (1, 2), (3, 4), (5, 6), (7, 8), (10,26),(11, 12), (13, 14), (15, 16), (17, 25), (18, 24), (19, 23), (20, 22)]
input:[][][[]]
output:[(0, 1), (2, 3), (4, 7), (5, 6)]
input:[[[[[asd]as]sd]df]fgf][][]
output:[(0, 21), (1, 17), (2, 14), (3, 11), (4, 8), (22, 23), (24, 25)]
input:[]
output:[(0,1)]
input:[[(])]
output:[(0, 5), (1, 3)]
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes for each programming language wins.
[Answer]
# [Brain-Flak Classic](https://github.com/DJMcMayhem/Brain-Flak), 108 bytes
```
{((((((([][][]){}){}){}()){}){}{}[])()()){{}<>{}(<>)}{}((){[](<{}>)}{}){{}<>[({}<[{}]>)](<>)}{}<>(({}()))<>}
```
[Try it online!](https://tio.run/##LU07DsMgDL1Klkr2kKnphriI5YEGGdKiDiEdKouzEwj1V@8j@7m77TNLcu9aFUYQ90QtowDH1tJIwA61GNsEY7GxAKjEYLRccKgEbZIWtsh/n7EA1zU0ttRK5LKX/urwQHj8Hku4TRwDkfCXSYheMTAF8dyNrTOH6Fn25S5cZ5emNbmct/UE "Brain-Flak – Try It Online")
Stores each opening `[` in the right stack, and outputs whenever we hit a `]`.
[Answer]
# [Python 2](https://docs.python.org/2/), 74 bytes
```
s=[];i=0
for c in input():
if'['==c:s+=i,
if']'==c:print s.pop(),i
i+=1
```
[Try it online!](https://tio.run/##HYo7DsMgFAR7n4ImAmQrysdpHHGS1SsiowekwAhw4dMTYmm2GO2ko/otPlorBvQO5jbwlsUqQuykvSq9DCKwhDRmXcpownQ6nZ5yiFWUa9qS0lPoz2jurUngUywTCNUq6Hq8ZncR5B3AtBMY@HpHcGzpH/YVct4S5/nJJH8 "Python 2 – Try It Online")
[Answer]
# JavaScript, ~~69~~ 62 bytes
A quick bit of golf on the train home. Can probably be improved on.
Takes input as an array of characters and outputs an object with the keys being the indices of the `[`s and their values being the indices of their corresponding `]`s.
```
a=>a.map((x,y)=>x==`]`?o[a.pop()]=y:x==`[`&&a.push(y),o={})&&o
```
[Try it online](https://tio.run/##FcqxCoMwFEDRXylCQwI2S@1SiN07tEPHxwOD8UXFmmC0GEq/PdXhLofb648O9dT5@TQ60yRSSatSy7f2nK95FKpclaqwujnQ0jvPBap43Q0qxjZaQsujyJ36/gRjLtVuDG5o5OAsv7@eDxnmqRttR5ETByllBqCDIQSE2XAQc7wU9njA1gIQLggE0LcWwZLBfdwKaFuDNBVnwgyFEOkP)
[Answer]
# [Haskell](https://www.haskell.org/), ~~92~~ 79 bytes
```
g(u:a)n(']':x)=(u,n):g a(n+1)x
g a n(s:x)=g([n|s=='[']++a)(n+1)x
g[]_[]=[]
g[]0
```
[Try it online!](https://tio.run/##NYpBCsIwEEX3PUUoQmaIC90G5iSfQWbRxmIdxLTQhXePcSG8xXv8f7f6mNa1tUJ7NnaKGvPBQvvZOZdg5OnKx9AtONXfVAj@qSIRUVMy/j@gN6hAh1m6X9rTFpfXe/HtNI/QbUIAoNrR2jtAx/YF "Haskell – Try It Online")
## Explanation
We create a function `g` which takes 3 arguments.
* `a`, which is the locations of all unmatched `[`s.
* `n`, which is the number of characters processed
* `x` which is the characters unprocessed.
If our first character is `]` we remove `u` from the front our `a` and return `(u,n)` plus whatever else remains.
```
g(u:a)n(']':x)=(u,n):g a(n+1)x
```
If our first character is not `]`, that is either `[` or something else, we increment `n` and add `[n|s=='[']` to the front of `a`. `[n|s=='[']` will be `[n]` if `s=='['` and `[]` otherwise.
```
g a n(s:x)=g([n|s=='[']++a)(n+1)x
```
If we are out of characters we return the empty list.
```
g[]_[]=[]
```
[Answer]
# Java 10, 95 bytes
A void lambda taking the input string as an `int[]` of Unicode code points.
```
s->{int r=0,w=0;for(var c:s){if(c==91)s[w++]=r;if(c==93)System.out.println(s[--w]+","+r);r++;}}
```
[Try It Online](https://tio.run/##XY/BasMwEETP9lcIQ0HCsUhJemhdB0rPhUKOyx5UyVLkOlKQ5IQQ/O2uAjn1sAw77AxvB3EWzaB@l9P0M1pJ5ChiJF/COnIri4cZk0hZtHViJENO8CnZkevJyWS945/exenYh3frEuCOaNKVS2x2t7yT0K1Xl27dah/oWQQi3yK7WU1l170@swiXusYutA9nw/bXmPoj91Pip5ALRkcjNM0F62pV1YG1oa7beV7Koi3/E569VeSY4ek@5awBJCKYyO6/FJoLKftTohWAiEojICRFgaXry9Y8ETwYAI0TggYYDgbBaIX3wzwRzUGhDtuNxopLr/pvn@EiZTz5jxDElTLWlsVczuXyBw)
## Ungolfed
```
s -> {
int r = 0, w = 0;
for (var c : s) {
if (c == 91)
s[w++] = r;
if (c == 93)
System.out.println(s[--w] + "," + r);
r++;
}
}
```
## Acknowledgments
* thanks to Jonathan Frech for the idea of using the input string as a stack ([here](https://codegolf.stackexchange.com/a/166464/44945))
[Answer]
# vim, 89 bytes
```
:s/\(.\)/\1<C-V><C-M>/g|g/^\[/ :norm %mm%:pu! =line('.').','.line(\"'m\")<C-V><C-M><C-X>$<C-X>J
:v/\[/d|%s/\[//g
```
## Annotated
```
:s/\(.\)/\1<C-V><C-M>/g " one character per line
|g/^\[/ " for each opening square bracket:
:norm %mm% " mark the line with the matching bracket
:pu! =line('.').','.line(\"'m\") " write the line numbers to preceeding line
<C-V><C-M><C-X>$<C-X>J " convert to 0-based counting and join lines
:v/\[/d " remove all non-opening bracket lines
|%s/\[//g " remove brackets
```
`<C-V>` is 0x16. `<C-M>` is 0x0d. `<C-X>` is 0x18.
[Try it online!](https://tio.run/##HctLCsMgFEDRuQsIGZpQMYHio7ShIHQD3cLTjIy2QZOiSTrJ3u1ndDmDu@UsE6hGqBbUqSDgdge9QqBymmOgLAQmX2tFb/45DQ0XvBX8yMVfquZB1W1BykN5J3KD72d2ln4FR3Ou@kuXjDX4GLyf6XuO3iCa0a6LZuzcXXWKOFqdNKa4GKdRfwA "V – Try It Online")
[Answer]
## QBasic (QB64), ~~137~~ ~~127~~ 112 bytes
```
INPUT a$
for i=0to len(a$)
c$=mid$(a$,i+1,1)
if"["=c$then
b(n)=i
n=n+1
elseif"]"=c$then
n=n-1
?b(n),i
endif
next
```
We need ~~four~~ two bytes because the challenge requires 0-indexing. My first QBasic post, feedback is appreciated.
* 10 bytes thanks to steenbergh
* 3 bytes thanks to Erik the Outgolfer
* 12 bytes by saving in unix file format (`\r\n` -> `\n`)
Looks like this when executed:
[](https://i.stack.imgur.com/Wypko.png)
[Answer]
# Pyth, 26 bytes
```
VQIqN\[=+YZ)IqN\],.)YZ)=hZ
```
[Try it here](http://pyth.herokuapp.com/?code=VQIqN%5C%5B%3D%2BYZ%29IqN%5C%5D%2C.%29YZ%29%3DhZ&input=%22%5B%5Basdf%5D%5B%5D%5Btd%28%5B%29ty54g%25%20%5Dhg%5B%5Bf%5Du%5D%5Bf%5B%5Bjhg%5D%5Bgfd%5Dsdf%5Dsdfs%5Dghd%5Dfr43f%5D%22&debug=0)
### Explanation
```
VQIqN\[=+YZ)IqN\],.)YZ)=hZ
VQ =hZ For each character in the input (indexed by Z)...
IqN\[=+YZ) ... if the character is [, add the index to Y...
IqN\],.)YZ) ... if the character is ], output the previous index
and current index.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~20~~ 18 bytes
*Saved 1 byte thanks to @user202729 informing me that `µ€` is `)`*
```
ẹⱮØ[µ³ḣċþØ[_/Ụị)Z’
```
[Try it online!](https://tio.run/##y0rNyan8///hrp2PNq47PCP60NZDmx/uWHyk@/A@IC9e/@HuJQ93d2tGPWqY@f//f/Xo6MTilLTY6NjokhSNaM2SSlOTdFWF2Iz06Oi02NLY6LTo6KyM9Njo9LSUWJBCIC6OTc9IiU0rMjFOi1UHAA "Jelly – Try It Online")
After wrestling with this for several hours just to get it working... I'm honestly surprised that it's gotten this short :-)
### Explanation
```
ẹⱮØ[µ³ḣċþØ[_/Ụị)Z’ Main link. Argument: s (string) '[a[b]c[]][d]'
Ø[ Shortcut for the string "[]".
Ɱ For each char in the "[]":
ẹ Find the indices of each occurrence in the input.
For our example, this gives the array [[1, 3, 7, 10], [5, 8, 9, 12]].
µ Begin a new monadic chain, with said array as its argument.
) For each of the two sub-arrays q within the array:
[[1, 3, 7, 10], [5, 8, 9, 12]]
³ḣ For each item n in q, take the first n chars of the input.
[['[', '[a[', '[a[b]c[', '[a[b]c[]]['],
['[a[b]', '[a[b]c[]', '[a[b]c[]]', '[a[b]c[]][d]']]
þØ[ For each string s in this, and each char c in "[]":
ċ Count the occurrences of c in s.
[[[1, 0], [2, 0], [3, 1], [4, 3]],
[[2, 1], [3, 2], [3, 3], [4, 4]]]
_/ Reduce each pair by subtraction. This is the number of open brackets
at each position.
[[1, 2, 2, 1], [1, 1, 0, 0]]
U Sort the indices by their values, using position as a tiebreaker.
[[1, 4, 2, 3], [3, 4, 1, 2]]
ị Index these values back into q.
[[1, 10, 3, 7], [9, 12, 5, 8]]
) Start a new monadic chain with the result as its argument.
Z Zip; transpose rows and columns.
[[1, 9], [10, 12], [3, 5], [7, 8]]
’ Decrement; switch to 0-indexing.
[[0, 8], [9, 11], [2, 4], [6, 7]]
```
[Answer]
# [R](https://www.r-project.org/), ~~141 133 115 112~~ 108 bytes
```
function(y,x=utf8ToInt(y)){for(i in seq(x)){if(x[i]==91)F=c(i,F);if(x[i]==93){T=c(T,F[1],i);F=F[-1]}};T[-1]}
```
[Try it online!](https://tio.run/##RcixCsIwEADQXzktQgLtUFRUStaAeyePE6TJ2UhJMEmxIn57FRenBy/OrGYefZdd8OJZTmrMvG/D0WfxlPLFIQoHzkOydzF9w7GY0JFSh1pq1QlXatn8cy1f7XfbUmNNpZONVhqrmt7vpv05s1guzpttMmywt8MQ4BHiYBDNjcdMq9V6u6MU8caUCFPM5kpISwkV1ABFUcDJxlA5b@wEF842Qu4t8KXL8wc "R – Try It Online")
Nothing special. 1-indexed, because I said so. R doesn't really have stacks, so I originally used `c`, `head`, and `tail` to get the same literal effect. Ungolfed original version (updates using `utf8ToInt` to remove some bytes, using the start of the vector as the top of the stack, and abusing `T` and `F` builtins to avoid initializing the stacks.):
```
f <- function(y, x=el(strsplit(y,""))) {
p <- l <- NULL
for(i in seq_along(x)) {
if(x[[i]]=='[') {
p <- c(p, i)
}
if(x[[i]]==']') {
l <- c(l, tail(p, 1), i)
p <- head(p, -1)
}
}
l # Because I said so. Change to l-1 if you want to check the test cases.
}
```
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 75 bytes
```
: f 0 do dup i + c@ dup 91 = if i s>f then 93 = if f>s . i . cr then loop ;
```
[Try it online!](https://tio.run/##JYpBCsIwFESvMhQERSxK66KKxXt8/kIaJ6mIKUm68PQxtYthhveGPiR3sFwq5wuII4yHmSeM2GO4/2d3wg0jC4o9kdzzg65ZEfuIuogaQ1jN2/sJ1xwriDyioYpKMlvZpe@5tRuosyLUWYUiL2dVLI0ux5Ko1hllaBtqBeYf "Forth (gforth) – Try It Online")
Abuses the floating-point stack, but allows using a `do loop` since the code doesn't (manually) touch the return stack.
### Explanation
1. Loop through characters in string
2. Check each character
1. If equal to `[`, put on floating point stack
2. if equal to `]` pop from floating point stack and output with current position
### Code Explanation
```
0 do \ start a loop from 0 to string-length
dup \ duplicate the starting address to avoid losing it
i + c@ \ get the address of the current position and retrieve the character
dup \ duplicate the character, to allow checking twice
91 = if \ if char = [
i s>f \ store the current address on the floating point stack
then \ end the if-statement
93 = if \ if char = ]
f>s . \ pop the starting position from the float-stack and print
i . \ print the current position
cr \ output a newline
then \ end the if-statement
loop \ end the loop
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 36 bytes
```
L$v`\[((\[)|(?<-2>])|[^]])*
$.`,$.>`
```
[Try it online!](https://tio.run/##K0otycxLNPz/30elLCEmWkMjJlqzRsPeRtfILlazJjouNlZTi0tFL0FHRc8u4f9/xTgT0@KUtJTojNScnHyF8vyinJTo6JSstNKSWFVVY1Pz2OKi6Ky02OLY6OKikpT02OhYAA "Retina – Try It Online") Explanation:
```
L
```
Generate a list from the match results.
```
$
```
Use the following substitution to generate the list instead of the matches.
```
v`
```
Allow matches to overlap.
```
\[((\[)|(?<-2>])|[^]])*
```
This is an application of .NET's balancing groups. The `[` is matched literally, then as many characters as possible are consumed. As each subsequent `[` is matched, the match is added to the `$2` stack. If that stack isn't empty, we can then match a `]`, removing the match from the stack. Otherwise, we can match anything that's not a `]` (the `[` was already matched earlier). The match stops when it meets the matching `]` for the `[`, since the `$2` stack is (now) empty at that point.
```
$.`,$.>`
```
The substiution consists of two variables separated by a comma. The `.` indicates that the length of the variable, rather than its value, be used. The `>` indicates that the variable should be evaluated in terms of the right-hand separator rather than the match. The `$`` variable refers to the prefix of the match, which means `$.`` gives the position of the `[`; the `>` modifier alters this to the prefix of the match's right separator, which gives the position of the matching `]`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~22 21 20~~ 19 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
No doubt it is possible in Jelly in half this byte count :p ...
```
n€Ø[ḅ-µMịÄÐƤi€0ĖƊ’Ä
```
A monadic link accepting a list of characters which returns a list of lists of integers.
As a full program it accepts a string and prints a representation of said list.
**[Try it online!](https://tio.run/##y0rNyan8/z/vUdOawzOiH@5o1T201ffh7u7DLYcnHFuSCRQ2ODLtWNejhpmHW/7//68UDQKJxSmxicWxQDIlLTYtPS02GgiVAA "Jelly – Try It Online")**
### How?
```
n€Ø[ḅ-µMịÄÐƤi€0ĖƊ’Ä - Link: list of characters e.g. "[f[o]o!]"
Ø[ - list of characters = ['[', ']']
n€ - not equal? for €ach [[0,1],[1,1],[0,1],[1,1],[1,0],[1,1],[1,1],[1,0]]
- ...relating to the characters: [ f [ o ] o ! ]
ḅ- - convert from base -1 [1,0,1,0,-1,0,0,-1]
- ...i.e.: 1 where '['; -1 where ']'; and 0 elsewhere
µ - start a new monadic chain with that as the argument, say V
Ɗ - last 3 links as a monad (function of V):
ÐƤ - for post-fixes:
Ä - cumulative sum [[1,1,2,2,1,1,1,0],[0,1,1,0,0,0,-1],[1,1,0,0,0,-1],[0,-1,-1,-1,-2],[-1,-1,-1,-2],[0,0,-1],[0,-1],-1]
i€0 - 1st index of 0 in €ach (or 0) [8,1,3,1,0,1,1,0]
Ė - enumerate [[1,8],[2,1],[3,3],[4,1],[5,0],[6,1],[7,1],[8,0]]
M - maximal indices of V [1,3]
ị - index into [[1,8],[3,3]]
’ - decrement [[0,7],[2,2]]
Ä - cumulative sum (vectorises) [[0,7],[2,4]]
```
[Answer]
# SWI-Prolog 254 bytes
```
d([']'|T],I,[S|Z],M,R):-J is I+1,d(T,J,Z,[',','(',S,',',I,')'|M],R).
d(['['|T],I,S,M,R):-J is I+1,d(T,J,[I|S],M,R).
d([_|T],I,S,M,R):-J is I+1,d(T,J,S,M,R).
d(_,_,_,R,R).
m(X):-atom_chars(X,A),d(A,0,[],[']'],[_|R]),atomic_list_concat(['['|R],S),print(S).
```
Example:
```
?- m('!^45sdfd[hello world[[djfut]%%357]sr[jf]s][srtdg][]').
'[(49,50),(42,48),(8,41),(36,39),(20,33),(21,27)]'
true
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 87 bytes
```
f(char*Z){for(char*z=Z,*q=z;*z;*z++-93||printf("%d,%d;",*--q,z-1-Z))*z-91||(*q++=z-Z);}
```
[Try it online!](https://tio.run/##VU7BjoMgED1vv8KQmADCwbR7aI1fsTfpHIwUdGO1Ch5W7be7iG12HZjwmHnvzRRcF8WyKFyUeU8zMqm23/CYZox26ZjQ9UYRPx/n@dFXjVUYhZKFMkGMct6xkcc8I4SO/BzPM6ZdFKWjqyTPxd6M3eyM7cnk0Zft03te122BXbG@NetDopgk5mXvGAyFBrG1kbxnVs1jsMElCM21aQfrPpfgRfESxxyswejaIDf6cM@rBpPp8OF3QELkRioQIKzEgtifz5MOAyi1EAoGEEqI71KD0ErCSnRpQJcSVH86KnCWf06wHXgjFxhcEPKf5juwVwq/BuTG@YOborRfaUfaKzAQX3guvw "C (gcc) – Try It Online")
# Explanation
To keep track of opening bracket's string indices, the input string is overwritten and used as a stack.
```
f(char*Z){ // take mutable input string
for(char*z=Z,*q=z; // copy pointer to current string index, current stack index
*z; // loop through the entire string
*z++-93|| // if z == ']'
printf("%d,%d;", // decrement stack pointer,
*--q,z-1-Z)) // write bracket pair position
*z-91|| // if z == '['
(*q++=z-Z);} // write bracket position onto stack, increment stack pointer
```
[Try it online!](https://tio.run/##bZHdbqMwEIWvl6cYIaFiflRF7V60iKfYu7i@oGCDt8QmtlFb0j57djCkDdUOQjbjcw6fxnXe1vX5LOK6q0yyJyf4qttbcNULh8Poqueeg1TD6MA6I1UbgNBm8UzlPkuO5VTMhloP7zBoqRw34DTUozFcXVwY0fC37Kpb1S9LM4AEE34UBvZaD@A6o8e2w5UD@qThXxjJlKb5w93Hx8YlBUxQlnDDbgLsDKh1Ig6jJouaIsxmScNrww/fFCt0NushyfNjNuW7fE/IGgmvRjoOzwbF3MFQSYMeK53UCj3JlD/srik2GNRjxMkxTcsJQ4vPi@RH6hoIWuHwPFiG8/kv6dlx65YrwGGQk9/9caY8VH2v6xibPVfzQtIdKew6BFRkYWTDbD4oLpNZ7vYRIvuk9Ojw4xFWibegcnQ2Dp9UiPDBoZIqJqfgl2cIKa1sIxhl1DUxJe79930bAetaSgUbGRWU/u1aRlvRsFmIr2Vt1zBh7u8Ew8jvJLY87LLDihkWIdcyf8K2TuoxWGUxn@FfROuRNqKtI2bENz7P/wA "C (gcc) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 20 bytes
```
=©ⱮØ[_/aÄ$+®ŻĠḊẎ_2s2
```
[Try it online!](https://tio.run/##y0rNyan8/9/20MpHG9cdnhEdr594uEVF@9C6o7uPLHi4o@vhrr54o2Kj/4fbj056uHPG///q0dGJxSlpsdGx0SUpGtGaJZWmJumqCrEZ6dHRabGlsdFp0dFZGemx0elpKbEghUBcHJuekRKbVmRinBarDgA "Jelly – Try It Online")
It has a side-effect on the register, hope it's allowed to be a function.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v1.4.5, 23 bytes
```
;Ë¥']?ApENo):D¥'[©NpE
A
```
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=O8ulJ10/QXBFTm8pOkSlJ1upTnBFCkE=&input=LVEKIltbYXNkZl1bXVt0ZChbKXR5NTRnJSBdaGdbW2ZddV1bZltbamhnXVtnZmRdc2RmXXNkZnNdZ2hkXWZyNDNmXSI=)
### Unpacked & How it works
```
;UmDE{D==']?ApENo):D=='[&&NpE
A
; Use alternative set of initial variables
A = [] is used here
UmDE{ Map over each char of input string...
D==']? If the char is closing bracket...
ApENo) Push the current index and N.pop() to A
:D=='[&& Otherwise, if the char is opening bracket...
NpE Push the current index to N
A Output A
```
The output is a flattened array of `[closing index, opening index]`. If the reversed order is not desired, adding `w` at the end does the job (+1 bytes).
[Answer]
## Common Lisp, 95 bytes
```
(lambda(u &aux s)(dotimes(p(length u))(case(elt u p)(#\[(push p s))(#\](print`(,(pop s),p))))))
```
Long version
```
(defun par (string &aux stack)
(dotimes (pos (length string))
(case (char string pos)
(#\[ (push pos stack))
(#\] (print (list (pop stack) pos))))))
```
Tests
```
((lambda(u &aux s)(dotimes(p(length u))(case(elt u p)(#\[(push p s))(#\](print`(,(pop s),p))))))
"!^45sdfd[hello world[[djfut]%%357]sr[jf]s][srtdg][] ")
```
prints:
```
(21 27)
(20 33)
(36 39)
(8 41)
(42 48)
(49 50)
```
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), ~~38~~ 37 bytes
```
{b@0N 2#,/=(|':+\-/a)b:&|/a:"[]"=\:x}
```
[Try it online!](https://tio.run/##NZDrbsIwDIX/7yms7tZqIBonvXpIe4K9gLFEEUrZmEAqTCoC9uqd20KiKJHlc77jbKe7etd1vjyvPuJPwMfJbB5eXsu3xXRWRavy5TKryoAlmC/K9tod9s2xPLcf7@31QR9P3Bf4JH/9DU3poaXlfkvh0ldfP9TSiZpItJcD5uqw9sLCx3XI0fGUuPoZZFMze/kV9szfm1q49mvpG/UcpN6sxTfOegkojCFFMpBSBjkVkKRkLCASJmBjwhQwJ2sgQbIWXEbWgdVKAc5GMkaQccv9pSuUfkXRACjUX@XgKLlxTAyoIAMGe5xxZBIwWskAEzI5oFYKQEuonXgDDd4yhjaEYMlB1nveg/DwHVIddE7RaX09fM2oQKMxTKY6xSnTqDonxIHilHunBDRR/5tlKNEo11igE3f/ "K (ngn/k) – Try It Online")
`{` `}` function with argument `x`
`"[]"=\:x` two boolean lists for the occurrences of `"["` and `"]"`
`a:` assign to `a`
`|/` boolean "or" of the two lists
`&` where (at which indices) are the brackets?
`b:` assign to `b`
`-/` a list with 1 for `"["`, -1 for `"]"`, and 0 everywhere else
`+\` partial sums
`|':` pairwise maxima (each element max'ed with the previous one, the initial element remains the same)
This represents bracket depth for each character.
We index it with `b` (juxtaposition is indexing) and get bracket depth only for the brackets.
`=` "group by" - a dictionary mapping depths to the indices at which they occur
`,/` concatenate the values in the dictionary, ignoring the keys
`0N 2#` reshape to a 2-column matrix (list of lists)
`b@` index `b` with each element of the matrix
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes
```
FLθ≡§θι[⊞υι]«I⊟υ,Iι⸿
```
[Try it online!](https://tio.run/##VcpPC4IwHMbxs76KJQg/wU4lQZ2iU9DB@1ow9scpw@U2Mwhf@1IpqOPzeb5MUcsM1SFIYxFcRFt5BV2WITfUnikER39uuXhCl6N64lccMeoESnCyR2XvFPTzcfgymXhqotLWrYcTdR5Kc4c@y@bmw0me/Kwlqv/@q12CMR5DWN22heOSYyW0NmgwVnOMeSN7T9J0U@yIs7iRxBHsrOcVwSQO64d@Aw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
FLθ
```
Loop over the implicit range of the length of the input string.
```
≡§θι
```
Switch on the current character.
```
[⊞υι
```
If it's a `[` then push the current index to the predefined array variable.
```
]«I⊟υ,Iι⸿
```
If it's a `]` then pop the latest index from the array variable and print it and the current index separated by a comma and start a new line. Alternate output formats, if acceptable, would save some bytes: `]I⟦⊟υιω` saves 2 bytes but prints each index on a separate line, double-spacing the pairs of indexes; `]I⟦⊟υι` simply prints the indexes on separate lines, making it hard to distinguish them.
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 25 bytes
```
0q{"[]"#"_ \p_p "S/=~)}/;
```
Surprisingly competitive - loses only to Japt and Jelly [**Edit**: and Charcoal and Stax :(]
[Try it online!](https://tio.run/##Fco7CoQwFAXQrYQMgqkURitxFVNeLyKG90JA8DfFILr1OBanO2McppTK5bCgfdnedHM/G/sp2sudRZMSMGxeCGL3Odz@qyvNDIMCwi8hQAxKqHg@8W@jBk9Zq7fwBg "CJam – Try It Online")
## Explanation
```
0 Push 0.
q Push the input.
{ }/ For each character in the input:
"[]"# Find index of this character in the string "[]" (or -1 if not found).
= Use this index to choose
" "S/ one of the following snippets
~ and execute it:
_ If it was 0 ('['), duplicate the number on the stack.
\p_p If it was 1 (']'), print the current number and the one under it.
If it was -1, do nothing.
) Increment the number on top of the stack.
; Delete the number.
```
[Answer]
# [Python 2](https://docs.python.org/2/), 109 bytes
```
def a(s,r=[],i=0):
o=[]
while i<len(s):exec["r+=[i]","o+=[(r.pop(),i)]",'']['[]'.find(s[i])];i+=1
return o
```
[Try it online!](https://tio.run/##NY3NasQwDITvfgoRCLbYEPqzvaTNk2h1CHWceEltI3tp9@lTp0tHCGaGDybdyxrDy77b2cFkcicjcefHJxwUxOoVfK9@m8F/bHMwGYf5Z/6kRk4jeW66JlZjpE8xGew81kprJk2se@eDNbliyO/@ND4rkLncJEDc/VeKUiDfs3JRYPOhLoQj97lYH4YkPpRmMq0gjJcA0ErTmoOrgPhk9CVo7Ka/CnEnmrJ1TEzFGsJyfzsvLfC6EDm@MTmi67owLc7yAdbPvKyWnZxfHSsifhz/uyrDVYjqkZl/AQ "Python 2 – Try It Online")
[Answer]
# [Pyth](https://pyth.readthedocs.io), ~~28~~ 26 bytes
```
{I#.e,t+lhfSI/LT`Y+._>Qk\]
```
[Test suite.](https://pyth.herokuapp.com/?code=%7BI%23.e%2Ct%2BlhfSI%2FLT%60Y%2B._%3EQk%5C%5D&input=%22%21%5E45sdfd%5Bhello+world%5B%5Bdjfut%5D%25%25357%5Dsr%5Bjf%5Ds%5D%5Bsrtdg%5D%5B%5D%22&test_suite=1&test_suite_input=%22%5B%5Basdf%5D%5B%5D%5Btd%28%5B%29ty54g%25+%5Dhg%5B%5Bf%5Du%5D%5Bf%5B%5Bjhg%5D%5Bgfd%5Dsdf%5Dsdfs%5Dghd%5Dfr43f%5D%22%0A%22%5B%5B%5D%5B%5D%5B%5D%5B%5D%5D%5B%5B%5D%5B%5D%5B%5D%5B%5B%5B%5B%28%5D%5D%5D%5D%29%29%22%0A%22%5B%5D%5B%5D%5B%5B%5D%5D%22%0A%22%5B%5B%5B%5B%5Basd%5Das%5Dsd%5Ddf%5Dfgf%5D%5B%5D%5B%5D%22%0A%22%5B%5D%22%0A%22%5B%5B%28%5D%29%5D%22&debug=0)
~~At the moment it's longer than Mnemonic's approach~~, but I feel like I can golf this down a little and this fortunately also doesn't use Pythonically-imperative structures like `V`. The initial version was 36 bytes and also had numerous bugs.
### How it works
```
{I#.e,t+lhfSI/LT`Y+._>Qk\] – Full program. Takes a quoted string Q from STDIN.
.e – Enumerated map. k = iteration index, b = current element.
>Qk – Get the elements of Q at indices greater than k.
._ – Generates all the prefixes of this.
+ \] – And append an "]" (for handling some edge-cases).
f – Filter over this list, with T = current element.
L `Y – For each character in str([]), "[]"...
/ T – ... Count the occurrences of it in T.
SI – And check if the values are sorted increasingly.
h – Head. Retrieve the first element.
+l – Get the length of this + k.
t – Decrement (by 1).
, – And pair this value with k. Returns [i, k] where i is
the index of the corresponding ] and k is that of [.
# – Filter this list by:
{I – The pair is invariant over deduplicating.
```
[Answer]
# Perl 5, 53 bytes
```
say"$-[0] ".($+[0]-1)while s/\[[^][]*\]/1x length$&/e
```
Run as `perl -nE '<above code snippet>'`. Takes input through stdin.
As usual, the optimal Perl solution to the problem is a regular expression. We attempt to match any pair of brackets which does not contain any pairs within it using a rather silly-looking character class (`s/\[[^][]*\]/.../`). If the match is successful, we replace the matched text with the digit `1` over and over again so that we don't accidentally match those brackets again, and we print out the indices of the match. Rinse and repeat.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 13 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
é√p(l▓1½\á²ë(
```
[Run and debug it](https://staxlang.xyz/#p=82fb70286cb231ab5ca0fd8928&i=%22[[asdf][][td%28[%29ty54g%25+]hg[[f]u][f[[jhg][gfd]sdf]sdfs]ghd]fr43f]%22%0A%22[[][][][]][[][][][[[[%28]]]]]%29%29%22%0A%22[][][[]]%22%0A%22[[[[[asd]as]sd]df]fgf][][]%22%0A%22[]%22%0A%22[[%28]%29]%22&a=1&m=2)
It uses the input stack to track open brace pairs. Here's the program unpacked, ungolfed, and commented.
```
F iterate over input characters
.][I get the index of the character in the string "[]", or -1
^|cv skip the rest of this iteration if index was -1
i~ push the current iteration index to the input stack
C skip the rest of this iteration if index was 0
\ form a pair with the top two items from the input stack
JP join with space, and print
```
[Run this one](https://staxlang.xyz/#p=82fb70286cb231ab5ca0fd8928&i=%22[[asdf][][td%28[%29ty54g%25+]hg[[f]u][f[[jhg][gfd]sdf]sdfs]ghd]fr43f]%22%0A%22[[][][][]][[][][][[[[%28]]]]]%29%29%22%0A%22[][][[]]%22%0A%22[[[[[asd]as]sd]df]fgf][][]%22%0A%22[]%22%0A%22[[%28]%29]%22&a=1&m=2)
] |
[Question]
[
# Divinacci ([OEIS](https://oeis.org/A000458))
**Perform the Fibonacci sequence but instead of using:**
```
f(n) = f(n-1)+f(n-2)
```
**Use:**
```
f(n) = sum(divisors(f(n-1))) + sum(divisors(f(n-2)))
```
For an input of `n`, output the nth term, your program should only have 1 input.
---
**First 14 terms (0-indexed, you may 1-index; state which you used):**
```
0 | 0 # Initial | []
1 | 1 # Initial | [1] => 1
2 | 1 # [] + [1] | [1] => 1
3 | 2 # [1] + [1] | [1,2] => 3
4 | 4 # [1] + [1,2] | [1,2,4] => 7
5 | 10 # [1,2] + [1,2,4] | [1,2,5,10] => 18
6 | 25 # [1,2,4] + [1,2,5,10] | [1,5,25] => 31
7 | 49 # [1,2,5,10] + [1,5,25] | [1,7,49] => 57
8 | 88 # [1,5,25] + [1,7,49] | [1, 2, 4, 8, 11, 22, 44, 88] => 180
9 | 237 # [1,7,49] + [180] | [1, 3, 79, 237] => 320
10 | 500 # [180] + [320] | [1, 2, 4, 5, 10, 20, 25, 50, 100, 125, 250, 500] => 1092
11 | 1412 # [320] + [1092] | [1, 2, 4, 353, 706, 1412] => 2478
12 | 3570 # [1092] + [2478] | [1, 2, 3, 5, 6, 7, 10, 14, 15, 17, 21, 30, 34, 35, 42, 51, 70, 85, 102, 105, 119, 170, 210, 238, 255, 357, 510, 595, 714, 1190, 1785, 3570] => 10368
13 | 12846 # [2478] + [10368] | [1, 2, 3, 6, 2141, 4282, 6423, 12846] => 25704
Etc...
```
*You may choose whether or not to include the leading 0. For those who do: the divisors of `0` are `[]` for the purpose of this challenge.*
It's [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") lowest byte-count wins...
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
```
XÎFDŠ‚ÑOO
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/4nCfm8vRBY8aZh2e6O///7@hMQA "05AB1E – Try It Online")
**Explanation**
```
XÎ # initialize stack with 1,0,input
F # input times do
D # duplicate
Š # move down 2 places on the stack
‚ # pair the top 2 elements on the stack
Ñ # compute divisors of each
OO # sum twice
```
[Answer]
## Mathematica, ~~45~~ 40 bytes
```
If[#<3,1,Tr@Divisors@#0[#-i]~Sum~{i,2}]&
```
Mathematica's divisor related functions `Divisors`, `DivisorSum` and `DivisorSigma` are all undefined for **n = 0** (rightly so), so we start from `f(1) = f(2) = 1` and don't support input `0`.
Defining it as an operator instead of using an unnamed function seems to be two bytes longer:
```
±1=±2=1
±n_:=Sum[Tr@Divisors@±(n-i),{i,2}]
```
[Answer]
# [Perl 6](http://perl6.org/), 58 bytes
```
{my&d={sum grep $_%%*,1..$_};(0,1,{d($^a)+d $^b}...*)[$_]}
```
[Try it online!](https://tio.run/##BcFBCoAgEADAr@xhEy1Z8tJFekmkGGaXJDE6iPh2m0lnvpceC7AAa6@xML/W94tw5TMB2mEYpSJC2zSfpZLVczROTB7QHI2IRrGh3VvXEDhaQa8rEJ4MRs39Bw "Perl 6 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 55 bytes
```
f n=sum[a|n>1,k<-f<$>[n-1,n-2],a<-[1..k],mod k a<1]+0^n
```
[Try it online!](https://tio.run/##FcpNCoAgEAbQq3wLd6k0QTvrImIwUFKYk/Sz6@5Gb/1WvtKy77VGyHA92fMrI@nkTHRq9GJIi@mCZmc8WZuCzseMBHYUmnaSmnkTDCjnJjcUMhdE/JX6UD8 "Haskell – Try It Online")
One-indexed.
[Answer]
# [Python 2](https://docs.python.org/2/), 76 bytes
```
f=lambda n:sum(a for k in[1,2][:n]for a in range(1,3**n-8)if f(n-k)%a<1)or n
```
[Try it online!](https://tio.run/##JcpBCoMwEAXQq8xGyEgEo1CK1JOIiyk6Nth8Q7SLnj61uH28@D1eG5qctX9LeE5C6PZPMEK6JVrJY3C2GYcO4x/kBEqCZTbOtmWJ6s5eSQ2qlQt5OD4TckweBwWJRu21a3tjzj8 "Python 2 – Try It Online")
Ridiculously slow.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 9 bytes
```
ð,ÆDẎSð¡1
```
[Try it online!](https://tio.run/##y0rNyan8///wBp3DbS4Pd/UFH95waKHh//@mAA "Jelly – Try It Online")
Thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis) for -1.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~88~~ ~~83~~ 81 bytes
```
f=lambda n:+(n<3)or g(f(n-1))+g(f(n-2))
g=lambda n,i=1:n>=i and(n%i<1)*i+g(n,i+1)
```
[Try it online!](https://tio.run/##PYyxCsJAEAV7v2IbYZ8XizVdyOVHxOIk3rmgL@FI49efAcFuYIZZP9tzYd9ajq/0vs9JOATl2GOpUjQrzwaEH12AQ/l3nUcbOEWXxFl59NFw8j3dTTC0tTo3vWZ1SN5vLk6pieWh1pnhhvYF "Python 3 – Try It Online")
Excludes the `0`
[Answer]
# MATL, ~~16~~ 15 bytes
```
Oliq:",yZ\s]+]&
```
This solution uses 0-based indexing.
Try it at [MATL Online](https://matl.io/?code=Oliq%3A%22%2CyZ%5Cs%5D%2B%5D%26&inputs=9&version=20.1.1)
**Explanation**
```
O % Push the number literal 0 to the stack
l % Push the number literal 1 to the stack
i % Explicitly grab the input (n)
q % Subtract 1
: % Create the array [1...(n - 1)]
" % For each element in this array...
, % Do the following twice
y % Copy the stack element that is 1-deep
Z\ % Compute the divisors
s % Sum the divisors
] % End of do-twice loop
+ % Add these two numbers together
] % End of for loop
& % Display the top stack element
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~64~~ 60 bytes
```
d n=sum[a|a<-[1..n],mod n a<1]
f=0:scanl((.d).(+).d)1f
(!!)f
```
[Try it online!](https://tio.run/##DcixCoAgEADQva@4oEGpjqQt8kvE4cikSK/Q2vp3a3rwNsrHGkIpDljnJxp6ae6NQmTbxfNfoFnZyuthygtxEAKdRNHKH@WrpEVdS18i7QwarrTzDQ1EuiCBGRDVaMsH "Haskell – Try It Online")
[Answer]
# [PHP](https://php.net/), 97 bytes
```
for($f=[0,$y=1];++$i<$argn;$x=$y,$y=$r)for($f[]=$r=$v=$n=$x+$y;--$v;)$n%$v?:$r+=$v;echo$f[$argn];
```
[Try it online!](https://tio.run/##JYw9C8IwFEX3/oxyhYZYUNx8fXSQDi66uJVQRNKPJQkPKe3iX4@xbpdzDjeMIVZ1GENmRbx0YoOX9@SG4tN0t/vjemkUZXjK4Dg/5RR7LwV6bg97rHw0pDWmavOEhbH@MET9s9akzZgZjrForFSWmEnB7TDXZ4hOkuxr9KndTgzF@AU "PHP – Try It Online")
# [PHP](https://php.net/), 101 bytes
```
for($f=$d=[0,1];$i<$argn;$d[]=$r)for($f[]=$r=$v=$n=$d[$i]+$d[++$i];--$v;)$n%$v?:$r+=$v;echo$f[$argn];
```
[Try it online!](https://tio.run/##JYw9C8IwFEX3/oxyhZZYsLj5@uggHVx0cSuhiP1IliQ8JKN/PYY63QP33BtMSF0fTCgWES@TLMHLx7qt@g7T/fG8XYeaCrxkc1y255LS6qXCyph5PB1bTbDdXhPmUTOk/gs7MyLDZXeE1SqHUhmoaRCphjsg9heIyhotb@Pzar/SlNIP "PHP – Try It Online")
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 39 bytes
```
f(n)=if(n<3,1,sum(i=1,2,sigma(f(n-i))))
```
Based on [Martin Ender's Mathematica answer](https://codegolf.stackexchange.com/a/128040/9288).
[Try it online!](https://tio.run/##FYyxDcAgDARXsVIZyS4MbcguNCAXEAuS@YnzxRWn01uZys32rjhCVueZSGi9HTULRVraekH3rMG36z1xQAYhkERgU8fj4gC@HP@LRx8 "Pari/GP – Try It Online")
[Answer]
# R, 81 bytes
```
f=function(n,a=1,b=1,d=numbers::divisors)`if`(n-1,f(n-1,b,sum(d(a))+sum(d(b))),a)
```
1-indexed, and excludes the 0 at the start of the sequence. That zero gave me a lot of trouble to implement, because the builtin `numbers::divisors` doesnt handle it well.
The rest is a modified version of the standard recursive function that implements the fibonacci sequence.
```
> f(1)
[1] 1
> f(2)
[1] 1
> f(3)
[1] 2
> f(5)
[1] 10
> f(13)
[1] 12846
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes
```
1{~"vKf∑…
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIxe35cInZLZuKIkeKApiIsIiIsIiJd)
Prints the sequence forever.
```
1 # Push 1
{ # Forever...
~" # Grab top two elements, without popping
vK # Get divisors of each
f∑ # Deep sum
… # Print that without popping
```
[Answer]
# [Julia](https://julialang.org), ~~47~~ 44 bytes
```
~n=(n.%(r=1:n).<1)'r
!N=N<3||~!(N-1)+~!(N-2)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700qzQnM3HBgqWlJWm6Fjd16vJsNfL0VDWKbA2t8jT1bAw11Yu4FP1s_WyMa2rqFDX8dA01tcG0kSZEz6aCosy8kpw8PQ09RQ1DK0NjTagEzFAA)
-3 bytes thanks to [Czylabson Asa](https://codegolf.stackexchange.com/users/90445/czylabson-asa). (I forgot [how `a'*b` worked](https://ato.pxeger.com/run?1=m700qzQnM3HBgqWlJWm6FjdVghRsFQytTLkcijPyyxWC1LWCoEwNAwU9baCAplYQRC1UC0wrAA))
[Answer]
# [Husk](https://github.com/barbuz/Husk), 11 bytes
```
!¡ȯΣṁḊ↑_2ŀ2
```
[Try it online!](https://tio.run/##ASAA3/9odXNr//8hwqHIr86j4bmB4biK4oaRXzLFgDL///8xMw "Husk – Try It Online")
## Explanation
```
!¡ȯΣṁḊ↑_2ŀ2
ŀ2 array [0,1]
¡ iterate on the array, expanding it:
ȯ using the following 4 functions:
↑_2 get last 2 elements
ṁḊ get divisors of both
Σ sum them
! Get element at index n
```
[Answer]
# [Factor](https://factorcode.org/) + `math.primes.factors math.unicode`, 53 bytes
```
[ 0 1 rot [ tuck [ divisors Σ ] bi@ + ] times drop ]
```
[Try it online!](https://tio.run/##JYy9CsIwGEX3PsXdhaCb1MVNXFzEqXSI@aGhaRK@fBF8Ht/HV4qpnQ5czrlWKo5UH/fr7dJjNhSMR56Ktd5gkTyJRG4xWdi/mLetBKei3gQkMszvpgXGqeuOdcAeB1BkDOCi5gbtXi6v@feDEU93xq6R12doigljVdJ7iPoD "Factor – Try It Online")
0-indexed.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 93 87 86 bytes
```
f(n){return n<2?n:s(f(n-1))+s(f(n-2));}s(n,c,i){for(c=i=0;n/++i;)c+=n%i?0:i;return c;}
```
[Try it online!](https://tio.run/##LY7NDoIwEITvfYoNhqQbihaPlMqLeDEt6Ca6GH5OhGfHBZnLTiZfZifkzxDWtdWMc9@MU8/A1bXmctCS5QVi9ndXRLcMmk0whHPb9Tp48tbxJcvIYcg8p1TbktxRE9yynojDe4oNVMMYqTu/bop4hM@DWKOaFYikCvSWEniwTk7loRAjvbgTm769IK1O0lhCGu@cGCADrSaZpXbqeGudWtYf "C (gcc) – Try It Online")
A simple recursive solution that finds divisors by brute force.
Thanks to @ceilingcat for -6 bytes on the for loop and -1 on some superfluous parens.
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 23 bytes
```
0 1 2{fc++jfc++.+}C~j!!
```
[Try it online!](https://tio.run/##SyotykktLixN/V@U@d9AwVDBqDotWVs7C0Toadc612UpKv7/b2gMAA "Burlesque – Try It Online")
```
0 1 # Initial
2 # Keep top 2 stack elements
{
fc++ # Factors, Sum
j # Swap stack
fc++ # Factors, Sum
.+ # Sum
}C~ # Continue forever
j!! # Get input element
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
1λè‚јO
```
Outputs the 1-based \$n^{th}\$ value.
[Try it online.](https://tio.run/##yy9OTMpM/f/f8NzuwyseNcw6PPH0HH8g1wAA)
With some small modifications, we could output:
* **7 bytes:** The first 1-based \$n\$ values by replacing `è` with `£`: [try it online](https://tio.run/##yy9OTMpM/f/f8NzuQ4sfNcw6PPH0HH8g1xgA).
* **5 bytes:** The infinite 1-based sequence by removing the `1` and `è`: [try it online](https://tio.run/##yy9OTMpM/f//3O5HDbMOTzw9x///fwA).
* Or with 0-based sequence by adding `Ý` after the `1`:
+ **8 bytes:** 0-based \$n^{th}\$: [try it online](https://tio.run/##yy9OTMpM/f/f8PDcc7sPr3jUMOvwxNNz/IEChgA).
+ **8 bytes:** 0-based first \$n\$ values: [try it online](https://tio.run/##yy9OTMpM/f/f8PDcc7sPLX7UMOvwxNNz/IECJgA).
+ **7 bytes:** 0-based infinite sequence: [try it online](https://tio.run/##yy9OTMpM/f/f8PDcc7sfNcw6PPH0HP///wE).
So with [default sequence rules](https://codegolf.stackexchange.com/tags/sequence/info), this could have been 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage).
**Explanation:**
```
λ # Start a recursive environment,
è # to output the a(input)'th value
# (which is output implicitly at the end)
1 # Starting at a(0)=1
# And where every following a(n) is calculated as:
‚ # Pair the (implicit) previous two terms together: [a(n-2),a(n-1)]
# (a(n-2) is unknown in the first iteration, so will default to 0)
Ñ # Get the divisors of both inner values
˜ # Flatten this list of lists of integers
O # Sum them together
```
**Explanation of the 5-bytes infinite 1-based sequence:**
```
λ # Start a recursive environment,
# to output the infinite sequence
# (which is output implicitly at the end)
# Implicitly starting at a(0)=1
# And where every following a(n) is calculated as:
‚јO # See above
```
[Answer]
# [Scala](https://www.scala-lang.org/), 123 bytes
Golfed version. [Attempt it online!](https://Scala%203,%20123%20bytes:%20%5B%60def%20f(n:Int):Int=if(n%3C3)1%20else%7Bdef%20g(n:Int,i:Int=1):Int=if(n%3E=i)if(n%25i%3C1)i+g(n,i+1)else%20g(n,i+1)else%200;g(f(n-1))+g(f(n-2))%7D%60%5D(https://ato.pxeger.com/run?1=VY7BDsFAEIbvnmIukp0UsVykVOIo4SRO4rBq24zUlu6QCJ7EpQ68k7exbYm47L___38zu7enDVWiuvnrkq42OmSYKjJwrgGsdQRbZ4TKYuvDKMvUaTHjjEy8RB_mhhiCkgQ4qgSs3h-0CbULhQROQbaxtVU7EWGL0wlZLtGdW8CJEV8cXXp9HDhq9l7n4s1IGH9sGIsjIOcGXZSgE6vLOq7qBpW9_GHDgLDQOg0kkue4BnkSi0H4M-1-LBzXlIhedesgfr5w_2ieV_oG))
```
def f(n:Int):Int=if(n<3)1 else{def g(n:Int,i:Int=1):Int=if(n>=i)if(n%i<1)i+g(n,i+1)else g(n,i+1)else 0;g(f(n-1))+g(f(n-2))}
```
Ungolfed version. [Attempt it online!](https://Scala%203,%20342%20bytes:%20%5B%60object%20Main%20%7B%20%20%20def%20main(args:%20Array%5BString%5D):%20Unit%20=%20%7B%20%20%20%20%20val%20sequence%20=%20(1%20to%2010).map(f).toList%20%20%20%20%20println(sequence)%20%20%20%7D%20%20%20%20def%20f(n:%20Int):%20Int%20=%20%7B%20%20%20%20%20if%20(n%20%3C%203)%201%20%20%20%20%20else%20g(f(n%20-%201))%20+%20g(f(n%20-%202))%20%20%20%7D%20%20%20%20def%20g(n:%20Int,%20i:%20Int%20=%201):%20Int%20=%20%7B%20%20%20%20%20if%20(n%20%3E=%20i)%20%7B%20%20%20%20%20%20%20if%20(n%20%25%20i%20%3C%201)%20i%20+%20g(n,%20i%20+%201)%20%20%20%20%20%20%20else%20g(n,%20i%20+%201)%20%20%20%20%20%7D%20else%200%20%20%20%7D%20%7D%20%60%5D(https://ato.pxeger.com/run?1=bZBBSwMxEIXxur_iXYQMtqWxF1lawaNgT6IX8RDXZEnZztbNtCCyv8RLL_qj_DXGNFsoeMlkPh7vDe_zO1SmMbP9_msrbnz1c_bYvqxsJVgaz_gogFfrsI6LMl0dStx0nXl_upfOc_1MJR7YCxZJCexMg2DftpYrG6HSkBZ6SpO12ShHE2nvfJAk3UQDaVgNcoq0L3KeU1ziloXSe7T3Dooxx4ygE7BNsKhVlGMMTYSL43ZJJ451dhzBD576X_frBTxlMrBz-JiqKY6_AB6lj6Ysylec4v6Ap-mIvjjUm1se2v4F))
```
object Main {
def main(args: Array[String]): Unit = {
val sequence = (1 to 10).map(f).toList
println(sequence)
}
def f(n: Int): Int = {
if (n < 3) 1
else g(f(n - 1)) + g(f(n - 2))
}
def g(n: Int, i: Int = 1): Int = {
if (n >= i) {
if (n % i < 1) i + g(n, i + 1)
else g(n, i + 1)
} else 0
}
}
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Starts with `0` and outputs the `n`th term, zero-indexed. Replace `g` with `h` to output the first `n` terms instead.
```
@Zo2 câ x}g
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QFpvMiBj4iB4fWc&input=MTM)
] |
[Question]
[
# Prime Wednesdays
Your task is to count the number of Wednesdays that fall on a prime day of the month in a particular year. For instance, `7-13-16` is a prime Wednesday. For consistency use the [Gregorian calendar](https://en.wikipedia.org/wiki/Gregorian_calendar) for all dates.
## Input
The input to your program/function will be a year (eg `2016`) and is flexible. The year will be an integer between [**1912**](https://en.wikipedia.org/wiki/Sliced_bread) and [**2233**](https://en.wikipedia.org/wiki/James_T._Kirk) inclusive.
## Output
The output is also flexible and should be the number of prime Wednesdays (eg `18`).
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in bytes wins!
## Test Cases
>
> input -> output
>
> --------------------
>
> [1912](https://en.wikipedia.org/wiki/Sliced_bread) -> 19
>
> [1914](https://en.wikipedia.org/wiki/World_War_I) -> 16
>
> [1984](https://en.wikipedia.org/wiki/Nineteen_Eighty-Four) -> 17
>
> [1996](https://en.wikipedia.org/wiki/Deep_Blue_(chess_computer)) -> 19
>
> [2063](https://en.wikipedia.org/wiki/Star_Trek:_First_Contact) -> 19
>
> [2150](https://en.wikipedia.org/wiki/The_Dalek_Invasion_of_Earth) -> 16
>
> [2199](https://en.wikipedia.org/wiki/The_Matrix) -> 18
>
> [2233](https://en.wikipedia.org/wiki/James_T._Kirk) -> 18
>
>
>
>
[Answer]
# Python 2, ~~95~~ ~~93~~ ~~68~~ 67 bytes
```
lambda y:0x10ea2c8dbb06c5619/5**((y+((y-22)/99-y/2002)*16)%28)%5+16
```
*Thanks to @Josay for golfing off 1 byte!*
Test it on [Ideone](http://ideone.com/tLlqp0).
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~6588~~, ~~2310~~, ~~2308~~, 2290 bytes
First things first, I did not write nearly 100% of this program, which is probably evidenced by the enormous size of the program. Most of this code was written by [my own Brain-Flak golfing algorithm](https://github.com/Wheatwizard/Brain-Flak-Tools). Along with an additional python script I wrote to prompt it in the right direction.
[Try it online!](http://brain-flak.tryitonline.net/#code=KHt9PCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKSgpKCkpKXt9e30pe30pWygpKCldKSgpKSgpKCkpWygpKCkoKSgpXSkoKSkoKSgpKCkpWygpKCkoKV0pKCkoKSlbKCkoKSgpXSkoKSgpKVsoKV0pKSgpKSgpKCkpWygpKCkoKSgpXSkoKSkoKSgpKCkpWygpKCkoKV0pKCkpKCkpWygpXSlbKCldKSgpKCkoKSlbKCkoKV0pKCkoKSlbKCkoKSgpKCldKSgpKCkpKCkpWygpKCldKSgpKSgpKCkpWygpKCkoKSgpXSkoKSgpKVsoKV0pKCkoKSgpKVsoKSgpXSkoKSgpKVsoKSgpKCkoKV0pKCkoKSkoKSlbKCkoKV0pKCkpKCkoKSlbKCkoKSgpKCldKSgpKSgpKCkoKSlbKCkoKSgpXSkoKSgpKVsoKSgpKCldKSgpKCkpWygpXSkpKCkpKCkoKSlbKCkoKSgpKCldKSgpKSgpKCkoKSlbKCkoKSgpXSkoKSkoKSlbKCldKVsoKV0pKCkoKSgpKVsoKSgpXSkoKSgpKVsoKSgpKCkoKV0pKCkoKSkoKSlbKCkoKV0pKCkpKCkoKSlbKCkoKSgpKCldKSgpKSgpKCkoKSlbKCkoKSgpXSkoKSgpKVsoKSgpKCldKSgpKCkpWygpXSkpKCkpKCkoKSlbKCkoKSgpKCldKSgpKSgpKCkoKSlbKCkoKSgpXSkoKSkoKSlbKCldKVsoKV0pKCkoKSgpKVsoKSgpXSkoKSgpKVsoKSgpKCkoKV0pKCkoKSkoKSlbKCkoKV0pKCkpKCkoKSlbKCkoKSgpKCldKSgpKSgpKCkoKSlbKCkoKSgpXSkoKSgpKVsoKSgpKCldKSgpKCkpWygpXSkpKCkpKCkoKSlbKCkoKSgpKCldKSgpKSgpKCkoKSlbKCkoKSgpXSkoKSkoKSlbKCldKVsoKV0pKCkoKSgpKVsoKSgpXSkoKSgpKVsoKSgpKCkoKV0pKCkoKSkoKSlbKCkoKV0pKCkpKCkoKSlbKCkoKSgpKCldKSgpKSgpKCkoKSlbKCkoKSgpXSkoKSkoKSgpKVsoKSgpKCkoKV0pKCkoKSkoKSlbKCkoKV0pKCkpKCkoKSlbKCkoKSgpKCldKSgpKSgpKCkoKSlbKCkoKSgpXSkoKSgpKVsoKSgpKCldKSgpKCkpWygpXSkpKCkpKCkoKSlbKCkoKSgpKCldKSgpKSgpKCkoKSlbKCkoKSgpXSkoKSkoKSlbKCldKVsoKV0pKCkoKSgpKVsoKSgpXSkoKSgpKVsoKSgpKCkoKV0pKCkoKSkoKSlbKCkoKV0pKCkpKCkoKSlbKCkoKSgpKCldKSgpKSgpKCkoKSlbKCkoKSgpXSkoKSgpKVsoKSgpKCldKSgpKCkpWygpXSkpKCkpKCkoKSlbKCkoKSgpKCldKSgpKSgpKCkoKSlbKCkoKSgpXSkoKSkoKSlbKCldKVsoKV0pKCkoKSgpKVsoKSgpXSkoKSgpKVsoKSgpKCkoKV0pKCkoKSkoKSlbKCkoKV0pKCkpKCkoKSlbKCkoKSgpKCldKSgpKSgpKCkoKSlbKCkoKSgpXSkoKSgpKVsoKSgpKCldKSgpKCkpWygpXSkpKCkpKCkoKSlbKCkoKSgpKCldKSgpKSgpKCkoKSlbKCkoKSgpXSkoKSkoKSlbKCldKVsoKV0pKCkoKSgpKVsoKSgpXSkoKSgpKVsoKSgpKCkoKV0pKCkoKSkoKSlbKCkoKV0pKCkpKCkoKSlbKCkoKSgpKCldKSgpKSgpKCkoKSlbKCkoKSgpXSkoKSgpKVsoKSgpKCldKSgpKCkpWygpXSkpKCkpKCkoKSlbKCkoKSgpKCldKSgpKSgpKCkoKSlbKCkoKSgpXSkoKSkoKSlbKCldKVsoKV0pKCkoKSgpKVsoKSgpXSkoKSgpKVsoKSgpKCkoKV0pKCkoKSkoKSlbKCkoKV0pKCkpKCkoKSlbKCkoKSgpKCldKSgpKSgpKCkoKSlbKCkoKSgpXSkoKSgpKVsoKSgpKCldKSgpKCkpWygpXSkpKCkpKCkoKSlbKCkoKSgpKCldKSgpKSgpKCkoKSlbKCkoKSgpXSkoKSkoKSlbKCldKVsoKV0pKCkoKSgpKVsoKSgpXSkoKSgpKVsoKSgpKCkoKV0pKCkoKSkoKSlbKCkoKV0pKCkpKCkoKSlbKCkoKSgpKCldKSgpKSgpKCkoKSlbKCkoKSgpXSkoKSgpKVsoKSgpKCldKSgpKCkpWygpXSkpKCkpKCkoKSlbKCkoKSgpKCldKSgpKSgpKCkoKSlbKCkoKSgpXSkoKSkoKSlbKCldKVsoKV0pKCkoKSgpKVsoKSgpXSkoKSgpKVsoKSgpKCkoKV0pKCkoKSkoKSlbKCkoKV0pKCkpKCkoKSlbKCkoKSgpKCldKSgpKSgpKCkoKSlbKCkoKSgpXSkoKSgpKVsoKSgpKCldKSgpKCkpWygpXSkpKCkpKCkoKSlbKCkoKSgpKCldKSgpKSgpKCkoKSk-WygoKCgoKCgoKCgpKCkoKSgpKCkpKXt9e30pe30pe30pe30pe31bKCldKXt9KXt9KXt9XSl7KHt9WygpXTx7fT4pfXt9KHt9PHt7fX0-KQ&input=MTk5Nw)
```
({}<(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((()()())){}{}){})[()()])())()())[()()()()])())()()())[()()()])()())[()()()])()())[()]))())()())[()()()()])())()()())[()()()])())())[()])[()])()()())[()()])()())[()()()()])()())())[()()])())()())[()()()()])()())[()])()()())[()()])()())[()()()()])()())())[()()])())()())[()()()()])())()()())[()()()])()())[()()()])()())[()]))())()())[()()()()])())()()())[()()()])())())[()])[()])()()())[()()])()())[()()()()])()())())[()()])())()())[()()()()])())()()())[()()()])()())[()()()])()())[()]))())()())[()()()()])())()()())[()()()])())())[()])[()])()()())[()()])()())[()()()()])()())())[()()])())()())[()()()()])())()()())[()()()])()())[()()()])()())[()]))())()())[()()()()])())()()())[()()()])())())[()])[()])()()())[()()])()())[()()()()])()())())[()()])())()())[()()()()])())()()())[()()()])())()())[()()()()])()())())[()()])())()())[()()()()])())()()())[()()()])()())[()()()])()())[()]))())()())[()()()()])())()()())[()()()])())())[()])[()])()()())[()()])()())[()()()()])()())())[()()])())()())[()()()()])())()()())[()()()])()())[()()()])()())[()]))())()())[()()()()])())()()())[()()()])())())[()])[()])()()())[()()])()())[()()()()])()())())[()()])())()())[()()()()])())()()())[()()()])()())[()()()])()())[()]))())()())[()()()()])())()()())[()()()])())())[()])[()])()()())[()()])()())[()()()()])()())())[()()])())()())[()()()()])())()()())[()()()])()())[()()()])()())[()]))())()())[()()()()])())()()())[()()()])())())[()])[()])()()())[()()])()())[()()()()])()())())[()()])())()())[()()()()])())()()())[()()()])()())[()()()])()())[()]))())()())[()()()()])())()()())[()()()])())())[()])[()])()()())[()()])()())[()()()()])()())())[()()])())()())[()()()()])())()()())[()()()])()())[()()()])()())[()]))())()())[()()()()])())()()())[()()()])())())[()])[()])()()())[()()])()())[()()()()])()())())[()()])())()())[()()()()])())()()())[()()()])()())[()()()])()())[()]))())()())[()()()()])())()()())>[(((((((((()()()()())){}{}){}){}){}){}[()]){}){}){}]){({}[()]<{}>)}{}({}<{{}}>)
```
While this program is quite long for code golf, it really is decently short for Brain-Flak. Currently the world record for integer division is over 1000 bytes.
# Explanation
The algorithm is quite simple. Because there is a limited number of years available (321) it simply pushes the answers in reverse order under the input and uses a lookup algorithm to find the correct answer. While hardcoding all 321 possibilities may seem rather inefficient with an task as complex as this one and a language as esoteric as brain-flak it may very well be the best solution. (I plan to find out in the coming week).
Since most of the 321 numbers are about 18 on average and they differ by very little from year to year instead of pushing all the numbers individually I push the first year (2233) normally and then just duplicate and change the value a bit for each year after. This way instead of paying to push ~18 for all 321 years I only pay to push ~2 for every year.
Once all the answers have been pushed it subtracts 1912 from the input `({}[(((((((((()()()()())){}{}){}){}){}){}[()]){}){}){}])` (This may be suboptimal, I rewrote the optimizer to skip certain values that I believed would not be optimal because hardcoding numbers is a super-exponential process and running it to completion may have taken a few days).
It then subtracts one from the first element and pops the second element until the result reaches zero, `{({}[()]<{}>)}`.
It pops the zero, `{}` and all the elements below the top element `({}<{{}}>)`.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~38~~ ~~36~~ 34 bytes
```
FT+"@llI$YO]q&:t8XO!s9\~)9#1$ZOZps
```
[Try it online!](http://matl.tryitonline.net/#code=RlQrIkBsbEkkWU9dcSY6dDhYTyFzOVx-KTkjMSRaT1pwcw&input=MjE5OQ) Or [verify all test cases](http://matl.tryitonline.net/#code=YApGVCsiQGxsSSRZT11xJjp0OFhPIXM5XH4pOSMxJFpPWnBzCkRU&input=MTkxMgoxOTE0CjE5ODQKMTk5NgoyMDYzCjIxNTAKMjE5OQoyMjMz) (takes a few seconds).
### Explanation
```
FT+ % Input year implicitly. Add [0 1] element-wise. Gives array with input year
% and next year
" % For each of those two years
@ % Push year
ll % Push 1 twice. This indicates January 1.
I$YO % Convert year, month, day to serial date number
] % End for each. We now have the serial date number for January 1 of the input
% year and that of the following year
q % Subtract 1 to the latter, to yield December 31 of the input year
&: % Inclusive range between those two numbers. This gives an array of serial date
% numbers for the whole input year
t % Push another copy of that array
8XO % Convert to date string with format 8. This gives weekday as "Mon", "Tue" etc.
% The result is a 3-column 2D char array, where each row is a day
!s % Transpose, sum of each column. 'Wed' gives 288 (sum of ASCII codes)
9\~ % 288 gives 0 modulo 9, and is the only weekday to do so. So we compute modulo 9
% and negate. This gives true for Wednesdays, false for the rest
) % Apply as logical index into the array of serial date numbers
9#1$ZO % Array of month numbers corresponding to those serial date numbers
Zp % Array that contains true for prime numbers, false for the rest
s % Sum of array. Display implicitly
```
[Answer]
# Bash + common utilities, 39
```
ncal $1|grep W|factor|egrep -c ': \S+$'
```
Takes the input year as a command-line parameter. Typically outputs messages like this to STDERR - I think this is legal as per [this meta-answer](https://codegolf.meta.stackexchange.com/a/4781/11259):
```
factor: ‘We’ is not a valid positive integer
```
If you want to explicitly suppress the STDERR output then you can do this instead for a score of **43**:
```
ncal $1|grep W|factor 2>-|egrep -c ': \S+$'
```
[Answer]
# Octave, 86 bytes
This is *not* fast, by any stretch. But that's not really the goal of a code golf, is it?
```
function r=p(y)r=0;for(i=698346:7:815953)d=datevec(i);r+=d(1)==y*isprime(d(3));end;end
```
Octave can track dates by "date number" - number of days elapsed where Jan 1, 0 is day 1. By this measure, Jan 3, 1912 (the first Wednesday in our set) is day 698,346. Start there, and iterate through every 7th day (all Wednesdays) until the end of 2233, and add 1 if the year is the target year AND the month-day is prime.
[Answer]
# Python 2.7, ~~166~~, ~~165~~, 150 bytes
```
from datetime import*
y=input()
d,c=date(y,1,1),0
while d.year==y:n=d.day;c+=n>1<2==d.weekday()>0<all(n%x for x in range(2,n));d+=timedelta(1)
print c
```
There is certainly room for improvement here. I am rather new to golfing in python. This uses the `datetime` module. It loops through all the days in the year adding one to an accumulator if it fits the criterion. It then prints the result. Most of the heavy lifting is in the module so the code can be quite slim.
One byte saved thanks to [Morgan Thrapp](https://codegolf.stackexchange.com/users/38770/morgan-thrapp) and 15 bytes saved by [Pietu1998](https://codegolf.stackexchange.com/users/30164/pietu1998).
[Answer]
# J, 44 bytes
```
+/@(valdate*3=weekday)@,.&(,/(>:,"0/p:)i.12)
```
I just discovered that J has builtins for date manipulation.
### Usage
Extra commands are used for formatting multiple input/output.
```
f =: +/@(valdate*3=weekday)@,.&(,/(>:,"0/p:)i.12)
(,.f"0) 1912 1914 1984 1996 2063 2150 2199 2233
1912 19
1914 16
1984 17
1996 19
2063 19
2150 16
2199 18
2233 18
```
### Explanation
```
+/@(valdate*3=weekday)@,.&(,/(>:,"0/p:)i.12) Input: year
i.12 The range [0, ..., 11]
>: Increment each to get the months [1, ..., 12]
p: Get the first 12 primes [2, ..., 37]
,"0/ Make a table between each month and prime
,/ Join the rows
,.& Prepend the year to each
The date format is YYYY MM DD
3=weekday Check if each date occurs on Wednesday
valdate* and is a valid date
+/@ Count the number of true values and return
```
[Answer]
## PowerShell v3+, ~~99~~ 95 bytes
Brute force approach --
```
param($y)(1..12|%{$m=$_;2,3,5,7,11,13,17,19,23,29,31|?{(date "$m-$_-$y").DayofWeek-eq3}}).Count
```
Takes input `$y`, loops from `1` to `12`, stores the month temporarily into `$m`, then loops over every prime from `2` to `31`. For each of those, we construct a `Get-Date` of that particular day, then select only those with `DayOfWeek` `-eq`ual to `3` (i.e., Wednesday). Encapsulates that all in a parens to formulate an array, and takes the `.Count` thereof.
---
Alternatively, mathematical approach --
### PowerShell v3+, 105 bytes
```
param($y)(16,19,18,20,16,18,19)[($a=(date "1-1-$y").DayOfWeek)]+(1,-3,0,1,2)[$y%5]*($a-in0,2,3,4)*!($y%4)
```
Winds up being just a hair longer than the brute force approach, but I'm including it here since it may be beneficial to others.
Again takes input `$y` as the year. This time we're performing strictly math operations based on the first day of the year. We first calculate what day of the week that is, and store that into `$a` for use later. That indexes into the first array, which gets us the number that is usually correct. We have to add to that a second index based on whether it's a potential leap year, whether it's a Sunday, Tuesday, Wednesday, or Thursday, and based on what the year is.
This is based on the following observation. The first column is what day of week January 1st is, the second is the usual output. Unless the year is one of the middle numbers, then it's the number in parens instead. The final column describes how the %5 indexing works.
```
Jan-1 -> # ... Except if $y= (then it's this number) | $y % 5 =
Sun -> 16 ... 1928 1956 1984 etc. (17) | 3
Mon -> 19
Tue -> 18 ... 1924 1952 1980 etc. (20) | 4
Wed -> 20 ... 1936 1964 1992 etc. (17) | 1
Thur -> 16 ... 1920 1948 1976 etc. (17) | 0
Fri -> 18
Sat -> 19
```
---
Note: Both of these assume `en-us` is the current PowerShell setting for culture/date information. The date formatting and `DayOfWeek` number may need to be adjusted accordingly for other culture variants.
[Answer]
# Ruby, 83 + 15 ( `-rdate -rprime` flags) = 98 bytes
[Try it online!](https://repl.it/ChGd) (Imported modules are inlined because idk if I can use flags in repl.it)
```
->y{k=0;Prime.each(31){|d|k+=(1..12).count{|m|Date.new(y,m,d).wday==3 rescue p}};k}
```
[Answer]
# JavaScript ES6, ~~187~~ ~~182~~ ~~181~~ 179 bytes
**179** *Swapped in a for-loop for the while-loop*
```
z=y=>{D=new Date("1/3/1912");N=0;a=()=>D.getFullYear();b=()=>D.getDate();c=()=>D.setDate(b()+7);for(;a()<=y;c())N+=y-a()?0:-1<[2,3,5,7,11,13,17,19,23,29,31].indexOf(b());return N}
```
**181** *Compacted the ternary*
```
z=y=>{D=new Date("1/3/1912");N=0;a=()=>D.getFullYear();b=()=>D.getDate();c=()=>D.setDate(b()+7);while(a()<=y){N+=y-a()?0:-1<[2,3,5,7,11,13,17,19,23,29,31].indexOf(b());c()}return N}
```
**182** *Combined the two loops*
```
z=y=>{D=new Date("1/3/1912");N=0;a=()=>D.getFullYear();b=()=>D.getDate();c=()=>D.setDate(b()+7);while(a()<=y){N+=a()==y?-1<[2,3,5,7,11,13,17,19,23,29,31].indexOf(b()):0;c()}return N}
```
**187**
```
z=y=>{D=new Date("1/3/1912");N=0;a=()=>D.getFullYear();b=()=>D.getDate();c=()=>D.setDate(b()+7);while(a()<y)c();for(;a()==y;c())N+=-1<[2,3,5,7,11,13,17,19,23,29,31].indexOf(b());return N}
```
[Answer]
## Batch, 248 bytes
```
@set/ad=0,l=1,n=20
@for /l %%i in (1913,1,%1)do @set/ad=(d+l+1)%%7,l=!(%%i%%4)-!(%%i%%100)+!(%%i%%400)
@goto %l%%d%
:03
:06
@set/an-=1
:12
:13
:16
@set/an-=1
:01
:04
:14
@set/an-=1
:00
:05
:10
:15
@set/an-=1
:02
:11
@echo %n%
```
Explanation: `d` is the day of the week, with `0` for Monday, which is conveniently 1st Jan 1912. `l` is a flag for whether the year is a leap year, `1` for 1912. We then loop through from 1913 to the input year, updating the day of week and recalculating the leap year flag as we go. Finally we use the leap year flag and day of week to index into what is effectively a big switch statement to determine `n`, the number of prime Wednesdays. Setting `n` to 20 and decrementing it with fall though is cheaper than using flow control logic, but the upshot is that if the 1st of January of a non-leap year is Thursday or Sunday then there are 16 prime Wednesdays and so on for the other cases.
[Answer]
# JavaScript ES6 ~~206~~ ~~203~~ ~~199~~ ~~197~~ ~~195~~ ~~183~~ ~~182~~ 179
Not the shortest, but best I can do for now... Golfing suggestions welcome...
```
p=n=>--d-1?n%d&&p(n):1;v=Date;D=(x,y)=>new v(x.setDate(x.getDate()-y));W=a=>eval('for(Z=0,z=D(w=new v(a,11,31),(w.getDay()+4)%7);z>new v(a,0,1);)Z+=~~p(d=z.getDate()),z=D(z,7);Z')
```
Changes:
1. altering ternary component from: `3>=x?3-x:10-x` to `6-(x+10)%7`, saving: 3
Changes to declaration locations;
2. merged `x=w.getDay();z=D(w,6-(x+10)%7)` to `z=D(w,6-(w.getDay()+10)%7)`, saving: 4
3. shifted `Z=0` from `for` loop to Date declaration and pushed `z=D(w,6-(x+10)%7)` into `for` loop to tidy up, saving: 2
4. shifted `w=new Date(a,Z=0,1)` declaration into `for` loop, merging with existing `w` declaration, saving: 2
5. rewriting the prime finding function to a prime testing function, saving: 12
6. changing `+!!` to `~~` to reduce and still convert `p(d=1)` from `NaN` to `0`, allowing Prime Test function to still work, saving: 1
7. Moved all extra functions out of main calling function `W`, redefined `for` loop - going in reverse from 31st Dec, writing `Date` object out as a separate variable, then re-wrote `for` loop into `eval` call; saving 3.
@PandaCoder, I'm catching up to you, mate!
[Answer]
# R, ~~149~~ 147 bytes
```
y=function(x){s=strftime;b=ISOdate
a=seq(b(x,1,1),t=b(x,12,31),b='d')
length(a[s(a,'%u')==3&trimws(s(a,'%e'))%in%c(2,3,5,7,11,13,17,19,23,29,31)])}
```
Test it on [Ideone](http://ideone.com/7uqNXt).
[Answer]
# Groovy, 126
Groovy doesn't have prime number validation, had to build that too.
```
{n->p={x->x<3||(2..Math.sqrt(x)).every{x%it}};(new Date("1/1/$n")..new Date("12/31/$n")).collect{it[7]==4&&p(it[5])?it:0}-[0]}
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 39 bytes
```
{+/1⍭2⊃¨¯1⎕DT{⍵/⍨3=7|⍵}⊃↓∘⍳/1⎕DT,¨⍵+⍳2}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkGXI862lxCgKxqQ9tHvbusHvU0pSRWFh9a8ah3qw6Q7GoyVDBUeNTdogCWKUkFy9T@TwNp0dY3fNS71uhRV/OhFYfWG4KNqgZK6z/qXWFsa14DUgmUfNQ2@VHHjEe9m/UhSnTAZmgDBYxqQS4BGpWmYGhpaMSFxDFB4lggcyzN4BwjAzNjBMfQ1ACJY2mJ4BgZG/8HAA "APL (Dyalog Extended) – Try It Online")
Just *that* much away from MATL.
`∆DT` is polyfilled in this answer because it isn't available on tio.
It was created by Adám(I simply cannot thank him enough for his help).
## Explanation
```
{+/1⍭2⊃¨¯1⎕DT{⍵/⍨3=7|⍵}⊃↓∘⍳/1⎕DT,¨⍵+⍳2}
⍵+⍳2 year and year+1
1⎕DT,¨ convert each of those to their day numbers
↓∘⍳/ get inclusive range between them
⊃ remove nesting
{⍵/⍨3=7|⍵} Wednesday filter:
3=7|⍵ 7 mod <daynum> always returns day of the week (starting on Monday)
⍵/⍨ filter dates by that bitmask
¯1⎕DT convert the filtered day numbers to mm dd yy
2⊃¨ pick 2nd element of each(dd)
1⍭ check if prime(1 or 0)
+/ sum the array
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-x`](https://codegolf.meta.stackexchange.com/a/14339/), 20 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
366õÈ=ÐUTX)f j «3aXe
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LXg&code=MzY29cg90FVUWClmIGogqzNhWGU&input=MTkxMg)
] |
[Question]
[
In this challenge you will be converting a mixed number to an improper fraction.
Because improper fractions use fewer numbers, your code will need to be as short as possible.
---
## Examples
```
4 1/2
9/2
12 2/4
50/4
0 0/2
0/2
11 23/44
507/44
```
## Specification
You may assume the denominator of the input will never be 0. The input will always be in the format `x y/z` where x,y,z are arbitrary nonnegative integers. You do not need to simplify the output.
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in bytes wins.
[Answer]
# LabVIEW, 29 [LabVIEW Primitives](http://meta.codegolf.stackexchange.com/a/7589/39490)
[](https://i.stack.imgur.com/TvVku.gif)
[Answer]
## CJam, ~~16~~ ~~15~~ 14 bytes
```
l'/']er~:Xb'/X
```
or
```
l'/']er~_@b'/@
```
[Test it here.](http://cjam.aditsu.net/#code=l'%2F'%5Der~%3AXb'%2FX&input=11%2023%2F44)
## Explanation
```
l e# Read input.
'/']er e# Replace the "/" with a "]".
~ e# Evaluate the string as code. If the input was "i n/d", this pushes [i n] d.
:X e# Store the denominator in X.
b e# Treat [i n] as base-d digits. This effectively computes i*d + n.
'/ e# Push a slash.
X e# Push the denominator.
```
The other version avoids using a variable by using a bit more stack shifting.
[Answer]
## Mathematica, 58 bytes
```
ToExpression@StringReplace[#," "->"+"]~ToString~InputForm&
```
This returns the simplified result. If outputting a rational number instead of a string is fine, we can save 19 bytes:
```
ToExpression@StringReplace[#," "->"+"]&
```
[Answer]
## PowerShell, ~~47~~ ~~44~~ 42 Bytes
[Crossed out 44 is still regular 44 ;(](http://meta.codegolf.stackexchange.com/a/7427/42963)
```
$l,$n,$d=$args-split'\D';"$(+$l*$d+$n)/$d"
```
Golfed a couple bytes by using regex `-split`. Golfed a couple more thanks to [TessellatingHeckler](https://codegolf.stackexchange.com/users/571/tessellatingheckler) by swapping the regex.
The `$args-split'\D'` takes our input argument and splits on non-digit characters. Here it performs two splits, one on whitespace, the other on the `/` character. The results are then stored in the three variables using a simultaneous assignment. We then formulate the string output as (the `$l`eft number times the `$d`enominator plus the `$n`umerator) executed as a code block, a `/` slash, and then the `$d`enominator again.
[Answer]
# Java with [Ten Foot Laser Pole](https://github.com/SuperJedi224/Ten-Foot-Laser-Pole) 1.03, 79+25 (import) = 104 bytes
Requires `import sj224.tflp.math.*;`
```
String m(String[]a){return ""+new BigRational(a[0]).add(new BigRational(a[1]));}
```
This will almost certainly work with 1.04 as well, but so far I've only tested it with 1.03 because I already happened to have a java project set up with 1.03 in the build path.
[Answer]
# JavaScript (ES6), ~~44~~ 41 bytes
```
m=>([x,y,z]=m.match(/\d+/g),+y+x*z+"/"+z)
```
*Saved 3 bytes thanks to [@ETHproductions](https://codegolf.stackexchange.com/users/42545/ethproductions)!*
## Explanation
Very simple.
```
m=>
([x,y,z]=m.match(/\d+/g), // x, y and z = numbers from input
+y+x*z // numerator
+"/"+z // denominator
)
```
## Test
Test is without destructuring assignment to work in most browsers.
```
var solution = m=>+(p=m.match(/\d+/g))[1]+p[0]*p[2]+"/"+p[2]
```
```
<input type="text" id="input" value="11 23/44" />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```
[Answer]
# Japt, 10 bytes
Woohoo, currently beating CJam!
```
U*W+V+'/+W
```
[Try it online!](http://ethproductions.github.io/japt?v=master&code=VSpXK1YrJy8rVw==&input=MTEgMjMvNDQ=)
### How it works
```
// Implicit: [U,V,W] = eval(input). This automatically discards the slash.
U*W+V // Calculate the new numerator: (whole part * denominator) + numerator.
+'/+W // Add the slash and the denominator.
// Implicit: output last expression
```
[Answer]
# Julia, ~~58~~ 50 bytes
```
s->eval(parse((r=replace)(r(s," ","+"),"/","//")))
```
This is an anonymous function that accepts a string and returns a `Rational` type object. To call it, give it a name, e.g. `f=s->...`.
We can take advantage of the fact that the input can be manipulated slightly to be an expression that evaluates to a rational. In particular, an integer plus a rational is a rational, and rationals are denoted with double slashes. So if we turn `4 1/2` into `4+1//2`, the evaluated result will be `9//2`.
Ungolfed:
```
function f(s::AbstractString)
# Replace the space in the input with a plus
r1 = replace(s, " ", "+")
# Replace the / with //
r2 = replace(r1, "/", "//")
# Parse the resulting expression as a rational
return eval(parse(r2))
end
```
[Answer]
# Smalltalk – 76 characters
The input exactly matches the array delimiter and inherent fraction representation of Smalltalk. If it just weren't so verbose, it could have been a serious contender!
```
Compiler evaluate:'|p|p:=0.#(',FileStream stdin nextLine,')do:[:q|p:=p+q].p'
```
It's too bad simplification wasn't a requirement, Smalltalk does it automatically!
[Answer]
# Bash + coreutils, 28
```
dc<<<${@/\// }sarla*+n47Plap
```
`$@` expands to all command-line parameters, so `${@/\// }` expands to all command-line parameters with `/` replaced with , which is put on `dc`'s stack. The rest is simple stack manipulation and arithmetic.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~17~~ 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
#`'/¡R`Š©*+®'/ý
```
-2 bytes thanks to *@MagicOctopusUrn*.
[Try it online](https://tio.run/##MzBNTDJM/f9fOUFd/9DCoISjCw6t1NI@tE5d//De//9NFAz1jQA) or [verify all test cases](https://tio.run/##MzBNTDJM/W/i9l85QV3/0MKghKMLDq3U0j60Tl3/8N7/Ov9NFAz1jbgMjRSM9E24DBQMQBxDBSNjfRMTAA).
**Explanation:**
```
#` # Split input by spaces and push all items to the stack
# i.e. "4 1/2" → "4" and "1/2"
'/¡ # Push the second item by "/"
# i.e. "1/2" → [1,2]
R` # Revert the list, and also push all items to the stack
# i.e. [1,2] → [2,1] → 2 and 1
Š # Triple-swap the stack
# [4,2,1] → [1,4,2]
© # Store the 2 in the register
* # Multiple the top two items
# 4 and 2 → 8
+ # Add the top two items
# 1 and 8 → 9
® # Push the 2 from the register to the stack again
'/ý # Join the two items by "/"
# 9 and 2 → "9/2"
```
---
With flexible input- and output-format, taking the integers in the order `x,z,y` and outputting the nominator and denominator on separated lines it would be **4 bytes** (which is why I added the [parsing](/questions/tagged/parsing "show questions tagged 'parsing'")-tag to the challenge..):
```
*+²»
```
[Try it online](https://tio.run/##MzBNTDJM/f9fS/vQpkO7//834TLiMgQA) or [verify all test cases](https://tio.run/##MzBNTDJM/W/i5ul5aOV/Le1D6w7t/q9zaJv9fxMuIy5DLkMjLhDDAIwNDblMgDxjAA).
**Explanation:**
```
* # Multiply the first two inputs (x and z)
# i.e. 4 and 2 → 8
+ # Add the third input (y)
# i.e. 8 and 1 → 9
² # Take the second input again (z)
» # Join the stack by newlines and implicitly print it
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~74~~ ~~67~~ 63 bytes
```
r=read
f x|(a,(c,s:d):_)<-lex<$>lex x!!0=show(r a*r d+r c)++s:d
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/v8i2KDUxhStNoaJGI1FHI1mn2CpF0ype00Y3J7XCRsUOSCpUKCoa2BZn5JdrFCkkahUppGgXKSRramsDlf7PTczMsy0oyswrUUlTMjRSMNY3UfoPAA "Haskell – Try It Online")
## Explanation
As [H.PWiz](https://codegolf.stackexchange.com/users/71256/h-pwiz) figured out we can use Haskell's lexer here to break up the string into it's parts. (Earlier I was using `span(>'/')`) And Laikoni pointed out that `<$>` works just like `mapSnd` from `Data.Tuple`.
The pattern guard breaks up our code into the three numbers we want using `lex`. `lex` invokes haskell's lexer to break off the first token. It returns a list with each element representing a possible way to parse the string. These elements are tuples with the first element being the first token and the rest of the string being the second element. Now since the input format is very regular we are only ever going to have exactly one parse, so we can always take the first one. The first thing we do is invoke `lex` on the input
```
lex x
```
Then we unwrap it from it's list giving us a 2-tuple
```
lex x!!0
```
The first token will be the whole part of the mixed fraction leaving the fraction prepended by a space to still parse. Then since tuples are `Functors` we can use `(<$>)` an alias for `fmap` to apply `lex` to the second element of the tuple.
```
lex<$>lex x!!0
```
This eats through the space and breaks off the next token, the numerator of our fraction. Now we bind this to a pattern match using `<-`. Our pattern is
```
(a,(c,s:d):_)
```
`a` grabs the whole part of the fraction, our first token. `:_` unwraps the list resulting from our second `lex`. `c` grabs the second token we lexed, that is the numerator of the fraction. Everything that remains is bound to `s:d` which splits it into its first character, guaranteed by the format to be a `/` and the remainder which will be the denominator.
Now that we have parsed the input we do the actual computation:
```
show(r a*r d+r c)++s:d
```
Where `r` is the read function we bound earlier.
It is important to note that `lex` returns a list empty if it fails and non-empty if it succeeds. Why this is not a `Maybe` I do not know.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 1 byte
```
+
```
[Run and debug it](https://staxlang.xyz/#c=%2B&i=4+1%2F2%0A12+2%2F4%0A0+0%2F2%0A11+23%2F44&a=1&m=2) (although there's not much to debug)
The challenge specification says "You do not need to simplify the output." Assuming it's *allowed* to simplify, then there's a built-in instruction in stax to do this. The input is implicitly interpreted as an integer and a rational number. The `+` instruction widens both to rationals, adds, and simplifies. The result is implicitly printed.
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 92 bytes
```
: f 0 -rot 3. do 0 -rot >number 1 m+ loop 2drop + >r swap i * + r> <# 0 #s '/ hold + #s #> ;
```
[Try it online!](https://tio.run/##ZY3LCsIwFET3fsXQLARLzaNdqeRf1DRWaL3hJiJ@fbwuBNHNDOfAMJG4TN0lvqvWHSIMOqaCfotAH/C3@3IaGRZLi5kowQWWbOEZ@XFMuGIjxB4HJSOVsdaYaA4iBZTHvuYG1sL1ehga@SnPNOLMK9EDrHY/zsD8Oevg9Pe4vgA "Forth (gforth) – Try It Online")
The pain of parsing and formatting...
Takes a string as `pointer length` (gforth standard), and returns a string in the same format.
### How it works
```
: f ( addr u -- addr u ) \ take a string and return a string
0 -rot \ ( 0 addr u )
3. do \ repeat 3 times...
0 -rot \ ( ... 0 0 addr u )
>number \ ( ... num 0 addr u ) parse an integer;
\ `addr` now points to right after the parsed int
1 m+ \ increment the addr to point to the next integer
loop \ end loop ( x y z 0 addr u )
2drop + \ discard input string and zero on the top
>r \ ( x y R:z ) so the value of z can be copied by `i`
swap i * + \ ( x*z+y R:z )
r> \ ( x*z+y z )
<# \ start formatting the output from the end
0 #s \ push z to the output; formatting built-ins take double cells
'/ hold \ push a slash
+ #s \ #s leaves two zeros at the top, so discard one and push x*z+y
#> \ finish formatting and get the string ( pointer length )
;
```
[Answer]
# Wolfram|Alpha, 0 or 1 byte
```
=
```
The challenge says it's not necessary to simplify the output, but doesn't disallow it. If it's not disallowed, then:
1)The online Wolfram|Alpha interpreter will automatically convert mixed numbers to improper fractions (0 bytes). E.g.:
[](https://i.stack.imgur.com/sm5uP.png)
2)The Wolfram|Alpha interpreter can be called within Mathematica by entering `=` followed by the input (1 byte):
[](https://i.stack.imgur.com/vJq6F.png)
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 18 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
OẸ'//ẸsNṭẊ,p+x,'/j
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPU8lRTElQkElQjgnJTJGJTJGJUUxJUJBJUI4c04lRTElQjklQUQlRTElQkElOEElMkNwJTJCeCUyQyclMkZqJmZvb3Rlcj0maW5wdXQ9JTIyNCUyMDElMkYyJTIyJTIwJTIwJTIwJTIwLSUzRSUyMCUyMjklMkYyJTIyJTBBJTIyMTIlMjAyJTJGNCUyMiUyMCUyMCUyMC0lM0UlMjAlMjI1MCUyRjQlMjIlMEElMjIwJTIwMCUyRjIlMjIlMjAlMjAlMjAlMjAtJTNFJTIwJTIyMCUyRjIlMjIlMEElMjIxMSUyMDIzJTJGNDQlMjIlMjAtJTNFJTIwJTIyNTA3JTJGNDQlMjImZmxhZ3M9Q2U=)
#### Explanation
```
OẸ'//ẸsNṭẊ,p+x,'/j # Implicit input ("x y/z")
OẸ # Split on spaces, then dump onto the stack
'//Ẹ '# Split the fraction on "/", then dump again
sN # Swap and convert the numerator to integer
ṭ # Triple swap to get the order [y, x, z]
Ẋ # Copy z to the register without popping
,p # Multiply x and z (implicit conversion to int)
+ # Add this to y (which we converted earlier)
x, # Pair this with z (from the register)
'/j '# Join this pair on "/"
# Implicit output
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 3 bytes
```
⌈E∑
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCLijIhF4oiRIiwiIiwiNCAxLzIiXQ==) -4 thanks to lyxal
```
⌈ # Split on spaces
E # Evaluate each
∑ # Sum
```
[Answer]
# [Factor](https://factorcode.org), 43 bytes
```
[ eval( -- x x ) + >fraction [I ${}/${}I] ]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=JU29CsIwGNz7FEcQVEpJGzOIgrhJFxfRpXQIkmogJiVG8QefxKWLPoBv49sYDB_HHXfcfc93I7beuu67Wa_K5WICeRYaB-H3UMZL11otvMROGumEVjfhlTVHKItpkhCOgjKSkIKBUR5EjjwaBdiIck5eJ99k429a_YcHyDJcwg2RYta48DvMoSrRuz9oQFmjjpVPv8IcRqMGhxFtq68x6LrIPw)
Assumes the input must be a string, otherwise this can be shorter. Simplifies the output.
[Answer]
# Javascript ES6, 62 bytes
```
p=prompt;b=p(a=+p()).split`/`;alert((+b[1]*a+ +b[0])+"/"+b[1])
```
[Answer]
# Perl, ~~82~~ ~~61~~ 38 bytes
```
#!perl -paF/\D/
$_=$F[0]*$F[2]+$F[1]."/$F[2]"
```
This can probably be golfed more.
**Changes**
* Saved 16 bytes by using a regex in `split`, and 5 by using `<>` instead of `<STDIN>`.
* Saved another 16 bytes thanks to Dennis.
[Answer]
## Mathematica, 51 bytes
```
Interpreter["ComputedNumber"]@#~ToString~InputForm&
```
Interestingly, Mathematica supports this with a built-in. If outputting a number is allowed, than we only need 28 bytes:
```
Interpreter@"ComputedNumber"
```
[Answer]
# Java, ~~159~~ ~~148~~ ~~142~~ ~~120~~ 110 bytes
```
String m(String[]a){Long b=new Long(a[0]),d=new Long((a=a[1].split("/"))[1]);return b*d+new Long(a[0])+"/"+d;}
```
Saved a bunch of bytes thanks to FlagAsSpam.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 23 bytes
```
->x{eval x.split*?++?r}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf166iOrUsMUehQq@4ICezRMteW9u@qPZ/QWlJsUJatJKJgqG@kVLsfwA "Ruby – Try It Online")
[Answer]
# [ARBLE](https://github.com/TehFlaminTaco/ARBLE), 13 bytes
```
a*c+b.."/"..c
```
[Try it online!](https://tio.run/##SyxKykn9/z9RK1k7SU9PSV9JTy/5////hob/jYz/m5gAAA "ARBLE – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~78~~ 76 bytes
```
def f(s):a,b=s.split();b,c=b.split('/');return'%s/'%(int(a)*int(c)+int(b))+c
```
[Try it online!](https://tio.run/##TY3BDoIwEETvfMVezHaFUECMEdIvUQ6AJZIaIG09EOO3Y4uYuJfZmbydnWZ7H4fDstxkBx0zVNRRI0xspkdvGZVN1Ipmc8iRSi3tUw@4Mxx3rB8sq2nvpaXQS0MUtouVxhoQ8MIcUp5hAXh2EgGmGWQ898ExceqSBJIvkWxECtmB5xtz8ts76EYNCvoB1uZYydkwKgJwM2n/V7lLgKt1DStyUdWafKOOKfqzDKXWo8YIR4V0@R0I4bmKguUD "Python 3 – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) with -la -Mfeature=say, 32 bytes 25 bytes
```
m|/|;say$_*$'+$F[1],"/$'"
```
[Try it online!](https://tio.run/##K0gtyjH9/z@3Rr/GujixUiVeS0VdW8Ut2jBWR0lfRV3p/38TBUN9Iy5DIwUjfRMuAwUDEMdQwchY38TkX35BSWZ@XvF/3ZzE/7q@aamJJaVFqbZAcwA "Perl 5 – Try It Online")
*(-7 bytes thanks to Dom Hastings)*
`$_` is the whole input `x y/z`, which evaluates the value of `x` in numeric contexts (like the `*` here). `$'` is the regex post-match string, which here contains whatever comes after `/` - so, `z`. To get the `y` value, we use the `-a` flag which splits the input on spaces and places them in the `@F` array. So here, `@F = ("x", "y/z")`, which means `$F[1]="y/z"` which evaluates in `y` in numeric contexts (since `y` is the initial contiguous sequence of digits with `$F[1]`).
[Answer]
# [Husk](https://github.com/barbuz/Husk), 4 bytes
```
Σmrw
```
[Try it online!](https://tio.run/##yygtzv7//9zi3KLy////mygY6hsBAA "Husk – Try It Online")
`ṁrw` is supposed to work, but there's some bug that returns an empty list. Anyway, hooray for native rational number support.
[Answer]
# [GNU AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 5+16 = 21 bytes
Command-line argument: `-F |/`
Source code:
```
$0=$1*$3+$2"/"$3
```
[Try it online!](https://tio.run/##SyzP/v9fxcBWxVBLxVhbxUhJX0nF@P9/EwVDfSMuQyMFI30TLgMFAxDHUMHIWN/E5F9@QUlmfl7xf103hRp9AA "AWK – Try It Online")
The command-line argument sets the field separator to the regex `/ |\//`. Thus, it is easy to map the input as three fields.
[Answer]
# [Itr](https://github.com/bsoelch/OneChar.js/blob/main/ItrLang.md), 1 byte
`+`
Itr has built-in support for rational numbers, including for parsing input numbers.
[online interpreter](https://bsoelch.github.io/OneChar.js/?lang=Itr&src=Kw==&in=MTEgMjMvNDQ=)
## Explanation
```
; implicit input, by default numbers are separated by spaces
; two integers with a '/' between them are interpreted as a fraction
+ ; add the integer part to the fractional part
; implicitly output the fraction
```
[Answer]
# [Headass](https://esolangs.org/wiki/Headass), 80 bytes
```
-(----[]]]][]]][{{U]>)D^^D^^^^^R]^}:DON-)}:NE.U[UOUO{^)N+E:]OD-}.U^U[{U^)DPD]P:}
```
[Try It Online!](https://dso.surge.sh/#@WyJoZWFkYXNzIiwiIiwiLSgtLS0tW11dXV1bXV1dW3t7VV0+KUReXkReXl5eXlJdXn06RE9OLSl9Ok5FLlVbVU9VT3teKU4rRTpdT0QtfS5VXlVbe1VeKURQRF1QOn0iLCIiLCI0OSAvLyAxXG40OSAvLyAxXG4zMiAvLyBzcGFjZVxuNTAgLy8gMlxuNTEgLy8gM1xuNDcgLy8gL1xuNTIgLy8gNFxuNTIgLy8gNCIsIiJd) Takes character codes as input and outputs as two numbers Numerator, Denominator.
### Explanation:
Fairly straightforward, parses by looping through digits, subtracting 48, and then multiplying by 10 before adding each new number. when it hits a charcode less than 48, it knows to move on to the next number. There's not an easy way to multiply within a single code block to my knowledge, so the next two code blocks respectively copy a bunch of x onto the queue and then add them all up. Probably still golfable within the same approach, I found a few golfs while writing up the explanation, even.
```
-(----[]]]][]]][{{U]>)D^^D^^^^^R]^}:DON-)}:NE. block 0: parses input
-( r3 = -1
----[]]]][]]][ r2 = -48
{ N-)}: while input remains
{U]>) }: while input + r2 > r3
D^^D^^^^^ r1 *= 10
R]^ r1 += input + r2
DO enqueue and reset r1
NE go to block 1
. end block
U[UOUO{^)N+E:]OD-}. block 1: copies x z times onto queue
U[ r2 = x
UO enqueue y
UO enqueue z
U ^ r1 = z
{^) : D-} while(r1--){
]O enqueue x
}
N+E go to block 2
. end code block
U^U[{U^)DPD]P:} block 2: sums copies of x and adds y, prints x*z+y and z
U^ r1 = y
U[ r2 = z
{U ) :} while items remain unvisited on the queue (all of which are x)
U^ r1 += x
DP print r1
D]P print r2
```
] |
[Question]
[
Given a number *N*, output/return ***X* so that *N+X* is a palindrome, where *|X|* has to be as small as possible.**
**Palindrome:** A number is a palindrome, if its sequence of digits is the same when reading them from left to right as when reading from right to left.
`95359` and `6548456` are symmetric, `123` and `2424` are not. Numbers with leading zeros such as `020` are not a palindrome.
**Input** is a positive integer smaller than 1015. Read it from stdin, as a method-parameter, whatever.
**Output** has to be an integer (positive or negative) and ought to be 0 if the input is already a palindrom. You may write your output to stdout, return it from a function or whatever you like. If there are 2 numbers (e.g. `2` and `-2`) that satisfy the requirements, output only one of them.
**Examples:**
```
Input Output
3 0
234 -2
1299931 -10
126 5 or -5 (only one of them)
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 26 20
```
Lnb_bWP`+QZ=Z-g0ZZ)Z
```
Updated to meet the new rules.
The program runs in an infinite loop which tests every possible increment, in the order 0, -1, 1, -2, -2 ...
Explanation:
```
Q=eval(input()) implicit
Z=0 implicit
Lnb_b def P(b): return b != rev(b)
WP`+QZ while P(repr(Q+Z)):
=Z-g0ZZ Z=(0>=Z)-Z
) <end while>
Z print(Z)
```
Example run:
```
python3 pyth.py programs/palin.pyth <<< 965376457643450
-2969881
```
This took 23 seconds.
---
Bonus solution, same character count:
```
Wn`+QZ_`+QZ=Z-g0ZZ)Z
```
[Answer]
# Ruby, ~~111~~ 84 bytes
```
i=$*[j=-1].to_i
r=->j{s=(i+j).to_s
abort(j.to_s)if s==s.reverse}
loop{r[j+=1]
r[-j]}
```
Takes the number as its only command-line argument.
[Answer]
# CJam, ~~34~~ ~~29~~ 25 bytes
```
q~:I!{:R1<R-RI+`_W%=!}g;R
```
[Try it online.](http://cjam.aditsu.net/ "CJam interpreter")
### Examples
```
$ cjam palfind.cjam <<< 120; echo
1
$ cjam palfind.cjam <<< 121; echo
0
$ cjam palfind.cjam <<< 122; echo
-1
```
### How it works
```
q~:I " Read from STDIN, evaluate and save the result in “I”. ";
! " Compute the logical NOT (0 since the integer is positive). ";
{ " ";
:R " Save the topmost integer in “R”. ";
1<R- " Compute (R < 1) - R. This produces the sequence 0 → 1 → -1 → 2 → -2 → … . ";
RI+ " Push I + R. ";
`_ " Cast to string and push a copy. ";
W%=! " Check if the reversed copy matches the original. ";
}g " If it doesn't, repeat the loop. ";
;R " Discard the integer on the stack and push “R”. ";
```
[Answer]
# Python 2.7, ~~98~~, 81
Creates a palindrome from the input number, then subtracts that from the input to find the delta.
```
def f(n):
m=map(int,str(n));l=len(m)/2;m[-l:]=m[l-1::-1];return int(`m`[1::3])-n
```
usage:
```
print f(3) # 0
print f(234) # -2
print f(2342) # -10
print f(129931) # -10
print f(100000) # 1
```
ungolfed and annotated:
```
def f(n): # take a integer n
m=map(int,str(n)); # convert n into array of ints
l=len(m)/2; # get half the length of the array of ints
m[-l:]=m[l-1::-1]; # replace the last elements with the first elements reversed
return int(`m`[1::3])-n # convert array of ints backinto single int and subtract the original number to find the delta
```
[Answer]
# Haskell - 62
```
f n=[x-n|x<-[0..]>>= \v->[n+v,n-v],show x==(reverse.show)x]!!0
```
Save it to a file named `golf.hs` and then test it with ghci:
```
*Main> :l golf
[1 of 1] Compiling Main ( golf.hs, interpreted )
Ok, modules loaded: Main.
*Main> map f [1000..1050]
[-1,0,-1,-2,-3,-4,-5,-6,-7,-8,-9,-10,-11,-12,-13,-14,-15,-16,-17,-18,-19,-20,-21,-22,-23,-24,-25,-26,-27,-28,-29,-30,-31,-32,-33,-34,-35,-36,-37,-38,-39,-40,-41,-42,-43,-44,-45,-46,-47,-48,-49]
*Main>
```
[Answer]
## Perl 5, 93 89 88 87 75 63 44
```
$/=($/<1)-$/while$_+$/-reverse$_+$/;$_=$/+0
```
Ungolfed:
```
while($input + $adjustment - reverse($input + $adjustment)) {
$adjustment = ($adjustment < 1) - $adjustment;
}
$input = $adjustment + 0; ## gives 0 if $adj is undefined (when $input is a palindrome)
print $input; ## implicit
```
Thanks to Dennis's suggestions, got it down to 43 + `-p` = 44
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~15~~ 14 bytes (-1 Thanks to Emigna)
```
2äнsgÈi∞ë.∞}s-
```
[Try it online!](https://tio.run/##MzBNTDJM/f/f6PCSC3uL0w93ZD7qmHd4tR6QrC3W/f/f0BgA "05AB1E – Try It Online")
---
# Method:
* Take the first half of the number.
* Mirror it intersected if odd, non-intersected if even.
* Difference.
[Answer]
# Java : ~~127~~ 109
Basic iteration, checking both negative and positive before moving to the next candidate.
```
int p(long n){int i=0;for(;!(n+i+"").equals(new StringBuilder(n+i+"").reverse()+"");i=i<1?-i+1:-i);return i;}
```
For input `123456789012345`, it returns `-1358024`, to equal palindrome `123456787654321`.
Line breaks:
```
int p(long n){
int i=0;
for(;!(n+i+"").equals(new StringBuilder(n+i+"").reverse()+"");i=i<1?-i+1:-i);
return i;
}
```
[Answer]
# Clojure, 92
Takes the first from a lazy for-sequence that works from 0 out and only includes values that make palindromes:
```
(defn p[x](first(for[i(range)j[1 -1]k[(* i j)]s[(str(+ x k))]:when(=(seq s)(reverse s))]k)))
```
REPL-LPER session:
```
golf-flog> (p 3)
0
golf-flog> (p 10)
1
golf-flog> (p 234)
-2
golf-flog> (p 1299931)
-10
golf-flog> (p (bigint 1e15))
1
```
[Answer]
# JavaScript (ES6), 84 bytes
```
n=>[...(''+n)].reduce((p,c,i,s,m=s.length-1)=>i<m/2?p+(c-s[m-i])*Math.pow(10,i):p,0)
```
My first golf challenge! I know the shorter and more elegant solution has already been posted by @Brian H., but this is another approach.
### Test Code
```
const t =
n=>[...(''+n)].reduce((p,c,i,s,m=s.length-1)=>i<m/2?p+(c-s[m-i])*Math.pow(10,i):p,0)
;
console.log('t(3) =', t(3)); // expected: 0
console.log('t(234) =', t(234)); // expected: -2
console.log('t(1299931) =', t(1299931)); // expected: -10
console.log('t(126) =', t(126)); // expected: -5
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes
```
;.≜+A↔A∧
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3w31rvUeccbcdHbVMcH3Us//8/2ljHyNhEx9DI0tLS2BBIm8UCAA "Brachylog – Try It Online")
The label predicate `≜` is vital here, because by using it on the output before anything else happens (although it's really being invoked on the list containing the input and the output), its absolute value is minimized, because instead of doing anything smarter based on the constraints the program [guesses every integer starting from 0 until it can find one that works.](https://codegolf.stackexchange.com/a/182893/85334) If `≜` is omitted, it dawns on the program that 0 is a very nice palindrome, and it will [always output the negative of the input.](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3w31pP2/FR2xTHRx3L//@PNtYxMjbRMTSytLQ0NgTSZrEA)
```
The input
; + plus
. the output
≜ which is instantiated immediately
A is A
↔ which reversed
A is still A
∧ but isn't necessarily the output.
```
[Answer]
# JavaScript, 175 136 117
Straightforward. `p` returns true if a given number is palindrome, `f` searches the nearest.
**EDIT:** I also golfed it a little bit more thanks to the sweet "indecrement" trick by [Geobits](https://codegolf.stackexchange.com/users/14215/geobits) in the [Java answer](https://codegolf.stackexchange.com/a/36914/20449) here.
```
p=function(n){return (s=''+n).split('').reverse().join('')==s}
f=function(n){for(i=0;!p(n+i);i=i<1?-i+1:-i);return i}
```
Usage:
```
f(3)
f(234)
f(1299931)
```
[Answer]
# J - 49 char
A function mapping integers to integers.
```
((0{g#f)>:@]^:(+:/@g=.(-:|.)@":@+f=._1 1*])^:_&0)
```
Here's how you might build to this result, in three parts. This is the display of the J REPL: indented lines are user input and outdented ones are REPL output. And yes, J spells the negative sign with an underscore `_`.
```
236 (_1 1*]) 4 NB. -ve and +ve of right arg
_4 4
236 (f=._1 1*]) 4 NB. name it f
_4 4
236 (+f=._1 1*]) 4 NB. add left to each
232 240
236 (":@+f=._1 1*]) 4 NB. conv each to string
232
240
236 ((-:|.)@":@+f=._1 1*]) 4 NB. palindrome? on each
1 0
236 (g=.(-:|.)@":@+f=._1 1*]) 4 NB. name it g
1 0
236 (+:/@g=.(-:|.)@":@+f=._1 1*]) 4 NB. logical NOR (result 1 if both=0)
0
palin =: (+:/@g=.(-:|.)@":@+f=._1 1*])
236 (>:@]) 0 NB. increment right
1
236 (>:@]^:2) 0 NB. functional power
2
236 (>:@]^:(236 palin 3)) 3 NB. power 1 if no palindromes
4
236 (>:@]^:(236 palin 4)) 4 NB. power 0 if has palindrome
4
236 (>:@]^:palin) 4 NB. syntactic sugar
4
236 (>:@]^:palin^:_) 0 NB. increment until palindrome, start with 0
4
(>:@]^:(+:/@g=.(-:|.)@":@+f=._1 1*])^:_&0) 236 NB. bind 0
4
delta =: >:@]^:(+:/@g=.(-:|.)@":@+f=._1 1*])^:_&0
((f) delta) 236 NB. f=: -ve and +ve
_4 4
((g) delta) 236 NB. g=: which are palindromes
1 0
((g#f) delta) 236 NB. select the palindromes
_4
((g#f) delta) 126 NB. what if both are equal?
_5 5
((0{g#f) delta) 126 NB. take the first element
_5
((0{g#f)>:@]^:(+:/@g=.(-:|.)@":@+f=._1 1*])^:_&0) 236 NB. it works!
_4
```
Examples:
```
pal =: ((0{g#f)>:@]^:(+:/@g=.(-:|.)@":@+f=._1 1*])^:_&0)
pal 3
0
pal every 234 1299931 126
_2 _10 _5
pal 2424
18
2424 + pal 2424
2442
```
You can also make the golf prefer the positive solution over the negative when they're equal, by changing `_1 1` to `1 _1`.
[Answer]
# Javascript 86
```
n=>{s=(n+'').split('');for(i=0,j=s.length-1;i<j;i++,j--)s[j]=s[i];return s.join('')-n}
```
This is my first codegolf challenge. Hope this solution is acceptable.
ungolfed:
`n => {
s = (n + '').split('');
for (i = 0, j = s.length - 1; i < j; i++,j--)
s[j] = s[i];
return s.join('') - n
}`
Explanation:
Convert input n to String and split.
Iterate over both sides of the resulting array and copy digit on s[i] to s[j] until i < j. This will result in our desired palindrome.
Join array back together and subtract n to get x
[Answer]
# [C (clang)](http://clang.llvm.org/), 85 bytes
```
f(n,x,y,z){for(x=0;z=n+x;x=(1>x)-x){for(y=0;z;z/=10)y=y*10+z%10;if(y==n+x)return x;}}
```
This turned out to be a port of [isaacg's Pyth solution](https://codegolf.stackexchange.com/a/36910/112488).
[Try it online!](https://tio.run/##VY5BCsIwEEXXzimCUkg01cSKUmJ6EjfStBrQqdQoaaVnr6mK6O593vzP5HF@2uOh70uK3POGt@xRVjX1WqhW48wrr6nMPIv9WzSDUO1CS8Ea3UylmLWRFMqWQQ0FVhfuViPxquv6icX8dDMF2V6dsdX8mAHcK2vAFVdHLTqCDB4wutSBSzqONobEGYkSs8MxJ8hJ@IsxBR1AuIDz3iIdBl6t10gS7JuWyeqHE/kNcpmm6V9eB4bR51MR5vsn "C (clang) – Try It Online")
[Answer]
## Groovy - 131 111 107 chars
Golfed:
```
n=args[0] as long;a=n;b=n;f={if("$it"=="$it".reverse()){println it-n;System.exit 0}};while(1){f a++;f b--}
```
sample runs:
```
bash-2.02$ groovy P.groovy 0
0
bash-2.02$ groovy P.groovy 234
-2
bash-2.02$ groovy P.groovy 1299931
-10
bash-2.02$ groovy P.groovy 123456789012345
-1358024
```
Ungolfed:
```
n=args[0] as long
a=n
b=n
f={ if("$it"=="$it".reverse()) {
println it-n
System.exit 0
}
}
while(1) {
f a++
f b--
}
```
[Answer]
# Python 2 - 76
```
i=input()
print sorted([r-i for r in range(2*i)if`r`==`r`[::-1]],key=abs)[0]
```
Gets the input number and generates a list of the differences between the input and every number between `0` and `2*i` only if the number is palindromic.
It then sorts the list by absolute value and prints the first element.
[Answer]
## C++ 289
Function P checks for palindromes using `<algorithm>` method.
Ungolfed:
```
bool P(int32_t i)
{
string a,b;
stringstream ss;
ss<<i;
ss>>a;
b=a;
reverse_copy(b.begin(),b.end(),b.begin());
int k=a.compare(b);
return (k==0);
}
int main()
{
int32_t n; cin>>n;
int32_t x=0,y=n,z=n,ans=x;
while(1)
{
if(P(y)){ans=x; break;}
if(P(z)){ans=-1*x; break;}
x++;
y+=x;
z-=x;
}
cout<<ans<<endl;
return 0;
}
```
[Answer]
## Mathematica 75
Probably can be golfed more..
```
p = (j=0; b=#; While[a=IntegerDigits[b]; b += ++j(-1)^j; a!=Reverse[a]]; #-b+(-1)^j) &
```
Spaces not counted and not needed.
[Answer]
# CoffeeScript: 73
```
(x)->(x+="")[0...(y=x.length/2)]+x[0...-y].split("").reverse().join("")-x
```
**Explanation:**
This takes advantage of the fact that if we have a number of odd length (say 1234567), `x.slice(0, y)` won't include the middle digit but `x.slice(0, -y)` will. JavaScript's `slice` probably *shouldn't* work this way, but it does.
I was expecting CoffeeScript/JavaScript to have a better way to reverse a string, but the split/reverse/join method seems to be all there is.
[Answer]
# PHP, 56 bytes
```
for(;strrev($i+$n=$argv[1])-$n-$i;$i=($i<1)-$i);echo+$i;
```
takes input from command line argument; run with `-nr`.
[Answer]
# javascript 68 bytes
```
(n,s=[...(''+n)],j=s.length)=>s.map((v,i,)=>i>--j?s[j]:v).join('')-n
```
HUGE props to @Beldraith for the algorithm, i'm posting this as an answer though, because it took me quite the time to get it to work in a single statement.
Any tips are welcome ;)
### ungolfed
```
(
n, // input
s=[...(''+n)], // input split to array of chars
j=s.length, // highest available index in s
)=>
s.map( // this will return a new array, without modifying s
(
v, // value of current iteration
i, // index of current iteration
)=> i > --j ? s[j] : v
).join('') - n
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~55~~ 54 bytes
```
l=lambda n,d=0:`n+d`!=`n+d`[::-1]and l(n,~d+(d<0))or d
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P8c2JzE3KSVRIU8nxdbAKiFPOyVB0RZMRVtZ6RrGJualKORo5OnUpWhrpNgYaGrmFymk/C8oyswr0cjRMNbU5IKxjYxNkHiGRpaWlsaGKCJmmpr/AQ "Python 2 – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 8 bytes
```
nȥsw}cU
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=bsilc3d9Y1U&input=MTI2)
```
nȥsw}cU :Implicit input of integer U
cU :Get the first number in the sequence [U,U-1,U+1,U-2,U+2,...,U-n,U+n]
È :That returns true when passed the the following function
¥ : Test for equality with
s : Convert to string
w : Reverse
} :End function
n :Subtract U from the result
```
[Answer]
# [Raku](https://raku.org/), 45 bytes
```
{($_,{++$*($*=-1)+$_}...{$_==.flip})[*-1]-$_}
```
[Try it online!](https://tio.run/##DcjRCkAwFAbgV/nTSWy2mkmtHC8iLRdWiogrLc8@u/rqu9Z779PxogzgFCvyTZSSREWClakl@U9rHckz67Bv11dPQplZ5U/P8qIgDx4RA/IUCOeNwaK1HUzrnLMm24/pBw "Perl 6 – Try It Online")
* `$_, { ... } ... { ... }` defines a sequence that starts with the input argument `$_`.
* The first set of braces `{ ++$ * ($ *= -1) + $_ }` generates each term of the sequence from the previous one. It uses two anonymous state variables, both written as `$`. The first one increments on each call to the block, and the other alternates between -1 and +1. Multiplying them together and adding to the previous element gives the sequence `$_, $_ + 1, $_ - 1, $_ + 2, $_ - 2, ...`.
* The second set of braces `{ $_ == .flip }` is the terminating condition, met by the first number which is equal to itself with the digits flipped (reversed).
* `[* - 1]` picks the last element of the sequence (the palindromic one).
* `- $_` subtracts the input element to give the required difference.
[Answer]
Python, 109
```
def q(x,z):
r=lambda s:int(str(s)[::-1])
if x+z==r(x+z):return z
if x-z==r(x-z):return -z
return q(x,z+1)
```
[Answer]
## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 38 bytes, nc
```
:{[-1,1,2|A=!a+b*c$~A=_fA||_xb*c]c=c+1
```
Explanation:
The code reads an input, and then applies a modifier. It then tests to see if the number + modifier is a palindrome. Then, it flips the sigh on the modifier, re-applies that and tests again.
```
:{ Read the input value, start a DO-loop
[-1,1,2| FOR (b = -1; b <= 1; b+=2 )
A=!a+b*c$ Get a string from the input number,
plus modifier c (which is 0 at the start of QBIC)
times -1 or 1, depending on b's iteration.
~A=_fA| if that string is equal to it's own reversed version
|_xb*c] then Quit, printing the modifier * sign
c=c+1 Increment the modifoer and DO-LOOP again.
The DO-loop is implicitly closed by QBIC at EOF
```
[Answer]
# Bash, 73 bytes
```
i=$1;x=$i;while((x-10#$(rev<<<$x)));do ((r=(1>r)-r,x=r+i));done;echo $x
```
Input goes to the 1st command line argument:
```
foo.sh 123456789
```
[Answer]
# Axiom, ~~720~~ ~~594~~ 412 bytes
```
R(x)==>return x;p(r,a)==(n:=#(a::String);if r<0 then(a=0=>R a;n=1 or a=10^(n-1)=>R(a-1);a=10^(n-1)+1=>R(a-2));if r>0 then(n=1 and a<9=>R(a+1);a=10^n-1=>R(a+2));r=0 and n=1=>1;v:=a quo 10^(n quo 2);repeat(c:=v;w:=(n rem 2>0=>v quo 10;v);repeat(c:=10*c+w rem 10;w:=w quo 10;w=0=>break);r<0=>(c<a=>R c;v:=v-1);r>0=>(c>a=>R c;v:=v+1);R(c=a=>1;0));c)
D(a:NNI):INT==(p(0,a)=1=>0;w:=p(-1,a);s:=p(1,a);a-w<s-a=>w-a;s-a)
```
The byte count it is again this, but the algo it would be O(log(n)) because it would dipend only from the digit lenght of its input (and log10(n) would be near the lenght of the decimal digits of n).
ungolfed and results
```
-- Ritorna il precedente numero palidrome rispetto ad 'a' NNI, se r<0
-- ha la particolarita' palpn(-1,0) = 0
-- Ritorna il successivo numero palidrome rispetto ad 'a' NNI, se r>0
-- Se r=0 ritorna 1 se 'a' e' palindrome, 0 se 'a' non e' palindrome
R(x)==>return x
palpn(r,a)==
n:=#(a::String) -- n la lunghezza in cifre di base 10 di a
if r<0 then(a=0 =>R a;n=1 or a=10^(n-1)=>R(a-1);a=10^(n-1)+1=>R(a-2))
if r>0 then(n=1 and a<9=>R(a+1); a=10^n-1 =>R(a+2))
r=0 and n=1=>1
v:=a quo 10^(n quo 2)
repeat -- because here not there is a goto instruction i have to use repeat
c:=v;w:=(n rem 2>0=>v quo 10;v)
repeat
c:=10*c+w rem 10
w:=w quo 10
w=0=>break
r<0=>(c<a=>R c;v:=v-1)
r>0=>(c>a=>R c;v:=v+1)
R(c=a=>1;0) -- for r==0
c
-- Ritorna la distanza minima tra l'input 'a' e una palindrome:
-- 0 se 'a' e' una palindrome
-- r numero con segno negativo se tale palindrome precede 'a'
-- r numero con segno positivo se tale palindrome e' successiva ad 'a'
palDistance(a:NNI):INT==
palpn(0,a)=1=>0
p:=palpn(-1,a);s:=palpn(1,a)
a-p<s-a=>p-a
s-a
--------------------------------------
(3) -> [[i,D(i)] for i in [3,10,234,1299931,126]]
(3) [[3,0],[10,1],[234,- 2],[1299931,- 10],[126,5]]
Type: List List Integer
(4) -> D 7978986575546463645758676970789089064235234524548028408198401348930489104890184018410
(4) - 199223418598327604580355025458434427119613
Type: Integer
(5) -> p(0,7978986575546463645758676970789089064235234524548028408198401348930489104890184018410+%)
(5) 1
Type: PositiveInteger
(6) -> 7978986575546463645758676970789089064235234524548028408198401348930489104890184018410+%%(-2)
(6)
7978986575546463645758676970789089064235234325324609809870796768575463646455756898797
Type: PositiveInteger
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~16 12~~ 9 bytes
```
ḟoS=↔+⁰İZ
```
Thanks @H.PWiz for -4 bytes!
[Try it online!](https://tio.run/##yygtzv7//@GO@fnBto/apmg/atxwZEPU////DY0sLS2NDQE "Husk – Try It Online")
### Explanation
```
ḟ(S=↔+⁰)İZ -- input ⁰ a number, for example: 126
İZ -- built-in integers: [0,1,-1,2,-2...]
ḟ( ) -- first element that satisfies the following (eg. 5):
+⁰ -- add element to input: 131
S= -- is it equal to itself..
↔ -- ..reversed: 131 == 131
```
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.