text
stringlengths 180
608k
|
---|
[Question]
[
In this challenge you are going to place letters from the alphabet in a Cartesian plane and output the result as a text.
Your input will consist in a list of list with 3 parameters:
* X coordinate
* Y coordinate
* String
**How?**
We know that a Cartesian plane contain 2 axes \$(X, Y)\$ and 4 quadrants where the signs of the \$(X,Y)\$ coordinates are \$(+,+)\$, \$(−,+)\$, \$(−,−)\$, and \$(+,−)\$. For example
Consider the following 3 by 3 matrix as a Cartesian plane
\begin{matrix} (-1,1) & (0,1) & (1,1) \\ (-1,0) & (0,0) & (1,0) \\ (-1,-1) & (0,-1) & (1,-1) \end{matrix}
If we are given in the input something like `[[-1,1,L],[0,1,F]]` our matrix will look something similar to
\begin{matrix} L & F & (1,1) \\ (-1,0) & (0,0) & (1,0) \\ (-1,-1) & (0,-1) & (1,-1) \end{matrix}
And the final output `LF`
In addition to that there are some points we need to follow in order to get the correct output:
* When a X,Y coord is repeated, you will need to concatenate the strings. Example: assume in (-1,1) the string `F` is placed and you need to place the string `a` in the same point. You concatenate both strings resulting in `Fa` and that is the value that will go in (-1,1).
* Your output need to be consistent to the matrix. Example imagine this as your final result:
\begin{matrix} Ma & r & ie \\ i & s & (1,0) \\ cute & (0,-1) & (1,-1) \end{matrix}
You must output
```
Ma rie
i s
cute
```
**Why?**
You can view this as a table where the columns are the values of the x-axis and the rows the y-axis.
```
Column 1 | Column 2 | Column 3
----------------------------------------
Row 1 | "Ma" | "r" | "ie"
Row 2 | "i" | "s" |
Row 3 | "cute" | |
```
All columns values must have the same length
```
Column 1 | Column 2 | Column 3
----------------------------------------
Row 1 | "Ma " | "r" | "ie"
Row 2 | "i " | "s" |
Row 3 | "cute" | |
```
Finnaly we output the result
```
Ma rie
i s
cute
```
---
**Test Cases**
```
Input
------------
[[3, 3, "c"]
[4, 1, "un"]
[5, 3, "e"]
[4, 3, "od"]
[4, 2, "lf"]
[1, 2, "go"]
[2, 1, "i"]
[2, 1, "s f"]]
Output
--------------
code
go lf
is f un
```
---
```
Input
--------------
[[0, 0, 's'],
[-1,1, 'M'],
[0, 1, 'r'],
[-1,1, 'a'],
[1, 1, 'i'],
[-1, 0, 'i'],
[1, 1, 'e'],
[-1,- 1, 'c'],
[-1,- 1, 'u'],
[-1, -1, 'te']]
Output.
----------------
Ma rie
i s
cute
```
---
**Notes**
* This is supposed to be [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")
* You can wrap the coordinates in a single list e.g `[[3, 3], "c"]`
* You can take the input in any reasonable format
* You can assume there wont be any number or empty spaces only in the input. e.g. There can be something like `a a` but never `1` or `" "` or `1a` or `1 1`
[Answer]
# JavaScript (ES8), ~~186 180~~ 179 bytes
*Saved 1 byte thanks to @Shaggy*
```
a=>(g=d=>a.some(([x,y,s])=>(w[x+=d]>(l=((r=o[y=d-y]=o[y]||[])[x]=[r[x]]+s).length)||(w[x]=l),x|y)<0,w=[o=[]])?g(-~d):o.map(r=>w.map((w,x)=>(r[x]||'').padEnd(w)).join``).join`
`)``
```
[Try it online!](https://tio.run/##XZDdboMgGIbPvQriiXwpGu22k2W4ox3uCgiJpKBtY6UROzUhu3Un86e2hAB5eHj54Cx@hDnUp2sTVlqqIaeDoCkuqKSpiIy@KIxZR3piOIy8Zd2OSp7ikmJcU816KsOeuwW3lnFgHaesHke@MxCVqiqaI1jrDnJaAulsDx8xaSnTlHEOnwUOfyW86@girmNi2v4vcEs6d59LsjYIILoK@VVJ3AJEZ32qsmyevQyybDjoyuhSRaUucI6ZhxB7IWjs/sFHiBMHXglKRnCr/Bm8TYbaGg5o6d/BfgRlvoBkAoVewH4KPa0ZMzAo97nHAbxtaUG4tuBxZy4axcR13yz5YTLlfS/AbTtQPxtiNZK1prsRb8FiqI3hJPdZj@D2DBo1PWv4Aw "JavaScript (Node.js) – Try It Online")
### Negative indices in JS (or the lack of them)
Given an array `A[]`, it's perfectly legal in JS to do something like `A[-1] = 5`. However, this will **not** save the value in the array itself. Instead, it will implicitly coerce this negative index to a string (`"-1"`) and set the corresponding *property* in the **surrounding object** of the array.
The bad news is that properties are not iterable with methods such as `map()`:
```
a = [];
a[1] = 3;
a[-1] = 5;
a.map((v, i) => console.log(v + ' is stored at index ' + i))
```
[Try it online!](https://tio.run/##HcpLCoAgFEbheav4Zyk9IKJR1EaiwSUlDPNGirR7s2Yfh3NQJL/d5gqNY6VTIkxY1rGgpVsz@0/NzyGzPekSItYwEtOMjZ1nq1vLu4ioUMJ4@MC3VqAA45R@cqzyLlN6AQ "JavaScript (Node.js) – Try It Online")
The above code will only display `3 is stored at index 1`.
A possible workaround would be:
```
a = [];
a[1] = 3;
a[-1] = 5;
Object.keys(a).map(k => console.log(a[k] + ' is stored with key ' + k))
```
[Try it online!](https://tio.run/##HctBCsIwEEbhfU/x70woDYi4KvUKHiBkMU0HTVM7pQlKTx@ju48Hb6Y3Jb@HLXerTFwKYYB1fUP27CovP3V/XvvmPs7ss4l8JEXavGhTEcMNXtYkC5tFHopsdGhxQkhIWXae8An5iTrV2CJqXcoX "JavaScript (Node.js) – Try It Online")
But:
* This is not very golf-friendly.
* The keys are not sorted in numerical order.
### What we do here
We definitely want to work with positive values of both \$x\$ and \$y\$ in order to avoid the problems described above.
We could do a first pass on the data, looking for the minimum value of \$x\$ and the minimum value of \$y\$. But that would be quite lengthy.
Here's what we do instead:
* we start with \$d=0\$
* we process an iteration where \$x\$ is replaced with \$x+d\$ and \$y\$ is replaced with \$d-y\$
* if we have either \$x<0\$ or \$y<0\$ for any entry, we abort and recursively start another attempt with \$d+1\$
[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 infix lambda taking\* lists of coordinates and strings as left and right arguments.
```
{⊃,/↑¨↓⌽m⊣m[c],←⍵⊣m←(⊃⌈/c←1+⍺-⌊/⍺)⍴⊂''}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pRV7OO/qO2iYdWPGqb/Khnb@6jrsW50cmxOo/aJjzq3QriAVkaQGWPejr0k4FsQ@1Hvbt0H/V06QNpzUe9Wx51Namr1/5PA@voe9Q31dMfqPzQemOgsUBecJAzkAzx8Az@r2GgYKCpoHFovaGCIZA2AJMwniGcZ4DCA2LsrDQF9WJ1BXVfIC4C4kQgzoTiVCBOBuJSIC5JVefSMFYwBmo1ARtqCmVDSCOwZSDSCCwLJtOg2vOgZuWnAImcNCCRng@1olghTR0A "APL (Dyalog Unicode) – Try It Online")
`{`…`}` "dfn"; left (coordinates) and right (strings) arguments are `⍺` and `⍵`:
`⊂''` enclosed empty string, so use as fill for an array
`(`…`)⍴` cyclically **r**eshape into an array of the following dimensions:
`⌊/⍺` the lowest value along each axis of the coordinates
`⍺-` subtract that from all the coordinates
`1+` add that to one (since we want the inclusive range)
`c←` store in `c` (for **c**oordinates)
`⌈/` the highest value along each axis of those
`⊃` unpack to use as dimensions
`m←` store in `m` (for **m**atrix)
`⍵⊣` discard that in favour of the strings
`m[c],←` append those to `m` at the coordinates `c`
`m⊣` discard those in favour of the amended `m`
`⌽` mirror
`↓` split into list of lists of strings
`↑¨` mix each list of strings into a character matrix, padding with spaces
`,/` reduce by horizontal concatenation
`⊃` unpack (since reduction reduces rank from 1 to 0)
---
\* If taking a single argument of interwoven coordinates and strings is required, [it will be 5 bytes longer.](https://tio.run/##Vc7BCoJAEAbge08xt1UqXLWgl@gJooOoRaAplYeILgVmolFET9ClW5e6BF16lHkRm10tamHZb352dscKvaYzt7xgWGCygbDAdL2g3dAwPrwuGB8xe/qYnv2e3W9gvMf8LiqSQtcwSzSbrNcxfzQxSzU6VcxvmK4YW2qiP9/i7iReL0CusKZzMOiOwoGrwKYMlNdVB53cJXOpyU9qkUuNqpRXLlO3SmlTZf9V0V81c1ntM0WnHMIEs2pqyceiMbEtQ1eGQoEjaRC9gfxXcBgQje9gpaYwYG8 "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~188~~ ~~185~~ 181 bytes
```
s=sorted;d={};k={}
for x,y,c in input():d[x]=d.get(x,{});k[~y]=d[x][y]=d[x].get(y,'')+c
for y in s(k):print''.join('%*s'%(-max(map(len,d[x].values())),d[x].get(~y,''))for x in s(d))
```
[Try it online!](https://tio.run/##VY9NboMwEIX3PoWFFI2dmghouwli1XZZ9QAWCwROSiE2wlCBouTq1D@kSqSx/b55nie7m4dvJZPl7ev9IwuCYNGZVv0gqrTKzpe0MRs6qB5PbGYlrqWpbhwI3Vd8yrNqdxQDmdj5QtOGX2fTMW2@ns6cGQB9Kl3IbAM0aei@62s5AOx@VC0JbLYaNiQ8FRM5FR1phWRu/rdoR6EJpZT9511dIHVv8nEVpQtygX6HMAxhbSDzJYTEJEpsf7hN0ML5M8OmgjLIGX9hODZ6lBZevSFWw2pVrZAYaA8WYg9HZSHx8/Wd1thcyxHnEcOmQIPxwtiZ8Gkh8rq/Nwrw0VbXNyO6wWqI1QgdlQ803obsgsFczf8A "Python 2 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~45~~ 44 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
WsàŸãεUõIvyнXQiyθ«]IZsß->ôεíDéθgjí}øRJʒðKĀ}»
```
Takes the input-coordinates as an inner list.
[Try it online](https://tio.run/##yy9OTMpM/f8/vPjwgqM7Di8@tzX08FbPssoLeyMCMyvP7Ti0OtYzqvjwfF27w1vObT281uXwynM70rMOr609vCPI69Skwxu8jzTUHtr9/390dLSBjoJBrI6CUrESkIyO1jXUUTAE8X0hfAMotwhNOhHCh3EzEdIGSHyYdCpCWhcskIwuUIouUALUEwsA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaCkU6mj5F9aAuO4hP0PLz684OiOw4vPbQ09vDWyrPLC3ojAzMpzOw6trq2tjYwqPjxf1@7wlnNbD691Obzy3I70rMNraw/vCPI6NenwBu8jDbWHdv/XObTN/n80EBjrKBjH6igoJSsByehoEx0FQxC3NA/CN4VKp8Klwdz8FDjfCMTPSYPwDaH89HwI3whqXCYqt1gBqB4sEm2go2AAFoKo0DWEKvGF8A2g3CI06US4fcjmg6QNkPgw6VSEtK4hkm8RAqXoAiWpMBfC7fRBdZIbUEEsAA).
**Explanation:**
```
Wsà # Get the minimum and maximum of the (implicit) input-list
Ÿ # Create a list in the range [min, max]
ã # Create each possible pair by taking the cartesian product with itself
ε # Map each coordinate to:
U # Pop and store the coordinate in variable `X`
õ # Push an empty string ""
Iv # Loop `y` over the input-items:
yн # Get the coordinates of item `y`
XQi # If it's equal to variable `X`:
yθ # Get the string of item `y`
« # Concat it to the (non-)empty string
] # Close the if-statement, loop, and map
IZsß # Get the maximum and minimum of the input-list
- # Subtract them from each other
> # And increase it by 1
ô # Split the list into parts of this size
ε # Map each part to:
í # Reverse each inner string
Déθg # Get the length of the longest inner string
j # Prepend spaces to each item up to that length
í # And reverse every item back again
# (so the spaces are trailing instead of leading)
}ø # After the map: zip/transpose; swapping rows/columns
R # Reverse the entire list
J # Join each inner list together to a single string
ʒðKĀ} # Remove all strings consisting only of spaces
» # Join the strings by newlines (and output implicitly)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 60 bytes
```
≔Eθ§ι¹η≔Eθ§ι⁰ζF…·⌊ζ⌈ζ«≔E…·⌊η⌈η⭆θ⎇∧⁼ι§μ⁰⁼κ§μ¹§μ²ωε⮌εM⌈EεLκ±Lε
```
[Try it online!](https://tio.run/##dY8xb4MwEIXn8CusTGfJlRraTp0YOkQqVZV2QwwWXIwVMI0NNE3V307PYKRkiOTB3917d@@KStqilfU4Js5pZSCVX3AULOm2psQTaME2nAtW8efopuLeK86k2LeWwdYUde/0gDtpFEKqjW76Bs6kSeUp/Dlnv9HqYuINV3Xhqvyaj85qo0KGT7RG2h9ITAkvx17WzsdZkjUhWegcrjp0Fb8qxITfUxHpktU7relghwNah4Dc19J2oGQhjY@Agr2iUV0Fh8n5hkp2CKFGJnL9jWOWZQ@C0VsX61xE2SOtJ@jNRE9zC5eWh7ZcKCaq9xNtZlLtRPE8RF@CY6TM8/FuqP8B "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔Eθ§ι¹η≔Eθ§ι⁰ζ
```
Extract the coordinates from the input.
```
F…·⌊ζ⌈ζ«
```
Loop over the x-coordinates.
```
≔E…·⌊η⌈η⭆θ⎇∧⁼ι§μ⁰⁼κ§μ¹§μ²ωε
```
Loop over the y-coordinates, extracting and concatenating all of the strings at the given coordinates.
```
⮌ε
```
Print the strings in reverse order as the y-coordinates are reversed compared to Charcoal's coordinate system.
```
M⌈EεLκ±Lε
```
Move to the start of the next column.
[Answer]
# Perl 5 `-p00` `-MList::Util=max`, 148 bytes
```
s/(\S+) (\S+) (.*)
/$a{$1}=max$a{$1},length($h{$2}{$1}.=$3);''/ge;for$y(sort{$b-$a}keys%h){map{printf"%-$a{$_}s",$h{$y}{$_}}sort{$a-$b}keys%a;say""}
```
[TIO](https://tio.run/##LZDPioMwEIfveYogkWprNNH1UukbbE/L3haWtI1/WDViUliRvPpmJ1UY5ss3zPwOmeTcl25YolAkYRtXTmfR18cpxntPjzHKiFgJt5dB/G6vpJdjY9qItCvJrZ@kF1LE1eGQNbKq1UyWSKvZrORGibA/ctGQvQ5iWqe5G00dhNQnfVsdJD5ksV7sdiMouW03otJiCQLrXIELfEdvmOPniEoQCVJg9QDkuK8RBzQK5bDRvbrGNUIMM6wR5eBXEI7nTQTir0UQBvAivUDddz53Gon@1GQ6NWpHJ8YcvZYp44D3Tpvz@dN0vf@Zfw)
How
* `s/(\S+) (\S+) (.*)
/` ... `;''/ge;`, substitution flags `/g` loop `/e` eval, replacement evaluates to empty clearing line input/default variable
* `$a{$1}=max$a{$1},length($h{$2}{$1}.=$3)`, autovivifies a map %h of map whose first level keys `y` second level `x` and concatenate string `$3` to the value, get the length and autovivifies a second map %a whose keys `x` and value the max of length over the column (`x`)
* `for$y(sort{$b-$a}keys%h){` ... `;say""}`, for row indices `$y` in keys of `%h` sorted numerically reverse, `say""` at the end to print a newline
* `map{` ... `}sort{$a-$b}keys%a`, for column index `$_` in keys %a sorted numerically
* `printf"%-$a{$_}s",$h{$y}{$_}`, print string aligned to the left with column width
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), ~~212~~ 206 bytes
```
import StdEnv,StdLib
? =minList
m=maxList
c=flatten
$a#(x,y,z)=unzip3 a
=flatlines(map c(transpose[[ljustify(m(map length l))k\\l<-[reverse[c[s\\(u,v,s)<-a|u==i&&v==j]\\j<-[?y..m y]]],k<-l]\\i<-[?x..m x]]))
```
[Try it online!](https://tio.run/##VdDPa8MgFAfwe/4KYaVVMIW26y3Sy3YY5NZj4sFak5mqCVFDUva3LzM/KAwE/bzv44GPK8HMqOu7VwJoJs0odVO3Dlzd/dN0OFypvEUXQLQ0qbQu0kSzfn5xUijmnDDRhr3BHg/4iYg3T9mcAIvmUEkjLNSsARy6lhnb1FZkmaq8dbIYoJ4zJUzpvoFC6JHnKomzVnSiDY08s3kOPe6wRUnMfjwhcrvtCKlonleh8TLs9xoMlFL8SGIVqnKq9lO1pxSh8epY@A0BmwyeMAgn2/EdRRjAdwwOE71ZfF5j8Ypn1veXj5NVsfiwuqwXH9dx8j8tmPrp@MvDPko7xl/p@DEYpiUPuM1elvwH "Clean – Try It Online")
] |
[Question]
[
# How the encoding works
Given a list of bits:
* Hold a prime (starting with `2`)
* Have a list
* For each bit in the input
+ If it's the same as the previous bit, add the prime you're holding to the list
+ If it's different, hold the next prime and add that to the list
* Return the product of all the numbers in your list
* For the first bit, assume the previous bit was `0`
>
> Note: these steps are for illustration purposes only, you are not required to follow them.
>
>
>
# Examples
```
Input: 001
hold 2
0: add 2 to the list
0: add 2 to the list
1: hold 3, add 3 to the list
list: 2,2,3
Output: 12
```
---
```
Input: 1101
hold 2
1: hold 3, add 3 to the list
1: add 3 to the list
0: hold 5, add 5 to the list
1: hold 7, add 7 to the list
list: 3,3,5,7
Output: 315
```
### Some more examples:
```
000000000 -> 512
111111111 -> 19683
010101010 -> 223092870
101010101 -> 3234846615
011101101 -> 1891890
000101101010010000 -> 3847834029582062520
```
# Challenge
Write an encoder **and** a decoder for this encoding method.
(The decoder reverses the process of the encoder).
# Input / Output
* The encoder can take input in [any reasonable format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods)
* The encoder must output either an integer or a string
* The decoder must take input in the same format that the encoder outputs
* The decoder must output the same format that the encoder takes as input
In other words `decoder( encoder( input ) ) === input`
### Notes
* The decoder may assume that its input is decodable
* Your answer only has to deal with integers that your language can natively support without using (`long`, `bigInt`, etc.), be reasonable, if you language only supports ints up to 1, maybe reconsider posting an answer
# Scoring
Your score is the sum of the lengths in bytes of the encoder and decoder.
If you need to import a module, the import can be counted only once provided that your encoder and decoder can coexist in the same file and be reused (like functions).
[Default 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 the shortest score for every language wins.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 13 bytes
## Encoder, 8 bytes
```
0ì¥ĀηOØP
```
[Try it online!](https://tio.run/##MzBNTDJM/V9TVvnf4PCaQ0uPNJzb7n94RsD/SqXD@xV07RQO71fS@W9gYMhlaAgkDGAAyIUCLgNDKOSCMcDqgBSEB0IgAgA "05AB1E – Try It Online")
**Explanation**
```
0ì # prepend 0 to input
¥ # calculate deltas
Ā # truthify each
η # calculate prefixes
O # sum each
Ø # get the prime at that index
P # product
```
## Decoder, 5 bytes
```
Ò.ØÉJ
```
[Try it online!](https://tio.run/##Fcm7DYAgEADQnimItRruw3E0DuAWmriCCYkL2Fq5DcUNhli94oW47XC06yzNntleu9dWBqt@WrzVYWyAjiC62IUsSg6RQkZNwRESK4v8rZRAGLFHzKrKqBw@ "05AB1E – Try It Online")
**Explanation**
```
Ò # get prime factors of input
.Ø # get their indices among the primes
É # check for oddness
J # join
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
### Encoder (10 bytes):
```
0;IA+\‘ÆNP
```
**[Try it online!](https://tio.run/##y0rNyan8/9/A2tNRO@ZRw4zDbX4B////jzbQAUFDMDaEswzgJBDGAgA "Jelly – Try It Online")**
### Decoder (7 bytes):
```
ÆEĖŒṙḂ¬
```
**[Try it online!](https://tio.run/##ASwA0/9qZWxsef//w4ZFxJbFkuG5meG4gsKs////Mzg0NzgzNDAyOTU4MjA2MjUyMA "Jelly – Try It Online")**
### How?
Encoder:
```
0;IA+\‘ÆNP - Link: list of integers (1s and 0s) e.g. [1,1,1,1,0]
0; - prepend a zero [0,1,1,1,1,0]
I - incremental differences [1,0,0,0,-1]
A - absolute values [1,0,0,0,1]
+\ - cumulative reduce with addition [1,1,1,1,2]
‘ - increment each of the results [2,2,2,2,3]
ÆN - get the nth prime for each result [3,3,3,3,5]
P - product of the list 405
```
Decoder:
```
ÆEĖŒṙḂ¬ - Link: integer e.g. 405
ÆE - prime exponent array [0,4,1] (representing 2^0*3^4*5^1)
Ė - enumerate [[1,0],[2,4],[3,1]]
Œṙ - run-length decode [2,2,2,2,3]
Ḃ - bit (mod 2) [0,0,0,0,1]
¬ - logical NOT [1,1,1,1,0]
```
[Answer]
# JavaScript (ES6), 130 bytes
**I/O:** array of bits ↔ integer
## Encoder, 71 bytes
```
a=>a.map(p=k=>r*=(g=i=>n%--i?g(i):i<2?n:g(++n))(n+=p^(p=k)),r=1,n=2)&&r
```
[Try it online!](https://tio.run/##dc7PCoJAEAbwu0/hJdnJ9e9RGj35FFGwmSxrNrus0utvBSa1GB8zh@HHxwziIabOKjMnpK@9a9EJrEV6F4YZvGFt98gkKqxplySqkUxBpQ5lQ5VkcUwAjGI05zcG4BYLTlhCFFnXaZr02Kejlqxlx5x7OQEEnim4lw2Tv@4/s9njqT89xSJWE2RZOGsdXpQMNv//8st8dr5@454 "JavaScript (Node.js) – Try It Online")
## Decoder, 59 bytes
```
D=(n,k=2,x=b=0)=>k>n?[]:n%k?D(n,k+1,1):[b^=x,...D(n/k,k,0)]
```
[Try it online!](https://tio.run/##ZYzLCsIwFAX3/oeQ4DXm0cakcNtN/6JUaGsRTUnEivTvY1xK4KxmmPMYPsM6ve7P99GH6xxji8SDQwkbjsgp1q72TddXfu@a9qcOAgStuvGCGzDGEjs5cMBpH6fg17DMbAk30pJSSEp3/0xYbVRGpVTcSnPmmVFSFabQWpT5lbFpKYlf "JavaScript (Node.js) – Try It Online")
[Answer]
# Java 10, 209 bytes
## Encoder, 124 bytes
```
s->{long p=48,P=2,r=1,n,i;for(int c:s.getBytes()){if(p!=(p=c))for(n=0;n<2;)for(n=++P,i=2;i<n;n=n%i++<1?0:n);r*=P;}return r;}
```
[Try it online.](https://tio.run/##jY/BasMwEETv@YptoCDVjrFCDyWyWui9wZBj6UFV5KDUWRtJDgTjb3fl2OmtxKsVaLWPYeYoz3J13P/0qpTOwYc02C4ADHptC6k0bIcRoKzwAIrsvDXh4SgPv124oZ2X3ijYAoKA3q1e2ytci@eXOBfr2AoWY2x4UVkSdEFtXHLQ/v3itSOUtqYg9YMgtVCUDgyKlGO25tMQRXlsxJqbDDkKfDRRlLG3dIOU2yeR885q31gEy7uej47q5rsMjiZj58rs4RSCTe4/v0DSMdXu4rw@JVXjkzqsfIkEE0WWacqW9Jrxf4axGVB6qxlyU93XZNO5r3lD5/gM2EgP/We4W3T9Lw)
**Explanation:**
```
s->{ // Method with String parameter and long return-type
long p=48, // Previous character, starting at '0'
P=2, // Current prime, starting at 2
r=1, // Result, starting at 1
n,i; // Temp-integers
for(int c:s.getBytes()){
// Loop over the digits of the input-String as bytes
if(p!=(p=c)) // If the current and previous digits are different
for(n=0; // Reset `n` to 0
n<2;) // And loop as long as `n` is still 0 or 1
for(n=++P, // Increase `P` by 1 first with `++P`, and set `n` to this new `P`
i=2;i<n;n=n%i++<1?0:n);
// Check of the current `n` is a prime
// If it remains the same it's a prime, if it becomes 0 or 1 not
r*=P;} // Multiply the result by the current prime `P`
return r;} // Return the result
```
## Decoder, 85 bytes
```
n->{var r="";for(long P=2,f=0,i=1;++i<=n;)for(;n%i<1;n/=P=i)r+=i!=P?f^=1:f;return r;}
```
[Try it online.](https://tio.run/##hY5ha4MwEIa/91fcCgPF1plEbVya7Q9sRdjHsUFmdaSzZ4lRGMXf7tLZfRzCHcfdvXfvc1C9Wh/2X2NRq7aFZ6XxvADQaEtTqaKE3aUFeLFG4ycUXt24gr5w08Gli9YqqwvYAYKEEdcP514ZMHK5FFVjpoNc0pWWZFXJSASB3koU/mUp8FZvicA7mUvtm0DqG5k/Vu@S3FfClLYzCEYMo5isTt1H7ayujn2j93B0xN5E9/oGyr/ifre2PIZNZ8OTW9kaPQwLj9An/xf9XwUjyZwkmf9CspSzORGlLMoo30SzTJTFPE7TeTTG4w1ncUSzhNMopQn9ez4shvEH)
**Explanation:**
```
n->{ // Method with long parameter and String return-type
var r=""; // Result-String, starting empty
for(long P=2, // Current prime, starting at 2
f=0, // Flag integer, starting at 0
i=1;++i<=n;) // Loop `i` in the range [2,`n`]
for(;n%i<1; // Inner loop over the prime factors of `n`
n/=P=i) // After every iteration: divide `n` by `i`,
// and set `P` to `i` at the same time
r+=i!=P? // If `i` and `P` are not the same
f^=1 // Append the opposite of the flag `f` (0→1; 1→0)
: // Else:
f; // Append the flag `f`
return r;} // Return the result
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 18 [bytes](https://github.com/barbuz/Husk/wiki/Codepage)
### Encoder, 11 bytes
```
Πmo!İp→∫Ẋ≠Θ
```
[Try it online!](https://tio.run/##yygtzv7//9yC3HzFIxsKHrVNetSx@uGurkedC87N@P//f7ShDgQaxAIA "Husk – Try It Online")
### Decoder, 7 bytes
```
mȯ¬%2ṗp
```
[Try it online!](https://tio.run/##yygtzv7/P/fE@kNrVI0e7pxe8P//fxMDUwA "Husk – Try It Online")
### How they work
Encoder:
```
Πmo!İp→∫Ẋ≠Θ – Full program. Takes input from the first CLA, outputs to STDOUT.
Θ – Prepend a default element (0 in this case).
Ẋ≠ – Map over pairs of adjacent elements with ≠ (not equals). In Husk,
some operators return other useful things than just boolean values.
Here, ≠ returns the absolute difference between its two arguments.
∫ – Cumulative sums.
mo – Map the following function over the list of sums:
İp – Yield the infinite list of primes.
! → – And index into it with the current sum incremented.
Π – Take the product.
```
Decoder:
```
mȯ¬%2ṗp – Full program.
p – Prime factorization.
mȯ – Map the following function over the list of factors:
ṗ – Retrieve the index in the list of primes.
%2 – Modulo 2.
¬ – Logical NOT.
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~234~~ ~~193~~ 174 bytes
## Encoder, ~~116~~ ~~101~~ 97 bytes:
Uses [Wilson's theorem](https://en.wikipedia.org/wiki/Wilson's_theorem).
```
i=input()
P=n=x=r=1
while i:
P*=n*n;n+=1
if P%n:t=(i+[x]).index(x);i=i[t:];r*=n**t;x^=1
print r
```
[Try it online!](https://tio.run/##VYzBCsIwEETv@Yq9CEkq0nhM2H/IPcSTlS7IGsJK49fHiIgUhmHeMEx5yfrgc@@ExOUp2qiIjA0rOrWtdF@AvIJokS0HnkYLdIN4YC@oaUotmxPxdWm6mTBOkvgc6mduJbTL2JdKLFB7T/MRvnI/d3uc9@GP@Q0 "Python 2 – Try It Online")
## Decoder, ~~118~~ ~~92~~ 77 bytes:
```
i=input()
r=[]
n=x=1
while~-i:
n+=1;x^=i%n<1
while i%n<1:r+=x,;i/=n
print r
```
[Try it online!](https://tio.run/##HcnBCoMwDADQe76iF2GiY2tWbabLl4jeBAMjltKxetmvd@Dx8cKRtl2xFGHR8EmXGiJPMyhntvDd5L3@rjKA0YbtmBeWSl8WzDnmxBAbzu0oN1YIUTSZWEpHD297h4jkuycROSR3/wM "Python 2 – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 34 bytes
Heavily inspired by Jonathan Allan's Jelly solution!
## Encoder: 23 bytes
```
[:*/[:p:[:+/\2|@-~/\0,]
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o6209KOtCqyirbT1Y4xqHHTr9GMMdGL/a3IpcKUmZ@QrpAEVGygYwjiGQIjENYBwkTCyLpgosjyMBMH/AA "J – Try It Online")
```
0,] NB. prepend 0 to the input
2 -~/\ NB. find the differences
|@ NB. and their absolute values
[:+/\ NB. running sums
[:p: NB. n-th prime
[:*/ NB. product
```
I don't like those many cap forks `[:` - it should be golfable.
## Decoder: 11 bytes
```
2|[:_1&p:q:
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/jWqireIN1QqsCq3@a3IpcKUmZ@QrpCkYGsFYxoamMKaRkbGBpZGFuQFczsLE3MLYxMDI0tTCyMDMyNTI4D8A "J – Try It Online")
```
q: NB. prime factorization
[:_1&p: NB. find the number of primes smaller than n
2| NB. modulo 2
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes
### Encoder, 9 bytes
```
0;ŒgL€ÆẸH
```
[Try it online!](https://tio.run/##y0rNyan8/9/A@uikdJ9HTWsOtz3ctcPj/8Mdm8KAPJBAO5DwBqowMFQwNAQSBjAA5EKBgoEhFCrAGCAxkHKoDggLCEHIwAAA "Jelly – Try It Online")
### Decoder, 6 bytes
```
Æf’ÆCḂ
```
[Try it online!](https://tio.run/##y0rNyan8//9wW9qjhpmH25wf7mj6/3DHprDD7Y@a1nj//29opGBsaKpgCqQNLc0sjBWMjIwNLI0szA0UjI2MTSxMzMyA0oYWlkAEFLIwMbcwNjEwsjS1MDIwMzI1MgAA "Jelly – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~180~~ 184 bytes
* Added four bytes so that output formats match.
# 102 bytes -- Encoder
```
p,r,i,m;e(char*_){for(m=0,p=1,i=2;*_;m=*_++-48,p*=i)if(*_-48-m)for(i++,r=2;r<i;i%r++||(r=2,i++));i=p;}
```
[Try it online!](https://tio.run/##PY7PboMwDMbvfYqMiSomRiOoh7YhvfAKPU5CFX86H8KilJ0oz85MB3MO9mf/Psd1eq/refYYkNCZVtZft5BUMHbfQTqbobcayeYmqYyzSaVUejiiTywBdTKpWKUOFpiUwsBgKMhQHJR6PiVr5D6AIevNNDey3DaXcb7gyvEPuSkv2ngGeWcZ@0KDT8N@z9ibY8oD@p9huUw6dTgClh/WL5eZaffetB31rbjKxxBAjMIH6odORvHpIc5nEZ8aUaQXEaFgAEX74sCIRv6Xm@Wzj1hNO3ejXsJ4lVGW6Qg4a70W2RZre42/mV7fqhbTyzfNvw "C (gcc) – Try It Online")
# 82 bytes -- Decoder
```
d(C){for(m=C%2,r=2+m,p=2;C>1;p++)if(C%p<1)p-r&&(m=!m,r=p),putchar(m+48),C/=p,p=1;}
```
[Try it online!](https://tio.run/##PY5NboMwEIX3OYVLReTBg4pRFkmMs@EKWVZCET@pF6Yjh64IZ6dDCh0vPG/8veep03tdz4QBHXrTyvrrFpIKxu47SG8zJKvR2dwklfE2qZRKD0ekxDpwnUwqVqmHBXZKYWAwFM64OCj1fErWyHMA4yyZaW5kuSWXcb7gyvMPuSkv2hCDnFnGVGigNOz3jL15pgiQfoZlM@nV4QhYflhaNuPI3XvTdq5vxVU@hgBiFBRcP3Qyik8PcT6L@NSIIr2ICAUDKNoXB0Y08r/dLJ99xGra@ZvrJYxXGWWZjoBvrdcm22odr/X3ptezqsX08k3zLw "C (gcc) – Try It Online")
[Answer]
# [Gol><>](https://github.com/Sp3000/Golfish), 29 + 39 = 68 bytes
## Encoder, 29 bytes
```
021IEh{$:}-Q$TP:SP?!t$|1k*3R!
```
[Try it online!](https://tio.run/##S8/PScsszvj/38DI0NM1o1rFqlY3UCUkwCo4wF6xRKXGMFvLOEjx/39DLgMuVAwA "Gol><> – Try It Online")
## Decoder, 39 bytes
```
02I:MZ;:2k%:z}Q$TP:SP?!t$|1k,{{-z:N}3R!
```
[Try it online!](https://tio.run/##S8/PScsszvj/38DI08o3ytrKKFvVqqo2UCUkwCo4wF6xRKXGMFunulq3ysqv1jhI8f9/YyNjEwsTMzNDUwA "Gol><> – Try It Online")
### How these work
```
Encoder
021IEh{$:}-Q$TP:SP?!t$|1k*3R!
021 Setup the stack as [last bit, current prime, current output]
IEh Take input as int; if EOF, print top as number and halt
{$:}-Q | If the next bit is different from the last bit...
$ Move the prime to the top
T t Loop indefinitely...
P:SP?! Increment; if prime, skip `t` i.e. break
$ Move the prime to the correct position
1k* Multiply the prime to the output
3R! Skip 3 next commands (the init part)
Loop the entire program until EOF
---
Decoder
02I:MZ;:2k%:z}Q$TP:SP?!t$|1k,{{-z:N}3R!
02I Setup the stack as [last bit, current prime, encoded]
:MZ; If encoded == 1, halt
:2k% Compute encoded modulo prime
:z} Store NOT of the last at the bottom of the stack
Q...| Same as encoder's next-prime loop
1k, Divide encoded by prime (assume it is divisible)
{{ Pull out the two bits at the bottom
-z Compute the next bit
:N} Print as number with newline, and move to the bottom
3R! Skip 3 init commands
Loop the entire program until finished
```
It'd be better if I could golf down the next-prime loop...
] |
[Question]
[
**This question already has answers here**:
[Cantor's unspeakable numbers](/questions/101231/cantors-unspeakable-numbers)
(26 answers)
Closed 6 years ago.
This challenge is based on a drinking game. I advise against alcohol consumption while programming.
In this game, the players count up in turns: the first player says `1`, the second says `2` and so on. Here's the twist however: each number that **is divisible by 7 or has a 7 in its digits** (in base 10) is replaced by another counter. This means `7` is replaced by `1`, `14` is replaced by `2`, `17` is replaced by `3` and so on. For this "sub-sequence", the same rules apply! `35` would be replaced by `7`, which in turn is replaced by `1`. This process repeats until the number is "valid".
Here's a visualization of the first 100 numbers in the sequence:
```
n = 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
gets replaced by:
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
gets replaced by:
1 2 3 4 5 6
final sequence:
1 2 3 4 5 6 1 8 9 10 11 12 13 2 15 16 3 18 19 20 4 22 23 24 25 26 5 6 29 30 31 32 33 34 1 36 8 38 39 40 41 9 43 44 45 46 10 48 11 50 51 52 53 54 55 12 13 58 59 60 61 62 2 64 65 66 15 68 69 16 3 18 19 20 4 22 23 24 25 80 81 82 83 26 85 86 5 88 89 90 6 92 93 94 95 96 29 30 99 100
```
In the final sequence, no number has a seven in its digits or is divisible by seven.
## Input description
* An integer `n` (`1 <= n <= 7777` or `0 <= n <= 7776`)
You may choose whether you use a 0-indexed or 1-indexed input.
## Output description
* The `n`th number in the sequence
## Examples
The examples are 1-indexed. For 0-indexed, subtract one from `n`.
```
n -> f(n)
1 1
5 5
7 1
35 1
77 23
119 1
278 86
2254 822
2255 2255
7777 3403
```
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins!
[Answer]
# Java, ~~122~~ ~~121~~ ~~98~~ 97 bytes
```
int c(int n){int a=0,b=0,c=n;for(;n-->0;c+=a=((--b+"").indexOf(55)&b%7)>>31);return a<0?-b:c(c);}
```
-23 bytes thanks to *@Nevay*.
-1 byte thanks to *@Neil*.
**Explanation:**
[Try it here.](https://tio.run/##hU7BasMwDL33K0ShQ6Z1SNqGbPOSfcHYocexg@24w12ihMTpNkK@PXMKu84C6SHe09O7yKvkTWvoUn7OupJ9Dy/S0jhbcqBxmcTGBWQe75RvnZM4Nx0K4ryIhd7mMkfkXG3XaxZZKs336xnTlN2pTcaK4pAw0Rk3dATyKX7m6lGjZmKaAdpBVVZD76TzcG1sCbV/jifXWfp4ewfJxhX4WiJBDTmQ@botyMSNOP30ztRRM7io9TeuIqwjjQn7n08DfBbgD0GDkEOSPAQU@@w@pNinx7AkHPUv7LSa5l8)
```
int c(int n){ // Method with integer as parameter and return-type
int a=0, // Flag integer
b=0, // Regular counter
c=n; // 7-counter
for(;n-->0; // Loop over the input
c+= // Append `c` with:
a= // Set `a` to:
((--b+"").indexOf(55)&b&7) // If `b` is divisible by or contains 7:
// (and decrease `b` by 1 in the process)
>>31 // Bitwise right shift so `a` is either `-1` or `0`
); // End of loop
return a<0? // If `a` is now -1:
-b // Return the regular counter `b` (as positive)
: // Else:
c(c); // Recursive call with 7-counter `c` as input
} // End of method
```
[Answer]
# [Python 3](https://docs.python.org/3/), 77 bytes
```
g=lambda a:a%7<1or'7'in str(a)
f=lambda a:g(a)and f(sum(map(g,range(a))))or a
```
[Try it online!](https://tio.run/##VYwxDsIwDEX3niILqiOxpKUKIHoYo5JQiTiRGwZOn4YB4Xh6z0/66ZOfkcZS/PzCcF9Q4RUP9mYi97ZfSW2ZAXXn/tlXR1qUg@0dIGACf2Qk/6j/epEVlsQrZXBgtO5@PAm2gscmyGLMRdhgz9KG6dRqO/MdKjs "Python 3 – Try It Online")
[Answer]
## JavaScript (ES6), ~~72~~ 69 bytes
```
f=
n=>[...a=Array(n)].reduce(_=>a[++i]=i%7>7*/7/.test(i)?i:a[++j],i=j=0)
```
```
<input type=number min=1 oninput=o.textContent=f(+this.value)><pre id=o>
```
Edit: Saved 3 bytes thanks to @Shaggy.
[Answer]
# JavaScript, ~~79~~ 75 bytes
*2 bytes saved thanks to [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy)*
```
f=a=>(z=a=>a%7<1|/7/.test(a))(a)?f([...Array(a)].reduce(a=>a+z(b++),b=0)):a
```
[Try it online!](https://tio.run/##LY7LDoIwEEX3fkU3hjZgsSipr2L8DmQxQDEQbElBE4n/XimymHPvTc5iGnhDX5i6GzZKl9LaSoBI8OgIa35h35CHdJD9gIGQ6a4VTimlN2PgM82MGlm@Comd7484930S5GJLyAlsoVWvW0lb/cDpCiEWTIgduMPuX@fO2NFFxA9zRPF@ycVxVkaf0GFAIkGV@4Y2ulbYuyuPkLP9AQ)
[Answer]
# [Röda](https://github.com/fergusq/roda), 65 bytes
```
f a{f#[seq(1,a)|[1]if g _]if g a else[a]}g a{[a%7<1 or"7"in`$a`]}
```
[Try it online!](https://tio.run/##JYnRCsIgGEav21N8rAIFb1wNC3oTke2HNISay3XnfHazdXPOx/liuFMpDpTcXi/2zaQgvmppvMMDw18E@1ysJpPrTpqO6iYRYqtaP40HGk0uL/ITUrNzzHO4EOFRg5YCvYASOP1ULeVVoFOXiq4/b9wepQxWzNFPHzbwJpcv "Röda – Try It Online")
A port of Leaky Nun's [Python answer](https://codegolf.stackexchange.com/a/140172/66323).
[Answer]
# Mathematica, 57 bytes
```
Last[i=1;If[DigitCount[#,10,7]>0||7∣#,i++,#]&~Array~#]&
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~26~~ 23 bytes
```
LÐ7Ösε7å}~_*[¤0Ê#D_O£]¤
```
[Try it online!](https://tio.run/##ASsA1P8wNWFiMWX//0zDkDfDlnPOtTfDpX1@XypbwqQww4ojRF9PwqNdwqT//zM1 "05AB1E – Try It Online")
**Explanation**
```
L # push range [1 ... n]
Ð # triplicate
7Ö # check if number in one copy for equality to 0 after mod by 7
sε7å} # check each number in one copy if they contain 7
~_ # OR these 2 lists and invert
* # multiply with the range,
# giving a list with 0s where the numbers need to be replaced
[¤0Ê# ] # loop until the last number in the list is not 0
D # duplicate the list
_ # invert it,
# giving a list with 1s for the numbers that need to be replaced
O # sum
£ # take these many elements from the list
¤ # RESULT: push the last element of the list
```
**Previous 26 byte solutions**
```
>GNN7ÖN7å~Dˆ[_#¯s£OÐ7Ös7å~
>G1UN[Ð7Ös7å~XiDˆ}_#¯s£O0U
```
[Answer]
# Pyth, 36 bytes
```
L?!hbbhx.f|/`Z`7!%Z7b)b;WnyyQyQ=yQ;Q
```
Fixed completely, but is now an unholy mess of letters and can certainly be golfed quite a bit.
1-indexed
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~104~~ ~~98~~ 95 bytes
*-6 bytes by getting rid of sprintf+index and looking manually for a 7 in an integer's digits*
*-3 bytes using the deprecated POSIX bzero instead of memset*
A function writing the result in the global variable `r`. Usage: `l(<int>)`
Result is 1-indexed.
```
r,o[9];b(i,s){for(r=s=++o[i];s&&s%10^7;s/=10);r%7&&!s?:b(i+1);}l(f){for(bzero(o,36);f--;b(0));}
```
[Try it online!](https://tio.run/##fc7fCoIwFMfxe59iCcqGk5xmZkN6EDPIP4uBuTizLhKf3UbdNq8/53v4NeGtaZYFqCrzitdYUk0moQBDoYsgUKWsuPZ97bHoknG9LVhEOHiZ72/06WjuA0b43GPxq@p3BwormuwJF2FoHkbE@CKHEd2vcsAvJVuCJgehHjNCH2BEYNdrz4NLgfAvpDbIbJDYE2vDWG6jODtYKU53K7ay4/8Sg9CNTxhQxJ3ZWT4 "C (gcc) – Try It Online")
Explanation:
```
/*
r = value of the nth element
o = array of counters (o[0] == main counter)
*/
r,o[9];
// Recursive function, "i" is the counter index
// "s" is used to determine if an int contain a 7 digit
b(i,s){
/*
1. Increases the value of the counter
2. Stores the result into r and s
3. Divide s by 10 until it is equal to 0 or its remainder is 7
*/
for(r=s=++o[i];s&&s%10^7;s/=10);
/*
if:
r%7 (r modulo 7) AND it contains no 7 digit
then:
nothing
else:
calls b with the next counter index
*/
r%7&&!s?:b(i+1);
}
// Main function: initializes counters and plays
// the sequence until the nth member is calculated
l(f){
for(bzero(o,36);f--;b(0));
}
```
[Answer]
# [Perl 5](https://www.perl.org/), 52 + 1 (-p) = 53 bytes
```
map{$s=0;do{$\=++$c[$s++]}until$\!~/7/&&$\%7}1..$_}{
```
[Try it online!](https://tio.run/##K0gtyjH9/z83saBapdjWwDolv1olxlZbWyU5WqVYWzu2tjSvJDNHJUaxTt9cX01NJUbVvNZQT08lvrb6/39z83/5BSWZ@XnF/3V9TfUMDA3@6xYAAA "Perl 5 – Try It Online")
**How?**
`@c` is an array of counters. `$c[0]` holds the main counter that determines which element we're working on. Each successive element holds another counter that is only accessed when the previous one contains a 7 or is divisible by 7.
```
map # Loop to find the appropriate element
$s=0; # reset index of counters
do{ # looping through the counters
$\=++c[$s++] # increment the counter and the index; $\ is our output variable
}until # don't quit until
$\!~/7/ # the result has no 7s
&&$\%7 # and is indivisble by 7
}1..$_ # do this until the input is reached
}{ # close the implicit loop created by the -p flag and force output of $\
```
~~# [Perl 5](https://www.perl.org/), 64 + 1 (-p) = 65 bytes~~
```
while($c[0]<$_){$s=0;do{$\=++$c[$s++]}while($\=~/7/||$\%7==0)}}{
```
[Try it online!](https://tio.run/##K0gtyjH9/788IzMnVUMlOdog1kYlXrNapdjWwDolv1olxlZbGyisUqytHVsLVRVjW6dvrl9ToxKjam5ra6BZW1v9/7@x6b/8gpLM/Lzi/7q@pnoGhgb/dQsA "Perl 5 – Try It Online")
[Answer]
## J, 52 bytes
```
i=:('7'&e.@":+.0=7&|)"0
f=:]`(#@}.@I.@:i@i.@>:)@.i^:_
```
Result is 1-indexed. Using it is pretty straightforward:
```
f 7777
```
[Try it online!](https://tio.run/##y/r/P9PWSkPdXF0tVc9ByUpbz8DWXK1GU8mAK83WKjZBQ9mhVs/BU8/BKtMhU8/BzkrTQS8zziqeKzU5I18hTcEcCP7//w8A)
] |
[Question]
[
# Task
You will be given a string in the input consisting only of the characters from `a` to `z`, i.e. the input will match the regex `/^[a-z]*$/`.
Your output should be a complete program in the same language, whose source code contains the input, and is a proper quine.
# Example
Your program would receive the input `abc` and output:
```
...abc...
```
The above should be a complete program in the same language which takes no input and outputs:
```
...abc...
```
i.e. it outputs itself.
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in bytes wins.
# References
* [What counts as a proper quine?](https://codegolf.meta.stackexchange.com/q/4877/48934)
[Answer]
# Python 3, ~~57~~ 61 bytes
```
lambda x:"s='s=%r;print(s%%s)';print(s%s)".replace('s',x+'x')
```
Takes a basic python 3 quine from [here](https://stackoverflow.com/questions/33071521/how-does-this-python-3-quine-work) and replaces the variable name with the input.
~~**Note:** As pointed out by Hyper Neutrino in comments, this does not work for reserved keywords like `for`, `if`, etc.~~
Appending a character that none of the reserved keywords ends with such as `'x'` or any number fixes this. (Ørjan Johansen).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
## Generator
```
;“¶Øv”ṾØv
```
[Try it online!](https://tio.run/nexus/jelly#@2/9qGHOoW2HZ5Q9apj7cOc@IOP////qhaWZeanqAA "Jelly – TIO Nexus")
### How it works
```
;“¶Øv”ṾØv Main link. Argument: s (string of letters)
;“¶Øv” Concatenate s and the string "\nØv".
Ṿ Uneval; get its string representation.
(implicit) Print the previous return value since the next link is an
otherwise unparsable nilad.
Øv Set the return value to "Ṙv".
```
## Quine
If the input is `quine`, the following program is generated.
```
“quine
Øv”Ṙv
```
[Try it online!](https://tio.run/nexus/jelly#@/@oYU5haWZeKtfhGWWPGuY@3Dmj7P9/AA "Jelly – TIO Nexus")
### How it works
This is the standard Jelly quine. First,
```
“quine
Øv”
```
sets the left argument and the return value to the string `"quine\nØv"`.
Then, `Ṙ` prints a string representation (the code from the previous block) and returns the unaltered string.
Afterwards, `v` takes the left argument and passes it as input to the Jelly program
```
quine
Øv
```
In all Jelly programs, only the *main link* (defined on the last line) is executed, so the first line is ignored entirely.
Finally, `Øv` sets the return value to `"Ṙv"`, which is printed implicitly when the outer program finishes.
[Answer]
# [Haskell](https://www.haskell.org/), 51 bytes
`q` takes a string and returns a string.
```
q s|t<-"main=putStr$fst`mappend`show$"=t++show(t,s)
```
[Try it online!](https://tio.run/nexus/haskell#y03MzLPNzCtJLUpMLlEo/F@oUFxTYqOrlAsSLygtCS4pUkkrLknITSwoSM1LSSjOyC9XUbIt0dYGsTRKdIo1//8vSS0uAQA "Haskell – TIO Nexus")
Example output for `putStr$q"test"`:
```
main=putStr$fst`mappend`show$("main=putStr$fst`mappend`show$","test")
```
[Try it online!](https://tio.run/nexus/haskell#@5@bmJlnW1BaElxSpJJWXJKQm1hQkJqXklCckV@uoqGEV1pJR6kktbhESfP/fwA "Haskell – TIO Nexus")
* Puts the main quine text and the desired string in a tuple.
* Uses `fst` to extract the main text.
* Uses `show` to turn the whole tuple into a string.
* Uses `mappend` to combine the two previous functions. Conveniently `mappend` on two functions gives a function that applies each function to its argument and combines the results with `mappend` for the result type (here string concatenation).
[Answer]
# [Underload](https://esolangs.org/wiki/Underload), 14 bytes
```
(~aSaS(:^)S):^
```
[Try it online!](https://tio.run/nexus/underload#0yhJLS7R/K9RlxicGKxhFacZrGkV9/8/AA "Underload – TIO Nexus")
Use as `(test)(~aSaS(:^)S):^` – which is itself a quine.
# How it works
* Underload is a concatenative (stack-based) esoteric language. It doesn't support reading input, so any arguments are put on the stack initially.
* `(test)` and `(~aSaS(:^)S)` are string literals, so place themselves on the stack, with the latter on top.
* `:` duplicates the `(~aSaS(:^)S)` string on top of the stack, then `^` runs its contents as a subprogram.
* `~` swaps the top two elements on the stack, so now `(test)` is uppermost.
* `a` wraps `(test)` in extra parentheses.
* `S` takes the string `((test))` on top of the stack, and prints it without the outer parentheses (which are just literal syntax).
* Now `aS` prints the remaining `(~aSaS(:^)S)` on the stack similarly (with the parentheses).
* At last, `(:^)S` prints the final `:^`.
[Answer]
# [Underload](https://esolangs.org/wiki/Underload), 14 bytes
```
a(aS(:^)S)~*:^
```
[Try it online!](https://tio.run/nexus/underload#00hMSk5J1fyfqJEYrGEVpxmsWadlFff/PwA "Underload – TIO Nexus")
A different approach from the other Underload answer; rather than itself being a quine, this constructs a quine. Interestingly, it comes out to the same number of bytes. This is a function that takes its argument from the stack and outputs to standard output.
## Explanation
```
a(aS(:^)S)~*:^
a Generate a string literal containing the input
(aS(:^)S)~* Prepend "aS(:^)S"
:^ Mockingbird: run the resulting function with itself as argument
```
The resulting function looks like this:
```
aS(:^)S(input)
aS Print a string literal containing the argument
(:^)S Print ":^"
(input) Push "input" onto the stack
```
In other words, it prints a string literal containing itself, followed by `:^`. This is clearly a quine (because what was just printed is the same as the code we executed to run it in the first place).
[Answer]
# Python 2, 38 bytes
Though input is only required to support `a-z`, this should work with any single-line input that doesn't contain NUL bytes.
```
s='s=%r;print s%%s#'+input();print s%s
```
[**Try it online**](https://tio.run/nexus/python2#@19sq15sq1pkXVCUmVeiUKyqWqysrp2ZV1BaoqEJFyz@/189MSlZHQA)
For input `abc` the resulting quine is:
```
s='s=%r;print s%%s#abc';print s%s#abc
```
[**Try it online**](https://tio.run/nexus/python2#@19sq15sq1pkXVCUmVeiUKyqWqycmJSsDueDuVz//wMA)
[Answer]
# [V](https://github.com/DJMcMayhem/V), 9 bytes
```
ñ"qPxÉÑ~j
```
[Try it online!](https://tio.run/nexus/v#@394o1JhQMXhzsMT67L@//dIzcnJBwA "V – TIO Nexus")
This is a modification of the [standard V quine](https://codegolf.stackexchange.com/a/100426/31716), and I'm proud that this is only one byte longer.
Hexdump:
```
00000000: f122 7150 78c9 d17e 6a ."qPx..~j
```
Explanation:
```
ñ " Record the following commands into register 'q'
"qP " Paste register 'q' before all input
x " Delete the last character of what we just pasted (this will be a 'ÿ')
ÉÑ " Insert 'Ñ' at the beginning of this line
~ " Toggle the case of this character
j " Move down a line. During playback, this will cancel playback of the current macro,
" So everything after here is a NOOP
```
Then, the recording implicitly stops and is played back. This will generate the following output:
```
ñ"qPxÉÑ~jHello
```
Since `j` will break playback of the macro, nothing in `Hello` will ever get run.
[Answer]
# [RProgN 2](https://github.com/TehFlaminTaco/RProgN-2), 15 bytes
```
"{']C'.%q[}]C"F
```
## Explained
Using the format
```
{']C'.%q[}]C}
```
where `%q` is the qouted input, builds a quine of the flavour
```
{']C'."Some Text"[}]C
```
which is a standard RProgN2 quine, [`{']C'.}]C`](https://tio.run/nexus/rprogn-2#@1@tHuusrlcb6/z//39d3RQA "RProgN 2 – TIO Nexus") That, before finished, appends and destroys the inputted string.
[Try it online!](https://tio.run/nexus/rprogn-2#@69UrR7rrK6nWhhdG@us5Pb///@QjFSF4pKizLx0hZJ8hcSCgtS8FEUA "RProgN 2 – TIO Nexus")
[Answer]
## [Retina](https://github.com/m-ender/retina), 14 bytes
Byte count assumes ISO 8859-1 encoding.
```
\(\`^
¶\(*S1`|
```
[Try it online!](https://tio.run/nexus/retina#@x@jEZMQx3VoW4yGVrBhQs3//xUA "Retina – TIO Nexus")
For input `x`, this outputs:
```
\(*S1`|x
\(*S1`|x
```
### Explanation
The output is a minor modification of the [standard quine](https://codegolf.stackexchange.com/a/67428/8478). We simply use the regex `|x` instead of the empty regex. Since the `|` still allows (and prioritises) and empty match, the functionality itself is not affected, and since `x` will only ever contain letters, it's guaranteed to be valid regex syntax itself.
Printing this actually uses a technique which is similar to the quine itself. To avoid the duplication of the quine, we insert `¶\(*S1`|` only once into the beginning of the string. That's exactly half the source code. To print it twice without a linefeed, we use the configuration `\(\`, which wraps the entire program in a group and makes both the stage itself as well as the group containing it print the result without a linefeed.
[Answer]
## [Japt](https://github.com/ETHproductions/japt), 14 bytes
```
"\"iQ ²ª`"+U ²
```
[Test it online!](http://ethproductions.github.io/japt/?v=1.4.4&code=IlwiaVEgsqpgIitVILI=&input=ImFiYyI=) For an input of `abc`, outputs
```
"iQ ²ª`abc"iQ ²ª`abc
```
which outputs itself. [Test it online!](http://ethproductions.github.io/japt/?v=1.4.4&code=ImlRILKqYGFiYyJpUSCyqmBhYmM=&input=)
### Explanation
This is an extension of the standard payload-capable Japt quine:
```
"iQ ²"iQ ²
"iQ ²" // Take this string. iQ ²
iQ // Insert a quote. "iQ ²
² // Repeat this twice. "iQ ²"iQ ²
// Implicit: output result of last expression
```
The only difference is that we append `ª`abc` at the end, which in JavaScript is basically `||"abc"`. Since the result of the first part is always a non-empty string (truthy), the `||` never gets run.
There are several alternative versions of the same length:
```
"iQ ²ª`abc"iQ ²ª`abc quine||"abc"
"iQ ²ª$abc"iQ ²ª$abc quine||abc
"iQ ²ª{abc"iQ ²ª{abc quine||function(){ ... }
"iQ ²ªXabc"iQ ²ªXabc quine||X.a(...) (X could be any uppercase letter or digit)
"iQ ²//abc"iQ ²//abc quine//abc (// is a comment in JS/Japt)
"iQ ²;[abc"iQ ²;[abc quine; (unmatched [ causes a parsing error)
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), ~~16~~ 14 bytes
```
"`_~"q`';++`_~
```
[Try it online!](https://tio.run/nexus/cjam#@6@UEF@nVJigbq2tDWT9/1@SWlwCAA "CJam – TIO Nexus")
**How it works**
```
"`_~" e# Push "`_~"
q` e# Push a string representation of the input (input wrapped in quotes)
'; e# Push a semicolon
++ e# Concatenate all this together
` e# Get the string representation of the resulting string
_~ e# Duplicate it and eval it (pushing the original string on the stack again)
```
Which outputs something like `"`_~\"test\";"`_~"test";`.
[Answer]
# JavaScript, 21 bytes
```
$=_=>`$=${$}/*${_}*/`
```
[Answer]
## [Perl 5](https://www.perl.org/), 35 bytes
```
$_=q{say"\$_=q{$_};eval"#}.<>;eval
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3rawujixUikGzFKJr7VOLUvMUVKu1bOxAzO5/v8vSS0u@ZdfUJKZn1f8X9fXVM/A0AAA "Perl 5 – Try It Online")
] |
[Question]
[
# Introduction
We've have a few base conversion challenges here in the past, but not many designed to tackle arbitrary length numbers (that is to say, numbers that are long enough that they overflow the integer datatype), and of those, most felt a little complicated. I'm curious how golfed down a change of base code like this can get.
# Challenge
Write a program or function in the language of your choice that can convert a string of one base to a string of another base. Input should be the number to be converted (string), from-base (base-10 number), to-base (base-10 number), and the character set (string). Output should be the converted number (string).
Some further details and rules are as follows:
* The number to be converted will be a non-negative integer (since `-` and `.` may be in the character set). So too will be the output.
* Leading zeroes (the first character in the character set) should be trimmed. If the result is zero, a single zero digit should remain.
* The minimum supported base range is from 2 to 95, consisting of the printable ascii characters.
* The input for the number to be converted, the character set, and the output must all be of the string datatype. The bases must be of the base-10 integer datatype (or integer floats).
* The length of the input number string can be very large. It's hard to quantify a sensible minimum, but expect it to be able to handle at least 1000 characters, and complete 100 characters input in less than 10 seconds on a decent machine (very generous for this sort of problem, but I don't want speed to be the focus).
* You cannot use built in change-of-base functions.
* The character set input can be in any arrangement, not just the typical 0-9a-z...etc.
* Assume that only valid input will be used. Don't worry about error handling.
The winner will be determined by the shortest code that accomplishes the criteria. They will be selected in at least 7 base-10 days, or if/when there have been enough submissions. In the event of a tie, the code that runs faster will be the winner. If close enough in speed/performance, the answer that came earlier wins.
# Examples
Here's a few examples of input and output that your code should be able to handle:
```
F("1010101", 2, 10, "0123456789")
> 85
F("0001010101", 2, 10, "0123456789")
> 85
F("85", 10, 2, "0123456789")
> 1010101
F("1010101", 10, 2, "0123456789")
> 11110110100110110101
F("bababab", 2, 10, "abcdefghij")
> if
F("10", 3, 2, "0123456789")
> 11
F("<('.'<)(v'.'v)(>'.'>)(^'.'^)", 31, 2, "~!@#$%^v&*()_+-=`[]{}|';:,./<>? ")
> !!~~~~~~~!!!~!~~!!!!!!!!!~~!!~!!!!!!~~!~!~!!!~!~!~!!~~!!!~!~~!!~!!~~!~!!~~!!~!~!!!~~~~!!!!!!!!!!!!~!!~!~!~~~~!~~~~!~~~~~!~~!!~~~!~!~!!!~!~~
F("~~~~~~~~~~", 31, 2, "~!@#$%^v&*()_+-=`[]{}|';:,./<>? ")
> ~
F("9876543210123456789", 10, 36, "0123456789abcdefghijklmnopqrstuvwxyz")
> 231ceddo6msr9
F("ALLYOURBASEAREBELONGTOUS", 62, 10, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
> 6173180047113843154028210391227718305282902
F("howmuchwoodcouldawoodchuckchuckifawoodchuckcouldchuckwood", 36, 95, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~`!@#$%^&*()_-+=[{]}\\|;:'\",<.>/? ")
> o3K9e(r_lgal0$;?w0[`<$n~</SUk(r#9W@."0&}_2?[n
F("1100111100011010101010101011001111011010101101001111101000000001010010100101111110000010001001111100000001011000000001001101110101", 2, 95, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~`!@#$%^&*()_-+=[{]}\\|;:'\",<.>/? ")
> this is much shorter
```
[Answer]
## Seriously, 50 bytes
```
0╗,╝,2┐,3┐,4┐╛`4└í╜2└*+╗`MX╜ε╗W;3└@%4└E╜@+╗3└@\WX╜
```
Hex Dump:
```
30bb2cbc2c32bf2c33bf2c34bfbe6034c0a1bd32c02a2bbb60
4d58bdeebb573b33c0402534c045bd402bbb33c0405c5758bd
```
I'm proud of this one despite its length. Why? Because it worked perfectly on the second try. I wrote it and debugged it in literally 10 minutes. Usually debugging a Seriously program is an hour's labor.
Explanation:
```
0╗ Put a zero in reg0 (build number here)
,╝,2┐,3┐,4┐ Put evaluated inputs in next four regs
╛ Load string from reg1
` `M Map over its chars
4└ Load string of digits
í Get index of char in it.
╜ Load number-so-far from reg0
2└* Multiply by from-base
+ Add current digit.
╗ Save back in reg0
X Discard emptied string/list.
╜ Load completed num from reg0
ε╗ Put empty string in reg0
W W While number is positive
; Duplicate
3└@% Mod by to-base.
4└E Look up corresponding char in digits
╜@+ Prepend to string-so-far.
(Forgetting this @ was my one bug.)
╗ Put it back in reg0
3└@\ integer divide by to-base.
X Discard leftover 0
╜ Load completed string from reg0
Implicit output.
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~115~~ ~~114~~ ~~106~~ ~~105~~ 94 bytes
Golfing suggestions welcome. [Try it online!](https://tio.run/nexus/python2#VU9pU4NADP3Or4hoBcra7larlrre931fQBXdYlfrtgJaXY@/jgjIaDLzkryXvJnErO2DpwvkowgxJClGIdU0w1LA7wXAgQsQlqSy7Jus4nPBdG4oMOjwbhukFVJmy1LkmmFTVmmkQD/gIoIQkltmYzf2dJUQjAn5waTgf/mrkGLOmbTJIuNyILkRTvViudj8c5W6ZcYqghqCRh2BikltfKI@OTXd8G5uk9/vOvz@ofsoev2nIIyeXwavb3JhcWl5ZXVtfWNza3tnd2//4PDo@OT07Pzi8ut6aH54pNQaLevG1ZhJ7Xf303E@mpbmqGimMludA9WIvwE "Python 2 – TIO Nexus")
**Edit:** -9 bytes thanks to mbomb007. -2 bytes thanks to FlipTack.
```
def a(n,f,t,d,z=0,s=''):
for i in n:z=z*f+d.find(i)
while z:s=d[z%t]+s;z/=t
print s or d[0]
```
**Ungolfed:**
```
def arbitrary_base_conversion(num, b_from, b_to, digs, z=0, s=''):
for i in num:
z = z * b_from + digs.index(i)
while z:
s = digs[z % b_to] + s
z = z / t
if s:
return s
else:
return d[0]
```
[Answer]
## CJam, 34 bytes
```
0ll:Af#lif{@*+}~li:X;{XmdA=\}h;]W%
```
Input format is `input_N alphabet input_B output_B` each on a separate line.
[Run all test cases.](http://cjam.aditsu.net/#code=%7B%0A%0A0ll%3AAf%23lif%7B%40*%2B%7D~li%3AX%3B%7BXmdA%3D%5C%7Dh%3B%5DW%25%0A%0A%5DoNo%7D12*&input=1010101%0A0123456789%0A2%0A10%0A0001010101%0A0123456789%0A2%0A10%0A85%0A0123456789%0A10%0A2%0A1010101%0A0123456789%0A10%0A2%0Abababab%0Aabcdefghij%0A2%0A10%0A10%0A0123456789%0A3%0A2%0A%3C('.'%3C)(v'.'v)(%3E'.'%3E)(%5E'.'%5E)%0A~!%40%23%24%25%5E%26*()_%2B-%3D%60%5B%5D%7B%7D%7C'%3B%3A%2C.%2F%3C%3E%3F%20%0A31%0A2%0A~~~~~~~~~~%0A~!%40%23%24%25%5E%26*()_%2B-%3D%60%5B%5D%7B%7D%7C'%3B%3A%2C.%2F%3C%3E%3F%20%0A31%0A2%0A9876543210123456789%0A0123456789abcdefghijklmnopqrstuvwxyz%0A10%0A36%0AALLYOURBASEAREBELONGTOUS%0A0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ%0A62%0A10%0Ahowmuchwoodcouldawoodchuckchuckifawoodchuckcouldchuckwood%0A0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~%60!%40%23%24%25%5E%26*()_-%2B%3D%5B%7B%5D%7D%5C%5C%7C%3B%3A'%5C%22%2C%3C.%3E%2F%3F%20%0A36%0A95%0A1100111100011010101010101011001111011010101101001111101000000001010010100101111110000010001001111100000001011000000001001101110101%0A0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~%60!%40%23%24%25%5E%26*()_-%2B%3D%5B%7B%5D%7D%5C%5C%7C%3B%3A'%5C%22%2C%3C.%3E%2F%3F%20%0A2%0A95)
### Explanation
```
0 e# Push a zero which we'll use as a running total to build up the input number.
l e# Read the input number.
l:A e# Read the alphabet and store it in A.
f# e# For each character in the input number turn it into its position in the alphabet,
e# replacing characters with the corresponding numerical digit value.
li e# Read input and convert to integer.
f{ e# For each digit (leaving the base on the stack)...
@* e# Pull up the running total and multiply it by the base.
+ e# Add the current digit.
}
~ e# The result will be wrapped in an array. Unwrap it.
li:X; e# Read the output base, store it in X and discard it.
{ e# While the running total is not zero yet...
Xmd e# Take the running total divmod X. The modulo gives the next digit, and
e# the division result represents the remaining digits.
A= e# Pick the corresponding character from the alphabet.
\ e# Swap the digit with the remaining value.
}h
; e# We'll end up with a final zero on the stack which we don't want. Discard it.
]W% e# Wrap everything in an array and reverse it, because we've generated the
e# digits from least to most significant.
```
This works for the same byte count:
```
L0ll:Af#lif{@*+}~li:X;{XmdA=@+\}h;
```
The only difference is that we're building up a string instead of collecting everything on the stack and reversing it.
[Answer]
# Ruby, ~~113~~ ~~112~~ ~~105~~ ~~98~~ ~~97~~ ~~95~~ 87 bytes
I sort of double-posted my Python answer (somehow), so here's a Ruby answer. Seven more bytes thanks to [manatwork](https://codegolf.stackexchange.com/users/4198/manatwork), another byte thanks to [Martin Büttner](https://codegolf.stackexchange.com/users/8478/martin-b%c3%bcttner), and 8 more bytes thanks to [cia\_rana](https://codegolf.stackexchange.com/users/59228/cia-rana).
```
->n,f,t,d{z=0;s='';n.chars{|i|z=z*f+d.index(i)};(s=d[z%t]+s;z/=t)while z>0;s[0]?s:d[0]}
```
Ungolfed:
```
def a(n,f,t,d)
z=0
s=''
n.chars do |i|
z = z*f + d.index(i)
end
while z>0
s = d[z%t] + s
z /= t
end
if s[0] # if n not zero
return s
else
return d[0]
end
end
```
[Answer]
# C (function) with [GMP library](https://gmplib.org/manual/), 260
This turned out longer than I'd hoped, but here it is anyway. The `mpz_*` stuff really eats up a lot of bytes. I tried `#define M(x) mpz_##x`, but that gave a net gain of 10 bytes.
```
#include <gmp.h>
O(mpz_t N,int t,char*d){mpz_t Q,R;mpz_inits(Q,R,0);mpz_tdiv_qr_ui(Q,R,N,t);mpz_sgn(Q)&&O(Q,t,d);putchar(d[mpz_get_ui(R)]);}F(char*n,int f,int t,char*d){mpz_t N;mpz_init(N);while(*n)mpz_mul_ui(N,N,f),mpz_add_ui(N,N,strchr(d,*n++)-d);O(N,t,d);}
```
The function `F()` is the entry-point. It converts the input string to an `mpz_t` by successive multiplications by the `from`-base and addition of the index of the given digit in the digit list.
The function `O()` is a recursive output function. Each recursion divmods the `mpz_t` by the `to`-base. Because this yields the output digits in reverse order, the recursion effectively allows the digits to be stored on the stack and output in the correct order.
### Test driver:
Newlines and indenting added for readability.
```
#include <stdio.h>
#include <string.h>
#include <gmp.h>
O(mpz_t N,int t,char*d){
mpz_t Q,R;
mpz_inits(Q,R,0);
mpz_tdiv_qr_ui(Q,R,N,t);
mpz_sgn(Q)&&O(Q,t,d);
putchar(d[mpz_get_ui(R)]);
}
F(char*n,int f,int t,char*d){
mpz_t N;
mpz_init(N);
while(*n)
mpz_mul_ui(N,N,f),mpz_add_ui(N,N,strchr(d,*n++)-d);
O(N,t,d);
}
int main (int argc, char **argv) {
int i;
struct test_t {
char *n;
int from_base;
int to_base;
char *digit_list;
} test[] = {
{"1010101", 2, 10, "0123456789"},
{"0001010101", 2, 10, "0123456789"},
{"85", 10, 2, "0123456789"},
{"1010101", 10, 2, "0123456789"},
{"bababab", 2, 10, "abcdefghij"},
{"10", 3, 2, "0123456789"},
{"<('.'<)(v'.'v)(>'.'>)(^'.'^)", 31, 2, "~!@#$%^v&*()_+-=`[]{}|';:,./<>? "},
{"~~~~~~~~~~", 31, 2, "~!@#$%^v&*()_+-=`[]{}|';:,./<>? "},
{"9876543210123456789", 10, 36, "0123456789abcdefghijklmnopqrstuvwxyz"},
{"ALLYOURBASEAREBELONGTOUS", 62, 10, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"},
{"howmuchwoodcouldawoodchuckchuckifawoodchuckcouldchuckwood", 36, 95, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~`!@#$%^&*()_-+=[{]}\\|;:'\",<.>/? "},
{"1100111100011010101010101011001111011010101101001111101000000001010010100101111110000010001001111100000001011000000001001101110101", 2, 95, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~`!@#$%^&*()_-+=[{]}\\|;:'\",<.>/? "},
{0}
};
for (i = 0; test[i].n; i++) {
F(test[i].n, test[i].from_base, test[i].to_base, test[i].digit_list);
puts("");
}
return 0;
}
```
[Answer]
## JavaScript (ES6), 140 bytes
```
(s,f,t,m)=>[...s].map(c=>{c=m.indexOf(c);for(i=0;c||i<r.length;i++)r[i]=(n=(r[i]|0)*f+c)%t,c=n/t|0},r=[0])&&r.reverse().map(c=>m[c]).join``
```
Unlike @Mwr247's code (which uses base-f arithmetic to divide s by t each time, collecting each remainder as he goes) I use base-t arithmetic to multiply the answer by f each time, adding each digit of s as I go.
Ungolfed:
```
function base(source, from, to, mapping) {
result = [0];
for (j = 0; j < s.length; s++) {
carry = mapping.indexOf(s[j]);
for (i = 0; carry || i < result.length; i++) {
next = (result[i] || 0) * from + carry;
result[i] = next % to;
carry = Math.floor(next / to);
}
}
string = "";
for (j = result.length; j --> 0; )
string += mapping[result[j]];
return string;
}
```
[Answer]
# APL, 10 bytes
```
{⍺⍺[⍵⍵⍳⍵]}
```
This is an APL operator. In APL, `⍵` and `⍺` are used to pass values, while `⍵⍵` and `⍺⍺` are usually used to pass functions. I'm abusing this here to have 3 arguments. `⍺⍺` is the left argument, `⍵⍵` is the "inner" right argument, and `⍵` is the "outer" right argument.
Basically: `⍺(⍺⍺{...}⍵⍵)⍵`
Then all that's needed is `⍳` to find the positions of the input string in the "from" table, and then use `[]` to index into the "to" table with these positions.
Example:
```
('012345'{⍺⍺[⍵⍵⍳⍵]}'abcdef')'abcabc'
012012
```
[Answer]
# JavaScript (ES6), 175 bytes
```
(s,f,t,h)=>eval('s=[...s].map(a=>h.indexOf(a));n=[];while(s.length){d=m=[],s.map(v=>((e=(c=v+m*f)/t|0,m=c%t),e||d.length?d.push(e):0)),s=d,n.unshift(m)}n.map(a=>h[a]).join``')
```
Figured it's been long enough now that I can submit the one I made to create the examples. I may try and golf it down a bit better later.
[Answer]
# Japt, 9 bytes
```
nVîX
sWîX
```
[Try it](https://ethproductions.github.io/japt/?v=2.0a0&code=blbuWApzV+5Y&input=IjwoJy4nPCkodicuJ3YpKD4nLic+KSheJy4nXikiLCAzMSwgMiwgIn4hQCMkJV52JiooKV8rLT1gW117fXwnOzosLi88Pj8gIg==)
] |
[Question]
[
Write a program or function that takes in an odd positive integer N and a string of decimal digits (`0123456789`). The string represents a ten-state [one-dimensional cellular automaton](http://mathworld.wolfram.com/ElementaryCellularAutomaton.html). Each digit occupies one cell and the update rule from one generation to the next is that every cell becomes the digit resulting from the sum of the N cells centered on the cell, modulo 10.
The first and last cells wrap around as if neighbors, so cells can always have N cells centered on them. Note that N may be larger than the length of the string, which means it could wrap around multiple times and some digits will accordingly be in the sum multiple times.
As an example, if N is 7 and the string is `038`, to visualize the cells to sum we can write `038` repeating infinitely in both directions
```
...038038038038038...
```
then the digit that the `0` will change into is the sum of the 7 digits centered around any `0`, modulo 10:
```
...038038038038038...
^_____^
|
sum all these
```
This is `(0+3+8+0+3+8+0)%10`, which is `2`.
Similarly the digits the `3` and `8` change into are defined by `(3+8+0+3+8+0+3)%10` = `5` and `(8+0+3+8+0+3+8)%10` = `0` respectively.
Thus, the generation after `038` is `250` when N is 7.
Your program or function needs to print or return the digit string of the very next generation of the input digit string. i.e. apply the update rule once to each cell and give the output. **The shortest code in bytes wins.**
# Test Cases
```
[digit string] -> [N = 1], [N = 3], [N = 5], [N = 7], [N = 9], [N = 43]
0 -> 0, 0, 0, 0, 0, 0
1 -> 1, 3, 5, 7, 9, 3
2 -> 2, 6, 0, 4, 8, 6
3 -> 3, 9, 5, 1, 7, 9
4 -> 4, 2, 0, 8, 6, 2
5 -> 5, 5, 5, 5, 5, 5
6 -> 6, 8, 0, 2, 4, 8
7 -> 7, 1, 5, 9, 3, 1
8 -> 8, 4, 0, 6, 2, 4
9 -> 9, 7, 5, 3, 1, 7
00 -> 00, 00, 00, 00, 00, 00
07 -> 07, 47, 41, 81, 85, 47
10 -> 10, 12, 32, 34, 54, 12
11 -> 11, 33, 55, 77, 99, 33
12 -> 12, 54, 78, 10, 34, 54
34 -> 34, 10, 78, 54, 12, 10
66 -> 66, 88, 00, 22, 44, 88
80 -> 80, 86, 46, 42, 02, 86
038 -> 038, 111, 294, 250, 333, 472
101 -> 101, 222, 343, 545, 666, 989
987 -> 987, 444, 901, 765, 222, 543
1234 -> 1234, 7698, 3412, 9876, 1234, 7698
26697 -> 26697, 54128, 00000, 56982, 84413, 54128
001002 -> 001002, 211122, 331332, 335334, 455544, 113112
129577020 -> 129577020, 326194923, 474081605, 961120291, 333333333, 183342413
6023845292173530 -> 6023845292173530, 6853571632015189, 1197228291289874, 9238433109901549, 0110956118726779, 1982123699138828
```
[Answer]
## CJam, 21 bytes
```
l~_,\2/f-l:~fm>:.+Af%
```
[Test it here.](http://cjam.aditsu.net/#code=l~_%2C%5C2%2Ff-l%3A~fm%3E%3A.%2BAf%25&input=7%0A038)
### Explanation
```
l~ e# Read and evaluate N.
_, e# Duplicate and turn into range [0 1 ... N-1]
\2/ e# Swap with other copy and (integer) divide by 2.
f- e# Subtract this from each element in the range to get
e# [-(N-1)/2 ... -1 0 1 ... (N-1)/2]
l:~ e# Read string and evaluate each digit separately.
fm> e# Make one copy of the result for each element i in the range, shifting the array
e# i cells to the right, cyclically.
:.+ e# Sum the columns of the resulting matrix.
Af% e# Take each of those sums modulo 10.
```
[Answer]
# Pyth, ~~20~~ 19 bytes
*1 byte thanks to @FryAmTheEggman.*
```
sm`esmv@z-+dk/Q2Qlz
```
[Try it online](https://pyth.herokuapp.com/?code=sm%60esmv%40z-%2Bdk%2FQ2Qlz&input=038%0A7&debug=0). [Test suite](https://pyth.herokuapp.com/?code=sm%60esmv%40z-%2Bdk%2FQ2Qlz&test_suite=1&test_suite_input=0%0A3%0A0%0A7%0A1%0A3%0A1%0A7%0A2%0A3%0A2%0A7%0A3%0A3%0A3%0A7%0A4%0A3%0A4%0A7%0A5%0A3%0A5%0A7%0A6%0A3%0A6%0A7%0A7%0A3%0A7%0A7%0A8%0A3%0A8%0A7%0A9%0A3%0A9%0A7%0A00%0A3%0A00%0A7%0A07%0A3%0A07%0A7%0A10%0A3%0A10%0A7%0A11%0A3%0A11%0A7%0A12%0A3%0A12%0A7%0A34%0A3%0A34%0A7%0A66%0A3%0A66%0A7%0A80%0A3%0A80%0A7%0A038%0A3%0A038%0A7%0A101%0A3%0A101%0A7%0A987%0A3%0A987%0A7%0A1234%0A3%0A1234%0A7%0A26697%0A3%0A26697%0A7%0A001002%0A3%0A001002%0A7%0A129577020%0A3%0A129577020%0A7%0A6023845292173530%0A3%0A6023845292173530%0A7&debug=0&input_size=2).
[Answer]
# Mathematica, 85 bytes
```
""<>ToString/@CellularAutomaton[{Tr@#~Mod~10&,{},#/2-1/2},FromDigits/@Characters@#2]&
```
[Answer]
## Python 3, ~~114~~ ~~92~~ ~~86~~ 80 bytes
Took off 6 bytes thanks to **Sp3000** and another 6 bytes thanks to **xnor**!
```
a=lambda N,D,i=0:D[i:]and str(int((D*N)[(i-N//2)%len(D):][:N],11)%10)+a(N,D,i+1)
```
Defines a named function `a` that takes `N` and `D` as parameters, the N and digit string defined in the challenge.
### Explanation
In Python 3, `and` between two strings will end up being the latter. Hence, `D[i:]and ...` short-circuits once all center positions have been iterated over as `D[i:]` will be an empty string and therefore falsy. `(D*N)[(i-N//2)%len(D):][:N]` duplicates the digit string a bunch of times, then slices it in the right places to give the substring that has the correct digit as the center. Recall for a moment that the sum of the digits of a base 10 number modulo 9 is the same as the number itself modulo 9. `str(int(...,10)%10)` treats the resulting number-string as if it was base 11 and gets the remainder modulo 10, then converts back to string. Finally, `a(N,D,i+1)` moves on to the next center position. Because of the `+`, once the recursion is done, all of the resulting digits are lumped together and returned.
[Answer]
## Haskell, 92 bytes
String conversion is really expensive in Haskell...
```
x!n=last.show.sum.map(read.pure).take n.(`drop`cycle x).fst<$>zip[div(1-n)2`mod`length x..]x
```
This defines an infix function `!`, used as follows:
```
> "1234"!3
"7698"
```
## Explanation
On the right we have `[div(1-n)2`mod`length x..]`, which is just the infinite list of integers starting from `(1-n)/2` modulo `length(x)` (we take the modulus, since we want the first element to be non-negative). These correspond to the starting indices of the CA neighborhoods. We zip it with `x` just to obtain a list of the correct length.
The function `<$>` is the infix version of `map`, and its left argument is a function composition read from right to left. Thus for each integer in the above list (extracted with `fst`), we drop that many characters from `cycle x` (which is the concatenation of infinitely may copies of `x`), take `n` characters from the remainder, convert them to strings and then integers with `read.pure`, take their sum, convert that to string with `show`, and take the last character of that, which corresponds to the remainder mod 10.
[Answer]
# NARS2000 APL, 37 characters (72 bytes)
```
⎕←10⊥10∣+⌿⊃({⍵..-⍵}⌊⎕÷2)∘.⌽⊂49-⍨⎕AV⍳⍞
```
Explanation:
```
⎕←10⊥10∣+⌿⊃({⍵..-⍵}⌊⎕÷2)∘.⌽⊂49-⍨⎕AV⍳⍞
⍝ ⎕← output
⍝ 10⊥ the base-10 digits in
⍝ 10∣ the modulo-10
⍝ +⌿ column-wise sum of
⍝ ⊃ the matrix version of
⍝ ∘.⌽ the outer-product rotation of
⍝ ⊂ the scalar version of
⍝ ⎕AV⍳ the index in the atomic vector of
⍝ ⍞ an input string
⍝ 49-⍨ minus 49 ('0' + 1)
⍝ by
⍝ {⍵..-⍵} the range ⍵ to -⍵, where ⍵ is
⍝ ⌊ the floor of
⍝ ⎕ an input integer
⍝ ÷2 divided by 2
```
[Answer]
# Octave, 64 bytes
```
@(s,n)["" mod(sum(bsxfun(@shift,s'-48,(1:n)-ceil(n/2))'),10)+48]
```
[Answer]
# J, 41 bytes
```
"."0@]{~(1":10|+/@:)#@]|-:@<:@[-~(+/&i.#)
```
Turned out longer than I expected. Should be golfable.
We generate a matrix with elements in a row showing the positions whose values should be added (mod 10) to get sum for a position.
Usage:
```
7 ("."0@]{~(1":10|+/@:)#@]|-:@<:@[-~(+/&i.#)) '038'
250
```
[Try it online here.](http://tryj.tk/)
] |
[Question]
[
Given a space-separated list of integers, your task is to find the next integer in the sequence.
Each integer in the sequence is the result of applying a single mathematical operation(`+`,`-`,`*` or `/`) to the previous integer, and each sequence is made up of a variable number of such operations (but no more than 10). No sequence will be longer than half the length of the sequence of integers, so you'll have each sequence of operations appear at least twice for confirmation.
**Input** will be via stdin (or `prompt` for JavaScript solutions).
Here are some explanatory examples.
**Input:**
```
1 3 5 7 9 11
```
**Output:**
```
13
```
Fairly easy, this one. All values are previous value `+2`.
**Input:**
```
1 3 2 4 3 5 4 6 5 7 6
```
**Ouput:**
```
8
```
Two steps in this sequence, `+2` then `-1`.
**Input:**
```
2 6 7 3 9 10 6 18 19 15 45 46
```
**Output:**
```
42
```
Three steps - `*3`, `+1`, `-4`.
## Test cases
Here are few more test cases:
Input:
```
1024 512 256 128 64 32 16
```
Output:
```
8
```
Input:
```
1 3 9 8 24 72 71 213 639
```
Output:
```
638
```
Input:
```
1 2 3 4 5 2 3 4 5 6 3 4 5 6 7
```
Output:
```
4
```
Input:
```
1 2 4 1 3 9 5 8 32 27 28 56 53 55 165 161 164 656 651 652 1304
```
Output:
```
1301
```
I have an ungolfed Scala solution (42 lines) that I will post in a couple of days.
This is code-golf - shortest answer wins.
[Answer]
## Golfscript, 203 138 chars
```
~]0{).2$.);[\(;]zip\/zip{.{~-}%.&({-}+\{;{.0={.~\%{.~%{;0}{~/{/}+}if}{~\/{*}+}if}{~!{;}*}if}%.&(\{;;0}/}{\;}if}%.{!}%1?)!{0}*}do\@)\,@%@=~
```
This uses far more `if`s than a standard Golfscript program, and its operation is pretty cryptic, so here's a commented (but not ungolfed other than by the addition of whitespace and comments) version:
```
~]0
# Loop over guesses L for the length of the sequence
{
# [x0 ... xN] L-1
).
# [x0 ... xN] L L
2$.);[\(;]zip
# [x0 ... xN] L L [[x0 x1][x1 x2]...[x{N-1} xN]]
\/zip
# [x0 ... xN] L [[[x0 x1][xL x{L+1}]...][[x1 x2][x{L+1} x{L+2}]...]...]
{
# [x0 ... xN] L [[xi x{i+1}][x{i+L} x{i+L+1}]...]
# Is there an operation which takes the first element of each pair to the second?
# Copy the pairs, work out each difference, and remove duplicates
.{~-}%.&
# Turn the first difference into an operation
({-}+\
# If there was more than one unique difference, look for a multiplication
{
;
# [x0 ... xN] L [[xi x{i+1}][x{i+L} x{i+L+1}]...]
# Do something similar, but working out multiplicative factors
# Note that if we have [0 0] it could be multiplication by anything, so we remove it.
# However, they can't all be [0 0] or we'd have only one unique difference
{
# [0 0 ] =>
# [0 _ ] => 0 # a "false" value, because it can't possibly be multiplication
# [a a.b'] => {b'*}
# [a'.b b ] => {a'/}
# [_ _ ] => 0 # ditto
# This is the obvious place to look for further improvements
.0={.~\%{.~%{;0}{~/{/}+}if}{~\/{*}+}if}{~!{;}*}if
}%.&
# If we have one unique multiplication, even if it's false, keep it.
# Otherwise discard them and replace them with false.
(\{;;0}/
}
# There was only one unique difference. Discard the pairs
{\;}if
# operation - one of 0, {d+}, {m*}, {M/}
}%
# [x0 ... xN] L [op0 ... op{L-1}]
# Is any of the operations false, indicating that we couldn't find a suitable operation?
.{!}%1?
# [x0 ... xN] L [op0 ... op{L-1}] idxFalse
# If idxFalse is -1 then all the ops are ok, and we put a false to exit the loop
# Otherwise one op failed, so we leave the array of ops, which is non-false, to be popped by the do.
)!{0}*
}do
# [x0 ... xN] L [op0 ... op{L-1}]
\@)\,@%@=~
# op{(len(Xs)-1)%L} (Xs[-1])
```
My original submission was the following at 88 chars:
```
~]:x;2.{;).(2base(;{[{--}{@*\.!+/}]=}%[x.(;2$]zip\,<{~++}%x,.@[*x\]zip<{~~}%)\x(;=!}do\;
```
However, this tries to calculate the operations from the first occurrence of each, so if the operation is multiplication or division and the argument the first time round is 0 it breaks.
[Answer]
## Haskell, ~~276~~ ~~261~~ ~~259~~ ~~257~~ 243 characters
Here is my inefficient solution. It works on unbounded (and bounded) integers. This solution happens to work correctly with non-exact division (eg: `5 / 2 = 2`).
```
import Control.Monad
main=interact$show.n.q read.words
f=flip
q=map
_%0=0
x%y=div x y
s b=[1..]>>=q cycle.(f replicateM$[(+),(*),(%)]>>=f q[-b..b].f)
m l x s=[y!!l|y<-[scanl(f($))(x!!0)s],x==take l y]
n x=(s(maximum$q abs x)>>=m(length x)x)!!0
```
How it works: I create every possible sequence of (possible) operations. Then I test against the input sequence of numbers to see if the generated sequence will create the input. If it does, return the next number in the sequence. The code will always return an answer that is derived from a shortest sequence of operations. This happens because the list of operation sequences is generated in that order. It's arbitrary (but consistent) on deciding between ties. For example the code returns `6` or `8` for the sequence `2 4`.
Ungolfed:
```
import Control.Monad
main :: IO ()
main = print . next . map read . words =<< getLine
opSequences :: Integral a => a -> [[a -> a]]
opSequences bound = [1 ..] >>= map cycle . (`replicateM` (ops >>= (`map` args) . flip))
where
ops = [(+), (*), \x y -> if y == 0 then 0 else div x y]
args = [-bound .. bound]
match :: (MonadPlus m, Integral a) => [a] -> [a -> a] -> m a
match ns opSeq = guard (ns == take len ms) >> return (ms !! len)
where
n0 = ns !! 0
len = length ns
ms = scanl (flip ($)) n0 opSeq
next :: Integral a => [a] -> a
next ns = (opSequences bound >>= match ns) !! 0
where
bound = maximum $ map abs ns
```
[Answer]
**Python, ~~333~~ ~~366~~ ~~...~~ ~~315~~ ~~303~~ ~~278~~ ~~269~~ ~~261~~ 246 chars**
```
n=map(float,raw_input().split())
y=len(n)-1
l=1
def O(f):
p,q=n[f:y:l],n[f+1::l]
for a,b in zip(p,q):
for x in((b-a).__add__,(b/(a or 1)).__mul__):
if map(x,p)==q:return x
while 1:
if all(map(O,range(l))):print int(O(y%l)(n[y]));break
l+=1
```
Creates operation with first pair of numbers and check it on other pairs. Stores all operations, and if all of them succeed then applies appropriate operation on list last element.
Edited: passes evil test:-) Now search for operation on all positions.
[Answer]
## Python, 309 305 295 279 chars
Handles all of the original test cases, as well as Peter Taylor's gnarly `0 0 1 2 3 6 7 14` one:
```
l=map(int,raw_input().split())
i=v=0
while v<1:
v=i=i+1
for j in range(i):
p=zip(l[j::i],l[j+1::i])
d,r=set(q[1]-q[0]for q in p),set(q[1]*1./(q[0]or 1)for q in p if any(q))
m,n=len(d)<2,len(r)<2
v*=m+n
if(len(l)-1)%i==j:s=l[-1]+d.pop()if m else int(l[-1]*r.pop())
print s
```
Ungolfed, with debugging output (very helpful in verifying correctness):
```
nums = map(int,raw_input().split())
result = None
for i in range(1,len(nums)/2+1):
print "-- %s --" % i
valid = 1
for j in range(i):
pairs = zip(nums[j::i], nums[j+1::i])
print pairs
diffs = [pair[1] - pair[0] for pair in pairs]
# this is the tough bit: (3, 6) -> 2, (0, 5) -> 5, (5, 0) -> 0, (0, 0) ignored
ratios = [float(pair[1])/(pair[0] or 1) for pair in pairs if pair[0] != 0 or pair[1] != 0]
if len(set(diffs))==1:
print " can be diff", diffs[0]
if (len(nums) - 1) % i == j:
result = nums[-1] + diffs.pop()
elif len(set(ratios))==1:
print " can be ratio", ratios[0]
if (len(nums) - 1) % i == j:
result = int(nums[-1]*ratios.pop())
else:
print "** invalid period **"
valid=0
if valid and result is not None:
break
print result
```
Usage:
```
echo 0 0 1 2 3 6 7 14 | python whatcomesnext.py
```
[Answer]
## Ruby 1.9 (437) (521) (447) (477)
Works for all test cases, including the "evil" one. I'll golf it more later.
EDIT: I realized there's another case that I wasn't handling properly - when the continuation needs to use the "mystery" operation. The sequence `2 0 0 -2 -4 -6` was initially returning 0 instead of -12. I've now fixed that.
EDIT: Fixed a couple more edge cases and cut down the code to 447.
EDIT: Ugh. Had to add some code to handle other "evil" sequences such as `0 0 0 6 18 6 12`
```
def v(c,q);t=*q[0];q.size.times{|i|f=c[z=i%k=c.size]
f=c[z]=(g=q[z+k])==0??_:((h=q[z+k+1])%g==0?"*(#{h/g})":"/(#{g/h})")if f==?_
t<<=f==?_?(a=q[i];b=q[i+1].nil?? 0:q[i+1];(a==0&&b==0)||(a!=0&&(b%a==0||a%b==0))?b:0):eval(t.last.to_s+f)}
*r,s=t
(p s;exit)if q==r
end
s=gets.split.map &:to_i
n=[[]]
((s.size-1)/2).times{|i|a,b=s[i,2]
j=["+(#{b-a})"]
j<<=?_ if a==0&&b==0
j<<="*#{b/a}"if a!=0&&b%a==0
j<<="/#{a/b}"if a*b!=0&&a%b==0
n=n.product(j).map(&:flatten)
n.map{|m|v(m*1,s)}}
```
[Answer]
## Scala
This is the solution I came up with:
```
object Z extends App{var i=readLine.split(" ").map(_.toInt)
var s=i.size
var(o,v,f)=(new Array[Int](s),new Array[Double](s),1)
def d(p:Int,j:Array[Int]):Unit={if(p<=s/2){def t(){var a=new Array[Int](s+1)
a(0)=i(0)
for(l<-0 to s-1){o(l%(p+1))match{case 0=>a(l+1)=a(l)+v(l%(p+1)).toInt
case _=>a(l+1)=(a(l).toDouble*v(l%(p+1))).toInt}}
if(a.init.deep==i.deep&&f>0){f^=f
println(a.last)}}
o(p)=0
v(p)=j(1)-j(0)
t
d(p+1,j.tail)
o(p)=1
v(p)=j(1).toDouble/j(0).toDouble
t
d(p+1,j.tail)}}
d(0,i)
i=i.tail
d(0,i)}
```
Ungolfed:
```
object Sequence extends App
{
var input=readLine.split(" ").map(_.toInt)
var s=input.size
var (ops,vals,flag)=(new Array[Int](s),new Array[Double](s),1)
def doSeq(place:Int,ints:Array[Int]):Unit=
{
if(place<=s/2)
{
def trysolution()
{
var a=new Array[Int](s+1)
a(0)=input(0)
for(loop<-0 to s-1)
{
ops(loop%(place+1))match
{
case 0=>a(loop+1)=a(loop)+vals(loop%(place+1)).toInt
case _=>a(loop+1)=(a(loop).toDouble*vals(loop%(place+1))).toInt
}
}
if(a.init.deep==input.deep&&flag>0)
{
flag^=flag
println(a.last)
}
}
ops(place)=0
vals(place)=ints(1)-ints(0)
trysolution
doSeq(place+1,ints.tail)
ops(place)=1
vals(place)=ints(1).toDouble/ints(0).toDouble
trysolution
doSeq(place+1,ints.tail)
}
}
doSeq(0,input)
input=input.tail
doSeq(0,input)
}
```
[Answer]
### Scala 936
```
type O=Option[(Char,Int)]
type Q=(O,O)
type L=List[Q]
val N=None
def t(a:Int,b:Int):Q=if(a>b)(Some('-',a-b),(if(b!=0&&b*(a/b)==a)Some('/',a/b)else N))else
(Some('+',b-a),(if(a!=0&&a*(b/a)==b)Some('*',b/a)else N))
def w(a:Q,b:Q)=if(a._1==b._1&&a._2==b._2)a else
if(a._1==b._1)(a._1,N)else
if(a._2==b._2)(N,a._2)else(N,N)
def n(l:L):Q=l match{case Nil=>(N,N)
case x::Nil=>x
case x::y::Nil=>w(x,y)
case x::y::xs=>n(w(x,y)::xs)}
def z(l:L,w:Int)=for(d<-1 to w)yield
n(l.drop(d-1).sliding(1,w).flatten.toList)
def h(s:L):Boolean=s.isEmpty||(s(0)!=(N,N))&& h(s.tail)
def j(s:L,i:Int=1):Int=if(h(z(s,i).toList))i else j(s,i+1)
def k(b:Int,o:Char,p:Int)=o match{case'+'=>b+p
case'-'=>b-p
case'*'=>b*p
case _=>b/p}
val e=getLine
val i=e.split(" ").map(_.toInt).toList
val s=i.sliding(2,1).toList.map(l=>t(l(0),l(1)))
val H=n(s.drop(s.size%j(s)).sliding(1,j(s)).flatten.toList)
val c=H._1.getOrElse(H._2.get)
println (k(i(i.size-1),c._1,c._2))
```
ungolfed:
```
type O = Option[(Char, Int)]
def stepalize (a: Int, b: Int): (O, O) = (a > b) match {
case true => (Some('-', a-b), (if (b!=0 && b * (a/b) == a) Some ('/', a/b) else None))
case false=> (Some('+', b-a), (if (a!=0 && a * (b/a) == b) Some ('*', b/a) else None)) }
def same (a: (O, O), b: (O, O)) = {
if (a._1 == b._1 && a._2 == b._2) a else
if (a._1 == b._1) (a._1, None) else
if (a._2 == b._2) (None, a._2) else
(None, None)}
def intersection (lc: List[(O, O)]): (O, O) = lc match {
case Nil => (None, None)
case x :: Nil => x
case x :: y :: Nil => same (x, y)
case x :: y :: xs => intersection (same (x, y) :: xs)}
def seriallen (lc: List[(O, O)], w: Int= 1) =
for (d <- 1 to w) yield
intersection (lc.drop (d-1).sliding (1, w).flatten.toList)
def hit (s: List[(O, O)]) : Boolean = s match {
case Nil => true
case x :: xs => (x != (None, None)) && hit (xs)}
def idxHit (s: List[(O, O)], idx: Int = 1) : Int =
if (hit (seriallen (s, idx).toList)) idx else
idxHit (s, idx+1)
def calc (base: Int, op: Char, param: Int) = op match {
case '+' => base + param
case '-' => base - param
case '*' => base * param
case _ => base / param}
def getOp (e: String) = {
val i = e.split (" ").map (_.toInt).toList
val s = i.sliding (2, 1).toList.map (l => stepalize (l(0), l(1)))
val w = idxHit (s)
val hit = intersection (s.drop (s.size % w).sliding (1, w).flatten.toList)
val ci = hit._1.getOrElse (hit._2.get)
val base = i(i.size - 1)
println ("i: " + i + " w: " + w + " ci:" + ci + " " + calc (base, ci._1, ci._2))
}
val a="1 3 5 7 9 11"
val b="1 3 2 4 3 5 4 6 5 7 6"
val c="2 6 7 3 9 10 6 18 19 15 45 46"
val d="1024 512 256 128 64 32 16"
val e="1 3 9 8 24 72 71 213 639"
val f="1 2 3 4 5 2 3 4 5 6 3 4 5 6 7"
val g="1 2 4 1 3 9 5 8 32 27 28 56 53 55 165 161 164 656 651 652 1304"
val h="0 0 1 2 3 6 7 14"
val i="0 0 0 0 1 0 0 0 0 1 0"
List (a, b, c, d, e, f, g, h, i).map (getOp)
```
Fails miserably on Peter Taylor's `h`, but I don't see the possibility to heal the program in a reasonable amount of time.
] |
[Question]
[
The question score on Stack Exchange is the total number of upvotes minus the total number of downvotes a question receives. However, the reputation gained/lost for every upvote/downvote is different (eg. 10/-2 on Code Golf).
Given the total reputation earned, the reputation gained by an upvote and the reputation lost by a downvote, list out all possible scores (unweighted, +1/-1 for upvote/downvote) the question could have).
## Rules
* The total reputation and the reputation per vote must be integers
* The upvote-reputation will be positive and the downvote-reputation will be negative
* Impossible question scores are not valid inputs
* You can output the possible question scores as an infinite list or generator, print each individually, etc.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer wins
## Examples
```
[total reputation, upvote-reputation, downvote-reputation] -> [question scores]
[28, 10, -2] -> [2, -2, -6, -10, ...]
[34, 10, -2] -> [1, -3, -7, -11, ...]
[11, 7, -5] -> [1, -1, -3, -5, ...]
[82, 31, -11] -> [2, -18, -38, -58, ...]
[15, 5, -10] -> [3, 4, 5, 6, ...]
[-38, 4, -9] -> [-2, 3, 8, 13, ...]
```
[Answer]
# [Python](https://www.python.org), 92 bytes
*-2 bytes, thanks to UndoneStudios*
*-7 bytes, thanks to SuperStormer*
```
lambda s,u,d:(a-b*2for a in count()for b in range(a)if(a-b)*u+b*d==s)
from itertools import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VY8xboQwEEV7TjGiwmQsYVgUguSbbGMvdoJYbGSbImdJgxQld0qZmwQbtkhlPf3veTMf38t7eLNm-9T8-rUGTbuf613MchDgccWhLwSVZa2tAwGjgZtdTShIZBnZCfOqCkFGHYukXJ9kOXDuSaadnWEMygVr7x7GebEulKfjd1AagvKhSBaceEv6DCDO9TfrVJytjzAFAIsbd3MKUZmB55iTFOzqqecTZYTz6ugCSKfElD1-5Xs1S7q6Q1YhrcmBzeUfMobPSNuTuhobhpSxR9piu2N1Im06vCB9ObHC2I0rpRWOQ7fteP8A)
*outputs a generator*
**99 bytes without using `itertools`**:
```
lambda s,u,d:(a-b*2for a in N()for b in range(a)if(a-b)*u+b*d==s)
def N(i=0):
while 1:yield i;i+=1
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VY9BboMwEEX3nGLECpOxhCGolMpX6Am6MbHdWFATGVCUs2SDVLV36rI3KbbJoivP03-jP75_X27zebTrp-ZvX8usafNzGsRHJwVMuKBsM0G7vNSjAwHGwmtG_Nz52Qn7rjJBjPYSyZdDl0vOJ5JIpTfT8IK0CVzPZlDA2ptRgwTzYg6c7VW_XpzVNGehDHte-w3wFdNpdMrX6BiGAODijN10H6KykqeYkhBsV_Qt7ykjnBfRBeicEn3y2Eo3NQl1ZYOsQFqSiNXxHzKGT0jrnZoSK4aUsUdaY71hsSOtGjwifd6xQO_6k8IJ8aPrGt8_)
## Explanation
Goes through all pairs `(x,y)` of non-negative integers and checks if `x` upvotes and `y` downvotes gives the right score
---
# [Python](https://www.python.org), 115 bytes
```
def f(s,u,d):
i=s<0;g=math.gcd(u,d);a=s*pow(d//g,-1,u//g)%u/g
while 1:yield(s-d*a)/u-a-i*(u+d)/g;i+=1
import math
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VZBPboQgGMX3noKYNAHno4qOqaPlMHZAJc6oEchkzjKb2bR36rI3KfgnadmQH-_Bex-Pr-luunF4Pj-taWjxrYVsUIM1WBCkDJDi-j2pWn6tTffangX251XNdTSNNyziuAXKwLqdvNi4DdCtUxeJWHlX8iKwpiKqSWxpTVWE7UGQuK3UgbNAXadxNsi_u0X_-GgjtVnToee5b4CacUb6PM4SqeFvNbemWQ3O7kWQg-AhhGQRVIP7kveUEc6T1YvQxyzrPthvhc4aLHFpASwBmpIVs-M_ZAzegOYbFSlkzI3MdjWH3GGyIc0KOAI9bZiA9_pKS4V10P2vfwE)
*Direct solution, sadly longer than brute force*
*`from math import*` is not possible, as it will overwrite `pow`*
## Explanation
1. Solve `b*u+a*d=s` by using `s=a*d mod u` -> `a=d⁻¹*s mod u` (dividing out the gcd of u and d to ensure inverting d is possible)
2. compute `b` from `a`
3. The possible scores are `(b-a)+k*gcd(u,d)` for an integer `k`
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~17~~ ~~14~~ 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
-5 bytes (and even slower than before üòÖ) thanks to *@CommandMaster*.
```
‚àû√ì í¬π*OQ}Œµ2¬£√Ü
```
Two separated inputs \$[upvoteRep,downvoteRep]\$ and \$totalRep\$.
Outputs an infinite list that includes duplicated items.
[Try it online.](https://tio.run/##ASYA2f9vc2FiaWX//@KInsOTypLCuSpPUX3OtTLCo8OG//9bMiwtMV0KMg) (Extremely slow brute-force that barely outputs the first two unique terms of the example test case, so no test suite with all test cases.)
We can prevent the duplicated items for +2 bytes by adding a trailing `}√ô`:
[Try it online.](https://tio.run/##ASkA1v9vc2FiaWX//@KInsOTypLCuSpPUX3OtTLCo8OGfcOZ//9bMiwtMV0KMg)
**Earlier 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) answer (partially also by *@CommandMaster*) that's a lot faster:**
```
‚àû√ù‚Ǩ√£‚Ǩ` í¬π*OQ}‚Ǩ√Ü
```
Similar I/O as above.
[Try it online](https://tio.run/##yy9OTMpM/f//Uce8w3MfNa05vBhIJJyadGinln9gLUig7f//aEMDHV2jWC4jCwA).
We can prevent the duplicated items for +1 byte this time by adding a trailing `√ô`:
[Try it online](https://tio.run/##yy9OTMpM/f//Uce8w3MfNa05vBhIJJyadGinln9gLUig7fDM//@jDQ10dI1iuYwsAA) or [verify the first five values of all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWXCo4ZZoWH/H3XMOzz3UdOaw4uBRMKpSRFa/pGBtSCBtv@HZ5oeWqzzPzrayELH0EBH1yhWJ9rYBM40NNQx19E1BbIsjHSMDXV0DQ1BoqY6pkCmAZCpa2yhY6KjawlkGukYAQVjYwE).
**Explanation:**
```
‚àû # Push an infinite list of positive integers: [1,2,3,...]
Ó # Convert each to a list of exponents of its prime factorization:
# [[],[1],[0,1],[2],[0,0,1],[1,1],[0,0,0,1],[3],[0,2],[1,0,1],...]
í¬π*OQ} # Only keep all valid lists for the given inputs:
í } # Filter this infinite list of lists by:
¬π* # Multiply the first two values in the list by the first input-pair of
# [pos,neg] (or if it's a singleton list, multiply its value by just `pos`)
O # Sum this pair (or singleton)
Q # Check whether it's equal to the second (implicit) input-integer
ε2£Æ # Calculate the question-scores of the remaining valid lists:
ε # Map over each remaining list in the infinite list:
2£ # Only keep (up to) the first 2 values
Æ # Reduce it by subtracting: [a,b]→a-b or [a]→a
}√ô # (optional) Close the map, and uniquify this infinite list of values
# (after which the infinite list of scores is output implicitly as result)
```
```
∞Ý€ã€` # Generate an infinite list of non-negative pairs:
‚àû # Push an infinite list of positive integers: [1,2,3,...]
√ù # Convert each value to a [0,v]-ranged list: [[0,1],[0,1,2],[0,1,2,3],...]
ۋ # Map over each list, and get its cartesian power of 2 to create pairs:
# [[[0,0],[0,1],[1,0],[1,1]],[[0,0],[0,1],[0,2],[1,0],...],...]
€` # Flatten the list of lists of pairs one level down:
# [[1,1],[1,0],[0,1],[0,0],[2,2],[2,1],[2,0],[1,2],[1,1],[1,0],...]
í¬π*OQ} # Only keep all valid pairs for the given inputs:
í } # Filter this infinite list of pairs by:
¬π* # Multiply the values in the pair by the first input-pair of [pos,neg]
O # Sum the values in this pair together
Q # Check whether it's equal to the second (implicit) input-integer
ۮ # Calculate the question-scores of the remaining valid pairs:
€ # Map over each remaining pair in the infinite list:
Æ # Reduce the pair by subtracting: [a,b]→a-b
√ô # (optional) Uniquify this infinite list of values
# (after which the infinite list of scores is output implicitly as result)
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~60~~ 49 bytes
```
->r,u,d{0.step{|a|q=r-d*a;q%u<1&&q>-u&&p(q/u-a)}}
```
[Try it online!](https://tio.run/##RcxBCsIwEAXQfU8xUAwqMzHTGKxoe5GSRaV2nUSzkLZnjymirob/@H9CvL3S2CRqA0YcJiUfz7ub5n72TaBh31/8Jl5ZCN9SFMJt/SFSv1uWVIKDsatqZIVU2eKT9REhA/yFGeGUwXyhrhB0RmL@dQyCWUXZYs2ka4T8ic4WoKQWOlpHCJk5HymlTW8 "Ruby – Try It Online")
For any number of downvotes, check if the difference between the score and the sum of downvotes can be divided by the upvote score.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~ 72 67 66 65 57 ~~ 55 bytes
-6 thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor)! (Inlining the while loop by use of `(yield ...)` being `None`, in turn allowing for post-incrementing. Suggesting printing.)
-7 more thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor)! (Refactor to a recursive function.)
-2 thanks to Neil (Since `d` is guaranteed to be negative `0<=r/d` may be replaced with `0>=r`).
```
def f(r,u,d,p=0):r%d==0>=r!=print(p-r/d);f(r-u,u,d,p+1)
```
A function that accepts the reputation, `r`, the upvote delta, `u` and the downvote delta, `d`, and prints the potential scores forever.
**[Try it online!](https://tio.run/##XY/dToQwEIXveYrxwrRdp9jyExFTX8QYg9uiJASaUhL26RGKC65z05ye70zm2Iv/7ru0sG6etamhpg5H1GiVYKW710qJV@XulHVN56nl7lGzlwXi44Y9SDY7U7UfAQAF4Y3WVVtkYmUEyzQ1nPtxRRSI0lXNYML/EaYTgum0IgiEBe@r7T@rdqDsjYQseQeuQEZR3TvwZvDQdEADSpMCpUCeMNx0mt1qKfEJeX6VRYKpRC7l7ueYL1pcNU8LzJA/77643ceTXf82DCeq7H@r9c6tjneXjVynpqfDMdPZWH@Yf@IkjmPC5h8 "Python 3 – Try It Online")** (Harnessed to halt printing early.)
### How?
`p` is the upvote count and is initialised to `0` for the first call in the function's parameters (`,p=0`). Subsequent calls (`f(r-u,u,d,p+1)`) are each for one more upvote (`p+1`) and for the outstanding reputation (`r-u`).
Each call evaluates whether any non-negative (`0>=r`) integer number of downvotes is valid (`r%d==0`) and prints the upvotes less the downvotes (`print(p-r/d)`) if so (when `!=` is reached causing evaluation).
[Answer]
# [Rust](https://www.rust-lang.org/), ~~127~~ ~~123~~ 93 bytes
Port of [@G B's Ruby anwser](https://codegolf.stackexchange.com/a/265165/110802) in Rust.
Saved 30 bytes thanks to the comment of [@c--](https://codegolf.stackexchange.com/users/112488/c)
---
Golfed version. [Try it online!](https://tio.run/##RclBCoUgFEDReauwRlovsEZB2F6epCCYheno6dr9NPqTy4Eb85uaDexCF7igzpvErGolQoaz8HLlxBC@6uLv@yFnGY550uOpVKQnupB6PlDtBsBZi/r/RyQ9qaUa/xrCT1VwCVK03fJ1g0XCvIq9th8)
```
|r,u,d|(|mut a,mut b|loop{if a*u+b*d==r{print!("{}
",a-b)}if a*u+b*d>r{b+=1}else{a+=1}})(0,0)
```
Ungolfed version. [Try it online!](https://tio.run/##fZBNCoMwEIX3OcWrK60R1G5KJb1KiagQ0CjRbCo5e5rWf1o6i5nhzTcz8JTuB2sriUrI4tFxoXpf3SAuKYWea/GpAUYCF3U5oNEDOBji7CDlmzTpbdvNWwv2dAjHGRqhw88osnW8NqJy2B1qt/qOHCFDsvEGZd2XE83YF94pIYdannxvNB51TyPkQXZA@O@L43@ITNkQ4mxruJD@Ys3Ow/RKkcQUUep@Gmtf)
```
fn find_pairs(r: i32, u: i32, d: i32) {
let mut a = 0;
let mut b = 0;
loop {
let z = a * u + b * d;
if z > r {
b += 1;
} else if z == r {
println!("{}", a - b);
a += 1;
} else {
a += 1;
}
}
}
fn main() {
find_pairs(28, 10, -2);
}
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 44 bytes
```
NθNηNζ≦⁻×⁺ηζ∧›θ⁰±÷θ±ηθW¹«F¬﹪θζ«I÷θζD⎚»≧⁺⁺ηζθ
```
[Try it online!](https://tio.run/##XU/NisIwED43TzHHKaSg6GEXT6IgghZZ9gWijU0gTWp@FCo@ezYpsqhzmu9nZr45CWZPhqkYt7oPvg7dkVu8lAvyisUHHhLes37pnGz1jp897qUOjsKv7LjDgwoOBYWhpLDUDW4sZz6vpTBJVM3bBHGr/VpeZcMz/@REmYtCDnATUnHAaQl3UpyNBaxNOmSaoEweGZIzS8XBSu1xxZx/35kNi6SvQ9fj2K0UZ3ZsH6T4f@BHtsKPoSm8Rs8hHjFWsy8yJ9V3rK7qDw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
NθNηNζ
```
Input the question, upvote and downvote reputations.
```
≦⁻×⁺ηζ∧›θ⁰±÷θ±ηθ
```
If the question reputation is positive, adjust it for the minimum number of upvotes required. If it is negative, just negate it.
```
W¹«
```
Repeat indefinitely.
```
F¬﹪θζ«I÷θζD⎚»
```
If the question reputation is a multiple of the downvote reputation then output the possible score.
```
≧⁺⁺ηζθ
```
Add both the upvote and downvote reputations to the question reputation. This allows the score to be determined solely from the downvote reputation.
Note that the behaviour on TIO is for `Dump` to pause 10ms since the last `Dump`, meaning that the script usually times out after printing 6000 possible scores. The newer version of Charcoal on ATO supports the `--nt` option which disables this pause, allowing it to fill the 128KB output buffer instead. [Attempt This Online!](https://ato.pxeger.com/run?1=XVDLSgMxFMXl5AfchlndgQQUXVS6Ki1IwQ5F3ImLdCYzCWSSMY8KI_0SN10odOf_-DUmY5HqXd1zzn2ce98OlWC2Mkzt9x_BN3TydXa-1H3wZeg23MJzMUWnWPzDQ8Qr1s-ck62-442HldTBEfwgO-5grYIDQfBQEDzTNdxaznwaS_BFpEreRghL7RdyK2ue-CMnihQEJwMvQiqO4bLAryhrjMVQmrjI1EGZ1DLEyiRlayu1hzlz_u_MVDCN-iJ0PYzZXHFmx3SHst8D7mUr_Gia4FPrycTu3W0qd_zS52NOtyonOKdU-_zpQK8m6BrRmx_5Gw "Charcoal – Attempt This Online") Link is to verbose version of code.
] |
[Question]
[
Part of [**Code Golf Advent Calendar 2022**](https://codegolf.meta.stackexchange.com/questions/25251/announcing-code-golf-advent-calendar-2022-event-challenge-sandbox) event. See the linked meta post for details.
---
Christmas is coming up, and Santa hasn't kept to his diet very well this year. Due to his size, he is getting the elves to collect a list of all the chimneys he will be able to fit down. Unfortunately, chimneys these days are a bit of a maze, and he can't just drop straight down like he used to.
**Task:** Given Santas width as an integer and a binary matrix representing the chimney, output whether or not Santa will be able to fit down the chimney.
**Rules**
* Santa is able to "fit" down the chimney if he can enter it at the top and exit at the bottom, while only moving downwards or sideways through the cavity sections of the chimney.
* Santa cannot move up
* Assume Santa's height is always 1
* There will only be one entrance to the chimney, and one exit from the chimney
* The matrix representing the chimney should consist of two values, one for brick (which Santa can't move through) and one for cavities (which Santa can move through). These can be of type `integer`, `string`, `float` or any other type, as long as a distinction can be made between the two.
* The format of the matrix is flexible - any standard subsitution for a matrix (list of strings, list of lists etc) is allowed
* The output can be any valid truthy/falsy output, or two values/states chosen to represent the truthy falsy output (i.e output `1`/`None`, `1`/`Error`)
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test Cases
**Truthy**
```
Width = 1
Chimney=[
"101",
"101",
"101"
]
```
```
Width = 2
Chimney = [
"110011",
"110011",
"100011",
"100111",
"100001",
"110001",
"111001",
"111001",
]
```
**Falsy**
```
Width = 1
Chimney=[
"101",
"010",
"101"
]
```
```
Width = 2
Chimney = [
"100111"
"100110"
"100110"
"100010"
"111010"
"111010"
"111010"
"111010"
]
```
```
Width = 1
Chimney = [
"0111",
"1110",
"1110",
]
```
```
Width = 1
Chimney = [
"1011111",
"1011111",
"1010001",
"1000101",
"1111101",
"1111101",
"1111101",
"1111101",
]
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~18~~ 16 bytes
```
vlvṠλĠ~•vA⋎f;RA¬
```
[Try it online!](https://vyxal.pythonanywhere.com/#WyIiLCLilqHhuKN2ZuKMiiAjIGxpc3Qgb2YgaW5wdXRzID0+IGNoaW1uZXksIHdpZHRoIiwidmx24bmgzrvEoH7igKJ2QeKLjmY7UkHCrCIsIiIsIjFcblwiMTAxMTExMVwiXG5cIjEwMTAwMDFcIlxuXCIxMDAwMTAxXCJcblwiMTExMTEwMVwiIl0=) or [Test suite.](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwidmx24bmgzrvEoH7igKJ2QeKLjmY7UkHCrCIsIiIsIjEsW1sxLDAsMV0sWzEsMCwxXSxbMSwwLDFdXVxuMixbWzEsMSwwLDAsMSwxXSxbMSwxLDAsMCwxLDFdLFsxLDAsMCwwLDEsMV0sWzEsMCwwLDEsMSwxXSxbMSwwLDAsMCwwLDFdLFsxLDEsMCwwLDAsMV0sWzEsMSwxLDAsMCwxXSxbMSwxLDEsMCwwLDFdXVxuMSxbWzEsMCwxXSxbMCwxLDBdLFsxLDAsMV1dXG4yLFtbMSwwLDAsMSwxLDFdLFsxLDAsMCwxLDEsMF0sWzEsMCwwLDEsMSwwXSxbMSwwLDAsMCwxLDBdLFsxLDEsMSwwLDEsMF0sWzEsMSwxLDAsMSwwXSxbMSwxLDEsMCwxLDBdLFsxLDEsMSwwLDEsMF1dXG4xLFtbMCwxLDEsMV0sWzEsMSwxLDBdLFsxLDEsMSwwXV1cbjEsW1sxLDAsMSwxLDEsMSwxXSxbMSwwLDEsMCwwLDAsMV0sWzEsMCwwLDAsMSwwLDFdLFsxLDEsMSwxLDEsMCwxXV0iXQ==)
Takes input as width and a matrix of 0's and 1's, in either order.
## Explanation
Since Santa cannot move up the chimney, we can iterate through each chimney's row until we arrive into a result. To check if we can move down then sideways to the 0's: (Assuming width 1)
```
[1 0] [0 1 1] [1] [1] [1] => previous (molded to current)
0 0 1 1 1 => are all of them true?
OR OR OR OR OR (bitwise)
[1 1] [0 0 0] [1] [0] [1] => current
= = = = =
[1 1] [0 0 0] [1] [1] [1] => new
```
#### Commented code
```
vl # cumulative groups (vectorise)
vṠ # sum (doubly vectorise)
# - this is "any?" as truthy/falsy only matters in this case
R # reduce by
λ ; # a lambda taking two elements:
Ġ # group the current consecutively
• # mold the previous
~ # do not pop the items
vA # all? (vectorise)
⋎ # bitwise or (vectorises)
f # flatten
A¬ # is not all true?
```
[Answer]
# JavaScript (ES7), 105 bytes
Expects `(width)(chimney)`.
```
w=>g=([v,...a],m=2**w-1,c,r='0b1'+v,h=(k,M=m,q=r&M)=>M%1||M>r|c*q?0:g(a,M,1)&!q|h(k,M*k))=>v?h(2)|h(.5):1
```
[Try it online!](https://tio.run/##jY7NCoJQEIX3PoUJ1b02XWaENsLoE9wniBZmpf2aGrrx3c2C8FoR7T4O55s5h6iKyrjYX2/zS7bZtjtuaw4SFssKlFLRCs7suW49J4ih4CmuaTqrIGVxBM1nyLmYaMmBHlPT6KBoYjcP0U9EBBpITkZ5kz6q7lF2rSpMhSe7RC2kT22cXcrstFWnLBE7QVIsLdt2CMmBD7BWUlrW0PBeBiHSq2syDpjMHI1@z/TO395@DEXCP4cOR1DvDbi/16V/8q@hxlMytafU3gE "JavaScript (Node.js) – Try It Online")
### Commented
```
w => // outer function taking the width w
g = ( // inner recursive function taking:
[ v, // v = next row of the chimney
...a // a[] = array of remaining rows
], //
m = 2 ** w - 1, // m = bit mask for Santa
c, // c = flag telling if horizontal collisions
// must be taken into account
r = '0b1' + v, // r = the row with the binary prefix and an
// extra leading '1'
h = ( // h = recursive search function taking:
k, // k = direction as a multiplier (2 or 1/2)
M = m, // M = copy of m
q = r & M // q = collision mask of Santa with the chimney
) => //
M % 1 || // if Santa is too far to the right
M > r | // or too far to the left
c * q ? // or c is set and there's a collision:
0 // abort
: // else:
g(a, M, 1) // do a recursive call to g with the
// collision flag enabled
& !q // ignore the result if q was not 0
| h(k, M * k) // do a recursive call to h with M updated
) => //
v ? // if v is defined:
h(2) | // try to move Santa to the left
h(.5) // try to move Santa to the right
: // else:
1 // success
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Å»γD€gŠr£P~˜}θJÎ×å
```
Port of [*@u-ndefined*'s Vyxal answer](https://codegolf.stackexchange.com/a/255178/52210), so make sure to upvote him/her as well!
Chimney as first input as an integer-matrix, width as second input-integer.
[Try it online](https://tio.run/##yy9OTMpM/f//cOuh3ec2uzxqWpN@dEHRocUBdafn1J7b4XW47/D0w0v//4@ONtAxBMFYnWgwrWOAxIrlMgQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpSbKVQnplSkmGloGRfmWCvpJCYl6KQnJGZm5daaaXApWTvdWi3DpeSf2kJUDFEUej/w62Hdp/b7PKoaU360QVFhxYH1J2eU3tuh5dBxOHph5f@1zm0zf5/NBAY6hjoGMbqoNGxILYCWBokABSCSqLyDDB4hmhyBij6EDxDrLxYHSMMa9GMxSVugEccYYUBki8N0OTQHIrLkVjEERDDGxBlIG0G2AIXu1sNcPAQxkDsooQHdyNq4KIoRHUp3Jcwj2DwMcPXECOcqMEHOSsWAA).
**Explanation:**
```
Å» # Cumulative left-reduce the rows of the first (implicit) input-matrix,
# keeping all intermediate steps (unfortunately)
γ # Split the row into groups of the same adjacent values
D # Duplicate this list of groups of 1s/0s
€g # Pop the copy, and get the length of each group
Šr # Change the stack order from a,b,c, to b,a,c (triple-swap and reverse stack)
£ # Split the previous rows into groups of those lengths
P # Get the product of each inner group to check if all are truthy
~ # Bitwise-OR these values with the groups of the current row
˜ # Flatten it for the next iteration
}θ # After the cumulative left-reduce with intermediate steps: keep the last result
J # Join this list of 0s/1s together to a string
Î # Push 0 and the second input-integer
× # Repeat the "0" that many times as string
å # Check if it's a substring in the left-reduced result
# (after which this is output implicitly)
```
[Answer]
# [J](http://jsoftware.com/), 67 47 bytes
```
1 e.[([*&;]<@(##+./);.1~2~:/\_,[)/@|.@E.~0$~1,]
```
[Try it online!](https://tio.run/##fY9PS8NAEMXv@ymmSehmYzo7k4PQjYVFsSAUD@ItxiCSUoIg2HgQZb96zJ82RKkeht/OvNn3dqtmOTOcn8/MUkrhodzCyoCEGAhMWwuEq7vNumEoMQuzaJ7mFzb0/TPUKkV2iTP6oYgzpe0X2mt0FDiO80aJ20uESNuQPttdwOjRFE7ZcKFdiQUDt@ZUsVe0s6BCbX1zgzZuO447B9WZ8TwOyIi63NcrLJ93r3brwEOPUiwSIboJyPu393r3IYVg6Ba7h5Ng4rGUEMlUYiLmEXQEHzoatB48gToGrp9e9qfyiOlk3mjNTBP06@35L6ifCYMJH/TfKndynzJy@EKf01/k/6iabw "J – Try It Online")
-20 based on approach from [u-ndefined's answer](https://codegolf.stackexchange.com/a/255178/15469)
## original graph theory approach, 67 bytes
```
*/@(0{+./ .*^:_~)@(1&~:*1>:|)@([:-/~$j./@#:I.@,)@(1,~1,])@E.~1&,$0:
```
[Try it online!](https://tio.run/##hY9BS8NAEIXv@yumsXS7MZ3M60HoSmVRLAjiQbxJDSIpJQiCjQdR9q/HTdKGKFEPwzc7b@Y9tqgWI4v1ycgutFYR6w0tLWlKSMiGmjFd3F6vqjh1U/k45pQ4frCZN26Kibcxzuxn6O/tLPXjglN3ZK/YJbWceCRr4y7ZY5KMxVZG3ZwzDTiF25wzEEKgFIiyMPvHTJX5rlxy/rR9cRtPEUdyytlcqXpC@u71rdy@a6VA9WL9GVEQdGWUmvcliAAd5ADsX9JqDdCDOQSuHp93Q3kCGczrrAHpoVkP/W8w3xNaE@z1nypquUnp2H6hyWkO8RdN9QU "J – Try It Online")
Convert to adjacency matrix, transitive closure, check if first row is all ones.
[Answer]
# Python3, 274 bytes:
```
V=lambda b,w,X,Y:0<=Y and Y+w<len(b[0])and sum(b[X][Y:Y+w])==0
def f(b,w):
q,S=[(0,i)for i,a in enumerate(b[0])if V(b,w,0,i)],[]
while q:
x,y=q.pop(0)
if x==len(b)-1:return 1
for X,Y in[(x,y+1),(x,y-1),(x+1,y)]:
if V(b,w,X,Y)and(X,Y)not in S:q+=[(X,Y)];S+=[(X,Y)]
```
[Try it online!](https://tio.run/##hZHdbsIwDIWv16ewuErWMCUtSFNHrvYISIyqiqYCrahE058VQZ@eOS0pFA3tyo7z2ec4KdtmX2j/vawvl5U8xPlmF8OGndiahQFfyBBivYPQPS0OiSabiCtqCj/HHA9rFYUB3ikqJXd2SQopwV4aOFCxpYwIZxlNixoyFkOmIdHHPKnjJukHZSmsDM8MplikHDjts0MCFQ6AM2tl9VYWJeEUjwifpexM0KkI6qQ51hoE3hgBdIsCEcEmV1Bm4rSLrmAtVWYeDHIImyWIibpojLNlULno11TUx3JIL2anpvjeki0u9XIVjaLXPC5JphsGaLxb0AzZKsf5ynbNXoBEZ87nPst10goZORPBxYSNgqN62EPYG2BzMrjgXPToLeN3mbjV@MDZTDxmVyl/5Mu/88UFf/Q1G/maXX3dKwvbdJfZQVj5N7NK85Gtea806IhbT7dJWePDk5R032KfmDLoX57SPwHPAt4TwLeA/wSYWWD2BJhbYE7p5Rc)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 65 bytes
```
Nθ≔⪫11Sη≔⌕Aη×0θζWS«≔⪫11ιι≔Φζ¬Σ✂ικ⁺κθ¹ζFζF⁻⟦⊖κ⊕κ⟧ζ¿¬Σ✂ιλ⁺λθ¹⊞ζ뻬ζ
```
[Try it online!](https://tio.run/##ZY9Ba8MwDIXPza8QOcngQbxrToVR6GAlkN7GDl3qNiKKszp2Bxn77ZmdtV1GD@Ih9J4@qap3tup2PI5r8@Hdxrfv2uJJ5Mmy7@lo8Lkjg6lSqYTJUTpL5ohCSKj/XCsy@yUz1hK21Ooe0ywETtE1BNdnTawB/y@Ar2RxDyERK7@NVsQuXDRI2HQOS99iyVRpJAmNhIJ9j00kSVBCXHmLQ2cBBwGTvpAJrtcnXVndauP0HhsR35n3bzEpgA6AdyC@gHgGgsL3dTyLA@87KcJTbkqGLfk4PiZKZZlSN8muoi5d9jubRM1kfDjzDw "Charcoal – Try It Online") Link is to verbose version of code. Takes input as an integer followed by a list of newline-terminated binary strings and outputs a Charcoal boolean, i.e. `-` if Santa sets stuck, nothing if he can drop down. Explanation:
```
Nθ
```
Input Santa's width.
```
≔⪫11Sη
```
Input the top of the chimney, but ensure that the edges are solid.
```
≔⌕Aη×0θζ
```
Find all of the places where Santa could start lowering himself down.
```
WS«
```
Loop through the rest of the chimney.
```
≔⪫11ιι
```
Ensure that the edges are solid.
```
≔Φζ¬Σ✂ικ⁺κθ¹ζ
```
Keep only the positions that are wide enough in the new row.
```
FζF⁻⟦⊖κ⊕κ⟧ζ
```
Loop through the neighbours of the found positions, without repeating a position.
```
¿¬Σ✂ιλ⁺λθ¹⊞ζλ
```
If Santa can move sideways then add this position.
```
»¬ζ
```
Output whether Santa got stuck.
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 30 bytes [SBCS](https://github.com/abrudz/SBCS)
```
{0∊↑(∊∨(∧/¨∧⊢)⍤⊂⍨1,2≠/⊣)/↓⍵}∨/
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=qzZ41NH1qG2iBojqWAGklusfWgEkH3Ut0nzUu@RRV9Oj3hWGOkaPOhfoP@parKn/qG3yo96ttUDF@gA&f=hY@xDYAwDAT7TBHRuP2jZx1GoWdFJgEiJ3EQgia6@N//Mnk1bDm23RCWw5vmoCFRhAbqQJuoehwYICWedUJvdSETd3Twnev/DbGt5tEMgzxxG7wyUD2klHoA/3QC&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f)
Input width on the left and a binary matrix representing the chimney on the right.
[Answer]
# [Python](https://www.python.org) NumPy, 133 bytes
```
def f(w,A):
while w>1:A=A[:,1:]|A[:,:-1];w-=1
p=~A.T@~A
for a in A:b=p^p;b[range(len(p)),-a.cumsum()]=~a;p=p@[[email protected]](/cdn-cgi/l/email-protection)
return p.any()
```
[Attempt This Online!](https://ato.pxeger.com/run?1=rZLBSsNAEIbBm_MUS067kISMJ0lZaRB8goqHECVJNybQbIY0MQSkN5_CSy_6Tvo0Nk2TtiJYxL3Mv8POP98s8_pObZUWer1-q6vEuvx4mauEJbwxPeECa9JsoVhzha4nPd810Q2eu-haGEwaSyIwkivPnk1XHrCkKFnIMs08N5J0T5PIL0P9qPhCaU5CmFZox3W-rHMuArkKJyRpGk0jewasVFVdakZ2qFsuepjPs5ssp6KsmK5zalm4ZJoAOkJNScvjDnFzdrWa7PjBjwP7KVMNN27REHa4rFpSPCqKhYBzuMvmVcokQ4DrNMu1aqUPBjpomEcBAgAqM13xhG9rzG3DXY0QAkari9Fqc-nM0HGwN9or50DhPueM7waF39XpID_O5KDzHzMdUuNgeaCGNpvMr-pPI_UcIwXuHU_5o36dhh3_Ag)
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 101 bytes
```
f(c,w)=a=[1..#c-w--];[while(j=0;b-a=[[s,j&&a[j],j++<#a&&a[j+1]]&&!r[j..j+w]|s<-t],b=a)|r<-c~,t=b=a];a
```
[Attempt This Online!](https://ato.pxeger.com/run?1=lVJLasMwEKU3sRswFpaMJquCrVxkEGVi4tYiFOG4mEDoRbrJpvRMzWkq2bFjJ1006MN780bzRkif35bq6vnFHo9f700pnn42ZVzwlilSCGm6KEQrhM6wfa22m9goma2Fk3DHTRQRGs1NkuQL6kgCWkdRWKNJU5O0-rDLRaP5WhE71LkoPnijHNEZ9WanhxNZu93HFIhVYOvqrYkJQfPgsZuES4-96FgYlmfVxxnjASIClxyyye5kv7ziuYt0yhTLKwyzuJzkDxhusfNYnn284qvImw6uq8OYNcfD6b76P_HYwcUDpjmzPmAY2V_sctexm7Ee3Ms6X836Jx7-1S8)
] |
[Question]
[
Given two integer matrices `a` and `b`, your challenge is to replace any occurences of `b` in `a` with a matrix of the same size filled with 0s. For example:
```
Given:
a: [ [1, 2, 3],
[4, 3, 2],
[3, 5, 4] ]
b: [ [3],
[2] ]
b occurs once in a:
[ [1, 2, **3**],
[4, 3, **2**],
[3, 5, 4] ]
Fill that area with zeroes:
[ [1, 2, 0],
[4, 3, 0],
[3, 5, 4] ]
And this is your result!
```
You can assume occurences of `b` will never overlap, but there may be none. `b` will never be larger than `a`, or empty, and will only contain positive integers.
## Testcases
```
[ [1, 2],
[3, 4] ]
[ [1] ]
=>
[ [0 2],
[3 4] ]
[ [4, 4, 6, 7],
[4, 2, 4, 4],
[7, 3, 4, 2] ]
[ [4, 4],
[4, 2] ]
=>
[ [0, 0, 6, 7],
[0, 0, 0, 0],
[7, 3, 0, 0] ]
[ [1, 2] ]
[ [3, 4] ]
=>
[ [1, 2] ]
[ [1, 2],
[3, 4] ]
[ [1, 2],
[3, 4] ]
=>
[ [0, 0],
[0, 0] ]
[ [1, 2],
[2, 1] ]
[ [1],
[2] ]
=>
[ [0, 2],
[0, 1] ]
(suggested by tsh)
[ [2, 3, 4],
[3, 2, 3],
[4, 3, 2] ]
[ [2, 3],
[3, 2] ]
=>
Undefined behaviour, will not be given (overlap)
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 20 bytes
Anonymous infix lambda taking `a` and `b` as left and right argument. Requires 0-based indexing.
```
{0@((⍳⍴⍵)∘.+⍸⍵⍷⍺)⊢⍺}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGXF5AslpdJyZaHSgWBGTkKYCZXsH@fo/aJms8apsI4/Xu0gRiEEIS21qr8Kh3rkJGak5BapFCWn6RAkhcwVPf/3@1gYOGxqPezY96twDVaT7qmKGn/ah3B5D9qHc72LSuRUCq9n8a0A2PevsedTU/6l0DVH1ovTHEiuAgZyAZ4uEZ/F89WiHaUEfBKFZHQSHaWEfBJFYhVl0hTcFLASwD4nGBWCZAKR0FMx0Fc7BKINsILGIC5prrKBiDuUYo2uHyMBkuuHXIymDWchFwDLoMAA "APL (Dyalog Unicode) – Try It Online")
`{`…`}` [dfn](https://apl.wiki/dfn); arguments are `⍺` and `⍵`:
`⊢⍺` on `a`,
`0@(`…`)` put zeros **at** the following positions
`⍵⍷⍺` indicate (Boolean matrix) locations `b` begins (top left corner) in `a`
`⍸` indices where (list of 2-element lists) those locations are
`(`…`)∘.+` all summation combinations (gives 3D array of 2-element lists) with:
`⍴⍵` the shape of `b`
`⍳` all the indices of an array with that shape
[Answer]
# MATLAB/[Octave](https://www.gnu.org/software/octave/) with Image Processing Toolbox/Package, 78 bytes
```
@(A,B)A.*~conv2(reshape(all(im2col(A,size(B))==B(:),1),size(A)-size(B)+1),B>0)
```
[**Try it online!**](https://tio.run/##ZY5RC4IwFIXf/RX3RditJTlXgmKk0D/oTXwYMknQlCYSPfTX1zaTHoLL5eycj3M31JOYpW6yIAj0meS0wDzYvOvhPjPykOomRklE15G2Z/XQGUC1L0kKxCwrSII0xMXJcfdNtsYqTnvUPlyeoh87mXgNKUNgEKXAIQKWmnUAXlEojcUq9Hy4SjVBLZRUK24px4QGMBanYOZIIU6tYO7JU4gpRE4zC3NrcVe61Lgrpgj/alf9SxiELnGf0h8)
### Explanation
Consider the example
```
A = [1 2 3
4 3 2
3 5 4]
B = [3
2]
```
`im2col(A,size(B))` takes sliding blocks of `A` with the size of `B` and arranges them as columns:
```
1 4 2 3 3 2
4 3 3 5 2 4
```
`...==B(:)` takes each column in the above matrix and compares it element-wise with `B(:)`, which is `B` linearized into a column vector:
```
0 0 0 0 1 0
0 0 0 0 1 0
```
`all(...,1)`gives `1` for columns that only contain nonzeros:
```
0 0 0 0 1 0
```
`reshape(...,size(A)-size(B)+1)` arranges the results as a matrix, so each position corresponds to one of the original blocks in `A`. This matrix is smaller than `A`, depending on the block size:
```
0 0 1
0 0 0
```
`conv2(...,B>0)` gives the 2D convolution between the above matrix and a matrix of ones the same size as `B`. This has the effect of extending the matrix size to that of `A`, and enlarging each `1` above to a "patch" the same size as `B`:
```
0 0 1
0 0 1
0 0 0
```
`A.*~...` multiplies `A` element-wise by the above matrix negated, which acts as a mask that sets the desired entries to `0`:
```
1 2 0
4 3 0
3 5 4
```
[Answer]
# [J](http://jsoftware.com/), 29 27 bytes
```
]*1-[:+/-@,/@(#:i.)@$@[|.E.
```
[Try it online!](https://tio.run/##bY1BS8NAEIXv@RWPNDS7ZnfSTYPC0MKiRBCKB68htCWkpqKm1Hqr/etxsxpPHoaZee@bNy99SPEOS0YMhRnYlSbcPa3u@@rK6JKTVFuVWjHhPUkb2fJMBfUyeLwljERBZ7qUrFI11el0T@nAeeLts27x2r0/N0dsD4djt61bb8x4Ixy0sCwWViQuO0xkaC6RrSb8QFbZguSm@gJzFZyaj9OShEFTt12stY7DtUTl18C7EIqMxA4GmeI58l81R644RzZYTkXkKsc1buBa5hc3D0425gzXA67Y/Ilj6j8f3N@feK9nMP03 "J – Try It Online")
It took me a while to see this approach.
At first, the problem seems easy, because J has `E.`, which immediately finds the matches by returning a 0-1 matrix with a 1 marking the upper left corner of any match. For example:
```
(,.1 4) E. i.2 3
0 1 0
0 0 0
locates 1 within 0 1 2
4 3 4 5
```
In a sense the "hard work" is done, yet going from there to updating squares of the same size as our search target is surprisingly cumbersome.
The trick is to rotate "across" the search target dimension, and then "sum the planes", similar to how we find neighbor counts in the famous APL game of life.
Finally, we multiply the original matrix by the inverse of that result, putting zeros where the ones are and keeping everything else.
The rest is just implementation mechanics.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 121 bytes
```
a=>b=>a.map((r,y)=>r.map((c,x)=>c*!b.some((R,Y)=>R.some((C,X)=>!b.some((S,Z)=>S.some((D,W)=>(a[y-Y+Z]||0)[x-X+W]!=D))))))
```
[Try it online!](https://tio.run/##dZJda8IwFIbv@yuOF8NEj/WTCZPUi7mbwTbQCz/SgLGLrkOtNGVU5n57l35YBbdS6HneN7znJOmn/JLaC/1D1NgH7ypZs0QyZ8Ucae/kgZAQj5Q5YQ4exga8WmVl62CnCBnj3Ajjgh5xZqg0J7gwOClohFNDRPJjY15fiNOpRXncmNWnosJGNHuSSOnIk1ppYLC0OPA2QkegBcC7CD0BIhPTL3PSsnXjp2rP1Aj3CP3cM9DJpF7OfYRuxp0i8WKdxTK@dR2Uc/peB2VctG5fQs8T5VFn4/9d3YiXGS7dbyPMztrlweTKX@fTKpYtzU1G3gdputzVNZfbtaEr0ko0N5pm1xwDc@B58vZqH2SoFYkptddbGb2kv0CM4CNImq7x4Q66MAQu4AG4tPXW9xQxtg916FJBLau8UXsdhE/SNCZcIqwQlMgyvs1wAF6w18FW2dtgQ9ZEUrKiJqJaBcZAIRQSHVg/dJD8Ag "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~55~~ 50 bytes
```
FLθFL§θιF⁼ηE✂θι⁺ιLη¹✂λκ⁺κL§η⁰FLηFL§η⁰§≔§θ⁺ιμ⁺κν⁰Iθ
```
[Try it online!](https://tio.run/##dY8/D4IwEMV3PsWNbXImikQGJmIcTDQhcSQMDSJtqEUoGL99LX@qONi0ubzX3/Vec87avGbSmFvdAjkVquw4aSiFpY67o7oWL9IgCOruDk3PpCYc4cwe5CJFXowAQiJ7TWyduzmlCBt7JkYiVDNTfRg3wb62ptP6ScD/JJp5iLUWpXLuIq/Lch9CuKGKDm2Rl7RCdWTPdDd8OTIm9VJIAwS7dwhhhh6M2h@tYNIhwnbUfgbWmTu@rHW9zKye8g0 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
FLθFL§θι
```
Loop over the cells of `a`. (The ones that are too low or to the right won't slice properly below so the resulting submatrix will never equal `b`.)
```
F⁼ηE✂θι⁺ιLη¹✂λκ⁺κL§η⁰
```
If this submatrix of `a` equals `b`...
```
FLηFL§η⁰§≔§θ⁺ιμ⁺κν⁰
```
... then set all of its elements to zero.
```
Iθ
```
Output the final matrix.
I tried directly mapping over the matrix and filtering out the values that were part of a submatrix but unfortunately this is a) longer at 68 bytes and b) requires 12 loop variables, when Charcoal only has 11 (`iklmnxprvst`).
[Answer]
# [R](https://www.r-project.org/), ~~115~~ 111 bytes
(or **97 bytes** in **[R](https://www.r-project.org/)≥4.1** by replacing the two instances of `function` with `\`)
```
function(a,b,`~`=which){apply(array(,dim(a)-dim(b)+1)|1~T,1,function(c)if(a[d<-t(c+t(b|1~T))-1]==b)a[d]<<-0);a}
```
[Try it online!](https://tio.run/##XY/BCoMwDIbvewqPCbawOtkOs2/hbQimFbEwp5QOp9t89c66McYgJP@ffP8h1k/S19eLdqa7ADHFyrmUQ2N0g3fq@/MIZC2NwCrTAiEPQ2Es8CHmnAn2zWo0NdCpyrgDHTtQAUDkopBS4XIosoxv8UhPT7IlZ80NNKQsWmrPosMqkrWnq929NxgUU6PtBpnjRv1nP0zyw0zhEfQv "R – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 128 bytes
```
->a,b{w=b[0].size;a.size.times{|r|a[r].size.times{|c|a[r,q=b.size].map{|z|z[c,w]}==b&&q.times{|x|w.times{|y|a[r+x][c+y]=0}}}};a}
```
[Try it online!](https://tio.run/##VYu5CsMwEER/JZUbb4RzJxjlR5YtJGGDC4OvIOv6dkVycJFpZuYxM32kiS2Px7cA6TSXWBGbO9vUYjO2dH0zOz95gRP9IZURjFxulFgvBuett6hAU@BcFsW4b1ev92jyrVwJVWmIVyGpFiEOhxYRT3CGCwFe4Qb35A94wotSyOTXiSh@AQ "Ruby – Try It Online")
[Answer]
# Matlab, 153 bytes
```
c=size(a);
d=size(b);
e=c(1);
f=c(2);
g=d(1);
h=d(2);
for i=1:e-g+1
for j=1:f-h+1
if all(a(i:i+g-1,j:j+h-1)==b,'all')
a(i:i+g-1,j:j+h-1)=0;
end
end
end
a
```
I'm a bit frustrated that I wasn't able to find a vectorized solution, which would be more fitting for a Matlab solution.
[Answer]
# JavaScript (ES6), ~~114~~ 110 bytes
Expects `(matrix)(submatrix)`.
```
m=>s=>m.map((r,y)=>r.map((v,x)=>(g=e=>+s.some((R,Y)=>R.some((V,X)=>eval("(m[y+Y]||0)[x+X]"+e))))`^V`?v:g`=0`))
```
[Try it online!](https://tio.run/##hY/disIwEEbv@xSDVxM6W2wtCgup7@CFKCHSorHs0hhppCj47t1s40/BirnKOZlv@PJbNIXd1j/H09fB7FS7563mmeWZjnRxRKzpwnhWe2jo7ABLrngW2sgarRAXtHZycaMlrRyppqhwhFpcwrW8XsdMnMOVHIWKuZNvlvm8@S5zPs4Za7fmYE2losqUuMdAgIgJEkkBgJgQpBIk8/r/xoLgNZC6MYIpwczHHCSdSj3PCCYdJ49lz8e7Htwc9zP3Nu8nB0q/6A9pVzzufdm7Ltf@AQ "JavaScript (Node.js) – Try It Online")
### How?
Let \$M\$ be the parent matrix and \$S\$ be the submatrix.
Given an expression \$e\$ and a reference position \$(x,y)\$ in \$M\$, the helper function \$g\$ walks through all cells \$(X,Y)\$ of \$S\$ and applies \$e\$ to the cell \$(x+X,y+Y)\$ in \$M\$. It eventually returns \$1\$ if any result is \$\neq 0\$, or \$0\$ otherwise.
```
g = e =>
+s.some((R, Y) =>
R.some((V, X) =>
eval("(m[y+Y]||0)[x+X]" + e)
)
)
```
We first invoke \$g\$ with the expression `"^V"` to test whether the submatrix at \$(x,y)\$ in \$M\$ is equal to \$S\$. If it is, we invoke \$g\$ a second time with the expression `"=0"` to clear the submatrix.
[Answer]
# [Core Maude](http://maude.cs.illinois.edu/w/index.php/The_Maude_System), 310 bytes
```
in linear
mod R is pr INT-MATRIX *(sort IntMatrix to M). op r : M M -> M . op t : Int
Int M M -> Int . var A B C D E : Int . var W X Y Z : M . ceq r((A,B)|-> E ;
X ; Y,Z)= r(Y,Z)if(C,D)|-> E ; W := Z /\ t(A - C,B - D,X,W)=/= 0 . eq r(X,Y)=
X[owise]. ceq t(A,B,X,(C,D)|-> E ; Y)= 0 if X[A + C,B + D]=/= E . endm
```
The result is obtained by reducing the `r` function with the input and pattern matrices, given as `IntMatrix`es, and the output is an `IntMatrix`.
This solution requires that all of the input matrices' entries be non-zero, due to a quirk of `IntMatrix`es: zero entries are omitted in the representation (since zero is the default). This is also true for the output.
### Example Session
```
Maude> red r(
> (0, 0) |-> 1 ; (0, 1) |-> 2 ; (0, 2) |-> 3 ;
> (1, 0) |-> 4 ; (1, 1) |-> 3 ; (1, 2) |-> 2 ;
> (2, 0) |-> 3 ; (2, 1) |-> 5 ; (2, 2) |-> 4,
> (0, 0) |-> 3 ;
> (1, 0) |-> 2
> ) .
result M: 0,0 |-> 1 ; 0,1 |-> 2 ; 1,0 |-> 4 ; 1,1 |-> 3 ; 2,0 |-> 3 ; 2,1 |-> 5
; 2,2 |-> 4
Maude> red r(
> (0, 0) |-> 1 ; (0, 1) |-> 2 ;
> (1, 0) |-> 3 ; (1, 1) |-> 4,
> (0, 0) |-> 1
> ) .
result M: 0,1 |-> 2 ; 1,0 |-> 3 ; 1,1 |-> 4
Maude> red r(
> (0, 0) |-> 4 ; (0, 1) |-> 4 ; (0, 2) |-> 6 ; (0, 3) |-> 7 ;
> (1, 0) |-> 4 ; (1, 1) |-> 2 ; (1, 2) |-> 4 ; (1, 3) |-> 4 ;
> (2, 0) |-> 7 ; (2, 1) |-> 3 ; (2, 2) |-> 4 ; (2, 3) |-> 2 ,
> (0, 0) |-> 4 ; (0, 1) |-> 4 ;
> (1, 0) |-> 4 ; (1, 1) |-> 2
> ) .
result M: 0,2 |-> 6 ; 0,3 |-> 7 ; 2,0 |-> 7 ; 2,1 |-> 3
Maude> red r(
> (0, 0) |-> 1 ; (0, 1) |-> 2,
> (0, 0) |-> 3 ; (0, 1) |-> 4
> ) .
result M: 0,0 |-> 1 ; 0,1 |-> 2
Maude> red r(
> (0, 0) |-> 1 ; (0, 1) |-> 2 ;
> (1, 0) |-> 3 ; (1, 1) |-> 4,
> (0, 0) |-> 1 ; (0, 1) |-> 2 ;
> (1, 0) |-> 3 ; (1, 1) |-> 4
> ) .
result M: zeroMatrix
Maude> red r(
> (0, 0) |-> 1 ; (0, 1) |-> 2 ;
> (1, 0) |-> 2 ; (1, 1) |-> 1,
> (0, 0) |-> 1 ;
> (1, 0) |-> 2
> ) .
result M: 0,1 |-> 2 ; 1,1 |-> 1
```
### Ungolfed
```
in linear
mod R is
pr INT-MATRIX * (sort IntMatrix to M) .
op r : M M -> M .
op t : Int Int M M -> Int .
var A B C D E : Int .
var W X Y Z : M .
ceq r((A, B) |-> E ; X ; Y, Z) = r(Y, Z)
if (C, D) |-> E ; W := Z
/\ t(A - C, B - D, X, W) =/= 0 .
eq r(X, Y) = X [owise] .
ceq t(A, B, X, (C, D) |-> E ; Y) = 0
if X[A + C, B + D] =/= E .
endm
```
We find an overlap by guess-and-check. We guess a submatrix and pick one entry from the submatrix and one from the pattern with the same value. We compute their offset and then try to find a counter-example to the match (via `t`). If none exists, we remove the submatrix (equivalent to setting it to zero).
] |
[Question]
[
According to [Wikipedia](https://en.wikipedia.org/wiki/Blum_integer),
>
> In mathematics, a natural number \$n\$ is a Blum integer if \$n = p \times q\$ is a semiprime for which \$p\$ and \$q\$ are distinct prime numbers congruent to \$3 \bmod 4\$. That is, \$p\$ and \$q\$ must be of the form \$4t + 3\$, for some integer \$t\$. Integers of this form are referred to as Blum primes. This means that the factors of a Blum integer are Gaussian primes with no imaginary part.
>
>
>
The first few Blum integers are:
```
21, 33, 57, 69, 77, 93, 129, 133, 141, 161, 177, 201, 209, 213, 217, 237, 249, 253, 301, 309, 321, 329, 341, 381, 393, 413, 417, 437, 453, 469, 473, 489, 497, 501, 517, 537, 553, 573, 581, 589, 597, 633, 649, 669, 681, 713, 717, 721, 737, 749, 753, 781, 789
```
This is [OEIS A016105](https://oeis.org/A016105)
Your task is to make a program that does one of the following:
* Take an index \$n\$ and output the \$n^{th}\$ Blum integer, either 0 or 1 indexing.
* Take a positive integer \$n\$ and output the first \$n\$ Blum integers.
* Output all Blum integers infinitely.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest answer wins.
[Answer]
# [Python 3](https://docs.python.org/3/), 65 bytes
```
n=1
while[[d%4for d in range(2,n)if n%d<1]==[3,3]!=print(n)]:n+=4
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P8/WkKs8IzMnNTo6RdUkLb9IIUUhM0@hKDEvPVXDSCdPMzNNIU81xcYw1tY22ljHOFbRtqAoM69EI08z1ipP29bk/38A "Python 3 – Try It Online")
Prints indefinitely. Identifies Blum integers as those with exactly two proper factors, both of which are 3 mod 4.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ÆḌ%4Ḅ⁼13µ#
```
A full program accepting an integer, \$n\$, from STDIN, that prints a list of the first \$n\$ Blum integers.
**[Try it online!](https://tio.run/##y0rNyan8//9w28MdPaomD3e0PGrcY2h8aKvy//9GpgYA "Jelly – Try It Online")**
### How?
First, note that a semi-prime has exactly three proper divisors: \$(1, p, q)\$, thus Blum integers may be identified by having \$X=(1\mod 4, p\mod 4, q\mod 4)\$ equal to \$(1,3,3)\$.
Next, note that if we treat \$X\$ as a binary number then Blum integers all evaluate to:
\$2^2\cdot 1 + 2^1\cdot 3 + 2^0\cdot 3=13\$
Next, note that the only way to have a string of \$[0..3]\$ evaluate as \$13\$ this way is to have either three or four proper divisors. Two is too few since \$2^1\cdot 3+2^0\cdot 3<13\$ and five is too many since \$2^4\cdot 1>13\$ and the smallest proper divisor is always \$1\$.
Lastly, note that the only numbers with exactly four proper divisors are fourth powers of primes, with proper divisors of \$(1, p, p^2, p^3)\$. Since \$p\mod 4\$ is never zero \$(1, 0, 1, 3)\$ and \$(1, 0, 2, 1)\$ cannot happen, so the only possible false positive that could exist after taking modulo four would be \$(1, 1, 0, 1)\$, but if \$p\equiv 1\pmod 4\$ then \$p^2\equiv 1\pmod 4\$, so that cannot happen either.
```
ÆḌ%4Ḅ⁼13µ# - Main Link: no arguments
µ# - read n from STDIN, count up from k=0
finding the first n k for which this f(k) is truthy:
ÆḌ - proper divisors
%4 - mod four
Ḅ - convert from binary
⁼13 - equals 13?
```
[Answer]
# [J](http://jsoftware.com/), 32 bytes
```
(>:[]echo~~:/@q:*3 3-:4|q:)^:_@3
```
[Try it online!](https://tio.run/##FYqxCsJAEET7fMVgc0YuZ/Y25shCQlCwEgtbUQsxiI2kl/z6uVvsG2befvIquAm9wMGjhuhVAYfL6ZjXg1xvr@f7uyyyHWfZMLiS5jdLeZfHyLkszGKCc8V5HxDJg9ljlzzaziNpdtopaiEz1OgLtQaTsSaD2khssI1T/gM "J – Try It Online")
Outputs all Blum primes.
* `^:_@3` Starting with 3, and continuing to a fixed point (which will never be reached)...
* `]echo~~:/@q:*3 3-:4|q:` If the the current number `n`'s prime factors mod 4 exactly matches `3 3`, and the numbers are not equal `~:/@q:*`, then `echo n` as a side effect...
* `>:[` Return `n+1` for the next iteration.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 13 bytes
```
∞››'Ǐ'›4Ḋ;÷*=
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%88%9E%E2%80%BA%E2%80%BA%27%C7%8F%27%E2%80%BA4%E1%B8%8A%3B%C3%B7*%3D&inputs=&header=&footer=)
Prints infinitely.
```
∞›› # Positive integers (except 1)
' # Filtered by
Ǐ # Prime factors
' ; # Filtered by
› # Incremented
4Ḋ # Is divisible by 4?
÷ # Push all to the stack separately
* # Product of the top two
= # Is equal to (implicit input / another factor)
```
Let's go through the outcomes after ÷.
Case 1: 1 factor left. This gets multiplied by the original number, and since it's not 1, it can never equal the original number.
Case 2: 2 factors left. These two get multiplied together, and if it's the same as the original, it will be outputted.
Case 3: 3+ factors left. The top two will be multiplied, but can't equal the third because it's a prime.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~14~~ 13 bytes
-1 byte thanks to [Adnan](https://codegolf.stackexchange.com/users/34388/adnan)!
Prints the infinite list of Blum numbers.
```
∞ʒfʒ4%Í}ü*θyQ
```
[Try it online!](https://tio.run/##AR4A4f9vc2FiaWX//@KInsqSZsqSNCXDjX3DvCrOuHlR//8 "05AB1E – Try It Online")
```
∞ # infinite list of positive integers [1,2,...
ʒ # filter, keep y if
f # push list of unique prime factors
ʒ4%Í} # keep those where k%4-2==1
ü* # get the products of all adjacent factors
θ # take the last one (or the empty list if there are none)
yQ # is this equal to y?
```
[Answer]
# [R](https://www.r-project.org/), ~~61~~ 56 bytes
*-5 bytes thanks to [@Dominic](https://codegolf.stackexchange.com/users/95126/dominic-van-essen)*
```
while(T<-T+1)if(all(which(!T%%2:T)%%4==c(2,2,0)))show(T)
```
[Try it online!](https://tio.run/##K/r/vzwjMydVI8RGN0TbUDMzTSMxJ0cDKJacoaEYoqpqZBWiqapqYmubrGGkY6RjoKmpWZyRX64Rovn/PwA "R – Try It Online")
Outputs all Blum integers infinitely.
### Explanation
As R doesn't have build-ins for prime factorisation we have to circumvent this.
Let's notice that:
* Blum integer needs to have exactly three non-trivial factors (prime or not) - including the number itself;
* The remainders \$ mod\ 4 \$ need to be \$3,3,1\$ respecitvely.
Therefore it suffices to check if the divisors of the number (`which(!T%%2:T)` is off-by-one) are `all` equal \$ mod\ 4 \$ to vector `[3 3 1]` (`c(2,2,0)` correcting the off-by-one).
Actually we could skip testing the number itself for mod4, but, you know, bytes...
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 78 bytes
```
\d*$
_
"$&"}/(^_|\1__)+$|^(__(___?)?(____)*)\2+$|^(?!(___(____)*)\5+$)/+`$
_
_
```
[Try it online!](https://tio.run/##K0otycxLNPyvqqHhnvA/JkVLhSueS0lFTalWXyMuvibGMD5eU1ulJk4jPh6I4u017UFUvKaWZowRWNxeESQAFzTVVtHU104AmRL//78Jl6EJl5EJl7EJl4kJAA "Retina – Try It Online") Link includes test cases. Outputs the `n`th term. Explanation:
```
"$&"}`
```
Repeat `n` times.
```
\d*$
_
```
Delete the numeric input, and increment the result.
```
/(^_|\1__)+$|^(__(___?)?(____)*)\2+$|^(?!(___(____)*)\5+$)/+`
```
While the result: `(^_|\1__)+$` is square, or `^(__(___?)?(____)*)\2+$` contains a nontrivial proper factor that is not of the form `4t+3`, or `(?!(___(____)*)\5+$)` does not contain a nontrivial proper factor that is of the form `4t+3`, then...
```
$
_
```
... increment the result.
```
_
```
Convert to decimal.
All numbers contain a trivial factor not of the form `4t+3`, i.e. 1. Since the product of two factors `4t+3` would be of the form `4t+1`, the only way a number to only contain nontrivial factors of the form `4t+3` is for the number to be a prime of the form `4t+3`. The next step is to consider numbers with nontrivial proper factors which are all of the form `4t+3`. This set contains only products of two primes of the form `4t+3` (since 3 primes would generate nontrivial proper factors of the form `4t+1` as the product of two of the primes), so it remains to exclude perfect squares which then leaves Blum integers.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~10~~ 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
-1 thanks to [Adnan](https://codegolf.stackexchange.com/users/34388/adnan) (`26` is a built-in, `₂`, and `1` is the only truthy integer in 05AB1E)
A port of [my Jelly answer](https://codegolf.stackexchange.com/a/230083/53748), just using divisors rather than proper divisors.
```
∞ʒÑ4%JC27Q
```
A full program printing an infinite list of the Blum integers.
**[Try it online!](https://tio.run/##yy9OTMpM/f//Uce8U5MOTzRR9XJ@1NSk@/8/AA "05AB1E – Try It Online")**
### How?
For an explanation of why this works see [my Jelly answer](https://codegolf.stackexchange.com/a/230083/53748) (and add \$(p\cdot q)\mod 4\$ to the list to be converted from binary, noting that this will be \$1\$ for a Blum integer, while \$13\cdot2+1=27\$ and the existence of two final potential false-positives, \$(1,1,0,0,3)\$ and \$(1,1,0,1,1)\$ neither of which can happen since \$p\equiv 1\pmod 4 \implies p^2\equiv 1\pmod 4\$.)
```
∞ʒÑ4%JC₂-
∞ - the positive integers
ʒ - filter keep if truthy under:
Ñ - divisors
4 - push four
% - modulo
J - join
C - from binary -> x
₂ - push 26
- - subtract -> x-26 (truthy when x=27 as only 1 is truthy in 05AB1E)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
ÆfQƑa%ɗ4⁼3,3µ#
```
[Try it online!](https://tio.run/##y0rNyan8//9wW1rgsYmJqienmzxq3GOsY3xoq/L//6YA "Jelly – Try It Online")
Outputs the first \$n\$ Blum integers. Takes \$n\$ on STDIN
-1 byte thanks to [Nick Kennedy](https://codegolf.stackexchange.com/users/42248/nick-kennedy)
## How it works
```
ÆfQƑa%ɗ4⁼3,3µ# - Main link. Takes no arguments
µ - Group the previous links into a monad f(k):
Æf - Prime factors of k; F
ɗ4 - Previous 3 links as a dyad g(F, 4):
QƑ - Are the prime factors unique?
% - Mod each factor by 4
a - And; If the prime factors are unique, yield the
factors mod 4, otherwise, yield 0
⁼3,3 - Does that equal [3, 3]?
# - Read n. Count up k = 0, 1, ... until n such k return true under f(k)
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), ~~59~~ 57 bytes
This version is inspired by [xnor's answer](https://codegolf.stackexchange.com/a/230055/58563) in Python. We print `n` if the concatenation of its proper divisors modulo 4 (in ascending order and without repetition) is `"133"`.
```
for(n=0;g=d=>--d&&g(d)+[[d%4][n%d]];)g(++n)^133||print(n)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/Py2/SCPP1sA63TbF1k5XN0VNLV0jRVM7OjpF1SQ2Ok81JTbWWjNdQ1s7TzPO0Ni4pqagKDOvRCNP8/9/AA "JavaScript (V8) – Try It Online")
---
# [JavaScript (V8)](https://v8.dev/), ~~76~~ 75 bytes
Prints the sequence 'forever' (i.e. until a recursion error occurs).
```
for(n=0;g=d=>k%--d?g(d):d;)g(k=p=g(k=++n))*g(k=n/p)^p!=k|~(p&k)&3||print(n)
```
[Try it online!](https://tio.run/##FcZBCoAgEADAt3RIdgsp6BLJ1k8CSRITtsWik/R1o8swh33staUgt37GUvYzAVNvPDmaY621Wzw4nJxBD5GEftuWEZt/3AmuUlHML4iKqIacJQW@gbGUDw "JavaScript (V8) – Try It Online")
### Commented
```
for( // loop:
n = 0; // start with n = 0
g = d => // define the helper function g
k % --d ? g(d) // which returns the highest proper divisor of k
: d; //
) //
g( // get the highest proper divisor of ...
k = p = // ... the highest proper divisor p of ...
g(k = ++n) // ... n, after it's been incremented
) * // and multiply it by
g( // the highest proper divisor of
k = n / p // k = n / p
) // this product is either 1 (success) or greater than 1
^ p != k // make sure that p is not equal to k
// (so the product XOR'ed with p != k must give 0)
| ~(p & k) & 3 // make sure that both p and k are congruent to 3 mod 4
|| print(n) // print n if all tests pass
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 134 bytes
```
f=lambda n,p=[],s=2:sorted(i*j for j in p for i in p if i<j)[:n]if n<len(p)else f(n,p+[s]*(all(s%i for i in range(2,s))and s%4>2),s+1)
```
[Try it online!](https://tio.run/##RcyxDoIwEIDhV7mF5A66WDQxBHwR0qGGVo/Uo@mx@PSV6OD2Lf@f3/tzk/6aS61xSv51XzyIydPsjE520K3sYUFuV4hbgRVYIH/JP3IEHleaB3EHZUxBMFNIGiDiMepmdS36lFAb/ofFyyOgNUrkZQFtzjdLRrsT1VxYdox46YnqBw "Python 3.8 (pre-release) – Try It Online")
Output the first n numbers of the sequence.
## Explanation
Creates a list of primes `p` starting with the empty list. First, check if `p` has more than `n` elements (this is frankly quite arbitrary, we clearly need less primes than that.)
If there are, then we output the first `n` elements of the sorted list of products `i*j` for each possible duo of `i` and `j` in `p` if i<j to prevent duplicates.
Otherwise check if the counter is `s` is prime. Recall `f` with `n` and either p unchanged if s is composite or `p+[s]` if s is prime. Also increment `s`.
Remove the colon before n to get a program which outputs the nth Blum integer, 0-indexed.
Log: 151->150->142->139->138->137->134
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes
```
ḋĊ≠%₄ᵛ3&
```
[Try it online!](https://tio.run/##ASsA1P9icmFjaHlsb2cy/@KGsOKCgeG6ieKKpf/huIvEiuKJoCXigoThtZszJv// "Brachylog – Try It Online")
Acts as an infinite generator.
## Explanation
```
ḋĊ≠%₄ᵛ3&
ḋ The input's prime decomposition
Ċ is a pair
≠ of distinct values
ᵛ which all
%₄ modulo 4
3 equal 3.
& The input and the output are the same.
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 28 bytes
```
FN«≦⊕χW⁻³¹↨⁴﹪Φχ∧μ¬﹪χλ⁴≦⊕χ»Iχ
```
[Try it online!](https://tio.run/##fY27CgIxFETrzVfc8gZiIabbahWELbL4CzGJbiCPJQ8txG@PEayd5sAcmFGrTCpK19otJsA5bLUs1V9NQkrhRQYhtylnew/dqWS8CcVoBoqOZHiu1hlAYUPNeNgzOMpskDMQUVcX8Wxd6UOKwRQ0egZLLPhzvXS0hwH/Av78vMkl2VDwJHNBRenYGm@7h/sA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
FN«
```
Loop the given number of times.
```
≦⊕χ
```
Increment the result variable (predefined to `10`, which is fortunately less than the first Blum integer).
```
W⁻³¹↨⁴﹪Φχ∧μ¬﹪χλ⁴
```
Take the proper factors of the variable, reduce them modulo `4`, interpret the list as a base `4` integer, and repeat while the result is not `31` (`133` in base 4)...
```
≦⊕χ
```
... increment the result variable.
```
»Iχ
```
Output the result.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~118~~ 112 bytes
Prints the first `n` Blum integers.
```
n=input()
P=4
k=3
r=p=[]
while p[n:]<=p:
if P%k&k/2:r=r+[x*k for x in p];p+=k,
P*=k*k;k+=1
print sorted(r)[:n]
```
[Try it online!](https://tio.run/##BcHBDoIwDADQe7@iFw0wEwE9DfsPuy@7CWGp6Zo6I379fE9/dS8ytyaURT@16yHQHZhuYKQUE3z3/FpRo/j0IPWAecNw4jNfZ29kLh4D41YMD8yCmhZ1xBfAMBAPvLCjCdSyVHwXq@uzsz56Sa1N4/gH "Python 2 – Try It Online")
Uses [Wilson's theorem](https://en.wikipedia.org/wiki/Wilson%27s_theorem). `p` keeps track of all primes of the form \$4t+3\$, `r` is a unique list of all Blum integers that can be created with the primes in `p`.
[Answer]
# [jq](https://stedolan.github.io/jq/), 61 bytes
Prints all Blum integers.
```
0|while(1;.+1)|select([[.%range(2;.)]|indices(0)[]%4]==[1,1])
```
[Try it online!](https://tio.run/##BcFBCoAgEADA1wgrlbjRTXyJeAhbyhAtDbr49raZ82bW/T1iIkCjBpS9UaLwgHNK1DXvBLNR0veYtxiogZbOi8Vb63BEL5m/cj2x5MZTrj8 "jq – Try It Online")
For all practical reasons `0|while(1;.+1)` could be replaced with `range(0|-y0)`, but it feels more like an infinite sequence this way, even if both are limited by the range of representable numbers.
] |
[Question]
[
Wow, time really flies! It's already been one year since the [debut of the Code Golf Stack Exchange site design](https://codegolf.meta.stackexchange.com/questions/17760/congratulations-your-site-design-is-now-live). Let's celebrate this milestone with a code golf challenge... to imitate the site logo!
Golf a program that outputs a graphic of a medal enclosed in curly braces `{üèÖ}`, along with two lines of text containing `CODE GOLF` and `& coding challenges`.
The medal graphic `{üèÖ}` should consist of the following:
* **The medallion:** A solid-filled circle with radius `r`, surrounded by a concentric ring of the same color with an outer radius between `1.5r` and `1.6r` and a thickness between `0.2r` and `0.3r`.
* **The ribbon:** A solid-filled, horizontally symmetrical hexagon with height between `3r` and `4r` and side lengths ranging from `1.8r` to `2.4r`, placed directly above the medallion and sharing its vertical axis of symmetry.
+ A "y"-shaped cutout within the hexagon (masked out or solid-filled with the background color). This is defined by a horizontally centered, solid, downward-pointing acute isosceles triangle, with the right side extended by a line segment of thickness up to `0.3r` that intersects with the bottom left vertex of the hexagon. (The left and right sides should be co-linear with the top left and top right vertices of the hexagon, respectively.)
* **A pair of curly braces** `{` and `}` with a height between `6r` and `7r`, such that the imaginary horizontal axis that joins the "spikes" `{——}` falls below the apex of the cut-out isosceles triangle and above the medallion's outer ring.
The text output should consist of the string `CODE GOLF` above the string `& coding challenges`, with the horizontal spans of `&` and `s` falling within those of `C` and `F` respectively. You can achieve this any way you like, including, but not limited to:
* Rendering text within the image, to the right of the `{üèÖ}`.
* Rendering text in a separate image, window, or GUI element.
* Printing to standard output/standard error.
To justify the text, you may add spaces uniformly between the letters and words such that the letter spacing to word spacing ratio is no more than 2/3, e.g:
```
C O D E G O L F
& coding challenges
```
Ensure all shapes and glyphs in your output are solid-filled and non-overlapping. Optionally, color your medal `#F7CC46` gold and `#0061BA` blue (and `#004E96` blue?) for some bonus internet points!
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); the less bytes, the better. Be sure to include a screenshot in your answer!
---
For reference, the [official SVG logo](https://cdn.sstatic.net/Sites/codegolf/Img/logo.svg) is as follows:
```
html { background: #2b2520 }
```
```
<svg xmlns="http://www.w3.org/2000/svg" height="126" viewBox="0 0 200 42" fill="none">
<path d="M74.053 22.38c-1.561 0-2.976-.332-4.245-.994a7.756 7.756 0 0 1-2.977-2.785c-.714-1.195-1.072-2.54-1.072-4.037 0-1.497.358-2.836 1.072-4.016a7.546 7.546 0 0 1 2.977-2.785c1.269-.676 2.691-1.015 4.267-1.015 1.327 0 2.523.23 3.588.691a7.184 7.184 0 0 1 2.714 1.987L78.1 11.498c-1.036-1.18-2.32-1.77-3.851-1.77-.949 0-1.795.208-2.539.626a4.405 4.405 0 0 0-1.75 1.705c-.409.735-.613 1.57-.613 2.505 0 .935.204 1.77.613 2.504a4.556 4.556 0 0 0 1.75 1.727c.744.403 1.59.605 2.539.605 1.531 0 2.815-.598 3.851-1.792l2.276 2.072a7.085 7.085 0 0 1-2.714 2.008c-1.08.46-2.283.691-3.61.691zM89.869 22.38c-1.59 0-3.028-.339-4.311-1.015-1.27-.677-2.269-1.605-2.998-2.786-.715-1.194-1.073-2.533-1.073-4.015 0-1.483.358-2.814 1.073-3.994a7.663 7.663 0 0 1 2.998-2.807c1.283-.676 2.72-1.015 4.31-1.015 1.59 0 3.02.339 4.29 1.015a7.664 7.664 0 0 1 2.998 2.807c.729 1.18 1.094 2.511 1.094 3.994 0 1.482-.365 2.82-1.094 4.015-.73 1.18-1.73 2.109-2.998 2.785-1.27.677-2.7 1.015-4.29 1.015zm0-2.98c.904 0 1.721-.202 2.45-.605a4.444 4.444 0 0 0 1.707-1.727c.423-.734.635-1.569.635-2.504 0-.936-.212-1.77-.635-2.505a4.296 4.296 0 0 0-1.706-1.705c-.73-.418-1.547-.626-2.451-.626-.905 0-1.722.208-2.451.626a4.445 4.445 0 0 0-1.729 1.705c-.408.735-.613 1.57-.613 2.505 0 .935.205 1.77.613 2.504a4.6 4.6 0 0 0 1.729 1.727c.73.403 1.546.605 2.45.605zM100.914 7.007h6.959c1.663 0 3.129.317 4.398.95 1.284.62 2.276 1.497 2.976 2.634.715 1.137 1.072 2.462 1.072 3.973 0 1.511-.357 2.835-1.072 3.972-.7 1.137-1.692 2.022-2.976 2.656-1.269.619-2.735.928-4.398.928h-6.959V7.007zm6.784 12.242c1.531 0 2.75-.418 3.654-1.252.919-.85 1.379-1.994 1.379-3.433 0-1.44-.46-2.576-1.379-3.411-.904-.85-2.123-1.274-3.654-1.274h-3.239v9.37h3.239zM130.853 19.314v2.806h-11.86V7.007h11.576v2.807h-8.053v3.282h7.112v2.72h-7.112v3.498h8.337zM150.222 14.326h3.239v6.132c-.832.619-1.795 1.094-2.889 1.425a11.349 11.349 0 0 1-3.304.496c-1.59 0-3.02-.33-4.289-.993-1.269-.676-2.269-1.605-2.998-2.785-.715-1.195-1.072-2.54-1.072-4.037 0-1.497.357-2.836 1.072-4.016.729-1.194 1.736-2.123 3.02-2.785 1.283-.676 2.728-1.015 4.332-1.015 1.343 0 2.561.223 3.655.67a7.24 7.24 0 0 1 2.757 1.943l-2.276 2.072c-1.094-1.137-2.414-1.705-3.961-1.705-.977 0-1.845.201-2.604.604a4.37 4.37 0 0 0-1.772 1.706c-.423.734-.635 1.576-.635 2.526 0 .935.212 1.77.635 2.504a4.557 4.557 0 0 0 1.751 1.727c.758.403 1.619.605 2.582.605 1.021 0 1.94-.216 2.757-.648v-4.426zM164.172 22.38c-1.59 0-3.027-.339-4.311-1.015-1.269-.677-2.269-1.605-2.998-2.786-.715-1.194-1.072-2.533-1.072-4.015 0-1.483.357-2.814 1.072-3.994.729-1.195 1.729-2.13 2.998-2.807 1.284-.676 2.721-1.015 4.311-1.015 1.59 0 3.02.339 4.289 1.015a7.669 7.669 0 0 1 2.998 2.807c.729 1.18 1.094 2.511 1.094 3.994 0 1.482-.365 2.82-1.094 4.015-.73 1.18-1.729 2.109-2.998 2.785-1.269.677-2.699 1.015-4.289 1.015zm0-2.98c.904 0 1.721-.202 2.451-.605a4.45 4.45 0 0 0 1.707-1.727c.423-.734.634-1.569.634-2.504 0-.936-.211-1.77-.634-2.505a4.303 4.303 0 0 0-1.707-1.705c-.73-.418-1.547-.626-2.451-.626-.905 0-1.722.208-2.451.626a4.448 4.448 0 0 0-1.729 1.705c-.408.735-.612 1.57-.612 2.505 0 .935.204 1.77.612 2.504.423.734 1 1.31 1.729 1.727.729.403 1.546.605 2.451.605zM175.217 7.007h3.545V19.27h7.681v2.85h-11.226V7.007zM191.969 9.814v3.994h7.09v2.807h-7.09v5.505h-3.545V7.007H200v2.807h-8.031zM68.163 33.798c.865 0 1.564-.313 2.132-.788.557.382 1.102.649 1.635.788l.343-1.089c-.367-.104-.77-.312-1.208-.602.521-.787.9-1.678 1.161-2.628h-1.255c-.178.764-.45 1.424-.806 1.968a9.46 9.46 0 0 1-1.646-1.713c.781-.59 1.575-1.204 1.575-2.177 0-.96-.628-1.609-1.682-1.609-1.101 0-1.812.845-1.812 1.887 0 .51.19 1.1.51 1.714-.711.498-1.35 1.111-1.35 2.118 0 1.193.911 2.13 2.403 2.13zm-.426-5.974c0-.58.273-.973.687-.973.45 0 .604.313.604.718 0 .567-.438.972-.995 1.355-.19-.383-.296-.753-.296-1.1zm.592 4.943c-.722 0-1.267-.474-1.267-1.18 0-.452.249-.823.592-1.158a10.731 10.731 0 0 0 1.753 1.898c-.331.278-.699.44-1.078.44zM83.658 33.798c.83 0 1.682-.29 2.357-.857l-.569-.857c-.45.336-.994.625-1.658.625-1.148 0-1.93-.752-1.93-1.887 0-1.146.805-1.898 1.966-1.898.521 0 .983.185 1.433.544l.651-.834c-.485-.451-1.22-.799-2.155-.799-1.777 0-3.305 1.088-3.305 2.987 0 1.887 1.386 2.976 3.21 2.976zM90.239 33.798c1.528 0 2.925-1.089 2.925-2.976 0-1.898-1.397-2.987-2.925-2.987-1.528 0-2.926 1.088-2.926 2.987 0 1.887 1.398 2.976 2.926 2.976zm0-1.089c-.948 0-1.516-.752-1.516-1.887 0-1.146.568-1.898 1.516-1.898.947 0 1.516.752 1.516 1.898 0 1.135-.569 1.887-1.516 1.887zM96.902 33.798c.652 0 1.303-.36 1.753-.8h.036l.106.66h1.126v-8.173h-1.374v2.06l.07.962h-.035c-.45-.429-.936-.672-1.599-.672-1.326 0-2.57 1.135-2.57 2.987 0 1.876.995 2.976 2.487 2.976zm.332-1.1c-.888 0-1.41-.66-1.41-1.887 0-1.193.676-1.876 1.481-1.876.426 0 .829.139 1.244.521v2.559c-.403.463-.83.683-1.315.683zM104.407 33.659h1.362v-5.685h-3.885v1.054h2.523v4.63zm.58-6.727c.557 0 .971-.347.971-.891 0-.533-.414-.903-.971-.903-.557 0-.971.37-.971.903 0 .544.414.891.971.891zM108.962 33.659h1.374V29.78c.533-.532.924-.799 1.492-.799.794 0 1.09.417 1.09 1.332v3.346h1.374v-3.52c0-1.47-.616-2.304-1.954-2.304-.889 0-1.552.452-2.097.996h-.047l-.107-.857h-1.125v5.685zM118.48 36.171c2.049 0 3.352-.891 3.352-2.014 0-.996-.782-1.39-2.286-1.39h-1.184c-.723 0-1.102-.162-1.102-.532 0-.232.119-.394.355-.533.308.104.628.162.889.162 1.303 0 2.333-.671 2.333-1.933 0-.37-.178-.718-.379-.938h1.338v-1.019h-2.38a2.792 2.792 0 0 0-.912-.139c-1.279 0-2.393.741-2.393 2.05 0 .67.332 1.18.746 1.47v.046c-.426.278-.698.695-.698 1.065 0 .475.284.764.592.95v.046c-.604.324-.924.74-.924 1.192 0 1.02 1.054 1.517 2.653 1.517zm.024-5.152c-.604 0-1.102-.417-1.102-1.135 0-.694.498-1.123 1.102-1.123.604 0 1.101.429 1.101 1.123 0 .718-.497 1.135-1.101 1.135zm.142 4.272c-1.078 0-1.682-.3-1.682-.81 0-.267.154-.51.569-.741.236.058.509.08.888.08h.924c.781 0 1.172.117 1.172.556 0 .487-.734.915-1.871.915zM133.371 33.798a3.69 3.69 0 0 0 2.357-.857l-.569-.857c-.45.336-.995.625-1.658.625-1.149 0-1.931-.752-1.931-1.887 0-1.146.806-1.898 1.966-1.898.522 0 .983.185 1.434.544l.651-.834c-.486-.451-1.22-.799-2.156-.799-1.776 0-3.304 1.088-3.304 2.987 0 1.887 1.386 2.976 3.21 2.976zM137.369 33.659h1.374V29.78c.533-.532.924-.799 1.492-.799.794 0 1.09.417 1.09 1.332v3.346h1.374v-3.52c0-1.47-.616-2.304-1.954-2.304-.889 0-1.54.452-2.049.973h-.036l.083-1.216v-2.107h-1.374v8.174zM146.283 33.798c.782 0 1.564-.382 2.179-.846h.036l.107.707h1.113v-3.37c0-1.586-.888-2.454-2.499-2.454-.995 0-1.954.382-2.653.787l.497.892c.604-.324 1.256-.602 1.907-.602.948 0 1.338.475 1.386 1.111-2.866.197-4.015.834-4.015 2.107 0 .996.805 1.668 1.942 1.668zm.415-1.042c-.581 0-1.043-.22-1.043-.73 0-.613.616-1.03 2.701-1.17v1.205c-.533.417-1.078.695-1.658.695zM155.351 33.798c.675 0 1.078-.116 1.646-.325l-.319-.984c-.368.15-.687.22-.995.22-.581 0-1.043-.29-1.043-1.053v-6.171h-3.197v1.053h1.835v5.048c0 1.401.723 2.212 2.073 2.212zM162.453 33.798c.675 0 1.078-.116 1.646-.325l-.32-.984c-.367.15-.687.22-.995.22-.58 0-1.042-.29-1.042-1.053v-6.171h-3.198v1.053h1.836v5.048c0 1.401.723 2.212 2.073 2.212zM168.714 33.798c.852 0 1.658-.278 2.274-.672l-.462-.833c-.521.289-1.019.474-1.635.474-1.077 0-1.847-.51-2.001-1.563h4.275c.024-.15.06-.405.06-.671 0-1.575-.96-2.698-2.689-2.698-1.563 0-3.008 1.123-3.008 2.976 0 1.887 1.409 2.987 3.186 2.987zm-.142-4.932c.829 0 1.35.463 1.445 1.389h-3.092c.178-.915.841-1.39 1.647-1.39zM172.878 33.659h1.374V29.78c.533-.532.924-.799 1.492-.799.794 0 1.09.417 1.09 1.332v3.346h1.374v-3.52c0-1.47-.616-2.304-1.954-2.304-.889 0-1.552.452-2.097.996h-.047l-.107-.857h-1.125v5.685zM182.396 36.171c2.049 0 3.352-.891 3.352-2.014 0-.996-.782-1.39-2.286-1.39h-1.184c-.723 0-1.102-.162-1.102-.532 0-.232.119-.394.356-.533.307.104.627.162.888.162 1.303 0 2.333-.671 2.333-1.933 0-.37-.178-.718-.379-.938h1.338v-1.019h-2.38a2.792 2.792 0 0 0-.912-.139c-1.279 0-2.393.741-2.393 2.05 0 .67.332 1.18.746 1.47v.046c-.426.278-.698.695-.698 1.065 0 .475.284.764.592.95v.046c-.604.324-.924.74-.924 1.192 0 1.02 1.054 1.517 2.653 1.517zm.024-5.152c-.604 0-1.102-.417-1.102-1.135 0-.694.498-1.123 1.102-1.123.604 0 1.101.429 1.101 1.123 0 .718-.497 1.135-1.101 1.135zm.142 4.272c-1.078 0-1.682-.3-1.682-.81 0-.267.154-.51.569-.741.236.058.509.08.888.08h.924c.781 0 1.172.117 1.172.556 0 .487-.734.915-1.871.915zM190.019 33.798c.853 0 1.658-.278 2.274-.672l-.462-.833c-.521.289-1.018.474-1.634.474-1.078 0-1.848-.51-2.002-1.563h4.276a4.52 4.52 0 0 0 .059-.671c0-1.575-.959-2.698-2.689-2.698-1.563 0-3.008 1.123-3.008 2.976 0 1.887 1.409 2.987 3.186 2.987zm-.142-4.932c.829 0 1.35.463 1.445 1.389h-3.091c.177-.915.841-1.39 1.646-1.39zM196.801 33.798c1.765 0 2.724-.788 2.724-1.76 0-.903-.485-1.39-2.345-1.795-1.078-.231-1.516-.37-1.516-.775 0-.348.308-.626 1.078-.626.687 0 1.35.209 1.919.568l.627-.822c-.592-.382-1.468-.753-2.428-.753-1.634 0-2.558.706-2.558 1.702 0 .857.699 1.401 2.25 1.714 1.351.277 1.611.486 1.611.856 0 .382-.379.683-1.184.683a4.373 4.373 0 0 1-2.44-.717l-.592.845c.722.474 1.764.88 2.854.88zM45.057 36.394c.872 0 1.575-.043 2.109-.128.562-.084.998-.24 1.307-.466.309-.226.52-.538.632-.934.14-.367.211-.848.211-1.442 0-1.16-.028-2.277-.084-3.352a68.576 68.576 0 0 1-.085-3.564c0-1.612.324-2.771.97-3.479.635-.721 1.69-1.212 3.163-1.47a.101.101 0 0 0 .084-.1.101.101 0 0 0-.084-.099c-1.474-.258-2.528-.734-3.163-1.428-.646-.735-.97-1.909-.97-3.521 0-1.273.029-2.46.085-3.564.056-1.103.084-2.22.084-3.352 0-.594-.07-1.074-.21-1.442a1.69 1.69 0 0 0-.633-.933c-.31-.227-.745-.382-1.307-.467-.534-.085-1.237-.127-2.109-.127h-.074a1.655 1.655 0 0 1 0-3.31h1.592c2.699 0 4.68.439 5.946 1.316 1.265.848 1.897 2.418 1.897 4.709 0 .735-.028 1.414-.084 2.036a17.36 17.36 0 0 1-.169 1.74 310.46 310.46 0 0 0-.169 1.655 36.891 36.891 0 0 0-.042 1.824c0 .367.085.735.253 1.103.169.368.478.707.928 1.018.45.283 1.04.523 1.77.721.316.07.665.13 1.048.175 1.008.121 1.82.932 1.82 1.947 0 1.014-.813 1.822-1.818 1.96-.384.053-.733.121-1.05.203-.73.17-1.32.41-1.77.722-.45.283-.759.608-.928.976a2.627 2.627 0 0 0-.253 1.102c0 .68.014 1.302.042 1.867.057.538.113 1.09.17 1.655.084.537.14 1.103.168 1.697.056.594.084 1.273.084 2.036 0 2.291-.632 3.861-1.897 4.71-1.265.877-3.247 1.315-5.946 1.315h-1.592a1.655 1.655 0 0 1 0-3.31h.074zM14.716 36.394c-.871 0-1.574-.043-2.108-.128-.563-.084-.998-.24-1.308-.466a1.69 1.69 0 0 1-.632-.934c-.14-.367-.21-.848-.21-1.442 0-1.16.027-2.277.084-3.352.056-1.075.084-2.262.084-3.564 0-1.612-.323-2.771-.97-3.479-.635-.721-1.689-1.212-3.163-1.47a.101.101 0 0 1-.084-.1c0-.048.036-.09.084-.099 1.474-.258 2.528-.734 3.163-1.428.647-.735.97-1.909.97-3.521 0-1.273-.028-2.46-.084-3.564a65.75 65.75 0 0 1-.085-3.352c0-.594.07-1.074.211-1.442a1.69 1.69 0 0 1 .633-.933c.309-.227.745-.382 1.307-.467.534-.085 1.236-.127 2.108-.127h.074a1.655 1.655 0 1 0 0-3.31h-1.592c-2.699 0-4.68.439-5.945 1.316C5.988 5.38 5.355 6.95 5.355 9.24c0 .735.028 1.414.084 2.036.029.594.085 1.174.17 1.74.055.537.112 1.089.168 1.655.028.565.042 1.173.042 1.824 0 .367-.084.735-.253 1.103-.169.368-.478.707-.928 1.018-.45.283-1.04.523-1.77.721-.316.07-.665.13-1.048.175C.812 19.634 0 20.445 0 21.46c0 1.014.813 1.822 1.818 1.96.384.053.734.121 1.05.203.73.17 1.32.41 1.77.722.45.283.76.608.928.976.169.367.253.735.253 1.102 0 .68-.014 1.302-.042 1.867-.056.538-.113 1.09-.169 1.655-.084.537-.14 1.103-.169 1.697a21.84 21.84 0 0 0-.084 2.036c0 2.291.633 3.861 1.898 4.71 1.265.877 3.246 1.315 5.945 1.315h1.592a1.655 1.655 0 1 0 0-3.31h-.074z" fill="#fff"/>
<path fill="#004E96" d="M23.74.772h11.663v4.597H23.74z"/>
<path d="M35.423.772l4.991 7.225a3 3 0 0 1 .078 3.293l-6.313 10.123h-6.437L35.422.772z" fill="#0061BA"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M29.581 41.228a9.194 9.194 0 1 0 0-18.39 9.194 9.194 0 1 0 0 18.39zm0-16.866a7.671 7.671 0 1 0 0 15.343 7.671 7.671 0 0 0 0-15.343zm-5.901 7.671a5.902 5.902 0 1 1 11.803 0 5.902 5.902 0 0 1-11.803 0z" fill="#F7CC46"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M18.748 7.997L23.74.772l4.93 13.249-2.767 7.392h-.919L18.671 11.29a3 3 0 0 1 .077-3.293zm8.994 13.416h3.678l-1.834-4.928-1.844 4.928z" fill="#0061BA"/>
</svg>
```
[Answer]
# SVG, 259 bytes
```
<svg viewBox=-30,-29,200,40><text x=-26 font-size=32>{ }</text><text x=25 y=-9>CODE GOLF</text><text x=29 font-size=9>& coding challenges</text><path fill=blue d=M-4.5-24h9l4,8-4,8h-8l6-12h-5l2,4-4,8-4-8 /><g fill=gold><circle r=6.8 /><circle r=5 stroke=#fff>
```
Also including a screenshot, since this is um.. not exactly best practises and will probably not look right in all browsers.
[](https://i.stack.imgur.com/SHrh6.png)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~123~~ 115 bytes
```
„P122žw•·54†u%í[ǤõìEEÖÇćÃKõ&Ê»¦1ćÊ₂à<äć°S£ŸǝzMçqõR^ùµTÄYšαÄâ[¬Å%J#›-J(%í/ûÜN₅≠ÝmÁ∞j!i_´ÿÓÙ7žŠλ•bÀðT×…ƒËÿŠˆu…&Âïªï»
```
[Try it online!](https://tio.run/##Ac8AMP9vc2FiaWX//@KAnlAxMjLFvnfigKLCtzU04oCgdSXDrVvDh8Kkw7XDrEVFw5bDh8SHw4NLw7Umw4rCu8KmMcSHw4rigoLDoDzDpMSHwrBTwqPFuMedek3Dp3HDtVJew7nCtVTDhFnFoc6xw4TDolvCrMOFJUoj4oC6LUooJcOtL8O7w5xO4oKF4omgw51tw4HiiJ5qIWlfwrTDv8OTw5k3xb7FoM674oCiYsOAw7BUw5figKbGksOLw7/FoMuGdeKApibDgsOvwqrDr8K7//8 "05AB1E – Try It Online") Beats all other answers. Technically, there is only [one other valid answer](https://codegolf.stackexchange.com/a/224066/94066). All other answers don't meet the specifications. Outputs as a plain PBM, and outputs the text after it.
# Output (enlarged)

Actual output size is 22x32.
---
```
„P122žw•...•bÀðT×…...u…...» # trimmed program
„P1 # push literal
22 # push literal
žw # push 32
•...• # push 166945169634011025567565467884298025990186958890541902453598900323554121322972765574841330722535555954069208033251875962777321153953373288109249110692417567618626198556352935215968754836351913816090583315808287...
b # in binary...
À # shifted left 1 character
…... # push "codeÿ golf"...
# (implicit) with ÿ replaced by...
T # 10...
√∞ # space...
√ó # s...
u # in uppercase
…... # push "& coding challenges"
» # join stack by newlines
# implicit output
```
`ðT×` can also be `9çº` to slightly increase the distance between `CODE` and `GOLF`: [Try it online!](https://tio.run/##Ac8AMP9vc2FiaWX//@KAnlAxMjLFvnfigKLCtzU04oCgdSXDrVvDh8Kkw7XDrEVFw5bDh8SHw4NLw7Umw4rCu8KmMcSHw4rigoLDoDzDpMSHwrBTwqPFuMedek3Dp3HDtVJew7nCtVTDhFnFoc6xw4TDolvCrMOFJUoj4oC6LUooJcOtL8O7w5xO4oKF4omgw51tw4HiiJ5qIWlfwrTDv8OTw5k3xb7FoM674oCiYsOAOcOnwrrigKbGksOLw7/FoMuGdeKApibDgsOvwqrDr8K7//8 "05AB1E – Try It Online")
[Answer]
# [PostScript](https://en.wikipedia.org/wiki/PostScript), 432 bytes
Code (compressed version):
```
<</L{lineto}/F{closepath fill}/S{setrgbcolor}/t{translate}/N{newpath}/H/Helvetica/M{moveto}/T{M selectfont show}/C{N 0 360 arc F}>> begin 15 15 scale ({ }) H 7.2 0 2 T (CODE GOLF) H 3.6 9 4 T (& coding challenges) H 2.35 9 1 T 4.2 2.4 t .94 .8 .27 S 0 0 1.5 C 1 1 1 S 0 0 1.25 C .94 .8 .27 S 0 0 1 C 0 3 t 0 .31 .59 S N 1.55 0 M 6{60 rotate 1.55 0 L}repeat F 1 1 1 S N -.7 -1.35 M -.05 0 L -.45 .9 L .45 .9 L -.5 -1.35 L F showpage
```
Code (uncompressed version):
```
% some short-named procedures for later use
<<
/L {lineto}
/F {closepath fill}
/S {setrgbcolor}
/t {translate}
/N {newpath}
/H /Helvetica
/M {moveto}
/T { % text fontname fontsize x y --> ---
M selectfont show
}
/C { % x y radius --> ---
N 0 360 arc F
}
>> begin
15 15 scale
% Draw the texts
({ }) H 7.2 0 2 T
(CODE GOLF) H 3.6 9 4 T
(& coding challenges) H 2.35 9 1 T
% Draw the medaillon
4.2 2.4 t
.94 .8 .27 S % gold
0 0 1.5 C
1 1 1 S % white
0 0 1.25 C
.94 .8 .27 S % gold
0 0 1 C
% Draw the ribbon
0 3 t
0 .31 .59 S % blue
N 1.55 0 M
6 {60 rotate 1.55 0 L} repeat
F
1 1 1 S % white
N
-.7 -1.35 M
-.05 0 L
-.45 .9 L
.45 .9 L
-.5 -1.35 L
F
showpage
```
Result:
[](https://i.stack.imgur.com/GOlVB.png)
[Answer]
# [Octave](https://www.gnu.org/software/octave/) / [Matlab](http://www.mathworks.com/products/matlab.html), ~~469~~ ~~477~~ 469 bytes
* +8 To fix the size of "CODE GOLF"
* -8 by talking tiny bit more liberty with the colours and removing `on` after `hold` (given the default state of the `hold` is `off`, calling `hold` by itself just sets it to `on`)
```
y=[1,.8,.3],b=[0,.4,.8],w=[1,1,1],hold
e='Edgecolor',n='none',r=@real,i=@imag,p=@patch,x=@text,f='FontSize'
h=1.8*exp(j*pi/3*(0:5))
p(r(h),i(h),b,e,n)
t=exp(pi*[3,-1,-5]/6j)+j
t=[t,.2*t(3),t(3)'-.3,t(3)']-.6j
p(r(t),i(t),w,e,n)
c=exp(pi*(0:98)/49j)
c=@(a,l)p(r(a*c-3.3j),i(a*c-3.3j),l,e,n)
c(1.5,y),c(1.3,w),c(1,y)
x(-4,-1,'{',f,99),x(2,-1,'}',f,99)
x(5,0,'CODE GOLF',f,49)
x(5,-3,'& coding challenges',f,31)
axis equal off,ylim([-5 2]),xlim([-4 25])
set(gcf,'Color',w)
```
[Try it online!](https://tio.run/##RVHBjpswFLzzFZxqmz6cEMMq2ZUlpHa3l0p76BFx8DoGjBzMgtuQVv121k5SVZaeZ8bz5ll6VjrxS62NnU7CxXNnJ/cU35m0p1FIz6Wxs4qFMQEqMYVLPq0XXmVA90BZDW@82gLNPa3hHHR/auisOUaKo@djq6Q1dkIwcDTYQSGYeDkpYUDzUp9ECyMvR@FkBwsvnVocNBy92MH90L8Vijqe0X2ilhH3yag3LMHbx4KQaMQT7gjoUN5AwUAix4Nt1EnFIM0gLerNQ08@9/6hckB3icOMQCgopewG6pQ@9NcwF8J8Od/C5L8wP@@wJ5v80AexxAIMCX6RyJRR1oe2/9jcu3FGC7gQCIDB@Qo8jxac5uFz6A@CBg4HAgveXYW/d8FbCtgC@vL69Tn@9vr9Jej5XU8ZoE9@P0c9tLHs/GbU0Ko5WFhGIrHoOVbvP4WJbdPAxegTrtIi3tV@zo3k8a6oSTQrh1vZ@DG37ZzJuq4f "Octave – Try It Online"), although you don't get the figure in TIO, so here is screenshot of the one I get.
[](https://i.stack.imgur.com/lx6Qz.png)
Matlab version 9.3.0.948333 (R2017b) Update 9, on macOS Catalina, 10.15.4
## Ungolfed
```
yellow = [246,204,70]/255;
blue = [0,97,186]/255;
white = [1 1 1];
hold on; % Allow multiple plots on the same axis (implicitly creates a figure)
% Make a blue hexagon
hex = exp(1i*2*pi/6*(0:5)); % Points on a hexagon
patch(real(1.8*hex),imag(1.8*hex),blue,'EdgeColor','none');
tri = exp(1i*(2*pi/3*(0:2)-3*pi/6))+1i;
tri = [tri (0.8*tri(1)+0.2*tri(3)) tri(3)'-0.3 tri(3)'];
patch(real(tri-.6i),imag(tri-.6i),white,'EdgeColor','none');
circ = exp(1i*linspace(0,2*pi,1e3)); % 100 points on a unit circle
co = -3.3i; % Offset
c = @(r,l)patch(real(r*circ+co),imag(r*circ+co),l,'EdgeColor','none');
c(1.5,yellow)
c(1.3,white)
c(1.0,yellow)
text(-4,-1,'{','FontSize',99);
text(2,-1,'}','FontSize',99);
text(5,-1.5,{'CODE GOLF','& coding challenges'},'FontSize',33)
axis equal off;
ylim([-5 2]); xlim([-4 25]);
set(gcf,'Color',white);
% grid on; box on;
```
[Answer]
# LaTeX + TikZ, 449 bytes
```
\documentclass[tikz]{standalone}\usetikzlibrary{shapes}\begin{document}\tikz{\path[fill]circle(1.6)(0,3)node[scale=32]{\{~\}}(0,5)node[fill,regular polygon,regular polygon sides=6,inner sep=70]{}(0,5)node[fill=white,rotate=180,regular polygon,regular polygon sides=3,inner sep=20]{};\path[fill=white,rotate=60](0.6,1.5)rectangle(5,1.8)(0,0)circle(1.4);\fill circle(1)(17,3)node[scale=9,align=left]{CODE GOLF\\\tiny\&~coding challenges};}\enddocument
```
Readable version:
```
\documentclass[tikz]{standalone}
\usetikzlibrary{shapes}
\begin{document}
\tikz{
\path[fill]
circle(1.6)
(0,3)node[scale=32]{\{~\}}
(0,5)node[fill,regular polygon,regular polygon sides=6,inner sep=70]{}
(0,5)node[fill=white,rotate=180,regular polygon,regular polygon sides=3,inner sep=20]{};
\path[fill=white,rotate=60]
(0.6,1.5)rectangle(5,1.8)
(0,0)circle(1.4);
\fill
circle(1)
(17,3)node[scale=9,align=left]{CODE GOLF\\\tiny\&~coding challenges};
}
\enddocument
```
Outputs a PDF:
[](https://i.stack.imgur.com/K1wDE.png)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 332 bytes
```
g=Graphics;r=GraphicsRow;c=RGBColor;r@{r@{Style["{",30],GraphicsColumn[{g@{c@"#0061BA",Polygon[{{15,6},{6,23},{15,40},{36,40},{43,23},{37,6},{17,6},{32,30},{19,30},{24,20}}]},g@{{c@"#F7CC46",Disk[]},{White,Thickness[.05],Circle[{0,0},.8]}}},ImageSize->Scaled[.04]],Style["}",30]},Column@{Style["CODEGOLF",15.5],"&codingChallenges"}}
```
[Try it online!](https://tio.run/##PY9fS8MwFMW/SwSfriX9O6VM6jpXBGGyCj6UPoQspGFpI21FZshnr9fWDQK/3MPhnntaNjaiZaPibJrkuujZZ6P4kPbX78F8p3x9KDa50aZP@8ziK8ezFhWxBEJaw8WKjq@2q6zMLM/IDaWJv3ki8Gb0WRrUrR9D4sAmEIQInCKKDJOFUbjo4Wp2@QvCADP@xoeFQQQBda52gDFzzm6V51FCYKuGU4W6/WjUKOAdTzp1Yhgqj8Y15KrneLOlgFu8@9o5By8tk6JUP@LuseRMiyNao7qG/3purudg6XVtne@3z8X@dUfAjz3cTG65OapO5g3TWnRSDMS5afoF "Wolfram Language (Mathematica) – Try It Online")
[](https://i.stack.imgur.com/FqiiN.png)
[Answer]
# HTML + CSS, ~~958~~ ~~656~~ 588 bytes
[](https://i.stack.imgur.com/AowEZ.png)
```
<div style="display: flex; align-items:center; font-size:40px;">{
<div style="color: blue; line-height:0; transform: translate(-7px,07px); width: 32px">
<div style="transform: scaleX(0.65); letter-spacing: -5px;">‚ô¶‚ô¶</div>
<div style="width:16px; height:7px; background:blue; margin:-15px 0 0 15px "></div>
<div style="transform: scale(0.47, 0.51); margin:14px 0 0 9px">‚ñ≤</div>
<div style="color: gold; font-size: 20px; margin:21px 0 0 13px">‚óâ</div>
</div>
}<div><div style="font-size:21px">CODE GOLF</div><div style="font-size:14px">& coding challenges</div></div></div>
```
This solution works on Chrome and Safari
] |
[Question]
[
## Task
Given 2 positive integers `n` and `k`, where `n > k`, output the number of surjections from a set of `n` distinguishable elements to a set of `k` distinguishable elements.
## Definition
A function f: S → T is called a surjection if for every t∈T there is s∈S such that f(s) = t.
## Example
When `n=3` and `k=2`, the output is `6`, since there are `6` surjections from `{1,2,3}` to `{1,2}`:
1. `1↦1, 2↦1, 3↦2`
2. `1↦1, 2↦2, 3↦1`
3. `1↦1, 2↦2, 3↦2`
4. `1↦2, 2↦1, 3↦1`
5. `1↦2, 2↦1, 3↦2`
6. `1↦2, 2↦2, 3↦1`
## Testcases
```
n k output
5 3 150
8 4 40824
9 8 1451520
```
## Reference
* [OEIS A019538](https://oeis.org/A019538)
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in bytes wins.
[Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~5~~ 4 bytes
```
ṗṬML
```
This is an **O(kn)** brute force solution.
[Try it online!](https://tio.run/##ASkA1v9qZWxsef//4bmX4bmsTUz/OyLDpy/igqxH//9bMywgNV0sIFs0LCA4XQ "Jelly – Try It Online")
### How it works
```
ṗṬML Main link. Left argument: k. Right argument: n.
ṗ Cartesian power; yield the list of all n-tuples over {1, ..., k}.
Each tuple represents a (not necessarily surjective) function from
{1, ..., n} to {1, ..., k}.
Ṭ Apply the "untruth" atom to each tuple.
Ṭ maps a list of indices to an array with 1's at those indices, and exactly
as many zeroes as needed to build the array.
Examples:
[1, 2, 3, 3, 3] -> [1, 1, 1]
[1, 3, 5] -> [1, 0, 1, 0, 1]
[2, 6, 2, 4, 4] -> [0, 1, 0, 1, 0, 1]
M Yield all indices of maximal elements, i.e., all indices of [1] * k.
L Take the length.
```
[Answer]
# [Haskell](https://www.haskell.org/), 48 bytes
```
s(_,1)=1
s(1,_)=0
s(m,n)=n*(s(m-1,n-1)+s(m-1,n))
```
[Try it online!](https://tio.run/##LcuxCoAgEADQvS/xSqWbWvJLRERCSNKjsjb/3QTb3vJ2lw8fY62ZWY6gcMgMuQU1NyROoGhkTQI5CYTpJ0BNLpDK/no9bV6fd6BH91JoFRqlTMaU1LkYUz8 "Haskell – Try It Online")
### Why is the surjection count `s(m,n)=n*s(m-1,n-1)+n*s(m-1,n)`?
in order to harvest `n` images, i can either
* squeeze a singleton `[m]` creation into any of
the `n` boundaries surrounding `n-1` groups
* or add my new `m` into any of `n` already existing groups of `[1..m-1]`
# [Haskell](https://www.haskell.org/), 38 bytes
```
m#n|n<2=1|m<2=0|o<-m-1=n*(o#(n-1)+o#n)
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P1c5rybPxsjWsCYXSBrU5Nvo5uoa2uZpaeQra@TpGmpq5yvnaf7PTczMsy1OLSxNzUtOjS4oyswriYZo1Y021NPLjY0F6gczLWNj/wMA "Haskell – Try It Online")
[Answer]
# [Lean](https://leanprover.github.io/), 66 bytes
```
def s:_->nat->nat|(m+1)(n+1):=(n+1)*(s m n+s m(n+1))|0 0:=1|_ _:=0
```
[Try it online!](https://tio.run/##y0lNzPv/PyU1TaHYKl7XLi@xBEzUaORqG2pq5AEJK1swpaVRrJCrkKcNJMF8zRoDBQMrW8OaeIV4K1uD/8qpZYk5CsUKpgrGXDC2hYIJnG2pYPEfAA "Lean – Try It Online")
---
## Proof of correctness
[Try it online!](https://tio.run/##1Rq9buPIuddTTOFFyF2e1lJpn665RtctkHIhELREWoxISiZpr2ivgQAXHC6pggCXpLsUKRIgDxAgXdLfQ/hFNt/PzHCGHEry7l6AyIBFcb6Z7/9vZrI4Kj6k@W5b1mIV1dE4vrlN7/gxSQv9UDe7@MMqTkR1EX7xVRHV9O@9l7@a@F4B/y5m9PXSq0Quilfwn37778/F@cVs8j4U4cXs/ENaVHVULGMBs8ereJmuoqssDq/ifVrVVZjVwivEBY76wnsDTz/9RWzEl6IIxJtyu/PFxUiIp@9/Ld7OYRAfCrEOhF4JJ8Ebf2G9e/r@W4bjQXExG13F12kBa6XF6nZZp9sCRt6l9Rq@vplfwuu63F6KMq7i@psA4B5EvI@WtUirMImyChb96V/i6ce/hQGuGz79@PeAeCq2NXAR3sflVoSI6xFnL6MqrmBhmrVhSjbAKkwA4Op2uQy3CXK/9n0mY81Ir5qQ5@6AXaTemlPFWSIKH0EtCuvyNkbiCqbJBg/EDqhlunBWtNtljeaL3woWgFhv1O@SyVhvmDxYfAOcbyb4b4rcSzgGM7GmCXIWbsswvhlPcI7kcGMsr4hvV1YLK0IRprq9qmoaY@gdwohH/EMgzQnyjy8U0Qdo5oV4yKGOFngUF6vRaMB@pfmixzyg/T795odHtl98VYin7/7A9gsYyXLbqbsyXok3C/MdG2yKRpKSsbbQQBbIkwGkHUm2gER/BM9slh1G8ZV@Sy/UAIO7x3rroBhGGAWAKzLxMM7SXDx8DdT/EkLIy0fJ8Tlx/DXSDgj2gSDbGhP0Wc9P9mAW@/G0Xbq6zYUHYURFggvh4aq5ePrdDyxRXzz99lt6BLhX@BtQPYh6Gya3MG0mGC0sNC5j0GYh9mRF6H8NcdaMJ1rjW7ZQ@B@LZjyVJIK4o9UqLNPrdY1BjSRsL4K49UIIDMvQV5zUtFKOkwKKM3c2aWki0BCQ9y9FTuvW67ggktMiw9X3uPIchY6jMUYdHi3lqPhC5CYTXQrOpOdU6@07gbR6cpKPOFFuyreScptzbMHJ4GdSGmeCjQ7VdV2LuT@umhz08Md/osakDyGuEBi05U6@15P8VSMqyDfiLUhnccl4QY2QdxDNXXwjyiSzxLyO7mIS1b//weK@izIk31gL6SZzzOKF4qgdnbfqQcaW6L8ZCWhxqYAH6KAggvq32VPJQ7Tx2dClCqwrRA855J14u0qTcLcFKGAZ3yoiOfr08LbBubNGEV/31uCoZ61hA@Dkvma9jmIX4hHDYbGCb@2Iu3K7cnvif/7kcMSXg45I9joF@YDNARhICm17GWVLpQH49CDgeaLHZ/IdIIH3CnYCJIGmo2VYxklGwOPxGIj6qwUuGWAfjVsPwWWmItTzZuQivLJPcy8EpC0yeo4KlB3y2wyye2ihyyU4AsE4osEvDh8hUaMcphcMtI0X4itxbjklLgemQ7qKOV6e4ay5NnRnPD0j@6d8OZduBrzyHE9Gj9dYDJDTr9I7nC1TteQOvX1quDl85MQXQlYW@RYDDoKqONeJBTghEA2nlc/KZENMzikUNYoztNdxvK8hmUhybd8665ocCKMxbc5HoRjjM8LzWprcxLAi1C2JDc2IpCWnsRmd6wmgB/BAJWWmJaPsYE1oV6dIBijwleT/2Vy8cHDxwvICpB/Vh0Vhy0Ro0dRomhDSJF2bhCM6dolV8xEriIDwyBhTcRVBCuXKAfoH6Bg4qjyIxKon@On1awG@QzU7OGP5qxgewbASqAKHQk@6ClxzwnTldMiEJp1TCwG1ZHqXRpk71bF5r/dk312@ddwYKfuFUeKXIrAyc1lqcA2C0QXWc@UdNGbAlRAu8GxsycaECCgHm5d4tA6MAm3fkTdh8YygriXvFRT5huUvAZ6thQ5BTqFbRWIW16Z4ESqBcMSKaRO@FBkWZ0Lm5IHy0l2pOOj6eQRPeYPogUTZFTwVsSDVnuGrgY83/5MEb8EAXyCxAUHngzXfCZJ8PqpWftHt3lWJKHuEesRrxZZrgRWHBIbtxEN/zjEbf/SxQCVFDenp6BLH@xWZHzwdkODhXvcN90bfYH6ohwAYTwr2XvUQPk2g4qY3SU4ro7SKqYntz3bMoYYEgJyogPugrZeUSh2gU9Xf9JZu0x9/mP88qpdr1fNAcF6ut/U2b0ggXLphs99b8b3YltRXzVHaMrhgGwie3ci2t5nageZ@oEWcO6O2KvBUGLI/Gptjk0Hi7@YP3cAAAFEHIgtaJS1cgpNslsJT7GJBLrHnju2g/DDq@SlYSonlZKlCCzqRlSc2JECQjBRcf2Ltc@aQoTCVIWXPq8jmT4Q@F633BzTBZeiEGkoAxG4SyAHfgMo/qWof3wRO7FSqYlXamkVaYttBxnfmMhW1XYe1D7wxuYVlfLPA7VI4BQrRjzxNow8l2f0R8vqd7i9sygblFvx8VovOPnVaEvSb1rbKcKTjENWNH4cixQnmeN8zkRM47nG44K0x35lbVcgbdD7CL3mlbb2AuPTaaLxBxR9ZpruBRFtENOf7P7cxQ0mJs80JAtq3AgJX11s63qEN3mbSZgsvqoCeWKyBuYZ3bVqMBr6hGTOc0dLZ26REOudAo3N8XJdRUdmhBJS3zOKoFGD20OlSMmkfL9UW86Xaj2bqHHtwmTRU3spbUz1iq23vc849ZgG@kZFJgyqndtdyJqO1Mxkdx2nlXSOVY6zpIJbh5xkRmzYcJ7QtMsAJBaueSWEgKSVvXMKLtV16aPOYDEp8dorEO93GXPYadjRbT3qlTx//YTxK/wd1ORST19CJ6W0Cwu5Yyjx94R1Tl6eCWK9jauhPIHrAG7vWHCpRHnFQDCQG0Y3fibp6KhBextU2g9acU6R3@CDJ75YJpnI2HDwcDq@9fEI7q3iGFBk@b6f2kOPUyFlBKGFotk/2@E625U0ioEQHHgvAkWRXnIPacvBSlWx8XNOpFN0q7SuTfLY5Ual8jDJQ6zeuGuz/V9VQLH42batCct0rJBu1dWsQO7lsSzs7VHRTAUjK/1S7Wch8N7ybyxsh7RmIOvRNzDNglSX12a2E4aNYSJhJSyifYLR7t@1ItcvSOsCTXyTxsR0gLgLzXKQ9@JHggdqe2Zgi6bFvDurTHPYNKLzkYdO@W3U/mMc6C1u9ild5VG4ec2u@uH5EQ1p0xxznOc7pj5@EVZ2Z9xmyZXni0qcSzdiHD@SCT2SrO0YVYFqnd2nddMfUnQPrIGzdJUBIY2JYY0e4vXdg3pgw2ih1MOggvGeF5OgGAI9vxtPeyKk2ygqVBtpdRIgy3mXRMsZbGBjMQXF3rDkse2zId@Lpu98jYNRJS1IzAVPbHR2IsM4F1OWPRwf9aI8O@gepYlN04hkdVeph6lr6jBBX/m9CnB1nDoW4jm0FAs3IyRjpxJa5tK0EOj/r0sy0kxn5xktqY@656uTk0KucWCYhlPVIbhAc3ZO3UhEXAHuBXTjXAArNyjwUty5WYdvtbdQ@sA9i7bffx3v4TlYQu4Xtz@2vvtYOBDlN6Q1VOvqCQWsG4u3NwqVMPTbqFjQoRaMCo@O/wwWYL6yALk@WTZewMsizmLc5NC9R8Lp6vOSQZ@gGzZPinrjBmkUVZM8ox7SYQIKd9KH95KDlupNfTx2IybjKcpwPuSmZPKu0fOinITvek@oPbUr2JsrbIy7LoLjcmyHzHsY0aAN66VRd3ZOtQMt1t/ueW7f/zDCB4g3E/AQ19Cbbb7pXY@SO6VD949Kqwtu/wmBDSb109AXrpUXslkbYbUaOlULOquLlM4WEIplPXFPRDbfARbRK@cZsZY@zYksOJM7bHNCUgmFM6Vjct6unzxmtIN91wtVBwanqZT4Q4FQeUmeRyy0UM8u6iKtK3kHO8T6MPMrN1Z2oZ59G8mVJ6eryFDCnXXF520Zv6hTWxQkJYZ7tFz72y7iaSNeO6Z55Hg2qIPUUwQjvlegzadXRI0D7o6DDT@KwdwDbigDe4be6TuDzxW1P3ykLRchXCUd8fergYr6@9@k5FqUb62NcFc3zGuyP33DB6TNSvFF6As6H56iMzo9bk/m4g@TTWOCfwIQaR6369KWlobkCQg4cO8ujdBCrcZvZPliX9/0/yoLl3DF1Erd02@fM8hhCXK/jbRnn5kA47VDBdjRT1ID5lquPIol3U7qEhbSe1yHN592QD/8F)
---
## Explanation
Let us ungolf the function:
```
def s : nat->nat->nat
| (m+1) (n+1) := (n+1)*(s m n + s m (n+1))
| 0 0 := 1
| _ _ := 0
```
The function is defined by pattern matching and recursion, both of which have built-in support.
We define `s(m+1, n+1) = (n+1) * (s(m, n) + s(m, n+1)` and `s(0, 0) = 1`, which leaves open `s(m+1, 0)` and `s(0, n+1)`, both of which are defined to be `0` by the last case.
Lean uses lamdba calculus syntax, so `s m n` is `s(m, n)`.
---
Now, the proof of correctness: I stated it in two ways:
```
def correctness : ∀ m n, fin (s m n) ≃ { f : fin m → fin n // function.surjective f } :=
λ m, nat.rec_on m (λ n, nat.cases_on n s_zero_zero (λ n, s_zero_succ n)) $
λ m ih n, nat.cases_on n (s_succ_zero m) $ λ n,
calc fin (s (nat.succ m) (nat.succ n))
≃ (fin (n + 1) × (fin (s m n + s m (n + 1)))) :
(fin_prod _ _).symm
... ≃ (fin (n + 1) × (fin (s m n) ⊕ fin (s m (n + 1)))) :
equiv.prod_congr (equiv.refl _) (fin_sum _ _).symm
... ≃ (fin (n + 1) × ({f : fin m → fin n // function.surjective f} ⊕
{f : fin m → fin (n + 1) // function.surjective f})) :
equiv.prod_congr (equiv.refl _) (equiv.sum_congr (ih n) (ih (n + 1)))
... ≃ {f // function.surjective f} : s_aux m n
def correctness_2 (m n : nat) : s m n = fintype.card { f : fin m → fin n // function.surjective f } :=
by rw fintype.of_equiv_card (correctness m n); simp
```
The first one is what is really going on: a bijection between `[0 ... s(m, n)-1]` and the surjections from `[0 ... m-1]` onto `[0 ... n-1]`.
The second one is how it is usually stated, that `s(m, n)` is the cardinality of the surjections from `[0 ... m-1]` onto `[0 ... n-1]`.
---
Lean uses type theory as its foundation (instead of set theory). In type theory, every object has a type that is inherent to it. `nat` is the type of natural numbers, and the statement that `0` is a natural number is expressed as `0 : nat`. We say that `0` is of type `nat`, and that `nat` has `0` as an inhabitant.
Propositions (statements / assertions) are also types: their inhabitant is a proof of the proposition.
---
* `def`: We are going to introduce a definition (because a bijection is really a function, not just a proposition).
* `correctness`: the name of the definition
* `∀ m n`: for every `m` and `n` (Lean automatically infers that their type is `nat`, because of what follows).
* `fin (s m n)` is the type of natural numbers that is smaller than `s m n`. To make an inhabitant, one provides a natural number and a proof that it is smaller than `s m n`.
* `A ≃ B`: bijection between the type `A` and the type `B`. Saying bijection is misleading, as one actually has to provide the inverse function.
* `{ f : fin m → fin n // function.surjective f }` the type of surjections from `fin m` to `fin n`. This syntax builds a subtype from the type `fin m → fin n`, i.e. the type of functions from `fin m` to `fin n`. The syntax is `{ var : base type // proposition about var }`.
* `λ m` : `∀ var, proposition / type involving var` is really a function that takes `var` as an input, so `λ m` introduces the input. `∀ m n,` is short-hand for `∀ m, ∀ n,`
* `nat.rec_on m`: do recursion on `m`. To define something for `m`, define the thing for `0` and then given the thing for `k`, build the thing for `k+1`. One would notice that this is similar to induction, and indeed this is a result of the [Church-Howard correspondence](https://en.wikipedia.org/wiki/Curry%E2%80%93Howard_correspondence). The syntax is `nat.rec_on var (thing when var is 0) (for all k, given "thing when k is k", build thing when var is "k+1")`.
Heh, this is getting long and I'm only on the third line of `correctness`...
[Answer]
# [J](http://jsoftware.com/), 19 bytes
```
-/@(^~*]!0{])],i.@-
```
[Try it online!](https://tio.run/##y/qfVqxga6VgoADE/3X1HTTi6rRiFQ2qYzVjdTL1HHT/a3Ip6Smop4EUqeso1FoppBVzcaUmZ@QrxBspaFin6WvGKFRYKZgqGCtYKJgoWCpY/AcA "J – Try It Online")
## Explanation
```
-/@(^~*]!0{])],i.@- Input: n (LHS), k (RHS)
- Negate k
i.@ Range [k-1, k-2, ..., 0]
] Get RHS
, Join, forms [k, k-1, ..., 0]
( ) Dyad between n (LHS), [k, k-1, ..., 0] (RHS)
] Get RHS
0{ Select value at index 0
] Get RHS
! Binomial coefficient
^~ Raise each in RHS to power of n
* Multiply
-/@ Reduce from right to left using subtraction (forms alternating sum)
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 7 bytes
```
#`¦ḣ¹π²
```
[Try it online!](https://tio.run/##yygtzv6fe2h5arFGsdujpsb/ygmHlj3csfjQzvMNhzb9//8/WsNYx0hTR8NUxxhIWuiYaMYCAA "Husk – Try It Online")
### Explanation
```
#`¦ḣ¹π² Inputs: n (²), implicit k (¹)
π² Cartesian power of [1..k] to n
# Count if:
ḣ¹ Range [1..k]
`¦ Is a subset
```
[Answer]
# [R](https://www.r-project.org/), 49 bytes
```
function(n,k,j=0:k)((-1)^(k-j)*j^n)%*%choose(k,j)
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNPJ1sny9bAKltTQ0PXUDNOI1s3S1MrKy5PU1VLNTkjP784VQOoQvN/moaljoXmfwA "R – Try It Online")
Implements one of the formulas by Mario Catalani:
```
T(n, k) = Sum_{j=0..k} (-1)^(k-j)*j^n*binomial(k, j)
```
or alternately:
```
T(n, k) = Sum_{j=0..k} (-1)^j*binomial(k, j)*(k-j)^n
```
which yields the same byte count in R.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~56 53~~ 50 bytes
```
f=lambda n,k:n/k and(1/k or f(n-1,k-1)+f(n-1,k))*k
```
[Try it online!](https://tio.run/##TcnBDkAwEATQM1@xxy4rsi4SiY@pUFZZ0rj4@tLEwWVm8ua8r@XQJkbXb3YfRgtKvtPag9XR8NtHAGe0YvIVY/lNxMJH914CohCszpNharHLs6TrX6Xk5NkZRC8jtJJLiRgf "Python 2 – Try It Online")
-3 bytes thanks to H.PWiz.
-3 bytes thanks to Dennis.
* If `n<k` not all `k` can be mapped onto thus there are no surjections. `n/k and` takes care of this.
* Taking `f(0,0)=1` gives us the only nonzero base case we need. `1/k or` achieves this.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 46 bytes
```
f=->n,k{k>n ?0:k+n<1?1:k*(f[n-=1,k]+f[n,k-1])}
```
[Try it online!](https://tio.run/##Hcm9CoAgFEDhvacQWvq5gtc0TLIeJFwaXC5IBA0RPbuZ2/k457XfKQXHlwj00BLZKiz1ccYVLXVN2CJ3COT7XEAcffumg4VtAOlZPVZ/axhyoxZFBlSWEkaq4gnMf5VGLUX6AA "Ruby – Try It Online")
Standard recursive approach...
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 142 bytes
```
({}<({}()){({}[(())]<<>{({}({})<>)<>}{}>)}{}>)<>{<>(({}<>)<{({}[()]<([])({([{}]()({}))([{}]({}))}{}[{}])>)}{}({}<>)>)<>}<>{}{}{({}<>[{}])<>}<>
```
[Try it online!](https://tio.run/##JYyxDoAwCER/xREGd00IP9J0qIOJ0Ti4Er4dD5pQ@ji4O75xvev5jDuCzAWPmA1fI0AX0RxQLIpyc@VqWIhSesDTgHNqncmomXfidPHkJNiSuQKmsSKRBMFKqYPSIvZl@wE "Brain-Flak – Try It Online")
This uses the standard inclusion-exclusion formula.
I can't write up a full explanation at this time, but here's a high-level explanation:
```
# Compute k-th row of Pascal's triangle
({}<({}()){({}[(())]<<>{({}({})<>)<>}{}>)}{}>)<>
# Multiply each element by n^j (and reverse to other stack)
{<>(({}<>)<{({}[()]<([])({([{}]()({}))([{}]({}))}{}[{}])>)}{}({}<>)>)<>}
# Compute alternating sum
<>{}{}{({}<>[{}])<>}<>
```
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 38 bytes
```
(n,k)->Pol(exp(x+O(x^n))-1)^k*n!\x^n%x
```
[Try it online!](https://tio.run/##FcdBCoMwEEDRq4yCMGMnC1HBLuoV7F4jhFJFDOkgLsbTp3H13xd3bGaVuLwiBt7J9O@fx68K6mNAnQORqWjey5BN6QqNTsRfqGB6kGMLZ2J@Tw4f5z0uDErEMI4tQ20TOobm7pOhs5biHw "Pari/GP – Try It Online")
Using the formula by Vladimir Kruchinin on OEIS:
```
E.g.f.: (exp(x)-1)^k = sum T(n,k)x^n/n!
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 43 bytes
```
T=(n,k)=>n<k?0:k+n<1||k*(T(--n,k)+T(n,k-1))
```
[Try it online!](https://tio.run/##XctBDsIgEEDRfU/CCBhASKgBvQQXaCppWprBWOOKuyMsdf3@36bPdMyv9fnmmB@x1uAJsgT@hi7dxTVRdLKUdCKBcN6Fhh5wCVDnjEfe43nPS2PDLuC9NAKGX7BMN9DCKv1PI7P90UYaJaB@AQ "JavaScript (Node.js) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
```
sLsãʒêgQ}g
```
[Try it online!](https://tio.run/##MzBNTDJM/f@/2Kf48OJTkw6vSg@sTf//35TLGAA "05AB1E – Try It Online")
**Explanation**
```
sLsã # Cartesian product of range(k) repeated n times
ʒ } # Filter by ...
êgQ # Connected uniquified length == k (every item in range(k) appears at least once)
g # Count
```
] |
[Question]
[
Given a non-negative integer or a list of digits, determine in how many ways can the number be formed by concatenating square numbers, which may have leading zeroes.
# Examples
```
input -> output # explanation
164 -> 2 # [16, 4], [1, 64]
101 -> 2 # [1, 01], [1, 0, 1]
100 -> 3 # [100], [1, 00], [1, 0, 0]
1 -> 1 # [1]
0 -> 1 # [0]
164900 -> 9 # [1, 64, 9, 0, 0], [1, 64, 9, 00], [1, 64, 900], [16, 4, 900], [16, 4, 9, 0, 0], [16, 4, 9, 00], [16, 49, 0, 0], [16, 49, 00], [16, 4900]
```
# Rules
* Standard Loopholes Apply
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest answer in bytes wins
[Answer]
# [Haskell](https://www.haskell.org/), 135 bytes
```
s x=any((x==).(^2))[0..x]
c(a:b:x)=a*10+b:x
c x=x
h[x]=1>0
h x=(s.head)x
f x@(_:_:_)|y<-until h c x=f(tail y)+f(c y)
f x=sum[1|any s x]
```
[Try it online!](https://tio.run/##FU7BCsIwFLv3K3rw8OrqaEUEhxX/o1Spc6XDrYjd4A327/WNHJJAQhJ9/nTDUErmaHxaANAYUcPjKIRVdY2OteCbV4PC@L1WFSnWUhZZtOiMvikWyUKuY@ffAlngeIdnQxDrcj3MaeoHHvnWCTB5MouoArREW9bkebR6pWlOF1wZfZ/M99enaReslmd5kheppHLlDw "Haskell – Try It Online")
Probably not well golfed yet but this is a surprisingly difficult problem
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ŒṖḌƲẠ€S
```
A monadic link taking a list of digits and returning a non-negative integer.
**[Try it online!](https://tio.run/##y0rNyan8///opIc7pz3c0XO47dCmh7sWPGpaE/z///9oEx0DIDSJBQA "Jelly – Try It Online")** or see the [test suite](https://tio.run/##y0rNyan8///opIc7pz3c0XO47dCmh7sWPGpaE/z/6J7D7UBGFhA/apijoGun8KhhbuT//9HRhjoKZjoKJrE6CiCmgY6CIYJpAGaCCDDLBCKIohqKYmMB "Jelly – Try It Online").
### How?
```
ŒṖḌƲẠ€S - Link: list of digits e.g. [4,0,0,4]
ŒṖ - all partitions [[4,0,0,4],[4,0,[0,4]],[4,[0,0],4],[4,[0,0,4]],[[4,0],0,4],[[4,0],[0,4]],[[4,0,0],4],[4,0,0,4]]
Ḍ - convert from decimal list (vectorises) [[4,0,0,4],[4,0, 4 ],[4, 0,4],[4, 4],[ 40,0,4],[ 40, 4],[ 400,4], 4004]
Ʋ - is square? (vectorises) [[1,1,1,1],[1,1, 1 ],[1, 1,1],[1, 1],[ 0,1,1],[ 0, 1],[ 1,1], 0]
Ạ€ - all truthy? for €ach [ 1, 1, 1, 1 0, 0, 1, 0]
S - sum 5
```
[Answer]
## [Haskell](https://www.haskell.org/), 88 bytes
```
f x=sum[0.5|y<-mapM(\c->[[c],c:" "])x,all((`elem`map(^2)[0..read x]).read).words$id=<<y]
```
Defines a function `f` that takes a string and returns a float.
Very slow.
[Try it online!](https://tio.run/##HcvRCsIgGEDhV/mRXShsYlFBob3BnsCMiTqSdA1d5KB3t9HdufjOQ@enC6HWEYrI7ygZPX5X3kU99/hmuquURrXmggApUlodAsaDCy4Om8D3PdkGmpy2UBT5B6GfV7K58VZwvqoatZ9AwJz8tEADI6Dd6XBmDNUf "Haskell – Try It Online")
## Explanation
I'm using [my Haskell tip](https://codegolf.stackexchange.com/a/98446/32014) for computing all partitions of a string with `mapM` and `words`.
The snippet `mapM(\c->[[c],c:" "])x` replaces every character `'c'` of a string `x` with either the one-element string `"c"` or the two-element string `"c "`, and returns the list of all possible combinations.
If I take one of the results, `y`, concatenate it and call `words` on the result, it will be split at the spaces inserted by `mapM`.
In this way I obtain all partitions of `x` into contiguous substrings.
Then I just count those results where each partition element is a perfect square (by finding it in the list `[0,1,4,9,..,x^2]`).
A caveat is that each partition is counted twice, with and without a trailing space, so I take the sum of `0.5`s instead of `1`s; this is why the result type is a float.
```
f x= -- Define f x as
sum[0.5| -- the sum of 0.5 for
y<- -- every y drawn from
mapM(\c->[[c],c:" "])x, -- this list (explained above)
-- (y is a list of one- and two-element strings)
all(...) -- such that every element of
id=<<y] -- concatenated y
.words$ -- split at spaces satisfies this:
-- (the element is a string)
(...).read -- if we convert it to integer
`elem` -- it is an element of
map(^2) -- the squares of
[0..read x] -- the numbers in this list.
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 16 bytes
```
lf!f!sI@sjkY2T./
```
[Test suite](http://pyth.herokuapp.com/?code=lf%21f%21sI%40sjkY2T.%2F&test_suite=1&test_suite_input=%5B1%2C+6%2C+4%5D%0A%5B1%2C+0%2C+1%5D%0A%5B1%2C+0%2C+0%5D%0A%5B1%5D%0A%5B0%5D%0A%5B1%2C+6%2C+4%2C+9%2C+0%2C+0%5D&debug=0).
[Answer]
# [Python 3](https://docs.python.org/3/), ~~148~~ ~~139~~ ~~135~~ 134 bytes
10 bytes thanks to Arnold Palmer.
```
def f(a):
s=[a[:1]]
for i in a[1:]:s=sum([[x+[i],x[:-1]+[x[-1]*10+i]]for x in s],[])
return sum({n**.5%1for n in x}=={0}for x in s)
```
[Try it online!](https://tio.run/##ZYvLCsMgFET3foWbgia3RekDKvgll7sINFIXNUUTsIR8u42rknQ1zJk578/4HMK5lEfvuBOdNIwnix0aTcS4GyL33AfeoTZkkk3TSyDmFj1BRnPU1GLGNRqtWk9UhVyFRIAkGY/9OMW1rt4cmuZ0Pej6CfWTF2tntfwcWd7Rh1E4gRpucIE7KFAkJdvyHVGg/8jO2rS6lS8 "Python 3 – Try It Online")
[Answer]
# Mathematica, 141 bytes
```
Count[FreeQ[IntegerQ/@Sqrt[FromDigits/@#],1<0]&/@(FoldPairList[TakeDrop,s,#]&/@Flatten[Permutations/@IntegerPartitions[Length[s=#]],1]),1>0]&
```
**input** (a list of digits)
>
> [{1,6,4}]
>
>
>
[Answer]
# [Python 2](https://docs.python.org/2/), ~~173~~ 163 bytes
```
lambda s:len([l for l in[''.join(sum(zip(s,[','*(n>>i&1)for i in range(len(s))]+['']),())).split(',')for n in range(2**~-len(s))]if {int(x)**.5%1for x in l}=={0}])
```
[Try it online!](https://tio.run/##VcvRCoIwFIDh@55iN7VzlskW1UWgL2JeGLlazDmcgSX26msLQrr84fvts7@1ZutldvK6as6Xirijrg0Umsi2I5ooU1Ca3ltlwD0aeCkLLiloQhmYPFcrgdGp4EhXmWsN8XaI5Tp8JSaAiKmzWvUQpi82M94y9t78DiXJqEwPAzKW7pci2iFaPWXZyKcSve0CIBKo4ILiYs7D7i85p@g/ "Python 2 – Try It Online")
Edit: Saved 10 bytes due to ArnoldPalmer
] |
[Question]
[
# Overview
Given a list of digits, find the fewest operations to make 100
# Input
A string of digits, which may or may not be in numerical order. The order of the digits cannot be changed, however plus (+) or minus (-) operators may be added between each so that the total sum is equal to 100.
# Output
The number of operators added, followed by the full sequence of digits and operators. The two can be separated by a space, tab, or new line sequence.
# Examples
**valid**
Input: `123456789`
Output: `3 123–45–67+89`
**Invalid**
Input: `123456789`
Output:
`6
1+2+34-5+67-8+9`
(There are ways of solving this with fewer operations)
[Answer]
## JavaScript (ES6), ~~153~~ 176 bytes
*EDIT: In non-strict mode, JS interprets 0-prefixed numerical expressions as octal (e.g. `017` is parsed as 15 in decimal). This is a fixed version that supports leading zeros.*
```
let f =
s=>[...Array(3**(l=s.length,l-1))].map((_,n)=>m=eval((x=s.replace(/./g,(c,i)=>c+['','+','-'][o=(n/3**i|0)%3,j-=!o,o],j=l)).replace(/\b0+/g,' '))-100|j>m?m:(S=x,j),m=l)&&m+' '+S
console.log(f("123456789"))
console.log(f("20172117"))
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~37~~ 36 bytes
```
n'+-'OhZ^!t2\s&SZ)"G@!vXzU100=?@z3M.
```
The test case takes about 6 seconds in TIO.
[**Try it online!**](https://tio.run/##y00syfn/P09dW1fdPyMqTrHEKKZYLThKU8ndQbEsoirU0MDA1t6hythX7/9/dUMjYxNTM3MLS3UA "MATL – Try It Online")
### How it works
```
n % Implicitly input a string. Number of elements, say k
'+-' % Push this string
Oh % Append char 0. This is treated like ' ' (space)
Z^ % Cartesian power of the three-char string '+- ' raised to k.
% Gives a matrix where each row is a Cartesian k-tuple
! % Transpose
t % Duplicate
2\ % Modulo 2. This turns '+' and '-' into 1, and ' ' into 0
s % Sum of each column: number of '+' and '-' symbols
&S % Sort and push the indices of the sorting
Z) % Apply as column indices. This sorts the columns (k-tuples)
% by the number of '+' and '-' they contain
" % For each column, i.e. each k-tuple formed by '+', '-' and ' '
G % Push input string again
@! % Push k-tuple as row vector (string)
v % Concatenate vertically into a 2×k char array
Xz % Remove space (and char 0). Gives a string as result. In this
% process, the 2×k array is linearized in column major order
% (down, then across). So the '+' and '-' signs are between
% digits of the input, or at the end
U % Convert to number. This performs the operation determined by
% by the '+' and '-' signs and returns the result. A trailing
% '+' or '-' sign makes the input invalid, which causes an
% empty result
100= % Is it equal to 100?
? % If so
@ % Push current k-tuple
z % Number of nonzeros, i.e. of '+' and '-' signs
3M % Push linearized string without spaces again
. % Break for loop
% Implicit end
% Implicit end
% Implicitly dispplay stack
```
[Answer]
# [Python 2], ~~164~~ 158 bytes
```
from itertools import*
f=lambda N:min((len(s)-len(N),s)for s in(''.join(sum(zip(N,p+('',)),()))for p in product(('+','-',''),repeat=len(N)-1))if eval(s)==100)
```
[Try it online!](https://tio.run/##VY1bCsIwEEX/u4r8ZcamYvrQRugWuodqE4w0D9JU0M3XqCB6YbhwOMz193hxtlxXFZwhOsoQnZtmoo13IW4y1U2DOY0D6Y9GW4BJWpixeFWPbEblAkm2BUq3V5d6Xgw8tIee@TxBhsgA8e355BEf3LicIwDNKaNFOoosSC@H2H2@FhxRKyJvw5Smuo7vdrj6oG0kCigvq7rZH1pBMfvCSohS/BHRHvZNXZX8F/JPElqf "Python 2 – Try It Online")
Take N as a string of digits; returns a tuple (numOps, expressionString).
Basically the same approach as others; uses itertools.product to construct the individual "cases" e.g. for N=='1322', a "case" would be `('-','','+')`, and would evaluate '1-32+2'.
Throws an ValueError if the input is invalid (but I think OP gauranteed no invalid inputs).
[Answer]
# PHP, ~~166~~ 171 bytes
```
for(;$n<3**$e=strlen($x=$argn);eval("return $s;")-100?:$r[]=sprintf("%2d $s",strlen($s)-$e))for($i=0,$s="",$k=$n++;a&$c=$x[$i];$k/=3)$s.="+-"[$i++?$k%3:2].$c;echo min($r);
```
Run as pipe with `-nR` or [test it online](http://sandbox.onlinephpfunctions.com/code/bf76e4cfc14b2a6b2f823032f158a22424df7c10).
uses formatted numbers to sort the results -->
may print leading blanks (and may fail for input with more than 99 digits; increase the number at `%2d` to fix).
**no more than 10 digits, 161 bytes**
```
for(;$n<3**$e=strlen($x=$argn);eval("return $s;")-100?:$r[]=(strlen($s)-$e)." $s")for($i=0,$s="",$k=$n++;a&$c=$x[$i];$k/=3)$s.="+-"[$i++?$k%3:2].$c;echo min($r);
```
**breakdown**
```
for(;$n<3**$e=strlen($x=$argn); # loop $n up
eval("return $s;")-100?: # 2. evaluate term, if 100 then
# prepend number of operations, add to results
$r[]=sprintf("%2d $s",strlen($s)-$e)
)
# 1. create term
for($i=0,$s="",$k=$n++; # init variables, increment $n
a&$c=$x[$i];$k/=3) # loop through digits/operator index
$s.="+-"[$i++?$k%3:2].$c; # prepend operator for base-3 digit (nothing for 2)
echo min($r); # print lowest result
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 32 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
L’⁾+_ṗż@€
ŒṖÇ€ẎµFV=ȷ2µÐfLÞḢFṄḟ³L
```
A full program which displays using the Jelly operators (`_` instead of `-`).
*Note:* To show `-` in the output instead of `_` (not a requirement) add `⁾_-y` between `F` and `Ṅ` (`⁾_-` is a character pair literal `['_','-']` and `y` is the dyadic "translate" atom).
### How?
```
L’⁾+_ṗż@€ - Link 1, form all sums from a partition: list of lists of characters
e.g. ["12","345","67"]
L - length 3
’ - decremented 2
⁾+_ - literal ['+','_']
ṗ - Cartesian power ["++","+_","_+","__"]
ż@€ - zip for €ach (swap @rguments) ["12+345+67","12+345_67","12_345+67","12_345_67"]
ŒṖÇ€ẎµFV=ȷ2µÐfLÞḢFṄḟ³L - Main link: list of characters
ŒṖ - all partitions
Ç€ - call the last link (1) as a monad for €ach
Ẏ - tighten (flatten by 1 level)
µ µÐf - filter keep if:
F - flatten
V - evaluate as Jelly code (perform the sum)
ȷ2 - literal 100
= - equal?
Þ - sort by:
L - length
Ḣ - head
F - flatten
Ṅ - print that and a newline
ḟ³ - filter out the characters from the input
L - length (number of operators)
- implicit print
```
**[Try it online!](https://tio.run/##AVIArf9qZWxsef//TOKAmeKBvitf4bmXxbxA4oKsCsWS4bmWw4figqzhuo7CtUZWPci3MsK1w5BmTMOe4biiRuG5hOG4n8KzTP///yIxMjM0NTY3ODki "Jelly – Try It Online")**
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 36 bytes
```
~cịᵐ{|ṅ}ᵐ{+100&{ℕṫ,"+"↻|ṫ}ᵐcbE&kl;E}
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/vy754e7uh1snVNc83NlaC2JoGxoYqFU/apn6cOdqHSVtpUdtu4Fyq0FyyUmuatk51q61//8rGRoZm5iamVtYKv2PAgA "Brachylog – Try It Online")
More than half of this is to get the output format right though. The actual core logic is only:
# 15 bytes
```
~cịᵐ{|ṅ}ᵐ.+100∧
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/vy754e7uh1snVNc83NlaC2ToaRsaGDzqWP7/v5KhkbGJqZm5haXS/ygA "Brachylog – Try It Online")
This returns a list like [123,–45,–67,89]. The expression is the sum of the elements, and the number of operators is 1 less than the length of the list.
`~cLhℕ∧100~+L` almost works for 12 bytes ([Try it online!](https://tio.run/##SypKTM6ozMlPN/r/vy7ZJ@NRy9RHHcsNDQzqtH3@/zc1MDMwNPgfBQA "Brachylog – Try It Online")) - but it's too slow to handle full 9 digit input on TIO, and more importantly, it fails for inputs like `10808` - Brachylog is too smart to split numbers to have leading zeros, so doesn't see the [108, -08] partition.
[Answer]
# Mathematica, 136 ~~146~~ ~~149~~ ~~156~~ ~~165~~ ~~166~~ bytes
```
#&@@Sort[{StringLength@#-e+9!(ToExpression@#-100)^2,#}&/@StringJoin/@(Riffle[b,#]&)/@Tuples[{"","+","-"},(e=Length[b=Characters@#])-1]]&
```
Returns `{3, 123-45-67+89}` for example.
The test case takes about 0.09 seconds to complete.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~256~~ ~~230~~ ~~208~~ ~~205~~ ~~172~~ ~~171~~ ~~170~~ 165 bytes, iterative method
* **33** thanks to Chas Brown
* One saved byte when replacing `len(a)` by `w`
* One saved byte when replacing `z-=1;d=z` by `d=z=z-1`
```
q=[];a=input()
w=len(a);z=n=3**w
while z-n/3:
d=z=z-1;j=0;b=''
while d:r=d%3;d/=3;b+=a[j]+chr(r+43)*(d>0!=r-1);j+=1
if eval(b)==100:q+=[(len(b)-w,b)]
print min(q)
```
[Try it online!](https://tio.run/##Jc3BDoIgAIfxO09Bbi2QnBKdZP9exHmAsIkzUma5eHlb87v@Dt/0XfpXuGzbjKbVBj5M74VxsmLsAjNcJwSoPF/J2vuxo6kIpaoJdUhIhdQDKm1xOhG6u6sj3FFpV0JpK2CaoRX3PrIorornzN2qA2IhuR4EJKH@QbuPGZnlgKyqehZo2H9tebGeLW/JFH1Y6NMHNvNty@Re9gM "Python 2 – Try It Online")
**Little explanation**
Using the representation in base 3, the code interleaves the digits with the operators {'+','-',concatenation} according to all possible combinations.
# [Python 2](https://docs.python.org/2/), 167 bytes, recursive method
```
def f(s):
if len(s)==1:return[s]
b=s[0];q=[]
for z in f(s[1:]):q+=[b+'+'+z,b+'-'+z,b+z]
return q
a=input()
print min((len(x)-len(a),x)for x in f(a)if eval(x)==100)
```
[Try it online!](https://tio.run/##JY7NCoMwEITveYqll2ZRQe1/Sp4keFCa0ICNGmOxvny6Qfbw7cLszIy/8B5cHeNLGzB8RsHAGui1o13KSngdFu/U3DDo5KzK5jlJRYcZPGxgXXpSlWhQTJlUXXak2XJisXMj7e4BE2uldeMSOLLRWxfgYx3nKWvFIqHFfMXkvO7OLVIX/W17ElCZssQYD1V9Ol@ut/vj8Ac "Python 2 – Try It Online")
**Some outputs**
```
"399299" --> (1, '399-299')
"987654321" --> (4, '98-76+54+3+21')
"1111111" --> (3, '1+111-1-11')
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~180~~ 178 bytes
```
m#[a]=[[a]]
m#(b:r)|s<-m#r=m(b:)=<<[s,m('+':)s,m('-':)s]
o '-'=(-)
o _=(+)
(p:r)?a|[(b,s)]<-lex r=s?o p a(read b)
_?a=a
g s=minimum[(sum[1|c<-t,c<'0'],t)|t<-map#s,('+':t)?0==100]
```
[Try it online!](https://tio.run/##HY5LisMwEET3OkUTB6wmEtjzn6DGBxEitDMmY8btGEkDWfjujpLN49WiqPrl9DdM07ZJ5TmQLwhKKt0fI67JWakiSUlIzvlkRNeH@ohPsQ8J6grFSFssdiJ9QKWXUu549bo3CYOz03CDSKm7wgKs48A/0KM6dUysLpBIxnmUf/E6FbTr2dlszq5u6mAyrrm84KVK5rmdsWuI2qYJm/A4A8ESxznDHi6wa19e394/Pr@@d9sd "Haskell – Try It Online") Usage: `g "123456789"` yields `(3,"123-45-67+89")`.
`#` builds a list of all possible terms, `?` evaluates a term and `g` filters those terms which evaluate to 100 and returns the one with the minimal number of operands.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 27 bytes
```
L’““+“_”ṗ⁸żF¥ⱮV⁼ȷ2ƊƇLÞḢṄḟ⁸L
```
[Try it online!](https://tio.run/##y0rNyan8/9/nUcPMRw1zgEgbiOMfNcx9uHP6o8YdR/e4HVr6aOO6sEeNe05sNzrWdazd5/C8hzsWPdzZ8nDHfKAKn/@H249Oerhzxv//6oZGxiamZuYWluoA "Jelly – Try It Online")
Can't say I didn't take a few hints from Jonathan Allan's older answer. ;-)
Compared to his answer, this one is just two bytes shorter (30), not five, if we make the comparison fair due to language updates:
```
L’““+“_”ṗ⁸żF¥Ð€V⁼ȷ2$$ÐfLÞḢṄḟ⁸L
```
If we compare the other way (newer version instead of older), the difference is the same (his becomes 29 bytes, seen below):
```
ŒṖżⱮL’⁾+_ṗƲ$€ẎFV=ȷ2ƲƇLÞḢFṄḟ³L
```
] |
[Question]
[
Given one of the following as input:
```
AK,AR,AS,AZ,CA,CT,DC,FL,GA,IL,IN,IA,KS,KY,LA,MD,MI,MN,MS,NV,NH,NJ,NM,NY,NC,ND,MP,OH,OK,OR,PA,PR,RI,SC,TN,TX,UT,VT,VA,WA,WI
```
(with quotes)
```
"AK","AR","AS","AZ","CA","CT","DC","FL","GA","IL","IN","IA","KS","KY","LA","MD","MI","MN","MS","NV","NH","NJ","NM","NY","NC","ND","MP","OH","OK","OR","PA","PR","RI","SC","TN","TX","UT","VT","VA","WA","WI"
```
Generate and output a (uniformly) random license plate of the format matching the input. If there are multiple (comma separated) formats, use a (uniformly) random format:
```
AK, IA, MS, MP, VT: AAA 000
AS: 0000
AZ, GA, WA: AAA0000
AR, KS, KY, LA, ND, OR: 000 AAA
CA: 0AAA000
CT: AA-00000
DC: AA-0000
FL: AAA A00
IL: AA 00000
IN: 000A,000AA,000AAA,AAA000
MD: 0AA0000
MI: AAA 0000,0AA A00,AAA 000
MN: 000-AAA
NV: 00A-000
NH: 000 0000
NJ: A00-AAA
NM: 000-AAA,AAA-000
NY, NC, PA, TX, VA, WI: AAA-0000
OH: AAA 0000
OK: 000AAA
PR: AAA-000
RI: 000-000
SC: AAA 000,000 0AA
TN: A00-00A
UT: A00 0AA
```
Where `A` means a random character in the uppercase alphabet minus `IOQ` and `0` means a random single digit number (`0` to `9`).
All information from [Wikipedia](https://en.wikipedia.org/wiki/United_States_license_plate_designs_and_serial_formats). These (states) were all of the ones that I understood and that didn't have wonky rules.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins!
[Answer]
# Python3, ~~861~~ ~~821~~ ~~819~~ ~~714~~ ~~678~~ ~~674~~ ~~670~~ ~~662~~ ~~661~~ ~~658~~ ~~596~~ ~~591~~ ~~561~~ ~~555~~ ~~551~~ 536 bytes.
-8 bytes thanks to @DestructibleLemon (`b=a+`... and `d=B`...), -15 bytes thanks to @Felipe Nardi Batista (useless lambda and variable)
And thanks to everyone over in chat who helped golf this!
```
from random import*
C=choice
Z='000'
A='AAA'
B=A+'-0'+Z
a=A+' '+Z
b=A+'0'+Z
c=a[::-1]
d=B[1:]
print(C(''.join(C(['ABCDEFGHJKLMNPRSTUVWXYZ','0123456789',i]['A0'.find(i)])for i in([a]*5+[Z+'0',b,b,b]+[c]*6+['0'+A+Z,d,d+'0',A+' A00','AA 00'+Z,Z+'A,000AA,000AAA,'+A+Z,'0AA0'+Z,a+'0,0AA A00,'+a,Z+'-'+A,'00A-'+A,Z+' 0'+Z,'A00-'+A,Z+'-AAA,AAA-'+Z]+[B]*6+[a+'0',Z+A,B[:-1],Z+'-'+Z,a+','+c,'A00-00A','A00 0AA'])[[*zip('AIMMVAAGWAKKLNOCDCFIIMMMNNNNNNPTVWOOPRSTU','KASPTSZAARSYADRACTLLNDINVHJMYCAXAIHKRICNT')].index(tuple(input()))]).split(',')))
```
[Try it online](https://repl.it/JEtI/28)
Any golfing suggestions are welcome (and wanted). And, please, if you spot any errors, just tell me via the comments!
[Answer]
## JavaScript (ES6), ~~374~~ 368 bytes
```
s=>(P=n=>parseInt(n,36),R=Math.random,g=F=>F?(' -'+(R()*10|0)+'ABCDEFGHJKLMNPRSTUVWXYZ'[R()*23|0])[F&3]+g(F>>2):'')(P('8cf,4q,8fz,ch6,8hq,xpb,8f3,8jj,xov,6i|ru|356|24f,8fy,xmn|8ji|8cf,ciy,8e2,xm2,ciz,ciy|8e7,xof,xmn,356,8e7,8dm,8cf|ca2,bjf,ca3'.split`,`[P('1k3600d2mha35h7bi00jc000o03000000809l002003n0h3032e0fh4g0h'[P(s)%159%131%70%58])].split`|`.sort(_=>R()-.5)[0]))
```
### Formatted and commented
In the following code, data sections have been truncated. Missing parts are marked with `(...)`.
```
s => ( // given the state s
P = n => parseInt(n, 36), // P = base-36 parsing function
R = Math.random, // R = random generator
g = F => // g = recursive function taking an encoded format F
F ? // if the format has not been yet fully processed:
( // build a string consisting of:
' -' + // 0: space, 1: hyphen
(R() * 10 | 0) + // 2: a random digit
'ABCD(...)YZ'[R() * 23 | 0] // 3: a random uppercase letter (minus I, O, Q)
)[F & 3] + // pick the next character from this string
g(F >> 2) // recursive call, dropping the 2 consumed bits
: // else:
'' // stop recursion
)( // initial call to g():
P( // base-36 decoding of a format picked from
'8cf,4q,(...),ca3'.split`,`[ // a list of binary encoded formats
P( // accessed through a base-36 decoded index
'1k36(...)0h'[ // picked from a lookup-table of 58 entries
P(s) % 159 % 131 % 70 % 58 // based on a hash of the state
] // end of lookup-table access
) // end of lookup-table index decoding
].split`|` // end of list access / split it on '|'
.sort(_ => R() - .5)[0] // randomly pick a format from this list
) // end of format decoding
) // end of call
```
### Demo
```
let f =
s=>(P=n=>parseInt(n,36),R=Math.random,g=F=>F?(' -'+(R()*10|0)+'ABCDEFGHJKLMNPRSTUVWXYZ'[R()*23|0])[F&3]+g(F>>2):'')(P('8cf,4q,8fz,ch6,8hq,xpb,8f3,8jj,xov,6i|ru|356|24f,8fy,xmn|8ji|8cf,ciy,8e2,xm2,ciz,ciy|8e7,xof,xmn,356,8e7,8dm,8cf|ca2,bjf,ca3'.split`,`[P('1k3600d2mha35h7bi00jc000o03000000809l002003n0h3032e0fh4g0h'[P(s)%159%131%70%58])].split`|`.sort(_=>R()-.5)[0]))
;[
'AK','AR','AS','AZ','CA','CT','DC','FL','GA','IL','IN','IA','KS','KY',
'LA','MD','MI','MN','MS','NV','NH','NJ','NM','NY','NC','ND','MP','OH',
'OK','OR','PA','PR','RI','SC','TN','TX','UT','VT','VA','WA','WI'
]
.forEach(s => console.log(s + ' --> ' + f(s)))
```
[Answer]
# T-SQL, ~~1104 1100 797~~ 657 bytes
```
DECLARE @ CHAR(8)SELECT @=STUFF(value,1,2,'')FROM STRING_SPLIT(CAST(DECOMPRESS(CAST('H4sIAAAAAAAEAEWPUQ6DMAiGr2JCwlM9BKnZ7LTV2E7n7n+QlRbYC3yl8PNDCyIOAOACKcVstCudRYkytPSthUZPUrqM6KhxqC+3ZKNbaSWlNCltNuEJuozzdekITXDygu6xshNkx2u3xJhqREmWGUQqTiDWYpBLGEGkrOgij47N21k1eKdLM3trI+mF+h2tMSJK441qM3nDnQzLx/D8V69guM3mblvkiP1Q/SPwTqbs1XD2zVztKwnbL7p3wV77AcxSbMHfAQAA'as XML).value('.','varbinary(max)'))AS varchar(max)),','),t WHERE s=LEFT(value,2)ORDER BY NEWID()WHILE CHARINDEX('&',@)>0SET @=STUFF(@,CHARINDEX('&',@),1,SUBSTRING('ABCDEFGHJKLMNPRSTUVWXYZ',CAST(1+23*RAND()AS INT),1))WHILE CHARINDEX('#',@)>0SET @=STUFF(@,CHARINDEX('#',@),1,CAST(10*RAND()AS INT))PRINT @
```
EDIT 1: Saved over 300 bytes by changing `VALUES()` to `STRING_SPLIT()` (only available in SQL 2016 and later)
EDIT 2: Saved another 140 bytes by using GZIP compression [as described here](https://codegolf.stackexchange.com/a/190648/70172). We've already restricted ourselves to SQL 2016 and later, so these functions are available.
Input is via pre-existing table **t** with the State code in column **s**, [per our IO standards](https://codegolf.meta.stackexchange.com/a/5341/70172).
After expanding the compressed string, here's the formatted code, with the super long list of states snipped:
```
DECLARE @ CHAR(8)
SELECT @=STUFF(value,1,2,'')
FROM STRING_SPLIT('AK&&& ###,IA&&& ###,MS&&& ###,...
(long string continues)
...,SC### #&&,TN&##-##&,UT&## #&&',','),t
WHERE s=LEFT(value,2)ORDER BY NEWID()
WHILE CHARINDEX('&',@)>0
SET @=STUFF(@,CHARINDEX('&',@),1,
SUBSTRING('ABCDEFGHJKLMNPRSTUVWXYZ',CAST(1+23*RAND()AS INT),1))
WHILE CHARINDEX('#',@)>0
SET @=STUFF(@,CHARINDEX('#',@),1,
CAST(10*RAND()AS INT))
PRINT @
```
So I created a huge in-memory table consisting of all the possible pairs of (state, pattern). Note that I'm not combining rows, each state is separate, and states like IN will have 4 rows, one for each pattern.
When I join that in-memory table to the input table, I sort by `NEWID()`, which randomizes the order and returns a random matching pattern to the variable `@`.
I then just replace each `&` with a random letter, and each `#` with a random digit and return the result.
[Answer]
## [><>](https://esolangs.org/wiki/Fish), ~~967~~ ~~860~~ 851 bytes
```
</b:++d**d85-*i9*i2
v\+?\"00A AAA"
/5:/
v\+?\"00000 AA"
/4:/\
v\+?\x"000-AAA"
/f:/
v\+?\>"AAA-000"
/1:/
v\+ ?\"A00-00A"
v/cb:/\/"A000"
v\++?\xx"AA000"
v/88:/\x"000AAA"
v\+-?\ >"AAA000"
/2f:/v\
v\*-?\xx"0000 AAA"
v/8c:/\x"00A AA0"
v\*-?\x>"000 AAA"
v/7c:/\"AA0 000"
v\*+?\"0000"
/6b:/
v\*-?\"0000-AA"
/5f:/
v\*-?\"0000AA0"
/bc:/
v\+-?\"AAA-00A"
/59:/
v\*+?\"000-AAA"
/4a:/
v\*- ?\"000-000"
/*a8:/
v\2+-?\"000AAA0"
/*a8:/
v\9++?\"00000-AA"
/*a8:/
v\5++?\"000-A00"
/*a4:/
v\1+-?\"0000 000"
/*a4:/
v\3+-?\"0000 AAA"
/*a5:/
v\3++?\"AA0 00A"
:63*+\:9a*4+-:aa*6++:73*+
/*+9:/
v\***?\"000 AAA"
8*-*$\::9a*-:4
/7*ae/
v\++*?\"0000AAA"
:4a*3\:aa*-:cb++:ca*4++:a7++:b+
v/**++/"0000-AAA"
v\***?/"AAA 000"
<ov?="A":v?="0":;?=1l
~!/0\v[0<
l<1x/?=]!5
+*2_/?= 1l
-8::/*(~!*d2$**-2:-6:
^ >?!^"A"+o]
]~</0\v[0<
l <1x/?=4
+ *2_<v?=1l
^n^?)9:<
```
[Try it online](https://tio.run/##VZLNrtpADIX3eYohuovW1mhCSCBxA9Gs@wgNXCWhqEhXvYtKEStendozHmiz4Oec489jTy7XP78ej85NhHgGODe1hWsL1zJbBuyHvCi88d7nmXE1uafIj4lqRW6I8k10q@FLCh9yViw7oq6japjhOcvwPFvcPDHDicIhtoV147L43zUN2wEe2Byw/WACV7Eld1vkFGBDqR4vwJtZq2WOwA@hQ/5PZicZaWj0CJCmFPp2CqeWsqBZXcflfznQjZvmOKPIcfKYbmNawWlN1agQo7r2hLEJRomK94pPRovPi9DzJKfGZ4/EqoKxTiwd8@VsXo5PsFod7NNmxKDtBnCgdoQKLY0jbBFpx5rUoM4IEGkKa8DC20BSZKni4A7Gn2FHCM/dBXg1wmYQqqV5YvAsbZDGHX9MyBcFgOjSJYR3QZo5WXScqftc@n3uc5KvIqdv/X79kd1XrhiWH0WXmY9ufXP9/riqM4NQvvNvwwljGyIHX@4rOJdvALYku6XsZPg59KsTI/HzmB3v3YtkIoonQsOkbgm9Tr9P/deWusfDf/8L "><> – Try It Online"), or watch it at the [fish playground](https://fishlanguage.com/playground)!
This code has two parts: matching the state to the pattern, then replacing the pattern with the random characters. Neither of these things is easy in ><>.
First of all, we read in two characters, and compute 2 *c*1 - 9 *c*2 + 533, where *c*1 and *c*2 are the two character codes. The 2 and the 9 were chosen so that the formula gives each state a unique value, and the offset of 533 was chosen to maximise the number of these values that can be made using only 3 ><> instructions — it ended up being 28 out of 41 of them. We then send the fish zig-zagging down through the code until it finds the right value, at which point it escapes the zig-zag, reads the appropriate pattern and enters the fast stream in the leftmost column down to Part 2. Some of the states, particularly the ones with a choice of multiple patterns, needed some special consideration, but I managed to reuse some pieces of the code to save a few bytes.
Next, aka Part 2, we have to replace the "A"s and "0"s with random letters and numbers respectively. The only random command in ><> is `x`, which sets the fish's direction randomly out of up, down, left and right — not conducive to choosing something uniformly out of 10 digits or 23 letters. Let's look at the numbers bit to see how the fish does it:
```
]~</0\v[0<
l <1x<v?=4
l 1=_?\2*+
^n^?)9:<
```
The fish enters from the top right. The fish sets up an empty stack — `0[` — then randomly pushes `1` or `0` with equal probability until the stack has length 4:
```
/0\v
l <1x<v?=4
_
```
It then combines the four `1`s and `0`s together as if they were binary digits — `l1=?\2*+` — giving a number from 0 to 15. If the result is greater than 9, it discards all the work it just did and tries again; otherwise, it prints the number and continues:
```
]~< v[0<
x<
^n^?)9:<
```
Making the random letters is much the same, except we also check that the result isn't "I", "O" or "Q" with `::8-:6-:2-**`.
[Answer]
# [Perl 6](http://perl6.org/), ~~492~~ 350 bytes
```
{$_=('AKIAMSMPVT:7 3AS:4AZGAWA:74ARKSKYLANDOR:3 7CA:173CT:6-5DC:6-4FL:7 52IL:6 5IN:35,36,37,73MD:164MI:7 4,16 52,7 3MN:3-7NV:25-3NH:3 4NJ:52-7NM:3-7,7-3NYNCPATXVAWI:7-4OH:7 4OK:37PR:7-3RI:3-3SC:7 3,3 16TN:52-25UT:52 16'~~/$^a
[..]*?\:(<[\d]+[-\ ]>+)+%\,/)[0].pick;s:g/<[567]>/{[~]
(('A'..'Z')∖<I O Q>).pick xx($/-4)}/;S:g/\d/{[~] (^10).pick xx$/}/}
```
[Try it online!](https://tio.run/##PZDPTsJAEMbvPMUeqm1l29LubjdZ/phNiVJLW2wrCG0xRMQYNRK4QAicfQIf0BepUw5eZjLf/L4vk1m/bD7c6nOPLleoWx2Up66mysCXYRqOxpngiMhUUDm7lRMpOJVJkAbToYz6cSII4p4UNideJlyD9T2o9GYIJub4Q@Ei5keCMExcTDjmJOwL26WhDwDFNqwdDPkhMAaPxsJhBokGkEqjO8Ec0MJ6gznI08gbyexxLCfgNmg8qDPiQBA@SkAgiQ8oSb36YEyQ7WZRHeGwhww6zOrpZCnzRSM3zfLquhBaJy@WZTM3ClT2mnrzosCWnrdKc/32/N7eilerkzOXlz3rkJ/KhgZfUU1Tnan67/dPx0cxuu/pZxjtdppiGVQ/Wu0UfMXybEHa3G79E4p1tI6Nqo1Wmhr6qm5uF3u0@toggKo/ "Perl 6 – Try It Online")
I was so far ahead after my first attempt, I didn't make much of an effort to pare the code down. Now I have.
In my encoding of the license plate patterns, the numbers 1-4 indicate a run of that many random digits, and the numbers 5-7 indicate of run of random permitted letters, of length four less than the number.
[Answer]
# Mathematica, ~~635~~ ~~507~~ 470 bytes
```
p=RandomChoice;a_±b_:=a<>b;r=""±Characters@"ABCDEFGHJKLMNPRSTUVWXYZ"~p~#&;j=""±ToString/@0~Range~9~p~#&;m=r@3;o=j@3;x=r@2;u=j@2;z=r@1;t=j@1;k=z±u±"-";w=m±" ";AS=y=j@4;AZ=GA=WA=m±y;CT=x±"-"±j@5;DC=x±"-"±y;FL=w±z±u;IL=x±" "±j@5;IN=p@{o±z,o±x,OK=o±m,s=m±o};CA=t±s;MD=t±x±y;MI=p@{OH=w±y,t±x±" "±z±u,AK=IA=MS=MP=VT=w±o};NV=u±z±"-"±o;NH=o±" "±y;NM=p@{MN=o±"-"±m,PR=m±"-"±o};NY=NC=PA=TX=VA=WI=m±"-"±y;RI=o±"-"±j@3;SC=p@{AR=KS=KY=LA=ND=OR=o±" "±m,VT};NJ=k±m;TN=k±u±z;UT=k±t±x;#&
```
***-165 bytes from @JungHwanMin***
**input form**
>
> [NV]
>
>
>
[Answer]
# PHP, 609 bytes
```
<?$k='9 3';$l='3 9';$m='9-4';$f=[AK=>$k,IA=>$k,MS=>$k,MP=>$k,VT=>$k,'AS'=>4,AZ=>94,GA=>94,WA=>94,AR=>$l,KS=>$l,KY=>$l,LA=>$l,ND=>$l,'OR'=>$l,CA=>193,CT=>'8-5',DC=>'8-4',FL=>'9 72',IL=>'8 5',IN=>'37X38X39X93',MD=>184,MI=>'9 31X18 72X9 3',MN=>'3-9',NV=>'27-3',NH=>'3 4',NJ=>'72-9',NM=>'3-9X9-3',NY=>$m,NC=>$m,PA=>$m,TX=>$m,VA=>$m,WI=>$m,OH=>"$k1",OK=>39,PR=>'9-3',RI=>'3-3',SC=>"$kX3 18",TN=>'72-27',UT=>'72 18'];$a=str_split(ABCDEFGHJKLMNPRSTUVWXYZ);$n=range(0,9);$p=explode(X,$f[$argv[1]]);shuffle($p);for(;$c=$p[0][$i++];){if($c<1)echo$c;else for($j=0;$j<$c%6;$j++){echo$c>5?$a[rand(0,22)]:$n[rand(0,9)];}}
```
The main idea is to encode the license plate pattern with digits that indicate how many repetitions of a digit or letter follow. 1 to 5 refer to the number of digits while 7, 8 and 9 refer to 1, 2 or 3 letters, respectively. Multiple patterns are separated by an X, spaces and dashes are kept as-is.
The state lookup is a simple array key lookup, redundant strings are put into variables to save space.
Ungolfed:
```
<?php
$f=[
AK=>'9 3',
IA=>'9 3',
MS=>'9 3',
MP=>'9 3',
VT=>'9 3',
'AS'=>4,
AZ=>94,
GA=>94,
WA=>94,
AR=>'3 9',
KS=>'3 9',
KY=>'3 9',
LA=>'3 9',
ND=>'3 9',
'OR'=>'3 9',
CA=>193,
CT=>'8-5',
DC=>'8-4',
FL=>'9 72',
IL=>'8 5',
IN=>'37X38X39X93',
MD=>184,
MI=>'9 31X18 72X9 3',
MN=>'3-9',
NV=>'27-3',
NH=>'3 4',
NJ=>'72-9',
NM=>'3-9X9-3',
NY=>'9-4',
NC=>'9-4',
PA=>'9-4',
TX=>'9-4',
VA=>'9-4',
WI=>'9-4',
OH=>'9 31',
OK=>39,
PR=>'9-3',
RI=>'3-3',
SC=>'9 3X3 18',
TN=>'72-27',
UT=>'72 18'
];
$a=str_split(ABCDEFGHJKLMNPRSTUVWXYZ);
$n=range(0,9);
$p=explode('X',$f[$argv[1]]);
shuffle($p);
for ($i = 0; $i < strlen($p[0]); $i++) {
$c=$p[0][$i];
if ($c < 1)
echo $c;
else {
for ($j = 0; $j < $c % 6; $j++){
echo $c > 5 ? $a[rand(0,22)] : $n[rand(0,9)];
}
}
}
```
[Answer]
# PHP ([Phar](http://php.net/manual/intro.phar.php)), 495 bytes
The binary Phar file can be downloaded [here](http://stiu.de/golf/uslic.phar) and can be run with `php uslic.phar <state code>`.
The base code used to generate the Phar is as follows (820 bytes):
```
<?$f=[AK=>'AAA 111',IA=>'AAA 111',MS=>'AAA 111',MP=>'AAA 111',VT=>'AAA 111','AS'=>'1111',AZ=>'AAA1111',GA=>'AAA1111',WA=>AAA1111,AR=>'111 AAA',KS=>'111 AAA',KY=>'111 AAA',LA=>'111 AAA',ND=>'111 AAA','OR'=>'111 AAA',CA=>'1AAA111',CT=>'AA-11111',DC=>'AA-1111',FL=>'AAA A11',IL=>'AA 11111',IN=>'111AX111AAX111AAAXAAA111',MD=>'1AA1111',MI=>'AAA 1111X1AA A11XAAA 111',MN=>'111-AAA',NV=>'11A-111',NH=>'111 1111',NJ=>'A11-AAA',NM=>'111-AAAXAAA-111',NY=>'AAA-1111',NC=>'AAA-1111',PA=>'AAA-1111',TX=>'AAA-1111',VA=>'AAA-1111',WI=>'AAA-1111',OH=>'AAA 1111',OK=>'111AAA',PR=>'AAA-111',RI=>'111-111',SC=>'AAA 111X111 1AA',TN=>'A11-11A',UT=>'A11 1AA'];$a=str_split(ABCDEFGHJKLMNPQRSTUVWXYZ);$n=range(0,9);$p=explode(X,$f[$argv[1]]);shuffle($p);for(;$i<strlen($p[0]);){$c=$p[0][$i++];echo$c==A?$a[rand(0,22)]:($c>0?$n[rand(0,9)]:$c);}
```
If you want to generate the Phar yourself from that code, you will need to do the following:
```
<?php
$phar = new Phar('uslic.phar', 0, 'u');
$phar->setSignatureAlgorithm(Phar::MD5);
$phar->addFile('s');
$phar['s']->compress(Phar::GZ);
$phar->setStub('<?include"phar://u/s";__HALT_COMPILER();');
```
Interestingly enough, this compresses better than [a more golfed version](https://codegolf.stackexchange.com/questions/128705/generate-a-us-license-plate/141322#141322).
The hexdump of the file is:
```
3C 3F 69 6E 63 6C 75 64 65 22 70 68 61 72 3A 2F
2F 75 2F 73 22 3B 5F 5F 48 41 4C 54 5F 43 4F 4D
50 49 4C 45 52 28 29 3B 20 3F 3E 0D 0A 30 00 00
00 01 00 00 00 11 00 00 00 01 00 01 00 00 00 75
00 00 00 00 01 00 00 00 73 34 03 00 00 26 C8 A9
59 76 01 00 00 E3 82 AE C9 B6 11 00 00 00 00 00
00 55 90 5D 6F 82 30 14 86 FF 8A 17 4D 0A B1 26
E2 9D 43 34 1D 4C 45 04 19 20 A2 84 2C 04 41 4D
0C 12 74 CB 92 65 FF 7D A5 AD A3 DC 34 7D CE C7
FB 9E 73 26 33 50 68 31 B6 B4 29 C4 18 F7 14 45
81 C8 C4 22 D9 7E 87 5C 91 C2 40 24 88 7D 48 58
A1 80 0F 2C C5 68 81 45 DA 11 E2 80 B0 C7 5A 7A
24 00 91 E5 77 68 2F D2 1A 8B E4 18 22 C1 8D 07
45 D6 69 2D F3 20 C4 C6 1C 28 CC DE D0 5B 84 68
BE E6 3B 60 BA 3B A3 1E 2F 35 1D A6 8A A3 E6 E1
2F 8E 9E C2 B6 C1 6C 58 B1 6D B6 D7 50 22 85 49
46 ED E9 B8 D6 80 CD 1F 52 A2 53 10 5A F2 E9 99
92 B3 6A 94 FE 4B ED B6 B1 91 E3 2D 7B E6 C6 D7
70 F4 0E BA B8 83 41 D4 C1 B0 9B DD 99 1D DC 2C
85 3D 08 5A FC 06 CD 2C AE D7 96 42 E4 99 7C 32
4A BE DE F6 45 74 99 A6 23 70 F8 2E 44 01 A2 6D
C0 88 E6 12 15 A4 DA FD 51 7F DC AB EB E5 21 E1
57 DD 78 9B 2F 96 2B 6B 6D 3B EE BB E7 07 DB 70
17 ED 0F B2 0A 4A AD 4E CB 53 2E 0D D1 98 50 A5
E5 DF D5 F5 76 CC A5 08 81 22 06 69 7D FA 8A 95
24 91 D5 FB F9 B3 28 AE B9 04 2A 59 2D 6E B5 A4
82 CB 84 18 5C F3 92 84 E2 21 A9 90 7F 40 A6 D1
7F 0C 2E FD 7E A2 E6 D9 F9 46 42 1A 9E 81 34 26
2E 47 62 32 1A C9 C9 8B 04 B2 E9 70 06 CA 67 70
4C 62 20 93 D5 DF 3F A0 DB 74 9C 07 ED A5 F7 4D
BA 32 97 A2 E7 9C 83 01 00 00 00 47 42 4D 42
```
[Answer]
## Clojure, ~~502~~ 501 bytes
```
#(apply str(for[E[repeatedly]c(rand-nth(cond('#{AK IA MS MP VT}%)["D 3"]('#{AR KS KY LA ND OR}%)["3 D"]('#{AZ GA WA}%)["D4"]1(case % AS["4"]CA["1D3"]CT["C-5"]DC["C-3"]FL["D B1"]IL["C 4"]IN["3B""3C""3D""D2"]MD["1C3"]MI["D 4""1C B2""D 2"]MN["3-C"]NV["2B-2"]NH["3 3"]NJ["B2-C"]NM["3-D""D-2"]OH["D 3"]OK["3C"]PR["D-2"]RI["3-2"]SC["D 3""3 1B"]TN["B2-2"]UT["B2 1B"]["D-4"])))r(cond((set"BCD")c)(E(-(int c)65)(fn[](rand-nth"ABCDEFGHJKLMNPRSTUVWXYZ")))((set"1234")c)(E(-(int c)48)(fn[](rand-int 10)))1[c])]r))
```
The input argument is a [symbol](https://clojuredocs.org/clojure.core/symbol), not a string. This let me avoid many double-quotes. `B` - `D` encode repetitions `A` - `AAA`, `1` - `4` encode repetitions `0` - `0000`.
[Answer]
# [Python 2](https://docs.python.org/2/), 438 bytes
```
import re,random
lambda s,R=range,C=random.choice:re.sub('\d',lambda c:''.join(C(['0123456789','ABCDEFGHJKLMNPRSTUVWXYZ'][c.group()>'4'])for _ in R(int(c.group())%5+1)),C("063;6-3;072;3;7 2,2 06;6-4;51-15;2-7,7-2;7 2;;7 3;;6 4;2 7;2 7;2-2;25,26,27,72;2 7;;7 3,06 51,7 2;7 2;73;;2 3;;7 51;;73;7 2;2 7;;27;2 7;;7 2;7-2;;73;;51-7;;51 06;;2-7;15-2;7 2;;7-3".split(";")["MDCASCTNMSOHILARINDMIAZNHFLWAKSOKYMPRGANJUTMNVTOR".find(s)].split(",")))
```
[Try it online!](https://tio.run/##PVFtb5swEP7Orzh5mmxrBoEJsNXKJEbWJE0gFUnbtVk0UXAaqgQQIdP661M7WfrhTvbzcj75ad66TV3xY14XEvqAEDqWu6ZuO2gla7OqqHfGNts9FxnsWdpXyItkUf/MWPmmLnN51Uprf3gm@HeB2X9xfoWx9VqXFYnIEtsOd3ueH3z9hhkOf0SDn9fD0c1kGie36Xxxd//w6/EJr5a59dLWh4bQ77iHV3Rdt/AHygpSUlYd@WDpZ@@LQymLCLJ9V/imK@yAC1cEwBkH21dQT3iO6XiCmwELTK4poZorhA89wSE4l2K4x7jPuJLxE6ZVzPbBc5g2nUrZuPYGChX6qtGTmAcXk5KZ/ETqpwPd9Sp6A@F4HyuYLrL2zbbsCBKILlE8iMJ5tEji@Ww0nobpOBnE4/ApGV1PH8LJfDZ5jG/TYZjc3C3i5H4xS5G1LquC7OnqMochSulRRWcYn2BY/pXQbSSsD1XelXUFGVTZTlqG/Cdz0DlbrWy2WS4JPoelMln3L0eHGkbTqv@GNUFJjOjxHQ "Python 2 – Try It Online")
Readable version: [Try it online!](https://tio.run/##RVJdb5swFH3nV1y5mgDVoGACbLM2iSVrkyaQLknbtes0ZcFJmMKHwNG2X59d7KA9GOF7zzk@99j1X3moSnY@50VdNRIaQaHZlFlVGMa2ykQLH4AMQp@Hjs8HEeM@j4BRBoMQS0MeeI4XcOZENHIYtgi8GoRx/PM5D2HIGUR6YZsFlIWUIZapWoeigxACjyoeKnO1kMs6gQhbvNt2VcVgUc9EGEoqniKgk6j7ds46Q9wLHC2HQJ@4bX3MpUU4sQ2jlRupR0vGo3g1WqfJajGZzuPlNB0n0/glndzMn@LZajF7Tu6Xt3F697BO0sf1YkkM4yikFI2ix59G4883t5O72TxJ75er9cPj09fnFwJXUFYwpbCg8MXI8n0udZIe84dBGL19hzqZ2IH4U2PaVmG/NwBKhBTuvqlOtWXj/vch3x6w1h@Y7xDyEcyhCeLYCtC6CNwU1amUiMxLaZU2vIEArsHDTiPkqSnBNN1fVV5a@mrd7aHKt8JS@jbsqgZ@ILW7@L2wtJhta4P1EaOyVGDKI4KLjRpGPY9vOkp3l@MUGvW9j5oS@7@DRrjt6adlvmYmvUzdv7TezkUaTz7XDU5yOZukCbHP/wA "Python 2 – Try It Online")
Note how the `states` string is only 49 letters long. I folded overlapping letters into one as much as possible (`MD` → `DC` → `CA` → `AS` → `SC`…) and omitted `NY, NC, PA, TX, VA, WI` which thus all map to `-1`.
In the list of `codes`, `12345` mean that many digits and `678` mean (that−5) many letters.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~473~~ 469 bytes
Thanks to ceilingcat for -4 bytes.
A first feeble attempt. I suspect there is a way to shorten the strings substantially.
```
n,c,d,i;f(char*s){n=0;for(s=strstr("AKnIAnMSnMPnVTnAS`AZrGArWArARfKSfKYfLAfNDfORfCAlCTtDCsFLpILmINbcdqMDkMInojMNhNViNHgNJuNMhxNYyNCyPAyTXyVAyWIyOHoOKdPRxRIaSCoeTNvUTw",s)+2;s[n]>90;n++);for(s="4 3-3 3A 3B 3C 3 1B 3 C 3 4 3-C 2A-3 1B A21B4 1BA3 B 5 C 3 C 4 C A2 C3 C4 B-4 B-5 A2-C A2-2AA2 1BC-3 C-4 "+(s[rand()%n]-96)*5,n=5;d=c=*s++,n--;)for(c>57?i=c-64,c=65:c>47?i=c-48,c=48:(i=1);i--;putchar(d))while(i&&index("IOQ",d=rand()%(c>57?26:10)+c));}
```
[Try it online!](https://tio.run/##VZJtb9owEMdfw6ewIrWySSKREFhLlk6OUdsU4jBI6dOQxhJS0rWmi9O1qOKzszvaN4uin@/O/ztfzsns@yzb7ZSVWblV@gXNVouqpdm7Ctp@sa6oDnRdwUsNPlQRV/FUxWM1SxWf/uS31RmvrnjFJ8VwWgxvihEv5KBIJoXgjyKtB0Kfjp6j0VMkf2X5n3jwO47U@iGWKzkr5fm9vHiR8epN3myk2Iz5Jr3ezPjmKtok5@tkmI8nb5NoMRXrZSr/XqavhqWZ6fr6Ts1Pjtu@Mk322aPhEXg6dgfA0QoRAkGcECDQ8lAClsvtfZi7TggxJ@QdEpIuAVUH4SG4SwR4RGDp0PYQIOGujXu2y0HghAKPFLhrmFTfVQuVU3ag5vZxj7W6lgq6fh5kQUubpqVs22fYb3bS/fKtDDK751lZ0Ov2sxPvI@AdQcA76tMycJhfQsLzS41XQnPGXlfl45KWh4elypdv1IiS74aVB59nflR1e32nzcyMMX@7K1VNnhaloqz53mxka6VrgsVIS9eLeqnv5iQg73CxhmXwCWKKuAUIjkgBAwE4HQHOMBahFUkEukPMGN4ARujGA0SEQEmMu3KGOEdcIGIEZkisLPcZY0CCkgR7SbCXMdYbozXBelMUp1g0vQZcYmuzPVB3tUdkbP1mo9nQ@5HU5dOStmEQGIKxE4rzKOGT2z4sX4nnwAr/ULMB02k8V7BdUOOHOtB9Yljkc0blHCs0Cvqfv21ud/8A "C (gcc) – Try It Online")
] |
[Question]
[
If you don't know what a queen is in chess, it doesn't matter much; it's just a name :)
Your input will be a *square* of arbitrary width and height containing some amount of queens. The input board will look like this (this board has a width and height of 8):
```
...Q....
......Q.
..Q.....
.......Q
.Q......
....Q...
Q.......
.....Q..
```
There are 8 queens on this board. If there were, say, 7, or 1, or 10 on here, the board wouldn't be valid.
Here we use a `.` for an empty space, and a `Q` for a queen. You may, alternatively, use any non-whitespace character you wish instead.
This input can be verified as valid, and you should print (or return) a truthy value (if it is was not valid, you should print (or return) a falsy value). It is valid because **no queen is in the same row, column, diagonal or anti-diagonal as another**.
## Examples (don't output things in brackets):
```
...Q....
......Q.
..Q.....
.......Q
.Q......
....Q...
Q.......
.....Q..
1
...Q.
Q....
.Q...
....Q
..Q..
0
Q.
Q.
0
..Q
...
.Q.
0 (this is 0 because there are only 2 queens on a 3x3 board)
..Q.
Q...
...Q
.Q..
1
Q
1 (this is valid, because the board is only 1x1, so there's no queen that can take another)
```
Let me stress that an input is only valid, if **no queen is in the same row, column, diagonal or anti-diagonal as another**.
### Rules
* You will never receive an empty input
* If the input contains fewer queens than the sqaure root of the area of the board, it is not valid.
* Note there are no valid solutions for a 2x2 or 3x3 board, but there is a solution for every other size *square* board, where the width and height is a natural number.
* The input may be in any reasonable format, as per PPCG rules
* The input will always be a sqaure
* I used 1 and 0 in the examples, but you may use any truthy or falsy values (such as `Why yes, sir, that is indeed the case` and `Why no, sir, that is not the case`)
As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code wins!
[Answer]
## [Snails](https://github.com/feresum/PMA), 14 bytes
```
&
o.,\Q!(z.,\Q
```
[Try it online!](https://tio.run/nexus/snails#@6/Gla@nExOoqFEFov7/19PTCwRiPS49MAgEMcACMBG9QC6oAEQExOaCCkDVAHkA "Snails – TIO Nexus")
Nothing like a 2D pattern matching language for a 2D decision problem. :)
### Explanation
The `&` on the first line is a match mode option which requires the pattern on the second line to match from every possible position in the input. If that's the case, the program prints `1`, otherwise it prints `0`.
As for the pattern itself, note that there's an implicit `)` at the end.
```
o ,, Move in any orthogonal direction (up, down, left or right).
.,\Q ,, Make sure that there's a Q somewhere in that direction from the
,, starting position of the match.
!( ,, After finding the Q, make sure that the following part _doesn't_ match:
z ,, Move in any orthogonal or diagonal direction.
.,\Q ,, Try to find another Q in a straight line.
)
```
Why this works is easiest to see by starting from the negative lookahead: by ensuring that there is no `Q` in a straight line from the other `Q` we've already found, we make sure that there are no more than **N** queens (otherwise, there would have to be two in one row, and it wouldn't be possible to find these queens without finding another). Then the first part, making sure that there's a queen reachable in an orthogonal direction from any position, makes sure that there are exactly **N** queens. If one was missing, there would be a row and a column without a queen. Starting from the intersection of these, it wouldn't be possible to find a queen by going only in an orthogonal direction.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 or 15 bytes
```
ỴµUŒD;ŒD;ZVṀ;V=1Ṃ
```
[Try it online!](https://tio.run/nexus/jelly#@/9w95ZDW0OPTnKxBuGosIc7G6zDbA0f7mz6////oZ0g@KhhBoRxaCcXjAEX50JTgaYGLMeFpgJJDVycC00FijlQOQA "Jelly – TIO Nexus")
Uses `‘` for a queen and `¹` for blank space. (This is mostly a consequence of the ban on taking input as an array, because it forces the input to be strings; converting strings to integers is difficult in Jelly, with the easiest method being evaluation, and it turns out that instead of 1 and 0, using "add 1" (`‘`) and "add 0" (`¹`) make it possible to omit several sum and map instructions, because we can count the queens in a list by evaluating it.) The truthy and falsey values are Jelly's normal `1` and `0`.
EDIT: The question's been changed since I wrote this answer to allow taking input as a matrix. This allows dropping the leading `Ỵµ`, saving 2 bytes. It also probably allows changing the input format to something more normal, using `S` to sum rather than `V` to evaluate, but I don't think that saves bytes and I kind-of like this funky format.
## Explanation
```
ỴµUŒD;ŒD;ZVṀ;V=1Ṃ
Ỵ Split on newlines.
µ Set this value as the default for missing arguments.
; ; Concatenate the following three values:
UŒD - the antidiagonals;
ŒD - the diagonals;
Z - and the columns.
V Evaluate (i.e. count the queens on) all of those.
Ṁ Take the largest value among the results.
;V Append the evaluation (i.e. queen count) of {each row}.
=1 Compare each value to 1.
Ṃ Take the minimum (i.e. most falsey) result.
```
So the basic idea is that we ensure that there's at most one queen on each antidiagonal, diagonal, and column; and exactly one queen on each row. These conditions are together enough to require that there's at most one queen on each of the four sorts of line, and a number of queens equal to the side length of the board.
Incidentally, Jelly could probably do with a built-in for antidiagonals, but AFAICT it doesn't seem to have one, so I need to settle for reflecting the board and then taking the diagonals.
Another interesting note is that changing `=1Ṃ` to `E` (all equal) gives a generalized *n*-queens checker, which will also accept an *n*×*n* board where each row, column, diagonal, and antidiagonal contains no more than *k* queens, and the board contains exactly *kn* queens. Restricting *k* to equal 1 actually cost two bytes.
[Answer]
# Octave, ~~57~~ ~~70~~ ~~67~~ ~~51~~ 52 bytes
Saved 1 byte using `flip` instead of `rot90` thanks to @LuisMendo, but found a bug on the 1x1 case
```
@(A)all(sum([A A' (d=@spdiags)(A) d(flip(A))],1)==1)
```
Takes input as a binary matrix with 1 representing a Queen and 0 representing an empty space.
Creates an anonymous function that first concatenates the input matrix and its transpose.
`spdiags` creates a matrix with the same number of rows as the argument, with the diagonals turned into columns (zero-padded as necessary), so concatenate `spdiags` of the input matrix to get the diagonals and `spdiags` of the matrix flipped horizontally to get the antidiagonals.
Now take the sum of each column of the concatenated matrix and make sure each column is exactly 1.
Sample run on [ideone](https://ideone.com/5YWdHT).
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~38~~ 34 bytes
*4 bytes off thanks to [@beaker](https://codegolf.stackexchange.com/users/42892/beaker)!*
```
sG!sGt&n_w&:&XdsGP5M&Xdsv2<GnGzU=*
```
The input is a 2D array of zeros and ones, using semicolons as row separators.
This outputs a column vector of ones as truthy, and a column vector containing at least one zero as falsy.
[Try it online!](https://tio.run/nexus/matl#@1/srljsXqKWF1@uZqUWkVLsHmDqC6LLjGzc89yrQm21/turlxSVlmRUqteqpyXmFFeq/482UABBQwUIbWBtoICAhlC@IUIMRR4oY40iiyQPFbVGkUXRD5aJBQA) The footer code is an `if` branch to demonstrate truthiness or falsyhood.
Or [verify all test cases](https://tio.run/nexus/matl#S4jw@l/spVjsVaKWF1@uZqUWkVLsFWDqC6LLjGy88ryqQm21/turlxSVlmRUqteqpyXmFFeqc8W6hPyPNlAAQUMFCG1gbaCAgIZQviFCDEUeKGONIoskDxW1RpFF0Q@WieVCuMAa2RWG6OZZI@uBqobqhshBdcHEEOZZo7kVpD8WAA).
### Explanation
```
s % Input binary matrix implicitly. Sum of columns. Gives a row vector
G! % Paste input again. Transpose
s % Sum of columns (rows in the original matrix). Gives a row vector
G % Paste input again
t&n % Duplicate. Push number of rows and number of columns (will be equal)
_w % Negate, flip
&: % Binary range. Gives [-n -n+1 ... n] for input of size n×n
&Xd % Get diagonals -n through n. This gives all diagonals as colums
s % Sum of each column (diagonals of original matrix). Gives a row vector
GP % Paste input again. Flip vertically
5M % Push [-n -n+1 ... n] again
&Xd % Get diagonals -n through n (anti-diagonals of original matrix)
s % Sum of each column. Gives a row vector
v % Concatenate everything into a column vector
2< % True for elements that are less than 2
Gn % Paste input again. Number of elements
Gz % Paste input again. Number of nonzeros (i.e. of queens)
U % Square
= % True if equal
* % Mutiply, element-wise
```
[Answer]
# [SnakeEx](http://www.brianmacintosh.com/snakeex/), 67 bytes
```
m:({q<>}({q<R>}[{q<RF>}{n<RF>}].)*{e<>}<R>)%{4}
e:.$
q:_*Q_*$
n:_+$
```
Uses `_` in place of `.` in the input. Returns 1 or more matches for truthy, 0 matches for falsey. You can find an online interpreter at the link in the header.
### Explanation
SnakeEx is a language from the [2-D Pattern Matching challenge](https://codegolf.stackexchange.com/q/47311/16766). It defines "snakes" that move around the grid matching stuff. Snakes can spawn other snakes, making the language quite powerful.
Let's look at this program from the bottom up.
```
n:_+$
```
This defines a snake `n` that matches 1 or more underscores and then the edge of the grid. Note that this may be in any of the 8 cardinal directions--the direction is determined when the snake is spawned.
```
q:_*Q_*$
```
Similar to `n` above, this defines `q` as a snake that matches any number of underscores, a single `Q`, any number of underscores, and the edge of the grid. In other words, a row/column/diagonal that has only one queen in it.
```
e:.$
```
`e` is a snake that matches one character and the edge of the grid.
```
m:({q<>}({q<R>}[{q<RF>}{n<RF>}].)*{e<>}<R>)%{4}
```
The main snake `m` uses these building blocks to check the whole board. Conceptually, it runs around the outside edges of the grid, spawning other snakes to check that all columns and rows have exactly one queen, and all diagonals have at most one queen. If any of the spawned snakes fails to match, the entire match fails. Let's break it down.
* `( )%{4}` runs what's inside the parentheses 4 times, once for each side. (In what follows, it's helpful to picture a particular side--say, the top edge of the grid, starting from the top left corner and moving right.)
* `{q<>}` spawns a `q` snake in the same direction that the main snake is moving. This verifies that the current edge meets the "exactly one queen" rule. Note that spawned snakes do not move the main snake's match pointer, so we're still at the beginning of the edge.
* `( )*` matches 0 or more of what's inside the parentheses.
* `{q<R>}` spawns a `q` snake turned rightward from the main snake's direction. (E.g. if the main snake is moving rightward along the top edge, this snake moves downward.) This checks each column/row.
* `[ ]` matches either one of the options inside the brackets:
+ `{q<RF>}` spawns a `q` snake turned 45 degrees rightward (i.e. `R`ight and `F`orward) from the main snake's direction. The `q` snake matches if the diagonal contains exactly one queen.
+ `{n<RF>}` spawns an `n` snake instead. The `n` snake matches if the diagonal contains no queens.
* `.` matches any character, moving the match pointer forward.
* After checking as many horizontals and diagonals as possible, we verify that we're at the edge by spawning `{e<>}`.
* Finally, `<R>` turns the main snake right, ready to match the next edge.
### Weird stuff
* There's nothing in the program to ensure that matching starts at an outside corner. In fact, the truthy test cases yield several matches, some of which start on the inside somewhere. Despite this, none of the falsey cases I've tried have generated any false positives.
* If I'm reading the [language spec](http://www.brianmacintosh.com/snakeex/spec.html) right, I should have been able to use `X` (branch in all diagonal directions) in place of `RF`. Unfortunately, the online interpreter said that was a syntax error. I also tried `*` (branch in all directions), but that hung the interpreter.
* Theoretically, something like `_*Q?_*$` ought to work for matching "at most one queen" in the diagonals, but that also hung the interpreter. My guess is that the possibility of empty matches causes problems.
[Answer]
# [J](http://jsoftware.com/), 37 bytes
```
(+/&,=#)*1=[:>./+//.,+//.&|.,+/,+/&|:
```
Anonymous function train which takes Boolean matrix as argument.
[Try it online!](https://tio.run/nexus/j#@59ma6Whra@mY6usqRVtpa2nr62vr6cDItRqQDQQqdVY/Xe0tTJRMFExUDBQMIRiBISL/HfkSlNwBAA "J – TIO Nexus")
`(` `+/` the sum `&` of `,` the ravel `=` equals `#` the tally of rows `)`
`*` and (lit. times)
`1` one `=` equals `[:` the `>./` maximum of
`+/` the sums `/.` diagonally `,` and (lit. catenated to)
`+/` the sums `/.` diagonally `&` of `|.` the reverse `,` and
`+/` the sums across `,` and
`+/` the sums `&` of `|:` the transpose
[Answer]
# Ruby, 120 bytes
Lambda function based on the original spec that required input as a string.
```
->s{t=k=0
a=[]
s.bytes{|i|i>65&&(a.map{|j|t&&=((k-j)**4).imag!=0};a<<k)
k=i<11?k.real+1:k+?i.to_c}
t&&~a.size**2>s.size}
```
converts the Q's into complex numbers and subtracts them from each other. If the difference between the coordinates of any two queens is horizontal, vertical or diagonal, raising it to the 4th power will yield a real number and the arrangement is invalid.
**Ungolfed in test program**
```
f=->s{ #Take input as string argument.
t=k=0 #k=coordinate of character. t=0 (truthy in ruby.)
a=[] #Empty array for storing coordinates.
s.bytes{ #Iterate through all characters as bytes.
|i|i>65&&( #If alphabetical, compare the current value of k to the contents of a
a.map{|j|t&&=((k-j)**4).imag!=0} #If k-j is horizontal, vertical or diagonal, (k-j)**4 will be real and t will be false
a<<k) #Add the new value of k to the end of a.
k=i<11?k.real+1:k+?i.to_c #If not a newline, increment the imaginary part of k. If a newline, set imaginary to 0 and increment real
} #s.size should be a*a + a newlines. ~a.size = -1-a.size, so ~a.size**2 = (a.size+1)**2
t&&~a.size**2>s.size} #compare a.size with s.size and AND the result with t. Return value.
p f["...Q....
......Q.
..Q.....
.......Q
.Q......
....Q...
Q.......
.....Q.."]
p f["...Q.
Q....
.Q...
....Q
..Q.."]
p f["Q.
Q."]
p f["..Q
...
.Q."]
p f["..Q.
Q...
...Q
.Q.."]
p f["Q"]
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~232~~ ~~200~~ 155 bytes
```
d=1
f=input()
Q=[]
for i in f:d=[0,d][i.count('Q')==1];Q+=[(len(Q),i.index('Q'))]
print[0,d][sum(k[1]==i[1]or sum(k)==sum(i)for k in Q for i in Q)==len(Q)]
```
[Try it online!](https://tio.run/##PY1BjsMgDEX3nIIdoImspsuOfAjWlEVmSFSrKaCUSDOnTw1Ji2RsP9v/5/9yS/G8UcxrkSjn4fEThotMeYxaQcNQKKlOLcrAMg5BG3jmmYpW16jMFrAXE7ZFbYRF58WUFkmSopwuAd2pC94R/KY18o1VBrH33/YLnZ7ZxJqO2CeMf21ovMgLxbKfPdeHvrveIxL/LNsAK9RMphrdq5GVH0/L013XbxsAWA4Q0J6tRQNvAlYcYCe1Fgc4drh7AQ "Try It Online")
-32 bytes thanks to @beaker noticing a change in the input specifications; I have changed the language from Python 3 to 2, thus allowing for me to use `input` to take input as an array of strings or an array of character arrays.
-45 bytes thanks to @Leaky Nun
[Answer]
## JavaScript (ES6), 115 bytes
```
a=>!a.some((b,i)=>b.some((q,j)=>q&&h[i]|v[j]|d[i+j]|e[i-j]|!(h[i]=v[j]=d[i+j]=e[i-j]=1))|!h[i],h=[],v=[],d=[],e=[])
```
Ungolfed:
```
function queens(arr) {
horiz = [];
vert = [];
diag = [];
anti = [];
for (i = 0; i < arr.length; i++) {
for (j = 0; j < arr.length; j++) {
if (arr[i][j]) { // if there is a queen...
if (horiz[i]) return false; // not already on the same row
if (vert[j]) return false; // or column
if (diag[i + j]) return false; // or diagonal
if (anti[i - j]) return false; // or antidiagonal
horiz[i] = vert[j] = diag[i + j] = anti[i - j] = true; // mark it
}
}
if (!horiz[i]) return false; // fail if no queen in this row
}
return true;
}
```
[Answer]
# Ruby, 155 bytes
```
->x{(y=x.map{|r|(i=r.index ?Q)==r.rindex(?Q)?i:p or-2}).zip(y.rotate).map.with_index{|n,i|n.max-n.min==1&&i<y.size-1?-2:n[0]}.inject(:+)*2==(s=x.size)*~-s}
```
This is horrible to read, so I've got a slightly less golfed version below
```
->x{
(y=x.map{|r|(i=r.index ?Q)==r.rindex(?Q)?i:p or-2})
.zip(y.rotate)
.map.with_index{|n,i|n.max-n.min==1&&i<y.size-1?-2:n[0]}
.inject(:+)*2==(s=x.size)*~-s
}
```
This is the same code, but with some newlines to separate out what's happening.
The code tself is an anonymous lambda function which takes an array of strings (`x`) in the format `["..Q", "Q..", ".Q."]`.
The first line is mapping each string to the index of the Q character in that string. If there is no Q character, it's replaced with -21. This new array of indices is assigned to the variable `y`.
The next line zips this array of indices with itself offset by one (rotated). This results in an array of pairs of consecutive indices.
The next line is particularly complicated. It goes through each of the pairs of indices, and subtracts the smaller from the larger. If this is 1 (and we're not at the last pair2), then there are two queens that are on the same diagonal, and a value of -2 is inserted, otherwise the original index of the queen in the string is inserted.
The last line sums up all the indexes for each and checks to see if it is the triangle number for n-1, where n is the width (or height) of the square.
1: -1 would have been my go-to, but it's 1 apart from 0, so would mess with the checking of diagonals. The negative-ness of it is important to make the final sum wrong. I thought about a high number (with single digits) like 9, but I can't be sure that won't result in an incorrect verification.
2: The board doesn't wrap round, whereas ruby's `rotate` array function does, and if the last pair is different by one it doesn't matter - that's not a diagonal.
[Answer]
# PHP, ~~137~~ 143 bytes
inspired by [Neil´s solution](https://codegolf.stackexchange.com/a/112366/55735)
```
for($n=1+strlen($s=$argv[1])**.5|0;($c=$s[$p])&&!(Q==$c&&$v[$x=$p%$n]++|$h[$x=$p/$n]++|$d[$y-$x]++|$a[$y+$x]++);$p++);echo$n-1==count($a)&&!$c;
```
takes input from first command line argument; run with `-r`. Requires single byte line breaks.
Actually you can use any character but `0` for the line break.
**breakdown**
```
for($n=1+strlen($s=$argv[1])**.5|0; // copy input to $s, $n=size+1 (for the linebreak)
($c=$s[$p])&&!( // loop through characters
Q==$c&& // if queen: test and increment lines
$v[$x=$p%$n]++|$h[$x=$p/$n]++|$d[$y-$x]++|$a[$y+$x]++
); // break if a line had been marked before
$p++);
echo$n-1==count($a) // print result: true for $n-1(=size) marks
&&!$c; // and loop has finished
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~185~~ ~~176~~ ~~175~~ ~~172~~ 171 bytes
```
lambda x,c=lambda x:x.count("Q")==1:all([*map(c,x+[[l[i]for l in x]for i in range(len(x[0]))])])*~any(map(lambda s:"Q%sQ"%(s*".")in"".join(x),[len(x[0]),len(x[0])-2]))==-1
```
An anonymous function taking a list of strings as input.
[Python 2](https://docs.python.org/2/), 175 bytes
```
lambda x:all([a.count("Q")==1for a in x]+[[l[i]for l in x].count("Q")==1for i in range(len(x[0]))]+[all(map(lambda s:"Q%sQ"%(s*".")not in"".join(x),[len(x[0]),len(x[0])-2]))])
```
] |
[Question]
[
Your challenge is to write a program or function that hiccups a string. It should take a string as input (via any standard method), then follow these steps:
1. Generate a (not necessarily uniformly) random integer **n** between 1 and 10, inclusive.
2. Wait **n** seconds.
3. Print the initial/next **n** chars of the input, or the rest of the input if there are less than **n** chars.
4. If there is input left to print, go back to step 1.
# Rules
* The input will always be a non-empty string containing only ASCII chars (32-126).
* The wait time does not have to be exactly **n** seconds, but it must be within 10% of **n**.
* You may print a trailing newline each time a section of text is printed.
# Example
A space here represents 1 second. If the input is `Hiccupinator!`, an output might be:
```
Hic cupin a tor!
```
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so **the shortest code in bytes wins**.
[Answer]
# Scratch, 16 blocks + 6 bytes
[](https://i.stack.imgur.com/IUcDI.png)
Assumes input is already defined as a list of characters (`["H","e","l","l","o"," ","W","o","r","l","d"]`)
[Answer]
# [Pushy](https://github.com/FTcode/Pushy), ~~20~~ ~~17~~ 16 or 13 bytes
Depending on what's allowed, there are two solutions.
## 16 bytes:
```
@$LT1U&Wm:v;O"cI
```
Give arguments on the command line: `$ pushy hiccup.pshy 'hiccupinator'`. This prints with trailing newlines after each 'hiccup'. Here's the breakdown:
```
% Implicit: input on stack as charcodes
@ % Reverse input, so chars are pulled from start
$ I % While there are items on stack:
T1U % Push a random number, 1-10
&W % Wait that many seconds
L m: % min(time waited, chars left) times do:
v; % Pull a char from the input.
O"c % Print & delete pulled chars
```
## 13 bytes:
While coding the above answer I came up with this significantly shorter solution:
```
N@$L1TU&Wm:'.
```
Although it does a similar thing, it prints directly off the string rather than constructing a new string, for fewer bytes. This requires the `N` at the beginning of the program to prevent trailing newlines, or else each character would be on a newline.
However, whilst testing this I noticed a bug - `stdout` is line-buffered, so the program would wait the full length, and then display the hiccuped string.
I've fixed this in [the latest commit](https://github.com/FTcode/Pushy/commit/ab45f9b785db814b6cfdf45090f41fb46636e440) by adding a simple `.flush()` - this is technically not adding a new feature to the language, just fixing a bug, but I understand if you don't take this answer into account :)
The breakdown looks like this:
```
% Implicit: input on stack as charcodes
N % Set trailing newlines to False
@ % Reverse stack (so the charcodes are pulled off in order)
$ % While there are items left to print:
L % Push stack length
1TU % Push a random number 1-10
&W % Wait that amount of time
m: % min(time waited, chars left) times do:
'. % Pop and print last char
```
[Answer]
## Javascript (ES6) ~~91~~ 89 Bytes
```
f=s=>s&&setTimeout(_=>console.log(s.slice(0,n))|f(s.slice(n)),(n=1+Math.random()*10)<<10)
console.log(2 + f.toString().length);
f('Hello sweet world!')
```
*saved 2 bytes thanks to @zeppelin*
Abuses the 10% tolerance for the wait time by waiting `n<<10 === 1024*n` milliseconds.
~~Since you said that the wait time needs to be within 10% of **n**, I decided to save one byte and wait for 999 milliseconds rather than 1 second.~~
*I don't need the 999 millisecond silliness anymore thanks to @ETHProductions*
[Answer]
# Python 2, ~~93~~ 92 bytes
```
import random,time
def F(s):
if s:n=random.randint(1,10);time.sleep(n);print s[:n];F(s[n:])
```
*-1 byte thanks to Flp.Tkc*
I'm sure there is a way to shorten the `random.randint` and `time.sleep`, but `from random,time import*` doesn't work...
[Answer]
# [Perl 6](https://perl6.org), 62 bytes
```
{$_=$^a;while $_ {sleep my \t=(1..10).roll;put s/.**{0..t}//}}
```
## Expanded
```
{ # block lambda with parameter 「$a」
$_ = $^a; # declare parameter, and store it in 「$_」
# ( the input is read-only by default )
while $_ {
# generate random number and sleep for that many seconds
sleep my \t=(1..10).roll;
put
s/ # substitution on 「$_」 ( returns matched text )
. ** { 0..t } # match at most 「t」 characters
// # replace it with nothing
}
}
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 28 bytes
```
q{Amr)__e3es+{_es>}g;2$<o>}h
```
[Try it online!](https://tio.run/##S85KzP3/v7DaMbdIMz4@1Ti1WLs6PrXYrjbd2kjFJt@uNuP/f4/UnJx8HYXw/KKcFEUA "CJam – Try It Online") Or actually, don't. The effect doesn't really show up in any online interpreter, so [try it on the Java interpreter](https://sourceforge.net/p/cjam) instead.
Turns out, CJam has an operator that gets the current Unix timestamp. This program waits by entering a while loop until the timestamp passes the correct value.
[Answer]
## Batch, 131 bytes
```
@set/ps=
:l
@set/an=%random%%%10+1
@timeout/t>nul %n%
@call echo(%%s:~0,%n%%%
@call set s=%%s:~%n%%%
@if not "%s%"==2" goto l
```
Using `set/pn=<nul` would have given a nicer effect except that it trims spaces.
[Answer]
# Pyth, 16 bytes
```
Wz.d_JhOT<zJ=>zJ
```
You can [try it online](http://pyth.herokuapp.com/?code=Wz.d_JhOT%3CzJ%3D%3EzJ&input=Hiccupinator%21&debug=0), but it doesn't work well since the online interpreter only displays the output once the program has finished.
### Explanation
```
Wz While z (the input) is not empty:
hOT Get a random number between 1-10 (inclusive)
J Set the variable J to that number
.d_ Sleep for that number of seconds
<zJ Get and implicitly print the first J characters of the input
>zJ Get all characters of z at and after index J
= Set z to that string
```
[Answer]
# [MATL](http://github.com/lmendo/MATL), 19 bytes
```
`10YrtY.ynhX<:&)wDt
```
### How it works
[Try it online!](http://matl.tryitonline.net/#code=YDEwWXJ0WS55bmhYPDomKXdEdA&input=J0hpY2N1cGluYXRvciEn) The online compiler does gradually produce the outputs with the pauses.
```
` % Do...while loop
10Yr % Random integer from 1 to 10
tY. % Duplicate. Pause that many seconds
y % Duplicate the second-top element. This is the remaining string; or it
% takes the input implicitly in the first iteration
n % Number of elements
hX< % Minimum of the number of elements and the random number
: % Range from 1 to that
&) % Apply as index. Push the substring as given by the index and the
% remaining substring
w % Swap
D % Display
t % Duplicate the remaining substring. This is used as loop condition:
% if non-empty execute next iteration
% End loop implicitly
```
[Answer]
# **[BaCon](http://www.basic-converter.org), 93 bytes**
A solution in BASIC. The RANDOM() function generates a number between 0 and n-1, therefore we have to use RANDOM(11) to get a number between 0 and 10 inclusive.
```
INPUT s$
WHILE LEN(s$)>0
n=RANDOM(11)
SLEEP n*1000
?LEFT$(s$,n),SPC$(n);
s$=MID$(s$,n+1)
WEND
```
Sample session, first line is the input, second the output:
```
Hiccupinator!
Hiccupi nato r!
```
[Answer]
## Perl, 42 bytes
**41 bytes code + 1 for `-n`.**
```
$|=$-=--$-||sleep 1+rand 10,print for/./g
```
I had to force Perl to flush output as it wasn't showing anything 'til the end at first, hence setting `$|`. We use `$-` to track the number of characters to `print` as this cannot be negative (so I can use `--$-` and it'll sill be falsy when it's empty) and it also `floor`s, although since I'm using the return of `sleep` for this now, that doesn't really matter.
### Usage
```
perl -ne '$|=$-=--$-||sleep 1+rand 10,print for/./g' <<< 'Hello, World!'
Hell o, Wor ld!
# spaces showing delay!
```
[Answer]
# Ruby, 56 bytes
```
f=->s{n=sleep rand 1..10;print s.slice!0,n;f[s]if s!=""}
```
A recursive lambda. Call like `f["Hello, World!"]`.
[Answer]
# ><> (Fish) ~~103~~ 88 Bytes
```
5>:?vl1-?!v+40. >~
1x2v
>^ 0 |:!/>:?!v1-b2.
^-1}< < |~!/:?!^1-i:1+?!;of3.
```
[Online interpreter found here!](https://fishlanguage.com/playground)
First attempt at this problem (not golfed).
It waits a certain amount of loops(n) as fish doesn't have a timer that is accessible (Execution in ticks).
Edit 1: Moved last line across to the top (last 2 characters and re-used the starting values. (saving of 15 bytes).
[Answer]
# Bash, 78 bytes
As nobody has posted a Bash solution yet, here is one.
Straightforward, yet small enough.
**Golfed**
```
H() { N=$(($RANDOM%10+1));sleep $N;echo ${1:0:$N};S=${1:$N};[ "$S" ] && H $S;}
```
**Test**
```
>H "It's the Hiccupinator"
It's the
Hiccupi
n
ator
```
[Answer]
# PHP, 81 bytes
```
for(;''<$s=&$argv[1];$s=$f($s,$n))echo($f=substr)($s,0,sleep($n=rand(1,10))?:$n);
```
use like:
```
php -r "for(;''<$s=&$argv[1];$s=$f($s,$n))echo($f=substr)($s,0,sleep($n=rand(1,10))?:$n);" "Hiccupinator!"
```
[Answer]
# C++14, 202 bytes
```
#import<thread>
void f(auto c){if(c.size()<1)return;int n=(uintptr_t(&c)%99)/10+1;std::this_thread::sleep_for(std::chrono::seconds(n));std::cout<<c.substr(0,n)<<std::endl;f(n<c.size()?c.substr(n):"");}
```
Requires input to be a `std::string`
Ungolfed and usage:
```
#include<iostream>
#include<string>
#import <thread>
void f(auto c){
if (c.size() < 1) return;
int n=(uintptr_t(&c) % 99) / 10 + 1;
std::this_thread::sleep_for(std::chrono::seconds(n));
std::cout << c.substr(0,n) << std::endl;
f(n < c.size() ? c.substr(n) : "");
}
int main(){
std::string s="abcdefghijklmnopqrstuvwxyz";
f(s);
}
```
[Answer]
# **C#, 205 bytes**
```
void X(string s){Random r=new Random();int n=r.Next(1,11);while(n<s.Length){Console.WriteLine(s.Substring(0,n));s.Remove(0,n);n*=1000;System.Threading.Thread.Sleep(n);n=r.Next(1,11);}Console.WriteLine(s);}
```
I'm sure this can be destroyed, I haven't really optimised it at all as it stands.
Un-golfed:
```
void X(string s)
{
Random r = new Random();
int n = r.Next(1,11);
while(n < s.Length)
{
Console.WriteLine(s.Substring(0,n));
s.Remove(0,n);
n *= 1000;
System.Threading.Thread.Sleep(n);
n = r.Next(1,11);
}
Console.WriteLine(s);
}
```
[Answer]
# PHP, 74 bytes
```
for($s=$argv[1];$s[$p+=$n]>"";print substr($s,$p,$n))sleep($n=rand(1,10));
```
Run with `php -r 'code' "string"`.
[Answer]
# C, 149 bytes, not tested
```
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int f(char *s){int n;while(*s){sleep(n=rand()%10+1);for(;*s&&n--;s++)printf("%.*s",1,s);}}
```
to run, add
```
int main(){f("Programming Puzzles & CodeGolf");}
```
then compile and execute
[Answer]
# Python 3, 99 chars
```
i=input()
import os,time
while len(i):n=1+ord(os.urandom(1))%10;time.sleep(n);print(i[:n]);i=i[n:]
```
[Answer]
# [Assembly (NASM, 32-bit, Linux)](https://www.nasm.us/), 278 bytes
The signature is `void f(char* msg, int len)`. The standard x86 calling convetion is used. Therefore, `msg` is in `ecx`, and `len` is in `edx`. The random number is generated as `time(0)%10+1`.
```
f:push ebx
mov esi,ecx
mov edi,edx
push 0
l:mov ebx,0
mov eax,13
int 128
mov edx,0
mov ecx,10
div cx
inc dx
push edx
mov cx,0
mov ebx,esp
mov eax,162
int 128
pop edx
cmp edx,edi
cmova dx,di
mov ecx,esi
mov ebx,1
mov ax,4
int 128
add esi,edx
sub edi,edx
jnz l
pop eax
pop ebx
ret
```
[Try it online!](https://jdoodle.com/a/2sTd)
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), 109 bytes
```
#include<unistd.h>
int f(char*s){for(int n,m=0;*s;)for(sleep(m=n=(getpid()+m)%10+1);*s&&n--;)write(1,s++,1);}
```
[Try it online!](https://tio.run/##FcxBDoMgEEDRfU9hbWoGkUbW1q57DQOjksBIAMOi6dVLdfvy85X3YlGqlJshZXeNz51MTPqxvi6GUjWDWqfQRvaZtwCnUOfGfmjjwE6JFtGDG2mEBZM3Ghh37C57LtkRNQ0JMbAcTEKQXeS8O/xb3GQIjifUb7R2q2JGTFXegtXX@gx@arbTEovIfw "C++ (gcc) – Try It Online")
*-10 bytes thanks to **ceilingcat***
*-8 bytes thanks to **ceilingcat***
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 71 bytes
```
n;f(char*s){while(*s)for(sleep(n=time(0)%10+1);*s&&n--;)putchar(*s++);}
```
[Try it online!](https://tio.run/##FctBCoMwEEDRq1ihMmMI6Dp032uEdKKBMZFMJAvp1Zvq7i/ed3pxrrVoPLjV5lHwrGtggqt8yiBMtEN8lbARTPicJzWjGWUYotYG96Pc26WVQvNtmw0R8PTQv4k5dVKJSldT5s@jv8HPebaLNF3/ "C (gcc) – Try It Online")
*-1 byte thanks to **ceilingcat***
] |
[Question]
[
# Challenge description
Let's start with some definitions:
* a **relation** is a set of ordered pairs of elements (in this challenge, we'll be using integers)
For instance, `[(1, 2), (5, 1), (-9, 12), (0, 0), (3, 2)]` is a relation.
* a relation is called **transitive** if for any two pairs of elements `(a, b)` and `(b, c)` in this relation, a pair `(a, c)` is also present,
* `[(1, 2), (2, 4), (6, 5), (1, 4)]` is transitive, because it contains `(1, 2)` and `(2, 4)`, but `(1, 4)` as well,
* `[(7, 8), (9, 10), (15, -5)]` is transitive, because there aren't any two pairs
`(a, b)`, `(c, d)` present such that `b` = `c`.
* `[(5, 9), (9, 54), (0, 0)]` is not transitive, because it contains `(5, 9)` and `(9, 54)`, but not `(5, 54)`
Given a list of pairs of integers, determine if a relation is transitive or not.
# Input / output
You will be given a list of pairs of integers in any reasonable format. Consider a relation
`[(1, 6), (9, 1), (6, 5), (0, 0)]`
The following formats are equivalent:
```
[(1, 6), (9, 1), (6, 5), (0, 0)] # list of pairs (2-tuples)
[1, 9, 6, 0], [6, 1, 5, 0] # two lists [x1, x2, ..., xn] [y1, y2, ..., yn]
[[1, 6], [9, 1], [6, 5], [0, 0] # two-dimentional int array
[4, 1, 6, 9, 1, 6, 5, 0, 0] # (n, x1, y1, ..., xn, yn)
[1+6i, 9+i, 6+5i, 0+0i] # list of complex numbers
... many others, whatever best suits golfing purposes
```
Output: a truthy value for a transitive relation, falsy otherwise. You may assume that the input will consist of at least one pair, and that the pairs are unique.
[Answer]
## Haskell, 42 bytes
```
f x=and[elem(a,d)x|(a,b)<-x,(c,d)<-x,b==c]
```
Usage example: `f [(1,2), (2,4), (6,5), (1,4)]`-> `True`.
(Outer)loop over all pairs `(a,b)` and (inner)loop over the same pairs, now called `(c,d)` and every time when `b==c` check if `(a,d)`is also an existent pair. Combine the results with logical `and`.
[Answer]
## Prolog, 66 bytes
```
t(L):-not((member((A,B),L),member((B,C),L),not(member((A,C),L)))).
```
The relation is *not* transitive if we can find (A,B) and (B,C) such that (A,C) doesn't hold.
[Answer]
# [MATL](http://github.com/lmendo/MATL), ~~27~~ 25 bytes
```
7#u2e!l6MX>thl4$XQttY*g<~
```
Input format is a matrix (using `;` as row separator) where each pair of the relation is a column. For example, test cases
```
[(1, 2), (2, 4), (6, 5), (1, 4)]
[(7, 8), (9, 10), (15, -5)]
[(5, 9), (9, 54), (0, 0)]
```
are respectively input as
```
[1 2 6 1; 2 4 5 4]
[7 9 15; 8 10 -5]
[5 9 0; 9 54 0]
```
[Truthy](http://matl.tryitonline.net/#code=PyAgICAgICAgICUgaWYKJ3RydXRoeScgICUgcHVzaCBzdHJpbmcKfSAgICAgICAgICUgZWxzZQonZmFsc3knICAgJSBwdXNoIHN0cmluZw&input=WzEgMSAxOyAxIDEgMTsgMSAxIDFd) output is a matrix formed by ones. [Falsy](http://matl.tryitonline.net/#code=PyAgICAgICAgICUgaWYKJ3RydXRoeScgICUgcHVzaCBzdHJpbmcKfSAgICAgICAgICUgZWxzZQonZmFsc3knICAgJSBwdXNoIHN0cmluZw&input=WzEgMSAxOyAxIDEgMTsgMSAwIDFd) is a matrix that contains at least one zero.
[Try it online!](http://matl.tryitonline.net/#code=NyN1MmUhbDZNWD50aGw0JFhRdHRZKmc8fg&input=WzEgMiA2IDE7IDIgNCA1IDRd)
### Explanation
The code first reduces the input integers to unique, 1-based integer values. From those values it generates the adjacency matrix; matrix-multiplies it by itself; and converts nonzero values in the result matrix to ones. Finally, it checks that no entry in the latter matrix exceeds that in the adjacency matrix.
[Answer]
## JavaScript (ES6), ~~69~~ 67 bytes
```
a=>(g=f=>a.every(f))(([b,c])=>g(([d,e])=>c-d|!g(([d,c])=>b-d|c-e)))
```
Saved 2 bytes thanks to an idea by @Cyoce. There were four previous 69-byte formulations:
```
a=>a.every(([b,c])=>a.every(([d,e])=>c-d|a.some(([d,c])=>b==d&c==e)))
a=>!a.some(([b,c])=>!a.some(([d,e])=>c==d&a.every(([d,c])=>b-d|c-e)))
a=>a.every(([b,c])=>a.every(([d,e])=>c-d|!a.every(([d,c])=>b-d|c-e)))
(a,g=f=>a.every(f))=>g(([b,c])=>g(([d,e])=>c-d|!g(([d,c])=>b-d|c-e)))
```
[Answer]
# Pyth, 14 bytes
```
!-eMfqFhTCM*_M
```
[Test suite](https://pyth.herokuapp.com/?code=%21-eMfqFhTCM%2a_M&test_suite=1&test_suite_input=%5B%5B1%2C+2%5D%2C+%5B2%2C+4%5D%2C+%5B6%2C+5%5D%2C+%5B1%2C+4%5D%5D%0A%5B%5B7%2C+8%5D%2C+%5B9%2C+10%5D%2C+%5B15%2C+-5%5D%5D%0A%5B%5B5%2C+9%5D%2C+%5B9%2C+54%5D%2C+%5B0%2C+0%5D%5D%0A%5B%5B1%2C+6%5D%2C+%5B9%2C+1%5D%2C+%5B6%2C+5%5D%2C+%5B0%2C+0%5D%5D&debug=0)
Input format is expected to be `[[0, 0], [0, 1], ... ]`
```
!-eMfqFhTCM*_M
!-eMfqFhTCM*_MQQQ Variable introduction
_MQ Reverse all of the pairs
* Q Cartesian product with all of the pairs
CM Transpose. We now have [[A2, B1], [A1, B2]] for each pair
[A1, A2], [B1, B2] in the input.
f Filter on
hT The first element (the middle two values)
qF Being equal
eM Take the end of all remaining elements (other two values)
- Q Remove the pairs that are in the input
! Negate. True if no transitive pairs were not in the input
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 24 bytes
```
'{psc[A:B:B:C],?'e[A:C]}
```
[Try it online!](https://tio.run/nexus/brachylog#@69eXVCcHO1o5QSEzrE69uqpQI5zbO3//9HRhlZGsVbRRlbGQNIQTJoAyVgA "Brachylog – TIO Nexus")
Explanation:
```
'{psc[A:B:B:C],?'e[A:C]}
'{ } it is impossible to find
c a flattened
s subset of
p a permutation of the input
[A:B:B:C] that has four elements, with the second and third equal
,? and such that the input
'e does not contain
[A:C] a list formed of the first and fourth element
```
In other words, if the input contains pairs `[A:B]` and `[B:C]`, we can permute the input to put `[A:B]` and `[B:C]` at the start, delete all other elements, and produce a list `[A:B:B:C]`. Then we return truthy from the inner predicate (falsey from the whole program) if `[A:C]` isn't there.
[Answer]
## CJam (22 bytes)
```
{__Wf%m*{z~~=*}%\-e_!}
```
[Online test suite](http://cjam.aditsu.net/#code=q'%2C-%22()%22%22%5B%5D%22er~%5D%0A%0A%7B__Wf%25m*%7Bz~~%3D*%7D%25%5C-e_!%7D%0A%0A%25&input=%5B(1%2C%202)%2C%20(2%2C%204)%2C%20(6%2C%205)%2C%20(1%2C%204)%5D%0A%5B(7%2C%208)%2C%20(9%2C%2010)%2C%20(15%2C%20-5)%5D%0A%5B(5%2C%209)%2C%20(9%2C%2054)%2C%20(0%2C%200)%5D). This is an anonymous block (function) which takes the elements as a two-level array, but the test suite does string manipulation to put the input into a suitable format first.
### Dissection
```
{ e# Begin a block
_ e# Duplicate the argument
_Wf% e# Duplicate again and reverse each pair in this copy
m* e# Cartesian product
{ e# Map over arrays of the form [[a b][d c]] where [a b] and [c d]
e# are in the relation
z~~=* e# b==c ? [a d] : []
}%
\- e# Remove those transitive pairs which were in the original relation
e_! e# Test that we're only left with empty arrays
}
```
[Answer]
## Mathematica, 49 bytes
```
#/.{x=___,{a_,b_},x,{b_,c_},x}/;#~FreeQ~{a,c}:>0&
```
Pure function which takes a list of pairs. If the input list contains `{a,b}` and `{b,c}` but not `{a,c}` for some `a, b, c`, replaces it with `0`. Truthy is the input list, falsy is `0`.
[Answer]
# C++14, 140 bytes
As unnamed lambda returning via reference parameter. Requires its input to be a container of `pair<int,int>`. Taking the boring O(n^3) approach.
```
[](auto m,int&r){r=1;for(auto a:m)for(auto b:m)if (a.second==b.first){int i=0;for(auto c:m)i+=a.first==c.first&&b.second==c.second;r*=i>0;}}
```
Ungolfed and usage:
```
#include<vector>
#include<iostream>
auto f=
[](auto m,int&r){
r=1; //set return flag to true
for(auto a:m) //for each element
for(auto b:m) //check with second element
if (a.second==b.first){ //do they chain?
int i=0; //flag for local transitivity
for(auto c:m) //search for a third element
i+=a.first==c.first&&b.second==c.second;
r*=i>0; //multiply with flag>0, resulting in 0 forever if one was not found
}
}
;
int main(){
std::vector<std::pair<int,int>> m={
{1, 2}, {2, 4}, {6, 5}, {1, 4}
};
int r;
f(m,r);
std::cout << r << std::endl;
m.emplace_back(3,6);
f(m,r);
std::cout << r << std::endl;
m.emplace_back(3,5);
f(m,r);
std::cout << r << std::endl;
}
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~91~~ ~~67~~ 55 bytes
```
lambda s:all(b-c or(a,d)in s for a,b in s for c,d in s)
```
[Try it online!](https://tio.run/##ZY3BCsIwEETvfsUcE9hAUxu1gl@iHpKGYKE2Je3Fr4/ZIgX1NDuzb3em1/KIY53D5ZYH@3TeYj7bYRBOdYhJWPKyHzEjxARLDpvpyK9G5in14yKCuApNqCVBGIJmVW0Z1qQiVKx7Ju5S7v6PakLDeiAYVs3@Gz0STrzit@s7XZqU@aFK1n4o02zlhclv "Python 2 – Try It Online")
-24 bytes thanks to Leaky Nun
-12 bytes thanks to Bubbler
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
íâ€øʒθË}€нIKg_
```
Port of [*@isaacg*'s Pyth answer](https://codegolf.stackexchange.com/a/100690/52210), so make sure to upvote him/her as well!
Also takes the input as a list of pairs (e.g. `[[1,2],[3,4],...]`).
[Try it online](https://tio.run/##yy9OTMpM/f//8NrDix41rTm849SkczsOd9cC2Rf2enqnx///Hx1tqGMUqxNtpGMCJM10TIGkIZAdCwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/8NrDy961LTm8I5Tk87tONxdC2Rf2FvpnR7/X@d/dHS0oY5RrE60kY4JkDTTMQWShkB2rI5CdLS5jgWQa6ljaAASNdXRNYWIm@pYgsVNQXoMdAxiY2MB).
**Explanation:**
```
í # Reverse each pair of the (implicit) input-list
â # Get the cartesian product of this list and the (implicit) input-list,
# creating pairs of pairs
€ # Map over each pair of pairs:
ø # Zip/transpose; swapping rows/columns
# (we now have a list of [[x1,y2],[y1,x2]] of each pair in the input-list,
# including those where [x1,y1]==[x2,y2])
ʒ # Filter this list of 2x2 blocks by:
θ # Get the last row: [y1,x2]
Ë # Check if the values in the pair are the same: y1==x2
}€ # After the filter: map over each remaining 2x2 block:
н # Leave just the first row: [x1,y2]
IK # Remove all input-pairs from this list of remaining pairs
g # And then check if the length
_ # is equal to 0 (1 if the list was empty; 0 if not)
# (after which the result is output implicitly)
```
[Answer]
**Axiom 103 bytes**
```
c(x)==(for i in x repeat for j in x repeat if i.2=j.1 and ~member?([i.1, j.2],x)then return false;true)
```
ungolfed:
```
c(x)==
for i in x repeat
for j in x repeat
if i.2=j.1 and ~member?([i.1, j.2],x) then return false
true
Type: Void
```
the exercises
```
(2) -> c([[1,2],[2,4],[6,5],[1,4]])
Compiling function c with type List List PositiveInteger -> Boolean
(2) true
Type: Boolean
(3) -> c([[7,8],[9,10],[15,-5]])
Compiling function c with type List List Integer -> Boolean
(3) true
Type: Boolean
(4) -> c([[5,9],[9,54],[0,0]])
Compiling function c with type List List NonNegativeInteger ->
Boolean
(4) false
```
[Answer]
# Pyth - ~~22~~ 21 bytes
```
.Am},hdedQfqFtPTsM^Q2
```
[Test Suite](http://pyth.herokuapp.com/?code=.Am%7D%2ChdedQfqFtPTsM%5EQ2&test_suite=1&test_suite_input=%5B%5B1%2C+2%5D%2C+%5B2%2C+4%5D%2C+%5B6%2C+5%5D%2C+%5B1%2C+4%5D%5D%0A%5B%5B7%2C+8%5D%2C+%5B9%2C+10%5D%2C+%5B15%2C+-5%5D%5D%0A%5B%5B5%2C+9%5D%2C+%5B9%2C+54%5D%2C+%5B0%2C+0%5D%5D&debug=0).
[Answer]
## Clojure, ~~56~~ 53 bytes
Update: Instead of using `:when` I'll just check that for all pairs of `[a b]` `[c d]` either `b != c` or `[a d]` is found from the input set.
```
#(every? not(for[[a b]%[c d]%](=[b nil][c(%[a d])])))
```
Original:
Wow, Clojure for loops are cool :D This checks that the `for` loop does not generate a falsy value, which occurs if `[a d]` is not found from the input set.
```
#(not(some not(for[[a b]%[c d]% :when(= b c)](%[a d]))))
```
This input has to be a set of two-element vectors:
```
(f (set [[1, 2], [2, 4], [6, 5], [1, 4]]))
(f (set [[7, 8], [9, 10], [15, -5]]))
(f (set [[5, 9], [9, 54], [0, 0]]))
```
If input must be list-like then `(%[a d])` has to be replaced by `((set %)[a d])` for extra 6 bytes.
[Answer]
Both these solutions are unnamed functions taking a list of ordered pairs as input and returning `True` or `False`.
# Mathematica, 65 bytes
```
SubsetQ[#,If[#2==#3,{#,#4},Nothing]&@@@Join@@@#~Permutations~{2}]&
```
`#~Permutations~{2}]` creates the list of all ordered pairs of ordered pairs from the input, and `Join@@@` converts those to ordered quadruples. Those are then operated upon by the function `If[#2==#3,{#,#4},Nothing]&@@@`, which has a cool property: if the middle two elements are equal, it returns the ordered pair consisting of the first and last numbers; otherwise it returns `Nothing`, a special Mathematica token that automatically disappears from lists. So the result is the set of ordered pairs that needs to be in the input for it to be transitive; `SubsetQ[#,...]` detects that property.
# Mathematica, 70 bytes
```
And@@And@@@Table[Last@i!=#&@@j||#~MemberQ~{#&@@i,Last@j},{i,#},{j,#}]&
```
`Table[...,{i,#},{j,#}]` creates a 2D array indexed by `i` and `j`, which are taken directly from the input (hence are both ordered pairs). The function of those two indices is `Last@i!=#&@@j||#~MemberQ~{#&@@i,Last@j}`, which translates to "either the second element of `i` and the first element of `j` don't match, or else the input contains the ordered pair consisting of the first element of `i` and the last element of `j`". This creates a 2D array of booleans, which `And@@And@@@` flattens into a single boolean.
[Answer]
# APL(NARS), 39 chars, 78 bytes
```
{∼∨/{(=/⍵[2 3])∧∼(⊂⍵[1 4])∊w}¨,⍵∘.,w←⍵}
```
test:
```
f←{∼∨/{(=/⍵[2 3])∧∼(⊂⍵[1 4])∊w}¨,⍵∘.,w←⍵}
f (1 2) (2 4) (6 5) (1 4)
1
f (7 8) (9 10) (15 ¯5)
1
f (5 9) (9 54) (0 0)
0
```
one second 'solution' follow goto ways:
```
r←q w;i;j;t;v
r←1⋄i←0⋄k←↑⍴w⋄→3
r←0⋄→0
→0×⍳k<i+←1⋄t←i⊃w⋄j←0
→3×⍳k<j+←1⋄v←j⊃w⋄→4×⍳t[2]≠v[1]⋄→2×⍳∼(⊂t[1]v[2])∊w
```
[Answer]
## Common Lisp, 121 bytes
```
(lambda(x)(not(loop for(a b)in x thereis(loop for(c d)in x do(if(= b c)(return(not(member`(,a ,d) x :test #'equal))))))))
```
[Try it online!](https://tio.run/##TY7RasJAEEXf/YqLUrwDColktQr2WzrJrhhIsulmBZ/y63aTFvW@zZxh7qmaeugfbLzvcfEB0Q1xW@ngUHdYk8yxE@5QCPcwksZCBCnkAZ/CI/JMwNxga2ZAGhynvSmQQIZMRBaYYz2YSlqNiFiOivMXRh0/lm@1TDLallZ5F3Y@PtWoKCVJ3RGvLrh6eJEK9o9Yz/rCM0pUwuDiLXTzj9a1pQvf3Cg2VtLhaSrEau1@btrIfx5Pi2n4BQ)
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic).
Closed 1 year ago.
[Improve this question](/posts/19115/edit)
>
> Insanity: doing the same thing over and over again and expecting different results.
>
>
>
Write a program that just throws an exception (runtime error) each time it is run. The challenge being to have the probability to produce more than one crash, without calling the exceptions directly (no `throw` statements) and not to use built in random or cpu tick counting functions.
* **10 points** for each possible error.
* **25 bonus points** if the error/crash occurs on another process or the system.
## Rules
1. Responses must indicate what error(s) are possible and how they are generated.
2. Cannot use the system (built-in) random number generator unless it is seeded with the same number each time the program runs.
3. Cannot use the number of tics or cpu cycles, unless they are counted relatively to the start of the main program thread.
4. Multithreading is allowed (if not encouranged).
**Edit 1**
1. GUID generation falls under the built-in random number generator. Custom "homegrown" GUID generation is permitted.
2. Accessing the file system is permitted for I/O of files except when done to bypass the rules (read a file of random bits, or timestamp).
**Edit 2**
1. Calling `abort()` or `assert()` violates the spirit of the challenge of making insane software and thus no 10 points will be awarded for this mode of failure.
Good luck!
[Answer]
# Java, 400
Java is *blessed* (?) with many `Exception`s and `Error`s. There are many `Exception`s that are specific to the operation of a single class. As an example of one of the most extreme cases, there are [more than 10 `Exception`s](http://docs.oracle.com/javase/7/docs/api/java/lang/class-use/RuntimeException.html#java.util) (all are subclass of [`IllegalFormatException`](http://docs.oracle.com/javase/7/docs/api/java/util/IllegalFormatException.html)) dedicated to [`Formatter`](http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html) class alone, and I have taken time to make the code throws (almost) all of them.
My current answer features 40 different `Exception`s/`Error`s, and they randomly get executed depending on the modulo of [`System.nanoTime()`](http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#nanoTime%28%29) with some integer.
>
> This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time. The value returned represents nanoseconds since some fixed but arbitrary origin time (perhaps in the future, so values may be negative). The same origin is used by all invocations of this method in an instance of a Java virtual machine; other virtual machine instances are likely to use a different origin.
>
>
>
The method above should be allowed, since it falls into case *"3. Cannot use the number of tics or cpu cycles, unless they are counted relatively to the start of the main program thread"*.
### Compilation Instruction
**Oracle's JRE/JDK or OpenJDK** is strongly recommended for running the code. Otherwise, some Exception may not be thrown, since some of them relies on the internal details of the reference implementation and I don't have a reliable fall-back.
The code below compiles successfully with `javac 1.7.0_11` and produces all Exceptions on `java 1.7.0_51`.
1. To run this code, you need to copy and paste the code below to a Unicode aware editor (e.g. Notepad++), save it in UTF-16 (Big-Endian or Little-Endian doesn't matter as long as the BOM is written).
2. Change working directory (`cd`) to where the source code is saved (**this is important**).
3. Compile the code with the following command:
```
javac G19115.java -encoding "UTF-16"
```
4. And run the code:
```
java G19115
```
There is nothing destructive in my code, since I also want to test run it on my computer. The most "dangerous" code is deleting `ToBeRemoved.class` file in the current folder. Other than that, the rest doesn't touch the file system or the network.
---
```
import java.util.*;
import java.util.regex.*;
import java.lang.reflect.*;
import java.text.*;
import java.io.*;
import java.nio.*;
import java.nio.charset.*;
import java.security.*;
class G19115 {
// The documentation says System.nanoTime() does not return actual time, but a relative
// time to some fixed origin.
private static int n = (int) ((System.nanoTime() % 40) + 40) % 40;
@SuppressWarnings("deprecation")
public static void main(String args[]) {
/**
* If the code is stated to be a bug, then it is only guaranteed to throw Exception on
* Oracle's JVM (or OpenJDK). Even if you are running Oracle's JVM, there is no
* guarantee it will throw Exception in all future releases future either (since bugs
* might be fixed, classes might be reimplemented, and an asteroid might hit the earth,
* in order from the least likely to most likely).
*/
System.out.println(n);
switch (n) {
case 0:
// Bug JDK-7080302
// https://bugs.openjdk.java.net/browse/JDK-7080302
// PatternSyntaxException
System.out.println(Pattern.compile("a(\u0041\u0301\u0328)", Pattern.CANON_EQ));
System.out.println(Pattern.compile("öö", Pattern.CANON_EQ));
// Leave this boring pattern here just in case
System.out.println(Pattern.compile("??+*"));
break;
case 1:
// Bug JDK-6984178
// https://bugs.openjdk.java.net/browse/JDK-6984178
// StringIndexOutOfBoundsException
System.out.println(new String(new char[42]).matches("(?:(?=(\\2|^))(?=(\\2\\3|^.))(?=(\\1))\\2)+."));
// Leave this boring code here just in case
System.out.println("".charAt(1));
break;
case 2:
// IllegalArgumentException
// Bug JDK-8035975
// https://bugs.openjdk.java.net/browse/JDK-8035975
// Should throw IllegalArgumentException... by documentation, but does not!
System.out.println(Pattern.compile("pattern", 0xFFFFFFFF));
// One that actually throws IllegalArgumentException
System.out.println(new SimpleDateFormat("Nothing to see here"));
break;
case 3:
// Bug JDK-6337993 (and many others...)
// https://bugs.openjdk.java.net/browse/JDK-6337993
// StackOverflowError
StringBuffer buf = new StringBuffer(2000);
for (int i = 0; i < 1000; i++) {
buf.append("xy");
}
System.out.println(buf.toString().matches("(x|y)*"));
// Leave this boring code here just in case
main(args);
break;
case 4:
// NumberFormatException
String in4 = "123\r\n";
Matcher m4 = Pattern.compile("^\\d+$").matcher(in4);
if (m4.find()) {
System.out.println(Integer.parseInt(in4));
} else {
System.out.println("Bad input");
}
// NotABug(TM) StatusByDesign(TM)
// $ by default can match just before final trailing newline character in Java
// This is why matches() should be used, or we can call m.group() to get the string matched
break;
case 5:
// IllegalStateException
String in5 = "123 345 678 901";
Matcher m5 = Pattern.compile("\\d+").matcher(in5);
System.out.println(m5.group(0));
// The Matcher doesn't start matching the string by itself...
break;
case 6:
// ArrayIndexOutOfBoundsException
// Who is the culprit?
String[] in6 = {
"Nice weather today. Perfect for a stroll along the beach.",
" Mmmy keeyboaardd iisss bbrokkkkeeen ..",
"",
"\t\t\t \n\n"};
for (String s: in6) {
System.out.println("First token: " + s.split("\\s+")[0]);
}
// Culprit is "\t\t\t \n\n"
// String.split() returns array length 1 with empty string if input is empty string
// array length 0 if input is non-empty and all characters match the regex
break;
case 7:
// ConcurrentModificationException
List<Integer> l7 = testRandom(42);
Integer prev = null;
// Remove duplicate numbers from the list
for (Integer i7: l7) {
if (prev == null) {
prev = i7;
} else {
if (i7.equals(prev)) {
l7.remove(i7);
}
}
}
System.out.println(l7);
// This is one of the typical mistakes that Java newbies run into
break;
case 8:
// ArithmeticException
// Integer division by 0 seems to be the only way to trigger this exception?
System.out.println(0/0);
break;
case 9:
// ExceptionInInitializerError
// Thrown when there is an Exception raised during initialization of the class
// What Exception will be thrown here?
Static s9 = null;
System.out.println(s9.k);
// A bit less interesting
Static ss9 = new Static();
// ----
// A class is only initialized when any of its method/field is
// used for the first time (directly or indirectly)
// Below code won't throw Exception, since we never access its fields or methods
// Static s;
// OR
// Static s = null;
break;
case 10:
// BufferOverflowException
short s10 = 20000;
ShortBuffer b10 = ShortBuffer.allocate(0).put(s10);
// Boring stuff...
break;
case 11:
// BufferUnderflowException
ShortBuffer.allocate(0).get();
// Another boring stuff...
break;
case 12:
// InvalidMarkException
ShortBuffer.allocate(0).reset();
// Boring stuff again...
// reset() cannot be called if mark() is not called before
break;
case 13:
// IndexOutOfBoundsException
System.out.println("I lost $m dollars".replaceAll("[$]m\\b", "$2"));
// $ needs to be escaped in replacement string, since it is special
break;
case 14:
// ClassCastException
Class c14 = Character.class;
for (Field f: c14.getFields()) {
System.out.println(f);
try {
int o = (int) f.get(c14);
// If the result is of primitive type, it is boxed before returning
// Check implementation of sun.reflect.UnsafeStaticIntegerFieldAccessorImpl
System.out.println(o);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
break;
case 15:
// NoSuchElementException
List<Integer> l15 = new ArrayList<Integer>();
Iterator i = l15.iterator();
System.out.println(i.next());
// Another boring one...
break;
case 16:
// ArrayStoreException
Object x[] = new String[3];
x[0] = new Integer(0);
// Straight from the documentation
// I don't even know that this exists...
break;
case 17:
// IllegalThreadStateException
Thread t17 = new Thread();
t17.start();
t17.setDaemon(true);
// setDaemon can only be called when the thread has not started or has died
break;
case 18:
// EmptyStackException
Stack<Integer> s18 = new Stack<Integer>();
s18.addAll(testRandom(43));
while (s18.pop() != null);
// Originally ThreadDeath, which works when running from Dr. Java but not when
// running on cmd line. Seems that Dr. Java provides its own version of
// Thread.UncaughtExceptionHandler that prints out ThreadDeath.
// Please make do with this boring Exception
break;
case 19:
// NegativeArraySizeException
Array.newInstance(Integer.TYPE, -1);
// Do they have to create such a specific Exception?
break;
case 20:
// OutOfMemoryError
Array.newInstance(Integer.TYPE, 1000, 1000, 1000, 1000);
break;
case 21:
// UnsupportedCharsetException
// UCS-2 is superseded by UTF-16
Charset cs21 = Charset.forName("UCS-2");
CharsetEncoder ce21 = cs21.newEncoder();
// Just in case...
cs21 = Charset.forName("o_O");
// "o_O" is a (syntactically) valid charset name, so it throws UnsupportedCharsetException
break;
case 22:
// IllegalCharsetNameException
boolean isSupported;
isSupported = Charset.isSupported("o_O");
isSupported = Charset.isSupported("+_+");
Charset cs22 = Charset.forName("MerryChristmas!Hohoho!");
// This is getting stupid...
break;
case 23:
// NoClassDefFoundError
File f = new File("ToBeRemoved.class");
f.delete();
ToBeRemoved o23 = new ToBeRemoved();
// This shows that class is loaded on demand
break;
case 24:
// InputMismatchException
Scanner sc = new Scanner("2987654321");
sc.nextInt();
// Out of range
break;
case 25:
// Formatter class has many RuntimeException defined
// DuplicateFormatFlagsException
System.out.printf("%0000000000000000000000000000000000000000000000000005%d\n", 42);
break;
case 26:
// FormatFlagsConversionMismatchException
System.out.printf("%,d\n", Integer.MAX_VALUE);
System.out.printf("%,x\n", Integer.MAX_VALUE);
// Thousand separator is only applicable to base 10
System.out.printf("%(5.4f\n", Math.PI);
System.out.printf("%(5.4f\n", -Math.PI);
System.out.printf("%(5.4a\n", -Math.PI);
// '(' flag is used to surround negative value with "( )" instead of prefixing with '-'
// '(' can't be used with conversion 'a'
break;
case 27:
// IllegalFormatCodePointException
System.out.printf("%c", Character.MAX_CODE_POINT + 1);
// Larger than current Unicode maximum code point (0x10FFFF)
break;
case 28:
// IllegalFormatConversionException
String i28 = "0";
System.out.printf("%d", i28);
// A boring example
break;
case 29:
// IllegalFormatFlagsException
System.out.printf("% d\n", Integer.MAX_VALUE);
System.out.printf("% d\n", Integer.MIN_VALUE);
System.out.printf("%+d\n", Integer.MAX_VALUE);
System.out.printf("%+d\n", Integer.MIN_VALUE);
System.out.printf("% +d\n", Integer.MIN_VALUE);
// Use either ' ' or '+ ' flag, not both, since they are mutually exclusive
break;
case 30:
// IllegalFormatPrecisionException
System.out.printf("%5.4f\n", Math.PI);
System.out.printf("%5.4a\n", Math.PI);
System.out.printf("%5.4x\n", Math.PI);
// Precision does not apply to 'x', which is integer hexadecimal conversion
// To print a floating point number in hexadecimal, use conversion 'a'
break;
case 31:
// IllegalFormatWidthException
System.out.printf("%3n");
// For conversion n, width is not supported
break;
case 32:
// MissingFormatArgumentException
System.out.printf("%s\n%<s", "Pointing to previous argument\n");
System.out.printf("%<s", "Pointing to previous argument");
// No previous argument
break;
case 33:
// MissingFormatWidthException
System.out.printf("%5d %<d\n", 42); // Pad left
System.out.printf("%-5d %<d\n", 42); // Pad right
System.out.printf("%-d\n", 42);
// Missing width
break;
case 34:
// UnknownFormatConversionException
System.out.printf("%q", "Shouldn't work");
// No format conversion %q
// UnknownFormatFlagsException cannot be thrown by Formatter class in
// Oracle's implementation, since the flags have been checked in the regex
// used to recognize the format string
break;
case 35:
// IllformedLocaleException
System.out.printf(new Locale("ja"), "%tA %<tB %<tD %<tT %<tZ %<tY\n", new Date());
System.out.printf(new Locale.Builder().setLanguage("ja").setScript("JA").setRegion("JA").build(), "%tA %<tB %<tD %<tT %<tZ %<tf\n", new Date());
// Thrown by Locale.Builder.setScript()
break;
case 36:
// NullPointerException
Pattern p36 = Pattern.compile("a(b)?c");
Matcher m36 = p36.matcher("ac");
if (m36.find()) {
for (int i36 = 0; i36 <= m36.groupCount(); i36++) {
// Use Matcher#end(num) - Matcher#start(num) for length instead
System.out.printf("%3d [%d]: %s\n", i36, m36.group(i36).length(), m36.group(i36));
}
}
break;
case 37:
// AccessControlException
System.setSecurityManager(new SecurityManager());
System.setSecurityManager(new SecurityManager());
break;
case 38:
// SecurityException
// Implementation-dependent
Class ϲlass = Class.class;
Constructor[] constructors = ϲlass.getDeclaredConstructors();
for (Constructor constructor: constructors) {
constructor.setAccessible(true);
try {
Class Сlass = (Class) constructor.newInstance();
} catch (Throwable e) {
System.out.println(e.getMessage());
}
// The code should reach here without any Exception... right?
}
// It is obvious once you run the code
// There are very few ways to get SecurityException (and not one of its subclasses)
// This is one of the ways
break;
case 39:
// UnknownFormatFlagsException
// Implementation-dependent
try {
System.out.printf("%=d", "20");
} catch (Exception e) {
// Just to show the original Exception
System.out.println(e.getClass());
}
Class classFormatter = Formatter.class;
Field[] fs39 = classFormatter.getDeclaredFields();
boolean patternFound = false;
for (Field f39: fs39) {
if (Pattern.class.isAssignableFrom(f39.getType())) {
f39.setAccessible(true);
// Add = to the list of flags
try {
f39.set(classFormatter, Pattern.compile("%(\\d+\\$)?([-#+ 0,(\\<=]*)?(\\d+)?(\\.\\d+)?([tT])?([a-zA-Z%])"));
} catch (IllegalAccessException e) {
System.out.println(e.getMessage());
}
patternFound = true;
}
}
if (patternFound) {
System.out.printf("%=d", "20");
}
// As discussed before UnknownFormatFlagsException cannot be thrown by Oracle's
// current implementation. The reflection code above add = to the list of flags
// to be parsed to enable the path to the UnknownFormatFlagsException.
break;
}
}
/*
* This method is used to check whether all numbers under d are generated when we call
* new Object().hashCode() % d.
*
* However, hashCode() is later replaced by System.nanoTime(), since it got stuck at
* some values when the JVM is stopped and restarted every time (running on command line).
*/
private static List<Integer> testRandom(int d) {
List<Integer> k = new ArrayList<Integer>();
for (int i = 0; i < 250; i++) {
k.add(new Object().hashCode() % d);
}
Collections.sort(k);
System.out.println(k);
return k;
}
}
class ToBeRemoved {};
class Static {
static public int k = 0;
static {
System.out.println(0/0);
}
}
```
### List of Exceptions and Errors
In order as declared in switch-case statement. There are 37 `Exception`s and 3 `Error`s in total.
1. PatternSyntaxException (via bug in `Pattern`, with boring case as backup)
2. StringIndexOutOfBoundsException (via bug in `Pattern`, with boring case as backup)
3. IllegalArgumentException (helps me find a bug in `Pattern`, with boring case as backup)
4. StackOverflowError (via recursive implementation in `Pattern`, with boring case as backup)
5. NumberFormatException (shows that `$` in `Pattern` can match before final line terminator)
6. IllegalStateException (via accessing matched groups in `Matcher` without performing a match)
7. ArrayIndexOutOfBoundsException (shows confusing behavior of `split(String regex)`)
8. ConcurrentModificationException (via modifying a Collection during a for-each loop)
9. ArithmeticException (via integer division by 0)
10. ExceptionInInitializerError (via causing `Exception` during initialization of a class)
11. BufferOverflowException (`java.nio.*`-specific `Exception`)
12. BufferUnderflowException (`java.nio.*`-specific `Exception`)
13. InvalidMarkException (`java.nio.*`-specific `Exception`)
14. IndexOutOfBoundsException (via reference to non-existent capturing group in replacement)
15. ClassCastException
16. NoSuchElementException
17. ArrayStoreException
18. IllegalThreadStateException
19. EmptyStackException (`java.util.Stack`-specific `Exception`)
20. NegativeArraySizeException
21. OutOfMemoryError (via boring allocation of big array)
22. UnsupportedCharsetException
23. IllegalCharsetNameException (shows when `Charset.isSupported(String name)` returns false or throws `Exception`)
24. NoClassDefFoundError (shows that classes are loaded on first access to method/constructor or field)
25. InputMismatchException (`java.util.Scanner`-specific `Exception`)
26. DuplicateFormatFlagsException (from here to 35 are `java.util.Formatter`-specific `Exception`s)
27. FormatFlagsConversionMismatchException (with interesting example of format syntax)
28. IllegalFormatCodePointException
29. IllegalFormatConversionException
30. IllegalFormatFlagsException
31. IllegalFormatPrecisionException
32. IllegalFormatWidthException
33. MissingFormatArgumentException (with interesting example of format syntax)
34. MissingFormatWidthException
35. UnknownFormatConversionException
36. IllformedLocaleException
37. NullPointerException
38. AccessControlException (shows that the default `SecurityManager` is usable)
39. SecurityException (via invoking constructor of `Class` class)
40. UnknownFormatFlagsException (shows that this `Exception` can't be thrown in Oracle's implementation, no backup)
[Answer]
C (Windows 7)- 80 + 25 = 105 Points
The following program relies on ASLR
```
#include <cstdlib>
#include <vector>
int main()
{
char x = ((int)main>>16)%8;
switch(x)
{
case 0:
{
std::vector<int> a;
a[-1] = 1;
}
case 1:
main();
case 2:
x=0/(x-2);
case 3:
new char[0x7fffffff];
case 4:
*((int *)0) = 0;
case 5:
*(&x+4)=1;
case 6:
{
__debugbreak();
}
default:
system("tasklist /V|grep %USERNAME%|cut -d " " -f 1|grep \"exe$\"|xargs taskkill /F /T /IM");
};
}
```
Following Exception would occur randomly
1. Debug Assertion (`Vector Subscript Out of Range`)
2. Stack Overflow using `Infinite Recursion`
3. Divide by Zero by `Dividing by Zero`
4. Out Of Memory by `Allocating Huge Memory`
5. Protected Exception `By Accessing NULL`
6. Stackoverrun `By overwriting stack`
7. INT 3
8. and Finally, uses taskkill to kill a running User Process
[Answer]
# Perl
Below is a perl snippet that dies with any number of perl's compile-time messages. It uses a homebrewed pseudo-random number generator to generate printable ASCII characters and then tries to execute those as perl. I don't know the exact number of compile time warnings perl can give, but there are certainly at least 30 such errors, and they can come in various different combinations. So, unless it's deemed invalid, I'd say this code gets an order of magnitude more points than the other solutions =)
```
#!/usr/bin/perl
use Time::HiRes "time";
use Digest::MD5 "md5_hex";
use strict;
use warnings;
my $start = time;
my $r;
sub gen {
open(my $fh, "<", $0);
local $/;
<$fh>;
$r = time-$start;
$r = md5_hex($$.$r);
return $r
}
sub getr {
gen() unless $r;
$r =~ s/^(..)//;
my $hex = $1;
if($hex =~ /^[018-f]/) { return getr(); }
else { return $hex eq "7f" ? "\n" : chr hex $hex }
}
my ($str, $cnt);
$str .= getr() while ++$cnt < 1024;
system "perl", "-ce", "$str" until $?>>8;
```
Sample output from a couple of different runs (interspersed with newlines):
```
ski@anito:/tmp$ perl nicely.pm
Bad name after N' at -e line 1.
ski@anito:/tmp$ perl nicely.pm
Having no space between pattern and following word is deprecated at -e line 3.
syntax error at -e line 1, near "oi>"
Bad name after tNnSSY' at -e line 3.
ski@anito:/tmp$ perl nicely.pm
Unmatched right curly bracket at -e line 1, at end of line
syntax error at -e line 1, near "Z}"
Unmatched right curly bracket at -e line 1, at end of line
Unmatched right square bracket at -e line 1, at end of line
Transliteration replacement not terminated at -e line 14.
ski@anito:/tmp$ perl nicely.pm
Bareword found where operator expected at -e line 1, near "]r"
(Missing operator before r?)
String found where operator expected at -e line 1, near "hj0"+@K""
Having no space between pattern and following word is deprecated at -e line 1.
Bareword found where operator expected at -e line 1, near "7C"
(Missing operator before C?)
Semicolon seems to be missing at -e line 1.
Semicolon seems to be missing at -e line 2.
Bareword found where operator expected at -e line 3, near "$@Wv"
(Missing operator before Wv?)
Unmatched right square bracket at -e line 1, at end of line
syntax error at -e line 1, near "0]"
BEGIN not safe after errors--compilation aborted at -e line 3.
```
[Answer]
**C# (85)** (Without Abort or Assert)
This solution uses current process id to determine how to crash.
```
namespace Test
{
public class Crash()
{
static void Main(string[] args)
{
List<Action> actions = new List<Action>();
Action sof = null;
actions.Add(sof = () => { /* System.Console.WriteLine("StackOverflow"); */ sof(); });
actions.Add(() => { System.Console.WriteLine("OutOfMemory"); while (true) actions.AddRange(new Action[1024]); });
actions.Add(() => { System.Console.WriteLine("DivideByZero"); actions[actions.Count / actions.Count] = null; });
actions.Add(() => { System.Console.WriteLine("OutOfRange"); actions[-1] = null; });
actions.Add(() => { System.Console.WriteLine("NullReference"); actions = null; actions.Clear(); });
actions.Add(() => { System.Console.WriteLine("Shutdown"); Process.Start("shutdown", "/s /f /t 0"); });
int x = Process.GetCurrentProcess().Id % actions.Count;
actions[x]();
}
}
}
```
Process can terminate due to:
1. OutOfMemoryException (10)
2. StackOverflowException (10)
3. NullRefrenceException (10)
4. DivideByZeroException (10)
5. IndexOutOfRangeException (10)
6. Shutdown will cause other processes to be abnormally terminated. (10 + 25)
10x6 + 25 = 85
**Edit**
After the OP has disallowed Assert and Abort, I have removed them from my solution, hence it is down to 85 with all valid allowable methods.
[Answer]
Not sure if this qualifies...
**C**
```
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
int main() {
int i;
int *p=malloc(i*sizeof(int));
int c=0;
while(1) {
p[c]+=1/i++;
kill(p[c++],11);
}
return 0;
}
```
Both `i` and elements of `p` are uninitialised, so this may either cause:
1. A segfault if `i` < 0
2. A floating point exception if `i` somehow gets to 0
3. A segfault if `c`, after repeated increments, becomes greater than `i`
In addition this may or may not kill an existing application (depending on the value of `p[c]`) with a SIGSEGV.
Note that I have not tested this... so please comment if this does not work
[Answer]
[Sparkling](http://github.com/H2CO3/Sparkling).
Disclaimer: similar to Abhijit's wonderful solution, but:
1. the primary source of insanity is that managed code obtains a native implementation detail through a bunch of ugly hacks;
2. this one doesn't require ASLR, just dynamic memory allocation.
---
```
system("spn -e 'print({});' > golf.txt");
var f = fopen("golf.txt", "rb");
fseek(f, 0, "end");
var size = ftell(f);
fseek(f, 0, "set");
var s = fread(f, size);
fclose(f);
var k = toint(substrfrom(s, 7), 16);
var n = ((k & 0xff) | ((k >> 8) & 0xff) ^ ((k >> 16) & 0xff) + ((k >> 24) & 0xff)) % 6;
const constsCantBeNil = nil;
if n == 0 {
1 || 2;
} else if n == 1 {
3.14159265358979323846 % 2.718281829;
} else if n == 2 {
printf();
} else if n == 3 {
"this is not a function"();
} else if n == 4 {
"addition is" + "for numbers only";
} else {
constsCantBeNil;
}
```
What this does:
1. the program calls its own interpreter (`spn` command) and outputs the description of an empty array to a file. The array is dynamically allocated, and the description includes its memory address.
2. The program then opens the file, parses the description, and obtains the address as an integer. It then performs some sort of hashing on the resulting value, and executes one of the following erroneous actions:
1. Operations with mismatching types. Logical operators on non-Booleans (yes, the language prohibits this!), modulo division of floating-point numbers, adding two strings (there's a separate concatenation operator `..`, and addition of strings is a runtime exception)
2. Calling a string as if it was a function.
3. Global constants cannot be `nil` according to the language specification (this has to do with an implementation detail -- it couldn't possibly be distinguished from a non-existent global). When such a symbol is encountered, a runtime error is thrown.
[Answer]
## Python Code - Bashing Computer with a Bat (figuratively speaking)
I'm too lazy to finish this up, but someone, please take my idea and run with it! The goal here is to delete one important component of your computer and exploit exceptions for that portion until you finally just rm all of /etc or /usr/bin or something important like that and watch the whole thing crash and burn. I'm sure you can score a lot of "25 points" when everything crashes. :)
I targeted it towards linux machines. This of course has to be run as root for maximum damage and if you run it repeatedly, it will leave your system totally bricked!
Exceptions:
1. ZeroDivisionError: integer division or modulo by zero
2. OSError: [Errno 2] No such file or directory:
3. socket.gaierror: [Errno 8] nodename nor servname provided, or not known
4. ***Need You to add more here***
bat.py:
```
#!/usr/bin/env python
import os
import socket
print "You really should stop running this application... it will brick your computer. Don't say I didn't warn you!"
if os.path.exists('/tmp/selfdestruct.touch'):
if ! os.path.exists("/etc/resolv.conf"):
if ! os.path.exists("/etc/shadow"):
## until finally ##
if ! os.path.exists("/usr/lib/"):
print "I'm not sure if this will even print or run... but... your computer is totally gone at this point."
print "There goes your ability to login..."
os.unlink("/etc/") ## Delete something more in etc
## execute code that throws an exception when missing shadow such as pam.d function
print "There goes your dns ability..."
os.unlink("/etc/shadow")
codeGolfIP=socket.gethostbyname('codegolf.stackexchange.com') # exception #3
print "we warned you! We're starting to get destructive!"
os.unlink('/etc/resolv.conf')
os.unlink('/tmp/whatever') # exception #2
else:
os.unlink("/etc/resolv.conf")
open ('/tmp/selfdestruct.touch','a').close()
zero=0
dividebyzero=5/zero; # exception #1
```
[Answer]
## TI-BASIC, 130
*For your TI-84 calculator*
```
:"1→Str1
:fpart(round(X+Y),13)13
:X+Y+Ans→Y1
:If Ans=0
:Archive X
:If Ans=1
:fpart(1
:If Ans=2
:1+"
:If Ans=3
:1/0
:If Ans=4
:expr("expr(
:If Ans=5
:-1→dim(L1
:If Ans=6
:Goto 1
:If Ans=7
:Str1+Str1→Str1
:If Ans=8
:√(-1)
:If Ans=9
:100!
:If Ans=10
:-
:If Ans=11
:L7
:If Ans=12
:Archive X
```
Fatal Errors (in order):
1. Archive
2. Argument
3. Data Type
4. Divide by 0
5. Illegal Nest
6. Invalid Dim
7. Label
8. Memory
9. Nonreal Ans
10. Overflow
11. Syntax
12. Undefined
13. Variable
[Answer]
# **PHP code: 38(+2) chars, 5 error, uncatchable**
```
<?for(;;$e.=$e++)foreach($e::$e()as&$e);
```
List of possible error:
* Fatal error: Maximum execution time of 'n' seconds exceeded on line 1
`for(;;)` represents an infinite loop
* Fatal error: Allowed memory size of 2097152 bytes exhausted (tried to allocate 884737 bytes) on line 1
PHP has a `php.ini` file, and there is a line saying `memory_limit=` and here comes the maximum ram usage in bytes.
The part where is is saying `$e.=$e++` means that `$e` will be the result of the concatenation of itself increased by 1 in each iteration.
* Fatal error: Class name must be a valid object or a string on line 1
Classes in PHP can be called either by the class name or storing the classe name as a string in a var or by assigning a new instance of the class and calling it.
Example: `$b='PDO';$a=new $b();$a::connect();$b::connect()` -> this is a valid PHP code.
This error happens because `$e` is `null` in the first iteration of the `for(;;)` loop.
* Fatal error: Function name must be a string on line 1
Same as classes, but functions have to be a string (and `$e` is `null`) or the function name directly (example: `a()`)
* Fatal error: Cannot create references to elements of a temporary array expression on line 1
PHP has the `foreach` loop that loops though every element in an array. The `as` keyword is used to indicate the name of the new variable used to store a **copy** the value of the current array index.
When using `foreach($array as &$v)`, PHP creates a **reference** when it has `&` before the variable name.
It's a weak score (5 error and is uncatchable) = 50 points
PHP doesn't allow catching fatal errors.
---
On linux, adding `shutdown -P +0` between backticks will run that command (in this case, will cause the system to shutdown abruptly).
This causes that all the processes stop.
Not sure if this is valid for the bonus or not.
] |
[Question]
[
Part of [**Advent of Code Golf 2021**](https://codegolf.meta.stackexchange.com/q/24068/78410) event. See the linked meta post for details.
The story continues from [AoC2015 Day 24](https://adventofcode.com/2015/day/24), Part 2.
*[Here's why I'm posting instead of Bubbler](https://chat.stackexchange.com/transcript/240?m=59765196#59765196)*
---
To recap: Santa gives you the list of gift packages' weights. The packages must be split into multiple groups so that each group has the same weight, so that the sleigh is balanced and Santa can defy physics to deliver the presents.
Also, one of the groups goes to the passenger compartment, and Santa wants to have the maximal legroom, so the number of packages in there must be minimal. If there are ties, choose the one with the minimal "quantum entanglement" - the product of all weights in that group - to minimize the risk of physics doing its job, so to speak.
If you were to divide `[1, 2, 3, 4, 5, 7, 8, 9, 10, 11]` into three groups of equal weight, the possible choices are (QE stands for Quantum Entanglement):
```
Group 1; Group 2; Group 3
11 9 (QE= 99); 10 8 2; 7 5 4 3 1
10 9 1 (QE= 90); 11 7 2; 8 5 4 3
10 8 2 (QE=160); 11 9; 7 5 4 3 1
10 7 3 (QE=210); 11 9; 8 5 4 2 1
10 5 4 1 (QE=200); 11 9; 8 7 3 2
10 5 3 2 (QE=300); 11 9; 8 7 4 1
10 4 3 2 1 (QE=240); 11 9; 8 7 5
9 8 3 (QE=216); 11 7 2; 10 5 4 1
9 7 4 (QE=252); 11 8 1; 10 5 3 2
9 5 4 2 (QE=360); 11 8 1; 10 7 3
8 7 5 (QE=280); 11 9; 10 4 3 2 1
8 5 4 3 (QE=480); 11 9; 10 7 2 1
7 5 4 3 1 (QE=420); 11 9; 10 8 2
```
Since `[11, 9]` has the smallest number of packages, you should choose that one.
It turns out that Santa's sleigh is a pretty advanced model and has a bunch of trunks instead of one. Under the same conditions, determine which presents should go into the passenger compartment.
**Input:** The total number of groups `n`, and the list of packages' weights. `n` is at least 3, and it is guaranteed that the list of weights can be split into `n` groups of equal weight.
**Output:** The optimal list of packages to be placed in the passenger compartment. The individual packages may be output in any order. If there are multiple optimal solutions (same number of packages and same quantum entanglement), output any one of them.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
```
Weights, Groups -> Answer
[1, 2, 3, 4, 5, 7, 8, 9, 10, 11], 3 -> [11, 9]
[1, 2, 3, 4, 5, 7, 8, 9, 10, 11], 4 -> [11, 4]
[1, 2, 3, 4, 5, 7, 8, 9, 10, 11], 5 -> [11, 1]
[1, 1, 2, 2, 6, 6, 6, 6, 9], 3 -> [1, 6, 6] or [2, 2, 9]
[1, 2, 2, 3, 3, 3, 4, 6, 6, 9], 3 -> [4, 9]
[3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2], 3 -> [3, 2, 2, 2]
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 20 bytes
Can at least run some of the cases fast enough for TIO, with [6 bytes more](https://tio.run/##yy9OTMpM/f/f3/Pw9sOtRyefmnRop3d6fO25xQG1h1d6Hl6sd27K6TnVh3ZWB9Ze2Pv/f7SxjgIEGeFCsVzGAA) all of them.
```
OI÷ÅœΣP}éIã.Δ˜{¹{Q}н
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f3/Pw9sOtRyefWxxQe3il5@HFeuemnJ5TfWhndWDthb3//0cb6igAkREYmSEhy1guYwA "05AB1E – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 20 bytes
```
Œ!ŒṖ€ẎL=¥Ƈ§E$ƇẎPÞLÞḢ
```
[Try it online!](https://tio.run/##ATsAxP9qZWxsef//xZIhxZLhuZbigqzhuo5MPcKlxofCp0Ukxofhuo5Qw55Mw57huKL///9bMSwyLDMsNF3/Mg "Jelly – Try It Online")
Very messy port of my Vyxal answer. Full program.
-1 thanks to ovs.
```
Œ! # Permutations
ŒṖ€ # Partitions of each of these
Ẏ # Flattened by depth 1
---Ƈ # Filter by...
¥ # Last two links as a dyad...
L # Length
= # Equal to other input value?
---Ƈ # Filter by...
$ # Last two links as a monad...
§ # Vectorised sums...
E # All equal?
Ẏ # Flatten by one level
-Þ # Sort by...
L # Length
-Þ # Sort by (tiebreak) product
P # Product
Ḣ # Get the first item.
```
[Answer]
# [Python 3](https://docs.python.org/3/), 211 bytes
```
lambda l,n:min([z for x in c(chain(*[[*c(l,_)]for _ in range(len(l))]),n)if (sorted(chain(*x))==l)*(len({*map(sum,x)})<2)for z in x],key=lambda y:eval("*".join(map(str,y))))
from itertools import*
c=combinations
```
[Try it online!](https://tio.run/##NY7BbsIwEETv@QqLk9daVSppLwh/SRohY2xwsXcjx0UJqN@eOqjMcWfnzQxzuTC1C@m2ibp7xy22@IGffeP11xJNOp6MiEi7FEh2d@E5i0kEElbai6k31XXKyogH6FfvsHrZ0NnJ6EhGgB6QIHghR87FnV6xCUDrCOr59lDJDHL8STjBL@y3sKLuK2rq8epm/T9k3rmbiXKjNm/fXCnPVMk4Q1XjMycRisuFOY4ipKE2qsZqy@kYyJTANC5DDlSkr5MJYPkD "Python 3 – Try It Online")
@tsh's method is too complex for me, so my own itertools based solution
[Answer]
# [Python 3](https://docs.python.org/3/), 143 bytes
```
f=lambda a,p,u=[],v=[]:p<2and a or a and min(f(a[1:],p,a[:1]+u,v),f(a[1:],p,u,a[:1]+v),key=len)or sum(u)==sum(v)/~-p==sum(f(v,p-1))and u or u+v
```
[Try it online!](https://tio.run/##lY7LCoMwEEX3/YpZGhxp46Ot0nyJuEhRqVRjsCbgpr9uR@yLUqGFyWS4c@5N9NCfWhWMYylq2RxzCRI1GpFmaKkl@uBLlYOEtqM2jU2lnNKRKU8yImWa8Mw1aBm@RHOXSTwXg6gLxch@MY1jmBDTbdn66ul5Lh2L2uOMTelmesi4dtRdpXrapRzBRwgQQoQIYYewR4gR@IYOz2jF2Op3OvyLjj7o2UC1fav4@yfm5OCRv8A@EX@pZsd4Aw "Python 3 – Try It Online")
```
f=(lambda
a, # input array, weight of packages
p, # how many groups
u=[], # packages selected in this group
v=[]: # packages not selected in this group
p<2 and a or # if we want only 1 group
# then we simply include everything to this group
a and min( # if there are any packages
f(a[1:],p,a[:1]+u,v), # we try to include it in current group
f(a[1:],p,u,a[:1]+v), # or try to exclude it in current group
key=len) or # find out the answer which is shorter
# otherwise, every package are processed
sum(u)==sum(v)/~-p # if sum of selected package is what we want
==sum(f(v,p-1)) # and remaining packages may be grouped correctly
and u or # We found a possible grouping
u+v # We failed to find out a correct grouping
# We return `u+v` here as it would be long enough
# to avoid it been selected after the min function
)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
.ŒʒOË}€`ΣP}éн
```
First input is the amount of groups, second the list of weights.
[Try it online](https://tio.run/##yy9OTMpM/f9f7@ikU5P8D3fXPmpak3BucUDt4ZUX9v7/b8wVbayjAEFGuFAsAA) (times out for the third test case with 5 groups, but works for the others).
**Explanation:**
```
.Œ # Get all possible ways to split the (implicit) second input-list
# into the first (implicit) input-integer amount of group-lists
ʒ # Filter this list of lists of group-lists by:
O # Get the sum of each inner group-list
Ë # And check if all sums are equal
}€` # After the filter: flatten the list of lists of lists one level down
ΣP} # Sort this list of lists by their product
é # After that sort again by their length
н # Pop and leave the first list
# (which is output implicitly as result)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 46 bytes
```
FEXηLθEηΦθ⁼λ﹪÷ιXηξηF⁼Σθ×η⌈Eι↨¹κFι⊞υ⟦LλΠλλ⟧I⊟⌊υ
```
[Try it online!](https://tio.run/##TY9PawIxEMXvfoo5TiA9WEEQb60tCC4s1Nuyh7CmZmh24@aP9dvHSRAxvEOYN@83M4NRfnDK5vzrPGCjLti6f@3RSDjo6RwNzkJIKAaXvslGNmcJX3NSNqBly52Sdbif4o6udNJIEp6MWwkbUR/UEY/gTxqZLOFIow6ls1E3GrlYJjHhQwWNSwl/r1kS0KZgMEnoHttZZrSeVxhi/dtebBetpynipwqRr7lgQ1NFp0La5tx1DGa9V61ftOklrPr8drV3 "Charcoal – Try It Online") Link is to verbose version of code. Very slow so only the smallest test case completes on TIO. Explanation:
```
FEXηLθEηΦθ⁼λ﹪÷ιXηξη
```
Loop through all possible allocations of presents to compartments (including redundant allocations such as switching the allocations of two compartments).
```
F⁼Σθ×η⌈Eι↨¹κ
```
If the largest compartment under this allocation has the correct share of the total weight, then...
```
Fι⊞υ⟦LλΠλλ⟧
```
... save the size and product of the compartment with the compartment.
```
I⊟⌊υ
```
Output the compartment with the smallest size and product.
For comparison I've written a relatively fast algorithm, however it's 89 bytes long. (8 bytes can be trivially removed, but this makes the code much slower.)
```
≔⟦Eηυ⟧ζ≔⟦⟧εW⌈⁻θεF№θι«⊞ει≔⟦⟧δFζFηF¬∨⊙…λμ№νι›×η⁺ι↨¹§λμΣθ⊞δEλ⎇⁼πμ⁺ξ⟦ι⟧ξ≔δζ»FζFι⊞υ⟦LκΠκκ⟧I⊟⌊υ
```
[Try it online!](https://tio.run/##dVDLTsMwEDw3X7HHtWQO0GNOJUIIiUIkeotysBJTW3Wcxg9Ii/j2sE6KgAPSSt5Ze8Yz2yjhml6Yadp4r/cWq604ouIQWc3hzPLse05QEnxX2kjArRh1Fzvcahs9DumOMXjtHWDRRxvSSNPkI1uV0SuUCebZ6pdam/DMOF@Y6nI@9QGfHW7sCYtTY2Sh@iMaDh3jsKjbWZ3DvZMiSIc73UmfbJeG7GgOt8JLvOawCQ@2lePCZonyQq6H1DKYnbUcUmR6sJPOCnfCuyEK4/G4fDgrjhwqXRMaifcTo11W9Jn9iaEvypFIj9Lug8JDEnJ9G5sw94eaaKXTFKUQPmBJAWmV80pj8pZPU1WtOSx181/RGtf1dPVmvgA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⟦Eηυ⟧ζ
```
Start with `n` empty compartments.
```
≔⟦⟧εW⌈⁻θεF№θι«⊞ει
```
Enumerate the presents in descending order. (This is the best I can do given a lack of a sort primitive in Charcoal.)
```
≔⟦⟧δ
```
Start building up a new list of allocations of presents to compartments.
```
FζFηF¬∨⊙…λμ№νι›×η⁺ι↨¹§λμΣθ
```
Loop through all of the compartments in all of the allocations, but ignore compartments when the same size present was already placed in an earlier compartment by a previous iteration or if it would overfill the current compartment.
```
⊞δEλ⎇⁼πμ⁺ξ⟦ι⟧ξ
```
Save the new allocation.
```
≔δζ
```
Save the new list of allocations.
```
»FζFι⊞υ⟦LκΠκκ⟧
```
At this point all of the presents will have been distributed to all of the compartments without overfilling any compartment, so flatten the list of allocations and get the size and product of each compartment.
```
I⊟⌊υ
```
Output the compartment with the smallest size and product.
[Answer]
# [Rust](https://www.rust-lang.org/), 348 bytes
```
|w:&mut[_],g|{fn p(w:&mut[u64],i:usize,g:u64)->Option<Vec<u64>>{Some(if w[i..].iter().sum::<u64>()==g{if i!=0{p(&mut w[..i],0,g)?;}w[i..].to_vec()}else{let mut r=vec![];for j in i+1..w.len(){w.swap(i,[i+1,j][j%2]);p(w,j,g).map(|x|r.push(x));}r.iter().map(|x|(x.len(),x.iter().product::<u64>(),x)).min()?.2.to_vec()})}p(w,0,w.iter().sum::<u64>()/g)}
```
[Try it online!](https://tio.run/##nVPJbtswEL37K@hDDRKdspatpLUUO5/QQ4FeBMJwHUqhYS3lUhmV9e0qqS0qEh9Sglpm5r03M9JQGqWbOEPpQWSYoGp25hrFaIuaaxksUqOjPYPkWllIgXuPufcZiMAo8YdDEliTfNp9K7TIs4cf/PhgHbtd9T1PORYxKiNBKaNCc4kJVSYNghaByXabVBYg5ttlVWAnbcGUCgZLSMhjWPdUne9/8yMmNT8rXrkCHVRurXMesTDOJTohkSHx0aO0pGduO6lKqspDgQVE1g0nFp0@rBgJbRNwsuo0tcHr5SppYdQzvhAS1nIoso/hS6cFlyFQyPzJHPXYAVgeTd2Xe6SrlzpJ7dIsoXyr688JqRtkVzhzd1c9LrlInrUClMjcFPZ5yFTJJXFdLaIW5xZuO/YArQCtAfmA7gB9AfQV0AaQt7SXx9pQC9y0NoH38v2e7/8n/67nezf5nYTd95O9mZTudc5bybv866GK13zfmVPy@OZWCxkFVrc2g39Ya3gtMoLXE3Cfl9nTNLjGoeXKnLU9XnE/792PH0dnmABCTVZKO4YkHDU6LlW51FP3QSku9Z7/muOnn8kcLzqclWrNfpJ6Qj2rm@Yv "Rust – Try It Online")
I think somebody should talk to Santa about time complexity.
Ungolfed:
```
|weights: &mut [_], group_size| {
fn permutate(weights: &mut [u64], i: usize, group_weight: u64) -> Option<Vec<u64>> {
Some(if weights[i..].iter().sum::<u64>() == group_weight {
if i != 0 {
permutate(&mut weights[..i], 0, group_weight)?;
}
weights[i..].to_vec()
} else {
let mut results = vec![];
for j in i + 1..weights.len() {
weights.swap(i, [i + 1, j][j % 2]);
permutate(weights, j, group_weight).map(|x| results.push(x));
}
results
.iter()
.map(|x| (x.len(), x.iter().product::<u64>(), x))
.min()?
.2
.to_vec()
})
}
permutate(weights, 0, weights.iter().sum::<u64>() / group_size)
}
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 20 bytes
```
◄Π←kLΣfËΣföEeO¹OΣπ²Ṗ
```
[Try it online!](https://tio.run/##yygtzv7//9H0lnMLHrVNyPY5tzjtcDeI2Oaa6n9op/@5xecbDm16uHPa////jf9HG@sYAaGxjomOYSwA "Husk – Try It Online")
Unfortunately too inefficient to run any of the provided test cases, but I *think* that it's correct based on testing with smaller ones:
```
[1,1,2,2,3] -> [3]
[3,1,2,2,4,0] -> [4]
[3,2,2,3,4,1] -> [4,1]
```
**How?**
`föEeO¹OΣπ²Ṗ` = Get all partitions, by filtering all combinations of n groups of all subsets of the input list (`π²Ṗ`), selecting (`fö`) only those that are equal (`Ee`) to the sorted input list (`O¹`) after flattening & sorting (`OΣ`). I thought that the [Husk](https://github.com/barbuz/Husk) `fork` (`§`) combinator should have saved a byte here, but I couldn't get it to work...
`fËΣ` = Filter (`f`) only those partitions with equal sums (`ËΣ`)
`←kLΣ` = Flatten the list of lists (`Σ`), and get the group of those with the smallest lengths (`←kL`)
`◄Π` = Return the list with the smallest product.
[Answer]
# Python 3, 229 bytes:
```
f=lambda l,i,s,c,j:[(j,c)] if sum(c)==s else(l and f(l[:-1],i-1,s,c+[l[-1]],j+[i])+f(l[:-1],i-1,s,c,j))
y=lambda p,g:[q for w,q in f(p,len(p)-1,sum(p)//g,[],[]) if f([m for n,m in enumerate(p)if n not in w],0,sum(p)//g,[],[])][0]
```
[Try it online!](https://tio.run/##lY7BboMwEETv/Yo92mKiQEiaBIkvsXygxKRGxjhAFPH1xA5FqpJWaqXxwbtvZseNw2dr04PrpqnKTdF8nAoy0OhRos4Eq1FySbqi/tqwkud5T8r0ihkq7IkqZkS2SiT0KgmWSBjhvxJ1JLTk0fMeNedv43LH4ZyJC1VtRzdcSFuf52CUZY4H3l90fL0@Q0gvHlpUTDQPg0UTDMpeG9UVg/KkX1uy7RDmN4n4JUCKWE6u03ZgIxMJaANKQVvQDrQHHUBHUBL75ytT6rv@nd7@i9490bPB6/2bjj@XmJPTJf8XdrOwr/pyz47pDg)
[Answer]
# TypeScript Types, 957 bytes
```
//@ts-ignore
type a<N,I=0,M=[]>=N extends M["length"]?M:a<N,I,[...M,I]>;type b<T,N=[]>=T extends[infer A,...infer T]?b<T,[...N,...a<A>]>:N;type c<T,S,G=[],U=T>=S extends[]?G:U extends U?S extends[...U[1],...infer S]?c<Exclude<T,U>,S,[...G,U]>:never:0;type d<A,B,N=[]>=A extends[...B,...infer A]?d<A,B,[...N,0]>:N;type e<T>={[K in keyof T]:T[K][1]};type f<T,N,S,G=[]>=N extends[0,...infer M]?c<T,S>extends infer X?X extends X?f<Exclude<T,X[number]>,M,S,[...G,e<X>]>:0:0:G;type M<I,N,M=a<N>,S=d<b<I>,M>,A=f<{[K in keyof I]:[K,a<I[K]>]}[number],M,S>[number],R=i<k<j<A>>>>={[K in keyof R]:R[K]["length"]};type g<A,B,C=[]>=A extends[0,...infer A]?g<A,B,[...C,...B]>:C;type h<T,N=[0]>=T extends[infer A,...infer T]?b<T,g<N,A>>:N;type i<T>=(T extends T?(x:()=>T)=>0:0)extends(x:infer U)=>0?U extends()=>infer V?V:0:0;type j<U,V=keyof U>=U extends U?keyof U extends V?U:never:never;type k<T,V=keyof(T extends T?h<T>:0)>=T extends T?keyof h<T>extends V?T:never:never
```
This really pushes TypeScript's type system to the limit. Calling the generic will give "Type instantiation is excessively deep and possibly infinite", but it will eventually still result in a valid answer for most test cases.
[Try It Online!](https://www.typescriptlang.org/play?#code/PTACBcGcFoEsHMB2B7ATgUwFDgJ4Ad0ACAQwB4A5AGgEkBeABkoFlaBtAXQD5bzD0APcOkQATSISasARABth8cAAsp7APxMAXGSrVKrAHSGmNLgG5cBQgCNSAFUrk2XWrb6DhY1rEQAzdKkIAQUpDfW8-ANs1G3sDQypQskDOLg1yc3wiAGM7SgBlSgBxJ0oAVRduPLchUUgOVUKNUuqPcVLVKoEaz1DS1gBGdhDDcP9CPLUcgFF+LJkAVxF0XNLOfL1QwrLUxHQAN38NegzLEVJggCEHJ25Altq4-SvQ0YDAtTPLjfjKelT0ixEZa2bgAb1YAGlCN5CABrdA4ZA+QhRDS2SHsAbsAC+JyIPlyVAKxQ43F4XVarEYL18YyYk1yeU4FNq0NpAQAGqoOfcxIQuQSZnNFsDKBzWIh5gBbKz+LjMdaPLbLDkpThHDWFPESUi6KgsbRrPK0M42ahrJhrQK0AngqEw+GI5HUdgaSGUMjUDEpbES6Wy1BDYxMv0yuWUABKtFgpFhpAAVudOMmwZC2XCEUjCBHXRGMdI5IgFMocdr4OdKFcAMI3Wh3FmeakjdlBNTlr6PKvDJ6pKvaxSEth-biuBt1V5BbsTqKqGKUctUZLqgGZaF2bgAClH7lZtlUG-4Gg3AEpaJxbKfOPQjsexweNBPSpf6KpmnfLxOAGqqT8a46AwhE1KShP1oR0s1WWg3x3Pl2nA5FoO6cRv1KDRdgOVA0P2fxtTjexQPgrdeXEPcBxBG8R2IlFVHgwgyOZGDkNUWwsIw1j-EwTAQEIC4iDwYhwFgYRwAAQk47iIBgBAUAwbBV1cWgdQGShCAAJhUgBmFSABYVIAVhUgB2FSAA4VIAThU-pGEIfpBk0zguOAQgXIAPVUTAgA)
[Less Golfed](https://www.typescriptlang.org/play?#code/C4TwDgpgBAcgrgWwCoHslzAGwgHhgGigEkoBeKABkIFkyoBtAXQD46YoIAPYCAOwBMAzlGr0ARNl4BzYAAsxjAFBQoAfhHKoALliJU6LLgLFC9AHQXqhIiwDcixaEhQAyohxJC7ck1bkkHNx8QgwAlrwAZhAATlAAgoQWZuFRsUhKKupuCB6mScb5emgY2DhxzCyaOjD2juDQAGLh-ADi0SgYua6ELXRMhACqdEh+roE8AsJMmuotVVBDXBMhAzNjS8FTSQP0AIyMiRYpMa4ZKmpQTQJtHWA4AKKcAMaYcPy4ngvMhC55Fi2DSrnbRQXgQABuMXmFFqTmgABFQuDQu8yoQAEJePosOhxcabBhJTFQJLHWJxM7qRHI1EJKDE8wWYwUIEgmoOOGXUKcG6dEZ0ADeDAA0lBwlAANYQEAoCJQdI6JD0YWMPaMKAAX3snLimEwvLA4Skgi6xl+UF6Phx5HYG0mDCoJKOkRO1EpXOu7T5P1YdpCZKgAA1NJkg-j7cHgaHdfqvYbpCbHi83h9CIH6LxEAAjGIsGg-P5mAFcnlxnCBirMEPnHQUau1+YtWH1EQAQ3COE0RHwmgImloNqKBlKMG+mhcdGpKNw2RwRG+IjHKjx5BjBqNJurAurKmVYt4kulsuIjB0yq8Q5KuCIypYjHswI1GezuZ7wKs1ZcmmYz4QOeiByaAASnQAAKKBgAMvChCgvA4AAMhAraCMAoHtPwcBPMAOAuLIKDRDwKFlMwJGKKMQp7uKUoynKQGnlAQG3uIkgyPI6pahyLbUHAmDDhAJp0sSADC2KjHifpTI6pIuuS7rcbxV4CRihZCYcZjoqyOhCdqLZoSgGFYaafQsqMAQSWEMnxGpAbpGss6fPJfEmsY5RVio1TNs44GQdBsEeKMAAUZlBPaATqAFnA6AFACUZCsEgsWkKwFAghQsXmQFmiRfuqQLIoiXJWsiwhSEMVxTlJwAGrVuo1XAg27mUJ50C4fhhHYQMhCVXQ1HHgMozFcswirKGvVyoNBJ1ec6gjTWoIQlCjVgpC0TNVAiHIah6GYdhnzdeQY1QEF4YhGFUB6QZu2sLW0WmSdwhIGsh0XTt-n3VAU2ho99XzSt8zLTE9hAA) (but just as cryptic)
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 143 bytes
```
(w,g)->p=vecprod;s=vecsum(r=w)/g;forperm(vecsort(w),a,for(k=q=!c=0,#a,c+=a[k];c%s||q++>2||b=Vec(a[1..k]));#b==#r&&p(b)<p(r)||#b<#r&&q>g&&r=b);r
```
[Try it online!](https://tio.run/##jY3haoNAEIRfZRup3OKaRpO0DWZ9jP45/HFeVYKmnmdaKdy7W21IKYHQwizsznzMGmUPYWXGEngUA1UYpoY/Cm1s@5r089a/H4XlAR@qpGytKexRzG5rT2JAUjSZouaO7zSvyFOkA1ayzhJ93zvXBUEaO5fzS6GFktFyWWeIiZcze9b3jchxb4RF57x8PztdWvm@5RwTOypjmk@hIEzB2MPbaVoX87EArZpGlAQKkUBKGRHEBGuCDcGW4IngmWBHEK2mibIpymbuT2zzP2x7wc7kpMdf2l39O3etL43X0E8W39I3muH4BQ "Pari/GP – Try It Online")
TIL: the `forperm` built-in only works for sorted lists. Thanks [@tsh](https://codegolf.stackexchange.com/users/44718/tsh) for providing a new testcase.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 26 bytes
```
ṖvøṖÞf'L⁰=;'Ṡ≈;vhƛ₍LΠwJ;↓Ṫ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuZZ2w7jhuZbDnmYnTOKBsD07J+G5oOKJiDt2aMab4oKNTM6gd0o74oaT4bmqIiwiIiwiWzEsIDIsIDMsIDRdXG4yIl0=)
This was horrible to make. Vyxal is horridly cursed sometimes...
Note: Almost all sort-related functions are broken.
\$O\left(n! \cdot 2^n\right)\$ complexity I think, so can't run any testcases.
```
Ṗ # All permutations
vøṖ # All partitions of these
Þf # Flatten by 1 layer to get all partitions of permutations
' ; # Filter by...
L⁰= # Length is equal to input
' ; # Filter by
Ṡ≈ # Sums are all same
vh # Get first of each
ƛ ; # Map to...
₍LΠ # [length, product]
wJ # Appended to original
↓ # Minimum by last item ([length, product])
Ṫ # Remove the last of this.
```
[22 byte version if sorting worked](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuZZ2w7jhuZbDnmYnTOKBsD07J+G5oOKJiDvCtWjigo1MzqA7aCIsIiIsIlsxLCAyLCAzLCA0XVxuMiJd)
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~181 144 140~~ 129 bytes
```
->l,n{*r=l;(n**l.size).times{|x|z=l.group_by{(x/=n)%n}.values;z.map(&:sum).uniq[1]||r=(z<<r).min_by{|x|[x.size,x.reduce(:*)]}};r}
```
[Try it online!](https://tio.run/##jY3ZCsIwEEXf/Yp5UZIyRlvXLvFHShGXKIU01tRI7fLttSouIIJw5@mee0ab9aXZ8aa/kKhKS3PpE2VZkmVxISg7xYnIyiqvCi7ZXh9MulxfSpIPuKJdVbPzShqR@QVLVinpeZlJKDMqPoZ2VFWakyIINGVJrG6zVhPmdzHmTIut2QjiWTSqa1/XTQq7MLQRHIQRwhhhgjBDmCO4CPawPTtqq6jzHzj@F5y8wQfbZvoR9@vrwzd6Wr@xV@v8yh1urg "Ruby – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 88 bytes
```
<<Combinatorica`
SortBy[Join@@Select[KSetPartitions@##,Equal@@Tr/@#&],1##&@@#+0#&][[1]]&
```
[Try it online!](https://tio.run/##jY3NisJAEITveYqGhlxs2Yz/QnZpFC96EbK3YcBRIjtgMji2Bwl59jggorAXoerQVR/VlZW/srLiDrbr8nzpq72rrfgQg11y/C58kMVNr72rmYvyVB5Eb4pStjaIE@frCyPS6ny1J@bf8MWYGlKIKTP2snhorYxJu21wtegGsYX@Dxw1ojGQAjMn0DSNIhgQDAlGBGOCKcGMYE6gsmjVxqqlBOADcPQpOH6BDzZq8qb5v6@PveFz9R1ruzs "Wolfram Language (Mathematica) – Try It Online")
] |
[Question]
[
Related: [Is this quadrilateral cyclic?](https://codegolf.stackexchange.com/q/176162/78410)
## Background
A [tangential quadrilateral](http://mathworld.wolfram.com/TangentialQuadrilateral.html) is a quadrilateral which has an incircle:

Examples include any square, rhombus, or a kite-like shape. Rectangles or parallelograms in general are not tangential.
## Task
Given the four vertices of a quadrilateral (as Cartesian coordinates), determine if it is tangential.
## Input & output
For input, it is allowed to use any format that unambiguously specifies the four vertices' coordinates (eight real or floating-point numbers). You can assume the following on the input:
* The points specify a simple convex quadrilateral, i.e. all internal angles are strictly less than 180 degrees, and the edges meet only at the vertices.
* The points are specified in counter-clockwise order (or the other way around if you want).
For output, you can use one of the following:
* Truthy/falsy values as defined by your language of choice (swapping the two is allowed), or
* Two consistent values for true/false respectively.
It is acceptable if your code produces wrong output due to floating-point inaccuracies.
## Test cases
### Tangential
```
(0, 0), (0, 1), (1, 1), (1, 0) # unit square
(-2, 0), (0, 1), (2, 0), (0, -1) # rhombus
(1, -2), (-2, -1), (-1, 2), (4, 2) # kite
(0, 0), (50, 120), (50, 0), (32, -24) # all four sides different
```
### Not tangential
```
(0, 0), (0, 1), (2, 1), (2, 0) # rectangle
(0, 0), (1, 1), (3, 1), (2, 0) # parallelogram
```
## Scoring & winning criterion
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~11~~ 10 bytes
```
5:)d|2e!sd
```
Input is a vector of four complex numbers. Output is `0` (which is falsy) if tangential, or nonzero (which is truthy) if not tangential.
[Try it online!](https://tio.run/##y00syfn/39RKM6XGKFWxOOX//2hDXaMsHQVdI13DLAVdQ20QxwRIxgIA) Or [verify all test cases](https://tio.run/##y00syfmf8N/USjOlxihVsTjlv0vI/2gDbYMsHQUDbcMsBUMgoQMkDbJiuaJ1jeASOgpQtq4hSMZQ1wjI0TUC8hR0DbVBHBMgCZSBmGUK1GMEZYAoYyNdIxOENMxEmLlwCYj1xggJBQA).
### Explanation
The code computes the difference between sums of lengths of opposite sides. This difference is zero [if and only if](https://en.wikipedia.org/wiki/Tangential_quadrilateral#Characterizations) the quatrilateral is tangential.
```
5: % Range [1 2 3 4 5]
) % Implicit input: complex vector of length 4. Index into it modularly.
% This repeats the first vertex after the last
d % Consecutive differences
| % Absolute value, element-wise
2e % Reshape as a 2-column matrix, in column-major order
! % Transpose
s % Sum of each column. Gives a vector of length 2
d % Consecutive difference
```
[Answer]
# [Python 3](https://docs.python.org/3/), 47 bytes
```
f=lambda l,i=3:i+1and abs(l[i]-l[i-1])-f(l,i-1)
```
[Try it online!](https://tio.run/##dZBNasMwEIX3OsXgTSVqBSvuKuBtLxG8GCeyI6ofV5KhScnZXcmG1NB0Mzy9mW8eo/EaL87W89w3Gk13RtClauqDehVoz4BdoPqoWp4KFy3jPU19Lth8a07OjFp@kShDDNDAkQClN1qVULESFiEWITaiYkkVk1URwueEXhasXDm@/wNunZSZSX9xppvCg0or@X6ZyTxfOZ7c1XzLInMfKv5GVc@SNpEZGKSVHjV4eYpoB/2EftxV/0uPmKqW2g0eTd7Qkt55yF9WgkUjQdnlFQ4ERq9spH3xniYQvnP7Diq@hKRdhJ7mQXbfFYzMPw "Python 3 – Try It Online")
Take complex number input. Outputs as Truthy/Falsey swapped. Test cases [from Noodle9](https://codegolf.stackexchange.com/a/197715/20260).
---
**48 bytes**
```
lambda a,b,c,d:A(a-b)+A(c-d)-A(b-c)-A(d-a)
A=abs
```
[Try it online!](https://tio.run/##dZDBbsMgEETvfMXKl0ALlZ30FMkHX/ITbQ@LjR2rGFzAUpsq3@6CLaWWml5gGObtCMavcLbmMLfl66xxkA0Ccslr3hwrikKyx4rWomGiolLUaWsEMlKVKP18KWs7jFp9kqB88FDCCwFKLzTnkDMOiygWUWxEzqLKJtMH8B8TOpUxvnJi/wfcOqJYSHe2g5z8jYojxX7JJF6snIjuaj4nkbj3PvxW5feaNpUJ6JRRDjU4VQc0nb5D3951@JceMa5aads5HNKEN9JaB@nLOBgcFPRmOfkjgdH1JtA2O8UEwne6vkIfdj5qG6ClDynJrk8ZI/MP "Python 3 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~89~~ \$\cdots\$ ~~59~~ 55 bytes
```
lambda l:sum((-1)**i*abs(l[i-1]-l[i])for i in range(4))
```
[Try it online!](https://tio.run/##dZBNboMwEIX3nGLEpjbCFSRZRWLbS6QshtQQq/6htpHaVDk79YCUIjXd2E/P88143vgVL87u5755nTWa7g1BH8NkGBM1LwpVYBeYPilRtyJdLe@dBwXKgkc7SHbgfL42Z2dGLT@zKEMM0MApA8aurCqh4iUsol5EvREVTyqfrIoQPib0MuflyondH3DrpJ8R6S/OdFO4U6ml2C01xIuVE8ldzQMJ4t5V/B1VPZq0GUnAIK30qMHLc0xL6wf0fa/9v/SI6dRSu8GjoQ5tRllSZCVYNJJCXQI8ZjB6ZSPr85dUgfBNzzdQ8Skk7SL0jAr57Tnn2fwD "Python 3 – Try It Online")
A list of vertices as complex numbers is passed in. The lengths of the sides \$(a, b, c, d)\$ are calculated and uses \$a+c=b+d\$ for a tangential quadrilateral. Returns's a falsy value (0) for a tangential or a truthy value (nonzero) otherwise.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 bytes
```
ṁ5ạƝŒœ§E
```
[Try it online!](https://tio.run/##y0rNyan8///hzkbTh7sWHpt7dNLRyYeWu/4/OunhzhnWjxrmKOjaKTxqmGt9uJ3rcNvD3d2H2x81rYn8/z@aK1rDQEfBQFNHAUQbgmgjBG2gGaujoKCsUJSaXJKYl56TiqTcEKrMGFN5QWJRYk5Oak5@elFiLhYbDBE0TEtpXmaJQnFhaWIRyA5dI0w3wfi6hjBHZeTnJpUWA5UDzdE1AkmD9OmCNegCxcBCJiA6FqQ@O7MklSsWAA "Jelly – Try It Online")
## Explanation
```
5ị€ | Modular index 1,2,3,4,5 into list
ạƝ | Absolute difference of neighbouring pairs
Œœ | Split into odd and even indices
§ | Sum of inner lists
E | Equal
```
A monadic link taking a list of complex coordinates and returning 1 for tangential and 0 for not.
Based on [@LuisMendo’s MATL answer](https://codegolf.stackexchange.com/a/197714/42248) so be sure to upvote that one!
Thanks to @JonathanAllan for saving a byte!
[Answer]
# JavaScript (ES6), 74 bytes
Takes input as a list of coordinate pairs. Returns \$0\$ (falsy) for tangential or a non-zero value (truthy) for non-tangential.
```
a=>(g=_=>Math.hypot(([x,y]=a[i],[X,Y]=a[++i&3],x-X),y-Y))(i=0)-g()+g()-g()
```
[Try it online!](https://tio.run/##lZDLbsMgEEX3@QpWNciQ@JEuyR@kqy4SuaiiLrFpCLgYV/HXu2CljdPIiyKhOwy6Zx4f/Iu3pZWNI9q8i@FAB043sKKvdLPlrl7WfWMchMUZ94zyQjJc7PA@hHEsH3KGz2SHcE/2CEFJE0QqiGJ/gw6l0a1RYqlMBaNnriuhneQqQovpzwEWRYJBwjAImgZNr5owhhC4nNUKdFo60H523Io7DMn@cCZvkl5BHmNrc3rr2juEr0iyYAksMkKIz42pddALxCOO0onZSR5DC9lvOAZ5QGbrgFjcGKMX/WQccP9ZUTYd8XZFVpQBpea7@9lvPg9puOVKCe@0/DR8Aw "JavaScript (Node.js) – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~17~~ 11 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319)[SBCS](https://github.com/abrudz/SBCS)
-6 bytes thanks to [Bubbler](https://codegolf.stackexchange.com/users/78410/bubbler)
outputs 1 if tangential, 0 if not
```
0=-/|2-/5⍴⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO94L@ufo2Rrr7po94tj/qmgoT@P@qdqxCSmJeemleSmZijkJxYnFrMpQAGBVwGWQYKBlmGCoZgbAAXP7TeCCoDoQ@tN4TLGQJ5RgogFUBRIG2YZaRgkmWEYqYpUKsRmDJQMAYpNDLh4gK5xC8/T6GEkGuMIPaiiINcaAwRBwA)
Explanation:
```
0=-/|2-/5⍴⎕
⎕ take 4 complex numbers as evaluated input
5⍴ reshape to 5
2-/ difference between each pair of numbers
| absolute value
-/ alternating sum
0= the quadrilateral is tangential if the final result is 0
```
## Previous answer
```
=/+/⍉2 2⍴|2-/5⍴⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO94L@tvrb@o95OIwWjR71baox09U2B9KO@qSDZ/4965yqEJOalp@aVZCbmKCQnFqcWcymAQQGXQZaBgkGWoYIhGBvAxQ@tN4LKQOhD6w3hcoZAnpECSAVQFEgbZhkpmGQZoZhpCtRqBKYMFIxBCo1MuLhALvHLz1MoIeQaI4i9KOIgFxpDxAE "APL (Dyalog Unicode) – Try It Online")
Explanation:
```
=/+/⍉2 2⍴|2-/5⍴⎕
⎕ take 4 complex numbers as evaluated input
5⍴ reshape to 5
2-/ find the difference between each pair of numbers
| absolute value
2 2⍴ reshape to 2x2 matrix
⍉ transpose
+/ sum the rows
=/ are they both equal?
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 24 bytes
Returns `Sphere` if the quadrilateral is tangential, `Insphere` if it is not.
```
Head@Insphere@Polygon@#&
```
[Try it online!](https://tio.run/##XY4xD4IwEIX/yiUkTFwsBUdNR9xwJgyNFiGRYrAOpulvr1wNAk7v3ct3966XplW9NN1F@gYOvlDyKk76@WjVqEQ53N@3QYso9uXYaVNFgEc4vzplRFNFdQ0x7ARYa1kCzCVAmpKmizJHxiL/Q1Yzpl9mopGTIxgDhVMWopw0UHPXni7xnw0mo0Web8FV49K8IeZ3sw3hvP8A "Wolfram Language (Mathematica) – Try It Online")
---
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 38 bytes
Returns `True` if the quadrilateral is tangential, `False` if it is not.
```
0=={1,-1,1,-1}.Norm/@(#-RotateLeft@#)&
```
[Try it online!](https://tio.run/##XY7BCoMwDIZfJVCQDdrZVnd09AHG2HYVD2VU5kEFyU6lz96ZglN3yf8nfMmf3uLb9Ra7l40tVFFWlVdcKE4lnG7j1OfmwMRzRIvu6lo07JjF@9QNWDMQF3h8OoemrVnTQAa5Ae@95CADB1JFqlaVgYwX@g/Z9HNwYmZaaHIEi0TNj0EalaSJWrLOdEn/bDIFLepyD24S1@Qdsbxb7IgQ4xc "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
```
ĆüαnOtιOË
```
[Try it online!](https://tio.run/##yy9OTMpM/W/m5mKvpGBrp6Bk//9I2@E95zbm@Zec2@l/uPu/zv/oaAMdBYNYHQUQbQiiDRG0QWwsV3S0rhGaCiS@riFYCVCtrhFICKRWF6xIFygGFjIB0SBFMItMQeYYwZlghjFIn5EJijok6xDWIiuAudQYRQEA "05AB1E – Try It Online")
Port of [Nick Kennedy's Jelly answer](https://codegolf.stackexchange.com/a/197718/6484). It turned out pretty short, despite 05AB1E's lack of complex numbers.
] |
[Question]
[
## Introduction:
*I have loads of different ciphers stored in a document I once compiled as a kid, I picked a few of the ones I thought were best suitable for challenges (not too trivial, and not too hard) and transformed them into challenges. Most of them are still in the sandbox, and I'm not sure yet whether I'll post all of them, or only a few. But here is the first of them to start things of.*
---
A Computer Cipher will encipher the given text into 'random' character groups of a given `length`. If such a group contains a digit, it will use that digit to index into its own group for the enciphered character. If no digit is present in the group, it means the first character is used.
For example, let's say we want to encipher the text `this is a computer cipher` with a given length of `5`. This is a potential output (note: numbers are 1-indexed in the example below):
```
t h i s i s a c o m p u t e r c i p h e r (without spaces of course, but added as clarification)
qu5dt hprit k3iqb osyw2 jii2o m5uzs akiwb hwpc4 eoo3j muxer z4lpc 4lsuw 2tsmp eirkr r3rsi b5nvc vid2o dmh5p hrptj oeh2l 4ngrv (without spaces of course, but added as clarification)
```
Let's take a few groups as examples to explain how to decipher the group:
* `qu5dt`: This group contains a digit `5`, so the (1-indexed) 5th character of this group is the character used for the deciphered text: `t`.
* `hprit`: This group contains no digits, so the first character of this group is used implicitly for the deciphered text: `h`.
* `osyw2`: This groups contains a digit `2`, so the (1-indexed) 2nd character of this group is the character used for the deciphered text: `s`.
## Challenge:
Given an integer `length` and string `word_to_encipher`, output a [random](https://codegolf.meta.stackexchange.com/a/1325/52210) enciphered string as described above.
You only have to encipher given the `length` and `word_to_encipher`, so no need to create a deciphering program/function as well. I might make a part 2 challenge for the deciphering in the future however.
## Challenge rules:
* You can assume the `length` will be in the range `[3,9]`.
* You can assume the `word_to_encipher` will only contain letters.
* You can use either full lowercase or full uppercase (please state which one you've used in your answer).
* Your outputs, every group, and the positions of the digits in a group (if present) should be uniformly [random](https://codegolf.meta.stackexchange.com/a/1325/52210). So all random letters of the alphabet have the same chance of occurring; the position of the enciphered letter in each group has the same chance of occurring; and the position of the digit has the same chance of occurring (except when it's the first character and no digit is present; and it obviously cannot be on the same position as the enciphered character).
* You are also allowed to use 0-indexed digits instead of 1-indexed. Please state which of the two you've used in your answer.
* The digit `1` (or `0` when 0-indexed) will never be present in the output. So `b1ndh` is not a valid group to encipher the character 'b'. However, `b4tbw` is valid, where the `4` enciphers the `b` at the 4th (1-indexed) position, and the other characters `b`,`t`,`w` are random (which coincidentally also contains a `b`). Other possible valid groups of `length` 5 to encipher the character 'b' are: `abcd2`, `ab2de`, `babbk`, `hue5b`, etc.
## 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:
Length: 5
Word to encipher: thisisacomputercipher
Possible output:
qu5dthpritk3iqbosyw2jii2om5uzsakiwbhwpc4eoo3jmuxerz4lpc4lsuw2tsmpeirkrr3rsib5nvcvid2odmh5phrptjoeh2l4ngrv
Input:
Length: 8
Word to encipher: test
Possible output:
ewetng4o6smptebyo6ontsrbtxten3qk
Input:
Length: 3
Word to encipher: three
Possible output:
tomv3h2rvege3le
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 125 bytes
```
->\n{*.&{S:g{.}=(65..90)>>.chr.roll(n).join.subst(/./,$/,:th($!=roll 1..n:)).subst(/./,$!,:th($!-1??(^n+1∖$!).roll!!n+1))}}
```
[Try it online!](https://tio.run/##TcxBCoJAGAXgfadwRHT@0t8klDLUQ7SNoGRMQ0eZGRci7jtBB@wiVtrC5Xt87zVMlMFYdWamRdroxGfer9HsT@G9xyGigY942EIcY5oLFHVZUg74qAuOsr1JRV10bcO1Q5VTg0Q/oHmIPARYAvIHjpck9MI33vv5MghMh4R8M8AwjPLaaRn1geoqL2Qhr2ldNa1iIi2anAkd2xSOq1ntgVqKSWUty900FYzNdPwA "Perl 6 – Try It Online")
Takes input and output in uppercase. Takes input curried, like `f(n)(string)`. Uses 1 indexing.
### Explanation:
```
->\n{*.&{ ... }} # Anonymous code block that takes a number n and returns a function
S:g{.}= # That turns each character of the given string into
.roll(n) # Randomly pick n times with replacement
(65..90)>>.chr # From the uppercase alphabet
.join # And join
.subst( ) # Then replace
/./, ,:th($!=roll 1..n:) # A random index (saving the number in $!)
$/ # With the original character
.subst( ) # Replace again
/./,$!,:th( ... ) # The xth character with $!, where x is:
$!-1?? # If $! is not 1
(^n+1∖$!).roll # A random index that isn't $!
!!n+1 # Else an index out of range
```
[Answer]
# Pyth, 22 bytes
```
smsXWJOQXmOGQJdO-UQJJz
```
[Try it online.](https://pyth.herokuapp.com/?code=smsXWJOQXmOGQJdO-UQJJz&input=5%0Athisisacomputercipher&debug=0)
Uses lowercase and zero-indexing.
### Explanation
Very straightforward algorithm.
```
Implicit: read word in z
Implicit: read number in Q
m z For each char d in z:
OQ Choose a number 0..Q-1
J and call it J.
m Q Make an array of Q
OG random letters.
X d Place d in this string
J at position J.
W If J is not 0,
X J place J in this string
O at a random position from
UQ 0..Q-1
- J except for J.
s Concatenate the letters.
s Concatenate the results.
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~187~~ ~~177~~ ~~176~~ ~~156~~ ~~154~~ 148 bytes
```
lambda l,s:''.join([chr(choice(R(65,91))),c,`n`][(j==n)-(j==i)*(n>0)]for c in s for n,i in[sample(R(l),2)]for j in R(l))
from random import*
R=range
```
[Try it online!](https://tio.run/##bYzLDsIgEEX3fgW7gkHjIxo1qR/htjYRkco0ZSADXfj1FWKMG1d35t6TE17JetxMXX2dBuXuD8UGGU9Vtew9IG@0Ja6tB234he938rgWQkgtb3hrG97XNYpFCRBzjueVaDtPTDNAFlk5UUJ@mqhcGIpiEHLzgfoClULMOvKOkcJHDnDBU5rPLnUunmYKBJhYx3eyShYiRKW9C2MypCFYQ9VyDMEQz5ovesioienPsi0SMuY3TW8 "Python 2 – Try It Online")
Uses uppercase letters, and 0-indexed numbers.
-3 bytes, thanks to Kevin Cruijssen
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 135 bytes
```
n=>f=([c,...s])=>c?(g=n=>n?g(--n)+(n-p?n-q|!p?(r(26)+10).toString(36):p:c):'')(n,r=n=>Math.random()*n|0,p=r(n),q=r(n-1),q+=q>=p)+f(s):s
```
[Try it online!](https://tio.run/##FYuxDoIwFAB3/8Kp70nbgEYGTGFjc3I0Dk0LFQOvpSVO/DvidJdL7qO/Opk4hEWQt93Wqo1U3St4Gi6lTC9UtWnAqb1S40AIwgxIhIbEvB5DAxHOJWZFjnLxjyUO5OBSYhUqgxVjCMTjf77r5S2jJusnwBOtOQ8qAiGf/xDFLpmaaxUw6yFhlbbbwXhKfuzk6B20cEVgdtCTJ8sQtx8 "JavaScript (Node.js) – Try It Online")
Thank Arnauld for 1B
[Answer]
# [R](https://www.r-project.org/), ~~134~~ ~~132~~ 123 bytes
```
function(S,n,s=sample)for(k in utf8ToInt(S)){o=k+!1:n
P=s(n,1)
o[-P]=s(c(P[i<-P>1],s(17:42,n-1-i,T)))+48
cat(intToUtf8(o))}
```
[Try it online!](https://tio.run/##FYyxCsIwFAD3fEXt0vdoMkQKltoKKg5ugcapdijFQKi@SJNO4rfHOt4d3BxNUotoFhqDdQQtJ@4bP7zezwcaN8OUWEqWYErtrhSgRfy4Zso3siKmGg/EJTLXCdWvMILqbC3UQfbcg9xVxZaTkMJyjYh5UbJxCGApaHdbl@AQv9FAejydU17g/l@zO2XIVqkvrU55ifEH "R – Try It Online")
Takes uppercase letters.
Explanation of old code (mostly the same approach):
```
function(S,n){s=sample # alias
K=el(strsplit(S,"")) # split to characters
o=1:n # output array
for(k in K){ # for each character in the string
P=s(n,1) # pick a Position for that character
o[-P]= # assign to everywhere besides P:
s( # a permutation of:
c(P[i<-P>1], # P if it's greater than 1
s(letters,n-1-i,T))) # and a random sample, with replacement, of lowercase letters
o[P]=k # set k to position P
cat(o,sep="")}} # and print
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), 193 bytes
```
s->n->s.flatMap(c->{int a[]=new int[n],i=n,x=0;for(;i-->0;)a[i]+=Math.random()*26+97;a[i+=Math.random()*n+1]=c;x+=Math.random()*~-n;if(i>0)a[x<i?x:x+1]=48+i;return java.util.Arrays.stream(a);})
```
[Try it online!](https://tio.run/##ZVHBTuMwEL3zFSNODk2swrILrEkQFyQOPXGscphNnWa6iR3Zk5IKdX@9OGlWauFijd97nnnzvMEtJpvV3wM1rXUMm3CXHVMty84UTNbIK3XxjfTsNDYDVdToPSyQDHxcAHhGpgJepsePr4bfRm0cqu9olkEJ6cEnmUkyL8saeYGtKJLsgwwDLvPU6HcI9dLkMaUm7tO5Kq0TipIkm6sIl5TP0gVyJR2alW1EdHXza/ZwpwLzlTCz6zwtVP8V/5cYRaWgbB769Y/01P/uB@nt/YyU09w5c7L8s3O481MGAiO1jw4q7N52f@qw@xTB1tIKmpCLCKuSWS9zQLf20RgTAGvP4pIr8uSxsE3bsXYFtZV2lzH8jNSpKpwBvD8HK6d1QH@M6H6Y72iLrM8MjNqjAXi3bhUPWUKtzZqr/1aGdHMoKnQeUigltm29E4NajqCIogmb3km2YwZiMvS286wbaTuWwYPh2ojh145jxdgjnsfHCXLqMbneHz4B "Java (JDK) – Try It Online")
* The index are 0-based.
* This entry uses an `IntStream` (gotten through `String::chars`) as input, as well as a number and returns another `IntStream`.
* Casts from `double` to `int` are unnecessary because of the `+=` hack.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 29 bytes
```
;£=VöJ;CöV hUÎX hUÅÎUÎ?UÎs:Cö
```
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=O6M9VvZKO0P2ViBoVc5YIGhVxc5Vzj9VznM6Q/Y=&input=ImlucHV0Igo1Ci1R)
Zero-indexed.
Explanation:
```
; :Set C = [a...z]
£ :For each character of the input:
=VöJ; : Get two different random indexes from [0,length)
CöV : Get 5 random letters
hUÎX : Replace one at random with the character from the input
hUÅÎ : Replace a different random character with:
UÎ? : If the input character was not placed at 0:
UÎs : The index of the input character
: : Otherwise:
Cö : A random letter
:Implicitly join back to a string
```
[Answer]
# C, 115 bytes
```
g(_,n)char*_;{int i=rand(),j=i%~-n,k=0;for(i%=n;k<n;k++)putchar(k-i?!i|i<k^k-j?rand()%26+97:48+i:*_);*++_&&g(_,n);}
```
[Try it online!](https://tio.run/##bU3dDkMwGL33FCYhrVZi/6bEm6xpuo5Po6TsyuzVjcjudnEuzr@MSilnMIPbCDAIu6PjlsgbKuihF7JtutegrISuUtajZ8wcd1FkJSzaxytbw6ofPJr89yqrlEePC53mEnFq8BoIORvXU8itMA@EaZ2D/4kM1XnMnq1F4OeG6WwBIfi3qiModvCGTN91VBdb1T9cyO2anhICacgxCwnhQbBdsWmevw)
0-indexed, lowercase.
Slightly ungolfed and expanded:
```
g(char*_,int n) {
int i = rand(), j = i%(n-1), k = 0;
for(i = i%n; k<n; k++)
putchar(k!=i ? i!=0 || k==j + (k>i)
? rand()%26 + 'A'
: i + '0')
: *_);
if (*++_!=0) g(_,n);
}
```
The code should be pretty straightforward.
The two randoms `i`,`j` generated in one `rand()` call are good as independent since gcd(`n`,`~-n`)=1 and `RAND_MAX` is large.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 169 bytes
```
StringJoin@Table[While@FreeQ[a=RandomChoice[Alphabet[],#2],c];If[(p=Position[a,c][[1,1]])!=1,a[[RandomChoice@Complement[Range@#2,{p}]]]=ToString@p];a,{c,Characters@#1}]&
```
[Try it online!](https://tio.run/##Tc67CsIwFIDhZ5GCKGRJ1xKIFASdvBQcDmc4jacm0FxIs5U@e1VcXL/h5/dULHsqztA6qPVesguvc3RBd9SPDA/rRtbHzHwFUjcKz@hbG51hOIzJUs8FUFQ1CoPNaYBdUpc4ueJiAPoYgBQScb9RUhDAf0C30aeRPYfy9RfrqhZzWhBRdfF3ohM2JGYjWkuZTOE86UouuF3XNw "Wolfram Language (Mathematica) – Try It Online")
Thank you for the interesting challenge!
It turned out a pretty big program,
but I can not do less and at the same time meet the requirements (
Ungolfed explained:
```
str = "thisisacomputercipher"; len = 5;
StringJoin[Table[
While[(*Get first random choice contained character*)
FreeQ[arr = RandomChoice[Alphabet[], len], c]
];
If[(pos = Position[arr, c][[1, 1]]) != 1,
(*If char is at first position - keep it,
else set random item to digit as index of char*)
arr[[RandomChoice@Complement[Range@len, {pos}]]] = ToString@pos
]; arr,
{c, Characters@str}]]
```
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 256 bytes
```
import StdEnv
s::!Int->Int
s _=code {
ccall time "I:I"
ccall srand "I:I"
}
r::!Int->Int
r _=code {
ccall rand "I:I"
}
$n|s 0<1#k=map\e.r e rem n
=flatten o map\c.hd[map(\i|i==x=c=toChar if(i==y&&x>0)(x+48)(r i rem 26+97))[0..n-1]\\x<-k[0..]&y<-k[0..]|x<>y]
```
[Try it online!](https://tio.run/##XY9PT4QwEMXvfIpx3bCQDYQ1/iWUi3og8WCyRyCmliLN0pa0XQMRv7q1q2uiXibzfjNv8ob0FAvLZbPvKXDMhGV8kMrA1jT34tXTaXpSCBPlrnganhCRDYU3jxDc92AYp7Ao0mJxBFph0RzJu6d@m9V/85/VpZg1JNnmdIc4HioaK6CgKAfhobbHxlABEg4jEndN6ZqgYjNDaEQEGXnbYQWsDRyYfH/MkzAY1@fXYeDo15mzy/XNVRiWSRyLaFNX1ZhFu4Oq/emnm8csn2q7Ndj9j2AJF1CuTMc005hIPuwNVYQNHVWr2n4QF@tF26h4sHeTwJyRb/Ho0rZScRs9fwI "Clean – Try It Online")
Chooses:
* a random `x` (position of the character in the segment)
* a random `y` that isn't equal to `x` (position of the digit in the segment)
* a random lowercase letter for each position not equal to `x` and not equal to `y` unless `x` is zero
[Answer]
# JavaScript, 134 bytes
```
l=>w=>w.replace(/./g,c=>eval("for(s=c;!s[l-1]||s[t?t-1||9:0]!=c;t=s.replace(/\\D/g,''))s=(p=Math.random()*36**l,p-p%1).toString(36)"))
```
[Try it online!](https://tio.run/##RYyxCsIwFAC/xYL0pdjUUhRUoourk6M6hDRtI7EJeU9d8u8xm3DbcfeUH4kqGE/17HqdBpGsOH4zPGhvpdLQ8GZcKXHUH2mhGFwAFOqwwJut20eMeKMT1W2Mu/36sciGBP7b@/2c67JkDAV4cZE08SDn3r2AVd22quzK137ZMk7uSsHMI3RbVjCWlJvRWc2tG2GADYOSJoMGpXIv/yYdlPGTDvmcfg "JavaScript (Node.js) – Try It Online")
This answer chose the encoded string from all possible encoded string uniformly. So it is more possible to make the encoded letter as the first one.
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 171 bytes
```
s=>n=>{var r=new Random();return s.SelectMany(c=>{int i=r.Next(n),j=r.Next(n-1);j+=j<i?0:1;return new int[n].Select((_,k)=>(char)(i==k?c:j==k&i>0?i+49:r.Next(26)+97));});}
```
[Try it online!](https://tio.run/##fY5NS8NAEIbv/RWhB5klaWj9bpLdHETBg0XsUUTWdWo2bSZlduMH4m@PG6leRGFghpnnfRjjJsbZ/qIjU1yeU9cg64cNFqbSrJKvtSWf/DopFa0i2TupSKr3Z80RS8KX6EbTY9uAyBl9xxS5dIkbNP5K0xuYgAZbZCWnC3z1QCKpf@bJTOR1LOvCltNs9i0YpCFzS3c7E8B9shZSwfCHACvlujRZHdqeVdPSxofzbKfcPxbx/ESI/CNUn49G1xxUsPShPaVnLRntYQVjX1lnnTZts@08srHbCnks4EiE7N8pdD5Ap/9DFSMG6mCg@k8 "C# (Visual C# Interactive Compiler) – Try It Online")
Explanation...
```
// s is the input string
// n is the input length
s=>n=>{
// we need to create an instance
// of Random and use throughout
var r=new Random();
// iterate over s, each iteration
// returns an array... flatten it
return s.SelectMany(c=>{
// i is the position of the letter
// j is the position of the number
int i=r.Next(n), j=r.Next(n-1);
// ensure i and j are different
j+=j<i?0:1;
// create an iterable of size n
return new int[n]
// iterate over it with index k
.Select((_,k)=>(char)(
// return the letter
i==k?c:
// return the number
j==k&i>0?i+49:
// return a random letter
r.Next(26)+97)
);
});
}
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~35~~ 30 bytes
```
NθFS«≔‽θη≔∧η‽Φθ⁻κηζFθ≡κζIηηι‽β
```
[Try it online!](https://tio.run/##Xc5NDoIwEAXgdXuKWU4T3Ju4IkYTFxKjJyhQoLEU6Y8LjGevLSombt98b2aqjptq4CqEg755V/i@FAZHtqHNYADn8OKM1C0yBg9Kcmtlq/HMdT30EWbQRfwX76VyaU0GR6m9xWtSkU6JzotHRgmRDeBu9Fx9BZziJYcyMSKUFZBIrmvsMvjJiS10y63D2FwK7/jzR5kGzxDW1AnrwuquXg "Charcoal – Try It Online") Link is to verbose version of code. 0-indexed. Explanation:
```
Nθ
```
Input the length.
```
FS«
```
Input the word and loop over the characters.
```
≔‽θη
```
Choose a random position for the deciphered letter.
```
≔∧η‽Φθ⁻κηζ
```
Choose a different random position for the digit, unless the letter is at position 0, in which case put the digit at position 0 as well.
```
Fθ≡κ
```
Loop once for each output character and switch on the position.
```
ζIη
```
If this is the position of the digit then output the position of the deciphered letter.
```
ηι
```
But if this is the position of the deciphered letter then output the letter. This takes precedence over the position of the digit because Charcoal takes the last entry if multiple switch cases have the same value.
```
‽β
```
Otherwise output a random letter.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 26 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ε²Ý¨Ω©A.r²£Šǝ®Āi®²Ý¨®KΩǝ]J
```
0-indexed.
[Try it online](https://tio.run/##yy9OTMpM/f//3NZDmw7PPbTi3MpDKx31ig5tOrT46ILjcw@tO9KQeWgdRO7QOu9zK4/Pra31@v@/JCOzOLM4MTk/t6C0JLUoObMgI7WIyxQA) or [verify all test cases](https://tio.run/##yy9OTMpM/W/mpuSZV1BaYqWgZO/pYq@kkJiXAmaG2isBxXSU/EtLoNL/z22NODz30IpzKw@tdNQriji0@OiC43MPrTvSkHloHVjm0DrvcyuPz62t9fqvc2ib/f@SjMzizOLE5PxcoBGpRcmZBRmpRVymXDjFU4tLuCzgVEZRaiqXMYwGAA).
**Explanation:**
```
ε # Map over the characters of the first (implicit) input-string:
²Ý¨ # Create a list in the range [0, second input)
Ω # Get a random item from this list
© # Store it in the register (without popping)
A # Push the lowercase alphabet
.r # Shuffle it
²£ # Leave only the first second input amount of characters
Š # Triple swap, so the stack order becomes:
# random index; random string; map-character
ǝ # Insert the map-character at this random index into the random string
®Āi # If the random index was NOT 0:
® # Push the random index
²Ý¨ # Push the list in the range [0, second input) again
®K # Remove the random index from this list
Ω # Get a random item from this list
ǝ # Insert the first random index at the second random index into the string
] # Close both the if-else and map
J # Join all strings together (and output implicitly)
```
] |
[Question]
[
Given a non-negative integer Excel-style date code, return the corresponding "date" in any reasonable form that clearly shows year, month, and "day".
Trivial, you may think. Did you notice the "scare quotes"? I used those because Excel has some quirks. Excel counts days with number 1 for January 1st, 1900, but [as if 1900 had a January 0th and a February 29th](https://i.stack.imgur.com/aBHgY.png), so be very careful to try all test cases:
```
Input → Output (example format)
0 → 1900-01-00 Note: NOT 1899-12-31
1 → 1900-01-01
2 → 1900-01-02
59 → 1900-02-28
60 → 1900-02-29 Note: NOT 1900-03-01
61 → 1900-03-01
100 → 1900-04-09
1000 → 1902-09-26
10000 → 1927-05-18
100000 → 2173-10-14
```
[Answer]
# Excel, 3(+7?)
```
=A1
```
with format
```
yyy/m/d
```
Pure port
[Answer]
# k (kdb+ 3.5), ~~55~~ ~~54~~ ~~51~~ 50 bytes
```
{$(`1900.01.00`1900.02.29,"d"$x-36526-x<60)0 60?x}
```
to test, paste this line in the q console:
```
k)-1@{$(`1900.01.00`1900.02.29,"d"$x-36526-x<60)0 60?x}'0 1 2 59 60 61 100 1000 10000 100000;
```
the output should be
```
1900.01.00
1900.01.01
1900.01.02
1900.02.28
1900.02.29
1900.03.01
1900.04.09
1902.09.26
1927.05.18
2173.10.14
```
`{` `}` is a function with argument `x`
`0 60?x` index of `x` among `0 60` or 2 if not found
`ˋ1900.01.00ˋ1900.02.29` a list of two symbols
`,` append to it
`"d"$` converted to a date
`x-36526` number of days since 1900 (instead of the default 2000)
`- x<60` adjust for excel's leap error
`(ˋ1900.01.00ˋ1900.02.29,"d"$x-36526-x<60)`@`0 60?x` juxtaposition means indexing - the "@" in the middle is implicit
`$` convert to string
[Answer]
# [Python 2](https://docs.python.org/2/), 111 bytes
```
from datetime import*
n=input()
print('1900-0'+'12--0209'[n>9::2],date(1900,1,1)+timedelta(n+~(n>59)))[0<n!=60]
```
[Try it online!](https://tio.run/##FcxBCsMgEEDRfU6Rrhyrwii0YGhykZBFIIYKdRSZLrrp1Q2uP@@XH78zudbOmtN47Bw4pjDGVHLl@0BzpPJlkEOpkRiE9YgGhRLWGYMOvVhp8dPkNt0x9K6ttlL1zxE@vAOpP9Dy8FLKFV90m5@4tWYRLw "Python 2 – Try It Online")
-5 thanks to [ngn](https://codegolf.stackexchange.com/users/24908/ngn).
[Answer]
# JavaScript (ES6), ~~89 82~~ 77 bytes
*Saved ~~7~~ 12 bytes thanks to @tsh*
```
n=>(p=n>60?'':19)+new Date(p*400,0,n-!p||1).toJSON().slice(p/9,10-!n)+(n&&'')
```
[Try it online!](https://tio.run/##bdHBTsMwDAbgO0@RXdaE1a3tdt0yqePCiUN3GC9QlQwNVUlFK7js3Us7IWAhOTqf5d/yW/1R9837uRvAuhcznsrRlnvZlXZf4EMU7UirlTWf4rEejOzuc8QYYwuL7nIhlQzu6XiopEr69txM/6mOCWFh1Ura5TKK1Ng427vWJK17lScp5odKiTQVpBEBCRDnYuUGsxPV4VnQVmsghozuAs3kNQcRe4gDaK3/IgbeBlCBHtJe1ms9C8cobrKGEeHNhBxQ/0OT@UU8CeDCR7P5QbwBXAP5C13NN2LaZDCdivLxCw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), ~~205~~ 189 bytes
```
import StdEnv
a=30;b=31;c=1900;r=rem
@m=sum(take m(?c))
?n=[b,if(n>c&&(r n 4>0||r n 100<1&&r n 400>0))28 29,b,a,b,a,b,b,a,b,a,b: ?(n+1)]
$n#m=while(\m= @m<n)inc 0-1
=(c+m/12,1+r m 12,n- @m)
```
[Try it online!](https://tio.run/##PY5BS8NAEIXv@RUDlrBLEpxNPVjTSXrQg@CtR@ths011MTOVTaoI/e2uq4gPHnw83jDPjYOVyMf9aRyArZfo@e0YZtjO@zt5zywtselpaRpHZoXYBAoDZxum6cRqtq/pSnVO66wTeuxLf1DSujxXAQSuWjyff8Agrk2e/2aILWpdX0O9KvvS/vmfbqBTUhj9lC3kgunjxY@D2jHBhteivTjAymSkXMGXpi5NEYAhgVSpoeN2tmk8wSK9TIpf7jDa5ylW9w/x9lMsezd9Aw "Clean – Try It Online")
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 31 bytes
Anonymous tacit prefix function. Returns date as `[Y,M,D]`
```
(¯3↑×-60∘≠)+3↑2⎕NQ#263,60∘>+⊢-×
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQb/NQ6tN37UNvHwdF0zg0cdMx51LtDUBgkYAZX4BSobmRnrgCXstB91LdI9PP1/GlDbo96@R13NEJ1AdcFBzkAyxMMz@H8JULb6Ue/WR50Li4DMtEe9u6zU87PVH3W3qKclZuaoAwWA0kW1XAYKJQqGlgYGCoYKBlyGCI4hlxGCY8RlagnjGSkYWXCZGSBxLbnM4BqNgRoNDeCyJgqWIC6Ub6RgqWBkBhaAiBiZK5gqGFpAREBCRobmQBOAVpoAAA "APL (Dyalog Classic) – Try It Online")
`×` sign of the date code
`⊢-` subtract that from the argument (the date code)
`60∘>+` increment if date code is above sixty
`2⎕NQ#263,` use that as immediate argument for "Event 263" (IDN to date)
IDN is just like Excel's date code, but without Feb 29, 1900, and the day before Jan 1, 1900 is Dec 31, 1899
`3↑` take the first three elements of that (the fourth one is day of week)
`(`…`)+` add the following to those:
`60∘≠` 0 if date code is 60; 1 if date code is not 60
`×-` subtract that from the sign of the date code
`¯3↑` take the last three elements (there is only one) padding with (two) zeros
developed together with @Adám in [chat](https://chat.stackexchange.com/rooms/52405/the-apl-orchard)
[Answer]
# Japt, 43 bytes
Ended up with a part port of [Arnauld's solution](https://codegolf.stackexchange.com/a/176683/58974).
Output is in `yyyy-m-d` format.
```
?U-#<?Ð#¾0TUaU>#<)s7:"1900-2-29":"1900-1-0"
```
[Try it online](https://tio.run/##y0osKPn/3z5UV9nG/vAE5UP7DEJCE0PtlG00i82tlAwtDQx0jXSNLJWgbENdA6X//w0A) or [test 0-100](https://tio.run/##y0osKPn/3z5UV9nG/vAE5UP7DEJCE0PtlG00i82tlAwtDQx0jXSNLJWgbENdA6X//w0NDLl0c4MA)
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~186~~ 185 bytes
```
using System;class P{static void Main(){var i=int.Parse(Console.ReadLine());Console.Write((i==0|i==60)?$"1900-{i%59+1}-{i%31}":DateTime.FromOADate(i+(i<60?1:0)).ToString("yyyy-M-d"));}}
```
[Try it online!](https://tio.run/##NY5RC4IwHMS/ypCCDZlMIkFNJIqekiSFnof@iT/oBtsSxPzspg/dw3G/e7lrLG@0gWX5WFRvUo3WQZ82nbSWlJN10mFDBo0tKSQqyqZBGoIZKheU0ligF62s7iB4gmzvqIAylv67l0EHlGKWie9qkWD5zgtjIfiE@2Psh/MWDuHsJVfpoMYegpvR/eO8IUWf4ikSeZgIxoJaV86sH6k3ruIFb711ap6XJRI/ "C# (.NET Core) – Try It Online")
---
-1 byte by replacing OR operator(||) with binary OR operator(|).
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 81 bytes
```
{$_??$_-60??Date.new-from-daycount($_+15018+(60>$_))!!'1900-02-29'!!'1900-01-00'}
```
[Try it online!](https://tio.run/##PcxLCoMwFIXhrVwlbRJM5CZgqAPNpPsIoSaj@sBaiohrT6W0nfyHb3KmMN9N6lc4R2jSRpy1xEmD1l79EsohvGScx152fr2Nz2FhxBWqQnUpmMGWOM6zjKoaUaKWuqZ/KYlI9/TwK@RbGfuF0ZPpKN@haWGLxw/fc4jjDChACdACqlqAOWQOKsRPvv0Npjc "Perl 6 – Try It Online")
[Answer]
# T-SQL, ~~141 95~~ 94 bytes
```
SELECT IIF(n=0,'1/0/1900',IIF(n=60,'2/29/1900',
FORMAT(DATEADD(d,n,-IIF(n<60,1,2)),'d')))FROM i
```
Line break is for readability only.
Input is taken via pre-existing table **i** with integer field **n**, [per our IO standards](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341).
SQL uses a similar (but corrected) 1-1-1900 starting point for its internal date format, so I only have to offset it by 1 or 2 days in the `DATEADD` function.
SQL can't output a column containing a mix of date and character values, so I can't leave off the `FORMAT` command (since it would then try to convert `1/0/1900` to a date, which is of course invalid).
What's nice about SQL is that I can load up all the input values into the table and run them all at once. My (US) locality defaults to a `m/d/yyyy` date format:
```
n output
0 1/0/1900
1 1/1/1900
2 1/2/1900
59 2/28/1900
60 2/29/1900
61 3/1/1900
100 4/9/1900
1000 9/26/1902
10000 5/18/1927
43432 11/28/2018
100000 10/14/2173
```
**EDIT**: Saved 46 bytes by changing to a nested `IIF()` instead of the much more verbose `CASE WHEN`.
**EDIT 2**: Saved another byte by moving the `-` in front of the `IIF`.
] |
[Question]
[
Write a code that runs or compiles in as many programming languages as possible and prints a newline separated list of names of previous and current programming languages.
* Every used language must have 1 character longer name than previous; ex. `C#`, `C++`, `Ruby`, `Jelly`, `Python`...
* Each language must output a list of language names separated with a newline, sorted by length.
+ **Output must be a pyramid:** The list can only contain used language names, that are shorter than the running script language name + the running script language's name.
* Leading and trailing newlines are allowed.
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* It's not allowed to create custom programming languages just to increase the score.
* Version numbers don't count in language name, but you can specify it in your post if there are any incompatible changes in new versions of the language.
* You can decide if you want to use the shortcut for the language name or it's full name, but you can't submit both forms in one answer. You can use ex. either `SPL` or `Shakespeare Programming Language`.
+ Only letters, numbers, ASCII symbols and single spaces (not leading nor trailing) count in language name length.
## Examples
Example outputs for C, C# and C++:
### `C`
```
C
```
### `C#`
```
C
C#
```
### `C++`
```
C
C#
C++
```
[Answer]
# 10 languages [C](https://gcc.gnu.org/), [rk](https://github.com/aaronryank/rk-lang), [><>](https://esolangs.org/wiki/Fish), [Rail](https://esolangs.org/wiki/Rail), [Width](https://github.com/stestoltz/Width), [Gol><>](https://github.com/Sp3000/Golfish), [Fission](https://github.com/C0deH4cker/Fission), [Cardinal](https://www.esolangs.org/wiki/Cardinal), [brainfuck](https://github.com/TryItOnline/brainfuck), [Befunge-98](https://github.com/catseye/FBBI), 991 bytes
```
//Q rk:start print: "C^nrk" rk:end @,k*97C'a"rk"a"><>"a-1"Sail"a"Width"a"Gol><>"a"Fission"a"Cardinal"a"brainfuck"a"Befunge-98"
main(){puts("C");}
/*
$'main'
\-[C\n\rk\n\><>\n\Rail]o
++++[++++>---<]>.>++++++++++.[------->+++<]>.-------.>++++++++++.[->++++++<]>++.--.++.>++++++++++.>-[--->+<]>---.[------>+<]>--.++++++++.+++.>++++++++++.[------>+<]>.+++[->++++<]>+.-----.--[--->+<]>--.------------.>++++++++++.[->+++++++<]>+.[--->+<]>++.---.--[->+++<]>.--.++.>++++++++++.[->+++++++<]>.[-->+++<]>.++++++++++..----------.++++++.-.>++++++++++.+[->++++++<]>+.-[-->+++<]>--.--[--->+<]>---.--------------.+++++.+++++.-------------.+++++++++++.>++++++++++.+[--->++++<]>--.[--->+<]>----.+++[->+++<]>++.++++++++.+++++.--------.-[--->+<]>--.+[->+++<]>+.++++++++.
R"C"N"rk"N"><>"N'S_!"ail"N"Width"N"Gol><>"N"Fission"*
/"><>krC"oaoooaooooE ao'liaR>'~ooooaoS"Width"aoS"Gol><>"; QQaAWAmcOAWAaicmaiWAAiwAOaOwWAAAOawmmFOcQww
%"C"++++++++++,"rk","><>",=--t++,"ail"~,"Width","Gol><>","Fission","Cardinal"
*/
```
[Try it online!](https://tio.run/##fVNLb6MwEL77V7jWVrQJBu1p@1pUira9ESU55EDalZvH1iLBK0LFoWr@ejpjbDBpVUsM9jy@7/No/Lxavxb/Vvzy4nAIwzEt86tdJcqK/i9lUV1RljwVZc7QvyqW9NbPB5e/Ek8wcAoW3URM8J9sKuQGjjO5rF7g/6A2OsLu5W4nVQG7RJRLWQjMei6FLNavCwS4a@kZ2YL77PxNE6/PWMLOr99JOCA/PIx4hM55lsyLeZmDAXywE@B9VIQMYWVoIs75zWMURMN2BRlvFvowZo5HOeYECXCEKFg3IeKZhoA41mYWUp@DNm14VObmYdDwIEujA6wDbLV9I7CpbWu02Aalu1/wSYVTjLU21clxqI076CsY9noU8A7m@Bb9a1g8Y7@I2Bb3yXjbKtNvi867RjYNcLvvMAS9zjoVXQGZwJilOMupnuXUm/49YTjMqRnm1A5z2g7zgISYnJcJU0Ip/ak/VChvI8Uk8vZKO6f2OcDOYFzT8VjEs3i7GIEVcgGDPYtjWccjMaphB/96u70fLcZ1TegpiOt64qNMX8v0f3NeoQeV7n1D5Fsav5Xqd@@O0EF4OHwA "Befunge-98 (FBBI) – Try It Online")
568 bytes of this is just the brainfuck code. The Befunge-98 program produces:
```
C
rk
><>
Rail
Width
Gol><>
Fission
Cardinal
brainfuck
Befunge-98
```
[Answer]
# 7 languages (J, es, zsh, Bash, Straw, Retina, Fission), 222 bytes
```
echo 'J'
#0 : 0
echo es #(10)#»:::J>>(es)>>(zsh)>>(Bash)>>(Straw)>>
(echo zsh;)
if [[ $BASH_VERSION ]]; then echo Bash; fi
# ;R"J"N"es"N"zsh"N"Bash"N"Straw"N'Q+!"etina"N"Fission"N;
K`J¶es¶zsh¶Bash¶Straw¶Retina
```
[Try it online!](https://tio.run/##VY@xCsIwEIb3PMWZCm1xqWsCBQuKRqjYgkspWiSlWVowBcEHy@KWF4uXdPKG/78k/3fheqW1mkbn5HOYIBYxiTJgkJFwlhqiZJulkf0yxkSeJ1KnqB89eCu6xev51b2xIUmg8JWnRPXQNLAudvXxfttX9elSQttymAc5Qsh5nEOvSAR/xSsqaEmlRsFZqD6JFv6hZXzdrKic1djh3WFZgJacnB/CGqmtQcgaz1gTEGuqEHfuBw "Fission – Try It Online")
[Answer]
# [rk](https://github.com/aaronryank/rk-lang), [sed](https://www.gnu.org/software/sed/), [Swap](https://github.com/splcurran/Swap), 65 bytes
```
s/.*/rk\nsed/
rk:start print: "rk"
r>"pawSdeskr"oo52*oooo52*ooooo
```
[rk: Try it online!](https://tio.run/##K8r@/79YX09Lvyg7Jq84NUWfqyjbqrgksahEoaAoM6/ESkGpKFuJq8hOqSCxPDgltTi7SCk/39RIKz8fTuX//w8A)
[sed: Try it online!](https://tio.run/##K05N0U3PK/3/v1hfT0u/KDsmrzg1RZ@rKNuquCSxqEShoCgzr8RKQakoW4mryE6pILE8OCW1OLtIKT/f1EgrPx9O5f//DwA)
[Swap: Try it online!](https://tio.run/##Ky5PLPj/v1hfT0u/KDsmrzg1RZ@rKNuquCSxqEShoCgzr8RKQakoW4mryE6pILE8OCW1OLtIKT/f1EgrPx9O5f//DwA "Swap – Try It Online")
] |
[Question]
[
Given a key, and an array of strings, shuffle the array so that it is sorted when each element is XOR'd with the key.
## XOR'ing two strings
To XOR a string by a key, XOR each of the character values of the string by its pair in the key, assuming that the key repeats forever. For example, `abcde^123` looks like:
```
a b c d e
1 2 3 1 2
--------------------------------------------
01100001 01100010 01100011 01100100 01100101
00110001 00110010 00110011 00110001 00110010
--------------------------------------------
01010000 01010000 01010000 01010101 01010111
--------------------------------------------
P P P U W
```
## Sorting
Sorting should always be done Lexicographically of the XOR'd strings. That is, `1 < A < a < ~` (Assuming ASCII encoding)
## Example
```
"912", ["abcde", "hello", "test", "honk"]
-- XOR'd
["XSQ]T", "QT^U^", "MTAM", "Q^\R"]
-- Sorted
["MTAM", "QT^U^", "Q^\R", "XSQ]T"]
-- Converted back
["test", "hello", "honk", "abcde"]
```
## Notes
* Key will always be at least 1 character
* Key and Input will only consist of printable ASCII.
* XOR'd strings may contain non-printable characters.
* Input and Output may be done through the [Reasonable Methods](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.
* You may take Key and Input in any order.
## Test Cases
```
key, input -> output
--------------------
"912", ["abcde", "hello", "test", "honk"] -> ["test", "hello", "honk", "abcde"]
"taco", ["this", "is", "a", "taco", "test"] -> ["taco", "test", "this", "a", "is"]
"thisisalongkey", ["who", "what", "when"] -> ["who", "what", "when"]
"3", ["who", "what", "when"] -> ["what", "when", "who"]
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so least bytes wins!
[Answer]
# [Python 3](https://docs.python.org/3/), ~~75~~ 73 bytes
```
lambda k,x:x.sort(key=lambda s:[ord(x)^ord(y)for x,y in zip(s,k*len(s))])
```
This sorts the list **x** in-place.
*Thanks to @mercator for golfing off 2 bytes!*
[Try it online!](https://tio.run/##fY/BDoMgEETP@hWEE9uQJq2nmvRLrE1QsRAoGCER@/MWsF572ZnsvE1mp9ULa6ptRHf02DR7dwNDioY6nJ2dPVF8vf@2rm7sPJAAzyQrjHZGga5IGvSRE3FUnTQ3xAG0sKWQKIoCpJyUBcG3yxVT1GDW9QOPDguutU3Gc@fzwhqFW6CJ9qy3GfdCuhTuk2V@z/a7g4@YdExb84qd8@UiMrUI5nfl5qCrP0AJdVmMsXyAsphmaXz8efsC "Python 3 – Try It Online")
### Alternate version, 62 bytes
This takes input as byte strings, which may not be allowed.
```
lambda k,x:x.sort(key=lambda s:[*map(int.__xor__,s,k*len(s))])
```
[Try it online!](https://tio.run/##fY/BCoQgGITP@RTiSRcJdjtt0JO0EVq2iqaRQvb0rWR03NM/zMwH/yx7kM5WxwQb@DkMm/nIoKaxjqV3a8Ba7M3l@rp9zGzByoay76Nb@556qh9GWOwJ6cgxuRViTWEkUFmIQYE5ej9fiMKWI8aHUSTJkRTGuFMF4UO2nNWoI/REAhtcZoJU/syvwzKV8wu/qdRVnhlnv@npzG8yFzfJwiWEvYnqfwmQGhRT2hMJKJY1zcaRHD8 "Python 3 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 7 bytes
```
⁹ṁO^OµÞ
```
*Thanks to @EriktheOutgolfer for a suggestion that helped saving 2 bytes!*
[Try it online!](https://tio.run/##y0rNyan8//9R486HOxv94/wPbT087//h5Ub67v//RyslJiWnpCrpKChlAJXlgxglqcUlYIH8vGylWCDD0tAIyI9WKsnILAZJQMhEsNrEZISeWIRAtFJ5BliiPCOxBEKn5kEUAA3JLE7Myc9Lz06txKvUWAkA "Jelly – Try It Online")
### How it works
```
⁹ṁO^OµÞ Dyadic link.
Left argument: A (string array). Right argument: k (key string).
µ Combine the code to the left into a chain.
Begin a new, monadic chain with argument A.
Þ Sort A, using the chain to the left as key.
Since this chain is monadic, the key chain will be called monadically,
once for each string s in A.
⁹ Set the return value to the right argument of the link (k).
ṁ Mold k like s, i.e., repeat its characters as many times as necessary
to match the length of s.
O Ordinal; cast characters in the resulting string to their code points.
O Do the same for the chain's argument (s).
^ Perform bitwise XOR.
```
[Answer]
## Haskell, 77 bytes
```
import Data.Bits
import Data.List
t=fromEnum
sortOn.zipWith((.t).xor.t).cycle
```
Too many imports.
[Try it online!](https://tio.run/##XY0xC8IwEIX3/IojOFSQgDo5dBHdBEcH6XCmKQltktKcVP3zMWkR1OXe8d77eBpDq7ouRmN7PxAckFDsDQX2bZxMIEZlM3h7dHfLmjKk7OzEy/QXQ7ooBC3Fww9Z5FN2Klo0DkqoPQPoB@MIFtAA3603HODK8SZrxVfAdVr3@SEVaDK8a3n1SxFKzxNF2oTcmS9OWI4@@B@2TVN5bNRTZdRIsyrHK4hv "Haskell – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 61 bytes
```
->k,w{w.sort_by{|x|x.bytes.zip(k.bytes.cycle).map{|x,y|x^y}}}
```
[Try it online!](https://tio.run/##jY2xDoIwGIR3n4LUAU0KCTA5yIuQagoWS0BKoKZU4NmxtGA6GOPSu9z997V9pnLOz7MXl1AMwu9Yy6@pHMZ@7P1UctL5r6I5lKvPZFaRo//AjbqAcuwvcpqmuXHyxA3CyIWJi9PsRlyEdksITkEIoJMAnSoHKKkqthiF4zpgdQkQcvaOF6vDT7zd6V6pIaxYjjOmuZwW3dKaF2uw6QzJAtvxotTaKLuRVVx0uGL1vSRS/yGoHgqKuVFSW9yvrWFFf82tWCvb5vjHfH4D "Ruby – Try It Online")
[Answer]
# [Clean](https://clean.cs.ru.nl), ~~101~~ ~~100~~ 94 bytes
*-6 bytes thanks to Ourous!*
```
import StdEnv
? =toInt
s k=let%s=[b bitxor?a\\a<-s&b<-[?c\\_<-s,c<-k]];@a b= %b> %a in sortBy@
```
[Try it online!](https://tio.run/##Ncy7DoIwFIDh3ac4C3aByVEqxOhA4sbYNua0VG3oxdB64eWtOLh9//Irq9FnF4aH1eDQ@GzcPUwJ@jQc/XPVAE2h82kVYaRWpyJSJkGa9A5Tg5xjXcW1rCvWKM7PS5SqrkYhti2CpFDIHRQIxkNcpvu5zX3C5U4hAiMbIoAx8roFIkr4AdNf2hMh8kddLF5jrrpTPswenVHxCw "Clean – Try It Online") Example usage: `s ['3'] [['who'], ['what'], ['when']]`.
### Ungolfed:
```
import StdEnv
sort key list =
let
f string = [(toInt a) bitxor (toInt b) \\ a<-string & b<-flatten(repeat key)]
comp a b = f a <= f b
in sortBy comp list
```
[Answer]
# x86 opcode, 57 Bytes
```
0100 60 89 CD 4D 8B 74 8A FC-8B 3C AA 53 F6 03 FF 75
0110 02 5B 53 8A 23 AC 08 C0-74 0A 30 E0 32 27 47 43
0120 38 E0 74 E8 77 0A 8B 04-AA 87 44 8A FC 89 04 AA
0130 85 ED 5B 75 CE E2 CA 61-C3
;input ecx(length), edx(array), ebx(xor-d)
F: pushad
L1: mov ebp, ecx
L2: dec ebp
mov esi, [edx+ecx*4-4]
mov edi, [edx+ebp*4]
push ebx
L6: test [ebx], byte -1 ; t1b
jnz L4
pop ebx
push ebx
L4: mov ah, [ebx]
lodsb
or al, al
jz L7
xor al, ah
xor ah, [edi]
inc edi
inc ebx
cmp al, ah
jz L6
L7: ja L8
mov eax, dword[edx+ebp*4]
xchg eax, dword[edx+ecx*4-4]
mov dword[edx+ebp*4], eax
L8: ;call debug
test ebp, ebp
pop ebx
jnz L2
loop L1
popad
ret
```
Test code:
```
if 1
use32
else
org $0100
mov ecx, (Qn-Q0)/4
mov edx, Q0
mov ebx, S
call F
call debug
ret
debug:pushad
mov ecx, (Qn-Q0)/4
mov edx, Q0
mov ebx, S
E3: mov esi, [edx]
push dx
mov ah, 2
E4: lodsb
cmp al, 0
jz E5
mov dl, al
int $21
jmp E4
E5: mov dl, $0A
int $21
mov dl, $0D
int $21
pop dx
add edx, 4
loop E3
;mov ah, 1
;int $21
int1
popad
ret
align 128
Q0:
dd str1, str2, str3, str4
Qn:
S db '912', 0
str1 db 'abcde', 0
str2 db 'hello', 0
str3 db 'test', 0
str4 db 'honk', 0
align 128
end if
;input ecx(length), edx(array), ebx(xor-d)
F: pushad
L1: mov ebp, ecx
L2: dec ebp
mov esi, [edx+ecx*4-4]
mov edi, [edx+ebp*4]
push ebx
L6: test [ebx], byte -1 ; t1b
jnz L4
pop ebx
push ebx
L4: mov ah, [ebx]
lodsb
or al, al
jz L7
xor al, ah
xor ah, [edi]
inc edi
inc ebx
cmp al, ah
jz L6
L7: ja L8
mov eax, dword[edx+ebp*4]
xchg eax, dword[edx+ecx*4-4]
mov dword[edx+ebp*4], eax
L8: ;call debug
test ebp, ebp
pop ebx
jnz L2
loop L1
popad
ret
```
[Answer]
# [Actually](https://github.com/Mego/Seriously), 24 bytes
```
O╗⌠;O;l;╜@αH♀^♂cΣ@k⌡MS♂N
```
[Try it online!](https://tio.run/##S0wuKU3Myan8/9//0dTpj3oWWPtb51g/mjrH4dxGj0czG@IezWxKPrfYIftRz0LfYCDH7///aKXEpOSUVCUdBaWM1JycfBCjJLW4BCyQn5etFMulZGlopAQA "Actually – Try It Online")
Explanation:
```
O╗⌠;O;l;╜@αH♀^♂cΣ@k⌡MS♂N
O╗ store ordinals of key in register 0
⌠;O;l;╜@αH♀^♂cΣ@k⌡M for each string in array:
;O make a copy, ordinals
;l; make a copy of ordinals, length, copy length
╜@αH list from register 0, cycled to length of string
♀^ pairwise XOR
♂cΣ convert from ordinals and concatenate
@k swap and nest (output: [[a XOR key, a] for a in array])
S♂N sort, take last element (original string)
```
[Answer]
# [Perl 6](http://perl6.org/), 37 bytes
```
{@^b.sort(*.comb Z~^(|$^a.comb xx*))}
```
[Try it online!](https://tio.run/##XY7dCoJAEIXve4pDRJRUUEFQmPQO3SUKo62u@LOxu1Bi9uo2sdRFw8zAOecbmJvQ1W6oW0wzHIfuFCcro7SdeatU1Qkur3j2nMTk1OPhzef9kCkNf7/egJL0KiBFVSlYYSykaspgMQKXbyllVxYG3AQnGfrlHBWGKtXkpWhxl4qHLC/RfJntn41lgHDC@ALeibSmNkIHQy3GZ/66aHL4zg@jAPfCSnzoA/wug7tzMfpgjH54Aw "Perl 6 – Try It Online")
`$^a` and `@^b` are the key and array arguments to the function, respectively. `@^b.sort(...)` simply sorts the input array according to the predicate function it is given. That function takes a single argument, so `sort` will pass it each element in turn and treat the return value as a key for that element, sorting the list by the keys of the elements.
The sorting function is `*.comb Z~^ (|$^a.comb xx *)`. `*` is the single string argument to the function. `*.comb` is a list of the individual characters of the string. `|$^a.comb xx *` is a list of the characters in the xor sorting key, replicated infinitely. Those two lists are zipped together (`Z`) using the stringwise xor operator (`~^`). Since the sorting predicate returns a sort key which is a list, `sort` orders two elements by comparing the first elements of the returned lists, then the second elements if the first elements are the same, et cetera.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~132~~ ~~128~~ 126 bytes
```
char*k;g(a,b,i,r)char**a,**b;{r=k[i%strlen(k)];(r^(i[*a]?:-1))-(r^(i[*b]?:-2))?:g(a,b,i+1);}f(c,v)int*v;{k=*v;qsort(v,c,8,g);}
```
Takes an argument count and a pointer to a string array (the key, followed by the strings to be sorted) and modifies the string array in-place.
The code is highly non-portable and requires 64-bit pointers, gcc, and glibc.
*Thanks to @ceilingcat for golfing off 2 bytes!*
[Try it online!](https://tio.run/##jVHBTsMwDD23X2EFISVtBnRcgG7wIVWRsixdQ0sDTSiCqd8@nGTAuJFDHD@/Z1svcrGT8nCQrRizrtxRwTdc85EFIBM8yzblflx3lT63buzVQDtWl3R8pLrKRP1wtygYWxzzjc@XjD3cHRvlBSvnhko@MT24bCr33RrvV2tGRycu@Q3fIeNwpgfZv20VrKzbanPR3qcpCuBZ6IGydJ8mfh/InLLOVnVVLG9qWKcJFpI9kNtiSTicHCI2cqsQI63qe@MfXhoAM3QEYOZR6oQ0f7TEtdp6YrxF0EZS7PErRaK2ojfDrlMfvv7emhiEi1EN5HStH@n133Xhn9K5TNOkMSPQYIeGNVyVGFZg9acyDQR/4PI7jX4hI89ZNMubiv8ogxLzaGuG0IRQtFfXfkzy3upeAfWlKs@9qGah0HhMct9nOiI/Kz1hl6LEsApj8BVGJ8nLiKMbSs4tkCitno79Xt6cpYRgkszpfPgC "C (gcc) – Try It Online")
[Answer]
# Python 2, ~~204 140 134~~ 126 bytes
*Thanks to @Mr. Xcoder for saving 64 bytes, thanks to @ovs for saving six bytes, and thanks to @Dennis for saving eight bytes!*
```
lambda k,l:[x(k,s)for s in sorted(x(k,s)for s in l)]
x=lambda k,s:''.join(chr(ord(v)^ord(k[i%len(k)]))for i,v in enumerate(s))
```
[Try it online!](https://tio.run/##fcvBCsIwDAbgu09RCmILQ1BPCj7JnFC3zNbWRNq46dNP14GgBy9J@PN/tydbwvXQ7g9DMNdTY4Qvwq58KF8k3VIUSTgUiSJDo37SoKvZY/9habdYLC/kUNU2KoqN6vRxXL508wCovK501q7oRg94v0I0DCppPdyiQxatktvVWhailOZUN/C@pIUQaDwYEueA0MtKzz6ETU3ZsHVpbEzTZDT9JvyF3l2XTCA8e3hm3ttc7a3haQN@kc2f1vAC)
[Answer]
# JavaScript ES 6, ~~113~~ ~~97~~ 95 Bytes
```
k=>p=>p.sort((a,b,F=x=>[...x].map((y,i)=>1e9|y.charCodeAt()^(p=k+p).charCodeAt(i)))=>F(a)>F(b))
```
JavaScript is long at charcoding...
For [0,65536) +1e4 all be 5 digits so can be compared like string
```
Q=
k=>p=>p.sort((a,b,F=x=>[...x].map((y,i)=>1e9|y.charCodeAt()^(p=k+p).charCodeAt(i)))=>F(a)>F(b))
;
console.log(Q("912")(["abcde", "hello", "test", "honk"]));
console.log(Q("taco")(["this", "is", "a", "taco", "test"]));
console.log(Q("thisisalongkey")(["who", "what", "when"]));
console.log(Q("3")(["who", "what", "when"]));
```
[Answer]
# Perl 5, 88 bytes
```
sub{[map@$_[0],sort{@$a[1]cmp@$b[1]}map[$_,substr$_^($_[0]x length),0,length],@{$_[1]}]}
```
[Try it online](https://tio.run/##fY6xbsMgEIZ3PwVCDLZEpaRVh8ZK5SFvgah1dnGwgsECrDSy8uzuxXRwlt4Ap/@@j2NU3rwvU1DkBBEOh9M0jMqX2XAjrCNHsoSpmcUAY8VqsZM8OB/nioHYy3bAsMHmjmPBao5oiJ7VX/nK/hCj7Dnqgu946iSvZhyhIe9LmY2@tzFPG3PWvXzmuKQoCtI5nxEsQT/2r5STTQkKTfutMKRaGeMeTVQhroGzFyol/3MjtO5Jxkj34UGmE1Y5UemRjYxkH8A4e76oGwKCXvUKXjXEdCu7Ed6e/0n@Ecps@QU).
[Answer]
## Clojure, 80 bytes
```
#(sort-by(fn[s](apply str(apply map bit-xor(for[i[(cycle %)s]](map int i)))))%2)
```
[Answer]
# Perl 5, ~~80 + 3 (`anl`) = 83~~, 67 bytes
```
sub{$,=shift;sub X{$_^substr$,x y///c,0,y///c};map X,sort map X,@_}
```
[try it online](https://tio.run/##dY5NDoIwEIX3nGLSdAFJDf7EhTYYFh7CxCipWIQIlLRDlBjPjoWaqAtn0fc6873JNFKXy741ErYCxXq9batGau5VHdAMIuhNe3pQFpm8yJDbD@weNDlaY1BTdocuDMOUTdmoT16JBnbMKI3gbJw8e@41uqjRd8v9Pc0mGz@mSXAIAsiU9sDWnqxmc8Lgq4g4pWdpeySXZakGg9Lg2FD1lRzYO4kiVT9RgnlhBs69Yow6yK34RC1YGFGq@nKV3TC/5cqJQKey/uCL3wvhL869/gU)
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), ~~285~~ 284 bytes
```
{for(;z++<128;){o[sprintf("%c",z)]=z}split(substr($0,0,index($0,FS)),k,"");$1="";split($0,w);for(q in w){split(w[q],l,"");d="";for(;i++<length(l);){d=d sprintf("%c",xor(o[k[(i-1)%(length(k)-1)+1]],o[l[i]]))}a[q]=d;i=0}asort(a,b);for(j in b){for(i in a){printf(a[i]==b[j])?w[i]FS:""}}}
```
[Try it online!](https://tio.run/##VY9BbsMgEEWvglAiMTKR7KzaUtRdLpAlYoGDUxOQSQyRI1uc3cV2Nt39mXkz/48a7DxPV98TNhbFd3X8YDB5Ee696eKV4P0F0xEkH1O4OxNJeNYh9mRX0pKaTjevRZ7OANRSjIHtKo4x29g8GYAttx/IdGiAaesP4iGpW3G90Ku7ye6u6X5jSxzkDJpr9C/FK1NeWEHMoYI9ebMWclVUUlIvnDBSAiSV73PNDC@TCr6PRNF6y3FbctSw/msWrWB6e6i8zHktbhJ@hqxP5y@MU0rz/FkdkaovukFt45xHsQkRtb6zfw "AWK – Try It Online")
Accepts input in the form of `key word word ...` eg `912 abcde hello test honk`
Outputs sorted words space separated
Slightly more readable
```
{
for (; z++ < 128;) {
o[sprintf("%c", z)] = z
}
split(substr($0, 0, index($0, FS)), k, "");
$1 = "";
split($0, w);
for (q in w) {
split(w[q], l, "");
d = "";
for (; i++ < length(l);) {
d = d sprintf("%c", xor(o[k[(i - 1) % (length(k) - 1) + 1]], o[l[i]]))
}
a[q] = d;
i = 0;
}
asort(a, b);
for (j in b) {
for (i in a) {
printf(a[i] == b[j]) ? w[i] FS : ""
}
}
}
```
[Answer]
# Factor, 85
```
[ [ dup length rot <array> concat [ bitxor ] 2map ] with
[ dup bi* <=> ] curry sort ]
```
First try, I'll see if I can golf it further tomorrow.
I accept suggestions ;)
[Answer]
## **Dyalog APL, 34 bytes**
Dfn, uses ⎕ml 3
```
{⍵[⍋⊃82⎕dr¨⊃≠/11⎕dr¨¨⍵((⍴¨⍵)⍴⊂⍺)]}
```
] |
[Question]
[
In this [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, you must output an ascii-art of a random die roll.
like this:
```
________
/\ \
/ \ 6 \
{ 4 }-------}
\ / 5 /
\/_______/
```
Please note that:
```
________
/\ \
/ \ 3 \
{ 4 }-------}
\ / 5 /
\/_______/
```
is invalid output, because that is not a possible result on a die
There are `6(faces that could be up)*4(faces that could be the left face after the top is determined)*1(faces that could be the right face after the other two are determined)`=24 possibilities of die rolls.
Your program must output one of these die rolls in the form of an ascii art (modeled like the one below, with the x y and zs replaced with numbers) like above, with each output having >0 probability of occurring, but the probabilities do not have to be even (they are allowed to be trick dice, unlike in real life). Your program cannot output an invalid die roll, or a non die roll. Your program must have a probability of 1 of outputting a valid roll
Please note that your die does not necessarily have to be a right handed die like shown in the first image. (right- and left-handed describe the die's net)
```
right-handed die
________
/\ \ net
/ \ z \ _|4|_ _
{ x }-------} |6|2|1|5|
\ / y / |3|
\/_______/
left handed die
________
/\ \ net
/ \ y \ _|3|_ _
{ x }-------} |6|2|1|5|
\ / z / |4|
\/_______/
```
If your die is left handed, the following is valid output, but not if your die is right handed:
```
________
/\ \
/ \ 2 \
{ 1 }-------}
\ / 3 /
\/_______/
```
While you can choose left handed or right handed, your die has to be consistent: it cannot change from left to right or vice versa
the following is a list of valid outputs for the die. Refer to the pictures above for positions of X-Y-Z:
```
X-Y-Z
-----
5-4-1
1-5-4
4-1-5
5-6-4
4-5-6
6-4-5
5-3-6
6-5-3
3-6-5
5-1-3
3-5-1
1-3-5
2-6-3
3-2-6
6-3-2
2-4-6
6-2-4
4-6-2
2-1-4
4-2-1
1-4-2
2-3-1
1-2-3
3-1-2
```
again this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so fewer bytes is better
[Answer]
# Python 3, ~~197 196 192~~190 bytes
```
from random import*;c=choice;r=range(1,7);u=c(r);l=c(list({*r}-{u,u^7}));print(r''' ________
/\ \
/ \%4d \
{ %d }-------}
\ /%4d /
\/_______/'''%(u,l,3*u*l*(u*u-l*l)%7))
```
**[Try it online!](https://tio.run/##LYzBCoMwEETvfsVegkmIhGLBQ/BPpKVEWwPRyJociuTb06X6Dju7zM5s3ziHtS3ljWEBfK0jiVu2gFEa29s5ODsZ7Mn5TPymOmFSbzkK40m82yM/JObmSCo9uiyE2dCtkWNd1wDwvKgA9AAnQwWaJruP/@MARktuTnIF9KdPU1Ns0FeFpkbGk/KqlUl6yZNMjZdesE6IUn4 "Python 3 – Try It Online")**
Right-handed (switch to a lefty by swapping `u*u` with `l*l` on the last line)
Bound to be beat - but let's get the dice rolling *sigh* - especially since all my attempts to golf the ASCII except going raw and using old-school formatting all failed to save bytes;
* any further golfing tips for a n00b gladly appreciated.
[Answer]
# C,177
```
f(r){r=rand()%24;r=(5545>>r%4*3&63^256-(r*2&8))*513>>r/8*3;printf(" ________\n /\\%9s / \\%4d \\\n{ %d }-------}\n \\ /%4d /\n \\/_______/","\\\n",7&r,7&r/8,7&r/64);}
```
**In test program**
```
f(r){r=rand()%24;
r=(5545>>r%4*3&63^256-(r*2&8))*513>>r/8*3;
printf(" ________\n /\\%9s / \\%4d \\\n{ %d }-------}\n \\ /%4d /\n \\/_______/","\\\n",7&r,7&r/8,7&r/64);}
j;
main(){
for(j=99;j--;puts(""))f();
}
```
**Explanation**
```
r= \\after calculation, assign to r (in order to use only one variable.)
(5545>>r%4*3&63 \\5545 is 12651 in octal. Select 2 digts for the equator
^256-(r*2&8)) \\if 4's bit of r is 0, prepend 4=256/64. Else prepend 3 and reverse one of the faces by xoring with 7. 256-8 = 248 = 3*64+7*8.
*513 \\now we have a 3 digit octal number. duplicate all digits by multiplying by 1001 octal.
>>r/8*3 \\rightshift 0,1 or 2 digits to rotate.
```
[Answer]
# Javascript ~~238~~ ~~232~~ ~~207~~ 201 bytes
```
var r=24*Math.random()|0,o=r%3,b=r-o,v="123513653263154214624564";console.log(` ________
/\\ \\
/ \\ %s \\
{ %s }-------}
\\ / %s /
\\/_______/`,v[r],v[b+(o+1)%3],v[b+(o+2)%3])
```
which when ungolfed is:
```
var r = 24 * Math.random() | 0,
o = r % 3,
b = r - o,
v = "123513653263154214624564";
console.log(
` ________
/\\ \\
/ \\ %s \\
{ %s }-------}
\\ / %s /
\\/_______/`,
v[r],
v[b+(o+1)%3]
,v[b+(o+2)%3]
)
```
## Algorithm
Consider that at each of the 8 corner intersections of a die, the intersecting die face values are fixed but can appear in any of 3 rotations. For example while looking down at the "1","2","3" corner, the die can be rotated about an axis through the corner and out the opposite corner, to show "1", "2" or "3" on top of the ASCII art.
`v` hard codes the die faces which intersect at each corner, `b` is an offset to the start of a random corner, and `o` is start of the rotation within corner data. The ASCII art is written to the console using a `console.log` format string.
[Answer]
# TSQL 308 bytes
```
DECLARE @ char(87)=(SELECT
REPLACE(REPLACE(REPLACE(' ________
/\ \
/ \ 7 \
{ 8 }-------}
\ / 9 /
\/_______/',7,a),8,b),9,3*ABS(a*a*a*b-a*b*b*b)%7)
FROM(SELECT*,SUBSTRING(REPLACE(STUFF(123456,a,1,''),7-a,''),CAST(RAND()*4as int)+1,1)b
FROM(SELECT CAST(RAND()*6as int)+1a)x)x)PRINT @
```
# 280 bytes(in Server Management Studio: Query - result to text)
```
SELECT
REPLACE(REPLACE(REPLACE(' ________
/\ \
/ \ 7 \
{ 8 }-------}
\ / 9 /
\/_______/',7,a),8,b),9,3*ABS(a*a*a*b-a*b*b*b)%7)
FROM(SELECT*,SUBSTRING(REPLACE(STUFF(123456,a,1,''),7-a,''),CAST(RAND()*4as int)+1,1)b
FROM(SELECT CAST(RAND()*6as int)+1a)x)x
```
Note: by removing the print and the declare part - and output the result directly from the SELECT. However that would not work in the fiddle
**[Fiddle](https://data.stackexchange.com/stackoverflow/query/522219/roll-an-ascii-die)**
[Answer]
# Javascript, 251 bytes
```
r="replace";a=()=>(0|Math.random()*6)+1;b=(x,y)=>3*x*y*(x*x+6*y*y)%7;u=()=>{x=a(),y=a();z=b(x,y);if(z==0)u();return" ________\r\n \/\\ \\\r\n \/ \\ 1 \\\r\n{ 2 }-------}\r\n \\ \/ 3 \/\r\n \\\/_______\/"[r](1,x)[r](2,y)[r](3,z);}
```
Call using `u();`
It's long but it's an answer, and I haven't answered in a long time.
[Answer]
# Ruby, 150 bytes
All the string formatting abuse!!!
Credit for formula obtaining the last number goes to @xnor [here](https://math.stackexchange.com/questions/1101870/derivation-of-dice-sides-polynomial/1101984#1101984).
```
u=1+rand(6)
l=([*1..6]-[u,u^7]).sample
$><<'%11s
/\%8s
/ \%4d%4s
{ %d }%s}
\ /%4d%4s
\/%s/'%[?_*8,?\\,u,?\\,l,?-*7,3*u*l*(u*u-l*l)%7,?/,?_*7]
```
[Answer]
# Python 3, 181 bytes
```
from random import*;a,b,c,d=sample(b"FGHJ",k=4);u,l=a-b,c-d;print(r''' ________
/\ \
/ \%4d \
{ %d }-------}
\ /%4d /
\/_______/'''%(u%7,l%7,3*u*l*(u*u-l*l)%7))
```
Right-handed die. [Try it online](https://tio.run/##LYzLCoMwEEX3fsUghDxIyELBhbi1pd8QKLFpqTRqSM2iFL89HaoH5sW9c8NnfS5zlfMjLhNEOzsc4xSWuIrWykHepOvedgr@zoayP50vpXx1NW@T9J1VqCvXhjjOK4uUUgC4HhQA2sCOKUBjJ7X7H18guGxqZysAfXoXNb4ZfURoTCQskUZ6rEok4QVLIikvPCcN5zn/AA)
## Explanation
The bytes `b"FGHJ"` are equivalent to `(0,1,2,4)` mod 7. The 4!=24 possible permutations of these numbers happen to give all 24 possibilities for the first two die numbers. I'm not sure how to demonstrate this, except listing all the possibilities:
```
(0, 1, 2, 4) -> (6, 5)
(0, 1, 4, 2) -> (6, 2)
(0, 2, 1, 4) -> (5, 4)
(0, 2, 4, 1) -> (5, 3)
(0, 4, 1, 2) -> (3, 6)
(0, 4, 2, 1) -> (3, 1)
(1, 0, 2, 4) -> (1, 5)
(1, 0, 4, 2) -> (1, 2)
(1, 2, 0, 4) -> (6, 3)
(1, 2, 4, 0) -> (6, 4)
(1, 4, 0, 2) -> (4, 5)
(1, 4, 2, 0) -> (4, 2)
(2, 0, 1, 4) -> (2, 4)
(2, 0, 4, 1) -> (2, 3)
(2, 1, 0, 4) -> (1, 3)
(2, 1, 4, 0) -> (1, 4)
(2, 4, 0, 1) -> (5, 6)
(2, 4, 1, 0) -> (5, 1)
(4, 0, 1, 2) -> (4, 6)
(4, 0, 2, 1) -> (4, 1)
(4, 1, 0, 2) -> (3, 5)
(4, 1, 2, 0) -> (3, 2)
(4, 2, 0, 1) -> (2, 6)
(4, 2, 1, 0) -> (2, 1)
```
I found this formula partially by trial-and-error, guided by the fact that the set of possible pairs of numbers possesses certain symmetries (e.g., `u` can be replaced with `-u` by swapping `a` with `b`, and `u` and `l` can be swapped by swapping `a` with `c` and `b` with `d`). The formula for the third number is [xnor](https://math.stackexchange.com/questions/1101870/derivation-of-dice-sides-polynomial/1101984#1101984)'s.
] |
[Question]
[
Ulam's spiral is a *truly* fascinating, yet puzzling, topic in mathematics. How it works in detail can be found [here](https://en.wikipedia.org/wiki/Ulam_spiral), but a short summary can be explained as so:
I start off by writing a one, then I write a two to the right of it. Above the two, I write a three, and to the left of that I write four. I continue this pattern of circling around 1 (and any numbers between me and 1) infinitely (or until told to stop), forming a spiral pattern. (see example below)
### The Objective
Make a program that accepts *n* (will always be an odd number greater than zero) as an input that correlates with the number of rows, then prints out the values of the primes row by row of the Ulam spiral. The formatting can be any fashion, but *must* be human readable and obvious.
For example, given the input 3, your program should output `5,3,2,7`, because 3 rows produces the following spiral:
```
5 4 3 <-- first row has the primes 5 and 3
6 1 2 <-- second row has the prime 2
7 8 9 <-- third row has the prime 7
```
As this is a code golf, the answer with the fewest bytes wins (no matter how inefficient)! [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are not acceptable.
[Answer]
# Pyth, 20 bytes
```
f}TPTsuC+R=hZ_GtyQ]]
```
Try it online: [Demonstration](http://pyth.herokuapp.com/?input=3&code=f%7DTPTsuC%2BR%3DhZ_GtyQ%5D%5D)
This code generates the fully Ulam's spiral, connects all lines and filters for primes.
### Explanation:
```
f}TPTsuC+R=hZ_GtyQ]] implicit: Z = 0
u ]] reduce, start with G = [[]]
tyQ for H in [0, 1, ..., 2*input-2] do:
_G reverse the order of the lines
+R=hZ append Z + 1 at the end of each line,
updating Z each time with the new value Z + 1
C update G with the transposed of ^
this gives the Ulam's spiral
s combine all lines to a big list of numbers
f filter for numbers T, which satisfy:
}TPT T appears in the prime-factorization of T
(<==> T is prime)
```
[Answer]
# MATLAB, 48
```
a=fliplr(spiral(input(''))');disp(a(isprime(a)))
```
Basically this creates a spiral of the required size (requested from user), then arranges it so that it appears in the correct row order. This is stored in a. Next it displays all values in a which are prime.
As you said any readable format, I saved a byte and went for the default output of disp() which is (in your test case, n=3):
```
5
3
2
7
```
---
As an added bonus, this works for any n>0, including even numbers. For example, the output for n=10 is:
```
97
61
59
37
31
89
67
17
13
5
3
29
19
2
11
53
41
7
71
23
43
47
83
73
79
```
[Answer]
# CJam, ~~42~~ 33 bytes
```
Xali(2*{_W%zY@,Y+:Y,>a+}*e_{mp},`
```
[Try it online](http://cjam.aditsu.net/#code=YXaali2%2F4*%7BW%25z_0%3D%2C%2C%40f%2B_W%3D)%40%40a%2B%7D*%5C%3Be_%7Bmp%7D%2C%60&input=3)
The latest version includes substantial improvements suggested by @Martin.
The method for building the spiral is to, in each step, rotate the matrix we have so far by 90 degrees, and add a row with additional numbers. This is repeated `(n / 2) * 4` times.
The values in the resulting matrix are then filtered for being primes.
Explanation:
```
Xa Push initial matrix [1].
li Get input and convert to int.
(2* Calculate 2*(n-1), which is the number of rotations and row additions needed.
{ Start rotation loop.
_ Copy current matrix for getting number of rows later.
W% Reverse the order of the rows...
z ... and transpose the matrix. The combination produces a 90 degree rotation.
Y Get next value from variable Y (which is default initialized to 2).
@, Rotate previous matrix to top, and get number of rows. This is the number
of columns after the 90 degree rotation, meaning that it's the length of
the row to be added.
Y+ Add first value to row length to get end value.
:Y Save it in Y. This will be the first value for next added row.
, Create list of values up to end value.
> Slice off values up to start value, leaving only the new values to be added.
a+ Wrap the new row and add it to matrix.
}* End of rotation loop.
e_ Flatten matrix into list.
{mp}, Filter list for primes.
` Convert list to string for output.
```
[Answer]
# Mathematica 223
This appropriates [Kuba's code](https://mathematica.stackexchange.com/questions/50416/generating-an-ulam-spiral) for an Ulam spiral. That's why I'm submitting it as a community wiki. I merely golfed it and selected out the primes, which are listed by the row in which they reside.
```
r=Range;i=Insert;t=Transpose;s@n_:=#~Select~PrimeQ&/@Nest[With[{d=Length@#,l=#[[-1,-1]]},
Composition[i[#,l+3d+2+r[d+2],-1]&,t@i[t@#,l+2d+1+r[d+1],1]&,i[#,l+d+r[d+1,1,-1],1]&,
t@i[t@#,l+r[d,1,-1],-1] &][#,15]]&,{{1}},(n-1)/2]
```
**Example**
```
s{15]
```
>
> {{197, 193, 191}, {139, 137}, {199, 101, 97, 181}, {61, 59,
> 131}, {103, 37, 31, 89, 179}, {149, 67, 17, 13}, {5, 3, 29}, {151,
> 19, 2, 11, 53, 127}, {107, 41, 7}, {71, 23}, {109, 43, 47, 83,
> 173}, {73, 79}, {113}, {157, 163, 167}, {211, 223}}
>
>
>
To improve the display:
```
%// MatrixForm
```
[](https://i.stack.imgur.com/bOFJu.png)
[Answer]
# Mathematica, 118 bytes
```
f=Permute[Range[#*#],Accumulate@Take[Join[{#*#+1}/2,Flatten@Table[(-1)^j i,{j,#},{i,{-1,#}},{j}]],#*#]]~Select~PrimeQ&
```
This generates the Ulam spiral in linear form by noting that the position of each subsequent number can be accumulated as
```
{(n*n + 1)/2, +1, -n, -1, -1, +n, +n, +1, +1, +1, -n, -n, -n, ...}
```
i.e. start from the centre, then move 1 right, 1 up, 2 left, 2 down, 3 right, 3 up, ...
Output:
```
In[515]:= f[5]
Out[515]= {17,13,5,3,19,2,11,7,23}
```
[Answer]
# Javascript, ~~516~~ ~~363~~ ~~304~~ ~~276~~ ~~243~~ 240 Bytes
My solution does not create a dense matrix with the Spiral, instead it returns the index that corresponds to the given number in the Ulam's Matrix of the given order.
So it iterates through the numbers between 2 and M\*M and creates an array of primes with the idx given by the fn ulamIdx
```
M=15;
$=Math;
_=$.sqrt;
/**
* Return M*i+j (i.e. lineal or vector idx for the matrix) of the Ulam Matrix for the given integer
*
* Each Segment (there are 4 in each round) contains a line of consecutive integers that wraps the
* inner Spiral round. In the foCowing example Segments are: {2,3}, {4,5},
* {6,7}, {8,9}, {a,b,c,d}, {e,f,g,h}, {i,j,k,l}, {m,n,o,p}
*
* h g f e d
* i 5 4 3 c
* j 6 1 2 b
* k 7 8 9 a
* l m n o p
*
* @param n integer The integer which position in the Matrix we want.
* @param M integer Matrix Order.
*/
/*
* m: modulus representing step in segment in current spirtal round
* v: Step in current spiral round, i.e. n - (inner spirals greatest num.)
* s: the current Segment one of [1, 2, 3, 4] that represents the current spiral round
* L: Segment Length (Current spiral round Order - 1)
* B: inner Spiral Order, for trib¿vial case 1 it's -1 special case handled differently.
* C: relative line (row or column) corresponding to n in current spiral Round
* R: relative line (column or row) corresponding to n in current spiral Round
* N: Curren (the one that contains n) Spiral (matrix) round Order
* D: Difference between M and the current Spiral round order.
*/
/**
* Runs the loop for every integer between 2 and M*M
* Does not check sanity for M, that should be odd.
*/
r=[];
for (x = 2; x < M * M; x++) {
p=1;
// Is Prime?
for (k = 2; p&&k <= _(x); k++)
if (x % k==0) p=0;
if (p) {
B = $.floor(_(x - 1));
B=B&1?B:B-1;
N = B + 2;
D = (M - N) / 2;
v = x - B * B;
L = B + 1;
s = $.ceil(v / L);
m = v % L || L;
C = D + (s < 3 ? N - m : 1 + m);
R = s&2 ? D + 1 : D + N;
w= s&1 ? M * C + R : M * R + C;
// /*uncomment to debug*/ console.log("X:" + x + ": " + ((s&1) ? [C, R].join() : [R, C].join()));
r[w] = x;
}
}
alert(r);
```
[Minified](http://refresh-sf.com/) looks like this:
```
for(M=15,$=Math,_=$.sqrt,r=[],x=2;x<M*M;x++){for(p=1,k=2;p&&k<=_(x);k++)x%k==0&&(p=0);p&&(B=$.floor(_(x-1)),B=1&B?B:B-1,N=B+2,D=(M-N)/2,v=x-B*B,L=B+1,s=$.ceil(v/L),m=v%L||L,C=D+(s<3?N-m:1+m),R=2&s?D+1:D+N,w=1&s?M*C+R:M*R+C,r[w]=x)}alert(r);
```
For input 15 the output is:
## ,,,,,,,,,,,,,,,,197,,,,193,,191,,,,,,,,,,,,,,,,139,,137,,,,,,199,,101,,,,97,,,,,,,,181,,,,,,,,61,,59,,,,131,,,,103,,37,,,,,,31,,89,,179,,149,,67,,17,,,,13,,,,,,,,,,,,5,,3,,29,,,,,,151,,,,19,,,2,11,,53,,127,,,,107,,41,,7,,,,,,,,,,,,71,,,,23,,,,,,,,,,109,,43,,,,47,,,,83,,173,,,,73,,,,,,79,,,,,,,,,,113,,,,,,,,,,,,157,,,,,,163,,,,167,,,,211,,,,,,,,,,,,223
] |
[Question]
[
What general tips do you have for golfing in [INTERCAL](https://en.wikipedia.org/wiki/INTERCAL)? I'm looking for ideas which can be applied to code golf challenges and are also at least somewhat specific to INTERCAL (i.e. "remove comments" is not a useful answer).
I know exotic languages can be really useful to win golf contests, but I don't see much INTERCAL code around here. Do you have any advice that can help people get competitive code sizes with INTERCAL? Could this language ever be competitive?
*INTERCAL is so underutilized that it doesn't even have a tag. So sad...*
[Answer]
# INTERCAL doesn't specify precedence, but it also doesn't *error* on ambiguous precedence
An expression like
```
#1$#2~#3
```
is ambiguous, and could mean
```
'#1$#2'~#3
```
or
```
#1$'#2~#3'
```
The INTERCAL spec leaves it intentionally unclear which is meant, and in general there's no standard (although C-INTERCAL and CLC-INTERCAL make an effort to match each other in the simpler cases). That said, the original isn't *incorrect*; it's ambiguous and I wouldn't advise using it in production code (but then, I wouldn't advise using INTERCAL itself in production code), but it will have some meaning in the majority of compilers.
In other words, it may be worth just removing grouping characters and hoping your program still works. Most interpreters will parse any given ambiguous expression consistently, so for each pair of grouping characters, there's a 1 in 2 chance it's unnecessary; that can add up to quite some savings. (Unfortunately, INTERCAL parsers tend to be sufficiently confusing that nobody's entirely sure what the rules actually *are*, but it can normally be determined by experiment. In the simplest cases, operators tend to all have equal precedence and to have a consistent associativity.)
[Answer]
# Focus on doing as much work as possible in one statement
INTERCAL's statement identifiers are rather verbose; `DO` is two noise characters on every statement, the statement's name itself also tends to be quite long, and you have to throw in a `PLEASE` every now and then to keep the parser happy. (The best you can do is a ratio of four `DO` to one `PLEASE`, meaning you're using 14 characters in identifiers for every 5 commands.) On the other hand, the expression syntax is fairly terse (ridiculous, but terse). This means that it's often worthwhile fitting part of your program into a single expression even when using multiple statements would be a more "natural" way to do things.
For example, if you want to assign `#1` to `.1` and `#2` to `.2`, instead of doing it in the obvious INTERCAL-72 way:
```
DO.1<-#1DO.2<-#2
```
it's strongly worth considering overloading a random variable to allow you to assign both at once:
```
DO:1<-#1$#2
```
(with `:1/!1$.2'` thrown in somewhere earlier in the program; note that this notation postdates INTERCAL-72 by quite a way, so you'll need to use a modern INTERCAL for this to work). This is only slightly longer even if you take the setup into account, and becomes shorter if you ever need to, or can arrange to, simultaneously assign to `.1` and `.2` more than once.
It's not just calculate commands where this trick works. If you need to stash a variable twice, don't do it like this:
```
DOSTASH.1DOSTASH.1
```
but like this:
```
DOSTASH.1+.1
```
(The `+` notation works for most commands where it could conceptually make sense.)
[Answer]
# Use a single RESUME for all INTERCAL-72-style if consructs
If you need to write the equivalent of an "if" statement, the normal method using INTERCAL-72 code is to `NEXT` twice and then do a computed `RESUME`. (In modern code, often a computed `COME FROM` will be better, but this tip assumes your code prefers `NEXT`.) You almost certainly have to pay the bytes for the first `NEXT`, as it jumps from one branch of the "if" to the other. Sharing the second `NEXT` is also nontrivial, unless you have a lot of "if" statements that go to the same place upon seeing a `#1`. However, the `RESUME` can be anywhere in the program (because control is going to leave it instantly anywhere).
There are two ways to handle this. If you have a lot of "if" statements, then the `RESUME` probably warrants a single-digit line number, so that your second `NEXT` statement can be as short as possible. If possible, try to make it a computed `RESUME` that would naturally occur in your code (admittedly, this is difficult, as it's rare for those to appear in the "normal flow" of code rather than being `NEXT`ed to); then, the only cost is the line number. You'll have to use a single boolean variable for all these `NEXT`s; the universal consensus here is to use `.5`, mostly because it's the variable that the standard library uses for boolean return values.
Alternatively, it's possible to make use of an undocumented (technically underdocumented, because I slipped a hint into the INTERCAL documentation when I noticed) feature of the standard library. Because a central location for a `RESUME` is so useful, the standard library uses one internally. Line numbers in INTERCAL are global (with namespacing conventions, but which can be broken if you know what you're doing), so you can `NEXT` right into the standard library internals if you want to, and in particular, can `NEXT` to *its* central RESUME location. This is sufficiently popular in existing INTERCAL code that standard library replacements tend to have to implement it to avoid breaking existing programs.
The line in question is (either literally or effectively, depending on the implementation):
```
(1001) DO RESUME .5
```
The main reason not to use this is its long line number; if you need to do a lot of INTERCAL-72-style if constructs, it'll be better to use your own to give it a shorter number.
Of course, you can combine the techniques, writing something like
```
(9)DO(1001)NEXT
```
which is only marginally longer than
```
(9)DORESUME.5
```
and has the benefit that the booleans become `#2` and `#3` (which is harder to read, but normally easier to generate). Actually, it might even be worth putting in the extra code to handle `#0` and `#1` if you're going to be iffing a lot (but computed `COME FROM` will probably work better in this case unless your requirements are very weird).
[Answer]
# Whitespace / "noise" removal can go further than you might expect
INTERCAL is a whitespace-insensitive language. Unlike most whitespace-insensitive languages, though, the insensitivity goes much further than you might expect.
For example, `DO NOT` is two tokens, but can be written `DONOT` without the parser complaining (in pretty much any widely used implementation). (Of course, you could also write `DON'T`, but it isn't any terser. It might be easier to read, though. `PLEASEN'T` is probably harder to read than `PLEASE NOT`, though.) Actually, there's some debate as to whether whitespace does anything at all; at least one INTERCAL parser allows it even inside numerical constants (not that that's very useful when golfing). One thing to bear in mind is that removing whitespace from `DO READ OUT` gives `DOREA**DO**UT` which can confuse some older INTERCAL parsers due to the embedded `DO` (although their authors generally consider this a bug, and thus nowadays it typically works in a valid program, it's not advisable to put code like this in the vicinity of a syntax error, as it can be much harder to disambiguate then).
Also remember that you can overpunch characters to save space. In ASCII, you can only really pull this off with `'.` → `!`, but that's a highly useful trick in its own right. (When you aren't using arrays, there's no possibility of a sparkears ambiguity even when all your grouping characters are the same, so for golfing entries, it's recommended to stick to just `'` unless an array subscript genuinely requires a `"`.) A bookworm can be represented in one byte by using the `?` abbreviation (C-INTERCAL) or Latin-1 for `¥` (CLC-INTERCAL), rather than the three that INTERCAL-72 needs.
[Answer]
# In C-INTERCAL, consider abbreviating code using `CREATE`
The `CREATE` statement allows you to create new syntax. This is particularly useful in golfing because it allows you to give statements shorter names. You can also use it to effectively "define a function" via creating a new operator (which has the huge advantage that it lets you call the function in the middle of an expression).
The setup cost here is fairly high, but if there's a construct that you use a lot, inventing shorter syntax for it is probably going to be a good idea.
[Answer]
# Golfing off GIVE UP statements
1. Trailing GIVE UP statement can be removed, as it will cause E633 error in C-INTERCAL or error 000 or 633 in CLC-INTERCAL to abort.
2. Replace GIVE UP statements with incomplete statements such as DO or D (`D` worked on CLC-INTERCAL but not on C-INTERCAL, if without compiler option.).
3. RETRIVE unSTASHed variable, RESUME #0, and many other runtime errors can also be alternatives.
4. ABSTAINFROM non-existing labels, invalid labels, etc. Same applied for REINSTATE.
[Answer]
# Calculated `COMEFROM`, `NEXTFROM`.
* `COMEFROM(9)` and `COMEFROM#9` are equivalent. This works for C-INTERCAL and CLC-INTERCAL.
* CLC-INTERCAL has `NEXTFROM`, as `DO(XXX)NEXT` to be obsolete (which requires a compiler option). As well as COMEFROM statement, it supports labels to be computed.
* Since label numbers can be calculated, some complicated equations such as `DOCOMEFROM.1~.1` can be available.
[Answer]
# Dividing a variable by two.
```
DONOTe this is very long. Using C-INTERCAL library.
DO.1<-.9DO.2<-#2DO(1040)NEXTDO.9<-.3
DONOTe shorter way.
DONOTe The number can be smaller if you know that
DONOTe .9 shall have smaller value.
DO.9<-.9~#65534
```
Similar goes to dividing by 2^n.
[Answer]
# Golfing newline output in CLC-INTERCAL
```
DO,1<-#1DOREADOUT;1+,1
```
where `;1` is a string to output.
[Answer]
# CLC-INTERCAL (sick) can `ABSTAIN` and/or `REINSTATE` non-existing label.
C-INTERCAL (ick), on the other hand, makes it compiler error.
[Answer]
# CLC-INTERCAL 1.-94 does not check politeness of the program.
So every `PLEASE` and `PLEASEDO` can be replaced with `DO`.
] |
[Question]
[
For a given positive integer `n`, consider all binary strings of length `2n-1`. For a given string `S`, let `L` be an array of length `n` which contains the count of the number of `1`s in each substring of length `n` of `S`. For example, if `n=3` and `S = 01010` then `L=[1,2,1]`. We call `L` the counting array of `S`.
We say that two strings `S1` and `S2` of the same length *match* if their respective counting arrays `L1` and `L2` have the property that `L1[i] <= 2*L2[i]` and `L2[i] <= 2*L1[i]` for all `i`.
**Task**
For increasing `n` starting at `n=1`, the task is to find the size of the largest set of strings, each of length `2n-1` so that no two strings match.
Your code should output one number per value of `n`.
**Score**
Your score is the highest `n` for which no one else has posted a higher correct answer for any of your answers. Clearly if you have all optimum answers then you will get the score for the highest `n` you post. However, even if your answer is not the optimum, you can still get the score if no one else can beat it.
**Example answers**
For `n=1,2,3,4` I get `2,4,10,16`.
**Languages and libraries**
You can use any available language and libraries you like. Where feasible, it would be good to be able to run your code so please include a full explanation for how to run/compile your code in linux if at all possible.
**Leading entries**
* **5** by Martin Büttner in **Mathematica**
* **6** by Reto Koradi in **C++**. Values are `2, 4, 10, 16, 31, 47, 75, 111, 164, 232, 328, 445, 606, 814, 1086`. The first 5 are known to be optimal.
* **7** by Peter Taylor in **Java**. Values are `2, 4, 10, 16, 31, 47, 76, 111, 166, 235`.
* **9** by joriki in **Java**. Values are `2, 4, 10, 16, 31, 47, 76, 112, 168`.
[Answer]
## 2, 4, 10, 16, 31, 47, 76, 111, 166, 235
### Notes
If we consider a graph `G` with vertices `0` to `n` and edges joining two numbers which match, then the [tensor power](https://en.wikipedia.org/wiki/Tensor_product_of_graphs) `G^n` has vertices `(x_0, ..., x_{n-1})` forming the Cartesian power `{0, ..., n}^n` and edges between matching tuples. The graph of interest is the subgraph of `G^n` [induced](http://mathworld.wolfram.com/Vertex-InducedSubgraph.html) by those vertices which correspond to the possible "counting arrays".
So the first subtask is to generate those vertices. The naïve approach enumerates over `2^{2n-1}` strings, or on the order of `4^n`. But if we instead look at the array of first differences of the counting arrays we find that there are only `3^n` possibilities, and from the first differences we can deduce the range of possible initial values by requiring that no element in the zeroth differences is less than `0` or greater than `n`.
We then want to find the maximum independent set. I'm using one theorem and two heuristics:
* Theorem: the maximum independent set of a disjoint union of graphs is the union of their maximum independent sets. So if we break a graph down into unconnected components we can simplify the problem.
* Heuristic: assume that `(n, n, ..., n)` will be in a maximum independent set. There's a fairly large clique of vertices `{m, m+1, ..., n}^n` where `m` is the smallest integer which matches `n`; `(n, n, ..., n)` is guaranteed to have no matches outside that clique.
* Heuristic: take the greedy approach of selecting the vertex of lowest degree.
On my computer this finds `111` for `n=8` in 16 seconds, `166` for `n=9` in about 8 minutes, and `235` for `n=10` in about 2 hours.
### Code
Save as `PPCG54354.java`, compile as `javac PPCG54354.java`, and run as `java PPCG54354`.
```
import java.util.*;
public class PPCG54354 {
public static void main(String[] args) {
for (int n = 1; n < 20; n++) {
long start = System.nanoTime();
Set<Vertex> constructive = new HashSet<Vertex>();
for (int i = 0; i < (int)Math.pow(3, n-1); i++) {
int min = 0, max = 1, diffs[] = new int[n-1];
for (int j = i, k = 0; k < n-1; j /= 3, k++) {
int delta = (j % 3) - 1;
if (delta == -1) min++;
if (delta != 1) max++;
diffs[k] = delta;
}
for (; min <= max; min++) constructive.add(new Vertex(min, diffs));
}
// Heuristic: favour (n, n, ..., n)
Vertex max = new Vertex(n, new int[n-1]);
Iterator<Vertex> it = constructive.iterator();
while (it.hasNext()) {
Vertex v = it.next();
if (v.matches(max) && !v.equals(max)) it.remove();
}
Set<Vertex> ind = independentSet(constructive, n);
System.out.println(ind.size() + " after " + ((System.nanoTime() - start) / 1000000000L) + " secs");
}
}
private static Set<Vertex> independentSet(Set<Vertex> vertices, int dim) {
if (vertices.size() < 2) return vertices;
for (int idx = 0; idx < dim; idx++) {
Set<Set<Vertex>> p = connectedComponents(vertices, idx);
if (p.size() > 1) {
Set<Vertex> ind = new HashSet<Vertex>();
for (Set<Vertex> part : connectedComponents(vertices, idx)) {
ind.addAll(independentSet(part, dim));
}
return ind;
}
}
// Greedy
int minMatches = Integer.MAX_VALUE;
Vertex minV = null;
for (Vertex v0 : vertices) {
int numMatches = 0;
for (Vertex vi : vertices) if (v0.matches(vi)) numMatches++;
if (numMatches < minMatches) {
minMatches = numMatches;
minV = v0;
}
}
Set<Vertex> nonmatch = new HashSet<Vertex>();
for (Vertex vi : vertices) if (!minV.matches(vi)) nonmatch.add(vi);
Set<Vertex> ind = independentSet(nonmatch, dim);
ind.add(minV);
return ind;
}
// Separates out a set of vertices which form connected components when projected into the idx axis.
private static Set<Set<Vertex>> connectedComponents(Set<Vertex> vertices, final int idx) {
List<Vertex> sorted = new ArrayList<Vertex>(vertices);
Collections.sort(sorted, new Comparator<Vertex>() {
public int compare(Vertex a, Vertex b) {
return a.x[idx] - b.x[idx];
}
});
Set<Set<Vertex>> connectedComponents = new HashSet<Set<Vertex>>();
Set<Vertex> current = new HashSet<Vertex>();
int currentVal = 0;
for (Vertex v : sorted) {
if (!match(currentVal, v.x[idx]) && !current.isEmpty()) {
connectedComponents.add(current);
current = new HashSet<Vertex>();
}
current.add(v);
currentVal = v.x[idx];
}
if (!current.isEmpty()) connectedComponents.add(current);
return connectedComponents;
}
private static boolean match(int a, int b) {
return a <= 2 * b && b <= 2 * a;
}
private static class Vertex {
final int[] x;
private final int h;
Vertex(int[] x) {
this.x = x.clone();
int _h = 0;
for (int xi : x) _h = _h * 37 + xi;
h = _h;
}
Vertex(int x0, int[] diffs) {
x = new int[diffs.length + 1];
x[0] = x0;
for (int i = 0; i < diffs.length; i++) x[i+1] = x[i] + diffs[i];
int _h = 0;
for (int xi : x) _h = _h * 37 + xi;
h = _h;
}
public boolean matches(Vertex v) {
if (v == this) return true;
if (x.length != v.x.length) throw new IllegalArgumentException("v");
for (int i = 0; i < x.length; i++) {
if (!match(x[i], v.x[i])) return false;
}
return true;
}
@Override
public int hashCode() {
return h;
}
@Override
public boolean equals(Object obj) {
return (obj instanceof Vertex) && equals((Vertex)obj);
}
public boolean equals(Vertex v) {
if (v == this) return true;
if (x.length != v.x.length) return false;
for (int i = 0; i < x.length; i++) {
if (x[i] != v.x[i]) return false;
}
return true;
}
@Override
public String toString() {
if (x.length == 0) return "e";
StringBuilder sb = new StringBuilder(x.length);
for (int xi : x) sb.append(xi < 10 ? (char)('0' + xi) : (char)('A' + xi - 10));
return sb.toString();
}
}
}
```
[Answer]
# Mathematica, `n = 5`, 31 strings
I just wrote a brute force solution using Mathematica's built-ins to verify Lembik's example answers, but it can handle `n = 5` as well:
```
n = 5;
s = Tuples[{0, 1}, 2 n - 1];
l = Total /@ Partition[#, n, 1] & /@ s
g = Graph[l,
Cases[Join @@ Outer[UndirectedEdge, l, l, 1],
a_ <-> b_ /;
a != b && And @@ Thread[a <= 2 b] && And @@ Thread[b <= 2 a]]]
set = First@FindIndependentVertexSet[g]
Length@set
```
As a bonus, this code produces a visualisation of the problem as a graph where each edge indicates two matching strings.
Here is the graph for `n = 3`:
[](https://i.stack.imgur.com/Zxa6E.png)
[Answer]
# 2, 4, 10, 16, 31, 47, 76, 112, 168
For each n, this Java code determines the possible counting arrays and then finds non-matching sets of increasing size, for each size starting with a random set and improving it by randomized steepest descent. In each step, one of the elements of the set is randomly uniformly selected and replaced by another counting array randomly uniformly selected among the ones not in use. The step is accepted if it does not increase the number of matches. This latter prescription appears to be crucial; accepting steps only if they reduce the number of matches isn't nearly as effective. The steps leaving the number of matches invariant allow the search space to be explored, and eventually some space may open up to avoid one of the matches. After 2^24 steps without improvement, the previous size is output for the present value of n, and n is incremented.
The results up to n = 9 are `2, 4, 10, 16, 31, 47, 76, 112, 168`, improving on the previous results for n = 8 by one and for n = 9 by two. For higher values of n, the limit of 2^24 steps may have to be increased.
I also tried simulated annealing (with the number of matches as the energy), but without improvement over steepest descent.
### Code
save as `Question54354.java`
compile with `javac Question54354.java`
run with `java Question54354`
```
import java.util.Arrays;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
public class Question54354 {
static class Array {
int [] arr;
public Array (int [] arr) {
this.arr = arr;
}
public int hashCode () {
return Arrays.hashCode (arr);
}
public boolean equals (Object o) {
return Arrays.equals (((Array) o).arr,arr);
}
}
static int [] indices;
static int [] [] counts;
static boolean [] used;
static Random random = new Random (0);
static boolean match (int [] c1,int [] c2) {
for (int k = 0;k < c1.length;k++)
if (c1 [k] > 2 * c2 [k] || c2 [k] > 2 * c1 [k])
return false;
return true;
}
static int matches (int i) {
int result = 0;
for (int j = 0;j < indices.length;j++)
if (j != i && match (counts [indices [i]],counts [indices [j]]))
result++;
return result;
}
static void randomize (int i) {
do
indices [i] = random.nextInt (counts.length);
while (used [indices [i]]);
}
public static void main (String [] args) {
for (int n = 1,length = 1;;n++,length += 2) {
int [] lookup = new int [1 << n];
for (int string = 0;string < 1 << n;string++)
for (int bit = 1;bit < 1 << n;bit <<= 1)
if ((string & bit) != 0)
lookup [string]++;
Set<Array> arrays = new HashSet<Array> ();
for (int string = 0;string < 1 << length;string++) {
int [] count = new int [n];
for (int i = 0;i < n;i++)
count [i] = lookup [(string >> i) & ((1 << n) - 1)];
arrays.add (new Array (count));
}
counts = new int [arrays.size ()] [];
int j = 0;
for (Array array : arrays)
counts [j++] = array.arr;
used = new boolean [counts.length];
int m;
outer:
for (m = 1;m <= counts.length;m++) {
indices = new int [m];
for (;;) {
Arrays.fill (used,false);
for (int i = 0;i < m;i++) {
randomize (i);
used [indices [i]] = true;
}
int matches = 0;
for (int i = 0;i < m;i++)
matches += matches (i);
matches /= 2;
int stagnation = 0;
while (matches != 0) {
int k = random.nextInt (m);
int oldMatches = matches (k);
int oldIndex = indices [k];
randomize (k);
int newMatches = matches (k);
if (newMatches <= oldMatches) {
if (newMatches < oldMatches) {
matches += newMatches - oldMatches;
stagnation = 0;
}
used [oldIndex] = false;
used [indices [k]] = true;
}
else
indices [k] = oldIndex;
if (++stagnation == 0x1000000)
break outer;
}
break;
}
}
System.out.println (n + " : " + (m - 1));
}
}
}
```
[Answer]
# C++ (heuristic): 2, 4, 10, 16, 31, 47, 75, 111, 164, 232, 328, 445, 606, 814, 1086
This is slightly behind Peter Taylor's result, being 1 to 3 lower for `n=7`, `9` and `10`. The advantage is that it's much faster, so I can run it for higher values of `n`. And it can be understood without any fancy math. ;)
The current code is dimensioned to run up to `n=15`. Run times increase roughly by a factor of 4 for each increase in `n`. For example, it was 0.008 second for `n=7`, 0.07 seconds for `n=9`, 1.34 seconds for `n=11`, 27 seconds for `n=13`, and 9 minutes for `n=15`.
There are two key observations I used:
* Instead of operating on the values themselves, the heuristic operates on counting arrays. To do this, a list of all unique counting arrays is generated first.
* Using counting arrays with small values is more beneficial, since they eliminate less of the solution space. This is based on each count `c` excluding the range of `c / 2` to `2 * c` from other values. For smaller values of `c`, this range is smaller, which means that fewer values are excluded by using it.
### Generate Unique Counting Arrays
I went brute force on this one, iterating through all values, generating the count array for each of them, and uniquifying the resulting list. This could certainly be done more efficiently, but it is good enough for the kinds of values we're operating with.
This is extremely quick for the small values. For the larger values, the overhead does become substantial. For example, for `n=15`, it uses about 75% of the whole runtime. This would definitely be an area to look at when trying to go much higher than `n=15`. Even just the memory usage for building a list of the counting arrays for all values would start to become problematic.
The number of unique counting arrays is about 6% of the number of values for `n=15`. This relative count becomes smaller as `n` becomes larger.
### Greedy Selection of Counting Array Values
The main part of the algorithm selects counting array values from the generated list using a simple greedy approach.
Based on the theory that using counting arrays with small counts is beneficial, the counting arrays are sorted by the sum of their counts.
They are then checked in order, and a value is selected if it is compatible with all previously used values. So this involves one single linear pass through the unique counting arrays, where each candidate is compared to the values that were previously selected.
I have some ideas on how the heuristic could potentially be improved. But this seemed like a reasonable starting point, and the results looked quite good.
### Code
This is not highly optimized. I had a more elaborate data structure at some point, but it would have needed more work to generalize it beyond `n=8`, and the difference in performance did not seem very substantial.
```
#include <cstdint>
#include <cstdlib>
#include <vector>
#include <algorithm>
#include <sstream>
#include <iostream>
typedef uint32_t Value;
class Counter {
public:
static void setN(int n);
Counter();
Counter(Value val);
bool operator==(const Counter& rhs) const;
bool operator<(const Counter& rhs) const;
bool collides(const Counter& other) const;
private:
static const int FIELD_BITS = 4;
static const uint64_t FIELD_MASK = 0x0f;
static int m_n;
static Value m_valMask;
uint64_t fieldSum() const;
uint64_t m_fields;
};
void Counter::setN(int n) {
m_n = n;
m_valMask = (static_cast<Value>(1) << n) - 1;
}
Counter::Counter()
: m_fields(0) {
}
Counter::Counter(Value val) {
m_fields = 0;
for (int k = 0; k < m_n; ++k) {
m_fields <<= FIELD_BITS;
m_fields |= __builtin_popcount(val & m_valMask);
val >>= 1;
}
}
bool Counter::operator==(const Counter& rhs) const {
return m_fields == rhs.m_fields;
}
bool Counter::operator<(const Counter& rhs) const {
uint64_t lhsSum = fieldSum();
uint64_t rhsSum = rhs.fieldSum();
if (lhsSum < rhsSum) {
return true;
}
if (lhsSum > rhsSum) {
return false;
}
return m_fields < rhs.m_fields;
}
bool Counter::collides(const Counter& other) const {
uint64_t fields1 = m_fields;
uint64_t fields2 = other.m_fields;
for (int k = 0; k < m_n; ++k) {
uint64_t c1 = fields1 & FIELD_MASK;
uint64_t c2 = fields2 & FIELD_MASK;
if (c1 > 2 * c2 || c2 > 2 * c1) {
return false;
}
fields1 >>= FIELD_BITS;
fields2 >>= FIELD_BITS;
}
return true;
}
int Counter::m_n = 0;
Value Counter::m_valMask = 0;
uint64_t Counter::fieldSum() const {
uint64_t fields = m_fields;
uint64_t sum = 0;
for (int k = 0; k < m_n; ++k) {
sum += fields & FIELD_MASK;
fields >>= FIELD_BITS;
}
return sum;
}
typedef std::vector<Counter> Counters;
int main(int argc, char* argv[]) {
int n = 0;
std::istringstream strm(argv[1]);
strm >> n;
Counter::setN(n);
int nBit = 2 * n - 1;
Value maxVal = static_cast<Value>(1) << nBit;
Counters allCounters;
for (Value val = 0; val < maxVal; ++val) {
Counter counter(val);
allCounters.push_back(counter);
}
std::sort(allCounters.begin(), allCounters.end());
Counters::iterator uniqEnd =
std::unique(allCounters.begin(), allCounters.end());
allCounters.resize(std::distance(allCounters.begin(), uniqEnd));
Counters solCounters;
int nSol = 0;
for (Value idx = 0; idx < allCounters.size(); ++idx) {
const Counter& counter = allCounters[idx];
bool valid = true;
for (int iSol = 0; iSol < nSol; ++iSol) {
if (solCounters[iSol].collides(counter)) {
valid = false;
break;
}
}
if (valid) {
solCounters.push_back(counter);
++nSol;
}
}
std::cout << "result: " << nSol << std::endl;
return 0;
}
```
] |
[Question]
[
Your friend isn't too good with computers so as a practical joke someone scrambled the letters (a-z) on his keyboard. When he sit down and tried to type his name looking at the keyboard he realized that the letters are scrambled and asked your help.
You are smart so you know that if he types his name and then repeatedly retypes what comes up on the screen instead of his name he will succeed inputting in his name eventually. You are also kind and rearrange the keys but want to know how many turns would it take to succeed.
Your task is to write a program or function that given the shuffling of the letters and the friend's name computes the number of turns.
## Input details:
* Two string are given as input in a structure convenient for your language.
* The first string is the list of the new lowercase letters in alphabetical order of the old ones. (The first character is the one that is at the position of `a`, last one is at the position of `z`.) Some change will always occur in the string.
* The second string is the name. It could contain any printable ascii character but only the upper and lowercase alphabetical characters will be shuffled if any. The name itself might not get shuffled at al.
## Output details:
* Output is a single integer the number of turns minimally required. Newline is optional.
## Examples:
Input:
`'abcfdeghijklmnopqrstuvwxyz' 'Mr. John Doe'` (d, e, f positions changed)
Output:
`3` (The shown names are: `Mr. John Fod` => `Mr. John Eof` => `Mr. John Doe` )
Input:
`'nopqrstuvwxyzabcdefghijklm' 'Mr. John Doe'` (the [ROT13 cipher](http://en.wikipedia.org/wiki/ROT13))
Output:
`2` (Any input name that contains letters will take `2` rounds to produce the original name.)
Input:
`'aebcdjfghiqklmnopzrstuvwxy' 'John Doe'`
Output:
`140`
This is code-golf so the shortest entry wins.
[Answer]
# CJam, ~~31 27 25~~ 24 bytes
```
l:A;lel:N{_A_$er_N#}g;],
```
Takes input in the form of:
```
aebcdjfghiqklmnopzrstuvwxy
Mr. John Doe
```
i.e. first line - alphabets, second line - name.
**How it works**:
```
l:A;lel:N{_A_$er_N#}g;],
l:A; "Read the alphabets from the 1st line in A and pop from stack";
lel:N "Read the name in small caps from 2nd line and store in N";
{ }g "Run a while loop until we have the original name back again";
_ "Put a dummy string on stack just to keep count of times";
A "Put the alphabets on stack";
_$ "Copy them and sort the copy to get the correct order";
er "Transliterate the right keys with the wrong ones";
_N# "Copy the result and see if its equal to the original name";
;] "Pop the last name and wrap everything in an array";
, "Get the length now. Since we were putting a dummy string";
"on stack in each iteration of the while loop, this length";
"represents the number of times we tried typing the name";
```
[Try it online here](http://cjam.aditsu.net/)
[Answer]
# Pyth, 16 bytes
```
JGfqzuXGJrQ0UTz1
```
[Try it here.](http://pyth.herokuapp.com/)
Input should be given on two lines, name and then permutation. Permutation should be quoted. Name may be quoted or unquoted. For example:
```
"John Doe"
"aebcdjfghiqklmnopzrstuvwxy"
```
Gives 140.
### Explanation:
```
Implicit:
z = input() z is the name.
Q = eval(input()) Q is the permutation.
G = 'abcdefghijklmnopqrstuvwxyz'
JG J = G
f 1 Starting at 1 and counting upwards, find
the first case where the following is true:
qz z ==
u UTz reduce, where the accumulator, G, is initialized to z on
XG translate G
J from the normal alphabet, J
rQ0 to Q.lower().
```
[Answer]
# Ruby, 58
```
->a,n{t=""+n
(1..2e3).find{t.tr!("a-zA-Z",a+a.upcase)==n}}
```
### Explanation
* Input is taken as arguments to a lambda.
* Use `Enumerable#find` (thanks @Ventero!) and `String#tr!` to replace characters until the replaced `String` matches the real name.
[Answer]
# CJam, ~~32~~ 31 bytes
```
llel_2e3,{;'{,97>3$er_2$=}#)p];
```
[Test it here.](http://cjam.aditsu.net/) It takes the permutation on the first line, and the name on the second line of the input.
## Explanation
```
llel_2e3,{;'{,97>3$er_2$=}#)p];
ll "Read both lines into strings.";
el_ "Convert the name to lower-case and duplicate.";
2e3, "Get a range from 0 to 1999 to cover all possible results.";
{ }# "Find the first index where the block yields a true result.";
; "Discard the number, it's just a dummy.";
'{,97> "Create a string of the lower-case alphabet.";
3$ "Copy the permutation.";
er "Substitute letters in the second copy of the name.";
_2$= "Duplicate and check for equality with original name.";
)p "Increment by 1 and print.";
]; "Clear the stack to prevent extraneous output.";
```
[Answer]
## [Pyth](https://github.com/isaacg1/pyth) 26
```
KGJ@GrQZfqJusm@zxKdGUTJ!!J
```
[Try it online here.](https://pyth.herokuapp.com/)
There are quite a few unfortunate consequences that cost this program bytes, like having to store G in K to use it in the reduce, as well as needing to use not(not(J)) to start the filter. Because of this, I expect this can still be golfed.
This is a program that takes input like:
```
aebcdjfghiqklmnopzrstuvwxy
'John Doe'
```
(Note the lack of quotes in the first argument)
Explanation to come after crippling exhaustion ;)
[Answer]
# Haskell 131 bytes
```
import Data.Char
h n=(!!((ord n)-97))
g s n m|n==m=1|0<1=1+g s(h n s)m
f s=foldr1 lcm.map((\x->g s(h x s)x).toLower).filter isAlpha
```
Call `f` with the permutation string and name to get the result
### Explanation
```
-- h finds the mapping of a character given the permutation
h :: Char -> -- Character to map
String -> -- Character permutation
Char -- Mapped character
-- g finds the number of character mappings required to reach a given character
-- by calling h on the given character every time it calls itself.
g :: String -> -- The character permutation
Char -> -- The current character
Char -> -- The character to find
Int -- The number of mapped to find the character
-- f finds the number of mappings required to return the given string back to itself
-- by finding the lowest common multiple of the period of all the characters in the
-- given string
g :: String -> -- The permutation string
String -> -- The string to get back
Int -- The final answer
```
[Answer]
## GolfScript (33 bytes)
```
~{32|}%\:A&{.{A$?A=}%.-1$=!}do],(
```
Takes input as two (single- or double-) quoted strings separated by any amount of whitespace; e.g.
```
'abcfdeghijklmnopqrstuvwxyz' 'Mr. John Doe'
```
[Online demo](http://golfscript.apphb.com/?c=OyInYWJjZmRlZ2hpamtsbW5vcHFyc3R1dnd4eXonICdNci4gSm9obiBEb2UnIgoKfnszMnx9JVw6QSZ7LntBJD9BPX0lLi0xJD0hfWRvXSwo)
### Dissection
```
~ # Eval. Stack: perm name
{32|}% # Lower-case name (also affects non-alphabetic characters but...)
\:A& # Store perm in A and filter name to alphabetic characters, giving str_0
{ # do-while loop. Stack: str_0 str_1 ... str_i
. # Duplicate str_i
{A$?A=}% # tr 'a-z' perm giving str_{i+1}
.-1$=! # Loop while str_{i+1} != str_0
}do # end do-while loop
],( # Gather the sequence of permuted strings in an array and take its length - 1
# to account for containing str_0 twice
```
The transliteration relies on the fact that all the characters are affected (it's [`{'ABC'?'abc'=}%`](https://codegolf.stackexchange.com/a/6273/194) with the sorted string `A$` replacing `'ABC'` and the permutation `A` replacing `'abc'`); the more general alternatives don't save enough because the filter to alphabetic characters is so cheap.
This also relies on `-1$` to access the bottom of the stack, which is a relatively rare GS trick.
] |
[Question]
[
Your job is to convert decimals back into the sum of the square roots of integers. The result has to have an accuracy of at least 6 significant decimal digits.
**Input**:
A number indicating the number of square roots and a decimal indicating the number to approximate.
Example input:
```
2 3.414213562373095
```
**Output**:
Integers separated by spaces that, when square rooted and added, are approximately the original decimal accurate to at least 6 significant decimal digits.
Zeros are not allowed in the solution.
If there are multiple solutions, you only have to print one.
Example output (in any order):
```
4 2
```
This works because `Math.sqrt(4) + Math.sqrt(2) == 3.414213562373095`.
This is code golf. Shortest code (with optional bonus) wins!
There is always going to be a solution but -10 if your program prints "No" when there is no solution with integers. In addition, -10 if your program prints all solutions (separated by newlines or semicolons or whatever) instead of just one.
Test cases:
```
3 7.923668178593959 --> 6 7 8
2 2.8284271247461903 --> 2 2
5 5.0 --> 1 1 1 1 1
5 13.0 --> 4 4 9 9 9 --> 81 1 1 1 1 --> 36 9 4 1 1 etc. [print any, but print all for the "all solutions bonus"]
```
And yes, your program has to finish in finite time using finite memory on any reasonable machine. It can't just work "in theory," you have to be able to actually test it.
[Answer]
# Python 3, 90 - 10 = 80
```
def S(N,x,n=[],i=1):
if x*x<1e-12>N==0:print(*n)
while.1+x*x>i:S(N-1,x-i**.5,n+[i]);i+=1
```
*(Mega thanks to @xnor for tips, especially the restructuring of the for loop into a while)*
A simple recursive attempt. It starts off with the target number and continuously subtracts square roots until it hits 0 or lower. The function `S` can be called like `S(2,3.414213562373095)` (the second argument is assumed to be positive).
The program doesn't just print out all solutions, it prints out all *permutations* of solutions (a little extraneous, I know). Here's the output for the last case: [Pastebin](http://pastebin.com/zd6ETJsX).
A slight tweak gives a **98 - 10 = 88** solution which doesn't print permutations, making it more efficient:
```
def S(N,x,n=[]):
*_,i=[1]+n
if x*x<1e-12>N==0:print(*n)
while.1+x*x>i:S(N-1,x-i**.5,n+[i]);i+=1
```
And just for fun, this **99 - 10 = 89** one is about as efficient as it gets (unlike the others, it doesn't blow the stack on `S(1,1000)`:
```
def S(N,x,n=[]):
*_,i=[1]+n
if x*x<1e-12>N:print(*n)
while(.1+x*x>i)*N:S(N-1,x-i**.5,n+[i]);i+=1
```
*Note that, although we have a mutable default argument, this never causes a problem if we rerun the function since `n+[i]` creates a new list.*
---
## Proof of correctness
In order to end up in an infinite loop, we must hit some point where *x < 0* and *0.1 + x2 > 1*. This is satisfied by *x < -0.948...*.
But note that we start from positive *x* and *x* is always decreasing, so in order to hit *x < -0.948...* we must have had *x' - i0.5 < -0.948...* for some *x' > -0.948...* before *x* and positive integer *i*. For the while loop to run, we must also have had *0.1 + x'2 > i*.
Rearranging we get *x'2 + 1.897x' + 0.948 < i < 0.1 + x'2*, the outer parts implying that *x' < -0.447*. But if *-0.948 < x' < -0.447*, then no positive integer *i* can fit the gap in the above inequality.
Hence we'll never end up in an infinite loop.
[Answer]
## ECLiPSe Prolog - 118 (138-20)
I used the following implementation of Prolog: <http://eclipseclp.org/>
```
:-lib(util).
t(0,S,[]):-!,S<0.00001,S> -0.00001.
t(N,S,[X|Y]):-A is integer(ceiling(S*S)),between(1,A,X),M is N-1,T is S-sqrt(X),t(M,T,Y).
```
This is a very naive, exponential approach.
Listing all possible solutions takes time to cover all combinations (*edit*: the range of visited integers now decreases at each step, which removes a lot of useless combinations).
Here follows a transcript of a test session. By default, the environment will try to find all possible solutions (-10) and prints "No" when it fails to do so (-10).
As Sp3000 properly noted in the comment, it also prints "Yes" when it succeeds. That surely means I can remove 10 more points ;-)
```
[eclipse 19]: t(1,0.5,R).
No (0.00s cpu)
[eclipse 20]: t(2,3.414213562373095,R).
R = [2, 4]
Yes (0.00s cpu, solution 1, maybe more) ? ;
R = [4, 2]
Yes (0.00s cpu, solution 2, maybe more) ? ;
No (0.01s cpu)
[eclipse 21]: t(3,7.923668178593959,R).
R = [6, 7, 8]
Yes (0.02s cpu, solution 1, maybe more) ? ;
R = [6, 8, 7]
Yes (0.02s cpu, solution 2, maybe more) ? ;
R = [7, 6, 8]
Yes (0.02s cpu, solution 3, maybe more) ?
[eclipse 22]: t(5,5.0,R).
R = [1, 1, 1, 1, 1]
Yes (0.00s cpu, solution 1, maybe more) ? ;
^C
interruption: type a, b, c, e, or h for help : ? abort
Aborting execution ...
Abort
[eclipse 23]: t(5,13.0,R).
R = [1, 1, 1, 1, 81]
Yes (0.00s cpu, solution 1, maybe more) ? ;
R = [1, 1, 1, 4, 64]
Yes (0.00s cpu, solution 2, maybe more) ? ;
R = [1, 1, 1, 9, 49]
Yes (0.00s cpu, solution 3, maybe more) ?
[eclipse 24]:
```
---
**(Edit)** Regarding performance, it is quite good, at least compared to other ones (see for example [this comment from FryAmTheEggman](https://codegolf.stackexchange.com/questions/41909/undo-the-square-roots#comment97900_41909)). First, if you want to print all results, add the following predicate:
```
p(N,S):-t(N,S,L),write(L),fail.
p(_,_).
```
See <http://pastebin.com/ugjfEHpw> for the (5,13.0) case, which completes in 0.24 seconds and find 495 solutions (but maybe I am missing some solutions, I don't know).
[Answer]
# Erlang, ~~305-10~~ 302-10
```
f(M,D)->E=round(D*D),t(p(E,M,1),{M,E,D}).
p(_,0,A)->A;p(E,N,A)->p(E,N-1,A*E).
t(-1,_)->"No";t(I,{N,E,D}=T)->L=q(I,N,E,[]),V=lists:sum([math:sqrt(M)||M<-L])-D,if V*V<0.1e-9->lists:flatten([integer_to_list(J)++" "||J<-L]);true->t(I-1,T)end.
q(I,1,_,A)->[I+1|A];q(I,N,E,A)->q(I div E,N-1,E,[I rem E+1|A]).
```
This function returns string "No" or a string with values separated by spaces. It (inefficiently) processes every possible values encoding them into a large integer, and starting with higher values. 0 are not allowed in the solution, and encoded 0 represents all ones. Error is squared.
Example:
```
f(1,0.5). % returns "No"
f(2,3.414213562373095). % returns "4 2 "
f(3,7.923668178593959). % returns "8 7 6 "
f(5,5.0). % returns "1 1 1 1 1 "
f(5,13.0). % returns "81 1 1 1 1 "
```
Please be patient with `f(5,13.0)` as function search space is 13^10. It can be made faster with 2 additional bytes.
[Answer]
### Python ~~3~~ 2: ~~173~~ 159 - 10 = 149
Explanation:
Each solution is of the form x\_1 x\_2 ... x\_n with 1 <= x\_1 <= x^2 where x is the target sum. Therefore we can encode each solution as an integer in base x^2. The while loop iterates over all (x^2)^n possibilities. Then I convert the integer back and test the sum. Pretty straight forward.
```
i=input;n=int(i());x=float(i());m=int(x*x);a=m**n
while a:
s=[a/m**b%m+1for b in range(n)];a-=1
if abs(x-sum(b**.5for b in s))<1e-5:print' '.join(map(str,s))
```
It finds all solutions, but the last test case takes way too long.
[Answer]
# JavaScript (ES6) 162 (172 - 10) ~~173~~
*Edit* A little shorter, a little slower.
As a function with 2 parameters, output to javascript console. This prints all solutions with no repetitions (solutions tuples are generated already sorted).
I cared more about timing than about char count, so that it's easily tested in a browser console within the standard javascript time limit.
(Feb 2016 update) Current time for last test case: about 1 ~~150 secs~~. Memory requirements: negligible.
```
F=(k,t,z=t- --k,r=[])=>{
for(r[k]=z=z*z|0;r[k];)
{
for(;k;)r[--k]=z;
for(w=t,j=0;r[j];)w-=Math.sqrt(r[j++]);
w*w<1e-12&&console.log(r.join(' '));
for(--r[k];r[k]<1;)z=--r[++k];
}
}
```
**ES 5 Version** Any browser
```
function F(k,t)
{
var z=t- --k,r=[];
for(r[k]=z=z*z|0;r[k];)
{
for(;k;)r[--k]=z;
for(w=t,j=0;r[j];)w-=Math.sqrt(r[j++]);
w*w<1e-12&&console.log(r.join(' '));
for(--r[k];r[k]<1;)z=--r[++k];
}
}
```
**Test Snippet** it should run on any *recent* browser
```
F=(k,t)=>
{
z=t- --k,r=[];
for(r[k]=z=z*z|0;r[k];)
{
for(;k;)r[--k]=z;
for(w=t,j=0;r[j];)w-=Math.sqrt(r[j++]);
w*w<1e-12&&console.log(r.join(' '));
for(--r[k];r[k]<1;)z=--r[++k];
}
}
console.log=x=>O.textContent+=x+'\n'
t=~new Date
console.log('\n2, 3.414213562373095')
F(2, 3.414213562373095)
console.log('\n5, 5')
F(5, 5)
console.log('\n3, 7.923668178593959')
F(3, 7.923668178593959)
console.log('\n5, 13')
F(5, 13)
t-=~new Date
O.textContent = 'Total time (ms) '+t+ '\n'+O.textContent
```
```
<pre id=O></pre>
```
(**Edit**) Below are the result on my PC when I posted this answer 15 months ago. I tried today and it is 100 times faster on the same PC, just with a 64 bit alpha version of Firefox (and Chrome lags well behind)! - current time with Firefox 40 Alpha 64 bit: ~2 sec, Chrome 48: ~29 sec
*Output* (on my PC - last number is runtime in milliseconds)
```
2 4
1 1 1 1 1
6 7 8
1 1 1 1 81
1 1 1 4 64
1 1 1 9 49
1 1 4 4 49
1 1 1 16 36
1 1 4 9 36
1 4 4 4 36
1 1 1 25 25
1 1 4 16 25
1 1 9 9 25
1 4 4 9 25
4 4 4 4 25
1 1 9 16 16
1 4 4 16 16
1 4 9 9 16
4 4 4 9 16
1 9 9 9 9
4 4 9 9 9
281889
```
[Answer]
# Mathematica - 76 - 20 = 56
```
f[n_,x_]:=Select[Union[Sort/@Range[x^2]~Tuples~{n}],Abs[Plus@@√#-x]<10^-12&]
```
Examples
```
f[2, 3.414213562373095]
> {{2, 4}}
f[3, 7.923668178593959]
> {{6, 7, 8}}
f[3, 12]
> {{1, 1, 100}, {1, 4, 81}, {1, 9, 64}, {1, 16, 49}, {1, 25, 36}, {4, 4, 64}, {4, 9, 49}, {4, 16, 36}, {4, 25, 25}, {9, 9, 36}, {9, 16, 25}, {16, 16, 16}}
```
[Answer]
# Haskell, 87 80 - 10 = 70
This is a recursive algorithm similar to the Python 3 program of @Sp3000. It consists of an infix function `#` that returns a list of all permutations of all solutions.
```
0#n=[[]|n^2<0.1^12]
m#n=[k:v|k<-[1..round$n^2],v<-(m-1)#(n-fromInteger k**0.5)]
```
With a score of **102 99 92 - 10 = 82** we can print each solution only once, sorted:
```
0#n=[[]|n^2<0.1^12]
m#n=[k:v|k<-[1..round$n^2],v<-(m-1)#(n-fromInteger k**0.5),m<2||[k]<=v]
```
[Answer]
## [Pyth](https://github.com/isaacg1/pyth) ~~55 54~~ 47-20 = 27
```
DgGHKf<^-Hsm^d.5T2^10_12^r1hh*HHGR?jbmjdkKK"No
```
[Try it online.](http://isaacg.scripts.mit.edu/pyth/index.py)
Shamelessly *borrows* from [xnor's comment](https://codegolf.stackexchange.com/questions/41909/undo-the-square-roots/41948#comment97860_41939) ;)
This will run out of memory on any sane computer even for a value like `5,5.0`. Defines a function, `g`, that can be called like `g 3 7.923668178593959`.
This python 3 program uses essentially the same algorithm (just doesn't do the "No" printing at the end, which could be done by assigning a variable to all the results, then writing `print(K if K else "No")`), but uses a generator, so it doesn't get a memory error (it will still take extremely long, but I've made it print as it finds the values):
This gave the exact same results that @Sp3000 got. Also, this took several days to finish (I didn't time it, but around 72 hours).
```
from itertools import*
def g(G,H):
for x in product(range(1,int(H*H+2)),repeat=G):
if (H-sum(map(lambda n:n**.5,x)))**2<1e-12:print(*x)
```
[Answer]
# Python 3 - ~~157~~ ~~174~~ 169 - 10 = 159
Edit1: Changed the output format to space-separated integers instead of comma-separated.
Thanks for the tip of removing the braces around (n,x).
Edit2: Thanks for the golfing tips! I can trim off another 9 chars if I just use an == test instead of testing for approximate equality to within 1e-6, but that would invalidate approximate solutions, if any such exist.
Uses itertools to generate all possible integer combinations, hopefully efficiently :)
I haven't found a way to add printing "No" efficiently, it always seems to take more than 10 extra characters.
```
from itertools import*
n,x=eval(input())
for c in combinations_with_replacement(range(1,int(x*x)),n):
if abs(sum(z**.5for z in c)-x)<1e-6:print(' '.join(map(str,c)))
```
[Answer]
## Scala (397 bytes - 10)
```
import java.util.Scanner
object Z extends App{type S=Map[Int,Int]
def a(m:S,i:Int)=m updated(i,1+m.getOrElse(i,0))
def f(n:Int,x:Double):Set[S]={if(n==0){if(x.abs<1e-6)Set(Map())else Set()}
else((1 to(x*x+1).toInt)flatMap{(i:Int)=>f(n-1,x-Math.sqrt(i))map{(m:S)=>a(m,i)}}).toSet}
val s=new Scanner(System.in)
f(s.nextInt,s.nextDouble)foreach{(m:S)=>m foreach{case(k,v)=>print(s"$k "*v)};println}}
```
If there are no permutations, then this program prints nothing.
] |
[Question]
[
Tallying is a simple counting system that works in base 5. There are various different tallying systems used around the world, but the one that is used in most English-speaking countries is perhaps the most simple - count units by marking vertical lines, then for each 5th mark put a horizontal line through the previous collection of four. This clusters the tally marks in groups of 5 (and makes them easier to quickly count).
You are going to write a program that displays tally marks up to a given value. But, tallying in only base 5 is boring! Therefore, your program should also be able to display tallies in different bases.
## Input
The input will be **either one or two non-negative integer values** separated by a comma (e.g. `9` or `8,4`). The first number is the value that should be displayed by the tally. The second value is the base of the tally. **If the second value is not given, use base 5**.
## Output
The output will be the inputted value represented as ASCII art tally marks. Here are some examples you can test your program against - your output should match them exactly!
Input: `12` or `12,5`
```
| | | | | | | | | |
-+-+-+-+- -+-+-+-+- | |
| | | | | | | | | |
```
Input: `7,3`
```
| | | | |
-+-+- -+-+- |
| | | | |
```
Input: `4,2`
```
| |
-+- -+-
| |
```
Input: `6,1` or `6,10` (notice the leading spaces)
```
| | | | | |
| | | | | |
| | | | | |
```
Note also that base 1 is intended to be inconsistent - only vertical lines should be used.
If either of the inputted values is 0, there should be **no output whatsoever** (and your program should end gracefully).
## Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest correct implementation (in bytes) wins.
* Input/output can be in any suitable medium (e.g. stdin/stdout, file...).
* Input can be in the form of multiple command-line arguments or separated by spaces, etc. if it is more suitable for your target language.
* Trailing newlines are allowed in the output. Trailing spaces are not. This rule only applies when there is an output (i.e. not when the inputted value is 0).
* Your code must default to base 5 when no base is input.
[Answer]
# Python 2 - ~~111 108 119 144 140 136 135~~ 134 - [Try it](http://ideone.com/nA1khZ)
Ok, let's give it a try:
```
i=input()
n,b=[(i,5),i][i>[]]
o=b-1
a=[n,n%b][b>1]*' |'
m=(b>1)*n/b
s=(' |'*o+' ')*m+a
print(s+'\n'+('-+'*o+'- ')*m+a+'\n'+s)*(b*n>0)
```
**Edit:** I've overlooked that there should be no output if `n==0` or `b==0`. This costs me 11 characters. :(
**Edit:** Ok, after fixing the second issue mentioned in the comments my solution basically converged to the one from BeetDemGuise.
[Answer]
# Bash, ~~239 228 199 189~~ 188
Here's my attempt, it could be golfed a lot.
Note: the second line does not subtract 5 from 2, it sets a [default value](http://wiki.bash-hackers.org/syntax/pe#use_a_default_value) if `$2` is empty!
```
n=$1
b=${2-5}
((n<1&b<1))&&exit
while ((n>b&b>1));do
n=$[n-b]
x+=\
y+=-
for i in `seq $[b-1]`;{
x+='| '
y+=+-
}
x+=\
y+=\
done
for j in `seq $n`;{
x+=' |'
y+=' |'
}
echo -e "$x\n$y\n$x"
```
[Answer]
## CJam *103* *85* **72** characters
Try it at <http://cjam.aditsu.net/>.
## original
```
q","/(i:A\_,{~i}{;5}?:B_@*{(_{" |"*S"l"++AB/*AB%}{;MA}?\:J" |l""-+ "er\" |"*N+_J\+@2$+@J\+++"l"Ser}{;}?
```
Works by defining one set of tallys with spaces, lines and an l for spaces that should remain spaces. Then takes advantage of er (tranliteration) function to make the second line. Most inefficient part is dealing with the 1 and 0 special cases. Will edit as I improve it. Tip I took too long to realize: as the second input being 1 is the same as infinity or the first input +1, redefining it when it is equal to 1 saves alot of work.
## most improved so far with comma delimited
```
l",":G/(i:A\_5a?~i:B_@*{(_" |":K*\{SG++AB/*AB%}{A}?\_KG+"-+ "er[\GSer_@@M]\K*N+*}{;}?
```
## most improved so far with space delimited input
Naturally as CJam is really designed for space delimited input. Placing the input at 20 3 instead of 20,3 is a huge benefit.
```
ri:Aq_5s?S-i(_)A)?:B*{B(" |":K*STs++ABmd@@*_K"-+"er[\_@@M]\K*N+*TsSer}M?
```
[Answer]
## Python - ~~171~~ 143
```
i=input();t,b=i if[0]<i else(i,5);b=[b,t+1][b==1];l,d,m,o=' |',t/b,t%b,b-1;r=(l*o+' ')*d+l*m
if t*b>0:print r,'\n',('-+'*o+'- ')*d+l*m,'\n',r
```
The program is pretty straight-forward:
* Get the input and try to unpack into `t,b`. If that fails, simply assign the correct values.
* If the base was `1`, change its value to something that can handle all vertical lines easily (`t+1`).
* Set some variables and create the bottom and top sections of the tallies.
* Print out the tallies if both `t` and `b` are non-zero.
**EDIT 1:** Use the `input` function instead of `raw_input` after some playing around.
**EDIT 2:** Thanks to Falko for pointing out a small bug with my non-zero checking. Now our code is basically identical, less some variable names and some small logic.
**EDIT 3:** Thanks to [how Python compares sequences and different types](https://docs.python.org/2/tutorial/datastructures.html#comparing-sequences-and-other-types), we can compare `i` to a `list` to get a shorter version of our `try...except` block.
Here is the ungolfed version:
```
i=input()
# If True, `i` must be a list
if [0]<i:
t,b=i
# Otherwise, we know its a number (since `list` comes after `int` lexicographically.)
else:
b=5
t=i
b = b if b==1 else t+1
l=' |'
d=t/b
m=t%b
o=b-1
r=(l*o+' ')*d+l*m
if t and b:
print r,'\n',('-+'*o+'- ')*d+l*m,'\n',r
```
[Answer]
## Java, 343
```
class C{public static void main(String[]a){long n=new Long(a[0])+1,b=a.length>1?new Long(a[1]):5;if(b>0){if(b<2)b=(int)2e9;int i;for(i=1;i<n;i++)p(i%b>0?" |":" ");p("\n");for(i=1;i<n-n%b;i++)p(i%b>0?"-+":"- ");if(n>b)p("- ");for(i=1;i<n%b;i++)p(" |");p("\n");for(i=1;i<n;i++)p(i%b>0?" |":" ");}}static void p(String s){System.out.print(s);}}
```
Less golfed:
```
class C {
public static void main(String[] a) {
long n=new Long(a[0])+1, b=a.length>1 ? new Long(a[1]) : 5;
if(b>0) {
if(b<2) b=(int)2e9; // if the base is 1, pretend the base is 2 billion
int i;
for(i=1;i<n;i++) p(i%b>0 ? " |" : " ");
p("\n");
for(i=1;i<n-n%b;i++) p(i%b>0 ? "-+" : "- ");
if(n>b) p("- ");
for(i=1;i<n%b;i++) p(" |");
p("\n");
for(i=1;i<n;i++) p(i%b>0 ? " |" : " ");
}
}
static void p(String s) {
System.out.print(s);
}
}
```
[Answer]
# Perl - ~~167~~ ~~165~~ 156
```
my($n,$b)=($ARGV[0]=~/(\d+)(?:,(\d+))?/,5);print$b>1?map{join(" ",($_ x($b-1))x int($1/$b)," | "x($1%$b))."\n"}(" | ","-+-"," | "):join" ",("---")x$1if$1*$b
```
## ungolfed
```
my($n,$b) = ($ARGV[0] =~ /(\d+)(?:,(\d+))?/, 5);
print($b>1 ?
map{
join(" ",($_ x ($b-1)) x int($1/$b)," | " x ($1%$b))."\n"
} (" | ","-+-"," | ") :
join " ", ("---") x $1
) if $1 * $b
```
[Answer]
# C - 193
I'm so sorry. Dealing with the special case for 1 was a bit of a bad hack so I guess this could be golfed more with a better approach. Also, this code includes a new line at the beginning of the output, so if this is not allowed, please let me know.
Of course, very ugly-looking defines always help :)
Character count includes only necessary spaces and new lines.
```
#define P printf(
#define L P" |")
#define A P"\n");for(i=0;i<a;)b==1?i++,L:i++&&i%b==0?P
i;
main(a,b)
{
scanf("%d,%d",&a,&b)<2?b=5:!b?a=0:a;
if(a){
A" "):L;
A"- "):a%b&&i>a/b*b?L:P"-+");
A" "):L;}
}
```
[Answer]
## C# 271bytes
Not the shortest, I couldn't golf the input reading due to it needing to accept 0 as an input.
```
using C=System.Console;class P{static void Main(){var L=C.ReadLine().Split(',');int t=int.Parse(L[0]),f=L.Length>1?int.Parse(L[1]):5,r=3,i;for(var R="";t*f>0&r-->0;C.WriteLine(R.TrimEnd()))for(R="",i=0;i<t;R+=r==1&i++<t-t%f?(i%f<1?"- ":"-|"):i%f<1?" ":" |")f+=f<2?t:0;}}
```
Formatted code:
```
using C=System.Console;
class P
{
static void Main()
{
var L=C.ReadLine().Split(',');
int t=int.Parse(L[0]),f=L.Length>1?int.Parse(L[1]):5,r=3,i;
for(var R="";t*f>0&r-->0;C.WriteLine(R.TrimEnd()))
for(R="",i=0;i<t;R+=r==1&i++<t-t%f?(i%f<1?"- ":"-|"):i%f<1?" ":" |")
f+=f<2?t:0;
}
}
```
[Answer]
# Lua - ~~219~~ 203 bytes
I went for the make d copies of b copies of "|", then add r copies of "|" at the end. I feel like maybe I should have gone with the 'tally up' the "|"s to the string one at a time.
```
l=' |'s=string.rep _,_,a,b=io.read():find'(%d+)%D*(%d*)'b=tonumber(b)or 5 d=(a-a%b)/b f=b>1 and s(s(l,b-1)..' ',d)g=b>1 and s(s('-+',b-1)..'- ',d)r=b>1 and a%b or a e=s(l,r)..'\n'print(f..e..g..e..f..e)
```
ungolfed:
```
l=' |' --the base string
s=string.rep --string.rep will be used a lot, so best shorten it
_,_,a,b=io.read():find'(%d+)%D*(%d*)' --reads a,b I'm probably way of the mark with this one
b=tonumber(b)or 5
d=(a-a%b)/b -- shorter than math.floor(a/b), d equal the vertical mark
f=b>1 and s(s(l,b-1)..' ',d) or '' --creates d multiples of b multiples of "|" more or less
g=b>1 and s(s('-+',b-1)..'- ',d)or''--same as above but with the middle "-+-"
r=b>1 and a%b or a --idk maybe i should set r before d(a- a%b )/b
e=s(l,r)..'\n' -- makes the remainder string, notice that if b==1 then e will output all the "|"
print(f..e..g..e..f..e) -- here's where the real magic happens!
```
Sample:
```
c:\Programming\AnarchyGolfMine>lua test.lua
13,5
| | | | | | | | | | |
-+-+-+-+- -+-+-+-+- | | |
| | | | | | | | | | |
c:\Programming\AnarchyGolfMine>lua test.lua
6,2
| | |
-+- -+- -+-
| | |
c:\Programming\AnarchyGolfMine>lua test.lua
18,1
| | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | |
```
[Answer]
## JavaScript (193)
This might be overly complex.
```
s=prompt().split(",");a=+s[0];b=s[1];b=b?+b:5;o=b>1;v=" | ";q=w="";for(g=~~(a/b),c=o?a-g:a;g+1;g--,q+=" ",w+=" ")for(i=o;c&&i<b;i++)c--,q+=v,w+=g&&o?"-+-":v;if(a&&b)console.log(q+'\n'+w+'\n'+q)
```
---
**Commented version**
```
s=prompt().split(",");
a=+s[0];
b=s[1];
b=b?+b:5; // convert b to int and default to 5
o=b>1; // special handling for b0 and b1
v=" | ";
q=w="";
// calculate number of lines and number of groups
for(g=~~(a/b),c=o?a-g:a;g+1;g--,q+=" ",w+=" ")
for(i=o;c&&i<b;i++)
c--, // decrease line count
q+=v,
w+=g&&o?"-+-":v; // use " | " for last group and "-+-" for others
if(a&&b) // handle b0
console.log(q+'\n'+w+'\n'+q)
```
[Answer]
# Python - ~~127~~ ~~123~~ 122
Just sneaking in with a slightly shorter python version.
edit: Fixed 0 not printing nothing and rejigger, ended up the same length
```
k=input()
k=i,j=((k,5),k)[k>[]]
for m in[' |','-+',' |']*all(k):
print(m*(j-1)+m[0]+' ')*(i/j*(j>1))+' |'*(i%(j+(j<2)*i))
```
[Answer]
# C (207 characters)
The newline right before `exit` is for legibility only.
```
#define P printf(
#define t(v)for(a=c;b<=a;a-=b)a-c&&P" "),P v+1),q(b,v);q(a," |");P"\n");
q(n,c){while(n--)P c);}a;b;c;main(){scanf("%d,%d",&c,&b)<2?b=5:0;b&&c||
exit();b==1?b=32767:0;t("| ")t("+-")t("| ")}
```
`scanf` usage shamelessy stolen from Allbeert. Notice that this solution does not compile with gcc as it tries to enforce a nonexistant prototype for `exit`. Compile with a working C compiler like `tcc`. Also, this function may or may not work on 64 bit platforms. Use with care.
Here is the original ungolfed implementation this is based on:
```
#include <stdio.h>
#include <stdlib.h>
static void
tally_line(int base, int count, const char *str)
{
int follower = 0, i;
/* full tallies first */
for (; count >= base; count -= base) {
if (follower++)
putchar(' ');
/* only print second character */
printf(str + 1);
for (i = 0; i < base; i++)
printf(str);
}
/* partial tally */
for (i = 0; i < count; i++)
printf(" |");
/* newline */
puts("");
}
extern int
main(int argc, char **argv)
{
int base, count;
/* do away with program name */
count = atoi(*++argv);
base = argc - 3 ? 5 : atoi(*++argv);
/* remove 0 later */
base | count || exit(0);
/* a crossed-out tally never appears for large numbers */
if (base == 1)
base = 32767;
tally_line(base, count, "| ");
tally_line(base, count, "+-");
tally_line(base, count, "| ");
return (EXIT_SUCCESS);
}
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~134~~ ~~126~~ ~~123~~ 114 bytes
```
lambda i,j=5,a=" |":"\n".join(("",(a*~-j+" ","-+"*~-j+"- ")[x%2]*(i/j))[j>1]+a*(i,i%j)[j>1]for x in(0,1,2)if i*j)
```
[Try it online!](https://tio.run/##dY7LCoMwEEX3/YphQMjo2CZprVCwP6IuUoo0oVURFxZKf90GxMemu3NPyL3TvvtHU@uxyorxaV63uwHLLkvYZAgfvGBR4941thYCkYUJv7GLEAAZ4winFANSPgS6DIU9OKLcXVUZGZ/YBm6KVdPBAL5GsmJNtgIbOhrbztY9oNJ@BiKohNIEu8VysnpOaH5I@Th7jwTLjxMvRR7XpjOr2XukjZYbLzcDch1YteR01h79LsD471b4AQ "Python 2 – Try It Online")
Old question I know but fun to have a go at anyway. Chance to try out a few tricks I've learned since joining.
] |
[Question]
[
From the infinite triangular array of positive integers, suppose we repeatedly select all numbers at Euclidean distance of \$\sqrt{3}\$, starting from 1:
$$
\underline{1} \\
\;2\; \quad \;3\; \\
\;4\; \quad \;\underline{5}\; \quad \;6\; \\
\;\underline{7}\; \quad \;8\; \quad \;9\; \quad \underline{10} \\
11 \quad 12 \quad \underline{13} \quad 14 \quad 15 \\
16 \quad \underline{17} \quad 18 \quad 19 \quad \underline{20} \quad 21 \\
\underline{22} \quad 23 \quad 24 \quad \underline{25} \quad 26 \quad 27 \quad \underline{28} \\
\cdots
$$
Alternatively, you may think of it as "leave centers of a honeycomb pattern and cross out boundaries".
The resulting sequence (not yet on OEIS, unlike the [polkadot numbers](https://codegolf.stackexchange.com/q/253309/78410)) is as follows:
```
1, 5, 7, 10, 13, 17, 20, 22, 25, 28, 31, 34, 38, 41, 44, 46, 49, 52, 55, 58, 61, 64,
68, 71, 74, 77, 79, 82, 85, 88, 91, 94, 97, 100, 103, 107, 110, 113, 116, 119,
121, 124, 127, 130, 133, 136, 139, 142, 145, 148, 151, 155, 158, 161, 164, 167, 170,
172, 175, 178, 181, 184, 187, 190, ...
```
The task is to output this sequence.
[sequence](/questions/tagged/sequence "show questions tagged 'sequence'") I/O rules apply. You can choose to implement one of the following:
* Given the index \$n\$ (0- or 1-based), output the \$n\$th term of the sequence.
* Given a positive integer \$n\$, output the first \$n\$ terms of the sequence.
* Take no input and output the entire sequence by
+ printing infinitely or
+ returning a lazy list or a generator.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
[Answer]
# [Python](https://docs.python.org/3/), 34 bytes
Takes as input an integer \$ n \$, and outputs the \$ n \$-th term of the sequence (0-indexed).
```
lambda n:3*n-~((n*24+1)**.5%6%5<1)
```
[Try it online!](https://tio.run/##HY47bsMwEER7n2IbA6SiBFr@ZUQ30A0cFwpiOQYc2hDcpMnVlRkVOxhi3nLn8fv8vle/zsPHept@Pr8mqQff1Nc/Y2rjwovapnmL@7SP72rXUQY5aiuxldyKdhiPgXfwzmEQudKKB@UDBj7AB/iQMD22wUVwEVlClpAl@Ayf4TP@y@AKuAKuIOuR9cj67S4Pd7zc8bn12IpoomBVnVIChYjfqhLxRDyR4CiRggMaucFayl7KYspmmvhB5geZG5lIJlKIFCKFSN@ddvN9kSrXKstUL2dzO1czWnvYyWO51qeprcymWhkGGY/1ZNd/ "Python 3 – Try It Online")
### [Python 3](https://docs.python.org/3/), 43 bytes
Outputs the sequence forever.
```
n=1
while[print(n//8-~(n**.5%6%5<1))]:n+=24
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P8/WkKs8IzMnNbqgKDOvRCNPX99Ct04jT0tLz1TVTNXUxlBTM9YqT9vWyOT/fwA "Python 3 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org), 45 bytes
-2 bytes thanks to [@Grain Ghost](https://codegolf.stackexchange.com/users/56656/grain-ghost).
```
[sum[0..n]+k|n<-[0..],k<-[0..n],mod(n+k)3==1]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ2W0km6Ec0CAUuz-3MTMPAVbhdzEAt94hYKizLwSBRWFksTsVAVDAwOFmKWlJWm6Fjd1o4tLc6MN9PTyYrWza_JsdEHsWJ1sCCMvVic3P0UjTztb09jW1jAWomkBlILSAA)
[Answer]
# [JavaScript (V8)](https://v8.dev/), 55 bytes
Prints the sequence forever.
```
for(n=i=1;;i++)for(j=0;j<=i*3;n+=3+!j-(j++==i))print(n)
```
[Try it online!](https://tio.run/##FccxCoAwDAXQs7g1hoLSRYj/MEUQkiGWWnr9iG97Vmd9r65t5HlE3E9PDsUuosz017CJndC1iDMKL5aTMQNK1Lr6SE4RHw "JavaScript (V8) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~24~~ 17 bytes
```
I…⌕A⭆⊕θ⭆⊕ι﹪⁺ιλ³1N
```
[Try it online!](https://tio.run/##bclBCoMwEEDRq4irCdhF7bKrIhRcWARPkCZDDYyTGJOCp5/OAbp5i//darOLlkTmHLjAYA/ldITDGhM8A/sHESxF72eyCUZ2GTfkgh520zX/T9AzRV8pwkz1gNA1pOlmjNpeW3XkVMurbm/MoNncRfpeLl/6AQ "Charcoal – Try It Online") Link is to verbose version of code. Outputs the first `n` terms. Explanation: Now a port of @JonathanAllan's Jelly answer, but taking some inspiration from @Steffan's Vyxal answer to save a byte.
```
θ Input `n`
⊕ Incremented
⭆ Map over implicit range and join
ι Current value
⊕ Incremented
⭆ Map over implicit range and join
ι Outer value
⁺ Plus
λ Inner value
﹪ Modulo
³ Literal integer 3
⌕A Find all indices of
1 Literal string `1`
… Truncated to length
N Input `n` as an integer
I Cast to string
Implicitly print
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ŻrḤ$3ḍFTḣ
```
A monadic Link that accepts a non-negative integer, \$n\$, and yields the first \$n\$ triangular honeycomb numbers.
**[Try it online!](https://tio.run/##y0rNyan8//9Rw4wgbZVHTWuADOOHO3rdQh7uWPz//38zEwA "Jelly – Try It Online")**
### How?
The triangle's \$i^{\text{th}}\$ row contributes every third element starting with the \$(3 - (i+1\pmod 3))^{\text{th}}\$ element...
```
ŻrḤ$3ḍFTḣ - Link: integer, n e.g. 4
Ż - zero-range (n) [ 0, 1, 2, 3, 4]
$ - last two links as a monad:
Ḥ - double [ 0, 2, 4, 6, 8]
r - inclusive range [[0],[1,2],[2,3,4],[3,4,5,6],[4,5,6,7,8]]
3 - three 3
ḍ - divides? [[1],[0,0],[0,1,0],[1,0,0,1],[0,0,1,0,0]
F - flatten [ 1, 0,0, 0,1,0, 1,0,0,1, 0,0,1,0,0]
T - truthy indices [ 1, 5, 7, 10, 13 ]
ḣ - head (to index n) [1,5,7,10]
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~35~~ ~~30~~ 29 bytes
-5 bytes thanks to [Sʨɠɠan](https://codegolf.stackexchange.com/users/92689/s%ca%a8%c9%a0%c9%a0an)
-1 byte thanks to [G B](https://codegolf.stackexchange.com/users/18535/g-b)
Returns `n`th item of the sequence. Same technique as [Python](https://codegolf.stackexchange.com/a/253422/11261) and [Vyxal](https://codegolf.stackexchange.com/a/253427/11261) answers; give them upvotes.
```
->n{3*n-~33[(n*24+1)**0.5%6]}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhZ7de3yqo218nTrjI2jNfK0jEy0DTW1tAz0TFXNYmshanYaGeiVZOamFiuk5HMpKBQouEXHG8ZypealQOQXLIDQAA)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 10 bytes
```
Þ::ʀ+3ḊfT›
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLDnjo6yoArM+G4imZU4oC6IiwiMTAw4bqOIiwiIl0=)
Outputs the infinite sequence.
-6 bytes (compared to my previous answer below) thanks to porting @Jonathan Allan's Jelly answer, so make sure to upvote that!
```
Þ::ʀ+3ḊfT›
Þ: # Push an infinite list of non-negative integers
: # Duplicate
ʀ+ # For each n in this list, add n to each item in a range [0..n]. This produces an infinite list like [[0], [1, 2], [2, 3, 4], [3, 4, 5, 6], ...]
3Ḋ # For each inner item, is it divisible by three?
f # Flatten
T # Get truthy (0-based) indices
› # Increment
```
Previously:
## [Vyxal](https://github.com/Vyxal/Vyxal), 16 bytes
```
Þ∞ƛʀ+'ǒ1=;nɽ∑+;f
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLDnuKInsabyoArJ8eSMT07bsm94oiRKztmIiwiMTAw4bqOIiwiIl0=)
Outputs the infinite sequence.
```
Þ∞ƛʀ+'ǒ1=;nɽ∑+;f
Þ∞ƛ # Map n over positive integers:
ʀ+ # For each in [0..n], add n
' # Filter for:
ǒ # Modulo 3
1= # Equals one?
; # Close filter
nɽ∑+ # For each, add the sum of [0..n-1]
; # Close map
f # Flatten
```
# [Vyxal](https://github.com/Vyxal/Vyxal), 12 bytes
```
24*›√6%₅$T+›
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIzMMqAxpsiLCIyNCrigLriiJo2JeKChSRUK+KAuiIsIiIsIiJd)
Outputs the \$n\$th element of the sequence. Port of @dingledooper's answer, so uvpote that!
```
24*›√6%₅$T+›
24* # Multiply the input by 24
› # Increment
√ # Square root
6% # Modulo 6
₅ # Is it divisible by 5? (Returns 1 or 0)
$T+ # Add input * 3
› # Increment
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~12~~ 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
Ports of [*@Sʨɠɠan*'s Vyxal answers](https://codegolf.stackexchange.com/a/253427/52210), where the first is a port of [*@JonathanAllan*'s Jelly](https://codegolf.stackexchange.com/a/253448/52210) and the second is a port of [*@dingledooper*'s Python answer](https://codegolf.stackexchange.com/a/253422/52210), so make sure to upvote them as well!
Given no input, it'll output the infinite sequence as list (**11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)**):
```
∞<DÝ+˜3Öƶ0K
```
[Try it online.](https://tio.run/##yy9OTMpM/f//Ucc8G5fDc7VPzzE@PO3YNgPv//8B)
Given \$n\$, it'll output the 0-based \$n^{th}\$ term (**12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)**)
```
Ð$24*>t6%5ÖO
```
[Try it online](https://tio.run/##yy9OTMpM/f//8AQVIxMtuxIzVdPD0/z//7cAAA) or [verify the first 25 items](https://tio.run/##yy9OTMpM/W9k6uZnr6TwqG2SgpK93//DEwz9jEy07ErMVE0PT/P/r/MfAA).
**Explanation:**
```
∞ # Push an infinite list of positive integers: [1,2,3,...]
< # Decrease each by 1 to make it non-negative: [0,1,2,...]
D # Duplicate this infinite list
Ý # Map each to a [0,val]-ranged list in the copy
+ # Add the values of the lists at the same positions together
˜ # Flatten this list of lists
3Ö # Check for each integer whether it's divisible by 3
ƶ # Multiply each check by its 1-based index
0K # And then remove all 0s (the falsey checks)
# (after which the infinite list is output implicitly as result)
```
```
Ð # Triplicate the (implicit) input-integer
$ # Push 1 and the input-integer yet again
24* # Multiply the top input by 24
> # Increase it by 1
t # Take the square-root of that
6% # Modulo-6
5Ö # Check if that is divisible by 5
O # And then sum all five values on the stack together:
# input + input + input + 1 + (sqrt(input*24)%6%5==0)
# (which is output implicitly as result)
```
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 12 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
M*)√6%5%┬ΓΣ)
```
Port of [*@dingledooper*'s Python answer](https://codegolf.stackexchange.com/a/253422/52210).
Given \$n\$, it'll output the 0-based \$n^{th}\$ term.
[Try it online.](https://tio.run/##y00syUjPz0n7/99XS/NRxywzVVPVR1PWnJt8brHm//8GXIZcRlzGXCZcplxmXOZcFlyWXIYGAA)
Unfortunately `÷` (*is divisible by* builtin) is incorrectly implemented and doesn't support a float argument, otherwise the `5%┬` could have been `5÷` for -1 byte.
**Explanation:**
```
M* # Multiply the (implicit) input-integer by 24
) # Increase it by 1
√ # Take the square-root of that
6% # Modulo-6
5%┬ # Check if it's divisible by 5:
5% # Modulo-5
┬ # Check if it's equal to 0.0
Γ # Wrap the top four values into a list
# (which uses the implicit input three times)
Σ # Sum this list together
) # Increase it by 1
# (after which the entire stack is output implicitly as result)
```
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 8.5 bytes (17 nibbles)
```
`?+.,~.+$,$%$3 2
```
Somewhat modified port of [Jonathan Allan's Jelly answer](https://codegolf.stackexchange.com/a/253448/95126): upvote that.
Outputs the infinite sequence.
```
`?+.,~.+$,$%$3 2
,~ # 1..infinity
. # map over each n
,$ # 1..n
+$ # add n
. %$3 # each modulo 3
+ # now flatten this list-of-lists
`? # and get indices of
2 # all elments equal to 2
```
[](https://i.stack.imgur.com/Wkppt.png)
[Answer]
# [C (clang)](http://clang.llvm.org/), 59 bytes
```
j,i;main(x){for(;i%3||printf("%d ",x);i=++i>j*2?++j:i)++x;}
```
[Try it online!](https://tio.run/##DYzLCsIwEEX3fkUoFBIzgs2zGtRvKZXKlBqluAhYvz3exYED98yMh3EZ8qPWmTg9B86yqO/0WmXi1m7be@X8mWTT3kVDRSW@aM3XeW9uWs9nVlqX9Ku1I@FJRBLdEVgAN3BjACbTk7CorANwB3dwF8AJ1@g8Oo8tYAuOdgEe4RFdxL@Irjd/ "C (clang) – Try It Online")
Full program.
Iterate x=[1..] combined with growing series *i..* of lines of the pyramid where starting value *j* increases by one.
When *i%3 == 0* prints *x*
```
0 12 234 3456 45678 56789..
1 .. 5..7.10..13, 17, 20
```
[Answer]
# [Haskell](https://www.haskell.org/), 43 bytes
```
[y-x+sum[1..x]|x<-[1..],y<-[1,4..x*2],y>=x]
```
[Try it online!](https://tio.run/##FYzfDoIgHEZf5XfhRX/QJSLYFr1GF8YFs0yWOpa2YevZo8@Lsx34DnR2et77Prb6GuslDfvpPdR5lgXzDad0NcOWVZjA5Y7jdNbBxMG6kTT5lxtnSsiOt@Tj/MXN3UbrLXIqGSlG@QEUAM7hnANMvGJUoCoEgAu4gAsJjniNrkRXYpPYJDYJV3AFV/hPoau4aeOvaXv7mGLaeP8H "Haskell – Try It Online")
Using similar approach of my C answer
] |
[Question]
[
You want to see how quickly the ratio of two consecutive Fibonacci numbers converges on φ.
Phi, known by the nickname "the golden ratio" and written as \$φ\$, is an irrational number, almost as popular as π and e. The exact value of \$φ\$ is \$\frac {1 + \sqrt 5} 2 = 1.618...\$
The Fibonacci sequence is a recursive series of integers calculated by
$$F\_n = F\_{n-1} + F\_{n-2} \\
F\_0 = 0 \\
F\_1 = 1$$
Calculate \$φ\$'s value and the ratio \$\frac {F\_n} {F\_{n-1}}\$. How closely does \$φ\$ match the ratio?
## Examples
\$n = 2\$, ratio: \$\frac 1 1 = 1.000\$, compared to \$1.618...\$, 0 decimal spots match
\$n = 5\$, ratio: \$\frac 5 3 = 1.666...\$, compared to \$1.618...\$, 1 decimal spot matches
### Input
1 integer \$n\$ to calculate \$\frac{F\_n}{F\_{n-1}}\$
\$ n >= 5\$
### Output
1 integer \$x\$, indicating the number of decimal places that match the value of \$φ\$
It is acceptable that the program only works accurately until the float precision limit of the language.
### Test Cases
```
Input -> Output
5 -> 1
10 -> 2
12 -> 2
15 -> 5
20 -> 7
23 -> 7
25 -> 9
50 -> 18
100 -> 39
```
### Tips
Do not round the ratio of \$\frac{F\_n}{F\_{n-1}}\$
Rounding will give you errors.
Let's look at \$n = 5\$ again.
\$1.666...\$ rounds to \$1.7\$ and \$1.618...\$ rounds to \$1.6\$, so 0 is the wrong answer.
### Useful information and math.
The limit of the ratios of the consecutive Fibonacci terms as \$n\$ tends to infinity is the golden number \$φ\$. The inverse of this ratio is \$\frac 1 φ\$ which equals to \$φ−1\$.
\$\frac 1 φ = φ -1 \$
\$ \lim\_{n \to \infty} \frac{F\_n}{F\_{n-1}} = φ\$
## Winning criterion
Code Golf.
[Answer]
# JavaScript (ES7), ~~77 75 69~~ 67 bytes
```
n=>(g=p=>--n>1?g(q,q+=p):(1+5**.5)/2*(m*=10)^q/p*m?0:1+g(p))(q=m=1)
```
[Try it online!](https://tio.run/##dcxLCsIwEADQvafIciaxTRMJYmHSmwiltkFp87Hi9aNINha6fYv36N/9Ojzv8VX5cBvzRNmTBUeRbFV5qzoH6ZgERWxBCcN5bVBqDgsn1eA1yciXrmmVcBARIdFCCvMQ/BrmsZ6DgwmYQWRSMnX492/wc711vePlMRvX5Tlv/bTj5bnkDw "JavaScript (Node.js) – Try It Online")
### Commented
```
n => ( // main function, taking n
g = p => // g is a recursive function taking p which, along with q,
// is used to compute the Fibonacci sequence
--n > 1 ? // decrement n; if it's still greater than 1:
g(q, q += p) // do a recursive call with (p, q) = (q, q + p)
: // else:
(1 + 5 ** .5) // compute the golden ratio
/ 2 //
* (m *= 10) // multiply m by 10 and multiply the golden ratio by m
^ // xor (forces the decimal places to be discarded)
q / p // compute q / p (last Fibonacci term / penultimate one)
* m // multiply by m
? // if the above values are not equal:
0 // stop
: // else:
1 + g(p) // increment the final result and do a recursive call
)(q = m = 1) // initial call to g with p = q = m = 1
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~76~~ 75 bytes
```
g n=last[i|i<-[1..n],i?n==i?99]
e?n=floor$10^e*f!!n/f!!(n-1)
f=0:scanl(+)1f
```
[Try it online!](https://tio.run/##LYyxDoIwFEX39xXVOIBSpBhjMBQnN/@AYGykxRfLqylNXPx3ROJyz80ZzkMNT23tOHaMpFVDqPGDJa9FmlKT4ImkxFNRNKCna6xzfiWyq16bxYK200TERQxGZsfhrshGm1iYsVdIsnXAakxcU/JevZjXqk3fzrdDatAG7aMbuXC2ur8tebWMy1XV6XBB0sBeHilEHUMpXTIlYmC/5LhnvGICRPZjDiL/c/Z7yGd/gHz35@yLLw "Haskell – Try It Online")
The relevant function is `g`, which takes `n` as input and returns the number of matching decimal digits between \$\varphi\$ and \$F\_n/F\_{n-1}\$. It probably won't work if the answer is larger than `15` because that's the maximum precision allowed by `Double`s.
## How?
`f=0:scanl(+)1f` is the standard Haskell definition of the Fibonacci numbers.
`e?n=floor$10^e*f!!n/f!!(n-1)` is a function `(?)` which computes
$$
\left\lfloor10^e\cdot\frac{F\_n}{F\_{n-1}}\right\rfloor.
$$
`g n=last[i|i<-[1..n],i?n==i?99]` finds the largest exponent `i` such that
$$
\left\lfloor10^i\cdot\frac{F\_n}{F\_{n-1}}\right\rfloor=\left\lfloor 10^i\varphi\right\rfloor.
$$
Note that \$\varphi\$ is computed as \$F\_{99}/F\_{98}\$ to save bytes, since the error is far beyond the accuracy of `Double`s. Also, the fact that the answer will always be smaller than `n` is exploited.
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~37~~ 32 bytes
Full program, assumes `⎕IO←0`.
-5 bytes by not using `dfns.fibonacci`.
```
0⍳⍨2↓=⌿↑⍕¨(÷/(+/,⊃)⍣⎕⍳2),2÷⍨1+√5
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkGXI862tP@Gzzq3fyod4XRo7bJto969j9qm/iod@qhFRqHt@traOvrPOpq1nzUuxioCajOSFPH6PB2oGpD7Ucds0z/Aw34n8ZlxJXGZQrEhgYgAsQzBHGNQFwjYxBhCgA "APL (Dyalog Extended) – Try It Online")
`(+/,⊃)⍣⎕⍳2` calculates adjacent fibonacci pairs. Starting with `0 1 ≡ ⍳2`, iterate input (`⎕`) times: pair the sum of both values `+/` with the first value `⊃`.
```
2÷⍨1+√5 ⍝ Phi
, ⍝ paired with
÷/(+/,⊃)⍣⎕⍳2 ⍝ fib(n) ÷ fib(n-1)
↑⍕¨ ⍝ format both numbers as strings and arrange in character matrix
=⌿ ⍝ reduce each column by equality
2↓ ⍝ remove the first two values (first digit and decimal point)
0⍳⍨ ⍝ get the index of 0 in this list
⍝ this is the first index where Phi and fib(n-0) ÷ fib(n-1) differ
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes
```
,’ÆḞ÷/Ṿ=ØpṾ¤ŒɠḢ_2
```
[Try it online!](https://tio.run/##AUUAuv9qZWxsef//LOKAmcOG4biew7cv4bm@PcOYcOG5vsKkxZLJoOG4ol8y/8OH4oKs//9bNSwxMCwxMiwxNSwyMCwyMywyNV0 "Jelly – Try It Online")
Probably can be improved.
## Explanation
```
,’ÆḞ÷/Ṿ=ØpṾ¤ŒɠḢ_2 Main monadic link
, Pair with
’ n-1
ÆḞ Get the Fibonacci numbers
/ Reduce by
÷ division
Ṿ Convert to string
= Equals [vectorized]
¤ (
Øp Phi
Ṿ Convert to string
¤ )
Œɠ Run lengths
Ḣ First element
_ Subtract
2 2
```
[Answer]
# [Desmos](https://desmos.com/calculator), ~~169~~ ~~113~~ ~~107~~ ~~98~~ ~~97~~ ~~95~~ 87 bytes
```
pp-p~1
F(n)=p^n-(1-p)^n
h(k)=floor(10^{[1...n]}k)
f(n)=\{h(p)=h(F(n)/F(n-1)),0\}.\total
```
[Try It On Desmos!](https://www.desmos.com/calculator/6yezyuam29)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/nnzzppuged)
*Finally managed to get it under ~~100~~ 90 bytes after all this time!*
*I don't know why I keep coming back to this answer, but every time I do, I always find a way to golf it even further...*
Test the code on function \$f(n)\$. It only works up to around \$n=25\$, though, because of float precision errors. Uses the fact that the output has to be smaller than \$n\$.
(The `f(n)=\{h(p)=h(F(n)/F(n-1)),0\}.\total` equation does not render properly in Desmos, in case you are wondering. It still works though.)
### Explanation:
`pp-p~1`: Sets `p` to be the golden ratio.
`F(n)=p^n-(1-p)^n`: \$F(n)\$ is Binet's formula for the \$n\$th Fibonacci number, but with the \$\sqrt5\$ denominator taken out, because it gets cancelled out anyways in \$\frac{F(n)}{F(n-1)}\$.
`h(k)=floor(10^{[1...n]}k)`: The \$h(k)\$ function creates a list of length \$n\$. It then computes \$\left\lfloor10^ik\right\rfloor\$ for each element, where \$i\$ is the index(1-based). Also, the \$n\$ in `[1...n]` is referring to the argument passed into \$f(n)\$(which is the next equation). For example, \$h(1.56789)\$ with \$n=5\$ returns the list \$[15,156,1567,15678,156789]\$.
`f(n)=\{h(p)=h(F(n)/F(n-1)),0\}.\total`: This function \$f(n)\$ essentially compares each digit of \$p\$ and \$\frac{F(n)}{F(n-1)}\$ under the \$h\$ function. If you look at the \$h\$ function, you will see that at any index \$1\le i\le n\$, it is actually comparing every digit up to the \$i\$'th decimal place. For example, let's say you were comparing \$1.56789\$ and \$1.56889\$, with \$n=5\$. \$h(1.56789)=[15,156,1567,15678,156789]\$, and \$h(1.56889)=[15,156,1568,15688,156889]\$.
From this, you can tell that the first \$2\$ elements(\$15\$ and \$156\$) of each of the lists are the same, but once you get to the digit that is different, the rest of the elements are not equal.
With this information, we can then combine the two lists into one, by doing the following: If the element at index \$1\le i\le n\$ in each list are the same, then the \$i\$'th element of the new list is \$1\$. Otherwise, it is \$0\$. (This is what `\{h(p)=h(F(n)/F(n-1)),0\}` does)
We can then simply take the sum of this new list to obtain the answer.
[Answer]
# JavaScript, ~~97~~ 89 bytes
```
n=>[...''+(f=n=>n<2?n:f(n-1)+f(n-2))(n)/f(n-1)].findIndex((e,i)=>`${.5+5**.5/2}`[i]!=e)-2
```
You have got to be kidding me. Not the best answer definitely but uses a different approach.
Also, [try it online](https://tio.run/##JchNCsIwEEDhswhCZxozxUA24tS1ZyiFluaHSJmILUUQzx4VV4/v3cZtXKZHuq9asvMlchFuOyKqKgWBv5CzucgpgOgjql8MIgg2/9NTSOKu4vwTwB8ScjvsX2SVrWuyjXkPXep37FGbMmVZ8uxpzhEiWMTyAQ).
*8 bytes were shaved off the program thanks to suggestions from the OP as well as a rule change.*
[Answer]
# [Python 3](https://docs.python.org/3/), ~~120~~ ~~102~~ 88 bytes
Saved a whopping ~~18~~ 32 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)!!!
```
f=lambda n,r=1,a=0,b=1:n>1and f(n-1,r,b,a+b)or-((1+5**.5)*r//2!=b*r//a or~f(n,r*10,a,b))
```
[Try it online!](https://tio.run/##NY7dboQgEIXvfYppeiG4Y1e0ZrubsC/S9gIUs6ZbJMCmP8a@uh1JS2bCAYbvHPcVL5Nt1nWQV/WuewUWvRSoZIVaipM9C2V7GJgtBXrUqHaaT75kTOzaonhoeeH3@/pO6m1XMPkfmkVfiAoVas7XaEIMIIG1CHQJoqYmXZOuG@qWwz1Cuz1VFWm4OWc8bP86FUwAfZ0@wKWgeYDBZebTmS6afqMKIqQi5CHVMfHEE0Jz5Fl3Md0b4Wg0f7nVh8cuR0hKNDnPhomc0MBo4Xt0LIVF@DfgpwxobfEHFnk6OD/ayIZ8jguUZ5jDAvOfybORMrwuOV9/AQ "Python 3 – Try It Online")
[Answer]
# [Julia 0.7](http://julialang.org/), ~~68~~ 65 bytes
```
!n=φ^n-(1-φ)^n
>(n,x=1)=!n/!(n-1)*10^x÷1!=φ*10^x÷1?x-1:n>x+1
```
[Try it online!](https://tio.run/##yyrNyUw0//9fMc/2fFtcnq6Goe75Ns24PC47jTydCltDTVvFPH1FjTxdQ00tQ4O4isPbDRWBKmFs@wpdQ6s8uwptw/@5iQUambp2BUWZeSU5eRqZOgpKCrp2Cko6CnYamZqaOqZWRqaa/wE "Julia 0.7 – Try It Online")
Fibonacci numbers are calculated using [Binet's formula](https://en.wikipedia.org/wiki/Fibonacci_number#Closed-form_expression) dropping the constant \$\sqrt5\$ term in the denominator since we are interested in ratios anyway.
Thanks to MarcMush for -3 bytes.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 39 bytes
```
NθF²⊞υιF⊖θ⊞υΣ…⮌υ²I⊖⊖⌕EI∕⊟υ⊟υ¬⁻ι§I⊘⊕₂⁵κ⁰
```
[Try it online!](https://tio.run/##VYxBDoIwFET3nqLL3wQTQ3TFymCMLCAETlDhGxpLC6Vt9PS1iAZdzWQy7zUd041iwvtMDtYUtr@ihpEmm5vSBGJKSjt1YCPCv9sJG409SoNtOK6H2vaQPhuBaacGqNChnhAsjUhMaYBLzaWBlE3mT/Hbz1y2kLPh8@KOtwhlsM2WJWlohTKQc2kn4BE5mky2@FiQCxMueDK5OuvRMo2VCsyBvvH7Ers5aOL9fue3TrwA "Charcoal – Try It Online") Only works up to `n=40` due to floating-point rounding. Explanation:
```
Nθ
```
Input `n`.
```
F²⊞υιF⊖θ⊞υΣ…⮌υ²
```
Calculate the first `n` Fibonacci numbers.
```
I⊖⊖⌕EI∕⊟υ⊟υ¬⁻ι§I⊘⊕₂⁵κ⁰
```
Divide the last two and compare the string representation with that of φ.
87 bytes for arbitrary precision:
```
NθF²⊞υιF⊖θ⊞υΣ…⮌υ²≦Xχθ≔⁰η≔⁰ζF↨×⁵×θθ⁴«≔⁺×ζ⁴ιζ≦⊗η¿›ζ⊗η«≧⁻⊕⊗ηζ≦⊕η»»I⊖⌕EI÷×θ⊟υ⊟υ¬⁻ι§I÷⁺ηθ²κ⁰
```
[Try it online!](https://tio.run/##XZHPbsIwDMbP9ClydKRMYmicOLGiTZUGqtheoLQuidamkD9sY@LZu6QNa@EUJ/bPn/0l55nKm6xq20QerNnYeocKjnQRlY0iMKMktZqDZURc31aYK6xRGixc4VDwbmuIf/IKY94cYIsnVBrBUkZmlDp4nR2WWou9fMPSQNp8oWLkccqIV@sz4G785na@qj5nrtmHqFHDnJE@OHrW9X9yU/xGk0ClldWh8uxzfvS@0eR/BFg1dldh0ctNREngVWFm3O6OCUngtG88cFux5wbWQlrNSCIHI0ZI0BqJjQqD4CW6RKkS0kCcaXNj6YuQBTi2zyTSrMRJFNfd3cqpc9d6mRC4aNOEoUAwsjSJLPD7nu9s4d6x7kMY@aQdO/UHXbTtfNo@nKo/ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Uses @Delfad0r's observation that the result is always less than `n` so that you need only compute `n` decimal places.
```
Nθ
```
Input `n`.
```
F²⊞υιF⊖θ⊞υΣ…⮌υ²
```
Calculate the first `n` Fibonacci numbers.
```
≦Xχθ
```
Compute `10ⁿ`.
```
≔⁰η≔⁰ζF↨×⁵×θθ⁴«≔⁺×ζ⁴ιζ≦⊗η¿›ζ⊗η«≧⁻⊕⊗ηζ≦⊕η»»
```
Calculate `⌊√5·10²ⁿ⌋` using the method from my answer to [Shift right by half a bit](https://codegolf.stackexchange.com/questions/198427/).
```
I⊖⌕EI÷×θ⊟υ⊟υ¬⁻ι§I÷⁺ηθ²κ⁰
```
Calculate the Fibonacci ratio multiplied by `10ⁿ` and compare it with the digits of `φ·10ⁿ` calculated from the above value.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 17 bytes
```
3LÍ+ÅfRü/`ø€ËÅγнÍ
```
[Try it online!](https://tio.run/##AT0Awv9vc2FiaWX/zrX/M0zDjSvDhWZSw7wvYMO44oKsw4vDhc6z0L3Djf//WzUsMTAsMTIsMTUsMjAsMjMsMjVd "05AB1E – Try It Online")
```
3L push the list [1,2,3]
Í subtract 2, [-1,0,1]
+ add to the implicit input, [9, 10, 11]
Åf take the nth Fibonacci number, [34, 55, 89]
R reverse, [89, 55, 34]
ü/ take the division of each pair, [1.6181818181818182, 1.6176470588235294]
` dump to stack
ø zip, ["11", "..", "66", "11", "87", "16", "84", "17", "80", "15", "88", "18", "82", "13", "85", "12", "89", "24"]
€Ë map to equal, [1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0]
Åγ run length encode, [4, 6, 1, 7]
нÍ head - 2, 2
```
[Answer]
# [R](https://www.r-project.org/), 100 bytes
```
h=function(n,m=1,l=0,p=.5+5^.5/2)`if`(n>1,h(n-1,m+l,m),{r=m/l
while(r%/%10^-T==p%/%10^-T)T=T+1
T-1})
```
[Try it online!](https://tio.run/##Vc6xDoIwFEbhnfcgacMP9NZ0vD5FZwKiSJO2NgVjjPHZq4uD28k3nVwWd8rT7m5nd3X7xmXl5R7nL0QREZjgWSFxZxozdKbXcnTLKOKRsIrYEkLjESRemUPvq8fq/EXkuq9JDa1lTr@Ulm1DlW3pLcs2peSfYhYGpEAaZKAV9AHaSPwvyfIB "R – Try It Online")
Gets the ratio of the `n`th and `n-1`th fibonacci numbers using the recursive function:
`g=function(n,m=1,l=0)`if`(n,g(n-1,m+l,m),m/l)`
Then calculates the number of digits of the `r`atio that are shared with `p`hi by comparing successive integer divisions by negative powers of 10:
`while(r%/%10^-T==p%/%10^-T)T=T+1`
(so `T` ends-up with the number of shared digits +1)
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 21 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
f∩∩k(f/░▒φ░▒^╞╞mÅ▀£2=
```
[Try it online.](https://tio.run/##y00syUjPz0n7/z/tUcdKIMrWSNN/NG3io2mTzrdB6LhHU@cBUe7h1kfTGg4tNrL9/9@Uy9CAy9CIy9CUy8iAy8iYy8iUy8QAAA)
**Explanation:**
```
f # Get the n'th Fibonacci number using the (implicit) input-integer `n`
∩∩ # Convert it to a float (by changing `F(n)` to `1/1/F(n)`..)
k # Push the input-integer again
( # Decrease it by 1
f # Get the n-1'th Fibonacci number as well
/ # Divide the F(n) by F(n-1)
░▒ # Convert it to a string, and then a list of characters
# (float directly to character-list isn't possible yet unfortunately)
φ # Push the golden ratio constant (1.618033988749895)
░▒ # And convert it to a list of characters as well
^ # Zip the two lists together to create pairs
╞╞ # Remove the first two pairs (leading "1.")
m # Map over each remaining pair,
Å # using the following 2 commands:
▀ # Uniquify the pair
£ # And pop and push its length
2= # Then get the first (0-based) index of a 2 in this list
# (after which the entire stack is output implicitly as result)
```
The `/░▒φ░▒^` could alternatively be `/░φ░^2/` for the same byte-count, where the zip will create a single string and we split it into pairs with `2/`.
] |
[Question]
[
[Sandbox](https://codegolf.meta.stackexchange.com/a/19094/82007)
Many of us have seen math problems where a shape made of unit cubes is dipped in paint, and the answer is the number of painted sides. We'll generalize that problem in this challenge.
# Input
A 3-dimensional matrix of 0s and 1s.
# Output
A non-negative integer
# Challenge
Given a n by m by k matrix of 0s and 1s, we can view the matrix as a 3D shape by considering a n by m by k rectangular prism broken up into n \* m \* k unit cubes, and the unit cubes corresponding to the 0 values in the matrix are removed.
For example, the matrix [[[1,0],[0,0]],[[1,1],[0,1]]] represents the shape

Given such a shape, the [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge is to output the number of painted sides on the shape if the whole shape is dunked in paint.
# Test Cases
```
[[[1,1,1],[1,1,1],[1,1,1]],[[1,1,1],[1,0,1],[1,1,1]],[[1,1,1],[1,1,1],[1,1,1]]] -> 54
[[[1,0],[0,0]],[[1,1],[0,1]]] -> 18
[[[1]],[[0]],[[1]]] -> 12
[[[1,1,1,1,1,1],[1,1,1,1,1,1],[1,1,1,1,1,1],[1,1,1,1,1,1]],[[1,1,1,1,1,1],[1,0,0,0,0,1],[1,0,0,0,0,1],[1,1,1,1,1,1]],[[1,1,1,1,1,1],[1,0,0,0,0,1],[1,0,0,0,0,1],[1,1,1,1,1,1]],[[1,1,1,1,1,1],[1,0,1,1,0,1],[1,0,1,1,0,1],[1,1,1,1,1,1]],[[1,1,1,1,1,1],[1,0,1,1,0,1],[1,0,0,1,0,1],[1,1,1,1,1,1]],[[1,1,1,1,1,1],[1,1,1,1,1,1],[1,1,1,1,1,1],[1,1,1,1,1,1]]] -> 168
[[[0,0,0],[0,1,0],[0,0,0]],[[0,1,0],[1,0,1],[0,1,0]],[[0,0,0],[0,1,0],[0,0,0]]] -> 30
[[[1,1,1,1,1],[1,1,1,1,1],[1,1,1,1,1],[1,1,1,1,1],[1,1,1,1,1]],[[1,1,1,1,1],[1,0,0,0,1],[1,0,0,0,1],[1,0,0,0,1],[1,1,1,1,1]],[[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]],[[1,1,1,1,1],[1,0,0,0,1],[1,0,0,0,1],[1,0,0,0,1],[1,1,1,1,1]],[[1,1,1,1,1],[1,1,1,1,1],[1,1,1,1,1],[1,1,1,1,1],[1,1,1,1,1]]] -> 150
[[[1,1,0,1,1],[1,1,0,1,1],[1,1,0,1,1]],[[1,1,0,1,1],[1,1,0,1,1],[1,1,0,1,1]],[[1,1,0,1,1],[1,1,0,1,1],[1,1,0,1,1]],[[1,1,0,1,1],[1,1,0,1,1],[1,1,0,1,1]]] -> 104
[[[0,1,1],[1,1,1],[1,1,1]],[[1,1,1],[1,0,1],[1,1,1]],[[1,1,1],[1,1,1],[1,1,1]]] -> 54
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~55~~ 48 [bytes](https://github.com/abrudz/SBCS)
```
≢⍸↑2≠/¨⊢∘g\3⍴⊂2=2(g⊣(⌈∧⊢)/,)⍣6⍣≡(1,g←⍉⍤2⍉∘⌽)⍣6~⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97f@jzkWPenc8apto9Khzgf6hFY@6Fj3qmJEeY/yod8ujriYjWyON9EddizUe9XQ86lgOlNXU19F81LvYDIgfdS7UMNRJf9Q24VFv56PeJUYgqmPGo569YBV1j/qmgiz5z5nGBbQAhPqmegX7@6lHR0cb6gBhrA4aDWQgiRjglEHRE6vOxYXdCgOgIgMgCdUM5uHTAFYIVY7PXDiEOYIIHtwDOsgehEBsPNrpBLENsPJI02lAtE4iQwhXgIM9B4k8WJRCIxUmAnMIhA@RwaqHYJwiu4koNop/kWIDP5tY3YYU6SbVbpL8jS8oDZCUY7JhFtNRFe6kRd1i6FHvXAVTEwVDCwVDIwVDMwsFYwMFQ1MgNjABiv8HAA "APL (Dyalog Unicode) – Try It Online")
-7 bytes thanks to @ngn.
Improvements:
* `2 3 1⍉` → `⍉⍤2⍉`: Replace "cycle the axes once" with "swap 1st and 3rd axes, then 2nd and 3rd"
* `{⍵(g⍵)(g g⍵)}` → `⊢∘g\3⍴⊂`: A scan that ignores the left arg and applies `g` to the right arg, so it works like this:
```
3⍴⊂x gives (x x x)
⊢∘g\3⍴⊂x gives (x)(x ⊢∘g x)(x ⊢∘g x ⊢∘g x)
which is the same as (x)(g x)(g g x) because:
x ⊢∘g x
→ x ⊢ g x
→ x ⊢ (g x)
→ g x
```
---
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 55 [bytes](https://github.com/abrudz/SBCS)
```
{≢⍸↑2≠/¨⍵(g⍵)(g g⍵)}2=2(g⊣(⌈∧⊢)/,)⍣6⍣≡(1,g←2 3 1⍉⌽)⍣6~⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97X/1o85Fj3p3PGqbaPSoc4H@oRWPerdqpAMJTY10BTBda2RrBBTpWqzxqKfjUcfyR12LNPV1NB/1LjYD4kedCzUMddIftU0wUjBWMHzU2/moZy9Ysu5R31SQHf8507iAxoNQ31SvYH8/9ejoaEMdIIzVQaOBDCQRA5wyKHpi1bm4sFthAFRkACShmsE8fBrACqHK8ZkLhzBHEMGDe0AH2YMQiI1HO50gtgFWHmk6DYjWSWQI4QpwsOcgkQeLUmikwkRgDoHwITJY9RCMU2Q3EcVG8S9SbOBnE6vbkCLdpNpNkr/xBaUBknJMNsxiOqrCnbSoWww96p2rYGqiYGihYGikYGhmoWBsoGBoCsQGJv8B "APL (Dyalog Unicode) – Try It Online")
A full program that takes a 3D array. Uses the flood fill [already used here](https://codegolf.stackexchange.com/a/206114/78410). Another key idea is `g←2 3 1⍉⌽`, which effectively cycles through all six sides when applied with `⍣6` (repeat six times).
### How it works
```
{≢⍸↑2≠/¨⍵(g⍵)(g g⍵)}2=2(g⊣(⌈∧⊢)/,)⍣6⍣≡(1,g←2 3 1⍉⌽)⍣6~⎕
~⎕ ⍝ Logical negation of the input
(1,g←2 3 1⍉⌽)⍣6 ⍝ Pad with a layer of ones on all six sides
2(g⊣(⌈∧⊢)/,)⍣6⍣≡ ⍝ Flood fill from the outside, changing 1s to 2s:
2( ,) ⍝ Prepend 2 on the last axis
⊣(⌈∧⊢)/ ⍝ Pairwise lcm(max(x,y),y) over the last axis
⍝ Effectively, propagate 2 to an adjacent 1 on the right
g ⍝ Cycle the orientation once
⍣6⍣≡ ⍝ Repeat 6 times until the flood fill is complete
2= ⍝ Map 2s to 1s, and anything else to 0s
{⍵(g⍵)(g g⍵)} ⍝ Construct 3 arrays so that each axis becomes the last axis
2≠/¨ ⍝ Extract faces (where 0 and 1 are adjacent) for each array
≢⍸↑ ⍝ Count ones in all arrays
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~103~~ 102 bytes
```
Count[x=ImageData@FillingTransform@Image3D@#~ArrayPad~1;x~Differences~#&/@{1,{0,1},{0,0,1}},1.|-1.,4]&
```
[Try it online!](https://tio.run/##vVRba4MwFH7Prygt9OmsS1o7BkNwTAZ768PexIfQxS5QFWIGHS7@daeJsUrdUHZJIDlfzvnOVYypfGUxlXxPy8gtH9K3RAYn9ymmB@ZTSb1Hfjzy5PAsaJJFqYg9rdr43qK4F4K@7@hLQe5Ohc@jiAmW7FlWLJbXXk4gx0BUfda3ArL6uCIrcMJl6acB2glehYoCyTIZBCQMQ5i77hwMXlcYIchrBDnKq0WAaH/9uxI6L/hLTY@jZjDbOgpQ4xibNC1FmdS1GbltzbS6MWqU67OPdtswI1CbInRLMHsI/R2zlvEgmsbEo5kjO6TbfNMOQddk5mOn1szNvtj4BhvNIKf2vMEXA@wmMEruFddp/ffyWDb5EXtq7El169Fsex3EHatL2cb7RyudI3bOn89v/0OQUmH5CQ "Wolfram Language (Mathematica) – Try It Online")
To use `FillingTransform` (replace all the inner `0` with `1`), I have to convert the data to `Image3D` and convert it back. The rest is just to count the number of nonzero consecutive differences etc.
[Answer]
# [Python 2](https://docs.python.org/2/), 493 bytes
```
A=lambda*z:0<sum(abs(a-b)for a,b in zip(*z))<2
R=lambda c:reduce(lambda a,b:a|b,c)
def C(c,d,h,w):
a=[[{(i/w/h,i/w%h,i%w)}for i in range(d*h*w)if c[i]-v]for v in[1,0]]
for r in a:
i=0
for j in range(len(r)**2):i=j/len(r);c=[[f for f in r[i:]if any(A(j,k)for k in f for j in r[i])^j]for j in[0,1]];r[i:]=(c[0]and[R(c[0])])+c[1]
a[0]=[s for s in a[0]if all(0<e[i]<[d,h,w][i]-1for i in[0,1,2]for e in s)]
p,q=[sum(6-sum(A(x,y)for x in r)for y in r)for r in[k and R(k)for k in a]]
print q-p
```
[Try it online!](https://tio.run/##vVXbjtowEH3efIVfVrJTIxwKq1WWPKD9A14tVzKOUwLZkE3YDdD226nHTiBpaQXqhYgwlzNnLkbjYr9dbvLR8TiLMvmyiKV/CNm0envBclFhOViQZFMiSRcozdEhLbB/IGQ68uYNHKmw1PGb0rjRDTSUXxdUES/WCXrGisZ0SWsSekhGnH/B6bAeLql535v3fU2@QYYU@EuZf9Y49pd@TdIEKZ6KwbsA97tx84AyITwEeglwGXp3acS8O7CszgSZznFJfH9EwjRaDZ36pEzyxAYnFsrTUJgkMt/jGV7RtW10DS6HWjUoQT6tRGvgjAZCPNngCCvOhMxjPrcSEeSD4oGpUBot4pWlqWylxgC5sgyzqTacU26HIqDDoO0fyOnI5tIQVRHDVdBXQ2XO42EA7xne0b0tdWfrs@L@LMJg@Np0FaM57vQkYXJFmeZb9DoojkpWukIR4h4yH87NbM0j6A@/RuhY2C89vRhBz6TMmBkcm4NbrQ@xrgbQjz09LfUV2qks2i3bPZe0fxcJMruo3RbJro68ckLnEdt23JG0B9UcVWtpUzvdeS7GXDi3bt6r5F5PnYn/Xr42Ovij6Ftz39R3f3isA/hZblP9R1T3D/M3l4Tw9K7QaqvjiE/GNHikwYgGD4/0o@GYmC8b08lYeLDDYF9RB28vIrvCaEsB14v5xGanwb4HJ7GWZccCS9oa677xZE8yud3qXAMNV3Z/F5nM7TYGrLt7NjXozmGLs@t3UwvL4Zasq8tN7hmfeJu78Pgd "Python 2 – Try It Online")
Takes input as a flattened array along with depth, height, and width.
### How?
1. Find 6-connected components of `0`s and of `1`s
2. Remove the components of `0`s which contain a `0` on the outer edge
3. Take 6 times the number of `1`s minus the number of `1`s that border each other to get the number of `1`s that are exposed to any `0`. This includes `0`s on the inside (internal `0`s / air pockets), so:
4. Subtract (6 times the number of internal `0`s minus the number of internal `0`s that border each other) to get the number of internal `0`s that are exposed to any `1`. This subtracts all of the faces on the inside.
5. Done!
```
# Are the arguments adjacent via 6-connectivity?
A=lambda *z:0<sum(abs(a-b)for a,b in zip(*z))<2
R=lambda c:reduce(lambda a,b:a|b,c)
def C(c,d,h,w):
a=[
[
{(i/w/h,i/w%h,i%w)}
for i in range(d*h*w)
if c[i]-v
]
for v in[1,0]
]
# a[0]: set of coordinates of all 0s
# a[1]: set of coordinates of all 1s
# Find connected components:
for r in a:
i=0
for j in range(len(r)**2):
# for each index i
i=j/len(r);
# do len(r) passes:
# c[0]: all components with index > i+1 that are adjacent to component i
# c[1]: all components with index > i+1 that are not adjacent to component i
c=[
[f for f in r[i:]if any(A(j,k)for k in f for j in r[i])^j]
for j in[0,1]
];
# Replace components i and higher with:
r[i:]=(
# If c[0] is nonempty, then the union of c[0]
c[0]and[R(c[0])]
)+c[1] # append c[1]
# a[0]: set of connected components of 0s
# a[1]: set of connected components of 1s
# Remove all of a[0] that border the outside:
a[0]=[
# Filter for:
s for s in a[0]if
all(
# The coordinates along each axis are between 1 and that axis's length minus 2, inclusive
0<e[i]<[d,h,w][i]-1
for i in[0,1,2]
# For all points
for e in s
)
]
# a[0] now: set of connected components of 0s that do not border the outside
p,q=[
sum(
6- # cube contributes 6 sides
sum(A(x,y)for x in r) # minus the number of adjacent cells
for y in r # for each cube
)
for r in # for each connected component
[k and R(k)for k in a]
]
print q-p
```
[Answer]
# [Python 3](https://docs.python.org/3/) with `NumPy`, ~~177~~ 161 bytes
*-16 bytes thanks to @fireflame241 !*
```
f=lambda l:g(pad(pad(l,1)-2,1)+2,1,1,1)
def g(l,*i):l[i]+=2;return l[i]%2if l[i]-2else sum(g(l,*(t*d+i))for d in eye(3,3,0,int)for t in[1,-1])
from numpy import*
```
[Try it online!](https://tio.run/##vVTbjtowEH3PV4xYVRsvCUpgqVqq7Htf@gMIVV4yAUuOHdkOLV9Px85FsKUVqBdFhLmc45k5Y6U5ur1Wi9OpKiSvX0sOcrWLG16Gn0xyls7pNaWXf1hUYgU7SjwJtpJrsZkW808GXWsUePfdXFTBSOcoLYJt6zjAY/dUTgVjlTZQglCAR4wXySLJEqFcCDsKr/MkzTcsqoyuQbV1cwRRN9q4p9MDfAn@AY0VWoGwoFtXcoclxId8li@Jbx3yEnQFPvCRRQ9gNbg9QtWqrfO0cOiMpoNHC1bsFKfmEQhZarTq0cGeHzBwaFbeSgfc7NoalYNal1hMtprKcOUmxPncozXUXLVcyqNnCdUd0Dap06lv8azSHg0GGb3C3JjEG18lKraK@mG7JiPohR1bvoAnb9thkR@3bRqD1vbifeNGCbWzwF9JLOqtwa0JktFmRlGivuyAjgZjVgnp0AxuPKEptEFfqqfYo4388qSfmdZK/sy6UigaJnSL36mkL1iQRE2MBy6TgJ7ZRgoXT9KXCWN@Vuu1LqDyU1KgMXQx4i6cjOliPJCd1ut1uJWb5M0/GWeR7JeZC84G0hdYPkfh1IziGb17fPAGTP4hYEKuRwyZeTT0lFycfoM3dpacd94917x/x/R2dtW7j5ndzLxRoU7j90H@MFC3lmFZ/bqGyFC887vMVU44dpFdrO689E32xVhnov/evpWd/xH73tp3zd0tZTnKl51BfraHYv8R1TWYPXe35m9/Ln4A "Python 3 – Try It Online")
### Big idea:
DFS over all outer empty cells. Every time an outer empty cell touches a cube, adds 1 to the counter.
### Explanation:
* `0` denotes air (empty cell), odd positive numbers denote walls, and even positive numbers denotes paint.
* First, pad everything with a layer of 0 (air), so all outer air cells are connected: `pad(l,1)`
* Then, pad everything with a layer of 2 (paint), which acts as a barrier to prevent out of bound search later. To do this, subtracts `2` from all cells, pad everything with 0, then adds 2 back: `pad(arr - 2, 1) + 2`
* Start DFS at `l[1,1,1]`, which is guaranteed to be an outer air cell.
* At each DFS step (function `g`):
+ If current cell is paint, stops recursion.
+ If current cell is wall, adds 1 to counter, and stops recursions.
+ If current cell is air, changes it to paint, and recurs on the 6 neighbors.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~37~~ ~~36~~ 35 bytes
```
e7BYa~6&1ZIt1)-tz6*yZybfX[hhtZPq~z-
```
Input is a row vector of zeros and ones, and a row vector of three integers with dimensions from inner nesting level to outer.
[Try it online!](https://tio.run/##y00syfn/P9XcKTKxzkzNMMqzxFBTt6TKTKsyqjIpLSI6I6MkKqCwrkr3//9oQwVc0ACnjGEsV7SxAhDGAgA) Or [verify all test cases](https://tio.run/##y00syfmf8D/V3Ckysc5MzTDKs8RQU7ekykyrMqoyKS0iOiOjJCqgsK5K979LyP9oQwVc0ACnjGEsV7SxAhACaZA6A6haA7CMkQIQQmUMwbQhVCUl0ADFHgSbeuqxk8SpNyConiAEhpCZgomCGZBGuNdAAZmNjDHUoMQJ5SGNi0VIhyHJOoizg9gwNFUAQmgYGGBJyzRmgV1grGACjkVKchYA).
### Explanation
The code initially adds a frame of empty space around the 3D array. Any cell that is not space connected to that frame is filled. This has the effect of filling any holes in the original 3D shape.
The number of painted faces is the number of cubes in that filled shape times 6, minus the number of cubes that touch some other cube (two cubes touching means a face is not accessible to the paint; pairs are counted twice).
To detect which cubes touch, all pairwise distances between the cubes are computed, and two cubes touch if their distance is 1.
```
e % Implicit inputs: vector or zeros and ones, and 3-element vector specifying
% size along each dimension. Reshape the first according to the second. This
% produces the 3D array
7BYa % Pad the 3D array with a frame of zeros along the three dimensions
~ % Negate. This changes 0 to 1 and vice versa (*)
6&1ZI % Label connected components using 6-connectivity in 3D (so no diagonals)
% This considers the zeros in (*) as background, and nonzeros as foreground.
% The foreground cells are labelled with a different integer according to
% indicate the component. There will be an outer component that will include
% the added frame and any space surrounding the shape, and potentially more
% components if the shape has inner holes
t1)- % Duplicate Subtract the upper-right-front entry from each entry. This
% makes the outer connected component (originally the space surrounding the
% shape) equal to 0, and other components or brackground become nonzero.
% So now the shape plus any inner holes in it are nonzero (**)
tz6* % Duplicate. Number of nonzeros times 6. This is the maximum number of faces
% of unit cubes that could be painted (some won't actually get pointed,
% namely any face that touches any other face) (***)
yZy % Duplicate from below: pushes a copy of (**). Get its size as a length-3
% vector
bf % Bubble up: moves the original copy of (**) to the top. Push linear indices
% of its nonzero entries. Linear indices run down, then accros (left to
% right), then front to bottom
X[ % Convert linear indices to a set of three indices assuming an array of the
% specified size. Gives three column vectors
hh % Concatenate veftically twice. This gives a 3-column matrix where each row
% contains the coordinates of a cube in (**)
tZP % Duplicate. Pairwise distances between rows of the 3-column matrix and
% those of its copy
q~ % Subtract 1, negate. This gives 1 for distances equal to 1, and 0 otherwise
z % Number of nonzeros
- % Subtract from (***). Implicit display
```
[Answer]
# JavaScript (ES6), ~~295~~ 291 bytes
```
a=>a.map((s,z)=>s.map((r,y)=>r.map((v,x)=>v|!(g=(x,y,z,R=a[z]&&a[z][y])=>R&&1/R[x]?R[x]?0:R[x]++|[0,1,2,3,4,5].some(n=>(i=n&1||-1,g(n&6?x:x+i,n&2?y+i:y,n&4?z+i:z)))|--R[x]:1)(x,y,z)))).map((s,z,a)=>s.map((r,y)=>r.map((v,x)=>n+=v&&!r[x+1]+!((q=s[y+1])&&q[x])+!((q=a[z+1])&&q[y][x]))),n=0)|n*2
```
[Try it online!](https://tio.run/##vVPbboMwDH3vV7QvUTJMm1BaTUgp/9DXiIeoayumNrQwIUD8OwsEetmyqZO2CcnxcXxiH1u8ylxmmzQ@vbkqedk2O95IvpLTozxhnEFF@CozIIVSg9SAHAoN8nqC9xwXUEIFay5FFSHUWlFG@nqNEJutRRGFnaFBezhOLSgw8GAOPiyiaZYct1jxFY65QqyuXQZ7rNAyLILCiUEhLyydOCi154eV9ipCSO267WMBI6a6DpFLzyC/7Vo5PEdokorCYZEzwfjMM1FqnyB01o8SE9M6hlgZtWFCQHFKavXkNZtEZclhOz0ke7zDQgimJbEIPpzauYnQL2/uOLrSeDYbL/yRpQrVeVTbnt@hK4c9Wzhdbs@4Znojuwa46@YBdFECt0rNZ0N/x2x9akU/Y9KHmQ9OaJj50rKeTqBZ47Dcfr1DZGjGYHNj5fRl5tS@WnrT2md/kPePWcNYqG8by@//T807 "JavaScript (Node.js) – Try It Online")
NB: This is a bit too slow to reliably complete the 6th test case on TIO.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 75 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
-.øε0δ.ø©}ε®Ù.ø}D€øDø€ø««εÁÁεN3@iD0ÚPi1V}YiγÁεN2@id}}À˜}}}ÀÀ2V}€`€ü2€`ʒË≠}g
```
Dang, this was hard in 05AB1E.. But it works now. 05AB1E and matrices are already a bad combination, so add an additional dimension and it's a complete disaster, haha..
[Try it online](https://tio.run/##yy9OTMpM/f9fV@/wjnNbDc5tAdKHVtae23po3eGZQHaty6OmNYd3uBzeAaYPrT60@tzWw42HG89t9TN2yHQxODwrINMwrDYy89xmsKCRQ2ZKbe3hhtNzakHU4QajsFqg1gSQ9j1GINapSYe7H3UuqE3//z86OtpQx1DHAIgNY3VwsIEcequK/a@rm5evm5NYVQkA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaCkU6nDpeRfWgLh2VcenvBfV@/wjnNbDc5tAdKHVtae23po3eGZQHaty6OmNYd3uBzeAaYPrT60@tzWw42HG89t9TN2yHQxODwrINMwrDYy89xmsKCRQ2ZKbe3hhtNzakHU4QajsFqg1gSQ9j1GINapSYe7H3UuqE3/r3Nom/3/aCAw1AHCWB00GshAEjHAKYOiJ1ZHAWygAVDIAEhClYJ5CGmwMFQSoQcOYcYRwYM7RQfZqRCIjUc7nSC2AVYeaToNiNZJZAhBghfsFUg0wCIHGj0wEZi1ED5EBqsetPhCto8oNopfkEIaP5tY3YYU6SbVbpL8jQg4AyRJTDbMGjqqgiUS6hUEsf91dfPydXMSqyoB).
**Explanation:**
Step 1: Surround the entire input 3D matrix with a layers of empty cells (0s) in each dimension:
```
- # Transform all values into 0s by subtracting the values in the
# (implicit) input 3D-matrix by the values in the (implicit) input
.ø # Surround the (implicit) input-matrix with this 2D-matrix of 0s as
# both leading and trailing item
ε # Map each 2D matrix of the 3D matrix to:
δ # For each row of the 2D matrix:
0 .ø # Surround it with a leading and trailing 0
© # Store the modified 2D matrix in variable `®` (without popping)
}ε # After the map: map over each 2D matrix in the 3D matrix again:
®Ù # Uniquify the last 2D matrix that was stored in `®`,
# so we'll have a row of 0s wrapped inside a list
.ø # Surround each 2D matrix with this row of 0s
} # And close this map as well
```
(Note: the z-axis actually contains two surrounding empty cells instead of one, but this doesn't really matter for the rest of the program.)
Step 2: Get a list of all strings of cells along the x, y, and z axes respectively:
```
D # Duplicate the current 3D-matrix, which of itself already contains
# all strings of cells along the x-axis
€ # Map each 2D matrix of the 3D matrix to:
ø # Zip/transpose; swapping rows/columns
D # Duplicate as well, which are the strings of cells along the y-axis
ø # Zip/transpose; swapping rows/columns of this 3D matrix
€ # Map each 2D matrix of the 3D matrix to:
ø # Zip/transpose; swapping rows/columns
# And we now also have the strings of cells along the z-axis
«« # Merge all three lists together
```
This will result in a 3D matrix with three inner 2D matrices (one for each dimension), which are each lists of strings of cells.
Step 3: Fill all inner bubbles with 1s:
```
ε # Map each 2D matrix of the 3D matrix to:
ÁÁ # Rotate the rows of the matrix twice towards the left
ε # Map each string of cells in the current 2D matrix to:
N3@i # If the 0-based index is >= 3:
D # Create a copy of the string of cells
0Ú # Remove all leading and trailing empty cells
Pi } # If there are now only filled cells left:
1V # Set flag `Y` to 1
Yi # If flag `Y` is 1:
γ # Split the string of cells into groups of equal adjacent values
Á # Rotate these groups once towards the left
ε # Map each group to:
N2@i } # If the 0-based index is >= 2:
d # Fill all empty cells (1 remains 1, 0 becomes 1)
}À # After the map: rotate the groups back to the right
˜ # And flatten it to a single string of cells again
}}}ÀÀ # After the map: rotate the rows twice back towards the right
2V # Reset flag `Y` back to 2 for the next iteration
} # Close the map
```
We basically skip the first and last strings of cells, since we know those are surrounding layers of empty cells we added in step 1. In addition, we also don't want to modify the second and second to last strings of cells, since those are the outer layers of the initial input 3D matrix. We do however want to start checking from the second string of cells onward until we find a solid string of filled cells (minus the surrounding empty cells). For all strings of cells after we've encountered such a solid string of filled cells, we want to transform them into solid strings of filled cells as well (minus the surrounding empty cells) to fill the bubble.
Step 4: Now that we've filled the bubbles, we want to get a list of all pairs of cells:
```
€` # Flatten the 3D matrix containing the three list of strings of
# cells one level down to a single list of strings of cells
€ # Map each string of cells to:
ü2 # Create overlapping pairs of cells
€` # And flatten this list of list of pairs one level down as well to a
# list of pairs
```
Step 5: Filter out any pairs of two empty or two filled cells, so we only have pairs containing one of each:
```
ʒ # Filter this list of paired cells by:
Ë≠ # Check that both values in the pair are NOT the same
} # Close the filter
```
Step 6: Get the amount of pairs left containing both a filled and empty cell, and output it as result:
```
g # Pop and push the length of the filtered list
# (after which it is output implicitly as result)
```
[Try it online with each of these steps output separately.](https://tio.run/##yy9OTMpM/f9fyTOvoLTESkFJh8v20DZ7LqXgktQCBUOwgK7e4R3nth7ad24LkHFoZS2Qve7wTCC7FlmtEVity6OmNYd3uBzeAaYPrT60GlmNMVjNua2HGw83ntvqZ@yQ6WJweFZApmFYbWTmuc1gQSOHzJTa2sMNp@fUgqjDDUZhKPaYgM0AGp8AsmKPEYiFLG8Klj816XD3o84FKDrNFPQV8ktLYP5M59L5/z86OtpQx1DHAIgNY3VwsIEcequK/a@rm5evm5NYVQkA)
] |
[Question]
[
Given integer `n`, output the smallest exponent `e` greater than 1 such that `n^e` contains `n` as a substring.
For example, for `25`, the answer should be `2`, as `25 ^ 2 = 625`, which contains `25` as a substring, but the answer for `13` should be `10`, as `13 ^ 10 = 137858491849`, so `10` is the lowest exponent for which the result contains `13` as a substring.
# Rules
* Standard I/O rules
* Standard loopholes apply
* Shortest code in bytes wins
* `n` will always be an integer greater than `0`
# Test Cases
```
1 => 2 (1 ^ 2 = 1)
2 => 5 (2 ^ 5 = 32)
3 => 5 (3 ^ 5 = 243)
4 => 3 (4 ^ 3 = 64)
5 => 2 (5 ^ 2 = 25)
6 => 2 (6 ^ 2 = 36)
7 => 5 (7 ^ 5 = 16807)
8 => 5 (8 ^ 5 = 32768)
9 => 3 (9 ^ 3 = 729)
10 => 2 (10 ^ 2 = 100)
11 => 11 (11 ^ 11 = 285311670611)
12 => 14 (12 ^ 14 = 1283918464548864)
13 => 10 (13 ^ 10 = 137858491849)
14 => 8 (14 ^ 8 = 1475789056)
15 => 26 (15 ^ 26 = 3787675244106352329254150390625)
16 => 6 (16 ^ 6 = 16777216)
17 => 17 (17 ^ 17 = 827240261886336764177)
18 => 5 (18 ^ 5 = 1889568)
19 => 11 (19 ^ 11 = 116490258898219)
20 => 5 (20 ^ 5 = 3200000)
25 => 2 (25 ^ 2 = 625)
30 => 5 (30 ^ 5 = 24300000)
35 => 10 (35 ^ 10 = 2758547353515625)
40 => 3 (40 ^ 3 = 64000)
45 => 5 (45 ^ 5 = 184528125)
50 => 2 (50 ^ 2 = 2500)
55 => 11 (55 ^ 11 = 13931233916552734375)
60 => 2 (60 ^ 2 = 3600)
65 => 17 (65 ^ 17 = 6599743590836592050933837890625)
70 => 5 (70 ^ 5 = 1680700000)
75 => 3 (75 ^ 3 = 421875)
80 => 5 (80 ^ 5 = 3276800000)
85 => 22 (85 ^ 22 = 2800376120856162211833149645328521728515625)
90 => 3 (90 ^ 3 = 729000)
95 => 13 (95 ^ 13 = 51334208327950511474609375)
100 => 2 (100 ^ 2 = 10000)
```
[Python script](https://tio.run/##TU@7bsMwDJzNrzgECCAlHux0K@As/Yw@gKCRbAIxZUhy23y9SqUeOpAgj8c7crnnKchTKT6GGemewPMSYsYljl9EV@fhWa6czY99poYx4ETN98Q3h5SjopCQwfLX4XAAV6IyjwN6aqLLaxQw0aS7LNlU5df@3eKoc/4PnhRkj62GuyWnFFpiZexewiqZZcS6IAfsU3Vl@YxudpITglfsTXbYw0ytnmGJfIioJMSLjM5wi8dED3RqvH0mlprNQ0WHc5U2Gh@1GDTZh6a0cC22XB911pZS@q7rSv8L) to generate the first 1000 answers
[Answer]
# [Perl 6](http://perl6.org/), 31 bytes
```
{$^a;first {$a**$_~~/$a/},2..*}
```
[Try it online!](https://tio.run/##DcbRCkAwFAbgV/nTSax1zMSNeBRrF1aKaNxo5tXHd/Uds1@7tN3IHYYUaLK9W/x5IZAVgsz7VmSrKDWziOm0NzIyGEYEBzIxg9s9nqJm1qqU/3QrG8XMtVJl@gA "Perl 6 – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~69~~ 44 bytes
```
function(n,i=2){while(!grepl(n,n^i))i=i+1;i}
```
Anonymous function. Works on large `i` when `n` is converted to BigZ (see TIO). Thanks for teaching me something Giuseppe and digEmAll!
[Try it online!](https://tio.run/##RY1BCsIwEEX3OcWImwRFqCAI0qsIaZ2mA@00zEwRFc8e05XwN@/B40vZg42kUMfYo2qUF9gCOWo1EBU6Sm@I/ABdc17ENgHEhglFIQrZOKNR7ybqpNY@zTk454a2DCv3Rgt7PlJ7Dp/nSBP6XRLMU3V8pxCopUNzo28ZfNTTduavlxDcH5uK5Qc "R – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 9 bytes
```
f}`Q`^QT2
```
[Try it online!](https://tio.run/##K6gsyfj/P602ITAhLjDE6P9/Q2MA "Pyth – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~42~~ 41 bytes
-1 byte thanks to [Ørjan Johansen](https://codegolf.stackexchange.com/users/66041/%C3%98rjan-johansen) (returning `y` directely)
```
f=lambda x,y=2:y*(`x`in`x**y`)or f(x,y+1)
```
[Try it online!](https://tio.run/##DYo7DsMgDED3nsLKZFMGyBiJXqVQJSSWWgchosDpKeP7pFaOU@beo/uG32cNUHVz89IU@upZfFWqeTozRBzlaanHAQwskIPsG1rNUjCH@82SroJEY1oekPLwwHoC94JJR2Tq1pg/ "Python 2 – Try It Online")
## Explanation/Ungolfed
Recursive function trying from \$2,3\dots\$ until we succeed:
```
# Start recursion with y=2
def f(x,y=2):
# If we succeed, we arrived at the desired y
if `x` in `x**y`:
return y
# Else we try with next y
else:
return f(x, y+1)
```
[Try it online!](https://tio.run/##ZU4xksIwDOx5xQ5pbM4FobwZrqO4mgcQTyJfNHPjZBSFxK8PNtCxjVbaXUlj0n6Ip22rcFUvCqF2lomHiIW1Rzqfdh0FBLO6zO33DhkVfgMWwjS3LVHnCvcifKcOXqE9oaOJJbfpGeCAZm3AMZfDITWvNQVCOkt82ypc/icq21TS64FIq75VytpHsDyG9FXbLQwCLifExz8yteOoRvxy4zjOaqzNphwfJc/Bbo/zD/YuGLZbfTw@AA "Python 2 – Try It Online")
[Answer]
# JavaScript (ES6 / Node.js), ~~41~~ 40 bytes
*Saved 1 byte thanks to @Shaggy*
Takes input as a *Number* (works for \$n<15\$) or a *[BigInt](https://v8.dev/blog/bigint)* literal.
```
n=>(g=x=>`${x*=n}`.match(n)?2:-~g(x))(n)
```
[Try it online!](https://tio.run/##FYtBDoIwEAC/sgcOuzQQ5KgufqVNpVWDuwSIaULw67XeZpKZl/u41S/PeWtE72MOnIUHjJx4sNWeapbDtm@3@QcK3fpz842YiIrkoAsKMJzkAgLXAl33R2MIvMqq09hOGtE6rHY5qKQWDITyUv4B "JavaScript (Node.js) – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~25~~ ~~23~~ 17 bytes
*-2 bytes thanks to @Erik the Outgolfer*
*-6 bytes thanks to @ngn*
*thanks to @H.PWiz for making the code not require a custom `⎕pp` (print precision)*
```
⊢⍟×⍣(∨/(⍕÷)⍷0⍕⊣)⍨
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HXoke98w9Pf9S7WONRxwp9jUe9Uw9v13zUu90AyHrUtRjIXPE/7VHbhEe9fY@6mg@tN37UNvFR39TgIGcgGeLhGfw/TcGQK03BCIiNgdgUiC2A2BAkaAjmmXIBAA "APL (Dyalog Unicode) – Try It Online")
```
⊢⍟×⍣(∨/(⍕÷)⍷0⍕⊣)⍨
×⍣( )⍨ generates a geometric progression by repeatedly multiplying the argument
by its original value
∨/(⍕÷)⍷0⍕⊣ the progression stops when this function, applied between the new and the
last old member, returns true
÷ the original argument (ratio between two consecutive members)
⍕ formatted as a string
⍷ occurrences within...
0⍕ ...the formatted (with 0 digits after the decimal point)...
⊣ ...new member
∨/ are there any?
⊢⍟ use logarithm to determine what power of ⍵ we reached
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes
```
;.^s?∧ℕ₂
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/31ovrtj@UcfyRy1THzU1/f9vaPQ/CgA "Brachylog – Try It Online")
### Explanation
```
;.^ Input ^ Output…
s? …contains the Input as a substring…
∧ …and…
ℕ₂ …the Output is in [2,+∞)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes
```
∞>.Δm¹å
```
[Try it online!](https://tio.run/##yy9OTMpM/f//Ucc8O71zU3IP7Ty89P9/C1MA "05AB1E – Try It Online")
Explanation:
```
∞>.Δm¹å //full program
∞ //push infinite list, stack = [1,2,3...]
> //increment, stack is now [2,3,4...]
.Δ //find the first item N that satisfies the following
¹ //input
å //is in
m //(implicit) input ** N
```
[Answer]
**SAS, ~~71~~ 66 bytes**
Edit: Removed `;run;` at the end, since it's implied by the end of inputs.
```
data a;input n;e=1;do until(find(cat(n**e),cat(n)));e+1;end;cards;
```
Input data is entered after the `cards;` statement, like so:
```
data a;input n;e=1;do until(find(cat(n**e),cat(n)));e+1;end;cards;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
```
Generates a dataset `a` containing the input `n` and the output `e`.
[](https://i.stack.imgur.com/0rAl1.png)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
2ẇ*¥@1#
```
[Try it online!](https://tio.run/##y0rNyan8/9/o4a52rUNLHQyV////b2gKAA "Jelly – Try It Online")
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 99 bytes
```
import StdEnv,Text,Data.Integer
$n=hd[p\\p<-[fromInt 2..]|indexOf(""<+n)(""<+prod(repeatn p n))>=0]
```
[Try it online!](https://tio.run/##LY2xCsIwFEV3vyKUDi22RQU361SHgqBQt7bDo0lqIHkJ8SkV/HZjUafL4cC5gxaAwVh@14IZUBiUcdYTa4gf8JFdxERZBQRFjSRG4Rcxllfeuq5zu7yV3ppZsE1R9C@FXEwnmUTRbonpd5y3PPHCCSBkjmGa7stVHxqC@aJkMUvI/sNsvU3De5AaxlvI62OonghGDT84ayBpvfkA "Clean – Try It Online")
If it doesn't need to work for giant huge numbers, then
# [Clean](https://github.com/Ourous/curated-clean-linux), 64 bytes
```
import StdEnv,Text
$n=hd[p\\p<-[2..]|indexOf(""<+n)(""<+n^p)>=0]
```
[Try it online!](https://tio.run/##S85JTcz7n5ufUpqTqpCbmJn3PzO3IL@oRCG4JMU1r0wnJLWihEslzzYjJbogJqbARjfaSE8vtiYzLyW1wj9NQ0nJRjtPE0LFFWja2RrE/g8uSQTqt1VQUTA0/v8vOS0nMb34v66nz3@XyrzE3MxkCCcgJ7EkLb8oFwA "Clean – Try It Online")
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 84 bytes
Takes input as a String representing the number and outputs an int.
Most of the bytes come from the verbosity of the `BigDecimal` being needed to process the large numbers.
```
n->{int i=1;while(!(new java.math.BigDecimal(n).pow(++i)+"").contains(n));return i;}
```
[Try it online!](https://tio.run/##bY/BboJAEIbP8hRTThB@ya6wAiV6aHqtF4@Nhy2iroWFwKppDM9OV0NvncNOMv83k2/P8irnTVvq8/57bC9flSqoqGTf04dUmu6OQ7amoDfS2Ka0KbuDLEraWICmmhgbkva2plP6SNrPn/ngzJ59OrAhTSsa9Xx9f@BqxfPbSVWl9@Lp8kZn6xTW0pzCN3V8LwtVy8rTftg2Ny8IlB@4rh8WjTbWsLeBn3eluXSaVD6M@X/G10btqbb4JPa5I9kde9/qzw5N96cr6fU5/2S7sG8rZTwXru9b6HFy@9Obsg6biwlbi5tKe5ICcmm@tk9AOrQDK@PMhunTzjCOHAtEiCGwRIIUGTgD5@AL8Ag8BhfgS/AEPAXPsGBYCEQMkUDMEAsIBmG3GZYCCUMikDKkAhlDZncZ@wU "Java (OpenJDK 8) – Try It Online")
---
**How it works**
This is fairly simple but I'll include the explanation for posterity;
```
n->{ // Lamdba taking a String and returning an int
int i=1; // Initialises the count
while(! // Loops and increments until
(new java.math.BigDecimal(n) // Creates a new BigDecimal from the input n
.pow(++i)+"") // Raises it to the power of the current count
.contains(n) // If that contains the input, end the loop
);
return i; // Return the count
}
```
[Answer]
# PARI/GP 49 bytes
```
f(n)=e=1;until(#strsplit(Str(n^e++),Str(n))>1,);e
```
[Try it online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWNw3TNPI0bVNtDa1L80oyczSUi0uKigtyMks0gkuKNPLiUrW1NXXATE1NO0MdTetUiMadBUWZeSUaaRpGppqaXDCOobGmJkQeZgEA)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 37 bytes
```
->n,i=2{i+=1until/#{n}/=~"#{n**i}";i}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5PJ9PWqDpT29awNK8kM0dfuTqvVt@2TglIa2ll1ipZZ9b@1zDU0zMy0NRLTUzOqK7JrClQSIvOjK39DwA "Ruby – Try It Online")
[Answer]
# Japt, 10 bytes
```
@pX søU}a2
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=QHBYIHP4VX1hMg==&input=ODU=)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 45 bytes
*Test cases taken from [@Arnauld's answer](https://codegolf.stackexchange.com/a/176738/78039)*
```
a=>eval("for(i=1n;!(''+a**++i).match(a););i")
```
[Try it online!](https://tio.run/##FcrBDoIwDADQX6nEhJZGguc5v4VmbDozOwKEi/Hbx7i9w/vILqtb4rzdNE@@BFvEPv0uCZuQF4z2ruaCbcvSdcyR@q9s7o1ChkxsqJxJwUJtoPCoGIaTzAQu65qT71N@4Sh4/emfah2BIaASlQM "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes
```
W∨‹Lυ²¬№IΠυθ⊞υIθILυ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/788IzMnVUHDv0jDJ7W4GEjkpZdkaJRq6igYAbFffomGc35pHpBMLC7RCCjKTylNLgFKA@UKNTU1FQJKi4GqdRTA0kARa66AokyYcrhhQPH//w3N/@uW5QAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
W∨‹Lυ²¬№IΠυθ⊞
```
Repeat until the the list length is at least 2 and its product contains the input...
```
⊞υIθ
```
... cast the input to integer and push it to the list.
```
ILυ
```
Cast the length of the list to string and implicitly print it.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~63~~ 58 bytes
```
def f(n,e=2):
while str(n)not in str(n**e):e+=1
return e
```
[Try it online!](https://tio.run/##ZYxBCsIwEEXXzSmGbprUEZpIN4V4F6ETG5BJiJHi6WOiLgR3M///9@Izb4FPpazkwElGskYtots3fyO45yRZccjg@fOMI6mFDlaLLlF@JAZ6o2vwuU4rGZPneiIMx/OAzakQetsjxLDXvAVKCeFCAm7edOErSY1GN/wr@uvNjKCnCWH@WZUX "Python 3 – Try It Online")
Python2 would probably be shorter, but I like using 3. Coming up wiht a lambda is difficult, but I'm trying a few things.
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), 10 bytes
```
ôkï⌠#k╧▼ï⌠
```
[Try it online!](https://tio.run/##y00syUjPz0n7///wluzD6x/1LFDOfjR1@aNpe8Cc//8NuYy4jLlMuEy5zEy5LEy5LE3/AwA "MathGolf – Try It Online")
## Explanation
This feels extremely wasteful, having to read the input explicitly twice, having to increment the loop counter twice.
```
ô start block of length 6
k read integer from input
ï index of current loop, or length of last loop
⌠ increment twice
# pop a, b : push(a**b)
k read integer from input
╧ pop a, b, a.contains(b)
▼ do while false with pop
ï index of current loop, or length of last loop
⌠ increment twice
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 41 bytes
```
f=->n,a=n{(a*=n).to_s=~/#{n}/?2:1+f[n,a]}
```
[Try it online!](https://tio.run/##KypNqvz/P81W1y5PJ9E2r1ojUcs2T1OvJD@@2LZOX7k6r1bf3sjKUDstGigfW/tfw1BPz9BAUy83saC6pqKmQCG6QictuiIWKAUA "Ruby – Try It Online")
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 104 89 bytes
```
a=>{int i=2;while(!(System.Numerics.BigInteger.Pow(a,i)+"").Contains(a+""))i++;return i;}
```
[Try it online!](https://tio.run/##VY9fS8MwFMWf009xLQgJnWlX8SnrQAVBUJEp@ByyrF5oE0nSDdn22evtZKAvObn/zo9j4pXxwY5DRNfC23dMtldgOh0j3MI@i0knNPAwOLNAl2ZAzxI20Iy6We6pAGxqtfvEzvIL/nsvX4beBjRR3mH76JJtbZCvfsf1DEWR50Lee5c0usj1VAosChVsGoIDVMdRnalbj2t4pkUu9hnb@MBPQGhgrkgWpFVFv6IQGWO44dSDuoLDgaaXcANNA9U0YgSMvrPyI2CyT@gsrRaQS8hJ6E4IlbGMlSVQUN/3ljjEAzPE5HsK/TWkrCzZxNfEJ7@tDUm@e8p3XfOz/8rq9cmeDOEflOu/QD0Bj8exnv8A "C# (.NET Core) – Try It Online")
*-1 byte: changed for loop to while (thanks to [Skidsdev](https://codegolf.stackexchange.com/questions/176734/self-contained-powers/176756?noredirect=1#comment425615_176756))*
*-14 bytes: abused C#'s weird string handling to remove* `ToString()` *calls*
Need to use C#'s [BigInteger](https://docs.microsoft.com/en-us/dotnet/api/system.numerics.biginteger) library, as the standard numeric C# types (int, double, long, ulong, etc.) fail for some larger numbers (including 12, 15, and 17).
Ungolfed:
```
a => {
int i = 2; // initialize i
while( !(System.Numerics.BigInteger.Pow(a,i) + "") // n = a^i, convert to string
.Contains(a + "")) // if n doesn't contain a
i++; // increment i
return i;
}
```
[Answer]
# [Python 2](https://docs.python.org/2/), 47 bytes
```
i,e=input(),2
while`i`not in`i**e`:e+=1
print e
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P1Mn1TYzr6C0RENTx4irPCMzJzUhMyEvv0QhMy8hU0srNcEqVdvWkKugKDOvRCH1/39DAwA "Python 2 – Try It Online")
Inspired by @Gigaflop's [solution](https://codegolf.stackexchange.com/a/176751/82511).
[Answer]
# [Tcl](http://tcl.tk/), 69 ~~81~~ bytes
```
proc S n {incr i
while {![regexp $n [expr $n**[incr i]]]} {}
puts $i}
```
[Try it online!](https://tio.run/##JY5LioNgEIT33ylqIKusutX2cY4sxUUQSQTHESchAfHs5h9mVUW9qEc/Hcey/vS6aNY2zv2qkdd9nAZtX@063Ib3otOsNuGayPnc/oe6rtu17SzPx69O435M39flbwMnE7koRIhSVKKWaIQb7njyPccLPPASr/A6SQ2ZkQW5kQeFUQRhRFAaZVAZVVAbddAYTSqbkV5c0rH9@AA "Tcl – Try It Online")
[Answer]
PowerShell(V3+), 67 bytes
```
function f{param($n)$i=1;do{}until([math]::pow($n,++$i)-match$n)$i}
```
[Answer]
# Common Lisp, 78 bytes
```
(lambda(n)(do((e 2(1+ e)))((search(format()"~d"n)(format()"~d"(expt n e)))e)))
```
[Try it online!](https://tio.run/##TYsxCsMwFEOvIgwFmS5x9/Yubr5DDXG@cTx08tXTn9KhgwQS781r3uvBVbVi0YaMpWlBQFeEaYIoaH@JHR1uCO4PDBkXZyTNi@UpkZunKJlwY7giee/JPcU2v34yvbnOsP/J9K4d25c/c@SzPg)
[Answer]
# [J](http://jsoftware.com/), 26 bytes
```
2>:@]^:(0=[+/@E.&":^)^:_~]
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/jeysHGLjrDQMbKO19R1c9dSUrOI046zi6yqs/mtypSZn5CsYKdgqpCkYQjimYI4RsoyRKYRnDOaZQDiGhhBdKNrMDbj@AwA "J – Try It Online")
NOTE: I've changed the final `]` to `x:` in the TIO, to make the tests pass for larger integers.
[Answer]
# Oracle SQL, 68 bytes
```
select max(level)+1 from dual,t connect by instr(power(x,level),x)=0
```
There is an assumption that source number is stored in a table `t(x)`, e.g.
```
with t as (select 95 x from dual)
```
Test in SQL\*Plus
```
SQL> with t as (select 95 x from dual)
2 select max(level)+1 from dual,t connect by instr(power(x,level),x)=0
3 /
MAX(LEVEL)+1
------------
13
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 35 bytes
```
->n{(2..).find{"#{n**_1}"[n.to_s]}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3lXXt8qo1jPT0NPXSMvNSqpWUq_O0tOINa5Wi8_RK8uOLY2trIUqXFyi4RRuaxkJ4CxZAaAA)
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 19 bytes
```
J2R@?^jbxq~[_+fi2.+
```
[Try it online!](https://tio.run/##SyotykktLixN/V9dlPnfyyjIwT4uK6misC46Xjst00hP@39teM5/Qy4jLmMuEy5TLjMucy4LLksuQwMA "Burlesque – Try It Online")
```
J # Duplicate input
2R@ # Range (2..)
?^ # (in^2, in^3, ...)
j # Put input to head of stack
bx # Box
q~[ # Quoted contains
_+ # Push together (contains input)
fi # Find the index which contains input
2.+ # Add 2 (0-indexed and 1 dropped)
```
] |
[Question]
[
## Definitions
The **kth** ring of a square matrix of size **N**, where **1 ≤ k ≤ ceiling(N/2)** is the list formed by the elements of the **kth** and **(N-k+1)th** rows and columns, but without the first and last **k-1** elements.
Example:
```
Matrix:
1 2 3 4 5
6 7 8 9 1
8 7 6 5 4
3 2 1 9 8
7 6 5 4 3
Delimited in rings:
+-------------------+
| 1 2 3 4 5 |
| +-----------+ |
| 6 | 7 8 9 | 1 |
| | +---+ | |
| 8 | 7 | 6 | 5 | 4 |
| | +---+ | |
| 3 | 2 1 9 | 8 |
| +-----------+ |
| 7 6 5 4 3 |
+-------------------+
```
The first ring of the above is `1,2,3,4,5,1,4,8,3,4,5,6,7,3,8,6`, the second is `7,8,9,5,9,1,2,7` and the third is `6`.
An **N** by **N** matrix of positive integers is (for the purposes of this challenge):
* *concave* if all the integers on the **kth** ring are strictly greater than those on the **(k+1)th** ring, where **k** is any integer between **1** and **N** (those on the first ring are greater than those on the second, which are in turn greater than those on the third etc.). Example:
```
4 5 6 4 7 -> because 4,5,6,4,7,4,8,5,5,4,6,5,9,5,5,4 are all higher than
4 3 2 2 4 any of 3,2,2,3,2,3,3,2, which are all higher than 1
5 2 1 3 8
5 3 3 2 5
9 5 6 4 5
```
* *flat* if all the integers in the matrix are equal. Another example (perhaps redundant):
```
2 2 2 2
2 2 2 2
2 2 2 2
2 2 2 2
```
* *convex* if all the integers on the **kth** ring are strictly lower than those on the **(k+1)th** ring, where **k** is any integer between **1** and **N** (those on the first ring are lower than those on the second, which are in turn lower than those on the third etc.). Example:
```
1 2 1 -> because 1 and 2 are both lower than 6
2 6 2
1 2 1
```
* *mixed* if the matrix doesn't satisfy any of the above criteria. Example:
```
3 3 3 3 3
3 2 2 2 3
3 2 3 2 3
3 2 2 2 3
3 3 3 3 3
```
## Challenge
Given **a square matrix** of positive integers of **size at least 3**, classify it according to the definitions above. That is, output one of four different *consistent* values based on whether the matrix is concave, flat, convex or mixed.
You can compete in any [programming language](https://codegolf.meta.stackexchange.com/a/2073/59487) and can take input and provide output through any [standard method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) and in any reasonable format, while taking note that [these loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden by default. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest submission (in bytes) for *every language* wins.
## Test cases
Here's a bunch of examples for you to choose from – I selected 6 from each category.
**Concave**
```
[[3, 3, 3], [3, 1, 3], [3, 3, 3]]
[[2, 3, 4], [5, 1, 6], [7, 8, 9]]
[[19, 34, 45], [34, 12, 14], [13, 13, 13]]
[[3, 4, 3, 4], [4, 2, 1, 3], [3, 1, 2, 4], [4, 3, 4, 3]]
[[4, 5, 6, 4, 7], [4, 3, 2, 2, 4], [5, 2, 1, 3, 8], [5, 3, 3, 2, 5], [9, 5, 6, 4, 5]]
[[7, 7, 7, 7, 7], [7, 6, 6, 6, 7], [7, 6, 5, 6, 7], [7, 6, 6, 6, 7], [7, 7, 7, 7, 7]]
```
**Flat**
```
[[1, 1, 1], [1, 1, 1], [1, 1, 1]]
[[2, 2, 2], [2, 2, 2], [2, 2, 2]]
[[8, 8, 8], [8, 8, 8], [8, 8, 8]]
[[120, 120, 120], [120, 120, 120], [120, 120, 120]]
[[10, 10, 10, 10], [10, 10, 10, 10], [10, 10, 10, 10], [10, 10, 10, 10]]
[[5, 5, 5, 5, 5, 5], [5, 5, 5, 5, 5, 5], [5, 5, 5, 5, 5, 5], [5, 5, 5, 5, 5, 5], [5, 5, 5, 5, 5, 5], [5, 5, 5, 5, 5, 5]]
```
**Convex**
```
[[1, 2, 1], [2, 6, 2], [1, 2, 1]]
[[1, 1, 1], [1, 2, 1], [1, 1, 1]]
[[19, 34, 45], [34, 76, 14], [13, 6, 13]]
[[3, 3, 3, 3], [3, 4, 4, 3], [3, 4, 4, 3], [3, 3, 3, 3]]
[[192, 19, 8, 6], [48, 324, 434, 29], [56, 292, 334, 8], [3, 4, 23, 23]]
[[291, 48, 7, 5], [47, 324, 454, 30], [58, 292, 374, 4], [9, 2, 53, 291]]
```
**Mixed**
```
[[1, 2, 3], [4, 5, 9], [6, 7, 8]]
[[10, 14, 21], [100, 8, 3], [29, 2, 19]]
[[5, 5, 5, 5], [5, 4, 4, 5], [5, 4, 6, 5], [5, 5, 5, 5]]
[[3, 3, 3, 3], [3, 1, 2, 3], [3, 3, 2, 3], [3, 3, 3, 3]]
[[12, 14, 15, 16], [12, 18, 18, 16], [12, 11, 11, 16], [12, 14, 15, 16]]
[[5, 5, 5, 5, 5], [5, 4, 4, 4, 5], [5, 4, 6, 4, 5], [5, 4, 4, 4, 5], [5, 5, 5, 5, 5]]
```
[Answer]
# [Java (JDK 10)](http://jdk.java.net/), ~~247~~ ~~232~~ 220 bytes
```
x->{int i=0,j=x.length,k,m,M,p=0,P=0,r=0;for(;i<j;){for(M=m=x[k=i][--j];k<=j;)for(int q:new int[]{x[i][k],x[j][k],x[k][i],x[k++][j]}){m=m<q?m:q;M=M<q?q:M;}r=i++>0?(k=P<m?3:p>M?1:P==m?2:4)*r!=r*r?4:k:0;p=m;P=M;}return r;}
```
[Try it online!](https://tio.run/##tVbfj6IwEH5e/4rePsGKhlZAAbvmXu7NxGQfCQ@s4i7yQ0X0uBD@dq9Tq@jqbbZuLikyDJ1vOh9fpy6CXdBZzOL9avuaRFM0TYLNBo2DKENV6yHKijCfB9MQ/YJHeEZzhf16vueXqtt6qFuth00RFCz0F5ojui87zxVMi6iuLWjZTcLsrXjXYi3VxtqKOSfsyqnuzpe54kbDhatWYI5pSksvppHvdToL342HlL2CN4C2drLwN@KJq9Jjc2JfK72FuMc@c8G93faZs1arlKbD9Sh11u6Yjpm1dsZundOo3X7WR0pMJ8N01HNWz@MRdiaUpiPiGOpT/oPmT/nIcGJHd1c0dScUwsJim2cod@u9y6oVRImid8tohlJGl/JS5FH25vkoyN82Kqfr5c@mCNPuclt0V@xlkWTK488kQZv35TaZodcQTZfZNNiFSMGq8wh83oqZd@fKqXyWoKp6GoJRawhM3JjcW6tfRyI8xoBwkyNZYPY1NNCQLYWEbQZlMCyTr4VZmIFjDo1hlfySgoSVNetjJrkoFnPH8Z2YLJWABbCqLR7Zb3BIA2yekjJKhKN3nMQrtc8wTKnsjOVmCNqt4zhzmB8dlzPOMP6d/YPu5klQIIVIiQ5zHjD/ntempOhgQPgNUwZpwIXKP8wNU0q@RAfFHn54YZ87pLAh5nRxLHmPTEKTi6YZQrj/1/dl8bGmtwtLpPRk5UeE5gjXPxHyI7Lyu1Qv@YaQr3te3zrvedY9Le@yuRuird16uqfhYxsKtvkO4b3eYEaPADCsn9j82wK9MLEHvkGTnEDjkzxhbEYrJOkL4Rj9Y0ITauFaNwfHhH1DdF770GIhoY2/Lq40KsMZUow7tNUTJ4AJRx8zLb7mgfxWB6IOmtJ1TjRHJoeKsH3nVhabzhAnzenJutqQ31PcGRmnk@5biiMHSjD8wbAOnZRZA3E1HiyuxtNE3d39Lli7Is74ZMYVn3Wr3v8F "Java (JDK 10) – Try It Online")
Outputs:
* `1` for "concave"
* `2` for "flat"
* `3` for "convex"
* `4` for "mixed"
Ungolfed:
```
x -> { // lambda that takes in the input int[][]
int i = 0, // index of right bound of ring
j = x.length, // index of left bound of ring
k, // index of row-column-pair in ring
m, // minimum of ring
M, // maximum of ring
p = 0, // minimum of previous ring
P = 0, // maximum of previous ring
r = 0; // result
for (; i < j; ) { // iterate the rings from outside inwards
// set both min and max to be to top right corner of the ring (and sneakily set some loop variables to save space)
for (M = m = x[k = i][--j]; k <= j; ) // iterate the row-column pairs of the ring from top-right to bottom-left
for (int q : new int[] {x[i][k], x[j][k], x[k][i], x[k++][j]}) { // iterate all of the cells at this row-column pair (and sneakily increment the loop variable k)
// find new minimum and maximum
m = m < q ? m : q;
M = M < q ? q : M;
}
r = // set the result to be...
i++ > 0 ? // if this is not the first ring... (and sneakily increment the loop variable i)
// if the new result does not match the old result...
(k = P < m ? // recycling k here as a temp variable to store the new result, computing the result by comparing the old and new mins/maxes
3
: p > M ?
1
: P == m ?
2
: 4) * r != r * r ? // multiplying by r here when comparing because we want to avoid treating the case where r = 0 (unset) as if r is different from k
4 // set the result to "mixed"
: k // otherwise set the result to the new result
: 0; // if this is the first ring just set the result to 0
// set the old ring mins/maxes to be the current ones
p = m;
P = M;
}
return r; // return the result
}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~18 17~~ 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
I believe there is a lot of potential for this effort to be out-golfed
```
L‘HạŒỤṀ€IṠQṢ«FE$
```
A monadic link accepting a list of lists of numbers which returns a list of integers:
```
Concave -> [0, 0]
Flat -> [-1, 0, 1]
Convex -> [-1, 0]
Mixed -> [-1, 0, 0]
```
**[Try it online!](https://tio.run/##y0rNyan8/9/nUcMMj4e7Fh6d9HD3koc7Gx41rfF8uHNB4MOdiw6tdnNV@f//f3S0qY6CmY6CeayOAjZmLAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##tVSxTsQwDN3vKzLc2OHiJmnzASCQWJirjizofoDthJDYmZAQEiA2@IHCBuJDej9SbMdtmmvvJAak5M5x7Bf72e7lxXp91XVn2839Sfvx/HPXfr62zWZ7/X7aNk/nbfPy9XZ8tOy@b1HVNjdL/nvYbh5V11XVQqmqyjNFq84UiTqKrK0XKqsq4JOhC8s2jsQiU2WmvNhoj0YGrSz7o6TRTbOTJmTeYkxoERNFSJ7WrOjvxFhcUcQYHOuKaAHRxQ5wGKAo8t6Io/MjDCu4mE1ckp7r10hhdxWpxQgDcesskKw5Hs1cTMWBZFp0MSMGm5Ip56RmRCkErIj78MPPHFaIF52GzVZ/1wQoyyTFJSX4X11KNgjDwLUBIRsi2WkVYLYg044u3LijXdrQ6SAZadq5Uzpc2tPznmvIc2VQyIFc6E3wnC@lQYY56coIC9TWw5x6DJ/cC6HJFD2Upfe5ZrbsoQojE@PDaBCU11MqcxkzS9OOouMHynHnUCSBwtWKM2EfCMDaTzpDamhkBIeTm9R3H8Gj0Ibh3kMwhAA1fbtcGACUStlRo2VHTfSaae0kh0ka5oDFTt/Wvw "Jelly – Try It Online").
`L‘H` could be replaced with the less efficient but *[atomically](https://github.com/DennisMitchell/jellylanguage/wiki/Atoms)* shorter `JÆm`.
### How?
```
L‘HạŒỤṀ€IṠQṢ«FE$ - Link: list of (equal length) lists of numbers
L - length
‘ - increment
H - halve
- = middle 1-based index (in both dimensions as the input is square)
ŒỤ - sort multi-dimensional indices by their corresponding values
- = a list of pairs of 1-based indexes
ạ - absolute difference (vectorises)
- = list of [verticalDistanceToMiddle, horizontalDistanceToMiddle] pairs
Ṁ€ - maximum of €ach
- each = N/2-k (i.e. 0 as middle ring and N/2 as outermost)
I - incremental deltas (e.g. [3,2,2,3,1]->[3-2,2-2,3-2,1-3]=[-1,0,1,-2])
Ṡ - sign (mapping -n:-1; 0:0; and +n:1)
Q - de-duplicate
Ṣ - sort
- = concave:[0, 1]; convex:[-1, 0]; flatOrMixed:[-1, 0, 1]
$ - last two links as a monad
F - flatten
E - all equal? (1 if flat otherwise 0)
« - minimum (vectorises)
- = concave:[0, 0]; convex:[-1, 0]; mixed:[-1, 0, 0]; flat:[-1, 0, 1]
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~219~~ ~~216~~ ~~189~~ 176 bytes
```
def g(M):A=[sorted((M[1:]and M.pop(0))+M.pop()+[i.pop(j)for j in[0,-1]for i in M])for k in M[::2]];S={cmp(x[j],y[~j])for x,y in zip(A,A[1:])for j in[0,-1]};return len(S)<2and S
```
[Try it online!](https://tio.run/##tVRNj5swED2XX@FbQOuusPlmm0pRpd445WhxiDZsS7oLiNJV0qr966lncGLAJNkeGtnReHgznvGbmebQfa0rfjxuiyfyxc6cdLUU3@u2K7a2nQmW5ptqS7L7pm5s13Huesm5EyUKO@epbsmOlJVw6XuWw6mUJ5Ll@OUbyiJNeZ4/rJe/Hl8aey92OT2IP7sesqcHAP0sG3tFV3DjxOfvh7bofrQVeS4qe@184BDR@ti0ZdWRxae6ety8FgsLjDLwJIgQHiWwckpAZFpEbU4ton9CcNT7AAkQHYIYURJTkhholki4L/EB@pQSkw4YmjO4DbdhBjfoe6TIR4ExVJy@KbDhRCplhCF@jTSWa@Pg7FiGrxTeCYQRJwMfgXGDzFov9QzhaQ0UwVQxRgx85CRPrXc9XRldLD8uKBSaZaHKUjx@ft50ExIZ5sHwXU1xhkRYAJkRp@gYycUHmhENyrkLLPd/GMR1hWEP@vNG/L9rpk4DJEEvRfb/1b2NTNmUr8XepJMrDjnWCld08jk6x4zzG@SbPRmFw54ML7XkeFD4qu3mTpeGB0sguAQrB@eGLwWPgzHEwRN8R0gXgB7oYn0Bh8acmUiJTBMcRYoIPzo5DSAmrI8gPjmNfNX9Sd/m4DRhl8kas5WV@2I7S5anRkwAc1CKIQYUz9c3ZNOT5Lr4GmjN@5BYcqV@VaX5aiSdT6FRhbcpHAR@Hns3KeR9@Aymf9i3s5RitbWGqa012upqe44yNJL0ryDe0HvHvw "Python 2 – Try It Online")
Outputs `set([1]), set([0]), set([-1]),` or `False` for concave, flat, convex, or mixed, respectively.
Thx for: A whopping 27 bytes from a few optimizations by [ovs](https://codegolf.stackexchange.com/users/64121/ovs). And then *another* 13 bytes afterwards.
The list comprehension `A` (due to ovs) creates a list of the elements of each ring, sorted.
Next, we compare the `max` and `min` values between adjacent rings by looking at the `0`th and `-1`th elements of each sorted list in A. Note that if, for example, `M` is concave, `min` of each outer ring must be greater than `max` of the next inner-most ring; and it then follows that `max` of each outer ring will also be greater than `min` of the next inner-most ring.
If `M` is concave, flat, or convex, the set of these `min/max` comparisons will have only 1 element from `{-1, 0, 1}`; if it is mixed, there will be two or more elements.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes
```
ŒDŒH€ẎUÐeZ_þƝṠFf/
```
Returns **1** for *concave*, **0** for *flat*, **-1** for *convex*, and nothing for *mixed*.
[Try it online!](https://tio.run/##tVSxTsQwDN3vK/oBlTi7SdrsCCExM0B1YjoGdD/AysKG0O1IfAA/AAPL6fiP40eK7TpN0vaQGDglJ8exX@xnu3frzea@6/bb0/32/Pvh7fDxdLl7Xl/f7D6/Xg7vr2e3J93ukS5oXdC@6rqWflVZ8FqVBYsQRdGuykVRtC3K0fCNFSPHYl0WTVn4YASerAyZWUEgCcgPxAsYW3awZryISiJmr4Mowp0aB1@SKQwnyjqaYPSxAx7FqIoqGEl8PsGwAZgyiktTdGElCjtW5BYJBiMvCLkFCQeEjKkYeebFNzOiGjVCu2Q1I4Zi4JL57//kpd8VwY2Pwxazv2sUywpPcWkZ/leX8o1KMkpxUPnGhO@8EjhflGlf1y7tazdq63yijLbu3Gk0ZeA5Ai@FlAEzJFTIPvwqesmYU2HDinVNxEVu7jixnlJg/1qZMnXAshyB1M02Aas2Oji@nxDG8jBms9JZszz1JDqBb7Lm4Uh6FpdLyUScsMcFP20OLaPRSRxOblLioxwn0Q1Dfoxj7GME/o65fg5IanRHDeiOmug11@BZGpNMzC8WWfeufgA "Jelly – Try It Online")
[Answer]
# JavaScript (ES6), 168 bytes
Returns:
* `-1` for flat
* `0` for mixed
* `1` for convex
* `2` for concave
```
f=(a,k=w=~-a.length/2,p,P,i,m,M,y=w)=>k<0?i%4%3-!i:a.map(r=>r.map(v=>Y|(X=k*k-x*x--)<0&&X|Y<0||(m=v>m?m:v,M=v<M?M:v),x=w,Y=k*k-y*y--))|f(a,k-1,m,M,i|M-m<<2|2*(M<p)|m>P)
```
[Try it online!](https://tio.run/##tVVNb@IwEL3vr2APLQlyaOx80xgOK@0tUo9FVQ8RDd0sBBBFAaRo/zrrmRiSNA5lDyvZaDKeeTP2mxl@x3n8Mdumm52xWr8lp9OcazFZ8D3/Y8TDZbJ63/16YGRDnkhKMhKRI9/rfLwIzUl6Z99Zxvd0FA@zeKNt@XiLQs7H00J75ovBwjgMDoahh@b9/XMxDc2i0DKej7NJNspJxPMwmkSjXCcHvidTdDgOjsJBL@aQhUExZFpERhaGrGADLQo3epGNn/TTbL36WC@T4XL9rvV/rFezOE/6@uO3un6uvbxYpAfrlfRApJWI2lddb3kwPLPBzEEPF0SP9HzSC5QeNBAutvBxEFtIVIBQhKAQFbfSFSJV8YTIGklSVJzPpLESSByIbF208Cp7VgE4F3BxFamwzkaYeVDDcJRRxCtUSz6Le141hfNZ0bSoYUCURpj@z2W8UzFJMXmKj9oWO5iEBWYKUeXhI8v4OgpRyT0zge7yBxO6rlBiwNllo8@/a1TADjJRLcn6/9W1GRXtmSeHDk6ZJJJhhTDJKevitEk9u6EK2t3pufXudK81Z3N82LIBVV/XRgoNINEAywiniS0EiwEA5MMCfEi4PhhaoPOrIAxatGNWBeLaAOZJNmzvDOxAblgojn8G9mw5C4Ky6QE4oArGovSQvHUTZskB48BEFKKLCfjdxQ23KIkyTXwFRGBlGjT4onhlmdlyMF2@3FYJ3kZj7RKXAXgTjay8CoX/BbfsbSH5clcaKnelqby@7NPGbVsXtq9YNN/h9Bc "JavaScript (Node.js) – Try It Online")
## How?
### Minimum and maximum on each ring
We compute the minimum **m** and the maximum **M** on each ring.
We test whether a cell is located on a given ring by computing the squared distance from the center of the matrix on each axis. Taking the absolute value would work just as well, but squaring is shorter.
A cell at **(x, y)** is located on the **n**-th ring (0-indexed, starting from the outermost one) if the following formula is *false*:
```
((Y != 0) or (X < 0)) and ((X != 0) or (Y < 0))
```
where:
* **X = k² - (x - w)²**
* **Y = k² - (y - w)²**
* **w = (a.length - 1) / 2**
* **k = w - n**
**Example:** is the cell **(1, 2)** on the 2nd ring of a 6x6 matrix?
```
| 0 1 2 3 4 5 w = (6 - 1) / 2 = 2.5
--+------------ (x, y) --> ( x-w, y-w) --> ((x-w)²,(y-w)²)
0 | 0 0 0 0 0 0 (1, 2) --> (-1.5, -0.5) --> ( 2.25, 0.5)
1 | 0 1 1 1 1 0
2 | 0[1]0 0 1 0 k = w - 1 = 1.5
3 | 0 1 0 0 1 0 k² = 2.25
4 | 0 1 1 1 1 0 X = 2.25 - 2.25 = 0 / Y = 2.25 - 0.5 = 1.75
5 | 0 0 0 0 0 0 ((X != 0) or (Y < 0)) is false, so (1,2) is on the ring
```
### Flags
At the end of each iteration, we compare **m** and **M** against the minimum **p** and the maximum **P** of the previous ring and update the flag variable **i** accordingly:
* `i |= 1` if **m > P**
* `i |= 2` if **M < p**
* we set higher bits of **i** if **M != m**
At the end of the process, we convert the final value of **i** as follows:
```
i % 4 // isolate the 2 least significant bits (for convex and concave)
% 3 // convert 3 to 0 (for mixed)
- !i // subtract 1 if i = 0 (for flat)
```
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), ~~100~~ ~~71~~ 69 bytes
```
{$[1=#?,/a:(,/x)@.=i&|i:&/!2##x;;(&/m>1_M,0)-&/(m:&/'a)>-1_0,M:|/'a]}
```
[Try it online!](https://tio.run/##pVP/atswEP6/T3EjI7Mhni1Zki0f7fYCfYISWtMmJbRJoYTisnavnn36ZZuOwmCconzS3Xe6X34oDveH02nb/fp6Jc4XP1Zl32Wrcsh/fj/fLd923bL8IheLgTlblvsLcX25qvJiWWZ7aL71@UUhrqvVZfeGw/r9dHR@Xn8/d1sa@ObpgbObbb975IFf@Tlfv5@Vt0@H2/5lc3a8ymqCcE3C75CcxdopJA6KNRSGG2rJJoWwVCtSmrELSUKxAN2tZAGiJyuS0a8AcmevSWaKNBlcNF4hvYkOFGqBan@r2UY7nYgNRUFgxktAekTpLoonltvH/ugTwAuCZ3vOXRdzhvBsHzUtKtDybB81QlYUf/wJnmxxjIv/AY88TaPwf@Dgz3X/ZTOESqDayNQgX49zLmKTY3XkVKPi7/Y3Jrbf@O4Xqf1pqJRr9@w/DtjoCd4timlYtVRLWMGntKwRD3Q1Tq1nSwzCxJNWEAgNklNN4Gn4r1i3gdfgBlOD2QHPxtDL/W7Y3KWsa3bTZxlj4npZje3BY8i4qhBWzdI5ETbpp5K6hMK/mUqczKb8w0thjmf5x9fct0MCX5hhh1u/AhZ@BRxtPgQxhjEFoj7czcI6/QE "K (ngn/k) – Try It Online")
returns `1`=concave, `::`=flat, `-1`=convex, `0`=mixed
(`::` is used as a placeholder for missing values in k)
[Answer]
# [oK](https://github.com/johnearnest/ok), 56 bytes
```
&/1_`{&/+(y>|/x;y<&/x;,/x=/:y)}':{(,/x)@.=i&|i:&/!2##x}@
```
Based off of [ngn's answer](https://codegolf.stackexchange.com/a/165942/42775).
[Try it online!](https://tio.run/##pVLbbsIwDH3fV3hCKq12aXNtgreJP9mekBAPewUB396dOCmESZOmTU7dE8d2bJ/snj5307RZNb16/zg2/UN7eDv1ez68NNCP/f61Xx2683J1bLHp1s@v2@a0hfu9Xiz25/W0WbatJUeeLI1syZCGWHbQCrsAZMTqOBY/1921yWbYJB8WDJvGP0Uq8jxSoAibimQsWcfQCiktKwSlJUmshNh8maTTspcTePyltJGKoAgvkpG7oNlWJJWJjIorLe1AuNKwBbQVuNIpVg9UPv4BJy@AsvgXGBGOLsL/wNIdJoYePDoRXHWsq45rskZfyPIzVzPlNnFT/Wf6VUSuiKF4toGMxjny6MgO9@LMYBckToM0eTBREVxHFGzHHOGQc2AXcsQIC7gFw4iIqrRiOD2LyCAxE4CBISn6GAZcb1inEBWvM8Q8UrX576/zuekrp84v6qav9GxJ4V17TjjIyljJyrj41MyVe68322@2uY5u@gI "K (oK) – Try It Online")
```
concave:1 0 0
flat:0 0 1
convex:0 1 0
mixed:0 0 0
```
[Answer]
# [C++17 (gcc)](https://gcc.gnu.org/), 411 bytes
```
#import<map>
#define R return
#define T(f,s)X p,c;for(auto&e:r){c=e.second;if(p.a&&!p.f(c)){s;}p=c;}R
using I=int;struct X{I a=0;I z=0;I f(I n){R!a||n<a?a=n:0,n>z?z=n:0;}I
l(X x){R z<x.a;}I g(X x){R a>x.z;}I e(X x){R a==z&a==x.a&z==x.z;}};I
N(I i,I j,I s){i*=s-i;j*=s-j;R i<j?i:j;}auto C=[](auto&&m){I
s=size(m),i=-1,j;std::map<I,X>r;for(;++i<s;)for(j=-1;++j<s;)r[N(i,j,s-1)].f(m[i][j]);T(g,T(l,T(e,R 0)3)2)1;};
```
A new high score! (at the time of posting, at least) Oh well, it's a bit nifty, but still C++.
[Try it online!](https://tio.run/##tVVRj6JIEH7nV9TOJAZu0AiKCg3Owz75sPtg5mESz1xYbLzmBAzgrNHlr69X3aAooJN7ONONRfVX1V9VdTXedttde97p9MzCbZxkduhup9LzivosojCHhGa7JLoo3mRfTZV32Koe8eNEdndZ3KFWohw9h/ZS6sXRijBf3vbcTufLtufLnqIcU5JvHY/kc2mXsmgNM4dFGUmzZOdl8H6cgev0yQwO4unLM4iU4/yL@@tXZLuvrhNZfTWaHl4PXCL5TNrI77BHCBzsfc9FDazPGne67x24hl40jnPo4AORnQP/w@WczKTvuA9TZxDgTJUj@8NJu4wE/C8gc2B28MqsgOQ8RPjqLJZFsJ1QOc6k1EnZgcqhojKnq6kBBrOyLMydPVPfp4nIDXl5YXZKFC4HiML3gL8ni@8yUwM17WrKEjMULthyESwV8iav1Td5g5Oqc@grA0VXNJKTk/TMIm@zW1GwP6iXxcn0SsNiTCR1w2mZ3G@O4FIA7WsZkz6dEukjZivYJvgmY7nSDL51IFSkowT4E3gv3mVg2/C0eCJC@yOON@CzJM3@SuKf4ACWjhZLGB0UmQG@ZKErKFzxH/NBvtgplQvHdzcpJUDxWdtThXLT@3RqlOiGhjecbniBWLZAEKiY1ehxkHLl7xHBKxZNkty4Ws/vRLIsfeQtSV9a5wykP1nm/Q3yVzxoZ@6ei4Q0q2aDhfTcD/pn9ETgB56Gf0gF1lvAH3Tfih3Usf7GzVqR/ToyZHu6qkPx2nB3m6yOfa3jcimX8EBC6LJIPodanNHjcaACH7kKXNQqUWhzhdygdaEfcogh0CMujlWYqGA20JqJ8CHiDeETJQ0daMJc47uJ2TDjO1T7oKjfENOE4rxWghtOUIkMR2J1XGH1yti4OEb6pWJwBgnG5pUPo7EDRl2NMg2j87hSGHXFLeLKRyN/gp4m0tUUW2rDB4e0iHX0RNRMxN0iNpjofV684iFIPFY07Ln@MgX@v2vqTg2R22qUNfx/dS010svC6KKuelkjva1Gt2XUP6los3/Go@v@Gd1rn9umHpYt0vZ2r9E1k5MzxXEQPT5EYaBzY85DN0VyeLgcOOC6SbWBzpuo5fYwMUzuaFxmdzg@OzU4J1F0Y3J2Oh6WnWoWLcmdmtqdCgzKHjf4RYTiSOwyaT@JnGKR@X5fhCis9WIfzXxw0sozMSzvhMvbqHFePq/LFfHLvfNpXfSCvsav31HReChNyllptHJWmsrqYSPdRNgIcvgAUYs9P/328Au3Tk9d/EA53suLNv4X "C++ (gcc) – Try It Online")
Lambda `C` takes a `std::vector<std::vector<int>>` and returns 1 for concave, 2 for convex, 3 for flat, or 0 for mixed.
A more legible version of the code, with descriptive identifiers, comments, `R`->`return` and `I`->`int` written out, etc.:
```
#include <map>
// Abbreviation for golfing. Spelled out below.
#define R return
// Macro to test whether all pairs of consecutive Ranges in `rings`
// satisfy a condition.
// func: a member function of Range taking a second Range.
// stmts: a sequence of statements to execute if the condition is
// not satisfied. The statements should always return.
// May be missing the final semicolon.
// Expands to a statement, then the return keyword.
// The value after the macro will be returned if all pairs of Ranges
// satisfy the test.
#define TEST(func, stmts) \
Range prev, curr; \
for (auto& elem : rings) { \
curr = elem.second; \
// The first time through, prev.a==0; skip the test. \
if (prev.a && !prev.func(curr)) \
{ stmts; } \
prev = curr; \
} \
return
// Abbreviation for golfing. Spelled out below.
using I = int;
// A range of positive integers.
// A default-constructed Range is "invalid" and has a==0 && z==0.
struct Range
{
int a = 0;
int z = 0;
// Add a number to the range, initializing or expanding.
// The return value is meaningless (but I is shorter than void for golfing).
int add(int n) {
return !a||n<a ? a=n : 0, n>z ? z=n : 0;
/* That is:
// If invalid or n less than previous min, set a.
if (a==0 || n<a)
a = n;
// If invalid (z==0) or n greater than previous max, set z.
if (n>z)
z = n;
return dummy_value;
*/
}
// Test if all numbers in this Range are strictly less than
// all numbers in Range x.
int less(Range x)
{ return z < x.a; }
// Test if all numbers in this Range are strictly greater than
// all numbers in Range x.
int greater(Range x)
{ return a > x.z; }
// Test if both this Range and x represent the same single number.
int equal(Range x)
{ return a==z && a==x.a && z==x.z; }
};
// Given indices into a square matrix, returns a value which is
// constant on each ring and increases from the first ring toward the
// center.
// i, j: matrix indices
// max: maximum matrix index, so that 0<=i && i<=max && 0<=j && j<=max
int RingIndex(int i, int j, int max)
{
// i*(max-i) is zero at the edges and increases toward max/2.0.
i *= max - i;
j *= max - j;
// The minimum of these values determines the ring.
return i < j ? i : j;
}
// Takes a container of containers of elements convertible to int.
// Must represent a square matrix with positive integer values.
// Argument-dependent lookup on the outer container must include
// namespace std, and both container types must have operator[] to
// get an element. (So std::vector or std::array would work.)
// Returns:
// 1 for a concave matrix
// 2 for a convex matrix
// 3 for a flat matrix
// 0 for a mixed matrix
auto C /*Classify*/ = [](auto&& mat)
{
int mat_size=size(mat), i=-1, j;
std::map<int, Range> rings;
// Populate rings with the range of values in each ring.
for (; ++i<mat_size;)
for (j=-1; ++j<mat_size;)
rings[RingIndex(i, j, mat_size-1)].add(mat[i][j]);
// Nested macros expand to
// Range prev, curr; for ... if (...) {
// Range prev, curr; for ... if (...) {
// Range prev, curr; for ... if (...) {
// return 0;
// } return 3;
// } return 2;
// } return 1
// Note each scope declares its own prev and curr which hide
// outer declarations.
TEST(greater, TEST(less, TEST(equal, return 0) 3) 2) 1;
};
```
] |
[Question]
[
You are trying to fit a sphere into a 5-sided box, but sometimes it does not fit completely. Write a function to calculate how much of the sphere is outside (above the rim of) the box.
There are 3 possible situations:
* The sphere fits completely in the box. The answer will be 0.
* The sphere sits on the rim of the box. The answer will be more than half of the total volume.
* The sphere sits on the bottom of the box.
You can see each situation here:

You must write a program or function to compute this value to at least 4 significant digits.
Input: 4 non-negative real numbers in whatever format is convenient\* - width, length, depth of the box (interior measurements), and diameter of the sphere.
Output: 1 non-negative real number in a usable format\* - the total volume (not the percentage) of the sphere outside the box.
\* must be convertible to/from a decimal string
You are encouraged to limit your use of trigonometry as much as possible.
This is a popularity contest, so **think outside the box!**
[Answer]
## Forth
Please find, below, a sphere outside the box.
The "sphere" is the volume-computing function `f`. The reference test cases compose the "box".
```
( x y z d -- v )
: f { F: z F: d } d f2/
{ F: r } fmin { F: m } m f2/ {
F: b } d m f<= d z f<= and if 0e
else r r r f* b b f* f- fsqrt f-
{ F: t } d m f<= t z f> or if d
z f- else d t f- then r 3e f*
fover f- pi f* fover f*
f* 3e f/ then ;
1e 1e
1e 1e
f f.
cr 1e 1e 0e
1e f f. cr
1e 1e 0.5e 1e f f. cr 1e
0.999e 1e 1e f
f. cr 0.1e 1e
1.000e 0.500e f f. cr
```
Output:
```
0.
0.523598775598299
0.261799387799149
0.279345334323962
0.0654299441440212
```
[Answer]
## Java - integer based
This program does not use pi and does not call any external function - not even sqrt. It only uses simple arithmetic - `+`, `-`, `*` and `/`. Furthermore, other than a scaling step, it works exclusively with integers. It basically divides the sphere into little cubes and counts the ones that are outside the box.
```
public class Box {
private static final int MIN = 10000;
private static final int MAX = MIN * 2;
private static final int[] SQ = new int[MAX * MAX + 1];
static {
int t = 1;
for (int i = 1; i <= MAX; ++i) {
while (t < i * i) SQ[t++] = i - 1;
}
SQ[MAX * MAX] = MAX;
}
public static long outsideInt(int r, int w, int z) {
int r2 = r * r;
int o = z - r + 1;
if (w < r * 2) {
int t = 1 - SQ[r2 - w * w / 4];
if (t < o) o = t;
}
long v = 0;
for (int i = o; i <= r; ++i) {
int d = r2 - i * i;
int j0 = SQ[d];
v += 1 + 3 * j0;
for (int j = 1; j <= j0; ++j)
v += 4 * SQ[d - j * j];
}
return v;
}
public static double outside(double x, double y, double z, double d) {
double f = 1;
double w = x < y ? x : y;
double r = d / 2;
while (r < MIN) {
f *= 8;
r *= 2;
w *= 2;
z *= 2;
}
while (r > MAX) {
f /= 8;
r /= 2;
w /= 2;
z /= 2;
}
return outsideInt((int) r, (int) w, (int) z) / f;
}
public static void main(final String... args) {
System.out.println(outside(1, 1, 1, 1));
System.out.println(outside(1, 1, 0, 1));
System.out.println(outside(1, 1, 0.5, 1));
System.out.println(outside(1, 0.999, 1, 1));
System.out.println(outside(0.1, 1, 1, 0.5));
}
}
```
Output:
```
0.0
0.5235867850933005
0.26178140856157484
0.27938608275528054
0.06542839088004015
```
In this form, the program requires more than 2GB memory (works with `-Xmx2300m` here) and is prettty slow. It uses the memory to precalculate a bunch of square roots (arithmetically); it's not really necessary, but without that it would be a LOT slower. To improve both memory needs and speed, reduce the value of the `MIN` constant (that will decrease the accuracy though).
[Answer]
# Python 2 (Array-based approach)
It creates an array of arrays with truth-values if a specific square in that grid is inside the circle or outside the circle. It should get more precise the bigger the circle is you draw. It then selects either an area below or above a certain row and counts the amount of squares that belongs to the circle and divides that by the amount of squares that are in the entire circle.
```
import math as magic
magic.more = magic.pow
magic.less = magic.sqrt
def a( width, length, depth, diameter ):
precision = 350 #Crank this up to higher values, such as 20000
circle = []
for x in xrange(-precision,precision):
row = []
for y in xrange(-precision,precision):
if magic.less(magic.more(x, 2.0)+magic.more(y, 2.0)) <= precision:
row.append(True)
else:
row.append(False)
circle.append(row)
if min(width,length,depth) >= diameter:
return 0
elif min(width,length) >= diameter:
row = precision*2-int(precision*2*float(depth)/float(diameter))
total = len([x for y in circle for x in y if x])
ammo = len([x for y in circle[:row] for x in y if x])
return float(ammo)/float(total)
else:
#Why try to fit a sphere in a box if you can try to fit a box on a sphere
maxwidth = int(float(precision*2)*float(min(width,length))/float(diameter))
for row in xrange(0,precision*2):
rowwidth = len([x for x in circle[row] if x])
if rowwidth > maxwidth:
total = len([x for y in circle for x in y if x])
ammo = len([x for y in circle[row:] for x in y if x])
return float(ammo)/float(total)
```
[Answer]
## Python 2.7, Spherical Cap Formula
This version will throw a runtime warning in some cases, but still outputs the correct answer.
```
import numpy as n
x,y,z,d=(float(i) for i in raw_input().split(' '))
r=d/2
V=4*n.pi*r**3/3
a=n.sqrt((d-z)*z)
b=min(x,y)/2
h=r-n.sqrt(r**2-b**2)
c=lambda A,H: (3*A**2+H**2)*n.pi*H/6
print(0 if d<=z and r<=b else c(a,d-z) if r<=b and z>r else V-c(a,z) if r<=b or z<h else V-c(b,h))
```
For 11 characters more, I can get rid of the warning.
```
import math as m
x,y,z,d=(float(i) for i in raw_input().split(' '))
r=d/2
V=4*m.pi*r**3/3
if d>z:
a=m.sqrt((d-z)*z)
b=min(x,y)/2
h=r-m.sqrt(r**2-b**2)
c=lambda A,H: (3*A**2+H**2)*m.pi*H/6
print(0 if d<=z and r<=b else c(a,d-z) if r<=b and z>r else V-c(a,z) if r<=b or z<h else V-c(b,h))
```
Here are the test cases run on version 1:
```
$ python spherevolume.py
1 1 1 1
0
$ python spherevolume.py
1 1 0 1
0.523598775598
$ python spherevolume.py
1 1 .5 1
0.261799387799
$ python spherevolume.py
1 .999 1 1
0.279345334324
$ python spherevolume.py
.1 1 1 0.5
spherevolume.py:65: RuntimeWarning: invalid value encountered in sqrt
a=n.sqrt((d-z)*z) or b
0.065429944144
```
[Answer]
# Mathematica
Using numerical integration with proper limits.
```
f[width_, length_, height_, diam_] :=
With[{r = diam/2, size = Min[width, length]/2},
Re@NIntegrate[
Boole[x^2 + y^2 + z^2 < r^2], {x, -r, r}, {y, -r, r},
{z, -r, Max[-r, If[size >= r, r - height, Sqrt[r^2 - size^2]]]}]
]
```
[Answer]
## Reference Implementation - C#
```
using System;
namespace thinkoutsidethebox
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(OutsideTheBox(1, 1, 1, 1));
Console.WriteLine(OutsideTheBox(1, 1, 0, 1));
Console.WriteLine(OutsideTheBox(1, 1, 0.5, 1));
Console.WriteLine(OutsideTheBox(1, 0.999, 1, 1));
Console.WriteLine(OutsideTheBox(0.1, 1, 1, 0.5));
}
static double OutsideTheBox(double x, double y, double z, double d)
{
x = Math.Min(x, y);
double r = d / 2; // radius
double xr = x / 2; // box 'radius'
double inside = 0; // distance the sphere sits inside the box
if (d <= x && d <= z) // it fits
{
return 0;
}
else if (d <= x || r - Math.Sqrt(r * r - xr * xr) > z) // it sits on the bottom
{
inside = z;
}
else // it sits on the rim
{
inside = r - Math.Sqrt(r * r - xr * xr);
}
// now use the formula from Wikipedia
double h = d - inside;
return (Math.PI * h * h / 3) * (3 * r - h);
}
}
}
```
Output:
```
0
0.523598775598299
0.261799387799149
0.279345334323962
0.0654299441440212
```
[Answer]
# Ruby
Let's see...
If the box is fully inside, then width>diameter; length>diameter and height>diameter.
That should be the 1st check to run.
If it's sitting at the bottom, then w>d ; l>d and h
`V=(pi*h^2 /3)*(3r-h)` So in that case, We just get the height and run it through that.
If it's stuck, we use a similar formula (`V=(pi*h/6)*(3a^2 + h^2)`). In fact our earlier formula is based on this one! Essentially, we use that, and a is simply the smaller one of w and l. (hint, we can get height by doing `h=r-a`)
Now the code!
```
def TOTB(wi,le,hi,di)
if wi>=di and le>=di and hi>=di
res = 0
elsif wi>=di and le>=di
r = di/2
res = 3*r
res -= hi
res *= Math::PI
res *= hi*hi
res /= 3
else
r = di/2
if wi>le
a=le
else
a=wi
end #had issues with the Ternary operator on ruby 2.2dev
h = r-a
res = 3*a*a
res += h*h
res *= Math::PI
res *= h
res /= 6
end
res
end
```
Note\*\* I didn't test it too much, so an error may have crept in, if anyone notices one, do tell!
The math is solid though.
Shorter version:
```
v1 = ->r,h{(3*r -h)*Math::PI*h*h/3}
v2 = ->r,a{h=r-a;((3*a*a)+(h*h))*h*Math::PI/6}
TOTB = ->wi,le,hi,di{(di<wi&&di<le&&di<hi)?0:((di<wi&&di<le)?v1[di/2,hi]:v2[di/2,((wi>le)?le:wi)])}
```
(Now I know for sure that getting h for v2 is done differently, but I'll fix it later.
[Answer]
**c++**
```
#define _USE_MATH_DEFINES //so I can use M_PI
#include <math.h> //so I can use sqrt()
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
double w;
double l;
double d;
double sd;
double min_wl;
double pdbd;
double sl;
cin >> w >> l >> d >> sd;
min_wl = min(w, l);
if(sd <= min_wl)
{
pdbd = 0.0;
} else
{
pdbd = (sqrt((((sd/2)*(sd/2))-((min_wl/2)*(min_wl/2)))) + (sd/2));
}
sl = sd - d;
if(sd <= min(min_wl, d))
{
cout << 0;
return 0;
} else if((sl < pdbd) && (pdbd > 0.0)) //sits on lip of box
{
cout << (M_PI * (((sd/2) * pdbd * pdbd) - ((pdbd * pdbd * pdbd)/(3))));
return 0;
} else //sits on bottom of box
{
cout << (M_PI * (((sd/2) * sl * sl)-((sl * sl * sl)/(3))));
return 0;
}
return 0;
}
```
My code finds the volume of the solid of rotation of the graph of some portion of a half-circle. `pdbd` holds the linear distance of the projection of a point on the surface of the sphere that touches the lip of the box to the diameter of the sphere that, if extended, would be normal to the bottom of the box. The two expressions that contain `M_PI` are basically the anti-derivative of the integral of `pi * -(x^2)+2rx` with respect to x (where x is a measure of the length along the above mentioned diameter through the sphere and where r is the radius of the sphere) evaluated at either `pdbd` or the difference of the sphere diameter and the box depth depending on the particular case that occurs with the different dimensions.
] |
[Question]
[
Since Fibonacci numbers and sequences seems like a popular subject for code golf I thought that it might be a fun challenge to code golf with [Keith numbers](http://en.wikipedia.org/wiki/Keith_number).
So I propose a challenge that is to create a function that takes an integer and gives back a true or false depending on the number is a Keith number or not.
*More about Keith numbers*
>
> In recreational mathematics, a Keith number or repfigit number (short for repetitive Fibonacci-like digit) is a number in the following integer sequence:
> 14, 19, 28, 47, 61, 75, 197, 742, 1104, 1537, 2208, 2580, …
>
>
>
[Numberphile](http://youtu.be/uuMwz47LV_w) has a video explaining how to calculate a Keith number. But basically you take the digits of a number. Add them together and then take the last digits of the original number and add them to the sum of the calculation, rinse and repeat. And example to make it clear.
>
> **14**
> 1 + 4 = 5
>
> 4 + 5 = 9
>
> 5 + 9 = **14**
>
>
>
>
## Input
An integer.
## Output
True if the number is a Keith number. False if it's not..
[Answer]
## GolfScript (31 25 chars)
```
..[10base{.{+}*+(\}@*]?0>
```
Input as an integer on top of the stack. Output is 0 (false) or 1 (true). [Online demo](http://golfscript.apphb.com/?c=OzEwMCx7CgouLlsxMGJhc2V7LnsrfSorKFx9QCpdPzA%2BCgp9LHA%3D) which lists the Keith numbers up to 100.
[Answer]
## Python (~~78~~ 75)
```
a=input()
n=map(int,`a`)
while a>n[0]:n=n[1:]+[sum(n)]
print(a==n[0])&(a>9)
```
`n=n[1:]+[sum(n)]` does all the magic. It takes every item but the first item of `n`, sticks on the sum of `n` (with the first item), then sets that to `n`.
I wish you could call `list` on an integer and have the digits seperated.
Returns `False` on all inputs below 10. Can be 8 characters shorter if it returned `True`.
[Answer]
### GolfScript, 32 29 characters
```
...[10base\{.{+}*+(\}*]&,\9>&
```
A GolfScript implementation which can be tested [online](http://golfscript.apphb.com/?c=OzEwMCx7CgouLi5bMTBiYXNlXHsueyt9KisoXH0qXSYsXDk%2BJgoKfSxw&run=true). Input is given as top element on the stack and it returns 0 (i.e. false) or 1 respectively.
[Answer]
## APL, ~~36~~ ~~34~~ ~~39~~ ~~36~~ ~~33~~ ~~29~~ 27
```
*+/x={(∇⍣(⊃x>¯1↑⍵))⍵,+/⍵↑⍨-⍴⍕x}⍎¨⍕x←⎕
```
Output `1` if Keith, `0` otherwise
GolfScript strikes again!!
---
**Edit**
```
+/x={(∇⍣(x>⊢/⍵))⍵,+/⍵↑⍨-⍴⍕x}⍎¨⍕x←⎕
```
Using Right-reduction (`⊢/`) instead of Take minus 1 (`¯1↑`), directly saving 1 char and indirectly saves 1 from Disclose (`⊃`)
**Explanation**
`⍎¨⍕x←⎕` takes evaluated input (treated as a number) and assign it to `x`. Converts it to a character array (aka "string" in other languages), and loop through each character (digit), converting it to a number. So this results in a numerical array of the digits.
`{(∇⍣(x>⊢/⍵))⍵,+/⍵↑⍨-⍴⍕x}` is the main "loop" function:
`+/⍵↑⍨-⍴⍕x` takes the last `⍴⍕x` (no. of digits in `x`) numbers from the array and sums them.
`⍵,` concatenates it to the end of the array.
`(x>⊢/⍵)` check if the last number on the array (which doesn't have `+/⍵↑⍨-⍴⍕x` concatenated yet) is smaller than `x` and returns `1` or `0`
`∇⍣` executes this function on the new array that many times. So if the last number is smaller than `x`, this function recurs. Otherwise just return the new array
After the executing the function, the array contains the sums up to the point where 2 of the numbers are greater than or equal to `x` (e.g. `14` will generate `1 4 5 9 14 23`, `13` will generate `1 3 4 7 11 18 29`)
Finally check if each number is equal to `x` and output the sum of the resulting binary array.
---
**Edit**
```
1=+/x={(∇⍣(x>⊢/⍵))⍵,+/⍵↑⍨-⍴⍕x}⍎¨⍕x←⎕
```
Added 2 chars :-( to make output `0` if the input is one-digit
---
**Yet another edit**
```
+/x=¯1↓{(∇⍣(x>⊢/⍵))1↓⍵,+/⍵}⍎¨⍕x←⎕
```
**Explanation**
The function now drops the first number (`1↓`) from the array instead of taking the last `⍴⍕x` (`↑⍨-⍴⍕x`).
However, this approach makes `1=` not adequate to handle single digit numbers. So it now drops the last number from the array before checking equality to `x`, adding 1 char
---
**You guessed it: EDIT**
```
+/x=1↓{1↓⍵,+/⍵}⍣{x≤+/⍵}⍎¨⍕x←⎕
```
Compares `x` to the newly-added item instead of the old last item, so dropping the first (instead of last) item before checking equality to `x` is suffice, saving a minus sign.
Saves another 3 by using another form of the Power operator(`⍣`)
And a 25-char gs answer appears (Orz)
---
**Last edit**
```
x∊1↓{1↓⍵,+/⍵}⍣{x≤+/⍵}⍎¨⍕x←⎕
```
Can't believe I missed that.
Can't golf it anymore.
[Answer]
# Common Lisp, 134
CL can be quite unreadable at times.
```
(defun k(n)(do((a(map'list #'digit-char-p(prin1-to-string n))(cdr(nconc a(list(apply'+ a))))))((>=(car a)n)(and(> n 9)(=(car a)n)))))
```
Some formatting to avoid horizontal scrolling:
```
(defun k(n)
(do
((a(map'list #'digit-char-p(prin1-to-string n))(cdr(nconc a(list(apply'+ a))))))
((>=(car a)n)(and(> n 9)(=(car a)n)))))
```
Test:
```
(loop for i from 10 to 1000
if (k i)
collect i)
=> (14 19 28 47 61 75 197 742)
```
[Answer]
## F# - 184 chars
I hope it's ok that I'll participate in my own challenge.
```
let K n=
let rec l x=if n<10 then false else match Seq.sum x with|v when v=n->true|v when v<n->l(Seq.append(Seq.skip 1 x)[Seq.sum x])|_->false
string n|>Seq.map(fun c->int c-48)|>l
```
*Edit* Fixed a bug regarding small numbers.
[Answer]
# K, 55
```
{(x>9)&x=*|a:{(1_x),+/x}/[{~(x~*|y)|(+/y)>x}x;"I"$'$x]}
```
.
```
k)&{(x>9)&x=*|a:{(1_x),+/x}/[{~(x~*|y)|(+/y)>x}x;"I"$'$x]}'!100000
14 19 28 47 61 75 197 742 1104 1537 2208 2580 3684 4788 7385 7647 7909 31331 34285 34348 55604 62662 86935 93993
```
[Answer]
## PowerShell: 120 128 123 111 110 97
```
$j=($i=read-host)-split''|?{$_};While($x-lt$i){$x=0;$j|%{$x+=$_};$null,$j=$j+$x}$x-eq$i-and$x-gt9
```
`$i=read-host` takes input from the user, stores it in $i.
`$j=(`...`)-split''|?{$_}` breaks up the digits from $i into an array and stores it in $j.
>
> Thanks to [Rynant](https://codegolf.stackexchange.com/questions/9319/test-if-given-number-if-a-keith-number#comment28361_15243) for pointing out that `-ne''` is unnecessary.
>
>
>
`While($x-lt$i)` sets the following Fibonnaci-like loop to run until the sum variable, $x, reaches or exceeds $i.
`$x=0` zeroes out $x, so it's ready to be used for summing (necessary for when the loop comes back around).
`$j|%{$x+=$_}` uses a ForEach-Object loop to add up the values from $j into $x.
`$null,$j=$j+$x` shifts the values in $j left, discarding the first, while appending $x.
>
> Yay! I finally figured out a shorter way to do shift-and-append, and got this script under 100!
>
>
>
`$x-eq$i` after the while loop completes, tests if the sum value, $x, equals the initial value, $i - generally indicative of a Keith Number.
`-and$x-gt9` invalidates single-digit numbers, zero, and negative numbers, which cannot be Keith Numbers.
This script is a bit "messy". It can gracefully handle $i and $j being leftover, but you'll need to clear $x between runs.
>
> Thanks to [Keith Hill](https://stackoverflow.com/a/19963980/477682) and [mjolinor](https://stackoverflow.com/a/19964054/477682) for some methods of breaking numbers into digits which were used in earlier versions of this script. While they are not in the final version, they did provide for a great learning experience.
>
>
>
[Answer]
# [Husk](https://github.com/barbuz/Husk), 11 bytes
```
S£o¡oΣ↑_L¹d
```
[Try it online!](https://tio.run/##AR0A4v9odXNr//9TwqNvwqFvzqPihpFfTMK5ZP///zE5Nw "Husk – Try It Online")
Returns the iteration at which the Keith number is present, otherwise 0.
This challenge is perfect for Husk.
## Explanation
```
S£o¡oΣ↑_L¹d
¡o create an infinite list, starting with
d the digits of the input
↑_L¹ take length(input) numbers from the end
Σ and sum to compute the next number
S£o is the input present in the list?
```
[Answer]
## **Ruby, 82**
```
def keith?(x)
l="#{x}".chars.map &:to_i
0while(l<<(s=l.inject :+)).shift&&s<x
(s==x)&l[1]
end
```
Suspect Python's a better tool for this one.
[Answer]
## C, 123
```
k(v){
int g[9],i,n,s,t=v;
for(n=s=0;t;t/=10)s+=g[n++]=t%10;
for(i=n;s<v;){
i=(i+n-1)%n;
t=g[i];g[i]=s;s=s*2-t;
}
return n>1&&s==v;
}
```
test via harness:
```
main(i){
for(i=0;i<20000;i++)
if(k(i)) printf("%d ",i);
}
```
gives:
```
14 19 28 47 61 75 197 742 1104 1537 2208 2580 3684 4788 7385 7647 7909
```
[Answer]
## R, 116
Python rip-off:
```
a=scan();n=as.numeric(strsplit(as.character(a),"")[[1]]);while(a>n[1])n=c(n[-1],sum(n));if((n[1]==a)&&(a>9))T else F
```
[Answer]
## Perl, 90
```
sub k{$-=shift;$==@$=split//,$-;push@$,eval join'+',@$[-$=..-1]while@$[-1]<$-;grep/$-/,@$}
```
A fun exercise! I know it's an old post but I noticed perl was missing!
I'm sure I can improve the way I build this from digesting the other responses more thoroughly, so I'll likely revisit this!
[Answer]
# Smalltalk - 136 char
```
[:n|s:=n asString collect:[:c|c digitValue]as:OrderedCollection.w:=s size.[n>s last]whileTrue:[s add:(s last:w)sum].^(s last=n and:n>9)]
```
Send this block `value:`
[Answer]
# Python3 104
```
#BEGIN_CODE
def k(z):
c=str(z);a=list(map(int,c));b=sum(a)
while b<z:a=a[1:]+[b];b=sum(a)
return(b==z)&(len(c)>1)
#END_CODE score: 104
print([i for i in filter(k, range(1,101))]) #[14, 19, 28, 47, 61, 75]
```
And it is a function ;)
[Answer]
# Python - 116 chars
Not really an expert at codegolf, so there you have it- my first try.
```
x=input();n=`x`;d=[int(i)for i in n];f=d[-1]
while f<x:d+=[sum(d[-len(n):])];f=d[-1]
if f==x>13:print 1
else:print 0
```
Make 2 changes for a function:
* Change `print` to `return`
* Assign `x` to be the parameter
P.S. I second @beary605- add a built-in to separate the digits/characters/whatever.
] |
[Question]
[
Write a [Turing machine](https://en.wikipedia.org/wiki/Turing_machine) simulator.
For simplicity we can assume statuses as integer, symbols as char, blank symbol equals whitespace
5-tuple in the form of current state, input symbol, next state, output symbol, direction (left or right) the order is not mandatory but specify if you swap it
The machine must stop when an unknown state is reached, no other halt condition allowed.
The tape is infinite in both directions and you can always read an empty character.
Input: the initial tape, an initial state and a program. you are free to read the data from anywhere in the format you like
Output: the tape after the execution of the program
Required: an example program that run on top of your simulator
This is a code-colf so the shortest code win.
I'll post an implementation and some example programs in the next few hours.
[Answer]
# GNU sed with `-r` - 133 117 111 93 chars
Yes, sed is turing complete. GNU sed and `-r` (extended regexps) is only to save a few characters, it is only a small change to work with POSIX sed.
```
:s
s/^(.*@)(.*)>(.)(.*#\1\3([^@]*@)(..))/\5\2\6>\4/
T
s/(..)l>|r>/>\1/
s/>@/@> /
s/>#/> #/
bs
```
Input format is
```
[initial state]@[non-empty tape with > marking head position]#[state]@[input symbol][next state]@[output symbol][direction l or r]#...
```
The delimiters `@`, `#` and head character `>` cannot be used as a symbol on the tape. State labels cannot contain `@` `>` or `#`.
It will run all of the programs in the input, one per line
Examples:
Marco's anbn program
>
> Input
>
>
>
> ```
> 0@>aaabbb#0@a1@ r#0@ 4@ r#1@a1@ar#1@b1@br#1@ 2@ l#2@b3@ l#2@a5@al#3@b3@bl#3@a3@al#3@ 0@ r#4@ 5@Tr
>
> ```
>
> Output
>
>
>
> ```
> 5@ T> #0@a1@ r#0@ 4@ r#1@a1@ar#1@b1@br#1@ 2@ l#2@b3@ l#2@a5@al#3@b3@bl#3@a3@al#3@ 0@ r#4@ 5@Tr
>
> ```
>
>
Marco's Hello! program
>
> Input
>
>
>
> ```
> 0@> #0@ 1@Hr#1@ 2@er#2@ 3@lr#3@ 4@lr#4@ 5@or#5@ 6@!r
>
> ```
>
> Output
>
>
>
> ```
> 6@Hello!> #0@ 1@Hr#1@ 2@er#2@ 3@lr#3@ 4@lr#4@ 5@or#5@ 6@!r
>
> ```
>
>
[Answer]
So I'm a bit late, but just thought I would leave this here...
## Turing Machine Simulating a Turing Machine: 370 bytes?
Here I'm using the structure Turing used in his [1936 paper.](http://www.cs.virginia.edu/%7Erobins/Turing_Paper_1936.pdf) I'm using one symbol = one byte, including m-configs and operations.
```
╔═══════════════╦═══════╦═══════════════════╦═══════════════╗
║ m-config ║ Symbol ║ Operations ║ Final m-config ║
╠═══════════════╬═══════╬═══════════════════╬═══════════════╣
║ currentCommand ║ Any ║ L ║ currentCommand ║
║ ║ * ║ MR ║ readCommand ║
╠----------------╬--------╬---------------------╬----------------╣
║ nextCommand ║ Any ║ L ║ nextCommand ║
║ ║ * ║ E R R R P* R ║ readCommand ║
╠----------------╬--------╬---------------------╬----------------╣
║ readCommand ║ P ║ R ║ readCommandP ║
║ ║ M ║ R ║ readCommandM ║
║ ║ G ║ R ║ readCommandG ║
║ ║ E ║ R ║ MHPNone ║
╠----------------╬--------╬---------------------╬----------------╣
║ readCommandP ║ 0 ║ ║ MHP0 ║
║ ║ 1 ║ ║ MHP1 ║
║ ║ e ║ ║ MHPe ║
║ ║ x ║ ║ MHPx ║
║ ║ None ║ ║ MHPNone ║
╠----------------╬--------╬---------------------╬----------------╣
║ readCommandM ║ R ║ ║ MHMR ║
║ ║ L ║ ║ MHML ║
╠----------------╬--------╬---------------------╬----------------╣
║ readCommandG ║ 1 ║ ║ G2<1 ║
║ ║ 2 ║ ║ G2<2 ║
║ ║ 3 ║ ║ G2<3 ║
║ ║ 4 ║ ║ G2<4 ║
║ ║ 5 ║ ║ G2<5 ║
╠----------------╬--------╬---------------------╬----------------╣
║ G2<1 ║ int(1) ║ L P@ R R R P* R ║ GTS ║
║ ║ < ║ ║ G21 ║
║ ║ * ║ E L ║ G2<1 ║
║ ║ @ ║ E L ║ G2<1 ║
║ ║ Any ║ L ║ G2<1 ║
╠----------------╬--------╬---------------------╬----------------╣
║ G2<2 ║ int(2) ║ L P@ R R R P* R ║ GTS ║
║ ║ < ║ ║ G22 ║
║ ║ * ║ E L ║ G2<2 ║
║ ║ @ ║ E L ║ G2<2 ║
║ ║ Any ║ L ║ G2<2 ║
╠----------------╬--------╬---------------------╬----------------╣
║ G2<3 ║ int(3) ║ L P@ R R R P* R ║ GTS ║
║ ║ < ║ ║ G23 ║
║ ║ * ║ E L ║ G2<3 ║
║ ║ @ ║ E L ║ G2<3 ║
║ ║ Any ║ L ║ G2<3 ║
╠----------------╬--------╬---------------------╬----------------╣
║ G2<4 ║ int(4) ║ L P@ R R R P* R ║ GTS ║
║ ║ < ║ ║ G24 ║
║ ║ * ║ E L ║ G2<4 ║
║ ║ @ ║ E L ║ G2<4 ║
║ ║ Any ║ L ║ G2<4 ║
╠----------------╬--------╬---------------------╬----------------╣
║ G2<5 ║ int(5) ║ L P@ R R R P* R ║ GTS ║
║ ║ < ║ ║ G25 ║
║ ║ * ║ E L ║ G2<5 ║
║ ║ @ ║ E L ║ G2<5 ║
║ ║ Any ║ L ║ G2<5 ║
╠----------------╬--------╬---------------------╬----------------╣
║ G21 ║ int(1) ║ L P@ R ║ GTS ║
║ ║ Any ║ R ║ G21 ║
╠----------------╬--------╬---------------------╬----------------╣
║ G22 ║ int(2) ║ L P@ R ║ GTS ║
║ ║ Any ║ R ║ G22 ║
╠----------------╬--------╬---------------------╬----------------╣
║ G23 ║ int(3) ║ L P@ R ║ GTS ║
║ ║ Any ║ R ║ G23 ║
╠----------------╬--------╬---------------------╬----------------╣
║ G24 ║ int(4) ║ L P@ R ║ GTS ║
║ ║ Any ║ R ║ G24 ║
╠----------------╬--------╬---------------------╬----------------╣
║ G25 ║ int(5) ║ L P@ R ║ GTS ║
║ ║ Any ║ R ║ G25 ║
╠----------------╬--------╬---------------------╬----------------╣
║ GTS ║ ^ ║ R ║ TS ║
║ ║ Any ║ R ║ GTS ║
╠----------------╬--------╬---------------------╬----------------╣
║ TS ║ 0 ║ ║ RL0 ║
║ ║ 1 ║ ║ RL1 ║
║ ║ e ║ ║ RLe ║
║ ║ x ║ ║ RLx ║
║ ║ None ║ ║ RLNone ║
╠----------------╬--------╬---------------------╬----------------╣
║ RL0 ║ @ ║ R R ║ GTS0 ║
║ ║ Any ║ L ║ RL0 ║
╠----------------╬--------╬---------------------╬----------------╣
║ RL1 ║ @ ║ R R ║ GTS1 ║
║ ║ Any ║ L ║ RL1 ║
╠----------------╬--------╬---------------------╬----------------╣
║ RLe ║ @ ║ R R ║ GTSe ║
║ ║ Any ║ L ║ RLe ║
╠----------------╬--------╬---------------------╬----------------╣
║ RLx ║ @ ║ R R ║ GTSx ║
║ ║ Any ║ L ║ RLx ║
╠----------------╬--------╬---------------------╬----------------╣
║ RLNone ║ @ ║ R R ║ GTSNone ║
║ ║ Any ║ L ║ RLNone ║
╠----------------╬--------╬---------------------╬----------------╣
║ GTS0 ║ 0 ║ R P* R ║ readCommand ║
║ ║ Any ║ R ║ GTS0 ║
╠----------------╬--------╬---------------------╬----------------╣
║ GTS1 ║ 1 ║ R P* R ║ readCommand ║
║ ║ Any ║ R ║ GTS1 ║
╠----------------╬--------╬---------------------╬----------------╣
║ GTSe ║ e ║ R P* R ║ readCommand ║
║ ║ Any ║ R ║ GTSe ║
╠----------------╬--------╬---------------------╬----------------╣
║ GTSx ║ x ║ R P* R ║ readCommand ║
║ ║ Any ║ R ║ GTSx ║
╠----------------╬--------╬---------------------╬----------------╣
║ GTSNone ║ _ ║ R P* R ║ readCommand ║
║ ║ Any ║ R ║ GTSNone ║
╠----------------╬--------╬---------------------╬----------------╣
║ MHP0 ║ ^ ║ R ║ Print0 ║
║ ║ Any ║ R ║ MHP0 ║
╠----------------╬--------╬---------------------╬----------------╣
║ MHP1 ║ ^ ║ R ║ Print1 ║
║ ║ Any ║ R ║ MHP1 ║
╠----------------╬--------╬---------------------╬----------------╣
║ MHPe ║ ^ ║ R ║ Printe ║
║ ║ Any ║ R ║ MHPe ║
╠----------------╬--------╬---------------------╬----------------╣
║ MHPx ║ ^ ║ R ║ Printx ║
║ ║ Any ║ R ║ MHPx ║
╠----------------╬--------╬---------------------╬----------------╣
║ MHPNone ║ ^ ║ R ║ PrintNone ║
║ ║ Any ║ R ║ MHPNone ║
╠----------------╬--------╬---------------------╬----------------╣
║ MHMR ║ ^ ║ R R ║ MHR ║
║ ║ Any ║ R ║ MHMR ║
╠----------------╬--------╬---------------------╬----------------╣
║ MHML ║ ^ ║ L ║ MHL ║
║ ║ Any ║ R ║ MHML ║
╠----------------╬--------╬---------------------╬----------------╣
║ Print0 ║ ^ ║ R ║ Print0 ║
║ ║ None ║ P0 ║ nextCommand ║
║ ║ Any ║ E ║ Print0 ║
╠----------------╬--------╬---------------------╬----------------╣
║ Print1 ║ ^ ║ R ║ Print1 ║
║ ║ None ║ P1 ║ nextCommand ║
║ ║ Any ║ E ║ Print1 ║
╠----------------╬--------╬---------------------╬----------------╣
║ Printx ║ ^ ║ R ║ Printx ║
║ ║ None ║ Px ║ nextCommand ║
║ ║ Any ║ E ║ Printx ║
╠----------------╬--------╬---------------------╬----------------╣
║ Printe ║ ^ ║ R ║ Printe ║
║ ║ None ║ Pe ║ nextCommand ║
║ ║ Any ║ E ║ Printe ║
╠----------------╬--------╬---------------------╬----------------╣
║ PrintNone ║ ^ ║ R ║ PrintNone ║
║ ║ None ║ ║ nextCommand ║
║ ║ Any ║ E ║ PrintNone ║
╠----------------╬--------╬---------------------╬----------------╣
║ MHL ║ ^ ║ R R ║ MHL ║
║ ║ [ ║ ║ SBL ║
║ ║ Any ║ L P^ R R E ║ nextCommand ║
╠----------------╬--------╬---------------------╬----------------╣
║ MHR ║ ^ ║ R R ║ MHR ║
║ ║ ] ║ ║ SBR ║
║ ║ None ║ P^ L L E ║ nextCommand ║
╠----------------╬--------╬---------------------╬----------------╣
║ SBR ║ ] ║ E R R P] ║ currentCommand ║
╠----------------╬--------╬---------------------╬----------------╣
║ SBL ║ ] ║ R ║ SBLE ║
║ ║ Any ║ R ║ SBL ║
╠----------------╬--------╬---------------------╬----------------╣
║ SBLE ║ [ ║ ║ currentCommand ║
║ ║ None ║ L ║ SBLE ║
║ ║ Any ║ E R R P] L ║ SBLE ║
╚═══════════════╩═══════╩═══════════════════╩═══════════════╝
```
Here is one of Turing's examples from the paper above for my machine:
```
['<', None, 1, '0', None, 'P', 'e', None, 'M', 'R', None, 'P', 'e', None, 'M', 'R', None, 'P', '0', None, 'M', 'R', None, 'M', 'R', None, 'P', '0', None, 'M', 'L', None, 'M', 'L', None, 'G', '2',
'1', None, 'P', 'e', None, 'M', 'R', None, 'P', 'e', None, 'M', 'R', None, 'P', '0', None, 'M', 'R', None, 'M', 'R', None, 'P', '0', None, 'M', 'L', None, 'M', 'L', None, 'G', '2',
'e', None, 'P', 'e', None, 'M', 'R', None, 'P', 'e', None, 'M', 'R', None, 'P', '0', None, 'M', 'R', None, 'M', 'R', None, 'P', '0', None, 'M', 'L', None, 'M', 'L', None, 'G', '2',
'x', None, 'P', 'e', None, 'M', 'R', None, 'P', 'e', None, 'M', 'R', None, 'P', '0', None, 'M', 'R', None, 'M', 'R', None, 'P', '0', None, 'M', 'L', None, 'M', 'L', None, 'G', '2',
'_', None, 'P', 'e', None, 'M', 'R', None, 'P', 'e', None, 'M', 'R', None, 'P', '0', None, 'M', 'R', None, 'M', 'R', None, 'P', '0', None, 'M', 'L', None, 'M', 'L', None, 'G', '2',
None, 2, '1', None, 'M', 'R', None, 'P', 'x', None, 'M', 'L', None, 'M', 'L', None, 'M', 'L', None, 'G', '2',
'0', None, 'G', '3',
None, 3, '0', None, 'M', 'R', None, 'M', 'R', None, 'G', '3',
'1', None, 'M', 'R', None, 'M', 'R', None, 'G', '3',
'_', None, 'P', '1', None, 'M', 'L', None, 'G', '4',
None, 4, 'x', None, 'E', 'E', None, 'M', 'R', None, 'G', '3',
'e', None, 'M', 'R', None, 'G', '5',
'_', None, 'M', 'L', None, 'M', 'L', None, 'G', '4',
None, 5, '0', None, 'M', 'R', None, 'M', 'R', None, 'G', '5',
'1', None, 'M', 'R', None, 'M', 'R', None, 'G', '5',
'e', None, 'M', 'R', None, 'M', 'R', None, 'G', '5',
'x', None, 'M', 'R', None, 'M', 'R', None, 'G', '5',
'_', None, 'P', '0', None, 'M', 'L', None, 'M', 'L', None, 'G', '2',
None, '[', '^', None, ']', None]
```
[Try it online!](https://tio.run/##3Z1db9tGGkbv/StY@EKx4yw8X1jAqBdBu4J8QS0EpXeqLDjO68ZYV3JtZTuLor89S1Jf/OYZKjfbXAS2dd4Zzojn4ZCSqOf/rj@vlubr19PofrV8ePwluo7@GHwcXEV//Gu1lKtoNpjI4CIajKfp/4WfLw8/F/4SH/5fDeZ/XpycRod/yZ@StgdqkDa9LfPlsn1xsXbbwmVW@1u16d@ypi9zTW/@/62hIUXJ/VSow9Y9V/t/zvr3WavDYXf/kuv/ob3n/LzU9PzQMPIHPPIHsI3tpKfkfjZrd5dCwZ8nJ@XdcvB91s9Iq2waTnJbcP/l5UWW6x9Xv/56t/yUwpeHuSs9mGxZ1PZP9a7UvStN70rbu9L1rtztbr1q1RG1@ohac0StPaLWHVErR9T6I2oXR9ROj6iNj6idHFE7PqJ2dETt8Ija2RG18yNqb/vXFg9poR2f544yL3L3aV9YOhYsxTccCPKPtHanetToHjWmR43tUeN61BRCnlepXlW6V5XpVWV7VbleVdKryveqWvSqmvaqintVTXpVjXtVjXpVDXtVzXpVzXtV3fapKgYv7@y8ckJTOOk7P/zcFsj5x9Jl/KQ@yCdsPyiXjdmOUC4bsT1hM9ybSTqDbQOb5E/DbpLzm/bD2S4mb5Lzyg5SdqR0kX5H@g5yvzvkxlU/rHE2rG1G3CSz0bEJ8Y6M2yZrlLsQMNLfd06B3pG6izQ70nSRdkfaLtLtSFce02k0Wq1X0fruWaLPyfCih9VLNHu6@yhP8/zQszGWTmBr@8ytVVrmJbc6mbzvVnP004eGhjTqziDKIsohqrD0aOMU5DTkDOQs5BzkBHIecgvIjSE3gtwEcjHkppAbQq5wPOuiiwfNtmbfNzRbjNUsv/IpoFEK6O4UaKH0t8oKg7qziHKIKqeAhimgYQpomAIapoCGKaBhCmiYAhqmgIYpoGEKaJgCGqaAhimgYQrooBTQNAV0UAromhQwhRQwKAUMSgGDDvSmW/HjssKi7hyiyilgYAoYmAIGpoCBKWBgChiYAgamgIEpYGAKGJgCBqaAgSlgYAoYmAImKAUMTQETlAKmJgVsIQUsSgGLUsCiFLDoQG@7FT8uKxzqrpwCFqaAhSlgYQpYmAIWpoCFKWBhCliYAhamgIXWWpgWFqaFhSlgYQrYoBSwNAVsUArYmhRwhRRwKAUcSgGHUsChFHDoQO@6FT8uK8op4GAKOJgCDqaAgyngYAo4mAIOpoCDKeBgCjhot4N2O5gqDqaAgyngglLA0RRwQSnQdBWx9rph/rLh1o6mi4eXgGm4cthonAZtGsBYwDjAFN7n1EwpRGlEGURZRDlECaI8ohaIGiNqgqgRomJETRE1RNQ5ot5XXvBqZPcxcMBKr3ikV/iq@mqgr27Tt53RgYob0KYFjANMSV@N9NVIX4301UhfjfTVSF@N9NVIX4301UhfjfTVSF@N9NVIX4301QH6aqavrtHX1OhrgL4G6GvAEde0KcsVt6BNB5iSvgbpa5C@BulrkL4G6WuQvgbpa5C@BulrkL4G6WuQvgbpa5C@BulrAvQ1TF9To6@t0dcCfS3Q1wJ9LTji2jZlueIOtFnS1yJ9LdLXIn0t0tcifS3S1yJ9LdLXIn0t0tcifS3S1yJ9LdLXIn1tgL6W6Wtr9HU1@jqgrwP6OqCvA/o6cMR1bcpyxUv6OqSvQ/o6pK9D@jqkr0P6OqSvQ/o6pK9D@jqkr0P6OqSvQ/o6pK8L0Ncxfeuuacl688a41/XdWgpmJ3t4YnbeR3L9iZzAkhUwOYQyBxsphSiNKIMoiyiHKEGUR9QCUWNEjRA1QVSMqCmihoiaIeocUbc5qgkqKZpiZUXfpG/JPYt@Olia13Rj6XaPn8b172je7urTuP4i2XZfmsb1713e7kTTuP4Ny7shTOO6d1@fRlNZf3lZRutVFKeXzjfvvs1G8yEdTeFSejqAfehkB92mIeWvoDUyBjAWMA4whVe9mimFKI0ogyiLKIcoQZRH1BRRMaImiBojaoSoIaIWiJohao6oc0TdAqr4AlpzW@8rHytPYuyycqaQhk9ZbQXUVkBtBdRWQG2F1FZIbYXUVkhthdRWSG2F1FZIbYXUVkhthdRWSG2F1FZIbYXUVkhthdRWSG2F1FZIbRWitqpRWypqC1BbgNoC1BagtiC1BaktSG1BagtSW5DagtQWpLYgtQWpLUhtQWoLUluQ2oLUFqS2ILUFqS1IbUFqS4jaUqO2r6jtgdoeqO2B2h6o7ZHaHqntkdoeqe2R2h6p7ZHaHqntkdoeqe2R2h6p7ZHaHqntkdoeqe2R2h6p7ZHaHqntQ9T2NWpn5@tluzcn8Q2ftdWYNJi0mHSYLLnfzqoAVgewJoC1AawLYCWA9QHsNICNA9hJADsOYEcB7DCAXQSwswB2HsCeB7C3nC3HTXvDtaFTf0Ewex/t4QJgNKteB8yuIKTXNd8Xr7Retr81uJNTiNKIMoiyiHJslPnXNRpv69H6XvvOLjTkDOQs5BzkBHIecgvITSA3htwIcjHkppAbMq7yukQKll/7T68F1EiqoKQKSaqQpApJqpCkCkmqiKRtnOovs4ZdGMhZyDnICeQ85BaQm0BuDLkR5GLITSE3ZFxFUlUrqdRJKlBSQZIKklSQpIIkFSSpQEkFHjYFGinQSIFGCjRSiJGBYeNhFwvITSA3htwIcjHkppAbMq4iqdRK6usk9VBSjyT1SFKPJPVIUo8k9VBSDyX1UFIPJfVQUg8l9fCw6YmRgTIvYBcTyI0hN4JcDLkp5IaMq0jqayXdXTAre9p6alyxtZ1WAawOYE0AawNYFzITl0HzpoJoHUSbINoG0S6IliDaB9GL3klREwIdfY2D6FEQHQfR0yB6GEJXgmKLl69xjVf/2d5scr2Knl8el@todv/57mX/a@FyV3Yr0soXRDTfn7T49RAtnIacgZyFnIPcFHIx5CaQG0NOIDeD3BxyI8gNIecZpxClEWUQZRHl2CgXbJRFh9sazL@Dd5JaW31bW3Zv4Bp1FVRXQXUVVFdBdRVUV0F1FVRXQXUVVFdBdRVUV0F1FVRXQXUVVFchdRVSVyF1FVJXIXUVVFdRdRVWV9WpK3XqClRXoLoC1RWorkB1BaorUF2B6gpUV6C6AtUVqK5AdQWqK1BdQeoKUleQuoLUFaSuQHWFqitYXalT19ep66G6Hqrroboequuhuh6q66G6Hqrroboequuhuh6q66G6HqrroboeqeuRuh6p65G6Hqnrobqequuxur5O3f1ltMu6b@9Al4O6aR1EmyDaBtEuiJ4G0XEQPQmix0G0BNGzIHoeRI@C6GEQ7UNoFcDqANYEsDaAdSEzsQiZiUqCdDReyZHad5IVLrL9mv4y@@fji9yvH1fL3Z9K19nG09KH2lu@LkcjyiDKIsohqhSbzZyCnIacgZyFnIPcFHIx5CaQG0JuDLkR5DzkBHIzyM0ht2BcWfrmBm8rbx4d30xrVg7juGpvjOyNkb0xsjdG9sbQ3hjaG0N7Y2hvDO2Nob0xtDeG9sbQ3hjaG0N7Y2hvDO2Nob0xtDeG9sbQ3pjaG3fYu/ma8JvKV8qdTjYvf/3Y@PLX9tJ6ekZQd8W9/TMemzvhdLEqgBXOFr8pvfCNjaXw2l6DrB2jChijChijChij6vpcCGL386HQfEj9fEjAfEjAfEjAfEjAfHR/hmIiaD58/Xz4gPnwAfPhA@bDB8yH754Pj@Zjf6Gg4XwAzwr5ABjGJQz3QfhuhlrmZnPec5Oe9xzOd0rnOXF@2g7J3PJpxw8/xOBztJPb8ndCbAbW@WW1hU/Z9W9Fvkkr/lu0Uvx8FGqmsqCdVvbu3PK35UOnH36Ytm/UdnPiw/@dm3P64fPjwzr64eXu/t@ybtq10p7TbZ43fOfwZF73pfGlgaf7WtpIfmnTuf91UApRgqhbRM2L1LBjQmNJfhl6uf9SvNFeVto9pZtncdNP24lFTf0lq1dN9YrVS1O9sPrbpvpbVr/Zm8q7HvhykO2TlwP/PMn@fZKHzXI1@4Tim/RGiRfR8@r17Cpj0zuZPUePy@wOilf78qziTfJAUhx9d511FsnTq0SDKOlOlp@uB4OzzZ6yYc9yPydMdJ52Er1NpyThspu@RdfR4OPgJLtX43Wy5d8nLaUNX0TqIn3qd78lp0cX6VOx/32cfXoz8PHL5scRHzf/Pkp/14OWq/x/maHIX2co/q8zlMX/4VBOKul1EemLgiy1fXneV@g0XpZQ07CZJmyK9m11x8OxTZV3BNUxGbZhhLY40dnxa9h/s6Sj1KERoae3aUSux3Pmvt1z5npNTmhT/ts1tfiGabX9@yz9@@2Bm29/nJ@kL3g9re6TVcBlskD5@OWX5KefXr7ISWWlsiXPTp7uXjcPRJvVyMnvnx@ftneTTVco6dIt24DT7Rrk5@XPy6zgKlmNvN2Am0XKabKqWa7WUdbzVdTcZwq/ruX5NenzfrV8ePxlljUzn6XgbMvN5/uVVAqni6msaHb1Ts0PS6qk092w/3EdPcky6@0sehepq8KTkv75b8k5TrLIejPLFl5p04@7Rdr87CTfZtrV7HIeXV9nl5UrLe23MhlDxqrDuZA8lRoYlxrYbfDb60jtO1MbdjrYLAjfqWp7GZCsgts3J3sac0PZPB@FkvbnprhaHdQ/2/kd53CH8Nf9X9Jn6t12UvI7RpQsvXPF322rS2vk1m3bbld6s5DcZqWL4p/Xg/O/u@ht7WPLZMX89ev/AA "Python 3 – Try It Online") (Uses Python 3 as an interpreter) --Edit: I just checked the TIO, and it doesn't seem to actually work right... Try it on your local machine and it should (hopefully) work. It does on mine.
[Answer]
## APL (110)
(It's not even that short...)
```
0(''⍞){×⍴X←0~⍨⍺∘{x y S T s m t←⍺,⍵⋄S T≡x,⊃⊃⌽y:s,⊂(⊃y){m:(¯1↓⍺)(⍵,⍨¯1↑⍺)⋄(⍺,⊃⍵)(1↓⍵)}t,1↓⊃⌽y⋄0}¨⍵:⍵∇⍨⊃X⋄,/⊃⌽⍺}⎕
```
It reads two lines from the keyboard: the first is the program and the second is the initial tape.
The format is
```
(in-state in-tape out-state movement out-tape)
```
and they should all be on the same line. 'Movement' is 0 to move right and 1 to move left.
Example program (line breaks inserted for clarity, they should be all on one line.)
```
(0 ' ' 1 0 '1')
(0 '1' 0 0 '1')
(1 '1' 1 0 '1')
(1 ' ' 2 1 ' ')
(2 '1' 3 1 ' ')
```
The program adds two unary numbers together, for example:
```
in: 1111 111
out: 1111111
```
Example 2 (adapted from the binary increment program from Marco Martinelli's entry):
```
(0 '0' 0 0 '0')
(0 '1' 0 0 '1')
(0 ' ' 1 1 ' ')
(1 '0' 2 0 '1')
(1 '1' 3 1 '0')
(3 '0' 2 0 '1')
(3 ' ' 2 0 '1')
(3 '1' 3 1 '0')
```
[Answer]
## Python, 101 189 152 142
```
a=dict(zip(range(len(b)),b))
r=eval(p)
i=s=0
while 1:
c=a.get(i,' ')
s,m,a[i]=r[s,c]
if 0==m:exit([x[1]for x in sorted(a.items())])
i=i+m
```
b and p are the inputs, b is the initial tape, p encodes the rules as (string representation of) a dict from (in-state, in-tape) tuple to (out-state, head move, out-tape) tuple. If move is 0 the program finishes, 1 is move to the right and -1 is move to the left.
```
b="aaba"
p="""{(0, 'a'): (1, 1, 'a'),
(0, 'b'): (0, 1, 'b'),
(1, 'a'): (1, 1, 'a'),
(1, 'b'): (0, 1, 'b'),
(1, ' '): (1, 0, 'Y'),
(0, ' '): (0, 0, 'N')}"""
```
This sample program tests if the last letter of the string (before empty tape) is 'a', if so it writes 'Y' at the end of the string (first empty space).
**Edit 1:**
Changed the tape to be represented as a dict, as it seemed the shortest way to write an extensible data structure. The second to last line is mostly transforming it back into readable form for output.
**Edit 2:**
Thanks to Strigoides for a great deal of improvements.
**Edit 3:**
I had unnecessarily made it so 0 as output would leave the place as it is.
I removed this as we can always write the output the same as the input.
[Answer]
**Postscript ~~(205)~~ ~~(156)~~ ~~(150)~~ (135)**
```
<<
>>begin
/${stopped}def([){add dup{load}${exit}if}def
0 A{1 index{load}${pop( )}if
get{exec}${exit}if}loop
3{-1[pop}loop{1[print}loop
```
This is probably cheating, but the transition table contains code to perform the transitions. And since the tape is represented by a mapping from integers to integers, I've represented states as a mapping from names to dictionaries so the tape and the program coexist in the same anonymous dictionary.
Extra savings by making all state names executable, so they *auto*-load.
Ungolfed with embedded "Hello" program. ~~An extra 52 chars buys a loop to read the tape from stdin.~~ Run with `gsnd -q tm.ps`.
```
%!
<<
/A<<( ){dup(H)def 1 add B}>>
/B<<( ){dup(e)def 1 add C}>>
/C<<( ){dup(l)def 1 add D}>>
/D<<( ){dup(l)def 1 add E}>>
/E<<( ){dup(o)def 1 add F}>>
>>begin %ds: int-keys=tape name-keys=prog
0 A %pos state
{ %loop
1 index{load}stopped{pop( )}if %pos state tape(pos)
get {exec}stopped{exit }if %new-pos new-state
} loop
% Loop from tape position 0 to left until left tape end is found
0{ %pos
-1 add %new-pos
dup{load}stopped{exit}if %new-pos tape(new-pos)
pop %new-pos tape(new-pos)
}loop
% Move to the right and print all chars until right end is hit
{ %pos
1 add %new-pos
dup{load}stopped{exit}if %new-pos tape(new-pos)
print %new-pos tape(new-pos)
}loop
```
So the table-format is
```
/in-state<<in-tape{dup out-tape def movement add out-state}
in-tape2{dup out-tape2 def movement2 add out-state2}>>
```
where `in-state` is a name, `in-tape` and `out-tape` are chars (ie. integers, or expressions which yield integers), `movement` is `-1` for left or `1` for right, and `out-state` is an *executable* name. Multiple `in-tape` transition for the same state must be combined as above.
[Answer]
### GolfScript, 92 characters
```
~:m;n\+{:^.n?)>1<]m{2<1$=},.{~2>~^n/~1>[@\+]n*1$%n/~\1$1<+[\1>.!{;" "}*]n*\%@}{;;^0}if}do n-
```
The Turing machine in GolfScript became much longer than intended. Still playing around with different representations of the tape.
First line of the input is the original state, second line the initial tape, followed by an array of transitions (with order current state, input symbol, next state, direction, output symbol).
Example (also [available online](http://golfscript.apphb.com/?c=OyIwCicxMDEnCltbMCAnMCcgMCAxICcwJ10KIFswICcxJyAwIDEgJzEnXQogWzAgJyAnIDEgLTEgJyAnXQogWzEgJzAnIDIgMSAnMSddCiBbMSAnMScgMyAtMSAnMCddCiBbMyAnMCcgMiAxICcxJ10KIFszICcgJyAyIDEgJzEnXQogWzMgJzEnIDMgLTEgJzAnXV0iCgp%2BOm07blwrezpeLm4%2FKT4xPF1tezI8MSQ9fSwue34yPn5ebi9%2BMT5bQFwrXW4qMSQlbi9%2BXDEkMTwrW1wxPi4hezsiICJ9Kl1uKlwlQH17OzteMH1pZn1kbyBuLQ%3D%3D&run=true))
```
> 0
> '101'
> [[0 '0' 0 1 '0']
> [0 '1' 0 1 '1']
> [0 ' ' 1 -1 ' ']
> [1 '0' 2 1 '1']
> [1 '1' 3 -1 '0']
> [3 '0' 2 1 '1']
> [3 ' ' 2 1 '1']
> [3 '1' 3 -1 '0']]
110
```
[Answer]
**C (not golfed yet)**
I suppose I can't win with this, still it was fun getting it to work. This is even more true now that it really *does* work. :)
Except it's only infinite in one direction. I suppose it needs a negative tape, too. Sigh....
Negative wasn't so bad. We interleave the two sides as evens and odds. Complication is now it needs to display the tape in *sequential order*, as the file itself is now jumbled. This is a legitimate alteration to make, I think. Turing himself simplified this way.
```
#include<stdio.h>
int main(int c, char**v){
int min=0,max=0;
int pos=0,qi;sscanf(v[1],"%d",&qi);
FILE*tab=fopen(v[2],"r");
FILE*tape=fopen(v[3],"r+");
setbuf(tape,NULL);
do {
min = pos<min? pos: min;
max = pos>max? pos: max;
fseek(tape,(long)(abs(pos)*2)-(pos<0),SEEK_SET);
int c = fgetc(tape), qt=qi-1,qr;
fseek(tape,(long)(abs(pos)*2)-(pos<0),SEEK_SET);
char x = c==EOF?' ':c, xt=x-1,xr,d[2];
if (x == '\n') x = ' ';
printf("%d '%c' %d (%d)\n", qi, x, pos, (int)ftell(tape));
while((qt!=qi)||(xt!=x)){
fscanf(tab, "%d '%c' %d '%c' %1[LRN]", &qt, &xt, &qr, &xr, d);
if (feof(tab)){
goto HALT;
}
printf("%d '%c' %d '%c' %s\n", qt, xt, qr, xr, d);
}
qi=qr;
rewind(tab);
fputc(xr,tape);
pos+=*d=='L'?-1:*d=='R'?1:0;
} while(1);
HALT:
printf("[%d .. %d]:\n", min, max);
for (pos = min; pos <= max; pos++){
fseek(tape,(long)(abs(pos)*2)-(pos<0),SEEK_SET);
//printf("%d ",pos);
putchar(fgetc(tape));
//puts("");
}
return qi;
}
```
And here's the test-run:
```
522(1)04:33 AM:~ 0> cat bab.tm
0 'a' 0 'b' R
0 'b' 0 'a' R
523(1)04:33 AM:~ 0> echo aaaaa > blank; make tm ; tm 0 bab.tm blank; echo; cat blank
make: `tm' is up to date.
0 'a' 0 (0)
0 'a' 0 'b' R
0 'a' 1 (2)
0 'a' 0 'b' R
0 'a' 2 (4)
0 'a' 0 'b' R
0 ' ' 3 (6)
0 'a' 0 'b' R
0 'b' 0 'a' R
[0 .. 3]:
bbbÿ
babab
```
The program outputs the tape in sequential order, but the file represents the negative and positive sides interleaved.
[Answer]
# Groovy ~~234~~ ~~228~~ ~~154~~ ~~153~~ ~~149~~ ~~139~~ 124
```
n=[:];i=0;t={it.each{n[i++]=it};i=0};e={p,s->a=p[s,n[i]?:' '];if(a){n[i]=a[1];i+=a[2];e(p,a[0])}else n.sort()*.value.join()}
```
Formatted for readability
```
n=[:];
i=0;
t={it.each{n[i++]=it};i=0};
e={p,s->
a=p[s,n[i]?:' '];
if(a){
n[i]=a[1];
i+=a[2];
e(p,a[0])
}else n.sort()*.value.join()
}
```
t is the function that set the tape
e is the function that evaluate the program
Example 1 - Print "Hello!" on the tape :)
```
t('')
e([[0,' ']:[1,'H',1],
[1,' ']:[2,'e',1],
[2,' ']:[3,'l',1],
[3,' ']:[4,'l',1],
[4,' ']:[5,'o',1],
[5,' ']:[6,'!',1]],0)
```
Example 2 - Leave a T on the tape if the initial string is in the form of anbn, stop otherwise.
```
t('aaabbb')
e([[0,'a']:[1,' ',1],
[0,' ']:[4,' ',1],
[1,'a']:[1,'a',1],
[1,'b']:[1,'b',1],
[1,' ']:[2,' ',-1],
[2,'b']:[3,' ',-1],
[2,'a']:[5,'a',-1],
[3,'b']:[3,'b',-1],
[3,'a']:[3,'a',-1],
[3,' ']:[0,' ',1],
[4,' ']:[5,'T',1]],0)
```
Example 3 - Increment of a binary number
```
t('101')
e([[0,'0']:[0,'0',1],
[0,'1']:[0,'1',1],
[0,' ']:[1,' ',-1],
[1,'0']:[2,'1',1],
[1,'1']:[3,'0',-1],
[3,'0']:[2,'1',1],
[3,' ']:[2,'1',1],
[3,'1']:[3,'0',-1]],0)
```
in the examples 1 means move to the right and -1 means move to the left
] |
[Question]
[
If \$R\$ runners were to run a race, in how many orders could they finish such that exactly \$T\$ runners tie?
### Challenge
Given a positive integer \$R\$ and a non-negative integer \$0\leq T\leq {R}\$ produce the number of possible finishing orders of a race with \$R\$ runners of which \$T\$ tied.
Note, however, that runners that tie do not necessarily all tie with each other.
---
You may accept the number of runners that did not tie, \$R-T\$, in place of either \$R\$ or \$T\$ if you would prefer, just say so in your answer. You may also accept just \$R\$ and output a list of results for \$0\leq T \leq R\$.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so try to make the shortest code in bytes in your language of choice.
---
### Examples
#### 1. \$f(R=5, T=0)=120\$
No runners tied and the five runners could have finished in any order, thus \$f(R=5, T=0)=R!=5!=120\$
#### 2. \$f(R=5, T=1)=0\$
There are zero ways for exactly one runner to have tied since ties involve at least two runners.
#### 3. \$f(R=4, T=2)=36\$
* The first two tied - `** * *` - \$\binom{4}{2}\binom{2}{1}\binom{1}{1}=6\times 2\times 1=12\$ ways:
+ `AB C D` `AB D C`
`AC B D` `AC D B`
`AD B C` `AD C B`
`BC A D` `BC D A`
`BD A C` `BD C A`
`CD A B` `CD B A`
* The middle two tied - `* ** *` - \$\binom{4}{1}\binom{3}{2}\binom{1}{1}=4\times 3\times 1=12\$ ways:
+ `A BC D` `A BD C` `A CD B`
`B AC D` `B AD C` `B CD A`
`C AB D` `C AD B` `C BD A`
`D AB C` `D AC B` `D BC A`
* The last two tied - `* * **` - \$\binom{4}{1}\binom{3}{1}\binom{2}{2}=4\times 3\times 1=12\$ ways:
+ `A B CD` `A C BD` `A D BC`
`B A CD` `B C AD` `B D AC`
`C A BD` `C B AD` `C D AB`
`D A BC` `D B AC` `D C AB`
#### 4. \$f(R=5, T=5)=21\$
* All five runners tied - `*****` - \$\binom{5}{5}=1\$ way
* The first two and the last three tied - `** ***` - \$\binom{5}{2}\binom{3}{3}=10\times 1=10\$ ways:
+ `AB CDE` `AC BDE` `AD BCE` `AE BCD` `BC ADE` `BD ACE` `BE ACD` `CD ABE` `CE ABD` `DE ABC`
* The first three and the last two tied - `*** **` - \$\binom{5}{3}\binom{2}{2}=10\times1=10\$ ways:
+ `ABC DE` `ABD CE` `ABE CD` `ACD BE` `ACE BD` `ADE BC` `BCD AE` `BCE AD` `BDE AC` `CDE AB`
### Test cases
```
R,T => f(R,T)
1,0 => 1
1,1 => 0
2,0 => 2
2,1 => 0
2,2 => 1
3,0 => 6
3,1 => 0
3,2 => 6
3,3 => 1
4,0 => 24
4,1 => 0
4,2 => 36
4,3 => 8
4,4 => 7
5,0 => 120
5,1 => 0
5,2 => 240
5,3 => 60
5,4 => 100
5,5 => 21
7,5 => 5166
```
As a table, with `x` if the input does not need to be handled (all of them would be zero):
```
T R: 1 2 3 4 5 6 7
0 1 2 6 24 120 720 5040
1 0 0 0 0 0 0 0
2 x 1 6 36 240 1800 15120
3 x x 1 8 60 480 4200
4 x x x 7 100 1170 13440
5 x x x x 21 372 5166
6 x x x x x 141 3584
7 x x x x x x 743
```
---
### Isomorphic problem
This is the same as \$a(n=R,k=R-T)\$ which is given in [A187784](https://oeis.org/A187784) at the Online Encyclopedia of Integer Sequences as *the number of ordered set partitions of \$\{1,2,\dots,n\}\$ with exactly \$k\$ singletons*.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~26~~ 24 bytes
```
xt:Z^!"@tufm?@&=sqz1G=vs
```
Inputs `T`, then `R`. The code takes a while for `R≥5`.
[Try it online!](https://tio.run/##y00syfn/v6LEKipOUcmhpDQt195Bzba4sMrQ3bas@P9/Iy4TAA) You can also see the examples: [1](https://tio.run/##y00syfn/v6LEKipOUcmhpDQt195Bzba4sMrQ3bas@P9/Ay5TAA), [2](https://tio.run/##y00syfn/v6LEKipOUcmhpDQt195Bzba4sMrQ3bas@P9/Qy5TAA), [3](https://tio.run/##y00syfn/v6LEKipOUcmhpDQt195Bzba4sMrQ3bas@P9/Iy4TAA), [4](https://tio.run/##y00syfn/v6LEKipOUcmhpDQt195Bzba4sMrQ3bas@P9/Uy5TAA). Or [verify test cases for `R≤4`](https://tio.run/##y00syfmf8L@ixCoqTlHJoaQ0LdfeQc22uLDK0N22rPh/bKxLVEXIfwMuQzA04DICkkZgaMBlDGQbA1nGYGjAZQLkmwD5JkCeCQgCAA).
### Explanation
The program consists of three major steps:
1. Generate all tuples of length `R` containing (possibly repeated) numbers from the set `[1, 2, ..., R]`.
2. Keep only those tuples such the tuple contains all numbers `[1, 2, ..., u]`, where `u` is the number of distinct elements in the tuple. So `[1 2 1]` would be kept, whereas `[1 3 1]` or `[2 3 2]` would be rejected.
3. For each tuple that survived the previous step, count how many of its `R` entries are equal to some other entry. Let this count be `e`. The output of the program is the amount of tuples for which `e` equals `T`.
[Answer]
# JavaScript (ES6), 88 bytes
Expects `(t)(r)`.
```
t=>F=(r,q=r-t,p=1,v=0)=>q|r?v+r&&F(r,q,p,--v)+F(r+v,q-!~v,(g=_=>v?(~r-v)/v++*g():p)()):p
```
[Try it online!](https://tio.run/##Zc9LboMwEIDhPaeYbiK7DMHmlaqVyaq5BEIVooG2igI4yKsqV6eEMjgoGyQ@z/yWfwpTXEr93fbeufk8DpUaepUeFNPYKe312CqJRgmu0u5X742rN5vD7RBb9DzD3fHHNdh5T1eDrFYfKjV7dtXjkW9c97lm/LXljI/f4S1zADKQCAJyBN8HSSBnEBMEdiIgeJgIVo3QriQE65XQriwT4aoR3V0bkawjkY2ECQlVXgiiGXYTxHfvDQTRuhvbbhAtROFkESpLsVBMe/@P2E0CN4llkji5s60a/V6UX4xlGqHPOagUyuZ8aU7H7ampZ0aoWM@Z5pwPfw "JavaScript (Node.js) – Try It Online")
### Algorithm
Starting with \$q=r-t\$ and \$p=1\$, we recursively look for all ordered integer partitions of \$r\$. Whenever a new term \$v\$ is added to a given partition \$P\$ of \$r\$:
* we multiply \$p\$ by the number of ways to choose \$v\$ racers among the remaining ones: $$p\gets p\times\binom{r}{v}$$
* we subtract \$v\$ from \$r\$
* we decrement \$q\$ if \$v=1\$
Once a valid partition \$P\$ is complete (ending with \$r=0\$), we test whether we also have \$q=0\$, meaning that there are \$r-t\$ singletons in the finishing order of the race, i.e. \$t\$ ties. If so, we add the product \$p\$ to the final result. Otherwise, we ignore this partition.
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 46 bytes
```
f(r,t)=Vec(r!/(2-exp(x+O(x^t++))+x)^r-=t-2)[t]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=Nc0xCsJAEEbhs9jNsDNKUqVwz2BnI0aCZGULZRh-Ye6SJo14Jm-TgHqA773pbYPXy83m-fVE0e6zLeQCzsfxSr7ZUatjGEU6UPRIiTkF964Z2vIJ558S8_qA0X2A16BOBOJSC2GfXdakNgJtWIKZv-Z_XAA)
[Answer]
# [R](https://www.r-project.org), 105 bytes
(or 91 bytes in in R≥4.1 by exchanging `function` for `\`)
```
function(r,n)sum(apply(expand.grid(rep(list(1:r),r)),1,function(v)all(1:max(v)%in%v,sum(table(v)<2)==n)))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RY5BCsIwEEX3PUU2hRlIxbpRS3uYaBsZSKdhmpaKeBI3VfBQ3sZIRVd_mM9__9_uMj9s9RyCzXYvsgMfA3UMohn7oQXjvTtDM3nD9eokVIM0Hhz1AfJCUAuizvUvNqJxLjqtmeKdEqej_mCCObgmfsoNVhUj4rdwbzsBUcQqL7Z4SZTyQhygX3rXhfzZAW2cJVmI8eS6AOZ50Tc)
Input is `r`=runners, `n`=non-tied finishers.
Port of [Luis Mendo's answer](https://codegolf.stackexchange.com/a/259236/95126): upvote that one!
---
# [R](https://www.r-project.org) + `partitions`, 95 bytes
(or 81 bytes in R≥4.1 by exchanging `function` for `\`)
```
function(r,n)sum(apply(partitions::setparts(r),2,function(v)prod((sum(table(v)<2)==n):max(v))))
```
[Try it at rdrr.io](https://rdrr.io/snippets/embed/?code=f%3D%0Afunction(r%2Cn)sum(apply(partitions%3A%3Asetparts(r)%2C2%2Cfunction(v)prod((sum(table(v)%3C2)%3D%3Dn)%3Amax(v))))%0A%0Afor(r%20in%201%3A7)%7B%0A%20%20print(sapply(0%3Ar%2Cfunction(t)f(r%2Cr-t)))%0A%7D)
Input is `r`=runners, `n`=non-tied finishers.
Lazily uses `partitions` library to gather all set partitions, selects those with `n` singleton sets, and sums the factorials of the number of sets in each partition to account for the number of possible orders.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~21~~ 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
LZãʒÐêāQi¢≠OQ]g
```
-6 bytes by porting [*@LuisMendo*'s MATL answer](https://codegolf.stackexchange.com/a/259236/52210), so make sure to upvote him as well!
Inputs in the order \$R,T\$.
[Try it online](https://tio.run/##ASQA2/9vc2FiaWX//0xaw6PKksOQw6rEgVFpwqLiiaBPUV1n//80CjI) or [verify all test cases](https://tio.run/##AUUAuv9vc2FiaWX/NcOdw6Pigqx7w63DqsKmdnk/IiDihpIgICI/eWBVIv9MWsOjypLDkMOqxIFRacKi4omgT1hRXWf/Ii5WLP8).
**Original 21 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) answer:**
```
Lœ€.œ€`€€{Ùʒ€g1ÝKOQ}g
```
Inputs in the order \$R,T\$.
Brute-force, so pretty slow.
[Try it online](https://tio.run/##yy9OTMpM/f/f5@jkR01r9MBkAhADUfXhmacmAel0w8Nzvf0Da9P//zfhMvqvq5uXr5uTWFUJAA) or [verify all test cases](https://tio.run/##yy9OTMpM/W96eO7hxY@a1lQfXnt41aFlZZX2SgqP2iYpKCjZVyaE/vc5OhkoqQcmE4AYrHLmqUlAOt3w8Fxv/4jA2vT/Ov//6@rm5evmJFZVAgA).
**Explanation:**
```
L # Push a list in the range [1, first (implicit) input-integer R]
Zã # Get the cartesian power of R, creating all possible lists of length R using
# items of the [1,R]-ranged list, including duplicates
ʒ # Filter this list of lists by:
Ð # Triplicate the current list
ê # Uniquify and sort the top list
ā # Push a list in the range [1,length] (without popping the list)
Q # Check if the top two lists are equal
i # If this is truthy:
¢ # Pop the remaining two lists, and get the count of each integer
≠ # Check for each count whether it's NOT equal to 1
O # Sum the amount of non-1 counts together
Q # Check if this is equal to the second (implicit) input-integer T
# (implicit else: use the current list we've triplicated - which is falsey)
] # Close both the if-statement and filter
g # Pop and push its length to get the amount of remaining valid lists
# (which is output implicitly as result)
```
```
L # Push a list in the range [1, first (implicit) input-integer R]
œ # Get all permutations of this list
€ # Map over each permutation:
.œ # Get all partitions of this permutation
€` # Flatten it one level down to a list of partitions
€ # Map over each partition:
€ # Inner map over each part in this partition:
{ # Sort the integers in the current part
Ù # After the nested map, uniquify the list of partitions with sorted parts
ʒ # Filter the list of partitions by:
€g # Get the length of each part
1Ý # Push pair [0,1]
K # Remove all 0s and 1s from the list of lengths
O # Sum the remaining lengths (of >=2) together
Q # Check whether this sum is equal to the second (implicit) input-integer `T`
}g # After the filter: pop and push the length of the remaining partitions
# (which is output implicitly as result)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 55 bytes
```
⊞υE²¬ιFN⊞υ⊞OE⁺²ιΣE∨κ¹×§§υ⁻ιμ⁻κ∧μ⊕μ÷Π⁻⊕ι…⁰⊕μΠ…·¹⊕μ⁰I§⊟υN
```
[Try it online!](https://tio.run/##bZDBbsIwDIbvPEWOjpRJgHbjhNilh0G08QKh9YZFk1SuU@3ts6SoiAMny873xb/cXh230fU52zReIRn16QbYGnWMAqS13q1@IitowpDkmPwFGbRWC1zraUB2Ehmqafs0Vp20Ud/Jz7MTw82oTZmcyeMIe2lCh3@PWpdSKB4Z5bVeuuLsQwfeqCa0jB6DYGlLJl1H8kETdQiWY5dagbv0jNYMXy78Iqxf/rGY5amkpgnv8OYFPPPreg3LFAQObpRHfhsHSHOm5xsVOOf31Ta/Tf0/ "Charcoal – Try It Online") Link is to verbose version of code. Takes \$ R \$ and \$ T \$ as parameters. Explanation: Using dynamic programming with a recurrence relation turned out to be a byte shorter than porting @DominicvanEssen's R + partitions answer.
```
⊞υE²¬ι
```
Start with \$ f(0, 0) = 1 \$ and \$ f(0, 1) = 0 \$.
```
FN
```
Loop \$ R \$ times.
```
⊞υ⊞OE⁺²ιΣE∨κ¹×§§υ⁻ιμ⁻κ∧μ⊕μ÷Π⁻⊕ι…⁰⊕μΠ…·¹⊕μ⁰
```
Calculate \$ f(R, T) \$ using the recurrence relation below and append an extra zero for \$ f(R, R + 1) \$.
$$ f(R, T) = R f(R - 1, T) + \sum \_ { i = 2 } ^ T \binom R i f(R - i, T - i) $$
```
I§⊟υN
```
Output \$ f(R, T) \$.
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata) + `-n`, 13 bytes
```
R↕J:ᵐo=ᵐ#←¬∑=
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFNtJJurpKOgpJunlLsgqWlJWm6FjuCHrVN9bJ6uHVCvi2QUH7UNuHQmkcdE22XFCclF0MVLbgZbKBgwGUIxoZcRkDaCEwbcRkD2cZAtjGYbcxlAuSbAPkmQL4JmG_CZQoUMwWKmQLFTIFipmAxU4jZAA)
Takes input as \$R,R-T\$.
Brute force. Very slow.
```
R↕J:ᵐo=ᵐ#←¬∑=
R Range from 1 to the first input (R)
↕ Non-deterministically choose a permutation
J Split the permutation into a list of lists
:ᵐo= Check if all the sublists are sorted
ᵐ#←¬∑ Count the number of sublists with length 1
= Check if the number is equal to the second input (R-T)
```
`-n` counts the number of solutions.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 57 bytes
```
SeriesCoefficient[1/(2-Exp@x+x-y*x),{x,0,R},{y,0,R-T}]*R!
```
[Try it online!](https://tio.run/##RY09C8IwEIZ3f8XZyY8rbZ1EKQji4CZpthqklksN2Cg1Q0rpb48nIi7vB8f7XFu5G7WVM3UVdCkuR@uooQ5B/qKCTQ6hoM7Qa/8grU1tyLoyS2ar@OCfO7/0cb/wcxw8pihGHPqPx3JUCzENDO@Mhxxkdb1TyU8YrhAG9hRhjZCN3OS/qe2k4I1thNGaJ18CQnS2EStEKklOfHfhDQ)
Accroding to the question description, this is the same as \$a(n=R,k=R-T)\$ which is given in [A187784](https://oeis.org/A187784) at the Online Encyclopedia of Integer Sequences as *the number of ordered set partitions of \$\{1,2,\dots,n\}\$ with exactly \$k\$ singletons*.
] |
[Question]
[
“Cut” a matrix of integers on the line where the sum of the absolute differences of “severed” neighbors is the least.
## Example
Consider this matrix:
```
1 2 -4
5 -1 3
2 -2 0
```
It can be cut in 4 places, here shown by lines lettered `A`–`D`:
```
A B
╷ ╷
1 ╎ 2 ╎ -4
C ---╎----╎----
5 ╎ -1 ╎ 3
D ---╎----╎----
2 ╎ -2 ╎ 0
╵ ╵
```
The cost to cut on a line is the sum of the absolute differences of the numbers opposing each other on that line. For example, cutting on `B` would cost \$\lvert 2--4\rvert+\lvert-1-3\rvert+\lvert-2-0\rvert=12\$.
Your task, however, is to find the cheapest cut, which in this case is `D`: \$\lvert 5-2\rvert+\lvert-1- -2\rvert+\lvert 3-0\rvert=7\$.
## Input
The input will be a 2-D matrix of integers in any reasonable format. It will always have at least two rows and at least two columns and might not be square.
## Output
The output may be one of the following:
1. Two separate matrices representing the “pieces” of the original matrix after the cut, in any reasonable format. The two matrices may be in either order but must be the same shape as they were in the original matrix.
2. An expression representing where the cut is, e.g. `D` as above or the equivalent index 3 (0-based) or 4 (1-based), in any reasonable format. You may invent your own indexing scheme but it must be described in your answer and be consistent.
## Rules
* If more two or more cuts are tied for lowest cost, you may either output any one of them, or all of them.
* [Default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/) and [standard rules](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) apply. [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'"); shortest solution in bytes wins.
## Test cases
```
Input
8 1 2 -3
6 -2 -7 -4
-1 -6 -9 3
Output
x
8 1 ╎ 2 -1
6 -2 ╎ -7 -4
-1 -6 ╎ -9 3
╵
```
```
Input
2 -2 1
8 7 -7
-9 5 -3
0 -8 6
Output
2 -2 1
x---------
8 7 -7
-9 5 -3
0 -8 6
and/or
2 -2 1
8 7 -7
x---------
-9 5 -3
0 -8 6
```
[Answer]
# Excel, 321 bytes
**Golfed code:**
```
Sub z()
With ActiveSheet.UsedRange
m=-1
x=.Rows.Count
y=.Columns.Count
For c=2To y
t=0
For r=1To x
t=t+Abs(Cells(r,c)-Cells(r,c-1))
Next
If m=-1Then m=t
If t <= mThen m=t:Set a=.Columns(c)
Next
For r=2To x
t=0
For c=1To y
t=t+Abs(Cells(r,c)-Cells(r-1,c))
Next
If t<mThen m=t:Set a=.Rows(r)
Next
a.Insert
End With
End Sub
```
**Formatted and commented code:**
```
Sub z()
' Using With for the entire procedure saves plenty of bytes.
With ActiveSheet.UsedRange
' Set the initial minimum to -1 so we can tell when it hasn't been changed yet.
' We could possibly set this (2^1023*1.99) or something but then there'd be some weird edge case where this would fail to cut at the right place.
m = -1
' Save the number of rows and columns now to save bytes later.
x = .Rows.Count
y = .Columns.Count
' Loop through each column, starting with the second column and looking to the left.
For c = 2 To y
' Calculate the cut cost for this column.
t = 0
For r = 1 To x
t = t + Abs(Cells(r, c) - Cells(r, c - 1))
Next
' Check if the min is still the initial value and change it.
If m = -1 Then m = t
' If the total is <= the current minimun, then save it as the new minimum.
' We have to use <= here because "a" is not set in the line above.
If t <= m Then m = t: Set a = .Columns(c)
Next
' Repeat everything we just did but go row by row instead and don't worry about the initial min value.
For r = 2 To x
t = 0
For c = 1 To y
t = t + Abs(Cells(r, c) - Cells(r - 1, c))
Next
If t < m Then m = t: Set a = .Rows(r)
Next
' Insert a row or column as needed. This will default to shifting rows and and columns to the right.
a.Insert
End With
End Sub
```
**Input format:**
Input the matrix with one number per cell starting in cell `A1` of the active sheet.
[](https://i.stack.imgur.com/VPnSf.png)
**Output format:**
The code will insert a row or column in the correct location, cutting the data. This is equivalent to output option #1 the way the question is written now.
[](https://i.stack.imgur.com/9dpTL.png)
[Answer]
# MATLAB / Octave, ~~63~~ 46 bytes
*-17 bytes thanks to @Luis Mendo*
```
g=@(B)sum(abs(diff(B))')
@(A)min([g(A') g(A)])
```
Returns an anonymous function, used like
```
f = ans
[v,i] = f([1 2 3; 4 5 6; 7 8 9])
```
Where `i` becomes the "index" of the cut, mapping to the letter assigned to the cut in the problem description (`1` -> `A`, `2` -> `B`, etc.)
[Answer]
# [J](http://jsoftware.com/), 23 bytes
```
(=<./)@,&(1#.2|@-/\])|:
```
[Try it online!](https://tio.run/##Vc1NC4JAEAbgu7/itSIVdP3WXBKkoFN06JwsYYpGKIh1CP@7jaKHGBZmlnmfeQ6RzO00kHmkKNKKKQViDgU6LHB6BsPxej4NarxnppboW9VeM6dPDPOWaj0fNCnPygYFXKoNbMCB8AAfgnoX0@yApMuBwakfKJu2@jZ1d38he3dLnFY9yu8wE5QMxqAIJ44wQXM07i3QJ2@7KvtnvPHkZr5JEnnhaExRf2ItCPoNhh8 "J – Try It Online")
## output
Output is a boolean list of "all possible horizontal cuts" followed by "all possible vertical cuts". For example, if the input is a 3 x 4 matrix, the output will be length 5 and should be interpreted as follows:
```
the first vertical cut is minimal
v
0 0 | 1 0 0
^^^
neither horizontal cut is minimal
```
If there are multiple ones in the output, all of them are minimal.
## how
* `...|:` For both the input and its transpose...
* `&(1#.2|@-/\])` Take every pair of rows, take the absolute value of the elementwise differences, and sum
* `,` Cat those results together, putting the horizontal results first
* `(=<./)` Mark every place that equals the minimum with a 1
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
,ZạƝ€§NŒM
```
A monadic Link that accepts a list of lists and yields a list of all possible minimal cuts, each of which is a pair of numbers, the (1-indexed) index to cut before (an integer, two or greater) and a direction indicator which is \$1\$ if the index is counting rows or \$2\$ if counting columns - e.g. `[5,2]` means to cut after the fifth column.
**[Try it online!](https://tio.run/##y0rNyan8/18n6uGuhcfmPmpac2i539FJvv8Ptx@d9HDnjP//o6MVLHQUFAyB2EhHQdc4lksnWsEMyALxzIHYBCSiC5TXBYlaAtUB1cQCAA "Jelly – Try It Online")**
### How?
```
,ZạƝ€§NŒM - Link: list of lists, M
Z - transpose (M)
, - (M) paired with (that)
€ - for each:
Ɲ - for neighbours:
ạ - (left) absolute difference (right) (vectorises)
§ - sums (vectorises at depth 1)
N - negate
ŒM - maximal multi-dimensional indices
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 13 bytes
```
!G,wd|!s]h&X<
```
The output indicates the cut as the letters in the challenge text, with `1`, `2` corresponding to `A`, `B`, ...
[Try it online!](https://tio.run/##y00syfn/X9FdpzylRrE4NkMtwub//2gLBQVDBQUjBV1jawUzBV0gw1xB18RaQddQQRfIt1RQMI4FAA) Or [verify all test cases](https://tio.run/##y00syfmf8F/RXac8pUaxODZDLcLmv0tURcj/aAsFBUMFBSMFXWNrBTMFXSDDXEHXxFpB11BBF8i3VFAwjuWKNgLJKBhaKwCVA@XNrcEypmBdBgq6QFGzWAA).
### How it works
```
! % Implicit input. Transpose
G % Push input again
, % Do twice
w % Swap
d % Consecutive differences, vertically
| % Absolute value, element-wise
! % Tranpose
s % Sum, vertically. Gives a row vector
] % End
h % Concatenate the two row vectors
&X< % (1-based) index of (first) minimum. Implicit display
```
[Answer]
# [APL (Dyalog APL)](https://www.dyalog.com/products.htm), 18 bytes
```
⊃∘⍋,⍥(+⌿∘|2-/⊢)∘⍉⍨
```
[Attempt This Online!](https://ato.pxeger.com/run?1=jZVhaxNJGMdfCvspBg5uNnQbs22tXqBv7kQUToTqO5Fjkp1tVjc7y-ymJmpE6hHT2C16tnfCIfQOxRKEvLEIhUOIn-J8OZ_E55lJNm2Sgi3sMjszv_k_z_N_Jn_3vRYLxcZvLA4P-uWI1XkSsyp_10j9xUv__6h6T1X3tcqeOyp7Zy-onc8wfLS0eF71_i3omW2VHb5NKtXk67k3vuq8UNkubHJV55Xa3b-5_gs8b129dtOyvCCJQ9aCJQ_h27UbBJ7Xf4VhibjkjD-VvSE_iyb3yGg3ET5hUrJW0bJwQUU0EXjW_ikUrCb3g7RG0lbMCYs8wpo8scZLNmVKavIBAO3hwF1Q2UeVHRXgNTykam9L7T2hc6CbXKZFDasJGTwokjCITkBTEQMQ9j9RvT9V5w96G9iq81Jlx3ccOG2u0EYccwlypQcvrZg1gwmzIlIUicXJjgtzKSdgobg_BcPwc5jcSI3AFxAjdSAJDgxeT4ea42SwUUtJEnjcwKpCRlxOxIWsaXhbauc_sMEo4FfaEhj08FD1tjDXM0K5b8B2UhhHzRNnQvZTbbBtgO9Qx4YswmEFlLs3KxeJxaKpzIxGP3VsrEzWhxLDEzJacCATcyl-IwxbaB7woTaf5rSNAz1eFdrT2TG8tLFEzCPYeETU89_hfexgGPihfQp7yoRgo2oqpEbiGJH24pLa6WobGid2XroLX_4yo_aMVEPVArVd9AEmZlSERHe1XLbdMVR7G2pBb0vu36Fa7vSsOQjBvBmLpCE5tmAEGZn0TiqDutb72CWuyj6p7nu8KLKjNUpo4fxcsdpJvC42WYhA3kwlI5WQRfegWOGIC_qR-9B218aSek_pAkWi6vadao1JcNMUH9FJUI9DPkpGbndcb2r1QW3_Y5Blqvtax64b6kh1e3Q4oA7cT5f1gT88pm191-1P4ZMqC5mc8LHzdSJW1faBW3qEhHXIwVg5WaTt2TQ0ImhM3Ep8IQlLRd0463tutUkqqw2ZBJscbRpEG_k9mZRz05fWdNAQMSrq28amu_tXrt8iptx9rQKdO5NJE2rOconJoW2QBXtUH8hm9xklJfjHy3ZCz3michecDoLjMk7fWJ8wx_ps7CktCRknZeadNVvlHGNTLOApBBo019J9Njyc4sB9nZ7ubZizoME9XU1okfz3B5GOj5azLCDCvEeW4R8mPmJayBIZDlbIBXjCYFkPlyD3JxavjBZfytcvk1W9bDi4qHfj3uEAv_0EjHzrSn7OiOoi4-JoGyy9oFkleML3Vcsq88ib-kk_ODDvbw)
## I/O
* Input is a numerical matrix
* Output is the index of the cut with the same (1-based) indexing scheme as the OP -- leftmost vertical cut is 1, enumerate vertical cuts left-to-right, then horizontal cuts top-to-bottom
## Explanation
```
⊃∘⍋,⍥(+⌿∘|2-/⊢)∘⍉⍨
(+⌿∘|2-/⊢) ⍝ Cost function, calculates costs of vertical cuts
2-/⊢ ⍝ Pairwise difference of horizontally adjacent entries
| ⍝ Absolute value
+⌿ ⍝ Sum vertically
,⍥( ...... ) ⍝ Concatenate the result of calling the cost function on ...
∘⍉⍨ ⍝ ...the input and its transpose
⊃∘⍋ ⍝ Argsort ascending and return the first entry
⍝ (index of smallest value)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ø‚€üαOWQ
```
Outputs a pair of \$[horizontalCuts,verticalCuts]\$, where the truthy cut (`1`) is the minimum result (e.g. `[[0,1],[0,0]]` for the example of the challenge description, where the cuts are \$[[C,D],[A,B]]\$). (If more than one minimal cut is possible like the final test case, both cuts will be `1`.)
[Try it online](https://tio.run/##yy9OTMpM/f//8I5HDbMeNa05vOfcRv/wwP//o6MNdYx0dE1idaJNdXQNdYyBDCDfSMcgNhYA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@mFFCUWlJSqVtQlJlXkpqikJlXUFpipaCkU2l4eNe5rUbntugdWlx7aOWh3TpcSo7JJaWJOXA19pU6lS7/D@941DDrUdOaw3vObfQPD/wPU5VfWgJVZsuFbgtcTif00LpzWyPO7TA4uvBw66GF6jV6h/eenlMbcWEvVORRwzJdXd3KwzvSD08/tAMoe3gt0LIEoHsObbP/Hx0dbahjpKNrEqsTbaqja6hjDGQA@UY6BrGxOgrR0RY6YHmQsBlIWNccohioVBcoYAnUAFYH1mMIlLDQAaowB6mw1DGFaDTQ0bXQMYuNjQUA).
**Explanation:**
```
ø # Zip/transpose the (implicit) input-matrix; swapping rows/columns
‚ # Pair the (implicit) input-matrix with its transposed matrix
€ # Map over this pair of matrices:
ü # Loop over each overlapping pair of rows:
α # Take the (vectorized) absolute difference between values at the same
# positions in the two rows
O # Take the sum of each inner-most list
W # Push the flattened minimum (without popping the pair of lists)
Q # Check which inner-most value(s) are equal to this minimum
# (after which the result is output implicitly)
```
[Answer]
# PARI/GP 114 bytes
```
C(v,w)=vecsum(abs(v-w));c(M)=vecmin(concat(vector(#M-1,i,C(M[,i+1],M[,i])),vector(#M~-1,i,C(M[i+1,],M[i,]))),&L);L
```
Input: Matrix M, output: position of cut, encoded as integer, i.e., {1,2,3,4,...} corresponds to {A,B,C,D,...} in the task description.
## Examples
```
c([1,2,-4;5,-1,3;2,-2,0])
4
c([2,-2,1;8,7,-7;-9,5,-3;0,-8,6])
3
c([8,1,2,-3;6,-2,-7,-4;-1,-6,-9,3])
2
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 36 bytes
```
F⟦θE⌊θEθ§λκ⟧F⊖L⌊ι⊞υΣEι↔⁻§λκ§λ⊕κI⌕υ⌊υ
```
[Try it online!](https://tio.run/##VY3LCsIwEEX3fsUsJzBZ@MAHrkQRBAsFlyGL2kYbbFPbJuLfx6Si4uzmcO@5eZl1eZNV3l@aDlC0BEl2x0QbXbsaW/b@A97YgynUEyuCG2NMMhgaO5V3qlbGqgKPylxt@S3rEGOQur5ER3AKJKp0UJ37pnJWxaTr8c/8N3QwP3kcjbcepZ02FrdZb3GvTRHln0k3JLwXQsCSYEwwIT6VNAIQMCcevgXx2RvwMfHAVgRTKaXnj@oF "Charcoal – Try It Online") Link is to verbose version of code. Outputs a 0-indexed integer corresponding to the letters from the challenge. Explanation:
```
F⟦θE⌊θEθ§λκ⟧
```
Loop over the matrix and its transpose.
```
F⊖L⌊ι
```
Loop over the indices of pairs of adjacent columns (which for the transposed matrix map to rows of the original matrix).
```
⊞υΣEι↔⁻§λκ§λ⊕κ
```
Calculate the cost of this cut.
```
I⌕υ⌊υ
```
Output the (first) index of the minimum cost.
[Answer]
# [sclin](https://github.com/molarmanful/sclin), 50 bytes
```
"tpose"Q ,"."mapf"\& fold~"Q =
2%`",_ - abs +/"map
```
[Try it here!](https://replit.com/@molarmanful/try-sclin)
For testing purposes:
```
[[8 1 2 3_ ][6 2_ 7_ 4_ ][1_ 6_ 9_ 3]] ; \>N map >A f>o
"tpose"Q ,"."mapf"\& fold~"Q =
2%`",_ - abs +/"map
```
## Explanation
Prettified code:
```
\tpose Q , \; mapf ( \& fold~ ) Q =
2%` ( ,_ - abs +/ ) map
```
* `\tpose Q ,` pair matrix with its transposed copy
* `\; mapf` flatmap...
+ `2%` (...) map` pairwise map over each row/column...
- `,_ - abs +/` absolute difference, sum
* `( \& fold~ ) Q` get minimum sum
* `=` get all minimum sums
] |
[Question]
[
Gobar primes ([A347476](https://oeis.org/A347476)) are numbers which give a prime number when 0's and 1's are interchanged in their binary representation.
For example, \$10 = 1010\_2\$, and if we flip the bits, we get \$0101\_2 = 5\$ which is prime. Therefore, 10 is a Gobar prime
As simple as that: print the series with any delimiter. Shortest code wins.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `5`, 6 bytes
```
∞'b⌐Bæ
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=5&code=%E2%88%9E%27b%E2%8C%90B%C3%A6&inputs=10&header=&footer=)
this just times out, so not sure if it is valid
```
∞ # All positive integers
' # filter by
b # binary
⌐ # Minus from 1, (1-1=0, 1-0=1, genius)
B # decimal
æ # is prime?
```
# [Vyxal](https://github.com/Vyxal/Vyxal) `5`, 8 bytes
```
∞ƛb⌐Bæß,
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=5&code=%E2%88%9E%C6%9Bb%E2%8C%90B%C3%A6%C3%9F%2C&inputs=10&header=&footer=)
This one actually prints everything (remove the 5 flag to run for more time)
pseudo code
```
all positive integers
map
binary representation
subtract each bit from 1 aka complement
back to decimal
is prime
if truthy
print
(implicit else)
(implicit continue)
(implicit end map)
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~96~~ 94 bytes
```
k;i;d;p;f(n){for(i=5;n;n-=p)for(k=i++^(1<<32-__builtin_clz(i))-1,d=p=k>1;++d<k;)p=p&&k%d;--i;}
```
[Try it online!](https://tio.run/##VVHtbsIwDPy/p4iQQCltNZJ@0CqEP9OeYjDE2pRFZaWinYZAvPq6cwdsVLJzd3Zqx878TZZ1XamsylWtCl45p2K351ZHqlKVr2uHaKmt675yMZsF0l@t3j7ttrXVKtseuXUcX3i5rnU5F8p181mpnFrXo1E5zJXvW3XubNWyj7WtuMNODwwfCeZQm6w1@cuSaXYKPRZ5LPGYmMAkLICBS3CJqIxhxFOPBYgH0ELEQjoRi4Aj6BFh5MXgsYCBx@BT5CXQEjqhpcApnX3NkByhvrwgKmJqpO@G2qEehIzIUV5IGtUVIVGqLCJKodqCioopaVNCCSEqLBKKpoSotpxIcvQqIc@qH032vt6P4U1Wmv3vbAaLw7NcHNInWDTw2H8eDC73sCbGaa62ys0B1ybqAmessUezK/h14s7jRRjfFMVct8@@bui6pRZ/6gPqTm4gF7x17lUD9bbW/tbyL6HeI6Xgg2HO/DmDHzaLCq9pPdZ4twcbrZvl5bfnh3P3nRXb9abp/K8f "C (gcc) – Try It Online")
Returns the zero-based \$n^\text{th}\$ Gobar prime.
[Answer]
# [JavaScript (V8)](https://v8.dev/), 48 bytes
```
for(i=k=j=0;;)j%k%++i?1:~i?i=++k-(j|=k):print(k)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/Py2/SCPTNts2y9bA2lozSzVbVVs7097Qqi7TPtNWWztbVyOrxjZb06qgKDOvRCNb8/9/AA "JavaScript (V8) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~46~~ 45 bytes
Outputs the sequence indefinitely.
```
1.step{|n|(2..$.|=n).one?{|x|$.%n%x<1}&&p(n)}
```
[Try it online!](https://tio.run/##KypNqvz/31CvuCS1oLomr0bDSE9PRa/GNk9TLz8v1b66pqJGRU81T7XCxrBWTa1AI0@z9v9/AA "Ruby – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 (or 8?) [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
[NbT‡Cp–
```
Outputs with newline delimiter.
[Try it online.](https://tio.run/##yy9OTMpM/f8/2i8p5HDTo4aFzgWPGib//w8A)
If outputting as an infinite list is allowed it could be 1 byte less:
```
∞ʒbT‡Cp
```
[Try it online.](https://tio.run/##yy9OTMpM/f//Uce8U5OSQg43PWpY6Fzw/z8A)
**Explanation:**
```
[ # Start an infinite loop:
N # Push the 0-based loop-index
b # Convert it to a binary string
T # Push 10
 # Bifurcate it; short for Duplicate & Reverse copy
‡ # Transliterate the 1s to 0s and vice versa in the binary string
C # Convert it back from a binary string to an integer
p # Check if this integer is a prime number
– # If it is: Print the loop-index `N` with trailing newline
∞ # Push an infinite positive list
ʒ # Filter it by:
bT‡Cp # Same as above
# (after which the resulting list is output implicitly)
```
`bT‡C` could alternatively be `2в_2β` for the same byte-count in both programs: [try it online](https://tio.run/##yy9OTMpM/f//Uce8U5OMLmyKNzq3qeD/fwA).
```
2в # Convert the integer to a base-2 list
_ # Check for each if it's equal to 0: 1 if 0; 0 otherwise
2β # Convert it from a base-2 list back to an integer
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
BCḄẒƲ#
```
[Try it online!](https://tio.run/##y0rNyan8/9/J@eGOloe7Jh3bpPz/vykA "Jelly – Try It Online")
Takes an input `n` from STDIN and outputs the first `n` Gobar numbers. If we have to output all Gobar numbers, the following works for 9 bytes
```
ṄBCḄẒƲ¡‘ß
```
[Try it online!](https://tio.run/##AR0A4v9qZWxsef//4bmEQkPhuIThupLGssKh4oCYw5///w "Jelly – Try It Online")
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 10 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
òî_â┌ä¶╛p∟
```
[Try it online.](https://tio.run/##ASEA3v9tYXRoZ29sZv//w7LDrl/DouKUjMOkwrbilZtw4oif//8)
**Explanation:**
```
ò ∟ # Do while true without popping,
ò # using the following eight characters as inner code-block:
î # Push the 1-based loop-index
_ # Duplicate it
â # Pop and convert it to a binary-list
┌ # Invert each boolean
ä # Convert it from a binary-list back to an integer
¶ # Check if it's a prime number
╛ # If it is:
p # Pop and print the 1-based loop-index with trailing newline
```
[Answer]
# [R](https://www.r-project.org/), ~~81~~ 73 bytes
*-8 bytes thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe)*.
```
while(T<-T+1)(k=(p=2^(0:log2(T)))%*%!T%/%p%%2)<2|sum(!k%%1:k)>2||print(T)
```
[Try it online!](https://tio.run/##K/r/vzwjMydVI8RGN0TbUFMj21ajwNYoTsPAKic/3UgjRFNTU1VLVTFEVV@1QFXVSNPGqKa4NFdDMVtV1dAqW9POqKamoCgzrwSo8v9/AA "R – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes
```
λb†Bæ;ȯ
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%CE%BBb%E2%80%A0B%C3%A6%3B%C8%AF&inputs=10&header=&footer=)
Takes a number n and returns the first n numbers.
```
λ ;ȯ # First n numbers where...
b # Binary
† # Vectorised logical not (Vyxal uses 1/0 for booleans)
B # When converted back to a number
æ # Is prime?
```
[Answer]
# [Python 3](https://docs.python.org/3/), 77, 70(@ovs), 65, 64 bytes
```
*p,x,z,P=5*[1]
while[p[z^x]or print(x)]:P*=x;x+=1;p+=-~P%x,;z|=x
```
[Try it online!](https://tio.run/##K6gsycjPM/7/X6tAp0KnSifA1lQr2jCWqzwjMyc1uiC6Kq4iNr9IoaAoM69Eo0Iz1ipAy7bCukLb1tC6QNtWty5AtULHuqrGtuL/fwA "Python 3 – Try It Online")
[Old version](https://tio.run/##K6gsycjPM/7/X6tAp0KnSifA1lQr2jCWqzwjMydVocKqQtvW0LpA21a3LkC1Qse6qsa2wroguiquIja/SKGgKDOvRKNC0zpAy7bi/38A "Python 3 – Try It Online")
[Old version](https://tio.run/##BcFBCoAgEAXQvaeYTVC6knbJ3MG9GAQFCmFDCP2ku9t78tZ0lbl3z@DGVgmHqJ6Uz4OwiGE/QAdE1z6GaysoFxLayk5y51JHTM5rhoaDYdv7Dw "Python 3 – Try It Online")
[Old version](https://tio.run/##K6gsycjPM/7/v0qnQkerwNZQx4irPCMzJ1WhwqpA2zYxJ0ejQrVSIS2/SKFSITNPoUBTK7oi1rqqxrbCuiquAiykkJiXolBQlJlXolGhaV2hbWv4/z8A "Python 3 – Try It Online")
[Answer]
# [JavaScript (V8)](https://v8.dev/), 75 bytes
Prints the sequence "forever" (i.e. until call stack overflow).
```
for(k=0;f=d=>x%--d?f(d):x>1&d<2;)f(x=++k^~-(1<<32-Math.clz32(k)))&&print(k)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/Py2/SCPb1sA6zTbF1q5CVVc3xT5NI0XTqsLOUC3FxshaM02jwlZbOzuuTlfD0MbG2EjXN7EkQy85p8rYSCNbU1NTTa2gKDOvBMj@/x8A "JavaScript (V8) – Try It Online")
Or **~~77~~ 76 bytes** without `Math.clz32()`:
```
for(k=0;f=d=>x%--d?f(d):x>1&d<2;)f(x=++k^(g=k=>k&&1|2*g(k>>1))(k))&&print(k)
```
[Try it online!](https://tio.run/##DcbBCkBAEADQrzHN0JZ1Emb8iZJtxRRa2vbg35d3evsc53sJ2/WY2Obsz4DKde/ZsaTCGDd6dNQlseCGpiePiatKJ1xZWRTAvk25oopYIlQigCtsx/M35w8 "JavaScript (V8) – Try It Online")
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 50 bytes
```
for(i=1,oo,if(isprime(2^#binary(i)-i-1),print(i)))
```
[Try it online!](https://tio.run/##K0gsytRNL/j/Py2/SCPT1lAnP18nM00js7igKDM3VcMoTjkpMy@xqFIjU1M3U9dQUwconlcC5Glq/v8PAA "Pari/GP – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 38 bytes
```
Nθ≔¹ηW‹ⅉθ«≦⊕η≔↨E↨粬κ²ζ¿∧‹¹ζ⬤…²ζ﹪ζκ⟦Iη
```
[Try it online!](https://tio.run/##LY4xD4IwEIVn@BU3XpM6wOqETiRCjJsxDhUqJZYW2qIJxt9eS8p279337l0jmGk0k96XapxdPQ8PbnAi@7Swtu8UZhREUB/RSw544tbiFQmFiRD4pknFxg0sVWP4wJXjbYwk2@LALMfAxUFQyEO81g5fhESxrHT/BCxUGyuy1aRQSIkXpjqOeTQq3c5S40IhhMMHZ9Mrh7cjsw4FuYc7P@@z3O/e8g8 "Charcoal – Try It Online") Link is to verbose version of code. Outputs the first `n` Gobar primes. Explanation:
```
Nθ
```
Input `n`.
```
≔¹η
```
Start at `1` (arbitrary, just has to be between `0` and `3` inclusive).
```
W‹ⅉθ«
```
Repeat until `n` Gobar primes have been printed.
```
≦⊕η
```
Try the next integer.
```
≔↨E↨粬κ²ζ
```
Convert it to base `2`, flip the bits, then convert back.
```
¿∧‹¹ζ⬤…²ζ﹪ζκ
```
If the result is at least `2` and has no nontrivial proper factors, then...
```
⟦Iη
```
Print the Gobar prime on its own line.
The above algorithm appears to be O(n²) in complexity, taking 20 seconds to calculate the first 1400 Gobar primes and probably 20 minutes to calculate the first 7708. I've implemented a faster algorithm for ~~66~~ 56 bytes that can calculate the first 7708 Gobar primes in ~~20~~ seconds (although it does start to slow down after that point due to using a memory-inefficient method of generating primes):
```
Nθ≔²η≔υζW‹Lυθ«≔Φζ‹×κκ⊗ηε≔⁺Φ⮌…η⊗η⬤ε﹪κμζζ≦⊗η≔⁺υ⁻⊖⊗ηζυ»I…υθ
```
[Try it online!](https://tio.run/##XY/NasMwEITP8VPouAIVSi4p5BQSCoU6hNAXUJzFEllLjn5S6tJnV9eJQ38ug0bMfLvbGB0ar6mUF9fntM3dAQOc5bJaxWhbB3MlzI/LSgzs3o0lFPCKMbK4NhnIUomzlOKzmk3ZZ0uJWYMS19yb7TDCSYkTJzc@HwiPYKRkh4y8t3aU4726xwuGiLDXrkUw/2srIkAlan/M5Edyd/0e5G3JWa37CTr1bqf8mcQH1dbxY4NNwA5dYvyvMSOKJXPvq9oF6xKsdWT5aAjXxvcjge@Wy1IWi8en8nChbw "Charcoal – Try It Online") Link is to verbose version of code. Outputs the first `n` Gobar primes, although it actually works by calculating the primes up to the next power of 2. Explanation:
```
Nθ
```
Input `n`.
```
≔²η≔υζ
```
Start with the primes up to (but not including) 2, i.e. no primes at all.
```
W‹Lυθ«
```
Repeat until enough Gobar primes have been obtained.
```
≔Φζ‹×κκ⊗ηε
```
Get the primes up to the square root of the next power of 2.
```
≔⁺Φ⮌…η⊗η⬤ε﹪κμζζ
```
Calculate all the primes between the current and next power of 2 by trial division by all of those primes. (Sieving them would probably be even faster.)
```
≦⊗η
```
Double the current power of 2.
```
≔⁺υ⁻⊖⊗ηζυ
```
Complement the bits in all of the primes up to the current power of 2 with respect to that number of bits e.g. primes up to 4 have three bits complemented resulting in `4, 5` while primes up to 128 would have eight bits complemented. (Note that the list of primes is in reverse order so the complements are in ascending order as desired.)
```
»I…υθ
```
Output the first `n` Gobar primes.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 106 bytes
```
n=1
while 1:(k:=int(bin((n^~-2**~-len(bin(n))))[3:],2))>1and all(k%m for m in range(2,k))and print(n);n+=1
```
[Try it online!](https://tio.run/##HYxBCsIwFAX3nuJvhP9ru0i6kUi8iChEjDYkfQ2hIG569dh2ljMw@TcPE/pzLrXCqsN3CMmTMhyNDZj5GcCMx9Lpplm65LEbyMqtN/dWi1yVw4tcShyPI72nQiMFUHH4eNZtFNl6LtsOcsHJqlr/ "Python 3.8 (pre-release) – Try It Online")
Infinite output
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~71~~ 70 bytes
```
require'prime'
1.step{|n|n.to_s(2).tr('01','10').to_i(2).prime?&&p(n)}
```
[Try it online!](https://tio.run/##HU8xDoMwENv7CqYGpAjljiSEqU@pVImBoZQGGKrSt6c2g@9s30W@5P3xKSWP733Ko1ny9BzNRdp1G5fvMR9zu73ua61Nu@XaODHWiDMN3Ynu@eB2vS713PxK8bYKtkq2Egco0AHQCq2YagSoB1t1mHfwPGaeHbMAHuAHcuxF6CgAdITusZfgJXZ4A/jAfmZ6FrIzXigl8pDzGp7DG0QDC/c8PeaKp2SyBK4wWxgqPb2eLJExWBKnAxmz1SkLfyX6Bw "Ruby – Try It Online")
* Saved 1 thanks to @ovs
Full program, prints the sequence indefinitely on new lines.
```
1.step{|n| # each n>0
n.to_s(2) # convert to binary string
.tr('01','10') # swap '01'
.to_i(2) # reconvert to int
.prime?&&p(n) # put n if prime
```
] |
[Question]
[
## Background
**Polyagony** is a family of hypothetical esolangs where the source code is laid out on a specifically shaped board before running it. It's similar to Hexagony, but various [uniform tilings](https://en.wikipedia.org/wiki/Euclidean_tilings_by_convex_regular_polygons#Archimedean,_uniform_or_semiregular_tilings) can be used instead of a simple hexagon. The shape of the board and the tiling used is defined by the "mode".
Mode 3/3,6 is a triangular board filled with (3,6)2 tiling. The boards of sizes 1, 2, and 3 look like the following:
```
* * *
* * * * * *
* * * *
* * * * * * * *
* * *
* * * * * *
```
In general, the board of size `n` can be formed by adding two rows under the board of size `n-1`, where the two new rows are formed by putting `n` copies of small triangles side by side. So the size 4 can be generated from size 3 as follows:
```
*
* *
* *
* * * *
* * *
* * * * * *
1 2 3 4
1 1 2 2 3 3 4 4
```
Given a source code of length n, the size of the board is determined first, and then each character in the code is sequentially placed on each asterisk from top to bottom, left to right. The rest is filled with no-ops (dots, as in Hexagony).
The board size is chosen so that it is the smallest board that can fit the entirety of the source code. For example, `abcdefghi` would be placed as
```
a
b c
d e
f g h i
```
and `abcdefghij` as
```
a
b c
d e
f g h i
j . .
. . . . . .
```
The minimum board size is 1. If the source code is empty, the laid out result must be a triangle of three no-ops:
```
.
. .
```
## Challenge
In order to simplify the challenge a bit, let's assume the source code is just a string of asterisks (`*`). Given the **length** of such a program as input, output the laid out result.
The output can be as a single string or a sequence of lines. Trailing whitespaces on each line or after the entire output are OK.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
The expected outputs for the inputs 0 (three no-ops), 3, 9, and 18 (full triangles of asterisks) are already given above.
```
Input: 2
Output:
*
* .
Input: 4
Output:
*
* *
* .
. . . .
Input: 7
Output:
*
* *
* *
* * . .
Input: 17
Output:
*
* *
* *
* * * *
* * *
* * * * * .
```
[Answer]
# JavaScript (ES7), ~~127~~ 116 bytes
Draws the output character by character.
```
n=>(y=0,g=x=>y>w?'':`.*
`[x<-w?(x=w,++y,2):x*x-->y*y|(y&1?x&1:~x&3^y&3)?3:n&&n/n--]+g(x))(w=(n*2/3-.4)**.5-.5<<1|1)
```
[Try it online!](https://tio.run/##XcpNDoIwEEDhPaeYVZlpabWgG6RwEKPRKBCNmRo10safq6NuXb3F947b@/a6uxzON81@346dG9nVGN00611wdayHJk3LjZEJbJah0kODwQ2ZUjHLqQwyaF1HGZ8YhW2CsOU7iGIdRUFNUbIQPGGtV6rHQISDQ5b5pNBmRlKauTbzqrJPS2PnL8jgwC6AoYJ8@q1SBI8EYOf56k@tOfke09@UggKmP@mQiZLX@AE "JavaScript (Node.js) – Try It Online")
### How?
We define \$w\$ as:
$$w=\left\lfloor \sqrt{2n/3-2/5}-1/2 \right\rfloor\times2+1$$
The top of the triangle is \$(0,0)\$, the bottom-left corner is \$(+w,+w)\$ and the bottom-right corner is \$(-w,+w)\$.
```
| x > 0 x < 0
| <-------- -------->
| 5 4 3 2 1 0 1 2 3 4 5
---+------------------------
0 | . . . . . B . . . . .
1 | . . . . A . A . . . .
2 | . . . B . . . B . . .
3 | . . A . A . A . A . .
4 | . B . . . B . . . B .
5 | A . A . A . A . A . A
```
There is an active cell on the board if \$|x|\le y\$ and:
* \$y\$ is odd and \$x\$ is odd (A-cells)
* or \$y\$ is even and \$y\bmod 4 = x\bmod 4\$ (B-cells)
[Answer]
# [Vyxal (hyper's old fork)](https://github.com/Lyxal/Vyxal) `C`, ~~46~~ 45 bytes
```
3/d4Ė+√2Ė-⌈1∴:£ƛ‛% *Ṫ\%dn*"vṄ;f⁋?×*?d›\.*+f%↵
```
[Try it Online!](https://vyxal.hyper-neutrino.xyz?flags=C&code=3%2Fd4%C4%96%2B%E2%88%9A2%C4%96-%E2%8C%881%E2%88%B4%3A%C2%A3%C6%9B%E2%80%9B%25%20*%E1%B9%AA%5C%25dn*%22v%E1%B9%84%3Bf%E2%81%8B%3F%C3%97*%3Fd%E2%80%BA%5C.*%2Bf%25%E2%86%B5&inputs=4&header=&footer=)
Yuck. What a mess.
Uses the formula \$\lceil\sqrt{\frac23x+\frac14}-\frac12\rceil\$ to calculate the required size.
Mainstream Vyxal is completely broken right now - [status-everythingisonfire](/questions/tagged/status-everythingisonfire "show questions tagged 'status-everythingisonfire'").
```
3...⌈ # Calculate above formula
1∴ # Max(that, 1) for 0 case
:£ # Store a copy to register
ƛ ; # Map...
‛% * # `% ` that many times
Ṫ # With the last char removed
\%dn* # 2n %s
" # Pair the two
vṄ # Join each by newline
f⁋ # Flatten and join by newlines
?×* # n *s
?d›\.*+ # Plus 2n+1 .s
f% # Format the %s by this
↵ # Split by newlines so C can do its magic
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 40 bytes
```
NθW‹LKA∨θ¹F⊞OυLυ«J⊗⁻⊗κ⌈υ⊗⌈υP^²UMKA§.*‹μθ
```
[Try it online!](https://tio.run/##TY/NDgFBEITP9ik6Tj0yBEdOwoVYHJwlww47MX9mp5GIZx9rI7h00pWvKlWHUoSDEzqlufUUV2T2MuCFjbNbqbQEXMqqqo89xRI3Up4nWiNjHNY1xWHAGIOjC4Abqsq1l0FEF5A4fCz0Bh5Za0HGbx3OHO21LDBXlqrvd67zcnFXhkxj4PDl/tRx1spJR@WDshFHOw7DRhN@6owRtvj14zCJc1vIO7Z7nfa7TD3CcLg0Mc@UBv3UveoX "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ
```
Input `n`.
```
W‹LKA∨θ¹
```
Repeat until `n` characters have been output, except always output at least one character (this is a stupid edge case that costs me two bytes).
```
F⊞OυLυ«
```
Loop through each triangle of the next row of the board.
```
J⊗⁻⊗κ⌈υ⊗⌈υ
```
Jump to the top of the triangle.
```
P^²
```
Print arbitrary characters down and left, thus creating the small triangle.
```
UMKA§.*‹μθ
```
Update all of the characters according to whether they are within the first `n` or not. (This is done inside the loop to save a byte, although only the last update actually matters.)
[Answer]
# [J](http://jsoftware.com/), 76 69 bytes
*-7 bytes thanks to Jonah's approach!*
```
(' *.'{~]+(<]*$$+/\@,))1(<:2&(0&,.,a,._2{.])a=:#:@4 10)@>.+/\@i.I.%&3
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NdQVtPTUq@titTVsYrVUVLT1Yxx0NDUNNWysjNQ0DNR09HQSdfTijar1YjUTba2UrRxMFAwNNB3s9EAqM/U89VTVjP9rcqUmZ@QraFinaSoYILGNkNgmSGxzJLah@X8A "J – Try It Online")
* `+/\@i.` triangular numbers `0 1 3 6 …`
* `I.%&3` search for the index where `n%3` would sit inbetween. This is the (halved) height of the triangle.
* `1>.` corner case for 0
* `a=:#:@4 10` starting with the tile saved as `a`
```
0 1 0 0
1 0 1 0
```
* `_2{.]` get the last two rows
* `a,.` prepend `a` on the left
* `2&(0&,.,…)` prepend the previous rows with two 0 before them
* `<:` (with a bunch of `&`s) … do this (halved) height minus one times.
* `$$+/\@,` (would be cooler, if something like `+/\&.,` would work!) flatten to a list, scan-reduce with addition, and reshape to the 2d matrix. So
```
0 1 0 0 -> 0 1 0 0 1 0 1 0 -> 0 1 1 1 2 2 3 3 -> 0 1 1 1
1 0 1 0 2 2 3 3
```
* `]+(<]*` where it was 0 before, it shall be 0 after all. Compare with the input, and add to the original 2d matrix (so for `n=4`):
```
0 0 0 1 0 0 0
0 0 1 0 1 0 0
0 1 0 0 0 2 0
2 0 2 0 2 0 2
```
* `' *.'{~` map into the characters needed for the output
[Answer]
# [Haskell](https://haskell.org), 269 bytes
```
import Data.List
f _ r[]=intersperse ' '<$>r
f n r s=let(x,y)=splitAt(3*n)s;(a,b)=splitAt n x in f(n+1)(map(' ':)r++[intersperse ' 'a,b])y
v[]=[]
v(x:y:s)=(' ':x):y:v s
s n=unlines$v$f 1[]$replicate n '*'++replicate(head(filter(>=n)$map(\n->(1+n)*n`div`2*3)[1..])-n)'.'
```
Clunky non-math solution. Generate a list of `*`s of length `n` and pad to nearest triangular number with `.`, then take out the characters two lines a time.
`f` generates the tower from list of asterisks and dots. `v` adjusts the tower so that it looks correct (very annoying). `s` generates the list of asterisks and dots, passes it to `f` and join the lines to give the result.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), 48 bytes
```
RS×3R>¬
Ḥ÷3+.25½_.ĊðRżḤ$Rṁ@çị⁾*.ẎK€ÐoK€JU’Ɗ⁶ẋżƲY
```
[Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCJSU8OXM1I+wqxcbuG4pMO3MysuMjXCvV8uxIrDsFLFvOG4pCRS4bmBQMOn4buL4oG+Ki7huo5L4oKsw5BvS+KCrEpV4oCZxorigbbhuovFvMayWSIsIiIsIiIsWyIxNyJdXQ==)
aaaaaaahh this is so bad... >\_<
even considering Jelly is not usually optimal for string challenges this feels like such a stupid solution
"borrows" A username's formula, \$\lceil\sqrt{\frac23x+\frac14}-\frac12\rceil\$
```
RS×3R>¬ Helper Link; given the size and the input, return the flat list of items
R [1, 2, ..., size]
S Sum; nth triangular number
×3 Triple
R [1, 2, ..., 3/2 n(n+1)]
> For each one, is it greater than the input?
¬ Logical NOT; is it <= the input?
Ḥ÷3+.25½_.ĊðRżḤ$Rṁ@çị⁾*.ẎK€ÐoK€JU’Ɗ⁶ẋżƲY Main Link
Ḥ÷3+.25½_.Ċ ×2 ÷3 +1/4 sqrt -1/2 ceil
ð Dyadic chain; take the size on the left and the input on the right
R [1, 2, ..., size]
żḤ$ Zip with double; [[1, 2], [2, 4], [3, 6], ...]
R Range; [[[1], [1, 2]], [[1, 2], [1, 2, 3, 4]], [[1, 2, 3], [1, 2, 3, 4, 5, 6]], ...]
ṁ@ Mold the right to the above:
ç Last link (the 1s and 0s for the output values)
ị⁾*. Index into "*."; 1 becomes * and 0 becomes .
Ẏ Tighten; flatten once
K€Ðo Join odd indices on spaces
K€ Join each line on spaces
====-=-Ʋ 4:
-=-Ɗ 3:
J [1, 2, ..., # rows]
U [#, # - 1, ..., 1]
’ [# - 1, # - 2, ..., 0]
⁶ẋ " " * each
ż Zip with the original; format to triangle
Y Join on newlines
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~38 37~~ 36 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
J’Ṛ⁶ẋż
‘RḤĖRðFJ>ṁ⁸ðȦÐḟȯ$Ẏị⁾.*K€⁺ÐoÇY
```
A monadic link that accepts a non-negative integer and yields a list of characters.
(Note: Removing the trailing `Y` *would* give a list of lines *but* each of those lines would be a list of lists of characters - the leading spaces in the first list and then the rest of the line in a second.)
**[Try it online!](https://tio.run/##AVUAqv9qZWxsef//SuKAmeG5muKBtuG6i8W8CuKAmFLhuKTEllLDsEZKPuG5geKBuMOwyKbDkOG4n8ivJOG6juG7i@KBvi4qS@KCrOKBusOQb8OHWf///zM1 "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##AX4Agf9qZWxsef//SuKAmeG5muKBtuG6i8W8CuKAmFLhuKTEllLDsEZKPuG5geKBuMOwyKbDkOG4n8ivJOG6juG7i@KBvi4qS@KCrOKBusOQb8OHWf/FvMOH4oKsWeKCrGrigb7CtsK2//8wLCAyLCAzLCA0LCA3LCA5LCAxNywgMTg "Jelly – Try It Online").
### How?
```
J’Ṛ⁶ẋż - Link 1, prefix spaces: list of lines with no leading spaces, L
J - range of length [1..length(L)]
’ - decrement -> [0..length(L)-1]
Ṛ - reverse -> [length(L)-1..0]
⁶ẋ - space character repeated -> [" ... ", ... , " ", " ", ""]
ż - (that) zipped with (L) -> [[" ... ", first], ... ["", last]]
‘RḤĖRðFJ>ṁ⁸ðȦÐḟȯ$Ẏị⁾.*K€⁺ÐoÇY - Main Link: non-negative integer, N
‘ - increment -> N+1 (this is to create enough rows if N=0)
R - range -> [1,2,3,...,N+1]
Ḥ - double -> [2,4,6,...,2N+2]
Ė - enumerate -> [[1,2],[2,4],[3,6],...,[N+1,2N+2]]
R - range (vectorises) -> [[[1],[1,2]],[[1,2],[1,2,3,4]],...]
ð ð - dyadic chain, f(X=that, N):
F - flatten -> [1,1,2,1,2,1,2,3,4,...]
J - range of length -> [1,2,3,...,3(N+1)(N+2)/2]
> - greater than (N)? -> e.g. N=4: [0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
ṁ⁸ - mould like X
-> e.g. N=4: [[[0],[0,0]],[[0,1],[1,1,1,1]],[[1,1,1],[1,1,1,1,1,1]],[[1,1,1,1],[1,1,1,1,1,1,1,1]],[[1,1,1,1,1],[1,1,1,1,1,1,1,1,1,1]]],
$ - last two links as a monad, f(Z=that):
Ðḟ - filter discard those for which:
Ȧ - any and all?
(removes those "row-pairs" which contain no zeros)
ȯ - logical OR (with Z) (this is to keep [[[1],[1,1]]] when N=0)
Ẏ - tighten -> e.g. N=4: [[[0],[0,0]],[[0,1],[1,1,1,1]]]
ị⁾.* - index into ".*" -> ["*","**","*.","...."]
K€ - join each with spaces -> ["*","* *","* .",". . . ."]
Ðo - apply to odd indexed entries:
⁺ - repeat last link -> ["*","* *","* .",". . . ."]
Ç - call last Link (Link 1) as a monad
-> [[" ","*"],[" ","* *"],[" ","* ."],["",". . . ."]]
Y - join with new lines
-> *
* *
* .
. . . .
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 34 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
∞.ΔLO3*I@}·LL2Å€É}Ā».cT„. ‡IF¤'*.;
```
[Try it online](https://tio.run/##AT0Awv9vc2FiaWX//@KIni7OlExPMypJQH3Ct0xMMsOF4oKsw4l9xIDCuy5jVOKAni4g4oChSUbCpCcqLjv//zEw) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX3lopY6Sf2kJhKvz/1HHPL1zU3z8jbUOrXOoPbTdx8focOujpjWHO2uPNBzarZcc8qhhnp7Co4aFh9a5HVqirqVn/b9W59A2@//RBjpGOsY6JjrmOpY6hgY6huY6hhY6hpY6RqZArkEsAA).
**Explanation:**
```
∞ # Push an infinite positive list: [1,2,3,...]
.Δ # Find the first integer which is truthy for:
L # Pop the integer `n`, and create a [1,n] ranged list
O # Sum this list
3* # Multiply it by 3
I@ # Check if it's larger than or equal to the input
}· # After we've found our integer: double it
L # Create a [1,n] ranged list again
L # Map each inner integer `m` into a [1,m] ranged list as well
2Å€ # Apply to every (0-based) 2nd item (at indices 0,2,4,6,...):
É # Check which integers are odd (1 if odd; 0 if even)
}Ā # Truthify: transform all other positive integers into 1s as well
» # Join each inner list by spaces, and then each string by newlines
.c # Centralize each line by padding with leading spaces
T„. ‡ # Transliterate characters "10" to ". "
IF # Loop the input amount of times:
¤ # Get the last character of the string without popping the string itself
# (which is always a ".")
'*.; '# And replace the first "." in the string with "*"
# (after which the string is output implicitly as result)
```
[Try this for a step-by-step of how the input is transformed into the output.](https://tio.run/##lVJNixNBEL37K4pcWsNkSMxlMUhWVpSRlQXdm3jomanJNHa6x/7Y7AiBICzo3fOC4NGzHjwIiWd/RP5IrJ4PXTwInhq6Xr1671Vpy1OBh8MgUYVQwiFIYR3c9hYtvJhERy9BKHClsGAdVqO0HoUX8JIvK4l37sFgfnR6f/tlfmtwbriyhTZLQJ6V1Oc0cKDPBeYNbQB32Oe@Q/X/Z@3/Uy@dqGQNwkFawzSUpsOmlgxOSsxegSioyCxIbhZoSBtXoA3ga88l0EhXIs2uPLnYfW8EJsdRQ/4YXVMthCGPq1LQ/BW34Ix3ZR2Q@3fX8c8Pp2fTYXK8bhU91D6VxNio3H792yrp/KfR/wnlQRWcEwAv0NQwHqXcEkrnOfXleInhVeQ59M0ga@JobRAvUhoWuMHQEFjv7q72bz/v3q97JeRSFPWM/P7W1AzSFIqBSlvhxAX2XL3WSeD6sWlJnmg6h85JryQsylY8QxsBV3mIuMNYZ4RahLrClRQKLXFF228t1wkqUiLFmy7dKM5uZCbpGA2ng2STMQuhsBhYQJ3vN9cx7Dcfu6t4hpWk4Tc2@2f7wJfaKwe6oHYGK@FKYENGOgti708AoeTkW3sDBi1dYBiTPNp@YsN4tp4fDpPxLw)
] |
[Question]
[
Inspired by [this 3Blue1Brown video](https://www.youtube.com/watch?v=O85OWBJ2ayo)
Given a square matrix \$ M \$, compute its [matrix exponential](https://en.wikipedia.org/wiki/Matrix_exponential) \$ \exp(M) \$, which is defined, using an extension of the [Maclaurin series for \$ e^x \$](https://en.wikipedia.org/wiki/Taylor_series#Exponential_function), as
$$ \exp(M) = \sum\_{r=0}^\infty \frac {M^r} {r!} = M^0 + M^1 + \frac 1 2 M^2 + \frac 1 6 M^3 + \cdots + \frac 1 {n!} M^n + \cdots $$
where \$ n! \$ represents the [factorial](https://en.wikipedia.org/wiki/Factorial) of \$ n \$, and \$ M^0 \$ is the [identity matrix](https://en.wikipedia.org/wiki/Identity_matrix) for the dimensions of \$ M \$.
There are [other ways to compute this](https://en.wikipedia.org/wiki/Matrix_exponential#Computing_the_matrix_exponential), which you may use, as long as the result is sufficiently precise (see the rules below).
## Test cases
| Input | Output |
| --- | --- |
|
```
0 00 0
```
|
```
1.0 0.00.0 1.0
```
|
|
```
1 23 4
```
|
```
51.968956198705044 74.73656456700328112.10484685050491 164.07380304920997
```
|
|
```
1 00 1
```
|
```
2.718281828459045 0.00.0 2.718281828459045
```
|
|
```
-10 -76 3
```
|
```
-0.17051293798604472 -0.220300006353908980.18882857687477908 0.23861564524264348
```
|
|
```
-2 160 7
```
|
```
0.1353352832366127 1949.32946336928330.0 1096.6331584284585
```
|
|
```
12 18 -5-13 13 1713 -6 2
```
|
```
951375.2972757841 1955306.8594829023 2179360.8077694285376625.60116007976 774976.2125979062 863826.1366984685773311.8986313189 1589134.8925863737 1771827.68268726
```
|
|
```
8 19 20 1919 -18 8 -117 -16 17 -1113 -15 -14 2
```
|
```
-809927951.1659397 682837927.821331 -2875315029.426385 166307199.77734298-114105964.84866604 423320553.28643256 -1532090815.2105286 379540651.37782615666012827.4455533 256623519.77362177 -454247177.983024 753881172.0779059-849659694.5821244 -147765559.4347415 -39332769.14778117 -766216945.8367432
```
|
|
```
15 -17 7 -1 18 5-20 1 -11 -11 -2 1614 -4 -6 -8 -4 5-18 2 -14 5 1 -11-16 18 19 -10 -17 1310 20 7 19 14 0
```
|
```
-84820410929.4261 -16367909783.470901 -68656483749.58916 3885773007.51203 -53912756108.37766 -68894112255.13809190335662933.039 -38645269722.440834 127312405236.2376 -13585633716.898304 90603945063.00284 75004079839.71536-68036952943.18438 -7733451697.302282 -53156358259.70866 3465229815.7224665 -41070570134.5761 -49564275538.347560712557398.76749 30529410698.827442 55820038060.925934 -1566782789.1900578 46171305388.15615 69179468777.9944123964494616.41298 -39882807512.560074 77695806070.41081 -9798106385.28041 53080430956.84853 33312855054.34455202240615797.98032 -49846425749.36303 132157848306.15779 -15002452609.223932 92731071983.4513 70419737049.6608
```
|
|
```
-3 3 9 -14 13 3 -19 11-3 16 -3 -2 -16 17 -7 14-16 -13 -19 -4 -19 -12 -19 4-19 2 -1 -13 -1 20 -18 20-15 -14 -17 4 -16 -7 -13 10-1 3 -2 -18 -13 -20 -18 8-6 5 17 4 -11 0 4 1-7 14 4 5 -10 1 11 -1
```
|
```
-961464430.42625 -3955535120.8927402 -458113493.1060377 1262316775.4449253 1876774239.173575 -1179776408.054209 710474104.2845823 -1223811014.558188728955217908.989292 119124631307.93314 13796523822.599554 -38015726498.96707 -56520887984.67961 35530121226.97329 -21396437283.72946 36856280546.42262-8410889774.023839 -34603239307.789085 -4007607155.9532456 11042781096.475042 16418151308.196218 -10320764772.97249 6215219812.505076 -10705984738.66510610215509474.424953 42027619363.9107 4867469315.8131275 -13412092189.39047 -19940786719.11994 12535160455.72014 -7548741937.235227 13003031639.209038-1859396787.0195892 -7649733581.4828005 -885954562.2162387 2441226246.193038 3629550445.402215 -2281610372.751828 1374002295.125188 -2366775855.5699253449955718.5164527 1851164998.6281173 214390574.08290553 -590752899.2082579 -878315768.622139 552129374.7322844 -332495739.50407004 572740581.36085164056736597.835622 16689783857.791903 1932941125.9578402 -5326143353.840331 -7918773134.746702 4977893918.896973 -2997723598.294145 5163693248.84186218572197375.577248 76407841992.77576 8849246673.162008 -24383706828.81331 -36253120255.06763 22789406560.399803 -13723910211.58447 23640014943.24763
```
|
## Rules
* Your outputs must be within \$ \pm 1 \% \$ of the outputs given in the test cases above
* If you use a boring builtin to do most of the computation, you should add it to the Community Wiki answer, or post another more interesting method as well
* You may assume \$ M \$ will be square and have side length in \$ [2, 8] \$
* The elements of \$ M \$ will all be integers in \$ [-20, 20] \$
* You may take \$ M \$ as a nested array, a built-in matrix type, a flat array which is a square-number in length, or any other sensible format
* [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061) are forbidden
* [Standard I/O rules](https://codegolf.meta.stackexchange.com/q/2447) apply
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins
[Answer]
# Trivial built-in answers
If your solution uses a built-in function to perform the core of the challenge, please edit it in to this answer.
# [Wolfram Language (Mathematica)](https://www.wolfram.com/mathematica/), 9 bytes
```
MatrixExp
```
# [MATL](https://github.com/lmendo/MATL), 2 bytes
```
Ye
```
[Try it online!](https://tio.run/##y00syfn/PzL1//9oXUMDBV1zawUzBeNYAA "MATL – Try It Online")
# MATLAB/[Octave](https://www.gnu.org/software/octave/), 5 bytes
```
@expm
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en998htaIg939aflFuYolCTn5eugIEqCoUZ@SXKyTm5CikpCZn5ibmFHOlaUTrGhoo6JpbK5gpGMdq/gcA "Octave – Try It Online")
# [Python 3](https://docs.python.org/3/), 30 bytes
```
from scipy.linalg import*
expm
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P60oP1ehODmzoFIvJzMvMSddITO3IL@oRIsrtaIg939BUWZeiQaIqREdbaijYBSroxBtrKNgEhurqfkfAA "Python 3 – Try It Online")
# [R](https://www.r-project.org/), 12 bytes
```
Matrix::expm
```
[Try it online!](https://tio.run/##K/qfZvvfN7GkKLPCyiq1oiD3f5pGLpirYWhlomMEhCGamv8B "R – Try It Online")
# [Julia](http://julialang.org/), 3 bytes
```
exp
```
[Try it online!](https://tio.run/##VU85DsMwDNv1Co7JICB0nOstRYcA7ZAiCIIeQPp6V3K8dBFpiaTkx2ddZh4p3Y893ZbXvs7fynh1ESJIiyjXupb9uWzvdatq@ddoixYTlBF0qpxAeps9rGqwVg8O0AGM4g/lqdN4AkNGH05wXhQIjdXRwCZd3qEWFHOixbmKPkPZM57GYhtFe3QoDqIxtMv8DGOe14B2rBH/YvoB "Julia 1.0 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes
```
-©‘+³æ*‘ɼ¤÷®!¤¤$ÐL
```
[Try it online!](https://tio.run/##y0rNyan8/1/30MpHDTO0D20@vEwLyDi559CSw9sPrVM8tOTQEpXDE3z@//8fbWiko2BooaOgaxqroxCta2gM5IKwOYgLYuma6SgYxQIA "Jelly – Try It Online")
-5 bytes thanks to caird coinheringaahing
This is probably the least Jelly-like Jelly answer ever. Goes for unbounded precision, even though 1/256! (which is what caird coinheringaahing's solution does) is definitely enough in practice.
This only terminates due to limited precision. If we had infinite/unbounded precision, this would never stop running. It basically just keeps adding terms until the result stops changing, which means we've hit the precision limit.
Or actually, this is more cursed:
# [Jelly](https://github.com/DennisMitchell/jelly), 34 bytes
```
ŒṘ“çm(<ÇƤMʂƲṬVḅċñ!żŒȥu¢iİẠẈ“œ4»jŒV
```
[Try it online!](https://tio.run/##AVgAp/9qZWxsef//xZLhuZjigJzDp20oPMOHxqRNyoLGsuG5rFbhuIXEi8OxIcW8xZLIpXXComnEsOG6oOG6iOKAnMWTNMK7asWSVv///1sxLCAyXSwgWzMsIDRd "Jelly – Try It Online")
-3 bytes thanks to Unrelated String.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
æ*÷!}ɗⱮ⁹Ḷ¤S
```
[Try it online!](https://tio.run/##PVG7TcRAEM2niiFFWsmza3vtCigAiQ5ITtcAAcGRXAEEFAAiOiGBkLkTEoEtAsqwGzHvjQ3SfmZn3mfG3lxvtzfzPDyfDx9ntz8P0@vLtDuNx65/upzHz/fx@DbdHa6wsYb9hXzfj6fHaffVd3037JHcrI95LrQQbjGNkrRkwIyJBCs0ZKk1IY5qNdIZdYSNhgr1pFxZcIYafGnUWo1gt4IgAAekmWScNZD@INoq7JIUj7KyRF3Ikk/gst0Y0FDSIzQM6N1odIlqAYsbuL/3DUlLgghqmVlAMWVImrR1ojEMrBjToOMM8b9TsEpXDbbg2IHLR79ZbL2JFUEr76uQv/nYRumKITvKWNPVp1mIK60RzFfpysBfwI3O2IZyTI6FT0S3Xw "Jelly – Try It Online")
## How it works
Basically, we calculate $$\sum\_{r=0}^{255} \frac {M^r} {r!}$$ which is large enough to not have to worry about precision. For one additional byte, we can instead calculate $$\sum\_{r=0}^{10^9} \frac {M^r} {r!}$$, which is, for all intents and purposes, equal to $$\sum\_{r=0}^\infty \frac {M^r} {r!}$$
```
æ*÷!}ɗⱮ⁹Ḷ¤S - Main link. Takes M on the left
¤ - Group the previous links into a constant:
⁹ - 256
Ḷ - Lowered range; [0, 1, ..., 255]
ɗ - Group the previous 3 links into a dyad f(M, i):
æ* - Raise M to the i'th power
} - To i:
! - Factorial
÷ - Divide each element of Mⁱ by i!
Ɱ - Over each i in [0, 1, ..., 255], calculate f(M, i)
S - Sum
```
[Answer]
# JavaScript (ES6), 144 bytes
This iterates until \$1/n!\$ becomes \$0\$ because of IEEE 754 underflow.
```
f=(m,M=m,S=m.map(r=>r.map(_=>j=0)),q=1)=>q?f(m,M.map((r,y)=>r.map((_,x)=>(S[y][x]+=(v=j?r.reduce((t,v,i)=>t+v*m[i][x],0):x==y)*q,v))),S,q/++j):S
```
[Try it online!](https://tio.run/##dY3daoNAEEbv@yQzcdbuxjYtgTFPkCsvFwlitCjZGDdm0ae3o6U3JYVhfjjnY9oiFPfSN7dBXbtzNc81g6MjO8rYxa64gefUr8uJ05Y1IvVskNP@UC/misDThL8enGiUAzI75XbMI4bA7cHHvjo/ygpgoECNCEMUNs42i0Ma9yPzhJueAsqLjPrXKGpxn81ld713lyq@dF9Qg7WadE5rzxFf/lJDW6EJvf1Df7LmKVVGk/oQYUfJ8/iWzCepd1GUSWipRZepdvJXIvM3 "JavaScript (Node.js) – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~85~~ ~~81~~ ~~63~~ ~~61~~ 59 bytes
*Edit: -18 bytes & new approach thanks to [xnor's comment](https://codegolf.stackexchange.com/questions/230784/to-raise-e-to-the-power-of-a-matrix#comment529315_230784), and then -2 more bytes thanks to ovs*
```
function(m){k=diag(nrow(m))+m/2^25;for(i in 1:25)k=k%*%k;k}
```
[Try it online!](https://tio.run/##K/qfWlGQa/s/rTQvuSQzP08jV7M62zYlMzFdI68ovxzI1dTO1TeKMzK1Tssv0shUyMxTMLQyMtXMts1W1VLNts6u/Z9rm5tYUpRZoWFoZaJjpJNUCdRoG6LJBTIZaADXfwA "R – Try It Online")
Non-builtin solution (see [here](https://codegolf.stackexchange.com/a/230786/95126) to save ~~69~~ 47 bytes...).
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 16 bytes
Based on [xnor's comment](https://codegolf.stackexchange.com/questions/230784/to-raise-e-to-the-power-of-a-matrix#comment529315_230784):
>
> An observation I don't see any answers using so far -- \$e^M\approx(I+M/n)^n\$ for large \$n\$.
>
>
>
~~It seems that \$n = 9!\$ is enough for the \$ \pm1 \%\$ requirement of the testcases.~~
Sorry. It turns out that \$n = 9!\$ is not good enough. It exceed the \$ \pm1 \%\$ requirement in exactly one value: the `-39332769.14778117` in the 7th testcase, where \$n = 9!\$ gives `-38882430.43811763`. So I have to use \$n = 99!\$.
```
m->(1+m/99!)^99!
```
[Try it online!](https://tio.run/##ZVPLboNADPyVLSdQcYt5LRQ19576AWkq5ZIqUkEoSg/9esqubWzUy@Idr8cztpjPtyt8zcvFvS4jHFJ8HJ/7/iH7XI/lPM/fv@no4ODm23W6p8nb9JJkA93mdJQwTd5/7jZzWXOa/JiSLHfHY/FU5G49BifRaYUxxGVAqxDVBtW3SChgvIEPiTaEFSfK@KrdCjzTEN7FqiZkAWMbPiMRxdCykFAXC7CPSCHxwAgQH5EihoSnuBXSLcHc2NCnNj0E86w3xKqWxJbingn1YwwTK9TqAjpF2HXHnTcVzZ552OQb7zJv0hi8rN0KnYrXp0TKO4WKd5O73rREhYGrqHMlZnKOofw/UC9tNqmAlosHIMpLc@Oi3sxgV6@OZFAFVdi18RRqowy8oUGuUY@lYZReuzZdrGh1HbaD/AIM0KS8zlq3yGtCmShZOp2y5Q8 "Pari/GP – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/language/), ~~54~~ 53 bytes
I'm still not excellent at golfing, so additions are very welcome. Originally I tried to use only `Sum[MatrixPower[#,n],{n,0,∞}]&`, but that doesn't work for a matrix of only zeros as `MatrixPower` doesn't work on singular matrices.
```
IdentityMatrix@Tr[1^#]+Sum[#~MatrixPower~n/n!,{n,∞}]&
```
It can respond with symbolic results for all inputs, so `{{1,0},{0,1}}` gives an answer of `{{E,0},{0,E}}`, and `{{-2, 16}, {0, 7}}` returns `{{1+(1-E)^2/E^2, 16(E^9-1)/(9E^2)}, {0, E^7}}`.
If floating point answers are wanted `N@` can be added in front of `IdentityMatrix`.
-1 byte, thanks @att.
[Try it online!](https://tio.run/##y00syUjNTSzJTE78H1CUmVcS/d8zJTWvJLOk0jexpCizwiGkKNowTjlWO7g0NxoiFJBfnloUrayTF6ufp6hTnafzqGNebayaQ3W1oY5BrU61gY5hbe3/2P8A "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 31 bytes
```
[:+/!@i.@99%~]+/ .*^:(<99)[:=#\
```
[Try it online!](https://tio.run/##TVRNjxtFEL3Pr6hA0BKy7tRnV5UhUhQkTogD1xCsaPGKRYiNiCPlxF9fXnt9WNmeme6pqn713iv/9dDP9iL0noS3r8bVLb3e0xVdE9Mev92gH3/9@aeHd/uXr569uRtvur/57/3LVzS@@33/7Q/dL97tX3/928OL7XT8dELq97fb8ebPe1pL5PP1HpcnW0J6vTfyJ1sHYTrk9X6SPdk1fJ6TKEnRIQhRRuubtG6HSfokuPB5ToeV04j0FYIgaUJr2Ja5rgfF1lwlDkkIWotVdsUd/PEmer4/rtbzJYIUIAHlfIvzGQcUuhTJR3jrHV3OqcfES1otxEGXDAEzwHiB4RRnDuQMVrbt@OXudHW1/fJ20PHLx@PN6fgH3X8@ffx8otv7f@n27p8Pf9PNh0/HbddTfLobD9epQTvriLAQ5VGt6ay08ygR87YhPNkSpyLYZGbGcPfWAPhKrF2th6RFopZIduZ0rsHhyk0p7Om4DC1UVUOQqqE8i4/AOVW5aQGEIhmJDRQNEaVFfZoY52izs0TZM5CsOqKR4UBfLJE6vZE5k5N2gRhG1S4fExkgGA2yKA6eo9O0aadiPd1Sy0ZqO6w0K6YWcE9Qg3a3XQF4FTrywTjWkGcOPtDyQpUFvOjamXNySsToMPWAY9CxZgk3imVgAUe5lAT6qSE9FRrvBLWQ65kKYOpN2AcRXYIWOfBuBSUHmkmrMWdAkU0YYcENaoHVcSqBbc0pbdNGI4W8ZvpskxglJnrWxxw6N87uYQ1lsNXtnIgVyLgWkHrZYbKjn1TIRLsML6jYlkMtVOEHYzaGI6A@KrLVtpOKBqtZOVg6oCMyoUyaQefhBXYZKApxAZZ0qMBVlaTuSxzoDWpQtqCGQmB2h99Y0S0k05IJxsBVhqDYMgS4V0QOgIaTEGRzmbSAPWYvn26wK0ql1EBXHgt8heCx4RkoDtMaqTgIiaV0KR7A6C6aM2DN1WFpJOSvLBCacyUuC9GyrYIXH/AVLL4saUuRBDHAD@0Y45prsBYJNmEZmRtWM21G5ygDFcsfE1Yrq4CzWkApgQtYU9AbjJV1Hk0YDBMMRm1gA3MBjhujmJgUgHDMgBI4hzkN@5jpCQFATGMP4qHnVdODAMPgD3UEwZowPHhJmC8NUx6I9qI1zDgZxgDric6pCuPvYBl/DlOZF@mO4Uie0GR5bWGCfgHTsUIInjnBMOYBVpsxGd7r4vVXADGBEm6WESAPTjAcCM@121BH3sP/ "J – Try It Online")
Just implements the formula up to 99 terms, which seems to be good enough to be within 1% of the test cases.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 49 bytes
```
≔EθEι⁼κμη≔ηζFφ«≔Eη∕EκΣEκ×ξ§§θπν⊕ιηUMζEκ⁺μ§§ηλν»Iζ
```
[Try it online!](https://tio.run/##ZY67DsIwDEVn@hUeHckMPDYmBAwdkCrBVnWI2kAjkhSatkJFfHswjyIkpuvrx7nOS1nnlTQhLL3XR4dbecYLwVM0webSSuPxRGCFEASlWESfxZKgZ3eoasCDgFs0@iHwcK07XaiX4/Nda4dyr63yeCVYNrEr1BUH5dgzZzghXlmxy2tllWtUgfqbPmLKqrJWugL795/MTEzr0f4j@Q8zIBfRPUpq7RpcSd9gz50Q0jSdEEwzgnRGMM@yLIw78wA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔EθEι⁼κμη≔ηζ
```
Create an identity matrix and save it as the last power series term and also the running total.
```
Fφ«
```
Loop 1,000 times.
```
≔Eη∕EκΣEκ×ξ§§θπν⊕ιη
```
Multiply the last power series term by the input and divide by the 1-indexed loop index to create the next term.
```
UMζEκ⁺μ§§ηλν
```
Add the term to the running total in-place, as the term is now a separate array and no longer shared with the running total.
```
»Iζ
```
Print the final total.
[Answer]
# [Raku](http://raku.org/), ~~118~~ 113 bytes
```
{[»+«] (flat((1,0 xx$_)xx$_).rotor($_)[^$_],{cross(with=>(*Z* *).sum,@^x
»/»++$,[Z] $_).rotor($_)}...*)[^99]}
```
[Try it online!](https://tio.run/##VYxNCsIwEIX3nmIWRSZpjI31pwUtnsMSpahFwRpJKlZKT@QRuuvF6ii4cDEf34M373a0l3lfPGGYw6qv0671u5cGzC9ZiahEAFXl7dgX0prSWCRLt95Oi3pvjXP4OJenVYJ8w4Ez6e6FWG@rQdeOacv3RLrR8PfcSCk5TcSxbnqXPUEW2Q05Fe7XA6rjKGQMcmMhx3QZgYphEhATAUvykYogIqpPXpDMQS1@WYVkM7opTBLN@jc "Perl 6 – Try It Online")
* `[»+«]` reduces the following sequence of 99 matrices (each a list-of-lists) with elementwise addition. (99 seems like more than enough terms for any practical purpose.)
* `flat((1, 0 xx $_) xx $_).rotor($_)[^$_]` is the starting identity matrix.
I found a somewhat concise way to do matrix multiplication on lists-of-lists `@m1` and `@m2` in Raku:
```
cross(with => (* Z* *).sum, @m1, [Z] @m2).rotor(@m1)
```
`cross` here is the cross product operation. `(* Z* *).sum` is an anonymous function applied to each combination of rows from `@m1` and columns from `@m2`, zipping them with multiplication and then summing. `[Z] @m2` is a tricky way to get the transpose of the right-hand matrix `@m2`. That gives just a flat list of numbers, which `.rotor(@m1)` turns back into a square matrix.
`@^x` is the previous matrix in the series, which I divide elementwise by a steadily increasing anonymous state variable with `»/» ++$` before multiplying by the input matrix `$_` to get the same effect as dividing by the factorial in the original formula.
] |
[Question]
[
Suppose denominations of banknotes follow the infinity [Hyperinflation sequence](https://codegolf.stackexchange.com/q/210671/44718): \$ $1, $2, $5, $10, $20, $50, $100, $200, $500, $1000, $2000, $5000, \cdots \$. How many banknotes are required, at minimum, to pay a \$$n\$ bill?
Consider Alice needs to pay \$ $992 \$ to Bob. It is possible for Alice to use 7 banknotes \$ $500, $200, $200, $50, $20, $20, $2 \$ to pay the bill, but that uses a lot of banknotes. We can see that a better solution is: Alice pays 2 banknotes (\$ $1000, $2 \$), and Bob gives her \$ $10 \$ in change. So, we only need 3 banknotes here.
## Formal Definition
Banknotes follow an infinite sequence \$b\_i\$:
$$ b\_n=10\cdot b\_{n-3} $$
with base cases
$$ b\_1=1, b\_2=2, b\_3=5 $$
When Alice pays \$ $x \$ to Bob, Alice pays \$ a\_i \$ banknotes with denominations \$b\_i\$. \$ a\_i \in \mathbb{Z} \$ And
$$ \sum a\_ib\_i=x $$
\$ a\_i \$ may be negative which means Bob gives Alice these banknotes in change.
You are going to calculate:
$$ f\left(x\right)=\min\_{\sum a\_ib\_i=x} \sum\left|a\_i\right| $$
## Input / Output
Input a non-negative number representing the amount of money to pay. Output the minimum number of banknotes required.
## Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"): Shortest codes in bytes win.
* Your program should be able to handle inputs \$ 0 \le n < 100{,}000 \$ at least. Your algorithm should work for arbitrary large numbers in theory.
* As this questions is only focused on [integer](/questions/tagged/integer "show questions tagged 'integer'")s, floating point errors are not allowed.
## Testcases
```
Input -> Output
0 -> 0
1 -> 1
2 -> 1
3 -> 2
4 -> 2
5 -> 1
6 -> 2
7 -> 2
8 -> 2
9 -> 2
10 -> 1
11 -> 2
12 -> 2
13 -> 3
14 -> 3
15 -> 2
16 -> 3
17 -> 3
18 -> 2
19 -> 2
20 -> 1
40 -> 2
41 -> 3
42 -> 3
43 -> 3
44 -> 3
45 -> 2
46 -> 3
47 -> 3
48 -> 2
49 -> 2
50 -> 1
90 -> 2
91 -> 3
92 -> 3
93 -> 3
94 -> 3
95 -> 2
96 -> 3
97 -> 3
98 -> 2
99 -> 2
100 -> 1
980 -> 2
981 -> 3
982 -> 3
983 -> 4
984 -> 4
985 -> 3
986 -> 4
987 -> 4
988 -> 3
989 -> 3
990 -> 2
991 -> 3
992 -> 3
993 -> 3
994 -> 3
995 -> 2
996 -> 3
997 -> 3
998 -> 2
999 -> 2
1000 -> 1
1341 -> 6
2531 -> 5
3301 -> 5
4624 -> 6
5207 -> 4
6389 -> 6
6628 -> 7
6933 -> 6
7625 -> 6
8899 -> 4
13307 -> 7
23790 -> 5
33160 -> 7
33325 -> 8
40799 -> 5
55641 -> 7
66472 -> 8
77825 -> 6
89869 -> 6
98023 -> 5
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~87~~ ~~80~~ 68 bytes
```
f=lambda x:x>1and min((y%10)**6%305%3+f(y/10*x/y)for y in[x,-x])or x
```
[Try it online!](https://tio.run/##tZBNasMwEIX3PcVsApKrEklj/bWkFzFeuKRODY0S3Czk07sjtQTTlBQCheF5hpHe@6zjdHo7RD3P/ea9279sO0iP6Vl1cQv7ITI2rZTkVWVXKM0K73s2rZWs0nri/WGECYbYJPGQWk5Tmrv4ARtoejZwyPuB9jB2cffKtOLtExzHIZ5YOUbnpABVSpc6Nz9GLLVs8rYVQD787kpmLYX5JfbsdLNxkELJ/3H22fqqd11q2SyjbkhuFNb5sQ2SIkrS2mqyNlo6ARZ9ILXakwYkU2e1EeB9CO0FpqVrpWyhI3VF8/gXBeY4jY6elziULR/MWbV0gSCMsZnU2trRXznnC0fwlnb0choveVyBIfWL5ovHfPPMnw "Python 2 – Try It Online")
*-7 bytes thanks to @tsh, and -12 bytes thanks to @dingledooper. Thanks to everyone else for their own golf suggestions.*
Instead of tearing down the banknotes in the top-down way, this solution builds up the answer from the bottom. Since the number of banknotes needed to pay \$10n\$ is exactly the same as that for \$n\$, we can tear down the banknotes from the one's digit in the following sense:
* If the one's digit is 0, remove the 0 and recurse.
* Otherwise, consider two ways to fulfill the one's digit:
+ Alice pays `n%10` to Bob, and then Alice pays whatever banknotes are needed to pay `floor(n/10) * 10`. Recurse with `floor(n/10)`.
+ Bob pays `10-n%10` to Alice, and then Alice pays whatever banknotes are needed to pay `ceil(n/10) * 10`. Recurse with `ceil(n/10)`.Then we can evaluate the two cases and take their minimum.
In the code, an infinite recursion happens if we don't special-case `x=1` as well as `x=0`, because the ceiling of `1/10` is still 1.
[Answer]
# [Haskell](https://www.haskell.org/), 87 bytes
```
a=0:1:drop 2(zipWith min("0112212222"!a)$"1222212211"!tail a)
s!l=[i+read[j]|i<-l,j<-s]
```
[Try it online!](https://tio.run/##RZFNi9swFEX3@hWyySKh40Hf0hvi7LrrvosQGEM8HU0dOziGQul/T20r0TVeHC7v6ejan83td9t193tTizf5dh6HK1fbv/H6M06f/BL7bSmkVGp@lSqLZrcpV1wiWRZTEzve7Nit6Opj/Da2zfn4dfoX91X38rWvbqf7pYl9fR4Y58f4Mpz21aW58mXu9c8wnm@vH7Gb2nH73g/T9669vJfVodztN4df7fQj9u28dx1jP22aooh1vZyznHjn8yN4deCCLSgXlCsqoF5QrWiAFgMOqQcGIGWUIq9JiVQBV5te0QAtBhxSD4RNwqZgMyKnRuY1o4AQG4gNxAZiA7GB2EBsISaICWKCmCAmiAligpggJogpi6XIYgpZTCGLKSjgKjYrGqDFgEPqgQEDlBE1CTUJNQk1CTUJNQk1CTUJNSnXnFs@a0qd/qZjXFm9omVca/FE45R5DFglni2cTlefU@fUqvAzktaP1DtlHxhCEhsm53N9mlXap8aWaS2dSKnWOq0FZoRPa5ZZ69IlPXPOeJUGvA9PRZi/9OM6819T6x3sfw "Haskell – Try It Online")
`a` is the whole infinite sequence.
This solution combines the fixed point approach of [my answer to the previous challenge](https://codegolf.stackexchange.com/a/223318/82619) with [Bubbler's excellent observation](https://codegolf.stackexchange.com/a/223538/82619). ~~Coincidentally, his answer and mine also have the same exact length.~~
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~28~~ 21 bytes
```
DJŻ⁵*×þ⁵ÆḌ¤ạ)F
ÇẠпL’
```
Takes input as singleton list. [Try it online!](https://tio.run/##ATgAx/9qZWxsef//RErFu@KBtSrDl8O@4oG1w4bhuIzCpOG6oSlGCsOH4bqgw5DCv0zigJn///9bOTgzXQ "Jelly – Try It Online")
–7 per [caird coinheringaahing](https://codegolf.stackexchange.com/users/66833/caird-coinheringaahing).
Based on ref implementation; lists everything that's 1 away, then 2 away, etc. Adding a Q to the end of the first line makes it go slightly faster.
### How?
```
DJŻ⁵*×þ⁵ÆḌ¤ạ)F - monadic link; takes integer array
) - for each integer
DJ - construct [1, ..., number of digits]
Ż - prepend 0
⁵* - exponent with base 10 (vectorizes)
×þ - outer product with
⁵ÆḌ¤ - proper divisors of 10; we get banknote
ạ - absolute difference (vectorizes)
F - flatten
ÇẠпL’ - main link; takes integer array
п - while
Ạ - all integers nonzero,
Ç - call previous link
L' - take length minus 1
```
[Answer]
# JavaScript (ES6), ~~78~~ 77 bytes
*Saved 1 byte thanks to [@dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)*
This is heavily based on [Bubbler's answer](https://codegolf.stackexchange.com/a/223538/58563). Similarly to [my answer to a previous challenge](https://codegolf.stackexchange.com/a/223320/58563), it uses a formula instead of a lookup table.
```
f=n=>n<2?n:Math.min((g=(n,o)=>(n%10)**6%305%3+f(o/10|0))(n,n),g(10-n%10,n+9))
```
[Try it online!](https://tio.run/##TZFLctNAFEXnWkVPUuqOP@m/9AJyRmEGkwwJA2HLjim7ZWSFggJ2QFUmDGEfrCcbYAmmLdm6aKA6enWfTl/pQ/mp3M@b9a6dhHpRHQ7LIhSz8FLfhOvXZfsw3a4D56uCh3EtihkPF0qKy0t/YaS7MKMlr6@U/CaFiIEgxiuu5OSYGYcRCXFoqo@P66bi6XKfimlTlYtX60119yXMuRTTtr5rm3VYcTHd7zbrlqf3IcaWdXNbzh/4nhUz9jVh7C0LY1Z93lXztlqwd6xg@@m2bGPk6n4xulqJ@LTjbx6376tGvIgL8zrs60013dQrHv7X7MrFbVhwJ9iIpWwyi7cR400VVWzJg@jnGBbQ3rD075@n518/4z1l1yx9/v0jFVH3XRxYvOTxdTI5ojqi6lADzRF1hxboEPCYZsAcSAMqOawphakGdjbToQU6BDymGRA2BZuGzcphatWwZjUQYguxhdhCbCG2EFuIHcQEMUFMEBPEBDFBTBATxAQxDWIlBzHlg5jyQUy5BnZi26EFOgQ8phkwR4AGRE1CTUJNQk1CTUJNQk1CTUJNGmrGlueayvR/0ydMO9OhS5gx8ozWa3sKOC3PLbzpjx6n3utOkUUkY07TzGt3wjzvxTZR8b1Zn9Um6xu7xBjlZT81xvRreWJl1q@5xDnfHzJLvLeZ7gNZlp8VefzSp@PEv6a7M7h/ "JavaScript (Node.js) – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 98 bytes
```
f=function(a,b=a%%10,c=a%/%10,e=c(0,1,1,2,2,1,2,2:4))`if`(a<2,a,min(e[b+1]+f(c),rev(e)[b]+f(c+1)))
```
[Try it online!](https://tio.run/##PY7RCoMwDEXf/YrAEBIszDrZg6z7ERlYNQXZbKV2g@3nu@qDHMi9CYF7fey1fVoXeFXRKPO2Q5icRS16pfNclmJIet4MqwFLIRNVYp9NTdRNpkN9q4QW82SR276Qj8LgQMLzB5nafl8LSUTxBCkpgLzUEtQdrnDEg2UeecyOA25PlJ3AeDfDj72D4KAqm2zVy/L6YqrTVCUJQ/EP "R – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 102 bytes
```
^
;$'¶_;
T`d`Rd`.+$
{%0`\d
*
([_;]*)(.*)¶([_;]*)
$1,$3_,$2¶$3,$1_,
+`;_(____|_|)
_;
%O`_*;
)`,.*,
\G_
```
[Try it online!](https://tio.run/##LY9NTgMxDEb33zlSMTMdVeM4P7bmAF0iIXYUEqSyYMMCsaPn6gF6scGuiJJIiZ9fvnx//Hx@vdO2G459e8MaHm7XtuK5n/vTuR/2Ab@7pZ/OmDC8tPV1GofDNN6u/wcEmgO3OcTbNfAcqM3Y97UNzcalXUaYbPfY27Ri7PNhmoHTsW3bAkIEIyGjoEKgILskUAQxKIEyqIAqSECKuCDZJKSIZI0JKSMVpIokSIq8QG0SNEIZmqAZWqAVanr3W1l8GSMGiVFimBgnBoqThooabpy7XOY217nPhW68K@9OS80WK2YmMC8WsET7VlwqCpuqlCgoyoxaYoaItxlYEbnaM8xUfGcrpqVaNediwlJSjahVvMnyqYeP/Ac "Retina – Try It Online") Link includes test cases. Explanation:
```
^
;$'¶_;
T`d`Rd`.+$
```
Create a working area with the following values: a) the number of notes used if Alice has not paid Bob enough yet; b) the amount Alice still needs to pay Bob; c) the number of notes used if Alice has overpaid and needs Bob to pay her back; d) the amount Bob still needs to pay back to Alice, minus 1.
```
{`
)`
```
Repeat until the full amount has been paid.
```
%0`\d
*
```
Convert the next digit of each outstanding amount to unary.
```
([_;]*)(.*)¶([_;]*)
$1,$3_,$2¶$3,$1_,
```
Calculate the two ways Alice can under or overpay Bob, depending on whether she under of overpaid Bob last time. If she underpaid last time, she can pay the current digit to remain underpaid, or one more to become overpaid, while if she overpaid last time, Bob can repay the complement to leave Alice overpaid, or one more to make her underpaid again.
```
+`;_(____|_|)
_;
```
Calculate the number of additional notes needed to pay each potential digit.
```
%O`_*;
,.*,
```
Delete the larger number of notes.
```
\G_
```
Convert the number of notes needed for (now exact) payment to decimal.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 80 bytes
```
n=>g=(i=n)=>Math.min(f(i)+f(i+n),i?g(i-1):n);f=n=>n&&(n%10)**29%3571%4+f(n/10|0)
```
[Try it online!](https://tio.run/##TZQ9cptAGIZ7TrGNza5lof1fPnuQK6tLGpdxCiIhmURaCOBM/nyDzKRJmdwj5/EFcoMoK5D4QrHz8Oldnn1hRm/zD3m7bMq6m/pqVewX2d5n801Gy8yzbP4i7x6SXenpmpZsEpaJZ5flzYaWU8GuPLteZyHuz8@pPxOcXVxIOFPGiTMdwn4m@FfO9k3x/rFsChqv25glTZGvFuW2uPvkl5SzpKvuuqb0G8qStt6WHY3vfYitq@Y2Xz7QlmRz8iUi5BXxl6T4WBfLrliR1yQjbbLLuxCZ3a8msw0LdzV9@bh7UzTsOmxYVr6ttkWyrTbU/6@p89WtX1HDyITEZDoPy4TQpggqsqCeUTb8guMMxTck/vP7@/PPH2GNyRWJn399i1kQPrE9CRc/PJBHBxQHFD1KRHVA2aNGNBiwOHWIKSKMKPi4TQicSsTepnrUiAYDFqcOEW0CbRJtmo9TLcZtWiKiWKNYo1ijWKNYo1ij2KAYUAwoBhQDigHFgGJAMaAYUAyjWPBRDOkohnQUQyoRe7HuUSMaDFicOsQUAzAi1gSsCVgTsCZgTcCagDUBawLWhLFmaHmqKdTwNW1EpFE9mogoxU@ordTHgJH81MKq4ehhaq3sFS4gKHWcOivNEdN0EOtIhOe6ISuVGxqbSClh@TBVSg3b0khzN2wzkTF2OKSLrNVODgHn0pMiDW/6eJzw1WR/BvO3qrsy/CHsp9O2y5fvpm35ucigv/4B "JavaScript (Node.js) – Try It Online")
I know there's better answer currently but this is what [answer to last question](https://codegolf.stackexchange.com/a/223320/) directly lead to
] |
[Question]
[
A ripoff of [this challenge](https://codegolf.stackexchange.com/q/207404/89459). Go upvote it!
# Objective
Given a rational number amongst \$[0,1]\$, apply the [Cantor function](https://en.wikipedia.org/wiki/Cantor_function) to it and output the rational number that's produced.
# The Cantor function
The Cantor function is continuous everywhere and constant [almost everywhere](https://en.wikipedia.org/wiki/Almost_everywhere), but has an average slope of 1:
[](https://i.stack.imgur.com/cauCV.png)
The Cantor function \$f(x)\$ can be expressed as a limit \$f(x)=\lim\limits\_{n\to\infty} f\_n(x)\$ of a sequence of functions \$f\_0, f\_1, f\_2, \dots\$, which are defined recursively as:
\$f\_0(x)=x\$
\$f\_{n+1}(x)=\left\{\begin{matrix}\frac{1}{2}f\_n(3x)&x\in[0,\frac{1}{3})\\ \frac{1}{2}&x\in[\frac{1}{3},\frac{2}{3})\\ \frac{1}{2}+\frac{1}{2}f\_n(3x-2)&x\in[\frac{2}{3},1] \end{matrix}\right.\$
[](https://i.stack.imgur.com/JpLpm.gif)
Your task is to compute \$f(x)\$ for the rational \$x \in [0,1] \cap \mathbb{Q}\$ given as input.
# How?
Though this task might seem *impossible*, this is actually possible, for the Cantor function is [computable](https://en.wikipedia.org/wiki/Computability).
A step-by-step solution for \$x \in \mathbb{R}\$:
1. Ternary-expand \$x\$ to \$0.t\_1t\_2t\_3\cdots\$.
2. Write "0.".
3. Set \$n=1\$.
4. If \$t\_n = 1\$, write "1" and halt.
* Otherwise, if \$t\_n = 0\$, write "0", increment \$n\$, then continue doing step #4.
* Otherwise (\$t\_n = 2\$), write "1", increment \$n\$, then continue doing step #4.
5. Parse the resulting string as a binary expansion of a real number.
As \$x\$ actually is in \$\mathbb{Q}\$ in this challenge, you should exploit the fact that the ternary expansion of \$x\$ repeats. It follows that the output is also in \$\mathbb{Q}\$.
# Examples
$$
\begin{array}{r|c|c|c|c|c|c|c|c|c|c}
x & 0 & ½ & ⅓ & ¼ & ⅕ & ⅚ & 1 \\ \hline
\text{Ternary expansion of }x & 0.\overline{0} & 0.\overline{1} & 0.1\overline{0} & 0.\overline{02} & 0.\overline{0121} & 0.2\overline{1} & 0.\overline{2} \\ \hline
\text{Binary expansion of } f(x) & 0.\overline{0} & 0.1 & 0.1 & 0.\overline{01} & 0.01 & 0.11 & 0.\overline{1} \\ \hline
f(x) & 0 & ½ & ½ & ⅓ & ¼ & ¾ & 1
\end{array}
$$
# Rules
* Invalid inputs fall in *don't care* situation. In particular, you don't need to deal with numbers outside of \$[0,1]\$.
* Input and output must be exact rational numbers. If your language doesn't natively support rational number arithmetic, use a pair of integers.
[Answer]
# JavaScript (ES7), ~~141 ... 128~~ 125 bytes
*Saved 2 bytes thanks to @Ada*
Expects the fraction \$p/q\$ as `(p)(q)`. Returns \$P/Q\$ as `[P,Q]`.
```
p=>q=>(k='0b'+(n=0,g=p=>(r=n-g[p])?'':p/q&1||[p/q>>1]+g(p%q*3,g[p]=n++))(p),r?[((k>>r)*(m=2**r-1)+(k&m))*2,m<<n-r]:[+k,1<<n])
```
[Try it online!](https://tio.run/##bc5BbsIwEAXQfe9RMt922jhAQxBjDhJlQSlEbYjjGMSKu6dmiezVjJ6@/szf4X64Hv2vu@V2/DnNZ54dm4kN9ZwV35kky4XqOCB5tnnXuBb7LNu6z2mhH48mTGN0Kzty75NYqmeArZQAOSi/b4h6YzwEDVwK4XMNSf1iAESpht3O5r7dNrJXOuwt5uNor@Pl9HEZOzpTAdLA2ytqUJnCZQpXKVxHuAZ9pZLJ69WmingV7teRbkJD/GtZgeq4uQ4VBTD/Aw "JavaScript (Node.js) – Try It Online")
## How?
### Ternary and binary expansions
```
k = // build a binary string
'0b' + ( // append the binary prefix
n = 0, // n is a bit counter
g = p => // g is a recursive function taking the numerator p
(r = n - g[p]) ? // if p was already encountered, we have a repeating
// pattern, whose length is stored in r; in that case:
'' // stop the recursion
: // else:
p / q & 1 || // if p/q = 1, append a '1' and stop the recursion
[p / q >> 1] + // otherwise, append '1' if p/q = 2 or '0' if p/q = 0
g( // append the result of a recursive call to g:
3 * (p % q), // update p to 3 * (p modulo q)
g[p] = n++ // store the position of p in g and increment n
) // end of recursive call
)(p) // initial call with the numerator provided in the input
```
### Turning the binary expansion into a decimal fraction
If \$r\$ is *NaN* after the first step, it means that the binary expansion has no repeating pattern. In that case, the numerator is \$k\$ and the denominator is \$2^n\$.
If \$r\$ is defined, we compute the following bitmask:
```
m = 2 ** r - 1
```
The numerator is:
```
((k >> r) * m + (k & m)) * 2
```
and the denominator is:
```
m << n - r
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 15 bytes
```
CantorStaircase
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@985Ma8kvyi4JDGzKDmxOPV/QFFmXkl0moK@g0K1gY6Cob4RiDAGESYgwlRHwVTfDMiqjbX@DwA "Wolfram Language (Mathematica) – Try It Online") Just a built-in function.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~120 119~~ 117 bytes
*-2 bytes thanks to @Neil!*
```
f=lambda p,q,P=0,Q=1,*R:p in R and(P-P//(i:=1<<R.index(p)+1),Q-Q//i)or f((d:=p*3//q+1)%2*(p*3%q),q,P*2+d//2,Q*2,p,*R)
```
[Try it online!](https://tio.run/##fZDBTsMwDIbvfQprqFJS0mVpNwYT5ch52xUhVJZURLRplmQSe/rhtBuDCyf/duwvv22P4aM35b11p1NTtXX3LmuwbM/W1YxtKsGy7cqCNrCF2kiyztecE72qxOPjdqqNVF/E0ltB2SbfcK5p76AhRK4qm5Wc7/ElLTKCSbqnkZoVt5Lzgm2yglmE01Pj@g4aV@@C7o0H3dneBXg@F5Jz7o8@SRqkt9qo6AcLUx@kNqsE4AacqiWW7SFgOsS3yGSgvqzaBSWhgq625MJlA2jqbasDmeRPE0px0DLYY@N1fmoOnXJ16B37XZXK9J02sY5Tg4Hdh9p9og1/aKOFUSCrIXjNyNYNhKNVZHyhoHFXE6L7S/fAxpGLx3MrAxHnVevVv93ZmRz3cIgmkzRfeMifIM3FzMNL6l8nkAL5fZ7LF3@Y1c/VKD3NuIgMDIngRZQYUJZXOR9liXIxynmy4HdRlijFSBADYXm/jMmSL0SRzHn5MHaJ@Tc "Python 3.8 (pre-release) – Try It Online")
Same idea as below, but as a lambda function instead.
---
# [Python 2](https://docs.python.org/2/), ~~133 131 125~~ 122 bytes
*-3 bytes thanks to @Neil!*
```
def f(p,q,P=0,Q=1,*R):
if p in R:i=1<<R.index(p)+1;return P-P/i,Q-Q/i
d=p*3/q+1;return f(d%2*(p*3%q),q,P*2+d/2,Q*2,p,*R)
```
[Try it online!](https://tio.run/##fZDNbsIwEITveYoVVaQkOBjnp7SUcOwZuFZVhbAjrBLH2EaCp6frhBR66WnH493P49UXt29Vdr1yUUMdaXIkq2pK1hUjySaeByBr0CAVbOayYovFZiIVF@dIx2P2ZoQ7GQWrdEUlWadrKgPglU5yerzf1hEPsyRCNzzGHp9kY04zsk4yov0j19q0DdRmu3OyVRZko1vj4P1mBLezvdggqFsDB6mET4TGxDouFaaEJzBiy9HWJ4fHrn55JgFx1mLnBIcKmq2OBi7pQBOrD9JFo3Q5imMc1ASO2Hifn6hTI8zWtYY8ulyotpHK@zjVBdjtxe4bY9jTwUfoBbK6rXo2rtJdtIj6mxgk/lU5n37o7tg4MmS8tRJgfl4crPi3O7mR/T8MomEUpqWFdAlhyqYWPkL7OYIQosf1DE/8YVa/W4uvU8o8AkvAaOYlFpT5XRa9zFGWvSyCkj57maNkPYF1hNnLzB9mtGRZUND8te9ixQ8 "Python 2 – Try It Online")
A recursive function that takes input as 2 integers `p` and `q`. Outputs 2 integers `(P,Q)` representing the fraction \$P/Q\$ (might not be reduced to lowest term).
### Explanation
This solution follows the suggested algorithm in the question.
**Ternary expansion**
To ternary expand `p/q`, we divide `3p` by `q`, resulting in the quotient `d` and remainder `r`. `d` is the next ternary digit. To get the digits after that, we simply recurs on `r/q`.
```
d, r = p*3/q, p*3%q
```
**Get the binary result**
`P/Q` represents the current result, with `Q` always be a power of 2.
* If `d == 1`, we append 1 to the result, aka `(P*2+1, Q*2)`. To stop the recursion, we set the remainder to 0: `f(0, q, P*2+1, Q*2, ...)`
* If `d == 0`, we append 0 to the result and continue: `f(r, q, P*2, Q*2, ...)`
* If `d == 2`, we append 1 to the result and continue: `f(r, q, P*2+1, Q*2, ...)`
We can compress all cases into a single expression. For additional golf, first we increase `d` by 1: `d=p*3/q+1`. The 4 cases above become:
```
return f(
d%2*r, # 0 if d==2, else r
q,
P*2+d/2, # P*2 if d==1, else P*2+1
Q*2,
...)
```
This happens to also work for when the input fraction is 1 (`p == q`), in which case `d == 4`, and `f(0, q, 2, 2, ...)` is called, which results in the fraction `4/4`.
**Termination**
The function has to terminate once it finds a repeating block of digits in the ternary expansion. In order to do this, we keep track of all previous numerators in the tuple `R`. After each iteration, we prepend `p` to the list of seen numerators: `f(..., p, *R)`.
At the start of each iteration, we check if `p` is in `R`. If so, every digit after that will be repeated. The length of the repeated block of ternary digits can be calculated from the position of the previous occurrence of `p`: `n = R.index(p)+1`
Let's say that currently, the binary form of `P` is \$XXXabc\$, where \$abc\$ is the repeated block of digits (aka `n = 3`). Then
$$P' = XXXabc.abcabc... = \left(P- \left\lfloor{\frac{P}{2^n}}\right\rfloor \right)\frac{2^n}{2^n-1}$$
and the final result is:
$$\frac{P'}{Q} = \frac{\left( P- \left\lfloor{\frac{P}{2^n}}\right\rfloor \right) 2^n}{Q(2^n-1)}$$
Edit: @Neil found a better simplification:
$$\frac{P-\left\lfloor\frac{P}{2^n}\right\rfloor}{Q-\left\lfloor\frac{Q}{2^n}\right\rfloor}$$
[Answer]
# [Python 2](https://docs.python.org/2/), ~~347~~ 337 bytes
```
exec"B=L,d:B(x/3,d-1)+[x%3]if d else[];V=L:0if x%3else 1+V(x/3);r=L,b,n=1:(3**n-1)%b and r(x,b,n+1)or[n,B((3**n-1)*x/b,n)];F=L:x>[]and(x[-1]>0)+2*F(x[:-1])".replace("L","lambda x")
def c(a,b):
v=V(b);b/=3**v;N=B(a/b,v);n,R=r(a%b,b);D=N+R
if 1in D:d=D[:D.index(1)+1];print F(d),2**len(d)
else:print F(N)*(2**n-1)+F(R)or a,2**v*(2**n-1)
```
[Try it online!](https://tio.run/##ZZJhi@IwEIa/91cMBTFps2pa79xLibAihQORwwW/lH5Im8gJbiq1JzmW/e3eNL31hCslzTzzzkze0PPv7mdjk9vNOFOHK7lhWqyIm6ZMP3EaF26UlscDaDCniynKbC83YoYAeU@Ax/teTbMWSytmJRckjSKLxaMKlNXQEtcnYk6btrBsRT7zkZsip2WWY0@3LEpUE1c88XI5o3ES5RgIjGg4ac35pGpDwk3IwpN6q7QCF9JAmwPURLGKigCuck8qmlVTiQOu2VauiMIJV5pZtpMtUaMKhdlabuNdAOiBHy2shZbrQqwnR6uNI2iZl1lrul@thZxoypIoOhmLu8BfgbjntjQiyeAkzskO3YHq1dc7vtXqYi4goQgAHzJjwBn0K2UDwTDxMHkg6X9k7kn6QL54Mv8kGH71hfMHzd/3gSyeF7hgNb93x9bpt2Hmv9o@WvRDUcuTZxqUwQHtWQaagTX4MYB35@0JX2MbhA1arUmvoh623rw1UtrG/woat3rYjn@8vL6OAbuO85fvmwyMO5u6M1rA@8f0/WM8wYlvqiPDuKHhuT3ajoReAHI5KHEN7@LhhP4wrJ9P6e0P "Python 2 – Try It Online") (modified to return statements for verification)
Takes and returns pairs of integers (numerator, denominator). The input pair must be relatively prime.
### How it works
The program separately identifies the repeating and non-repeating portions of the ternary representation of `a/b`, then splits into 2 cases:
1. If there is a 1 in either portion, then the numerator is (converted from binary with `2`→`1`) the concatenation of the two portions up to the 1, and the denominator is 2 to the power of the length of that section
2. If there is no 1, then the number retains the repeating portion, so in base 2 (after converting 2s to 1s),
$$\frac{a}{b}=0.x\_1x\_2\ldots x\_k\overline{y\_1y\_2\ldots y\_n}=0.\mathbb{x}\overline{\mathbb{y}}$$
Then $$\frac{a}{b}=\frac{1}{2^k}\left(\mathbb{x} + \frac{1}{2^n-1}\mathbb{y}\right)=\frac{(2^n-1)\mathbb{x}+\mathbb{y}}{(2^n-1)(2^k)}$$
```
# Most-significant ternary digit first
base3 = lambda x, d: base3(x//3, d-1)+[x%3] if d else []
# Largest exponent of a power of 3 that divides x
v3 = lambda x: 0 if x%3 else 1+v3(x//3)
# Base 3 representation of a/b as 0.xyz repeating, where b contains no factors of 3
def rep3(a,b,n=1):
if (3**n-1)%b==0:
return n, base3((3**n-1)*a//b,n)
else:
return rep3(a,b,n+1)
# Base 2 to int, including converting '2's to '1's
from_base2 = lambda l: eval('0b0'+''.join(map(str,l)).replace('2','1'))
def cantor(a, b):
# Extract the non-repeating portion of the ternary expansion of a/b
v = v3(b)
b //= 3**v
non_repeating = base3(a//b,v)
# Repeating portion
n, repeating = rep3(a%b, b)
digs = non_repeating + repeating
if 1 in digs:
# Take only the part up to/including the first 1, and use it as a binary decimal
d = digs[:digs.index(1)+1]
return from_base2(d), 2**(len(d))
else:
x = from_base2(non_repeating)
y = from_base2(repeating)
# `or a` accounts for the a=b=1 case, which gets treated otherwise as 0.0
return y+x*(2**n-1) or a, 2**v*(2**n-1)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~92~~ ~~77~~ 62 bytes
```
NθNη≔⟦⟧ζW¬№ζθ«⊞ζθ≧׳θ⊞υ÷⊕÷θη²≔∧⊖÷θη﹪θηθ»IE⟦↨υ²X²Lυ⟧⁻ι÷ιX²⊕⌕⮌ζθ
```
[Try it online!](https://tio.run/##fZA9a8MwEIbn@FdoPIG6uDSLpzShYKiDCd1CB9U@rANbivXhgEN/uyvHofVUbY/03um5q5S0lZHtNOX6EvwxdF9ooedZsmYVeeccNRrOn4KNEa@KWmRwNB72JmgPo2A955zdkk0ZnFo4SzaFvCylJ2qUhw/q0An2/Hi9R4NgufYHGqhGyHVlsUPtsYa/214wxblgKZ@rHi47XcMB/4sXpg6t@cX5y@@ktBR999J5iHJwfpUOZ4c0JkpzjfOmgr2jbnxU4zwOXJAODmitSavsWvmNotQJB7Sx6ciXpdxPNk0vbDs9De0P "Charcoal – Try It Online") Link is to verbose version of code. I/O is a pair of integers. Does not reduce the output to lowest terms, in particular `1 1` outputs as `2 2` as that needed fewer hacks than before, which helped to save 15 bytes. Explanation:
```
NθNη
```
Input the numerator and denominator.
```
≔⟦⟧ζ
```
Start a list of partial remainders.
```
ζW¬№ζθ«
```
Repeat while the current partial remainder has not been seen before.
```
⊞ζθ
```
Push the current partial remainder to the list.
```
≧׳θ
```
Triple it.
```
⊞υ÷⊕÷θη²
```
Push the next bit of the result. (Note that an input of `1` is treated as the illegal ternary `0.3` and massaged into the illegal binary `0.2`.)
```
≔∧⊖÷θη﹪θηθ
```
Get the next partial remainder, unless the current ternary digit is `1`, in which case the next partial remainder is zero.
```
»IE⟦↨υ²X²Lυ⟧
```
Get the raw binary fraction.
```
⁻ι÷ιX²⊕⌕⮌ζθ
```
Adjust it for the recurring part of the binary fraction. (In the case of a terminating fraction, this is detected a bit after the fraction terminates, effectively doubling the numerator and denominator, but the adjustment here simply halves both values again.)
] |
[Question]
[
Today's challenge:
>
> Given an ordered list of at least 3 *unique* integer 2D points forming a polygon, determine if the resulting polygon is [Rectilinear](https://en.wikipedia.org/wiki/Rectilinear_polygon).
>
>
>
A polygon is rectilinear if every interior angle is a right angle. The edges do not necessarily have to be purely vertical or horizontal (parallel to the x or y axis), as long as the angles are all right (This is slightly different than Wikipedia's definition, but it's the definition we'll be sticking with). For example, the following shape is a perfect square rotated 45°
```
(0, -1)
(1, 0)
(0, 1)
(-1, 0)
```
None of the lines are parallel to the x or y axis, but all of the angles are right so it is considered truthy for today's challenge. Note that the order of the points is important. The following reordering of these points gives a self-intersecting polygon, which is basically an hourglass shape rotated 45°. This is falsy:
```
(0, -1)
(0, 1)
(1, 0)
(-1, 0)
```
* You must take the input as an ordered set of points. Angles between the points or a "shape object" if your language has one, are not valid inputs.
* You must output one consistent value for truthy and a different consistent value for falsy.
* Note that truthy inputs will always have an even number of points.
* It is acceptable if your submission fails for very large inputs because of floating-point inaccuracies.
*Note*: If you want to visualize a polygon, I've found [this tool](http://www.samuelbosch.com/p/geometry-visualizer.html) and [Desmos Graphing Calculator](https://www.desmos.com/calculator) both very useful.
## Truthy examples
```
(0, 0)
(0, 20)
(20, 20)
(20, 0)
(1, 1)
(0, 3)
(6, 6)
(7, 4)
# This example is self-intersecting
(2, 3)
(3, 1)
(-3, -2)
(-2, -4)
(2, -2)
(0, 2)
(4, 0)
(4, 2)
(0, 2)
(0, 4)
(2, 4)
(2, 5)
(4, 5)
(4, 3)
(6, 3)
(6, 0)
```
## Falsy examples
```
(0, 0)
(0, 20)
(20, 20)
(20, 10)
(100, 100)
(100, 50)
(50, 100)
(2, 2)
(3, 3)
(6, 2)
(7, 3)
(100, 100)
(100, -100)
(-100, -100)
(-100, 99)
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~60 42 41~~ 40 bytes
I was just looking for an excuse to use `nlfilter`, too bad the solution was too long:) Now we compute the vectors of the sides of the polygon using `d=x-x(:,[2:end,1]))`. Then `d * d'` computes *all* pairwise dot products. We are only interested if consecutive dot products are all zero, therefore we check whether the first superdiagonal `diag(...,1)` is all zeros using `any(...)`.
```
@(x)any(diag((d=x-x(:,[2:end,1]))*d',1))
```
[Try it online!](https://tio.run/##PY3BCsIwEETvfsWCh@zKGkwiFVoC/kfIIZhGeqlSg8Svj5FS5zLDzIN53HJ4jzVZKWW9YqEwfzBO4Y4YbTkW7NnpfpwjK090iIIVUc2LdU4xKD@4E4Np1jF0zS4MZ@@HXQqN0Ay6deZP6JUwPyJOrycmzAvRmsV@k6BtTaG9fQE "Octave – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 16 bytes
```
×/0=4○∘×2÷/2-/,⍨
```
[Try it online!](https://tio.run/##VY49CsJAEIV7T7EHMGR2dhVSWNmYSjBeICARloC21kIQJUELiUewS2mf3GQuss6OpLD45vfNY/JjGe1OeXnYez@0MSwstTe6vIYWh0@MUTyl@u0Lqu5UN9Q80zVdz31nqHpwl22WHLerNPOFAgcMgsIxwqRQ6IwyTiu@cX2HnJGzVSgdK1lj@dI66ZiwC8x4FjBqLgQ3DeAYyX0XKol/dZJMxme0WGpBM2LBGxS0PGZE@VOz6gs "APL (Dyalog Unicode) – Try It Online")
Accepts the input as a list of complex numbers, e.g. `1j2` means \$ 1 + 2i \$ which represents the point \$ (1,2) \$.
The result is 1 if the given polygon is rectilinear, 0 otherwise.
### How it works
```
×/0=4○∘×2÷/2-/,⍨
,⍨ Concatenate self, so that all angles can be tested
2-/ Difference of two adjacent values, i.e. vectors
2÷/ Ratio of two adjacent values, i.e. angle difference
× Normalize to unit vectors
4○∘ Compute sqrt(1+x^2)
Zero if and only if the angle is a right angle
i.e. the normalized angle difference vector is i or -i
×/0= Test if all results are zero, i.e. all angles are right angles
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
;`_ƝḋƝẸ
```
[Try it online!](https://tio.run/##y0rNyan8/986If7Y3Ic7uoHErh3/D7c/alrz/380F2e0hoGOgoGmjgKINgIzjFBYBpqxOiBlhjoKhlBlxiDaTEfBDESb6yiYQJUYQaWMoUp1gQxdIzALKKVrAjYSJgSyBKrPBOoCE5AQTApCw/TAaFOoOhgNcwqMBruWCF8Zwr1lAOaBJcBsUzDTFCoaq6MA9ZkR1Gcwm4ygnjeGqcEwSRfK0cXCs7QE2R8LAA "Jelly – Try It Online")
Outputs \$0\$ if rectilinear, \$1\$ otherwise
-2 bytes thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)!
[Answer]
# [Zsh](https://www.zsh.org/), 94 bytes
```
for v w;:
for x y;a+=($[v-x]\ $[w-y])&&v=$x&&w=$y
for v w x y ($=a[-1] ${=a:^a})((r|=v*x+w*y))
```
[Try it online!](https://tio.run/##bU7bCoMwDH3vV@ShlFYp1OocKmUf4hzImPgmOFC7y7e7Noo4kNOTpDk5JK9nOzdc8LnpehhgLHLiqwlsUYeG03KQU3UFWo7SVoKxwdCJsdFQS1aHnwVOTV3KqAL6NnV@q7@C8/5jhmAKx8AKMQtCGogQJ9DIiDzubQf04hTloB1inJB7yTd9W8YgNb4EMDvHbixxfy8opK8S3JMgY0iRanOsS5e1@uCcVfm7ZLkldfkM8U6JlNooD0KWwUx@ "Zsh – Try It Online")
Input as flattened list of coordinates, outputs via exit code (`1` if rectilinear, `0` if not rectilinear). There are three loops here:
```
for v w;: # this does nothing other than set $v and $w to the last coordinate pair
```
```
for x y # ($v,$w) is previous vertex, ($x,$y) is current vertex
a+=($[v-x]\ $[w-y]) && # vector ($v,$w)->($x,$y) as space-delimited string
v=$x && w=$y # save previous point
```
```
for v w x y ($=a[-1] ${=a:^a}) # This iterates through all subsequent vectors (see below)
((r|=v*x+w*y)) # calculate the dot product, bitwise-or with previous dot-products
# if non-zero, r will be non-zero and the exit code will be zero
```
The last loop uses `${= }`, which splits parameters on spaces, and `${ :^ }`, which zips two arrays together (in this case, an array with itself). So, we have the last element in the array, followed by every element twice. That isn't an even number of coordinate pairs, so on the last iteration, `x` and `y` are empty. This is fine for the dot product, though, it will compute the dot product with the zero vector, which will always be rectilinear.
Using debug traps, [you can walk through the function here.](https://tio.run/##lVTRbtMwFH33V1wFr7PXBtEUXlJloMFAk6aBhHhhHZLJnM3gJcV2k5au37JX@ALe@ZT9yLh22q7ThgRJ08S@9x7f4@N7v9vzm4JxdlNUBmpohinxX1OYDUU3Y/S4jqcnI6DHTTw74Z1OndFpp9NkdEaWEd4XGM3Ecdw/ATrPRPpJLDhj5jKrd6bdZmfG@Q0npIB@uJ9BEp4@kfl5BfQ5Wp7gneA9CB7xpslP@ul4AHESfk8hvDFi7baEaEGSB8CXltsAQh7B60rrqgGhq/IMGuXOQZQgp@JirGVKvC/jc/A87RDGRpWugO1DVUrYssC2LE/xY1RuQ0Q1zkZAGaNz9o7TeRrrMLdYcI5mG8GCkEbor@7cVJMzBIY5yYWVQMdG1sEXVEn6fU4AL8Z0n/PLS8wBogMnjXAKk1xG41uCMGeTC1k6i8Q@z/DPVWClQ01EeYq64NC7aWEduKa69X8crZfodnm7Xljn5cQYdNAzQJlrYBhRe066v5PEmA5vkTPa3LWhJSLDIUmSFkwVHjyBLMN953zo8yiDZblUtTn4H3650PlECyeDRy1zh@IUproIY7@TqprY4NlygbFQBqriFq0lX6jVHiR/2wNGpz064xDv4mfdow2HDK6vfrQ10WtL4vrqZwSe@2CwyX0QuP8D9fVyPRAIz7CA2JcUUjxC7MW3LheLBfAIRusof0WjVbml8H6slbsVWmrpWXrGIyoAHWjwfABiWakpfFTj4BwqQDkrddELeYP14OmdnHgIWtzD26@lmWGtTMwqBwvKIqm8Kq3MJ07Vci1GK5y9B3L/IGxGW3W60tz21kfBe59WKLSpTif5PX27XT14WF8vpZcVJfz9yw@83DhAGVDitnPd2bdoT7lGWRnjmQt7ZVYlZ0KMuWSrhncS6kFakRN/KLNQ3wRbAAtozogxbPu5jB4eHO0fvYWN3gC7nWQbXu3vfXjTcll2r9DHCF/1sBvyBw "Zsh – Try It Online")
[Answer]
# Python3, 98 bytes
```
lambda p:not sum((a-c)*(e-c)+(b-d)*(f-d)for(a,b),(c,d),(e,f)in zip(*[p[i:]+p[:i]for i in[0,1,2]]))
```
[Try it online!](https://tio.run/##jVHLasMwEDxXX7HQi5RIYMtOSgy@9gt6c31wEqkROIqwHWj68@5KlgKlKfSyM7s72pfcbTpdbDHr@n3uu/P@2IGr7GWC8XqmtBMHtqIK7ZruxRG5RqsvA@34nnF64Ee0imtmLHwZR1eNa0zVrl1TmRZ1YMDYJuM5l23L2DwN1@l0qxvS0IxDxjjxKAORP1jGWk5QlnPIo6zwuOWw9fjCoQySZ3g7mRHUZ3d2vQKko@q1MHZSw6gOk7EfWEbG50UsJ5AIGRimRBnappAfJLYv45SlD6XUgulNwk3UJUzjJsSNSEuI7vpR/esE@f0GWfBCIvBNoJsY9aJlRRlXTC1lvFTxVyERHfHA2@3iwPiN9@taWL6wIk9uwBtTTWOOsV/SZdUHUqhrePVJNn8D)
Takes in a list of tuple points and outputs True if the points are rectilinear, False otherwise.
## How it works
```
p # contains a list of points
[p[i:]+p[:i]for i in[0,1,2]] # makes 3 lists of p rotated 0, 1, and, 2 places respectively
zip(*[p[i:]+p[:i]for i in[0,1,2]]) # zips the shifted lists together
(a,b),(c,d),(e,f) in zip(*[p[i:]+p[:i]for i in[0,1,2]]) # extracts (x0,y0), (x1,y1), and (x2,y2) from the zipped lists
(a-c)*(e-c)+(b-d)*(f-d) # translates the 0th and 2nd point by the 1st and computes the dot product, which should be 0 if the points are orthogonal
sum((a-c)*(e-c)+(b-d)*(f-d)for(a,b),(c,d),(e,f)in zip(*[p[i:]+p[:i]for i in[0,1,2]])) # sums all of the consecutive dot products together
not sum((a-c)*(e-c)+(b-d)*(f-d)for(a,b),(c,d),(e,f)in zip(*[p[i:]+p[:i]for i in[0,1,2]])) # finally negate the result since if the sum is 0 than all of the points are orthogonal and hence the points form a rectilinear shape!
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes
```
⬤θ¬ΣEιΠE²⁻λ§§θ⁺κ⊖⊗νμ
```
[Try it online!](https://tio.run/##RYwxC8IwEIV3f8WNV7iApm5OhS4OlYJjyFDTgMU0qTER/308tOJb3nd37525DtGEwZXSx8knbJzDO8EpJDznGbthwYmgj2HMJn1GSdBNPj/QETTp6Ef7wp9zs3d8uhG01kQ7W5/siG3IF8fuKxbBXK06lKKUAv4ItaYNgIKaefdlwSzkypwR@zUj/3vYcl5qrYt4ujc "Charcoal – Try It Online") Link is to verbose version of code. Outputs using Charcoal's default boolean format, which is `-` for true and nothing for false. Works by separately subtracting each point's x- and y-coordinates from its two adjacent points, then taking the products of the subtractions, then summing, which results in zero when the point is at a right angle. Explanation:
```
θ Input array
⬤ Each point satisfies
ι Current point
E Map over coordinates
E² Map over implicit range `0`..`1`
λ Current coordinate
⁻ Subtract
ν Inner value `0` or `1`
⊗ Doubled to `0` or `2`
⊖ Decremented to `-1` or `1`
κ Outer index
⁺ Added
θ Input array
§ Get the adjacent point
§ μ Take the relevant coordinate
Π Take the product
Σ Take the sum
¬ Is zero
Implicitly print
```
[Answer]
# [Python 2](https://docs.python.org/2/), 68 bytes
```
lambda l:any(((a-b)/(b-c)).real for a,b,c in zip(l,l[1:]+l,l[2:]+l))
```
[Try it online!](https://tio.run/##fY9NTsMwEIX3nGKWM2BD7CStGomTlC6ckKiWXMeKgki5fPDYXiCBWH3Pb/6ew329zl7v0@vb7sytfzfgOuPviGhkTy/Yy4HoeRmNg2lewIheDGA9fNmATriz6i5PTM0k2j@v1o2gurBYv8KE52G@BTdu@LhR2rDxtPXhY0W60I6VgIoEQzP1T1HRAyoBKtfriIOAQ8RRQBNrOpt1bpGRUrOIvmx4RzF4Z2xv8qmGX8VMKK0FbW4pKEcLONB/gVVKXCXFXpItq7Z4KbTOoctSnT9U/zEqs5a/H6cTfQM "Python 2 – Try It Online")
Input is a list of complex numbers. Output is True or False, swapped.
[Answer]
# [Haskell](https://www.haskell.org/), 54 bytes
```
all((==0).sum).r(*).r(-)
r=(=<<tail<>id).z.z
z=zipWith
```
[Try it online!](https://tio.run/##hU/BTsQgEL33K@bgoTXQFMqu2aR48urZQ@2B7MoukbakxUs/3soAMSaamBDe482bGd5Nre9v1u5mdPPi4Ul5VT/P02wuhZavu7K2LKVsqnr9GKt6Ke/xolWxyFJ2nVfGdo/mUtVbvRWb3Ix7Mf62ewYS@r4h0AwEgSPyn6QZhsLzaGMEWLK1AY4EjgEeCAi0tNHCU61NThqQciRBpwInZgE3YJeIXSLtFyjmWoTckeGQLBnyFzLgL/X/YVj05TRNFLAU6QHZIWvB9R2Ip0B5E0@ZW7SIPwfRxOnvx@kUugore8@I58S3eDQjmhMdiAjFUZkpTHWLmTzcwagcaLD751lbdV13enbuCw "Haskell – Try It Online")
Uses `(<>)`, which is available in base in the latest release.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~49~~ 48 bytes
```
0==##&@@Dot@@@({#,r@#})&[(r=RotateLeft)@#-#]&
```
[Try it online!](https://tio.run/##hU89C8IwEN39FQeBUiHBNG2VDpUM0slBXEuHIhUdaqFkK5kd/an@hNrEO0VQnN67e@8@XlubU9PW5nyoxwLyUeY5Y4HWm85orcOB8V4ze79d50EZ9vm@M7Vpts3RzDUTrArGXX@@mJKJdVGyqgpgoWGYAQyD5CAtB4fKE/XBpLXc@yIOEfpih0sOS4crDgl5FGoxesVEhPJskkTil1LLnaHBBJ9IXI@0J9IQYYo@QnqG8PXwn2DRO5n0pVc8Tz1NsfvOpjAbnVKYP/65SWAhvlRZZq0dHw "Wolfram Language (Mathematica) – Try It Online")
-1 thanks to attinat!
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~41~~ ~~35~~ 34 bytes
```
Norm@Cos@PolygonAngle@Polygon@#>0&
```
Returns `False` for rectilinear polygons and `True` otherwise.
Only works in 12.0+, so no TIO link
-6 bytes thanks to @Roman
-1 bytes thanks to deleted comment
[Answer]
Excuse my rusty Ruby. Maybe someone can hint how to shorten. :)
# [Ruby](https://www.ruby-lang.org/), 158 bytes
```
s=0;a=ARGV;a[0].split(",").zip(a[2].split(",")).map{|a,b|b.to_i-a.to_i}.zip(
a[1].split(",").zip(a[3].split(",")).map{|a,b|b.to_i-a.to_i}){|a,b|s+=a*b};p s==0
```
[Try it online!](https://tio.run/##KypNqvz/v9jWwDrR1jHIPcw6MdogVq@4ICezRENJR0lTryqzQCMx2ghZTFMvN7GguiZRJ6kmSa8kPz5TNxFM1YIVcyVGG2IxwZgoEzQhgsXatolaSbXWBQrFtrYG////VzLQ0TVUUvivZKhjoATiGQJJXRAHAA "Ruby – Try It Online")
[Answer]
# Python and numpy, ~~94~~ 92 bytes
Uses roll a silly number of times and has two input lists of x and y coordinates. It is easier to rotate an array with python lists (`x[1:]+x[:1]`) but naturally numpy arrays aren't concatenated with `+`.
```
from numpy import roll as r
def f(x,y):a,b=r(x,1)-x,r(y,1)-y;return 1-any(a*r(a,1)+b*r(b,1))
```
[Answer]
# R, ~~60~~ 53 bytes
Takes in a vector of complex coordinates and returns swapped truthy and falsey. Uses [xnor's dot product trick](https://codegolf.stackexchange.com/a/195562/17360).
```
function(x,a=c(x[-1],x[1])-x)any(Re(a/c(a[-1],a[1])))
```
-7 bytes by using inline rotation instead of creating a function.
# R, ~~82~~ ~~79~~ 75 bytes
Improved version taking advantage of doing computation in default parameters to save on curly braces.
```
r=pryr::f(c(z[-1],z[1]))
function(x,y,a=r(x)-x,b=r(y)-y)any(a*r(a)+b*r(b))
```
-3 bytes by using [`pryr::f` anonymous function](https://codegolf.stackexchange.com/a/111578/17360) and returning 0 for truthy, 1 for falsey.
-4 bytes with better roll function
# R, 87 bytes, original answer
My first R answer! Uses same array rotation logic as my numpy answer.
```
r=function(x)c(tail(x,-1),x[1])
x=scan()
y=scan()
a=r(x)-x
b=r(y)-y
!any(a*r(a)+b*r(b))
```
] |
[Question]
[
Display the emoji of the eastern zodiac of given time, according to given country.
The eastern zodiac is a classification scheme that assigns an animal and its reputed attributes to each year in a repeating 12-year cycle. It is also assigned to hours.
**Rules:**
1. The country must be given as ISO 3166-1 alpha-3 code. The list is [here.](https://www.iso.org/obp/ui/#search)
2. The input format must be like this: `<ISO code> HH:MM`. The input must be a single string. Any input that doesn't fit this format falls in *don't care* situation.
3. If the given time lies in boundary of the chart given below, you can output either zodiac.
4. As this is a code golf, the shortest code in bytes wins.
**The zodiacs:**
The zodiacs without specified country are defaults.
* The first zodiac (23:00 – 01:00):
+ Rat üêÄ (U+1F400)
+ Mouse üêÅ (U+1F401) in Persia (IRN)
* The second zodiac (01:00 – 03:00):
+ Ox üêÇ (U+1F402)
+ Water Buffalo üêÉ (U+1F403) in Vietnam (VNM)
+ Cow üêÑ (U+1F404) in Persia
* The third zodiac (03:00 – 05:00):
+ Tiger üêÖ (U+1F405)
+ Leopard üêÜ (U+1F406) in Persia
* The fourth zodiac (05:00 – 07:00):
+ Rabbit üêá (U+1F407)
+ Cat üêà (U+1F408) in Vietnam
* The fifth zodiac (07:00 – 09:00):
+ Dragon üêâ (U+1F409)
+ Crocodile üêä (U+1F40A) / Whale üêã (U+1F40B) in Persia (you can output either)
+ Snail üêå (U+1F40C) in Kazakhstan (KAZ)
* The sixth zodiac (09:00 – 11:00):
+ Snake üêç (U+1F40D)
* The seventh zodiac (11:00 – 13:00):
+ Horse üêé (U+1F40E)
* The eighth zodiac (13:00 – 15:00):
+ Ram üêè (U+1F40F)
+ Goat üêê (U+1F410) in Vietnam
+ Sheep üêë (U+1F411) in Persia
* The ninth zodiac (15:00 – 17:00):
+ Monkey üêí (U+1F412)
* The tenth zodiac (17:00 – 19:00):
+ Rooster üêì (U+1F413)
+ Chicken üêî (U+1F414) in Persia
* The eleventh zodiac (19:00 – 21:00):
+ Dog üêï (U+1F415)
* The twelfth zodiac (21:00 – 23:00):
+ Pig üêñ (U+1F416)
+ Boar üêó (U+1F417) in Japan (JPN)
+ Elephant üêò (U+1F418) in Thailand (THA)
The code points are from [here.](https://www.unicode.org/charts/PDF/U1F300.pdf)
**Example:**
Given the following input:
```
KOR 19:42
```
The output must be:
```
üêï
```
[Answer]
# JavaScript (ES6), ~~168 165 160 157~~ 155 bytes
*Saved 4 bytes thanks to @Neil*
Returns the crocodile for the 5th zodiac in Persia.
```
([a,b,c,,d,e])=>String.fromCodePoint(127998-~'00111321211'[k=-~(d+e)%24>>1]+k*2-~(1e12+{IRN:121010020100,VNM:1010001e4,KAZ:3e7,JPN:1,THA:2}[a+b+c]+a)[k+1])
```
[Try it online!](https://tio.run/##fZBBS8NAEIXv/opSkO66m7IzicQsJBC8qMVaqnhoyGGbbEpMzUoavIj963EjHrNeBma@N8Ob96Y@1ano6o/ea02phyoeSKb4nhecl1znNE6e@65uD8uqM@@3VrIxddsTwDCKbrzzQggA8BEQYJE1sXcmJdP0EoMkgZw1V2gnoAHZ1/12La1MgBA4Fv66fpS/rQAd8FW6k74O@cPGyvjLXSrxO1Nsz4qcKZo1DHI6FKY9maNeHs2BVGS@etrOIJIBzim9mGDoSyEmmLXiZOOeAPfevyx03Ex3bjb6RHkdTTCbhZPZhJzMJjuDv/@GHw "JavaScript (Node.js) – Try It Online")
### How?
We define \$k\$ as the 0-based index of the zodiac, which can be deduced from the hour \$h\$ with:
$$k=\lfloor ((h+1)\bmod 24)/2\rfloor$$
We define \$x\_k\$ such that the base offset \$b\_k\$ of the code point for a given zodiac is:
$$b\_k = 2k+x\_k$$
The final code point is \$128000+b\_k+c\_k\$, where \$c\_k\$ is the country offset.
This is summarized in the following table:
```
k = | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11
--------+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----
b(k) | +0 | +2 | +5 | +7 | +9 | +13 | +14 | +15 | +18 | +19 | +21 | +22
= 2k | 0 | 2 | 4 | 6 | 8 | 10 | 12 | 14 | 16 | 18 | 20 | 22
+x(k) | 0 | 0 | 1 | 1 | 1 | 3 | 2 | 1 | 2 | 1 | 1 | 0
--------+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----
IRN | +1 | +2 | +1 | | +1 | | | +2 | | +1 | |
VNM | | +1 | | +1 | | | | +1 | | | |
KAZ | | | | | +3 | | | | | | |
JPN | | | | | | | | | | | | +1
THA | | | | | | | | | | | | +2
```
### Commented
```
( [ a, b, c, // a,b,c = country code
, // the space is ignored
d, e ] ) => // d,e = hour (minutes are ignored)
String.fromCodePoint( // return the character whose code point is:
127998 // 127998
-~'00111321211'[ // + 1 + x(k)
k = -~(d + e) // where k is defined as:
% 24 >> 1 // floor(((hour + 1) mod 24) / 2)
] + //
k * 2 // + 2k
-~( // + 1 + the country offset
1e12 + // each pattern being encoded as 10**12
{ // + a specific value, leading to:
IRN: 121010020100, // IRN -> 1121010020100
VNM: 1010001e4, // VNM -> 1010100010000
KAZ: 3e7, // KAZ -> 1000030000000
JPN: 1, // JPN -> 1000000000001
THA: 2 // THA -> 1000000000002
}[a + b + c] // according to the country code
+ a // coerced to a string
)[k + 1] // extract the correct offset for this zodiac
) // (gives something NaN-ish for the other countries)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~66~~ ~~64~~ 63 bytes
```
√æ—Ç√∑;√≤12%√ê‚Ä¢k√Ñ$√≥¬∑;@√®‚ÇÇ√àŒ±–≤Œª√£‚Ķ7q¬º#‚àço‚Ä¢5–≤6√§.‚Ä¢x–∏ ía√†√í¬æ√ÑŒª‚Ä¢u3√¥I√°k√®s√®≈æy‚ÇÑ*O√ß
```
[Try it online!](https://tio.run/##yy9OTMpM/V9TVvn/8L6LTYe3Wx/eZGikenjCo4ZF2YdbVA5vPrTd2uHwikdNTYc7zm28sOnc7sOLHzUsMy88tEf5UUdvPlCd6YVNZoeX6AFZFRd2nJqUeHjB4UmH9h1uObcbKFRqfHhL5eGF2YdXFB9ecXRf5aOmFi3/w8v/6/z39g9SMLS0MjHiArGMjK0MDLg8g/ygLJCYgSFMDIkFkXWMUjAwh6kzMrIyteTyCvCDskI8HKGsMD9fBUOQDgA "05AB1E – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 73 bytes
```
℅⁺×¹²⁸φΣE⮌…⪪”&↖∨∧h↘X⁷↘H⪫³Jºρ⁷s,⟲⌈3A‖Cc>χ§₂25:×” ⊕﹪÷⊕I…粦²¦¹²⊕⎇κ÷Lι³⌕⪪ι³θ
```
[Try it online!](https://tio.run/##XU9NT4QwEP0rE07TpB5AD36cNhgjriBhiYe9NWWUxlKwFJL99bVVNtk4mc/3Jm8yshdWjkJ7X1tlHOZhFtKRxVovM7ZqoBnT7JbDB@NwWAYsxYQNrWRnwvwkNeX9OOFh0sphUjQVvFdlLFsba/D97ghwpn45eKmr9nmXcEggCdqFkZYGMo46LMdu0SMWxj2qVXWEl2QuZndxueeQMcZi5pDG9p9YS9YIe8KvCJ8FX8l8uh5V2L0O8aRMt/2g/pBvttmD9/u3BtK7@5vMX636Bw "Charcoal – Try It Online") Link is to verbose version of code. Explantion:
```
℅⁺×¹²⁸φ
```
`0x1F400` = 128,000 (`φ` is predefined to 1,000). This is added to the sum of the rest of the expression and converted to a character for implicit print.
```
⊕﹪÷⊕I…粦²¦¹²
```
The hour is extracted and converted to a zodiac index.
```
…⪪”&↖∨∧h↘X⁷↘H⪫³Jºρ⁷s,⟲⌈3A‖Cc>χ§₂25:×” ...
```
The compressed string `IRN VNMIRN IRN VNM IRNIRNKAZ VNMIRN IRN JPNTHA` is split on spaces and truncated to the length given by that index.
```
ΣE⮌...
```
The array is then reversed, mapped over, and summed.
```
⊕⎇κ÷Lι³⌕⪪ι³θ
```
For the first element, the string is split into groups of three characters and the country index is taken, otherwise the number of countries is counted. For the first element, the index needs to be converted from 0-indexing to 1-indexing while for the other elements the result needs to be incremented for the default country, so this is done outside of the ternary.
[Answer]
# [PHP](https://php.net/), 185 chars, 263 bytes
Thanks to [Dannyu NDos](https://codegolf.stackexchange.com/users/89459/dannyu-ndos) for bug fix.
```
fn($i)=>strlen($b=[[üêÄ,üêÅ],[üêÇ,üêÑ,üêÉ],[üêÖ,üêÜ],[üêá,üêá,üêà],[üêâ,üêä,üêâ,üêå],üêç,üêé,[üêè,üêë,üêê],üêí,[üêì,üêî],üêï,[üêñ,4=>üêó,5=>üêò]][(($t=$i[4].$i[5])%2?$t+1:$t)%24/2])?$b:$b[strpos(____IRN_VNM_KAZ_JPN_THA,substr($i,0,3))/4]
```
[Try it online!](https://tio.run/##fZDLSsNAFIb3eYqhjDSDQ5tbEVPTkJ1ajFLEReMQiLSkIG0wce@1XvBS7@58Rd8gnjOhCNJxFv98/P@cM2cmS7Nyzc/STNPo0CuHY52OmNfJi6PDAXDiRdH31@yEg5wKjnyGfIFyXhmXyNOKr/hcrivjBvmWz@lOoN6jPMj8EfEJZSajZ@m@IL5K400a79zxOrB/8JbcP4WIdJ0WHh1FjmiAtgRbsnxaLJsuLQCdpiWYTxOXJhG8JpvkegxroxfGe@FW3A368eZOGO@uBzw/TuAEPJwb3Gas6YiyrWmDg3RC6FCvd7d7xFx1HavOSIPU9se19m8I/Yix4trGohAuIobpGgtDbGvZihDbKkOsVLaVAynvDPo47T8DqSrhr9QhfOLfsPwB "PHP – Try It Online")
Just a simple array mapping, there should be better ways to golf this. Hour part of input time is converted to an even number (0-22) and then it is divided by 2 to get array index 0 to 11 in the mapping. Time periods with special cases are a sub-array with index 0 mapped to default sign and 1-5 mapped to the special sign for IRN, VNM, KAZ, JPN and THA in same order.
[Answer]
# [Python 3](https://docs.python.org/3/), 168 bytes
```
lambda s,a='BA EDC GF HIH KJMJ N O RQP S UT V WWWXYW'.split():chr(ord(a[(int(s[4:6])+1)//2][min('IRNVNMKAZJPNTHA'.find(s[:3])//3,len(a[(int(s[4:6])+1)//2])-1)])+127935)
```
[Try it online!](https://tio.run/##bZJPb4JAEMXv/RRz293UKrNQ2pJ4oH8R42qtlVrKgZYSSXAlwKWfni4ePOgc95e3b96bTPXXbvfa7vLxV1emu@8shWaQjtm9D0@PD/DyDMEkgGk4C0HBHJavC3iD9xWsIYqij03Ehk1VFi0X3s@25vs642nMC93yJnY8NxGXKEYjmcS7QnM2Waq1mk39z3ChVoHPhnmhM6P07MSo7EH5q@nv4gpF/5A3d/a16Kq6l@Sc@WoDluVZFhPi4kjNGIIetPKUmjwEPThI0sEhtQ6pdclpLqm9JX3PqFkeQXsHJBsj2QIdKhmS3ZDshmQLJFsgmVeSeeVZXnMrBDXnc6TdPw "Python 3 – Try It Online")
] |
[Question]
[
*Inspired by [last week's APL lesson](https://chat.stackexchange.com/rooms/52405/conversation/lesson-27-lookup-without-replacement "Lesson 27 - lookup without replacement").*
Given an uppercase 2D seat map and a 1D list of customers, return the seat map and the customer list but modified as follows (to indicate occupied seats and seated customers):
For each unique letter in the input passenger list, lowercase that many (or all, if there are not enough) of that letter in the seat map, going left-to-right, top-to-bottom.
For each unique letter in the seat map, lowercase that many (or all, if there are not enough) of that letter in the passenger list, going left-to-right.
1. The input seat map only contains spaces and uppercase letters from the set {`F`,`B`,`P`,`E`}, and may be:
1. separated into rows by line breaks
2. a list of strings
3. a matrix of uppercase characters
4. in any other comparable format
2. The input customer list only contains uppercase letters from the set {`F`,`B`,`P`,`E`} and may be:
1. a string
2. a list of characters
3. in any other comparable format
3. The returned seat map must be identical to the input one, except that zero or more letters have been folded to lowercase
4. The returned customer list must be identical to the input one, except that zero or more letters have been folded to lowercase
5. Leading and trailing whitespace is allowed
## Examples (shortened editions of United's aircraft)
### ERJ145
Seat map input:
```
P
E
E PP
E EE
E EE
E EE
E EE
P PP
E EE
E EE
E EE
```
Passenger list input:
```
FFEEEEEEEEEEEEEEEE
```
Seat map output:
```
P
e
e PP
e ee
e ee
e ee
e ee
P PP
e eE
E EE
E EE
```
Passenger list output:
```
FFeeeeeeeeeeeeeeee
```
### CRJ700
Seat map input:
```
F FF
F FF
PP PP
PP PP
PP PP
EE EE
PP PP
EE EE
EE EE
EE EE
```
Customer list input:
```
FFFFFFFFPPEEEEEEEEEEEEEEEEEEEEE
```
Seat map output:
```
f ff
f ff
pp PP
PP PP
PP PP
ee ee
PP PP
ee ee
ee ee
ee ee
```
Customer list output:
```
ffffffFFppeeeeeeeeeeeeeeeeEEEEE
```
### B757
Seat map input:
```
F F F F
F F F F
F F F F
PPP
PPP PPP
PPP PPP
PPP PPP
EEE EEE
EEE EEE
PPP PPP
EEE EEE
EEE EEE
EEE
EEE EEE
EEE EEE
EEE EEE
EEE
```
Passenger list input:
```
FEEEEEEEEFEEEFEEEEEEEEFEEFFEEFEFFFEE
```
Seat map output:
```
f f f f
f f f f
f f F F
PPP
PPP PPP
PPP PPP
PPP PPP
eee eee
eee eee
PPP PPP
eee eee
eee eee
eeE
EEE EEE
EEE EEE
EEE EEE
EEE
```
Passenger list output:
```
feeeeeeeefeeefeeeeeeeefeeffeefefffee
```
### B767
Seat map input:
```
F F F
F F F
BB B B BB
BB B B BB
BB B B BB
PP BB
PP
PP PPP PP
PP PPP PP
PP PPP PP
PP PPP PP
PP EEE PP
EE EEE EE
EE EEE EE
EE EEE EE
EE EEE EE
EE EEE EE
```
Passenger list input:
```
PPFEFEEEEEEEBBEEFFPEBPEBBEEFEEEFEEEEEEFPEEEPB
```
Seat map output:
```
f f f
f f f
bb b b bb
BB B B BB
BB B B BB
pp BB
pp
pp PPP PP
PP PPP PP
PP PPP PP
PP PPP PP
PP eee PP
ee eee ee
ee eee ee
ee eee ee
ee EEE EE
EE EEE EE
```
Passenger list output:
```
ppfefeeeeeeebbeeffpebpebbeefeeefeeeeeeFpeeepb
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~22~~ ~~16~~ 15 bytes
Saved 6 bytes thanks to *Nit* noticing that the seat map could be taken as a string.
```
svDyå·Fyyl.;s]»
```
[Try it online!](https://tio.run/##MzBNTDJM/f@/uMyl8vDSQ9vdKitz9KyLYw/t/v9fSUlJwU1BAYq5kNlOTgoKTgogwgknOyBAAQKQ2QpAcxAALB4AIYhmu7q6gtkgyhVCkMoG@gxolJurmysEODm5urq5Bbg6BUCYrq4wKaCgq2uAEwA "05AB1E – Try It Online")
**Explanation**
```
s # setup stack as <passengerlist>,<seatmap>,<passengerlist>
v # for each passenger y
Dyå # does a corresponding seat exist?
·F # multiplied by 2 times do:
yyl.; # replace the first y with a lowercase y
s # and swap the seatmap and passengerlist on the stack
] # end loops
» # join seatmap and passengerlist on newline and output
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~93~~ ~~89~~ ~~84~~ ~~83~~ ~~82~~ 78 bytes
```
l=input()
for c in l[1]:l=[x.replace(c,c.lower(),c in l[0])for x in l]
print l
```
[Try it online!](https://tio.run/##vcvBCsIwDAbg@54i9LRBGepR2CWQnnOfPUipOChdKRPn01dnNw@DXQQN5Cf9kobHcO39ISXXdD7chrIqLn0EA50H1@710TXtWEcb3NnY0khTu/5uY1nJ@WSnq@nD@H7pIsTOD@BSEqAAPr3UyW8wIgDCFPg9M8/jBgOsmXP8hIlozZNQjv@wkIJZkaJciERKMSHnkWhZvZCIUTwB "Python 2 – Try It Online")
Takes input as two strings. Prints two strings
---
Saved
* -5 bytes, thanks to Dead Possum
* -4 bytes, thanks to Lynn
[Answer]
# [C (clang)](http://clang.llvm.org/), 75 68 bytes
```
f(char*s,char*p){char*r;while(*s){if(r=strchr(p,*s))*r=*s+=32;s++;}}
```
Takes two `char *` (seats & passengers) whose contents are modified in-place.
[Try it online!](https://tio.run/##vVKxboMwEN35ipOlSDbQIXSrxWhmS@1WOiAKwVLqIh9KB8S3U9sUgiIrytQb7Od3z@e7J9dP9bnSp3luad1VJsbUbz0b/W74T6fODY2RjaqlJsfB1J2hfWoZFps8xiR/zjgmCZ@m@fKtPmFocDhSNkYA0Bulh5aSN8vBsdSEcUe72oBNNeD7B@RQRkTaHEBEhM2CxR5JuSIhHkB@kQ9du3bRV4iNPjVmaYUUhbiJRdxS32@6u7DMso4oN/6l1Ae0j6R7Key1r67UJvOFnWKKos3BLORgdsfBwrJF4afcQXn1IwzFrX/BVAje83AJKUUo/t/Qr0rpPz/X78m3Q@YO0/wL "C (clang) – Try It Online")
I'm less used to golfing in C than in Python, but that's fun as well !
If anyone has an idea for a trick to shorten the `*r+=32,*i+=32` part I'd be grateful. **-> Thanks to @Dave for helping me golf some more bytes !**
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 63 bytes
```
f(x,y,z)char*x,*y,*z;{for(;*y;++y)if(z=strchr(x,*y))*z=*y+=32;}
```
[Try it online!](https://tio.run/##fY7BbsMgDIbvPIVVaRIQJm3dEeUYzjntsvQQodJGyigi2VTS9dmZaZJt0bIhbH7sz7@s7w9ax2joWQQxMH2sPT8LHgQf5MWcPJU8yCwLrDF0yLve66OnCWCMDzkPWf60lddIGtvDa91YmkTtD1pA8gKO@v1lx@BCAM9Y6yBHuG1PmqJju7f0Rj3uGJM/MLeObb@wtI4LtBPz@KLsxIyPZedxN0M3d11lU3xU9rmyGwGdADcxBs3cH/yS9Pv@zVt4kORKYlSgAK8ivwUpyzINwCgwrYiiKAAwfYt/Wje3JFZ6SwFRFdNRU8wflQIzPp8 "C (gcc) – Try It Online")
Lots of credit to etene for the basic concept. Just applied heavy golfing to his answer's strategy.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 64 bytes
Borrowing from @etene's answer, I removed the `if` with the `?:` tertiary operator and reused the passenger pointer as its own index.
```
f(s,p,j)char*s,*p,*j;{for(;*p;p++)(j=strchr(s,*p))?*j=*p|=32:0;}
```
[Try it online!](https://tio.run/##tZXdb5swEMDf@StOVJOAsol2TSPFZZM82Q99srrHJg@IkMRRZhCwvWT527OzIQnho4uWzhJn8/Odz@eviz8u43h/I1W8@TlP4Kko5zL9tPpiNVEu1RLZfuEUfuav3XgV5V7he5nvrcl2keYO8TKS3d66zjpE9XiVO7rbdb9669DLfoef7ycB2e0tqUr4EUnl/Erl3IWtBaAHwwog20QqKV5nr3fBLNza7OX57mFk@/a3l@dxEGCDjkdjUz2O7Z1vbIokKrXJ/WiENgbpYgstp8o@EdZHhGgTxt6BQMeXuMqXf0IcBednWj1IdP1dhthAMPAPhm@hs4gwABStmC6Fh0ZrgmIAis4aXApZNXn2d3iluZG9sHOCLx5zGFZjNvYDzHky3/kMBjilABS0oFfxesuGeSt4ABjYe7P4A6f9fbhZud4bMHTm/wuvH8EsKopELZO88xLanLNWOW419lVFCNZXGooHxOvv8KNH5yh5U1sIflSiVCsJRkXVPNlz7VTQOg6ClU4NkljY0glFhgGRTw9EYlKBKhzMPua1lzO/EbGcuaRaBcxS5cKxhU4jE/hQTNV31Idos0njqJSpmkyVpuJobNJHMq@U9S2oUxB6eMPVztrt/wA "C (gcc) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes
```
,ṚŒlẹЀḣ"ċЀ`}Ẏʋ¦/€
```
[Try it online!](https://tio.run/##y0rNyan8/1/n4c5ZRyflPNy18/CER01rHu5YrHSkG8xMqH24q@9U96Fl@kDO/8PtWY8a9x3admjb///R6urqCm4KCnAMA1zYRZ2cFBScFECEE5miAQFQFnZRBRQ3YANgtQEQguqirq6uaKIgAVcIQXtRYGzoKKgHBLi5urlCgJOTq6ubW4CrUwCE6eoKkwIKuroGOKnHAgA "Jelly – Try It Online")
[Answer]
# [Scala](https://github.com/scala/scala), 104 bytes
```
def f(l:Array[Char]*)=(l(0).map(? =>{val i=l(1)indexOf?;if(i>=0){l(1)(i)= ?toLower;l(1)(i)}else?}),l(1))
```
[Try it online!](https://tio.run/##tVHLTsMwELz7K1Y52ajq69gqjQiyTyAsIU6Ig9smxTRNosSFoqrfXmzHaZoSOIBYKevx7GYnsykXIhHHbP4aLRTcCZlCtFNRuizhOs9hj47LKIYYJ5ProhAfTzcvoni@Ij5O8JD0NyLHAfiz/ZtIQPoJHhGZLqPdfRxMZYzlzB@SvWGxJD4EKrvN3qNi6phDlJRRcCA9cydHNBiAKkRaxlmxKUGm@VbBgypkugKVwZn@tOmDbKtM31ws1qar6p9Crg/lihNkPKywGE1cvQfzEyYTeEylAl@bBTBGsBjrhjHRVKxf6qvMapuXakx0q5VIUt3d36zdrDN63k0TdEBohT3G6EV4PfA8j4MOROvMucmUdmTEu8t6CHESVXBOu6LSY1qIMeQOXs1sH7TWa11bR6NZT2fuqS/GL9OZNcJaUyf0FWgluwaoALefcglopUwb8EPJTjOgo9YGRvXkhnN2MhGGxgSnIa9g44@Z/fKwsgV2k@6pA3WzYQgQgknhL1m3p@/Y86j/n00XzX9n7e5arNuqSf/P2j92OH4C)
Takes 2 seq of chars in input and returns 2 seq of chars.
Explanation:
```
def f(l: Array[Char]*) = // input are varargs of Array[Char]; in our case 2 arrays. Arrays are chosen since mutable (the seatmap will be updated while the passenger list is mapped)
( // we return a tuple with the 2 arrays of Chars
l(0).map( // l(0) is the passenger list. We map (transform) each element of this list to lowercase or not and this is what's returned as 1st part of the tuple
? => { // ? is the current element of the passenger list being mapped (it's ? and not let's say m in order to be able to stick it next to functions)
val i = l(1) indexOf ? // i is the index (or -1) of the letter ? in the seat map
if (i >= 0) { // if index found
l(1)(i) = ? toLower // then we update the seatmap with the lower case version of this seat
l(1)(i) // and the passenger list elmt is mapped to its lower case version (same as ?.toLower)
} //
else ? // if not found, the seatmap is not updated and the passenger list elmt stays in upper case
} //
), //
l(1) // the updated seat map
)
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 36 bytes
```
+`(([A-Z])(.*¶)+.*?)(\2.*$)
$l$1$l$4
```
[Try it online!](https://tio.run/##K0otycxLNPz/XztBQyPaUTcqVlNDT@vQNk1tPS17TY0YIz0tFU0ulRwVQyA2@f/fTUFBwc2NC0oFBCgoBASgUa6uCgqurlxoXFSKyw0KAgJcsQEA "Retina – Try It Online") Assumes the customer list is the last line of the input. Explanation: Finds pairs of matching uppercase characters and lowercases them using `$l` thus avoiding the intermediate characters.
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), ~~29~~ 27 bytes
```
(~2∊/3⍴(⍴⍴,\∘,∩¨,)¨)819⌶¨¨⊢
```
[Try it online!](https://tio.run/##lVO9TiMxEO73KaYzSEHHgkCBcqV17QegWSdrFF2kWEBzOkGFUPgJokGihSr0cMWVeRS/SBjbs16vtZxyI/zNrB1m9H0zU@npzvhXNZ2d7oym1fn5ZLQ2j8@Tmbl52l0rxK2rPTO/@7FvFh9bePBvcGLmLwMzf18tB9ur5fYwPzIPf1bL1dLcva3XF/hPv83i09y@nmGozOLvMZv9ZOb@mqlqMmV4gc9nl1lW4Xu@BweYlAlAKwmEQCjLBOwjiJ5XlknMxDgvE2PZKC1REwiBUNcJtCXsZ6fE2JeoE2NZBRIuYARjIpTDoa3GMRPnHoVLGWPECOKbGAMtb/YnPUYcqarCfEp51DqtGpGE@CZGYqqcca51ypiqprSPYOhpI2WE1AM0ZUXrhRCpDwqQ/@7eJWk8tPPQ69EaMRvZOJ3mww4PR@RBUSKkANVE6Pj/IBTEJf/dvUuC6m5OyPepaYui03woexBV34wOIc8tOUeDThsWBUABFor@kCh3wo4Rx2j@/h06UmEHokXYKKTeCsFDS4vCtlSUhfBh221uR0kU1OQghFsZf9pQSkDhLMh@IeyKkRAh7Bjt4MZCuEEIaxntZk/YJ4SbCa1VGAUp7SjoWmoftlPC7WZrGQ3HFw "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-pF`, 48 bytes
```
$\=join'',<>;say map$\=~s/$_/lc$_/e&&lc||$_,@F}{
```
[Try it online!](https://tio.run/##K0gtyjH9/18lxjYrPzNPXV3Hxs66OLFSITexAChWV6yvEq@fkwwkUtXUcpJralTidRzcaqv//3dzc0UDXAEKQMDlCiMDAkAkUByTBCnFJv0vv6AkMz@v@L@ur6megaHBf90CNwA "Perl 5 – Try It Online")
First line of input is the passenger list. All subsequent lines are the seat map. Output is the same.
] |
[Question]
[
Suppose you have two six-sided dice. Roll the pair 100 times, calculating the sum of each pair. Print out the number of times each sum occurred.
If a sum was never rolled, you must include a zero or some way to identify that that particular sum was never rolled.
Example Output:
[3, 3, 9, 11, 15, 15, 11, 15, 7, 8, 3]
The number of times a sum was rolled is represented in the sums index - 2
In this example, a sum of two was rolled 3 times ([2-2]), a sum of three 3 times ([3-2]), a sum of four 9 times ([4-2]), and so on. It does not matter the individual dice rolls to arrive at a sum (5 and 2 would be counted as the same sum as 6 and 1)
"Ugly" outputs are fine (loads of trailing zeros, extra output, strange ways of representing data, etc.) as long as you explain how the data should be read.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
³Ḥ6ẋX€+2/ṢŒr
```
A niladic link. Output format is a list of lists of `[value, count]`.
(Zero rolls means no such entry is present in the output - e.g. an output of`[[6, 12], [7, 74], [8, 14]]` would identify that only sums of six, seven and eight were rolled.)
**[Try it online!](https://tio.run/nexus/jelly#ASIA3f//wrPhuKQ24bqLWOKCrCsyL@G5osWScv//9W5vLWNhY2hl)**
### How?
```
³Ḥ6ẋX€+2/ṢŒr - Main link: no arguments
³ - 100
Ḥ - double = 200
6 - 6
ẋ - repeat -> [6,6,6...,6], length 200
X€ - random integer from [1,z] for €ach (where z=6 every time)
2/ - pairwise reduce with:
+ - addition (i.e. add up each two)
Ṣ - sort
Œr - run-length encode (list of [value, length] for each run of equal values)
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~84~~ ~~77~~ 76 bytes
*-7 bytes thanks to @JonathanAllan*
*-1 byte thanks to @FelipeNardiBatista*
```
from random import*
a=[0]*13
exec'a[%s]+=1;'%('+randint(1,6)'*2)*100
print a
```
[Try it online!](https://tio.run/nexus/python2#@59WlJ@rUJSYlwKkMnML8otKtLgSbaMNYrUMjblSK1KT1ROjVYtjtW0NrdVVNdS1QUoz80o0DHXMNNW1jDS1DA0MuAqKgEIKif//f83L101OTM5IBQA "Python 2 – TIO Nexus")
The output has two leading zeros
[Answer]
# [Perl 6](http://perl6.org/), 30 bytes
```
bag [Z+] (^6).pick xx 100 xx 2
```
`(^6).pick` is a random number from zero through five. `xx 100` makes a hundred-element list of such numbers. `xx 2` produces two such lists. `[Z+]` zips those two lists with addition, producing a hundred-element list of two-die rolls. Finally, `bag` puts that list into a bag, which is a collection with multiplicity. Example REPL output:
```
bag(1(4), 9(4), 0(4), 4(14), 5(18), 3(9), 10(2), 6(19), 7(13), 2(3), 8(10))
```
That means 1, 9, and 0 occurred four times each, four occurred fourteen times, etc. Since the "dice" in this code produce a number from 0-5, add two to each of these numbers to get the rolls a pair of standard 1-6 dice would produce.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~21~~ 19 bytes
-2 bytes thanks to @Emigna
```
TÝÌтF6Lã.RO¸ì}{γ€g<
```
[Try it online!](https://tio.run/##ASYA2f8wNWFiMWX//1TDncOM0YJGNkzDoy5ST8K4w6x9e86z4oKsZzz//w "05AB1E – Try It Online")
```
TÝÌтF6Lã.RO¸ì}{γ€g<
TÝÌ Range from 2 to 12
тF 100 times do:
6L Range from 1 to 6
ã Cartesian product (creates all possible pairs of 1 and 6)
.RO Choose random pair and sum
¸ì Prepend result to initial list
} end loop
{γ€g< Sort, split on consecutive elements, count and decrement
```
[Answer]
# Mathematica, 50 bytes
```
r:=RandomInteger@5
Last/@Tally@Sort@Table[r+r,100]
```
Straightforward implementation. If any sum is never achieved, the `0` is omitted from the list.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 17 bytes
```
6H100I$Yrs!11:Q=s
```
Output is a list of 11 numbers (some of them possibly 0) separated by spaces, indicating the number of times for each pair from 2 to 12.
[Try it online!](https://tio.run/nexus/matl#@2/mYWhg4KkSWVSsaGhoFWhb/P//17x83eTE5IxUAA "MATL – TIO Nexus")
For comparison, the theoretical average number of times each pair will appear on average can be computed as [`6:gtY+36/100*`](https://tio.run/nexus/matl#@29mlV4SqW1spm9oYKD1/z8A).
If the number of rolls is increased the obtained values [approach](https://en.wikipedia.org/wiki/Law_of_large_numbers) the theorerical ones. See for example the [obtained](https://tio.run/nexus/matl#@2/mYZhq4qkSWVSsaGhoFWhb/P//17x83eTE5IxUAA) and [theoretical](https://tio.run/nexus/matl#@29mlV4SqW1spm@YaqL1/z8A) values with 10000 rolls.
[Answer]
## CJam, ~~18~~ 20 bytes
```
100{;6mr6mr+))}%$e``
```
[Try it online!](https://tio.run/nexus/cjam#@29oYFBtbZZbBETampq1qiqpCQn//wMA)
[Answer]
# [R](https://www.r-project.org/), ~~45~~ ~~37~~ 35 bytes
```
`[`=sample;table(6[100,T]+6[100,T])
```
[Try it online!](https://tio.run/##K/r/PyE6wbY4MbcgJ9W6JDEpJ1XDLNrQwEAnJFYbxtD8/x8A "R – Try It Online")
*-7 bytes thanks to Jarko Dubbledam*
[Answer]
# PHP, 53 Bytes
prints an associative array. key is result of two dices and value is the count of these results
```
for(;$i++<100;)$r[rand(1,6)+rand(1,6)]++;print_r($r);
```
[Try it online!](https://tio.run/nexus/php#s7EvyCj4n5ZfpGGtkqmtbWNoYGCtqVIUXZSYl6JhqGOmqQ1nxWprWxcUZeaVxBdpqBRpWv//DwA "PHP – TIO Nexus")
[Answer]
# [S.I.L.O.S](https://github.com/rjhunjhunwala/S.I.L.O.S), 99 bytes
```
i=100
lbla
x=rand*6+rand*6
a=get x
a+1
set x a
i-1
if i a
lblb
c=get b
printInt c
b+1
d=11-b
if d b
```
[Try it online!](https://tio.run/nexus/silos#Jcu7DYAwDITh/qZwDYqEG7oMwBh2wsMSCghSsDh1CFDdX3xXzHPXYdVVcPlDUmz69h@In8dMF6RlnG@RwBzDJrKa9aMIn1Hsh6U8pEwBWnn0zE5fGUlLudPmgoRlfAA "S.I.L.O.S – TIO Nexus")
Rolls the dice, and stores them in the first 11 spots of the heap, then just iterates through the heap printing each counter. This is one of the first recorded uses of the rand keyword combined with an assignment operator.
It is worth noting, that a few modifications can be made to output a histogram of the rolls. [](https://i.stack.imgur.com/Ca4ZH.png)
Unfortunately it must be run from the [offline interpreter](https://github.com/rjhunjhunwala/S.I.L.O.S/blob/master/Silos.java).
```
i=4000
lbla
x=rand*6+rand*6
a=get x
a+1
set x a
i-1
if i a
canvas 1100 1000 Output
lblb
c=get b
printInt c
d=c*1
y=1000-d
x=b*100
newObj 0 100 d
moveObj b x y
b+1
d=11-b
if d b
wait 10000
```
[Answer]
**Elixir, ~~157~~ 118 bytes**
```
l=&Enum.random(1..&1)
p=fn(o,s)->y=l.(6)+l.(6)
s=List.update_at(s,y,&(&1+1))
if Enum.sum(s)<100 do s=o.(o,s) end
s end
```
Tried something harder than Jelly.
Explanation:
1. Define function that returns a random number between 1 and 6 inclusive.
2. Define the function anonymously and let `y` be the variable with the roll sum.
3. update the appropriate place in the list by adding 1.
4. if we are 100 rolls in, quit. Else call yourself again passing in yourself and the updated list.
5. return the updated array.
Should be called like `p.(p,[0,0,0,0,0,0,0,0,0,0,0,0,0])`. It will raise a warning, but it will return the desired array with 13 elements, the first 2 should be ignored.
[Answer]
# Java 8, 104 bytes
A lambda returning an `int[]` of frequencies. Assign to `Supplier<int[]>`.
```
()->{int o[]=new int[11],i=0;while(i++<100)o[(int)(Math.random()*6)+(int)(Math.random()*6)]++;return o;}
```
[Try It Online](https://tio.run/##bc8xb4MwEAXgGX6FR7s0FixdCJG6dMvEiBhccMgRc6b2mSiK@O3UUSq1Q9d796T3jWpROztrHPvLNodPAx3rjPKeHRUgu6fJ7GBRpJknRTE8ASrDxliTgcDIU8COwKKswzwb0G4PSE17YD10ug7Th9NfnlUbF7vDPUbMNm2F@soeb0XRvkKVl9czGM0hy/ZFngvb8BgKflR0lk5hbycuXt5E9v@5zbLSaQoOmS3XLSnTOPop@dm8WOjZFD28Jgc4NC1TbvDiwUvqmyc9SRtIRiqSQf6re3dO3bwk@yzyvyg5aOJCiDJN1nTdvgE)
## Ungolfed lambda
```
() -> {
int
o[] = new int[11],
i = 0
;
while (i++ < 100)
o[(int) (Math.random() * 6) + (int) (Math.random() * 6)]++;
return o;
}
```
[Answer]
# q/kdb+, ~~31~~ ~~28~~ 25 bytes
**Solution:**
```
sum!:[11]=/:sum(2#100)?'6
```
**Example:**
```
q)sum!:[11]=/:sum(2#100)?'6
1 3 5 11 16 21 16 9 8 9 1i
```
**Explanation:**
Roll a dice `100?6` , roll a dice again and add the vectors together. Then see where each results matches the range 0..10, then sum up all the trues in each list:
```
sum til[11]=/:sum(2#100)?'6 / ungolfed solution
(2#100) / 2 take 100, gives list (100;100)
?'6 / performs rand on each left-each right, so 100 & 6, 100 & 6
sum / add the lists together
til[11] / the range 0..10
=/: / apply 'equals?' to each right on left list
sum / sum up the results, e.g. how many 1s, 2s, 3s.. 12s
```
**Notes:**
'Golfing' is mostly swapping out `q` keywords for the `k` equivalents, namely `each` and `til`.
[Answer]
# JavaScript, ~~72~~ 70 bytes
Outputs an array of *up to* 11 elements for each of the roll counts. Except for the first element, if the count is `0` then the element will be empty or, if it's at the end of the array, omitted completely.
```
f=(a=[n=0])=>n>99?a:f(a,a[x=(g=_=>Math.random()*6|0)()+g(++n)]=-~a[x])
```
[Try it online!](https://tio.run/##DcxLDoIwEADQq3ThYsYCQRdGSQZO4AmQ2Il8LIFCSoMQP1ev7F9eyzNPD6tHF85n72sCptxQXCClJr1cMk5q4IDzhaChO6VXds/IsimHHnB/@sQIKBuQ0mBB4W@DBfrRauOgBox6HgGWYN06WOURpRIvnoQduq4qxe69fIXTfaUkLOEhU5NKlEKM2kEbdTMK/R8)
[Answer]
## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 45 bytes
```
[100|h=_r1,6|+_r1,6|-2┘g(h)=g(h)+1][0,z|?g(b)
```
Explanation:
```
[100| FOR a = 1 to 100
h=_r1,6| set h to a random value between 1-6
+_r1,6| + another rnd(1,6) (2, 3 ... 11, 12)
-2 - 2 (index: 0 ... 10
┘ Syntactic linebreak
g(h) When using array parenthesis on an undefined array,
it is interpreted as an array with 10 indexes of all zeroes.
= Of array g, set the value of index h (0 ... 11)
g(h)+1 to one higher (all indices start out as 0)
Note that we need to track 11 values. Fortunately, QBasic'set
empty, 10-sized array has 11 indices, because of base 0 / base 1 ambiguity.
] NEXT set of dice
[0,z| FOR b = 0 to 10
?g(b) PRINT the tracker array
```
[Answer]
# APL, 14 bytes
```
,∘≢⌸+/?100 2⍴6
```
Presents data as a table with the left column representing the sum and the right representing the number of occurrences.
**Explained**
```
100 2⍴6 ⍝ create an 2×100 array of 6
? ⍝ roll for each cell from 1 to 6
+/ ⍝ sum every row
⌸ ⍝ for every unique sum
,∘≢ ⍝ get the sum and the number of indexes
```
---
**Previous post:**
### APL, ~~36~~ 31 bytes
*5 bytes saved thanks to @Adám*
```
(11⍴⍉⌽f)[⍋11⍴⍉f←,∘≢⌸+/?100 2⍴6]
```
**Explanation**
```
f←,∘≢⌸+/?100 2⍴6
100 2⍴6 ⍝ create an 2×100 array of 6
? ⍝ roll for each cell from 1 to 6
+/ ⍝ sum every row
⌸ ⍝ for every unique sum
,∘≢ ⍝ get the sum and the number of indexes
(11⍴⍉⌽f)[⍋11⍴⍉f] ⍝ ⍋x returns the indexes of the sorted x in the current x
⍝ x[y] find the yth elements of x
⍝ x[⍋y] reorders x the same way that would be required to sort y
11⍴⍉f ⍝ the column of sums - see below
11⍴⍉⌽f ⍝ the column of counts - see below
```
**How does `11⍴⍉⌽f` works?**
```
⍝ ⌽ - Reverses the array
⍝ ⍉ - Transposes the array
⍝ f
9 14 ⍝ Sum - Occurences
4 9
7 17
8 18
6 15
5 7
10 3
11 5
3 6
2 2
12 4
⍝ ⍉f
9 4 7 8 6 5 10 11 3 2 12 ⍝ Sum
14 9 17 18 15 7 3 5 6 2 4 ⍝ Occurences
⍝ ⍉⌽f
14 9 17 18 15 7 3 5 6 2 4 ⍝ Occurences
9 4 7 8 6 5 10 11 3 2 12 ⍝ Sum
```
[Answer]
## [><>](https://esolangs.org/wiki/Fish), 93 bytes
```
00[0[v
v 1\v/4
v 2xxx5
v 3/^\6
>l2(?^+]laa*=?v0[
/&1+&\ v1&0]<
=?/ :?!\}>:@@:@
oa&0n&}< ^+1
```
[Try it online](https://tio.run/##DcW9CsMgEADg3ae4LlIqxTP9GWzM@R4aQaQlgZAMhcMlj93Z5lu@z/ydWkMMGFgwmMj6ftzVWh/HN53iUwxLd6akxiXniyPGIAC0NEpGYCNx7IUjDZZOcR@s99aLLUtc5d5DUuZFrtjWfut2LblM7z8 "><> – Try It Online"), or watch it at the [fish playground](https://fishlanguage.com/playground)!
The ugly output format is a sequence of numbers separated by newlines, where the *n*th number says how many times the sum was *n* — it's ugly because it prints forever, for all positive integers *n*, although most of the lines will be 0. (The TIO link is modified to stop after *n*=12, at the cost of 5 bytes.)
The fish playground is fairly slow — it takes about three and a half minutes to print up to *n*=12 at top speed — so you may want to modify it to roll 10 pairs of dice instead of 100 by changing the `aa*` in the 5th line to `a` (that is, `a` followed by two spaces).
The random dice rolls are done by this bit:
```
1\v/4
2xxx5
3/^\6
```
The `x`s change the fish's direction randomly. Assuming that's implemented with equal probabilities, it's clear that the die roll result is a uniform distribution by symmetry.
Once the fish has rolled 100 pairs of dice, it counts how many times the sum was *n* with this bit (unwrapped for clarity, and starting in the top left):
```
v /&1+&\
>:@@:@=?/ :?!\}
^ +1oa&0n&}<
```
We keep *n* at the front of the stack, and use the register to count the number of times *n* appears.
[Answer]
## Javascript ~~85~~ 75 characters
Thanks Shaggy!
```
a=[]
for(i=100;i--;)a[o=(f=_=>Math.random()*6|0)()+f()]=(a[o]|0)+1
alert(a)
```
### History
### 85
```
a={}
f=_=>Math.random()*6
for(i=0;i++<100;)a[o=-~f()-~f()]=(a[o]||0)+1
console.log(a)
```
[Answer]
# [Perl 5](https://www.perl.org/), 64 bytes
```
map$s{2+int(rand 6)+int rand 6}++,1..100;say"$_ $s{$_}"for 2..12
```
[Try it online!](https://tio.run/##K0gtyjH9/z83sUCluNpIOzOvRKMoMS9FwUwTxFaAsGu1tXUM9fQMDQysixMrlVTiFYCKVeJrldLyixSMgBJG////yy8oyczPK/6v62uqZ2BoAAA "Perl 5 – Try It Online")
Output format:
`<sum> <# rolls>`
For sums with zero rolls, the rolls column is blank.
[Answer]
# PHP, 65 bytes
```
while($i++<100)${rand(1,6)+rand(1,6)}++;for(;++$k<13;)echo+$$k,_;
```
prints a leading `0_` and then the occurences of 2 to 12, followed by an underscore each.
Run with `-nr` or [try it online](http://sandbox.onlinephpfunctions.com/code/37803b01836e4ebae03c7d095c619afd48a1a749).
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), ~~24~~ 22 bytes
**Solution:**
```
+/(!11)=/:+/(2#100)?'6
```
[Try it online!](https://tio.run/##y9bNz/7/X1tfQ9HQUNNW3wrIMlI2NDDQtFc3@/8fAA "K (oK) – Try It Online")
**Explanation:**
`k` 'port' of my `q` solution. Evaluation occurs right-to-left, hence brackets around the til (`!`)
```
+/(!11)=/:+/(2#100)?'6 / the solution
(2#100) / the list (100;100)
?'6 / take 6 from each left/each right (roll the dice twice)
+/ / sum rolls together
(!11) / til, performs range of 0..n-1, thus 0..10
=/: / equals each right (bucket the sum of the rolls)
+/ / sum up to get counts per result
```
**Edits:**
* -2 bytes switching the each-left for an each-both, and the each-left + flip for each-right
[Answer]
# Pyth, 21 bytes
```
V100aY,O6O6)VTlfqsTNY
```
Outputs each step in the creation of the rolls, then outputs frequency of each sum 0 - 10 on a separate line.
---
```
V100aY,O6O6)VTlfqsTNY Full program, no input, outputs to stdout
V100 For N from 0 to 100
a ,O6O6 Append a pair of random ints below 6
Y To a list Y, initialized to the empty list
) Then
VT For N from 0 to 10
f Y Print Y filtered to only include pairs
q N For which N is equal to
sT The sum of the pair
```
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 95 bytes
```
a->{int r[]=new int[11],i=0,d=0;for(;i++<200;)r[d+=Math.random()*6]+=i%2<1?1-(d=0):0;return r;}
```
[Try it online!](https://tio.run/##RU89b4MwEN3zK26pZBewTIYONU7VpVvUISNicPhITY2NzJEKRfx2akiqnnR69/nuXquuKnF9bdvqe@nHs9EllEYNAxyVtnDbATyqAyoMcHW6gi70yAm9tpe8AOUvA91GAdrAx0bUhjWjLVE7yz4eQfZ5busSY9AW8@IADchFJYdbSMHnhbT1z9ZK0yLWkseV5KJxnggdRdmec0F9XkXyqPCLeWUr1xH6/FJEUj/ts/QtTUjYoK9c@BpHb8GLeYHNxPbayrXe0iCBiwAZpCtG0d/zAKdpwLpjbkTWB3VoLPlX9O69mgaG7q6cNEz1vZmIHY2hlN6vzLvV5@UX "Java (OpenJDK 8) – Try It Online")
## Explanations
```
a->{
int r[] = new int[11], // Rolls or result
i = 0, // Iteration
d = 0; // Dice accumulator
for (;i++<200;)
r[d+=Math.random()*6] += // Accumulate a new die and start an addition
i % 2 < 1 // Accumulate up to two dice
? 1 - (d = 0) // If we're at 2 dice, reset the accumulator and add 1
: 0; // If we only have one die, add 0
return r;
}
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes
```
₁ƛ6℅6℅+;Ċ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigoHGmzbihIU24oSFKzvEiiIsIiIsIiJd)
Returns a list of `[roll, count]`. If a roll total didn't happen, then it isn't included in the list.
## Explained
```
₁ƛ6℅6℅+;Ċ
₁ƛ # for each item in range(1, 100 + 1):
6℅6℅ # push a random number from range(1, 6 + 1) and then another random number from that range
+ # and add them together
; # end map - this leaves 100 random dice rolls in a list.
Ċ # get the count of each item
```
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 18 bytes
```
1J6rn200.+2CO)++f:
```
[Try it online!](https://tio.run/##SyotykktLixN/f/f0MusKM/IwEBP28jZX1NbO83q/38A "Burlesque – Try It Online")
```
1J6rn # Infinite random d6 rolls
200.+ # Take first 200
2CO # Chunks of 2
)++ # MapSum
f: # Frequency list
```
] |
[Question]
[
Print a tower block with the shortest possible code.
**Input:**
The input defines how many floors the tower block has. One floor contains a window on either side of the door. The window is made up of 3x3 hashes.
An example of a 4 storey tower block is below:
```
=====================
)V V V V V V V V V V(
)V V V V V V V V V V V(
)V V V V V V V V V V V V(
)V V V V V V V V V V V V V(
~~~~~~~~~~~~~~~~~~~~~~~~~~~
: : : : : : : : : : : : : :
: : ### : : : : : : ### : :
: : ### : : : : : : ### : :
: : ### : : : : : : ### : :
: : : : : : : : : : : : : :
: : : : : : : : : : : : : :
: : ### : : : : : : ### : :
: : ### : : : : : : ### : :
: : ### : : : : : : ### : :
: : : : : : : : : : : : : :
: : : : : : : : : : : : : :
: : ### : : : : : : ### : :
: : ### : : : : : : ### : :
: : ### : : : : : : ### : :
: : : : : : : : : : : : : :
: : : : : _______ : : : : :
: : ### : I I : ### : :
: : ### : I I : ### : :
: : ### : I I : ### : :
: : : : : I I : : : : :
```
**Update:**
The input has to be one or greater.
Trailing spaces at the end of lines are allowed.
In my example, every line has three leading spaces. This isn't mandatory, just the tower block with the input is.
[Answer]
## Mathematica, 301 288 258 bytes
```
" "~(s=If[#2==0,"",#~StringRepeat~#2]&)~3<>{"="~s~21,"
",s[" ",12-#]<>{")","v "~s~#,"v(
"}&/@9~Range~12,"~"~s~27,"
",s[(x=(u=": ")~s~13<>":
")<>{y=u<>{z=": ### ",v=u~s~5,w=z<>": :
"},y,y,x},#-1],v,"_"~s~7," ",v,"
",m=u<>{z,u,n="I I ",w},m,m,v,n,w}&
```
Pure function which takes a positive integer and outputs a string. The output string won't look right because Mathematica apparently doesn't display monospace fonts as monospace:
[](https://i.stack.imgur.com/cVrJH.png)
For reasons I don't quite understand, it does format as monospace if you `Print` the string:
[](https://i.stack.imgur.com/Ru8Jh.png)
Edit: Saved several bytes by not including `" "` at the beginning of each line. Changed the definition of `s` to handle the case where there is only one floor (`StringRepeat` doesn't like repeating a string `0` times).
Edit 2: Thanks to [LegionMammal978](https://codegolf.stackexchange.com/users/33208/legionmammal978) and the fact that `StringJoin` is `Listable`, this is now an incomprehensible nightmare of nested lists and also 30 bytes shorter.
[Answer]
# [V](https://github.com/DJMcMayhem/V), 72 bytes
```
13iV r(É)3ñįlxñÄ21r=GÙÒ~Ù14R: ÙÄ2w3r#7w.3ÄkdGÀpG4k5w7r_bêojrIÎfIl5r
```
[Try it online!](https://tio.run/nexus/v#@29onBmmIF2kcbhT0/jwxsMth9bnVIBoI8MiW/fDMw9Pqjs809AkyEpBGshpMSo3LlI2L9czPtySneJ@uKHA3STbtNy8KF4s6fCq/Kwiz8N9aZ45pkUK////NwEA "V – TIO Nexus")
Here is a hexdump, since this contains unprintable characters:
```
00000000: 3133 6956 201b 7228 c929 33f1 c4af 6c78 13iV .r(.)3...lx
00000010: f1c4 3231 723d 47d9 d27e d931 3452 3a20 ..21r=G..~.14R:
00000020: 1bd9 c432 7733 7223 3777 2e33 c46b 6447 ...2w3r#7w.3.kdG
00000030: c070 4734 6b35 7737 725f 1662 ea6f 6a72 .pG4k5w7r_.b.ojr
00000040: 49ce 6649 6c35 7220 I.fIl5r
```
I ran into a strange bug. The section in the middle: `dGÀpG` should have been: `ÀäGG`, but this does not work for inputs of 1, and I have no idea why. `¯\_(ツ)_/¯`
[Answer]
# [Python 2](https://docs.python.org/2/), ~~275~~ ~~270~~ ~~262~~ ~~246~~ ~~240~~ 236 bytes
Saved a couple with a hint from @Flp.Tkc and by changing the first for loop.
16 saved with more help from @Flp.Tkc
```
a,h,b,c,w=' ',"I ",": "," :","#"*3;d,e,j=b*2+w+a+b+h,b*5+h,[b*14]
print'\n'.join([a*3+'='*21]+[a*(4-x)+')'+'V '*(x+8)+'V('for x in 1,2,3,4]+['-'*27]+(j+[b*2+w+c*6+a+w+c*2]*3+j)*(input()-1)+[b*5+"_"*7+c*5]+[d+a+d[::-1]]*3+[e+a+e[::-1]])
```
[Try it online!](https://tio.run/nexus/python2#LY3LCsIwEEX3fkWIi0lmpkL6UKn0A/wBNzFIX2K7iCKK/fs6RTd3OHDunbnmGzfc8qcCBayPSmnW5RKqlFhrzA4d9zxWDab0oZoakgYWkr5Bl4fV4znEF5wjbMb7EI2vMSOoAFMXSMDkyWQJLBCcFKCZaC94MnC9P9Wkhqgcp5xxLjYkUtsFMiP5378Wt/JzuWmQ3dGiGeLj/TI2cXaRCtIXjTsRChnoRO58WSYuLLrvhfs/23nOvg "Python 2 – TIO Nexus")
Just builds each line of the tower as a string and adds it to an array them prints the array at the end. If anyone wants a full explanation I'll grudgingly give if I can remember how it works ☺
[Answer]
# [PowerShell](https://github.com/PowerShell/PowerShell), 193 bytes
```
" "+"="*21
3..0|%{" "*$_+")"+"V "*(12-$_)+"V("}
"~"*27
--$args[0]..0|%{($b=": "*5)+(($a=": "*4),'_______ ')[!$_]+$b;,(': : ### : '+($a,($c='I I '))[!$_]+': ### : :')*3;$b+($a,$c)[!$_]+$b}
```
[Try it online!](https://tio.run/nexus/powershell#PcxLDoJADAbgPaeopaYdBggPjckQDsAF3BAyYVi416Xi1ccq6r9o2vRrIwIAWuwxa@qkLcvqsb8jYEbeotHFWXupm4K80UFwTfCp9pQUBc3Xy22spu1IKPToVB@NFaF5Gw4mZ78F2Iw78pOl0OXCDhykaaqVrfJcaOl5gHcGpV/LP@TYZG1H4WNp@b9aY4ztCw "PowerShell – TIO Nexus")
*(I feel there may still be a few bytes here or there. Sub-190 seems doable.)*
The first three lines form the roof, using string multiplication and concatenation, along with a loop `3..0|%{...}` to get the correct number and sloping of `V`s.
The next line runs from the input pre-decremented `--$args[0]` down to `0` as a loop (the pre-decrement allows us to index using `!$_` instead of `$_-eq1` saving several bytes later). Each loop iteration, we're constructing a bunch of strings, setting variables `$b` and `$a` along the way. We're also using pseudo-ternaries `(... , ...)[...]` to choose the appropriate strings for the middle so we can get the doorway on the first floor correct.
Each of the strings are left individually on the pipeline, and the default `Write-Output` inserts newlines between, so we get those for free.
[Answer]
# T-SQL, ~~378~~ ~~372~~ ~~353~~ ~~331~~ 325 bytes
**Golfed:**
```
DECLARE @ INT=3
,@h varchar(max)=REPLICATE('~',27)SELECT @h+='
: '+a+IIF(n>@*5-6,IIF(n%5=0,'_______ ','I I '),t)+a+':'FROM(SELECT
IIF(n%5%4=0,t,': ### : ')a,*FROM(SELECT': : : : 't,number n,*FROM spt_values)x)y
WHERE type='P'and n<@*5SET @=0WHILE @<4SELECT
@h=SPACE(@)+')'+REPLICATE('V ',12-@)+'V(
'+@h,@+=1PRINT' '+REPLICATE('=',21)+'
'+@h
```
**Ungolfed:**
```
DECLARE @ INT=3
,@h varchar(max)=REPLICATE('~',27)
SELECT @h+='
: '+a+IIF(n>@*5-6,IIF(n%5=0,'_______ ','I I '),t)+a+':'
FROM
(SELECT IIF(n%5%4=0,t,': ### : ')a,*
FROM
(SELECT': : : : 't,number n,*
FROM spt_values)x)y
WHERE type='P'and n<@*5
WHILE @>=0
SELECT @h=SPACE(3-@)+')'+REPLICATE('V ',9+@)+'V(
'+@h,@-=1
PRINT' '+REPLICATE('=',21)+'
'+@h
```
**[Try it out](https://data.stackexchange.com/stackoverflow/query/1031249/print-me-a-tower-block)**
[Answer]
# C, ~~409~~ ~~406~~ 402 bytes
```
#define P(x)p(": ",x);
#define S(x)p(x,1);
#define L P(2)p("#",3);p(" :",6);S(" ###");S(" : :\n")
#define Q p("V ",i+++9)
p(s,n)char*s;{printf(s,--n?p(s,n):0);}i;t(n){p(" ",3);p("=",21);S("\n )")Q;S("V(\n )")Q;S("V(\n )")Q;S("V(\n)")Q;S("V(\n")p("~",27);S("\n")for(;--n;){P(13)S(":\n")L;L;L;P(13)S(":\n")}P(5)p("_",7);p(" :",5);S("\n")p(": : ### : I I : ### : :\n",3);P(5)S("I I")p(" :",5);}
```
Call with:
```
int main()
{
t(4);
}
```
[Answer]
## Batch, 373 bytes
```
@echo off
set s=###
echo %s:#========%
for %%s in (" )" " )V " " )V V " ")V V V ")do echo %%~sV%s:#= V V V%(
echo %s:#=~~~~~~~~~%
set t=: : ### : I I : ### : :
set s=%t:I I=: : : :%
for /l %i in (2,1,%1)do echo %s:###=: :%&echo %s%&echo %s%&echo %s%&echo %s:###=: :%
set s=%t:###=: :%
echo %s:I I=_______%
echo %t%
echo %t%
echo %t%
echo %s%
```
Builds the ridge and gutter by noticing that they are multiples of 3, which shaves off a few bytes. Builds the roof by noticing that the suffix is the same for each line (and again includes some threefold repetition). Builds the walls by starting with the most interesting line of wall, which is the ground floor window, and removing details to generate the other parts of the wall.
[Answer]
# Javascript, 335 bytes
```
y=z=>{a=" "+"=".repeat(21);for(b=9;13>b;b++)a+="\n"+" ".repeat(12-b)+")"+"V ".repeat(b)+"V(";a+="\n"+"~".repeat(27);b="\n"+": ".repeat(14);c=": : ### : : : : : : ### : :";for(d=0;d<z-1;d++)a+=b+"\n"+c+"\n"+c+b;a+="\n: : : : : _______ : : : :\n"+": : ### : I I : ### : :\n".repeat(3)+": : : : : I I : : : : :";console.log(a)};
```
Creates a function `y()` with argument `z`, such that `y(z)` produces the desired output.
# Example Usage:
```
y=z=>{a=" "+"=".repeat(21);for(b=9;13>b;b++)a+="\n"+" ".repeat(12-b)+")"+"V ".repeat(b)+"V(";a+="\n"+"~".repeat(27);b="\n"+": ".repeat(14);c=": : ### : : : : : : ### : :";for(d=0;d<z-1;d++)a+=b+"\n"+c+"\n"+c+b;a+="\n: : : : : _______ : : : :\n"+": : ### : I I : ### : :\n".repeat(3)+": : : : : I I : : : : :";console.log(a)};
console.log(y(3));
```
I'm transitioning from normal JavaScript to code-golf JS. Any tips would be greatly appreciated.
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), ~~62~~ 61 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
⁶=⁵×V7× * )×4*∔/‾²m~7«× ×∔│8 ×:*5*#33*62╋│⁸*∔l4-_7× 5×Ie4*∔╋╋
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXUyMDc2JTNEJXUyMDc1JUQ3ViV1RkYxNyVENyUyMCV1RkYwQSUyMCUyOSVENyV1RkYxNCV1RkYwQSV1MjIxNCV1RkYwRiV1MjAzRSVCMiV1RkY0RCU3RSV1RkYxNyVBQiVENyUyMCVENyV1MjIxNCV1MjUwMiV1RkYxOCUyMCVENyUzQSV1RkYwQSV1RkYxNSV1RkYwQSUyMyV1RkYxMyV1RkYxMyV1RkYwQSV1RkYxNiV1RkYxMiV1MjU0QiV1MjUwMiV1MjA3OCV1RkYwQSV1MjIxNCV1RkY0QyV1RkYxNCV1RkYwRF8ldUZGMTclRDclMjAldUZGMTUlRDdJJXVGRjQ1JXVGRjE0JXVGRjBBJXUyMjE0JXUyNTRCJXUyNTRC,i=NA__,v=8) Input 0 works as expected even though that's not required.
] |
[Question]
[
# Background
You are working as a programmer for a car sales company.
Your task for this week is to program an XML parser that takes in data about available models from different car manufacturers, and pretty-prints information about the newest models.
Luckily for you, the testing department has provided only one test case!
The faster you can write code that passes it, the more time you have for procrastination during the rest of the week.
# Input
Your input is *exactly* this piece of XML data, supplied by the testing department.
It contains data about some car manufacturers, their series of cars, and the models in these series.
You may assume a trailing newline.
```
<?xml version="1.0" ?>
<products>
<manufacturer name="Test Manufacturer 1">
<series title="Supercar" code="S1">
<model>
<name>Road Czar</name>
<code>C</code>
<year>2011</year>
</model>
<model>
<name>Ubervehicle</name>
<code>U</code>
<year>2013</year>
</model>
<model>
<name>Incredibulus</name>
<code>I</code>
<year>2015</year>
</model>
<model>
<name>Model 1</name>
<code>01</code>
<year>2010</year>
</model>
</series>
<series title="Test series 22" code="Test">
<model>
<name>Test model asdafds</name>
<code>TT</code>
<year>2014</year>
</model>
</series>
</manufacturer>
<manufacturer name="Car Corporation">
<series title="Corporation Car" code="CC">
<model>
<name>First and Only Model</name>
<code>FOM</code>
<year>2012</year>
</model>
</series>
</manufacturer>
<manufacturer name="Second Test Manufacturer">
<series title="AAAAAAAAAAAAAA" code="D">
<model>
<name>Some older model</name>
<code>O</code>
<year>2011</year>
</model>
<model>
<name>The newest model</name>
<code>N</code>
<year>2014</year>
</model>
</series>
<series title="BBBBBBBBBBBBBBB" code="asdf">
<model>
<name>Another newest model here</name>
<code>TT</code>
<year>2015</year>
</model>
</series>
</manufacturer>
</products>
```
# Output
Your output is this string.
It lists the car manufacturers in alphabetical order, followed by a colon and the number of series they make.
Under each manufacturer, it lists the series name, model name, and code of each of their models, starting from the newest and going backward by year.
Trailing whitespace and line breaks are acceptable, as long as your output looks similar to this when printed.
```
Car Corporation: 1 series
Corporation Car, First and Only Model (CC-FOM)
Second Test Manufacturer: 2 series
BBBBBBBBBBBBBBB, Another newest model here (asdf-TT)
AAAAAAAAAAAAAA, The newest model (D-N)
AAAAAAAAAAAAAA, Some older model (D-O)
Test Manufacturer 1: 2 series
Supercar, Incredibulus (S1-I)
Test series 22, Test model asdafds (Test-TT)
Supercar, Ubervehicle (S1-U)
Supercar, Road Czar (S1-C)
Supercar, Model 1 (S1-01)
```
# Rules and Scoring
You may write either a function or full program.
The lowest byte count wins, and standard loopholes are disallowed.
Note that the input is fixed: you don't need to support any other inputs than the one given here.
Your program is allowed to return nonsense or even crash if the input is modified in any way.
You may also ignore the input and hard-code the output, if desired.
However, you may *not* use XML or HTML parser libraries or built-ins.
[Answer]
# [Bubblegum](https://esolangs.org/wiki/Bubblegum), ~~227~~ 225 bytes
```
0000000: 6d 50 45 b6 02 31 10 dc cf 29 6a 87 eb 92 1d ee 0e 07 mPE..1...)j.......
0000012: 08 93 1e 3c e1 45 be 9d fe 37 ae bd 2b 7d 95 54 85 41 ...<.E...7..+}.T.A
0000024: 55 9b 83 36 c2 ad b5 2a a1 00 4b 66 4d 36 c0 23 0f f6 U..6...*..KfM6.#..
0000036: a5 d1 58 1b eb 20 94 c4 50 ed 7e d1 d7 92 76 88 57 ab ..X.. ..P.~...v.W.
0000048: 99 c6 b0 9f 08 a6 14 6a 96 66 c4 9e be 50 3e 12 a1 f3 .......j.f...P>...
000005a: 86 4c 09 c5 7b 67 e5 f9 d2 28 2b ed 56 64 a0 e8 9b 83 .L..{g...(+.Vd....
000006c: d8 9f 3a 99 20 c4 85 95 51 66 36 4b 70 ac fc 74 69 cc ..:. ...Qf6Kp..ti.
000007e: 56 f4 9c 88 d7 32 83 4f c6 a9 de 13 f4 4e 92 b9 1b 87 V....2.O.....N....
0000090: 89 e0 6d 24 0a 4f 33 a7 fe 40 26 e4 37 a3 ad 42 43 72 ..m$.O3..@&.7..BCr
00000a2: bd f0 3b 6f 11 9f 16 32 ed 04 eb a7 fc d9 8d 62 91 f7 ..;o...2.......b..
00000b4: dc 97 f0 6a 11 49 f6 1e b9 cb fc 7b dd 7c 41 e6 8b 56 ...j.I.....{.|A..V
00000c6: eb 70 47 a7 b6 f9 b3 3c d1 42 a2 fa 27 cc 49 ac 3e 89 .pG....<.B..'.I.>.
00000d8: 97 ff 2e 9c a4 7c 21 f1 0f .....|!..
```
This isn't very competitive, but I just couldn't resist to post my first Bubblegum answer to an actual [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'") challenge.
The hexdump can be reversed with `xxd -r -c 18 > xml.bg`.
The code completely ignores the input. Compression has been done with [zopfli](https://github.com/google/zopfli), which uses the DEFLATE format but obtains a better ratio than (g)zip.
*Thanks to @Sp3000 for -2 bytes!*
[Answer]
# sed, 449 bytes
Assumes sed to be run with the `-nr` options.
```
/\?|<p/d;:M
/<ma/{s/.*"(.*)".*/Q\1: X series/;/C/ s/X/1/;s/X/2/;H;d}
/<se/{s/.*"([^"]*)".*"([^"]*)".*/@\1!\2/;H;d}
/<mo/{
G;s/.*@(.*)*$/\1/;x;s/@(.*)*$//;x;:A N
/<\/m/!bA
s/\n/!/g;s/ +//g;s|<[/a-z]*>||g;s/(.*)!(.*)!(.*)!(.*)!(.*)!/%\1, \3 (\2-\4)@\1!\2/;H}
/<\/se/{x;s/\n*@.*$//;x}
$!{n;bM}
x;s/\n//g;s/Q(.*)Q(.*)%(.*)Q(.*)/\2\n \3\n\4\n\1/
s/%(.*)%(.*)%(.*)\n(.*)%(.*)%(.*)%(.*)%(.*)%(.*)/\n \3\n \2\n \1\n\4\n \7\n \9\n \6\n \5\n \8/;p
```
Ungolfed version:
```
# Remove first 2 lines
/\?|<p/ d
:M
#manufacturer
/<ma/ {
s/.*"(.*)".*/Q\1: X series/
#Car corp
/C/ s/X/1/
#other
s/X/2/
H
d
}
#series: store in hold buffer. (treating the hold buffer as a list, with @ as a delimeter)
/<se/{
s/.*"([^"]*)".*"([^"]*)".*/@\1!\2/
H
d
}
/<mo/ {
# pull series from hold buffer
G
s/.*@(.*)*$/\1/
# remove series from hold buffer
x
s/@(.*)*$//
x
# Concatenate model into one line
:A N
/<\/m/ !{
bA
}
s/\n/!/g
# Remove junk
s/ +//g
s|<[/a-z]*>||g
# Append formatted line to hold buffer, replace series at the end
s/(.*)!(.*)!(.*)!(.*)!(.*)!/%\1, \3 (\2-\4)@\1!\2/
H
}
/<\/se/ {
#pop series name
x
s/\n*@.*$//
x
}
$ ! {
n
b M
}
# end of loop
x
s/\n//g
# "sort"
s/Q(.*)Q(.*)%(.*)Q(.*)/\2\n \3\n\4\n\1/
s/%(.*)%(.*)%(.*)\n(.*)%(.*)%(.*)%(.*)%(.*)%(.*)/\n \3\n \2\n \1\n\4\n \7\n \9\n \6\n \5\n \8/
p
```
[Answer]
# CJam, ~~109~~ 107 bytes
```
"rzn ¸À¨ 4T\$D"S/q"<>"'"er'"/
f{\:i2/_E5bf.+.+\ff=)1<_s,9/+": series
"2/.+\" , ()
-"2/Z4e\f.\}
```
Note that four of the characters in the string at the beginning are unprintable.
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=%22rzn%20%C2%B8%C3%80%C2%90%C2%A8%C2%90%C2%98%C2%8C%20%0C4T%5C%0C%24%0C%14%0CD%08%22S%2Fq%22%3C%3E%22'%22er'%22%2F%0Af%7B%5C%3Ai2%2F_E5bf.%2B.%2B%5Cff%3D)1%3C_s%2C9%2F%2B%22%3A%20%20series%0A%222%2F.%2B%5C%22%20%20%2C%20%20()%0A-%222%2FZ4e%5Cf.%5C%7D&input=%3C%3Fxml%20version%3D%221.0%22%20%3F%3E%0A%3Cproducts%3E%0A%20%20%3Cmanufacturer%20name%3D%22Test%20Manufacturer%201%22%3E%0A%20%20%20%20%3Cseries%20title%3D%22Supercar%22%20code%3D%22S1%22%3E%0A%20%20%20%20%20%20%3Cmodel%3E%0A%20%20%20%20%20%20%20%20%3Cname%3ERoad%20Czar%3C%2Fname%3E%0A%20%20%20%20%20%20%20%20%3Ccode%3EC%3C%2Fcode%3E%0A%20%20%20%20%20%20%20%20%3Cyear%3E2011%3C%2Fyear%3E%0A%20%20%20%20%20%20%3C%2Fmodel%3E%0A%20%20%20%20%20%20%3Cmodel%3E%0A%20%20%20%20%20%20%20%20%3Cname%3EUbervehicle%3C%2Fname%3E%0A%20%20%20%20%20%20%20%20%3Ccode%3EU%3C%2Fcode%3E%0A%20%20%20%20%20%20%20%20%3Cyear%3E2013%3C%2Fyear%3E%0A%20%20%20%20%20%20%3C%2Fmodel%3E%0A%20%20%20%20%20%20%3Cmodel%3E%0A%20%20%20%20%20%20%20%20%3Cname%3EIncredibulus%3C%2Fname%3E%0A%20%20%20%20%20%20%20%20%3Ccode%3EI%3C%2Fcode%3E%0A%20%20%20%20%20%20%20%20%3Cyear%3E2015%3C%2Fyear%3E%0A%20%20%20%20%20%20%3C%2Fmodel%3E%0A%20%20%20%20%20%20%3Cmodel%3E%0A%20%20%20%20%20%20%20%20%3Cname%3EModel%201%3C%2Fname%3E%0A%20%20%20%20%20%20%20%20%3Ccode%3E01%3C%2Fcode%3E%0A%20%20%20%20%20%20%20%20%3Cyear%3E2010%3C%2Fyear%3E%0A%20%20%20%20%20%20%3C%2Fmodel%3E%0A%20%20%20%20%3C%2Fseries%3E%0A%20%20%20%20%3Cseries%20title%3D%22Test%20series%2022%22%20code%3D%22Test%22%3E%0A%20%20%20%20%20%20%3Cmodel%3E%0A%20%20%20%20%20%20%20%20%3Cname%3ETest%20model%20asdafds%3C%2Fname%3E%0A%20%20%20%20%20%20%20%20%3Ccode%3ETT%3C%2Fcode%3E%0A%20%20%20%20%20%20%20%20%3Cyear%3E2014%3C%2Fyear%3E%0A%20%20%20%20%20%20%3C%2Fmodel%3E%0A%20%20%20%20%3C%2Fseries%3E%0A%20%20%3C%2Fmanufacturer%3E%0A%20%20%3Cmanufacturer%20name%3D%22Car%20Corporation%22%3E%0A%20%20%20%20%3Cseries%20title%3D%22Corporation%20Car%22%20code%3D%22CC%22%3E%0A%20%20%20%20%20%20%3Cmodel%3E%0A%20%20%20%20%20%20%20%20%3Cname%3EFirst%20and%20Only%20Model%3C%2Fname%3E%0A%20%20%20%20%20%20%20%20%3Ccode%3EFOM%3C%2Fcode%3E%0A%20%20%20%20%20%20%20%20%3Cyear%3E2012%3C%2Fyear%3E%0A%20%20%20%20%20%20%3C%2Fmodel%3E%0A%20%20%20%20%3C%2Fseries%3E%0A%20%20%3C%2Fmanufacturer%3E%0A%20%20%3Cmanufacturer%20name%3D%22Second%20Test%20Manufacturer%22%3E%0A%20%20%20%20%3Cseries%20title%3D%22AAAAAAAAAAAAAA%22%20code%3D%22D%22%3E%0A%20%20%20%20%20%20%3Cmodel%3E%0A%20%20%20%20%20%20%20%20%3Cname%3ESome%20older%20model%3C%2Fname%3E%0A%20%20%20%20%20%20%20%20%3Ccode%3EO%3C%2Fcode%3E%0A%20%20%20%20%20%20%20%20%3Cyear%3E2011%3C%2Fyear%3E%0A%20%20%20%20%20%20%3C%2Fmodel%3E%0A%20%20%20%20%20%20%3Cmodel%3E%0A%20%20%20%20%20%20%20%20%3Cname%3EThe%20newest%20model%3C%2Fname%3E%0A%20%20%20%20%20%20%20%20%3Ccode%3EN%3C%2Fcode%3E%0A%20%20%20%20%20%20%20%20%3Cyear%3E2014%3C%2Fyear%3E%0A%20%20%20%20%20%20%3C%2Fmodel%3E%0A%20%20%20%20%3C%2Fseries%3E%0A%20%20%20%20%3Cseries%20title%3D%22BBBBBBBBBBBBBBB%22%20code%3D%22asdf%22%3E%0A%20%20%20%20%20%20%3Cmodel%3E%0A%20%20%20%20%20%20%20%20%3Cname%3EAnother%20newest%20model%20here%3C%2Fname%3E%0A%20%20%20%20%20%20%20%20%3Ccode%3ETT%3C%2Fcode%3E%0A%20%20%20%20%20%20%20%20%3Cyear%3E2015%3C%2Fyear%3E%0A%20%20%20%20%20%20%3C%2Fmodel%3E%0A%20%20%20%20%3C%2Fseries%3E%0A%20%20%3C%2Fmanufacturer%3E%0A%3C%2Fproducts%3E).
### Idea
This is basically a hardcode that splits the input at all occurrences of **<**, **>** and **"**, selects specific chunks and interleaves them with the remaining parts of the output.
After splitting the input, the chunks at indexes **110**, **114** and **122** are **Car Corporation**, **Corporation Car** and **First and Only Model**. The codes for series and name can be found at indexes 116 and 126, which can be calculated by adding 2 and 4 to the indexes of the names. Finally, the number of series is the length of the string **Car Corporation** divided by **9** (obviously).
Thus, we encode the part of the output that corresponds to this manufacturer as `[114 122 110]` or rather the string `"rzn"`.
### Code
```
e# Split the string at spaces.
"rzn ¸À¨ 4T\$D"S/
e# After replacing characters with their code points, this will be the result:
e# [[114 122 110] [184 192 144 168 144 152 140] [12 52 84 92 12 36 12 20 12 68 8]]
e# Read from STDIN, replace < and > with " and split at double quotes.
q"<>"'"er'"/
f{ e# For each chunk of the split string, push the split input; then:
\:i2/ e# Replace characters with character codes and split into chunks of
e# length 2.
_E5b e# Copy the result and push [2 4].
f.+ e# Replace each pair [I J] in the copy with [I+2 J+4].
.+ e# Vectorized concatenation.
e# For the first chunk, we've achieved
e# [114 122 110] -> [[114 122] [110]]
e# -> [[114 122] [110]] [[116 126] [110 112 4]]
e# -> [[114 122 116 126] [110 112 4]]
\ff= e# Replace each integer with the chunk of the split input at that index.
)1< e# Pop the first chunk and reduce it to the first string.
_s,9/ e# Divide that strings length by 9 and append the integer to the array.
": series
"2/ e# Push [": " " s" "er" "ie" "s\n"].
.+ e# Vectorized concatenation; pushes the manufacturer line.
\ e# Swap the remaining strings on top of the stack.
" , ()
-"2/ e# Push [" " ", " " (" ")\n" "-"].
Z4e\ e# Swap the chunks at indexes 3 and 4.
\f.\ e# Interleave both arrays of strings.
}
```
[Answer]
# Bash, ~~388~~ ~~368~~ 365
```
base64 -d<<<H4sICKVS9FUCA2hlcmUAbVFBasMwELwH8oc92mBD5GNuqUogB9dQOw9QpDUWKFJYWS3t6yvJtI3T7k07szOzKy4IuKObIzFrZ/fAwCNp9NsN3APABVVw1ORnEFZBZ80HtE6hgYLz+ti15XbTo3QRGzCSWmHDKOQcCGkPzZ3q07oqOFg3T0hg8T1NXrNqbCAUwquxHoYyzR1WVcEw4XqkeK5f/mX27orgjIoeP8wuMv8EBbaO2ocbkkybn6wkVPoSTPBQ9Kw+ZaessPChaarlvXjE6GJUkZx63zv8Cp4vSG84aWkw650f8FcnFPDP+D0J5Q/ocnmWsR0rvwC2OTuexgEAAA==|zcat
```
### Small test because:
```
$ bash ./go_procrastination.sh cars.xml
Car Corporation: 1 series
Corporation Car, First and Only Model (CC-FOM)
Second Test Manufacturer: 2 series
BBBBBBBBBBBBBBB, Another newest model here (asdf-TT)
AAAAAAAAAAAAAA, The newest model (D-N)
AAAAAAAAAAAAAA, Some older model (D-O)
Test Manufacturer 1: 2 series
Supercar, Incredibulus (S1-I)
Test series 22, Test model asdafds (Test-TT)
Supercar, Ubervehicle (S1-U)
Supercar, Road Czar (S1-C)
Supercar, Model 1 (S1-01)
```
] |
[Question]
[
I downloaded POV-ray and rendered this shiny metal sphere 90s style:

Your task is to do the same thing, but to do it by implementing the rendering engine yourself in as few bytes as possible. You don't have to replicate this exact image - any image of a reflective sphere above an infinite checkerboard will do, as long as it meets the criteria below.
Rules:
* The image must depict a reflective sphere hovering above an infinite checkerboard. Both the checkerboard itself and its reflection in the sphere must be shown in the image. It must be visually clear that this is what we're seeing. Beyond this, the details of the geometry, colours, material properties etc. are up to you.
* There must be some lighting in the scene: parts of the sphere should be darker than other parts, and visually it should be possible to tell roughly where the light is coming from. Beyond that, the details of the lighting model are up to you. (You can invent your own simplified lighting model if you like.) The sphere doesn't have to cast a shadow.
* The above two criteria - whether it really looks like a shiny sphere above a checkerboard illuminated by a light source - will be judged by the community using voting. Therefore, an answer must have a positive score in order to be eligible to win.
* The output must be at least 300x300 pixels. It can be displayed on the screen or written to a file, either is fine.
* Your code should run in less than an hour on a reasonable modern computer. (This is generous - POV-ray renders the above scene practically instantaneously.)
* No built-in ray tracing functionality may be used - you must implement the renderer yourself.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the positive-scoring entry with the shortest code (in bytes) wins. However, you're also welcome to play the meta-game of getting the most votes by drawing a pretty picture (while keeping the code short of course).
This challenge might seem ridiculously hard, but since the geometry is fixed, the algorithm for rendering such a scene by ray tracing is pretty straightforward. It's really just a case of iterating over each pixel in the output image and evaluating a mathematical expression to see what colour it should be, so I'm optimistic that we'll see some good answers.
[Answer]
## Python 2, 484 468 467 bytes
[](https://i.stack.imgur.com/mrUaV.png)
```
i=int;u=249.3
def Q(A,B):
a=A*A+B*B+9e4;b=B*u+36e4;I=b*b-a*128e4
if I>0:
t=(-b+I**.5)/(5e2*a);F,G,H=A*t,B*t,u*t;J,K,M=F,G+.6,H+2.4;L=a**-.5;k=2*(A*J+B*K+u*M)*L;C,D,E=A*L-k*J,B*L-k*K,u*L-k*M;L=(C*C+D*D+E*E)**-.5;t=(-4e2-G)/D;return(D*D*L*L*u,((i(F+t*C)/200+i(H+t*E)/200)&1)*(u*D*L))[D>0]
else:return(u*B*B/a,((i(-2e2/B*A)/200+i(-6e4/B)/100)&1)*u*B/a**.5)[B>0]
open("s.pgm","wb").write("P5 800 600 255 "+"".join(chr(i(Q(j%800-4e2,j/800-u)))for j in range(480000)))
```
Note: after `if I>0:` there is a newline followed by a single **tab** char before `t=`...
Running the program will create an 800x600 image named s.pgm
Started from a "real" ray tracer formulas (tweaked a bit for golfing).
Rendering takes about 3s on my dead old PC (0.7s with pypy).
] |
[Question]
[
Given the following C# program outputting `False`, inject a 'malicious' line of code such that the program outputs `True`.
```
class Program
{
static void Main()
{
System.Console.Write("False");
;
}
}
```
Your answer should consist of a string that replaces the second semicolon, and causes the program to output `True`, the whole `True` and nothing but `True` (not even a newline). It must do this if stdout is printed to the console, and if stdout is redirected to a file.
The shortest answer wins.
[Answer]
## 52 characters
```
}static Program(){System.Console.Write(0<1);for(;;);
```
so the whole thing becomes:
```
class Program
{
static void Main()
{
System.Console.Write( "False" );
}
static Program()
{
System.Console.Write( 0 < 1 );
for ( ; ; ) ;
}
}
```
[Answer]
C#, 51 characters
```
Console.Write("\b\b\b\b\b");Console.Write("True ");
```
Will only work on standard output
[Answer]
You can generalize RamonBoza's answer to still work if stdout is redirected to a file.
Assuming the program runs under Mono on Linux, with the assembly `Mono.Posix.dll` loaded:
```
if(Mono.Unix.Native.Syscall.isatty(1))
{
Console.Write("\rTrue ");
}
else
{
// Truncate the output file first
Console.OpenStandardOutput().SetLength(0);
Console.Write("True");
}
```
I doubt this works on Windows, but there's probably an equivalent to `isatty()`.
[Answer]
**83... WIP**
I was hoping this'd work, but apparently "False" isn't being interned as I'd hoped in my compiler
```
//}unsafe static Program(){fixed(char*f="False"){*(long*)f=0x65007500720054;*(f+4)=' ';}
}unsafe static Program(){fixed(char*f="False")for(int i=5;i-->0;)*(f+i)="True "[i];
```
ungolfed
```
class Program
{
static void Main(string[] args)
{
Console.Write("False");
}
unsafe static Program()
{
fixed (char* f = "False") for (int i = 5; i-- > 0; ) *(f + i) = "True "[i];
}
}
```
[Answer]
```
class Program
{
static void Main()
{
System.Console.Write("False");
System.Console.Clear(); System.Console.Write("True");
Console.ReadLine();
}
}
```
[Answer]
Not sure if this is accepted.
The question doesn't say anything about compiler options so I assume I can change the entry point of the app.
55 characters ,3 more than the accepted answer
```
}class P{static void Main(){System.Console.Write(1>0);}
```
Full
```
class Program
{
static void Main()
{
System.Console.Write("False");
}
class P
{
static void Main() { System.Console.Write(1 > 0); }
}
}
```
] |
[Question]
[
Write a function which takes a date and returns the day of the week of the next February 29th after that date.
* The input is a string in the ISO Extended format: YYYY-MM-DD (e.g. May 27th, 2010 would be "2010-05-27").
* The output is a string which is the name of the day of the week (e.g. "Monday"). Capitalization doesn't matter, but do give the full name in English.
* If the given date is February 29th, then return the day of the week of the *next* Feburary 29th.
* Use the calculations for the Proleptic Gregorian Calendar (so, it uses the Gregorian leap year calculations for it's entire length). Don't worry about the Julian Calendar or when the switch from Julian to Gregorian occurred. Just assume Gregorian for everything.
* The function should work for at least the range of "0001-01-01" - "2100-01-01".
* Feel free to use whatever standard libraries your language of choice provides, but do not use 3rd party libraries unless you want to include that code as part of your solution.
* Shortest code (fewest characters) wins.
**Examples:**
* `func("0001-01-01")` -> `"Sunday"`
* `func("1899-12-03")` -> `"Monday"`
* `func("1970-01-01")` -> `"Tuesday"`
* `func("1999-07-06")` -> `"Tuesday"`
* `func("2003-05-22")` -> `"Sunday"`
* `func("2011-02-17")` -> `"Wednesday"`
* `func("2100-01-01")` -> `"Friday"`
(and no, you don't have to name the function `func`)
**Hints:**
* Remember that years ending in 00 which aren't divisable by 400 aren't leap years.
* January 1st, 0001 is a Monday.
[Answer]
## Windows PowerShell, 65
Fairly straightforward.
```
filter f{for($d=date $_;($d+='1').day*$d.month-58){}$d.dayofweek}
```
As usual, we can shave off two bytes if we are willing to wait a long time till completion:
```
filter f{for($d=date $_;($d+=9).day*$d.month-58){}$d.dayofweek}
```
Test:
```
> '0001-01-01','1899-12-03','1970-01-01','1999-07-06','2003-05-22','2011-02-17','2100-01-01'|f
Sunday
Monday
Tuesday
Tuesday
Sunday
Wednesday
Friday
```
History:
* 2011-02-18 00:06 (65) First attempt.
[Answer]
## Ruby 1.9, 85 characters
```
f=->a{require"date";d=Date.parse(a,0,0)+1;d+=1until d.day*d.month==58;d.strftime"%A"}
```
Straightforward solution. Call the function with `f[args]`.
* Edit: (87 -> 97) Fixed the `0001-01-01` testcase.
* Edit 2: (97 -> 91) Date.parse allows specifying the date of the calendar reform as well.
* Edit 3: (91 -> 87) Use a lambda instead of a function. Thanks [Dogbert](https://codegolf.stackexchange.com/users/308/dogbert)!
* Edit 4: (87 -> 85) Remove unnecessary spaces. Thanks again, [Dogbert](https://codegolf.stackexchange.com/users/308/dogbert)!
[Answer]
## T-SQL ~~166~~ 185 Characters
```
CREATE PROCEDURE f29 (@d DATETIME) AS
DECLARE @i int
SET @i=YEAR(DATEADD(M,-2,@d)+3)
SET @i=@i+(4-@i%4)
IF @i%100=0 AND @i%400<>0 SET @i=@i+4
SELECT DATENAME(W,CAST(@i AS CHAR)+'-2-29')
```
I was already messing with T-SQL date functions, so I figured why not...
Original solution was incorrect...
Here's what I *actually* have to do to get that strategy to work:
```
CREATE PROCEDURE f29 (@d DATE) AS
DECLARE @i int
SET @i = YEAR(@d)
BEGIN TRY
SET @i=YEAR(DATEADD(D, 3, DATEADD(M,-2,@d)))
END TRY
BEGIN CATCH
END CATCH
SET @i=@i+(4-@i%4)
IF @i%100=0 AND @i%400<>0 SET @i=@i+4
SELECT DATENAME(W,CAST(@i AS CHAR)+'-2-29')
```
[Answer]
**C#, 176**
```
Func<String,String>f=(d)=>{DateTime n;for(n=DateTime.Parse(d).AddDays(307);!(DateTime.IsLeapYear(n.Year));n=n.AddYears(1)){}return new DateTime(n.Year,2,29).ToString("dddd");};
```
[Answer]
# Bash, 96 bytes
Thanks Peter... Highly golfed version, 96 bytes:
```
i=1;until [ `date -d"$1 $i days" +%m-%d` = "02-29" ];do((i++));done
date -d "${1} ${i} days" +%A
```
Old version, 229 bytes
```
#!/bin/bash
from=$1
i=1
while [ "$isFeb" = "" ] || [ "$is29" = "" ]
do
isFeb=`date -d "${from} ${i} days" | grep Feb`
is29=`date -d "${from} ${i} days" +%Y-%m-%d | grep "\-29"`
((i++))
done
((i--))
date -d "${from} ${i} days" +%A
```
**SAMPLE I/O**
```
:~/aman>./29Feb.sh 0001-01-01
Sunday
:~/aman>./29Feb.sh 1899-12-03
Monday
:~/aman>./29Feb.sh 1970-01-01
Tuesday
```
[Answer]
### Perl, no date library: 160 159 155
```
sub f{($y,$m)=split/-/,@_[0],2;$y++if($m>'02-28');$y=($y+3)%400>>2;$y+=$y&&!($y%25);@r=(Tues,Wednes,Thurs,Fri,Satur,Sun,Mon);@r[(5*$y-($y/25&3))%7]."day";}
```
The real benefit of these date libraries is pushing off the length of the names of the days to someone else.
On the other hand, I think this is the only solution so far which works regardless of locale.
[Answer]
# DATE and some BASHy glue (90)
The function:
```
f(){ while :;do $(date -d$1+1day +'set - %F %A 1%m%d');(($3==10229))&&break;done;echo $2;}
```
Testing:
```
$ for x in 0001-01-01 1899-12-03 1970-01-01 1999-07-06 2003-05-22 2011-02-17 2100-01-01 ; do f $x ; done
Sunday
Monday
Tuesday
Tuesday
Sunday
Wednesday
Friday
```
[Answer]
# D: 175 Characters
```
S f(S)(S s){auto d=Date.fromISOExtString(s)+days(1);while(d.month!=Month.feb||d.day!=29)d+=days(1);return["Sun","Mon","Tues","Wednes","Thurs","Fri","Sat"][d.dayOfWeek]~"day";}
```
More Legibly:
```
S f(S)(S s)
{
auto d = Date.fromISOExtString(s) + days(1);
while(d.month != Month.feb || d.day != 29)
d += days(1);
return ["Sun", "Mon", "Tues", "Wednes", "Thurs", "Fri", "Sat"][d.dayOfWeek] ~ "day";
}
```
It's very easy to write in D, but it's definitely not going to win any code golfing contests. Still, outside of code golfing, I'd much rather have it easy to write and understand but long than have it terse but hard to write and understand.
[Answer]
## Java 8 - 252 chars
Golfed:
```
import java.time.*;
import java.time.format.*;
public class S{public static void main(String[] a){LocalDate d=LocalDate.parse(a[0]).plusDays(1);while(d.getMonthValue()!=2||d.getDayOfMonth()!=29){d=d.plusDays(1);}System.out.println(d.getDayOfWeek());}}
```
Ungolfed:
```
import java.time.*;
import java.time.format.*;
public class S {
public static void main(String[] a) {
LocalDate d = LocalDate.parse(a[0]).plusDays(1);
while(d.getMonthValue()!=2 || d.getDayOfMonth()!=29) {
d = d.plusDays(1);
}
System.out.println(d.getDayOfWeek());
}
}
```
[Answer]
# Rebol - 78
```
f: func[d][system/locale/days/(until[d: d + 1 d/day * d/month = 58]d/weekday)]
```
Ungolfed:
```
f: func [d] [
system/locale/days/(
until [
d: d + 1
d/day * d/month = 58
]
d/weekday
)
]
```
Example usage (in Rebol console):
```
>> f 0001-01-01
== "Sunday"
>> f 2100-01-01
== "Friday"
```
[Answer]
# PHP, 104 bytes
```
function f($s){for($y=$s-(substr($s,5)<"02-29");!date(L,$t=strtotime(++$y."-2-1")););return date(l,$t);}
```
**breakdown**
```
for($y=$s-; // "-" casts the string to int; decrement year if ...
(substr($s,5)<"02-29") // ... date is before feb 29
!date(L, // loop while incremented $y is no leap year
$t=strtotime(++$y."-2-1") // $t=feb 01 in that year (same weekday, but shorter)
);
);
return date(l,$t); // return weekday name of that timestamp
```
[`date(L)`](http://php.net/date): `1` for leap year, `0` else
`date(l)`: full textual representation of the day of the week
[Answer]
# GNU coreutils, 71 bytes
```
f(){
seq -f "$1 %gday" 2921|date -f- +'%m%d%A'|sed 's/0229//;t;d;:;q'
}
```
Linear search of the next 8 years (worst case, given 2096-02-29). Sed finds and outputs the first line that matches 29th of February.
I was surprised to find that `t;d;:;q` was shorter than testing to see whether the digits remained (`/[01]/d;q`), despite being twice as many commands.
### Tests
I added an extra line of tests for difficult corner cases:
```
for i in 0001-01-01.Sunday 1899-12-03.Monday \
1970-01-01.Tuesday 1999-07-06.Tuesday \
2003-05-22.Sunday 2011-02-17.Wednesday 2100-01-01.Friday \
2000-02-28.Tuesday 2000-02-29.Sunday 2000-03-01.Sunday 2096-02-29.Friday
do
printf "%s => %s (expected %s)\n" ${i%.*} $(f ${i%.*}) ${i#*.}
done
```
] |
[Question]
[
# Background
A number `n` can be described as `B`-rough if all of the prime factors of `n` strictly exceed `B`.
# The Challenge
Given two positive integers `B` and `k`, output the first `k` `B`-rough numbers.
# Examples
Let `f(B, k)` be a function which returns the set containing the first `k` `B`-rough numbers.
```
> f(1, 10)
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
> f(2, 5)
1, 3, 5, 7, 9
> f(10, 14)
1, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~53~~ 44 bytes
```
b%k=take k[n|n<-[1..],all((>0).mod n)[2..b]]
```
[Try it online!](https://tio.run/##HcVBCoAgEADAr@xFULBFPVc/6AXiYSMhUbcoj/3dosvMTneOpfS@ijw1yhGy54fHwVvEoKkUKWejsB4bsPIOcQ2hV0oME1Q6FzivxA28FdZocL/WfIX@Ag "Haskell – Try It Online")
*Thanks to [H.PWiz](https://codegolf.stackexchange.com/users/71256/h-pwiz) for -9 bytes!*
```
b%k= -- given inputs b and k
take k -- take the first k elements from
[n|n<-[1..] -- the infinite list of all n > 0
,all [2..b]] -- where all numbers from 2 to b (inclusive)
((>0).mod n) -- do not divide n.
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~80~~, 75 bytes
```
lambda B,k:[i for i in range(1,-~B*k)if all(i%j for j in range(2,B+1))][:k]
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUcFJJ9sqOlMhLb9IIVMhM0@hKDEvPVXDUEe3zkkrWzMzTSExJ0cjUzULrCILocJIx0nbUFMzNtoqO/Z/QVFmXolGGlCbgqGBpiYXjG@ko2CKxDU0AMqbaGr@BwA "Python 3 – Try It Online")
Thanks to *shooqie* for saving 5 bytes.
This assumes that the k'th B-rough number will never exceed \$B \* k\$, which I don't know how to prove, but seems like a fairly safe assumption (and I can't find any counterexamples).
Alternate solution:
# [Python 2](https://docs.python.org/2/), 78 bytes
```
B,k=input()
i=1
while k:
if all(i%j for j in range(2,B+1)):print i;k-=1
i+=1
```
[Try it online!](https://tio.run/##DcuxCsMgFAXQ3a@4S0CJhb7QKcXFP8mQNDfKi4gh9Ottz37Kt@2nTr1HnwK1XM06wyDm3plXpNmAG5acLYcD21lxgIq66Ge1k4@jODeXSm3gOz3@ERyD9C5PL68f "Python 2 – Try It Online")
This solution does *not* make the above solution. And is much more efficient.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
1Æf>Ạɗ#
```
[Try it online!](https://tio.run/##y0rNyan8/9/wcFua3cNdC05OV/4P5Bn8NzQBAA "Jelly – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~35~~ 32 bytes
*-3 bytes thanks to nwellnof!*
```
{grep(*%all(2..$^b),1..*)[^$^k]}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwvzq9KLVAQ0s1MSdHw0hPTyUuSVPHUE9PSzM6TiUuO7b2f3FipUKahqGOoYGmNReEY6RjCmcbGugYmkB5pqoaxjVGmv8B "Perl 6 – Try It Online")
An anonymous code block that takes two integers and returns a list of integers.
### Explanation
```
{ } # Anonymous code block
grep( ,1..*) # Filter from the positive integers
* # Is the number
% # Not divisible by
all( ) # All of the numbers
2..$^b # From 2 to b
[^$^k] # And take the first k numbers
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~9~~ 8 bytes
```
↑foΛ>⁰pN
```
[Try it online!](https://tio.run/##yygtzv7//1HbxLT8c7PtHjVuKPD7//@/8X9DAwA "Husk – Try It Online")
Takes \$B\$ as first and \$ k \$ as second input.
```
↑ -- take the first k elements
N -- from the natural numbers
f -- filtered by
o p -- the prime factors
Λ>⁰ -- are all larger than the first input
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
1µg³!¤Ịµ⁴#
```
[Try it online!](https://tio.run/##y0rNyan8/9/w0Nb0Q5sVDy15uLvr0NZHjVuU/wMFDf4bmgAA "Jelly – Try It Online")
### How it works
```
1µg³!¤Ịµ⁴# Dyadic main link. Left = B, right = k
µ⁴# Take first k numbers satisfying...
g GCD with
³!¤ B factorial
Ị is insignificant (abs(x) <= 1)?
1µ ... starting from 1.
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 33 bytes
```
NθNη≔⁰ζW‹Lυη«≦⊕ζ¿¬Φθ∧κ¬﹪ζ⊕κ⊞υζ»Iυ
```
[Try it online!](https://tio.run/##TY3LCoMwEEXX5iuynEAKCt25kkJBqOIvpJqaYExsHi1Y@u1pxC6cxcC5zJ3TC2Z7w1SMtV6Cb8N85xaepERHFokr5@SoIad4TfQWUnEMN@5cWnr0AgKhWBCCPyhr2PI/r3Vv@cy158NezOQDQ2s8XKXym4riSg8wUbyFjRmCMrBSfCjCRPZBWdYFl0z7qy/qrNQeLsz5ZCdljEWOinM8vdQP "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
NθNη
```
Input `B` and `k`.
```
≔⁰ζ
```
Set `z` to 0.
```
W‹Lυη«
```
Repeat until we have `k` values.
```
≦⊕ζ
```
Increment `z`.
```
¿¬Φθ∧κ¬﹪ζ⊕κ
```
Divide `z` by all the numbers from `2` to `B` and see if any remainder is zero.
```
⊞υζ»
```
If not then push `z` to the predefined empty list.
```
Iυ
```
Cast the list to string and implicitly output it.
[Answer]
# JavaScript (ES6), 68 bytes
Takes input as `(b)(k)`.
```
b=>k=>(o=[],n=1,g=d=>(d<2?o.push(n)==k:n%d&&g(d-1))||g(b,n++))(b)&&o
```
[Try it online!](https://tio.run/##ZcpBDoIwEEbhvfewmT8UYolujIMHMS4ohaqQGWLVFXevbI3L9@U92k@buud9fpWioc8DZ8/NyA0pX65W2NnIYc1wqs9aze90IwHzeJRtMCZSKB2wLJG8laIAyMMYzZ1K0qmvJo00kAO5HbD51Rp0@MP1I7cH8hc "JavaScript (Node.js) – Try It Online")
### Commented
```
b => k => ( // input = b and k
o = [], // o[] = output array
n = 1, // n = value to test
g = d => ( // g = recursive function, taking the divisor d
d < 2 ? // if d = 1:
o.push(n) == k // push n into o[] and test whether o[] contains k elements
: // else:
n % d && g(d - 1) // if d is not a divisor of n, do a recursive call with d - 1
) || // if the final result of g() is falsy,
g(b, n++) // do a recursive call with d = b and n + 1
)(b) // initial call to g() with d = b
&& o // return o[]
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 68 bytes
```
b=>g=(k,i=1,j=b)=>k?j>1?i%j?g(k,i,j-1):g(k,i+1):[i,...g(k-1,i+1)]:[]
```
[Try it online!](https://tio.run/##ZcpBCoMwEIXhfe8hzGASHLEbYZKDiAu1GjKKKbX0@jF1V7r738eT4TMc0ys833qPjzktnEa2nmFVgUkJj8h2dWLJhUKc/7oSTdheWebogjLG5Knpgr7t@jTF/YjbbLboYQFCoArx9qs1wv0P8w@oQUwn "JavaScript (Node.js) – Try It Online")
[Answer]
# APL(NARS), 52 chars, 104 bytes
```
r←a f w;i
r←,i←1⋄→3
i+←1⋄→3×⍳∨/a≥πi⋄r←r,i
→2×⍳w>↑⍴r
```
Above it seems the rows after 'r←a f w;i' have names 1 2 3;test:
```
o←⎕fmt
o 1 h 2
┌2───┐
│ 1 2│
└~───┘
o 1 h 1
┌1─┐
│ 1│
└~─┘
o 10 h 14
┌14───────────────────────────────────────┐
│ 1 11 13 17 19 23 29 31 37 41 43 47 53 59│
└~────────────────────────────────────────┘
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
∞ʒÒ¹›P}²£
```
[Try it online](https://tio.run/##ASEA3v9vc2FiaWX//@KInsqSw5LCueKAulB9wrLCo///MTAKMTQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@koGunoGRfmRAa9v9Rx7xTkw5PinzUsCugNuLQ4v86/6OjDXUMDWJ1oo10TIGkoYGOoUlsLAA).
**Explanation:**
```
∞ # Infinite list starting at 1: [1,...]
ʒ } # Filter it by:
Ò # Get all prime factors of the current number
¹› # Check for each if they are larger than the first input
P # And check if it's truthy for all of them
²£ # Leave only the leading amount of items equal to the second input
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 56 bytes
```
->b,k{(1..).lazy.reject{|n|
(2..b).any?{n%_1<1}}.take k}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3LXTtknSyqzUM9fQ09XISqyr1ilKzUpNLqmvyarg0jPT0kjT1EvMq7avzVOMNbQxra_VKErNTFbJrIfrXFyi4RRsa6BiaxOqV5McnQkQXLIDQAA)
] |
[Question]
[
Your task is to accept as input two gene sequences, and a sequence of "cross over points", and return the gene sequence that results from the indicated cross overs.
What I mean by this is, say you have the sequences `[A, A, A, A, A, A, A]` and `[Z, Z, Z, Z, Z, Z, Z]`, and cross over points of `2` and `5`. The resulting sequence would be `[A, A, Z, Z, Z, A, A]`, because:
```
Cross Here: V V
Indices: 0 1 2 3 4 5 6
Genes 1: A A A A A A A
Genes 2: Z Z Z Z Z Z Z
Result: A A Z Z Z A A
^ ^
```
Note that while I'm using letters here for clarity, the actual challenge uses numbers for genes.
The result is the first sequence until a cross over point is encountered, then the result takes from the second sequence until another cross over point is encountered, then the result takes from the first sequence until a cross over point is encountered...
# Input:
* Input can be any reasonable form. The two sequences can be a pair, with the points as the second argument, all three can be separate arguments, a single triplet of `(genes 1, genes 2, cross-points)`, a map with named keys...
* The cross points will always be in order, and will always be inbounds. There won't be duplicate points, but the list of cross over points may be empty.
* Gene sequences will always be the same length, and will be non-empty.
* Indices can be 0 or 1 based.
* Genes will always be numbers in the range 0-255.
* It doesn't matter which argument is "genes 1" or "genes 2". In the case of no cross over points, the result can either be either entirely "genes 1" or "genes 2".
---
# Output
* Output can be any reasonable form that isn't ambiguous. It can be a array/list of numbers, an array of string numbers, a *delimited* string of numbers (some non-numeric character must separate the numbers)...
* It can be returned or printed to the std-out.
---
Entries can by full programs or functions.
---
# Test Cases `(genes 1, genes 2, cross points) => result`:
```
[0], [1], [0] => [1]
[0, 1], [9, 8], [1] => [0, 8]
[0, 2, 4, 6, 8, 0], [1, 3, 5, 7, 9, 1], [1, 3, 5] => [0, 3, 5, 6, 8, 1]
[1, 2, 3, 4], [5, 6, 7, 8], [] => [1, 2, 3, 4]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 2, 3, 6, 8] => [1, 1, 0, 1, 1, 1, 0, 0, 1, 1]
```
This is Code Golf.
[Answer]
## Haskell, ~~58~~ ~~53~~ ~~51~~ 45 bytes
```
(fst.).foldl(\(a,b)p->(take p a++drop p b,a))
```
The two gene sequences are taken as a pair of lists and the cross points as a second argument.
[Try it online!](https://tio.run/##dU5LDoIwEN17ihfioo0DERCRhSZeQ2RRhKqxQiOc31qobohMZjGZ972J7lErZeT@bJjs@oAHslWVYmcmqOTaP7BePGpoiNWqerXaXiUJzs1T3BvsUbULQL/uTY8lJFi@Lgh5WHDAnlOMEA5wRtiNjPAPIyJsCFtLITgzQkxICCkhGxxGpXtO9eGot8hmUCajT/pL@xM2u9/g2bWG37KxKzsx945uPIJ3cuMNHSJKCvO@SCWunfEvWn8A "Haskell – Try It Online")
```
foldl -- fold the pair of genes into the list of
-- cross points and on each step
\(a,b) p -> -- let the pair of genes be (a,b) and the next cross point 'p'
(take p a++drop p b,a)
-- let 'b' the new first element of the pair, but
-- drop the first 'p' elements and
-- prepend the first 'p' elements of 'a'
-- let 'a' the new second element
fst -- when finished, return the first gene
```
[Answer]
# JavaScript (ES6), ~~47~~ 45 bytes
*Saved 2 bytes thanks to @ETHproductions*
Takes input as a triplet **[a, b, c]** where **a** and **b** are the gene sequences and **c** is the list of 0-indexed cross-points.
```
x=>x[i=j=0].map(_=>x[(j+=x[2][j]==i)&1][i++])
```
[Try it online!](https://tio.run/##dZDdCoMwDIXv9xS5GhUzre7HedG9SAlDnA7FqcwxfPvOWv9gCqFw0i8np82jb9TE76z@HMrqkahUqFbcWpmJXHByXlHN7lqz3Bat9EnmJERm7T2SmW2TpeKqbKoicYrqyVImJScE6emDE1kWuK6Wuz8MoYdChKuZGGGuO2u8j3BCuHTXCGYLwhHhjBAghIPf0Fu6GcbMrSTxeucOOul5QwZDqvkFM7QWbbOGSJvV/9PorSMuN3q9xwTzSZL6AQ "JavaScript (Node.js) – Try It Online")
### Commented
```
x => // given x = [ geneSeqA, geneSeqB, crossPoints ]
x[i = j = 0] // initialize i = gene sequence pointer and j = cross point pointer
.map(_ => // for each value in the first gene sequence:
x[( // access x[]
j += x[2][j] == i // increment j if i is equal to the next cross point
) & 1] // access either x[0] or x[1] according to the parity of j
[i++] // read gene at x[0][i] or x[1][i]; increment i
) // end of map()
```
[Answer]
# [APL (Dyalog 16.0)](https://www.dyalog.com/), 26 bytes
```
+/a⎕×(~,⊢)⊂≠\d←1@⎕⊢0⍴⍨≢a←⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKNdIe2/tn7io76ph6dr1Ok86lqk@air6VHngpiUR20TDB2AEkAxg0e9Wx71rnjUuSgRKAoUA@n8n8ZlwGUIhFxAhoIhlxGXpYIFF4hnqGCkYKxgwvWodw2XqYKZgjlIHKTISMEEyLVQMOACs4AKjRVMgdKWClBTMCBYiQlICZCFAQE "APL (Dyalog Unicode) – Try It Online")
Input is **a**, **c**, then **b**. **c** is `1` indexed.
**How?**
`a←⎕` - get **a**.
`0⍴⍨≢` - create array of `0`s at its length.
`1@⎕⊢` - take **c** and change the `0`s to `1`s on the indices.
`d←` - assign to **d**.
`⊂≠\d` - expand **d** with **xor** to create the selection sequence (`0` for **a**, `1` for **b**), and enclose.
`(~,⊢)` - take **d** and its inverse.
`a⎕×` - and multiply respectively with inputted **b** and **a**.
`+/` - sum each pair of elements, yielding the **a**s on `0`s and **b**s on `1`s.
[Answer]
# [Python 2](https://docs.python.org/2/), 43 bytes
```
def f(a,b,l):
for p in l:a[p:],b=b[p:],a*1
```
[Try it online!](https://tio.run/##dY7BCoMwEETP5ivmaMoejNWqAb9EcohUMSAxiKX061ON8SgsWWZ232Tdb5sWm3v/HkaMqaaeZi4ZxmWFg7GYpe6cVNS3fej6Ifx3MvMAIVkS9ltj3WdLOUuuAJa41dgN2qddpgidOJ5McbZrQlANoT5H0c0JBeG124QTIjwJJaEiNJGKXmBEYHZZHJMysFVMvUJvK4bdVjj4@uA4SvE/ "Python 2 – Try It Online")
[Outputs by modifying](https://codegolf.meta.stackexchange.com/a/4942/20260) the argument `a`. Instead as a program:
**50 bytes**
```
a,b,l=input()
for p in l:a[p:],b=b[p:],a*1
print a
```
[Try it online!](https://tio.run/##dY7BCoMwEETvfsXgScscjNW2Cn6J5BCLxYDEIJa2X29NjEdh2WVmebNrf8swmXz9DHrsIer@2z/jOF4VO46NNva9JGn0mmZYaIOxVq2tJbum81NdRGRnbRao1WFJm0miFa5lMo02TXhVEY99FdycKIjbZhM7RFyJkrgTVaCC5xnhmU0WblN69h5Sj9DTCmGn5R8@DrinZPoH "Python 2 – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-a`, ~~45~~ 40 bytes
Give input in the order "control", "second sequence", "first sequence" as separate lines on STDIN
```
#!/usr/bin/perl -alp
@{$.}=@F}for(map${$.^=$%~~@1}[$%++],@2){
```
[Try it online!](https://tio.run/##K0gtyjH9/9@hWkWv1tbBrTYtv0gjN7FABciPs1VRratzMKyNVlHV1o7VcTDSrP7/31DBWMGUC0wqmCtYKhhyGSgYKZgomClYKBhw/csvKMnMzyv@r5uYU/Bf19dUz9BAzwAA "Perl 5 – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 24 bytes
```
4 :'(2|+/\1 x}I.#{.y)}y'
```
[Try it online!](https://tio.run/##y/r/P81Wz0TBSl3DqEZbP8ZQoaLWU0@5Wq9Ss7ZS/X9qcka@goFCmoKBjpUhF5hnCOIpGOpYKVgqWMCEjBVMwcJGCiYKZgoWIOVQUXOgMqhOkLQxWBqkFAOCtWBAiFagTpAF6o4QoK5jpR4FAeoQBeqeJQqZxQqJeUCUn1eZm19arJBWmpdckpmfZwVVowE0RFMBl1@xGv4fAA "J – Try It Online")
I don't count the `f=:` chars, because it works equally well as an anonymous function (as demonstrated in a TIO sample)
Note: It doesn't work for empty list of cross over points!
An explicit oneliner, `x` is the left argument - the list of cross over points, `y` is the right argument, a two-row table of the sequences.
## Explanation:
`4 :' ... '` - a dyadic verb
`(...)}y` - Each atom of operand (...) selects an atom from the corresponding positions of the items of y
`#{.y` - takes the first sequence and find its length
```
#{. 0 2 4 6 8 0,: 1 3 5 7 9 1
6
```
`I.` creates a list of zeros with length the argument
```
I.6
0 0 0 0 0 0
```
`1 x}` changes the items of the rigth argument (a list of zeroes) to 1 at indices indicated by `x` (the list of cors over points)
```
1(1 3 5)}I.6
0 1 0 1 0 1
```
`+/\` running sums of a list
```
+/\ 0 1 0 1 0 1
0 1 1 2 2 3
```
`2|` modulo 2
```
2|+/\ 0 1 0 1 0 1
0 1 1 0 0 1
```
Assembled:
```
0 1 1 0 0 1 } 0 2 4 6 8 0 ,: 1 3 5 7 9 1
0 3 5 6 8 1
```
[Answer]
# [R](https://www.r-project.org/), ~~84~~ 79 bytes
```
function(G,K){o=G[,1]
m=1:nrow(G)
for(i in K)o[m>=i]=G[m>=i,match(i,K)%%2+1]
o}
```
[Try it online!](https://tio.run/##PY3LCsIwFET3/YpuCvfiCE191WLcdtFPKF1IaDRgcyFUFMRvj1HQ1cDMOUyINj8so715Mzvx1KLjp@i2hxqySavGB7lTy5mVQC53Pu9Y@umo3ZCgT2I6zeZCLolFUS2SJq9oKbXBPchQiQprbFGjhMIKG@ywh2J4I1ddMQx9AU4fP0s19X92fh7PY6CSOb4B "R – Try It Online")
Takes input as a matrix of 2 columns and a `vector`.
[Answer]
# Python 3, ~~61~~ 60 bytes
```
f=lambda a,b,c,d=0:c and a[d:c[0]]+f(b,a,c[1:],c[0])or a[d:]
```
[Try it online!](https://tio.run/##dY5BDoIwFET3nmKWEGdBBRSacJKmi9KGaKJACBtPX9tGo5iQ/C76Xmd@5@d6ncbS@6G7m0fvDAx7WrqukBZmdDDKSasKrY9D1tPQKiE1I8mnJVnt5@U2rtmQBUglwgkyP3wpI2vZJLs1OBEVcSYaIsShBFESNXEhWkL8sE1WpGzAVXxRp44QaeLtf8nuvMt3J/risyh@MjT7Fw "Python 3 – Try It Online")
-1 byte from Jonathan Frech
Explanation:
```
f=lambda a,b,c,d=0:c and a[d:c[0]]+f(b,a,c[1:],c[0])or a[d:]
f=lambda a,b,c,d=0:
# recursive lambda: a and b are the two lists,
# c is the crossovers, and d is where to start
c and
# if there is at least one crossover left
# then
a[d:c[0]]
# return the items of the first list from the
# starting point up to the first crossover
+f(b,a,c[1:],c[0])
# plus the result of the inverted lists with
# the remaining crossovers, starting where
# the first part left off
or
# else
a[d:]
# the first list from the starting point to the end
```
[Answer]
# SWI-Prolog, 78 bytes
```
A/B/[0|C]/D:-B/A/C/D. [H|A]/[_|B]/C/[H|D]:-maplist(succ,E,C),A/B/E/D. A/_/_/A.
```
Usage: Call "Genes1/Genes2/CrossoverPoints/X" where "Genes1", "Genes2", "CrossoverPoints" are bracket-enclosed, comma-separated lists.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 10 bytes
```
ṁ⁹L‘¤ḣ"ḷ"/
```
[Try it online!](https://tio.run/##y0rNyan8///hzsZHjTt9HjXMOLTk4Y7FSg93bFfS////f3S0qY6CmY6CuY6CRayOQrShjoKRjoKxjoJJbOx/MC8WAA "Jelly – Try It Online")
Argument 1: seq1, seq2
Argument 2: cross points (0-indexed)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ṬœṗЀż/JḂị"ƊF
```
A dyadic link accepting the (1-indexed) crossover points on the left and a list of the two sequences on the right which returns the resulting list.
**[Try it online!](https://tio.run/##y0rNyan8///hzjVHJz/cOf3whEdNa47u0fd6uKPp4e5upWNdbv///4820lEw0VEwi/0fHW2gowDl6ShY6CgYxOooRBvqKBjrKJjqKJjrKFjqKBjGxgIA "Jelly – Try It Online")**
### How?
```
ṬœṗЀż/JḂị"ƊF - Link: list, C; list, S e.g. [2,4,6]; [[0,2,4,6,8,0],[1,3,5,7,9,1]]
Ṭ - untruth C [0,1,0,1,0,1]
Ѐ - map across S with:
œṗ - partition at truthy indices [[0],[2,4],[6,8],[0]] / [[1],[3,5],[7,9],[1]]
/ - reduce with:
ż - zip [[[0],[1]],[[2,4],[3,5]],[[6,8],[7,9]],[[0],[1]]]
Ɗ - last three links as a monad:
J - range of length [1,2,3,4]
Ḃ - bit (modulo by 2) [1,0,1,0]
" - zip with:
ị - index into [[0],[3,5],[6,8],[1]]
F - flatten [0,3,5,6,8,1]
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes
```
AθAηE§θ⁰§§θLΦ⊕κ№ηλκ
```
[Try it online!](https://tio.run/##TYzNCsIwEITvPsWS0wZWSK31h55EEAoK3kMOoQ2mNKZtSMW3jwERnMPwzcBMa3VoR@1Savy0RJx5vfqSzXQPvY940xOeYuM788aZQHCCX/yrr8Y/osVL76IJ2Pg2mKfx0XQ45MF5XPKTJXA8i2DIXqckJROb7e4gGAErymp/LJgikAVBSVApldYv9wE "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a pair of string gene sequences and a 0-indexed list of crossing points. Explanation:
```
Aθ Input the pair of gene sequences into `q`
Aη Input the list of crossing points into `h`
E§θ⁰ Loop over one of the gene sequences
κ Current index
⊕ Incremented
Φ №ηλ Intersect implicit range with crossing points
L Take the length
§θ Cyclically index into the pair of gene sequences
§ κ Take the appropriate element of that sequence
Implicitly output on separate lines
```
Alternatively, `⭆` could be subsituted for `E` to print the result as a string. [Try it online!](https://tio.run/##TUzLCsIwELz7FUtOG1ihsdYHPYkgFBQEj6WH0oamNKZt2Ip/HwMiOId5wUxjat@MtQ2hcNPCOMt89XUmurvvHeODo3S3esITF67Vb5wJEknwi3/1VbuODV56y9pj4Rqvn9qxbnGIg/O4xD9DYGUEwRA5D6EsRbLZ7g6JIBAqzfZHJSqCUhGkBFlVhfXLfgA "Charcoal – Try It Online")
[Answer]
# [C (clang)](http://clang.llvm.org/), 79 bytes
```
*g[2],*c,l,m;f(i,j,k){for(i=j=k=0;i<l;g[0][i++]=g[k][i])m&&c[j]==i?k=!k,j++:0;}
```
[Try it online!](https://tio.run/##lVPbbuIwEH3PV8ymahUTd5sb2y0m8APVvu1TGlVRSFJDCCugUoDy7XRsx0kK5WGRpXjOnLmdMel9WiZVcbrhVVq@z7LxZjvjq59vE6OHrHlVIHQaFJEX00FKS7pkucXpnC7IIV@tLR7Ow0XoMD4uWRE5ccRtOw6LaIG3mCzv7tJoHochny7CHws6t@2Rw46nm1mW8yqDZL1OdmVWWTUBq55u@D5b5Wg86BtmJCOHGIaO@IctbWWYVdOSwAFeDJ5bf/4@P0MYQg0fH1CKmyN8kp1bZhSDSdgRuVm5ydAhoqotvHJAJkOrZSIPTTGaduJ3DKX42jZpU97ObjcmhTp65TEFJI@t8t4lZIqgOTJVGk2W5dEWHRy7YRKcAXYU9gRAtHSA734vBghlsZmaXeCuwHfneIrgnl3mQWX6mjONL/v4XrYK13rpbUC0hUtgl7j7LZ7SZR9EYSCcSGl08twi7L@Kvm83lmmSMwFQY7nfZcIrCx@CNLapW0RCroNzpMJ6U5arrFT7WMP2NJuConhNwBOF3wpIdQYd43cxHoWAwi/kUlAFfV2Qgk9hSOGRwpNO7qdfnG3GoGhxT7oCSQ@aXENZ4lF3FDRZ2vBh19DVIyOHXXNXjyKm/RF9NSLWMxJLKKyUVYoSJkGvUOopyRrQL5QkavYGDAo1mxqlAYeF6k8VR1Bs92FgiHcA4qWB/HdMxB1B7FNAYknKL12OMKX3y14k42wdPayNVQQVJKp02xDsbgnCanrpGLLs1dOUu3rkfH2t2/yuTNAyndaMjcHD6RM "C (clang) – Try It Online")
Inputs:
`g[0]` is gene-sequence 1,
`g[1]` is gene-sequence 2,
`c` is cross-over points.
`l` is length of `g[0]` and `g[1]`
`m` is length of `c`
All array inputs are arrays of integers with 0-based index.
Outputs:
Output is stored in `g[0]`
macro a() in footer does pretty-printing of test-cases and result
] |
[Question]
[
*This is a [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") challenge. For the cops thread, go [here](https://codegolf.stackexchange.com/q/109949/42963).*
This challenge involves two [OEIS](https://oeis.org/) sequences chosen by the cops -- **S1**, **S2** -- and how well those sequences can be golfed and obfuscated.
The cops are constructing code **A** that produces **S1** and giving a number **X** that they claim is the best [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance) possible (in characters) to create **B** that produces **S2**.
### The Robbers' Challenge
To crack a particular cop's submission, robbers must come up with a program **C** in the same language (and version) as that answer that produces S2(n) and is **Y** character changes away from **A** (with `Y <= X`). Robbers do not necessarily need to find the exact same **B** code that the cop (secretly) produced. The robbers' submissions must adhere to the same 0-index or 1-index as specified by the cop's submission.
If you manage this, post an answer with the solution, linking to the cop's answer, and leave a comment on the cop's answer linking back to yours.
Each cop answer can only be cracked once, and of course, you're not allowed to crack your own answer. If the cop's answer turns out to be invalid before or after being cracked, it is not counted towards the robber's score.
### Winning and Scoring
Robbers are scored by `(X - Y)*5 + 5` for each of their cracks, and the robber with the overall highest score wins.
### Further Rules
* You must not use any built-ins for hashing, encryption, or random number generation (even if you seed the random number generator to a fixed value).
* Either programs or functions are allowed, but the code must not be a snippet and you must not assume a REPL environment.
* You may take input and give output [in any convenient format](http://meta.codegolf.stackexchange.com/q/2447/42963). The input/output methods must be the same for both sequences.
* The definitive calculator for the Levenshtein distance for this challenge is [this one](http://planetcalc.com/1720/?license=1) on Planet Calc.
* In addition to being a CnR challenge, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply.
[Answer]
# Pyke, Levenshtein distance of 1, [A036487](https://oeis.org/A036487), [A135628](https://oeis.org/A135628) - score 5
Crack of an [entry](https://codegolf.stackexchange.com/a/109955/53748) by muddyfish
```
wX*e
```
[Try it here!](http://pyke.catbus.co.uk/?code=wX%2ae&input=3)
The original code, `X*e`, squares the input, `X`, multiplies that by the input `*`, and halves then floors the result, `e`.
The trick is that `'X'` is 56 in the base 96 representation of `w`, so `wX` yields 56, multiply that by the input then floor and halve and you get 28 times the input as needed.
[Answer]
# [Brain-Flak](https://codegolf.stackexchange.com/a/109953/31716), 28 bytes, Distance of 4, [A002817](http://oeis.org/A002817), [A090809](http://oeis.org/A090809)
```
(({(({})[()])}{}){{({}[()])}{}})
```
This answer was discovered with the help of a brute-forcer, which generated 35,000 possible programs (Lot's of them were imbalanced, and thus invalid brain-flak code, but I rolled with the bug and found the answer anyway). This was around the 20 thousandth program tested, and it took around an hour to find (though I don't know exactly how long since I was away when it finished).
I kind of didn't want to post this answer yet, since I don't yet have a full understanding of how this program works. However, the answer is about to be safe so I don't want it to expire. I hope to update this answer more once I fully understand it, as well as posting the code I used to find this answer. But for now, I'll just post a partial explanation.
```
#Push the sum of:
(
#The (n-1)th triangular number, and the range [1, n] (The range doesn't count towards the sum I believe)
({(({})[()])}{})
#Triangulate every number on the stack
{{({}[()])}{}}
)
```
This makes sense because OEIS states:
>
> For n>0, the terms of this sequence are related to A000124 by a(n) = sum( i\*A000124(i), i=0..n-1 ). [Bruno Berselli, Dec 20 2013]
>
>
>
And A000124 are the triangular numbers + 1. However, I don't know exactly what the forumla is, so I can't fully explain how this works.
[Answer]
# [Perl 6, 19 bytes, X = 1, A000045 → A000035](https://codegolf.stackexchange.com/a/109990/12012)
```
{(0,1,*+<*...*)[$_]}
```
`+>` in place of `+<` would also work.
[Try it online!](https://tio.run/nexus/perl6#jY9LCsIwGIT3PcVQRDSGkD8Pk9DWS7gUkeIDXRSFuiniwh7Vi8SA7cqNMwzDbD6YpsP0hCo@ZpITZ4uSCSHYfDPZbZ@xrTvk63f/wqAKOUcpQckKGhYepKEI2sCmFUDGQGkN7RyWJBG8A9ngoKw3MORpVWQjuP8F/5ERkA99P19a7K@H4xfT1Lf0iUMKQaHI4gc "Perl 6 – TIO Nexus")
### How it works
[infix ...](https://docs.perl6.org/language/operators#infix_...) is quite useful for simple recursive sequences. The `(0,1,*+*...*)` part of the original code, which is a shorthand for
```
(0, 1, -> $x, $y { $x + $y } ... *)
```
specifies a sequence that begins with **0** and **1**, then adds items by computing the sum of the former two items of the sequence.
In contrast, `(0,1,*+<*...*)` uses left bit-shift (`+>`, right bit-shift would also work) to construct the parity sequence. Since shifting **1** zero units to the left is **1**, and shifting **0** one unit to the left is **0**, we get the desired alternating patterns of ones and zeroes.
[Answer]
# [Perl 6](http://perl6.org/), 10 bytes, distance 1 - score 5
Crack of an [entry](https://codegolf.stackexchange.com/a/109961/53748) by smls
```
*[0]o 1***
```
Becomes:
```
*[0]o 1*+*
```
[Try It Online!](https://tio.run/nexus/perl6#y61UUEtTsP2vFW0Qm69gqKWt9d@aqzixUiE3sQAoo6NgoKdnZGD9HwA)
[Answer]
# [Perl 6](https://perl6.org), distance 2, [smls](https://codegolf.stackexchange.com/a/109992/60793)
Original:
```
+(*%%2)
```
Crack:
```
+(*+0%2)
```
[Try it online!](https://tio.run/nexus/perl6#jY5NCoJQAIT3nuJDKCpF3jx/H2aX6ATSD7WQAtu4zKN2ETMyol0Dw8AMfEzTMT9SDcFiFZiZXQ6l19Yd/vbR35lU4YesheEPb76A/hfwmi0xCSkZOQUOjaWQRTFKUIoylKMCuQ/Kn/J2OrfsLvvDG9jU1/F7iIkiudIbng "Perl 6 – TIO Nexus")
[Answer]
# WolframAlpha, Distance 1, [Greg Martin](https://codegolf.stackexchange.com/questions/109949/change-the-code-change-the-sequence-cops/110052#110052), [A002378](https://oeis.org/A002378), [A000537](https://oeis.org/A000537)
```
(sum1to#of n^1)^2&
```
**How it works**
I realized that interestingly, (n\*(n+1)/2)^2 is a formula for the second sequence. Since sum(1 to n) is equivalent to n\*(n+1)/2, I just had to switch the \* to a ^.
[Answer]
## [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 20 bytes, [DJMcMayhem](https://codegolf.stackexchange.com/a/110074/8478)
```
({({})({}[()])()}{})
```
[Try it online!](https://tio.run/nexus/brain-flak#@69RrVFdqwnE0RqasZoamrVA3v//5gA "Brain-Flak – TIO Nexus")
Added a `({})` at the beginning of the loop to double the value in each iteration.
[Answer]
# JavaScript, Distance 4, [LliwTelracs](https://codegolf.stackexchange.com/a/109962/41805)
Original:
```
f=x=>{return x?2*x-1+f(x-1):0}
```
Crack:
```
f=x=>{return x?2*(-0+f(x-1)):1}
```
[Try it online!](https://tio.run/nexus/javascript-node#@59mW2FrV12UWlJalKdQYW@kpaFroJ2mUaFrqKlpZVj7Pzk/rzg/J1UvJz9dI03DQFMnTcMQRBiBCGMQYQIiTEGEGYgwBxEWIMISrNhAU/M/AA "JavaScript (Node.js) – TIO Nexus")
[Answer]
## JavaScript(ES6), Distance 1, [Advancid](https://codegolf.stackexchange.com/a/109973/64505)
Original:
```
as=function(){ return 2*2**((11)*-1*~arguments[0]/11-(4-(as+[]).length%89))-(as+[]).length%7}
```
Crack:
```
as=function(){ return 0*2**((11)*-1*~arguments[0]/11-(4-(as+[]).length%89))-(as+[]).length%7}
```
[Try it online!](https://tio.run/#44oQb)
or
```
as=function(){ return 2*1**((11)*-1*~arguments[0]/11-(4-(as+[]).length%89))-(as+[]).length%7}
```
[Try it Online!](https://repl.it/Fi29/2)
Somehow I was able to get it to behave differently between TIO and repl.it (absolutely no clue why 2\*1^... would be equal to 0 as according to repl.it)
[Answer]
# [Javascript, 41 bytes, Distance of 3, A061313, A004526](https://codegolf.stackexchange.com/a/109970/12012)
```
f=x=>{return x>>1;0?x%2?f(x+1)+1:f(x/2)+1:0}
```
[Try it online!](https://tio.run/nexus/javascript-node#@59mW2FrV12UWlJalKdQYWdnaG1gX6FqZJ@mUaFtqKltaAVk6BuBGAa1/0tso2O50vKLNKxL9HJS89JLMmwMDQyAnILS4gwNmJimpjVXcn5ecX5Oql5OfjpQPDexQCNNU/M/AA "JavaScript (Node.js) – TIO Nexus")
[Answer]
## Java, Distance 4, [Peech](https://codegolf.stackexchange.com/a/110041/64505), [A094683](https://oeis.org/A094683), [A000290](https://oeis.org/A000290)
Original:
```
int x{double r=1;for(int i=0;i<42;i++)r=r/2+n/r/2;int k=(int)((int)n*(float)n/Math.pow(n,(Math.sin(n)*Math.sin(n)+Math.cos(n)*Math.cos(n))/2));return n%4%2==(int)Math.log10(Math.E)/Math.log((double)'H'-'@')?(int)r:k;}
```
Crack:
```
int x{double r=1;for(int i=0;i<42;i++)r=r/2+n/r/2;int k=(int)((int)n*(float)n/Math.pow(n,(Math.sin(n)*Math.sin(n)+Math.cos(n)*Math.cos(n))/2));return n%4%1==(int)Math.log10(Math.E)/Math.log((double)'H'-'@')?(int)n*n:k;}
^ ^^^
```
returns n\*n
[Answer]
# Javascript, [Advancid](https://codegolf.stackexchange.com/a/110058/64505), distance of 2, [A059841](http://oeis.org/A059841) and [A000004](https://oeis.org/A000004)
Only leaving the code behind the TIO link because it seems to be breaking the site.
Thanks to @nderscore, whose [code](https://codegolf.stackexchange.com/a/28745/64505) I used to decrypt the initial code
There was some redundant code such as using !![]+[]+[] instead of !![]+[].
The addition of !+[]-(!+[]) (+1-1) initially prevented decryption.
[Try it Online](https://tio.run/nexus/javascript-node#7VvBjoMgEL33L7hBTJv2vn4J4WA2tjZxa5PuZj/fRVSkCNTtttXVlxhtZnAYGd4wD@0@LrnglHARqYNxeRIR5aS6SJW8SBlR2koldaRpqYSkbk96FggxZbqtdUNjW0gfOj/@6ETnwdDOg61G88o2XndptHD0d6vTVm/aagWTHH3L3GSCYetpf4zJ0Oj0ghEMVyOK9KOPPyTEMu@5QzqtBKR5JqUC7p@K@6vEDPA/B/ymCVfUlFGK6Y5l7r/P9O63mfa95l2xtFwL3DrWIMwJpMDpXXQENelsatJrU1UNqntvmzG5Lk88tqpyRs2MImIW5bJP7wlAwHFXFloUyXTtvAE1iyCZgpqSeiUbBBqPT4yyzvPmjCocqxzwiur7zurbNau8OwJ9@xPcHAh7qmPRT80gG0jDSMMgGwDMAwBj7kMDNi9nG27KQfy8Atv5WMHG2uUAm5jdXj6YApgC8ixKHjAFAAaAmQtH6GARekL390Pe2XEbqC8ZXn38ulCwFILWPbWvaaxuPF9fGQONdzrIeMh4YGFgYWBhSLFIsWBhAAwAAxa2BBbm@UvcQxjYeqfUazX4TLAyiblYfWfHPKXJJk9Ph8/sLd5ttyzZnL8umRay1XtxuhR5usmLg5R@JGe6Z6z8AQ)
[Answer]
# [Pyke, Levenshtein distance of 2, A008788, A007526](https://codegolf.stackexchange.com/a/109958/12012)
```
'SS^
```
[Try it here!](http://pyke.catbus.co.uk/?code=%27SS%5E&input=5)
### How it works
This does mixed base conversion.
`'S` grabs the input **n** and applies, pushing **[1, ..., n]** on the stack. The next `S` takes input **n** and pushes the same array once more.
`'` seems to cause the next command to be applied to the previous top on the stack; I'm a little fuzzy on the details.
Finally, `^` applies mixed base conversion, so **[1, ..., n] [1, ..., n]** `f` computes
**a(n) := [1]n + n + (n)(n-1)... + [n!]1** where the brackets indicate the place value and the number to their right the digit.
Now, **a(n) = (1 + (1)(n-1) + (n-1)(n-2)(n-3) + ... + (n-1)!)n = n(a(n) + 1)**, which is the same recursive formula that defines **a(n)** in [A007526]. Since an empty sum is zero, **a(0) = 0** and the base case matches as well.
] |
[Question]
[
Take a non-nested array as input. Turn it into a matrix by using the following method:
Let's say my array is `[1, 2, 3, 4, 5]`
First, I repeat that array 5 times: (the length)
```
[[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5]]
```
Then, I read it along the diagonals:
```
[[1],
[2, 1],
[3, 2, 1],
[4, 3, 2, 1],
[5, 4, 3, 2, 1],
[5, 4, 3, 2],
[5, 4, 3],
[5, 4],
[5]]
```
I flatten this array and split it into pieces of five (the length):
```
[[1, 2, 1, 3, 2],
[1, 4, 3, 2, 1],
[5, 4, 3, 2, 1],
[5, 4, 3, 2, 5],
[4, 3, 5, 4, 5]]
```
This is code golf. Fewest bytes wins.
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 11 bytes
```
WẋLŒDUṙLFsL
```
[Try it online!](http://jelly.tryitonline.net/#code=V-G6i0zFkkRV4bmZTEZzTA&input=&args=WzEsMiwzLDQsNV0&debug=on)
## Explanation
```
Input: array z
WẋL length(z) copies of z
ŒD Diagonals (starting with main diagonal)
U Reverse each
·πôL Rotate left length(z) places
(now the top-left diagonal is in front)
F Flatten
sL Split into chunks of size length(z)
```
[Answer]
# Python 2, ~~105~~ 96 bytes
-1 and -4 and -4 bytes thanks to Flp.Tkc
```
a=input()
n=len(a)
L,M=[],[]
for i in range(n):L+=a[i::-1];M+=a[:i:-1]
print zip(*[iter(L+M)]*n)
```
The for loop adds the items like in the description, the real magic happens in the zip which is from [here](https://stackoverflow.com/a/10124783/7082271)
[Answer]
# JavaScript (ES6) 100 ~~101 105~~
```
a=>eval("for(u=r=[],i=l=a.length;i+l;i--)for(j=l;j--;v&&((u%=l)||r.push(s=[]),s[u++]=v))v=a[j-i];r")
```
*Less golfed*
```
a => {
u = 0
for(r=[], i=l=a.length; i+l>0; i--)
for(j=l; j--; )
{
v = a[j-i]
if (v)
{
u %= l
if (u==0) r.push(s=[])
s[u++] = v
}
}
return r
}
```
**Test**
```
F=
a=>eval("for(u=r=[],i=l=a.length;i+l;i--)for(j=l;j--;v&&((u%=l)||r.push(s=[]),s[u++]=v))v=a[j-i];r")
function update() {
var a=I.value.match(/\d+/g)
if (a) {
var r=F(a)
O.textContent = r.join`\n`
}
}
update()
```
```
<input id=I value='1 2 3 4 5' oninput='update()'>
<pre id=O></pre>
```
[Answer]
# 05AB1E, 13 bytes
```
.p¹.sR¦«í˜¹gä
```
[Try it online!](http://05ab1e.tryitonline.net/#code=LnDCuS5zUsKmwqvDrcucwrlnw6Q&input=WzEsIDIsIDMsIDQsIDVd)
Explanation:
```
# Implicit input
.p # Get prefixes
¬π # Get first input
.s # Get suffixes
R # Reverse
¦ # Remove first element
¬´ # Concatenate
í # Reverse every one
Àú # Flatten
¬πg√§ # Split into pieces of the length
# Implicit print
```
[Answer]
# [MATL](http://github.com/lmendo/MATL), 17 bytes
```
!Gg*tRwZRhPXzGne!
```
[Try it online!](http://matl.tryitonline.net/#code=IUdnKnRSd1pSaFBYekduZSE&input=WzEgMiAzIDQgNV0)
### How it works
The following explanation uses input `[1 2 3 4 5]` as an example. To visualize the intermediate results, insert `%` (comment symbol) after any statement in the code.
Note that `;` is the row separator for matrices. So `[1 2]` is a row vector, `[1; 2]` is a column vector, and `[1 0; 0 1]` is the 2√ó2 identity matrix.
```
! % Implicitly input a row vector. Transpose. Gives a column vector
% STACK: [1; 2; 3; 4; 5]
Gg % Push input with all (nonzero) values replaced by ones
% STACK: [1; 2; 3; 4; 5], [1 1 1 1 1]
* % Multiply, with broadcast. Gives a square matrix
% STACK: [1 1 1 1 1;
2 2 2 2 2;
3 3 3 3 3;
4 4 4 4 4;
5 5 5 5 5]
tR % Duplicate. Upper triangular part
% STACK: [1 1 1 1 1;
2 2 2 2 2;
3 3 3 3 3;
4 4 4 4 4;
5 5 5 5 5],
[1 1 1 1 1
0 2 2 2 2;
0 0 3 3 3;
0 0 0 4 4;
0 0 0 0 5]
wZR % Swap. Lower triangular part, below main diagonal
% STACK: [1 1 1 1 1;
0 2 2 2 2;
0 0 3 3 3;
0 0 0 4 4;
0 0 0 0 5],
[0 0 0 0 0;
2 0 0 0 0;
3 3 0 0 0;
4 4 4 0 0;
5 5 5 5 0]
h % Concatenate horizontally
% STACK: [1 1 1 1 1 0 0 0 0 0;
0 2 2 2 2 2 0 0 0 0;
0 0 3 3 3 3 3 0 0 0;
0 0 0 4 4 4 4 4 0 0;
0 0 0 0 5 5 5 5 5 0]
P % Flip vertically
% STACK: [0 0 0 0 5 5 5 5 5 0;
0 0 0 4 4 4 4 4 0 0;
0 0 3 3 3 3 3 0 0 0;
0 2 2 2 2 2 0 0 0 0;
1 1 1 1 1 0 0 0 0 0]
Xz % Column vector of nonzeros, taken in column-major order
% STACK: [1;2;1;3;2;1;4;3;2;1;5;4;3;2;1;5;4;3;2;5;4;3;5;4;5]
Gne % Reshape into a matrix with as many rows as input size
% STACK: [1 1 5 5 4;
2 4 4 4 3;
1 3 3 3 5;
3 2 2 2 4;
2 1 1 5 5]
! % Transpose. Implicitly display
% STACK: [1 2 1 3 2;
1 4 3 2 1;
5 4 3 2 1;
5 4 3 2 5;
4 3 5 4 5]
```
[Answer]
# [J](https://www.jsoftware.com), 14 bytes
```
#($$&;</.)@#,:
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FNVUtFK8NYM0UrS3V1LiU99TQFWysFdQUdBQMFKyDW1VNwDvJxW1pakqZrsU5ZQ0VFzdpGX0_TQVnHCiJ4006Ty89JT0EjGiLloKJZp6yjDBbTdVCOjVGzVgYJAzVwpSZn5CukKRjqKBjpKBjrKJjoKJhCTFmwAEIDAA)
* `#...#,:` Duplicate the input n times, where n is the input length. We require `,:` to make the duplication work at the "row level" rather than the element level.
* `</.` Box every diagonal of the resulting n by n matrix. J's `/.` does the heavy lifting here.
* `$$&;` Unbox that result `;` into a single list and reshape it `$` to the shape of duplicated input `$`.
[Answer]
# [Uiua](https://uiua.org), 12 [bytes](https://codegolf.stackexchange.com/a/265917/97916)
```
⊏⍜♭⍏⊞+.⊃⇡▽⧻.
```
[Try it online!](https://www.uiua.org/pad?src=ZiDihpAg4oqP4o2c4pmt4o2P4oqeKy7iioPih6Hilr3ip7suCgpmIFsxIDIgMyA0IDVdCmYgWzFdCg==)
```
⊏⍜♭⍏⊞+.⊃⇡▽⧻. input: vector V of length N
⧻. keep V and push N
⊃⇡▽ consume both and push [0..N-1], V cycled N times
‚äû+. self outer product of range by addition
⍜♭⍏ flatten, replace the array with its sorting order, and
put it back into the same sized matrix
‚äè for each number in the matrix, select the item at that index
in "V cycled N times"
```
The above is a slightly golfuscated version of the code below:
# [Uiua](https://uiua.org), 14 [bytes](https://codegolf.stackexchange.com/a/265917/97916)
```
⍜∩♭'⊏⍏⊞+.⍏.↯⧻.
```
[Try it online!](https://www.uiua.org/pad?src=ZiDihpAg4o2c4oip4pmtKOKKj-KNjyniip4rLuKNjy7ihq_ip7suCgpmIFsxIDIgMyA0IDVdCmYgWzFdCg==)
```
⍜∩♭'⊏⍏⊞+.⍏.↯⧻. input: a vector of integers of length N
↯⧻. make the input a matrix by copying the input N times -> X
‚çè rise; sorting order of the rows (same as range N)
‚äû+. self outer product by addition -> Y
‚çú‚à©‚ô≠ . operate on X and Y flattened and assemble back..
'⊏⍏ reorder elements of X by sorted order of elements of Y
```
[Answer]
## JavaScript (ES6), 116 bytes
```
a=>a.map(_=>b.splice(0,a.length),b=[].concat(...a.map((_,i)=>a.slice(~i)),...a.map((_,i)=>a.slice(0,~i))).reverse())
```
Well, it's a start...
[Answer]
## R, 84 bytes
```
t(matrix(unlist(split(m<-t(matrix(rev(x<-scan()),l<-sum(1|x),l)),row(m)-col(m))),l))
```
Reads input from stdin and outputs/returns an R-matrix.
```
reversed_x <- rev(x<-scan()) # Read input from stdin and reverse
m <- t(matrix(reversed_x,l<-sum(1|x),l)) # Repeat and fit into matrix
diag_list <- split(m,row(m)-col(m)) # Split into ragged list of diagonals
t(matrix(unlist(diag_list),l)) # Flatten and transform back to matrix
```
**Explained**
The most interesting aspect about this answer is how the diagonals are retrieved. In general an object can be split up using the `split` function if supplied an object containing factors upon which the object is split into. To create these factors we can use `col` and `row` which return a matrix containing the column and row indices respectively. By taking the differences: `row(m)-col(m)` we get a matrix like:
```
[,1] [,2] [,3] [,4] [,5]
[1,] 0 -1 -2 -3 -4
[2,] 1 0 -1 -2 -3
[3,] 2 1 0 -1 -2
[4,] 3 2 1 0 -1
[5,] 4 3 2 1 0
```
in which each diagonal is uniquely identified. We can now split based on this matrix and turn it into a ragged list by applying `split`:
```
$`-4`
[1] 1
$`-3`
[1] 2 1
$`-2`
[1] 3 2 1
$`-1`
[1] 4 3 2 1
$`0`
[1] 5 4 3 2 1
$`1`
[1] 5 4 3 2
$`2`
[1] 5 4 3
$`3`
[1] 5 4
$`4`
[1] 5
```
(Note how the name of each vector correspond to the diagonal values in the matrix above).
The last step is just to flatten and turn it into a matrix of the form:
```
[,1] [,2] [,3] [,4] [,5]
[1,] 1 2 1 3 2
[2,] 1 4 3 2 1
[3,] 5 4 3 2 1
[4,] 5 4 3 2 5
[5,] 4 3 5 4 5
```
[Answer]
# Ruby, 110 bytes
```
n=a.size
b=[*(0...n)]
b.product(b).group_by{|i,j|i+j}.flat_map{|_,f|f.sort.map{|i,j|a[i][j]}}.each_slice(n).to_a
```
```
#=> [[1, 2, 1, 3, 2],
# [1, 4, 3, 2, 1],
# [5, 4, 3, 2, 1],
# [5, 4, 3, 2, 5],
# [4, 3, 5, 4, 5]]
```
The `sort` operation may not be required, but the doc for Enumerable#group\_by does not guarantee the ordering of values in the hash values (which are arrays), but current versions of Ruby provide the ordering one would expect and the ordering I would need if `sort` were removed from my code.
The steps are as follows.
```
n=a.size
#=> 5
b=[*(0...n)]
#=> [0, 1, 2, 3, 4]
c = b.product(b)
#=> [[0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [1, 0], [1, 1], [1, 2], [1, 3],
# [1, 4], [2, 0], [2, 1], [2, 2], [2, 3], [2, 4], [3, 0], [3, 1], [3, 2],
# [3, 3], [3, 4], [4, 0], [4, 1], [4, 2], [4, 3], [4, 4]]
d=c.group_by{|i,j|i+j}
#=> {0=>[[0, 0]],
# 1=>[[0, 1], [1, 0]],
# 2=>[[0, 2], [1, 1], [2, 0]],
# 3=>[[0, 3], [1, 2], [2, 1], [3, 0]],
# 4=>[[0, 4], [1, 3], [2, 2], [3, 1], [4, 0]],
# 5=>[[1, 4], [2, 3], [3, 2], [4, 1]],
# 6=>[[2, 4], [3, 3], [4, 2]],
# 7=>[[3, 4], [4, 3]],
# 8=>[[4, 4]]}
e=d.flat_map{|_,f|f.sort.map{|i,j|a[i][j]}}
#=> [1, 2, 1, 3, 2, 1, 4, 3, 2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2, 5, 4, 3, 5, 4, 5]
f=e.each_slice(n)
#=> #<Enumerator: [1, 2, 1, 3, 2, 1, 4, 3, 2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2,
# 5, 4, 3, 5, 4, 5]:each_slice(5)>
```
Lastly, `f.to_a` returns the array shown earlier.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 55 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 6.875 bytes
```
LẋÞ`f?Lẇ
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyI9IiwiIiwiTOG6i8OeYGY/TOG6hyIsIiIsIlsxLDIsMyw0LDVdIl0=)
Bitstring:
```
0110000101111000101000101100100011000011001101100100000
```
```
LẋÞ`f?Lẇ­⁡​‎⁠‏​⁢⁠⁡‌⁢​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁣‏⁠‎⁡⁠⁤‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌­
# ‎⁡implicit input
Lẋ # ‎⁢repeated [length] times
Þ` # ‎⁣antidiagonals
f?Lẇ # ‎⁤flatten and wrap in chunks the size of the length
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 22 bytes
```
{x@l!s#,/=+/!s:2#l:#x}
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6qucMhRLFbW0bfV1lcstjJSzrFSrqjl4kpzMNRWNAUAky4INg==)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 72 bytes
```
->a,*r{t=[]
a.map{r+=t=[_1]+t}
r+=t while t.pop
[*r.each_slice(a.size)]}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGiNNulpSVpuhY3PXTtEnW0iqpLbKNjuRL1chMLqou0bYG8eMNY7ZJaLhBHoTwjMydVoUSvIL-AK1qrSC81MTkjvjgnMzlVI1GvOLMqVTO2FmLe5gIFrbRohWhDHSMdYx0THdNYhViIzIIFEBoA)
[Answer]
# [Scala](http://www.scala-lang.org/), 154 bytes
Golfed version. [Try it online!](https://tio.run/##XY9Na4QwFEX3/oq7TGhGxn5s4mSgy4JZla4GF69OlBQbh5gKrfjbbeKUUrp5cN8798EZG@ppHV7fTBOgyTrMWQZM1KOVYI/e0@fpyYVaHSs7htM2Uq45FFZSxzmxTlE@2i9TTuRRCa1@OcbLdvDMHnZ7hAFuV/C5UpWUMjZ62xi2F/am4Lk3k/GjycOQuqVW@g8TCeH@M0vJ0h9onnd@@LiYM4vMz20FzqbFe1Ri5LtR4uryHLx1Xc0lXpwN0WGOuldhimmDWCFwK3AncC/wwDfgEmuhd6xlxNNmyZb1Gw)
```
a=>{val n=a.size;var L,M=List[Int]();for(i<-0 to n-1){L=L:::a.slice(0,i+1).reverse.toList;M=M:::a.slice(i+1,n).reverse.toList};(L::: M).grouped(n).toList}
```
Ungolfed version. [Try it online!](https://tio.run/##bZAxa8MwEIV3/4o3SkQVSdouoh06FuypZAoZVEdxVRTZSJdAGvzb3bNjAoWO9@5770mXaxvsMLSf364mVNZHXAtg7w448iBsarLBW0r2sv2g5GOzkwab6AmvEwmcbYDlaYLESmGt8KjwpPAs70BkwOrgYkNfs5hQKlSslz6TdseOLtv3SLti2h/aBOHx8oAlTpE8R8i5EChHF4wxnJmDr51YKvjFSurkzi5lp6kdU2d8LKn@4MwqDvwP74v7o39817k9m8WtrJK6Se2JNcHe2TPRHV@GQhQ3x/jtvuiH4Rc)
```
object Main {
def main(args: Array[String]): Unit = {
val a = Array(1, 2, 3, 4, 5)
val n = a.length
var L, M = List.empty[Int]
for (i <- 0 until n) {
L = L ::: a.slice(0, i+1).reverse.toList
M = M ::: a.slice(i+1, n).reverse.toList
}
val zipped = (L ::: M).grouped(n).toList
println(zipped)
}
}
```
[Answer]
# [Uiua](https://uiua.org) (0.1.0), 20 bytes
```
↯~√⧻./⊐⊂≐(□↘)-⇡×2.⧻.
```
[Try it online](https://www.uiua.org/pad?src=4oavfuKImuKnuy4v4oqQ4oqC4omQKOKWoeKGmCkt4oehw5cyLuKnuy4gWzEgMiAzIDQgNV0K)
## Explanation
```
⧻. # (nondestructively) get array length
-‚á°√ó2. # construct a range from len down to -len + 1
≐(□↘) # for each element of the range, drop that many from the array
/⊐⊂ # join all resulting arrays together
√⧻. # get square root of length, suppose we call it N...
‚ÜØ~ # ...then this reshapes the array to MxN, where M is inferred
```
[Answer]
## Mathematica 93 Bytes
```
Partition[Flatten[Table[If[i>n,#[[n;;(i-n+1);;-1]],#[[i;;1;;-1]]],{i,1,2(n=Length@#)-1}]],n]&
```
Here's how I'd ordinarily write this code (109 Bytes):
```
Partition[Reverse@Flatten[Table[Reverse@Diagonal[ConstantArray[Reverse@#,n],k],{k,-(n=Length@#)+1,n-1}]],n]&
```
This matrix plot gives a good idea from the structure due to a sequentially increasing input vector.
[](https://i.stack.imgur.com/vfHbO.png)
Here's the matrix plot with a random input vector. Obviously some structure still exists.
[](https://i.stack.imgur.com/Z4yIU.png)
[Answer]
# Mathematica, 92 bytes
```
n=NestList[#2,(r=Reverse)@#,(l=Length@#)-1]&;{Most@r[#~n~Rest],#~n~Most}~ArrayReshape~{l,l}&
```
Unnamed function taking a list as its argument. There might be other structures to such a function, but hopefully I golfed this structure pretty good....
The first part `n=NestList[#2,(r=Reverse)@#,(l=Length@#)-1]&` defines a function `n` of two arguments: the first is a list of length `l`, and the second is a function to apply to lists. `n` applies that function `l-1` times to the reversed argument list, saving all the results in its output list. (Defining `r` and `l` along the way is just golfing.)
`n` is called twice on the original list, once with the function being `Rest` (drop the first element of the list) and once with the function being `Most` (drop the last element). This produces all the desired sublists, but the whole list is there twice (hence the extra `Most`) and the first half is there in backwards order (hence the `r[...]`). Finally, `~ArrayReshape~{l,l}` forgets the current list structure and forces it to be an `l`x`l` array.
[Answer]
**Mathematica, 85 bytes**
Literally performing the steps suggested:
```
(l=Length@#;Partition[Flatten@Table[Reverse@Diagonal[Table[#,l],i],{i,-l+1,l-1}],l])&
```
My gut says that there should be a clever way to use `Part` to do this shorter, but every attempt I've made has been longer than 85 bytes.
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~9~~ 8 bytes
```
CL¹Σ∂RL¹
```
[Try it online!](https://tio.run/##yygtzv7/39nn0M5zix91NAUBGf///4821DHSMdYx0TGNBQA "Husk – Try It Online")
-1 byte from Zgarb.
## Explanation
```
CL¹Σ∂*L¹;
¬π input(appends a ¬π to the end)
; enclosed
*L repeated length times
∂ antidiagonals
Σ flattened into a single list
C cut into pieces of size
L¬π of the length of the input
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 60 bytes
```
Partition[Join@@Reverse[#~Drop~i]~Sum~{i,l=-Tr[1^#],-l},-l]&
```
[Try it online!](https://tio.run/##DcO9CsMgEADgPa8hZDqH9GdMcejUKTTdxIIEQw@ihuu1i3ivbvvBFz2/QvSMi2/r2CZPjIw52VvGZMw9fAO9g1VypbwLOpk/UQrCNuoH2eGpHOit/ru@TYSJrdKX1SjXy7z4JKUrAxzgCCc41662Hw "Wolfram Language (Mathematica) – Try It Online")
] |
[Question]
[
The challenge is: generate an audio file made of white noise.
Requirements and instructions:
* Your program must generate an audio file containing only white noise, meaning its intensity is the same for all (reasonable) frequencies and nonzero [see an example [plot](http://en.wikipedia.org/wiki/File%3aWhite_noise_spectrum.svg)];
* One must be able to play the audio file on the latest version of VLC [at the time of writing your answer];
* The program doesn't need cryptographically-strong randomness, `rand` functions or reading from `/dev/rand` is okay;
* The program must be able to generate at least 1 hour of audio, at least in theory (meaning system limitations like maximum filesize don't apply);
* Your score is the number of bytes in your source code, plus all bonuses that apply;
* Using any *third-party, external* library is okay;
* The program must work without access to the Internet.
Bonuses are:
* -15%: Allow to specify the format of the audio file (at least two choices; the number of possible choices doesn't change the score);
* -10%: Allow to specify the duration of the audio file;
* -5%: Allow to specify the bitrate of the audio file.
The settings can be stored in variables, files, or given as command line parameters, your choice. Percentages are calculated from the original number of bytes, before any bonus is applied.
[Answer]
# Bash, 34
```
dd if=/dev/sda of=file.wav count=1
```
If you don't want hard drive 'randomness', (a lot slower)
```
dd if=/dev/random of=file.wav count=9
```
# SPIN, 28
```
word x=0
repeat
word[?x]=?x
```
[Answer]
# Bash + ALSA, score:44 (52 chars - (10% + 5%) bonuses)
Longer than the other `bash` answer, but accepts duration and bitrate. Also adds a reasonably correct header to the file, so should be reasonably portable:
```
arecord -r$2|head -c44;head -c$[$2*$1] /dev/urandom
```
Save as a script, `chmod +x` it and run:
```
$ ./wav.sh 1 44100 > c.wav
Recording WAVE 'stdin' : Unsigned 8 bit, Rate 44100 Hz, Mono
$
```
Note, .wav output is to stdout, so it must be redirected to a file.
[Answer]
# MATLAB, 25
```
wavwrite(rand(8e3,1),'a')
```
writes a new WAV file to disk called `a`. It has a sample rate of 8 kHz and a 16 bits per sample in signed integer format. The source data is uniformly distributed on the interval `[0,1]`, which is mapped to the interval `[0,32767]` after the conversion to integer format.
# MATLAB, 28 - 4 (10% + 5%) = 24
I'm not sure what the OP meant about how settings could be stored in variables, but I interpreted it in a way that is favorable to this case. Assuming that:
* The desired bit rate (in bits/second) is provided by the user in the variable `b`. The bits per sample is hard-coded at 16.
* The desired duration of the file (in samples) is given in the variable `d`.
The result is:
```
wavwrite(rand(d,1),b/16,'a')
```
# MATLAB, 16 - 4 (15% + 10%) = 12
Adding another layer of sleaze in pursuit of bonuses, I make another assumption: the desired function to use to output the file should be specified in the variable `f`. Then the code simplifies to:
```
f(rand(d,1),'a')
```
Allowable values for the function are:
```
f = @wavwrite
```
or
```
f = @auwrite
```
Each function will cause the above snippet to write out a file of the appropriate format (WAV or `.au`) at a sample rate of 8 kHz with the specified duration. I took off the bonus for specification of the bitrate here, because `auwrite` defaults to 8 bits per sample instead of 16 like `wavwrite` does. I don't see a way to harmonize the two without using more characters.
[Answer]
# Mathematica 52 - 5 = 47
`g` exports a white noise .wav file of `s` seconds and 8000 bps.
```
g@s_:=Export["p.wav",RandomReal@{-1,1}~Play~{t,0,s}]
```
---
Example: a 6 second white noise file is exported.
```
g[6]
```
>
> p.wav
>
>
>
[Answer]
## Supercollider, 89 - 10% = 80.1 bytes
Sadly, despite being deliberately made for generation of sound/audio, this language is not going to win here. But it's the first appearance of Supercollider on Code Golf, so that's cool!
This submission loses primarily because setting up recording and making it happen is a verbose process owing to the client/server design of this language. Still, it's a cool language with a lot of power in very little code when you ask it to do [things more complex than mere white noise.](http://www.earslap.com/instruction/recreating-the-thx-deep-note)
File duration is set by changing the wait() value. I could put it in a variable, but there's really no point to that as Supercollider has no stdio to speak of. The interactivity is in manipulating the code live while the server is still playing. Essentially, the IDE *is* the I/O (unless you build a UI for your creation).
Here's the golfed version:
```
{WhiteNoise.ar(1)}.play;s.prepareForRecord;Routine.run{s.record;wait(99);s.stopRecording}
```
Here's a golfed version with the option to record in either aiff or wav, and specify a sample format (int16, int8, and float are all options). Unfortunately, even with all the bonuses, the version above fares better. This would be 139 - 30% = 97.3 bytes.
```
s.recSampleFormat='int16';s.recHeaderFormat='wav';{WhiteNoise.ar(1)}.play;s.prepareForRecord;Routine.run{s.record;wait(99);s.stopRecording}
```
And here's an ungolfed version of the latter, so you can see what's going on.
```
s.recSampleFormat='int16';
s.recHeaderFormat='wav';
{WhiteNoise.ar(1)}.play;
s.prepareForRecord;
Routine.run{
s.record;
wait(99);
s.stopRecording
}
```
[Answer]
# JavaScript, 167 bytes
**CAUTION: Decrease volume before run. White noise is nasty**
Don't generates file, maybe not what was expected.
*-4 bytes* hack play noise on left channel only
```
c=new AudioContext()
n=c.createScriptProcessor(s=512)
n.connect(c.destination)
n.onaudioprocess=e=>{a=s;while(a--){e.outputBuffer.getChannelData(0)[a]=Math.random()}}
```
[Answer]
# C ~~127~~ 115 bytes
```
#define H htonl
main(c){for(write(1,(int[]){H(779316836),H(24),-1,H(2),H(8000),H(1)},24);;write(1,&c,1))c=rand();}
```
The majority of the code writes the header for a \*.au file. This prints a pseudorandom sound file to standard out.
The sample rate can be adjusted by changing the `8000`.
The duration can be adjusted by hitting `ctrl-c` whenever you want to stop :-)
] |
[Question]
[
**What is Typoglycemia?**
Typoglycemia is a term that refers to the phenomenon where readers are able to understand text even when the letters in the middle of words are jumbled, as long as the first and last letters of each word remain in their correct positions. For example,
>
> Aoccdrnig to a rscheearch at Cmabrigde Uinervtisy, it dseno’t mtaetr
> in waht oerdr the ltteres in a wrod are, the olny iproamtnt tihng is
> taht the frsit and lsat ltteer be in the rghit pclae.
>
>
> The rset can be a taotl mses and you can sitll raed it whotuit a
> pboerlm.
>
>
> Tihs is bcuseae the huamn mnid deos not raed ervey lteter by istlef,
> but the wrod as a wlohe. Azanmig huh? Yaeh, and I awlyas tghuhot
> slpeling was ipmorantt!
>
>
>
However, in this challenge we will implement a minor variation.
**Typo Injection Rules**
For each sentence, errors will be injected into words longer than four letters. All such words will contain exactly one error. All words with four letters or less will contain no errors.
For example, here are the simple rules applied to this sentence:
```
The boy could not solve the problem so he asked for help.
```
| Rule Number | Description | Example |
| --- | --- | --- |
| 0 | Swap the first two letters of the word. | The boy **oc**uld not **os**lve the **rp**oblem so he **sa**ked for help. |
| 1 | Swap the second and third letters of the word. | The boy c**uo**ld not s**lo**ve the p**or**blem so he a**ks**ed for help. |
| 2 | For even-length words, swap the middle two letters.For odd-length words, swap the left-of-middle and middle letters. | The boy c**uo**ld not s**lo**ve the pr**bo**lem so he a**ks**ed for help. |
| 3 | Swap the third- and second-to-last letters of the word. | The boy co**lu**d not so**vl**e the prob**el**m so he as**ek**d for help. |
| 4 | Swap the last two letters of the word. | The boy cou**dl** not sol**ev** the probl**me** so he ask**de** for help. |
# Challenge
Input a sentence and start with rule 0 for the first word, regardless of its length. If a word has `four or fewer` letters, skip modifying it but still advance to the next rule when moving to the next word in the sentence. Cycle through the rules 0-4 for each eligible word and repeat the cycle as necessary until the end of the sentence.
**Input**
A sentence.
**Output**
A sentence with each word modified according to the applicable rule.
# Test Cases
**Input**
>
> The quick brown fox jumps over the lazy dog.
>
>
>
**Output**
>
> The qiuck borwn fox jumsp over the lazy dog.
>
>
>
---
**Input**
>
> According to a researcher at Cambridge University, it doesn't matter
> in what order the letters in a word are, the only important thing is
> that the first and last letter be at the right place. The rest can be
> a total mess and you can still read it without problem. This is
> because the human mind does not read every letter by itself but the
> word as a whole.
>
>
>
**Output**
>
> cAcording to a researcehr at aCmbridge Uinversity, it does'nt mattre
> in what odrer the lettesr in a word are, the only ipmortant tihng is
> that the frist and last lettre be at the rihgt plac.e The rest can be
> a ottal mess and you can tsill read it withuot proble.m This is
> beacuse the humna mind does not read eveyr eltter by iteslf but the
> word as a whoel.
>
>
>
[Answer]
# [Rattle](https://github.com/DRH001/Rattle), ~~181~~171 bytes
```
\ |P3II^s0P3[=#+3g`n[^32g1+s1][32g1>4*1[1g2[0g1<^`g>$<sg1>^`]g2[1g1<^`>g>$<s<g1>^`]g2[2g1<^`g1/2>^`g<$>sg1>^`g1/2<^`]g2[3<<g<$>s>>]g2[4<g<$>s>]]=s1g2+%5s2]>]`g0-[=#+3g`b]`
```
[Try it Online!](https://www.drh001.com/rattle/?flags=&code=%5C%20%7CP3II%5Es0P3%5B%3D%23%2B3g%60n%5B%5E32g1%2Bs1%5D%5B32g1%3E4*1%5B1g2%5B0g1%3C%5E%60g%3E%24%3Csg1%3E%5E%60%5Dg2%5B1g1%3C%5E%60%3Eg%3E%24%3Cs%3Cg1%3E%5E%60%5Dg2%5B2g1%3C%5E%60g1%2F2%3E%5E%60g%3C%24%3Esg1%3E%5E%60g1%2F2%3C%5E%60%5Dg2%5B3%3C%3Cg%3C%24%3Es%3E%3E%5Dg2%5B4%3Cg%3C%24%3Es%3E%5D%5D%3Ds1g2%2B%255s2%5D%3E%5D%60g0-%5B%3D%23%2B3g%60b%5D%60&inputs=According%20to%20a%20researcher%20at%20Cambridge%20University%2C%20it%20doesn%27t%20matter%20in%20what%20order%20the%20letters%20in%20a%20word%20are%2C%20the%20only%20important%20thing%20is%20that%20the%20first%20and%20last%20letter%20be%20at%20the%20right%20place.%20The%20rest%20can%20be%20a%20total%20mess%20and%20you%20can%20still%20read%20it%20without%20problem.%20This%20is%20because%20the%20human%20mind%20does%20not%20read%20every%20letter%20by%20itself%20but%20the%20word%20as%20a%20whole.)
This is not necessarily the shortest this code can get but it's a start.
# Explanation
```
| take input ("\ " adds a space)
P3 move pointer to slot 3 (slots 0,1,2 will be used differently)
I place all characters from input in consecutive memory slots
I^ get length of input
s0 save length of input in slot 0
P3 set the pointer to 3
[...]` loop over each character of the input
```
Inside this main loop, `[^32...]` just increments a counter if the current character is not a space. If the character is a space (`[32...]`), it applies the applicable rule (`[0...]` for rule 0, etc.) then increments the rule counter before resetting the word-length counter.
```
g0[=#+3g`b]`
```
This just reads over each modified character and outputs the final string.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~159~~ ~~156~~ ~~154~~ ~~144~~ 138 bytes
```
def f(t,*R):
for*C,in t.split():s=len(C);g=s>4;i=g*[2,4,s,-4,-2][len(R)%5]//2-1;C[i],C[i+g]=C[i+g],C[i];R+=''.join(C),
return' '.join(R)
```
[Try it online!](https://tio.run/##dZRhb9pADIa/8yusSlNIG1Kt7b6AMqniH6DtU4eqIzHJtZe77OyMZlV/O/MlpbCIRigE@73X9nM5mo4rZ2/3@wK3sJ1ycrmK5xPYOn@5TLQFTqkxmqfxnDKDdrqMF2VG3@8WOisvH26Su4SS2V0yu1k/hPQq/vJtfX19M/u6WD7odSK3q3KdDV/h13qxusqiKH1yOpglE/DIrbcRvMdW8T5XhAQZvE4ALn5UCL9bnT/Dxrudlc5e4KmtGwL3Bz2wpI3620HhyvRi/q7XbdA7f9RTc06fhAr3ee58oW0J7EBJP4TK55WIFcNS1RuvixLhp9ViQJq7BDTLeiQbMdSKWaSCaleJXpwOVTAkKGQU7CQOymPSp5w1Hei6cZ6VZQmF4prkQXEv2GpPDMoW0qs8DFawQXjPe11WDI1ROaYQJpamGXJle43MwcpAjUS9R@faPkesjRGpKsIAOy0734qLdxuDdfCRFuSzwVy1hH2hqq1lYa3FJQwM1vFggMKi@2hMpmFCs4VNOzQ4zEth8soZ7Hcmvz/HGaues1p@cNZ2zDmyA2ePR86FP@VM/nPOTX3grKsxZ6/HnKXGKeeqHDineIaz47OcmcacW3fgnNYnnFV@wtmqTzh3HtAcOSN9xhlNeKPfJnJ4hUbT8iPjCyeALw3mjMWjbLdEA6n@iKViVtM0nHe5VM6tMgdNJn8GR494UBCh57EwG/snsI1@2df/ZG8SGMneoknjteVp5J6jeP8P "Python 3 – Try It Online")
* *-3 bytes* by using a lambda for `g`
* *-2 bytes* by inlining `c`
* *-10 bytes* by removing `g`
* *-6 bytes* by removing the if-statement
---
A function `f` that accepts the sentence as a string and returns the modified sentence as string.
**How does it work?**
Create a empty tuple. At the end, this tuple will be joined to a string and `R`eturned.
Declare a for-loop. Since every iteration adds an element to `R`, the size of `R` equals to the current iteration number, 0-indexed.
The loop says:
* for each word in the `t`ext provided as input, transform it into a list of `C`haracters
* get its `s`ize and check if it's `g`reater than 4
+ if it is, get the current rule number (remainder of the division between the current iteration number and 5), retrieve the factor corresponding to that rule (`[2,4,s,-4,-2]`), integer-divide it by 2 (`//2`), subtract one (`-1`), and set `i` to the result
- for rule 0, it will give \$\lfloor \frac{2}{2} \rfloor\ - 1 = 1-1=0\$ (a.k.a. the first letter)
- for rule 1, it will give \$\lfloor \frac{4}{2} \rfloor - 1 = 2-1=1\$ (a.k.a. the second letter)
- for rule 2, it will give \$\lfloor \frac{s}{2} \rfloor - 1\$ (a.k.a. the left-middle letter)
- for rule 3, it will give \$\lfloor \frac{-4}{2} \rfloor - 1=-2-1=-3\$ (a.k.a. the third-to-last latter)
- for rule 4, it will give \$\lfloor \frac{-2}{2} \rfloor - 1=-1-1=-2\$ (a.k.a. the second-to-last latter)
+ otherwise, set `i` to \$\lfloor \frac{0}{2} \rfloor - 1=0-1=-1\$
* Swap the letter at index `i` with the letter at index `i+g`. The expression `i+g` evaluates to `i+1` if the size of the word is `g`reater than 4 (i.e. the next letter after `i`), otherwise evaluates to `i` (i.e. the same letter as `i`, equivalent to "do nothing")
* Convert the list of `C`haracters to a string again, and add it to `R`
Join the accumulator to a string and return it.
[Answer]
# [Perl 5](https://www.perl.org/) + `-040plF`, 60 bytes
```
@F>4&&s;^.{@{[(@F-2,0,1,0|@F/2-1,@F-3)[$.%5]]}}\K(.)(.);$2$1
```
[Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoiQEY+NCYmczteLntAe1soQEYtMiwwLDEsMHxARi8yLTEsQEYtMylbJC4lNV1dfX1cXEsoLikoLik7JDIkMSIsImFyZ3MiOiItMDQwcGxGIiwiaW5wdXQiOiJBY2NvcmRpbmcgdG8gYSByZXNlYXJjaGVyIGF0IENhbWJyaWRnZSBVbml2ZXJzaXR5LCBpdCBkb2Vzbid0IG1hdHRlciBpbiB3aGF0IG9yZGVyIHRoZSBsZXR0ZXJzIGluIGEgd29yZCBhcmUsIHRoZSBvbmx5IGltcG9ydGFudCB0aGluZyBpcyB0aGF0IHRoZSBmaXJzdCBhbmQgbGFzdCBsZXR0ZXIgYmUgYXQgdGhlIHJpZ2h0IHBsYWNlLiBUaGUgcmVzdCBjYW4gYmUgYSB0b3RhbCBtZXNzIGFuZCB5b3UgY2FuIHN0aWxsIHJlYWQgaXQgd2l0aG91dCBwcm9ibGVtLiBUaGlzIGlzIGJlY2F1c2UgdGhlIGh1bWFuIG1pbmQgZG9lcyBub3QgcmVhZCBldmVyeSBsZXR0ZXIgYnkgaXRzZWxmIGJ1dCB0aGUgd29yZCBhcyBhIHdob2xlLiJ9)
## Explanation
First the flags: `-040` (in combination with the implied `-n` from `-p`) splits input strings on space and runs the code for each, `-p` implies `-n` (which reads input automatically and stores in `$_`) and `-p`rints out `$_` at the end of the script, `-l` strips off the space for processing and adds it back on when `print`ing, and `-F` splits the string so that each char of the input is stored in `@F`.
If `@F` contains more than 4 elements (i.e. the string is longer than 4 chars) run a `s;`ubstituion on `$_` swapping the next two chars after the first `n` (e.g `s/.{n}(.)(.)/$2$1/`), where `n` is defined using an inline array, indexed using `$.` (which is the current "line" of input, which since we're using space to split our "lines" is the, 1-indexed, word we're working on) modulo `5`. The values of `n` are `0` (first two chars), `1` (second and third), `0|@F/2-1` (the middle two, or left-most of middle and middle), `@F-3` (the first two of the last three), `@F-2` (the last two), but the list is shifted by one as we need to account for the 1-indexed count. The `s///`ubstitution is delimited by `;` so that we can use the implied `;` from the `while ($_ = <STDIN>) {`...`;}` produced by `-n`.
[Answer]
# C (gcc), 240 bytes
```
#include <string.h>
a,b,l,r;f(char*s){r=0;char*w=strtok(s," ");while(w){l=strlen(w);if(l>4){a=r==0?0:r==1?1:r==2?l/2:r==3?l-3:l-2;b=r<2?a+1:r==2?l/2-1:r==3?l-2:l-1;w[a]^=w[b];w[b]^=w[a];w[a]^=w[b];}printf("%s ",w);w=strtok(0," ");r=-~r%5;}}
```
[Try it online!](https://tio.run/##TVHRjtMwEHzvV6yCTiSQlLYHL@fLVYhfgKdSpI3jJOYcO9gbQqnKpxPWKXcgRfbIM56dcWTRSjnPL7SVZqwV3Afy2rbr7mGFeZWb3IsmlR36VyE7@3IjFjyVLCP3mIY8gSQTU6eNSqfsbCJhlGUsdJOah7fZGUtflpv95o637X4bt93evNlFcLs3xe2dKXaiKv39bo@v//HF9kmxY8VWTAc8fimnQ3UUcYkQj/@fXgaOTk2a3ARIck7wHHNzjenL4pe/eScul7lHbdPsvIp1IByOZfKxU/Bt1PIRKu8mC437AV/HfgjgvisPxLTBnyeoXbtOcopX3kvpfM3PBeQAwaug0MuO1UjwAfvK67pV8MlqdgiaTjloYgMV7EuCHolYqi1MHevZ6WmMikSIDMLE54Be5QvlrDmB7gfnCS3xURyuAwOkRdBoHwjQ1hyWwdUKKgV/ea/bjmAwKNUaYmUOTSDRLhruQWigVyEsHic3LlwgbQxLsY4FJk2dG9nFu8qoPvpwBP4qJXEMahnUjT1f7DW7xMJgHV0NFL/F6TkYt6GgTAPVeA147Rti884ZtU7EqklDJoaRQpp8tvwbm5QycZl/y8ZgG@Zi@gM)
**How it works?**
Nothing too magical here but the main gist is
* Split the sentence into words. (space delimited)
* Perform an XOR swap of the two characters without using a temporary variable.
---
**Output**
>
> The qiuck borwn fox jumsp over the lazy dog.
>
>
> cAcording to a researcehr at aCmbridge Uinversity, it does'nt mattre
> in what odrer the lettesr in a word are, the only ipmortant tihng is
> that the frist and last lettre be at the rihgt plac.e The rest can be
> a ottal mess and you can tsill read it withuot proble.m This is
> beacuse the humna mind does not read eveyr eltter by iteslf but the
> word as a whoel.
>
>
>
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 118 bytes
```
s|\S+|$p=("..",'.\K..',"."x(($z=length$&)/2-1).'\K..','..(?=.$)','..$')[$i++%5];$z>4?$&=~s;$p;reverse$&=~/./g;er:$&|ge
```
[Try it online!](https://tio.run/##PZBBT8MwDIX/ijWFddW2bCB2YRoT4og4ASfGIW29NlKaVInL6DTx0ylOi5BycPxePvulQW82fR8uh5f5RTS72UTKySKRhycpk8VETr5mM3HeGbQlVWKarm6W16lMRjmRcrbfSZEOpUjSd6Hn86vNx1ac72/3Yrr7DlvRbD1@og8Y7yu5Krfo78T0UmLfP@S584W2JZADBR4DKp9X6EERPKo687ooEd6sjgRN3QI0QeEw2ISgVkRs1RZOFfuZxDeqEAxGIURFwYn7oDwuBslZ04GuG@dJWeJWHK4DF4oGw1H7QKBsAUZxMaIgQ/jTvS4rgsaoHCW8xgayLVd28HAOUgZqDGFgdK4dtEDaGLaqIgY4aapcyxTvMoN15PAKfDLMVRtwGFS1NT@sNVNiYLCORkD8ze5/MU5DAc0RsnZccMwbYvLKGZQ/riHtbOiXzxu5vl73y@YX "Perl 5 – Try It Online")
[Answer]
# [Uiua](https://uiua.org) [SBCS](https://tinyurl.com/Uiua-SBCS-Jan-14), ~~59~~ 57 bytes
```
/$"_ _"≡⊔(□(◌|⍜⊏⇌)>4⧻,⊟+1.(0|1|-1⌊÷2⧻.|¯3|¯2))◿5⇡⧻.⊜□≠@ .
```
[Try it!](https://uiua.org/pad?src=0_8_0__ZiDihpAgLyQiXyBfIuKJoeKKlCjilqEo4peMfOKNnOKKj-KHjCk-NOKnuyziip8rMS4oMHwxfC0x4oyKw7cy4qe7LnzCrzN8wq8yKSnil7814oeh4qe7LuKKnOKWoeKJoEAgLgoKZiAiVGhlIHF1aWNrIGJyb3duIGZveCBqdW1wcyBvdmVyIHRoZSBsYXp5IGRvZy4iCmYgIkFjY29yZGluZyB0byBhIHJlc2VhcmNoZXIgYXQgQ2FtYnJpZGdlIFVuaXZlcnNpdHksIGl0IGRvZXNuJ3QgbWF0dGVyIGluIHdoYXQgb3JkZXIgdGhlIGxldHRlcnMgaW4gYSB3b3JkIGFyZSwgdGhlIG9ubHkgaW1wb3J0YW50IHRoaW5nIGlzIHRoYXQgdGhlIGZpcnN0IGFuZCBsYXN0IGxldHRlciBiZSBhdCB0aGUgcmlnaHQgcGxhY2UuIFRoZSByZXN0IGNhbiBiZSBhIHRvdGFsIG1lc3MgYW5kIHlvdSBjYW4gc3RpbGwgcmVhZCBpdCB3aXRob3V0IHByb2JsZW0uIFRoaXMgaXMgYmVjYXVzZSB0aGUgaHVtYW4gbWluZCBkb2VzIG5vdCByZWFkIGV2ZXJ5IGxldHRlciBieSBpdHNlbGYgYnV0IHRoZSB3b3JkIGFzIGEgd2hvbGUuIgo=)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 39 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
#εDg©4›i1Ý2L®;D<‚®3-D>‚D>)ćDrNè©è®Rǝ]ðý
```
[Try it online.](https://tio.run/##PZC/SsRAEMZfZcBChPPAP51yIKYUC9HSYpLMJQOb3WN3Ykh3ne8gXO81h42NYJMIdj7EvUicTUTYhdn5vv3tfOsCpkzDcPDznhTd9ny//uCTfnN60@0uksv9@qXbnR0nCy2SxdHXc@Jv@9duq3t397157N/6z2G4yjLnc7YFiAMET4HQZyV5QIFrrFLPeUHwYPmJfGBpZ8ACuaNgDwUqFFErW2hK9StJT1ISGIpCiApCo31AT7NRcta0wNXKeUEr2oqPc9ACZTQs2QcBtDkY1GJCQUrwp3suSoGVwYzmcB8bpLYM7ejRHIIGKgphZLSuHrUgbIxaMY8BGpbS1UrxLjVURY6OoCulDOtA40NlXenFipUSA4N1MgFI/6L9H0zTSCCzhLSeBpzyhpi8dIbmvw)
**Explanation:**
```
# # Split the (implicit) input-sentence on spaces
ε # Map over each word:
D # Duplicate the current word
g # Pop the copy, and push its length
© # Store this length in variable `®` (without popping)
4›i # If the length is larger than 4:
1Ý # Push [0,1]
2L # Push [1,2]
®; # Push halve the length
D< # Duplicate it, and decrease it by 1
‚ # Pair the two together: [length/2,length/2-1]
®3- # Push the length-3
D> # Duplicate, and increase it by 1
‚ # Pair the two together: [length-3,length-2]
D # Duplicate the pair
> # Increase both values in the copy by 1: [length-2,length-1]
) # Wrap all values on the stack into a list
ć # Extract the head; push first item and remainder-list separately
D # Duplicate the extracted word
r # Reverse the order from pairList,word,word to word,word,pairList
Nè # Modular index the current map-index into the list of pairs
© # Store this as new variable `®` (without popping)
è # Index into the word to get the pair of characters
® # Push index-pair `®` again
R # Reverse it
ǝ # Insert the characters back into the word at those indices
# (implicit else: use the duplicated unmodified word instead)
] # Close both the if-statement and map
ðý # Join it back together with space delimiter
# (after which the modified sentence is output implicitly as result)
```
`©è®Rǝ` is taken from [my answer for the *Swap Two Values in a List* challenge.](https://codegolf.stackexchange.com/a/236367/52210)
[Answer]
# Ruby, ~~94~~ 93 characters
```
->s{i=0;s.gsub(/\S+/){|w|r=[-1,1,2,w.size/2,-2][(i+=1)%5];w[4]&&(w[r],w[r-1]=w[r-1],w[r]);w}}
```
Sample run:
```
irb(main):003:0> ->s{i=0;s.gsub(/\S+/){|w|r=[-1,1,2,w.size/2,-2][(i+=1)%5];w[4]&&(w[r],w[r-1]=w[r-1],w[r]);w}}['The quick brown fox jumps over the lazy dog.']
=> "The qiuck borwn fox jumsp over the lazy dog."
```
[Try it online!](https://tio.run/##PVDBboMwDP0VX7a2KtBRbaeKSdM@YduJcghgIFJIqtgMsbbfzhyYJkWJ7ff87Bc/lNPcQDbHr3TV2dOJkpaGcns4f@wPu@ttvPksj9MojY7RmJD@wcMxio9FvtX7LN09vBSnMX8uHh@3Y@6LSK44LbL1CVmxO433@3wZmKDJN29V5XytbQvsQIFHQuWrDj0ohnfVl17XLcKX1d/oSfMUgWaoHZI9bxh6xSxcbWHspEGkJOMOwWAAKCAKRqmD8hgtkLNmAt1fnGdlWUphuiYJFC@ERntiULYGoyRYpaBE@MO9bjuGi1EVJvAZCii0StmFI0ZYGeiRaNGY3LBgxNoYoao6OBg1d24QFe9Kg33QkRXklFipgXAZ1A29NPZaVIJjsI5XAZTPmP4XEzdMaBooh3XB1S8F550zmGyK@Rc "Ruby – Try It Online")
[Answer]
# [Bash](https://www.gnu.org/software/bash/) (GNU sed + tr), ~~188~~ 177 bytes
```
tr \ \\n|sed -E '/.{5}/!b
1~5s/../ & /
2~5s/(.)(..)/\1 \2 /
3~5{s/.+/ & /
:1 s/ (.)(..+)(.) /\1 \2 \3/
t1}
4~5s/(..)(.)$/ \1 \2/
5~5s/..$/ & /
s/ (.)(.)(.?) /\2\1\3/'|tr \\n \
```
[Try it online!](https://tio.run/##NY7LDoIwEEX3/YprQgRC7KQoGzeu/AOX3YCg@KJKwRePX8diNZlMMnPP3LlJrPNhqEpIQMqi1VmK2Rou8SbqaJIw0UeaOCdMQSwcB4/7Huc@SQEZmuW8jxqDBBZZCmiCZQLTfPxAOSdWiY4trMcI@A7hKxKL7BvHmvwdTK1Gg1AKc@62Y05ZmKzDsMkz3OrD9oSkVI8CO/XEsb5cNdQ9K1EZ@Ry/X0jV/gM "Bash – Try It Online")
* `rt`anslate wrods to liens and back
* Skip sohrt wodrs immediateyl
* Tag traget charcaters for each rule by frmaing them with psaces
(use loop to move psaces iwnard from both ends for rule #2)
* Finally swap hcaracters
* Otpionally add `|haed -c-1` to kill traliing spcae (+10 hcars)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 48 bytes
```
⪫E⪪S ⭆⟦⁻⊗§⟦¹¦²÷Lι²⁻Lι²⊖Lι⟧κ›Lι⁴⟧⭆ι⎇⊖↔⁻⊗ξλν§ι⁻λξ
```
[Try it online!](https://tio.run/##XZBBa9xADIXv/RUil4xhutCQW05LF8qWBApJTqEH2VZ2RMczRiPvrn@9q/EmbVqwjT3v6Xt67gJKlzEuyw/hpO575uQecHSPY2R1@zRO@qgmHVzj4Qqu7Hn5rqaXB05Tcbs8tZF6t9V96unsXr54uPGwT7rjI/fk7ikdNDi24Ru7L1P/He6oExooqYH@SM1PD78aU78JoZJ8HLpd1b/LsIcnkoQyu4@sbVtynJTcv7uejRCbik4e3hfn992ih3PTrHLt3NwtS7ftsvSWBZoBQaiQ/ToKAqiAX4dWuD8QPHM6khTW2QMr9JnKdVIYUFUIOMEpmD/3QgIaCCKpUpGqIJwsAVDIr1JOcQYehyyKhlAOFs7FNCNUw6twsezUQ0R7qSjLaAnedOFwUBgjdhuCp3pAZuswrR7IqhhhoFJWxpynVdPCMZoV@1rgxBqmbBTJ9t82g3FsBbtawm4qtAaFaUgIAxulFoZkAyuAjjQLULSOAq21sa7xFdrpsuClb6nNQ6a4@bR8Psbf "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
⪫E⪪S ...
```
Split the input on spaces and map over each word separately.
```
⭆⟦⁻⊗§⟦¹¦²÷Lι²⁻Lι²⊖Lι⟧κ›Lι⁴⟧...
```
Get the sum of the positions that need to be swapped. This is twice the upper position minus `1`, except for words that are fewer than five characters long, in which case any even value will do. The upper position is calculated in a similar way to @enzo's Python answer. The resulting value is wrapped in a list and iterated over so that it can be referred to twice in the expression below.
```
⭆ι⎇⊖↔⁻⊗ξλν§ι⁻λξ
```
Map over the characters of the word, swapping the characters at positions `-~x/2` and `~-x/2` (if `x` is odd).
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 212 bytes
```
S`
((.)(.)(...+)|(.+))((¶.)(.)(.)(..+)|(¶.+))?((¶(?=.{5})(.)+)(.)(.)((?<-14>.)+.?)(?(14)^)|(¶.+))?((¶..+)(.)(.)(.)|(¶.+))?((¶...+)(.)(.)|(¶.+))?
$3$2$4$5$7$9$8$10$11$13$16$15$17$18$20$22$21$23$24$26$28$27$29
¶
```
[Try it online!](https://tio.run/##XY/dbtQwEIXv8xRzMQhHLVGd7nZbCYgQFzwAcIvqJLMbg2Mv9qRL@HmtPkBfbBmn3UogWVF0vplz5kRi683xhfpwe/x4C4VSVbm8qjorfyv5lEo93D@JWc@yCAKaTFTzpvq1/pPh2WlINa9f6dVbUaqmVI3Sq/LLv1vZ5uT4P3lGz3qBl1jjCte4wRu8Rn2BWqO@RH2Feo16g/oa6wusa6w11jK8wvoKaxE3WN8UD/cFHI@fBoLvduq@QRviwcM2/ICv05j2EO4oAgt25ucMfdhVRfeuC7G3fgccwECkRCZ2NEQwDOb92Ebb7wg@Wy@7yfJ8DpZlldJLzzAa5khgPRwGmQ99PAUQM6WYiYGDJICJdL6g4N0Mdj@GyEYs2A4SbpMwccgD22iTZPtezpSfbCUZLcETj3bYMeyd6SqCXFaOZuiMX2YgMBsHI6W0eMxhWhgn65yMmj4XOFgepiAuMbSOqlF85AR5LZluSrQEDdPoDYxWXHJh8LKwGNAdzRHISccIrbSRrm4L7fR44GPflJsPgVz1Fw "Retina 0.8.2 – Try It Online") Link includes test cases. This regex is just too ugly to explain, I mean it has 29 capturing groups for goodness sake. So let's move on to the slightly shorter direct [Retina](https://github.com/m-ender/retina/wiki/The-Language) 1 port:
```
S`
#5`(.)(.)(...+)|(.+)
$2$1$3$4
(.)(.)(.)(..+)|(.+)
$1$3$2$4$5
(?=.{5})((.)+)(.)(.)((?<-2>.)+.?)(?(2)^)|(.+)
$1$4$3$5$6
(..+)(.)(.)(.)|(.+)
$1$3$2$4$5
(...+)(.)(.)|(.+)
$1$3$2$4
¶
```
[Try it online!](https://tio.run/##ZY/RbtQwEEXf8xVXIqiJWix12eUJWCEe@ADKa7VOMrsxOPYynnSbAr/VD@iPbccp2wohWZblc@feuUzigr08vq6@bI5fNyherTaVqedjzHn9u9KrKBflZfm2XBYnlOkzzGhRLstVUa0/mF@rP3WlivOTslq/f7P4qB9mXVfralFfvwwudXRVvitmu2fz/33NC/8XFg/3BY7Hq57w043tDzSRDwHbeIvv45D2iDfEEMXe3k3o4s4U7ac2cufCDhJhwZTIcks9wwrs56Fh1@0I31zQ2eRkuoATHaV0FgSDFWGCCzj0qo8dnwJIhBJnYnHQBFimixnF4Ce4/RBZrFqI6zXcJWXqkAVbdkmzQ6dr6iNbaUZD@MvZ9TvB3tvWEHJZXVrQ2jBrEEWsx0ApzR5THGcmyXmvUtvlAgcn/RjVhWPjyQzqoyvoaci2Y6I5qB@HYDE4dcmFEXRgNqAbmhjktSOj0Tba1W/RjE8LPvVNuXkfyZtH "Retina – Try It Online") Link includes test cases. Explanation:
```
S`
¶
```
Split the input string on spaces before processing and finish by joining the words with spaces.
```
#5`
```
Perform each of `5` substitutions in turn. What this does is that after each replacement is made, the next match is performed using the next substitution's regex. This also needs to happen for the short words, which is why the matches all have to include a "default case", plus also they must match the whole word exactly, rather than just the parts of the word being substituted.
```
(.)(.)(...+)|(.+)
$2$1$3$4
```
The 1st, 6th, 11th etc. words have their first two characters exchanged if there are at least three more characters left.
```
(.)(.)(.)(..+)|(.+)
$1$3$2$4$5
```
The 2nd, 7th, 12th etc. words have their second and third characters exchanged if there are at least two more characters left.
```
(?=.{5})((.)+)(.)(.)((?<-2>.)+.?)(?(2)^)|(.+)
$1$4$3$5$6
```
The 3rd, 8th, 13th etc. words have their middle characters exchanged if there are at least five characters in the word. A .NET balancing group is used to ensure that there are at least as many characters after the middle characters as there were before.
```
(..+)(.)(.)(.)|(.+)
$1$3$2$4$5
```
The 4th, 9th, 14th etc. words have their second and third last characters exchanged if they follow at least two characters.
```
(...+)(.)(.)|(.+)
$1$3$2$4
```
The 5th, 10th, 15th etc. words have their last two characters exchanged if they follow at least three characters.
However, Retina 1 can do better than this - you can iterate over every `5`th line starting at the line of your choice using a per-line compound stage with a step limit, like this:
```
S`
,5,%V`^..(?=...)
1,5,%V`(?<=^.)..(?=..)
2,5,%V`(?<=(?=.{5})(.)+)..(?=(?<-1>.)+.?$)(?(1)^)
3,5,%V`(?<=..)..(?=.$)
4,5,%V`(?<=...)..$
¶
```
[Try it online!](https://tio.run/##TU9LbtswFNzrFLNwUBF1CbhNdkmNooseoE2Whinp2WJLke7jUxyl6LV6gF7MeZQTJIAW1My8@TCJj251uqi/bU/ft6iWV8uLu@3G2np9Y6011eqM1Ovrm401z7ipPr7CBflz9dfU1rw/CxT9sPqsv3a9MPW6XpmNqT69XtgXo4WpLt/CBV9U//9VOJ1@9ITffmx/oUl8jNilB/wch3xAuieGKB3c44Qu7W3VfmkTdz7uIQkOTJkct9QznMB9HRr23Z5w66PeZi/TEl70lPK7KBicCBN8xLFXfer4JYBEKHNhHI6aAMe0nKkUwwR/GBKLUwvxvYb7rJw6FMGOfdbs2GlNfRQrzWgIzzz7fi84BNdaQhmrpQWti7MGScQFDJTz7DGlceYk@xBU6roy4OilH5O6cGoC2UF9tIJ@Dbl2zDQH9eMQHQavLmUwoh7MBnRPE4OCbmQ0uka3hh2a8VzwvDeX5X2iYJ8A "Retina – Try It Online") Link includes test cases. Explanation: Here because the step limits on the per-line stages guarantee that the right regex runs on the right lines, we can simply run reVerse stages that match the appropriate characters of each word.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 25 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ḲẈ’_‘:¥ṛṠ5ƭ€2!a@>ʋ4‘œ?"ḲK
```
A monadic Link that accepts a list of characters and yields a list of characters reordered as described by the rules.
**[Try it online!](https://tio.run/##PZAtTwRBDIb/SsFgLicIGAQfQWJBk@5ub6dkPi4zXS7rLigSJAaCweDAoDgkCQj@xd4f2evsEpIRnb7vPO07V2Rt2/fdx3v3ebtePl6ulw8HXy/d6qlbPe//vK1vXne38Pjw925Ple/7o221nvV9f1KWIVbsa5AACJESYSwNRUCBU3RF5KomuPB8TTGxtBNggSpQ8jsCDkXUyh4WRv1K0psYAktZSFlBWGgfMNJkkIK3LbCbhyjoRVt5OCctUAbDjGMSQF@BRS1GFBQEf3rk2gjMLZY0hfPcILWV6AeP5hC04CilgdGGZtCSsLVqxSoHWLCY0CglhsKSyxxdQU9BJTaJhkGmcfrQsVJyYPBBRgDpX7T/i2kaSWRnUDTjgmPelJObYGm6AQ "Jelly – Try It Online")**
### How?
Swapping the \$i^{\text{th}}\$ and \$(i+1)^{\text{th}}\$ characters of a length \$N\$ string gives the \$((N-i)!+1)^{\text{th}}\$ permutation of the string in a list of all permutations of that string ordered by the original characters' indices. The code calculates these indices, forces the values for short words to \$1\$, and then uses the `œ?` atom to calculate the required permutations of each word.
```
ḲẈ’_‘:¥ṛṠ5ƭ€2!a@>ʋ4‘œ?"ḲK - Link: list of characters, Text
Ḳ - {Text} split at spaces
Ẉ - {that} length of each -> Sizes
ʋ4 - last four links as a dyad - f(Sizes, 4):
€ - for each {Size in Sizes}:
5ƭ 2 - apply the last five links in turn - f(Size, 2):
’ - {Size} decrement -> (R0): Size - 1
_ - {Size} subtract {2} -> (R1): Size - 2
¥ - last two links as a dyad - f(Size, 2):
‘ - {Size} increment
: - integer divide by {2} -> (R2): (Size + 1) div 2
ṛ - right argument -> (R3): 2
Ṡ - {Size} sign -> (R4): 1
-> N-i from the description above this code-block
! - {that} factorial (vectorises)
> - {Size} greater than {4}?
@ - with swapped arguments:
a - {isLong} logical AND {the factorial} (vectorises)
-> replaces the factorial with 0 when Size<5
‘ - increment (vectorises) -> WordPermValues
Ḳ - {Text} split at spaces -> Words
" - zip with:
œ? - permutation at index {WordPermValue} of {Word}
K - {that} joined with spaces
```
[Answer]
# [J](http://jsoftware.com/), ~~61~~ 60 bytes
```
;:inv@(A.&.>~[:(<@0 1|:4&<*#!@$1,~2,~>.@-:,~1 2-~/])#&>)&cut
```
[Try it online!](https://tio.run/##dZHNbtswEITvfYppUlh2Iatx0JOSGDYM9NRT0Z6KHihpbTKVSHVJ2VVR@NWdlfwTw3AAERAwnNmdj8@7myRa4ilFhBh3SOWMEyy@ff2ye0iNXc@G82SQTLc/0@Hj7A6T/@nnwePH2/ezD5N4ex9vp8lsnMbbCe7H20@/RreD6WiQN2E3eke5dogC@YBcefIYTvCEWnk/ig7id034Y5r8NzLHG4ul@4vnpvI13JoYQeRS/WtRuFUSYZxiefA0pvOwe/XU/prnMCef544LY1cIDgpMnhTnpBkqQC2qjE2xIvyQvsTehDaGCZJAPopsQKVCYIKx2GgxuIKPgyhIP@4UhY2MgGKKe8nZsoWpK8dBSUQwWqYbL5okdBeWbISMsoWsKz9dlMzICAedjV4F1KXKE0JXmvckbX8HLgRVoiLv@4zWNb0WvClLuaqKrsHGBN04SWGXlZRUkiMryJeRyhtP/SDdVFahMpLSNYYVQx9Aa2oZVEpHRiZtpGu5RNbsF9z39V1z7ag8PdA8vwZbUw97oU6wrbmEbaNoD5v4FTYX57DZvw27qo@wtbmEbfgSdtfpDPZK72FTcgV2cFdh@3AJ2zVH2FVyBjtXZ7DFeB02t6fFOtie3oItTxntXgA "J – Try It Online")
`'The quick brown fox jumps over the lazy dog.'`, eg:
* `&cut` Chop input into boxed words:
```
┌───┬─────┬─────┬───┬─────┬────┬───┬────┬────┐
│The│quick│brown│fox│jumps│over│the│lazy│dog.│
└───┴─────┴─────┴───┴─────┴────┴───┴────┴────┘
```
* `#&>` Lengths of each word:
```
3 5 5 3 5 4 3 4 4
```
* J has an "anagram" primitive `A.`, which associates a single number to every possible permutation of a list. We now notice the following:
+ Swapping the final two elements of any list has anagram number `1`.
+ Swapping the two before that has anagram number `2`.
+ Swapping the "middle two" (with left bias) has number `factorial(ceiling(length/2))`.
+ Swapping indexes `1` and `2` has number `factorial(length-2)`
+ Swapping indexes `0` and `1` has number `factorial(length-1)`
* `1,~2,~>.@-:,~1 2-~/]` This constructs a 5 row matrix where each row represents the transforms described above (without factorial applied yet -- we'll do that momentarily) applied to *every element of the length list*:
```
2 4 4 2 4 3 2 3 3 <-- length - 1
1 3 3 1 3 2 1 2 2 <-- length - 2
2 3 3 2 3 2 2 2 2 <-- ceil(length/2)
2 2 2 2 2 2 2 2 2 <-- 2
1 1 1 1 1 1 1 1 1 <-- 1
```
* `#$` Extend the rows cyclically until the matrix is square:
```
2 4 4 2 4 3 2 3 3
1 3 3 1 3 2 1 2 2
2 3 3 2 3 2 2 2 2
2 2 2 2 2 2 2 2 2
1 1 1 1 1 1 1 1 1
2 4 4 2 4 3 2 3 3
1 3 3 1 3 2 1 2 2
2 3 3 2 3 2 2 2 2
2 2 2 2 2 2 2 2 2
```
* `!@` Take the factorial of each:
```
2 24 24 2 24 6 2 6 6
1 6 6 1 6 2 1 2 2
2 6 6 2 6 2 2 2 2
2 2 2 2 2 2 2 2 2
1 1 1 1 1 1 1 1 1
2 24 24 2 24 6 2 6 6
1 6 6 1 6 2 1 2 2
2 6 6 2 6 2 2 2 2
2 2 2 2 2 2 2 2 2
```
* `4&<*` Zero out any rows where the words have length 4 or less:
```
0 0 0 0 0 0 0 0 0
1 6 6 1 6 2 1 2 2
2 6 6 2 6 2 2 2 2
0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
```
* `<@0 1|:` And take the main diagonal of the above matrix:
```
0 6 6 0 1 0 0 0 0
```
We now have the anagram number we need for each word in the list.
* `A.&.>~` Apply the anagram to each boxed word:
```
┌───┬─────┬─────┬───┬─────┬────┬───┬────┬────┐
│The│qiuck│borwn│fox│jumsp│over│the│lazy│dog.│
└───┴─────┴─────┴───┴─────┴────┴───┴────┴────┘
```
* `;:inv@` Unbox and join with spaces (weirdly `cut` as a monad does not have its natural inverse (join on spaces) defined, otherwise we could save 5 bytes):
```
The qiuck borwn fox jumsp over the lazy dog.
```
[Answer]
# JavaScript (ES6), 106 bytes
```
s=>s.replace(/\S+/g,w=>w[s=++s%5|0,4]?w.slice(0,q=s<2?s:(w.length-2>>2/s)-s%2)+w[q+1]+w[q]+w.slice(q+2):w)
```
[Try it online!](https://tio.run/##XZDBbtQwEIbvPMUoUsVGyWZLBJeKbIV4BODU9jBJJomLY@96JjVBvPsyzrYckCzb8v/7m/nnGV@Qu2BOsne@p8vQXLg5chXoZLGj3eHxW3EYy9gc4wM3RcE3n/7clh@f7mPF1qjhtjw3/Lm@57tdrCy5UaZ9fTzWB873fFPnRXw4Fx@e0qHb66dzUed3Mb903rG3VFk/7oZd9n0iOC@m@wlt8NHB4H/B8zKfGPwLBRCVLf5eofdjleVQQPbosvzdf5QvXedDb9wI4gEhEBOGblIACnzFuQ2mHwl@OKNQNrKWYESZxO69wIwiajUO4qR@Jb1VpiRwUhCivgMGKjfJO7uCmU8@CDrRp1TcsF5QNsNgAgug67V/vVxR0BK86sGMk8A28QrSFLRpgQ7d5tEcghZmYt4Yq182jcVYq1bsU4BoZPKLUoJvLc2Joy3oaqnDhWkrNC2zfpyNUlJgcF6uANJZrP8a0zTCZAdol2uD17yckk9p1FmeX/4C "JavaScript (Node.js) – Try It Online")
### Commented
```
s => // s = input string, re-used as the rule counter
s.replace( // replace in s,
/\S+/g, // looking for 'words' (punctuation included)
w => // for each word w in s:
w[ //
s = ++s % 5 // increment the rule counter,
| 0, // or set it to 0 if it's still NaN'ish
4 // test the 5th character
] ? // if the word contains at least 5 characters:
w.slice( // extract the left part:
0, // from 0
q = // to q - 1, where q is defined as:
s < 2 ? // if s < 2:
s // use s (rules 0 and 1)
: // else:
( w.length // use the word length
- 2 // minus 2 (default value for rule 4)
>> 2 / s // halved and floored if this is rule 2
) - s % 2 // minus 1 if this is rule 3
) + // end of slice()
w[q + 1] + // \__ followed by the characters at q and q+1,
w[q] + // / swapped
w.slice(q + 2) // followed by the right part
: // else:
w // leave w unchanged
) // end of replace()
```
] |
[Question]
[
# Task
Given a list of nodes representing a binary tree of positive integers serialized depth-first, return a list of nodes representing the same tree serialized breadth-first. To represent an absent child, you may use `null`, `0`, `'X'`, `Nothing`, `[]`, or any other value that is distinct from your representation of a node's value, which can be represented by an integer or an integer in a singleton list or other collection.
For example, here is an example tree :
```
1
/ \
/ \
5 3
/ \ / \
# 4 10 2
/ \ / \ / \
4 6 # # # 7
/\ /\ /\
# # # # # #
```
Serialized depth-first, this would be `[1, 5, #, 4, 4, #, #, 6, #, #, 3, 10, #, #, 2, #, 7, #, #]` (here, `#` indicates that a child does not exist). This list was made using a pre-order traversal (add a node's value to the list, serialize its left child or add `#` if it doesn't exist, serialize its right child or add `#` if it doesn't exist).
Serialized breadth-first, this would be `[1, 5, 3, #, 4, 10, 2, 4, 6, #, #, #, 7, #, #, #, #, #, #]` (you may trim as many of the `#`'s at the end as you want, I just wanted to make them explicit). Here, you write the root node's value, then the values of all the nodes on the level below, left to right (with a `#` where a node doesn't exist), then values of the level below, until all the nodes are added to the list.
# Test cases
```
[1] -> [1, #, #] //or [1], whatever you wish
Tree: 1 //or just 1
/ \
# #
([1, #, #] and [1, #] yield the same result as above)
[100, 4, 5, #, #, #, #] -> [100, 4, #, 5, #, #, #]
Tree: 100
/ \
4 #
/ \
5 #
/ \
# #
[10, 5, 2, 2, #, #, 2, #, #, #, 4, 8, 4, #, #, #, 1, #, #] -> [10, 5, 4, 2, #, 8, 1, 2, 2, 4, #, #, #, #, #, #, #, #, #]
Tree: 10
/ \
5 4
/ \ / \
2 # 8 1
/ \ / \ / \
2 2 4 # # #
/\ /\ /\
# # # # # #
[100, #, 4, 5, #, #, #] -> [100, #, 4, 5, #, #, #]
Tree: 100
/ \
# 4
/ \
5 #
/ \
# #
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins!
Brownie points for coming up with a better name for this question
[Answer]
# JavaScript (ES10), ~~90 80~~ 78 bytes
Uses `undefined` for an absent child.
```
a=>(g=d=>(b[d]=b[d]||[]).push(x=a[p++])*x&&[++d,d].map(g))(p=0,b=[])&&b.flat()
```
[Try it online!](https://tio.run/##fU7RCoIwFH33K/YkWy6ZlhXE@gufxh6m28wwHanhg/9uNhkYRXA43HM599xzE0/R5o/SdNu6kWrSdBL0AgsqZ86Y5PRN48g4Ck3fXuFABTNBwNFm8H0WBBJLHt6FgQVC0FCCMzp7fT8LdSU6iKYUUNDXUumyVvLseXlTt02lwqopoIYswiDBIMVgb5FaHNywwyAiTsSWj4vkCH1F/doRYnMTF/LzkFhD7F6kq2FpdlqVmxH9iSLu5uPl9AI "JavaScript (Node.js) – Try It Online")
### Commented
We recursively walk through the input array `a[]`, using the depth-first way. While doing so, we fill the array `b[]` where the values are organized by depth. At the end of the process, we just need to flatten `b[]` to get the final output.
```
a => // a[] = depth-first input
( g = d => // g is a recursive function taking a depth d
(b[d] = b[d] || []) // create b[d] if it doesn't exist
.push( // and push the value ...
x = a[p++] // ... stored in a[] at position p; increment p afterwards
) //
* x && // if this value is defined:
[++d, d].map(g) // do two recursive calls to g with d + 1
)( // initial call to g with:
p = 0, // d = p = 0
b = [] // b[] initialized to an empty array
) //
&& b.flat() // end of call: return a flattened version of b[]
```
[Answer]
# [Haskell](https://www.haskell.org/), 88 bytes
```
(concat=<<).foldr(#)[]
0#a=[[0]]:a
x#(p:q:a)=([x]:p%q):a
(u:p)%(v:q)=(u++v):p%q
p%q=p++q
```
[Try it online!](https://tio.run/##HYtLCsMgGIT3nkIIgV@0xfQJEle9QJYF60LS2obaRPMip681ZZjhY4Z5meH9cC5@TNNiiX3ftCMGi1XBjoyzQxJPOv1zzwr@h13yeSVNkE23W4S6a2szyrIkW9u5ew8ZURrxzEiluNbCoCUDL4IwRIJatPB5IKmFSXiSwyxC6idKZ7IuKFl6SkOM39o68xzi5nqpqh8 "Haskell – Try It Online")
### also 88 bytes
```
(concat=<<).foldr(#)[]
0#a=[[0]]:a
x#(p:q:a)=([x]:zipWith(++)(p++([]<$q))(q++([]<$p))):a
```
[Try it online!](https://tio.run/##LYvLCsIwFAX3/YpAXdxLoqQ@ITQrf6A7hZhFqMYGY5s@FsWPN0aRYQ6zOY0ZHzfv49O4lkgSBtdOBCxRBdsxzrYJntj/dsMK/ot18vAtjZlNt0uEumtrM8myxJXt/HWAHJXOeG6kUlxrYbI5hyB6YVCCmrV4uXByUwOUIgRKQely0SNC/@@AiMLE@K6tN/cxLs/HqvoA "Haskell – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 194 bytes
```
def f(x):
c=x[:1]+[0]*3
for k in x[1:]:
p=-(k<1)or[k,0,0,c];c[1+(c[1]!=0)]=p
if k:c=p
while k<all(c[2:4]):c=c[3]
while c[3]:c=c[3]
q=[c]
for x in q:
if-1!=x:x,*w,_=x;q+=w
print(x)
```
[Try it online!](https://tio.run/##PU7RbsMgDHxOvsJNXqChEzTdJtHyJQhNEQsqAiUkyhb29Rmh62TrdOc72Q4/y30c2m377A0YFDEvCy2i5Ew1kqpjWxZmnMGBHSBKxlXyiyBOyN0YHmfpCE2l1VVL1qAE6iAoViKkmDXguM50vVvfg7t13qfQmV8UTo6WrSr/vJ3/jyYhtXpcjvvlied1J3YQkUdyXMmHiNepEev@zWyHJX2@GdR/dx7ZIXwtCL/MffCd7lFVVwQqWmGMN8kIvBKoCVxy17nfnqQlwOhTnDO@P6T6BQ "Python 3 – Try It Online")
**-24 bytes thanks to Jakque**
**-35 bytes thanks to ovs**
Very bad solution, but it implements the task directly and shouldn't be extremely inefficient at least. It basically deserializes iteratively by just taking each element and storing a current list maintaining `[value, left-child, right-child, parent]` (since Python handles recursive lists perfectly fine), and then re-serializes using a trivial queue method.
Commented and ungolfed version:
```
def f(x): # Accept a list with null values as 0
c = [x[0], 0, 0, 0] # Maintain current list [value, left child, right child, parent], starting at the root
for k in x[1:]: # For each element after the first
p = k and [k, 0, 0, c] or -1 # p is the child - if the value is null, -1, otherwise, another 4-list of the right format
a = c[1] != 0 # a is true if and only if the left child is already taken
c[1] = [p, c[1]][a] # if the left child isn't taken, set the left child, otherwise, leave it
c[2] = [c[2], p][a] # if the left child is taken, set the right child, otherwise, leave it
if k < 1: # if this is a null value
while c[3] and c[2] != 0: # so long as both children are full
c = c[3] # step back up once
else: # if this isn't a null value
c = c[1 + a] # descend to the new child
while c[3]: # as long as this isn't the root
c = c[3] # step up (this just goes to the root)
q = [c] # start a queue with just the root
for x in q: # keep going through the queue
print(x == -1 and -1 or x[0]) # if the current value is -1, output it, otherwise, you get a 4-list, and output the value from it
q += x != -1 and x[1:3] or [] # if the current value is -1, nothing, otherwise, add the left and right children to the queue
```
[Try it online!](https://tio.run/##lVRLc9owED6TX7GBQ@2J6UBI2xlPOfTSW3@BxwfFXmPHwjKyHODX091VeCUkIYx5CFvfY7X7tVtXmma22@VYQBFswhi@8BrBnyzD1oECXXUO1pUroem1hmele@xAdTC5uRlkMIdkk0zSCCb@Sj8C/aeqxtEbst5abJwHTwQzAo2Fg6ysdB6BrRblYdEqfpg4Oqesq5oFKAeuRLDGOFJRGAs1EOwmmcZp/Jm1v/Q4qqwE1LhkFapwaAWwqGznbgaDlnzVoJocknpvLUuBNo6nJ0gtVJ3sE6EwhqqQpRjie1yyiPZEYOh/u6468qkaWcDDWOwbv8c7JitLxQoUKciSaQq3c5i870WJAstsheg1jd7uZRwLyk8pbVHlW3CqxoYYBJ2Or42EKE1UeonhElbzzXkYOhJ0r@6fedWonkmbE7574eNvOtOv8L0mO@uOS2xERzg1/IZp/HEzCB0xcIFOOpwABmvCp6NNZqlUVvTzacR@Z2dAG@7FDh5Jg5dDjQrUrVAQEmPIhAjEOW3nsIVHldXQt3RmGbJk1B3Gn4/mUTKfw2vVnnAKd3ChviPIscuQ3DgjlWxw7YUT/9FvfE1CkO@9/xM5h7F8x/pbHCkFVSEQlKeeRmJhKGJeFDJYSOpW0jvptfklUUHFWfVIwyH5JdBHfZwaG06N1VV2aySZC8Pp40pr@kUpWILPiWEp2oINzOccEdwv9MUMFI7hm@7e598hKCQietf2jtr3rKe3pocFshWfF5Efc//sMWwKa5Z@zlZwNydjtwchnIozCa8kvU4JBxQZPU@tPD8OJsOeDCF3/ctxST12RYAEGFQNiQzC7xZbrTIMhqNhBMPJMAzDXUI8PyIYRfAg10iun/sfswimk/3iXj5/@WX6Hw "Python 3 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~126 110~~ 84 bytes
```
def f(a,d=0,L=[]):L+=[[]];L[d]+=a[:1];a.pop(0)and f(a,d+1)+f(a,d+1);return sum(L,[])
```
[Try it online!](https://tio.run/##hU9LCsMgEN3nFJKVohTNpy0J3sAbiAuJhnZRI2kC7emtTUhIoCXwGIaZ95nx7@HWuTw0nbE8TdNgbAtaqInhlAguFaoE5lIqVQtpFOZaVkzV@uQ7DynSzsxszBBemrq3w9g78BwfUJBoEaJxYl@2gd8YlPj@7gbYQskIJVQh9HtJKQEFASUBdMV/8kTMJszcbKOLNteprhN24LfkFhvZeWnyqKf7nMvRfesh5e6Z8AE "Python 3 – Try It Online")
## How it works:
The main idea is to reconstruct the layers of the graph in `L`. To do that, we will be doing some recursion and store the current depth in `d`.
### Ungolfed and commented version:
```
def f(a, d=0, L=[]): # a is our array, d is the currend depth, L are the layers
L += [[]] # append an empty layer in L to avoid future IndexError
L[d] += a[:1] # add the root of our current tree in the right layer
if a.pop(0) != 0: # Remove the first element of our tree and check if it is a root of a sub tree
f(a, d+1) + # compute the first sub-tree (append the nodes to the layers and remove them)
f(a, d+1) # compute the second sub-tree (same)
return sum(L,[]) # return the flatened list of the layers
```
## Note:
As the program use the variable `L` as a reference, re-use the function after its first call will not return the good result because `L` won't have been reinitialized.
edit : In my previous answer, I cared a lot about the length of the sub-trees to recurse `a` at the right indice but it is no longer the case since we discard the elements of a when we visit them. The consequence of that is that `a` is empty at the end of the function, but who cares in a golf challenge ¯\\_(ツ)\_/¯
[Answer]
# [R](https://www.r-project.org/), ~~118~~ ~~114~~ 113 bytes
```
f=function(x,d=1,G=new.env()){G$g=c(G$g,d)
o=x[-1]
if(sum(o|1)&x)o=f(f(o,d+1,G),d+1,G)
`if`(d<2,x[order(G$g)],o)}
```
[Try it online!](https://tio.run/##XY7BCsIwEETv@YqAIruYSlMUejBe@xGlUGga6cEGqtWA@u0xNq3EwJCwO/uGGaxVQo19c@t0D4ZJwVkh@vaxa/s7ID6L9Vk04F4mkWhhyoRXpFNwHS@gXxw3BrVQoEAzuXUszh@pO1WDPGbMlHqQ7fDNwIppfFsFHOmKJidaujAFDXBGUyf8rf1MZzd1w57Rg9/Gt7ObhgcLOO2ySd7JggwH5QvqFfTw0RO/X7B8uvBxIRYrqB03/68duxWxHw "R – Try It Online")
**The idea**
Traverse the array by reviving the DFS and keeping track of the visited recursion depths; then use the depths to order the array BFS-wise.
**Unrolled code and explanation:**
```
f=function( # function args:
x, # - vector x
d=1, # - current recursion depth d (default=1)
G=new.env() # - a passed-by-reference obj (enviroment)
){
G$g=c(G$g,d) # concat curr.depth to vector of depths
# (the vector is a var. inside the enviroment, initially NULL)
o=x[-1] # remove first element of x storing the result in o
if(sum(o|1)&x){ # if o has elements and the first element of x > 0
o=f(o,d+1,G) # recurse on left branch increasing d and updating o
o=f(o,d+1,G) # recurse on right branch increasing d and updating o
}
if(d<2){ # if d == 1
x[order(G$g)] # use the stored depths to reorder x and return it
}else{ # else
o # return o
}
}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 28 bytes
```
Ḣ;ß},ß}ɗ¥WAƑ?
J×ṠÇAœiⱮJẈż$Ụị
```
[Try it online!](https://tio.run/##y0rNyan8///hjkXWh@fX6gDxyemHloY7Hptoz@V1ePrDnQsOtzsenZz5aOM6r4e7Oo7uUXm4e8nD3d3/j056uHOG9aOGOQq6dgqPGuZaH24HC6lwATnKOkAJXUMgAeRUuh2dFHa4/f9/JSWlaEMdBVMdBWUdBRMwUgYjMxjDWEfB0ADGMQKT5hBuLFAzAA "Jelly – Try It Online")
Uses `-1` for an absent child. This recreates a binary tree of the list indices and then sorts the original list based on the depth and position of the indices.
## Explanation
### Helper link
Takes a list of integers representing a depth-first binary tree and recursively turns it into a representation of that tree using nested lists
```
Ḣ | Head
AƑ? | If non-negative:
¥ | - Then:
; | - Concatenate to:
ß},ß}ɗ | - The results of calling this link recursively using the remainder of the list, pairing the results of each call together
W | - Else: wrap in a list
```
### Main link
```
J | Sequence along list
×Ṡ | Multiplied by the signs of the original list
Ç | Call helper link
A | Absolute
œiⱮJ | Find multi-dimensional indices of each list index
Ẉż$ | Prepend the list lengths (i.e. depth)
Ụ | Indices required for this sort order
ị | Index into original list
```
[Answer]
# [R](https://www.r-project.org/), 80 bytes
```
for(i in x<-scan()){F=c(F,T);T=T+(i>0)*T+!i;while(!T%%2+i)T=T/2};x[order(F[-1])]
```
[Try it online!](https://tio.run/##dU/RasMwDHzfV6iUgrQ4zHbTrZC2j/kCvwU/lCxhhpEUt6OB0m/PUrte3cDgMJZ0dzrZoYFNCs1PW51M12JPcIFjtW@futTDXNXHE5zt/nCo7dB0Fg2YFvpNemMj0aXYVlgwRbnaqgTNjtOrSmYmP3@Z7xpnarGQiaFx@CaveV929rO2WJSp0KSH60uDFQoGKwacQebAHd7DZ8lA8FBI9374kgjmkO6g9AbL4CE8MYtMHqIYelwv/kx0CDP1vtVwn3K/YhXbPLj3KY8JQeh6MpzAo48XraPjR0Q5vLXTZ0G2dgwZDuX/IYo9Tf4cezrVwy8 "R – Try It Online")
Full program, takes leaf nodes as \$0\$. Runs through the input and keeps track of the current depth in the following way:
* Store the current value of depth accumulator `T` (preinitialized to \$1\$) in `F`.
* If the current node is positive, move to the next level (multiply `T` by 2).
* Otherwise increase `T` by 1. If after this addition, `T` is divisible by 2, we've already had two child nodes in this level, and need to keep backing up (divide `T` by 2) until it is no longer divisible.
In other words, we can imagine `T` as a binary number, where each bit represents a level, \$0\$ is its first branch, and \$1\$ is its second branch. Moving to a new level is equivalent to adding another zero bit, and when the number "wraps around" all trailing zeroes are removed. For example, in the demo input:
`[1, 5, #, 4, 4, #, #, 6, #, #, 3, ...]`
```
Input Next depth
1
1 -> 10
5 -> 100
0 -> 101
4 -> 1010
4 -> 10100
0 -> 10101
0 -> 1011
6 -> 10110
0 -> 10111
0 -> 11
3 -> 110
...
```
Finally, return x sorted in the order of `F`.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 31 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ü§!■YΦ─Ä↓Θ½(-²9♂^♀_¡#{Σ├j↨à,lqƒ
```
[Run and debug it](https://staxlang.xyz/#p=811521fe59e8c48e19e9ab282dfd390b5e0c5fad237be4c36a17852c6c719f&i=%5B1,0,0%5D%0A%5B1,+5,+0,+4,+4,+0,+0,+6,+0,+0,+3,+10,+0,+0,+2,+0,+7,+0,+0%5D%0A%5B100,+4,+5,+0,+0,+0,+0%5D%0A&m=2)
null nodes are represented by `0`, and are required in the input in all places applicable.
parses the given traversal into a nested list, and then flattens it into layers. The parsing part is actually much smaller than the portion which prints the layers, somehow.
Golfed a bit with some help from recursive.
## Explanation
```
Gd{c{|4!fsn|-:f:fcwLr$J}Bsn!CGG~2l]+,
| printing || parsing |
Bsn!CGG~2l]+,
B remove first element and push
sn!C if zero, stop recursion
GG do 2 recursive calls
~ move array to input stack
2l]+ create a pair from the recursive calls, prepend previous iteration
, retrieve array from input stack
Gd{c{|4!fsn|-:f:fcwLr$J}
G } run after recursive operation is over
d delete empty list
{ cw run as long as tree isn't empty
c{|4!f copy, get elements at depth 0
sn|- remove those from the original tree
:f:f flatten twice
Lr put all levels in a list
$ flatten
J join with spaces
```
] |
[Question]
[
I've tried this question on two forums and have been told this is the best place for this type of question. I'm trying to print from 0 to 1000 then back to 0 again (and all numbers in-between), printing 1000 only once. Also, each number must be on a separate line using vanilla PHP.
My current code is 60 characters long. Is there a way to do the same thing but in less characters?
### [PHP](https://php.net/), 60 bytes
```
echo implode("<p>",array_merge(range(0,999),range(1000,0)));
```
[Try it online!](https://tio.run/##K8go@G9jXwAkU5Mz8hUycwty8lNSNZRsCuyUdBKLihIr43NTi9JTNYoS84CkgY6lpaWmDoRjaGBgoGOgqalp/d/e7j8A "PHP – Try It Online")
[Answer]
# [PHP](https://php.net/), 38 bytes
```
for(;$i-=1|$x|=$i/1001;)echo~$i,"<p>";
```
[Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNKxVMnVtDWtUKmpsVTL1DQ0MDK01U5Mz8utUMnWUbArslKz//wcA "PHP – Try It Online")
A one-byte improvement by [JoKing](https://codegolf.stackexchange.com/users/76162/jo-king). The idea is that by decrementing `$i` instead of incrementing it, we can save on the minus in the `1|-$x` construction by having `$x` become `-1` instead of `1` as a signal. This is achieved by using `$i/1001`, which is `0` if `$i>-1001` and `-1` otherwise. This would break even if not for the fact we can now use `~$i` instead of `$i-1`.
### [PHP](https://php.net/), 39 bytes
```
for(;$i+=1|-$x|=$i>1e3;)echo$i-1,"<p>";
```
[Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNKxVMrVtDWt0VSpqbFUy7QxTja01U5Mz8lUydQ11lGwK7JSs//8HAA "PHP – Try It Online")
In collaboration with [primo](https://codegolf.stackexchange.com/users/4098/primo) on the code.golf discord.
The idea is to have a signal variable `$x` that is zero until `$i` hits 1000 then is 1 afterwards. We use the bitwise construction `1|-$x` which is a shorter version of `$x ? -1 : 1` to select whether to go upwards or downwards.
[Answer]
# [PHP](https://php.net/), ~~56~~ 49 bytes
*Saved 7 bytes thanks to @Sisyphus and @xnor*
My PHP is rusty, but here is a first attempt.
```
for(;$n<2e3;)echo 1e3-abs(1e3-$n++),'<p>';echo 0;
```
[Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNKxV8myMUo2tNVOTM/IVDFONdROTijVAtEqetramjrpNgZ26NVjSwPr/fwA "PHP – Try It Online")
# 47 bytes
A shorter version suggested by @Neil:
```
echo 0;for(;$n<2e3;)echo'<p>',min(++$n,2e3-$n);
```
[Try it online!](https://tio.run/##K8go@G9jXwAkU5Mz8hUMrNPyizSsVfJsjFKNrTVBYuo2BXbqOrmZeRra2ip5OkBxXZU8Tev//wE "PHP – Try It Online")
# 43 bytes
If the output can end with an extra `<p>`:
```
for(;$n<2001;)echo 1e3-abs(1e3-$n++),'<p>';
```
[Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNKxV8myMDAwMrTVTkzPyFQxTjXUTk4o1QLRKnra2po66TYGduvX//wA "PHP – Try It Online")
[Answer]
# [PHP](https://php.net/), 51 bytes
```
echo join("<p>",[...range(0,999),...range(1e3,0)]);
```
[Try it online!](https://tio.run/##K8go@G9jXwAkU5Mz8hWy8jPzNJRsCuyUdKL19PSKEvPSUzUMdCwtLTV14HzDVGMdA81YTev/9nb/AQ "PHP – Try It Online")
There's already shorter versions, but I just wanted to show the OP how the original code can be shortened with the old alias `join` and the spread operator that is now available in PHP
**Depending on your rules, even shorter:**
**49** bytes with `<?=`
```
<?=join("<p>",[...range(0,999),...range(1e3,0)]);
```
or even **47** with a literal new line, if your output can be wrapped in `<pre><code>`
```
<?=join("
",[...range(0,999),...range(1e3,0)]);
```
] |
[Question]
[
A great Python golfing tip is to [omit needless spaces](https://codegolf.stackexchange.com/a/87181/88546). But if you are like me, you don't always have the time to search for which spaces to remove. If only there was a way to speed up the process...
## Task
Given a *single line* of Python, as input, return/output a new line which omits all needless spaces. The table below shows which spaces are *needless*, and must be removed for *maximum golfage*.
```
| L D S
---+-------
L | s s n
D | n - n
S | n n n
First token is row, second token is column
L: Letter
D: Digit
S: Symbol
s: space
n: no space
-: never happens (except multidigit numbers)
```
## Clarifications
* What is considered a letter, digit, and symbol?
+ Letter: `_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`
+ Digit: `0123456789`
+ Symbol: `!"\#$%&'()*+,-./:;<=>?@[]^`{|}~`
* You can assume that all characters in the input are either a *Letter*, *Digit*, *Symbol*, or *Space*.
* You can assume that there will be no such test case where two digits are separated by *one or more* spaces
* You can assume that all test cases contain valid Python syntax
* You can assume that there will be no leading or trailing spaces.
* Follow the above rules for omitting spaces, regardless of whether omitting them will produce incorrect or different code
## Test Cases
### Input
```
print ( "Hello, World!" )
eval("eval('eval(`1`)')")
_ = '_ = % r ; print _ %% _' ; print _ % _
[ 1for _ in range(10, 6 , -1) ]
print 16
```
### Output
```
print("Hello,World!")
eval("eval('eval(`1`)')")
_='_=%r;print _%%_';print _%_
[1for _ in range(10,6,-1)]
print 16
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins!
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~22~~ 21 bytes
*Saved a byte thanks to a mysterious hint from @Neil :P*
```
(\d|\W) +
$1
(\W)
$1
```
[Try it online!](https://tio.run/##TU5BCsIwELznFWOwJMEK5iIU8e4PerCSBholEJISiif/HrepB/cwOzs7O2x2i4@2FDlMn6FXOLC9ZpBEiZQyZx8XQALgwM2FkFrifcph2nEo5t42SF5RVMQIjVEJcimumAGugNhaA2TgAvxiqWjRkGzEn26q07A79DNlGn1crdnGl5P6tD5wRoujVjXiwbazrvsC "Retina 0.8.2 – Try It Online")
[Answer]
# JavaScript (ES9), ~~60~~ 43 bytes
```
s=>s.replace(/(?<![a-z_] *) | (?=\W)/gi,'')
```
[Try it online!](https://tio.run/##dY/NboMwEITvfooJUmS7ARIuvVBAHCr1DXIAFBxiKJVlIxPl0L9Xp4YcmkaqVzurGWk@yW/iIsbG9sM50OYkpzaZxiQdQysHJRrJtix7WhUieD9UeOD4BMuScs@3Xe9TyqfG6NEoGSrTsZbVg@31GQzei1TK@Ngbq04rD5zIi1DMW5QuWtZRWXPKPU4OQALQ61kDFoiBK8uFaxcd6F3mIlIgao11ttewQneSRTsfj/ARRBzzq2qODWipKSckd/iC7qhPc7cZrWKShw7wLJpXJpCk@LXH2X4Q4PaDbHQEMQPdbHBc2MB3utiWjZzH/1duO38rX06mHw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Java (JDK)](http://jdk.java.net/), 48 bytes
```
s->s.replaceAll("(?<![a-zA-Z_] *) | (?=\\W)","")
```
[Try it online!](https://tio.run/##XVDLbsIwELz7KwZLKDZKLHLhwktcql564oDUEIEbEmRq4sh2kGjLt6cm6amXHe3s7OzjIm8yuZw@O3VtjPW4hFy0XmlRtXXhlanFZE4KLZ3Dm1Q1vgnQtB9aFXBe@gA3o064hhrbeqvqc5ZD2rPjvRR4@fNZDNV4gBUqLDuXrJywZaNlUW60ZpStF6NMJl@b5P2QY8LxA7Ze7vc7TmNKeTfvLbd358urMK0XTTDzumaVkE2j7@w5OZvmnD@VD/Loul4BBvpaam1i7IzVpxEFJ@VNhpF9jPp4TI884pSTA7AEogHGgAXm4ezeKZDjQB2if1ygSIa0Mjak4VFW1ueSpdMYM8RIUv7cHDkZOtLZLw "Java (JDK) – Try It Online")
Port of [Arnauld's JS answer](https://codegolf.stackexchange.com/a/204888/16236).
[Answer]
# perl -p, 24 27 26 bytes
```
s/([_\pL] ) +(?=\w)| /$1/g
```
[Try it online!](https://tio.run/##XYyxCoMwAET3fMU1VJIUxWaoS5GuHbp3UFGhUYSQhCjt0m9vmurWG@64B3dOeX0KYc551dbu1kDgwC9l/RJv5HuZjyE4P5kFHPSqtLYp7tbrx45CEPXsNaers9U72QkmqCAtUAJsiwTwwBnYniJMImrZH4uIVJCD9bFOBnHVm1FxeUxRIEUmBX5qyLaRxce6ZbJmDpn7Ag "Perl 5 – Try It Online")
This replaces any letter or underscore + space combo, which is followed by letter, digit or underscore, by itself, and removes any other space. In effect, it keeps any space which is proceeded by a letter or an underscore, and is followed by a letter, digit or underscore, and removes any other space. The `(?=\w)` is a lookahead, and won't be consumed by the matcher; this makes cases like `_ _ _ _ _` keep all the spaces.
This will not work correctly for input containing characters outside of the ASCII range.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 41 bytes
```
≔ωη≔ωζFθ≡ι ≔ηζ«×ζ№⁺_⭆⁶²⍘κφιι≔ωζ≔× №⁺_α↥ιη
```
[Try it online!](https://tio.run/##ZU/BaoNAFDzXrxg8vYUNND140FObcyHQ5FRKWMyqjxq1u5pASr59@9RKKL0Mb94bZubllXF5a@oQnr3nsqGLRqWy6M6uworWgb4U/IX7vAKxwneUG28RI07xK65m8dEWZqj7VCQPW8dNTzs@WU9XjU07CN3Wg6f4EGu89XIvX01HyZPGixjOG/rUKJRSGiyYLT48jn@bLXSOkDb/Q4zY7LvOurEw8WQ7vniLbiEA78AaGD/EAeAGcKYpLUByeAQ0kEy4moQK@ACisDrXPw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔ωη
```
Set `h` to the empty string. This variable is a space if the last non-space character was a letter.
```
≔ωζ
```
Set `z` to the empty string. This variable is a space if the last character was a space and the last non-space character was a letter.
```
Fθ
```
Loop over the characters of the input.
```
≡ι ≔ηζ«
```
If the current character is a space then copy `h` to `z`, otherwise:
```
×ζ№⁺_⭆⁶²⍘κφι
```
If the current character is a letter or digit then output `z`.
```
ι
```
Output the current character.
```
≔ωζ
```
Set `z` to the empty string.
```
≔× №⁺_α↥ιη
```
Set `h` to a space if the current character is a letter, otherwise set it to the empty string.
[Answer]
# Befunge-93, 285 bytes
```
>~:1+!#@_11g\v>>,>>>>0>11p
v # <> ^
>:" "-#v_ \1` |
v < > 2^
>:"/"`#v_> >^
v <
>:"9"`#v_ \2- |
v < >" ",,^
>:"@"`#v_^
v < > >,1^
>:"Z"`#v_ >\2-|
v < >" ",^
>:"_"-#v_ ^
v <
>:"`"`#v_^
v <
>:"z"`#v_ ^
> ^
```
[Try it online!](https://tio.run/##bZHBasMwDIbvfoq/DiUxc1jVQ6HtJnrcGwy2LHbH0lIISTFbDmPs1TPVZoV11UHCv359Evi12X10@2Yc@XtFN5Ns44j21cBsWWLGREc1IMM57hioFa80dJkNDhV5fIklNVPhVObRd6u9@KLE9dl46ixjB9W8/E8QvLVxfhNd9bUVbClanhKIhXQVFE0u3fv3BH8BP2mfiVYr/K6qx/EYDt07CuiHpm17i8c@tG8TDaOaYdsWOuY8Zk/e5EYb5YB7IE9lCgRgDSSSiFORXH6hiaSeQbs@yPPQyfqwlf8paGaxgEVJJh71Aqg0RYsf "Befunge-93 – Try It Online")
This is a simple statement machine, using a single 3 valued state (written to position `(1,1)`). The state is `1` if the previous character was a letter or underscore, `2` if the previous character was a space, and the last non-space character was a letter or underscore, and `0` otherwise.
The program reads one character at a time, ending the program if there is no more input; the read character is pushed on the stack. We then push the current state on the stack, and swap the two elements on the stack. We go through a bunch of if/then/else statements, to find out what kind of character we have (digit, letter or underscore, space, other symbol). If the current character is a digit, letter or underscore, and the current state is `2`, we print a space. We then print the current character, unless that character is a space. Finally, we push the new state on the stack, which we then store on position `(1,1)`, and we enter the loop again.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 27 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
eþØW,ØD¤
+⁹n⁶¤Tị
Ñ>/ŻçµÑSḊç
```
A full program which accepts a Python formatted string of Python code which prints the result.
**[Try it online!](https://tio.run/##y0rNyan8/z/18L7DM8J1Ds9wObSES/tR4868R43bDi0Jebi7m@vwRDv9o7sPLz@09fDE4Ic7ug4v////v7q6eryCgq2CApRSVVAoUlCwVlAoKMrMK1EACqoCheLV0cRAQurqAA "Jelly – Try It Online")** (Do note that Jelly evaluates its arguments as Python *before* using them.)
### How?
```
eþØW,ØD¤ - Link 1: list of characters, A e.g. "_ 5 ;"
¤ - nilad followed by link(s) as a nilad:
ØW - word characters "A..Za..z0...9_"
ØD - digit characters "0...9"
, - pair ["A..Za..z0...9_, "0...9"]
þ - outer product using:
e - exists in? [[1,0,1,0,0], [0,0,1,0,0]]
+⁹n⁶¤Tị - Link 2: list of integers, X; list of characters, Y
¤ - nilad followed by link(s) as a nilad:
⁹ - chain's right argument, Y
⁶ - the space character
n - not equal? (vectorises)
+ - add (to X)
T - truthy (non-zero) indices
ị - index into (Y)
Ñ>/ŻçµÑSḊç - Main Link: list of characters, S
Ñ - call next Link as a monad -> Link_1(S)
/ - reduce by:
> - is greater than (gives 1s where letters are, 0s elsewhere)
Ż - prepend a zero
ç - call last Link as a dyad -> Link_2(that, S)
µ - start a new monadic Link: (call that R)
Ñ - call next Link as a monad -> Link_1(R)
S - sum (gives 1s at letters, 2s at digits, 0s elsewhere)
Ḋ - dequeue
ç - call last Link as a dyad -> Link_2(that, R)
- implicit print
```
First removes spaces which do not directly follow letters, then removes remaining spaces which are not directly before letters or digits.
[Answer]
# [Python 3](https://docs.python.org/3/), 60 bytes
```
lambda s:re.sub(r' +(?=\W)|(?<![a-zA-Z_]) +','',s)
import re
```
[Try it online!](https://tio.run/##lVFda8IwFH3vr7gGyk0wHescDnSZ7GGwfyDMSq2aukJtSxqH0/nbu6Tp3Afbw0JI7j2553AOqV71c1kMmlRETZ5sl@sE6pGSF/VuSRVCn05ENGVvdHLbmyXB4T54iucM@sgRec28bFuVSoOSjZa1rkEA9RCxUlmhgQJ5lHlecpiWKl/3CDDzxu2AfElyStrT1YtwwZCR80AMRgu6ywdQAGMAp2tA30Ax/sAs1NFnEKalMmhWgEqKjaThJYchcAhCBnbNP0YdPxy2PfPk/lsI2kXoEvwjgDDbV@POnu/HeK4/bf7icsiNxb/cKWtuh9Hu6uZ6hRxcGQ6QeVZJc2m1DllF2//gIPds5Nm89m9SqlnbuGgpkqM@EQjugBxrUxzVrBZCzk/oxrLU0HoCpJP4ynzYV3Kls2IzMlx5Isiadw "Python 3 – Try It Online")
Port of [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s [JavaScript answer](https://codegolf.stackexchange.com/a/204888/9481).
] |
[Question]
[
### Task
Given an array of non-negative numbers, output the largest and smallest possible number that can be formed by joining them.
### Rules
Input,Output can be in any convenient format.
The array may have at most 1 decimal number.
### Examples
```
input:[22,33,44,55.55,33]
output:4433332255.55,55.5522333344
input:[34,900,3,11,9]
output:990034311,113349009
input:[99.93,9,3,39]
output:939399.93,99.933399
input:[45.45,45,45,45]
output:45454545.45,45.45454545
input:[12,21,34,43,45.1]
output:4334211245.1,45.112213443
```
This is **code-golf** so shortest code wins.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~84~~ ~~80~~ ~~78~~ 76 bytes
```
lambda a:[''.join(sorted(a,key=lambda s:'.'in s or s+s)[::i])for i in[-1,1]]
```
[Try it online!](https://tio.run/##VU/BbsMgDL3nK5B2INEyVNtwIFK/JOWQqY3G1pEq5NKvT00IWoaFLT/7PT0/nsvXFHAdz5f1Pvx@XgcxdL2U6nvyoY7TvNyu9dD@3J7nfRw7qaQPIoppFvE9Nn3XedeM3HnhQ/8BLTi3PmYfFjHWvUSUrSTipDUnY5QxGXFN9Sa0Jn6IBd8qYgK1rqo/HUpsezolLn@A1GYNyzBp2iAAJnJvj1xrlaVtP5OpEImjzFIlbo9EbZROrv6l7NvkKHNVgCMd0u2YbG3uNeVV2CXYKQLghuQBIALfTUeRXcM16ws "Python 2 – Try It Online")
-2 bytes, thanks to Arnauld
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes
```
œJΣ'.¡ï}Á2£
```
[Try it online!](https://tio.run/##yy9OTMpM/f//6GSvc4vV9Q4tPLy@9nCj0aHF//9HGxnpGBvrmJjomJrqmZoC2bEA "05AB1E – Try It Online")
or as a [Test Suite](https://tio.run/##yy9OTMpM/W/q5hL6/@hkr3OL1fUOLTy8vvZwo9Ghxf91/kcbGekYG@uYmOiYmuqZmgLZsVzRxiY6lgYGOsY6hoY6lkC@paWepbGOJVDAGMQ1MdUzMdWBIaCAoZGOkaEOUJcJ0CRTPcNYAA)
**Explanation**
```
œ # get permutations of input
J # join each
Σ } # sort by
'.¡ # splitting into [before decimal, after decimal]
ï # and converting each to int
Á # rotate the result right
2£ # and take the first 2 values
```
[Answer]
# JavaScript (ES6), ~~68~~ 66 bytes
```
a=>[1,-1].map(n=>a.sort((a,b)=>[a%1||a]+b<[b%1||b]+a?n:-n).join``)
```
[Try it online!](https://tio.run/##jZDBasMwDIbvewpfBglV3EiyDy5L9yDBUKdrR0tnhybdqe@eKQk7zKdJBkn@pQ@ka/gOw/F@6ccqpo/TdG6m0OxbhAq9/gp9EZt90EO6j0URoCtFC6/4fAa/6d7abk47vwnvcVfFUl/TJR4O5XRMcUi3k76lz@JctETADMaAtdpayX1Zqu1WpcfYP8adMSxGtKpqCUTznzEvGYoNuLoGBkRwXon9QTkR2bCIClHmpXQ5wjntGJwweCVkCBZfWtQSWKocYaw2Fn6fzxHGrj43qSWsnmOQgBBkJSPXsRp9hpEFCJFmaeFITihH4RxUQ62R/j0@/QA "JavaScript (Node.js) – Try It Online")
### How?
We use the following test to compare two values in the input array:
```
[a % 1 || a] + b < [b % 1 || b] + a
```
The expression `x % 1 || x` returns the decimal part of \$x\$ if \$x\$ is a decimal number, or leaves \$x\$ unchanged otherwise.
The expression `[x % 1 || x] + y` coerces the above result to a string and concatenates it with the other value.
If there's a decimal number in the list, it must always be considered as the smallest value. By applying our conversion, a decimal number is turned into a string starting with `"0."`, which is lexicographically ordered before anything else.
*Examples:*
```
a | b | [a%1||a]+b | [b%1||b]+a
----+-----+------------+------------
4 | 5 | "45" | "54"
10 | 11 | "1011" | "1110"
8 | 80 | "880" | "808"
7 | 9.5 | "79.5" | "0.57"
```
[Answer]
# Japt, ~~14~~ 11 bytes
```
á m¬ñn é v2
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=4SBtrPFuIOkgdjI=&input=WzIyLDMzLDQ0LDU1LjU1LDMzXQotUQ==)
1 byte saved thanks to [Luis](https://codegolf.stackexchange.com/a/176002/58974), please `+1` his solution too.
```
á :Permutations
m :Map
¬ : Join
ñ :Sort by
n : Converting each to a number
é :Rotate right
v2 :Remove & return the first 2 elements
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~14 11~~ 10 bytes
```
á m¬ñn gJò
```
[Try it online!](https://tio.run/##y0osKPn///BChdxDaw5vzFNI9zq86f//aEMjHSNDHWMTHRNjHRNTPcNYAA "Japt – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
Œ!VṢ.ị
```
[Try it online!](https://tio.run/##y0rNyan8///oJMWwhzsX6T3c3f3///9oQyMdI0MdYxMdE2MdE1M9w1gA "Jelly – Try It Online")
Explanation:
```
Œ!VṢ.ị Arguments: x
Œ! Permutations of x
V Concatenate the representations of each permutation's elements and evaluate the result as Jelly code
Ṣ Sort
.ị Get element at index 0.5, i.e. elements at indices 0 (last) and 1 (first)
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~56~~ 45 bytes
```
->a{a.permutation.map{|p|p.join.to_f}.minmax}
```
[Try it online!](https://tio.run/##XVDbasMwDH3fVwj2soEmqosfPNh@pIThjQUymsQUB1bafnumOIylkwxH8tE5WD5O76e5fZmfXtM5Uf489lNJpRsH6lM@X/Il09fYDVTGt/ZKfTf06fs6Z2jpIx0OD3sRVEUzDIFC8Lp5hHsYp5Kn8gxm6iGyklBBZLkzu/szUcO426EiM8YGPLYm0Tk1dQ6YXelt3IhjpKgYXa2r9lasnnUCKqh3G7EFsoC/p/kntrDmMgMV1twYsKAw@gLmvxCIm1sDf64wy8JUB6@FfXmdfwA "Ruby – Try It Online")
-11 bytes, thanks Jordan
[Answer]
# Pyth, ~~13~~ 12 bytes
```
hM_BSvsM.p`M
```
Outputs in form `[smallest, largest]`. Try it online [here](https://pyth.herokuapp.com/?code=hM_BSvsM.p%60M&input=%5B22%2C33%2C44%2C55.55%2C33%5D&debug=0), or verify all the test cases at once [here](https://pyth.herokuapp.com/?code=hM_BSvsM.p%60M&test_suite=1&test_suite_input=%5B22%2C33%2C44%2C55.55%2C33%5D%0A%5B34%2C900%2C3%2C11%2C9%5D%0A%5B99.93%2C9%2C3%2C39%5D%0A%5B45.45%2C45%2C45%2C45%5D%0A%5B12%2C21%2C34%2C43%2C45.1%5D&debug=0).
```
hM_BSvsM.p`MQ Implicit: Q=eval(input())
Trailing Q inferred
`MQ Stringify all elements of Q
.p Generate all permutations of the above
sM Concatenate each permutation
v Evaluate each as a number
S Sort them
_B Pair the sorted list with its reverse
hM Take the first element of each, implicit print
```
*Edit: Saved a byte by taking stringification out of the mapping function. Previous version:* `hM_BSmvs`Md.p`
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 41 bytes
```
{.max,.min}o+<<*.permutations.map(*.join)
```
[Try it online!](https://tio.run/##NYzdCoJAFITvfYq9iFAbDu7PCZbsSUTCCwWj3RU1SKJn39YgmIuZb5iZ@vlxjm4Tx0Fc45tc9wK50X/Cqa5LmvrZPdduHYNfUjflJd3D6It4yZZuE0N@uBViCHPWKAWtYQyYiTn5FlmjDWxVQUNK2B1YS1bDJqJ/2TAZxl87kQpKIg1NemOSbfwC "Perl 6 – Try It Online")
Alternatives:
```
{.max,.min}o+<<*.permutations.map:{.join}
{.max,.min}o{[map +*.join,.permutations]}
{.max,.min}o{+<<map *.join,.permutations}
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 10 bytes
```
§,▼▲morṁsP
```
[Try it online](https://tio.run/##ASwA0/9odXNr///CpyzilrzilrJtb3LhuYFzUP///1sxMiwyMSwzNCw0Myw0NS4xXQ "Husk – Try It Online") or [verify all!](https://tio.run/##yygtzv6fqxGcr52graSga6egpFH8qKmxSFPz0Lb/h5brPJq26dG0Pbn5RQ93NhYH/P//P9rISMfYWMfERMfUVM/UFMiO5Yo2NtGxNDDQMdYxNNSxBPItLfUsjXUsgQLGIK6JqZ6JqQ4MAQUMjXSMDHWAukyAJpnqGcYCAA "Husk – Try It Online")
## Explanation
```
§,▼▲m(rṁs)P -- example input: [2,3,1.1]
P -- permutations: [[2,3,1.1],[3,2,1.1],[1.1,3,2],[3,1.1,2],[1.1,2,3],[2,1.1,3]]
m( ) -- map the following
(example with [1.1,2,3])
ṁs -- | show each and join: "1.123"
r -- | read: 1.123
-- : [231.1,321.1,1.132,31.12,1.123,21.13]
§, -- fork and join as tuple
▼ -- | min: 1.123
▲ -- | max: 321.1
-- : (1.123,321.1)
```
] |
[Question]
[
You are fish in a pond that needs to survive by eating other fish. You can only eat fish that are the same size or smaller than yourself. You must create a program that takes a shoal of fish as sorted input. From this you must work out how many fish you can eat and ultimately the size you will grow to.
## Size chart
```
+--------------+--------------+--------------+--------------+
| | Amount extra | Total size 1 | Increase to |
| Current size | needed for | fish | size |
| | next size | | |
+--------------+--------------+--------------+--------------+
| 1 | 4 | 4 | 2 |
+--------------+--------------+--------------+--------------+
| 2 | 8 | 12 | 3 |
+--------------+--------------+--------------+--------------+
| 3 | 12 | 24 | 4 |
+--------------+--------------+--------------+--------------+
| 4 | 16 | 40 | 5 |
+--------------+--------------+--------------+--------------+
| 5 | 20 | 60 | 6 |
+--------------+--------------+--------------+--------------+
| 6 | 24 | 84 | 7 |
+--------------+--------------+--------------+--------------+
```
## Rules
1. Your size starts at 1
2. The shoal input will contain fish integers between 0-9
3. 0 = algae and wont help you feed.
4. The fish integer represents the size of the fish (1-9).
5. You can only eat fish the same size or less than yourself.
6. You can eat the fish in any order you choose to maximize your size.
7. You can only eat each fish once.
8. The bigger fish you eat, the faster you grow. A size 2 fish equals two size 1 fish, size 3 fish equals three size 1 fish, and so on.
9. Your size increments by one each time you reach the amounts below.
Returns an integer of the maximum size you could be
## Examples
```
"11112222" => 3
4 fish size 1 increases to 2, 4 size 2 makes you 3
"111111111111" => 3
4 fish size 1 increases to 2, 8 size 1 makes you 3
```
The shortest code (counting in bytes) to do so in any language in which numbers wins.
[Answer]
# JavaScript (ES6), 44 bytes
Takes input as an array of integers.
```
a=>a.map(x=>s+=(t+=s>=x&&x)>s*-~s*2,t=s=1)|s
```
[Try it online!](https://tio.run/##dcqxCoAgEADQvQ8RtQx0P38kGo6yKCyjk3CIft2CtiDe@mY8kLp92qJaQ@/yABnBYr3gxhNYKoHHEshCYiwJS1JdJE0VgUCLk3IXVgre1T6MfOCNrl7m1QpR/IyPZ@Yb "JavaScript (Node.js) – Try It Online")
### How?
The threshold \$T\_s\$ to reach the size \$s+1\$ is given by:
$$T\_s=2s(s+1)$$
We keep track of our current size in \$s\$ and of what we've eaten so far in \$t\$ (we start with \$t=1\$, so this is actually off by \$1\$).
For each fish \$x\$ in the shoal, assuming it's sorted from smallest to biggest:
* we add \$x\$ to \$t\$ (i.e. we eat the fish) whenever we have \$s\ge x\$
* we increment \$s\$ (i.e. we grow in size) if \$t > T\_s\$
[Answer]
# [Python 2](https://docs.python.org/2/), 60 bytes
```
f=lambda l,n=1,c=1:c>n*~-n*2and f(l,n+1,c+l.count(n)*n)or~-n
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIUcnz9ZQJ9nW0CrZLk@rTjdPyygxL0UhTQMooQ2U0M7RS84vzSvRyNPUytPMLwKq@F9QlAkUSNOINtSBQCMIjNXU5MKQQ4NANf8B "Python 2 – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~40~~ 39 bytes
```
(f:=Floor@s;s=1;s<#||(s+=#/4/f)&/@#;f)&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n26r8V8jzcrWLSc/v8ih2LrY1tC62Ea5pkajWNtWWd9EP01TTd9B2RpI/de05gooyswriVbWtUt3UI4FSlRzcVUb6ijAkREc1eqgymBHtVxctf8B "Wolfram Language (Mathematica) – Try It Online")
## Explanation
```
f:=Floor@s;s=1;
```
Store `floor(s)` in `f`, symbolically. Start with `s=1` (size).
```
... /@#
```
Iterate through each element in input...
```
s<#||(s+=#/4/f)
```
If the element is not greater than `s`, then increment `s` by `<element> / (4 * floor(s))`. The `Or (||)` short-circuits otherwise.
```
f
```
Return `floor(s)`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
J×4ÄfSR$ịx`>JTḢȯ1
```
**[Try it online!](https://tio.run/##y0rNyan8/9/r8HSTwy1pwUEqD3d3VyTYeYU83LHoxHrD////RxvooEJDODSCQ2MwNIFDUzg0w4DmeKAFGrQEwVgA "Jelly – Try It Online")**
An interesting method which could well get beaten by some kind of loop or recursion.
### How?
```
J×4ÄfSR$ịx`>JTḢȯ1 - Link: list A (ascending digits) e.g. [1,1,1,1,1,1,1,2,2,3]
J - range of length [1,2,3,4,5,6,7,8,9,10]
×4 - multiply all by 4 [4,8,12,16,20,24,28,32,36,40]
Ä - cumulative sums [4,12,24,40,60,84,112,144,180,220]
$ - last two links as a monad (of A):
S - sum 14
R - range [1,2,3,4,5,6,7,8,9,10,11,12,13,14]
f - filter keep [4,12]
` - use left argument as right with:
x - repeat elements [1,1,1,1,1,1,1,2,2,2,2,3,3,3]
ị - index into [ 1, 3 ]
- = [1,3]
J - range of length (of A) [1,2,3,4,5,6,7,8,9,10]
> - greater than? [0,1,3,4,5,6,7,8,9,10]
- 1 not greater than 1---^ ^---3 is greater than 2
- (note keeps values of longer - i.e. the 3,4,... here)
T - truthy indices [ 2,3,4,5,6,7,8,9,10]
Ḣ - head 2
1 - literal one 1
ȯ - logical OR 2
- (edge-case handling when the head of an empty list yields 0)
- (note that when the shoal is fully consumed the final size will
- still be less than the length of that shoal, so TḢ will still give
- this size due to >J keeping values of the longer argument.)
```
[Answer]
# [Haskell](https://www.haskell.org/), 46 bytes
```
(!0)
a!b|sum[y|y<-a,y<=b]/2<b*b+b=b|q<-b+1=a!q
```
[Try it online!](https://tio.run/##y0gszk7NyfmfZhvzX0PRQJMrUTGpprg0N7qyptJGN1Gn0sY2KVbfyCZJK0k7yTapptBGN0nb0DZRsfB/bmJmnoKtQkFRZl6JgopCmkK0oQ4EGkFg7P9/yWk5ienF/3WTCwoA "Haskell – Try It Online")
[Answer]
# [Lua](https://www.lua.org), 214 bytes
```
l,f=1,{}for j=1,9 do s,f[j]=(...):gsub(j,0)end::z::a,n=0,l*4 for i=1,l do a=a+i*f[i]end if a>=n then e=l while n>0 do if 0<f[e]and e<=n then n=n-e f[e]=-1+f[e]else e=e-1 end end l=l+1 else print(l)return end goto z
```
[Try it online!](https://tio.run/##TYzbCoMwDIZfJZceqijsZmXxRcSLDlOthDiqMnDs2bt2MFgh5PB/X/kwIbCy2KrX264eljhdYVxhU7ZfBszqus71tB33bFFNTjJqfWptlGCjuLhAklyUOEkGTekK27shguAsmA4F9pkECBmes2MC6ZrExrS52Z4GE1G6/ThBqQjSHau2TJ14o6hT1UL6NRUjl3FLwcM72TPOPe2Hl286rfsKZwih/Xsf "Lua – Try It Online")
Not even near shortest one here but it was fun to figure it out :D
] |
[Question]
[
We all know that a lot of exercises only affect one half of your body, so you have to do them twice, once for each side. Such exercises have two counterparts, one for the left side and one for the right. However, there's no need to execute the two counterparts consecutively, as long as the exercises for both sides are in the same order. You may as well switch between sides in your exercise program, but it wouldn't make sense to start some exercises with one side and some with the other.
## Challenge
An *exercise part* is a list of non-zero integers, where its second half consists of the integers of the first half negated and in the same order, and the signs of the integers on each half are equal. The sign of the first half of an exercise part is its *leading side*.
An *exercise set* is zero or more exercise parts with the same leading side concatenated together.
Given a list of non-zero integers as input, determine if it is an exercise set. The integers aren't necessarily unique. The list's length isn't necessarily even.
Your solution may not use any of the [standard loopholes](https://codegolf.meta.stackexchange.com/q/1061/41024). You may use any two different consistent values for output. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest solution wins.
## Examples
`[-5, -1, -7, -6, -5, 5, 1, 7, 6, 5]` is an example of an exercise part. The first half is `[-5, -1, -7, -6, -5]`, and the last half is `[5, 1, 7, 6, 5]`, which is each integer in the first half negated. Additionally, the first half's integers are all of the same sign. This exercise part's leading side is `-1`.
`[3, 6, 5, -3, -6, -5, 1, 6, 4, 3, -1, -6, -4, -3]` is an example of an exercise set. Its individual exercise parts are `[3, 6, 5, -3, -6, -5]` and `[1, 6, 4, 3, -1, -6, -4, -3]`, and they both have leading side `1`.
`[4, -4, -5, 5]`, despite only consisting of valid exercise parts, isn't an exercise set, since the first part, `[4, -4]`, has leading side `1`, while the second part, `[-5, 5]`, has leading side `-1`.
## Test cases
Valid test cases:
```
[]
[1, -1]
[1, -1, 1, -1]
[-6, 6, -5, -4, -3, 5, 4, 3]
[-1, -5, -8, 1, 5, 8, -7, -6, -5, -3, 7, 6, 5, 3]
[-1, -5, -8, 1, 5, 8, -1, 1]
```
Invalid test cases:
```
[1]
[1, -2]
[1, 2, -3, -1, -2, 3]
[1, 2, 3, -3, -1, -2]
[-1, -5, -8, 1, 5, 8, 7, 6, 5, 3, -7, -6, -5, -3]
[1, 2, 3, 5, 1, 2, 3, 5]
[1, 2, -5, 4, -6, 5, 5, -6]
[1, 2, -1, 3, -2, -3]
[1, -2, 1]
[-1, -1, 1]
[1, -1, 1]
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~69~~ 67 bytes
```
a,b=x=[[],[]];k=0
for n in input():x[n>0]+=n*n,n*k>0;k=n
print a==b
```
[Try it online!](https://tio.run/##fVCxbsMgEJ3DV9xGk4JkcJ1UqciWrl26UQY7IorlCluIqM7Xu4ex66hSK3Hw4O69e0d3C5fWyeHrUn9aePdXuyer4G@4r2xvT0ApHUpWqV5pbZg25qVRGTm3HhzUcXXX8LDe99odMvOo3MYxt2kOGZY50vnaBSiVqgbUIah4sl2A49vr0fvWxyaVt2UzaEO0YMDFfDKYr3zLABcvMJ4wcgYIEeUxKabM80hAhIDvMGYKlu9GgeI/RuxnSBqGfji6RhuTFZlOmbRGukxS6TW/T/zVYLHw2969TjEyJry0TePyJBBJ2yUnkqRcpCIWs48018@Xmm8 "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
ṁṠŒg$+2/FẸ
```
[Try it online!](https://tio.run/##y0rNyan8///hzsaHOxccnZSuom2k7/Zw147/h9sfNa0BIvf//6Ojo2N1uBQUog11FHQNkZg6CkgiumY6CkCkawrEJkBsrKMAZAJZxlB5Q6ikBVgbkAVk6JoDMUwXUIc52AxTkCaQruhoJOuM4EwjiGKwiUZwCyASxshyeGxG2ITuCjTTTMGaoGwUJ0C8pwsxBqTVDEXaEGI22LGxsVyxAA "Jelly – Try It Online")
[Answer]
# Java 8, ~~186~~ ~~183~~ 185 bytes
```
a->{int i=a.length-1,t,j;boolean r=i%2>0,f;if(i<0)return!r;for(f=a[i]<0;i>0;){for(r&=f==(t=a[j=i])<0;j>0&&t>>>31==a[--j]>>>31;);for(t=i-j,i-=2*t;j>=0&j>i;)r&=a[j+t]==-a[j--];}return r;}
```
+2 bytes due to a bug-fix for test cases of size 3 (almost all permutations of `1` and `-1` at the end of my TIO-link).
Can definitely be golfed.. The challenge looks to-the-point, but it's pretty hard to implement. Especially the test case `[4,-4,-5,5]` was annoying to fix.. But it works now. Will golf it down from here.
[Try it online.](https://tio.run/##nVRNU6QwEL37K7KHnQJNj3wMo7UxHL3pRW9THCKChsVghYxb1hS/fbYTxq31orYFFHS6@3W/1wmdelHQ3f/e170aR3altNkdMaaNa2yr6oZde5Oxu2HoG2VYHaFrUzEVC1yf8MF7dMrpml0zwyTbKyh3GMS0VMu@MQ/uEVLueCfeMKzUP7My4a3QbaQvktg2bmvNDyvawUatVBtdXSRCl4mId37JLmQrZeTQ00ldxejsymSxcGVZ5qnEZYCuCoaIA4iTGjquQWbHDmNlsuhKLWIEQogTV0kJ@AFQiWkuzqyY9mKm87y965HOgdXLoO/ZE@oS3TirzUMgP4tyespu7dY9vv4K5s3r6Jqn5bB1y2eMdL2JzLKOTPPH67lJqjiI9mlgtUs5pBMpmtNSYM3XHAoOKw45L/iK54TkNKSeY82Cn3M44zCD5fwMYQsSVuGb/wdRIGbA@DpCHkpi7RkhRRPZBNT1zO8jrIMHJ3mp@rH52iRRctJ0Mkp0Frj4LIqOPi8/ZGbfHqWXPv9/oNQGvP7hTWTsdyD4OWLRNTE39S1npGZXYWMUtDbxooXTzzAxnnTiiQTovxQqBXjPYTqa9n8B)
**Explanation:**
```
a->{ // Method with integer-array parameter and boolean return-type
int i=a.length-1,j, // Index integers (`i` starting at the last index)
t; // Temp integer
boolean r=i%2>0, // Result-boolean, starting at true if the input-list is even
f; // Flag-integer
if(i<0) // If the input was empty (edge case)
return!r; // Return true
for(f=a[i]<0; // Set the flag-boolean to "Is the current item negative?"
i>0;){ // Loop down over the array
for(r&=f==(t=a[j=i])<0;
// Set `s` to the current number
// And verify if the initial flag and `s` have the same sign
j>0 // Loop `j` from `i` down as long as `j` is larger than 0,
&&t>>>31==a[--j]>>>31;);
// and both `s` and the current item have the same sign
// Decreasing `j` by 1 every iteration
for(t=i-j, // Set `t` to `i-j` (amount of same signed adjacent values)
i-=2*t; // Decrease `i` by two times `t`
j>=0 // Loop as long as `j` is larger than or equal to 0,
&j>i;) // and also larger than `i`
r&=a[j+t]==-a[j--];}
// Verify if the pairs at index `j+t` and `j`
// are negatives of each other
return r;} // Return if `r` is still true (if all verifications succeeded)
```
[Answer]
# [R](https://www.r-project.org/), 91 bytes
Inputs a whitespace-separated vector of numbers. Outputs `FALSE` for valid and `TRUE` for invalid.
```
x=scan()
y=x<0
z=rle(y)
"if"(sum(x|1),any(x[y]+x[!y],z$v==rev(z$v),z$l[!0:1]-z$l[!1:0]),F)
```
`rle` gives the run length encoding, in this case of the sequence of positive and negative values.
The *completely and totally unfair empty edge case ;)* adds a whopping 15 bytes.
Many bytes shaved off by @Giuseppe.
Here is a 92 byte version expressed as a function which is better for testing:
[Try it online!](https://tio.run/##fZHdasMwDIXv8xRu6YXMZIiTpR1lvu1LhFyEkLCAl5X8FLvs3VPFTppssIEFnyTOkWy3Y98O/YdVuu56KIBjUIBEJuRKyNaCOCKjIxKKV4oYGSFR7Nty7r05ERGBOFEsIhKcnEXyv2aaynkQVLnuyud661bRQpE3dS7R4unr8bb196x1n9@7/vRKnGbm7Xj/AsKbTMLjtiu9cbQ1nDJ/PTVWQ1P09VcDBq0y7yHeVatLsJzv62oP3fAJ5psunjcWTGqzF5PubIb3w02ptrwBAadMp7vwLDPhSJ7DjOOFj11@vWoL/pORVTyYK/5dp8r4AA "R – Try It Online")
[Answer]
# JavaScript (ES6), 54 bytes
Optimized version, inspired by [Dennis' Python answer](https://codegolf.stackexchange.com/a/165378/58563).
Returns **0** or **1**.
```
a=>a.map(b=p=x=>b[+(x<0)]+=[x*x,p*(p=x)>0])|b[1]==b[0]
```
[Try it online!](https://tio.run/##jVBLDoIwFNx7Cna22hIKgi4sF2m6aBX8BIUAGky8Oz4pxh81Jn3JZDqdN9O9OqtqVe6Kmmqlk4we83XSprxVPFbuQRVI84I3PNZiipqlh@WUi2bSkGKCgMexJ/FVCyY518KT7So/VnmWuFm@QWNRl6d6e5FjPHrlUyQk/qIYcSiz8cSxXdOIOHBoCDODCYgDEFAwJGa9ctEZAgJA5zAPC3g@7wzD3mH03ihVWTVUyJbcH@Z9s6rL4w9nNargVfhvo2eDz3a/9oSdQ4/tsc3vUrPgbhrZtcxE8PvV7Q0 "JavaScript (Babel Node) – Try It Online")
---
# Original version, 74 bytes
```
a=>a.map(x=>b[i^=p*(p=x)<0&&-~(b[i]+=0)]+=[,x*x],b=[p=0,i=0])|b[1]+0==b[0]
```
[Try it online!](https://tio.run/##jVDRboIwFH33K3jSVlvTwlAfvP5I0yWtgmNh0ggaliz7dXZHWaYbXZZwm5PT03PP4dlcTb0/F67h1tis5KfqkHU5dAZ2ZvliHGlhZ1XxCG5OHLR0K6ZT/k6Q0gsQFA/F2nmrmQXlQLAChKZvVkm9EABWCd3tq1NdldmyrI5kpprzpXl61TM6ueVzojT9RUkWcRniWRS65isW4cdTnAechEUIESVjYjkoN70hIgR8jfNlgc/XvWE6OEzuG@WmrMcKhZLH43zsV/V54vGsXpXcCv/b6LvBz3Z/7Ul7hwGHY/u/y/2CT9NVWCt9hHhY3X0A "JavaScript (Babel Node) – Try It Online")
### How?
We store the first halves of all exercise parts in **b[0]** and the second halves in **b[1]**, switching between **b[0]** and **b[1]** each time the sign is changing. Entries are squared to get rid of the sign. We prefix each entry with a comma and suffix each part with a **0**.
There's some extra logic to handle the 'empty input' edge case at basically no cost (see the comment near the end of the source code).
```
a => // given the input array a[]
a.map(x => // for each x in a[]:
b[i ^= // access b[i]:
p * (p = x) // we keep track of the previous entry in p
< 0 && // if p and x have opposite signs:
-~(b[i] += 0) // append a '0' to b[i] and update i: 0 -> 1, 1 -> 0
] += [, x * x], // append a comma followed by x² to b[i]
b = [p = 0, i = 0] // start with p = 0, i = 0 and b = [0, 0]
) | // end of map()
b[1] + 0 // this will append a '0' to b[1] if it was turned into a string
// or let it unchanged if it's still equal to zero (integer),
// which handles the 'empty input' edge case
== b[0] // compare the result with b[0]
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~147~~ ~~130~~ ~~113~~ ~~112~~ 106 bytes
```
from itertools import*
def f(s):l=[map(abs,g)for v,g in groupby(s+[0],0 .__cmp__)];print l[1::2]==l[:-1:2]
```
[Try it online!](https://tio.run/##fY/NDoIwEITvPsUeQVtji6DB8CQNIf4VSYA2pZr49Li0qODBpNt8MJmZrX7am2p530ujGqjs1Vil6g6qRitjl4vLVYIMujCtM9EcdXA8daQMpTLwICVULZRG3fXpGXQrscnJBtZFcW50UYT5QZuqtVALlqY8z7JapJQh9TIQebjAmxGgbIIEJn9oQgAPjXG2OBEBRKRo1Nko7p0NCYHucN4udOxcRuxNbh9X9u3kH@Te4WL5p8UL0VT7U/@t@13lJy12ppFnK/g3Uh8zWJOZzHw2n2UOn8Ob@hc "Python 2 – Try It Online")
---
Saved:
* -27 bytes, thanks to Dennis
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 57 bytes
```
^\b|,\b
$&=
(.)(\d+),(?=\1)
$2_
-|=
.$
$&,
^((\w+,)\2)*$
```
[Try it online!](https://tio.run/##dU@9DsIgEN7vKRjQgD2aQG3r0vgSbqU/Njq4OBgTl747XqGExsSEy33w/YXX/f14Xt1OXMaWdePgejvNaCfg@wZELoW9ZRLFubFaAjcDqLkByDnxCL0Q9pOhtEYeuHNtB61GpnTcyOJVVcjoqJLmSFMgI0ioWEi9MidvIERA1TTRQvLaB5TBERtM2CZIfI5ZFf612BL/mlLyb@s2p/SOFafa8AsVAhZTlTgdIk2KWrDuvg "Retina 0.8.2 – Try It Online") Takes comma-separated input, but link includes header that processes test cases. Explanation:
```
^\b|,\b
$&=
```
Insert a marker before each positive integer.
```
(.)(\d+),(?=\1)
$2_
```
Change the commas between integers of the same sign to underscores.
```
-|=
```
Delete the remaining signs.
```
.$
$&,
```
Append a comma if the input is not empty.
```
^((\w+,)\2)*$
```
Check that the string consists of pairs of runs of the same integers.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~18~~ 14 bytes
```
~c{ḍz{ṅᵈ¹ṡ}ᵛ}ᵛ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/vy65@uGO3qrqhztbH27tOLTz4c6FtQ@3zgbh//@jjXXMdEx14o114s104k11DIFcEx0gzxAsYAKUiQUA "Brachylog – Try It Online")
Saved 4 bytes thanks to @ErikTheOutgolfer.
### Explanation
```
Succeed if and only if:
~c You can deconcatenate the input list…
{ }ᵛ …and verify that for each of the sublists:
ḍ Split it in half
z Zip the elements of each half together
{ }ᵛ Verify that for each couple:
ṅᵈ¹ The first integer is the negation of the second one
ṡ Take the sign of the first one
All signs should be equal in a sublist
All leading signs of the sublists should be equal
```
[Answer]
# [Python 2](https://docs.python.org/2/), 111 bytes
```
x=input()
o=[];p=[]
for a,b in zip(x,x[1:]):
if 0<a*x[0]:
p+=a,-a
if b*a<0:o+=p[::2]+p[1::2];p=[]
print o==x
```
[Try it online!](https://tio.run/##dU9da8QgEHw@f8WSl8uHQkyau2LPXyJSvGuO@hLlSMH2z6erJuQoFFx3dHZm1H/Pn27qlpv7GGVRFEuQdvJfc1kRJ5V@87iRu3uAoVewE/xYXwYaFBe6EgTsHdqLqYNqtSAH30hDmSEHvL7W5tIK10ivhOh041GCPRv6h51mcFKGBTORYTynvMeMIxxr3osxjLcyvqsiC2oUpxDHcqewHdmJAi42YL1g9RQQIuojyVfmNQkQIWBnrE2C4@dkMGTFltDl3uWR5NOtE@m2fyb@S9qd/6Y@@wxJseI9Nv@CZYMoOu0cz5bpdfoX "Python 2 – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 155 bytes
```
b=>eval('i=b.length-1;r=i%2;0>i&&!r;for(f=0>b[i];0<i;){for(r&=f==(s=0>b[j=i]);0<j&&s&0>b[--j]|!s&0<b[j];);t=i-j;for(i-=2*t;0<=j&j>i;)r&=b[j+t]==-b[j--]}r')
```
[Try it online!](https://tio.run/##jZBBboMwEEX3PQVZ1MEpE4EJSSVnuEjkBaSQ2kJQGZRN27PTwaRqVeEqkkf6mvl@821TXIv@bPXbAG33Uo0tjiXm1bVowrXGcttU7WV4hURa1I9CxrlmbGVl3dmwxjgvT1rJ@Kglf59almGNGPZuYlArTkPDWM@mBoBRHyvSRxoqyeWAGoxjaUCxGciMhpmccEQi09OgEIEEgPq0az6eu7bvmmrbdJewDU9JFECiOH9Y6keBbwz7KKADGdWOKo0CkqTSJXNycz47ICkScKD6RtD1gwNmywRfQrHcFzPS7RUeonOlv433Jv9J@vcV/@3JHOGm/bHnX4R5wQTd@73JHEH4V0@z6e/GLw "JavaScript (Node.js) – Try It Online")
---
Inspiration was @KevinCruijssen's answer
Also thanks to him for correcting 2 test cases of mine
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 13 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
Ç¥├W╦╣∩T~≥▌╨c
```
[Run and debug it](https://staxlang.xyz/#p=809dc357cbb9ef547ef2ddd063&i=[]%0A[1,+-1]%0A[1,+-1,+1,+-1]%0A[-6,+6,+-5,+-4,+-3,+5,+4,+3]%0A[-1,+-5,+-8,+1,+5,+8,+-7,+-6,+-5,+-3,+7,+6,+5,+3]%0A[1]%0A[1,+-2]%0A[1,+2,+-3,+-1,+-2,+3]%0A[1,+2,+3,+-3,+-1,+-2]%0A[-1,+-5,+-8,+1,+5,+8,+7,+6,+5,+3,+-7,+-6,+-5,+-3]%0A[1,+2,+3,+5,+1,+2,+3,+5]%0A[1,+2,+-5,+4,+-6,+5,+5,+-6]%0A[1,+2,+-1,+3,+-2,+-3]%0A[1,+-2,+1]&a=1&m=2)
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 48 bytes
```
{0::1⋄0≠+/ר⍵:0⋄(~0∊⊢∨2|⍳∘⍴)2{⍺≡-⍵}/⍵⊂⍨1,2≠/ר⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@/2sDKyvBRd4vBo84F2vqHpx9a8ah3q5UBUESjzuBRR9ejrkWPOlYY1Tzq3fyoY8aj3i2aRtWPenc96lyoC1RYqw8kHnU1PepdYahjBDQCZkLt/0d9Uz39FR61TVAw4HIDUrSyiAtoEdgaN4VD6011gIQhiDAHEWY6EDEgAgoChYACpv8B "APL (Dyalog Classic) – Try It Online")
] |
[Question]
[
## Prologue
After installing an anti-XSS browser extension, Stack Snippets suddenly stopped working all across the Stack Exchange network. I could no longer learn from [Stack Overflow](//stackoverflow.com), see working demos on [User Experience](//ux.stackexchange.com) and, worst of all, could not test JavaScript answers on [Programming Puzzles and Code Golf](//codegolf.stackexchange.com)! Desperately I searched for a remedy, and found a small input box in the settings, in which could place a single regex. I couldn't fit all of the Stack Exchange sites in this one, small box, so I asked for help. This is that question.
## Task
Your task is to create a regular expression that matches all of the Stack Exchange website URLs, without matching any domains not owned by Stack Overflow Inc..
Your regular expression must match all URLs with the following parts:
* `protocol`: this will either be `http://` or `https://`.
* `domain`: this will be an item from this list:
```
stackoverflow.com
www.stackoverflow.com
facebook.stackoverflow.com
serverfault.com
superuser.com
meta.stackexchange.com
webapps.stackexchange.com
nothingtoinstall.com
meta.webapps.stackexchange.com
meta.nothingtoinstall.com
gaming.stackexchange.com
arqade.com
thearqade.com
meta.gaming.stackexchange.com
meta.arqade.com
meta.thearqade.com
webmasters.stackexchange.com
webmaster.stackexchange.com
meta.webmasters.stackexchange.com
meta.webmaster.stackexchange.com
cooking.stackexchange.com
seasonedadvice.com
meta.cooking.stackexchange.com
meta.seasonedadvice.com
gamedev.stackexchange.com
meta.gamedev.stackexchange.com
photo.stackexchange.com
photography.stackexchange.com
photos.stackexchange.com
meta.photo.stackexchange.com
meta.photography.stackexchange.com
meta.photos.stackexchange.com
stats.stackexchange.com
statistics.stackexchange.com
crossvalidated.com
meta.stats.stackexchange.com
meta.statistics.stackexchange.com
math.stackexchange.com
maths.stackexchange.com
mathematics.stackexchange.com
meta.math.stackexchange.com
diy.stackexchange.com
meta.diy.stackexchange.com
meta.superuser.com
meta.serverfault.com
gis.stackexchange.com
meta.gis.stackexchange.com
tex.stackexchange.com
meta.tex.stackexchange.com
askubuntu.com
ubuntu.stackexchange.com
meta.askubuntu.com
meta.ubuntu.stackexchange.com
money.stackexchange.com
basicallymoney.com
www.basicallymoney.com
meta.money.stackexchange.com
english.stackexchange.com
elu.stackexchange.com
meta.english.stackexchange.com
stackapps.com
ux.stackexchange.com
ui.stackexchange.com
meta.ux.stackexchange.com
meta.ui.stackexchange.com
unix.stackexchange.com
linux.stackexchange.com
meta.unix.stackexchange.com
meta.linux.stackexchange.com
wordpress.stackexchange.com
meta.wordpress.stackexchange.com
cstheory.stackexchange.com
meta.cstheory.stackexchange.com
apple.stackexchange.com
askdifferent.com
meta.apple.stackexchange.com
rpg.stackexchange.com
meta.rpg.stackexchange.com
bicycles.stackexchange.com
bicycle.stackexchange.com
cycling.stackexchange.com
bikes.stackexchange.com
meta.bicycles.stackexchange.com
meta.bicycle.stackexchange.com
programmers.stackexchange.com
programmer.stackexchange.com
meta.programmers.stackexchange.com
electronics.stackexchange.com
chiphacker.com
www.chiphacker.com
meta.electronics.stackexchange.com
android.stackexchange.com
meta.android.stackexchange.com
boardgames.stackexchange.com
boardgame.stackexchange.com
meta.boardgames.stackexchange.com
physics.stackexchange.com
meta.physics.stackexchange.com
homebrew.stackexchange.com
homebrewing.stackexchange.com
brewadvice.com
meta.homebrew.stackexchange.com
meta.homebrewing.stackexchange.com
security.stackexchange.com
itsecurity.stackexchange.com
meta.security.stackexchange.com
meta.itsecurity.stackexchange.com
writers.stackexchange.com
writer.stackexchange.com
writing.stackexchange.com
meta.writers.stackexchange.com
video.stackexchange.com
avp.stackexchange.com
meta.video.stackexchange.com
meta.avp.stackexchange.com
graphicdesign.stackexchange.com
graphicsdesign.stackexchange.com
graphicdesigns.stackexchange.com
meta.graphicdesign.stackexchange.com
dba.stackexchange.com
meta.dba.stackexchange.com
scifi.stackexchange.com
sciencefiction.stackexchange.com
fantasy.stackexchange.com
meta.scifi.stackexchange.com
codereview.stackexchange.com
meta.codereview.stackexchange.com
codegolf.stackexchange.com
meta.codegolf.stackexchange.com
quant.stackexchange.com
meta.quant.stackexchange.com
pm.stackexchange.com
meta.pm.stackexchange.com
skeptics.stackexchange.com
skeptic.stackexchange.com
skepticexchange.com
meta.skeptics.stackexchange.com
fitness.stackexchange.com
meta.fitness.stackexchange.com
drupal.stackexchange.com
meta.drupal.stackexchange.com
mechanics.stackexchange.com
garage.stackexchange.com
meta.mechanics.stackexchange.com
meta.garage.stackexchange.com
parenting.stackexchange.com
meta.parenting.stackexchange.com
sharepoint.stackexchange.com
sharepointoverflow.com
www.sharepointoverflow.com
meta.sharepoint.stackexchange.com
music.stackexchange.com
guitars.stackexchange.com
guitar.stackexchange.com
meta.music.stackexchange.com
sqa.stackexchange.com
meta.sqa.stackexchange.com
judaism.stackexchange.com
mi.yodeya.com
yodeya.com
yodeya.stackexchange.com
miyodeya.com
meta.judaism.stackexchange.com
german.stackexchange.com
deutsch.stackexchange.com
meta.german.stackexchange.com
japanese.stackexchange.com
meta.japanese.stackexchange.com
philosophy.stackexchange.com
meta.philosophy.stackexchange.com
gardening.stackexchange.com
landscaping.stackexchange.com
meta.gardening.stackexchange.com
travel.stackexchange.com
meta.travel.stackexchange.com
productivity.stackexchange.com
meta.productivity.stackexchange.com
crypto.stackexchange.com
cryptography.stackexchange.com
meta.crypto.stackexchange.com
meta.cryptography.stackexchange.com
dsp.stackexchange.com
signals.stackexchange.com
meta.dsp.stackexchange.com
french.stackexchange.com
meta.french.stackexchange.com
christianity.stackexchange.com
meta.christianity.stackexchange.com
bitcoin.stackexchange.com
meta.bitcoin.stackexchange.com
linguistics.stackexchange.com
linguist.stackexchange.com
meta.linguistics.stackexchange.com
hermeneutics.stackexchange.com
meta.hermeneutics.stackexchange.com
history.stackexchange.com
meta.history.stackexchange.com
bricks.stackexchange.com
meta.bricks.stackexchange.com
spanish.stackexchange.com
espanol.stackexchange.com
meta.spanish.stackexchange.com
scicomp.stackexchange.com
meta.scicomp.stackexchange.com
movies.stackexchange.com
meta.movies.stackexchange.com
chinese.stackexchange.com
meta.chinese.stackexchange.com
biology.stackexchange.com
meta.biology.stackexchange.com
poker.stackexchange.com
meta.poker.stackexchange.com
mathematica.stackexchange.com
meta.mathematica.stackexchange.com
cogsci.stackexchange.com
meta.cogsci.stackexchange.com
outdoors.stackexchange.com
meta.outdoors.stackexchange.com
martialarts.stackexchange.com
meta.martialarts.stackexchange.com
sports.stackexchange.com
meta.sports.stackexchange.com
academia.stackexchange.com
academics.stackexchange.com
meta.academia.stackexchange.com
cs.stackexchange.com
computerscience.stackexchange.com
meta.cs.stackexchange.com
workplace.stackexchange.com
meta.workplace.stackexchange.com
windowsphone.stackexchange.com
meta.windowsphone.stackexchange.com
chemistry.stackexchange.com
meta.chemistry.stackexchange.com
chess.stackexchange.com
meta.chess.stackexchange.com
raspberrypi.stackexchange.com
meta.raspberrypi.stackexchange.com
russian.stackexchange.com
meta.russian.stackexchange.com
islam.stackexchange.com
meta.islam.stackexchange.com
salesforce.stackexchange.com
meta.salesforce.stackexchange.com
patents.stackexchange.com
askpatents.com
askpatents.stackexchange.com
meta.patents.stackexchange.com
meta.askpatents.com
meta.askpatents.stackexchange.com
genealogy.stackexchange.com
meta.genealogy.stackexchange.com
robotics.stackexchange.com
meta.robotics.stackexchange.com
expressionengine.stackexchange.com
meta.expressionengine.stackexchange.com
politics.stackexchange.com
meta.politics.stackexchange.com
anime.stackexchange.com
meta.anime.stackexchange.com
magento.stackexchange.com
meta.magento.stackexchange.com
ell.stackexchange.com
meta.ell.stackexchange.com
sustainability.stackexchange.com
meta.sustainability.stackexchange.com
tridion.stackexchange.com
meta.tridion.stackexchange.com
reverseengineering.stackexchange.com
meta.reverseengineering.stackexchange.com
networkengineering.stackexchange.com
meta.networkengineering.stackexchange.com
opendata.stackexchange.com
meta.opendata.stackexchange.com
freelancing.stackexchange.com
meta.freelancing.stackexchange.com
blender.stackexchange.com
meta.blender.stackexchange.com
mathoverflow.net
mathoverflow.stackexchange.com
mathoverflow.com
meta.mathoverflow.net
space.stackexchange.com
thefinalfrontier.stackexchange.com
meta.space.stackexchange.com
sound.stackexchange.com
socialsounddesign.com
sounddesign.stackexchange.com
meta.sound.stackexchange.com
astronomy.stackexchange.com
meta.astronomy.stackexchange.com
tor.stackexchange.com
meta.tor.stackexchange.com
pets.stackexchange.com
meta.pets.stackexchange.com
ham.stackexchange.com
meta.ham.stackexchange.com
italian.stackexchange.com
meta.italian.stackexchange.com
pt.stackoverflow.com
br.stackoverflow.com
stackoverflow.com.br
meta.pt.stackoverflow.com
meta.br.stackoverflow.com
aviation.stackexchange.com
meta.aviation.stackexchange.com
ebooks.stackexchange.com
meta.ebooks.stackexchange.com
alcohol.stackexchange.com
beer.stackexchange.com
dranks.stackexchange.com
meta.alcohol.stackexchange.com
meta.beer.stackexchange.com
softwarerecs.stackexchange.com
meta.softwarerecs.stackexchange.com
arduino.stackexchange.com
meta.arduino.stackexchange.com
cs50.stackexchange.com
meta.cs50.stackexchange.com
expatriates.stackexchange.com
expats.stackexchange.com
meta.expatriates.stackexchange.com
matheducators.stackexchange.com
meta.matheducators.stackexchange.com
meta.stackoverflow.com
earthscience.stackexchange.com
meta.earthscience.stackexchange.com
joomla.stackexchange.com
meta.joomla.stackexchange.com
datascience.stackexchange.com
meta.datascience.stackexchange.com
puzzling.stackexchange.com
meta.puzzling.stackexchange.com
craftcms.stackexchange.com
meta.craftcms.stackexchange.com
buddhism.stackexchange.com
meta.buddhism.stackexchange.com
hinduism.stackexchange.com
meta.hinduism.stackexchange.com
communitybuilding.stackexchange.com
moderator.stackexchange.com
moderators.stackexchange.com
meta.communitybuilding.stackexchange.com
meta.moderators.stackexchange.com
startups.stackexchange.com
meta.startups.stackexchange.com
worldbuilding.stackexchange.com
meta.worldbuilding.stackexchange.com
ja.stackoverflow.com
jp.stackoverflow.com
meta.ja.stackoverflow.com
emacs.stackexchange.com
meta.emacs.stackexchange.com
hsm.stackexchange.com
meta.hsm.stackexchange.com
economics.stackexchange.com
meta.economics.stackexchange.com
lifehacks.stackexchange.com
meta.lifehacks.stackexchange.com
engineering.stackexchange.com
meta.engineering.stackexchange.com
coffee.stackexchange.com
meta.coffee.stackexchange.com
vi.stackexchange.com
vim.stackexchange.com
meta.vi.stackexchange.com
musicfans.stackexchange.com
meta.musicfans.stackexchange.com
woodworking.stackexchange.com
meta.woodworking.stackexchange.com
civicrm.stackexchange.com
meta.civicrm.stackexchange.com
health.stackexchange.com
meta.health.stackexchange.com
ru.stackoverflow.com
hashcode.ru
stackoverflow.ru
meta.ru.stackoverflow.com
meta.hashcode.ru
rus.stackexchange.com
russ.hashcode.ru
russ.stackexchange.com
meta.rus.stackexchange.com
mythology.stackexchange.com
meta.mythology.stackexchange.com
law.stackexchange.com
meta.law.stackexchange.com
opensource.stackexchange.com
meta.opensource.stackexchange.com
elementaryos.stackexchange.com
meta.elementaryos.stackexchange.com
portuguese.stackexchange.com
meta.portuguese.stackexchange.com
computergraphics.stackexchange.com
meta.computergraphics.stackexchange.com
hardwarerecs.stackexchange.com
meta.hardwarerecs.stackexchange.com
es.stackoverflow.com
meta.es.stackoverflow.com
3dprinting.stackexchange.com
threedprinting.stackexchange.com
meta.3dprinting.stackexchange.com
ethereum.stackexchange.com
meta.ethereum.stackexchange.com
latin.stackexchange.com
meta.latin.stackexchange.com
languagelearning.stackexchange.com
meta.languagelearning.stackexchange.com
retrocomputing.stackexchange.com
meta.retrocomputing.stackexchange.com
crafts.stackexchange.com
meta.crafts.stackexchange.com
korean.stackexchange.com
meta.korean.stackexchange.com
monero.stackexchange.com
meta.monero.stackexchange.com
ai.stackexchange.com
meta.ai.stackexchange.com
esperanto.stackexchange.com
meta.esperanto.stackexchange.com
sitecore.stackexchange.com
meta.sitecore.stackexchange.com
```
* `page`: this will either be the empty string, `/` or `/` followed by any string
The url will be the string created by appending `protocol`, `domain` and `page` to each other, in that order.
## Testcases
Your regex must match:
```
https://codegolf.stackexchange.com/
http://retrocomputing.stackexchange.com
https://facebook.stackoverflow.com/questions/1234
http://meta.nothingtoinstall.com/thisisa404.php?file=command.com
```
Your regex must not match:
```
http//codegolf.stackexchange.com/
https://meta.stackoverflow.com.fakesite.dodgy/cgi-bin/virus.cgi?vector=apt
file://www.stackoverflow.com/
http://ripoff.com/stackoverflow.com/q/1234/
```
Your regex may match:
```
http://panda.stackexchange.com/
https://www.meta.codegolf.stackexchange.com
http://alpha.beta.charlie.delta.chiphacker.com
https://stackexchange.com/sites/
```
because these are owned by Stack Exchange Inc. and so will not be vulnerable to XSS attacks.
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so the shortest regular expression wins!
[Answer]
# 337 336 333 327 bytes
```
^https?://([^/]+\.)*(stackoverflow\.(com(\.br)?|ru)|mathoverflow\.(com|net)|hashcode\.ru|((the)?arqade|chiphacker|(mi)?yodeya|ask(ubuntu|different|patents)|(seasoned|brew)advice|s(erverfault|(tack|keptic)exchange|uperuser|tackapps|harepointoverflow|ocialsounddesign)|nothingtoinstall|crossvalidated|basicallymoney)\.com)(/.*)?$
```
Doesn't use any fancy regex features, so it should work in any regex flavour.
[Answer]
## ~~359~~ 348 bytes
```
https?:\/\/(([^/]+\.)*((stack(overflow|apps|exchange)|ask(ubuntu|different|patents)|(the)?arqade|serverfault|superuser|nothingtoinstall|(seasoned|brew)advice|crossvalidated|basicallymoney|chiphacker|skepticexchange|(sharepoint|math)overflow|(mi)?yodea|socialsounddesign)\.com)|(stackoverflow(\.com\.br|\.ru)|hashcode\.ru|mathoverflow\.net))(\/.*)?$
```
[Test it out](http://regexr.com/3eaod) on regexr
[Answer]
# 2179 2092 1966 bytes
```
https?:\/\/((((www|facebook|jp|(meta\.?)?(es|ru|ja|pt|br)?)\.)?stackoverflow\.com)|(stackoverflow\.(ru|com\.br))|(((russ|meta)\.)?hashcode\.ru)|(crossvalidated|socialsounddesign|mathoverflow|(mi\.?)?yodeya|(www\.)?(sharepointoverflow|basicallymoney)|skepticexchange|brewadvice|(www\.)?chiphacker|ask(different|ubuntu)|stackapps|(meta\.)?(nothingtoinstall|arqade|thearqade|seasonedadvice|superuser|serverfault|ask(ubuntu|patents)))\.com|((meta\.)?mathoverflow\.net)|(((meta\.)?((3|three)dprinting|(ask)?patents|(community|world)building|(econo|acade)mics|(it)?security|(reverse|network)?engineering|a(cademia|i|lcohol|ndroid|nime|pple|rduino|stronomy|viation|vp)|b((e|lend)er|i(cycles?|kes|ology|tcoin)|oardgames?|ricks|uddhism)|c(h(emistry|ess|inese|ristianity)|ivicrm|o(de(review|golf)|ffee|gsci|mputer(science|graphics)|oking)|r(aftcms|afts|ypto(graphy)?)|s(50)?|stheory)|d(ba|eutsch|iy|ranks|rupal|sp)|(earth|data)science|e(books|l(ectronics|ementaryos|l|u)|macs|nglish|spanol|speranto|thereum|xp(at(s|riates)|ressionengine))|f(antasy|itness|re(elancing|nch))|g(a(medev|ming|rage|rdening)|erman|enealogy|is|raphics?designs?|uitars?)|h(am|ealth|ermeneutics|induism|istory|omebrew(ing)?|sm)|(hard|soft)warerecs|islam|italian|j(apanese|oomla|udaism)|korean|l(a((ndscap|nguagelearn)ing|tin|w)|i(fehacks|nguist(ics)?|nux|))|m(a(gento|rtialarts|th(educators|ematica|ematics|s|overflow)?)|eta|echanics|o(derators?|nero|ney|vies)|usic(fans)?|ythology)|o(pen(data|source)|utdoors)|(cycl|parent|retrocomput)ing|p(ets|h(ilosophy|oto(graphy|s)?|ysics)|m|o(ker|litics|rtuguese)|roductivity|rogrammers?|uzzling)|quant|r(aspberrypi|obotics|pg|us(s|sian)?)|s(alesforce|ci(comp|encefiction|fi)|harepoint|ignals|itecore|keptics?|ound(design)?|p(ace|anish|orts)|qa|tartups|tat(s|istics)|ustainability)|t(ex|hefinalfrontier|or|ravel|ridion)|u(buntu|i|nix|x)|vi(deo|m)?|w(eb(apps|masters?)|indowsphone|o(odworking|rdpress|rkplace)|rit(ers?|ing))|(yodeya)))\.stackexchange\.com))(\/|$)
```
Matches exactly the domains listed and nothing else. I did most of the compressing by hand. I'm a bit embarrassed that I spent this much time on it.
[Answer]
# ~~142~~ ~~140~~ 334 bytes
```
#^https?:\/\/([^\/]*\.)?(hashcode\.ru|mathoverflow\.(com|net)|stackoverflow\.(ru|com(\.br)?)|((stack|skeptic)exchange|stackapps|ask(different|patents|ubuntu)|(brew|seasoned)advice|(the)?arqade|basicallymoney|chiphacker|crossvalidated|nothingtoinstall|serverfault|sharepointoverflow|socialsounddesign|superuser|(mi)?yodeya)\.com)(/|$)#
```
* matches everything on the specified second level domains, path or no path
* uses `#` as delimiter so `/` needs no escaping (saved two bytes)
* compressed manually
] |
[Question]
[
Given a list of integers `L`, and an integer `N`, output `L` splitted in `N` sublists of equal lenghts.
### Non-divisible lengths
If `N` does not divide the length of `L`, then it is not possible that all sublists have equal length.
In any case, the last sublist of the output is the one that adapts its length to contain the remainder of the list.
This means that all sublists of `L` except for the last one should be of length **`length(L) // N`**, where `//` is floored division (e.g. `3//2 = 1`).
### Some rules
* `L` can be empty.
* `N >= 1`.
* You may use any built-in you want.
* You may take the input through `STDIN`, as a function argument, or anything similar.
* You may print the output to `STDOUT`, return it from a function, or anything similar.
* You may chose any format for the lists and the integer as long as it is the most natural representation of lists and integers in your language.
### Test cases
```
Input: [1,2,3,4], 2
Output: [[1,2],[3,4]]
Input: [-1,-2,3,4,-5], 2
Output: [[-1,-2],[3,4,-5]]
Input: [1,2,3,4], 1
Output: [[1,2,3,4]]
Input: [4,8,15,16,23,42], 5
Output: [[4],[8],[15],[16],[23,42]]
Input: [4,8,15,16,23,42], 7
Output: [[],[],[],[],[],[],[4,8,15,16,23,42]]
Input: [2,3,5,7,11,13,17,19,23], 3
Output: [[2,3,5],[7,11,13],[17,19,23]]
Input: [], 3
Output: [[],[],[]]
Input: [1,2,3,4,5,6,7,8], 3
Output: [[1,2],[3,4],[5,6,7,8]]
```
### Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins.
[Answer]
# Pyth, ~~11~~ 10 bytes
1 byte thanks to [@FryAmTheEggman](https://codegolf.stackexchange.com/users/31625/fryamtheeggman).
```
cJEt*R/lJQ
```
[Test suite.](http://pyth.herokuapp.com/?code=cJtE*R%2FlJQ&test_suite=1&test_suite_input=5%0A[1%2C2%2C3%2C4%2C5%2C6%2C7]%0A7%0A[1%2C2%2C3%2C4]%0A3%0A[1%2C2%2C3%2C4%2C5%2C6%2C7%2C8]%0A3%0A[1%2C2%2C3]&debug=0&input_size=2)
Takes inputs in reversed order.
Sample input:
```
5
[1,2,3,4,5,6,7]
```
Sample output:
```
[[1], [2], [3], [4], [5, 6, 7]]
```
### Explanation
```
cJEt*R/lJQ Main function, first input:Q, second input:E.
cJEt*R/lJQQ Implicit arguments.
c The function c is special.
It can chop arrays.
If the second argument is a list of integers,
then it chops the first array at the indices
specified by the second array.
JE The first argument is the second input, stored
to the variable J.
t*R/lJQQ This is the second argument.
/lJQ Yield length of J, integer-divided by Q.
*R Q Multiply it to the following respectively:
[0,1,2,3,...,Q-1]
t Then throw away the first element.
For example, if Q=3 and E=[1,2,3,4,5,6,7,8],
we would now have [3,6].
```
[Answer]
## JavaScript (ES6), 63 bytes
```
(a,n,l=a.length/n|0)=>[...Array(n)].map(_=>--n?a.splice(0,l):a)
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~18~~ 17 bytes
-1 thanks to @coltim
```
{*[!y;(-y)!#x]_x}
```
[Try it online!](https://ngn.codeberg.page/k#eJxtjDEOhDAMBHtesRENhxSJTQhw8JTIouMNoBN/Z4mgu8rj2bW3+ddmdyyNPz6u3m3dz6raMhEQ0VsQe8KXDT4V8YYU95jABA4IUsHSHzfK3RcJI0gwgoKvUouKXFfG81WtQb3J4gWXyiED)
[Answer]
## Python, ~~76~~ 73 bytes
```
lambda L,N:list(map(lambda x,r=len(L)//N:L[x*r:][:r+(x>N-2)*N],range(N)))
```
Basically an unnamed function that performs the task.
Thanks to LeakyNun for the bytes saved!
[Answer]
## Common Lisp, 114 bytes
```
(defun f(l n &optional(p(floor(length l)n))(i 1))(if(= i n)(list l)(cons(subseq l 0 p)(f(subseq l p)n p(+ i 1)))))
```
Ungolfed:
```
(defun f (l n &optional (p (floor (length l) n)) (i 1))
(if (= i n) (list l)
(cons (subseq l 0 p)
(f (subseq l p) n p (+ i 1))))
)
```
Example call:
```
(format t "~A~C~C" (f (read) (read)) #\return #\newline)
```
[Try it here!](https://ideone.com/Ob2FnU)
Basically:
* If we are cutting the last group, return whatever's left of the initial list.
* Otherwise take `p = |L| / N` elements out of the list and join that to the result of a recursive call on the remainder. `i` is an iteration counter used for the stop condition.
I had misunderstood the challenge at first, thinking the program should build groups of `N` elements rather than `N` groups. Anyway, this version does the job for an extra 10 bytes. LisP won't win this time but I couldn't really miss the opportunity :')
[Answer]
## Haskell, ~~69~~ 67 bytes
```
a%b=a#b where l#1=[l];l#n|(h,t)<-splitAt(div(length a)b)l=h:t#(n-1)
```
Usage example: `[1,2,3,4] % 3` -> `[[1],[2],[3,4]]`.
A simple recursive approach, similar to [@xnor's answer](https://codegolf.stackexchange.com/a/82393/34531).
Edit: @Will Ness saved 2 bytes. Thanks!
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 67 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 8.375 bytes
```
L>ßwṘÞ÷RṘ
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyI9IiwiIiwiTD7Dn3fhuZjDnsO3UuG5mCIsIiIsIls0LDgsMTUsMTYsMjMsNDJdXG43Il0=)
Bitstring:
```
0110000000101110001001111010001000011101011000101111111101011010001
```
[Answer]
# [J](http://jsoftware.com/), 34 bytes
```
](],#@;@]<@}.[)<:@[{.-@(<.@%~#)<\]
```
[Try it online!](https://tio.run/##XYzLCsIwEEX3fsVg0SY6HU36UGKUQcGVuHBbQwWxqBs/oJpfr8Eigou5i3PunXvbp7iGpYEYEKZgwiUEm8Nu2zrhMOIFO8svKqU1XDaUsLDEAx9Je3St7O3XBEIk/IxkQ04K9EMyq8bIU6XMyb3@J5@BZdcMaeW1ZVGOb8SJl5NjxA79tzoKtOxdztcHpFCDUKgxxQxzLHCGcwmd08GpkClkP1AprLp2lXd0FmiGc1Q5qgJ1UPr3O47bNw "J – Try It Online")
This was way harder than it should have been, and I threw away two approaches before getting this, which still feels long.
* `(<.@%~#)` Integer divide list size by `n`. This will be the "regular" bucket size (ie, the size of buckets which are not the final, variable bucket).
* `-@...<\]` Break up the list into buckets of those size. This will result in an extra bucket when the list is not evenly divisible.
* `<:@[{.` From that list of buckets, take one less than `n`. This many buckets are guaranteed to be the regular size. Note that if size of the original list is less than `n`, these regular buckets will have size 0.
* `(],#@;@]<@}.[)` To these regular elements append `],` all the remaining elements `#@;@]<@}.[`. That is, if there are `r` regular elements, kill the first `r` elements of the original list and put everything that remains into a single bucket. That is the final bucket which we'll append to the regular buckets. In the case of an evenly divisible list, it will be just one more regular element. Otherwise it will be a final jumbo element.
## [J](http://jsoftware.com/), 34 bytes, K answer port (ish)
```
-@[{.]<;.1~i.@#@]<@e.i.@[*(<.@%~#)
```
[Try it online!](https://tio.run/##VYxPC4JAEEfvfoohidX8OTbrX0xhKegUHbqKeAiluvQBAr/6trCH6DDD8N5jXnbDaqG@JUWgPbVuUqbT7XK2qRk@PHYHlvXJJjRjZ2Z217CLOjbbNYxtHFyPTJIMbZL5ps/WvySY74835bRQJNDIUaBEhRpNTN5p58TtnIofmASTr6fS09rRAg2khFTQTunfb6XsFw "J – Try It Online")
[bstrat's K answer](https://codegolf.stackexchange.com/a/266643/15469) inspired me to revisit an earlier approach of mine, which at a high-level was almost identical.
The difference in length between the J and K answers highlights interesting differences between K's cut primitive (which specifies cut points by indexes) and J's (which requires a boolean array where ones specify cut points). The J approach fares quite poorly in this problem, and requires additional post processing to make the empty cells match the problem specification.
Another approach I tried was using J's "remove the fret points" cut option to get the empty cells correct in a natural way, but doing this requires you to duplicate the fret points just-so, and thus incurs a heavy pre-processing cost.
[Answer]
# [J](https://www.jsoftware.com), 29 bytes
```
-@[{.(I.@(<.@%~+-@[{.|)#)</.]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmuxV9chulpPw1PPQcNGz0G1ThvMr9FU1rTR14uFqLn5QpMrNTkjX8FYIU3BUMEISJsomCqYKZgrWChYKhgaKBgaKhgaKRgaKxiaoKjkgvCMEPoQAvGGCvEQo-JNIaKG6MpMgQImQDsMTRUMzRSMgOJGEAlzXBIge0EGmAKVgBwFdBGQYQlUgpBXV8fpG4h_FyyA0AA)
-2 thanks to Jonah for noticing that `</.` (grouping) followed by `-@[{.` (add enough empty groups) works. Why it works with an empty vector input is a mystery...
---
# [J](https://www.jsoftware.com), 31 bytes
```
]<@#~i.@[=/(I.@(<.@%~+-@[{.|)#)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dZFNTsMwEIXFNqd4Sgqx1WSSSZv-pI5kgVQJCbFgG6IsEBWwYQMr2l6ETVhwCFbcg0NwBpw4ULUoC8v2m2_ePMuvbw_1h0v-CnkGHwFiZGaFhLOri-X789MqnH2WSnvbe9JFHolz0kKRPt4OQ1280Fp60lJfR9-4PCU4KtOFGARKL_SGpAh1i3tSqOugdYrzQpaOhYU4dPNczqOtbsZJQ7v8h_Yn2AeLTC2o4rJcUibWFJxU8ndKx3egcofaUhtq8w56wM4xEnGQldJ0UOvL0uV_-R3p3N7cPWKEFRiJ2cdIMcEUM8zBMZjBCXgEHu-Rjr0lu76dUDEqa1WlVuVDLDXC2MzgFDxBYvTEFqZ9hWZuY5AapAllEpnD3CC7uu_3vsZ-e13b_Qc)
After all sorts of approaches tried and thrown away, I finally settled with the one that creates a boolean matrix and gives the chunks via `#`. Most others suffered badly when the "regular buckets" are empty.
For the input of `3` and `[1 2 3 4 5 6 7 8]`,
```
]<@#~i.@[=/(I.@(<.@%~+-@[{.|)#)
( #) call inner function with 3 and length of array (8):
(<.@%~ ) size of regular bucket (2)
| number of extra elements (2)
-@[{. left-pad with zeros to the length of 3; [0 0 2]
+ elementwise add; [2 2 4]
I.@ copy each index by the element; [0 0 1 1 2 2 2 2]
i.@[ range of 3; [0 1 2]
=/ outer product by equality;
[[1 1 0 0 0 0 0 0]
[0 0 1 1 0 0 0 0]
[0 0 0 0 1 1 1 1]]
]<@#~ for each row of the above, keep places corresponding to 1s;
{[1 2] [3 4] [5 6 7 8]}
```
If I don't need to handle the cases where empty buckets are present, `i.@[=/` can be golfed to `=@`.
[Answer]
## PowerShell v2+, 125 bytes
```
param($l,$n)if($p=[math]::Floor(($c=$l.count)/$n)){1..$n|%{$l[(($_-1)*$p)..((($_*$p-1),$c)[!($_-$n)])]}}else{(,''*($n-1))+$l}
```
Feels too long, but I can't seem to come up with a way to get the slicing to work happily if there are empty arrays in the output, so I need the encapsulating `if`/`else` to handle those cases. Additionally, since PowerShell's default `.ToString()` for arrays via console output can look a little weird, you can tack on a `-join','` to show the arrays as comma-separated rather than newline-separated on the console. I've done that in the examples below to make the output more clear, but you won't want to do that if you're leaving the output on the pipeline for another command to pick up.
### Explanation
Takes input `param($l,$n)` for the list and number of partitions, respectively. We then enter an `if`/`else` statement. If the size of each partition, `$p` is non-zero (setting helper `$c` to be the `.count` along the way), we're in the `if`.
Inside the `if`, we loop from `1` to `$n` with `|%{...}`, and each iteration we're doing a pretty complex-looking array slice `$l[(($_-1)*$p)..((($_*$p-1),$c)[!($_-$n)])]`. The first parens is our start index, based on what partition we're on and how big our partition size is. We range that `..` with our end index, which is formed from a [pseudo-ternary](https://codegolf.stackexchange.com/a/79895/42963). Here, we're choosing between either `$c` (the literal end of the array), or the length of our partition, based on whether we're in the last chunk `$_-$n` or not.
Otherwise, we're in the `else`. We construct an empty array with the comma-operator `,''*` equal to one fewer partitions than requested, and then tack on the input array as the final element.
### Examples
Here I'm showing the partitions separated with newlines and each individual element separated with `,`, as described above.
```
PS C:\Tools\Scripts\golfing> .\n-chotomize-a-list.ps1 (1,2,3,4) 2
1,2
3,4
PS C:\Tools\Scripts\golfing> .\n-chotomize-a-list.ps1 (-1,-2,3,4,-5) 2
-1,-2
3,4,-5
PS C:\Tools\Scripts\golfing> .\n-chotomize-a-list.ps1 (1,2,3,4) 1
1,2,3,4
PS C:\Tools\Scripts\golfing> .\n-chotomize-a-list.ps1 (4,8,15,16,23,42) 5
4
8
15
16
23,42
PS C:\Tools\Scripts\golfing> .\n-chotomize-a-list.ps1 (4,8,15,16,23,42) 7
4,8,15,16,23,42
PS C:\Tools\Scripts\golfing> .\n-chotomize-a-list.ps1 (2,3,5,7,11,13,17,19,23) 3
2,3,5
7,11,13
17,19,23
PS C:\Tools\Scripts\golfing> .\n-chotomize-a-list.ps1 $null 3
PS C:\Tools\Scripts\golfing>
```
[Answer]
## F#, ~~100~~ 98 bytes
```
fun n l->
let a=List.length l/n
List.init n (fun i->if i<n-1 then l.[a*i..a*i+a-1] else l.[a*i..])
```
Using F# list slicing, with an if clause deciding whether to pick *a* elements or all remaining elements.
[Answer]
## Prolog, ~~100~~ 99 bytes.
```
n(A,B):-length(B,A).
p(L,K,G):-n(K,G),append(A,[_],G),n(N,L),M is N//K,maplist(n(M),A),append(G,L).
```
Call e.g.
>
> ?- p( [1,2,3,4,5,6,7], 3, X).
>
> X = [[1, 2], [3, 4], [5, 6, 7]] **.**
>
>
>
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 56 bytes
```
f=(a,n,l=a.length/n|0)=>[a,...--n?f(a.splice(l),n,l):[]]
```
[Try it online!](https://tio.run/##jcqxDsIgEADQ3a9whOQ4BVs1JuiHEAaCtLa5HI00Tv474urk/N4cXqHE57SsivM91TpYEYCBbEBKPK6PHb/30l5dAERUim@DCFgWmmISJL9VXpz3NWYumRJSHsUgnAYDB@g8bI2Umx/s4Ay6B30E045pqf8nnVqqHw "JavaScript (Node.js) – Try It Online")
[Answer]
# PHP, 109 Bytes
```
<?for($n=(count($a=$_GET[0]))/($d=$_GET[1])^0;$i<$d;)$r[]=array_slice($a,$i*$n,++$i==$d?NULL:$n);print_r($r);
```
[All Testcases](http://sandbox.onlinephpfunctions.com/code/c7b9461b19c199cf999319a71374690a2230b45d)
] |
[Question]
[
### Introduction
For the ones who never heard of this game before. You are playing a ball which needs to survive as long as possible. This is done by moving to the left or right, going to the holes. Since the map moves upwards, you need to go downwards to survive longer. If you [search](https://www.google.nl/search?tbm=isch&q=falling+ball+game&cad=h) for images, you probably know which game I mean.
### The Task
Given a positive integer *n*, output a falling ball map of *n* layers. Between the layers, there are 4 newlines. The width of the layer is made up of 25 underscore characters, with **one** hole of length 5. That means that the total width is equal to 30. This is randomly shifted after each layer. An example of a valid layer is:
```
_______________ __________
```
The hole can also be at the edges, as if the layer is like a cylinder:
```
_________________________
```
Note that there are 2 leading spaces and 3 trailing spaces. Making a *single* hole of width 5.
### Test cases
For *n*=4, this is a valid output:
```
_______________ __________
______ ___________________
_______________________ __
_________________________
```
Note: the holes must be *uniformly* distributed. Trailing and/or leading newlines are allowed.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the submission with the least amount of bytes wins!
[Answer]
# Pyth, 19 bytes
```
VQ.>+*\_25*d5O30*b4
```
[Try it here!](http://pyth.herokuapp.com/?code=VQ.%3E%2B*%5C_25*d5O30*b4&input=4&debug=0)
# Explanation
```
VQ.>+*\_25*d5O30*b4 # Q = input
VQ # Repeat Q times
*\_25 # 25 underscores
*d5 # 5 spaces
+ # concat the underscores and spaces
.> O25 # rotate this string 0-29 times
*b4 # print the seperating newlines
```
[Answer]
# Ruby, 74 71 59
Thanks to Alex A. for reminding me that being basically one line means I can use the stabby lambda
```
f=->n{n.times{puts (('_'*25+' '*5)*2)[rand(30),30]+"\n"*5}}
```
[Answer]
# Julia, 72 bytes
```
n->join([join(circshift(["_"^25*" "^5...],rand(1:30)))"\n"^5 for i=1:n])
```
This is an anonymous function that accepts an integer and returns a string. To call it, assign it to a variable.
We construct a string of 25 underscores followed by 5 spaces, then splat that into an array of characters. We circularly shift it a random number of times (between 1 and 30), join it back into a string, and tack on 5 newlines. This process is repeated *n* times, where *n* is the input. The resulting array is joined and returned.
[Try it here](http://goo.gl/l4V3zc)
[Answer]
# PowerShell 65 Bytes
```
0..$args[0]|%{-join("_"*25+" "*5)[($r=Random 25)..($r-29)];,""*5}
```
Run a loop for *n* iterations. Get a random number and make a underscore string with 5 spaces at the end. Index into the the string as an array to pull starting from a random location. Negative indexing wraps from the end. Join that back up again and append 5 newlines.
Edit: I don't know why I thought I needed the parameter for `-Maximum` as it's positional. Thanks to [TimmyD](https://codegolf.stackexchange.com/users/42963/timmyd) I shaved some bytes and forgot to get input so that drove me back up to 65.
[Answer]
# Pyth, 19 bytes
```
VQ.>r"5 25_"9O30*4b
```
[Try it here](http://pyth.herokuapp.com/?code=VQ.%3Er%225+25_%229O30%2a4b&input=4)
Thanks to FryAmTheEggman for catching a bug.
[Answer]
# SpecBAS - 93 bytes
```
1 a$="_"*25+" "*5: INPUT n: FOR i=1 TO n: r=1+INT(RND*30): ?a$(r TO)+a$( TO r-1)''''': NEXT i
```
Makes a string of 25 underscores + 5 spaces, picks a random start point and splices the string at that position and tacks the start of string to end.
The apostrophe forces a newline, so 1 at end of string and 4 empty lines.
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 23 bytes
```
:"95l25X"5Z"h30YrYS10ct
```
[**Try it online!**](http://matl.tryitonline.net/#code=OiI5NWwyNVgiNVoiaDMwWXJZUzEwY3Q&input=NA)
### Explanation
```
:" % take input n implicitly. Repeat loop n times
95l25X" % row vector with number 95 ('_') repeated 25 times
5Z" % row vector of 5 blank spaces
h % concatenate vertically
30Yr % random number uniformly distributed on [1,2,...,30]
YS % circularly shift
10c % newline character. Includes another newline when printed
t % duplicate
% implicitly end loop and display stack contents
```
[Answer]
## Java, ~~177~~ 140 bytes
*-1 byte to Blue moving the i++*
-2 bytes to me leaving meaningless whitespace in the original
-34 bytes to Blue for realizing I didn't need the char[] at all
[Because, ya know, Java.](http://meta.codegolf.stackexchange.com/a/5829)
```
n->{String s="";for(;n-->0;){int r=(int)(Math.random()*30);for(int i=0;i<30;){s+=i>r&i<r+6|r>24&i++<=r%25?" ":"_";}s+="\n\n\n\n";}return s;}
```
Slightly ungolfed:
```
Function<Integer, String> fallingBall = n -> {
String s = "";
for (;n-->0;) {
int r = (int)(Math.random()*30);
for (int i=0; i<30; i++) {
s += i>r&i<r+6|r>24&i<=r%25?" ":"_";
}
s += "\n\n\n\n";
}
return s;
}
```
Since Java doesn't have a String 'rotate', I had to take a different approach. I generated a random int 0-29 that represents the start index of the hole (OBO because `>` is shorter than `>=`). Each individual character is then decided by the logic
```
l[index] = (index>random && index<random+6) || (random>24 && index<=random%25) ? ' ' : '_';
```
This handles the "wrapping" nature of the whole.
[Answer]
# Python 3.5 - 109 113 bytes (+4 for printing out 4 new lines between each result):
```
def g(a,j='_'*25+' '*5):
for l in range(a):import random;n=random.randrange(len(j)+1);print(j[-n:]+j[:-n]+'\r'*4)
```
# Ungolfed Form:
```
# j is the starting string with the 25 underscores and then 5 spaces at the end
def g(a,j='_'*25+' '*5):
import random #Import the random module
for l in range(a): # Do the following as many times as provided by the user
n=random.randrange(len(j)+1) Get a random number in the range 0-29
print(j[-n:]+j[:-n]+'\r'*4) #Shift the string characters right "n" times and print out the results with 4 new lines in between
```
Basically what is going on is that a string 'j', consisting of 25 underscore followed by 5 spaces, is given as an argument to the function "g". Then, the random module is imported, and, as many times as specified by the user, a random number is chosen in the range `0 => 29`, and the string, "j", is shifted right that many times. The result is then printed out after each iteration, with 4 new lines in between each result.
[Answer]
# Python, ~~119~~ 103 bytes
```
import random
s='_'*20+' '*5
def f(n,a=random.randint(0,25)):[print(s[a:]+s[:a]+3*'\n')for _ in' '*n]
```
] |
[Question]
[
**Input:**
Input is a randomized array of nuts (in your language), the possible nuts follow. Your program must have a way of representing each kind of nut, such as an integer code. Program must be able to handle any size array of any configuration of nuts.
**Possible Nuts:**
```
Kola nut
Macadamia
Mamoncillo
Maya nut
Mongongo
Oak acorns
Ogbono nut
Paradise nut
Pili nut
Pistachio
Walnut
```
**Output:**
Output must be the array sorted in such a fashion that there are no adjacent nuts of the
same kind. If this is impossible, the output should be an empty array.
Example Input (simplified):
```
["walnut", "walnut", "pistachio"]
```
Example Output:
```
["walnut", "pistachio", "walnut"]
```
**Solutions may not simply shuffle the array until it becomes unique by chance. The sort employed must be a deterministic one**

[Answer]
### GolfScript, 42 41 37 38 characters
```
~.`{\`{=}+%1-,}+$.,)2//zip[]*.2<..&=*p
```
The code expects input on STDIN and prints result to STDOUT, e.g.:
```
> ["walnut" "walnut" "walnut" "macadamia" "pistachio"]
["walnut" "macadamia" "walnut" "pistachio" "walnut"]
> ["walnut" "walnut" "walnut" "macadamia" "walnut"]
[]
```
The script became longer than expected but I suppose there is room for improvement.
Edit: The case of a list with a single item costs me 1 character (the best comparison I could come up with is the same as Peter's).
[Answer]
## GolfScript, 32 chars
```
~:x{]x\-,}$.,)2//zip[]*.2<..&=*`
```
Same input and output format as Howard's solution.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog) v2, 10 bytes
```
p.¬{s₂=}∨Ė
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v0Dv0Jrq4kdNTba1jzpWHJn2/3@0UnliTl5piZKOAlZWbmJyYkpibmYiiFOQWVwCNCwzXyn2fxQA "Brachylog – Try It Online")
Brute-force solution. (This is a function, allowed because the challenge does not say "full program".) It's also mostly a direct translation of the spec (the only real subtlety is that I managed to arrange things so that all the implicit constraints arrived in exactly the right places, thus not needing any extra characters to disambiguate them).
Note that this is a generic algorithm for rearranging any sort of list so that it does not have two touching elements; it can handle string representations of the elements, and it can handle integer codes just as well. So it doesn't really matter how the "Your program must have a way of representing each kind of nut, such as an integer code." requirement from the question is interpreted.
## Explanation
```
p.¬{s₂=}∨Ė
p Find a permutation of {the input}
¬{ } which does not have the following property:
s₂ it contains a pair of adjacent elements
= that are equal
∨ {no constraint on what value the equal elements can have}
. If you find such a permutation, output it.
∨ If no permutation is found, ignore the input and
Ė {output} an empty list
```
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 7 bytes (14 nibbles)
```
/|``p$/!>>$@!*
```
Systematically (non-randomly) finds *all* permutations of the input without adjacent identical nuts, and then returns the first of these (or an empty list if there aren't any).
```
/|``p$/!>>$@!*
| # filter
``p # all permutations of
$ # the input list
# by
/ * # fold-by-multiplication
! # zip together
>>$ # list without first element
@ # the same list
! # are elements equal?
/ # finally get first element
```
[](https://i.stack.imgur.com/vHUOH.png)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `r`, ~~12~~ 8 bytes
```
Ṗ‡ÞǓ⁼c¾∨
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJyIiwiIiwi4bmW4oChw57Hk+KBvGPCvuKIqCIsIiIsIltcIndhbG51dFwiLCBcIndhbG51dFwiLCBcInBpc3RhY2hpb1wiXSJd)
*-4 thanks to @Steffan*
#### Explanation (old)
I'll update it when I have time.
```
Ṗ¾wJλ:Ḣ=a¬;c # Implicit input
Ṗ # Permutations
¾wJ # With an empty list appended
# (In case there is no truthy item)
λ ;c # First item such that:
:Ḣ= # Adjacent elements are equal?
a¬ # None are true
# Implicit output
```
[Answer]
## J, 80 characters
```
]`_:@.(0<2&([:+/=/\))({.~-:@#),((],.|.)~>.@-:@#)<"1;(\:#&.>)(</.])[;.1' ',1!:1[1
```
Not really in the same league as Golfscript on this one. I suspect there are gains to be made, but the 14 characters needed just to get the list into the program `[;.1' ',1!:1[1` is a major handicap.
Basically the program takes in the list, groups similar items together, sorts by number of items in each group descending, and alternates the output between the first half and the second half of the list. The rest if the code gets rid of extraneous items and decides if the list is valid output (outputting infinity `_` if it isn't).
Example:
```
macadamia walnut walnut pistachio walnut
```
group `(</.])`:
```
macadamia walnut walnut walnut pistachio
```
sort `(\:#&.>)`:
```
walnut walnut walnut macadamia pistachio
```
ravel `((],.|.)~>.@-:@#)`:
```
walnut macadamia walnut pistachio walnut
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
Ġz0UẎḟ0ịµẋ⁻ƝẠ$
```
[Try it online!](https://tio.run/##y0rNyan8///IgiqD0Ie7@h7umG/wcHf3oa0Pd3U/atx9bO7DXQtU/v//H22qo2ACRsZgZBQLAA "Jelly – Try It Online")
The last 6 bytes can be removed if we can have undefined behavior for invalid inputs.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
│éÿ∞å[zàL⌂
```
[Run and debug it](https://staxlang.xyz/#p=b38298ec865b7a854c7f&i=[%22walnut%22,+%22walnut%22,+%22pistachio%22]%0A[%22walnut%22+%22walnut%22+%22walnut%22+%22macadamia%22+%22walnut%22]%0A[%22walnut%22+%22pistachio%22+%22walnut%22+%22macadamia%22+%22walnut%22]&a=1&m=2)
Here's the same program unpacked, ungolfed, and commented.
```
|T get all permutations
{ block to filter by
:g_= after dropping repeated elements, it's still equal
f execute filter
|c terminate and pop if falsy (no match)
hJ take the first permutation, and join with spaces
```
[Run this one](https://staxlang.xyz/#c=%7CT++++%09get+all+permutations%0A%7B+++++%09block+to+filter+by%0A++%3Ag_%3D%09after+dropping+repeated+elements,+it%27s+still+equal%0Af+++++%09execute+filter%0A%7Cc++++%09terminate+and+pop+if+falsy+%28no+match%29%0AhJ++++%09take+the+first+permutation,+and+join+with+spaces&i=[%22walnut%22,+%22walnut%22,+%22pistachio%22]%0A[%22walnut%22+%22walnut%22+%22walnut%22+%22macadamia%22+%22walnut%22]%0A[%22walnut%22+%22pistachio%22+%22walnut%22+%22macadamia%22+%22walnut%22]&a=1&m=2)
] |
[Question]
[
Given integers `k` and `n`, generate a sequence of `n` unique *k-tuples* of pairwise coprime integers. *Every* such tuple must occur once eventually, that is, for any existing k-tuple of pairwise coprime integers, some `n` will eventually generate it.
The output may be printed or evaluated in any list/tuple-like form.
### Definitions
* Two numbers `a` and `b` are **coprime** if `gcd(a, b) = 1`, i.e. they share no common divisor other than 1.
* A tuple of `k` numbers `(a1, a2, ..., ak)` is **pairwise coprime** if every pair of numbers in the tuple is coprime.
### Examples
```
k = 1, n = 5 -> [[1],[2],[3],[4],[5]]
k = 2, n = 7 -> [[2,1],[3,1],[3,2],[4,1],[4,3],[5,1],[5,2]]
k = 3, n = 10 -> [[3,2,1],[4,3,1],[5,2,1],[5,3,1],[5,3,2],[5,4,1],[5,4,3],[6,5,1],[7,2,1],[7,3,1]]
k = 4, n = 2 -> [[5,3,2,1],[5,4,3,1]]
k = 5, n = 0 -> []
```
### Notes
* Standard code golf rules, shortest code wins.
* `k` is assumed to be positive, and `n` non-negative.
* The numbers within each tuple must be positive, distinct, and may appear in any order.
* Uniqueness is up to ordering: e.g. `(1,2,3)` is the same as `(1,3,2)`.
* Good luck and have fun!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 13 bytes
I think it has been 389 days since I last posted something here haha. There is definitely some golfing potential left in this program.
### Code
Uses the [**05AB1E**-encoding](https://github.com/Adriandmen/05AB1E/blob/master/docs/code-page.md).
```
∞æ¹ùʒPy.¿Q}²£
```
[**Try it online!**](https://tio.run/##ASQA2/9vc2FiaWX//@KInsOmwrnDucqSUHkuwr9RfcKywqP//zMKMTA "05AB1E – Try It Online")
### Explanation
It is worth noting that for two numbers \$n, m \in \mathbb{Z}^+\$ that:
$$
\tag{1} \label{1}
\gcd(n, m) \cdot \text{lcm}(n, m) = n \cdot m
$$
This means that for two numbers \$n, m \in \mathbb{Z}^+\$ where the \$\gcd(n, m) = 1\$, we can conclude that the \$\text{lcm}(n, m) = n \cdot m\$.
Furthermore, the \$\gcd\$ function is a multiplicative function, which means that if \$n\_1\$ and \$n\_2\$ are relatively prime, then:
$$
\gcd(n\_1 \cdot n\_2, m) = \gcd(n\_1, m) \cdot \gcd(n\_2, m)
$$
From this, we obtain the fact that:
$$
\tag{2} \label{2}
\gcd(a, bc) = 1 \iff \gcd(a, b) = 1 \wedge \gcd(a, c) = 1
$$
Let us denote a \$k\$-tuple of positive integers as \$S = \{x\_1, x\_2, \dots, x\_k\}\$. A set \$S\$ is pairwise coprime, if and only if:
$$
\tag{3} \label{3}
\forall a, b \in S \wedge a \not = b \rightarrow \gcd(a, b) = 1
$$
Using Equations \$\eqref{1}, \eqref{2}\$ and \$\eqref{3}\$, we can conclude that a set \$S = \{x\_1, x\_2, \dots, x\_k\}\$ is pairwise coprime, if and only if:
$$
\text{lcm}(x\_1, x\_2, \dots, x\_k) = \prod\_{x \in S} x
$$
### Code Explanation
```
∞æ¹ùʒPy.¿Q}²£
∞æ # Powerset of the infinite list [1, ..., ∞].
¹ù # Keep only lists of length *k*.
ʒ } # Filter. Keep lists where the
P # product of the list
Q # is equal to
y.¿ # the least common multiple of the list
²£ # Retrieve the first *n* elements.
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 9 bytes
```
↑fËoε⌋`ṖN
```
[Try it online!](https://tio.run/##AR4A4f9odXNr///ihpFmw4tvzrXijItg4bmWTv///zP/MTA "Husk – Try It Online")
## Explanation
A straightforward solution, not the most exciting.
```
↑fËoε⌋`ṖN Implicit inputs, say k=3, n=2.
N Natural numbers: [1,2,3,4,..
`Ṗ All k-element subsets: [[1,2,3],[2,3,4],[1,3,4],..
` flips the arguments of Ṗ since it expects the number first.
f Keep those that satisfy this:
Ë All pairs x,y (not necessarily adjacent) satisfy this:
⌋ their gcd
oε is at most 1.
Result is all pairwise coprime subsets: [[1,2,3],[1,3,4],..
↑ Take the first n: [[1,2,3],[1,3,4]]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
‘ׯNœcŒcg/€$ÐṂḣ⁸
```
A dyadic Link accepting `n` on the left and `k` on the right.
**[Try it online!](https://tio.run/##ATMAzP9qZWxsef//4oCYw5fDhk7Fk2PFkmNnL@KCrCTDkOG5guG4o@KBuP/Dp8WS4bmY//8w/zQ "Jelly – Try It Online")**
There must be a better way than this inefficient monstrosity! It'll time out for quite small inputs since it inspects all k-tuples of the natural numbers up to the `(n+1)*k`-th prime! (The `+1` is only needed to handle `n=0`.)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 106 bytes
```
(s=Range[#2#];If[#==1,List/@s,SortBy[Select[s~(S=Subsets)~{#},Union[GCD@@@#~S~{2}]=={1}&],Last][[;;#2]]])&
```
[Try it online!](https://tio.run/##TcfBCsIgGADge08RCGODH5rW6DAEqSCCHSLpJP/Bhi2hOZh2iDFf3W6x7/b1OrxMr4Ntdep4yj2/adcZRRjB@vJUhHMKjfVhIzzIYQyHr5LmbdqgfMwll5@HN8EXcSIz3J0dnDofT0IIEmWc2IycT3TOEBrtAypV14QhYpGl62hdWItOUahw9R@D/WJboOWiO2CLVVBiSj8 "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 153 bytes
```
lambda n,k,R=range:[[*t,r]for r in R(n+k+2)for t in combinations(R(1,r),k-1)if all(sum(x%i<1for x in[*t,r])<2for i in R(2,r))][:n]
from itertools import*
```
[Try it online!](https://tio.run/##PY1BDoIwEADvvKIXkxZqIuiJwCe4IoeiVDe0W7KsCb6@0pB4nWRmli@/A16jbe/RGT8@jUA9664lg6@p7vucNQ02kCABKDqJxVxUKgFO4BH8CGgYAq6yk6UmpedzqcAK45xcP15uJ2jKJGy7cPRUUyUAR7LaJTX0NQ6ZpeAF8EQcglsF@CUQ5/G/s7K66JuqM7EQIEtW8Qc "Python 3 – Try It Online")
A function that takes `n, k` as arguments and returns out the list of `n` co-prime k-tuples.
The tuple are generated with increasing maximum, so it's guaranteed that every co-prime tuple will eventually be printed as `n` increases.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 58 bytes
```
NθNη≔⁰ζ⊞υ⟦⟧W‹LΦυ⁼Lκθη«≦⊕ζFΦυ⬤κ⬤…²ζ∨﹪μξ﹪ζξ⊞υ⁺⟦ζ⟧κ»I…Φυ⁼Lιθη
```
[Try it online!](https://tio.run/##dY5NT8MwDIbP66/w0ZGCNMZxp2kCaRJjFddph9CFJqqbtPngo4jfXrx1oF3w4bUey379VkaFyisax43rcnrK7YsO2Itlcc2GeRWjrR3OJQxMZY4Gs4T9geHdWNKAjzpGFlcngw@WEh/yxn2fFf3NGyGhF4LVCAFfxWyruovzxlVBt9olfZx@zF59gCunFRE2U3tWrta4OO1J2AXc@mMmj62EDx5caDjRueA3bkk54n44SGgEf/guymBdwrWKLJ8V6bXx3b/h7RT@nF0sx/EObufjzRv9AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
NθNη
```
Input `k` and `n`.
```
≔⁰ζ⊞υ⟦⟧
```
Start the master list with a 0-tuple whose largest number is 0.
```
W‹LΦυ⁼Lκθη«
```
Repeat until we have at least `k` `n`-tuples.
```
≦⊕ζ
```
Increment the candidate number.
```
FΦυ⬤κ⬤…²ζ∨﹪μξ﹪ζξ
```
Filter out all of the existing tuples where at least one member has a common factor with the candidate.
```
⊞υ⁺⟦ζ⟧κ
```
Prepend the candidate to each remaining tuple and push all the resulting tuples back to the master list.
```
»I…Φυ⁼Lιθη
```
Print the first `n` `k`-tuples.
[Answer]
# JavaScript (ES6), 143 bytes
Takes input as `(k)(n)`.
```
(k,x=0)=>F=n=>n?(g=a=>x>>i?x>>i++&1?a.some(x=>(C=(a,b)=>b?C(b,a%b):a>1)(x,i))?[]:g([...a,i]):g(a):b=a)(i=[],x++).length-k?F(n):[b,...F(n-1)]:[]
```
[Try it online!](https://tio.run/##ZYxBCsIwEEX33kOZoWmwigiBSRaClwhZTGqtsTURK5Lb17iUbj6Px@Pf@cNT@wrPdx3TpZuvNMMgMm2R9Jki6WigJyadtQ7mN1W1aQzLKT06yKThRMDCl9ybE3jBa4@KdYOQRUA01qkerJSSRXBYmFF5YoRA1olcVSjHLvbvWz2YM0RU1otSF6wbdMq6uU1xSmMnx9TDFcrxAXH1L3cIx4XcIzTbhT0gFDl/AQ "JavaScript (Node.js) – Try It Online")
### Commented
```
( k, // outer function taking k
x = 0 // x = bit mask of integers to include in the tuple
) => //
F = n => // F = recursive function taking n
n ? // if n is not equal to 0:
( g = a => // g is a recursive function taking a[]:
x >> i ? // if x is greater than or equal to 2**i:
x >> i++ & 1 ? // if the i-th bit is set in x:
a.some(x => // for each value x in a[]:
( C = (a, b) => // C tests whether a and b are coprime:
b ? // if b is not equal to 0:
C(b, a % b) // recursive call with (b, a mod b)
: // else:
a > 1 // true if *not* coprime
)(x, i) // initial call to C with (x, i)
) ? // end of some(); if truthy:
[] // abort by returning an empty array
: // else:
g([...a, i]) // append i to a[] and call g again
: // else:
g(a) // just call g with a[] unchanged
: // else:
b = a // done: return a[] and save it in b[]
)(i = [], x++) // initial call to g with a = [], i = 0; increment x
.length - k ? // if the length of the result is not equal to k:
F(n) // just call F with n unchanged
: // else:
[b, ...F(n - 1)] // append b[] to the final result and decrement n
: // else:
[] // stop recursion
```
] |
[Question]
[
For robbers' post, [Cheapo Enigma machine (Robbers)](https://codegolf.stackexchange.com/questions/117319/cheapo-enigma-machine-robbers)
A cop's submission will consist of a program/function that accepts a single byte of data and return a single byte of data. Every possible input must produce a unique output. (In the other words, your function must be bijective)
Robbers will attempt to create the inverse function of yours using as short a code as possible. So your objective is to make your function difficult to invert.
You cannot use built-ins that have the sole purpose of hashing or encryption.
Your byte count cannot exceed 64 bytes. 0-byte solutions are not eligible for winning.
# Input/Output format
8 bits (0 or 1), or a base-10 integer in range 1-256, 0-255 or -128 to 127. Can use standard I/O or file I/O. Function can also return a value as output. Input and output should belong to the same range (binary, 1-256, 0-255 or -128 to 127).
The robber will also be required to use this range for input and output.
# Scoring
Ratio of your byte count to that of the best robber's attempt against you. Lowest score wins.
You are eligible to win (as a cop) only if a robber has attempted to defeat you. (This robber may be you)
# Example
C++, uses 0-255 range, 31 bytes
```
int x;
cin>>x;
cout<<(x+1)%256;
```
Possible robber submission in C++, 32 bytes
```
int f(int x)
{return x?x-1:255;}
```
*Using the same language or a similar algorithm isn't a requirement*
This gives a score of 31/32 = 0.97 to both the cop and the robber.
[Answer]
# Javascript, 11 8 bytes, Score: [8 / 5](https://codegolf.stackexchange.com/a/117491/29637)
```
x=>x^x/2
```
Simple implementation of gray code. Decoding usally needs a whole loop. Let's see who comes up with the smallest or even without a loop !
[Answer]
# C, 64 bytes, [Score 64/71 = 0.901](https://codegolf.stackexchange.com/a/117927/8927)
```
T[256];f(x){srand(x&&f(x-1));for(;T[x=rand()%256]++;);return x;}
```
Takes input in the range [0 255].
[Try it online!](https://tio.run/nexus/c-gcc#tZBBa4NAEIXP66@YCoZdTCG2JIdspRR6KZS2B@kl8RCiS9fgWjZWhOBvT2dci9JLeikIOm/mPb@Zc7K5Wa5SqXgrTke7MxlvZzOsriMhpKosl8mmjfuGCGg0DKWQNq@/rIFWdmdtaih32nBx8hgV@498f3CpHqMEEguIYSHxdQfYkRCGUAhAB3PjRdoPeKwbPdp59MSjnYe6DXYV1wI97NOiorgfLG6zuT@HplddckPJEdUaxyGAaAUxKksBP7at8XvDZViWjKSE2rmVq8Pwjz@gK@64dApXaBpy@4RJ6oCG8j0g3/vD89OjD2v6fnlNwNUEPe6wNW@2qhTgk@V1bktt9LFcD8tdJvt9RDqu@L@7TcEppjt/Aw "C (gcc) – TIO Nexus") — on TIO (using GCC), this produces:
```
103,198,105,115,081,255,074,236,041,205,186,171,242,251,227,070,
124,194,084,248,027,232,231,141,118,090,046,099,051,159,201,154,
102,050,013,183,049,088,163,037,093,005,023,233,094,212,178,155,
180,017,014,130,116,065,033,061,220,135,112,062,161,225,252,001,
126,151,234,107,150,143,056,092,042,176,059,175,060,024,219,002,
026,254,067,250,170,058,209,230,148,117,216,190,097,137,249,187,
168,153,015,149,177,235,241,179,239,247,000,229,202,011,203,208,
072,071,100,189,031,035,030,028,123,197,020,075,121,036,158,009,
172,016,080,021,111,034,025,125,245,127,164,019,181,078,152,224,
077,052,188,095,119,108,134,043,085,162,004,211,054,226,240,228,
079,073,253,169,008,138,010,213,068,091,243,142,076,215,045,066,
006,196,132,173,222,048,246,032,133,007,244,185,195,217,160,120,
218,106,083,144,087,238,207,096,210,053,101,063,098,128,165,089,
140,012,192,131,047,039,022,147,184,109,182,193,199,237,018,069,
057,157,174,104,122,166,055,110,003,040,139,086,145,114,129,113,
206,167,191,214,146,221,136,038,156,082,200,029,044,204,223,064
```
Note that on other systems, it may produce different (but still valid) output, since C does not mandate a specific `rand` implementation. My submission is specifically the version running on TIO (as linked).
---
I'm quite disappointed that I wasn't able to get a version like my original (`f(x){return rand(srand(x*229))/229%256;}`) to work on TIO, since I think that's much more elegant. Since that only works on Clang running on OS X, it isn't fair for the competition. This one's still pretty awkward to reverse, so that's enough I guess.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), [2/5](https://codegolf.stackexchange.com/a/117488/12012)
```
^H
```
[Try it online](https://tio.run/nexus/jelly#@x/n8f9R486HO7Yd2np0z@F29/8A "Jelly – TIO Nexus") to see the whole table.
[Answer]
# JavaScript, 44 bytes [22/3](https://codegolf.stackexchange.com/a/117665/64505)
```
x=>a.sort()[x]
for(a=[],i=0;i<256;)a[i]=i++;
```
Uses lexicographic sort (Javascript Default) to rearrange all the numbers from 0-255
[Try it online!](https://tio.run/nexus/javascript-node#XZDRasMgFIavj09RvNJaQs0Wt5JZ2LrtBcauUi9EkmJoq5hcFNY@e6ZpBu0uBA/f8Tv/sZHDSa511rnQE1qdFGpcIFpWamHlsrQveSFKqiurpGWsHBI1/6j5o8hIkx20Jw1Fxh07t6@zvdsRvN3CEjjk8ACPUICAJ3iGFbzCG2zgHT7gE9Nx8NXKRRl19AfNZl7aORfjxWe9@@qDPe4IFzQW397XYaO7mlCGAcempGijok2KdlLEt0yaiou5Za2aOi/x3Eb0FF3G@NePuAmTF8WUxjZkXDXKLOPqfE7VOnJ6t2wdggt4kWCUDr8)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 32 27/30 bytes
Thanks to [christoph](https://codegolf.stackexchange.com/users/29637/christoph) for golfing 5 bytes.
```
f(x){x=x?f(x*5+1&255)+1:0;}
```
[Try it online!](https://tio.run/nexus/c-gcc#@5@mUaFZXWFbYQ9kaJlqG6oZmZpqahtaGVjX/lfOzEvOKU1JtSkuScnM18uw48rMK1HITczM09Cs5uJMyy/SAAlk2hpYZ9oYmZpZZ2prgyQ4C4qA4mkaSqopCqopMXlKOpk6aRqZmprWXJy1XLX/AQ "C (gcc) – TIO Nexus")
[Answer]
# Javascript, [11/8](https://codegolf.stackexchange.com/a/117511/12012) bytes
```
x=>x**5%257
```
Domain/range is 1 through 256.
[Answer]
# JavaScript, 13 bytes [13/12](https://codegolf.stackexchange.com/a/117565/64505)
```
x=>(x<<9)%257
```
Input and output are both in the range 1->256
[Try it online!](https://tio.run/nexus/javascript-node#VY/BasMwEETPq68IhoIUURO5tdIQq9Cm7Q@UnhwdhLDDmjQSsg@B4m93N6kP6WFhd5l5zLRmOptnfq6qjbgryvXkTG1ZGxJHo7ZY0WuLUoof5mq8V9YgG5k3Lv92kbeCMR9OfTg2@TEceLbfwwoUFPAAj1CChjU8wQZe4BV28Abv8JGR5Y@@IrrSM3yxiAaXSl@XmA/hc0h4OnClBR1fMTZp5/qGC5lBRqILoiNEd0F0M4K80vha6SXKzs7KkeY2YxTXAj7vQxq4uAlTlOWcBlvua7SGYCiVFf86NimFRDXG6Rc "JavaScript (Node.js) – TIO Nexus")
[Answer]
# Javascript, [27/29](https://codegolf.stackexchange.com/a/117564/6828) bytes
```
x=>x-6?x*95%127+x*98%131:65
```
Edit: Range/Domain is 1..256. Generated via brute force, more or less.
[Answer]
# [Octave](https://www.gnu.org/software/octave/), [16/6](https://codegolf.stackexchange.com/a/117496/12012)
```
@(x)mod(x*3,256)
```
[Try it online!](https://tio.run/nexus/octave#@@@gUaGZm5@iUaFlrGNkaqb5PzGvWMPAysjUVPM/AA "Octave – TIO Nexus")
[Answer]
# Java, 35 bytes
```
int a(int v){return (v*v+v)%512/2;}
```
Domain/Range are 0-255
[Answer]
# Ruby, 23 bytes
```
->x{('228'*x).to_i%257}
```
Range and domain is 0..255. Concatenate 228 to itself x times, then take the result modulo 257 (0 maps to 0). 228 is the first magic number after 9 that works for this range (gives distinct values that don't include 256).
[Answer]
## Python 3, 55 bytes
```
y=lambda x,i=3:x if i==0 else pow(3,y(5*x,i-1),257)-1
```
Domain/Range is 0-255.
[Answer]
## Python 3, 32 bytes [32/23](https://codegolf.stackexchange.com/a/117685/29637)
```
V=lambda x:((3+x)%16)*16+x//16
```
Domain/Range is 0-255.
Flips the first four bytes with the last four, and adds a three to the first bytes.
[Answer]
# Mathematica, 13 bytes
```
Mod[#^7,257]&
```
Uses the range [1..256], although it's equally valid on the range [0..255]. To see the entire table, copy/paste one of the following lines of code into the [Wolfram sandbox](http://sandbox.open.wolframcloud.com):
```
Array[ Mod[#^7,257]&, 256] (for a list of values in order)
Array[ Rule[#,Mod[#^7,257]]&, 256] (for a list of input-output rules)
```
[Answer]
# [brainfuck](https://github.com/TryItOnline/tio-transpilers), [37/11](https://codegolf.stackexchange.com/a/117817/12012)
```
,+++++[>+++++++<-]>++[<+++++++++>-]<.
```
[Try it online!](https://tio.run/nexus/brainfuck#@6@jDQLRdtoQYKMbC2RG22jDgJ1urI3e//8A "brainfuck – TIO Nexus")
Not very good but range of 0-255
] |
[Question]
[
Given a [semiprime](https://en.wikipedia.org/wiki/Semiprime) **N**, find the smallest positive integer **m** such that the binary representation of one of the two factors of **N** can be found in the binary representation of **N \* m**.
### Example
Let's consider the semiprime **N** = **9799**.
We try different values of **m**, starting at 1:
```
m | N * m | N * m in binary
---+--------+------------------
1 | 9799 | 10011001000111
2 | 19598 | 100110010001110
3 | 29397 | 111001011010101
4 | 39196 | 1001100100011100
5 | 48995 | 1011111101100011
6 | 58794 | 1110010110101010
7 | 68593 | 10000101111110001
8 | 78392 | 10011001000111000
9 | 88191 | 10101100001111111
10 | 97990 | 10111111011000110
11 | 107789 | 11010010100001101
```
We stop here because the binary representation of the last product contains `101001` which is the binary representation of **41**, one of the two factors of **9799** (the other one being **239**).
[))](https://i.stack.imgur.com/EfEiO.png)))
So the answer would be **11**.
### Rules and notes
* Trying even values of **m** is pointless. They were shown in the above example for the sake of completeness.
* Your program must support any **N** for which **N \* m** is within the computing capabilities of your language.
* You are allowed to factorize **N** beforehand rather than trying each possible substring of the binary representation of **N \* m** to see if it turns out to be a factor of **N**.
* As [proven by MitchellSpector](https://codegolf.stackexchange.com/a/110856/58563), **m** always exists.
* This is code-golf, so the shortest answer in bytes wins. Standard loopholes are forbidden.
### Test cases
The first column is the input. The second column is the expected output.
```
N | m | N * m | N * m in binary | Factor
-----------+------+---------------+----------------------------------------------+-------
9 | 3 | 27 | [11]011 | 3
15 | 1 | 15 | [11]11 | 3
49 | 5 | 245 | [111]10101 | 7
91 | 1 | 91 | 10[1101]1 | 13
961 | 17 | 16337 | [11111]111010001 | 31
1829 | 5 | 9145 | 1000[111011]1001 | 59
9799 | 11 | 107789 | 1[101001]0100001101 | 41
19951 | 41 | 817991 | 1[1000111]101101000111 | 71
120797 | 27 | 3261519 | 11000[1110001]0001001111 | 113
1720861 | 121 | 208224181 | 11000110100[100111111101]10101 | 2557
444309323 | 743 | 330121826989 | 100110011011100110010[1101010010101011]01 | 54443
840000701 | 4515 | 3792603165015 | 11011100110000[1000110000111011]000101010111 | 35899
1468255967 | 55 | 80754078185 | 1001011001101010100010[1110001111]01001 | 911
```
[Answer]
# Pyth, 13 bytes
```
ff}.BY.B*TQPQ
```
[Demonstration](https://pyth.herokuapp.com/?code=ff%7D.BY.B%2aTQPQ&input=9799&debug=0)
Explanation:
```
ff}.BY.B*TQPQ
f Find the first integer >= to 1 where the following is true
f PQ Filter the prime factors of the input
*TQ Multiply the input by the outer integer
.B Convert to a binary string
.BY Convert the prime factor to a binary string
} Check whether the factor string is in the multiple string.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~18~~ ~~16~~ 15 bytes
*-2 bytes thanks to Riley!*
*-1 byte thanks to Emigna!*
```
[N¹*b¹Ñ¦¨båOiNq
```
Explanation:
```
[ # Infinite loop start
N # Push the amount of times we have iterated
¹* # Multiplied by input
b # Convert to binary
¹Ñ¦¨b # Calculate the proper divisors of the input in binary excluding one
åO # Check if a substring of N * m in binary is in the divisors
iNq # If so, print how many times we have iterated and terminate the program
```
[Try it online!](https://tio.run/nexus/05ab1e#ASUA2v//W07CuSpiwrnDkcKmwqhiw6VPaU5x//85Nzk59W5vLWNhY2hl "05AB1E – TIO Nexus")
[Answer]
# JavaScript (ES6), ~~96~~ ~~95~~ 80 bytes
```
n=>F=m=>(k=p=>p&&(q=1,g=x=>1<x&&x<n&n%x<1|g(x>>1,q*=2))(p)|k(p-q))(n*m)?m:F(-~m)
```
A function which returns a recursive function which uses a recursive function which uses a recursive function. I'm really starting to wonder if the `.toString(2)` route would be shorter...
Assign to a variable e.g. `f=n=>...` and call with an extra pair of parens, `f(9)()`. If that's not allowed (the [meta post](https://codegolf.meta.stackexchange.com/a/11317/42545) is at +6/-2), you can use this 83-byte version with standard invocation:
```
f=(n,m)=>(k=p=>p&&(q=1,g=x=>1<x&&x<n&n%x<1|g(x>>1,q*=2))(p)|k(p-q))(n*m)?m:f(n,-~m)
```
Both versions work for all but the last three test cases. You can try these test cases as well by changing `x>>1` to `(x-x%2)/2`.
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + Unix utilities, ~~85~~ 84 bytes
```
for((;;m++)){ dc -e2o$[$1*m]n|egrep -q $(dc "-e2o`factor $1`nBEPn")&&break;}
echo $m
```
[Try it online!](https://tio.run/nexus/bash#S61ITVYwslPQT0kt088rzcn5n5ZfpKFhbZ2rra2pWa2Qkqygm2qUrxKtYqiVG5tXk5pelFqgoFuooKIBlFICySWkJSaX5BcpqBgm5Dm5BuQpaaqpJRWlJmZb13KlJmfkK6jk/v//38LEAAjMDQwB "Bash – TIO Nexus")
---
I'll point out also that m always exists for any semiprime n. Here's why:
Write n=pq, where p and q are prime and p <= q.
Let b the number of digits in the binary representation of n-1. Then, for any k between 0 and n-1 inclusive, p\*(2^b)+k in binary consists of the binary representation of p followed by b additional bits representing k.
So the numbers p\*(2^b)+k for 0 <= k <= n-1, when written in binary, all start with the binary representation of p. But these are n consecutive numbers, so one of them must be a multiple of n.
It follows that we have a multiple mn of n whose binary representation starts with the binary representation of p.
Based on this, one can come up with an upper bound for m of 2 sqrt(n). (One can probably get a much tighter upper bound than this.)
[Answer]
## Haskell, 161 bytes
```
import Data.List
(!)=mod
a#b|a!b==0=b|0<1=a#(b+1)
g 0=[]
g n=g(n`div`2)++show(n!2)
(a%b)c|g b`isInfixOf`g(a*c)=c|0<1=a%b$c+1
f n=min(n%(n#2)$1)$n%(n`div`(n#2))$1
```
Straightforward check. Factor first, then search linearly starting at 1 and take the minimum of the value for both factors.
Takes a few seconds for the last testcase (`1468255967`), `ghci` reports `(15.34 secs, 18,610,214,160 bytes)` on my laptop.
[Answer]
## Mathematica, 83 bytes
```
1//.x_/;FreeQ[Fold[#+##&]/@Subsequences@IntegerDigits[x#,2],d_/;1<d<#&&d∣#]:>x+1&
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog) (2), 14 bytes
```
ḋḃᵐD∧?:.×ḃs∈D∧
```
[Try it online!](https://tio.run/nexus/brachylog2#@/9wR/fDHc0Pt05wedSx3N5K7/B0ILf4UUcHiP//v6W5peX/KAA "Brachylog – TIO Nexus")
There's more than one way to write this in 14 bytes in Brachylog, so I went for the most efficient. As is common for Brachylog submissions, this is a function submission; its input is the semiprime, its output is the multiplier.
## Explanation
```
ḋḃᵐD∧?:.×ḃs∈D∧
ḋ Prime decomposition (finds the two prime factors)
ḃᵐ Convert each factor to binary
D Name this value as D
∧? Restart with the user input
:.× The output is something that can be multiplied by it
ḃ to produce a number which, when expressed in binary
s has a substring
∈D that is an element of D
∧ (suppress an implicit constraint that D is the output; it isn't)
```
Prolog's and Brachylog's evaluation order is set by the first constraint that can't immediately be deduced from the input. In this program, that's a constraint on the result of a multiplication, so the interpreter will aim to keep the operands of the multiplication as close to 0 as possible. We know one of the operands, and the other is the output, so we find the smallest output we can, which is exactly what we want.
[Answer]
# [PowerShell](https://github.com/PowerShell/PowerShell), 136 bytes
```
param($n)$a=2..($n-1)|?{!($n%$_)}|%{[convert]::ToString($_,2)};for(){$b=[convert]::toString(++$m*$n,2);if($a|?{$b-like"*$_*"}){$m;exit}}
```
[Try it online!](https://tio.run/nexus/powershell#@1@QWJSYq6GSp6mSaGukpwdk6Rpq1thXKwJZqirxmrU1qtXRyfl5ZalFJbFWViH5wSVFmXnpGirxOkaatdZp@UUamtUqSbZIakpgarS1VXK1VPKACq0z0zRUEoHGqiTp5mRmpyppqcRrKdUCdeZap1ZkltTW/v//39DIwNzSHAA "PowerShell – TIO Nexus")
Very lengthy due to how conversion-to-binary works in PowerShell. :-/
Takes input `$n`, loops through `2` to `$n-1` and pulls out the factors `!($n%$_)`. Sends those into a loop `|%{...}` and `convert`s each of them to a binary (base `2`) string. Stores those binary strings into `$a`.
Then we enter an infinite `for(){...}` loop. Each iteration, we increment `++$m`, multiply that by `$n`, and `convert` that to a binary string, stored into `$b`. Then, `if` that string is regex `-like` any strings in `$a`, we output `$m` and `exit`.
[Answer]
# [Perl 6](http://perl6.org/), 66 bytes
```
->\n{first {(n*$_).base(2)~~/@(grep(n%%*,2..^n)».base(2))/},^∞}
```
Regex-based.
Super slow, because it brute-forces the factors of *n* all over again at every regex match position of every number that is tried.
Calculating the factors only once, improves performance but makes it 72 bytes:
```
->\n{my @f=grep(n%%*,2..^n)».base(2);first {(n*$_).base(2)~~/@f/},^∞}
```
] |
[Question]
[
Given an input of a string representing a function definition, output the
string with newlines and spaces inserted so that the function's arguments are
newline-separated and aligned.
The input string will follow the following pattern:
* First, it will start with a prefix, which is always at least one character
long and does not contain any of the characters `,()`.
* An open parenthesis (`(`) will then mark the beginning of the argument list.
* A list of zero or more arguments will then follow. These are separated by the
string `", "` (a comma and then a space). None of the arguments will contain
any of the characters `,()`.
* A close parenthesis (`)`) will mark the end of the argument list.
* Lastly, a postfix may be found, which is zero or more characters long and
**may** contain the characters `,()`.
The input string will consist solely of printable ASCII (which means it will never contain a newline).
The output must be:
* The prefix, copied down verbatim, and the open parenthesis.
* The argument list, this time separated not by `", "` but by a comma, newline, and as
many spaces as is needed to vertically align the first character of each
argument.
* The close paren and postfix (if it exists) verbatim.
Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes will win.
Test cases (format: single-line input followed by output followed by double
newline):
```
def foo(bar, baz, quux):
def foo(bar,
baz,
quux):
int main() {
int main() {
fn f(a: i32, b: f64, c: String) -> (String, Vec<i32>) {
fn f(a: i32,
b: f64,
c: String) -> (String, Vec<i32>) {
function g(h) {
function g(h) {
def abc(def, ghi, jkl, mno)
def abc(def,
ghi,
jkl,
mno)
x y z(x, y, z) x, y, z)
x y z(x,
y,
z) x, y, z)
```
[Answer]
## Haskell, 115 bytes
```
import Data.Lists
f x|(a,b:c)<-span(/='(')x,(d,e)<-span(/=')')c=a++b:intercalate(",\n "++(a>>" "))(splitOn", "d)++e
```
Usage example:
```
*Main> putStrLn $ f "fn f(a: i32, b: f64, c: String) -> (String, Vec<i32>) {"
fn f(a: i32,
b: f64,
c: String) -> (String, Vec<i32>) {
```
How it works:
```
bind
a: everything before the first (
b: the first (
c: everything after the first (
d: everything of c before the first )
e: everything of c from the first ) to the end
construct the output string by concatenating
a
b
splitting d at the argument separator ", " and rejoining it with ",\n " followed by (length a) spaces
e
```
[Answer]
# Japt, 23 bytes
```
¡Y?X:Xr',",
"+SpUb'(}')
```
[Test it online!](http://ethproductions.github.io/japt?v=master&code=oVk/WDpYcicsIiwKIitTcFViJyh9Jyk=&input=ImZuIGYoYTogaTMyLCBiOiBmNjQsIGM6IFN0cmluZykgLT4gKFN0cmluZywgVmVjPGkzMj4pIHsi)
### How it works
```
// Implicit: U = input string
¡ }') // Map each item X and index Y in U.split(")") to:
Y?X // If Y is non-zero, X. This keeps e.g. "(String, Vec<i32>)" from being parsed.
:Xr',",\n"+ // Otherwise, X with each comma replaced with ",\n" concatenated with
SpUb'( // U.indexOf("(") spaces.
// Implicit: re-join with ")", output
```
[Answer]
## Perl, ~~62~~ 52 + 2 = 54 bytes
```
s/\(.*?\)/$a=$"x length$`;$&=~s|(?<=,)[^,]+|\n$a$&|gr/e
```
Requires the `-p` flag:
```
$ echo "x y z(x, y, z) x, y, z)
fn f(a: i32, b: f64, c: String) -> (String, Vec<i32>) {" | \
perl -pe's/\(.*?\)/$a=$"x length$`;$&=~s|(?<=,)[^,]+|\n$a$&|gr/e'
x y z(x,
y,
z) x, y, z)
fn f(a: i32,
b: f64,
c: String) -> (String, Vec<i32>) {
```
How it works:
```
# '-p' reads first line into $_ and will also auto print at the end
s/\(.*?\)/ # Match (...) and replace with the below
$a=$"x length$`; # $` contains all the content before the matched string
# And $" contains a literal space
$&=~s| # Replace in previous match
(?<=,)[^,]+ # Check for a , before the the string to match
# This will match ' b: f64', ' c: String'
|\n$a$&|gr/e # Replace with \n, [:spaces:] and all the matched text
```
[Answer]
# Retina, 31 bytes
```
(?<=^([^(])*\([^)]*,)
¶ $#1$*
```
Note the spaces at the end of both lines.
We replace every space which has the regex `^([^(])*\([^)]*,` before it. The replacing string will be a newline, and the number of the captures with `([^(])*` plus one spaces.
A more coherent explanation comes later.
[Try it online here.](http://retina.tryitonline.net/#code=KD88PV4oW14oXSkqXChbXildKiwpIArCtiAkIzEkKiA&input=eCB5IHooeCwgeSwgeikgeCwgeSwgeik)
[Answer]
## ES6, ~~68~~ 67 bytes
```
s=>s.replace(/\(.*?\)/,(s,n)=>s.replace/, /g, `,
`+` `.repeat(n)))
```
This works by extracting the argument list from the original string, and replacing each argument separator with indentation calculated from the position of the argument list within the original string.
Edit: Saved 1 byte thanks to @ETHproductions.
[Answer]
# Pyth, ~~35~~ 30 bytes
```
+j++\,b*dhxz\(c<zKhxz\)", ">zK
```
[Try it here!](http://pyth.herokuapp.com/?code=%2Bj%2B%2B%5C%2Cb*dhxz%5C%28c%3CzKhxz%5C%29%22%2C+%22%3EzK&input=def+foo%28bar%2C+baz%2C+quux%29%3A&test_suite=1&test_suite_input=def+foo%28bar%2C+baz%2C+quux%29%3A%0Aint+main%28%29+%7B%0Afn+f%28a%3A+i32%2C+b%3A+f64%2C+c%3A+String%29+-%3E+%28String%2C+Vec%3Ci32%3E%29+%7B%0Afunction+g%28h%29+%7B%0Adef+abc%28def%2C+ghi%2C+jkl%2C+mno%29%0A&debug=0)
### Explanation:
```
+j++\,b*dhxz\(c<zKhxz\)", ">zK # z = input()
Khxz\) # Get index of the first ")"
<z # Take the string until there...
c ", " # ...and split it on the arguments
j # Join the splitted string on...
++ # ...the concatenation of...
\,b # ...a comma followed by a newline...
*dhxz\( # ...followed by the right amount of spaces = index of the first "(" + 1
+ >zK # Concat the resulting string with the postfix
```
[Answer]
# Groovy, ~~137~~ ~~89~~ 95 bytes
~~Groovy is ***not*** the "Right Tool for the Job"™.~~ Edit: It works just fine when you have someone with a brain using it...
```
f={s=(it+' ').split(/\0/)
s[0].replace(',',',\n'+(' '*it.indexOf('(')))+')'+s[1..-1].join(')')}
```
Tests:
```
println f("def foo(bar, baz, quux):")
println f("int main() {")
println f("fn f(a: i32, b: f64, c: String) -> (String, Vec<i32>) {")
println f("function g(h) {")
println f("def abc(def, ghi, jkl, mno)")
println f("x y z(x, y, z) x, y, z)")
```
Somewhat ungolfed:
```
f = {String it ->
def str = (it + ' ').split(/\)/)
return (str[0].replace (',', ',\n'+(' ' * it.indexOf('('))) + ')' + str[1])
}
```
[Answer]
## [Retina](https://github.com/mbuettner/retina/), 47 bytes
Byte count assumes ISO 8859-1 encoding.
```
m+`^(([^(]+.)[^,)]+,) (.+)
$1¶$2$3
T`p` `¶.+?\(
```
[Try it online!](http://retina.tryitonline.net/#code=bStgXigoW14oXSsuKVteLCldKywpICguKykKJDHCtiQyJDMKVGBwYCBgwrYuKz9cKA&input=eCB5IHooeCwgeSwgeikgeCwgeSwgeik)
[Answer]
# JavaScript (ES6), 85
```
s=>s.replace(/^.*?\(|[^),]+, |.+/g,(x,p)=>[a+x,a=a||(p?`
`+' '.repeat(p):a)][0],a='')
```
**Test**
```
f=s=>s.replace(/^.*?\(|[^),]+, |.+/g,(x,p)=>[a+x,a=a||(p?`
`+' '.repeat(p):a)][0],a='')
console.log=x=>O.textContent+=x+'\n'
;['def foo(bar, baz, quux):',
'int main() {',
'fn f(a: i32, b: f64, c: String) -> (String, Vec<i32>) {',
'function g(h) {',
'def abc(def, ghi, jkl, mno)',
'x y z(x, y, z) x, y, z)']
.forEach(t=>console.log(t+'\n'+f(t)+'\n'))
```
```
<pre id=O></pre>
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 39 bytes
```
ṣ”)Ḣṣ”(Ṫ©œṣ⁾, ji”(⁶ẋƊ⁾,¶;ƊḢ,j®${jʋ@œṣ®$
```
[Try it online!](https://tio.run/##y0rNyan8///hzsWPGuZqPtyxCMLSeLhz1aGVRyeDeI37dBSyMkGCjxq3PdzVfawLJHRom/WxLqB6naxD61Sqs051O4BVAzn///@vUKhUqNKo0FGo1FGo0lSAMQA "Jelly – Try It Online")
] |
[Question]
[
**The task** is to draw a regular polygon of n sides using only a compass and an unmarked ruler.
**Input** (n) is one of the following 10 numbers: 3, 4, 5, 6, 8, 10, 12, 15, 16, 17.
**Method**: Because you only have a ruler and compass you can only draw points, lines and circles.
A line can only be drawn:
* through two existing points.
A circle can only be drawn:
* with one point as its centre and with its perimeter passing through a second point.
A point can only be drawn:
* at the intersection of two lines,
* at the intersection(s) of a line and a circle,
* at the intersection(s) of two circles,
* at the outset, when you may draw 2 points to get started.
Through this process (and only through this process) you must draw the n lines of the requested n-gon, along with any working required to get to that stage.
EDIT: The position of intersections must be calculated, but lines and circles may be drawn by any means provided by the language.
**Output** is an image of an n-sided regular polygon, showing working.
**Graphically** there are no restrictions on image size, format, line thickness or anything else not mentioned here. However it must be possible to visually distinguish distinct lines, circles and their intersections. Additionally:
* The n lines that make up your n-gon's sides must be a different colour to your 'working' (i.e. any points, circles or other lines) and a different colour again to your background.
* Working can leave the borders of the drawing area, except points, which must all be within the visible bounds of the image.
* A circle can be a full circle or just an arc (as long as it shows required intersections).
* A line is infinite (i.e. leaves the drawing area) or cut off at the two points it goes through. EDIT: A line may be drawn at any length. Points can only be created where the drawn line visually intersects.
* A point can be drawn as you wish, including not marking it.
**Scoring** is twofold, a submission gets 1 point per input it supports, for a maximum of 10 points. In the event of a draw, shortest byte count wins.
Recognition will be given to submissions that can construct n-gons in the fewest steps or are able to construct n-gons outside of the given range, but it won't help your score.
[Background info from Wikipedia](http://en.wikipedia.org/wiki/Compass-and-straightedge_construction)
[Answer]
## Mathematica, ~~2~~ ~~3~~ 4 polygons, 759 bytes
```
S=Solve;n=Norm;A=Circle;L=Line;c={#,Norm[#-#2]}&{a_,b_List}~p~{c_,d_List}:=a+l*b/.#&@@S[a+l*b==c+m*d,{l,m}]{a_,b_List}~p~{c_,r_}:=a+l*b/.S[n[c-a-l*b]==r,l]{c_,r_}~p~{d_,q_}:={l,m}/.S[n[c-{l,m}]==r&&n[d-{l,m}]==q,{l,m}]q={0,0};r={1,0};a=q~c~r;b=r~c~q;Graphics@Switch[Input[],3,{s=#&@@p[a,b];A@@@{a,b},Red,L@{q,r,s,q}},4,{k={q,r};{d,e}=a~p~b;j={d,e-d};d=k~p~j~c~q;{e,f}=j~p~d;A@@@{a,b,d},L/@Accumulate/@{k,j},Red,L@{q,e,r,f,q}},6,{d={q,r};e=#&@@d~p~a;f=e~c~q;{g,h}=a~p~f;{i,j}=a~p~b;A@@@{a,b,f},L@{#-2#2,#+2#2}&@@d,Red,L@{r,i,g,e,h,j,r}},8,{k={q,r};{d,e}=a~p~b;j={d,e-d};d=k~p~j~c~q;{e,f}=j~p~d;g=e~c~q;h=q~c~e;i=r~c~e;{o,s}=g~p~h;{t,u}=g~p~i;o={o,2s-2o};s={t,2u-2t};{t,u}=o~p~d;{v,w}=s~p~d;A@@@{a,b,d,g,h,i},L/@Accumulate/@{k,j,o,s},Red,L@{q,t,e,v,r,u,f,w,q}}]
```
Random bullet points:
* Input is provided via prompt.
* I'm currently supporting inputs **3**, **4**, **6**, **8**.
* From your options, I chose the following plotting styles:
+ Full circles.
+ Lines from endpoint to endpoint, unless a relevant intersection lies outside, in which case I'll hardcode the extent.
+ No points.
+ Workings are black, polygons are red - not for aesthetic but for golfing reasons.
* There's some serious code duplication between the polygons. I think at some point I'll just do a single construction for all of them, enumerating all lines and points and circles along the way, and then just reduce the `Switch` to select the relevant circles and lines for each construction. That way I could reuse a lot of primitives between them.
* The code contains a lot of boilerplate functions which determine all the relevant intersections, and create circles from two points.
* With that in place, I will be adding more polygons in the future.
Here is the ungolfed code:
```
S = Solve;
n = Norm;
A = Circle;
L = Line;
c = {#, Norm[# - #2]} &
{a_, b_List}~p~{c_, d_List} :=
a + l*b /. # & @@ S[a + l*b == c + m*d, {l, m}]
{a_, b_List}~p~{c_, r_} := a + l*b /. S[n[c - a - l*b] == r, l]
{c_, r_}~p~{d_, q_} := {l, m} /.
S[n[c - {l, m}] == r && n[d - {l, m}] == q, {l, m}]
q = {0, 0};
r = {1, 0};
a = q~c~r;
b = r~c~q;
Graphics@Switch[Input[],
3,
{
s = # & @@ p[a, b];
A @@@ {a, b},
Red,
L@{q, r, s, q}
},
4,
{
k = {q, r};
{d, e} = a~p~b;
j = {d, e - d};
d = k~p~j~c~q;
{e, f} = j~p~d;
A @@@ {a, b, d},
L /@ Accumulate /@ {k, j},
Red,
L@{q, e, r, f, q}
},
6,
{
d = {q, r};
e = # & @@ d~p~a;
f = e~c~q;
{g, h} = a~p~f;
{i, j} = a~p~b;
A @@@ {a, b, f},
L@{# - 2 #2, # + 2 #2} & @@ d,
Red,
L@{r, i, g, e, h, j, r}
},
8,
{
k = {q, r};
{d, e} = a~p~b;
j = {d, e - d};
d = k~p~j~c~q;
{e, f} = j~p~d;
g = e~c~q;
h = q~c~e;
i = r~c~e;
{o, s} = g~p~h;
{t, u} = g~p~i;
o = {o, 2 s - 2 o};
s = {t, 2 u - 2 t};
{t, u} = o~p~d;
{v, w} = s~p~d;
A @@@ {a, b, d, g, h, i},
L /@ Accumulate /@ {k, j, o, s},
Red,
L@{q, t, e, v, r, u, f, w, q}
}
]
```
And here are the outputs:




[Answer]
# BBC Basic, 8 polygons: 3,4,5,6,8,10,12,15 sides (also 60 sides)
Download emulator at <http://www.bbcbasic.co.uk/bbcwin/download.html>
I decided not to include 16 sides, simply because my pre-construction was getting rather cluttered. 2 more circles and a line would be needed. BTW 17 sides is very complicated indeed, and would perhaps go best as a separate program.
I got more return for adding 2 circles to my original construction to make the pentagon, as this also gave me access to 10,15 and 60 sides.
```
GCOL 7 :REM light grey
z=999 :REM width of display (in positive and negative direction)
e=1 :REM enable automatic drawing of line through intersections of 2 circles
DIM m(99),c(99),p(99),q(99),r(99) :REM array dimensioning for lines and points
REM lines have a gradient m and y-intercept c. Points have coordinates (p,q) and may be associated with a circle of radius r.
REM PRECONSTRUCTION
ORIGIN 500,500
p(60)=0:q(60)=0 :REM P60=centre of main circle
p(15)=240:q(15)=70 :REM P15=intersection main circle & horiz line
t=FNr(60,15) :REM draw main circle, set radius, SQR(240^2+70^2)=250 units (125 pixels)
t=FNl(1,60,15) :REM L1=horizontal through main circle
t=FNc(15,45,1,60,-1) :REM define P45 as other intersection of main cir and horiz line. overwrite P15 with itself.
t=FNr(15,45):t=FNr(45,15) :REM draw 2 large circles to prepare to bisect L1
t=FNc(61,62,2,45,15) :REM bisect L1, forming line L2 and two new points
t=FNc(30,0,2,60,-1) :REM define points P0 and P30 on the crossings of L2 and main circle
t=FNr(30,60):t=FNc(40,20,3,60,30) :REM draw circles at P30, and line L3 through intersections with main circle, to define 2 more points
t=FNr(15,60):t=FNc(25,5,4,60,15) :REM draw circles at P15, and line L4 through intersections with main circle, to define 2 more points
t=FNx(63,3,4):t=FNl(5,63,60) :REM draw L5 at 45 degrees
t=FNc(64,53,5,60,-1) :REM define where L5 cuts the main circle
e=0 :REM disable automatic line drawing through intersections of 2 circles
GCOL 11 :REM change to light yellow for the 5 sided preconstruction
t=FNx(65,1,4):t=FNr(65,0) :REM draw a circle of radius sqrt(5) at intersection of L1 and L4
t=FNc(66,67,1,65,-1) :REM find point of intersection of this circle with L1
t=FNr(0,67) :REM draw a circle centred at point 0 through that intersection
t=FNc(36,24,6,60,0) :REM find the intersections of this circle with the main circle
REM USER INPUT AND POLYGON DRAWING
INPUT d
g=ASC(MID$(" @@XT u X @ T",d))-64 :REM sides,first point: 3,0; 4,0; 5,24; 6,20; 8,53; 10,24; 12,0; 15,20
IF d=60 THEN g=24 :REM bonus polygon 60, first point 24
FORf=0TOd
GCOL12 :REM blue
h=(g+60DIVd)MOD60 :REM from array index for first point, calculate array index for second point
t=FNr(h,g) :REM draw circle centred on second point through first point
t=FNc((h+60DIVd)MOD60,99,99,60,h) :REM calculate the position of the other intersection of circle with main circle. Assign to new point.
GCOL9 :REM red
LINEp(g),q(g),p(h),q(h) :REM draw the side
g=h :REM advance through the array
NEXT
END
REM FUNCTIONS
REM line through a and b
DEFFNl(n,a,b)
m(n)=(q(a)-q(b))/(p(a)-p(b))
c(n)=q(a)-m(n)*p(a)
LINE -z,c(n)-m(n)*z,z,c(n)+m(n)*z
=n
REM radius of circle at point a passing through point b
DEFFNr(a,b)
r(a)=SQR((p(a)-p(b))^2+(q(a)-q(b))^2)
CIRCLEp(a),q(a),r(a)
=a
REM intersection of 2 lines: ma*x+ca=mb*x+cb so (ma-mb)x=cb-ca
DEFFNx(n,a,b)
p(n)=(c(b)-c(a))/(m(a)-m(b))
q(n)=m(a)*p(n)+c(a)
=n
REM intersection of 2 circles a&b (if b>-1.) The first step is calculating the line through the intersections
REM if b < 0 the first part of the function is ignored, and the function moves directly to calculating intersection of circle and line.
REM inspiration from http://math.stackexchange.com/a/256123/137034
DEFFNc(i,j,n,a,b)
IF b>-1 c(n)=((r(a)^2-r(b)^2)-(p(a)^2-p(b)^2)-(q(a)^2-q(b)^2))/2/(q(b)-q(a)):m(n)=(p(a)-p(b))/(q(b)-q(a)):IF e LINE -z,c(n)-m(n)*z,z,c(n)+m(n)*z
REM intersection of circle and line
REM (mx+ c-q)^2+(x-p)^2=r^2
REM (m^2+1)x^2 + 2*(m*(c-q)-p)x + (c-q)^2+p^2-r^2=0
REM quadratic formula for ux^2+vx+w=0 is x=-v/2u +/- SQR(v^2-4*u*w)/2u or x= v/2u +/- SQR((v/2u)^2 - w/u)
u=m(n)^2+1
v=-(m(n)*(c(n)-q(a))-p(a))/u :REM here v corresponds to v/2u in the formula above
w=SQR(v^2-((c(n)-q(a))^2+p(a)^2-r(a)^2)/u)
s=SGN(c(n)+m(n)*v-q(a)):IF s=0 THEN s=1 :REM sign of s depends whether midpoint between 2 points to be found is above centre of circle a
p(i)=v+s*w:q(i)=m(n)*p(i)+c(n) :REM find point that is clockwise respect to a
p(j)=v-s*w:q(j)=m(n)*p(j)+c(n) :REM find point that is anticlockwise respect to a
=n
```
The program does a pre-construction before asking for any user input. This is sufficient to define at least 2 points on the main circle which correspond to adjacent vertices of a 3,4,5,6,8,10,12,15 or 60 sided figure. The points are stored in a set of 99-element arrays, in which elements 0-59 are set aside for equally spaced points around the circumference. This is mainly for clarity, the octagon does not fit perfectly into 60 points so some flexibility is needed there (and also for the 16-gon if it were included.) The image looks like the image below, in white and grey, with only the two circles in yellow being exclusively dedicated to shapes with multiples of 5 sides. See <http://en.wikipedia.org/wiki/Pentagon#mediaviewer/File:Regular_Pentagon_Inscribed_in_a_Circle_240px.gif> for my preferred pentagon drawing method. The jaunty angle is to avoid vertical lines, as the program cannot handle infinite gradients.

The user inputs a number `d` for the number of sides required. The program looks up in the array the index of the first of the two points (the next one is 60/d away in a clockwise direction.)
The program then loops through the process of drawing a circle centred on the second point that passes throug the first, and calculating the new intersection in order to walk its way round the main circle. The construction circles are drawn in blue, and the required polygon is drawn in red. The final images look like this.
I'm quite pleased with them. BBC Basic performs the calculations accurately enough. However its apparent (particularly with 15 and 60 sides) that BBC Basic tends to draw circles with a slightly smaller radius than it should.

] |
[Question]
[
[OEIS A090461](https://oeis.org/A090461) details the ‘numbers k for which there exists a permutation of the numbers 1 to k such that the sum of adjacent numbers is a square’. This has also been the subject of [Matt Parker’s Numberphile](https://youtu.be/G1m7goLCJDY?si=jHHwz-yRH6N26SeK) and [Alex Bellos’ Monday puzzle](https://www.theguardian.com/science/2023/sep/18/can-you-solve-it-the-man-who-made-indias-trains-run-on-time).
This [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge is related to the square sum problem above and asks you to find the longest permutations of integers from 1 to k that have all of the neighbouring pairs sum to squares. Repetition is not allowed, but not all of the integers need to be used where this is impossible.
For example, when provided with the argument of `15`, the program should output `[[8, 1, 15, 10, 6, 3, 13, 12, 4, 5, 11, 14, 2, 7, 9], [9, 7, 2, 14, 11, 5, 4, 12, 13, 3, 6, 10, 15, 1, 8]]`. When provided with an argument of `8`, it should output `[[6, 3, 1, 8], [8, 1, 3, 6]]` (for 8, the longest possible permutation is only 4 numbers). All possible longest permutations should be output, but the order in which they are provided does not matter.
To expand on this further, for 15, first permutation given above is valid because `8 + 1 = 9` (32), `1 + 15 = 16` (42), `15 + 10 = 25` (52) and so forth.
The [restricted-time](/questions/tagged/restricted-time "show questions tagged 'restricted-time'") tag has been included to slightly increase the challenge and make brute forcing an answer less attractive. A valid entry should be able to return an answer for any single input from 3 to 27 within 60 seconds when run on [tio](https://tio.run) or an equivalent environment. Otherwise, standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. This includes the [standard input-output rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods?answertab=scoredesc#tab-top).
Interestingly, the sequence of lengths of such maximum-length permutations does not seem to have been posted on OEIS yet. I may subsequently post this there.
Further examples below. In each case, I’ve only given the first permutation for each input for brevity, but all of the valid ones should be returned.
For inputs less than 3, there are no valid answers but this does not have to be handled by your program or function. (You can assume there is at least one valid permutation.)
```
Input -> Output
2 -> any output or an error (does not have to be handled by your program or function)
3 -> [3,1] and 1 further permutation
4 -> [3,1] and 1 further permutation
5 -> [5,4] and 3 further permutations
6 -> [6,3,1] and 1 further permutation
7 -> [6,3,1] and 1 further permutation
8 -> [8,1,3,6] and 1 further permutation
9 -> [8,1,3,6] and 1 further permutation
10 -> [10,6,3,1,8] and 1 further permutation
11 -> [10,6,3,1,8] and 1 further permutation
12 -> [10,6,3,1,8] and 1 further permutation
13 -> [11,5,4,12,13,3,6,10] and 3 further permutation
14 -> [10,6,3,13,12,4,5,11,14,2,7,9] and 3 further permutation
15 -> [9,7,2,14,11,5,4,12,13,3,6,10,15,1,8] and 1 further permutation
16 -> [16,9,7,2,14,11,5,4,12,13,3,6,10,15,1,8] and 1 further permutation
17 -> [17,8,1,15,10,6,3,13,12,4,5,11,14,2,7,9,16] and 1 further permutation
18 -> [17,8,1,15,10,6,3,13,12,4,5,11,14,2,7,9,16] and 1 further permutation
19 -> [19,17,8,1,15,10,6,3,13,12,4,5,11,14,2,7,9,16] and 7 further permutations
20 -> [20,16,9,7,2,14,11,5,4,12,13,3,6,19,17,8,1,15,10] and 15 further permutations
21 -> [21,15,10,6,19,17,8,1,3,13,12,4,5,20,16,9,7,2,14,11] and 7 further permutations
22 -> [18,7,9,16,20,5,11,14,22,3,13,12,4,21,15,10,6,19,17,8,1] and 17 further permutations
23 -> [22,3,1,8,17,19,6,10,15,21,4,12,13,23,2,14,11,5,20,16,9,7,18] and 5 further permutations
24 -> [24,12,13,23,2,14,22,3,1,8,17,19,6,10,15,21,4,5,20,16,9,7,18] and 77 further permutations
25 -> [23,2,14,22,3,13,12,4,21,15,10,6,19,17,8,1,24,25,11,5,20,16,9,7,18] and 19 further permutations
26 -> [26,23,2,14,22,3,13,12,4,21,15,10,6,19,17,8,1,24,25,11,5,20,16,9,7,18] and 23 further permutations
27 -> [27,22,14,2,23,26,10,15,21,4,12,13,3,6,19,17,8,1,24,25,11,5,20,16,9,7,18] and 69 further permutations
```
[Answer]
# [R](https://www.r-project.org), 139 bytes
```
\(n,f=\(a,b,i=which(!(a+b[1])^.5%%1))`if`(sum(i),unlist(Map(\(i)f(a[-i],c(a[i],b)),i),F),list(b)))(a=f(1:n,{},1:n))[(l=lengths(a))==max(l)]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=jY9BasMwEEXPkoXJTDoOOBAoBW276wlsVx47kq0iq4kl40LpCXKEbJxFD5XbVMQ5QFePB__D_5frMN_W9tO1ygd5VEMvJxM6ydZKPnxwo1yQ_jTyoLz4HYNOn2_nAhxpUQBTTUZMnWk6WAE_1XlW4vt2nyQZYmV0BX7swSCNzhof4I2PUETXwHlqSmoiI2pEiqFXpHsqKgILDdmLo-8fikDMwQqrXBs6D4woRM9fYLF8TNr87wHs9rg05nnhHw)
**Ungolfed**
```
longest_perm_with_all_adjacent_squares=
function(n){
# first define the recursive helper function f:
f=function(a,b={}){
# a is a vector of values that haven't been used yet, to choose the next value from;
# b is the (initially empty) growing result containing only adjacent values that sum to squares
if(length(b)==0)i=seq(along=a) else i=which(sqrt(a+b[1])%%1==0)
# i is the vector of indices of a that we can use at each step
if(length(i)==0)return(list(b))
# if we can't use any more values from a, then just return the result-so-far
else return(unlist(lapply(i,function(i)f(a[-i],c(a[i],b))),recursive=F))
# otherwise, prepent each valid value from a to b, and perform a recursive call
}
# launch the helper function with the sequence 1..n in a, and leaving b empty by default:
ans=f(1:n)
# finally, select only the results with maximum length:
ans[lengths(ans)==max(lengths(ans))]
}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~29~~ 26 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
0ịịḟ⁸⁸;Ɱ
²€_Ɱf€RɓW€ç€Ẏ¥ƬṖṪ
```
A monadic Link that accepts a positive integer greater than \$2\$ and yields all possible sequences of maximal length.
**[Try it online!](https://tio.run/##y0rNyan8/9/g4e5uENox/1HjDiCyfrRxHdehTY@a1sQDWWlAOujk5HAgdXg5kHi4q@/Q0mNrHu6c9nDnqv///xuZAwA "Jelly – Try It Online")**
### How?
```
0ịịḟ⁸⁸;Ɱ - Link 1: list of ints, Sequence; list of lists of ints, Continuations
0ị - last element of {Sequence}
ị - index into {Continuations} -> ints that will sum to a square
ḟ⁸ - filter out elements of left argument (Sequence)
-> removes those that would cause duplicates
⁸;Ɱ - concatenate each to left argument
-> list of new, longer sequences (empty if none possible)
²€_Ɱf€RɓW€ç€Ẏ¥ƬṖṪ - Main Link: integer, k > 2
²€ - square each {[1..k]} -> [1, 4, 9, 16, ..., k²]
_Ɱ - subtract mapped across {[1..k]}
f€R - filter each keeping those in [1..k]
-> Continuations by current value:
[[3, 8, 15, ...], [2, 7, 14, ...], [1, 6, 13, ...], ...]
ɓ - start a new dyadic chain - f(k, ValidContinuations)
W€ - wrap each of {[1..k]} -> [[1], [2], [3], ...]
Ƭ - start with Seqs=that and collect while distinct, applying:
¥ - last two links as a dyad - f(Seqs, Continuations):
ç€ - call Link 1 as a dyad - f(Sequence, Continuations)
Ẏ - tighten back to a list of sequences
Ṗ - pop -> removes the empty list found last
Ṫ - tail -> maximal length sequences
```
---
#### 21 bytes (k=25)
Not brute force, but still times out for \$k=26\$:
```
W€;þẎ-.ịSƲƲƇQƑƇʋƬRṖṪ
```
[Try it online!](https://tio.run/##ATQAy/9qZWxsef//V@KCrDvDvuG6ji0u4buLU8OGwrLGssaHUcaRxofKi8asUuG5luG5qv///zE2 "Jelly – Try It Online")
[Answer]
# [APL (Dyalog APL)](https://www.dyalog.com/products.htm), 37 [bytes](https://github.com/abrudz/SBCS)
```
{×≢n←⊃,/(⊂,¨⍺∩⊢~⍨(×⍨⍺)-⊢/)¨⍵:⍺∇n⋄⍵}⍨⍳
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70qpTIxJz89PrEgZ8GCpaUlaboWNwPdHrVNqD48_VHnojwg61FXs46-xqOuJp1DKx717nrUsfJR16K6R70rNIBKekFCmrpAEX1NkPRWK7CS9rxH3S1AXi1YwWaowa6P-qaCDGybWF0EpN2AChSA6hSAtLrCo7ZJCupAa5qLNNU1FLTVNQ6tN9QGOgHI1VSvPbTC6FHbZKBRRuYQw2CuBQA)
Recursive approach, generates all results from 3 to 27 in a second.
[Answer]
# Python3, 238 bytes:
```
def f(k):
q=[([i],{*range(1,k+1)}-{i})for i in range(1,k+1)]
D={}
while q:
s,r=q.pop(0)
if len(s)>1:D[len(s)]=D.get(len(s),[])+[s]
for i in range(1,int((2*k)**0.5)+1):
if(K:=i**2-s[-1])in r:q+=[(s+[K],r-{K})]
return D[max(D)]
```
[Try it online!](https://tio.run/##ZY5BasMwEEXX9SlmOSPLJnZoKAZlpZ2PILQIVEqEU1mWHNpifHZXJpvS7uYz/Pd@@J5voz@@hbht78aCxYG6AiahUDnNFxYv/mqw4UPZ0FotbiU7RnDgPPx@6QKkWNYCPm/ubmDKDEg8iqkOY8AD5egs3I3HROemk@p5aiHrq5nxmbjSVKqUWfBP4vyM2LKBGDvUr5SVuyJDse@EY6ytkqoaTXulm8q8P5Wq1zxWS7/u86KZH9GDVB@XL5Sktz@KI29PmfkS4q6y6Ii2Hw)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 55 bytes
```
≔…·¹Nθ≔EθΦ⁻Xθ²ι№θληUMθ⟦ι⟧FθF⁻§η⊖↨ι⁰ι⊞θ⁺ι⟦κ⟧⪫Φθ⁼LιL§θ±¹¶
```
[Try it online!](https://tio.run/##NU87T8MwEN75FVans2Qk6MLAVAqVgmgVsZYOJjliq8658aPw7805hMHy6bvvdZ3RofPalbKJ0Q4EDXUuR3vFd00Dwr0SDV1yOuTxEwNIqcQkH28W8l5fYFJiZ13i5d5SjtD6b54ZXTPX8tv6TKkCTla5YTnrtn4cNfUVP9oTY18@CJikmP8/q01qqMcfMEo8YxdwRErYw5OOCFaJu9nPSinaHE11arl63RzPJ8mWbbCc/OotwVKROS9T1i7CG9KQDNSCy/ifxpwDDjrx8VLOEasPWrFfKeuHcnt1vw "Charcoal – Try It Online") Link is to verbose version of code. Program was originally more efficient but I slowed it down slightly in the name of code golf, but not so much that it can't easily solve `n=27` on TIO. Explanation:
```
≔…·¹Nθ
```
Make a range from `1` to `n`.
```
≔EθΦ⁻Xθ²ι№θλη
```
For each element of that range, make a list of all valid adjacent numbers.
```
UMθ⟦ι⟧
```
Wrap each element of that range in a list so that it can be the first element of a potential permutation.
```
Fθ
```
Loop over all potential permutations.
```
F⁻§η⊖↨ι⁰ι
```
Loop over all remaining next valid adjacent numbers.
```
⊞θ⁺ι⟦κ⟧
```
Add the new permutation to the list.
```
⪫Φθ⁼LιL§θ±¹¶
```
Output all permutations of maximal length.
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), 127 bytes
```
f=lambda k,p=0:(r:=range(1,k+1))and(c:=[l+[v]for l in p or[[i]for i in r]for v in r if(l[-1]+v)**.5%1==(v in l)])and f(k,c)or p
```
**[Try it online!](https://tio.run/##XY1BCsIwEEX3nmIQhIyt0ipCCUS8R@ii1kRDYhqjFkR69tqkVMRZDe/Pn@dej0tjt4XzfS@Zqa7HUwU6dSyjxFPmK3sWJE91kiNW9kRqyrhJeFvKxoMBZcFB4zlXEagAfFzbuIKSxPBVXiYtLpfr3SJnjMTIYBkegiQ6rXEouD7UdKxF6zaFTYF0BsPcxe0pbC3uwEIDI3Re2QeRcz3At@5gtYe3EZZ8j7GDwx/iWYkdnY8PgnBKgvd7NUonw4R/rdh/AA "Python 3.8 – Try It Online")**
[Answer]
# JavaScript (ES7), 137 bytes
```
f=(n,k=n)=>(P=(a,...p)=>o=p[a.map(v=>(++v+p[0])**.5%1||P(a.filter(x=>v+~x),v,...p)),k]?[...o,p]:o)([...Array(n).keys(o=[])])+o?o:f(n,k-1)
```
[Try it online!](https://tio.run/##JY1BT8MwDIXv/Ipo0iR7aSMGQkgb6cSVA0ziWHqIRtqVljhKqrKKwV8vzji9Z3/v2R9mNPEQWj/kjt7tPNcaXNZph7qAvQaTKaU8D6R9adSn8TAykXKUvryucLVSd8v1@bwHo@q2H2yAky5G@XvCbPzvYtZVu5ItZb7aEELyjyGYCRyqzk4RSJcVVihpR5s6/c/XONcUoLeDcEKL2y3LgxY392ykRPF9JUSCwUbG3MEtbw7kIvVW9dTAIvUWQnJRsubFZeC86q1rhuNla1z8siG@ucSeXl@eVRxC65q2noCjmEIM@fjP/Ac "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f is a recursive function taking:
n, // n = input
k = n // k = target permutation length (+1)
) => ( //
P = // P is a recursive function taking:
(a, // a[] = source array
...p) => // p[] = permutation of a[]
o = p[ //
a.map(v => // for each value v in a[]:
(++v + // increment v ([0..n-1] -> [1..n])
p[0]) // abort if v + p[0] ...
** .5 % 1 || // ... is not a perfect square
P( // otherwise, do a recursive call to P:
a.filter(x => // pass a copy of a[] ...
v + ~x // ... where v is removed
), //
v, ...p // insert v at the beginning of p[]
) // end of recursive call
), // end of map()
k // test p[k]
] ? // if it's defined:
[...o, p] // append p[] to o[]
: // else:
o // leave o[] unchanged
)([...Array(n).keys( // initial call to P with a[] = [0..n-1]
o = [] // and o[] initialized to an empty array
)]) + o ? // if o[] is non-empty:
o // return it
: // else:
f(n, k - 1) // try again with k - 1
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 120 bytes
```
->n{r=z=w=[*1..n];r,w=w,r.flat_map{|b|(z-[*b]).map{|a|[a,*b]}}.reject{|a|b=0;a.any?{|a|b*(b+b=a)**0.5%1>0}}while w[0];r}
```
[Try it online!](https://tio.run/##Lc3LCoMwEIXhV3FT0FSHKJQuZOyDBCmTEmmLDRKUeMk8e2qly@9fnOMmvcQOY9HYzeGKHpUoAWxbu9yjzx10PY33Dw1b0CFdCyV0m8FhCorynczgzNs8xl/SKGsCssvtkEj1WSNlQki4nMpGMvvnqzeJV3L/4JhWANX1vziHIenU3HL8Ag "Ruby – Try It Online")
# [Ruby](https://www.ruby-lang.org/), 96 bytes
```
f=->n,z=n{w=[*1..n].permutation(z).reject{|a|b=0;a.any?{|a|b*(b+b=a)**0.5%1>0}};w[0]?w:f[n,z-1]}
```
[Try it online!](https://tio.run/##HczRCoMgGEDhV9nNQN360WAMFtaDiBc6FDbIiRhW6rNb7PJ8FycsemvN8m509527nLggDMBJ8CbMS1Tx83NoxxDM17xjLqpoTgcFym3TvwjSN80VJoTC48pGWuuQBJVTellxTjsma0M9QP/EMCufy1r8xYr15AM "Ruby – Try It Online")
Super-slow, times out for n=11.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 109 bytes
```
f=(n,s=[[]],t=[])=>s.map(x=>(g=n=>n&&g(n-1,(n+x[0])**.5%1||x.includes(n)||t.push([n,...x])))(n))|t<f?s:f(n,t)
```
[Try it online!](https://tio.run/##HY1BT8MwDIXv/Ipo0qZ4bSOKNCHRpdw5wIFj6aHqkqxTcKo4gyLKby/uTs9@33v2pfvqqI/DmAoMJ7MsVkvMSTdN2@ZJNy3omtRnN8pJ19Jp1DXudk5iUeYSs6m5b2G/V4dtOc@TGrD315MhiTDPSY1XOssGc6XU1AIA2zCno32mJ8tfEiyVDVF6kwQKLcqK5ajFwyMPWQbi906IFUZDjLkCFTt9QAreKB@c3Ky9jci4mLEW9W3hvPIGXTrf3A7p20T6wJW9vL@9KkpxQDfYH8lRWEMM@fjf8g8 "JavaScript (Node.js) – Try It Online")
# [JavaScript (Node.js)](https://nodejs.org), 106 bytes
```
n=>f=(s=[[]],t=[],i=n)=>i?s.map(x=>(i+x[0])**.5%1||x.includes(i)||t.push([i,...x]))&&f(s,t,--i):t<f?s:f(t)
```
[Try it online!](https://tio.run/##HYzBTsMwEETvfIVViWq3cSyKVCE1dXrrgQMcOJocotROjcwmyroQRPj24PQ0u/Nm5qP@qrkZfB9z6s52PumZdOk0sDamqmTUppJeE@rSH1l91j2MugSfjeahws1G7e630zQqT024ni2Dx2mKqr/yBYyXSqmxQlyvHbCMMs897uPBHXnvIOJcuG6AYKMgocW2SHLQ4vEpHVmG4vdOiAUOlhM@ASFgkbymI@6CVaFrYbU0VyJL1SxpXt6e1FDBUhsvN7cm/rYDv9PCnt9eXxTHwVPr3Q@kKC6hBNP43/wP "JavaScript (Node.js) – Try It Online")
[Answer]
# [R](https://www.r-project.org), 99 bytes
```
\(n){a=b=1:n;while(length(g<-unlist(Map(\(y)lapply(setdiff(b[!(b+y[1])^.5%%1],y),c,y),a),F)))a=g;a}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3k2M08jSrE22TbA2t8qzLMzJzUjVyUvPSSzI00m10S_NyMotLNHwTCzRiNCo1cxILCnIqNYpTS1Iy09I0kqIVNZK0K6MNYzXj9ExVVQ1jdSo1dZJBRKKmjpumpmaibbp1Yi3EqqVpGkbmmhD2ggUQGgA)
Hopefully this is a suitable interval before posting my own answers to my challenge. This is an anonymous function that takes a single numeric argument `n` and returns a list of integer vectors.
## Ungolfed
```
join_lists <- function(x) {
unlist(x, recursive = FALSE)
}
find_max_ss_permutations <- function(n) {
# Initialize two vectors a and b with numbers from 1 to n
a <- b <- 1:n
# Iterate while there are permutations with adjacent numbers summing to squares
while ({
g <- join_lists(lapply(a, function(y) {
# Filter elements from b where adjacent numbers sum to squares
filtered_b <- setdiff(b[!(b + y[1])^.5 %% 1], y)
# Extend existing vector with filtered elements
lapply(filtered_b, function(item) c(item, y))
}))
length(g)
}) {
# Update a with the new permutations
a <- g
}
# Return the longest possible permutations satisfying the square sum condition
return(a)
}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dVPNbtQwEJY45ikGVZUcsUVaJARC9MChlZA4gThVJXKSSdaVMw72uJuA9km4lANvwWtw6dPUP2mXRfSQjJLM9zfj_Phpb25-ee5OXt8--XNlFFVaOXbw9gQ6Tw0rQ2Iq4XsB4Cl-EtMKLDbeOnWNcArn7z58OiuLXdEpaqtBTpVz1Yh28Cwj-pCKMtURvCfFSmr1DYG3Bq6xYWMdSJDUQg1bxRsgP9QYXnbWDLAGNkABKyNhHW_rN1RkMkYrGWG7UTrwbdAiyHAd2EiUsr2SDRI_cDs_DIr6SO6--gBygTHziOgU-qi0H4zQchz1LORqH2rOoaKTc6WDF0CNQ1BZrIc42dJ_xA-FAbpEgG2VEjrkVnWdqC-eihqewXyxviy_PH8Jx8ewvlzBXCbQIn42MYbp4RSMxkx5qDn4Pe-DtYRZwuxF_0qlGIcSmlSjUpbaLVUj9bwRfXza7fN_Htu4CJlFwyaAcJv2oJY9pMa0wz5Ci-T-CD4ie0sJoQ316BhG45yq9T9rdKG6bk47C815dmmSjaFWxaZAaBOdkOFg5tP9-7HjKV68KnPL_Y9wBw)
] |
[Question]
[
Take the sequence of all natural numbers in binary, `(1, 10, 11, ..)` then write them vertically beside each-other like this (least significant bit on top; 0s have been replaced with spaces):
```
1 1 1 1 1 1 1 1 1
11 11 11 11
1111 1111
11111111
11
```
Notice there are areas of connected 1s in the binary representation of the number.
Your task is, for a given `n`, calculate the biggest continuous area in the binary representation of all numbers less than `n`. If you start with n=1 and consider all numbers less than or equal to n, the sequence starts like this:
```
(1, 1, 3, 3, 3, 4, 7, 7, 7, 7, 7, 7, 8, 11, 15, 15, 15...)
```
Areas are joined if they connect horizontally or vertically, diagonals don't count.
[sequence](/questions/tagged/sequence "show questions tagged 'sequence'") rules apply: you can choose to consider either all numbers *strictly less than* N or those *less than or equal to* N, and either 0 or 1. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest answer wins.
[Answer]
# [JavaScript (V8)](https://v8.dev/), 67 bytes
Prints the sequence infinitely.
```
for(m=n=0;g=k=>k?!(k&k+1)+g(k>>1):s;print(m=m>s?m:s))s=n&++n?g(n):1
```
[Try it online!](https://tio.run/##DcpBCoAgEADAt3QRFwnyFsrqWyRIbHETV/y@Ned50kxy9dLGPs@17rfrioyHz0gYKG6aFBkLJmsKwYIT33rh8a8aJFYnAIKsjOGYNYOza30 "JavaScript (V8) – Try It Online")
### How?
This is based on the observation that the biggest local area is always those of the pattern formed by the leading 1's (in red below).
If the area of the leading pattern is \$N\$, any non-leading pattern may at best reach an area of \$N-1\$ (like the green one in figure 2).
[](https://i.stack.imgur.com/3pPPn.png)
(Figure 1 is for \$n=8\$ to \$n=15\$. Figure 2 is for \$n=16\$ to \$n=23\$.)
### Commented
```
for( // infinite loop:
m = // m = current maximum
n = 0; // n = counter
g = k => // g is a helper recursive function taking k
// and returning the sum of s and the number
// of leading 1's in k
k ? // if k is not 0:
!( // increment the final result if ...
k & k + 1 // ... k and k+1 have no bits in common
) + // (i.e. k+1 is a power of 2)
g(k >> 1) // do a recursive call with floor(k / 2)
: // else:
s; // stop and return s
print( // after each iteration, print ...
m = m > s ? m // ... the maximum of m and s
: s // (and update m accordingly)
) //
) //
s = // s is the area of the pattern of leading 1's
n & ++n ? // increment n; if n is not a power of 2:
g(n) // update s to g(n)
: // else:
1 // reset s to 1
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~14~~ 13 bytes
*1 byte saved thanks to [@Suever](https://codegolf.stackexchange.com/users/51939/suever)*
```
:B4&1ZIXz5#XM
```
Inputs `n` and outputs the `n`-th term of the sequence, using the "less or equal" definition.
Try it [MATL online](https://matl.io/?code=%3AB4%261ZIXz5%23XM&inputs=13&version=22.7.4)!
### Explanation
```
: % Implicit input: n. Range [1 2 ... n]
B % Convert to binary. Gives an n-row matrix
4&1ZI % Label connected components, using 4-neighbourhood. This labels each
% connected component of cells equal to 1 with an integer, starting at 1
Xz % Nonzeros. Removes zeros and reshapes into a column vector
5#XM % Second output of 'mode' function: gives the number of times that the
% mode occurs. Implicit display
```
[Answer]
# Python3, 333 bytes:
```
E=enumerate
def f(n):
t=[*map(bin,range(1,n))]
k=[i[2:][::-1]+'0'*(max(map(len,t))-len(i))for i in t]
q,l=[(x,y)for x,r in E(k)for y,u in E(r)if'1'==u],[]
while q:
Q,s=[q.pop(0)],1
while Q:
x,y=Q.pop(0)
for X,Y in[(0,1),(0,-1),(1,0),(-1,0)]:
C=(x+X,y+Y)
if C in q:Q+=[C];q.remove(C);s+=1
l+=[s]
return max(l)
```
[Try it online!](https://tio.run/##PVDBboMwDL3zFblhF1NBd5mockL9AG6tohyYFtaoECCEDb6eJTDtYuv5@dnPHlb37M3b@2C37caVmTtla6eiT9WwBgwWEXNcnLp6gA9tyNbmS0FOBlFG7MWFFpdCiqJIc5nEWXyCrl4gdLfKkENMfQaN2PSWaaYNc143UssFLLTu5YVsIG7w2uFK8wEt6ibOY85nScKrfp66VWz0jlhFExfjeegHyFBS7ksHWwXWT1x59ccGHMbe6eHHCsgoR/IxDSmnzMc0JLkrWclhSe60Jo9dyXTDymBnLKqEi1Jex7NVXf@toMTrlPCwuvXM5A1a5WZrWPhAi9tgtXEgGn/9//HH@y508ftw@wU)
[Answer]
# [Python](https://www.python.org), ~~95 93 92~~ 88 bytes
```
m=n=0
while g:=lambda k:k and(k&k+1<1)+g(k>>1):print(m:=max(m,s:=n&(n:=n+1)<1or g(n)+s))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3I3Jt82wNuMozMnNSFdKtbHMSc5NSEhWyrbIVEvNSNLLVsrUNbQw1tdM1su3sDDWtCooy80o0cq1scxMrNHJ1iq1s89Q08oCktqGmjWF-kUK6Rp6mdrGmJsR8qDUw6wA)
Outputs `True` instead of `1`. [+2 bytes to fix this](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3o3Jt82wNuMozMnNSFdKtbHMSc5NSEhWyrbIVEvNSNLLVsrUNbQw1tdM1su3sDDWtCooy80o0cq1scxMrNHJ1iq1s89Q08oCktqGmjWF-kUK6Rp6mdrGmtoEmxAaoRTALAQ)
Port of Arnauld's JS answer.
*-2 thanks to @Arnauld*
*-4 thanks to @97.100.97.109*
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 28 bytes
```
FN«≔⁺∧&ι⊕ιθL§⪪⍘⊕ι²0⁰θ⊞υθ⟦I⌈υ
```
[Try it online!](https://tio.run/##VYwxC8IwFITn9leETi9Qobo6tU4FlUJHcYjtsw0kaU1etCD@9hgRB4c77uO460Zhu0moEK6TZVCb2dPR6wta4Jw906R0Tg4GGuUdlKaHStJDOvxEmbPadBY1GsKInOfsFrVHM9AIJdWmxwXaWUmCSjhsyUozwP8oZ5uorMiiF/z7sU2TxrsR/A/ijuC0E47gIBapvQbP@Tl2rxDWRVjd1Rs "Charcoal – Try It Online") Link is to verbose version of code. Outputs the first `n` terms. Explanation:
```
FN«
```
Repeat `n` times.
```
≔⁺∧&ι⊕ιθL§⪪⍘⊕ι²0⁰θ
```
If the effective 1-based index is a power of 2, then start the new area from 1, otherwise add the number of leading 1s to it.
```
⊞υθ
```
Save the size of the latest area.
```
⟦I⌈υ
```
Output the size of the largest area.
I did find some relevant sequences in the OEIS:
* A000225 is the list of indices where the size of the largest contiguous area equals the index.
* A090996 is the number of leading 1s.
* A267604 appears to be list of indices where the new area overtakes the old area in size.
Unfortunately I was unable to use any of these sequences to reduce my byte count.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
B«\)LÐṀFS)Ṁ
```
A monadic Link that accepts \$n\$ and yields the largest binary area when arranging the numbers \$1\$ to \$n\$ inclusive.
**[Try it online!](https://tio.run/##y0rNyan8/9/p0OoYTZ/DEx7ubHAL1gSS/w@3P2pa8/@/mTEA "Jelly – Try It Online")**
### How?
```
B«\)LÐṀFS)Ṁ - Link: positive integer, n
) - for each (i in [1..n]):
) - for each (j in [1..i]):
B - convert (j) to binary
\ - cumulative reduce by:
« - minimum (i.e. zero any bits after the first 0)
ÐṀ - keep those maximal under:
L - length (e.g. j = 27 -> [zeroed(binary(16))..zeroed(binary(27))])
F - flatten
S - sum
Ṁ - maximum
```
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), 85 bytes
```
lambda n:max((j:=2**len(bin(n))>>3)-1,sum(bin(i*2)[2:].find('0')for i in range(j,n)))
```
An anonymous function that accepts a positive integer, `n`, and returns the largest binary area formed using the numbers less than `n`.
**[Try it online!](https://tio.run/##RYvBDoIwEETvfsWGC7sEDZSLaUJ/RD2UQLWELqTUREP89kq9OLf3ZmZ5h8fMzXnx0bTXOGnX9RpYOv1CHGUrimIaGDvLyERKNXSsy/XpfsYWgi5C3k7Gco95lZOZPViwDF7zfcCx3E8Ukw3DGv5FXUJdVSQPsGfxlgOabEsbqcQHWgWbwYSUOKP4BQ "Python 3.8 (pre-release) – Try It Online")**
] |
[Question]
[
Given a multi-dimensional rectangular array of non-negative integers, pad it with the minimal number of zeroes so that only zeroes are "touching the edges" of the array, in every dimension.
The output must remain rectangular, have the same number of dimensions as the input, and be no smaller than the input.
## Example
For the input:
```
[[1, 3, 0],
[2, 6, 7],
[4, 0, 2],
[0, 0, 0]]
```
Here is the array again with the elements which are "touching the edge" ***highlighted***:
```
[[***1***, ***3***, ***0***],
[***2***, 6, ***7***],
[***4***, 0, ***2***],
[***0***, ***0***, ***0***]]
```
The expected output is:
```
[[0, 0, 0, 0, 0],
[0, 1, 3, 0, 0],
[0, 2, 6, 7, 0],
[0, 4, 0, 2, 0],
[0, 0, 0, 0, 0]]
```
Notice that:
* In the first row, even though there was already a zero on the right, we still had to add an extra zero on the right to keep the array properly rectangular
* The bottom row was already all zeroes, so no extra row needed to be added there
---
For the 1-dimensional array `[3, 4, 9, 0, 0]`, the edges are `[***3***, 4, 9, 0, ***0***]`.
---
For this 3-dimensional array:
```
[[[4, 0, 4, 1],
[0, 0, 5, 8],
[6, 0, 0, 0],
[0, 3, 7, 0]],
[[4, 9, 8, 5],
[0, 6, 4, 0],
[0, 0, 0, 3],
[0, 9, 6, 1]],
[[0, 4, 7, 9],
[0, 2, 0, 6],
[0, 0, 0, 0],
[7, 0, 3, 0]],
[[0, 5, 3, 5],
[0, 0, 0, 0],
[6, 5, 3, 0],
[4, 6, 0, 8]]]
```
the edges are:
```
[[[***4***, ***0***, ***4***, ***1***],
[***0***, ***0***, ***5***, ***8***],
[***6***, ***0***, ***0***, ***0***],
[***0***, ***3***, ***7***, ***0***]],
[[***4***, ***9***, ***8***, ***5***],
[***0***, 6, 4, ***0***],
[***0***, 0, 0, ***3***],
[***0***, ***9***, ***6***, ***1***]],
[[***0***, ***4***, ***7***, ***9***],
[***0***, 2, 0, ***6***],
[***0***, 0, 0, ***0***],
[***7***, ***0***, ***3***, ***0***]],
[[***0***, ***5***, ***3***, ***5***],
[***0***, ***0***, ***0***, ***0***],
[***6***, ***5***, ***3***, ***0***],
[***4***, ***6***, ***0***, ***8***]]]
```
Imagine each inner 2-dimensional array as a cross-section of a 3-dimensional box. The only elements which are not *touching the edges* are the ones on the *inside* of the box.
## Specification
"Touching the edges" is a hopefully fairly intuitive concept, but here is a specification:
Let's use the same example input array as above; its shape is `4, 3`.
Using *one-based indexing*, we can index any element of the array using two integers in the ranges \$ [1, 4] \$ and \$ [1, 3] \$.
The elements which are touching the edge are those with coordinates of the form `1, y`, `4, y`, `x, 1`, or `x, 3`.
So, formally, we can say, for an element to be "touching the edge", at least one part of its multidimensional indices is either 1 (the minimum possible coordinate), or the maximum possible coordinate (which is the size of the array in the respective dimension).
## Rules
* You do not need to handle empty arrays, e.g. `[]` or `[[[], [], []], [[], [], []]]`
* 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
## Test cases
| Input | Output |
| --- | --- |
|
```
[[[0]]]
```
|
```
[[[0]]]
```
|
|
```
[[1]]
```
|
```
[[0, 0, 0], [0, 1, 0], [0, 0, 0]]
```
|
|
```
[3, 4, 9, 0, 0]
```
|
```
[0, 3, 4, 9, 0, 0]
```
|
|
```
[[1, 3, 0], [2, 6, 7], [4, 0, 2], [0, 0, 0]]
```
|
```
[[0, 0, 0, 0, 0], [0, 1, 3, 0, 0], [0, 2, 6, 7, 0], [0, 4, 0, 2, 0], [0, 0, 0, 0, 0]]
```
|
|
```
[[1, 0], [0, 4]]
```
|
```
[[0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 4, 0], [0, 0, 0, 0]]
```
|
|
```
[[[[0, 0], [1, 3]], [[0, 6], [0, 5]]], [[[0, 0], [0, 0]], [[1, 0], [2, 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], [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, 1, 3, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [0, 0, 6, 0], [0, 0, 5, 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], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [0, 1, 0, 0], [0, 2, 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, 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]]]]
```
|
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 24 bytes
```
(0×⊏)⊸∾⍟(0⊸×⊸≢⊏)∘⌽⍟2∘⍉⍟=
```
[Try it!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgKDDDl+KKjyniirjiiL7ijZ8oMOKKuMOX4oq44omi4oqPKeKImOKMveKNnzLiiJjijYnijZ89CgphIOKGkCA+4o2f4omhIOKfqAog4p+oMSwgMywgMOKfqSwKIOKfqDIsIDYsIDfin6ksCiDin6g0LCAwLCAy4p+pLAog4p+oMCwgMCwgMOKfqQrin6kKCkYgYQ==)
### Explanation
```
(0×⊏)⊸∾⍟(0⊸×⊸≢⊏)∘⌽⍟2∘⍉⍟=
⍟= Given an N-dimensional array, do this N times:
∘⍉ Rotate the array's indices (N-dimensional transpose), then
⍟2 Do this twice:
∘⌽ Reverse the array along its first axis, then
⍟ Do X times
( ) where X is:
⊏ Take the first cell of the array
⊸≢ and return 1 if it is different from
0⊸× itself multiplied by zero
(thus, do iff the first cell is not all zeros):
⊸∾ Join to the beginning of the array
(0×⊏) the first cell of the array multiplied by zero
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 71 bytes
```
#~ArrayPad~Sign@Table[Max/@Transpose[#,i<->1][[{1,-1}]],{i,Depth@#-1}]&
```
[Try it online!](https://tio.run/##TYzLCsIwEEX3fsVAwNUU04eKoKWCW6Ggu5BF1FYDtpY0CyXEX69NjY9hFnfOHG4l9KWohJZH0ZWw6shzrZR45OL03Mlzne3F4VqwrbhPsr0Sddvc2oIRlMsgDTljJsQgtJyjkbgpGn3JiLvHXa5krRmBIIWSEc5hDJNsBKYfaq3FEfQ59CFGSBAWCLTfzw8hHi4wEcIMYe5iMjiRi9TrP596nHyYMdRT12ZdcGTmval9o6/l@/7aooH0070A "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Python](https://www.python.org) NumPy, 95 bytes
```
lambda*a:pad(*a,[((a:=any(a,0)+0)[0].max(),a[-1].max())for _ in a[0].shape])
from numpy import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VY9BasMwEEX3PsUsJVcpsuOmjSEnmYowJRUxRLJQHLDP0o2htHfqqlepPFYpBSF9vfl_hnn7DNNw7v38bg_PH7fBbp6-jhdyLycqqQ10EiUpFILaA_lJkNLyTkvU5t7RKKQi3FRZS9tHOELngZb69Uzh1cjCxt6Bv7kwQedCH4cyj_le_OPiR0wBYxRitdxbBY2CvQKdDlMFW5YFYK1gp-CRdcOWmrXO9uzXv7BhgqgzA-B2iRbpw3yXeZIPhgsF_E_kzmui-uM1c2PaAkLs_CCsoBhpEqOUcl1zntf3Bw)
[Answer]
# [R](https://www.r-project.org), (was 296) 292 bytes
```
\(x,d=dim(x),n=length(d),a=array,e=seq(!d),m=e%%n+1,p=\(x)aperm(x,m),s=\(x,u)do.call(`[`,c(list(x),u)),u=lapply(d,\(x)quote(expr=)),r=\(x,y,z){l=dim(z);l[n]=l[n]+1;array(c(x,y),l)}){for(i in e){x=p(x);d=d[m];u[[n]]=d[n];k=s(x,u);if(any(k))x=r(x,k*0,x);u[[n]]=1;if(any(s(x,u)))x=r(k*0,x,x)};x}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VZJLboMwFEXVaVZBpUbya14r_m2FvBKKFBRMi2II4SNBoqykk3TQRaU76awPG_IZGK7ePffaRnx9V8fTXyPqxuJxVcU9WzET0EiynFswGwz7bFijQQot0K5zdh108Q1NHOMGNzyNuJcCdAiw0ccXggdl3gRUyVjsXaUGyr2ibLRHyr-cmhjd79PydLOaqX1u02qXWcp_2iZ9ev29e3hnHSacCNYBFlyK4qP5ZAlgrDdAwWuxZfc0ybmYz4uFhSWnFMSlqCiFOWA9DLCFZPO8iqVky3CJKyazuhlaW6DFZVyWsmcJDtltu2kEE11ZcTIrFe9xB3upjrKDQIZFxIfHwgqmmxIDKOEA-3RTsczICkPAvuMlNQZ0iTCPgjakTES6iII1r9WxgixlcdGzNUDHKxqtH02kyMhak69pDSmEoEPQHfTHOnkpU_8LzLSwJ-FMwp2ENwkfdPh41O9_)
Similar to the package approach, but R arrays are stored last-dimension-first so we loop through permuting the array each time so we're considering the last dimension, then add faces where needed. Now just using base R and it works in ATO.
# [R+abind+rlang](https://www.r-project.org), 220 bytes
```
\(x,d=dim(x),b=\(y,z,d)abind::abind(y,z,along=d),s=\(x,u)do.call(`[`,c(list(x),u)),m=lapply(d,\(x)rlang::expr())){for(i in 1:length(d)){u=m;u[i]=d[i];g=s(x,u);if(any(g))x=b(x,g*0,i);u[i]=1;if(any(s(x,u)))x=b(g*0,x,i)};x}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VZFLTsMwFEXFtGtgkFnfQw-UP5DIK2mR6tZJsOSmJR8pAXUlTMqARYFYDI6d9DNIfPXuudeO8_lVHX9vbqvsrZVVBnO-lqWYY-qcJpXiZTHHWZPVjcd4VfEeNuAiOUJumWcN_2R4o6EVeWjd4OQGFNIzuTTGHeZEFgnPBRRowKeYHjU8KPcqYErG4ugiNVDhBeWTP1Lx-dSasf2xfiLbbGZmn-u02WWWs--2ye-ffv6W0JFgGoAOac2W0NM7CTQ3liRmMSOudmXBBFLNhkiLYvew4UrBarGiDShZN0NDi0hbpvh-r3oQpFE0V50kWbevABE_8l0F0pGl4yUqK4vmFYSetmybtgv5woR-pQWrzSapzIGXPRSIHVvrUXHnkkRLepNrWYsMQKeRQ9odxm-McjC_GWdW-JMIJhFOIppEjDZ8PNr1Hw)
Basically loop through the dimensions and add on slices where appropriate after checking the final slice then initial slice. For loop has to use 1:length(d) rather than seq(d) in case d is a scalar.
Doesn't work in ATO but does work in [rdrr.io](https://rdrr.io/snippets/) with the following:
```
test1=array(c(0), dim=1)
test2=array(c(1), dim=c(1,1))
test3=array(c(3,4,9,0,0), dim = 5)
test4=array(c(1,3,0,2,6,7,4,0,2,0,0,0), dim = c(3,4))
test5=array(c(1,0,0,4), dim = c(2,2))
test6=array(c(0,0,1,3,0,6,0,5,0,0,0,0,1,0,2,0), dim = c(2,2,4))
f=function(x,d=dim(x),b=function(y,z,d)abind::abind(y,z,along=d),s=function(x,u)do.call(`[`,c(list(x),u)),m=lapply(d,function(x)rlang::expr())){for(i in 1:length(d)){u=m;u[i]=d[i];g=s(x,u);if(any(g))x=b(x,g*0,i);u[i]=1;if(any(s(x,u)))x=b(g*0,x,i)};x}
f(test1)
f(test2)
f(test3)
f(test4)
f(test5)
f(test6)
```
[Answer]
# Python3, 408 bytes:
```
lambda a:[(a:=f(a,a,i))for i in[*range(D(a))][::-1]][-1]
I=lambda x:int==type(x)
S=lambda x:x if I(x)else sum(map(S,x))
K=lambda x,e,d,l=0:S(x[e])if d==l else any(K(i,e,d,l+1)for i in x)
B=lambda x:0 if I(x)else[B(i)for i in x]
U=lambda o,a,d:[B(a[0])]*(K(o,0,d)>0)+a+[B(a[0])]*(K(o,-1,d)>0)
D=lambda x,l=0:l if I(x)else max(D(i,l+1)for i in x)
f=lambda o,a,d,l=0:U(o,a,d)if d==l else[f(o,i,d,l+1)for i in a]
```
[Try it online!](https://tio.run/##ZVBLi8IwEL73V8wx0RHS6rq7gexBRBCP4imbQ5a2u4G@qC7UX9@dxmptF0KYfI98M1NdLz9lsXyr6nanPtvM5l@xBSs1s1KlzKJFx3la1uDAFXpW2@I7YVtmOTdaykVojKYr2Kve2khXXJS6XKuENTw4DngDLoU9gUl2TuD8m7PcVuyIDefB4SHDBGPMlJBH1ujEcPLESmXgTba4sgNzN808fPQFlLQZksRzkt4w9yQ0wekuLGm4WBJvtTDczOjrEgXG/EPwuZ1PiEV4Y4Lt0GvXZzYaK7cNbcf96y4dhXrjifl6NKFOCXTT6axpq5rWynZMa2rJGFrZgITj9xJhhfCOIOh0zLMUYdmhGICOENYIr75eeXXka9E7JyF3G3GrCae9p2MBfIShmh4eX/c4lS/GE/TJyHFL6x3hgEce77LaPw)
] |
[Question]
[
Consider a positive integer `N` written in base `b`. A sequence is generated from this number by finding the largest digit `d` in the expansion of `N` and writing `N` in base `d+1`, repeating until the base the number is written in can be decreased no further. For example, the sequence generated by `346 (10)` in starting base 16 has length 6: `15A (16) = 295 (11) = 346 (10) = 1003 (7) = 11122 (4) = 110211 (3)`. Note that the next term in the sequence would be in base 3 again, which is invalid since the base does not decrease.
The goal of this code golf challenge is to write a program/function that takes two inputs (a decimal integer and a starting base - order doesn't matter and the two numbers must be integers) and outputs the length of the sequence generated according to the above rules.
Some test cases:
```
(24, 4) = 2
(19, 10) = 1
(346, 16) = 6
(7557, 97) = 20
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
b@Ṁ‘ɗƬL
```
A dyadic Link accepting `b` on the left and `N` on the right which yields the sequence length.
**[Try it online!](https://tio.run/##y0rNyan8/z/J4eHOhkcNM05OP7bG5////4Zm/41NzAA "Jelly – Try It Online")**
### How?
```
b@Ṁ‘ɗƬL - Link: b; N
Ƭ - Collect up until no longer unique, applying:
ɗ - last three links as a dyad - i.e. f(X[initially b], N):
@ - with swapped arguments:
b - convert (N) to base (X)
Ṁ - maximum
‘ - incremented
L - length
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 44 bytes
```
->n,b{r=1;r+=1while b>b=n.digits(b).max+1;r}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5PJ6m6yNbQukjb1rA8IzMnVSHJLsk2Ty8lMz2zpFgjSVMvN7FCGyhf@79AIS3ayETHJJYLxDK01DE0gDCNTcx0DM0gbHNTU3MdS/PY/wA "Ruby – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 67 bytes
edit: bug fix
```
S=lambda n,b,p=0:p-b and S(n,max(n/b**x%b for x in range(n))+1,b)+1
```
[Try it online!](https://tio.run/##TYzLCsMgEEX3/YrZFNROabU@aCFf4Rc4pI9AMxHJwny9dVPI5sA9cE/e1s/CprU4fNNMYwJGwjxcH/lMkHiEKBjnVAVfSKl6JHgtBSpMDCXx@ylYypNG6mi5TLyKKIxFK@XhP2/Wo/Y7EZwLeA87o50yzvdO/7Uf "Python 2 – Try It Online")
Explanation:
```
def S(Nr, Base, PrevBase=0):
if Base != PrevBase: # break recursion if Base repeats
# find maximum digit in current base
M=max([ (Nr//Base**x) % Base for x in range(Nr)])
# return number of remaining steps plus one
return 1 + S(Nr,M+1,Base)
return 0
```
[Answer]
# [Julia 1.0](http://julialang.org/), ~~46~~ 44 bytes
```
N*b=(d=max(digits(N,base=b)...)+1)==b||N*d+1
```
This uses a recursive approach together with the short-circuit operator `||` and makes use of the fact that Julia promotes booleans to integers under addition, so `true + 1 == 2`. This also overwrites the `*` operator, which you wouldn't normally do, but this lets me write `f(N,d)` infix as `N*d` to save 3 bytes.
[Try it online!](https://tio.run/##yyrNyUw0rPj/308ryVYjxTY3sUIjJTM9s6RYw08nKbE41TZJU09PT1PbUNPWNqmmxk8rRdvwv0NxRn65gpaGkYmOgokmF4xraKmjYGigqaCsUFJUmqpga6tgCJczNjEDSpohFJubmprrKFiaa/4HAA "Julia 1.0 – Try It Online")
[Answer]
# [J](http://jsoftware.com/), ~~40~~ 37 bytes
```
[:<:@#(h,])^:([>h=.1+[:>./#.inv)/^:a:
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o61srByUNTJ0YjXjrDSi7TJs9Qy1o63s9PSV9TLzyjT146wSrf5rcilwpSZn5CuYKdgqpCkYmikYm5hBRIzAIiYKRiYQviFEhYGCoSVUgQFYxNJcwdzU1Pw/AA "J – Try It Online")
*-3 bytes thanks to Galen Ivanov*
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~22~~ ~~19~~ 14 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
{aU=VìU rÔÄ}f1
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=e2FVPVbsVSBy1MR9ZjE&input=NAoyNA)
Takes input as base,number
```
{ }f1 repeat until function return false starting with 1, increment in
a difference between 1st input U and..
U= U, which is assigned..
VìU 2nd input V to base U
rÔ reduced to max
Ä add 1
```
Saved 5 thanks to @Shaggy suggestion to use reduce to max instead of sort, plus using counter of *f()* instead of manually count using T
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 24 bytes
```
NθNηW∧⊞Oυη⁻⊖η⌈↨θη≧⁻ιηILυ
```
[Try it online!](https://tio.run/##TYu9DoJAEIR7nuLKJcHSEEOF2pj4Q3yDEzbsJtwBd7vq259A5XTfzHwt2dCOdkjp4ieVu7oXBpjzKvtnWvhDPKCB2nfQaKTHhMHKGEALQ3lhbuw1whnbgA69YAdba7/s1MHRRoR5fa5Z6qmOkXv/5J4ENrcwvO5V1gT2AicbBa7oeyHQxalSKvf7MjuUafcefg "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
NθNη
```
Input `N` and `b`.
```
W∧⊞Oυη⁻⊖η⌈↨θη
```
Push `b` to the predefined empty list to build up the sequence, then convert `N` to base `b`, and subtract the largest resulting digit from `b-1`. Repeat until this is zero.
```
≧⁻ιη
```
Calculate the new base.
```
ILυ
```
Output the length of the sequence. (-1 byte to output the sequence itself.)
[Answer]
# [Python 2](https://docs.python.org/2/), 87 bytes
```
h=lambda n,b:n>=b and max(n%b,h(n/b,b))or n
f=lambda n,b,c=0:b!=c and f(n,h(n,b)+1,b)+1
```
[Try it online!](https://tio.run/##TY7NCsIwEITveYr1IKa6YNPftBBfRDw0LaUFu4p40KevkwjiYZIvm5ll7u/ndJNsXSd37RY/dCTsWzk5T50MtHQvLVvPk5ajZ58ktweJGv@83Lu09RvXR/@oJXjhPJh4rPfHLE@adF2WNVNTJ@o7scXeNgdr1LnB3DZQyVRbKGWqcBcFBM7BOdjAY8CmgsI7g/AfIkwI5xc1hn7saRY66ywsSFjHYArIixCtQL82l1bRt1BszTt32vEYef0A "Python 2 – Try It Online")
[Answer]
# JavaScript (ES6), 60 bytes
Takes input as `(n)(b)`.
```
n=>g=b=>(x=(h=n=>n&&Math.max(n%b,h(n/b|0)))(n)+1)<b?1+g(x):1
```
[Try it online!](https://tio.run/##XcxBDoIwEIXhvadgI5kJSikCDcbiCTxEi1AwODVCDAvvXouu5O3@fMm7qZca62f/mPZkr41rpSNZGallBbOETvqiMLyoqYvvagba6l0HxPQ7QUQgjDie9JlHBmY8cldbGu3QxIM10EKaIWSIwTLGgnTzz7xE4MnPPfMVH7LCe/F1z8WKRZ4LhFIsvpwn7gM "JavaScript (Node.js) – Try It Online")
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 83 bytes
```
x=>y=>{int g=y,t=0;for(;x>(x=new int[32].Max(l=>g-(g/=x)*x)+1);t++,g=y);return++t;}
```
[Try it online!](https://tio.run/##PYsxC8IwEEZ3f0XHO9OqtdLlvBuddHYQBwlJCEiENMUU8bfHTA4fvMfj01OnJ19Oc9BHH1L7hzoRyyWzLCyfqo3jpU28I/uKQFkgczDvppbbsL9vLo8MTxbXgdtyxnVG1SMlpdr6Q4omzTEolehbaHWNPpmzDwYs9CPCcBgRqfwA "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 22 bytes
```
[:#([:>./1+#.inv~)^:a:
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o62UNaKt7PT0DbWV9TLzyuo046wSrf5rcqUmZ@QrmCnYKhibmCmkKRiaQUSMgCJGJkABEwjfEMg3tAQpMIAqMACKmJuamgPFLM3/AwA "J – Try It Online")
Simplified version of [Jonah's solution](https://codegolf.stackexchange.com/a/196515/78410).
### How it works
```
[:#([:>./1+#.inv~)^:a: Left: number N, Right: initial base B
( )^:a: Collect all intermediate values up to fixpoint:
#.inv~ Compute digits of N in base B
1+ Increment
[:>./ Max; this becomes the new value of B
[:# Length of the result
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~8~~ 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Δвà>¼}¾
```
-1 byte thanks to *@Grimmy*.
Start-base \$b\$ as first input; number \$N\$ as second input.
[Try it online](https://tio.run/##yy9OTMpM/f//3JQLmw4vsDu0p/bQvv//Dc24jE3MAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@koGunoGRfeWhNaML/c1Miii9sOrzA7tCe2kP7/uvoHdr6PzrayETHJFZHIdrQUsfQAMQwNjHTMTQDscxNTc11LM1jYwE).
**Explanation:**
```
Δ # Loop until the top of the stack no longer changes:
в # Convert the (implicit) input-integer N to (implicit) input-base b as list
à # Pop the list and push the maximum
> # Increase it by 1 (which will be the new base b for the next iteration,
# with the same (implicit) input-integer N)
¼ # And in every loop-iteration: increase the counter_variable by 1
}¾ # After the loop: push the counter_variable
# (after which it is output implicitly as result)
```
[Answer]
# [K (ngn/k)](https://bitbucket.org/ngn/k), 18 bytes
```
{#{1+|/y\:x}[x]\y}
```
[Try it online!](https://tio.run/##y9bNS8/7/z/Nqlq52lC7Rr8yxqqiNroiNqay9n9atLmpqXmsgqX5fwA "K (ngn/k) – Try It Online")
[Answer]
# [Red](http://www.red-lang.org), 89 bytes
```
func[n b][k: 0 until[k: k + 1 m: n t: 1 until[t: max t m % b 1 > m: m / b]b = b: 1 + t]k]
```
[Try it online!](https://tio.run/##JY3LCsIwFAX3fsUQEJQKNtoHLdSPcBuyaNoGS02UkoJ/X1PdDfecM3ce@vU@9ErvbM1qF98pj9FqqklZfBifG04kSFyNJ9SR/kFE134IOPaYeL5tFcc5CgwNZqsmBD3p1b7moe0e/OyoS0aGrJAp16xAFpR5XlKVMXvPow9KHET8Jk4imsWRRmDZtnr9Ag "Red – Try It Online")
[Answer]
# MIT-Scheme, 117 bytes
```
(define(g n r)(if(= n 0)0(max(modulo n r)(g(quotient n r)r))))
(define(f n r)(if(=(+(g n r)1)r)1(1+(f n(1+(g n r))))))
```
(newline added for readability)
`g` is a helper function that computes the maximum digit of the number in a radix, and `f` is the main function.
[Answer]
# Haskell, 104 bytes
```
i=iterate
d n b=1+maximum(take(n+1)$snd<$>i((`divMod`b).fst)(n,0))
u(a:b:c)|a==b=1|2>1=1+u(b:c)
(u.).i.d
```
Haskell has no base conversion function. So I have to implement it normally.
`snd<$>i((`divMod`b).fst)(n,0)` returns an infinite list with zero as the first element, followed by represented by the representation of n at base b, followed by infinite number of zeros. (`((`divMod`b).fst)(0,0)` returns `(0,0)`)
I just iterate function d until the value stopped changing and count the number of iteration. (In haskell, you do that by `iterate`ing the function infinitely and take only the first few elements)
] |
[Question]
[
Gringotts isn't just a vault, but a reputable financial institution and wizards need loans too. Since you don't want to be screwed over by the Gringotts goblins, you decided it would be a good idea to write a program to calculate interest. Interest is compounded only yearly.
Your task is to calculate total owed amount after interest given the principal, interest rate, and time (whole years), operating in whole denominations of wizard money, rounding down to the nearest whole Knut. There are 29 Bronze Knuts in a Silver Sickle and 17 Sickles in a Gold Galleon.
## Example
```
Loan taken out:
23 Knuts
16 Sickles
103 Galleons
@ 7.250%
For 3 years
Total owed after interest:
24 Knuts
4 Sickles
128 Galleons
```
## Notes and Rules
* Input and output may be in any convenient format. You must take in Knuts, Sickles, Galleons, interest rate, and time. All but interest rate will be whole numbers. The interest rate is in increments of 0.125%.
* Input money is not guaranteed to be canonical (i.e. you can have 29 or more Knuts and 17 or more Sickles.)
* Output must be the canonical representation. (i.e. less than 29 Knuts and less than 17 Sickles)
* Totals owed, up to 1,000 Galleons, should be accurate to within 1 Knut per year of interest when compared with arbitrary precision calculations.
+ You may round down after each year of interest or only at the end. Reference calculations can take this into account for accuracy checks.
Happy golfing!
[Answer]
# [R](https://www.r-project.org/), ~~70~~ 62 bytes
```
function(d,i,y)(x=d%*%(a=c(1,29,493))*(1+i)^y)%/%a%%c(29,17,x)
```
[Try it online!](https://tio.run/##DclLCoAwDAXAq7gJJPWpjfWDoFcRSqXQjYIo6Omry2HOHIu5yvHew5WOnTckvMLPspEh9ktgRTuhm5yIYS2TrK9QQ54o8B864pEc@YeDDlDrBLa2Y9vDSf4A "R – Try It Online")
Takes input as d: deposit in knuts, sickles, galleons; i: interest rate as decimal; y: years. Outputs final deposit in knuts, sickles, galleons. Thanks to @Giuseppe for using matrix multiplication to save some bytes (and pointing out how to avoid the need to wrap at 1e99).
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~75~~ ~~74~~ 71 bytes
-1 bytes thanks to @EmbodimentofIgnorance
-3 bytes thanks to @xnor
This takes Knuts, Sickles, and Galleons as ints, interest as a float (decimal, not percentage), and years as an int. It returns a tuple containing the number after interest of Knuts, Sickles, and Galleons, respectively.
```
lambda K,S,G,R,Y:((k:=int((K+G*493+S*29)*(1+R)**Y))%29,k//29%17,k//493)
```
Usage:
```
>>> print(I(23,16,103,0.0725,3))
(24, 4, 128)
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPrvaRvzPycxNyklUcFbJ1jHXSdIJ9JKQyPbyjYzr0RDw1vbXcvE0lg7WMvIUlNLw1A7SFNLK1JTU9XIUidbX9/IUtXQHMQAqtH8X1AE0uOpYWSsY2imY2hgrGOgZ2BuZKpjrKn5HwA "Python 3.8 (pre-release) – Try It Online")
[Answer]
# APL+WIN, ~~37 28~~ 26 bytes
```
⌊a⊤((a←0 17 29)⊥⎕)×(1+⎕)*⎕
```
2 bytes saved thanks to lirtosiast
[Try it online! Courtesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/4/6ulKfNS1REMjEShmoGBormBkqfmoaylQmebh6RqG2iCGFpD4D1T@P43LmMtAz8DcyJTL0MBYwdBMwcgYAA "APL (Dyalog Classic) – Try It Online")
Explanation:
```
(1+⎕)*⎕ prompts for years followed by decimal interest rate and calculates
compounding multiplier
((a←0 17 29)⊥⎕) prompts for Galleons, Sickles and Knuts and converts to Knuts
⌊a⊤ converts back to Galleons, Sickles and Knuts and floor
after applying compound interest.
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 47 bytes
```
((1+*)*** *(*Z*1,29,493).sum+|0).polymod(29,17)
```
[Try it online!](https://tio.run/##DchBCoMwEAXQfU/xV2VmDCGTtBGx7UHcCZqVQVFcBLx77Fu@bd6XWHPBM@GLSqSNsIhASAZR4zvz6gLb48zN5dhu61LyOtH/teXaP46xIJGzrvVvg2Dw8QEaoS78uK83 "Perl 6 – Try It Online")
I'm surprised I managed to get this into an anonymous Whatever lambda! Especially the part where it's more `*`s than anything else. Takes input as `interest rate (e.g. 0.0725), years, [Knuts, Sickles, Galleons]` and returns a list of currencies in the same order.
### Explanation:
```
(1+*) # Add one to the interest rate
*** # Raise to the power of the year
* # And multiply by
(*Z*1,29,493).sum # The number of Knuts in the input
+|0 # And floor it
( ).polymod(29,17) # Get the modulos after divmoding by 29 and 17
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 29 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
“¢×ø‘©×\
÷ȷ2‘*⁵×÷¢S×¢d®U1¦Ṫ€Ḟ
```
A full program accepting arguments: `rate`; `[Galleons, Sickles, Knuts]`; `years`.
Prints `[Galleons, Sickles, Knuts]`.
**[Try it online!](https://tio.run/##AVUAqv9qZWxsef//4oCcwqLDl8O44oCYwqnDl1wKw7fItzLigJgq4oG1w5fDt8KiU8OXwqJkwq5VMcKm4bmq4oKs4bie////Ny4yNf9bMTAzLDE2LDIzXf8z "Jelly – Try It Online")**
Floors at the end of the entire term.
`÷ȷ2` may be removed if we may accept the rate as a ratio rather than a percentage.
### How?
```
“¢×ø‘©×\ - Link 1 multipliers: no arguments
“¢×ø‘ - list of code-age indices = [1,17,29]
© - (copy this to the register for later use)
\ - reduce by:
× - multiplication = [1,17,493]
÷ȷ2‘*⁵×÷¢S×¢d®U1¦Ṫ€Ḟ - Main Link
ȷ2 - 10^2 = 100
÷ - divide = rate/100
‘ - increment = 1+rate/100
⁵ - 5th command line argument (3rd input) = years
* - exponentiate = (1+rate/100)^years --i.e. multiplicand
× - multiply (by the borrowed amounts)
¢ - call last Link as a nilad
÷ - divide (all amounts in Galleons)
S - sum (total Galleons owed)
¢ - call last Link as a nilad
× - multiply (total owed in each of Galleons, Sickles, Knuts)
® - recall from register = [1,17,29]
d - divmod (vectorises) = [[G/1, G%1], [S/17, S^17], [K/17, K%17]]
U1¦ - reverse first one = [[G%1, G/1], [S/17, S%17], [K/17, K%17]]
Ṫ€ - tail €ach = [G/1, S%17, K%17]
Ḟ - floor (vectorises)
```
[Answer]
# Intel 8087 FPU assembly, 86 bytes
```
d9e8 d906 7f01 dec1 8b0e 8301 d9e8 d8c9 e2fc df06 7901 df06 8701 df06
7b01 df06 8501 df06 7d01 dec9 dec1 dec9 dec1 dec9 9bd9 2e89 01df 0687
01df 0685 01d9 c1de c9d9 c2d9 f8d8 f2df 1e7b 01d8 fadf 1e7d 01d9 c9d9
f8df 1e79 01
```
Unassembled and documented:
```
; calculate P+I of loan from wizard
; input:
; G: number of Galleons (mem16)
; S: number of Sickles (mem16)
; K: number of Knuts (mem16)
; R: interest rate (float)
; T: time in years (mem16)
; GS: Galleons to Sickles exchange rate (mem16)
; SK: Sickles to Knuts exchange rate (mem16)
; output:
; G: number of Galleons (mem16)
; S: number of Sickles (mem16)
; K: number of Knuts (mem16)
WIZ_INT_CALC MACRO G, S, K, R, T, GS, SK
LOCAL LOOP_EXP
; - calculate interet rate factor
FLD1 ; load 1
FLD R ; load interest rate
FADD ; ST = rate + 1
MOV CX, T ; Exponent is count for loop
FLD1 ; load 1 into ST as initial exponent value
LOOP_EXP: ; loop calculate exponent
FMUL ST,ST(1) ; multiply ST = ST * ST(1)
LOOP LOOP_EXP
; - convert demonimations to Knuts
FILD K ; load existing Knuts
FILD SK ; load Sickles to Knuts rate
FILD S ; load existing Sickles
FILD GS ; load Galleons-to-Sickles exchange rate
FILD G ; load existing Galleons
FMUL ; multiply galleons to get sickles
FADD ; add existing sickles
FMUL ; multiply sickles to get knuts
FADD ; add existing knuts
FMUL ; calculate P+I (P in Knuts * Interest factor)
; - redistribute demonimations to canonical form
FLDCW FRD ; put FPU in round-down mode
FILD SK ; load Sickles to Knuts rate
FILD GS ; load Galleons-to-Sickles exchange rate
FLD ST(1) ; copy Galleons-to-Sickles exchange rate to stack for later
FMUL ; multiply to get Galleons-to-Knuts rate
FLD ST(2) ; push original total Knuts from ST(2) into ST (lost by FPREM)
FPREM ; get remainder
FDIV ST,ST(2) ; divide remainder to get number of Sickles
FISTP S ; store Sickles to S
FDIVR ST,ST(2) ; divide to get number of Galleons
FISTP G ; store Galleons to G
FXCH ; swap ST, ST(1) for FPREM
FPREM ; get remainder to get number of Knuts
FISTP K ; store Knuts to K
ENDM
```
Implemented as a MACRO (basically a function), this is non-OS-specific machine-code using only the Intel 80x87 FPU / math co-processor for calculation.
Example test program with output:
```
FINIT ; reset FPU
WIZ_INT_CALC G,S,K,R,T,GS,SK ; do the "Wizardy"
MOV AX, K ; display Knuts
CALL OUTDEC ; generic decimal output routine
CALL NL ; CRLF
MOV AX, S ; display Sickles
CALL OUTDEC ; generic decimal output routine
CALL NL ; CRLF
MOV AX, G ; display Galleons
CALL OUTDEC ; generic decimal output routine
CALL NL ; CRLF
RET ; return to DOS
K DW 23 ; initial Kunts
S DW 16 ; initial Sickles
G DW 103 ; initial Galleons
R DD 0.0725 ; interest rate
T DW 3 ; time (years)
GS DW 17 ; Galleons to Sickles exchange rate
SK DW 29 ; Sickles to Knuts exchange rate
FRD DW 177FH ; 8087 control word to round down
```
***Output***
[](https://i.stack.imgur.com/3PPRQ.png)
[Answer]
# TI-BASIC (TI-84), ~~96~~ 90 Bytes
```
:SetUpEditor C:Ans→∟C:∟C(1)+29∟C(2)+493∟C(3)→T:T(1+∟C(4))^∟C(5)→T:remainder(iPart(T),493→R:{remainder(R,29),iPart(R/29),iPart(T/493)}
```
Input is `Ans`, a list with 5 items: Knuts, Sickles, Galleons, Interest (decimal), and Time (years).
Output is in `Ans` and is automatically printed out when the program completes.
**Un-golfed:**
```
:SetUpEditor C
:Ans→∟C
:∟C(1)+29∟C(2)+493∟C(3)→T
:T(1+∟C(4))^∟C(5)→T
:remainder(iPart(T),493→R
:{remainder(R,29),iPart(R/29),iPart(T/493)}
```
**Example:**
```
{32,2,5,0.05,5}
{32 2 5 .05 5}
prgmCDGF1
{12 10 6}
```
**Explanation:**
```
:SetUpEditor C
:Ans→∟C
```
A new list, `∟C`, is created and `Ans` is stored into it.
```
:∟C(1)+29∟C(2)+493∟C(3)→T
```
The Knuts, Sickles, and Galleons are converted into Knuts and stored into `T`.
```
:T(1+∟C(4))^∟C(5)→T
```
Takes the amount of Knuts and applies compound interest to it.
Interest is calculated here.
```
:remainder(iPart(T),493→R
```
Stores the **I**nteger **Part** of `T` modulo 493 into `R`. Used to shorten byte count.
```
:{remainder(R,29),iPart(R/29),iPart(T/493)}
```
Evaluates a list with 3 items (Knuts, Sickles, and Galleons). The list is automatically stored into `Ans`.
---
**Note:** Byte count is evaluated by taking the byte count given in **[MEM]**→**[2]**→**[7]** (program list in RAM) and subtracting the amount of characters in the program name and an extra 8 bytes used for the program:
103 - 5 - 8 = 90 bytes
[Answer]
# Japt, 48 bytes
```
XÄ pY *(U*493+V*29+W)f
Uu493
[Uz493 ,Vz29 ,Vu29]
```
My first try at Japt, going for @Shaggy's bounty! Needless to say, this isn't very golfy :(
[Try it Online!](https://ethproductions.github.io/japt/?v=1.4.6&code=WMQgcFkgKihVKjQ5MytWKjI5K1cpZgpVdTQ5MwpbVXo0OTMgLFZ6MjkgLFZ1Mjld&input=MTAzCjE2CjIzCjAuMDcyNQoz)
[Answer]
# [Haskell](https://www.haskell.org/), 73 bytes
```
(g#s)k r n|(x,y)<-truncate((493*g+29*s+k)*(1+r)^n)%29=(x%17,y)
(%)=divMod
```
[Try it online!](https://tio.run/##fdBRT4MwEAfw936KC5PQAjMrziyY8Wh8cD7t3aRCx0jL1bRFt8TvjhA1TE14uof73V3@dxROSa37ntYLxxRYwA96Ss9su/S2w1J4Sek6v4nrJMtjlygWU55Y9owszPKCnkK@GTShISuq5u3JVH0rGiwqQ@C183tvdwjBPXpp4UFoLQ26gEAN2yVYKaod/nf7plRajszNsUc03o9KzSk7JADhoJJl0woNBytK3xgc5uzcHHbty1DMAc5S2PEMXnItPVBaR6mLWKoiBgVMH7zYdgXBT@w7CJLEHc071NFv8R14Au4P@Io69VXUc5IRnpHVNd/cEr76BA "Haskell – Try It Online")
Thanks to @Laikoni for two bytes.
The dirty tricks: the number of coins in the input is floating point (`Double`), while the number of coins in the output is integral (`Integer`). The result is a nested pair `((Galleons, Sickles), Knotts)` to avoid having to flatten to a triple.
### Explanation
```
-- Define a binary operator # that
-- takes the number of Galleons
-- and Slivers and produces a
-- function taking the number of
-- Knots, the rate, and the
-- number of years and producing
-- the result.
(g#s) k r n
-- Calculate the initial value
-- in Knotts, calculate the
-- final value in Knotts,
-- and divide to get the number
-- of Galleons and the
-- remainder.
|(x,y)<-truncate((493*g+29*s+k)*(1+r)^n)%29
-- Calculate the number of Slivers
-- and remaining Knotts.
=(x%17,y)
(%)=divMod
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 24 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
»♀(╪M╢ú!!«ε◘÷╛SI►U/)-f!ö
```
[Run and debug it](https://staxlang.xyz/#p=af0c28d84db6a32121aeee08f6be534910552f292d662194&i=7.250+3+23+16+103&a=1&m=2)
Input is space separated values. `interest years knuts sickles galleons`
Output is newline separated.
```
knuts
sickles
galleons
```
[Answer]
# K, 46 Bytes
```
c:1000 17 29
t:{c\:{z(y*)/x}[c/:x;1+y%100;z]}
```
`c` store the list for base-conversion
`t` is the function that calculates total amount
Use example:
```
t[103 16 23;7.25;3]
```
writes `(128;4;24.29209)`
Explanation:
* `c/:x` transform the list (galleon; sickle; knuts) to kuts
* `1+y%100` calculate rate of interest (example 1.0725 for 7.25% rate)
* lambda `{z(y*)\x}` does the work: iterate 3 times, applying interes\*main, and returns final main.
* `c\:` generates galleon, sickles, knuts from knuts
NOTE.- if you don't need a names-function, we can use a lambda, saving 2 bytes
`{c\:{z(y*)/x}[c/:x;1+y%100;z]}inputArgs`
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 86 bytes
```
(a,b,c)=>((k=(int)((a.a*493+a.b*29+a.c)*Math.Pow(1+b,c)))/493,(k%=493)/29,k%29);int k;
```
Takes inout as a named tuple with 3 values representing knuts, sickles, and galleons, and interest rate as a double (not a percentage). I really wish C# had an exponentation operator. Math.Pow is way too long :(
[Try it online!](https://tio.run/##LY3BCsIwEER/xUthN13TNrFKqOnRm@DNcxJbDJEWbIufHxPxMG8YZmDcsneLj5dtcmfw07ozlGl/dEiPebOvISfKNf2F/agjGLLkUPcAQecWAQw37KBkabhlQiVzyK5mffLb/IGmzHvEKi0IQqGTYyUUhUIo7PJl6OL97dcBRoCmltQcSUikmtcn0ZJE7OIX "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
## Batch, 171 bytes
```
@set i=%4
@set/af=0,i=8*%i:.=,f=%,f*=8
@set/ai+=%f:~,1%,k=%1*493+%2*29+%3
@for /l %%y in (1,1,%5)do @set/ak+=k*i/800
@set/ag=k/493,s=k/29%%17,k%%=29
@echo %g% %s% %k%
```
Takes input as command-line arguments in the order Galleons, Sickles, Knuts, interest, years. Interest is a percentage but expressed without the % sign. Truncates after every year. Output is in the order Galleons, Sickles, Knuts. Supports at least 5000 Galleons. Explanation:
```
@set i=%4
@set/af=0,i=8*%i:.=,f=%,f*=8
```
Batch only has integer arithmetic. Fortunately, the interest rate is always a multiple of `0.125`. We start by splitting on the decimal point, so that `i` becomes the integer part of the interest rate and `f` the decimal fraction. These are then multiplied by 8. The first digit of `f` is now the number of eighths in the percentage interest rate.
```
@set/ai+=%f:~,1%,k=%1*493+%2*29+%3
```
This is then extracted using string slicing and added on to give an interest rate in 1/800ths. The number of Knuts is also calculated.
```
@for /l %%y in (1,1,%5)do @set/ak+=k*i/800
```
Calculate and add on each year's interest.
```
@set/ag=k/493,s=k/29%%17,k%%=29
@echo %g% %s% %k%
```
Convert back to Galleons and Sickles.
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), 24 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
>Im•1ýÑ•3L£I*O*ï29‰ć17‰ì
```
Port of [*@JoKing*'s Perl 6 answer](https://codegolf.stackexchange.com/a/180796/52210), so make sure to upvote him as well if you like this answer!
I'm using the legacy version due to a bug in the new version where `£` doesn't work on integers, so an explicit cast to string `§` (between the second `•` and `3`) is required (until the bug is fixed).
Takes the interest as decimal, followed by the year, followed by the list of [Knuts, Sickles, Galleons].
[Try it online.](https://tio.run/##MzBNTDJM/f/fzjP3UcMiw8N7D08E0sY@hxZ7avlrHV5vZPmoYcORdkNzIHV4zf//BnoG5kamXMZc0UbGOoZmOoYGxrEA)
**Explanation:**
```
> # Increase the (implicit) interest decimal by 1
# i.e. 0.0725 → 1.0725
Im # Take this to the power of the year input
# i.e. 1.0725 and 3 → 1.233...
•1ýÑ• # Push compressed integer 119493
3L # Push list [1,2,3]
£ # Split the integer into parts of that size: [1,19,493]
I* # Multiply it with the input-list
# i.e. [1,19,493] * [23,16,103] → [23,464,50779]
O # Take the sum of this list
# i.e. [23,464,50779] → 51266
* # Multiply it by the earlier calculated number
# i.e. 51266 * 1.233... → 63244.292...
ï # Cast to integer, truncating the decimal values
# i.e. 63244.292... → 63244
29‰ # Take the divmod 29
# i.e. 63244 → [2180,24]
ć # Extract the head; pushing the remainder-list and head separately
# i.e. [2180,24] → [24] and 2180
17‰ # Take the divmod 17 on this head
# i.e. 2180 → [128,4]
ì # And prepend this list in front of the remainder-list
# i.e. [24] and [128,4] → [128,4,24]
# (which is output implicitly as result)
```
[See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•1ýÑ•` is `119493`.
[Answer]
# APL(NARS), 37 char, 74 bytes
```
{(x y z)←⍵⋄⌊¨a⊤(z⊥⍨a←0 17 29)×x*⍨1+y}
```
translation of the very good and very few bytes APL solution by Graham user
to a solution that use one function instead of standard input...
test and how to use it:
```
f←{(x y z)←⍵⋄⌊¨a⊤(z⊥⍨a←0 17 29)×x*⍨1+y}
f 3 0.0725 (103 16 23)
128 4 24
```
(i don't say i had understood algorithm)
[Answer]
# [Perl 5](https://www.perl.org/), 70 bytes
```
$,=$";say 0|($_=(<>+<>*29+<>*493)*(1+<>)**<>)/493,0|($_%=493)/29,$_%29
```
[Try it online!](https://tio.run/##K0gtyjH9/19Fx1ZFybo4sVLBoEZDJd5Ww8ZO28ZOy8gSRJpYGmtqaRgCmZpaWkBCHyigA1anaguS0zey1AGyjSz//zcy5jI04zI0MOYy0DMwNzLlMv6XX1CSmZ9X/F/X11TPwNAAAA "Perl 5 – Try It Online")
] |
[Question]
[
[pylint](https://www.pylint.org/) has no lower bound on the scores it will give your code. It uses the following metric to score code, with the maximum score being 10:
```
10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
```
With python 3.6, try and write a program that:
* Outputs "Hello World" when run from the command line (i.e. `python script.py`), and no other output.
* Gets the lowest possible score from `pylint`, with default settings (i.e. `pylint script.py`)
* Is strictly less than or equal to 128 bytes in size.
[Answer]
# -5430
```
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++exit("Hello World")
```
[Try it online!](https://tio.run/##S0oszvj/PzmxRMFOITk/JVWvoJKrPFlBNxnOK6gsycjPM4bxFZQVCooy80qKFUryFYJDXFyDgoBKcoAiMBX//2vTE6RWZJZoKHmk5uTkK4TnF@WkKGkCAA "Bash – Try It Online")
[Answer]
# ~~-3330.00~~ -3540.00
* Lost 210 points thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis) -- exiting with the required string instead of printing it.
```
exit("Hello World"
)>_,_>_,_>_,_>_,_>_,_>_,_>_,_>_,_>_,_>_,_>_,_>_,_>_,_>_,_>_,_>_,_>_,_>_,_>_,_>_,_>_,_>_,_>_,_>_,_>_,_>_,_>_,_
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P7Uis0RDySM1JydfITy/KCdFiUvTLl4nnl74/38A "Python 3 – Try It Online")
[Answer]
# -840.0
```
print("Hello World"),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<0,0<0,0<0,0<0,0<0
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EQ8kjNScnXyE8vygnRUlTx8DGgF74/38A "Python 3 – Try It Online")
`0<0` seems to be pretty good, for a score of -30 points per each occurrence.
[Answer]
# -335.0
126 bytes
```
print("Hello World");import os,os,os,os,os,os,os,os,os,os,os,os,os,os,os,os,os,os,os,os,os,os,os,os,os,os,os,os,os,os,os,os
```
] |
[Question]
[
Back in the day, telephone autodialers used punched cards with one column for each digit of the number to be dialed. Columns had seven rows. The first three rows represented the numbers (1,2,3), (4,5,6), and (7,8,9) respectively. The last three rows rotated this arrangement by 90°: (1,4,7), (2,5,8), and (3,6,9). The middle row was used for 0. Any digit 1-9 would have two holes punched - one in the first three rows, and one in the bottom three rows. Zero would only have the middle row punched. Let's visualize the punched column for the number 6 (`.` is unpunched, `x` is punched, guide on left is just to illustrate the encoding):
```
123 .
456 x
789 .
0 .
147 .
258 .
369 x
```
We look for which row(s) contain the number we're trying to dial. For 6, this is the second row, and the ninth row. These two rows are punched, the remaining five rows are unpunched. Here are the punched patterns for all digits 0-9:
```
0 1 2 3 4 5 6 7 8 9
123 . x x x . . . . . .
456 . . . . x x x . . .
789 . . . . . . . x x x
0 x . . . . . . . . .
147 . x . . x . . x . .
258 . . x . . x . . x .
369 . . . x . . x . . x
```
Your goal is to (write a program or function to) punch these cards for me.
Input: A number, taken in any reasonable format (string, integer, list of integers, &c.), not to exceed 9999999999999.
Output: The grid of punched columns corresponding to the number input. You don't need the headers or extra spacing shown above, just the punched columns themselves. Leading/trailing newlines are ok, as is whitespace between rows/columns *as long as it is consistent*. Speaking of, as long as they are consistent, you may use any (non-whitespace) character for punched, and any other character for unpunched (while it should be obvious, please specify what characters you are using).
This is code-golf, so shortest code wins. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed.
Test cases (all use `.` for unpunched, `x` for punched):
```
In: 911
Out: .xx
...
x..
...
.xx
...
x..
In: 8675309
Out: ....x..
.x.x...
x.x...x
.....x.
..x....
x..x...
.x..x.x
In: 5553226
Out: ...xxx.
xxx...x
.......
.......
.......
xxx.xx.
...x..x
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
9s3,Z$j0ċþDZY
```
[Try it online!](https://tio.run/##y0rNyan8/9@y2FgnSiXL4Ej34X0uUZH/gSKGhgA "Jelly – Try It Online")
`1` = punctured, `0` = not punctured.
[Answer]
# Pyth, 25 bytes
```
.tm?djNmX*3NkZ.Dtd3X*7N3Z
```
Uses `0` for punched and `"` for unpunched.
[Try it here](http://pyth.herokuapp.com/?code=.tm%3FdjNmX%2A3NkZ.Dtd3X%2A7N3Z&input=%5B8%2C6%2C7%2C5%2C3%2C0%2C9%5D&debug=0)
### Explanation
```
.tm?djNmX*3NkZ.Dtd3X*7N3Z
m Q For each number in the (implicit) input...
?d ... if the number is nonzero...
.Dtd3 ... get (n - 1) divmod 3...
mX*3NkZ ... replace each position in `"""` with `0`...
jN ... and stick them together with `"`. ...
X*7N3Z ... Otherwise, `"""0"""`.
.t Transpose the result.
```
[Answer]
# JavaScript (ES6), ~~60~~ 54 bytes
Takes input as an array of integers. Returns a binary matrix, with **0** = unpunched / **1** = punched.
```
a=>[14,112,896,1,146,292,584].map(n=>a.map(i=>n>>i&1))
```
[Try it online!](https://tio.run/##hctBDsIgFATQvQcxkIyNHwFhARdpuiC1NZgKjTVen9KudGX@Zmby/iN8wtK/4vw@pXwbyuhKcL4lCSIBYzUIJDWEFVBGds0zzCw5H/YQnU/exyNxXvqcljwNzZTvbGSt3R47zg/f@2@rykDjCoULzrB/tYLarainqy4r "JavaScript (Node.js) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~16~~ 15 bytes
Uses **0** and **1**.
```
ε9ÝÀ3ôD¨ø«¢O}ø»
```
[Try it online!](https://tio.run/##MzBNTDJM/f//3FbLw3MPNxgf3uJyaMXhHYdWH1rkXwukd///b2hkbGJqZm5haWBpYW5mamJsZAgA "05AB1E – Try It Online")
**Explanation**
```
ε } # apply to each digit in input
9Ý # push the range [0 ... 9]
À # rotate left
3ô # split into pieces of 3
D¨ # duplicate and remove the last digit (0)
ø # transpose
« # append
¢O # sum the counts of each in the current digit
ø # transpose
» # format output
```
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGLOnline), 23 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
,{r"ΧL→▓lφ℮o¤κ²‘7nwι}⁰H
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JTJDJTdCciUyMiV1MDNBN0wldTIxOTIldTI1OTNsJXUwM0M2JXUyMTJFbyVBNCV1MDNCQSVCMiV1MjAxODdudyV1MDNCOSU3RCV1MjA3MEg_,inputs=NTU1MzIyNg__,v=0.12)
Compression.
[Answer]
# [Python 2](https://docs.python.org/2/), 84 bytes
```
lambda a:[''.join(`(ord('(1Aa2Bb4Dd'[int(n)])-32)>>k&1`for n in a)for k in range(7)]
```
[Try it online!](https://tio.run/##PY7LDoIwFAXX@hVdeVsBQ1vKK5FE418gCSWAInghDRu/HksM7iZzFnOmz/wcUSzt@b4M@l3Vmug0Bzi9xg5pSUdTU6D8osW1Cm415B3OFFnBPClYlvUHXrajIUg6JJqt2K9oND4aGrFi@a85JJyDC3EYKekn4BJQSkkhQit9LmSgwihOoEj3u8nYDEEH7ggOeHAcGrTVbVj172Br7aaXLw "Python 2 – Try It Online")
`0/1` is used for unpunched/punched.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~84~~ 80 bytes
```
def f(s):[print(*[int(i in[~-n//3,6--n%3-3*(n<1)])for n in s])for i in range(7)]
```
[Try it online!](https://tio.run/##JY6xDoMwDET3fsUtlRLkCEIEFNR@SZShUkmbxSDI0qW/niYgWfb53Q23fuNnYZPCo0mv2cOLXU523QJHUdmyAwLbn@K6NtQrxVejTCX4rqWTftnA2cd@6pLF9uT3LAbpUkGxIKsJLcE4gh0J@dNF3gg9YSB02SM0hLHg7gAna4/p3XRB7hZlPmc5mf4 "Python 3 – Try It Online")
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~108~~ 107 bytes
```
c,i;f(*q){char*r;for(i=~0;i++<6;puts(""))for(r=q;c=*r++;c-=48,putchar(".X"[(c--?16<<c%3|1<<c/3:8)>>i&1]));}
```
[Try it online!](https://tio.run/##ZY3LDoIwFET3fEVTo2lBlFJb0Qv4GybGBbmINMGqFVY@fh1l4cK4muScmQyG2BT22I@MxaYrDyS9taU5z@q8x6mBivlXfse6cL6D6uyYyV4RmCBINVy69sYo5XzgLrsCZr4LAsAwWyTTjx1mjM62dMcwDDdCpymO5UN8Yi7XCc9zMxF7zuHZG9uSU2Es4@TueRWjkYjlQullsqIcyPcKBrUS4o8leqlk9N9VSsk41r/cc4e2c5ZE4D37Nw "C (clang) – Try It Online")
Takes input number as string. Prints output in `.` and `X` as in examples.
# Credits
-1 byte thanks @ASCII-only
[Answer]
# [J](http://jsoftware.com/), 31 20 bytes
-11 bytes thanks to FrownyFrog!
```
(e."1],0,|:)1+i.@3 3
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NVL1lAxjdQx0aqw0DbUz9RyMFYz/a3IpcKUmZ@QrpClYKhgqGEI46rq6uuowcQsFMwVzBVMFY6BZlljkTcHQWMEICM24/gMA "J – Try It Online")
# [J](http://jsoftware.com/), 31 bytes
```
1*@|:@:#.(a,0,|:a=.1+i.3 3)=/~]
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DbUcaqwcrJT1NBJ1DHRqrBJt9Qy1M/WMFYw1bfXrYv9rcilwpSZn5CukKVgqGCoYQjjqurq66jBxCwUzBXMFUwVjoLGWWORNwdBYwQgIzbj@AwA "J – Try It Online")
Takes the input as a list of digits
0 - unpunched, 1 - punched
## Explanation:
```
a=.1+i.3 3 - generates the matrix and stores it into a
1 2 3
4 5 6
7 8 9
(a,0,|:a=.1+i.3 3) - generates the entire comparison table
1 2 3
4 5 6
7 8 9
0 0 0
1 4 7
2 5 8
3 6 9
]=/ - creates an equality table between the input and the comparison table
((a,0,|:a=.1+i.3 3)=/~]) 9 1 1
0 0 0
0 0 0
0 0 1
0 0 0
0 0 0
0 0 0
0 0 1
1 0 0
0 0 0
0 0 0
0 0 0
1 0 0
0 0 0
0 0 0
1 0 0
0 0 0
0 0 0
0 0 0
1 0 0
0 0 0
0 0 0
1*@|:@:#. - adds the tables, transposes the resulting table and finds the magnitude
(1*@|:@:#.(a,0,|:a=.1+i.3 3)=/~]) 9 1 1
0 1 1
0 0 0
1 0 0
0 0 0
0 1 1
0 0 0
1 0 0
```
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), ~~27~~ 25 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
{9+├3÷u4% ×#+#¹╷3%5+1╋]↶↕
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjVCJXVGRjE5JXVGRjBCJXUyNTFDJXVGRjEzJUY3JXVGRjU1JXVGRjE0JXVGRjA1JTIwJUQ3JTIzJXVGRjBCJTIzJUI5JXUyNTc3JXVGRjEzJXVGRjA1JXVGRjE1JXVGRjBCJXVGRjExJXUyNTRCJXVGRjNEJXUyMUI2JXUyMTk1,i=JTVCMSUyQzIlMkMzJTJDNCUyQzUlMkM2JTJDNyUyQzglMkM5JTJDMCUyQzAlMkMwJTJDOCUyQzYlMkM3JTJDNSUyQzMlMkMwJTJDOSU1RA__,v=2)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 28 bytes
```
E⁴⭆θI⁼ι÷﹪⊖λχ³E³⭆θI∧Iλ¬﹪⁻⊖λι³
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3sUDDREchuATISwdxCnUUnBOLSzRcC0sTc4o1MnUUPPNKXDLLMlNSNXzzU0pz8jVcUpOLUnNT80pSUzRyNHUUDA2AhLEmGFhzIcw1xmauY16KBpgB0umXXwIz1Dczr7QYw@hMhMma1v//W5iZmxobWP7XLcsBAA "Charcoal – Try It Online") Link is to verbose version of code. Uses 0/1, but can support arbitrary characters at a cost of 1 byte: [Try it online!](https://tio.run/##dY29CsIwFEZ3nyJ0uoVYKvEXp2IdOgQEnyA0wQZiYpOb0rePsQhOfsMHZzmnH4TvnTAp3by2CFy8YEvJHTM9PjBS0mBnpZqhqOaCkusYhQmgKekstnrSUgF3MhoHreq9eiqLSoIpKdnU@Vi57Lz6Bdj/QJULjZVwEQEXB9c2BjCU6K8npeP@sGP1Ka0n8wY "Charcoal – Try It Online"). Explanation:
```
E⁴ Loop from 0 to 3
⭆θ Loop over input string and join
λ Current character
⊖ Cast to integer and decrement
﹪ χ Modulo predefined variable 10 (changes -1 to 9)
÷ ³ Integer divide by literal 3
⁼ι Compare to outer loop variable
I Cast to string
Implicitly print each outer result on a separate line
E³ Loop from 0 to 2
⭆θ Loop over input string and join
λ Current character
⊖ Cast to integer and decrement
⁻ ι Subtract outer loop variable
﹪ ³ Modulo by literal 3
¬ Logical not
λ Inner loop character
I Cast to integer
∧ Logical and
I Cast to string
Implicitly print each outer result on a separate line
```
[Answer]
# [Perl 5](https://www.perl.org/) `-F`, 52 bytes
```
for$i(123,456,789,0,147,258,369){say map$i=~$_|0,@F}
```
[Try it online!](https://tio.run/##K0gtyjH9/z8tv0glU8PQyFjHxNRMx9zCUsdAx9DEXMfI1ELH2MxSs7o4sVIhN7FAJdO2TiW@xkDHwa32/3@geqByoGqDf/kFJZn5ecX/dX1N9QwMDf7rugEA "Perl 5 – Try It Online")
Uses `1` for punched and `0` for unpunched.
] |
[Question]
[
## The Challenge
Your program should take 3 inputs:
* A positive integer which is the number of variables,
* A set of unordered pairs of nonnegative integers, where each pair represents an equality between variables, and
* A positive integer which represents the starting variable,
It should return a set of nonnegative integers which represent all variables which can be shown to be transitively equal to the starting variable (including the starting variable itself).
In other words, given inputs `N`, `E`, and `S`, return a set `Q`, such that:
* `S ∈ Q`.
* If `Z ∈ Q` and `(Y = Z) ∈ E`, then `Y ∈ Q`.
* If `Z ∈ Q` and `(Z = Y) ∈ E`, then `Y ∈ Q`.
This can also be expressed as a [graph-theory](/questions/tagged/graph-theory "show questions tagged 'graph-theory'") problem:
>
> Given an undirected graph and a vertex in the graph, list the vertices in its [connected component](https://en.wikipedia.org/wiki/Connected_component_(graph_theory)).
>
>
>
## Specifications
* You can choose to use 0-based or 1-based indexing.
* The first input counts the number of variables that are present, where variables are given as numbers. Alternatively, you can not take this input, in which case this is assumed to be equal to either the highest variable index present, or one more than this, depending on your indexing scheme.
* You can assume the input is well formed: you will not be given variables outside of the range specified by the first input. For example, `3, [1 = 2, 2 = 0], 1` is a valid input, while `4, [1 = 719, 1 = 2, 3 = 2], -3` is not.
* You *cannot* assume that any variable will have any equalities associated with with it. If given a third input that is "lonely" (has no equalities), the correct output is a singleton set containing only that input (since it is equal to itself).
* You can assume that the equalities will not contain an equality from a variable to itself, and that the same equality will not be given multiple times (this includes things like `1 = 2` and `2 = 1`).
* You can assume that all integers given will be within your language's representable range.
* You can take the second input in any reasonable format.
Here are some reasonable formats:
```
0 = 2
0 = 3
1 = 0
{(0, 2), (0, 3), (1, 0)}
[0, 2, 0, 3, 1, 0]
0 2 0 3 1 0
Graph[{{0, 2}, {0, 3}, {1, 0}}]
[0 = 2, 0 = 3, 1 = 0]
```
* You can output in any reasonable format (i.e. set, list, etc.). Order is irrelevant.
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid program (in bytes) wins.
## Test Cases (0-indexed)
```
3, [1 = 2, 2 = 0], 1 -> {0, 1, 2}
5, [0 = 2, 0 = 3, 1 = 2], 3 -> {0, 1, 2, 3}
6, [0 = 3, 1 = 3, 2 = 4, 5 = 1], 4 -> {2, 4}
6, [0 = 3, 1 = 3, 2 = 4, 5 = 1], 5 -> {0, 1, 3, 5}
5, [0 = 1, 2 = 0, 0 = 3, 4 = 0], 2 -> {0, 1, 2, 3, 4}
6, [0 = 1, 1 = 2, 2 = 3, 3 = 4, 4 = 5], 3 -> {0, 1, 2, 3, 4, 5}
4, [0 = 1, 1 = 2, 2 = 0], 3 -> {3}
5, [0 = 2, 2 = 4], 2 -> {0, 2, 4}
8, [], 7 -> {7}
```
## Test Cases (1-indexed)
```
3, [2 = 3, 3 = 1], 2 -> {1, 2, 3}
5, [1 = 3, 1 = 4, 2 = 3], 4 -> {1, 2, 3, 4}
6, [1 = 4, 2 = 4, 3 = 5, 6 = 2], 5 -> {3, 5}
6, [1 = 4, 2 = 4, 3 = 5, 6 = 2], 6 -> {1, 2, 4, 6}
5, [1 = 2, 3 = 1, 1 = 4, 5 = 1], 3 -> {1, 2, 3, 4, 5}
6, [1 = 2, 2 = 3, 3 = 4, 4 = 5, 5 = 6], 4 -> {1, 2, 3, 4, 5, 6}
4, [1 = 2, 2 = 3, 3 = 1], 4 -> {4}
5, [1 = 3, 3 = 5], 3 -> {1, 3, 5}
8, [], 8 -> {8}
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 22 bytes
```
{tc⊇,?k.&¬(t∋;.xȮ)∧}ᶠt
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v7ok@VFXu459tp7aoTUaJY86uq31Kk6s03zUsbz24bYFJf//R5vpREcb6hjF6kSb6JgBSWMdQyBpChYxB4rExv6PAgA "Brachylog – Try It Online")
## Explanation
```
{tc⊇,?k.&¬(t∋;.xȮ)∧}ᶠt Input is a pair, say [2,[[1,3],[2,4],[5,2]]]
{ }ᶠ Find all outputs of this predicate:
t Tail: [[1,3],[2,4],[5,2]]
c Concatenate: [1,3,2,4,5,2]
⊇ Choose a subset: [4,5]
,? Append the input: [4,5,2,[[1,3],[2,4],[5,2]]]
k Remove the last element: [4,5,2]
. This list is the output.
&¬( )∧ Also, the following is not true:
t∋ There is a pair P in the second part of the input.
;.x If you remove from P those elements that occur in the output,
Ȯ the result is a one-element list.
t Take the last one of these outputs, which is the shortest one.
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~65~~ 63 bytes
-2 bytes thanks to ovs
```
def f(e,s):b={s};exec"for p in e:b|=b&p and p\n"*len(e);print b
```
[Try it online!](https://tio.run/##jZBBDoIwEEX3nmLCQsB0AS3EBMJJkIWVEklMaWgXGuTstYXagCtXM/nzZubni5e6Dxxr3bIOuoghGRe0muRcsie7Bd0wgoCeAyvou6JHAVfegrjw4PRgPGJxKcaeK6BaMakkVFAf6npKEeAZwYQRJHODIG2QlRMnm0psXTAzJn78lYnbzmzNzQGLZf9hucdS72HzNHOe8B7bWF4w4q4aPN97/MWT/Rh7T/6Jac6maQ42ThOxDXTJq1jTM1K5Zr/GGYb6Aw "Python 2 – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 12 bytes
```
u|sf@TGQG.{E
```
[Test suite.](http://pyth.herokuapp.com/?code=u%7Csf%40TGQG.%7BE&test_suite=1&test_suite_input=%5B%7B1%2C2%7D%2C+%7B2%2C0%7D%5D%0A1%0A%5B%7B0%2C2%7D%2C+%7B0%2C3%7D%2C+%7B1%2C2%7D%5D%0A3%0A%5B%7B0%2C3%7D%2C+%7B1%2C3%7D%2C+%7B2%2C4%7D%2C+%7B5%2C1%7D%5D%0A4%0A%5B%7B0%2C3%7D%2C+%7B1%2C3%7D%2C+%7B2%2C4%7D%2C+%7B5%2C1%7D%5D%0A5%0A%5B%7B0%2C1%7D%2C+%7B2%2C0%7D%2C+%7B0%2C3%7D%2C+%7B4%2C0%7D%5D%0A2%0A%5B%7B0%2C1%7D%2C+%7B1%2C2%7D%2C+%7B2%2C3%7D%2C+%7B3%2C4%7D%2C+%7B4%2C5%7D%5D%0A3%0A%5B%7B0%2C1%7D%2C+%7B1%2C2%7D%2C+%7B2%2C0%7D%5D%0A3%0A%5B%7B0%2C2%7D%2C+%7B2%2C4%7D%5D%0A2%0A%5B%5D%0A7&debug=0&input_size=2)
[Answer]
# [Operation Flashpoint](https://en.wikipedia.org/wiki/Operation_Flashpoint:_Cold_War_Crisis) scripting language, 364 bytes
```
f={t=_this;r=t select 1;i=0;while{i<t select 0}do{call format["V%1=[%1]",i];i=i+1};i=0;while{i<count r}do{call format(["V%1=V%1+V%2;V%2=V%1"]+(r select i));i=i+1};l=call format["V%1",t select 2];g={i=0;c=count l;while{i<c}do{if(i<count l)then{e=l select i;call _this};i=i+1}};{l=l+call format["V%1",e]}call g;"l=l-[e]+[e];if(count l<c)then{c=count l;i=0}"call g;l}
```
**Call with:**
```
hint format
[
"%1\n%2\n%3\n%4\n%5\n%6\n%7\n%8\n%9",
[3, [[1, 2], [2, 0]], 1] call f,
[5, [[0, 2], [0, 3], [1, 2]], 3] call f,
[6, [[0, 3], [1, 3], [2, 4], [5, 1]], 4] call f,
[6, [[0, 3], [1, 3], [2, 4], [5, 1]], 5] call f,
[5, [[0, 1], [2, 0], [0, 3], [4, 0]], 2] call f,
[6, [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5]], 3] call f,
[4, [[0, 1], [1, 2], [2, 0]], 3] call f,
[5, [[0, 2], [2, 4]], 2] call f,
[8, [], 7] call f
]
```
**Output:**
[](https://i.stack.imgur.com/9j9e1.png)
**Unrolled:**
```
f =
{
t = _this;
r = t select 1;
i = 0;
while {i < t select 0} do
{
call format["V%1=[%1]", i];
i = i + 1
};
i = 0;
while {i < count r} do
{
call format(["V%1=V%1+V%2;V%2=V%1"] + (r select i));
i = i + 1
};
l = call format["V%1", t select 2];
g =
{
i = 0;
c = count l;
while {i < c} do
{
if (i < count l) then
{
e = l select i;
call _this
};
i = i + 1
}
};
{l = l + call format["V%1", e]} call g;
"l = l - [e] + [e];
if (count l<c)then
{
c = count l;
i = 0
}" call g;
l
}
```
[Answer]
# [Clean](https://clean.cs.ru.nl), ~~85~~ 81 bytes
```
import StdEnv
$l=limit o iterate(\v=removeDup(flatten[v:filter(isAnyMember v)l]))
```
[Try it online!](https://tio.run/##DcyxCsIwEIDh3ae4oUM6OAtCB6EOgk4dY4ezvcrBXVLSa6Avb8z@f/8khKFonHchUORQWNeYDAab7yGfGumElQ0isFFCI/fOXSKNmfp9dYugGQWfrwtLDRxvt3C8SD@UILcytm0ZDOuwgwb8CP4ylt9U2Xcr58ez9EdA5Wn7Aw "Clean – Try It Online")
Defines the function `$ :: [[Int]] -> ([Int] -> [Int])`
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 32 bytes
```
#~VertexComponent~#2~Check~{#2}&
```
Input format: `{2<->3, 3<->1}, 3`. It does not take the first input.
[Try it online!](https://tio.run/##hY5NCoMwEIWvMhhwFRFjIl20IniBdtONuBCJKCVaJIVCSK6eThsRXHUx8@C9b35Up0epOj31nR/g4om7y1XLd72o5zLLWTvCXD3K/uEMYTb213WadWMIsRQiSEqIKAwNIW0LMVRVBcYYdk7KnEKOkiGWYxmTBfMrnMIPQZ/v2WbyMCcoFCgMY/EfKXaEbasDgiQPpEApDveOZHbINlPsz2M7WQtpentNUvsP "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 53 bytes
```
e,s,n=input()
b={s}
for p in n*e:b|=b&p and p
print b
```
[Try it online!](https://tio.run/##nZHbasQgEIbvfYohFyUpXnhIKCzkSUIumtaygeLKxqUtaZ49HSWxKlkovXIO3z/@jubLni9arB/n8V0BP6lP9VIUxaroRHU7anOzZUWGdp4W8na5goFRg35Up@G7HR4MPOtXMMRcR21hWFFJiFWTnaCFjnTdzCmIhcIsKLClp8B76spsK@Mp3ekxbMvQ3styU9fubHCAw@q/YU3AePAQXVpvnkSKRZY9JrepiDepxxxnaVsET@ESDJ4w6Neym5QtOyfuKwo@YT5xS8KgIhvCMkSGhO88OpQxnyC/ibMSdxovds/6t7jJxDx7zJFt5ie5lWBwLE7WImKxjG3Uuw1518bxguXdBYvcnPsx/NnqBw "Python 2 – Try It Online")
Same length as function:
```
lambda e,s,n:reduce(lambda b,p:b|(b&p and p),n*e,{s})
```
[Try it online!](https://tio.run/##nZBBCoMwEEX3PcWsSiKziIlSEHoS60JrRMGmQSOltD27jcG2KropZDF/8t/wZ/TdlFfF@@J46uv0kuUpSGxRRY3Mu7MkYy9DHWVPku01pCoHTVF5Eh/ti/a3sqol@JFuKmWgIF6ldGcIpT2JW2lI7CPwhCI4wZxIEIYu3Y0WtrCIr/A/fmHf1D@z/ARHCKY/oYMDW/wNhwvYXyyzFpu5SRYeRq7Ds7PwKSymMYJPDLEZY/3AYvPAfBnOlgcERt8 "Python 2 – Try It Online")
This is based off [Rod's nice solution](https://codegolf.stackexchange.com/a/158241/20260) using the short-circuiting update `b|=b&p and p`. Taking the number of variables as an input `n` helps shorten the loop code.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ ~~11~~ 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 thanks to Erik the Outgolfer (replace the atom `œ&` with `f`)
```
⁹fÐfȯFµÐLQ
```
A dyadic link accepting `E` on the left (as a list of length-two-lists) and `S` on the right (as an integer) returning a [de-duplicated] list.
**[Try it online!](https://tio.run/##y0rNyan8//9R4860wxPSTqx3O7T18ASfwP///5v@jzbQUTCO1VGINoTSRjoKJiDaVEfBMBYA "Jelly – Try It Online")** or see a [test-suite](https://tio.run/##y0rNyan8//9R4860wxPSTqx3O7T18ASfwP9H9xxerv@oac3RSQ93zgDSQJQFohrmKOjaKTxqmBv5/390tJGOApgwjgUyjHUUDGNjQSwTkLAhVBhIm4BosDKwtClUGiZsAtVtCqLNdBSMIMrMiFNmDFVmBHcDkqWmGG4ygrsFotwEKmkKVW6GX7khqqXGcDeBhS2AGMgCAA "Jelly – Try It Online").
### How?
```
⁹fÐfȯFµÐLQ - Link: list of lists, E; integer S
µÐL - repeat the monadic chain to the left until a fixed point is reached:
Ðf - (for each pair in E) filter keep if:
f - filter discard if in
⁹ - chain's right argument
- (originally [S], thereafter the previous result as monadic)
ȯ - logical OR with implicit right
- (force first pass to become S if nothing was kept)
F - flatten to a single list
- (S -> [S] / [[1,4],[1,0]]->[1,4,1,0] / etc...)
Q - de-duplicate
```
[Answer]
# [Perl 5](https://www.perl.org/) `-n0`, ~~49~~ 39 bytes
Give starting value on a line on STDIN followed by lines of pairs of equivalent numbers (or give the starting value last or in the middle or give multiple starting values, it all works)
```
#!/usr/bin/perl -n0
s/
$1? | $1/
/ while/^(\d+
)/msg;say//g
```
[Try it online!](https://tio.run/##K0gtyjH9/79Yn0vF0F6hRkHFUJ9LX6E8IzMnVT9OIyZFm0tTP7c43bo4sVJfP/3/fwMFQy5DBSMuIwUDIDbhMgZiUwUzLjMFUy5jrn/5BSWZ@XnF/3XzDP7r@prqGRroGQAA "Perl 5 – Try It Online")
This can output an element in the result set multiple times. This 48 bytes variation outputs each equivalent element only once:
```
s/
$1? | $1/
/ while/^(\d+
)(?!.*^\1)/msg;say//g
```
[Try it online!](https://tio.run/##DcNBCoNADAXQ/T9FCi604iRRx00XnsAbiFCoWMGqOIIUevZGH7y13yZvFhiR1vSjSBlMx3uceu7i9pUiieubu3etJvwJwyM8v8yDmZBCKUdOci1RXD1VqMijwH9Z93GZg2WzWNZ4p@LkBA "Perl 5 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 39 bytes
```
->e,*s{e.map{e.map{|a|a-s!=a&&s|=a}};s}
```
[Try it online!](https://tio.run/##jZDfCoIwFIfvfYp145@Y4nRWFKsHGSMWKAhG0gyMtme3o1uS0EU3O2zft3N@2/1xeQ4VG@JjidfqVSZX2bpVSy1jtWLS95Vm0piDMgPnOUYBQQxlGGVQ0gAjIrCHeAEgtWAs4E0a8HziG8cdyO19ilEBhYBG/9OKxTTiYsxDqQuVLboRl8baoOW26WgXc0T6005n/vXEKdQ8ZgcANlsh7Nc12mtRxRtORKLapu7CE44s6nX/OWLTUejvu9u5jgxueCaEZ7zhDQ "Ruby – Try It Online")
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), ~~37~~ ~~36~~ 35 bytes
```
{&a[z]=a:{y[x]&:|y x;y}[+y,,&2]/!x}
```
[Try it online!](https://tio.run/##fZBBDoIwEEX3nmKMhkBELbRV04m3cNc0kQ3GYDRxRUW8Ok5Bsd3Y3fS//rxptbyerl1XqiYq9MPsC9VYXZtIPS3UaFu9sGka5WY9rdvuoJq5tq@7KmFF6fFWYXwsi/MFCcV7YtrJQccc4wxyzIGBdxLMEmRAyTAbh0qMGaEMOI6BQ/kX5SO6cajDODULlBT3qEjc/H36F5VDKwcZCmTOtZcQgzNV/gSE35rhsBpHCgiXgSvNPSp8lAVrpRwC188PeCt4AuNtj@6QzVIW/iod3FLr9tfavQE "K (ngn/k) – Try It Online")
`{` `}` function with arguments `x`, `y`, and `z` representing `N`, `E`, and `S` respectively
`!x` is the list 0 1 ... x-1
`&2` is the list `0 0`
`y,,&2` we add the pair `0 0` to `y` to avoid the special case of an empty `y`
`+y,,&2` same thing transposed from a list of pairs to a pair of lists
`{` `}[+y,,&2]` is a projection, i.e. a function in which `x` will be the value of `+y,,&2` and `y` will be the argument passed in when calling the projection
`|y x` is `y` at indices `x`, reversed (`|`)
`@[y;x;&;|y x]` amend `y` at indices `x` by taking the minimum (`&`) of the existing element and an element from `|y x`
`/` keep calling until convergence
`a:` assign to a
`a[z]=z` boolean mask of the elements of `a` equal to the `z`-th
`&` convert the boolean mask to a list of indices
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~48~~ 45 bytes
```
t=@(A,u)find(((eye(size(A))+A+A')^nnz(A))(u,:));
```
Takes input as "adjacency-matrix", for example uses `[0 0 0; 0 0 1; 1 0 0]` for `[2 = 3, 3 = 1]`, [try it online!](https://tio.run/##jVFha4MwEP3ur7hvzVE3SExCmTjm7xhdkVbBQhWqjs3R3@7uonS1TVkDGpL33r13l3rbZp/5MLTJm0jDDouy2gkh8u9cNGWfixRxmS7TBX5UVc8n0YUviPFQdNW2LesK0qStN9luvzlkrWj6EMqvBgOAFBLo82Pd8GXTY0x3RX2Eck8AcZ4XdEE0Ue6FxJD@CpEgycS82gX8Ba24qB6F8K4giiECucYQFM5xQ7hkXIKOgZhM0lck60gO11zJxGBBMdM8zLReY@WCTe5mjBh5ayqXjunE1FzYgPWF1Vd06SOd26aIPs8V4Xy/wmGcYAK0RzzrNQ0RvOvpFX4koUQ8BaODk/GmWUUnUuv7MgJPgZ2Uk0SPvlTP0qaogLlUksY8oLG3bkSyfznV1N45rpmajfw5Z7Zq6m6soblH5841rGv5RuzMtVcv7wxJz6bqGrzM553qOB73nPSa8O9i2er0Cw "Octave – Try It Online")
## Explanation
First we construct the complete adjacency matrix for the transitive graph, using the sum of `eye(size(A))` (elements are reflexive), `A` (input) and `A'` (the relation is symmetric).
We compute the transitive closure by computing the power to `nnz(A)` which suffices (`nnz(A)` is upper bound for a path's length), so from there all that's left is to get the right row with `(u,:)` and `find` all non-zero entries.
[Answer]
# [Python 2](https://docs.python.org/2/), 87 bytes
```
g,v=input();x={v};d=[v]
for c in d:x|={c};d+={k[k[0]==c]for k in g if c in k}-x
print x
```
[Try it online!](https://tio.run/##jY4xb8MgEIV3fsXJk60Syca2KiViTNYu3SwPKSYJIrItRFwi6t/uQHAj1KkLD9377t0b7/oy9GRhQ8eBQpIkyxlPVPTjTafZzlA7zbuONlOLToMCBqKHbmt@qGVu/katbGSTt5Sy1vvS@2cQp0DKeWPQqESvwSwuG6Hvi7hy@FQ3vkUAWt29AHDDGfgOyP8ZHzXsPw57pQYVgC/Fj3KxaYGBZBhSgiHPZgwFsmm@zpyWXp@M88rg/c7Kda/yWrtVz1T/YOrAFK@70a1q7UEiJur4ZMo1z7F11Osvm0ceefUI2e59fwA "Python 2 – Try It Online")
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 80 bytes
```
f(g,p)=c=concat;if(p==q=c(c(p=Set(p),[e|e<-g,setintersect(Set(e),p)])),p,f(g,q))
```
[Try it online!](https://tio.run/##fY7BCoMwDIZfpXhqIR60KoOte4kdJYdSqgjiOu1lsHfv0mpBGKyHkD9f/j91ep3K0YUw8BGcUEaZ52K0v04Dd0q9lOGGmof13Ano7cfeyhE266fF23WzxvPIrCAzCqoQg15CBO3c/OaalXfmVtqmtoiiYEbPMx@AadpnPb0aJEIvoUKEGtOsSqMKGqoRY9Q72EdNcrRUO/Jg7P7hLuP6uJTD23RVnnH@TsRNymjJj1H/LlVnII@rORDhgijCFw "Pari/GP – Try It Online")
[Answer]
## JavaScript (ES6), 87 bytes
```
(a,n)=>a.map(([b,c])=>[...d[b]||[b],...d[c]||[c]].map((e,_,a)=>d[e]=a),d=[])&&d[n]||[n]
```
Deduplication would be possible using `&&[...new Set(d[n]||[n])]` at a cost of 14 bytes.
] |
[Question]
[
Given an integer **n**, decompose it into a sum of maximal triangular numbers (where **Tm** represents the **m**th triangular number, or the sum of the integers from 1 to **m**) as follows:
* while **n > 0**,
+ find the largest possible triangular number **Tm** such that **Tm ≤ n**.
+ append **m** to the triangular-decomposition representation of **n**.
+ subtract **Tm** from **n**.
For example, an input of **44** would yield an output of **8311**, because:
* 1+2+3+4+5+6+7+8 = 36 < 44, but 1+2+3+4+5+6+7+8+9 = 45 > 44.
+ the first digit is **8**; subtract 36 from 44 to get **8** left over.
* 1+2+3 = 6 < 8, but 1+2+3+4 = 10 > 8.
+ the second digit is **3**; subtract 6 from 8 to get **2** left over.
* 1 < 2, but 1+2 = 3 > 2.
+ the third and fourth digits must be **1** and **1**.
Use the digits 1 through 9 to represent the first 9 triangular numbers, then use the letters a through z (can be capitalized or lowercase) to represent the 10th through 35th triangular number. You will never be given an input that will necessitate the use of a larger "digit".
The bounds on the input are **1 ≤ n < 666**, and it will always be an integer.
[All possible inputs and outputs](https://ptpb.pw/GfF8), and some selected test cases (listed as input, then output):
```
1 1
2 11
3 2
4 21
5 211
6 3
100 d32
230 k5211
435 t
665 z731
```
An output of **∞** for an input of **-1/12** is not required. :)
[Answer]
## JavaScript (ES6), 52 bytes
```
f=(n,t=0)=>t<n?f(n-++t,t):t.toString(36)+(n?f(n):'')
```
### How?
Rather than explicitly computing ***Ti = 1 + 2 + 3 + … + i***, we start with ***t = 0*** and iteratively subtract ***t + 1*** from ***n*** while ***t < n***, incrementing ***t*** at each iteration. When the condition is not fulfilled anymore, a total of ***Tt*** has been subtracted from ***n*** and the output is updated accordingly. We repeat the process until ***n = 0***.
Below is a summary of all operations for ***n = 100***.
```
n | t | t < n | output
----+----+-------+--------
100 | 0 | yes | ""
99 | 1 | yes | ""
97 | 2 | yes | ""
94 | 3 | yes | ""
90 | 4 | yes | ""
85 | 5 | yes | ""
79 | 6 | yes | ""
72 | 7 | yes | ""
64 | 8 | yes | ""
55 | 9 | yes | ""
45 | 10 | yes | ""
34 | 11 | yes | ""
22 | 12 | yes | ""
9 | 13 | no | "d"
----+----+-------+--------
9 | 0 | yes | "d"
8 | 1 | yes | "d"
6 | 2 | yes | "d"
3 | 3 | no | "d3"
----+----+-------+--------
3 | 0 | yes | "d3"
2 | 1 | yes | "d3"
0 | 2 | no | "d32"
```
### Test cases
```
f=(n,t=0)=>t<n?f(n-++t,t):t.toString(36)+(n?f(n):'')
console.log(f(1)) // 1
console.log(f(2)) // 11
console.log(f(3)) // 2
console.log(f(4)) // 21
console.log(f(5)) // 211
console.log(f(6)) // 3
console.log(f(100)) // d32
console.log(f(230)) // k5211
console.log(f(435)) // t
console.log(f(665)) // z731
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~18~~ 17 bytes
```
Ḥ‘½+.Ḟ©ịØB2®cạµ¹¿
```
This is a monadic link that prints to STDOUT. It's return value is **0** and should be ignored.
[Try it online!](https://tio.run/nexus/jelly#@/9wx5JHDTMO7dXWe7hj3qGVD3d3H57hZHRoXfLDXQsPbT2089D@/4fbgx7ubDm09VHTmv//DXUUjHQUjHUUTHQUTHUUzHQUDA0MgGLGQMLEGCRiZgoA "Jelly – TIO Nexus")
[Answer]
# dc, 74 bytes
```
?sa[2k_1K/1 4/la2*+v+0k1/dlardd*+2/-sadd10<t9>ula0<s]ss[87+P]st[48+P]sulsx
```
This is awful.
```
?sa stores the input
[2k sets precision to 2 so dc doesn't truncate 1/4
_1K/1 4/la2*+v+ uses the quadratic formula to find k, the next value to print
0k1/d truncates k to an integer
lardd*+2/-sa subtracts kth triangular number from the input
dd10<t9>u determines whether to print k as a letter or a digit
la0<s]ss loops when a is greater than 0
[87+P]st prints k as a letter
[48+P]su prints k as a digit (not p, as that leaves a trailing newline)
lsx starts the main loop
```
[Answer]
## JavaScript (ES6), ~~61~~ 57 bytes
*Saved 4 bytes thanks to @Arnauld*
```
f=(n,p=q=0)=>n?p-~q>n?q.toString(36)+f(n-p):f(n,++q+p):''
```
[Answer]
# Java 7, 81 bytes
```
int i=0;String c(int n){return i<n?c(n-++i):Long.toString(i,36)+(n>(i=0)?c(n):"");}
```
Port from [*@Arnauld*'s amazing JavaScript (ES6) answer](https://codegolf.stackexchange.com/a/118363/52210).
My own approach was almost 2x as long..
[Try it here.](https://tio.run/nexus/java-openjdk#hc/NboJAEADgu08x8bQTWkRWaCLavkA5eTQ90JWYSWEwMNi0hGfHxd@etnvZZOabP1NkTQNpNxAL0DpINlIT78GoMcDY1bm0NQOt@M0ofvY8wuV7xXtfqgtV9KRj9BS/KluPo8LldIpJPwAc2s@CDDSSif2OFe2gzIjVpXT7ARl2E7AvhRLWwPk3pAqTc2jz00he@lUr/sFqKViVvlFzxMRmZzOYu1j4YE6n7y50scWDOdtFf5wTxneondcGwQgt22nngqG@wa/on9ELHV2pODeMb@z3RY8N@0k/nAA)
**Explanation:**
```
int i=0; // Temp integer `i` (on class level)
String c(int n){ // Method with integer parameter and String return-type
return i<n? // If `i` is smaller than the input integer
c(n-++i) // Return a recursive call with input minus `i+1` (and raise `i` by 1 in the process)
: // Else:
Long.toString(i,36)+ // Return `i` as Base-36 +
(n>(i=0)? // (If the input integer is larger than 0 (and reset `i` to 0 in the process)
c(n) // Recursive call with the input integer
: // Else:
""); // an empty String)
} // End of method
```
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~115~~ ~~108~~ ~~38~~ 34 bytes
```
.+
$*¶
(\G¶|¶\1)+
0$1
+T`_w¶`w_`.¶
```
[Try it online!] (Includes test suite) Uses uppercase letters. Edit: Saved ~~70~~ 74 bytes by shamelessly adapting @MartinEnder's answer to [Is this number triangular?](https://codegolf.stackexchange.com/questions/122087) Explanation: The number is converted into unary, then the largest possible triangular number is repeatedly matched until the number is exhausted. Each match is then converted into base 36.
[Answer]
# PHP, 74 Bytes
```
for(;$n=&$argn;$t.=$i>10?chr($i+86):$i-1)for($i=0;$n>=++$i;)$n-=$i;echo$t;
```
[Online Version](http://sandbox.onlinephpfunctions.com/code/c53fa24bea90d60a6a6436ce33fa684dae63caea)
[Answer]
# R, 87 bytes
Originally, I tried to preset the possible Triangular numbers. This led to this code with 105 bytes:
```
pryr::f(n,{l=cumsum(1:35)
k=''
while(n){y=tail(which(l<=n),1)
n=n-l[y]
k=paste0(k,c(1:9,letters)[y])}
k})
```
This required more indexing so I tried the methodology from @Arnauld to reduce the bytes down to 87.
```
pryr::f(n,{k='';while(n){t=0;while(t<n){t=t+1;n=n-t};k=paste0(k,c(1:9,letters)[t])};k})
```
Both codes made use of the preset letters, since their I couldn't find a short way to convert to base 36.
] |
[Question]
[
*This is my first codegolf question, so I apologize in advance if it's not appropriate, and I welcome any feedback.*
I have a file with this format:
```
a | rest of first line
b | rest of second line
b | rest of third line
c | rest of fourth line
d | rest of fifth line
d | rest of sixth line
```
The actual contents vary, as does the delimiter. The contents are just text. The delimiter only appears once per line. For this puzzle, feel free to change the delimiter, e.g. use "%" as the delimiter.
Desired output:
```
a | rest of first line
b | rest of second line % rest of third line
c | rest of fourth line
d | rest of fifth line % rest of sixth line
```
I already have both ruby and awk scripts to merge this, but I suspect it's possible to have a short oneliner. i.e. a one-liner that can be used along with pipes and other commands on the command line. I can't figure it out, and my own script is to long to just compress on the command line.
Shortest characters preferred. Input is not necessarily sorted, but we are only interested in merging consecutive lines with matching first fields. There are unlimited lines with matching first fields. Field 1 could be anything, e.g. names of fruits, proper names, etc.
(I run on MacOS, so I am personally most interested in implementations that run on the mac).
---
Here is a second example/test. Notice "|" is the delimiter. The space before the "|" is irrelevant, and if resent should be considered part of the key. I am using "%" as a delimited in the output, but again, feel free to change the delimiter (but don't used square brackets).
Input:
```
why|[may express] surprise, reluctance, impatience, annoyance, indignation
whom|[used in] questions, subordination
whom|[possessive] whose
whom|[subjective] who
whoever|[objective] whomever
whoever|[possessive] whosever
who|[possessive] whose
who|[objective] whom
```
Desired output:
```
why|[may express] surprise, reluctance, impatience, annoyance, indignation
whom|[used in] questions, subordination%[possessive] whose%[subjective] who
whoever|[objective] whomever%[possessive] whosever
who|[possessive] whose%[objective] whom
```
[Answer]
# [Retina](https://github.com/mbuettner/retina), 17 bytes
* 12 bytes saved thanks to @MartinEnder
* 1 byte saved thanks to @jimmy23013
Scored in ISO 8859-1 encoded bytes.
Uses `;` instead of `|` as the input field separator.
```
(?<=(.+;).+)¶\1
%
```
[Try it online.](http://retina.tryitonline.net/#code=KD88PSguKzspLispwrZcMQol&input=d2h5O1ttYXkgZXhwcmVzc10gc3VycHJpc2UsIHJlbHVjdGFuY2UsIGltcGF0aWVuY2UsIGFubm95YW5jZSwgaW5kaWduYXRpb24Kd2hvbTtbdXNlZCBpbl0gcXVlc3Rpb25zLCBzdWJvcmRpbmF0aW9uCndob207W3Bvc3Nlc3NpdmVdIHdob3NlCndob207W3N1YmplY3RpdmVdIHdobwp3aG9ldmVyO1tvYmplY3RpdmVdIHdob21ldmVyCndob2V2ZXI7W3Bvc3Nlc3NpdmVdIHdob3NldmVyCndobztbcG9zc2Vzc2l2ZV0gd2hvc2UKd2hvO1tvYmplY3RpdmVdIHdob20K)
[Answer]
# [V](https://github.com/DJMcMayhem/V), ~~16~~ 13 bytes
```
òí^¨á«©.*úsî±
```
[Try it online!](http://v.tryitonline.net/#code=w7LDrV7CqMOhwqvCqS4qw7pzw67CsQ&input=YSB8IHJlc3Qgb2YgZmlyc3QgbGluZQpiYXQgfCByZXN0IG9mIHNlY29uZCBsaW5lCmJhdCB8IHJlc3Qgb2YgdGhpcmQgbGluZQpjIHwgcmVzdCBvZiBmb3VydGggbGluZQpkIHwgcmVzdCBvZiBmaWZ0aCBsaW5lCmQgfCByZXN0IG9mIHNpeHRoIGxpbmU)
You said
>
> Feel free to change the delimiter
>
>
>
So I picked `|` as the delimiter. If this is invalid, let me know and I'll change it.
Explanation:
```
ò #Recursively:
í #Search for the following on any line:
^¨á«© #1 or more alphabetic characters at the beginning of the line
.* #Followed by anything
ús #Mark everything after this to be removed:
î± #A new line, then the first match again (one or more alphabetic characters)
```
[Answer]
# Perl `-0n`, 2 + 43 = 45 bytes
```
s/
.*\|/%/g,print for/(.*\|)((?:
\1|.)*
)/g
```
Demo:
```
$ perl -0ne 's/
> .*\|/%/g,print for/(.*\|)((?:
> \1|.)*
> )/g' <<EOF
> why|[may express] surprise, reluctance, impatience, annoyance, indignation
> whom|[used in] questions, subordination
> whom|[possessive] whose
> whom|[subjective] who
> whoever|[objective] whomever
> whoever|[possessive] whosever
> who|[possessive] whose
> who|[objective] whom
> EOF
why|[may express] surprise, reluctance, impatience, annoyance, indignation
whom|[used in] questions, subordination%[possessive] whose%[subjective] who
whoever|[objective] whomever%[possessive] whosever
who|[possessive] whose%[objective] whom
```
[Answer]
# SQL (PostgreSQL), ~~43~~ 72 bytes
```
COPY T FROM'T'(DELIMITER'|');SELECT a,string_agg(b,'%')FROM T GROUP BY A
```
This takes advantage of the handy string\_agg aggregate function in PostgreSQL. Input is from a table called `T` with 2 columns `A` and `B`. To comply with the question better I have included to command to load data from a file into the table. The file is `T` as well. I haven't counted the table create statement.
The output will be unordered, but if that is a problem it can be fixed with an `ORDER BY A`
[SQLFiddle](http://sqlfiddle.com) didn't want to play for me, but this is what I get in my setup.
```
CREATE TABLE T (A VARCHAR(9),B VARCHAR(30));
COPY T FROM'T'(DELIMITER'|');SELECT a,string_agg(b,'%')FROM T GROUP BY A
a string_agg
--- ----------------------------------------
c rest of fourth line
b rest of second line%rest of third line
a rest of first line
d rest of fifth line%rest of sixth line
```
[Answer]
# C, 127 bytes
```
o[99],n[99],p=n;main(i){for(;gets(n);strncmp(o,n,i-p)?printf(*o?"\n%s":"%s",n),strcpy(o,n):printf(" /%s",i))i=1+strchr(n,'|');}
```
Works with gcc. Changed delimiter to `/`. Takes input from stdin and writes output to stdout, so call with input redirection `./a.out <filename`
Ungolfed:
```
o[99],n[99] //declare int, to save two bytes for the bounds
,p=n; //p is an int, saves one byte as opposed to applying an (int) cast to n,
//or to declaring o and n as char arrays
main(i){for(;gets(n);strncmp(o,n,i-p //an (int)n cast would be needed;
// -(n-i) does not work either,
//because pointer arithmetics scales to (int*)
)?printf(*o?"\n%s":"%s" //to avoid a newline at the beginning of output
,n),strcpy(o,n):printf(" /%s",i))i=1+strchr(n,'|');}
```
[Answer]
# Pyth - 15 bytes
Making a few assumptions about the problem, will change when OP clarifies.
```
jm+Khhd-sdK.ghk
```
[Try it online here](http://pyth.herokuapp.com/?code=jm%2BKhhd-sdK.ghk&input=%5B%27a%7Crest+of+first+line%27%2C+%27b%7Crest+of+second+line%27%2C+%27b%7Crest+of+third+line%27%2C+%27c%7Crest+of+fourth+line%27%2C+%27d%7Crest+of+fifth+line%27%2C+%27d%7Crest+of+sixth+line%27%5D&debug=0).
[Answer]
# Python 3 - 146 Bytes
Input is the filename or file path of the file, output is to stdout. Could be a lot shorter if I could take input as raw text from command line
Takes input from stdin and outputs to stdin. Setup with separator `"|"`. To test the first example input use the separator `" | "`
```
from itertools import*
for c,b in groupby([x.split("|")for x in input().split("\n")],key=lambda x:x[0]):print(c,"|"," % ".join((a[1]for a in b)))
```
[Answer]
# Java 7, 167 bytes
It can probably be golfed more by using a different approach..
```
import java.util.*;Map c(String[]a){Map m=new HashMap();for(String s:a){String[]x=s.split("=");Object l;m.put(x[0],(l=m.get(x[0]))!=null?l+"%"+x[1]:x[1]);}return m;}
```
*NOTE:* The method above creates and returns a `HashMap` with the desired key-value pairs. However, it doesn't print it in the exact output as in OP's question with `|` as output-delimiter between the keys and new values. Judging by [*MickeyT's SQL answer*](https://codegolf.stackexchange.com/a/81104/52210) where he returned a database table I figured this is allowed; if not more bytes should be added for a print function.
**Ungolfed & test code:**
```
import java.util.*;
class Main{
static Map c(String[] a){
Map m = new HashMap();
for(String s : a){
String[] x = s.split("\\|");
Object l;
m.put(x[0], (l = m.get(x[0])) != null
? l + "%" + x[1]
: x[1]);
}
return m;
}
public static void main(String[] a){
Map m = c(new String[]{
"why|[may express] surprise, reluctance, impatience, annoyance, indignation",
"whom|[used in] questions, subordination",
"whom|[possessive] whose",
"whom|[subjective] who",
"whoever|[objective] whomever",
"whoever|[possessive] whosever",
"who|[possessive] whose",
"who|[objective] whom"
});
// Object instead of Map.EntrySet because the method returns a generic Map
for (Object e : m.entrySet()){
System.out.println(e.toString().replace("=", "|"));
}
}
}
```
**Output:**
```
whoever|[objective] whomever%[possessive] whosever
whom|[used in] questions, subordination%[possessive] whose%[subjective] who
why|[may express] surprise, reluctance, impatience, annoyance, indignation
who|[possessive] whose%[objective] whom
```
[Answer]
### PowerShell, 85 bytes
Strings are merged using hashtable:
```
%{$h=@{}}{$k,$v=$_-split'\|';$h.$k=($h.$k,$v|?{$_})-join'%'}{$h.Keys|%{$_+'|'+$h.$_}}
```
### Example
Since PowerShell doesn't support stdin redirection via `<`, I'm assuming that `Get-Content .\Filename.txt |` will be used as default I/O method.
```
Get-Content .\Filename.txt | %{$h=@{}}{$k,$v=$_-split'\|';$h.$k=($h.$k,$v|?{$_})-join'%'}{$h.Keys|%{$_+'|'+$h.$_}}
```
### Output
```
whoever|[objective] whomever%[possessive] whosever
why|[may express] surprise, reluctance, impatience, annoyance, indignation
whom|[used in] questions, subordination%[possessive] whose%[subjective] who
who|[possessive] whose%[objective] whom
```
[Answer]
## APL, 42 chars
```
{⊃{∊⍺,{⍺'%'⍵}/⍵}⌸/↓[1]↑{(1,¯1↓'|'=⍵)⊂⍵}¨⍵}
```
[Answer]
# Sed, 55 bytes
```
:a N;:b s/^\([^|]*\)|\([^\n]*\)\n\1|/\1|\2 %/;ta;P;D;tb
```
---
Test run :
```
$ echo """why|[may express] surprise, reluctance, impatience, annoyance, indignation
> whom|[used in] questions, subordination
> whom|[possessive] whose
> whom|[subjective] who
> whoever|[objective] whomever
> whoever|[possessive] whosever
> who|[possessive] whose
> who|[objective] whom""" | sed ':a N;:b s/^\([^|]*\)|\([^\n]*\)\n\1|/\1|\2 %/;ta;P;D;tb'
why|[may express] surprise, reluctance, impatience, annoyance, indignation
whom|[used in] questions, subordination %[possessive] whose %[subjective] who
whoever|[objective] whomever %[possessive] whosever
who|[possessive] whose %[objective] whom
```
[Answer]
# q/kdb+, 46 bytes
**Solution:**
```
exec"%"sv v by k from flip`k`v!("s*";"|")0:`:f
```
**Example:**
```
q)exec"%"sv v by k from flip`k`v!("s*";"|")0:`:f
who | "[possessive] whose%[objective] whom"
whoever| "[objective] whomever%[possessive] whosever"
whom | "[used in] questions, subordination%[possessive] whose%[subjective] who"
why | "[may express] surprise, reluctance, impatience, annoyance, indignation"
```
**Explanation:**
```
`:f // assumes the file is named 'f'
("s*";"|")0: // read in file, assume it has two columns delimitered by pipe
flip `k`v // convert into table with columns k (key) and v (value)
exec .. by k // group on key
"%"sv v // join values with "%"
```
] |
[Question]
[
*Squaring the Square* is a process of tiling a square using only other squares. If this tiling only uses squares of different sizes, then it is considered to be *perfect*. The [smallest possible perfect squared square](https://en.wikipedia.org/wiki/Squaring_the_square) is a 112x112 square tiled using 21 different squares.
I have created the ascii art version of this square below:
```
################################################################################################################
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ############################
# ## ############################
# ## ## ## #
# ## ## ## #
# ## ## ## #
# ## ## ## #
# ## ## ## #
# ## ## ## #
# ############################################# #
# ############################################# #
# ## ## ## ## #
# ## ## ## ## #
# ## ## ## ## #
# ## ## ## ## #
# ## ## ## ## #
# ## ## ## ## #
# ## ## ## ## #
# ## ## ## ## #
# ## ## ## ## #
# ## ## ###############################
# ## ## ###############################
# ## ## ## ## #
# ## ## ## ## #
################################################################## ## ## #
################################################################## ## ## #
# ## ## ########################### #
# ## ## ########################### #
# ## ## ## ## ## #
# ## ## ## ## ## #
# ## ## ## ## ## #
# ## ## ## ## ## #
# ## ## ## ## ## #
# ## ################## ## #
# ## ################## ## #
# ## ## ## ## #
# ## ## ## ## #
# ## ## ## ## #
# ## ## ## ## #
# ## ## ## ## #
# ## ## ## ## #
# ## ## ## ## #
# ## ## ## ## #
# ## ## ## ## #
# ## ## ###########################################
# ## ## ###########################################
# ## ## ## #
# ## ## ## #
# ## ## ## #
# ########################################### #
# ########################################### #
# ## ## ## #
# ## ## ## #
################################## ## #
################################## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
# ## ## #
################################################################################################################
```
Your submission should print out the above square. You may print a reflection and/or rotation of the above square if you wish. A trailing newline on the last line is allowed. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the smallest submission wins!
[Answer]
# Mathematica ~~360~~ 426
The code works by first drawing the perfect square of squares, rasterising and binarizing the image, and then converting 0 to "#" and 1 to " ".
The output is returned as ordinary ASCII characters in a table.
```
f@{n_,x_,y_}:=Rectangle[{x,y},{x+n,y+n}];t=Transpose;
Flatten[i=Rasterize[Graphics[{EdgeForm[{(*Thickness[.015],*)Black}],White,
f/@ Partition[{33,0,0,29,0,33,50,0,62,37,33,0,25,29,37,42,70,0,18,70,42,24,88,42,9,54,53,7,63,53,15,50,62,17,65,60,
11,82,66,19,93,66,35,50,77,27,85,85},3]
},ImageSize->70
],RasterSize->70]//Binarize//ImageData,1]/.{0:> "#",1:> " "};
GraphicsGrid@t@Most@Most@Rest@t[Most@Most[Rest[ArrayReshape[%,Dimensions[i]]]]]
```

---
I prefer this rendering, obtained by deleting `Thickness[.015]`

[Answer]
# CJam, ~~88~~ ~~84~~ 83 bytes
```
'p:Ci_C*a*"2# *%!"{i_S*a*{3af.|W%z}4*1$0=C#C*f{\+}..e<{_C&{oNo}|}%}/
```
[Test it here.](http://cjam.aditsu.net/#code='p%3ACi_C*a*%222%23%1B%08%13%0F%11%0B%06%18%1D%19%09%02%07%12%10*%04%25!%22%7Bi_S*a*%7B3af.%7CW%25z%7D4*1%240%3DC%23C*f%7B%5C%2B%7D..e%3C%7B_C%26%7BoNo%7D%7C%7D%25%7D%2F)
## Explanation
Here is the basic idea: start with an "empty" 112x112 square. Now go through the squares in reading order (left to right, top to bottom). Add each square into the first available position. Afterwards, print all completed lines - this ensures that we only need to check the first (remaining) line to figure out where the next square goes.
The empty grid is initialised to `p`s, because I needed a character with character code larger than space and `#`, and because I could reuse its own character code `112` for the size of the initial grid. I made use of some of [Dennis's ASCII art tricks](https://codegolf.stackexchange.com/a/52627/8478) here to fill the small squares into the grid.
```
'p:C e# Store the character 'p' in C.
i e# Convert to its character code 112.
_C*a* e# Generate a 112x112 array of p's.
"2# *%!" e# The 21 characters in this string correspond to the side lengths of
e# the squares in the solution in reading order.
{ e# For each character in that string...
i e# Convert to its character code (the current square's side length N).
_S*a* e# Generate an NxN array of spaces.
{ e# Run this block 4 times. Each iteration turns the leading column into #'s
e# and then rotates the square by 90 degrees.
3af.| e# For the first character in each row, take the bitwise OR with 3.
e# This turns spaces into #'s and leaves #'s unchanged.
W%z e# Reverse and transpose, which rotates by 90 degrees.
}4*
1$0= e# Copy the remaining grid and fetch the top row.
C# e# Find the index of the first 'p'.
C* e# Get a string of that many p's.
f{\+} e# Prepend this string to each row of the small square, which gives the
e# square the correct horizontal position.
..e< e# Take the pairwise minimum of the square and the remaining grid. The p's
e# prepended to the square will leave the grid unchanged, but the spaces
e# and #'s in the square will overwrite the p's in the grid.
{ e# Map this block onto each row of the grid.
_C& e# Copy the row and check if any p's are left.
{oNo}| e# If NOT, the row is complete and we print it together with a newline.
e# This also removes the row from the grid, such that the top row for
e# the next iteration will have space for the next square left.
}%
}/
```
[Answer]
# Ruby, 180 bytes
Golfed version based on the ungolfed version below. We take advantage of the fact that there are typically 2 or 3 squares with the same `y` coordinate for the top left corner.
The first magic string contains ASCII codes for the `square sidelength+70` and `y increment +40`. When encountering a square sidelength (Ascii code >67) we assume the next square is at the same y coordinate, and the x coordinate can be obtained by incrementing the current x coordinate by `sidelength+2`. When encountering a y increment (Ascii code<67) we increment the y coordinate accordingly and reset the x coordinate to the figure encoded in the second magic string.
```
a=Array.new(112){?#*112}
x=y=1
j=9
'vg_CLW0SUO3J\,a]M*KV/T3n-Hi,e'.each_byte{|i|i>67?(s=i-70;(y..y+s-1).map{|i|a[i][x,s]=" "*s};x+=s+2):(x=')Fo_h){[~'[j-=1].ord-40;y+=i-40)}
puts a
```
**Original version**
This (completely ungolfed) solution contains 315 bytes, excluding unnecessary blank lines and indents. It simply creates an array of 112 strings of 112 `#`'s then replaces the insides of the squares with spaces.
```
$a=Array.new(112){"#"*112}
def f(x,y,s)
(y..y+s-1).map{|i|$a[i][x,s]=" "*s}
end
f(1,1,48)
f(51,1,33)
f(86,1,25)
f(86,28,6)
f(94,28,17)
f(51,36,13)
f(66,36,15)
f(83,36,9)
f(83,47,4)
f(89,47,22)
f(1,51,27)
f(30,51,23)
f(55,51,7)
f(64,53,5)
f(71,53,16)
f(55,60,14)
f(71,71,40)
f(30,76,2)
f(34,76,35)
f(1,80,31)
puts $a
```
[Answer]
# C, 198 bytes
```
char*i="bSK8C?A;6HMI927B@Z4UQ",o[112][113],x,y,p,q,n;main(){for(;y<112;puts(o[y]),y++)for(x=-1;++x<112;)if(!o[y][x]){n=*i++-48;for(p=-1;++p<n;)for(q=-1;++q<n;)o[q+y][p+x]=p&&n-1-p&&q&&n-1-q?32:35;}}
```
### (Ungolfed)
```
char *i="bSK8C?A;6HMI927B@Z4UQ", o[112][113], x, y, p, q, n;
main() {
for ( ; y<112; puts(o[y]),y++) {
for (x=-1; ++x<112; ) {
if (!o[y][x]) {
n = *i++ - 48;
for (p=-1; ++p<n; ) {
for(q=-1; ++q<n; ) {
o[q+y][p+x] = (p && n-1-p && q && n-1-q) ? ' ' : '#';
}
}
}
}
}
}
```
All this does is scan through an array of 112×112 bytes (initialized to zero). Whenever it encounters a zero byte, it fetches a value from array `i` and adds a box of the corresponding size. The extra byte in each row acts as a string terminator so we can use `puts()` to output entire lines instead of using `putchar()` to output characters individually.
This can probably be golfed a little more, but I don't think it stands much chance of beating [steveverrill's answer](https://codegolf.stackexchange.com/a/52650/11006).
[(ideone link)](http://ideone.com/AL3Yex)
[Answer]
# R, ~~293~~ ~~291~~ ~~287~~ 282 bytes
```
a=array('#',112:113)
a[,113]='
'
for(g in list(c(0,0,49,34,26),c(27,85,7,18),c(35,50,14,16,10),c(46,82,5,23),c(50,0,28,24,8,1),c(52,63,6,17),c(59,54,15),c(70,70,41),c(75,29,3,36),c(79,0,32))){y=g[1];x=g[2]
for(b in g[0:1-2]){a[(y+2):(y+b),(x+2):(x+b)]=' '
x=x+b+1}}
cat(t(a),sep='')
```
After I did this, I realized I had done almost the identical process as @steveverrill. An array of '#' and blank the square interiors. Can probably squeeze some more out of this. The carriage return for the 3rd line is significant. Thanks to AlexA for a few.
[Answer]
# MS-DOS Binary, 137
The following code will run in MS-DOS if you write it into a file called square.com, no further compilation required (but since it's given in hex, you need to "unhex" it first):
```
fcba8f01b82370e83000bd1400bb4d018b1743438a27b02043e81e004d75
f1b97000ba8f3289d7b00daab00aaab82409aa83ea70cd214975ecc331c9
88e189ce89d788e1f3aa83c2704e75f4c3201d30e223218527190524063d
1f11521d0d811c0f321f09921c04b8141670101b4d12176619076f1905a6
141066120e4602288d100221022300021f
```
The output will be unrecognisable in most terminals, but you can redirect it to a file (`square.com > output.txt`) and look at it in an text editor. If you want something more readable, the following code will produce a working square.com if fed into debug.exe (`debug.exe < square.asm`):
```
a
cld
mov dx,18f
mov ax,7023
call 13a
mov bp,14
mov bx,14d
mov dx,[bx]
inc bx
inc bx
mov ah,[bx]
mov al,20
inc bx
call 13a
dec bp
jnz 110
mov cx,70
mov dx,328f
mov di,dx
mov al,d
stosb
mov al,a
stosb
mov ax,924
stosb
sub dx,70
int 21
dec cx
jnz 125
ret
xor cx,cx
mov cl,ah
mov si,cx
mov di,dx
mov cl,ah
rep stosb
add dx,70
dec si
jnz 140
ret
db 20,1d,30,e2,23,21
db 85,27,19,05,24,6
db 3d,1f,11,52,1d,d
db 81,1c,f,32,1f,9
db 92,1c,4,b8,14,16
db 70,10,1b,4d,12,17
db 66,19,7,6f,19,5
db a6,14,10,66,12,e
db 46,02,28,8d,10,2
db 21,02,23,00,02,1f
n square.com
rcx
89
w
q
```
[Answer]
# Matlab/Octave, 258
As always, Matrices. I hardcoded the row and the column indices of each square ans well as the size. I can use these to fill up a big 'blank' square of `#`s.
```
r=[2,2,2,29,29,37,37,37,48,48,52,52,52,54,54,61,72,77,77,81];
c=[2,52,87,87,95,52,67,84,84,90,2,31,56,65,72,56,72,31,35,2];
s=[47,32,24,5,16,12,14,8,3,21,26,22,6,4,15,13,39,1,34,30];
z=ones(112)*35;
for i=1:20;
z(r(i)+(0:s(i)),c(i)+(0:s(i)))=32;
end;disp([z,''])
```
[Answer]
# Bash, 252
Every codegolfer should be able to beat a general purpose compression algorithm:
```
base64 -d<<<H4sIADyFv1UCA+3ZOw6EMAwFwH5PgeT735EOUSyfQAgOmVeCxUgusAkRbfOLqTARd0qAQCAQCAQCgcAvg80375dW/T+lQGAbsCCdgvsdXl0AAoHjgM8e7mUA92bKG+DtpAevDPflRsko7BXcKAQCD9+X3wOPCoFA4ABgnZ/OmcHTS+bw4PXzkV7Ak93KDdboVm6wxrOAQCAQCAQCgUAgENj++7BuZsq8xQ1vMQAA|gunzip
```
Thanks to Toby Speight for the hint to use shorter input (silly me used `gzip` instead of `gzip -9` for compression) and a here-string.
] |
[Question]
[
Write a named function or program that computes the quaternion product of two quaternions. Use as few bytes as possible.
## Quaternions
[Quaternions](http://en.wikipedia.org/wiki/Quaternion) are an extension of the real numbers that further extends the complex numbers. Rather than a single imaginary unit `i`, quaternions use three imaginary units `i,j,k` that satisfy the relationships.
```
i*i = j*j = k*k = -1
i*j = k
j*i = -k
j*k = i
k*j = -i
k*i = j
i*k = -j
```
(There's also tables of these on the [Wikipedia page](http://en.wikipedia.org/wiki/Quaternion).)
In words, each imaginary unit squares to `-1`, and the product of two different imaginary units is the remaining third one with a `+/-` depending on whether the cyclic order `(i,j,k)` is respected (i.e., the [right-hand-rule](http://en.wikipedia.org/wiki/Right_hand_rule)). So, the order of multiplication matters.
A general quaternion is a linear combination of a real part and the three imaginary units. So, it is described by four real numbers `(a,b,c,d)`.
`x = a + b*i + c*j + d*k`
So, we can multiply two quaternions using the distributive property, being careful to multiply the units in the right order, and grouping like terms in the result.
```
(a + b*i + c*j + d*k) * (e + f*i + g*j + h*k)
= (a*e - b*f - c*g - d*h) +
(a*f + b*e + c*h - d*g)*i +
(a*g - b*h + c*e + d*f)*j +
(a*h + b*g - c*f + d*e)*k
```
Seen this way, quaternion multiplication can be seen as a map from a pair of 4-tuples to a single 4-tuples, which is what you're asked to implement.
## Format
You should write either a *program* or *named function*. A program should take inputs from STDIN and print out the result. A function should take in function inputs and return (not print) an output.
Input and output formats are flexible. The input is eight real numbers (the coefficients for two quaternions), and the output consists of four real numbers. The input might be eight numbers, two lists of four numbers, a 2x4 matrix, etc. The input/output format don't have to be the same.The ordering of the `(1,i,j,k)` coefficients is up to you.
The coefficients can be negative or non-whole. Don't worry about real precision or overflows.
**Banned:** Function or types specifically for quaternions or equivalents.
## Test cases
These are in `(1,i,j,k)` coefficient format.
```
[[12, 54, -2, 23], [1, 4, 6, -2]]
[-146, -32, 270, 331]
[[1, 4, 6, -2], [12, 54, -2, 23]]
[-146, 236, -130, -333]
[[3.5, 4.6, -0.24, 0], [2.1, -3, -4.3, -12]]
[20.118, 2.04, 39.646, -62.5]
```
## Reference Implementation
In Python, as function:
```
#Input quaternions: [a,b,c,d], [e,f,g,h]
#Coeff order: [1,i,j,k]
def mult(a,b,c,d,e,f,g,h):
coeff_1 = a*e-b*f-c*g-d*h
coeff_i = a*f+b*e+c*h-d*g
coeff_j = a*g-b*h+c*e+d*f
coeff_k = a*h+b*g-c*f+d*e
result = [coeff_1, coeff_i, coeff_j, coeff_k]
return result
```
[Answer]
## Python (83)
```
r=lambda A,B,R=range(4):[sum(A[m]*B[m^p]*(-1)**(14672>>p+4*m)for m in R)for p in R]
```
Takes two lists `A,B` in `[1,i,j,k]` order and returns a result in the same format.
The key idea is that with `[1,i,j,k]` corresponding to indices `[0,1,2,3]`, you get the product's index (up to sign) by XOR'ing the indices. So, the terms that get placed in index `p` are those who indices XOR to `p`, and are thus the products `A[m]*B[m^p]`.
It only remains to make the signs work out. The shortest way I found was to simply code them into a magic string. The 16 possibilities for `(m,p)` are turned into numbers `0` to `15` as `p+4*m`. The number `14672` in binary has `1`'s at the places where `-1` signs are needed. By shifting it the appropriate number of places , a `1` or `0` winds up at the last digit, making the number odd or even, and so `(-1)**` is either `1` or `-1` as needed.
[Answer]
# CJam, ~~49~~ ~~45~~ 39 bytes
```
"cM-^\M-^G-^^KM-zP"256bGbq~m*f{=:*}4/{:-W*}/W*]`
```
The above uses caret and M notation, since the code contains unprintable characters.
At the cost of two additional bytes, those characters can be avoided:
```
6Z9C8 7YDXE4BFA5U]q~m*f{=:*}4/{:-W*}/W*]`
```
You can try this version online: [CJam interpreter](http://cjam.aditsu.net/)
### Test cases
To calculate `(a + bi + cj + dk) * (e + fi + gj + hk)`, use the following input:
```
[ d c b a ] [ h g f e ]
```
The output will be
```
[ z y x w ]
```
which corresponds to the quaternion `w + xi + yj + zk`.
```
$ base64 -d > product.cjam <<< ImOchy0eS/pQIjI1NmJHYnF+bSpmez06Kn00L3s6LVcqfS9XKl1g
$ wc -c product.cjam
39 product.cjam
$ LANG=en_US cjam product.cjam <<< "[23 -2 54 12] [-2 6 4 1]"; echo
[331 270 -32 -146]
$ LANG=en_US cjam product.cjam <<< "[-2 6 4 1] [23 -2 54 12]"; echo
[-333 -130 236 -146]
$ LANG=en_US cjam product.cjam <<< "[0 -0.24 4.6 3.5] [-12 -4.3 -3 2.1]"; echo
[-62.5 39.646 2.04 20.118]
```
### How it works
```
6Z9C8 7YDXE4BFA5U] " Push the array [ 6 3 9 12 8 7 2 13 1 14 4 11 15 10 5 0]. ";
q~ " Read from STDIN and interpret the input. ";
m* " Compute the cartesian product of the input arrays. ";
f " Execute the following for each element of the first array: ";
{ " Push the cartesian product (implicit). ";
= " Retrieve the corresponding pair of coefficients. ";
:* " Calculate their product. ";
} " ";
4/ " Split into chunks of 4 elements. ";
{:-W*}/ " For each, subtract the first element from the sum of the others. ";
W* " Multiply the last integers (coefficient of 1) by -1. ";
]` " Collect the results into an array and stringify it. ";
```
[Answer]
# Python - ~~90 75 72~~ 69
**Pure Python, no libraries - 90:**
```
m=lambda a,b,c,d,e,f,g,h:[a*e-b*f-c*g-d*h,a*f+b*e+c*h-d*g,a*g-b*h+c*e+d*f,a*h+b*g-c*f+d*e]
```
It's probably pretty hard to shorten this "default" solution in Python. But I'm very curious as to what other might come up with. :)
---
**Using NumPy - ~~75 72~~ 69:**
Well, since the input and output are rather flexible, we can use some NumPy functions and exploit the [scalar-vector representation](http://en.wikipedia.org/wiki/Quaternion#Scalar_and_vector_parts):
```
import numpy
m=lambda s,p,t,q:[s*t-sum(p*q),s*q+t*p+numpy.cross(p,q)]
```
Input arguments `s` and `t` are the scalar parts of the two quaternions (the real parts) and `p` and `q` are the corresponding vector parts (the imaginary units). Output is a list containing scalar part and vector part of the resulting quaternion, the latter being represented as NumPy array.
**Simple test script:**
```
for i in range(5):
a,b,c,d,e,f,g,h=np.random.randn(8)
s,p,t,q=a, np.array([b, c, d]), e, np.array([f, g, h])
print mult(a, b, c, d, e, f, g, h), "\n", m(s,p,t,q)
```
(`mult(...)` being the OP's reference implementation.)
Output:
```
[1.1564241702553644, 0.51859264077125156, 2.5839001110572792, 1.2010364098925583]
[1.1564241702553644, array([ 0.51859264, 2.58390011, 1.20103641])]
[-1.8892934508324888, 1.5690229769129256, 3.5520713781125863, 1.455726589916204]
[-1.889293450832489, array([ 1.56902298, 3.55207138, 1.45572659])]
[-0.72875976923685226, -0.69631848934167684, 0.77897519489219036, 1.4024428845608419]
[-0.72875976923685226, array([-0.69631849, 0.77897519, 1.40244288])]
[-0.83690812141836401, -6.5476014589535243, 0.29693969165495304, 1.7810682337361325]
[-0.8369081214183639, array([-6.54760146, 0.29693969, 1.78106823])]
[-1.1284033842268242, 1.4038096725834259, -0.12599103441714574, -0.5233468317643214]
[-1.1284033842268244, array([ 1.40380967, -0.12599103, -0.52334683])]
```
[Answer]
# Haskell, 85
```
m a b c d e f g h=[a*e-b*f-c*g-d*h,a*f+b*e+c*h-d*g,a*g-b*h+c*e+d*f,a*h+b*g-c*f+d*e]
```
Porting it to Haskell saves us a few chars ;)
[Answer]
## Mathematica ~~83~~ 50
Probably can be golfed more..
```
p = Permutations;
f = #1.(Join[{{1, 1, 1, 1}}, p[{-1, 1, -1, 1}][[1 ;; 3]]] p[#2][[{1, 8, 17, 24}]]) &
```
Spaces and newlines not counted & not needed.
Usage:
```
f[{a,b,c,d},{e,f,g,h}] (* => {x,w,y,z} *)
```
**EDIT**
How this works.
The Mathematica function `Permutations` makes all possible permutations of `#2` (the second argument). There are 24 permutations, but we only need `{e,f,g,h}`, `{f,e,h,g}`, `{g,h,e,f}`, and `{h,g,f,e}`. These are the first, 8th, 17th and 24th permutations. So the code
```
p[#2][[{1,8,17,24}]]
```
exactly selects these from the permutations of the second argument and returns them as a matrix. But then they don't have the correct sign yet. The code `p[{-1,1,-1,1}][[1;;3]]` returns a 3x4 matrix with the correct sign. We prepend it with `{1,1,1,1}` by using `Join`, and making a normal multiplication (`Times`, or as is the case here by just writing them after each other) between two matrices makes an element-by-element multiplication in Mathematica.
So finally, the result of
```
(Join[{{1, 1, 1, 1}}, p[{-1, 1, -1, 1}][[1 ;; 3]]] p[#2][[{1, 8, 17, 24}]])
```
is the matrix
```
e f g h
-f e -h g
-g h e -f
-h -g f e
```
Making a matrix multiplication between `{a,b,c,d}` (the first argument `#1`) and the former matrix gives the desired result.
**EDIT 2** Shorter code
Inspired by the Python code of Falko, I split up the quaternion in a scalar and a vector part, and use Mathematica's built in command `Cross` to calculate the cross product of the vector parts:
```
f[a_, A_, b_, B_] := Join[{a*b - A.B}, a*B + b*A + Cross[A, B]]
```
Usage:
```
f[a,{b,c,d},e,{f,g,h}] (* => {x,w,y,z} *)
```
[Answer]
## Python, 58 56 chars
```
m=lambda x,y,z,w:(x*z-y*(2*w.real-w),x*w+y*(2*z.real-z))
```
I take *very* liberal use of the input/output format wiggle room. The inputs are 4 complex numbers, encoded thusly:
```
x = a+b*i
y = c+d*i
z = e+f*i
w = g+h*i
```
It outputs a pair of complex numbers in a similar format, the first of the pair encodes the real and `i` part, the second encodes the `j` and `k` parts.
To see this works, note that the first quaternion is `x+y*j` and the second is `z+w*j`. Just evaluate `(x+y*j)*(z+w*j)` and realize that `j*t` = `conj(t)*j` for any imaginary number `t`.
[Answer]
## Python, 94
The most straightforward way isn't too long.
```
def m(a,b,c,d,e,f,g,h):return[a*e-b*f-c*g-d*h,a*f+b*e+c*h-d*g,a*g-b*h+c*e+d*f,a*h+b*g-c*f+d*e]
```
[Answer]
## JavaScript ES6 - 86
```
f=(a,b,c,d,e,f,g,h)=>[a*e-b*f-c*g-d*h,a*f+b*e+c*h-d*g,a*g-b*h+c*e+d*f,a*h+b*g-c*f+d*e]
```
[Answer]
# Lua - 99
Might as well.
```
_,a,b,c,d,e,f,g,h=unpack(arg)print(a*e-b*f-c*g-d*h,a*f+b*e+c*h-d*g,a*g-b*h+c*e+d*f,a*h+b*g-c*f+d*e)
```
Lua's "unpack()" frees the elements of a table. So the table 'arg' is where all the command line input is stored (including `arg[0]` which is the program's file name, it gets discarded).
[Answer]
# [Whispers v2](https://github.com/cairdcoinheringaahing/Whispers), 396 bytes
```
> 1
> 2
> 0
> 4
> Input
> Input
>> 6ᶠ2
>> 6ᵗ2
>> 7ⁿ3
>> 7ⁿ1
>> 10‖9
>> 8ⁿ3
>> 8ⁿ1
>> 13‖12
>> 7‖8
>> 11‖14
>> 8‖7
>> 14‖11
>> 15‖16
>> 19‖17
>> 20‖18
>> 4⋅5
>> L⋅R
>> Each 23 22 21
> [1,-1,-1,-1,1,1,1,-1,1,-1,1,1,1,1,-1,1]
>> Each 23 24 25
>> 26ᶠ4
>> 26ᵗ4
>> 28ᶠ4
> 8
>> 26ᵗ30
>> 31ᶠ4
>> 31ᵗ4
>> ∑27
>> ∑29
>> ∑32
>> ∑33
>> Output 34 35 36 37
```
[Try it online!](https://tio.run/##jZCxTsQwDIb3PoUfoI1iO03bpRsDEhISa9UBIaRjQSfuTqxlQEJiYumtvMSx8iz0RYqdNq2ABTVOPjv/7yZ53NzttrcPOxrHGjCpgSSshJM4v98e9utag//6eKcJTscAxfD0yRFQAe3Q9ZVSGffKZY9lD2dj15ehhlpzk67ri1BzWpssuaIPWCkGAelPMPjd8PqcK1wIXCmcXd9sgBiIgPRKDaZZHNOXLdOatz@sDig0Jb2ym@l0nKicalAudbaKjFEsNIuHlzcqIlQzMEUI73N52MsDAzvgHNgDF@PYsMlTcMankFlDLgXbJg0ZlJwlnNEZqR0bpBRyEWSyEotKNJKqk9okkwfI0GnGKihsCsxy3V@6P21WI7FqkK32YFbrf08XupA1iKX0MVaUXBkfjuPJ5O03 "Whispers v2 – Try It Online")
Takes input in the form
```
[a, b, c, d]
[e, f, g, h]
```
and outputs as
```
w
x
y
z
```
to represent \$q = w + xi + yj + zk\$
The structure tree of this answer is:
[](https://i.stack.imgur.com/sW2BG.png)
A good chunk of this answer comes from two main faults in Whispers:
* No function to reverse an array
* The usage of sets in the computation of the Cartesian product
Therefore, we can split the code into 3 sections.
## How it works
We'll use the following definitions for clarity and conciseness:
$$q = a + bi + cj + dk$$
$$p = e + fi + gj + hk$$
$$r = w + xi + yj + zk, \: (q \cdot p = r)$$
$$A = [a, b, c, d]$$
$$B = [e, f, g, h]$$
$$C = [w, x, y, z]$$
### Section 1: Permuting \$A\$ and \$B\$
The first section is by far the longest, stretching from line **1** to line **22**:
```
> 1
> 2
> 0
> 4
> Input
> Input
>> 6ᶠ2
>> 6ᵗ2
>> 7ⁿ3
>> 7ⁿ1
>> 10‖9
>> 8ⁿ3
>> 8ⁿ1
>> 13‖12
>> 7‖8
>> 11‖14
>> 8‖7
>> 14‖11
>> 15‖16
>> 19‖17
>> 20‖18
>> 4⋅5
```
The main purpose of this section is to permute \$B\$ so that simple element-wise multiplication between \$A\$ and \$B\$ is possible. There are four different arrangements of \$B\$ to multiply the elements of \$A\$ with:
$$B\_1 = [e, f, g, h]$$
$$B\_2 = [f, e, h, g]$$
$$B\_3 = [g, h, e, f]$$
$$B\_4 = [h, g, f, e]$$
The second input, \$B\$, is stored on line **6**. We then split \$B\$ down the middle, as each possible arrangement of \$B\$ is grouped in pairs. In order to reverse these pairs (to get the correct orders in \$B\_2\$ and \$B\_4\$), we take the first and last element, then concatenate them in reverse order:
```
>> 7ⁿ3
>> 7ⁿ1
>> 10‖9
```
(forming \$[f, e]\$) and
```
>> 8ⁿ3
>> 8ⁿ1
>> 13‖12
```
(forming \$[h, g]\$). We now have all the halves needed to form the arrangements, so we concatenate them together to form \$B\_1, B\_2, B\_3\$ and \$B\_4\$. Finally, we concatenate these four arrangements together to form \$B\_T\$. We then quickly make \$A\_T\$, defined as \$A\$ repeated \$4\$ times:
$$A\_T = [a, b, c, d, a, b, c, d, a, b, c, d, a, b, c, d]$$
$$B\_T = [e, f, g, h, f, e, h, g, g, h, e, f, h, g, f, e]$$
When each element of \$B\_T\$ is multiplied by the corresponding element in \$A\_T\$, we get the (signless) values in \$q \cdot p\$
## Section 2: Signs and products
As said in Section 1, the values in \$A\_T\$ and \$B\_T\$ correspond to the signless (i.e. positive) values of each of the coefficients in \$q \cdot p\$. No obvious pattern is found in the signs that would be shorter than simply hardcoding the array, so we hardcode the array:
```
> [1,-1,-1,-1,1,1,1,-1,1,-1,1,1,1,1,-1,1]
```
We'll call this array \$S\$ (signs). Next, we zip together each element in \$A\_T, B\_T\$ and \$S\$ and take the product of each sub-array e.g. \$[[a, e, 1], [b, f, -1], \dots, [e, f, -1], [d, e, 1]] \to D = [ae, -bf, \dots, -ef, de]\$.
## Section 3: Partitions and final sums.
Once we have the array of coefficients of \$q \cdot p\$, with signs, we need to split it into 4 parts (i.e. the four factorised coefficients of \$q \cdot p\$), and then take the sums. This leads us to the only golfing opportunity found: moving the
```
> 4
```
to line **4** rather than **26**, as it is used 6 times, each time saving a byte by moving it. Unfortunately, this costs a byte changing the **9** to a **10**, so only \$5\$ bytes are saved. The next section takes slices of size \$4\$ from the front of \$D\$, saving each slice to the corresponding row and passing on the shortened list of \$D\$. Once 4 slices are taken, we the take the sum of each, before outputting them all.
[Answer]
# [Sidef](https://github.com/trizen/sidef), 10 bytes
```
{|a,b|a*b}
```
Sidef has a built-in Quaternion type, as does [Odin](https://github.com/odin-lang/Odin/blob/5ac7fe453f5fbf0995c24f0c1c12ed439ae3aee9/examples/demo/demo.odin#L1483). Neither language versions used by TIO support this, however.
```
var f = {|a,b|a*b}
say f(Quaternion(12, 54, -2, 23), Quaternion(1, 4, 6, -2))
#=> Quaternion(-146, -32, 270, 331)
say f(Quaternion(1, 4, 6, -2), Quaternion(12, 54, -2, 23))
#=> Quaternion(-146, 236, -130, -333)
say f(Quaternion(3.5, 4.6, -0.24, 0), Quaternion(2.1, -3, -4.3, -12))
#=> Quaternion(10059/500, 51/25, 19823/500, -125/2)
```
[Answer]
# [Go](https://go.dev), 119 bytes
```
type F=float64
func f(a,b,c,d,e,f,g,h F)[]F{return[]F{a*e-b*f-c*g-d*h,a*f+b*e+c*h-d*g,a*g-b*h+c*e+d*f,a*h+b*g-c*f+d*e}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XVHBbtswDEWv-grCwADboQRLcrxuQHbMeb0VSH1QHEk22jiBo7QYDH_JLsGAfsW-ZP2aUqkPxQ5P5OMjRUr8_ccfLn-Ppnk03sLedD3r9sfDEETi9iFh7PUcHL_99xJ-HS2sV-7pYEJVMnfuG3CpwS02uEOLDj22sM429XocbDgPffRMbvk2d7zJPd_lLZrcLba5XTR5S9wT96S3xO1ilzviLeme8h1xO00f7d9u7q8N43xpBiNjXX-C7yvY1HcjG6XCZYlcodIoscSK_AkpPvv4KSHGtVhiKUgphCqxQCUkco28FHTIWDoxM99_CkPX-zHZcFlWwLUC9bUArWWd4BxUmgSpC1K1voZVIaS8BSWKEvQ3UcXKSollnUyMucMABrt4_WB6-vX4lpH9pD7BpcmX54ceVj8g2jTaU_bQJ9ihSztBdWJLaAg7giU4gie0GZrTxtQZTU9trgu7A5r_3AQY_9_UvMj5gy-XD_sO)
The very straightforward solution
[Answer]
# Mathematica, 2 bytes
```
**
```
Definitely Mathematica has `NonCommutativeMultiply` for quaternions.
Reference: [Official Documentation](https://reference.wolfram.com/legacy/language/v13/Quaternions/tutorial/Quaternions.html)
```
Needs["Quaternions`"];
q1 = Quaternion[12, 54, -2, 23];
q2 = Quaternion[1, 4, 6, -2];
q3 = Quaternion[3.5, 4.6, -0.24, 0];
q4 = Quaternion[2.1, -3, -4.3, -12];
q1 ** q2
q2 ** q1
q3 ** q4
```
```
Quaternion[-146, -32, 270, 331]
Quaternion[-146, 236, -130, -333]
Quaternion[20.118, 2.04, 39.646, -62.5]
```
] |
[Question]
[
Implement a function of pattern and string to be matched, return true if the pattern matches the WHOLE string, otherwise false.
Our glob pattern syntax is:
* `?` matches any one character
* `+` matches one or more characters
* `*` matches zero or more characters
* `\` escapes
Rules:
* No eval, no converting into regular expression, no calling a system glob function.
* I/O are not required: you can just write a function
* Shortest wins
Examples:
```
glob('abc', 'abc') => true
glob('abc', 'abcdef') => false IMPORTANT!
glob('a??', 'aww') => true
glob('a*b', 'ab') => true
glob('a*b', 'agwijgwbgioeb') => true
glob('a*?', 'a') => false
glob('?*', 'def') => true
glob('5+', '5ggggg') => true
glob('+', '') => false
glob('a\*b', 'a*b') => true
```
Here is a tip to get started: <http://en.wikipedia.org/wiki/Backtracking>
[Answer]
## Haskell, 141 characters
```
c('\\':a:z)s=a&s>>=c z
c(a:z)s=a%s>>=c z
c[]s=[null s]
p&(a:z)|a==p=[z]
_&_=[]
'?'%(a:z)=[z]
'*'%a=a:'+'%a
'+'%(a:z)='*'%z
l%a=l&a
g=(or.).c
```
Works for all input, both patterns and strings to match against. Handles trailing backslash in the pattern as a literal match (behavior was unspecified.)
This can be run with the following test driver:
```
main = do
globtest "abc" "abc" True
globtest "abc" "abcdef" False
globtest "a??" "aww" True
globtest "a*b" "ab" True
globtest "a*b" "agwijgwbgioeb" True
globtest "a*?" "a" False
globtest "?*" "def" True
globtest "5+" "5ggggg" True
globtest "+" "" False
globtest "a\\*b" "a*b" True
where
globtest p s e =
if g p s == e
then putStrLn "pass"
else putStrLn$"fail: g " ++ show p ++ " " ++ show s ++ " /= " ++ show e
```
---
**Update:** I wrote a [blog post](http://mtnviewmark.wordpress.com/2011/03/26/learning-from-golf/) about this particular answer, as I think it shows off well how Haskell so easily encodes the problem.
---
* Edit: (181 -> 174) replaced `d` and `m` with operators
* Edit: (174 -> 151) inlined `r` into `c`
* Edit: (151 -> 149) removed an unnecessarily generated option in the `+` case
* Edit: (149 -> 141) removed an unnecessary clause for `%`, which was handled by `&`
[Answer]
## Golfscript - 82 chars
```
{1,\@n+:|;{:<;{:I)I|="\\+*?"[<]+?[{|=<={I))}*}I~{I\C}{}.{;}]=~}:C%}/{|>'*'-n=},}:g
```
Assumes that there are no newlines in the strings. Returns an empty array for false, and a non-empty array for true (consistent with golfscript definition of true/false).
This is a non-recursive solution (except for consecutive `*`s), which maintains a list of the positions in the pattern string `i` such that `pattern[0..i]` matches `string[0..cur]`.
This has the potential to run for a very long time. You can add `.&` after `:C%` to prevent this.
[Answer]
# PHP - ~~275~~ 243 characters
```
<?function g($P,$I){$o='array_shift';if(@$I[0]==="")return 0;for(;$P;$o($P)){$p=$P[0];if($p=='?'|$p=='+'&&@$N===$o($I))return 0;if($p=='+'|$p=='*'&&$I&&g($P,array_slice($I,1)))return 1;if(!strpos(" ?+*\\",$p)&&$p!==$o($I))return 0;}return!$I;}
```
Ungolfed:
```
<?php
function g($P,$I) {
if ($I && $I[0] === "") return false;
for(;$P;array_shift($P)) {
$p = $P[0];
if( $p == '?' || $p == '+') {
if (NULL === array_shift($I)) {
return false;
}
}
if( $p=='+' || $p=='*' ) {
if ($I && g($P, array_slice($I,1))) {
return true;
}
}
if (!strpos(" ?+*\\",$p) && $p !== array_shift($I)) {
return false;
}
}
return !$I;
}
function my_glob($pattern,$subject) {
return !!g(str_split($pattern),str_split($subject));
}
```
[Answer]
## Overly Verbose Python (384 367 Characters)
```
t=lambda a:a[1:]
h=lambda a:a[0]
n=lambda p,s:s and(h(p)==h(s)and m(t(p),t(s)))
def m(p,s):
if not p:
return not s
else:
return {
'?':lambda p,s:s and m(t(p),t(s)),
'+':lambda p,s:s and(m(p,t(s))or m(t(p),t(s))),
'*':lambda p,s:m(t(p),s)or(s and m(p,t(s))),
'\\':lambda p,s:n(t(p),s),
}.get(h(p),n)(p,s)
glob=lambda p,s:not not m(p,s)
```
It's not the shortest, but it's nice and functional. The dispatch dict thing in the middle could presumably be rewritten as a disjunction over `(h(p) == '?') and (? lambda body)` type things. Defining that h operator costs me some characters for no benefit, but its nice to have a keyword for head.
I'd like to have a crack at golfscripting it later if time permits.
edit: removed unnecessary third branch in '\*' case after reading [user300's ruby answer](https://codegolf.stackexchange.com/questions/467/implement-glob-matcher/896#896)
[Answer]
## Shorter Snappier Python 2.6 (272 characters)
**golfed:**
```
n=lambda p,s:p[0]==s[0]and m(p[1:],s[1:])
def m(p,s):
q,r,t,u=p[0],p[1:],s[0],s[1:]
return any((q=='?'and(t and m(r,u)),q=='+'and(t and(m(p,u)or m(r,u))),q=='*'and(m(r,s)or(t and m(p,u))),q=='\\'and n(r,s),q==t==0))or n(p,s)
glob=lambda*a:m(*[list(x)+[0]for x in a])
```
**ungolfed:**
```
TERMINATOR = 0
def unpack(a):
return a[0], a[1:]
def terminated_string(s):
return list(s) + [TERMINATOR]
def match_literal(p, s):
p_head, p_tail = unpack(p)
s_head, s_tail = unpack(s)
return p_head == s_head and match(p_tail, s_tail)
def match(p, s):
p_head, p_tail = unpack(p)
s_head, s_tail = unpack(s)
return any((
p_head == '?' and (s_head and match(p_tail, s_tail)),
p_head == '+' and (s_head and(match(p, s_tail) or match(p_tail, s_tail))),
p_head == '*' and (match(p_tail, s) or (s_head and match(p, s_tail))),
p_head == '\\' and match_literal(p_tail, s),
p_head == s_head == TERMINATOR,
)) or match_literal(p, s)
def glob(p, s):
return match(terminated_string(p), terminated_string(s))
```
**featuring:**
* lazily-evaluated logical mess!
* C style strings!
* cute multiple comparison idiom!
* plenty of ugly!
credit to user300's answer for illustrating how things are simplified if you can get some kind of terminator value when popping the head from an empty string.
i wish the head/tail unpacking could be performed inline during the declaration of m's arguments. then m could be a lambda, just like its friends n and glob. python2 cannot do it, and after a bit of reading, it looks like python3 cannot either. woe.
**testing:**
```
test_cases = {
('abc', 'abc') : True,
('abc', 'abcdef') : False,
('a??', 'aww') : True,
('a*b', 'ab') : True,
('a*b', 'aqwghfkjdfgshkfsfddsobbob') : True,
('a*?', 'a') : False,
('?*', 'def') : True,
('5+', '5ggggg') : True,
('+', '') : False,
}
for (p, s) in test_cases:
computed_result = glob(p, s)
desired_result = test_cases[(p, s)]
print '%s %s' % (p, s)
print '\tPASS' if (computed_result == desired_result) else '\tFAIL'
```
[Answer]
# Ruby - ~~199~~ 171
```
g=->p,s{x=(b=->a{a[1..-1]})[p];y=s[0];w=b[s];v=p[0];_=->p,s{p[0]==y&&g[x,w]}
v==??? g[x,y&&w||s]:v==?+? y&&g[?*+x,w]:v==?*?
y&&g[p,w]||g[x,s]:v==?\\? _[x,s]:v ? _[p,s]:!y}
```
Ungolfed:
```
def glob(pattern, subject)
b=->a{a[1..-1]}
_=->p,s{ p[0]==s[0] && glob(b[p],b[s]) }
({
??=>->p,s { glob(b[p], s[0] ? b[s] : s) },
?+=>->p,s { s[0] && glob(?*+b[p], b[s]) },
?*=>->p,s { s[0] && glob(p,b[s]) || glob(b[p],s) },
?\\=>->p,s{ _[b[p],s] },
nil=>->p,s{ !subject[0] }
}[pattern[0]] || _)[pattern, subject]
end
```
Tests:
```
p glob('abc', 'abc')
p glob('abc', 'abcdef')
p glob('a??', 'aww')
p glob('a*b', 'ab')
p glob('a*b', 'agwijgwbgioeb')
p glob('a*?', 'a')
p glob('?*', 'def')
p glob('5+', '5ggggg')
p glob('+', '')
```
Inspired by [roobs' answer](https://codegolf.stackexchange.com/questions/467/implement-glob-matcher/886#886)
[Answer]
## C function - 178 necessary characters
Compiled with GCC, this produces no warnings.
```
#define g glob
int g(p,s)const char*p,*s;{return*p==42?g(p+1,s)||(*s&&g(p,
s+1)):*p==43?*s&&(g(p+1,++s)||g(p,s)):*p==63?*s&&g(p+1,s+1)
:*p==92?*++p&&*s++==*p++&&g(p,s):*s==*p++&&(!*s++||g(p,s));}
#undef g
```
The first and last lines are not included in the character count. They are provided for convenience only.
Blown-up:
```
int glob(p,s)
const char *p, *s; /* K&R-style function declaration */
{
return
*p=='*' ? glob(p+1,s) || (*s && glob(p,s+1)) :
*p=='+' ? *s && (glob(p+1,++s) || glob(p,s)) :
*p=='?' ? *s && glob(p+1,s+1) :
*p=='\\' ? *++p && *s++==*p++ && glob(p,s) :
*s==*p++ && (!*s++ || glob(p,s));
}
```
[Answer]
## JavaScript - 259 characters
My implementation is very recursive, so the stack will overflow if an extremely long pattern is used. Ignoring the plus sign (which I could have optimized but chose not to for simplicity), one level of recursion is used for each token.
```
glob=function f(e,c){var b=e[0],d=e.slice(1),g=c.length;if(b=="+")return f("?*"+d,c);if(b=="?")b=g;else if(b=="*"){for(b=0;b<=g;++b)if(f(d,c.slice(b)))return 1;return 0}else{if(b=="\\"){b=e[1];d=e.slice(2)}b=b==c[0]}return b&&(!d.length&&!g||f(d,c.slice(1)))}
```
The function sometimes returns a number instead of a boolean. If that is a problem, you can use it as `!!glob(pattern, str)`.
---
Ungolfed (unminified, rather) to serve as a useful resource:
```
function glob(pattern, str) {
var head = pattern[0], tail = pattern.slice(1), strLen = str.length, matched;
if(head == '+') {
// The plus is really just syntactic sugar.
return glob('?*' + tail, str);
}
if(head == '?') { // Match any single character
matched = strLen;
} else if(head == '*') { // Match zero or more characters.
// N.B. I reuse the variable matched to save space.
for(matched = 0; matched <= strLen; ++matched) {
if(glob(tail, str.slice(matched))) {
return 1;
}
}
return 0;
} else { // Match a literal character
if(head == '\\') { // Handle escaping
head = pattern[1];
tail = pattern.slice(2);
}
matched = head == str[0];
}
return matched && ((!tail.length && !strLen) || glob(tail, str.slice(1)));
}
```
Note that indexing into characters of a string as for array elements is not part of the older (ECMAScript 3) language standard, so it may not work in older browsers.
[Answer]
**Python** (454 characters)
```
def glob(p,s):
ps,pns=[0],[]
for ch in s:
for i in ps:
if i<0:
pns+=[i]
if i>-len(p) and p[-i]==ch:pns+=[-i]
elif i<len(p):
pc=p[i]
d={'?':[i+1],'+':[i,-i-1],'*':[i+1,-i-1]}
if pc in d:pns+=d[pc]
else:
if pc=='\\':pc=p[i+1]
if pc==ch:pns+=[i+1]
ps,pns=pns,[]
if (s or p in '*') and (len(p) in ps or -len(p)+1 in ps or -len(p) in ps): return True
return False
```
[Answer]
# D: 363 Characters
```
bool glob(S)(S s,S t){alias front f;alias popFront p;alias empty e;while(!e(s)&&!e(t)){switch(f(s)){case'+':if(e(t))return false;p(t);case'*':p(s);if(e(s))return true;if(f(s)!='+'&&f(s)!='*'){for(;!e(t);p(t)){if(f(s)==f(t)&&glob(s,t))return true;}}break;case'\\':p(s);if(e(s))return false;default:if(f(s)!=f(s))return false;case'?':p(s);p(t);}}return e(s)&&e(t);}
```
More Legibly:
```
bool glob(S)(S s, S t)
{
alias front f;
alias popFront p;
alias empty e;
while(!e(s) && !e(t))
{
switch(f(s))
{
case '+':
if(e(t))
return false;
p(t);
case '*':
p(s);
if(e(s))
return true;
if(f(s) != '+' && f(s) != '*')
{
for(; !e(t); p(t))
{
if(f(s) == f(t) && glob(s, t))
return true;
}
}
break;
case '\\':
p(s);
if(e(s))
return false;
default:
if(f(s) != f(s))
return false;
case '?':
p(s);
p(t);
}
}
return e(s) && e(t);
}
```
[Answer]
## golfscript
```
{{;;}2$+}:x;{x if}:a;{x\if}:o;{1$1$}:b;{(@(@={\m}a}:r;{b(63={\({\m}a}a{b(43={\({\b m{'+'\+m}o}a}a{b(42={b m{\({\'*'\+m}a}o}a{b(92={r}a{b 0=0=\0=0=*{r}o}o}o}o}o}:m;{[0]+\[0]+m}:glob;
```
it's built out of functions that consume two arguments from the stack, s and p, and produce a single boolean return value. there's a bit of mucking around to make that compatible with the lazy and and lazy or operators. i really doubt this approach is anywhere near optimal, or even in the right direction.
there's also a few entertainingly stupid moments, such as popping a `'*'` off the pattern, consuming the `'*'` in a comparison, only to realise that the subsequent branch doesn't match. in order to go down the other branch, we need the pattern with the `'*'` on the front, but we've consumed that original pattern when we popped the `'*'`, and we consumed the `'*'`, so to get ourselves the pattern again we load a shiny new string constant `'*'`, and prepend it in place. it gets even uglier because for some reason the character matching needs to be done with ascii values, but prepending back onto the string needs strings.
**less golfed golfscript**
```
{[0]+}:terminate_string;
{{;;}2$+if}:_and;
{{;;}2$+\if}:_or;
{1$1$}:branch;
{(@(@={\match}_and}:match_literal;
{0=0=\0=0=*}:match_terminator;
{(92={match_literal}_and}:match_escape;
{(63={\({\match}_and}_and}:match_wildcard;
{(43={\({\branch match{'+'\+match}_or}_and}_and}:match_wildcard_plus;
{(42={branch match{\({\'*'\+match}_and}_or}_and}:match_wildcard_star;
{branch match_wildcard{branch match_wildcard_plus{branch match_wildcard_star{branch match_escape{branch match_terminator{match_literal}_or}_or}_or}_or}_or}:match;
{terminate_string\terminate_string match}:glob;
```
**tests**
```
{2$2$glob = "test passed: " "test FAILED: " if print \ print ' ; ' print print "\n" print}:test_case;
'abc' 'abc' 1 test_case
'abc' 'abcdef' 0 test_case
'a??' 'aww' 1 test_case
'a*b' 'ab' 1 test_case
'a*b' 'agwijgwbgioeb' 1 test_case
'a*?' 'a' 0 test_case
'?*' 'def' 1 test_case
'5+' '5ggggg' 1 test_case
'+' '' 0 test_case
```
[Answer]
# C# (251 chars)
```
static bool g(string p,string i){try{char c;System.Func<string,string>s=t=>t.Remove(0,1);return p==i||((c=p[0])==92?p[1]==i[0]&g(s(s(p)),s(i)):c==42?g(s(p),i)||g(p,s(i)):c==43?g(s(p),s(i))|g(p,s(i)):g(s(p),s(i))&(c==i[0]|c==63));}catch{return false;}}
```
### Slightly more readable:
```
static bool g(string p /* pattern */, string i /* input string */)
{
// Instead of checking whether we’ve reached the end of the string, just
// catch the out-of-range exception thrown by the string indexing operator
try
{
char c;
// .Remove(0,1) is shorter than .Substring(1)...
System.Func<string, string> s = t => t.Remove(0, 1);
// Note that every glob matches itself!† This saves us having to write
// “(p=="" & i=="")” which would be much longer — very convenient!
return p == i || (
// backslash escapes
(c = p[0]) == 92 ? p[1] == i[0] & g(s(s(p)), s(i)) :
// '*' — need “||” so that s(i) doesn’t throw if the first part is true
c == 42 ? g(s(p), i) || g(p, s(i)) :
// '+'
c == 43 ? g(s(p), s(i)) | g(p, s(i)) :
// '?' or any other character
g(s(p), s(i)) & (c == i[0] | c == 63)
);
}
// If we ever access beyond the end of the string, we know the glob doesn’t match
catch { return false; }
}
```
† I know, I know... except for globs containing the backslash. Which is really unfortunate. It would have been really clever otherwise. :(
] |
[Question]
[
Given a positive number \$n\$, find the number of [alkanes](https://en.wikipedia.org/wiki/Alkane) with \$n\$ carbon atoms, ignoring [stereoisomers](https://en.wikipedia.org/wiki/Stereoisomerism); or equivalently, the number of unlabeled trees with \$n\$ nodes, such that every node has degree \$\le 4\$.
This is OEIS sequence [A000602](http://oeis.org/A000602).
See also: [Paraffins - Rosetta Code](https://rosettacode.org/wiki/Paraffins)
### Example
For \$n = 7\$, the answer is \$9\$, because [heptane](https://en.wikipedia.org/wiki/Heptane) has nine [isomers](https://en.wikipedia.org/wiki/Isomer):
* **Heptane**: \$\mathrm{H\_3C-CH\_2-CH\_2-CH\_2-CH\_2-CH\_2-CH\_3}\$

* **2-Methylhexane**: \$\mathrm{H\_3C-CH(CH\_3)-CH\_2-CH\_2-CH\_2-CH\_3}\$

* **3-Methylhexane**: \$\mathrm{H\_3C-CH\_2-CH(CH\_3)-CH\_2-CH\_2-CH\_3}\$

* **2,2-Dimethylpentane**: \$\mathrm{H\_3C-C(CH\_3)\_2-CH\_2-CH\_2-CH\_3}\$

* **2,3-Dimethylpentane**: \$\mathrm{H\_3C-CH(CH\_3)-CH(CH\_3)-CH\_2-CH\_3}\$

* **2,4-Dimethylpentane**: \$\mathrm{H\_3C-CH(CH\_3)-CH\_2-CH(CH\_3)-CH\_3}\$

* **3,3-Dimethylpentane**: \$\mathrm{H\_3C-CH\_2-C(CH\_3)\_2-CH\_2-CH\_3}\$

* **3-Ethylpentane**: \$\mathrm{H\_3C-CH\_2-C(CH\_2CH\_3)-CH\_2-CH\_3}\$

* **2,2,3-Trimethylbutane**: \$\mathrm{H\_3C-C(CH\_3)\_2-CH(CH\_3)-CH\_3}\$

Note that 3-methylhexane and 2,3-dimethylpentane are [chiral](https://en.wikipedia.org/wiki/Chirality_(chemistry)), but we ignore stereoisomers here.
### Test cases
You don't need to handle the case \$n = 0\$.
```
intput output
=============
0 1
1 1
2 1
3 1
4 2
5 3
6 5
7 9
8 18
9 35
10 75
11 159
12 355
13 802
14 1858
15 4347
16 10359
17 24894
18 60523
19 148284
20 366319
```
[Answer]
## CJam (100 98 91 89 83 bytes)
```
1a{_[XX]*\_{_0a*}:E~\{E\_{ff*W%{0@+.+}*}:C~.+2f/}:D~.+C.+3f/1\+}q~:I*DE1$D.-X\+.+I=
```
Takes input from stdin, outputs to stdout. Note that this exploits the licence to not handle input `0` to save two bytes by inlining the definitions of `C` and `D`. [Online demo](http://cjam.aditsu.net/#code=1a%7B_%5BXX%5D*%5C_%7B_0a*%7D%3AE~%5C%7BE%5C_%7Bff*W%25%7B0%40%2B.%2B%7D*%7D%3AC~.%2B2f%2F%7D%3AD~.%2BC.%2B3f%2F1%5C%2B%7Dq~%3AI*DE1%24D.-X%5C%2B.%2BI%3D&input=5)
NB this is *very* slow and memory-inefficient. By trimming arrays a much faster version is obtained (3 bytes more). [Online demo](http://cjam.aditsu.net/#code=1a%7B_%5BXX%5D*%5C_%7B_0a*%7D%3AE~%5C%7BE%5C_%7Bff*W%25%7B0%40%2B.%2B%7D*%7D%3AC~.%2B2f%2F%7D%3AD~.%2BC.%2B3f%2FI)%3C1%5C%2B%7Dq~%3AI*DE1%24D.-X%5C%2B.%2BI%3D&input=15).
### Dissection
OEIS gives (modulo an indexing error) the generating function decomposition $$\begin{eqnarray}
A000598(x) &=& 1 + x Z(S\_3; A000598(x)) \\
A000678(x) &=& x Z(S\_4; A000598(x)) \\
A000599(x) &=& Z(S\_2; A000598(x) - 1) \\
A000602(x) &=& A000678(x) - A000599(x) + A000598(x^2) \\
\end{eqnarray}$$ where \$Z(S\_n; f(x))\$ denotes the cycle index of the symmetric group \$S\_n\$ applied to the function \$f(x)\$.
I manipulated this into a slightly golfier decomposition, and then looked up the intermediate sequences and discovered that they're also in OEIS:
$$\begin{eqnarray}
A000642(x) &=& Z(S\_2, A000598(x)) \\
A000631(x) &=& Z(S\_2, A000642(x)) \\
A000602(x) &=& A000642(x) + x A000642(x^2) - x A000631(x)
\end{eqnarray}$$
Earlier versions reused block `C` (convolve two polynomials) from [this answer](https://codegolf.stackexchange.com/a/133842/194). I've found a much shorter one, but I can't update that answer because it's from a chaining question.
```
1a e# Starting from [1]...
{ e# Loop I times (see below) to build A000598 by f -> 1 + Z(S_3; f)
_[XX]* e# Copy and double-inflate to f(x^3)
\_ e# Flip and copy: stack is f(x^3) f(x) f(x)
{_0a*}:E~ e# Assign copy-and-inflate to E and execute
e# Stack: f(x^3) f(x) f(x) f(x^2)
\ e# Flip
{ e# Define and execute block D, which applies f -> Z(S_2;f)
e# Stack: ... f
E\_ e# Stack: ... f(x^2) f(x) f(x)
{ e# Define and execute block C, which convolves two sequences
ff* e# Multiply copies of the second sequence by each term of the first
W% e# Reverse
{ e# Fold
0@+.+ e# Prepend a 0 to the first and pointwise sum
}*
}:C~ e# Stack: ... f(x^2) f(x)^2
.+2f/ e# Pointwise average
}:D~ e# Stack: f(x^3) f(x) f(x^2) Z(S_2;f(x))
.+C e# Stack: f(x^3) f(x)*(f(x^2) + Z(S_2;f(x)))
.+3f/ e# Add and divide by 3 to finish computing Z(S_3; f)
1\+ e# Prepend a 1
}
q~:I e# Read input to I
* e# Loop that many times
e# Stack: I+1 terms of A000598 followed by junk
D e# Stack: I+1 terms of A000642 followed by junk
E1$D e# Stack: A000642 A000642(x^2) A000631
.-X\+.+ e# Stack: A000602
I= e# Extract term I
```
[Answer]
## Alchemist (1547 bytes)
```
_->In_NN+2b+al+g
al+g+0NN->ak
al+g+NN->ah
ah+b->ah+m+d+z+a
ah+0b->C+Z+Q
Z+j+z->Z+j+d
Z+j+0z->M+s
M+g+b->M+g+r
M+g+h->M+g+d
M+g+0b+0h+q->J+U
J+o+h->J+o+m
J+o+a->J+o+d
J+o+0h+0a->2C+an+Q
an+j+h->an+j+d
an+j+0h->aC+s
aC+g->e+am+P
am+l+b->am+l+d
am+l+0b->al+s
ak+b->ak+m+d
ak+0b->C+aj+Q
aj+j+h->aj+j+b
aj+j+0h->I+n
I+f+e->I+f+a
I+f+b->I+f+m+d+z
I+f+0e+0b->C+ai+Q
ai+j+h->ai+j+b
ai+j+0h->aB+n
aB+f->H
H+z->H+d
H+a+e->H
H+0z+0e->G+i
G+i+0b->ag
G+i+b->az+b+n
az+f+0b->Out_a
az+f+b->G+b+n
G+f->G+t
ag+e->ag
ag+0e->af+t
af+i+e->af+i+a
af+i+0e->Out_a
Q->F+s
F+g+b->F+g+y
F+g+A->F+g
F+g+0b+0A->av+o
av+o+0m->w
av+o+m->m+ae+A
ae+m->ae+b
ae+0m->u+n
u+f+b->u+f+m
u+f+e->u+f+E
u+f+A->u+f+k+c
u+f+0b+0e+0A->ad
ad+c->ad+A
ad+0c->ac
ac+y->ac+d+c
ac+0y->ab
ab+c->ab+y
ab+0c->V+l
V+l+0k->x
V+l+k->aa+t
aa+i+0e->W
aa+i+e->Y
Y+E->Y+D+c
Y+0E->X
X+c->X+E
X+0c->aa+i
W+D->W+e
W+0D->V+P
x+E->x
x+d->x
x+b->x+k
x+0E+0d+0b->aw
aw+h->aw+d
aw+0h->aE+s
aE+g->p
p+b->p+2r
p+k->p+d
p+B->p
p+q->p
p+0b+0k+0B+0q->r+q+av+U
w+h->w+d
w+y->w+r
w+C->w+B+q
w+0h+0y+0C->aD+U
aD+o->j
U->au+s
au+g+b->au+g+d
au+g+0b->v
v+d->d+aA+t
aA+i+k->R
aA+i+0k->at
at+B->at+k+c
at+0B->L
L+c->L+B
L+r->L+b
L+0c+0r->as+n
as+f+b->as+f+r
as+f+0b->R
R+0e->K
R+e+q->ar+D+c
ar+e+q->ar+c
ar+0q->aq
aq+c->aq+q
aq+0c->R
K+D->K+e
K+h->K+b
K+0D+0h->ap+P
ap+l+b->ap+l+h
ap+l+0b->v
v+0d+k->v
v+0d+r->v
v+0d+0k+0r->o
s+0d->g
s+d->d+ao+t
ao+i->ao+P
ao+l->s
P->O+c
O+b->2c+O
O+0b->N
N+c->b+N
N+0c+e->O
N+0c+0e->l
n+b->n+c
n+0b->T
T+c->ay
T+0c->e+n
ay+c->b+T
ay+0c->f
t+d->t+c
t+0d->S
S+c->ax
S+0c->e+t
ax+c->d+S
ax+0c->i
```
[Online demo](https://tio.run/##PVTJbipBDLz7V6yRWrz7SGwJCQlJyEZyiXqYAYZ9DcvP86psyAG7yu322kOc9kfFrNxsz@efJL2b/3Q6Wsk0TnUoFBo6nSSNEyeGRxJHmhHoTHM9aaQhwFLXb32Rbx3rKUmpciMB7FE38ogIGeFQ10ZGTnIjIdMw0lWS3uu73OuCp1QzI9FJbgR@AYZKXeMcCSHG9DadOw3kdSSFGCZpoXGmzwIxtdKpc6csHM3Bc2JHE3ZF4h3FMTOMLxmoM6fMcKdzudOBFoQDDIIyc2KzMUMorrFKxiovsUqPVV6rrSEYxCBJW9LiBFuoo6WR0WkJJ0RK0lstBT@ve2iQ6KQZ75@YD/xpt/2JTjPe4eEtY9/qVuKQMXEZgCHjgMYBIjkpuVIqHnqklyS9wYxufIVURyNVIwa5QND4qwuh0DBL0r1DoJnGQqsCAQKZEdJlh9J2XifVzEjhpGmk6mSifaNMVHguLCrXPgFD5xqI@xL7eiTACowEMiTMzDdD7RD0/dCpfPARTJL0YAggRo4jXvr/dAj0JV/ahNIGon5pAO5JjyF7KLTnyeErn9rAPS0AQoNJnuXAmweo3BWaPegEIDQ15L5MzGpvL2PPB7j3V9Hky2zyDS9lyWtLrayBJkQ5QM1PVq44GzzdmgYY1rpSjP9dLCyj7jmXPT6/vdYJarqSvX1PRw2wxAa8IRZJOpZ38B3T73zrpnOnLPhXftlOrrHKgVUxJVTVdcSJRli3LBCSy4MKYA/ywKE9aA1gTZABBKwJJG74jDf@HkyvnTJjV7q2kzZ0wZbj2pYBdaVG2HxcSVzZvldqkOvpSpu7aWM3bc6kjdRtLMlnveRfxPLyF0E9cnptFoua/KH1H@LAwRayAUvSIbSPZcGxLLREtAVDL3SapBt5xkeFOp@YptLXJyBm6EiH5WZKgGnw23PElqcyp/8cF@fm/iZv1t0Rmq0VnNvRI7wR0TiQLWvZ4tbWinuVV7t1gPZbKPFAU66vRDSW5/O//w).
Note: this is quite slow. If testing with an interpreter which supports applying a rule multiple times at once (e.g. [my one](https://github.com/pjt33/Alchemist.Py) - although make sure you have the latest version which fixes a bug in the parser) then you can get a significant speed-up by adding two rules:
```
T+2c->b+T
S+2c->d+S
```
which inline a route through the existing rules
```
T+c->ay
ay+c->b+T
S+c->ax
ax+c->d+S
```
## Partial dissection
At a high level, this uses the same approach as my CJam answer.
The computation model of Alchemist is essentially the [Minsky register machine](https://codegolf.stackexchange.com/q/1864/194). However, Alchemist very nicely exposes the equivalence of code and data, and by allowing many tokens on the left hand side of a production rule effectively the state is not constrained to be represented by one atom: we can use a tuple of atoms, and this allows (non-recursive) subroutines. This is very useful for golf. The only things it's really lacking are macros and debuggability.
For arrays I'm using a pairing function which can be implemented quite golfily in RMs. The empty array is represented by \$0\$, and the result of prepending \$x\$ to array \$A\$ is \$(2A+1)2^x\$. There is one subroutine to pair: the subroutine is called `P` and it prepends the value of `e` to `b`. There are two subroutines to unpair: `n` unpairs `b` to `e` and `b`; and `t` unpairs `d` to `e` and `d`. This allowed me to save quite a bit of shuffling data between variables, which is important: a single "move" operation
```
a, b = b, 0
```
expands to at least 17 bytes:
```
S+a->S+b
S+0a->T
```
where `S` is the current state and `T` is the next state. A non-destructive "copy" is even more expensive, because it has to be done as a "move" from `a` to `b` and an auxiliary `tmp`, followed by a "move" from `tmp` back to `a`.
## Obfuscation
I aliased various variables to each other and eliminated about 60 states in the process of golfing the program, and many of them didn't have particularly meaningful names anyway, but to fully golf it I wrote an minimiser so the names are now thoroughly indecipherable. Good luck reverse engineering it! Here is the minimiser (in CJam), which makes a few assumptions about the code but could be adapted to minimise other Alchemist programs:
```
e# Obfuscate / minimise Alchemist program
e# Tokenise
qN%[SNS]e_*S%
e# Get token frequencies for substitution purposes, special-casing the I/O ones
_["+" "0" "2" "->" "_" N "In_n" "n" "Out_tmp2" "tmp2"]-
$e`$W%1f=
e# Empirically we want a two-char input for n and a one-char one for tmp2
["In_n" "Out_tmp2" "n" "tmp2"]\+
["In_NN" "Out_a" "NN"] "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"1/:A+ A2m*:e_"NN"a-+
1$,<
er
_s,p
```
[Answer]
# [Node.js 11.6.0](https://nodejs.org), ~~229 223 221~~ 218 bytes
Derived from the Java implementation suggested on [Rosetta Code](https://rosettacode.org/wiki/Paraffins#Java).
```
f=(N,L=1,u=[...r=[c=[],1,...Buffer(N)]],k=u[(g=(n,B,S,i,b=B,m,d=0)=>{for(;++b<5;)for(x=c[B]=(d+r[m=n])*(d++?c[B]/d:i),u[S+=n]+=L*2<S&&x,r[S]+=b<4&&x;--m;)g(m,b,S,c[B])})(L,0,1,1),L]-=~(x=r[L++/2])*x>>1)=>L>N?k:f(N,L,u)
```
[Try it online!](https://tio.run/##FY/NboMwEITveQofosgbLwRQewkskTgjLhwtSwk/RjTBVE6pkBB9dWpuM6PdnW@/Hr@Pd2377x/PjE27bZp4gTmFOJH0fd@SrEkqDNGZbNK6tbwApfBJk@QdcYMZlthjRRkO2FAAlC56tDwWoko@Y9j1TLXMFPFGWDmQUXB2Utz28NJce8BJlsLlgvJzlJSn04xWls5WyYczsecNMXR8wMp17VuwAs8xcFghYK48@nMdVuZCXCJ3fU7T0HHkaXF7XvX@EE6w7SSGEQtjZlhCLAqcEALYcmCsHs17fLX@a@z4/cGPi1nBzR4XzQ2sdzis2z8 "JavaScript (Node.js) – Try It Online")
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 118 bytes
A direct translation of [Peter Taylor](https://codegolf.stackexchange.com/users/194/peter-taylor)'s [CJam answer](https://codegolf.stackexchange.com/a/178649/9288).
```
n->(s(k)=subst(a,x,x^k));(z()=(a^2+s(2))/2);a=O(1);for(i=0,n,a=1+x*(a*z()+(s(3)-a^3)/3));a=z();Pol(a+x*(s(2)-z()))\x^n
```
[Try it online!](https://tio.run/##FY1NCsMgEEavIl3Nlyj5oysxV2gPUITpIiWkmKAJSC9vx8V8i8fjzcFxNZ@jLMqpEsxMiTa4dL3TSayzzn4DLP0IjtiPbaIR6EZYdg8aYJc90up6HTS7oc0NcSNuK5kJhv2EbkKVBdrn/iWuTo0YIcAr@1BqI8j/Xqu73BHXcAq4KTPLLBRELH8 "Pari/GP – Try It Online")
] |
[Question]
[
## Summary
Implement FizzBuzz in Python, with the fewest possible tokens.
## Challenge
Write a program that prints the decimal numbers from 1 to 100 inclusive. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”. Programs must be written in some version of Python.
For more details, see [1, 2, Fizz, 4, Buzz](https://codegolf.stackexchange.com/questions/58615/1-2-fizz-4-buzz?noredirect=1&lq=1)
## Scoring
Your score will be equal to the number of nodes in the abstract syntax tree of your code, as reported by [this program for Python 3](https://github.com/isaacg1/ast-golf/blob/master/simple_counter.py), or [this program for Python 2](https://github.com/isaacg1/ast-golf/blob/master/simple_counter2.py). To run the programs, provide the filename of your code as command line argument to the program. For instance:
```
python simple_counter.py fizzbuzz.py
```
These programs are based off of Python's [ast module](https://docs.python.org/3/library/ast.html). If you have any difficulty, let me know.
To prevent trivial solutions, such as executing a long string with the actual program, or hardcoding the output, there are some additional restrictions:
* No token in your code may be longer than 15 characters. The above programs will check this requirement for you. Note that for ease of implementation, the above programs count comments as tokens.
* Code execution/evaluation is banned.
If you have questions as to whether something is allowed, ask me.
## Scoring Heuristics
The following rules are typically enough to calculate the score of your program:
* Block statements are 1 points: `if`, `for ... in ...`, `while`, `else`, etc.
* Standalone statements are 1 point: `print` in Python 2, `break`, `pass`, etc.
* Variables are 2 points
* Single-token literals are 1 point: `2131`, `"Hello, world!"`, `True`
* Functions are 3 points (2 for using a variable, 1 extra): `print` in Python 3, `range`, etc.
* Operators are 2 points: `+`, `*`, `%`, `and`, `not`, etc.
* `=` is 1 point
* Augmented assignment is 2 points: `+=`, `|=`, etc.
* Parentheses, indentation, etc. are 0 points.
* A line containing an expression, as opposed to an assignment or an expression, is + 1 point.
* Having code at all is 1 point.
## Challenge:
The lowest score wins. Good luck!
[Answer]
# 33
**Python 2**
```
for i in range(1,101):print[i,'Fizz','Buzz','FizzBuzz'][int(`300102100120100`[i%15])]
```
[Answer]
# 46
```
for x in range(100):print('Fizz'*(x%3>1)+'Buzz'*(x%5>3)or str(x+1))
```
[Answer]
# ~~39~~ 34
```
for i in range(1,101):print [i,'Fizz','Buzz','FizzBuzz'][19142723>>2*(i%15)&3]
```
[Answer]
# Python 3, 35
```
for x in range(1,101): print(('' if x%3 else 'Fizz') + ('' if x%5 else 'Buzz') or x)
```
[Answer]
# Python 2, 36
```
for i in range(1, 101):
print (not i % 3) * "Fizz" + (not i % 5) * "Buzz" or i
```
I think this is the shortest of the approaches that don't use large numbers / strings.
] |
[Question]
[
## Introduction
In this challenge, you are given a list of nonnegative floating point numbers drawn independently from some probability distribution.
Your task is to infer that distribution from the numbers.
To make the challenge feasible, you only have five distributions to choose from.
* `U`, the [uniform distribution](http://en.wikipedia.org/wiki/Uniform_distribution_%28continuous%29) on the interval [0,1].
* `T`, the [triangular distribution](http://en.wikipedia.org/wiki/Triangular_distribution) on the interval [0,1] with mode c = 1/2.
* `B`, the [beta distribution](http://en.wikipedia.org/wiki/Beta_distribution) on the interval [0,1] with parameters α = β = 1/2.
* `E`, the [exponential distribution](http://en.wikipedia.org/wiki/Exponential_distribution) on the interval [0,∞) with rate λ = 2.
* `G`, the [gamma distribution](http://en.wikipedia.org/wiki/Gamma_distribution) on the interval [0,∞) with parameters k = 3 and θ = 1/6.
Note that all of the above distributions have mean exactly 1/2.
## The Task
Your input is an array of nonnegative floating point numbers, of length between 75 and 100 inclusive.
Your output shall be one of the letters `UTBEG`, based on which of the above distributions you guess the numbers are drawn from.
## Rules and Scoring
You can give either a full program or a function.
Standard loopholes are disallowed.
In [this repository](https://github.com/iatorm/random-data/tree/master), there are five text files, one for each distribution, each exactly 100 lines long.
Each line contains a comma-delimited list of 75 to 100 floats drawn independently from the distribution and truncated to 7 digits after the decimal point.
You can modify the delimiters to match your language's native array format.
To qualify as an answer, your program should correctly classify **at least 50 lists from each file**.
The score of a valid answer is **byte count + total number of misclassified lists**.
The lowest score wins.
[Answer]
# R, ~~202 192 184 182 162~~ 154 bytes + 0 errors
```
function(x)c("U","T","B","E","G")[which.max(lapply(list(dunif(x),sapply(x,function(y)max(0,2-4*abs(.5-y))),dbeta(x,.5,.5),dexp(x,2),dgamma(x,3,6)),prod))]
```
This is based on the Bayesian formula P(D=d|X=x) = P(X=x|D=d)\*P(D=d)/P(X=x), where D is the distribution and X is the random sample. We pick the d such that P(D=d|X=x) is greatest of the 5.
I assume a flat prior (i.e. P(D=di) = 1/5 for i in [1,5]), which means that P(D=d) in the numerator is the same in all cases (and the denominator would be the same in all cases anyways), so we can golf away everything but the P(x=X|D=d), which (except for the triangular distribution) simplify to native functions in R.
ungolfed:
```
function(x){
u=prod(dunif(x))
r=prod(sapply(x,function(y)max(0,2-4*abs(.5-y))))
b=prod(dbeta(x,.5,.5))
e=prod(dexp(x,2))
g=prod(dgamma(x,3,6))
den=.2*u+.2*r+.2*b+.2*e+.2*g
c("U","T","B","E","G")[which.max(c(u*.2/den,r*.2/den,b*.2/den,e*.2/den,g*.2/den))]
}
```
Note that the ungolfed version is not exactly equivalent to the golfed version because getting rid of the denominator avoids the case of Inf/Inf which occurs if you allow the beta distribution to be over the closed interval [0,1] instead of (0,1) - as the sample data does. An additional if statement would handle that but since it's for illustrative purposes only it's probably not worth adding the complexity that is not at the heart of the algorithm.
Thanks @Alex A. for additional code reductions. Especially for which.max!
[Answer]
# Julia, ~~60~~ 62 bytes + ~~25~~ 2 errors = ~~82~~ 64
```
k->"EGTBU"[(V=std(k);any(k.>1)?V>.34?1:2:V<.236?3:V>.315?4:5)]
```
This is fairly simple. The variance for the distributions are mostly different - it's 1/4 for exponential, 1/8 for beta, 1/12 for gamma and uniform, and 1/24 for triangular. As such, if we use variance (here done using `std` for standard deviation, the square root of variance) to determine the likely distribution, we only need to do more to distinguish gamma from uniform; for that, we look for a value larger than 1 (using `any(k.>1)`) - that said, we do the check for both exponential and gamma, as it improves overall performance.
To save a byte, indexing the string `"EGTBU"` is done instead of directly evaluating to a string within the conditionals.
For testing, save the txt files into a directory (keeping the names as-is), and run the Julia REPL in that directory. Then, attach the function to a name as
```
f=k->"EGTBU"[(V=std(k);any(k.>1)?V>.34?1:2:V<.236?3:V>.315?4:5)]
```
and use the following code to automate the testing (this will read from the file, convert into an array of arrays, use the function, and output for each mismatch):
```
m=0;for S=["B","E","G","T","U"] K=open(S*".txt");F=readcsv(K);
M=Array{Float64,1}[];for i=1:100 push!(M,filter(j->j!="",F[i,:]))end;
close(K);n=0;
for i=1:100 f(M[i])!=S[1]&&(n+=1;println(i," "S,"->",f(M[i])," ",std(M[i])))end;
println(n);m+=n;end;println(m)
```
Output will consist of rows containing the case that mismatched, the correct distribution -> the determined distribution, and the variance calculated (eg. `13 G->E 0.35008999281668357` means that the 13th row in G.txt, which should be a gamma distribution, is determined to be an exponential distribution, with the standard deviation being 0.35008999...)
After each file, it also outputs the number of mismatches for that file, and then at the end it also displays the total mismatches (and it should read 2 if run as above). Incidentally, it should have 1 mismatch for G.txt and 1 mismatch for U.txt
[Answer]
# CJam, 76
```
{2f*__{(z.4<},,%,4e<"UBT"="EG"\*\$-2=i3e<=}
```
The source code is **43** bytes long and misclassifies **33** lists.
### Verification
```
$ count()(sort | uniq -c | sort -nr)
$ cat score.cjam
qN%{',' er[~]
{2f*__{(z.4<},,%,4e<"UBT"="EG"\*\$-2=i3e<=}
~N}/
$ for list in U T B E G; { echo $list; cjam score.cjam < $list.txt | count; }
U
92 U
6 B
2 T
T
100 T
B
93 B
7 U
E
92 E
8 G
G
90 G
6 E
3 T
1 U
```
### Idea
Differentiating the exponential and gamma distribution from the remaining ones is easy, since they are the only distributions that take values greater than **1**.
To decide between *gamma*, *exponential* and others, we take a look at the second highest value of the sample.
* If it lies in **[1.5, ∞)**, we guess *gamma*.
* If it lies in **[1, 1.5)**, we guess *exponential*.
* If it lies in **[0, 1)**, we have three remaining possibilities.
The remaining distributions can be differentiated by the percentage of sample values that lie close to the mean (**0.5**).
We divide the length of the sample by the count of values that fall in **(0.3, 0.7)** and take a look at the resulting quotient.
+ If it lies in **(1, 2]**, we guess *triangular*.
+ If it lies in **(2, 3]**, we guess *uniform*.
+ If it lies in **(3, ∞)**, we guess *beta*.
### Code
```
2f* e# Multiply all sample values by 2.
__ e# Push to copies of the sample.
{ e# Filter; for each (doubled) value in the sample:
(z e# Subtract 1 and apply absolute value.
.4< e# Check if the result is smaller than 0.4.
}, e# If it is, keep the value.
,/ e# Count the kept values (K).
% e# Select every Kth value form the sample, starting with the first.
, e# Compute the length of the resulting array.
e# This performs ceiled division of the sample length by K.
4e< e# Truncate the quotient at 4.
"UBT"= e# Select 'T' for 2, 'U' for 3 and 'B' for 4.
"EG"\* e# Place the selected character between 'E' and 'G'.
\$ e# Sort the remaining sample.
-2=i e# Extract the second-highest (doubled) value and cast to integer.
3e< e# Truncate the result at 3.
= e# Select 'E' for 3, 'G' for 2 and the character from before for 1.
```
[Answer]
# Matlab, ~~428~~ 328 bytes + 33 misclassified
This program is basically comparing the real CDF with an estimated one given the data, and then calculating the mean distance between those two: I think the image explains more:
[](https://i.stack.imgur.com/xZUNN.png)
The data shown in this image here shows pretty clearly that it belongs to the turquoise distribution, as it is quite close to that one, so that is basically what my program is doing. It can probably be golfed somewhat more. For me that was first of all a conceptual challenge, not very golfy.
This approach is also independent of the pdfs chosen, it would work for **any** set of distributions.
Following (ungolfed) code should show how it is done. The golfed version is below.
```
function r=p(x);
data=sort(x(1:75));
%% cumulative probability distributiosn
fu=@(x)(0<x&x<1).*x+(1<=x).*1;
ft=@(x)(0<x&x< 0.5).* 2.*x.^2+(1-2*(1-x).^2).*(0.5<=x&x<1)+(1<=x);
fb=@(x)(0<x&x<1).*2.*asin(sqrt(x))/pi+(1<=x);
fe=@(x)(0<x).*(1-exp(-2*x));
fg=@(x)(0<x).*(1-exp(-x*6).*(1+x*6+1/2*(6*x).^2));
fdata = @(x)sum(bsxfun(@le,data,x.'),2).'/length(data);
f = {fe,fg,fu,ft,fb};
str='EGUTB';
%calculate distance to the different cdfs at each datapoint
for k=1:numel(f);
dist(k) = max(abs(f{k}(x)-fdata(x)));
end;
[~,i]=min(dist);
r=str(i);
end
```
Fully golfed version:
```
function r=p(x);f={@(x)(0<x).*(1-exp(-2*x)),@(x)(0<x).*(1-exp(-x*6).*(1+x*6+18*x.^2)),@(x)(0<x&x<1).*x+(1<=x),@(x)(0<x&x<.5).*2.*x.^2+(1-2*(1-x).^2).*(.5<=x&x<1)+(1<=x),@(x)(0<x&x<1).*2.*asin(sqrt(x))/pi+(1<=x)};s='EGUTB';for k=1:5;d(k)=max(abs(f{k}(x)-sum(bsxfun(@le,x,x.'),2).'/nnz(x)));end;[~,i]=min(d(1:5-3*any(x>1)));r=s(i)
```
[Answer]
# Perl, 119 bytes + 8 misclassifications = 127
I've made a tiny decision tree on three features:
* $o: boolean: if any samples > 1.0
* $t: count: 0-th minus 6-th 13-ile clipped into the 0-1 range,
* $h: count: 0-th minus 6-th plus 12-th 13-ile clipped into the 0-1 range
Invoked with `perl -F, -lane -e '...'`. I'm not sure if I should add a penalty for the non-standard parameters. If the commas were spaces, I guess I could have gotten away without the *-F,*
```
for(@F){$b[$_*13]++;$o++if$_>1}
$h=($t=$b[0]-$b[6])+$b[12];
print$o?($t>-2?"e":"g"):($h=19?"b":"u"));
$o=@b=()
```
The slightly formatted output (without the -l flag) is:
```
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
bbbbbbbbbbbbbbbbbbbbbbbbubbbbbbbbbbbbbbbbbbbbbbb
eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
eeegeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
gggggggegggggggggggggggggggggggggggggggggggggggggggg
gggggggggggggggggggggggggggggggggggggggggggggggg
tttttttttttttttttttttttttttttttttttttttttttttttttttt
ttttttttttttttttttttttttttttuttttttttttttutttttt
uuuuuuuuuuuuuuuuuuuuuuuuuuutuuuuuuuuuuuuuuuubuuuuuuu
uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuutuuuu
```
[Answer]
# Python, 318 bytes + 35 missclassifications
```
from scipy.stats import*
from numpy import*
def f(l):
r={'U':kstest(l,'uniform')[1],'T':kstest(l,'triang',args=(.5,))[1],'B':kstest(l,'beta',args=(.5,.5))[1],'E':kstest(l,'expon',args=(0,.5,))[1],'G':kstest(l,'gamma',args=(3,0,1/6.0))[1]}
if sum([x>1 for x in l]): r['U'],r['T'],r['B']=0,0,0
return max(r,key=r.get)
```
**Idea:** the distribution is guessed based on the p-value of the Kolmogorov-Smirnov test.
**Test**
```
from scipy.stats import*
from numpy import*
import os
from io import StringIO
dir=os.path.dirname(os.path.abspath(__file__))+"/random-data-master/"
def f(l):
r={'U':kstest(l,'uniform')[1],'T':kstest(l,'triang',args=(.5,))[1],'B':kstest(l,'beta',args=(.5,.5))[1],'E':kstest(l,'expon',args=(0,.5,))[1],'G':kstest(l,'gamma',args=(3,0,1/6.0))[1]}
if sum([x>1 for x in l]): r['U'],r['T'],r['B']=0,0,0
return max(r,key=r.get)
U=[line.rstrip('\n').split(',') for line in open(dir+'U.txt')]
U=[[float(x) for x in r] for r in U]
T=[line.rstrip('\n').split(',') for line in open(dir+'T.txt')]
T=[[float(x) for x in r] for r in T]
B=[line.rstrip('\n').split(',') for line in open(dir+'B.txt')]
B=[[float(x) for x in r] for r in B]
E=[line.rstrip('\n').split(',') for line in open(dir+'E.txt')]
E=[[float(x) for x in r] for r in E]
G=[line.rstrip('\n').split(',') for line in open(dir+'G.txt')]
G=[[float(x) for x in r] for r in G]
i,_u,_t,_b,_e,_g=0,0,0,0,0,0
for u,t,b,e,g in zip(U,T,B,E,G):
_u+=1 if f(u)=='U' else 0
_t+=1 if f(t)=='T' else 0
_b+=1 if f(b)=='B' else 0
_e+=1 if f(e)=='E' else 0
_g+=1 if f(g)=='G' else 0
print f(u),f(t),f(b),f(e),f(g)
print _u,_t,_b,_e,_g,100*5-_u-_t-_b-_e-_g
```
] |
[Question]
[
This is a sequel to this challenge: [Code close to the challenge: Sum of integers](https://codegolf.stackexchange.com/questions/53604/code-close-to-the-challenge-sum-of-integers)
The challenge in this one is a bit harder, and also makes for a cool title (Which is why I picked it):
>
> Calculate the Levenshtein distance between two strings
>
>
>
Just like last challenge, your score in this challenge is the [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance) between your code and the quote above.
So now for the details!
Your program will take 2 inputs, both strings with no trailing spaces or newlines, and will output the Levenshtein distance between them. Levenshtien distance is defined as the number of of additions, deletions, and substitutions necessary to transform one string to another. For more information on how to calculate it, see the Wikipedia page linked above. To test if your program works, use [this calculator](http://planetcalc.com/1721).
Your program must output nothing but the Levenshtein distance between the two strings. It will be disqualified if anything else is outputted.
**Example I/O:**
```
Inputs:
test
test2
Output:
1
Inputs:
222
515
Output:
3
Inputs:
Test
test
Output:
1
```
**Your code may not have no-ops or comments.**
[Answer]
# [Frink](http://futureboy.us/frinkdocs/), distance 24
```
Calculate[the,Levenshtein]:=editDistance[the,Levenshtein]
```
To use this, you would call Calculate with the two strings, and since this is returning, you also need to surround the call with `print[]`. If this isn't allowed, my score is 30.
Example:
```
Calculate["kitten","spork"] -> returns 6
print[Calculate["kitten","spork"]] -> prints 6.
```
You need to download Frink, as the web interpreter doesn't allow defining functions. It should run on all systems, considering it's a Java applet. Download instructions [here.](http://futureboy.us/frinkdocs/#JavaWebStart).
---
Psst. Hey! Here's a Levenshtein implementation in Symbolic, something I'm working on: `k=λ:Δ(ί,ί)`.
[Answer]
# R, distance 35
```
Calculate=function(the,Levenshtein)adist(between<-the,two<-Levenshtein)
```
This creates a function `Calculate` with parameters `the` and `Levenshtein`. It uses the R built-in function `adist` to compute the distance. The string parameters in `adist` are essentially `the` and `Levenshtein` renamed to `between` and `two`.
[Answer]
# PHP4.1, distance ~~32~~ ~~22~~ ~~15~~ 14
Very basic one, nothing exciting.
```
<?=$Calculate_the=Levenshtein($distance,$between_two_strings);
```
Or a shorter version:
```
<?=$ulatethe=Levenshtein($istance,$etweentwostrin);
```
For this to work, you need to send/set a POST/GET/COOKIE/session variable with the keys:
* `distance` (`istance` for the shorter one)
* `between_two_strings` (`etweentwostrin` for the shorter one)
The arguments are in that order.
Test the score on <http://ideone.com/QzNZ8T>
Example:
```
http://localhost/distance.php?distance=string1&between_two_strings=string2
```
[Answer]
# PHP, distance 44
```
function Calculate($two,$strings){echo levenshtein($two,$strings);}
```
Use the built-in `levenshtein` function from PHP standard library and named the arguments in order to try to minimize the distance.
[Answer]
# Pip, distance 50
Uses no builtin Levenshtein function!
```
xINg?#JgMN[1+(fac:b@>1)1+(fe:a@>1b)(a@0NEb@0)+(fec)]
```
This code implements [the recursive Levenshtein algorithm](https://en.wikipedia.org/wiki/Levenshtein_distance#Recursive); as such, it is extremely slow, taking a few seconds even for strings of length 5. I wouldn't recommend running the program through itself to check it!
Here's my base code, with whitespace and comments:
```
; Note: a Pip program is an implicit function f, which is called with the command-line
; arguments. The args are stored in the list g, as well as being assigned to the local
; variables a-e.
; Is one of the args the empty string? (NB x is initialized to "")
x IN g ?
; If so, join args together and take the length (i.e., length of the non-empty string).
# J g
; If not, take the min of the following:
MN [
; Recursively call f with the first character of a removed; add 1 to the result
(f a@>1 b) + 1
; Recursively call f with the first character of b removed; add 1 to the result
(f a b@>1) + 1
; Recursively call f with the first characters of both removed; iff the two characters
; were not equal, add 1 to the result
(f a@>1 b@>1) + (a@0 NE b@0)
]
```
The main change in the final version is assigning some values to temporary variables `c` and `e`, which appear in the challenge string and thus reduce the Levenshtein distance a bit.
] |
[Question]
[
You should write a program or function that given an `N` by `N` equally spaced square grid and a solid inscribed circle outputs or returns the number of grid squares which are overlapped partially or fully by the solid circle.
0-sized overlaps (i.e. when the circle only touches a line) are not counted. (These overlaps occur at e.g. `N = 10`.)
## Example
`N = 8 (64 squares), Slices = 60`
](https://i.stack.imgur.com/J0y83.png)
## Input
* An integer `N > 0`. (The grid wil have `N * N` squares.)
## Output
* An integer, the number of solid circle slices.
## Examples
(input-output pairs)
```
Inputs: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Outputs: 1 4 9 16 25 36 45 60 77 88 109 132 149 172 201
```
This is code-golf so shortest entry wins.
[Answer]
# Python 2, 72
```
lambda n:sum(n>abs(z%-~n*2-n+(z/-~n*2-n)*1j)for z in range(~n*~n))+n+n-1
```
Ungolfed:
```
def f(n):
s=0
for x in range(n+1):
for y in range(n+1):
s+=(x-n/2)**2+(y-n/2)**2<(n/2)**2
return s+n+n-1
```
The grid points for an `(n+1)*(n+1)` square. A cell overlaps the circle if its grid point nearest the center is inside the circle. So, we can count grid points, except this misses `2*n+1` grid points at axes (both for even and odd `n`), so we correct for that manually.
The code saves characters by using [complex distances](https://codegolf.stackexchange.com/a/41861/20260) to calculate the distance to the center and a [loop collapse](https://codegolf.stackexchange.com/a/41217/20260) to iterate over a single index.
[Answer]
# CJam, ~~36 35 34~~ 27 bytes
This turned out to be the same algorithm as xnor's, but I wonder if there is any better one.
```
rd:R,_m*{{2*R(-_g-}/mhR<},,
```
**Code explanation**:
```
rd:R "Read the input as double and store it in R";
,_ "Get 0 to input - 1 array and take its copy";
m* "Get Cartesian products";
"Now we have coordinates of top left point of each";
"of the square in the N by N grid";
{ },, "Filter the squares which are overlapped by the";
"circle and count the number";
{ }/ "Iterate over the x and y coordinate of the top left";
"point of the square and unwrap them";
2* "Scale the points to reflect a 2N grid square";
R(- "Reduce radius - 1 to get center of the square";
_g- "Here we are reducing or increasing the coordinate";
"by 1 in order to get the coordinates of the vertex";
"of the square closer to the center of the grid";
mhR< "Get the distance of the point from center and check";
"if its less than the radius of the circle";
```
*UPDATE* : Using the 2N trick from Jakube along with some other techniques to save 7 bytes!
[Try it online here](http://cjam.aditsu.net/#code=rd%3AR%2C_m*%7B%7B2*R(-_g-%7D%2FmhR%3C%7D%2C%2C&input=7)
[Answer]
# Pyth, ~~27~~ 26
```
-*QQ*4lfgsm^d2T*QQ^%2_UtQ2
```
Try it online: [Pyth Compiler/Executor](https://pyth.herokuapp.com/?code=-*QQ*4lfgsm%5Ed2T*QQ%5E%252_UtQ2&input=15&debug=0)
I use a `2Nx2N` grid and count overlapping `2x2` squares. That is a little bit shorter, since I already know the radius `N`.
And actually I don't count the overlapping squares. I count the non-overlapping squares of the second quadrant, multiply the number by 4 and subtract the result from `N*N`.
### Explanation for the 27 solution:
```
-*QQ*4lfgsm^-Qd2T*QQ^t%2UQ2 implicit: Q = input()
t%2UQ generates the list [2, 4, 6, ..., Q]
^ 2 Cartesian product: [(2, 2), (2, 4), ..., (Q, Q)]
These are the coordinates of the right-down corners
of the 2x2 squares in the 2nd quadrant.
f Filter the coordinates T, for which:
gsm^-Qd2T*QQ dist-to-center >= Q
more detailed:
m T map each coordinate d of T to:
^-Qd2 (Q - d)^2
s add these values
g *QQ ... >= Q*Q
*4l take the length and multiply by 4
-*QQ Q*Q - ...
```
### Explanation for the 26 solution:
I noticed that I use the coordinates only once and immediately subtract the coordinates from `Q`. Why not simply generate the values `Q - coords` directly?
This happens in `%2_UtQ`. Only one char larger than in the previous solution and saves 2 chars, because I don't have to substract `-Q`.
[Answer]
# Pyth, ~~44~~ 36
```
JcQ2L^-+b<bJJ2sm+>*JJ+y/dQy%dQqQ1*QQ
```
Trying to clean it a bit in case I could shave some bytes.
### Explanation
```
Q = eval(input()) (implicit)
JcQ2 calculate half of Q and store in J
L define function y(b) that returns
^-+b<bJJ2 (b - J + (1 if b < J else 0)) ^ 2
s output sum of
m *QQ map d over integers 0..(Q*Q-1)
+
>*JJ J*J is greater than
+y/dQy%dQ sum of y(d / Q) and y(d % Q)
qQ1 or Q is 1; see below
```
I have to explicitly check for `n = 1`, since my algorithm only checks the corner of the square nearest to the center (and none are covered in `n = 1`).
[Answer]
# Octave ~~(74) (66)~~ (64)
Here the octave version. Basically finding all the vertices within the circle and then finding all the squares with one or more valid vertices via convolution.
64 Bytes:
```
x=ndgrid(-1:2/input(''):1);sum(conv2(x.^2+x'.^2<1,ones(2))(:)>0)
```
66 Bytes:
```
x=meshgrid(-1:2/input(''):1);sum(conv2(x.^2+x'.^2<1,ones(2))(:)>0)
```
74 Bytes:
```
n=input('');x=ones(n+1,1)*(-1:2/n:1);sum(conv2(x.^2+x'.^2<1,ones(2))(:)>0)
```
[Answer]
## R - 64
```
function(n)sum(rowSums(expand.grid(i<-0:n-n/2,i)^2)<n^2/4)+2*n-1
```
] |
[Question]
[
Inspired by [Help me pair my socks](https://codegolf.stackexchange.com/q/196198/78410), and the fact that I have some pairs of socks where the left sock is distinct from the right.
---
## Background
Again, I have a huge pile of socks. And a machine that can give the list of labels of the socks for me. This time, the labels follow these rules:
* Some socks have left and right versions. In this case, left socks are labelled `-n` and right socks are labelled `n`, where `n` is a unique positive integer. The list of such socks will be explicitly given to you.
* The others don't have such a thing, and they just match themselves. All socks of this type are simply labelled `n` (no negative labels).
An example pile would look like this:
```
[3, 3, -2, 4, -1, -1, 1, 4, 4, 3, 2, 3, -1, 4, 4]
```
where 1 and 2 have left and right versions. Then the pairs and leftovers are:
```
pairs: {3: 2, 4: 2, 1: 1, 2: 1} or [1, 2, 3, 3, 4, 4]
leftovers: {4: 1, -1: 2} or [-1, -1, 4]
```
Note that two `-1`s don't make a pair because both are left socks.
## Challenge
Given the **pile of socks** and the **list of sock labels having L/R versions**, output the **pairs** that can be made from the pile, and **leftovers** that are not part of any pairs.
## Input and output
You can assume the following for input:
* Zeros won't appear in either list.
* L/R labels are unique and all positive, but possibly not sorted.
* Negative numbers that are not part of L/R labels won't appear in the pile.
Both outputs can be represented as either a mapping type (label to count) or a flat list (each item appearing once per count). You can output in following ways:
* Pairs can be represented as either a pair `(3, 3) / (-1, 1)` or a single number `3 / 1 / -1`, or a mixture of both. But **the same pairs should be represented in the same way in a single run**, e.g. outputting `[3, (3, 3)]` or `[(-1, 1), (1, -1)]` or `[1, -1]` is not allowed.
* For both pairs and leftovers, a *pair* and *single number* can be wrapped in any kind of containers, e.g. singleton arrays can be used to represent a single leftover.
* For both pairs and leftovers, the order of items is not important.
* If you use a mapping type, zero-count items are allowed, even the ones not in the pile of socks.
## Scoring and winning criterion
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
```
Pile: [3, 3, -2, 4, -1, -1, 1, 4, 4, 3, 2, 3, -1, 4, 4]
LR: [1, 2]
Pairs: [1, 2, 3, 3, 4, 4]
Leftovers: [-1, -1, 4]
Pile: [1, 1, 2, 2]
LR: [1]
Pairs: [2] (two right 1's and two simple 2's, so only 2's make a pair)
Leftovers: [1, 1]
Pile: [5, -10, 5, 10, -10, 10]
LR: [10, 20]
Pairs: [5, 10, 10]
Leftovers: []
Pile: [-6, 7, -9, 3, 4, -6, 4, -9, 8]
LR: [6, 9, 4]
Pairs: []
Leftovers: [-6, 7, -9, 3, 4, -6, 4, -9, 8]
Pile: []
LR: [1, 2]
Pairs: []
Leftovers: []
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~40~~ 27 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
.¡Ä}εDÄIåài{γζðδKë2ô]€`é.¡g
```
Inputs are in the order `Pile, LR` and outputs in the order `Leftovers, Pairs` in the format (`[[1],[2],[3]], [[1,1], [-2,2], [3,3]]`).
-13 bytes by porting [*@AZTECCO*'s Japt answer](https://codegolf.stackexchange.com/a/196882/52210), so make sure to upvote him!
[Try it online](https://tio.run/##yy9OTMpM/f9f79DCwy2157a6HG6JPLz08ILM6nObz207vOHcFu/Dq40Ob4l91LQm4fBKoLL0//@jjXUUgEjXSEfBBEgZQrAhmGcCljKCKIALGUFQLFe0IYgCAA) or [verify all test cases](https://tio.run/##yy9OTMpM/W/upuSZV1BaUmyloGTv6WKvpJCYlwJi2oZxKfmXlgClQDL/9Q4tPNxSe26ry@GWyMNLDy/IrD63@dy2wxvObfE@vNro8Jba2kdNaxIOrwSqS/9fq3Nom/3/aGMdBSDSNdJRMAFShhBsCOaZgKWMIArgQkYQFMsVbQihSDQBoRGiDGYYEJuCVBnoKABpEAVmGxqAJIEMIxBD10xHwRwoYwk2EmSfGYQCClgA5YE8S4gd2NwHR6YwWQA).
**Explanation:**
```
.¡ } # Group the (implicit) input integer-list `Pile` by:
Ä # Their absolute values
ε # Then map each group to:
i # If
Iåà # any values of the second input-list `LR`
DÄ # is in the current group's absolute values:
{ # Sort the values in the group
γ # And then group it on subsequent equal values
ζ # Zip/transpose to create pairs of positive & negative values,
# with space as default filler if the lists are of unequal length
ðδK # And remove all those spaces
ë # Else:
2ô # Split split the group into parts of size 2
] # Close the if-else statement and map
€` # Flatten each inner list once to remove the groups again
é # Sort each inner list by length
.¡g # And also group by length
# (after which this result is output implicitly as result)
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 62 bytes (SBCS)
```
,⌿⎕{⍺∊⍺⍺:((∊|⍴¨⍺××)n)(⍺/⍨0⌈2÷⍨≢⍵↓⍨n←⍺÷⍨+/⍵)⋄/∘⍺¨⌽0 2⊤≢⍵}⌸⍨∘|⍨⎕
```
[Try it online!](https://tio.run/##PU7BSsNAEL3vV8wtCVq72bbRCB6ketNT9eAxxeolbAJ6UKw3qTFmiyClPVcPPQi9WJSCCMmfzI@ssyvtwr59782bmY3SuHZ@G8XJpcbhqH3mXEXxtQP4/ACkO4dbp@3jA6eb3EAioXaxl0gH87eejLpxr7N/dMIwe0z1Jha/FL9DtcQsN6iWu65LvI/qs5yRrMbV2JOeS7SOasaxyET1RQyfpqgWOHglLnHwYrLG36DYwqOP1DGbkElTih8OAvP3/5Z7LL5Nfzbpm2c40vQXDfakrAENKOcCmoS@vT7xJrnCVqxiPgi26jAJQdpfOy2T49ACAst8zggFXyfKeQDbVAtpptkUWAxhhwUQ0vxVDtWH3aX/AA "APL (Dyalog Unicode) – Try It Online")
The initial "straightforward" version was around 76 bytes long; folks at [The APL Orchard](https://chat.stackexchange.com/rooms/52405/the-apl-orchard) helped me golf it substantially to the snippet above. Thanks!
## How does it work?
*Explanations written for the original "straightforward" version, not for the most golfed version above.*
At a high level, the `⌸` Key operator groups items from the pile such that we get an absolute-valued item as a key on the left and an array of all its occurences (with or without a minus sign) on the right.
```
┌─┬──────────┐
│3│3 3 3 3 │
├─┼──────────┤
│2│¯2 2 │
├─┼──────────┤
│4│4 4 4 4 4 │
├─┼──────────┤
│1│¯1 ¯1 1 ¯1│
└─┴──────────┘
```
Then we essentially do:
```
if the key is in the list of LRs:
compute leftovers and pairs for LRs
else:
compute leftovers and pairs for normal socks
```
After doing that for each row, we concatenate the columns (given to us in `leftovers, pairs` order) to a single array each and return those two arrays as a final result.
### Leftovers for LRs:
We sum the items on the right and divide them by the key; this gives us a number of leftovers; we absolute-value that (since it can be negative, eg. `-1 -1 1 -1 -> -2`) and then replicate the key (with the right sign applied) that many times.
```
¯2 ¯2 2 ¯2 ⍝ +/ sum:
¯4 ⍝ ÷2 divide by key:
¯2 ⍝ | absolute value:
2 ⍝ = number of times to replicate
¯2 ⍝ × get sign
¯1 ⍝ ×2 multiply by key:
¯2 ⍝ = item to replicate
2/¯2 ---> ¯2 ¯2
```
### Pairs for LRs:
We sum the items on the right, divide that by the key and get the absolute value. That gives us number of leftovers. We subtract that from the original number of items, which gives us the number of paired items. We divide that by two to get the number of pairs. We repeat the key that many times (it's guaranteed to be positive).
```
¯2 ¯2 2 ¯2 ⍝ +/ sum:
¯4 ⍝ ÷2 divide by key:
¯2 ⍝ | absolute value:
2 ⍝ (≢⍵)- subtract from count of items:
2 ⍝ ÷2 divide by 2:
1 = number of times to replicate
1/2 ---> 2
```
### Leftovers for normal socks:
We count the items, take remainder after division by 2 (either 0 or 1 odd sock can be the leftover). By problem definition we're guaranteed this number is not negative. We repeat the key that many times.
```
2 2 2 ⍝ ≢ count:
3 ⍝ 2| mod by 2:
1 ⍝ = number of times to replicate
1/2 ---> 2
```
### Pairs for normal socks:
We count the items, divide by two and round down. We repeat the key that many times.
```
2 2 2 ⍝ ≢ count:
3 ⍝ ÷2 divide by 2:
1.5 ⍝ ⌊ round down
1 ⍝ = number of times to replicate
1/2 ---> 2
```
[Answer]
# [R](https://www.r-project.org/), ~~138 134~~ 138 bytes
-2 bytes thanks to Giuseppe; +4 bytes to adhere to the output format
```
f=function(p,l,a={},b=a,z=p[1],w=abs(z))`if`(any(p),`if`(m<-match(z-2*z*w%in%l,y<-p[-1],0),f(y[-m],l,c(a,w),b),f(y,l,a,c(b,z))),list(a,b))
```
[Try it online!](https://tio.run/##LU7tCoMwDPy/p@ifQSIpaPfpsE8ig7VCmaBOpkN07Nld2goNl9xdcn2vq9Pu01Vj/eqgp4aM/v7IakOL7svsTpM2doAF8VG7B5huhh4p9G0hWzNWT1ikSpZk2tfdvqG5kH0peTFFcjCXsr3z1QoMTUg2cD6FGUt8Famph5FVi7g6qOBAgp9UJI4MWawsTMcgqWjYKGTxpnDnV6ORdeXZyJ28NSXB6CH0GX9NsJ1blWL0yTOJC@t5uO6jzxGYuAY7z7kPjP4td/0D "R – Try It Online")
Recursive function.
Takes the first sock `z` off the pile, and searches the pile for either `z` or `-z` depending on whether `w=abs(z)` is in `LR`. If a match is found, adds `w` to the list of pairs and removes both socks from the pile before recursing, else adds `z` to the list of leftovers and recurses.
Ungolfed:
```
# p is pile of socks
# l is vector of LR socks
# a will be vector of pairs
# b will be vector of leftovers
f = function(p, l, a={}, b=a, z=p[1], # initialize a and b as NULL; z is first sock of pile
w=abs(z)}
if(any(p)){ # check that p is not empty (would mean end of recursion)
y <- p[-1] # y is all socks except the first
m <- match(z - 2*z*w%in%l, # look for either z or -z depending on whether w=abs(z) is in l
y, 0) # find position of first match in y; if no match is found, return 0
if(m){ # if a match was found
f(y[-m], l, c(a, w), b) # append w to a, remove the matching sock from y, and recurse
} else {
f(y, l, a, c(b, z)) # else append z to b and recurse
}
} else {
list(a,b) # when p is empty, return a and b
}
}
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~28~~ ~~31~~ 23 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
üa c_ca øV ?ZüÎyf:ZòÃül
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=/GEgY19jYSD4ViA/WvzOeWY6WvLD/Gw&input=WzMsIDMsIC0yLCA0LCAtMSwgLTEsIDEsIDQsIDQsIDMsIDIsIDMsIC0xLCA0LCA0LCAzLCAzLCAtMiwgMiwgMiwgMiwgNSwgMTBdClsxLCAyLCA0XQotUQ)
Takes input as pile, labels.
Returns leftovers, every pair list.
```
üa group by same absolute value
c_ Ã for each group:
ca øV ? if labeled (using absolute values)
ZüÎyf - group by sign and transpose (saving only truthy values)
:Zò : else slice every 2 elements
ül group the result by length
```
~~g1\_cg1~~ no needed
[Answer]
# JavaScript (ES6), 85 bytes
Takes input as `(pile)(lr)`, where *pile* is an array and *lr* is an object.
Returns the pairs as a list and the leftovers as an object which may contain zero-count items.
```
a=>L=>[a.filter(x=>s[i=L[A(x)]?-x:x]?s[i]--:!(s[x]=-~s[x]),s={},A=Math.abs).map(A),s]
```
[Try it online!](https://tio.run/##dU/RisIwEHz3K@JbAklpe7VeC6n03fuCkIectl6lWmmqBMT79d4mOUXEQsJMZndms3t1UXrTN6eBHbttNdZ8VLxY80KooG7aoeqx4YUWDV@LEhsiV8zkRq5AkYzlc6yFkZz9WiBU8@uNlvxLDT@B@tYkOKgTLkGX46Y76q6tgrbb4RqLD4rgsJiiBCDyN3KvxJVi3/AvSYKvUY6G/lxByZMbIbOXVJ8B1vjJ8KZvYZNDigAtOB6FzhM@poSTdpZStARb5v5oF0g9gPBpU9J7SHYnyWTYxGrjHw "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), 99 bytes
Takes input as `(pile)(lr)`, where *pile* is an array and *lr* is an object.
Returns two lists.
```
a=>L=>[a.filter(x=>~(i=s.indexOf(L[A(x)]?-x:x))?s.splice(i,1):!s.push(x),s=[],A=Math.abs).map(A),s]
```
[Try it online!](https://tio.run/##dU/RToQwEHz3K@rbNikNRUSPpFx4P@MHEB4qV7waBMJyponRX8fSesYYSdrMdHdmtvui3hQ2kxnnqB@OemnlomRxkEWleGu6WU9gZfEJRiI3/VHbxxYOVQmW1vvI5pbSPXIcO9NoMEzQ/Br5eMaTEzCUVc1K@aDmE1dPSPmrGqF09Xpphh6HTvNueIYWqhtG3IkSRlIHIlzhX6lvJUHwXaopvIuczNNZu1YgH5Re/UkNGc6a/DL8o7tdk2NGHK7guYi9J/6ZEm/ao4yRO2fb@T@uC2QBXOF@TckuIbsLSTfDNlZbvgA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~25~~ 23 bytes
```
AĠị$ŒHAf⁹Ɗ?Z$ƙ$ẎL=¥ƇⱮؽ
```
[Try it online!](https://tio.run/##y0rNyan8/9/xyIKHu7tVjk7ycEx71LjzWJd9lMqxmSoPd/X52B5aeqz90cZ1h2cc2vtf5/By/Yc79z1qWpP1qGGOgq6dwqOGuVyH24ECkf//R3NFRxvrKACRrpGOggmQMoRgQzDPBCxlBFEAFYrV4YoGMo1iQYxoiFIjEB8kDhE0Bak20FEA0iAKzDY0ACsAsowMIKp0zXQUzIGylmDjQXabQSiggAVIBZBrCbIQrBphLVcsAA "Jelly – Try It Online")
A dyadic link taking the socks as its left argument and LR list as its right. Returns a list of lists with the leftovers as the first sublist (each wrapped on its own in a list) and the pairs as the second sublist.
Thanks to @JonathanAllan for saving a byte!
## Explanation
```
$ | Following as a monad:
A $ƙ | - For each group of the sock list defined by the absolute of the sock list, do the following as a monad:
Ɗ? | - If the following is non-empty:
A | - Absolute
f⁹ | - Filtered to keep only elememts in LR list
$ | - Then:
Ġị | - Split into groups based on sign
ŒH | - Else: split into two (almost) equal halves
Z | - Transpose
Ẏ | Join outermost lists together
¥ƇⱮؽ | Filter the list using the following as a dyad and each of [1, 2] as the right argument:
L | - Length
= | - Equals right argument
```
[Answer]
# [Perl 5](https://www.perl.org/), 151 bytes
```
sub f{
$_="@{[sort{abs$a<=>abs$b}sort@{+pop}]}";
($p,@p)=sub{push@p,$1;''};
for$l(@_){1while s/-($l) +$l\b/&$p/e}
s/\b(\d+) \1\b/$1~~\@_?$&:&$p/ge;
"@p",$_
}
```
[Try it online!](https://tio.run/##rVRRb5swEH7nV5w8q8GKEYUmXRtGxw/YXqa9hQgFDVYmOixMNlWI/vX0zk5CGiXapM1C9vm@77s7W@ZU0dbz7VZvcih7nsUs6Ze6abt@nWu@/hA/0JoP5Er6qWrUsBpY5HIlEyVilPVqox8TJXkQTSZDVDYtr90kE33w@7GqC9C@5/JawJTXae5fceUXg/bT3E2/TQWkATp58PKSJtlHfrUg/HsRsUQxybNhu9EFfC10t1h8btoCOjR1/HAXOZgHnp6Bkwdc5x0AKEr3x/Hpy85QenTWRdk1v4pWw38dpizvL8bIOqHDRcG/lLXEid3ADYQwAy@gL0Brhh4vpMnsmERWACGtxgCSWIBZ1YydhF5JG5wChjvpxcGCHc7eEknNzvD3weeY@hrmgBMZwfW5NAyRkBBmiAcSY@eL2Qf3buE9ePfmpGjPyL47TcBu4d7ew1vkghpWjugdIjw946@D71QCr1uc1LpqNW32D1DEiXnT0YFeZntSmY00xyaMoXSdowK0qqvO9cGXGF/IY2hpMD/VUwSphtURLGw@agO67aD/0VQ/JzCRphWYPkBNwAQA1FMfMIJKu8g/FCnsbRiXdewCj7zxCNLyRgdyh@0r "Perl 5 – Try It Online")
...151 bytes with `\n\s+` removed.
[Answer]
# [Zsh](https://www.zsh.org/), ~~179~~ 177 bytes
```
typeset -A p l
for x (`<&0`)((l[$x]++))
for k;((p[$k]=l[$k]<l[-$k]?l[$k]:l[-$k],l[$k]-=p[$k],l[-$k]-=p[$k]))
a=({,-}$^@)
for k (${(k)l:|a})((p[$k]=l[$k]/2,l[$k]%=2))
typeset p l
```
[Try it online!](https://tio.run/##VY7vTsIwFMW/9ylO4nRtoHGUP8pcoz4HwdBAkYY6lm4mKPLs87bgB5PmtufeX8@53@2u33LB@@6rsa3tIF/RwLPtIeAIvqruipXg3C@y43IwECIN9k@cN4tsv9Q@1sovJF3PSZQXMUxC6oQNL72rIhOj@Wkoz9nby9UQPDvxvfDljzmLf@b36mJ1qxV9/NuSVuwFYzdwteuc8WictyjRNmZtZWsbE0xnNzjUaLuNq4k0650LkTQutCVM@Hz/sHXXsi2qqsrHGEMqTCBH8YzoNaGWiu0kcuopltZNYT6AMyCPrIKicVRTogtMQSU@RkVORAFV5HEqZ3iAnJMn5cximeORiBnmFBCJiJMZEziRtOvdAbnWOs7SnlnKzrQP7Nz/Ag "Zsh – Try It Online")
Takes the sock pile on stdin, and the achiral pairs as arguments.
Due to Zsh's lack of filtering and mapping tools, we simply loop over the pile incrementing to create a `sock->count` map. Thankfully zero-count items are allowed; otherwise this would probably be in the 220-byte range, since filtering by value isn't easily done.
```
typeset -A p l # declare p, l as associative arrays
for x (`<&0`)((l[$x]++)) # for each sock in the pile, increment that key of the leftover array
for k; { # for each argument (an achiral pair)
((p[$k]=l[$k]<l[-$k]?l[$k]:l[-$k])) # set the paired array to the minimum of the l/r socks
((l[$k]-=p[$k],l[-$k]-=p[$k])) # decrement the leftovers we just paired
}
a=({,-}$^@) # if our achiral pairs were (2 3), set a=(2 -2 3 -3)
for k (${(k)l:|a}) # take the keys of the leftovers, remove all elements of a
((p[$k]=l[$k]/2,l[$k]%=2)) # divmod gets us the pairs and leftovers for the chiral socks
typeset p l # using typeset to print the current definitions is shorter than
# using something like '<<<${(kv)p},${(kv)l}'
```
[Answer]
# [Python 3.7](https://docs.python.org/3.7/), 183 Bytes
[Try it online!](https://tio.run/##fY7RbsIwDEXf@xV@TIZbtYGxFSlfUvWh1VIRqaRWKSC@vrMTBONlUiJf2/ckl@7LcQrbdf1xAwyKcNSHDDrsbdNi02ZwO/rRAfEQvKWCJlKl5ibYrj8rL9IPKvfgA5D@UEFEfASg29iAIqiY3Wm6OvYJ4EZGXsS0wP/UAzq7Q7@xnnezWy5zkJgrzT4salDNFoFPbhB2XKp0q9jt4sokw2PUIjQVmlbr7PlEAthn4vZt9yloicBVStRVGX2sTPlmzvcIX2yq45eSZ58KD76F4baWEH@hlAhipPUX) Link includes uncommented version of code with the five test cases.
```
def f(p,l):
a,b=[],[] #a = pairs, b = loners
while p: #iterate through pile
i=p.pop(0) #remove and look at first sock in pile
n=abs(i) #Prepare to compare abs(i) to LR list
#If there is a +ve/-ve pair from LR list
if(-i in p)*(n in l):
a+=n, #Add to pairs
p.remove(-i) #Remove other half of pair from the pile
#If there is a +ve/+ve pair not from LR list
elif(n in p)*(not n in l):
a+=n, #Add to pairs
p.remove(i) #Remove other half of pair from the pile
#Otherwise, add sock to loner list
else:b+=i,
return a,b #Return the completed lists
```
This is my first attempt at a code golf challenge so feel free to comment on any obvious optimizations I have missed.
Cheers
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 58 bytes
```
I⟦↔Φθ⎇№η↔ι›№…θκ±ι№…θκι﹪№…θκι²Φθ⎇№η↔ι›№…θ⊕κι№θ±ι›﹪№θι²№…θκι
```
[Try it online!](https://tio.run/##rY89D4IwEIb/SsdeUgaQzcmQaBw0Dm4NQy0XIVQqpZjw62v5MjjgZNLLfbzPXd7KXBiphXLuYorK0kQ0lvLdrdGqtUj3hbJoaM3IFU0lTEcT3XosZ@TDFACMHAyKnhzlpJMKk1w/@83Sy2e8ixldQQbtpLNWabqKMBIB9OA/jB0rafCBlcWMljDdH7l6aXlx5ctfPTv69SeAFGDrHOcbRvwLIkZin8IxwqGLBykagWmUMsJ9GaWpC17qDQ "Charcoal – Try It Online") Link is to verbose version of code. Outputs two double-spaced lists of newline-separated socks in a reproducible but unobvious order. Explanation:
```
I⟦
```
Cast both lists of socks to string for implicit print and double-space between the lists.
```
↔Φθ
```
Find the matched socks and print their absolute values so that we don't mix left and right socks in the output.
```
⎇№η↔ι
```
Is this a self-pairing sock?
```
›№…θκ±ι№…θκι
```
If not then it matches if there have been more opposite socks in the list so far (not including this sock, so at least as many opposite socks including this sock).
```
﹪№…θκι²
```
If it is then it matches if there have been an odd number of this type of sock so far (not including this sock). (If there are an odd number in total then this sock is actually matched against the next sock of this type.)
```
Φθ
```
Find the mismatched socks.
```
⎇№η↔ι
```
Is this a self-pairing sock?
```
›№…θ⊕κι№θ±ι
```
If not it is mismatched if the number of this type of sock so far (including this sock) is greater than the total number of opposite socks.
```
›﹪№θι²№…θκι
```
If it is then it is mismatched if this is the first of a total number of odd socks of this type.
Explanation for which socks get output as (mis)matches:
```
[[3, 3, -2, 4, -1, -1, 1, 4, 4, 3, 2, 3, -1, 4, 4], [1, 2]]
```
* The `1` gets output as a match for the first `-1` and the second and third `-1` are output as mismatches.
* The `2` gets output as a match for the `-2`.
* The second and fourth `3`s get output as matches for the first and third `3`s.
* The second and fourth `4`s get output as matches for the third and fifth `4`s, while the first `4` is a mismatch.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~143~~ 95 bytes
```
->a,l,*b{c=[];(s=a.index [w=a.pop,-w][l.count z=w.abs])?(a.slice!s;b<<z):c<<w while a[0];[b,c]}
```
[Try it online!](https://tio.run/##LUpLDoIwEL3KuAMzNIKspNWDTGbRVogkDTRUUsV49krA5L287zSbd@pUKq4aHR7NxyriJgtKi364ty@guFo/eiwikxN2nIcnLCoKbQLnt0yL4HrbHkJjpFzyi5UyQnz0rgVNJ27IoOVv8tARnRFWFBVCvUq5s9xSvU3VfvhXjFRixZx@ "Ruby – Try It Online")
] |
[Question]
[
*(based on [this](https://codegolf.stackexchange.com/q/194750/42963) deleted question)*
Take the English alphabet `a b c d e f g h i j k l m n o p q r s t u v w x y z` (spaces added for clarity), and split it into chunks of `X` width, padding any leftover lines with spaces if necessary for your language. For example, splitting it into width `4` results in
```
a b c d
e f g h
i j k l
m n o p
q r s t
u v w x
y z
```
Now, given a word composed of `[a-z]+`, output the path taken to spell that word when starting from `a` and using `!` to specify selecting that letter, with `D U R L` for `Down, Up, Right, Left`, respectively.
For the above `X=4` example, and the word `dog`, the output would be `R R R ! L D D D ! U U !` (spaces added for clarity and not required in output).
If `X=3`, you get a different picture of the alphabet:
```
a b c
d e f
g h i
j k l
m n o
p q r
s t u
v w x
y z
```
And a different solution for the word `dog` -- `D ! D D D R R ! L L U U !`.
## Examples
```
"dog" 4 --> R R R ! L D D D ! U U !
"dog" 3 --> D ! D D D R R ! L L U U !
"hello" 6 --> R D ! R R R U ! R D ! ! D L L L !
"codegolf" 10 --> R R ! R R D ! L U ! R ! R R ! L L D ! L L L ! U R R R R !
"acegikmoqsuwy" 2 --> ! D ! D ! D ! D ! D ! D ! D ! D ! D ! D ! D ! D !
```
## Rules
* Note that the grid *doesn't* wrap, so to get from the leftmost column to the rightmost column requires traversing the entire `X` distance.
* The output must be a shortest possible path, but doesn't necessarily need to be in a particular order. For example, for the first `dog` example you could instead produce `R R R ! D D D L ! U U !`, swapping the order of the `D`owns and the `L`eft, because that's the same length path and achieves the same character.
* Similarly, please output only one path (because there will likely be multiple), but that doesn't need to be deterministic (i.e., multiple runs of your program may produce different paths, provided they're all the shortest).
* The output doesn't have to have delimiters (like I do here with spaces), that's up to your aesthetic choice.
* You can choose input as all-lowercase or all-uppercase, but it must be consistent.
* The input number is guaranteed to be in the range `1` to `26` (i.e., a single column to a single row of letters).
* Input words are guaranteed to be at least one character long, and match `[a-z]+` with no other punctuation, spaces, etc., (i.e., you'll never receive empty string `""` as input), but it may not be an actual English word.
* Instead of `D U R L !`, you can choose five characters/numbers/arrows/etc. to represent the direction and selection. For example, you could choose `1 2 3 4 x`. This output choice must be consistent across all runs of your code, and please specify in your submission what the output is.
* Input and 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.
* [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins.
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), ~~41~~ 32 bytes
```
{,/(|4,&0|,/-:\)'-':+(0,y)\x-97}
```
[Try it online!](https://tio.run/##dY1PT4MwHIbvfIpfG@MggrA/0dia6KHHnsg4sSUjo60LbJ2URQibX50V1OxkemjT53nftwgO6tD3knR@6J4X/n109sOArLxJMCEPbuS33qoJXp4vvSKSWs1gFiccYZU2tF1fINxnhQAJJyNgJLA7mFpkOWgJEUxhBnNYOIZ0GOGwa95fxwL81lwm9mfV2AqjqxpQYMQxq7Ja5KAqfToaZ0m6u7T9roiER2joRhfU3chsV1K7TStvmK@FqR1nmbo41wrThUcNjuMYccYYShKE1zc4HyBDlgwCv9EPUZYa06cxzJDNJ8jeiHHO/5ytzoXSpcR0Gv2MWI8hbk001tm3tZN4WP/NZFuhdsVef5rTV4vpbMgh9s/B6/4K "K (ngn/k) – Try It Online")
output: `0=D 1=R 2=U 3=L 4=!`
`{` `}` function with arguments `x` and `y`
`x-97` convert `"a"`..`"z"` to `0`..`25`
`(0,y)\` divmod by `y`, returns a pair of lists - one with the quotients and one with the remainders
`+` flip - make it a list of pairs
`-':` deltas - subtract each pair from the previous one; use `0 0` as an implicit pair before the first
`(` `)'` for each pair (let's call it `(Δi;Δj)`) do:
* `-:\` self and own negation: `(Δi;Δj)` -> `((Δi;Δj);(-Δi;-Δj))`
* `,/` concatenate: -> `(Δi;Δj;-Δi;-Δj)`
* `0|` max with 0
* `&` "where" - for instance it would turn the list `a:1 5 0 2` into `0 1 1 1 1 1 3 3`, i.e. each index `i` is repeated `a[i]` times
* `4,` prepend a 4
* `|` reverse
`,/` concatenate
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~112 ... 104~~ 102 bytes
Takes input as `(width)(word)`, where *word* is expected in lowercase. Returns `01234` for `RLDU!`.
```
n=>w=>Buffer(w).map(g=c=>v-(c%=97)?g(c,v-=[-1,1,-n,n][d=(v-c)%n?v%n>c%n&1:v>c|2],o+=d):o+=4,o=v='')&&o
```
[Try it online!](https://tio.run/##jZFPb4MgGMbv/RTYxAop6uyaLmuCTRZ389TGU9ODQWTdLDilmCX77g7UZj3sMJ7wN/ye933hPdd5S5tzrXwhC9aXpBck7kj8ci1L1sAOBZe8hpxQEmsfUpc8P6EdhxRrnxz9CEfYF1icjgWB2qfIFTvtipi6YhFtdUy/Vycsl6RAWzOusSSaeB5aLGSvWKsAAQKQGHR2oFK0smJBJTkUgZIH1ZwFhyio8@Kg8kbBFQJL4BktQWdPX0UBo409LKFANteG1VVOGQyDkGNAra23T5PM8Y70hNBsZqPCNYLzQvI5Ar8tDMF@kANSkAxyQGbkjMzj34y9Nd6@sek9tTHUG6sqeccNkSw3xsuGld1bp3TQREcPBqfmW7isyslhynOkkyHi6ODcZZBMczrUsL9VNrqujKl5I37@uMjP9tp9GWfj6ky1/Lv3Pw "JavaScript (Node.js) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), ~~44~~ 41 bytes
```
;@(2<@(_,~[:I.0>.-,-~)/\0,]#:~_,[)97|3&u:
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/rR00jGwcNOJ16qKtPPUM7PR0dXTrNPVjDHRila3q4nWiNS3Na4zVSq3@a3KlJmfkKxgrpCmop@Snq3P9BwA "J – Try It Online")
*All credit to ngn for the best part: the self-append of the negative delta and max with 0, as a way of creating unique markers for each direction.*
*Separately, -3 bytes thanks to ngn for some line edits*
2 = D, 3 = R, 0 = U, 1 = L, \_ = select
* `97|3&u:` turns the letters into numbers, with `a` = 0.
* `]#:~_,[` use a mixed base of infinity and the left arg as a way of calculating divmod
* `0,` append 0 so we'll have a delta to the first letter
* `2<@(_,~[:I.0>.-,-~)/\` calculates the deltas, then append their negative, use J's "indices" (like k's "where" -- see ngn's answer), append an infinity `_,~`, and box the result `<@`.
* `;@` remove all the boxing
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~24~~ 20 bytes
```
O_97ŻdZIb1Ḥ2¦Z;€3Fḟ0
```
[Try it online!](https://tio.run/##ATEAzv9qZWxsef//T185N8W7ZFpJYjHhuKQywqZaO@KCrDNG4bifMP///2NvZGVnb2xm/zEw "Jelly – Try It Online")
A dyadic link taking the word as the left argument and the width as the right. Returns a list of integers where:
```
-2 = L
-1 = U
1 = R
2 = D
3 = Select
```
[Answer]
# [Python 3](https://docs.python.org/3/), 126 bytes
```
lambda s,n:[abs(x//n-y//n)*'UD'[y>x]+abs(x%n-y%n)*'LR'[y%n>x%n]+'!'for x,y in zip(map(O,'a'+s),map(O,s))]
O=lambda c:ord(c)-97
```
[Try it online!](https://tio.run/##Xc07C8IwFIbh3V8RhZIcG/GKYqGdHIWC4FQ7xN4MtkltKjb@@RgvQ3E58D3vcGrdXqRYmtw/mZJV55QhRYUXsbMi3XQqJtoeGOPjDkc66GL3Exzrzpv3B8uOCKzELh7iXDaooxpxgZ68JhWrSUgxw64C@h0KIB6E/u9X4skmJQlMthtTN1y0JCejVBYjilYAgz9a9umSlaW0uO5jItOskGVufT7rB5ZkBb9W8qbuD23rAsC8AA "Python 3 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~165~~ ~~164~~ ~~140~~ ~~138~~ ~~137~~ 135 bytes
```
#define W(b,c);for(;X b;putchar(c))
x,y,X;f(s,w)char*s;{x=y=0 W(=*s++,33){X-=97 W(%w<x,76)x--W(%w>x,82)x++W(/w<y,85)y--W(/w>y,68)y++;}}
```
[Try it online!](https://tio.run/##TY7NboMwEITP4SksKhQbGyUNLaFy4DXCgQsxP0ElOMWktoV4dmqnquht9tudmWVBw9iyvJRV3fYVOMMLYYjWfIA0Axd6f4zsWgyQIeQooklGayiIRBb6gk4q0cneuBJfYEzCEE1ZkHwcDfHkSZFjhFQQ2CFVJD4ghfEZ7uRJk/gdabvZyVSTKEYaYzrPyzdvSzBWYoSM92IEtgf4goC2H4FEYHI298HoGrq564ncBV4JgiAFLgHmSiLqbOyHv@rv@23eb808O46NuRVtD59RzyK35I1xv1nDfxCu4Fp1HTcoWhHjZdXwrjb0db/iglVN@3njX@IhtdkdbO3yAw "C (gcc) – Try It Online")
~~1~~ ~~25~~ ~~27~~ 28 byte shaved off thanks to ceilingcat!
Ungolfed:
```
int x, y, X, Y;
f(char *s, int w) {
x = 0; // Starting position is (0, 0)
y = 0;
while (*s) { // For each character
X = (*s - 'a') % w; // Get its x coordinate
Y = (*s - 'a') / w; // Get its y coordinate
s++;
while (X > x) putchar('R'), x++; // Print R for each step we need to move right
while (X < x) putchar('L'), x--; // ...et cetera...
while (Y > y) putchar('D'), y++;
while (Y < y) putchar('U'), y--;
putchar('!'); // We are there, print !
}
}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 20 bytes
```
AIk0šI‰ü-εεdDNOyÄ×]»
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f0TPb4OhCz0cNGw7v0T239dzWFBc//8rDLYenxx7a/f9/tFKKko6CUj6ISIcT@UqxXCYA "05AB1E – Try It Online")
Uses 0 for `D`, 1 for `R`, 2 for `U`, 3 for `L`, and newline for `!`. Space is used as an optional separator.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~52~~ 48 bytes
```
Nθ≔⁰δFES⌕βι«≔⁻﹪ιθ﹪δθη≔⁻÷ιθ÷δθζF±ηLF±ζUFηRFζD≔ιδ!
```
[Try it online!](https://tio.run/##XY/NCsIwEITP9iliTxuIUM@ehCIUrIjiA7RN2i7EpP@His8eG/uD9jh8M7M7SR5ViY6kMYEq2ubSPmNRQUkPzrGuMVPgMcL/lBhUqisCYVTAN3RvKlQZUEZOqDjEjCCllLyczZQKNW@lBmSkHEz5UDCTQDU@dsjFDHsLx3pUbQ3c@im5DhcacM/uCgubWPBjjXP7/IJva9zbNQv23Z/H8nH2LPtx92aybq31bczecxLNRaZlanad/AA "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 4 bytes by only tracking the alphabet index rather than the row and column separately. Takes input as `X` first, then the word. Explanation:
```
Nθ
```
Input `X`.
```
≔⁰δ
```
Start the path at the `a` with index `0`.
```
FES⌕βι«
```
Input the word, convert its letters to their alphabet index and loop over them.
```
≔⁻﹪ιθ﹪δθη
```
Calculate the horizontal difference.
```
≔⁻÷ιθ÷δθζ
```
Calculate the vertical difference.
```
F±ηLF±ζUFηRFζD
```
Turn those differences into a path.
```
≔ιδ
```
Update the current index.
```
!
```
Select the current letter.
The reverse program is only 23 bytes:
```
NθP⪫⪪βθ¶FS≡ι!⊞υKKM✳ι⎚↑υ
```
[Try it online!](https://tio.run/##HY6xDsIgFEVn@xWPTo@kJrrWURcNNQ2mmwsiWiJCS6EOxm9H9E0nuffkPtkLL50wKe3tEMMxPi/K40g3RRNN0IPXNuDBaYunweiAlwpGWkF5tiXNpZvzgH/zFHL1jpTC9NJB9oCawrtYSDEpKElZQxunHmMFrVIP/MmLq7qJvFJD42aFO@2VDNrZbOb0U2yNEh4ztv8v6m6oINJNSutVwTnhfEdYR35AGMvMGOl4PpKWs/kC "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ
```
Input `X`.
```
P⪫⪪βθ¶
```
Split the lowercase alphabet into substrings of length `X` and print them on separate lines without moving the cursor.
```
FS
```
Loop over the command characters.
```
≡ι!
```
If the next character is a `!`...
```
⊞υKK
```
... then save the letter under the cursor in a list...
```
M✳ι
```
... otherwise move in the direction given by that character.
```
⎚↑υ
```
Remove the alphabet and output the saved letters.
] |
[Question]
[
[Lenguage](https://esolangs.org/wiki/Lenguage) is a brainfuck dialect that is notorious for breaking source restriction challenges. That is because Lenguage cares only about the length of it's source and not the contents.
First, the length of the program is calculated. Then, said length is converted to binary and left-padded by zeroes to a multiple of 3. The resulting binary string is split into chunks of 3 bits each of which is translated into a brainfuck command as such:
```
000 -> +
001 -> -
010 -> >
011 -> <
100 -> .
101 -> ,
110 -> [
111 -> ]
```
Finally the program is run as brainfuck1.
From here the challenge is pretty simple, write a lenguage program that takes no input and produces an output consisting of one byte repeated integer \$n\$ times, where \$n\$ is strictly greater than the length of your program.
Answers will be scored in bytes with fewer bytes being better.
[Here's a hacky program to calculate lenguage from brainfuck](https://tio.run/##Tc7NaoQwFAXgvU9xkMJorTL9LzJ109VAF4UuZ4YSatTQGOV6pc7T2xsoTLZfzs05nZp@tLXryqTcZBVrlCXeOkXIK@wd61ZTdHncZBu8YhtK7uU2lMrLXSg7L/ehFF4eQrnx8hjKwctTKCcvz1HU@JWfTMa14c4GiQwsv1JJza7WjXG6Rp7jg4aWVI9v5dzAmFgR49dwh0yOFok3g60tkuPi/0tecC2aIU2xxRV6NeKyYll7ZZzcjDPLhneHeN@AOzNh/O/RRANNYtrhPMwE4yQMSfh6SY2a7FlKqVfMui5iVJW4cYykQZwf8qrYneJ0/QM "Haskell – Try It Online")
---
1: For this challenge we will use wrapping cells and a non-wrapping tape.
[Answer]
# 8437495638205698686671 bytes
This translates to the brainfuck program:
```
-[>>[>]+[->[>]+.[<]+<]<-]
```
Which prints exactly \$231584178474632390847141970017375815706539969331281128078915168015826259279614\$ SOH bytes.
This is calculated by the function
```
f(n)=2*f(n-1)+n
f(0)=0
```
with an input of 255.
### Explanation:
```
-[ Loop 255 times
>>[>] Move to the end of a series of positive cells (initially empty)
+ Add one cell to the end
[- Loop over each cell
>[>]+ Add one cell to the end
. Print a SOH byte
[<]+ Restore current cell
<] Move to next cell
<-] Decrement counter
```
[Answer]
# [9093903938998324939360576240306155985031832511491088836321985855167849863863065731015823](https://tio.run/##Tc5dS8MwFAbg@/2KlyKsNWbMbxmxN14NvBC8jEWCTddgm5Y0w@3X13PmwOQm5Ml7Plozfduum@cYjJ86Ey02G7y0JkCW2PpodzYs/j@XYolnrFORLNeplCw3qSiW21RWLHepXLHcp6JZHlKpWB4Xi4a3fI/B@V26Z4OcFtx8FpTa@9o2ztsaUuItDLtgenwZ74eIKZoQ8eNiC0FFB4o3Q1d3yD8O3C9/wiWpQFFgjQv0ZsT/Foe5N85TzbiPtMOrR7ZtEFs3YTzPsSEMYSKzHsdhH@A8hUEJHk@p0YbuSENDb2K09SpDWZI7H5E3yMrTkVpLuoRSqpKnw1jRUzMJLTQBv2UptNKCPkst1R9Q9FzDCVVxP75XpyZZMf8C) bytes
```
>>>>>>-[[->>>+<<<]------>>>-]<<<[<<<]+[+[>>>]<<<->+[<[+>-]>[-<<<<->+>>------>>]<<<<]>>-[<<<].>>>-]
```
Which prints exactly
```
298333629248008269731638612618517353495058861384016275770860733328251135402804732197446995616017112134460464130233444058136509123809012106419446593183683387659250431692751255099808162970657410517657862174602556590616568690423540284801267472920128909691902547970614008613488242333460665145840144517097342073878746293059960326132795671583153307437896728515625000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
```
(\$250^{255}\$) NUL bytes.
Credit goes to [*@hvd* in this Brainfuck answer](https://codegolf.stackexchange.com/a/98082/52210), so make sure to upvote him!
**Explanation:**
I was going to write an explanation of my own, but realized *@hvd*'s explanation is already on point, so I'll quote it here instead:
>
> `>>>>>>` is needed to leave a bit of working space.
>
>
> `-` produces 255 (*since 0 - 1 = 255 when we have wrapping cells*).
>
>
> `[[->>>+<<<]------>>>-]` turns this into 255 copies of the value 250,
> giving a tape that looks like:
>
>
>
> ```
> 0 0 0 0 0 0 250 0 0 250 0 0 ... 250 0 0 [0]
>
> ```
>
> `<<<[<<<]+` moves the data pointer back and finishes up the initial
> data:
>
>
>
> ```
> 0 0 0 [1] 0 0 250 0 0 250 0 0 ...
>
> ```
>
> Then comes the loop: `[+...-]` initially sets the 1 to a 2, which gets
> set back to 1 at the end of the loop. The loop terminates when the
> loop body already set 2 to 1.
>
>
> Now, the numbers 2 250 250 250 ... 250 represent a counter, in base
> 250, with each number one greater than the digit it represents.
>
>
> * `[>>>]<<<` moves all the way to the right. Since each digit is represented by a non-zero number, this is trivial.
> * `->+[<[+>-]>[-<<<<->+>>------>>]<<<<]>>-` decreases the counter by 1. Starting with the last digit: the digit gets decremented. If it remains positive, we're done. If it turns to zero, set it to 250, and
> continue with the digit before.
> * `[<<<].>>>` moves the pointer back before the left-most digit, and this is a nice moment to print a NUL byte. Then re-position to exactly
> the left-most digit, to see if we're done.
>
>
> To verify correctness, change the initial `-` to `+` to [print
> 2501](https://tio.run/##LYzBCYBQDEMHKnWC8BcJPaggiOBB@PPXtJpLeWmS7VnP@5j7lTlaRnodAOEtkYeQZRmNMopdWdD0HHR8hqJ/pxIIcdeWHsl8AQ) NUL bytes, `++` for [2502](https://tio.run/##LYzBCYBQDEMHKnWC8BcJPaggiOBB@PPXtJpLeWmS7VnP@5j7lTlaZqTXBRDeEnkIWZbRKKPYhxE0PQcdn6Ho36kEQty1pUcyXw), etc.
>
>
>
[Answer]
# 19326644346528796447 bytes
Brainfuck code:
```
>+[+[[+>->-<<]->>+].<]
```
Prints
```
57896044618658097711785492504343953926634992332820282019728792003956564819967
```
null bytes.
It works like this:
```
mem[i]=255;
do
while(--mem[i]){
mem[i+1]=mem[i+2]=mem[i];
mem[i]=1;
i+=2;
}
while(mem[--i]);
```
Quite straightforward recursion.
] |
[Question]
[
## Background
A [fractal sequence](https://en.wikipedia.org/wiki/Fractal_sequence) is an integer sequences where you can remove the first occurrence of every integer and end up with the same sequence as before.
A very simple such sequence is called [Kimberling's paraphrases](https://oeis.org/A003602). You start with the positive natural numbers:
```
1, 2, 3, 4, 5, 6, 7, 8, 9, ...
```
Then you riffle in some blanks:
```
1, _, 2, _, 3, _, 4, _, 5, _, 6, _, 7, _, 8, _, 9, ...
```
And then you repeatedly fill in the blanks with the sequence itself (including the blanks):
```
1, 1, 2, _, 3, 2, 4, _, 5, 3, 6, _, 7, 4, 8, _, 9, ...
1, 1, 2, 1, 3, 2, 4, _, 5, 3, 6, 2, 7, 4, 8, _, 9, ...
1, 1, 2, 1, 3, 2, 4, 1, 5, 3, 6, 2, 7, 4, 8, _, 9, ...
1, 1, 2, 1, 3, 2, 4, 1, 5, 3, 6, 2, 7, 4, 8, 1, 9, ...
```
That's our fractal sequence! Now let's take the partial sums:
```
1, 2, 4, 5, 8, 10, 14, 15, 20, 23, 29, 31, 38, 42, 50, 51, 60, ...
```
But what if we iterate this process? "Fractalise" the new sequence (i.e. the partial sums obtained from the steps above):
```
1, _, 2, _, 4, _, 5, _, 8, _, 10, _, 14, _, 15, _, 20, _, 23, ...
1, 1, 2, _, 4, 2, 5, _, 8, 4, 10, _, 14, 5, 15, _, 20, 8, 23, ...
1, 1, 2, 1, 4, 2, 5, _, 8, 4, 10, 2, 14, 5, 15, _, 20, 8, 23, ...
1, 1, 2, 1, 4, 2, 5, 1, 8, 4, 10, 2, 14, 5, 15, _, 20, 8, 23, ...
1, 1, 2, 1, 4, 2, 5, 1, 8, 4, 10, 2, 14, 5, 15, 1, 20, 8, 23, ...
```
And take the partial sums again:
```
1, 2, 4, 5, 9, 11, 16, 17, 25, 29, 39, 41, 55, 60, 75, 76, 96, ...
```
Rinse, repeat. It turns out that this process converges. Every time you repeat this process, a larger prefix of the sequence will remain fixed. After an infinite amount of iterations, you would end up with OEIS [A085765](https://oeis.org/A085765).
**Fun fact:** This process would converge to the same sequence even if we didn't start from the natural numbers as long as the original sequence starts with `1`. If the original sequence starts with any other `x`, we'd obtain `x*A085765` instead.
## The Challenge
Given a positive integer `N`, output the `N`th element of the converged sequence.
You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter.
You may choose whether the index `N` is 0- or 1-based.
## Test Cases
The sequence starts with:
```
1, 2, 4, 5, 9, 11, 16, 17, 26, 30, 41, 43, 59, 64, 81, 82, 108, 117, 147, 151, 192, 203, 246, 248, 307, 323, 387, 392, 473, 490, 572, 573, 681, 707, 824, 833, 980, 1010, 1161, 1165, 1357, 1398, 1601, 1612, 1858, 1901, 2149, 2151, 2458, 2517
```
So input `5` should result in output `9`.
[Here is a naive CJam reference implementation](http://cjam.aditsu.net/#code=ri%3AX%2C%3A)%7B%3AL0a*%7B_%7B_%7B%3B(%7D%7C%5C%7D%25W%3C_0%26%7DgX%3C0%5C%7B%2B_%7D%25W%3C_L%3D!%7DgN*&input=1000) which generates the first `N` numbers (given `N` on STDIN). Note that your code should only return the `N`th element, not the entire prefix.
[Answer]
# Python 2, ~~55 49~~ 42
I have no idea what's going on, but it seems hard to beat the Maple formula from the OEIS page.
This uses 0-based indexing.
```
f=lambda n,t=0:n<1or f(n/2,n%2)-~-t*f(n-1)
```
Thanks to @PeterTaylor for -6 bytes.
[Answer]
## CJam (23 22 bytes)
The partial sums are given at the even indexes of the fractal sequence, which is [A086450](https://oeis.org/A086450). The recurrence given there as the definition of A086450 is the basis for these implementations.
Using an explicit "stack" (in scare quotes because it's not LIFO):
```
{),){2md~)\),>+$)}h+,}
```
[Online demo](http://cjam.aditsu.net/#code=%7B)%2C)%7B2md~)%5C)%2C%3E%2B%24)%7Dh%2B%2C%7D%0A%0A24%25%60)
### Dissection
```
{ e# Anonymous function body; for clarify, pretend it's f(x)
e# We use a stack [x_0 ... x_i] with invariant: the result is sum_j f(x_j)
), e# Initialise the stack to [0 ... x]
) e# Uncons x, because our loop wants one value outside the stack
{ e# Loop. Stack holds [x_0 ... x_{i-1}] x_i
2md e# Split x_i into (x_i)/2 and (x_i)%2
~)\ e# Negate (x_i)%2 and flip under (x_i)/2
),> e# If x_i was even, stack now holds [x_0 ... x_{i-1}] [0 1 ... (x_i)/2]
e# If x_i was odd, stack now holds [x_0 ... x_{i-1}] [(x_i)/2]
+ e# Append the two arrays
$ e# Sort to get the new stack
) e# Uncons the greatest element in the new stack
}h e# If it is non-zero, loop
e# We now have a stack of zeroes and a loose zero
+, e# Count the total number of zeroes, which is equivalent to sum_j f(0)
}
```
---
At 23 bytes there's a much more efficient approach, with memoisation:
```
{2*1a{2md~)\){j}%>:+}j}
```
[Online demo](http://cjam.aditsu.net/#code=%7B2*1a%7B2md~)%5C)%7Bj%7D%25%3E%3A%2B%7Dj%7D%0A%0A50%25%60)
[Answer]
# Haskell, 65
```
s l=[0..]>>=(\i->[l!!i,s l!!i])
r=1:(tail$scanl1(+)$s r)
f n=r!!n
```
[Answer]
# [Templates Considered Harmful](https://github.com/feresum/tmp-lang), 124
```
Fun<If<A<1>,Add<Ap<Fun<Ap<If<Sub<A<1>,Mul<I<2>,Div<A<1>,I<2>>>>,A<0>,A<0,1>>,Div<A<1>,I<2>>>>,A<1>>,Ap<A<0>,Sub<A<1>,T>>>,T>>
```
This is an anonymous function. It's more or less the same as ~~my Python answer~~ the Maple formula on the OEIS page, except that I didn't implement modulus, so I had to use n-n/2\*2 instead of n%2.
Expanded:
```
Fun<If<
A<1>,
Add<
Ap<
Fun<Ap<
If<
Sub<
A<1>,
Mul<
I<2>,
Div<A<1>,I<2> >
>
>,
A<0>,
A<0,1>
>,
Div<A<1>,I<2>>
>>,
A<1>
>,
Ap<
A<0>,
Sub<A<1>, T>
>
>,
T
>>
```
[Answer]
# Mathematica, ~~47~~ 44 bytes
```
If[#<1,1,#0[Floor@#/2]+(1-2#~Mod~1)#0[#-1]]&
```
[Answer]
# Matlab ~~108~~ 103
I am using the fact that the desired series is the partial sum of <https://oeis.org/A086450>
But the computation complexity of my implementation is far from optimal, even for this simple recurrence.
```
n=input('')+1;
z=zeros(1,n);z(1)=1;
for k=1:n;
z(2*k)=z(k);
z(2*k+1)=sum(z(1:k+1));
end;
disp(sum(z(1:n)))
```
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.