text
stringlengths 180
608k
|
---|
[Question]
[
Typically, polyglots are constructed in such a manner that each language can ignore parts of the code that are present for other languages, by wrapping them in string literals, using comment syntax, or other similar tricks.
Your goal is to write a polyglot where the output for each language is the code from the polyglot that produces that output. Specifically, the output must be constructed from the polyglot code with only deletions, and it must be a quine in the given language.
## Rules
* Only [proper quines](https://codegolf.meta.stackexchange.com/a/4878/45941) are allowed (no reading the source code, no taking input, output must be to STDOUT or closest alternative if STDOUT is not an option, and the programs must consist of more than just literals that are implicitly printed).
* Since different languages can use different encodings, the raw bytes are what matters here. For example, if language A uses UTF-8 and language B uses CP437, the (hex) code `C3 88 46 47` would be `ÈFG` for language A and `├êFG` for language B.
* All outputs must be distinct (again, comparing raw bytes). This avoids complications with trying to restrict minor language versions - if two languages use the same part of the code to do the same thing, you can't claim them both.
+ If you have two languages A and B such that `XY` is a valid output in both, but `YZ` is also valid in B, you may choose `XY` as the output for A and `YZ` as the output for B, so you can claim both of them in your score (but you can't claim `XY` for both languages because of the above rule).
* All outputs must be as short as possible. For example, if your code was `print('foo')#something`, for Python 3 (ignoring the fact that the output is not correct), the code you would need to output would be `print('foo')`, and `print('foo')#` would not be allowed. If there are multiple strings of equal (minimal) length that produce correct output, you may choose any one of them.
* Submissions must be polyglots in at least 2 languages.
* Your score will be given by `(number of programming languages with distinct outputs)**3/(total byte size of polyglot)`. The highest score wins. In the event that two submissions achieve the same score, the submission that reached that score first will win.
[Answer]
## [GolfScript](http://www.golfscript.com/golfscript/) + [CJam](https://sourceforge.net/p/cjam) + [Fission 2](https://github.com/C0deH4cker/Fission) + [Jelly](https://github.com/DennisMitchell/jelly), 4 languages, 24 bytes, score 2.667
Let's start with the hex dump:
```
00000000: 3322 3024 700a 2721 2b4f 5222 0a3c 3024 700a 6523 7fff cccc
```
For GolfScript, CJam and Fission 2, we interpret this in some ASCII-compatible single-byte encoding like ISO 8859-1 (the exact encoding doesn't really matter, because the languages only define operators for ASCII characters anyway):
```
3"0$p
'!+OR"
<0$p
e#<DEL>ÿÌÌ
```
Where `<DEL>` is the control character `0x7f`.
In Jelly, this is assumed to be in Jelly's own code page, where it looks like this instead:
```
3"0$p½'!+OR"½<0$p½e#¶”ṘṘ
```
### GolfScript
The `e` on the last line is an unknown variable and `#` comments out the remainder of the line, so this prints
```
"0$p"
0$p
```
*with* a trailing linefeed. This is the GolfScript/CJam polyglot version of the standard quine:
```
".p"
.p
```
[Try the polyglot.](https://tio.run/nexus/golfscript#@2@sZKBSwKWuqO0fpMRlA2KnKtcf3n@453DP//8A "GolfScript – TIO Nexus") | [Try the quine.](https://tio.run/nexus/golfscript#@69koFKgxAUkuP7/BwA "GolfScript – TIO Nexus")
### CJam
Here, `e#` comments out the last line, so almost identically, this prints
```
"0$p"
0$p
```
*without* a trailing linefeed.
[Try the polyglot](https://tio.run/nexus/cjam#@2@sZKBSwKWuqO0fpMRlA2KnKtcf3n@453DP//8A "CJam – TIO Nexus") | [Try the quine.](https://tio.run/nexus/golfscript#@69koFLApa6o7R@kxGVsA@T8/w8A "GolfScript – TIO Nexus")
### Fission
Fission only sees the second line which *is* the standard Fission quine, so it prints
```
'!+OR"
```
I can't provide an online link for the polyglot here, because TIO sends the file to Fission as UTF-8, but Fission reads the source byte by byte, which makes the last line too long. However, I've tested this locally with an ISO 8859-1 encoded file (in which the last line has the same length as the second), to confirm that this works.
[Try the quine.](https://tio.run/nexus/fission2#@6@uqO0fpPT/PwA "Fission 2 – TIO Nexus")
### Jelly
The pilcrow is an alias for linefeeds in Jelly, so the source is equivalent to:
```
3"0$p½'!+OR"½<0$p½e#
”ṘṘ
```
All but the last line of a Jelly program are "helper links" (i.e. functions) which can be ignored unless they are called, provided they are syntactically valid. This is actually the reason the `3` comes first in the CJam and GolfScript programs, because otherwise the `"` can't be parsed in Jelly.
Otherwise, since the function isn't called, the program is equivalent to only its second line, which is the standard Jelly quine.
[Try the polyglot.](https://tio.run/nexus/jelly#@2@sZKBScGivuqK2f5DSob02YF6q8qFtjxrmPtw5A4j@/wcA "Jelly – TIO Nexus") | [Try the quine.](https://tio.run/nexus/jelly#@/@oYe7DnTOA6P9/AA)
[Answer]
# ><> + Python, 2 languages, ~~51~~ 46 bytes, score~=~~0.16~~ 0.17
Since there are no answers yet, I'll start with a simple one
```
#.09;!?lo}*2+2f"
_='_=%r;print _%%_';print _%_
```
Try it for [><>](http://fish.tryitonline.net/#code=Iy4wOTshP2xvfSoyKzJmIgpfPSdfPSVyO3ByaW50IF8lJV8nO3ByaW50IF8lXw&input=) and [Python](https://repl.it/Eirl/1)
For ><> the first line is a quine (# reflects, " puts the whole line on the stack, then we push 34 (charcode for ") and print everything) , execution never moves from it, so it effectively ignores the rest of the code.
For Python the first line is a comment, while the second one is a quine (standard approach in python, using string substitution with the same string as both arguments).
[Answer]
# JavaScript + Python 2 + Japt, 3 languages, 132 bytes, score ~= 0.205
```
A="`i96d)p2`i96d)p2";1//2;A=1
S="S=%s;console.log(S,uneval(S))";A//2;S="S=%r;print S%%S";"""
console.log(S,uneval(S))//""";print S%S
```
This prints
```
S="S=%s;console.log(S,uneval(S))";console.log(S,uneval(S))
```
in JavaScript (only in Firefox),
```
S='S=%r;print S%%S';print S%S
```
in Python 2, and
```
`i96d)p2`i96d)p2
```
in Japt. ([Test it online!](http://ethproductions.github.io/japt/?v=master&code=QT0iYGk5NmQpcDJgaTk2ZClwMiI7MS8vMjtBPTEKUz0iUz0lcztjb25zb2xlLmxvZyhTLHVuZXZhbChTKSkiO0EvLzI7Uz0iUz0lcjtwcmludCBTJSVTIjsiIiIKY29uc29sZS5sb2coUyx1bmV2YWwoUykpLy8iIiI7cHJpbnQgUyVT&input=))
### JavaScript
This is what JavaScript sees:
```
A="`i96d)p2`i96d)p2";1
S="S=%s;console.log(S,uneval(S))";A
console.log(S,uneval(S))
```
The first line is a no-op because `A` is not used in any way. The second line sets `S` to the string `S=%s;console.log(S,uneval(S))`, and the third prints it after replacing the `%s` with the `uneval`ed representation of `S` (just `S` wrapped in quotes). The result is a quine in JavaScript.
### Python
This is basically what Python sees:
```
A="`i96d)p2`i96d)p2";1//2;A=1
S="S=%s;console.log(S,uneval(S))";A//2;S="S=%r;print S%%S"
print S%S
```
The first line is pretty much a no-op; the only important part is the `A=1` at the end. This turns `A` into a number so that the integer division `A//2` on the second line doesn't throw an error.
The second line is mostly the same way, except it sets `S` to the string `S=%r;print S%%S`. The third line prints `S` after replacing the `%r` with the raw representation of `S` (just `S` wrapped in single-quotes). The result is a quine in Python 2.
### Japt
This is the JavaScript code the Japt interpreter sees:
```
A="`i96d)p2`i96d)p2";1//2;A=1
S="S=%s;console.log(S,uneval(S))";A//2;S="S=%r;print S%%S";"","\nconsole.log(S,uneval(S))//","";.p("r".i("n".t(),S%S))
```
As you can see, it's mostly the same as the JavaScript answer, with one main exception: the last two lines are combined. As a result, this is what the interpreter actually sees:
```
A="`i96d)p2`i96d)p2";1
S="S=%s;console.log(S,uneval(S))";A
```
The first line sets `A` to the Japt quine, and the second sets `S` to part of the JS quine. In Japt however, only the last expression is sent to output; this is `A`, so the output is ``i96d)p2`i96d)p2`.
[Answer]
# Jolf + ><>, score = 2\*\*3/15 = 0.533....
```
"r0:g>o<
"Q«Q«
```
Working on adding another language to this.
[Answer]
## ><>, Python 2 and 3, 3 languages, 107 bytes, score = 27/107 ~= 0.252
```
#o<}-1:"
a=1/1is 1;b="(_%(_,b))"[a:-a|9];_='a=1/1is 1;b="(_%%(_,b))"[a:-a|9];_=%r;print %s';print (_%(_,b))
```
Try it online: [Python 2](https://tio.run/nexus/python2#@6@cb1Ora2ilxJVoa6hvmFmsYGidZKukEa@qEa@TpKmpFJ1opZtYYxlrHW@rjq4EixrVIuuCosy8EgXVYnUoC27W//8A), [Python 3](https://tio.run/nexus/python3#@6@cb1Ora2ilxJVoa6hvmFmsYGidZKukEa@qEa@TpKmpFJ1opZtYYxlrHW@rjq4EixrVIuuCosy8EgXVYnUoC27W//8A), [><>](https://tio.run/nexus/fish#@6@cb1Ora2ilxJVoa6hvmFmsYGidZKukEa@qEa@TpKmpFJ1opZtYYxlrHW@rjq4EixrVIuuCosy8EgXVYnUoC27W//8A)
The Python 3 output is the second line exactly, and the Python 2 output is [this quine](https://tio.run/nexus/python2#@59oa6hvmFmsYGidZKukEa@qEa@TpKmpFJ1opZtYYxlrHW@rjq4EixrVIuuCosy8EgXVYnUoC2rU//8A). The ><> output is the first line.
## Explanation
This program is based off of the classic Python 2 quine:
```
_='_=%r;print _%%_';print _%_
```
First, to make it compatible with both Python 2 and Python 3, I changed the `print` statement to a function call, and added an extra space which will come in handy later:
```
_='_=%r;print (_%%_)';print (_%_)
```
Next, I needed a way to distinguish Python 2 from Python 3. One of the simplest ways is to take advantage of the fact that `/` is integer division in Python 2, but float division in Python 3. Thus, the following code evaluates to `True` in Python 2, but `False` in Python 3:
```
1/1is 1
```
In order to make the outputs distinct between the two languages, I needed to selectively remove the first and last parentheses in the `print` call (that's why I needed the space earlier - with no space, it wouldn't be a valid `print` statement in Python 2). Thus, I needed to modify the quine harness like so:
```
a=1/1is 1;b="(_%(_,b))"[a:-a|9];_='a=1/1is 1;b="(_%%(_,b))"[a:-a|9];_=%r;print %s';print (_%(_,b))
```
That expression `a:-a|9` evaluates to `0:9` in Python 2 and `1:-1` in Python 3. Thus, `b` is `"(_%(_,b))"` in Python 3, but in Python 2 the first and last characters are discarded, leaving `_%(_,b)`. And with that modification, the polyglot was valid for this challenge.
As suggested by Teal pelican, the ><> quine `#o<}-1:"` could be added fairly easily, thanks to the fact that `#` begins a single-line comment in Python. Simply prepending it and a newline adds another language and increases the score by nearly tenfold.
[Answer]
# Python 2 + Retina, 2 languages, 55 bytes, score = 2^3/55 ≈ 0.145
I used `$n` instead of `¶` to keep them both valid ASCII.
```
S='S=%r;print S%%S';print S%S#|
#$n\(*S1`$n\(*S1`
#\`#
```
[**Python**](https://tio.run/nexus/python2#@x9sqx5sq1pkXVCUmVeiEKyqGqwOZwcr13Apq@TFaGgFGybAaC7lmARlrv//AQ), [**Retina**](https://tio.run/nexus/retina#@x9sqx5sq1pkXVCUmVeiEKyqGqwOZwcr13Apq@TFaGgFGybAaC7lmARlrv//AQ)
Python:
```
S='S=%r;print S%%S';print S%S
```
Retina:
```
\(*S1`
\(*S1`
```
[Answer]
## ><> + Pyke + Python 2, 81 bytes, score = 3\*\*3/81 ~0.333
```
"""r00gol?!;60.
a=%r;print a%%a"""#);"34.Cp\D\Es"DEp00/
a=__doc__[-15:]
print a%a
```
I've tried to do something different with all the languages.
### ><> sees:
```
"""r00gol?!;60.
```
This is a slight modification of the standard ><> quine to use a triple quoted string at the beginning. This allows the ending triple quotes for Python to be on a different line.
[Try it online!](https://tio.run/nexus/fish#@6@kpFRkYJCen2OvaG1moMeVaKtaZF1QlJlXopCoqpoIlFbWtFYyNtFzLohxiXEtVnJxLTAw0Aeqi49PyU@Oj4/WNTS1iuWCaUn8/x8A "><> – TIO Nexus")
### Pyke sees:
```
"34.Cp\D\Es"DEp00/
```
I hadn't created a quine in Pyke before and thus had to think of one. I used traditional quining techniques to create a string and then eval it with itself as an input. Note for this to work without visual impact, warnings will have to be disabled. Errors out with a division by 0 error in the generation step.
[Try it here!](http://pyke.catbus.co.uk/?code=%22%22%22r00gol%3F%21%3B60.%0Aa%3D%25r%3Bprint+a%25%25a%22%22%22%23%29%3B%2234.Cp%5CD%5CEs%22DEp00%2F%0Aa%3D__doc__%5B-15%3A%5D%0Aprint+a%25a&warnings=0) Or [just the quine part.](http://pyke.catbus.co.uk/?code=%2234.Cp%5CD%5CEs%22DE&warnings=0)
### Python sees:
It all. Python uses all of the code to produce its quine. I decided to embed the quine part in the docstring (though ultimately it would save bytes to remove but I think it's cool). It's a modification of the standard quining technique.
[Try it online!](https://tio.run/nexus/python2#@6@kpFRkYJCen2OvaG1moMeVaKtaZF1QlJlXopCoqpoIlFbWtFYyNtFzLohxiXEtVnJxLTAw0Aeqi49PyU@Oj4/WNTS1iuWCaUn8/x8A "Python 2 – TIO Nexus")
] |
[Question]
[
Write a program that accepts a single lowercase word as input and outputs the number of pairs of letters that have the same number of letters between them in the word as in the alphabet.
For example, in the word 'nature', we have 4 pairs:
* nr: since there are three letters between them inside the word (a, t, u) and three letters between them in the alphabet (o, p, q)
* ae: since there are three letters between them inside the word (t, u, r) and three letters between them in the alphabet (b, c, d)
* tu: since there are no letters between them inside the word and no letters between them in the alphabet
* tr: since there is one letter between them inside the word (u) and one letter between them in the alphabet (s)
Since there are four pairs, the output in this case should be 4.
[Answer]
# Pyth, 19 bytes
```
lfqF-MSMCT.cCUBCMz2
```
Try it online: [Demonstration](http://pyth.herokuapp.com/?code=lfqF-MSMCT.cCUBCMz2&input=nature)
### Explanation:
```
lfqF-MSMCT.cCUBCMz2
z read a string from input
CM convert into list of ascii-values
CUB create a list of pairs (ascii-value, index in string)
.c 2 all combinations of length 2
f filter for combinations T, which satisfy:
CT transpose T ((ascii1, ascii2), (index1, index2)
SM sort each list
-M create the the difference for each
qF check if they are equal
l print the number of remaining combinations
```
[Answer]
## R, 110 bytes
```
function(s){w=strsplit(s,"")[[1]]
O=outer
n=nchar(s)
sum(abs(O(r<-match(w,letters),r,"-"))==O(1:n,1:n,"-"))-n}
```
Degolfed:
```
F = function(s){
chars = strsplit(s,"")[[1]]
num_chars = nchar(s)
letter_rank = match(chars, letters)
rank_dist = abs(outer(letter_rank, letter_rank, "-"))
position_dist = outer(1:num_chars, 1:num_chars, "-")
return(sum(rank_dist == position_dist) - num_chars)
}
F("nature")
# [1] 4
F("supercalifragilisticexpialidocious")
# [1] 25
```
[Answer]
# Octave, 41 bytes
```
@(s)nnz(abs(s-s')==(t=1:(u=nnz(s)))-t')-u
```
[Answer]
# CJam, 36 bytes
```
r:A,{)Aew}%1>{{:B,B0=BW=-z)=}%}%e_:+
```
[Try it Online.](http://cjam.aditsu.net/#code=r%3AA%2C%7B)Aew%7D%251%3E%7B%7B%3AB%2CB0%3DBW%3D-z)%3D%7D%25%7D%25e_%3A%2B&input=nature)
[Answer]
# [Husk](https://github.com/barbuz/Husk), 8 bytes
```
#S≡Γ·…→Q
```
[Try it online!](https://tio.run/##AR8A4P9odXNr//8jU@KJoc6TwrfigKbihpJR////bmF0dXJl "Husk – Try It Online")
## Explanation
```
#S≡Γ·…→Q
Q all continuous sublists
# number of sublists which satisfy:
S≡ has the same shape and distribution of truthy/falsy values as:
Γ·…→ the range between its first and last character?
```
[Answer]
# J, 27 bytes
```
#-:@-~#\+/@,@:=&(|@-/~)3&u:
```
Usage:
```
(#-:@-~#\+/@,@:=&(|@-/~)3&u:) 'nature'
4
```
Explanation:
```
#-:@-~#\+/@,@:=&(|@-/~)3&u:
#\ lengths of input prefixes (1,2,...,length)
3&u: codepoints of input
&( ) with the last two do parallel:
|@-/~ create difference table with itself and take absolute values
= compare the elements of the two difference tables
+/@,@: sum the table
# -~ subtract the length of the input (self-similar letters)
-:@ half the result (each pair was accounted twice)
```
[Try it online here.](http://tryj.tk/)
[Answer]
# CJam, 25 bytes
```
l:T,_2m*{_:-\Tf=:-z=},,\-
```
[Try it online](http://cjam.aditsu.net/#code=l%3AT%2C_2m*%7B_%3A-%5CTf%3D%3A-z%3D%7D%2C%2C%5C-&input=nature)
Explanation:
```
l Get input.
:T Store in variable T for later use.
, Calculate length.
_ Copy for use at the very end.
2m* Use Cartesian power to calculate all possible position pairs.
{ Start filter.
_ Create copy of index pair.
:- Calculate difference between indices.
\ Swap copy of index pair to top.
T Get input string stored in variable T.
f= Extract the letters for the index pair.
:- Calculate difference of the two letters.
z Take the absolute value.
= Compare index difference and letter difference.
}, End filter.
,\
- Pairs of identical indices passed the filter. Eliminate them from the
count by subtracting the length of the input.
```
[Answer]
# JavaScript (ES6), 98 bytes
```
f=w=>(p=0,q="charCodeAt",[...w].map((c,a)=>{for(b=a;w[++b];)p+=Math.abs(w[q](a)-w[q](b))==b-a}),p)
```
## Usage
```
f("nature")
=> 4
```
## Explanation
```
f=w=>(
p=0, // p = number of pairs
q="charCodeAt",
[...w].map((c,a)=>{ // iterate through each character of input
// a = character A index
for(b=a;w[++b];) // iterate through the remaining input characters
// b = character B index
p+= // add 1 to p if true or 0 if false
Math.abs(w[q](a)-w[q](b))==b-a // compare absolute difference of character codes
// to difference of indices
}),
p // return p
)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~32~~ 16 bytes
```
ḢØaṣU1¦=
ṫJÇ€Fċ1
```
[Try it online!](https://tio.run/##ASoA1f9qZWxsef//4biiw5hh4bmjVTHCpj0K4bmrSsOH4oKsRsSLMf///2FiZWY "Jelly – Try It Online")
–16 when I learned how to reverse just the first element of a list.
### How?
```
ḢØaṣU1¦= - helper monadic link, e.g. nature
Ḣ - pop first character n
Øa - lowercase alphabet abcdefghijklmnopqrstuvwxyz
ṣ - split list abcdefghijklm opqrstuvwxyz
U1¦ - reverse first element mlkjihgfedcba opqrstuvwxyz
= - equate with string mlkjihgfedcba opqrstuvwxyz
= ature ature
-> 00000hgfedcba 00010tuvwxyz
ṫJÇ€Fċ1 - main monadic link, e.g. nature
J - range 1 2 3 4 5 6
ṫ - tail; remove n-1 chars nature ature ture ure re e
Ç€ - map previous link 00000hgfedcba 00010tuvwxyz ...
F - flatten 00000hgfedcba 00010tuvwxyz ...
ċ1 - count 1s 4
```
[Answer]
# Python 2, 91 chars
```
lambda i:sum(y-x==abs(ord(i[y])-ord(i[x]))for x in range(len(i))for y in range(x+1,len(i)))
```
[Answer]
## MATLAB, 84 bytes
```
s=input('');disp(sum(diff(nchoosek(find(s),2),[],2)==abs(diff(nchoosek(s,2),[],2))))
```
This line asks for a string as input. It then creates all possible pairs of letters and does the same for their corresponding indices. Then we determine whether the (absolute) difference of the values matches to finally sum all cases where it does. The result is displayed in the command window.
[Answer]
# JavaScript ES7, 93
Using *array comprehension*. ES6 with `.map.map.map` is 2 bytes longer.
Test running the snippet below with Firefox
```
f=s=>[for(x of s)x.charCodeAt()].map((a,i,s)=>s.map((b,j)=>t+=j>i&(b>a?b-a:a-b)==j-i),t=0)&&t
document.write('nature'+'\n'+f('nature'))
```
[Answer]
## PowerShell, ~~114~~ 100 Bytes
```
param($a)$b=$a.length;0..($b-1)|%{$i=$_;($_+1)..$b|%{$o+=[math]::Abs(+$a[$_]-$a[$i])-eq($_-$i)}};+$o
```
Pretty straight-forward, but uses a couple tricks.
* `param(..)` takes our input, saves it to `$a`.
* We set a temp variable `$b` to be the `.length` of our input. This saves a byte later.
* `0..($b-1)|%{..}` is the equivalent of a `for($i=0;$i-le($b-1);$i++){..}` loop, but quite a lot shorter.
* However, we need to set variable `$i` in order to keep that going into ...
* `($_+1)..$b|%{..}` the next `for` loop, since `$_` is only positional to the inner loop.
* We then use a lengthy .NET call to check if the absolute value between our two characters (here we use implicit casting with prepending `+` to save a bunch of bytes) is `-eq`ual to the positional difference in the array. Since we're explicitly given lowercase input, we don't need to do case conversion. This statement will return either `True` or `False`.
* We blatantly abuse implicit casting again to accumulate that result into `$o`, so `True` will add 1, while `False` will add 0.
* Once the loops are finished, we output `$o`. Note we need to do the same tricksy-cast-to-int with `+` to avoid printing `False` if there were no matches.
[Answer]
# Ruby, 74
```
->s{[*0...s.size].permutation(2).count{|i,j|(s[i].ord-s[j].ord).abs==j-i}}
```
Nothing super interesting here. I would have loved to use `eval("s[i].#{["succ"]*(j-i)*?.}")` but... seemed too long.
[Answer]
## Matlab~~(94)~~(80)
>
> Edit: I didnt take in case inversed alphabetic order,as (t,r) in 'nature', so more bytes to upweight :(
>
>
>
```
@(a)sum(arrayfun(@(x)sum(1:nnz(find(a==fix(x/2)+(-1)^x*(1:1:nnz(a))))-1),2:244))
```
---
* ~~binomial function throws a stupid exception when k is bigger than n and I cant catch exceptions inside `arraycell` function, otherwise I could golf it more.~~ **Who needs a built in function ??**
Now I could just do it by hand, simplifying
binomial(n,2)=n/(2(n-2)!)=n(n-1)/2. remark that this last value
reprensents sum of integers from 1 to n-1, this doesnt throw any
exception in matlab, God bless maths.
* Ps: this method is diferent than slvrbld's
## Execution
```
>> ans('abef')
ans =
2
>> ans('abcd')
ans =
6
>> ans('nature')
ans =
4
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
ONƬ_JLƙ€c2SS
```
[Try it online!](https://tio.run/##y0rNyan8/9/f79iaeC@fYzMfNa1JNgoO/n@4HciK/P9fKS@xpLQoVUlHQSkxKRlMJSeBqPL8ohQwFwyUAA "Jelly – Try It Online")
Got too caught up in figuring out the best way to do this with `Ẇ` and forgot to post an answer at all, but now that I've remembered I think I might leave that as an exercise to @cjquines ;)
] |
[Question]
[
## Background
In some possible futures, the world will convert their numerical systems from decimal (base 10 or `b10`) to some other base (binary `b2`, octal `b8`, hexadecimal `b16`, or even unary `b1`, in which case we're screwed!). Thus, in preparation for this possible world-changing event, you decide to base-proof all of your programs. This can be done by using only singular `0`s and `1`s in conjunction with operators to replace the existing number constants.
However, there's just one problem: You have a ton of programs to change, and manually converting each number to an expression would take weeks! Thus, you decide to write a program (or function) to decide for you what expression should replace each number.
## Input
The input will be a positive integer. Your code **must** be able to handle any integer up to 1000.
(If your code supports decimals and/or negative inputs, see **Scoring** below.)
## Output
Your code must output an expression that evaluates to the input in at least one language. This may be any language; it does not have to be the same one your program or function is written in. Also, this expression does not need to be a full program or function.
For clarity, the output may contain any of these operations:
* increment / decrement
* add / sum
* subtract / negate
* multiply / double (only if it doesn't directly involve the number `2`!)
* divide / modulo
* exponents / logarithms
* square / sqrt (again, only if these don't directly involve the number `2`!)
* bitwise operations (bOR, bAND, bNOT, bXOR, bit-shifts)
* setting / getting variables
* stack manipulation
You may **not** use `eval()` or any similar functions in the output. You may also not use in the output any functions that perform an action(s) other than the ones mentioned above.
Oh, and one more thing: since we want the output to be valid in as many bases as possible, the only number constants it may contain are `0` and `1`. Numbers such as `10` (ten) are disallowed, unless the language interprets it as a `1` and a `0`. Using strings to contain numbers is not allowed either, as is using characters such as CJam's `A`-`K` (which represent `10`-`20`).
## Test-cases
(All outputs are in JavaScript, but may work in other languages.)
**Input 1:**
```
2
```
**Possible output 1:**
```
1+1
```
**Input 2:**
```
13
```
**Possible output 2:**
```
(a=1+1+1)*a+a+1
```
**Input 3:**
```
60
```
**Possible output 3:**
```
(b=(a=1+1+1+1)*a)*a-a
```
**Input 4:**
```
777
```
**Possible output 4:**
```
(c=(b=((a=1+1+1+1)*a-a+1)*a)*a+b)+c+c-a+1
```
**Input 5:**
```
1000
```
**Possible output 5:**
```
Math.pow((a=1+1+1)*a+1,a)
```
---
## Scoring
The goal of this challenge is to shorten your code's output as much as possible. Your score will be calculated in this way:
* **Base score:** The average byte-count of all outputs for integers 1 to 1000.
* **Decimal score:** If your code supports at least 3 decimal places, this is the average byte-count of all outputs of the sequence of numbers starting at `0.001` and ending at `1000`, increasing by `1.001` each time. `0.001, 1.002, 2.003...998.999, 1000.000` Then take 50% off of this score.
* **Negative score:** If your code supports negative numbers and zero, this is the average byte-count of the outputs of all integers from `-1000` to `0`. Then take 10% off of this score.
(The easiest way to calculate these would likely be a loop with your program/function inside.)
**Your final score is the average of whichever of the above formulas apply.**
If the output is non-deterministic (i.e. somewhat random; multiple runs with the same input produces multiple unique outputs), then the score for each input is determined by the largest output over ten runs on my CPU.
Also, as you don't know how precious computer data will be in the future, **the byte-count of your generator code must be less than 512 bytes.**
~~**Lowest score in two weeks (on Sep 30) will be declared the winner.**~~ Congratulations to your winner, **@ThomasKwa**!
---
## Leaderboard
```
var QUESTION_ID=58084,OVERRIDE_USER=42545;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[3],language:a[1]+'/'+a[2],lang2:a[2],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size.toFixed(3)).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.lang2,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){var E=e.lang.toLowerCase(),S=s.lang.toLowerCase();return E>S?1:E<S?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size.toFixed(3)).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,])\/([^\n,]*[^\s,]),.*?([\.\d]+)(?=[^\n\.\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\.\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Languages</td><td>Score</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Output Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```
To make sure your answer shows up correctly, please start it with this header:
```
# Language name/Other language name, X points
```
Where `X` is the score of your answer. Example:
```
# CJam/Pyth, 25.38 points
```
If you have any questions or suggestions, please let me know. Good luck!
[Answer]
# Python/Zilog Z80 machine code, ~~11.653~~ 11.488
```
import math,numpy as np
def R(n):
if n==0:return []
if n<0:return -R(-n)
e=int(math.log(n,2))
if n >= 5/3 * 2**e:
return np.append(2**(e+1),-R(2**(e+1)-n))
return np.append(2**e,R(n-2**e))
def strR(n):
b = R(n)
s = ""
if n==0:return s
e=max(abs(b))
while e:
if e in b:s+="#"
elif -e in b:s+="+"
s+=")"
e//=2
return s[:-1]
```
Bonuses: Negative numbers.
Assumes that the `hl` register pair initially holds 0, and returns the result in `hl`.
Only these three instructions are used:
```
ASCII Hex Instruction
--------------------------
# 23 inc hl
) 29 add hl,hl
+ 2B dec hl
```
We use a small modification of the [minimum-weight balanced binary representation BBR2](https://cs.uwaterloo.ca/~shallit/Papers/bbr.pdf). Since BBR2 minimizes the weight (number of nonzero digits), but we want to minimize the weight plus the number of bit shifts, we change a constant in the algorithm from `3/2` to `5/3`.
To compute the score and verify, use this code:
```
def verify(n):
v = 0
for c in strR(n):
if c=="#":v += 1
elif c=="+":v -= 1
else: v *= 2
return v==n
print(0.5*(sum([len(strR(n)) for n in range(1,1001)])/1000 + \
sum([len(strR(n)) for n in range(-1000,1)])/1001 * 0.9))
print(all([verify(n) for n in range(-1000,1001)]))
```
Example output:
```
strR(486)
'#)))))+)+))+)'
```
Or in assembly:
```
inc hl \ add hl,hl \ add hl,hl \ add hl,hl \ add hl,hl \ add hl,hl \ dec hl \ add hl,hl \ dec hl \ add hl,hl \ add hl,hl \ dec hl \ add hl,hl
```
More example programs:
```
-256 +))))))))
-255 +))))))))#
-254 +)))))))#)
-253 +)))))))#)#
-252 +))))))#))
-251 +))))))#))#
-250 +))))))#)#)
-249 +)))))#)))+
-248 +)))))#)))
-247 +)))))#)))#
-246 +)))))#))#)
-245 +)))))#))#)#
-244 +)))))#)#))
-243 +)))))#)#))#
-242 +))))#)))+)
-241 +))))#))))+
-5 +))+
-4 +))
-3 +)+
-2 +)
-1 +
0
1 #
2 #)
3 #)#
4 #))
5 #))#
```
Possible optimizations: OP rules that the `inc h` and `dec h` instructions, which directly change the upper byte of `hl`, are illegal, but `sla h` and the undocumented `sl1 h` (left bit shifts by 1 on `h` that shift in a `0` and `1` respectively) are permitted. `sla h` and `sl1 h` are two bytes each, but they can sometimes shorten the output.
[Answer]
# CJam/CJam, ~~143.263~~ ~~42.713~~ ~~28.899~~ ~~23.901~~ ~~21.903~~ 20.468
```
ri
[
['X\2b1>e`{~{"1)*)"*}{_({(')*1\"m<"}{"1)*"*}?}?}/]s
"X1)*"/"1)"*
"1)1)*"/"1)))"*
"X1)m<"/"1)))"*
_"1)"/("1):Y"+\'Y*+
]
{,}$0=
```
No bonuses apply.
Try it online: [sample run](http://cjam.aditsu.net/#code=ri%0A%5B%0A%20%20%20%20%5B'X%5C2b1%3Ee%60%7B~%7B%221)*)%22*%7D%7B_(%7B(')*1%5C%22m%3C%22%7D%7B%221)*%22*%7D%3F%7D%3F%7D%2F%5Ds%0A%20%20%20%20%22X1)*%22%2F%221)%22*%0A%20%20%20%20%221)1)*%22%2F%221)))%22*%0A%20%20%20%20%22X1)m%3C%22%2F%221)))%22*%0A%20%20%20%20_%221)%22%2F(%221)%3AY%22%2B%5C'Y*%2B%0A%5D%0A%7B%2C%7D%240%3D&input=60) | [score calculator](http://cjam.aditsu.net/#code=1000%2C%3A)%5B%7B%5B%0A%20%20%20%20%5B'X%5C2b1%3Ee%60%7B~%7B%221)*)%22*%7D%7B_(%7B(')*1%5C%22m%3C%22%7D%7B%221)*%22*%7D%3F%7D%3F%7D%2F%5Ds%0A%20%20%20%20%22X1)*%22%2F%221)%22*%0A%20%20%20%20%221)1)*%22%2F%221)))%22*%0A%20%20%20%20%22X1)m%3C%22%2F%221)))%22*%0A%20%20%20%20_%221)%22%2F(%221)%3AY%22%2B%5C'Y*%2B%0A%5D%7B%2C%7D%240%3D%2C%7D%2F%5D%3A%2Be-3) | [verification](http://cjam.aditsu.net/#code=1000%2C%3A)_%5B%7B%5B%0A%20%20%20%20%5B'X%5C2b1%3Ee%60%7B~%7B%221)*)%22*%7D%7B_(%7B(')*1%5C%22m%3C%22%7D%7B%221)*%22*%7D%3F%7D%3F%7D%2F%5Ds%0A%20%20%20%20%22X1)*%22%2F%221)%22*%0A%20%20%20%20%221)1)*%22%2F%221)))%22*%0A%20%20%20%20%22X1)m%3C%22%2F%221)))%22*%0A%20%20%20%20_%221)%22%2F(%221)%3AY%22%2B%5C'Y*%2B%0A%5D%7B%2C%7D%240%3D~%7D%2F%5D%3D)
### Example runs
```
1 X
2 1)
3 1))
4 1)))
5 1))))
6 1))1)*
7 1))1)*)
8 X1))m<
9 1)))1)*)
10 1))))1)*
11 1))))1)*)
12 1))1)m<
13 1))1)*1)*)
14 1))1)*)1)*
15 1))1)*)1)*)
16 X1)))m<
17 X1))m<1)*)
18 1)))1)*)1)*
19 1)))1)*)1)*)
20 1))))1)m<
```
```
981 1):Y)Y*)Y*)Y*Y*)Y*Y*)Y*Y*)
982 1):Y)Y*)Y*)Y*Y*)Y*Y*)Y*)Y*
983 1):Y)Y*)Y*)Y*Y*)Y*Y*)Y*)Y*)
984 1):Y)Y*)Y*)Y*Y*)Y*)Y)m<
985 1):Y)Y*)Y*)Y*Y*)Y*)Ym<Y*)
986 1):Y)Y*)Y*)Y*Y*)Y*)Y*Y*)Y*
987 1):Y)Y*)Y*)Y*Y*)Y*)Y*Y*)Y*)
988 1):Y)Y*)Y*)Y*Y*)Y*)Y*)Ym<
989 1):Y)Y*)Y*)Y*Y*)Y*)Y*)Y*Y*)
990 1):Y)Y*)Y*)Y*Y*)Y*)Y*)Y*)Y*
991 1):Y)Y*)Y*)Y*Y*)Y*)Y*)Y*)Y*)
992 1):Y)Y*)Y*)Y*)Y)))m<
993 1):Y)Y*)Y*)Y*)Y))m<Y*)
994 1):Y)Y*)Y*)Y*)Y)m<Y*)Y*
995 1):Y)Y*)Y*)Y*)Y)m<Y*)Y*)
996 1):Y)Y*)Y*)Y*)Ym<Y*)Ym<
997 1):Y)Y*)Y*)Y*)Ym<Y*)Y*Y*)
998 1):Y)Y*)Y*)Y*)Ym<Y*)Y*)Y*
999 1):Y)Y*)Y*)Y*)Ym<Y*)Y*)Y*)
1000 1):Y)Y*)Y*)Y*)Y*Y*)Y)m<
```
[Answer]
# [ß](https://github.com/minxomat/-S-)/BrainFuck, 34.201 points
### [ß](https://github.com/minxomat/-S-) source (194B):
```
E='++[------>+<]>++'°\c[1]<0°{E&='.'µA=ß"-ß°°c[1]),'')µE&='+++'°/B=1°(A[0]°\A[B]='.'°{µE&='--.++'°]E&=ß~A'+',A[B])&'.'&ß~A'-',A[B])°}°)°'ß"&E,'+-')+ß"&E,'-+')>0µE=ß"'ß"'E,'-+',''),'+-','')°!€E)
```
If someone is interested, I'll add an explanation. The BF output is pretty optimized already, but I guess I could use the remaining 318B of ß code to implement
* a loop-nesting-optimization,
* more 8bit overflow shortcuts,
* ~~operator collision removal~~.
### Samples:
Running in windows:
```
$ sharps encode.ss 42
++[------>+<]>+++++++++.--.--
$ sharps encode.ss -42
++[------>+<]>++.+++++++.--.--
$ sharps encode.ss 1.427
++[------>+<]>++++++.---.++++++.--.+++++.-------
$ sharps encode.ss -946.427
++[------>+<]>++.++++++++++++.-----.++.--------.++++++.--.+++++.-------
```
Running in linux:
```
$ WINEDEBUG=-all wine sharps source.ss -4.72
++[------>+<]>++.+++++++.------.+++++++++.-----.--
```
Validate in the [online BF interpreter](http://brainfuck.tk).
### Scores:
1. Base average `= 37.495`.
2. Decimal average `= 60.959 * 0.5 = ~30.48`.
3. Negative avg. `= 38.4765234765235 * 0.9 = ~34.629`
4. Avg of the above, final score `= (37.495 + 30.48 + 34.629)/3 = 34.201`.
[Answer]
# Ruby/Ruby, 29.77885
31.873\*0.9 (negative) 30.872 (positive).
Basic strategy is symmetrical base 3 representation ("balanced ternary"), ie when the digits are `-1,0,1` instead of `0,1,2`
```
#function
f=->n{m=n
a='0'
7.times{|i|
r=m%3;r-=r/2*3
m=(m-r)/3
#produce expression: replace 0 with (0*x+-1)
#only add 0*x if there are higher base 3 digits to follow.
#only add (..+-1) if the current base 3 digit is nonzero.
a.sub!('0',['','(','('][r]+(m.abs>0?'0*x':'')+['','+1)','-1)'][r])
}
#tidy up expression
a.sub!('(-1)*','-') #remove internal (-1)*
a.sub!('(+1)*','') #remove internal (+1)*
a[-1]==')' && a=a[1..-2] #remove unnecessary global brackets
a.sub!('x','(x=1+1+1)') #find the first x and define it as 1+1+1=3
#special cases for small numbers
n.abs<8 && a=n==0?'0':['','1'+'+1'*(n-1).abs,'-1'*n.abs][n<=>0]
a
}
#call like this
(1..1000).each{|p|
b=f.call(p)
puts b
```
Here's the output from 0 to 40 before cleanup
```
(+1)
((+1)*x-1)
(+1)*x
((+1)*x+1)
(((+1)*x-1)*x-1)
((+1)*x-1)*x
(((+1)*x-1)*x+1)
((+1)*x*x-1)
(+1)*x*x
((+1)*x*x+1)
(((+1)*x+1)*x-1)
((+1)*x+1)*x
(((+1)*x+1)*x+1)
((((+1)*x-1)*x-1)*x-1)
(((+1)*x-1)*x-1)*x
((((+1)*x-1)*x-1)*x+1)
(((+1)*x-1)*x*x-1)
((+1)*x-1)*x*x
(((+1)*x-1)*x*x+1)
((((+1)*x-1)*x+1)*x-1)
(((+1)*x-1)*x+1)*x
((((+1)*x-1)*x+1)*x+1)
(((+1)*x*x-1)*x-1)
((+1)*x*x-1)*x
(((+1)*x*x-1)*x+1)
((+1)*x*x*x-1)
(+1)*x*x*x
((+1)*x*x*x+1)
(((+1)*x*x+1)*x-1)
((+1)*x*x+1)*x
(((+1)*x*x+1)*x+1)
((((+1)*x+1)*x-1)*x-1)
(((+1)*x+1)*x-1)*x
((((+1)*x+1)*x-1)*x+1)
(((+1)*x+1)*x*x-1)
((+1)*x+1)*x*x
(((+1)*x+1)*x*x+1)
((((+1)*x+1)*x+1)*x-1)
(((+1)*x+1)*x+1)*x
((((+1)*x+1)*x+1)*x+1)
```
And after cleanup
```
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
(x=1+1+1)*x-1
(x=1+1+1)*x
(x=1+1+1)*x+1
((x=1+1+1)+1)*x-1
((x=1+1+1)+1)*x
((x=1+1+1)+1)*x+1
(((x=1+1+1)-1)*x-1)*x-1
(((x=1+1+1)-1)*x-1)*x
(((x=1+1+1)-1)*x-1)*x+1
((x=1+1+1)-1)*x*x-1
((x=1+1+1)-1)*x*x
((x=1+1+1)-1)*x*x+1
(((x=1+1+1)-1)*x+1)*x-1
(((x=1+1+1)-1)*x+1)*x
(((x=1+1+1)-1)*x+1)*x+1
((x=1+1+1)*x-1)*x-1
((x=1+1+1)*x-1)*x
((x=1+1+1)*x-1)*x+1
(x=1+1+1)*x*x-1
(x=1+1+1)*x*x
(x=1+1+1)*x*x+1
((x=1+1+1)*x+1)*x-1
((x=1+1+1)*x+1)*x
((x=1+1+1)*x+1)*x+1
(((x=1+1+1)+1)*x-1)*x-1
(((x=1+1+1)+1)*x-1)*x
(((x=1+1+1)+1)*x-1)*x+1
((x=1+1+1)+1)*x*x-1
((x=1+1+1)+1)*x*x
((x=1+1+1)+1)*x*x+1
(((x=1+1+1)+1)*x+1)*x-1
(((x=1+1+1)+1)*x+1)*x
(((x=1+1+1)+1)*x+1)*x+1
```
[Answer]
## Ceylon/Ceylon, ~~49.86~~ 40.95 points
The third version uses Ceylon 1.2 for the generator and 509 bytes of code:
`import ceylon.language{S=String,I=Integer,e=expand}S q(I n)=>n==0then"0"else(n<0then"-"+p(-n,"-")else p(n,"+"));variable Map<[I,S],S>c=map{};S p(I n,S s){S v=c[[n,s]]else(n<8then s.join([1].repeat(n)))else(let(a="+-".replace(s,""))e(e{for(x in 2..8)let(l=(n^(1.0/x)).integer){for(r in l:2)if(r>1)let(w=r^x){if(w-n<n)"("+p(r,"+")+")^("+p(x,"+")+")"+(w<n then s+p(n-w,s)else(n<w then a+p(w-n,a)else""))}}}).reduce<S>((x,y)=>x.size<y.size then x else y))else"";c=[n,s]in c then c else map{[n,s]->v,*c};return v;}`
It gets down to 35.22 points, but I won't put this in the title line because Celyon 1.2 only was published at october 29. I don't think I would be able to implement this algorithm in Ceylon 1.1 in this size.). More details down there, here I'll describe the second version. (The first version can be seen in the history – it supported only positive numbers, but did fit into 256 bytes.)
### Second version
Now the second version, which supports negative integers (and 0), and generally creates a bit shorter output by using in addition `-`.
(This version actually uses the permitted length, the first one tried to stay under 256 bytes instead of 512.)
```
String proof(Integer n) {
if (n == 0) { return "0"; }
if (n < 0) { return "-" + p(-n, "-"); }
return p(n, "+");
}
String p(Integer n, String sign) {
if (n < 9) {
return sign.join([1].repeat(n));
}
value anti = (sign == "+") then "-" else "+";
value root = ((n^0.5) + 0.5).integer;
return "(" + p(root, "+") + ")^(1+1)" +
( (root^2 < n) then sign + p(n - root^2, sign) else
((n < root^2) then anti + p(root^2 - n, anti) else ""));
}
```
Code has length 487, so there is still some space for more optimizations later. (There are also lots of reserves in form of whitespace and long variable names.)
The scoring:
```
Total positive: 42652
Average positive:42.652
Total negative: 43653
Average negative: 43.60939060939061
With bonus:39.24845154845155
Overall score: 40.95022577422577
```
Some sample outputs:
```
27: 21: (1+1+1+1+1)^(1+1)+1+1
28: 23: (1+1+1+1+1)^(1+1)+1+1+1
29: 25: (1+1+1+1+1)^(1+1)+1+1+1+1
30: 27: (1+1+1+1+1)^(1+1)+1+1+1+1+1
31: 29: (1+1+1+1+1+1)^(1+1)-1-1-1-1-1
32: 27: (1+1+1+1+1+1)^(1+1)-1-1-1-1
33: 25: (1+1+1+1+1+1)^(1+1)-1-1-1
34: 23: (1+1+1+1+1+1)^(1+1)-1-1
-27: 22: -(1+1+1+1+1)^(1+1)-1-1
-28: 24: -(1+1+1+1+1)^(1+1)-1-1-1
-29: 26: -(1+1+1+1+1)^(1+1)-1-1-1-1
-30: 28: -(1+1+1+1+1)^(1+1)-1-1-1-1-1
-31: 30: -(1+1+1+1+1+1)^(1+1)+1+1+1+1+1
-32: 28: -(1+1+1+1+1+1)^(1+1)+1+1+1+1
-33: 26: -(1+1+1+1+1+1)^(1+1)+1+1+1
-34: 24: -(1+1+1+1+1+1)^(1+1)+1+1
993: 65: ((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
994: 63: ((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
995: 61: ((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
996: 59: ((1+1+1+1+1+1)^(1+1)-1-1-1-1)^(1+1)-(1+1+1+1+1)^(1+1)-1-1-1
997: 57: ((1+1+1+1+1+1)^(1+1)-1-1-1-1)^(1+1)-(1+1+1+1+1)^(1+1)-1-1
998: 55: ((1+1+1+1+1+1)^(1+1)-1-1-1-1)^(1+1)-(1+1+1+1+1)^(1+1)-1
999: 53: ((1+1+1+1+1+1)^(1+1)-1-1-1-1)^(1+1)-(1+1+1+1+1)^(1+1)
1000: 55: ((1+1+1+1+1+1)^(1+1)-1-1-1-1)^(1+1)-(1+1+1+1+1)^(1+1)+1
-993: 66: -((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
-994: 64: -((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
-995: 62: -((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
-996: 60: -((1+1+1+1+1+1)^(1+1)-1-1-1-1)^(1+1)+(1+1+1+1+1)^(1+1)+1+1+1
-997: 58: -((1+1+1+1+1+1)^(1+1)-1-1-1-1)^(1+1)+(1+1+1+1+1)^(1+1)+1+1
-998: 56: -((1+1+1+1+1+1)^(1+1)-1-1-1-1)^(1+1)+(1+1+1+1+1)^(1+1)+1
-999: 54: -((1+1+1+1+1+1)^(1+1)-1-1-1-1)^(1+1)+(1+1+1+1+1)^(1+1)
-1000: 56: -((1+1+1+1+1+1)^(1+1)-1-1-1-1)^(1+1)+(1+1+1+1+1)^(1+1)-1
1: 1: 1
2: 3: 1+1
3: 5: 1+1+1
4: 7: 1+1+1+1
5: 9: 1+1+1+1+1
6: 11: 1+1+1+1+1+1
7: 13: 1+1+1+1+1+1+1
8: 15: 1+1+1+1+1+1+1+1
9: 13: (1+1+1)^(1+1)
10: 15: (1+1+1)^(1+1)+1
0: 1: 0
-1: 2: -1
-2: 4: -1-1
-3: 6: -1-1-1
-4: 8: -1-1-1-1
-5: 10: -1-1-1-1-1
-6: 12: -1-1-1-1-1-1
-7: 14: -1-1-1-1-1-1-1
-8: 16: -1-1-1-1-1-1-1-1
-9: 14: -(1+1+1)^(1+1)
-10: 16: -(1+1+1)^(1+1)-1
```
As you can see, the negative ones are always one byte (the leading `-`) longer than the corresponding positive ones.
The base idea is the same as the previous program: find a square near our target number, and represent its root and the remainder recursively.
But now we allow our square being also some larger than the target number, which then makes the remainder negative.
(The `+0.5` can be changed to a different constant to tweak the algorithm, but it seems that I already did hit the optimum here – both 0.4 and 0.6 give worse results.)
To make negative values negative (and otherwise have the same structure as the positive ones, we pass the operator `sign` to our recursive function `p` – that is either `"+"` or `"-"`. We can use that for the joiner in the trivial cases (i.e. n < 9) as well as for the remainder if it's positive, and use the opposite sign for the remainder if it is negative.
The `proof` function handles the initial sign (with a special case for 0), the `p` function does the actual work, with recursion.
### Third version, for Ceylon 1.2
```
import ceylon.language { S=String, I=Integer,e=expand }
// output a base-proof Ceylon expression for an integer
// (i.e. using only 0 and 1 as digits).
//
// Question: http://codegolf.stackexchange.com/q/58084/2338
// My Answer: http://codegolf.stackexchange.com/a/58122/2338
//
// The goal is to produce an expression as short as possible, with
// the code staying under 512 bytes in length.
//
// This approach is to represent a positive integer as a square
// of a positive integer plus some remainder (where the remainder
// can be negative), and for negative integers replace the + on the
// outer level by -.
S q(I n) =>
n == 0 then "0"
else (n < 0 then "-" + p(-n, "-")
else p(n, "+"));
// cache for values of p
variable Map<[I, S],S> c = map { };
// Transforms a positive number into a base-proof term, using
// the given sign for the summation on the outer level.
S p(I n, S s) {
S v =
// look into the cache
c[[n, s]] else (
// hard-code small numbers
n < 8 then s.join([1].repeat(n)))
else
// do the complicated stuff
(let (a = "+-".replace(s,""))
e(e {
for (x in 2..8) // try these exponents
let (l = (n ^ (1.0 / x)).integer) // \[ sqrt[exp]{n} \] in LaTeX
{ for (r in l:2) // lowerRoot, lowerRoot + 1
if (r > 1)
let (w = r ^ x)
{ if (w-n < n) // avoid recursion to larger or same number
// format the string as r^x + (n-w)
"(" + p(r, "+") + ")^(" + p(x, "+") + ")" +
(w < n then s + p(n - w, s)
else (n < w then a + p(w - n, a)
else ""))
} } })
// and now find the shortest formatted string
.reduce<S>((x, y) => x.size < y.size then x else y))
// this should never happen, but we can't tell the compiler
// that at least some of the iterables are non-empty due to the if clause.
else "";
// this builds a new cache in each step – quite wasteful,
// as this also happens when the value was found in the cache,
// but we don't have more characters remaining.
//// c = map { [n, s] -> v, *c };
///better way:
c = [n,s] in c then c else map{[n,s]->v, *c};
return v;
}
```
The golfed version (i.e. comments and whitespace removed) is posted at the top, at exactly 509 bytes of code.
This uses the same base principle as the second version, but instead of just squares, it also tries to use higher powers of numbers (trying exponents from 2 to 8), and uses the shortest result. It also caches the results, as otherwise this would be unacceptably slow for larger numbers with many recursive calls.
Scoring:
```
Total positive: 36622
Average positive: 36.622
Total negative: 37623
Average negative: 37.58541458541458
With bonus:33.826873126873124
Overall score: 35.22443656343656
```
The big indented construct in the middle are three nested iterable comprehensions, the inner two inside a let expression. These are then unnested using the expand function twice, and the `reduce` function finds the shortest of those strings.
I've filed a [feature request](https://github.com/ceylon/ceylon-spec/issues/1458#issuecomment-152881872) to be able to do this in a single comprehension.
Inside the comprehension, we are building a string from the root `r`, the exponent `x` and the remainder (`n-w` or `w-n`).
The `let` expression and the `map` function are new in Ceylon 1.2. `map` could have been replaced by `HashMap` (which would have needed more characters for the import, although it would probably be even faster, as I wouldn't build the map new for each new entry). The `let` expressions like `let (w = r ^ x)` could have been replaced by using an `if` clause like `if(exists w = true then r ^ x)` (and then I wouldn't have needed the two `expand` calls either), but this would still be a bit longer, not fitting inside the 511 allowed bytes.
Here the sample outputs corresponding to those selected above, all of them except the really small numbers are shorter:
```
27: 15: (1+1+1)^(1+1+1)
28: 17: (1+1+1)^(1+1+1)+1
29: 19: (1+1+1)^(1+1+1)+1+1
30: 21: (1+1)^(1+1+1+1+1)-1-1
31: 19: (1+1)^(1+1+1+1+1)-1
32: 17: (1+1)^(1+1+1+1+1)
33: 19: (1+1)^(1+1+1+1+1)+1
34: 21: (1+1)^(1+1+1+1+1)+1+1
-27: 16: -(1+1+1)^(1+1+1)
-28: 18: -(1+1+1)^(1+1+1)-1
-29: 20: -(1+1+1)^(1+1+1)-1-1
-30: 22: -(1+1)^(1+1+1+1+1)+1+1
-31: 20: -(1+1)^(1+1+1+1+1)+1
-32: 18: -(1+1)^(1+1+1+1+1)
-33: 20: -(1+1)^(1+1+1+1+1)-1
-34: 22: -(1+1)^(1+1+1+1+1)-1-1
993: 39: ((1+1+1)^(1+1)+1)^(1+1+1)-1-1-1-1-1-1-1
994: 37: ((1+1+1)^(1+1)+1)^(1+1+1)-1-1-1-1-1-1
995: 35: ((1+1+1)^(1+1)+1)^(1+1+1)-1-1-1-1-1
996: 33: ((1+1+1)^(1+1)+1)^(1+1+1)-1-1-1-1
997: 31: ((1+1+1)^(1+1)+1)^(1+1+1)-1-1-1
998: 29: ((1+1+1)^(1+1)+1)^(1+1+1)-1-1
999: 27: ((1+1+1)^(1+1)+1)^(1+1+1)-1
1000: 25: ((1+1+1)^(1+1)+1)^(1+1+1)
-993: 40: -((1+1+1)^(1+1)+1)^(1+1+1)+1+1+1+1+1+1+1
-994: 38: -((1+1+1)^(1+1)+1)^(1+1+1)+1+1+1+1+1+1
-995: 36: -((1+1+1)^(1+1)+1)^(1+1+1)+1+1+1+1+1
-996: 34: -((1+1+1)^(1+1)+1)^(1+1+1)+1+1+1+1
-997: 32: -((1+1+1)^(1+1)+1)^(1+1+1)+1+1+1
-998: 30: -((1+1+1)^(1+1)+1)^(1+1+1)+1+1
-999: 28: -((1+1+1)^(1+1)+1)^(1+1+1)+1
-1000: 26: -((1+1+1)^(1+1)+1)^(1+1+1)
1: 1: 1
2: 3: 1+1
3: 5: 1+1+1
4: 7: 1+1+1+1
5: 9: 1+1+1+1+1
6: 11: 1+1+1+1+1+1
7: 13: 1+1+1+1+1+1+1
8: 13: (1+1)^(1+1+1)
9: 13: (1+1+1)^(1+1)
10: 15: (1+1+1)^(1+1)+1
0: 1: 0
-1: 2: -1
-2: 4: -1-1
-3: 6: -1-1-1
-4: 8: -1-1-1-1
-5: 10: -1-1-1-1-1
-6: 12: -1-1-1-1-1-1
-7: 14: -1-1-1-1-1-1-1
-8: 14: -(1+1)^(1+1+1)
-9: 14: -(1+1+1)^(1+1)
-10: 16: -(1+1+1)^(1+1)-1
```
For example, now we have 1000 = (3^2 + 1)^3, instead of 1000 = (6^2-4)^2-5^2+1.
[Answer]
# Ruby/dc, ~~20.296~~ ~~18.414~~ 16.968
Dynamic programming! Defines a list of functions that, given a dc instruction, return a new expression and the numeric value of that expression. Then, starting with `1` prefined, it builds a list of all reachable values up to and including the wanted value.
### edit:
Added a function for *n-1* and made it run the algorithm through multiple passes. It seems to need 7 passes to stabilize. Had to shorten some variable names to stay within 512 bytes.
### edit 2:
Added functions for *n(n-1)*, *n(n+1)* and *n^3* while I was at it. Shortened the code some more, landing at exactly 512 bytes.
```
N = gets.to_i
fns = [
->(n,s){[n-1, s+'1-']},
->(n,s){[n+1, s+'1+']},
->(n,s){[n*2, s+'d+']},
->(n,s){[n*3, s+'dd++']},
->(n,s){[n*~-n, s+'d1-*']},
->(n,s){[n*n, s+'d*']},
->(n,s){[n*-~n, s+'d1+*']},
->(n,s){[n*n*n, s+'dd**']},
]
lst = []*(N+1)
lst[0..2] = %w[0 1 1d+]
loop do
prev = lst.dup
(1..N).each do |n|
fns.each do |f|
m,s = f[n, lst[n]]
lst[m] = s if m <= N && (lst[m].nil? || lst[m].size > s.size)
end
end
break if lst == prev
end
puts lst[N]
```
### Generated numbers:
Output consists entirely of five different characters: `1` pushes the value 1 on the stack; `d` duplicates the top of the stack; `+`, `-`, and `*` pops the two top values and pushes their sum, difference, and product, respectively. Each generated expression adds only one value to the stack after execution.
```
1: 1
2: 1d+
3: 1dd++
4: 1d+d+
5: 1d+d+1+
6: 1d+dd++
7: 1d+dd++1+
8: 1d+dd**
9: 1dd++d*
10: 1d+d+1+d+
11: 1d+d+1+d+1+
12: 1dd++d1+*
13: 1dd++d1+*1+
14: 1d+dd++1+d+
15: 1d+d+d*1-
16: 1d+d+d*
17: 1d+d+d*1+
18: 1dd++d*d+
19: 1dd++d*d+1+
20: 1d+d+d1+*
21: 1d+d+d1+*1+
22: 1d+d+1+d+1+d+
23: 1d+dd**dd++1-
24: 1d+dd**dd++
25: 1d+d+1+d*
```
...
```
989: 1d+d+d*d+d1-*1-1-1-
990: 1d+d+d*d+d1-*1-1-
991: 1d+d+d*d+d1-*1-
992: 1d+d+d*d+d1-*
993: 1d+d+d*d+d1-*1+
994: 1d+d+d*d+d1-*1+1+
995: 1d+d+d*d+d1-*1+1+1+
996: 1d+d+1+dd**d+1-d+d+
997: 1d+d+1+d+dd**1-1-1-
998: 1d+d+1+d+dd**1-1-
999: 1d+d+1+d+dd**1-
1000: 1d+d+1+d+dd**
```
[Answer]
# Python 2.6, ~~78.069~~ - 66.265 points
Submitting my answer for what it's worth (not a lot in this case ... but clearly demonstrating that for this challenge it's not enough to simply think of composing the output as a sum of bit-shifted values; when taken into account that no digits outside of 0 or 1 may appear in the output). I might come back later with a different way of generating output.
The code itself is not too long (176 characters):
```
def f(a):return'+'.join(('(1<<%s)'%['0','+'.join('1'*x)][x>0]).replace('(1<<0)','1')for x in[i for i,e in enumerate(bin(a)[::-1][:-2])if int(e)])
print"".join(f(int(input())))
```
It generates correct but verbose output:
```
17
1+(1<<1+1+1+1)
800
(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)
```
Snippet that calculates the score:
```
def f(a):return'+'.join(('(1<<%s)'%['0','+'.join('1'*x)][x>0]).replace('(1<<0)','1')for x in[i for i,e in enumerate(bin(a)[::-1][:-2])if int(e)])
print sum(len("".join(f(i)))for i in range(1000))
```
] |
[Question]
[
This question is inspired by [this awesome answer](https://codegolf.stackexchange.com/a/17103/106710).
The challenge is to write a program or function which takes in a positive integer, and outputs "Happy new year to you" or a slight variation thereof, such that the character codes of that string add up to the inputted number. The space counts towards the sum of character codes too.
The case does not matter at all; you may output `HappY New yEAR` or something so long as it satisfies the specifications below.
The specifications are as follows:
The outputted string must contain `happy new year`. As stated above, the case does not matter.
The `happy new year` component of the string may optionally be preceded by `have a` , again in any case. However, there must be a space before `happy` if the string starts with `have a` .
The `happy new year` string may optionally be followed by `to you`, again in any case. The space before `to` is mandatory.
Note that `Have a happy new year to you`, while not grammatically correct, is an acceptable output for the purposes of this challenge.
Finally, at the very end of the string, any number of exclamation marks can be outputted.
In summary, the outputted string must satisfy the following regular expression:
```
/^(have a )?happy new year( to you)?!*$/i
```
You may assume while writing your program or function that you will only be given numbers for which it is possible to construct a "happy new year" string.
I won't allow outputting in array or list format because it defeats the purpose of the challenge.
If there are multiple solutions, feel free to output any one of them, any subset of them, or all of them.
As this challenge is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code, measured in bytes, wins.
## Test cases
```
2014
-> Happy new year to you!
1995
-> HAPPY NEW YEAR TO You!!!!!!!!!!!!!!
989
-> HAPPY NEW YEAR
1795
-> Have a HAPPY new year!
2997
-> Have a HAppY new year to YOU!!!!!!!!!!!!!!!!!!!
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~159~~ 148 bytes
This code builds the string without resorting to brute force.
```
y=>Buffer((s="happy new year",r=n=y%33)>17&n<20?(n-=7,r-=5,"have a "+s):n<18?s+" to you":(n-=20,s)).map(c=>c-32*(c>32&&n-->0))+'!'.repeat(y/33+r-61)
```
[Try it online!](https://tio.run/##LdBLTsMwEIDhqwyRaGximzwoeVCnAsQpqi4s16GgYlt2WuQ7ILFhCffgPL0ARwguYvMtZn5ppHkWB@Gle7Ij1WajpoFPgfd3@2FQDiHPk62wNoBWrxCUcAlxXPNwXlW4L@qZXpT5EmnKa@Ion5NYHxQISDKPO70omqXPEhgNBLNPulNY5sRjzF6ERZL3klblBZJ9Vc5mmtI@xzhLz1LmlFViROGyqjJHrws83aygbVoCRd3Oo@2/zZ9xXubFVbRta1izwbgHIbcoAO9BGu3NTrGdeUQeOAwoYAIrxphfx0ObvVQIWQISn2oLGUgmt8Ldx3fcjii2edxwCLCE9Of7/fj5EU2hg/T49ZZiPP0C "JavaScript (Node.js) – Try It Online")
### How?
Let \$y\$ be the input year.
Because we can add \$k\times33,k\ge0\$ to the result by adding as many trailing exclamation marks as we want, we need to focus on \$n=y\bmod33\$.
The method that is used here can be split into the 4 following cases:
* If \$n\le17\$:
+ We use the base string `"happy new year to you"` and put \$n\$ characters in upper case, for a base score of \$2013-32n\$.
+ We add \$\lfloor y/33\rfloor+n-61\$ exclamation marks.
+ The final score is:
$$2013-32n+33\times(\lfloor y/33\rfloor+n-61)\\=33\times\lfloor y/33\rfloor+n=33\times\lfloor y/33\rfloor+(y \bmod 33)=y$$
* If \$n=18\$:
+ We use the base string `"HAVE A HAPPY New year"`, for a base score of \$1602\$.
+ We add \$\lfloor y/33\rfloor-48\$ exclamation marks.
+ The final score is:
$$1602+33\times(\lfloor y/33\rfloor-48)\\=33\times\lfloor y/33\rfloor+18=33\times\lfloor y/33\rfloor+(y \bmod 33)=y$$
* If \$n=19\$:
+ We use the base string `"HAVE A HAPPY NEw year"`, for a base score of \$1570\$.
+ We add \$\lfloor y/33\rfloor-47\$ exclamation marks.
+ The final score is:
$$1570+33\times(\lfloor y/33\rfloor-47)\\=33\times\lfloor y/33\rfloor+19=33\times\lfloor y/33\rfloor+(y \bmod 33)=y$$
* If \$n\ge20\$, we use the base string `"happy new year"` and put \$n-20\$ characters in upper case, for a base score of \$2013-32n\$.
+ We add \$\lfloor y/33\rfloor+n-61\$ exclamation marks.
+ The computation of the final score is similar to the 1st case.
Obviously, it's not possible to add a negative number of exclamation marks, which is why only some years before 1981 have a happy new year string ([as pointed out by @AnttiP](https://codegolf.stackexchange.com/questions/242683/happy-new-year-string-builder#comment546658_242683)).
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 130 bytes
```
f=(n,s='',...a)=>n|!/^(have a )?happy new year( to you)?!*$/i.test(s)?f(...a,...[...f+f].map(_=>(a=!a)?s+Buffer([i++]):n-i,i=2)):s
```
[Try it online!](https://tio.run/##FczRCsIgFIDhV1EIdk5uDrocOKHXGCsOpcwglekWQu9u7eK//P4X7ZQeq4u58@FparUKfJtU07RSSkI1@i/vb7DQbhgx1AvFWJg3H1YMrcByYCVsqPn51DuZTcqQUFs49LGY/llhZ/mmCHc1AilOqJO4btaaFSYnxIyD71zr1AVxSLX@AA "JavaScript (Node.js) – Try It Online")
Run out of memory on any computer as it use >128^14 args, but theoretically it works
[Answer]
# Excel, 219 bytes
```
=LET(r,MOD(A1,33),m,(r<20)+(r<18)+1,s,REPT("HAVE A ",m=2)&"HAPPY NEW YEAR"&REPT(" TO YOU",m=3),a,INDEX({989;1410;1469},m),b,MOD(a-r,33),d,b+SUM((b>{5,8,12,14})*1),LOWER(LEFT(s,d))&MID(s,d+1,26)&REPT("!",(A1-a-b*32)/33))
```
Inspired by @Arnauld 's answer. One of the ingenious things about his solution is that the numbers of cases that start with "HAVE A" is so small, that a different test to account for the spaces is not needed.
[Link to Spreadsheet](https://1drv.ms/x/s!AkqhtBc2XEHJnhvn64_z-8Ny8jwi?e=AM7Jrc)
`=LET(r,MOD(A1,33),` Set r = \$n \mod 33\$.
`m,(r<20)+(r<18)+1,` Set mode. Mode 1 \$> 19\$; Mode 2 \$[18, 19]\$; mode 3 \$< 18\$.
`s,REPT("HAVE A ",m=2)&"HAPPY NEW YEAR"&REPT(" TO YOU",m=3),` if mode 2, prepend "HAVE A "; if mode 3, append " TO YOU".
`a,INDEX({989;1410;1469},m),` Sum of character values for base string
`b,MOD(a-r,33),` distance of base string from \$n \mod 33\$
`d,b+SUM((b>{5,8,12,14})*1),` portion of base string to be converted to lower case. The numbers in the brackets account for the spaces.
`LOWER(LEFT(s,d))&MID(s,d+1,26)&REPT("!",(A1-a-b*32)/33))` return the string with the appropriate number of characters converted to lower case plus the number of "!" to reach the target number.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 83 bytes
```
NθF²F²«≔⁺⁺×ιHAVE A ”&±″/⍘=↧5"SA”×κ TO YOUκF⊕Lκ⊞υ⭆κ⎇‹νλμ↧μ»W⬤υ⁻θΣEκ℅μ≔⁺υ!υ⊟Φυ⁼θΣEι℅λ
```
[Try it online!](https://tio.run/##VZDBToQwEIbPy1OMnKYJJobrnjhg3GR3aRQ1HCtboaEt0FI3xvjsOCwa9dJpZub/5p@pW@HqXuh53tkhTMdgXqTDkW2j194Bpgx@4ke0ybxXjUWug1@fUhnpUSUQ32VPOWQQs8uf8wqO@TNUeXa/pNa@jmpQFlAVjzGjbEdTNhf8ztZOGmknecK9tM3UYscYAx58iyGBh8kp2xzEsDBK6axw79ToPdoENKFMAvv@LF0tvERDUkJ/RudWaQmYab1ADsqS5ZFoweA3q3AnZYVeJTTw74Ykia8W94FgnAxMyPsBb5We6ERUzccg9D@i@iXqlci285zepOl8/aa/AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ
```
Input the desired year.
```
F²F²«
```
Loop over the possibilities of prefixes and suffixes.
```
≔⁺⁺×ιHAVE A ”&±″/⍘=↧5"SA”×κ TO YOUκ
```
Take the compressed string `HAPPY NEW YEAR` and optionally prefix or suffix it as appropriate.
```
F⊕Lκ⊞υ⭆κ⎇‹νλμ↧μ
```
Generate more than enough permutations of the case of the characters in the strings. (In particular, unnecessary extra copies are created for each space in the string, because it's golfer not to filter them out.)
```
»W⬤υ⁻θΣEκ℅μ
```
While none of the strings has the desired character sum...
```
≔⁺υ!υ
```
... append an `!` to each string.
```
⊟Φυ⁼θΣEι℅λ
```
Output one of the strings with the desired character sum.
74 bytes for a version that's too slow for TIO:
```
NθFθF²F²«≔⁺⁺×κHAVE A ”&±″/⍘=↧5"SA”×λ TO YOUλF⊕Lλ⊞υ⁺⭆λ⎇‹ξμν↧ν×ι!»⊟Φυ⁼θΣEι℅λ
```
[Try it online!](https://tio.run/##RY9LT8MwDIDP668wPTlSkEavO/VQxKSxRqyAegxdaCPStM2DhxC/vbidBDk4lmN/n9N00jWDNPO8t2MMx9i/KIcT2yWvgwO82TJYk@z//k42ufe6tShM9JdQ6V55fOOQ3uVPBeSQsjUXooZj8Qx1kT8spUufoTeoSqjLx5RR1ZBus@L3tnGqVzaoMx6UbUOHhjEGIvoOI4dVdgpO2/ZejguoUs5K90Xd3uMnh554lsNh@FCukV6hZexPrEl8RUry/SSCKAHFMOKtNoF@TfxiitJ4nDicYo@LgkZKd9ZWmnWT5ezmOdtm2Xz9bn4B "Charcoal – Try It Online") with the second `θ` changed to `χ` so it does at least work for some years.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 52 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
“ṭ½IṾFhĿ_)Wẓȷ⁻⁸ẉ»ḲŒP“7dx‘ịK€ŒuƤŻoƊ€Ẏ;þḶ”!xⱮƊẎOS⁼ɗƇ⁸Ḣ
```
A monadic Link accepting a positive integer that yields a list of characters (or 0). Or a full program that prints a valid result (or 0).
[Don't Try it online!](https://tio.run/##AXgAh/9qZWxsef//4oCc4bmtwr1J4bm@RmjEv18pV@G6k8i34oG74oG44bqJwrvhuLLFklDigJw3ZHjigJjhu4tL4oKsxZJ1xqTFu2/GiuKCrOG6jjvDvuG4tuKAnSF44rGuxorhuo5PU@KBvMmXxofigbjhuKL///85ODk "Jelly – Try It Online") (it won't finish)
Rather, see this slightly altered **[test-suite](https://tio.run/##y0rNyan8//9Rw5yHO9ce2uv5cOc@t4wj@@M1wx/umnxi@6PG3Y8adzzc1Xlo98Mdm45OCgAqNE@peNQw4@Hubu9HTWuOTio9tuTo7vxjXUDOw1191of3WRkbP9yx7VHDXMWKRxvXHdsEFPUPftS45@T0Y@0gw3Ys@n90z@F2oPpIEP7/P9rSwlJHwdDc0hRIWkJJCzAJFDcyMDQBkpaW5rEA "Jelly – Try It Online")** which considers fewer possible strings (by using \$\frac{1}{33}\$ as many optional trailing `!`s).
### How?
```
“...»ḲŒP“7dx‘ịK€ŒuƤŻoƊ€Ẏ;þḶ”!xⱮƊẎOS⁼ɗƇ⁸Ḣ - Link: integer, N
“...» - "have a happy new year to you"
Ḳ - split at spaces
ŒP - powerset
“7dx‘ - [55,100,120]
ị - index into -> [["happy", "new", "year"], ["have", "a", "happy", "new", "year"], {"happy", "new", "year", "to", "you"]]
K€ - join each with spaces -> ["happy new year", "have a happy new year", "happy new year to you"]
Ɗ€ - last three links as a monad for each:
ŒuƤ - upper-case prefixes
Ż - prefix with a zero
o - logical OR (the full lower-case)
Ẏ - tighten
Ɗ - last three links as a monad - f(N):
Ḷ - [0..N-1]
”! - '!'
xⱮ - map with times -> ["", "!", "!!", ..., '!'*(N-1)]
;þ - table with concatenate
Ẏ - tighten
⁸ - use N as the right argument of...
Ƈ - filter keep those for which:
ɗ - last three links as a dyad - f(possibles, N):
O - ordinals
S - sum
⁼ - equals N?
Ḣ - head -> valid result or 0 if none exists
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 128 bytes
```
->y{n=y%33
s="HAVE A HAPPY NEW YEAR TO YOU"[n/2==9?0:7,w=21-n/20*7]
w.times{|i|(n=y-s.sum)%33>0&&s[i]=s[i].downcase}
s+?!*n/=33}
```
[Try it online!](https://tio.run/##RY3bCoJAEIbvfYpNKMrW41K2wRheCF2lRAdEvOigoKBJq4ioz24rQd38zDDffP@7ujdDDINsNW0OzZQQgYG4ty8OstHe9jwfHZwr8h37iE4u8t2zGOSqAUB32tbENRi6zHdNMkOhVsoki1jbJd2cu2SmsCpbcKWlzWYsSEIYQ3m@6vxxY1EvsOVuIuUqENIPgU7pCtMNxbrJB4NSM1SyWzHaChQkuISYf@NylIa9QMi/jd9TWOsSIcsvl/644QM "Ruby – Try It Online")
Similar to Arnauld's answer. Some notes on how it works:
* `"HAPPY NEW YEAR".sum % 33` is 32. Converting a letter to lowercase adds 32, reducing the remainder by 1 for each letter down to a minimum of 20 when all 12 letters are in lowercase.
* `"HAVE A HAPPY NEW YEAR".sum % 33` is 24. We convert 5 or 6 letters to lowercase to cover years of remainder 19 and 18.
* `"HAPPY NEW YEAR TO YOU".sum % 33` is 17. We convert 0 to 17 letters to lowercase to cover years of remainder 17 down to 0.
It's a fairly simple approach, avoiding the sophisticated formulas in Arnauld's answer (although it wouldn't work without them being true).
* Select the appropriate substring from `HAVE A HAPPY NEW YEAR TO YOU` as above
* Convert characters from uppercase to lowercase until `(y-s.sum)%33` is zero
* Append `(y-s.sum)/33` exclamation marks
`n` is used in two different ways. First it represents `y%33`. Later it represents `y-s.sum`. The reason for the re-use of `n` is that the second assignment occurs inside a loop and if a new variable were used (implicitly declared) inside the loop, it would not be recognised outside the loop, causing an error.
[Answer]
# Python3, 211 bytes:
```
lambda y:next(f(y,'',s:='happy new year to you'),0)or next(f(y,'','have a '+s))
def f(y,s,j):
if(v:=sum(map(ord,s)))==y:yield s
if v<y:
for i in{(k:=['!',j][j!=''])[0],k[0].upper()}:yield from f(y,s+i,k[1:])
```
[Try it online!](https://tio.run/##VY7RasMgFIbv@xSnV3qojKTbaJX5JFkuHFGqbVQ0ySZjz55ZtkF2c@Dn@/j/E8t0Cf7xHNPq5Ot6U@PboKAIrz8mamhhhLAsJLmoGAt4/Q5FqwRTgBJmgqzBkGArV3PRoIAcMuJu0AbuIDOHYgfW0EXIPI90VJGGNLAqoZRFFKtvA@S7AstLqS6Y2mzB@k96FbIje8Jc37m9JKTHrunZtZ6HOUadKH79FpgUxp/Bg61CK3pcY7J@oo4em/apvvQXW86fN5Gf@Rae/sEj5yfE9Rs)
] |
[Question]
[
While I was writing numbers I noticed after a while that my keyboard had the `Shift` key pressed and blocked and all I wrote was `$%&`-like characters. And even worse, I had been switching between the English and Spanish keyboard layouts so I don't know which one I used for each number.
### Challenge
Given a string containing symbol characters, try to guess which number I wrote. My keyboard produces the following characters for the numbers when the `Shift` is pressed:
```
1234567890
----------
!"·$%&/()= Spanish layout
!@#$%^&*() English layout
```
* The input will be a non-null, non-empty string composed of the symbols above.
* The output will be a single number if the keyboard layout can be inferred from the string (i.e. if the string contains a `@` an English layout was used, and if the string contains a `"` a Spanish layout was used) or if the number is the same for both layouts (i.e. the input is `!$` which translates as `14` for both layouts); otherwise the output will be the two possible numbers for both layouts if it cannot be inferred and the resulting numbers are different.
* The input string will always be written in a single layout. So you don't need to expect `"@` as input.
### Examples
```
Input --> Output
------------------
/() 789 (Spanish layout detected by the use of /)
$%& 456,457 (Layout cannot be inferred)
!@# 123 (English layout detected by the use of @ and #)
()&! 8961,9071 (Layout cannot be inferred)
((·)) 88399 (Spanish layout detected by the use of ·)
!$ 14 (Layout cannot be inferred but the result is the same for both)
!!$$%% 114455 (Layout cannot be inferred but the result is the same for both)
==$" 0042/42 (Spanish layout, if a number starts with 0 you can choose to
omit them in the result or not)
Single character translations:
------------------------------
! 1
" 2
· 3
$ 4
% 5
& 6,7
/ 7
( 8,9
) 9,0
= 0
@ 2
# 3
^ 6
* 8
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so may the shortest code for each language win!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~32~~ 31 bytes
```
O“=!"Ṣ$%&/()“)!@#$%^&*(‘iⱮ€PƇ’Q
```
[Try it online!](https://tio.run/##rZDPSsNAEMbvfYrJvzaRQJM2aZtDoRdvgopHUUiajYkku5JskN6Kl76CgifPRfAkXhV8D/MicZLWmoJSBOewMLs7v@/75pLE8awsD4v5/VgQP14eZKXdVTVsNWEiycp5e08t5rdR8fRY3CyP3hfF/O64fFtgU5anLRH/ilCXXh3ScOTAutSTK5dGWQixO2M5B59wMuXEB28GPCSQZwRYAF2tJaLoFsWyB7plD2vKwWp66lLKOHgEIhqQNCU@zqHFrTmz19@o79OLeLf6BFzqg4QsVWsLYoM1cgam7hhDc4cHVX191lZLWA@O@o7zpxUgALPI6yhfWSzYZPlVHzy8rkgpyfKYQ5TVXeYmBAKWgsd4WLEFWVYU8ZttWpZt/wu7Mx7LYqfh2zCsXtfq/RBfhygAF2ieeCSFjLspz@A64iEYgO@VBZiGjOFSOGudwXZJzYYlUe0tQbdNj2gLU2jwCQ "Jelly – Try It Online")
* -1 bytes thanks to Erik the Outgolfer
---
```
O“!"Ṣ$%&/()=“!@#$%^&*()‘iⱮ€PƇ%⁵Q
O ord of each character in the input
“!"Ṣ$%&/()=“!@#$%^&*()‘ Constant that yields the list:
[[33, 34, 183, 36, 37, 38, 47, 40, 41, 61],
[33, 64, 35, 36, 37, 94, 38, 42, 40, 41]
€ For each list of numbers:
Ɱ For each ord of the characters in the input:
i Find the index of the ord of the character
in the list of numbers.
If the number is not found, `i` returns zero
which means it's a character from only one
keyboard.
There are now two lists of numbers 1-10.
Ƈ Keep the list(s) that:
P have nonzero product.
%⁵ Modulo 10. This maps 10->0.
Q Unique elements. This removes duplicates if the two numbers are the same.
```
[Answer]
# [Python 3](https://docs.python.org/3/), 76 bytes
```
lambda s:{(*map(k.find,s),)for k in['=!"·$%&/()',')!@#$%^&*(']if{*s}<={*k}}
```
[Try it online!](https://tio.run/##rVK7bsIwFN39FTchEBtFECABghqJpVu3jkAlhziNRbCj2KhCiO9i58eoQwld@lClerq@x@dxbZd7nUsxumTx8lLQbZJSULMD7m5piTe9jIvUU8QjmaxgA1ws3Niyzyen3elj4nouseYtp/3S6WJ3xbNDVx0f4kN3czxeVGzb9hKZY9CsyTRqSvxcUsFVDgXdy52GlGm21iyFZA86Z7BTDGQGfYKM1V0gCMdeEE6uAk8fxDUVQmpImAmXsapiKUEm050yGI7uno/itfjdcw5UpNAiCJOO1XCn0XjgRf5k8LMzxucTaQaeTkdR9KdxDRlZDnyGD@7l966QmHYtUjG1KzRwdd0pumVQP1sidW5kLcdpt2@ygyAIw3@RjWPHbiL6fjDsB8Mv5vWAZ0BB7LYJq0BpWmkFb1zn4IPBa3dY51KaW9DSfBuEaoeCizoOqJ4qC66xuxQumSEwvRLiK3xDyMJfmX5ZcaFxhg1OCLq8Aw "Python 3 – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 62 bytes
```
{set grep {!/\D/},TR'=!"·$%&/()'0..9',TR')!@\x23$%^&*('0..9'}
```
[Try it online!](https://tio.run/##JcvBCoJAEAbgV/lHZ9cZCTcKgqANDz1BdBSjg3YpEu2QiM/l3RfbjK4ffE3VPnbh2cPW8GHoqjfubdVgIFec3Li6nBNP0TyxsU40WWfZPvmhUl58Nls2pU3lz2Pobj1q4auifrU4LAHLA@UxRC1BZJ5UQQwiZmPgPUcgRJgnMAwsHAQKjxwxSqTH8AU "Perl 6 – Try It Online")
Returns a Set. (Could be made two or three bytes shorter if [there wasn't a bug](https://github.com/rakudo/rakudo/issues/2118) in Rakudo's handling of # in search lists.)
[Answer]
# [Java (JDK)](http://jdk.java.net/), 173 bytes
**Golfed**
```
c->{String s="",e=s;var m="21#3457#908###6##12#456389###0#7".split("");for(int l:c){e+=m[l=l%16];s+=m[l+16];}return s.equals(e)|s.contains("#")?e:e.contains("#")?s:s+","+e;}
```
[Try it online!](https://tio.run/##lZLLTsMwEEXX5CscO0G20oa@X5F5iDXddFm6MK5bUpyk2E6lKuS72PNjwW2zQCAWmZVn5tzR3JF37MDau/Vbtc9fZMwBl0xr8MTitHCuHGBDG2ZsI06NUBvGBZgX5/opatHCqDjdAo75K1PLFeAkOiOl83PCHKSAAqfi7duiVmgKYUtQHR2YAgmFvS7qD4ZjNO1MEEIjhLo9NBiO@pOpTTtoDEO9l7HBEJJokylslwJyxkkhAposJZV@d7SK9DkJTs9SCZOrFOhQvOdMaizIhw55lhrrUGOIILkTM/Gromc6gC0YiKisoouH2mlt5ZDFa5BYAb4YsZ6Z2mpib7Y4aiOSMMtNuLctI1OchhzDG0xgaLJHe6EHpdgRE2Kv9C/u@ddNcPceNcExuXYb8fjrkzTa3/Ua0a7n@X4TBaXeM/wrAKD@eGX1DQ "Java (JDK) – Try It Online")
---
**Ungolfed**
```
c->{ // Lamdba taking char array as input
String s="",e=s; // Initialise Spanish and English strings
var m="21#3457#908###6##12#456389###0#7".split(""); // Create magic hashing lookup array (see below)
for(int l:c){ // Loops through all chars in input
e+=m[l=l%16]; // Get english number from array and append
s+=m[l+16]; // Get Spanish number from array and append
}
return s.equals(e)|s.contains("#")?e: // If equal or Spanish is invalid return english
e.contains("#")?s: // If English is invalid return Spanish
s+","+e; // If both are valid but not equal, return both
}
```
---
**The Magic Hashing Lookup Array**
After some experimenting with values I realised that each of the ASCII values of the characters `!"·$%&/()=@#^*` modulo 16 returns a unique number. The *'magic hashing lookup array'* stores the English numbers associated with each character at this unique index, and each of the Spanish numbers at this index offset by 16, making fetching the required number from the array trivial for each language. A hash is stored for values that are invalid for either language.
[Answer]
# Japt, 38 bytes
Outputs an array of strings with the Spanish layout first.
```
"=!\"·$%&/())!@#$%^&*("òA £ËXbD
kø'- â
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=Ij0hXCK3JCUmLygpKSFAIyQlXiYqKCLyQSCjy1hiRApr+CctIOI=&input=Jy8oKScKLVE=)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 38 bytes
```
183Ọ“=!"“$%&/()”j,“)!@#$%^&*(”iⱮ€⁸ẠƇ’Q
```
[Try it online!](https://tio.run/##y0rNyan8/9/Qwvjh7p5HDXNsFZWApIqqmr6G5qOGuVk6QJ6mooOyimqcmpYGUCTz0cZ1j5rWPGrc8XDXgmPtjxpmBv7//19D49B2TU0A "Jelly – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 60 bytes
```
.+
$&¶$&
T`=!"·$%&/()`d`^.+
T`)!@#$%^&*(`d`.+$
D`
Gm`^\d+$
```
[Try it online!](https://tio.run/##DYs9DsIwDIX3dwuXZ8shUjlBJAakXqAjioxUBgYYEGdr91wsZP1@vs/f6/Po6kv0OYPWdhrWKDK1g2oXT7FFHWqNJNcTtdrZB5ozcQss76j3LbMTbe@jxpgwQngygXs7UoIQIqQqSuH0Bw "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
.+
$&¶$&
```
Duplicate the input.
```
T`=!"·$%&/()`d`^.+
T`)!@#$%^&*(`d`.+$
```
Try to translate each line according to a different keyboard layout.
```
D`
```
Deduplicate the result.
```
Gm`^\d+$
```
Only keep lines that only contain digits.
[Answer]
# JavaScript (ES6), 99 bytes
```
s=>(g=l=>a=s.replace(/./g,c=>l.indexOf(c)))('=!"·$%&/()',b=g(')!@#$%^&*('))>=0?a-b&&b>=0?[a,b]:a:b
```
[Try it online!](https://tio.run/##ZY7RaoMwFIbv9xS1jTEZqVEbqxaO2xv0AcYGSRqlI2ipZezNet8Xc8k6VtBz9cP3Hf7/U37JQZ@Pp8u66w9mbGAcoCYtWKglDPHZnKzUhvCYt0xDbeNjdzDf@4ZoSimJIFjerijEnNCIKWhJRIPXFQo/8LOLtIbkRa4VxsqnN8nU@07u1Kj7buitiW3fkoZE/pvShTvOF0VZPU24K3hwkW@ZyIup42ofTpptppxQHNwFx8tqm7IqKdKZRW5Xeh/jtXJTzcYE6K/nt0jMcIBQGHrF41SIPJ8qAGj5PyVJRMZFNv4A "JavaScript (Node.js) – Try It Online")
### How?
The helper function \$g\$ attempts to convert the input string using a given layout.
Invalid characters are replaced with \$-1\$, which results in either a valid but negative looking numeric string (if only the first character was missing), or an invalid numeric string. Either way, the test `x >= 0` is falsy.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~42~~ 41 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
•Hhç₁d©u÷^Σ(“ðΣèõĆ
-•184в2äεIÇk}ʒ®å_}>T%Ù
```
Port of [*@dylnan*'s Jelly answer](https://codegolf.stackexchange.com/a/173950/52210).
[Try it online](https://tio.run/##AVAAr/9vc2FiaWX//@KAokhow6figoFkwql1w7dezqMo4oCcw7DOo8Oow7XEhgot4oCiMTg00LIyw6TOtUnDh2t9ypLCrsOlX30@VCXDmf//KCkmIQ) or [verify all test cases](https://tio.run/##AYEAfv9vc2FiaWX/fHZ5PyIg4oaSICI/eVX/4oCiSGjDp@KCgWTCqXXDt17OoyjigJzDsM6jw6jDtcSGCi3igKIxODTQsjLDpM61WMOHa33KksKuw6VffT5UJcOZ/yz/LygpCiQlJgohQCMKKCkmIQooKMK3KSkKISQKISEkJCUlCj09JCI).
**Explanation:**
```
•Hhç₁d©u÷^Σ(“ðΣèõĆ
-•184в # Compressed list [33,34,183,36,37,38,47,40,41,61,33,64,35,36,37,94,38,42,40,41]
2ä # Split into two parts: [[33,34,183,36,37,38,47,40,41,61],[33,64,35,36,37,94,38,42,40,41]]
ε } # Map each inner list to:
IÇ # Get the input, and convert each character to its unicode value
k # Then get the index of each unicode value in the current map-list
# (this results in -1 if the item doesn't exist)
ʒ } # Filter the resulting list of indices by:
®å_ # If the inner list does not contain any -1
> # Increase each index by 1 to make it from 0-indexed to 1-indexed
T% # Take modulo-10 to convert 10 to 0
Ù # Uniquify the result-lists (and output implicitly)
```
[See this 05AB1E tip of mine (section *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•Hhç₁d©u÷^Σ(“ðΣèõĆ\n-•184в` is `[33,34,183,36,37,38,47,40,41,61,33,64,35,36,37,94,38,42,40,41]`). This (together with the `2ä`) is 1 byte shorter than taking the unicode values of the string: `'""!ÿ·$%&/()=""!@#$%^&*()"‚Ç`.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 68 bytes
```
->s{%w[=!"·$%&/() )!@#$%^&*(].map{|a|s.tr a,'0-9'}.grep_v(/\D/)|[]}
```
[Try it online!](https://tio.run/##Jc1RCoIwHIDx9/8pNtt0C916DVz00CGEZWGgIlgMZ2U4z@W7F7NRB/h@X/e8fdZKrcnBjvStFQ6WmdBQMo44Pm4IvYRblot7YUZXOCv6DhVxtEv20STqrjTXF5Pnk@RO59PaNo/SqjTNhDVt0yMiwUPgPfAWMB5iYGyZOQdMAGNCKAWlSAAZ/Nr/Z3AG6SGu9JB79As "Ruby – Try It Online")
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 116 bytes
```
import StdEnv,Text
$s=removeDup[foldl(<+)""d\\r<-["=!\"·$%&/()",")!@#$%^&*("],d<-[[indexOf{c}r\\c<-s]]|all((<) -1)d]
```
[Try it online!](https://tio.run/##JY1NC4IwAEDv/Yq1TLdSojp0UehghyAoqJtbMLYZwj5kziiqv94SOj54j8eVZCZoK3olgWaNCY1urfPg7MXO3NOLfPhR1BVOanuXZd9WtVVCoXyOIRSEuDyrYDEmkKw3q2gaLxCGKcTj7SSaXuMZgjQVg1I1RsjHsX7xjyOE51lH6ZsphVCOQbbEgoazZ8O2ABGokiFPaPjyWrFbF7L9IZRPw3TD/3BSzNfW6R8 "Clean – Try It Online")
Takes input and is encoded in CP437. TIO only supports UTF-8, so an escape is used in the demo code to get the literal byte value 250 corresponding to the centre dot (counted as one byte).
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 40 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")
Anonymous tacit prefix function. Though unused, `·` [is in the Dyalog single byte character set](https://tio.run/##SyzI0U2pTMzJT/8PBOqHtqs/6uh61DfVMQwA "APL (Dyalog Unicode) – Try It Online"). Assumes 0-based indexing (`⎕IO←0`) which is default on many systems.
```
{∪⍵/⍨~10∊¨⍵}'=!"·$%&/()' ')!@#$%^&*('⍳¨⊂
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/6sfdax61LtV/1HvijpDg0cdXYdWALm16raKSoe2q6iq6Wtoqiuoayo6KKuoxqlpaag/6t0MVNLV9D8NqP9Rbx/EqK7mQ@uNH7VNBPKCg5yBZIiHZ/D/NAV1kH4uIA00CkwDDQLTGppqihCGxqHtmhA1iioQSlFFRVUVzLS1VVFSBwA "APL (Dyalog Unicode) – Try It Online")
`⊂` the entire argument
`'=!"·$%&/()' ')!@#$%^&*('⍳¨` indices of the characters in each of these strings
`{∪⍵/⍨~10∊¨⍵}` apply the following lambda (`⍵` is the argument):
`10∊¨⍵` for each list of digits, whether 10 (indicating "not found") is a member thereof
`~` local negation (i.e. only those where all digits are found)
`⍵/⍨` filter the argument by that
`∪` find the unique elements of that
[Answer]
# [Dart](https://www.dartlang.org/), 125 bytes
```
f(s)=>['=!"·\$%&/()',')!@#\$%^&*('].map((b)=>s.split('').map((e)=>b.indexOf(e)).join()).where((e)=>!e.contains('-')).toSet();
```
Ungolfed :
```
f(s){
['=!"·\$%&/()',')!@#\$%^&*(']
.map(
(b)=>s.split('').map((e)=>b.indexOf(e))
.join()
).where(
(e)=>!e.contains('-')
).toSet();
}
```
* Creates an array with the two specified key values, from 0 to 9
* For each of them, convert the input string to the corresponding number by using the characters' indexes
* Join the resulting array to create a number
* Remove any number having a '-' (Dart returns -1 when indexOf can't find a char)
* Return as a Set to remove duplicates
[Try it on Dartpad!](https://dartpad.dartlang.org/4a2cde45e47d38c8fbaa2358053e726c)
[Answer]
# T-SQL, 143 bytes
```
SELECT DISTINCT*FROM(SELECT TRY_CAST(TRANSLATE(v,m,'1234567890')as INT)a
FROM i,(VALUES('!"·$%&/()='),('!@#$%^&*()'))t(m))b
WHERE a IS NOT NULL
```
Input is taken via pre-existing table **i** with varchar field **v**, [per our IO standards](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341).
Joins the input table with the two different character strings, then uses the [new SQL 2017 function `TRANSLATE`](https://docs.microsoft.com/en-us/sql/t-sql/functions/translate-transact-sql) to swap out individual characters, and `TRY_CAST` to see if we end up with a number. If not, `TRY_CAST` returns `NULL`.
The final outer `SELECT DISTINCT` combines identical results and filters out the `NULLS`.
] |
[Question]
[
## Introduction:
When we think about Ladybugs, we usually think of a red or dark orange bug with black spots. Although this isn't necessary true, since there are also [black with red/orange spotted ladybugs](https://kids.nationalgeographic.com/content/dam/kids/photos/animals/Bugs/H-P/ladybug-on-leaf.ngsversion.1412637651930.jpg), or [ladybugs without spots at all](http://cdn-3.ladybug-life-cycle.com/graphics/Ladybug_red.jpg), we mainly picture ladybugs something like this Asian Ladybug:
[](https://i.stack.imgur.com/kChGNm.jpg)
Another thing to note is that the spots on the ladybugs are almost always symmetric. And that is where this challenge comes in.
## Challenge:
Given an integer `n` (`>= 0`), output the following ASCII-art ladybug one or multiple times, with symmetric spots evenly divided between the two sides, as well as the two or more ladybugs.
Here is the default ladybug layout:
```
_V_
/(@I@)\
/ | \
| | |
\ | /
''-!-''
```
If `n=0`, we output the ladybug above as is.
When `n` is larger than zero, we either fill in the spaces of the ASCII-art bug with a lowercase `o`, or replace the `|` in the center with a capital `O`. The goal is to make `n` changes to the 'empty' ladybug(s), while still producing a symmetric output (per ladybug), and outputting as few ladybugs as possible.
So valid outputs for `n=1` are:
```
_V_
/(@I@)\
/ O \
| | |
\ | /
''-!-''
_V_
/(@I@)\
/ | \
| O |
\ | /
''-!-''
_V_
/(@I@)\
/ | \
| | |
\ O /
''-!-''
```
But this would be invalid:
```
_V_
/(@I@)\
/ | \
| o | |
\ | /
''-!-''
```
Valid outputs for `n=2` are:
```
_V_
/(@I@)\
/ O \
| O |
\ | /
''-!-''
_V_
/(@I@)\
/ O \
| | |
\ O /
''-!-''
_V_
/(@I@)\
/ o|o \
| | |
\ | /
''-!-''
_V_
/(@I@)\
/ | \
| o | o |
\ | /
''-!-''
etc. There are a lot of possible outputs.
```
The first `n` that isn't possible to fit into a single ladybug anymore is `n=24`. In which case you'll have to divide it as evenly as possible into two ladybugs (you can choose whether to output them next to each other, or under one another - with optionally one space or one new-line in between them). For example:
```
_V_ _V_
/(@I@)\ /(@I@)\
/o o|o o\ /o o|o o\
|o o | o o||o o | o o|
\o o|o o/ \o o|o o/
''-!-'' ''-!-''
```
OR:
```
_V_
/(@I@)\
/ooo|ooo\
| | |
\ooo|ooo/
''-!-''
_V_
/(@I@)\
/ooo|ooo\
| | |
\ooo|ooo/
''-!-''
```
## Challenge rules:
* `n` will be in the range of `0-1000`.
* You can choose to output to STDOUT, return as String or 2D-char array/list, etc. Your call.
* Leading new-lines or unnecessary whitespaces aren't allowed. Trailing white-spaces and a single trailing new-line are allowed.
* As mentioned above, when two or more ladybugs are necessary, you can choose whether to output them next to each other or below each other (or a mix of both..)
* When two or more ladybugs are printed next to each other, a single optional space in between is allowed. When two or more ladybugs are printed down one another, a single optional new-line in between is allowed.
* You can choose the layout of the ladybugs at any step during the sequence, as long as they are symmetric and equal to input `n`.
* Since the goal is to have `n` changes AND as few ladybugs as possible, you will start using more than one ladybug when above `n=23`. The layout of these ladybugs doesn't necessary have to be the same. In fact, this isn't even possible for some inputs, like `n=25` or `n=50` to name two.
* In addition, sometimes it isn't possible to evenly split the dots among two or more ladybugs. In that case you'll have to split them as evenly as possible, with at most a difference of 1 between them.
So for `n=50`, keeping the last two rules in mind, this would be a valid possible output (where the first bug has 16 spots, and the other two have 17):
```
_V_ _V_ _V_
/(@I@)\ /(@I@)\ /(@I@)\
/oooOooo\ / O \ /o oOo o\
|ooooOoooo||ooooOoooo||o ooOoo o|
\ | / \oooOooo/ \o oOo o/
''-!-'' ''-!-'' ''-!-''
```
## General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code.
* Also, please add an explanation if necessary.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~252~~ ~~249~~ ~~238~~ ~~212~~ ~~211~~ ~~213~~ 209 bytes
```
n=input()
x=(n+22)/23or 1
for i in range(x):b=n/x+(n%x>i);c=r""" _V_
/(@I@)\
/361%s163\
|408717804|
\5201025/
''-!-''"""%'|O'[b%2];i=0;exec"c=c.replace(`i%9`,' |oO'[i>9::2][i<b/2],2);i+=1;"*11;print c
```
[Try it online!](https://tio.run/##DYy9bsMgGAB3noIiIaBOivns/JkSZe2UrUtsJTEiKVKFLepKVPK7u9xw0@nGv@lrCLAswfgw/k5coGR4KACEhGqIWKFHtsc@4HgPT8eTaHoTZCp4oOnohbYmEkJw5vp5RRhLfvo4iRZhWW0V/VHbqkVzXe53arcv6xnhdgOlKmEjc8zY@mXNWB5QNp/ZpafQaW9K7ZKzxBr7Ft34fbeO3zw93FYMz0PO/PHQNNBd/HsvoVuB0L4wSpNXpfQYfZiwXRao/wE "Python 2 – Try It Online")
* Saved 9 bytes thanks to Kevin Cruijssen
* Saved 18 bytes thanks to Mr. Xcoder
* Saved 2 bytes thanks to Jonathan Frech
[Answer]
# JavaScript (ES6), ~~183~~ 186 bytes
Uses the same formula as [TFeld's answer](https://codegolf.stackexchange.com/a/146896/58563) to split the spots among the ladybugs.
```
n=>(g=k=>k--?` _V_
/(@I@)\\
/3\\
|4|
\\3/
''-!-''
`.replace(/\d/g,i=>(h=s=>i--?h((p=N?(N-=2,'o'):' ')+s+p):s)('|O'[N>2*i|N&1&&+!!N--]),N=(n%j>k)+n/j|0)+g(k):'')(j=n/23+.99|0||1)
```
### Demo
```
let f =
n=>(g=k=>k--?` _V_
/(@I@)\\
/3\\
|4|
\\3/
''-!-''
`.replace(/\d/g,i=>(h=s=>i--?h((p=N?(N-=2,'o'):' ')+s+p):s)('|O'[N>2*i|N&1&&+!!N--]),N=(n%j>k)+n/j|0)+g(k):'')(j=n/23+.99|0||1)
console.log(f(0))
console.log(f(1))
console.log(f(9))
console.log(f(25))
```
[Answer]
# Befunge, ~~292~~ 279 bytes
```
#j07-00p&>::1-27*9+/\!!*:1+06pv-1_@#:<<g61$<<:
v"h"**95%2:+`g61%g60\/g60::p61<>-0g*+35*-,:!|
>\-30p2/:55+`:59**"g"\-40p-26pv^*84\!`"."::<<9
v\%+55+g62:%+55+4*g62:::-1<+55<>:"/n"$#->#<^#<
>`26g!+"O"*"Y"\-\-\5+0p:>#^_" 66<0<66// >,-"v
"n //>7OXO8k />'&%$%&'k !(*+)#)+*(! /k,-.$."<v
```
[Try it online!](http://befunge.tryitonline.net/#code=I2owNy0wMHAmPjo6MS0yNyo5Ky9cISEqOjErMDZwdi0xX0AjOjw8ZzYxJDw8Ogp2ImgiKio5NSUyOitgZzYxJWc2MFwvZzYwOjpwNjE8Pi0wZyorMzUqLSw6IXwKPlwtMzBwMi86NTUrYDo1OSoqImciXC00MHAtMjZwdl4qODRcIWAiLiI6Ojw8OQp2XCUrNTUrZzYyOiUrNTUrNCpnNjI6OjotMTwrNTU8PjoiL24iJCMtPiM8XiM8Cj5gMjZnISsiTyIqIlkiXC1cLVw1KzBwOj4jXl8iIDY2PDA8NjYvLyA+LC0idgoibiAvLz43T1hPOGsgLz4nJiUkJSYnayAhKCorKSMpKyooISAvaywtLiQuIjx2&input=OQ)
**Explanation**
The ASCII art for the ladybug is encoded in a single Befunge string, offset by 15, to allow the first 15 printable characters to be reserved for special purposes. The first two of these special characters represent the newline and the `|` character, both of which would otherwise not be printable. The third isn't used, because it's a `"`, which can't be used in a string. The next two represent the large spots in the centre. And the remaining ten are for the spots on the wings.
These special characters are translated into their final form via a lookup table, which is written over the first part of the first line.
To make it easier to explain, this is the code with the various component parts highlighted:

 We start by initialising the newline and `|` character in the lookup table, since these are constant.
 Next we read in the number of spots from stdin and calculate the number of ladybugs required.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~84~~ 81 bytes
```
Nθ≔⌈∕∨θ¹¦²³ηFη«≔⁺÷θη‹ι﹪θηζV_¶I@)↘²↙|/←''-↑!↑⎇›ζ²¹OO²§|OζE037×o⌊⟦⁻÷ζ²Iκ⁺³⁼κ3⟧↙»‖B←
```
[Try it online!](https://tio.run/##XZBNTwIxEIbP8CtqL0yTJX7sgSgXEYzZhBVC0Isas0KXbei20A8UxN@@ToUE5NJMnnln3r4zKTIz0ZmsqkQtvHv05Qc3sGTtesdaMVPQ5UIKNYOeWIkphwE2I3LJInIVM3wLVObaECgY@a7X9kND6S0kyu2HlkEXkT63FkREUj31Uu9o2LHBHbWhEcoBfX5/Vcktowd009OfaiRmhUPPE9znOVK6PT/W72Gj0TymTwtkZ6dkzI3KzBoeDM8cBt@gRwhHBwMa7A7yjkvUlH8B3YbO5qiTZgugF3EL8ViU3ALVWKZCidKX8ILFv2MEC3ToZtbBPMT/O1Yckfulz6SFObrHlLE3vE0wSfWKH9Ii@amPeC75xN15h3/O5XqXmbWr6rpVNVfyFw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ
```
Input the total number of spots.
```
≔⌈∕∨θ¹¦²³η
```
Calculate the number of ladybirds needed.
```
Fη«
```
Loop over each ladybird.
```
≔⁺÷θη‹ι﹪θηζ
```
Calculate the number of spots to put on this ladybird.
```
V_¶I@)↘²↙|/←''-↑!
```
Print the head and right wing of the ladybird.
```
↑⎇›ζ²¹OO²
```
If there are more than 21 spots, print two spots, otherwise print the back.
```
§|Oζ
```
If the number of spots is odd print another spot otherwise print the rest of the back.
```
E037×o⌊⟦⁻÷ζ²Iκ⁺³⁼κ3⟧
```
Divide the number of spots by two, and distribute them among three rows of 3, 4, and 3 spots.
```
↙»
```
Move to the start of the next ladybird.
```
‖B←
```
Reflect the canvas to the left, keeping the back.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~203~~ ~~193~~ 190 bytes
```
f=->n{s=%q{ _V_
/(@I@)\
/137x731\
|0596x6950|
\248x842/
''-!-''
}
n-=d=n>0?n/(1+~-n/23):0
s.gsub!(/\d/){$&.to_i<d/2??o:' '}
x=[d%2,d<=>21]*2
s.gsub!(?x){"|O|"[x.pop]}
n>0?s+f[n]:s}
```
[Try it online!](https://tio.run/##PY3LboMwEEX3/gpDmxqagB88kqAYsu2qUhfdAEKNLKouamgcJFdAf51aoDCrOVd3zly7y@801dxLZa/45qeHZqr3CgIIsXN@ObsFgJgGe70PaAEGEh1jHR8jMgBYsPCgDyHDpouQZ3kIgRFIjwsuU5JJ7NDtnycxC9yEAOV/qu5iObgQ2O0fn/xbU32dBGZZ1iQIohFonosN24kTTxktn9l6kmm3t4fXwc613zZtaZ4Yv9rWuSwTNU5td1PQJom9q3NSggXpjPSObEa2YrBwsAbhEoT3IFp80Sp8@5Ci@bbgQ6/51ewOpbE7ziVdTv8 "Ruby – Try It Online")
* Saved 10 bytes thanks to Jordan
] |
[Question]
[
The video game [Transistor](http://en.wikipedia.org/wiki/Transistor_(video_game)) features a very interesting ability system. You collect 16 "Functions" which you can use in 16 different slots. What's interesting is that there are 3 types of slots and every Function behaves differently according to which slot you use it in:
* There are **4 Passive Slots**.
* There are **4 Active Slots**.
* **Each Active Slot** has **2 Upgrade Slots**.
We want to figure out how many different skill sets that gives us.
However, some combinations are equivalent. In particular, within each of those groups of slots, the specific position of a Function doesn't matter. On the other hand, the effect of a Function in an Upgrade Slot *does* depend on the specific Function used in the parent Active Slot.
Therefore, using hexadecimal digits to stand in for the Functions, the following combinations are all equivalent:
```
Passive Slots: 0 1 2 3
Active Slots: 4 5 6 7
Upgrade Slots: 8 9 A B C D E F
Passive Slots: 2 0 1 3 # Permutation of passive slots.
Active Slots: 4 5 6 7
Upgrade Slots: 8 9 A B C D E F
Passive Slots: 0 1 2 3
Active Slots: 5 6 4 7 # Permutation of active slots together
Upgrade Slots: A B C D 8 9 E F # with their upgrade slots.
Passive Slots: 0 1 2 3
Active Slots: 4 5 6 7
Upgrade Slots: 8 9 B A C D F E # Permutation within upgrade slots.
```
as well as any combination of these rearrangings. Note that in the third case the Upgrade Slots were swapped along with the Active Slots to maintain the same overall effect.
On the other hand, the following combinations are all different from the above set:
```
Passive Slots: 4 5 6 7 # Passive slots swapped
Active Slots: 0 1 2 3 # with active slots.
Upgrade Slots: 8 9 A B C D E F
Passive Slots: 0 1 2 3
Active Slots: 5 4 6 7 # Permutation of active slots without
Upgrade Slots: 8 9 A B C D E F # changing upgrade slots.
Passive Slots: 0 1 2 3
Active Slots: 4 5 6 7
Upgrade Slots: 8 A 9 B C D E F # Permutation between different upgrade slots.
```
By my count that gives you 2,270,268,000 possible (functionally distinct) combinations, assuming all Functions are used.
If you have less than 16 Functions at your disposal, some of the slots will remain empty. However, note that **you can't place a Function in an Upgrade Slot if the parent Active Slot is empty.**
## The Challenge
You're to determine the number of possible configurations depending on how many functions you have. Furthermore, I will generalise the problem slightly by making the number of slots variable, in order to prevent trivial hardcoding solutions.
Write a program or function which, given two positive integers `M ≥ 1` and `1 ≤ N ≤ 4M`, determines the number of possible (functionally distinct) skill sets assuming exactly `N` different Functions are used to fill as many as possible of `M` Passive, `M` Active and `2M` Upgrade Slots.
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.
Your code must be able to handle any input up to and including `M = 8` within one minute on a reasonable desktop machine. There is some leeway in this, but it should rule out brute force solutions. In principle it should be no issue to solve any of those inputs in less than a second.
This is code golf, the shortest answer (in bytes) wins.
## Test Cases
Each test case is in the form `M N => Result`.
```
1 1 => 2
1 2 => 4
1 3 => 9
1 4 => 12
2 1 => 2
2 2 => 6
2 3 => 21
2 4 => 78
2 5 => 270
2 6 => 810
2 7 => 1890
2 8 => 2520
3 1 => 2
3 2 => 6
3 3 => 23
3 4 => 98
3 5 => 460
3 6 => 2210
3 7 => 10290
3 8 => 44520
3 9 => 168840
3 10 => 529200
3 11 => 1247400
3 12 => 1663200
4 1 => 2
4 2 => 6
4 3 => 23
4 4 => 100
4 5 => 490
4 6 => 2630
4 7 => 14875
4 8 => 86030
4 9 => 490140
4 10 => 2652300
4 11 => 13236300
4 12 => 59043600
4 13 => 227026800
4 14 => 718918200
4 15 => 1702701000
4 16 => 2270268000
5 1 => 2
5 2 => 6
5 3 => 23
5 4 => 100
5 5 => 492
5 6 => 2672
5 7 => 15694
5 8 => 98406
5 9 => 644868
5 10 => 4306932
5 11 => 28544670
5 12 => 182702520
5 13 => 1101620520
5 14 => 6122156040
5 15 => 30739428720
5 16 => 136670133600
5 17 => 524885961600
5 18 => 1667284819200
5 19 => 3959801445600
5 20 => 5279735260800
6 1 => 2
6 2 => 6
6 3 => 23
6 4 => 100
6 5 => 492
6 6 => 2674
6 7 => 15750
6 8 => 99862
6 9 => 674016
6 10 => 4787412
6 11 => 35304654
6 12 => 265314588
6 13 => 1989295308
6 14 => 14559228684
6 15 => 101830348620
6 16 => 667943115840
6 17 => 4042651092480
6 18 => 22264427465280
6 19 => 110258471363040
6 20 => 484855688116800
6 21 => 1854067032417600
6 22 => 5894824418683200
6 23 => 14025616720315200
6 24 => 18700822293753600
7 1 => 2
7 2 => 6
7 3 => 23
7 4 => 100
7 5 => 492
7 6 => 2674
7 7 => 15752
7 8 => 99934
7 9 => 676428
7 10 => 4849212
7 11 => 36601554
7 12 => 288486132
7 13 => 2349550632
7 14 => 19504692636
7 15 => 162272450340
7 16 => 1328431104000
7 17 => 10507447510560
7 18 => 78942848624640
7 19 => 554967220167360
7 20 => 3604592589998400
7 21 => 21411337810262400
7 22 => 115428212139240000
7 23 => 561247297649438400
7 24 => 2439121536313862400
7 25 => 9283622495827680000
7 26 => 29520583763711040000
7 27 => 70328449554723360000
7 28 => 93771266072964480000
8 1 => 2
8 2 => 6
8 3 => 23
8 4 => 100
8 5 => 492
8 6 => 2674
8 7 => 15752
8 8 => 99936
8 9 => 676518
8 10 => 4852992
8 11 => 36722169
8 12 => 291621462
8 13 => 2418755196
8 14 => 20834571186
8 15 => 184894557705
8 16 => 1672561326150
8 17 => 15217247948760
8 18 => 137122338089880
8 19 => 1204392465876600
8 20 => 10153538495100000
8 21 => 81007229522419200
8 22 => 604136189949692400
8 23 => 4168645459350372000
8 24 => 26403795950145213600
8 25 => 152700324078982680000
8 26 => 803784718213396920000
8 27 => 3838761204861983400000
8 28 => 16503742828841748480000
8 29 => 62545434470667308160000
8 30 => 198853691115980300400000
8 31 => 474189571122722254800000
8 32 => 632252761496963006400000
```
These are all the inputs your code has to handle within one minute (each), but it should in principle work for larger inputs. You can use some of the following `M = 10` test cases to check that:
```
10 1 => 2
10 2 => 6
10 3 => 23
10 4 => 100
10 5 => 492
10 6 => 2674
10 7 => 15752
10 8 => 99936
10 9 => 676520
10 10 => 4853104
10 11 => 36727966
10 12 => 291849866
10 13 => 2426074222
10 14 => 21033972388
10 15 => 189645995396
10 16 => 1773525588406
10 17 => 17155884420532
10 18 => 171073929494468
10 19 => 1750412561088334
10 20 => 18258387148774916
10 21 => 192475976310317700
10 22 => 2028834600633220380
10 23 => 21127206177119902860
10 24 => 214639961631544809360
10 25 => 2101478398293813739200
10 26 => 19602967930531817832000
10 27 => 172444768103233181556000
10 28 => 1417975382888905296456000
10 29 => 10820259026484304813416000
10 30 => 76213534343700480310584000
10 31 => 493916052421168703366040000
10 32 => 2941900199368102067135040000
10 33 => 16113144277547868007416960000
10 34 => 81222252655277786422930560000
10 35 => 376309102059179385262246080000
10 36 => 1589579966324953534441910400000
10 37 => 5981477408861097281112374400000
10 38 => 19005991357166148698688124800000
10 39 => 45381652832417130566255318400000
10 40 => 60508870443222840755007091200000
```
[Answer]
## CJam (56 bytes)
```
q~4@:Nm*:$_&{:+1$\-N),&},f{1$1$:+-\0-:(_e`0f=+++:m!:/}:+
```
[Online demo](http://cjam.aditsu.net/#code=q~4%40%3ANm*%3A%24_%26%7B%3A%2B1%24%5C-N)%2C%26%7D%2Cf%7B1%241%24%3A%2B-%5C0-%3A(_e%600f%3D%2B%2B%2B%3Am!%3A%2F%7D%3A%2B&input=4%2016)
This is an optimised version of the reference implementation I wrote for the sandbox. Note: I use `N` in the code because in a Real Combinatorics Question™ the parameters are \$n\$ and \$k\$, not `m` and `n`, but I'll use \$M\$ and \$N\$ in the explanation to avoid further confusion.
Suppose that we assign \$X\$ functions to the passive slots (where obviously \$0 \le X \le M\$). Then we have \$N-X\$ functions left for the active + upgrade slots (and we can choose those functions in \$\frac{N!}{X!(N-X)!}\$ ways). Because the order of the slot constellations is irrelevant, we want to consider each partition of \$N-X\$ into at most \$M\$ parts each of at most \$3\$ exactly once.
Take partition \$λ\_0, λ\_1, \ldots, λ\_k\$. We can assign \$λ\_0\$ parts to the first slot constellation, \$λ\_1\$ to the second, etc. in \$\frac{(N-X)!}{λ\_0! λ\_1! ... λ\_k!}\$ ways (multinomial), but we need to compensate for two factors. Firstly, if we have \$λ\_i = λ\_j\$ then the constellations are interchangeable, so we further divide by the factorials of the multiplicities of each part, \$μ\_i\$. (E.g. the partition `3 2 2 1` has \$μ\_3 = 1\$, \$μ\_2 = 2\$, \$μ\_1 = 1\$). Secondly, we have a designated "active" slot in each constellation, so for each \$λ\_i\$ we multiply by \$λ\_i\$ ways to select the active function.
So for each partition the number of distributions of functions is
$$\frac{N!}{X! (λ\_0-1)! \ldots (λ\_k-1)! μ\_1! μ\_2! μ\_3!}$$
The code above computes the partitions using the same approach as Dennis (it's obvious and short, although not very scalable) and then processes each partition into an array similar to `[N X λ_0-1 ... λ_k-1 μ_1 μ_2 μ_3]` over which it can lift the factorial function and then fold division.
[Answer]
# CJam, ~~74~~ 67 bytes
```
q~4@:Mm*:$L|{:+W$\-M),&},f{0-:F1@@{_m!\I-:Nm!/I(m!/*N}fI;Fm!Fe=/}:+
```
I've verified all test cases on my desktop computer using the [Java interpreter](https://sourceforge.net/p/cjam/wiki/Home/). This took 2.2 seconds for **1 ≤ M ≤ 8** and 3.5 minutes for **M = 10**.
Try [this fiddle](http://cjam.aditsu.net/#code=q~4%40%3AMm*%3A%24L%7C%7B%3A%2BW%24%5C-M)%2C%26%7D%2Cf%7B0-%3AF1%40%40%7B_m!%5CI-%3ANm!%2FI(m!%2F*N%7DfI%3BFm!Fe%3D%2F%7D%3A%2B&input=8%2032) in the CJam interpreter or [verify the first 84 test cases at once](http://cjam.aditsu.net/#code=qN%25%7BS%25)~%3AR%3B2%3CS*%3AQ%3B%0A%20%20%20%20Q~4%40%3AMm*%3A%24L%7C%7B%3A%2BW%24%5C-M)%2C%26%7D%2Cf%7B0-%3AF1%40%40%7B_m!%5CI-%3ANm!%2FI(m!%2F*N%7DfI%3BFm!Fe%3D%2F%7D%3A%2B%0AR%3Do%7D%2F&input=1%201%20%3D%3E%202%0A1%202%20%3D%3E%204%0A1%203%20%3D%3E%209%0A1%204%20%3D%3E%2012%0A2%201%20%3D%3E%202%0A2%202%20%3D%3E%206%0A2%203%20%3D%3E%2021%0A2%204%20%3D%3E%2078%0A2%205%20%3D%3E%20270%0A2%206%20%3D%3E%20810%0A2%207%20%3D%3E%201890%0A2%208%20%3D%3E%202520%0A3%201%20%3D%3E%202%0A3%202%20%3D%3E%206%0A3%203%20%3D%3E%2023%0A3%204%20%3D%3E%2098%0A3%205%20%3D%3E%20460%0A3%206%20%3D%3E%202210%0A3%207%20%3D%3E%2010290%0A3%208%20%3D%3E%2044520%0A3%209%20%3D%3E%20168840%0A3%2010%20%3D%3E%20529200%0A3%2011%20%3D%3E%201247400%0A3%2012%20%3D%3E%201663200%0A4%201%20%3D%3E%202%0A4%202%20%3D%3E%206%0A4%203%20%3D%3E%2023%0A4%204%20%3D%3E%20100%0A4%205%20%3D%3E%20490%0A4%206%20%3D%3E%202630%0A4%207%20%3D%3E%2014875%0A4%208%20%3D%3E%2086030%0A4%209%20%3D%3E%20490140%0A4%2010%20%3D%3E%202652300%0A4%2011%20%3D%3E%2013236300%0A4%2012%20%3D%3E%2059043600%0A4%2013%20%3D%3E%20227026800%0A4%2014%20%3D%3E%20718918200%0A4%2015%20%3D%3E%201702701000%0A4%2016%20%3D%3E%202270268000%0A5%201%20%3D%3E%202%0A5%202%20%3D%3E%206%0A5%203%20%3D%3E%2023%0A5%204%20%3D%3E%20100%0A5%205%20%3D%3E%20492%0A5%206%20%3D%3E%202672%0A5%207%20%3D%3E%2015694%0A5%208%20%3D%3E%2098406%0A5%209%20%3D%3E%20644868%0A5%2010%20%3D%3E%204306932%0A5%2011%20%3D%3E%2028544670%0A5%2012%20%3D%3E%20182702520%0A5%2013%20%3D%3E%201101620520%0A5%2014%20%3D%3E%206122156040%0A5%2015%20%3D%3E%2030739428720%0A5%2016%20%3D%3E%20136670133600%0A5%2017%20%3D%3E%20524885961600%0A5%2018%20%3D%3E%201667284819200%0A5%2019%20%3D%3E%203959801445600%0A5%2020%20%3D%3E%205279735260800%0A6%201%20%3D%3E%202%0A6%202%20%3D%3E%206%0A6%203%20%3D%3E%2023%0A6%204%20%3D%3E%20100%0A6%205%20%3D%3E%20492%0A6%206%20%3D%3E%202674%0A6%207%20%3D%3E%2015750%0A6%208%20%3D%3E%2099862%0A6%209%20%3D%3E%20674016%0A6%2010%20%3D%3E%204787412%0A6%2011%20%3D%3E%2035304654%0A6%2012%20%3D%3E%20265314588%0A6%2013%20%3D%3E%201989295308%0A6%2014%20%3D%3E%2014559228684%0A6%2015%20%3D%3E%20101830348620%0A6%2016%20%3D%3E%20667943115840%0A6%2017%20%3D%3E%204042651092480%0A6%2018%20%3D%3E%2022264427465280%0A6%2019%20%3D%3E%20110258471363040%0A6%2020%20%3D%3E%20484855688116800%0A6%2021%20%3D%3E%201854067032417600%0A6%2022%20%3D%3E%205894824418683200%0A6%2023%20%3D%3E%2014025616720315200%0A6%2024%20%3D%3E%2018700822293753600).
### Idea
In principle, we can fill each active slot and its corresponding upgrade slots with **0**, **1**, **2** or **3** functions. For **4M** slots in total, we take all vectors **V** of **{0, 1, 2, 3}M** and filter out those for which **sum(V) > N** (more functions in non-passive slots than total functions available) or **sum(V) + M < N** (not enough passive slots for non-active functions). We sort and deduplicate all kept vectors, since the order of the slot families in not important.
With **N** functions and **V = (x1, …, xM)** functions in the non-passive parts of the slot families, we calculate the number of combinations as follows:
1. If **x1 = 0**, there is only one possibility for that slot family.
If **x1 = 1**, there are **N** possibilities, since we have **N** functions, and the function must go in the active slot.
If **x1 = 2**, we must place one function in the active slot and another in an upgrade slot (it doesn't matter which). There are **N** choices for the active slot and **N-1** remaining choices for the upgrade slot, giving a total of **N(N-1)** combinations.
If **x1 = 3**, there are **N** choices for the active slot, **N - 1** remaining choices for the first upgrade slot and **N - 2** for the second upgrade slot. Since the upgrade slots have no order, this counts every combination twice, so there are **N(N - 1)(N - 2)** unique combinations.
In any case, there are **N! / ((N - x1)! × (x1 - 1)!** combinations for this family.
2. We have used up **x1** functions, so set **N := N - x1** and repeat step 1 for **x2**, then **x3**, etc.
3. If **V** contains duplicates, the product of the above results will have counted all combinations multiple times. For each unique element of **V**, if it occurs **r** times in **V**, there are **r!** equivalent ways
to arrange these slot families, so the result from above must be devided by **r!**.
4. The final result is the number of unique combinations for that **V**.
To calculate the total number of unique combinations, all that's left to do is to compute the sum of the results for each **V**.
### Code
```
q~ e# Read an evaluate all input from STDIN. Pushes M and N.
4@:M e# Push 4, rotate the M, and formally save it in M.
m* e# Push {0, 1, 2, 3}^M.
:$ e# Sort each vector.
L| e# Perform set union with the empty list (deduplicates).
{ e# For each sorted vector:
:+ e# Compute the sum of its coordinates.
W$\- e# Subtract the sum from N (bottom of the stack).
M),& e# Push [0 ... M] and intersect.
}, e# If the intersection was not empty, keep the vector.
f{ e# For each kept vector, push N and V; then:
0-:F e# Save the non-zero elements of V in F.
1@@ e# Push 1 (accumulator), and rotate N and F on top of it.
{ e# For each I in F:
_m! e# Push I and push factorial(I).
\I-:N e# Subtract I from N and update N.
m!/ e# Divide factorial(N) (original N) by factorial(N) (updated N).
I(m!/ e# Divide the quotient by factorial(I - 1).
* e# Multiply the accumulator by the resulting quotient.
N e# Push N for the next iteration.
}fI e#
; e# Pop N.
Fm! e# Push all non-unique permutations of F.
Fe= e# Count the number of times F appears.
/ e# Divide the accumulator by the result.
} e#
:+ e# Add all resulting quotients.
```
] |
[Question]
[
An [epicycloid](http://en.wikipedia.org/wiki/Epicycloid) is the curve a point on a circle makes as it rolls around another circle. A [cyclogon](http://demonstrations.wolfram.com/Cyclogons/) is the shape a point on a [regular polygon](http://en.wikipedia.org/wiki/Regular_polygon) makes as it rolls across a plane. An *epicyclogon* is the curve traced by a point on one regular polygon as it rolls around another.
Write a program that draws an epicyclogon given `r`, `r1`, `r2`, `n1`, `n2`:
```
r = number of clockwise revolutions rolling polygon makes around stationary polygon (any real number as limited by float values)
r1 = distance from center of stationary polygon to each of its vertices (positive real number)
r2 = distance from center of rolling polygon to each of its vertices (positive real number)
n1 = number of sides stationary polygon has (integer greater than 2)
n2 = number of sides rolling polygon has (integer greater than 2)
```
### Notes
* When `r` is negative the roller should go **counterclockwise**.
* For `r`, one revolution occurs when the line connecting the centroids of the two shapes sweeps out a full 360 degrees. This notion is expanded to include all values of `r`. (So in a quarter revolution the line connecting the centroids sweeps out 90 degrees.)
* These arguments should come from the command line or your program should prompt for them (e.g. with Python's `input()`).
* `r1` and `r2` are relative to each other, not the dimensions of the image. So you can set one "unit" to be any number of actual pixels.
The point you must trace out is one of the vertices of the rolling shape. The shapes must start with this vertex touching a stationary vertex and two sides adjacent:

The exact starting vertices and the angle of the stationary polygon do not matter.
# Output
The output should go to an image that is at least 600x600 pixels (or some variable dimension than can be set to 600). It must show the entire epicyclogon curve specified by the parameters, well framed in the image.
The rolling and stationary polygons must also be drawn (with the roller in it's final state). The two shapes and the epicyclogon should be three noticeably different colors.
There must also be a simple way to *not* draw the polygons (a change of `true` to `false` in the code suffices).
Please show us at least 2 output images. It's ok to shrink them if necessary.
# Scoring
The shortest code that produces valid output images wins.
**Bonuses**
* Minus 50 bytes if the output is an animated gif (or similar) of the curve being drawn.
* Minus 150 bytes if you let `n1` and `n2` take the value 2 so the shapes become line segments of length `2 * r1` (or `r2`), "rolling" around each other. How you handle `r` when `n1` and `n2` are 2 is up to you since the centroids don't revolve around each other the way they do in other cases. (Not "rolling" at all does not count as handling it.)
Since I am quite eager to see this novel idea executed well (and it's not exactly a cakewalk), **I am going to award 150 bounty rep** to the winner. The contest will end the same day the bounty runs out.
The bounty will not be awarded to the winner if it is clear that they simply rewrote most of the code from another submission.
Library functions that already happen to do this (if there are any) are not allowed.
*Note: This came from my [leftover questions](http://meta.codegolf.stackexchange.com/a/2007/26997) that anyone is free to post. But if no one else posts them there's a good chance I will in time. :P*
[Answer]
# Java - ~~2,726~~ 2,634 - 200 = 2434 characters
Improved from 3800 ish bytes
Thanks to all for your suggestions (especially pseudonym117), here is the new version.
I added a class P which is the point class and a class L which extends ArrayList
I also added some minor logic changes.
Here is the main class (not golfed):
```
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
public class Polygons2 extends JPanel{
public static void main(String[] args) throws InterruptedException{new Polygons2(args);}
double q=Math.PI*2;
int d=1;
public Polygons2(String[] args) throws InterruptedException{
double revolutions=Double.valueOf(args[0])*q;
double stationaryRadius = Double.valueOf(args[1]);
double rollingRadius = Double.valueOf(args[2]);
int stationarySides = Integer.valueOf(args[3]);
int rollingSides = Integer.valueOf(args[4]);
double dist = stationaryRadius+rollingRadius+70;
P sp = new P(dist,dist);
P rp = new P(sp.x,sp.y-rollingRadius-stationaryRadius);
//get points for rolling polygon and stationary polygon
int key=0;
for(double stationaryAngle=-q/4;stationaryAngle<q-q/4;stationaryAngle+=q/stationarySides){
P p=new P(Math.cos(stationaryAngle)*stationaryRadius+sp.x,Math.sin(stationaryAngle)*stationaryRadius+sp.y);
p.k=key;key++;
stationaryPoints.add(p);
}
for(double rollingAngle=q/4;rollingAngle<q+q/4;rollingAngle+=q/rollingSides){
P p=new P(Math.cos(rollingAngle)*rollingRadius+rp.x,Math.sin(rollingAngle)*rollingRadius + rp.y);
p.k=key;key++;
rollingPoints.add(p);
}
double g=(q/2)-((q/2-(q/rollingSides))/2) - ((q/2-(q/stationarySides))/2)-.05;
for(P p:rollingPoints){p.r(getPoint(0), g);}
//set up JFrame
JFrame f = new JFrame();
f.add(this);
f.setSize((int)dist*2+60,(int)dist*2+60);
f.setVisible(true);
int[] pKeys= new int[]{stationaryPoints.get(0).k,rollingPoints.get(0).k};
int index=1;
P rc = rollingPoints.c();
P sc =stationaryPoints.c();
double currentRadian=Math.atan2(rc.y-sc.y,rc.x-sc.x);
double totalRadian = 0;
while(Math.abs(totalRadian)<revolutions){
P rc2 = rollingPoints.c();
P sc2 =stationaryPoints.c();
double angle = Math.atan2(rc2.y-sc2.y,rc2.x-sc2.x);
if(currentRadian-angle<2){totalRadian+=(angle-currentRadian);}
currentRadian=angle;
L clone=(L)path.clone();
clone.add(new P(rollingPoints.get(1).x,rollingPoints.get(1).y));
path = clone;
for(P p:rollingPoints){
p.r(getPoint(pKeys[index]),.01);
int size = stationaryPoints.size();
for(int i=0;i<size;i++){
P stationaryPointAtI = stationaryPoints.get(i);
P nextPoint=null;
if(i==size-1){nextPoint=stationaryPoints.get(0);}
else{nextPoint=stationaryPoints.get(i+1);}
if(p.b(stationaryPointAtI, nextPoint)==1&&containsKey(pKeys,p.k)==0){
//rolling point is between 2 stationary points
if(index==1){index=0;}else{index=1;}
pKeys[index]=p.k;
}
int size2=rollingPoints.size();
for(int h=0;h<size2;h++){
P nextPoint2=null;
if(h==size2-1){nextPoint2=rollingPoints.get(0);}
else{nextPoint2=rollingPoints.get(h+1);}
if(stationaryPointAtI.b(rollingPoints.get(h), nextPoint2)==1&&containsKey(pKeys,stationaryPointAtI.k)==0){
//stationary point is between 2 rolling points
if(index==1){index=0;}else{index=1;}
pKeys[index]=stationaryPointAtI.k;
}
}
}
}
repaint();
Thread.sleep(5);
}
}
volatile L path = new L();
L rollingPoints = new L();
L stationaryPoints = new L();
P getPoint(int key){
for(P p:rollingPoints){if(p.k==key){return p;}}
for(P p:stationaryPoints){if(p.k==key){return p;}}
return null;
}
int containsKey(int[] keys,int key){
for(int i:keys){if(key==i){return 1;}}
return 0;
}
@Override
public void paintComponent(Graphics g){
Path2D.Double sPath = new Path2D.Double();
sPath.moveTo(stationaryPoints.get(0).x, stationaryPoints.get(0).y);
for(P p:stationaryPoints){
sPath.lineTo(p.x, p.y);
}
sPath.closePath();
Path2D.Double rPath = new Path2D.Double();
rPath.moveTo(rollingPoints.get(0).x, rollingPoints.get(0).y);
for(P p:rollingPoints){
rPath.lineTo(p.x, p.y);
}
rPath.closePath();
g.setColor(Color.white);
g.fillRect(0,0,getWidth(),getHeight());
Graphics2D t = (Graphics2D)g;
if(d==1){
t.setColor(Color.black);
t.draw(sPath);
t.setColor(Color.blue);
t.draw(rPath);
}
g.setColor(Color.green);
for(P p:path){g.fillOval((int)p.x-1, (int)p.y-1, 2, 2);}
}
}
```
And the golfed version:
```
import java.awt.*;import java.awt.geom.*;import javax.swing.*;import static java.lang.Math.*;class Polygons2Golfed extends JPanel{public static void main(String[]a)throws Exception{new Polygons2Golfed(a);}double q=PI*2;int d=1;public Polygons2Golfed(String[]a)throws Exception{double b,c,f;b=Double.valueOf(a[1]);c=Double.valueOf(a[2]);int d,e;d=Integer.valueOf(a[3]);e=Integer.valueOf(a[4]);f=b+c+100;P o=new P(f,f);P r=new P(o.x,o.y-c-b);int s=0;for(double u=-q/4;u<q-q/4;u+=q/d){P p=new P(cos(u)*b+o.x,sin(u)*b+o.y);p.k=s;s++;l.add(p);}for(double u=q/4;u<q+q/4;u+=q/e){P p=new P(cos(u)*c+r.x,sin(u)*c+r.y);p.k=s;s++;k.add(p);}double g=q/e/2+q/d/2-.05;for(P p:k){p.r(v(0),g);}JFrame j=new JFrame();j.add(this);j.setSize((int)f*2+60,(int)f*2+60);j.setVisible(true);m=new int[]{l.get(0).k,k.get(0).k};int ad=1;P rc=k.c();P sc=l.c();double ab,ac;ab=atan2(rc.y-sc.y,rc.x-sc.x);ac=0;while(abs(ac)<Double.valueOf(a[0])*q){P rc2=k.c();P sc2=l.c();double ah=atan2(rc2.y-sc2.y,rc2.x-sc2.x);if(ab-ah<2)ac+=(ah-ab);ab=ah;L ag=(L)n.clone();ag.add(new P(k.get(1).x,k.get(1).y));n=ag;for(P p:k){p.r(v(m[ad]),.01);int af=l.size();for(int i=0;i<af;i++){P aa=l.get(i);P w=null;if(i==af-1){w=l.get(0);}else{w=l.get(i+1);}if(p.b(aa, w)==1&&w(p.k)==0){if(ad==1)ad=0;else ad=1;m[ad]=p.k;}int ae=k.size();for(int h=0;h<ae;h++){P u=null;if(h==ae-1)u=k.get(0);else u=k.get(h+1);if(aa.b(k.get(h),u)==1&&w(aa.k)==0){if(ad==1)ad=0;else ad=1;m[ad]=aa.k;}}}}repaint();Thread.sleep(5);}}L n=new L();L k=new L();L l=new L();P v(int key){for(P p:k){if(p.k==key)return p;}for(P p:l){if(p.k==key)return p;}return null;}int[]m;int w(int key){for(int i:m){if(key==i)return 1;}return 0;}@Override public void paintComponent(Graphics g){Path2D.Double aq=new Path2D.Double();aq.moveTo(l.get(0).x,l.get(0).y);for(P p:l){aq.lineTo(p.x, p.y);}aq.closePath();Path2D.Double aw=new Path2D.Double();aw.moveTo(k.get(0).x, k.get(0).y);for(P p:k){aw.lineTo(p.x, p.y);}aw.closePath();g.setColor(Color.white);g.fillRect(0,0,getWidth(),getHeight());Graphics2D t=(Graphics2D)g;if(d==1){t.setColor(Color.black);t.draw(aq);t.setColor(Color.blue);t.draw(aw);}g.setColor(Color.green);for(P p:n){g.fillOval((int)p.x-1,(int)p.y-1,2,2);}}}
```
As well as classes P:
```
import java.awt.geom.*;class P{double x,y;public P(double a,double b){x=a;y=b;}int k;void r(P c,double g){double a,r;a=Math.atan2(y-c.y,x-c.x)+g;r=Math.sqrt((c.x-x)*(c.x-x)+(c.y-y)*(c.y-y));x=Math.cos(a)*r+c.x;y=Math.sin(a)*r+c.y;}public int b(P a,P b){if(Line2D.ptSegDist(a.x,a.y,b.x,b.y,x,y)<.5)return 1;return 0;}}
```
And L:
```
import java.util.*;public class L extends ArrayList<P>{public P c(){double x,y;x=0;y=0;for(P p:this){x+=p.x;y+=p.y;}return new P(x/size(),y/size());}}
```
Change int d to 0 or 1 to show polygons
arguments - 1 100 50 5 2

args - 1.5 100 100 7 3

args - 2 40 100 3 7

[Answer]
# Javascript, 1284 chars (-200 = 1084 chars)
Minified code is
```
function epi(B,r2,r1,n2,n1){K=Math;function C(t){return K.cos(t)}function S(t){return K.sin(t)}function A(y,x){return K.atan2(y,x)}P=K.PI;v=[[],[]];w=[[],[]];z=[];function Z(x,y,j){c=C(t=f*H+P/2);s=S(t);v[j][n]=c*x-s*y;w[j][n]=s*x+c*y;}function E(i){return{x:r1*S(t=p-i*q),y:r1*C(t)};}function D(x,y,X,Y,t){L=A(m.y,m.x);M=K.sqrt(m.x*m.x+m.y*m.y);N=K.sqrt(X*X+Y*Y);O=~~(t*(M>N?M:N)+1);for(i=J;i<=O;i++){J=1;z[n]=f*H+P+t*i/O;Z(x+M*C(T=L+t*i/O),y+M*S(T),0);Z(x+N*C(T=A(Y,X)+t*i/O),y+N*S(T),1);n++}}function F(x,y,n,r,L,s){I.strokeStyle=s;I.beginPath();for(i=0;i<n;i++)I[i?'lineTo':'moveTo'](x+r*C(t=L+(1-2*i)*P/n),y+r*S(t)*W);I.closePath();I.stroke()}p=P/n1;q=2*p;u=P/n2;H=2*u;s2=r2*S(u);g=f=l=n=J=h=0;R=300;while(l<=(B*2+1)*P/H){o=E(0);m=E(h);m.y-=o.y;m.x-=o.x;if(g<s2){D(g,-r2*C(u),-o.x,-o.y,q);h=(h+1)%n1;g+=2*r1*S(p)}else{m.x+=g-s2;D(s2,-r2*C(u),-o.x+g-s2,-o.y,H);g-=s2*2;f=(f+1)%n2;l++}}return function(e_,t,aa,W_){W=aa?-1:1;I=(e=e_).getContext('2d');I.fillStyle='black';I.fillRect(0,0,600,600);W_&1&&F(R,R,n2,r2,0,'white');T=A(w[1][0],v[1][0]);U=V=0;I.strokeStyle='teal';I.beginPath();I.moveTo(R+v[0][0],R+w[0][0]*W);while(U<t){_=A(w[1][V+1],v[1][V+1]);U+=_-T+(_+1<T?2*P:0);T=_;V++;I.lineTo(R+v[0][V],R+w[0][V]*W)}W_&2&&I.stroke();W_&4&&F(R+v[1][V],R+w[1][V]*W,n1,r1,z[V],'red')}}
```
Full code is
```
function epi( nr, r2, r1, n2, n1 ) {
function C( t )
{ return Math.cos( t ); }
function S( t )
{ return Math.sin( t ); }
function A( dy, dx )
{ return Math.atan2( dy, dx ); }
var iCCW, e, t_, xs = [[],[]], ys = [[],[]], ts = [], n = 0, iArc0 = 0;
function addpt( x, y, iBin ) {
var c_ = C(t_ = iFrame*t2 + Math.PI/2 ),
s_ = S(t_);
xs[iBin][n] = c_*x-s_*y;
ys[iBin][n] = s_*x+c_*y;
}
function poly1pt( iP )
{ return { x: r1*S(t_ = t1b2-iP*t1), y: r1*C(t_) }; }
function arc1( P_Arc_, xP_, yP_, xC_, yC_, t ) {
var dx_, dy_, dxC, dyC;
var t0 = A( dy_ = P_Arc_.y, dx_ = P_Arc_.x ),
r_ = Math.sqrt( dx_*dx_ + dy_*dy_ ),
t0C = A( dyC = yC_, dxC = xC_ ),
rC = Math.sqrt( dxC*dxC + dyC*dyC ),
nt = ~~(t*(r_>rC?r_:rC)+1);
for( var i = iArc0; i <= nt; i++ ) {
iArc0 = 1;
ts[n] = iFrame*t2 + Math.PI + t*i/nt;
addpt( xP_ + r_*C(t_ = t0+t*i/nt), yP_ + r_*S(t_), 0 );
addpt( xP_ + rC*C(t_ = t0C+t*i/nt), yP_ + rC*S(t_), 1 );
n++;
}
}
function poly( x,y, n, r, t0, sColor ) {
var Cx = e.getContext('2d');
Cx.strokeStyle = sColor;
Cx.beginPath();
for( var i = 0; i < n; i++ )
Cx[i ? 'lineTo' : 'moveTo']( x + r*C(t_ = t0+(1-2*i)*Math.PI/n), y + r*S(t_)*iCCW );
Cx.closePath();
Cx.stroke();
}
var t1b2 = Math.PI/n1,
t1 = 2*t1b2,
t2b2 = Math.PI/n2,
t2 = 2*t2b2,
s1 = 2*r1*S(t1b2),
s2 = 2*r2*S(t2b2),
xPivot = 0,
iPivot = 0,
iFrame = 0,
P_Pivot, P_Arc,
nFrame = 0;
while( nFrame <= (nr*2+1)*Math.PI/t2 ) {
P_Pivot = poly1pt( 0 );
P_Arc = poly1pt( iPivot );
if( xPivot < s2/2 ) {
P_Arc.x -= P_Pivot.x;
P_Arc.y -= P_Pivot.y;
arc1( P_Arc, xPivot, -r2*C(t2b2), -P_Pivot.x, -P_Pivot.y, t1 );
iPivot = (iPivot+1) %n1;
xPivot += s1;
} else {
P_Arc.x -= (P_Pivot.x - (xPivot - s2/2));
P_Arc.y -= P_Pivot.y;
arc1( P_Arc, s2/2, -r2*C(t2b2), -P_Pivot.x + xPivot - s2/2, -P_Pivot.y, t2 );
xPivot -= s2;
iFrame = (iFrame+1) %n2;
nFrame++;
}
}
function renderTo( eCanvas, t, isCCW, sWhat ) {
iCCW = isCCW ? -1 : 1;
var Cx = (e = eCanvas).getContext('2d');
Cx.fillStyle = 'black';
Cx.fillRect( 0,0, 600,600 );
if( sWhat &1 )
poly( 300,300, n2, r2, 0, 'white' );
var tRef = A( ys[1][0], xs[1][0] ),
tCum = 0,
i0 = 0;
Cx.strokeStyle = 'green';
Cx.beginPath();
Cx.moveTo( 300+xs[0][0], 300+ys[0][0]*iCCW );
while( tCum < t ) {
t_ = A( ys[1][i0+1], xs[1][i0+1] );
tCum += t_ - tRef + (t_ - tRef < -1 ? 2*Math.PI : 0);
tRef = t_;
i0++;
Cx.lineTo( 300+xs[0][i0], 300+ys[0][i0]*iCCW );
}
if( sWhat &2 )
Cx.stroke();
if( sWhat &4 )
poly( 300+xs[1][i0], 300+ys[1][i0]*iCCW, n1, r1, ts[i0], 'red' );
}
return renderTo;
}
```
A fiddle to behold the routine in all its polygony glory (and to demonstrate animation) is found at
<http://jsfiddle.net/7rv751jy/2/embedded/result/>
The script defines a function called `epi` that accepts the five listed parameters in the OP. `epi` returns a function with the signature `(e,t,isCCW,flags)` which accepts arguments:
* `e` - a reference to a 600x600 HTML5 canvas element on which to render
* `t` - the total angle (in radians) that the centroid of the second polygon should sweep around the centroid of the first. The argument passed in should not exceed 2 pi times the number of rotations passed to `epi`.
* `isCCW` - boolean indicating whether the trace should proceed in a counterclockwise direction (as opposed to a clockwise one)
* `flags` - a set of bit flags indicating which elements should be rendered
+ bit 1 - render polygon 1 if set
+ bit 2 - render trace if set
+ bit 3 - render polygon 2 if set
The function can be called any number of times with varying sets of arguments.
**Some Notes:**
* The routine handles the degenerate cases where `n1 = 2` and/or `n2 = 2`. When animating, certain combinations of lengths will cause sudden rapid advances in the trace. This is because the animation frames are indexed by the angle to the centroid of the second polygon, and d theta poly2 / d theta centroid becomes singular in cases where the centroid of 2-sided poly 2 is near a vertex of 2-sided poly 1. This does not affect the trace, however.
* The parameter names in `epi` will seem confusing since throughout development, I referred to polygon 1 as "2", and polygon 2 as "1". When I realized the inconsistency between my convention and that of the OP, rather than swapping all of the indices in the code, I simply swapped the order of the arguments in `epi`.
* The fiddle above imports jQuery, but this is to handle the UI. The `epi` function has no library dependencies.
* The code handles CCW traces by simply inverting the Y axis. This is somewhat inelegant since polygon 2 starts in a Y-inverted position during CCW traces, but nobody said the routine had to be elegant. ;)
[Answer]
# MATLAB: 735 bytes - 200 bonus = 535
My program handles the n=2 case and draws a real-time animation.
There are a few differences between the golfed and ungolfed versions:
The ungolfed version only has an option to save the animation to a file 'g.gif', by setting `savegif = 1` in the code. It is off by default as it can be annoying for a few reasons:
* Creation of an unwanted file
* Possible lag
* An error is generated if you have multiple monitors and the plot window is not on the right one...
The gif saving had to be dropped in the golfed version as it took about 100 bytes, exceeding the size of the bonus.
The ungolfed version draws a circle on the tracer vertex. It also produces more frames and moves faster (though this can be adjusted in the golfed version by changing the numbers).
## Samples:
`f(11,5,90,2,99,0)` after program termination

`epic(1.3,4,2,6,6,1)` with gif output

## Ungolfed code
```
%epicyclogon animation outputs to 'g.gif' if savegif=1 as well as animating in real time
function[] = epic(r,r1,r2,n1,n2,dispPoly)
savegif = 0; %set to 1 to write .gif
cs = @(a) [cos(a);sin(a)];
vert = @(r, n, v) r * cs(2*pi*v/n);
polyPt = @(l, s, n, r) vert(r, n, floor(l/s)) + mod(l/s,1)*(vert(r, n, floor(l/s)+1) - vert(r, n, floor(l/s)));
polyPt2 = @(i, f, n, r) vert(r, n, i) + f*(vert(r, n, i+1) - vert(r, n, i));
rotm = @(a) [cos(a) -sin(a);sin(a) cos(a)];
arrpluspt = @(a, p) a + kron(p, ones(1,length(a)));
arg = @(p) atan2(p(2), p(1));
E = 1e-9;
dispPoly = dispPoly / dispPoly;
sgn = sign(-r);
r = abs(r);
s1 = 2*r1*sin(pi/n1);
s2 = 2*r2*sin(pi/n2);
%d1 = (r1*r1 - s1*s1*.25)^.5;
d2 = (r2*r2 - s2*s2*.25)^.5;
plotmax = r1+2*r2;
astep = .05; %determines amount of frames per rotation
delay = .01; % time per frame
l = 0;
lRem = 0;
lr = 0;
P1 = vert(r1, n1, 1:n1+1) * dispPoly;
trace = [];
first = 1;
while 1
if lr %exists while rotating about a corner of the stationary
rotA = 2*pi/n1;
else
rotA = 2*pi/n2;
end
rotPt = polyPt(l, s1, n1, r1);
lb = l + lRem;
side1 = floor(l / s1 - E);
side1up = side1 + lr;
p2cen = polyPt2(side1, lb/s1 -side1 - .5 * s2/s1, n1, r1) + d2 * cs(2*pi*(side1+.5)/n1);
if first
p2cen0 = p2cen;
r = r + arg(p2cen0)/(2*pi);
end
for a = 0:astep:rotA
P2 = vert(r2, n2, 0:n2);
P2 = rotm( pi +pi/n1 -pi/n2 +2*pi*side1/n1) * P2;
P2 = arrpluspt(P2, p2cen);
P2 = arrpluspt(P2, -rotPt);
P2 = rotm(a) * P2;
P2 = arrpluspt(P2, rotPt);
trV = mod(floor(l/s2 + E) + lr, n2) + 1;
cen = rotm(a) * (p2cen - rotPt) + rotPt;
trace = [trace,P2(:,trV)];
plot(P1(1,:), sgn*P1(2,:), P2(1,:)*dispPoly, sgn*P2(2,:)*dispPoly, trace(1,:),sgn*trace(2,:),P2(1,trV), sgn*P2(2,trV),'o');
%plot(P1(1,:), P1(2,:), P2(1,:), P2(2,:), trace(1,:),trace(2,:),...
%[0,p2cen0(1)],[0,p2cen0(2)],[0,cen(1)],[0,cen(2)], P2(1,trV), P2(2,trV),'o');
axis([-plotmax,plotmax,-plotmax,plotmax]);
axis square
figure(1);
if savegif
drawnow
frame = getframe(1); % plot window must be on same monitor!
img = frame2im(frame);
[img1,img2] = rgb2ind(img,256);
end
if first
if savegif
imwrite(img1,img2,'g','gif','DelayTime',2*delay); %control animation speed(but not really)
end
first = 0;
else
if savegif
imwrite(img1,img2,'g','gif','WriteMode','append','DelayTime', 2*delay);
end
end
pause(.01);
adf = mod(arg(cen) - r*2*pi, 2*pi);
if adf < astep & l/(n1*s1) + .5 > r
return
end
end
%cleanup for next iteration
jump = lRem + ~lr * s2;
lnex = l + jump;
if floor(lnex / s1 - E) > side1up
lnex = s1*(side1up+1);
lRem = jump - (lnex - l);
lr = 1;
else
lRem = 0;
lr = 0;
end
l = lnex;
end
```
## Golfed code
```
function[]=f(r,h,H,n,N,d)
P=pi;T=2*P;F=@floor;C=@(a)[cos(a);sin(a)];g=@(i,f,n,r)r*C(T*i/n)*(1-f)+f*r*C(T*(i+1)/n);R=@(a)[C(a),C(a+P/2)];W=@(a,p)[a(1,:)+p(1);a(2,:)+p(2)];b=@(p)atan2(p(2),p(1));E=1e-9;d=d/d;S=1-2*(r>0);r=-r*S;x=2*h*sin(P/n);X=2*H*sin(P/N);M=h+2*H;l=0;z=0;L=0;A=h*C(T*(0:n)/n)*d;t=[];while 1
v=l/x;D=F(v-E);q=g(D,v-D,n,h);Z=D+L;c=g(D,v+z/x-D-.5*X/x,n,h)+H*cos(P/N)*C(T*D/n+P/n);r=r+~(l+L)*b(c)/T;for a=0:.1:T/(L*n+~L*N)
O=@(p)W(R(a)*W(p,-q),q);B=O(W(R(P+P/n-P/N+T*D/n)*H*C(T*(0:N)/N),c));t=[t,B(:,mod(F(l/X+E)+L,N)+1)];plot(A(1,:),S*A(2,:),d*B(1,:),d*S*B(2,:),t(1,:),t(2,:)*S)
axis([-M,M,-M,M],'square');pause(.1);if.1>mod(b(O(c))-r*T,T)&v/n+.5>r
return;end;end;j=z+~L*X;J=l+j;L=F(J/x-E)>Z;l=L*x*(Z+1)+~L*J;z=L*(J-l);end
```
## Instructions:
Save the function to a file with the same name, i.e. `epic.m` or `f.m`.
Run it by calling the function from the Matlab console.
Usage: `epic(r, r1, r2, n1, n2, dispPoly)`
where `dispPoly` is a Boolean variable (zero if false, a nonzero number if true) determining whether to draw the polygons.
Edit: Added bonus of 50 for animated image.
] |
[Question]
[
[](http://xkcd.com/149/)
Challenge: Write a makefile, which would lead to this behavior:
```
% make me a sandwich
What? Make it yourself
% sudo make me a sandwich
Okay
```
Rules:
1. Should work on a Linux machine, where the user isn't root but allowed to use `sudo`.
2. Must not say `Okay` to any shorter make command (e.g. `sudo make sandwich`).
3. The second command should work because of `sudo`, not because it's the second invocation.
Guidelines:
1. Keep it short (after all, it's a Code Golf site).
2. It would be nice if it would actually make a sandwich.
3. Try to cleverly hide why `sudo` makes a difference.
The winner will be decided by votes.
[Answer]
Okay, I'll bite. This doesn't necessarily adhere to guideline #3, but it does a fair job on the other two guidelines. It also cleans up after itself, as any good sandwich-maker should.
```
.SILENT:
%:%.c
$(CC) -o $@ $^ && rm -f $^
default:
echo 'The makings for a sandwich are here.'
a.c:
echo '#include <stdio.h>' > a.c
echo 'int main() {' >> a.c
echo ' char *txt[] = { "What? Make it yourself.", "Okay." };' >> a.c
echo ' int n = 0;' >> a.c
echo ' while (getchar() != EOF) n ^= 1;' >> a.c
echo ' puts(txt[n]); return 0; }' >> a.c
me.c:
echo '#include <stdio.h>' > me.c
echo '#include <unistd.h>' >> me.c
echo 'int main() {' >> me.c
echo ' char *txt[] = { "/dev/null", "sandwich" };' >> me.c
echo ' puts(txt[!getuid()]); return 0; }' >> me.c
sandwich:
./me | ./a | tee `./me`
rm -f me a
clean:
rm -f sandwich
```
(Less buggy, and hopefully a bit less boring, than my initial submission.)
[Answer]
A fairly compact solution that ignores guideline #2 (127 characters, including some unnecessary whitespace). I follow [breadbox's practice](https://codegolf.stackexchange.com/a/12166) of cleaning up after myself. Don't put any other file in the same directory as the makefile! Also, note that the makefile must be called `Makefile`, other names will not work.
```
me: ; echo echo Okay >$@
a: ; chmod u=x me
sandwich: ; ./me 2>/dev/null || echo 'What? Make it yourself'; rm -f [!M]*
.SILENT:
```
Usage:
```
$ make me a sandwich
What? Make it yourself
$ sudo make me a sandwich
Okay
$ sudo make me sandwich
What? Make it yourself
$ sudo make a sandwich
chmod: cannot access `me': No such file or directory
make: *** [a] Error 1
$ sudo make sandwich
What? Make it yourself
```
I like the way this one deals with guideline #3. Just one press of `Shift` makes the difference.
[Answer]
Not mine, and not a true solution as it violates rule #2, but it has a very interesting story that led me here:
```
# With apologies to XKCD #149
me:
@:
a:
@:
sandwich:
@[ "$$(id -u)" -eq 0 ] && { echo "Okay"; touch sandwich; } || echo "What? Make it yourself!"
```
So, where this came from?
I was just messing with the cloud-init script `/boot/user-data` in Ubuntu 22.04 Server image for Raspberry Pi, when I came into this example snippet:
```
## Write arbitrary files to the file-system (including binaries!)
#write_files:
#- path: /etc/default/console-setup
# content: |
# # Consult the console-setup(5) manual page.
# ACTIVE_CONSOLES="/dev/tty[1-6]"
# CHARMAP="UTF-8"
# VIDEOMODE=
# FONT="Lat15-Terminus18x10.psf.gz"
# FONTFACE=
# FONTSIZE=
# CODESET="Lat15"
# permissions: '0644'
# owner: root:root
#- encoding: gzip
# path: /root/Makefile
# content: !!binary |
# H4sICF2DTWIAA01ha2VmaWxlAFNWCM8syVBILMjPyU/PTC1WKMlXiPB2dlFQNjSx5MpNteLi
# dLDiSoRQxYl5KeWZyRkgXrSCkoqKRmaKgm6pppKCbmqhgoFCrIKamkK1QmpyRr6Ckn92YqWS
# NdC80uQMBZhOa4VahZoaqIrwjMQSewXfxOxUhcwShcr80qLi1Jw0RSUuAIYfEJmVAAAA
# owner: root:root
# permissions: '0644'
```
That binary blob caught my eye... was that an executable? A binary Makefile? It made no sense. Assuming this was plain text with base64 encoding, I tried in a terminal:
```
$ txt='H4sICF2DTWIAA01ha2VmaWxlAFNWCM8syVBILMjPyU/PTC1WKMlXiPB2dlFQNjSx5MpNteLi
> dLDiSoRQxYl5KeWZyRkgXrSCkoqKRmaKgm6pppKCbmqhgoFCrIKamkK1QmpyRr6Ckn92YqWS
> NdC80uQMBZhOa4VahZoaqIrwjMQSewXfxOxUhcwShcr80qLi1Jw0RSUuAIYfEJmVAAAA'
$ printf "$txt" | base64 -d
]�MbMakefileS�,�PH,���O�L-V(�W��vvQP64���M���t��J�Pʼny)��� ^�����Ff��n����nj���B����B�BjrF���vb��5м��
�Nk�Z�������{���T�����Ң�Ԝ4E%.���
```
Ouch, a true binary indeed! What the hell..
Oh, wait... `encoding: gzip`. Hummm...
```
$ printf "$txt" | base64 -d | gunzip
```
Ta-da! The `Makefile` above appears!
What a convoluted Easter Egg from... well, I have no idea! And, what was that all about?
So I read the comic, experimented a bit with that Makefile, finally understood the joke, then googled for "make me a sandwich", and finally arrived here!
[Answer]
This solution doesn't adhere to guideline #2 — or does being vaguely sandwich-shaped count? I went on a kind of palindrome theme at the beginning, but I could only find so many ways to make lines symmetric without resorting to lame `real code # ecod laer`. I didn't take guideline #1 very seriously, aesthetics comes first.
Remember that it's a makefile; the 3 successive lines beginning with `if`, `rm` and `echo` begin with a tab. The other indented lines begin with spaces.
```
me : mr ; env | grep -q DO_US || rm -- mr || SU_OD q- perg | vne ; rm : em
.SILENT:##:TNELIS.
. = a. .a = .
$(.:.=):;:>$@
sandwich:
if expr>/dev/null $$(id -u); then echo 'What? Make it yourself'; fi
rm f- a me mr 2>/dev/null
echo Okay
mr : ; true : ; touch me : em f- mr || rm -f me : em hcuot ; : eurt ; : rm
```
Usage (the commands can be issued in any order):
```
$ sudo make me a sandwich
Okay
$ sudo make me sandwich
make: *** [sandwich] Error 1
$ sudo make a sandwich
make: *** [sandwich] Error 1
$ sudo make sandwich
make: *** [sandwich] Error 1
$ make me a sandwich
What? Make it yourself
make: *** [sandwich] Error 1
```
As for guideline #3, this isn't cleverly hidden, just slightly weirdly. Some hints:
>
> There are two different tests: one search for `SUDO_USER`, and one test of whether `id -u` prints 0. Do you see why `What?` is *not* printed for root? Do you see how the lack of `SUDO_USER` causes `Okay` not to be printed?
>
>
>
[Answer]
Here is a first go using a different and simpler technique:
```
.SILENT:
reset_command:
@rm -f command
me a sandwich: reset_command
@echo $@ >> command
-@make `cat command | tr "\n" "_"` 2>/dev/null
me_a_sandwich_: reset_command
@if [ `whoami` == "root" ]; then echo "Okay"; else echo "What? Make it yourself."; fi
```
I'm pretty sure there is more that I can do with this - get it to respond to other input commands for instance. I'll have to work on the root switch obfuscation and the actual sandwich making.
] |
[Question]
[
## Input
A non-empty binary matrix consisting of 3x3 sub-matrices put side by side.
## Task
Your task is to identify valid dice patterns (as described below) among the 3x3 sub-matrices. Each valid pattern is worth the value of the corresponding dice. Invalid patterns are worth 0.
## Output
The sum of the valid dice values.
## Dice patterns
$$\begin{align}
&1:\pmatrix{\color{gray}0,\color{gray}0,\color{gray}0\\\color{gray}0,1,\color{gray}0\\\color{gray}0,\color{gray}0,\color{gray}0}
&&2:\pmatrix{1,\color{gray}0,\color{gray}0\\\color{gray}0,\color{gray}0,\color{gray}0\\\color{gray}0,\color{gray}0,1}\text{or}\pmatrix{\color{gray}0,\color{gray}0,1\\\color{gray}0,\color{gray}0,\color{gray}0\\1,\color{gray}0,\color{gray}0}\\
&3:\pmatrix{1,\color{gray}0,\color{gray}0\\\color{gray}0,1,\color{gray}0\\\color{gray}0,\color{gray}0,1}\text{or}\pmatrix{\color{gray}0,\color{gray}0,1\\\color{gray}0,1,\color{gray}0\\1,\color{gray}0,\color{gray}0}
&&4:\pmatrix{1,\color{gray}0,1\\\color{gray}0,\color{gray}0,\color{gray}0\\1,\color{gray}0,1}\\
&5:\pmatrix{1,\color{gray}0,1\\\color{gray}0,1,\color{gray}0\\1,\color{gray}0,1}
&&6:\pmatrix{1,\color{gray}0,1\\1,\color{gray}0,1\\1,\color{gray}0,1}\text{or}\pmatrix{1,1,1\\\color{gray}0,\color{gray}0,\color{gray}0\\1,1,1}
\end{align}$$
## Example
The expected output for the following matrix is **14** because it contains the dice **5**, **6** and **3**, followed by an invalid pattern (from left to right and from top to bottom).
$$\pmatrix{1,0,1,1,1,1\\
0,1,0,0,0,0\\
1,0,1,1,1,1\\
1,0,0,0,0,0\\
0,1,0,0,1,0\\
0,0,1,0,1,0}$$
## Rules
* Both the width and the height of the matrix are guaranteed to be multiples of 3.
* You must ignore sub-matrices that are not properly aligned on the grid (see the 3rd test case). More formally and assuming 0-indexing: the coordinates of the top-left cell of each sub-matrix to be considered are of the form \$(3x, 3y)\$.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'").
## Test cases
```
// 0
[ [ 1,0,0 ],
[ 0,0,1 ],
[ 1,0,0 ] ]
// 2
[ [ 0,0,1 ],
[ 0,0,0 ],
[ 1,0,0 ] ]
// 0 (0 + 0)
[ [ 0,0,1,0,1,0 ],
[ 0,0,0,1,0,0 ],
[ 0,0,1,0,1,0 ] ]
// 9 (3 + 3 + 3)
[ [ 1,0,0,0,0,1,1,0,0 ],
[ 0,1,0,0,1,0,0,1,0 ],
[ 0,0,1,1,0,0,0,0,1 ] ]
// 6 (6 + 0)
[ [ 1,0,1 ],
[ 1,0,1 ],
[ 1,0,1 ],
[ 1,0,1 ],
[ 1,0,0 ],
[ 1,0,1 ] ]
// 14 (5 + 6 + 3 + 0)
[ [ 1,0,1,1,1,1 ],
[ 0,1,0,0,0,0 ],
[ 1,0,1,1,1,1 ],
[ 1,0,0,0,0,0 ],
[ 0,1,0,0,1,0 ],
[ 0,0,1,0,1,0 ] ]
// 16 (1 + 2 + 3 + 4 + 0 + 6)
[ [ 0,0,0,1,0,0,1,0,0 ],
[ 0,1,0,0,0,0,0,1,0 ],
[ 0,0,0,0,0,1,0,0,1 ],
[ 1,0,1,1,1,1,1,0,1 ],
[ 0,0,0,1,0,1,1,0,1 ],
[ 1,0,1,1,1,1,1,0,1 ] ]
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~195~~ 189 bytes
*-6 bytes thanks to @Jo King*
```
lambda m:sum({16:1,257:2,68:2,273:3,84:3,325:4,341:5,455:6,365:6}.get(int(''.join(str(e)for c in m[3*i:][:3]for e in c[3*j:][:3]),2),0)for i in range(len(m)//3)for j in range(len(m[0])//3))
```
[Try it online! (189)](https://tio.run/##jVLLboMwELzzFXuLqVaJjYFElvIlrg80dVJQMBHQQ1X126nNowkGRRVi5d2ZHXbN3L7aj8rw7nx87a5Z@faeQSmaz5J8s1QwjJK9iDA92BDtueB4iG3gUSJi5DETCcZJIlLkqY0/24tuSW5astlsiyo3pGlrosNzVcMJcgOl5C@5UFJw5Wra1U62Vgy1EKMQaU/PHVRn5qLJVRtShrsd74HCAyRVPRZ2rW7aBo4gAwkSGFKkoDAAm9gjsikZEZdKH6OPXWvE4Z3RcfmpiTW19oyR67HZXcJXHrk4TvgoNlvmnwn1kJne8Phj@U1z1n26tX2eXgidb70UoGsys66VwZAt/iWyv4t81gFKBc5dzkPOYL2XhGUD3Gpn6DNxJeuyXw "Python 3 – Try It Online")
[~~Try it online! (195)~~](https://tio.run/##jVLLboMwELzzFXuLaVeJjYFElvIlLgeamgQUTAT0UFX9dmrzaIJBUYW8Ymdmh12zt6/2UmneZce37pqW7x8plKL5LMk3iwXDINqLAOODCcGeC46H0AQeRCJEHjIRYRhFIkYem/izPauW5Lolm822qHJNmrYmyoesquEEuYZS8pdcmPPKkx5VFj0ZtDBoYVAfAx/pUJJbsk71WZGr0qT0dzs@MIXDSJr0pN@1qmkbOIL0JEhgSJFCgh6YxLwim5KRsal0OfpYtSYczkyOy09Nqqm0V4xaR83uFq7zqMWxw0ez2TD/TKjDzPyGx23LLZqr7t2tzfP0Quh86qUBXbOZVa00hmzxL5H9XeSzCkgSz26X3SG7YP0uCaMGuNV2rTNiIbNlvw "Python 3 – Try It Online")
### Human readable version:
```
# 3x3 part matrix to dice, beginning at coordinates 3*i, 3*j
def single_matrix_to_dice(matrix, i, j):
# Example: matrix = [[0, 0, 0], [0, 1, 0], [0, 0, 0]], i=0, j=0 (result is 1)
matrix_string = ''.join(
str(e) for column in matrix[3*i:3*i+3]
for entry in column[3*j:3*j+3]
) # Slicing the matrix so that only the valid entries remain, here '000010000'
# Interpreting the matrix string as binary number, here 16
binary_number = int(matrix_string,2)
# binary representations of all valid dice rolls
dct = {16:1,257:2,68:2,273:3,84:3,325:4,341:5,455:6,365:6}
return dct.get(binary_number, 0)
def f(matrix):
return sum(
single_matrix_to_dice(matrix, i, j) for i in range(len(m)//3)
for j in range(len(m[0])//3))
) # len(m)/3 would generate a float, so len(m)//3 is used
```
[Answer]
# [R](https://www.r-project.org/), 134 bytes
```
function(m,d=dim(m)/3-1){for(a in 0:d)for(b in 0:d[2])F=F+sum(y<-m[1:3+a*3,1:3+b*3])*sum(y*2^(8:0))%in%utf8ToInt("āDđTŅŕLJŭ");F}
```
[Try it online!](https://tio.run/##jVLNTuMwEL7nxCOMQCgzrcvaDVtBl2gvbKW9onJKs1JKHYjUJChxpSLgwAFx3gOPwVtQ8VjFaU1okwihyHYcz/c3Trbcgys5vZYZhLPkQkVpAiqFS6kgDlQWzSHM0hiUzBVcBLnMrXgOJ52yGNVc0a0FoNfi@2U@G6ONo5FHd3r29Qx0x/C3OxolZDPbZrqSab2pOzw7/0MaGuQHay3MZDA5UMF4KlHJuXKL0lxeuxpHZN1bobsshWM2cSdRjDH9cDqCbsM0wwCiBHh/QsVmbDZe16eBO2jnsxhvTjqxJ/pOO2g5rFjHLcen1uqo1f2HR31OtB8l@zMVHg3Tv4nC3Z3Xh9PX/8PF4@L57Wnxsku/Bve6a9wKUTcDbQ88EIwzDj7TaTzQr0x8bMwJ@EUCaw@6BmatcFulfJOkiuOAHNrAaVN2BV@PLRJW9/NRVRIeAzqacDWolsWwVHjEJ3lV09Qyk6iU6QH2ar5FtUPf3PDKSakiDgF/apmeSdQgt36qWaqc21WfkZqa8HV/hU4utJWusXRY2Cos1m5wq68NBpsueAPV4J@J2n/FRHlJXyGM/eU7 "R – Try It Online")
I noticed I had the same idea of @Heteira
History :
* ~~171~~ : -10 bytes thanks to @JayCe !
* ~~161~~ : -3 bytes thanks to @Giuseppe !
* ~~158~~ : -13 bytes saved !
* ~~145~~ : -2 bytes thanks to @Giuseppe!
* ~~143~~ : -6 bytes saved !
* ~~137~~ : -3 bytes thanks to @JayCe!
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~113 105 97~~ 94 bytes
```
{sum (|@_[*;^3+3*$_]for ^@_[0]).rotor(9).map:{"@āđŅŕLJ@@DT@@ŭ".ords.first(:2[$_],:k)%7}}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv7q4NFdBo8YhPlrLOs5Y21hLJT42Lb9IIQ4oYhCrqVeUX5JfpGGpqZebWGBVreQgcKTxyMSjrUenHm93cHAJcXA4ulZJL78opVgvLbOouETDyigaaIKOVbamqnlt7f/ixEqFNI1ohWgFQx0DHQOFWB0uBSAHyNQxhHGgMgqxmtZcXAgNKGoMkHXj0wDBKNp0MK2GqUI3AqwSqgdNlyHCKHQboGp1oC7GZiiKZ4nkGKDJYDUXAtGdia4ZVRXCtdj8R1RAGaCGBqZBBtiMQ9GFxYE6hhhxrmMID2B8OsDu@w8A "Perl 6 – Try It Online")
Splits up the matrix into sub matrices of 3x3, converts the nine 1s and 0s to base 2 and then indexes it into a list of integers for the value.
### Explanation:
```
{ #Start anonymous code block
sum # Sum of all
(|@_[*;^3+3*$_] # Get the n*3 to n*3+3th elements in every sub-list
for ^@_[0]) # For n in the range 0 to width (divide by 3 to avoid warnings)
.rotor(9) # Split this list into groups of 9 (split the dice up)
.map:{ # And map each die to
"@āđŅŕLJ@@DT@@ŭ".ords # In the list of integers
.first( # The first appearance of
:2[$_], # The dice converted from a list of 0s and 1s to base 2
:k # Returning the index
)%7 # And modulo by 7 to get the alternate versions of 2, 3 and 6
}
}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~29~~ 28 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 thanks to Mr. Xcoder (use `Ṁ` to replace `ṢṪ`)
```
s€3ZẎs3µZU,ƊṀṙ1FḄ“°€⁼-Ḍ?‘i)S
```
A monadic link.
**[Try it online!](https://tio.run/##y0rNyan8/7/4UdMa46iHu/qKjQ9tjQrVOdb1cGfDw50zDd0e7mh51DDn0AaggkeNe3Qf7uixf9QwI1Mz@P///9EK0QoGOiBoiCAVYnW4FMASEEG4AoQEkiCIhEkYgoVgEEkCoRpNAosOhVgA "Jelly – Try It Online")** Or [run the tests](https://tio.run/##y0rNyan8/7/4UdMa46iHu/qKjQ9tjQrVOdb1cGfDw50zDd0e7mh51DDn0AaggkeNe3Qf7uixf9QwI1Mz@P/hdqDY///RXNEK0QqGOgY6BgqxOlwKQA6QqWMI40BlFGK5dMAqUSQNkLVhVQnBKOp1MC2DqYLrBSuBKkZTbogwA91oqFodqBtRTEPxEJEcAzQZVAMhEN1h6LpQVSHch81H@MPEANXjmCYYYDMHRRcWl@kYYkSojiE8LPHpADosFgA "Jelly – Try It Online").
### How?
```
s€3ZẎs3µZU,ƊṀṙ1FḄ“°€⁼-Ḍ?‘i)S - Link: list of lists of 1s and 0s
s€3 - split each into threes
Z - transpose
Ẏ - tighten
s3 - split into threes -> the sub-matrices in column-major order
µ ) - for each sub-matrix, say D:
Ɗ - last three links as a monad:
Z - transpose D
U - reverse each -> D rotated a quarter turn clockwise
, - pair with D
Ṁ - get the maximum of the two orientations
ṙ1 - rotate left by one (to ensure FḄ will yield integers <256 for all non-zero valued D)
F - flatten
Ḅ - convert from binary
i - first 1-based index in (0 if not found):
“°€⁼-Ḍ?‘ - code-page indices list = [128,12,140,45,173,63]
S - sum
```
For example when a sub-matrix is:
```
[[1,0,1],
[1,0,1],
[1,0,1]]
```
Then `ZU,Ɗ` yields:
```
[[[1, 1, 1],
[0, 0, 0],
[1, 1, 1]], ...which has maximum (Ṁ): ...and after ṙ1:
[[1, 0, 1], [[1, 1, 1], [[0, 0, 0],
[1, 0, 1], [0, 0, 0], [1, 1, 1],
[1, 0, 1]]] [1, 1, 1]] [1, 1, 1]]
```
...which flattens to `[0, 0, 0, 1, 1, 1, 1, 1, 1]`, which, converting from binary, is `63` which is the sixth entry in the code-page index list `“°€⁼-Ḍ?‘` (`?` being byte `3F` in [Jelly's code-page](https://github.com/DennisMitchell/jelly/wiki/Code-page))
[Answer]
# [Japt](https://github.com/ETHproductions/japt) `-x`, 36 bytes
*Now it's getting interesting. I'm sure can be golfed down even more*
```
ò3 ®®ò3Ãy f@"0ıtŵġdťƍǧ"øºXm¬¬Í+H)d
c
```
[Try it online!](https://tio.run/##y0osKPn///AmY4VD6w6tA9KHmysV0hyUDI5sLDm69cjClKNLj/UeX650eMehXRG5h9YcWnO4V9tDM4Ur@f//aIVoBQMdEDREkAqxOlwKYAmIIFwBQgJJEETCJAzBQjCIJIFQjSaBRQcQ6lYAAA "Japt – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 90 bytes
```
+`(...)(.+¶)(...)(.+¶)(...)
$1¶$3¶$5¶$2$4
¶
M!`.{9}
G`111000111|(101){3}|(.)0(.0).0\3\2
1
```
[Try it online!](https://tio.run/##XYq7DcJAEETz7QLpgl1ZWs34IKACInfg4AgISAgQme22roBr7FhbRATz5qN5Pz7P1733oai7m/rQqv1HSWw15dAlNKaztCoynYov101uhSSA4KoEbcnbqm5QhznmPI/C3rkfKNivkF87Co6RYQHiCw "Retina 0.8.2 – Try It Online") Explanation:
```
+`(...)(.+¶)(...)(.+¶)(...)
$1¶$3¶$5¶$2$4
```
Repeatedly remove \$3\times 3\$ blocks from each \$3\times n\$ row until all rows have 3 columns.
```
¶
M!`.{9}
```
Join all the blocks together and then split back up into rows of 9 columns.
```
G`111000111|(101){3}|(.)0(.0).0\3\2
```
Only keep valid dice patterns (two patterns for `6`, then one matches any number from `0` to `5`, although `0` of course will not contribute to the count below.)
```
1
```
Count the pips on the valid dice.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `d`, 34 bytes
```
3ẇƛƛ3ẇ;ÞTvf;f9ẇ'†B»@uS∨∪ċ#»b9ẇvB$c
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=d&code=3%E1%BA%87%C6%9B%C6%9B3%E1%BA%87%3B%C3%9ETvf%3Bf9%E1%BA%87%27%E2%80%A0B%C2%BB%40uS%E2%88%A8%E2%88%AA%C4%8B%23%C2%BBb9%E1%BA%87vB%24c&inputs=%5B%20%5B0%2C0%2C0%2C0%2C0%2C1%5D%2C%20%5B0%2C1%2C0%2C0%2C0%2C0%5D%2C%20%5B0%2C0%2C0%2C1%2C0%2C0%5D%2C%5B0%2C0%2C1%2C1%2C0%2C1%5D%2C%20%5B0%2C1%2C0%2C0%2C0%2C0%5D%2C%5B1%2C0%2C0%2C1%2C0%2C1%5D%20%5D&header=&footer=)
A mess.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 151 bytes
```
->m{m.each_slice(3).flat_map{|r|r.transpose.each_slice(3).map{|d|" \x10āđŅŕLJ DT ŭ".chars.map(&:ord).index(d.flatten.join.to_i 2)&.%7}-[p]}.sum}
```
[Try it online!](https://tio.run/##jVPdasIwFL7vUxwck5TFkKhzbOCu9gi760rp2ood9ocmgsP2Yhdj17vYY@wtlD1WbWs0NhYZIZCTfN93vpOTZMvX93I2LQeP0ToigevNHb4IvQCNTDJbuMKJ3HSdZ3lGRObGPE14oKEagJ/34GXF6OZj87393P78fQE8PQNsf3vEm7sZr2Go/5BkvknC2A9WyG/0RRCTtySMiUicEIZmn1zfFQMrtQvCl1FRioALx3N5wGEKlnEF1LDAAoYppmBjA6qgWmJ2CORJHVboYYNuAegptY2mgCjcADUVaz9bXHye/ICSOveARpVOM03lV5I1OlOaeiqJxdK/VJ8AmiiXTC/@nwHVTqQ4GwO6rdQn0v9plv3QnetSbZQqoKvkS5fIqjpZ5WAonYxrN7Uz1Z3W5XX46mreCavDNmZnTwWzYycuMcA2bMNQz7X5Jev8uJFDuhQcZtZxx4ai3AE "Ruby – Try It Online")
A lambda accepting a 2d array of ints (or strings, I guess). Takes inspiration from [Jo King's answer](https://codegolf.stackexchange.com/questions/169919/how-much-is-my-dice-matrix-worth/169926#169926). I feel like slicing the dice out of the input matrix took a lot of space, so I may well be outgolfed. Fortunately, dealing with nils only cost me a handful of bytes.
Ungolfed:
```
->m{
m.each_slice(3).flat_map{|r| # Split into groups of 3 rows
r.transpose.each_slice(3).map{|d| # Split into groups of 3 columns
" \x10āđŅŕLJ DT ŭ".chars.map(&:ord) # [0,16,257,273,325,341,455,0,0,68,84,0,0,365]
.index( # Find in that array
d.flatten.join.to_i 2 # the die flattened into a bitstring (nil if not found)
)&.%7 # Safe-modulo 7 (leaves nils as nil)
}-[p] # Remove nils
}.sum # Add 'em up
}
```
[Answer]
## Clojure, 197 bytes
```
#(apply +(for[R[range]i(R 0(count %)3)j(R 0(count(% 0))3)](case(apply +(map *(iterate(partial * 2)1)(for[x(R 3)y(R 3)]((%(+ i x))(+ j y)))))16 1 257 2 68 2 273 3 84 3 325 4 3 4 1 5 455 6 365 6 0)))
```
I should have come up with something smarter.
[Answer]
# [Python 2](https://docs.python.org/2/), 159 bytes
```
f=lambda a:a>[]and sum(u'ȀāDđTŅȀŕȀLJŭ'.find(unichr(int(J(J(map(str,r[i:i+3]))for r in a[:3]),2)))/2+1for i in range(0,len(a[0]),3))+f(a[3:])
J=''.join
```
[Try it online!](https://tio.run/##jVI9b8IwEJ2bqT/hJIbYikt9CUVtJCohdWLuFmVwgYArMCgkQzc6VJ079Gf0X4DKv6IOmI8kFqoiS8@@e@/e3WX@lo1nyt82oD8bSDUKIc@Sm/tt0pmI6ctAgAjFYxQLNYBFPiW5e71Zrt6fVl/P64/Ncv29Wf5@rn/cZiLVgORK9scpkSojPf1NxZwsspSlkQylF8SUJrMUUpAKRBTqO/Mppbe@h8W7LN5ToUZDwtlkqIiIuE4JKPUSjYMwpk6v47rN15lU2i935qmuBAmJIAJknHGImQP6oiHDw8VEQNOdBvglVimRn0uUWRwIBw84rbP3p6TB6mYOWUbvAUig9XaH1vswIhUZPGlXS5pcZvoxVdpA2nXXWB3OPy@8EjFFsAXkTldpm35s1fZftZOqZDnr1JBtBJeGi7pv1E5846hVuCoc1rdXGqrFn225ZyyLfYa1X4rhcUOXGDv3TrcTwVW04@nUAuER7d80xLPwOUIL2kfRTsaLZKyQrwy2ieNJ3Eavhe0ILdrFmxM7x9116Xb7Bw "Python 2 – Try It Online")
Hat tip to [Jonathan Frech](https://codegolf.stackexchange.com/users/73111/jonathan-frech) for the unicode encoding approach.
] |
[Question]
[
# The Challenge
There are N cities aligned in a straight line. The i-th city is located `A[i]` kilometers to the right of the origin. No two cities will be in the same place.
You are going to build an electrical grid with some power plants. Power plants must be built inside a city. However, you are only allowed to build `K` (< N) power plants, so there will be some cities with no power plants in them. For each city with no power plants, you must build a cable between it and **the nearest city that has a power plant**.
For example, if there are three cities located at `0, 1, 2`, and only the city at `0` has a power plant, you need to build two cables, one from `2` to `0`(2km) and the other from `1` to `0`(1km), which have a total length of 3km.
Given `K` and positions of cities (`A`), you should compute the minimum kilometers of cable you need to build the grid.
# Example Testcases
```
K = 1, A = [0, 2, 4, 6, 8] : 12
# build power plant in the city at position 4, total length = 4 + 2 + 0 + 2 + 4 = 12
K = 3, A = [0, 1, 10, 11, 20, 21, 22, 30, 32] : 23
# build power plants in cities at positions 0, 10 and 22
K = 5, A = [0, 1, 3, 6, 8, 11, 14] : 3
# build power plants in all cities except those at positions 0, 3
K = 6, A = [0, 1, 3, 6, 8, 14, 15, 18, 29, 30, 38, 41, 45, 46, 49, 58, 66, 72, 83, 84] : 49
```
# Specifications
* You should implement a function or a program, which takes a positive integer `K` and a list of integers `A` in any form, and output/return an integer representing the answer.
* `A` is sorted in ascending order, and all elements are non-negative integers.
* `A[0] = 0`, and `A[N-1]` will be no more than 1000N.
* Note that the output will be in magnitude of 1000N2, so in larger cases, you may need 64-bit integers in some languages.
* Multithreading is **not** allowed (I will set the affinity of your program to only 1 core when judging). Compiler optimizations (such as `-O2` in C) are allowed.
# Scoring
* I will time your code on my computer (Ubuntu 16.04 with Intel i7-3770S processor) with different size of testcases. Specifically, I will generate some testcases with N = floor(2x/5) where x is a positive integer.
Your score will be the x value of the smallest testcase that your program uses more than 10 seconds or 1 GiB of memory, or doesn't give a correct answer.
+ The answer with highest score wins. If two answers get the same score, the earlier answer wins.
* All programs will be judged by the same set of testcases.
* Feel free to post your own scorings. Explanations of your algorithm are encouraged.
# Bonus
[This](https://tio.run/##lVZbr9pGEH7Gv2KaKsg@NpRL1arcnnjj0ojXxIp8fAEnaxvZ5pxIR/z10m9m19gkbaUiYdYz33xz3V3C83lwDMPb7ec0D9UlimkRVnWUFiurlQTqWJRpfcpWlhUWeVVTmte029OSpiP@TOdWVZeXsKaqUC9xSW9WTxX5keRRXbKPu70/t3oGFBbZM71Ri3iZC2MwpytF50dwGeTHGGgGKI/OjCmPBsPCeutRfZhbXZevNmtST6y@OBxPr4zrS5lLNKlPriy@@DSQhZ1CAuAvNHkU4TvWYri7wokEHwbKbr190H72jtVjR8hg5KM2byOPRleY9eotXusDHiN@Rfj1wXU7GBKRP1QQ7dklp9MLLnVBCUQf@/73CZFJB85Sf/gCG@TsQYX6zBvb8BSHXzv2gbZ/1j9phyaxWefQaokl6xuepChJ@wbPeI5Gua6uZ09ccw6JzeFv/eFZOFwuCJSN0B8GnJLQ9dIEdLREmk4nBWmmVooV47kaiyWlugP11nUfMY3eofurQQvu9ZSqmGxw/SS17/d1OcT4gB6PdbwedQTKgafDYHD3xJ1jc@2kaZp4ga1OKVZVTE1YDRF7bZpq6iXTykF2cXBPLfIefRO@SGhBZcMhJBlMRFXKaM6NBiH8S4oZvyA39pUZuIStWsFVnt001T1F0f04o6K4Puw8OQBkYPZ6yjZeu9GfaG32iOwiTn7eOQayb6AeoLBZjsXvCv1d0G@jH8ZwhClETfZmGGVHy8RAd9/ea/zILmr5eRdivx0MbO83WZhib02xD6bYreWOC87qQ1twSaGMK6j4ONhxiT2MdTulcYXJX9Gm6R373@lisx7pLkjMHJ26oZARiau28O2ACeOiZTx8x5jDXcOYt4zlPzKa7cekL8Bt6Il0Fo7pbKcAa6EQ3Ba4cojjYs2BKpGhNuL0Ce/BvD1s1zykNowHWLLa3mAJDJfRBot5k7MVo3Yz90eCznWc69O@cyOFp7LIH@6oCtdFHGRdUVpkQZ6ecWm9FGlkJtOx3vS1gfHc8C0TBnliv3sfvY/eedSHtL/hcLicez5fUOsa3l55lv5zCg2RUky0Rt6p48kU8sFl6QO5qoOy5vGro9lMJzGbndLj6TO6UKhLnRb551AV4dfZLC9ebY7kXMKjYf6UgzsZ6lQ4A3hwGCTscR79T@4HbHQpAwYtouLyrOIVRWnCtw/TDnTonEgbT0JVjP8DUSVhMXoYFpe8tjkkHAtyVAVpLkUnfEwLoLz9QVNrhN02xmNMkxFN8Jzg/wRNJ3@FiQqO1W3w5/Q2QIjL0HXHv/4N) is my C++ program, it scores **108**. You can verify the SHA-256 digest `9a87fa183bad1e3a83d2df326682598796a216b3a4262c32f71dfb06df12935d` by the whole code segment (without footer) in the link.
The algorithm combines binary search and Knuth's optimization to find the correct penalty of each plant to get the desired number. The complexity is O(N log N log A[N-1]). I was surprised that the program got a higher score than the [O(N log A[N−1]) solution by Anders Kaseorg](https://codegolf.stackexchange.com/a/149780/75905). It's probably due to the fact that the log case in Knuth's optimization won't usually occur.
Note that this challenge is the same as [IOI 2000 Post Office](http://www.ioinformatics.org/locations/ioi00/contest/day2/post/post.pdf). The original constraints are N <= 300 and K <= 30, though.
[Answer]
# [Rust](https://www.rust-lang.org/), score = 104
This is an implementation of the algorithm noted by [Grønlund et al. (2017)](https://arxiv.org/abs/1701.07204) at the end of §3.3.1, though I had to follow a long citation chain and fill in some missing details. It runs in *O*(*N* log *A*[*N* − 1]) time.
Compile with `rustc -O`. Input format is `K` on the first line, followed by the entries of `A`, one entry per line, all on stdin.
(Note: I’m submitting this an hour after the bounty deadline, but I expect the [last version I submitted before the bounty deadline](https://codegolf.stackexchange.com/revisions/149780/16), which ran in *O*(*N* log *N* log *A*[*N* − 1]) time, to score about 94.)
```
use std::cmp::min;
use std::io::{self, BufRead};
use std::iter::{once, Cloned};
use std::num::Wrapping;
use std::ops::Range;
use std::slice;
use std::time::Instant;
use std::u64;
type Cost = u64;
const INF: Cost = u64::MAX;
trait ColsTrait<Col>: Clone {
type Iter: Iterator<Item = Col>;
fn len(&self) -> usize;
fn iter(&self) -> Self::Iter;
fn slice(&self, range: Range<usize>) -> Self;
}
impl<'a, Col: Clone> ColsTrait<Col> for &'a [Col] {
type Iter = Cloned<slice::Iter<'a, Col>>;
fn len(&self) -> usize {
(*self).len()
}
fn iter(&self) -> Self::Iter {
(*self).iter().cloned()
}
fn slice(&self, range: Range<usize>) -> Self {
unsafe { self.get_unchecked(range) }
}
}
impl ColsTrait<usize> for Range<usize> {
type Iter = Range<usize>;
fn len(&self) -> usize {
self.end - self.start
}
fn iter(&self) -> Range<usize> {
self.clone()
}
fn slice(&self, range: Range<usize>) -> Self {
Range {
start: self.start + range.start,
end: self.start + range.end,
}
}
}
fn smawk<Col: Copy, Cols: ColsTrait<Col>, Key: Ord, F: Copy + Fn(usize, Col) -> Key>(
n: usize,
shift: u32,
cols: Cols,
f: F,
) -> Vec<usize> {
if n == 0 {
Vec::new()
} else if cols.len() > n {
let mut s = Vec::with_capacity(n);
let mut sk = Vec::with_capacity(n);
for (jk, j) in cols.iter().enumerate() {
while match s.last() {
Some(&l) => f(!(!(s.len() - 1) << shift), j) <= f(!(!(s.len() - 1) << shift), l),
None => false,
} {
s.pop();
sk.pop();
}
if s.len() < n {
s.push(j);
sk.push(jk);
}
}
smawk1(
n,
shift,
cols,
f,
smawk(n / 2, shift + 1, &s[..], f)
.into_iter()
.map(|h| unsafe { *sk.get_unchecked(h) }),
)
} else {
smawk1(
n,
shift,
cols.clone(),
f,
smawk(n / 2, shift + 1, cols, f).into_iter(),
)
}
}
fn smawk1<
Col: Copy,
Cols: ColsTrait<Col>,
Key: Ord,
F: Fn(usize, Col) -> Key,
Iter: Iterator<Item = usize>,
>(
n: usize,
shift: u32,
cols: Cols,
f: F,
iter: Iter,
) -> Vec<usize> {
let mut out = Vec::with_capacity(n);
let mut range = 0..0;
for (i, k) in iter.enumerate() {
range.end = k + 1;
out.push(
range
.clone()
.zip(cols.slice(range.clone()).iter())
.min_by_key(|&(_, col)| f(!(!(2 * i) << shift), col))
.unwrap()
.0,
);
out.push(k);
range.start = k;
}
if n % 2 == 1 {
range.end = cols.len();
out.push(
range
.clone()
.zip(cols.slice(range.clone()).iter())
.min_by_key(|&(_, col)| f(!(!(n - 1) << shift), col))
.unwrap()
.0,
);
}
out
}
fn solve(k: usize, a: &[Cost]) -> Cost {
if k >= a.len() {
return 0;
}
let sa = once(Wrapping(0))
.chain(a.iter().scan(Wrapping(0), |s, &x| {
*s += Wrapping(x);
Some(*s)
}))
.collect::<Vec<_>>();
let c = |i: usize, j: usize| {
let h = (i - j) / 2;
unsafe {
(sa.get_unchecked(i) - sa.get_unchecked(i - h) - sa.get_unchecked(j + h)
+ sa.get_unchecked(j))
.0
}
};
let cost1 = c(a.len(), 0);
if k == 1 {
return cost1;
}
let cost2 = (1..a.len()).map(|j| c(j, 0) + c(a.len(), j)).min().unwrap();
let mut low = 0;
let mut high = cost1 - cost2;
let mut ret = INF;
while low <= high {
let penalty = low + (high - low) / 2;
let mut out = vec![(INF, 0); a.len() + 1];
out[0] = (0, 0);
let mut begin = 0;
let mut chunk = 1;
loop {
let r = min(a.len() + 1 - begin, 2 * chunk);
let edge = begin + chunk;
let (out0, out1) = out.split_at_mut(edge);
let f = |i: usize, j: usize| {
let h = (edge + i - j) / 2;
let &(cost, count) = unsafe { out0.get_unchecked(j) };
(
cost.saturating_add(
unsafe {
sa.get_unchecked(edge + i) - sa.get_unchecked(edge + i - h)
- sa.get_unchecked(j + h)
+ sa.get_unchecked(j)
}.0 + penalty,
),
count + 1,
)
};
for ((i, j), o) in smawk(r - chunk, 0, begin..edge, &f)
.into_iter()
.enumerate()
.zip(out1.iter_mut())
{
*o = min(f(i, begin + j), *o);
}
let x = unsafe { out1.get_unchecked(r - 1 - chunk) };
if let Some(j) = (edge..begin + r - 1).find(|&j| &f(r - 1 - chunk, j) <= x) {
begin = j;
chunk = 1;
} else if r == a.len() + 1 - begin {
break;
} else {
chunk *= 2;
}
}
let &(cost, count) = unsafe { out.get_unchecked(a.len()) };
if count > k {
low = penalty + 1;
} else {
ret = cost.wrapping_sub(k as Cost * penalty);
if count == k {
return ret;
}
high = penalty - 1;
}
}
ret
}
fn main() {
let stdin = io::stdin();
let mut lines = stdin.lock().lines();
let k = lines.next().unwrap().unwrap().parse().unwrap();
let a = lines
.map(|s| s.unwrap().parse().unwrap())
.collect::<Vec<_>>();
let start = Instant::now();
let cost = solve(k, &a);
let time = start.elapsed();
println!(
"cost: {}\ntime: {}.{:09} sec",
cost,
time.as_secs(),
time.subsec_nanos()
);
}
```
[Try it online!](https://tio.run/##1Vhtb9s2EP7uX3EtsFRyFM3OimJTbANbgQLFsBZoh21AFhisTMeyZUowpTpp7L@@7O4oydSLk2zrl7lAKvGOx3t97qhNrrP7@1xL0NksCMJ1GgTrSF30qqUoCYI7LeO5Bz/l8w9SzPY2NZMbpCcqlB68jhMla2SVr4Pg941I00hdW@tJqoPgg1DX0lrUcRTa71m0lkHwVulMqMxaz1@9vOj1sttUwutEZzAGXgkT5IS3794E1nIQ/PLjH8S9EVGG67H@lZ5G@DQJjMJw1wP8sby3ZA7/FVmyGeHDGuUQ8wUzzRXEUjkn5A8XziaQ6@iLrGjkDYv4ER/QAFysONhGw@LBhhwQAPthxJIm1b6L3r7Xi9ZpPHohPNKg0HbSMALmyQZOXgi4xLerpi2kPAdlxAcbZUqJkweNKkTRz@kzyScul1f3j1rcsZ15XT9khZqCnuwYS3CutJijokC7/GuZTXMVLmS4QvEswi3k70tnWs4zYtl99jkdHrTJT/QYKyTVDM7MI6bwJnvQcx06VILYY1/DYUy33vkEUi2w1IRTI868eTVmNKmTFdcPjJbPSc@12K5GJoGT9JYzTweNLPbgZ3kbwPvNzIM3hhFlv1EO28J72B7kmjgsXgXG6eZYvYjmaET@3bl5D6szzPs8gDdej0X8JsO6m6M5KBiPYWA5BpkQvOS2dDrIGNEHOUmwqQOY4LbDjlhmsM4z0JgwvHsbZYtpKFIRRtmto9yLNuvqcV5KT2e58mDpQqTM8UUdSQRXwinMjEZIt4solrAWWbgA1FborMVCv4/JGhMIHTvGMnCe4b/StDMYujAaGbe6fPho/AhP7HqtE94RvJJ0ge6rk/cdCmk/TVLHsr4irLoo@9obBqdUbVSLjCU91wtneUQ@01ZHjzg8cUIPnRqfqhvHPqkvhVUuVqFt7CGxjoJv4dwzArAChh6c6Evfv/Jg7rbU9iOVJVOTDm3iWqTObrE7oGQfzayD5AIB0gpbLdnvvoLBJXL9K8PZY0B942BlS1cbZIYjXjtATfnahhumVJDDbwg7nXhjqN2DgcERr/cfMIlTtxJ@DKNKyEjy7GHMKBkZlpF14PuDomcRkkQerBhI6MgjCFIhOm5fUSgOJYHHm0KpBZA3tPPP7lo1wpcodTg7TAsz5xXc5ZTQlc@Rmn66na7krbM7caacIO6uQKVz6ENUwyOidkjJ1RbH0S61BlZydZhsQ4PVH8lJF1Zn5m7yDZxTRxke8eqhifwfXKtaUP8VXGuchUaXBZzEn6WzKgsIRAAnlzTGX3FB8EBftesVTMYgCrC3XCyzfKNgYJ9A9aAF@pxuKE55E3EGlv5@uBCRckTZV3UolM3pwQ5x6ORm1@gpfQ2nY6gYbxqtg7trXx/O2dfOTOJYhlkQjKjWp5OJYxVwiPruosoXy@Jp1xg3FsjmRBgdbM8Inhetubimj6NFA/0jauLtVVxcdFKWCAaLdnRPOzi70mPQHBAtgzG8QyoMp4iqB4PCHxzuZi2ZQPOuZrBp8ZwcM/T9QphrWuFyh/KXJBlVtk5aEgMmgFslcB1K42RLQFpfXETXC65kUvzMnNpAYEnYgNdRs2xmMpKFkxTvrgczlUrE2S1uIZ5TcJjnjN4a0a33gs8yfHbp4DHssqoqELavauByObgirwwOnrVlfZLX2BQqK21SuMgVDapWG4iTJG1kF3HTXWnNlVTpgAawaA8IoFlUo0xoo5xxrzJKnBq2NpeDVqD6@BfRaMyAqdM4yqYim6KiDknpED5/vJhaRcUKnUJXbdm8Jw7FnfAwVxnpVI1apGqrJsqMr1Vla8WMChqNE5jlIkNsmYrZrJvxaLW3JtxmiZYmdla6ZX9HwTd/T4eKJ0HH0V17f4A7ikLxOtlc74g/MUA8VbbI9eMaEeKZiYamJeJEwoOTmVY3VPOUplhOnklc3yevYaP4x4O6NYZ1d3RKee5OnOcNbG3HvZ8UhTgn1cuqIhP6yYNXKMrpm0YaD5vfVWgaKK1vpTSiNQnh3rd0y1Ly/VIJ3u3680jNcNJARD6Z1yWWd82brgtriVLLdh11oFT94r6hJtKBTF3HbKRYdcq5O3Juf9yEiK6L46OQ0XB12b5sJ/MnCErmCbbFBgRznyr7SG1u71TfNCiGmm0xxEx1/slZgdBm4OqX0txWlI0S43FLC6s/438PZVvRQkuFz2oKW10dxRRD4prmNNe6EulsxglB36j5udW7IyXpiwwT/TgJV9jmedHmpMThRV/Jm8waBA4Pqdho2TkiiHJzr37z1jvQx/c/dRQs7xjFV/AgUMm2NiqaL93F@IzoIywifUBn41GGL2ORavruaujpBjEpVs8OfeU5yQrgbv@n4i/v@OTfBYMf9qBl@PyAnJzA1Rux@kJPkUfb93Nex3TC9akSKtEFuOHx@/v7YW/QO@@97L3qff9XOI/Ftb4/e/83 "Rust – Try It Online")
# [Rust](https://www.rust-lang.org/), pretest score = 73
Compile with `rustc -O`. Input format is `K` on the first line, followed by the entries of `A`, one entry per line, all on stdin.
```
use std::io::{self, BufRead};
use std::iter::once;
use std::num::Wrapping;
use std::time::Instant;
use std::u64;
type Cost = u64;
const INF: Cost = u64::MAX;
fn smawk<Col: Clone, Key: Ord, F: Clone + Fn(usize, &Col) -> Key>(
n: usize,
shift: u32,
cols: &[Col],
f: F,
) -> Vec<usize> {
if n == 0 {
Vec::new()
} else if cols.len() > n {
let mut s = Vec::with_capacity(n);
let mut sk = Vec::with_capacity(n);
for (jk, j) in cols.iter().enumerate() {
while match s.last() {
Some(l) => f(!(!(s.len() - 1) << shift), j) <= f(!(!(s.len() - 1) << shift), l),
None => false,
} {
s.pop();
sk.pop();
}
if s.len() < n {
s.push(j.clone());
sk.push(jk);
}
}
smawk1(
n,
shift,
cols,
f.clone(),
smawk(n / 2, shift + 1, &s, f)
.into_iter()
.map(|h| unsafe { *sk.get_unchecked(h) }),
)
} else {
smawk1(
n,
shift,
cols,
f.clone(),
smawk(n / 2, shift + 1, &cols, f).into_iter(),
)
}
}
fn smawk1<Col: Clone, Key: Ord, F: Clone + Fn(usize, &Col) -> Key, Iter: Iterator<Item = usize>>(
n: usize,
shift: u32,
cols: &[Col],
f: F,
iter: Iter,
) -> Vec<usize> {
let mut out = Vec::with_capacity(n);
let mut range = 0..0;
for (i, k) in iter.enumerate() {
range.end = k + 1;
out.push(
range
.clone()
.zip(unsafe { cols.get_unchecked(range.clone()) })
.min_by_key(|&(_, col)| f(!(!(2 * i) << shift), col))
.unwrap()
.0,
);
out.push(k);
range.start = k;
}
if n % 2 == 1 {
range.end = cols.len();
out.push(
range
.clone()
.zip(unsafe { cols.get_unchecked(range.clone()) })
.min_by_key(|&(_, col)| f(!(!(n - 1) << shift), col))
.unwrap()
.0,
);
}
out
}
fn solve(k: usize, a: &[Cost]) -> Cost {
let mut cost = vec![INF; a.len() + 1 - k];
let sa = once(Wrapping(0))
.chain(a.iter().scan(Wrapping(0), |s, &x| {
*s += Wrapping(x);
Some(*s)
}))
.collect::<Vec<_>>();
cost[0] = 0;
let cols = (0..a.len() + 1 - k).collect::<Vec<_>>();
for m in 0..k {
cost = {
let f = |i: usize, &j: &usize| {
if i + 1 >= j {
let h = (i + 1 - j) / 2;
unsafe {
cost.get_unchecked(j).saturating_add(
(sa.get_unchecked(i + m + 1) - sa.get_unchecked(i + m + 1 - h)
- sa.get_unchecked(j + m + h)
+ sa.get_unchecked(j + m))
.0,
)
}
} else {
INF
}
};
smawk(a.len() + 1 - k, 0, &cols, &f)
.into_iter()
.enumerate()
.map(|(i, j)| f(i, &j))
.collect()
};
}
cost[a.len() - k]
}
fn main() {
let stdin = io::stdin();
let mut lines = stdin.lock().lines();
let k = lines.next().unwrap().unwrap().parse().unwrap();
let a = lines
.map(|s| s.unwrap().parse().unwrap())
.collect::<Vec<_>>();
let start = Instant::now();
let cost = solve(k, &a);
let time = start.elapsed();
println!(
"cost: {}\ntime: {}.{:09} sec",
cost,
time.as_secs(),
time.subsec_nanos()
);
}
```
[Try it online!](https://tio.run/##1Vd7a@NGEP9fn2JyULNKFNVOj6OVH9AeBMLRO2ihLaTB7MmrSJa0Mt7VOTlbX73p7EqyVpaUXB9QugYjzWtndmZ@s9rmQj495YKBkCvPizLP2wuWBA78kAc/MboqplbDlWzreRn3mUHkeep5v27pZhPxe4Muo5R53g0XknJp0PM3r6eWJR83DN5mQsIcNMXPUBJu3l97Btnzfvz@N5QOOIiU7uLZ2yxBfpJx5sA79ujBh@3KgeuKBhdwzUkuos/IHqGsDZcLJbcgFuDiHpRM/SbCKJBI@eaqfPezRHgwukW9u5ISeHDtWNrIL8yfad0F7DUvCoDDfA7j6l0tFMLzYDtia1IBLMGoUVKZdhPGiQ0LVGs0EiYhzSUIjFdr7yIZLn26oX4kHwm3p13R@GXZINsCWccOrG2IeLm9Sh6xXYb5YlsqGfrS@KHWLowSBimVfgjoLRWyI6LWz1nKCJ7sfAEBOcNfHdklTGyYzcpztfXes/kLMontdDZ4rzKprFM8vTa76PFHuJtsQ4zgj4y4j1O03jA3tWuzVmIM67kIydr1VYERe2AfLRMPbtU86TKekJYcbwepz6ZNUglsU4LaoRNdZZ5w@BqunNIQ9sQEm0E4ENgd192Iy2xZVkaXmdINOYQHyLmgAYM9nGOo90wuc@6HzI/ZioQ2FIYLrbrf/@dBawsYtxlmx1mraPBl8ncBxoEbhY36n8psO8OHVGGYhox/BD@6TI/Gh@CoRocsl8/DQy24pfwe2wzGrjsuORo0IgdijRlqywGw0KrIW6F6rI66KXvcvmyGVoK0Qre@qmR2GZ@jDTkWnQavdtWVDtQdiRXYU7sRX358XMbskRxGZOkoM/ahQqMrOIeohUOK22Ml5zscbH0ujo066gnfhILSWxyDW5WaeGo1iKCHyFdwpQbJZOCEm9nxfztm3oH7f@GYy4PDA6j7Nks@MRLXrQW07CEh73Sj6LtEu0X88nrxiflnt3jfmAKtJgBWMnoc3zWNIigKqvsOqS84ZGwE4PohjTih9WwVPuWmpAMHxJ/Rw@FksJwLuJjDUfDhZG7oCXsumn2K1p5ZkjBfet5MgcASwaVSV3Hdju9UTzcRqLQihWCbn4RpD1tSSJAqEECt2PC9Orl2MGqXAKmH6JiD0RqToJ8PPSMViz7STizmsO7h10ZD5XdUuYuXCYT3aa9wXcO9zNrvk9peY7aozBHbMANLulqRQW21iKAnBpRjqXJOXWqGucgM7WdNq9VjYV1Z@ALtiwFt@2VVs8FOV7920aF2xr25sMGs500U055hflKrDoyP43z0l@8xxhQbuOSosbfWuBWp6u3DqKpZDBOFCUi6@ejxlhvfVfCUKoCwDQTCbyBsrDmoLy39TE4GcxJxplpWM90k82NEFk00JdVHgCa6nD2gV0cMbR42dCuYQWiUaa1stY9BHPC@O6j/JRhURlhOuurTD7@Isp3Jr1CkAm48b2ow1VejDh5tuCyhG4HVXPE3W0xzws@aVn2lbHmwL37n@nMTn9y9N/6uAMH8V04LuJo3JepSsUQZYV4INV3kH5G@5JRnoko2bl88PU2ssXVlvbbeWN/@4QcJvRdPlx/@BA "Rust – Try It Online")
[Answer]
# C, score = 56
content of `a.c`:
```
typedef void V;typedef char C;typedef long L;typedef unsigned long U;
#define R return
#define W while
#define S static
#include<sys/syscall.h>
#define h1(f,x )({L r;asm volatile("syscall":"=a"(r):"0"(SYS_##f),"D"(x) :"cc","rcx","r11","memory");r;})
#define h3(f,x,y,z)({L r;asm volatile("syscall":"=a"(r):"0"(SYS_##f),"D"(x),"S"(y),"d"(z):"cc","rcx","r11","memory");r;})
#define read(a...) h3(read ,a)
#define write(a...)h3(write,a)
#define exit(a...) h1(exit ,a)
S V P(U x){C s[32],*p=s+32;*--p='\n';do{*--p='0'+x%10;x/=10;}W(x);write(1,p,s+32-p);}
S V mc(V*x,V*y,L n){C*p=x,*q=y;for(L i=0;i<n;i++)p[i]=q[i];}
#define min(x,y)({typeof(x)_x=(x),_y=(y);_x+(_y-_x)*(_y<_x);})
#define t(x,i,j)x[(i)*(n+n-(i)+1)/2+(j)] //triangle indexing
#define x(i,j)t(x,i,j)
#define y(i,j)t(y,i,j)
#define z(i,j)t(z,i,j)
#define N 4096 //max
L n;U ka[N+1],c[N],x[N*(N+1)/2],y[N*(N+1)/2],z[N*(N+1)/2];
V _start(){
C s[1<<20];L r=0;U v=0;
W(0<(r=read(0,s,sizeof(s))))for(L i=0;i<r;i++)if('0'<=s[i]&&s[i]<='9'){v=s[i]-'0'+10*v;}else{ka[n++]=v;v=0;}
n--;U k=*ka,*a=ka+1;
for(L i=n-1;i>=0;i--)for(L j=i-1;j>=0;j--)x(j,i)=x(j+1,i)-a[j]+a[i];
for(L i=0;i<n;i++)for(L j=i+1;j<n;j++)y(i,j)=y(i,j-1)+a[j]-a[i];
for(L i=n-1;i>=0;i--)for(L j=i+1;j<n;j++){
U v=~0ul,*p=&x(i,i),*q=&y(i,j);for(L l=i;l<j;l++){v=min(v,*p+++*q);q+=n-l;} //min(v,x(i,l)+y(l,j));
z(i,j)=v;}
mc(c,z,8*n);
for(L m=1;m<k;m++)for(L j=n-1;j>=m;j--){
U v=~0ul,*p=&z(j,j);for(L i=j-1;i>=m-1;i--){v=min(v,c[i]+*p);p-=n-i;} //min(v,c[i]+z(i+1,j))
c[j]=v;}
P(c[n-1]);exit(0);}
```
shell script to compile and test the above:
```
#!/bin/bash -e
clang -O3 -nostdlib -ffreestanding -fno-unwind-tables -fno-unroll-loops -fomit-frame-pointer -oa a.c
strip -R.comment -R'.note*' a;stat -c'size:%s' a
t(){ r="$(echo "$1"|./a)";if [ "$r" != "$2" ];then echo "in:$1, expected:$2, actual:$r";fi;} #func tests
t '1 0 2 4 6 8' 12
t '3 0 1 10 11 20 21 22 30 32' 23
t '5 0 1 3 6 8 11 14' 3
t '6 0 1 3 6 8 14 15 18 29 30 38 41 45 46 49 58 66 72 83 84' 49
t '2 0 7 9' 2
for n in 1176 1351 1552 1782 2048;do #perf test
echo "n:$n";a=0 inp="$((2*n/3))" RANDOM=1;for i in `seq $n`;do inp="$inp $a";a=$((a+=RANDOM%1000));done
ulimit -t10 -v1048576;time ./a<<<"$inp"
done
```
~~n=776 takes 6.2s, n=891 takes 12s~~
~~n=1176 takes 5.9s, n=1351 takes a little over 10s~~
n=1351 takes 8.7s, n=1552 takes more than 10s
(with k=2\*n/3) on my `Intel(R) Core(TM) i3-2375M CPU @ 1.50GHz`
[Answer]
# C++, score = 53
The solution I had said in the comment. `O(n²×k)`. (now I deleted it because it is no longer necessary) Probably can be reduced to `O(n×k)`.
The input is pretty flexible, on the first line, the first number is `k`, the other numbers are items of array `a`, but if it encounters any close-parentheses it stops reading input. So input like `K = 1, A = [0, 2, 4, 6, 8] : 12` is accepted.
```
// https://codegolf.stackexchange.com/questions/149029/build-an-electrical-grid
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <climits>
bool read(std::istream& str, int& x) {
char ch;
do {
if (str >> x) return true;
if (str.eof()) return false;
str.clear(); // otherwise it's probably int parse error
} while (str >> ch && ch != ']' && ch != ')' && ch != '}');
// ignore 1 character, but treat any close parentheses as end of input
// cannot read anything now
return false;
}
int main() {
int k; std::vector<int> a;
//{ Read input
std::string st; std::getline(std::cin, st);
std::stringstream sst (st);
read(sst, k);
int x;
while (read(sst, x)) a.push_back(x);
//}
std::vector<std::vector<int>> dp (a.size(), std::vector<int>(k));
// dp[n][k] = min distance you can get for cities [n..a.size()-1]
// and [k+1] power plants, and city [n] has a power plant.
// sum_array[x] = sum of coordinates of cities [x..a.size()-1]
std::vector<int> sum_array (a.size()+1);
sum_array.back() = 0;
for (int n = a.size(); n --> 0;)
sum_array[n] = sum_array[n+1] + a[n];
for (int n = a.size(); n --> 0;) {
for (int k1 = k; k1 --> 0;) {
if (k1 == 0) {
int nWire = a.size() - 1 - n;
dp[n][k1] = sum_array[n+1] - nWire * a[n];
} else {
// unindent because my screen width is limited
dp[n][k1] = INT_MAX / 2; // avoid stupid overflow error (in case of -ftrapv)
// let [n1] be the next position for a power plant
int first_connect_right = n; // < lengthy variable name kills screen width
// ^ lengthy comment kills screen width
for (int n1 = n + 1; n1 < (int)a.size(); ++n1) {
while (a[first_connect_right]-a[n] < a[n1]-a[first_connect_right]) ++first_connect_right;
int nRightWire = n1 - first_connect_right, nLeftWire = first_connect_right - 1 - n;
dp[n][k1] = std::min(dp[n][k1],
a[n1]*nRightWire-(sum_array[first_connect_right]-sum_array[n1]) +
(sum_array[n+1]-sum_array[first_connect_right])-a[n]*nLeftWire +
dp[n1][k1-1]
);
}
}
}
}
int ans = INT_MAX;
for (int n = a.size()+1-k; n --> 0;) {
ans = std::min(ans, dp[n].back() + a[n]*n-sum_array[0]+sum_array[n]);
}
std::cout << ans << '\n';
return 0;
}
```
[Try it online!](https://tio.run/##hVnZbhzJEXznV7RhYEWuSKruYyUL8KPh48EwYAMyLYyGTXLAYQ89M9Thhb59HRHZPLQi7F1AwaquIysrMzKzZnl7e3K5XP7yy6tXw9V@f7v76dWr5eZ8vNysL053@8Xyevy8vFpMl@PpcnPz6t93426/2ky7Vz51F/qrD3er9fnJYjoZ1@Nyv10tF@uTy@3q/ODgt6tpub47H4c3q81uvx0XN2@f9H3E6M32aQ/GrKbLb3q@n7Zcr25W@93bg4MPm816wOfzw93@/KefVjb2hwF4PKym/Q/D56Ph54ODAf/hAFv889pa5xv0D/N/q4sBC2yHt285fjvu77bTsN/eja9/PeR03FwcHj2MuVisd08GccByPS62h0evB@hys78at59Wu3FY7V/shtvt5sPiw/oLJRtuF1v0j9vtZqv5X4dPV6v1@CDI8mr44Qf@@5vfDS/OXjxpHD1tfH1xZPtju9XltNmOg9dRF8v9CCV8uNsPVMp@WExfhuV6g02x9ThBtN24Gxa7YZzOh80FhLq92x/cr7VcTNNmL91y5v4K1zJMm0/6/u3pvx4c8EA3i9V0eDRrlR3Xrwfdit3yG3S9HRav73f4efgr17ZdTXkYa/ePv@e5l@N@vZpGu97lajpG93zgJ@Pt2geYCtV3NO9hdrHbHw/X910U67NNn7X9OOgzrnVxenu3u3r/ARZ/@PlBsV8PHjecD/Prg70dzm@Hw8XpbvWf8fDo@LuDH14fPd7T@e276ezd9dnwu@FmNQ3nMNvFtByHL5s76n3AoYeLDYx1tV/hit5Np6f3K5/4s/tVFri2d9cv/dlwu/k0bofb9WLa747Vj5lfMO9suML9Lp4OOH244d3dzfvFdrv48u4zJUGTVrDcbLbnq2mxx8ZsziJ8/l6E7@72YcFHRbz095d1/@1Uuj3Chs6@8KCHvJcJfffzXqN1cvIWY44enetB3mmW975JHbwcFuifr/n/rfnE9R@GXnuMhckCvx91zwAcBMl//enetKa/r@B/j1sOJ3DGk2F6/d3o2QT8Myc5mZf5cT7R02lfhxEu96vdcZd302o6h08PH8bl4g4jbr4Mu@V2HKfh0@p8fzWsdoNIcwQnP937D3/52/s///4fw6shiLEWHzerc1zt3S1g83HcXqw3n4ylqCaYJxaHXZxc7LeL249HBweYtIa9vpuw3odxAK0M0/gZ/LbZrRgkpOFvTFBscbHa7vbvl5tpggW9364ur/YQZ5IQb7DidLm/@jJ8XGxXYEwsubgZh@vVer375lzc/V8PoxGbbqiEZ8YdPJoE73mCvfjX/PuNeo8ejeTly8k/xIyZJBbvnhH37IT3gwUWPPvJ82OOsN4z/U/oaPorO2bDmWguz4w/HqY/jRf3o57T3TeW9o110U1BM4cPnccP1iPJf3yU4OTw0RafPfETU/U828NKh98a8cn/XudIqvvx8UyPC1FKTzHvaYbUPRPwgxc8Nr8ePOmgOhfT7tGs/wfDvPQn188zgq3woDY0j02h99RlVPPj9OSQ7uzlU3qaSe9p3FhuEIjfvNHqgBf/nF48hCkFU9Dh119@@SO29t0dD7/HH@9ij8eDL2z76urxEHrwx0OMvuPf6gP@bbEcD6kX/J2bx9fcE76WVNHTquO/jV@7rxnrOJcLAf8DfM7sDCFwj@hzFNRGCIEjYw8cUkrvhBaipHGJEFslNIoYogsCiRcgH1YJuTVsHqpXq9bIVivN6zQREyJEajxVoOAxZgoRU/WJx0uFna1z24Rkk6d1zUGk5EMhhEYhUuyerdR4vlQCz5dqppKgnoRv2XVKDeBRsncR2@YQPITI0flIKBQ@p1IFjatAoET15iQovnFeCZGLVQmRG6Qn5CpoCfOKczxm8S5UQuLlleC5UcFJsEqJ3TneVsyYV5pTZ9M9lJb0raWeCaV1AVVQeigAXC/1Ul3hBGiMRgKJKDw0zVupBTcIqIEiQf/coVYcEIbBqyZkKqSFLptJwWFIw3ExvRXH07aauUqrnTrDbVCRMMYEIXp0gtx59l5cEmQXBZSz16wh3ezFORe9jDBQa8AYzSgj9wQWJ1sN2ak/5qbxuA9aJrQkn3A1WX@VhXvXQq6Gc3vu77GzHwvQHIClcj7@cF2YKDouJsgBIEYTZp81rnQvb6lFvuC77BfYo7kPbk7Y5WMh2rkCvFP9CR3CxDuE3bai7/M6kYIJu5cfwjNmTPJEqEWuWCPtmNiDuSZvGhh5c7h@6R5Y6EpA2z9Bk2rz5ES4u2GUU6fopLeU53E5eLVLTsJapb/UivSRwSHcL8N/naHkyRCM4@A3hvCKIkyeWMxggGAAoWzalxglDzhG7FKqKARYRVYFblXEOja/OrkLMJHfQEPR@pMIBdcEQYRF54LVO@MpVzQOVh0N7XurRdiN5DCMbAXs0ncDdao/YymhyQkrbBoHyuW@5DOO77EUtUFfHNdxAZzfs91Thz70vWWtQzMCBsf/iLRgYaUdBWd6Ci6KH4AgIWLzaUb73uVXIDTdG5gm0D6BVd8xWgwNTNZuMRpSLwEXSSYGRtonMGk/Kl7rdHElMFfD0q1f3IsokrUf7ZzrBYjRhZl@SyQFAgv1QLepasOu9b05Gw@zFXb5JTDTngKJRqHFddoF3SwIU9N6MXvpDW7H@wdWyYvQ0NWPeyLCT6h3MKL4Atg6909GwyEVky8ZbQF7ppzwXvoxWKlL/9nLf4BF@sogZfXHpnXBmeR6qoG8hmOXpn4E82KxsXFegQK4TolJeoT50s5CSc6nGTkeqxf1F5OzGB8Ac9R3LMfviM46f3VN3yskVD8U6ISFsSvgeLqXCq7X@NJtfIdFM0y7WA2z7ILX4oVe947dpN8GGhaWqvM18LLmwbw4rjuzO4RfnQNa0b49NMkFf7F2L@QVkIoPQl/IZ5H8z5wA/E89wQugIqF4Ds7duxKJlqPmddk7sNOuI/xA44DUH7B6w8ZwBuxZ3xFNmV/5XMlzCI5KGCIcnkEepy7KRkCfmgfroz4iZpFfkAIonoL0XDKUPcRgSUKEomgPwJI0H2kb5aNbZ6HyBmRCkfwB5YXqLSWy/qK4Bey0txhBSzxv7Eo7gDUqdwqKzxFhh3ZEbNaW/onSD8yd/g3szGxgTJ5xDmRa7DvCmrAGWxfXq/Vg3uxHiNc9AWnvwMZ4BjJLTf10IEOdP2dP@8Pgon1zFf/w9pXRFlo2MclPI7fnejVYhlihcCdsSg5rslyx4r64Pnmf58Oyus8Kwta8rjgSQS@yrzbbAxIfyd3ASOrPUfeD67bkMyvRjK3IjoFFeqSda1zpth7@4D6wc9krU221YTgc10MKhpW8gnDtlccjustuOhTohEn6RFzQPr0p30hMkA275b/BN2H0xbAo6QU9Ur/JoQZQugyFGMLTiJZ/IfhU3h@M0bHCAKaqftwE5zMgJ0Pt55Fecj4DpuYh3mhe60XjLRtNCnQzZkPNQwCS/CByy9iT7UPkOogLqmJC7vTPBO@mHycQFe0faEk9rl3nAHHYOl18lUhLHAfHID/AvBWHieRBmrv2gblrPv1I46vyKgipOJugAMaZxAPxe7K4C1S@meg/@o7qivNo1sGQFROs1qtMQX5E@4M7OeYnicVFEcZsbcUNoOk1s0QQlqY2knbug6yXeSWwav3ixNup@EA7QpETmJelEoPmFwQkL@xO/eUB6VfI@YP0UJCpc52KPIHzKiO2sOleKm5c1RMU0IVJ@7NqqKqqUjdUXo6P4q3EOpB6Rx4l@RoTFWFjBQT2ztIDKhrptyGeUR7EC/sO9@B@iBvMoxlu6RfAJLn7bO8wL@kF6YHk6gjPKuxQCLBCc0joWaIhynO/jLihks1ZPkts6gd9q7@qUAP7ZVVxPqgAAzaek6ylUpF5EmtFlCeaj8SFfoasSXwClD6QBiRVmJiuohJ2yviWZzsFyyhPhhnEqKIzKg6wzKSfkD61HwhTBSvYrKhdPf0ik7i4DuyV9gwskpOVm6G3KhaZWRT2oP6o/D8jv6d@gaY3GFKaUeeGQc1Yu8YXxUdmc/G@LFZ/E3/BGuQntAryMKT2khcKlp5gltoXB6U/0tulFwikcyIttPFF9RZI2WnfbHk6sHat25SXwLnkr7k4xSVM8xoP7@iq0BFZhEn1GYKcL6rVkc84oeIXsEnu6hVHgcULrY4B9mztbuOSeIDZgfQLlF5rlR0DK/kaYU1vLZl@wHuCV3VhsPcEoO6vMUIRi8kLdpX@6O5q92Bt0FwVNukR6Sz9HUKHqnbWMw6wFb0AWT0D1GsNqnvlY3yPoH0U5/XCU5hm6Z0C4kZh11OD4wsL0ewZtKPzFcfASuy6H6DsEeylvAfKc@QLoPILXLLTswYKSvueZB9A6QG3HbywBpvHhFJYsrWVlxfGF81HQDRU/gP6i3pnCSl3valU1VNA2W1h4tqFqpMLy2ruj0SS9w1UXlCQ4GlfJmpCGDLPD7Yu2bBpPCxN43GDwiK@LQw7lAf@qX2jxYMS5/2RSOjNB3Em6rXHyT8LA3nQ64@XXEDyFtDOi4DT1A@H4bogfvorksdC3qF5e8Ok/UGAvH@gp58BG/NuJAfyb6C9NsGQmbeABZv2x8WTF4maRzekfEyzKQ834P6MLxoPBlI/LFLj@H5lKHsBbWStB57ivGpPbcAiPVZGNCILJGJRXgesQeNQ2EeheApYpA/4lY1HguX1XCZ/5JukzgnrZP4ErIYI10I@swmLztes7kSwzcxXGAWkV6RHhsig@B1hRXbWs9khaIf@DWxe7SaeL6B3rocqWXqG9KHqWQ5MlomgSUM/Y@b9g@UU98h2vGeoKXBdqov3ARTvVu9LEAa99lY@k2l8Skn9fMskQo/c30ORGgdFar2mdyRYp/JvGLlnfgYsrBsq/chQdgGtKw/DZdj6KNzor8BKe4MRq/6riEu8T2ZpOg8Sbad2F58hu8rkZ6QTXfKgzpCekGBlfU/Kc5he0D4q8ijJl7p4A6g8GKj6oWaYE79nvggQk50DgYd8gzJAdSXLAeY1QPFrJbHqe1f8qiA4xqVa5vsC0egZtXjFF6B4H2Ypu0YW7fWiCkfU/bAOVxsD9MQKe9I8q8MrX269sNPOER6UhzE60B8qFas32eR1/zig5MUBNR@nZdyn2Qf1I7GiHHArnY91OfsbX/OJQe/bwK5z8cVY48jAQr2jAJUfY7VIfqIbSW981lE7qI4EihcR7ZXn8llM@/B5TOOrfpMAqh6oHWWcF6puZjVOv2p8x8pCvRcxa6Aemguyf2DheYE16DvyqkSsek9B9efsfZovDnquDs6eraVnOGvuaifxGthG70dAvQ80PjRqHMTKhlXjm/LCBm8j36P8K4z3Qj2Eow4KwsY42IK9ixGLviNBFzKiCvX@hCiTsvrrvG4Lhr14wyY9RNM76ErvBMAkOVHXW39VnEESWPUwD5bUPtHqnsZ3qyZMvCdgl5ysT7hPomMRs94RgMobGgqBoPmgG/VX1RsN2YG@ZxIYMSiOAU3fDH/6SQAJZtdPA136QoIlfWN52ierVvsOYmV7ft9FNBc/APUeTDPUPRSLRyynNQ@j7Vcrr/weWBh3EDXl17Au8Vujw6vffutq1eIY/u2yE0Q9ydWS6V8HFcoPIZ3ep5EMRc1HFNH54Bfap9sPKUDFwdbt/Rfk4O3nj6x3NlS/@vmlkRb1HdfO3z7AljwfUPUWrFj64uss7byjTqf/walUDzB6OLVxwDwjfy5BPOD9YZBXP/yAdo2sS3Vk54N@ExbmQZ0P9YbiM2LSvKz3AqDe8XEc2YmeJzSu6T0MaaXiJbMk1vfAQv2BHvR7hn7vEQbxTuf7l8Yjkef6oeodvPMdV/N6Zr2KwyfJGen5Qr27AmNWG/ltEGbGd6hZ76RdDwTEWCQPCvaqdjE9JP6cReyq7zvL306EQNwX6QXzlY5CZ0bxD9LlQj/CNeqdiOE9a37X70YoluXnQP0CC8y0787ErQkL7azzR1a1s@y981lB46vJzR/ruB@05DS@289g6LUfxyyfRUt1G1D1L8wpZP1qVpK1cT08D8MAEUQq/YJeyA@gX/Eof06gXwMj@aG3@b7heJIP7KP9@S6r703@20kvXii@AFbmOx3lN/MwRE3VhfyZQvfDi1M7q/4gNq2DcK75EIf7UiB/9l8 "C++ (gcc) – Try It Online")
[Generate random test cases.](https://codegolf.stackexchange.com/questions/149029/build-an-electrical-grid?noredirect=1#comment365807_149029) (input `N` and optionally city range, `1000×N` by default)
[Answer]
# C#, score = 23
I am sure this is not going to win this challenge, I just wanted to post a first (and very basic) answer to encourage other people to post their algorithms and improve mine. This code must be compiled as a console project that uses the [Combinatorics package](https://github.com/eoincampbell/combinatorics) from NuGet. The main method contains some calls to the `Build` method to test the proposed cases.
```
using Combinatorics.Collections;
using System;
namespace ElectricalGrid
{
class Program
{
static void Main(string[] args)
{
if (Build(1, new long[] { 0, 2, 4, 6, 8 }) == 12)
Console.WriteLine("OK");
else
Console.WriteLine("ERROR");
if (Build(3, new long[] { 0, 1, 10, 11, 20, 21, 22, 30, 32 }) == 23)
Console.WriteLine("OK");
else
Console.WriteLine("ERROR");
if (Build(5, new long[] { 0, 1, 3, 6, 8, 11, 14 }) == 3)
Console.WriteLine("OK");
else
Console.WriteLine("ERROR");
if (Build(6, new long[] { 0, 1, 3, 6, 8, 14, 15, 18, 29, 30, 38, 41, 45, 46, 49, 58, 66, 72, 83, 84 }) == 49)
Console.WriteLine("OK");
else
Console.WriteLine("ERROR");
Console.ReadKey();
}
static long Build(int k, long[] a)
{
var combs = new Combinations<long>(a, k);
var totalDist = long.MaxValue;
foreach (var c in combs)
{
long tempDist = 0;
foreach (var i in a)
{
var dist = long.MaxValue;
foreach (var e in c)
{
var t = Math.Abs(i - e);
if (t < dist) dist = t;
}
tempDist += dist;
}
if (tempDist < totalDist) totalDist = tempDist;
}
return totalDist;
}
}
}
```
Really simple explanation: for each combination `c` of `k` elements from `a`, calculate the sum of the distances from each element of `a` to the nearest element in `c`, and return the combination with the least total distance.
One-liner version of the `Build` method (probably slower than the original, expanded version; this needs to add a reference to `System.Linq`):
```
static long Build(int k, long[] a)
{
return new Combinations<long>(a, k).Min(c => a.Sum(i => c.Min(e => Math.Abs(i - e))));
}
```
[Answer]
# C++, score = 48
```
#include <stdio.h>
#include <queue>
#include <algorithm>
typedef long long ull;
typedef unsigned int uint;
uint A[1<<20];
ull S[1<<20];
double ky = 1;
struct point {
ull dist;
int n;
inline point() {}
inline point(ull dist, int n): dist(dist), n(n) {}
inline double res() const{
return dist + n * ky;
}
inline int operator<(const point& other) const {
return res() < other.res();
}
} V[1<<20];
inline ull f(int L, int R) {
int m = L+R+1 >> 1;
return (S[R]-S[m]) - A[m]*(R-m) +
A[m]*(m-L) - (S[m]-S[L]);
}
int main() {
int N, K, i, j, p;
scanf ("%d%d", &N, &K);
ull s = 0;
for (i=1; i<=N; i++) {
scanf ("%u", A+i);
S[i] = s += A[i];
}
double kyL = 0, kyH = 1e99;
point cL, cR;
for (int step=0; step++<50; ky = std::min(ky*2, (kyL+kyH)*.5)) {
for (i=1; i<=N; i++) {
point tmp(f(0,i), 1);
for (j=1; j<i; j++) {
//printf("ky=%f [%d]=%d %I64d %f\n", ky, i, tmp.n, tmp.dist, tmp.res());
point cmp = V[j];
cmp.dist += f(j, i);
cmp.n ++;
if (cmp<tmp) tmp=cmp;
}
//printf("ky=%f [%d]=%d %I64d %f\n", ky, i, tmp.n, tmp.dist, tmp.res());
V[i] = tmp;
}
if (V[N].n == K) {
_: return! printf("%I64d", V[N].dist);
}
if (V[N].n > K) {
kyL = ky;
cL = V[N];
} else {
kyH = ky;
cR = V[N];
}
//printf("ky=%f %d %I64d %f\n", ky, V[N].n, V[N].dist, V[N].res());
//getch();
}
V[N].dist = (double)cL.dist / (cR.n-cL.n) * (K-cL.n) +
(double)cR.dist / (cL.n-cR.n) * (K-cR.n) + .5;
printf("%I64d", V[N].dist);
}
```
Usage input:
N K A[1] A[2] ... A[N]
[Answer]
# [Ruby](https://www.ruby-lang.org/), score = 23
```
->a,l{d=l.map{|x|l.map{|y|(x-y).abs}};[*0...l.size].combination(a).map{|r|r.map{|w|d[w]}.transpose.sum{|r|r.min}}.min}
```
[Try it online!](https://tio.run/##LYtNCoMwFISvkqWW@LAaraXYi4QsYlUQNEqiqDU5e/qoLmb4mB@9VLtvSx@9Je2PuuxhkNNhN3vBboMt2kOQlXHuxW8xAPRgum8j4DMOVafk3I0qkOG511afsNqar8LBrKUy02gaMMtw9Z1y7u9@Ii3PKY8puVOSUpJTUiAzVIZCTp5YYJ8iMxwxzBnOGOYZZjnyI8EbvgsmhP8B "Ruby – Try It Online")
I don't think it's going to win, but I wanted to give it a try.
[Answer]
# [JavaScript (ES6) (Node.js)](https://nodejs.org), score = 10
New Algorithm, will explain if it actually works this time.
```
const {performance} = require('perf_hooks');
class Connection{
constructor(left,index,length,right){
if(typeof right === 'undefined'){
this._distance = 0;
} else {
this._distance = typeof left === 'undefined' ? 0 :
Math.abs(right - left);
}
var half = Math.floor(length/2);
if(length % 2 < 1){
this._magnitude = half - Math.abs(index - half + 1);
} else {
var temp = index - half;
this._magnitude = half - Math.abs(temp >= 0 ?temp:temp + 1);
}
this._value = this.distance * this.magnitude;
}
get distance(){return this._distance;};
get magnitude(){return this._magnitude;};
set magnitude(value){
this._magnitude = value;
this._value = this.distance * this.magnitude;
};
valueOf(){return this._value};
}
class Group{
constructor(...connections){
this._connections = connections;
this._max = Math.max(...connections); //uses the ValueOf to get the highest Distance to the Left
}
get connections(){return this._connections;};
get max(){return this._max;};
cutLeft(index){
for(let i=1,j=index-1;;i++){
if(typeof this.connections[j] === 'undefined' || this.connections[j].magnitude <= i){
break;
}
this.connections[j].magnitude = i;
j--;
}
}
cutRight(index){
for(let i=0,j=index;;i++){
if(typeof this.connections[j] === 'undefined' || this.connections[j].magnitude <= i){
break;
}
this.connections[j].magnitude = i;
j++;
}
}
static of(...connections){
return new Group(...connections.map((c,i)=>new Connection(c.distance,i,connections.length)));
}
split(){
var index = this.connections.findIndex(c=>c.valueOf() == this.max);
if(index < 0){
return;
}
var length = this.connections.length;
var magnitude = this.connections[index].magnitude;
this.cutLeft(index);
this.cutRight(index);
this._max = Math.max(...this.connections);
}
center(){
if(typeof this._center === 'undefined'){
this._center = this.connections.reduce((a,b)=>a==0?b.valueOf():a.valueOf()+b.valueOf(),0);
}
return this._center;
}
valueOf(){return this._max;};
toString(){
var index = this.connections.findIndex(c=>c.valueOf() == this.max);
var value = this.connections[index].magnitude;
var ret = '';
for(let i = 0;i<value;i++){
ret += this.connections.map(c=>{return (i<c.magnitude)?c.distance:' ';}).reduce((a,b)=>a==''?b:a+'-'+b,'') + '\n';
}
return ret;
};
}
function crunch(plants, cities){
var found = [];
var size = cities.length;
cities = cities.map((city,i,arr)=> new Connection(city,i,size,arr[i+1])).slice(0,cities.length-1);
var group = new Group(...cities);
for(;plants>1;plants--){
group.split();
}
console.log(`Wire Length Needed: ${group.center()}`);
}
function biggestGroup(groups){
return groups.find(g => g[g.length-1].orig - g[0].orig);
}
function* range (start, end, limit) {
while (start < end || typeof limit !== 'undefined' && limit-- > 0) {
yield start
start += 1 + Math.floor(Math.random()*100);
}
}
function* cities (score){
let n = Math.floor(Math.pow(2,score/5));
var start = 0;
while (n-- > 0 && start <= (1000 * n)) {
yield start;
start += 1 + Math.floor(Math.random()*100);
}
}
if(typeof process.argv[3] === 'undefined'){
crunch(1,[0, 2, 4, 6, 8]);
console.log("Correct Answer: 12");
crunch(3,[0, 1, 10, 11, 20, 21, 22, 30, 32]);
console.log("Correct Answer: 23");
crunch(5,[0, 1, 3, 6, 8, 11, 14]);
console.log("Correct Answer: 3");
crunch(6,[0, 1, 3, 6, 8, 14, 15, 18, 29, 30, 38, 41, 45, 46, 49, 58, 66, 72, 83, 84]);
console.log("Correct Answer: 49");
crunch(2, [0, 21, 31, 45, 49, 54]);
console.log("Correct Answer: 40");
crunch(2, [0, 4, 7, 9, 10]);
console.log("Correct Answer: 7");
crunch(2, [0, 1, 3, 4, 9]);
console.log("Correct Answer: 6");
var max = 0;
var min = Number.POSITIVE_INFINITY;
var avg = [];
var score = typeof process.argv[2] === 'undefined' ? 60 : process.argv[2];
for(j = 0; j<10; j++){
var arr = []; for(let i of cities(score)) arr.push(i);
var plants = Math.floor(1 + Math.random() * arr.length);
console.log(`Running: Test:${j} Plants: ${plants}, Cities ${arr.length}, Score: ${score}`);
// console.log(`City Array: [${arr}]`);
var t0 = performance.now();
crunch(plants,arr);
var t1 = performance.now();
time = (t1-t0)/1000;
console.log(`Time Taken = ${time} seconds`);
avg.push(time);
max = Math.max(time,max);
min = Math.min(time,min);
}
console.log(`Bench: ${avg.reduce((a,b)=>a+b,0)/avg.length} Max: ${max} Min: ${min} Total: ${avg.reduce((a,b)=>a+b,0)}`);
} else {
var plants = process.argv[2];
var arr = process.argv.slice(3);
console.log(`Running: Plants: ${plants}, Cities ${arr.length}`);
var t0 = performance.now();
crunch(plants,arr);
var t1 = performance.now();
time = (t1-t0)/1000;
console.log(`Time Taken = ${time} seconds`);
}
```
[Try it online!](https://tio.run/##5Vhtb9s2EP5s/wquyCqplh3LTtLGihN03QsCbGnRBh0Gz2hlmZaZ2pJHyXmZ69@e3ZGiREm242LYpxltRB2Px7vj3XNH3Xi3XuxztkiaYTSmj49@FMYJWS0on0R87oU@XZM@4fSvJePUNJD@aRpFX2LDcut1f@bFMXnDkodVvSaW8qWfRNz0gWSTGZ0kNuEsmMKDWcBTS6Ysbn3CaRCLDzcjsnBM74HKchIKAErysKDRhMi3fp8YS2CdsJCODXJB2qQnJJGm4MhXi43z5enrxvVyrqk0WtfrtYAm4tW0VpwmSx6SXHd37UoGoXOZQxAzFtSpzCH0BAYCP@QR25eZBFFxxUoS/rFWBffgQ2OTwsRfxag8IZ7AWq/derMlfTvZptg6O9soDKmfsChciQ30QxbHK4y1ZzQMkqmdbio48ccm5i7na5z4kyqMWZxg3IG6bTebXxM6iyl5YsGTgVJYrn6/ecm05Y1iU0WB8LG2dza69TiZerMJbCUWTWaR8AMaf9jRloDhkkq@Jx1yRpyNps69IGTJcoyqC7HNXBeZDU1Jb4CAJ3yBqiV0vsAE0pa637itEHEOricXOOyJ99L29aI4EUrofHzLDuOFfM/2kushrlTMK85yCCq6nh@ZlDJzLl5LgJxbqKa5vmq/4HD/jUXysSWfBFnPp194tFyUwLLVavlZmsUVdbU5xMz8DZEuA7u5d6@iEoZlmS45PFzGNAaRlHyUupIkEs5F0hQinwLw/6iMhTmk/wqZgHAo0TAXWAFFTSsFfKhG5bju1UH5ywSFyzgHmwtxOhFZBfDad@ybvmBpOq7LGo1SHuGvQshRR@yq6Ta4GVZw4evXTWz5MZOzvqhdm5BjxKn3xa1MrSuU3TuImldectNsFolp7qQP8N97AfRPOLCtHPh/c1@jsct9EOYJ80k02Z59aeSG9E5mbYkTFFiYpm8zq3@OPHmlNP0MNGxm60tkTbAsK0PDWryYMSz9hRqjWqGy3S1w@vhS9Bx@/9xvZagDx6LQ6b5YhqSoM9IunYG0bluRS4vXBg3kjFvg1o@iclRCgaEOm0V8KwKBW5nUo9ytIHkZ9MrbW7KbExlDw4Ryc2N7kqKY4NirS1GsVQdxOl5CVTM9ewSR4fX77YtRflA9Lx83NLrd3lhhiyAr9iwU0i1lR8PZJPqQcBYG/1WIoaxCvdx99voyUBkWGUZOzWBLNH/sTFbnKm7hysYG3TElQWvlDJOd@fnm1kWelz2DGO7aqh6WYVyMel7DaBqNkW0YFvQ@xp@hseNs4JF1AnAqk2UolCE@h9HUXMy8MIltvEowivBSQ9MnEcQXGDkYqvaBk5j9TeWlCBgLeSZJ@ZxEHrxiMdvjHDQnZQSSkygSOQas4QwtqxXPGFjbtgt7NFVzh0oEiHSwUxH1pO6SC8/IlVadO@mg2UwPSCxvpZimIlXdG6IZbc2iwPz8O9wlobUQEHNF6ZiOe@RgJdeqLF1/tor@HLEggBZFKiV4hTfTU5AEEbxmQMAhwSDI7Bu2Imjtoc0NBm05Lsp@QbgXBpSYEBwcrqo0HMPllc1ZYqVd9t2UzdQ8gCkwiMKXXjeQk3xXKozPn8uJZpOcA/pq7foDo7MxEbIympQMMe1AxGl3CzEE7cbR3LReOO125tWC/mmEmLEfcWx4a5hFYfGaIoaL6M7s2ILt8BjrkAhHubu4cNVSU0OpN5qRWt0nJuzfhj44tNCcWk0zxP13ltRzKF7wyKdx3PJ4cDvoDregcZpdjj1o26RjkyObnNjk1TAVqofbszcR55AX5HUY31HeI07nmWKTUrpCigP/8AHPDgrFJ0juwrjb2Utwp1sSfKwEd6V6UrpztJe0srCTqjCw2jmG/zDunKaqwvgImI6AfgRsR0A/BtoJjF@COa9g9av9FDg6LWkAywepZ7pqCxS/p7j2ZnFgxEubnKL395LzcrMY6RgQdrqXlBMlpZ53Mff5NwdBYJhBV8v5iPLWu7cfLq8vP/706fLq58ury@s/cj7vNtCgPMdzTLL8o0QhrjvDDd8nTvBLVIkt7ZYQdG@EduTmzMG/hZootOBcaqFVUdhWIkMKDBZytRbLeGqyUg2XQF5EjCyDVdpC7qOAtI3NBRTQ/f0yDKHh6JFrgOvewepmTd4J4Qjycpu1jR8NEbEOVrlAoH5ANZFP6CtqgNrj8LC4DX51JK859x56ZCDErIefS0YlbTBI@5bZCgH@dL0LNRpLaWm9s3t9wuZ4wmbiNJO2dYjwuMUp18h57X2hGFIHK1y4JjEFnnGsaw2xJM8HOTR6qdPFWbvYiMlolRwsTDlYuL0K/0DBdvQ17llqhKD5AXtwIj0aEHyPvLAnjFkoxixck@so8Wa7pMhCrn@yKoRbJd6L8axPp@1Ld0N650G3Z6h91nqeXVGyLUKeio6tkfFNUbF@fHx0/gE "JavaScript (Node.js) – Try It Online")
Run the same way as the other one.
# [JavaScript (ES6) (Node.js)](https://nodejs.org), pretest score = 12
Outline of the algorithm:
The program first maps the Data into the City Class, which maps a few data points:
* city - the absolute distance of the city
* left - the distance of the closest city to the left
* right - distance of the closest city to the right
* index - (deprecated) index in original city array
the array is then thrown into the Group class, which has the following:
* cities - the city array
* dist - the distance spanning the group
* max - the largest left connection in the group
* split()
+ returns an array containing sub groups split along the largest connection connected to the center city in the group
+ if there are 2 center nodes (an even length group) it chooses from those 3 connections
+ (\*note\*: this will drop any groups with less than two cities)
* center()
+ returns the best wire value for the group
+ working on a solution to skip iterating over each city left for this step
+ now with 50% less mapping
Now the algorithm proceeds to split the groups as long as it has 2 or more
power plants to place.
Finally it maps the groups to the it's centers, and sums them all up.
## How to run:
### Run using Node.js (v9.2.0 is what was used for creation)
running the program using generated test cases for score 70:
```
node program.js 70
```
running the program using 1 power plant and cities [0,3,5]:
```
node program.js 1 0 3 5
```
## Code:
```
const {performance} = require('perf_hooks');
class City{
constructor(city, left, right, i){
this._city = city;
this._index = i;
this._left = typeof left === 'undefined' ? 0 : city - left;
this._right = typeof right === 'undefined' ? 0 : right - city;
}
get city(){return this._city;};
get index(){return this._index;};
get left(){return this._left;};
get right(){return this._right;};
set left(left){this._left = left};
set right(right){this._right = right};
valueOf(){return this._left;};
}
class Group{
constructor(...cities){
this._cities = cities;
// console.log(cities.map(a=>a.city).reduce((a,b)=>a===''?a+(b<10?' '+b:b):a+'-'+(b<10?' '+b:b),""));
// console.log(cities.map(a=>a.left).reduce((a,b)=>a===''?a+(b<10?' '+b:b):a+'-'+(b<10?' '+b:b),""));
// console.log(cities.map(a=>a.right).reduce((a,b)=>a===''?a+(b<10?' '+b:b):a+'-'+(b<10?' '+b:b),""));
// console.log("+==+==+==+==+==+==+==+==+==+==+==+==")
this._dist = cities[cities.length-1].city - cities[0].city;
this._max = Math.max(...cities); //uses the ValueOf to get the highest Distance to the Left
}
get dist(){return this._dist;};
get cities(){return this._cities;};
get max(){return this._max;};
split(){
//var index = this.cities.findIndex(city=>city.left == this.max);
//this.cities[index].left = 0;
// console.log(`Slicing-${this.max}-${index}------`)
var centerIndex = this.cities.length / 2;
var splitIndex = Math.floor(centerIndex);
if(centerIndex%1 > 0){
var center = this.cities[splitIndex];
if(center.right > center.left){
splitIndex++;
}
} else {
var right = this.cities[splitIndex];
var left = this.cities[splitIndex-1];
if(left.left > Math.max(right.right,right.left)){
splitIndex--;
} else if(right.right > Math.max(left.left,left.right)){
splitIndex++;
}
}
// console.log(splitIndex);
this.cities[splitIndex].left = 0;
this.cities[splitIndex-1].right = 0;
var leftCities = [...this.cities.slice(0,splitIndex)];
var rightCities = [...this.cities.slice(splitIndex)];
// var center = this.cities[]
if(leftCities.length <= 1){
if(rightCities.length <= 1){
return [];
}
return [new Group(...rightCities)]
}
if(rightCities.length <= 1){
return [new Group(...leftCities)];
}
return [new Group(...leftCities), new Group(...rightCities)];
}
center(){
if(typeof this._center === 'undefined'){
if(this.cities.length == 1){
return [0];
}
if(this.cities.length == 2){
return this.cities[1].left;
}
var index = Math.floor(this.cities.length/2);
this._center = this.cities.reduce((a,b)=> {
// console.log(`${a} + (${b.city} - ${city.city})`);
return a + Math.abs(b.city - this.cities[index].city);
},0);
// console.log(this._center);
}
return this._center;
}
valueOf(){return this._max;};
}
function crunch(plants, cities){
var found = [];
var size = cities.length;
cities = cities.map((city,i,arr)=> new City(city,arr[i-1],arr[i+1],i));
var groups = [new Group(...cities)];
// console.log(groups);
for(;plants>1;plants--){
var mapped = groups.map(g=>g.center()-g.max);
var largest = Math.max(...groups);
// console.log('Largest:',largest)
// console.log(...mapped);
var index = groups.findIndex((g,i)=> mapped[i] == g.center() - g.max && g.max == largest);
// console.log(index);
groups = index == 0 ?
[...groups[index].split(),...groups.slice(index+1)]:
[...groups.slice(0,index),...groups[index].split(),...groups.slice(index+1)];
}
// console.log(`=Cities=${size}================`);
// console.log(groups);
size = groups.map(g=>g.cities.length).reduce((a,b)=>a+b,0);
// console.log(`=Cities=${size}================`);
var wires = groups.map(g=>g.center());
// console.log(...wires);
// console.log(`=Cities=${size}================`);
console.log(`Wire Length Needed: ${wires.reduce((a,b)=>a + b,0)}`);
}
function biggestGroup(groups){
return groups.find(g => g[g.length-1].orig - g[0].orig);
}
function* range (start, end, limit) {
while (start < end || typeof limit !== 'undefined' && limit-- > 0) {
yield start
start += 1 + Math.floor(Math.random()*100);
}
}
function* cities (score){
let n = Math.floor(Math.pow(2,score/5));
var start = 0;
while (n-- > 0 && start <= (1000 * n)) {
yield start;
start += 1 + Math.floor(Math.random()*100);
}
}
if(typeof process.argv[3] === 'undefined'){
crunch(1,[0, 2, 4, 6, 8]);
console.log("Correct Answer: 12");
crunch(3,[0, 1, 10, 11, 20, 21, 22, 30, 32]);
console.log("Correct Answer: 23");
crunch(5,[0, 1, 3, 6, 8, 11, 14]);
console.log("Correct Answer: 3");
crunch(6,[0, 1, 3, 6, 8, 14, 15, 18, 29, 30, 38, 41, 45, 46, 49, 58, 66, 72, 83, 84]);
console.log("Correct Answer: 49");
crunch(2, [0, 21, 31, 45, 49, 54]);
console.log("Correct Answer: 40");
crunch(2, [0, 4, 7, 9, 10]);
console.log("Correct Answer: 7");
var max = 0;
var min = Number.POSITIVE_INFINITY;
var avg = [];
var score = typeof process.argv[2] === 'undefined' ? 60 : process.argv[2];
for(j = 0; j<10; j++){
var arr = []; for(let i of cities(score)) arr.push(i);
var plants = Math.floor(1 + Math.random() * arr.length);
console.log(`Running: Test:${j} Plants: ${plants}, Cities ${arr.length}, Score: ${score}`);
var t0 = performance.now();
crunch(plants,arr);
var t1 = performance.now();
time = (t1-t0)/1000;
console.log(`Time Taken = ${time} seconds`);
avg.push(time);
max = Math.max(time,max);
min = Math.min(time,min);
}
console.log(`Bench: ${avg.reduce((a,b)=>a+b,0)/avg.length} Max: ${max} Min: ${min} Total: ${avg.reduce((a,b)=>a+b,0)}`);
} else {
var plants = process.argv[2];
var arr = process.argv.slice(3);
console.log(`Running: Plants: ${plants}, Cities ${arr.length}`);
var t0 = performance.now();
crunch(plants,arr);
var t1 = performance.now();
time = (t1-t0)/1000;
console.log(`Time Taken = ${time} seconds`);
}
```
[Try it online!](https://tio.run/##vVh7b9s2EP/b/hRckNVSLTuWnaRtXKfYsgcCtGmxBh0Gw2hkm5aZOpInyXnM1WfP7khKImnJcTdsRmLR5N3vHrw7HnXt3XrxJGLLpBWEU/r4OAmDOCHrJY1mYXTjBROakgGJ6J8rFlGrgfOf52H4JW7Y/Xp9svDimJyx5GFdr3HWaDVJwsiawJRDFnSWOCRi/hwezAaaWjJncfszLgMsPvr5JAum9B5mWTGFADCTPCxpOCPi12BAGisgnbGAThvkDemQE45EWpyi4OaCC3b5s5RfrLUyjdJ6vebThP@07HVEk1UUkEL3ftoXBFxnk4JP5iSok0nB9QQCAh@k4eJNIj6ZUcUZEn7Za809@FDIBBj/zggzT/AnkNZrt95iRd/PqhRLs739NQpXS2Nz2@02OIHRGHaUyE/uG5gWOwuDfr58cEAQIVzQ9iL0LbHcvvGWljc49RDuwW5HdLqaUMvynLENs7BTjcYbr2mNX7udNw3SaI5PxvaJ12y0Gsaks7dn2ztL4y7836SJjfjPxO01B4Mn//bsPCmmLE7yDRpKZRc08JN5yx21ZSLJ5Y6YKFLqxsMMfeclczDwXomEPui1imHvkzkln0RwkSTk0Y1Tc/ACBck/gXisKriG829hL4p8Q@XMkMS5PJmEtJKUxGjLiFAzgwKm@jzu4@WCoQjFnbdeRLLaw6mlU6BATM95fqMPBqf43ZY1SBACqrYxCveQI44kPelU7t/VxwWbsMBv7a8zzBTGnD1t8c@VnTOjrhMaJDQ6L9FYbCM5IN2@xsGNzhj45s0WIVbpAkmxg83Uhe9dcko6isN0NXQNhoWkUV/jyEFFPgCm/CnqWV0j5pUsR2o2dag0/5USuogp2dQtr/y7qIYM2UFTSg95sWEMMojNPS3SgYsVBjpizK0znAefLda2Woa1wkYQqaCrQnNNHD4S5WZTJPlnHq4K24JZiZwKd5ckQaWj29nWdfQQRoiz7HQZQt1R4z6GFKJWx1GUGunsHPUJfp1bNbwy3Ef1uhETZ1omvh4Q19iKbCOfJMSPrGHDUdX@qEQBvRPHNZZlRYY9KtnOndUoRS8sVR1doD/F5JBqZUX7hSjC5WqxBq1lMycLv9wUvafb9HhJkRxs93hnq8srIbvVkGrcuCIntolQTyWlZG@KPejaOo7uGu2A0JsQsqmreTjtr72UNIm1vx7zTiCF3mB/zU9C/tO@MoQrBnvAyDX3xrE1zjqLkjOSd3@GL5yOMWNophppl4Vgvcz9kkHQp9VtsGwXgGK2CiYJCwMyiWA0t5YLL0hih@QNcA03ahZC9GFhkVHDD132F80bLblXYtXoknmrKG5MzPGiCHcG0wOvVWIaJocMiqMYNGHAsCPkon1MIl7UtJSa5NlUrxmuExzSaXDLs/rCqFNXDlotJYpRBii4pGifYOUK@4NTv51laMs3eiFesr3Ip7zZVPtFTXrJxjbeCraThiMB7CpSQBOaoS9qasJIPYsOzvLBZeBXQT9kI0zWQn@IS24BefZMDmA5E4/ghmRmHHz5JkgF4PiCi6UWv8Pc9izsZSvq5AvyHOLLTdcenVQA5OedUMP5duQsAcpSfiAK8WB/jRGcDoxPlvDbgkqG/ka0qKmwcSNqjvOc/zd6YRjcsYjnV1W4bhEDLuPc5VbuqoTG8zvgwT2HHxEXlE7p9ARqKJdi@gAqJnohRRy1@IyZj6Eoslu6GkqPrFlKtFs@gSj3h75ypQvheMUAx9scjnXs5yTyAp8SC@5lUeIQGkwdsmA3LLHl@XA3Z4tsnbxGAvL1a/5OBinJd8ZLFUgjvtBq8cuDctA8MLqYEo6VzwnkJhzI2Ykhzjo@BO2m4Y1lP3c7WXikuv6ynFrxJIwoumUBd8BAPzb5cBneWV2Hkx0c5QVUSOcNZ02aGgi90Qxp9YBYIL9DnpPARnNqNcWQ/r@zpGhqllE4oXHchsJzO@yNKvoaeRK5zrDjkK5DDh1y7JCXo5LY2zsLo4hOEvJDEN/R6IS43b2MTKD0OIoLf/iAZxdB8QnIPRj3ujsBd3sG8FEG3BPqCXT3cCc0E@x4Ewysdo/gH8bdV1JVGB8C0SHMHwLZIcwfwdwxjF@AOS@B@@VuChy@MjQA9qH0TC8TgfA7wnXK4cCIFw55hd7fCefFnlq6xNF8X1yW@ATD0L9Y3Yzhcv3h/cfzy/NPP38@v/jl/OL88o@Czrv1lYal6FowO4p3plpEdkclb0@P8fWpQSZvT9hbXHPtyPVrF7@bTaOzgIZGaMGJMXEZAbHyNY/IaBup2stVPLeY0WKIfkVP9Tz1snyDpEUAeewUAFqR/m0VBCzwT8gl9h776@uUfODgWKuFmNQh8gYJXXEOCLMfUU2k4/qmV4aSSQcUVF6otwOoQ6oeWmeJDaDB727nT9gN7piVuK2kYx9gnaow8hIpL70vFENkf42MKYkp0ExjVWuIDeFvpFDmjbd/uOrofZ@IPkHBAknBAlttODSVfqRgO/oOZZZ1BAe4IF0NwPdIi@/IyDsW8DELUnIZJt5iG4o4UdXXRVr4bMSvHp/qsmylemUnfR5EO4aO2rNsi5KqCHkqOioj45uiIn18fHT/Bg "JavaScript (Node.js) – Try It Online")
I will clean up the commented out code over the next couple of days as I am still working on this, just wanted to see if this was passing more than just the small cases.
[Answer]
# C (non-competing, pretest score = 76)
This is an attempt to translate @AndersKaseorg's second Rust solution to C.
```
typedef void V;typedef char C;typedef long L;
#define R return
#define W while
#define S static
#include<sys/syscall.h>
#define exit(x) ({L r;asm volatile("syscall":"=a"(r):"0"(SYS_exit ),"D"(x) :"cc","rcx","r11","memory");r;})
#define read(x,y,z) ({L r;asm volatile("syscall":"=a"(r):"0"(SYS_read ),"D"(x),"S"(y),"d"(z):"cc","rcx","r11","memory");r;})
#define write(x,y,z)({L r;asm volatile("syscall":"=a"(r):"0"(SYS_write),"D"(x),"S"(y),"d"(z):"cc","rcx","r11","memory");r;})
S V P(L x){C s[32],*p=s+32;*--p='\n';do{*--p='0'+x%10;x/=10;}W(x);write(1,p,s+32-p);}
#define N 0x100000 //max
#define INF (-1ul>>1)
S L cost[N],nk1,*am; //nk1:n-k+1, am:input's partial sums offset with the current "m" in _start()
S L f(L i,L j){if(i+1>=j&&cost[j]!=INF){L h=(i-j+1)>>1;R cost[j]+am[i+1]-am[j+h]-am[i-h+1]+am[j];}else{R INF;}}
S V smawk(L sh,L*c,L nc,L*r){ //sh:shift,c:cols,r:result
L n=nk1>>sh;if(!n)R;
L m=n>>1,u[m];
if(n<nc){
L ns=0,s[nc],sk[nc],*skp=sk;
for(L jk=0;jk<nc;jk++){
L j=c[jk];W(ns>0&&f(~(~(ns-1)<<sh),j)<=f(~(~(ns-1)<<sh),s[ns-1])){--ns;--skp;}
if(ns<n){s[ns++]=j;*skp++=jk;}
}
smawk(sh+1,s,ns,u);for(L i=0;i<m;i++)u[i]=sk[u[i]];
}else{
smawk(sh+1,c,nc,u);
}
L l=0,ish=(1<<sh)-1,dsh=1<<(sh+1);
for(L i=0;i<m;i++){
L k=u[i],bj=l,bc=f(ish,c[l]);
for(L j=l+1;j<=k;j++){L h=f(ish,c[j]);if(h<bc){bc=h;bj=j;}}
*r++=bj;*r++=k;l=k;ish+=dsh;
}
if(n&1){
L nsh=~(~(n-1)<<sh),bj=l,bc=f(nsh,c[l]);
for(L j=l+1;j<nc;j++){L h=f(nsh,c[j]);if(h<bc){bc=h;bj=j;}}
*r=bj;
}
}
S L inp(L*a){
L n=-1,l,v=0;C b[1<<20];
W(0<(l=read(0,b,sizeof(b))))for(L i=0;i<l;i++)if('0'<=b[i]&&b[i]<='9'){v=b[i]-'0'+10*v;}else{a[++n]=v;v=0;}
R n;
}
V _start(){
S L a[N];L n=inp(a),k=*a,s=0;for(L i=0;i<n;i++){a[i]=s;s+=a[i+1];}a[n]=s;
*cost=0;for(L i=1,l=n+1-k;i<l;i++)cost[i]=INF;
S L c[N];L nc=n+1-k;for(L i=0;i<nc;i++)c[i]=i;
S L r[N];nk1=n-k+1;for(L m=0;m<k;m++){am=a+m;smawk(0,c,nc,r);for(L i=n-k;i>=0;i--)cost[i]=f(i,r[i]);}
P(cost[n-k]);exit(0);
}
```
Compile with:
```
#!/bin/bash -e
clang -O3 -nostdlib -ffreestanding -fno-unwind-tables -fno-unroll-loops -fomit-frame-pointer -oa a.c
strip -R.comment -R'.note*' a
```
[Answer]
# [Clean](http://clean.cs.ru.nl/Clean), score = 65
```
module main
import StdEnv, System.IO
parseArgs :: *World -> ((Int, {#Int}), *World)
parseArgs world
# (args, world)
= nextArgs [] world
# args
= reverse args
# (k, a)
= (hd args, tl args)
= ((toInt k, {toInt n \\ n <- a}), world)
where
nextArgs :: [String] *World -> ([String], *World)
nextArgs args world
# (arg, world)
= evalIO getLine world
| arg == ""
= (args, world)
= nextArgs [arg:args] world
minimalWeight :: Int !{#Int} -> Int
minimalWeight k a
# count
= size a
# touches
= createArray ((count - k + 3) / 2 * k) 0
= treeWalk k count a [(0, 0, 0, 0)] touches
where
treeWalk :: Int !Int {#Int} ![(!Int, !Int, Int, Int)] *{Int} -> Int
treeWalk k verticies a [(weight, vertex, degree, requires) : nodes] touches
| vertex >= verticies
= weight
| requires >= k
= treeWalk k verticies a nodes touches
# index
= degree * k + requires
| (select touches index) > vertex
= treeWalk k verticies a nodes touches
# (next, pivot)
= (vertex + 1 + degree, verticies + requires)
# (nodes, touches)
= (orderedPrepend (weight, next, 0, requires + 1) nodes, update touches index (vertex + 1))
| pivot >= k + next
# (weight, vertex)
= (weight + (select a next) - (select a vertex), vertex + 1)
# nodes
= orderedPrepend (weight, next + 1, 0, requires + 1) nodes
| pivot == k + next
= treeWalk k verticies a nodes touches
# weight
= weight + (select a (next + 1)) - (select a vertex)
# nodes
= orderedPrepend (weight, vertex, degree + 1, requires) nodes
= treeWalk k verticies a nodes touches
= treeWalk k verticies a nodes touches
where
orderedPrepend :: (!Int, Int, Int, Int) ![(!Int, Int, Int, Int)] -> [(Int, Int, Int, Int)]
orderedPrepend a []
= [a]
orderedPrepend a [b : b_]
# (x, _, _, _)
= a
# (y, _, _, _)
= b
| y > x
= [a, b : b_]
= [b : orderedPrepend a b_]
Start world
# ((k, a), world)
= parseArgs world
= minimalWeight k a
```
Compile with:
`clm -h 1024M -gci 32M -gcf 32 -s 32M -t -nci -ou -fusion -dynamics -IL Platform main`
Takes `K`, and then each element of `A`, as command-line arguments.
] |
[Question]
[
# Your pyramid
The pyramid I want you to build is made entirely of cubes. It has 24 layers, and the Nth layer from the top contains N2 cubes arranged in an N by N square. The pyramid looks like this:
[](https://i.stack.imgur.com/ymtVx.png)
To build the pyramid, you will need a supply of cubes. You are given 4900 cubes arranged in a 70 by 70 square that looks like this:
[](https://i.stack.imgur.com/RwRhi.png)
(Okay, I admit that the picture of the square is entirely unnecessary.)
Since 12 + 22 + 32 + ... + 242 = 702, you have exactly the right number of cubes to build the pyramid. All you have to do is tell me where each cube should go.
# Your task
You should pick an arbitrary bijection between the cubes in the square and the cubes in the pyramid. (It would be nice if your answer said which of the 4900! different bijections you're using.)
Then, write a function or program that does the following:
* Given the location of a cube in the 70 by 70 square (as a pair of coordinates `(X,Y)`),
* Output its location in the pyramid (as a triple of coordinates `(A,B,C)`).
The input and output coordinates can all be either 0-indexed or 1-indexed. Assuming 1-indexed, your input `(X,Y)` will be a pair of integers between 1 and 70. Your output `(A,B,C)` will be a triple of integers; `A` should be the layer counting from the top (between 1 and 24) and `(B,C)` should be the coordinates of that cube within that layer (between 1 and `A`).
For example:
* the top cube of the pyramid has coordinates `(1,1,1)`.
* The four corners of the base of the pyramid have coordinates `(24,1,1)`, `(24,1,24)`, `(24,24,1)`, and `(24,24,24)`.
* If you decide to place the corners of the square at the corners of the pyramid, then on input `(70,1)` you might give the output `(24,24,1)`.
You may assume you will only be given valid coordinates `(X,Y)` as input. Correctness is entirely determined by the following rule: two different valid inputs should always give two different valid onputs.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"): the shortest code wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ 14 bytes
```
24p;€$€Ẏ
ḅ70ị¢
```
[Try it online!](https://tio.run/##y0rNyan8/9/IpMD6UdMaFSC21ud6uKPV3ODh7u5Di/7//x9tqKNgGAsA "Jelly – Try It Online")
This is fairly simple: we construct the list of coordinates of cubes within the pyramid as an actual list. Then all we need to do is biject the input coordinates within the square into an index within the list, which is trivial to do via base conversion.
This submission works either as a full program (taking the coordinates as `[x, y]` via the first command line argument and outputting on standard output), or as a function, implicitly named `2Ŀ`.
## Explanation
### Constructing the list
We start with the number `24`, which is interpreted as a range from 1 to 24 inclusive (because we're trying to use it as though it were a list). Then we iterate over it; that's what the last `€` in the program does. For each element *n* of the list:
* We construct the list of pairs *x*, *y* where each element comes from 1..*n*; `p` constructs a list of pairs given two sets of elements, and because only one value is available here (*n*), it's implicitly used for both sets, which both therefore become a list from 1..*n*.
* We append *n* (again, the only value we have available) to each element of the list (`;€`).
* In order to make the second `€` apply both of these operations to each *n* (i.e. to create a loop containing two instructions), we use `$` to group the two instructions into one.
Finally, we use `Ẏ` to flatten the list by one stage, in order to get a list that simply contains all the coordinates in order. It starts like this:
>
> [1, 1, 1], [1, 1, 2], [1, 2, 2], [2, 1, 2], [2, 2, 2], [1, 1, 3], [1, 2, 3], [1, 3, 3], [2, 1, 3], [2, 2, 3], [2, 3, 3], [3, 1, 3], [3, 2, 3], [3, 3, 3], [1, 1, 4], [1, 2, 4], [1, 3, 4], [1, 4, 4], [2, 1, 4], [2, 2, 4], [2, 3, 4], [2, 4, 4], [3, 1, 4], [3, 2, 4], [3, 3, 4], [3, 4, 4], [4, 1, 4], [4, 2, 4], [4, 3, 4], [4, 4, 4], …
>
>
>
and ends with [24, 24, 24].
### Indexing the list
We start by converting the input coordinates to a number by interpreting them as a base 70 integer: ḅ70. This gives us a value in the range 71 to 4970 inclusive; all these values are unique mod 4900. `ị` indexes into the list modulo the length of the list, so `[1, 1]` will give us the 71st element, `[1, 2]` the 72nd element, all the way up to `[70, 70]` which gives us the 70th element (i.e. the element before the answer for `[1, 1]`). Finally, we just need a `¢` to tell us which list to index (in this case, it's the list specified by the previous line; that's what `¢` does, run the previous line with no arguments).
[Answer]
# PHP, ~~75 82~~ 78 bytes
**0-indexed**:
set P=X\*70+Y then reduce P by A2 while walking down to the correct layer. A-1; P/A; P%A - done.
(reversed: while incrementing A to the correct layer: P=P+A2 then P=P+A\*B+C --> X=P/70, Y=P%70)
```
for($p=$argv[1]*70+$argv[2];$p>=++$a**2;$p-=$a**2);echo$a-1,_,$p/$a|0,_,$p%$a;
```
Run with `php -nr '<code>' <X> <Y>`; prints A\_B\_C.
**1-indexed, 82 bytes**:
```
for($p=$argv[1]*70+$argv[2]-71;$p>++$a**2;$p-=$a**2);echo$a,_,$p/$a+1|0,_,$p%$a+1;
```
[Answer]
# Python, ~~80~~ ~~73~~ 72 bytes
First submission, don't be too harsh q:
0-indexed
```
lambda x,y:[(a-1,b//a,b%a)for a in range(25)for b in range(a*a)][70*x+y]
```
Creates a list of length 4900 with all pyramind coordinates and returns a different list entry for each input.
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaFCp9IqWiNR11AnSV8/USdJNVEzLb9IIVEhM0@hKDEvPVXDyBQskoQQSdRK1IyNNjfQqtCujP1fUJSZV6KRpmGmY6Gp@f//fwA "Python 3 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 64 bytes
```
x,y=input()
n=-70*x-y
i=1
while n<0:i+=1;n+=i*i
print~-i,n/i,n%i
```
[Try it online!](https://tio.run/##XYzBDsIgEAXvfAUhMYG2ROqlCXU/BhXtJnVLCEa4@OtIPXp4h5lMXihp2ehU71vkmSPx6Ojh5WSUZXyX5V82Dq8Eq3tebs7KPBTVpM/@KoSoDeEXSMUI9GS6rAtDGNl7wdVzOhuLPYwz9YAdshCR0kfjQMe2A9b95As "Python 2 – Try It Online")
[Answer]
# C ~~89~~ , ~~87~~ , ~~82~~ , 71 bytes
[Took xnor's Python solution, and removed the linebreak](https://tio.run/##Pc7BCsIwDAbg@56iFAbt0mK9KJL1YUZlsoOzzAkJZb56bTcQksv3h58E@wgh56jIsE7ja1Hk7dV1bAv4M1LvkMADcMca4zLN66hkexf7SPO1bOhUti3xlp/DNCudmlpUTgV7h4J7f7khA@i/U3Xanaqn4wGMn/WtpCxVzZZ/)
```
p(x,y){for(x=-70*y-x,y=1;x<0;x+=++y*y);printf("%d %d %d",~-y,x/y,x%y);}
```
[0-indexed](https://tio.run/##PY5BCoMwEEX3niIIQuIkVDctZZybdFMsFhdNRbqYGfHsaWKh8FePx@OP4TmOKSkulr24bXqvloGkvXTQeyGlDnVgVCAAacWhBmJc1jl@Jls3D3PsFmsvofd6Eq9Ntvb0us/Ruq0qxSwbySUjA52vKADuz7lwPjgX/juC1Z6@)
```
z;p(x,y){for(x+=y*70+1,y=z=0;z<x;z+=++y*y);z-=x;printf("%d %d %d\n",y-1,z/y,z%y);}
```
[1-indexed](https://tio.run/##PY7BCoMwEETvfkUQhMRNqJ48rPsnvZQUi4emIj3srthfT6OFwszlMTwmhkeMOSsulr24bXqtloE@Qdqh80JKPerIqEAA0opDDcRBcFnn9J5s3dzNmWuqvXi9lDYCvcM9P29zsm6rDmcZGykuIyMNHQqA@3M@OJ@cD/67gtWevw)
```
z;p(x,y){for(x+=~-y*70,y=z=1;z<x;z+=++y*y);z-=x-y;printf("%d %d %d\n",y,z/y,z%y+1);}
```
[Answer]
## Batch, 103 bytes
```
@set/an=%1*70+%2,i=0
:l
@set/an-=i*i,j=i,i+=1,k=n%%i,l=n/i
@if %l% geq %i% goto l
@echo %j% %k% %l%
```
0-indexed. Works through each layer starting from the top.
[Answer]
# J, 37 bytes
*-4 bytes thanks to FrownyFrog*
```
(a:-.~,(<:,&.>{@;~&i.)"0 i.25){~70&#.
```
Fairly straightforward translation of the Jelly method into J. Uses 0 indexing. The top pyramid square is the first. The bottom right corner of the base is the last.
The majority of the code is boilerplate to produce the triple indexed list as a constant. Finding the correct element within that list based on the 2 element input is simply a matter of translating from base 70 with `70&#.`
[Try it online!](https://tio.run/##y/qfVqxga6VgoADE/zUSrXT16nQ0bKx01PTsqh2s69Qy9TSVDBQy9YxMNavrzA3UlPX@a3Ip6Smop9laqSvoKNRaKaQVc3GlJmfkK6QBjTFEMI0QTFMY08wSiP4DAA "J – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 13 bytes
```
!foEG▲π3Π4B70
```
[Try it online!](https://tio.run/##yygtzv7/XzEt39X90bRN5xuMzy0wcTI3@P//f7ShkY6JQSwA "Husk – Try It Online")
Indices start from 1.
## Explanation
Like some other answers, I construct the full list of pyramid coordinates and simply index into it.
I do this by listing all triples `[A,B,C]` where the numbers are between 1 and 24 (expressed as 4! to save a byte) and keeping those for which `A >= max(B,C)`.
```
!foEG▲π3Π4B70 Implicit input: a list of two numbers.
B70 Interpret in base 70.
! Modular index into the following list:
Π4 Factorial of 4: 24
π3 Take range and 3-fold Cartesian power: [[1,1,1],[1,1,2],..,[24,24,24]]
f Filter by
oE all values are equal
G▲ in cumulative reduce by maximum.
```
] |
[Question]
[
## Introduction
I have a room full of *magic mirrors*.
They are mysterious artifacts that can duplicate any item, except another magic mirror.
More explicitly, a duplicate version of the item will appear on the other side of the mirror, at the same distance.
However, if there is another magic mirror in the way on either side, between the duplicating mirror and either item (original or duplicate), the duplicate is not formed.
The original item can be either left or right of the mirror, and the duplicate will appear on the other side.
Also, the duplicate item can itself be duplicated by another mirror.
Items never block the duplication of other items (except by being directly on the position of the would-be duplicate).
## Input
Your input is a string consisting of the characters `.#|`, which represent empty space, items, and magic mirrors.
There will always be at least one magic mirror in the input.
## Output
Your output shall be another string where each magic mirror has duplicated every item it can, according to the rules above.
You can assume that there will always be an empty space on the spot where a duplicate item appears (so they will no go out of bounds).
## Examples
Consider the input string
```
.#.|.....|......#
A B C D
```
where we have marked some positions for clarity.
The mirror `B` duplicates item `A`, which ends up to its right:
```
.#.|.#...|......#
A B C D
```
Mirror `C` then duplicates the new item:
```
.#.|.#...|...#..#
A B C D
```
Mirror `C` cannot duplicate item `A`, since mirror `B` is in the way.
It also cannot duplicate item `D`, since mirror `B` is in the way on the other side.
Likewise, mirror `B` cannot duplicate item `D` or the duplicate next to it, since mirror `C` is in the way, so this is the correct output.
For another example, consider the input
```
.##..#...|#..##...|..##....#.
AB C DE FG H IJ K
```
Mirror `D` can duplicate `A` and `B` to the right, and `E` and `G` to the left.
`C` and `F` are already duplicates of each other.
The string becomes
```
.##.##..#|#..##.##|..##....#.
AB C DE FG H IJ K
```
Mirror `H` can duplicate `E`, `F`, and the duplicates of `A` and `B` to the right, and `I` to the left.
`G` and `J` are already duplicates of each other, and mirror `D` is in the way of `K`.
Now we have
```
.##.##..#|#..#####|#####..##.
AB C DE FG H IJ K
```
Finally, mirror `D` can duplicate the duplicate of `I` to the left.
We end up with
```
.#####..#|#..#####|#####..##.
AB C DE FG H IJ K
```
## Rules and scoring
You can write either a full program or a function.
The lowest byte count wins.
Submissions that don't use regex engines compete separately from those that do, and may be marked with **(no regex)**.
## Test cases
```
"|" -> "|"
"..|.." -> "..|.."
".#.|..." -> ".#.|.#."
"..#|.#." -> ".##|##."
".#..|....|.." -> ".#..|..#.|.#"
".|..|.#....." -> "#|#.|.#....."
"...|.#...|....#" -> ".##|##...|...##"
"......#|......." -> "......#|#......"
".#.|.....|......#" -> ".#.|.#...|...#..#"
".......|...#.##|...." -> "##.#...|...#.##|##.#"
"...#..||.......#..#...#" -> "...#..||.......#..#...#"
".##|.#....||#||......#|.#" -> ".##|##....||#||.....##|##"
".##..#...|#..##...|..##....#." -> ".#####..#|#..#####|#####..##."
".#|...||...|#...|..##...|#...." -> ".#|#..||.##|##..|..##..#|#..##"
"....#.|...#.|..|.|.....|..#......" -> "..#.#.|.#.#.|.#|#|#.#..|..#.#...."
"..|....|.....#.|.....|...|.#.|..|.|...#......" -> ".#|#...|...#.#.|.#.#.|.#.|.#.|.#|#|#..#......"
```
[Answer]
## [Retina](http://github.com/mbuettner/retina), 50 bytes
```
+`([#.])(([#.])*\|(?>(?<-3>[#.])*))(?!\1)[#.]
#$2#
```
[Try it online!](http://retina.tryitonline.net/#code=JShHYAorYChbIy5dKSgoWyMuXSkqXHwoPz4oPzwtMz5bIy5dKSopKSg_IVwxKVsjLl0KIyQyIw&input=fAouLnwuLgouIy58Li4uCi4uI3wuIy4KLiMuLnwuLi4ufC4uCi58Li58LiMuLi4uLgouLi58LiMuLi58Li4uLiMKLi4uLi4uI3wuLi4uLi4uCi4jLnwuLi4uLnwuLi4uLi4jCi4uLi4uLi58Li4uIy4jI3wuLi4uCi4uLiMuLnx8Li4uLi4uLiMuLiMuLi4jCi4jI3wuIy4uLi58fCN8fC4uLi4uLiN8LiMKLiMjLi4jLi4ufCMuLiMjLi4ufC4uIyMuLi4uIy4KLiN8Li4ufHwuLi58Iy4uLnwuLiMjLi4ufCMuLi4uCi4uLi4jLnwuLi4jLnwuLnwufC4uLi4ufC4uIy4uLi4uLgouLnwuLi4ufC4uLi4uIy58Li4uLi58Li4ufC4jLnwuLnwufC4uLiMuLi4uLi4) (The first line enables a linefeed-separated test suite.)
I guess this is the opposite of a (no regex) submission.
### Explanation
This is simply a regex substitution, which is applied repeatedly (`+`) until the string stops changing. I'm using [balancing groups](https://stackoverflow.com/a/17004406/1633117) to make sure that the two mirrored positions are the same distance from the given mirror (backreferences won't do, since the exact string on both sides of the `|` may be different).
```
([#.]) # Match and capture a non-mirror cell.
( # This will match and capture everything up to its corresponding
# cell so that we can write it back in the substitution.
([#.])* # Match zero or more non-mirror cells and push each one onto
# group 3. This counts the distance from our first match to
# the mirror.
\| # Match the mirror.
(?> # Atomic group to prevent backtracking.
(?<-3>[#.])* # Match non-mirror while popping from group 3.
) # There are three reasons why the previous repetition
# might stop:
# - Group 3 was exhausted. That's good, the next position
# corresponds to the first character we matched.
# - We've reached the end of the string. That's fine,
# the last part of the regex will cause the match to fail.
# - We've hit another mirror. That's also fine, because
# the last part of the regex will still fail.
)
(?!\1) # Make sure that the next character isn't the same as the first
# one. We're looking for .|# or #|., not for #|# or .|.
[#.] # Match the last non-mirror character.
```
This is replaced with `#$2#` which simply replaces both the first and last character of the match with a `#`.
[Answer]
## Perl, 49 bytes
Full credit to [@Martin Ender](https://codegolf.stackexchange.com/users/8478/martin-ender) for this one who suggested this regex 15 bytes shorter than mine.
47 bytes of code + `-pl` flags
```
s/([.#])(\||[^|](?2)[^|])(?!\1)[^|]/#$2#/&&redo
```
To run it :
```
perl -plE 's/([.#])(\||[^|](?2)[^|])(?!\1)[^|]/#$2#/&&redo' <<< ".##..#...|#..##...|..##....#."
```
The first (`([.#])`) and last (`(?!\1)[^|]`) parts are the same as in Retina answer (see the explanation over there).
The middle part (`(\||[^|](?2)[^|])`) uses perl recursion (`(?2)`) to match either a mirror (`\|`) or (`|`) two not-mirrors-characters (`[^|]`) separated by the very same pattern (`(?2)`).
---
My older (and uglier) version: `s/([.#])(([^|]*)\|(??{$3=~s%.%[^|]%gr}))(?!\1)[^|]/#$2#/&&redo`
[Answer]
# Haskell (no regex), 117 bytes
```
r=reverse
s=span(<'|')
m=zipWith min
g a|(b,l:c)<-s a,(d,e)<-s c=b++l:g(m(r b++[l,l..])d++e)|0<1=a
f x=m(g x)$r.g.r$x
```
[Answer]
# PHP, ~~123~~ ~~117~~ 100 bytes
```
for($t=$argv[1];$t!=$s;)$t=preg_replace("%([.#])(\||[.#](?2)[.#])(?!\g1)[.#]%","#$2#",$s=$t);echo$t;
```
program takes command line argument, regex taken from @Martin Ender/Dada. Run with `-r`.
[Answer]
# C, 176 bytes
```
void t(char*a){int x=0;for(int i=0;a[i];i++)if(a[i]=='|'){for(int j=x;a[j]&&j<=i*2-x;j++){if((a[j]==35)&&(a[2*i-j]==46)){a[2*i-j]=35;i=-1;}if((i-j)&&(a[j]=='|'))break;}x=i+1;}}
```
**Ungolfed**
```
void t(char*a)
{
int x=0;
for(int i=0;a[i];i++)
if(a[i]=='|')
{
for(int j=x;a[j]&&j<=i*2-x;j++)
{
if((a[j]=='#')&&(a[2*i-j]=='.'))
{
a[2*i-j]='#';
i=-1;
break;
}
if((i!=j)&&(a[j]=='|'))
break;
}
x=i+1;
}
}
```
[Answer]
## JavaScript (ES6), 170 bytes
```
s=>s.replace(/#/g,(c,i)=>(g(i,-1),g(i,1)),g=(i,d,j=h(i,d))=>j-h(j=j+j-i,-d)|s[j]!='.'||(s=s.slice(0,j)+'#'+s.slice(j+1),g(j,d)),h=(i,d)=>s[i+=d]=='|'?i:s[i]?h(i,d):-1)&&s
```
Ungolfed:
```
function mirror(s) {
for (var i = 0; i < s.length; i++) {
// Reflect each # in both directions
if (s[i] == '#') s = reflect(reflect(s, i, true), i, false);
}
return s;
}
function reflect(s, i, d) {
// Find a mirror
var j = d ? s.indexOf('|', i) : s.lastIndexOf('|', i);
if (j < 0) return s;
// Check that the destination is empty
var k = j + (j - i);
if (s[k] != '.') return s;
// Check for an intervening mirror
var l = d ? s.lastIndexOf('|', k) : s.indexOf('|', k);
if (l != j) return s;
// Magically duplicate the #
s = s.slice(0, k) + '#' + s.slice(k + 1);
// Recursively apply to the new #
return reflect(s, k, d);
}
```
] |
[Question]
[
I was wondering if there are any esoteric or golfing languages which specifically target text output and ASCII art?
For example, 05AB1E at least started by targeting base conversions. Are there any golfing languages targeting text output and text output art?
If so, do they have tip pages here, and are they in common use?
Note: I'm not looking for languages that are **able** to output ASCII art, but rather ones **intentionally** designed to be able to complete [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") challenges in a relatively short and concise way.
[Answer]
Well, as a matter of fact, there is! One such language is one I have been working on for a while called [V](https://github.com/DJMcMayhem/V).
Under the hood, V is just [vim](https://github.com/vim/vim), but all of the keystrokes are run automatically, and the contents of the vim buffer are printed to STDOUT when the program is over. This just makes running it more convenient.
Some history on the language. When I started using the vim text editor for code-golf, I discovered that it's actually pretty good at it, but has some annoying features that make it more difficult to compete it. For example, you can set up a "while loop" of sorts by doing
```
qq<foobar>@qq@q
```
which will repeat `<foobar>` until an error happens. This has 7 bytes of boilerplate code. In V, this is shortened to `ò<foobar>ò`.
Some of the things that make V great for ASCII-art:
* It is 2d by nature. One feature is that is has a "cursor" position, where most of the commands do something based on where the cursor is in the text. The other commands move the location of the cursor. For example, [x](http://v.tryitonline.net/#code=eA&input=SGVsbG8sIFdvcmxkIQ) deletes a single character, but [Wx](http://v.tryitonline.net/#code=V3g&input=SGVsbG8sIFdvcmxkIQ) moves forward a word and *then* deletes a character. Since most other languages are not intentionally 2 dimensional, this offers a nice edge when the challenge is about [positioning text in 2D space](https://codegolf.stackexchange.com/a/86650/31716)
* It is *entirely* string based. You *can* use some mathy operations, but these are usually the longer way to achieve things.
* It uses [regex compression](https://codegolf.stackexchange.com/a/80654/31716) to quickly change text.
* All of it's internal memory, which is just a 2d array of characters, is implicitly printed when the program ends. Additionally, all inputs is implicitly added into [it's internal memory](http://v.tryitonline.net/#code=&input=V2hpY2ggbWVhbnMgdGhpcyBpcyBiYXNpY2FsbHkgYSAwIGJ5dGUgY2F0IHByb2dyYW0u), which is nice when most of the challenge is about changing the input in a certain way.
So I really enjoy using this language, and if you are looking for a specifically [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") language, I highly recommend it. *However*, I would also give a few disclaimers.
* It is very confusing to learn. It's also very powerful, but because it's based on a very popular text editor that is 30 years old, there are lot's of obscure features that could very easily confuse new users.
* Even though it is better at handling numbers than vim, it's number support is still not great. Personally, I think this makes it more fun to work in (kind of like using retina for tasks regex was never intended for). :D
* It is still a WIP. There are some bugs, and some things I haven't gotten around to adding yet.
* It doesn't have very many users. (Current number of users: 1).
If you are interested in learning more, here are some good resources:
* A [chat room](http://chat.stackexchange.com/rooms/40448/vim-golf) where I would be happy to answer any questions you have, and help explain how it works to you.
* A [tips thread](https://codegolf.stackexchange.com/questions/71030/tips-for-golfing-in-vim) for golfing in vim, but most of the tips carry over.
* A [meta post](http://meta.codegolf.stackexchange.com/a/9627/31716) describing V in some more detail.
[Answer]
I recently made a new programming language, called [Turtlèd](https://github.com/Destructible-Watermelon/turtl-d/), which operates on a grid of characters with a turtle, which moves around the grid, writes to the grid, and has control flow with the grid. The grid is implicitly printed at the end. By this fact that it does not have to write spaces, and that it can write the text spatially, rather than left to right, up to down, it probably makes it meet the definition given, being good at ascii art.
Currently, there are not any docs, so you probably will not be able to use it, unless you want to read my interpreter, which is probably not something you want to do. I think there may also be bugs in the interpreter, but the spec is not developed enough to say if it is a bug. Turtlèd will probably be finished soon, with docs and all, though
[Answer]
# Intro to ASCII-Golfing for 05AB1E (Base Conversion [Simple])
While 05AB1E isn't intended for ASCII-Art directly, I've won 2 challenges with it. The best thing about 05AB1E is that, even with the simple base conversion there's often tricks you can use to extend and even halve your byte-count. Often in ASCII challenges there are repitition tricks you can utilize to only draw half the pattern then flip and concatenate. If it's a four way pattern you can do things like zip and bifurcate to only draw a corner of the pattern. There's plenty of data-structure manipulation techniques to use in conjunction with this simple base compression idea.
---
**Here's a quick crash-course on a base conversion tactic:**
In 05AB1E I enumerate all of the characters used in the ASCII-art, for instance:
`--===___===--`
Would result in:
```
-
=
_
```
I then assign them numbers starting with 1 then 0 then 2:
```
- is 1.
= is 0.
_ is 2.
```
I replace the characters in the original string with the numbers:
```
1122200022211
```
I convert to decimal using the lowest possible base (3):
```
879412
```
([How to do this using 05AB1E](https://tio.run/nexus/05ab1e#@29oaGRkZGBgACQNDRWMD2/7/x8A))
I then convert it to base 214:
```
Jh]
```
([How to do this using 05AB1E](https://tio.run/nexus/05ab1e#@29hbmliaKRgZGji9P8/AA))
I then wrap it in the following code:
# [05AB1E](https://github.com/Adriandmen/05AB1E), 16 bytes
```
•Jh]•3B…102…-_=‡
```
[Try it online!](https://tio.run/nexus/05ab1e#@/@oYZFXRiyQNHZ61LDM0MAISOrG2z5qWPj/PwA "05AB1E – TIO Nexus")
[Or try it with intermediate steps displayed.](https://tio.run/nexus/05ab1e#@/@oYZFXRiyQdNExdnLRedSwzNDACEzrxtu66CiFZGQWKwBReUZqUapCSUaqgqFCSWlRHlAwryRfQVcHLGYA4cXrKCTmpYBFjCAitgpJlQqlxZl56QqPGhbqAI3JTM5QSM7PKy7NTS0Gq8xJLC5RMFYoS8wpTS3WU9IBqfv/HwA)
**Final explained:**
```
•Jh]• # Push the compressed ASCII integer.
3B # Convert it to base 3.
…102 # Push the keys to the conversion.
…-_= # Push the values to the conversion.
‡ # Transliterate, replace 0, 1 and 2 with the symbols.
```
Now, with this specific challenge the string is so short it doesn't make sense to do. I'd probably just push half the string and Palindromize for 10 bytes `"--===__"û` or golf it like Adnan did in the comments using factorial, smart man `•Jh]•3B5!…-=_‡`. He's also *(one of?)* the creator *(s?)* of 05AB1E.
---
**More complex example:**
<https://codegolf.stackexchange.com/a/106621/59376>
---
~~Also, maybe try Dennis' kolmogorov-complexity language: [Bubblegum](https://esolangs.org/wiki/Bubblegum); no idea how to use this.~~
[Answer]
# [Paintbrush](https://github.com/alexander-liao/paintbrush)
Paintbrush is a recreational programming language created by myself, Hyper Neutrino, for the purposes of being good at ASCII-Art. It doesn't compete well with Charcoal in many cases, but it can take input and do a variety of other things. It operates on a 2D grid of characters and is able to manipulate the background character, manipulate what is considered a background character at the time, shift rows and columns, move rows and columns, copy rows, columns, or the entire grid, etc.
Some examples may be found in the GitHub repository.
] |
[Question]
[
[](https://i.stack.imgur.com/D6JFs.png)
The above image is called a hexa-glyph. Hexa-glyphs are some cool patterns I made up while doodling during my DiffEq class. Here's how you make one:
1. Consider the following set of points, shaped like a regular hexagram. The inner hexagon is what will contain the final glyph, while the outer 6 points form a star and are where we will start drawing our lines.
[](https://i.stack.imgur.com/xXFjd.png)
2. From the outer six points, randomly select a pair. For efficiency, there should be at least one other point between the two selected points (otherwise, it would have no effect on the final figure). Then, from each of the two points, cast a *ray* towards the other. This ray is *blocked* by previous lines.
[](https://i.stack.imgur.com/UrsJn.png)
3. Repeat this process until all 9 edges have been formed, as shown in the next few images.
[](https://i.stack.imgur.com/mHPrD.png)
4. Here is an example of rays being blocked. The ends of the ray segment are still visible, but the middle portion is occluded by the first two segments we drew.
[](https://i.stack.imgur.com/7vCF9.png)
5. These two rays are also "blocked," but this doesn't cause any visible difference because they are blocked by the same other line.
[](https://i.stack.imgur.com/UTDzQ.png)
6. Fast-forwarding until all 9 lines are drawn. If you want a more detailed explanation of these skipped steps, I can expound.
[](https://i.stack.imgur.com/20aDx.png)
7. Finally, remove the points of the star. To make it look prettier, the thick dots are also removed.
[](https://i.stack.imgur.com/D6JFs.png)
# The challenge
You challenge is to output a visual representation of a random hexa-glyph. This is code-golf, fewest bytes wins.
1. All possible hexa-glyphs should appear with some positive probability. Different hexa-glyphs are generated by changing the order in which the 9 edges are drawn.
2. Furthermore, all images output by your program must be valid hexa-glyphs. Certain patterns (like a complete outline of the inner hexagon) cannot possibly appear as a hexa-glyph, and so you program mustn't output these.
3. The output should be a graphical image (printed to screen or file).
4. The hexagon must be regular, but can appear in any orientation.
5. Reflections / rotations are *not* considered unique. (This might make requirement 1 easier to follow).
[Answer]
## Mathematica, ~~273~~ ~~268~~ ~~264~~ 242 bytes
```
c=CirclePoints;b@_=k=1>0;Graphics[Line/@Cases[Append[Join@@({c@6,{3^.5/2,-Pi/6}~c~6}),{0,0}][[b@#=!k;#]]&/@TakeWhile[#,t=k;(r=t;t=b@#;r)&]&/@Join@@RandomSample[{#,Reverse@#}&/@Partition[Range@12,3,2,1]~Join~Array[{2#,13,2#+6}&,3]],{_,__}]]
```
The `` renders as a superscript `T` in Mathematica and is a postfix transpose operator.
Sorting out the bugs in this took forever... towards the end I hacked a few things together to make it work, so this is definitely suboptimal. I also wonder whether it might be better overall to implement the spec more literally via the lines across the outer hexagon and let Mathematica's geometry functions handle the intersections.
Note that this is a full program and if you want to run the code multiple times within a single REPL session you'll have to prefix it with `Clear[b]`.
Here are the results of 20 runs:
[](https://i.stack.imgur.com/NC07u.png)
### Explanation
This solution doesn't make use of the outer star points at all. Instead it works directly with the points that are part of the hexaglyph and lines that cover three of them at a time.
Let's label the points:
[](https://i.stack.imgur.com/w35iv.png)
`1` starts on a slightly weird corner but this is due to the (also somewhat weird) default behaviour of `CirclePoints`. Starting the hexagon from there turned out cheapest.
Now we want to find the relevant lines through three of those points which correspond to connected points of the outer star. The ones around the hexagon are of course just 3 adjacent points (modulo 12), starting from an odd number. The ones across the centre consist of an even number `n`, `13` and `n+6`.
Representations of these lines (in the form of lists of three points are generated by the following code):
```
Partition[Range@12,3,2,1]~Join~Array[{2#,13,2#+6}&,3]
```
The `Partition` generates the lines around the hexagon and the `Array` the lines through the centre. To process both beams, we map this function over the list of lines:
```
{#,Reverse@#}&
```
Now we shuffle these with `RandomSample` to process them in a random order. `Join @@` flattens the list of pairs so that we have a list of beams.
Short intermission: to keep track of which points are already blocked we use a lookup function `b`, which is initialised to `True` for all values by `b@_=k=1>0;`. When processing a beam we keep all points until the first point that has `b[n] == False` (*including* that one):
```
TakeWhile[#,t=k;(r=t;t=b@#;r)&]&
```
I feel like this is the most golfable part right now... the use of two temporary variables to [play Mastermind](https://www.youtube.com/watch?v=BvmRI6K8TS8) seems really expensive. Anyway, the result of this gives us the points in a line we're allowed to draw. Now this function is mapped over each of those points:
```
Append[Join@@({c@6,{3^.5/2,-Pi/6}~c~6}),{0,0}][[b@#=!k;#]]&
```
The first part generates the list of all 13 points using the interleaved results of two calls to `CirclePoints` (with different radii for the edge centres and the corners of the hexagon). Note the `b@#=!k` which now sets the lookup table's value for the current point to `False` so that no further beam can pass through it. Finally, the value is used as an index into the list of coordinates to get the correct 2D point.
```
Cases[...,{_,__}]
```
This discards all single-element lists, because they would render as individual (and visible) points. Finally we render the result:
```
Graphics[Line/@...]
```
[Answer]
# [Shoes](http://shoesrb.com/) (Ruby) Rev C 184 bytes
12 bytes saved by transferring responsibility for checking if a particular half-line should be drawn from the main program to the drawing method. The main program still has to check if the whole line is completely blocked, though.
```
Shoes.app{t=[]
d=->p,q{t[p]&&t[q]||line(p/6*8,p%6*14,q/6*8,q%6*14)}
%w{1I IW WM M5 5' '1 =A P. R,}.shuffle.map{|i|b=i.sum/2
c=b*2-a=i.ord
t[a]&&t[c]||(d[a,b]
d[b,c]
t[a]=t[b]=t[c]=1)}}
```
# [Shoes](http://shoesrb.com/) (Ruby) ~~205~~ ... Rev B 196 bytes
Shoes is a ruby-based tool for building GUI's etc. It's the first time I've used it. mothereff.in/byte-counter counts my submission as 196 bytes, but for some reason Shoes counts it as 202.
Also, Ruby lets you do things like `t[a=i.ord]` but strangely, it seems not to work as expected with Shoes.
```
Shoes.app{t=[]
d=->p,q{line(p/6*8,p%6*14,q/6*8,q%6*14)}
%w{1I IW WM M5 5' '1 =A P. R,}.shuffle.map{|i|b=i.sum/2
c=b*2-a=i.ord
t[a]&&t[c]||(t[a]&&t[b]||d[a,b]
t[b]&&t[c]||d[b,c]
t[a]=t[b]=t[c]=1)}}
```
**Explanation**
I don't consider the parts of the line outside the hexagon. I only draw the part that needs to be drawn. The important thing is whether the lines cross the intersections (If we only draw the parts that need to be drawn, this means they begin / end at the intersections.)
The basic rule is that if both endpoints of a line have been visited, the line is blocked and should not be drawn. As the lines are drawn in two halves, we also have to check if the midpoint has been visited to see if each half should be drawn or not.
I keep track of which points have been visited in the array `t[]`. This ends up containing an entry for each physical coordinate on the grid below. There is no separate 13-element logical array. By the end, `t[]` may have 87 elements, though only up to 13 will contain useful data.
Internally, the coordinates of the endpoints of the lines are given by a single number z, where z%6 is the y coordinate and z/6 is the x coordinate. In this system the hexagon is flattened. When the lines are plotted, the x scale is multiplied by 8 and the y scale is multiplied by 14, which is a very close rational approximation to the correct ratio: 14/8=1.75 vs sqrt(3)=1.732.
The internal coordinate system is shown below, with a few sample outputs.
[](https://i.stack.imgur.com/a46gf.png)
**Ungolfed**
```
Shoes.app{
t=[] #Empty array for status tracking
d=->p,q{line(p/6*8,p%6*14,q/6*8,q%6*14)} #Drawing method. Convert p and q into x,y pairs, scale and draw line.
%w{1I IW WM M5 5' '1 =A P. R,}.shuffle.map{|i|#take an array of the coordinates of the endpoints of each line, shuffle, then for each line
b=i.sum/2 #b = midpoint of line, convert ASCII sum to number (average of the two coordinates)
a=i.ord #a = first endpoint of line, convert ASCII to number (no need to write i[0].ord)
c=b*2-a #c = second endpoint of line (calculating is shorter than writing i[1].ord)
t[a]&&t[c]||( #if both endpoints have already been visited, line is completely blocked, do nothing. ELSE
t[a]&&t[b]||d[a,b] #if first endpoint and midpoint have not both been visited, draw first half of line
t[b]&&t[c]||d[b,c] #if second endpoint and midpoint have not both been visited, draw second half of line
t[a]=t[b]=t[c]=1 #mark all three points of the line as visited
)
}
}
```
**More Sample outputs**
These were done with an older version of the program. The only difference is that the positioning of the hexaglyph in the window is now slightly different.
[](https://i.stack.imgur.com/vsWTe.png)
[Answer]
# Python, ~~604~~ ~~591~~ ~~574~~ ~~561~~ ~~538~~ ~~531~~ ~~536~~ ~~534~~ ~~528~~ ~~493~~ ~~483~~ ~~452~~ ~~431~~ ~~420~~ ~~419~~ ~~415~~ ~~388~~ ~~385~~ 384 bytes
I have adapted [Level River St's idea](https://codegolf.stackexchange.com/a/76943/47581) of checking if a line will be blocked by checking if both endpoints of the line have already been visited before. This saves 27 bytes. Golfing suggestions welcome.
**Edit:** Bug fixing and golfing `g(p,q)` for 3 bytes. Golfed `L` for one byte.
```
from turtle import*
from random import*
R=range
G=goto
*L,=R(9)
shuffle(L)
a=[0]*13
ht()
T=12
c=[(j.imag,j.real)for j in(1j**(i/3)*T*.75**(i%2/2)for i in R(T))]+[(0,0)]
def g(p,q):pu();G(c[p]);a[p]*a[q]or pd();G(c[q])
for m in L:
p=2*m;x,y,z=R(p,p+3)
if m<6:
if a[x]*a[z%T]<1:g(x,y);g(y,z%T);a[x]=a[y]=a[z%T]=1
else:
if a[p-11]*a[p-5]<1:g(p-11,T);g(p-5,T);a[p-11]=a[p-5]=a[T]=1
```
**Ungolfing:**
```
from turtle import*
from random import*
def draw_line(points, p_1, p_2):
penup()
goto(points[p_1])
if not (a[p] and a[q]):
pendown()
goto(points[p_2])
def draw_glyph():
ht()
nine_lines = list(range(9))
shuffle(nine_lines)
size = 12
center = [0,0]
points = []
for i in range(12): # put in a point of a dodecagon
# if i is even, keep as hexagon point
# else, convert to hexagon midpoint
d = 1j**(i/3) * 12 # dodecagon point
if i%2:
d *= .75**.5 # divide by sqrt(3/4) to get midpoint
points += (d.imag, d.real)
points.append(center)
a = [0]*13
for m in nine_lines:
p = 2*m
if m<6:
x, y, z = p, p+1, p+2
if not (a[x] and a[z%12]):
draw_line(points, x, y)
draw_line(points, y, z%12)
a[x] = a[y] = a[z%12] = 1
else:
if not (a[p-11] and a[p-5]):
draw_line(p-11, 12)
draw_line(p-5, 12)
a[p-11] = a[p-5] = a[12] = 1
```
The hexa-glyphs themselves are quite small as we use a 12-pixel hexagon as a base (for golfing reasons). Here are some example hexa-glyphs (apologies for the poor cropping):
[](https://i.stack.imgur.com/hWhwv.png) [](https://i.stack.imgur.com/vmVM6.png) [](https://i.stack.imgur.com/wdq6k.png) [](https://i.stack.imgur.com/mKdGO.png) [](https://i.stack.imgur.com/AadPN.png) [](https://i.stack.imgur.com/ctttA.png)
] |
[Question]
[
You should write a program or function which given three positive integers `n b k` as input outputs or returns the last `k` digits before the trailing zeros in the base `b` representation of `n!`.
## Example
```
n=7 b=5 k=4
factorial(n) is 5040
5040 is 130130 in base 5
the last 4 digits of 130130 before the trailing zeros are 3013
the output is 3013
```
## Input
* 3 positive integers `n b k` where `2 <= b <= 10`.
* The order of the input integers can be chosen arbitrarily.
## Output
* A list of digits returned or outputted as an integer or integer list.
* Leading zeros are optional.
* **Your solution has to solve any example test case under a minute** on my computer (I will only test close cases. I have a below-average PC.).
## Examples
*New tests added to check correctness of submissions. (They are not part of the under 1 minute runtime rule.)*
Input => Output (with the choice of omitting leading zeros)
```
3 10 1 => 6
7 5 4 => 3013
3 2 3 => 11
6 2 10 => 101101
9 9 6 => 6127
7 10 4 => 504
758 9 19 => 6645002302217537863
158596 8 20 => 37212476700442254614
359221 2 40 => 1101111111001100010101100000110001110001
New tests:
----------
9 6 3 => 144
10 6 3 => 544
```
This is code-golf, so the shortest entry wins.
[Answer]
# Mathematica, ~~57~~ 48 bytes
Saved 9 bytes thanks to @2012rcampion .
```
IntegerString[#!/#2^#!~IntegerExponent~#2,##2]&
```
[Answer]
## Python, 198 192 181 chars
```
def F(n,b,k):
p=5820556928/8**b%8;z=0;e=f=x=1
while n/p**e:z+=n/p**e;e+=1
z/=1791568/4**b%4;B=b**(z+k)
while x<=n:f=f*x%B;x+=1
s='';f/=b**z
while f:s=str(f%b)+s;f/=b
return s
```
It's fast enough, ~23 seconds on the biggest example. And no factorial builtin (I'm looking at you, Mathematica!).
[Answer]
# Pyth, ~~26~~ 35 bytes
```
M?G%GHg/GHH.N>ju%g*GhHT^T+YslNN1T_Y
```
This is a function of 3 arguments, number, base, number of digits.
[Demonstration.](https://pyth.herokuapp.com/?code=M%3FG%25GHg%2FGHH.N%3Eju%25g*GhHT%5ET%2BYslNN1T_Y%3A9+6+3&debug=0)
The slowest test case, the final one, takes 15 seconds on my machine.
[Answer]
## PARI/GP, 43 bytes
Trading speed for space yields this straightforward algorithm:
```
(n,b,k)->digits(n!/b^valuation(n!,b)%b^k,b)
```
Each of the test cases runs in less than a second on my machine.
[Answer]
# Haskell, ~~111~~ 109 bytes
```
import Data.Digits
f n b k=digits b$foldl(((unDigits b.reverse.take k.snd.span(<1).digitsRev b).).(*))1[1..n]
```
Usage: `f 158596 8 20` -> `[3,7,2,1,2,4,7,6,7,0,0,4,4,2,2,5,4,6,1,4]`
Takes about 8 seconds for `f 359221 2 40` on my 4 year old laptop.
How it works: fold the multiplication (`*`) into the list `[1..n]`. Convert every intermediate result to base `b` as a list of digits (least significant first), strip leading zeros, then take the first `k` digits and convert to base 10 again. Finally convert to base `b` again, but with most significant digit first.
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), 23 bytes
```
⌽k↑⌽{⍵↓⍨-⊥⍨0=⍵}b⊥⍣¯1⊢!n
```
This program works as long as the factorial does not exceed internal representation limit. In Dyalog APL, the limit can be raised by `⎕FR←1287`.
Assumes the variables n, b, and k have been set (e.g. `n b k←7 5 4`), but if you rather want prompting for *n*, *b*, and *k* (in that order) then replace the three characters with `⎕`.
[Answer]
# Python 3, 146 bytes
```
import math
i,f=input(),int
n=i.split()
e=math.factorial(f(n[0]))
d=''
while e>0:
d=str((e%f(n[1])))+d;e=e//f(n[1])
print(d.strip('0')[-f(n[2]):])
```
I'm not sure the test cases will all run fast enough - the larger ones are very slow (as it is looping through the number).
Try it online [here](http://repl.it/lsT) (but be careful).
[Answer]
# Java, ~~303~~ ~~299~~ 296 bytes
```
import java.math.*;interface R{static void main(String[]a){BigInteger c=new BigInteger(a[1]),b=c.valueOf(1);for(int i=new Integer(a[0]);i>0;i--){b=b.multiply(b.valueOf(i));while(b.mod(c).equals(b.ZERO))b=b.divide(c);b=b.mod(c.pow(new Integer(a[2])));}System.out.print(b.toString(c.intValue()));}}
```
On my computer, this averages a little under a third of a second on the `359221 2 40` testcase. Takes input via command line arguments.
[Answer]
# bc, 75 bytes
```
define void f(n,b,k){
obase=b
for(x=1;n;x%=b^k){
x*=n--
while(!x%b)x/=b}
x}
```
This uses some GNU extensions to reduce code size; a POSIX-conforming equivalent weighs in at 80 bytes:
```
define f(n,b,k){
obase=b
for(x=1;n;x%=b^k){
x*=n--
while(x%b==0)x/=b}
return(x)}
```
To keep run times reasonable, we trim the trailing zeros (`while(!x%b)x/=b`) and truncate to the final `k` digits (`x%=b^k`) as we compute the factorial (`for(x=1;n;)x*=n--`).
### Test program:
```
f(3, 10, 1)
f(7, 5, 4)
f(3, 2, 3)
f(6, 2, 10)
f(9, 9, 6)
f(7, 10, 4)
f(758, 9, 19)
f(158596, 8, 20)
f(359221, 2, 40)
f(9, 6, 3)
f(10, 6, 3)
quit
```
Runtime of the full test suite is approx 4¼ seconds on my 2006-vintage workstation.
[Answer]
## PHP, 80 bytes
```
function f($a,$b,$c){echo substr(rtrim(gmp_strval(gmp_fact($a),$b),"0"),-1*$c);}
```
Used as `f(359221,2,40)` for the last test case. Runs pretty smoothly for all test cases.
[Try here !](https://ideone.com/yt2zb9)
] |
[Question]
[
The [Koch snowflake](http://en.wikipedia.org/wiki/Koch_snowflake) (also known as the Koch star and Koch island) is a mathematical curve and one of the earliest fractal curves to have been described. It is based on the Koch curve, which appeared in a 1904 paper titled "On a continuous curve without tangents, constructible from elementary geometry" (original French title: "Sur une courbe continue sans tangente, obtenue par une construction géométrique élémentaire") by the Swedish mathematician Helge von Koch.

Here are some ascii representations of various iterations:
```
n=1
__
\/
n=2
__/\__
\ /
/_ _\
\/
n=3
__/\__
\ /
__/\__/ \__/\__
\ /
/_ _\
\ /
__/ \__
\ /
/_ __ __ _\
\/ \ / \/
/_ _\
\/
```
Since there is obviously a limit to the resolution of the ascii representation, we must enlarge the size of the snowflake by a factor of 3 for each iteration to show the extra detail.
Write the shortest code to output the snowflake in the same style for n=4
Your program should not take any input.
Your program should write the snowflake to the console.
[Answer]
## Python, 650 612 594 574 characters
```
n='\n'
S='_a/G\F I\n'
A=dict(zip(S,('III',' ','__/',' G','\ ','F__',' ','III','')))
B=dict(zip(S,('III',' ','\ ',' aF','/a ',' G',' ','III','')))
C=dict(zip(S,('___','aaa','/ ','GII','II\\',' F',' ','III','')))
def T(s):
a=b=c=d=r=u''
for k in s:
a+=A[k];b+=B[k];c+=C[k]
if k=='I':a=a[:-3]+('II\\'if'a '==d[1:3]else'GII'if' a'==d[:2]else 3*k)
d=d[3:]
if k==n:d=c.replace('____','__/F').replace('aaaa','aa ').replace('/ a','/a ').replace('a F',' aF');r+=a+n+b+n+d+n;a=b=c=''
return r
print T(T(T('__\n\G\n'))).translate({97:95,71:47,73:32,70:92})
```
This works by expanding the triangle by a factor of 3 each time. To do that, we need to keep track of whether each symbol is a left or right boundary (e.g. how `/` is expanded depends on which side of the `/` is the inside). We use different symbols for the two possible cases, as follows:
```
_: _, outside on the top
a: _, outside on the bottom
/: /, outside on the left
G: /, outside on the right
\: \, outside on the left
F: \, outside on the right
<space>: inside
I: outside
```
The `d` variable handles the special case where the expansion of an `a` needs to extend into the 3x3 in the next row.
[Answer]
## MS-DOS 16 bit machine code: 199 bytes
[Decode using this site](http://www.opinionatedgeek.com/dotnet/tools/Base64Decode/Default.aspx), save as 'koch.com' file and execute from WinXP command prompt.
```
sCAAxo7ajsKLz/OquF9fulwvvUoBM9u+BADoiQDodgDocwDogADobQDoagDodwCK8TLSs0+I98cHDQrGRwIktAnNIf7GOO5+7MNWAVwBYwFsAXoBgwGJB4DDAsOIN/7D6QQA/suIF/7P6R0A/suAPyB1AogH/suIB8OBw/8AiDfpBgD+x4gX/sM4734Ciu84z30Cis/Dg8UIg8UCgf1WAXLzg+0Mw07/dgB0GV/o9v/o5v/o8P/o3f/o2v/o5//o1//o4f9Gww==
```
**Update**
Here's an easy-to-read assembler version:
```
; L-System Description
;
; Alphabet : F
; Constants : +, -
; Axiom : F++F++F
; Production rules: F -> F-F++F-F
;
; Register usage:
; _ _
; bp = direction: 0 = ->, 1 = /|, 2 = |\, 3 = <-, 4 = |/_, 5 = _\|
; cl = min y, ch = max y
; bl = x (unsigned)
; bh = y (signed)
; si = max level
; clear data
mov al,20h
add dh,al
mov ds,dx
mov es,dx
mov cx,di
rep stosb
mov ax,'__'
mov dx,'/\'
; initialise variables
mov bp,Direction0
xor bx,bx
mov si,4
call MoveForward
call TurnRight
call TurnRight
call MoveForward
call TurnRight
call TurnRight
call MoveForward
mov dh,cl
xor dl,dl
mov bl,79
OutputLoop:
mov bh,dh
mov w [bx],0a0dh
mov b [bx+2],24h
mov ah,9
int 21h
inc dh
cmp dh,ch
jle OutputLoop
ret
Direction0:
dw MoveRight
dw MoveUpRight
dw MoveUpLeft
dw MoveLeft
dw MoveDownLeft
dw MoveDownRight
Direction6:
MoveRight:
mov w [bx],ax
add bl,2
ret
MoveUpRight:
mov b [bx],dh
inc bl
jmp DecBHCheckY
MoveUpLeft:
dec bl
mov b [bx],dl
DecBHCheckY:
dec bh
jmp CheckY
MoveLeft:
dec bl
cmp b [bx],20h
jne MoveLeftAgain
mov [bx],al
MoveLeftAgain:
dec bl
mov [bx],al
ret
MoveDownLeft:
add bx,255
mov b [bx],dh
jmp CheckY
MoveDownRight:
inc bh
mov b [bx],dl
inc bl
CheckY:
cmp bh,ch
jle NoMaxChange
mov ch,bh
NoMaxChange:
cmp bh,cl
jge NoMinChange
mov cl,bh
NoMinChange:
ret
TurnRight:
add bp,8
TurnLeft:
add bp,2
cmp bp,Direction6
jb ret
sub bp,12
ret
MoveForward:
dec si
push [bp]
jz DontRecurse
pop di
call MoveForward
call TurnLeft
call MoveForward
call TurnRight
call TurnRight
call MoveForward
call TurnLeft
call MoveForward
DontRecurse:
inc si
ret
```
[Answer]
# Perl, ~~176~~ 175 bytes
Posting this as a separate answer because it uses a binary source file, which is perhaps a bit cheaty. But considering that it’s still Perl *source code,* I think it’s remarkable that it beats the MS-DOS *machine code* solution!
### Source as base64-encoded
```
JF89IsLApwag0dhnMmAmMEcGIAcGQNHYwsDRFLsQ0djCwKcGoNHYwsDRFDdbECYwcRUxe1DCwNEUuxDR2
CI7c14uXiR4PW9yZCQmOyQieCgkeD4+MykucXcoXCAvXyBfXy8gXC8gX18gX1wgLyBfXy9cX18pWyR4Jj
ddXmVnO3NeLnsyN31eJF89cmV2ZXJzZSQmO3l+L1xcflxcL347cHJpbnQkJi4kXy4kL15lZw==
```
### Somewhat more readable
Replace all instances of `/<[0-9a-f]+>/` with the relevant binary data:
```
# Raw data!
$_="<c2c0a706a0d1d86732602630470620070640d1d8c2c0d114bb10d1d8c2>".
"<c0a706a0d1d8c2c0d114375b1026307115317b50c2c0d114bb10d1d8>";
# Decode left half of the snowflake (without newlines)
s^.^$x=ord$&;$"x($x>>3).qw(\ /_ __/ \/ __ _\ / __/\__)[$x&7]^eg;
# Reconstruct the right half and the newlines
s^.{27}^$_=reverse$&;y~/\\~\\/~;print$&.$_.$/^eg
```
In this version, the snowflake is encoded in the following way:
* The 8 bits in each byte are divided like this:
```
+---+---+---+---+---+---+---+---+
| 5 bits | 3 bits |
+---+---+---+---+---+---+---+---+
R C
```
* `R` encodes a run of spaces. The longest run is 27 characters, so all runs fit into 5 bits.
* `C` encodes a sequence of characters which are simply looked up in the literal array. (I used to have slightly crazier encodings here where the array contained only `/ \ _`, but the Perl code necessary to decode it was longer...)
* I am lucky that the binary data does not contain any `"`/`'` or `\` that would need escaping. I didn’t plan for this. But even if it did, I probably could have just changed the order of the items in the array to fix that.
* It is amazing how simple this solution is compared to the tens of other solutions I went through before I came up with this. I experimented with many different bitwise encodings more complex than this one, and it never occurred to me that a simpler one might be worth it simply because the Perl code to decode it would be shorter. I also tried to compress repetitions in the data using variable interpolation (see the other answer), but with the newest version that doesn’t gain any characters anymore.
[Answer]
## Python, 284
```
for s in "eJyVkNENACEIQ/+dgg1YiIT9tzgENRyWXM4/pH1tIMJPlUezIiGwMoNgE5SzQvzRBq52Ebce6cr0aefbt7NjHeNEzC9OAalADh0V3gK35QWPeiXIFHKH8seFfh1zlQB6bjxXIeB9ACWRVwo=".decode('base64').decode('zlib').split('\n'):print s+' '*(27-len(s))+'\\'.join([c.replace('\\','/')for c in s[::-1].split('/')])
```
With a bit more whitespace:
```
for s in "eJyVkNENACEIQ/+dgg1YiIT9tzgENRyWXM4/pH1tIMJPlUezIiGwMoNgE5SzQvzRBq52Ebce6cr0aefbt7NjHeNEzC9OAalADh0V3gK35QWPeiXIFHKH8seFfh1zlQB6bjxXIeB9ACWRVwo=".decode('base64').decode('zlib').split('\n'):
print s + ' '*(27-len(s)) + '\\'.join([c.replace('\\','/') for c in s[::-1].split('/')])
```
The left side is compressed; the right side is reproduced from the left side.
[Answer]
# Perl, ~~224~~ 223 characters
```
use MIME::Base64;$_=decode_base64 wsCnBqDR2GcyYCYwRwYgBwZA0djCwNEUuxDR2MLApwag0djCwNEUN1sQJjBxFTF7UMLA0RS7ENHY;s^.^$x=ord$&;$"x($x>>3).qw(\ /_ __/ \/ __ _\ / __/\__)[$x&7]^eg;s^.{27}^$_=reverse$&;y~/\\~\\/~;print$&.$_.$/^eg
```
### Somewhat more readable
```
use MIME::Base64;
# raw binary data in base-64-encoded form as a bareword
$_=decode_base64
wsCnBqDR2GcyYCYwRwYgBwZA0djCwNEUuxDR2MLApwag0djCwNEUN1sQJjBxFTF7UMLA0RS7ENHY;
# Decode left half of the snowflake (without newlines)
s^.^$x=ord$&;$"x($x>>3).qw(\ /_ __/ \/ __ _\ / __/\__)[$x&7]^eg;
# Reconstruct the right half and the newlines
s^.{27}^$_=reverse$&;y~/\\~\\/~;print$&.$_.$/^eg
```
### How it works
For an explanation of how it works, see [the other answer in which I post the same in binary](https://codegolf.stackexchange.com/questions/985/koch-snowflake-codegolf/1749#1749). I am really sorry that I am not actually *generating* the Koch snowflake, just compressing it...
### Previous versions
* **(359)** Encoded the entire snowflake instead of just the left half. Spaces were included in the bit encoding; no run-length yet. Used several interpolated variables plus a `@_` array which was accessed using `s/\d/$_[$&]/eg`. Newlines were encoded as `!`.
* **(289)** First version that encoded only the left half of the snowflake.
* **(267)** First version that used run-length encoding for the spaces.
* **(266)** Change `' '` to `$"`.
* **(224)** Radically different compression, encoded as base-64. (Now equivalent to the [binary version](https://codegolf.stackexchange.com/questions/985/koch-snowflake-codegolf/1749#1749).)
* **(223)** Realised that I can put the print inside the last subst and thus save a semicolon.
[Answer]
## Python, 338 bytes
```
#coding:u8
print u"碜䄎쀠ࢻ翀蝈⼖㗎芰悼컃뚔㓖ᅢ鄒鱖渟犎윽邃淁挢㇌ꎸ⛏偾헝疇颲㬤箁鴩沬饅앎↳\ufaa4軵몳퍋韎巃瓠깡未늳蒤ꕴ⁵ᦸ䥝両䣚蟆鼺伍匧䄂앢哪⡈⁙ತ乸ሣ暥ฦꋟ㞨ޯ庾뻛జ⻏燀䲞鷗".encode("utf-16be").decode("zlib")
```
Just another unicode exploit
run at [ideone](http://ideone.com/EAYUF)
] |
[Question]
[
Similar in spirit to [Number of distinct tilings of an n X n square with free n-polyominoes](https://codegolf.stackexchange.com/q/194056/53884) and [Partition a square grid into parts of equal area](https://codegolf.stackexchange.com/questions/179074/partition-a-square-grid-into-parts-of-equal-area), this challenge will have you count ways of partitioning a triangle in a triangular grid. The goal of this [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge is to write a program that outputs \$ a(n,m)\$, the number of ways to partition a triangle of side length \$n\$ into equal parts containing \$m\$ cells each. The parts must contiguous, where two cells are considered touching if they share a side.
# Examples
Up to rotation and reflection, there are two ways to partition the size-\$4\$ triangle into equal parts of size \$8\$, so \$a(4,8) = 2\$:
[](https://i.stack.imgur.com/cwPad.png)
[](https://i.stack.imgur.com/zF4zH.png)
Up to rotation and reflection, there are three ways to partition the size-\$4\$ triangle into four parts of size \$4\$, so \$a(4,4) = 3\$:
[](https://i.stack.imgur.com/IITjm.png)
[](https://i.stack.imgur.com/sDCut.png)
[](https://i.stack.imgur.com/F5DeW.png)
# Table
```
n | m | a(n,m)
---+----+-------
1 | 1 | 1
2 | 1 | 1
2 | 2 | 0
2 | 4 | 1
3 | 1 | 1
3 | 2 | 0
3 | 3 | 1
3 | 9 | 1
4 | 1 | 1
4 | 2 | 0
4 | 3 | 0
4 | 4 | 3
4 | 8 | 2
4 | 16 | 1
```
(I've made this table by hand, so comment if you spot any mistakes.)
# Challenge
Write a program that takes an input \$n\$, which is the size of a triangle, and a parameter \$m\$, which is the size of each region, and return the number of ways to partition the size \$n\$ triangle into \$n^2/m\$ parts of size \$m\$ *up to [the rotations and reflections of the triangle](https://en.wikipedia.org/wiki/Dihedral_group_of_order_6).*
Your code should be able to handle the inputs in the table on [TIO](https://tio.run/#), and it should be able to handle larger inputs in principle.
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so the shortest code wins.
[Answer]
# JavaScript (ES7), ~~367 362 359~~ 357 bytes
*Saved 1 byte thanks to @Shaggy*
Expects `(n)(m)`.
```
n=>m=>(T=Array(n*n).fill(N=0),g=(A,P=[-1],k=T.findIndex(v=>!v),B=[...A,P[S='sort']()][S]())=>g[B]?0:~[1,1,0,1,1,0][M='map'](r=>g[B=B[M](P=>P[M](i=>~i?(y=i**.5|0)*y-i-(r?1-((~y*~y+~i>>1)-n)**2:y*~-~y):i)[S]())[S]()]=1)/P[m]?~k?g(B):++N:T[M]((v,j)=>v||(~P?P.every(i=>(y=i**.5|0)^j**.5|(i-j)**2-1&&j-i+2*(i+y&1?y:~y)):j-k)||T[T[j]++,g(A,[...P,j]),j]--))([])&&N
```
[Try it online!](https://tio.run/##fZDBbqMwEEDv/Yr0QmbAJphkV7tIA2puPTRCKjfLK0UNQSYJVKRCawnx66lJKnVXhR48tvxm5o1dbtvt@aXRr2@8qnf5ZU@XiuITxZDRQ9NsDVRuhf5eH4@woQBZQfDAUpJcKHagzJJq91jt8r/QUnzfIluT9H3f5shnmp/r5m2uAJV8thEpLuRaJUHUS8EEC9g1KvlE89P21SY21wxayycFKcXpsGuKe52AIe26/o8uQNdwzaFJBAfojdsbr9dxLJBX6LphZG94bzDSeJNeoyKBi1SeVNIfkgLWGHneJsqG/tCy0k7Wdh30aZL6eZs3ZrD@o/xTXg@geTk4uHCckmsvdEF7xhGJiawRo5IfsOsymclSeR4r7FcNn5GyUqFdnCOCVOg4m8tLXZ3rY@4f6wL2IBBmAnG2WMzE3f8o/B6FNxSMoNV41XK64XK64YCW01W/x9Fq2rWadq0@XWPo413LEfTrhsKvSPz8GOPyDg "JavaScript (Node.js) – Try It Online")
## How?
### TL;DR
This is a recursive search that keeps track of all the patterns that were already tried, transformed in all possible ways, in order to prune the search as soon as possible when a collision is found. This allows it to perform at a decent speed on small triangles despite an otherwise inefficient piece-building method.
### Triangle description and cell indexing
A size-\$n\$ triangle is simply stored as an array of \$n^2\$ binary values. Empty cells are marked with \$0\$'s and occupied cells are marked with \$1\$'s.
JS initialization:
```
T = Array(n * n).fill(0)
```
By convention, the cells are numbered from \$0\$ to \$n^2-1\$, from left to right and top to bottom.
[](https://i.stack.imgur.com/myUWb.png)
Below are some basic formulas:
* The 0-indexed row of the cell \$c\$ is \$y\_c=\lfloor\sqrt{c}\rfloor\$
* The 0-indexed position of the cell \$c\$ within its row is \$c-{y\_c}^2\$
* The 0-indexed distance of the cell \$c\$ from the last cell in its row is \${(y\_c+1)}^2-c-1\$
### Testing whether 2 cells are neighbors
Two cells \$c\$ and \$d\$ are horizontal neighbors if \$y\_c=y\_d\$ and \$|c-d|=1\$ (e.g. \$c=10\$ and \$d=11\$, or the other way around).
Two cells \$c\$ and \$d\$ are vertical neighbors if either:
* \$c+y\_c\$ is even and \$d=c+2\times(y\_c+1)\$ (e.g. \$c=3\$ and \$d=7\$)
* \$c+y\_c\$ is odd and \$d=c-2\times y\_c\$ (e.g. \$c=7\$ and \$d=3\$)
Hence the following JS expression which is truthy if the cells `i` and `j` are ***not*** neighbors:
```
(y = i ** .5 | 0) ^ j ** .5 | (i - j) ** 2 - 1 && j - i + 2 * (i + y & 1 ? y : ~y)
```
### Reflections
A vertical reflection is applied by doing:
$$d=2\times y\_c\times (y\_c+1)-c$$
**Examples:**
$$2\times y\_{10}\times (y\_{10}+1)-10=2\times 3\times 4-10=14\\
2\times y\_{14}\times (y\_{14}+1)-14=2\times 3\times 4-14=10$$
[](https://i.stack.imgur.com/LHEJq.png)
### Rotations
A 120° rotation is applied by doing:
$$d=\left(n-\left\lfloor\dfrac{(y\_c+1)^2-c-1}{2}\right\rfloor\right)^2+{y\_c}^2-c-1$$
**Examples:**
* \$c=0\$ is turned into \$d=15\$
* \$c=7\$ is turned into \$d=12\$
[](https://i.stack.imgur.com/dasUy.png)
### Combining reflections and rotations
In the JS implementation, both formulas are combined into the following expression. This code applies a reflection to the cell `i` when `r = 0` or a rotation when `r = 1`.
```
(y = i ** .5 | 0) * y - i - (
r ?
1 - ((~y * ~y + ~i >> 1) - n) ** 2
:
y * ~-~y
)
```
To get all possible transformations of a tiling, we apply 2 rotations, followed by a reflection, followed by 2 rotations, followed by a reflection.
Hence the loop:
```
[1, 1, 0, 1, 1, 0].map(r =>
/* ... apply the transformation to each cell of each piece of the tilling ... */
)
```
### Describing the tiling
Each piece of the tiling is stored in an array of \$m+1\$ entries consisting of a leading `-1` followed by \$m\$ indices corresponding to the cells it contains.
The current piece is stored in `P[]`. The array `A[]` contains the previous pieces. The array `B[]` contains the previous pieces and the current piece, with all pieces sorted in lexicographical order and all indices also sorted in lexicographical order within each piece.
**Example:**
The following tiling:
[](https://i.stack.imgur.com/BGNXd.png)
would be described with:
```
B = [
[ -1, 0, 1, 2, 3 ],
[ -1, 10, 11, 4, 9 ],
[ -1, 12, 5, 6, 7 ],
[ -1, 13, 14, 15, 8 ]
]
```
Once coerced to a string, this gives a unique key that allows us to detect whether a similar configuration was already encountered and prune the search.
```
"-1,0,1,2,3,-1,10,11,4,9,-1,12,5,6,7,-1,13,14,15,8"
```
The purpose of the `-1` markers is to make sure that an incomplete piece followed by another piece in the key is not mixed up with another complete piece.
The keys are stored in the underlying object of the function `g`.
### Main algorithm
The recursive search function goes as follows:
* find the position `k` of the first empty cell in the triangle
* update `B[]`
* abort if `B[]` was already encountered
* apply all transformations to `B[]` and mark them as encountered
* if `P[]` is complete:
+ if the triangle is full (`k` is set to `-1`): we've found a new valid tiling, so increment the number of solutions `N`
+ otherwise, append `P[]` to `A[]` and start building a new piece
* if `P[]` is not yet complete:
+ if `P[]` does not contain any tile, append `k` to it
+ otherwise, try to append the index of each tile that has at least one neighbor in `P[]`
[Answer]
# [Scala 3](https://dotty.epfl.ch/), ~~526~~...~~358~~ 357 bytes
```
n=>m=>{val S=Set
var(c,d)=S(S(S(1->1)))->0
while(d<1&c!=S()){d=c.count{t=>t.size*m==n*n&t.forall(_.size==m)}
c=(for{t<-c
s<-t
a->b<-s
c=a%2*2-1
x->y<-S(a-1->b,a+1->b,(a+c,b+c))--t.flatten
if 0<y&y<=n&0<x&x<y*2}yield
S(0 to 4:_*).scanLeft(if(s.size<m)t-s+(s+(x->y))else t+S(x->y)){(t,i)=>t.map(_.map{(x,y)=>Seq((x,n+1-y+x/2),y*2-x->y)(i%2)})})map(_.head)}
d}
```
[Try it in Scastie!](https://scastie.scala-lang.org/UZoguHDFQ36m0XVp6C5ZdQ)
Dotty's tupled parameter destructuring save a few bytes, but it's pretty much the same as the approach below.
# Scala 2, ~~548~~...~~362~~ 361 bytes
```
n=>m=>{val S=Set
var(c,d)=S(S(S(1->1)))->0
while(d<1&c!=S()){d=c.count{t=>t.size*m==n*n&t.forall(_.size==m)}
c=(for{t<-c
s<-t
a->b<-s
c=a%2*2-1
x->y<-S(a-1->b,a+1->b,(a+c,b+c))--t.flatten
if 0<y&y<=n&0<x&x<y*2}yield
S(0 to 4:_*).scanLeft(if(s.size<m)t-s+(s+(x->y))else t+S(x->y)){(t,i)=>t.map(_.map{case(x,y)=>Seq((x,n+1-y+x/2),y*2-x->y)(i%2)})})map(_.head)}
d}
```
[Try it online](https://scastie.scala-lang.org/LRWqpdpxQcyDNEmTLjchWw)
[Ungolfed version](https://scastie.scala-lang.org/R8meXNzcR8aM580CtLYOWQ)
[To see the individual triangles](https://tio.run/##tVPLjtowFN3nK1xEkZ04ATKoalEcqYsuKnVWzG6KRiYYlDYxNDaIEPLt9NohhUm7GI2mDnZyH@f6Pg4q4Rk/bxY/RKLRPU8lqs663Ar0wGZCP5qNv0pNYZP53FmKVYzl1GhyeyZT4/IwN9643SM/HhFYra3a8wwtWRIkm53UlWaxDlR6FG7OmHTlYKCD1abgWYafrJ6xnNROusLLeHRKglR9ybe6JEmwSjMtipcGEJkSkC3NKW4SwWQ4xeBY6chPHBX52sGcLkjkKydhY5@/D93QwQdagmomfmHuj/14QblnX5h7CV14CSHpCo0iVg7KSA7g4zA4RKUbeuNrHu@ebBhSl6nIlghqUTazKCfaVx6G38GPwcEkibRn2tYoSIVPVBMWAwZyCFKomGuBNb0jUF7Ot1VzJlwJewmLTX/3TEK2JcT1xmQYOns39CHivq7JKuP6HhDQN1OVpvrfYXBpMPAJmFocUqXViZxsH0/I06A8D13HXHZkpd9ehLEEWEiMInSPhGJIhPhH4rwdkcDjrVi0/K@8uDSlJUfLDvYXPaAKqeH/pi5jfxVRdq8hyotmBwwIXkWboOEN3hGys51GO8scxx2aoaMcasa8WKsp@lwUvHyc6SKV6zlBDFUOgmVy1AJigOYbxMJWixAeU3gIbcWwK6KQjp7Jk1v7HUXjjvzMH@S7jv3TrTzp4Ccd/MTgn8sTmMSt/JGGt/L4A8SzYnMCNxC2vCwIivymCeTSFYS20CedSdzzL6tHLhbTsUKYfllakw5A9STrS4py1s8pKli/oGi90axfAciSre51MRcRmbhm3lcFQk9dhVX9bAaJexXqUfuga9hrkc26cX8oUi7XmZh@l8gg/7xuwNevG6DxaA1cKVFo3NbDWNFYasfs@vwb)
## Explanation
Each point is represented by an x-y pair `(Int,Int)`. The x-position starts out at 1 at the left and increases as it goes to the right. The y-position starts out at 1 at the top and increases as it goes to the bottom. A piece of the triangle is represented as a set of points (`Set[(Int,Int)]`), and a triangle (possible solution) is represented as a set of those pieces (`Set[Set[(Int,Int)]]`)
The first line defines `c`, a `Set` which will hold all possible solutions (and currently just holds a single partially completed triangle that holds a single piece that holds a single point (\$(1,1)\$, the top of the triangle)). `d` says how many of those triangles are completed. This is the variable that will be returned at the very end.
The bulk of the function is taken up by a while loop that runs as long as `d` is 0 and `c` is not empty (if `d` is more than 0, it means we've found all the triangles we're ever going to find, and if `c` is empty, it means there aren't any possible solutions).
Each iteration, `d` is set to the number of triangles in `c` that have has \$\frac{n\*n}{m}\$ pieces and all their pieces are of size `m`. For that, the expression `c.count{t=>t.size*m==n*n&t.forall(_.size==m)}` can be used.
Then, we find the next value of `c`. The code creates new triangles by adding neighbors to the old triangles in `c`, and to ensure only unique triangles are kept, it first creates a set of all 6 permutations for each of the new triangles. Because `c` is a `Set`, it removes duplicates by default without us having to do any work. After the permutations have been generated and the duplicates remove, it's simple to extract a single permutation with `<all_permutations>map(_.head)`.
When the while loop ends, we simply return `d`.
### Specifics:
**Generating new triangles**
For every shape in a triangle, we take all its neighbors, and remove the ones that are already in the triangle. Then, if the shape already has \$m\$ cells, we make a new shape containing only the neighbor and add it to the triangle, otherwise we add the neighbor to the shape. For comprehensions make this part easy:
```
for {
t <- c //For every triangle t in c
s <- t //For every piece/shape s in t
a -> b <- s //For every point (a, b) in s
e = a % 2 * 2 - 1 //This is just to reuse
//The cell to the left, the cell to the right, and the cell above/below
neighbors <- Set( (a - 1, b) , (a + 1, b) , (a + e, b + e) )
//x and y are the coordinates of the neighbor
x -> y <- neighbors -- t.flatten //Remove neighbors already in the triangle
//Make sure the neighbor is within bounds of the triangle
if 0 < y & y <= n & 0 < x & x < y * 2
} yield (
if (s.size < m) t - s + (s + (x -> y)) //If s is not full, add the neighbor to s
else t + Set(x -> y) //Otherwise, make a new shape containing just (x, y)
)
```
The new triangles are not directly yielded, this is just an example.
**Generating all permutations**
Each triangle has 6 different permutations, which can be found by alternating between reflecting over the y-axis and rotating 60 degrees clockwise + reflecting it over the y-axis. We can `scanLeft` over a range of numbers, doing the first transformation when the element is even, and the second when it's odd.
Assuming we already have a triangle `<new_triangle>`, we can scan left over a range of 5 numbers, leaving us with 6 triangles:
```
0.to(4).scanLeft(<new_triangle>){
(t, i) => //i is the current index/element, t is the triangle to transform
t.map { s => //Transform every shape s in t
s.map {
case (x, y) => //Transform every point in s (x, y)
//If i is even, it will rotate+reflect, if it's odd, it will reflect
Seq( (x, n + 1 - y + x / 2) , (y * 2 - x, y) )(i%2)
}
}
}
```
**Reflecting a point over the y-axis**:
For a point \$(x,y)\$, the y-coordinate stays the same after reflecting, and the x-coordinate becomes \$y \* 2 - x\$, since \$y \* 2\$ is the biggest possible x-coordinate for a given y-coordinate.
**Rotating a point 60 degrees clockwise + reflecting it over the y-axis**:
You can rotate and reflect a point at once if you keep the x-coordinate the same and set the y-coordinate to \$n + 1 - y + x / 2\$.
## Commented:
```
//Take n and m, curried
n => m => {
val S = Set //The Set companion object, to reuse later
//c holds all our possible solutions/triangles as we build them
//d holds how many of the triangles in c are complete
var (c, d) = S(S(S(1 -> 1))) -> 0
//While we haven't found any complete triangles and
//the set of possible solutions is nonempty, keep going
while (d < 1 & c != S()) {
//Count how many of c's triangles have n*n/m pieces, each with m cells
d = c.count { t => t.size * m == n * n & t.forall(_.size == m) }
//This for comprehension adds a cell to each triangle and
//generates all permutations of each new triangle
c = (for {
t <- c
s <- t
a -> b <- s
c = a % 2 * 2 - 1
x -> y <- S(a - 1 -> b, a + 1 -> b, (a + c, b + c)) -- t.flatten
if 0 < y & y <= n & 0 < x & x < y * 2
} yield
S(0 to 4:_*).scanLeft(
if (s.size < m) t - s + (s + (x -> y))
else t + Set(x -> y)
) { (t, i) =>
t.map(_.map { case (x, y) =>
Seq((x, n + 1 - y + x / 2), y * 2 - x -> y)(i % 2)
})
}
//Convert the Seq of permutations to a set so duplicates can be compared out of order and removed
) //End of massive for-comprehension
map (_.head) //Extract only the first permutation from each set of permutations
}
d
}
```
```
] |
[Question]
[
*Inspired by [Generate Keyboard Friendly Numbers](https://codegolf.stackexchange.com/questions/50047/generate-keyboard-friendly-numbers).*
## Background
Many number pads have the following layout:
`7``8``9`
`4``5``6`
`1``2``3`
`0`
We define a number's neighborhood as the set of cells orthogonally adjacent to it on the numpad shown, including itself. For example, 2's neighborhood is `{1,5,3,0,2}` and 0's neighborhood is `{1,2,0}`. There is a list of each number's neighborhood below, above test cases.
We define a ***numpad friendly number*** as a positive integer where, when written in decimal without leading zeroes, each digit except for the first is in the neighborhood of the previous digit.
For example,
* 7856 is a numpad friendly number because 8 is in the neighborhood of 7, 5 is in the neighborhoood of 8, and 6 is in the neighborhood of 5.
* 1201 is a numpad friendly number because 2 is in the neighborhood of 1, 0 is in the neighborhood of 2, and 1 is in the neighborhood of 0.
* 82 is **not** a numpad friendly number because 2 is not in the neighborhood of 8.
* 802 is **not** a numpad friendly number because 0 is not in the neighborhood of 8 (neighborhoods don't wrap around).
[Related OEIS Sequence](https://oeis.org/A124097). Note that this related sequence is distinct because it counts `0` as adjacent to `7` instead of `1` and `2`.
# Challenge
Given a positive integer `n`, return the `n`-th or the first `n` numpad friendly numbers, where the first is 1. You may use 0-based indexing, where the 0-th numpad friendly number would be 1.
# Neighborhoods
Each digits's neighborhood is listed here:
```
0:{0,1,2}
1:{0,1,2,4}
2:{0,1,2,3,5}
3:{2,3,6}
4:{1,4,5,7}
5:{2,4,5,6,8}
6:{3,5,6,9}
7:{4,7,8}
8:{5,7,8,9}
9:{6,8,9}
```
# Test Cases / Sequence
These are the first 100 terms
```
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 20, 21, 22, 23, 25, 32, 33, 36, 41, 44, 45, 47, 52, 54, 55, 56, 58, 63, 65, 66, 69, 74, 77, 78, 85, 87, 88, 89, 96, 98, 99, 100, 101, 102, 110, 111, 112, 114, 120, 121, 122, 123, 125, 141, 144, 145, 147, 200, 201, 202, 210, 211, 212, 214, 220, 221, 222, 223, 225, 232, 233, 236, 252, 254, 255, 256, 258, 320, 321, 322, 323, 325, 332, 333, 336, 363, 365, 366, 369, 410, 411, 412, 414, 441, 444, 445, 447]
```
[Answer]
# JavaScript (ES6), ~~104~~ ~~93~~ ~~89~~ 88 bytes
Returns the N-th term of the sequence, 1-indexed.
```
f=(i,k,n=k,N=n/5>>1)=>(N?8530025>>(n%10*6191^N%10*6191)%26&1:!i--)?N?f(i,k,N):k:f(i,-~k)
```
### Demo
```
f=(i,k,n=k,N=n/5>>1)=>(N?8530025>>(n%10*6191^N%10*6191)%26&1:!i--)?N?f(i,k,N):k:f(i,-~k)
for(n = 1; n <= 50; n++) {
console.log('a(' + n + ') = ' + f(n))
}
```
[Answer]
# [Perl 5](https://www.perl.org/), 123 + 1 (-p) = 124 bytes
```
while($_){$r=@d=++$\=~/./g;map$r&&=(120,1240,12350,236,1457,24568,3569,478,5789,689)[$d[$_-1]]=~/$d[$_]/,1..$#d;$r&&$_--}}{
```
[Try it online!](https://tio.run/##HYzRCoIwFEA/poso3s3duc2JDPqBvsBEAqUEy2FBD2Kf3tJeDgcOHN/Pow7hfRvGPoY2WWB2x86lKZzdJ@PZtbpfPMxR5GKSAkmqHbkWKHODpHSBUmljMdemRFVY1IUt0dgyqaGroWXUNNvp702GxDkcumo/bo2t6xICCfGd/GuYHs/ATpoLEoH5Hw "Perl 5 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~27~~ 24 bytes
Returns the N first terms of the sequence.
```
D⁽ÞȦ×^2\%26“⁷wð’æ»ḂẠ
1Ç#
```
[Try it online!](https://tio.run/##ATcAyP9qZWxsef//ROKBvcOeyKbDl14yXCUyNuKAnOKBt3fDsOKAmcOmwrvhuILhuqAKMcOHI///MTAw "Jelly – Try It Online")
This is a port of [my JS answer](https://codegolf.stackexchange.com/a/143681/58563).
```
D⁽ÞȦ×^2\%26“⁷wð’æ»ḂẠ - helper link: test numpad-friendliness of a number, e.g. 1257
D - get decimal digits -> [1, 2, 5, 7]
× - multiply by ...
⁽ÞȦ - ... the integer 6191 -> [6191, 12382, 30955, 43337]
^2\ - bitwise XOR overlapping reduce -> [10353, 18613, 53666]
%26 - modulo 26 -> [5, 23, 2]
æ» - right-shift by each value ...
“⁷wð’ - ... the integer 8530025 -> [266563, 1, 2132506]
Ḃ - isolate the LSB -> [1, 1, 0] which means that 1->2
and 2->5 are OK and 5->7 is not
Ạ - all (0 if there's any 0) -> 0, i.e. not numpad-friendly :'(
1Ç# - main link: return the [input] first matching numbers,
using our helper link as a monad and starting with 1
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~24~~ 23 bytes
```
µNSü‚εW_iO<ë<3BÆ}ÄR2‹}P
```
[Try it online!](https://tio.run/##AS4A0f8wNWFiMWX//8K1TlPDvOKAms61V19pTzzDqzwzQsOGfcOEUjLigLl9UP//MTAw "05AB1E – Try It Online")
Returns the nth number in the sequence.
**Explanations:**
```
µNSü‚εW_iO<ë<3BÆ}ÄR2‹}P Full program
µ Until counter is equal to input
N Push current iteration number (e.g. 1025)
S Split to a list of chars (-> ['1', '0', '2', '5'])
ü‚ Group into pairs (-> ['1', '0'], ['0', '2'], ['2', '5'])
ε For each pair
W_ Is smallest digit equal to 0?
iO< True: sum all digits and decrement
ë False:
< - decrement all digits
3B - convert to base 3
Æ - reduced substraction
} End if
Ä Absolute value
R Reverse
2‹ 1 if result is < 2, 0 otherwise
} End for each
P Cumulative product (1 if all pair results are
1, 0 otherwise)
-- implicit counter increment if stack value is 1
```
The main idea is that, apart from the `0` key, any digit decremented and converted to base 3 has the following properties:
* left and right neighbours have an absolute difference of 1
* up and down neighbours have an absolute difference of 10 which, reversed, is conveniently equal to 1
* any other pair of numpad keys result in different values, even when reversed
Of course we need a `if` statement to handle the `0` numpad key.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~29~~ 27 bytes
```
`@J3:qEt!J*+hYAd|2>~A?@]NG-
```
Outputs the first `n` numpad-friendly numbers.
[**Try it online!**](https://tio.run/##y00syfn/P8HBy9iq0LVE0UtLOyPSMaXGyK7O0d4h1s9d9/9/QwMDAA)
### Explanation
Each digit from `1` to `9` is encoded as a complex number representing its position in the numpad, using in a step-2 grid, where real part represents vertical position and imaginary part represents horizontal position. So `1` is `0+0j`, `2` is `0+2j`, `3` is `0+4j`, `4` is `2+0j`, ..., `9` is `4+4j`.
Digit `0` is encoded as `0+1j`, i.e. as if it were placed exactly between `1` and `2`.
For each candidate numpad-friendly number, a "decimal" base conversion is applied using the above complex numbers instead of the digits `0`, `1`, ..., `9`. This gives an array, of which the absolute consecutive differences are computed. The candidate number is numpad-friendly if and only if all absolute differences are at most `2` (i.e. the grid step). If that's the case, the number is left on the stack.
The code uses a `do`...`while` loop, which is exited when the amount of numbers in the stack equals the input `n`.
A unit grid would have been a more natural choice. Digits `1`, `2` and `0` would then correspond to `0+0j`, `1+0j` and `0.5+0j` respecrively. But it's golfier to use a step-2 grid, because multiplying by `2` (function `E`) and pushing `0+1j` (function `J`) is one byte shorter than pushing `0+0.5j` (`J2/` or `.5j`)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 26 bytes
```
’d-,.⁸?3µ€ạ/S
Dṡ2Ç€<2Ạ
1Ç#
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw8wUXR29R4077I0PbX3UtObhroX6wVwuD3cuNDrcDuTbGD3ctYDL8HC78v//hqYA "Jelly – Try It Online")
-2 bytes thanks to caird coinheringaahing
-2 bytes thanks to Erik the Outgolfer
# Explanation
```
’d-,.⁸?3µ€ạ/S Helper Link; compute the distance between two keys z = [x, y]
? Switch:
⁸ If z (is not 0):
’ Decrement
d Divmod by:
-,. Else: [-1, 0.5] (special position for 0)
3 3; right argument for divmod otherwise ignored
µ Begin a new monadic link / end this link
€ Compute the position for each [x, y]
/ Reduce on
ạ Absolute Difference
S Sum (this gives the Manhattan Distance)
Dṡ2Ç€<2Ạ Helper Link; determine if a number <z> is numpad friendly
D Convert number to decimal digits
ṡ Slice into overlapping slices of length
2 2 (pairs)
€ For each pair,
Ç The distance between the keys
<2 Compare with 2 (the distance between two adjacent keys is 1; corners 2; 0 - 1 and 0 - 2 are 1.5)
Ạ All; either all of the distances are less than 2 or there were no distances
1Ç# Main Link; find the first (input) numpad friendly numbers
# nfind; counting up from _ collect the first _______ matches that are
1 1
(input)
Ç Numpad Friendly
```
[Answer]
# [Python 2](https://docs.python.org/2/), 134 bytes
```
g=lambda n,k=1:n and g(n-(lambda l:all(abs(a-b)<1.2for a,b in zip(l,l[1:])))([~-d%3+~-d/3*1j-d/~d*1.5for d in map(int,`k`)]),k+1)or~-k
```
[Try it online!](https://tio.run/##LYzBasMwDIbvfQpdBlLrZHXDLmF9klCoMmeeG0c2tnfoDnn1zIEKpB/E/33xWX6CXLbNXj0vo2EQNV91L8BiwKI0@Pr7nr1HHjNyM9Knbi/fIQGrEZzAn4volR90fyMiHNbGvHWnet@7o37UWM1Rtx87Yfb@whGdFHWf73QjNZ80hbQ28@aWGFKB/MyHum2eSpq@flN2QbxbXMHuXIcOMVUcB4uJYLem3ZpY7IRaQXeu1lfHoq4Abf8 "Python 2 – Try It Online")
[Answer]
# Mathematica, ~~249~~ ~~234~~ 202 bytes
```
(a=o=1;While[a<=#,s=IntegerDigits@o;t=1;p=0;While[t+p<Length@s,If[!FreeQ[(IntegerDigits/@{210,4210,53210,632,7541,86542,9653,874,9875,986})[[s[[t]]+1]],s[[t+1]]],t++,p++]];If[t==Length@s,a++];o++];o-1)&
```
[Try it online!](https://tio.run/##VY1NC4JAFEX/ShGEMi9y1PGDccBFBEKLWrUYZiEx6kCpOG8X/XYbI4I2h8vlXO6jxs7c7NyI2avFICi/duauZV2IDVhR9ahbPR1Ma9CWA0cnjCL4SkjG4qT7FrvSQtXI9XHS@iK9v9W@fIY0gHgBixYmUQgpiylkCYtDyBMWQZbGkGcpc0hevpRWSlSKUKVgiUtQgITASIhS3J2hEL/v2pV8@GBH/e18nkyPq7KRNAjU/AY "Mathics – Try It Online")
*thanks user202729 for compressing data (-32 bytes)*
My results:
>
> 100 ->447
>
> 1000 ->20023
>
> 10000 ->788777
>
>
>
[Answer]
# PHP, 124+1 bytes
```
while($argn-=$r)for($p=$r=~0,$x=++$n;$x>=1;$p=[7,23,47,76,178,372,616,400,928,832][$c],$x/=10)$r&=!!($p&1<<$c=$x%10);echo$n;
```
Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/873fd8427780e2e1d16abf0a4f51cdd64086a0e4).
[Answer]
# Java 8, ~~192~~ 190 bytes
```
n->{int r=1,p;a:for(;n>0;){p=-1;for(int c:(r+++"").getBytes())if(p>-1&!"012;0124;01235;236;1457;24568;3568;478;5789;689".split(";")[c-=48].contains(p+""))continue a;else p=c;n--;}return~-r;}
```
Returns the (1-indexed) `n`'th number in the sequence.
This was surprisingly harder than I thought.. Probably just having some brain-farts this afternoon..
**Explanation:**
[Try it here.](https://tio.run/##NVDBbsIwDL3vK7wcpkSlVQstFLxw2H1cOE4cshJQWJtGTcqEUPfrXVI2yX7Ws6VnvXcRVxG3RurL8WusamEtvAul708ASjvZnUQlYRfotICKBtQM/Wbw7WsHGvio4@09nDqezQyKzantKOptiuxueJxh4JPAhnZRFBHCkrN0bzcnLWVMnajZ8vTlmaTZHH3nARYFzhdLzPJihfO8WJa4CJCvSixW5RqX5Zok1tTKUYKEfVQxz8tDUrXaeQ@WmvCGBap0L0GgrK0EwyvUcYxDJ13f6Z@4w2HEhxfTf9aqAuuE8@PaqiM0XoruXaf0@eMAgj2yCCFBAxy0/J4InSIB@PepeIagXnmWpn5GEZuuAPubdbJJ2t4lxms62iQ68amyiMzIX6zD@As)
```
n->{ // Method with integer as both parameter and return-type
int r=1, // Return-integer
p; // Previous digit
a:for(;n>0;){ // Loop (1) as long as the input is larger than 0
p=-1; // Start `p` at an integer that is not 0-9 (-1 in this case)
for(int c:(r+++"").getBytes())
// Loop (2) over the digits of the current number
if(p>=0 // If this is not the first digit (`p` != -1),
&!"012;0124;01235;236;1457;24568;3568;478;5789;689".split(";")[c-=48]
.contains(p+""))
// and the adjacent digits are NOT part of a NumberPad-Friendly Nr:
continue a; // Go to the next iteration of loop (1)
else // Else:
p=c; // Set `p` to the current digit for the next iteration
// End of loop (2) (implicit / single-line body)
n--; // If we haven't encountered the `continue`, decrease `n` by 1
} // End of loop (1)
return~-r; // Return the result-integer - 1
} // End of method
```
] |
[Question]
[
OEIS [has a variation](https://oeis.org/A111439) (A111439) on [Golomb's sequence](https://oeis.org/A001462). As in Golomb's sequence, `A(n)` describes how often `n` appears in the sequence. But in addition, no two consecutive numbers may be identical. While building up the sequence, `A(n)` is always chosen as the smallest positive integer that doesn't violate these two properties. Due to disallowed consecutive identical numbers, the series wobbles slightly up and down as it grows. Here are the first 100 terms:
```
1, 2, 3, 2, 3, 4, 3, 4, 5, 6, 5, 6, 5, 6, 7, 6, 7, 8, 7, 8, 9, 8, 9, 8, 9,
10, 9, 10, 9, 10, 11, 10, 11, 10, 11, 10, 11, 12, 11, 12, 13, 12, 13, 12,
13, 12, 13, 12, 13, 14, 15, 14, 15, 14, 15, 14, 15, 14, 15, 14, 15, 16, 15,
16, 17, 16, 17, 16, 17, 16, 17, 16, 17, 18, 17, 18, 17, 18, 19, 18, 19, 18,
19, 18, 19, 18, 19, 18, 19, 20, 19, 20, 21, 20, 21, 20, 21, 20, 21, 20
```
The full list of the first 10,000 numbers [can be found on OEIS](https://oeis.org/A111439/b111439.txt).
The challenge is to write a program or function which computes `A(n)`, given `n`. `n` is `1`-based to ensure that the self-describing property works.
## Rules
You may write a [program or a function](https://codegolf.meta.stackexchange.com/q/2419) and use any of the our [standard methods](https://codegolf.meta.stackexchange.com/q/2447) of receiving input and providing output.
You may use any [programming language](https://codegolf.meta.stackexchange.com/q/2028), but 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 valid answer – measured in *bytes* – wins.
## Test Cases
```
n A(n)
1 1
4 2
10 6
26 10
100 20
1000 86
1257 100
10000 358
```
[Answer]
## [Haskell](https://www.haskell.org/), 67 bytes
```
f k|k<4=k|p<-k-1=[n|n<-[1..],n/=f p,sum[1|a<-[1..p],f a==n]<f n]!!0
```
Defines a function `f`. [Try it online!](https://tio.run/nexus/haskell#Jck9CsAgDAbQq3xCR7UVOpqTSAaXQBFD6M/m3S2l63u9HgqCnYfeWNCrQVBSjGnjKWij5Z3asBxaSFR0aA5fs9eVBOavp5c06q/GXlCJlLNA2bltzhc "Haskell – TIO Nexus") It's very slow, computing `f 15` times out on TIO.
## Explanation
Just going with the definition: at every stage, choose the minimal positive number `n` that satisfies the constraints (not equal to previous entry, and has not occurred `f n` times yet).
```
f k -- Define f k:
|k<4=k -- If k < 4, it's k.
|p<-k-1= -- Otherwise, bind k-1 to p,
[n| -- compute the list of numbers n where
n<-[1..], -- n is drawn from [1,2,3,...],
n/=f p, -- n is not equal to f p, and
sum[1| -- the number of
a<-[1..p], -- those elements of [1,2,3,...,p]
f a==n] -- whose f-image equals n
<f n] -- is less than f n,
!!0 -- and take the first element of that list.
```
[Answer]
# Mathematica, ~~69~~ 68 bytes
*Thanks to Martin Ender for finding an extra –1 byte for me!*
```
Last@Nest[{##&@@#,1//.x_/;x==Last@#||#~Count~x==#[[x]]->x+1}&,{},#]&
```
Unnamed function taking a positive integer `n` as input and returning a positive integer. We construct the entire list of the first `n` elements of this sequence, then take the `Last` element. The list is constructed by starting with the empty list `{}` and operating on it with a function `n` times in a row (via `Nest`).
The function in question is `{##&@@#,1//.x_/;x==Last@#||#~Count~x==#[[x]]->x+1}&`, which takes a partial list of sequence values (essentially `##&@@#`) and appends the next value to it. The next value is computed by starting with `x=1`, then repeatedly replacing `x` by `x+1` as long as the condition `x==Last@#||#~Count~x==#[[x]]` is met—in other words, if either `x` is the previous element, or else `x` is already in the list the correct number of times. This function spits some errors, since (for example) we shouldn't be calling the `x`th element of the initial list `{}`; however, the values are all correct.
[Answer]
# Python 2, 99 86 bytes
Thanks to @Dennis for several improvements totaling 13 bytes!
```
s=0,1,2,3
exec't=1\nwhile t==s[-1]or s.count(t)/s[t]:t+=1\ns+=t,;'*input()
print s[-4]
```
The program proceeds pretty naively: It keeps track of the list of values it's determined so far, and looks to append the next value. It tries to append a `1` to the end of the list if it can; if not, then it tries a `2` and so on until something is allowed.
Now, we start by seeding the results for `1,2,3` to be `1,2,3`. This is done to avoid any problems with the list of already-computed values being too short: I **conjecture** that if `n` is at least `4` then `a(n)` is strictly less than `n`. (In this program, `s[n]` is equal to `a(n)`. Our list actually is initialized to be `[0,1,2,3]` because lists are `0`-indexed in Python. So for instance `a(1)=s[1]=1`, and `a(2)=s[2]=2`.)
So, let's say we're trying to determine `s[m]`, meaning that our list already includes `s[0], s[1], ..., s[m-1]`. We'll start at `t=1` and try to set `s[m]=1`. When that doesn't work, we go to `t=2` and try to set `s[m]=2`. Each time we increment `t`, we check whether `s.count(t)==s[t]`...but the right-hand side won't produce an error so long as we never have to go as high as `t=m`. The conjecture says that we never have to, since the first value we compute is actually `s[4]`.
This implementation computes 3 more values of the sequence than it needs to. For example if `n` is `8`, it'll compute up through `s[11]` before it returns the value of `s[8]`.
I'd be happy to see a proof of the conjecture. I believe it can be proven by (strong?) induction.
Edit: Here is a **proof of the conjecture**. We actually prove a slightly stronger form of the statement, since it involves no extra work.
**Theorem:** For all `n` greater than or equal to `4`, the term `a(n)` is less than or equal to `(n-2)`.
Proof (by Strong Induction): (Base `n=4`): The statement is true for `n=4`, since `a(4) = 2 = 4-2`.
Now assume `a(k)` is less than or equal to `k-2` for all `k` from `4` through `n`, inclusive (and assume `n` is at least `4`). In particular, this means that all previous terms of the sequence were at most `(n-2)`. We need to show that `a(n+1)` will be at most `(n-1)`. Now, by definition, `a(n)` is the smallest positive integer that doesn't violate any of the conditions, so we just need to show that the value `(n-1)` will not violate any of the conditions.
The value `(n-1)` will not violate the "no consecutive repeats" condition, because by the induction hypothesis the previous entry was at most `(n-2)`. And it won't violate the "`a(m)` is the number of times `m` appears" condition, unless `(n-1)` had already been reached `a(n-1)` times. But by the strong induction assumption, `(n-1)` had previously been reached `0` times, and `a(n-1)` is not equal to `0` since `a(m)` is positive for all `m`.
Therefore `a(n+1)` is less than or equal to `n-1 = (n+1)-2`, as desired. QED.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes
```
Ṭ€S<;1Tḟ®Ḣ©ṭ
⁸Ç¡Ṫ
```
The last three test cases are too much for TIO. I've verified **1000** and **1257** locally.
[Try it online!](https://tio.run/nexus/jelly#ASkA1v//4bms4oKsUzw7MVThuJ/CruG4osKp4bmtCuKBuMOHwqHhuar//zEwMA "Jelly – TIO Nexus") or [verify the first 100 terms](https://tio.run/nexus/jelly#ASoA1f//4bms4oKsUzw7MVThuJ/CruG4osKp4bmtCuKBuMOHwqFzMjVH//8xMDA "Jelly – TIO Nexus").
### How it works
```
⁸Ç¡Ṫ Main link. No arguments.
⁸ Yield [].
Ç¡ Execute the helper link n times (where n is an integer read from
STDIN), initially with argument [], then with the previous return
value as argument. Yield the last return value.
Tail; yield the last element of the result.
Ṭ€S<;1Tḟ®Ḣ©ṭ Helper link. Argument: A (array)
Ṭ€ Untruth each convert each k into an array of k-1 zeroes and one 1.
S Sum; column-wise reduce by +, counting the occurrences of all
between 1 and max(A).
< Compare the count of k with A[k] (1-indexed), yielding 1 for all
integers that still have to appear once or more times.
;1 Append a 1 (needed in case the previous result is all zeroes).
T Truth; find all indices of ones.
ḟ® Filter-false register; remove the value of the register (initially 0)
from the previous result.
Ḣ© Head copy; yield the first (smallest) value of the result and save
it in the register.
ṭ Tack; append the result to A.
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~77~~ 74 bytes
```
f=lambda n,k=1:n*(n<4)or map(f,range(n)+k*[n-1]).count(k)<f(k)or-~f(n,k+1)
```
This is a recursive implementation of [@mathmandan's algorithm](https://codegolf.stackexchange.com/a/109069/12012).
The implementation is **O(insane)**: input **9** takes 2 seconds locally, input **10** 52 seconds, and input **11** 17 minutes and 28 seconds. However, if declared as a regular function rather than a lambda, memoization can be used to verify the test cases.
[Try it online!](https://tio.run/nexus/python2#pZBBboMwEEXX4RSzQbGJQbhBXdBQ9R4RQi7YyMIMkU0qtYtendqE0gN0Mx5/vf9n7E4qGOU46S9JFC2jQ2uEc7vU6XYO6qHzXNNo1HPTECeNYuBxCF2moAK1M60wZmcSYXvnOSvnu8UVvwap3vFRO6ex3x2D/HzwH8L43NXhtXrrM0WSgLz8Rj7I6LBd/96yqMqI8b0TgGyoeIkJwUtBJwujuBHFrMBeEqSnIbliymuatdMdZzLQi/Jlsum3It564nR522KjsPOqVpyW28h/BEeR8jYEjcAZFAx4zuDpOZz5WnL/9zercYZjXHSQvkJ87o4Qgw8Ii1C6/AA "Python 2 – TIO Nexus")
Note that even with memoization, TIO cannot compute **f(1257)** or **f(10000)** (both verified locally).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~32~~ 31 bytes
```
XˆXˆG[N¯2(è<›¯¤NÊsN¢¯Nè‹&&#]N.ˆ
```
[Try it online!](https://tio.run/nexus/05ab1e#@x9xug2I3KP9Dq030ji8wuZRw65D6w8t8TvcVex3aNGh9X6HVzxq2Kmmphzrp3e67f9/QwMDAA "05AB1E – TIO Nexus")
**Explanation**
```
XˆXˆ # initialize global list as [1,1]
G # input-1 times do:
[ #] # loop until expression is true
N¯2(è<› # n > list[-2]-1
¯¤NÊ # list[-1] != N
sN¢¯Nè‹ # count(list, N) < list[N]
&& # logical AND of the 3 expressions
N.ˆ # add N to global list
and output last value in list and end of program
```
We are technically in loop `G` when we add **N** to global list, but all loops in 05AB1E use the same variable **N** as index, so the inner loop `[...]` has overwritten the **N** of `G` meaning we can add it outside the loop.
Issues with nested loops and conditionals prevents us from doing this inside the loop.
[Answer]
# Befunge, ~~141~~ 136 bytes
```
<v9\0:p8\2:*2:-1<9
v>p1+:3\8p0\9p:#^_&
>1-:#v_1.@>$8g.@
*+2%\>1-:!|>$!:::9g!\!9g!*\:8g\!8g`
9\+1g9::< \|`g9\g8+2::p
g2+\8p2+^:<>:0\9p::8
```
[Try it online!](http://befunge.tryitonline.net/#code=PHY5XDA6cDhcMjoqMjotMTw5CnY+cDErOjNcOHAwXDlwOiNeXyYKPjEtOiN2XzEuQD4kOGcuQAoqKzIlXD4xLTohfD4kITo6OjlnIVwhOWchKlw6OGdcIThnYAo5XCsxZzk6OjwgXHxgZzlcZzgrMjo6cApnMitcOHAyK146PD46MFw5cDo6OA&input=MTI1Nw)
Because of Befunge's memory limitations, it's not really practical to keep track of all previous entries entries in the sequence, so this solution uses an algorithm with a lower memory footprint which calculates the values more directly.
That said, we're still limited by the cell size, which in the Befunge-93 reference interpreter is a signed 8-bit value, so the highest supported even number in the sequence is `A(1876) = 126`, and the highest supported odd number is `A(1915) = 127`.
If you want to test larger values, you'll need to use an interpreter with a larger cell size. That should include most Befunge-98 implementations ([Try it online!](http://befunge-98.tryitonline.net/#code=PHY5XDA6cDhcMjoqMjotMTw5CnY+cDErOjNcOHAwXDlwOiNeXyYKPjEtOiN2XzEuQD4kOGcuQAoqKzIlXD4xLTohfD4kITo6OjlnIVwhOWchKlw6OGdcIThnYAo5XCsxZzk6OjwgXHxgZzlcZzgrMjo6cApnMitcOHAyK146PD46MFw5cDo6OA&input=MTAwMDA)).
[Answer]
# [Husk](https://github.com/barbuz/Husk), 18 bytes
```
!¡λḟ≠→¹f§<!#¹ŀΘ)ḣ3
```
[Try it online!](https://tio.run/##ASsA1P9odXNr//8hwqHOu@G4n@KJoOKGksK5ZsKnPCEjwrnFgM6YKeG4ozP///81 "Husk – Try It Online")
I decided to spare my soul and do it without combinators, and it's still the same size with them. Fun sequence.
just need to save a single byte...
## Explanation
```
!¡λḟ≠→¹f§<!#¹ŀΘ)ḣ3
ḣ3 start with [1,2,3]
¡λ ) apply the following repeatedly:
ŀΘ prepend zero, get range [1..length+1]
→ [1,2,3,4]
f§ filter out values where:
#¹ frequency in sequence
< is not less than
! ¹ projected frequency in sequence
→ [2,3]
ḟ find the first element
≠→¹ which isnt equal to the most recent element
→ 2
! take the nth element of this infinite list
```
[Answer]
# Python 2, 117 bytes
Meh. Not that short. The simple iterative solution.
```
L=[1,2,3]
n=input()
while len(L)<n:
for i in range(2,n):
if L.count(i)<L[i-1]and L[-1]!=i:L+=[i];break
print L[n-1]
```
[**Try it online**](https://tio.run/nexus/python2#DclBDsIgEAXQtZxi3EFEE@oOyw3mBqQLVKoTm9@G0PT4yO4lr3GIzg72PikEwbZXbdTxlSXTkqHZjPCK5rWQkIBKwifrwcJ4dZKZ@PZad1QtZuQoVzclvIljxzmI50uIMj2eJaef2oqg9kPP1twf)
Here's a really bad attempt at a recursive solution (129 bytes):
```
def f(n,L=[1,2,3]):
if len(L)>=n:print L[n-1];exit(0)
for i in range(2,n):
if L.count(i)<L[i-1]and L[-1]!=i:f(n,L+[i])
f(n,L)
```
] |
[Question]
[
This challenge is in honor of the tacky Christmas lights at my in laws' house.
---
**The challenge is to create a graphical output showing the decoration in "real time".**
The video (gif or other format) will have **n-by-m** vertical and horizontal "lights". **5 <= m,n <= 40**. The frame size and resolution may vary dependent on **n** and **m**, but must be at least **50x50** pixels for **n,m=5** (vector graphics is OK). A picture with `n=6` and `m=5` will look something like this:
[](https://i.stack.imgur.com/IJkq0.png)
---
## The decoration:
**Colors:**
All lights will have one of the following 6 RGB-colors `{255,0,0}`, `{0,255,0}`, `{0,0,255}`, `{255,255,0}`, `{0,255,255}` and `{255,0,255}`.
**Animation:**
* `n` and `m` will be taken as input on any reasonable format and in the order you like
* The image will change every `dt = 25 ms`. Deviations are OK if it's due to "outside factors" such as limitation in the interpreter, slow computer etc.
+ If it's *impossible* to set the time step manually, then the default time step is accepted.
* All lights will be red (`{255,0,0}`) at `t=0`.
* There's always a 5% chance that the first light (top-left) will change color. All colors (except the color it currently has) should be equally likely.
* Each light (except the first) will get the color of the light to its left. If the light is at the far left then it will get the color of the light on the far right on the row above. The lights are numbered as shown below. Light number `k` will get the color of the light number `k-1`.
```
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
```
* The output should in theory run for ever (unless your language / interpreter has some limitation that prevents this).
* Please provide a sample of at least 5 seconds, preferably more in the answer (this is an encouragement, not a requirement). (A link to TIO or similar is of course OK too :D )
* Frames, axes, grid lines etc are accepted.
**6-by-5**
[](https://i.stack.imgur.com/0kc10.gif)
**15-by-30**
[](https://i.stack.imgur.com/5UYW8.gif)
[Answer]
## JavaScript/CSS/HTML, 436 bytes
```
b="red"
f=_=>{o.textContent='';o.style.width=w.value*10+"px";o.style.height=h.value*10+"px"}
setInterval(_=>o.insertBefore(document.createElement("s"),o.firstChild).style.background=b=["red","yellow","lime","aqua","blue","fuchsia"][Math.random()*100|0]||b,25)
```
```
#o{overflow:hidden;background:red}s{display:block;float:left;width:10px;height:10px}
```
```
<div oninput=f()><input id=h type=number min=1><input id=w type=number min=1></div><div id=o>
```
[Answer]
# Mathematica, ~~186~~ ~~161~~ 158 bytes
```
(b=Table[{1,0,0},1##];Dynamic@Image[Partition[[[email protected]](/cdn-cgi/l/email-protection);If[Random[]<.06,b[[1]]={1,1,0,0}~RandomSample~3];b=RotateRight@b;b[[1]]=b[[2]];b,#],ImageSize->50#])&
```
**Explanation**
```
b=Table[{1,0,0},1##];
```
Create the initial board in 1D, filled with red. Store that in `b`.
```
[[email protected]](/cdn-cgi/l/email-protection)
```
Pause for 25ms
```
If[Random[]<.06,b[[1]]={1,1,0,0}~RandomSample~3]
```
If a (pseudo-)random real number is less than 0.06, replace the first element of `b` with a random sample length `3` of the list `{1,1,0,0}`. (i.e. any one of `{1, 1, 0}, {1, 0, 1}, {1, 0, 0}, {0, 1, 1}, {0, 1, 0}, {0, 0, 1}`)
```
b=RotateRight@b
```
Cyclic rotate right.
```
b[[1]]=b[[2]]
```
Change the first cell value to the second cell value (i.e. undo the shift of the first cell)
```
Partition[ ... ;b,#]
```
Partition `b` into (height).
```
Dynamic@Image[ ... ,ImageSize->50#]
```
Make that into a dynamic (constantly updating) image, whose width is 50(width)
**Cellular automaton version (186 bytes)**
```
(b=Table[{1,0,0},1##];Dynamic@Image[Partition[[[email protected]](/cdn-cgi/l/email-protection);If[Random[]<.06,b[[1]]={1,1,0,0}~RandomSample~3];i=2;b={#[[2-Boole[i--<0],2]]&,{},{1,1}}~CellularAutomaton~b,#],ImageSize->50#])&
```
**Sample Output** (inputs: 16, 10)
[](https://i.stack.imgur.com/npFVD.gif)
[Answer]
# MATLAB, ~~255~~ 210 bytes
This is my first golf, so there are probably improvements to be made.
Thanks to Luis for helping me save 45 bytes :)
```
function f(n,m)
c=dec2bin(1:6)-48;r=1;p=c(r,:);x=zeros(1,n*m,3);x(:,:,1)=1;while 1
x=circshift(x,[0,1,0]);if rand>0.94;r=randi(6);end
x(1,1,:) = c(r,:);imagesc(permute(reshape(x,n,m,3),[2 1 3]));pause(1/40);end
```
**Explanation:**
```
c=dec2bin(1:6)-48 % c is the colormap
r=1;p=c(r,:); % p is color number r (starting at 1) from the colormap c
x=zeros(1,n*m,3);x(:,:,1)=1; % 2D matrix in the third dimension. The first layer is 1
while 1 % while true
x=circshift(x,[0,1,0]); % shift the vector horizontally along the second dimension
if rand()>0.94; % 5 percent chance of changing color
k=randperm(6);k=k(k~=r);r=k(1); % Create a vector with color numbers 1..6. Discard the current color, and choose the first color
x(1,1,:) = c(r,:); % The first light gets color number r
imagesc(permute(reshape(x,n,m,3),[2 1 3])); % Reshape the vector so that it's a 3D matrix
% Permute it so that the dimensions are correct
% Use imagesc to display
pause(1/40) % 0.025 seconds pause
```
Unfortunately, this doesn't save the animation, it just runs it. In order to save it I either need a screen capture program, or rewrite it all using `imwrite`. Instead, I'll provide two pictures showing different times, for `n=15,m=30`.
[](https://i.stack.imgur.com/gJk0M.png)
[](https://i.stack.imgur.com/Bpbhq.png)
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~52~~ 47 bytes
```
6:BoHZGKipY"`tGe!2YG50Yr3>?t1)}6Yr]0(1YS.015Y.T
```
Input is an array `[ncols nrows]`. Output is a figure with vector graphics.
Example run for 15 cols × 10 rows:
[](https://i.stack.imgur.com/36TWg.gif)
### How it works
Pause time has been set to 15 ms (for the same byte count as 25 ms) to try compensate for the processing time.
To keep the color with 19/20 probability (change it with 1/20), we proceed as follows:
* With 47/50 probability we keep the color.
* With 3/50 probability we pick a new color choosen uniformly among the 6 colors. It may happen that the "new" color is the same as the old, and this occurs with probability 1/6.
Thus the probability of keeping the color is 47/50 + 3/(50\*6) = 19/20.
```
6: % Push [1 2 3 4 5 6]
B % Convert to binary. This gives a 6×3 matrix, where each row
% corresponds to a number. First row is [0 0 1] (blue), second is
% [0 1 0] (green), etc
o % Convert to double
HZG % Set as colormap (creates a figure)
K % Push 4
i % Take input array
p % Product of array. This gives the total number of squares
Y" % Repeat 4 that many times. This gives a row vector representing the
% image. The initial value, 4, corresponds to red in the colormap
` % Do...while
t % Duplicate
Ge % Reshape to size given by the input. Gives a matrix where each
% entry will be interpreted as a pointer to the colormap
! % Transpose. This is required because the color shifting will be
% done in column-major order: down, then across; whereas we want
% the opposite
2YG % Show matrix as image using the defined colormap
50Yr % Push a uniformly distributed random integer between 1 and 50
3> % True if greater than 3. This happens with probability 47/50
? % If true
t1) % Duplicate and get first entry (to repeat the first color)
} % Else
6Yr % Push a uniformly distributed random integer between 1 and 6.
% This is the new color (possibly the same as the old)
] % End
0( % Assign that color (repeated or new) to the last entry of the row
% vector representing the image
1YS % Circularly shift to the right. The last value becomes the first
.015Y. % Pause 0.015 ms
T % Push true
% End (implicit). Since the top of the stack is true, this creates
% an infinite loop
```
[Answer]
# MATLAB, ~~153~~ 147 bytes
**Note**: The GIF shown is of the older version, which is nice as it does not display axes (see edit history), but was *extremely* slow due to the implementation of `imshow`. For the current version, [Chelsea G.'s MATLAB answer](https://codegolf.stackexchange.com/a/105026/32352) or [Luis Mendo's MATL answer](https://codegolf.stackexchange.com/a/105045/32352) show the same result as my current version.
Size is taken as a `2x1` vector, so call as e.g.:
```
>> l([5 5])
```
---
```
function l(s)
c=eye(3);x=eye(s);while 1
a=rand>.94;x=[a*randi(6)+~a*x(1),x(1:end-1)];imagesc(reshape(x,s)',[1,6]);colormap([c;1-c])
pause(.025)
end
```
This answer exploits the subtleties of the MATLAB language. For example, `x` is initalized as an `m x n` zero matrix, but so-called *linear indexing* allows for circular shifting with 1-dimensional indices. Weak typing allows for multiplication with logicals, so that `if` statements are avoided (a trick I heavily used back in the days of programming on a TI-84 calculator). Even though a colormap is read row-wise, MATLAB treats it as a normal matrix, so that `eye(3)` can be used to create red, green and blue, and `1-eye(3)` the other three colours. A simple `reshape` brings the linear vector back into matrix form, which is mapped to the desired colours using `ind2rgb`. Finally, `imagesc`, shows the image, shown at default figure size (which is big enough for the requirements). As luck would have it, `imagesc` does not mind values being outside the specified range, so `eye` can be used to initialize the matrix since both `1` and `0` are considered red.
[](https://i.stack.imgur.com/Nurkm.gif)
[Answer]
# Python 3.6 (316 Bytes)
Using ANSI colour codes and the [new formatted string literals of Python 3.6](https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep498) ([PEP 489](https://www.python.org/dev/peps/pep-0489/)) (the `f"{X}"` magic).
Otherwise it’s just pretty basic, but obfuscated python. Width and Height are passed as arguments on the command line.
```
import random as n,time,sys
r=range
X="\x1b["
C=[f"{X}1;4{x}m " for x in r(1,7)]
w,h=list(map(int,sys.argv[1:]))
a=[C[0]for i in r(w*h)]
while 1:
print(f"{X}0m{X}2J{X}f");f=a[0];a.pop();a[:0]=n.choice([x for x in C if x!=f])if n.random()<=.05 else f,
for i in r(0,h*w,w):print(*a[i:i+w],sep="")
time.sleep(.025)
```
[](https://i.stack.imgur.com/IyXd2.gif)
] |
[Question]
[
According to the [Wikipedia page on the number 69](https://en.wikipedia.org/wiki/69_(number)), it is of note that \$69^2 = 4761\$ and \$69^3 = 328509\$ together use all decimal digits. The number **69** is in fact the lowest number that satisfies this property.
For a similar reason, \$32043\$ is remarkable: \$32043^2 = 1026753849\$ uses all decimal digits.
If we're going to keep talking about numbers that are interesting this way, we'll need some notation.
For most integers \$n\$, the powers \$n^2, ..., n^k\$ will use all ten decimal digits (not counting leading zeroes) at least once for sufficiently large values of \$k\$ . If it exists, we'll call the lowest such \$k\$ the *CUDDLE* (***CU**mulative **D**ecimal **D**igits, **L**east **E**xponent*) of \$n\$.
### Task
Write a program or a function that accepts a single non-negative integer \$n\$ as input and calculates and returns its *CUDDLE*.
If \$n\$ does not have a *CUDDLE*, you may return anything but a positive integer, including an error or an empty string, as long as your code halts eventually.
### Test cases
Left column is input, right column is output.
```
0
1
2 15
3 10
4 10
5 11
6 12
7 7
8 5
9 6
10
11 7
12 6
13 6
14 7
15 9
16 5
17 7
18 4
19 5
20 15
26 8
60 12
69 3
128 3
150 9
200 15
32043 2
1234567890 3
```
### Additional rules
* Your code must work for all inputs up to \$255\$.
*Note that this involves dealing with pretty large numbers. \$20^{15}\$ is already larger than \$2^{64}\$.*
* If you print the result, it may be followed by a linefeed.
* Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply.
[Answer]
## Python 2, 56
```
f=lambda n,i=2,s='L':len(set(s))>10or-~f(n,i+1,s+`n**i`)
```
A recursive solution. Counts up exponents `i` starting from `2` and accumulates the digits of powers `n**i` into the string `s`. When `s` has all ten digits, returns `True`, which equals `1`, and otherwise recurses and adds `1`. This turned out shorter than returning `i`.
Calling the function on a number without a CUDDLE terminates with `Internal error: RangeError: Maximum call stack size exceeded`. Numbers up to `255` that do output never need more than 15 iterations.
Because of Python 2's annoying habit of appending an `L` to large numbers, we actually initialize the digit string to `L` and check if the set size is at least 11. Python 3 saves 2 chars by not needing this, but loses 3 chars on using `str` over backticks. Python 3.5 saves 2 more chars with set unpacking, saving a char over Python 2 in total:
```
f=lambda n,i=2,s='':len({*s})>9or-~f(n,i+1,s+str(n**i))
```
[Answer]
# Pyth, 16 bytes
```
hf<9l{=+k^QTtS15
```
Try it online: [Demonstration](http://pyth.herokuapp.com/?code=hf%3C9l%7B%3D%2Bk%5EQTtS15&input=20&test_suite_input=0%0A1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12%0A13%0A14%0A15%0A16%0A17%0A18%0A19%0A20%0A26%0A60%0A69%0A128%0A150%0A200%0A32043%0A1234567890) or [Test Suite](http://pyth.herokuapp.com/?code=hf%3C9l%7B%3D%2Bk%5EQTtS15&input=20&test_suite=1&test_suite_input=0%0A1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12%0A13%0A14%0A15%0A16%0A17%0A18%0A19%0A20%0A26%0A60%0A69%0A128%0A150%0A200%0A32043%0A1234567890)
Like other solutions, I use 15 as an upper limit. I believe that this is also the maximal *CUDDLE*. I tested all numbers up to 10.000.000, and there's no number with a *CUDDLE* greater than 15.
Numbers with a *CUDDLE* >= 10 are already quite rare. The only numbers with a *CUDDLE* of 15 are the numbers `2*10^k`. There are no numbers with a *CUDDLE* of 14 or 13, the *CUDDLE* 12 only appears for the numbers `6*10^k`, the *CUDDLE* 11 only for `5*10^k`.
So I think this code works perfectly for any natural number.
Prints an error message, if there is no solution.
### Explanation:
```
hf<9l{=+k^QTtS15 implicit: Q = input number
k = empty string
tS15 the list [2, 3, 4, ..., 15]
f filter this list for elements T, which satisfy:
^QT compute Q^T
+k k + ^ (converts to string implicitly)
= k save the result in k
l{ k length of set of k (number of different chars)
<9 test if 9 is smaller than ^
h print the first number in the filtered list
(throws error if empty)
```
[Answer]
## Ruby, ~~67~~ 65 chars
```
->n{s='';[*2..99].index{|i|(s+="#{n**i}").chars.uniq.size==10}+2}
```
Works near-instantaneously for all the test cases, even the ones > 255.
Errors for numbers with no CUDDLE.
Explanation:
```
-> n { # define function with short lambda syntax
s = '' # the string we are storing the numbers in
[*2..99] # for all numbers from 2 to 99...
.index {|i| # find index of the number `i` for which...
(s+="#{n**i}") # after appending pow(n,i) to s...
.chars.uniq.size==10} # num of uniq chars in s is 10 (each digit)
+ 2 # add 2, because our index starts from 2
}
```
[Answer]
# CJam, 28 bytes
```
LliG,2>f#{s+_&_}%:,A#)_)s\g*
```
[Try it online](http://cjam.aditsu.net/#code=LliG%2C2%3Ef%23%7Bs%2B_%26_%7D%25%3A%2CA%23)_)s%5Cg*&input=200)
This relies on the fact that the CUDDLE (if it exists) is never larger than 15 for the input range, as first observed by @xnor.
There's probably a better way of producing the output for the case where there's no solution. I'll update if I think of anything.
Explanation:
```
L Push empty string, will be used for accumulating digits.
li Get input and convert to integer.
G, Build list of exponents [0 .. 15].
2> Slice off first two values, to produce [2 .. 15].
f# Apply power operator with all exponents to input.
{ Start loop over powers.
s Convert to string. We care about the digits here.
+ Concatenate with previously found digits.
_& Uniquify using set intersection of digit list with itself.
_ Copy for continued accumulation in next loop iteration.
}% End of loop over powers. We'll have an extra copy of the last value here,
but it does no harm so we just keep it.
:, Apply length operator to accumulated digit lists.
A# Find 10 in the list. The search result will correspond to the first power
that resulted in 10 different accumulated digits. If not found, the result
will be -1. Note that 0 corresponds to power 2, since that was the first
power we used. So we need to add 2 to get the result, and check for -1.
) Increment value. 0 now corresponds to no solution.
_ Copy this value. Will be used as multiplier to create empty string if 0.
) Increment again, to get the +2 needed for the result.
s Convert to string.
\ Swap once-incremented value to top, which is 0 for no solution, non-zero
otherwise.
g Signum to get 0/1 for no solution vs. solution.
* Multiply with result string, to get empty string for no solution.
```
[Answer]
## Mathematica, 103 bytes
```
f=(d=DigitCount;x=1;y=d[0];For[n=0,!IntegerQ@Log10[#]&&MemberQ[y,0],++n,x*=#;y+=d[x]];Print[#,"\t",n])&
```
It appears that only powers of 10 would not eventually have CUDDLEs, so they are skipped. Function keeps a list of seen digits and stops when there are no longer zeros in it.
Output:
```
1 0
2 15
3 10
4 10
5 11
6 12
7 7
8 5
9 6
10 0
11 7
12 6
13 6
```
[Answer]
# JavaScript (ES6) 188
Not bad for a language that is limited to 53 bits integers.
Test running the snippet below in a browser that implements EcmaScripts 6, including arrow functions and spread operator (AFAIK Firefox)
```
f=n=>{for(p=1,d=[],v=n=[...n+''].reverse();++p<20;){v.map((a,i)=>n.map((b,j)=>r[j+=i]=a*b+~~r[j]),r=[],c=0),r=r.map(r=>(r+=c,c=r/10|0,d[r%=10]=r));v=c?[...r,c]:r;if(d.join``[9])return p;}}
// Less golfed
U=n=>{
// Arbitrary precision multiplication
M=(A,B,R=[],c=0)=>
(
A.map((a,i)=>B.map((b,j)=>R[j+=i]=a*b+~~R[j])),
R=R.map(r=>(r+=c,c=r/10|0,r%10)),
c?[...R,c]:R
);
v=n=[...n+''].reverse();
for(p=1,d=[];++p<20;)
{
v=M(n,v)
v.map(c=>d[c]=c)
if (d.join``[9])return p
}
}
// TEST
for(i=o='';++i<300;)o+=i+' : '+f(i)+'\n'
O.innerHTML=o
```
```
<pre id=O></pre>
```
[Answer]
### PowerShell, 94 bytes
```
param($n,$s='')
2..99|%{$s+=[bigint]::Pow($n,$_);if(($s-split''|sort -U).Count-eq11){$_;break}}
(As a single line)
```
Nothing too clever about it, but piping to `sort -U[nique]` is a neat way to ape Python's `set()` functionality for this kind of use, without explicitly adding items to a hashtable.
```
param($n,$s='') # Take command line parameter.
2..99 |%{ # Loop from 2 to 99, inclusive.
$s+=[bigint]::Pow($n,$_) # $n^Loopvar, concatenate to string.
if (($s-split''|sort -U).Count-eq11) { # Convert to unique-characters-array; count.
$_;break # Print current loopvar and quit.
}
} # Otherwise, finish (silently).
```
e.g.
```
PS C:\> .\CUDDLE-of-n.ps1 10
PS C:\> .\CUDDLE-of-n.ps1 12
6
PS C:\> .\CUDDLE-of-n.ps1 255
5
```
[Answer]
# gawk 4, 73 + 5 for flags = 78 bytes
```
{for(n=$0;a-1023&&++i<15;j=0)for($0*=n;j++<NF;)a=or(a,2^$j)}$0=i<15?++i:_
```
For every digit `0` bis `9` it encounters in the powers of the input, it sets the bit representing `2^digit` in `a`, until the first 10 digits are found (`a == 1023 == 2^10-1`) or there's been more than 15 iterations.
Has to be called with an empty field seperator and the -M flag for big numbers.
```
echo 17 | awk -M '{for(n=$0;a-1023&&++i<15;j=0)for($0*=n;j++<NF;)a=or(a,2^$j)}$0=i<15?++i:_' FS=
```
Fiddling around with this I found the following sequences for the different CUDDLEs:
```
2: 32043 32286 33144 35172 35337 35757 35853 37176 37905 38772 39147 39336 40545 42744 43902 44016 45567 45624 46587 48852 49314 49353 50706 53976 54918 55446 55524 55581 55626 56532 57321 58413 58455 58554 59403 60984 61575 61866 62679 62961 63051 63129 65634 65637 66105 66276 67677 68763 68781 69513 71433 72621 75759 76047 76182 77346 78072 78453 80361 80445 81222 81945 83919 84648 85353 85743 85803 86073 87639 88623 89079 89145 89355 89523 90144 90153 90198 91248 91605 92214 94695 95154 96702 97779 98055 98802 99066
3: 69 128 203 302 327 366 398 467 542 591 593 598 633 643 669 690 747 759 903 923 943 1016 1018 1027 1028 1043 1086 1112 1182 1194 1199 1233 1278 1280 1282 1328 1336 1364 1396 1419 1459 1463 1467 1472 1475 1484 1499 1508 1509 1519 1563 1569 1599 1602 1603 1618 1631 1633 1634 1659 1669 1687 1701 1712 1721 1737 1746 1767 1774 1778 1780 1791 1804 1837 1844 1869 1889 1895 1899 1903 1919 1921 1936 1956 1958 1960 1962 1973 1984 1985 1991 1994 1996 2003 2017 2019 2030 2033 2053 2075 2123 2126 2134 2157 2158 2159 2168 2175 2183
4: 18 54 59 67 71 84 93 95 97 108 112 115 132 139 144 147 148 152 156 157 159 169 172 174 178 179 180 181 182 184 195 196 213 214 215 216 221 223 227 228 232 234 235 239 241 242 248 265 266 267 270 272 273 279 281 285 287 294 298 299 306 311 312 314 315 316 323 326 329 332 336 338 342 343 353 354 356 361 362 364 365 368 369 379 388 391 393 395 396 397 403 412 413 414 416 419 423 426 431 434 439 442 443 444 448 451 452 453 454 455 457 459 463 466 469 472 473 477 479 482 484 486 489 493 494 496 503 507 508 509 515 517 523
5: 8 16 19 27 28 38 44 47 55 57 61 77 79 80 82 83 86 87 91 92 103 106 113 116 117 118 121 123 125 126 129 131 133 136 138 140 141 142 143 145 146 151 154 158 160 161 165 167 173 175 176 177 183 185 186 187 189 190 191 192 193 197 198 204 207 218 224 226 229 230 231 236 240 243 246 249 253 255 257 258 259 261 263 268 269 271 275 276 277 278 280 282 283 284 286 288 289 292 293 304 309 322 328 331 339 341 344 345 346 347 348 349 352 357 359 367 371 372 373 374 375 377 380 381 384 387 389 402 407 408 409 411 417 418 422 427
6: 9 12 13 22 23 24 33 36 37 39 42 43 45 46 49 51 53 58 62 66 72 73 75 78 81 88 90 94 98 105 107 109 114 119 120 122 127 130 134 137 149 153 155 162 163 164 166 168 170 194 199 206 211 212 217 219 220 222 225 233 237 238 244 247 252 254 256 262 264 274 291 295 296 301 308 317 319 321 324 325 330 333 334 337 351 355 358 360 370 376 378 382 383 385 386 390 394 399 401 404 405 406 415 420 421 424 425 429 430 433 435 438 446 450 460 471 476 478 488 490 498 502 504 506 510 513 514 519 530 539 548 556 578 620 628 631 634 636
7: 7 11 14 17 29 31 32 35 41 48 52 56 63 64 70 74 85 89 96 99 102 104 110 111 135 171 188 201 202 205 208 245 251 290 297 303 305 307 310 313 318 320 335 350 363 392 410 465 475 480 483 485 501 511 518 520 521 560 582 584 595 601 630 640 682 700 736 740 786 798 850 890 952 956 965 975 982 990 999 1002 1005 1011 1020 1040 1054 1100 1110 1171 1219 1313 1331 1350 1379 1414 1447 1468 1601 1707 1710 1735 1748 2001 2010 2020 2050 2080 2450 2510 2534 2641 2745 2900 2914 2955 2970 3030 3050 3070 3100 3130 3136 3180 3193 3200
8: 21 25 26 30 34 65 76 124 209 210 250 260 300 340 505 650 1004 1240 2002 2090 2100 2500 2600 2975 3000 3400 3944 4376 5050 6500 6885 7399 10040 12400 15483 20002 20020 20900 21000 25000 26000 29750 30000 34000 43760 50500 65000 68850 73990
9: 15 68 101 150 1001 1010 1500 10001 10010 10100 15000
10: 3 4 40 400 4000 40000
11: 5 50 500 5000 50000
12: 6 60 600 6000 60000
15: 2 20 200 2000 20000
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
*Ḋ}DFQL
çⱮ⁴i⁵
```
[Try it online!](https://tio.run/##y0rNyan8/1/r4Y6uWhe3QB@uw8sfbVz3qHFL5qPGrf@NDI7utjYy0zEz0DGz1DE0stAxNDXQMTIw0DE2MjAxBooYm5iamVtYGlgfbld51LTG/T8A "Jelly – Try It Online")
Assumes that the *CUDDLE* of a number is never greater than 16. [This](https://tio.run/##y0rNyan8///hji4tBxe3QB/bR41buYwOLzdU/m9kcHS3tZGZjpmBjpmljqGRhY6hqYGOkYGBjrGRgYkxUMTYxNTM3MLS4OGO@QY6hjqGBoe2Wh9u13T/DwA) is a **14** byte version that only assumes the *CUDDLE* exists (runs forever for \$n = 0, 1, 10\$)
## How it works
```
*Ḋ}DFQL - Helper link. Takes n on the left and k on the right
} - To k:
Ḋ - Dequeue; Yield [2, 3, ..., k]
* - Raise each to the power n
D - Convert to digits
F - Flatten
Q - Deduplicate
L - Length
çⱮ⁴i⁵ - Main link. Takes n on the left
⁴ - 16
Ɱ - Over each k in [1, 2, ..., 15, 16]:
ç - Run the helper link with n on the left and k on the right
⁵ - 10
i - First index of 10 or yield 0 if not present
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
₂L.ΔL¦mS9ÝåP
```
Outputs `-1` if \$n\$ does not have a *CUDDLE*.
[Try it online](https://tio.run/##yy9OTMpM/f//UVOTj965KT6HluUGWx6ee3hpwP//hkbGJqZm5haWBgA) or [verify all test cases](https://tio.run/##yy9OTMpM/W9kcHju4TVllYdW2ispPGqbpKBk//9RU5OP3rkpPoeWHVpXnBtsCVSxNOB/rc7/aCMzHTMDHTNLHUMjCx1DUwMdIwMDHWMjAxNjoIixiamZuYWlQSwA).
**Explanation:**
```
₂L # Push a list in the range [1,26]
# (note: 26 is the smallest single-byte builtin integer above 15)
.Δ # Find the first integer k in this list which is truthy for:
# (results in -1 if none were truthy)
L # Push a list in the range [1,k]
¦ # Remove the first item to make the range [2,k]
m # Take the (implicit) input-integer to the power of each of these
S # Convert the list of integers to a flattened list of digits
9Ý # Push a list in the range [0,9]
å # Check for each digit it it's in the flattened list of digits
P # And check if this is truthy for all of them
# (after which the result is output implicitly)
```
The `S9ÝåP` could also have been `JÙgTQ` for the same byte-count:
```
J # Join the list of integers together to a single string
Ù # Uniquify its characters/digits
g # Pop and push its length
TQ # And check that this length is equal to 10
```
] |
[Question]
[
Make a snake fill any maze (until it gets stuck).
## The snake
The snake starts at a given starting point, pointing **EAST**. It moves by always having a wall or a part of its body immediately to the **LEFT** of its head ("*left-hand rule wall follower*"), until it gets stuck because all four directions around its head are occupied.
(Note: a stuck snake can possibly not fill all the reachable space, but that is not the goal!)
## The challenge
Write a program or function that accepts a maze as input in the form of a 2D text:
* The input can be in any reasonable format: e.g. a list of strings, a single string with newlines, a file.
* The maze has walls ("`#`"), empty spaces ("") and exactly one starting point ("`o`").
* You can choose to
+ either assume that the first and last row and column are entirely walls;
+ or assume that every input is considered to have an *implicit* outer layer of walls
* You can assume that the starting point has a wall (or an implicit wall) directly above it (NORTH) and that the snake can make a valid starting move in the EAST or SOUTH direction.
* You can assume that no other characters are present in the text (except newlines if your input needs them).
* You can assume that all lines are the same length.
and prints / returns a "filled maze" as output, with **a snapshot of the snake at the moment it got stuck**:
* The body of the snake is represented by the characters `>v<^` pointing to where its **next** segment is
* The starting point of the snake is either its direction at the start ("`>`" unless it had to turn immediately) or an `o` character (no need to be consistent)
* The end point of the snake is an `o` character
## Scoring
Usual code golf: the shortest code wins
## Example
```
in:
#################################
# o #
# #
# ## ### ## #
# ## ## ## ## #
# ## ## ## ## #
# ## ## ## ## #
# ## ## ## ## #
# ## ### ## #
# ## ##### ## #
# ## ##### ## #
# ## ### ## #
# ## ## #
# #
# #
#################################
out:
#################################
#>>>>>>>>>>>>>>>>>>>v>>>>>>>>>>v#
#^>>>>>>>>>>>>>>>>>v>>>>>>>>>>vv#
#^^ ##>>>>>>v###o>>>>>v## vv#
#^^ ##>^ ##>>>>^## >v## vv#
#^^ ##^ ## ## v## vv#
#^^ ##^ ## ## v## vv#
#^^ ##>^ ## ## >v## vv#
#^^ ##^< ### v<## vv#
#^^ ##^ ##### v## vv#
#^^ ##^ ##### v## vv#
#^^ ##^< ### v<## vv#
#^^ ##^<<<<<<<<<<<<<<<<## vv#
#^^<<<<<<<<<<<<<<<<<<<<<<<<<<<<v#
#^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<#
#################################
```
**Animated (for illustration purposes):**
[](https://i.stack.imgur.com/qRkTU.gif)
Edit: note that, when in doubt, the snake should "keep its left hand" on the wall it is already on, following corners, not jumping to a wall 1-block away.
[](https://i.stack.imgur.com/kj67V.png)
Thanks Jonathan Allan for bringing it up, and Draco18s for the explanatory snapshot above.
### Other examples
```
in:
####################
# o# #
# ###
# #
# ## #
# ###
####################
out:
####################
#>>>>>>>>>>>>>>vv# #
#^>>>>>>>>>>>>vvv###
#^^ v<<<o<<<<v>>v#
#^^<<<<##^<<<<<<v<<#
#^<<<<<<<<<<<<<<<###
####################
```
```
in:
####################
# o #####
# #####
# #
# ##
####################
out:
####################
# >>>>v#####
# v#####
# >>>>o#
# ##
####################
```
```
in:
################
#o #
# ########## #
# # # #
# # # #
# # # #
# # # # #
# # # #
# # # #
# # # #
# ############ #
# #
################
out:
################
#>>>>>>>>>>>>>v#
#>>v##########v#
#^#>>>>>>>>>v#v#
#^#>>>>>>>>vv#v#
#^#^>>>>>>vvv#v#
#^#^^# vvv#v#
#^#^^o<<<<<vv#v#
#^#^^<<<<<<<v#v#
#^#^<<<<<<<<<#v#
#^############v#
#^<<<<<<<<<<<<<#
################
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~94~~ 68 bytes
```
F²⊞υSW¬⁼§υ⁰§υ±¹⊞υS≔⪫υ¶θPθ…θ⌕θo≔⁰θW№KV «≧⁺⊖⌕E³§KV⁺θκ θ✳§rdluθ§>v<^θ»o
```
[Try it online!](https://tio.run/##lZBRS8MwEMef108R0pcrVJj6OBHGpjBhYyj4JEJpzzYsS7o2mYr42WuyVpfMzbl7ubvkd3f/u7RIqlQmvGleZEXgIiJzXRegYzIRpVYPqmIihygKXgvGkcBMKrhZ6YTXMFQTkeGbZftRTJx0hnmiEM4jawcaDoJhXbNcwJ1kwn7TJ0FNm5X5mWquWGlABTadb6LRe8pxVMgSVjG5ZSKznkoaOb36bX2ndSS1qZsjLh6lmKFeJkKAGUGJKSIfQW@alG3hPcsLQ3Jdx2SMaYVLFAoz2IwxFFxu9/vdz9ZZMQsjpeve6ui1yseswlQxKX5ORquMa2oh53D0en313D4Ogs9ua7vgoGnCYxaEZI/JbXiAIL@J8BsMncglQo/z3KlE672kI/zZO5lPuEo9wltlZ5nTCXeKR7hKyN6L/ePqfxLHrDlb8y8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
F²⊞υSW¬⁼§υ⁰§υ±¹⊞υS≔⪫υ¶θ
```
Slurp the input into a string. This could be avoided by using a less convenient input format.
```
Pθ…θ⌕θo
```
Print the input without moving the cursor, and then print up to the `o` again, so that the cursor ends up under it.
```
≔⁰θ
```
Initialise the current direction.
```
W№KV «
```
Repeat while there's still a free space in some direction.
```
≧⁺⊖⌕E³§KV⁺θκ θ
```
Calculate whether the snake can turn left, or whether it is forced to turn right. The code `≦⊖θW¬⁼§KVθ ≦⊕θ` also works for this for the same byte count although it considers `0` as up instead of right so the rest of the code needs to be adapted.
```
✳§rdluθ§>v<^θ
```
Output the appropriate body character in the appropriate direction.
```
»o
```
Restore the head. This can also be written as `Po` which prints the head without moving the cursor each pass through the loop instead (but this allows the loop to be implicitly closed for the same byte count).
[Answer]
# [Python 2](https://docs.python.org/2/), ~~273~~ ~~253~~ 242 bytes
-11 bytes thanks to ArBo
```
g=input()
d=0
t=lambda g,k=1:'\n'.join(map(''.join,zip(*g.split('\n')[::k])[::-k]))
h='o '
while 1:
l,r=t(g,-1),t(g)
if h in l:g=l;d-=1
elif h in g:g=g.replace(h,'>v<^'[d%4]+'o')
elif h in r:g=r;d+=1
else:break
exec-d%4*'g=t(g);'
print g
```
[Try it online!](https://tio.run/##nZHbboMwDIbv8xSW0OSkBTSmXcGyF2k7iZYsZKQhSrPjyzMQQiOoW7f5Ir9tfY7txL77ujU3XSe5MvbZU0Yqfk081@VxX5Ug44ZnOW4Npk@tMvRYWoqjH38oS1cyPVmtPB0QtsnzZjecSS@M1BxbQPJaKy0gywno2HFPZZxkLO6VEVCPUIMyoHPJdVElPCMg9JSVfVamTlhdHgStY7x/uXvATXV1u1tji2zOup51RbUebziJfO9E2RDxJg5JX7BCObRmBRLrlPEguw6jS7Y1EZyx9sv9DoEzSDSR0cwLkCgAA/k7MmoQTEjYfxEtkPm4IRIstFjpP8i8UYjMp4HzT/ebD/gZuWT4CQ "Python 2 – Try It Online")
This working by searching the string `'o '`, and replacing it by `'[>v<^]o'`, if it is in the maze.
The same check will also be made on the rotated maze, printing the filled maze when the string isn't there anymore.
The function `t=lambda g,k=1:'\n'.join(map(j,zip(*g.split('\n')[::k])[::-k]))` is used to rotate the grid
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~72~~ 56 bytes
```
œṣ€⁾o j€ṛị“v<^>”;”oʋ,
UZ$ṛ¡+ƭ€Ɱ3r5¤ç/€ḟ$Ḣß$ṛ¹?
,0ÇZU$ṛ¡/
```
[Try it online!](https://tio.run/##y0rNyan8///o5Ic7Fz9qWvOocV@@QhaQ8XDn7Ie7ux81zCmzibN71DDXGojzT3XrcIVGqQDlDi3UPrYWpH7jOuMi00NLDi/XB2naMV/l4Y5Fh@eDley059IxONweFQrRoP//4e4th9sj/2NX@19JSUmZEOBSVsAC8hFMHCoUMFUowxQqI7GQVSijqEOhSFUBoVE4UBWodqPxUFUguxRFBYpX0DxDugpkW1BUILtEAWuIERHqeFUQAsAUAgA "Jelly – Try It Online")
A full program that takes the input as a list of strings and returns a list of strings with the final snake. Note the footer on TIO converts a single newline separated string into the desired input and restores the newlines at the end; this is merely for convenience.
Solution somewhat inspired by the method used by [@Rod’s Python 2 answer](https://codegolf.stackexchange.com/a/186919/42248), though implementation is very different.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~126~~ 118 bytes
*-8 bytes saved by abusing `+=` instead of manually searching for `o` again after repositioning it.*
```
->s{d=[q=1,1+l=s=~/$/,-1,~l];i=s=~/o/;(s[i]=">v<^"[q];s[i+=d[q]]=?o)while q=[~-q%4,q,-~q%4].find{|e|s[i+d[e]]==' '};s}
```
[Try it online!](https://tio.run/##ldDdCoIwFADg@55iOKPCmQjdzWMPMhYUUxIkm8si/Hl1s0Dayn48NztnfHB@8mJ3bWNo3VCVApgEn/hOCgoaz/aI65Mm5TR51JlH54olHKzwHGwsJjntSgdEl3FYZ4vLPkkjJIE1rpyuiCRu0718GScHUVZRddeCRR2GGZrVVNXtsTgpFDM7WObRVvAW/4oJRgORPdMPAr0L3EOsZbrAhjOeEUL77Pvowuz9UplCn9QQxiovy4wXehdD6JOgwYv9cfWv4lfcAA "Ruby – Try It Online")
[Answer]
# T-SQL 2008 query, ~~373~~ ~~371~~ 366 bytes
I had a priority list, always slither left, straight, right. I changed that priority to always slither back, left, straight, right. Slithering back will always be blocked, so the priority is still the same except the first slither. By turning the snake down initially (C=4), it attempts to slithering up when backslithering. This little stunt saved me 2 bytes. Because I didn't need to add 1 to ~-~-c%4.
I inserted 2 line breaks to make it readable
```
DECLARE @ varchar(8000)=
'################
#o #
# ########## #
# # # #
# # # #
# # # #
# # # # #
# # # #
# # # #
# # # #
# ############ #
# #
################';
WITH s as(SELECT 0i,4c,@ m
UNION ALL
SELECT~-i,x,stuff(stuff(m,~-a+x/3*2+(x-3)%2*s,1,'o')
,a,1,char(59+x+~x%2*11*~x))FROM(SELECT
charindex(' ',replicate(stuff(substring(m,~-a,3),2,1,substring(m,a+~s,1))+
substring(m,a-~s,1)+'~',2),-~-~c%4)%5x,*FROM(SELECT*,charindex('o',m)a,charindex('
',M)S FROM S)Q)L
WHERE x>0)SELECT top 1m FROM s
ORDER BY i
OPTION(MAXRECURSION 0)
```
I had to make some minor adjustments to execute this online, the posted version runs in MS-SQL server management studio.
Push Ctrl-T before execute in MS-SQL server management studio, this will show result as text.
**[Try it online](https://rextester.com/edit/NSQDV54987)**
[Answer]
# [Python 3](https://docs.python.org/3/), 343 bytes
```
import sys
X=0,1,0,-1
F,*Y=*X,0
L=3
g=[*map(list,sys.stdin.read().split("\n"))]
e=enumerate
r,c=[[r,c]for r,R in e(g)for c,C in e(R)if"o"==C][0]
while 1:
if" "==g[r+X[L]][c+Y[L]]:F,L=L,~-L%4
elif" "<g[r+X[F]][c+Y[F]]:
if" "<g[r-X[L]][c-Y[L]]:g[r][c]="o";break
L,F=F,-~F%4
g[r][c]=">v<^"[F];r,c=r+X[F],c+Y[F]
for r in g:print("".join(r))
```
[Try it online!](https://tio.run/##lZCxbsIwEIZn/BRWokoxXKIgOgHugpQpExPIdSUKJrgNTuSkrVh49dQhlMaUlnKDz3f@9J//y3flJlODqpLbPNMlLnYFmtEQ@hCC30cRdOe0O4MQxXSAEsq620XupbIowZBBUa6kCrRYrDwSFHkqS895VA4hHAkq1NtW6EUpkIYlZcycfJ1prGGKpcLCS0hdLmHSlFMi107mUDrhLOToYyNTgftD1DFtbNoJ070Zizlny968zsMIYhrD3o/v7lFHpAdu3GDRETPZKHROT/5RwW8UTMcUnJq5o2fj49WwMUQ0An8f1aon4OF9/OQYuVFtppkAzQB0MFV7SIa5lsrswAleMqk8TUhVudcCufhCZN/XXwj8k3C/QLd1axOuxVnpVqLJVnEk7NlnlU20f2oRlpUzM7cT7SkW0f4Jvrixf2z9T@JafAI "Python 3 – Try It Online")
-11 bytes thanks to ArBo
-4 bytes thanks to Jonathan Frech
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~54~~ 52 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
[S¶¡øí3FDíø})J€»¼D¾èU¼.Δ.¼„o ©å}DÄiXqë®">^<v"¾è'o«.;
```
I/O both as a single multi-line string.
[Try it online](https://tio.run/##yy9OTMpM/f8/OvjQtkMLD@84vNbYzeXw2sM7ajW9HjWtObT70B6XQ/sOrwg9tEfv3BS9Q3seNczLVzi08vDSWpfDLZkRhYdXH1qnZBdnU6YEUqaef2i1nvX//0pKSsqEAJeyAhaQj2DiUKGAqUIZplAZiYWsQhlFHQpFqgoIjcKBqkC1G42HqgLZpSgqULyC5hnSVSDbgqIC2SUKWEOMiFDHq4IQAKYQAA) or [verify all test cases](https://tio.run/##yy9OTMpM/a@kTAhwKStgAfkIJg4VCpgqlGEKlZFYyCqUUdShUKSqgNAoHKgKVLvReKgqkF2KogLFK2ieIV0Fsi0oKpBdooA1xIgIdbwqCAElJaLSRL6yAlAI00Ic6QcuiOw/ZRzayXFVPlLAoxuLM1VjEyTaAVzK@VgMQ8iDBZB9S7yAMula0ASU0dxBIBUoaZYpeeYVlJZYKSjpVOoc2mav5F9aAuP/jw4@tO3QwsM7Dq81dnM5vPbwjlpNr0dNaw7tdgk9tOfQHr1zU/QO7XnUMC9f4dDKw0trXQ63ZEYc2mdzeIWh8uHVh9Yp2cXZlCkd2nd4hXr@odV61v9ra4FW6Ogd2qoZ8x8A).
**Explanation:**
```
[ # Start an infinite loop:
S # Split the multi-line string into a list of characters
# (which will use the implicit input in the first iteration)
¶¡ # Then split by newlines
øí # Rotate the matrix once clockwise
3F # Loop 3 times:
D # Create a copy of the matrix
íø # And rotate this copy once counterclockwise
}) # After the loop: wrap all four matrices into a list
J # Join each inner-most character-list to string-lines again
€» # And join each inner list of lines by newlines again
¼ # Increase variable `c` by 1 (variable `c` is 0 by default)
D¾<è # Index the updated variable `c` in a copy of the list of matrices
# (note that indexing wraps around in 05AB1E)
U # Pop and store it in variable `X`
¼ # Then increase variable `c` again
.Δ # Find the first multi-line string in the list which is truthy for:
.¼ # Decrease variable `c` by 1 first
„o # Push string "o "
© # Store this string in variable `®` (without popping)
å # Check if the current multi-line string contains this "o "
}D # Duplicate the result (results in -1 if none were truthy/found)
Äi # If no result was found:
X # Push variable `X`
q # And stop the program, after which this multi-line string of
# variable `X` is output implicitly as result
ë # Else:
">^<v"¾è # Get the `c`'th character in string ">^<v"
# (note that indexing wraps around in 05AB1E)
'o« '# Append a trailing "o" to this character
® .; # And replace the first variable `®` ("o ") in the
# multi-line string with this
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 161 bytes
```
J.zK[Z1Z_1)=Y+tKZVlJFTl@JNIq@@JNT\oA[NT;=N3=TZ#Iq@@J+G@KN+H@YNd=TN=N%tN4.?In@@J+G@KT+H@YTdIn@@J-G@KN-H@YNd XJGX@JGH\oB=NT=T%hT4)) XJGX@JGH@">v<^"TA(+G@KT+H@YT;jJ
```
[Try it online!](http://pythtemp.herokuapp.com/?code=J.zK%5BZ1Z_1%29%3DY%2BtKZVlJFTl%40JNIq%40%40JNT%5CoA%5BNT%3B%3DN3%3DTZ%23Iq%40%40J%2BG%40KN%2BH%40YNd%3DTN%3DN%25tN4.%3FIn%40%40J%2BG%40KT%2BH%40YTdIn%40%40J-G%40KN-H%40YNd+XJGX%40JGH%5CoB%3DNT%3DT%25hT4%29%29+XJGX%40JGH%40%22%3Ev%3C%5E%22TA%28%2BG%40KT%2BH%40YT%3BjJ&input=%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%0A%23++++++++++++++++++++o++++++++++%23%0A%23+++++++++++++++++++++++++++++++%23%0A%23+++++%23%23+++++++%23%23%23+++++++%23%23+++++%23%0A%23++++%23%23+++++%23%23+++++%23%23+++++%23%23++++%23%0A%23++++%23%23+++++%23%23+++++%23%23+++++%23%23++++%23%0A%23++++%23%23++++++%23%23+++%23%23++++++%23%23++++%23%0A%23+++%23%23+++++++%23%23+++%23%23+++++++%23%23+++%23%0A%23+++%23%23+++++++++%23%23%23+++++++++%23%23+++%23%0A%23++++%23%23+++++++%23%23%23%23%23+++++++%23%23++++%23%0A%23++++%23%23+++++++%23%23%23%23%23+++++++%23%23++++%23%0A%23++++%23%23++++++++%23%23%23++++++++%23%23++++%23%0A%23+++++%23%23+++++++++++++++++%23%23+++++%23%0A%23+++++++++++++++++++++++++++++++%23%0A%23+++++++++++++++++++++++++++++++%23%0A%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23&debug=0)
Port of [HyperNeutrino's Python 3 solution](https://codegolf.stackexchange.com/a/186912/71803). Now that I'm done with it, I'm thinking maybe I should have ported Rod's Python 2 solution instead, but I already spent way too much time on this.
] |
[Question]
[
Write a program that will determine if a given matrix represents a quandle. A [quandle](https://en.wikipedia.org/wiki/Racks_and_quandles) is a set equipped with a single (non-commutative, non-associative) operation \$◃\$ which obeys the following axioms:
* The operation is closed, meaning that \$a◃b = c\$ is always an element of the set if \$a\$ and \$b\$ are elements of the set.
* The operation is right-self-distributive: \$(a◃b)◃c = (a◃c)◃(b◃c)\$.
* The operation is right-divisible: For any chosen pair of \$a\$ and \$b\$, there is a single unique \$c\$ such that \$c◃a = b\$
* The operation is idempotent: \$a◃a = a\$
A finite quandle can be represented as a square matrix. Below is an example of an order-\$5\$ quandle ([source](https://arxiv.org/pdf/math/0412417.pdf)).
```
0 0 1 1 1
1 1 0 0 0
3 4 2 4 3
4 2 4 3 2
2 3 3 2 4
```
The value located at the \$n\$-th row and \$m\$-th column (0-indexed) is the value of \$n◃m\$. For example, in this quandle, \$4◃1 = 3\$. Some of the quandle properties are easy to see from this matrix:
* It is closed because only values \$0-4\$ appear in this \$5\times5\$ matrix.
* It is idempotent because the matrix diagonal is \$0, 1, 2, 3, 4\$
* It is right-divisible because no column contains any duplicate values. (The rows can, and usually will.)
The property of right-self-distributivity is harder to test. There might be a shortcut, but the simplest method is to iterate over each possible combination of three indexes to verify that `m[m[a][b]][c] = m[m[a][c]][m[b][c]]`.
## Input
Input will be the list of rows of a square matrix, using either 0-indexing or 1-index (your choice). Each entry will be a single digit number from `0` to `8` (or `1` through `9`). I will be flexible on the input format. Some acceptable formats include:
* Your language's most natural formatting for matrices or lists, such as `[[0 0 0][2 1 1][1 2 2]]` or `(0,0,0,2,1,1,1,2,2)`.
* The list of values delimited by whitespace, newlines, commas, etc.
* A single string consisting of all values concatenated together, such as `000211122`.
You are also allowed to take the transpose of the matrix as input (swapping rows with columns). Just be sure to state this in your answer.
## Output
A single truthy/falsey value indicating the matrix's status as a quandle.
## Examples of quandles
```
0
0 0
1 1
0 0 0
2 1 1
1 2 2
0 0 1 1
1 1 0 0
3 3 2 2
2 2 3 3
0 3 4 1 2
2 1 0 4 3
3 4 2 0 1
4 2 1 3 0
1 0 3 2 4
```
## Examples of non-quandles
**not closed**
```
1
0 0 0
2 1 1
1 9 2
```
**not right-self-distributive**
```
0 0 1 0
1 1 0 1
2 3 2 2
3 2 3 3
(3◃1)◃2 = 2◃2 = 2
(3◃2)◃(1◃2) = 3◃0 = 3
```
**not right-divisible**
```
0 2 3 4 1
0 1 2 3 4
3 4 2 2 2
3 3 3 3 3
4 1 1 1 4
0 1 2 3
3 1 2 0
3 1 2 3
0 1 2 3
```
**not idempotent**
```
1 1 1 1
3 3 3 3
2 2 2 2
0 0 0 0
2 1 0 4 3
3 4 2 0 1
4 2 1 3 0
1 0 3 2 4
0 3 4 1 2
```
[Answer]
## Haskell, 100 bytes
This answer uses **transposed** input.
```
q m=and$(elem<$>v<*>m)++[a#a==a&&a#b#c==a#c#(b#c)|a<-v,b<-v,c<-v]where v=[0..length m-1];i#j=m!!j!!i
```
Seems like I can't use a pattern guard to bind an infix operator, so I'm using `where` in this case.
(First version was 108 bytes but missed idempotency test, fixed version was 120 bytes, later versions had 108, 103 and 98 bytes but I had to realize thanks to @nimi that they were all wrong: of course I need to do the right-divisibility test (which implies closedness) before doing any dangerous `!!` operations, but I could still use most of my later golfing ideas and with one more, it was 102 bytes, now improved by changing the operand order of `#` (which is nicer anyway to compensate the transposition) to make better use of its associating to the left)
Use like this:
```
*Main> q [[0,1,2,3],[0,1,3,2],[1,0,2,3],[0,1,2,3]]
False
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~104~~ ~~103~~ 102 bytes
```
t=input();e=enumerate
[0%(a==A[a]in B>C[B[a]]==t[C[b]][C[a]])for(a,A)in e(t)for(b,B)in e(t)for C in t]
```
Input is transposed. Output is via exit code, so **0** (success) is truthy and **1** (failure) is falsy.
[Try it online!](https://tio.run/nexus/python2#jVFNb4MwDD2XX@HLBEg5QMNlnTKprbrrLrshDsBcDa0DlAZt@/XMEKehUzVNihI/fzw/O3X3iqAgDMPRqKbtBxPFD6iwHT5QlwaDPLmLSqW2eVk0Lewe9/mOzEIpk@/zqijoJhgfOx2VYhtTDkZmhpXYLSDsgYApRmoVBJ9vzQnhRQ@4CVZGf9O9wi@soSY9ZPe6aQ2E56Gu8XwOAwrW2Bs4PD8dtO70lF9pLN9dZOOLjmVzGjSGYx4lIi6C6YE0FmBfdqwXPkJL05UIkFcRh8i0BPIX8tSUmnEDOddmszuZHJkrSD2D9bkGlsASZzNrKm7rvr@t22n7S/cikwutgkk6i7DCpB9k7YZLeRB55bjMKZ3uC2XCcT7cgA@zT8kgJA/M3K7wP2gq9Mv3cV6@H3zt9pL5D5F@t37581p/AA "Python 2 – TIO Nexus")
### How it works
`e(t)` returns the enumerated rows of the input matrix **t** – which represents an operator **◃** – as (index,row) pairs. `for(a,A)in e(t)`, e.g., iterates over these, storing the index in **a** and the row itself in **A**, so `A` becomes a shortcut for `t[a]`.
Between the former, `for(b,B)in e(t)`, and `for C in t`, we iterate over all possible ordered tuples **(a, b, c)** in the Cartesian power **t3**.
For each of these tuples, we evaluate the expression
```
0%(a==A[a]in B>C[B[a]]==t[C[b]][C[a]])
```
The value of the parenthesized Boolean is *False* if and only if one or more of the following individual comparisons do the same.
* `a==A[a]` will fail (for some value of **a**) iff **◃** is not idempotent.
* `A[a]in B` will fail if **B** doesn't contain all indices of **A**.
Since **A** has **n** indices and **B** has **n** elements, non-failure means that the elements of **B** match the indices of **A**, so **◃** is closed and right-divisible.
* `B>C[B[a]]` is a tautology, since Python 2 considered numbers "smaller" than iterables.
* `C[B[a]]==t[C[b]][C[a]]` will fail for some value if **◃** is not right-self-distributive.
If any one of the comparisons returns *False*, the expression `(0%...)` will throw a *ZeroDivisionError*. Also, if **◃** is not closed `A[a]` or `C[b]` may also throw an *IndexError*. In both cases, the program exits with status code **1** (failure).
If all test passed, the program will exit normally with status code **0** (success).
[Answer]
# [Python 2](https://docs.python.org/2/), 138 bytes
```
def f(m):R=range(len(m));return all(m[i][i]==i<set(zip(*m)[i])==set(R)>m[m[j][k]][i]==m[m[j][i]][m[k][i]]for i in R for j in R for k in R)
```
`m` is a list of lists of integers.
[Try it online!](https://tio.run/nexus/python2#jZLPboMwDMbvfgrfSKapgtDL/jBpL1CpvTIOCMKWQlIUqFTt5Ts7RGJdL1NA@fzZJj/ktLpDr@tWWPlMYj57h2Vp3CwuEruTxwsah34zjYOZhayC59mz0Us@XCIrgH1h61Hwtx4xSZIUIMUUMsyCIKmQgwwVqsVawiwkc8xDgl5SORfkuKWkCn0p6RzYUdwIvGdUwQekoXVLZ65EzCQBdn@g7lieVpY0smSgIku@sqiFBrgw6MiylMUFzMtrC/@FXn/zHv/a0mw6Hsyh8LX71GLQjkL5EudUD4OwpanoKQrzOulZfJtRPFhJjiwKNg7yzZa2PFZlXy2FMTQUWjJZ8EwNz/QQxntcZR@kvNbTpP0cTuxubsZewq@cO814m99RwejpPmHyPgzYfOmmn3A6N43WrW43yfUH "Python 2 – TIO Nexus")
[Answer]
## JavaScript (ES6), 150 bytes
```
a=>!(a.some((b,i)=>b[i]-i)|a.some(b=>[...new Set(b)].sort()+''!=[...b.keys()])||a.some((_,i)=>a.some((_,j)=>a.some((b,k)=>b[a[j][i]]-a[b[j]][b[i]]))))
```
Takes input as an array of column arrays of integers.
[Answer]
# Mathematica, 122 bytes
```
(n_±m_:=#[[m,n]];#&@@Union[Sort/@#]==Range@l==Array[#±#&,l=Length@#]&&And@@Flatten@Array[±##2±#==(#2±#)±(#3±#)&,{l,l,l}])&
```
Pure function taking a 2D array of integers (1-indexed) as input, with rows and columns reversed from the convention in the question, and returning `True` or `False`. The first line defines the binary infix operation `n_±m_` to be the quandle operation.
For an `l` x `l` array, closed and right-divisible is equivalent to every row (in my case) being some permutation of `{1, ..., l}`, and idempotent is equivalent to the main diagonal being exactly `{1, ..., l}`. So `#&@@Union[Sort/@#]==Range@l==Array[#±#&,l=Length@#]` detects for these three conditions. (The use of `Sort/@#` here is why I chose to swap rows and columns.)
For right-distributive, we literally check all possibilities using `Array[±##2±#==(#2±#)±(#3±#)&,{l,l,l}])`. (Note that `±##2±#` automatically expands to `(#2±#3)±#`, since `##2` represents the sequence of the second and third arguments to the three-variable pure function being arrayed over.) Then `&&And@@Flatten@` checks whether every single test was passed. For some non-closed quandles, errors might be thrown when it tries to access a part of a matrix that doesn't exist, but the correct answer is still returned.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~38~~ 36 bytes
```
ŒDḢJƑ;ZQƑ€$;Jṗ3Ṗịṛ/ịⱮ¥œịʋ=Ṫṭœị⁺ʋɗ€ƲẠ
```
[Try it online!](https://tio.run/##jVC7SkNBEO3nK7awdx@3kZAuVTobQXsbyQ/YmTQpbpUETMBGFBtRwSAhm4DFDfdC8hezP7KZmd0khY0sy5yZc86e3b277fXuY6zHHVy@dJtR6@ayGYXBx1mri37q0D/iukT/dE4lfH9Vb/WE0K5so39H/yld6K925XZKrmaOq@eI6x9czqm9oh0eZpthPUY/AxL719D/rRbVYjMk7jpGDaCVBqOMAIJWcWOUVTaNUmuEdMoJQZuQY4FTBZFWfJqwA55YNgJXQwoO0GItAP4kXZySdE4yYHOSOyXZlAUsFJyTkiwv4NvwKuAgJJKrztUd55CU5uCWZ/Fpcj8y/PtRx2/YAw "Jelly – Try It Online")
Takes input as a matrix. The Footer converts the test case formats into matrix formats for you.
Truly a monstrosity of a program. This is broken into 3 stages, each of which checks a different axiom (except closedness as this is implied by right-divisibility):
```
ŒDḢJƑ - Checks for idempotentness
ZQƑ€ - Checks for right-divisibility and closedness
Jṗ3Ṗịṛ/ịⱮ¥œịʋ=Ṫṭœị⁺ʋɗ€ - Checks for right-self-distributiveness
```
We group these 3 results together using `;` and check that `Ạ`ll are true.
## How each stage works
We use `œị` to calculate \$b ◃ a\$, when the left argument is `[a, b]` and the right argument is `M`. `œị` is the "multi-dimensional index-into" command, which retrieves the `b`th element of the `a`th row of `M`. As we're checking every triple of coordinates, and the arguments are reversed for both sides of the indexing equality, the fact that we're calculating \$b ◃ a\$ instead of \$a ◃ b\$ doesn't matter. That means that instead of checking that \$(a◃b)◃c=(a◃c)◃(b◃c)\$, we instead check that \$c◃(b◃a) = (b◃c)◃(a◃c)\$ for all triples \$a, b, c\$.
Each stage is run as a "monadic link", meaning that the only argument passed to it is the inputted matrix.
```
ŒDḢJƑ - Argument: an n×n matrix M
ŒD - Yield the diagonals of M
Ḣ - Extract the first i.e. the main diagonal
JƑ - Is it in the form [1, 2, 3, ..., n]?
ZQƑ€ - Argument: an n×n matrix M
Z - Transpose M
€ - Over each row:
QƑ - Is it unchanged when deduplicated?
Jṗ3Ṗịṛ/ịⱮ¥œịʋ=Ṫṭœị⁺ʋɗ€ - Argument: an n×n matrix M
J - Extract n and yield [1, 2, 3, ..., n]
ṗ3 - Yield all triples of elements of [1, 2, 3, ..., n]
ɗ€ - Over each triple [a,b,c], do the following, with M as the right argument:
= - Are the two following results equal?
ʋ - First result:
Ṗ - Yield [a,b]
¥ - Group the previous 2 links into a dyad:
ṛ/ - Yield c
Ɱ - Over each row in M:
ị - Get the c'th element
This returns a list [1◃c, 2◃c, 3◃c, ..., n◃c]
ị - Get the a'th and b'th elements
This yields [a◃c, b◃c]
œị - Calculate (b◃c)◃(a◃c); See above
ʋ - Second result:
Ṫ - Yield c and replace the left argument with [a, b]
œị - Calculate (b◃a)
ṭ - Tack on c; [b◃a, c]
⁺ - Repeat the previous link (œị), yielding c◃(b◃a)
= - Does c◃(b◃a) equal (b◃c)◃(a◃c)?
```
* The first yields either `1` or `0`, depending on whether the matrix is idempotent or not.
* The second yields an array of \$n\$ `1`s or `0`s, for each row in `M`. `M` is only right-divisible and closed iff all of these are `1`
* The third yields a list of \$n^3\$ `1`s if `M` is right-self-distributive, or a list with at least one `0` if not.
Finally, we concatenate all of these results into a single list. If that list contains a `0`, then `M` is not a quandle, otherwise it is.
[Answer]
# C++14, 175 bytes
As unnamed lambda, assuming `n` to be like `std::vector<std::vector<int>>` and returning via reference parameter. 0 is false, everything else is true.
```
#define F(x);for(x=-1;++x<s;){
[](auto m,int&r){int s=r=m.size(),a,b,c F(a)auto A=m[a];r*=s==A.size()&&A[a]==a;int u=0 F(b)u|=1<<m[b][a];r*=A[b]<s F(c)r*=m[A[b]][c]==m[A[c]][m[b][c]];}}r*=!(u-(1<<s)+1);}}
```
Ungolfed and usage:
```
#include<vector>
#include<iostream>
auto f=
#define F(x);for(x=-1;++x<s;){
[](auto m,int&r){
int s=r=m.size(),a,b,c
F(a)
auto A=m[a]; //shortcut for this row
r*=s==A.size()&&A[a]==a; //square and idempotet
int u=0 //bitset for uniqueness in col
F(b)
u|=1<<m[b][a]; //count this item
r*=A[b]<s //closed
F(c)
r*=m[A[b]][c]==m[A[c]][m[b][c]];
}
}
r*=!(u-(1<<s)+1); //check right-divisibility
}
}
;
int main(){
int r;
std::vector<std::vector<int>>
A = {
{0, 0, 1, 1},
{1, 1, 0, 0},
{3, 3, 2, 2},
{2, 2, 3, 3},
},
B = {
{0, 2, 3, 4, 1},
{0, 1, 2, 3, 4},
{3, 4, 2, 2, 2},
{3, 3, 3, 3, 3},
{4, 1, 1, 1, 4},
};
f(A,r);
std::cout << r << "\n";
f(B,r);
std::cout << r << "\n";
}
```
] |
[Question]
[
## Mash Up Time!
This is instalment #5 of both my [Random Golf of the Day](https://codegolf.stackexchange.com/q/45302/8478) and Optimizer's [ASCII Art of the Day](https://codegolf.stackexchange.com/q/50484/8478) series. Your submission(s) in this challenge will count towards both leaderboards (which you can find the linked posts). Of course, you may treat this like any other code golf challenge, and answer it without worrying about either series at all.
## Hole 5: Diamond Tilings
A regular hexagon can always be tiled with diamonds like so:

We will use an ASCII art representation of these tilings. For a hexagon of side-length 2, there are 20 such tilings:
```
____ ____ ____ ____ ____ ____ ____ ____ ____ ____
/\_\_\ /\_\_\ /\_\_\ /\_\_\ /_/\_\ /_/\_\ /\_\_\ /_/\_\ /_/\_\ /_/\_\
/\/\_\_\ /\/_/\_\ /\/_/_/\ /\/_/\_\ /\_\/\_\ /\_\/_/\ /\/_/_/\ /\_\/\_\ /\_\/_/\ /_/\/\_\
\/\/_/_/ \/\_\/_/ \/\_\_\/ \/_/\/_/ \/\_\/_/ \/\_\_\/ \/_/\_\/ \/_/\/_/ \/_/\_\/ \_\/\/_/
\/_/_/ \/_/_/ \/_/_/ \_\/_/ \/_/_/ \/_/_/ \_\/_/ \_\/_/ \_\/_/ \_\/_/
____ ____ ____ ____ ____ ____ ____ ____ ____ ____
/_/_/\ /\_\_\ /_/\_\ /_/_/\ /_/\_\ /_/\_\ /_/_/\ /_/_/\ /_/_/\ /_/_/\
/\_\_\/\ /\/_/_/\ /_/\/_/\ /\_\_\/\ /\_\/_/\ /_/\/_/\ /_/\_\/\ /\_\_\/\ /_/\_\/\ /_/_/\/\
\/\_\_\/ \/_/_/\/ \_\/\_\/ \/_/\_\/ \/_/_/\/ \_\/_/\/ \_\/\_\/ \/_/_/\/ \_\/_/\/ \_\_\/\/
\/_/_/ \_\_\/ \_\/_/ \_\/_/ \_\_\/ \_\_\/ \_\/_/ \_\_\/ \_\_\/ \_\_\/
```
Given a side length `N`, you should generate such a tiling for a hexagon of side length `N` at random. The exact distribution doesn't matter, but each tiling must be returned with non-zero probability.
For `N ≤ 4`, your submission must produce a tiling within 1 minute at least 80% of the time and at least 80% of the tilings must potentially be generated within 1 minute. Most approaches won't have to worry about this rule (it's very lenient) - this is just to rule out very naive rejection-based algorithms that generate arbitrary strings until one happens to be a tiling.
You might like to know that the total number of possible tilings for given N can be found in [OEIS A008793](https://oeis.org/A008793).
You may write a full program or a function and take input via STDIN (or closest alternative), command-line argument or function argument and produce output via STDOUT (or closest alternative), function return value or function (out) parameter.
You must not output more leading spaces than necessary to align the hexagon (that is the left corner of the hexagon should have no spaces in front of it). Each line may contain up to `N` trailing spaces (not necessarily consistently, so you could e.g. have a rectangular output, printing the hexagon's bounding box).
This is code golf, so the shortest submission (in bytes) wins. And of course, the shortest submission per user will also enter into the overall leaderboard of the series.
## Leaderboards
**The first post of each series generates a leaderboard.**
* [Random Golf Leaderboard](https://codegolf.stackexchange.com/q/45302/8478)
* [ASCII Art Leaderboard](https://codegolf.stackexchange.com/q/50484/8478)
To make sure that your answers show up, please start every answer with a headline, using the following Markdown template:
```
# Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
# Ruby, <s>104</s> <s>101</s> 96 bytes
```
*(The language is not currently shown, but the snippet does require and parse it, and I may add a by-language leaderboard in the future.)*
[Answer]
# CJam, 105 bytes
```
ri:A" __"e*A,2f*:B,[W1]{J+B:):B,{N1$S*"\/"J%A2*4$-:D*
0{;B{_1&!2mr+J*m1e>D(2*e<}%__:)&}g:B{'_t}/+@J+}*}fJ;
```
Newline added to avoid scrolling. [Try it online](http://cjam.aditsu.net/#code=ri%3AA%22%20__%22e*A%2C2f*%3AB%2C%5BW1%5D%7BJ%2BB%3A)%3AB%2C%7BN1%24S*%22%5C%2F%22J%25A2*4%24-%3AD*0%7B%3BB%7B_1%26!2mr%2BJ*m1e%3ED(2*e%3C%7D%25__%3A)%26%7Dg%3AB%7B'_t%7D%2F%2B%40J%2B%7D*%7DfJ%3B&input=5)
**Explanation:**
This solution starts each line as a zigzag, then places N underscores on it, based on their position on the previous line and a couple of rules. I got this from a series of observations while looking at the output as a plain 2D matrix of characters:
* each line has exactly N underscores
* the underscores can be replaced with / or \ to make a perfectly repeating zigzag pattern (`/\` in the top half, `\/` in the bottom half)
* underscores can not touch the sides, and can't be adjacent to another underscore
* when going to the next line, the position of each underscore changes by -1, 0 or 1
* more than that, `/_/` can only change by -1 or 0, and `\_\` can only change by 0 or 1
* for the initial underscore positions we can either use a `"_ "` pattern or a `" _"` pattern, both are fine
* the above rules are sufficient to obtain all the tilings
So I decided to implement it by keeping the previous underscore positions, modifying them with a random factor (2 choices for each underscore) and repeating until the rules are satisfied. In the process of optimizing, I switched to underscore positions relative to the left side of the hexagon (not including spaces).
```
ri:A" __"e* read the input (A) and generate the top line
A,2f*:B make an array [0 2 4 ... 2A-2] and store in B
these are the initial positions for the underscores
, B's length = A, used as the initial number of leading spaces
let's call it C
[W1]{…}fJ for J in [-1 1] (top half, bottom half)
J+ add J to C
B:):B increment the underscore positions (adjustment before each half)
,{…}* repeat A times
N1$S* add a newline and C spaces
"\/"J% take "\/" and reverse it if J=-1 (zigzag pattern)
A2*4$-:D* calculate D=A*2-C and repeat the pattern
0 dummy value (for the next loop)
{…}g do-while
;B pop last value and push B
{…}% apply block to each item (say x)
_1&! duplicate x and calculate !(x&1) (for /_/ vs \_\)
2mr+ randomly add 0 or 1
J*m multiply by J and subtract from x
1e> limit the minimum value to 1
D(2*e< and the maximum value to 2*(D-1)
__:)& check if the modified array has any adjacent values
:B store the new positions in B
{'_t}/ place underscores over the zigzag pattern
+@J+ bring C to the top and add J to it
; pop C
```
**Old "3D" version, 189 bytes:**
```
ri:A" __"e*aA4*S*aA2**+[0-2XXW1]:C;"/\_\\\/_/":D;A3m*{{C2/.f*:.+~
A(2*+:V;A+:U;2{UI+1$1$=4{_V+D4/I=@=t}/t}fI}:F~}/[0Y1WWW]:C;
"/_/\\\_\/":D;AaA*:B;A{A[_{_BI=e<)mr}fI]:B;{BQ={[PQR]F}fR}fQ}fPN*
```
[Try it online](http://cjam.aditsu.net/#code=ri%3AA%22%20__%22e*aA4*S*aA2**%2B%5B0-2XXW1%5D%3AC%3B%22%2F%5C_%5C%5C%5C%2F_%2F%22%3AD%3BA3m*%7B%7BC2%2F.f*%3A.%2B~A(2*%2B%3AV%3BA%2B%3AU%3B2%7BUI%2B1%241%24%3D4%7B_V%2BD4%2FI%3D%40%3Dt%7D%2Ft%7DfI%7D%3AF~%7D%2F%5B0Y1WWW%5D%3AC%3B%22%2F_%2F%5C%5C%5C_%5C%2F%22%3AD%3BAaA*%3AB%3BA%7BA%5B_%7B_BI%3De%3C)mr%7DfI%5D%3AB%3B%7BBQ%3D%7B%5BPQR%5DF%7DfR%7DfQ%7DfPN*&input=5)
[Answer]
# Python 2, ~~337~~ ~~335~~ ~~324~~ ~~318~~ ~~311~~ ~~300~~ 296 bytes
```
from random import*
n=input()
R=range(n*2)
b=[]
l=[]
for i in R:o=abs(i-n)-(i<n);b+=[o];l+=[list(' '*o+'\//\\'[i<n::2]*(n*2-o))]
for i in R[:n]:
o=1;p=n+i*2
for j in R:r=randint(0,p<n*3+i*2-j);p+=(r or-1)*(o==r);q=p<=b[j];o=r|q;p+=q;l[j][p]='_';b[j]=p+1
for s in[' '*n+'__'*n]+l:print''.join(s)
```
The idea is to first create a hexagon of diamonds, like this:
```
____
/\/\/\
/\/\/\/\
\/\/\/\/
\/\/\/
```
And then fill it up with downward paths of underscores, like this:
```
____ ____
/_/\/\ /\_\/\
/_/\/\/\ or maybe this: /\/_/\/\
\_\/\/\/ \/_/\/\/
\_\/\/ \_\/\/
```
The final result with all paths added would then look something like this:
```
____ ____
/_/\_\ /\_\_\
/_/\/_/\ or maybe this: /\/_/\_\
\_\/_/\/ \/_/\/_/
\_\_\/ \_\/_/
```
Quite a bit of code goes into making sure these paths don't go out of bounds or cross eachother.
## The ungolfed code:
```
# Initialize l with all diamonds
blocked = []
l = [[] for _ in range(n*2)]
for i in range(n*2):
offset = n-i-1 if i<n else i-n
blocked.append(offset)
l[i] += ' '*offset + ('/\\' if i<n else '\/')*(2*n - offset)
# Generate the random _'s
for i in range(n):
oldright = True
pos = n + i*2
for j in range(n*2):
# Go randomly right (true) or left (false), except when you out of bounds on the right side
right = randint(0, 1) and pos < n*3 + i*2 - j
if right == oldright:
pos += 1 if right else -1
if pos <= blocked[j]:
right = True
pos += 1
l[j][pos] = '_'
blocked[j] = pos + 1
oldright = right
# Print the result
print ' '*n + '__'*n
for s in l:
print ''.join(s)
```
[Answer]
# Perl, ~~174 168 166~~ 161
```
#!perl -n
for$l(-$_..$_){$t=/_/?join'',map'/_'x($%=rand
1+(@z=/__?/g)).'/\\'.'_\\'x(@z-$%),split/\/\\/:__
x$_;$l>0&&$t!~s!^.(\\.*/).$!$1!?redo:print$"x abs$l-.5,$_=$t.$/}
```
Try [me](http://ideone.com/LQYTLP).
[Answer]
# JavaScript (*ES6*), 376 ~~416 494~~
Just to be there ...
This build all the tilings, then choose a random one. Time for the 232848 tilings for N=4 is ~45 sec on my laptop. I did not try N=5.
Being EcmaScript 6 it runs on Firefox only.
```
F=n=>{
for(i=s=r=b='';i<n;i++)
s='\n'+b+'/\\'[R='repeat'](n-i)+'_\\'[R](n)+s,
r+='\n'+b+'\\/'[R](n-i)+'_/'[R](n),
b+=' ';
for(h=[t=0],x=[s+r];s=x[t];t++)
for(d='';!d[n*3];d+='.')
if(l=s.match(r=RegExp("(\n"+d+"/)\\\\_(.*\n"+d+"\\\\)/_","g")))
for(j=2<<l.length;j-=2;h[z]||(h[z]=x.push(z)))
z=s.replace(r,(r,g,h)=>(k+=k)&j?g+'_/'+h+'_\\':r,k=1);
return b+'__'[R](n)+x[Math.random()*t|0]
}
function go()
{
var n = N.value | 0,
t0 = performance.now(),
r = F(n),
t1 = performance.now();
O.innerHTML = r+'\n\nTime (msec): '+(t1-t0)
}
```
```
N: <input id=N value=3><button onclick="go()">GO</button>
<pre id=O></pre>
```
[Answer]
# SmileBASIC, 241 bytes
```
INPUT N
T=N*2CLS?" "*N;"__"*N
DIM B[T]FOR I=-1TO N-1O=1P=N+I*2FOR J=0TO T-1IF I<0THEN O=ABS(J0N+.5)<<0B[J]=O?" "*O;MID$("\/\",J<N,2)*(T-O)ELSE R=P<N*3+I*2-J&&RND(2)P=P+(R*2-1)*(O==R)A=P<=B[J]R=R||A:P=P+A:LOCATE P,J+1?"_"B[J]=P+1O=R
NEXT
NEXT
```
Heavily based off of [Matty's answer](https://codegolf.stackexchange.com/a/51357/64538)
[Answer]
# x86 machine code, 155 bytes
Hexdump:
```
60 8b fa 51 b0 20 f3 aa 59 51 b0 5f 03 c9 f3 aa
5e b0 0a aa 57 5f 57 b7 2f 8d 14 36 8b ce 2b ca
75 03 80 f7 73 7d 02 f7 d1 51 b0 20 f3 aa 59 8a
c7 aa 8b ee 53 6b d9 fe 8d 5c b3 ff 53 6b de fc
8b 5c 1f fe 8b 47 fe 80 fc 5f 74 23 8a c4 34 73
3c 2f 75 0a 80 ff 5f 74 3e 80 ff 5c 74 37 c1 eb
08 66 81 fb 2f 5c 74 2f 0f c7 f3 d1 eb 72 24 aa
3c 5f 75 01 4d 5b 4b 75 c3 5b 85 ed 75 97 32 c7
3c 73 75 91 b0 20 f3 aa b0 0a aa 4a 75 8e 88 17
5f 61 c3 b3 5f 8a fb 8a c7 eb d4
```
Explanation:
It's a `fastcall` function. It takes the size of the hexagon, `n`, in `ecx`, and a pointer to output string in `edx`.
First of all, it prints the first line: a few spaces and a few underscores. Then, it goes into a double loop: outer loop of lines, and inner loop of chars.
Each line starts with a few spaces and a border char (either `/` or `\`, depending on whether we are in upper or lower half of the output). Last chars in each line are spaces and a newline byte. The chars in the middle are generated according to the following rules. They guarantee that the output is a valid tiling.
1. If previous char is `_`, current char must be the same as the one to the left of it:
```
(case 1) /_/
(case 2) \_\
```
2. If previous char is `\` and upper char is `_`, current char must be `_`:
```
_
\_
```
3. If previous and upper chars are `\`, current char must be equal to upper-left char:
```
(case 1) _\
\_
(case 2) /\
\/
```
4. If upper char is `/` and upper-right char is `\`, current char must be `\`:
```
/\
\
```
5. If none of the above holds, choose one of the following two possibilities for current char randomly:
* Underscore `_`
* Slash with opposite direction from the previous slash: `/\` or `\/`
To implement these rules, it loads 4 bytes from the upper line into `ebx` and 4 bytes from current line into `eax`. Then, `ah` is the previous char, while `al` is the one preceding it. Also, `bl` is the upper-left char, `bh` is the upper char, and the byte in `ebx` above `bh` is the upper-right char. After taking into account the upper-left char, it shifts `ebx` right by 8 bits so the upper-right char becomes accessible in `bh`.
To flip the direction of a slash, it does `XOR` with `0x73`.
After finishing a line, it checks two conditions:
1. Last char must be a slash in the appropriate direction (opposite to the direction of the first slash in line)
2. There must be exactly `n` underscores in the line
If either condition is violated, it starts over from first line. So for large `n`, the output will be very slow, because successful execution requires luck in each line. The following example output for `n = 8` takes about a minute to calculate:
```
________________
/_/_/_/\_\_\_\_\_\
/_/_/_/\/_/\_\_\_\_\
/_/_/\_\/\_\/_/_/_/\_\
/_/_/\/\_\/_/_/_/_/\/_/\
/_/\_\/\/_/_/_/\_\_\/_/\/\
/\_\/\_\/_/\_\_\/_/_/_/\/\/\
/\/_/\/_/\_\/_/\_\_\_\_\/\/\/\
/\/\_\/_/\/_/\_\/_/_/\_\_\/\/\/\
\/\/_/\_\/\_\/\_\_\_\/\_\_\/\/\/
\/_/\/_/\/\_\/_/_/_/\/_/\_\/\/
\_\/_/\/\/_/_/_/\_\/_/\/_/\/
\_\_\/\/_/\_\_\/\_\_\/_/\/
\_\_\/_/\/\_\_\/_/_/_/\/
\_\_\_\/\/_/_/_/_/_/\/
\_\_\_\/_/\_\_\_\_\/
\_\_\_\_\/_/_/_/_/
```
Here is assembly source code mixed with disassembly. I took it while stopped at a breakpoint in Visual Studio.
```
pushad;
10014190 60 pushad
mov edi, edx;
10014191 8B FA mov edi,edx
push ecx;
10014193 51 push ecx
mov al, ' ';
10014194 B0 20 mov al,20h
rep stosb;
10014196 F3 AA rep stos byte ptr es:[edi]
pop ecx;
10014198 59 pop ecx
push ecx;
10014199 51 push ecx
mov al, '_';
1001419A B0 5F mov al,5Fh
add ecx, ecx;
1001419C 03 C9 add ecx,ecx
rep stosb;
1001419E F3 AA rep stos byte ptr es:[edi]
pop esi; // esi = n
100141A0 5E pop esi
mov al, '\n';
100141A1 B0 0A mov al,0Ah
stosb;
100141A3 AA stos byte ptr es:[edi]
push edi;
100141A4 57 push edi
again:
pop edi;
100141A5 5F pop edi
push edi;
100141A6 57 push edi
mov bh, '/'; // bh = first char in line
100141A7 B7 2F mov bh,2Fh
lea edx, [esi + esi]; // edx = line index
100141A9 8D 14 36 lea edx,[esi+esi]
line_loop:
mov ecx, esi;
100141AC 8B CE mov ecx,esi
sub ecx, edx;
100141AE 2B CA sub ecx,edx
jnz skip1;
100141B0 75 03 jne doit+25h (100141B5h)
xor bh, '\\' ^ '/';
100141B2 80 F7 73 xor bh,73h
skip1:
jge skip2;
100141B5 7D 02 jge doit+29h (100141B9h)
not ecx; // ecx = spaces before and after chars
100141B7 F7 D1 not ecx
skip2:
push ecx;
100141B9 51 push ecx
mov al, ' ';
100141BA B0 20 mov al,20h
rep stosb;
100141BC F3 AA rep stos byte ptr es:[edi]
pop ecx;
100141BE 59 pop ecx
mov al, bh;
100141BF 8A C7 mov al,bh
stosb;
100141C1 AA stos byte ptr es:[edi]
mov ebp, esi; // ebp = underscore counter
100141C2 8B EE mov ebp,esi
push ebx;
100141C4 53 push ebx
imul ebx, ecx, -2;
100141C5 6B D9 FE imul ebx,ecx,0FFFFFFFEh
lea ebx, [ebx + 4 * esi - 1]; // ebx = char counter
100141C8 8D 5C B3 FF lea ebx,[ebx+esi*4-1]
i_loop:
push ebx;
100141CC 53 push ebx
imul ebx, esi, -4;
100141CD 6B DE FC imul ebx,esi,0FFFFFFFCh
mov ebx, [edi + ebx - 2];
100141D0 8B 5C 1F FE mov ebx,dword ptr [edi+ebx-2]
mov eax, [edi - 2];
100141D4 8B 47 FE mov eax,dword ptr [edi-2]
cmp ah, '_';
100141D7 80 FC 5F cmp ah,5Fh
je x_done;
100141DA 74 23 je doit+6Fh (100141FFh)
mov al, ah;
100141DC 8A C4 mov al,ah
xor al, '/' ^ '\\';
100141DE 34 73 xor al,73h
cmp al, '/';
100141E0 3C 2F cmp al,2Fh
jne al_diff;
100141E2 75 0A jne doit+5Eh (100141EEh)
cmp bh, '_';
100141E4 80 FF 5F cmp bh,5Fh
je mov_al_bh;
100141E7 74 3E je skip5+22h (10014227h)
cmp bh, '\\';
100141E9 80 FF 5C cmp bh,5Ch
je mov_al_bl;
100141EC 74 37 je skip5+20h (10014225h)
al_diff:
shr ebx, 8;
100141EE C1 EB 08 shr ebx,8
cmp bx, '\\' << 8 | '/';
100141F1 66 81 FB 2F 5C cmp bx,5C2Fh
je mov_al_bh;
100141F6 74 2F je skip5+22h (10014227h)
rdrand ebx;
100141F8 0F C7 F3 rdrand ebx
shr ebx, 1;
100141FB D1 EB shr ebx,1
jc mov_al_underscore;
100141FD 72 24 jb skip5+1Eh (10014223h)
x_done:
stosb;
100141FF AA stos byte ptr es:[edi]
cmp al, '_';
10014200 3C 5F cmp al,5Fh
jne skip5;
10014202 75 01 jne skip5 (10014205h)
dec ebp;
10014204 4D dec ebp
skip5:
pop ebx;
10014205 5B pop ebx
dec ebx;
10014206 4B dec ebx
jnz i_loop;
10014207 75 C3 jne doit+3Ch (100141CCh)
pop ebx;
10014209 5B pop ebx
test ebp, ebp;
1001420A 85 ED test ebp,ebp
jne again;
1001420C 75 97 jne doit+15h (100141A5h)
xor al, bh;
1001420E 32 C7 xor al,bh
cmp al, '/' ^ '\\';
10014210 3C 73 cmp al,73h
jne again;
10014212 75 91 jne doit+15h (100141A5h)
mov al, ' ';
10014214 B0 20 mov al,20h
rep stosb;
10014216 F3 AA rep stos byte ptr es:[edi]
mov al, '\n';
10014218 B0 0A mov al,0Ah
stosb;
1001421A AA stos byte ptr es:[edi]
dec edx;
1001421B 4A dec edx
jne line_loop;
1001421C 75 8E jne doit+1Ch (100141ACh)
mov [edi], dl; // terminating zero byte
1001421E 88 17 mov byte ptr [edi],dl
pop edi;
10014220 5F pop edi
popad;
10014221 61 popad
ret;
10014222 C3 ret
mov_al_underscore:
mov bl, '_';
10014223 B3 5F mov bl,5Fh
mov_al_bl:
mov bh, bl;
10014225 8A FB mov bh,bl
mov_al_bh:
mov al, bh;
10014227 8A C7 mov al,bh
jmp x_done;
10014229 EB D4 jmp doit+6Fh (100141FFh)
```
Here is C++ code which I used to develop my assembly code:
```
#include <stdio.h>
#include <iostream>
#include <random>
#include <set>
#include <string>
#define MY 1
std::random_device rd;
std::mt19937 gen(rd());
std::bernoulli_distribution distr(0.5);
#if MY
__declspec(naked) void __fastcall doit(int, char*)
{
_asm {
pushad;
mov edi, edx;
push ecx;
mov al, ' ';
rep stosb;
pop ecx;
push ecx;
mov al, '_';
add ecx, ecx;
rep stosb;
pop esi; // esi = n
mov al, '\n';
stosb;
push edi;
again:
pop edi;
push edi;
mov bh, '/'; // bh = first char in line
lea edx, [esi + esi]; // edx = line index
line_loop:
mov ecx, esi;
sub ecx, edx;
jnz skip1;
xor bh, '\\' ^ '/';
skip1:
jge skip2;
not ecx; // ecx = spaces before and after chars
skip2:
push ecx;
mov al, ' ';
rep stosb;
pop ecx;
mov al, bh;
stosb;
mov ebp, esi; // ebp = underscore counter
push ebx;
imul ebx, ecx, -2;
lea ebx, [ebx + 4 * esi - 1]; // ebx = char counter
i_loop:
push ebx;
imul ebx, esi, -4;
mov ebx, [edi + ebx - 2];
mov eax, [edi - 2];
cmp ah, '_';
je x_done;
mov al, ah;
xor al, '/' ^ '\\';
cmp al, '/';
jne al_diff;
cmp bh, '_';
je mov_al_bh;
cmp bh, '\\';
je mov_al_bl;
al_diff:
shr ebx, 8;
cmp bx, '\\' << 8 | '/';
je mov_al_bh;
rdrand ebx;
shr ebx, 1;
jc mov_al_underscore;
x_done:
stosb;
cmp al, '_';
jne skip5;
dec ebp;
skip5:
pop ebx;
dec ebx;
jnz i_loop;
pop ebx;
test ebp, ebp;
jne again;
xor al, bh;
cmp al, '/' ^ '\\';
jne again;
mov al, ' ';
rep stosb;
mov al, '\n';
stosb;
dec edx;
jne line_loop;
mov [edi], dl; // terminating zero byte
pop edi;
popad;
ret;
mov_al_underscore:
mov bl, '_';
mov_al_bl:
mov bh, bl;
mov_al_bh:
mov al, bh;
jmp x_done;
}
}
#else // not MY
void doit(int n, char* s)
{
for (int i = 0; i < n; ++i)
*s++ =' ';
for (int i = 0; i < n * 2; ++i)
*s++ ='_';
*s++ ='\n';
char* save = s;
again:
for (int line = 2 * n; line > 0; --line)
{
int spaces = n - line;
char border1 = '\\';
if (n - line < 0)
{
border1 = '/';
spaces = ~spaces;
}
for (int i = 0; i < spaces; ++i)
*s++ = ' ';
*s++ = border1;
int check = n;
for (int i = 4 * n - 1 - 2 * spaces; i; --i)
{
char al = s[-2];
char ah = s[-1];
char bl = s[-4 * n - 2];
char bh = s[-4 * n - 1];
char bk = s[-4 * n - 0];
if (ah == '_')
goto x_done;
al = ah ^ '/' ^ '\\';
if (al != '/')
goto al_diff;
if (bh == '_')
{
al = bh;
goto x_done;
}
else if (bh == '\\')
{
al = bl;
goto x_done;
}
al_diff:
bl = bh;
bh = bk;
if (bl == '/' && bh == '\\')
{
al = bh;
}
else if (distr(gen))
{
al = '_';
}
x_done:
*s++ = al;
if (al == '_')
--check;
}
if (check)
{
s = save;
goto again;
}
if (s[-1] != (border1 ^ '/' ^ '\\'))
{
s = save;
goto again;
}
for (int i = 0; i < spaces; ++i)
*s++ = ' ';
*s++ ='\n';
}
*s++ ='\0';
}
#endif // MY
int main(void)
{
char s[1000];
std::set<std::string> results;
while (true)
{
doit(3, s);
if (!results.count(s))
{
puts(s);
results.insert(s);
std::cout << results.size() << '\n';
}
}
}
```
] |
[Question]
[
There are 88 [keys](http://en.wikipedia.org/wiki/Piano_key_frequencies) on a standard piano and 95 [printable ascii](http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters) characters (hex codes 20 through 7E):
```
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
```
('character' refers to any printable-ASCII character from here on)
In [this JSFiddle](http://jsfiddle.net/CalvinsHobbies/x7yrc9aq/embedded/result/) I've taken advantage of that and made a simple syntax that generates piano tunes using [AudioSynth](https://github.com/keithwhor/audiosynth). *(If anyone can direct me to a linkable set of **real** piano note sounds I'll be grateful.)*
Each character in the input string besides `() 01+-` corresponds to one piano key:
```
CHARACTER: ! " # $ % & ' * , . / 2 3 4 5 6 7 8 9 : ; < = > ? @ 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 [ \ ] ^ _ ` 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 { | } ~
KEY NUMBER: 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
NOTE: A A# B C C# D D# E F F# G G# A A# B C C# D D# E F F# G G# A A# B C C# D D# E F F# G G# A A# B C C# D D# E F F# G G# A A# B C C# D D# E F F# G G# A A# B C C# D D# E F F# G G# A A# B C C# D D# E F F# G G# A A# B C
OCTAVE: 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 5 5 6 6 6 6 6 6 6 6 6 6 6 6 7 7 7 7 7 7 7 7 7 7 7 7 8
```
So `RPNPRRR` plays the first 7 notes of [Mary Had a Little Lamb](http://en.wikipedia.org/wiki/Mary_Had_a_Little_Lamb) using the preset timing parameters you can see in the JSFiddle.
Space () represents a musical rest that lasts for one note interval. So `RPNPRRR PPP RUU` plays the first 13 notes of Mary Had a Little Lamb with rests in their proper places.
If any character besides `()01` is prefixed by a sequence of `0`'s and `1`'s (regex `[01]+`), that sequence is read as a binary number *b*, and the character is replaced with *b* copies of itself. So `101A11 10+1-0B01C` becomes `AAAAA ++-C` because `101` = 5, `11` = 3, etc. (A sequence of `0`'s and `1`'s at the end of the string has no effect.)
Matched parentheses (`()`) serve two purposes:
1. If their content ***does not*** end with a sequence of `0`'s and `1`'s, all the notes are played at the same time as a chord (which otherwise is no different than a note). So `(NQU)` is a [C minor chord](http://www.pianochord.com/C-minor) on octave 4.
If duplicate notes are present their sound is also duplicated. So `(NN)` and `(NNN)` sound different.
2. If their content ***does*** end with a sequence of `0`'s and `1`'s, that sequence is read as a binary number *b*, and the parentheses and their content are replaced with *b* copies of the content. So `(NQU11)` becomes 9 individual notes: `NQUNQUNQU`.
Parentheses Details:
* Nesting replicating parentheses (purpose 2) is fine: `(N(QU10)11)` → `(NQUQU11)` → `NQUQUNQUQUNQUQU`.
* Nesting non-replicating parentheses (purpose 1) is fine but has no effect: `(A((+)C))` is the same as `(A+C)`.
* You can also combine both: `((N(QU10))11)` → `(NQUQU)(NQUQU)(NQUQU)`.
* A sequence of `0`'s and `1`'s before non-replicating parentheses repeats them in the same way individual characters are repeated. So `10(NQU)` becomes `(NQU)(NQU)`.
* A sequence of `0`'s and `1`'s before replicating parentheses has no effect.
* `(` must always have a matching `)`, but not vice-versa: e.g. `N)` is valid.
Plus (`+`) and minus (`-`) respectively increase and decrease the the duration of notes **or** the time interval between notes, depending on their context:
* When *inside* non-replicating parentheses, they immediately increase or decrease the note duration variable by some preset number of milliseconds (see [JSFiddle](http://jsfiddle.net/CalvinsHobbies/x7yrc9aq/embedded/result/)). So `(++)N` will play `N` at a longer duration than normal.
* When *outside* non-replicating parentheses, they increase or decrease the interval between the start of the next note and the note after it (and each subsequent interval) by some preset number of milliseconds. So in `++NP` the interval between the `N` and `P` is longer than usual.
The duration of notes and the time interval between them cannot drop below 0.
# Challenge
I intentionally chose `() 01+-` to be the 7 special characters because they can be innocuously placed in many contexts in lots of programming languages.
Your task is to write a quine in 512 bytes or less that produces the best sounding tune when the code itself is used as the input string in [the JSFiddle](http://jsfiddle.net/CalvinsHobbies/x7yrc9aq/embedded/result/).
You may choose any initial values (non-negative integers) for the 4 interval/duration parameters, but your tune must not last more than 10 minutes. You should also tell us if your tune sounds best in a particular instrument.
### Rules
* Only tabs, newlines, and printable-ASCII are allowed in your code. All non-printable ASCII is ignored by the tune creator.
* Output may go to a file or stdout or the closest alternative (e.g. JS alert). There is no input.
* No reading of source code. It must be a true quine.
* The removal of any **3 contiguous** source characters must make the program no longer function as a quine. This is to ensure people don't write a good song in a string then have a tiny quine portion to output it.
+ So if your program was `MYCODE` then `MYC`, `MYE`, `MDE`, and `ODE` should all not be quines (they may error or output something else).
This is a popularity-contest, the highest voted answer wins.
**Update:** Relaxed last rule.
[Answer]
# C
I decided I liked the low rumbling noise generated by the string `/**/` which is not-so-coincidentally the way to open and close a comment in C. The only other interesting bit here is that `34` for a `"` is replaced by `35-1`(Ending in a `1` intentionally) to avoid god-awful chords. I also tried to make the ending sound dramatic. I really did. I intend to edit this later to make it sound a bit better.
```
/**/char*p= "/**/char*p= %c%s%c; int main(){printf(p,34,p,35-1);p++;/**/}/**/";
int main(){printf(p,34,p,35-1);p++;/**/}/**/
```
To my understanding of the rules, the commented sections still pass the final rule because their removal results in a failed quine.
[Answer]
# J
Yeah, I think you can guess how this is going to go.
It's hard to get anything cool done in J without parens, and since you can rarely end them with 0s and 1s, most things sound like someone sitting on the high and low halves of the keyboard at the same time. I tried my best, I'll have you know.
Here's a funky baseline for piano, I think. I really don't know the first thing about composition, I just grabbed a quine and twiddled the numbers around a bit.
```
(23 23,~,~i.124+-100){,'(23 23,~,~i.124+-100){,'''
```
And, just for fun, play this one as EDM. I call it *Japhex Twin*.
```
".s=:'''".s=:'',''''''''&,@(,&'''''''')@(#~>:@(=&''''''''))s'
```
You can confirm the quineiness of these fine snippets of code at [tryj.tk](http://tryj.tk).
[Answer]
# Musique Concrete with Python
I don't have a lot of time today but I wanted to get an answer in. The genre is an excuse for not sounding like anything. Maybe a sound effect in a video game?
```
BFIN10=r"print('BFIN10=r\"'+BFIN10+'\"'+'\nexec(BFIN10)')"
exec(BFIN10)
```
[Answer]
# C
```
int(printf)(char*,...); (main)(){char*b=",*",i=(34),*m=("int(printf)(char*,...); (main)(){char*b="),
*z="%s%c%s%c,i=(34),*m=(%c%s%c)%sz=%c%s%c,*B=%c%s%c,*f=(%c%s%c)%s(/*)*/%s/*(*/);}//(+++fim)",*B="(f,
i,m,z),(i,z,m),(m,i),(f,b),(m,i),(m,i),(f,z,m),(m,i),(f,z,b),(m,i),(b,z),(B,i),(38,i),(29,B),(26,i),
(26,i),(B,f),(42,i),(i,m,f),B",*f=(";(printf)");(printf)(/*)*/(f,i,m,z),(i,z,m),(m,i),(f,b),(m,i),(m
,i),(f,z,m),(m,i),(f,z,b),(m,i),(b,z),(B,i),(38,i),(29,B),(26,i),(26,i),(B,f),(42,i),(i,m,f),B/*(*/)
;}//(+++fim)
```
Broken up with line breaks for presentation purposes only; this is only a quine (and only meets length requirements) if newlines are removed.
The printf declaration was needed to compile `(printf)`. `/*(*/` and `/*)*/` were used to match parentheses in the code, while a mix of parentheses and the comma operator were used to form chords from the `printf` parameters.
Edit: Shortened to fit size requirements as well as make the piece go a bit faster.
This sounds best on the piano.
[Answer]
# Scheme
This may not be particularly melodic (actually it sounds like somebody dropped a dead pig into a baby-grand), but at least it is a short piece of music. It would be difficult to make anything much longer or less dead-flying-pig-like in scheme.
```
((lambda (x) (list x (list 'quote x))) '(lambda (x) (list x (list 'quote x))))
```
[Answer]
# Für [Golfscript](http://golfscript.apphb.com/?c=IjpIO0dIR0hDRkRBO1szNF1IKzIqey19OyI6SDtHSEdIQ0ZEQTtbMzRdSCsyKnstfTs%3D)
```
":H;GHGHCFDA;[34]H+2*{-};":H;GHGHCFDA;[34]H+2*{-};
```
This satisfies the letter of the no-three-consecutive-letter-removal rule, though not the intent, I gather.
[Answer]
# Cobra / Batch
```
@number float# 2>nul||@echo off
/# 2>nul
for /f "delims=" %%a in (%0) do echo %%a
#/# 2>nul
class P# 2>nul
def main# 2>nul
r="# 2>nul"# 2>nul
s="@number float{3}||@echo off{2}/{3}{2}for /f {1}delims={1} %%a in (%0) do echo %%a{2}#/{3}{2}class P{3}{2} def main{3}{2} r={1}{3}{1}{3}{2} s={1}{0}{1}{3}{2} Console.write(s,s,34to char,10to char){3}"# 2>nul
Console.write(s,s,34to char,10to char,r)# 2>nul
```
Technically not a quine in Batch (it reads it's own source). It is however a quine in Cobra.
It sounds best with the piano mode, somewhat like ghost-level music from a Super Mario World-era video game.
[Answer]
# Pyth
```
J"+K+N+J+N+\K+N+K+NJ"K"J"+K+N+J+N+\K+N+K+NJ
```
Best played with the fourth setting (amount + and - change interval) at around 20, rest at defaults. Sounds best on the piano.
[Answer]
# Haskell
(I'm not sure whether the variable name violates the last rule.)
```
main=putStr$ jjlmjiebab ++ {--} show jjlmjiebab;jjlmjiebab = "main=putStr$ jjlmjiebab ++ {--} show jjlmjiebab;jjlmjiebab = "
```
Best played on piano with 1000 millisecond note duration and 250 millisecond note interval, with standard + and - values.
] |
[Question]
[
In this challenge, we define a *range* similarly to Python's `range` function: A list of positive integers with equal differences between them. For example, `[1, 2, 3]` is a range from 1 to 3 with a skip count of 1, because there is a difference of 1 between each item, and `[4, 7, 10, 13]` is a range from 4 to 13 with a skip count of 3.
Here, I'll represent ranges as a list of integers, but you can use any reasonable format that unambiguously represents a single range, e.g representing it as `[start, skip, end]` or something.
Your challenge is to, given a strictly increasing list of positive integers, represent it as a union of multiple ranges of integers with as few ranges as possible. For example, `[1, 2, 4, 7, 12]` can be represented as a union of `[1, 4, 7]` and `[2, 7, 12]`, and this is (an) optimal solution as it uses two ranges and there is no way to represent it as one range.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest wins!
## Testcases
Note that these only show one possible solution. In almost all cases there will be multiple optimal solutions, and you can output any one or all of them.
```
[1, 5] -> [1, 5]
[1, 2, 3] -> [1, 2, 3]
[1, 2, 4, 7, 12] -> [1, 4, 7], [2, 7, 12]
[1, 2, 3, 11, 12, 13, 21, 22, 23] -> [1, 2, 3], [11, 12, 13], [21, 22, 23]
[8, 9, 13] -> [8, 9], [13]
[23, 24, 25, 27, 30, 33, 35, 37, 40, 44, 45] -> [24, 27, 30, 33], [23, 30, 37, 44], [25, 30, 35, 40, 45]
[1,2,3,4,5,6,7,9,10,11,12,13,14,15] -> [1,2,3,4,5,6,7], [9,10,11,12,13,14,15]
[1, 2, 4, 7, 12, 17] -> [1, 4, 7], [2, 7, 12, 17]
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~13~~ 12 bytes
-1 thanks to @KevinCruijssen
```
æʒ¥Ë}æé.Δ˜êQ
```
[Try it online!](https://tio.run/##AS8A0P9vc2FiaWX//8OmypLCpcOLfcOmw6kuzpTLnMOqUf//WzEsIDIsIDQsIDcsIDEyXQ "05AB1E – Try It Online")
```
æ # all subsets
ʒ # keep those such that
¥ # their deltas
Ë # are all equal
}
æ # look at sets of such ranges
é # sorted by length
.Δ # and return the first one such that
˜ # flattened
ê # and sort uniquified
Q # and is equal to the implicit input
```
[Answer]
# [Haskell](https://www.haskell.org) + [hgl](https://www.gitlab.com/wheatwizard/haskell-golfing-library), 31 bytes
```
mBl<(sSt<iS^.sr<fo*^sSt(lq<δ))
```
This is really quite slow.
## Explanation
* `sSt(lq<δ)` get all sublists of the input that have constant deltas
* `sSt<iS^.sr<fo` get all sublists of the above that contain the input when unioned
* `mBl` get the minimum by length
## Reflection
There are a few things that could be improved here. I will note separately things that improve the golf score, and things that don't necessarily improve the golf score but help with speedy ways to complete this.
### Golf improvements
* Support for sets has been on my todo for a while, this answer really could have benefited from that. Here are some things I could have used here:
+ Some sort of union for lists
+ Some sort of subset for list (are all of this lists elements contained in this other list?)
* `lss` gets the longest sublist satisfying a predicate but there is no function to get the shortest sublist satisfying a predicate. That should exist.
* This is the second time I have used `lq<δ` in a challenge. It should have an abbreviation at this point.
### Performance improvements
* It would be nice to have a version of `sSt` restricted to non-empty lists. This wouldn't change the big O complexity or anything but it would halve the number of checks that need to be performed.
* As an extension of the above it would be nice to have a version of `sSt` which would only give the maximum elements, i.e. it would give only subsequences satisfying a predicate that are not subsequences of other subsequences also satisfying the predicate. In our case we don't need to care about the set `[2]` or `[2,3]` or `[3]` etc. if the set `[2,3,4]` is present, so eliminating those other ones would save a ton of time. It would be fastest if it never generated the bad subsequences, however either way would speed things up.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 127 bytes
```
f=(a,b=m=a,...p)=>m=p[m.length]?m:b+b?a.map(n=>f(a,a.filter(v=>v-i?b.includes(v):c.push(v)>(i+=n),n-=i=b[0],c=[]),...p,c))&&m:p
```
[Try it online!](https://tio.run/##dVJNb9swDL3nV/AwxPLCCPFHljWFnNMuO2yHHTUDUVy50eAvWK7RoehvzyjFcYdiAySA7/HxUSL4S43KFr3phnXTPuhLKegwhSdRC4Wc8y4UWS06WfNKN4/DOT/U@9PqdFC8Vh1rRFaSWvHSVIPu2SiycW0OJ26aonp60JaN4b7g3ZM9U5QxsxJNiM1aGHGSmxwLIfPQt8EiDJfLet9dBm2HQlltQcBxISOEbQ7rDK6RJ2KEZOY8uNEpwg4hiuesI3IEGd8SswGhyDF0KY4dS3H8zphK32Te6E24kJ8R7nzC1zjkC1wqdqbUPd7SpdbJhi5xCeGEcEo4pXw6/c5rZ53vlEzIqVPPbCdmO9Vf5xFjgilu8RPu8A6jDdKL6cH0rSjFaJ7eXzJn9i/l@zHS3f13lD65OPKhNzULue0qM7DgZxOEfjeeQWTwfKPX2USPjv764/s33qneanaUH17G1/wYhtc8k9JQF53T4oE0PrpfzEvBy7b/oooz6a45Z/eyACjaxraV5lX7yFhLu1MyQ5bXrQUhBOgbWC6h5XrU/W/Wu/J@AmxEMN5w9AU9rSiswMBHYL2MaBCeopc6CzNVNa6g5bat9c1u3v7GaQ8QdMraAPYQlMpUAUJLX3oN7y9/AA "JavaScript (Node.js) – Try It Online")
```
f=(
a, // `a` is the input array
b= // `b` is uncovered numbers
m=a, // `m` is best solution we have ever found
// initialize use `a` as length of `a` greater than best answer
...p // all ranges we have used, initialized as empty array
)=>m= // save best answer we found to `m`
p[m.length]?m: // if currently used ranges is more than best answer
// give up attempt and return `m` directly
b+b? // if there are numbers not covered yet
a.map(n=> // for each number `n` in input
// generate a range contains `b[0]` and `n` and step `n-b[0]`
f(a,
a.filter(v=> // for each number in input
v-i?b.includes(v): // keep it in `b` as is if it not belongs to new range
c.push(v)> // otherwise, add it to new range
(i+=n), // calculate next expected number
// the next expected number >= length of `c`
// so it is false, and filter this number out from `b`
n-=i=b[0], // `i` is next number expected in the new range
// `n` is step of the new range
c=[] // `c` is the new range
),...p,c)
)&&m: // returns the best answer got so far
p // found a better solution, assign it to m
```
[Answer]
# JavaScript (ES13), 148 bytes
Some kind of a compromise between golfiness and speed.
Output ranges are in reverse order ([+5 bytes](https://ato.pxeger.com/run?1=fVGxTsMwEBUr38BgtjM4VuykUCol_QIWGC0PTmOHSJGDaCpi1B9BLB3go-BrODdiQLQMZ93de_fu2X57931td7uPzeCS-eerK8AwX6S0KKEpTFEa_mTrzcretc3DAFCxEaGKu84Mt-YRAvJGboZlUF4v5EVQqU6CEjoZ6VIFvVCBqZFxzoPWlCmFJ4UGDKXctb6GqijPjfL2mdzbASZhQHDdvlhNt1sX_VwKOhn8Ojlb9X7dd5Z3fQMOlGBkhpKnf9uSkewokjNyzYiQx0cRFZGBgbmMXczlIck5IzeRdgCScRaXyRkGbsxSDOxlWGdY51jniOf_XGLvFvlXe89xU_rbnEBcRIHpkX5-8xs) if this is not acceptable).
```
f=(a,n=0)=>(g=a=>a.reduce((b,x)=>b.flatMap(y=>(x.at?y[n]:2*y[0]-y[1]-x)?[y]:[y,[x,...y]]),[[]]))(g(a)).find(b=>!a[new Set(b.flat()).size])||f(a,n+1)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=fVGxTsMwEBUr38BgtjM4VuykUCo5_QImRsuD09hRpchBNBUx6mewsXSAj4Kv4dyIAdEynHX33ru7Z_vtPfSN2-8_toPP5p-vXoFlQeVUVdAqqyrLn1yzXTmAmo2I1tx3dri3jxBRMnI7LKMOZiGvos5NFrUw2UiXOpqFjkyPjHMejaFMazwptGAp5X4dGqhVdWl1cM_kwQ0wDQYkN-sXZ-hu55OVa0Enb19nF6s-bPrO8a5vwYMWjMxw5PlfWDJSnGRKRm4ZEfJ0K7IiKTAwlwnFXB4bOWfkLsmOUDL14jI5w8CNRY6BWIF1gXWJdYl8-c8lDm5Rf3PwnDblv80J5EUaMD3Sz0d-Aw)
## Commented
### Helper function `g`
This function computes the powerset of its input, applying the following constraints:
* If the input contains integers, we make sure that the output sets are valid 'ranges' (as per the Python definition).
* If the input contains arrays, we make sure that the output sets contain at most `n+1` entries (where `n` is defined in the scope of the main function).
```
g = a => // a[] = input array
a.reduce((b, x) => // for each array x[] in a[],
// using b[] as the accumulator
b.flatMap(y => // for each array y[] in b[]:
( //
x.at ? // if x is an array:
y[n] // test whether y[n] is defined
: // else:
2 * y[0] - // test whether y[0] - x is equal
y[1] - // to y[1] - y[0]
x //
) ? // if the above test is truthy:
[y] // just pass y[]
: // else:
[ //
y, // pass y[]
[x, ...y] // create a new entry with x
] // inserted at the beginning of y[]
), // end of flatMap()
[[]] // start with b[] = [ [] ]
) // end of reduce()
```
### Main function `f`
This function recursively attempts to find a solution using a single range, then two ranges, and so on. The counter `n` holds the maximum number of ranges, minus 1.
```
f = ( // f is a recursive function taking:
a, // a[] = input array
n = 0 // n = counter
) => //
g( // get the powerset ...
g(a) // ... of the powerset of a[],
) // using the constraints described above
.find(b => // look for an array b[] in there:
!a[ // such that the total number of distinct
new Set( // items in b[] is equal to the length of
b.flat() // the input array
).size // (i.e. a[number_of_items] is undefined)
] //
) // end of find()
|| f(a, n + 1) // if not found, try again with n + 1
```
[Answer]
# Python3, 306 bytes
```
def f(s):
q,S=[[[s[0]]]],[]
while q:
b=q.pop(0)
if S and len(b)>=len(S):continue
U={i for j in b for i in j}
if not{*s}-U:S=b;continue
if len(B:=b[-1])<2:
for i in s:
if i>B[-1]:q+=[b[:-1]+[B+[i]]]
elif(y:=2*B[-1]-B[-2])in s:q=[b[:-1]+[B+[y]]]+q
else:q+=[b+[[min({*s}-U)]]]
return S
```
[Try it online!](https://tio.run/##fU/LbsIwELzzFXu0yVLFTlLArTnwCxEnK4emJMKIOk9UIcS3p@twKKlQI22y8/B4Ul/6Q@WiVd0Ow74ooWQdVzNoMNXGmM6EGT1oshl8H@ypgIZEyHXzUlc1CzkBW0IKH24Pp8KxnG@0/6ZcfVaut@5ckGWnrxbKqoUjWAf5uFq/Hm/3AFf113l3W@xUqvO3h5Ok@bit0rlZiIy/S3//b0A3Qm@zm613qCbQJjeK1sBsA2OpPlmKky3ZRWk5H10LesuMjwHNxH8hf9CMJ7riHhYY82UduxfkY15b9OfWQTrUrXU9K5kRCEnG@eyRkAjREy5GWCII@cxOvPAaDe3Ss7TLacwKYe0NE1J6P0XLhIbyo5CGuIhwRDgmHJMe/60pMcIYE3zFJa5RhEgNqADdL2IUyT8/QLMkefgB)
A little long, but runs in 0.026 seconds on all test cases.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~126 ...~~ 101 bytes
```
->l{t=a=[];t,*a=a|l.product(l,l).map{|a,b,c|t+[[*a.step(b,c>a ?c-a:1)]]}while t.flatten.sort|[]!=l;t}
```
[Try it online!](https://tio.run/##dVFLT8JAEL7zK8Zw4TEt7KNWhOJFr/6BzZostUSSFRpYNIby2@vsUooSPUwy32MeO7vdL77qZVZHc3twmcmUnjocmMxUNi63m9d97noWbT9@N@WhMrjAvHJDpQYm3rmi7BGeG3jII3PP@lofP99WtgAXL61xrljHu83WVUrfZHbqjvVs9vT8GNvVutgdKluVsFTFh7Fg1Ui9aD3UI2rRUQwh0RDN4ZQFgiOIlgvgTEuEFIHxVvWERlD8LJycGrrdbltOAvMiBeXcs5TzqxnU5WILPS/GjrpDmAQh1HgUCsTvgdz3p514QkELiTEFcYKwICwJS9Jl8@bgbX1hqGiQd8vAJA2TNPWnK3EUKDHBW0xxgmyMtDztTi9kEll70x823@wv5/VxKdJ/DxzEDn1t/Q0 "Ruby – Try It Online")
### Let me explain:
First, initialize 2 empty lists, one as a list of possible solutions, and one as an iterator on the list.
```
->l{t=a=[];
```
On every iteration: t is the first element of the list. We append all possible solutions including the previous value of `t` and another range to the list. This way, we check all solutions breadth-first.
```
t,*a=a|l.product(l,l).map{|a,b,c|t+
```
The ranges are calculated by getting 3 values `a, b, c` from the initial list, then going from `a` to `b` using `c-a` as increment. We need to be careful in case `c==a` (the step is 0 which is an error)
```
[[*a.step(b,c>a ?c-a:1)]]}
```
Check in the while-loop if `t` is a solution (must be the same as the input list if flattened and sorted).
```
while t.flatten.sort|[]!=l;t}
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~217~~ 216 bytes
```
def f(s):
q,*S=[[[s[0]]]],
while q:b,*q=q;R={*s}-{*sum(b,[])};*T,B=b;*_,Z=B;0<len(S)<=len(b)or(R and(q:=(len(B)<2and[T+[B+[i]]for i in s if i>Z]or[[b+[[min(R)]],T+[B+[y:=2*Z-B[-2]]]][y in s]])+q)or(S:=b))
return S
```
[Try it online!](https://tio.run/##fU9BbsIwELzzij3aySIlTlIgwT3kCYQTK6tqRCIsgUMSUIUq3p6u20upUC2NvTszXo/Pt8uhc8nyPEzTvmmhFaPMZ9BjUGkiGikyvHAGHwd7bKDPawx63Rcb/RmM9zlv15OokYy8F8EWS10XwRvudFlE62PjRCXX2p@17AaxgXe3F32uhadKuVbc0zakMiRrTNsNYME6GMG2YF93phuI6pDoZJ3YSM7x473lWgW7eUlz5dPR7fuSMTLs/TNVrmspZzA0l@vgoJrOg3UX0QqKETLD0m9CISRPuBRhgRCrZ3bmY68xuFae5Vo9jlkirLzhgVTez6NVxuD5ScRgLuE@4T7lPmU9/RtTYYIpZviCC1xhHCEn4AD8fpxinP3zAcaC5ekL "Python 3.8 (pre-release) – Try It Online")
Severely golfed answer by [Ajax1234](https://codegolf.stackexchange.com/a/265686/110585).
Monads are awesome - `{*sum(b,[])}` is significantly shorter compared to plain comprehension (`{i for j in b for i in j}`).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 62 bytes
```
⊞υ⟦θ⟧Fυ¿¬ⅉ«≔⊟ικFΦ⁻θ⌊κ›λ⁰«≔⟦⌊κ⟧ζW№θ⁺⌈ζλ⊞ζ⁺⌈ζλ≔⁺ι⟦ζ⁻κζ⟧ζ¿⌊ζ⊞υζIζ
```
[Try it online!](https://tio.run/##bY8xa8MwEIVn@1fceAIVQuzQIVMJtFOK12A0iKBUworVSFYbCPntyklUZOlwoHfv8d3TUUt/dNKmNMSgMXIYL4Jt25PzgJGBOQF@ugUPyBiDW9u8hWC@ZhzcNxrGYaJsU8Lvxi7K497MMeCFAz3MOZ5xYhT78Epm13JY/YEqaXwGBQedec2vNlYB7lycl8waLDH38lpymng2Q0pj/b@7fR4otqGP6VKKxJTvCFav5T/WErpyY3WVDQoGb6jJToYlJ2h9b@8pjeO647DuaTY0rxy6FQ3tOtId6Z50T36/ESK9/NgH "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
⊞υ⟦θ⟧Fυ
```
Start a breadth-first search with no ranges in the union and the input list as the remaining elements.
```
¿¬ⅉ«
```
Stop once a solution is found (which will necessarily have a minimum number of ranges).
```
≔⊟ικ
```
Get the remaining numbers.
```
FΦ⁻θ⌊κ›λ⁰«
```
Loop over the potential step sizes.
```
≔⟦⌊κ⟧ζW№θ⁺⌈ζλ⊞ζ⁺⌈ζλ
```
Calculate the largest set that contains the minimum remaining element with this step size.
```
≔⁺ι⟦ζ⁻κζ⟧ζ
```
Calculate the elements remaining after this set is excluded and create a new union with this set and the remaining elements.
```
¿⌊ζ⊞υζIζ
```
If there are elements remaining then add this union so far to the list of unions to be processed otherwise print this union.
] |
[Question]
[
Imagine this short function to clamp a number between 0 and 255:
```
c = n => n > 0 ? n < 255 ? n : 255 : 0
```
Is this the shortest possible version of a clamp function with JavaScript (without ES.Next features)?
P.S: Not sure if it's relevant but, the 0 and 255 are not random, the idea is to clamp a number as an 8-bit unsigned integer.
[Answer]
# 20 bytes
For reference, this is the original version without whitespace and without naming the function:
```
n=>n>0?n<255?n:255:0
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1i7PzsA@z8bI1NQ@zwpIWhn8T87PK87PSdXLyU/XSNPQNTQy1tRUAAJ9fQUDLnRJiBRWSQOYHDZJQ2RJQ3RJA5hekKQBul6gMxHSQA6GtBk@aWNkw7Ho1tIyNgL7C7c0WD9E@j8A "JavaScript (Node.js) – Try It Online")
---
# 19 bytes
We can save a byte by inverting the logic of the ternary tests and using `n>>8` to test whether \$n\$ is greater than \$255\$. Because of the bitwise operation, this will however fail for \$n\ge 2^{32}\$.
```
n=>n<0?0:n>>8?255:n
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1i7PxsDewCrPzs7C3sjU1Crvf3J@XnF@TqpeTn66RpqGrqGRsaamAhDo6ysYcKFLQqSwShrA5LBJGiJLGqJLGsD0giQN0PUCnYmQBnIwpM3wSRsjG45Ft5aWsRHYX7ilwfqB0mmJmTnF/wE "JavaScript (Node.js) – Try It Online")
---
# 19 bytes
This one returns \$false\$ instead of \$0\$ but works for \$n\ge 2^{32}\$.
```
n=>n>255?255:n>0&&n
```
[Try it online!](https://tio.run/##fc/NCoQgEMDx@z5Fp6igGhX3EGTPEn2xS4xR0eubFVKYNeBh@PFH5l8u5VSNv2GOUdaNanOFuUBBOS/0y1CA76OqJE6yb5JedkEbxISyMPT0pKkHHxsPciIYcyG5IrERTLsh2C0F45q3xXbOz1wvN/6@Mbt@7qijiNH97mfe@4PVCg "JavaScript (Node.js) – Try It Online")
---
# 18 bytes
By combining both versions above, we end up with a function that works for \$256-2^{32}\le n<2^{32}\$ and returns \$false\$ for \$n<0\$.
```
n=>n>>8?n>0&&255:n
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1i7Pzs7CPs/OQE3NyNTUKu9/cn5ecX5Oql5OfrpGmgZQTNdIS8vYSFNTQV9fIS0xM6eYC12JGbISAzRpXUMjY6AMGGCVhklilTZAyGKTNkSVNkSXNkDoB0kbGGC43RRZAZCL6Tn8CoxRrcBiAihooL7ErQBqBiyI/wMA "JavaScript (Node.js) – Try It Online")
### Commented
```
n => // n = input number
n >> 8 ? // if n is greater than 255 or n is negative:
n > 0 && // return false if n is negative
255 // or 255 otherwise
: // else:
n // return n unchanged
```
(This is a fixed revision of the code proposed by [@ValueInk](https://codegolf.stackexchange.com/users/52194/value-ink) in the comments.)
---
# 17 bytes
We can go a step further by limiting the valid input range to \$-2^{24}< n\le 2^{24}\$:
```
n=>n>>8?-n>>>24:n
```
[Try it online!](https://tio.run/##fdDRCsIgFIDh@57CS13Y9GyLCGbPImvGQnRk9Pq2pLU0240g338UzlU@pOtuw3inxp57r1pvWmGEOJzodAqoj8Z31jir@522F6wwxVAUUBNCECpLpOSg3SZOOH0nKCQsYcqhCvaPZ8wyWzTHPGaeMlvmX8zSeWia72C6/gT79aCKv8i88FnOWrDl8/7Civ0T "JavaScript (Node.js) – Try It Online")
### Commented
```
n => // n = input number
n >> 8 ? // if n is greater than 255 or n is negative:
-n >>> 24 // non-arithmetic right-shift of -n by 24 positions
: // else:
n // return n unchanged
```
] |
[Question]
[
The *Dirichlet convolution* is a special kind of *convolution* that appears as a very useful tool in number theory. It operates on the set of [*arithmetic functions*](https://en.wikipedia.org/wiki/Arithmetic_function).
### Challenge
Given two arithmetic functions \$f,g\$ (i.e. functions \$f,g: \mathbb N \to \mathbb R\$) compute the *Dirichlet convolution* \$(f \* g): \mathbb N \to \mathbb R\$ as defined below.
### Details
* We use the convention \$ 0 \notin \mathbb N = \{1,2,3,\ldots \}\$.
* The Dirichlet convolution \$f\*g\$ of two arithmetic functions \$f,g\$ is again an arithmetic function, and it is defined as $$(f \* g)(n) = \sum\_\limits{d|n} f\left(\frac{n}{d}\right)\cdot g(d) = \sum\_{i\cdot j = n} f(i)\cdot g(j).$$ (Both sums are equivalent. The expression \$d|n\$ means \$d \in \mathbb N\$ divides \$n\$, therefore the summation is over the natural *divisors* of \$n\$. Similarly we can subsitute \$ i = \frac{n}{d} \in \mathbb N, j =d \in \mathbb N \$ and we get the second equivalent formulation. If you're not used to this notation there is a step by step example at below.) Just to elaborate (this is not directly relevant for this challenge): The definition comes from computing the product of [Dirichlet series](https://en.wikipedia.org/wiki/Dirichlet_series): $$\left(\sum\_{n\in\mathbb N}\frac{f(n)}{n^s}\right)\cdot \left(\sum\_{n\in\mathbb N}\frac{g(n)}{n^s}\right) = \sum\_{n\in\mathbb N}\frac{(f \* g)(n)}{n^s}$$
* The input is given as two [black box functions](https://codegolf.meta.stackexchange.com/a/13706/24877). Alternatively, you could also use an infinite list, a generator, a stream or something similar that could produce an unlimited number of values.
* There are two output methods: Either a function \$f\*g\$ is returned, or alternatively you can take take an additional input \$n \in \mathbb N\$ and return \$(f\*g)(n)\$ directly.
* For simplicity you can assume that every element of \$ \mathbb N\$ can be represented with e.g. a positive 32-bit int.
* For simplicity you can also assume that every entry \$ \mathbb R \$ can be represented by e.g. a single real floating point number.
### Examples
Let us first define a few functions. Note that the list of numbers below each definition represents the first few values of that function.
* the multiplicative identity ([A000007](https://oeis.org/A000007))
$$\epsilon(n) = \begin{cases}1 & n=1 \\ 0 & n>1 \end{cases}$$
`1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...`
* the constant unit function ([A000012](https://oeis.org/A000012))$$ \mathbb 1(n) = 1 \: \forall n $$
`1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ...`
* the identity function ([A000027](https://oeis.org/A000027))
$$ id(n) = n \: \forall n $$
`1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, ...`
* the Möbius function ([A008683](https://oeis.org/A008683))
$$ \mu(n) = \begin{cases} (-1)^k & \text{ if } n \text{ is squarefree and } k \text{ is the number of Primefactors of } n \\ 0 & \text{ otherwise } \end{cases} $$
`1, -1, -1, 0, -1, 1, -1, 0, 0, 1, -1, 0, -1, 1, 1, 0, -1, 0, -1, ...`
* the Euler totient function ([A000010](https://oeis.org/A000010))
$$ \varphi(n) = n\prod\_{p|n} \left( 1 - \frac{1}{p}\right) $$
`1, 1, 2, 2, 4, 2, 6, 4, 6, 4, 10, 4, 12, 6, 8, 8, 16, 6, 18, 8, ...`
* the Liouville function ([A008836](http://oeis.org/A008836))
$$ \lambda (n) = (-1)^k $$ where \$k\$ is the number of prime factors of \$n\$ counted with multiplicity
`1, -1, -1, 1, -1, 1, -1, -1, 1, 1, -1, -1, -1, 1, 1, 1, -1, -1, -1, ...`
* the divisor sum function ([A000203](http://oeis.org/A000203))
$$\sigma(n) = \sum\_{d | n} d $$
`1, 3, 4, 7, 6, 12, 8, 15, 13, 18, 12, 28, 14, 24, 24, 31, 18, 39, 20, ...`
* the divisor counting function ([A000005](http://oeis.org/A000005))
$$\tau(n) = \sum\_{d | n} 1 $$
`1, 2, 2, 3, 2, 4, 2, 4, 3, 4, 2, 6, 2, 4, 4, 5, 2, 6, 2, 6, 4, 4, 2, 8, ...`
* the characteristic function of square numbers ([A010052](http://oeis.org/A010052))
$$sq(n) = \begin{cases} 1 & \text{ if } n \text{ is a square number} \\ 0 & \text{otherwise}\end{cases}$$
`1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, ...`
Then we have following examples:
* \$ \epsilon = \mathbb 1 \* \mu \$
* \$ f = \epsilon \* f \: \forall f \$
* \$ \epsilon = \lambda \* \vert \mu \vert \$
* \$ \sigma = \varphi \* \tau \$
* \$ id = \sigma \* \mu\$ and \$ \sigma = id \* \mathbb 1\$
* \$ sq = \lambda \* \mathbb 1 \$ and \$ \lambda = \mu \* sq\$
* \$ \tau = \mathbb 1 \* \mathbb 1\$ and \$ \mathbb 1 = \tau \* \mu \$
* \$ id = \varphi \* \mathbb 1 \$ and \$ \varphi = id \* \mu \$
The last for are a consequence of the [Möbius inversion](https://en.wikipedia.org/wiki/M%C3%B6bius_inversion_formula): For any \$f,g\$ the equation \$ g = f \* 1\$ is equivalent to \$f = g \* \mu \$.
### Step by Step Example
This is an example that is computed step by step for those not familiar with the notation used in the definition. Consider the functions \$f = \mu\$ and \$g = \sigma\$. We will now evaluate their convolution \$\mu \* \sigma\$ at \$ n=12\$. Their first few terms are listed in the table below.
$$\begin{array}{c|ccccccccccccc}
f & f(1) & f(2) & f(3) & f(4) & f(5) & f(6) & f(7) & f(8) & f(9) & f(10) & f(11) & f(12)
\\ \hline
\mu & 1 & -1 & -1 & 0 & -1 & 1 & -1 & 0 & 0 & 1 & -1 & 0
\\
\sigma & 1 & 3 & 4 & 7 & 6 & 12 & 8 & 15 & 13 & 18 & 12 & 28
\\
\end{array}$$
The sum iterates over all natural numbers \$ d \in \mathbb N\$ that divide \$n=12\$, thus \$d\$ assumes all the natural divisors of \$n=12 = 2^2\cdot 3\$. These are \$d =1,2,3,4,6,12\$. In each summand, we evaluate \$g= \sigma\$ at \$d\$ and multiply it with \$f = \mu\$ evaluated at \$\frac{n}{d}\$. Now we can conclude
$$\begin{array}{rlccccc}
(\mu \* \sigma)(12) &= \mu(12)\sigma(1) &+\mu(6)\sigma(2) &+\mu(4)\sigma(3) &+\mu(3)\sigma(4) &+\mu(2)\sigma(6) &+\mu(1)\sigma(12)
\\
&= 0\cdot 1 &+ 1\cdot 3 &+ 0 \cdot 4 &+ (-1)\cdot 7 &+ (-1) \cdot 12 &+ 1 \cdot 28
\\
&= 0 & + 3 & 1 0 & -7 & - 12 & + 28
\\
&= 12 \\
& = id(12)
\end{array}$$
[Answer]
# [Lean](https://leanprover.github.io/), ~~108~~ ~~100~~ ~~95~~ ~~78~~ 75 bytes
```
def d(f g:_->int)(n):=(list.iota n).foldr(λd s,ite(n%d=0)(s+f d*g(n/d))s)0
```
[Try it online!](https://tio.run/##TYxNCsIwFIT3PcWACO/5U9uFm0C8igTzUgPhFUzozVx5h16ppropDHzMBzNJnC6LlwBPAYO5n29RC5OysZRiLm0ci4NyG8bkXzR/PPIpFiHde9sx5WOdHgbSi2fO3P2@5jdIYaCucEV9hLGIAQqLHuUpWiEpC7qm2cnkEvy6qumvW/EYZWvW@lfLFw "Lean – Try It Online")
[More testcases with all of the functions.](https://tio.run/##pVSxjhoxEO35ipGSKPaez2EpkciPRDlk1t7FkvHC2heljARC1GlSXpso9VVcdenhH/ZHyHgNKw5xoCiVNX4zb2bf@K1Rwu70ZFpWHoQp1KgSfKqH2jovbKYcSOEFt8LzaaUnaidVDpLkUPSHtx@19ZRY2h8Qo53nuvQCLOV5aWRFNmsJjmmviH0nB11K3A2WJgWxHySljnZ3psyEAW1z/RUS6A9AdjqBf/MIxEIfsCvFA7sEUOdgYQAp@LGyeCjjFHRjwdMrBc1YtpT3U7A8F5kvKxfryW1K79o7bpQt/PiYc7s8x5mjMMrzTFQSyD7ItfGqwmwUKSsbmVCFFq6ELcIFbWiff2/Wz@tz1GcniqPMz@ZH0Rv6t/YmpftBUHiQDKLolLv7SSRZ/AfJ0TBu9tpyuJtV/q6HO7InO@q8UV9w00e93iOY9iifiCmu@zJO0tgO6uX30I9eSc9K9U8Fm6fL@HZ5GY8rvcIxv4IvLuNuFq0hRm54/rUjAgQhS2PmRPhsnPYgePVEDgxHZWmwqlOvvoGEerWC074M0K24y@LgSq@cz4TDX0K/Sca384L0zw94cUED/yeyeWTIl6DKlHWAbOcs@DtBRZo4wHtPJPuva/PQgpi3aGJcKgtGiEQRD4tOIG1wNzviSUNGjFj4OSSoX2RdxGGahJQFU7STxQ7LA7pdHhog/vnwhBuVhDFHagSr1A8/cwZF/fCLtcKj7nT3Fw)
[Answer]
# [Haskell](https://www.haskell.org/), 46 bytes
```
(f!g)n=sum[f i*g(div n i)|i<-[1..n],mod n i<1]
```
[Try it online!](https://tio.run/##FcixDkAwFAXQ3VdciaEVJE2MfIl0KNV6oY8oJv9eccazmLjO25aScLmX3Mc7DA5UemHpAYPkS109qKZhXYXd/tUpnYIhRg@7Z8BxEl8oIMwY83hPk4Rq2/QB "Haskell – Try It Online")
Thanks to flawr for -6 bytes and a great challenge! And thanks to H.PWiz for another -6!
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 17 bytes
Of course Mathematica has a built-in. It also happens to know many of the example functions. I've included some working examples.
```
DirichletConvolve
```
[Try it online!](https://tio.run/##lYu7CsIwGEb3PkVA6BTQCI6BinVroegYMqT1r/0hF8htEZ89tugLyLccDuczKi5gVMRJlZmXFj1Oi4Z4cTY7naEMHm1sZnFNGvywoLCSkhYzBufvyQhLCSP16lYwsvonZ8dfL2bRoUsZtYZOmfGhttt5DE3vYMQU@rQJS3ey3jc3ZZ8gTpLzF6OH796yKh8 "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 59 bytes
```
lambda f,g,n:sum(f(d)*g(n//d)for d in range(1,n+1)if 1>n%d)
```
[Try it online!](https://tio.run/##TcyxCoMwEAbgV7lFuNNAOEoXoT5Jl8iZNFB/JU0Hnz4uDm7f9O1H/Wx4NHu92zesswWKLjmMv//KkU36xPDeJG6FjDKoBKSF1WFQyZF0QmfS9pJR2fg6MKqju/Up0k4 "Python 3 – Try It Online")
[Answer]
# [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 51 bytes
```
D,g,@~,$z€¦~¦*
D,f,@@@,@b[VdF#B]dbRzGb]$dbL$@*z€g¦+
```
[Try it online!](https://tio.run/##S0xJKSj476KTkZpTkFqk4@Cgo/KoaY1@CpDIrAISh5bZJoUqc7noFGRk6jjopLgpO8U6BTgGgVRVQzTVpiT5qBxaph3PBVRWklgKVObmY6gN4mWmADkgRn5eKpBlCLQoXcehTkcFYnTdoWVaQMk0oLUOOg5J0WFg41OSgqrck2JVQMY6aIFUpgNN/6@SZpeZYgc0yM7QiMufC8gFOskOaB@Y/x8A "Add++ – Try It Online")
Takes two pre-defined functions as arguments, plus \$n\$, and outputs \$(f \* g)(n)\$
## How it works
```
D,g, ; Define a helper function, $g
@~, ; $g takes a single argument, an array, and splats that array to the stack
; $g takes the argument e.g. [[τ(x) φ(x)] [3 4]]
; STACK : [[τ(x) φ(x)] [3 4]]
$z ; Swap and zip: [[3 τ(x)] [4 φ(x)]]
€¦~ ; Reduce each by execution: [[τ(3) φ(4)]]
¦* ; Take the product and return: τ(3)⋅φ(4) = 4
D,f, ; Define the main function, $f
@@@, ; $f takes three arguments: φ(x), τ(x) and n (Let n = 12)
; STACK: [φ(x) τ(x) 12]
@ ; Reverse the stack: [12 τ(x) φ(x)]
b[V ; Pair and save: [12] Saved: [τ(x) φ(x)]
dF#B] ; List of factors: [[1 2 3 4 6 12]]
dbR ; Copy and reverse: [[1 2 3 4 6 12] [12 6 4 3 2 1]]
z ; Zip together: [[[1 12] [2 6] [3 4] [4 3] [6 2] [12 1]]]
Gb] ; Push Saved: [[[1 12] [2 6] [3 4] [4 3] [6 2] [12 1]] [[τ(x) φ(x)]]]
$dbL ; Number of dividors: [[[τ(x) φ(x)]] [[1 12] [2 6] [3 4] [4 3] [6 2] [12 1]] 6]
$@* ; Repeat: [[[1 12] [2 6] [3 4] [4 3] [6 2] [12 1]] [[τ(x) φ(x)] [τ(x) φ(x)] [τ(x) φ(x)] [τ(x) φ(x)] [τ(x) φ(x)] [τ(x) φ(x)]]]
z ; Zip: [[[τ(x) φ(x)] [1 12]] [[τ(x) φ(x)] [2 6]] [[τ(x) φ(x)] [3 4]] [[τ(x) φ(x)] [4 3]] [[τ(x) φ(x)] [6 2]] [[τ(x) φ(x)] [12 1]]]
€g ; Run $g over each subarray: [[4 4 4 6 4 6]]
¦+ ; Take the sum and return: 28
```
[Answer]
# [R](https://www.r-project.org/), 58 bytes
```
function(n,f,g){for(i in (1:n)[!n%%1:n])F=F+f(i)*g(n/i)
F}
```
[Try it online!](https://tio.run/##XZDBioMwEIbPO0@RPQiZVmmzR9FTwfPCHksLsSY6YCZFk70s@@xWe2jR0wwfP98M/zA1NNCt6004ef4VRTbZyLdAniWnNm3xz/pBkiAWUuWM509Oknm5YFVWeysJd63kAyFU/5MJ@qPIxNuAZCWXpUIlTD8acYTIFDYZBdRsEIOLC@LoajOMee68qSmOcO9oxU3s5/ndEfTa1c32vMwUXl9h70yrZwojtU6LlehnQRB03H6yCsydHBFg1ZlUX6mL6dOJ0wM "R – Try It Online")
Takes `n`, `f`, and `g`. Luckily the `numbers` package has quite a few of the functions implemented already.
If vectorized versions were available, which is possible by wrapping each with `Vectorize`, then the following 45 byte version is possible:
# [R](https://www.r-project.org/), 45 bytes
```
function(n,f,g,x=1:n,i=x[!n%%x])f(i)%*%g(n/i)
```
[Try it online!](https://tio.run/##dVBNi4MwED03vyJ7EDIl0qZHqaf@gYWFvZQtRB11wEwWTRbpn3dtDy0echqY9zFv3rg0NFLdDxgunv/kOV/ayHUgz4p1qzs9l6ZgTeV8/eAsm3@gVQTZPusUHwgWDHZ3zuU31sGPdEf1lgO1isvSgJE4TCiPICJTSNINCGqSKINwcYtydBWOU1E4jxXFCcRvTwkKxmGdnz2BGKyrmnRqlRu4vXTeYWfXLYiJOmdlwv7rAYIINqYf2HDXdo@rqdjUr8xJu6ifl2D5Bw "R – Try It Online")
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 20 bytes
```
{(⍺⍺¨∘⌽+.×⍵⍵¨)∪⍵∨⍳⍵}
```
with `⎕IO←1`
[Try it online!](https://tio.run/##bVE9b9swEN35K7jJiuBWlOQ0CaDJ/yMAG9kuEckfoAWoaDO1KIy2DroU6dKlS4wuGYIsAboo/4R/xH1HSgkDBCRP7x6P9053clkOi/eyXMyGZ6XUWp3tzeVPtTBffoj9GPbDwGzvsdud2fwy3/9Frx6uzPYOu92FZvOX8GZntrcAF/v9ZKnpkcjJZfVcra17wVQBYL7@YVVtwSekE7y9cSe2tscxf872yFq2fKe8DIInWBnOISwdEZMh/whLHAKII1bK6m0hX5D2bS/X495/xjCtZpWfKYXeG1JJSG/ERQpB8hJYVGZ3KohMj3kSs7X0e0D1p90/ZDYZ1U444yOHmV55D1yD4m49Ic9jbD3RtvVmc/0aI7zEPMKW5iSOT4LFeWC@fQ6mUpUngZ2UjQ8wvZxmxse8qgPHTXOwfDyYIlsWtTcj1PBwFR3gk0YJ7EEYcLP9zWut5jM@HTRhng1HTdSc4v604VJzOeeTRlbLcvKk4waCxB@rOuy0bGdzDBgFoEkdq4rcXvhVuUhVgKOCe3b1mNanHZdXNWi96kjk7//VCyWY48rXgr4ryYsD4dQpavgf "APL (Dyalog Classic) – Try It Online")
Easy to solve, hard to test - generally not my type of challenge. Yet, I enjoyed this one very much!
`{` `}` defines a dyadic operator whose operands `⍺⍺` and `⍵⍵` are the two functions being convolved; `⍵` is the numeric argument
`∪⍵∨⍳⍵` are the divisors of `⍵` in ascending order, i.e. unique (`∪`) of the LCMs (`∨`) of `⍵` with all natural numbers up to it (`⍳`)
`⍵⍵¨` apply the right operand to each
`⍺⍺¨∘⌽` apply the left operand to each in reverse
`+.×` inner product - multiply corresponding elements and sum
---
[The same in ngn/apl](https://tio.run/##bVLBTsJAEL3vV@yNlop224Jg0l8hQaFKJCBtDxjlBCFErdGD0UNNiBeJMSGN4SJ4wXv7D/sjdabdBpqY3Z28eZ19M92ZxkWn1D3txjH3Az55uJK49w17M@fTF373o@z/PnNvCXszl/n0A/F0zhTufQEcEhIt4RaDYJPwxxkqsCFpNwHwmzcSrhMwgu8qZXSzSI@a2AyrNM9mKLEkmuQkGNVgGXAqYPEwFQ36VVisAoBVSbj6N/OuzbJlOPNzDIlGOSEdkh1iCg2TlSnTIRt6GlgoK9k6Q1KvUU0l0Th3H6vXxR8YiRpWjtig5RQTp5@7kr6QKtYW7XjEwpc3FGmzKCcNkxVo5LKoy4pWxEZR7r3Shn3cdu2GfUmtLrV6NnXPWtRpnfS6Teq2HHePWtJANo1SeaAM6rqi1QeEuKjMp@8HNhYlhiMZAFY74vdPwBZ65wV@OxaO1Wh3CjaMhhQtTZwJPwjXssu9TyJZJsyLH1jChQDokx9I1xCRcSMTWu4H0VgQ7aYJPdgRgQgYMBjXx5lgnH6qs2XClQmz5wdOP7s0FrVsYwCZ0J0dZUw1ycVEkzSXCInjPw) looks better because of Unicode identifiers, but takes 2 additional bytes because of 1-indexing.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
ÆDṚÇ€ḋÑ€Ʋ
```
[Try it online!](https://tio.run/##y0rNyan8f7gtzUdX61iXQeCxifZAnsvDnbMOtz9qWvNwR/fhiUD62CagaDGX0ZH9//8bGgEA "Jelly – Try It Online")
Line at the top is the main line of \$f\$, line at the bottom is the main line of \$g\$. \$n\$ is passed as an argument to this function.
[Answer]
# [Swift 4](https://developer.apple.com/swift/), ~~74 70~~ 54 bytes
```
{n in(1...n).map{n%$0<1 ?f(n/$0)*g($0):0}.reduce(0,+)}
```
[Try it online!](https://tio.run/##fYw9DsIwFINncoo3FOkFSkgkFsrfzClQ1TRVhj5VIYWhykEYEFfkBiGBncWWrc@@3q3xm2hGasBqvABVcCbPYXXMDhObudaPjoBYYOzLvZ@vxz9SZfJWOzBwSKcldMnzaPerdYpxIrCESghBXPT1MNG8kHsFJ4O0LiRfdJi0kkG4Vo9Ni7Jc8hAHZ8mjRrXlPH4A "Swift 4 – Try It Online")
[Answer]
# JavaScript (ES6), 47 bytes
Takes input as `(f)(g)(n)`.
```
f=>g=>h=(n,d=n)=>d&&!(n%d)*f(n/d)*g(d)+h(n,d-1)
```
[Try it online!](https://tio.run/##dZDNjoJAEITvPEV7kHSD/Jl4MRnMJsYbT7DZbFgHkQUHBTQx8d3ZZgDl4M5lSHXVV0P/xre43lfZuXFUKZN2J9qDCFMRHgWqhRSKRChNc4ZqLsk6oPL4SlGSfezmTkBtkZXXW1YUCQhQIEJAVsGyALessAtyvpfUjXII2bMBH9Y8gTkLG9j2Hhs4toaAP1gBD3JWiQgVGafyJ7vWwGfsiCbsQLM7nG13wL7l8YBIOzqq5uk@0wQnmvA7fH2B4Qx4e4Zs4X/w3RVxLCAjk4lqsub@9ASG4XnAUQGvFVgw@ox9qeqySNyiTPHTdd2PqorvuFzRl3uKz4jfC1D64Tt85gnHOL9Lb4RI10yXPCzD4u7/Svw3JX2MsL682O0f "JavaScript (Node.js) – Try It Online")
### Examples
```
liouville =
n => (-1) ** (D = (n, k = 2) => k > n ? 0 : (n % k ? D(n, k + 1) : 1 + D(n / k, k)))(n)
mobius =
n => (M = (n, k = 1) => n % ++k ? k > n || M(n, k) : n / k % k && -M(n / k, k))(n)
sq =
n => +!((n ** 0.5) % 1)
identity =
n => 1
// sq = liouville * identity
console.log([...Array(25)].map((_, n) => F(liouville)(identity)(n + 1)))
// liouville = mobius * sq
console.log([...Array(20)].map((_, n) => F(mobius)(sq)(n + 1)))
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 108 bytes
```
#define F float
F c(F(*f)(int),F(*g)(int),int n){F s=0;for(int d=0;d++<n;)if(n%d<1)s+=f(n/d)*g(d);return s;}
```
Straightforward implementation, shamelessly stolen from [Leaky Nun's Python answer](https://codegolf.stackexchange.com/a/176109/56453).
Ungolfed:
```
float c(float (*f)(int), float (*g)(int), int n) {
float s = 0;
for(int d = 1; d <= n;++d) {
if(n % d == 0) {
s += f(n / d) * g(d);
}
}
return s;
}
```
[Try it online!](https://tio.run/##jZT/TtswEMf/bp7iBkJLaEqbFtim0EmoardKTJooTJMYqkLiFEv5URoHsaH@NYT2BnuS/TWeAd5hL9Ld2Umb0AqQkth39n389dkXtzZy3dk6j9wg9RjsJcLj8db5e63kCvgZ@mbrHvN5xKAHfhA7QuuBq/f0Td/QeSQME7ujrIsfiIzrHiTthu3HE/KCh32vWt2LbIP7erTh7VlGUm1jt@4ZmyPdM@wJE@kkgsSeznrAxgkP4khXMLjWKtlwBO02WLY2RQVxxJYnZGPcWxFLQ/U6dM6ZI4CH44CFLBKO4HGUAEqFWJyzCfhp5CrfGXOdNGHQfx2CiGMInB/fsQM@H6UTBnEqKCxMAyfR8gx1Pnb3j4b9T58PdAKZsLW1ZVDe0JhrSmhVF72XTpCy5OQU2nA9HH7ZH@4ffhgMh1MbMtHZhAhqYJ3aU00r8MPUBMuEWvY2VLOwGkUjG1oYeWMUkeNznk9rymdbfndlR32thmqU@618rF1pWGSVeIETnnlOSWa5WciqLXkeOWtWCZ3wUajILSnojZLQVIJ28G0pReRqUkt7yd6WpcZa79CmDTVLbOGkhRy0CpnYzpdT21cefHYKnt2yzos8641CZ6W5wmlo85t11B0cZXfKN2Fk0k3CahIsEY/dWCTdr/2j4eC40@kOBoYNLMB7zK640OVAb79/cHzYNTS6kZLQA31zktUwkOEXjby6YVFVWKVXY@YK5uGqsbC1Sl7tHKhGsdlrY9FBtcplQCWfj8M40cCICgai5epKufLhnuYzX7WJrcIr4wnSfX3tZMM7nS8OGz6cYSESacP/Fq0hxixLk9RKvZ6VVDEBNDLV6CkOZmmj/4VMUOjwSL@MuSeFjFOR6GuUNHj4Q1uFf79@w/3dGq0jDyn7fZn0izKByrTZoEEVSfPKlJ9IebiVmIebBSa74bIm5Y18ksIpr4h6LIZjEjLSy5QgiBjWkhAiyR09yUgukHH/d4mBZZD/DZ6HYDxC7iQkuVhQcgLthIhP7@ZmfjoFITKTUsHzMixK6c1SSmWg5IQvO5XbxyIolfJcn9eAwfMzKYqQ4cRZrWH1fZ79Bw "C (gcc) – Try It Online")
[Answer]
## F#, 72 bytes
```
let x f g n=Seq.filter(fun d->n%d=0){1..n}|>Seq.sumBy(fun d->f(n/d)*g d)
```
Takes the two functions `f` and `g` and a natural number `n`. Filters out the values of `d` that do not naturally divide into `n`. Then evaluates `f(n/d)` and `g(d)`, multiples them together, and sums the results.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 32 bytes
```
(f,g,n)->sumdiv(n,d,f(n/d)*g(d))
```
[Try it online!](https://tio.run/##Hcs7DoAgDADQqzi2pqDs6kUIg6ZKGKgEP5N3r8b9vTLXZGJRbsZGYaNIgmY6rszpBiGmDaRjbCMwopaa5ATPID@gvK9Luo7vPDIY76x1fQioLw "Pari/GP – Try It Online")
There is a built-in `dirmul` function, but it only supports *finite* sequences.
[Answer]
# APL(NARS), 47 chars, 94 bytes
```
{(m⍵[1])×n⍵[2]}{+/⍺⍺¨{k←⍳⍵⋄(⍵÷b),¨b←k/⍨0=k∣⍵}⍵}
```
where m and n are the function one has to use (this because i don't know how
to call one array of function in one function in APL).
Using the example above the multiplication of Mobius function (here it is 12π) and sum of divisors
function (here it is 11π) for value 12 that multiplication would be:
```
{(12π⍵[1])×11π⍵[2]}{+/⍺⍺¨{k←⍳⍵⋄(⍵÷b),¨b←k/⍨0=k∣⍵}⍵}12
12
```
if one has to calculate some other value:
```
{(12π⍵[1])×11π⍵[2]}{+/⍺⍺¨{k←⍳⍵⋄(⍵÷b),¨b←k/⍨0=k∣⍵}⍵}1002
1002
{(12π⍵[1])×11π⍵[2]}{+/⍺⍺¨{k←⍳⍵⋄(⍵÷b),¨b←k/⍨0=k∣⍵}⍵}1001
1001
{(12π⍵[1])×11π⍵[2]}{+/⍺⍺¨{k←⍳⍵⋄(⍵÷b),¨b←k/⍨0=k∣⍵}⍵}20000x
20000
```
One can see if for example the first 2000 number the function result is the identity
```
(⍳2000)≡{(12π⍵[1])×11π⍵[2]}{+/⍺⍺¨{k←⍳⍵⋄(⍵÷b),¨b←k/⍨0=k∣⍵}⍵}¨⍳2000
1
```
] |
[Question]
[
# Landslides
In this challenge, your job is to predict the extent of damage caused by a massive landslide.
We use the following simplified two-dimensional model for it, parameterized by an *initial height* `h >= 0` and a *critical coefficient* `c > 0`.
You start with a cliff of height `h`, and it is assumed that the terrain is completely flat infinitely to the left and to the right of it.
For `h = 6`, the situation looks like this:
```
##########
##########
##########
##########
##########
##########
-----------------------
```
The `-` are immovable bedrock, and the `#` are unstable soil.
If the height difference between two neighboring columns is more than `c`, a *landslide* occurs: the top `c` units of soil from the left column fall down to the next `c` columns on the right, one to each.
The rightmost non-empty column in the figure is unstable for `c = 2`, so a landslide is triggered:
```
#########
#########
##########
##########
##########
############
-----------------------
```
The column is still unstable, which causes a second landslide:
```
#########
#########
#########
#########
############
############
-----------------------
```
Now, the column on its left has become unstable, so a new landslide is triggered there:
```
########
########
#########
###########
############
############
-----------------------
```
After this, the cliff is stable again.
The nice thing about this model is that the order in which the landslides are processed does not matter: the end result is the same.
# The Task
Your program is given the integer parameters `h` and `c` as inputs (the order does not matter, but you must specify it on your answer), and it should output the total number of *columns* that the landslide affects.
This means the number of columns in the resulting stable cliff whose height is strictly between `0` and `h`.
In the above example, the correct output is `4`.
You can write a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.
# Test Cases
These are given in the format `h c -> output`.
```
0 2 -> 0
2 3 -> 0
6 2 -> 4
6 6 -> 0
10 1 -> 10
15 1 -> 14
15 2 -> 11
15 3 -> 6
40 5 -> 16
80 5 -> 28
80 10 -> 17
```
[Answer]
# CJam, ~~62~~ 57 bytes
As far as I can see, this is completely different approach to implement the solution from aditsu's answer.
```
q~:C;:HaH)*H){(:I\_@>2<:-C>{I0a*C~)+C1a*+]z1fb_,}I?}h-H-,
```
Input goes in the form of `h c`
Example:
```
80 5
```
Output:
```
28
```
**How it works**
The logic is pretty straight forward here with a few tricks used to reduce code size.
* Get `h + 1` (`+ 1` for `h = 0` case) length array with each element being `h` to represent the cliff
* Start iterating from the right most index of this array
+ If the two elements from current index have different more than `c`
- Remove `c` from the current index element
- Add `1` to next `c` elements of the array from the current index
- Make the current index equal to the length of this new array
- This makes sure that we stabilize the stones to the right of the current index first
+ else, reduce the current index
* When we hit the left most index, we are making sure that all adjacent indexes have less than or equal to `c` difference
* Remove any `0` or `h` value from the array and get length.
**Code expansion**
```
q~:C;:HaH)*H){(:I\_@>2<:-C>{I0a*C~)+C1a*+]z1fb_,}I?}h-H-,
q~:C;:HaH)*H)
q~:C;:H "Read the input, evaluate it, store height in H and coeff. in C";
aH)* "Wrap the height number in an array and repeat it H + 1 times";
H) "Put H+1 on stack, representing the current index of iteration";
{(:I\_@>2<:-C>{I0a*C~)+C1a*+]z1fb_,}I?}h
(:I\_@>2<:-C>
(:I "Decrement the current index and store it in I";
\_ "Swap to put array on top and make 1 copy";
@>2< "Get the two elements starting from Ith index";
:- "Get the difference. The best part of this approach is that";
"For the right most index, where there is only element, it";
"returns the element itself, which is the expected difference";
C> "Check if difference is greater than C";
{I0a*C~)+C1a*+]z1fb_,} "This block will be executed when the difference is more than C";
I0a* "Get an array of I length and all elements 0";
C~)+ "Get -C value and append it to the above array";
C1a*+ "Get C length array of 1s and concat with the above array";
] "Wrap the two arrays, the cliff and the above one in an array";
z1fb "Transpose to get number pairs and add those pairs. For example";
"If we are at the right most index with H = 80 and C = 5,";
"The right section of the cliff looks like:";
"[ ... 80 80 80 80 80] and the array created in above step";
"looks like [ ... 0 0 0 0 -5 1 1 1 1 1]. After z, we have:";
"[ ... [80 0] [80 0] [80 0] [80 0] [80 -5] [1] [1] [1] [1] [1]]";
"After 1fb we get [ ... 80 80 80 80 75 1 1 1 1 1]";
_, "Take a copy of the above resultant array and take its length";
I? "If difference was not greater than C, put I on stack";
"Now we either have the decremented index or new array length";
"on stack."
{ ... }h "This is a do while loop which makes sure that we iterate to";
"the left of the array. This loops runs till the top stack";
"element is 0 while not popping the top element";
-H-, "After the loop, we have the final cliff array and 0 on stack";
"Remove any 0 elements from the array, then remove any H";
"elements from the array and then take length to get the";
"number of columns which were modified";
```
[Try it online here](http://cjam.aditsu.net/)
[Answer]
# CJam - 70
```
q~:C;:H0]H*$W%{[__W<\1>]z{~-}%{C>}#):I{I(_2$=C-tC,{I+_2$=)t}/}0?}h-H-,
```
Try it at <http://cjam.aditsu.net/>
**Explanation:**
```
q~ read and evaluate the input
:C; store the 2nd number in C and remove
:H store the first number in H
0]H* make an array [H 0] and repeat it H times
$W% sort and reverse, obtaining [(H H's) (H 0's)] (initial cliff)
{ loop...
[__W<\1>] make an array with the cliff without the first column
and the cliff without the last column
z{~-}% subtract the 2 arrays to get the height differences
{C>}# find the index of the first height diff. greater than C
):I increment and store in I
{ if the value is non-zero (i.e. landslide occurring)
I(_2$=C-t subtract C from the corresponding column height
C, make an array [0 1 ... C-1]
{ for each of those numbers
I+ add I, obtaining a column index where some soil falls
_2$=)t increment the column height
}/ end loop
}0? else break outer loop; end if
}h ...while the condition is true
-H- remove all 0 and H from the final stable cliff
, count the remaining columns
```
The `h` operator checks the last value on the stack without removing it. If a landslide occurred, the value is the cliff array, which evaluates to true because it's not empty. If not, the last value is 0 (false).
So in case of landslide, the loop continues with the array on the stack, otherwise it ends with a 0 pushed after the array. That 0 is then removed from the array by the next `-` operator.
[Answer]
# Python, ~~200~~ ~~190~~ 174
```
h,c=input();q=[h]*h+[0]*h
try:
while 1:
d=[b-a for a,b in zip(q[1:],q)];g=max(d);a=d.index(g)
for i in range(c):q[a+1+i]+=1/(g>c);q[a]-=1
except:print sum(h>i>0for i in q)
```
Expanded version:
```
h, c = input()
# Initialize the heights
q = [h]*h + [0]*h
try:
while 1:
# Difference between the heights
d = [b-a for a,b in zip(q[1:],q)]
# It may error here, when h == 0, but thats okay
g = max(d)
a = d.index(g)
for i in range(c):
# This is the termination condition, when g <= c
q[a+1+i] += 1 / (g>c)
# Save the newline; also move this line to after termination
q[a] -= 1
except:
# Count all heights that have changed
print sum(h > i > 0 for i in q)
```
**Edit:** After some optimizing, I eliminated the awkward loop termination via break (saves 1 byte). Also changed the slide from slice based to loop based.
[Answer]
# Python 2 - ~~194~~ 158 bytes
```
h,c=input()
b=l=[h]*h+[0]*h
while b:
b=0
for i in range(len(l)-1):
if l[i]-l[i+1]>c:
for j in range(c):l[i-~j]+=1
l[i]-=c;b=1
print sum(h>e>0for e in l)
```
(Note that SE's markdown interpreter converts literal tabs to 4 spaces. Lines 7 and 8 of this program have only a single tab [i.e. one byte] of indentation each.)
Takes input on stdin, `h` first. For example:
```
$ ./landslide.py <<< '6, 2'
4
```
This program has been through a lot of improvements. I had been editing this answer to explain some of the more major edits, but it was getting kind of long. You can check the edit history if you're curious.
**Explanation**
First, `h`and `c` are read from stdin. In Python 2, `input()` is equivalent to `eval(raw_input())`, which is why I ask for a comma separating the numbers. `input()` gives returns a tuple of ints, no conversion required.
Next, a list of integers is made. It is `2*h` long. The first half are `h` and the second half are 0. I don't have any reasoning to show that this is enough to simulate infinite `h`s to the left and 0s to the right. I just sort of stumbled into it and it works for all the test cases, so if someone can find input it doesn't work for I'll gladly change it. Anyway, this list is called `l`, but another copy of it is called `b`.
`b`'s value doesn't actually matter, all that matters is that it's truthy. A non-empty list is truthy and the only way `b` can be empty here is if `h` is 0, in which case the correct answer is still printed. In any other case, `b` has to be truthy to ensure we enter the `while b:` loop. However, the first thing that happens in the loop is setting `b` to 0, a falsey value. During each repetition of the loop `b` must be specifically set back to a truthy one or the loop will end.
The rest of the loop is the actual simulation. It's very naive, essentially just being a code translation of the problem description. If any element of `l` is more than `c` greater than the one following it, it is subtracted by `c` and the next `c` elements have 1 added to them. (The bitwise magic used here is just a shorter way of writing `i+1+j`, by the way.) While making these transformations, `b` is set to 1. The first time no transformations are made, `b` will stay 0 and the loop terminates.
Any true expression evaluates to `True`, and when you try to do math on `True` it evaluates to 1. The same is true of `False` and 0. The last line of the program uses every element of `l` as `e` in the expression `h>e>0` and sums the result. This gets the number of columns greater than 0 but lower than the original cliff height, which is the value the question asks for. It's printed and the program exits.
[Answer]
# Haskell, 163 156 151 Bytes
```
h#c=sum[1|e<-(until=<<((==)=<<))s$r h++r 0,e`mod`h/=0]where r=replicate$h+1;s w@(x:y:z)|x==0=w|x>c+y=x-c:map(+1)(take c(y:z))++drop c(y:z)|1<2=x:s(y:z)
```
Usage: `h#c`, e.g. `6#2` which outputs `4`.
How it works: the helper function `s` does a single landslide. Repeatedly apply `s` until the output does not change anymore. Count the affected elements.
Found the "apply until output doesn't change" function (i.e. `until=<<((==)=<<)`) at [Stackoverflow](https://stackoverflow.com/questions/7442892/repeatedly-applying-a-function-until-the-result-is-stable/23924238#23924238).
[Answer]
# Mathematica, ~~108~~ ~~104~~ ~~100~~ ~~97~~ 95
```
f=Max@#-Min@#&[0Range@#2//.{x___,k:##..&[a_,{#}],a_,y___}:>Sort@{x,##&@@({k}-1),a+#,y}/.{}->0]&
```
Usage:
```
f[c, h]
```
Example:
```
f[5, 80]
```
>
> 28
>
>
>
[Answer]
### C# 303 295
It works!
But it is a ....
```
int q(int n,int c){var s=Enumerable.Repeat(n,n).ToList();s.Add(0);var d=new HashSet<int>();var g=true;while(g){g=false;for(int i=s.Count-1;i>0;i--){int z=i;int y=i-1;if((s[y]-s[z])>c){s[y]-=c;d.Add(y);g=true;for(int j=1;j<=c;j++){s[y+j]++;d.Add(y+j);if(s[s.Count-1]>0)s.Add(0);}break;}}}return d.Count;}
```
I must find new language ;)
I'll check this CJam thing ...
Improved:
```
int q(int n,int c){var s=Enumerable.Repeat(n,n).ToList();s.Add(0);var d=new HashSet<int>();var g=1>0;while(g){g=1<0;for(int i=s.Count-1;i>0;i--){int z=i,y=i-1;if((s[y]-s[z])>c){s[y]-=c;d.Add(y);g=1>0;for(int j=1;j<=c;j++){s[y+j]++;d.Add(y+j);if(s[s.Count-1]>0)s.Add(0);}break;}}}return d.Count;}
```
] |
[Question]
[
## Flavortext
So...this is awkward. It seems I accidentally turned into a monkey last night after eating one too many banana sundaes. This has made many things inconvenient, especially typing. You see, monkeys only need the following characters: uppercase letters (`A-Z`), space, comma (`,`), exclamation mark (`!`), and question mark (`?`). For all other purposes, the Stack Overflow keyboard is enough for copy-pasting a.k.a. monkey see, monkey do. Furthermore, since we are superior to humans and do not have opposable thumbs, we can use our thumbs for more than just the space bar. Finally, monkeys absolutely hate typing consecutive characters with the same finger, so typing combos such as "dee" and "un" on a QWERTY keyboard is very annoying.
## Task
That's why I've made a new ergonomic keyboard that looks like this, and your task is to assign its keys.
Left paw                        Right paw
`⎕``⎕``⎕``⎕``⎕`    `⎕``⎕``⎕``⎕``⎕`
`⎕``⎕``⎕``⎕``⎕`    `⎕``⎕``⎕``⎕``⎕`
`⎕``⎕``⎕``⎕``⎕`    `⎕``⎕``⎕``⎕``⎕`
Every finger is used for the three keys in one column and only those keys (so the left pinky would be used for the first column and the right thumb for the sixth).
You will be given a string representative of what I usually type, and will design a keyboard according to the following requirements:
* It will be in the shape of the blank keyboard above.
* It will contain the characters `ABCDEFGHIJKLMNOPQRSTUVWXYZ ,!?` (note the space) and only those characters.
* None of the strings in the input will cause me to type consecutive characters using the same finger.
Here's an example:
```
Input: 'I LIKE BANANAS! WHERE BANANA?!'
```
A valid keyboard would be:
``I````L````A````N````R``    ``D````F````G````J````M``
``E````K````!````S````?``    ``Z````O````P````Q````T``
``B````Y````W````H````C``    ``,````U````V````X``
An invalid keyboard would be:
``I````E````A````N````R``    ``D````F````G````J````M``
``L````K````!````S````?``    ``Z````O````P````Q````T``
``B````W````H````C``    ``,````U````V````X````Y``
This violates the third requirement, because to type `LI` in `I LIKE BANANAS!`, I would have to use my left pinky twice for consecutive characters: once for `L` on the middle row and once for `I` on the top row. I would also have to use my left ring finger twice while typing `KE`.
## Rules
* The input will always consist only of the characters `ABCDEFGHIJKLMNOPQRSTUVWXYZ ,!?`, just like the keyboard.
* You may assume that a valid keyboard exists for the input.
* You may input and output in any reasonable format.
## Test cases
The output of each test case is formatted the same as the examples above, but without `<kbd>` and spaces between the two paws' keys. An underscore (`_`) is used instead of a space for clarity.
```
'Input'
Keyboard
'I HAVE A TAIL AND YOU DO NOT! WHY?! I PITY YOU!'
I_HAVETLND
Y?OUWPBCF,
!GJKMQRSXZ
'REJECT MODERNITY, RETURN TO MONKE! EAT BANANA!'
RECOD!BQSX
JNKI,FGAV?
TM_YUHLPWZ
```
[Here](https://tio.run/##XVDdT9swEH@e/4qLnxItiyi8oEqo6tZtdIOWj0LJMqsyiUs9EtuyXVj554sv7VjpQxz7fl93Z1Z@odXRsbHrtWyMth7cyqXgvJXqgZBaKuHgBAq8ZFg1Mf2taAJzbQGLIBVKAlZJlVnBq1YTJyDnsK9iBM1aQnHAyON99fb8dNRlhDTSuVm54BYzy0WbEn6Y0XaUcVdKOVsaI2zJnYCPQKNeChTTAlFpj2RKsz9aqjgEYCZvxKzU9bJRwdYtmziM43z8Etqy@rmTQjgPk81MWEAL7G37Pty@WQoFS3btZl789diq4dK29PYS6OiNeyw6Xdau4h@wow7zBqDoHKSw@RhEuI7QWsNNXAuVYmySdMkHE6b3MS3uGEytVg/g5IugCRF1sHjb2nvieSiHnQEivPTCui5N/5O34v1x3ntcBxTmwUVYFO@T0cOJHcktg1wvLTyK1b3mtgLp4InXssposl4P4bR/@xX6MOkPz6A/GkA@voHBGEbjSQTT07wXwRAuhpMcgYiQjWByNhqQvDe@mV58/vItJdH3Hz/PL6@u7369Ag) is a validator kindly provided by [tsh](https://codegolf.meta.stackexchange.com/users/44718/tsh).
[Answer]
# [Perl 5](https://www.perl.org/), 134 bytes
```
sub f{@k=(A..Z,$",',','!','?');splice@k,rand@k,0,pop@k for 1..1e3;@p{@k}=0..29;join('',map$p{$_}%10,split//,$_[0])=~/(.)\1/?f(pop):@k}
```
[Try it online!](https://tio.run/##RY9RT4MwFIXf@RWXhUmJTQsaHxwhozqSMRUMYZopZtkcGGSDBtjDQthfx8IezE17k3v6nd7D43J/13XVcQtJY2cWYoR8YGWE1b5kcaaqZlZ8n37HdobLTb4TTce84HYGSVGCQYgR35o2F3hr6YTc3Ju/RZojVcWHDVd4o6zbsaHj3qSmFCvrT/1Ls84UES0y6DRBwkybCLo7nMCu46q2kASgujBnbw4wCJn7DMybwcpfwswHzw9leJ@vpjK48OqGq14Qu/ZQ4CycxxBe/JkTeELCEDjhMvAg9MXQe3JkcFgID8wTJauSZkpSH0N8raQ5P9aAhhW0RrjBMM62O6tPJAJBgi6vBNbLvEzzOoGRO5DXkMWnbbEpd5Moj/Jx9X@P8IXDg9u5oqQx9JYqV1FOf0pTars/ "Perl 5 – Try It Online")
```
sub f{
@k=(A..Z,' ',',','!','?'); #put valid keys in array @k
splice@k,rand@k,0,pop@k for 1..1e3; #shuffle array @k in random order
@p{@k}=0..29; #assign a position 0-29 to each key
join('',map$p{$_}%10,split//,$_[0]) #make string of each input char mapped...
#to its key position modulus 10 = column number
=~ /(.)\1/ #check if two adjacent column numbers exists...
#for current input
? f(pop) #if yes, try new keyboard on same input
: @k #if no, return current random valid keyboard...
#as an array of 30 chars
}
```
This approach tries random keyboards until it hits a valid one for the current input string. In a test of 1000 runs of both the given test strings, a valid keyboard was found at the 20th trial on average. üêµ
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), 18 bytes
```
30Œ!ðiⱮ’:3nƝẠðƇḢs3
```
[Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCIzMMWSIcOwaeKxruKAmTozbsad4bqgw7DGh+G4onMzIiwiw5hBO+KAnCAsIT/igJ3CpGnisa7Dh+G7i+KBuMqLWlkiLCIiLFsiJ0kgTElLRSBCQU5BTkFTISBXSEVSRSBCQU5BTkE/ISciXV0=)
-1 byte thanks to caird coinheringaahing
This should work in theory. However, it is \$O(N! \times NM)\$ where \$N\$ is the size of the alphabet and \$M\$ is the size of the input.
You can try this for a restricted alphabet of "ABCDEF" [here](https://jht.hyper-neutrino.xyz/tio#WyIiLCI2xZIhw7Bp4rGu4oCZOjM9xp3hurjDsMOQ4bif4biiczMiLCLDmEE74oCcICwhP+KAncKkaeKxrsOH4buL4oG4yotaWSIsIiIsWyJBQ0JFRkQiXV0=).
```
30Œ!ðiⱮ’:3nƝẠðƇḢs3 Main Link; accept a list of numbers from 1 to 30 on the left
30Œ! Get all permutations of 1..30
ð ðƇ Filter to keep; map over a dyad, which feeds the input to the right
iⱮ Get the index of each input in the permutation
’ Decrement to get into the range 0..29
:3 Floor divide by 3
n∆ù For each overlapping pair, check if the column indices are inequal
Ạ Are all inequal? (Filter will keep these)
·∏¢ Take the first valid permutation
s3 Divide it into non-overlapping chunks of length 3
```
Borrowing Kjetil's idea to use random permutations (which I actually had, but I wasn't sure if it'd be valid), we get the following solution, which is way faster (as in you can actually run it):
# [Jelly](https://github.com/DennisMitchell/jellylanguage), 18 bytes
```
iⱮ³’:3=ƝẸ
30RẊÇ¿s3
```
[Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCJp4rGuwrPigJk6Mz3GneG6uFxuMzBS4bqKw4fCv3MzIiwiIiwiIixbIls5LCAyNywgMTIsIDksIDExLCA1LCAyNywgMiwgMSwgMTQsIDEsIDE0LCAxLCAxOSwgMjksIDI3LCAyMywgOCwgNSwgMTgsIDUsIDI3LCAyLCAxLCAxNCwgMSwgMTQsIDEsIDMwLCAyOV0iXV0=)
-1 byte thanks to caird coinheringaahing by observing that we can bind the input to the right of the index link to avoid needing a combinator that we would've needed from binding it to the link reference call in the while loop.
You can translate test cases from words to numbers [here](https://jht.hyper-neutrino.xyz/tio#WyIiLCLDmEE74oCcICwhP+KAncKkaeKxriIsIiIsIiIsWyInSSBMSUtFIEJBTkFOQVMhIFdIRVJFIEJBTkFOQT8hJyJdXQ==) and translate the output back to text [here](https://jht.hyper-neutrino.xyz/tio#WyIiLCLhu4vDmEE74oCcICwhP+KAncKkWlkiLCIiLCIiLFsiW1s1LCAxMywgN10sIFszMCwgMTcsIDNdLCBbMTAsIDE0LCAxOV0sIFsyOSwgMSwgMThdLCBbMiwgMjYsIDE1XSwgWzIzLCA5LCAyNV0sIFs0LCAxMiwgOF0sIFsyMCwgMTEsIDZdLCBbMjIsIDI4LCAyMV0sIFsyNCwgMTYsIDI3XV0iXV0=).
```
iⱮ³’:3=ƝẸ Helper Link; check if a permutation is invalid
iⱮ³ Get the index of each input in the permutation
’ Decrement to get into the range 0..29
:3 Floor divide by 3
=∆ù For each overlapping pair, check if the column indices are equal
·∫∏ Are any equal?
30RẊÇ¿s3 Main Link
30R 1..30
¬ø While
Ç The permutation is invalid
Ẋ Shuffle it
s3 Divide it into non-overlapping chunks of length 3
```
Unfortunately, I have to explicitly bind the input as the right argument to `ç` because otherwise the while loop will Fibonacci.
[Answer]
# [Haskell](https://haskell.org), 181 bytes
```
import Data.List
f[]=[]
f(a:b:c:x)=[a,b,c]:f x
g(a:b:x)=(a,b):g(b:x)
g _=[]
q s=head$filter(\x->not$any(\(a,b)->any(\r->a`elem`r&&b`elem`r)$f x)$g s)$permutations$['A'..'Z']++"?!, "
```
[Try it online](https://tio.run/##LY1BDoIwFET3PcWXNNBG5ABN0GhcGjfuBCIfLdgIBdua4OmxEDOLmXnJZJ5oX7Jtp0l1Q28cHNFhclLWkTor0qwgNUNRibsYeZphXMX3QtQwkmbBHjIPuWjYXEgDt3nzBps@JT5orVonDcvHzVb3jqL@snwZbLZLNt5L2cquNGFY/ROn/oDTBiyngzTdx6FTvbY0i/ZRkkTXqFivg90qhoCQDpWGFAajtAP2huCwP3tddquAT9MP)
Goes through all permutations and picks the first one that does not have any adjacent characters on the same column. Output is flattened. It should work in theory with an awful complexity of O(SNS!) where S the size of the alphabet and N the length of input.
[Answer]
# [Python 3](https://docs.python.org/3/), 163 bytes
```
s=input()
l=k=''.join({}.fromkeys(s).keys())
while any(x+y in l for x,y in zip(k,k[1:])):k=''.join({*k})
print(k+''.join({*'ABCDEFGHIJKLMNOPQRSTUVWXYZ ,!?'}-{*k}))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v9g2M6@gtERDkyvHNttWXV0vKz8zT6O6Vi@tKD83O7WyWKNYUw9Ma2pylWdk5qQqJOZValRoVypk5inkKKTlFylU6IA5VZkFGtk62dGGVrGamlZIhmll12pyFRRl5pVoZGsjRNUdnZxdXN3cPTy9vH18/fwDAoOCQ0LDwiMioxR0FO3Va3XBOjX///dU8PH0dlVwcvQDwmBFBQA "Python 3 – Try It Online")
Returns keyboard transposed flat and joined
[Answer]
# JavaScript (ES6), 136 bytes
*-16 bytes thanks to @tsh*
Expects an array of characters. Returns a random keyboard as an array of 3 strings.
```
f=a=>a.some(c=>p==(p=k.indexOf(c)%10),p=k=[...'ABCDEFGHIJKLMNOPQRSTUVWXYZ ,!?'].sort(_=>Math.random()-.5))?f(a):k.join``.match(/.{10}/g)
```
[Try it online!](https://tio.run/##bY1Nb4JAGITv/RUvh4bdRF/10EuThayFlq0IfqCWNqZu@FBUWAKkadL0tyOa9NbMaWbyzBzll6yjKiubfqHipG1TJpkhsVZ5QiJmlIyRkp0wK@Lk209JRO9HQ9rrIvaBiDofP1n284sjXifu1PNn88UyWK03b@E79DRT33ZDVUM@mTGVzQErWcQqJ7SPD5SaKZH08YRHlRW7HeayiQ5kgD@j4e9gT9tIFbU6J3hWe5KS25kAh69t4BBw4QL3LAj9FVg@eH6gwcYJTQ0EzEQQXgtN31J69@@MKyY2jLnXaXkF7cWfNW9UewE "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
Try to create a simple ASCII art scissors animation!
# Challenge
All inputs will be integers -31 through 31.
The output will be an animation (To be outputted *somewhere*, as long as the previous frame is replaced. GIFs are allowed.), separated by (approximately) 1 quarter of a second.
If the input (`n`) is positive:
* The animation should start with `8<`, AKA open scissors.
* The next frame is `8=`. This shows the scissors "cutting".
* A dash (cut mark) is added behind the scissors, and the animation repeats until there are `n` dashes.
If the input is negative:
* The scissors start open and facing towards the left (Like this: `>8`), with `n` spaces in front of it.
* The scissors close and remain facing towards the left (`=8`).
* The scissors re-open, as space is removed, and a dash is added behind the scissors.
If the input is zero:
* Output just the scissors opening and closing, for 10 frames. They can be facing either direction, as long as it is consistent.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest submission in bytes wins. (Even if your entry clearly won't win because of some sort of newfangled "golfing language", we'd still like to see it.)
Error messages are allowed, as long as the error message itself does not interfere with the animation.
# Example Input and Output Pairs:
(I separated the frames for clarity, but there should be approximately .25 seconds between each frame)
```
Input: 1
Output:
8<
8=
-8<
Input: 2
Output:
8<
8=
-8<
-8=
--8<
Input: 5
Output:
8<
8=
-8<
-8=
--8<
--8=
---8<
---8=
----8<
----8=
-----8<
Input: 0
Output:
8<
8=
8<
8=
8<
8=
8<
8=
8<
8=
Input: -2
Output:
>8
=8
>8-
=8-
>8--
Input: -3
Output:
>8
=8
>8-
=8-
>8--
=8--
>8---
```
Enjoy!
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGLOnline), 53 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
LA0≠?.θ«IA}a∫H.¡*»:B┌* 8+Ƨ<=F2%W+a»b-@*+.0<?↔±}1¼UU░P
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=TEEwJXUyMjYwJTNGLiV1MDNCOCVBQklBJTdEYSV1MjIyQkguJUExKiVCQiUzQUIldTI1MEMqJTIwOCsldTAxQTclM0MlM0RGMiUyNVcrYSVCQmItQCorLjAlM0MlM0YldTIxOTQlQjElN0QxJUJDVVUldTI1OTFQ,inputs=MA__,v=0.12)
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~59~~ ~~58~~ 57 bytes
```
|EQG~10*+:"&FXx45@q2/kGg*XHY"8Vh61@oGO<Eq*+h4M?G|H-Z"hP]D
```
Try it at [MATL Online!](https://matl.io/?code=%7CEQG%7E10%2a%2B%3A%22%26FXx45%40q2%2FkGg%2aXHY%228Vh61%40oGO%3CEq%2a%2Bh4M%3FG%7CH-Z%22hP%5DD&inputs=5&version=20.6.0) Or see an example run from the offline compiler:
[](https://i.stack.imgur.com/B1c6Z.gif)
[Answer]
# JavaScript (ES2017) + HTML, 165 + 10 bytes
**-16 bytes by @Shaggy**
```
n=>(g=i=>i<-~(n?2*m:9)&&setTimeout(g,250,i+1,s=8+"<>="[i%2?2:n<0|0],o=("-".repeat(i/2)+s).padEnd(m+2),e.innerHTML=(n?n<0?[...o].reverse().join``:o:s)))(0,m=n<0?-n:n)
```
```
<pre id=e>
```
Try it in the below snippet:
```
let globalTimeout;
const _setTimeout = setTimeout;
window.setTimeout = function(){ globalTimeout = _setTimeout.apply(this, arguments); }
// Code above is to support user input
f=
n=>(g=i=>i<-~(n?2*m:9)&&setTimeout(g,250,i+1,s=8+"<>="[i%2?2:n<0|0],o=("-".repeat(i/2)+s).padEnd(m+2),e.textContent=(n?n<0?[...o].reverse().join``:o:s)))(0,m=n<0?-n:n)
// Code below is to support user input
f(10)
const $inp = document.getElementById("inp");
inp.addEventListener("change", ()=>{
clearTimeout(globalTimeout);
f(+inp.value);
});
```
```
<input type="number" id="inp" min="-31" max="31" value="10" />
<pre id=e>
```
[Answer]
# TI-BASIC, 173 bytes
```
:"-
:For(X,1,5
:Ans+Ans
:End
:For(X,1,32
:" "+Ans+" →Str1
:End
:ClrHome
:Input N
:N<0→X
:For(A,not(N),abs(N+5not(N
:For(B,4-3X,6-3X-(A=abs(N)),2
:33X-Anot(not(N
:Output(1,16,sub(Str1,33X+32,abs(Ans-1)-NX-31X)+sub(">8=8<8=",B,2)+sub(Str1,Ans+32,1
:rand(11
:End
:End
```
Having the 0 input terminate in a different frame from the others was a very interesting obstacle!
Since TI-BASIC doesn't like empty strings, this maintains at least one dummy character to the left of the scissors, the first of which is constantly a space; to hopefully avoid counting this as part of the *n* spaces for negative inputs, this program begins printing from the rightmost column of the first row, then wraps the remainder of the string downward in order to begin the actual field of animation there, fresh off the first column.
Some notes for an exotic device: TI-BASIC code size is measured in tokens, not characters. For consistent cross-calculator comparisons, we usually ignore byte counts dealing with header lengths (e.g., we subtract 8 from PROGRAM:SCISSORS). Additionally, for routines which are fully well-behaved on the home screen (those lacking in control structures, for the most part), we further eliminate the size of an empty program to "save" on 9 bytes as well. This program in particular is not typable on the home screen, so that liberty won't be taken.
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~190~~ 186 bytes
```
k=32+~e((a=abs(n=(z=input(''))+~z*10))+1,1);for i=1:a
clc
k(i:i+1)=[56,61-(s=sign(n))];q=@(m)fprintf(rot90([m ''],s));q(k)
if(i-a)pause(.25)
clc
k(i+1)+=s;q(k)
pause(.25);k(i)=45;end
end
```
[Try it online!](https://tio.run/##RYy9DoIwFEb3PgVb77VgqFoSaW7iexCGisU0SPkpODDw6khijMOXbzgnp6sm87bb1tD5JFYLYMjcA3iChZzv5wk4RxTrcpDp/jKWqOtujBzJ3LDqVbEGXO6ERCpUFmcygUDBPT14xFIPdIMW6350fqph7KZrCkUbcV7GAVEP0CBzNbjEYG/mYOF4UvjL7lFB4Sv9qd4J0kVp6x9s37apDw "Octave – Try It Online") (note: `clc` does not work in TIO, so it's just all the animation frames outputted sequentially). Thanks for @LuisMendo for making me aware of the function `e(...)` in Octave, which is equal to `exp(1)*ones(...)`.
It turns out that inline assignments return only the changed array entries, not the entire array. This means that constructions like `q(k(i+1)+=s)` are not possible, so the program is almost like MATLAB. In fact, the MATLAB entry is only slightly longer,
# MATLAB, ~~198~~ 195 bytes
```
n=input('');n=n+~n*10;a=abs(n);s=sign(n);k=zeros(a+1,1);q=@(k)fprintf(rot90([k ''],s));for i=1:a
k(i:i+1)=[56 61-s];clc
q(k)
if(i-a)pause(.25);
k(i+1)=k(i+1)+s;clc
q(k)
pause(.25)
k(i)=45;end
end
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 281 bytes
```
$n=$args[0];$o="8<";$c="8=";function x{sleep .25};if($n-le0){$n=[math]::abs($n);$o=">8";$c="=8";$p=' '*$n;$p+$o;$x;$p+$c;1..$n|%{$p=$p-replace"\s$","";$p+$o+('-'*$_);if($_-eq$n){break};$x;$p+$c+('-'*$_)};$x}else{$o;x;$c;1..$n|%{
$y='-'*$_;$y+"8<";if($n-eq$_){break};$x;$y+"8=";$x}}
```
[Try it online!](https://tio.run/##VY9dCsIwEITfPUUJK7XWFhWE0hgvolJiWX8wprFRVGLPHrctKD7tsjP7DWOqB9b2iEp5D1qArA92Pd1yqATLloxDSVMwvr/r8naqdPB0ViGaIJ0vGn7aj0AnCqeRo@f1Rd6O2zyXO0vnqGOssp4h2mlEGIRj0LTFUHF4dkvJZ2kK@j10ZACT1GiULJFtLLAJY705HoUJvRZRl1kkeKUEt6tRnpsv6GtqTw0qi45iSPxFDOAlehOHV9xV7EsQsPgDtioVJ1DjvV98AA "PowerShell – Try It Online")
[Answer]
# [Clean](https://clean.cs.ru.nl), 294 bytes
```
import StdEnv,System.Time,ArgEnv,System._Unsafe
Start#n=toInt(select(getCommandLine)1)
=[?k l\\k<-[1..]&l<-if(n==0)(flatten o$5)(init)[$(abs n+2)'\b'++if(n<0)(rjustify(abs n+2))reverse[c,'8': $i'-']\\i<-[0..abs n],c<-[if(n<0)'>''<','=']]]
?t#(Clock n)=accUnsafe clock
|n>t*250=id= ?t
$ =repeatn
```
[Try it online!](https://tio.run/##TZBBa8JAEIXv@RULhm62JkEFoZSsUmwPgoeC7cmEsm4msjU7kd1REPrbu41aSm/z3nzMzBvdgsJgu/rYArPKYDD20Dlia6pf8JSuz57A5m/GQvrkdv@sj3f0qoFoTcrRACV1S6TEQwuakh3QorNWYb0yCGIsIrmZ71lblvsi24zzvLpri8w0CUo5EknTKiJA1sVTkRg0JDZxorae4XAieLnlw@GFLXrUfR49meb81xYOTuA8bHTKH/gjiw3PeFWWpl80yvMrVqW6V78j@Izzgqdc8qqqojkNkkXb6T1DIZXWt1RMX6zoC2d0P5mOpKklm1MUM@ngAIowhDD51v3dOx@ybciWq/B8RmWN9ldx@9W1fO3DNZ2zPw)
Note that this doesn't work on TIO, the link is just for presentation purposes.
Your results may vary if you have a `CLOCK_PER_TICK` constant other than `1000`, the default for x86 Windows Clean.
[Answer]
# [Python 2](https://docs.python.org/2/), 170 bytes
```
import time
n=input()
a=abs(n);s=a and n/a
for i in range([a-~a,10][a<1]):print'\n'*30+(a-i/2)*-s*' '+i/2*s*'-'+'>='[i%2]*(s<1)+'8'+'<='[i%2]*s+i/2*-s*'-';time.sleep(.25)
```
[Try it online!](https://tio.run/##NY5LCsIwFAD3PUU2kp/pJyKIbbxI7eKJVR/Y15DEhRuvHmvB3TDMYvw7PWayOePk55BYwmksyCH5VxKyAAeXKEi20QEDujKqoLjNgSFDYgHoPooezAe2TT300DWDPPqAlPiZuNrVWoDBykplouKM64XVQoZrfnK8x40dlIhdIzU/LK77u7iWZk3b31MZn@PoRWn3Mmdjvw "Python 2 – Try It Online")
[Answer]
# Ruby, 169 bytes
```
->x{i="";o=?=;(x!=0&&x.abs*2+1||10).times{|l|o=o[?=]?x>0?"8<":">8":x>0?"8=":"=8";f=?\s*(x<0&&-x-l/2||0);system"cls";puts x>0?i+o:f+o+i;i+=?-if(l).odd?&&x!=0;sleep 0.25}}
```
Pretty much self explainatory when you dig into it, atleast in my opinion.
Program has to be running on a computer with the cls command/alias.
[Try it online!](https://repl.it/@hrrs01/EnergeticConcernedAmethystsunbird) ( Had to overwrite the system() method, just for this script, due to the limitations mentioned above. )
I did try to use
```
puts `cls`, ...
```
But it just printed an invisible character, anyone know why?
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~46~~ 41 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
üîφL↑≥ª⌡↨ÄA ¡`╢Σ·TmÄ↕=≈─Xí♫αF²M☻8]▒2±(═[3
```
[Run and debug it](https://staxlang.xyz/#p=818ced4c18f2a6f5178e4120ad60b6e4fa546d8e123df7c458a10ee046fd4d02385db132f128cd5b33&i=1%0A2%0A5%0A0%0A-2%0A-3%0A&a=1&m=2)
`|,` was included in a [recent release](https://github.com/tomtheisen/stax/releases/tag/v1.2.0), which is great for this challenge!
Uses JS `requestAnimationFrame` for pausing between snips.
Each testcase happens continuously after the other, so if you want a more clear version, [try this!](https://staxlang.xyz/#c=c%7Ca%5E5%3Fr%7Bxs0%3FY.%3C%3D%7B%27-y*%278%2Bs%2Bx%7Ca%5E%5E%28x%7Bx%3A%2B*%7DM.%3C8.%3E8R%7B%7C,%7D9*%7C%3A%22Testcase%3A+%22pxPpFFzP%22Complete%21%22P%7B%7C,%7DAJ*&i=1%0A2%0A5%0A0%0A-2%0A-3%0A&m=2).
-5 bytes from recursive. (`:R`)
## Explanation
`c|a^5?rFxs0?.<={n'-*'8+s+x|a^^(x0<{:R}M{|,}9*|:pF`
`c|a^5?` initial zero check:
`?` if the input is truthy
`|a^` take abs(n) and increment
`5` otherwise push 5
`r` range 0..n-1
`F` for each value in the range,
`xs0?` **r:** if input is 0, then push 0, otherwise push loop iteration no.
`.<={...F`for each value in "<=",
`n'_*` repeat "\_" r times
`'8+` add 8 to that
`s+` add current loop iteration to that
`x|a^^` take abs(input) and increment twice
`(` pad on right to that length
`x0<{...}M` if input is less than 0
`:R` reflect the string (`<` → `>`)
`{|,}9*` delay 9 frames
`|:` output a form feed (clear screen)
`p` print the string without newline
] |
[Question]
[
Alternate name: `ChessMoveQ`
Given a list of up to 32 elements, each consisting of 4 elements, and a second list with 4 elements, determine whether the move detailed in the second input is a valid chess move.
The first list indicates the position of all 32 pieces on the board. Each element will follow the structure `<colour>, <piece-name>, <x-coord>, <y-coord>`, such as `["W", "K", 5, 1]`, which indicates that the white king is on `5, 1` (`e1` on a normal chess board). All elements of the first input will be unique. `<x-coord>` and `<y-coord>` will always be between 1 and 8. One example would be:
```
[["B", "K", 3, 8], ["B", "Q", 1, 5], ["B", "N", 4, 7], ["B", "N", 7, 8],
["B", "B", 2, 4], ["B", "R", 4, 8], ["B", "R", 8, 8], ["B", "P", 1, 7],
["B", "P", 2, 7], ["B", "P", 3, 6], ["B", "P", 5, 6], ["B", "P", 6, 7],
["B", "P", 7, 7], ["B", "P", 8, 7], ["W", "K", 5, 1], ["W", "Q", 6, 3],
["W", "N", 3, 3], ["W", "B", 5, 2], ["W", "B", 6, 4], ["W", "R", 1, 1],
["W", "R", 8, 1], ["W", "P", 1, 3], ["W", "P", 2, 2], ["W", "P", 3, 2],
["W", "P", 4, 4], ["W", "P", 6, 2], ["W", "P", 7, 2], ["W", "P", 8, 3]]
```
which would represent the board:
[](https://i.stack.imgur.com/NhRX7.png)
The second input will consist of the same structures as the sublists of the first one, but rather than the x and y coordinates indicating where the piece is, they are indicating where it is trying to move to.
For the above example, a valid move could be `["W", "B", 4, 3]` (bishop moves one square forward and to the left), and an invalid move could be `["B", "R", 4, 1]` as the rook would have to move through the knight, and the pawn to get to the square. As the move could refer to multiple pieces at times, you must test whether *any* of the specified pieces can make the move, not just one of them. For instance, the first example is valid for only one bishop, but it is still a valid move. However, neither black rook can perform the second move, so it is invalid.
Your task is to determine whether the move detailed in the second input is a valid chess move. The validity of a rule varies, depending on the piece trying to move (click on the name of the piece for a diagram of valid moves):
* **Any piece**: No pieces can move onto an already occupied square, or off the board, unless that square is occupied by a piece from the other colour. For example, a white piece may move onto a square occupied by a black piece, but not a white piece. Additionally, no pieces, except for Knights, can move to squares which are directly obstructed by another piece.
+ A move by piece **B** to square **C** is "directly obstructed" by piece **A** if **A** is directly, in a straight (orthogonal or diagonal) line, between **B** and **C**.
* **Any piece**: The position of the king can also affect the validity of a piece's move. If either of these two conditions are met, the move is invalid:
+ Exposing the king to check, by moving a piece on the same side as the endangered king. This only applies if a non-opposing piece makes the move, rather than an opposing piece moving to place the king into check.
+ Leaving the king in check, in which case it *has* to move out of check. Therefore, if the king is in check and the move dictates that another piece moves, it is an invalid move, *unless* the other piece is preventing check. A piece can prevent check in one of two ways: either it takes the piece performing check, or it obstructs the path between the piece performing check and the king.
+ A "check" is a situation in which the king's opponent could (if it was their turn to move) legally move a piece onto that king. This rule does not apply recursively, i.e. a king is in check even if the move by the opponent onto that king would leave their own king in check.
* [**Pawns**](https://i.stack.imgur.com/VmwIB.gif): A pawn can move forwards (i.e. upwards if white, downwards if black) one square to an unoccupied square. There are also three special situations:
+ If the pawn hasn't yet moved (you can determine this using the Y-coordinate; white pawns haven't moved if their Y-coordinate is 2, black pawns haven't moved if their Y-coordinate is 7), the pawn is allowed to move two squares forward to an unoccupied square.
+ If there is an opponent's piece diagonally in front of the pawn (i.e. on the square to the north-west or north-east of the pawn if it is white, or to the south-west or south-east if it is black), the pawn is allowed to move onto the occupied square in question.
+ If a pawn moves to the final Y-coordinate (8 for white, or 1 for black) in normal chess rules it must be promoted to a queen, rook, knight, or bishop of the same color. For the purposes of this question, the choice of promotion is irrelevant to whether the move is valid or not (and cannot be expressed in the input format), but pawn moves that would result in promotion must be allowed.
* [**Bishops**](https://i.stack.imgur.com/0rNIP.gif): Bishops can move between 1 and 8 squares along any continuous non-obstructed intercardinal (i.e. diagonal) path.
* [**Knights**](https://i.stack.imgur.com/utNVJ.jpg): Knights can move in an `L` shape, consisting of either of the following (equivalent) moves:
+ A single square in any cardinal direction, followed by a 90/270° turn, followed by a final move of 2 squares forward.
+ 2 squares in any cardinal direction, followed by a 90/270° turn, followed by a final move of a single square forward.
(Remember that the path of a knight cannot be blocked by intervening pieces, although its final square must still be legal.)
* [**Rooks**](https://i.stack.imgur.com/aw0ID.gif): Rooks can move between 1 and 8 squares along any continuous non-obstructed cardinal path.
* [**Queens**](https://i.stack.imgur.com/J0d5P.gif): Queens can move between 1 and 8 squares along any continuous cardinal or intercardinal (i.e. diagonal) non-obstructed path.
* [**Kings**](https://i.stack.imgur.com/rUiHI.gif): Kings move like queens, except that they are limited to moving only one square per move (i.e. a king can only move to cardinally or diagonally adjacent squares). As a reminder, you cannot make a move that leaves your king in check; thus you cannot move your king into check, either.
The rules of chess also contain special moves called "castling" and "en passant". However, because the legality of these moves depend on the history of the game, not just the current position (and because castling requires moving two pieces at once, which doesn't fit with the input format), you should consider neither of these moves to exist (i.e. a move that would be castling or en passant should be considered illegal).
You may output any two distinct results to indicate the validity of a move, and you may take input in a method you want. You may also choose 0-indexing rather than 1-indexing for the positions if you prefer. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins!
## Test cases
```
Board
Move => Output (Reason)
[["B", "K", 3, 8], ["B", "Q", 1, 5], ["B", "N", 4, 7], ["B", "N", 7, 8], ["B", "B", 2, 4], ["B", "R", 4, 8], ["B", "R", 8, 8], ["B", "P", 1, 7], ["B", "P", 2, 7], ["B", "P", 3, 6], ["B", "P", 5, 6], ["B", "P", 6, 7], ["B", "P", 7, 7], ["B", "P", 8, 7], ["W", "K", 5, 1], ["W", "Q", 6, 3], ["W", "N", 3, 3], ["W", "B", 5, 2], ["W", "B", 6, 4], ["W", "R", 1, 1], ["W", "R", 8, 1], ["W", "P", 1, 3], ["W", "P", 2, 2], ["W", "P", 3, 2], ["W", "P", 4, 4], ["W", "P", 6, 2], ["W", "P", 7, 2], ["W", "P", 8, 3]]
["W", "R", 8, 2] => True (The rook on h1 can move forward one)
[['B', 'K', 6, 8], ['B', 'Q', 1, 7], ['B', 'N', 1, 3], ['B', 'N', 7, 1], ['B', 'B', 8, 8], ['B', 'B', 2, 5], ['B', 'R', 4, 3], ['B', 'R', 1, 5], ['B', 'P', 5, 5], ['B', 'P', 7, 2], ['B', 'P', 5, 7], ['B', 'P', 5, 6], ['B', 'P', 4, 4], ['W', 'K', 7, 3], ['W', 'Q', 3, 2], ['W', 'N', 4, 8], ['W', 'N', 7, 5], ['W', 'B', 1, 1], ['W', 'B', 8, 1], ['W', 'R', 1, 8], ['W', 'R', 3, 7], ['W', 'P', 8, 2], ['W', 'P', 6, 3], ['W', 'P', 4, 2], ['W', 'P', 1, 4], ['W', 'P', 8, 7]]
['W', 'N', 1, 5] => False (Neither knight to move to a5 from where they are)
[['B', 'K', 7, 3], ['B', 'Q', 2, 4], ['B', 'N', 5, 2], ['B', 'N', 1, 6], ['B', 'B', 7, 7], ['B', 'B', 1, 8], ['W', 'K', 7, 1], ['W', 'Q', 6, 1], ['W', 'N', 5, 6], ['W', 'N', 3, 3], ['W', 'B', 2, 2], ['W', 'B', 6, 5]]
['B', 'K', 8, 3] => False (The white bishop would put the king in check)
[['B', 'K', 7, 6], ['B', 'Q', 8, 3], ['B', 'N', 7, 7], ['B', 'N', 8, 7], ['B', 'B', 2, 2], ['B', 'B', 3, 8], ['B', 'R', 1, 1], ['B', 'R', 1, 6], ['B', 'P', 8, 5], ['B', 'P', 4, 3], ['B', 'P', 8, 6], ['W', 'K', 7, 8], ['W', 'Q', 7, 2], ['W', 'N', 5, 1], ['W', 'N', 4, 6], ['W', 'B', 1, 2], ['W', 'B', 2, 6], ['W', 'R', 4, 4], ['W', 'R', 3, 6], ['W', 'P', 5, 2], ['W', 'P', 6, 2]]
['B', 'N', 5, 8] => False (The white queen currently has the king in check, and this move doesn't prevent that)
[['B', 'K', 7, 6], ['B', 'Q', 8, 3], ['B', 'N', 7, 7], ['B', 'N', 8, 7], ['B', 'B', 2, 2], ['B', 'B', 3, 8], ['B', 'R', 1, 1], ['B', 'R', 1, 6], ['B', 'P', 8, 5], ['B', 'P', 4, 3], ['B', 'P', 8, 6], ['W', 'K', 7, 8], ['W', 'Q', 7, 2], ['W', 'N', 5, 1], ['W', 'N', 4, 6], ['W', 'B', 1, 2], ['W', 'B', 2, 6], ['W', 'R', 4, 4], ['W', 'R', 3, 6], ['W', 'P', 5, 2], ['W', 'P', 6, 2]]
['B', 'N', 7, 5] => True (The king is in check, and the knight blocks that)
[['B', 'K', 8, 3], ['B', 'Q', 6, 5], ['B', 'N', 7, 8], ['B', 'N', 3, 7], ['B', 'B', 4, 1], ['B', 'B', 1, 1], ['W', 'K', 7, 7], ['W', 'Q', 7, 1], ['W', 'N', 2, 2], ['W', 'N', 1, 3], ['W', 'B', 3, 5]]
['B', 'B', 2, 2] => True (takes the white knight)
[['B', 'K', 6, 1], ['B', 'Q', 6, 2], ['W', 'K', 8, 1]]
['B', 'Q', 7, 1] => True (Smallest checkmate possible, in terms of bounding box)
```
This challenge was [sandboxed](https://codegolf.meta.stackexchange.com/a/14204/66833). It received downvotes, without any explanation, so I decided to post it anyway
[Answer]
# Regex (PCRE2), ~~931~~ ~~925~~ 837 bytes
This solution departs from the problem statement in that two board states are passed to the regex, instead of one board state and a move. The move is inferred from the difference between the two board states. So I made it the job of the TIO program to take the test cases in the format provided by this question, find all instances of the described piece on the board, and with each one, try moving it to the destination position and evaluating the regex with that possibility, finding if any are reported by the regex as valid. If this is not okay, let me know; it's possible to implement a regex as position + move, but would be much less elegant and require serious refactoring.
The board is represented in 8×8 ASCII where white pieces are uppercase and black are lowercase: **P**awn, k**N**ight, **B**ishop, **R**ook, **Q**ueen, **K**ing. Black's side (the 8th rank) is on the top and white's side (the 1st rank) is on the bottom. Each rank is separated by a newline, and empty squares are marked as `-`. The two board positions are separated by an extra newline.
The actual aim of this project is to validate entire games, not just single moves. See below for the current state of progress.
```
()?(?>|((.|
(?=.)){2})((?=(\X{72})-))((?=(?(1)[-a-z]|[-A-Z])))((?5)(?(?=(.*
)
)[qnrb]|p))((?5)(?(?=(?8){8}
)[QNRB]|P)))(?>((.)(?=(?5)\11)|(?(m)$)((?(1)(-(?=(?9))(?=(?3){8}((?3){9})?P(?4))(?(-1)(?=(?8){4}
))|[a-z](?=(?9))(?=(?3){7}(?2)?P(?4)))|(p(?4)((?=(?3){8}((?3){9})?-(?7))(?(-1)(?=(?8){7}
))|(?=(?3){7}(?2)?[A-Z](?7)))))|(?<e>(?6).)?(?=(?i:(?|(?(e)|(B|Q))(?27)(?(e)(B|Q))|(?(e)|(R|Q))(?31)(?(e)(R|Q))|(?(e)|(N))(?34)(?(e)(N))|(?(e)|(K))(?35)?(?(e)(K))))(?(e)(?<=(?!(?6)).)(?4)|(?6).(?5)\19))(?(e)(?=(?5)\20)|(?!(?6)).(?4)))(?<m>)|(?(+1)$)(.))+
)+\k<m>
(?!\X{0,70}((?(1)p|k)(?=(?3){7}(?2)?(?(1)K|P))|(?i:(?<E>(?!(?6))K)?((?(E)|((?6)[BQ]))(()?((?(-1)-)(?3){7}(?(-2)(?2)))+)(?(E)(?-4))|(?(E)|((?6)[RQ]))(-*|((?(-1)-)(?3){8})+)(?(E)(?-3))|(?(E)|((?6)N))((?<=..)(?2){3}|(?=.)(?2){5}|(?2){8}(?2)?)(?(E)(?-2)))(?(E)|(?&E))|K((?3){7,9})?K)))
```
[Try it online!](https://tio.run/##7Vhbc9pIFn7nV7SZnajbIMcSFynGmDIxW3ExITbG60wwRcnQGBUgKZII6xj/9fGcvgipkWf3ZR72YakUqL9z6/Od06flTIJAf5xMXn@Z0pnrUXT1sd8xxx@/XHTGt73Lwfju8mLwCdmFX1xvslxPKToNJiE1j@ZnhcncCdE4GI5QE/WL7c1m8VBZ//709HUwr2/m@BWTFm6dbTE@2hZwq3lEyLP5QjA84vuvzxY860QsW9ggQ93Rf462Q/1c/zYiXFAjIAHx0WGBFMjwuxc@jLaBImrZ5Nl@AeF1r98eba@YYesMQhIurZF7wyBb0F2RfzA7CIR1LvpAhEqFOcD898MLaV3hVpVJsG6QJEAVApDtkO1v39R6wS0zsYJAAXvAbzmGqNa@Y4s73vM1ZARwZe6xdUrPcKtOjohI2D3BLZYQBVl7e81cmhbhgFgnwr4QVgwp7GeFPS6qSlEvFXS5oMaCMUmXcEbZY@sUoh@wrRDGbpWZwLYEyR92WoJ185iJpbYgBxysznicksGKAf1QKpDS/QJg6I8D6InjsnX8IqoUbBf7JHO8y2q8FTScds6SGF0Qg7wDIrYetq9HrE8ECozrZOcJ6ybjDHZUItwEt/SqIGBn3ufm@uFWNbdfMjYV1abH@/K0eXTEvT9XXra86fmixhYmbwiWyc6HKdhlPlrvOuCwKxrGKrOWYeS/kv2DVSyjw6A5DkpGI3Mqo3jq@uxUZqHQ9R5VzPUBpc4qr3dWcL0YBfAYj2kY@iGe@F4UI37KD1c0ipxHSp4hzsnJBBTQ6SmSKHvkOPWmywYKabwOPWQ0XnIu2XriTylBzwUEH@5cehmatfqowWF3hjAfM@NHKk3HUgsz8zLCYk7dfvx03rcPiRSWUeT@pP4MJ9tF7xMkow@s8ijso6RT5EqIxztBxb/MkFvvsiyINFeO6@Ekr2AIpC6phwOiG6PmcQOtQadijmPkN49hmz7MTLGlm9v2zeBycDvojDtfB53eRecCbfOy295NZzDufL4a/N5ALN4jeC3sUhA1BEGwjhtIcMeYQochTdYrJ57Mx1MndqCeu2fhLaTRehmXRe6NJPzltw5HZrOIgtBfx5DTYzxXFA79H3QSg5WkBTJL4q8Cd0mx5P7matAnQVmafuv0v4wHnf7ny975oHNRRsDKOx5d/sqYxyRtiYMQKip5z3YV/5Z6mSSbubzHsHZiOp6F/mocOHFMQw@H0Da9299@kw5mfoh4n/5kZePkQhMu4W7Eollcryx4Jg3QMZKSJ5v8SRDIWGNj7d7TpNdEyg2Hx6NmUxtqWdPdaXjwnXAa8Uu1qMvPvff3PP1dfrIeiw01h8zQiJo83aPJGNoTEzawsqqc6UYjKjUNe58K9pFM4GhoGCNdM4CvEsKaremAVEfkENtwkzCioqE14jJH07VzDSTR0GQct7P8Z@sAHuqjg6ZWBqcP0BQLVe0lX5cVj2PW84GMNyOxFvrhLN1pck6VtAVBcVPk2NjlyjI6tGFilOMmkDaZhxgOwQpaLS6V3iJpRVeT4AkL@5K0Lxll6REmpYDgEstHYQ3a@EveE18s4WhYOd6vQaWSrQEk09SutHfvuACebQ21kHatoRMhCzIyg8u@C1kDvX@P2K0Ed4WzYUfbX/mx63vIiZCz3DhPkf59TamH8BwQz0d0NoORg0AjnlPBshs/IX/G1ysYSCSXVZwmxLYL9ctnLqagOjj4fMiOsIRYebGIJYx5PsLgXzpulLmy34Ey1ilMuDfKuqd1kNwWnX7/S3/c@/L5fPDxE1GmoFB9I9oLostI0lQqlYXRDBd/jRDmIIFTnDQM@U8Hge1IWOSCJE7vvV@n6F9MB27Qsgi655Pt5r80HTsAmX3ee5fej53PpAD7vtO9zjahG1OsTB85tI9Y2dgK6gXz3F8njAnr3I0xCynF6ZpkL1chhEtp984jagCvBK/DYbENey124atSRvaojCRyXeTBaynSg69qGVkqYilW7MsEtRTpCytbRWwFuRKxLBUxcwjssK4itRxSz1lZOcROkLskd/BjpMi18FNJkZ6InkHawspUkXqS@12SqaF4lrlnEJl7RUVMxbPMfQ@pKrFk7ns6Vg6xWazchkwYNmdoEK4pwgMYTqHvL9jgmhto4nh8VrEbYQMtDTDMrcJwCJdJGWldjcfl1RTItZZWUyA9Lc0xRSzJg0DYl634YV@m7ECB9DWedUVFDEXnSuN12UMSHhQdK4fUVSRhWLtLMrWS6HdJpkldBNLT0m5PESvZz12SV9IVKWIriMzLVpFKsue7ZIe2Ev1KS/s2Rao5HUPJS/qxRuqmOa2sK/7psLmMe9SFaytEC899nMco9kVXwK9TQ@xVFW1ATNnd9oSccL9HLKVu11o6J9KOqClVkpuoqx1hKXVr53jqZjtrV6W6gvSy1d4hFYU52X2mitQZKWn4riYPVIYndnw2cxjs6MGN5n6ANv56OWVv2/zaX4g/gOBtjU4WeY7qKkf2W6dm72TZOUZMhce2ls525dQYOWSv/@3cOVJPn9Sp59i3Vfat3Bmp5epRVfzIupq5etTVE6GeUHlG6mpv1946I@Yo13r221UU73STdRhSL14@IfZylytkGTneFGA3Eqdi6tPI09j/KtAfYAYSJ/5/sf9Xim0loy298EQ1o1xBaTLvHpb@ZBG9VUg7N9nqCpW9LE3tzLTZK2Q1dx@qt0Q32xBZuvfINXMFMHKTraLOsV0fpaTEzoKKRhfHQNCQv/iNXOqmumV@salKfM9pqJuVs1xS/vc4MA9vsRQFfhS5D0vKXodRTMNVxP5sevDX3pQV6sH/N/ljMls6j9GrvuSvurr9Jw "C++ (gcc) – Try It Online")
Pretty-printed, and partially ungolfed (absolute backrefs changed to relative, and capturing groups changed to non-capturing, or in some cases atomic for speed):
```
# Chess move validation regex (PCRE)
()? # decide whether to evaluate this as white's or black's move; \1 set = white, \1 unset (NPCG) = black
(?>| # subroutines:
((.|\n(?=.)){2}) # (?3) = for moving within the board, without wrapping to the next board, (?2) = (?3){2}
((?= # (?4) = assert that position of just-consumed piece is vacated on the next turn
(\X{72}) # (?5) = skip to the position of the just-consumed piece on the next turn
-))
((?=(?(1)[-a-z]|[-A-Z]))) # (?6) = assert that the piece at the current position belongs to the current player's opponent or is empty
((?5)(?(?=(.*\n)\n)[qnrb]|p)) # (?7) = black pawn that might be promoted, (?8) = .*\n
((?5)(?(?=(?8){8}\n)[QNRB]|P)) # (?9) = white pawn that might be promoted
)
(?>
(?>
# Handle squares that don't change (empty->empty or pieces that doesn't move)
(.)(?=(?5)\g{-1}) |
# Handle a piece that moves (and optionally captures an enemy piece)
(?(m)$) # allow only one move to be made per turn
(?>
(?(1)
(?: # white pawn
- (?=(?9))(?=(?3){8}((?3){9})?P(?4))(?(-1)(?=(?8){4}\n)) | # move 1 or 2 spaces forward
[a-z](?=(?9))(?=(?3){7}(?2)? P(?4)) ) # capture diagonally
|
(?:p(?4)(?: # black pawn
(?=(?3){8}((?3){9})? - (?7))(?(-1)(?=(?8){7}\n)) | # move 1 or 2 spaces forward
(?=(?3){7}(?2)? [A-Z](?7)) ) ) # capture diagonally
) |
# bishops, rooks, queens, knights, or kings
(?<e>(?6).)? # decide between scanning forward (<e> is unset) or backwards (<e> is captured)
(?=
(?i:
(?|
(?(e)|(B|Q)) (?&B) (?(e)(B|Q)) | # bishops or queens
(?(e)|(R|Q)) (?&R) (?(e)(R|Q)) | # rooks or queens
(?(e)|(N )) (?&N) (?(e)(N )) | # knights
(?(e)|(K )) (?&K)? (?(e)(K )) # kings
)
)
(?(e)(?<=(?!(?6)).)(?4)|(?6).(?5)\g{-2}) # verify that the piece moved, and optionally captured piece, are of the correct color
)
(?(e)(?=(?5)\g{-1})|(?!(?6)).(?4)) # verify that the piece moved is the same type and color at its destination in the next turn's board position
)(?<m>) |
(?(+1)$)(.) # handle the destination/source square that a piece moved to/from (only allow matching one of these per turn)
)+\n
)+
\k<m> # assert that a move has taken place
\n
# don't allow moving into check
(?!
\X{0,70}
(?:
# pawns (capture diagonally)
(?(1)p|k)(?=(?3){7}(?2)?(?(1)K|P)) |
# bishops, rooks, queens, knights, or kings
(?i:
(?<E>(?!(?6))K)? # decide between scanning forward (<E> is unset) or backwards (<E> is captured)
(?:
(?(E)|((?6)[BQ])) (?<B>()?((?(-1)-)(?3){7}(?(-2)(?2)))+) (?(E)(?-4)) | # bishops or queens
(?(E)|((?6)[RQ])) (?<R>-*|((?(-1)-)(?3){8})+) (?(E)(?-3)) | # rooks or queens
(?(E)|((?6) N )) (?<N>(?<=..)(?2){3}|(?=.)(?2){5}|(?2){8}(?2)?) (?(E)(?-2)) # knights
)
(?(E)|(?&E)) |
K(?<K>(?3){7,9})?K # kings
)
)
)
```
*-88 bytes by using non-atomic subroutine calls, thus retargeting from PCRE1 to PCRE2*
The version above has been modified not to allow en passant or castling, but the full project is currently at a state where it validates every type of move, starting at the initial board state (which must be the standard chess starting position – Chess960 is not supported, yet at least). The full rules of en passant and castling are enforced.
[Here is a sample game validated by the full regex [regex101.com]](https://regex101.com/r/GUZl7X/6).
An invalid move will result in every subsequent board position not being matched/highlighted. Checkmate/stalemate detection, and thus detection of who the winner is (or if it's a draw), is not yet implemented; that's why the final board state in this example is not highlighted.
[Here is a C/C++ program that converts algebraic notation into the format recognized by this regex.](https://github.com/Davidebyzero/chessconv) The algebraic notation currently must be put in the form of an array inline in the source code, with separate strings for each move, but reading it as single string from stdin or a command-line argument, with the entire sequence of moves separated by spaces and dot-terminated move numbers, is planned.
I also started on a regex that validates a full game purely in algebraic chess notation, with the standard initial position being implied. All it needs is an empty "scratch board" appended at the end of the input (after the list of moves). I'm pretty sure it's possible to implement this in full, and plan on finishing it sometime.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 693 bytes
```
(b,M,[c,p,x,y]=M,m=Math.abs,J='some',F=(C,X,Y,W,T,Q=P=>P[2]==X&P[3]==Y)=>W.filter(([i,j,k,l])=>i==C&j==(T||j)&[B=m(H=k-X)==m(V=l-Y)&!W[J](([I,J,K,L])=>(K-k)/H==(L-l)/V&(k>X?K<k&K>X:K>k&K<X)&(l>Y?L<l&L>Y:L>l&L<Y)),R=!(k-X&&l-Y)&!W[J](([I,J,K,L])=>k-X?L==Y&(k>X?K<k&K>X:K>k&K<X):K==X&(l>Y?L<l&L>Y:L>l&L<Y)),B|R,k==X?!W[J](Q)&(l-Y==1-2*(C<'E')|l-Y==2-4*(C<'E')&!W[J](E=>E[2]==X&E[3]==Y+1-2*(C<'E'))):m(k-X)==1&l-Y==1-2*(C<'E')&W[J](E=>Q(E)&E[0]!=i),(k-X)**2+(l-Y)**2==5,(k-X)**2+(l-Y)**2<3]['BRQPNK'.search(j)]))=>x>0&x<9&y>0&y<9&!b[J](([i,j,k,l])=>k==x&l==y&(i==c|j=='K'))&F(c,x,y,b,p).some(e=>!F(c<'E'?'W':'B',...(W=b.map(E=>E[J]((a,i)=>a!=e[i])?E:M)).find(Z=>Z[0]==c&Z[1]=='K').slice(2),W)[0])
```
[Try it online!](https://tio.run/##7Vddj9o4FH3nV4R5iO2pSZsASRbhIDGi6k4YBKhqYNJIDTSzBcKHJqia0bK/fdbOB8nF9L0PfbHRiX3vPeceO2Ed/gyT5fPqcGzs9t@jtyf2hhf0gfpLeqAv9DVgD3TLHsLjDy1cJPSeoWS/jRD9yPAdndE59ehnOmFj5ox9I2Bspo79Jp/nhDme9rSKj9Ezxv6KrumGxgFHV4zdqWvG8OfTaU1Uv8@2@BPbNGaE8V9fWNyYE7Xu@fcB3/c3vacuHYp92G1syPtPfOOwEZP3X1S8cWY9t7tRXWfWcR0@d2dExbEz7w27sTp05p2hw@funBA6ZXXMc6jqr8Lzh70hr/t62I4rqP0idv80pRv@vJeFnYgiGnPG9IZxi@@6aIDIKQWMRqsA8hIGzBnkug0y3d5VdhHS2eJMGV29DKkWASZ4QPjuD0GdrQhN19/eGu9EDeIHY20Z7DYDH/Wnk/HIRVoShc/LH3hNAsKFeHE@qC/dv9RXPr/yub7ItKq0kJN9UWPGXlXMu7k88W4il5erfsRLYRq6oAeiCaPgiDl1joqKe8hDHdRHVNM07LGFtg0PmQAifkhXPHJYZ5G/Ckhv0HkghPtn9x0/MueRs@OJ1EdfD7JcWhKvlhE2CPUIf0jejlFyvAuTKFGY8u0J@/5N/4YqNy4fmlSxA6rkyIQPOlXaJTLiQ4sqFkQssEsMBl9WItNslw0RGyDjLJcFEUNCeIUmRNoSYkq7LAmxC8QruPM4eolMsjjNEhll2StIP9tlQMQsuHsFUx1EzrlXkJx7EyIGiJxzv0BaIFfO/WKNJSG2yCUVZASkVhN2EMZTuHPSYGmLMmSCyhZlyAiVhZeIlZPLEDHYII4YjNxWGTJFKZUmRHSwZoxSsS@QghxYY0mICZFCNn7McqZWkd0rmBZiZ8gIlRYuEauoxyt4Fa0uERsgOS8bIs2iZq@o0AbZx6g0Y4m0pDU64JXHsQJYdCqr1GoLyD9B5RkuG9sGYuexTNhYC8jfl@i6VYOcxTYBMqo27Yw0gQC5iQyImIJbmd5Fudmv0TUhXfuajy@8bkvkDCBJH5VXKPCxLiEXjrQlZ8PzkK8xJSFtKKQlubYtSdsCcfIWGZK0JvQoPDO5a03otvY11xqB5CL7T0N@o4ZYVy8EW7oQTCDJqEq3XzmkFw1pSW8DeEe61cZWZbsQyZCE1KULoQmP/9kP115sukTOgEWlFzdclFZFvtVq6ScU/xMgPqHOn1NacohXR4y@7r7ukEi5f1bwcr9LjsqSr1X2T8p5H1H@rSmKeLiPIy3e/4Ojn2GMxTpCav@9/Q8 "JavaScript (Node.js) – Try It Online")
I sought out this challenge with the aim of combining CodeGolf with a project idea for a chess app. I realized that most of the functionality of a chess app hinges on the ability to validate a chess move, and while the challenge's input format does not explicitly include *which* piece in particular (which white bishop?) is moving, I still found this fun to write. My original working code was 1200 bytes, so I'm proud I managed to cut it down to 693. It takes input in the same format as the spec and outputs 0 for invalid, 1 for valid.
## Explanation
Really simple when you get down to it. We call a huge function `F` which returns the list of pieces that can move to an `X,Y` coordinate with color `C` and type `T` within a board `W`. This is called to retrieve the list of eligible pieces based on the `[c,p,x,y]` input, and again to determine whether there is check or not. Here we do not call with a type parameter as we want to consider every piece.
The large list in the `filter` function body is simply a list of booleans which check Xs and Ys, the code is too unreadable for me to explain how that works... but it should be easy to figure it out by reading the code. Notably, all a queen needs is either bishop eligibility or rook eligibility. The pawn code was what took the longest to write.
Then we have a simple `some` call which operates on the filtered list, checking if there is any piece where, after recalling `F` with a slightly modified board (that particular piece is moved to the target), we get an empty list (no eligible pieces of the opposite color) or in other words there is no first element.
Here's an expanded version of my code (thanks Emanresu A!):
```
(b,M,
[c,p,x,y]=M,
m=Math.abs,
J='some',
F=(C,X,Y,W,T,
Q=P=>
P[2]==X&
P[3]==Y
)=>W.filter(
([i,j,k,l])=>
i==C&
j==(T||j)&
[
B=m(H=k-X)==m(V=l-Y)
&!W[J](
([I,J,K,L])=>
(K-k)/H==(L-l)/V
&(
k>X?
K<k&K>X
:K>k&K<X
)
&(
l>Y?
L<l&L>Y
:L>l&L<Y
)
),
R=
!(k-X&&l-Y)
&!W[J](
([I,J,K,L])=>
k-X?
L==Y
&(
k>X?
K<k&K>X
:K>k&K<X
)
:K==X
&(
l>Y?
L<l&L>Y
:L>l&L<Y
)
),
B|R,
k==X?
!W[J](Q)
&(
l-Y==1-2*(C<'E')
|l-Y==2-4*(C<'E')
&!W[J](
E=>
E[2]==X
&E[3]==Y+1-2*(C<'E')
)
)
:m(k-X)==1
&l-Y==1-2*(C<'E')
&W[J](E=>Q(E)&E[0]!=i),
(k-X)**2+(l-Y)**2==5,
(k-X)**2+(l-Y)**2<3
]['BRQPNK'.search(j)]
)
)=>
x>0
&x<9
&y>0
&y<9
&!b[J](
([i,j,k,l])=>
k==x
&l==y
&(
i==c
|j=='K'
)
)
&F(c,x,y,b,p).some(
e=>!F(
c<'E'?
'W'
:'B',
...(
W=b.map(
E=>E[J](
(a,i)=>
a!=e[i]
)
?E
:M
)
).find(
Z=>
Z[0]==c
&Z[1]=='K'
).slice(2),
W)[0]
)
```
[Answer]
# [Python 2](https://docs.python.org/2/) (with [python-chess](https://github.com/niklasf/python-chess)), ~~141 138 134 133~~ 132 bytes
Without doing any of the really interesting code - but maybe this can compete with golfing languages or (dare I mention it) Mathematica?
Note: [python-chess](https://github.com/niklasf/python-chess) is a [Pypi](https://pypi.python.org/pypi) package install it on Python 2.7.9+ with:
`python -m pip install python-chess`)
```
import chess
a,p,n=input()
S=chess.Board(a+' - - 0 1')
for m in S.legal_moves:1/(m.to_square!=n)**(`p`in`S.piece_at(m.from_square)`)
```
A full-program accepting input of three items:
1. the beginning of a [FEN record](https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation) - the string containing the first two fields. This is to define the board state AND which colour is moving (since this is the information in the input in the OP, whereas fields three through six are "fixed" by the OP hence should not be a part of the input)
2. the piece-name attempting to move (as given in the OP -- one of `PRNBQK`)
3. the square to which the named piece is attempting to move where `a1` is `0`, `b1` is `1`, ... `a2` is `8`, ..., `h8` is `63`,
The program [outputs via its exit-code](https://codegolf.meta.stackexchange.com/a/5330/53748) given valid input:
* `1` if the move is a valid one (the program raised an error - due to division by
zero);
* `0` it it is not (the program exited normally)
(Don't) **[Try it online!](https://tio.run/##NY/BTsQgEIbvfQo8AWsXHPZgNOmlVxOD26MxLa6sSywwC6zGp6/YaCYzyffnm8OP3@UUg1qcx5gKQYdNXeGNC@yZupCLmWfaEoqruD2cbM70hf8/rNyYFtvQuYCXwngzdGsq@mjSGzPXlGzr3BCgvDnGRDxxgQxitu9mHn38tPkeJPOixDGfLybZqy7wzYZNOLkwDQKdPdjRlKocU/R/Ep/4slD1kVRIEhECIKJUCLiT51sJr6ChV1LDo3pSEnQlrbXc7x7Unnz9Vurrgbsf "Python 2 – Try It Online")** (because the python-chess package is not installed there and TIO does not allow internet connectivity so the pip-install code in the header wont work).
Note that the power operator in Python makes `1**1 == 1**0 == 0**0 == 1` but `0**1 == 0`
...hence `1/0**1` raises a division by zero error while `1/1**1`, `1/1**0`, and `1/0**0` all succeed
(...and that in Python `False` and `True` equate to `0` and `1` respectively).
[Answer]
# [Python 2](https://docs.python.org/2/) (with [python-chess](https://github.com/niklasf/python-chess)), ~~127~~ ~~125~~ 124 bytes
```
import chess
a,m=input()
S=chess.Board(a+' - - 0 1')
for l in S.legal_moves:1/(m!=str(S.piece_at(l.from_square))+`l`[17:19])
```
[Try it on replit.com - test cases](https://replit.com/@Davidebyzero/cgcc-148587-python2-test)
Jonathan Allan never responded to the golf optimization and other comments I provided under [his answer](https://codegolf.stackexchange.com/a/148609/17216). So I'm finally doing that here. This program is based on his.
Input consists of two items:
1. The board state, in the form of a [FEN record](https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation). As per the challenge's specifications, this is abbreviated not to include extra information about the state (castling, en passant, halfmove clock, or fullmove number) but it must include the color whose turn is next to move.
2. The move whose legality is being queried; this is a 3-character string. The first character is the piece type; as in the challenge's input specification, this is one of `PRNBQK`, except that a white piece must be in uppercase, and a black piece must be in lowercase. The next two characters are the destination square for the move. This is given in standard chess column,row format, where the column is one of `abcdefgh` and the row is one of `12345678`.
Python 2 automatically runs `eval()` on `input()`, so the input is taken in the form of comma-delimited Python string literals. Examples:`'rnbqkbnr/pppppppp/8/8/8/5N2/PPPPPPPP/RNBQKB1R b','nf6'`
`'rnbqkb1r/pppppppp/5n2/8/8/5N2/PPPPPPPP/RNBQKB1R w','Pc4'`
[Here is a C++ program that converts the test cases.](https://tio.run/##7VdNc9pIEL3zKzqknEEG7yIJJJUJSYXDXlxF2dlUcWAplxBjIyMkVhL2Jil@u7dnRkJqjZzzHpaDbD/153s9PTg4HK4eg@D19X0YB9Fxw@FjmGR5yv39p06QxFkO6ySJgD/70X0YH4454GcKeXrkk7pB4X4fJFGSng3COIe9H8Y9A352hGeWb66vMX4YP4IMN5HwA/r0hPGP6XCijB55HoUx78k/gjAeKHtjUoYSn/BBuCG8HK6mU7Zk9ZelwQ8D0CLY@mmP/RUzY4JZzAkxEy@xDz/dLL1Lb4X1/xyeGiayV2l4mU1l0t@Ce2ylZ/Qb0WQ3k0nWn5pesyDxUYl6zGNX2dIcrYxLD/rQw9/N1RUzmSEKyJbuSqDMZ1fsCzMu8b0lmpxhB1pI0Sf6O6t3UzZAFtao4I6anTq0BhRtHfnB7j5P7vfJM5c5LVOlaKHnEPKgMHJkZdT7MxSVwjUMjRZ/NHzZ8pQvrb4pGZaKZEt7uOqrLrFzY4DxbXs1gCb/osNqCuuSsiYh52l6EtP09NHDR7/fpoQI@gTvplhxFfD3NoLPMUMRM8SYbfHOzQbYoJL5SYobriatxqKA4K1I4lNWFeDY9vthe5QT8Cjjv4giCo@n4QQ2iYwCL9sw4ighKXE6HcKHD6I5TIbmV/Hk7YhYeFwjbcj6sfFGdZ1fIydNZ7JMMAmui/yh14WLoDsAbezWYuTYS1O1wqu2uT5Dlw2AXQQX2UXG4P1F1kVPEVYAGFqO@KCxy9BLmLUEUt5dnNlytnF6kUnbq5Wiujt1Tq@vy2V3hlm6N/iwB@DhlBfIHT7MAYwrZI6P0QBcirjESzwsNKuQr8rLo4hHkFuVy6WIpSFYoUORsYY4mperIV6JLMreMY5ZIXcqjl0hc5W9hsyUl0URp@x9UXZqkshF7zWk6N2miEUiF703kBHJVfTesHE1xBO5tIIsXH@f4BvekND7tuWQJskOkhi2JgR@DHKucd@84NlEmBudznKJOxkn7obJvFJNhdyxSk2FzFnVY4W4BQ8KEQ@PxBEPq5hAhXxlsmubIiaxuWVSlwZS8kBsXA1xKFIyzBZlp26ZfVF2WuqikDmrpr1C3LKeRdlXORUV4hGk6MujiF3WvCgr9Ej2W1bNbYWMNBuT9FXEcVe0aEmrmIo/fLHJe3Me5rhQYBeHj9sc94uaCvzpj@EhTfYg9w2g0Xfw0@aMuES3O1btiWoixkSlogiHToRLdJtpPN3UJ@uskkOQeV3tM2IT5orpsyjiCFKq9DesOFA1nsTxwbss57AOs21ygJfkGG3EtSSogZ36nol3Mg92OkcO5chrOzWNk@VpjFiExxmrdjs5NaaGNObf084RPX2FjaOx71H2Xe2MjDU9RiROoaul6eHQE0FPaHFGHDrb47YzYq200fPaVfz7yDnKdUxTHufRd9j6mS7kAPx4g3CYqVOxSXgWsxxvfP6MbvjGz/8X@78itluuturCU2pmmqC83HfrKAl2WZuQnrbZHELlvE7TrLZtGkKOtPuQ3hI39YGo090g19IEMLXNZtM9dp6jipTc33E16OoYKBr0i9/UWrdoyfJio0ay5irVn3s/irj8VxaZ3/uY7ZBkWbiO5DdfyHm6zyB5wH9fjvFGCLVO/jH@BQ "C++ (gcc) – Try It Online")
The program [outputs via its exit-code](https://codegolf.meta.stackexchange.com/a/5330/53748) given valid input:
* `1` if the move is legal (the program raised a `ZeroDivisionError`)
* `0` it the move is illegal (the program exited normally)
[Try it on replit.com](https://replit.com/@Davidebyzero/cgcc-148587-python2)
Can't [Try it online!](https://tio.run/##HYhLCsIwFAD3PUVcJUFtfFXxA910K0i0S5EaNWoxn2cSBU9fiwwDw@A3Pbwruq616EMil4eOMVMjW7YO34nxrC7/L6@8ClemhpSMeyYEKM9uPhBDWkfq3Oi7Mo31Hx3XIJgdlDEFVufY6otuVGImvwVvm/h6q6A5H57M6QCLNayOvOtocOfXE1wQiFj0iqWYyamASs77lLLYoJRiv4UdVNs9OdMRxTvQHw "Python 2 – Try It Online") (python-chess is not installed on TIO, nor is internet connectivity allowed, and even if it were, [Pypi](https://pypi.python.org/pypi) and the latest version of python-chess no longer support Python 2)
python-chess v0.23.11 was the last version to support Python 2. To install it for use with this program, you may run the following git command:
```
git clone --branch 0.23.x https://github.com/niklasf/python-chess.git
```
And then symlink, copy, or move its `chess` subdirectory to the directory from where you are running this CGCC program.
# [Python 3](https://docs.python.org/3/) (with [python-chess](https://github.com/niklasf/python-chess)), ~~134~~ ~~132~~ ~~121~~ 120 bytes
```
import chess
b,m=eval(input())
S=chess.Board(b)
for l in S.legal_moves:1/(m!=str(S.piece_at(l.from_square))+str(l)[2:4])
```
This is a straight port of the Python 2 version. Python 3 dropped support for the backtick alias for `repr`, so `str` is used instead. We can't use `str(l)[2:]` because an extra character is appended to `str(l)` in the case of pawn promotions, specifying what it is to be promoted to.
We save 11 bytes by using the latest python-chess, more than making up for the 7 bytes sacrificed by using Python 3, because python-chess v0.27 [added support for omitting the last 5 parts of the FEN string](https://github.com/niklasf/python-chess/commit/65e872995c6380522d3839e60a7235f06899fced?diff=split). This still accomplishes exactly what the challenge requires – it defaults to treating castling and en passant as impossible moves. (We still need to include the current turn, because otherwise it defaults to white's turn.)
[Attempt This Online!](https://ato.pxeger.com/run?1=LY7NisIwGEX3fYrMqgmjDek4UIRuuhUktstBSuqkWszPZ5KWmWdx043zTn0bO-riwoUD597rH_yGkzXjeOtDu8ymn06DdQEdTtL7qFnoXA5C4c5AHzAhUZU_SFJY4b5xQ6LWOqRQZ1CVKHkUqtZ2kH7NKNZvuQ8OVwl08iBrEbBKWmd17S-9cJKQ93-syFe6Xu3Jc_91Y5yy2JnmcmbGUQBI59CMrvgHZQX_nCvn6QY4p-WW7VixLVETL2I4svgpuAM "Python 3 – Attempt This Online")
[Attempt This Online! - test cases](https://ato.pxeger.com/run?1=nZS_b-M2FMfRdvNf8eoOklCdGFKxEzjQ4qFLAEFxbksPgmjRliCZpEkqjnN75-5dbmn_p7uxf0kfLecu7bVLbRgC33v8ft4v-bc_9NE1Sn74-L7daWUctCq2RxuPp77lk1psoGylHlwYLWDbK1714IR1N2CEG4w8HSZlyYe2d620ZZmcwiE737sBpYUMpz7OJvo4jaeHaZQcTOtEaKbT6e-D27y5_vh0TmHdCGsnPN5l4rHqwzM7mtxnJ0-yVJWpQx5NNspAD62E-6QX26ovd-pR2AUl4e77zDoT3ie6FWtRVi7sk41Ru9Luh8qIKPrRu_vogS0u30Uj_9M3EebyQBdv6LvoBrALia5cg8VYYVx4EUMQoP05uziBnQf7IOvqVi4mgJ92A88L0KaVmPCLxT2gYJYFP8tgAb4r7sEjTm7fEm8ZD-Y4yviP9u0rx46U5bl50-izf0R9HlNiRK-qOtRjhHhaC-1eqZ1SoljCn7_8GsTgYhCyzqZnQdFb8c_gi_8Kfs7ozdixD5---zZgnWHSEK2ppFprwjTVKdlfEcppQZeMFDRnd7QgtMAj_sgqvWUrOKBysGpYAD_AWzMICN82AoxSHSgJDYV1JcEPFLDbB5w4mkU0CVYspx3lZE9XVLOCXCLNcKTmlBRMXxLJDC1uKWF3eCzIciaXIyyvZh72U4XVQpiL1jXCQCfbbePAqRGGz2oGflfggG40NOIIfmcmAb8ic06JTPOUzLAyup8TlqcdJVinRNvdLQXuUV2TvkL5wg4Nbjvw1jZKw0ENfQ3-HUF16Fq59cuE273uEMN4iunPpSRmucpZp8mVJunqkqQ63ZMlZ0VxR4nBLEaYFNf_CtsPQqDqYIyQrj9CU9mveTFUskZza8f6ayWsDBwugXjEa-ip3P_JaTv7-2BHqP2KK14GwHu17uwLby5xgNIzrwlbsj3DZz7vCM3nhDOOCzVyOH-1QK7qxFji2IBRGdWuyZfvDLVmHb0d7--39Mv9-13V9_6NPGW4q1BCK2tb3ovYJ-6E2VlQG-BqkLUviKun87_HXw "Python 3 – Attempt This Online")
To install the latest release of python-chess:
```
pip install chess
```
# [Python 3](https://docs.python.org/3/) (with [python-chess](https://github.com/niklasf/python-chess)), ~~158~~ ~~152~~ ~~141~~ 138 bytes
```
import chess
b,p,n=input().split()
S=chess.Board(b)
S.turn=p<'a'
for m in S.legal_moves:p[p+n==str(S.piece_at(m.from_square))+str(m)[2:4]]
```
The [**132 byte**](https://codegolf.stackexchange.com/a/148609/17216), **124 byte**, and **120 byte** versions of this program have a problem. Their input is not bijective to the input specification given by the challenge – the color to move next must be given in two places, and if they disagree, the move is considered illegal.
This version solves that in the most natural way, by taking the color of the piece to move in the same place as the move itself is specified (i.e., whether the the piece identifier is in uppercase).
Also, evaluating the input as Python code is bad; there's a reason that was dropped in Python 3. So this answer uses `split` instead of `eval` on the input.
For optimal golf, the piece type and its destination coordinates are to be separated by a space in the move to be queried. Examples:`rnbqkbnr/pppppppp/8/8/8/5N2/PPPPPPPP/RNBQKB1R n f6`
`rnbqkb1r/pppppppp/5n2/8/8/5N2/PPPPPPPP/RNBQKB1R P c4`
[Here is a C++ program that converts the test cases.](https://tio.run/##7VdNc9pIEL3zKzqknEEG7yIBksqEpMJhL66i7GyqOLCUS4jByAiJlYTZJMVv9/bMSEitkXPew@owxk/9/bp7wD8cbp58//X1fRD54XHN4WMQp1nCvf2nlh9HaQarOA6Bv3jhYxAdjhngM4GNF6Z8XJXI9R/9OIyTUiKIMth7QdQx4GdL6KbZ@vYWPQTRE0iDYwlvUKkjhH9M@mMl9MSzMIh4R/7jB1FPyRvjwpR4go1QQ3jRX04mbMGqLwuBHwaghL/1kg77K2LGGL2YYyImXmIiXrJeuNfuEhP42T/XRGSyUvA6nUinv/mPmErH6NasyWzG47Q7Md16QOJRjjrMZTfpwhwujWsXutDBz@byhpnMEAGkC2cpUOaxG/aFGdf43hJJTjEDzaTIE/Xt5bsJ62EVVsjhjoqdWzQGZG0Vev7uMYsf9/ELlz4tU7loKM8h4H4uZMvIqPZnyCOFW@gbDfooeNryhC@srikrLBlJF4P@squyxMyNHtofDJY9qNdfZFj2YZVSVi/IpZueRTc9f3Tx6HabmBBGn@HdBCMuDf7eVOCLzUDYDNBmk71Lsj4mqGh@luQGy3GjsAjAf8uSeIqofGzbbjdotnIGjuP2Cysi8GgSjGEdSytw2gYhRwpJiJNJHz58EMmhMxS/icZvW8TAo0rR@qwbGW9E1/o1ctZ4JtsEneC6yDadNlz57R5obbcSLcdOddZyrcru@gxt1gN25V@lVymD91dpGzWFWQGgadnivdoyQy0h1mBIabexZ4vexu7FSg7cSigqu3Pr/Pq6WLSn6KV9h8egBy52eY484GH2YFQiMzyGPXAo4hAtcVgoViJflZZLEZcg98qXQxFLQzBCmyIjDbE1LUdD3AKZF7mjHbNEHpSdQYnMlPcKMlVaFkXsIvd5kalJLOe5V5A89wFFLGI5z72GDImvPPeajKMhrvClBWTh@vsE35IjTuC3LYckjncQR7A1wfcikH2N@@aEs4kwN1qtxQJ3MnbcHZN@JZsKeWAlmwqZsTLHEnHyOihEHC6xIw4r70CFfGUy6wFFTCJzzyQvNaSoA5FxNMSmSFFhNi8ydQrv8yLTgheFzFjZ7SXiFPHMi7yKrigRlyB5Xi5FBkXM8yJCl3i/Z2XflshQkzFJXrkdZ0mDlmUVXfGH@OIEnRkPMlwosIuCp22G@0V1Bf71RrBJ4j3IfQMo9B28pN4jDuHtgZV7ouyIEWEpD8KmHeEQ3qZane6qnXVhySbIrMr2BRmQyuXdZ1HEFkUp3d@xfKAqdRLjg3dZxmEVpNv4AKf4GK7FtSRKAzv1PRPvZO7v9BrZtEZu09TUJsvVKmKROk5ZudvJ1JgaUut/V5sjOn25jK1V36XVd7QZGWl8DImdnFdL48OmE0EnNJ8Rm/b2qGlGrKXWem4zi38fOUe6jknCoyz8Dlsv1YnsgRetEQ5SNRXrmKcRy/DG5y@ohm@87H@y/ytkO8VqKy88xWaqEcqLfbcKY3@XNhHpapvNJqWcVcs0rWybGpFD7T6kt8RdtSGq5a4V19IIMLXNNqB77NJHZVEyb8dVo6sxUGXQL35TS92iIcuLjQrJmEtXf@69MOTypyxWfu@ht0OcpsEqlN98IePJPoV4gz9fjtFaELWK/zH@BQ "C++ (gcc) – Try It Online")
Unlike the others, the error used to trigger an exit code of `1` in this version is `IndexError`, by attempting to access the second character of a single-character string.
[Attempt This Online!](https://ato.pxeger.com/run?1=LY7BisIwGITvfYrcbFETUhVEzKVXQaI9ipRUUw02ye-fVNhX2FfYSy-77-TbbHf1MMwwHwPz9QMf8epd3393sZkun5_GgsdITlcdQlJPYOKEcdDFNKMBWjN4Uop_Sguv8JzWQ0Fjh07AeqRGSeORWGIcKWmrL6qtrH_osIIDjJ0QIWJaUjD6pCsVU0sb9LYK906hzrLxH7bZIV_Nj8fXo_ex_jlDV99v3CEDgHwQW7K5nDFeyMUQpcw3ICXbb_mOF9s9AXLhr-0v "Python 3 – Attempt This Online")
[Attempt This Online! - test cases](https://ato.pxeger.com/run?1=lVGxbtswFERWfcWDFkmIIuZRtmPI1aLVgCDboxsIYkzbgmSKouimTvcOnbp3ydL-UzL2S0pZRloU6FASAvHeO94dT99-yJPeN-L55VN5kI3SUDZ-d-r8oapLZm34FvJSyKN2vQh2dcOKGjTv9AwU10clzoWV5-xY1roUXZ4HZzjEl3szaCQXrt3jukCebN9-tL3gUZWau8q27e9Hvb2Zvny5WHjY866zmC99EV-Eg07WpTmtVXyeBklTqI3LTCPoPcTynVM41rZRcIBSwCqo-a6o80PzgXeRXMtrEcedVu4qkCV_4Hmh3UOwVc0h79pjobjnXffjg7em0ej-fnD0euUZd2uMbvDem4HJJZCF3pvndVxp99YHxzH9p_j2rKx75R7U6U0pIgvMKrfwFIFUpejdXzp6bQjj2HkvnAj6nPS6lziP-5D6zlCo00DTL9kHmg8Z5fklTtt7mw9Sbz8uULxuio0rBwT_-MCl_oPtbAnNE35-_ur4oH3gYhPbF0Jed_xv8O2_wE8xzobEnl-vElopKhSREgVKKQmVKEPS3hFkmGFCSYYpXWBGMDOl-cgynNMlLGFPrSVNsUJGWlyipBkZmauKGYoUSUbliAiqMJsjoQtTZiQZiwRSKMYWuyMThkSEaUjGRgXbCaFpWCExmsL0FnOECvahRVloCCZCEJUsU1pJcidJuByRUIYtSRjNsgUSZYhAAJ_-H343tibC2BP9nSmhCW2pOdNJRTCdEEaZeTswYNSakt97bFDjCufQwg6HLH8B "Python 3 – Attempt This Online")
# [Python 2](https://docs.python.org/2/) (with [python-chess](https://github.com/niklasf/python-chess)), ~~294~~ ~~278~~ ~~276~~ ~~270~~ 197 bytes
```
from chess import*
b,m=input()
S=Board()
S.clear()
S.turn=m[0]<'a'
for P in b:S.set_piece_at(P[1],Piece.from_symbol(P[0]))
for l in S.legal_moves:1/(m!=[str(S.piece_at(l.from_square)),l.to_square])
```
Even the 138 byte program's input is not quite bijective to the input specification given by the challenge, in which the board's pieces can be listed in any order.
In this version, the board is provided as a list of pieces, as in the challenge's specification. Each piece's type (one of `PRNBQK`) is specified in lowercase for black or uppercase for white, instead of providing the color as a separate element. The coordinates are specified as single numbers, where `a1` is `0`, `b1` is `1`, …, `a2` is `8`, …, and `h8` is `63`. Following this list is a comma, followed by the move to be queried (in the same format as the pieces already on the board). Examples:
```
[['r', 56], ['n', 57], ['b', 58], ['q', 59], ['k', 60], ['b', 61], ['n', 62], ['r', 63], ['p', 48], ['p', 49], ['p', 50], ['p', 51], ['p', 52], ['p', 53], ['p', 54], ['p', 55], ['P', 8], ['P', 9], ['P', 10], ['P', 11], ['P', 12], ['P', 13], ['P', 14], ['P', 15], ['R', 0], ['N', 1], ['B', 2], ['Q', 3], ['K', 4], ['B', 5], ['N', 21], ['R', 7]], ['n', 45]
[['r', 56], ['n', 57], ['b', 58], ['q', 59], ['k', 60], ['b', 61], ['n', 45], ['r', 63], ['p', 48], ['p', 49], ['p', 50], ['p', 51], ['p', 52], ['p', 53], ['p', 54], ['p', 55], ['P', 8], ['P', 9], ['P', 10], ['P', 11], ['P', 12], ['P', 13], ['P', 14], ['P', 15], ['R', 0], ['N', 1], ['B', 2], ['Q', 3], ['K', 4], ['B', 5], ['N', 21], ['R', 7]], ['P', 19]
```
In this way, the input is fully bijective with the challenge's specification, but optimally golfy.
[Here is a Python program that converts the test cases.](https://tio.run/##7VZNj5swEL3nV4y2B5OWrgokgCptD5G2l5XS3bZSDlEOJHEKCmBqnE33129tbMdMvD@gh@bgwMPMx3szY7oXUbI2eX2tmo5xAZxOJnt6gB1rnykXjxXd0aBT6/TzBOSPU3HiLawHbB1toDqAvv60ubsjKwK07inYx7c1O1MeTEPQVtbx5mM0hQ/2NlG37/PNZHIuq5pCpL0I/qIv1G/LCr6HO6DPRR1UbXcSwXR6edqwZxrKeJuGtkLuMhtu@66uREDg7gsQvNuaUtdTz0td9SJoii4YUxDqx1PPEOIJG@x41YqgFzzQ734gIQlB3Q/7QiDvzL0JfmTdJDHc0z872gm4//b1nnPGR7xwWhxfX9frm8VNCDcPcklCyDchGORJLlEIc4cs5TILIcNIht5SSyy3OeS7fivHSI6QR@0rw0jsITLCFCNzD0m9tzIPyS2ysrlLO5FDnrSdxCFL7X2ELPRbMUZSm/vKZhohyyb3EWJyTzASI8sm9ytkhnyZ3K/2ZB6SK1@bCY4n3qhS/8lPFIKfJQXO2BFYC2UEu6LV9Xpg/KyqnLWyTifrNVnICiQPZHA7iKmRJ@LE1MiSuBQdkhkaNKKWHNlRS2wKUCPfyZB0gpEI7XkkgyxXiKUB7ck8JMWIJVgOJpNpZr2vbKZWFo0siSt2h2Q2npXNyxaFQ3KEmLxyjCQ25pWNMEfeH4krW4fMvD0RysvYyVRRuJgHVlVRfC3USA6WtBIl5XBsq1@lAMF0Ucj/Yg4Hzho4y8cSKOkLFPy6RDIk2xNxU8IVxByJZIJIcUFkSLaFR9PDuLAuIqUIWY7FviAJIs4UX4yRVJGiaLrkNXTTiCbVPPIwEhS2VV@yDs7sVO9BDmTFDByr9pecz7Ar6e7oU5RiivK3euaqr3KPkBjRuCBusKOeiTzkqvpzr4tw75k9qUd@jsnPvA6Ze3LMkB0ja@zJkeJ@wP1pOiTFlT1/q0NiJ6KJJ39bxN8nSqVaJ87lEVu/QFn0vo4hFO1ewlWve2LPaN8SIc9w@qw@K0RZiP9a/yNaZ3auucNOi9l7elI77LY12x37t3TMvbGWIiaXY5YWo1FzpePMOwvxCfEwrocx21fcxh7/kTfWEjTELlXkOBHFkeoy102gWfDP/MjLPMYRD2faxdMlYufpR1PUNe2F5r0ppLOO9X21reVHs5RDUN70wA7yA/rU7pVMW/Zn@hc "Python 3 – Try It Online")
[Try it on replit.com](https://replit.com/@Davidebyzero/cgcc-148587-v3-python2)
[Try it on replit.com - test cases](https://replit.com/@Davidebyzero/cgcc-148587-v3-python2-test)
Can't [Try it online!](https://tio.run/##Rc5Bb4MgFAfwu5@CnZTFOLWF2mZeel2yuHk0xKilqxmIBVzST@8EG7z9eLz/e2986JsY0nm@SsFBd6NKgZ6PQupXrw153g/jpAPolflZNPJiFHWMNtJKT3LIeRWTd7/xvauQoAD9ANpTGSmq67GnHa0bHRRVQsLCvCKzp1YP3gq2lGMCoc0xkysjRn8aVnPxR9UpeQv4S14pLYMycqPYc8J9aiSFMGSRFs8XgfNcVb70Q4AwCUHlD4YHy9Yws7wbHi1/F@LY9eLU0kzAO8tx4T7beHRE8catF@03IsdkbSgW7tbLzgtT5Kopdsyc1l0fJp@6YrLfuOa/F663fJqi1ZfZ5BYh94td4kDcdZj8Aw "Python 2 – Try It Online")
# [Python 3](https://docs.python.org/3/) (with [python-chess](https://github.com/niklasf/python-chess)), ~~309~~ ~~306~~ ~~290~~ ~~288~~ ~~282~~ ~~271~~ 203 bytes
```
from chess import*
b,m=eval(input())
S=Board()
S.clear()
S.turn=m[0]<'a'
for P in b:S.set_piece_at(P[1],Piece.from_symbol(P[0]))
for l in S.legal_moves:1/(m!=[str(S.piece_at(l.from_square)),l.to_square])
```
This is a straight port of the Python 2 fully-bijective-input version.
[Attempt This Online!](https://ato.pxeger.com/run?1=RdDNToMwHADweN1T1BNgEIGNji1y2dXEoBxJQ2B2jthSVsqSPYuXXfRlfAJ9GvtByu3Xf_9f7ed3fxFH1l2vX6M43Ke_PwfOKNgf8TCAlvaMi7tF49MMn2vitl0_CtfzFkW2YzV_c6WCPcE11xIj7zJahujRqZ3FgXGQg7YDzbYIBiyqvsV7XNXCzcsI-bk6BWpaNVxow4gMh0j2VnVE1RUBwe81qSg742EbPbj0NisHwd0isK3I1OE01hx7nk8CwaYT8syTppdd_25gWTrc8UECkQ9Kp1NcazaKqeZJcaP5IQlDmwtjTdUBLjV7yVU6c2OZhDPn3GQ1M7GMTEIuuTSb7STjxEZjaJlamVlPqj62wWg109S_SppdnlVQ60VNsoMSewttxRrZ7SAy__cP "Python 3 – Attempt This Online")
[Attempt This Online! - test cases](https://ato.pxeger.com/run?1=5Za9juM2EMeRKoCBvMNEKSgHWkXy1629cbPFNQcY3tvrFEOQbHolWCZlkl6fN33q9GmuSV4mT3BX5klCcmTSl0ueIG7802jImflzOPZvf7RnVXH24ePP9b7lQkHNI3mWET41ddnb0C3kNWuPKuzP4KnhZdGAolLdgaDqKJh96OV5eawbVTOZ57F1h3m37g54S1kYGD8Zt-cgCk5BPz6JWtFQBEHw-1Ftb24__rkVfA_rikoJGP_7Xhnt5_S5aMIug37vcX7PC7EJNcXrhhbCkklkvs-S1Y-kIL0tF7CEmkE5e4wlVXlb0zXNCxUus3QVLc1TbKLl8rwveaPNyUrvbdY1Zt1j3NCnosn3_JnKWfpDuP92nkklwsfYbdV0OxyOhaD9ftTEindPqz6W9OmrG11els5u0lX_DrSwcVuoSusjqVBhEgEh2v4yT2xoZUIbJ6k2NZv1QH_qLbzMoBU1UyH5iZH-xaoyvel8bmwzMGKrzISxr43SxoIP4oxbmU9rTiVHdfO8O5Og795jOHf6saANLzZhix70_Zq26mo3m1aqy_jrl19JBCoCyjbzoNuQNpL-0zn5L-eXeXqHqn349PU3WRbsggjGt6sIsuCgcTiwyIw1dThBa6lxMLYojMPU4WRosdU4uvU49TjwOHI49svGV1YM8cb4WnowcTGbhcYUI9wbHDgcYLC3GhNHrywtjefE4dQbE4eDK9ehx5F3GK7ctul4Bd_BO3GkEL6rKAjOd8AZVCmsCwamn0G32knfIG2m_V6WkZ0-jIktghzIRSbCyCU1i0gluShqcYgojOvUIZ4UaQ1OHGLCFsfeYeStWCd5YxAdHshFCLIgl1O1OMQc70knqSVc_9Z4Tjzi-yWx2lwQzwytHgcjh_qkfbCB0fR1obsZwgWtVUUF7Fj9VClQHDXV38UY7AA76dfaUNEzmMFwUbirySiMnYoKDxyOEqcrthzixKkycaKMXW6dfgZTr8nU0fAV1mEzGF7VYZrjVOkJDGUtK97CiR-bDZi5rVOHXc2ezDTS03i9czWMJr6GoUu8y5aRywWxiU99CbeuNRJHXbW2Saa-STyOfDtMrtrB13tFQ1ev12CUuh4Y-M7A244Hf4V4g7DRk39V6XCkVMtxFIIy1ZyhKuSXQkVQsI021xK7YsOpZETp0Uef9TL9plD_KzH1Pf1sHKFa8gvB6OU-lQ1f7-TnQnXqHLCd3Tn5mzP2N8fPpsRV3En64K7Qwim68EPO3pbR6kpyl7kqdhRPG3sBc3X5jV16OJ9t0O7eHWxQt9Pjvmga8-Nsq98XerOWS1mXDY2MKIqKvQS-hZIf2caIVfL33Z-JvwE "Python 3 – Attempt This Online")
It's almost a shame there turned out to be an interface in python-chess whereby the direct placing of the pieces and setting of the current turn could be done concisely, because there was some fun golf in converting the board to FEN in the **271 byte** version:
```
import chess
b,m=eval(input())
B=['1']*64
for P in b:B[P[1]]=P[0]
B='/'.join(map(''.join,[*zip(*[iter(B)]*8)][::-1]))
i=8
while i:B=B.replace('1'*i,str(i));i-=1
S=chess.Board(B+' '+'bw'[m[0]<'a'])
for l in S.legal_moves:1/(m!=[str(S.piece_at(l.from_square)),l.to_square])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RdDNToMwHADweN1T1BNgEIGNji1y2dXEoBxJQ2B2jthSVsqSPYuXXfRlfAJ9GvtByu3Xf_9f7ed3fxFH1l2vX6M43Ke_PwfOKNgf8TCAlvaMi7tF49MMn2vitl0_CtfzFkW2YzV_c6WCPcE11xIj7zJahujRqZ3FgXGQg7YDzbYIBiyqvsV7XNXCzcsI-bk6BWpaNVxow4gMh0j2VnVE1RUBwe81qSg742EbPbj0NisHwd0isK3I1OE01hx7nk8CwaYT8syTppdd_25gWTrc8UECkQ9Kp1NcazaKqeZJcaP5IQlDmwtjTdUBLjV7yVU6c2OZhDPn3GQ1M7GMTEIuuTSb7STjxEZjaJlamVlPqj62wWg109S_SppdnlVQ60VNsoMSewttxRrZ7SAy__cP "Python 3 – Attempt This Online!")
[Attempt This Online! - test cases](https://ato.pxeger.com/run?1=5Za9kts2EMcnVWY0k8krbJgC5JlHixJFS7qwUeHGMzd3PncMh0NK0BERRVAgdLIufWr3btwk7xSXeZLggwTkOHmCqNGPiyV2978LSB__aM-8os2nP38l-5YyDoT63bnz9VNNytEGbyEnTXvkrreEx5qWRQ0cd_wGGOZH1qiHUZ6XR1Jz0nR5Hih3SPr3boC2uHEd6dcF7dnxnZPjBSdGOHaZ4zi_H_n2ev75m-_7HNYV7rpR6e8T_FTUbh_cG62SFIUou4qj0ZYyuAPSQLlcpXdpmGXJXTrOhAt6iYJfKGncfdG6SLOfXj2T1r1KRUTmrrzsau5l6XJ5HWZiW5LMR6eK1BjIcpWsAobbulhjV8S6In7HmUs874ZcJ-HoIVG5BStasI27eoEAvUDlCaV7EfwnVKDMU6nVMrWHoMaPRZ3v6RPuluFLd_9DksrtHoKW4DXOC-7WwZbRfd4djgXDnufXAaf9U-YNulwLjdJQZXsDojtBW_BKiNxhxt2xDwgJ-3MyVqG5DC2dOr4hzXIE4kO28LyElpGGu-jnBnmDladi0ySRtiXIjvFUhlHLsl3Soh_YWW8lP61sba6bled9Yx3PrOtwZoSEoDUtNm6rPfD7NW75xW4qrVCU8ddvH5AP3AfcbBKn3xDXHf6n8_i_nJ-T8Ear9unzt9-lqbNzfJjNMx9S5yBwOlHYSGtoMNbWUuBkppBJh4XBeKqwFRjNLS4sTixGBmf2tdmFVYd4I30V3cu4OptbgaGOsJI4MTjRwd4KHBt6pehOesYGF9Y4Nji5cJ1ajKzDNDPbhrMMfoR37IjBfVdhYJTugDZQhbAuGpDzDGLUTuIMCDP2RmmKdqIZsSoCHdAgE2rQkJpCTSUaFFU41cik68Kg7hRqJcYGdcIKZ9YhslZdJ3ojUTvco0EIdIuGriqc6hxXqJdUkX7_rfSMLer1O6S0GVD3TFstTiKDotM22ERq-roQ0wzuLSa8wgx2DXmsOHCqNRXfxQzkhQAnsSwMFT6DvBgGhfuapMJ6UrXCE4PR2OiqR05jbFSJjSgzk1uvn8TQarIwNH2l61AZTC_qkMMhbk6OoSRdRVs40WO9AXn5i9RhR5pHeRuJO3O9MzVEsa1hahLvs23QcEBU4gtbwtyMxthQX60akoUdEouRHYf4YhxsvRc0NfVaDaLQzMDEToY-7brxF6hPkB708b-qdDhiLOQ4MoYbXp-hKrqvhfKhaDbCTDo9FRuKuwZxcfXhJ_GaWCn4_0pMcU6_uI60Wt1XguHhPJU1Xe-6L4Xq1TnocTZ9sidnZk-OvZvGpuJe0ntzhG6Norf2klOnJcouJDeZ82KHdbf1LOhcTX4zk56-n1XQ_twdVFCz08O-qGv546yq3xdis5Z2HSlr7EtRxH-cfQd0CyU9NhspVknf938m_gY "Python 3 – Attempt This Online!")
# [Python 3](https://docs.python.org/3/) (with [python-chess](https://github.com/niklasf/python-chess)), 163 bytes
```
from chess import*
b,m=eval(input())
S=Board()
S.clear()
S.turn=m[0].color
S.set_piece_map(b)
for l in S.legal_moves:1/(m!=[S.piece_at(l.from_square),l.to_square])
```
An even smaller code size is achieved here by setting a rather ridiculously specific input specification. Examples:
```
{56: Piece(ROOK, BLACK), 57: Piece(KNIGHT, BLACK), 58: Piece(BISHOP, BLACK), 59: Piece(QUEEN, BLACK), 60: Piece(KING, BLACK), 61: Piece(BISHOP, BLACK), 62: Piece(KNIGHT, BLACK), 63: Piece(ROOK, BLACK), 48: Piece(PAWN, BLACK), 49: Piece(PAWN, BLACK), 50: Piece(PAWN, BLACK), 51: Piece(PAWN, BLACK), 52: Piece(PAWN, BLACK), 53: Piece(PAWN, BLACK), 54: Piece(PAWN, BLACK), 55: Piece(PAWN, BLACK), 8: Piece(PAWN, WHITE), 9: Piece(PAWN, WHITE), 10: Piece(PAWN, WHITE), 11: Piece(PAWN, WHITE), 12: Piece(PAWN, WHITE), 13: Piece(PAWN, WHITE), 14: Piece(PAWN, WHITE), 15: Piece(PAWN, WHITE), 0: Piece(ROOK, WHITE), 1: Piece(KNIGHT, WHITE), 2: Piece(BISHOP, WHITE), 3: Piece(QUEEN, WHITE), 4: Piece(KING, WHITE), 5: Piece(BISHOP, WHITE), 21: Piece(KNIGHT, WHITE), 7: Piece(ROOK, WHITE)}, [Piece(KNIGHT, BLACK), 45]
{56: Piece(ROOK, BLACK), 57: Piece(KNIGHT, BLACK), 58: Piece(BISHOP, BLACK), 59: Piece(QUEEN, BLACK), 60: Piece(KING, BLACK), 61: Piece(BISHOP, BLACK), 45: Piece(KNIGHT, BLACK), 63: Piece(ROOK, BLACK), 48: Piece(PAWN, BLACK), 49: Piece(PAWN, BLACK), 50: Piece(PAWN, BLACK), 51: Piece(PAWN, BLACK), 52: Piece(PAWN, BLACK), 53: Piece(PAWN, BLACK), 54: Piece(PAWN, BLACK), 55: Piece(PAWN, BLACK), 8: Piece(PAWN, WHITE), 9: Piece(PAWN, WHITE), 10: Piece(PAWN, WHITE), 11: Piece(PAWN, WHITE), 12: Piece(PAWN, WHITE), 13: Piece(PAWN, WHITE), 14: Piece(PAWN, WHITE), 15: Piece(PAWN, WHITE), 0: Piece(ROOK, WHITE), 1: Piece(KNIGHT, WHITE), 2: Piece(BISHOP, WHITE), 3: Piece(QUEEN, WHITE), 4: Piece(KING, WHITE), 5: Piece(BISHOP, WHITE), 21: Piece(KNIGHT, WHITE), 7: Piece(ROOK, WHITE)}, [Piece(PAWN, WHITE), 19]
```
[Here is a Python program that converts the test cases.](https://ato.pxeger.com/run?1=7VdNbuM2FF5050XPQKQL2o3HGMm2JARwgXrgAQZpHSczgBeGEcg2PRIsiypFxeMUPclsspmeoKeZ05QUSVHPzAG6qBeM9Onp_Xzfe6Ty9e_izBOav7x8q_j-TfT9hx_TY0EZR4z00TYhZdnp7MgebWn-RBhfpGRLuoVcezcdJH4Fmii7Qf1ssGf0-FiejxuaKbuVt0bpHqnrt-vJBC8xIllJkHk8yOiJsG6vVztkhFcsRyusYuFr7f3D7N3scf7r77OPq2JQv_rIzwVZD6qikG9f4z4yxu_ufrt7aIy3NKOsZdcTljo3f_3G66FrczuUtz9H607nefK2c0rSjCBP1cnZWV3I34bGbCcKJ09x1k3zouIme_k70idJHj0eSc6FlTYYlEWW8i5Gk18QhtbGlby2TwRrzzeoYGku3m7Q54nXXKtn-E9REMl3E9xyexYFmOs9ZUKnNFd52zJ0kLMJIhl0PSlvHrhfSNVBS0B75a_krLsQAgvOb4Q2CyG_617XD7xBHnRyf_Vlfit8LZ8KV0pwGaMG6jBrif0kFglrBXpuTK1IfU--bEnB0ezu_YwxyloiMxIf1Fjo6Xj53vlntbqaXvXR1a1Yhn0UiYo0ci8Wr4_GFpmLZdRHIURC8JZcfGFmkQf1VgSRCCALFSuEiO8gIsMAImMHCZy3QgeJDLI0tQs_nkXulZ-hReYqeguZqrd8iASm9qWp1AOede0tRNc-hIgPPOvaL5ARiKVrv7AJHSSSsdYdmI-_lmP8iVUEdT8lBDFKD4jmKPHQNs5VU4uxO8l9guaimTurFZ7K7rzFddhaTIXcYyumQubYlmiRUNOgELlEwI9cfN2ACnnAddFDiHjAZoFrWS4QQwOwCR0kgIghWGzxutLQRF-aSo0sCplj2-wWCU0-S1OXaQqLRADRdUUQGZqclybDCERfYNu2Fhk5Nh6oS_sJZVPYnGtWZVO8j-Xh1p2TlCeEoUOefk444lQ1hfgbj5E8JdFJPBZAQs4oZpctEgLZ7rHdJWxDjIFIOokANkQIZJs6NN22G6sRKQDIvC12gwwBcbr5fIgEkhRJU1NXPU0tmuTwiIOWE7RJy4QW6ESrbIfE_iyZQYc0_yxPLnGubw8uRQGkKHptZi7mKnII8QGNU2w3djAznoNcdH_kTBGcPW0TOORHkPzQmZCxI8cI-NGy-o4cLZsHZz71hASws8evTYhvRdT5RK-L-EdFiFCrYkycvNkZJXHp6thHcb4TcFqqmdhRUuaYi4OePMlPJp7E_H-t_yNah2Zfs4edErN09CRms9tkdHsoX9Mxcra1ADA5b7PUIENHx5FzFsIT4rbdD222L7j1Hf49Z1sbgk2s6SLLCY8PRLW5GgLFgnvme07lPsy4PtOaSE3GNtLHY5xlpOSK92MsghW0LNNNJv7jEHJwwo4lonvxpV_lOynThn7pqa_XfwE "Python 3 – Attempt This Online")
[Attempt This Online!](https://ato.pxeger.com/run?1=ddPNTsIwAAfwgyd5inoxnZlz33wkO4AhsmAAHYYDIUuZRZZ06-w6EmN8Ei8kRt9Jn0YQhmNZb-3v37X_pN37V_LClzRerz8zvrhsfH8sGI1AsMRpCsIooYxf1OZy5OAVIjCMk4xDSap5Toci9gg3IyUgGLG_Ec9Y7ERTdaYElFC2kRRzPwlxgP0IJXAu1RaUAQLCGHgKwU-I-BFd4bSlXcHozJl6ym4x4pAo2yJ--pwhhiWZKJzuJzNpV3XfeP1zcv5q2S0w2n4K74fDvgw6t-3rviQDq557f-De9MaFpJEnHdfrDUeFpJkndw_d7uA_sNXDZu7gpuCaaCtbFx1vG9WFzUOtUXtSONtsVrulClwTuC5wQ-CmwK1qL9Wf9Nxxd8PNatZUgWsC1wVuCNwUuFXt6vGlHJaXbzEP9PLF54FRekK5m8cvKGdLtI8uPLpeVfVNBtPq92Zas9Pd__IL "Python 3 – Attempt This Online")
[Attempt This Online! - test cases](https://ato.pxeger.com/run?1=7Vc9b-NGEEVaFalTTpRCZEAzIilKsgwV54NzNhzYTuTgCsUgKGllEqK4vN2VdbKRNnX6NAcEyX-6K_NLsitKpLTkBEh_bCS-2Y_ZN29mln_8nW1ERNMPH1_iZUaZgJhafMOt_C2JJ40ZmUMQp9lKGOYAHhM6CRMQhIszYESsWLp9aQTBZBUnIk55ENjb4TDczTsDmpHUaKpx3M42Tau5bpr2msWCGKzZbP61EvOT_sc_54wuYRoRziHf_9vGxFoOyVOYGDsPzMZoeE5DNjPkP3uakJBt_ylHhstx-8Ge0oQyiXAigiwmUxIsw8yYmI05ZZBAnMLITshjmARL-kT4wPnOWH49HI_sfHAojMRWjgT83SpkxLQSW9Ddy4OZu_rpixPp9tgZnDgP5hlIwuwsFJE8NydMGG0LWi2JPw_b212F2lUN4mIWp4MGyCeew_MAMhanwmj9krbMPSrGctHhUGEDUCSKsdpma1YMKiR_YZt8KfVkiu0gZy0Idlw3zcKeb1dE1WYkoeHMyPIR5P2UZOJgta1bjjzGP7_93rJAWEDS2bC5W5AknOiD29jg56FzlrP24dOXX734_QHcKaaN66ubNxac__Dq9bVpgefu8R9_vri4KQ2-U0y4uXpzeV9aui5mcf295fxqdHl7d7Da6d7y0-3t9cFaXj3eKdy9e_X2wKvOKYK7CN6px30PwbHxPrL-MatvL6_uLxQRjsbq3uD0de4Ki6tzVyx2ilnax-Tt4V497HSPz7DHT-thp12Puz1kvIfgHWSd2vG_WjCudd5_gG_gnq0IGPcRAUbpAmgKkQPTMAVVU0Dm_FqWKAkTs_HSdeoVX0pLU3zJT0XxqMHDBO-hFgdJhTITNbxbLz2d10Kq_zMV9HgWuFuv7VIXmrbLHNe17aGqb2PS7mEGv1uvbh9JBsdH5OcgckVwF5GxXhl0GVe4cJWQvw9lLQfjhsQiIgwWafwYCRA0F7L8DX3YtuW1NEsgIhtQXbHxooelWnt1WaPlutPGLGUZrBTyLmbp1stFd2uPl3KsVEJULWgh9BC5HIThmCzvIAiqnKwjeSmCScwjmsGarpIZqKuU5B0WcfqoLhLygjRdyAB0ukgAPCQAfuWk1a6iWyonLab0MYum_2qQtbKCdFIH67BImehiZaKDBR6LbsfDLJUzF1MczOIiTbDj1uOOW5fGWFerpndBR7tWWe9WhEgJrRgjqUg2EIW8Ki4LwnQm4ZjnZWBGCU9bQt70yJOcJi2h-CzAzwL8TwF6_eOLUq4wXhEZ2TedSUKnC74XVyki7Tuhh4gL_xrw0faC3o0q14EaCR8FuYvEGL2KVC95RQ-p9Dydat2p05JpES5IntF5vufcSj79ejodLFd7decsXdDJLz0YLcMkUd-p2ygvQ-lERjmPJwmxVPAFYUsOdA4TukpnShQT-n73Xf0v "Python 3 – Attempt This Online")
] |
[Question]
[
Your bird has been itching for some exercise and is sick of being stuck in static positions all the time. Write a program that will show a randomly dancing ascii bird, updating every 100ms\*n or 200ms\*n depending on the dance move. The bird always begins with the dance move `<(")>`.
The program should accept one input which is a number to multiply the sleep interval by (`n >= 0 && n <= 50`).
**100ms Moves**
```
^(")v
v(")^
^(")^
v(")v
```
**200ms Moves**
```
(>")>
<(")>
<("<)
```
## Extra Details
* Randomness doesn't have to be uniform but each dance move should have a reasonable chance of occuring (at least 1 in 60 seems fair, it's OK if the same move occurs twice in a row)
* There should only be one bird displayed at a time, not multiple birds
* Trailing whitespace is allowed (but other trailing characters are not)
* A bird should be displayed *before* the sleep
## Example in Python 3
```
import random, time, sys
birds = """(>")>
<(")>
<("<)
^(")v
v(")^
^(")^
v(")v"""
birds = birds.split()
interval = int(input("Sleep for 100ms*"))
selection = -1
while True:
if selection == -1:
selection = 1
else:
selection = random.randint(0, len(birds)-1)
sys.stdout.write('\r'+birds[selection])
if selection > 2:
time.sleep(0.1*interval)
else:
time.sleep(0.2*interval)
```
## Winning
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so least bytes wins!
[Answer]
# Matlab, ~~125~~ 117 bytes
Unfortunately this cannot be displayed in TIO as there is no "streaming" of the output. Here's a gif for an input of `1` instead:

```
t=input('')*.1;a='^(")vv(")^^(")^v(")v(>")><(")><("<)';while 1;n=randi(7);clc;disp(a(n*5-4:n*5));pause(t+t*(n>4));end
```
Thanks @LuisMendo for -8 bytes!
[Answer]
## [\*><>](https://esolangs.org/wiki/Starfish), ~~103~~ 101 bytes
```
<vD[3'(")'
1x<.5
S\:43_C43CdooI:o@:o@:o@Do
R!"^"x"v">
>:2* _"><"92.
x '>)">('u.02S*2:oooooodO<'<("<)'
```
[Try it here!](https://starfish.000webhostapp.com/?script=DwNwIg2gzA5AFAIgJQwFAEYAewB0BWVAZQB0AuAFigH0BhSmgEwHsmBJUpgAQ+67CdQAlAIQIAegkwIQCAHypZpAEwAqAARU5wBAE4lOVJjUxZSOXBgBXHAAYlhFUo4sXDAPLAYwRMBRA) (write in `n` on the initial stack or you'll get an error)
I decided to take a stab at my challenge since there were no sub 100 bytes answers. Place `n` on the stack and away you go! This reuses the `(")` characters to save some bytes.
# Explanation
## Initialisation
`<vD[3'(")'`
Here we store `(")` for later usage.
```
< move the IP left
[3'(")' push '(")' to a new stack
D move back down to a clean stack
v move the IP down into "dance chooser"
```
## Dance chooser
```
1x<.5
\
```
This is frequently executed to select which type of dance we're going to generate.
```
x generate a 100ms dance or a 200ms dance
1 .5 jump to "200ms dance"
\ mirror IP into "100ms dance"
```
There's a `v` above the `x` and a `<` to the right of it too. These make the `x` get re-executed if it tries to move the IP in the wrong direction.
## Generate 100ms dance
```
S\:1*43_C43CdooI:o@:o@:o@Do
```
Here we generate and output one of the 100ms dance moves.
```
\ mirror the IP right
: copy n
43 C43C call "generate '^' or 'v'" twice
_ ignored mirror
do output a carriage return
o output the first hand of the bird
I:o@:o@:o@D select, copy, and output '(")'
o output the second hand of the bird
S sleep for previous n*100ms
\ mirror IP back to "dance chooser"
```
### 43C - Generate "^" or "v"
```
R!"^"x"v">
```
This is a simple function that generates "^" or "v" then returns. It works similarly to the dance chooser where it has instructions around `x` to ensure the IP only moves left or right.
```
x generate "^" or "v"
R!"^" > push "^" to stack and return
R "v" push "v" to stack and return
```
## Generate 200ms dance
This is another that begins with `x`. It'll be separated into two sections: `<(")>` and another `(>")> and <("<)`, because they're two distinct sections and `x` is the only thing they share.
### `<(")>`
```
>:2* _"><"b2.
```
This basically does the beginning of the `generate 100ms dance` routine, but populates the bird hands as `><` instead of a random `^v` combo. It multiplies `n` by two this time as well. This makes it all setup to utilise the `generate 100ms dance` routine to output the entire bird and wait 200ms instead.
```
> move IP right
:2* copy n and do n*2
_ ignored mirror
"><" push "><" to stack
b2. jump to "output carriage return" in "generate 100ms dance"
```
### `(>")>` and `<("<)`
```
x '>)">('u.02S*2:oooooodO<'<("<)'
```
This little explanation is about the `(>")>` and `<("<)` generation, though the `x` can send the IP outside of it (explained below).
```
x move to "choose dance", generate (>")>, <("<), or <(")> (previous routine)
'>)">(' push '(>")>' to the stack
'<("<)' push '<("<)' to the stack
u O< ensure inner code block is always executed with IP moving left
od output carriage return
ooooo output bird
S*2: sleep for n*200ms
.02 jump to "dance chooser"
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 53 bytes
```
xXx`'./U;HbG#3@@!{uu'F'v^<>(")'Za7e 7YrY)D5M3>QG*&XxT
```
Moves are uniformly random.
Below is a sample run with`n = 2`. Or try it at [**MATL Online!**](https://matl.io/?code=xXx%60%27.%2FU%3BHbG%233%40%40%21%7Buu%27F%27v%5E%3C%3E%28%22%29%27Za7e+7YrY%29D5M3%3EQG%2a%26XxT&inputs=2&version=19.7.0) (The interpreter is experimental. If it doesn't run initially try pressing "Run" again or refreshing the page).
[](https://i.stack.imgur.com/9n5mk.gif)
### Explanation
```
x % Take input n and delete it
Xx % Clear screen
` % Do...while
'./U;HbG#3@@!{uu' % Push this (compressed) string
F % Specify source alphabet for decompression
'v^<>(")' % Push target alphabet
Za % Base conversion (decompress)
7e % Reshape as a 7-row char matrix. Each row is a move
7Yr % Push random integer from 1 to 7
Y) % Select that row from the char matrix
D % Display it
5M % Push the integer again
3> % Does it exceed 3? Gives false (0) or true (1)
Q % Add 1
G* % Multiply by n
&Xx % Pause that many tenths of a second and clear screen
T % Push true
% End (implicit). Since top of the stack is true, this causes
% and infinite loop
```
[Answer]
# JavaScript (ES6) + HTML5: ~~118~~ 116 + 8 = 124 bytes
## Javascript: 119 bytes
```
f=n=>{a.innerHTML='(>")>0<(")>0<("<)0^(")v0v(")^0^(")^0v(")v'.split(0)[r=+new Date%7],setTimeout(f,(1+(r<3))*100*n,n)}
```
I'm using the milliseconds since epoch to generate a random-ish number. Theoretically, this would always generate the same (set of) number(s), but a test on my PC gave me a pretty random outcome (most numbers appeared more or less equally). Also using the fact that html elements with an id get added to the global window object in JavaScript, so `document.getElementById()` is not needed.
## HTML: 8 bytes
```
<b id=a>
```
I'm omitting the quotes here and I'm not closing the `b` tag. It's not valid html, but all browsers automatically close the tag anyway. I made it bold because `b` is a one-character HTML element and because my bird's dance deserves being noticed.
[Answer]
# [PowerShell](https://github.com/PowerShell/PowerShell), ~~124~~ 117 bytes
(Thanks [TimmyD](https://codegolf.stackexchange.com/users/42963/timmyd))
```
for(){(-split'^(")v v(")^ ^(")^ v(")v (>")> <(")> <("<)')[($i=0..6|random)];sleep -m((100,200)[$i-gt3]*$args[0]);cls}
```
[Try it online!](https://tio.run/nexus/powershell#LchLCoMwEADQqwQJOCONjApuYr1ISEBalUD8kEg22rOnRbp5i5emzQOeIMLu7JEbyDCy@NMwcxvvgT7DnnXwt8McFXD7pLJsLz@s721BLYMbx52JBaAietREqLgV89Hogg9@Doo0ypcLn5S@ "PowerShell – TIO Nexus") (Not that it will work in TIO...)
[Answer]
# [Noodel](https://tkellehe.github.io/noodel/), noncompeting 67 [bytes](https://tkellehe.github.io/noodel/docs/code_page.html)
```
ʠƘṣḳƑðẉḤż’ṀỴ(EḞ4ĊḌṀY%¤ĠẸG^ḞðxỌð
ḊḢðḞ’ṀḌcṀḌcİ8c¬ððɲḷṛḋʠṡʠạÇƥƥạƥḋʠ⁺µḍ
```
This challenge was very difficult for *Noodel* because it does not have any smart arithmetic or comparative based operators. But after doing this challenge, I think *Noodel* is ready for its first release.
[Try it:)](https://tkellehe.github.io/noodel/release/editor-0.0.html?code=%CA%A0%C6%98%E1%B9%A3%E1%B8%B3%C6%91%C3%B0%E1%BA%89%E1%B8%A4%C5%BC%E2%80%99%E1%B9%80%E1%BB%B4(E%E1%B8%9E4%C4%8A%E1%B8%8C%E1%B9%80Y%25%C2%A4%C4%A0%E1%BA%B8G%5E%E1%B8%9E%C3%B0x%E1%BB%8C%C3%B0%0A%E1%B8%8A%E1%B8%A2%C3%B0%E1%B8%9E%E2%80%99%E1%B9%80%E1%B8%8Cc%E1%B9%80%E1%B8%8Cc%C4%B08c%C2%AC%C3%B0%C3%B0%C9%B2%E1%B8%B7%E1%B9%9B%E1%B8%8B%CA%A0%E1%B9%A1%CA%A0%E1%BA%A1%C3%87%C6%A5%C6%A5%E1%BA%A1%C6%A5%E1%B8%8B%CA%A0%E2%81%BA%C2%B5%E1%B8%8D&input=2&run=true)
## How It Works
```
# Note: The input is immediately pushed onto the stack.
ʠ # Moves the pointer for the top of the stack down one.
ƘṣḳƑðẉḤż’ṀỴ(EḞ4ĊḌṀY%¤ĠẸG^ḞðxỌð # Creates a string based off of the key "ƘṣḳƑðẉḤż" and the compressed text "ṀỴ(EḞ4ĊḌṀY%¤ĠẸG^ḞðxỌð" to create "^(")vðv(")^ð^(")^ðv(")vð(>")>ð<(")>ð<("<)" which then gets split by the null character "ð" to create an array of strings which gets pushed to the stack.
\n # A new line to separate the literals.
ḊḢðḞ’ṀḌcṀḌcİ8c¬ðð # Creates a string based off of the key "ḊḢðḞ" and the compressed text "ṀḌcṀḌcİ8c¬ðð" to create "100ð100ð100ð100ð200ð200ð200" which then gets split the same way as before.
ɲ # Turns each element in the array into a number creating the array of delays.
ḷ # Loops the rest of the code unconditionally.
ṛ # Generates a random number from 0 to the length-1 of the array on top of the stack.
ḋ # Duplicates the random number.
ʠ # Moves the stack pointer down to save one of the random numbers for later.
ṡ # Swap the array with the random number such that the array is on top again.
ʠ # Moves the stack pointer down such that the random number is on top.
ạ # Uses the random number to access the bird array which is now after the random number and pushes the element onto the stack.
Ç # Clears the screen and pops the bird and pushes it to the screen.
ƥƥ # Moves the stack pointer up two times such that the random number is the top.
ạ # Use the random number to access the array with delays and pushes that item onto the stack.
ƥ # Moves the stack pointer up in order to have the input on top.
ḋ # Duplicates the users input.
ʠ # Moves the stack pointer back down in order to have the user input on top followed by the random item from the delay array.
⁺µ # This command pops two numbers off and multiplies them and pushes the result back on.
ḍ # Pops off of the stack and uses that as a delay in milliseconds.
```
---
**64 bytes**
Here is a version that works as a code snippet.
```
ʠƘṣḳƑðẉḤż’ṀỴ(EḞ4ĊḌṀY%¤ĠẸG^ḞðxỌð EAð¶’Ṁ|ṢĿ<h4¶¬ȥḷṛḋʠṡʠạÇƥƥạƥḋʠ⁺µḍ
```
```
<div id="noodel" code="ʠƘṣḳƑðẉḤż’ṀỴ(EḞ4ĊḌṀY%¤ĠẸG^ḞðxỌð EAð¶’Ṁ|ṢĿ<h4¶¬ȥḷṛḋʠṡʠạÇƥƥạƥḋʠ⁺µḍ" input="2" cols="5" rows="3"></div>
<script src="https://tkellehe.github.io/noodel/release/noodel-1.1.js"></script>
<script src="https://tkellehe.github.io/noodel/ppcg.min.js"></script>
```
[Answer]
# Python, 157 bytes
```
import time,random;n,m=5,int(input())
while 1:print('(>")><(")><("<)^(")vv(")^^(")^v(")v'[n:n+5]);time.sleep((.1+(n<15)/10)*m);n=(n+random.randint(1,6)*5)%35
```
I also tried to do it without the chicken ascii art, but that was way longer.
```
import time,random;n,m=5,int(input())
while 1:
print(['^v'[n%2]+'(")'+'v^'[0<n<3],''.join(map(chr,[40+20*(n>4),62-22*(n>4),34,41+19*(n>5),62-21*(n>5)]))][n>3])
time.sleep((.1+(n>3)/10)*m);n=(n+random.randint(1,6))%7
```
[Answer]
# Ruby, 97+1 = 98 bytes
+1 byte from the `-n` flag.
```
a=1;loop{puts %w{^(")v <(")> v(")^ (>")> ^(")^ <("<) v(")v}[a];sleep$_.to_i*0.1*(1+a%2);a=rand 7}
```
[Answer]
## Clojure, ~~185~~ 178 bytes
+18 bytes because it wasn't starting with `<(")>`.
-7 bytes by inlining `birds`, and getting rid of the `let`.
```
#(loop[m nil r(or m 1)](print"\r"((clojure.string/split"(>\")> <(\")> <(\"<) ^(\")v v(\")^ ^(\")^ v(\")v"#" ")r))(flush)(Thread/sleep(*(if(> r 2)100 200)%))(recur 1(rand-int 7)))
```
Just splits the birds on spaces, picks a random index from 0-6, displays the chosen bird, then if the chosen index is greater than 2, it waits for 100ms, else 200ms.
Clojure really needs a string `split` method in the core.
Ungolfed:
```
(defn dancing-bird [n]
(loop [m nil]
(let [birds (clojure.string/split "(>\")> <(\")> <(\"<) ^(\")v v(\")^ ^(\")^ v(\")v" #" ")
rand-i (or m 1)]
(print "\r" (birds rand-i))
(flush)
(Thread/sleep (* (if (> r 2) 100 200) n))
(recur (rand-int 7)))))
```
] |
[Question]
[
# **Input:**
A non-empty sequence of integers greater than zero, the length of which is greater than 1.
# **Output:**
The largest product of all elements of the longest subsequence between the minimum and maximum elements of sequence including themselves.
## Note:
Because the minimum and maximum elements can be repeated, then to a definite answer necessary to find the longest possible subsequence, at one end of which is a minimum and at the other end maximum elements of the sequence. If there is multiple longest subsequences then choose subsequence with largest product.
# Examples:
## 1st example:
Input: `[5, 7, 3, 2, 1, 2, 2, 7, 5]`
Output: `42`
Explanation:
`min == 1`, `max == 7`. There is 2 possible subsequences with min and max on ends: `[1, 2, 2, 7]` and `[7, 3, 2, 1]`. Their length is equal, so comparing products: `7*3*2*1 == 42` and `1*2*2*7 == 28`. Because `42 >= 28`, answer: `42`.
## 2nd example:
Input: `[1, 2, 2, 2, 4, 3, 3, 1]`
Output: `32`
Explanation:
`min == 1`, `max == 4`. 2 subsequences: `[1, 2, 2, 2, 4]` and `[4, 3, 3, 1]`. Length of `[1, 2, 2, 2, 4]` is greater than length of `[4, 3, 3, 1]`. product: `1*2*2*2*4 == 32` => answer is `32`.
## 3d example:
Input: `[1, 2, 3, 4, 3, 3, 1]`
Output: `36`
Short explanation:
`min == 1`, `max == 4`. 2 subsequences: `[1, 2, 3, 4]` and `[4, 3, 3, 1]`. `1*2*3*4 == 24`, `4*3*3*1 == 36`, `36 >= 24` => answer is `36`.
## 4th example:
Input: `[2, 2, 2]`
Output: `8`
Explanation:
`min == 2`, `max == 2`. 2 different subsequences: `[2, 2]` and `[2, 2, 2]`. Length of `[2, 2, 2]` is greater than length of `[2, 2]`. product: `2*2*2 == 8` => answer is `8`.
## More *(random)* examples:
```
>>>[7, 2, 3, 6, 8, 6, 2, 5, 4, 3]
288
>>>[3, 3, 8, 9, 1, 7, 7, 2, 2, 4]
9
>>>[3, 2, 6, 5, 4, 1, 8, 8, 7, 9]
4032
>>>[7, 4, 2, 8, 8, 3, 9, 9, 5, 6]
31104
```
# Check your solution:
Here is Python 3 lambda *(788 bytes)*, which satisfies the requirement of the task:
```
lambda O: __import__('functools').reduce(__import__('operator').mul,O[[[slice(O.index(max(O)),len(O)-1-O[::-1].index(min(O))+1),slice(O.index(min(O)),(len(O)-1-O[::-1].index(max(O)))+1)][__import__('functools').reduce(__import__('operator').mul,O[O.index(min(O)):(len(O)-1-O[::-1].index(max(O)))+1],1)>=__import__('functools').reduce(__import__('operator').mul,O[O.index(max(O)):len(O)-1-O[::-1].index(min(O))+1],1)],slice(O.index(min(O)),(len(O)-1-O[::-1].index(max(O)))+1),slice(O.index(max(O)),len(O)-1-O[::-1].index(min(O))+1)][(len(range(O.index(min(O)),(len(O)-1-O[::-1].index(max(O)))+1))>len(range(O.index(max(O)),len(O)-1-O[::-1].index(min(O))+1)))-(len(range(O.index(min(O)),(len(O)-1-O[::-1].index(max(O)))+1))<len(range(O.index(max(O)),len(O)-1-O[::-1].index(min(O))+1)))]],1)
```
# Winner:
Shortest solution will win. All programming languages accepted.
*P.S.: I will be happy to the explanations of your solutions*
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
NMpMr/€LÐṀịµP€Ṁ
```
**[TryItOnline!](http://jelly.tryitonline.net/#code=Tk1wTXIv4oKsTMOQ4bmA4buLwrVQ4oKs4bmA&input=&args=WzcsNiwxLDIsMiw3XQ)**
### How?
```
NMpMr/€LÐṀịµP€Ṁ - Main link: list of integers, L
µ - links to the left as a monadic chain with argument L
N - negate elements of L
M - indexes of maximal elements (i.e. indexes of minimal elements of L)
M - indexes of maximal elements of L
p - Cartesian product of the min and max indexes
/€ - reduce each list (all of which are pairs) with the dyad:
r - range(a,b) (note if a>b this is [a,a-1,...,b])
ÐṀ - filter keeping those with maximal
L - length
ị - index into L (vectorises) (get the values)
P€ - product of a list for €ach
Ṁ - maximum
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
.ịạ/;L;P
ẆÇ€ṀṪ
```
[Try it online!](https://tio.run/nexus/jelly#@6/3cHf3w10L9a19rAO4Hu5qO9z@qGnNw50ND3eu@g9mR/7/H83FGW2qo2Cuo2Cso2Cko2AIJo3AIqaxOkBZuAgQmYCVAZEhkpQxhjhUPZhtDlNjpqNgASaBXFOIFrACiEaglCXYdnMwgloHU2AE1gjRZQhWbAFWZgmzwgSsBiJuDDbKEqzeLJYrFgA "Jelly – TIO Nexus")
### How it works
```
ẆÇ€ṀṪ Main link. Argument: A (array)
Ẇ Window; generate all substrings of A.
Ç€ Map the helper link over the substrings.
Ṁ Take the maximum.
Ṫ Tail; select the last element.
.ịạ/;L;P Helper link. Argument: S (array / substring)
.ị At-index 0.5; select the last and first element of S.
ạ/ Reduce by absolute difference.
;L Append the length of S.
;P Append the product of S.
```
[Answer]
# [Perl 6](https://perl6.org/), 108 bytes
```
{max ([*] $_ for .[.grep(+.max(+*)) with (for .min,.max,.max,.min {.first($^a,:k).. .first($^b,:k,:end)})])}
```
[Answer]
# R, 146 bytes
```
z=apply(expand.grid(which(max(x<-scan())==x),which(min(x)==x)),1,function(y)c(prod(x[y[1]:y[2]]),abs(diff(y))));max(z[1,which(z[2,]==max(z[2,]))])
```
Tricky challenge because of the length requirement. Also annoying because the would-be useful builtin `which.max` only returns the index of the first maximum it encounters, forcing me to use `which(max(x)==x)` instead... 3 times. Ohwell...
### Readable:
```
x <- scan()
maxs <- which(max(x)==x)
mins <- which(min(x)==x)
q <- expand.grid(maxs,mins)
z <- apply(q,1,function(y){
c(prod(x[y[1]:y[2]]), abs(diff(y)))
})
max(z[1, which(z[2, ]==max(z[2, ]))])
```
[Answer]
# PHP, ~~189~~ ~~173~~ 166 bytes
```
<?foreach($a=$_GET[a]as$p=>$b)foreach($a as$q=>$c)$b>min($a)|$c<max($a)?:$r[$d=abs($p-$q)+1]=array_product(array_slice($a,min($p,$q),$d));ksort($r);echo max(end($r));
```
similarly lazy but 33 bytes shorter (had to add 10 bytes to turn the snippet into a program):
1. Loop `$p/$b` and `$q/$c` through the array; if `$b==min` and `$c==max`,
add product of the sub-sequence to `$r[sub-sequence length]`
2. Sort `$r` by keys.
3. Print the max value of the last element.
Call in browser with array as GET parameter `a`.
Example: `script.php?a[]=5&a[]=7&a[]=3&a[]=2&a[]=1&a[]=2&a[]=2&a[]=7&a[]=5`
[Answer]
# Mathematica, 122 bytes
```
(g=#;Sort[{#.{-1,1},Times@@Take[g,#]}&/@Sort/@Join@@Outer[List,Sequence@@(Union@@Position[g,#@g]&/@{Max,Min})]][[-1,-1]])&
```
Surprised how long this turned out to be. First generates the Cartesian product of the appearances of the minima and maxima (as per [Jonathan Allan's Jelly answer](https://codegolf.stackexchange.com/a/103751/56178)), then computes the lengths of those runs and their products, and selects the appropriate one by taking the last element of the sorted results.
[Answer]
# JavaScript, 187 bytes
```
f=
(l,M=Math,a=M.min(...l),z=M.max(...l),r=(m,n)=>[eval(l.slice(b=l.indexOf(m),c=l.lastIndexOf(n)+1).join`*`),M.abs(b-c)])=>(u=r(a,z),v=r(z,a),u[1]>v[1]?u[0]:v[1]>u[1]?v[0]:M.max(v[0],u[0]))
console.log([
[5, 7, 3, 2, 1, 2, 2, 7, 5],
[1, 2, 2, 2, 4, 3, 3, 1],
[1, 2, 3, 4, 3, 3, 1],
[2, 2, 2],
[7, 2, 3, 6, 8, 6, 2, 5, 4, 3],
[3, 3, 8, 9, 1, 7, 7, 2, 2, 4],
[3, 2, 6, 5, 4, 1, 8, 8, 7, 9],
[7, 4, 2, 8, 8, 3, 9, 9, 5, 6]
].map(a=>`[${a}] => ${f(a)}`).join`
`)
```
] |
[Question]
[
The [permanent](https://en.wikipedia.org/wiki/Permanent_(mathematics)) of an \$n\$-by-\$n\$ matrix \$A = (a\_{i,j})\$ is defined as:
$$\operatorname{perm}(A)=\sum\_{\sigma\in S\_n}\prod\_{i=1}^n a\_{i,\sigma(i)}$$
For a fixed \$n\$, consider the \$n\$-by-\$n\$ matrices whose entries are taken from \$\{-1, 0, +1\}\$ .
## Task
For each \$n\$ from 1 upwards, output the number of \$n\$-by-\$n\$ \$(-1, 0, 1)\$ matrices with zero permanent.
The output format looks like this:
```
n = 1, 1
n = 2, 33
n = 3, 7555
n = 4, 13482049
n = 5, 186481694371
n = 6, ...
```
## Score
Your score is the largest \$n\$ your code gets to in 20 minutes in total on my computer, this is not 20 minutes per \$n\$.
If two entries get the same \$n\$ score, then the winning entry will be the one that gets to the highest \$n\$ in the shortest time on my machine. If the two best entries are equal on this criterion too then the winner will be the answer submitted first.
You are in no way allowed to hard-code solutions.
## Languages and libraries
You can use any freely available language and libraries you like. I must be able to run your code so please include a full explanation for how to run/compile your code in windows if at all possible.
## My Machine
The timings will be run on my machine, Intel Core i7-9750H 6 cores, 12 threads, The machine runs Windows 10.
## Updated
Brute forcing every matrix (of which there are \$3^{n^2}\$) is not necessarily a particularly good answer, especially since there are many symmetries that preserve the value of the permanent. Thanks for @isaacg.
[Answer]
# Rust, \$A(5) = 186481694371\$ in 0.2 s, \$A(6) = 19733690332538577\$ in 580 s
(Unofficial times on a Core i7-10710U with 6 cores/12 threads.)
### `src/main.rs`
```
use itertools::Itertools;
use num_integer::gcd;
use rayon::prelude::*;
use std::cmp::Ordering;
use std::collections::HashMap;
use std::convert::TryFrom;
use std::sync::Mutex;
type Count = u64;
type Coeff = i32;
fn sort_scols(n: u32, i: u32, sets: &[u32], state: &[Coeff]) -> Vec<u32> {
let mut scol_ranks: Vec<u32> = (0..2 * n).map(|scol| (scol >> 1 > i) as u32).collect();
let mut sorted_scols: Vec<u32> = (0..2 * n).collect();
let mut scol_descs = vec![vec![]; 2 * n as usize];
for (set_index, (&set, &coeff)) in sets.iter().zip(state).enumerate() {
if coeff != 0 {
for col in 0..n {
if set & 1 << col != 0 {
scol_descs[(col as usize) << 1].push(set_index);
scol_descs[(col as usize) << 1 | 1].push(set_index);
}
}
}
}
let mut sorted_set_indexes: Vec<_> = (0..sets.len()).collect();
let mut set_ranks: Vec<u32> = vec![!0; sets.len()];
let mut set_descs = vec![(0, vec![]); sets.len()];
while {
for (&coeff, set_desc) in state.iter().zip(&mut set_descs) {
set_desc.0 = coeff;
set_desc.1.clear();
}
let mut seen = 0;
for &scol in &sorted_scols {
if seen & 1 << (scol >> 1) == 0 {
seen |= 1 << (scol >> 1);
if scol & 1 == 0 {
for (&set, set_desc) in sets.iter().zip(&mut set_descs) {
if set_desc.0 != 0 && set & 1 << (scol >> 1) != 0 {
set_desc.1.push(scol_ranks[scol as usize]);
}
}
} else {
for (&set, set_desc) in sets.iter().zip(&mut set_descs) {
if set_desc.0 != 0 && set & 1 << (scol >> 1) != 0 {
set_desc.0 = -set_desc.0;
set_desc.1.push(scol_ranks[scol as usize]);
}
}
}
}
}
let set_index_key =
|&set_index: &usize| (set_descs[set_index].0.abs(), &set_descs[set_index].1);
sorted_set_indexes.sort_by_key(set_index_key);
if sets.len() != 0 {
let mut next_set_rank = 0;
set_ranks[sorted_set_indexes[0]] = next_set_rank;
for (&set_index0, &set_index1) in sorted_set_indexes.iter().tuple_windows() {
if set_index_key(&set_index0) < set_index_key(&set_index1) {
next_set_rank += 1;
}
set_ranks[set_index1] = next_set_rank;
}
}
let scol_set_index_key = |scol: u32| {
let sign = 1 - 2 * (scol & 1) as Coeff;
let set_ranks = &set_ranks[..];
let set_descs = &set_descs[..];
move |&set_index: &usize| (set_ranks[set_index], set_descs[set_index].0 * sign)
};
for (scol, scol_desc) in scol_descs.iter_mut().enumerate() {
scol_desc.sort_by_key(scol_set_index_key(scol as u32));
}
let scol_cmp = |&scol0: &u32, &scol1: &u32| {
scol_ranks[scol0 as usize]
.cmp(&scol_ranks[scol1 as usize])
.then_with(|| {
scol_descs[scol0 as usize]
.iter()
.map(scol_set_index_key(scol0))
.cmp(
scol_descs[scol1 as usize]
.iter()
.map(scol_set_index_key(scol1)),
)
})
};
sorted_scols.sort_by(scol_cmp);
let mut new_scol_ranks = vec![!0; 2 * n as usize];
let mut next_rank = 0;
let mut changed = false;
new_scol_ranks[sorted_scols[0] as usize] = next_rank;
for (&scol0, &scol1) in sorted_scols.iter().tuple_windows() {
if scol_ranks[scol0 as usize] < scol_ranks[scol1 as usize] {
next_rank += 1;
} else if scol_cmp(&scol0, &scol1) == Ordering::Less {
changed = true;
next_rank += 1;
}
new_scol_ranks[scol1 as usize] = next_rank;
}
scol_ranks = new_scol_ranks;
changed
} {}
let mut seen = 0;
sorted_scols.retain(|scol| {
seen & 1 << (scol >> 1) == 0 && {
seen |= 1 << (scol >> 1);
true
}
});
assert_eq!(seen, !(!0 << n));
sorted_scols
}
fn count(n: u32) -> Count {
static ERR: &str = "n is too large";
Count::checked_pow(3, TryFrom::try_from(n * n).expect(ERR)).expect(ERR);
(1..=Coeff::try_from(n).expect(ERR)).fold(1, |x: Coeff, y| x.checked_mul(y).expect(ERR));
let mut cur_sets = vec![0];
let mut cur_set_indexes = vec![0];
let mut cur_states = HashMap::new();
cur_states.insert(vec![1], 1);
for k in 0..n {
for i in 0..n {
let keep_set = |&set: &u32| {
if set.count_ones() == k {
!set & !1 << i & !(!0 << n) != 0
} else {
set & 1 << i == 0
}
};
let enlarge_set = |&set: &u32| set.count_ones() == k && set & 1 << i == 0;
let new_sets: Vec<u32> = cur_sets
.iter()
.copied()
.filter(keep_set)
.chain(
cur_sets
.iter()
.copied()
.filter(enlarge_set)
.map(|set| set | 1 << i),
)
.collect();
let mut new_set_indexes = vec![!0; 1 << n];
for (set_index, &set) in new_sets.iter().enumerate() {
new_set_indexes[set as usize] = set_index;
}
let new_states = Mutex::new(HashMap::new());
cur_states.into_par_iter().for_each(|(cur_state, count)| {
for elt in -1..=1 {
let mut new_state: Vec<Coeff> = cur_sets
.iter()
.copied()
.zip(&cur_state)
.filter(|(set, _)| keep_set(set))
.map(|(_, &coeff)| coeff)
.chain(
cur_sets
.iter()
.copied()
.zip(&cur_state)
.filter(|(set, _)| enlarge_set(set))
.map(|(set, &coeff)| {
let mut new_coeff = coeff * elt;
if set & !(!0 << i) != 0 {
new_coeff +=
cur_state[cur_set_indexes[set as usize | 1 << i]];
}
new_coeff
}),
)
.collect();
let factor = new_state.iter().copied().fold(0, gcd);
if factor > 1 {
for coeff in &mut new_state {
*coeff /= factor;
}
}
let sorted_scols = sort_scols(n, i, &new_sets, &new_state);
let new_state: Vec<Coeff> = new_sets
.iter()
.map(|&set| {
let mut permuted_set = 0;
let mut sign = 0;
for (col, &permuted_scol) in sorted_scols.iter().enumerate() {
sign ^= set >> col & permuted_scol & 1;
permuted_set |= (set >> col & 1) << (permuted_scol >> 1);
}
(1 - 2 * sign as Coeff)
* new_state[new_set_indexes[permuted_set as usize] as usize]
})
.collect();
*new_states.lock().unwrap().entry(new_state).or_insert(0) += count;
}
});
cur_sets = new_sets;
cur_set_indexes = new_set_indexes;
cur_states = new_states.into_inner().unwrap();
}
}
*cur_states.get(&vec![0]).unwrap_or(&0)
}
fn main() {
for n in 1..=6 {
println!("{} {}", n, count(n));
}
}
```
### `Cargo.toml`
```
[package]
name = "permanent"
version = "0.1.0"
authors = ["Anders Kaseorg <[[email protected]](/cdn-cgi/l/email-protection)>"]
edition = "2018"
[dependencies]
num-integer = "0.1.41"
rayon = "1.2.1"
itertools = "0.8.2"
```
### Building and running
```
$ cargo build --release
$ time target/release/permanent
1 1
2 33
3 7555
4 13482049
5 186481694371
6 19733690332538577
5995.30user 282.67system 9:42.97elapsed 1076%CPU (0avgtext+0avgdata 6479028maxresident)k
0inputs+0outputs (0major+3259222minor)pagefaults 0swaps
```
### How it works
This counts matrices using dynamic programming so we don’t need to enumerate all of them directly. Basically, the state of a partially filled matrix is represented by the coefficients of an expression for the permanent as a polynomial in the remaining unfilled elements. Specifically, it corresponds to a partial execution of the following algorithm for calculating the permanent:
\$\operatorname{perm} A = c\_{\{0, 1, \dotsc, n - 1\}}\$, where \$c\_\varnothing = 1\$, \$c\_S = \sum\_{i \in S} c\_{S \smallsetminus \{i\}}a\_{|S| - 1, i}\$ for \$S \ne \varnothing\$.
For example, here’s the \$n = 4\$ calculation written out explicitly:
```
c = 1
c0 = c * a00
c1 = c * a01
c2 = c * a02
c3 = c * a03
c01 = c1 * a10; c02 = c2 * a10; c03 = c3 * a10
c01 += c0 * a11; c12 = c2 * a11; c13 = c3 * a11
c02 += c0 * a12; c12 += c1 * a12; c23 = c3 * a12
c03 += c0 * a13; c13 += c1 * a13; c23 += c2 * a13
c012 = c12 * a20; c013 = c13 * a20; c023 = c23 * a20
c012 += c02 * a21; c013 += c03 * a21; c123 = c23 * a21
c012 += c01 * a22; c023 += c03 * a22; c123 += c13 * a22
c013 += c01 * a23; c023 += c02 * a23; c123 += c12 * a23
c0123 = c123 * a30
c0123 += c023 * a31
c0123 += c013 * a32
c0123 += c012 * a33
return c0123
```
After executing each line, we can forget the filled elements `a…` and represent the current state with just the `c…` variables that are still live. This representation collapses many different partially filled matrices into the same coefficient vector. For example, swapping any two filled rows results in the same coefficient vector.
The `sort_scols` function further collapses the state space by using the symmetries of column permutations and column sign flipping to try to find a canonical representation for each state. It doesn’t do a perfect job, but this imperfection only impacts performance, not correctness.
[Answer]
## C# (\$\textrm{A330134}(5)=186481694371\$ in under 10 seconds)
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
namespace Sandbox
{
// See https://codegolf.stackexchange.com/q/196712
static class Permanent
{
const int numThreads = 12;
static void Main(string[] args)
{
var sw = new System.Diagnostics.Stopwatch();
sw.Start();
for (int n = 1; n < 8; n++)
{
Console.WriteLine($"{n}\t{_PPCG196712_LaplaceMT(n)}\t{sw.ElapsedMilliseconds}ms");
}
}
internal static BigInteger _PPCG196712_LaplaceMT(int n)
{
// If we have a zero row then the permanent is zero.
// If the first zero row is number i then the previous i rows have (3^n)-1 possibilities each, and the remaining ones have 3^n.
BigInteger result = 0;
int threePowN = (int)BigInteger.Pow(3, n);
for (int i = 0; i < n; i++)
{
result += BigInteger.Pow(threePowN - 1, i) * BigInteger.Pow(threePowN, n - i - 1);
}
// Let's call a row containing a permutation of 1^1 0^{n-1} a "singleton row".
// Under Laplace expansion it simplifies to a single {n-1}x{n-1} permanent.
// If we have two singleton rows with the same non-zero index, that {n-1}x{n-1} permanent has a zero row, so the nxn permanent must be zero.
// If we have multiple distinct singleton rows, we still need to worry about double-counting.
// But all this effort would give roughly a 1.5% improvement at n=6, so is probably not worth it.
// Now the interesting rows. We cluster similar rows as a technique to optimise column permutations.
var clusters = new List<Cluster>();
for (int ones = 1; ones <= n; ones++)
for (int negs = 0; negs <= ones && ones + negs <= n; negs++)
clusters.Add(new Cluster(n, ones, negs));
// Consider partitions of n-1 by cluster.
foreach (var partition in PartitionAssignments(clusters, n-1))
{
var subclusters = partition.OrderBy(tuple =>
{
var (cluster, k) = tuple;
// What's the speedup factor of pivoting on this cluster?
return k < cluster.DistinctCounts.Count ? cluster.DistinctCounts[k] / (double)cluster.NaiveCounts[k] : 1;
}).ToList();
// We pivot on the first cluster, and take a Cartesian product.
result += Enumerable.Range(0, numThreads).AsParallel().
Select(threadId => CountByPartition(n, subclusters, 0, new sbyte[n - 1][], 0, 1, threadId)).
Aggregate(BigInteger.Zero, (a, b) => a + b);
}
return result;
}
private static BigInteger CountByPartition(int n, IReadOnlyList<(Cluster cluster, int repeat)> clusters, int clusterIdx, sbyte[][] matrix, int rowIdx, BigInteger weight, int threadId)
{
if (clusterIdx == clusters.Count) return weight * Count_Laplace(matrix) << (n - 1);
int k = clusters[clusterIdx].repeat;
if (clusterIdx == 0 && clusters[0].repeat < clusters[0].cluster.DistinctCounts.Count)
{
// Pivot
weight *= Binom(n - 1, k) * Factorial(n - 1 - k); // Choose the pivoted rows and then permute the others freely
BigInteger sum = 0;
var reps = clusters[0].cluster.Representatives[k];
int delta = reps.Count >= numThreads || clusterIdx == clusters.Count - 1 ? numThreads : 1;
int skip = delta == 1 ? 0 : threadId;
for (int repIdx = skip; repIdx < reps.Count; repIdx += delta)
{
var (prefixWeight, prefix) = reps[repIdx];
for (int i = 0; i < k; i++) matrix[rowIdx + i] = prefix[i];
sum += CountByPartition(n, clusters, clusterIdx + 1, matrix, rowIdx + k, weight * prefixWeight, delta == 1 ? threadId : -1);
}
return sum;
}
{
if (clusterIdx == 0) weight = Factorial(n - 1); // Permute all rows freely
var rows = clusters[clusterIdx].cluster.Rows;
var indices = new int[k];
BigInteger sum = 0;
int skip = threadId > 0 ? threadId : 0;
int delta = threadId >= 0 ? numThreads : 1;
while (true)
{
if (skip == 0)
{
for (int i = 0; i < k; i++)
{
var j = indices[i];
var inRow = rows[j];
matrix[rowIdx + i] = inRow;
}
// Adjust the weight to account for duplicates in this cluster.
var recurWeight = weight;
int currRun = 1;
for (int i = 1; i < k; i++)
{
if (indices[i] == indices[i - 1]) currRun++;
else { recurWeight /= Factorial(currRun); currRun = 1; }
}
recurWeight /= Factorial(currRun);
sum += CountByPartition(n, clusters, clusterIdx + 1, matrix, rowIdx + k, recurWeight, -1);
}
skip--;
if (skip < 0) skip += delta;
if (indices[0] == rows.Count - 1) break;
NextOrderedMultiset(indices, rows.Count);
}
return sum;
}
}
private static IEnumerable<IReadOnlyList<(T, int)>> PartitionAssignments<T>(IReadOnlyList<T> elts, int n)
{
IEnumerable<IReadOnlyList<(T, int)>> Inner(int m, int maxPart, int off, List<(T, int)> prefix, ISet<int> indicesUsed)
{
if (m == 0)
{
yield return new List<(T, int)>(prefix);
yield break;
}
for (int part = Math.Min(m, maxPart); part > 0; part--)
{
// When we reduce the part, we re-enable skipped elts.
for (int i = part == maxPart ? off : 0; i < elts.Count; i++)
{
if (indicesUsed.Contains(i)) continue;
prefix.Add((elts[i], part));
indicesUsed.Add(i);
foreach (var soln in Inner(m - part, part, i + 1, prefix, indicesUsed)) yield return soln;
indicesUsed.Remove(i);
prefix.RemoveAt(prefix.Count - 1);
}
}
}
return Inner(n, n, 0, new List<(T, int)>(), new HashSet<int>());
}
private static void NextOrderedMultiset(int[] indices, int @base)
{
int j = indices.Length - 1;
while (indices[j] == @base - 1) j--;
indices[j]++;
j++;
while (j < indices.Length) { indices[j] = indices[j - 1]; j++; }
}
private static BigInteger Count_Laplace(sbyte[][] matrix)
{
int m = matrix.Length;
int n = m + 1;
BigInteger[] sums = new BigInteger[m];
uint gray = 0;
int sign = 1;
BigInteger[] weights = new BigInteger[n];
for (uint i = 0; i < 1u << n; i++)
{
BigInteger term = 1;
foreach (var sum in sums) term *= sum;
for (int j = 0; j < n; j++)
{
if (((gray >> j) & 1) == 1) weights[j] += sign * term;
}
// Gray code update
int flipPos = (i + 1).CountTrailingZeros();
if (flipPos == n) break;
uint bit = 1u << flipPos;
if ((gray & bit) == bit)
{
for (int j = 0; j < m; j++) sums[j] -= matrix[j][flipPos];
}
else
{
for (int j = 0; j < m; j++) sums[j] += matrix[j][flipPos];
}
gray ^= bit;
sign = -sign;
}
// Count weighted subsets which total zero, optimising with meet-in-the-middle
var distribL = SubsetSums(weights, 0, n >> 1);
var distribR = SubsetSums(weights, n >> 1, n - (n >> 1));
BigInteger total = -1; // Discount the zero column solution
foreach (var kvp in distribL)
{
if (distribR.TryGetValue(-kvp.Key, out var v2)) total += kvp.Value * v2;
}
return total;
}
private static Dictionary<BigInteger, BigInteger> SubsetSums(BigInteger[] weights, int off, int len)
{
var distrib = new Dictionary<BigInteger, BigInteger> { [0] = 1 };
for (int i = 0; i < len; i++)
{
var weight = weights[off + i];
var nextDistrib = new Dictionary<BigInteger, BigInteger>(distrib);
foreach (var kvp in distrib)
{
nextDistrib.TryGetValue(kvp.Key - weight, out var tmp);
nextDistrib[kvp.Key - weight] = tmp + kvp.Value;
nextDistrib.TryGetValue(kvp.Key + weight, out tmp);
nextDistrib[kvp.Key + weight] = tmp + kvp.Value;
}
distrib = nextDistrib;
}
return distrib;
}
class Cluster
{
internal readonly IReadOnlyList<sbyte[]> Rows;
internal readonly IReadOnlyList<int> NaiveCounts;
internal readonly IReadOnlyList<int> DistinctCounts;
internal readonly IReadOnlyList<IReadOnlyList<(int weight, IReadOnlyList<sbyte[]> prefix)>> Representatives;
internal Cluster(int n, int ones, int negs)
{
if (ones == 0) throw new ArgumentOutOfRangeException(nameof(ones));
if (negs > ones) throw new ArgumentOutOfRangeException(nameof(negs));
Rows = BuildRows(n, ones, negs);
// Build pairs and triples, and calculate their advantage factors.
var naiveCounts = new List<int> { 1, Rows.Count };
var distinctCounts = new List<int> { 1, 1 };
var representatives = new List<IReadOnlyList<(int, IReadOnlyList<sbyte[]>)>>
{
new List<(int, IReadOnlyList<sbyte[]>)>{ (1, new List<sbyte[]>()) },
new List<(int, IReadOnlyList<sbyte[]>)>{ (Rows.Count, new List<sbyte[]> { Rows.First() }) }
};
for (int k = 2; k < 4; k++)
{
var counts = new Dictionary<BigInteger, int>();
var reps = new Dictionary<BigInteger, IReadOnlyList<sbyte[]>>();
int uncollapsed = 0;
var indices = new int[k];
while (true)
{
var subset = new sbyte[k][];
for (int i = 0; i < k; i++) subset[i] = Rows[indices[i]];
BigInteger count = Factorial(k);
int currRun = 1;
for (int i = 1; i < k; i++)
{
if (indices[i] == indices[i - 1]) currRun++;
else { count /= Factorial(currRun); currRun = 1; }
}
count /= Factorial(currRun);
uncollapsed += (int)count;
var encoding = CanonicalEncoding(subset);
counts.TryGetValue(encoding, out var oldCount);
counts[encoding] = oldCount + (int)count;
if (oldCount == 0) reps[encoding] = (sbyte[][])subset.Clone();
if (indices[0] == Rows.Count - 1) break;
NextOrderedMultiset(indices, Rows.Count);
}
naiveCounts.Add(uncollapsed);
distinctCounts.Add(reps.Count);
representatives.Add(counts.Select(kvp => (kvp.Value, reps[kvp.Key])).ToList());
}
NaiveCounts = naiveCounts;
DistinctCounts = distinctCounts;
Representatives = representatives;
}
private static List<sbyte[]> BuildRows(int n, int ones, int negs)
{
var rows = new List<sbyte[]>();
void Append(sbyte[] row)
{
// Ensure that we don't have both a row and its negative by testing canonicity.
if (ones > negs || Array.IndexOf(row, (sbyte)1) < Array.IndexOf(row, (sbyte)-1)) rows.Add((sbyte[])row.Clone());
}
var perm = new sbyte[n];
for (int i = 0; i < negs; i++) perm[i] = -1;
for (int i = n - ones; i < n; i++) perm[i] = 1;
while (true)
{
Append(perm);
// Next permutation
int k;
for (k = n - 2; k >= 0; k--)
{
if (perm[k] < perm[k + 1]) break;
}
if (k == -1) return rows;
int l;
for (l = n - 1; l > k; l--)
{
if (perm[k] < perm[l]) break;
}
var tmp = perm[k]; perm[k] = perm[l]; perm[l] = tmp;
for (int i = k + 1, j = n - 1; i < j; i++, j--)
{
tmp = perm[i]; perm[i] = perm[j]; perm[j] = tmp;
}
}
}
private static BigInteger CanonicalEncoding(sbyte[][] rows)
{
return rows.Permutations().Select(_CanonicalEncodingInner).Min();
}
private static BigInteger _CanonicalEncodingInner(sbyte[][] rows)
{
BigInteger @base = BigInteger.Pow(3, rows.Length);
BigInteger[] digits = new BigInteger[rows[0].Length];
for (int i = 0; i < digits.Length; i++)
{
for (int j = 0; j < rows.Length; j++)
{
digits[i] = digits[i] * 3 + rows[j][i] + 1;
}
}
return digits.OrderBy(x => x).Aggregate(BigInteger.Zero, (accum, digit) => accum * @base + digit);
}
}
private static readonly int[] _DeBruijn32 = new int[]
{
0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
};
// Returns 32 for input 0.
public static int CountTrailingZeros(this uint i)
{
if (i == 0) return 32;
int j = (int)i;
i = (uint)(j & -j);
var idx = (i * 0x077CB531U) >> 27;
return _DeBruijn32[idx];
}
public static IEnumerable<T[]> Permutations<T>(this IEnumerable<T> elts)
{
T[] arr = elts.ToArray();
if (arr.Length == 0)
{
yield return arr;
yield break;
}
int[] indices = Enumerable.Range(0, arr.Length).ToArray();
while (true)
{
yield return arr.ToArray();
// Next permutation
int i = indices.Length - 1;
while (i > 0 && indices[i - 1] > indices[i]) i--;
if (i == 0) yield break;
int j = indices.Length - 1;
while (indices[j] < indices[i - 1]) j--;
_DoubleSwap(arr, indices, i - 1, j);
for (j = indices.Length - 1; i < j; i++, j--) _DoubleSwap(arr, indices, i, j);
}
}
private static void _DoubleSwap<T>(T[] elts, int[] indices, int i, int j)
{
var t1 = elts[i];
elts[i] = elts[j];
elts[j] = t1;
var t2 = indices[i];
indices[i] = indices[j];
indices[j] = t2;
}
private static BigInteger Factorial(int n) => n < 2 ? BigInteger.One : n * Factorial(n - 1);
private static BigInteger Binom(int n, int k)
{
BigInteger result = 1;
for (int i = 0; i < k; i++) result = result * (n - i) / (i + 1);
return result;
}
}
}
```
[Online demo](https://tio.run/##5Ttpc@O2kt/9K1Cp3XnkWNJY9ksmiWzleY6Xndq5ynZ2qtarpCgRkiBRoMLDxzr@7dnuBkCCFEHR2dlP68pEEgg0Gn2juzlL@7M44X/@madCLtjlfZrxzejA/jV4HUcRn2UilungZy55Ima1Ge@F/L029DHf4MR0dHAggw1Pt8GMs8tAhtP47uDhgMHfixfsknO2zLJt@uOLF7M45Is4mg/SLJit@d1sGcgFH8zizYvfXwx/@O7l8JiWweNMzNgsCtKUfebJJpBcZvRIwcW/GSCbMSEzJvPN1TLhQZiyM/Y9oGOmwEOeyCAyAG9iEbIPgZBemiVwkusJC5JF6hcLSuj4dxMkLL0FmJLfmkO/EcFCxilASweXWby9DbLZ0vNHlYXpLTwLkqw@Po8T5hHGAHQ4go9T9h18HB767DUcJ4744EsiMg7U5t6/fPMgH/8reziHE9yn3JM@/gLYb6Ngm/Lwg4gikXKgQ5g@btJvrM0e3TR4JRbvYGjBE2YAE0YuIgAL383ZLTAxuOEsYP/Nk5gl8S3Lllzi/9jWMIiJlB4PGgDgxLlIgGMFAJgNnJsCIsIClvAbEecpjMGcVO3qnfwq/f6QbeM0FVMRiUzwlPFgtuwxkDdamPANMBbFM5Zcr4NlVVyswyc8zaMM@HBU5RESIwNp4p/j24/wGKnjl@sGMOyd9IBeDtYKAgkfp0zCB7C2Mq9KXPzTiByesdouJRZ9Nuwx4bPnzimAEMwSOLOGmCUKmhvvefa3lM2CKAJ2IiNAgjJNu4C4maOoxJLFczb8dciOfn2Q/eEjPPwG9T/iGTyDhd/sMPoXGQJp3wfbCG0Bv9sGMkVAImOp2GwjMUfGZTGAUpAYQb5T8AtBGrRIYHYbswoWKbsV2ZJkIAUzxGQs@yRjApC568GDIGveBgCmlkT3WBoTGHknrUmbHIR2yp2SbRDbABfFFo4UCjAPcpbV0OzhTHgCZJech0iF2zhJ7lkwjfOMhXE@jTiY6lzC6sXOTq9gDrIsW4Le8DnIWwbr8yhkCwG7J3G@WEYAjA0H3/4rA2In8Q3f4AHg@PLsOzodLIXxaTCFmTJGAAmQTgDB69t9VBquzAfHAy3oFAP2hYNhBpoAo4GnIgIjSVwgWmZ8tpTi95zj8eJtBhNSmB9H@UbaopUOdiytBppqe/seqHj6Wo2NnYaUdJ1sKX07PUOlw691vauaX75IlZrSN1hFq589U5@HxbBUM5qAkQvSKA/Ow9BDpDW@nuwRpB6t9v3RDnnR2gvUlS24CUEUQW0D@WTTewN3UD8zWjzmIbGKZcAg9tn8OAfzuJDI9NQzuPUQqL/PCJGry6cWD4odBp8SQPTVvZflKN1n453FD43EQZAGix5b@wCTIIwaZwNNvoCigmEiRd6ChuRbNg9mGTANKLMVN3GmrLtSAQ35p0ZoCc/yRLI1GGFDyzdaK1@jgqUD@mA/OR5fryfsBfOUTvpmzscANK2c8COI3c7uj/7gKkbZ9epcN6fk6izqIMYpFnQidxas0dO@Bg7wVAQSdTbMZzWzWPUdbyVGY6DYfHCBQZV31LPiIn9wnoKUgP3gkecPGml2yTEEJJcShO9CYDSjs766L@QL5dqSkh7DTUDs0@l9xq/RAw0n1xMaHvaYgeQ7NjxfLBK@CDLuWV7tP8HK9pgX9NjURxQC0MZpu0vTzFa0aIyBtom4gX0aQqCdE5J56LF3F4D6JxndkxnytF6XbMJpCd/yIPPHrKQHDutf70LwPYowQBO2CSDivNML41t6auFxy8VimfWK6IPo5ojIxLzQKwDDzs5KO0TH8Q1FFFCIGmj4N@2WPYWKz05PmSd1xLATAq1ZCfa63G0yUKce7cHoCI1psf7ILCv1kQbbdHOfxQJV@ox6tPPAnBrjKRlv1BHJAD1n/yR7IoJIjcK/tT8ie7yMY3BUFIEiVPDPyqmp6NL4LjUjhv@BjZxD7BXd7yq5xdY03@xGmMY4AklSm8oWQS44xMEp2HGQ1xuO1qbBmCCbQh5lAQBBWNqmjc/sC9Eff7A2WSEq/GQvaLRquFW6FlvYSe94RuuOYLoR1wYMC4cL6NH2BGRkfp5aaBeDh3oL/yluBqg1F3dftBKpX74my7UCPGn2O01x@1rF7Vpnr5W6gh0SE/SLBPxaOOAhx@EITZazNBMWRw5RNo1xKHZa90rlrZ6tQv7CVv/I@vW4X5lAh2MELFtN6i6pG1TcNzie1fVK6dRnrTIYtZIyuRTmxoSQDpNTaAXMaVYlCPXFjJvQEdhJGtNFMdtEvSDvGAS9Qu2jUas2lgvPaGVdvXZt1lJAaOVlSc67yj0yROGJrGic0rxwj9Q717ihGS6sAJjmhFM/qlwDjqKWAl@vV3sWNCojQXCvezxwPgL5PA9XeLVDi64FGS@mM7qBEYUgAo3EDAKHFKNsO@ocHLSdK@GzPPlidEPBdiNJMUOeJBe5ygp1Y9rwazANZahkGEpS8YtiOd8gdnjYzhwegfN8qBz8hW0VNBiwC/ZJG@yT23KVFmzfHm6mfzXjbCHRaza9LeKHWtvvj9q1@hTtK30zDtFxLpuHR8RDuqYX3t1nU7A86@btPvK7jK53PPyA6YuUZwZYz4LT6Fqe4Fv2h@TvyvvLaS32vqKo2B@PG@@5p1djr7rgagzimOlg3JnW7LThOynhMo9wNgrcJrhDJNSPeD7vseoS7azh/nDJs1MYGhuN@iXlod/Bx24c9rxZke8Fj0JD@CJrUqCj4yKHeKrFDul4bInmMDUACvwhyJaDD0J6m54hDCg4PRyjU8Fv/X7Xo1ACgOOlBc4Dt10djBO1aazPJXKLlGIL8TkyebA/plPInhkMwRsD38iFkwElKDoCdVpStxW1tA85DJAolZp6wvcprypkzlsskmIQ5Y88RAXMcI9Q9v02j1FuiCtFm82rpI3SOKKMkRLsDdgHRWD1f6EMnpFhW3L9qqghnJY9bQQv@Ca@4YTjHiKomeeZllrLhLnMa/tIc5pAHR0svizSFzWl8dXovwXp0mix5/tdEgtUX2q2qdn1hBWWFWXzH9Mg5c4rPkywoqnBey4X2RJpUSWFjhuN/V@R/SfIyvSv6n6mnFl36av6gIa9AiWpouGDp7d3LH9Q0DAiUJ2sfj0RU6Qo6nmTNjphIK9mafx26zkYbmxQuEeOahBsBG7L3B@s8U0tKs0R3CIJ7psLR@iWdoO4yj4qHGzYSk4actx5LUgf5pi26VZYsqgL8cymObismgeIjwR58NRXa56fKX/udgYrhdxK1btWTSbUfYHxPKIluNqVz56hxOLN1lwsSbwg/CGqPieEOjkqcCU/I1gsN7N8G4LENV7X5pHYfo5TKvKhdPjK5FwlgYiEXGAqMvUajA9iXqwFPhYh1s5MYt9UoLdUnNPLmmEqYjzDBUQI/OxIzCZ2bBQ7iJ1Iyb7RE/hxrRGZdEkaYHT/FfE4/Kt4EHl@JbrsTteq18fPfRVQ5VmUkEEkkeZTMNIpWjzQhCzOgoiqfT1TwcK6AxUZN5xnfSH7EJr0NyIMI75TxsLqXyKm7wGXS4J7Ccf2tEArl4PyXndq1tILx1K1TlV6PQ3Ed1kafQwgyJCSMW9Eqi62GFVRxVMX5cCV5xhTu2tN65stWgVzsC5RrDnJ4Cq5/5ln/xFEOff6AGjw7/weyJpndOCbYwgsFKIgFPiYZoKu3xx3SfnT0i6O@Y2g5pYguT8tSWQn4Mc2xZvstRXy45eIy7auEX1@beQ77P7A6PLGhuxxf18BbN7JASAmt9U0RHqN0S9mT5oTaRKClzdPRN5w29/jXapy1NWyWRhVpEkLE@iCqZ0Yqco2W0fEaMG6rq9H6sNKvN8bOXREuPswOqxg9DRsDtuw6eD6bMEroHdRpbA@1Zqm@rB0Dcwdiak2I0xzxnCXrpXQdEQ3ZiqJ@6S1dI@2iq@jp6@uVpieBqCWHhCF6@i5zqiv3WCha4Uc18FN34CuPprOBp3D4HaLmtvoql4ISsxnS@zrQfU9TxY5Jko@5dmnOVWG397N@FalvYINj@e0zneEOdQIMSZkngi1sfMB/y5Upv9VLqIQv9eaJZqr5jQbrqki0TW5BFttUlUvnwXRLI8CVZ0TCQvCmwAovuC6f6AhTUC2rpQou@eE5OUBHe1FmUh7bDaXYUWsmqEMXYuTqmzYq3dFziVrIGSdDam56baCe2De0LoWmwdwA2aPvf8l4JKgDTsAtej5P7EhwoPd/KYbfttVBGvWxyPq@vg7fHS/ilD7kc1Ch9NTqYDRgTvxv90DoZk4TqB4qlxCpKY6Ph0lq6dVwfbWm9ozXrpTCGIlvY86xBou66O/Um/SwKj@QAJwXVYkJi05JivUVYGtXQtY@/8v6i3q4P9XlZY26G6@2OJ6qNtnCdKoVaQ4LAvxnnXGXgcylgKM@ls95ikRaeGpUt5KNGYAlnFhHIWuakYVzrVZiyJpVkEo1uUs5IjNEuWMqQnBBlmmt3x1ssHrCDyg10bW3TLPRfcyz95Sz0VbqaellGW5UMpEW8x3AKp6TFpUNoE41tQcJS3SHNdNa3i1OBszrwiWe4rqOqye@GVXXrda1sdqbOCKPfHvTT0GCFtiTQqAdvx@Uo8SW7Cr3WyrLrQMqv5yJGk1YzQEAQ2RDOa8z7dbLkMj17j@CWWftzLNE676tG85gxD8b5lqqZ7G2VL3qGOcJ4C8EjsGseF5es8y3Zc8UwZDZPcDZ6aRguOxauz94w8IYJPgfvAOO8Q/zT1q/lbY@6BJpy2PsZdWVUapZqNP7MOIUeJuAkZNvCora3VQTkYHXVwnnkJ7T4ShfGd/uGcx5o2QDJWXEywAX6kxRcsCwnUZNOwvB3NkN4Q7w591S9/WWp@Kgr4xkWfdVHHcX8MjKqwnQBf1DdPBk1ab@ugUtTVaZ5CTojF198ZrHzBqOWCkDwgePALphegj@irni/adzRljYlLiTBNpMjJfzFBkhiKdwHCcuyKXa1V2XJVnRflckXz2sIT11ANbOAqDkChwXJmhVYHjV6gutlS2dsOZorqForH//aBCigafrTcoPN94v992tqAip0/FeX/019B2AH0i8hZAVZbcecvpRDea6NpiW9ce7BmKhWgqnlEL2dFEQ@loRhUwUzVsDuy7lzmsUzjqYO1Sq7BRglp@f85OQD10hxwOHLquLI/d2z/1wc2LHXcYO935g9aG/Nks3/TUStWYjwOAnmLroX7y9M6fIummauS/veGvklys5MmxdY@dOLKO6kWD4@/hH/z3A/z6O3zCP5CqE3h4jMM46Vv4hH/Dlz0GT7@vJjJOEAY8GcKqY/yHWRsE9l2PwfAxfAwB0BC2wa/wFEEB2B8OmvIS4N0uiM4pg0OgqAi5hTvIURmdbPNpBGfXJEBBaqg8UsOhKgC3vQogimsG8fbkuKGbf2VeZBS11CeO4xa@t2LPWH/VUJUS1LgN2zxnR3dHL1@@fvXtyfAXH@tPxy9HTblki4fXotJ5bYtBhQR2O9YVRrK2pcMeLyJGZZZq83JR5ore7U0Ac@rwuYoppKtbQ6QfzDL9FbutV7vqWumDgbWjg859VY87jCmbQljzKzwlcr7rDM4QbT/uLpBdYzRjT/e1qditKtRM/exZLfPBxlbnsM8E9q00JqSNtFeI3IjY6omIlR0tpztpmVUjPr@9offDLm@DLUpRz2rwUe@crHyHI3LgthP4tG2xC/6xa4uSBRV1C3WlaJms9ykJ9bFqK3dmQ61nO23fetA8XjU9VnFY/fZBcI9bOsrtRJrVj@Tqd8I9jp/4dliZ@FK9pOj38J39Y/aTHcZ8kpz9yOTu@0X2/ce9i3pNybqwr120bnp9fbi/XmwyrcUa/eW5ev9L@Piuo@qAGXV7s079//HPP/8H)
This employs the following tricks:
* If there's a zero row, the permanent is zero. These can be counted very fast, and then we can assume there's no zero row.
* Multiplying a row by \$-1\$ inverts the sign of the permanent. So we can assume a canonical sign for each row and then multiply by \$2^n\$.
* Permuting the rows leaves the permanent unchanged, so we can assume a canonical permutation of the rows and then multiply by a suitable factor.
* The permanent can be computed in better-than-brute-force time using Ryser's formula with Gray code enumeration of subsets of columns.
* Laplace expansion of the last row turns a factor of \$\frac{3^n - 1}{2}\$ into an instance of the subset sum problem, which can be tackled using dynamic programming with meet-in-the-middle.
* We can also permute columns, which is what `Cluster` is for. I think I've pushed the `Cluster` approach about as far as it can go, but I would like to find an efficient way of replacing it, because if we take the first row `[1, 1, 0, -1, -1, -1]` (with weight 60) then it would be nice to exploit the symmetry of the first two columns and the last three columns in the next cluster. The problem is that doing this naïvely adds a factor of \$n!\$, which is more expensive than the saving.
* The permutations are independent, so after a bit of pre-processing we have an embarrassingly parallel problem.
I compiled with VS2017 Community targetting .Net Framework 4.7.1 and compiled for "Release" with default settings. You may prefer to use .Net Core.
\$n=6\$ is still technically out of range - I calculated it in just under 3 hours on a 4-core AMD with `numThreads = 8`.
[Answer]
# [Wolfram Language(Mathematica)](https://www.wolfram.com/wolframscript/), \$\textrm{A330134}(3)=7555\$ in under 3 seconds
Naive brute force. So slow.
[Try it online!](https://tio.run/##fVDBisIwEL3nKx6eXImoeFvpQVzYU8GDtxAk6ICBJJU0RbH027tTNYssrJBJmJmXee@NN@lE3iR7MH2/cWTi2jl1o1htKXoTKKTSpGgPVG@qJiQt/u@psNf4LARQVsfGkWqNcxnRSa4D4wm@KVA0icBdBFw5/BOEi00n8NxoOZkuJOYSC0w@7n9fpqHArjk7qtXzaTO4kwh6iJXIhHdxfzgGFzhnG5nhYeOFR8LvMVvh17DyGkWBuWa8Fl@V2kbL1VFgRSOmlcPN592WNOtrGcmKl50Wff8D)
```
ClearAll[zeroPermanentMatricesCount]
zeroPermanentMatricesCount[n_] :=
Module[{allMatrices},
(* Generate all n x n matrices with entries -1, 0, 1 *)
allMatrices = Tuples[Tuples[{-1, 0, 1}, n], n];
(* Count matrices with zero permanent *)
Count[allMatrices, m_ /; Permanent[m] == 0]
]
Do[Print["n = ", n, ", ", zeroPermanentMatricesCount[n]], {n, 1, 3}]
```
] |
[Question]
[
## Input:
Two strings (NOTE: the order of input is important).
## Output:
Both words/sentences start on lines with one empty line in between them. They 'walk' horizontally 'next to each other'. But when they have the same character at the same position, they cross each other, and then continue walking 'next to each other'.
Confusing you say? Let's give an example:
Input: `Words crossing over` & `Ducks quacking`:
```
Word quack n
s i g
Duck cross n over
```
[](https://i.stack.imgur.com/wFSpg.png)
*Excuse the bad MS paint..*
## Challenge rules:
* We always first go back walking a straight line after we've 'crossed over' before we can cross over again (see test case above {1} - where `ing` is equal, but after we've crossed on `i`, we first have to go back walking straight (thus ignoring `n`), before we can cross again on `g`).
* The inputs can be of different length, in which case the longer one continues walking in a straight line (see test cases 1, 2, 4 & 6).
* Both inputs can be the same (see test case 3).
* The inputs won't contain any tabs nor new-lines.
* **Spaces are ignored as characters that are the same (as an edge case)**, in which case the next (non-space) character after that - if any - is crossing over instead (see test cases 3, 5 & 6).
* The inputs can have no adjacent (non-space) characters on the same position at all, in which case both just walk in a straight line horizontally (see test cases 2).
* Even if the first character is equal, we always start two lines apart (see test cases 3 & 6).
* Trailing spaces and a single trailing new-line are optional.
* You can assume the inputs will only contain printable ASCII characters (new-lines and tabs excluded).
* The inputs are case-sensitive, so `A` and `a` aren't equal, and won't cross over (see test case 7).
* Both the inputs lengths will always be at least 2.
* Input & output can be in any reasonable format. Can be a single String with new-lines; a String-array/list; printed to STDOUT; 2D array of characters; 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, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code.
* Also, please add an explanation if necessary.
## Test cases:
```
1. Input: "Words crossing over" & "Ducks quacking"
1. Output:
Word quack n
s i g
Duck cross n over
2. Input: "bananas" & "ananas"
2. Output:
bananas
ananas
3. Input: "I see my twin!" & "I see my twin!"
3. Output:
I e y w n
s e m t i !
I e y w n
4. Input: "Is the weather nice?" & "Not really, no.."
4. Output:
Is th ally, no..
e
Not r weather nice?
5. Input: "Codegolf & Programming Puzzles" & "The golfer might solve puzzles"
5. Output:
Code o f & Programming P z l s
g l u z e
The o fer might solve p z l s
6. Input: "Can you turn the lights off?" & "Can you try to solve this?"
6. Output:
C n o urn the ve s off?
a y u t l t
C n o ry to so igh his?
7. Input: "one Ampere" & "two apples"
7. Output:
one Am les
p
two ap ere
8. Input: "Words crossing" & "Words Quacking"
8. Output:
W r s cross n
o d i g
W r s Quack n
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 64 bytes
```
{C←⎕UCS⋄1↓e⊖' '⍪1 0 1⍀⍵⊖⍨≠\e←C(2/⊃l)⎕R(l←C⌽⍳2)C(0@0=⌿⍵)∧' '≠1⌷⍵}
```
[Try it online!](https://tio.run/##XZDNSsNAFIX3PsV1Y1rQmnQvVeKmG61/uHEzptM0dJKJM0lLK4KgFFsbUUTX3SluRVyJ73JfpN6xVWMZmJ8z3zlzGBaLlXqXCelP8Oahuo39W3viKqk17U5dmkg@cPfw@tLB/j3H4aMFFmYvDtjgYHaO2RtpmD3jYHzEiXcL5VUcXogiGXcLwig4@sDstVx0C/a6vYajTzIV8erJJA3GDo7eSTibTN8F7N9Zh1LVNXjmHEQ@yDZXBG@mXkvDScq8FqnWwh9/zCIampjZJndXBc05hF1IOkG0SMickEc1JE0OHc5oURAFHq@QYUsmoDgTorsMkSyV8hZX1rkvRQOWoKakr1gYmsa1tNcT3BTap0ADUF4Y@M0EtBRtDvEMyEexCLoyhSRV0XcPYXgNstEwLX6vFTWXs5ikGehKPkRGHDbCmCtOlqQjgcXx3Dv/P5ewqbDz869f "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~56~~ ~~47~~ 33 bytes
```
y ®m+S éBv ©ZꬩZx ?°B:B=c2)¯3÷y
```
[Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=eSCubStTIOlCdiCpWuqsqVp4ID+wQjpCPWMyKa8zw7d5&input=WyJDYW4geW91IHR1cm4gdGhlIGxpZ2h0cyBvZmY/IiAmICJDYW4geW91IHRyeSB0byBzb2x2ZSB0aGlzPyJd) Takes input as an array of two strings.
I am a total moron... `y ®` is a million times easier to use on two different-length strings than `U¬íV¬@`...
### Explanation
```
y ® m+S éBv © Zê¬ © Zx ?° B:B= c2)¯ 3à · y
y mZ{Zm+S éBv &&Zêq &&Zx ?++B:B=Bc2)s0,3} qR y
Implicit: U = array of two strings
y Transpose U, padding the shorter string with spaces in the process.
mZ{ } Map each pair of chars Z by this function: (we'll call the chars X and Y)
Zm+S Append a space to each char, giving X + " " + Y + " ".
Bv If B is divisible by 2
&&Zêq and Z is a palindrome (X and Y are the same)
&&Zx ? and Z.trim() is not empty (X and Y are not spaces):
++B Increment B. B is now odd; the top and bottom strings are swapping.
: Otherwise:
B=Bc2 Ceiling B to a multiple of 2. (0 -> 0, 1 -> 2, 2 -> 2, etc.)
é ) Rotate the string generated earlier this many chars to the right.
s0,3 Take only the first 3 chars of the result.
qR Join the resulting array of strings with newlines.
y Transpose rows with columns.
Implicit: output result of last expression
```
`B` is a variable that keeps track of which state we're in:
* `B % 4 == 0` means first word on top, but ready to switch;
* `B % 4 == 1` means we've just switched;
* `B % 4 == 2` means second word on top, but ready to switch;
* `B % 4 == 3` means we've just switched back.
`B` happens to be preset to `11`; since `11 % 4 == 3`, the first column always has the first word on top. We increment `B` any time the words swap positions, or any time it's odd (with `B=c2`).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 69 bytes
```
AE⮌θιθAE⮌ηιηW∧θη«A⊟θεA⊟ηδA∧¬∨φ⁼ε ⁼εδφ¿φ«εAθδAηθAδη»«↑↓ε↓↗δ»»¿θ↑↓↑⮌⁺θη
```
[Try it online!](https://tio.run/##bVBLasMwEF3bpxiyGoFzgWQRQttlUhPIAUwsRQIhWR87hOKzq5YsGxe60GLedzQP3tiHbmQIZ@fEU@Gl6fBGB2odRUMqENMz5Fj@Q/NM84l@cSEp4Fm1aCJC4KcssqfWXYqik26LRX@7waL5qj1@W2QVfJm@kQ5pBTvYEUK2SBtHFq2CAbJUVtRWKI@pZEk0uWCZ@fyXdW7n5YsRqHQ0pVz0QPFw75Jsjjx86pfK62c@IlvFvbuJJ/e5bizHMi5mCKxxc8Mf9@qtYDlpLXuXD0iOIXw0Ct66B99bBZ5TkLHFgWbsVK6kfYPX4LQc6CQS7hT2Q9g7@Qs "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
AE⮌θιθAE⮌ηιη Turn the input strings into arrays and reverse them
W∧θη« While both valus still have characters left
A⊟θεA⊟ηδ Extract the next pair of characters
A∧¬∨φ⁼ε ⁼εδφ Determine whether this is a crossing point
¿φ«εAθδAηθAδη If so then print the character and switch the value
»«↑↓ε↓↗δ»» Otherwise print the two characters apart
¿θ↑↓ Move to print any remaining characters accordingly
↑⮌⁺θη Print any remaining characters
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~217~~ 210 bytes
-1 byte thanks to officialaimm
```
a,b=map(list,input())
n=max(len(a),len(b))
c=[' ']*n
a=(a+c)[:n]
b=(b+c)[:n]
for i in range(1,n):
if a[i]==b[i]!=' '==c[i-1]:c[i]=a[i];a[i]=b[i]=' ';a[i:],b[i:]=b[i:],a[i:]
print'\n'.join(map(''.join,[a,c,b]))
```
[Try it online!](https://tio.run/##RY7BTsQwDETv@QrTSxIwSMuxKNoDnxFySKJ2a9R1qjRF9OtLUoS4jMdvRpaXvUyJX4/DYzB3v6iZ1oLEy1aU1oIr@1bzwMprbCNUGI2VIN0jC2@Uf4ra9uxEMCr8@TFlICCG7Pk2qAuy7gXQCN6SMyZUfTD1hjHR0vPF9bHxFr6djVZoedt6h6GpORVPIpZMXOQHy5fPRKza4/LXo/UYMTitj6N79wx72qBsmaFMA8x0m8oKaRyvHSD8F/IOJcGa5q@hFmm9dj8 "Python 2 – Try It Online")
[Answer]
## Haskell, ~~142~~ 138 bytes
```
g(a:b)f(c:d)|f>0,a==c,a>' '=[' ',a,' ']:g d 0b|1<2=[a,' ',c]:g b 1d
g[]_[]=[]
g b f d=g(max" "b)f$max" "d
a&b=[[j!!i|j<-g a 0b]|i<-[0..2]]
```
[Try it online!](https://tio.run/##jZJfa8IwFMXf/RTHIv6BKrpHscrYXgbbcGywh1LGbZvGapt0SapT/O4ubYewsYcSSC6He37nJmRDesey7HLhQ5qHo2QYzePROVlOXfK8yKXlAAPPt5tLrt2DOUeMaXieLW48v5bcqBJDzOIO94MPP/D8oFMJCWKPD3P6cuBYcq@p4g71Q8/3t91uet4uxhxkecE5XYz96WRyEwSXnFIBD7HsAMipePpAUZpXox4FenDepYo1IiW1TgWH3DPloA/nvox2Gp8lRTurO5X5anOc/1khCbt07f8pW/keoBlDfoQ5pKJb2/9I7TAaZsNwYGQPBZFGbFXDnqWBYpRlRxdCTibtcHcyZlxmiSWsleSK8rx6oXV5OmWsueSbjatabFqe8o2BltmeWUrT0i6GBI6yhCmVqOfPKpKGTJJm@muDsq8hfyLMJtWrdgFSMNzmBVOsxpmDBBVF6/l@f5Aa0Ugv179x@QY "Haskell – Try It Online")
How it works:
```
g -- function g constructs a list of lists of three characters
-- the 1st char belongs to the upper line,
-- the 2nd char to the middle line and
-- the 3rd char to the lower line
f -- flag f indicates if crossing is allowed or not
(a:b) (c:d) -- strings to cross
|f>0 -- if crossing is allowed
,a==c -- and both strings start with the same char
,a>' ' -- that is not a space
=[' ',a,' '] -- return space for upper/lower line and char a for the middle line
:g d 0b -- and go on with crossing disabled and strings swapped
|1<2= -- else
[a,' ',c] -- keep chars in their lines and
:g b 1d -- go on with crossing enabled
g[]_[]=[] -- base case: stop when both strings are empty
g b f d= -- if exactly one string runs out of characters
g(max" "b)f$max" "d -- replace it with a single space and retry
a&b= -- main function
i<-[0..2] -- for each line i from [0,1,2]
j<-g a 0b -- walk through the result of a call to g with crossing disabled
j!!i -- and pick the char for the current line
```
[Answer]
# JavaScript (ES6), 112 bytes
```
(a,b,c='',g=([a,...A],[b,...B],w)=>a?w&a==b&a>' '?' '+g(B,A,c+=a):a+g(A,B,1,c+=' '):'')=>g(a,b)+`
`+c+`
`+g(b,a)
```
**Ungolfed:**
```
f=
(a,b, //the inputs
c='', //c will hold the middle sentence
g=([a,...A],[b,...B],w)=> //define a function to walk through the strings
//w will be false if we're at the beginning,
//... or if we've just done a swap
a? //are there any letters left?
w&a==b&a>' '?' '+g(B,A,c+=a): //if we haven't just swapped and the letters match,
//... add the current letter to c
//... and recurse swapping the strings
a+g(A,B,1,c+=' '): //else add a space to c and continue processing
''
)=>
g(a,b)+'\n'+ //call g with a, b
c+'\n'+ //output c
g(b,a) //call g with b, a
```
**Test cases:**
```
f=
(a,b,c='',g=([a,...A],[b,...B],w)=>a?w&a==b&a>' '?' '+g(B,A,c+=a):a+g(A,B,1,c+=' '):'')=>g(a,b)+`
`+c+`
`+g(b,a)
console.log(f('Words crossing over','Ducks quacking'));
console.log('____________');
console.log(f('bananas','ananas'));
console.log('____________');
console.log(f('I see my twin!', 'I see my twin!'));
console.log('____________');
console.log(f('Is the weather nice?', 'Not really, no..'));
console.log('____________');
console.log(f('Codegolf & Programming Puzzles', 'The golfer might solve puzzles'));
console.log('____________');
console.log(f('Can you turn the lights off?', 'Can you try to solve this?'));
console.log('____________');
console.log(f('one Ampere', 'two apples'))
console.log('____________');
console.log(f('Words crossing','Words Quacking'));
console.log('____________');
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 50 bytes
```
{3↑(0,+\2∨/2|{⍵⌈a×1+1,¯1↓⍵}⍣≡a←>⌿2=⌿3↑⍵)⊖⍵⍀⍨¯1*⍳4}
```
[Try it online!](https://tio.run/##XZC/SgNBEMZ7n2JsjJo/JtFWg2iTRiMINjbrZe9yZG/n3L1LuMSAVYiSE4OotdiksxBrQd9kXyTOJqeiLMwu3/y@b4ZloSg2EybQKzqCae07M3NzXz80w9vyzKXa3zTDyWq5kD@tmtF0o3rRN@mbGY/Y52MlXyl8vFTM8I6kgUmfzdUTI8uOGb9Xt6lYK7XWzPWDNaWXJp2SYd2kr1uDmY2f5E5QNTU4Cmm29AA7XOUgtx87bQ3nMXPapOaW5ugZk3Q0tbPHQq6D5hyCBKKuL5ep@0/IKA1Ri0OXM7oUSN/hNWIPMALFmRBJASSWShm9h03uoXBhBRoKPcWCwG7XiHs9we0Gx5RlAYoKfK8VgUbR4RBmQJbCJCQYQxQrOZ8uLKoBXdfO/mkrWhWzhKjl61rmR8lhNwi54kRHXQQWhr/pf3@OiIVw9P1pXw "APL (Dyalog Classic) – Try It Online")
`⍵⍀⍨¯1*⍳4` gives the matrix:
```
Words.crossing.over
...................
Ducks.quacking.....
...................
```
(the dots represent spaces). Its columns will be rotated by different amounts so the first three rows end up looking like the desired result - hence the `3↑` near the beginning. The rest of the algorithm computes the rotation amounts.
Within the parens: `3↑⍵` creates a matrix like
```
Words.crossing.over
Ducks.quacking.....
...................
```
and `2=⌿` compares its rows pairwise, i.e. first string vs second string and
second string vs the all-spaces row.
```
0 0 0 0 1 0 0 0 0 0 0 1 1 1 1 0 0 0 0
0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 1 1 1 1
```
We are interested in where the former is true (1) and the latter false (0), so
we reduce with `>⌿` to get a boolean vector named `a`.
```
0 0 0 0 1 0 0 0 0 0 0 1 1 1 0 0 0 0 0
```
Now, in every stretch of 1-s we need to zero out the even occurrences because
no two twists can occur next to each other. First we obtain a numbering like:
```
0 0 0 0 1 0 0 0 0 0 0 1 2 3 0 0 0 0 0
```
by, loosely speaking, replacing `a[i]` with `a[i]*max(a[i-1]+1, a[i])` until
the result stabilises: `{⍵⌈a×1+1,¯1↓⍵}⍣≡`, and we take that mod 2: `2|`
```
0 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 0 0
```
Now we know where the twists will occur. We copy each `1` to the left - `2∨/`
(pairwise "or"):
```
0 0 0 0 1 1 0 0 0 0 0 1 1 1 1 0 0 0 0
```
and compute the partial sums - `+\`
```
0 0 0 0 1 2 2 2 2 2 2 3 4 5 6 6 6 6 6
```
That gives us the column rotation amounts we needed in the beginning. Modulo 4 is implied.
[Answer]
# [Perl 5](https://www.perl.org/), 211 bytes
```
@a=map[/./g],<>;$b=1;($f,@{$r[$i]})=$a[0][$i]eq$a[1][$i]&&$f&&$a[0][$i]ne$"?(0,$",$a[0][$i],$",$t=$b++):(1,$a[$t%2][$i],$",$a[$b%2][$i]),$i++while$a[0][$i]||$a[1][$i];for$i(0..2){print$r[$_][$i]for 0..$#r;say''}
```
[Try it online!](https://tio.run/##RY7BjoIwEIbv@xSNjgqhYiHhIoua7HmfgJBNSVppgi3bVg1RX327hSgeJvm/@WYy0zHdZs4daHGiXbmJN8cKf@5yqIskD4Djww10CaJ6hAXQklRDZr8@JmNcLoH7ehnJYLYPCIYZnnoj2ALqKAq3QTIIsIv07TzXTw4xiCi6NqJl0/79Pl3LudIgAhLHaXjrtJB2eO5ndF4hL2Cuc0P71erh3BeVqFdnZM9aItsw1IpjYw1SnH9MTvfIKmRUe2F@Rpg/1VmhpHHr7ywmCfkH "Perl 5 – Try It Online")
~~# [Perl 5](https://www.perl.org/), 234 bytes~~
*fixed the bug Kevin pointed out*
```
@a=map[/./g],<>;$l=@{$a[0]}>@{$a[1]}?@{$a[0]}:@{$a[1]};$b=1;@{$r[$_]}=$a[0][$_]eq$a[1][$_]&&$_&&$r[$_-1][1]eq$"&&$a[0][$_]ne$"?($",$a[0][$_],$",$t=$b++):($a[$t%2][$_],$",$a[$b%2][$_])for 0..$l;for$i(0..2){print$r[$_][$i]for 0..$l;say}
```
[Try it online!](https://tio.run/##RY7BisIwFEX38xWhvJEWa20FN3aiwqznC0qQFFINZJKaRKFIf30yL52pLh6ce@5dvF5YtQ3hyOk375t1sT6z/GNfg6LHB/CmZON@goqNh9nsZlNDS6sak23gxEY61RHFdRpEXCzghBcXKzRV7BIU81QLSA4pJPnT5DF4Cu1yme1S1ODfN68Gc/ufs85YUhYFqBoJZIq8yR69ldr//dSAZK@R48MYwifXZDA34m9WE38RRMnzxTtiuu7t2dmBeEOcUXeBG@l@TO@l0S6svrZFWZW/ "Perl 5 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 31 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ζεËN¾Èyðå_Pi¼ë¾É½}yð«S¾._¨}øJ»
```
Port of [*@ETHproductions*'s Japt answer](https://codegolf.stackexchange.com/a/138546/52210), but with two minor differences:
1) I take the input as a 2D list of characters instead of list of strings.
2) The `counter_variable` in 05AB1E is 0 by default, instead of 11 (or 3) like the `B` in Japt, so the `NĀ` is added as additional check inside the map (and I rotate towards the right instead of left).
[Try it online](https://tio.run/##yy9OTMpM/f//3LZzWw93@x1pOLTvcEfl4Q2Hl8YHZB7ac3g1kN95aG8tUOjQ6uBD@/TiD62oPbzD69Du//@jo5XClXSU8oG4CIhTgLgYiBWAOBkqlg8VA@FMIM4D4nSoGpBcGRCngtXG6uA2LRCIS4E4EWpyNoppsbEA) or [verify all test cases](https://tio.run/##nVTBSsNAEP2VmoOnkF8oohc9lIiChxBK2qYxmCY1SVMiFDwqfocg9OKlRVB72PTcX4qT9C0ZQkKlh0d2Z@e9NzuzbRBZA9fOkzTfrXer7K23fRab7CXNPrP3vu6Kn2xJ@1fxu6CQWN6IjdYXH4vs60p856pYdzWxyg3DUO4UVQkIIWFEiAgdwhCxALECLsEnOMgpzhKCXeaaqqFc0GoG9gNTe0TcYmeVmmmqHSplgAS/9o1K6ZaTPfUSPhGqsbGfEFKsY8Kc@Z6UskcyK9uIJd0zgTnWVu0sxLkPwSHi3bKcHtoaIytkKh5QlKUylSJfK4GyzhEcgexgX5DHIJ7iq7M5O1hbuP@kYeY6JvkEePDYD@m21oS6M2@AVHfAidkkJCdhWtN25@ra8nV00KcAJDmhGQrwW6bmNRQVsec@BvbT@o9jWHtIwYFryopc5HTl9QIYycQz9HDK@mqXZcn3Kq0sZE2bunbcH0Bh08a8PvBjN/8A).
**Explanation:**
```
ζ # Zip/transpose (swapping rows/columns) the (implicit) input-list
# with space filler by default to create pairs
ε } # Map each pair `y` to:
Ë # Check if both values in the pair are equal
NĀ # Check if the map-index is not 0
¾È # Check if the counter_variable is even
yðå_ # Check if the pair contains no spaces " "
Pi # If all checks are truthy:
¼ # Increase the counter_variable by 1:
ë # Else:
¾É # Check if the counter_variable is odd
½ # And if it is: increase the counter_variable by 1
} # Close the if-else
yð« # Add a space after both characters in the pair
S # Convert it to a list of characters (implicitly flattens)
¾._ # Rotate this list the counter_variable amount of times towards the right
¨ # And then remove the last character
ø # Zip/transpose; swapping rows/columns
J # Join each inner character-list to a single string
» # Join everything by newlines (and output implicitly)
```
] |
[Question]
[
Everybody has heard of the phrase "be there or be square". So I thought it was time for a challenge about it.
## Input
You will take a full absolute directory address as text as input via STDIN or equivalent.
## Output
If the directory address exists and is valid, your program will move itself to that folder on your computer. If not, it will output via STDOUT or equivalent the following square:
```
+-+
| |
+-+
```
## Requirements
* Standard loopholes are disallowed.
* You may output a single trailing newline if unavoidable.
* Your program must produce no output if it has been moved.
* Your program must be able to run again wherever it has been moved to.
## Assumptions
* You may assume that the input is never empty.
* You may assume the directory never has a filename appended to the end.
* You may assume that the input directory is never the current one.
* You may assume you have permissions to write and execute everywhere.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
[Answer]
# [PowerShell](https://github.com/PowerShell/PowerShell), ~~59~~ ~~62~~ ~~61~~ 60 bytes
```
$z=ls($d=$args)-di;('"+-+
| |
+-+"','mv b.ps1 "$d"')[$?]|iex
```
[Try it online!](https://tio.run/nexus/powershell#yy1T0EvOT0nVK8nM1ysoNlRIApH/Vapsc4o1VFJsVRKL0os1dVMyrTXUlbR1tblqFGq4gLSSuo56bhlEtYKSSoqSuma0in1sTWZqxf@cYgX9ktyC//9BJAA "PowerShell – TIO Nexus")
## Explanation
PowerShell's `Move-Item` cmdlet (`mv`) renames a file as well, so giving it a directory that doesn't exist as the destination just renames the file to that last component instead (as long as the parent exists), so that was no good.
I could use `Test-Path` to determine that the destination exists and is a directory, but it's too long `Test-Path $d -PathT C`.
So instead I'm using `Get-ChildItem` (`ls`) with the (shortened) `-Directory` parameter, and checking `$?` to see if it was successful. The output if there is any is assigned to `$z` so that it isn't seen.
That's done in the form of an array with 2 elements, then indexing into the array with the boolean value of `$?`, which will get coalesced to `0` or `1`, so the first array element is chosen if the destination directory doesn't exist, and second if it does.
The first array element is a string containing the box (quoted); newlines are allowed in strings, even when they're not heredocs. The second element is a string containing the move command.
The result of that array selection gets piped into `Invoke-Expression` (`iex`) to be executed. This is necessary because of I just leave the actual move command in the array, it gets executed no matter what (to populate the array), which defeats the purpose.
[Answer]
# Octave, ~~60~~ ~~57~~ 52 bytes
*8 bytes saved thanks to @Stewie*
```
if~movefile('f.m',input(''))disp("+-+\n| |\n+-+")end
```
This is a script that lives within a file called `f.m`. When run, it will prompt the user for the folder to move the file to. If the folder does not exist and the move operation fails, then `movefile` returns `false` (or `0`) otherwise it returns `true` (or `1`). If it's `false`, we display the string `"+-+\n| |\n+-+"`.
[Answer]
## Batch, 80 bytes
```
@if not "%1"=="" move %0 %1\>nul 2>nul&&%1\%~nx0||(echo +-+&echo ^| ^|&echo +-+)
```
Batch doesn't like it if you move the batch file as it's running, so by invoking `%1\%~nx0` (which is the new name of the batch file) Batch stops looking for the old batch file.
[Answer]
## Bash + coreutils, 54 bytes
```
if [ -d $1 ];then mv $0 $1;else echo "+-+
| |
+-+";fi
```
Simple enough. It does a test to see if the first argument exists, if it exists the program moves itself into the argument, else prints the square.
Does not work on Windows, however it works on Bash on Ubuntu on Windows / WSL. Does not take a drive letter, however I think that has been clarified to be OK.
This account is owned by Mendeleev.
[Answer]
# Bash + coreutils, ~~43~~ 42 bytes
```
mv -t $1 $0 2> >(:)||echo -n '+-+
| |
+-+'
```
This avoids printing the trailing newline via the -n flag to echo.
I'm not quite sure what the OP means by allowing a trailing newline if it's "unavoidable".
If it's acceptable to include a trailing newline, change
```
echo -n '+-+
```
to
```
echo '+-+
```
and save 3 bytes, for 39 bytes total.
[Answer]
# Python 3, 71 bytes
```
from shutil import*
try:move('f',input())
except:print("+-+\n| |\n+-+")
```
It must be in a file named `f`
Fairly simple. It tries to move itself to whatever directory is given to it on STDIN, and if an error occurs it prints the box.
[Answer]
## C 137 bytes
```
#include<dirent.h> g(char *f,char *z){DIR* d=opendir(z);if(d){strcat(z,f);rename(f,z);}else{puts("+-+");puts("| |");puts("+-+");}}
```
Ungolfed version:
```
#include<dirent.h>
g(char *f,char *z)
{
DIR* d=opendir(z);
if(d)
{
strcat(z,f);
rename(f,z);
}
else
{
puts("+-+");
puts("| |");
puts("+-+");
}
}
```
`f` accepts the filename and `z` accepts the directory name. Destination string is a concatenation of `z` and `f`. `rename()` is used to move the file to the new location.
The `main()` would look like this:
```
int main(int argc, char *argv[])
{
g(argv[0]+2,argv[1]); // 1st arg is the Destination string
return 0;
},
```
Can definitely shortened somehow!
[Answer]
# Ruby, 58+12 = 70 bytes
Uses flags `-nrfileutils`. Input is piped in from a file w/o newlines into STDIN.
```
FileUtils.mv$0,File.exist?($_)&&$_ rescue$><<"+-+
| |
+-+"
```
[Answer]
# [Minecraft ComputerCraft Lua](http://github.com/dan200/ComputerCraft), 74 bytes
```
if fs.isDir(...)then fs.move("f",... .."f")else print("+-+\n| |\n+-+")end
```
Filename is hard-coded as "f". This runs on an in-game computer and runs relative to that computer's directory structure. Uses CC Lua's builtin `fs` API.
Ungolfed:
```
local tArgs = { ... } -- '...' is Lua's vararg syntax, similar to python's *args syntax
if fs.isDir(tArgs[1]) then -- Using '...' is like passing all args separately, extra args are usually ignored
fs.move("file", tArgs[1] .. "file") -- '..' is Lua's string concatenation syntax
else
print("+-+\n| |\n+-+") -- print the required output if the directory doesn't exist
end
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 41 bytes
```
{⎕NEXISTS⍵:'f'⎕NMOVE⍨⍵,'f'⋄3 3⍴'+-+| |'}⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT/@vXv2ob6qfa4RncEjwo96tVhpAQkddPU1dXRMk4esf5grmPepuMVYwftS7RV1dW1e7RqFGXb1WXQGkJCA0RAGo4n/ao7YJaIYBhWGGPOpdATY5DckkqEG1//@nKainq3MBSf3S4iL94ozEolR9dQA "APL (Dyalog Unicode) – Try It Online")
filename is hardcoded as `f`, in the current working directory.
] |
[Question]
[
It is time to embark on a perilous quest to defeat the British Intelligence. The aim of this challenge is to write the shortest code that will solve a Nonogram.
# What is a Nonogram?
[](https://i.stack.imgur.com/mdMjdm.png)
>
> The rules are simple.
> You have a grid of squares, which must be either filled in black or left blank. Beside each row of the grid are listed the lengths of the runs of black squares on that row. Above each column are listed the lengths of the runs of black squares in that column. Your aim is to find all black squares. In this puzzle type, the numbers are a form of discrete tomography that measures how many unbroken lines of filled-in squares there are in any given row or column. For example, a clue of "4 8 3" would mean there are sets of four, eight, and three filled squares, in that order, with at least one blank square between successive groups.
> [[1](http://www.puzzle-nonograms.com)][[2](https://en.wikipedia.org/wiki/Nonogram)]
>
>
>
So the solution to the above Nonogram would be:
[](https://i.stack.imgur.com/EbgM8m.png)
# Implementation Details
You can chose to represent the Nonogram however you would like and take it as an input in whatever way you deem fit for your language. Same goes for output. The aim of this challenge is to literally just get the job done; if you can solve the nonogram with whatever output your program gives, that is valid. One caveat is you can't use an online solver :)
This problem is very algorithmically challenging (np-complete) in that there is no completely efficient solution to it and as such, you won't be penalized for not being able to solve larger ones, although your answer will be heavily rewarded if it is able to handle big cases (see bonus). As a benchmark, my solution works for up to roughly 25x25 within 5-10 seconds. To allow for flexibility amongst different languages, solutions that take less than 5 mins for a 25x25 nonogram are good enough.
You may assume a puzzle in always a square NxN nonogram.
You can use [this](http://www.puzzle-nonograms.com) online nonogram puzzle maker to test your solutions.
# Scoring
You are, of course, free to use any language you want and since this is code golf, the entries will be sorted in the order: `accuracy -> length of code -> speed.` However, don't be discouraged by code golfing languages, answers in all languages that show attempts at golfing in an interesting way will be upvoted!
# Bonus
I actually learnt about Nonograms from a cryptographic Christmas card released by the British Intelligence [here](https://www.gchq.gov.uk/news-article/christmas-card-cryptographic-twist-charity). The first part was basically a massive 25x25 Nonogram. If your solution is able to solve this, you will get kudos :)
To make your life easier in terms of data entry, I have provided how I represented the data for this specific puzzle for your free use. The first 25 lines are the row clues, followed by a '-' separator line, followed by 25 lines of the col clues, followed by a '#' separator line, and then a representation of the grid with the square clues filled in.
```
7 3 1 1 7
1 1 2 2 1 1
1 3 1 3 1 1 3 1
1 3 1 1 6 1 3 1
1 3 1 5 2 1 3 1
1 1 2 1 1
7 1 1 1 1 1 7
3 3
1 2 3 1 1 3 1 1 2
1 1 3 2 1 1
4 1 4 2 1 2
1 1 1 1 1 4 1 3
2 1 1 1 2 5
3 2 2 6 3 1
1 9 1 1 2 1
2 1 2 2 3 1
3 1 1 1 1 5 1
1 2 2 5
7 1 2 1 1 1 3
1 1 2 1 2 2 1
1 3 1 4 5 1
1 3 1 3 10 2
1 3 1 1 6 6
1 1 2 1 1 2
7 2 1 2 5
-
7 2 1 1 7
1 1 2 2 1 1
1 3 1 3 1 3 1 3 1
1 3 1 1 5 1 3 1
1 3 1 1 4 1 3 1
1 1 1 2 1 1
7 1 1 1 1 1 7
1 1 3
2 1 2 1 8 2 1
2 2 1 2 1 1 1 2
1 7 3 2 1
1 2 3 1 1 1 1 1
4 1 1 2 6
3 3 1 1 1 3 1
1 2 5 2 2
2 2 1 1 1 1 1 2 1
1 3 3 2 1 8 1
6 2 1
7 1 4 1 1 3
1 1 1 1 4
1 3 1 3 7 1
1 3 1 1 1 2 1 1 4
1 3 1 4 3 3
1 1 2 2 2 6 1
7 1 3 2 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 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 1 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 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 1 0 0 1 0 0 0 1 1 0 0 1 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 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 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 0 1 0 0 0 0 1 0 0 0 1 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 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 1 0 0 0 0 1 1 0 0 0 0 1 0 0 0 0 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 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
```
And here is a slightly different version for your convenience; a comma separated tuple (row, col) where each element is list of lists.
```
([[7, 3, 1, 1, 7],
[1, 1, 2, 2, 1, 1],
[1, 3, 1, 3, 1, 1, 3, 1],
[1, 3, 1, 1, 6, 1, 3, 1],
[1, 3, 1, 5, 2, 1, 3, 1],
[1, 1, 2, 1, 1],
[7, 1, 1, 1, 1, 1, 7],
[3, 3],
[1, 2, 3, 1, 1, 3, 1, 1, 2],
[1, 1, 3, 2, 1, 1],
[4, 1, 4, 2, 1, 2],
[1, 1, 1, 1, 1, 4, 1, 3],
[2, 1, 1, 1, 2, 5],
[3, 2, 2, 6, 3, 1],
[1, 9, 1, 1, 2, 1],
[2, 1, 2, 2, 3, 1],
[3, 1, 1, 1, 1, 5, 1],
[1, 2, 2, 5],
[7, 1, 2, 1, 1, 1, 3],
[1, 1, 2, 1, 2, 2, 1],
[1, 3, 1, 4, 5, 1],
[1, 3, 1, 3, 10, 2],
[1, 3, 1, 1, 6, 6],
[1, 1, 2, 1, 1, 2],
[7, 2, 1, 2, 5]],
[[7, 2, 1, 1, 7],
[1, 1, 2, 2, 1, 1],
[1, 3, 1, 3, 1, 3, 1, 3, 1],
[1, 3, 1, 1, 5, 1, 3, 1],
[1, 3, 1, 1, 4, 1, 3, 1],
[1, 1, 1, 2, 1, 1],
[7, 1, 1, 1, 1, 1, 7],
[1, 1, 3],
[2, 1, 2, 1, 8, 2, 1],
[2, 2, 1, 2, 1, 1, 1, 2],
[1, 7, 3, 2, 1],
[1, 2, 3, 1, 1, 1, 1, 1],
[4, 1, 1, 2, 6],
[3, 3, 1, 1, 1, 3, 1],
[1, 2, 5, 2, 2],
[2, 2, 1, 1, 1, 1, 1, 2, 1],
[1, 3, 3, 2, 1, 8, 1],
[6, 2, 1],
[7, 1, 4, 1, 1, 3],
[1, 1, 1, 1, 4],
[1, 3, 1, 3, 7, 1],
[1, 3, 1, 1, 1, 2, 1, 1, 4],
[1, 3, 1, 4, 3, 3],
[1, 1, 2, 2, 2, 6, 1],
[7, 1, 3, 2, 1, 1]])
```
[Answer]
## Haskell, ~~242 230 201 199 177 163 160 149~~ 131 bytes
```
import Data.Lists
m=map
a#b=[x|x<-m(chunk$length b).mapM id$[0,1]<$(a>>b),g x==a,g(transpose x)==b]
g=m$list[0]id.m sum.wordsBy(<1)
```
Finally under 200 bytes, credit to @Bergi. Huge thanks to @nimi for helping almost halving the size.
Wow. Almost at half size now, partly because of me but mainly because of @nimi.
The magic function is `(#)`. It finds **all** solutions of a given nonogram.
This is able to solve all cases, but may be super slow, since it's complexity is about `O(2^(len a * len b))`. A quick benchmark revealed 86GB allocated for a 5x5 nonogram.
Fun fact: It works for all nonograms, not only square ones.
---
How it works:
* `a#b`: Given lists of lists of integers which represent the number of squares, generate all grids (`map(chunk$length b).mapM id$a>>b>>[[0,1]]`) and filter the results to keep only the valid ones.
* `g`: Given a potential nonogram it sums the runs of 1's horizontally.
[Answer]
# [Brachylog](http://github.com/JCumin/Brachylog), ~~70~~ 69 bytes
```
[R:C]hlL~l:L:1f=.:3aR,.z:3aC,
tL,?he##ElL,E:2a
.<2,_1<
@b:4f:la
e.h1,
```
This takes a list of two lists (first the rows indicators, then the column ones). Each indicator is itself a list (for situtions like `[3,1]` on one row).
This version takes about 3 minutes to solve the 5 by 5 example of the challenge.
## Way more efficient version, 91 bytes
```
[R:C]hlL~l:L:1f:Cz:3az:Rz:3a=.:4aR,.z:4aC,
tL,?he##ElL,E:2a
.<2,_1<
:+a#=,?h
@b:5f:la
e.h1,
```
[Try it online!](http://brachylog.tryitonline.net/#code=W1I6Q11obEx-bDpMOjFmOkN6OjNhJFw6Uno6M2E9Ljo0YVIsLiRcOjRhQywKdEwsP2hlIyNFbEwsRToyYQouPDIsXzE8CjorYSM9LD9oCkBiOjVmOmxhCmUuaDEs&input=W1tbMl06WzNdOlszXTpbMzoxXTpbMV1dOltbMl06WzNdOls0XTpbMl06WzJdXV0&args=Wg)
This one is not complete brute force: the only difference is that this one imposes constraints on the values of cells such that the number of 1s in each row and column matches the numbers given as indicators in the input. The only brute force part is then in finding the one grid with those constraints for which the "blocks" of 1s match what is given as indication.
This one takes about 0.05 seconds on the 5 by 5 example of the challenge. This is still way too slow for the bonus case, as I have no idea how to express the blocks of ones separated by one or more zeroes in terms of constraints.
### Explanation
I will explain below the 93 bytes version. The only difference between the two is the call to predicate 3 which doesn't exist in the 70 bytes version, and the numbering of the predicates (since there is one less).
* Main predicate:
```
[R:C] Input = [R, C]
hlL The length of R is L
~l Create a list of length L
:L:1f Each element of that list is a sublist of length L with cells 0 or 1 (Pred 1)
%%% Part unique to the 93 bytes version
:Cz Zip the rows of the list of lists with C
:3a The sum of 1s in each row is equal to the sum of the indicators (Pred 3)
z Transpose
:Rz Zip the columns of the list of lists with R
:3a The sum of 1s in each column is equal to the sum of the indicators (Pred 3)
%%%
=. Assign values to the cells of the list of lists which satisfy the constraints
:4aR, The blocks of 1s must match the indicators on rows
.z Transpose
:4aC, The blocks of 1s must match the indicators on columns
```
* Predicate 1: Forces the rows to have a specific length, and that each cell is 0 or 1.
```
tL, L is the length given as second element of the input
?he Take an element from the list
##ElL, That element E is itself a list of length L
E:2a The elements of E are 0s and 1s (Pred 2)
```
* Predicate 2: Constrain a variable to be either 0 or 1
```
.<2, Input = Output < 2
_1< Output > -1
```
* Predicate 3: The sum of 1s in a list must be equal to the sum of indicators (e.g. if the indicator is [3:1] then the list must have sum 4)
```
:+a Sum the elements of the list and sum the indicator
#=, Both sums must be equal
?h Output is the list
```
* Predicate 4: Check that blocks of 1s match the indicator
```
@b Split the list in blocks of the same value
:5f Find all blocks of 1s (Pred 5)
:la The list of lengths of the blocks results in the indicator (given as output)
```
* Predicate 5: True for blocks of 1s, false otherwise
```
e. Output is an element of the input
h1, Its first value is 1
```
[Answer]
# Pyth, ~~91~~ ~~72~~ 71 bytes
```
D:GHdRq@@QdG.nCf.)TrH8V^,01^hQ2=TcNhQ=Y1VhQ=*Y*:H@TH1:H@CTH2)IYjbmjkdTb
```
A program that takes input of a list of the form `[size, [horizontal clues], [vertical clues]]` where each clue is a list of integers (empty clues are the empty list, `[]`), and prints every solution, newline separated, in the form of a binary grid where `1` is shaded and `0` is unshaded.
This is a brute force, so is roughly `O(2^n^2)`. It starts taking a very long time for larger puzzles, but will solve any arbritrary size given sufficient time.
[Try it online](https://pyth.herokuapp.com/?code=D%3AGHdRq%40%40QdG.nCf.%29TrH8V%5E%2C01%5EhQ2%3DTcNhQ%3DY1VhQ%3D%2aY%2a%3AH%40TH1%3AH%40CTH2%29IYjbmjkdTb&input=%5B3%2C%5B%5B1%2C1%5D%2C%5B3%5D%2C%5B1%5D%5D%2C%5B%5B3%5D%2C%5B1%5D%2C%5B2%5D%5D%5D&debug=0)
**How it works**
The program generates every possible layout by taking the repeated Cartesian product of `[0, 1]` with a length equal to `size^2`. This is then split into chunks, giving a list for each horizontal line. Each line is run-length encoded, filtered by the presence of `1` and flattened, leaving the clue for that line. This is then checked against the input. The above process is repeated for the transpose of the chunks, checking the vertical lines. If there is a hit, each chunk is concatenated, and the concatenated chunks are joined on newlines and implicitly printed, with a trailing newline.
```
D:GHdRq@@QdG.nCf.)TrH8V^,01^hQ2=TcNhQ=Y1VhQ=*Y*:H@TH1:H@CTH2)IYjbmjkdTb Program. Input: Q
hQ Q[0], size
^ 2 Square
,01 [0, 1]
^ Cartesian product
V ) For N in the Cartesian product:
cNhQ Split N into Q[0] chunks
=T Assign that to T
=Y1 Y=1
VhQ For H in range [0, Q[0]-1]:
D:GHd def :(G, H, d)
rH8 Run-length-encode(H)
f.)T Filter by presence of 1 in character part
.nC Transpose and flatten, giving the clue
@@QdG Q[d][G], the relevant input clue
Rq Return clue==input clue
:H@TH1 :(H, T, 1)
:H@CTH2 :(H, transpose(T), 2)
=*Y* Y=Y*product of above two
IY If Y:
mjkdT Conacatenate each element of T
jb Join on newlines
b Add a newline and implicitly print
```
*Thanks to @Pietu1998 for some tips*
[Answer]
## Javascript (ES6), ~~401~~ ~~386~~ 333 bytes
This is an early attempt. It's not very efficient but I was curious to test a solution using regular expressions on the binary representation of the rows and columns.
For example, it will translate the clue `[3,1]` into the following regular expression:
```
/^0*1{3}0+1{1}0*$/
```
Right now, this version is not taking square clues into account. I will probably add this later.
### Code
```
(c,r)=>{W=c.length;w=[];S=0;M=(n,p)=>eval(`/^0*${p.map(v=>`1{${v}}`).join`0+`}0*$/`).exec(n);R=(y,i=0)=>S||(w[y]=r[y][i],y+1<W?R(y+1):c.every((c,y)=>(n=0,w.map((_,x)=>n+=w[W-1-x][y]),M(n,c)))&&(S=w.join`
`),r[y][i+1]&&R(y,i+1));r=r.map(r=>[...Array(1<<W)].map((_,n)=>((1<<30)|n).toString(2).slice(-W)).filter(n=>M(n,r)));return R(0)}
```
### Output
The solution is displayed in binary format. Such as:
```
00110
01110
11100
11101
00001
```
### Test
This is a simple test on the example grid.
```
let f =
(c,r)=>{W=c.length;w=[];S=0;M=(n,p)=>eval(`/^0*${p.map(v=>`1{${v}}`).join`0+`}0*$/`).exec(n);R=(y,i=0)=>S||(w[y]=r[y][i],y+1<W?R(y+1):c.every((c,y)=>(n=0,w.map((_,x)=>n+=w[W-1-x][y]),M(n,c)))&&(S=w.join`
`),r[y][i+1]&&R(y,i+1));r=r.map(r=>[...Array(1<<W)].map((_,n)=>((1<<30)|n).toString(2).slice(-W)).filter(n=>M(n,r)));return R(0)}
console.log(f(
[[2],[3],[4],[2],[2]],
[[2],[3],[3],[3,1],[1]]
));
```
[Answer]
## Haskell, 109 bytes
Disclaimer: this is derived from [@ThreeFx's answer](https://codegolf.stackexchange.com/a/91700/34531). I helped him to golf down his answer but he seems to have lost interest to include my last substantial improvements, so I post them as new answer.
```
import Data.List
n=mapM id
a#b=[x|x<-n$(n$" #"<$a)<$b,g x==a,g(transpose x)==b]
g=map$max[0].map length.words
```
Usage example: `[[2],[3],[3],[3,1],[1]] # [[2],[3],[4],[2],[2]]` -> `[[" ## "," ### ","### ","### #"," #"]]`.
Brute force. Try all combinations of and `#`, split int chunks of `#`, count the lengths and compare to the input.
[Answer]
# PHP, ~~751~~ ~~833 (720)~~ ~~753~~ ~~724~~ ~~726~~ ~~710~~ ~~691~~ ~~680~~ 682 bytes
I was eager to build a specialised sequence increment and try my cartesian generator once more;
but dropped the cartesian in favour of backtracking to solve the large puzzle faster.
```
$p=[];foreach($r as$y=>$h){for($d=[2-($n=count($h)+1)+$u=-array_sum($h)+$w=count($r)]+array_fill($i=0,$n,1),$d[$n-1]=0;$i<1;$d[0]+=$u-array_sum($d)){$o=$x=0;foreach($d as$i=>$v)for($x+=$v,$k=$h[$i];$k--;)$o+=1<<$x++;if(($s[$y]|$o)==$o){$p[$y][]=$o;$q[$y]++;}for($i=0;$i<$n-1&$d[$i]==($i?1:0);$i++);if(++$i<$n)for($d[$i]++;$i--;)$d[$i]=1;}}
function s($i,$m){global$c,$w,$p;for(;!$k&&$i[$m]--;$k=$k&$m<$w-1?s($i,$m+1):$k){for($k=1,$x=$w;$k&&$x--;){$h=$c[$x];for($v=$n=$z=$y=0;$k&&$y<=$m;$y++)$n=$n*($f=($p[$y][$i[$y]]>>$x&1)==$v)+$k=$f?:($v=!$v)||$n==$h[$z++];if($k&$v)$k=$n<=$h[$z];}}return$k?is_array($k)?$k:$i:0;}
foreach(s($q,0)as$y=>$o)echo strrev(sprintf("\n%0{$w}b",$p[$y][$o]));
```
* expects hints in arrays `$r` for row hints, `$c` for column hints and `$s` for square hints.
* throws `invalid argument supplied for foreach` if it finds no solution.
* to get the correct byte count, use a physical `\n` and remove the other two line breaks.
**description**
1) from row hints
generate possible rows that satisfy the square hints
and remember their counts for each row index.
2) backtrack over the row combinations:
If the combination satisfies the column hints,
seek deeper or return successful combination,
else try next possibility for this row
3) print solution
---
The last golfing had severe impact on the performance;
but I removed profiling assignments for the final benchmarks.
Replace `$n=$n*($f=($p[$y][$i[$y]]>>$x&1)==$v)+$k=$f?:($v=!$v)||$n==$h[$z++];`
with `if(($p[$y][$i[$y]]>>$x&1)-$v){$k=($v=!$v)||$n==$h[$z++];$n=1;}else$n++;`
to undo the last golfing step.
**examples**
For the small example (~~17 to 21~~ around ~~12~~ ~~8~~ ~~7~~ ~~6.7~~ 5.3 ms), use
```
$r=[[2],[3],[3],[3,1],[1]];$c=[[2],[3],[4],[2],[2]];$s=[0,0,0,0,0];
```
for the christmas puzzle:
* killed my small home server with the old solution
* killed the browser with test outputs
* now solved in ~~50~~ ~~37.8~~ ~~45.5~~ around 36 seconds
put data from question to a file `christmas.nonogram` and use this code to import:
```
$t=r;foreach(file('christmas.nonogram')as$h)if('-'==$h=trim($h))$t=c;elseif('#'==$h){$t=s;$f=count($h).b;}else
{$v=explode(' ',$h);if(s==$t)for($h=$v,$v=0,$b=1;count($h);$b*=2)$v+=$b*array_shift($h);${$t}[]=$v;}
```
---
**breakdown**
```
$p=[]; // must init $p to array or `$p[$y][]=$o;` will fail
foreach($r as$y=>$h)
{
// walk $d through all combinations of $n=`hint count+1` numbers that sum up to $u=`width-hint sum`
// (possible `0` hints for $h) - first and last number can be 0, all others are >0
for(
$d=[2-
($n=count($h)+1)+ // count(0 hint)=count(1 hint)+1
$u=-array_sum($h)+$w=count($r) // sum(0 hint) = width-sum(1 hint)
] // index 0 to max value $u-$n+2
+array_fill($i=0,$n,1) // other indexes to 1
,$d[$n-1]=0; // last index to 0
// --> first combination (little endian)
$i<1; // $i:0 before loop; -1 after increment; >=$n after the last combination
$d[0]+=$u-array_sum($d) // (see below)
)
{
// A: create row (binary value) from 1-hints $h and 0-hints $d
$o=$x=0;
foreach($d as$i=>$v)
for($x+=$v,$k=$h[$i];$k--;)
$o+=1<<$x++;
// B: if $o satisfies the square hints
if(($s[$y]|$o)==$o)
{
$p[$y][]=$o; // add to possible combinations
$q[$y]++; // increase possibility counter
}
// C: increase $d
// find lowest index with a value>min
// this loop doesn´t need to go to the last index:
// if all previous values are min, there is nothing left to increase
for($i=0;$i<$n-1&$d[$i]==($i?1:0);$i++);
if(++$i<$n) // index one up; increase $d if possible
for($d[$i]++ // increase this value
;$i--;)$d[$i]=1; // reset everything below to 1
// adjust $d[0] to have the correct sum (loop post condition)
}
}
// search solution: with backtracking on the row combinations ...
function s($i,$m)
{
global $c,$w,$p;
for(;
!$k // solution not yet found
&&$i[$m] // if $i[$m]==0, the previous iteration was the last one on this row: no solution
--; // decrease possibility index for row $m
$k=$k&$m<$w-1? s($i,$m+1) : $k // if ok, seek deeper while last row not reached ($m<$w-1)
)
{
// test if the field so far satisfies the column hints: loop $x through columns
for($k=1,$x=$w;$k&&$x--;) // ok while $k is true
{
$h=$c[$x];
// test column hints on the current combination: loop $y through rows up to $m
for($v=$n=$z= // $v=temporary value, $n=temporary hint, $z=hint index
$y=0;$k&&$y<=$m;$y++)
// if value has not changed, increase $n. if not, reset $n to 1
// (or 0 for $k=false; in that case $n is irrelevant)
$n=$n*
// $f=false (int 0) when value has changed, true (1) if not
($f=($p[$y][$i[$y]]>>$x&1)==$v)
+$k=$f?: // ok if value has NOT changed, else
($v=!$v) // invert value. ok if value was 0
|| $n==$h[$z // value was 1: ok if temp hint equals current sub-hint
++] // next sub-hint
;
// if there is a possibly incomplete hint ($v==1)
// the incomplete hint ($n) must be <= the next sub-hint ($c[x][$z])
// if $n was <$h[$z] in the last row, the previous column hints would not have matched
if($k&$v)$k=$n<=$h[$z];
}
// ok: seek deeper (loop post condition)
// not ok: try next possibility (loop pre condition)
}
return$k?is_array($k)?$k:$i:0; // return solution if solved, 0 if not
}
// print solution
foreach(s($q,0)as$y=>$o)echo strrev(sprintf("\n%0{$w}b",$p[$y][$o]));
```
] |
[Question]
[
A [Gaussian integer](https://en.wikipedia.org/wiki/Gaussian_integer) is a complex number whose real and imaginary parts are integers.
Gaussian integers, like ordinary integers, can be represented as a product of Gaussian primes, in a unique manner. The challenge here is to calculate the prime constituents of a given Gaussian integer.
Input: a Gaussian integer, which is not equal to 0 and is not a [unit](https://en.wikipedia.org/wiki/Unit_(ring_theory)) (i.e. 1, -1, i and -i can not be given as inputs). Use any sensible format, for example:
* 4-5i
* -5\*j+4
* (4,-5)
Output: a list of Gaussian integers, which are prime (i.e. no one of them can be represented as a product of two non-unit Gaussian integers), and whose product is equal to the input number. All numbers in the output list must be non-trivial, i.e. not 1, -1, i or -i. Any sensible output format can be used; it should not necessarily be the same as input format.
If the output list has more than 1 element, then several correct outputs are possible. For example, for input 9 the output can be [3, 3] or [-3, -3] or [3i, -3i] or [-3i, 3i].
Test cases, (taken from [this table](https://en.wikipedia.org/wiki/Table_of_Gaussian_integer_factorizations); 2 lines per test case)
```
2
1+i, 1-i
3i
3i
256
1+i,1+i,1+i,1+i,1+i,1+i,1+i,1+i,1+i,1+i,1+i,1+i,1+i,1+i,1+i,1+i
7+9i
1+i,2‚àíi,3+2i
27+15i
1+i,3,7‚àí2i
6840+585i
-1-2i, 1+4i, 2+i, 3, 3, 6+i, 6+i
```
Built-in functions for factoring Gaussian integers are not allowed. Factoring ordinary integers by built-in functions is allowed though.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~258~~ ~~256~~ ~~249~~ 246+8 = ~~264~~ ~~257~~ 254 bytes
Uses the `-rprime` flag.
Geez, what a mess.
[Uses this algorithm from stackoverflow.](https://stackoverflow.com/questions/2269810/whats-a-nice-method-to-factor-gaussian-integers)
```
->c{m=->x,y{x-y*eval("%d+%di"%(x/y).rect)};a=c.abs2.prime_division.flat_map{|b,e|b%4<2?(1..e).map{k=(2..d=b).find{|n|n**(~-b/2)%b==b-1}**(~-b/4)%b+1i;d,k=k,m[d,k]while k!=0;c/=d=m[c,d]==0?d:d.conj;d}:(c/=b<3?(b=1+1i)**e:b**e/=2;[b]*e)};a[0]*=c;a}
```
[Try it online!](https://tio.run/##LY/raoNAGERfJQ0Iu6uul5oSNF98ECviXmy3XtFNqqh99FoT@mcGzsDA6W9s2gp43@wrn2uwr6M1zaM9EXnPK3Q0hGkIdTTQ6EyY9pJrvEY5cJqzwaddr2qZCXVXg2obWlS5zuq8mxdmyYUZwcWPkUepxPRBS0A@pQIYpoVqxLw0S0MI@rGZ42ODATDbW/9BsAPTU5GwSiitOtk7/f5UlTyUL@BG3AEBdcItkQK4sQgF5W3zFYk1RPvGLq8xYuDtD5gQGbI9HPCjhKVEPgQSNyXAo3zdupseDkXytP2QesBUtxlPt7dz4Jqn80n9tp3e5YbN7p@6fw "Ruby – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~250~~ ~~239~~ ~~223~~ 215 bytes
```
e,i,w=complex,int,abs
def f(*Z):
if Z:
z=Z[0];q=i(w(z));Q=4*q*q
while Q>0:
a=Q/q-q;b=Q%q-q;x=e(a,b)
if w(x)>1:
y=z/x
if w(y)>1 and y==e(i(y.real),i(y.imag)):f(x,y);z=Q=0
Q-=1
if z:print z
f(*Z[1:])
```
[Try it online!](https://tio.run/##VY7BboMwEETP@Ct8qeQF0wBJEwHa/IOvRDk4jd04IgTSSGD/PLVbtSqn3Xk7O5rePi/3rphnxQ0f8f1@61s1cdM9uTx9krPSVLO4gYpQo2lTkchhc8iO9YCGjcwB1AI38RAPJBovplVU7DNvjqhEsRrSoT6heAlzQsUkP0G4@aiRTbDPfV5k0a0mP7@h9ZDK7kwter9h9vWhZAs8bOYmPwAqzSZuoXYoMAthIsWchG9X9Q9fnDoShc6HvDrCrFkB9Q@nRLO0SNbr6y/xYCF2SXn97y52Sf62IGWZbBdgu/lT8xc "Python 2 – Try It Online")
* -11 bytes when using *Multiple Function Arguments*
* -2²\*² bytes when using one variable to parse couples `(a,b)`
* -2³ bytes when mixing tabs and spaces: thanks to ovs
**Some explanation** recursively decompose a complex to two complexes until no decomposition is possible...
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~61~~ ~~55~~ 50 bytes
```
ÆiḤp/-,1p`¤×€×1,ıFs2S€⁸÷ÆiḞƑ$ƇỊÐḟ1;Ṫð,÷@\ḟ1
Ç€F$ÐL
```
[Try it online!](https://tio.run/##y0rNyan8f3TSw50zjk5@uHPxo4Y5hlmPGuaCMUxE2wDEfbirDyagCxN4uGM@kBsdq6GpABR41LgvK7Py/@G2zIc7lhTo6@oYFiQcWnJ4@qOmNYenG@oc2ehWbBQM5Dxq3HF4O1jVvGMTVY61P9zddXgC0ChD64c7Vx3eoHN4u0MMiMt1uB2o2k3l8ASf/zqH2w9PBPL8gTbPsTq09dDWRw0zHu7uAdJNayL//482AroyVifaQNsYRBmZmkH45tqWYL65tqFpViwA "Jelly – Try It Online") (Header and Footer formats the output)
*-6 bytes thanks to @EricTheOutgolfer*
*-5 bytes thanks to @caird coinheringaahing*
**How it Works**
```
ÆiḤp/-,1p`¤×€×1,ıFs2S€⁸÷ÆiḞƑ$ƇỊÐḟ1;Ṫð,÷@\ḟ1 - helper: outputs a factor pair of the input
ÆiḤp/ - creates a list of possible factors a+bi, a,b>=0
-,1p`¤×€ - extend to the other three quadrants
×1,ıFs2S€ - convert to actual complex numbers
⁸÷ - get quotient with input complex number
ÆiḞƑ$Ƈ - keep only Gaussian numbers (those unchanged when complex parts are floored)
ỊÐḟ - remove units (i,-i,1,-1)
1; - append a 1 to deal with primes having no non-unit factors
·π™√∞,√∑@\ - convert to a factor pair
ḟ1 - remove 1s
Ç€F$ÐL
Ç€ - factor each number
$ - and
F - flatten the list
ÐL - until factoring each number and flattening does not change the list
```
[Answer]
# [Rust](https://rust-lang.org) - 212 bytes
```
use num::complex::Complex as C;fn f(a:&mut Vec<C<i64>>){for _ in 0..2{for x in -999..0{for y in 1..999{for i in 0..a.len(){let b=C::new(x,y);if(a[i]%b).norm_sqr()==0&&(a[i]/b).norm_sqr()>1{a[i]/=b;a.push(b)}}}}}}
```
I'm not 100% sure if this works 100% correct, but it seems to be correct for a large range of tests. This isn't smaller than Jelly, but at least it is smaller than the interpreted languages (so far). It also seems to be faster and can work through inputs of a billion magnitude in less than a second. For example 1234567890+3141592650i factors as (-9487+7990i)(-1+-1i)(-395+336i)(2+-1i)(1+1i)(3+0i)(3+0i)(4+1i)(-1+1i)(-1+2i), [(click here to test on wolfram alpha)](https://www.wolframalpha.com/input/?i=(-9487%2B7990i)(-1%2B-1i)(-395%2B336i)(2%2B-1i)(1%2B1i)(3%2B0i)(3%2B0i)(4%2B1i)(-1%2B1i)(-1%2B2i))
This started out as the same idea as naive factoring of integers, to go through each number below the integer in question, see if it divides, repeat until done. Then, inspired by other answers, it morphed... it repeatedly factors items in a vector. It does this a good number of times, but not 'until' anything. The number of iterations has been chosen to cover a good chunk of reasonable inputs.
It still uses "(a mod b) == 0" to test whether one integer divides another (for Gaussians, we use builtin Rust gaussian modulo, and consider "0" as norm == 0), however the check for 'norm(a/b) != 1' prevents dividing "too much", basically allowing the resulting vector to be filled with only primes, but not taking any element of the vector down to unity (0-i,0+i,-1+0i,1+0i) (which is prohibited by the question).
The for-loop limits were found through experiment. y goes from 1 up to prevent divide-by-zero panics, and x can go from -999 to 0 thanks to the mirroring of Gaussians over the quadrants (I think?). As regarding the limitations, the original question did not indicate a valid range of input/output, so a "reasonable input size" is assumed... (Edit... however i am not exactly sure how to calculate at which number this will begin to "fail", i imagine there are Gaussian integers that are not divisible by anything below 999 but are still surprisingly small to me)
Try the somewhat ungolfed version on [play.rust-lang.org](https://play.rust-lang.org/?version=stable&mode=release&edition=2018&gist=d3afa7b4de68598232516661fe4f1f22)
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~141~~ 124 bytes
*Thanks to Jo King for -17 bytes*
```
sub f($_){{$!=0+|sqrt .abs²-$^a²;{($!=$_/my \w=$^b+$a*i)==$!.floor&&.abs>w.abs>1>return f w&$!}for -$!..$!}for ^.abs;.say}
```
[Try it online!](https://tio.run/##LYtNDoIwGETXcIoP0xCwgviPNrD0FARSDE1I0GqLIVC5FEfgYliMm5fJzJtnIarjNMl3DsxBmasUsqIAf@RL1ODTXI6Dh1I6DkQ5ekHZ@t5C0kQozTGiy9KNImT5rOJc2Pbsx82Pm1gU9Vs8gEFjI6tnXICnTf@f09kivqRtPxFzbpwtDsoVBHinecJnzWO4D/AhPJQueDEkHSjT0A9YXOmt5kICZ6C6/rIgpsGcziVmP30B "Perl 6 – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~54~~ ~~51~~ ~~45~~ ~~42~~ 36 bytes
```
.W>H1cZ
h+.aDf!%cZT1>#1.jM^s_BM.aZ2
```
[Try it online!](https://tio.run/##K6gsyfj/X0Ev3M7DMDmKK0NbL9ElTVE1OSrE0E7ZUC/LN6443sk3VC8xyuj/fyMA "Pyth – Try It Online")
Accepts input in the form `1+2j` - purely real or imaginary numbers can omit the other component (e.g. `9`, `2j`). Output is a newline-separated list of complex numbers, in the form `(1+2j)`, with purely imaginary numbers omitting the real part.
This uses simple trail division, generating all gaussian integers with magnitude greater than 1 and less than the current value, plus the value itself. These are filtered to keep those that are a factor of the value, and the smallest by magnitude is chosen as the next prime factor. This is output, and the value is divided by it to produce the value for the next iteration.
Also, Pyth beating Jelly üò≤ (I don't expect it to last though)
```
.W>H1cZ¶h+.aDf!%cZT1>#1.jM^s_BM.aZ2ZQ Implicit: Q=eval(input())
Newline replaced with ¶, trailing ZQ inferred
.W Q While <condition>, execute <inner>, with starting value Q
>H1 Condition function, input H
>H1 Is magnitude of H > 1?
This ensures loop continues until H is a unit, i.e. 1, -1, j, or -j)
cZ¶h+.aDf!%cZT1>#1.jM^s_BM.aZ2Z Inner function, input Z
.aZ Take magnitude of Z
_BM Pair each number in 0-indexed range with its negation
s Flatten
^ 2 Cartesian product of the above with itself
.jM Convert each pair to a complex number
# Filter the above to keep those element where...
> 1 ... the magnitude is greater than 1 (removes units)
f Filter the above, as T, to keep where:
cZT Divide Z by T
% 1 Mod real and imaginary parts by 1 separately
If result of division is a gaussian integer, the mod will give (0+0j)
! Logical NOT - maps (0+0j) to true, all else to false
Result of filter are those gaussian integers which evenly divide Z
.aD Sort the above by their magnitudes
+ Z Append Z - if Z is ±1±1j, the filtered list will be empty
h Take first element, i.e. smallest factor
¶ Print with a newline
cZ Divide Z by that factor - this is new input for next iteration
Output of the while loop is always 1 (or -1, j, or -j) - leading space suppesses output
```
] |
[Question]
[
## Things to know:
First, lucky numbers.
Lucky numbers are generated like so:
Take all the natural numbers:
```
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20...
```
Then, remove each second number.
```
1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39...
```
Now, `3` is safe.
Remove every 3rd number:
```
1, 3, 7, 9, 13, 15, 19, 21, 25, 27, 31, 33, 37, 39, 43, 45, 49, 51, 55, 59...
```
Now, `7` is safe.
Remove every 7th number.
Continue, and remove every `n`th number, where `n` is the first safe number after an elimination.
The final list of safe numbers is the lucky numbers.
---
The unlucky numbers is composed of separate lists of numbers, which are `[U1, U2, U3... Un]`.
`U1` is the first set of numbers removed from the lucky "candidates", so they are:
```
2, 4, 6, 8, 10, 12, 14, 16, 18, 20...
```
`U2` is the second set of numbers removed:
```
5, 11, 17, 23, 29, 35, 41, 47, 53, 59...
```
And so on and so forth (`U3` is the third list, `U4` is the fourth, etc.)
---
## Challenge:
Your task is, when given two inputs `m` and `n`, generate the `m`th number in the list `Un`.
## Example inputs and outputs:
```
(5, 2) -> 29
(10, 1) -> 20
```
## Specs:
* Your program must work for `m` up to `1e6`, and `n` up to `100`.
+ You are guaranteed that both `m` and `n` are positive integers.
+ If you're curious, `U(1e6, 100)` = `5,333,213,163`. (Thank you @pacholik!)
* Your program must compute that within 1 day on a reasonable modern computer.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins!
*PS: It would be nice if someone came up with a general formula for generating these. If you do have a formula, please put it in your answer!*
[Answer]
# Perl, ~~87~~ ~~85~~ ~~82~~ 81 bytes
Includes +4 for `-pX`
Give input on STDIN as one line with n first (notice this is the reverse of the order suggested in the challenge). So to calculate `U(1000000, 100)`:
```
unlucky.pl <<< "100 1000000"
```
Algorithm based on [aditsu](https://codegolf.stackexchange.com/users/7416/aditsu)'s lucky numbers [answer](https://codegolf.stackexchange.com/questions/45785/generate-lucky-numbers/46801#46801)
The time complexity is `O(n^2)` so it's rather fast for the required range. The `100, 1000000` case gives `5333213163` in 0.7 seconds. Due to the problems perl has with `do$0` based recursion it uses a lot of memory. Rewriting it as a function would make the memory use `O(n)` but is a number of bytes longer
`unlucky.pl`:
```
#!/usr/bin/perl -pX
$_=$a{$_}||=/\d+$/>--$_?2*$&+$^S:($_=$_.A.(do$0,$^S?0|$&+$&/~-$_:$&*$_-1),do$0)
```
This works as shown, but use literal `^S` to get the claimed score.
I am not aware of any earlier use of `$^S` in perlgolf.
[Answer]
# Python 3, 170
```
from itertools import*
def L(n,k=1):
if n<2:yield from count(2+k,2)
t=L(n-1);l=next(t)
for i in t:
n+=1
if(n%l>0)==k:yield i
U=lambda m,n:sum(islice(L(n,0),m-1,m))
```
Function *L* generates the row of possible lucky numbers (if *k* is True) or *Un* (if False). Evaluated lazily (so I don't have to generate *n-1* infinite lists if I want *Un*).
Run function *U*.
## Speed
*U(1,000,000; 100)* takes about 1h 45min to run on my machine with PyPy. I suspect some four hours with CPython. (Yes, 4h 20min to be precise.)
If I used a list instead of generators, I might gain some speed, but I would need a list of greater size than Python allows me. And if it did, it would need dozens of gigabytes of RAM.
---
Yes, and *U(1,000,000; 100) = 5,333,213,163*.
[Answer]
## Haskell
## Not able to compute for n=1: ~~175~~ 160 bytes
When compiled, it took my computer 2h 35m to compute for an input of `(1000000,100)` using this:
```
n#s=y:(n#p)where y:p=drop(n-1)s
n%s=f n s$[]where f n s=(take(n-1)s++).f n(drop n s)
l 2=[1,3..]
l m=((l$m-1)!!(m-2))%(l$m-1)
m?n=(((l n)!!(n-1))#(l$n))!!(m-1)
```
I tried ridding the `where` modules, but they seem to affect the speed and I'm not sure why... But I think there is more pruning to be done here.
The method to use is `m?n` for querying the answer given an `m` and `n`.
## Ungolfed
```
everynth n xs = y:(everynth n ys) -- Takes every nth element from a list 'xs'
where y:ys = drop (n-1) xs
skipeverynth n xs = f' n xs $ [] -- Removes every nth element from a list 'xs'
where f' n xs = (take (n-1) xs ++) . f' n (drop n xs)
l 2 = [1,3..] -- The base case of the list of lucky numbers for 'n=2'
l m = skipeverynth ((l$m-1)!!(m-2)) (l$m-1) -- Recursively defining next case as being the last one with every 'ath' element skipped. Here, 'a' is the (m-1)th elemnent of the (l (m-1)) list.
ul m = everynth ((l m)!!(m-1)) (l$m) -- This is not used other than to compute the final, required unlucky number list. It picks out every 'ath' element.
ans m n = (ul n)!!(m-1) -- The function giving the answer.
```
I reckon it may be possible to combine the 'skipeverynth' and 'everynth' functions into a single function which returns a pair.
I used [this kind person's code](https://stackoverflow.com/a/5290128/1351182) for skipping every nth element. I did it myself a few times, but it was always much more inefficient and I couldn't figure out why.
## Able to compute for all n: 170 bytes
This is basically the same, but a couple of `max` functions had to be thrown in to handle the special case of `n=1`.
```
n#s=y:(n#p)where y:p=drop(n-1)s
n%s=f n s$[]where f n s=(take(n-1)s++).f n(drop n s)
l 1=[1..]
l m=((l$m-1)!!(max 1$m-2))%(l$m-1)
m?n=(((l n)!!(max 1$n-1))#(l$n))!!(m-1)
```
[Answer]
## R 82 bytes
```
f<-function(m,n){a=1:2e8
i=1
while(i<n){a=c(0,a)[c(F,rep(T,i))]
i=i+1}
a[(n+1)*m]}
```
Usage
```
f(5,2)
Returns 29
```
This needs to have a large enough vector to start with so there are enough numbers left to return the value. The vector created is already about 800Mb and the function can handle upto m=1e4 and n=100 so still well short of the goal.
To create a large enough vector to calculate f(1e6,100) would take a starting vector of 1:2e10. Due to Rs data allocation procedures this creates a vector >70Gb which can't be run on any computer I know although the code would run.
```
Error: cannot allocate vector of size 74.5 Gb
```
For reference f(1e4,100) runs in about in about 30 seconds. Based on this and a couple smaller tests f(1e6,100) would take about an hour.
[Answer]
# [CJam](http://sourceforge.net/projects/cjam/), 74 bytes
```
ri0Lri:U{1$W%{1$\(1e>/+}/)+}/2t:A0@{@:B:(_0#):D{D(_A=tD<BD>+}&@)@DU=-}h]1=
```
[Try it online!](http://cjam.tryitonline.net/#code=cmkwTHJpOlV7MSRXJXsxJFwoMWU-Lyt9LykrfS8ydDpBMEB7QDpCOihfMCMpOkR7RChfQT10RDxCRD4rfSZAKUBEVT0tfWhdMT0&input=NSAy) *Will time out for larger cases, more on time constraints below.*
---
### Explanation:
Our program shamelessly borrows for [aditsu's code](https://codegolf.stackexchange.com/a/46801/46756) to generate a list of *N* lucky numbers, replacing 1 with a 2 gives the increment in each phase of the sieve. The remaining code decrements on every element until a zero is found (by slicing and appending an un-decremented tail) and effectively counts the steps in each of *N* phases of the sieve at once.
```
ri e# read M
0Lri:U{1$W%{1$\(1e>/+}/)+}/2t:A e# list steps (also becomes B)
0@ e# arrange stack [B I M]
{ e# while M
@:B e# get current B
:( e# decrement every element in B
_0#):D e# find first 0
{ e# if there is a 0
D(_A=t e# reset that element in B
D<BD>+ e# replace tail after 0
}& e# end if
@) e# increment I
@DU=- e# decrement M if N-th phase of sieve
}h e# end loop
]1= e# return I
```
---
[Answer]
## Racket 332 bytes
```
(λ(N m n)(let loop((l(filter odd?(range 1 N)))(i 1))(define x (list-ref l i))(if(= i (sub1 n))
(begin(set! l(for/list((j(length l))#:when(= 0(modulo(add1 j)x)))(list-ref l j)))(list-ref l(sub1 m)))
(begin(set! l(for/list((j(length l))#:unless(= 0(modulo(add1 j) x)))(list-ref l j)))(if(>= i(sub1 (length l)))l
(loop l(add1 i)))))))
```
Ungolfed version:
```
(define f
(λ(N m n)
(let loop ((l (filter odd? (range 1 N))) (i 1))
(define x (list-ref l i))
(if (= i (sub1 n))
(begin (set! l (for/list ((j (length l))
#:when (= 0 (modulo (add1 j) x)))
(list-ref l j)))
(list-ref l (sub1 m)))
(begin (set! l (for/list ((j (length l))
#:unless (= 0 (modulo (add1 j) x)))
(list-ref l j)))
(if (>= i (sub1 (length l)))
l
(loop l (add1 i))))))))
```
Testing:
```
(f 100 5 2)
```
Output:
```
29
```
[Answer]
## Clojure, 221 bytes
Mighty long but handles the case `(f 1)`. Without that special case it was 183 bytes. This was too much effort not to have it posted.
```
(defn f([n](if(< n 2)(take-nth 2(drop 2(range)))(f n 1(take-nth 2(rest(range))))))([n i c](if (< n 2)c(let[N(first(drop i c))F #((if(= 2 n)= >)(mod(inc %)N)0)](f(dec n)(inc i)(filter some?(map-indexed #(if(F %)%2)c)))))))
```
Sample outputs:
```
(pprint (map #(take 10 (f %)) (range 1 10)))
((2 4 6 8 10 12 14 16 18 20)
(5 11 17 23 29 35 41 47 53 59)
(19 39 61 81 103 123 145 165 187 207)
(27 57 91 121 153 183 217 247 279 309)
(45 97 147 199 253 301 351 403 453 507)
(55 117 181 243 315 379 441 505 571 633)
(85 177 277 369 471 567 663 757 853 949)
(109 225 345 465 589 705 829 945 1063 1185)
(139 295 447 603 765 913 1075 1227 1377 1537))
```
1000000 100 case was calculated in about 4.7 hours, at least it didn't crash.
```
java -jar target\stackoverflow-0.0.1-SNAPSHOT-standalone.jar 1000000 100
5333213163
"Elapsed time: 1.7227805535565E7 msecs"
```
] |
[Question]
[
# Background
The Italian definite article (corresponding to English *the*) has seven different forms: *l'*, *il*, *lo*, *gli*, *i*, *la*, *le*. Which one to use depends on three variables:
* Gender: masculine / feminine.
* Number: singular / plural.
* Initial letter of the subsequent word: vowel / consonant type A / consonant type B.
+ Vowel is any of these: *aeiou*.
+ Consonant type B is any of these cases: *s-* followed by another consonant, *z-*, *gn-*, *pn-*, *ps-*, *x-*, *i-* followed by vowel (this *i* acts as a semivowel).
+ Consonant type A is a consonant that is not type B.
The table shows the article form to be used in each of the twelve combinations of the three above variables. Note that the *l'* form is attached to the following word with a single quote and without a space.
[](https://i.stack.imgur.com/vHKES.png)
# The challenge
Input **a word** and one or two strings, numbers or Booleans indicating **gender** and **number**. (The initial letters will have to be obtained from the input word).
The input word will be a sequence of lowercase ASCII letters. Accented vowels will be replaced by their non-accented versions (for example, *realtà* will be input as *realta*).
The gender and number inputs can be separate numbers, Booleans or strings, or a combined number of string (for example, 1 for masculine singular, 2 for feminine singular, etc).
Any reasonable format and separator can be used, as long as it is specified in the answer.
Output the **word preceded by the appropriate form of the article**, with space or single quote as needed. The output should also be lowercase. Trailing or leading blank space is allowed.
Code golf, shortest wins.
# Test cases
In the following I use the input letters `m`, `f` to specify gender, and `s`, `p` for number (this is just one possible input format).
```
Input Output Comment
macchina f s la macchina Initial letter is cons. A
zio m s lo zio Initial letter is cons. B
libri m p i libri Initial letter is cons. A
ieri m s lo ieri Initial letter is cons. B
aquile f p le aquile Initial letter is vowel
spagnoli m p gli spagnoli Initial letter is cons. B
golf m s il golf Initial letter is cons. A
ombra f s l'ombra Initial letter is vowel
impossibili m p gli impossibili Initial letter is vowel
```
[Answer]
# Retina, ~~138~~ ~~133~~ ~~129~~ 113 bytes
```
^.(s[^aeiou]|z|gn|pn|ps|x|i[aeiou])
B$&
^.[aeiou]
V$&
^\d.
A$&
V[02]
l'
A0
il
B0
lo
A1
i
.1
gli
.2
la
.3
le
```
[Test suite.](http://retina.tryitonline.net/#code=JShHYApeLihzW15hZWlvdV18enxnbnxwbnxwc3x4fGlbYWVpb3VdKQpCJCYKXi5bYWVpb3VdClYkJgpeXGQuCkEkJgpWWzAyXQpsJwpBMAppbCAKQjAKbG8gCkExCmkgCi4xCmdsaSAKLjIKbGEgCi4zCmxlIA&input=Mm1hY2NoaW5hCjB6aW8KMWxpYnJpCjBpZXJpCjNhcXVpbGUKMXNwYWdub2xpCjBnb2xmCjJvbWJyYQoxaW1wb3NzaWJpbGk)
(prepended `%(G`\n` to run all test-cases at once)
Input format: `macchina f s` becomes `2macchina` instead.
```
0: Masculine Singular
1: Masculine Plural
2: Feminine Singular
3: Feminine Plural
```
Conversion table thanks to [Kevin Lau](https://codegolf.stackexchange.com/a/85493/48934).
[Answer]
# Python 3.5, ~~238~~ ~~235~~ ~~192~~ ~~181~~ 178 bytes:
(*-13 bytes thanks to tips from Leaky Nun!*)
```
import re;R=re.match;lambda a,b:(R('s[^aeiou]|(z|gn|pn|ps|x|i)[aeiou]',a)and['lo ','gli ','la '][b]or R('[aeiou]',a)and["l'",'gli '][b%2]or['il ','i ','la '][b]if b<3else'le ')+a
```
An anonymous lambda function that takes arguments in the form of `(<String>, <Integer Gender-Plurality mapping>)`, where the mapping is as follows:
```
0 -> Masculine Singular
1 -> Masculine Plural
2 -> Feminine Singular
3 -> Feminine Plural
```
To call it, simply give the function any valid name, and then call it like a normal function wrapped inside a print statement. Therefore, if the question were to be named `U`, simply call it like `print(U(<String>, <Integer Gender-Plurality mapping>))`.
[Try It Online! (Ideone)](https://ideone.com/EjFmf2)
[Answer]
# Java, ~~227~~ ~~208~~ 195 bytes
*-13 bytes thanks to Leaky Nun*
```
String f(String a,int o){boolean v=a.matches("^([aeou]|i[^aeiou]).*"),b=a.matches("^([ixz]|gn|pn|ps|s[^aeiou]).*");return(o>1?o>2?"le ":v?"l'":"la ":o>0?v||b?"gli ":"i ":v?"l'":b?"lo ":"il ")+a;}
```
Takes your string and an int based on the following mapping:
```
0: Masculine Singular
1: Masculine Plural
2: Feminine Singular
3: Feminine Plural
```
Returns a string with the result.
Ungolfed with test cases and with no ternary operators (for real now):
```
class Test {
public static String f(String a, int o) {
boolean v = a.matches("^([aeou]|i[^aeiou]).*");
boolean b = a.matches("^([ixz]|gn|pn|ps|s[^aeiou]).*");
String r;
if(o > 1)
if(o > 2)
r = "le ";
else
if(v)
r = "l'";
else
r = "la ";
else
if(o > 0)
if(v || b)
r = "gli ";
else
r = "i ";
else
if(v)
r = "l'";
else if(b)
r = "lo ";
else
r = "il ";
return r + a;
}
public static void main(String[] args) {
System.out.println(f("macchina", 2));
System.out.println(f("zio", 0));
System.out.println(f("libri", 1));
System.out.println(f("ieri", 0));
System.out.println(f("aquile", 3));
System.out.println(f("spagnoli", 1));
System.out.println(f("golf", 0));
System.out.println(f("ombra", 2));
System.out.println(f("impossibili", 1));
}
}
```
Uses a little bit of regex magic and acts depending on the two booleans specified. To my surprise, no imports are needed, which helps out with the code size!
[Answer]
# Ruby, ~~147~~ 146 bytes
[Try it online?](https://repl.it/Cc7O/1)
It might be possible to use a better method to determine which article to use, but I'm not aware of any.
As per the spec, the identifier is a number, as follows:
```
0: Masculine Singular
1: Masculine Plural
2: Feminine Singular
3: Feminine Plural
```
---
```
->w,i{(%w"lo gli la le l' gli l' le il i la le"[(0..2).find{|r|[/^(i[aeiou]|s[^aeiou]|z|x|[gp]n|ps)/,/^[aeiou]/,//][r]=~w}*4+i]+' '+w).sub"' ",?'}
```
[Answer]
## Batch, ~~446~~ ~~390~~ ~~385~~ 380 bytes
```
@echo off
set w=%2
call:l %1 l' gli_ l' le_ il_ i_ la_ le_ lo_ gli_ le_ le_
exit/b
:l
for /l %%a in (0,1,%1)do shift
set o=%5
for %%a in (gn pn ps)do if %%a==%w:~,2% set o=%9
for %%a in (s z x)do if %%a==%w:~,1% set o=%9
for %%a in (a e i o u)do if %%a==%w:~,1% set o=%1
for %%a in (a e i o u)do if i%%a==%w:~,2% (set o=%9)else if s%%a==%w:~,2% set o=%1
echo %o:_= %%w%
```
New version uses the same `0-3` encoding for the gender and number as several other answers. Works by creating a 1-dimensional array `%2` .. `%13` of forms, then shifting out the first `1+%1` elements so that the forms of interest become `%1`, `%5` and `%9` (which is fortunate as Batch won't go above `%9` without shifting). It then laboriously checks the lists of prefixes to find out which form needs to be used. `_` is used as a placeholder to represent a space until the word is output.
[Answer]
# Python 3, 235 bytes
I was interested to see how short I could get this in Python without regexes. It turns out that this is not the best option...
```
lambda s,c,v='aeiou':[["l'",'il','lo'],['gli','i','gli'],["l'",'la','la'],['le']*3][c][[[1,2][s[0]=='s'and s[1]not in v or s[0]in'zx'or s[:2]in['gn','pn','ps']or s[0]=='i'and s[1]in v],0][s[0]in v and not(s[0]=='i'and s[1]in v)]]+' '+s
```
An anonymous function that takes input via argument of the word `s` and the gender-number code `c` as an integer, using the following mapping:
```
0 - Masculine Singular
1 - Masculine Plural
2 - Feminine Singular
3 - Feminine Plural
```
and returns the word with the correct article.
**How it works**
A list containing the possibilities for each `c` as separate lists is created. The list is then indexed into using the value of `c`, yielding a 3-element list with the relevant options. A list index is now chosen by indexing into another nested list with the results of Boolean expressions. If the first character of `s` is a vowel and is not `i` followed by a vowel, the option for `vowel` is yielded via the returning of the index `0`. Else, a Boolean expression returning `True` for `cons. B` and `False` for `cons. A` is evaluated, yielding the indices `2` and `1` respectively. Finally, the index is used to yield the article, which is concatenated with a space and the original string before being returned.
[Try it on Ideone](https://ideone.com/67PBkv)
[Answer]
# JavaScript 210 bytes
```
(s,p)=>{var c=i=>!("aeiou".indexOf(s[i])+1),r=["z","gn","pn","ps","x"].some(t=>!s.indexOf(t))||(c(1)?s[0]=="s":s[0]=="i")?2:c(0)?1:0;return (p&1?(p&2?"le ":r&1?"i ":"gli "):!r?"l'":p&2?"la ":r&1?"il ":"lo ")+s}
```
An anonymous function taking two parameters s and p where
```
s is the input string
p is plurality (bit 0, set=plural) and gender (bit 1, set=f) combined as
0 = masculine singular
1 = masculine plural
2 = feminine singular
3 = feminine plural
```
After assigning the function to a variable and some unpacking), it can be tested as
```
var f=(s,p)=>{
var c = i=>!("aeiou".indexOf(s[i])+1),
r = ["z","gn","pn","ps","x"].some(t=>!s.indexOf(t))
|| ( c(1)? s[0]=="s":s[0]=="i" )
? 2 : c(0) ? 1 : 0;
return (p&1?(p&2?"le ":r&1?"i ":"gli "):!r?"l'":p&2?"la ":r&1?"il ":"lo ")+s;
}
console.log("%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n",
f("macchina",2),
f("zio",0),
f("libri",1),
f("ieri", 0),
f("aquile",3),
f("spagnoli",1),
f("golf",0),
f("ombra",2),
f("impossibili",1))
```
where
* `c` is a function to test `s` for a consonant at position `i`.
* `r` evaluates to 0 for starting with a vowel, 1 for starting with a type A consonant and 2 for starting with a type B consonant (tested in reverse order).
* Bit bashing in the return statement puts it together.
] |
[Question]
[
Given a ragged list of positive integers, where the maximum depth is \$d\_\text{max}\$, return the same list, except for every element \$e\$, its depth is \$d\_\text{max}+1-d\_e\$ (where \$d\_e\$ is the depth of that element).
Your output should contain the minimal number of brackets, and you can assume the same from your input. Or in other words, "],[" doesn't appear in the input, and shouldn't appear in the output. You can assume that nonempty inputs contain at least one element with depth 1.
# Test cases
```
[] <-> []
[[1,2],3,4] <-> [1,2,[3,4]]
[1,[2],1,[3],1] <-> [[1],2,[1],3,[1]]
[3,[2,[1],2],3] <-> [[[3],2],1,[2,[3]]]
[1,2,3,4] <-> [1,2,3,4]
[[[1]],10] <-> [1,[[10]]
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 83 bytes
```
+`],
,]
T`[]`][
+`,]
],
{`^(?!\[((\[)|(?<-2>])|\d|,)*(?(2)^)]$).*
[$&]
\[([][])]
$1
```
[Try it online!](https://tio.run/##LYuxDsIwDER3/wVSQXZrkJIwIjLyA2zOVUGCgYUBsZF/D1bLcrp3fn4/Ps/XrW/5UvtUoaSgazVUGE3VwadvnTlvijEXk8b5tI9nSCv3pjJy5iizYJDDSDbsQC4aDAIaQu8GMgsaoUmP3oOad8/k6Zyc1QIWY7nHv7mq698P "Retina 0.8.2 – Try It Online") Link include test cases. Explanation:
```
+`],
,]
T`[]`][
+`,]
],
```
Exchange `],` with `,[`, and also flip the leading `[`s and trailing `]`s.
```
{`
```
Repeat until the string has been rebalanced.
```
^(?!\[((\[)|(?<-2>])|\d|,)*(?(2)^)]$).*
[$&]
```
If it's unbalanced then wrap it in `[]`s.
```
\[([][])]
$1
```
Collapse unnecessary `[]` pairs.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage/wiki/Tutorial), ~~31~~ ~~30~~ 27 [bytes](https://github.com/DennisMitchell/jellylanguage/wiki/Code-page)
```
ŒJẈạṀ$‘Ø0jIr0Ṣ€Ṡị“[],”żFFḊṖ
```
I'm pretty rusty in Jelly, ~~so can probably be golfed a bit further~~. It indeed can:
-3 bytes thanks to *@JonathanAllan*.
Input as a list; output as a string.
Port of [my 05AB1E answer](https://codegolf.stackexchange.com/a/242190/52210). The `Ø0jIr0Ṣ€Ṡị“[],”żFFḊṖ` is a slight modification from [*@xigoi*'s Jelly answer for the *Build a list from a depth map* challenge](https://codegolf.stackexchange.com/a/241653/52210).
[Try it online](https://tio.run/##AVEArv9qZWxsef//xZJK4bqI4bqh4bmAJOKAmMOYMGpJcjDhuaLigqzhuaDhu4vigJxbXSzigJ3FvEZG4biK4bmW////WzMsWzIsWzFdLDJdLDMsNF0) or [verify all test cases](https://tio.run/##y0rNyan8///oJK@Huzoe7lr4cGeDyqOGGYdnGGR5Fhk83LnoUdOahzsXPNzd/ahhTnSszqOGuUf3uLk93NH1cOc0oLaHO2foHG7PAkoq6NopAGU1I///jwYqVIiONtQxitUx1jEBcQx1ooEcIGkMJEECxkABnWggE6QGosIIphisGqQ0NlbHRMc0NhYA).
**Explanation:**
```
# Main link, taking the input-list as argument:
ŒJẈ # Determine the depth of each integer:
ŒJ # Get the multidimensional arguments
Ẉ # Get the length of each inner list
ạṀ$‘ # Invert this depth-list:
$ # Apply the previous two links as monad:
Ṁ # Get the maximum of this list of depths
ạ # Calculate the absolute difference
‘ # Increase each 0-based depth by 1
Ø0jIr0Ṣ€Ṡị“[],” # Create a string to zip with:
Ø0j # Surround the list with leading/trailing 0
I # Forward-differences
r0 # Map each integer `n` to a list in the range [n,0]
Ṣ€ # Sort each range
Ṡ # Signum (-1 if <0; 0 if 0; 1 if >0)
ị“[],” # Index into "[]," ("[" if 1; "," if 0; "]" if -1)
ż # Zip/transpose, using the list above
F # and the flattened input as arguments
F # Then flatten the result
ḊṖ # And remove the leading/trailing ","
# (after which the result is output implicitly)
```
[Answer]
# [R](https://www.r-project.org/), 172 bytes
Or **[R](https://www.r-project.org/)>=4.1, 151 bytes** by replacing three `function` occurrences with `\`s.
```
function(l,`?`=unlist,g=function(l)"if"(is.list(l),1+?Map(g,l),0),h=function(v)"if"(any(v),{y[]=cumsum(c(T,y<-v<2)|y);Map(h,split(v-1,y))},v))relist(?l,h(max(g(l))-g(l)+1))
```
[Try it online!](https://tio.run/?fbclid=IwAR1LuUT8zKk_OaDLtmpg4YS-vE-DQlpYLwWbKDUBVzGBeBuScasDenpyqkI##jZHNboMwDMfve4qKU6yaaSm7tYwn6G03iFSEBkSCtCofKtr27MxOQQw0rXAwjuP8/Ld97VO/TxuT1PpsRIGn4OQ3ptBVjZk/xcHRqSN09cw3dES5DY7xRWRI/gtgPuW299zYdOTiZxcqP2nKqilFIt6xO7jtYQdfHez5fY7VpdC1aF2JHcA3tgDXD1skKDAXZXwTGdUDl@1WAvSpsNcA@ySuhbNx3zahioy7/CITGQeehnRrJO4APXydvaUghhRUjyGcah3L@A1himL0Goj9kZLB88hbwBRrkgwku7Y5GNVJbnLwFq2GpJKsR/YxdoBMVJ7eXCmT7kgeolqrdex7GsI4WJgr9ixY2iLeugX9td9/F9P/AA "R – Try It Online")
### Explanation outline
1. Compute the depths of elements using recursive function `g`.
2. Compute the target depths.
3. Compute the target structure of the list using a recursive function `h` just like here: [Build a list from a depth map](https://codegolf.stackexchange.com/a/242243/55372).
4. Use an obscure [R](https://www.r-project.org/) function `relist` to assign original values to the new structure (as [suggested by @Giuseppe](https://codegolf.stackexchange.com/questions/241633/build-a-list-from-a-depth-map?noredirect=1&lq=1#comment545828_242243)).
[Answer]
# Python3, 274 bytes:
```
from itertools import*
f=lambda x,c=0:[i for j in x for i in([(j,c)]if int==type(j)else f(j,c+1))]
g=lambda x,m:[j for a,b in groupby(x,key=lambda x:x[1]==m)for j in(lambda b:[u for u,_ in b]if a else[[*g(b,m-1)]])([*b])]
r=lambda x:g(l:=f(x),max(b for _,b in l))if x else x
```
[Try it online!](https://tio.run/##XY/RbsMgDEXf8xU82pknLc0epkh8CUJV6EJGFgqiRCJfnxLatepeLNuXey72a/xx5/bLh23TwVlm4hCic/OFGetdiHWl@dxb9d2zRCf@0QnDtAtsYubMUmlNbkHARCeURuchch5XP8CEw3wZmN6ltwZRVuOTZTsxFXtPameNwS1erZDod1gfz7okGsm5xb9MuCuqE0uxL3Tc7WqP7tkeKEQ9giL73qCUCKJWMkeHJ3OEueMaEpLtE6iCOd5@MSNmTiocljYf8jUQQEjE6jGIhg6SWvp82TYk8jbXNtcXpc0K5TuK65/ncOdsVw)
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 191 bytes
```
f=lambda a:(a*0==0)*[(0,a)]or[(d+1,x)for y in a for d,x in f(y)]
def g(a):
s=",".join("["*(z:=max(f(a))[0]+1-n)+f"{x}"+z*"]"for n,x in f(a))
for _ in s:s=s.replace("],[",",")
return s or[]
```
[Try it online!](https://tio.run/##VY7RaoNAEEXf/YplnmZ1ErT2IQj7JctQJtFNLckqqwFN6bfbsdBCXy5zOZfDjOv8PsT6NKZtC@4m93MrRhqUvHSutLnHksTykDy2RUWLDUMyq@mjEbOfLS17CbhaztoumCuKbTIzOSA4fgx9RPCQ47Nxd1kwKLW@5KI6RFsE@Fy@oHjmwLDL4q9MR9mP/m3vUzO56Zi68SaXDoHJq5tAJ6mbH0kHRv/jbUx9nPGKviL/wqRZa7K6/kithHzFpLym139My/YN "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Python](https://www.python.org), 165 bytes
```
lambda x,i=0:x and[*eval(",".join((j-i)*"["+(i-(i:=j))*"],"+str(k)for j,k in d(x,-min(d(x))[0]))+i*"]")]
d=lambda x,c=0:x*-1and[(c,x)]or sum((d(y,c-1)for y in x),[])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XU9LboMwEN1zCsurmWRAIekiikov4npBQ1CHgEGYVHCGHqGbSFV6p9ym45BWVb0Y-828j-fjq5uG19adP8vs-XIaynh7vdR581LkaiTOVrtR5a4wi8NbXoMmnVQtO4AqZlxoo5fAMfAuq1CgJb30Qw9HLNteVXRU7FQBI8WNaOSBaFYWccnC1WijIvuN2oeoRZyGMNjTiFYs_KkB0U20j9Ob5xQcRyRj8f7Znpuu7QflJx8FRh0YAhI_FOyS_pAXNbuDB9xFSg5TlTV5B2EfqhPf1TyAVo_xk9KIN0rXsxugIv4LS2CkEmTPaE4-X9-NvemMjYxJaW1pQw_3lkAyAcosJSMzqRup97lJbWCkQSNVWHLPjeDzwwqSWRvs7Oy2_pcT0Pynbw)
#### Old [Python](https://www.python.org), 169 bytes
```
lambda x,i=0:x and[*eval(",".join(((n:=j-min(d(x))[0])-i)*"["+(i-(i:=n))*"],"+str(k)for j,k in d(x))+i*"]")]
d=lambda x,c=0:x*-1and[(c,x)]or sum((d(y,c-1)for y in x),[])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XU9LboMwEN1zCsurcTJGIekiQqUXcb2gIahDwCBwKjhDj9BNpKqVeqTcpmNIq6pejP1m3mf89tlN_rl1l_cye_w4-1Lvr1913jwVuRiRsk06itwVZnV8yWuQKOOqJQcALs0q3fCzgFEps7FKk1pJI9dAGijNnGJoUa4H38NJlW0vKjwJcmJWrImnUtmoyH7jDiFupZMQCAcclWXRcG6AQyY86GR2mYLHqNBYdVu4p6Zrey-GaYgCow4MBvHgC3Jxf8yLmtxxAJVGgg9hlTV5B-FPWMdDV5MHKe71g5BKzZSuJ-ehQvoLSyCFJVTMWZIv11djZ52xkTEJbi3u8O7WYogmQJ4laHjGdcf1NjeJDYwkaLgyi--lEXx-WEGyaIOdXdy2_3ICWnb6Bg)
#### Old [Python](https://www.python.org), 174 bytes
```
lambda x,i=0:x and[*eval(",".join(((n:=j-min(sum(d(x),())))-i)*"["+(i-(i:=n))*"],"+str(k)for j,k in d(x))+i*"]")]
d=lambda x,c=0:x*-1and[(c,x)]or sum((d(y,c-1)for y in x),[])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XU9LTsMwEN3nFJZX43YckZYFiggXMV6EphGTJk6UpCg5A0dgUwnBkvv0Nsw0BSFmMfabeR_77bObx-c2nN7L7PHjOJb27vxV581TkasJKbtJJ5WHwq32L3kNGnVctRQAIKRZZRu-DscGCpgMguGyZFba6TWQBUqzYBh61Oth7OFgyrZXFR4UBSUSsybeauOjIvvN3EnmyiaSCjucjGeRhHDKjDubXFxm8eBQ58311T01XduPapiHSBi1MBjEw1hQiPt9XtQU9gOYNFJchFXW5B3Ix7COh66mEbS6tw9KG3OhdD2FESqkv7AEMlhCxZwl-XR-df6icz5yLsGNxy3eXkcM0QnkXYKOd9y33K97l3hhJKLhziw-l4H4_LBEsmjFzi9um385gpY3fQM)
#### Old [Python](https://www.python.org), 178 bytes
```
lambda x,i=0:x and eval("["+",".join(((n:=j-min(sum(d(x),())))-i)*"["+(i-(i:=n))*"],"+str(k)for j,k in d(x))+-~i*"]")
d=lambda x,c=0:x*-1and[(c,x)]or sum((d(y,c-1)for y in x),[])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XU9LTsMwEN3nFJZX43YckZYFiggXMV6EphGTJk6UpCjZcAGOwKYSggNwm96GmTawYBZjv5n3sd-_unl8bsPpo8weP49jae_O33XePBW5mpCym3RSeSjU_iWvQTu91qjjqqUAACHNKtvwdTg2UMBkEAyXJbMSJpAFSrNgGHrU62Hs4WDKtlcVHhQFJRKztq_Ee22iIvvL3Unuyiac7GCHk_GskhSOmXFnk4vNLCac6rxZXv5MTdf2oxrmIRJGLQwG8TAWFOJ-nxc1hf0AJo0UF2GVNXkH8jus46GraQSt7u2D0sZcKF1PYYQqirAEMtwqg7Tknc5vzl_YzkfOJbjxuMXbZcQQnUDeJeh4x33Lfdm7xAsjEQ13ZvF5HYjPL0skV63Y-avb5l-OoOubfgA)
Based on [this](https://codegolf.stackexchange.com/a/241637/107561) answer to a related challenge.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~75~~ 72 bytes
```
If[v@#,#/.l->List,#0[##&@@@SequenceReplace[#,{a__}?v:>!l@a]]]&
v=VectorQ
```
[Try it online!](https://tio.run/##LYq9CsIwFEb3vIUEOt2q/VFBaM0qOKgFlxAkhBQLbdUau1zSV48JdTl83@F00jx0J02jpKsLd6z5yCjQ1bKNy1PzMUDXnNKIMVbp91f3Sl/1q5VKcwoo73d7GPflomVSCBGRsbhpZZ7DxZ2HpjecxmXNqIimSsl@QoIWCGICqYUM8nASQH88M88gMi8A/QzNXKT/eK4hJDngBnBrrYWdB7HuBw "Wolfram Language (Mathematica) – Try It Online")
-9 bytes if lower levels can have non-`List` heads: [Try it online!](https://tio.run/##LYrLCsIwFET3@QsJdHUF@1BBaM3WnVpwE0IJ4RYLbdUSu7mkvx4TKgOHmeEM2j5x0LYz2relv7RyFhxCdpLzRAhR4@eLo8E7vnttUHIg3TTuPJ@qTS@0Uiphc/lAY1/TzV@nbrSSb6tWcJUstdHjQowcMKIUMgc5FHGkQGEE5oHxyMMBFGp0ViP7y6sNUSmA9kAH5xwcA5jzPw "Wolfram Language (Mathematica) – Try It Online")
```
SequenceReplace[#,{a__} ] group consecutive
?v non-List elements
:> l@a by wrapping with l
##&@@@ ! flatten out Lists
#0[ ] recurse
If[v@#, , ] until no Lists left
#/.l->List turn l into List
```
---
### [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~76~~ 74 bytes
```
#/.{{__d}:>#0/@d/@SplitBy[D@@@#,Head],{__}:>#0[d/@#]}&
d@{a__}=d@a:{__d}=a
```
[Try it online!](https://tio.run/##LctNC4JAEAbg@/6NBU9T5kcFgrJEh46BRxEZ3CQhJWIvMYx/fZvVLi8z7zwzoXs@JnRjj34ovY73RF1nuaj0ITY2NvX7NbrLt7kaYzTcHmhbELGCRu665UhZQyhdaQ0W63uJ/v4ZZ9foXTWIiZa6x3khRQyKKIGUIYM8LAmQLJKZZCgyKYBkDGYT6R9vGgLJgY5AJ2aGs4Ri/wM "Wolfram Language (Mathematica) – Try It Online")
```
main function:
#/. {__}:>#0[d/@#] get depths
#/. {__d}:> construct by:
d/@SplitBy[D@@@#,Head] group this layer
#0/@ recurse
(atoms are unchanged)
depth helper:
d@a:{__d}=a don't change lists that only have d[...]s
d@{a__}= a splat other lists
(stay unevaluated on atoms)
```
The first step of the main function wraps each value in a number of `d`s equal to their final depth. Then the final structure is constructed recursively in a manner similar to [this answer](https://codegolf.stackexchange.com/a/241678/81203).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 44 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
_"Ddië®δ.V>"©.V˜ZαU˜εXNèF…[ÿ]]',ý…[ÿ]…],[',:
```
I knew this approach would be pretty long, but not sure what a good alternative would be..
Input as a list; output as a string.
[Try it online](https://tio.run/##yy9OTMpM/f8/XsklJfPw6kPrzm3RC7NTOrRSL@z0nKhzG0NPzzm3NcLv8Aq3Rw3Log/vj41V1zm8F8oGUrE60eo6Vv//RxvrRBvpRBvG6hjF6hjHAgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/3gll5TMw6sPrTu3RS/MTunQSr2w03Oizm0MPT3n3NYIv8Mr3B41LIs@vD@2tlZd5/BeKAdIxepEq@tY/df5Hx0dq6MQHW2oYxSrY6xjAuIY6kQDOUDSGEiCBIyBAjrRQCZIDUSFEUwxWDVIaWysjomOaWwsAA).
**Explanation:**
In pseudo-code I do the following steps:
1. Determine the (0-based) depth of each integer in the nested input-list (`_"Ddië®δ.V>"©.V˜Zα` - [try it online](https://tio.run/##ATEAzv9vc2FiaWX//18iRGRpw6vCrs60LlY@IsKpLlbLnFrOsf//WzMsWzIsWzFdLDJdLDNd)).
2. Flatten the input-list (`˜`).
3. Use a minor modification of [my 05AB1E answer for the *Build a list from a depth map* challenge](https://codegolf.stackexchange.com/a/241695/52210) with the list of step 1 to mold the flattened input-list (as string..) (`εXNèF…[ÿ]}}',ý…[ÿ]…],[',:`).
As for the actual code:
```
_ # Transform each integer in the (implicit) input to 0
"..." # Push the recursive string explained below
© # Store it in variable `®` (without popping)
.V # Evaluate and execute it as 05AB1E code
D # Duplicate the current list
dië # If it's not an integer (so it's a list):
δ # Map over each item:
® .V # Do a recursive call
> # Then increase each integer in this list by 1
˜ # Flatten the result
Z # Push the maximum depth (without popping the list)
α # Pop and push the absolute difference
U # Pop and store this list in variable `X`
˜ # Flatten the (implicit) input-list
ε # Map over each integer:
XNè # Get the depth from `X` at the same index
F # Loop that many times:
…[ÿ] # Wrap it in square blocks
] # Close both the inner loop and outer map
',ý '# Join everything by "," delimiter
…[ÿ] # Wrap the entire string in square blocks as well
…],[',: '# Replace all "],[" with ","
# (after which the string is output implicitly as result)
```
[Answer]
# JavaScript (ES6), 156 bytes
```
f=(a,i=d=+(m=b=[]))=>a.map?a.map(v=>f(v,i+1))|i||eval('b='+[...b,[f,'b']].map(g=a=>d^([v,x]=a,v+=~m)?d-->v?"["+g(a):"],"+g(a,d+=2):x)):b.push([i<m?i:m=i,a])
```
[Try it online!](https://tio.run/##bY7NboMwEITvfYqIC7a8OIL0hLrwICtXMuGnriCg0lg5oLw69RL1N/VhZM1@M7uv1tv5@Oam9@Q01s26tigsOKxRiQErJCMlFlYPdio3FR6LVnhwKpVyccvSeNuLuMJYkda6AmohrmJjNrhDi0X9LMjDxaAFr/A6yLJOksKXEUWqE1bmkYHtB7XCTOYXKfNKT@f5RZB7GkqXD@jAGrkex9M89o3ux060gm/b/Xr7/Y7Mwx@KUsgMHODxE2cqeEDs3eEpUMCDHoJyhHFKDQdS7gl6FwrubcybvkJcceviZea/XdnPw75PY3P9AA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 27 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
Is there something shorter than the `¬ȦƇẈƊ` this uses?
```
ŒṖṚ¬ȦƇẈƊÞṪḢ’$Ȧ¡€
ŒJẈÇŒṪ¿ṁ@F
```
A monadic Link accepting a ragged list that yields a ragged list.
**[Try it online!](https://tio.run/##y0rNyan8///opIc7pz3cOevQmhPLjrU/3NVxrOvwvIc7Vz3csehRw0yVE8sOLXzUtIbr6CQvoNzhdpDyVYf2P9zZ6OD2H8Kd8f9/dHS0QWysDpAyjAXSRrEA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///opIc7pz3cOevQmhPLjrU/3NVxrOvwvIc7Vz3csehRw0yVE8sOLXzUtIbr6CQvoNzhdpDyVYf2P9zZ6OD2XwfCnwFU8HDHfCD5qHFb1qOGOQq6dgqPGuZqRv7/Hx0dqxMdbahjFKtjrGMCZBvqRAPZQNIYSAL5xkA@UDQWrAIsbwRWGQsA "Jelly – Try It Online").
### How?
Firstly, get the depths of the items.
While there are any non-zero integers at any depth group together as many zeros, and lists that are only zeros at all depths, as possible and decrease all the other integers by one.
Lastly, mould a flattened version of the input like that ragged list.
```
ŒJẈÇŒṪ¿ṁ@F - Main Link: ragged list, A
ŒJ - multidimensional indices of A
Ẉ - length of each -> flat list of depths
¿ - while...
ŒṪ - ...condition: truthy multidimensional indices
Ç - ...do: call the helper link
F - flatten A
@ - with swapped arguments:
ṁ - mould like
ŒṖṚ¬ȦƇẈƊÞṪḢ’$Ȧ¡€ - Helper link: ragged list, Current State
ŒṖ - all partitions of the Current State
Ṛ - reverse (to have longest last rather than first)
Þ - sort by:
Ɗ - last three links as a monad:
¬ - logical NOT (vectorises)
Ƈ - filter keep those for which:
Ȧ - any and all?
Ẉ - length of each
Ṫ - tail
€ - for each:
¡ - repeat...
Ȧ - ...times: any and all?
$ - ...action: last two links as a monad:
Ḣ - head
’ - decrement
```
---
Alternative helper, same byte count:
```
ŒṖṚŒṪƇẈ$ÞḢḢ’$Ȧ¡€
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 137 bytes
```
x=>(y=JSON.stringify(x).replace(/,\[|],/g,t=>t>'['?(b+=']]',',['):(a+='[[','],'),a=b=''),g=t=>t?t.map?t[1]?t:g(t[0]):[t]:[])(eval(a+y+b))
```
[Try it online!](https://tio.run/##bU7LboMwELz3K3KzrWyhJD0hGe49tIcet3sw1FhEFBBYUZD673RXUR9J6sNYOzuzMwd3dHM9tWO874d3vzZ2PdlCL/bp9eU5mePU9qFtFn0yyeTHztVep/CGnwRpgGiLWChUpa62VhEpUIDK5NrxiMgjgTLgbGUV/8GKoYzJhxvLiBmVMQ864gOZHCPlSEb7o@vYvmwrY9Z66Oeh80k3BN1oXpvNxUvTDdLdlQoz2BHs4fFbLirmAIW7kWeALGfcM4pF5NxNDJncYbwxMXteS9KPSU6cb0kY/Ze1@1vst5qQ6xc "JavaScript (Node.js) – Try It Online")
First with lots of outer brackets then clean some
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~122~~ 120 bytes
```
≔&θ⁰η≔⟦η⟧ζFζFιF⁼κ⁺⟦⟧κ«UMκ⊖μ⊞ζκ»⊞υθ⊞υηFυFιF⁼κ⁺⟦⟧κ⊞υκF⮌υ«≔⟦⟧ζWι⊞ζ⊟ιF⮌ζ¿⁺⟦⟧κFκ⊞ιλ⊞ικ»≔⮌θθ≔⁰ζF⁻η⊖⌊η«F⁻ζι]→F⁻ιζ[I⊟θ≔ιζ»Fζ]UB,
```
[Try it online!](https://tio.run/##jVFNj4IwED3Lr2g4tUlNXL2tJ3X3aGLcY8OhwWonFBBKNWHjb2cHaAne9tTOzJv30aZa1mkpTdftrIVbQffQPMGqXXGhFScrxolm28gPhU44abG@ljWhLSPDCf78rpw0lmacnIyzVCA2Y4yR32hxlPdDmecSWXH8pdJa5apo1IXmDOkWJ2c1bXv8NnpFQ@U4qbAKdx1U3T9Vw2IWFs/qoWqrkGCwFCL5RIunBqMG2mDmVN6x7Gdv@y3uw5XQudxoJfO7wIlhW6KMVVNjTOZFA1XFxpC@vZo97hEKpNfvj4VNyF1ONfPvOoOiYehj11A0NE7i3vexfCj6eYabbqYYIxp6qQktBvRYHKRtaB@9YkN27w1Gb6/p6@dCP6rZyzS71aXDH4459rpOiA0Xay4@Er5O@CZJuuXD/AE "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Not an easy problem to solve without access to recursion.
```
≔&θ⁰η
```
Make a deep clone of the input and set all of the integers in that clone to zero. (`BitwiseAnd` fully vectorises, unlike, say, `Times`.)
```
≔⟦η⟧ζFζFιF⁼κ⁺⟦⟧κ«UMκ⊖μ⊞ζκ»
```
Perform a breadth-first search over the clone and decrement each sublist. (Again, it is fortunate that `Decremented` fully vectorises, although I still have to `MapCommand` it because I need to modify each sublist in-place.) The resulting list ends up with values appropriate to their depth.
```
⊞υθ⊞υηFυFιF⁼κ⁺⟦⟧κ⊞υκF⮌υ«≔⟦⟧ζWι⊞ζ⊟ιF⮌ζ¿⁺⟦⟧κFκ⊞ιλ⊞ικ»
```
Flatten both the input and the depth clone in-place.
```
≔⮌θθ≔⁰ζF⁻η⊖⌊η«F⁻ζι]→F⁻ιζ[I⊟θ≔ιζ»Fζ]UB,
```
Adjust the depth list so that the minimum depth is 1, and use that to build the desired output list from the depth list and the flattened input list. (See my answer to [Build a list from a depth map](https://codegolf.stackexchange.com/questions/241633/) for more detail.)
] |
[Question]
[
Alice is an intern in a company that uses Brainfuck as a primary language for both client-side and server-side development. Alice just has written her first code and she's a bit nervous as she's getting ready for her first code review.
Alice wants to make her code properly formatted and look nice, but she has no time to read the 328-pages company code style guide, so she decided to format it as a *perfect square*. Alas, code length may be insufficient to form a square, so she decided to leave a *rectangular* gap in the middle. Gaps must be perfectly *centered* and as *close to square* as possible.
### Examples
```
++++++ +++++ +++++ +++++ +++++ +++++
++++++ +++++ +++++ + ++ ++ ++ +++++
++++++ ++ ++ + + + ++ + +
++++++ +++++ +++++ +++++ ++ ++ +++++
++++++ +++++ +++++ +++++ +++++ +++++
Perfect OK Acceptable Unacceptable No way! Nope.
```
Write a program or a function to help Alice.
Given Alice's code as an input string, output properly formatted code as described below if possible.
If formatting is impossible, output crying emoji `:~(`.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers are scored in bytes with fewer bytes being the aim.
### Constraints
1. Your program or function should take a single string as an input and output one or more lines of text (or return multi-line string or array of strings, if you implement a function).
2. Input string may contain any ASCII characters including whitespaces.
3. All whitespaces in input must be ignored. They shouldn't count for code length and they shouldn't be used in output.
4. Input string contains at least one non-whitespace character.
5. Formatted code must have the same non-whitespace characters in the same order as in input code.
6. Formatted code must be a perfect square, i.e. all lines should have same length, and number of lines should be equal to the lines' length.
7. Formatted code may contain a gap in the middle.
8. Only space characters (ASCII code 32) may be used in the gap.
9. Gap (if present) must be rectangular.
10. Every line of formatted code must contain at least one non-whitespace character, i.e. gap width must be strictly less than square width (gap 5x1 is unacceptable for 5x5 square).
11. Gap should be horizontal, i.e. gap width should be greater than or equal to gap height.
12. Gap must be perfectly centered.
13. Consequently gap width and height parity should be the same as square width parity (for example for 5x5 square gap may be 1x1, 3x1, or 3x3).
14. If possible, output square with no gap at all.
15. In case of multiple solutions, choose one with gap closest to square, i.e. difference between gap width and gap height is minimal (for example: gap 10x10 is more preferable than 8x6, and 8x6 is more preferable than 6x2).
16. If still there's a tie, choose solution with minimal gap area (for example gap 2x2 is more preferable than 4x4).
17. If it is impossible to format code at all, output `:~(`.
18. Newline after last line is optional.
19. **[New]** You may safely assume that any character with code below 33 is a white-space. I hope it will help you for golfing.
### Tests
```
Input Output Code length Comment
+++++++++ +++ 9 Alice is lucky,
+++ her code perfectly fits a square.
+++
++++++++ +++ 8 Though code length isn't enough for a square,
+ + a small gap fixes it.
+++
++++++ :~( 6 No luck, code cannot be formatted.
Hello, Hell 12 Input may contain any ASCII characters,
World! o , but whitespaces in input should be ignored.
W o
rld!
+++++ + +++++ +++++ 22 Gap is not required to be a square,
+++++ + +++++ +++++ it can be a rectangle.
+ +
+++++
+++++
+++ + +++ ++++++++ 28 There exists another solution:
+++ + +++ + + 6x6 square with 4x2 gap,
+++ + +++ + + but in Alice's opinion square gap
+++ + +++ + + makes code more readable.
+ +
+ +
+ +
++++++++
```
### Tricky tests
```
This must be Thism 24 7x7 with 5x5 gap looks good,
5x5 with 1x1 ustbe but 5x5 with 1x1 gap is better,
gap. 5x 5w because gap area is smaller.
ith1x
1gap.
+++ +++ +++ :~( 18 In case you tried 5x5 square
+++ +++ +++ with 7x1 gap ;)
```
### Resources
To save space you can find sample code and extra test cases on
[tio.run](https://tio.run/##nVffc6M2EH7nr1Cd6cQEw8W@y7VNMc996tPN9MHxZBQjG82BRISYJPfQfz3dFb8EyHHniE0E2v12v93VSi7fdCbF5/f3lB3JUaqC6uVBpsy/9whcV6TSipfkJeOaVSU9sMq8N29Llj6iLNmS3SGjih40UwhChicuiBHhRyKkHiYiXhm4pb/3WktHLtJGOGfipDPzGp8fm2cwA4PlyLTv9W5SpclRyYKsX9ekeq6pYo2rZvj4wlMDse40hCSVzGvNpQCfa7BNNdEZI4UsmNBG6olV@vHINej9LQXrVCEaOWuBCa8MMy0lyak6MRgRVDFMABshn6RKmTLaje7S9ipc@zdf4q1F9b6xZMWlNQZf2k@1GPgOHLQRb242M4RSaqDFaU5OtCQV/8F6CXgxQTFPoR19Gw@SiRgtc8Wea65YSoA0vKKkZOrIDhqj0Cs1Kq2VLbm972fwGj1YQR@FaUVu4eOPZQHv@8S1IS9P/ESYkPUps5Pi9ClBl0bQV6Skius3Ihu2VSbrPDUow4RVZxbqqOR@JRtkvB4z7sKeMX7KtKlLe4rlFbugsJm6q9VbQxOTrWSJaxHWmlTVSLApwG@qdhhwloqh4fSlW1N9FD99snz0HPCIV9SVhiSTTCr@QwpN85lgm5kGP7Yw5y47qsBtTkFJUnGqYZFOK25m8mYU6oGg2/zVEKauSsCezqjoatEdQgdTu3LcxhqDBf0ODagG6KEWGwyaVxKm9SFj1VmAkdW2QKdFe948ccVvWkYKoj7urx@qgEf9uoeVi932Ywc@7hQ9u5WVSf9DQPeSm1OT0NDVQI298kpXK9ia9HUF/aUoMeEgU1zEsrMQWgUX98R2633Yjzf7y@79VFQ@6jMBNBqT7@mu09RJYG2oQIcXpawq/pQ3u6A5TngX0ytrXdbo7vX9v8trb54Mg90hg@9MG7Q@CU7fztAFM50n9r6hM3ALPtUzxVVFj3h4oXlO/vSn6D2Obc3znGsrme50bYfFhgGE@Mj7LvQ5O86SB5txj@pjn93M1LQsLa3Wy9DOtFtPOeiA3rrVRW9mOk9SazhqbcnUWqcFznjnV5Y5fYHYOeoDHdvBkeFwbaevOf69cPCcFSX0QzwlitO8xBYLW42KtG1Vw4kVOikXIDwkVKTsFVRvR@cMEKUaF7oy54umbnoBPAQr@YLHXwWbDhvl0h8HwxyYoZILMRNv8@baqHG1iYrDGRPCsuoImjP1ub3NBDfedsZiO7q0KUoTdZhA32M74u7W01qFLrAgC@//d9S2i@IhtMMQ7NXKwgVro98AO5OgvXt7NbkLpscrqD/2QnIuxrGy6DyIgY8ZKKZrJVqR9xKqSy/b30uL9ebzl7uvv/3@x8L3PffU2ZmFv2Ii3YJBMDmV@YvluVw9iH@kytNf5hgBXgT@zH@4Ri@c8s3kg7gwnOt@ww7ZHabuXu@a1YY/tqBKojO25l/gS84TDnZhmIS7JAmSEK843sdwh9E@CaME3sMtigBnFyX7GC4cR0Y2jOLYyIDQ3B1EieNgF@xig52YPwDYIw4qm5gFBgRu8Iym4NMZMU9oJA6iM6lAv5LujoPmi34CgQBZgXc7JLVHOHS61Ys6G2B@RCpsr8iQD4zt9/8A "Alice's First Code Review - Python 3")
**[New]** You may take a look at [the table of accepted solutions for inputs upto 100 characters](https://pastebin.com/9BmzyA3Z). I swapped width and height because it seems to look more intuituve.
Inspired by: [A square of text](https://codegolf.stackexchange.com/questions/88926/a-square-of-text/)
### Changes
* Added 2 tests, fixed bug in sample code.
* Added table of solutions upto 100, added white-space clarification.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 80 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ö╦Çc▀╕╡ëé╓]µiÖ9♪`W|╣▐↑╖D┘↕♫╗╔äƒ■úφ■U`ÿ⌠%é┴☼vAú)☺@ı◄¬¶¢(îÉ┼6⌠D~♀└lfæA.I@º╤∟òîü╦(
```
[Run and debug it](https://staxlang.xyz/#p=94cb8063dfb8b58982d65de66999390d60577cb9de18b744d9120ebbc9849ffea3edfe556098f42582c10f7641a32901408ef111aa149b288c90c536f4447e0cc06c6691412e4940a7d11c958c81cb28&i=%2B%2B%2B%2B%2B%2B%2B%2B%2B%0A%0A%2B%2B%2B%2B%2B%2B%2B%2B%0A%0A%2B%2B%2B%2B%2B%2B%0A%0AHello,%0AWorld%21%0A%0A%2B%2B%2B%2B%2B+%2B+%2B%2B%2B%2B%2B%0A%2B%2B%2B%2B%2B+%2B+%2B%2B%2B%2B%2B%0A%0A%2B%2B%2B+%2B+%2B%2B%2B%0A%2B%2B%2B+%2B+%2B%2B%2B%0A%2B%2B%2B+%2B+%2B%2B%2B%0A%2B%2B%2B+%2B+%2B%2B%2B%0A%0AThis+must+be%0A5x5+with+1x1%0Agap.%0A%0A%2B%2B%2B+%2B%2B%2B+%2B%2B%2B%0A%2B%2B%2B+%2B%2B%2B+%2B%2B%2B&a=1&m=1)
How does it work?
* Consider all squares with rectangle cutouts.
* Filter out program shapes that aren't the right size.
* Filter out program shapes that don't have matching parity.
* Filter out program shapes where the cutout is too big for the square.
* If none are found, output failure and quit.
* Find the shape that minimizes "rectangularity" of cutout, then by cutout size.
* Replace each character in the program shape with the corresponding character in the program input.
Unpacked, ungolfed, and commented it looks like this.
```
input e.g. "big socks"
L$j$ remove whitespace from input e.g. "bigsocks"
cr{~F copy push each remaining character to input stack in reverse order
%c get length L of flattened input and copy e.g. 8
^r3:$ create triples [a,b,c] in range 0..n e.g. [[0,0,0], [0,0,1], ... [8,8,8]]
{E*NsJ+n=f filter triples: require a*a-b*c=L e.g. [[3,1,1], [4,1,8], ...]
{ET>f filter triples: a>b and a>c e.g. [[3,1,1]]
{{2%m:u_0#+f filter triples: a%2=b%2=c%2 or b*c=0 e.g. [[3,1,1]]
":~("s|c if there are no triples, output ":~(" and terminate
{D:s_D:*\oh sort by [abs(b-c),b*c]; keep the first e.g. [3,1,1]
X store the chosen triple in the X register
E explode onto stack e.g. 3, 1, 1
z)]* using last two values, make a rectangle of zeroes e.g. 3, [[0]]
~ this will be the cutout, push it to the input stack
c'X*]* make a square of "X" e.g. ["XXX", "XXX", "XXX"]
xEd-h given the dimensions in x register, calculate the centered cutout coordinates
xEsd-h e.g. ["XXX", "XXX", "XXX"], 1, 1
,|| embed the cutout grid at the specified coordinates e.g. ["XXX", "X X", "XXX"]
m'X{,]}R for each line, regex replace "X" with a character from the input stack
```
[Run this one](https://staxlang.xyz/#c=++++++++++++%09input+e.g.+%22big+socks%22%0AL%24j%24++++++++%09remove+whitespace+from+input+e.g.+%22bigsocks%22%0Acr%7B%7EF+++++++%09copy+push+each+remaining+character+to+input+stack+in+reverse+order%0A%25c++++++++++%09get+length+L+of+flattened+input+and+copy+e.g.+8%0A%5Er3%3A%24+++++++%09create+triples+[a,b,c]+in+range+0..n+e.g.+[[0,0,0],+[0,0,1],+...+[8,8,8]]%0A%7BE*NsJ%2Bn%3Df++%09filter+triples%3A+require+a*a-b*c%3DL+e.g.+[[3,1,1],+[4,1,8],+...]%0A%7BET%3Ef+++++++%09filter+triples%3A+a%3Eb+and+a%3Ec+e.g.+[[3,1,1]]%0A%7B%7B2%25m%3Au_0%23%2Bf%09filter+triples%3A+a%252%3Db%252%3Dc%252+or+b*c%3D0+e.g.+[[3,1,1]]%0A%22%3A%7E%28%22s%7Cc++++%09if+there+are+no+triples,+output+%22%3A%7E%28%22+and+terminate%0A%7BD%3As_D%3A*%5Coh+%09sort+by+[abs%28b-c%29,b*c]%3B+keep+the+first+e.g.+[3,1,1]%0AX+++++++++++%09store+the+chosen+triple+in+the+X+register%0AE+++++++++++%09explode+onto+stack+e.g.+3,+1,+1%0Az%29]*++++++++%09using+last+two+values,+make+a+rectangle+of+zeroes+e.g.+3,+[[0]]%0A%7E+++++++++++%09this+will+be+the+cutout,+push+it+to+the+input+stack%0Ac%27X*]*++++++%09make+a+square+of+%22X%22+e.g.+[%22XXX%22,+%22XXX%22,+%22XXX%22]%0AxEd-h+++++++%09given+the+dimensions+in+x+register,+calculate+the+centered+cutout+coordinates%0AxEsd-h++++++%09e.g.+[%22XXX%22,+%22XXX%22,+%22XXX%22],+1,+1%0A,%7C%7C+++++++++%09embed+the+cutout+grid+at+the+specified+coordinates+e.g.+[%22XXX%22,+%22X+X%22,+%22XXX%22]%0Am%27X%7B,]%7DR++++%09for+each+line,+regex+replace+%22X%22+with+a+character+from+the+input+stack&i=big+socks&m=1)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~354~~ 348 bytes
-6 thanks to ceilingcat
```
h,i,j,k,l,m;g,v,w,d;f(char*s){for(j=l=0;i=s[j];d=g=l+=!isspace(s[j++]));for(;i++<l;)if(h=i*i-l)for(j=0;j<i-++j;h>0&h%k<1&k<=m&m<i&m+~k&m-k<g|m==k+g&(d-2*v)*(d-2*w)>h?w=i-m>>1,v=j,g=m-k,d=i:0)k=i-2*j,m=h/k;else g=0,v=w=d=i;if(g-l)for(i=j=1;*s;j+=!i++,k=0,i%=~d)for(putchar(i?v>=j|j>d-v|w>=i|i>d-w?k=1,*s:32:10);k;k*=isspace(*++s));else puts(":~(");}
```
[Try it online!](https://tio.run/##fZLbjpswEIZfhSAt8okupNqbmCG3fYBKvUiiKuU4NiZRzMIqm82rpwaWqr2pufB4/t/DzCdnYZVlj0ctUCihRSOMrEQvBpHLkmT18cIsfS9PF6KggUgi2J06yBwqaDis0NrzMSuIS3J@oFSOTomcJ42kWJIakGHY0LlAJFWCIedK1mkU1E86iQOdgAlMgoHhdx2YUCfVzQBoXgUkD9esp2zaB5rW2wEwNGkaix6UqMC5RQ64iah2wpopYaB@1rJobOFVEDnbAM4gXSfVZxcICmLJrFRj@5wL7Xz4BPd8ks@v3Tg0wW2fgrqpNA/725AC3tCFw1ZDLJjdfF1v4ohKLTWDhQHj3DoC089dGUv8zZ34VH48rtIcsSUzx4lptzvAu8@X5Qv/T/CtaJqT2Lc/TpcmXy2K575x7dt/jrM8nybpf6Ezf6/ReubVdt6vYt@@vL14A3a1F7/F@7Y6nr8s9fjfd/ly@6f/4YaX18TitTiVXvc8B6yT88A@FSXpdtfxLYglNXG14NKHkftwwa4gsbCOPbMrcBxHRr8B "C (gcc) – Try It Online")
[Answer]
# JavaScript (ES6), ~~284 ... 274~~ 270 bytes
*Saved 4 bytes thanks to @Shaggy*
Returns an array of strings.
```
s=>(s=s.replace(/\s/g,''),n=s.length,o=[':~('],W=d=g=(x,w=0,h=p=0)=>4*~-x>n?o:h>w?++w>x-2?g(-~x):g(x,w):g(x,w,h+1,o=n-x*x+w*h|(w^x|h^x)&!!(w|h)|w-h>d|w-h==d&w>W?o:[...Array(x)].map((_,Y,a)=>a.map((_,X)=>2*X>=x-w&2*X<x+w&2*Y>=x-h&2*Y<x+h?' ':s[p++]).join``,d=w-h,W=w)))``
```
[Try it online!](https://tio.run/##lU/LboMwELzzFc4ltrEhDzUXVIN66wdUSqI8Cg0EExGMMK1dCeXXqUmaqpVSKfjg2R3vzKwP0Uckd1VW1k4h4qTds1YyH0km3Sop82iXoNFajlIKIaaFYfOkSGtOBVtB74Tghs5ZzFKGNFVsTDkr2Rgz/8E@OdovAuFxXwWEKF870yBFzkljL@2Gv4FyMjFmhaNtTZTNG6S2uuFbjYeDAVINx41yuB93N2PxUPlzY7pyXfepqqJPpPHGPUYlQq90SSOTHF3bhWmm9sJn2lFDUzwaf4PLjuBdYQgeQAA9uSoJ2WD3ILIiDGnMTJb5lsIYh2G7E4UUeeLmIkV7ZAEAyfVA6yJCcF1ADAg4o2X9L@mruH/@OclzQc0rIF07F1UeD3rGmYEz/rj8YXuZXUS/je5n7g964ZkEx3dZg7cEzPQMqKzmYKInII1Kt@fC5MY65MZCuP0C "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 120 bytes
```
≔E⮌⪫⪪S ωιθ≔⁰ηF⊕Lθ¿⁼Lθ×ιι«≔ιη≔ιζ≔ιε»F⊘ιF⊕κF∧⁼Lθ⁻×ιι×⁻ι⊗⊕κ⁻ι⊗⊕λ∨¬η›⁻ζε⁻κλ«≔ιη≔⊕κζ≔⊕λε»¿η«UOη#JεζF›η⊗ζUO⁻η⊗ε⁻η⊗ζψUMKA⊟θ»:~(
```
[Try it online!](https://tio.run/##dVJRT8IwEH6WX9HMly6si89KlhA1KhEhwhvhYcDBGrp2dB1GjP71ed06YSqXtL279vv69XrLJNZLFYuy7Oc530g6jDP6CnvQOdCB4pJOMsENfZJZYSZGc7mhfkA84uH85uPEcez8m47DXwUkwWitNEHQUkMK0sCKPoPcmITufN8nfE3o/a6IRX5MB2TKU8gpt4x45qNz4Rh5zXgSHtohYPhJQORAqmsfY7HHG5GG/JGxbZJ9ufpHw5DLIqcnShpZ9Qam7lSxEEj0i/QHe@aI8CsLyEjTF2Vogu6DhtiAdtwH@5CGZRuQGnG@Dm0B7aK0b3YV6tiyJxXjaCEUfmSCH3npWdygSLOpouBoqgo18pLjiw5WkQPXQk824ViENiQg75YUO@tWpWmMhR8DbPtC2E4aq8w2hdVX/eAYW8xQ7/qLorCy7DqbRc1snXr00Ng8Qi9iUdSd9eY2jMKIMRY6XGidEJM9FvYqn1XmFnQQGSJfWLK9@AY "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔E⮌⪫⪪S ωιθ
```
Strip the spaces from the input, then reverse it and split it into characters, so that we can loop over the characters more easily later.
```
≔⁰η
```
Start with a size of zero, indicating no result found (yet).
```
F⊕Lθ
```
Check all side lengths up to the length of the string. (Throwing a division in would of course make the code faster.)
```
¿⁼Lθ×ιι«≔ιη≔ιζ≔ιε»
```
If the result turns out to be a perfect square then save the square size and also set that as the border size.
```
F⊘ιF⊕κ
```
Loop over the possible border heights and widths (the border width is no greater than the border height, making the gap height no greater than the gap width.)
```
F∧⁼Lθ⁻×ιι×⁻ι⊗⊕κ⁻ι⊗⊕λ∨¬η›⁻ζε⁻κλ«≔ιη≔⊕κζ≔⊕λε»
```
If the size of the border is the desired length and we don't have a solution yet or it's not as square as this solution then update the solution with this square and border sizes.
```
¿η«
```
If we have a solution...
```
UOη#
```
Draw a rectangle of an arbitrary character of the given square size.
```
JεζF›η⊗ζUO⁻η⊗ε⁻η⊗ζψ
```
If the border is small enough to leave a gap then erase the gap. (The drawing command will draw upwards and leftwards for negative values and doesn't like zero values at all.)
```
UMKA⊟θ
```
Replace all (remaining) characters with characters from the input.
```
»:~(
```
Otherwise output `:~(`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~91~~ 85 bytes
```
ÆDżU$<Ạa;ḂEɗʋƇṢƑƇ;€€
ḟ⁶ḟ⁷;©⁶L’²<¥Ðḟ²_ç;,`Wɗ¹?⁸ʋ€$Ẏạ/ÞḢµIH+""Rp"/ḟ@/ŒṬ€ĖP€Sị®Yµ“:~(”¹?
```
[Try it online!](https://tio.run/##y0rNyan8//9wm8vRPaEqNg93LUi0frijyfXk9FPdx9of7lx0bOKxdutHTWuAiOvhjvmPGreBye3Wh1YC2T6PGmYe2mRzaOnhCUDhQ5viDy@31kkIPzn90E77R407TnUDtak83NX3cNdC/cPzHu5YdGirp4e2klJQgZI@UIOD/tFJD3eCzD4yLQBIBj/c3X1oXeShrY8a5ljVaTxqmAs05781kHdoW82hbWWHtgGFrA@3cx2d/HDn4keN@w5tO7TtcDtQZxaU8/@/NgxwcaGzuLg8gN7N1wnPL8pJUYSKKgAhWBKVxwXnEGBxhWRkFivklhaXKCSlcplWmCqUZ5ZkKBhWGHKlJxboQQ3SRtIGwQA "Jelly – Try It Online")
A monadic link that takes the input string as its argument and returns a string either with the formatted output or `:~(`.
[Answer]
# Python 2, ~~287~~ ~~281~~ 279 bytes
```
c=list("".join(input().split()))
l=len(c)
p=[]
for q in range(l*l):x=q%l;y=q/l;s=(l+x*y)**.5;p+=[(abs(x-y)/2,int(s),-x)]*(s%1==0)*(x<s-1>y>=s%2==x%2==y%2or x<1)
if p:d,s,x=min(p);b=(s+x)/2;Y=0;exec"c[b:b]=' '*-x*(b+d<=Y<s-b-d);print''.join(c[:s]);c=c[s:];Y+=1;"*s
else:print':~('
```
[Try it online!](https://tio.run/##JY@9jsIwEIT7PIUVKcra@YFEorFZnuIaFKXAxoBPxhg26JzmXj2XE81MM/pmJs7T7RH6ZTHoHU2Q5@33wwVwIb4n4C1F71bnPPPobQDDs4jDmF0eL/ZkLrDXKVwteOG5TPgsvJrxufGKEHyVxMyFaHcqVjjASROkZuabvnZhAuJ1k/gogIoOccsFpD013WE@IBU9YvqXuejXorTveOYuLMpzTXXC@zowcqURqEorTx1xq2yyJjeDlnrEkpWiSQJ0dd7jccXq5sxVfK29Zfk5aAZJI1cGzUByVMcKO5ULyqwnKz9J@QvlsuRfN0fs/qaJact2acd@3HRjXerY9RTb/A8 "Python 2 – Try It Online")
Uses Python's lexicographic list comparison by using the same values for both choosing a solution and printing it. I'm pretty sure ~~10~~ ~~4~~ 2 or so bytes can still be shaved off.
### Explanation
```
c=list("".join(input().split()))
l=len(c)
p=[]
```
Remove whitespaces by splitting with whitespace and joining with `""`, then convert input to a list for later. Also initialize `l` to length of actual code and `p` to list of valid possibilities.
```
for q in range(l*l):x=q%l;y=q/l;s=(l+x*y)**.5;
```
Loop through all possibilities of gap sizes from `0*0` to `l*l`. Compute the edge length of the square with `l` code chars and `x*y` spaces as `s`.
```
p+=[(abs(x-y)/2,int(s),-x)]*(s%1==0)*(x<s-1>y>=s%2==x%2==y%2or x<1)
```
Check if the following conditions match:
* `s % 1 == 0`, i.e. a perfect square would be formed
* `x < s-1 > y`, i.e. `x` and `y` are at most `s-2` and fit inside the square
* `s % 2 == x % 2 == y % 2`, i.e. both `x` and `y` match the edge's parity and can be centered
* but if `x < 1`, i.e. `x == 0`, ignore all but the perfect square requirement
If the conditions matched, add the following items in a tuple to `p` to find the optimal one:
* `abs(x-y)/2`; first find the minimal difference of `x` and `y` to get the most square gap. This is always even so we divide by 2.
* `int(s)`; next find the minimal side length. Since `s` is an integer and increases as the gap area `x*y`, this sorts by gap area.
* `-x`; next find the maximal width to prefer horizontal gaps. This comes after the area due to how it was developed, but the area is the same for `x*y` and `y*x` so it works.
```
if p:d,s,x=min(p);b=(s+x)/2;Y=0
```
If we found any valid layouts, find the optimal one as described above. Compute the horizontal border `b` and initialize the line number `Y` to 0.
```
exec"c[b:b]=' '*-x*(b+d<=Y<s-b-d);print''.join(c[:s]);c=c[s:];Y+=1;"*s
```
If the line number `Y` is inside the gap (the vertical border is `b+d`, with `d` from the tuple), add the gap width's worth of spaces after the horizontal border in `c`. (The modification of `c` is why we need it to be a list.) Then print a line of the square and remove it from `c`. Repeat `s` times, incrementing the line number.
```
else:print':~('
```
If no layouts were found, fail.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~99~~ 98 bytes
```
#JscQ)=QshKh|oaFtNSf!|%hT1&eT|t{%R2TgeStThT+L@+lJ*Fd2^UJ2
":~("Am/-Qd2tKW=W}~hZrG-QGJj*eKdcJ]H<~>J
```
[Try it online!](https://tio.run/##K6gsyfj/X9mrODlQ0zawOMM7oyY/0a3ELzhNsUY1I8RQLTWkpqRaNcgoJD01uCQkI0Tbx0E7x0vLLcUoLtTLiEvJqk5DyTFXXzfDO8WoxDvcNry2LiOqyF030N0rSyvVOyXZK9bDps7O6/9/pZCMzGKF3NLiEoWkVAXTClOF8sySDAXDCkOF9MQCPSUA "Pyth – Try It Online")
This uses the same algorithm as my Python answer, but many details are significantly changed to be shorter in Pyth.
Pyth shows its age here, since it hasn't been updated in ages and only uses the printable ASCII characters (for code, not data), wasting a lot of space.
Interestingly, if Pyth used the same kind of base-256 packing as Stax, this program could be ⌈98 log256 95⌉ = 81 bytes long, right next to Stax (80 bytes) and Jelly (85 bytes). I think this nicely shows how close golfing languages are even with their drastically different paradigms.
### Explanation (only slightly less unreadable than the code)
`#` wraps everything in a `while True:` that suppresses the message and quits on error.
`JscQ)` `c`hops input (`Q`) at whitespace, `s`ums the parts together and saves the result in `J`.
`^UJ2` makes the list of indices (`U`) of `J` and takes its `2`nd Cartesian power (`^`), resulting in all pairs `[h,w]` with `0<=h<len(J)` and `0<=w<len(J)`.
`+L@+lJ*Fd`: for all (`L`) such pairs `d`, adds (`+`) the square root (`@`…`2`) of (the `l`ength of `J` plus (`+`) the product (`*F`) of the pair `d`) to the left side of the pair, creating a triplet `[side length, gap height, gap width]`.
`f!|%hT1&eT|t{%R2TgeStThT`: `f`ilter for triplets `T` where
* neither of (`!|`):
+ side length (`hT`) modulo 1 (`%`…`1`) is nonzero
+ both of (`&`):
- gap height (`eT`) is nonzero
- either of (`|`):
* each number in the triplet (`R`) modulo 2 (`%`…`2`), with duplicates (`{`) and the first unique (`t`) removed, is nonempty
* the larger (`eS`) of gap height and gap width (`tT`) is `g`reater-or-equal than side length (`hT`)
`S` sorts the triplets lexicographically (by side length, then by gap height). `oaFtN` then `o`rders the triplets by the `a`bsolute difference between gap height and gap width (`tN`).
At this point, if we have no valid solutions, `|` evaluates its second argument, `\n":~("`, which prints and returns `:~(`. `h` takes the optimal solution (or `":"` if none) and it is saved in `K`. Then `h` takes its side length (or `":"` if none), `s` casts it to integer (or fails and quits if none) and it is saved (`=`) in `Q`.
Each of (`m`) `[gap height, gap width]` (`tK`) is then subtracted (`-`) from side length (`Q`) and the result divided by 2 (`/`…`2`). The results are `A`ssigned to `G` and `H`.
Finally, we enter a `W`hile loop. `Z` starts at 0 and each iteration we increment it but use the old value (`~hZ`, think `Z++` in C).
* If (`W`) the old value is in (`{`) the `r`ange `G` to (side length - `G`) (`-QG`), assign (`=`) to `J` the following: `c`hop `J` at position (`]`) `H` and `j`oin the halves with gap width `eK` times (`*`) a space (`d`). If the value was not in the range, just return `J`. If this result is empty, stop the loop.
* Remove (`>`) the first `Q` characters from `J` and assign (`~`) the result to `J`. From the old value of `J`, take (`<`) the first `Q` characters and print them.
Finally, the `#` loop starts again, errors and quits because `cQ)` with `Q` containing a number is invalid.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~95~~ 89 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
…
мDg©Ý3ãʒćnsP-®Q}ʒć‹P}ʒÈËyß_~}Dg_i…:~(ëΣ¦DÆÄsP‚}н©¤_iнë¬Uć᤮Ås<иs;R`X*+šXnª£®θð×ýX}ô»
```
A few bytes here and there can definitely be golfed.
The first three steps of the program are inspired by [*@recursive*'s Stax answer](https://codegolf.stackexchange.com/a/187802/52210), so make sure to upvote him!
[Try it online](https://tio.run/##Ab4AQf9vc2FiaWX//@KApiAKCdC8RGfCqcOdM8OjypLEh25zUC3CrlF9ypLEh@KAuVB9ypLDiMOLecOfX359RGdfaeKApjp@KMOrzqPCpkTDhsOEc1DigJp90L3CqcKkX2nQvcOrwqxVxIfOscKkwq7DhXM80LhzO1JgWCorxaFYbsKqwqPCrs64w7DDl8O9WH3DtMK7//9BIGxvbmcgdGVzdCB0byBzZWUgaWYgaXQgd29ya3MgYXMgaW50ZW5kZWQu) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaCkU6nDpeRfWgLj/X/UsEyBi/PCHpf0QysPzzU@vPjUpCPtecUBuofWBdaC2I8adgYAGYc7DndXHp4fX1frkh6fCdRlVadxePW5xYeWuRxuO9xSHPCoYVbthb2HVh5aEp95Ye/h1YfWhB5pP7fx0JJD6w63Fttc2FFsHZQQoaV9dGFE3qFVhxYfWndux@ENh6cf3htRe3jLod3/a3U0Yw5ts/8fraQNA0o6CkqYbBDLIzUnJ18nJi88vygnRREupwCEIBCTh8KFykO4YDl8TJDqkIzMYoXc0uIShaTUmDzTClOF8sySDAXDCsOYvPTEAj24idrIurXh@h0VcvLz0hVKUoEmlOQrFKemKmSmKWSWKJTnF2UXKyQWK2TmlaTmpaSm6CnFAgA).
**Explanation:**
Step 1: Remove all white-spaces:
```
…
# Push string " \n\t"
м # And remove those from the (implicit) input-string
```
Step 2: Create all possible triplets \$[a,b,c]\$, where \$a\$ is the dimension of the resulting \$a×a\$ square, and \$b×c\$ is the size of the gap. We do this by creating all possible triplets using integers in the range \$[0,a]\$. And then we filter these where all of the following is truthy for the triplet:
* \$a^2-b×c=L\$, where \$L\$ is the length of the string
* \$(a\gt b)\text{ and }(a\gt c)\$
* \$(a\pmod2=b\pmod2=c\pmod2)\text{ or }(min(a,b)\neq0)\$
For example: \$L=28\$ will result in the triplets `[[6,2,4],[6,4,2],[8,6,6]]`.
```
Dg # Get the length of this string (without popping by duplicating first)
© # Store this length in variable `®` (without popping)
Ý # Create a list in the range [0,®]
3ã # Create all possible triplets by repeating the cartesian product 3 times
ʒ # Filter these triplets by:
ć # Extract head; pop and push remainder-list and head to the stack
n # Square the head
sP- # Take the product of the remainder, and subtract it from the squared head
®Q # And check if it's equal to the string length in variable `®`
}ʒ # Filter the remaining triplets further by:
ć‹P # Where the first integer is larger than the other two
}ʒ } # And filter it a third time by:
ÈË # Where all three are either odd or even
~ # Or
yß_ # It does not contain any 0s
```
Step 3: Check if we still have any triplets left. If not, output `":~("`; if we do, determine which one to use by sorting and only leaving the first. We do this by sorting the tuples \$(abs(b-c),b×c)\$.
For example: the triplets `[[6,2,4],[6,4,2],[8,6,6]]` will be sorted to `[[8,6,6],[6,2,4],[6,4,2]]`, after which only `[8,6,6]` remains.
```
Dg_i # If this completely filtered list is now empty:
…:~( # Push string ":~("
ë # Else:
Σ # Sort the triplets by:
¦ # Remove the first character
DÆÄ # Get the absolute difference between the remaining two integers
sP‚ # And pair it with the product of the remaining two integers
}н # After we're done sorting: only leave the first triplet
```
Step 4: Create a list on how we should split the string to insert the spaces. This is done like this:
Given \$[a,b,c]\$, create a list with:
* As first item: \$\frac{a-b}{2}×a + \frac{a-c}{2}\$
* As middle \$b-1\$ items: \${a-c}\$
* As last item: \$a^2\$
For example: triplet `[7,3,5]` will result in the list `[15,2,2,35]`.
```
© # Store this triplet in variable `®` (without popping)
¤_i # If the last value is 0 (which means the string is a square without gap):
н # Simply keep the first value of the triplet
ë # Else:
¬U # Store the first value in variable `X` (without popping)
ć # Extract the first value; pop and push remainder-list and head to the stack
α # Get the absolute difference of this head with the other two values
¤ # Push the last value (without popping the pair itself)
®Ås<и # And repeat it the middle element or `®` minus 1 amount of times
s # Swap to get the difference pair again
; # Halve both values
R` # Push them reversed to the stack
X* # Multiple the first value by `X`
+ # And then add it to the second value
š # Prepend this in front of the repeated list
Xnª # And also append the square of `X`
```
Step 5: And finally we split the string based on this list, join it back together with \$c\$ amount of spaces, split it into parts of size \$c\$, and join those together by newlines. For example:
String `"Alongtesttoseeifitworksasintended."` split according to list `[15,2,2,35]` will result in: `["Alongtesttoseei","fi","tw","orksasintended."]`. This is then joined by \$c=5\$ amount of spaces to `"Alongtesttoseei fi tw orksasintended."`. And then split into parts of size \$a=7\$ to this: `["Alongte","sttosee","i f","i t","w o","rksasin","tended."]`. Which is then joined by newlines to output.
```
£ # Then split the string into parts based on this list
®θð× # Push a string consisting of the last value of `®` amount of spaces
ý # Join the list of substrings by this
X # Push variable `X`
}ô # After the if-else: split the string into parts of that size
» # And then join these by newlines
# (after which the top of the stack is output implicitly as result)
```
] |
[Question]
[
>
> Note: The title of this question should be "Loop It", but because title needs to be at least 15 characters, there are some invisible spaces. This note is such that the challenge can be searched for.
>
>
>
---
### Challenge
Given a finite list of unique integral points in the plane, find a polygon whose vertices are exactly those points, which does not self intersect.
### Details
* As input you can take e.g. two lists with each the x- and y-coordinates or a list of pairs.
* The input list contains at least 3 points.
* Note that this means there is never a unique solution.
* The list of inputs is can be assumed to be not co-linear (the points cannot be contained in one line), this means there actually is such a non-self-intersecting polygon.
* The angles at each vertex is arbitrary, this includes 180°.
* For an input of length `n`, the output should be a permutation `(p1,p2,p3,...,pn)` of `(1,2,3,...,n)` where the `k`-th entry `pk` represents the `p`-th point in the input list. This means we have a line from `p1` to `p2`, a line from `p2` to `p3` etc, as well as a line from `pn` to `p1`. (You can also use the 0-based indices.) **Alternatively** you can just output the list of input points in the right order.
### Examples
Let's say we have the points `[(0,0),(0,1),(1,0),(-1,0),(0,-1)]` and we want to represent following path:
[](https://i.stack.imgur.com/LR3JE.png)
This means we would output the list `[5,1,4,2,3]`
Here some more suggestion to try (I recommend looking at the corresponding plots to verify the goals.)
```
Triangle
[(0,0),(0,1),(1,0)]
S-Curve
[(0,0),(0,1),(0,2),(0,3),(0,4),(1,0),(2,0),(2,1),(2,2),(2,3),(2,4),(3,4),(4,0),(4,1),(4,2),(4,3),(4,4)]
L-Shape
[(4,0),(1,0),(3,0),(0,0),(2,0),(0,1)]
Menger Sponge
[(1,1),(2,1),(3,1),(4,1),(5,1),(6,1),(7,1),(8,1),(9,1),(10,1),(11,1),(12,1),(13,1),(14,1),(15,1),(16,1),(17,1),(18,1),(19,1),(20,1),(21,1),(22,1),(23,1),(24,1),(25,1),(26,1),(27,1),(1,2),(3,2),(4,2),(6,2),(7,2),(9,2),(10,2),(12,2),(13,2),(15,2),(16,2),(18,2),(19,2),(21,2),(22,2),(24,2),(25,2),(27,2),(1,3),(2,3),(3,3),(4,3),(5,3),(6,3),(7,3),(8,3),(9,3),(10,3),(11,3),(12,3),(13,3),(14,3),(15,3),(16,3),(17,3),(18,3),(19,3),(20,3),(21,3),(22,3),(23,3),(24,3),(25,3),(26,3),(27,3),(1,4),(2,4),(3,4),(7,4),(8,4),(9,4),(10,4),(11,4),(12,4),(16,4),(17,4),(18,4),(19,4),(20,4),(21,4),(25,4),(26,4),(27,4),(1,5),(3,5),(7,5),(9,5),(10,5),(12,5),(16,5),(18,5),(19,5),(21,5),(25,5),(27,5),(1,6),(2,6),(3,6),(7,6),(8,6),(9,6),(10,6),(11,6),(12,6),(16,6),(17,6),(18,6),(19,6),(20,6),(21,6),(25,6),(26,6),(27,6),(1,7),(2,7),(3,7),(4,7),(5,7),(6,7),(7,7),(8,7),(9,7),(10,7),(11,7),(12,7),(13,7),(14,7),(15,7),(16,7),(17,7),(18,7),(19,7),(20,7),(21,7),(22,7),(23,7),(24,7),(25,7),(26,7),(27,7),(1,8),(3,8),(4,8),(6,8),(7,8),(9,8),(10,8),(12,8),(13,8),(15,8),(16,8),(18,8),(19,8),(21,8),(22,8),(24,8),(25,8),(27,8),(1,9),(2,9),(3,9),(4,9),(5,9),(6,9),(7,9),(8,9),(9,9),(10,9),(11,9),(12,9),(13,9),(14,9),(15,9),(16,9),(17,9),(18,9),(19,9),(20,9),(21,9),(22,9),(23,9),(24,9),(25,9),(26,9),(27,9),(1,10),(2,10),(3,10),(4,10),(5,10),(6,10),(7,10),(8,10),(9,10),(19,10),(20,10),(21,10),(22,10),(23,10),(24,10),(25,10),(26,10),(27,10),(1,11),(3,11),(4,11),(6,11),(7,11),(9,11),(19,11),(21,11),(22,11),(24,11),(25,11),(27,11),(1,12),(2,12),(3,12),(4,12),(5,12),(6,12),(7,12),(8,12),(9,12),(19,12),(20,12),(21,12),(22,12),(23,12),(24,12),(25,12),(26,12),(27,12),(1,13),(2,13),(3,13),(7,13),(8,13),(9,13),(19,13),(20,13),(21,13),(25,13),(26,13),(27,13),(1,14),(3,14),(7,14),(9,14),(19,14),(21,14),(25,14),(27,14),(1,15),(2,15),(3,15),(7,15),(8,15),(9,15),(19,15),(20,15),(21,15),(25,15),(26,15),(27,15),(1,16),(2,16),(3,16),(4,16),(5,16),(6,16),(7,16),(8,16),(9,16),(19,16),(20,16),(21,16),(22,16),(23,16),(24,16),(25,16),(26,16),(27,16),(1,17),(3,17),(4,17),(6,17),(7,17),(9,17),(19,17),(21,17),(22,17),(24,17),(25,17),(27,17),(1,18),(2,18),(3,18),(4,18),(5,18),(6,18),(7,18),(8,18),(9,18),(19,18),(20,18),(21,18),(22,18),(23,18),(24,18),(25,18),(26,18),(27,18),(1,19),(2,19),(3,19),(4,19),(5,19),(6,19),(7,19),(8,19),(9,19),(10,19),(11,19),(12,19),(13,19),(14,19),(15,19),(16,19),(17,19),(18,19),(19,19),(20,19),(21,19),(22,19),(23,19),(24,19),(25,19),(26,19),(27,19),(1,20),(3,20),(4,20),(6,20),(7,20),(9,20),(10,20),(12,20),(13,20),(15,20),(16,20),(18,20),(19,20),(21,20),(22,20),(24,20),(25,20),(27,20),(1,21),(2,21),(3,21),(4,21),(5,21),(6,21),(7,21),(8,21),(9,21),(10,21),(11,21),(12,21),(13,21),(14,21),(15,21),(16,21),(17,21),(18,21),(19,21),(20,21),(21,21),(22,21),(23,21),(24,21),(25,21),(26,21),(27,21),(1,22),(2,22),(3,22),(7,22),(8,22),(9,22),(10,22),(11,22),(12,22),(16,22),(17,22),(18,22),(19,22),(20,22),(21,22),(25,22),(26,22),(27,22),(1,23),(3,23),(7,23),(9,23),(10,23),(12,23),(16,23),(18,23),(19,23),(21,23),(25,23),(27,23),(1,24),(2,24),(3,24),(7,24),(8,24),(9,24),(10,24),(11,24),(12,24),(16,24),(17,24),(18,24),(19,24),(20,24),(21,24),(25,24),(26,24),(27,24),(1,25),(2,25),(3,25),(4,25),(5,25),(6,25),(7,25),(8,25),(9,25),(10,25),(11,25),(12,25),(13,25),(14,25),(15,25),(16,25),(17,25),(18,25),(19,25),(20,25),(21,25),(22,25),(23,25),(24,25),(25,25),(26,25),(27,25),(1,26),(3,26),(4,26),(6,26),(7,26),(9,26),(10,26),(12,26),(13,26),(15,26),(16,26),(18,26),(19,26),(21,26),(22,26),(24,26),(25,26),(27,26),(1,27),(2,27),(3,27),(4,27),(5,27),(6,27),(7,27),(8,27),(9,27),(10,27),(11,27),(12,27),(13,27),(14,27),(15,27),(16,27),(17,27),(18,27),(19,27),(20,27),(21,27),(22,27),(23,27),(24,27),(25,27),(26,27),(27,27)]
```
[Answer]
## Mathematica ~~29~~ 28 Bytes
`FindShortestTour` (16 Bytes) does the trick but delivers some extraneous info not asked for (the path length, and a return to the starting point).
```
Most@*Last@*FindShortestTour
```
gives just the answer ( -1 byte thanks to @user202729 )
To visualize, use `Graphics@Line[g[[%]]]`, where `%` is the permutation found above and g is the original point list.
Here is the visualization of the solution for the Menger Sponge:
[](https://i.stack.imgur.com/4ZIfj.png)
Here is a solution on a 1000 random points:
[](https://i.stack.imgur.com/oOVVL.png)
The key here is knowing that the shortest tour or traveling salesman problem solution will never yield intersections when Euclidean distance is used as the metric. One of the steps to localize a solution and ensure optimality is to remove such intersections.
[Answer]
# JavaScript (ES6), ~~365~~ 341 bytes
Without any built-in, this turned out to be much longer than I expected. Many bytes are spent detecting collinear overlapping segments.
Takes input as an array of `[x,y]` coordinates. Returns a permutation of the input.
```
f=(a,p=[],o=([p,P],[q,Q],[r,R])=>Math.sign((S=[(p>q?r<q|r>p:r<p|r>q)|(P>Q?R<Q|R>P:R<P|R>Q),...S],Q-P)*(r-q)-(q-p)*(R-Q)))=>[...p,p[0]].some((A,i,P)=>P.some((C,j)=>j>i+1&&P[++j+!i]&&[E=o(A,B=P[i+1],C,S=[]),F=o(A,B,D=P[j]),G=o(C,D,A),H=o(C,D,B)].some(v=>!v&!S.pop())|E!=F&G!=H))?0:a[0]?a.some((_,i)=>r=f(b=[...a],p.concat(b.splice(i,1))))&&r:p
```
### Demo
This snippet logs the output and draws the corresponding path in a canvas.
```
f=(a,p=[],o=([p,P],[q,Q],[r,R])=>Math.sign((S=[(p>q?r<q|r>p:r<p|r>q)|(P>Q?R<Q|R>P:R<P|R>Q),...S],Q-P)*(r-q)-(q-p)*(R-Q)))=>[...p,p[0]].some((A,i,P)=>P.some((C,j)=>j>i+1&&P[++j+!i]&&[E=o(A,B=P[i+1],C,S=[]),F=o(A,B,D=P[j]),G=o(C,D,A),H=o(C,D,B)].some(v=>!v&!S.pop())|E!=F&G!=H))?0:a[0]?a.some((_,i)=>r=f(b=[...a],p.concat(b.splice(i,1))))&&r:p
draw(f([[0,0],[0,1],[1,0]]), 1, 1)
draw(f([[0,0],[0,1],[1,0],[-1,0],[0,-1]]), 61, 21)
draw(f([[4,0],[1,0],[3,0],[0,0],[2,0],[0,1]]), 101, 1)
function draw(a, dx, dy) {
console.log(JSON.stringify(a));
ctx = C.getContext('2d');
ctx.beginPath();
[...a, a[0]].forEach(p => ctx.lineTo(p[0] * 20 + dx, p[1] * 20 + dy));
ctx.stroke();
}
```
```
<canvas id=C></canvas>
```
### How?
Here is the structure of the main recursive function **f()**, leaving aside the intersection testing code for now:
```
f = (a, p = []) => // a = array of points, p = current path
[...p, // build a closed path array P[] by adding the first
p[0]] // point at the end of p[]
.some((A, i, P) => // for each point A at position i in P:
P.some((C, j) => // for each point C at position j in P:
j > i + 1 && // test whether C is at least 2 positions after A
P[++j + // and C is not the last point
!i] && // and i > 0 or C is not the penultimate point
intersection( // and there's an intersection between
A, P[i + 1], C, P[j] // the segments (A, P[i + 1]) and (C, P[j + 1])
) // (j was incremented above)
) // end of inner some()
) ? // end of outer some(); if truthy:
0 // discard this path by stopping recursion
: // else:
a[0] ? // if there's at least one remaining point:
a.some((_, i) => // for each remaining point at position i:
r = f( // do a recursive call with:
b = [...a], // a copy b[] of a[] without a[i] and
p.concat(b.splice(i, 1))) // the extracted point added to the path
) && r // end of some(); return the result, if any
: // else:
p // this is a valid path: return it
```
Below is the detail of the **intersection()** test. [This page](https://www.geeksforgeeks.org/check-if-two-given-line-segments-intersect/) provides a comprehensive explanation about the algorithm used.
```
[ // build an array containing:
E = o(A, B = P[i + 1], C, S = []), // E = test of (A, B, C) (+ initialization of S[])
F = o(A, B, D = P[j]), // F = test of (A, B, D)
G = o(C, D, A), // G = test of (C, D, A)
H = o(C, D, B) // H = test of (C, D, B)
] //
.some(v => // the segments are collinear and overlapping if:
!v & // any value above is 0
!S.pop() // and the corresponding entry in S[] is falsy
) | // the segments intersect if:
E != F & G != H // E is not equal to F and G is not equal to H
```
Finally, here is the definition of the helper function **o()**:
```
o = ( // given three points represented by
[p, P], [q, Q], [r, R] // a lowercase letter for x
) => // and an uppercase letter for y:
Math.sign( //
( // 1) prepend to the array S[]
S = [ // a boolean which is true if the
(p > q ? r < q | r > p : r < p | r > q) | // segment (P, Q) would not contain
(P > Q ? R < Q | R > P : R < P | R > Q), // the point R, assuming that the
...S // 3 points are collinear
], //
// 2) return the orientation of P, Q, R:
Q - P // -1 = counterclockwise
) * (r - q) - (q - p) * (R - Q) // 0 = collinear
) // +1 = clockwise
```
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), ~~42~~ 38 bytes
```
{⍋(⍪,(|z)ׯ1*⊢=⌈/)12○z←0j1⊥¨⍵-⍵[⊃⍋↑⍵]}
```
[Try it online!](https://tio.run/##TZfBjtxEFEX38xVezqCMqHfbVS4v@BLEYhQ0KChSkLIiwAopQhMGwQJlj4SE2LDiB8Kf9I8M9c512l7MrWm73nnPdvft23ffvLz98tu7l6@@un3@8u716xfPn86//P7i1fntr@Xpfuh358d31@fHv59df//m5r/3H/6JT84Pf3x2/vmnT29C5/fv3uTWr@P88OeHv86P/96Ov8/PDz@OsvPb38aLL354erq/LlO5GRI31zH@u7q9Oh4qk1JOKbN3XMsSKUo5pYyzp5Q5z855ds6zc56dxwnAnARycouPuGw2dtxNY@SxIbYGJ3OG1JSWsqT0lJWhPTo1QVFQFVl2dfcMINVBeVAfAAKCIMhdfV0QRGNRq7bTZEJe3cmXqBxNOZpyKjGVmEfMk1pR9o3uuszGfoGTbyhAsV8gw7f4lA1P2z2tKS1lSelDNuKar4OHFlQGpUFtUBxUB@VBfXSUWpUdJvf2Q4YgCIIgCDIhn/7@PlhSesqaT3@7WL@L2BrsHTPMzDAzw8wMMzPM3JaZXjO9ZnrttKlms5rNavapXHeFXWFXqBVqhVfhVUh5fGqXSx3/DlxLXMvZWzIbzMbUDXKD3Ji6wW/wG1O3w51r9GrM3uiYO6cl79OSvZZ8mEs@zCUf5pKtl2y9ZOuF1svlcqkMSoPaoDioDsqD@gAQEFRQd9VOEwRBEARBkAlTz/l6ztdztJ6j9ZyqM1Vnkn6Zjb1jks4knRk6M3S6d7p3OnY6dnrlnmnNG7Jmw/UjcM7XNaWlLCk9ZU0ZA6w8kZUxVm7Iyg1ZGWNljAstqA8AAUEQ5N4QBEEQBEG0lmunKPsbJXCwsNMV3KlgTwV/KhhUwaGKbabYZ4qNpthpyuFhcMw0GSfzZOCosiHaEe2GtkNbYRwcJTZD2xxtM7PNzcJMPCww8MDKAi9LrakbrXFkQTu6ouElL8r@FTYwFsNkmo44mScDRxXOFlhbYGaBm6WuaHjJRic32s2p@ljz4tqxAQ8KTCgwoLCvhC0l7ClhO4mDn0RlGmwl8JXUjq5oeMlp7CdhQ2FpuRy@JfCXaDDxltQZrWhDF7SjKxpessvRTzhmlgyTaTJO5snAsR@TCVwmcJi4fP4XjqxoeJErsoOtIewNYVtg5xSdy8Eeou8f1zxS0YYuaEdXNLzkRdkTwqbAcoTJNBkn82TgqMItArtIndGKNnRBe@rlKzHsGmHbCPtG2DjCzhG2jrB3sJgU3ct6IMosbfOYJbNklsySWdpYk/AO4R0q@8dMeIdwjdSMEMUZojhEFKeI4hhRnCPsL7Kx7Dy5TLMXl8n8sc/hDUORoxoZS9iKsBURsxT7PZTjlpy35MAlJy45crGYEwaFSdG9rAeizNI2j1kyS2bJLJmljTUJ25ITmPa3tDApOYVtMUyedotjWwaTB9uymO1MtrOdp61R9eIybWWT8CzhWcKt5NwlRy45YeniVtnJfiYbmZyjZO/i3CRClHAw4WAiRwkf0zFJyVFKzlJymJLTlBynZN@TA5Vsf7L97Sy5TFvZJFxQuGDqjFa0oQva0RXNeeohqcgpjMWUMCbMCYPCpDAqzNKRpW0es2SWzJJZMksbaxJeK7xWuKza4T2Cy8q5To50LC7J@Zzw5HAn@3EuMls6AOUecpnMH/sIecKAhQGLnCdsWCQ9EfWEDWs5PtnFT9ZxT857cuCTE58c@eTMJ4c@2ct3lszSNo9ZMktmySyZJVhX99Mdv9d0@b12@Un4Pw "APL (Dyalog Classic) – Try It Online")
Input is a list of coordinate pairs.
Output is a 0-based permutation.
`⍵` is the list of points - the argument to `{ }`
`⍵[⊃⍋↑⍵]` is the leftmost-lowest point
`⍵-` translates all points so that leftmost-lowest is at the origin of the coordinate system
`0j1` the imaginary unit i=sqrt(-1)
`0j1⊥¨` decodes the coordinates as if digits in a base-i number system - i.e. turns (x,y) into a complex number ix+y
`z←` assign to `z`
`12○` computes the complex numbers' arguments, a.k.a. theta angles, or [APL circular function](http://help.dyalog.com/16.0/Content/Language/Primitive%20Functions/Circular.htm) 12
`(⍪,(|z)ׯ1*⊢=⌈/)` is a train that computes a boolean mask of where the angles are at a maximum (`⊢=⌈/`), turns the 0 1 in the mask into 1 ¯1 by raising ¯1 to the corresponding power (`¯1*`), multiplies by the magnitudes of the complex numbers `|z`, and concatenates that to the right (`,`) of a tall thin 1-column matrix (`⍪`) of the angles.
`⍋` grade - returns the permutation that would sort the rows of the matrix lexicographically in ascending order
] |
[Question]
[
This challenge requires a small amount of knowledge about [chess](/questions/tagged/chess "show questions tagged 'chess'"). A description of the details required can be found at the bottom if you are not familiar with chess or want a refresher.
For a certain board configuration consisting only of queens we can say that each queens *threat number* is the number of other queens it threatens.
Here is an example board with each queen labeled by their threat number:
```
. . . . . . . .
. . . . . . . .
. . . 2 . . . .
. . . . . . . .
. . . . . . . .
. 2 . 3 . . 2 .
. 1 . . . . . .
. . . . . . . 0
```
A board is at a peaceful standoff if every queen can only attack other queens with the same threat number as themselves.
For example:
```
. . . . . . . .
. . . . . . . .
. 2 . 2 . . . .
. . . . . . . .
. . . . . . . .
. 2 . 2 . . . .
. . . . . . . .
. . . . . . . .
```
Each queen can attack 2 others so it's a peaceful standoff.
As another example:
```
3 . . . . . . 3
. . . . . . . .
. 1 . . . . 1 .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
3 . . . . . . 3
```
Here not all queens have the same threat number. Some threaten 3 others and some only threaten 1 other. However none of the `3`s threaten a `1` (or vice versa) so it's peaceful.
## Task
You will take as input a chessboard and output whether it is a peaceful standoff. You may assume the input board is always the standard chess size of 8 units by 8 units and you may take it as a list of list of booleans, a list of piece locations or any other reasonable format.
You may not require the threat numbers to be pre-calculated in the input. They are shown in the above examples but they are not a part of the input.
You should output one of two consistent distinct values. One when the input is a peaceful standoff and the other when it is not.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to minimize the size of your source code as measured in bytes.
## Test cases
### False
```
. . . . . . . .
. . . . . . . .
. . . Q . . . .
. . . . . . . .
. . . . . . . .
. Q . Q . . Q .
. Q . . . . . .
. . . . . . . Q
. . . . . . . .
. Q . Q . Q . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
```
### True
```
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . Q . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . Q . . . .
. . . . . . . .
. . . . . . . .
. Q . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . Q Q . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. Q . Q . . . .
. . . . . . . .
. . . . . . . .
. Q . Q . . . .
. . . . . . . .
. . . . . . . .
Q . . . . . . Q
. . . . . . . .
. Q . . . . Q .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
Q . . . . . . Q
Q . . . . . . Q
. . Q . . Q . .
. Q . . Q . Q .
. . Q . . . . .
. . . . . Q . .
. Q . Q . . Q .
. . Q . . Q . .
Q . . . . . . Q
```
## Chess
Chess is a game played on an 8 by 8 square grid. Each location on the grid can have up to 1 piece. One such piece is the "queen". Queens can attack any piece that's located in the same row, column, or diagonal as they are, so long as there's not another piece between them an their target. If a piece can attack a piece it is considered to "threaten" that piece.
[Answer]
# JavaScript (ES6), 157 bytes
Expects a binary matrix. Returns an inverted Boolean value.
```
m=>(F=p=>m.some((r,y)=>r.some((v,x)=>!p*([s=0,..."1235678"].map(d=>(g=X=>((X+=d%3-1)|(Y+=~-(d/3)))&8?0:v*(V=m[Y][X])?s+=p|V!=v:g(X))(x,Y=y)),r[x]=s))))(F(1))
```
[Try it online!](https://tio.run/##vVTbTgIxEH3frygkygwsFSQqwQw8yXtDQiDAw2a34Jq92a4EIvrr62IItwCCgmnS5kzPzDm9vlhjS9vKjeJiEDoyGVLiUx2aFFHd5zr0JYAyp0h1tUBjc5KiTJSHnqaSyTnPlm8rd/cP1eyA@1YETpo/ok7aQ6dAzlWlWMYZdAv0WQTnpoKI19VGqTbOQ5v8XnfQ6wywoQsUzdoZGtdG0EGEidmlKaKpepMB6TQHoQllxETJ1zdXScgNdQ65kpbTdD3ZmgY2lJDHYStWbjAC5Dry3Biy/aAfZJEPQ/Vk2c@gGdXZu8GYJ2PmM2J6RUxpc//flGWYLaL2PFqYD8RyIpcaekyr2GGgQ09yLxzBEPx58AMTzjaasRuLH@bXsVjyxRLv4wvjQAFxpODf8MUF/s2AOK@BU8/8wjsgTjJ0dgPi16/gKANi61kc2mJxhhVv6@00IFb3wFhHYnkkuwTEnn9gs96W3hc "JavaScript (Node.js) – Try It Online")
## How?
This code solves the puzzle in two passes:
* When called with \$p=1\$, \$F\$ computes the number of queens that interact with each queen, updates the matrix accordingly and returns \$\text{false}\$.
* When called with \$p=\text{false}\$, \$F\$ tests whether at least one queen interacts with a queen that interacts with a different number of queens.
## Commented
### Main wrapper
```
m => F(F(1)) // call F(1), then call F(false)
```
### Helper function F
```
F = p => // p = pass
m.some((r, y) => // for each row r[] at position y in m[]:
r.some((v, x) => // for each value v at position x in r[]:
!p * ( // do not trigger some() during the 1st pass
[ s = 0, // initialize s to 0 and build the list
..."1235678" // [ 0..3, 5..8 ]
].map(d => // for each direction d in this list:
g(x, Y = y) // invoke g with (X, Y) = (x, y)
), // end of map()
r[x] = s // update m[y][x] to s
) //
) // end of inner some()
) // end of outer some()
```
### Helper function g
```
g = X => // X is passed explicitly,
// Y is passed implicitly
( //
(X += d % 3 - 1) | // add dx = (d mod 3) - 1 to X
(Y += ~-(d / 3)) // add dy = floor(d / 3) - 1 to Y
) //
& 8 ? // if the resulting position is out of bounds:
0 // stop the recursion
: // else:
v * // force the test to fail if there's no queen
// on the source square
(V = m[Y][X]) // let V be the value stored at (X, Y)
? // if there's a queen there:
s += // increment s if:
p | // this is the first pass
V != v // or V is not equal to v
: // else:
g(X) // keep testing this ray
```
[Answer]
# Python3, 301 bytes:
```
lambda b:all(all(len([*t(b,x,y)])==len([*t(b,X,Y)])for X,Y in t(b,x,y))for x in R(8)for y in R(8)if b[x][y])
R=range
def t(b,x,y):
q=[(x,y,X,Y)for X in[-1,0,1]for Y in[-1,0,1]if X or Y]
while q:
x,y,X,Y=q.pop(0)
A,B=x+X,y+Y
if 0<=A<8 and 0<=B<8:
if b[A][B]:yield(A,B)
else:q+=[(A,B,X,Y)]
```
[Try it online!](https://tio.run/##tZTRTsIwFIav7VOccEMrk4CITkIv4AFM6hVkLmbLOq2p3ZgzsqfHtsCApCCIZlnS/2vP6b/T9eRV@Zqpnp8Xi5Q@LWT0HicRxINISmxeyRUOLksce3OvIiGhdEMm3lSTNCtAj0AoWC@zbG7II/atqNZCpBAH8zCoQoIeaRGpF44SntahAwQzGmA9tOltch0bXHW9jtcNjZ5uaZ1uAoaFCL5eheQw0xlgFU5n7TzLcYdoNPLGdN6aeFVrqpWO6wzpaOhDpBIzHA99EwjW3ygMxuGgElwmWMeZcODygw9mLe1Nk@WnL@IuUGg0Gm3YeZBbsx/mtzWr17Na71vPtAMUX@@zsk7Fjtz6LG2t9E6pyv9auflbK@wMK/1DVk79N86ryu3xVWEnWTtNWy93x3phv75Cx5bFX1phu7fr4AmwPygDc9zm@/1W2OaHQduK1Sfm2ortaSy7@RxWbHPOnuMsKhKc6P58UfDys1AQBG@UNlnTtOQ3095F@yOXosTEdmlhUCpkyQv8kCnuQbKabz6pJiEhQnkhVIlTXKePu4QQB752454b37hx341v3fjOjX03vtd48Q0)
[Answer]
# [J](http://jsoftware.com/), 82 71 bytes
```
[:(-:|:)@(*+/)@(=[:+/@(*]=&|[:<./"1|+_*0&=)]*"2(%|)=/~(%|)@1j1^i.@8)-/~
```
[Try it online!](https://tio.run/##tZNdS8MwFIbv8yvOqjZNuybtLsQdDQSEgeDNEe9KHSIrswiCqxdC6V@v7dC66draTQn5eMlJ8vCek7ScjjCMT0c45ZxZkiegETiMIQCsui/h8uZ6Vkbo@JijMI7rqWrUEXqqErG28wgvpLLC3Ju7ga1F7FoT5yQXWhX1ZMI0vHuU5kz4qigFyxarTEuIEBYPy2eT1CvnOJXKHOGVNGMBXPICfWlz4OdyPmGsDgQ@u39avfH1@RouYBK2Woumnv1NTU08NbotnpjoZPm8i3759mFafJh0@/KaLSuX1iqBKqeDDevXtDdkH8vQZB1i2DBfaBDbf7LQ3kU9lIW@FXxXDugPfKCOD7aLhb5qhm0qanK26y1q@ezb9/1gKd8B "J – Try It Online")
Takes input as a list of complex numbers.
We'll consider this example:
```
3 . . . . . . 3
. . . . . . . .
. 1 . . . . 1 .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
3 . . . . . . 3
```
which in complex numbers is `0j0 0j7 7j0 7j7 2j1 2j6`.
* `-/~` Table of differences:
```
0 0j_7 _7 _7j_7 _2j_1 _2j_6
0j7 0 _7j7 _7 _2j6 _2j1
7 7j_7 0 0j_7 5j_1 5j_6
7j7 7 0j7 0 5j6 5j1
2j1 2j_6 _5j1 _5j_6 0 0j_5
2j6 2j_1 _5j6 _5j_1 0j5 0
```
* `(%|)` Each of these differences divided by their magnitude, ie, as unit lengths. Pieces can attack each other only if these normalized vectors are equal to one of the 8 evenly spaced unit vectors:
[](https://i.stack.imgur.com/925Uk.png)
* `=/~(%|)@1j1^i.@8` So, create a 3d table showing where each of the normalized vectors of the difference table is equal to each of the 8 "compass" unit vectors:
```
0 0 0 0 0 0
0 0 0 0 0 0
1 0 0 0 0 0 Differences that point E
0 1 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0 NE
1 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 0 0
0 0 0 0 0 0 N
0 0 1 0 0 0
0 0 0 0 0 0
0 0 0 0 1 0
0 0 0 0 0 0
0 0 1 0 0 0
0 0 0 0 0 0 NW
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 1 0 0 0
0 0 0 1 0 0
0 0 0 0 0 0 W
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 0 0 0 0 0
0 0 0 0 0 0 SW
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 1 0 0 0 0
0 0 0 0 0 0
0 0 0 1 0 0 S
0 0 0 0 0 0
0 0 0 0 0 1
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 1 0 0 0 0 SE
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
```
* `]*"2` Use these as as filters for the original input:
```
0 0 0 0 0 0
0 0 0 0 0 0
7 0 0 0 0 0
0 7 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
7j7 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0j7 0 0 0 0 0
0 0 0 0 0 0
0 0 0j7 0 0 0
0 0 0 0 0 0
0 0 0 0 0j5 0
0 0 0 0 0 0
0 0 _7j7 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 _7 0 0 0
0 0 0 _7 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 _7j_7 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 0j_7 0 0 0 0
0 0 0 0 0 0
0 0 0 0j_7 0 0
0 0 0 0 0 0
0 0 0 0 0 0j_5
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 7j_7 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
```
* The problem now is that only the shortest positive distance in each
direction counts, because the others are blocked by the first piece. The
next series of steps filters these blocked pieces.
* `(=[:+/@(*]=&|[:<./"1|+_*0&=)` Ignoring zeros, take the min of each row (using norm for comparison), and keep only entries equal to that min. These are attackable queens. Then sum the planes, which are guaranteed not to overlap, and check where those equal the normalized differences. This is adjanceny matrix of connected queens:
```
1 1 0 0 1 1
1 1 0 0 1 1
0 0 1 1 0 0
0 0 1 1 0 0
1 1 0 0 1 1
1 1 0 0 1 1
```
* `(-:|:)@(*+/)@` Multiply the rows by the column sums, and check if the matrix is symmetric around the main diagonal:
```
4 4 0 0 4 4
4 4 0 0 4 4
0 0 2 2 0 0
0 0 2 2 0 0
4 4 0 0 4 4
4 4 0 0 4 4
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 30 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-4 thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) (remove an effectively redundant filter of the "direction" `[0,0]`, which also means there's no need to get the threatening queen separately.)
```
+8RĖ×Ɱ2Ż’p`¤¤f€ZḢ
ŒṪç€iƇẈEɗⱮ$Ạ
```
A monadic Link that accepts a list of lists of `1`s (queens) and `0`s (not queens) that yields `1` if there is a peaceful standoff or `0` if not.
**[Try it online!](https://tio.run/##y0rNyan8/1/bIujItMPTH21cZ3R096OGmQUJh5YcWpL2qGlN1MMdi7iOTnq4c9Xh5UBu5rH2h7s6XE@ClKo83LXg////0dEGOigwlksHm5AhNlWG2DQaYmo0xGe8IbqQIUhVLAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/1/bIujItMPTH21cZ3R096OGmQUJh5YcWpL2qGlN1MMdi7iOTnq4c9Xh5UBu5rH2h7s6XE@ClKo83LXg/8PdWx7u2ASUcQNi/4c7mg63cx2d/HDn4keN@w5tO7TtcDtQ/P9/PQUUyIWdH0hAHpkfCFcfCOfjUh/IhceAQCItpIxPcwvo5oBA6jqA1DincQgEkuQgqjsgkOxcQJQDAtGyBb4gDqSCj9Htw@qAQEQ64ELmBcKjBJsFgTjKAVTz0OwDAA "Jelly – Try It Online").
### How?
```
+8RĖ×Ɱ2Ż’p`¤¤f€ZḢ - Helper Link = get queen & threatened queens(
queen coordinate, Q;
all queen coordinates, A
):
¤ - nilad followed by links as a nilad:
8 - eight
R - range -> [1,...,7,8]
Ė - enumerate -> [[1,1],...,[7,7],[8,8]]
¤ - nilad followed by links as a nilad:
2 - two
Ż - zero-range -> [0,1,2]
’ - decrement -> [-1,0,1]
` - use as both arguments of:
p - Cartesian product -> [[-1,-1],[-1,0],[-1,1],[0,-1],[0,0],[0,1],[1,-1],[1,0],[1,1]]
Ɱ - map with:
× - multiply -> [[[-1,-1],...,[-7,-7],[-8,-8]],[[-1,0],...,[-7,0],[-8,0]],[[-1,1],...,[-7,7],[-8,8]], ... ... ... ,[[1,1],...,[7,7],[8,8]]]
+ - (Q) add (vectorises) -> nine lists of potential locations in
each of the eight lines of sight
in proximity order plus the direction
[0,0] which will all be Q
(includes off-board locations)
f€ - for each: filter keep (A) -> nine lists (eight are possibly empty)
Z - transpose
Ḣ - head -> list of threatened queens and Q herself.
ŒṪç€iƇẈEɗⱮ$Ạ - Link = is peaceful?(board):
ŒṪ - truthy multidimensional indices -> all queen coordinates
$ - last two links as a monad - f(all queens):
ç€ - call the Helper link for each queen with all queens on the right
Ɱ - map (across Q in all queens) with:
ɗ - last three links as a dyad - f(Helper results, Q):
Ƈ - keep those for which:
i - first 1-indexed index of Q or 0 if not found
Ẉ - length of each
E - all equal?
Ạ - all?
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 256 bytes
```
#define A(c)for(i=0;i<64;++i)for(m=j=0;j<64;++j)if(j-i&&b[i]>0&b[j]>0){x=i/8-j/8,y=i%8-j%8;t=0;x||(t=(y>0)+1);y||(t=(x>0)*4+4);abs(x)-abs(y)||(t=16<<((x>0)+(y>0)*2));if(t&&!(m&t)){c;}}
f(b,i,j,m,t,y,x)int*b;{A(b[i]++;m|=t)A(if(b[i]-b[j])return 0)return 1;}
```
[Try it online!](https://tio.run/##1ZVRb4IwEMef4VPcXCQ9W6IsxpjULvFzOB8EZWkTcGFdAkE@Ozswe9lcJm46TS659uj/7n5tgch/jqK6vl9vYp1uYM4ijLcZ02ok9WwylpzrNpAoQyGzDxnUMTO@9rxwoZePI3KGHJa50sOpb4ZTUSjdp1F/Ki3p8t2OWcUKWsMDlMV@mtN0MOZjlKvwleXoN67A9mEwmc1Yu4K3ssEDoqSq1vPuWOJZxDKSVeXGLBRaGJEIKwqRo07tIJTlnDWdcS6TnbI4Z6RsAn7TKGYb@5alMPoYBLKqSQfJSqcMS9d1Stdxmki4XWXrxRIUlH4gTjM4VfgpA3xJCB0yVJKQXjKCilmvv4antCeANqUBpJ11naorNRzq7crs76lvwW6AGm6HGq4R9n/OGq7lTb8cNZznG35Jauh@J@FyF/iHKnAe6oP/UPj@sKBL83B0iV9Ru5VbvwM "C (gcc) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 70 bytes
```
E⁸S≔E⁸E⁸⟦⟧ηF⁸F⁸F⁸«Jικ≔⌕AKD⁸✳λQθ¿∧№θ⁰⌈θ«M§θ¹✳λ⊞§§ηⅈⅉ§§ηικ»»⎚⬤η⬤ι⬤λ⁼LνLλ
```
[Try it online!](https://tio.run/##bVDLasMwEDxbXyFyWoFq2lsgJ5O2kNKATXtoKT0YW7FFZMkvhUDJt7u7fjQQKqQdaWd2tFJWpm3mUjMMcattD/u0hrXkO1v7/q3HVAFCiA2Luk4XdqFn@PoWQvIS6YNrOawFv8UfFrz4qn53oCU/ojCYjZ61zSNjIFbq@KhblfXaWfK8HgyZr5IVxoYq9YFDZHPYOo@NNpLfC@rkrCtfQYNd0m3B3p0URP3O5upMogdx44lOQey78k@0YCn5B9Cdn2P8h9aCHkEOF3ZhW6PSFvA0/Ry9BjUEegIj@VPjU9PBq7JFX4LF@nmLjdDYDEMSjiNhuMbJJkzCKRNSZlRM1EhexUv5cHcyvw "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of 8 strings of 8 `Q`s and `.`s. Explanation:
```
E⁸S
```
Input the board and print it to the canvas.
```
≔E⁸E⁸⟦⟧η
```
Start with no Queens being attacked.
```
F⁸F⁸F⁸«
```
Loop over each possible direction for each possible Queen.
```
Jικ≔⌕AKD⁸✳λQθ
```
Look at the pieces at the current position in the current direction.
```
¿∧№θ⁰⌈θ«
```
If there is a Queen at the current position and at least one more Queen in the current direction, then...
```
M§θ¹✳λ⊞§§ηⅈⅉ§§ηικ
```
... move to the next Queen in the current direction, and add the current Queen to the list of Queens that are attacking it.
```
»»⎚⬤η⬤ι⬤λ⁼LνLλ
```
Check that all lists of Queens have elements of the same length. Example: If there are Queens at a1, a8, h1 and h8, then let the lists at those positions be denoted by `a1`, `a8`, `h1` and `h8`, then we have `a1 = [a8, h1, h8]`, `a8 = [a1, h1, h8]`, `h1 = [a1, a8, h8]` and `h8 = [a1, a8, h1]`; each list `a1`, `h8`, `h1` and `h8` contains three elements and those three elements are also all lists of three elements. (Conveniently this is also vacuously true for the squares that don't contain Queens and are therefore empty lists.)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 91 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
Jõ ïJõ
@VmA{8õ@Am*XîíX'+Ãfe_>J©Z<8ãg$...$X
U=Ë£X©[EY]gW md x
Ëe@!Xª[EY]gW me_¥XªZ¥0Ãe}Ãe
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Ckr1IO9K9QpAVm1Bezj1QEFtKljDru1YJyvDZmVfPkqpWjw4w6NnJC4uLiRYClU9y6NYqVtFWV1nVyBtZCB4CstlQCFYqltFWV1nVyBtZV%2blWKpapTDDZX3DZQ&input=WwpbMSwwLDAsMCwwLDAsMCwxXQpbMCwwLDAsMCwwLDAsMCwwXQpbMCwwLDAsMCwwLDAsMCwwXQpbMCwwLDAsMCwwLDAsMCwwXQpbMCwwLDAsMCwwLDAsMCwwXQpbMCwwLDAsMCwwLDAsMCwwXQpbMCwwLDAsMCwwLDAsMCwwXQpbMSwwLDAsMCwwLDAsMCwxXQpdLVE)
Note that there should be an additional empty line in front of the code, but it's not displaying here. Takes input as a 2D array with Queens as `1` and empty spaces as `0`.
This is probably the worst Japt code I've ever written and I am certain there are a lot of improvements to make.
### Explanation
The first line is blank, because Japt automatically stores the result of each line in a variable. If the first line is not blank then its result would overwrite the input
```
# Implicitly store input as U
```
The second line generates the 8 direction vectors a queen can move in, as well as `[0,0]` i.e. "not moving" which is unnecessary but ends up not mattering
```
Jõ ïJõ
Jõ # The range [-1...1]
ï # Get every possible pair with:
Jõ # The range [-1...1] again
# Store as V
```
The third line does the bulk of the work here. It declares a function which takes a pair of coordinates as input, and returns an array indicating the cells in U which are in each of the 9 "directions" relative to those coordinates.
```
@VmA{8õ@Am*XîíX'+Ãfe_>J©Z<8ãg$...$X
@ # Declare a function:
VmA{ Ã # For each direction:
8õ@Am*XîíX'+ # (Get the coordinates for 8 cells in that direction)
8õ@ Ã # For each value X in the range [1...8]
Am*X # Multiply the direction vector by X
® # For each resulting pair:
íX'+ # Add the input coordinates
fe_>J©Z<8Ã # (Remove out-of-bounds coordinates)
f # Keep only coordinates which where:
e_ Ã # Both parts:
>J # Are greater than -1
© # And
Z<8 # Are less than 8
£g$...$X # (Get the values from U at those coordinates)
£ # For each remaining coordinates X:
g # Get the value from U at:
$...$X # Multi-dimensional coordinates X
```
The fourth line calls V on every pair of coordinates that has a queen, counts the number of directions which see another queen, then saves that count back in the same cell of U. Technically the number saved is 1 higher than the threat number since one of the directions is "don't move" but it doesn't affect anything.
```
U=Ë£X©[EY]gW md x
Ë£ # For every cell X in U:
X© # Return 0 if X is 0
[EY]gW # Otherwise call W on the coordinates of X
m # For each direction:
d # True if there are any queens
x # Count the number of true directions
U= # Save the results back into U
```
The fifth line uses W again to get the sightlines, then checks that every cell's sightlines only contain empty spaces and other queens with the same threat number.
```
Ëe@!Xª[EY]gW me_¥XªZ¥0Ãe}Ãe
Ë Ã # For every row D of U:
e@ } # True if every cell X in that row returns true:
!Xª # Return true if X is 0
[EY]gW # Otherwise call W on the coordinates of X
m # For each direction:
e_ Ã # True if every cell Z in that direction returns true:
¥X # Z == X
ª # Or
Z¥0 # Z == 0
e # Return true if every direction returned true
e # Output true if every row returned true
```
[Answer]
# [Raku](https://raku.org/), 122 bytes
```
{my%x=@^q.map:{$^q=>map {first(@q.any,($q,*+$^d...*)[1..7])//|()},((-1,0,1)X+(-i,0,i))};[&&] %x{*}.map:{[==] @^v,|%x{@v}}}
```
[Try it online!](https://tio.run/##bVBdj4IwEHz3V2yMSmtLBRS4nAfhL9ybCYGEi5A0OVTwIxjsb@e6FN/uoZPNzOzsdi9l@xsM9RNWFURDXz@XXZTkjaiLy2e/yJso1hX0lWyvN5I0ojg9OVk0fM0W@VEIsaapK0SY0c3mRajihNgud7hLD4zYUleSUrVPV6sMll2/ViY4jaIMkvzBX5pMHkqpoTq38OUyV4LLPAlbA76EAKuQOTLmaAiQ1uBr0Ayh@vlsKzkd5a2R0ethN0aYRg@TJ2aMR9rRueCwECeEZoxxBVPf/4Z3lvfeZPSbVX38g4cw/sFjOwk7VHHLGOwYkuZelqcr9DMAffnk51y0R4ggtYQFXQcf2Yh7LRstDcEGIessFW2Zaaf1bQEebEpCp7jcbyP3Mj0cKjLJ@jLz@X6mZsMf "Perl 6 – Try It Online")
Input is a list of complex numbers, the queen coordinates.
* `my %x = @^q.map: { $^q => ... }` generates a hash from each queen to a list of the other queens that it threatens, storing it in the variable `%x`.
* `(-1, 0, 1) X+ (-i, 0, i)` crosses the real numbers -1, 0, and 1 with the complex numbers -i, 0, and i with addition, producing the nine complex numbers -1-i, -1, -1+i, -i, 0, i, 1-i, 1, and 1+i. These are the steps that will be followed from each queen, looking for another queen that it threatens. For brevity, we don't omit the step 0, so each queen will count as attacking itself. That doesn't change the final boolean answer.
* `first(@q.any, ($q, * + $^d ... *)[1..7]) // |()` takes up to seven steps from each queen, stopping when it encounters one of the other queens. `first` returns `Nil` if it doesn't find anything, so the `// |()` converts that into a Slip object, which doesn't leave anything in the output list.
* `[&&] %x{*}.map: { [==] @^v, |%x{@v} }` checks that each hash value `@^v` (that is, each list of threatened queens) satisfies the condition that its size is equal to the sizes of every other list of queens threatened by those queens.
[Answer]
# Java 10, ~~248~~ ~~246~~ ~~241~~ ~~239~~ ~~237~~ ~~219~~ ~~217~~ 212 bytes
```
b->{boolean r=1>1,B;for(int m[]=new int[64],f=128,i,d,X,Y;f-->0;)for(d=9;b[i=f%64]&d-->0;m[i]+=B&&b[Y+=X*8]?f/64:0,r|=f<64&B&&m[i]!=m[Y])for(X=i/8,Y=f%8;(B=~(X+=d/3-1)%9<0&~(Y+=d%3-1)%9<0)&&!b[X*8+Y];);return!r;}
```
Inspired by [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/253415/52210).
-25 bytes thanks to *@ceilingcat*.
Input as a flat boolean-array.
[Try it online.](https://tio.run/##7Vhdb9owFH3nVxgkoqRJCGwIpRhTiYdJe1inqXsgsvKQz80dOMhxOlUs/evM@YChtZkY0A665CGKc5zje65PnPjeOneOfut/W3kzJ47BB4fQZQMAQnnAQscLwHXWBMCNolngUODJ5RW2XQUKKG2IU8wdTjxwDShaufp4ue7NUG/c0yYwjJgsKMEc24gG3zN6POjbWoh6b0yNaL421SwY6vq4C5Wss48uoYsJCtuim@TnwBwTW0UTSXKxpaLphWlfhcagP@xq7AcKR4O@JLCsUxPNsWXnPFNEDFOzBI8J5Ql6kKcq8o23ek9pX4660oMsmPz2uq1IUtPFglm1bKhAFvCE0SaD6QpmKheJOxMqS7F3EfHBXORLvuGM0C/YdpQiV4YB3jmzOLgf5k0exFzOVG8ytwwzWNv9nPM8cTwfD@AsOaV4DuHZ1vJY1/ad3XmeW1c@Vpq/YS/goKoMPVZ8XjP/3/OsHSSWpM8s4V/PeUmqeU7IULWDjsZT9VmpHVT/zvzr35DaQcfjKebtNTmxdtBpbGFe69bsPB20@/pc9DyFr8bum@B6Dari@ct5f2EH/bnwsZ@Dqt7e/eI51owdouuQ8tDhed7LQdsF2LwmmRtqYyZA6CLhZWXy5j7mwbwTJbyzYITyGZVb7zN8CFqlHdelWg91oTcyoaeq5cO/MCYwJjAmsI2W37nlfGDsXZgqs69an1rDVmc9yJORlFhaGenHhBehAhXQjlcMoJSPVRGmjXT1Ew)
**Explanation:**
```
b->{ // Method with boolean-array parameter & boolean return
boolean r=0>1, // Result-boolean, starting at false
B; // Flag whether we're still in boundary
for(int m[]=new int[64], // Array to keep track of queen's thread levels
f=128, // Flag-integer
i, // Index-integer
d, // Direction-integer
X,Y; // X,Y-coordinate integers of a taken direction of a queen
f-->0;) // Loop `f` in the range (128,0]:
for(d=9;b[i=f%64 // Set `i` to `f` modulo-64
]& // If the `i`'th cell contains a queen:
d-->0 // Inner loop `d` in the range (9,0]:
; // After every iteration of loop `d`:
m[i]+= // Increase the current `i`'th threat value by:
B // If we're still in bounds,
&&b[Y+=X*8]? // and `X,Y` contains a threatening† queen:
f/64 // Increase it by `f` integer-divided by 64
// (1 in the first 64 iterations, 0 in the second 64)
: // Else:
0, // Leave it unchanged by increasing with 0
r|= // Also update the result to:
f<64 // If this is within the first 64 iterations
&B // And we're still in bounds:
&&m[i]!=m[Y]) // Check whether the `i` and `X,Y` threat-levels
// are NOT the same
for(X=i/8,Y=f%8; // (Re)set `X,Y` based on `i` and `f`
(B=~(X+=d/3-1) // Go to the next `X`-coordinate based on `d`
%9<0 // And check if it's still in bounds
&~(Y+=d%3-1)%9<0)// Do the same for the `Y`-coordinate
&& // And if we're still in bound:
!b[X*8+Y];); // Stop the inner-most loop if we've encountered a
// threatening† queen
return!r;} // Finally: return the inverse of result `r`
```
*†*: Because we don't skip direction `d=4` (which means `x,y==X,Y`), every queen will have a tread-level one higher than in the challenge description, because it'll increase for its own position (a.k.a. every queen 'threatens' itself). But since this is done for *each* individual queen, it won't matter for the final output.
] |
[Question]
[
Lonely primes (as I call them) are primes, where given a number grid with width `w ≥ 3`, are primes which do not have any other primes adjacent to them orthogonally or diagonally.
For example, if we take this grid where `w = 12` (primes highlighted in bold):
```
1 **2** **3** 4 **5** 6 **7** 8 9 10 **11** 12
**13** 14 15 16 **17** 18 **19** 20 21 22 **23**...
...86 87 88 89 90 91 92 93 94 95 96
**97** 98 99 100 **101** 102 **103** 104 105 106 **107** 108
**109** 110 111 112 **113** 114 115 116 117 118 119 120
```
You can see that only the two primes **103** and **107** have no primes orthogonally or diagonally adjecant whatsoever. I've skipped over a section because there's no lonely primes there. (except 37, actually)
Your task is to, given two inputs `w ≥ 3` and `i ≥ 1`, determine the first lonely prime in a number grid with width `w`, where said lonely prime must be greater than or equal to `i`. Inputs may be taken in any reasonable format (including taking them as strings). It is guaranteed there will be a lonely prime for width `w`.
The grid doesn't wrap around.
Examples:
```
w i output
11 5 11
12 104 107
12 157 157
9 1 151
12 12 37
```
As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code wins!
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~159~~ ~~158~~ ~~149~~ 145 bytes
* Saved a byte thanks to [xanoetux](https://codegolf.stackexchange.com/users/72299/xanoetux); removing one newline character.
* Saved ~~nine~~ thirteen bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat); golfing a break condition.
```
P(n,d,b){for(d=b=1<n;n>++d;)b*=n%d>0;n=b;}F(w,i){w=P(i)&!(P(i-w)|P(i+w)|i%w>1&(P(--i)|P(i-w)|P(i+w))|++i%w>0&(P(++i)|P(i-w)|P(i+w)))?i-1:F(w,i);}
```
[Try it online!](https://tio.run/##fcyxCsIwFAXQWb@iFlreMwk0xSIaU7fO/QAX01DJYJQiZGj77THVQZDS6T7u4b6G3ZrG@xos1VRh3z460FJJfrLCloRogWorbaLLTFipxFiBowZ7J2swmG4gBHM4hCAhTOJKnoaSMfMpf4YDIRNnE4fzn/FsGD9@34vR36/GAvbr1bMz9tVCnOiLjWlUAec0KhDFHOU04tluAYv9PB6CLczyyUb/Bg "C (gcc) – Try It Online")
[Answer]
# JavaScript (ES6), ~~116~~ 104 bytes
Takes input in currying syntax `(w)(i)`.
```
w=>g=i=>!(C=(k,n=d=i+k)=>n>0?n%--d?C(k,n):d>1:1)(0)&[i,x=1,i-1].every(j=>C(x-w)&C(w+x--)|j%w<1)?i:g(i+1)
```
### Test cases
```
let f =
w=>g=i=>!(C=(k,n=d=i+k)=>n>0?n%--d?C(k,n):d>1:1)(0)&[i,x=1,i-1].every(j=>C(x-w)&C(w+x--)|j%w<1)?i:g(i+1)
console.log(f(11)( 5)) // 11
console.log(f(12)(104)) // 107
console.log(f(12)(157)) // 157
console.log(f( 9)( 1)) // 151
console.log(f(12)( 12)) // 37
```
### Commented
```
w => // main function, taking w
g = i => // g = recursive function, taking i
!( //
C = ( // define C:
k, // a function taking an offset k
n = d = i + k // and using n and d, initialized to i + k
) => //
n > 0 ? // if n is strictly positive:
n % --d ? // decrement d; if d does not divide n:
C(k, n) // do a recursive call
: // else:
d > 1 // return true if d > 1 (i.e. n is composite)
: // else:
1 // return true (n is beyond the top of the grid)
)(0) & // !C(0) tests whether i is prime (or equal to 1, but this is safe)
[ // we now need to test the adjacent cells:
i, // right side: i MOD w must not be equal to 0
x = 1, // middle : always tested (1 MOD w is never equal to 0)
i - 1 // left side : (i - 1) MOD w must not be equal to 0
] // for each value j defined above,
.every(j => // and for x = 1, 0 and -1 respectively:
C(x - w) & // test whether i - w + x is composite
C(w + x--) | // and i + w + x is composite
j % w < 1 // or j MOD w equals 0, so that the above result is ignored
) ? // if all tests pass:
i // return i
: // else:
g(i + 1) // try again with i + 1
```
[Answer]
# [Python 2](https://docs.python.org/2/), 144 bytes
```
f=lambda w,i,p=lambda n:all(n%j for j in range(2,n))*(n>1):i*(any(map(p,~-i%w*(i+~w,i-1,i+w-1)+(i-w,i+w)+i%w*(i-w+1,i+1,i-~w)))<p(i))or f(w,i+1)
```
[Try it online!](https://tio.run/##NY3BCsIwEETvfkUuhZ0mOSTHov5LRKtb2u1SKqGX/npMUQ8DM7xhRrf1NUsspb@Mabrdk8mOnf6DdGkcSZrB9PNiBsNiliTPB0UnQEtyDei4pSQbTUlJ3e65yS2x3euQD45t9gGW2OfDw36xz/ZgVX7PAM5KDNSPno5eQNGFZa2RRd8rwZmfQQnxFOIH "Python 2 – Try It Online")
Arguments in order: `w`, `i`.
No external modules used here.
# [Python 2](https://docs.python.org/2/) + sympy, 127 bytes
```
import sympy
f=lambda w,i,p=sympy.isprime:i*(any(map(p,~-i%w*(i+~w,i-1,i+w-1)+(i-w,i+w)+i%w*(i-w+1,i+1,i-~w)))<p(i))or f(w,i+1)
```
[Try it online!](https://tio.run/##LYzNCgIhFIX38xRugntHDXQZzcMYNXQh9eIY4sZXN60WB77zw@GanzHY3slzTFkc1XNd9u3l/O3uRFGkePuGZzo4kX9caAUXKnjHwKppOpUVSLYx1UaRLNqgBNJlMspfrYuc3ZBuBRGvDIQYk9hh7gz28R3ysBT4nQGV@AN2YxdjPw "Python 2 – Try It Online")
Not worthy of a different post, since the only difference here is that it uses `sympy.isprime` instead of a manually implemented prime check function.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 38 bytes
```
xx`@1G*:5MeZpt3Y6Z+>3LZ)ft2G<~)X<a~}2M
```
[Try it online!](https://tio.run/##y00syfn/v6IiwcHQXcvK1Dc1qqDEONIsStvO2CdKM63EyN2mTjPCJrGu1sj3/39DIy5DAxMA) Or [verify all test cases](https://tio.run/##y00syfmf8L@iIsHBMN5dy8rUNzWqoMQ40ixK287YJ0ozrcTA3aZOM8Imsa7WyPd/bIRLyH9DQy5TLkMjLkMDEzBlas5lyWUIZhoBAA).
### Explanation
The code essentially consists of a loop that keeps enlarging the grid as described in the challenge by one row at each iteration.
After creating the grid at each iteration, the last row is removed (we cannot know if those primes are lonely or not) and the remaining numbers are tested to see if at least one lonely prime exists. This is done via 2D convolution.
If there is some lonely prime we exit the loop and output the first such prime. Else we proceed with the next iteration, which will try a larger grid.
(The code actually uses a transposed version of the grid, which is enlarged by columns instead of by rows.)
```
xx % Take two inputs (implicit): w, i. Delete them. They get copied
% into clipboard G
` % Do...while
@ % Push iteration index (1-based)
1G % Push w
* % Multiply
: % Range from 1 to that
5M % Push w again (from automatic clipboard M)
e % Reshape into a matrix with w rows in column-major order
Zp % Is prime? Element-wise
t % Duplicate
3Y6 % Push neighbour mask: [1 1 1; 1 0 1; 1 1 1]
Z+ % 2D convolution, maintaining size
> % Greater than? Element-wise. Gives true for lonely primes
3LZ) % Remove the last column
f % Find linear indices of nonzeros
t % Duplicate
2G % Push i
<~ % Not less than?
) % Use as logical index: this removes lonle primes less than i
X< % Minimum. This gives either empty or a nonzero value
a~ % True if empty, false if nonzero. This is the loop condition.
% Thus the loop proceeds if no lonely prime was found
} % Finally (execute on loop exit)
2M % Push the first found lonely prime again
% End (implicit). Display (implicit)
```
[Answer]
# Julia 0.6, 135 bytes
```
using Primes
f(w,i,p=isprime)=findfirst(j->(a=max(j-1,0);b=min(j+1,w);c=a:b;!any(p,v for v=[c;c+w;c-w]if v>0&&v!=j)&&p(j)&&j>=i),1:w*w)
```
TIO doesn't have the `Primes` package. It's 5 bytes shorter if I'm allowed to return all lonely primes (`findfirst` becomes `find`). Julia's attempt to move functionality out of `Base` is hurting golfing (not a goal of Julia), `Primes` was included in 0.4.
### Ungolfed (mostly)
```
function g(w,i)
for j=i:w*w
a,b=max(j-1,0),min(j+1,w)
c=a:b
!any(isprime,v for v=[c;c+w;c-w]if v>0&&v!=j)&&isprime(j)&&return j
end
end
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 20 bytes
```
+‘ÆRœ^ḷ,ḷ’dạ/Ṁ€ṂḊð1#
```
[Try it online!](https://tio.run/##y0rNyan8/1/7UcOMw21BRyfHPdyxXQeIHzXMTHm4a6H@w50Nj5rWPNzZ9HBH1@ENhsr/rZUOL9cHCrn//x9tqqNgaBiroxBtaGACZBqBmabmcKaOgiWYNgKLAAA "Jelly – Try It Online")
### How it works
```
+‘ÆRœ^ḷ,ḷ’dạ/Ṁ€ṂḊð1# Main link. Left argument: i. Right argument: w.
ð Combine the links to the left into a chain and begin a new,
dyadic chain with arguments i and w.
1# Call the chain to the left with left argument n = i, i+1, ...
and right argument w until 1 of them returns a truthy value.
Return the match.
+ Yield n+w.
‘ Increment, yielding n+w+1.
ÆR Yield all primes in [1, ..., n+w+1].
ḷ Left; yield n.
œ^ Multiset OR; if n belongs to the prime range, remove it; if
it does not, append it.
,ḷ Wrap the resulting array and n into a pair.
’ Decrement all involved integers.
d Divmod; map each integer k to [k/w, k%w].
ạ/ Reduce by absolute difference, subtracting [n/w, n%w] from
each [k/w, k%w] and taking absolute values.
Ṁ€ Take the maximum of each resulting pair.
A maximum of 0 means that n is not prime.
A maximum of 1 means that n has a prime neighbor.
Ṃ Take the minimum of the maxima.
Ḋ Dequeue; map the minimum m to [2, ..., m].
This array is non-empty/truthy iff m > 1.
```
[Answer]
# [Perl 6](http://perl6.org/), ~~113~~ 104 bytes
```
->\w,\i{first {is-prime $_&none $_ «+«flat -w,w,(-w-1,-1,w-1)xx!($_%w==1),(1-w,1,w+1)xx!($_%%w)},i..*}
```
[Try it online!](https://tio.run/##PYrtCYMwAERXuUoUrYk0UlsKNYvUIv4wEPALFaKIE7mFi9mIWDh4d49r8rZ4bOUIRyLemEg0TdQkVdv1mFTHmlaVOUjqVHW1E@vir4sssh5MU01dphmnJgbeMFxckto6jrlHXW4Oxvt/b2tvpioIrvMm6xZvzhEJahiC3@5ni557e4GfIhRgAh@iKYj6YkKXjbCOiVhgkjjGbGHefg "Perl 6 – Try It Online")
[Answer]
# [Clean](https://clean.cs.ru.nl), ~~181~~ ... 145 bytes
```
import StdEnv
@w i=hd[x+y\\y<-[0,w..],x<-[1..w]|x+y>=i&&[x+y]==[a+b\\a<-[y-w,y,y+w]|a>=0,b<-[x-1..x+1]|0<b&&b<w&&all((<)0o(rem)(a+b))[2..a+b-1]]]
```
[Try it online!](https://tio.run/##FY49D4IwFEV3f0WnBkLbUGZKGHQwcWOEDo8PtUkLRtHShN9ufW4n996T3MFOMEe3jG87EQdmjsY9ludKmnU8zZ9D7YlR97HdstB1oeRtzrwQmm2IUgivd2wqZSj9T7RSLWR91wHWgXsWWMhwA5XKWY/ZxlHaMqn3vOwp7UtPKVibJGWaL8lzcmmCfpq2hRAIXGqtY7MCHlKklgWR8TtcLdxekZ8v8RhmcGZ4/QA "Clean – Try It Online")
**Ungolfed:**
```
@ w i
= hd [
x+y
\\ y <- [0, w..]
, x <- [1..w]
| x+y >= i && [x+y] == [
a+b
\\ a <- [y-w, y, y+w]
| a >= 0
, b <- [x-1..x+1]
| 0 < b && b < w && all ((<) 0 o (rem) (a+b)) [2..a+b-1]
]
]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~30~~ 29 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
My guess is this is probably beatable by a fair margin
```
ÆPŒR+€×¥+©⁸’:⁹Ġ®ṁLÞṪFÆPS’¬ð1#
```
A dyadic link taking `i` on the left and `w` on the right which returns the lonely prime.
**[Try it online!](https://tio.run/##AUUAuv9qZWxsef//w4ZQxZJSK@KCrMOXwqUrwqnigbjigJk64oG5xKDCruG5gUzDnuG5qkbDhlBT4oCZwqzDsDEj////Mzj/MTI "Jelly – Try It Online")**
### How?
```
ÆPŒR+€×¥+©⁸’:⁹Ġ®ṁLÞṪFÆPS’¬ð1# - Link: i, w e.g. 37, 12
1# - find the 1st match starting at i and counting up of...
ð - ...everything to the left as a dyadic link
- (n = i+0; i+1; ... on the left and w on the right):
ÆP - is i prime: 1 if so, 0 if not 1
ŒR - absolute range: [-1,0,1] or [0] [-1,0,1]
¥ - last two links as a dyad (w on the right):
× - multiply (vectorises) [-12,0,12]
+€ - add for €ach [[-13,-1,11],[-12,0,12],[-11,1,13]]
- - i.e. the offsets if including wrapping
⁸ - chain's left argument, i
+ - add [[24,36,48],[25,37,49],[26,38,50]]
- - i.e. the adjacents if including wrapping
© - copy to the register
’ - decrement [[23,35,47],[24,36,48],[25,37,49]]
⁹ - chain's right argument, w
: - integer division [[1,2,3],[2,3,4],[2,3,4]]
Ġ - group indices by value [[1],[2,3]]
- - for a prime at the right this would be [[1,2],[3]]
- - for a prime not at an edge it would be [[1,2,3]]
® - recall from register [[24,36,48],[25,37,49],[26,38,50]]
ṁ - mould like [[24,36,48],[[25,37,49],[26,38,50]]]
Þ - sort by:
L - length [[24,36,48],[[25,37,49],[26,38,50]]]
Ṫ - tail [[25,37,49],[26,38,50]]
- - i.e the adjacents now excluding wrapping
F - flatten [25,37,49,26,38,50]
ÆP - is prime? (vectorises) [0,1,0,0,0,0]
S - sum 1
’ - decrement 0
¬ - not 1
```
[Answer]
# Java 8, ~~176~~ 165 bytes
```
w->i->{for(;!p(i)|p(i-w)|p(i+w)|i%w>1&(p(--i)|p(i-w)|p(i+w))|++i%w>0&(p(++i)|p(i-w)|p(i+w)););return~-i;}boolean p(int n){for(int i=2;i<n;n=n%i++<1?0:n);return n>1;}
```
Port of [*Jonathan Frech*' C answer](https://codegolf.stackexchange.com/a/153097/52210).
-11 bytes thanks to *@ceilingcat*.
[Try it online.](https://tio.run/##lVCxbsIwFNzzFa8Dla3UgaCiqjWkW6UO7cJYdTDBUNPk2UpeiBCkv546KXRgAg@@s@7u2b6N2iphncbN8rtNM1WW8KYM7gOAjZeiikwWrSpMyViMXo5k@oqk17q4u8RzxCSBFGbQ1iIxItmvbMHkjWOGH/wm6h5CD2ZQJ/Etc0yIc40fwrCTR53s6bksuSw0VQX@CCObQIJfwyG8WwKnCgK7AvrSsNiRFqmtkIKFtZlWCH4AEiDvn9VRMxtLM0WJMxyYMJzGz6MnPI0HTGLZtACuWmQmhZIUedhas4Tct8fmVBhcf3wq3hUJfaWQ@9@jrvsD47IX5ruSdB7ZiiLnI5Qhy6M0Us5lOxbH/Mgm/CL/@OSPR/fXJiYPFyUe/wPXXjD@CzRB0/4C)
] |
[Question]
[
Do you remember [my mat properly grouped by colors](https://codegolf.stackexchange.com/q/148927/70347)?
[](https://i.stack.imgur.com/8hWGAm.jpg)
Yesterday I was looking at it and realized that some letters fit inside others. Example: a letter `P` fits in the place where the letter `R` goes. So here's a simple challenge: given two letters, return a truthy value if any one of the letters fits inside the other (directly or rotated, but not flipped), or a falsey value if they don't. That is, if the input is `[P,R]` or `[R,P]`, you must return truthy because in both cases one letter fits inside the other. If you get `[L,U]` you must return falsey as neither fit inside the other.
**Rules**
* The input must be two alphanumeric characters in the range [0-9A-Z], as there are also numbers in the mat, in any form you need (two separate chars as two inputs, a list with two chars, a string with the 2 chars, whatever).
* The output must be consistent (the truthy and falsey values must be always the same).
* Following is the table of fittings (note that a letter always fits in its proper place, just in case you get something like `[Y,Y]` as input):
```
char fits inside chars
--------------------------------------------------------
C G,O
F B,E,P,R
G O
I 0,1,7,B,D,E,F,H,K,L,M,N,O,P,R,T,V,W,X,Z
L E
M W
P R
S O
V A
W M
0 O
1 B,E,L
3 O
6 9,O
8 O
9 6,O
```
I solemnly swear that I have tested every fitting in my kid's mat. *(Dries his sweat from his forehead.)*
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so may the shortest code for each language win!
**Some test cases**
```
input output
-------------
[C,G] truthy (C fits inside G)
[G,C] truthy (C fits inside G)
[F,R] truthy (F fits inside R)
[M,W] truthy (both fit inside the other)
[O,S] truthy (S fits inside O)
[T,T] truthy (T fits in its place)
[E,V] falsey (no fit found)
[P,L] falsey
```
---
[Sandbox post](https://codegolf.meta.stackexchange.com/a/14425/70347). Please, forgive me if you spot more fittings that I missed. Many thanks to [Οurous](https://codegolf.meta.stackexchange.com/users/18730/%CE%9Furous) for helping me with the fittings list.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~135~~ ~~130~~ 129 bytes
-1 byte thanks to [Lynn](https://codegolf.stackexchange.com/users/3852/lynn)
```
lambda s:cmp(*s)%2*s[::cmp(*s)|1]in'OIH TIE XI7 RF O8 OGC LI0 O3 O96 VA O6 KI PI WI L1 WMI O0 RIB NI1 FE SOC VID ZIFB1 PF LE1 RP'
```
[Try it online!](https://tio.run/##NccxS8NAGIDh3V/xLnJt6dCrUDXg0MZc/DD1C2lIpOpQlWDApqG5RfC/R25weeDpf/zXqVuOzd3r@H04vn8eGKKPYz@ZDdPL5Wx4if73a9/azqg8UErCs1xTOPQGTWMyWaBX6O2Kao2ueBRyoRYyS70VdEEhG57E4hJ2GlPJPXtxG0vuyBJLkZuxOZ3xtB0mTs0ck8ZBVwS3dVB3wbIMJlUwz0x0Af257Tx@TjPx0/EP "Python 2 – Try It Online")
# [Python 3](https://docs.python.org/3/), 143 bytes
```
lambda*i:any({*i}&{a,c}=={*i}for a,b in zip('CFGILMPSVW013689','GO BEPR O 017BDEFHKLMNOPRTVWXZ E W R O A M O BEL O 9O O 6O'.split())for c in b)
```
[Try it online!](https://tio.run/##Tc1NC4JAEIDhe79iTu1aSyhBH4KHNLVI28VEI7qshrRgKualot9uzq3Lw8AM8zav7l5X876wrn0pH9lNTpQpqxf9TNR3/JEs/1oWzkXdgmQZqAreqqHE8fx9EIpTkurGfLFaE0Z8DrYrIuCgG0t763q7QxAeuYjiJD1fwIUUcLmBEPAyGFzzgQUns2dTqo5qGmZyjGRa/5ckjk8YEN9BvQgNU5Sf0DhG3QQVATFHAE2rqo7KacagoJIN/7T@Bw "Python 3 – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~93~~ 92 bytes
```
O`.
(.)\1|1[BEL]|69|AV|CG|BF|EF|EL|FP|FR|[017BDEFH]I|I[KLMNOPRTVWXZ]|MW|PR|OS|[03689CG]O
^$
```
[Try it online!](https://tio.run/##DcqxDsIgFAXQ/X2HJnVpJCbVjoKAjVQIbaARMXVwcHEwjvffsckZz/f1e3@eZV3pudi5pqre3BlY4tJkNC2OAUKDK8iFgXJQHmnL9vwk1Tl36NLF9Ffr/BjidMvoI5yHHZa0aw6t0NkSPValCE1akPLUR7IDjSPJQM78AQ "Retina – Try It Online") Edit: Saved 1 byte thanks to @ovs.
[Answer]
# [Clean](https://clean.cs.ru.nl), ~~276~~ 226 bytes
Vaguely golfed-ish. Will polish tomorrow.
```
import StdEnv
i a b=isMember b a
t=True
f'C'b=i['GO']b
f'F'b=i['BEPR']b
f'O'b=i['GS03689']b
f'I'b=i['017BDEFHKLMNOPRTVWXZ']b
f'L''E'=t
f'P''R'=t
f'V''A'=t
f'M''W'=t
f'1'b=i['BEL']b
f'6''9'=t
f _ _=False
?a b=a==b||f a b||f b a
```
[Try it online!](https://tio.run/##NY9Ba8JAEIXv@RVzm5OgFLQeFqmaWGnShERUWkRmk01ZyMaSrIWCv73bTcee9nvv7TDzykZR68ylujYKDOnWafN56SwUtgrbr0ADgRS6T5SRqgMJFFix664qqHGFPnnHTYon6WXEchlmORvpPS/GD9PHOXtb9saT2XIdRs8vcfKaZvlufzi@8YcYMURhPWWIOdMe8YkpQTwwTf63xTw3RZz/JXCGs4io6VWwGG4nIeTtVg89hsc3cIUl31DAAvwM@DvdT1k39NG7UfXdktGlp23s1nfxCw "Clean – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~149~~ 145 bytes
```
[]!_=0>1
(a:b:c)!t=(a,b)==t||(b,a)==t||c!t
f x y=x==y||"0I0O1B1E1I1L3O696O7I8O9OAVBFBICGCODIEFEIELFIFPFRGOHIIKILIMINIOIPIRITIVIWIXIZMWOSPR"!(x,y)
```
[Try it online!](https://tio.run/##bdFRa8IwEADg9/6Kaxk0wQ4sg20KEbRru8N2KbXomIhEqShTJ7ayFvrfu6TDuYcmD0nuC8ldshXZZ7rf1/V8oS9Zd2BrRPRX/TXVc0aEtaKM5VVFVpb4na31XNtAASUrGCuryuhil9sj27XRDh74Y@@RP@Ez7/HhdOSN0PEd/oKu56IbeOhFXuzzV8QxBhjiG3KMMMYEpzjDd/wIZ3wSxYZOCqukdZ5muSOyNAMGcw1kI8R0TAtM36QWJOdLCtS6gq/AaQFPQdwCoYJZC3AFkxZIFCQt4CqYKvDEPktvECkIbtDEF5qmapNeWFBKE8eMyiJPl3ySn4Mj3DXbsu3Xt3zpTgcM2eXQBEo5a9iA@8G/OGl@hV51t4EmAIyp4yHfpke5m/AxNSCVqciFN8RANzTtIHZHef1BnMIlNJn9PX39Aw "Haskell – Try It Online")
[Answer]
# Javascript ~~155 153 151~~ 149 bytes
I think this works on all cases, 1/0 for true/false.
```
(c,f,q=1)=>"CGO,FBEPR,GO,I017BDEFHKLMNOPRTVWXZ,LE,MW,PR,SO,VA,WM,0O,1BEL,3O,69O,8O,96O".split`,`.some((v=>v[0]==c&v.includes(f)))|c==f|(q?F(f,c,0):0)
```
Explanation:
```
F=(
c, // input 1
f, // input 2
q=1 // variable used to execute F twice
)=>(
"CGO,FBEPR,GO,I017BDEFHKLMNOPRTVWXZ,LE,MW,PR,SO,VA,WM,0O,1BEL,3O,69O,8O,96O".split`,`
// array of strings where [0] is input 1 and [>0] are the fittings
.some( // any element of the array meets:
(v=>v[0]==c&v.includes(f)))| // input 1 equals [0] and input 2 exists in the lookup string OR
c==f| // input 1 equals input 2 OR
(q?F(f,c,0):0) // input 2 fits inside input 1
```
```
let F=(c,f,q=1)=>"CGO,FBEPR,GO,I017BDEFHKLMNOPRTVWXZ,LE,MW,PR,SO,VA,WM,0O,1BEL,3O,69O,8O,96O".split`,`.some((v=>v[0]==c&v.includes(f)))|c==f|(q?F(f,c,0):0);
let tests = [
["C","G"], //truthy (C fits inside G)
["G","C"], //truthy (C fits inside G)
["F","R"], //truthy (F fits inside R)
["M","W"], //truthy (both fit inside the other)
["O","S"], //truthy (S fits inside O)
["T","T"], //truthy (T fits in its place)
["E","V"], //falsey (no fit found)
["P","L"] //falsey
];
tests.forEach((v)=>{console.log("F('"+v[0]+"','"+v[1]+"') = " + F(v[0],v[1]))});
```
## Changelog:
* saved 2 bytes thanks to kamoroso94
* saved 2 bytes thanks to Chris M
* saved 2 bytes by changing lookup method to .some()
[Answer]
# [Julia 0.6](http://julialang.org/), 139 bytes
```
(a,b)->(a==b)|any(map(x->all(in.((a,b),x))|all(in.((b,a),x)),zip("OCFILMPV16",split("CGS0368 G BEPR 017BDEFHKLMNOPRTVWXZ E W R A BEL 9"))))
```
[Try it online!](https://tio.run/##NcrBSsNAEAbge59iWAo7C9vQIkQ9pGBjEsXEhDQkpbcJGlhZ11ArVPHd45DFucw3//xvX9ZQOA3RhKR7tdoiRVGvfsl94zuNeFltyVo0LsC5oC@Kn/9Jr2lO9I8ZUZRx@pgXVbsJhf4crTmjiLP9@iq8gQx2SVXDenO9u0/Sh6e8eC6rumm7wxES6KCGO27kcCsUzzR8nIDAOECUsdQyk0oD8tJ8zkyZtWfB7DxL5t6zYTaeCbP1rJi5VGoBPOPJuLN1KJYESxyQgiBQSqjFq3uZ/gA "Julia 0.6 – Try It Online")
Saved some bytes by grouping the chars that fit into 'O'. But testing the reversed input uses too much code...
Explanation:
* `zip(☐)` zips corresponding single letters from `"OCFILMPV16"` & a string of matching letters.
* `.in(☐)` is applied elementwise, e.g. `(in(a,'O'),in(b,"OCFILMPV16"))`
* `all(.in(☐))` Both must be found...
* `|` for either `a,b` or `b,a`...
* `any(map(☐))` for at least one element of the zipped list.
[Answer]
# [Kotlin](https://kotlinlang.org), ~~147~~ 139 bytes
```
fun p(s:String)=setOf(s,s.reversed()).any{it.matches(Regex("(.)\\1|F[BEPR]|I[017BDEFHKLMNOPRTVWXZ]|1[BEL]|69|CG|LE|MW|PR|VA|O[CG69038S]"))}
```
[Try it online!](https://tio.run/##rdfvi6JAGAfw9/0Vc9KLEZZIuquMayHLStJmzsLCNljbxk2utdBpacn@9s5YloU99r4s3uA7PzqPzzO//L2T2yi@XMJDTPY0bU1kEsWPajsVkoU0vUkriXgWSSrWVFUrQfxyimTlKZAPG5FSVzyKI1VoRb2707L@wjC5u8ysRVVrGD2zPxzZzphxd@rN5v4y0/L79jKr61l3kNlm5swy7mZeJ2OL7qCuV2vNyVJR1XNpn0TPgRQkisPoSK6RvUZVuQ8jSdLN7rBdk5W4p6sWMXa7rQhilZxKJG/5o7HcxlQxj3vxIMWaXB8Jdwkpy02Ukvwqr0i7fUvKpyikq3Z7T683VFVhI4WIbSqIMmLf8qacFbV0Ll27fwqimAatTpIELz9fY7l96/HalO5AIR@CIzI5iHcx6CLRd5FwZkiwCRLTKRKm97cIgzwx74Tbn5GvpKTLYEoMKEwoePHED2CkVhUKDYoGFDAfVg8KmDGrD8UQihEUNhQOFGMocOXg@LDg@LDgpLI8KODktuZQ@EjYZvFFhsN8TGDWvQ4SM1j9KuxFg/NFg/nQ4DitwTjqOhTwHU0o9DoUn73jK/sUg8KAC4gJBYfChYLBLahqwfJD0YDCgKIHhQlFH4ohFCMobCgcKMZQMCg4FC4UUyg8KGZQzKHwcfXt4suly4ufHjvefzijwqOSAY9KJhQ2FKxWfEFlWDSLbw5Mh8s2h8Wtwc/1fdiNo8N/g18/8O9DE5Iah8T/Dsm88S9yvlz@AA "Kotlin – Try It Online")
The example on *Try It Online* includes test cases for every positive combination and a few negative ones.
I haven't optimized the reg.ex. too much, so it might be longer than necessary
**EDIT:** saved a few bytes on reg.ex.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 211 bytes
A first attempt. Very straight-forward.
```
i;char*c="CFGILMPSVW013689",*x[]={"GO","BEPR","O","017BDEFHKLMNOPRTVWXZ","E","W","R","O","A","M","O","BEL","O","9O","O","6O"};h(a,b){return(i=strchr(c,a)-c)>=0&&strchr(x[i],b);}f(a,b){return a==b|h(a,b)|h(b,a);}
```
[Try it online!](https://tio.run/##bY1Ra4MwFIWf66@QQGssKbQMunWSwtqpG9MpVnSs7UPM2ipsMlKFjs7f7m5WA3tYyM093@WcGz46cN62hcVzJoacoqXjPnp@uErS8eRqejNDZHhab@kZuQEiaGGHETQpx5Prxb3tPDx5/nMQRnGSvrzC2IZKoZTtDsrv9ML2OjULOjENUGPlmJHMPItdVYsSF/RYCZ4LzAkzR9yc0/Fg0I1O62ILVqvZ/43ojNLs@7IFWgY5q2mLstIPWL6M6LJlpnbWep8C9B6jPtfh0rnef9uUiEhTRnS5F4ympTWaJkMfrCjxJVhXR4xiUVf51@2mHF0OAmvvgI2lQQzX6MAFWCpwACIFPkCqIABYKYgB4l9QX21Kh70fd/98ZoM3UcEQwJPQtD8 "C (gcc) – Try It Online")
[Answer]
# [PHP](https://php.net/), 204 bytes
*-147 bytes because I cam back to remove 2 bytes only to find that my code had a few bugs and unused variables! My code is now much shorter.*
```
<?php $a=fgets(STDIN);for($w=0;$w<2;$w++){if(strpos(explode(',','GO,BEPR,O,017BDEFHKLMNOPRTVWXZ,E,W,R,O,A,M,O,BEL,O,9O,O,6O')[strpos(CFGILMPSVW013689,$a[0])],$a[1])!==false){echo"t";break;}$a=strrev($a);}
```
[Try it online!](https://tio.run/##LY5tC4IwHMS/SsWgjf4vtMCKJdGDWqRNLDQSX6yaGQUOlQqiz24T4uB3L@44TmayridTmckW4mZ6FVWJd/vlektomhcYvUyNotekr9Drkc8txWVVyLzE4i0f@UXgLig5DOaWHwADTR/Ol5a92rjelvnBPowOR7AggiacgQdN01UcMwWDdUn8H1zYztr1/F0YafrAGI0B8VhLSNK4npC2aab8UQryEecs71QdeioEv9Ovuq0WCvHEiBP6revA/gE "PHP – Try It Online")
[Answer]
# Ruby, 140 bytes
```
->c,t{x='CFGILMPSVW013689'.chars.zip('GO BEPR O 017BDEFHKLMNOPRTVWXZ E W R O A M O BEL O 9O O 6O'.split).to_h;p x.key?(c)&&x[c].include?(t)}
```
Pretty much the same as the python 3 answer, but with a different execution.
] |
[Question]
[
A number is in base-b simplified Goodstein form if it is written as
```
b + b + ... + b + c, 0 < c ≤ b
```
The simplified Goodstein sequence of a number starts with writing the number in base-1 simplified Goodstein form, then replacing all 1's with 2's and subtracting 1. Rewrite the result in base-2 simplified Goodstein form, then replace all 2's with 3's and subtract 1, etc. until you reach 0.
Your program is to take a positive integer input and output/print its Goodstein sequence and terminate. Your program should handle numbers less than 100, though it may not terminate in a reasonable amount of time.
For example, given 3 as the input, your program should output (the right side is just explanation)
```
1 + 1 + 1 | 3 = 1 + 1 + 1
2 + 2 + 1 | Change 1's to 2's, then subtract 1. (2 + 2 + 2 - 1 = 2 + 2 + 1)
3 + 3 | 3 + 3 + 1 - 1 = 3 + 3
4 + 3 | 4 + 4 - 1 = 4 + 3
5 + 2 | 5 + 3 - 1 = 5 + 2
6 + 1 | 6 + 2 - 1 = 6 + 1
7 | 7 + 1 - 1 = 7
7 | 8 - 1 = 7
6 | Numbers are now lower than the base, so just keep subtracting 1.
5 |
4 |
3 |
2 |
1 |
0 | End
```
Spacing doesn't matter.
---
## Winning criterion:
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest code wins.
[Answer]
# Python 2, 77 74 bytes
-3 bytes thanks to [Lynn](https://codegolf.stackexchange.com/users/3852/lynn)
```
n=input();b=1
while n:print"+".join(n/b*[`b`]+[`n%b`][:n%b]);n+=n/b-1;b+=1
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P882M6@gtERD0zrJ1pCrPCMzJ1Uhz6qgKDOvRElbSS8rPzNPI08/SSs6ISkhVjs6IU8VSEdbAalYTes8bVugnK6hdZK2reH//8YA)
Easily runs up to n = 100 (though the output is too long for tio fully show).
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 29 bytes
```
WQ=hZj\++*]Z/QZ<]J%QZJ=+Qt/QZ
```
**[Try it here!](https://pyth.herokuapp.com/?code=WQ%3DhZj%5C%2B%2B%2a%5DZ%2FQZ%3C%5DJ%25QZJ%3D%2BQt%2FQZ&input=3&debug=0)**
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 19 bytes
```
Å1[D'+ý,N>D>:`Ž<)0K
```
Could also be rearranged as `>Å1[ND>:`Ž<)0KD'+ý,`
[Try it online!](https://tio.run/##MzBNTDJM/f//cKthtIu69uG9On52LnZWCUf32mgaeP//bwwA "05AB1E – Try It Online")
**Explanation**
```
Å1 # push a list of 1's the length of the input
[ # start a loop
D # duplicate the current list
'+ý, # join on "+" and print
N>D>: # replace <current_iteration>+1 with <current_iteration>+2
` # flatten the list to the stack
Ž # break loop if the stack is empty
< # decrement the top number
) # wrap the stack in a list
0K # remove zeroes
```
[Answer]
# Mathematica, 123 bytes
```
(s=1~Table~#;i=1;While[s!={},Print@StringRiffle[ToString/@s,"+"];s=s/.i->i+1;s=Join[Most@s,{Last@s}-1]~DeleteCases~0;i++])&
```
[Try it online!](https://tio.run/##JYmxCsIwFAB/pVYQJa01OIZIQSdREC04hAypvNgHbQO@bKX59RhxujtuML6DwXh8mWgzmcU1SR4a0/YQlgIlF88Oe1C0kNNc3D44@vrhE953tDaNxv2zqqnIWa4FSaq2WB6Q8eRnh6O6OvJpTxfz41xyHU7Qg4ejIaCwE8iY3qyiVXsdvw "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# Python 3, 155 bytes
```
n=int(input());l=[1]*(n+1);i=0
while l:
l=[t+1 if t==i else t for t in l];l[-1]-=1;l=l[:-1] if l[-1]==0 else l;print("+".join(list(map(str,l))));i+=1
```
This can be reformatted into
```
n = int(input())
l = [0]*(n+1)
i = 0
while l:
l = [t+1 if t==i else t for t in l]
if l[-1] == 0:
l = l[:-1]
print("+".join(list(map(str,l))))
i += 1
```
[Answer]
# Javascript ES6, 121 chars
```
for(q=1,s=Array(+prompt()).fill(1).join`+`;s!=0;s=s.split(q).join(++q).replace(/\d+$/,x=>x-1).replace(/\+0$/,''))alert(s)
```
```
alert=s=>document.write(s+'\n')
document.write("<pre>")
for(q=1,s=Array(+prompt()).fill(1).join`+`;s!=0;s=s.split(q).join(++q).replace(/\d+$/,x=>x-1).replace(/\+0$/,''))alert(s)
```
[Answer]
# [Perl 5](https://www.perl.org/), 71 bytes
```
$,='+';for(@a=(++$")x<>;@a;--$a[-1]||pop@a){say@a;$_+=$_==$"for@a;$"++}
```
[Try it online!](https://tio.run/##K0gtyjH9/19Fx1ZdW906Lb9IwyHRVkNbW0VJs8LGztoh0VpXVyUxWtcwtqamIL/AIVGzujixEiisEq9tqxJva6uiBNQE4itpa9f@/2/8L7@gJDM/r/i/rq@pnoGhAQA "Perl 5 – Try It Online")
] |
[Question]
[
# Goal
You're playing a computerised chess game. The display is in black and white only and the pixels are chunky. White pixels use a lot power compared to black pixels and you're concerned about your carbon footprint.
Given a square and a piece in chess notation, return the number of white pixels displayed in the square.
The solution may be in the form of a function or a complete program.
# Input
A 4-character string defining:
1. One of `wb` for a white or black piece. (Not part of normal Chess notation, but required for this puzzle.)
2. One of `KQBNRP` for a King, Queen, Bishop, kNight, Rook or Pawn.
3. One of `abcdefgh` for the piece's file (column).
4. One of `12345678` for the piece's rank (row).
# Output
The number of white pixels used to draw the chess piece and the underlying square.
# Requirements
* Chess squares are 8x8 pixels and are either all white or all black.
* `a1` is a black square.
* White chess pieces are drawn as white with a black outline. Black pieces are black with a white outline. All pieces have transparent pixels which show the underlying square.
* Input is case-sensitive.
* Assume the input is valid.
The chess pieces have sprites as follows.
`.` is the piece's colour.
`#` is the inverse of the piece's colour.
`/` is the underlying square's colour.
```
King Queen Bishop
//////// //////// ////////
///#.#// /#.#.#.# ///#.#//
//#...#/ //#...#/ //##..#/
///#.#// ///###// //#.#.#/
///###// //#...#/ ///###//
//#...#/ //#...#/ //#...#/
//#...#/ //#...#/ //#...#/
//#.#.#/ //#.#.#/ //#.#.#/
kNight Rook Pawn
//////// //////// ////////
//////// /#.#.#.# ////////
//#..#// /#.....# ////////
/#....#/ /##...## ///#.#//
///#..#/ //#...#/ //#...#/
//#..#// //#...#/ ///#.#//
//#...#/ //#...#/ //#...#/
//#...#/ //#...#/ //#...#/
```
The number of pixels in the piece's colour, piece's outline and underlying square for each piece is:
```
Piece Fill Outline Square
==============================
King 13 16 35
Queen 17 18 29
Bishop 13 18 33
Knight 16 12 36
Rook 23 18 23
Pawn 11 10 43
```
# Test Cases
```
Input Output
wRa1 23
bRa1 18
wPc2 54
bKg8 51
```
# Scoring
The shortest code in bytes by Christmas Day gets a little something extra in their stocking.
[Answer]
# C#6, 107 bytes
Here's my own answer. I don't expect any points being the one who posed the challenge.
I have taken some inspiration from [user81655's answer](https://codegolf.stackexchange.com/a/66649/4934).
```
long P(string a)=>(a[0]>99?12201284685:11042628752)+(a[2]+a[3])%2*46566348643>>"KQBNRP".IndexOf(a[1])*6&63;
```
The pixel counts are encoded in 6-bit blocks. The outline or fill is added to the square (if it's white). Finally, the 6-bit block for the appropriate piece is extracted.
Thankfully, operation precedence worked heavily in my favor.
[Answer]
# JavaScript (ES6), 106
As an anonymous function.
```
x=>(o=+'137999'[p='PNKBQR'.search(x[1])],f=+'262149'[p]+p,(parseInt(x[2]+x[3],19)%2?9:55-f-o)+(x>'w'?f:o))
```
By now, I'm following the simplest way of find the answer with a calculation - this could be not the best way.
Over a black square, the answer is the size of fill for white pieces and the size of outline for black pieces. Over a white square, you need to add the free space. See the table below (inside the snippet)
I keep the size of fill and outline for each piece, the free space inside the square can be found subtracting from 64. To save space, the outline in stored as a single digit afer subtracing 9. The fill is trickier as the range is wider, check the code (that's way the pieces are sorted by occupied space)
Test snippet:
```
F=x=>(
o=+'137999'[p='PNKBQR'.search(x[1])], // get outline - 9
f=+'262149'[p]+p, // get fill -9
(
parseInt(x[2]+x[3],19) // parse with an odd base the differentiate between odd and even rows
%2?9:55-f-o // black square if odd,, white if even so calc free space
) +(x>'w'?f:o) // add fill or outline based on piece color
)
// Test suite
console.log=x=>O.innerHTML+=x+'\n'
for(i=0; z='PNKBQR'[i]; i++)
{
o = '';
t = 'w'+z+'c2'; // white piece, white square
o += t+' '+F(t)+', '
t = 'b'+z+'c2'; // black piece, white square
o += t+' '+F(t)+', '
t = 'w'+z+'a1'; // white piece, black square
o += t+' '+F(t)+', '
t = 'b'+z+'a1'; // black piece, black square
o += t+' '+F(t)
console.log(o);
}
```
```
<pre>
Piece Fill Outline Free w/w b/w w/b b/b
=============================================
Pawn 11 10 43 54 53 11 10
Knight 16 12 36 52 48 16 12
King 13 16 35 48 51 13 16
Bishop 13 18 33 46 51 13 18
Queen 17 18 29 46 47 17 18
Rook 23 18 23 46 41 23 18
</pre>
<pre id=O></pre>
```
[Answer]
# JavaScript (ES6), ~~135~~ 112 bytes
```
s=>(c={K:`\u000a\u0010\u0023`,Q:`\u0011\u0012\u001d`,B:`\u000a\u0012\u0021`,N:`\u0010\u000c\u0024`,R:`\u0017\u0012\u0017`,P:`\u000b\u000a\u002b`}[s[1]])[f="charCodeAt"](s<"w")+((s[f](2)-s[3])%2&&c[f](2))
```
Every `\u00xx` should be a single one-byte character. They are represented here as codes because Stack Exchange automatically removes unreadable characters from posts.
## Explanation
```
s=>
// c = string of three (mostly unreadable) characters, the ASCII code of each character
// represents the number of pixels in the fill, outline and square respectively
(c={
K:`\u000a\u0010\u0023`,
Q:`\u0011\u0012\u001d`,
B:`\u000a\u0012\u0021`,
N:`\u0010\u000c\u0024`,
R:`\u0017\u0012\u0017`,
P:`\u000b\u000a\u002b`
}[s[1]])
[f="charCodeAt"](s<"w") // if piece is black add outline pixels, else add fill pixels
+((s[f](2)-s[3])%2 // this returns 1 if the square is white or 0 if black
&&c[f](2)) // if the square is white add the square's pixels
```
## Test
```
var solution = s=>(c={K:`\u000a\u0010\u0023`,Q:`\u0011\u0012\u001d`,B:`\u000a\u0012\u0021`,N:`\u0010\u000c\u0024`,R:`\u0017\u0012\u0017`,P:`\u000b\u000a\u002b`}[s[1]])[f="charCodeAt"](s<"w")+((s[f](2)-s[3])%2&&c[f](2))
```
```
<input type="text" id="input" value="bKg8" />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```
[Answer]
# Pyth, ~~54~~ 53 bytes
The code contains unprintable characters, so here is a reversible `xxd` hexdump:
```
0000000: 732a 562b 5f57 2543 687a 322c 3031 2573 s*V+_W%Chz2,01%s
0000010: 434d 7474 7a32 4063 434d 2e22 0a2b 011e CMttz2@cCM.".+..
0000020: d699 71d0 c6dc 3db8 eeae 2233 252a 4368 ..q...=..."3%*Ch
0000030: 747a 5433 31 tzT31
```
Alternatively, here's a copy-paste friendly version, which you can also [try online](https://pyth.herokuapp.com/?code=s*V%2B_W%25Chz2%2C01%25sCMttz2%40cCM.%22%5Cn%2B%5Cx01%5Cx1e%5Cxd6%5Cx99q%5Cxd0%5Cxc6%5Cxdc%3D%5Cxb8%5Cxee%5Cxae%223%25*ChtzT31&input=bKg8&debug=0) or use the [test suite](https://pyth.herokuapp.com/?code=s*V%2B_W%25Chz2%2C01%25sCMttz2%40cCM.%22%5Cn%2B%5Cx01%5Cx1e%5Cxd6%5Cx99q%5Cxd0%5Cxc6%5Cxdc%3D%5Cxb8%5Cxee%5Cxae%223%25*ChtzT31&test_suite=1&test_suite_input=wRa1%0AbRa1%0AwPc2%0AbKg8&debug=0):
```
s*V+_W%Chz2,01%sCMttz2@cCM."\n+\x01\x1e\xd6\x99q\xd0\xc6\xdc=\xb8\xee\xae"3%*ChtzT31
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 84 bytes
```
s=>[a=~"0628"[[C,P,F,R]=Buffer(s),i=P%11%7],b=-"63682"[i]||4][C&1]+(F+R&1?45-a-b:19)
```
[Try it online!](https://tio.run/##ZcvNCoIwAADge08hA2XDLdv8yYIVJHjpIl7HDtNUDNFwlRfp1delCOz88V3VU@lybG930g@XytTcaH4Qir/AJmIxECLBGU5xLvnpUdfVCDXCLc9sSu2txAUnIPKjmAHRynkOpEgcKl2YurlDj0FIFCn2dIdMOfR66Kp1NzSwhmDKFQUIWZ5nMX@1wOKHNF7ilJXsg2HwN89N/EVq3g "JavaScript (Node.js) – Try It Online")
### How?
The color, the piece, the file and the rank characters are turned into ASCII codes which are saved into \$C\$, \$P\$, \$F\$ and \$R\$ respectively.
We compute the piece index \$i=(P \bmod 11)\bmod 7\$:
```
char. | code | mod 11 | mod 7
-------+------+--------+-------
'B' | 66 | 0 | 0 Reordered by index:
'K' | 75 | 9 | 2
'N' | 78 | 1 | 1 0 | 1 | 2 | 3 | 4 | 5
'P' | 80 | 3 | 3 ---+---+---+---+---+---
'Q' | 81 | 4 | 4 B | N | K | P | Q | R
'R' | 82 | 5 | 5
```
We compute \$a\$, which is the number of outline squares for the piece, minus \$19\$:
```
a = ~"0628"[i]
```
We compute \$b\$, which is the number of filled squares for the piece, minus \$19\$:
```
b = -"63682"[i] || 4
```
We use `C & 1` to figure out the color of the piece and `F + R & 1` to figure out the color of the square.
The final result is:
```
[a, b][C & 1] // use outline squares if the piece is black
+ // or filled squares if the piece is white
( //
F + R & 1 ? // if the square is white:
45 - a - b // add 19 + (64 - ((a + 19) + (b + 19)))
// = 45 - a - b
: // else:
19 // just add 19
) //
```
[Answer]
# Lua, 158 155 Bytes
```
c,p,l,n=(...):byte(1,4)m="KQBNRP"d={}d[1]={13,17,13,16,23,11}d[0]={16,18,18,12,18,10}p=m:find(string.char(p))print(d[c%2][p]+(l+n)%2*(64-d[0][p]-d[1][p]))
```
Could probably reduce the byte count by encoding the data, but I kinda like the current table method.
Bases color of the square on the ASCII value of 'w' or 'b' taking advantage of the fact that one is even and one is odd. Assigns integer value of the piece based on the position of the piece's symbol in the `m` string variable. Whether a square is dark or light is handled by `(l+n)%2` taking advantage of ASCII value again.
**Ungolfed**
```
c,p,l,n=(...):byte(1,4) --stores input of all characters into variables
m="KQBNRP" --piece encoded string
d={} --data table
d[1]={13,17,13,16,23,11} --fill
d[0]={16,18,18,12,18,10} --outline
p=m:find(string.char(p)) --position in string for position in tables
print(d[c%2][p] + --takes data element from corresponding table according to color of piece and type of piece
(l+n)%2 * --is square black or white? 0 if back, 1 if white
(64-d[0][p]-d[1][p]) --if white, pixels not used by piece would be area (64) minus pixels used by piece, or corresponding data in the tables
)
```
-3 Bytes by removing `c=c%2` before the `print` and using `d[c%2][p]` instead of `d[c][p]`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 41 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Ç`+É•wH˜OÝ•44в*s11%©è•2ĀpakΩÕðβ•₂в2ä+sè®è
```
[Try it online](https://tio.run/##yy9OTMpM/f//cHuC9uHORw2Lyj1Oz/E/PBfIMjG5sEmr2NBQ9dDKwyuAfKMjDQWJ2edWHp56eMO5TUCBR01NFzYZHV6iXXx4xaF1h1f8/5/knW4BAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/w@0J2oc7HzUsKvc4Pcf/8Fwgy8TkwiatYkND1UMrD68A8o2ONBQkZp9beXjq4Q3nNgEFHjU1XdhkdHiJdvHhFYfWHV7xX@d/tFJ5UKKhko5SEoQqD0g2AvG80y2UYgE).
**Explanation:**
```
Ç # Convert the (implicit) input to a list of codepoint integers
` # Pop and push the four integers separated to the stack
+ # Add the top two together (column+row)
É # Check if this is odd (1 if odd/white; 0 if even/black)
•wH˜OÝ• # Push compressed integer 245530244740
44в # Convert it to base-44 as list: [33,36,35,43,29,23,0]
* # Multiply each value by the odd-check
s # Swap so the piece is at the top of the stack
11% # Modulo-11 on that integer
© # Store it in variable `®` (without popping)
è # Index (0-based modulair) it into the list
•2ĀpakΩÕðβ• # Push compressed integer 45866137874521319810
₂в # Convert it to base-26 as list:
# [18,12,16,10,18,18,0,13,16,13,11,17,23,0]
2ä # Split it into two equal-sized parts:
# [[18,12,16,10,18,18,0],[13,16,13,11,17,23,0]]
+ # Add the earlier indexed value to each
s # Swap to get the final integer at the top (square-color)
è # Index (0-based modulair) it into this pair of lists
®è # And then index `®` (piece%11) into this list
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•wH˜OÝ•` is `245530244740`; `•wH˜OÝ•44в` is `[33,36,35,43,29,23,0]`; `•2ĀpakΩÕðβ•` is `45866137874521319810`; and `•2ĀpakΩÕðβ•₂в` is `[18,12,16,10,18,18,0,13,16,13,11,17,23,0]`.
The modulo-11 trick on the piece codepoint was inspired by [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/211576/52210). The trailing `0`s in the lists are just fillers, since 05AB1E indexes modulair, so we don't need the modulo-7 that *Arnauld* uses.
[Try it online for a step-by-step output.](https://tio.run/##jVI9SwNBEO39FcNB0JhYRFKIECRooVho4Q9wczfJLdnsnvthtBMb8QfYaSMWSSOSwlbI2gnib8gfibN7hmhnsXA79@bNe29WGdbhOJ8nB7JwdhuSemv6urOS7Cp5jtpiBlZBqjIsFJcW6GAPtQlAf1NC21lGCOEGEpjMQKsh9fTQ5qjrsZLmmPaBd4HbVQOK4GvDnKc5DJBJU1YZUMkiFBxTrAb609rejr/dS2DNv1WTehx17EwOghsLQ25zoBFwzoRDYu3GmzlzTKMp5w6csLwQlzQBOpfxf5QS2GdXj8P9j/sj/0BfzebXZL00c8L6CAOVOaE2Gg1QMrZFVcsYSnouM7wI3FRRBOMmSgvsptGoTMd@1Pqf6i4XgpIOpMpZwSVdCn6BwvxI3Xy/Klj/c@zv/MvnhAqz6@uvyaZ/Wm4g8CDTgqMulRFHnBIWiCzNA1WtxB9E5b@NCaX/blmRsehkYaJN4rpcMhHy/NtfoaB@MmB2sVtKQzkd/NC7igudPvtRfT7vHPa2vgE)
] |
[Question]
[
I have always failed to give an answer for [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'") challenges which require string compression, the main reason being that I don't know to use string compression tools *as effectively as I should*.
For this reason, I have posted this question. Unlike my other tips questions, this is not language specific meaning that if you can think of any tips in your own language, then you may post it (providing that you specify the language). General tips are also appreciated.
So, how can I use string compression tools to their maximum effectiveness?
[Answer]
# Base conversion (CJam)
An easy way to encode ASCII strings that do not start with a null byte is to convert from base 128 to integer, then to base 256:
```
128b256b:c e# Prints encoded string.
128b256b:c`"256b128b:c" e# Prints encoded string with decoder.
```
This uses 7 bits to encode each ASCII character.
If the original string consists only of, e.g., lowercase letters, and does no start with an **a**, we can start by mapping `"a...z"` to `[0 ... 25]`, then proceed as above:
```
'afm26b256b:c e# Prints encoded string.
'afm26b256b:c`"256b26b'af+" e# Prints encoded string with decoder.
```
Finally, if the original string has only a few unique characters (common in ASCII art), it is usually better to specify the alphabet explicitly.
For example:
```
" +-/\|"f#6b256b:c e# Prints encoded string.
" +-/\|"f#6b256b:c`"256b6b"" +-/\|"`"f=" e# Prints encoded string with decoder.
```
As a rule of thumb, you want the first character of the original string to be the *second* character of the alphabet, the next distinct character of the original string to be the first character of the alphabet, the next distinct character of the original string to be the third character of the alphabet, the next distinct character of the original string to be the fourth character of the alphabet, etc.
The encoder of last example works as follows:
```
" +-/\|"f# e# Replace each character by its index in that string.
6b256b e# Convert from base 6 (length of the alphabet) to base 256.
:c e# Cast each digit to character.
```
The decoder of last example works as follows:
```
256b6b e# Convert from base 256 to base 6.
" +-/\|"f= e# Replace each digit by the corresponding character of the alphabet.
```
[Answer]
Larger Kolmogorov complexity questions with some structure but no simple formula (e.g. song lyrics) will typically benefit from a grammar-based approach. In essence, you extract repeated substrings and encode them somehow. This is what Lempel-Ziv does, using a fairly restricted class of grammars; if you use more general grammars then you have to figure out how to encode the rules. E.g. one approach here is "offset encoding", where you offset each source byte by the number of rules (`n`), assign bytes `1` to `n` to the rules, use the `0` byte to separate rules, and repeatedly replace byte `i` with the evaluated rule `i`. Finally you undo the offset by subtracting `n` from each byte.
I have actually [written a Java program](https://github.com/pjt33/GolfScript-Kolmogorov) which implements various approaches:
>
> Most of the approaches follow a two-phase process. In the first phase the string is converted into a grammar which generates it; in the second phase, the grammar is converted into a GolfScript program. The first phase implementations are largely based on Charikar, Lehman, Liu, Panigrahy, Prabhakaran, Sahai, & Shelat (2005) [The smallest grammar problem](https://www.cs.virginia.edu/~shelat/papers/GrammarIEEE.pdf), Information Theory, IEEE Transactions on, 51(7), 2554-2576.
>
>
>
It also includes a Lempel-Ziv approach, a base encoding approach, and a runlength-encoding approach, and identifies the one which gives the shortest program.
[Answer]
# Stax
In the [Stax](https://staxlang.xyz) code golfing language, there's a helpful little tool called the *string literal compressor*. I don't know how it works, exactly, but there is another where I *do* know how it works. It converts strings into numbers, then into Base 256. It's [CP437](https://en.wikipedia.org/wiki/CP437), with 0x00 and 0xFF converted for copying. It's PackedStax. You could convert your strings with the string literal compressor then Pack it, for some good compression.
Using this process the string "This string is thirty-two bytes" can be converted to v\*"A]-|W4]}3"% (the compressed string is usually surrounded by backticks to tell the difference between a normal string in Stax) and finally to üvìë![┴╩qJu←▓α for a compression / reduction of 18 bytes, more than half.
] |
[Question]
[
Starting with 1, output the sequence of integers which cannot be represented as the sum of powers of earlier terms. Each previous term can be used at most once, and the exponents must be non-negative integers.
This sequence starts:
```
1, 2, 6, 12, 25, 85, 194, 590, 1695, 4879, 19077, 83994, 167988
```
For example, after 1 and 2:
* \$ 3 = 1^1 + 2^1 \$, so 3 is not in the sequence
* \$ 4 = 2^2 \$, so 4 is not in the sequence
* \$ 5 = 1^1 + 2^2 \$, so 5 is not in the sequence
* \$ 6 \$ cannot be represented in this way, so 6 is in the sequence
* etc.
The powers can also be 0; for example, \$ 24 = 1^1+2^4+6^1+12^0 \$, so 24 is not in the sequence.
This is [OEIS A034875](https://oeis.org/A034875).
## Rules
* As with standard [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") challenges, you may choose to either:
+ Take an input `n` and output the `n`th term of the sequence
+ Take an input `n`and output the first `n` terms
+ Output the sequence indefinitely, e.g. using a generator
* You may use 0- or 1-indexing
* You may use any [standard I/O method](https://codegolf.meta.stackexchange.com/q/2447)
* [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061) are forbidden
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins
[Answer]
# [Python 3](https://docs.python.org/3/), ~~121~~ ~~107~~ ~~105~~ ~~102~~ 101 bytes
-3 inspired by Neil's comments, and another -1 thanks to Neil!
Prints the sequence indefinitely. Runs out of memory before finding 25 on TIO.
```
d,*r=0,
while m:=1:
d+=1
for v in r:
w=m
for p in range(d):m|=w<<v**p
if~m>>d&1:r+=d,;print(d)
```
[Try it online!](https://tio.run/##HcpBCoMwEEDRfU4xK2ljFg3dSHS8izBaAyYOgyQI4tXTtJu/eHw@j3WP746lFDJa8GVUXv02Q3BonQJq0SpYdoEEPoJUgoyh9mf8tyl@5gc9XbgwD0PSmhX45Q7jSI110iKZnsXHo06lfAE "Python 3.8 (pre-release) – Try It Online")
---
# [Python 3](https://docs.python.org/3/), ~~186~~ ~~178~~ 166 bytes
Fast version, produces all terms on the OEIS page in 2 minutes locally. Assuming this is correct, the next two terms are \$3828253274\$ and \$24694834727\$. Because of the time is spent in arithmetic with large numbers (native code), a naïve C+gmp translation is only ~2 times faster, and [very ungolfy](https://tio.run/##ZVHJbsMgEL3nK6xElaAmld1eKmF6zyX9gDSyHGMcKGC80FaN/Ot1B1vqehmJefOWGcptXZbTtJHGNd2Q1cbdnB9WG14JaatoFxn3nksrh5VAe3yRdogUESyh3vaythWPdGPrSBNPOEuIO@yPNFCGyBBLWtLTHTIYig2lDaXH80RfDbmXyJAU09ez1BUSGTj8gNoAeTZ3ysImMJtgymPmFwsuX/I2v63eHCCGeExF0yEF4VQmqIrjLzUEURZX4/XC6CFeuvQksNqQFVMpkMJBRbOUIn3N3EEdccY4XbR@0fU/@gj8OVo/nOQAXY7xqauK5xlRjAl8cQdxBD0Rx9R1cE@B1lfaP9k1DNPx72JBmH/7hD1hk3GcTCEtwheB0nt4Tx@l0EXdT1sNPzhtH@8@AQ).
```
m=d=1;r=[]
print(1)
while q:=3:
s=(~m&m+1).bit_length()-1;d+=s;m>>=s
for v in r:
w=q;l=1
while l<=d:q|=w<<l;l*=v
if q&1<<d:break
else:r+=d,;print(d)
m|=q>>d
```
[Try it online!](https://tio.run/##JY7RCsIgGEbvfYr/KmarQHYT6u@LRERD1yR108lGMHp1W3X3weEcvvGV@yE05zGV4lEjEwkvVzImG3LFKFl66wxEjg0nMGH19jtfM3pqbb45Ex65r@iRCV3jJLxSOBHohgQz2ABpU2DBKByy7/qlnETN44qLlE64Pc4bsR3EHZNS8zaZ@5OAcZPhqUZ9EP8nmhLwK0aldCkf "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~24~~ 22 bytes
```
*þṀŻ$ZŒpŒP€Ẏ§‘ḟ$Ṃ;
⁸Ç¡
```
[Try it online!](https://tio.run/##ATUAyv9qZWxsef//KsO@4bmAxbskWsWScMWSUOKCrOG6jsKn4oCY4bifJOG5gjsK4oG4w4fCof//NA "Jelly – Try It Online")
Takes \$n\$ via STDIN and outputs the first \$n\$ terms in reverse order. [+1 byte](https://tio.run/##AToAxf9qZWxsef//KsO@4bmAxbskWsWScMWSUOKCrOG6jsKn4bmA4oCYUuG4n8ay4biiO0AKMcOHwqH///8z) if the output has to be in ascending order.
Incredibly slow, can handle up to \$n = 4\$ on TIO. If \$a\_n\$ is our sequence so far, then, to generate \$a\_{n+1}\$, the code runs in approximately \$O((2a\_n + 2)^n)\$ time.
-2 bytes thanks to [Jonathan Allan](https://codegolf.stackexchange.com/questions/246671/sequence-of-integers-not-the-sum-of-powers-of-earlier-terms#comment552682_246684)
## How it works
```
*þṀŻ$ZŒpŒP€Ẏ§‘ḟ$Ṃ; - Helper link. Given a list L of integers, returns the list with the next term prepended
$ - To L:
Ṁ - Maximum
Ż - [0, ..., max(L)]
þ - Over each pair (l, i), l ∈ L, i ∈ [0, ..., max(L)]:
* - Raise l to the ith power
Z - Transpose
Œp - Cartesian product of rows
ŒP€ - Powerset of each
Ẏ - Collapse into a list of lists
§ - Sums
$ - To our list of sums:
‘ - Increment
ḟ - Remove elements in the list of sums
Ṃ - Minimum
; - Prepend it to L
⁸Ç¡ - Main link. No arguments.
⁸ - Set the return value to []
¡ - Read n from STDIN. Starting with [], do n times:
Ç - Call the helper link, updating the argument with the previous return value each time
```
---
Alternatively, a much faster version at [36 bytes](https://tio.run/##y0rNyan8///hzgaPQ7uNj@7m0jq873B7lM2x9kdNa4If7liiEghkHJ1UcHRSAJDxcFffoeVAxY8aZgQ93DH/2KaHOxZZcz1q3HG4/dDC//8tAA "Jelly – Try It Online") that can do up to \$n = 8\$ on TIO.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 22 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
-rṀṗL‘a*@ɗ⁸§‘ḟ$Ṃ;@
⁸Ç¡
```
A full program that accepts an integer, `n`, from STDIN and prints the Jelly representation of the first `n` terms so STDOUT.
**[Try it online!](https://tio.run/##y0rNyan8/1@36OHOhoc7p/s8apiRqOVwcvqjxh2HlgM5D3fMV3m4s8nagQsocrj90ML//00B "Jelly – Try It Online")** (6 will time out on TIO.)
### How?
```
-rṀṗL‘a*@ɗ⁸§‘ḟ$Ṃ;@ - Link 1, getNext: list KnownTerms
Ṁ - maximum of KnownTerms (given an empty list yields 0)
- - -1
r - inclusive range -> Exponents (-1 is an indicator to exclude the base)
L - length of KnownTerms
ṗ - Cartesian power -> all sets of exponents of size NumberOfTerms
ɗ⁸ - last three links as a dyad - f(Sets, KnownTerms)
‘ - increment all Exponents in the Sets
*@ - KnownTerms exponentiate Sets (vectorises)
a - logical AND (vectorises) (i.e. replace with 0 when the exponent was -1)
§ - sums
$ - last two links as a monad:
‘ - increment all the found values
ḟ - filter out the found values
Ṃ - minimum
;@ - concatenate to KnownTerms
⁸Ç¡ - Main Link: no arguments
⁸ - empty list
¡ - repeat...
- ...times: implicitly take an integer from STDIN
Ç - ...action: call Link 1 as a monad
- implicit print
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), 104 bytes
Prints the sequence forever. Not tremendously fast, but fast enough to reach \$19077\$ on TIO.
```
for(a=N=[];;g``||a.push(N)&print(N))g=(q,i=1,n=++N)=>n<0|!a[i]?0:n<2||g(Q=q*a[i]||1,i,n+q-Q)||g(0,i+1,n)
```
[Try it online!](https://tio.run/##FctNCsIwEEDhs7iRxEwldSW2Y28Q6LoUOgjGcRGT9Gc1d4/t7vHB@9JG8ytzXKrtXsr7lxWhw2FsGj9NInSN6/xRTp9j5rDsoT2qBIw1BDTGaXyG1sqJBh47@wjtTcSrHtPlEJEaGIJJVa8Pt8BmH3Upfw "JavaScript (V8) – Try It Online")
### Note
The way this algorithm works, it would be a bit painful to use \$1^k\$ because we'd need some extra testing to avoid an infinite loop. Instead, we don't use it at all and try to reach either \$n\$ or \$n-1\$ with the other integers. This is why the search function \$g\$ starts at index \$i=1\$ in the array \$a[\:]\$.
---
# [JavaScript (V8)](https://v8.dev/), 101 bytes
Slower but a little shorter.
```
for(a=N=[];;g``||a.push(N)&print(N))g=(q,i=1,n=++N)=>n*a[i]>=0&&n<2|g(Q=q*a[i]||1,i,n+q-Q)|g(0,i+1,n)
```
[Try it online!](https://tio.run/##HctBCoMwEEDR24RME0W7Eux4hIBrERwKptNFmkTrau6ehu4@D/6bLjqemePZXEMp@ydrQofLOo5@20Sojd/jpR2omDmcNcCjTpaxtwGNcYBTuNHC64SdUuFxF69nTH8S6S3bYFIzQ@XOsqkXlPID "JavaScript (V8) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 42 bytes
```
Nθ≔⁰ηW‹Lυθ«≦⊕η≔⟦η⟧ζFυF⮌ζFλ⊞ζ⁻λXκμ¿Πζ⊞υη»Iυ
```
[Try it online!](https://tio.run/##LY69DsIwDIRn@hQebSlILEydEBMSoIoVMZRiSESatPkpUhHPHkLpYstnf3duZO0aW@uUdqaL4RjbKzvsqSw23quHwZUAmaeXVJoB9@x9LuYRJEYS0BPBu1gc6m4@35nGccsm8O0PLubFWV4EjD/hbh1kGKZ@4oGdZxxpFjRBFb3EUcBBmehRC6jsKz/1FNAS/RzUHbBy9habMIETEP95n6JyygTc1j7kFCpTWqfloL8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of @ovs' Python answer, except outputs the first `n` terms.
```
Nθ
```
Input `n`.
```
≔⁰η
```
Start looking for terms.
```
W‹Lυθ«
```
Repeat until enough terms have been found.
```
≦⊕η
```
Try the next integer.
```
≔⟦η⟧ζ
```
Start with a list of just that integer, corresponding to no powers of earlier terms yet.
```
Fυ
```
For each earlier term...
```
F⮌ζ
```
... for each value in a (reversed because it's the golfiest way to) copy of the list...
```
Fλ⊞ζ⁻λXκμ
```
... subtract some powers of the earlier term and add the results to the list.
```
¿Πζ⊞υη
```
If there were no zeros in the list (i.e. the product is nonzero), meaning that no sums of powers added to the current integer, then add it as a term.
```
»Iυ
```
Output all of the found terms.
~~76~~ 74 bytes for a somewhat faster version based on @ovs' faster version:
```
Nθ≔³ε≔⁰ζ⊞υ¹W‹Lυθ«W&εX²ζ≦⊕ζ≔³εFυ«≔εδ≔¹ιW∧⊖꬛ιζ«≧|×δX²ιε≧×κι»»¿¬&εX²ζ⊞υζ»Iυ
```
[Try it online!](https://tio.run/##fZBhS8MwEIY/t7/iPiYQYZ0f92kqyMDNIv6B2N7aY226JakFZb@9XtZmKoIQQl7u8r7PXVFrW3S6GceNOfZ@17dvaMVJrtK1c1QZcasAv9VCwQervHe16BVk/B5qahDEEzrHl6k8V6SCk5TwmSZz9Y78QA7XphSoIO8GDlkGL@7a6uPsvjGFxRaNx3LKSX5DJPvOArsH41hiuzKUos4U0EXPySHyAa@@4sBsu86LR4vaMwVNFJNncmV5oar2EfvZKnilFp0of8CTlDPWn3@XZgWHyHJOw6E9iBD9zzIkxNWG8c9pbsl4ca@d57HlahyzxXjz3nwB "Charcoal – Try It Online") Link is to verbose version of code.
[Answer]
# [Python 3](https://docs.python.org/3/), 179 bytes
```
from itertools import*
def f(n):
x,N=[1],2
while len(x)<n:x=[x+[N],x][N in[sum([N**p for N,p in zip(x,e)if-1<p])for e in product(*[list(range(-1,N))for _ in x])]];N+=1
return x
```
[Try it online!](https://tio.run/##HcpBDsIgEEDRdTkFywHpAo2b2l6BCxBijAVL0gKZ0oheHlu3//30yVMMl1odxoX6bDHHOK/ULyli5mS0jjoIrCNNEWrQ0ogzad6Tny2dbYDC@tCVQZeTVkYUoxX1Qa/bAlpxnqiLSJVIe6Rfn6AIy7xrZZ8MO8gekDCO2zMD17NfM@AjvCy0Uij2f@7HUwwz5qZOgyQN2rzhnmpCHzI4uDJWfw "Python 3 – Try It Online")
It is quite slow, the TIO link will only let you test up to `n=5`
# Explanation
```
from itertools import*
def f(n):
x,N=[1],2 # Initialise the list, start testing from 2
while len(x)<n: # Condition to get the first n terms of the sequence
[N in # Returns False (indexes 0) if N not in list,
x=[x+[N], # appending N to the list,
x] # else leave the list unchanged
[sum([N**p for N,p in zip(x,e) # Sum of the previous sequence terms raised to their respective powers,
if-1<p]) # unless it's not in this permutation (a power of -1 is used to represent a 0 multiplier)
for e in product( # Permutations of the possible powers for the previous terms of the sequence
*[list(range(-1,N))for _ in x])]]; # Possible powers for each previous term of the sequence.
N+=1 # Increment number
return x # Return the sequece
```
The main reason this runs so slow is because there are so many permutations for all the powers, and because list comprehension is used it has to calculate all permutations. Currently all possible powers from `0` to `n-1` are considered, as this was the shortest way to do it in bytes (and still theoretically be able to calculate for any `n`). A faster solution would be to limit the possible powers, for example by replacing `[list(range(-1,N))for _ in x]` with `([[-1,0]]+[[-1]+[i for i in range(int(math.log(N,j))+1)]for j in x[1:]])`, which only lets each term go up to the power such that \$t\_i^p<N\$
[Answer]
# [Ruby](https://www.ruby-lang.org/), 93 bytes
```
*r=p a=1;a+=1while[a]-[0].product(*r.map{|w|[0]+(0..a).map{|e|w**e}}).map(&:sum)==[]||r<<p(a)
```
[Try it online!](https://tio.run/##JcjRCkAwFADQX/GkbbJ4xf2StYeLFUXWZS25vn3E4zkU@jMlReAzhLrFAuo4zYszaEtTWe1pG8NwCEV6RX9x5HcLUWmN8h/HUSl33x9F3uxhlQDGMlPXeYEypQc "Ruby – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 119 bytes
```
while(){map{$o=$_;my$s;map{$s+=$o%$m?$_**($o%$m-1):0;$s-$t||next;$o/=$m}@s}0..($m=2+log(++$t)/.69)**@s;push@s,$t;say$t}
```
[Try it online!](https://tio.run/##HcdZCoMwFAXQzdxChhq1YKF9hLqBrkH8kCoYE/rSQdStNwX/zgndc6wSVltS@vTD2Am5uDYs8BYNuRlMe1lb@APcDY1SYmdWymtB4AxxXafuGwk@t3BbzVthjICzJz36h9AaUebmfJFK1UzhxX3NR0TidkbcUvr5EAc/ccru78qUxR8 "Perl 5 – Try It Online")
Dog slow. *Try it online* found 1, 2, 6, 12, 25, 85, 194 within its 60 second timeout. Same code found 85 within 0.7 seconds on my laptop, 194 within 8 seconds and 590 took 14 minutes.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 28 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
2Lλ∞λ©K.Δ®sÝδm0δšÅ»â}θ€˜Oyå≠
```
Outputs the infinite sequence.
Should have been 27 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage), but a regular reduce-by `.»â}` instead of 'keep last after cumulative reduce-by' `Å»â}θ` doesn't work for some reason.. :/
[Try it online.](https://tio.run/##ATsAxP9vc2FiaWX//zJMzrviiJ7Ou8KpSy7OlMKuc8OdzrRtMM60xaHDhcK7w6J9zrjigqzLnE95w6XiiaD//w)
**Explanation:**
```
λ # Start a recursive environment,
# to generate the infinite sequence
2L # Starting with a(0)=1 and a(1)=2
# Where every next a(n) is calculated as:
∞ # Push an infinite positive list [1,2,3,...]
λ # Push a list of all previous terms [a(0),a(1),...,a(n-1)]
© # Store it in variable `®` (without popping)
K # Remove those values from the infinite list
.Δ # Then find the first value which is truthy for:
® # Push the list of previous terms `®`
s # Swap so the current value is at the top
Ý # Pop and push a list in the range [0,value]
δ # Apply double-vectorized:
m # Exponentiation
δ # Map over each inner list:
0 š # Prepend a 0
Å» # Cumulative right-reduce by:
â # Cartesian product of both list to create pairs
}θ # After the cumulative right-reduce, leave the final result
€˜ # Flatten each inner list
O # Sum each inner list
yå≠ # Check that the current value is NOT in this list of sums
# (after which the result is output implicitly)
```
] |
[Question]
[
Here's an interesting sequence discovered by Paul Loomis, a mathematician at Bloomsburg University. From [his page](https://facstaff.bloomu.edu/ploomis/sequences.html) on this sequence:
Define
`f(n) = f(n-1) + (the product of the nonzero digits of f(n-1))`
`f(0) = x`, with `x` as any positive integer, written in base 10.
So, starting with `f(0)=1`, you get the following sequence
`1, 2, 4, 8, 16, 22, 26, 38, 62, 74, 102, 104, ...`
So far, so standard. The interesting property comes into play when you take any *other* integer as the starting point, eventually the sequence converges into a point along the above `x=1` sequence. For example, starting with `x=3` yields
`3, 6, 12, 14, 18, 26, 38, 62, 74, 102, ...`
Here are some more sequences, each shown only until they reach `102`:
```
5, 10, 11, 12, 14, 18, 26, 38, 62, 74, 102, ...
7, 14, 18, 26, 38, 62, 74, 102, ...
9, 18, 26, 38, 62, 74, 102, ...
13, 16, 22, 26, 38, 62, 74, 102, ...
15, 20, 22, 26, 38, 62, 74, 102, ...
17, 24, 32, 38, 62, 74, 102, ...
19, 28, 44, 60, 66, 102, ...
```
He conjectured, and empirically proved up to `x=1,000,000`, that this property (i.e., that all input numbers converge to the same sequence) holds true.
## The Challenge
Given a positive input integer `0 < x < 1,000,000`, output the number where the `f(x)` sequence converges to the `f(1)` sequence. For example, for `x=5`, this would be `26`, since that's the first number in common to both sequences.
```
x output
1 1
5 26
19 102
63 150056
```
## Rules
* If applicable, you can assume that the input/output will fit in your language's native Integer type.
* The input and output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963).
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins.
[Answer]
# JavaScript (ES6), ~~81~~ 67 bytes
*Saved 1 byte thanks to @l4m2*
```
f=(n,x=1)=>x<n?f(x,n):x>n?f(+[...n+''].reduce((p,i)=>p*i||p)+n,x):n
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVYjT6fC1lDT1q7CJs8@TaNCJ0/TqsIOxNSO1tPTy9NWV4/VK0pNKU1O1dAo0MkEqizQyqypKdDUBurUtMr7n5yfV5yfk6qXk5@ukaZhqKnJhSpiiiFiaIkhZGasqfkfAA "JavaScript (Node.js) – Try It Online")
### Commented
```
f = (n, // n = current value for the 1st sequence, initialized to input
x = 1) => // x = current value for the 2nd sequence, initialized to 1
x < n ? // if x is less than n:
f(x, n) // swap the sequences by doing a recursive call to f(x, n)
: // else:
x > n ? // if x is greater than n:
f( // do a recursive call with the next term of the 1st sequence:
+[...n + ''] // coerce n to a string and split it
.reduce((p, i) => // for each digit i in n:
p * i || p // multiply p by i, or let p unchanged if i is zero
) + n, // end of reduce(); add n to the result
x // let x unchanged
) // end of recursive call
: // else:
n // return n
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~18~~ 14 bytes
```
ḊḢDo1P+Ʋ;µQƑ¿Ḣ
```
Input is a singleton array.
[Try it online!](https://tio.run/##y0rNyan8///hjq6HOxa55BsGaB/bZH1oa@CxiYf2A0X@Wysdbjc8tsT9/39DHQVTHQVDSx0FM2MA "Jelly – Try It Online")
### How it works
```
ḊḢDo1P+Ʋ;µQƑ¿Ḣ Main link. Argument: [n]
¿ While...
QƑ all elements of the return value are unique...
µ execute the chain to the left.
Ḋ Dequeue; remove the first item.
Ḣ Head; extract the first item.
This yields the second item of the return value if it has
at least two elements, 0 otherwise.
Ʋ Combine the links to the left into a chain.
D Take the decimal digits of the second item.
o1 Perform logical OR with 1, replacing 0's with 1's.
P Take the product.
+ Add the product with the second item.
; Prepend the result to the previous return value.
Ḣ Head; extract the first item.
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~111~~ ~~95~~ 93 bytes
Using unpacking in `replace(*'01')` as in @Rod [answer](https://codegolf.stackexchange.com/a/163143/66855)
-18 bytes thanks to @Lynn
```
l=[1,input()]
while cmp(*l):l[0]+=eval('*'.join(`l[0]`.replace(*'01')));l.sort()
print l[0]
```
[Try it online!](https://tio.run/##FcxBCsMgEEDRfU7hzhkbRLNriycJAUMQYpnoYGxDTm@a7efx@axrTkNr5Ebbx8TfCjh1xxopiGVjUIQvGs30cOE3E0gl9SfHBP6OXpfANC8BlDRWIuKb9J7L/9FxiamKWwnRmn1e "Python 2 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 65 bytes
```
(!1)
a!b|a>b=b!a|a<b=(a+product[read[d]|d<-show a,d>'0'])!b|1<2=a
```
[Try it online!](https://tio.run/##DcsxDoMgGAbQvaeASUg1Kd2agBexDh/8Uk2pErBx4ezSvv3NyO8phOrNswqu5AXcFvTWWI4CbY3ANaaNvm4f0gQaaCykuzxvB0NLfXNrRvkvSt8N6gfLygyLaVl3JjxTD1lP5wNeuXYuxh8 "Haskell – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 78 bytes
```
f=lambda a,b=1:a*(a==b)or f(*sorted([a+eval('*'.join(`a`.replace(*'01'))),b]))
```
[Try it online!](https://tio.run/##DcvRCoMgFAbgV@nOc1zI3F0DnySCfpcyw1RMBnt667v/yr99c3r17k3EYTcMGK3Rb0iCMZZzHTzJM9fmNprxcD9EElKoPYdEK1ZVXYn4OJLiqQUzj3Zh7qWG1O6qJ@4X "Python 2 – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 13 bytes
```
→UΞm¡S+ȯΠf±dΘ
```
Takes input as a singleton list.
[Try it online!](https://tio.run/##ASIA3f9odXNr///ihpJVzp5twqFTK8ivzqBmwrFkzpj///9bNjNd "Husk – Try It Online")
# Explanation
```
Implicit input, e.g 5
Θ Prepend a zero to get [0,5]
m Map the following over [0,5]
¡ Iteratatively apply the following function, collecting the return values in a list
d Convert to a list of digits
f± keep only the truthy ones
ȯΠ then take the product
S+ add that to the original number
After this map, we have [[0,1,2,4,8,16,22,26,38,62...],[5,10,11,12,14,18,26,38,62,74...]]
Ξ Merge the sorted lists: [0,1,2,4,5,8,10,11,12,14,16,18,22,26,26,38,38,62,62,74...]
U Take the longest unique prefix: [0,1,2,4,5,8,10,11,12,14,16,18,22,26]
→ Get the last element and implicitely output: 26
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~126~~ 125 bytes
```
m=[1]
n=[int(input())]
while not{*m}&{*n}:
for l in m,n:l+=l[-1]+eval('*'.join(str(l[-1]).replace(*'01'))),
print({*m}&{*n})
```
[Try it online!](https://tio.run/##Pc2xCsIwEIDhPU@RydyltRgKDoU8SchQJNLI9RJiVKT02SM6uP7D9@d3XRKPra3WGS/YusgVIudHBUQvXkukIDnVTa/7YdO8T0JeU5EkI8u154k6S@5ofBeeM4HSarilyHCvBX4dhxIyzZcAWp2MQsRe5PK9/Els7Tx@AA "Python 3 – Try It Online")
Take the input as string
[Answer]
# [Java (JDK 10)](http://jdk.java.net/), 99 bytes
```
n->{for(int x=1;x!=n;n+=(""+n).chars().reduce(1,(a,b)->a*(b>48?b-48:1)))x^=x<n?n^(n=x):0;return n;}
```
[Try it online!](https://tio.run/##jY/LTsMwEEX3@YqhK7ttLCIKKjVOxZIFYlGxQlRyXsUhmUT2pCSq8u3Ban8gq9HVnNGcW@qzDsvsdzJ121iC0mfRkalE0WFKpkGxlEFaaefgXRuESwDwhvSJ2g4fbW41NRYKUBOG8aVoLDNI0KtI9ncKJa4UWyxWyEX6o61jXNg869KcRWum1wkPY71kSbzZ7pNws91FnPP@qPoX3OORoer57l7anDqLgHKcpH/edkllUnCkyY9zYzKovRg7kDV4@voGbU@OXz3hplyDAsz/roFxeV0cBkd5LZqOROvvqEJWi0Lotq2GV@cLMu8yF32cj0bP89mnhxs7BuP0Dw "Java (JDK 10) – Try It Online")
Mostly an iterative port of [Arnauld's JavaScript answer](https://codegolf.stackexchange.com/a/163144/16236), so go upvote him!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 23 bytes
```
ð⁹1,Dḟ0P+Ʋ⁸С€f/©µ1#ṛ®Ḣ
```
[Try it online!](https://tio.run/##ATUAyv9qZWxsef//w7DigbkxLEThuJ8wUCvGsuKBuMOQwqHigqxmL8KpwrUxI@G5m8Ku4bii////NQ "Jelly – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 50 bytes
tacit style function definition
```
[:{.@(e.~#])/[:(+[:*/@(*#])(#~10)&#:)^:(<453)"0,&1
```
if the argument (say 63) were pasted into a REPL expression it could be 45 e.g.
```
{.(e.~#])/(+[:*/@(*#])(#~10)&#:)^:(<453)"0]1,63
```
* `,&1` append 1 to generate search sequence as well as argument's sequence
* `^:(<453)"0` iterates each until 1mio is reached in 1's sequence
* `+ [: */@(*#]) (#~10)&#:` fork adds to hook which does the product of digits
* `(e.~ # ])/` uses repeat item if exists to get intersection of lists
* `{.` return only the first common value
[Try it online!](https://tio.run/##hZBbTsMwEEX/s4oRlVq7j7ghUAkXpIoFsIGqlYIzSQ2NHfyAQqVuPdihleCLrxmPx@f63peue3pMoYDW6BYNVF4JJ7WCEiupZGyTCh44rPkxXRFMT4MNZWtOJms@ZisyDkcyOGVzOhxwuuXk/uY2p1fz6TBLkp5sat@gciAttIVxoCsoFOChNWhtxIcaBY7phf4fe5NNFzkkiW20d613QCAyllBBmNMf3Z1zreWMCV1irfdVal0hXvEgdoWqMRW6YW8ebTRoWbbIs/yOlbKWbhaSKL1wM4thQQm0Pc@ikUFEKmEw@rHw/Ann1ehJaTX7QqNDcEI2xR56mI1Xwem71P7M2ekPCH85JwEXlSQ0MQYyCVHDxT789X89p79dj@KbbLSEvgLtum8 "J – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~110~~ 86 bytes
```
o=c(1,1:9);o=o%o%o%o%o;o=c(o%o%o)
x=c(1,n);while((x=sort(x))<x[2])x[1]=(x+o[x+1])[1]
x
```
[TIO](https://tio.run/##K/qfZ2tm/D/fNlnDUMfQylLTOt82XxUKrUHCYJYmVwVYRZ6mdXlGZk6qhkaFbXF@UYlGhaamTUW0UaxmRbRhrK1GhXZ@dIW2YawmkMdV8f8/AA "R – Try It Online")
**previous version 110:**
```
f=function(x){if((x[1]=x[1]+(c((y=(y=c(1,1:9))%o%y%o%y)%o%y))[x[1]+1])==x[2]){x[1]}else{f(sort(x))}}
f(c(1,n))
```
[TIO](https://tio.run/##HU/basMwDH3fVxwoBYutD9lg0IH/om8lD8GRM8NiB8seTUO@PVUiJHF0OxzlLdrvLwAn3H4ZXR7qyLEgCKZOhHuEiE7QRQWFB86bt75GV0KK5kFL8MY87k1r9/RunDGzVXem@Wh@rkTndJ73OADR/VhrWrJ68NnSstcr/wkv3kjKRTlpXd@82Rki0XaCS@NUCwukjoLkMeXUV1cOHFO8PDkn9GEI2qoTSsL1MJUsodevkNnVLCoZF/xznnXC3gcX9NftBQ "R – Try It Online")
] |
[Question]
[
## Challenge
Given a quark composition of a particle as input, output the corresponding hadron's name.
Quarks will be represented by a capital letter and antiquarks by a lowercase letter.
The quarks may be in any order, not necessarily the order given below.
Built-in functions the access data about particles and/or quarks are disallowed.
The only quarks you will be given are U (up), u (antiup), D (down), d (antidown), S (strange), s (antistrange), C (charm), c (anticharm), B (bottom or beauty), b(antibottom or antibeauty).
## List of Hadrons and their quark compositions
Note that although there are various other hadrons such as pentaquarks and glueballs etc., you only need to support the hadrons given in the following lists
### Baryons (QQQ) and Antibaryons (qqq)
The names in brackets are alternative names for the particles. You may output either name.
```
Input - Output
UUU - delta++
uuu - antidelta++
UUD - delta+ (proton)
uud - antidelta+ (antiproton)
UDD - delta0 (neutron)
udd - antidelta0 (antineutron)
DDD - delta-
ddd - antidelta-
UUS - sigma+
uus - antisigma+
UDS - sigma0
uds - antisigma0
DDS - sigma-
dds - antisigma-
USS - xi0
uss - antixi0
DSS - xi-
dss - antixi-
SSS - omega-
sss - antiomega-
UUC - charmed sigma++
uuc - charmed antisigma++
UDC - charmed sigma+
udc - charmed antisigma+
DDC - charmed sigma0
ddc - charmed antisigma0
UUB - bottom sigma+
uub - bottom antisigma+
UDB - bottom sigma0
udb - bottom antisigma0
DDB - bottom sigma-
ddb - bottom antisigma-
USC - charmed xi+
usc - charmed antixi+
DSC - charmed xi0
dsc - charmed antixi0
UCC - double charmed xi++
ucc - double charmed antixi++
DCC - double charmed xi+
dcc - double charmed antixi+
USB - bottom xi0
usb - bottom antixi0
DSB - bottom xi-
dsb - bottom antixi-
UBB - double bottom xi0
ubb - double bottom antixi0
DBB - double bottom xi-
dbb - double bottom antixi-
UCB - charmed bottom xi+
ucb - charmed bottom antixi+
DCB - charmed bottom xi0
dcb - charmed bottom antixi0
SSC - charmed omega0
ssc - charmed antiomega0
SSB - bottom omega-
ssb - bottom antiomega-
SCC - double charmed omega+
scc - double charmed antiomega+
SCB - charmed bottom omega0
scb - charmed bottom antiomega0
SBB - double bottom omega-
sbb - double bottom antiomega-
CCB - double charmed bottom omega+
ccb - double charmed bottom antiomega+
CBB - charmed double bottom omega0
cbb - charmed double bottom antiomega0
CCC - triple charmed omega++
ccc - triple charmed antiomega++
BBB - triple bottom omega-
bbb - triple bottom antiomega-
```
### Mesons (Qq)
```
Input - Output
Ud - pion+
Uu - pion0
Dd - pion0
Du - pion-
Us - kaon+
Ds - kaon0
Sd - antikaon0
Su - kaon-
Ss - phion0
Cd - D meson+
Dc - D meson-
Cu - D meson0
Uc - antiD meson0
Cs - strange D meson+
Sc - strange D meson-
Cc - psion0
Bu - B meson-
Ub - B meson+
Db - B meson0
Bd - antiB meson0
Sb - strange B meson0
Bs - strange antiB meson0
Bb - upsilon0
```
## Winning
Shortest code in bytes wins.
[Answer]
## JavaScript (ES6), ~~456~~ ~~448~~ ~~431~~ 420 bytes
This code is using only two small lookup tables:
* one to identify the quarks: 'CUBDScubds'
* another one to detect the 'anti' prefix of Mesons: 'SdUcBdBs'
Everything else is deduced from the quarks.
```
(s,[a,b]=[...s].map(c=>(i='CUBDScubds'.search(c)%5,m|=1<<i,j+=i<2,k+=i&1,p+=i?i-2?'':'bottom ':'charmed ',i),m=j=k=0,p=''))=>s[2]?p.replace(/(\w+) \1( \1)?/,(_,a,b)=>b?'triple'+b:'double '+a)+(s>'Z'?'anti':'')+['omega','xi','sigma','delta'][k]+('-0+'[j]||'++'):(m&16&&m&5?'strange ':'')+(~'SdUcBdBs'.search(s)?'anti':'')+(m&1?m^1?'D mes':'psi':m&4?m^4?'B mes':'upsil':m&16?m^16?'ka':'phi':'pi')+'on'+'-0+'[(a<2)-(b<2)+1]
```
```
let f =
(s,[a,b]=[...s].map(c=>(i='CUBDScubds'.search(c)%5,m|=1<<i,j+=i<2,k+=i&1,p+=i?i-2?'':'bottom ':'charmed ',i),m=j=k=0,p=''))=>s[2]?p.replace(/(\w+) \1( \1)?/,(_,a,b)=>b?'triple'+b:'double '+a)+(s>'Z'?'anti':'')+['omega','xi','sigma','delta'][k]+('-0+'[j]||'++'):(m&16&&m&5?'strange ':'')+(~'SdUcBdBs'.search(s)?'anti':'')+(m&1?m^1?'D mes':'psi':m&4?m^4?'B mes':'upsil':m&16?m^16?'ka':'phi':'pi')+'on'+'-0+'[(a<2)-(b<2)+1]
res = [
"UUU", "uuu", "UUD", "uud", "UDD", "udd", "DDD", "ddd", "UUS", "uus", "UDS", "uds", "DDS", "dds", "USS", "uss",
"DSS", "dss", "SSS", "sss", "UUC", "uuc", "UDC", "udc", "DDC", "ddc", "UUB", "uub", "UDB", "udb", "DDB", "ddb",
"USC", "usc", "DSC", "dsc", "UCC", "ucc", "DCC", "dcc", "USB", "usb", "DSB", "dsb", "UBB", "ubb", "DBB", "dbb",
"UCB", "ucb", "DCB", "dcb", "SSC", "ssc", "SSB", "ssb", "SCC", "scc", "SCB", "scb", "SBB", "sbb", "CCB", "ccb",
"CBB", "cbb", "CCC", "ccc", "BBB", "bbb", "Ud", "Uu", "Dd", "Du", "Us", "Ds", "Sd", "Su", "Ss", "Cd",
"Dc", "Cu", "Uc", "Cs", "Sc", "Cc", "Bu", "Ub", "Db", "Bd", "Sb", "Bs", "Bb"
]
.map(s => s + ' - ' + f(s)).join("\n");
console.log(res);
```
[Answer]
# [SOGL 0.11](https://github.com/dzaima/SOGL), ~~341~~ ~~339~~ ~~333~~ ~~310~~ ~~305~~ ~~305~~ 300 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
‘θw±
on”≥
0c{≤
”=?"▒
on0”←"█
c SW?"▲
?ļ0←j ►
?"anti”o}▼
SD”;W¡+}□
=?ļ-←ļ+←■
‘B≤a=+}:?"⁽¬Τk⅜K±l?@+}ob@+o}▓
UCl2-? CA"K¼⁶▓ BA"δ╬▓cd≠▼≤: U=; D=++}"8}↕x╔:⁵F┘¹±o≤"B□"κ§)Ƨ7%s±p←"Ss▒phi█Cc▒psi█Bb▒upsil█SdUcBd”2n{=▼}≤"U□1>?▲ka≥pc DW►S■"pi≥Pcρ►D■▲)»β⁴‘o}ƧBs=▼ Dc BW?X B}" mes≥+p"D═S┐╔¬ν↑FνF⌠V3╗βstA\≈²‘:cW2+Wp
```
[Answer]
# Perl 5, 318 bytes
```
$_=<>;$h=qw/- ++ + 0/[y/uc//*2*($i=3-map{${lc;}++}/./g)-$u-$c-$i];$a=($i?!$h&&/[dUB]/:/[a-z]/)&&anti;map{/(.)/;$q.=("","$_ ","double $_ ","triple $_ ")[$$1]}charmed,bottom;print(($i?($u+$d>1?pi:$s>1?phi:$c>1?psi:$b>1?upsil:$c+$b?($s?"strange $a":$a).($b?B:D).' mes':$a.ka).on:$q.$a.qw/omega xi sigma delta/[$u+$d]).$h)
```
Newlines added for readability (slightly):
```
$_=<>
$h=qw/- ++ + 0/[y/uc//*2*($i=3-map{${lc;}++}/./g)-$u-$c-$i]
$a=($i?!$h&&/[dUB]/:/[a-z]/)&&anti
map{/(.)/;$q.=("","$_ ","double $_ ","triple $_ ")[$$1]}charmed,bottom;
print(($i?($u+$d>1?pi:$s>1?phi:$c>1?psi:$b>1?upsil:$c+$b?($s?"strange $a":$a).($b?B:D).' mes':$a.ka).on:$q.$a.qw/omega xi sigma delta/[$u+$d]).$h)
```
] |
[Question]
[
## Challenge:
Given an NxN matrix where \$N\geq2\$ and one of eight distinct 'folding options', output a 2D array/list with the subtracted values.
The eight folding options are: left-to-right; right-to-left; top-to-bottom; bottom-to-top; topleft-to-bottomright; topright-to-bottomleft; bottomleft-to-topright; bottomright-to-topleft.
**Step by step examples:**
Input matrix:
```
[[ 1, 3, 5, 7],
[ 0, 8, 6, 4],
[ 1, 1, 1, 1], (a'th row in the explanation below)
[ 1,25, 0,75]]
```
With folding option top-to-bottom we output the following as result:
```
[[ 1,-7,-5,-3],
[ 0,22,-5,68]]
```
Why? We fold from the top to the bottom. Since the matrix dimensions are even, we don't have a middle layer to preserve as is. The \$a\$'th row `[1, 1, 1, 1]` will be subtracted by the \$(a-1)\$'th row (would have been \$(a-2)\$'th row for odd dimension matrices); so `[1-0, 1-8, 1-6, 1-4]` becomes `[1, -7, -5, -3]`. The \$(a+1)\$'th row `[1, 25, 0, 75]` will then be subtracted by the \$(a-2)\$'th row (would have been \$(a-3)\$'th row for odd dimension matrices); so `[1-1, 25-3, 0-5, 75-7]` becomes `[0, 22, -5, 68]`.
With folding option bottomright-to-topleft instead (with the same input-matrix above) we output the following as result:
```
[[-74, 2, 1, 7],
[ 0, 7, 6],
[-24, 1],
[ 1]]
```
With the following folding subtractions:
```
[[1-75, 3-1, 5-4, 7],
[ 0-0, 8-1, 6],
[1-25, 1],
[ 1]]
```
## Challenge rules:
* You can use any eight distinct letters `[A-Za-z]` or distinct numbers in the range \$[-99,99]\$ for the folding options. Numbers \$[1..8]\$ or \$[0..7]\$ are probably the most common options, but if you want to use different numbers within the range for some smart calculations, feel free to do so. **Please state which folding options you've used in your answer.**
* The input-matrix will always be a square NxN matrix, so you don't have to handle any rectangular NxM matrices. \$N\$ will also always be at least 2, since an empty or 1x1 matrix cannot be folded.
* The input of the matrix will always contain non-negative numbers in the range \$[0, 999]\$ (the numbers in the output will therefore be in the range \$[-999, 999]\$).
* With the (anti-)diagonal folding or odd-dimension vertical/horizontal folding, the middle 'layer' will remain unchanged.
* I/O is flexible. Can be a 2D array/list of integers; can be returned or printed as a space-and-newline delimited string; you can modify the input-matrix and replace the numbers that should be gone with `null` or a number outside of the `[-999, 999]` range to indicate they're gone; etc. 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-matrix 1:
```
Input-matrix (for the following eight test cases):
[[ 1, 3, 5, 7],
[ 0, 8, 6, 4],
[ 1, 1, 1, 1],
[ 1,25, 0,75]]
Input-folding option: left-to-right
Output: [[2,6],[-2,4],[0,0],[-25,74]]
Input-folding option: right-to-left
Output: [[-6,-2],[-4,2],[0,0],[-74,25]]
Input-folding option: top-to-bottom
Output: [[1,-7,-5,-3],[0,22,-5,68]]
Input-folding option: bottom-to-top
Output: [[0,-22,5,-68],[-1,7,5,3]]
Input-folding option: topleft-to-bottomright
Output: [[7],[6,-1],[1,-7,-2],[1,24,0,74]]
Input-folding option: topright-to-bottomleft
Output: [[1],[-3,8],[-4,-5,1],[-6,21,-1,75]]
Input-folding option: bottomleft-to-topright
Output: [[1,3,4,6],[8,5,-21],[1,1],[75]]
Input-folding option: bottomright-to-topleft
Output: [[-74,2,1,7],[0,7,6],[-24,1],[1]]
```
Input-matrix 2:
```
Input-matrix (for the following eight test cases):
[[17, 4, 3],
[ 8, 1,11],
[11, 9, 7]]
Input-folding option: left-to-right
Output: [[4,-14],[1,3],[9,-4]]
Input-folding option: right-to-left
Output: [[14,4],[-3,1],[4,9]]
Input-folding option: top-to-bottom
Output: [[8,1,11],[-6,5,4]]
Input-folding option: bottom-to-top
Output: [[6,-5,-4],[8,1,11]]
Input-folding option: topleft-to-bottomright
Output: [[3],[1,7],[11,1,-10]]
Input-folding option: topright-to-bottomleft
Output: [[17],[4,1],[8,-2,7]]
Input-folding option: bottomleft-to-topright
Output: [[17,-4,-8],[1,2],[7]]
Input-folding option: bottomright-to-topleft
Output: [[10,-7,3],[-1,1],[11]]
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~256~~ ~~248~~ ~~244~~ 248 bytes
```
m=d=x=@(a,b=1)rot90(a,b)
y=@(a,b=2)flip(a,b)
z=@(a,b=1)tril(a+1e3,-1)+a-x(y(tril(a)))+b*diag(diag(a))
f=@(a,b){m=((a-y(a))(:,1:(d=size(a,2)/2))),-y(m),m=y(x((a=x(a))-y(a)))(d+1:end,:),y(m,1),-y(z(a,-1)),x(z(x(a,2)),2),z(a=x(a,3)),x(z(x(a,2)),2)}{b}
```
[Try it online!](https://tio.run/##nY5Ba4QwEIXv@RW5CJk6oUbXdasEimdP4q30EKsWYe2WrZTosr/djuvSS08NJJnHe@9LcnobzXe7LINutNXPwmCtFZxP41OwamDT3QyhO/afmzf/FsdzfxTGV22EUoFvpBWT2EwA8OuHpjfv4naQwboNhMughTByWk2RokpFo7/6uaUwhMeQUKRwABz0JCxVtV2rGwCi8VXafjSYAlIL1a09E0x/ALQk7e0moI3zRmP0J7pe6uvSiReFPEIeI0@yAPkB@R75LiP3vlYZUhxgEmev9Bz7PxS6QJELtHOBYhdo7wIlLtABmFfKgnmFLJmXy4p5lcxJlbIityplTiMvZEXx8gM "Octave – Try It Online")
*-2 bytes (and a bity of tidying up) thanks to [Luis Mendo](https://codegolf.stackexchange.com/users/36398/luis-mendo)*
*+2 bytes due to the correction for T-B*
1-Indexed operations for values of b from 1-8:
```
R-L
L-R
B-T
T-B
BR-TL
TR-BL
BL-TR
TL-BR
```
This gave me a headache, I'll golf it properly later
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~39~~ 34 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
*There is possibly further golfing possible by combining some of the two "functions".*
...yep: **-5** thanks to NickKennedy!
```
ṃ“Z“Ṛ“U“ “ŒDṙL ZZṚ”ŒḄFḲj“ŒH_Ṛ}¥/”v
```
**[Try it online!](https://tio.run/##y0rNyan8///hzuZHDXOigPjhzllAMhSID209Oskj/uHOVUAhFZWHu/oObYWKujzcsSjcOh4kfmzTw52NXkcnPdzRA5KeC2K1uJX9///f0OB/dLSCoY6CsY6CqY6CeawOl0K0goGOgoWOgpmOggmED5SHIhjfCKjYQMfcNDYWAA "Jelly – Try It Online")**
A dyadic link accepting an integer (the instruction) and a list of lists of numbers (the matrix).
Uses the option to take the instruction as an integer in \$[-99,99]\$ to our advantage, and hence has the following seemingly bizarre mapping:
```
Instruction | integer
------------------------+---------
left-to-right | 4
right-to-left | 14
top-to-bottom | 9
bottom-to-top | 39
topleft-to-bottomright | 65
topright-to-bottomleft | 15
bottomleft-to-topright | 10
bottomright-to-topleft | 0
```
### How?
The link creates Jelly code which is then evaluated using M as an input...
```
ṃ“Z“Ṛ“U“ “ŒDṙL ZZṚ”ŒḄFḲj“ŒH_Ṛ}¥/”v - Link: integer, I; matrix, M
“Z“Ṛ“U“ “ŒDṙL ZZṚ” - list of lists of characters = ["Z", "Ṛ", "U", " ", "ŒDṙL ZZṚ"]
ṃ - base decompress (I) using those lists as the digits
- ...i.e. convert to base 5 and then convert the digits:
- [1,2,3,4,0] -> ["Z", "Ṛ", "U", " ", "ŒDṙL ZZṚ"]
ŒḄ - bounce
- ...e.g. [a, b, c] -> [a, b, c, b, a]
F - flatten to a list of characters
Ḳ - split at spaces
j - join with:
“ŒH_Ṛ}¥/” - list of characters = "ŒH_Ṛ}¥/"
v - evaluate as Jelly code with an input of M
```
Each of the eight options are then:
```
left-to-right (4): ŒH_Ṛ}¥/
right-to-left (14): ṚŒH_Ṛ}¥/Ṛ
top-to-bottom (9): ZŒH_Ṛ}¥/Z
bottom-to-top (39): ZṚŒH_Ṛ}¥/ṚZ
topleft-to-bottomright (65): ṚUŒDṙLŒH_Ṛ}¥/ZZṚUṚ
topright-to-bottomleft (15): UŒDṙLŒH_Ṛ}¥/ZZṚU
bottomleft-to-topright (10): ṚŒDṙLŒH_Ṛ}¥/ZZṚṚ
bottomright-to-topleft (0): ŒDṙLŒH_Ṛ}¥/ZZṚ
```
These each (except `0` and `4`) apply a transform to `M` using some of `Z` (transpose), `Ṛ` (reverse), and `U` (reverse each); then one of two functions (see below), then the inverse of the setup transformation (if there was one) implemented with the reverse of the code.
The two inner functions are:
```
ŒH_Ṛ}¥/ - Function A: Fold bottom-to-top: matrix, M
ŒH - split M into two equal lists of rows (first half bigger by 1 if need be)
/ - reduce by:
¥ - last two links as a dyad:
} - using the right argument (i.e. second half):
Ṛ - reverse
_ - subtract
ŒDṙLŒH_Ṛ}¥/ZZṚ - Function B: Fold topright-to-bottomleft: matrix, M
ŒD - diagonals of M
ṙ - rotate left by:
L - length of M (puts them in order from bottom left most)
ŒH_Ṛ}¥/ - same action as calling Function A on the diagonals
Z - transpose
Z - transpose
Ṛ - reverse
```
[Answer]
# JavaScript (ES6), ~~149 ... 133~~ 128 bytes
Takes input as `(matrix)(d)` with \$0\le d\le7\$. Removed values are replaced with `NaN`.
Folding directions: \$0 =\;\rightarrow\$, \$1 =\;\downarrow\$, \$2 =\;\small\searrow\$, \$3 =\;\small\swarrow\$, \$4 =\;\leftarrow\$, \$5 =\;\uparrow\$, \$6 =\;\small\nwarrow\$, \$7 =\;\small\nearrow\$
```
m=>d=>m.map((r,y)=>r.map((v,x)=>v-=(w=m.length+~y)-(p=[x+x-y,y,x,q=w+y-x][d&3])&&[r[q],m[w][x],m[q][w],m[x][y]][d>3^p>w?d&3:m]))
```
[Try it online!](https://tio.run/##VU/LbsIwELznK3xAYCubiBBoaCunp34BR@OKCIeXsB2MlYdQ@@upHShSpZV2dzQ7O3Mq6uK6NcfKRkqLst/RXtJc0FzGsqgwNtARmpv7UkPrljqiuKEyPpdqbw/hT0ciXFHWhm3UQQctXGgTdlHLmRinnIzHzLALB8kazlrfL9yNrjtGxx0rT7@qvPlw7DfJCeltebWIIolojtgUUAJoBigFNAe0APQCKOPxTpvPYnvAwrEChLZaXfW5jM96jzcOQ6Ob@F6r0W2HJcGCDAGMV7xnqf1Yx1avrDmqPSZxVYiVLYzFc0Likz4qPJk8p7WaECe3IQF5DwJvEDP3lXlv6eAq4zAAzu9y8Dh/AAn81ROYOf4UsgUP@H@5JBtCpg/m0t8lj7vESbz6P/6o/wU "JavaScript (Node.js) – Try It Online")
### Commented
```
m => d => // m[] = matrix; d = direction
m.map((r, y) => // for each row r[] at position y in m[]:
r.map((v, x) => // for each value v at position x in r[]:
v -= // subtract from v:
( // define w as:
w = m.length + ~y // the width of input matrix - y - 1
) - ( // and compare it with
p = [ // p defined as:
x + x - y, // 2 * x - y for vertical folding
y, // y for horizontal folding
x, // x for diagonal folding
q = w + y - x // q = w + y - x for anti-diagonal folding
][d & 3] // using d MOD 4
) && // if p is equal to w, leave v unchanged
[ // otherwise, subtract:
r[q], // r[q] for vertical folding
m[w][x], // m[w][x] for horizontal folding
m[q][w], // m[q][w] for diagonal folding
m[x][y] // m[x][y] for anti-diagonal folding
][ // provided that we're located in the target area:
d > 3 ^ // test p < w if d > 3
p > w ? d & 3 // or p > w if d <= 3
: m // and yield either d MOD 4 or m[]
] // (when using m[], we subtract 'undefined' from v,
// which sets it to NaN instead)
) // end of inner map()
) // end of outer map()
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~71~~ 34 bytes
```
ḃ2ŒḄ,UZṚŒDṙLƊŒH_Ṛ}¥/$ZZṚƊṚZ8ƭ$ị@¥ƒ
```
[Try it online!](https://tio.run/##y0rNyan8///hjmajo5Me7mjRCY16uHPW0UkuD3fO9DnWdXSSRzyQX3toqb5KFEjmWBeQiLI4tlbl4e5uh0NLj036/9/EREfBxEBHwdgMiI10FExBbKCYKRAbW/w3NvsfHa1gCGQDhXQUzGN1uBSiFYBqLHQUgDpMIHygPBTB@EZAxQY65qaxsQA "Jelly – Try It Online")
[Test Suite](https://tio.run/##y0rNyan8///hjmajo5Me7mjRCY16uHPW0UkuD3fO9DnWdXSSRzyQX3toqb5KFEjmWBeQiLI4tlbl4e5uh0NLj036X2FxePmjpjUPdyziMjHRMTHQMTbTMTbSMQUyTHRMTXSMIfJA43fOANKRXHCW9aOGOYe21RzaVnZo26OGudaH27kOtwMlsh417ju07dC2//@jo6MVDHUUjHUUTHUUzGN1uBSiFQx0FCx0FMx0FEwgfKA8FMH4RkDFBjrmprFAgehoQ3OgUqAZEFkLkFJDiFJDoCZLkLmxsQA "Jelly – Try It Online")
A full program. Right argument is the matrix. Left argument is the type of fold:
```
44 = L-R
40 = R-L
36 = T-B
32 = B-T
50 = TL-BR
34 = TR-BR
54 = BL-TR
38 = BR-TL
```
Rewritten to use 5-bit bijective binary as input. Note the program given above won’t work repeatedly for multiple folds.
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~482 bytes~~, 459 Bytes
The inputs for deciding folding directions are:
1)left to right
2)bottom to top
3)right to left
4)top to bottom
5)tr to bl
6)br to tl
7)bl to tr
8)tl to br
Each call only generates the specified fold, rather than all of them (which would probably would take less bytes). Biggest problem is that for this case I can't figure out how to put folds 1-4 and 5-8 in the same loop. But at least octave has nice looking matrices.
```
function[m]=f(n,o)
k=length(n);m=NaN(k);if(o<5)
if(mod(o,2)>0)n=n'end
q=[0,0,k+1,k+1](o)
for x=1:ceil(k/2)if(x*2>k)m(x,:)=n(x,:)else
for a=1:k
m(abs(q-x),a)=n(abs(q-x),a)-n(abs(q-(k+1-x)),a)end
end
end
if(mod(o,2)>0)m=flipud(m')end
else
if(mod(o,2)>0)n=flip(n)end
q=[0,0,k+1,k+1](o-4)
for x=1:k
for a=1:k+1-x
if(a==k+1-x)m(x,a)=n(x,a)else
m(abs(q-x),abs(q-a))=n(abs(q-x),abs(q-a))-n(abs(q-(k+1-a)),abs(q-(k+1-x)))end
end
end
end
if(mod(o,2)>0)m=flip(m)end
end
```
[Try it online!](https://tio.run/##jY/fbsIgFIfv@xTcLMKGmdQ6nQ4fwRdoeoFatCl/tOLSt@84NI122RIuCHA4H7/z2YMT32XXybs5uMqaXBdcYkMtSWquSnNyZ2zIRvOd2OGabCqJ7deCJH7X9ogtTcl2Rgw3k9IckyvPZ3RG6zcGq8D@F2kb1HK2PpSVwvV7SjzZvqbbmmjc0jXhJmylupWhV/jeOtFY7G/4Om0JFdDydJsON@wjfAlqkD2s8WSaS1Vd7kesJ30X5PweHlq85Z8G0@zhUD8mhGj4R3DejwE2orcRvc2zQzgIMlYZimMjQYanQXCk958i1kNbJ3GesyVFGUXzYpOjFUWMMuaPjFH0SdGyKCgj6EWV0iFnUVOdzi6JwlKP7a1zVgPo7CUOm3sspAAFsXFY5jGfAVAfGoctAGsCpeKID9AKhIsklkCoQDRxxAqmCsS@6X4A "Octave – Try It Online")
Output suppression costs bytes, so ignore everything that isn't the return statement(ans = ).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~78~~ 77 bytes
```
F⁴«UMηE⮌η§μλ¿⁼ιθUMηEκ⎇‹⊕⊗νLη⁻μ§⮌κν⎇›⊕⊗νLηωμ¿⁼ι﹪θ⁴UMηEκ⎇‹λν⁻μ§§ηνλ⎇›λνωμ»Eη⪫ι,
```
[Try it online!](https://tio.run/##jY9BS8NAEIXPza8YepqFEVpNrOBJVKTSgIi3kMOaTE3oZtfsJlURf3vcpA1F7KHsYWb27bz3bVZImxmpum5tLGAo4DuYxPL91lSV1DkWBH7CZ96ydYyFILhpljrnT6wIlBDiOpiUa8D7upXKYUlQCwH/HTYEL2y1tF@4YudwqTPLFeuGc7wz7avyVQtvv2L91hQ@yfdxqVvXB42ZI8fGi8Pr0fPBsmzYnmb7QVCJHTorx/CXPzZ5qwzWBKE46SuqZzkCO9Zip6tjvPvdA9FP8GRL3WAf5BcfTal7qClNe7nrkhkFSTKnC4pokVIA/uKKLikc@jkNZ9@fRzSjRZSmaXe2Vb8 "Charcoal – Try It Online") Link is to verbose version of code. Uses the following folding options:
```
0 top-to-bottom
1 left-to-right
2 bottom-to-top
3 right-to-left
4 bottomright-to-topleft
5 topright-to-bottomleft
6 topleft-to-bottomright
7 bottomleft-to-topright
```
Folded values are replaced by empty strings. Explanation:
```
F⁴«≔UMηE⮌η§μλ
```
Rotate the array four times.
```
¿⁼ιθUMηEκ⎇‹⊕⊗νLη⁻μ§⮌κν⎇›⊕⊗νLηωμ
```
Fold the array horizontally when appropriate.
```
¿⁼ι﹪θ⁴UMηEκ⎇‹λν⁻μ§§ηνλ⎇›λνωμ
```
Fold the array diagonally when appropriate.
```
»Eη⪫ι,
```
Output the array once it is rotated back to its original orientation.
] |
[Question]
[
# Introduction
This challenge consists in finding the greatest number removing *y* digits from the original number *n* which has *x* digits.
Assuming `y=2 n=5263 x=4`, the possible numbers removing *y=2* digits are:
```
[52, 56, 53, 26, 23, 63]
```
So, the greatest number is `63` which must be the output for this example.
---
Another logic would be: *for each y, search from left to right the digit which right next digit is greater, then remove it, else when no match, remove the last y-digits*.
Using `y=3 n=76751432 x=8` to explain:
```
y=3
76751432
-^------ remove 6 because right next 7 is greater
y=2
7751432
---^--- remove 1 because right next 4 is greater
y=1
775432
-----^ the search failed, then remove last y digits
result = 77543
```
Both methods explained above works.. of course, you can use another method too :)
# Challenge
The number *n* won't have more than 8 digits, and *y* will always be greater than zero and lower than *x*.
To avoid strict input format, you can use the values: `y n x` the way you prefer: as parameters in function, raw input, or any other valid way. Just don't forget to say how you did that in your answer.
The output should be the result number.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest answer in bytes wins.
# Example Input and Output
### Again: you do not need to be too strict :)
```
4 1789823 7 -> 983
1 54132 5 -> 5432
3 69314 5 -> 94
2 51794 5 -> 794
```
# Edit
I changed the input order to reflect the fact that some of you may not need the *x* value to solve the problem. *x* is now an optional value.
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 10 bytes
```
-jowXncUX>
```
This uses [version (9.2.1)](https://github.com/lmendo/MATL/releases/tag/9.2.1) of the language/compiler, which is earlier than this challenge.
It takes three inputs from stdin in this order: string length, number of removed characters, string.
### Example
```
>> matl
> -jowXncUX>
>
> 7
> 4
> 1789823
983
```
*EDIT*: [**Try it online!**](http://matl.tryitonline.net/#code=LWp3WE5jVVg-&input=Nwo0CjE3ODk4MjM) (the code in the link has `XN` instead of `Xn` to conform to changes in the language after this challenge; also, `o` is not needed anymore)
### Explanation
(This still costs 2 bytes more than it should due to Octave's and Matlab's `nchoosek` function behaving differently. Fixed in the next release of the compiler.)
```
- % implicitly input two numbers, and subtract them
jo % input string, and convert to ASCII codes
wXn % swap inputs. Generate all combinations, each in a row
c % convert to char array
U % convert each row to a number
X> % get maximum. Implicitly display
```
---
## Answer to original challenge (stricter input requirements): 16 bytes
```
jYbZ)b-wowXncUX>
```
Uses [current version (9.2.1)](https://github.com/lmendo/MATL/releases/tag/9.2.1) of the language/compiler.
### Example
```
>> matl jYbZ)b-wowXncUX>
> 4 1789823 7
983
```
### Explanation
(This should have been 4 bytes less, but I need that `wow...c` because Octave's `nchoosek` function, unlike Matlab's, doesn't work with character input. Will be fixed for next release of the compiler.)
```
j % input string
YbZ) % split at spaces into strings
b- % subtract first and third (1-digit) strings
wow % convert middle string into ASCII codes
Xn % get all combinations, each in a row
c % convert to char array
U % convert each row to a number
X> % get maximum. Implicitly display
```
[Answer]
## [A-Ray](https://github.com/mannymang/A-Ray), ~~9~~ 7 bytes
My new language! According to meta, this is allowed, but if this is not accepted, then I will remove it.
```
pM:i-II
```
Explanation:
```
:i-II Gets all permutations possible for the given number converted to an array,
with the length of y-x, which is the -II part
M Gets the maximum of the result above
p Prints the resulting array above, with no separators
```
Example input (number, x, y):
```
1736413 7 4
```
Output:
```
764
```
You can test this with the .jar file given in the github link.
[Answer]
# Pyth - ~~11~~ ~~9~~ 8 bytes
```
eS.cz-QE
```
[Test Suite](http://pyth.herokuapp.com/?code=eS.cz-QE&test_suite=1&test_suite_input=5263%0A4%0A2%0A1789823%0A7%0A4%0A54132%0A5%0A1%0A69314%0A5%0A3&debug=0&input_size=3).
[Answer]
# Japt, 19 bytes
```
Vs ¬àW-U m¬mn n!- g
```
[Try it online!](http://ethproductions.github.io/japt?v=master&code=VnMgrOBXLVUgbaxtbiBuIS0gZw==&input=MiA1MjYzIDQ=)
### How it works
```
// Implicit: U = y, V = n, W = x
Vs ¬ // Convert V into a string, then split into an array of chars.
àW-U // Generate all combinations of length W-U.
m¬mn // Join each pair back into a string, then convert each string to a number.
n!- // Sort by backwards subtraction (b-a instead of a-b; highest move to the front).
g // Get the first item in this list.
// Implicit: output last expression
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 30 bytes
```
,{,[N:Y].hs?lL,Nl-Y=L}?:1forh.
```
Since OP has relaxed the constraints on IO, this expects `[Number, NumberOfDigitsRemoved]` as input and returns the answer as output, e.g. `brachylog_main([1789823,4], Z).`.
### Explanation
```
,{ }?:1f § Declare sub-predicate 1 and find all inputs which satisfy
§ this sub-predicate with output = Input of the main predicate
§ (i.e. [Number, Number of digits to remove])
§ -- Sub-predicate 1 --
,[N:Y]. § Output = [N, Y]
hs? § Input = a subset of N
lL,Nl-Y=L § Length of Input = Length of N - Y
orh. § Order the list of answers, reverse it an return the first
§ element (i.e. the biggest number of the list)
```
[Answer]
## Python 3, 69 bytes
This defines an anonymous function accepting all three arguments. Taking full advantage of the rule that "you can use the values: `y n x` the way you prefer", I have chosen to accept `y` and `x` as integers and `n` as a string. The return value is a string.
```
from itertools import*
lambda y,n,x:''.join(max(combinations(n,x-y)))
```
Just in case anyone feels that this is stretching the rules too far, this version takes all inputs as integers and is 74 bytes.
```
from itertools import*
lambda y,n,x:''.join(max(combinations(str(n),x-y)))
```
And just for kicks, I also wrote a two-argument version, taking `y` and `n` from the command line and printing the result to `STDOUT`. It's 92 bytes.
```
import sys,itertools as i
_,y,n=sys.argv
print(*max(i.combinations(n,len(n)-int(y))),sep='')
```
[Answer]
## ES6, 70 bytes
```
r=(y,n)=>y?r(y-1,Math.max(...`${n}`.replace(/./g," $`$'").split` `)):n
```
Returns a numeric result unless `y` is falsy and `n` is a string. I've convinced myself that doing the recursion the wrong way around still works (my solution isn't applicable to doing the correct recursion).
Also my first code golf where I use all three quote signs (although not all as quotes), which prevented me from trivially calculating the length.
[Answer]
# Julia, ~~128~~ 95 bytes
```
f(y,n,x)=maximum(i->parse(join(i)),filter(k->endof(k)==x-y,reduce(vcat,partitions(["$n"...]))))
```
This is a function that accepts the three values as parameters and returns an integer.
Ungolfed:
```
function f{T<:Integer}(y::T, n::T, x::T)
# Get all ordered partitions of the digits of n
p = reduce(vcat, partitions(["$n"...]))
# Filter to groups of size x-y
g = filter(k -> endof(k) == x - y, p)
# Get the maximum resulting number
return maximum(i -> parse(join(i)), g)
end
```
[Answer]
## Haskell, 64 bytes
```
import Data.List
y#x=maximum.filter((==x-y).length).subsequences
```
Usage example: `(4#7)"1789823"` -> `"983"`.
The original number `n` is takes as a string. (Not sure if I'm overstressing the "no strict input format" rule, but string input was required(!) in the first version).
How it works: make a list of all subsequences of `n`, keep those with length `x-y` and pick the maximum.
[Answer]
# Ruby, 40 bytes
```
->y,n,x{n.chars.combination(x-y).max*''}
```
This is an anonymous function that takes `y` and `x` as integers and `n` as a string, and returns a string. You may call it for instance like this
```
->y,n,x{n.chars.combination(x-y).max*''}[2,"5263",4]
```
and it will return `"63"`.
[Answer]
# MATLAB 40 bytes
```
@(n,y)max(str2num(nchoosek(n,nnz(n)-y)))
```
Test:
```
ans('76751432',3)
ans = 77543
```
[Answer]
# Pyth, 45 bytes
```
=cz)Fk.P@z1-l@z1v@z0I:@z1j".*"k1I>vkZ=Zvk)))Z
```
[try it here](http://pyth.herokuapp.com/?code=%3Dcz%29Fk.P%40z1-l%40z1v%40z0I%3A%40z1j%22.%2a%22k1I%3EvkZ%3DZvk%29%29%29Z&input=3+69314+5%0A&debug=0)
[Answer]
# JavaScript (ES6), 78
A recursive function with 2 arguments y and d. `y` can be numeric or string, `d` must be a string.
```
r=(y,d)=>y?Math.max(...[...d].map((x,i)=>r(y-1,d.slice(0,i)+d.slice(i+1)))):+d
```
Before the challenge changed it was 107 - ... with all input/output oddities ...
```
x=>(r=(n,d)=>n?Math.max(...[...d].map((x,i)=> r(n-1,d.slice(0,i)+d.slice(i+1)))):+d)(...x.match(/\d+/g))+'\n'
```
**Test**
```
r=(y,d)=>y?Math.max(...[...d].map((x,i)=>r(y-1,d.slice(0,i)+d.slice(i+1)))):+d
function test() {
[a,b]=I.value.match(/\d+/g)
O.textContent=r(a,b)
}
test()
```
```
y,n: <input id=I value='4 1789823' oninput="test()">
<pre id=O></pre>
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
àVnW)ñ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=4FZuVynx&input=IjUyNjMiCjIKNA)
```
àVnW)ñ :Implicit input of string U=n and integers V=y & W=x
à :Combinations of U of length
VnW : V subtracted from W
) :End combinations
ñ :Sort
:Implicit output of last element
```
] |
[Question]
[
*This is one of several challenges left for the community by [Calvin's Hobbies](https://codegolf.stackexchange.com/users/26997/calvins-hobbies).*
Take a "family tree describing" file with lines of the form:
```
[ID] [mother ID] [father ID] [gender] [full name]
```
such as this which describes the first family tree at <http://en.wikipedia.org/wiki/Cousin>:
```
1 ? ? M Adam
2 ? ? F Agatha
3 ? ? M Bill
4 2 1 F Betty
5 2 1 M Charles
6 ? ? F Corinda
7 3 4 M David
8 6 5 F Emma
```
Write a program or function that takes in the file name and two IDs and outputs how those people are blood-related in simplest terms, using the common English names for relations. Input may be via STDIN, ARGV or function arguments but output should be to STDOUT.
## Notes
* IDs are positive integers.
* `?` is used when parentage is not known.
* Assume the graph will be connected and has no cycles.
* You may *not* assume that each person's parents are listed before that person (so a person's parent ID could be greater than their own ID).
* Assume everyone is either male or female and everyone has exactly one mother and exactly one father (of correct gender), although they might be unknown.
* Assume names are unique.
* Names can have spaces in them.
## Blood relations
The following definitions of relationships *R* determine if person *A* is the *R* or person *B*. If two variants of *R* are listed, the first is for female *A* and the second for male *A*. All of these need to be implemented. If multiple definitions match, the earlier one is to be used. Terms in parentheses are gender-neutral terms, which do not need to be implemented but will be reused in further definitions. In definitions involving *N* and *M*, assume *N > 1* and *M > 0*.
* daughter/son: *A* lists *B* as either parent.
* mother/father (parent): *B* lists *A* as either parent.
* sister/brother (sibling): *A* and *B* list the same mother *and* father.
* half-sister/half-brother (sibling): *A* and *B* list the same mother **or** the same father.
* niece/nephew: *A* lists a parent who is the sibling of *B*.
* aunt/uncle: *B* is *A*'s niece or nephew.
* granddaughter/grandson (grandchild): *A* lists a parent who lists *B* as their parent.
* grandmother/grandfather (grandparent): *B* is *A*'s grandchild.
* great-niece/great-nephew: *A* is the grandchild of *C* who is the sibling of *B*.
* great-aunt/great-uncle: *B* is *A*'s great-niece or great-nephew.
* great-granddaughter/son (1st great-grandchild): *A* is a grandchild of *C* who lists *B* as their parent.
* great-grandmother/father (1st great-grandparent): *B* is *A*'s 1st great-grandchild.
* Nth great-granddaughter/son (Nth great-grandchild): *A* is an (N-1)th grandchild of *C* who lists *B* as their parent.
* Nth great-grandmother/father (Nth great-grandparent): *B* is *A*'s Nth great-grandchild.
* Nth great-niece/nephew: *A* is the (N-1)th great-grandchild of *C* who is the sibling of *B*.
* Nth great-aunt/uncle: *B* is *A*'s Nth great-niece of Nth great-nephew.
* cousin: *A* is the grandchild of *C* who is the grandparent of *B*.
* Nth cousin: *A* is the (N-1)th grandchild of *C* who is the (N-1)th grandparent of *B*.
* cousin, M times removed: *A* is the grandchild of *C* who is the Mth grandparent of *B* **or** *A* is the Mth grandchild of *C* who is the grandparent of *B* .
* Nth cousin, M times removed: *A* is the Pth great-grandchild of *C* who is the Qth great-grandparent of *B*, where `N = min(P,Q) + 1` and `M = |P-Q|`.
For `Nth`, write `2nd`, `3rd`, `4th`, `5th` etc.
For `M times`, write `once`, `twice`, `thrice`, `4 times`, `5 times` etc.
## Examples
Assume the following file is used (you don't have to be able to deal with multiple spaces, but I added them for legibility):
```
1 ? ? F Agatha
2 ? ? M Adam
3 ? ? F Betty
4 1 2 M Bertrand
5 1 2 F Charlotte
6 ? ? M Carl
7 ? ? F Daisy
8 3 4 M David
9 5 6 F Emma
10 ? ? M Edward
11 ? ? F Freya
12 7 8 M Fred
13 9 10 F Grace
14 ? ? M Gerald
15 ? ? F Hillary
16 11 12 M Herbert
17 13 14 F Jane
18 ? ? M James
19 15 16 F Kate
20 17 18 M Larry
21 ? 18 F Mary
```
Then input IDs should map to outputs as follows:
```
1 2 --> Agatha is not a blood relative to Adam.
8 3 --> David is the son of Betty.
9 13 --> Emma is the mother of Grace.
4 5 --> Bertrand is the brother of Charlotte.
9 4 --> Emma is the niece of Bertrand.
5 8 --> Charlotte is the aunt of David.
16 7 --> Herbert is the grandson of Daisy.
1 9 --> Agatha is the grandmother Emma.
12 5 --> Fred is the great-nephew of Charlotte.
4 13 --> Bertrand is the great-uncle of Grace.
16 3 --> Herbert is the great-grandson of Betty.
6 17 --> Carl is the great-grandfather of Jane.
19 2 --> Kate is the 3rd great-granddaughter of Adam.
1 17 --> Agatha is the 2nd great-grandmother of Jane.
20 4 --> Larry is the 3rd great-nephew of Bertrand.
5 16 --> Charlotte is the 2nd great-aunt of Herbert.
8 9 --> David is the cousin of Emma.
19 20 --> Kate is the 4th cousin of Larry.
16 9 --> Herbert is the cousin, twice removed, of Emma.
12 17 --> Fred is the 2nd cousin, once removed, of Jane.
21 20 --> Mary is the half-sister of Larry.
```
I wrote those up by hand so let me know if you spot any mistakes.
*Another set of test data (provided by Scott Leadley, any errors are mine and not Martin's)*
Ptolemy family tree

The picture is illustrative; the data below comes from the Wikipedia article "[Ptolemaic dynasty](http://en.wikipedia.org/wiki/Ptolemaic_dynasty#Ptolemaic_family_tree)".
```
1 ? ? F Berenice I of Egypt
2 ? ? M Ptolemy I Soter
41 1 2 F Arsinoe II of Egypt
3 1 2 M Ptolemy II Philadelphus
4 ? ? F Arsinoe I of Egypt
5 ? ? M Philip
6 4 3 M Ptolemy III Euergetes
7 1 5 F Magas of Cyrene
8 7 ? F Berenice II
9 8 6 M Ptolemy IV Philopator
10 8 6 F Arsinoe III of Egypt
11 10 9 M Ptolemy V Epiphanes
12 ? ? F Cleopatra I of Egypt
13 12 11 M Ptolemy VI Philometor
14 12 11 F Cleopatra II
15 12 11 M Ptolemy VIII Physcon
19 ? ? F Eirene
16 14 13 M Ptolemy VII Neos Philopator
17 14 13 F Cleopatra III
18 14 15 M Ptolemy Memphites
20 19 15 M Ptolemy Apion
21 17 15 F Cleopatra IV
22 17 15 M Ptolemy IX Lathyros
23 17 15 F Cleopatra Selene I
24 17 15 M Ptolemy X Alexander I
25 23 22 F Berenice III of Egypt
26 23 24 M Ptolemy XI Alexander II
27 21 22 M Ptolemy XII Auletes
28 25 24 F Cleopatra V of Egypt
29 28 27 F Cleopatra VI of Egypt
30 28 27 F Berenice IV of Egypt
31 28 27 M Ptolemy XIII Theos Philopator
32 28 27 F Cleopatra VII Thea Philopator
33 28 27 M Ptolemy XIV
34 28 27 F Arsinoe IV of Egypt
35 ? ? M Julius Caesar
37 32 35 M Ptolemy XV Caesarion
36 ? ? M Mark Anthony
38 32 36 M Alexander Helios
39 32 36 M Ptolemy XVI Philadelphus
40 32 36 F Cleopatra Selene II
```
[Answer]
# Cobra - 932
Out of all the challenges I've answered in Cobra, this is by far one of the best examples of what it can do.
EDIT: It's now a function, but must be prefixed by the signature for Z (included in char count).
```
sig Z(m,n=nil,r=nil)as String?
def f(f='',u='',v='')
d={:}
for l in File.readAllLines(f)
w=l.trim.split
i,j,k,p=w[:4]
q=w[4:].join(' ')
if i==u,x,g=q,if(p<'M',1,0)
if i==v,y=q
d.add(i,[j,k])
o as Z=do(n,m,r)=if(n>1,"[n][if(0<n%10<4and not 10<n%100<14,'stndrd'[n%10-1:n%10+2],'th')] ",'')
z as Z=do(m,n,r)
h,a,b=n
if m[0]==m[1]
if if(b<1or 0<b<3and a>b,s=2,s=0),a,b=b,a
r="the [if(a,if(a<2,if(b<2,if(not'?'in'[c=d[u]][e=d[v]]'and c==e,'','half-')+['brother','sister'][g],if(b<3,'',o(b-2)+'great-')+['uncle','aunt','nephew','neice'][s+g]),o(a-1)+'cousin'+if(b>a,', '+if((b-=a)<4,['on','twi','thri'][b-1]+'ce','[b] times')+' removed,','')),if(b,if(b<3,'',o(b-2)+'great-')+'grand','')+['father','mother','son','daughter'][s+g])] of"
for t in d[m[h]],if'?'<>h,r?=if(h,z([m[0],t],[1,a,b+1]),z(m,[1,a,0])?z([t,v],[0,a+1,0]))
return r to String?
print x+" is [z([u,v],[0,0,0])?'not a blood relative to'] [y]."
```
Commented: (out of date, but still the same code-flow)
```
class F
# Initilaise link dict
var d={'?':@[''][:0]}
# Gender bool
var g
def main
# Initilaise name dict
d={'?':@[''][:0]}
# Take args
f,a,b=CobraCore.commandLineArgs[1:]
# For line in file
for l in File.readAllLines(f)
# Split line
i=l.split
# Add links to link dict
.d.add(i[0],i[1:3])
# Add names to name dict
d.add(i[0],i[3:])
# Get gender
.g=if(d[a][0]=='F',1,0)
# Print result
print _
'[d[a][1]] is '+ _ # Name A
.r(@[1,0,0],@[a,a,b,b]) _ # If link found, link
? _ # Else
'not a blood relative'+ _ # Not related
' of [d[b][1]].' # Name B
def r(n as int[],m as String[])as String?
# Recurse through the links at each level from A (A1), climbing when no links are found to B
# For each level incremented for A, search upwards to the end of all nodes from B (B1), looking for A1
r=nil
# Check if we're done searching/climbing
if m[1]==m[2]
a,b=n[1:]
s=if(b<1or b in[1,2]and a>b,1,0)
if s,a,b=b,a
# Take the A and B distance and translate them into a phrase
return'the '+ _
if(a, _
if(a<2, _
if(b<2, _
if('?'not in'[.d[m[0]]][.d[m[3]]]'and.d[m[0]]==.d[m[3]], _
'', _
'half-' _
)+['brother','sister'][.g], _
if(b<3, _
'', _
.o(b-2)+'great-' _
)+[['uncle','aunt'],['nephew','neice']][s][.g] _
), _
.o(a-1)+'cousin'+if(b>a, _
', '+if((b-=a)<4, _
['once','twice','thrice'][b-1], _
'[b] times' _
)+' removed,', _
'' _
) _
), _
if(b, _
if(b<3, _
'', _
'[.o(b-2)]great-' _
)+'grand', _
'' _
)+[['father','mother'],['son','daughter']][s][.g] _
)
# Check if we're climbing
if n[0]
# For each link in the current A-level
for x in.d[m[1]]
r?= _
.r(@[0,n[1],0],m) _ # Start a search
? _ # If the search failed
.r(@[1,n[1]+1,0],@[m[0],x,m[3],m[3]]) # Climb again
# Check if we're searching
else
# For each link in the current B-level
for x in.d[m[2]]
# Search up one level from the current B-level
r?=.r(@[0,n[1],n[2]+1],@[m[0],m[1],x,m[3]])
return r
def o(n as int)as String
# Get ordinal string for the number
return if(n>1,'[n][if(0<n%10<4and not 10<n%100<14,['st','nd','rd'][n%10-1],'th')] ','')
```
[Answer]
# ECMAScript 6, 886
Division by zero is a wonderful thing.
This uses quasi-literals once (which are not implemented in Firefox 33 or node.js, but *are* available in the nightly builds of Firefox). The quasi literal used:
```
`
`
```
may be replaced with `"\n"` if whatever you are using lacks support for these.
This script constructs a tree from the list of people, storing both parents and children. Every path from person A to person B is tried, and the optimal path is saved. A path is considered valid if it only changes from going up to going down the tree once. The opposite change is not allowed - if one needs to go down to a children and back up to another parent in order to find a path, the two people are not blood relatives. (`UUUUUDDD` is valid, `UUDUUU` is not. `U` means go up (to a parent), `D` means go down (to a child)).
Sort of golfed:
```
R=(a,b)=>{F="forEach",C='';p=[],g=[],c={},n=[],e=m=1/0;y=i=>i+(k=i%10,k&&k<4&&~~(i%100/10)-1?[,'st ','nd ','rd '][k]:'th ');q=(a,b,s,$)=>!($=$.slice())|!a|~$.indexOf(a)||a-b&&$.push(a)|[p,c][F]((M,N)=>M[a][F](j=>q(j,b,s+N,$)))||(z=(s.match(/0/g)||[]).length,r=s.length-z,_=e+m-z-r,s.indexOf(10)<0&_>0|!_&m>r&&(e=z,m=r));I.split(`
`)[F](V=>{P=V.split(' ');D=+P[0];p[D]=[+P[1],+P[2]];g[D]=P[3]<'L';n[D]=P.slice(4).join(' ');c[D]=[]});p[F]((V,I)=>V[F](Y=>Y&&c[Y].push(I)));q(a,b,C,[]);U=e>m?m:e,V=e>m?e:m;alert(n[a]+' is '+(e/m+1?'the '+(U*V---1?U<2?(V<3?C:y(V-1))+(V<2?C:'great-')+(V*!U?'grand':C)+'son0father0nephew0uncle0daughter0mother0niece0aunt'.split(0)[g[a]*4+2*U+(U==e)]:(V-=--U,(U<2?C:y(U))+'cousin'+(V?', '+(V>3?V+' times':[,'on','twi','thri'][V]+'ce')+' removed,':C)):(p[a].join()==p[b].join()?C:'half-')+(g[a]?'sister':'brother'))+' of ':'not a blood relative to ')+n[b]+'.')}
```
Ungolfed (kind of):
```
// function for running.
R=(a,b)=>{
F="forEach",C='';
p=[], g=[], c={}, n=[], e=m=1/0;
// returns suffixed number (1->1st, 2->2nd, etc)
y= i=>i+(k=i%10,k&&k<4&&~~(i%100/10)-1?[,'st ','nd ','rd '][k]:'th ');
// this looks for the shortest path up/down the family tree between a and b.
q=(a,b,s,$)=>
// copy the array of visited people
!($=$.slice())
// check if a is invalid
| !a
// check to make sure we are not visiting a for a second time
| ~$.indexOf(a)
// if a != b
|| a-b
// add a to visited, and call q(...) on all parents and children
&& $.push(a) |
[p,c][F]((M,N)=>M[a][F](j=>q(j,b,s+N,$)))
|| (
// a == b
// get number of ups and downs
z=(s.match(/0/g)||[]).length,
r=s.length-z,
_=e+m-z-r,
// if DU: path is invalid.
// if _>0: path is shorter
// if _==0: check m > r to see if new path should replace old
s.indexOf(10)<0 & _>0|!_&m>r && (e=z,m=r));
// load list of people into arrays
I.split(`
`)[F](V=>{
P=V.split(' ');
// ID
D=+P[0];
// parents: NaN if not given
p[D]=[+P[1],+P[2]];
// gender: 1 if female, 0 if male
g[D]=P[3]<'L';
// merge the rest of the array to get name
n[D]=P.slice(4).join(' ');
// empty children array..for now
c[D]=[]
});
// push current ID to parents' children array.
p[F]((V,I)=>V[F](Y=>Y&&c[Y].push(I)));
// get shortest path
q(a,b,C,[]);
U=e>m?m:e,V=e>m?e:m;
G=(a,b,c,d)=>(a<3?C:y(a-1))+(a<2?C:'great-')+(a*!b?'grand':C)+'son0father0nephew0uncle0daughter0mother0niece0aunt'.split(0)[g[d]*4+2*b+(b==c)];
// output
alert(n[a]+' is '+(e/m+1?'the '+(U*V---1?
U<2?
G(V,U,e,a)
:(V-=--U,
(U<2?C:y(U))+'cousin'+
(V?
', '+(V>3?V+' times':[,'on','twi','thri'][V]+'ce')+' removed,'
:C)
)
:(p[a].join()==p[b].join()?C:'half-')+(g[a]?'sister':'brother'))+' of ':'not a blood relative to ')+n[b]+'.')
}
```
Notes:
* List of people should be placed in a variable `I` (as a string, with single spaces and newlines).
* To call: `R(a,b)`, where `a` and `b` are the IDs of the two people being compared.
[Answer]
## C - ungolfed
```
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef enum {
MALE,
FEMALE
} gender_t;
typedef enum {
VISITED_A,
VISITED_B,
NOT_VISITED
} visited_t;
struct node {
int id;
int mother;
int father;
char *name;
int height;
gender_t gender;
visited_t visited;
};
struct queue_item {
void *item;
struct queue_item *next;
struct queue_item *previous;
};
struct queue {
struct queue_item *first;
struct queue_item *last;
};
void queue_push(struct queue *q, struct node *n)
{
struct queue_item *i = malloc(sizeof(*i));
i->item = (void *)n;
i->next = q->last;
i->previous = NULL;
q->last = i;
if(i->next != NULL) {
i->next->previous = i;
} else {
q->first = i;
}
}
void queue_pop(struct queue *q)
{
struct queue_item *temp = q->first;
if(temp) {
q->first = q->first->previous;
if(q->first == NULL) {
q->last = NULL;
} else {
q->first->next = NULL;
}
free(temp);
}
}
struct node *queue_front(struct queue *q)
{
if(q->first) {
return (struct node *)q->first->item;
} else {
return NULL;
}
}
void queue_free(struct queue *q) {
while(queue_front(q) != NULL) {
queue_pop(q);
}
free(q);
}
struct node *find_shortest_path(struct node **nodes, struct node *a, struct node *b)
{
struct queue *q = malloc(sizeof(*q));
q->first = NULL;
q->last = NULL;
a->visited = VISITED_A;
queue_push(q, a);
b->visited = VISITED_B;
queue_push(q, b);
struct node *n, *father, *mother;
while((n = queue_front(q)) != NULL) {
if(n->visited == VISITED_A) {
if(n->father != 0) {
father = nodes[n->father-1];
if(father->visited == VISITED_B) {
a->height = n->height + 1;
b->height = father->height;
n = father;
goto exit_queue_free;
} else if(father->visited == NOT_VISITED) {
father->visited = VISITED_A;
father->height = n->height+1;
queue_push(q, father);
}
}
if(n->mother != 0) {
mother = nodes[n->mother-1];
if(mother->visited == VISITED_B) {
a->height = n->height + 1;
b->height = mother->height;
n = mother;
goto exit_queue_free;
} else if(mother->visited == NOT_VISITED) {
mother->visited = VISITED_A;
mother->height = n->height+1;
queue_push(q, mother);
}
}
} else if (n->visited == VISITED_B) {
if(n->father != 0) {
father = nodes[n->father-1];
if(father->visited == VISITED_A) {
b->height = n->height + 1;
a->height = father->height;
n = father;
goto exit_queue_free;
} else if(father->visited == NOT_VISITED) {
father->visited = VISITED_B;
father->height = n->height+1;
queue_push(q, father);
}
}
if(n->mother != 0) {
mother = nodes[n->mother-1];
if(mother->visited == VISITED_A) {
b->height = n->height + 1;
a->height = mother->height;
n = mother;
goto exit_queue_free;
} else if(mother->visited == NOT_VISITED) {
mother->visited = VISITED_B;
mother->height = n->height+1;
queue_push(q, mother);
}
}
}
queue_pop(q);
}
exit_queue_free:
queue_free(q);
return n;
}
int main(int argc, char *argv[]) {
if(argc != 4) {
return -1;
}
FILE *file = fopen(argv[1], "r");
int id_1 = strtol(argv[2], NULL, 0);
int id_2 = strtol(argv[3], NULL, 0);
char name[128];
char id[128];
char id_father[128];
char id_mother[128];
char gender;
struct queue *read_queue = malloc(sizeof(*read_queue));
read_queue->first = NULL;
read_queue->last = NULL;
int nr_nodes = 0;
while(fscanf(file, "%s %s %s %c %s",
id, id_mother, id_father, &gender, name) == 5) {
struct node *n = malloc(sizeof(*n));
if(strcmp(id, "?") == 0) {
n->id = 0;
} else {
n->id = strtol(id, NULL, 0);
}
if(strcmp(id_mother, "?") == 0) {
n->mother = 0;
} else {
n->mother = strtol(id_mother, NULL, 0);
}
if(strcmp(id_father, "?") == 0) {
n->father = 0;
} else {
n->father = strtol(id_father, NULL, 0);
}
if(gender == 'M') {
n->gender = MALE;
} else {
n->gender = FEMALE;
}
n->name = malloc(strlen(name)+1);
strcpy(n->name, name);
n->visited = NOT_VISITED;
n->height = 0;
queue_push(read_queue, n);
nr_nodes++;
}
struct node **nodes = malloc(sizeof(*nodes) * nr_nodes);
struct node *temp;
while((temp = queue_front(read_queue)) != NULL) {
nodes[temp->id-1] = temp;
queue_pop(read_queue);
}
queue_free(read_queue);
struct node *a = nodes[id_1-1], *b = nodes[id_2-1];
temp = find_shortest_path(nodes, a, b);
if(temp) {
if(a->height == b->height) {
if(a->height == 1) {
if((a->father == b->father) &&
(a->mother == b->mother)) {
printf("%s is the %s of %s.\n", a->name,
a->gender == MALE ?
"brother" : "sister",
b->name);
} else {
printf("%s is the half-%s of %s.\n",
a->name,
a->gender == MALE ?
"brother" : "sister",
b->name);
}
} else if (a->height == 2) {
printf("%s is the cousin of %s.\n", a->name,
b->name);
} else if (a->height == 3){
printf("%s is the 2nd cousin of %s.\n", a->name,
b->name);
} else if (a->height == 4) {
printf("%s is the 3rd cousin of %s.\n", a->name,
b->name);
} else {
printf("%s is the %dth cousin of %s.\n", a->name,
a->height-1,b->name);
}
} else if (a->height == 0) {
if(b->height == 1) {
printf("%s is the %s of %s.\n", a->name,
a->gender == MALE ? "father" :
"mother", b->name);
} else if (b->height == 2) {
printf("%s is the grand%s of %s.\n", a->name,
a->gender == MALE ? "father" :
"mother", b->name);
} else if (b->height == 3) {
printf("%s is the great-grand%s of %s.\n",
a->name, a->gender == MALE ?
"father" : "mother", b->name);
} else if (b->height == 4) {
printf("%s is the 2nd great-grand%s of %s.\n",
a->name, a->gender == MALE ?
"father" : "mother", b->name);
} else if (b->height == 5) {
printf("%s is the 3rd great-grand%s of %s.\n",
a->name, a->gender == MALE ?
"father" : "mother", b->name);
} else if (b->height == 6) {
printf("%s is the %dth great-grand%s of %s.\n",
a->name, b->height-2,
a->gender == MALE ? "father" :
"mother", b->name);
}
} else if (b->height == 0) {
if(a->height == 1) {
printf("%s is the %s of %s.\n", a->name,
a->gender == MALE ? "son" :
"daughter", b->name);
} else if (a->height == 2) {
printf("%s is the grand%s of %s.\n", a->name,
a->gender == MALE ? "son" :
"daughter", b->name);
} else if (a->height == 3) {
printf("%s is the great-grand%s of %s.\n",
a->name, a->gender == MALE ?
"son" : "daughter", b->name);
} else if (a->height == 4) {
printf("%s is the 2nd great-grand%s of %s.\n",
a->name, a->gender == MALE ?
"son" : "daughter", b->name);
} else if (a->height == 5) {
printf("%s is the 3rd great-grand%s of %s.\n",
a->name, a->gender == MALE ?
"son" : "daughter", b->name);
} else {
printf("%s is the %dth great-grand%s of %s.\n",
a->name, a->height - 2,
a->gender == MALE ? "son" :
"daughter", b->name);
}
} else if (a->height == 1) {
if(b->height == 2) {
printf("%s is the %s of %s.\n", a->name,
a->gender == MALE ? "uncle" :
"aunt", b->name);
} else if(b->height == 3) {
printf("%s is the great-%s of %s.\n", a->name,
a->gender == MALE ? "uncle" :
"aunt", b->name);
} else if(b->height == 4) {
printf("%s is the 2nd great-%s of %s.\n", a->name,
a->gender == MALE ? "uncle" :
"aunt", b->name);
} else if(b->height == 5) {
printf("%s is the 3rd great-%s of %s.\n", a->name,
a->gender == MALE ? "uncle" :
"aunt", b->name);
} else {
printf("%s is the %dth great-%s of %s.\n",
a->name, b->height - 2,
a->gender == MALE ? "uncle" :
"aunt", b->name);
}
} else if (b->height == 1) {
if(a->height == 2) {
printf("%s is the %s of %s.\n", a->name,
a->gender == MALE ? "nephew" :
"niece", b->name);
} else if(a->height == 3) {
printf("%s is the great-%s of %s.\n", a->name,
a->gender == MALE ? "nephew" :
"niece", b->name);
} else if(a->height == 4) {
printf("%s is the 2nd great-%s of %s.\n", a->name,
a->gender == MALE ? "nephew" :
"niece", b->name);
} else if(a->height == 5) {
printf("%s is the 3rd great-%s of %s.\n", a->name,
a->gender == MALE ? "nephew" :
"niece", b->name);
} else {
printf("%s is the %dth great-%s of %s.\n",
a->name, a->height - 2,
a->gender == MALE ? "nephew" :
"niece", b->name);
}
} else {
int m = a->height > b->height ? a->height - b->height :
b->height - a->height;
int n = a->height > b->height ? b->height - 1:
a->height - 1;
printf("%s is the ", a->name);
if(n == 2) printf("2nd ");
if(n == 3) printf("3rd ");
if(n > 3) printf("%dth ", n);
printf(" cousin, ");
if (m == 1) printf("once");
if (m == 2) printf("twice");
if (m == 3) printf("thrice");
if (m > 3) printf("%d times", m);
printf(" removed, of %s.\n", b->name);
}
} else
printf("%s is not a blood relative to %s.\n", a->name, b->name);
int i;
for(i = 0; i < nr_nodes; i++) {
free(nodes[i]->name);
free(nodes[i]);
}
free(nodes);
fclose(file);
return 0;
}
```
[Answer]
### Ruby - ~~1892~~ ~~1290~~ 1247
Run as `ruby relation.rb ID1 ID2 relationship_file`.
```
P=Struct.new(:i,:m,:f,:s,:n,:c)
def f u,v,w,x,y,z
t=[y,z,v]
return t if v=='?'||x.include?(v)||v==w
r=x+[v];p=u[v]
p.c.each{|o|s=f(u,o,w,r,y,z+1);return s if s.last==w}
return t if z>0
[:m,:f].each{|i|s=f(u,p[i],w,r,y+1,z);return s if s.last==w}
t;end
def g j,a,r,b;puts"#{j[a].n} is the #{r} of #{j[b].n}.";end
def k n;n<2?'':n<3?'2nd':n<4?'3rd':"#{n}th";end
def h n;n<2?'':n<3?'great-':"#{k(n-1)} great-";end
def e n;s=n<2?'once':n<3?'twice':n<4?'thrice':"#{n} times";", #{s} removed,";end
def d u,a,b,x;y,z=x
if y==1&&z==1
w=u[a];v=u[b]
g(u,a,((w.f==v.f&&w.m==v.m)?'':'half-')+((w.s=='F')?'sister':'brother'),b)
elsif y<1||z<1
t=[y,z].max
g(u,a,h(t-1)+(t>=2?'grand':'')+(u[a].s=='F'?y>0?'daughter':'mother':y>0?'son':'father'),b)
elsif y==1||z==1
t=[y,z].max
g(u,a,h(t-1)+(u[a].s=='F'?y==1?'aunt':'niece':y==1?'uncle':'nephew'),b)
else
s=[y,z].min
g(u,a,(s-1>1?"#{k(s-1)} ":'')+'cousin'+((y==z)?'':e((z-y).abs)),b)
end;end
A,B=$*.shift(2);j={}
ARGF.each_line{|l|a=l.scan(/\s*(\d+)\s+(\d+|\?)\s+(\d+|\?)\s+([MF])\s+([\w\s]*\w+)\s*/).flatten;j[a[0]]=P.new(a[0],a[1],a[2],a[3],a[4],[])}
j.each{|k,i|[:f,:m].each{|l|j[i[l]].c<<k if i[l]!='?'}}
a=f(j,A,B,[],0,0)
if a.pop==B
d(j,A,B,a)
else
puts"#{j[A].n} is not a blood relative to #{j[B].n}."
```
Ungolfed version - ~~5251~~ 3416 (same call tree, just did a lot of code folding)
```
Person = Struct.new( :id, :mother, :father, :sex, :name, :children )
# Find a path between "start" and "finish". To reflect human consanguinity
# rules, either travel down through descendants or up through ancestors with a
# possible down leg through their descendants.
#
# Use depth-first search until forced to improve.
# If start up, path allowed one inflection point.
# Once start down, path must continue down.
# returns [stepsUp, stepsDown, trialResult],
# shortest path found if trialResult == finish
def findRelationship(people, start, finish, pathSoFar, stepsUp, stepsDown)
trialResult = [stepsUp, stepsDown, start]
# Return success or failure.
return trialResult if start == '?' || pathSoFar.include?(start) || start == finish
# If success or failure not known, explore further.
pathNext = pathSoFar + [start]
person = people[start]
# Follow descendants.
person[:children].each do |child|
trial = findRelationship(people, child, finish, pathNext, stepsUp, stepsDown+1)
return trial if trial.last == finish
end
# Already past inflection point?
return trialResult if stepsDown > 0
# Follow ancestry.
[:mother, :father].each do |parent|
trial = findRelationship(people, person[parent], finish, pathNext, stepsUp+1, stepsDown)
return trial if trial.last == finish
end
return trialResult
end
def printRelationship(people, a, relationship, b)
puts "#{people[a][:name]} is the #{relationship} of #{people[b][:name]}."
end
def formatNth(n)
return n<2?'':n<3?'2nd':n<4?'3rd':"#{n}th"
end
def formatGenerations(n)
return n<2?'':n<3?'great-':"#{formatNth(n-1)} great-"
end
def formatRemoves(n)
s=n<2?'once':n<3?'twice':n<4?'thrice':"#{n} times"
return ", #{s} removed,"
end
def describeRelationship(people, a, b, legLengths)
down = legLengths.pop
up = legLengths.pop
if up==1 && down==1
who = people[a]
what = people[b]
printRelationship(people, a,
(who[:father] == what[:father] && who[:mother] == what[:mother] ? '' : 'half-') +
((who[:sex] == 'F') ? 'sister' : 'brother'),
b)
elsif up<1 || down<1
pathLength = [up, down].max
printRelationship(people, a,
formatGenerations(pathLength-1) + ((pathLength>=2) ? 'grand' : '') +
(up>0 ?
people[a][:sex] == 'F' ? 'daughter' : 'son' :
people[a][:sex] == 'F' ? 'mother': 'father'
),
b)
elsif up==1 || down==1
pathLength = [up, down].max
printRelationship(people, a,
formatGenerations(pathLength-1) +
(up==1 ?
people[a][:sex] == 'F' ? 'aunt': 'uncle' :
people[a][:sex] == 'F' ? 'niece': 'nephew'
),
b)
else
shortestLeg = [up, down].min
printRelationship(people, a,
(shortestLeg-1>1 ? "#{formatNth(shortestLeg-1)} " : '') +
'cousin' +
(up==down ? '' : formatRemoves((down-up).abs)),
b)
end
end
A = $*.shift
B = $*.shift
# Meet and greet.
people = {}
ARGF.each_line do |line|
a = line.scan(/\s*(\d+)\s+(\d+|\?)\s+(\d+|\?)\s+([MF])\s+([\w\s]*\w+)\s*/).flatten
people[a[0]] = Person.new( a[0], a[1], a[2], a[3], a[4], [] )
end
# Build lineage.
people.each do |key, individual|
[:father, :mother].each do |l|
people[individual[l]][:children] << key if individual[l] != '?'
end
end
# How are A and B related?
a = findRelationship(people, A, B, [], 0, 0)
if a.pop == B
describeRelationship(people, A, B, a)
else
puts "#{people[A][:name]} is not a blood relative to #{people[B][:name]}."
end
```
Passes the following test suite:
```
#!/usr/bin/env perl
#
use strict;
use warnings;
require File::Temp;
use File::Temp qw( tempfile tempdir );
use Test::More qw(no_plan);
# use Test::More tests => 38;
# solution executable
my $solver='ruby relation.rb';
# "happy" path
my $dir = tempdir( CLEANUP => 1 );
my ($fh, $filename) = tempfile( DIR => $dir );
my $testData = <<'END_TEST_DATA';
1 ? ? F Agatha
2 ? ? M Adam
3 ? ? F Betty
4 1 2 M Bertrand
5 1 2 F Charlotte
6 ? ? M Carl
7 ? ? F Daisy
8 3 4 M David
9 5 6 F Emma
10 ? ? M Edward
11 ? ? F Freya
12 7 8 M Fred
13 9 10 F Grace
14 ? ? M Gerald
15 ? ? F Hillary
16 11 12 M Herbert
17 13 14 F Jane
18 ? ? M James
19 15 16 F Kate
20 17 18 M Larry
21 ? 18 F Mary
END_TEST_DATA
print $fh $testData;
close($fh);
is( `$solver 1 2 $filename 2>&1`, "Agatha is not a blood relative to Adam.\n", 'OP example #1, 1 2');
is( `$solver 8 3 $filename 2>&1`, "David is the son of Betty.\n", 'OP example #2, 8 3');
is( `$solver 9 13 $filename 2>&1`, "Emma is the mother of Grace.\n", 'OP example #3, 9 13');
is( `$solver 4 5 $filename 2>&1`, "Bertrand is the brother of Charlotte.\n", 'OP example #4, 4 5');
is( `$solver 9 4 $filename 2>&1`, "Emma is the niece of Bertrand.\n", 'OP example #5, 9 5');
is( `$solver 5 8 $filename 2>&1`, "Charlotte is the aunt of David.\n", 'OP example #6, 5 8');
is( `$solver 16 7 $filename 2>&1`, "Herbert is the grandson of Daisy.\n", 'OP example #7, 16 7');
is( `$solver 1 9 $filename 2>&1`, "Agatha is the grandmother of Emma.\n", 'OP example #8, 1 9 (amended)');
is( `$solver 12 5 $filename 2>&1`, "Fred is the great-nephew of Charlotte.\n", 'OP example #9, 12 5');
is( `$solver 4 13 $filename 2>&1`, "Bertrand is the great-uncle of Grace.\n", 'OP example #10, 4 13');
is( `$solver 16 3 $filename 2>&1`, "Herbert is the great-grandson of Betty.\n", 'OP example #11, 16 3');
is( `$solver 6 17 $filename 2>&1`, "Carl is the great-grandfather of Jane.\n", 'OP example #12, 6 17');
is( `$solver 19 2 $filename 2>&1`, "Kate is the 3rd great-granddaughter of Adam.\n", 'OP example #13, 19 2 (amended)');
is( `$solver 1 17 $filename 2>&1`, "Agatha is the 2nd great-grandmother of Jane.\n", 'OP example #14, 1 17 (amended)');
is( `$solver 20 4 $filename 2>&1`, "Larry is the 3rd great-nephew of Bertrand.\n", 'OP example #15, 20 4');
is( `$solver 5 16 $filename 2>&1`, "Charlotte is the 2nd great-aunt of Herbert.\n", 'OP example #16, 5 16');
is( `$solver 8 9 $filename 2>&1`, "David is the cousin of Emma.\n", 'OP example #17, 8 9');
is( `$solver 19 20 $filename 2>&1`, "Kate is the 4th cousin of Larry.\n", 'OP example #18, 19 20');
is( `$solver 16 9 $filename 2>&1`, "Herbert is the cousin, twice removed, of Emma.\n", 'OP example #19, 16 9');
is( `$solver 12 17 $filename 2>&1`, "Fred is the 2nd cousin, once removed, of Jane.\n", 'OP example #20, 12 17');
is( `$solver 21 20 $filename 2>&1`, "Mary is the half-sister of Larry.\n", 'OP example #21, 21 20');
# "sad" path
# none!
# "bad" path
# none!
exit 0;
```
[Answer]
# Javascript, 2292
```
for(var r=prompt().split("\n"),n=[{m:"",f:""}],t=1;t<r.length;t++){var e=r[t].split(" ");n[+e[0]]={m:"?"==e[1]?-1:+e[1],f:"?"==e[2]?-1:+e[2],s:e[3],n:e[4]}}var f=function(r,t){return r=n[r],t=n[t],~r.m&&r.m==t.m&&~r.f&&r.f==t.f?"M"==r.s?"brother":"sister":void 0},i=function(r,t){return r=n[r],t=n[t],~r.m&&r.m==t.m||~r.f&&r.f==t.f?"M"==r.s?"half-brother":"half-sister":void 0},o=function(r){var n=("0"+r).slice(-2),t=n[0];return n=n[1],r+(1==t?"th":1==n?"st":2==n?"nd":3==n?"rd":"th")+" "},a=function(r){return 1==r?"once":2==r?"twice":3==r?"thrice":r+" times"},h=function(r,t){var e,f,i=[t],a=[n[t].m,n[t].f];for(e=0;e<n.length&&!~a.indexOf(r);e++){i=a.slice(),a=[];for(var h=0;h<i.length;h++)i[h]>=0&&a.push(n[i[h]].m,n[i[h]].f)}if(!(e>=n.length))return f="M"==n[r].s?"father":"mother",e>0&&(f="grand"+f),e>1&&(f="great-"+f),e>2&&(f=o(e-1)+f),f},u=function(r,t){var e=h(t,r);return e?e.slice(0,-6)+("M"==n[r].s?"son":"daughter"):void 0},s=function(r){for(var t=[],e=1;e<n.length;e++)f(r,e)&&e!=r&&t.push(e);return t},l=function(r){return r=r.slice(0,-6),""==r?r:"grand"==r?"great ":"great-grand"==r?"2nd great ":o(+r.split(" ")[0].slice(0,-2)+1)+"great "},v=function(r,t){for(var e,f=s(r),i=0;i<f.length&&!(e=h(f[i],t));i++);return e?l(e)+("M"==n[r].s?"uncle":"aunt"):void 0},c=function(r,t){var e=v(t,r);return e?(e.split(" ").slice(0,-1).join(" ")+("M"==n[r].s?" nephew":" niece")).trim():void 0},g=function(r,n){for(var t=0;t<r.length;t++)if(~n.indexOf(r[t]))return!0},m=function(r,t){r=n[r],t=n[t];for(var e=[[r.m,r.f]],f=[[t.m,t.f]],i=0;i<n.length;i++){for(var h=e[i],u=f[i],s=[],l=0;l<h.length;l++){var v=0,c=0;-1!=h[l]&&(v=n[h[l]].m,c=n[h[l]].f),v>0&&s.push(v),c>0&&s.push(c)}for(var m=[],l=0;l<u.length;l++){var v=0,c=0;-1!=u[l]&&(v=n[u[l]].m,c=n[u[l]].f),v>0&&m.push(v),c>0&&m.push(c)}if(!s.length&&!m.length)break;e.push(s),f.push(m)}for(var i=1;i<Math.min(e.length,f.length);i++){var h=e[i],u=f[i];if(g(h,u))return(i>1?o(i):"")+"cousin"}for(var i=1;i<e.length;i++)for(var h=e[i],l=1;l<f.length;l++){var u=f[l];if(g(h,u)){var p=Math.min(i,l);return(p>1?o(p):"")+"cousin, "+a(Math.abs(i-l))+" removed,"}}},e=prompt().split(" "),p=+e[0],d=+e[1],M=u(p,d)||h(p,d)||f(p,d)||i(p,d)||c(p,d)||v(p,d)||m(p,d);alert(n[p].n+" is "+(M?"the "+M+" of ":"not a blood relative to ")+n[d].n+".\n"
```
I'm sure it can be golfed much further, all I did was put an ungolfed version through a minifier.
You can [run the ungolfed version here on jsFiddle](http://jsfiddle.net/peterolson/pmbbws1k/15/). Here is the output for the example data:
```
1 2 Agatha is not a blood relative to Adam.
8 3 David is the son of Betty.
9 13 Emma is the mother of Grace.
4 5 Bertrand is the brother of Charlotte.
9 4 Emma is the niece of Bertrand.
5 8 Charlotte is the aunt of David.
16 7 Herbert is the grandson of Daisy.
1 9 Agatha is the grandmother of Emma.
12 5 Fred is the great nephew of Charlotte.
4 13 Bertrand is the great uncle of Grace.
16 3 Herbert is the great-grandson of Betty.
6 17 Carl is the great-grandfather of Jane.
19 1 Kate is the 3rd great-granddaughter of Agatha.
2 17 Adam is the 2nd great-grandfather of Jane.
20 4 Larry is the 3rd great nephew of Bertrand.
5 16 Charlotte is the 2nd great aunt of Herbert.
8 9 David is the cousin of Emma.
19 20 Kate is the 4th cousin of Larry.
16 9 Herbert is the cousin, twice removed, of Emma.
12 17 Fred is the 2nd cousin, once removed, of Jane.
21 20 Mary is the half-sister of Larry.
```
[Answer]
# Python 3: 1183
```
def D(i):
if i==a:return 0
r=[D(c)for c in t[i][4]]
if r:return min(x for x in r if x is not None)+1
def A(i):
if i=="?":return None
r=D(i)
if r is not None:return 0,r
m,f=map(A,t[i][:2])
return(f[0]+1,f[1])if not m or(f and sum(f)<sum(m))else(m[0]+1,m[1])if f else None
def P(r):print("%s is %s of %s"%(t[a][3],r,t[b][3]))
O=lambda n:"%d%s "%(n,{2:"nd",3:"rd"}.get(n,"th"))
G=lambda n:(O(n-2)if n>3 else"")+("great-"if n>2 else"")
GG=lambda n:G(n)+("grand"if n>1 else"")
f,a,b=input().split()
t={}
for l in open(f):
i,m,f,g,n=l.strip().split(maxsplit=4)
t[i]=(m,f,g,n,[])
for i,(m,f,g,n,c)in t.items():
if m in t:t[m][4].append(i)
if f in t:t[f][4].append(i)
g=t[a][2]=="M"
r=A(b)
if r:
u,d=r
if u==d==1:P("the "+("half-"if t[s][0]!=t[e][0]or t[s][1]!=t[s][1]else"")+["sister","brother"][g])
elif u==0:P("the "+GG(d)+["daughter","son"][g])
elif d==0:P("the "+GG(u)+["mother","father"][g])
elif u==1:P("the "+G(d)+["niece","nephew"][g])
elif d==1:P("the "+G(u)+["aunt","uncle"][g])
else:
n,m=min(u,d)-1,abs(u-d);P("the "+(O(n)if n>1 else"")+"cousin"+(" %s removed"%{1:"once",2:"twice",3:"thrice"}.get(m,"%d times"%m)if m else""))
else:
P("not a blood relative")
```
The filename and the IDs of the people to be described are are read from standard input on a single line.
The top part of the code is function definitions. The script starts half-way down, and first works on processing the input (parsing the file, then assigning children to their parents in a second pass).
After the data is set up, we call the `A` function once to kick off a recursive search. The result defines the relationship.
The rest of the code is dedicated to describing that relationship in English. Siblings and cousins are complicated (and use long lines), the rest are pretty straight forward.
Example run (the second line is my input):
```
C:\>Python34\python.exe relations.py
relations.txt 20 4
Larry is the 3rd great-nephew of Bertrand
```
Function and variable name key:
* `f`: The filename the family's data is read from.
* `a`: The id of the person who's relationship we're naming.
* `b`: The id of the person the relationship is defined relative to.
* `t`: The family tree itself, as a dictionary mapping from an id to a 5-tuple of mother's id, father's id, sex, name and a list of children.
* `g`: A Boolean value reflecting the gender of person `a`. It is `True` if they are a male.
* `u`: The number of generations from `b` to the common ancestor of `a` and `b` (or 0 if `b` is `a`'s ancestor).
* `d`: The number of generations from `a` to the common ancestor of `a` and `b` (or 0 if `a` is `b`'s ancestor).
* `D(i)`: Recursively search the descendents of person `i` for person `a`. Return the depth `a` was found at, or None if it was not found.
* `A(i)`: Recursively search `i` and `i`'s descendents, but if its not found recursively search `i`'s ancestors (and their descendents) too. Returns a 2-tuple, who's values are `u` and `d` described above. If a relationship is found through both parents, the one with the smallest number of generational steps (`u+d`) is preferred. If person `a` has no blood relationship to person `i`, `A(i)` returns `None`.
* `P(r)`: Print result string `r` bracketed by the names of persons `a` and `b`.
* `O(n)`: Return an ordinal string for the given number `n`. Only supports `1 < n < 21`.
* `G(n)`: Return a prefix string equivalent to `n-1` "greats" (e.g. `"2nd great-"` for n=2`). Will return an empty string for n <= 1.
* `GG(n)`: Returns a prefix string with "Nth great-" and "grand", as appropriate for `n` generations. Will return an empty string for n <= 1.
I took a few shortcuts in the name of shorter code which could be revised for better (or slightly more correct) performance on large genealogies. The `A` function doesn't make any attempt to avoid recursing down child trees that have already been searched, which makes it slower than necessary (though probably still fast enough for reasonable sized families). The `O` function doesn't correctly handle ordinals greater than 20 (it's a bit tricky to get all of `11th`, `21st`, and `101st` right, but in one of my draft versions I did it in about 25 additional bytes). Unless you're dealing with very old and famous families (e.g. some of the royal families of Europe) I'm not sure I'd trust the accuracy of a genealogy that went back that far anyway.
On the other hand, I've also skipped over a few places where I could shave off a few bytes. For instance, I could save 3 bytes by renaming `GG` to a single character name, but basing the name off of `great-grand` seemed more worth while to me.
I believe that all white-space in the code is required, but it's possible that some can be skipped and I've just missed them (I kept finding stray spaces in argument lists as I was typing up this answer, but I think I've gotten them all now).
Because my recursive matching requires a relatively simple rule for which relationships to prefer if there is more than one, I don't give exactly the requested results in some obscure cases involving intergenerational incest. For instance, if person `a` is both person `b`'s uncle and grandfather, my code will prefer the grandfather relationship despite the question saying that the uncle relationship should have higher precedence.
Here's an example dataset that exposes the issue:
```
1 ? ? F Alice
2 1 ? M Bob
3 1 2 F Claire
4 3 ? F Danielle
```
I suspect that for most programs, the relationships between Bob and Claire or between Bob and Danielle will cause trouble. They will either call the first pair half-siblings rather than father/daughter or they'll describe the latter pair as grandfather/granddaughter rather than uncle/niece. My code does the latter, and I don't see any reasonable way to change it to get the requested results without also getting the first pair wrong.
[Answer]
A test suite. Stuff it into t/relation.t and run "prove" or "perl t/relation.t". It currently assumes the program file is "relation.rb".
It's community wiki, so feel free to add tests. If you change it, I think a timestamp (or some other obvious flag) would be in order. Wish list:
1. a "bad boy" test that will punish exhaustive search strategies
```
#
# S. Leadley, Wed Aug 27 20:08:31 EDT 2014
use strict;
use warnings;
require File::Temp;
use File::Temp qw( tempfile tempdir );
use Test::More qw(no_plan);
# use Test::More tests => 38;
# solution executable
my $solver='ruby relation.rb';
# "happy" path
my $dir = tempdir( CLEANUP => 1 );
my ($fh, $filename) = tempfile( DIR => $dir );
my $testData = <<'END_TEST_DATA';
1 ? ? F Agatha
2 ? ? M Adam
3 ? ? F Betty
4 1 2 M Bertrand
5 1 2 F Charlotte
6 ? ? M Carl
7 ? ? F Daisy
8 3 4 M David
9 5 6 F Emma
10 ? ? M Edward
11 ? ? F Freya
12 7 8 M Fred
13 9 10 F Grace
14 ? ? M Gerald
15 ? ? F Hillary
16 11 12 M Herbert
17 13 14 F Jane
18 ? ? M James
19 15 16 F Kate
20 17 18 M Larry
21 ? 18 F Mary
END_TEST_DATA
print $fh $testData;
close($fh);
is( `$solver 1 2 $filename 2>&1`, "Agatha is not a blood relative to Adam.\n", 'OP example #1, 1 2');
is( `$solver 8 3 $filename 2>&1`, "David is the son of Betty.\n", 'OP example #2, 8 3');
is( `$solver 9 13 $filename 2>&1`, "Emma is the mother of Grace.\n", 'OP example #3, 9 13');
is( `$solver 4 5 $filename 2>&1`, "Bertrand is the brother of Charlotte.\n", 'OP example #4, 4 5');
is( `$solver 9 4 $filename 2>&1`, "Emma is the niece of Bertrand.\n", 'OP example #5, 9 5');
is( `$solver 5 8 $filename 2>&1`, "Charlotte is the aunt of David.\n", 'OP example #6, 5 8');
is( `$solver 16 7 $filename 2>&1`, "Herbert is the grandson of Daisy.\n", 'OP example #7, 16 7');
is( `$solver 1 9 $filename 2>&1`, "Agatha is the grandmother of Emma.\n", 'OP example #8, 1 9 (amended)');
is( `$solver 12 5 $filename 2>&1`, "Fred is the great-nephew of Charlotte.\n", 'OP example #9, 12 5');
is( `$solver 4 13 $filename 2>&1`, "Bertrand is the great-uncle of Grace.\n", 'OP example #10, 4 13');
is( `$solver 16 3 $filename 2>&1`, "Herbert is the great-grandson of Betty.\n", 'OP example #11, 16 3');
is( `$solver 6 17 $filename 2>&1`, "Carl is the great-grandfather of Jane.\n", 'OP example #12, 6 17');
is( `$solver 19 2 $filename 2>&1`, "Kate is the 3rd great-granddaughter of Adam.\n", 'OP example #13, 19 2 (amended)');
is( `$solver 1 17 $filename 2>&1`, "Agatha is the 2nd great-grandmother of Jane.\n", 'OP example #14, 1 17 (amended)');
is( `$solver 20 4 $filename 2>&1`, "Larry is the 3rd great-nephew of Bertrand.\n", 'OP example #15, 20 4');
is( `$solver 5 16 $filename 2>&1`, "Charlotte is the 2nd great-aunt of Herbert.\n", 'OP example #16, 5 16');
is( `$solver 8 9 $filename 2>&1`, "David is the cousin of Emma.\n", 'OP example #17, 8 9');
is( `$solver 19 20 $filename 2>&1`, "Kate is the 4th cousin of Larry.\n", 'OP example #18, 19 20');
is( `$solver 16 9 $filename 2>&1`, "Herbert is the cousin, twice removed, of Emma.\n", 'OP example #19, 16 9');
is( `$solver 12 17 $filename 2>&1`, "Fred is the 2nd cousin, once removed, of Jane.\n", 'OP example #20, 12 17');
is( `$solver 21 20 $filename 2>&1`, "Mary is the half-sister of Larry.\n", 'OP example #21, 21 20');
# "sad" path
# none!
# "bad" path
is( `$solver 1 32 $filename 2>&1`, "person with ID 32 does not exist\n", 'not required, not in the spec');
exit 0;
```
] |
[Question]
[

Picture of me drafting this challenge with my advanced drawing skills.
## Background
The Stickman wars happened long ago, when Earth's dominant species was made of nothing but sticks. Historians regret the fact that there were no painters or cameras back then, we could use some pictures of that war in today's history books. That's where your coding powers become useful. Stickmen are very easily drawed and Historians managed to find some data about how many stickmen fought the wars¹. Now it's up to you to recreate an image of the moment right before the war began!
Here are the brave stickmen involved in the war:
```
O /
|/|\/
| |
/ \ Swordsman
O A
/|\|
| |
/ \| Spearman
.
.' *.
' O *
' \|/ .
. | *
'./ \*. Mage
O
/|\
|
/ \ Villager
O
/|\
/ \ Infant
```
**Input**
Receive via stdin or equivalent a representation of every stickman who appeared on each side of the battlefield. For example, if two Swordmen fought on the right side and two spearmen on the left side, your input can be `{Sword: 2}, {Spear: 2}`, `[2,0,0,0,0], [0,2,0,0,0]` or a `"WW", "SS"`.
**Output**
A representation of every brave stickmen in a battle field, according to the rules below. It can be shown on stdout or saved to a file, whatever rocks your boat.
**Rules**
1. On the left side will be every stickmen of the first array/string/object your program received.
2. Those stickmen must look exactly like the ones shown before on this question.
3. The order of the left side army must be `Infants Villagers Mages Swordsmen Spearmen`.
4. The right side army will behave just the same, but with the characters and the order mirrored.
5. Each stickman will be separated by 1 space.
6. Each class will be separated by 3 spaces.
7. The armies will be separated by 8 spaces.
8. Since stickmen don't fly, you must draw the ground using hyphen-minuses `-`.
9. The ground must end on the same column the last stickman of the right army ends.
**Example**
Let's assume my program expects two arrays with length 5 and each value in the array represents, in order, `Infants Villagers Mages Swordsmen Spearmen`.
Input: [1,1,2,3,1] [0,0,1,1,1]
```
. . .
.' *. .' *. .* '.
O ' O * ' O * O / O / O / O A A O \ O * O '
O /|\ ' \|/ . ' \|/ . |/|\/ |/|\/ |/|\/ /|\| |/|\ \/|\| . \|/ '
/|\ | . | * . | * | | | | | | | | | | | | * | .
/ \ / \ './ \*. './ \*. / \ / \ / \ / \| |/ \ / \ .*/ \'.
---------------------------------------------------------------------------------------
```
**Final Considerations**
Please note that [standard loopholes apply](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny) and that the mage is completely asymmetrical just because.
The result of most upvoted answer will be the "cover image" of this challenge. The shortest answer by the end of the month (08/31/2014) will be selected as the winner.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code, in bytes, wins.
---
¹Citation needed
[Answer]
# JavaScript (E6) 336 ~~344 356 369 424 478 522 570~~
**Edit 6** Last edit was buggy. Bug fix and shortened. That's all I hope.
**Edit 5** Finally found a way to get rid of multiply by 23 - bothered me from start. Plus another change to the input (@William shout when it's too much). Now the function expects one array parameter, containing 2 subarrays. Without this change it's 349 - still an improvement
**Edit 4** Shaved some more bytes and a little change to input format.
With the new input format a missing class is represented as an empty array element. So `D([1,,2,3,1],[,3,1,1,2])` instead of `D([1,0,2,3,1],[0,3,1,1,2])`. I think it still obeys the rules.
**Edit 3** Golfed more. No changes to the algorithm, but abusing a lot of array.map and local functions to avoid for loops.
**Edit 2** String compression, the right way ...
**Edit** Added string compression, a lot of work and not much gained. Now the mirror stickmen are generated from a template, not stored.
Made a few tries, first running. ~~To be golfed.~~
~~NB Kolmogorow-business still to be tackled.~~
**Test** In FireFox console. ~~Change 'return' with~~ Add 'alert(...)' to have an output statement (albeit not useful at all)
`console.log(D([[1,,2,3,1],[,3,1,1,2]]))`
*Output*
```
. . .
.' *. .' *. .* '.
' O * ' O * O / O / O / O A A O A O \ O * O ' O O O
O ' \|/ . ' \|/ . |/|\/ |/|\/ |/|\/ /|\| |/|\ |/|\ \/|\| . \|/ ' /|\ /|\ /|\
/|\ . | * . | * | | | | | | | | | | | | | | * | . | | |
/ \ './ \*. './ \*. / \ / \ / \ / \| |/ \ |/ \ / \ .*/ \.' / \ / \ / \
¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯
```
**Golfed Code**
```
D=a=>
(J=v=>v.join(''))((l=[r=n=' ',3,6,13,19,23]).map(_=>f=(F=f=>J(a[f].map((c,q)=>
("9.299.' *.87O2' O *3O21 O A O 1|0' 0|1 .|1|01 1|0|1|0 | .2|2*| |4| |1 01 0'.1 0*. 1 021 0|"[R='replace'](/[2-9]/g,x=>n.repeat(x))
.slice(l[q]-r,l[q+1]-r)[R](/\d/g,x=>'\\/'[x^f])+n).repeat(c)+n+n
))+n)(0)+J([...F(1)].reverse(r-=23))+'\n'))+f[R](/./g,'¯')
```
**Code (edit 2)**
```
D=(a,b)=>{
F=(s,f)=>(s=s[R](/\d/g,x=>'/\\'[x^f]),f?s:[...s].reverse().join('')),
v="9.299.' *.87O2' O *3O21 O A O 1|0' 0|1 .|1|01 1|0|1|0 | .2|2*| |4| |1 01 0'.1 0*. 1 021 0|"
[R='replace'](/\d/g,x=>x>1?' '.repeat(x):x),
l=[0,3,6,13,19,23];
for(o='',r=0;v[r];r+=23,f=F(z,1)+' '+F(w,0),o+=f+'\n',f=f[R](/./g,'¯'))
for(z=w=p='';p<10;++p)
if(c=(p<5?a:b)[q=p%5])x=(v.slice(r+l[q],r+l[q+1])+' ').repeat(c)+' ',p<5?z+=x:w+=x
return o+f
}
```
**Ungolfed code (1st version)**
```
D=(a,b)=>{
v=" . . .' *. .* '. O ' O * O / O A * O ' \\ O A O O /|\\' \\|/ .|/|\\/ /|\\|. \\|/ ' \\/|\\||/|\\/|\\ | . | *| | | |* | . | || | / \\/ \\'./ \\*. / \\ / \\|.*/ \\'. / \\ |/ \\"
l=[0,3,6,13,19,23,30,36,40]
o=''
for(r=0;r<6;++r)
{
z=w=''
for(p=0;p<10;p++)
{
c=a[p]||b[p-5];
if (c)
{
q = p<7 ? p%5 : p-2
x = (v.slice(r*40+l[q],r*40+l[q+1])+' ').repeat(c)
if (p<5)
z+=x+' ';
else
w=x+' '+w
}
}
f = z + ' ' + w
o += f + '\n'
f = '¯'.repeat(f.length-3)
}
return o+f
}
```
[Answer]
## Python ~~362~~ 353
**Edit:** Removing one for-loop and using the exec statement saved 9 bytes
```
z,x,t,j=" ",input(),str.replace,0
w=0,3,6,13,19,23
a=9*z+"."+20*z+".' *."+15*z+"o ' o * o a o A o a|b' b|a .|a|ba a|b|a|b | . | *| | | |a ba b'.a b*. a b a b|"
exec"b=''\nfor c in 0,1:b+=z*8*c+t(t(' '.join([z.join([a[w[k]+j:w[k+1]+j]]*v)for k,v in enumerate(x[c])if v])[::1-2*c],'a','\/'[c<1]),'b','\/'[c])\nprint b;j+=23;"*6
print'-'*len(b)
```
**Input:**
```
[0,0,2,1,1],[1,0,2,1,2]
```
**Output:**
```
. . . .
.' *. .' *. .* '. .* '.
' o * ' o * o / o A A o A o \ o * o ' * o '
' \|/ . ' \|/ . |/|\/ /|\| |/|\ |/|\ \/|\| . \|/ ' . \|/ ' o
. | * . | * | | | | | | | | | | * | . * | . /|\
'./ \*. './ \*. / \ / \| |/ \ |/ \ / \ .*/ \.' .*/ \.' / \
---------------------------------------------------------------------------------
```
[Answer]
# C, 418 414 404
−10 bytes thanks to **ceilingcat**
Example input:
>
> stickwar.exe IVMMWWWS SWM
>
>
>
Example output:
```
. . .
.' *. .' *. .* '.
O ' O * ' O * O / O / O / O A A O \ O * O '
O /|\ ' \|/ . ' \|/ . |/|\/ |/|\/ |/|\/ /|\| |/|\ \/|\| . \|/ '
/|\ | . | * . | * | | | | | | | | | | | | * | .
/ \ / \ './ \*. './ \*. / \ / \ / \ / \| |/ \ / \ .*/ \'.
----------------------------------------------------------------------------------------
```
Golfed code:
```
char*s,d[8][999],*a;p,f,t,x,y,c,l;main(o,g)char**g;{for(memset(d,32,6993);o-=2,a=*++g;p+=3)for(;f=*a;t-4-o||strcpy(d[5]+p-1,"'."),p+=l&-o,f^*++a?p+=2:0)for(t=f%27%5,l=t*3%12%5+4,p+=l&o,y=6,s="(A(21;\0(A2:B(212;F\08A*B*0210KP\0-70A47/RT-A20G=CD?5D7_\0(A:(21;"+"V3'? "[t]-32;c=*s++;d[y][p+o*x]="/\\|O*'A."[c&7])x=c/16-2+(c&8?--y*0:x),c^=o-1&&!(c&6);for(y=!memset(d[6],45,p-=4);*(s=d[y++]);s[p]=0,puts(s));}
```
Maximal width of the battlefield is 999 (I could save 2 chars by limiting it to 99). I used a control structure of 1 byte per output character (non-space), drawing the figures from the bottom up.
* 1 bit for y-coordinate (either "stay" or "go up")
* 3 bits for x-coordinate displacement (0...4)
* 3 bits for output char (fortunately, there are only 8 different chars)
There are 5 offsets into the control structure.
Some other obscure bits:
* The code `f%27%5` translates the characters `VWSMI` to numbers `0, 1, 2, 3, 4`
* The code `t*3%12%5+4` calculates the width of the stickman of type `t`
* The code `t^3|~o||(s=d[5]+p,*s--=46,*s=39)` accounts for the left/right asymmetry
* I use the fact that `argc=3` to generate drawing direction flags `1` and `-1`
Ungolfed code:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char k[] = "(A(21;\0(A2:B(212;F\08A*B*0210KP\0-70A47/RT-A20G=CD?5D7_\0(A:(21;";
char d[8][999], // data of the battlefield
*s, // control string
*a; // cmdline argument
p, // position in the battlefield
f, // figure (char)
t, // type of the figure (0...4)
x,y, // coordinates while drawing the stickman
c; // control char, specifying what to draw
main(o, g) char**g; // o means "orientation" (+1, then -1)
{
freopen("out.txt", "w", stdout);
memset(d, ' ', 6993);
for (; o -= 2, a=*++g;)
{
for (; f=*a;)
{
t = f%27%5;
if (o<0)
p += t*3%12%5+4; // go to the next stickman
y = 6;
for (s=k+"V3'? "[t]-32; c = *s++;) // loop over the control
{
if (c & 8) // bit 3: next line; set x to 0
--y, x = 0;
x += c / 16 - 2; // bits 6...4: x coordinate
if (o == -1 && !(c & 6)) // mirror \ <-> /
c ^= 1;
d[y][p + o * x] = "/\\|O*'A."[c & 7];
}
if (t == 3 && o<0) // fix the asymmetrical mage
{
s=d[5]+p;
*s--='.';
*s='\'';
}
if (o>0)
p += t*3%12%5+4; // go to the next stickman
if (f != *++a) // is next stickman of different type?
p += 2;
}
p += 3; // separate the armies
}
p -= 4;
memset(d[6], '-', p); // draw the ground
for (y = 0; *(s=d[y++]); ) // print the battle field
{
s[p] = 0;
puts(s);
}
}
```
[Answer]
## Haskell, 556
### Input Format
```
([1,1,2,3,1],[0,1,1,0,1])
```
Order: [Infant, Villager, Mage, Swordsman, Spearman], [Spearman, Swordsman, Mage, Villager, Infant]
### Sample Output
```
. . .
.' *. .' *. .* '.
O ' O * ' O * O / O / O / O A \ O * O '
O /|\ ' \|/ . ' \|/ . |/|\/ |/|\/ |/|\/ /|\| \/|\| . \|/ ' O
/|\ | . | * . | * | | | | | | | | | | * | . /|\
/ \ / \ './ \*. './ \*. / \ / \ / \ / \| / \ .*/ \.' / \
------------------------------------------------------------------------------------------
```
### Code
```
(?)=replicate
v=reverse
g=map
e=length
s=foldr1
p=zip[3,3,8,6,4]$g lines[" O\n/|\\\n/ \\"," O\n/|\\\n |\n/ \\"," . \n .' *.\n ' O * \n' \\|/ .\n. | *\n'./ \\*."," O /\n|/|\\/\n| |\n / \\"," O A\n/|\\|\n | |\n/ \\|"]
r n x a=a++(n-e a)?x
x '\\'='/';x '/'='\\';x c=c
y(w,p)=(w,g(v.dropWhile(==' ').g x.r w ' ')p)
m n(a,p)(b,q)=(a+b+n,[r(a+n)' ' c++d|(c,d)<-zip(h p)(h q)])where h=v.r(max(e p)(e q))[].v
p%c|sum c==0=(0,[])|1<2=s(m 3)[s(m 1)$d?(p!!i)|(i,d)<-zip[0..]c,d>0]
f(w,p)=p++[w?'-']
main=interact((\(a,b)->unlines.f$m 8(p%a)((g y.v$p)%b)).read)
```
### Ungolfed
```
type Pic = (Int, [String])
pics :: [Pic]
pics = zip[3,3,8,6,4]$map lines[" O\n/|\\\n/ \\"," O\n/|\\\n |\n/ \\"," . \n .' *.\n ' O * \n' \\|/ .\n. | *\n'./ \\*."," O /\n|/|\\/\n| |\n / \\"," O A\n/|\\|\n | |\n/ \\|"]
mirrorChar '\\' = '/'
mirrorChar '/' = '\\'
mirrorChar c = c
padL, padR :: Int -> a -> [a] -> [a]
padL n x a = replicate (n - length a) x ++ a
padR n x a = a ++ replicate (n - length a) x
mirrorPic :: Pic -> Pic
mirrorPic (w, pic) = (w, map (reverse . dropWhile (==' ') . map mirrorChar . padR w ' ') pic)
merge n (w1, pic1) (w2, pic2) =
let h = max (length pic1) (length pic2)
in (w1 + n + w2, [padR (w1 + n) ' ' line1 ++ line2 | (line1, line2) <- zip (padL h [] pic1) (padL h [] pic2)])
makeArmy :: [Pic] -> [Int] -> Pic
makeArmy pics counts | sum counts == 0 = (0, []) | otherwise = foldr1 (merge 3) [ foldr1 (merge 1) . replicate count $ pics !! i | (i, count) <- zip [0..] counts, count > 0]
addField :: Pic -> [String]
addField (w, pic) = pic ++ [replicate w '-']
main = do
(counts1, counts2)<- return . read =<< getLine
putStr . unlines . addField $ merge 8 (makeArmy pics counts1) (makeArmy (map mirrorPic . reverse $ pics) counts2)
```
[Answer]
# Haskell (~~736~~ ~~733~~ 720 Bytes)
```
import System.Environment
import Data.List
a=1<2
h=" "
n=" "
o=" "
b (x:y)|x<0=[]|a=x:(b y)
c (x:y)|x>=0=c y|a=y
d [] _=[]
d (x:y)z|z/=x=[-5,x]++(d y x)|a=[x]++(d y x)
e x y|x< -5=" "|x<0=h|a=(([[h,h," . ",n,o],[h,h," .' *. ",n,o],[h," o "," ' O * "," O /"," O A"],[" o ","/|\\", "' \\|/ .","|/|\\/ ","/|\\|"],["/|\\"," | ",". | *","| | "," | |"],["/ \\","/ \\","'./ \\*."," / \\ ","/ \\|"]]!!(div z 5))!!(mod z 5))++" "where z=5*y+x
(§)=map
g=putStrLn
m=concat
main=do
z<-getArgs
let y=read§z::[Int]
let w=sort(b y)
let v=reverse(sort(c y))
let u=(\(t,i)->(\s->e s i)§t)§(zip(take 6(cycle[((d w (w!!0))++[-9]++(d v (v!!0)))]))[0..5])
mapM(\x->g(m x))u
g(replicate(length(m(u!!0)))'-')
```
Call with **./stickmanwars 2 3 1 3 4 -1 3 2 4 1 0 4 2 1**. The -1 marks the delimiter for the two arrays. I hope that is okay.
Well, my first code golf challenge and the first time I've used haskell for a real application after I learned it this semester at my university. Probably not even close to being the best or shortest solution but I had fun creating it and it was a good exercise :) Critique and feedback is highly appreciated.
Golfed it out of this:
```
import System.Environment
import Data.List
layers = [
[" ", " ", " . ", " ", " "],
[" ", " ", " .' *. ", " ", " "],
[" ", " o ", " ' O * ", " O /", " O A"],
[" o ", "/|\\", "' \\|/ .", "|/|\\/ ", "/|\\|"],
["/|\\"," | ", ". | *", "| | "," | |"],
["/ \\","/ \\", "'./ \\*.", " / \\ ","/ \\|"],
["¯¯¯", "¯¯¯", "¯¯¯¯¯¯¯", "¯¯¯¯¯¯", "¯¯¯¯"]]
getLeftSide :: [Int] -> [Int]
getLeftSide (x:xs) | x < 0 = []
| otherwise = x : (getLeftSide xs)
getRightSide :: [Int] -> [Int]
getRightSide (x:xs) | x >= 0 = getRightSide xs
| otherwise = xs
addSpacing :: [Int] -> Int -> [Int]
addSpacing [] _ = []
addSpacing (x:xs) old | old /= x = [(-50),x] ++ (addSpacing xs x)
| otherwise = [x] ++ (addSpacing xs x)
getLayerStr :: Int -> Int -> String
getLayerStr item dimension | item < (-50) = " "
getLayerStr item dimension | item < 0 = " "
| otherwise = ((layers !! i) !! j) ++ " "
where
value = (item + (5 * dimension))
i = div value 5
j = mod value 5
main = do
-- Read Arguments from command line
a <- getArgs
-- Convert command line arguments to Int array
let args = map read a :: [Int]
-- Get left side of the array and sort it
let frstArray = sort $ getLeftSide args
-- Get right side of the array and sort it mirrored
let scndArray = reverse $ sort $ getRightSide args
-- Concat the two sides and put a delimiter in between them
let finalArray = (addSpacing frstArray (frstArray !! 0)) ++ [-99] ++ (addSpacing scndArray (scndArray !! 0))
-- Create the matrix by
-- 1. Duplicating the final array 6 times (one for each level)
-- 2. Pair each of those 6 arrays with its level (= index)
-- 3. Create a matrix like below:
--
-- 1 1 2 2 3 4 4 5 - 1 1 2 2 2 4
-- 6 6 7 7 8 9 9 10 - 6 6 7 7 7 9
-- 11 11 12 12 13 14 14 15 - 11 11 12 12 12 14
-- 16 16 17 17 18 19 19 20 - 16 16 17 17 17 19
-- 21 21 22 22 23 24 24 25 - 21 21 22 22 22 24
-- 26 26 27 27 28 29 29 20 - 26 26 27 27 27 29
--
-- 4. Convert the newly calculated indices to their respective strings
let matrix = map (\(list,i) -> map (\item -> getLayerStr item i) list) (zip (take 6 $ cycle [finalArray]) [0..5])
-- Finaly output the matrix by concating the elements ...
mapM (\x -> putStrLn (concat x)) matrix
-- ... and print the ground level.
putStrLn (replicate (length $ concat $ matrix !! 0) '¯')
-- Exit with a new line
putStrLn ""
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 120 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
εU•1ĆÊLî˜₅ÉÈ«-—gí"Mª§ÚÇGäÒ²ĀÛNYE™Eæ]Ç€Š–ôTú™<C₄+i*∍.[½P•"
|/\.O*'0A"ÅвJ0¡ε.B€S¸XNèиJøðý€S}õζJð3×ýNiεº2äθðÜ]øð8×ý¤'-s∍ª»
```
Input is similar as in the example, except it's paired together (i.e. `[[1,1,2,3,1],[0,0,1,1,1]]`).
[Try it online.](https://tio.run/##yy9OTMpM/f//3NbQRw2LDI@0He7yObzu9JxHTa2HOw93HFqt@6hhSvrhtUq@h1YdWn541uF298NLDk86tOlIw@HZfpGuj1oWuR5eFnu4/VHTmqMLHjVMPrwl5PAuoKiN86OmFu1MrUcdvXrRh/YGAE1XUuCq0Y/R89dSN3BUOtx6YZOXwaGF57bqOQH1Bh/aEeF3eMWFHV6HdxzecHgvSKj28NZz27wObzA@PP3wXr/Mc1sP7TI6vOQcSH5OLEiZBUji0BJ13WKgLUD37f7/PzraUMdQx0jHWMcwVifaQMdAB8Q3jI39r6ubl6@bk1hVCQA)
**Explanation:**
```
ε # Map both inner lists of the (implicit) input to:
U # Pop and store the list in variable `X`
•1ĆÊLî˜₅ÉÈ«-—gí"Mª§ÚÇGäÒ²ĀÛNYE™Eæ]Ç€Š–ôTú™<C₄+i*∍.[½P•
"# Push compressed integer 842496640498468305486897242730433696271358810529289612091214532817389449608887173562606281130145674459118763657187307135640
"
|/\.O*'0A" # Push string " \n|/\.O*'0A"
Åв # Convert the integer to this custom base-" \n|/\.O*'0A",
# (short for converting it to base-length and indexing each into the string)
J # Join this list of characters together to a single string
0¡ # And split it on "0"s
```
We now have a list of stick figures. [I've generated the stick figures string with this program](https://tio.run/##PY2xCsJAEET7/YohTSDFnfgDolipEIhtGgWRVBZpTwhCelshhSaVECwsxEaFO2yD33A/EvcUbWaZndm3q3Q2TxZtq49ma3bT4XOvS3Ntqua6juymft10rU@pyXvJsKuriPNxaur1SB@f90lks4M@Lc3FbvIB1zyblebBYrPCzcLkr/OobT3PIyKEJFVMEnHnb6A@HoAAQfgIBMFHiIB8xEpCkAAUnBfcDIS75RySFANYGYEfE31H5YX6ghV/fgM), which is a slightly modified version of [this 05AB1E tip](https://codegolf.stackexchange.com/a/120966/52210).
```
ε # Map each stick figure to:
.B # Box it (split on newlines, and append spaces to make all lines of equal length)
€S # Convert each line to a list of characters
¸ # Wrap the entire thing into a list
X # Push input-sublist `X`
Nè # Index the map-index into it
и # Repeat the stick figure that many times as list
J # Join each innermost list of characters together to a string
ø # Zip/transpose; swapping rows/columns
ðý # Join each line with a single space delimiter
€S # And convert each line back to a character list again
} # After the inner map:
ζ # Zip/transpose the list of stick figures,
õ # with an empty string as filler (in case the input contained a 0)
J # Join each inner list together to a string
ð3×ý # Join each line with 3 spaces as delimiter
Ni # If the map-index is 1 (thus the left army):
ε # Map each line to:
º # Mirror-reflect the line
2ä # Split it into 2 equal-sized parts
θ # Pop and only leave the last (mirrored) part
ðÜ # Remove any trailing spaces
# (necessary if the amount of infants in the left army is 0)
] # Close all maps and if-statements
ø # Zip/transpose; swapping rows/columns
ð8×ý # Join each line together with 8 spaces as delimiter
¤ # Push the last line (without popping the list itself)
'- '# Push string "-"
s # Swap so the last line is at the top of the stack
∍ # Extend the "-" to a length equal to that line
ª # Append it to the list
» # And join the lines by newlines
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•1ĆÊLî˜₅ÉÈ«-—gí"Mª§ÚÇGäÒ²ĀÛNYE™Eæ]Ç€Š–ôTú™<C₄+i*∍.[½P•` is `842496640498468305486897242730433696271358810529289612091214532817389449608887173562606281130145674459118763657187307135640`.
[Answer]
# Haskell, 450
```
import Data.List
s=[" -"]
c=[" //-":" O| -":" \\\\-":s," / /-":" O|| -":" \\ \\-":s," '.'-":" .' .-":" ' \\ /-":". O|| -":" * / \\-":" .* *-":" .*.-":s," || -":" / /-":" O|| -":" \\ \\-":" / -":" / -":s," / /-":" O|| -":" \\ \\-":" A|||-":s]
m '\\'='/'
m '/'='\\'
m x=x
u[]=[]
u x=x++[s,s]
f x=zipWith replicate x c>>=concat.u
k(a,b)=unlines.transpose$f a++s++s++map(map$m)(reverse$f b)
main=interact$k.read
```
Cool challenge! I might be able to golf that down a bit more.
Basically I'm storing the figures column wise so I can append them to each other easily, and then flip the whole array of `String`s arround using Haskell's `transpose`.
The input format is `([Infants,Villagers,Mages,Swordsmen,Spearmen],[Infants,Villagers,Mages,Swordsmen,Spearmen])`
Here is the example from the OP:
```
>>>echo ([1,1,2,3,1],[0,0,1,1,1]) | cg2
. . .
.' *. .' *. .* '.
O ' O * ' O * O / O / O / O A A O \ O * O '
O /|\ ' \|/ . ' \|/ . |/|\/ |/|\/ |/|\/ /|\| |/|\ \/|\| . \|/ '
/|\ | . | * . | * | | | | | | | | | | | | * | .
/ \ / \ './ \*. './ \*. / \ / \ / \ / \| |/ \ / \ .*/ \.'
----------------------------------------------------------------------------------------
```
And here is my favourite depiction of the infamous ritual infanticide during the second era!
```
>>>echo ([0,0,0,1,0],[5,0,0,0,0]) | cg2
O /
|/|\/ O O O O O
| | /|\ /|\ /|\ /|\ /|\
/ \ / \ / \ / \ / \ / \
---------------------------------
```
[Answer]
# Python (~~612~~,~~522~~,~~460~~,440)
* Rev1: Rudimentary compression and base64-encoding
* Rev2: Removed compression/encoding; got smaller
* Rev3: More byte count reduction by inlining
* Rev4: Removed unneeded input reversal on 2nd army; swapped swordsman and spearman to match spec
Each "line" is trimmed of right-padding, and this is added back in when reconstructing.
I pre-reversed the stickmen in my internal encoding because it saved me having to reverse them individually when rendering them in the code.
Sample run:
```
$ echo "[1,1,2,3,1],[0,0,1,1,1]"|python /tmp/g2.py
. . .
.' *. .' *. .* '.
O ' O * ' O * O / O / O / O A A O \ O * O '
O /|\ ' \|/ . ' \|/ . |/|\/ |/|\/ |/|\/ /|\| |/|\ \/|\| . \|/ '
/|\ | . | * . | * | | | | | | | | | | | | * | .
/ \ / \ './ \*. './ \*. / \ / \ / \ / \| |/ \ / \ .*/ \.'
----------------------------------------------------------------------------------------
```
Code:
```
c=",,A O,|/|\\,| |,|/ \\,,,\\ O, \\/|\\|, | |, / \\, . , .* '., * O ',. \\|/ ',* | .,.*/ \\.',,, O,/|\\, |,/ \\,,,, O,/|\\,/ \\".split(',')
r=['']*6
for b in input():
for e,f in '/$ \\/ $\\'.split():r=[x.replace(e,f)[::-1] for x in r]
if r[0]:r=[x+' ' for x in r]
for n,a in enumerate(b[::-1]):
m=c[n*6:n*6+6]
if a:r=[x+' '+(' '.join([y.ljust(max(map(len,m)))]*a)) for x,y in zip(r,m)]
print '\n'.join(r+['-'*len(r[0])])
```
[Answer]
# Python (476)
A different solver from my previous one; longer, but more functional.
```
$ echo "[1,1,2,3,1],[0,0,1,1,1]"|python g3.py
. . .
.' *. .' *. .* '.
O ' O * ' O * O / O / O / O A A O \ O * O '
O /|\ ' \|/ . ' \|/ . |/|\/ |/|\/ |/|\/ /|\| |/|\ \/|\| . \|/ '
/|\ | . | * . | * | | | | | | | | | | | | * | .
/ \ / \ './ \*. './ \*. / \ / \ / \ / \| |/ \ / \ .*/ \.'
----------------------------------------------------------------------------------------
```
Code:
```
c=",,A O,|L|R,| |,|L R,,,R O, RL|R|, | |, L R, . , .* '., * O ',. R|L ',* | .,.*L R.',,, O,L|R, |,L R,,,, O,L|R,L R".split(',')+['']*12
s=[sum([[4-n,5]*a+[6] for n,a in enumerate(b) if a]+[[5]],[])[::-1] for b in input()]
t=[[''.join([c[a*6+n].ljust([4,6,7,3,3,1,2][a]) for a in x]) for x in s] for n in range(0,6)]
for d,e,f in 'RL/ LR\\'.split():t=[[x[0].replace(d,f),x[1].replace(e,f)] for x in t]
t=[x[0][::-1]+x[1] for x in t]
print '\n'.join(t+['-'*len(t[0])])
```
] |
[Question]
[
In Minecraft, pistons are blocks that can move other blocks. However, they can only move at most twelve blocks, and won't work at all if any obsidian is in the way. Also, slime blocks are sticky and stick to other blocks, except for obsidian.
# Your challenge
Take as input a 5x5 matrix or similar, containing one piston at the bottom, and output the result of the single piston pushing upwards, as 5x6. Input format should have five distinct values for obsidian, slime, other block, piston and empty space, here represented by `O`, `S`,`B`,`P`, and respectively.
For example, say you start with
```
B
B
B
B
P
```
Output the result, if the piston was activated, as 5x6:
```
B
B
B
B
P
```
Note that the whole configuration with the piston is moved up, as long as it is legal
# Testcases:
```
BBBBB
BBBBB
SSSSS
S
P
=>
BBBBB
BBBBB
SSSSS
S
P
Because 16 is too many blocks.
SBS
SBS
SBS
SBS
P
=>
B
SBS
SBS
SBS
SPS
Because slime sticks to blocks, but blocks don't stick to slime.
O
SSSSS
S
S
P
=>
O
SSSSS
S
S
P
Because the obsidian is in the way, the whole thing can't move.
S S S
S S S
S P S
=>
S S S
S S S
P
S S
The stray blocks stay where they are.
SSSSS
B S B
B S B
B S B
B P B
=>
SSSSS
B S B
S
B S B
B P B
B B
The slime pulls the first two blocks, but the rest stay in place.
OSO
OSO
OSO
OSO
OPO
=>
S
OSO
OSO
OSO
OPO
O O
Slime doesn't stick to obsidian, so it's free to move.
```
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shorter the better!
[Answer]
# [J](http://jsoftware.com/), 121 98 bytes
Takes in `POSB` as digits `01234`. Probably some microgolfs left, these long tacit definitions tend to get confusing. :-)
```
((0,~*)+0,(*-.))[(]*(2 e.*&,)<14>+/@,@])[(]*@+(2&<@[*[:+/((,-)=i.2)t]*3=[)+*@[*1(t=:|.!.0)])^:_=&1
```
[Try it online!](https://tio.run/##bY4xb8MgEIV3fsW1A3AYE9vtREJlUalTJVAZkZvBSuJ06ZKx6l93z0mrSgkn8XHi3jvex3xvxB6cBQEaGrB0agPPb68vs5SN/lZYNVqq2iBmOSjZwc4ornHTPj5Vq173w/m9r2THN31W2VYrKXWN7mg6PA3qwWWsFE1aeXL2y9yZBgd8t1vH2xkZG50VEEPygh8NO1CSPTcjm6jJFqQAwfX6gJDXZtsxthunT5hAnqMi8wDgWSImlpZiIcQQGN4ql/rlRUke8tEVibcGSD5BiRAL6gDLrr/FS5x/lvSJPr9M4aqP1Bf0582elP6KkVhIH1KAIiMR5x8 "J – Try It Online")
### How it works
* `=&1` Start a will-be-pushed bitmap with the piston
* `^:_` expand the bitmap until it does not expand further:
* `1(t=:|.!.0)]` Push the bitmap upwards (non-wrapping, thus `!.0`)
* `*@[*` but only if a non-space was pushed.
* `t]*3=[` Extend push of the will-be-pushed slimes towards
* `((,-)=i.2)` all 4 direction
* `2&<@[*[:+` but only push slimes and blocks.
* `]*@+…+` OR old bitmap, slime pushes, and up pushes for the next iteration.
* `[(]*…)` Set the final bitmap to 0 if …
* `(2 e.#~&,)` There is an obsidian block in it
* `<14>+/@,@]` or the sum (including the piston) is not less 14.
* `0,(*-.)` Original map \* not-pushed bitmap and an empty row above.
* `(0,~*)` Original map \* pushed bitmap and an empty row under.
* `+` Add both maps – as empty spaces are 0 they don't overlap.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~144~~ 120 bytes
```
WS⊞υι≔⪫υ¶θPθ…θ⌕θP≔⟦⟦ⅈⅉ⟧⟧ηFη«J§ι⁰⊖§ι¹F‹@KK⊞η⟦ⅈⅉ⟧↓F⁼SKKF³«M✳⊗⁺²λF№⪪BS¹KK⊞η⟦ⅈⅉ⟧M✳⊗λ» »Fη«J§ι⁰⁻§ι¹›‹Lη¹⁴⊙η⁼O§§υ§ι¹§ι⁰§§υ⊟ι⊟ι
```
[Try it online!](https://tio.run/##hVLPT8IwGD2zv6Lp6WtSE1BPcpExNRAIS@ZBgxxwVNZY2rG1IDH87bNdmUCioYe234/3@r6Xptm8SNVcVNU244IhGMjc6EQXXC6BEBSbMgNDESfdoFeWfClhqLh0KfwmMaFobStjIzTPLUaDC@P61t@lgvUzlcOaokcuF@7EMSbkyDWdvoDleAUym1GU2cKHKhBkBH0HraFZ5c8KenogF@wLOEVt2xuxtGArJjVbnJY6NW2rho9YWQK@xxTFjH3aMQ5zZBQd33PdY7VhcBeprfzFPqzNXFh0coquKze1KI@JeMFSzZWESJl3YaXEwpRwTZEgXohn6ytjnUhywTXg0HF2yEVV/z0hPPM@aHmDMcI23l@2bMylFXdmFkVPBZtrVnizRkwutZVi851bu/XkzulqzJhY4Q28Oc0x5e0/i9vEr24j9g94bL8Gd7jDxQ1TVYlbQThJJuH5jmIUBtXVRvwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
WS⊞υι
```
Input the layout. (I've decided to take input as newline-terminated lines; this allows you to experiment with layouts of different numbers of lines if you so wish.)
```
≔⪫υ¶θPθ…θ⌕θP
```
Output the layout and move the cursor to the position of the piston.
```
≔⟦⟦ⅈⅉ⟧⟧ηFη«
```
Perform a breadth-first search starting with the position of the piston.
```
J§ι⁰⊖§ι¹
```
Jump to the square above the current position.
```
F‹@KK⊞η⟦ⅈⅉ⟧
```
Add this position to the list unless it's empty.
```
↓F⁼SKKF³«
```
If the current position is a sticky block, then check the other three sides too.
```
M✳⊗⁺²λF№⪪BS¹KK⊞η⟦ⅈⅉ⟧M✳⊗λ
```
If there is a (sticky) block on that side then add this position to the list.
```
» »
```
Erase the block, assuming it will be moved. This also avoids considering the same block twice.
```
Fη«
```
Loop over each block.
```
J§ι⁰⁻§ι¹›‹Lη¹⁴⊙η⁼O§§υ§ι¹§ι⁰
```
Jump to its old or new position depending on whether there weren't too many blocks to push or any obsidian in the way.
```
§§υ⊟ι⊟ι
```
Print the block.
] |
[Question]
[
# I see your BIDMAS and raise you a BADMIS
## Challenge
Given a set of numbers with operators between them: "5 + 4 \* 9 / 3 - 8", return all the possible results of the expression for every permutation of the order of basic operations: [/, \*, +, -].
## Rules
* Standard loopholes forbidden
* I/O
+ Input must be ordered with infix operations, but however that is easiest (string or array)
+ You are not required to support unary operators (e.g. "-3 \* 8 / +2")
+ Integers can be replaced by floats for languages that implicitly parse type (e.g. 45 ⟶ 45.0)
+ Output must be all of the possible results of the expression, no specified format or order
* All of the inputs are valid (e.g. do not need to deal with "7 / 3 + \*"). This also means that you will never need to divide by zero.
* Operators are all left-associative so "20 / 4 / 2" = "(20 / 4) / 2"
* This is Code Golf so fewest number of bytes wins
## Test Cases (With explanation)
* "2 + 3 \* 4" = [14, 20]
+ 2 + (3 \* 4) ⟶ 2 + (12) ⟶ 14
+ (2 + 3) \* 4 ⟶ (5) \* 4 ⟶ 20
* "18 / 3 \* 2 - 1" = [11, 2, 6]
+ ((18 / 3) \* 2) - 1 ⟶ ((6) \* 2) - 1 ⟶ (12) - 1 ⟶ 11
+ (18 / 3) \* (2 - 1) ⟶ (6) \* (1) ⟶ 6
+ (18 / (3 \* 2)) - 1 ⟶ (18 / (6)) - 1 ⟶ (3) - 1 ⟶ 2
+ 18 / (3 \* (2 - 1)) ⟶ 18 / (3 \* (1)) ⟶ 6
+ 18 / ((3 \* 2) - 1) ⟶ 18 / 5 ⟶ 3.6
## Test Cases (Without explanation)
* "45 / 8 + 19 / 45 \* 3" = [6.891666666666667, 18.141666666666666, 0.11111111111111113, 0.01234567901234568, 0.01234567901234568, 5.765740740740741]
* "2 + 6 \* 7 \* 2 + 6 / 4" = [112 196 23 87.5]
[Answer]
# [JavaScript (V8)](https://v8.dev/), ~~118~~ 112 bytes
Prints the results.
```
f=(s,x='',y=x,o='+-*/')=>[...o].map(v=>f(s.split(v).join(x+v+y),x+')',y+'(',o.replace(v,'')))|print(eval(y+s+x))
```
[Try it online!](https://tio.run/##TYzRioMwEEXf@xWDL5kxMaLtdl2W@COlD6EoWGwNJoTI7n67m9hS@jLcOXPnXLXX9jIPxhW@WddeoRVBMSYWFcSkGC/ykpFqT1LK6Sxv2qBXbY9WWjMODj3J6zTcMXDPFxKBM4q/nCETk5w7M@pLh14wRkS/Zh7uDjuvR1y45YFodZ11oMCCauEHHgVL39Bv87HH8LfbpSZmNXDYQw6HjJ6kaqDcUA0FVC98@Ii4ie3qK4a45bB/HZPlGMnn9pZy@WasUzfKjvGSpEmQ2smWrBvLaP0H "JavaScript (V8) – Try It Online")
Or [see the deduplicated results](https://tio.run/##TY7LbsMgEEX3@YpRNkAgRHk0TVsRqd/gZdsFsklF5BgLKMV9fLs7WFHUFcy5d47mrJMOtbd9XKbDOJ4UDSIrQsSgsnCK8OViRZg6vkgp3Zu86J4mdTzRIEPf2kgTk2dnO5p54gMTmROGu5xQIpz0pm91bWgShDDGfnpvu0hN0i0deOCZsTGaEEFBAHWE7xlAhUNnPqEy8QnHaQNRLnklddPQzEqAF0xv7brgWiNb904rGeyXAQ4EGhui7eoI3oSPNobH145g8Oy9HuTJuwutrocTAYSVHWyg8Xc2KyfR@QbZFhawm7MrWR9gNaENLGF9w7s7xAdsrx/wg9MCtrewWPZI7qe18l/9M25KF2V7TIq0CEq72Ip1YnM2/gE).
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 285 bytes
```
x=>{int c=0,j,t=1,i;for(;c++<25;t=c){var r="*+-/".ToList();for(i=j=1;j++<4;t=t/j+1)(r[j-1],r[t%j])=(r[t%j],r[j-1]);float k(float z,int p=4){char d;int l;float m;return i<x.Count&&(l=r.IndexOf(d=x[i][0]))<p?k((m=k(x[(i+=2)-1],l))*0+d<43?z*m:d<44?z+m:d<46?z-m:z/m,p):z;}Print(k(x[0]));}}
```
[Try it online!](https://tio.run/##lVZtT@M4EP5MfsUI6bZJm7a0dLk92oDQ3n1AQjq0i7QfKj64iUvdOnFkO1Ba9bdzM05fUra8XATCGY@fmXlmHofYNGMjXq5iK1Q2uBHGDpLnjKUivrgYRy/z6GIpMgtxdBJOQxt1QtEfK@3340Zj0P3at1EcLB@ZBh0d1xvN9nHrThGIHzg3EU2jTn@Kvj10te1poxP4ejhtdu5DPbR/TO@DyC8XYWnGc1IxCzO//LsIKXwe9YJlPME4SZ/e5dor7WtuC52BGMxb31WR2S9ffBnp1nWW8Pm/Yz@J5kNxPzy5D4JBfjnz/TSa@fOhLxpRN6AsZBDUTxrJoHd6uain57joXS4abnF2uWim54t2GubB@aK/utUY2qfjBNdfrV76nveoRAKWY8XG4v4DiCwvbABL74hokcgFRJDxJ9jjFvnxjpAhzuKJT44MD5ZnWz9zKZBAh3EkxlAy0brTz7dMG@6zEFRhoWRgtPY7okitqyTxRwR9tMJfLg2HrZ2RHc2/tLD8RmTcL1PtA2bik5tb7rbpdeV5rrjjLjTgFOrQO0aY0tT5Bm1n60ITOjt77yvav6F/5y9c4FsdTne7BHSGpj/dQVq3q6Bd8ka8M9wiXIIgd8IjXGdD9xfAh6YTPv202zcsHSUMLJuVnULW97rilY6vB/590CsYFVk8ATWGhMuYaUZSMjBlacpxNtQDtxOucQGGPXIYPWOl60i/Sen99JXKodsDK1JuwGcpDTzFzblOC7uOy8BwZ5U8e7AT6EHMMphg6MDbYK0V227UmxXFHo56nQkrmBQLDjimphxphFcYlVmlzRb1LcUfxv2Ow285IDdwh2lWagiJKOqQ5qaQlhqlQ2DSKLJgcYLI7Hg7tI/ulF2Kb1wusPw9wb/5GGUAUsVMwhh7TLlBbVYL4UlgxgtiIy605gjyyGTBgcVxkTKJdSXAsgTyqkuuecwTnsW8kvnBS@0gXz9VymHCJRJF/RNsJLmpIL2@Cd@eo@sxsi4M4E@mrOuAZNjUrEhHXHtV53ev0wokwBWWS0ibajfjUTOVwinkRDw4OUxwKqsHDtIz8z@rbYAfHKGMQIlhw2TZIwqwbQptrftk9qo89FU4HIPqVE7O@o1oGZ9vmERBSKmeaJIPMUOzYThOissp9OB/P5uMkl3kw7RjJPKoWMqYbkgNupMOmVPaZrSgltb2Uvr4M7mfUqI2hbM81ypHWJR7mR8JCSWcuvj7EvJri1qwFzgPPsvFLTNmfbN/MFn4Pf80x//QZ3RaoEDWEqtiv9LMart69d/CuxGcr4Nd33h4vdJUUS2z3WiNhd6q1A2PZdqSj2POq2aw@g8 "C# (Visual C# Interactive Compiler) – Try It Online")
```
x=>{ //Lambda taking in a List<dynamic>
int c=0,j,t=1,i; //A bunch of delcarations jammed together to save bytes
for(;c++<25;t=c){ //Loop 24 times (amount of permutations a set of length 4 can have)
var r="/+*-".ToList(); //Initialize r as list of operators
for(i=j=1;j++<4;t=t/j+1) //Create the Tth permutation, saving result in r, also reset i to 1
(r[j-1],r[t%j])=(r[t%j],r[j-1]);
float k(float z,int p=4) { //Define local function 'k', with z as current value accumalated and p as current precedence
char d;int l;float m; //Some helper variables
return i<x.Count //If this is not the last number
&&(l=r.IndexOf(d=x[i][0]))<p? // And the current operator's precedence is higher than the current precedence
k( // Recursive call with the accumalative value as
(m=k(x[(i+=2)-1],l)) // Another recursive call with the next number following the current operator as seed value,
// And the next operator's precedence as the precedence value, and store that in variable 'm'
*0+d<43?z*m:d<44?z+m:d<46?z-m:z/m, // And doing the appropriate operation to m and current value ('z')
p) // Passing in the current precedence
:z; //Else just return the current number
}
Print(k(x[0])); //Print the result of calling k with the first number as starting value
}
}
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 132 bytes
```
a=>(w=[],F=(b,a)=>b?[...b].map(q=>F(b.replace(q,""),a.replace(eval(`/[\\d.-]+( \\${q} [\\d.-]+)+/g`),eval))):w.push(a))("+-*/",a)&&w
```
[Try it online!](https://tio.run/##bY3LboMwEEX3/YqRVUUzYGwR0uYhme7yE4CUgThpIhIgtGFR9dupHaldVOzmzrm658x37qvbqf2Irs3ejgczsklxMFkhtwZLyWTS8i1TSpWFunCLnUm3WKqbbWuuLHZSCJL8l@2da9zpLM/3KipChDx//uq@4fdBoT7uSPoaEW0G1X7278hEKMIo0MIJZ7NhrJpr39RW1c0RDyjmEEICASwE0dM/Fq9AP@AcIognCosXV1i5hXjtDpcCSCZq3vHq2PIx5W896fOaxHHPxh8 "JavaScript (Node.js) – Try It Online")
This allows duplicated outputs.
# [JavaScript (Node.js)](https://nodejs.org), ~~165~~ ~~161~~ ~~155~~ ~~153~~ ~~152~~ 137 bytes
```
a=>Object.keys((F=(b,a)=>b?[...b].map(q=>F(b.replace(q,""),a.replace(eval(`/[\\d.-]+( \\${q} [\\d.-]+)+/g`),eval))):F[a]=1)("+-*/",a)&&F)
```
[Try it online!](https://tio.run/##bY3dasJAEIXv@xTDUmQmP7vEaGsLG@9y2wdIAs7GVarRJEYEKX32dFdoL0ru5sx3ON@BbzzUl8/uGp/brR13emSdfZiDra/yaO8DYq7RREw6M@tCSmkqeeIOe53laOTFdg3XFvtICIr4L9sbN7hRRVluZVyFCGX5/NV/w@@DQrXfUORrRPSeF1zphFCEcaCEs81mOY11ex7axsqm3eMOxRxCSCGAhSB6@seSFagHnEMMyURhsXSFlVtI3tzhUgDpRM07Xhx7fUz5W036vCZ13LPxBw "JavaScript (Node.js) – Try It Online")
Takes a string with spaces between operators and numbers.
```
a=> // Main function:
Object.keys( // Return the keys of the -
(
F=( // Index container (helper function):
b, // Operators
a // The expression
)=>
b // If there are operators left:
?[...b].map( // For each operator:
q=>
F( // Recur the helper function -
b.replace(q,""), // With the operator deleted
a.replace( // And all -
eval(`/[\\d.-]+( \\${q} [\\d.-]+)+/g`), // Expressions using the operator
eval // Replaced with the evaluated result
)
)
)
:F[a]=1 // Otherwise - set the result flag.
)(
"+-*/", // Starting with the four operators
a // And the expression
)
&&F
)
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~92 90~~ 88 bytes
```
{map {[o](@_)($_)},<* / + ->>>.&{$^a;&{S:g{[\-?<[\d.]>+]+%"$a "}=$/.EVAL}}.permutations}
```
[Try it online!](https://tio.run/##JY3NCoJAAITvPsUQJrmbu2hqVmZ16NYt6KImC2kI/qF1iGWf3ZIuw/AxH9PlfeWP9QdGgT1GWYsOMm7TxTEzF3pmqmVIwEFhRVHEDKnfxc6Q1@1Txol1COPkwdKIpnQ@0wVmaq9zdr6dLkqxLu/r90u8yrYZ1DiID9jvo2h7VGWTD6NtwaFYaVMQuJod8Kk4FmzN9TgCCnvD4XrkP/IJ1mRS/B/8Ag "Perl 6 – Try It Online")
Takes a string with a space after any operators and returns a set of numbers. This mostly works by substituting all instances of `n op n` with the eval'ed result for all permutations of the operators.
### Explanation:
```
{ } # Anonymous code block
<* / + ->>>.&{ } # Map the operators to:
$^a;&{ } # Functions that:
S:g{ } # Substitute all matches of:
\-?<[\d.]>+]+ # Numbers
%$a # Joined by the operator
=$/.EVAL # With the match EVAL'd
map { }, .permutations # Map each of the permutations of these operators
[o](@_) # Join the functions
($_) # And apply it to the input
```
[Answer]
# [Python 3](https://docs.python.org/3/), 108 bytes
```
f=lambda e,s={*"+-*/"}:[str(eval(p.join(g)))for p in s for g in zip(*map(f,e.split(p),[s-{p}]*len(e)))]or[e]
```
[Try it online!](https://tio.run/##RVBNb@MgEL37V4x8ApeQ4O9E8qFa9bCn/QGutaIJbl05gAzZtmvlt2cHUmkRh8fMe2@GZ7/8m9HF7TZ2szy/nCQo5ro1Sx822Ta9HnrnF6L@yJlY/m4mTV4ppaNZwMKkwUGArwH@nSzJztKSkSnu7Dx5Yinr3Wa11yGblSYKlYNZejXcvHL@91E65aCDPiFpDg9QQAZlyqAXJYN8N1CGDdHCNnZy2IAI3ZxBwWsGeIW4k8oKSS1aiD0CfGVQBOqO70RelFXd7AWDHRffBy0q3tRVU2K55u1e1HUdsGi5KOPjbhzWqtGtiQsEvL2vmBcM2oZXYQd0E/t6oMmQJNPZmsWDvpztF0gH2iZJiMhYx0B9xtD@f/6QAB5z8ZiCQ506kZjgbKRnTnkyEhRibDQSpXMKzUOWqKHQdRGjLQWpTziMy3k@zsapQIgDKYMxfdY/tb34QzBZ0fH6rH9d/HdlRSoWnj6tOuIGB1hRhoU0zrTLpD1Jf5hlwTY8avehlpTe/gE "Python 3 – Try It Online")
The function takes a single string as input and returns a list of possible results.
# Ungolfed
```
def get_all_eval_results(expr, operators={*"+-*/"}):
results = []
for operator in operators:
remaining_operators = operators - {operator}
# Split expression with the current operator and recursively evaluate each subexpression with remaining operators
sub_expr_results = (get_all_eval_results(sub_expr, remaining_operators) for sub_expr in expr.split(operator))
for result_group in zip(*sub_expr_results): # Iterate over each group of subexpression evaluation outcomes
expr_to_eval = operator.join(result_group) # Join subexpression outcomes with current operator
results.append(str(eval(expr_to_eval))) # Evaluate and append outcome to result list of expr
return results or [expr] # If results is empty (no operators), return [expr]
```
[Try it online!](https://tio.run/##bVRNb9swDL37VxDeRUpdN86HkxTIYRh66C477JgGhucojQdHEiS5bRb0t2ek/NUGNQpUpt575CPp6JM7KDm9XHZiD8/CZXlVZeIlrzIjbF05y8SbNhEoLUzulLHr8yi8uR3dhe/8PgB8WhysYbP1gb0yPRxKOVAbfMM55qUs5XPWXyJ/ON/CuXt5D3rWN/itq9IBVSSsLZWE19IdwB0EFLUxQrohcS53mAbDtnwR1QnIU507ASIvDmDrP9cqfU1DHX1mhGeEzwaz7MtmdcDoK4vct6aDUGvof2zJFOtQnA@GCd4oZ89G1Zoo/0rNRtf18HvfnkdHGgLUizCNz4am9leG22bQUdWuUEcxeKXHazvlvX0YTPxXlZJ9rIhT2p8YvUrQqTatvR7Op1ythTjXWsgds84wSss@1sA59wYfuiHSdBtClwqcaqWgKq0jz6TQrqirjew3Fbu6obut79m@j5cWxFG7EzCphiXgUcdvSBcnrMuK3Aq/8wELJ3ADUxjBLIxgk8wimIy3PMKLZAl3/maCG53Q7SSCaZxGgH9J0oBmcwQtUSJZ4QHfRjAl6DgeJ5PpbJ4uVkkE4zhpH5SYx4t0vphhOI2XqyRNUzonyziZ@ZdGmMpKUW3hC6DzXVPiZBrBchHPqQZUS1bplgfbICiPWhkHsj7qE@QWpA6C5mO2ETWT1m8w33zN2H3sgkWe2LFjrtm@UrmLrHBffyCohcPknptbKzBfJSRDGQ7rtT9jJu4HLHWM/KJSVhDA14DT2IdP8lHq2tHS0w@FfX@Sv2rXRs4IxcDDmxYFFnUPZ6RhIPQ5tSmlY@EPhRtZOPgu7aswIb/8Bw "Python 3 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 30 bytes
```
œṡ⁹¹jṪḢƭ€jŒVɗßʋFL’$?
Ḋm2QŒ!烀
```
[Try it online!](https://tio.run/##y0rNyan8///o5Ic7Fz5q3HloZ9bDnase7lh0bO2jpjVZRyeFnZx@eP6pbjefRw0zVey5Hu7oyjUKPDpJ8fDyY5OAKv5bP2qYo6Brp/CoYa714fajkx7unKHC5Xa4XQUoGfn/fzRXtKGOkraSjpGOkpaSjnGsDle0iamOkr6SjgVY3NASzAGJweSNwBJmYAFzMAkXAamM5YoFAA "Jelly – Try It Online")
A pair of links. The second one is the main link, and takes as its argument a Jelly list of floats/integers interspersed with the operators as characters. This is a flattened version of the way Jelly takes its input when run as a full program with command line arguments. The return value of the link is a list of list of single member lists, each of which is a possible value for the expression.
## Explanation
### Helper link
Takes a list of floats/integers alternating with operators (as characters) as its left argument and an operator as a character as its right argument; returns the input list after evaluating numbers separated by the relevant operator, working left to right.
```
œṡ⁹ | Split once by the right argument (the operator currently being processed)
? | If:
$ | - Following as a monad
L | - Length
’ | - Decremented by 1
ʋ | Then, following as a dyad:
¹ | - Identity function (used because of Jelly’s ordering of dyadic links at the start of a dyadic chain)
j ɗ | - Join with the following as a dyad, using the original left and right arguments for this chain:
ṪḢƭ€ | - Tail of first item (popping from list) and head from second item (again popping from list); extracts the numbers that were either side of the operator, while removing them from the split list
j | - Joined with the operator
ŒV | - Evaluate as Python (rather than V because of Jelly’s handling of decimals with a leading zero)
ß | - Recursive call to this helper link (in case there are further of the same operator)
F | Else: Flatten
```
### Main link
Takes a list of floats/integers alternating with operators (as characters)
```
Ḋ | Remove first item (which will be a number)
m2 | Every 2nd item, starting with the first (i.e. the operators)
Q | Uniquify
Œ! | Permutations
烀 | For each permuted list of operators, reduce using the helper link and with the input list as the starting point
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~182~~ 172 bytes
```
import re
def f(s,P=set('+-/*')):
S=[eval(s)]
for p in P:
t=s
while p+' 'in t:t=re.sub(r'[-\d.]+ \%s [-\d.]+'%p,lambda m:`eval(m.group())`,t,1)
S+=f(t,P-{p})
return S
```
[Try it online!](https://tio.run/##XVDBasMwDD3XXyE6iu3ESUm2QhfIdedCj2mgKXXWjCQ2trKyjX17J3eFlZ0k6z09vyf7gScz5pdLN1jjEJxmR91CK7zalF6j4HGyjLiUBYNtWen3phde1gxa48BCN8KmYDMsPZudT12vwcYcOI2xwNLp1E8H4XiV7I5pHcNu4eHW84VVfTMcjg0Mxf6qO6SvzkxWSLlXqDLJZtu4bAWqTfJlvyUjczi5EbaXYPGFfJAphBJ86m3foSAK6XiaDI0VHp0Kte1NgwqroshrSRRjAwOrLAx@Bchy@ma6UfhpEJ@dFUFGETGuOK@lIktVkWQ1bT9QZvQhuIfGaRjNOTzwpOH6UTjMQKXxgIF980wx/gKEu4aBZMw6kqMs8xwSeIQY1lRXoZ/LezCiYQz5fyBbw5LWoiuS3SNPK0LWtJM9U0OvKGxe2A8 "Python 2 – Try It Online")
Takes input with ints formatted as floats, as per "Integers can be replaced by floats for languages that implicitly parse type".
[Answer]
# [Julia 1.2](http://julialang.org/), 88 (82) bytes
```
f(t)=get(t,(),[f.([t[1:i-1];t[i+1](t[i],t[i+2]);t[i+3:end]] for i=1:2:length(t)-2)...;])
```
```
julia> f([2, +, 3, *, 4])
2-element Array{Int64,1}:
20
14
julia> f([18, /, 3, *, 2, -, 1])
6-element Array{Float64,1}:
11.0
6.0
2.0
3.6
6.0
6.0
```
Takes a tape in the form of a vector of numbers and infix functions, evaluates each single function call and recursively passes each resulting tape back to itself until only a single number is left. Unfortunately, `get(t, (), ...)` doesn't work properly in Julia 1.0, so a newer version is needed.
Six bytes can be saved, if a bunch of nested arrays is acceptable as an output:
```
f(t)=get(t,(),f.([t[1:i-1];t[i+1](t[i],t[i+2]);t[i+3:end]] for i=1:2:length(t)-2))
```
Output:
```
julia> f([18, /, 3, *, 2, -, 1])
3-element Array{Array{Array{Float64,1},1},1}:
[[11.0], [6.0]]
[[2.0], [3.6]]
[[6.0], [6.0]]
```
[Answer]
# Perl 5 (`-alp`), 89 bytes
```
my$x;map{$x.=$`.(eval$&.$1).$2.$"while/\d+[-+*\/](?=(\d+)(.*))/g}@F;$_=$x;/[-+*\/]/&&redo
```
[TIO](https://tio.run/##K0gtyjH9/z@3UqXCOjexoFqlQs9WJUFPI7UsMUdFTU/FUFNPxUhPRak8IzMnVT8mRTtaV1srRj9Ww95WA8jT1NDT0tTUT691cLNWibcFGqIPVaCvplaUmpL//7@RtrGWCZehhb6xlpGu4b/8gpLM/Lzi/7qJOQX/dX1N9QwMAQ)
or unique values, 99 bytes
```
my%H;map{$H{$`.(eval$&.$1).$2}++while/\d+[-+*\/](?=(\d+)(.*))/g}@F;$_=join$",keys%H;/[-+*\/]/&&redo
```
] |
[Question]
[
This challenge is based on the following puzzle: You are given an `n` by `n` grid with `n` cells marked. Your job is to the partition the grid into `n` parts where each part consists of exactly `n` cells, each containing exactly one marked cell.
# Example
Here is a puzzle on the left and its (unique) solution on the right:
[](https://i.stack.imgur.com/tYDYT.png)
[](https://i.stack.imgur.com/3BHUo.png)
# Challenge
You will be given a set of `n` zero-indexed coordinates in any reasonable format.
```
[(0,0), (0,3), (1,0), (1,1), (2,2)]
```
And your job is to write a program that returns any valid parition (again, in any reasonable format).
```
[
[(0,0), (0,1), (0,2), (1,2), (1,3)],
[(0,3), (0,4), (1,4), (2,4), (3,4)],
[(1,0), (2,0), (3,0), (4,0), (4,1)],
[(1,1), (2,1), (3,1), (3,2), (4,2)],
[(2,2), (2,3), (3,3), (4,3), (4,4)]
]
```
If the puzzle has no solution, the program should indicate that by throwing an error or returning an empty solution.
# Input/Output Examples
```
[(0,0)] => [[(0,0)]]
[(0,0), (1,1)] => [
[(0,0), (1,0)],
[(0,1), (1,1)]
]
[(0,0), (0,1), (1,0)] => [] (no solution)
[(0,0), (0,1), (0,2)] => [
[(0,0), (1,0), (2,0)],
[(0,1), (1,1), (2,1)],
[(0,2), (1,2), (2,2)],
]
[(0,0), (0,2), (1,2)] => [
[(0,0), (1,0), (2,0)],
[(0,1), (0,2), (1,1)],
[(1,2), (2,1), (2,2)],
]
```
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins.
[Answer]
# JavaScript (ES7), 166 bytes
Outputs a matrix of integers that describe the partition, or \$false\$ if there's no solution.
```
a=>(m=a.map(_=>[...a]),g=(n,X,Y,j=0,i)=>a[n]?a[j]?m.some((r,y)=>r.some((v,x)=>++v|(X-x)**2+(Y-y)**2-1?0:g(r[x]=n,x,y,j+1,i|x+[,y]==a[n])?1:r[x]=v)):i&&g(n+1):1)(0)&&m
```
[Try it online!](https://tio.run/##dY3NboMwEITveQqfyDpeLJveqBbOfYNEllVZKUGgYBBQBGr67BTSVOpPetqd@WZnSze47tgWTR/6@iWbTzQ7SqAiJyvXwDMlRkrpLMecwOMeD1iSwoJT4oy3qTOlTSvZ1VUG0OK0@O1NDTguSojhAvtw5LtdJOAQTusS6lTFObRmtORxxAlLobG4jMLgZInWap7q@BoYOI@LIMjBC81jzUHxIKjmPut6RswxStgbO9a@q8@ZPNc5bJ9889rHW2SOP/4gJ3D8l7XI981mLQNjFCpr@XeFzGjUf021mFem/mUKo3ss@ry7yx6@Om9vlxFdk/MH "JavaScript (Node.js) – Try It Online")
### How?
We first build a square matrix \$m\$ of size \$N\times N\$, where \$N\$ is the length of the input:
```
m = a.map(_ => [...a])
```
Each row of \$m\$ consists of a copy of the input, i.e. an array of \$N\$ coordinate pairs. The important point here is that all cells of \$m\$ are initialized to non-numeric values. We'll be able to detect them by applying the prefix increment operator `++`.
The recursive function \$g\$ takes a pointer \$n\$ into the input, the coordinates \$(X,Y)\$ of the previous cell, a counter \$j\$ that holds the number of filled cells in the current area, and a flag \$i\$ that is set when the marked cell is found in the area:
```
g = (n, X, Y, j = 0, i) => a[n] ? a[j] ? ... : i && g(n + 1) : 1
```
We test \$a[n]\$ to know if all areas have been processed and we test \$a[j]\$ to know if enough cells have been filled in the current area.
The main part of \$g\$ looks for the next cell of \$m\$ to fill by iterating on all of them:
```
m.some((r, y) => // for each row r[] at position y in m[]:
r.some((v, x) => // for each cell of value v at position x in r[]:
++v | // if this cell is already filled (i.e. v is numeric)
(X - x) ** 2 + // or the squared Euclidean distance between
(Y - y) ** 2 - // (X, Y) and (x, y)
1 ? // is not equal to 1:
0 // this is an invalid target square: do nothing
: // else:
g( // do a recursive call to g:
r[x] = n, // pass n unchanged and fill the cell with n
x, y, // pass the coordinates of the current cell
j + 1, // increment j
i | // update i:
x + [,y] == a[n] // set it if (x, y) = a[n]
) ? // if the result of the call is truthy:
1 // return 1
: // else:
r[x] = v // reset the cell to NaN
) // end of inner map()
) // end of outer map()
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 26 bytes
```
Jṗ2Œ!s€L_/ƝÆḊ€ỊẠƲ€Ạ$Ƈi"Ạ¥Ƈ
```
[Try it online!](https://tio.run/##y0rNyan8/9/r4c7pRkcnKRY/alrjE69/bO7htoc7uoCch7u7Hu5acGwTiLlrgcqx9kwlIH1o6bH2/48aZhxuf9QwU@HQVoUsoDwINe7TUQASGppZjzauAyIFb6CoQqQmUEHjvkPbDm37/z9aw0DHQFNHQcNQx1AzFgA "Jelly – Try It Online")
This is *wildly* inefficient, around \$O({n^2}!)\$ for an input of \$n\$ co-ordinates. As such, it times out on TIO for \$n \ge 3\$. I've tested it locally for the other test cases and it works as expected.
This takes input 1 indexed, and it returns a list of valid partitions. The Footer adjusts the output for you.
## How it works
```
Jṗ2Œ!s€L_/ƝÆḊ€ỊẠƲ€Ạ$Ƈi"Ạ¥Ƈ - Main link. Takes a list of n coordinates on the left
J - [1, 2, ..., n]
ṗ2 - All pairs; [[1, 1], [1, 2], ..., [n, n]]
Œ! - All permutations
L - Yield n
s€ - Split each permutation into n parts
$Ƈ - Keep the matrices for which the following is true:
Ʋ€ - Over each row:
Ɲ - For each overlapping pair:
_/ - Get the successive differences
ÆḊ€ - Get the norm for each
ỊẠ - All are between -1 and 1?
Ạ - This is true for all rows?
This filters out matrices of non-adjacent coordinates
¥Ƈ - Keep the matrices for which the following is true:
i" - Get the indices of each coordinate, or 0, if not in each row
Ạ - All non-zero?
```
] |
[Question]
[
Here is a list of 30 English nouns in their singular and plural form. Your job is simply to write the shortest regular expression that matches *all* the nouns in one form and *none* in the other (easy, all English nouns end in `s` in plural form right?).
```
SINGULAR PLURAL
--------- --------
car cars
boat boats
man men
woman women
omen omens
bus buses
cactus cacti
spy spies
pie pies
louse lice
mouse mice
amice amices
goose geese
creese creeses
person people
child children
siren sirens
ox oxen
foot feet
tooth teeth
formula formulae
minx minxes
sphinx sphinges
wife wives
knife knives
ion ions
criterion criteria
jinni jinn
zero zeros
hero heroes
```
Yes, some of the words have alternative forms, but these are the ones we're going to use.
[Here](http://ideone.com/7NVJnm) is a script that can help you with the testing; just put your regex between the two slashes (`/`) on the first line.
[Answer]
44, or 46 if delimiting `//` count:
```
dr|wome|[aglx]e|et|ti|ia|[^u]s$|nn$|^.ic|^me
```
[Answer]
42 (or 44 with delimiters)
`^.(e[^r]|ic)|x.|..me|ia|ti|.l..|nn$|[^u]s$` - [Try it online!](https://tio.run/##PZBda9swFIbvz69ISKmlsrodlF3UeKMX2xiEMdL1KiSgOsf2aWXJSHKdpt5vz44U2pvnvEZfz@sn9aJ85agPl76nHbrOmmd8PbrS4DhbYfN93wtxKL9eXRy3ucD11m0mquS0z6c873AiNQWacp3nkzFn03o7bPzZ8eLqIPNg74Mj0wiZe00Vii@fLm@kLGrrRF1@LoQuHaqdJoNCynlpBq2LuryWb1SLeS17PhyELPhL5xpNE9rzc72@3szLbJHJfgg@OF7qVKha4eS37K8b8HY2y26zH0p7jpks3rfJ4t9xMbv/9fvnw/JuBVApB49WBeiUgdFG2g4NPA6e16rAw/ev0BOCtoNH6BJVx02gsZZz5RB59Oi8NVC1pHfgyfEldg@1tQECo@XoukEr6Mjs@dI2jpFqhGcTSfGwo4AupicyhuCAzkIbAYvZn@XD6m6ZlH1y9hBNx@Qb4aM1nryJXyDOCfG3QzJO3h6aZHwS5z1oe40n86id5D3bc64R2Z/x4Y@pAPpThYbDSC9MbhEHy/v3HirVSC18qoH@Pw "JavaScript (SpiderMonkey) – Try It Online")
`^.(e[^r]|ic)|x.|..me|ia|[adjlu]...$|[^u]s$` - [Try it online!](https://tio.run/##PZBda9swFIbvz69ISKmlsrodjF3UeKMX2xiEMdL1KiSgOse2UlkyOnKdpt5vz44UupvnvEZfz@u9elFUed2Ha@r1Dn3n7DO@nnxpcZytsPl26IU4ll9urk7bXOB66zeTruR0yKc873DSalqr3d4MmzzPL6b1dtjQxenq5ijz4B6C17YRMiejKxSfP1x/krKonRd1@bEQpvSodkZbFFLOSzsYU9TlrXzTtZjXsufDQciCv0xu0Dahvbw069vNvMwWmeyHQMHzUqdC1Qovv2Z//IB3s1l2l31XhjhmsnjfJou/p8Xs4eevH4/L@xVApTw8ORWgUxZGF@k6tPA0EK9VgQf1r9BrBOMGQugSVcdNoHGOc@URefToyVmoWm12QNrzJe4AtXMBAqPl6LvBKOi0PfClbRyjrhGebaSOh70O6GPaa2s1HNE7aCNgMfu9fFzdL5MyJWeCaDom3wiK1nj21vyC5pwQfzsk4@RN0CTjszjvQdcbPJtH7SRPbM@5RmR/xn9/TAWQzhUaDqN@YXKLOFie3nuoVCO1oFQD6R8 "JavaScript (SpiderMonkey) – Try It Online")
[Answer]
65 or 67
```
^[lm]i[^n]|^ge|ti|ia|[l|a]e$|ox.|^(wo)?men$|dren|nn$|et|[netro]s$
```
] |
[Question]
[
Write a program that visualizes long division with ASCII art. Input consists of two integers, a numerator and a denominator, using the input format of your choice.
**Examples:**
1234 ÷ 56:
```
22
----
56|1234
112
---
114
112
---
2
```
1002012 ÷ 12:
```
83501
-------
12|1002012
96
---
42
36
--
60
60
--
12
12
--
```
0 ÷ 35
```
0
-
35|0
```
**Rules:**
* Use of the programming language's division operator **is** allowed.
* Use of big integer support is also allowed.
* For consistency:
+ If the quotient is zero, print a single zero at the end of the diving board.
+ If the remainder is zero, do not print it.
+ Do not print leading zeros on any numbers.
* Excess newlines at the end and trailing spaces to the right are allowed.
* Solution with the fewest characters wins.
**Limits:**
* 0 <= numerator <= 1072 - 1
* 1 <= denominator <= 9999999
This implies that the output will never be wider than 80 columns.
**Test suite and sample implementation:**
You can use [long-division.c](https://gist.github.com/raw/869887/long-division.c) ([gist](https://gist.github.com/869887)) to test your program. It is actually a bash script with a C program inside. Tweak it to invoke your program in the test suite. Look at the C code at the bottom to see the reference implementation. Please let me know if there are any problems with the sample program or test suite.
```
$ ./long-division.c 10 7
1
--
7|10
7
--
3
$ ./long-division.c
PASS 1234 ÷ 56
PASS 1002012 ÷ 12
PASS 1 ÷ 1
--- snip ---
Score: 35 / 35
All tests passed!
```
**Edit:** By request, I put the test suite [input](https://gist.github.com/raw/870827/input) and [expected output](https://gist.github.com/raw/870827/expected) into text files ([gist](https://gist.github.com/870827)). Sample usage (bash):
```
cat input | while read nd; do
./program $nd |
sed 's/\s*$//' | sed -e :a -e '/^\n*$/{$d;N;};/\n$/ba'
done > output
diff -u expected output
```
The weird sed commands filter out trailing newlines and spaces from the program output.
[Answer]
# Python 3, ~~284~~ 257 characters
## div.py
```
n,t=input().split()
d=int(t)
l=lambda x:len(str(x))
s=l(n)
def p(x):print(' '*(l(d)+s-l(x)+1)+str(x))
p(int(n)//d)
p('-'*s)
p(t+'|'+n)
s=z=f=0
while t:
try:
while z<d:z=z*10+int(n[s]);s+=1
except:t=0
if z*f:p(z)
if t:f=1;t=z//d*d;p(t);p('-'*l(z));z-=t
```
Usage: `python3 div.py`
Input: from keyboard
## test.py
```
import sys
sys.stdin=open('input'); sys.stdout=open('output','w')
for line in open('input'): exec(open('div.py').read())
```
*output* matches *expected*
Versions:
1. [284](http://ideone.com/90gcH)
2. [257](http://ideone.com/r99o6): `s,z,f=0,0,0`→`s=z=f=0`; `z and f`→`z*f`; better looping; removed a few newlines.
[Answer]
## Haskell, 320 characters
```
l=length
(®)=replicate
p!v=p&show v
p&s=(p-l s)®' '++s
0§_=[];_§l=l
d[m,n]=l c!(read m`div`e):l c&(l m®'-'):c:drop 1(g 0(map(toInteger.fromEnum)m)$1+l n)where
e=read n;c=n++'|':m
g r(d:z)p=i§[o!k,o!(i*e),o&(l(show k)®'-')]++g j z o where k=r*10+d-48;(i,j)=k`divMod`e;o=1+p
g r[]p=r§[p!r]
main=interact$unlines.d.words
```
Passes all tests. While is this pretty golf'd -- I think there is still yet more to be done here...
---
* Edit: (344 -> 339) delay `read` calls, which reduces need to call `show`, enough that abbreviating `show` as `s` isn't worth it.
* Edit: (339 -> 320) rewrote string field formatting functions
[Answer]
## JavaScript (400 394 418)
```
function d(n,d){t=parseInt;p=function(v){return(s+v).substring(v.length)};a=function(v,c){return v.replace(/\d/g,c)};w='\n';q=b=o=c=e='';s=a(d,' ')+' ';f=true;i=-1;z='0';while(++i<n.length){s+=' ';if(t(c+=n[i])>=t(d)){q+=r=Math.floor(t(c)/t(d));o+=(!f?p(c)+w:e)+p(''+r*t(d))+w+p(a(c,'-'))+w;c=t(c)%t(d);f=false}else if(!f){q+=z;}c=(c==0)?e:e+c}return p(!q?z:q)+w+p(a(n,'-'))+w+d+'|'+n+w+o+(q?p(c):e)}
```
NOTE: As tempting as it looks to shave off a few chars by replacing `c=(c==0)?` with `c=!c?`, it is not usable because it causes floating point-related bugs.
[http://jsfiddle.net/nLzYW/9/](http://jsfiddle.net/nLzYW/5/)
Sample Execution:
```
document.writeln("<pre>");
document.writeln(d("1234","56"));
document.writeln();
document.writeln(d("1002012","12"));
document.writeln();
document.writeln(d("0","35"));
document.writeln();
document.writeln(d("123000123000123","123"));
document.writeln("</pre>");
```
**Edit 1**: Minor bug fixes, numerous code optimizations.
**Edit 2**: Fix bug with 1/7 generating extra output.
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 422 bytes
I think it took me over a week to solve this problem.
```
function l(x){return length(x)}{P=9(d=$2);gsub(".",FS,P);N=l(L=n=$1);gsub(".","-",L);O(0,q=int($1/$2));Q=l(q);print P L RS d"|"n}function O(i,x){printf"%"l(d)+N-Q+1+i"d\n",x}m=substr(q,1,1)*d{for(i=1;i<=Q;){O(i,m);print P substr(L,1,N-Q+1);for(_=l(j=n)-l(n-=m*10**(Q-i));_--;)P=P FS;if(!n)exit;match(q,".0*");i+=R=RLENGTH;sub(".{"R"}",E,q);b=q+0?substr(n,1,M=l(m=substr(q,1,1)*d)):n;if(b<m)b=substr(n,1,M+1);O(i-(i>Q),b)}}
```
[Try it online!](https://tio.run/##ZY9dT8IwFIb/Sm0w6dk6XPETy9Er1IsJ2/DShDDGoLoVN0Ykmfvts0OiJN41p885z/vOPt@bJtnqeanWmqRsB1WxKLeFeS/0slyZQV352Gcxdnogl5ttxGiX8ocJ90GOMGUeauyIoy/qUO6BHDOX56h0yTrizOyCDAydg/wozJD4xCPhhMT0i@r6N8CYKW4i7JGEntKUxWCPnMAWtqLxq6Z8V2doTJuyYDkXXIAVV8m6YAqFVAMMJFTtkezPc6A9Q@8vgWz5qQnzhhqclGkHM0u4lsUCR5mcU8eR4KNPHiZSJexEw2KnSpnNyvnKSGnXtShIZWOIoTccPb48yZ/uFQ1pTfmQm5YR5rZ7f3Br4342wn/RAW5164gGGUR4TLc5TRGHqbsAeAR13TSEiN75xeUVub7pu98 "AWK – Try It Online")
## Usage
* Input is given from STDIN, as single line.
* Two natural numbers are on same line.
* Output is returned to STDOUT.
* This program does never handle overflow; fails on huge values.
* This program does not handle multiple lines of input correctly; only the first line is handled correctly.
## Formatted
```
function l(x){
return length(x)}
{
P=9(d=$2);gsub(".",FS,P);
N=l(L=n=$1);gsub(".","-",L);
O(0,q=int($1/$2));
Q=l(q);
print P L RS d"|"n}
function O(i,x){
printf"%"l(d)+N-Q+1+i"d\n",x}
m=substr(q,1,1)*d{
for(i=1;i<=Q;){
O(i,m);
print P substr(L,1,N-Q+1);
for(_=l(j=n)-l(n-=m*10**(Q-i));_--;)
P=P FS;
if(!n)
exit;
match(q,".0*");
i+=R=RLENGTH;
sub(".{"R"}",E,q);
b=q+0?substr(n,1,M=l(m=substr(q,1,1)*d)):n;
if(b<m)
b=substr(n,1,M+1);
O(i-(i>Q),b)}}
```
[Answer]
# Javascript: (372)
```
function g(a){for(var c="",e=0;e<a;e++)c=" "+c;return c}function i(a,c){for(var e=a+"/"+c+"\\",j=(""+c).split(""),k="",d=0,b=0;b<j.length;b++){d*=10;d+=parseInt(j[b],10);var f=d>9?b-1:b,h=0;h=Math.floor(d/a);d%=a;f=g(f+a.toString().split("").length);f+=h*a+"\n"+g(b+a.toString().split("").length)+"--\n"+g(b+a.toString().split("").length)+d+"\n";k+=f;e+=h}return e+"\n"+k}
```
Invoke by using i(divider,number).
Codegolfed JS: <http://jsfiddle.net/puckipedia/EP464/>
Ungolfed (dutch) JS: <http://jsfiddle.net/puckipedia/M82VM/>
Returns the long division (in dutch format as i learned it):
```
5/25\05
0
--
2
25
--
0
```
Testcase:
```
document.write("<pre>"+i(5,25)+"</pre>");
document.write("<pre>"+i(7,65669726752476)+"</pre>");
```
] |
[Question]
[
My final-year project at the National University of Singapore is on Zarankiewicz's problem:
>
> What is the maximum number of 1s in an \$m×n\$ binary matrix (\$m\$ rows and \$n\$ columns) with no \$a×b\$ minor (intersection of any \$a\$ rows and any \$b\$ columns) being all 1s?
>
>
>
For example, the matrix below contains a \$3×3\$ all-1 minor
$$\begin{bmatrix}
0&(1)&1&(1)&(1)&1\\
1&1&0&1&0&0\\
0&(1)&0&(1)&(1)&0\\
0&1&1&0&1&1\\
1&1&0&0&0&1\\
1&(1)&0&(1)&(1)&0
\end{bmatrix}$$
but this matrix contains no such minor – the intersection of any 3 rows and 3 columns always has at least one 0:
$$\begin{bmatrix}
0&1&1&1&1&1\\
1&0&0&1&1&1\\
1&0&1&0&1&1\\
1&1&0&1&0&1\\
1&1&1&0&0&1\\
1&1&1&1&1&0
\end{bmatrix}$$
Now any matrix with the maximum number of 1s is also *maximal* in the sense that adding another 1 anywhere in the matrix will create an \$a×b\$ minor. This task concerns itself with checking maximal matrices, not necessarily with the maximum number of 1s.
## Task
Given a non-empty binary matrix \$M\$ of size \$m×n\$ and two positive integers \$a\$ and \$b\$ where \$a\le m\$ and \$b\le n\$, determine whether \$M\$ has no \$a×b\$ all-1 minor, but has at least one such minor if **any** 0 in \$M\$ is changed to a 1. Output "true" or "false"; any two distinct values may be used for them. Formatting is also flexible for \$M\$.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); fewest bytes wins.
## Test inputs
These are given in the form `M a b`.
"True" output:
```
[[0]] 1 1
[[0,1,1],[1,0,1],[1,1,0]] 2 2
[[0,1,0],[1,1,1],[0,1,0]] 2 2
[[1,1,0,1,0],[1,0,1,1,1],[0,1,1,0,1]] 2 3
[[1,1,1,1,1],[1,1,1,1,1],[1,0,0,0,0]] 3 2
[[0,1,1,1,1,1,1,1],[1,1,1,1,1,0,0,0],[1,1,1,0,0,1,1,0],[1,1,0,1,0,1,0,1],[1,1,0,0,1,0,1,1],[1,0,1,1,0,0,1,1],[1,0,1,0,1,1,0,1],[1,0,0,1,1,1,1,0]] 3 3
[[1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0],[1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0],[1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0],[1,1,0,0,0,0,1,1,0,0,1,1,1,1,0,0],[1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0],[1,0,1,0,0,1,0,1,0,1,0,1,1,0,1,0],[1,0,0,1,1,0,0,1,0,1,1,0,0,1,1,0],[1,0,0,1,0,1,1,0,1,0,0,1,0,1,1,0],[0,1,1,0,1,0,0,1,0,1,1,0,1,0,0,1],[0,1,1,0,0,1,1,0,1,0,0,1,1,0,0,1],[0,1,0,1,1,0,1,0,1,0,1,0,0,1,0,1],[0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1],[0,0,1,1,1,1,0,0,1,1,0,0,0,0,1,1],[0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1],[0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1],[0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1]] 3 3
```
"False" output:
```
[[1]] 1 1
[[0,1,0,1,0],[1,0,1,0,1],[0,1,0,1,0]] 1 3
[[0,1,0],[0,1,0],[0,1,0]] 3 1
[[0,0],[1,1]] 2 2
[[0,0,0,0,0,1,1,1,1],[0,0,1,1,1,0,0,0,1],[0,1,0,0,1,0,0,1,0],[0,1,0,1,0,0,1,0,0],[0,1,1,0,0,0,0,0,0],[1,0,0,0,1,1,0,0,0],[1,0,0,1,0,0,0,1,0],[1,0,1,0,0,0,1,0,0],[1,1,0,0,0,0,0,0,1]] 2 2
[[0,1,1,1],[1,0,1,1],[1,1,0,1],[1,1,1,0]] 4 4
[[1,1,0,1,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,1],[0,1,1,0,1,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0],[0,0,1,1,0,1,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0],[0,0,0,1,1,0,1,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,1,1,0,1,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0],[0,0,0,0,0,1,1,0,1,0,0,0,0,1,0,0,0,0,0,1,0,0,0],[0,0,0,0,0,0,1,1,0,1,0,0,0,0,1,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,0,1,0,0,0,0,1,0,0,0,0,0,1,0],[0,0,0,0,0,0,0,0,1,1,0,1,0,0,0,0,1,0,0,0,0,0,1],[1,0,0,0,0,0,0,0,0,1,1,0,1,0,0,0,0,1,0,0,0,0,0],[0,1,0,0,0,0,0,0,0,0,1,1,0,1,0,0,0,0,1,0,0,0,0],[0,0,1,0,0,0,0,0,0,0,0,1,1,0,1,0,0,0,0,1,0,0,0],[0,0,0,1,0,0,0,0,0,0,0,0,1,1,0,1,0,0,0,0,1,0,0],[0,0,0,0,1,0,0,0,0,0,0,0,0,1,1,0,1,0,0,0,0,1,0],[0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,1,0,1,0,0,0,0,1],[1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,1,0,1,0,0,0,0],[0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,1,0,1,0,0,0],[0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,1,0,1,0,0],[0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,1,0,1,0],[0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,1,0,1],[1,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,1,0],[0,1,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,1],[1,0,1,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1]] 2 2
```
The fifth "false" test case is indeed false since flipping the \$(4,5)\$ entry from 0 to 1 does not make a \$2×2\$ minor.
[Answer]
# Python3, 175 bytes:
```
lambda m,a,b,z=lambda m:all(b>sum(map(all,zip(*s)))for s in combinations(eval(m),a)):z(M:=str(m))-any(z(M[:i]+'1'+M[i:])for i,c in enumerate(M)if"0"==c);from itertools import*
```
[Try it online!](https://tio.run/##rVVLjqMwEF03p7DYYKfdLZP0YsSIuUHmAjQaOWlQW@IncEZKLp8x5ld2ILAYIbBdfq9c1M/VVX6XxeFHVd/T8POe8fz0xVFOOT3RWzgsA55l@PSrueQ45xVWK3oTFd41hJC0rFGDRIHOZX4SBZeiLBqc/OUZzgnlhAQ3fAzCRtZqTd54ccVKEAUifvV87/UYiSDWSgQ9t2qS4pInNZcJPhKRuswNwzP5mdZljoRMalmWmTour8pa7u7diHgjHVlf5Pc1dF03ilgcIx/5jppRn/oxjXzK@lHN1O4e7ftd1kvbXWbsauyI0JpGVKevRR56pD@eBOesexTyMJ4IHojvkYOE9ScOEja9o2SQ@cBCZkkmawd7xvO0VYb90JLpAVYOMmttWDQ7AoS9CxGMPnkBwt4zEVA/m/Ems3lwDSM8jwQIG2ki4K6lDyAWXo0wPW15ECAWxh4xEzGQgVa0rVzw@yxRheXoMm2LNBWZqkX8uywSirrKe2@qTEjsfRaeqnnnRfcQFCLdMBr5nrXVy7M/bWegSPRwQpyXqhaFxCnWDCXo1t6bt9sz4qQ8a5KrUtQaoFLVKG07LQy3auQBlLk5tr/V6emTE7SFeSdBB04nga8RVDamNbOLCrQGs/AnbY8Jz2YLiY2NCLSXqR1MzWNqLAr9gT5gg4P6Z@Z20m9iGMm5gTEm4kaGldqrDCPRNzCswlhlPBTSCmOh8BYZ8DrZwgD5uYkxxmsjA8RrE8OI1waGFa9VhuWfVcaDf1YYM/55ypj1zxPGgn8WGcb/bmBY/7vKsHrPKqPrQcu3RNfH/98tcf8H)
[Answer]
# [R](https://www.r-project.org/), ~~196~~ ~~166~~ ~~155~~ ~~149~~ 135 bytes
Or **[R](https://www.r-project.org/)>=4.1, 107 bytes** by replacing four `function` occurrences with `\`s.
*Edit: -14 bytes thenks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe).*
```
function(M,a,b,`?`=all)M==sapply(seq(!M),g<-function(i){M[i]=1;?!combn(nrow(M),a,function(x)combn(ncol(M),b,function(y)?M[x,y]))})?g(0)
```
[Try it online!](https://tio.run/##fVLLboMwELz3K5qbV9pKdkilVqnFF/jWWxQpBpUIiUBKEgVU9dvphjTGD0BeDPbMmNld110mu@xSpue8KplCjQnu4p3URQFKypM@HouWnb6@2UIB7j9eDDeHH7XJt1Ks40VaHZKSlXV1ZcTSaEgN/ENpVdygZIBaiNWmwXYL8AvxnnHoMnbQ5zpvWEorRIGfgM@CAp5siIDbMG@iRj11SRFQbfoM1VA8ST@T7PUhiwJZOPh9GFk0ZmxOOnw7Pjx3Y16ddEeRexneHsYoHyeh@cJPPiZX4ZeIW17dJkThH3qTRFhONZQ7FRJetQZL4Wyvud2miX2fb5/Cne5Yp5D19@m76F5c4bVk1QtXFND9AQ "R – Try It Online")
Straightforward brute-force.
Takes advantage of redefining ``?`=all` and operator precedence (`?` has the lowest and is both unary and binary operator).
[Answer]
# [J](http://jsoftware.com/), 86 bytes
```
1=2#.1-((1 e.,@{@(<@(#~(-:~.)&>)@,@{@#"0;&i./@$)*/@,@{])"1 2],~$$"1,1:`[`]}"{~[:I.1-,)
```
[Try it online!](https://tio.run/##dVLfS8MwEH7fX3G0YW0kze5aBa1OCsJA8El8G4WJrEwRBH88yLD/ek3apLmtypFLLvfd17svfekinTSwLCEBBQilWZmGm/u7VUfLPNaUpSnBVqtqX6VXVRq3aVa2Ws6vZWXv4ggv5896UQl5srA3tYwI8lq1QkSkqNysN/VPtG/X5a0hU7KTs@3T7g2Sh/evz913MkRkrAGlAYc4N9ZAYUyYjmwWzEK3038wdGkLQw4retiZgZHjwZExwPt4KCkcsy@hsQl@xsF8if3KuTEx8v5VOBQBi4i1jmwBQxyqEOqA4UMVsg5w5hRfPb5@TAQnHweJcCIRBkXdvR@ZJvof7/ylrBds/MPshTHhNWUDAIt8xvNzzzv0HphcyKRHJjy/Cxk@Pec7ZgtTnBprei/Yj8Wfjj@rOXe/ "J – Try It Online")
The 2 long test cases time out on TIO, so I've removed them.
* Creates a list of all 0-to-1 mutated versions of the input, with the input itself as the final element in that list.
* For each of those, checks for the required minor, using brute force, returning 1 if a minor is found, 0 otherwise.
* Swaps those zeros and ones
* Convert to a binary number
* Checks if the number is 1.
+ This will only be true of every 0-to-1 mutation has the minor, but the input does not.
[Answer]
# Python 3, 176 bytes
```
lambda m,a,b:(z:=lambda m:all(b>sum(map(all,zip(*s)))for s in combinations(eval(m),a)))(M:=str(m))-any(z(M[:i]+'1'+M[i:])for i,c in enumerate(M)if"0"==c)
from itertools import*
```
[Try it online!](https://tio.run/##jVbbbqMwEH3PV1i81KRuZZo@rJDYP8gX0Dw4WdBa4ibsrtT8fNYQY8YTCBYC384ZD@Mz1nQ/@m/bHH51/a3Mvm6VqM9/BKmZYOeUXtNsmkhFVdHzb/Vd01p01IzYVXZ0r@I4LtueKCIbcmnrs2yElm2jaPFPVLSOmTAIekwzpXszjN9E80Ov9Jin8vT6kry8HnOZnkYbkl0GK0XzXRe90AU9xrKMeJRll3hX9m1NpC563baV2a3u2l7vb7pQ@iJUoUhGoija5Tk/nUhCkqHHEpacWJ4wblvTM6sf5MOucjs7rHJvdcQ6xGjJoe72BuTBIhO3E@zz@2OQB7cjeCDeIqcZbnecZvj8uplpLgEecjQzezv54/YbvfL8h57MD/BymkNjz6PFFiDwKkRw9uQFCLzmI6B9vhBNjnlwDE94GQkQGOkj4CqyBxAr74jwI40iCBArrUUsnBhQIDptpIXEqmSQiZdW@Ei8XxqRB5BifjuYvNuxwgApuewgdH7eCXy9gHInKY4FDdLST7rZ2qPY@KKIubsEQGrPqTgn7pzUBv1JPuHlAu0v9LHgghieMAIYTgSBDCSrTYYnsgAGEuUm40HEG4wV0a8y4FUewgD6DGK48wpkgPMKYnjnFcBA57XJQPHZZDzEZ4OxEJ@njMX4PGGsxGeV4f1vAAP97yYD3T2bDHsHmeLn3ZRYpiaL31VXSU2jryYydZMprPRQVrlKKd0R0vWy0bSk@6GYGyo1pi3LVGtEloZSVKog0VsU3/4D "Python 3.8 (pre-release) – Try It Online")
Based on [the Python answer](https://codegolf.stackexchange.com/a/242443) by [Ajax1234](https://codegolf.stackexchange.com/users/74571/ajax1234).
[Answer]
# JavaScript (ES6), 208 bytes
Returns \$0\$ or \$1\$.
Even though we don't have any combination built-in, this seems a bit too long. :-/
```
(m,a,b)=>(g=(v,n,C,i)=>i>>v.length||((h=i=>i&&i%2+h(i>>1))(i)^n||C(i))&&g(v,n,C,-~i))(m,a,p=>g(m[0],b,q=>m.some(X=Y=(r,y)=>r.some((v,x)=>p>>y&q>>x&~v&1?x-X|y-Y||![X=x,Y=y]:0))?1:(m[Y]||0)[X]+=2))&!/0/.test(m)
```
[Try it online!](https://tio.run/##XVHbbqMwEH3PV7iRltiqQ@2kT6nsPFTbH@hLIkolkjrEK24BFgWV7a9nJ8SAiSywfebMmZnjP0EVFPtcZ@U8Sb/U5SAuOKYB3REhcShwRRP6SjXctJSVG6kkLI9Ng/FRaMAcR/9aPB4xBDkhWJPPpGleYSeOE5rk@Q9cW9FMyBDHHvPpjp6EjN0ijRXeiK3AOa2hRn5DIPEMt0zK2jlJeXZ@Koevz/NNU8@3TfPgbcSZbkXtrxgha74Cza3fNIx4G/9RLKD4wxN7cktVlDgml1yd/upc4dmhmBE3V8HXm47Ue53sMSNumb6XuU5CTNwii3SJpx/JlLiHNP8d7I@4QEKi7wlCkSqRF1MUULTzkUCFoc8QiMZBhlUVROQFmPs0KdJIuVEK06I1OmCTRtAKTafA@UcuHtjgI474BE6UU@5Tj1NmdjhBdIEWJsoMeo2yUbTl9oxWqWfd9K7MpWHyvpJ9ZrcFzGVf0Vo23zA7hJmKHcKGr0c6jFsdsjtk6Lbrp6/XdrWcXAcYGTYemg3WmCTeDt2xxvtV8qZjGrfM7ha3rGT28FYl629X7/7WM/TLMnxs56B2P5mtd6c26pyPTR6eZHguYD@j5/8 "JavaScript (Node.js) – Try It Online")
### Commented
```
(m, a, b) => // m[] = binary matrix, a = rows, b = columns
( g = (v, n, C, i) => // g is a helper function:
i >> v.length || ( // for each i >= 0 and less than 2 ** L,
( h = i => // where L is the length of the vector v,
i && i % 2 + h(i >> 1) // count the number of set bits in i
)(i) ^ n || // if it's exactly equal to n:
C(i) // invoke C(i)
) //
&& g(v, n, C, -~i) // keep going while the above is truthy
)( //
m, a, // outer call to g: pick the rows
p => g( // for each row bitmask p:
m[0], b, // inner call to g: pick the columns
q => // for each column bitmask q:
m.some(X = Y = // initialize X and Y to non-numeric values
(r, y) => // for each row r[] at position y in m[]:
r.some((v, x) => // for each value v at position x in r[]:
p >> y & // if (x,y) belongs to a selected row
q >> x & // and a selected column
~v & 1 ? // and v is even:
x - X | y - Y || // abort if (X,Y) is set and ≠ (x,y)
![X = x, Y = y] // otherwise set (X,Y) = (x,y)
: // else:
0 // do nothing
) // end of inner some()
) ? // end of outer some(); if truthy:
1 // do nothing
: // else:
(m[Y] || 0)[X] += 2 // add 2 to m[Y][X] (results in NaN if Y
// is still non-numeric)
) // end of inner call to g()
) & // end of outer call to g()
!/0/.test(m) // make sure that all 0's in m[] are gone
```
[Answer]
# [Desmos](https://desmos.com/calculator), ~~247~~ 241 bytes
```
B(n,i)=mod(floor(n/2^i),2)
P(n)=∑_{i=0}^nB(n,i)
f(L,w,h,a,b)=\{\sum_{X=0}^w\sum_{Y=0}^h\{0<\sum_{s=0}^{2^h-1}\sum_{t=0}^{2^w-1}\{P(t)=b,0\}\{P(s)=a,0\}\prod_{x=0}^w\prod_{y=0}^h\{B(t,x)B(s,y)=0,L[yw+x+1]=1,\{x=X\}\{y=Y\}=1,0\},0\}=0^L.\total\}
```
Extra newline needed for pasting of the piecewise inside `f`.
Takes input as a flattened list `L`, width&height `w`,`h`, and the `a`,`b` of the submatrices given in the problem.
Returns 1 for Zarankiewicz-minimal matrices, otherwise NaN.
[Try it on Desmos!](https://www.desmos.com/calculator/b3qwdcj0qy) Takes too long for the larger test cases, so I commented them out.
Considering Desmos doesn't have 2d lists, combination built-in, or bit extract built-ins, this is decently good. Maybe the condition at the inside can be golfed (`\{B(t,x)B(s,y)=0,L[yw+x+1]=1,\{x=X\}\{y=Y\}=1,0\}`), or some conditions can be negated to simplify arithmetic, but I keep ending up longer.
## How it works
Since there's no combination built-in, we iterate over the powerset of rows+columns given by `u` in binary, then filter for those with hamming weight `a` and `b` respectively.
We have a big summation that gets compared with `0^L.\total` (number of 0s). If the matrix already has an a×b submatrix, then every summand is 1, so the comparison is `(w+1)(h+1)=total(1-L)`, which is always false. If the matrix does not have an a×b all-1s submatrix, then summands are 1 only for entries that are 0 and lead to an a×b all-1s submatrix when changed to 1. Hence the condition is met only if every 0 entry leads to an a×b all-1s submatrix when changed to 1.
I have since merged `s` and `t` into `u` as `u=2^w*s+t` for -5 bytes.
```
B(n,i): the i'th bit of n, where the 0th bit is the LSB
B(n,i)=mod(floor(n/2^i),2)
# P(n): hamming weight of n, the number of 1 bits
P(n)=∑_{i=0}^nB(n,i)
f(L,w,h,a,b)=\{
\sum_{X=0}^w\sum_{Y=0}^h # sum over all (X,Y)
\{ # does the matrix has an a×b all-1 minor if (X,Y) is changed to 1?
0<
\sum_{s=0}^{2^h-1}\sum_{t=0}^{2^w-1} # sum over powerset of rows and columns
\{P(t)=b,0\}\{P(s)=a,0\} # 1 if the number of rows = a and number of columns = b, so s,t defines an a×b submatrix
\prod_{x=0}^w\prod_{y=0}^h # for all entries (x,y) in the matrix, is the following true?
\{
B(t,x)B(s,y)=0, # (x,y) is not in the selected submatrix, or
L[yw+x+1]=1, # the entry at (x,y) is 1, or
\{x=X\}\{y=Y\}=1, # (x,y)==(X,Y), so the entry is changed to 1
0
\},
0
\}
= 0^L.\total # is this sum equal to the number of 0s?
\}
```
## Proper rendering of `f` for +9 bytes
(I have not kept this up to date with the latest golfs)
```
B(n,i)=mod(floor(n/2^i),2)
P(n)=\sum_{i=0}^nB(n,i)
Q=\{B(t,x)B(s,y)=0,L[yw+x+1]=1,\{x=X\}\{y=Y\}=1,0\}
f(L,w,h,a,b)=\left\{∑_{X=0}^w∑_{Y=0}^hsign(∑_{s=0}^{2^h-1}∑_{t=0}^{2^w-1}0^{(P(t)-b)^2}0^{(P(s)-a)^2}∏_{x=0}^w∏_{y=0}^hQ)=total(1-L)\right\}
```
] |
[Question]
[
Art stolen from [What size is the digit?](https://codegolf.stackexchange.com/questions/68960/what-size-is-the-digit)
---
7-segment digits can be represented in ASCII using `_|` characters. Here are the digits `0-9`:
```
_ _ _ _ _ _ _ _
| | | _| _| |_| |_ |_ | |_| |_|
|_| | |_ _| | _| |_| | |_| _|
```
Your job is to parse the art into normal numbers.
### Notes on numbers
* Each digit has a different width.
+ `1` has a width of `1`
+ `3` and `7` are `2` wide
+ `245689` and `0` are all `3` wide
Also between each digit is one char of padding. Here is the full char set:
```
// <-- should be one space, but SE formatting messed it up
|
|
-------------
_
_|
|_
-------------
_
_|
_|
-------------
|_|
|
-------------
_
|_
_|
-------------
_
|_
|_|
-------------
_
|
|
-------------
_
|_|
|_|
-------------
_
|_|
_|
-------------
_
| |
|_|
```
### Input
Input can be either from the console or as a string arg to a function.
### Output
Output is either put to the console or is returned from the function.
## Examples:
```
_ _ _
| | | |_
| | | |_|
1776
_ _ _
_| | | | |_
|_ |_| | |_|
2016
_ _
| |_| |_| |_
| _| | _|
1945
_ _ _ _ _ _
| | | | | | | | | | | | |
| |_| |_| |_| |_| |_| |_|
1000000
_ _ _ _ _ _ _ _
| | | _| _| |_| |_ |_ | |_| |_|
|_| | |_ _| | _| |_| | |_| _|
0123456789
```
This is code-golf so shortest byte count wins!
[Answer]
## Pyth, ~~33~~ 30 bytes
```
sm@."/9Àøw"%%Csd409hTcC.z*3d
```
Here's the idea: Once we transpose the input, and split into digits, we can sort of hash the individual digit strings and assign them to their values.
```
sm@."/9Àøw"%%Csd409hTcC.z*3d Implicit: z=input
C.z Transpose input.
c *3d Split that on " ", a space between digits.
m@."/9Àøw"%%Csd409hT Map the following lambda d over that. d is a digit string.
Csd Flatten the digit string, and convert from base 256.
% 409 Modulo that by 409
% hT and then by 11. All digits go to a distinct num mod 11.
."/9Àøw" The compressed string "03924785/61".
@ Index into that string.
s Flatten and implicitly output.
```
Try it [here](https://pyth.herokuapp.com/?code=sm%40.%22%2F9%08%C3%80%08%C3%B8w%22%25%25Csd409hTcC.z%2a3d&input=+_+++++_++_+++++++_+++_++_+++_+++_+%0A%7C+%7C+%7C++_%7C+_%7C+%7C_%7C+%7C_++%7C_+++%7C+%7C_%7C+%7C_%7C%0A%7C_%7C+%7C+%7C_++_%7C+++%7C++_%7C+%7C_%7C++%7C+%7C_%7C++_%7C&debug=0).
[Answer]
# Ruby, 184 bytes
```
a=0
l=$<.map{|x|x.bytes.map{|y|y==32?0:1}+[0]*2}
(0..l[0].count-1).map{|i|l[0][i]+2*l[1][i]+4*l[2][i]}.each{|x|
x>0?(a=x+2*a):(p Hash[[40,6,32,20,18,26,42,8,44,64].zip(0..9)][a];a=0)}
```
## Explanation
* takes the input from stdin
* converts the strings to binary sequences, 1/0 for segment on/off
* encodes columns to 3bit binary number
* encodes sequences of 3 bit numbers to 9 bit numbers, use '0' columns as stop symbols
* use a lookup table to convert the 9 bit numbers to digits
This is my first code-golf. Thanks for the fun!
[Answer]
# Pyth, 39 bytes
```
sm@"413-928-506--7"%%Crd6C\524cjbC.z*3d
```
This seems to work? [Try it online](https://pyth.herokuapp.com/?code=sm%40%22413-928-506--7%22%25%25Crd6C%5C524cjbC.z%2a3d&input=+_+++_+++++_+%0A+_%7C+%7C+%7C+%7C+%7C_+%0A%7C_++%7C_%7C+%7C+%7C_%7C&debug=0).
[Answer]
# Japt, 119 bytes
```
Ur"[|_]"1 z r" +
"R x1 qR² £"11
1 1
1151151
111
15111
115 1
1
115 1
111
1511
111
15 1
11511
111
115 1
111
11"q5 bXÃq
```
`[Try it here!](http://ethproductions.github.io/japt?v=master&code=VXIiW3xfXSIxIHogciIgKwoiUiB4MSBxUrIgoyIxMQoxIDEKMTE1MTE1MQoxMTEKIDE1MTExCjExNSAxCiAxCjExNSAxCjExMQoxNTExCjExMQoxNSAgMQoxMTUxMQoxMTEKMTE1IDEKMTExCjExInE1IGJYw3E=&input=IiAgXyAgXyAgIF8gCnwgIHwgIHwgfF8gCnwgIHwgIHwgfF98Ig==)`
Oh geez, this one's really long. I don't think I have finished golfing.
# Explanation
## Preparation
We take the input and convert any `|_` to `1`. Then we transpose, strip out ending spaces, and split along double-newlines.
## Translation
We map over the resulting array and find the index where the form appears in a reference array. Here's a diagram to help:
```
MAPITEM
11
1 1 --> This same form appears at index 0 in the reference array
11 |
|
V
change the mapitem to 0!
```
After that, we join the array of numbers and output!
**NOTE**: You may be wondering why we have to change each art character to a series of 1's. This is because there seems to be a bug (or something like that) which doesn't let me store the characters as is with `|_`.
[Answer]
# Python2, ~~299~~ ~~261~~ 244 bytes
```
s=lambda a,i=0:[a]if i==len(a[0])else[[j[:i]for j in a]]+s([j[i+1:]for j in a])if all(j[i]==' 'for j in a)else s(a,i=i+1)
p=lambda l:['95572431508448853268'.find(`sum(ord(c)**i for i,c in enumerate("".join(n)))%108`)/2for n in s(l.split('\n'))]
```
I really liked this challenge, good job !
## Explanation
The function `s` takes the three lines as input, it tries to find a digit separation (all characters are spaces). When such a separation is found it calls `s` with the rest of the three lines and add the value returned by the call to the three lines that compose the digit. If there is no separation it means there is only one digit.
The function `p` is the entry point so it takes a string that represent the digits. The digits are stored as a "hash" computed with `sum(ord(c)**i for i,c in enumerate("".join(n)))%108` to save space (thanks to other answers !).
## Exemple
```
digits="""
_ _
| | | _|
|_| | |_ """[1:] # remove the '\n' at the beginning
p(digits) # [0, 1, 2]
```
## Other versions
261 bytes (py3):
```
s=lambda a,i=0:[a]if i==len(a[0])else[[j[:i]for j in a]]+s([j[i+1:]for j in a])if all(j[i]==' 'for j in a)else s(a,i=i+1)
def p(l):[print([91,21,84,31,58,76,88,41,80,68].index(sum(ord(c)**i%20 for i,c in enumerate("".join(n)))),end="")for n in s(l.split('\n'))]
```
249 bytes, this one transpose the lines (py2):
```
f="".join
s=lambda a,i=0:[a]if i==len(a)else[a[:i]]+s(a[i+1:])if all(c==' 'for c in a[i])else s(a,i=i+1)
h=lambda s:ord(s[0])**len(s)+h(s[1:])if s else 0
p=lambda l:["10220907112527153129".index(`h(f(map(f,n)))%34`)/2for n in s(zip(*l.split('\n')))]
```
[Answer]
# JavaScript (ES6), 169 bytes
```
a=>[...(a=a.split`
`)[0]].map((b,c)=>(d={' ':0,'|':1,'_':2})[b]+d[a[1][c]]*2+d[a[2][c]]).join``.split(0).map(b=>[343,3,182,83,243,281,381,23,383,283].indexOf(+b)).join``
```
Starts by splitting into three lines, remapping each column into a value, and then building a unique identity for each column from those values. It then splits by `0` (the identity for the space between columns), and finally maps each identity to it's number values, which it concatenates and outputs.
[Answer]
# Python 3, ~~281~~ 254 bytes
## Edit
I just looked at the code for the other python answer and noticed that much of the code is similar. This was arrived at independently.
(newlines added for "readability")
```
def p(i):
n=[[]]
for l in zip(*i.split('\n')):
if all(i==" "for i in l):n+=[[]]
else:n[-1]+=l
return''.join(map(lambda l:str([''.join(l[2:])==x for x in
"|_ _ ||,|,|___ | ,_ ||, _ ||, ___ |,|___ |, ||,|___ ||, ___ ||"
.split(',')].index(1)),n))
```
Ungolfed:
```
def parse(input):
lines = list(input.split('\n'))
numbers = [[]]
for lst in zip(*lines):
if all(i==" " for i in lst):
numbers += [[]]
else:
numbers[-1] += lst
return ''.join(map(digit, numbers))
def digit(num):
fingerprint =
"|_ _ ||,|,|___ | ,_ ||, _ ||, ___ |,|___ |, ||,|___ ||, ___ ||".split(',')
return str([''.join(num[2:]) == y for y in fingerprint].index(True))
```
Tests:
```
assert (parse(" _ _ _ _ _ _ \n| | | | | | | | | | | | |\n| |_| |_| |_| |_| |_| |_|") == '1000000')
assert (parse(" _ _ \n| |_| |_| |_ \n| _| | _|") == '1945')
assert (parse(" _ _ _ \n _| | | | |_ \n|_ |_| | |_|") == '2016')
assert (parse(" _ _ _ _ _ _ _ _ \n| | | _| _| |_| |_ |_ | |_| |_|\n|_| | |_ _| | _| |_| | |_| _|") == '0123456789')
assert (parse(" _ _ _ \n| | | |_ \n| | | |_|") == '1776')
```
## How it works
(Note: I am explaining the ungolfed program here since it is more readable and it has the exact same code, with the exception that the `digit` function is in-lined into a lambda)
```
def parse(input):
lines = list(input.split('\n'))
numbers = [[]]
```
The main function is `parse`. It first splits the input into lines and creates the `numbers` array.
```
for lst in zip(*lines):
if all(i==" " for i in lst):
numbers += [[]]
else:
numbers[-1] += lst
```
This is my favorite part (since it took so long to figure out). Here we `zip` the lines so we can basically vertically traverse the input. When the line has chars on it we add it to the last number in the `numbers` array. If it does not have any chars on it we add a new number to the array.
```
return ''.join(map(digit, numbers))
```
Really simple, `numbers` is mapped with the `digit` function and is converted to a string.
```
def digit(num):
fingerprint =
"|_ _ ||,|,|___ | ,_ ||, _ ||, ___ |,|___ |, ||,|___ ||, ___ ||".split(',')
return str([''.join(x[2:]) == y for x, y in zip([num]*10, fingerprint)].index(True))
```
This is (fairly) simple. `fingerprint` is the string representation of the digits created above minus the first 2 chars (this was the smallest fingerprint I could find). We return the index of the first match.
[Answer]
# Haskell, ~~270~~ 207 bytes
Don't be too hard, this is my first ever haskell program ;) I'm almost certain this can be golfed further, but I don't know how given my limited knowledge of the language.
```
import Data.Lists
b n=map c$splitOn[" "]$transpose$lines n
c n|e<-drop 2$concat n,Just r<-elemIndex True[e==f|f<-splitOn",""|_ _ ||,|,|___ | ,_ ||, _ ||, ___ |,|___ |, ||,|___ ||, ___ ||"]=(show r)!!0
```
Ungolfed:
```
module Main where
import Data.Lists
main :: IO ()
main = print $ parse " _ _ _ _ _ _ _ _ \n| | | _| _| |_| |_ |_ | |_| |_|\n|_| | |_ _| | _| |_| | |_| _|"
parse :: String -> String
parse n = let lst = transpose $ lines n
numbers = splitOn [" "] lst --" " lst
number = map digit numbers
in number
digit :: [String] -> Char
digit n | e <- drop 2 $ intercalate "" n
, fingerprint <- ["|_ _ ||","|","|___ | ","_ ||"," _ ||"," ___ |","|___ |"," ||","|___ ||"," ___ ||"]
, Just res <- elemIndex True [e == finger | finger <- fingerprint]
= head $ show res
```
Big thanks to @nimi for the tips!
] |
[Question]
[
Have you ever wanted to ask the compiler "Why?" Most of us have been frustrated when the code isn't working as it should. Mathworks has therefore implemented a nice little function, `why`, that answers the question. To give a few examples from MATLAB:
```
why
The programmer suggested it.
why
To fool the tall good and smart system manager.
why(2)
You insisted on it.
why(46)
Bill insisted on it.
```
Your task is to implement the `why` function in your language. The function should work with and without an input argument (alternatively use input `0` or `-1`). The function must be named `why` (or, writing `why(n)` in STDIN should result in the appropriate string being printed).
If no argument is given, or the argument is zero or negative, the output string should be a random, valid phrase. So, there should be a function `why`, `why()`, `why(0)` or `why(-1)` that returns a random sentence.
If an input argument, `n` is given (function argument, not STDIN), the output should be the n'th string (defined below). So, `why(1)` should always output (print/display) the same result.
The sentences are built up as follows (Type 1, Type 2 and Special). All sentences end with `!`.
```
"Person" "ending" !
"Verb" "adjective" "Person" !
A list of special cases
```
The list of persons:
```
Stewie
Peter
Homer
The programmer
The system manager
You
```
The list of endings:
```
suggested it
insisted on it
did it
```
The list of verbs are:
```
To fool
To satisfy
To please
```
The list of adjectives:
```
the smart
the bald
the tall
the rich
the stupid
```
The list of special cases:
```
How should I know?
Stop asking!
Don't ask!
```
The way to select a numbered one is:
**Type of sentences:**
```
Odd number => Type 1
Even number => Type 2
n % 7 = 0 => Type 3 (% is the modulus operator)
```
**Names:** The nth name is defined using modulus (%).
```
n = 1: 1 % 7 => Stewie
n = 2: 2 % 7 => Peter
...
n = 6: 6 % 7 => You
n = 7: 7 % 7 => How should I know?
n = 11: 11 % 7 => The programmer
n = 14: 14 % 7 => Stop asking!
n = 21: 21 % 7 => Don't ask!
```
**Endings:** The nth ending is also defined using the modulus. Assume the endings (1, 2 and 3) are listed like `(1 2 2 3)`. As the numbers are always odd, use `((n+1)/2 % 4)`
```
n = 1: ((1+1)/2 % 4) => suggested it
n = 3: ((3+1)/2 % 4) => insisted on it
n = 13: ((13+1)/2 % 4) => did it
```
**Adjectives:** The nth adjective is defined using the modulus. As the numbers are always even, use: `(n % 10)/2`
```
n = 2: (2 % 10)/2 => Smart
n = 6: (6 % 10)/2 => The tall
...
```
**Verbs:** The nth verb is also defined using the modulus. Assume the verbs (1, 2 and 3) are listed like `(1 2 2 3)` As the numbers are always even for verbs, use `(n % 8) / 2`
```
n = 2: (2 % 8)/2 => To fool
n = 4: (4 % 8)/2 => To satisfy
n = 6: (6 % 8)/2 => To satisfy
n = 8: (8 % 8)/2 => To please
```
Now, the way to create a random one should be fairly simple, simply select a random `n`.
Some examples:
```
why
You suggested it!
why
To fool the tall Homer!
why
Don't ask!
why(1)
Stewie suggested it!
why(14)
Stop asking!
why(8)
To please the rich Stewie!
```
Standard code golf rules apply. A winner will be selected one week from the day the challenge was posted.
[Answer]
# JavaScript (ES6) 345
Not sure about the numbers, but here is my attempt.
Test running the snippet below in an EcmaScript compliant browser.
```
why=n=>(n<1?n=Math.random()*840|0:0,s="suggested,insisted on,did,fool,satisfy,please,stupid,smart,bald,tall,rich,Don't ask!,How should I know?,Stop asking!,Stewie,Peter,Homer,programmer,system manager,You".split`,`,n%7?(p=s[n%7+13],n&1?(p>'a'?'The ':'')+p+` ${s['2011'[-~n/2%4]]} it!`:`To ${s['5344'[n%8/2]]} the ${s[n/2%5+6]} ${p}!`):s[11+n%3])
for(o='',i=0;++i<1e3;)o+=i+':'+why(i)+'\n';O.innerHTML=o
function test() { R.innerHTML=why(+I.value) }
// Less golfed
WHY=n=>(
n=n<1?Math.random()*999|0:n,
s=["suggested", "insisted on", "did", "fool", "satisfy", "please",
"stupid", "smart", "bald", "tall", "rich",
"Don't ask!", "How should I know?", "Stop asking!",
"Stewie", "Peter", "Homer", "programmer", "system manager", "You"],
n%7
? ( p=s[n%7+13],
n&1
? (p>'a'?'The ':'')+p+` ${s['2011'[-~n/2%4]]} it!`
: `To ${s['5344'[n%8/2]]} the ${s[n/2%5+6]} ${p}!`)
: s[11+n%3]
)
```
```
#O { height:300px; width:50%; overflow:auto }
#I { width:2em }
```
```
Why(<input id=I>)<button onclick=test()>-></button><span id=R></span>
<pre id=O>
```
[Answer]
# C#, 502 bytes
This project needs to have the **AssemblyName** set to **why** which will produce an executable with the correct name.
Fully golfed:
```
using System;class W{static void Main(string[]i)int n=i.Length>0?int.Parse(i[0]):new Random().Next();string[]s={"Don't ask!","How should I know?","Stop asking!"},v={"To please ","To fool ","To satisfy ",null},a={"the stupid","the smart","the bald","the tall","the rich"},p={"","Stewie","Peter","Homer","The programmer","The system manager","You"},e={"suggested it!","insisted on it!",null,"did it!"};Console.Write(n%7<1?s[n%3]:n%2<1?(v[n%8/2]??v[2])+a[n%10/2]+" {0}!":"{0} "+(e[n/2%4]??e[1]),p[n%7]);}}
```
Indentation and new lines for clarity:
```
using System;
class W{
static void Main(string[]i)
int n=i.Length>0
?int.Parse(i[0])
:new Random().Next();
string[]
s={"Don't ask!","How should I know?","Stop asking!"},
v={"To please ","To fool ","To satisfy ",null},
a={"the stupid","the smart","the bald","the tall","the rich"},
p={"","Stewie","Peter","Homer","The programmer","The system manager","You"},
e={"suggested it!","insisted on it!",null,"did it!"};
Console.Write(
n%7<1
?s[n%3]
:n%2<1
?(v[n%8/2]??v[2])+a[n%10/2]+" {0}!"
:"{0} "+(e[n/2%4]??e[1]),
p[n%7]
);
}
}
```
Example input/output:
```
>Why
To fool the bald Homer!
>Why 1
Stewie suggested it!
```
[Answer]
# Powershell ~~437~~ ~~461~~ 453 Bytes
Edit: Missed the duplicated verbs
Splitting between the corpus and the calculations for byte-count
* 267 Bytes = Pre-coded text (excluding `to`,`the`,`it` and `!` since they have fixed places).
* 186 Bytes = calculation
Sets default argument to 0 if not specified. If argument is `<1` then it gets a random number `<99` `fn:1` and reruns. Technically this means `-50` will work as well, being treated as a random case.
```
function why{param($b=0)$p=@('Stewie','Peter','Homer','The programmer','The system manager','You');$e=@('did','suggested','insisted on','insisted on');$v=@('please','fool','satisfy','satisfy');$a=@('stupid','smart','bald','tall','rich');$s=@("Don't ask!",'How should I know?','Stop asking!');if($b-le0){why(Get-Random 99)}elseif(!($b%7)){$s[$b/7%3]}else{$n=$p[$b%7-1];if($b%2){"$n $($e[($b+1)/2%4]) it!"}else{"To $($v[$b%8/2]) the $($a[$b%10/2]) $n!"}}}
```
Explanation:
```
# Any -1 in calculations is to account for arrays starting at index 0
# Final key placed in position 0 for indexing (4%4 = 0)
# Powershell 1 = True, 0 = False
if($b-le0){why(Get-Random 99)} # If not positive, choose random number
elseif(!($b%7)) # $b%7 means special so use that
{$s[$b/7%3]} # Divide by 7 and find modulo, use that phrase.
else{$n=$p[$b%7-1] # Get the correct person (Used in both types). 6 max
if($b%2){"$n $($e[($b+1)/2%4]) it!"} # Create type 1 sentence
else{"To $($v[$b%8/2]) the $($a[$b%10/2]) $n!"} # Type 2
```
`fn:1` 99 Chosen to save a byte. If there are more than 99 possible sentences above (did not calculate) increase to 999 or 9999 as applicable (+1/2 bytes)
[Answer]
# MUMPS, 379 bytes
```
f(s,i) s:'i i=$L(s,"^") q $P(s,"^",i)
why(n) s:'n n=$R(840) s p="Stewie^Peter^Homer^The programmer^The system manager^You",e="suggested^insisted on^did",v="fool^satisfy^please",a="smart^bald^tall^rich^stupid",s="How should I know?^Stop asking!^Don't ask!" q:n#7=0 $$f(s,n#3) q:n#2 $$f(p,n#7)_" "_$$f(e,n+1/2#4)_" it!" q "To "_$$f(v,n#8/2)_" the "_$$f(a,n#10/2)_" "_$$f(p,n#7)_"!"
```
When no input is given, a random number in 0..839 is generated.
Usage:
```
>w $$why(15)
Stewie did it!
>w $$why()
Don't ask!
```
MUMPS's left-to-right evaluation strategy saves a good few bytes on parentheses here.
Side note: see those strings that look like `"foo^bar^baz^qux"`? Those are so-called "delimited strings", and are the standard way of storing lists that fit within the maximum string size limit, since MUMPS does not actually have lists/arrays (or, indeed, any data structures besides trees). For lists too large to fit in a single string, we instead use trees of depth 1 and put the values on the leaves of the tree. Fun!
[Answer]
# Emacs Lisp 473 Bytes
```
(defun why(n)(if(and n(> n 0))(let*((p'(t"Stewie""Peter""Homer""The programmer""The system manager""You"))(e'("did""suggested""insisted on""insisted on"))(v'("please""fool""satisfy""satisfy"))(a'("stupid""smart""bald""tall""rich"))(s'("Don't ask!""How should I know?""Stop asking!"))(q(nth(% n 7)p)))(cond((=(% n 7)0)(nth(%(/ n 7)3)s))((=(% n 2)1)(format"%s %s it!"q(nth(%(/(1+ n)2)4)e)))(t(format"To %s the %s %s!"(nth(/(% n 8)2)v)(nth(/(% n 10)2)a)q))))(why(random 99))))
```
Largest 'waste' is probably the `format`,`%s`... sections. If variables could be inlined into the strings without the specification it would save 10 bytes on `%s` and another 12 on `format`
[Answer]
# Ruby ~~396~~ ~~378~~ 372 bytes
I'm sure this is not golfed to the max.
```
p=%w[a Stewie Peter Homer The\ programmer The\ system\ manager You]
why=->n{n<1 ? why[rand(99)+1]:n%7<1 ? $><<%w[a How\ should\ I\ know? Stop\ asking! Don't\ ask!][n/7]:n%2<1 ? $><<'To '+%w[fool satisfy satisfy please][n%8/2-1]+' the '+%w[smart bald tall rich stupid][n%10/2-1]+' '+p[n%7]+?!:$><<p[n%7]+' '+%w[a suggested insisted\ on insisted\ on did][(n+1)/2%4]+' it!'}
```
Edit: I've just realized that I don't know operator precedence. Oh well..
[Answer]
## CJam, 281 bytes
```
99mrqi_])0>=i:A7md{;A2%{S["suggested""insisted on""did"]A2/=+" it"+}{"To "["fool""satisfy"_"please"]A(2/:B=" the "["smart""bald""tall""rich""stupid"]B=SM}?[M"Stewie""Peter""Homer""The programmer""The system manager""You"]A=\'!}{["How should I know?""Stop asking!""Don't ask!"]\(=}?
```
[Permalink](http://cjam.aditsu.net/#code=99mrqi_%5D)0%3E%3Di%3AA7md%7B%3BA2%25%7BS%5B%22suggested%22%22insisted%20on%22%22did%22%5DA2%2F%3D%2B%22%20it%22%2B%7D%7B%22To%20%22%5B%22fool%22%22satisfy%22_%22please%22%5DA(2%2F%3AB%3D%22%20the%20%22%5B%22smart%22%22bald%22%22tall%22%22rich%22%22stupid%22%5DB%3DSM%7D%3F%5BM%22Stewie%22%22Peter%22%22Homer%22%22The%20programmer%22%22The%20system%20manager%22%22You%22%5DA%3D%5C'!%7D%7B%5B%22How%20should%20I%20know%3F%22%22Stop%20asking!%22%22Don't%20ask!%22%5D%5C(%3D%7D%3F&input=21)
Haven't used CJam before, so I'll take any tips. I'm sure there's a lot of tricks I don't know!
(I couldn't figure out how to name this as a function called "why" - it appears that functions don't exist in CJam - so I'm not sure if a CJam answer is okay or not...)
[Answer]
# Lua 5.3.0, 452 460 446 bytes
This is my first attempt at a code golf, so please correct me if I did something wrong!
```
a={"Stewie","Peter","Homer","The Programmer","The system manager","You"}b={"fool ","satisfy ",n,"please "}b[3]=b[2]why=function(n)pcall(math.randomseed,n and n>0 and n)n=math.random(1e9)q=n>>4r=n>>8return 1>n&7 and({"How should I Know?","Stop asking!","Don't ask!"})[q%3+1]or 0<n%2 and a[q%6+1]..({" suggested"," insisted on"," did"})[r%3+1].." it"or"To "..b[q%4+1].."the "..({"smart ","bald ","tall ","rich ","stupid "})[r%5+1]..a[(r>>4)%6+1]end
```
Ungolfed:
```
a={
"Stewie",
"Peter",
"Homer",
"The Programmer",
"The system manager",
"You"
}
b={
"fool ",
"satisfy ",
n,
"please "
}
b[3]=b[2]
why=function(n)
pcall(math.randomseed,n and n>0 and n)
n=math.random(1e9)
q=n>>4
r=n>>8
return
1>n&7 and
({"How should I Know?","Stop asking!","Don't ask!"})[q%3+1]
or 0<n%2 and
a[q%6+1]..({" suggested"," insisted on"," did"})[r%3+1].." it"
or
"To "..b[q%4+1].."the "..({"smart ","bald ","tall ","rich ","stupid "})[r%5+1]..a[(r>>4)%6+1]
end
```
[Answer]
# Python (2), 692 bytes
I’m still learning, so please be gentle! :)
```
from sys import argv,maxint
import random
def why(*O):
P=["You","Stewie","Peter","Homer","programmer","system manager"];E=["did","suggested","insisted on","insisted on"];I=["please","fool","satisfy","satisfy"];Q=["stupid","smart","bald","tall","rich"];S=["Don't ask!","How should I know?","Stop asking!"]
if len(argv)>1:A=O[0]
else:A=random.randint(-maxint-1,maxint)
if A%7==0:print S[A%3]
else:
M=P[A%6]
if A%11==0:
M=P[4]
if A%2==0:
if M==P[0]:M="you"
U=I[(A%8)/2];Z=Q[(A%10)/2];print"To %s the %s %s!"%(U,Z,M)
if A%2==1:
if M==P[4]:M="The %s"%P[4]
if M==P[5]:M="The %s"%P[5]
C=E[((A+1)/2)%4];print"%s %s it!"%(M,C)
if len(argv)>1:why(int(argv[1]))
else:why()
```
Works with or without an int as a command line argument.
I tried to emphasise code correctness as much as possible, as with generating random numbers from `-sys.maxint - 1` to `sys.maxint` and displaying sentences in the right case.
The code relies very heavily of if-statements that I’m sure could be replaced with something more place efficient.
Feedback is very welcome!
### Ungolfed (1341 bytes)
```
from sys import argv, maxint
import random
def Why(*Optional):
Persons = ["You", "Stewie", "Peter", "Homer", "programmer", "system manager"]
Endings = ["did it", "suggested it", "insisted on it", "insisted on it"]
Verbs = ["please", "fool", "satisfy", "satisfy"]
Adjectives = ["stupid", "smart", "bald", "tall", "rich"]
SpecialCases = ["Don't ask!", "How should I know?", "Stop asking!"]
if len(argv) > 1:
Argument = Optional[0]
else:
Argument = random.randint(-maxint - 1, maxint)
if Argument % 7 is 0:
print SpecialCases[Argument % 3]
else:
Person = Persons[(Argument) % 6]
if Argument % 11 is 0:
Person = "programmer"
if Argument % 2 is 0:
if Person is "You":
Person = "you"
Verb = Verbs[(Argument % 8) / 2]
Adjective = Adjectives[(Argument % 10) / 2]
print "To %s the %s %s!" % (Verb, Adjective, Person)
if Argument % 2 is 1:
if Person is "programmer":
Person = "The programmer"
if Person is "system manager":
Person = "The system manager"
Ending = Endings[((Argument + 1) / 2) % 4]
print "%s %s!" % (Person, Ending)
if len(argv) > 1:
Why(int(argv[1]))
else:
Why()
```
] |
[Question]
[
# Introduction
For many centuries, there has been a certain river that has never been mapped. The Guild of Cartographers want to produce a map of the river, however, they have never managed to succeed -- for some reason, all the cartographers they have sent to map the river have been eaten by wild animals in the area. A different approach is required.
# Input Description
The area is a rectangular grid of cells of length `m` and width `n`. The cell in the bottom left would be `0,0`, and the cell in the top right would be `m-1,n-1`. `m` and `n` are provided in the input as a tuple `m,n`.
By using long distance geographical sounding techniques the location of islands around the river have been identified. The size of the islands (i.e. how many cells the island occupies) have also been identified but the shape has not. We supply this information in a tuple `s,x,y` where `s` is the size of the island, and `x` and `y` are the x and y positions of one particular cell of that island. Each tuple in the input is space separated, so here is an example input:
```
7,7 2,0,0 2,3,1 2,6,1 2,4,3 2,2,4 8,0,6 1,2,6 3,4,6
```
To illustrate more clearly, here are is the input on a graph:
```
y 6|8 1 3
5|
4| 2
3| 2
2|
1| 2 2
0|2
=======
0123456
x
```
# Output Description
Output a map using ASCII characters to represent parts of the area. Each cell will either be `#` (land) or `.` (water). The map should follow these rules:
1. **Definition.** An island is a orthogonally contiguous group of land cells that is bounded entirely by river cells and/or the border of the area.
2. **Definition.** A river is an orthogonally contiguous group of water cells that is bounded entirely by land cells and/or the border of the area, **and** does not contain "lakes" (2x2 areas of water cells).
3. **Rule**. The map shall contain exactly one river.
4. **Rule**. Each numbered cell in the input shall be part of an island containing exactly `s` cells.
5. **Rule**. Every island in the map shall contain exactly one of the numbered cells in the input.
6. **Rule**. There exists a single unique map for every input.
Here is the output of the example input:
```
#.#.##.
#....#.
#.##...
##..##.
###....
...##.#
##....#
```
Here is another input and output.
Input:
```
5,5 3,0,1 1,4,1 2,0,4 2,2,4 2,4,4
```
Output:
```
#.#.#
#.#.#
.....
###.#
.....
```
[Answer]
# C + [PicoSAT](http://fmv.jku.at/picosat/), ~~2345~~ ~~995~~ 952 bytes
```
#include<picosat.h>
#define f(i,a)for(i=a;i;i--)
#define g(a)picosat_add(E,a)
#define b calloc(z+1,sizeof z)
#define e(a,q)if(a)A[q]^A[p]?l[q]++||(j[++k]=q):s[q]||(i[q]=p,u(q));
z,F,v,k,n,h,p,q,r,C,*x,*A,*i,*l,*s,*j,*m;u(p){s[m[++n]=p]=1;e(p%F-1,p-1)e(p%F,p+1)e(p>F,p-F)e(p<=F*v-F,p+F)}t(){f(q,k)l[j[q]]=0;f(q,n)s[m[q]]=0;k=n=0;i[p]=-1;u(p);}main(){void*E=picosat_init();if(scanf("%d,%d",&F,&v)-2)abort();z=F*v;for(x=b;scanf("%d,%d,%d",&r,&p,&q)==3;g(p),g(0))x[p=F-p+q*F]=r;f(p,F*v-F)if(p%F)g(p),g(p+1),g(p+F),g(p+F+1),g(0);for(A=b,i=b,l=b,s=b,j=b,m=b;!C;){picosat_sat(E,C=h=-1);f(p,F*v)A[p]=picosat_deref(E,p)>0,i[p]=0;f(p,F*v)if(x[p])if(i[q=p]){for(g(-q);i[q]+1;)q=i[q],g(-q);g(C=0);}else if(t(),r=n-x[p]){f(q,r<0?k:n)g(r<0?j[q]:-m[q]);g(C=0);}f(p,F*v)if(!i[p])if(t(),A[p]){g(-++z);f(q,k)g(j[q]);g(C=0);f(q,n)g(-m[q]),g(z),g(0);}else{C&=h++;f(q,k)g(-j[q]);g(++z);g(++z);g(0);f(q,F*v)g(s[q]-z),g(q),g(0);}}f(p,F*v)putchar(A[p]?35:46),p%F-1||puts("");}
```
[Try it online!](https://tio.run/##zX1rVxtJkuj3/RWCPcYqqeSWcHfvDEXhQ2M8w7Yb@wKe6Vmvr44oFVC2XlRJ2G7M/vQ7Nx75iMzKEtjdu/fOmTaqzMjId2RkvDLrXWbZP/@1mGWT1TjfrZbjSXH@5GrvX2RSMfdSymJ26SRNimmxrJykbPl5kfuYRuVlDfls6Sc9pAnjcX5BSfC3mOWt10cHr073z4Ynh4fHZyf7x2fD/ddHtVxIG/7t8OT06NVx688/PK3lvzn@@fjV349b/VoO/Hd0@uJo/6eXh61BP1BQAmz3/wV7DzAtGKxVtmy9LrI5QOi/STafVctWdjUqOwtIqkbL4U1eVsV81r6ZF@MoBABJF8XluvzF57K4vFoqEN0E/Oq0Ddh0NJnMs4iAOnFV/JYPl43AZe5AyzLBorbkRZnnoWJRosbAQBazQjfZz5qavE61HC3z2O1E7DUzdipPsFzLglT5sq0r8DIhazhfLRcrCxG/OHp56MNN81G1KvMh1DbM4J9qHcJFCWvkk0UopiwADdN/Pq@K5WdbALZGa5Z/tFnDSX6TT0JVTUbFrF6Qkoc3o8kqDxS6nMzPR5MhTN1oNQEcV6Mqd3AEyjjAw0mxdCuFBPpL2aEJ4IKNw8YwVTYv18FM5zdQdz4qZ/nY1r@aVcUlpLQWeZnls@XoMtTpKaAeFtPFvFyOZstgDwKlJnlVfV2pKZSAFrhg3kTKFXExXcZPnjwJ1F3lwV6Wo9l4Ph3OVtPzvBxe5rO8HC3nJYFHCU2CQpLPRucT2HnlKMs1IBKaNUsX6CwMMw7iZFiuFsOLYpJ7OwOTqFNTXm4@lhHM0RzIUTEDHNlktFoz7VzlMi@hLjGytO/zT5COOJgAAFi7Y2Chq@0AVOQOAPQGCMYn2AilaIGEWKyqq4asixF0dIzEdwmVBKZdAvtQXi3zReMIwOKaFBefm/JH4/eryqsdu1SMP7l1QB8LnO6qoQ0jODjH6yaGqbRdx1DJ@edlXg2JwsLgjgXweL6CugzwspjmOAPThaLnbh9hamRNZilP5rNL/seMVDlfjC5pmT6wxDjPiurh4DcA7DTG60mVw1SO1wziPQsBIIbA7Fgo2ts@xES2ARF1MMUbtkWJa37tsTSqqtU0v48kUZvG8xr1ctsF/7mI9MgOickLnnNmshgmQK3sDCgsssqycbWOczhD7xlqghku5wuiqQ8CXozKZTG6DxbIBqynolrms@V64kDjv3CIqkXJRB4nt7GU7H4dfLqqgrCxZa7aHc1q2eIRz20A3@hTMUVSCVNWXRC1GFarc@KBLh7cqhnQuT8UFbB6iArO/jLPlnDD@AZMVysYLHeA2h1k1M5H2YdIMpJ0Zk2zin9QuSi2@R5ZvxrNLh3C5xJ9aDDRUXf2izrYAxiHj2WxzJku82j4By8m0YEcLjifLkbZkk97ryRzAI1F8Qyd4enwDWWRSbivmBwMGKxxeDDM1ep4//mB@fjl6Pjk8PRs/@QMbl/2@vXL/q8iGf9nsk6eHx4cPT@kdJP4wkAPnMTnbw4Oa2n7z/@9NdgeyMoOjl6eyuvfixcvj16/PnzOtdeSX58cHuiG2dyj47PDk5M3r89eHv0Cudvf2y6/Gv50dLx/8o/hwcv9N6eHpybn5au/tLP5OI/G89u7j1fIjvUjUW59/qvjl/@QEPg3qYO92H95ethqt/82mkS9gU1/c/z88IVKF@BnJ280tAA@ePXL6/2DsyFcwg8OD/56ePAz/xy@@OVM3KsPfz07BLTPw3B20GGcRPq27fLh34/bi3iG3WkvohSuO@1FRXfM@UW7A0lRpz0DRrDezYOXJ6boNJ/itRDA4/5DC0O2QiG6/fzw5SH0SOMd55N8mWOLFgG02OB@ADmszqP/ICTzyRhZ@xhvcfAXUSrGDHPwZ@qiVQUM/4YFA2AaHzUBzl3IxEZi/zXiWBcNdf/w@OX@yV8O20Aky2V8lY/GMdAMbJ456lVL0vZiWY6LCziao3YbgXpcKnLaiJCqxLP2dkd3Y2dgubdsvpot0zZWZnAkeqjUd23AEoZPVX6XkCTUDpOmYJPQhoLNedaeRDA4vT1kyrrtwf9uQ0JPJ0SRBQfY7aPnvyK802sJ/t22B//L65enugbk/qGKprJeyWNqWRuP9zYmnP7lGBI6thVeAc5vN7dtaxA96w12Bm6xv@2f6PbBraLqCvwO3F/PXpuOXC0XD@7Hv//9r7rY@49X3XWgz2Ud4/sq0QKpFYwQQMFK@3s5tgfL0SmgPDncP3113D6I2oOtNmRHB26NKv8lID@YVMBeDbqwPNsv5fzLjYvQ27hmAGP7ZQHsl1g6qgJYAnInPX/14gCWQAYFiPFQBeFvFumS@Iv2oi14@uoAqC4in6vbW5rSFy34Z1SrytiRUKJqxEBwVMSu@l8PgBDgOom6g2aklC0OF1gTtC7wLopjRD8AQg6oB6IgnCnR2fTvlsyEwq/c7O@2ex7ASx9AdPfX169Ozmy@qOxZ2ynbbZs@95yhi3acRrhthxycx0KgXjcNbyEb2r9hYN@5uP7jr8cBXL9djYpZxWXf7fQjeSKdbp@dPKd11D4rx7R@nPMbIRAVQTggQHmgOw4gnN0EuJ/hGharVFQJlIHW@o1Y5DjxN7wNkVp40CfHP2vocvYBt0QYFuAIc@lhLhkay3rQSKVKQaWaYH96@fMQWNKXw5/@cXZ42vqT3U9wjgxfvRgCQKutTsufJh@inlvCYnp9drINebRph0Bf1P6ln8@wKO7kNst5bU7UExVFO@Kw2f/b4ck@nKmj@BwKngOOdpvFEdEo@k7/hAwo9USUe314cnAIZwGVAy7zSb8jUYkKfoL1355Wl3hOXyxWy6q92el0NDO@09qEvM3/nG3G1RIuyGWUjM7n5bIdYgAI19GLNopHYoWyuGhvUEIUnZf56ENiKwxg@I/Dk1cvXp612v1PijPur8RmfX3qZg5E5tHxC5V5of4nMiHnYP/k5B@t9mC1u7v9g5Pzy@lPKv17N33/11/2j8@OTk/3W22GkzuHIDi7PYbJGUdbbiEHFAnNMc7IWJ/O8GtvD6rsDbb/5GI9OtbQrXY9d/9XmzvY/jexQ395ffr3/dcAQ3MMg/9ismwtp4sEJqHdHkW7uE6iW0hJ4SuB/1JISeC/FKHu6vPx5hj49Z8R4yqexnQ/aE@jVHZ9BQhySjJdxKRp9CXlMQtM89Hx6SGslFfHw1NYDEO46xydyasTph4d/2WI3WmfAZt8jTWfYV/STvs6SvCfFNnWBP/h1tdq0VhgXDSmbLrQ2HBM4BOpQ4xIYsQZ7fWjQOUB5P/rzdHBz9T613BnPMLOKPyjeBKX3N5FcTNf0t32fVKkyIkMkvcpEKGEcnAW3r5/l1zMy3aSRLdciWkV5na7xbuYgKPdfpR4EJRBcL3e@3cIAb16n2JNarfBd7GXvldfXtegYLegf99DFxszob1rR8D0m243dFlP@3GZwnWmN4BlM4HxKOMC21L2JrtpaPZVA/VIwA1h0i3hOAs1eUr/lrAXk4YpxvzJ10CthQEcGqp51gEgnnQHMVWIow49LXtFdDuZpEV3kJRlWiZlWsAKuMsnVY7pE0zFFAa54wHaC44Prle6DSADwvxXPi8ifeeirNm4yHJYFRos1lBJx6R1u@lkkvxxyMqS@9PCxkPrm5o/wWpLB9yg2RMVRrdl2un1TB6MjfPJpXm13N1HWdyVKfejXKFF/J4WXgEzVOzB4PR60ZrlUKjlACPBpSbd7aTYxcLdbnT7Pi3E7i7eNe/Z970B7dlbJgOpTkve93rJnUrkJt@FqZvXv85oRISdxJYz7F1S26QAC8nhYeK8elV/P3l@@h@G/0FJfdT5k7hK6cs4HDdG4Y9HD7CJiWfrABwQ/ucnwzUK//OT4cqD//nJJ7MP@J9NVrIA4KpafxtNfPC/UXJZQ778gP8l9vOWrlgkAPAkDDs0BGn6dPvZ9r/tPN0W6qMxDovI/wGz7xLbg1toUusGmmUSoTFWJDIdlR@kRKPMq/nkJh/LNFKMy4RRxT9kGopN5TdrEmQKqUZno4lfKr@oVRBKm1bVYl55KbP8UqaQsNyDojQPTmlZZBKpaBK8UMPmruYzO14w17ewllqk@xc4oJqnfdEayDV6eBdzVckMgxgqsxOB8yinfTLJMw8NWRU4SfPsQ3AW7PX2OTBsf3n55rC1/YOUFlNSuz3Y3TUQdC8ziC4nq3zH5NG4oC7k7fa7BJcp3n7wt@kL7Kpb2gHj0XL01r2fIFg@W01bp6i/uD05PD08AwJ4crj//B/pID7dP0u3YzJTSp/Gys4p/T5WhV7jQrh9/er09V/3Tw/j48O/8I9///tL/nFy/Jx/mMYo0f2trbRFqhOBsKXMRWiZMU0eVaRiJOsZVPxBbkKagvlqmbA5E5nNJI69BOsO0JrFzsLLw78dvhQrgxX8iTPXmFKZsUxgU3YoBVZbB@@HCZCwzvuPVzT0HZQr8S8SMSVALjokmcPEFv6KM/yXWoM/YMcXY06jn1QT6jyKSQx/6UjtdHI4C@BrqVLxryAuI9SvorgYdwaVH02AW8V/VXn4pcrmc/jNQHAnh4TMAOVz@I0N65QFlsd/OSuf42/KyigrE1mZzrqgWi9GNgt/U9YUKFFc/YZ/@LuqVAr94LSM0mbqL@RlJo9oAyTRX2p9TQFKIworvxxlS8yAtVFXktKsdaB5C@jvlem3mjwtX4G0ucmbc97E5k1U3uGrl9S4ypar5rrr1ZwahDYsaCnBq4@pGS/WcrWgRPhLR0k@1p/G/kInKPTUkOky48XUQVu@SQFnJ884GmXgTJuGj2itdvDgoJypyZlyzvgCezM2yWPuqT5ZIK00eWJT0A6jtQbF@a/uNH8Z0M4YyVzMfzQMfXjYzlcXF3kZd8410HmChPymmGXxhMh5XEzoq7jAP5SbUS79W/CfC/xX7N5ydqn1BNmqLPPZku1QdKIxTNEJZZ59zmDJaFMOZcIRX0zUL52R4xEpuzHTKWRVwyZ@sATRmqWYTYpzpkvlBMg6kmNaGr/RZ3xy8OrN8ZnGzEO4morjeKmsrdR6yPGEqgwppDnK5fygUaE8opVVi8M74IqrJKGbLsTnhbYlEq2oJ0F3gYi7qCeUmNcS2Pgomy0bcpyJo25Rpl7jsgY@TB08Hi82WZ1/dquCBJhsIJHLEQ3cx1HlpIWMTOodFjZAwrgoWDgMAIeSbDnTJzpW7DiHEvNQ4sXEm2lb/cWETGR4maluFLAZmHEFkiQaQZ9Dn6upDbsyS6vqbKJImmlKKJImtaS524@J@zknSiYXg/ddA/Ah6LNW641Ld6jWGmo9gGzbJTgDtCyBIRp7jZ3NZ01ZcjaKBR9j@rbcKTShK8REjBkwgIHnyMvmxBrPAu0hSLjEJGzXOL0sE9foGehX/jHxLJ9bOStzE2kB3cpZDa04tltr3pKQGeXFakYkQBnGwLXQGFYCM6mvUsZ0/TTBskVG977FKPtwMVm2bdPJhCOPSCAJjUngv3T6pW0gonbeRUEnyWAhd7kqZwR4J9CeA6O4HcaLUuZppMopITIKOaa7LIOMblnil@@mroBVl2HRcpLDzXu6u5sO9C3YIFBSG5W6l2qJMtWd76WuZFajZaF0kne7yXRvD9HeTbfS/1KCUQWkhwsFrE6HYRVjOv2MaQQieW@Mp@expXz5KM7PE08GjGOwca5bM0qsPBdKQ4FRJJLOEWEOhQhpmo96gBAQ0Ofu0@1oeg594BpJCjM9T/tUw1RUMR110ymVm4623FEapfcM0wjHacQDBaVTV55eGy/ugByx6Wpyz4iFduEoy1YPHUO9uB42ktCjFDDin@3vExqDvbVDQCC7a9cotjadjuhvB4caf8CYcQX0kX7DuCssgwASFxpmJqURwxlqWsr1qRlVWVHQ9hWW7UB8mCgs81lq9vegH/cjvH615rMcLSyvbN72j3/6/ukP3/8Y94BcJIqepGpW4uV0ESOo4wKTQi00vdkVcGtpZwG9hU5mVxvp4yePmXgU1bi4LKBtV5HXXURvas@ueo/7j2MhiWd8EWGBD8JoRO/3oFWrFX7G0MsoQfVGoCoEVaSAQKcLGNk7Ud@t6NWaKhF1qkeUKlMNqNdJgxiuOdTx@yoV9cS6AdE3t@DuLnBAENc8v9w22z@6VVBSMzWKurBNZJlsuqhRDNwBu3rH93hH7BkKMNCLvW8Q0RGJVmavTzvK0Gy4JCFDpE2z@DqCCmCijRuUaRBRLpljdYUmWIvp8VCPzlP9k9Pg8I@pWMTE@DxlFqCtErUyduM83pyvYCtdwPVlOi8/Q7dbjwHN480oQUzODapLjdAVO1kkpTc3q8j5SmvQepDOe3sokHKGqqUs4Hi0aPC0KvxBY2f05mqKk7vztKZ4r/etx327Z6y5bZH4LcbbGXFko1B/6qwCZTe3pmvGls6zxoukFR/VQwZrsvMP7KaugfS@BptJhj1rErupHAMkKm1TaWpaFpk0F16PGXdaL1FjOmhGLdAjs2oVkwpnpsjDWbbjYvfb@kXNFTesa43uv3FtyxvUtv5oE2XSnWhPdvvRs0F3u9Ob7Gx3JqYs3uCwGBk@0@JxyrWMxYuDexI5CDr5bIwm8eQ7QqIkUy9bj2UKScaWY6FdaVwTsRFM3bFuTlUUKxEmrCYvhmN2ks/aAro74Kngz9QlmOyFKCqLfcbAbRC0RiLTRr1cKcJjbfA3W3xuu62ygwT1WK/RBS5O7/60ALS@52hrwQvL8SBtLRShuKW2Q8tSLPtsQe1CzKwuw0HcUZTZpljqDF3YZCFAazlvaT8qvaov5qW5Y01Hs9FlXsLqVobJULQvakn0hksXdDFUpwU1KxEbM13o66AlcanqDaUZ4Tgwg/SNt8KUlAb0LQX3qVYCUI4QW6W9bUoSt9b0zdHx2RDY0IQNtNWKjrc7Tq2RzX7/8WpNLsrh12SP78kn6f2afPyMmzJRQeBnSvU5SaLph9CdX/EcUVKqobo8yCj9FBww8n3USBKLppZ53hw86f@gKBxLUGWpP@tiEx9fT2dl4YpIxOrV0x/oivxCtp6sqR5fPpjWErHkoN9naClXS/@rv5pMKB2IPLDvY1QACXKBmyZrqcYZRVDKqEgVBL/VLtnSc22N@HVKpDoBP5/Qzth2CmVrS2Wy2PptoTfQ/vN/mG3iK7qgwYbSG3Il@Z@hdiMiUulosmJfRWlYCS1rUV2AI4FYaubyOiqVLJIxuZduu2lA/BXGrS3M2NuOTGkA2s@WUcLenIsqJLVhpeXHb2o6n7REqNG8i/XCleLenBFRHHesMdDFQh0Pip/AMUAs2Mk94/rAn6pYqv5yolL/0qwgDImm9RcKHFny4Y8OqqnhwqltZUusG771vktCNxd59joDpQ5wZzzC3VfHOf41g2CP6EyPQnONlT7uSVG0IMOWRXr66iBZbKSH@CdlA3A0MOssIre5aEEH9zLj5iIsmhXlm7sm0w7oRIIevlJW9AbUWF0rM6V5aqzTU1XCZyyAysAwmHFEVW21/EC8DPyl/VguI90GmxSjOp6/2awjisxhC6nCCwjReeOpYkjwMIrj/csXSwL4EI03918ftVYYAmCHi7U@Fssr5GeROSlGk@I3IoSbehbNLOExbwVahTJAIvMjPsiU1BgOFTRGMgOhGDV2JSmg5XICSN4cm1/Kv0dChE9SCTG@H6ThvHWWQpAdkBBBjkAChE5tmR86uGU@K@h5qS17JsUbD326w5ne0wkuCKrMGQJ@9VSKC4JqegbJFAikeK0tDBr82dNpLlRmoTINldWgLmyTLnSbLmqNIoU@jQ8p9b1M1u6rbPrwADIJkNUBWN/P@exY644aKbvVuPVMit9EUnwz1LRnk7wleaG7yw4b8O0NrtaHqwHuyURvYbJWnAH5o2fTvXpJN65qxt89k@oCKuU4Q573bJK3b4QlZj4vetJY0gGsPKJbMdWtLNmtX6jcixyrsfvv1ATRZxhm4ME8RHpiXDDptmJFKPh1h8r0GVsJaYq65MgbTMPZTMeYwS6l5epSCPnZhIbdAgmQvu1GTlxID1DASW7eEoWlYOeXfDhRwdSAdS1em73t53MLk7uOQYqGucXSPVPYzG/I9nBqJMhOKbZmctGt4cBucPliWqot6ALIVCgfd1SFucNHhoiL8Se2iUqNvx8FQVDyALKw@vJlg0mp0URHtwZDav0PoeBen8pCE7XtYnRLZVk52kvFx3faRxpLGHwbKRTm4EGyZDeVHtW2KJE3Augm0JfUeCiqXkDarndBjfwLK44B@09fUKQNXntwUMebjyoF1Ho0Ru8YIXEwfphQE3IJd7rdqelLIsYBlV0AikfXJEW/6UR7mEJ5TiXn6@AeYSTudDqLIzCFN4pupWYeE2dtACaCc1cfijNjhTXhrakBvYYpsTqHkxFN@8ANjMggdpR@oL7F5@mEftBiW8WdG2UMU5HYPU3JwXxr63yDf7lS@Q2TnTrZrUGyMp3@AF22IxDJgigeq1I9IL2V@kGuCkAwJbeOgEpZoJ3WVuiASUZM1o1NpUQBFOrnqnfjbsxqXi6XH8l4gsV0NxFZIo/SG6TFnXP4O3iXOFqJBLPS8wRz0lFwaSBaDiJjZgAIh3P7YpYYr0PpdiSbcaPoM1mHY8nYTCisAuUALi55wMMiDRBVjejfc96qdFUmi9U@ttZNGmA/ZOVOtr2ikxVlqrUv5lof4MJtU2z1XLrvtzpb1@ws0O7snoZnXsuzhqZnDW3P/MZnodbrLbZYllLVMOE/H8SZoMS/yuVwEvXUrw81XMAZt8n2NcZ/lei3BIIozarhpuulOBuyDr7RAN8ieMTvWGcTfifFga@DbzTAm/bQdtyt9L4M5e55uUbF19Nj3I/L2L9AX60WauxxvGDP4kCuFnOYC/iHDFJXCf6kcwtSWHOKKXsDOHIpB/75bhtolb5EvMVk2ut6SlbxDR6erFM2YFjwXbpKVoSa8HBdWD658@BukhsBJ7cAxn1Sx3eBkcyM/EEHf6qfOBgparbMM@DvZktXVAHNlg70mVYGU3/S1OxZkUwspWTmSscNyeHRS8F8lcoPqVS8U@YxOxxBq4F7HMkKR06F9gYyErWNVG2jJk4Nz0O8TQ5H1ZAvI5JdMxVPZcVTp2Jxq5mKmqeq5qmq2Ts7sBTHrpO13TA6lN/X24XEwqXeOCXbDpNpBgx/zIE/LY0Ajr5Sn6qTMKxYpillRyEgOMLwDBUBFBSfw0VISKdo96KKmsSJakFgTC8OlDhczfx5dhgg15FnqBcUm0wuyAZ6Eqs@GhZELx/DCrmLHpI1J@RihRH3mC3AnkqtnC7HEjb@YsFHstgF4ASNKm55/DoLwcXwKOE4r9L0JkKzzWK2ygNNW@lrgN864ITJbMRJ3IOj/5aYFbo5OJvUnQ/KDxMMqHWgWB7ukGYqblUxucQM27iGwWRrO7tXzdZMLMGQ9EFIVus3H2DKa1uETjq@JKDtLgxNmVouLtFHQ2rtsvybjqVheIoBYdUpeDDgCvHOCxin@k7lKxHJBjRjp@TLSi2Ev3HeAjc5WEKZw2AHeX/FxqtRNwPskWqVbObLzjyVUjtVhDLRBaCTDfcjrheuR63Rkq3f8ff551bjZSk2F5IoGa@mi2xSzSZis0XJustopAeYCZyTt7UlFyYev@aiHCQn3mDdhUfry5f6prnllWs2NisOBnJvGKWB06Ztun0qI3i1U@/bk27/1TJ36TsLxOuSFHNko/sKcAZtZRqAnG5Kg0ti81SEI8JEGclJB4TSVhUblRat35KeVH8iaeBRUYVSlrNbKTuWJqULCmNSBUWiBNavdVSSiexkUHvNiBKDFYfwTsO91di73Xep7ilxWs44AVGd5dlyiORliGKa8JiRkoTup5mgdBNxJ44zfYAph2UeSI5UpFauHfANGvBbSCAPP7hXAHYup9P6lAbzEeBzNA2UdiNamcb3AK3aaqKdEmMxy95/vHL5On1WYs/owCTfuIsYfXMclxYajD7LjRLt9@ofgZk@/bL6wYc8BBx7KPTQMhESG40mW1tmpQM7fFunBPoWD7lYnO73tIvwiwQrgmRD2gaLVSK9WHxFNq@n@1p6kZpwVdgOGA1tr8jjA@zbRYpjdOeMso2MyOYSarxN9OSIfTlJ1vqnPvsVFUmlqCy5F20@enTy5vXzp9utRyv4P1NV6WWmE4z4l8O7UGGOuqjURz/80FNmNEqYu4fazV4vwgJZ@3HrsYbn7/@cmYSLCS56/njQvcJfoFbyuJoOl@UKtjL8WM3G@QX9Qg0Fm8rFTQzctVmYM@nzUSw5kDY60mruNda@xSxj0r5deqXyujXpMAr0ZMDhyQ4bzmh2xGomEmcD4ubX@lerHeZ7PDuzwEJjMq@dVKzBpVYhc76ENq42srQqeGc5pbku4yObO8jmLrK5g8x0zAIJERGZEljOwABrlQF/DN6x9OjWSKAkrJIeyeFRzNXEXo4OX72MbuXtyFEST8z9COE0b4aK4NRRMz8UgRpDhWcu72hztxmOhmUurmnzBzZjHYI7kjEKe4maYQMuZcfwILpl@iTY412zSh06xfczIqiUxhJgSUO17JPFFFa71dXQe6lNpNBvZuJM0l4qVWTuBFgVmvAtdcD5pmtz4brbJwq@YdPf6ta8M9UbL1RdO@vaZOVWJ2ddViUs12zy@IbPwxGqGvg5nApiMeiY1l927GyjrPbPjrsKaWKAwrX0eUn09mjeiY6Jqe@YlYxhWOCajC3pmHWlEu@klYo6EKxVp/VRjm5rR9LCnCAsyrTA5MikCXZqCHZqCDY0/Tplyxk8Nh@6SDvXSrYSarS8YsA3nH9juEo4yhaXb9AN7KaCBUhMa3UyKwIS03adztxBeABVoLS@1vyYMfJvq3Q71OdJpAkz8C91VpPuOZVhCuNSGUKrG8s9BQaqwJ0h1307zeRbHplfZmEg4AbQ9YYb3KPKvaupYXi2qX5s7mzqxwI2aze2KqrdwcwQ8wB4gpOQjAX1xLOxJ0CprPSksnzZzF1KHn9YuxsajZua59t69Tfr5Ci07X0x0Z22JVP3vWqdOEUzGUBL5st5S3EaTO/00uUx482VDrhz/UDvze8uW/biQKAtf2ehNIhqldcGB@223LG5szdjefRbSWAqVymCcCrdYXwAkvkRumax350rzvCu3mYT843YUhjiWLa2aH1pt2YlyHKGXeanRsES2GymyUr35RTUO2bDkILQHEXq8qTX7v2LIOjHtCyLm8I8wKGVQZLfhQ15o7hVV0WHfiYBMbY0pcGyRJ8tleIFdV2ny4h3eVVU7qLBFOZ3EFVKn0YeCcmYoJYd0lwYK303c5Q5XFqtBkJis@kkIADMYIUG09brsPuVcYeHTTym5yy8d0ykhWNGrXRHGfKi2wYSHmALH8rUOQcyGyh7/LXDujuc6MHL0w22HVUMl6A3athE7lsMJwakqllE24@8W@jVeP5xJpRYpbiPAUGNS9RmZfjPXKu0MuBwxlpejrTZWLQbQ7gEi6UsEzUR/RBLut3BLBJ@oBYM6bpSbCH@FBO7g4SqsBqxzNeIlTFBUOg0JD@Qj@RfS81NwblfkNvOdAcLc0XcFWof9fLuzkSos6i9Ns2b2gQ3Z9UjgVCErDMYSlLMUSHuMCvoaHxKPRhAjEWyV7Y06x/n5Wo5X@glLlyGCH7wzgVdWFCadbwXo016IieflDUSBZFIbEyf5p05WG/m0dsY8uCoEqQNUVtMkP/OdgXzGOvgXUpt4DWJpwB8uSQyoI28EpJNtYLV5rmS@/Uqeohzhhpsk9Pt2p7ZwScgHP4GOT9wSkOy9BoK6wvyMyfXeU3IBVPMBmdMfJeG@HYWXeVsX0OPm7sRO4ptE1FHlVrT3@2k2pWfns0wkKOIm6UFp9Aq/bOrZaj3tY4JTlP72MI87jAUN/Raihabbc9vuYy6zm7wlz15rlNOUVxRTezI4Op@e42SPMUtXifwR3fH3EHu7mo94weyHjqt4bvOmoHjp5q@ooJJpdHzEXD/zFQPRg6Hj0KePQw57g6khSHsFJ1LYteeT7tms61Dn88mo/Ky5kCiXTrZjPuWKsQGDAkFspHqJ60ydELFpFRbmtN5hqlYJtXG4UbH0GSQDt9uxU6JgIH6@gIhw/n1JcZfXyRoe7@@SN2QPl4DXTer96HxOmJnxExCT08LbG@PcvJNQBWAO59HWgLZYn@GcuX2CiKvGvMsxfUyyWXaLjqzjHp6Yal@2d2BR4aBj5i1tS6Xzqh5CuRZyNqTKaoSa/OVgHXbDZd6jeVeu1XvBq3uceZS3KhBtuGAlRra04X2H6ILvRXKUIyGay1kWa9TM5HlZEeHLzTzV1o3B4c1jRccQKhXw9sUnBviGRHs6gKPhM41tFTJ8@Ttd9F0971184FjusYPrKargz6blOQO/1X1dIxuUBl5@Akp8B8pF7uTWhZYI9t14/BRqddElcKHmTB9mdPce20Cca3Sbc@84TBiixNxoWNpCUHJm5syC3IMBJTfnVAYODf/mAs2usSRaZPa8Mv58BzfLyOnvHysfdsz66g38PfKeB46LvgWeqv2jtovVmq7NBJb9vph/oBZXebMmvWOaSoqEGb9iQpWbbavkRYZ0Zgt6XsUGOGwdCOgRB3GQEsoUmtWGglLUu0YbuCMFFBjoBYwFyHCjaq7sEjRt1eOOGoYkCbzD3xVD13aleXHyiM21mzBY58rVimq@4kKnjibf0wDD4mapzmZ9gJUj93eWa3HqSp@VT961t9hboAoLsd91OyGKIZoTJMU/ul54G7lxISwb3EMdne3@5GPYXRzqd6grOExgRyfWS3Aavqdk4Wve3jWwlJxbFUxwgNfKfkpqqRWffswAiQJTKI7aVEIpOVDOZ5EX11kEC7iN6QWcmP8eTaaFhnH0hsucrR4xCx8qJg@p8VkkgdGX/uctB03EnyYL3KEcsA5FKvpcHRZTOghbgfRA2uHEnvp9lN/JmF/TTGQiEbKYatIR/3J2MjyJKHYArloDKbxCePUfUIxHfPUPICf3nVFIA6dpq89i15vz0m/JYfejfRxS8et6ixY8WS0QMp6pyW0/2pmmLRwnNM01CvEUQ/uAWPFj2xeLGK1PUgtSR2OP8fQeFJ8Ju4b2MJ1a7qI88DIfEpte7YGyee0bb@/2446g@3up86PuqBqdzqIKqla0v5tm49@rDbjzc0ogfakakyx6ZE4MJQD3G4Kmd3P3QG7a6ci65niuvlrZ7D9p0RuEPHQXpMHntKYy8YFSw2aSqkUpeOHkUzb0Nzd9MfoGXby0aBfbe5sPurB30ffV5tJfThgUX2O8RlymjocE8PlwcwpQRz82gMc/a2tNnrgw2dnAGSr13/yQ0QZ@ELRbW1z9x59/2Rw0dqMe1DqOyyhzcUQSw/QUGIX0CQ5rHgefMjbw@gR9JzNd/CLgizeBbBvr/JHK0BPi0Yq@y8WW1vYemyZ12asLKKMUIsf/cAN9tqLo7GBSDUqhSGMQjVJ9vWert7b10dP/a7aZc4WTjX5Ge3Sr9ihF7wD7OaGcgQMgAjBqhNL0RZVgFZzEBB@D3qID0N7QQhkPGMZNoRDV4ibQdLEOzJNEPZGkMDWQGRWheFLmdyU8xVGf1YUwYQS2dXw@txUXIk0utQnq/id9gYk42CsqUeenm3vDBJVIf/p9czBrcBQfhzSxGauJpY6kPDkYTAUxc1sxoNYMDcSgnqD@YYRQYWHADBmY5txPxZiwZ6xkZbQaLiA2PQ7Y8ZWWRZ18BtNsUI/s27JFsjEJ9ZQJsHtC6ufNaZJABMtLg2h1o/MV@c49uHhh7fa7RbLLz8hAuAO3cHsx30dV0fNK24/@zTdq7@f4nMQ7tQ/amN672mUpvzr@yiSh/CFXoLq6JXMyXm2GF6v8lU@LKphPl1YBkX7SyPPvmGvDzb0oATYDkIYpZysUb3qra1OrWsNXw@kVLKGyXPgZrdosW7cvXwDu5ufurYqiwU9XWCELU5hK2SkLBQyphjnHuWL2Ehl2b@hTPsjnaBjUerv2AZSimyIJg2kvh2gmiHtUDRcW/xjjEl@yITFNOs9CzzFqbpv6gjdOtURe3BntAOD@lQ2qbZj3GLj5sCw7BOHqrl@ZLUbaAVAbnI25lRkJmXhu8Vht0fZsrgxXLK2IqbYOCy5t3FqhIMYC392yc6QLyupfXQS2VJtWMvKm4x6UDtcrkbVFRM4awpq@HR85a892Xo6iOruW0GHrbHUInk2ZSq@hGNNpi3Jat5aiHbhq@i0GRi/bOXYdcPsfv4tr52I8wXwxlM4yOkwg0RlVjdBS/i4iOlJCk/QExuzAdKvcAAB9HPqTGN@7Qi@Cg6xlCm7AJYxYG0YSUvVJxzGTc2QDWXh3yyV9NrofetmNRm6FYo1wklfYyRuvKO0AE4YG1h1UNB1ih3jBJDxlLPbFWVGjlXMSpdVch4ru7jFETJq@7CznVua5Sq18PJsZ6uBdvWIR2bojWu6GfkvqVjqGrtqyd3dHQc8vxYkFpYRzRSZGz1/dXw4fHF0cno2fHP0OrljK49e75qm07X0UGaNG5Cjxi8xP2nmhRwSO1wsooDHpzR8wWHr9UgnsIG/hXF/9OXLRqauonduK3dwiAC5K6Sk6jClm/qWJ1HSNNgq0oObKMwrVMdxO6XG/VKEmlGm83B87vIrMLguaS@lFghffyO/GEw3xmRm7c2VRUENtxZWq@fMhVGpNSi9QKqQIkXB8axNwX0TQFT4y5d2266sCC4uduVhnl1fkPlfZuHh69b6sUrT/j3b/i50LGor2jblp9n1WrE0VfVCS0e/Zv@75mt8JLrb2rjFsk2bHlA0b7u7Q7xTMU3JdNe0NJlyBZ2pZxbnj7DSL2SO4dOaAf8m@hYiYRtmvmTNG5qyqeHE42sjRRX3GkfRLOKQMcYE86FDc2PmkwffBE26lfj6ian7zlUrRAErMdIphDZhcKveWW9q0VpXJ@2doRwgF519lSsTH3ixozuDk5CfT0Rli34siLd1SPxsVyJH0/KepbJas9DaUfTAckD3uft9jS8xTb5jEbuqaS5cR2I@fxROsYxSWkaqlaS16vv7K2yXVh8OlNfDChIUkrRj3Xd1@1xrfHu7ZgzvG7Fmv@3/ibFspkkrI4dChO6@sJbJtC0QQGg7a67pd8LpQNFfHFS7b9eaBA6@Yg1Lze/GGufh36np9enobeZ7j9@zxnhgM9f5NgtWSB4cNmxWljSfak0nmi86ColvNClqLefzD61HKD1UIhpfDxIgMj3FBoTEdxg1d1vYAxDFZEqHdI5NuNAiDG7lHxIbzAEd3jAeKiYLF18muEzvJjYuZjJJ2QKM09gIjEdqspEql1@@VFZMntUJ1utNKBirZdKJ8EMKr@1be0Bw@oaxxvdtwvkmU7ciZ7vhKHEwfZNiVNqG0@1Jnbl3jtjjar6ajIfjorrHV1jc2YwrEWubPQ2y8Qm6EcGnNnSqazAdlBNYuYoutGvvaU2LZtK4aNSVEW2vY7IPspZ5@g3SmJ7DJFvzDoGoL3WDVF/W45mXFVLWLNUlkwzIEiILrpysbmSxwXbmt8JPnUzDM2NvoSx56YiyvtSJcKu23tSJcKxmwwotwTcu3QMVf0mvj8ywquTK7rQTqnGqhQruQpdTire1ZgnphR5xHD05ks@lgYh0C5cTID@gwXqwuYt2ixgIZYxicya6S90BHZEN7wZYy3wmA93uhLnNW7Vi0s4k6UzIgp@BVbqO6KcPOb3hLb8xYX5D3S8me7rqbYEb6UoQuz/oipp486g98xuIDLDF/gDZI0UtPV2hP0s0SSrzG6fJszs9z4zQiGI1wOat7LHDnl2qQ1rm4oh0rVUxjAMWxtsvHRv2JO1YcHzSx32ifWnkuUvH69M43SjLdqIqIZyEMlzIec2dz0EbBh4dQOYiGrrV9ZfFTR5SFsU34qnchXHnrozP1BoXRPdSeVOnyTcebd3a4pQ9DvNXparyRoOmzBNkG0tofPW0M6LHrC5G2XJeqifq9XtGVtrJ2U6Ygkkk@mbeZFxs2DDZ3L/MmE27V1YrdbU3RUfuOtIy784o5vqV6VLmycP5qVYN4cuEUeAs49o1S9MvWDYdOroQkZLzy2sd7kSWpvOU682hDdtZCGaNUbU98cKzWe1ud9puwtPou@/VFVQh6@KJbcxXXRN6zILN/kS5ocKx8MTaJppXO9jm1y0Z92Mde7@jISJZZHx/mXGtUMDK3y9EIE6h9x@v1hcBALw1aCNhR/ly8PKEwieFVTOYC2tDWmO6V3akxOHQI3xzJ16E6bV8KZ5TKDy/4uO/IeaIc/VS0UEVYnVweeKdBr/GxVtgb1U1zwY77JVVv9bU5XFcmSbmtcOJf9mYRP6@UEpOucdUUid9cXL4/M3BoXyY4zt6e0MpyvEmGD/uPvbQog0fvrv9oUZsrcEi83yOrhb2SINRoAZpudZcjuuwc0zAfVdJcXCUTK0pHwEs@lx3uSU70AUboysJOS8ypYhQunzBVW9tbfA9z3/AxBlS84IJj@3@839PQrnf2QdOHvIcSiLncaG8uZ3b5V76PTTQOUrRfqffR99JPZXfx48PHgdWSOaR4CABN4/BmDOb3njZNYdQtk71B/@vLLuiqD4tcF1/rZRghEPPX7h3dxU3SQZWMer/Xs9GR@ml5okrEx/FWBwowLkH6Fz0lOFxUWFoMI4M5qm8JYXiO5IiUz7h4TPpq8gPXxYC0c7qjrTmNUQvOizbRQeHNJPvm9SHn7dG7YkPE9JKWALoR9idypzHRDKrfSTu1owW9l@8UsMBjsrgc2s4puEDt8v2Nu6JjKfwLons0K2rywaTrKtJ@V0MXEYFu8p5EhCOfIZnDt5tKzjIpBxEzNEGzdGXL4EIKhF73ZVJtSsKO8KTSjtXK0FJ5YVat@J@PeFfvth7DdcddYAZUXfeO4E8LXuyzfZux17tXiAydStfiPv4tbn2BKKUXQNx164LnK0mP@ooFwVVzbVWtdwzOQvf@0I/MAqNiuQgZY2OF6bBws/C3NxqjYSGiyau8zYMc8wbAp3DSbs7jnZMxMa0t9dORCDP335umHTUh3K/yQsxE4/fXCvF/CSMY7Iex0ThoHAygR3GZkjZ52yCEalwPzYe4MoFo/VoMuY3iTwRZhvd8CKO/9EQ32CWwzG9nA9dhkUYBxmSvpc22goGLQsnq/PP1u6jEAzLBxowVPR/2H26nXzgkSrStI02IR@innFZJhuRD/BtSmjotsmKdtNia6vYrRWmBhQ9AdkdhHk12p3CQrH6gJpte8cltwT2YIDzvUOIu8RN40/kRzRfYdXOlgNT74Lz3H0cVVgGaCb7nEmmD6t99vj48c7jk8fGelNnb6vsGWSXjyPzGPieboZBeeunCL8Kr/p0oElRIK/vj1VBYVfsWNmakIlSvJWLIYzXGXYVDMGLvi5r0VOS4D@pZ/yvOXaeMxVLEUuvYX0VRNgTRhePLMfapxuw22aqb807EEPtL@LLoo3Qorl9wCE/xFfnq4K97qat54cHR6dHr47X@Bo6@N1otZ4PBiQNr0bV8LyYjcrPLrshYlY3HOt6i9qjcsNfbxcTIW7Dn4G3aXS8/GIGXDmwiBj@wQYgGNG/57UI/D0dKYKelPdQ0jPmsw/bNvCmimWg3jfHIJvxAl2LZ/AP8ScLYqJmeDPFn@nJ8c/sdge3JDpx8XgdJFiI/QsxROWCxmHmpM3U2JjnyE09TjRLL1XBYrukMGrQj2pvdgNM40kgxxFwe2NpXiKg17lTPUIsOKC3umUaXTL4OXj1TgcNtfMOR0@8w@HPIaKtBflH/aL1mBf0uYjf07PG7K9MqynO5tPpfBbzK2rM6Lm@6uZ5NSzKIR5TGxtSxK5ET3b@B8@92Dqx06xrFU1xM1dyL81kK9uFj7JZjhmDjWdDz2R6gfjZK3/PRsDw8qV0dpcf2KEGBqzkdaQ4YY6unuTBRy@RTlp/aYn2u0HfHjN08uHtlv6J7Glo0hItqWYnP5PpwSbUzFplXXtIqZ7UQHTXVbuhhogiLuGwx4HlG9txtCFGemJ0I/m0Sg3LAzEUxjmkNi08IbdyRotUzKj1FKTll5qVqETyiDq4Ou9EaJ0CbTY8siMjTDr8cgPVtqoCdjgXyuCGQ2ZZooCGDpmqpR5NhrJ5OZqsd2X3T0dtO@FtYGv5Kt4B4yNBnfhusLHDX1@/PDo4Onv5j@GL/aOXh8@HUO/hyf7LnaYno9Dro5V/AjqcFcvJZ68T97rkW4sHYcaYOylWZEc@A7Lxbqg0M9oHr47PTvafHx2cwTG945ZXkenO3pwcG1mUXG17qVpugmtR2hzfbuVrVoLA9nsWRbV@ND06GZx9QctTD77nrR6yk7fge96DmrfuCZC62dpL0CTs6A0uUbooIvezk247ITlCz3rGHobEzU7dbLYHfA9M0vtdeai9h@uQKfj2/TtrYvzWG5Pu@3eSoW3ah817jBZg4z5L6AhM24GZ2/WnK3oGVe3IFcnHtdINhnuJlz4bVUz3N5JSOpvB@DDCPAtlRMdx7ZKIACGiRsrwyC7dFkmkc3owAdf2LPDQnOI39LKWe8hf67aLXIgNrusHhzoR31szVNnx9Qb3jUSvzMQOJS0G9y5EAxu2rLKKCC4hL57kGoLtEjcWFQUQ0qqSiNxyMm5CdPv7q9N6I6r1m6r1gmAGyafXGBTOGRTBc6VwUoIb0zk6lLupYqS66Z87teOiJ3nGhM@VHSXIWhcW6pasodfwG6WJTIcxkFHuVSZ3v4vDujdUFcdWpXhxNkqcYIC5qybMhOCDe5oTD8avFCIhpRC0GobZfMmaBnGxUBI5dUeAYp3ruNDWzWxewAoIvpAq5amzmMR68ZRhwAuaG5DulMwO26HotVJMKhW/stARwwMPptJQL8X3UgTCWxoNyTIcesW4wt3W46uYgNjKDIXDuoWiqdgXYKk116bVybXbg@Sa1AcqbJxQgtOQm1AwffEWa58WLrRzW5nt9gpt@Cfe/OSpdTgmTnJeAL2zepuvF1wbi1g3dZ2ii4XYt@tC8WRIZOiDjGnXy43VOaAYv9pxxkJ1g9B59nzNovqaKdM@tyrTvDpXeOHqzcvbGlI8w62fnitMmHqa/Xumma1A7pln9WqJbL/t2J2@1DJl5ZcbjMoz6nK0AXt93u5z@AEupr5YYqo38dorsQNELuCGAOCR4NgOVDWFMx7nSyOLVC9x6kS3/Hb8uEDxspT2anJTBFrhi5AwNL5xKCTWVSo86d8x@Z@2RvF5jETxOjHyOd4ZiGJ3zH8do1uVt@fm9Qaud@q1@RgDj4L771ytNvtmKz86eb478vGTAdaY/4by9ty83qAhBLLUp9iwV4scKP5sObrMHWO5McusJvr80H@XaBklTw8TMoiwGxWDq3BolnpDIdr1q0eP9KsvDftfNFQ6vVn9vjDc3zNanqgdfL79wa9IWoo68Ylru@1sg10bCeEZ0N0dqY6LficVbqhoa@sPJc@O9QTgNnYVEwvjGNJLT@37rAb95zibSIheeqmBd2aOA5rj8ovDWzt2ZlRjixJeuKm7ZEzHBjq/bZdZh5O6f/4zRnYgwskppHZktKqU/m54Qqurdo1dtaVxH7HOcZkOJVeyP90fOW13VgOtNVKw8zSpDR2oDvntPY5UfHuNpGaKFNDLNdibUbAaYz3EaRgKJ/JgHuQ785@zRxVWV4wmLdMnlovjw1eGlARjiomfqt71UcTK2WVjEJoKMhP9o5MOfvzx@x@2f1iZpC50afD0z/3vt7efrpqfjQfIVjtqpXU1W6PO3DbFtC8WuoKP9uOquLySnidGj4DOPo6lNIYqgV2Ar8bwjxTL9gAbbpXpIsWqcN7hdyc10BiLaC99uo0/gJ@efyRtD2Jv7jD1GJoMPcb/gn3HXmADmgcBL0EcjVA9Ux94qRY4qaHPXbmGNeLmgNFq8gvCpd/htN/WOU/hTGxUeDTC4quGeLwKio5WkyUVT9PXr05f/3UfXQ8cU3oX6PjwLwrIqae5wMnxc1UAlVo8QcB7bUf4hksQR0c@TrcrlH4MGAWqvrUBsvDR6ObhsE5H9YV6mY2tGcbIrs9zsThx0Sj@iKJfjYBvOge2CdOVT6PKwdTRo3PIpzxV8chZGiWvjbqebvyJr8ZxBUttxM/G4briz/QEFdTPDxNnRDmPhtXGyRl/Si2EjHJEW0Aw/gCp1Y7KXEtZEzMf3oCEe4wDx82VmRvpgJn4Xg89aKECHbcSbVjGn/YkMHz3Uml1HWqeGmC/iWQglDrbTL9l0rS7GbhZdUEbunFHV@606clhY37tz1Km9LrBQgWUdWVAugvaZpvVD8zdX@n4CI3ECSH4/cQAPe6ZyNYvXp79sn98dnR6um9ejY8w9fDX16@OMQCWSY2@YRCr3zeIo/oghoLbhkIzKetTm8vsRu11pKCvLclT1j601CQSLspqqQW/Fl9z/xtcfdEhRpiH21vRg4xpzYOhtdi3tdC3xg/oXnXU6L6pFKo8pwprojNIJGkNX/XCM94cgwtje8BM65WyoOUkT5r66CphngaSt47Iz9wg7KXEjgmVTWjU/ciYt10RYcgJfytewFbBx@RbomytxZeKfmwE3er5NdftrEFWHxS1S6Fm6/XRwavT/bPhm2P49@j0xdH@Ty8Pk9rAkFxcQRw@N0ywudrVBC6REfyyBPYPrNsXp5iXFFU4PMnFrxO3iBFVd2PlZfiwsb3VfgGNOo0HdFa2YeBeUt1BuDUDsOMhlOiwnEApdDU6boF8uM4ZGCEGsDIu7awx2Uv7cEMjbW06qXfp5@NXfz/W3SbZdblaLJ9crGZ0r9FF@@jkQT8fHeGrcCdvXgNH@0ukmlIr56HDrZJH99Tu6vFpXTjrcn3poLDivqV@W1/rG4HQhTiNvnDkW/bDPfPvmSFzCfUz/qFfW8h6lNSWkg9S09O4Zp8JqncPdW3oiXqq3Hutq8zPi1FV9x61/iVCHzFIbnbDLno33W4kbjAYzcVx/iN3P9d/Mqq5/1n1mDFq943Z1wnAaiIl825eFgVfysatmfuPZLOSbLrUxpaYptVc06WV8AbwIas2/FiOFov629s1tBKXqEmyYLCu5yXdjOTBVCzp72xutVSaw@VJ2//p1cnZ0Qs6PVPY6cNfjo7jzf3XR61VNbrMd1oqTWvHNyNTZHReES@x1wbkkZguXpf@23EOVrT11fFe4UAd559aowuooPVYByBBD83Hm7R@dUW7qV8T2uw7Vws60C2jpd9AtP3f2pIqO@pKWzZMGfPAMcYDCo0DFq4Yi/4blkNi3fhGtLgA809LHc9aBR1oHNpI@h/r64jf/7vmoMSwywQNqNyXHZMwj22kZNBO2ARLzJ1MhjXAynkLOvgylHBw1zUpc/n7cKOddODxB/tS4qRKAu9FuO7vV3n2YYgXaxOcVq9lOGu/fFnwQ2NLFHQcnh6eOSt2NVMyQAwCthmFMOOypfI@doN4IwUi66DNPy3YmwWWxjluBWSfyCo7D1eymj2kGqLm91REMOuqwormpaqRfnyYzT/OHtJHJgGyMV4KHeX3j0TMrYxb87KlCoVbzEt7AQcgTFFIBmM4KgUjQ1agZGWA8pVdR2yBUg62M8Mj7C18vnuiSqtVa78CjYGtWpLQcjQZUh/rPsyr6XA2n/F7sta6unOdPGQCFs3XeVq@LdEAHmTvDYuo0QijTiiCbLXTfsWYXztqOeVser0rPVIdJKwct7pxPy6LU4dSM3xTdKU@SUXEIjHmJGRyR7G3@cqBv3TQP0pfAJl6Qwfh/q@iiFonzpqxNOTkcP/5P/xX5Ja191Jm6tEXGAW1IiWZ0m3UL8MEYwA6dQBnY0OTQB2s79G1BOzkAxufeJ1htVoQS4HP2eaf8my1rPM/WKjduYgwg5OR34gsA@N3pk7EMHUN93SRqNM0m08XJK75WCyvYJ23qJUt1UqfHqjzpOE0qb1oLMMSkwsDPndqHuq1Mdi0tcbU0e5yXmxis8Ua6P7Qdn6cULIhUxKzebUbis4auQEM8cna7rsHhAf9mogUKz/AqQnv6QcRXB9V4u4@jmBNTTJEsuIVBo3yvIdL8tAx1YifvybO3oPYlEFyJ16x0Ns1my8@l8Xl1ZLXtPI03TzQyS2YjNZ2v/9jqwd/Bt@39kugPa2fCtizrX//@Q1w@LPfNpO714APjkODF1kSByXpRdt9Hf@/VmBqSnQW08vShPubjtCsobUAvtykwVriRH7qxaRflHneWuC/kn/CkvI4/y0v55abZ/yPW6PycoUnkrhGbGj8zaVVSxqKY0vWFMZsp6QcKR4E6rXuJXUsueNAdQoHx8cQFys07TZ3kPBzoM49ScJ/y31JB@i4fOCtiU8aHbFEH1R@SxKnwanI6opwfyp7131OU0Qw8t7ZlNFACdmuNZWRtftXGT65lL/jsmXXeC3ikibJQOxWtDbwOESHxvPIdpyuaf7x49e5BpNtjvALN@9DyBaqO1zogTZp4wcT/Ky/IxUK8t10F@VCvECnfAoTV6vyO8bgQjLrxKZETRyrgC@N3WNp7B7x9qktSrSxo1LeBu6pjgzIioawb@L2DCTUyBLhs1rvMKzB/H1RI/@s1r/zTCS1gKA2Wfk88@wxYfpiuT0tFBseZcYWk1ximfXEdXFPDxSU8lwe54vlFYU24J2NC6HeExXjQDa7p9oYRV@3qtW75mLp2TcijFZHrUB514Oq0kZytZzPW9PR7LMgTPPFY0G1TRg8XlGjGgZYP8DvYQAYZWCzGf0PLnnx6KZ@e7rJrHgyr5As3zOL88U69/M1s8nOltby2Fmhvslwpk2GM9dkOLMmw5k1GZZN8Kvo6Y89uPIcHEFDbhvtKzFoBxlYTsa8HdF5CJl07WqjQ2NlJIQPRusIV45rWQrsB0qz7RNeNcW4mb99o9Wm6P59RmutoUb4A1inc2QFVcWwHmFhNlb4LRvX4VJwPRtLNo9ZMen6fdjQLdMApYEigcrIg9uriNKAxKOlcrASAkg9UJcE5TOk5OoaepnPPDtu7WTfr12V1w6N3OrlajHE66a80Oo06sqUOxTuAkCmGlonmNfL0qlOUnqJdBZoDCyPxWopq@cUwhmuFQBSAeQhVWuG7iXkKG7f8qyjCiwwvLnUJ5gWZv11vmpZ1hHTlHIBejqkjAIYq9xELzNsc0Mj0VAx9SeSqHZT1zizxkHCQSMWKfxHlmdmGdHYsoe5Z8bwDSeNPOBgCTBrDz@UxxV/c217qeWL3RXjsf5jVh2oI1XBKCpy8uZ1i59oI73SMp9tfjOHh1ItfEvGMNjVXB431dw5bCqtd4staGwg@bThVHRPmS1NeGQzAcSLWbUVzw9F@x4EXhmg4danAQmlEEQ/6meDXv1O9ocebCi1keuTJ094oZCh0QhaBFtgtMCfrG0d4VNgJmQY9giysDxk4DUvipTiTqxFo6caAaUbA6S9YrhQ/fpCHtpYIIi/Q343t7w18Zsf7cXWsuSFBDtttrGK2G2wsT3NjfAuwzj0c0/VCAccMeI8tZ62UmY2yvNgolrj4uIix7BgLepSOSJjm7CIj8QuNStca4Ek1y58Rrdy9Y4UpzRyGCUEC78x3hHAisVvDkR0rwxKmWAFuqN5Gl81Z7u1kdZfNhTacGBNdOzlTMjZ1GDBSOE60BULkp7PVlMY8DaRSLXmRxVs0EccD4U@Uh1mbLNabtpUbaS6ORuL1Kc6tYRU9XN5tenYUS2BcOUXIers3na9a5uGStbY1PWdFyY9Yzzp4@SbGjb7ONFefGCLxQUXxS6mxcp829VCtfqNPfyj2k5rbAqkcgV068NnXxfVmWdZFcPtnP4ugSrj35lqJnn1oqkHxcQ6z6slvrWbzKz@6/jw78dtKuOFx4ww5nJTFqZ20/DbmZVn11FZww4s9razeAcXa44e6cJnEh4y8VFsbDM9G0QdNA5WmUsbb3Eo1ZrUVNG8MC1NSPCl6b7CinOu8VLLIOEd0ExAtQihgoIq0E0NM5bxtPnm0RIPVE2RqBENyqA9W1sqazdVrbKFau1VoMrzhlZxA1WjZYN3J7rZwV8sV3N5oaVhVtHk2WarvZwvos2dzU1lckqqVNwRCBpZherArCZ6WTo4O6av9EwPfrl25s8PXx6eHTYtNqmwHTzI80ftldb8guLMoo02HlTwCb/Y0ovMOvDk0mxZGx/XefQo8gZGd05a1Zu3i0OZUe3YlcddkPD8z8lH/LNKy0yauTlz/Ehpw3oOzWF9gga3yLzRc9rZlZB409GnQnw1rObTs/2TsxYChWMNUnF7Hyd23T7XoNQe7fvkVXd/xLDiDQU7j0MXJRXsvuyKJB232QhmMmi@t5NdpY/7j4UymrJVYCSnnF9qIEvZMsoNiECeuYjZKFM81@bsqlvpo51dQX/Eg9J3drIbJurw@LmeJpxtaEKdqTITpmS82l2YzCcwY8glUxF6r8b2lzZotJDfh9C45e7lBsIKcFf9bXRZesfIlZWNZq3ZHAVWUBPrtuq2eMZA1SnKRfiiSIatam22lEyFDJmUgZ1ueN3k7L@fRakNqHE1Do1s05X760fv4V1XPyxrYDrv66qAo4Y7Ir711yiksNoknDEKAeqqk8rcvVs1dj1sTbF2QOQQmNFheyusWK@pB9hbhOcPkTgh3zGT1CRf2Xoss9v3rEbRjvsmb@lbv17PpPPZdMvuWWtRlrc4qIIY4BKb5fmYtsXvG4WaZcD9F4aHz9qoEoYOm1HysHENmbH3v2ILaPu5e61A7zG9uZdX8O50qgE32ggkONCOCvYPG2VrnCt1@Y1j5SmwfAPfB0/T/8Aw9x8wzEKo1LSqa4ZUQj@Nc6A1oRfSVBc/vnIweNHe/pFjc69hknoVo/bU84YZInEjROCQPu3Ck0PhtyNFvdCCqAtXEkWALES9GLlRfu7u/nuQ9@XRRJMUWALTVVWffzID7FTKGjA7ZxljJ7bFlUVg8YkZd4xdjH2JJ/ksnn2clx/iDv1LftEqrBhKpdAdZjYezZaJXGGEi1epXWwz81T6SGjqHr7WoCnC7@r/wYqDugL28XAhmgmz1ylgjfQ9VyewBP43ykvs7xSLDlg0EwQt3GfpHrgPpBjr/o2gK6aIvWoB27R3D3y/VsffgLsTXr9r5n6VvaOPzR19jJfxfuAyTqsOl4u5gZsUvvTBEs7O21VsRjyhRYoDysNJi5XSeF75cRfMxtddMB37JvrJxcxy1mVJNlZLtRgpwbwYYwABYc0/zb7QNIiao9Qu561xiR7n40fVWnPJIjYS4ShWHZJRPLll7/VbNmn63mnR@91iawv3u0y07X8v2u8JOICcUHXv33nafnULxncxWNmfpoO@Efjf0321Yn5n96EuomGeisTkB1QnJpbFAxpZrZj9/L3NlOskHYQnTVnUNjOsch5oQtPCey55Q@3@WzmvaW/wwBUJVGbe@vouvzddfh@JlXLH9DvUV37qXiw9sy@Jtr5LFZZEpivKFJru3rr55gYUQHf9PSKbsJe68uTmat6Hq3GGfBAQvDSFQkN9@/8rInp3p08uST91Wo0M1oVJwU4Zvyykb3Sqs4uQZ12TXGifByqrpsol3HVSJEi4nQeXEkl@4QFswJ1jTlpVnjIOuaVpJVW8I36dh0J4a@aJOSUtX/wNCtT4AkqKnfxEfimLdufD5GFtDusQwtYUSyQfldlV65fT09Yc5o7DLpsx8FYRdStKPqitW6Rw2u1S6O9CP5zG25n3UcMEUYNoq6yP0Q5EBvaQS14wEdu6E6KuI5z3KHBEjRShvfd4aozSQVYdX98S290PSLowOZE0h8ZOkxxXSknNhkHalcSnqX1InL@yke8ZfaiRHLm72y02gE@gVUwBl7Dx@A9D4D8cYEmdmg1tg/sBUJlaw4rZvaPHAaJ105DEr30ngZawIYke0g@RK8sjpL4foKO0sRu8tqWbo1cSBq1katxHkWQazfZpWrahe93oUzEdmdCOZH9Xrc7JVO0idOO3KMzjiTH0i@peL5U@OH7RkoLSVhsFcI9DMtTHkePLYJ4t8G94RKe48uBA0BqTlvdQyGxgpLY4NKq4mTSRpgmr/g6bEdUd6QD18GIyuqyGGRQxBozhuABo6j2cZriMXBd@6yvIueox6d/4i0Mj6S8nS7/poD53Bs7zDJwYC8Sxg1fd0@jjrYDCHS1jrtmVgO8dDp3DqwVF9KmlVkcMAPQnoz8cogDSEmdFxeb19LDcMjy@SmYEqNnQTo@QczCGuipH1xlOdUjqj7s/fgm69ljuKSI4CzZ4pQA7z18dH/LVyFu695Tgqz4uVc/owTVVETqdXTjAboi2zfJL/WyeSkFXRXz8laczXdDLVjypOpBEaBxInkCEv7lajD5jKolodUBVOu4CtUsDQLs8APog3p1btstt4msqZvq2bz1rX0jyniCQ0vXo7K0tXNhyxxqYOrPOK9KH7kdfPzx25PuJnRdYljjBOw@hXJJe1U8B3sC/7yiw5BoXoCEJ3OMw4WxqCHD22JBsXpYcuv0r2hF3kJOwjUF@QzZmEOnAoc/sDt/pP7iFV6vpSoo/2x3UEWMQJyX9pDsIW5EDcv5BhaLY5hvj0piA3scMImghJndE6NRCkUXh4UdFUkRgfIdxwaXfNpgUO01F8gAsX0UrlFSQGoQ781Z8oIUP/aawQma3aQjc6bfiwwW/w94123NAJt1Z7fWVitaZNhpl0tu0Fz3clGrA1Y1Vz6D@0eZJpFIKkE/F6jce9IHawwN82tmJHeENVqFsE01fBRaOeCjHzc28M9cwSolFbpS8Nzenr2/DrcH59j2e6jQwBZE5ZxY9sJ6GuxMZyEwHXSZ5QTtKOwx826DhtmY9TWYT6wNifJPuG9uzSY83UvBex14TiYT@CgQgembDgzDMuyeIbaff7Iui4j@h3pn3Yy2sglaVN8dhAGhyVanHkqrba2uY6QIlE8E4Vl9bIcHFB69@eb1/cDY8O9k/ODz46@HBz/xz@OKXs3Aj0A58Ns7Hf2QrDn@F8@354fOvaAb67vyBLTh589qpUT0qL65W/Mj1kLzY0ezmIbYhulTQLceEtON3qeshuc3znSouuoyCl06SuwCocdUUoAGbKOdtynV4bopKvFsqMHDG2rIm7maguMlziYpxwFo/uP4OrnlY5DWnkodiVE5E3nwBaaoCId3pWSvjdonma2EpOUaYx9xGK0URloesBoNSUsSi8utodMGkVvA/0bzkLozPvqQSaJrNDGCl4vrB6eaXqKHgapm1H//n7HFshLZhZN6rizWc9iGxr8Fqwi6GhoxzvgadWbc1dCbnq/qMES@N23toEjhEaKLWGr9LMZ8RI4hBzOjNnp6KcySSGurTT6c0PG1pXgHip1yDSMgyGh@Wz5fNiLQ2QTU7DjY7Clcwmaxakj75bQxRuMU6ZEyqGtAoAteIgLtrZojYjIbOElnEfM8EXMRpaqihpd50Q/HnpDgvR@XnwMwooGYs0/xyhMNSfcegHo79vx2e7CurEvex5PzHC6eG9VXwkN1fh4J7GHZo0Dk5oMvhYKVVaFfoJ/Gcwbep93dm5Xm0h7YCPVHVTPv0yyiBkjazeSh/@anFfvf5OIiBs75r88PbUXuwu7vdj9biU7f@yeeW4VIaln2In4G@1mu7@5d/LWbZZDXOd6vP1Xdo4//kas9NxLdpVmVWz1jNimo5xmT1engg9BlHPlL5yKj3Bkm1LGH4WiWx/K1VwlIwvGle5ktObZ@8OYWFNjw9fPki3lpFJCrrpqsn5Wq4olYub4DPyrqDvPdjx02GPZolFrwKg1cOuBOP0@uNWmkPYAj1G@Yue0ETWmdj/Zfa0ZA9ebn8gFKH7AMbU12ruGc2jq8NZPQ7fElQCz/rBmWkX/liINk9sROieNTOebMCMXpm6QOye9xNqcvwCy/B1GuWvv7y@uUpiy0wHhplkC9DueyqD35miWMZynyMYgjDdc0WBZ1rfHp6GVEj9b6iq8HmopXNSHNufUu0hegs@tpBaIjadm2ittlWua2A@jdt0LPriHmLqr3Zx0bRMvn/d3TVm8fQbB7lWtfg/9QPJ46K91Zvcsd2qexVWBojt9IxcitDI@fg7hAuZT7AA/cwByZnpzrBH@0ecoGc6I1NmKZ5ZcOJkvjkhpwlZISGi@mSndeF0zqKdex7E9asQvsQ0/LwzhJiQKW3O0Z1TG78gwSrQz924dIe4mRdT4Gr0ezS3oXvl/xYKQ8JZbwInbtpLTLnmoAgKhQovo0i7pgU3rw@4AxMr6sYYH4gxrzIKx/qtasNn27B1zR27ZfzLg7unoOXJ/iQzNWCGb0Yw2b41U/nN/lQMeDrXld0ZO@NbmY2xrwomzStNsRzOZmfAwrlBeY8f0Uzym80NcbCwGzPlePxfegfs6OpcfkIhP4juL2n34RXo2vttZ5uRkntqSv6NzASDq5hUIgph0SGBmSUrjuCP2Rf4xiBNIhr0citoLIfpaked1Ib6YfFUv2kVmpa5L5ElsrI/ELj1wTS91crjtIUBZLcj9FsOWyQ9bpDwRvq9wxImcLP7ZPjn9s3dpGUGA@gqkxj4k0t@MWwnjZsHDaZHrlH6JYBZy8xQIL5JlWTTD@d/Yr5LfDoarXQ@7k2QFjJ/z8D5PThWwfIGWUxQE66O0Dj@cdZeIicp8gfSte8UGENnsRXkDoazys3bmrfbwFANcoB/Xg5qrPS7CXgcvZ4Le7HFOFnwqHNJfZgYCbz0krbRHhVXhgm1IrRP7Y7BhqD2wagIvU2svt8S@oCJeGHX1KBPOTJ6YRkf4g34ze4xqo6vt1FViO4x1VWvBZg5@er5nhaVBgucDOqhaMXoTnkxS/gcPrPfwVCXMzy1kW7iEcRK/9GSZEUvV70Lzrzsj1ybBgOAdRknpNMeZ61f@sOYn5ZpfWbzc7bo/ga2fBRtP/2@t3/3n@7ePdsAr@63S9f2u/fdrsf3qXX0U4FSZBQwJ90Ea/aeMn4l9/iF/FN/CGexVfxIr6Oy/gg7nyKO/txp4CLaNyp4s77uDNNVnDnua3eTgHdDMqjGTPM@aMXvUG86A0i@h1j8A74tQe/ei/w1276onPTw4wX0d2yHd1etK/jD9Hk7XtoBSoh8XsWIV7@/pCSXw90AcUDWGlyN8W4dcAb41Y4TJ1oyjQzFaysizZcBOJH481460W8dRP1tqPRObqyR8lv2AZi8z6l54kEZvgy3lrEW9dwBj9NLqHC@LLdj6JPbxfpi96ie9158S6FO0l7EVNXcKChq5GCxB7TnxfqD38rc5H99Dwu4L8J/FfBf@/hvyk0YuMgsQbkaER0GB@kVynaEamKIpzF1LUIPYwX0V4/psHpG0BoD7T1Hf6FqYWZYXOAy3bvGkYHl8Egia5T/BVz4mX7IO1H9tVPGKS4TGc9QkMzVO72n33YmUEn8RfO1U4PZ8iWFbVvFKp6xLNPOKCebve3KOHZvmy/l2V5ygGEMEKbflMjxtzLwVZ6haFiVNGeLksIzR@FB5tw2caV3SMs1xqVaSDea@CK1aZd8fSHne9/jGJatl@@8AUbdSb//Oe/xf/W2sYw3PDv03gA//5I/34fP4V/4W/rT5D7Y2sAv39sPYX0H/9PRsZs/@y92v5n7@P/BQ "C (gcc) – Try It Online")
(Warning: this TIO link is a 30 kilobyte URL that contains a minified copy of PicoSAT 965, so you might not be able to load it in some browsers, but it loads in at least Firefox and Chrome.)
### How it works
We initialize the SAT solver with a variable for each cell (land or water), and only the following constraints:
1. Every numbered cell is land.
2. Every 2×2 rectangle has at least one land.
The rest of the constraints are difficult to encode directly into SAT, so instead we run the solver to get a model, run a sequence of depth-first searches to find the connected regions of this model, and add additional constraints as follows:
3. For every numbered cell in a land region that’s too big, add a constraint that there should be at least one water cell among the current land cells in that region.
4. For every numbered cell in a land region that’s too small, add a constraint that there should be at least one land cell among the current water cells bordering that region.
5. For every numbered cell in the same land region as another numbered cell, add a constraint that there should be at least one water cell along the path of current land cells between them (found by walking the parent pointers left over from the depth-first search).
6. For every land region including no numbered cells, add constraints that either
* all of those current land cells should be water, or
* at least one of the current water cells bordering that region should be land.
7. For every water region, add constraints that either
* all of those current water cells should be land, or
* every cell other than those current water cells should be land, or
* at least one of the current land cells bordering that region should be water.
Taking advantage of the incremental interface to the PicoSAT library, we can immediately rerun the solver including the added constraints, preserving all the previous inferences made by the solver. PicoSAT gives us a new model, and we continue iterating the above steps until the solution is valid.
This is remarkably effective; it solves 15×15 and 20×20 instances in a tiny fraction of a second.
(Thanks to [Lopsy](https://codegolf.stackexchange.com/u/26849) for suggesting this idea of interactively constraining connected regions in an incremental SAT solver, a while back.)
### Some larger test cases from [puzzle-nurikabe.com](https://www.puzzle-nurikabe.com/)
A random page of 15×15 hard puzzles ([5057541](https://www.puzzle-nurikabe.com/?specific=1&size=10&specid=5057541), [5122197](https://www.puzzle-nurikabe.com/?specific=1&size=10&specid=5122197), [5383030](https://www.puzzle-nurikabe.com/?specific=1&size=10&specid=5383030), [6275294](https://www.puzzle-nurikabe.com/?specific=1&size=10&specid=6275294), [6646970](https://www.puzzle-nurikabe.com/?specific=1&size=10&specid=6646970), [6944232](https://www.puzzle-nurikabe.com/?specific=1&size=10&specid=6944232)):
```
15,15 1,5,1 3,9,1 5,4,2 1,6,2 2,11,2 2,2,3 3,9,3 2,4,4 1,10,4 5,12,4 3,1,5 1,3,5 3,8,5 1,13,5 5,5,6 1,12,6 1,2,8 2,9,8 1,1,9 2,6,9 6,11,9 3,13,9 5,2,10 2,4,10 4,10,10 1,5,11 2,12,11 2,3,12 2,8,12 5,10,12 1,5,13 1,9,13 1,6,14 1,8,14
15,15 4,2,0 2,5,0 1,3,1 2,14,2 1,3,3 2,11,3 1,13,3 1,5,4 11,7,4 1,9,4 1,4,5 1,8,5 2,10,5 12,14,5 3,5,6 1,4,7 2,10,7 3,9,8 4,0,9 1,4,9 1,6,9 3,10,9 1,5,10 1,7,10 8,9,10 1,1,11 10,3,11 2,11,11 6,0,12 1,11,13 2,9,14 1,12,14
15,15 2,2,0 8,10,0 2,3,1 2,14,2 2,3,3 3,5,3 3,9,3 2,11,3 5,13,3 6,0,4 3,7,4 3,3,5 2,11,5 2,6,6 1,8,6 1,4,7 2,10,7 1,6,8 2,8,8 5,3,9 2,11,9 2,7,10 7,14,10 2,1,11 4,3,11 2,5,11 1,9,11 2,11,11 2,0,12 4,6,13 1,11,13 3,4,14 1,12,14
15,15 2,0,0 2,4,0 3,6,1 2,10,1 1,13,1 2,5,2 2,12,2 3,0,3 2,2,3 4,7,3 2,9,3 1,14,3 1,4,4 1,8,4 2,12,5 4,2,6 3,4,6 1,14,6 7,7,7 1,10,8 2,12,8 3,2,9 2,14,9 2,0,10 2,6,10 1,10,10 2,5,11 4,7,11 2,12,11 1,14,11 3,2,12 3,9,12 1,1,13 2,4,13 3,8,13 2,10,14 5,14,14
15,15 1,3,0 1,14,0 3,7,1 3,10,1 2,13,1 3,1,2 4,5,2 2,12,3 3,3,4 1,8,4 1,1,5 3,5,5 1,9,5 5,13,5 3,3,6 1,8,6 2,2,7 2,12,7 1,6,8 1,8,8 2,11,8 2,1,9 4,5,9 2,9,9 2,13,9 2,6,10 4,11,10 1,2,11 3,9,12 2,13,12 3,1,13 2,4,13 3,7,13 1,0,14
15,15 2,8,0 2,4,1 2,7,1 1,10,1 6,4,3 1,1,4 12,5,4 3,11,4 5,13,4 3,10,5 3,0,6 1,6,6 2,8,6 4,13,7 2,3,8 1,6,8 3,8,8 2,14,8 2,4,9 5,1,10 4,3,10 1,9,10 6,13,10 3,8,11 1,10,11 3,4,13 2,7,13 3,10,13 1,6,14 1,14,14
```
A random page of 20×20 normal puzzles ([536628](https://www.puzzle-nurikabe.com/?specific=1&size=4&specid=536628), [3757659](https://www.puzzle-nurikabe.com/?specific=1&size=4&specid=3757659)):
```
20,20 1,0,0 3,2,0 2,6,0 1,13,0 3,9,1 3,15,1 2,7,2 3,13,2 3,0,3 2,3,3 3,18,3 3,5,4 2,9,4 2,11,4 2,16,4 1,0,5 2,7,5 1,10,5 1,19,5 3,2,6 1,11,6 2,17,6 2,0,7 3,4,7 5,6,7 2,9,7 4,13,7 3,15,7 1,3,8 1,10,8 1,14,9 2,18,9 3,1,10 2,4,10 1,8,10 1,10,10 3,12,10 3,16,10 1,9,11 1,17,11 2,19,11 2,0,12 2,2,12 1,4,12 4,6,12 2,13,12 2,15,12 1,14,13 2,17,13 1,3,14 2,5,14 4,7,14 2,15,14 3,0,15 1,2,15 2,13,15 3,18,15 3,7,16 7,10,16 1,17,16 2,0,17 2,3,17 2,5,17 3,11,17 3,15,17 1,0,19 1,2,19 1,4,19 2,6,19 5,8,19 1,11,19 1,13,19 3,15,19 2,18,19
20,20 1,0,0 1,4,0 5,8,0 1,17,0 1,19,0 2,17,2 3,6,3 2,10,3 2,12,3 4,14,3 6,0,4 3,4,4 4,7,4 1,11,4 1,18,4 1,6,5 3,12,5 4,15,5 4,4,6 2,16,6 2,19,6 6,0,7 3,10,7 2,12,8 2,17,8 3,3,9 2,5,9 4,8,9 2,10,9 3,0,10 1,2,10 5,14,10 2,16,10 2,19,10 7,7,11 3,12,12 2,17,12 2,2,13 4,4,13 3,6,13 4,14,13 3,0,14 1,3,14 1,5,14 3,16,14 1,2,15 1,9,15 2,11,15 5,13,15 3,19,15 1,4,16 3,6,16 1,3,17 1,12,17 1,14,17 1,16,17 6,0,19 2,2,19 3,5,19 2,7,19 5,9,19 1,11,19 2,13,19 1,15,19 4,17,19
```
[Answer]
# [GLPK](https://www.gnu.org/software/glpk/)/GNU MathProg, ~~1286~~ ~~1227~~ ~~1086~~ ~~998~~ 947 bytes
The main idea is to encode the "contiguous islands" constraint by introducing a preserved flow variable that has a pre-specified source at the hint location. The decision variable `is_island` then plays the role of placeable sinks. By minimizing the total sum of this flow, the islands are forced to remain connected in the optimum. The other constraints rather directly implement the various rules. What puzzles me that I still seem to need `island_fields_have_at_least_one_neighbor`.
Performance of this formulation is not great, though. By directly eating all the complexity with a large amount of constraints, the solver takes close to 15 seconds for the 15 x 15 example.
## Code (golfed)
```
param M;param N;param P;set X:=0..N-1;set Y:=0..M-1;set Z:=0..P-1;set V:=X cross Y;set E:=setof{(p,q)in V,(r,s)in V:((abs(p-r)=1)&&(q=s))||((p=r)&&(abs(q-s)=1))}(p,q,r,s);param I{X,Y,Z},default 0;param t{z in Z}:=sum{x in X,y in Y}I[x,y,z];var u{X,Y},binary;var v{X,Y,Z},integer;var w{E,Z}>=0;minimize o:sum{(p,q,r,s)in E,z in Z}w[p,q,r,s,z];a{(x,y)in V,z in Z}:I[x,y,z]+sum{(p,q,r,s)in E:x=r&&y=s}w[p,q,x,y,z]-sum{(p,q,r,s)in E:x=p&&y=q}w[x,y,r,s,z]=v[x,y,z];b{(x,y)in V,z in Z}:v[x,y,z]*99>=I[x,y,z];c{(x,y)in V}:u[x,y]+sum{z in Z}v[x,y,z]=1;d{z in Z}:sum{(x,y)in V}v[x,y,z]=t[z];e{(x,y)in V:x>0&&y>0}:3>=u[x,y]+u[x-1,y-1]+u[x-1,y]+u[x,y-1];f{(x,y)in V}:sum{(p,q,r,s)in E:x=r&&y=s}u[p,q]>=u[x,y];g{(x,y)in V,z in Z:t[z]>1}:sum{(p,q,r,s)in E:x=r&&y=s}v[p,q,z]>=v[x,y,z];h{(x,y)in V,z in Z}:sum{(p,q,r,s)in E,oz in Z:x=p&&y=q&&z!=oz}v[r,s,oz]<=4*P*(1-v[x,y,z]);solve;for{y in M-1..0 by -1}{for{x in X}printf if u[x,y]=1 then"."else"#";printf"\n";}
```
## Code (ungolfed)
```
# SETS
param M > 0, integer; # height
param N > 0, integer; # width
param P > 0, integer; # no. of islands
set X := 0..N-1; # set of x coords
set Y := 0..M-1; # set of y coords
set Z := 0..P-1; # set of I
set V := X cross Y;
set E within V cross V := setof{
(sx, sy) in V, (tx, ty) in V :
((abs(sx - tx) = 1) and (sy = ty)) or
((sx = tx) and (abs(sy - ty) = 1))
}
(sx, sy, tx, ty);
# PARAMETERS
param I{x in X, y in Y, z in Z}, integer, default 0;
param island_area{z in Z} := sum{x in X, y in Y} I[x, y, z];
# VARIABLES
var is_river{x in X, y in Y}, binary;
var is_island{x in X, y in Y, z in Z}, binary;
var flow{(sx, sy, tx, ty) in E, z in Z} >= 0;
# OBJECTIVE
minimize obj: sum{(sx, sy, tx, ty) in E, z in Z} flow[sx, sy, tx, ty, z];
# CONSTRAINTS
s.t. I_are_connected{(x, y) in V, z in Z}:
I[x, y, z]
- is_island[x, y, z]
+ sum{(sx, sy, tx, ty) in E: x = tx and y = ty} flow[sx, sy, x, y, z]
- sum{(sx, sy, tx, ty) in E: x = sx and y = sy} flow[x, y, tx, ty, z]
= 0;
s.t. island_contains_hint_location{(x, y) in V, z in Z}:
is_island[x, y, z] >= if I[x, y, z] > 0 then 1 else 0;
s.t. each_square_is_river_or_island{(x, y) in V}:
is_river[x, y] + sum{z in Z} is_island[x, y, z] = 1;
s.t. I_match_hint_area{z in Z}:
sum{(x, y) in V} is_island[x, y, z] = island_area[z];
s.t. river_has_no_lakes{(x,y) in V: x > 0 and y > 0}:
3 >= is_river[x, y] + is_river[x - 1, y - 1]
+ is_river[x - 1, y] + is_river[x, y - 1];
s.t. river_squares_have_at_least_one_neighbor{(x, y) in V}:
sum{(sx, sy, tx, ty) in E: x = tx and y = ty} is_river[sx, sy]
>= is_river[x, y];
s.t. island_fields_have_at_least_one_neighbor{(x, y) in V, z in Z: island_area[z] > 1}:
sum{(sx, sy, tx, ty) in E: x = tx and y = ty} is_island[sx, sy, z]
>= is_island[x, y, z];
s.t. I_are_separated_by_water{(x, y) in V, z in Z}:
sum{(sx, sy, tx, ty) in E, oz in Z: x = sx and y = sy and z != oz}
is_island[tx, ty, oz]
<= 4 * P * (1 - is_island[x, y, z]);
solve;
for{y in M-1..0 by -1}
{
for {x in X}
{
printf "%s", if is_river[x, y] = 1 then "." else "#";
}
printf "\n";
}
```
## Problem data
### 5 x 5
```
data;
param M := 5;
param N := 5;
param P := 5;
param I:=
# x,y,z,area
0,1,0,3
4,1,1,1
0,4,2,2
2,4,3,2
4,4,4,2;
end;
```
### 7 x 7
```
data;
param M := 7;
param N := 7;
param P := 8;
param I:=
# x,y,z,area
0,0,0,2
3,1,1,2
6,1,2,2
4,3,3,2
2,4,4,2
0,6,5,8
2,6,6,1
4,6,7,3;
end;
```
### 15 x 15
```
data;
param M := 15;
param N := 15;
param P := 34;
param I:=
# x,y, z,area
5, 1, 0, 1
9, 1, 1, 3
4, 2, 2, 5
6, 2, 3, 1
11, 2, 4, 2
2, 3, 5, 2
9, 3, 6, 3
4, 4, 7, 2
10, 4, 8, 1
12, 4, 9, 5
1, 5, 10, 3
3, 5, 11, 1
8, 5, 12, 3
13, 5, 13, 1
5, 6, 14, 5
12, 6, 15, 1
2, 8, 16, 1
9, 8, 17, 2
1, 9, 18, 1
6, 9, 19, 2
11, 9, 20, 6
13, 9, 21, 3
2, 10, 22, 5
4, 10, 23, 2
10, 10, 24, 4
5, 11, 25, 1
12, 11, 26, 2
3, 12, 27, 2
8, 12, 28, 2
10, 12, 29, 5
5, 13, 30, 1
9, 13, 31, 1
6, 14, 32, 1
8, 14 33, 1;
end;
```
## Usage
Have `glpsol` installed, model as one file (e.g. `river.mod`), input data in separate file(s) (e.g. `7x7.mod`). Then:
```
glpsol -m river.mod -d 7x7.mod
```
This plus some patience will print the solution in the specified output format (together with "some" diagnostic output).
[Answer]
# [Python 3](https://docs.python.org/3.6/), 1295 bytes
This is a python only solution. It uses no libraries and loads the board through standard input. Further explanation to come. This is my first attempt at such a large golf. There is a link to the commented and none-golfed code at the bottom.
```
L,S,O,R,F=len,set,None,range,frozenset
U,N,J,D,I=S.update,F.union,F.isdisjoint,F.difference,F.intersection
def r(n,a,c):
U(c,P)
if L(I(N(Q[n],C[n]),a))<2:return 1
w=D(P,N(a,[n]));e=S();u=S([next(iter(w))])
while u:n=I(Q[u.pop()],w);U(u,D(n,e));U(e,n)
return L(e)==L(w)
def T(a,o,i,c,k):
s,p,m=a
for _ in o:
t=s,p,N(m,[_]);e=D(o,[_])
if t[2] in c:o=e;continue
c.add(t[2]);n=D(Q[_],m);U(k,n)
if not J(i,n)or not r(_,N(m,i),k):o=e
elif s==L(t[2]):yield t
else:yield from T(t,N(e,n),i,c,k)
s,*p=input().split()
X,Y=eval(s)
A=[]
l=1,-1,0,0
P=F((x,y)for y in R(Y)for x in R(X))
exec("Q%sl,l[::-1]%s;C%s(1,1,-1,-1),l[:2]*2%s"%(('={(x,y):F((x+i,y+j)for i,j in zip(',')if X>x+i>-1<y+j<Y)for x,y in P}')*2))
for a in p:a,x,y=eval(a);k=x,y;A+=[(a,k,F([k]))]
A.sort(reverse=1)
k=F(a[1]for a in A)
p=[O]*L([a for a in A if a[0]!=1])
g,h=p[:],p[:]
i=0
while 1:
if g[i]is O:h[i]=S();f=O;g[i]=T(A[i],Q[A[i][1]],D(N(k,*p[:i]),[A[i][1]]),S(),h[i])
try:p[i]=g[i].send(f)[2]
except:
f=I(N(k,*p[:i]),h[i]);g[i]=p[i]=O;i-=1
while J(p[i],f):g[i]=p[i]=O;i-=1
else:
i+=1
if i==L(p):
z=N(k,*p)
if not any(J(z,F(zip([x,x+1]*2,[y,y,y+1,y+1])))for x in R(X-1)for y in R(Y-1)):break
for c in h:U(c,z)
b=[X*['.']for i in R(Y)]
for x,y in z:b[y][x]='#'
for l in b[::-1]:print(''.join(l))
```
[Try it online!](https://tio.run/##ZVT/a9s6EP9df4XeHiGn5BLq9NENuxqUlUJLSNp1hQ5hiuvIjRpXNrazJhnvb@@7U7K9jREi6b597s73keptt6z88dvbFG9xjp/xQpfWY2s7nFXeYpP5J4tFU@2sJ6W4wxle4Tle6tvxul5kncWL8dq7ytPu2oVrnyvnOxIWrihsY33OHqSyTWvzjhzFwhayAY8Z5ioW8g5yvFZCukJO4RJmcGN8ip9oUZgpdTqJG9utGy8jIV/1OVzjDDJks0qsvgWVrGk13m46cJQGXpVKCe916Uor17HXlwS5HtdVDSrFV5XcwRrPqQCr@GzRk/chxxSs0npKGKHML5SpQoc5rrjUFmt80ZmQRdXIB@m8rEgrO82GGbygeUi5qHOowpFs1FVnJin75nGlbZJXvnN@bcmWj7PFAtisEk9BNxSDL1zTKtTEwb7q5BU4kiklCw08hFROcU2ESH62JM@W6w5g8dbZciG7YGntQaQhvlBDNNjQ8qEr0eKg1s7X6w7UuK1LR7u4x6/afstKaJU40yYVpY5wFOERHolrfQGwwa3ij7Dlxj7D1yBs9sK9UsJubA7vbnptiaWJ41GU9trkU6@FCAPQKFJsmKSDSa991wPo6@8BNGbwocPt8DlgOnxm1J2roY99RX3efyT7x1F0Si6nh8QY6rj@t68GE8rOuow1dZwhGfe9ZCpZaZKSs6E2NNgVXoBZEY1ScTZuq6aDxn5jmupIiRV1mZko/Ql1pkStzTwdTMFk8n81DykzR@lfOqKBP@FS1yZOkRfh9JHY0zCKA8GfjEtdK@fxkg6Bu4WeJ6zVX@CMNrwxvFHilCg6IyIMCMnRVfipV0hxyABEka7ZxjWHM8a4tX4BhSIOCGk3ua07pmehL39DCqH7pCF0nriRpst1uDFXwFosVPynS6ATE3MYAqgjx6yr@XJIudP7NEzdH9zN/BauYEefmkdoNrgZRjR0NFuk3zDiP43gN/4QOX7lFokqfmxstmJctuRsWcb8cuyUeNTmfmD6434YlvvByFT8Qo1d/Gi2qdmkuv93PxhKVj/uuRnXDb1Q0O@P@fWCUqm3t/f4Xk6Y8LQeY0TrSVj/wWNaaZcfyHoiIzqfyGPSn/wH "Python 3 – Try It Online")
[Un-golfed code here](https://gist.github.com/TheMatt2/1c55c15e3fa05004a0b7f6e9273d5a65).
] |
[Question]
[
## Background
This challenge is about the [Game of Go](https://en.wikipedia.org/wiki/Go_(game)). Here are some rules and terminology relevant to this challenge:
* Game of Go is a two-player game, played over a square board of size 19x19.
* One of the players plays Black, and the other plays White. The game is turn-based, and each player makes a single move each turn, starting with Black. In the diagrams below, we use `O` for White and `X` for Black. Any other symbol is a blank.
* A *move* consists of placing a new stone of the player's own color on an empty spot on the board.
* Given a group of orthogonally connected stones of single color, the [*liberty*](https://en.wikipedia.org/wiki/Go_(game)#Liberties_and_capture) is the number of empty positions orthogonally around it. For example, the following group has liberty of 7:
```
. . . .
. O O .
. O . .
. . . .
```
and the following configuration has two groups having liberties of 6 and 4 respectively:
```
. . . . .
. O O . .
. . . O .
. . . . .
```
* The opponent can reduce the liberty by placing their own stones around the target group. The following group of `O` has liberty 1 (the only empty adjacent position being `a`):
```
. X X .
X O O X
X O X .
. a . .
```
* If the Black places another black stone at `a`, the white group's liberty reduces to 0, where *capture* happens, and the white group is removed from the board.
* A player cannot make a move where their own stone(s) would be captured, unless it is itself a capturing move. For example, the Black cannot make a move at `a` or `b` (where one or two black stones would be captured immediately), but they *can* make a move at `c` because it captures two White stones on its right.
```
. . . . . O . . . O X .
. O . . O X O . O X O X
O a O . O b O . O c O X
. O . . . O . . . O X .
```
Finally, some terminology that is exclusive to this challenge:
* A *configuration* is one or more groups of stones of the same color.
* A configuration of White (color fixed for ease of explanation) is *fully alive* if Black cannot capture any of the given white stones even if arbitrarily many turns are given to Black.
## Challenge
Given a Game of Go configuration, test if it is fully alive.
The input is a rectangular 2D array representing the state of the board, where each cell is either occupied (`O` in the example below) or empty (`.`).
* You can choose any two distinct values to represent an occupied and an empty cell respectively.
* You can assume the input is always rectangular, and contains at least one stone.
* You can assume the input will always contain a margin of empty cells around the entire configuration of stones. For example, you don't need to handle this:
```
O O O .
O . O O
. O . O
. . O O
```
which will be given as the following instead:
```
. . . . . .
. O O O . .
. O . O O .
. . O . O .
. . . O O .
. . . . . .
```
* You may assume that the entire input (including the margin) will not exceed 19 rows and 19 columns.
* For output, you can choose to
1. output truthy/falsy using your language's convention (swapping is allowed), or
2. use two distinct values to represent true (affirmative) or false (negative) respectively.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code wins.
## Test cases
### Truthy (fully alive)
```
. . . . . . .
. . O O O O .
. O . O . O .
. O O O O . .
. . . . . . .
. . . . . .
. O O . . .
. O . O O .
. O O . O .
. . . O O .
. . . . . .
. . . . . .
. . O O . .
. O . O O .
. O O . O .
. . O O . .
. . . . . .
. . . . . .
. O O . . .
. O . O . .
. O O . O .
. . O O O .
. . . . . .
Truthy since both eyes must be filled in order to capture any of the two groups
. . . . . . .
. . O O O . .
. O . . O O .
. O O O . O .
. . . O O . .
. . . . . . .
Ditto
. . . . . . . .
. . O O O . . .
. O . . O O O .
. O O O . . O .
. . . O O O . .
. . . . . . . .
. . . . . . .
. . O O O . .
. . O . . O .
. O . O O O .
. O O . O . .
. . . O O . .
. . . . . . .
. . . . . . .
. . . O O O .
. . . O . O .
. O O . O O .
. O . O . . .
. O O O . . .
. . . . . . .
. . . . . . . . .
. . O O O O O O .
. O . . O . . O .
. O . . O . . O .
. O O O O O O . .
. . . . . . . . .
```
## Falsy (not fully alive)
```
. . .
. O .
. . .
. . . . .
. O O O .
. O . O .
. O O . .
. . . . .
. . . . . . . . .
. O O O . . O O .
. O . O . O . O .
. O O . . O O O .
. . . . . . . . .
. . . . . . .
. O O . O O .
. O . O . O .
. O O . O O .
. . . . . . .
The right group can be captured by Black, since Black doesn't need to fill
the upper area (of size 2) to capture it
. . . . . . .
. O O O . . .
. O . . O O .
. O O O . O .
. . . . O O .
. . . . . . .
The center singleton can be captured by Black
. . . . . . . . .
. . . O O O . . .
. O O O . O O O .
. O . . O . . O .
. O O O . O O O .
. . . O . O . . .
. . . O O O . . .
. . . . . . . . .
. . . . . . . . .
. . O O O O O O .
. O . . . O . O .
. O . . . O . O .
. O . . . O . O .
. O O O O O O . .
. . . . . . . . .
One part is fully alive but the other is not
. . . . . . . . . .
. O O O . . . O O .
. O . O O . O . O .
. . O . O . O O . .
. . O O . . . . . .
. . . . . . . . . .
```
[Answer]
# JavaScript, 178 bytes
```
(a,w,Q=(a,v)=>q=o=>a[o]?a[o]-v?0:[o+w,o-w,o+1,o-1].map(q,a[o]++).some(x=>x):a[o]=v/2)=>!a.some((c,i)=>c&&(E=Q(b=[...a],2)(i),b.map((d,j)=>d==1&&!Q([...b],1)(j)&&--b[E++,j]),E<3))
```
```
f=
(a,w,Q=(a,v)=>q=o=>a[o]?a[o]-v?0:[o+w,o-w,o+1,o-1].map(q,a[o]++).some(x=>x):a[o]=v/2)=>!a.some((c,i)=>c&&(E=Q(b=[...a],2)(i),b.map((d,j)=>d==1&&!Q([...b],1)(j)&&--b[E++,j]),E<3))
testcases = `
. . . . . . .
. . O O O O .
. O . O . O .
. O O O O . .
. . . . . . .
. . . . . .
. O O . . .
. O . O O .
. O O . O .
. . . O O .
. . . . . .
. . . . . .
. . O O . .
. O . O O .
. O O . O .
. . O O . .
. . . . . .
. . . . . .
. O O . . .
. O . O . .
. O O . O .
. . O O O .
. . . . . .
Truthy since both eyes must be filled in order to capture any of the two groups
. . . . . . .
. . O O O . .
. O . . O O .
. O O O . O .
. . . O O . .
. . . . . . .
Ditto
. . . . . . . .
. . O O O . . .
. O . . O O O .
. O O O . . O .
. . . O O O . .
. . . . . . . .
. . . . . . .
. . O O O . .
. . O . . O .
. O . O O O .
. O O . O . .
. . . O O . .
. . . . . . .
. . . . . . .
. . . O O O .
. . . O . O .
. O O . O O .
. O . O . . .
. O O O . . .
. . . . . . .
. . . . . . . . .
. . O O O O O O .
. O . . O . . O .
. O . . O . . O .
. O O O O O O . .
. . . . . . . . .
. . .
. O .
. . .
. . . . .
. O O O .
. O . O .
. O O . .
. . . . .
. . . . . . . . .
. O O O . . O O .
. O . O . O . O .
. O O . . O O O .
. . . . . . . . .
. . . . . . .
. O O . O O .
. O . O . O .
. O O . O O .
. . . . . . .
The right group can be captured by Black, since Black doesn't need to fill
the upper area (of size 2) to capture it
. . . . . . .
. O O O . . .
. O . . O O .
. O O O . O .
. . . . O O .
. . . . . . .
The center singleton can be captured by Black
. . . . . . . . .
. . . O O O . . .
. O O O . O O O .
. O . . O . . O .
. O O O . O O O .
. . . O . O . . .
. . . O O O . . .
. . . . . . . . .
. . . . . . . . .
. . O O O O O O .
. O . . . O . O .
. O . . . O . O .
. O . . . O . O .
. O O O O O O . .
. . . . . . . . .
One part is fully alive but the other is not
. . . . . . . . . .
. O O O . . . O O .
. O . O O . O . O .
. . O . O . O O . .
. . O O . . . . . .
. . . . . . . . . .
`.trim().split('\n').filter(x => !/[^\.O ]/.test(x)).join('\n').split('\n\n');
testcases.forEach(test => {
grid = test.match(/[\.O]/g).map(v => v == 'O' ? 2 : 0);
width = test.match(/(?<!\n.*)[\.O]/g).length;
table = document.body.appendChild(document.createElement('table'));
grid.forEach((v, i) => {
if (i % width == 0) row = table.appendChild(document.createElement('tr'));
ceil = row.appendChild(document.createElement('td'));
ceil.textContent = v ? '◯' : '';
});
output = document.body.appendChild(document.createElement('output'));
output.value = f(grid, width);
document.body.appendChild(document.createElement('hr'));
});
// P=(a,n=[],o='')=>{for(i=0;i<w*w;i++){if(n[i])o+='+';else o+='.XO'[a[i]];if((i+1)%w==0){print(o);o=''}}}
```
```
table { font-family: monospace; table-layout: fixed; border-collapse: collapse; }
table, tr, td { padding: 0; border: 0; }
td { line-height: 22px;width: 22px; height: 22px; text-align: center;
background: linear-gradient(to bottom, transparent 0, transparent 10px, #80808080 10px, #80808080 11px, transparent 11px, transparent 100%), linear-gradient(to right, transparent 0, transparent 10px, #80808080 10px, #80808080 11px, transparent 11px, transparent 100%); }
```
Input two parameters. First one is the board. The board is an 1d array, 2 for white, 0 for empty. Second one is its width, an integer.
Details (with comments):
```
(a, // input board as 1d array; 2 = white; 0 = empty
w, // input width of board
Q= // test if some stones on board `a` is alive
(a, // board to test
v // color of stone to test
)=>q=o=> // stone to test (when invoke by outside, a[o]==v always hold)
/*
We modify the board in-place. So caller need to duplicate a board if it requires the original one.
For input, we test if stones with color `v` connected to `a[o]` has at least 1 liberty.
And we modify connected stones by +1; modify all liberty by +v/2
Here, {0, v/2, v} should / would not be equal.
*/
a[o]? // If current ceil is not a liberty
a[o]-v?
0: // If current stone is something already visited or with wrong color (opposite color)
// It is not a liberty, we return 0
// If current ceil is connected stone which never visited
[o+w,o-w,o+1,o-1].map(q, // visit all its neighbors
a[o]++ // modify current ceil to remeber we had visited it
).some(x=>x): // Is there any liberty?
a[o]=v/2 // Current ceil is a liberty; mark it as visited, also return something truthy
)=>
!a.some( // Try to find out any stones may be captured
(c, // stone on board
i // position of stone
)=>c&& // current ceil is white stone (not empty)
(E= // Initial E to true (1)
// Input only contains white, and have an empty border
// So every white stones on inputed board has liberty as we known
// And Q(...)(...) would always return true
// We use this value to initialize variable E
Q(
b=[...a], // b is a duplicate of board, also used later
2 // White = 2
)(i),
b.map( // Try to find some black (black = 1 here) stones without liberty
(d,j)=>
d==1&& // Current ceil is black
!Q([...b],1)(j)&& // Current ceil has no liberty
--b[
E++, // We found a real eye for white, count it
j] // Pick current black stone up, as it should be placed as final move
),
E<3 // If white stones has less than 2 real eyes
// (E is initialized to 1, so E<3 means less than two E++ happened)
// we would be able to capture these white stones
// thus, we found some white stones not fully alived
))
```
] |
[Question]
[
This challenge is inspired by a talk about Schläfli symbols, etc that I gave in a Geometry seminar. While I was putting together this challenge, I saw that [Donald Knuth](https://en.wikipedia.org/wiki/Donald_Knuth) himself was interested in (some subset of) this problem. In October 2016, he [commented on a related OEIS sequence](https://oeis.org/history?seq=A119611&start=30):
>
> If [the OEIS author] is wrong about the hyperbolic {4,5} pentominoes, the next number is probably mistaken too. I don't have [time] right now to investigate further.
>
>
>
Successful completion of this challenge will have you investigating something that Donald Knuth might have investigated if only he had more time, and will result in new additions (and perhaps a rare correction) to the On-Line Encyclopedia of Integer Sequences.
---
# Challenge
This [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge will have you create a function that counts "free polyforms" on the hyperbolic plane. In particular, you will write a function that takes three positive integer parameters `p`, `q`, and `n` and counts the number of \$n\$-cell "free polyforms" on the tiling of the hyperbolic plane given by the Schläfli symbol \$\{p,q\}\$.
Shortest code wins.
---
# Definitions
The [Schläfli symbol](https://en.wikipedia.org/wiki/Schl%C3%A4fli_symbol) \$\{p,q\}\$ describes a tiling of the hyperbolic plane by \$p\$-gons, where each vertex touches exactly \$q\$ of the polygons. As an example, see [the Wikipedia page](https://en.wikipedia.org/wiki/Order-5_square_tiling) for the \$\{4,5\}\$ tiling that Donald references above.
A free [polyform](https://en.wikipedia.org/wiki/Polyform) is a collection of regular polygons that meet at their edges, counted up to rotation and reflection.
---
# Input
You can assume that the values of `p` and `q` which define the tiling indeed describe an actual tiling of the hyperbolic plane. This means that \$p \geq 3\$, and
* when \$p = 3\$, \$q \geq 7\$,
* when \$p = 4\$, \$q \geq 5\$,
* when \$p = 5\$, \$q \geq 4\$,
* when \$p = 6\$, \$q \geq 4\$, and
* when \$p \geq 7\$, \$q \geq 3\$.
---
# Data
OEIS sequence [A119611](https://oeis.org/A119611) claims that `f(4,5,n) = A119611(n)`, but Donald Knuth disputes the reasoning for the value of \$A119611(5)\$. (When I counted by hand, I got Knuth's answer, and I've included it in the table below.)
| \$p\$ | \$q\$ | \$n\$ | \$f(p,q,n)\$ |
| --- | --- | --- | --- |
| 3 | 7 | 1 | 1 |
| 3 | 7 | 2 | 1 |
| 3 | 7 | 3 | 1 |
| 3 | 7 | 4 | 3 |
| 3 | 7 | 5 | 4 |
| 3 | 7 | 6 | 12 |
| 3 | 7 | 7 | 27 |
| 3 | 9 | 8 | 82 |
| 4 | 5 | 3 | 2 |
| 4 | 5 | 4 | 5 |
| 4 | 5 | 5 | 16 |
| 6 | 4 | 3 | 3 |
| 7 | 3 | 1 | 1 |
| 7 | 3 | 2 | 1 |
| 7 | 3 | 3 | 3 |
| 8 | 3 | 3 | 4 |
| 9 | 3 | 3 | 4 |
Note: these values are computed by hand, so let me know if you suspect any mistakes.
# Final notes
The output of this program will result in quite a lot of new, interesting sequences for the OEIS. You are of course free to author any such sequences—but if you're not interested, I'll add the values you compute to the Encylopedia with a link to your answer.
[Answer]
# [GAP](https://www.gap-system.org) and its [kbmag](https://gap-packages.github.io/kbmag/) package, ~~711 682~~ 658 bytes
Note that the `kbmag` package consists not only of GAP code, it contains C programs that have to be compiled (see the package's `README` file).
```
LoadPackage("kbmag");I:=function(p,q,n)local F,H,R,r,s,x,c;F:=FreeGroup(2);s:=F.1;r:=F.2;R:=KBMAGRewritingSystem(F/[s^2,r^p,(s*r)^q]);AutomaticStructure(R);H:=SubgroupOfKBMAGRewritingSystem(R,[r]);AutomaticStructureOnCosets(R,H);x:=w->ReducedCosetRepresentative(R,H,w);c:=function(n,U,S,P)local N,Q,Z;if n=0 then Z:=Set(U,t->Set(U,p->(p/t)));return 1/Size(SetX(Union(Z,Set(Z,Q->Set(Q,q->(MappedWord(q,[s,r],[s,r^-1]))))),[1..p],{Q,i}->Set(Q,q->x(q*r^i))));fi;if P=[]then return 0;fi;N:=P[1];Q:=P{[2..Size(P)]};Z:=Filtered(Set([1..p],i->x(s*r^i*N)),w->not w in S);return c(n,U,S,Q)+c(n-1,Union(U,[N]),Union(S,Z),Union(Q,Z));end;return c(n,[],[r/r],[r/r]);end;
```
This is the result of removing indentation and newlines from this version, and some inlining:
```
LoadPackage("kbmag");
I:=function(p,q,n)
local F,G,H,R,r,s,x,c;
F:=FreeGroup(2);
s:=F.1;r:=F.2;
G:=F/[s^2,r^p,(s*r)^q];
R:=KBMAGRewritingSystem(G);
AutomaticStructure(R);
H:=SubgroupOfKBMAGRewritingSystem(R,[r]);
AutomaticStructureOnCosets(R,H);
x:=w->ReducedCosetRepresentative(R,H,w);
c:=function(n,U,S,P)
local N,Q,Z;
if n=0 then
Z:=Set(U,t->Set(U,p->(p/t)));
Z:=Union(Z,Set(Z,Q->Set(Q,q->(MappedWord(q,[s,r],[s,r^-1])))));
Z:=SetX(Z,[1..p],{Q,i}->Set(Q,q->x(q*r^i)));
return 1/Size(Z);
fi;
if P=[]then return 0;fi;
N:=P[1];Q:=P{[2..Size(P)]};
Z:=Filtered(Set([1..p],i->x(s*r^i*N)),w->not w in S);
return c(n,U,S,Q)+c(n-1,Union(U,[N]),Union(S,Z),Union(Q,Z));
end;
return c(n,[],[r/r],[r/r]);
end;
```
If the line containing `{Q,i}->` doesn't work, your GAP is too old. You can then replace that line with:
```
Z:=SetX(Z,[1..p],function(Q,i)return Set(Q,q->x(q*r^i));end);
```
Several of the `Set` operations could be slightly faster `List` operations (the improved version at least uses that it is a set for even more golfing *and* a little speed compensation), but that would cost one byte each time.
And yes, Knuth's and your result is confirmed:
```
gap> Read("i.gap");
─────────────────────────────────────────────────────────────────────────────
Loading kbmag 1.5.9 (Knuth-Bendix on Monoids and Automatic Groups)
by Derek Holt (https://homepages.warwick.ac.uk/staff/D.F.Holt/).
Homepage: https://gap-packages.github.io/kbmag
─────────────────────────────────────────────────────────────────────────────
gap> I(4,5,5);
16
gap> I(4,5,6);
55
gap> I(4,5,7);
224
gap> I(4,5,8);
978
gap> I(4,5,9);
4507
gap> I(4,5,10);
21430
```
The \$n=7\$ computation already takes several minutes. My computations also agree with the other results in the table.
[Answer]
# [bc](https://www.gnu.org/software/bc/manual/html_mono/bc.html), ~~673~~ 670 bytes
-3 bytes thanks to *@ceilingcat*
```
define y(){t[z=u[x[++n]=e]/p]=1;for(o=p;o--;){if(!u[a=z*p+o]){v(u[u[a]=c=s]=a);s+=p;v(c)}}}define j(e,i){return(e%p+p+i)%p+e/p*p}define v(e){auto l;for(l=j(e,b=1);y=u[e];++b){e=j(y,-1)};for(;y=u[l];++b){l=j(y,1)};if(b==q)v(u[u[l]=e]=l)}p=read();q=read();g=read();u[e=s=2*p]=p;y();e=p;for(y();e==p;){while(n-1){if(t[e/p]*!t[u[e]/p]){c=y();for(o=6;o-=2;){for(d=s;d--;){i[a=w=2]=f=u[d];if(t[d/p]*t[f/p]){i[b=1]=d;m[d/p]=m[f/p]=++r;for(z=0;w-z++;){for(f=i[z];f=j(f,o-3)!=i[z];a*=2){if(t[y=u[f]/p]){b+=a;if(m[y]<r){i[++w]=u[f];m[y]=r}}}};if(c<b)c=b}}};for(k[h]=c;k[o++]-c;){};if(o>h){++h;if(n<g){e=p;break};++l};t[u[e]/p]=0;--n};while(++e>s){t[u[e=x[n--]]/p]=0}}};l;if(g<3)1
```
[Try it online!](https://tio.run/##PVLJkuIwDL3PV8BhqiyEqwd6loNR/4jLhywOZAiJOws0SeXbGcmBOUWb33t6Spo9Hrkvytqv7gqm3o402C@LWDvy7i042pmiaVVDwTRaG5jKQq0Hm9C4Cdg4mK5qsJw7yqhzlIDpkGevKoN5np/Qf5XfljC1vh/aWvnvAQOWwB//FjbhNXVVHqZk6JtVFTkrkncp7cDcWZV3BjGFyXP5vtU7mONU7FXPXhV70mKZKdEnLPIq2YYqmAO1PskVmM9XcHwFzEAd7Te8czBshvH8FYYl5gSm26msvKqZXHzoLet3m3VvRR2HMGUk04tjv9kx2vMrSXPqTL4YyObdaO@oYOG5MxEoF6DeFhGktLy0o9xcYp0usU6IbUQe6Ye56RHxCV1QaUdnCt692Db6HdZLIdnQ/qlTPCoWhSlSIpwXe3eHVsgQby72jdSo5btF/7JDChmlkgnN2Z74yOZsG0SnMyaPU83HCSbEk8T14Sj3CSZlT88z36SazX93WLbW9WwWExH9Ryd/nPj@ZWut3TIkfJWgHQ/vsPv2ePxc/Vr9@Qc "bc – Try It Online")
This is a golfed version of the C code I'm about to post. Here, you have to supply the parameters (p, q and n) on standard input when bc is running. The code spits out lots of numbers while it calculates (because statements such as i+=1 are silent, but ++i is a value and is printed) -- the answer is the final number.
n<3 has to be handled as a special case. Infinite planar grids are handled OK (which gives us lots of test cases). Finite grids (the Platonic solids, but also p=2 and/or q=2) are not handled reliably.
Here we are counting "free" polyominoes, unique up to translation, rotation and reflection. If you had asked the same question but disallowing reflection, I could have saved a few bytes and even beaten Christian's excellent answer as it stands. (I don't know if that answer would be shorter for the not-free question.) Here's the not-free code:
[Try it online!](https://tio.run/##PVLJktowEL3nK@CQKrV7VBNIUjmInh9R6eBFBgdja7zAYJe/nXTLkJN6f69fK8sfj8KXVeM3dwXzYCca7ZdFbBx59x4c7UzZdqqlYFqtDcxVqbajTWlKArYO5qsaLfuOcuodpWB65NqrymFZlufov8q/VTB3fhi7RvnvAQNWwI9/D0l4VV2Vhzkdh3ZTR8yapC@jHZg7s/LOIGYwew7f3/QOllgVc/UzV8ecpJhmRvQJK71atqEalkCdTwsF5vNlHF8GI1BP@4R3DobFMJ5fQVhtdmC@naraq4bBRYfBMn@XbAcr7NiEOSeplq6CeqN1IYqxWjfaOyqZaeFM7Cykc7Bl7Kosb@moMJcYp0uME2IXR030w9z0hMjDxC@pspMzJS9b8rLb1U0T2j9piSTlSihDSgXxYu/u0AkU4s3FvJEYdXymKFd@yCCnbFllPdsTn9ScbYHodM7Isaj4OMGMeBK7ORzlGsFkrOB54QvUi/mvBXPWulnMKhmi/@jlf4nKX7bR2q1FAl7LtOPhJ@y@PR6/Nr83f/4B "bc – Try It Online") (~~655~~ 652 bytes, answering a different question).
Here's the main code unwrapped:
```
define y(){
t[z=u[x[++n]=e]/p]=1;
for(o=p; o--;){
if(!u[a=z*p+o]){
v(u[u[a]=c=s]=a);
s+=p;
v(c)
}
}
}
define j(e,i){
return(e%p+p+i)%p+e/p*p
}
define v(e){
auto l;
for(l=j(e,b=1); y=u[e]; ++b){
e=j(y,-1)
};
for(; y=u[l]; ++b){
l=j(y,1)
};
if(b==q)v(u[u[l]=e]=l)
}
p=read();
q=read();
g=read();
u[e=s=2*p]=p;
y();
e=p;
for(y(); e==p;){
while(n-1){
if(t[e/p]*!t[u[e]/p]){
c=y();
for(o=6; o-=2;){
for(d=s; d--;){
i[a=w=2]=f=u[d];
if(t[d/p]*t[f/p]){
i[b=1]=d;
m[d/p]=m[f/p]=++r;
for(z=0; w-z++;){
for(f=i[z]; f=j(f,o-3)!=i[z]; a*=2){
if(t[y=u[f]/p]){
b+=a;
if(m[y]<r){
i[++w]=u[f];
m[y]=r
}
}
}
};
if(c<b)c=b
}
}
};
for(k[h]=c; k[o++]-c;){
};
if(o>h){
++h;
if(n<g){
e=p;
break
};
++l
};
t[u[e]/p]=0;
--n
};
while(++e>s){
t[u[e=x[n--]]/p]=0
}
}
};
l;
if(g<3)1
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~753~~ ~~745~~ 705 bytes
-8 bytes thanks to *@ceilingcat*
-40 bytes, *@ceilingcat* strikes again!
```
#define X[99999]
#define S o=p;F[z=N[O[++n]=e]/p]=1 W o--)N[a=z*p+o]||v(c,s+=p,v(N[N[a]=c=s]=a))
#define W;while(
#define T atoi(*++V)
long C X,a,b,c,p,q,o,N X,F X,s,O X,A,n,P,e,m X,Q X,d,f,j,w,z,r;I(e,i){return(e%p+p+i)%p+e/p*p;}v(e,l){l=I(e,b=1)W N[e])++b,e=I(N[e],-1)W N[l])l=I(N[l],1),++b;b-q||v(N[N[l]=e]=l);}main(M,V)int**V;{p=T;q=T;M=T;N[e=s=2*p]=S;e=S;G:e=p W~-n){if(F[e/p]&!F[N[e]/p]){S;c=0;o=4 W o){d=s W d--)if(F[d/p]&F[(Q[a=w=2]=j=N[d])/p]){Q[b=1]=d;m[d/p]=m[j/p]=++r;z=0 W w-z++){f=Q[z]W(f=I(f,o-3))-Q[z])j=N[f],F[j/p]&&m[b+=a,j/p]<r?Q[++w]=j,m[j/p]=r:0,a+=a;}c=c<b?b:c;}o-=2;}C[P]=c W C[o++]-c);if(o>P){++P;if(n<M)goto G;++A;}F[N[e]/p]=0;--n;}W++e>s)F[N[e=O[n--]]/p]=0;}printf("%d",M<3?:A);}
```
[Try it online!](https://tio.run/##PVHbbtswDH3vV3gdWlgRhebSPSwKGwQFUuwhN6RoCgh68EXOXDiWa2cJENf79HlU1sUALfLwiBQPI7GNorb9GpskzY33qr67T1/9B9aexUJO1QnnaqE4zzUafVdo7HkbzwrB5irAU6fgVn98HPwIKo4FHPy5ooTGCCuNAWOXeht5/Jlmxr8Az16wt6nf4fyFXWU233qP3isEEEIEBbyDhTnFU7IKFvSfQA5LMLAjf0UWQwJvcIQTlPKHbyBldWn2v8rcNzcFL3jK6DB3RaeQzYHyGaszdMQQe2zjzZXRjPMQDIEuAPEPzjTLzlCmoceAKDIU725GN1rmZMCMyWYXpLk/gxeW5vtO50XWBT7Ld7IZGRXECvsd0mstDdnT0GDhbX6LnNVp4k8VvUzffpkq15pcVq9lhF1p8d7py@oYK3JiEvpMjx19qvwVqX7EvsY32kus2fnqStFMGmO5O/Nwp97cwXkpT9ilMkdx4pzVCa7USW/8hOZLwIoBY8IhzBVLNEzP925vdyrkGIALRuV4Rds/UkP4LFsOuxBQXjYRRqNwHA4j2ViBfdk8qiWtnho@Ksu5FhGT9Hr7sGQ150vn56MZ29q99Z4k5xPZXASg2YXIZbPh3DxU7IzjQuVC6M90U5QkdeJf38TXMBsNxsMJraFt2/v2W9vr/omSLNhWrVgM/gI "C (gcc) – Try It Online")
Parameters p, q and n are supplied as command-line arguments.
The array C[99999] contains a characteristic value for each polyomino found, of the specified size and all smaller (down to n=2). For p less than 7 or 8 or so, this is probably the limit on how far you can go up a sequence. For larger p, you might well run out of edges, for example in the array N[99999]. There is also a constraint that the characteristic values need (p-1)\*n bits, and here we are using 63ish bits. If we stick to unambitious values of p, q and n, I could save a handful of bytes with int and 9999. If you exceed any of the limits, there is no error trapping.
Here's the code unwrapped, but it's still fairly dense:
```
#define X[99999]
#define S o=p;F[z=N[O[++n]=e]/p]=1;while(o--)N[a=z*p+o]||v(c,s+=p,v(N[N[a]=c=s]=a))
#define T atoi(*++V)
long C X,a,b,c,p,q,o,N X,F X,s,O X,A,n,P,e,m X,Q X,d,f,j,w,z,r;
I(e,i){
return(e%p+p+i)%p+e/p*p;
}
v(e,l){
l=I(e,b=1);
while(N[e])++b,e=I(N[e],-1);
while(N[l])l=I(N[l],1),++b;
b-q||v(N[N[l]=e]=l);
}
main(M,V)int**V;
{
p=T;
q=T;
M=T;
N[e=s=2*p]=S;
e=S;
G:e=p;
while(~-n){
if(F[e/p]&!F[N[e]/p]){
S;
c=0;
o=4;
while(o){
d=s;
while(d--)if(F[d/p]&F[(Q[a=w=2]=j=N[d])/p]){
Q[b=1]=d;
m[d/p]=m[j/p]=++r;
z=0;
while(w-z++){
f=Q[z];
while((f=I(f,o-3))-Q[z])
j=N[f],F[j/p]&&m[b+=a,j/p]<r?Q[++w]=j,m[j/p]=r:0,a+=a;
}
c=c<b?b:c;
}
o-=2;
}
C[P]=c;
while(C[o++]-c);
if(o>P){
++P;
if(n<M)goto G;
++A;
}
F[N[e]/p]=0;
--n;
}
;
while(++e>s)F[N[e=O[n--]]/p]=0;
}
printf("%d",M<3?:A);
}
```
This post seems rather long already, so I'll link to TIO with a copy of ungolfed code with comments. The golfed code uses basically the same approach:
[Try it online!](https://tio.run/##rTzpctvImf/1FD1OuYa0QAqkqMsSnHI8mkSJ43HZznqzEy0LBJogLBCAANCSYus59oH2wbzf0Y3uBiGPnY3nsAT08fV3X41olETRly97T8RbKUVeNLIWYSNkHosnezu/S/Mo28RSnNVNnBbj1TP3UZYu3Gdp3jR3pazdp2Fdy6pxnzXpWtKTWC7TXApRhnkaDdZDEReflmUFKy0HsIWsKu/R4/qHf@SPPLEensrbtBmMJsPT@5tVmsmBP9zZgbGi9K69LF2nzTyf1zKTUSNjbx3ezrsPT9st//r8P@fnP/3x/K2Y@PSHFpJxIue5TJPVothU9a/tqMtTer/MwqRdbL4MI9k/JCrWZSYbOf8IZ5e3W4Nymlt7dRlWco67nu5s8jpNchkLWgVez9dhdeXAIIBUm5qGiCjMonm0CqsQYKnSukkjpFr/KrIKfPfsb89fnr94d/HLq7fi5OSEgCqqNEnzsCmqX90RvPG7VVoL@LdZScKTuFkVNbCNxpa4Cfmlxg9tP0ag@Mh1kW2atMjreZ3@U27toUe1pMLfkYgtvqU5wp@ev/3T24v/OtfU84925nN520g4fpHP5wI5EcaKFh/zOaw3mR6LDf89b@hUq6Yp66d7e3UTRlcFkGuZFTdjoN/e9UbWBO7ewexwduLPfMKvni1WYb1qwkUmf9XAtGfAV3OZN1Uq6w7i/3DxTgwGg3aZ4WR4djaZHg3bQT9fvHn7jiguyp0dAPFiKST8QdyHOaM@zWN5y3zQYVlvRzyBYbG4AQKFAE1TiDWcS6TwR9SNLGtRFRsYgKRCCokoK6Krm7SWNBce5/bkmyos1YwUcAniqyf@WIuoyJA2gCWcCkIZrRDMn5@UHvy3O/HG4zH9NChBbMc46B3OhmnFTZonIO@SmeZDsfDgeSXKok6bFACGn3OZhPQzAT8a4fx0CdD9@BHBTqMrwIE6TUHLlJX8mBabmmffsgjQueBIYRzj83qzaFBqRImzEtmIBdBerxBtqkoq2SHm1XS5ePXizflfz1@9m79/8/z16/OfBkgVD0EbioH4x46AP/hoFx/tlk/o/V45GrQPh3vlEFSWXvH5yzfnz3/6@/zi1RxZSPjtm9cvn784/6l9MYG1gWF2UEUDGxN/GRYS0XDnE4wAVnlZFFeExQhZA4cJYtExAkectCRshVklw/gOD1xJT1Sy2VS58M0w2Kk7CKgPykykDRACqVBvIlBh9XKTtQtMzAJNAXwX5jAbhUDcpM2q2ABWgXOR7qFIwtITHzZ1w8qfZ/L05zgNTATSDCfA6EUW5ldikAIc/5RVMRQoXXd4SKRZK4oeL4DaqJZhxdyIUk0iEeFveLLuNAU2sWZaIUgZCgZwRGYhtLZEPnrcCr115hVYTxi2TEEqYoY2L/IRQ7yA4@PmiAoReQLsg1gFEc9G8JYSJq2Q0AUK@ssXfxRlLTdxUcHbYg2cmssK1TOgu5QhaMTs7ilPFzAvEKsnf/3by3cXr19enL8Ru8L6ZbAu4qGY/jfwi9kPEWhOtNo60Ts8Ti3luiY9UFRXKF5g44EuWYZcYOgD1KSDAWb3faY5L7LJM2ASF92kycqyKsJohcxw5D8WwEaZ2vfPyBRk4cC8XKCoLzZ5ghjFVRAti00NUlLXHvIhYX0ZppnaEYEKAT4S6iIXg2g3HbaHI2KmwcSbevuonQw6nKVEuGyIawrkfrKYuML83ZuL87ce7kGsm6By2pS8yh5LqUi9D6fwo2Up3F8NXU5ZatH70nbo5uZmXEbJiGk@LqpkDzRiU@@hphylzWgBlB8BUKN1mqfrMBuB5crjsIrHq2adWYzc6tiPYbaRdG6LI4AEEzD8h0fT2aE/Ozo@Pj7Zn05Pjo73Z/7s4Pjo@PDgyD85mfkHCqtat4fAfWAe1@AlAkXgRKMFqASkCpDs33uMi0bEuBfMRM@0Fgfif/9H7B@fHBwe7eOP05PDk5N9OMfRwcFsf0rP9mcHh4fHB7OZfzSZnuyfMF3YjN4Vm9augeuUJyTjSJnD2bzxSCIMjoITxNDM3/ePD44Ppvuz46MjXs3CYyD8W8CiPwsPF4uDeBrNlotvdiz2J7PDyf7keGvVs7NAHM5O3Ye7uNd@GB7ODuKlfzDzp4fHHY/W8CiIIcxm53sQ/RBYHoc/JADfS/QlhY8oQK0cgUYRcl02d56oAT9B4BO9PxZp/KDLOWbQQY8hsMBjgxQcnvTMBeZ0F0TwExnID8EAABkOVo9tJ0hL53B4SqPS5cBopg@XAMrnz@6DaLgA63TFw1dPAleo4NFu59H9Di2bBoEL21B8Qmwg6UNRp@i3V6SqUHRqcBQamdw95WNCoMKxyaPz2wi0NaDFXSx4HAvUTQkJhJ49xvils@ups5zrMgJTPY498Th5zHrxHzku4I7xBuD5jv0ng7jYAE6G7tvh3kC/6KL2Q2BsFz/5Bqp9N0WE2N39oH/88Dhwd7z/Gj04Fnz0Isx/ZH@B/Rg2@Oh61JZjQ/j5/SM62xaIkYJeeScdd4uYQma15EHO1Ijh3N110XpqL@f6aMxi9zu2pt/pEZhB66uB/CnJDUUG70SxFKBKa7ZCMo@KWPYEVLUy@ZMx8FcIDhkMBsYtZZQuUxhD8YH0cbXQncnzpmMy5cijJg7ASTVOURawExWwi4E2W5K1n2hnmeAmw6liiYW8K2jNsFGRCntcbVQODvj2ev53rafXUrZ7f6z9uSxs0Gij3@D1rWLN9SjOMZDEsXV0BQzoabCbsE5KwR6dYyEhOoLRsvWh2zUG4BRgrM1UAoMpCSr0sdCFMRPt5YfqELMxR2ngr6jXbfSiT8fgoKeSFDgIYzkxNdQhbiDfujExOh0KeDdJwIcHDAB7ARApmh8HDrPMJm/STKADxedwdjdHaSryQBX4hpcbzBIAG4@IlIC1FwPpDz3jZgGWIvBu1fAXP@Jr0IMF6lOEXu0HVjptWRDIBsEHRiANoFzt@aq4aVcJwIv4xDvxivfK64djgCzAmviTK0dWsNOmGJ5NPMvTqevNGl1yCn8aRU8VIaDTA/LyArzeDNF1E97BucGcqqOCBYWTxgVxTS6Z7DU474omMH8bKRU4BlUaNUrqKYCBTSTJB8soRQ/OQRDJbfyvDvU2XadZWGV33jbIEhBzh0FwLYGoKtLlY1jwL2QUonsAkCVFwzGgWFYQhqC2yq@0plnI5gb5YdrBbh8a9PExbUSaTqa4rhV9IYjEOOu0JjPKgwn@UbEcsTTjVJRlXI4ck9DSubytJQsq6UJoVoovLm5yKw5SiS3Q1jrIeOQq7UesGpEmhMJeRnq7CkuptHdYcZqkDtcYH5CogStcg4YCyYN4uWjoJ9q/kss2iYILkZC1s11ILJ6J0@VSUqoCoKp5lnnmTqstHOeb9QJEQ1ubCrggJTzWgrI0T6wcaktE7SMDYZJVo1QhGKlik6wosjXhDcjyAuwoBOe1iYvMawhJIIydRx5AB9ETygGwfpzGoE7mZHdTOhIIvP6FdM92vpBfSt@Tnpx4iZeCi8TK7Bp@orRnDD/ERS69xMfxem/bGx5NTneU60qbBpNT@vtZMFI/jYKpciSMp2TlKW0vKfGDbgrZyqqml5en7cBRkPiPS/07rix9eHQq/bPE3y1hWVBjel1ybn7oyT5Lf6@8HEYFaMt8I0/b4ckWHNK/PP2t1ZL@xXZ3rUSys4j1/CywwbVxFXSSuIgwa6Cwk93pZeCfWi8f2Pq@/anlooDl3IyxuMqJfswIxS72jtfwCwWLmGBFGdHpwLSRa1Q1bAdVNEAziDnVUpeBtBaTE@dX65hEtqD3aCpkg7kweWgDyxwN/GkRRu17@hA4Se/2yYO744q8j70zipCNJa6@TBx6ywBA5t2vL20S8uCBDHoSqB4J2HD4A0x2VuvlYGfZrzOxu5bDDJ@DlmdOO6NgRWvgM60utlYTaBMLctHm0u@ucu/8TiGGIyuM/zML/1sb9BD2t8j7HUR@mNTb4Le4evbM5jyN//a1DtteFU1rFshO5x1T9Ghor3K/4wKEnGa/hz2ug0Cdt4MmJSmKPQOjkoen/eOUAD08EnbTNP8hsDhhiz5qST34mT22i@fW6HTM3EMYd6LobRxd21pQceBTo/Q6yvselRn4j1lRlFpr0TPXhRFpO@J36RLrZq9@effzm/NzmgDDXxTrEsSY3c/RT@otBkfGe9GxHlUosewUNuRIF@uiKsGpFmWR3RXgqRfKZ1Lud7sYT2efPqYkq0p5d72g2g4YTJSAXpETN@hN3IJXjVkE7fQZ8FuQ3uMZNVA2NEQZgWUMcLZwa6wOYCTYWEBEd1EmdY1NhoCBtpJkUfd3EPimy52WGBjeGBpZfBi4mbtPmiC6GqtC/zCjsPep8u7JNTe@vhMuYChrZQbc0IGdRCyaRGD5asoah5iFAftH3i@hTorX4MkWIPDgG2ZpXDPqgfs2ZUYbc9ocQaqpbidUEhmjCAaqhYXCyTam590p9gBfuqIcFqfl7uyYBP/CsopeuVvRcZKaWDXFvCbnkMYYrQKkWUy1P8MberfFnVkVIuUQAhIktsJsb92JgrsCvPUUk9V1io8o7e6Rc5xSWUglF/XiBCFw9EfgcV4Qx1jE5JoVp6lTylnDQbobtJnJh3xb1h8qZ6UHnWKmCrjoNQQiBZbKVaCGQSiGQZjjB/KDas8494lJYMwcGHs8IOfbMy0PKxldUb9DCiI2JKcaZ@2YF/KWJ9kpsE0t3ao2nhOEErhH5Sd4pirsMd6NtGH@SKetaI0Bh1ZOdovzWUi5Nt9CXLbc5Ky4CMTa2k3l2IDZL9r0D22s@jpEUcUA4cCk3WDAtc68UPQ5NCkVUpqseUA/5yx3C7nEaJgEB2tN7WhKNKCohYRYpAwdj@JozInqbAJBjdCFSZiaXBYA/fdiowK1myJHQEHwSCCJx5CR4USYfKtb/oyLNpD9jVN7cFA@TGhQbBMJtRws2twUFAejTjfHboqEQPHc86oB@Mu6ZwxiiXJruJeKqDK1KaJeQ@jOsJhYIYumEybUXBXXG/goy2KyWqwnolWBaQiUwFhbTCpfNrS41@JNJR3V4qies3VRNwY@5gXFPdej129@eQ7x7H9cvPv70GCfVSDtvMDscFIUlKXAfEiByZSUS1mI3ZuiqlKpspeUpTEoqCQrJSBSWkeYEIOB6qhYf2qTN8YyLiSZ1II6Pao2vwdAveBAKLtrTScZa3C9TJSPgRPqEGDSZAMGG9SbSndRGbduNtxn0ea@kE/oVcOHAJ8acx6c6gJsJZ5YCdmoIjlj9w6QWrc6wmD7Rv5YSVapsm4oMWRlS2QMuhoW5L9W@Fe7HuoggpJXYplgVZNWnUwkKByd7yl0@wilxYg9aHn6wdNWih71xDKeyj1ZWehv/ZP0hFJ8MG6ycZb73J39nQOS/9cKjJCHBoz0n92R@dNZQbZbMNH@hVMQ7T@v/rVT6Kp@4jGK4R/6O/VYGzbgWni3qv70gxySw61rpznIHsQK3IFG9gnOhz0FSpZbrVS1OQW21Gq93mZCeTl0RsIvBApH6BA3418I1gMRNKyLb5UvuT1GpUDAKQU7KjOVuC6NGYjSCnxcDTAzOK7IQUdctNmwr/GpqRMS8KowqJIF/UKTXOoiZg/QBADCDdIvGwO9ghIOnQSBCSF15ZUxh@XWa/g/1lmZrNctgCrW44GBeW4SXNdODlD0t4Aml3b83Iea7ePaeLp3waHD6HeGZ0xtFTDxRqoGG65ggEK6yosby1RoLR5atMXwZduyK2Fhw4V@AWjgZVihlcpR165gXWr30p6B7aRhIKIsX6IKdTW7ayos0jyAQD@PLactzT8WGYVa6AJDkLDUDQfEIH0ZJcaY4qNtHqKJwEeq6PvAMitPI95iz/sdlxnOFDPcBtcjNajt3zN2XfgscrdngW3tqekgzSMIB2tVNWtWwLqrAqx@uMBaoK8djkhmmeNwaKbuBd0VMPayuUjV@i4DsHy3z/whRxia9Iba2NlJfACU4xKH3tEwPZ/YZvxetl9ZbM/lfpoI8Dl5jtU3yMPKkgeWBkWNVRAk6vlvwGDAv2XQNcdt@XRj8aoQcrlEpxSDYIt2oNzHJgOs87VbwMIwo0OcyGnlmTffe/DfPOJ9r4KE98QY/eqThSJYdZEUWFjC3lNxFlBvUKjyPdzPX3eQ44FE@AZBOllB9WrUUzWlUIC30bldUFc48rSsSWeH2VhrybZnC6uBGJDAPFWIhXiZXFvOMFheoArB2MkHZ82sRQ0RubzJ7kZrWSXaIKNGXFkhhNJx1xwY6e6Fm7yNSizwXobYb0BxM8uXQSqeD3xjHWAsUCOSW8t@H@thaZZS4CMkDADrgGuVEAG9oMKBKNxgYLfAdqUs5H6HLDMLaa9irp1ZKmNzLVUqbqUprKWZ312Um4E8BqIHTHJQ87QqzHKvtrwNEWlcgk2KbAljYFtswffMisAmEKSgIJG1qCnLsDDJvViHTTbcOngrcGgG2OoGHEL3C/Mmz0W9SVUuRmLEhWp1QDbH5c4hrlQGh951sL91aSSY@H2LEwnWYSwFsByorSzVEYNLc0Ul4gb7MGYlHfXHqguarBz4hHDGhhhjUekMJcgZhUaqaQR2s6j0tiAWomZ4Fg@SKafvkyDwmD0pE0tdtQ7E1oqtvDr5GtIMRlk9ZHV79YnXr6xpjT7PEMYbo9UgPkF40hxzLKhunm7bINfxUhs8oB/bQ3yv6/Wd0FMTmM59fU/GbEcbo5r1VNvcwd1AmsfCqCqA3BxzUq@XFUvTdQqVg0d6U/o2v@N44042YyueUcHCQyFCH4ht9hk7ljGnsKlJQrGXoMPA6h4ZVlAtfmrtpsNk2pF1HiZDq2szobDqnI7b3kvgRLbh5e0IKgnsC1a9YUPS9xx8dRqPFSnyDPAXs9RuUCokmWfPgvae1lBdZ3ObRPmy2aArgcO2d/FhhH87su5bzmONRtAP3MtdBK7itveSurkr1QTDk0jn3omaaxxWxk1P9rZawg174vvCar3jrAwYMzb5vIPVNVaonTnJ6XHb3I1Upg2cC3MOMVAXLDzq7cc7PFfDtucfjYpuoSO1b/VQoRiwR6DlqraAsRr3ieq2HnFLyx08YKH5lKLvtsXDmJLLoDOaGO0r7SE0SEufPDPXwHRp9Q@hnb0jF8ggh9lIgd7bKaKhfeAd@48yGAzgt@HuZPikHE0oIvsZzb7TwuGp5LrqbLK7FcdtBcudciaH7gOQsNY1hCgI76XBciG3aeaUo65kvImwJkRLfhvujHHAFhqg6ANBIqdQXP2sg0cUe3MNkQ5jtQgGbiPSsE/YzWuky726vuVws2oEZpvQwyqUyaCiTVf6@gXvK0Kn99XtXFy0QC/ljsU7V94MOuBgOoxstEuOxXO6EMPtnVr6vFb6KMDU4ke2qUdvOBeqUBJbfaMDzNHIxXxngaBf0v4lof03i6JD20dfFTRK0/XT9tTS4Nj6PrdK5hbDAFt7iXupKDrdcYJ9dAC2AaAMe9H03dHt3gMge0X@Vd9B0vYgZlbb40@TTD@97unavhfLvgR1sS90mVrbHO5Zxc2U42d56TS1o07871Ynhqxfc4Ue6DDqaAHeXK7LogqxPtyp0iLey1Ddg1MxmKu/FVS2gkiGX9ufcGAPZ8fAJaIFYNt1t3UR29Cn88JXRmHrxeShF1N6Aaj4Cth4UKY8dnDfqL6Htl27vY7gka5AduAmhJvwjtqg8ZJ37FzVbat3nuHrWjbEN8RGJFtPe4juNrJpJ6zHcJqU9sNdaZj/Tx7WEF15No1Q39bI1qG13QSiOpdbt8doFQ8zr9vq3EqsJmO7mxFbfcIs2qD7pWJy5wsDyso4ytsz/UlcayMdT5va1ye02079HuoaMvxHnTwgEbEDB3ZL9dydoWJHizTnOnQ0DAL3So7TtUWqkcLpqko/ctNOqM6h7uQaBaOSnhY8ygmwFdizYKA13t7EHz450qTvXOaS2jHQo5/44yO3C44cDleSOubNgUK/OeumL9y2WupRNPx/apSt9thGGSjGTHvJ1nFNy1kadLyWrU7V1K5E3FshMwvX7i7ERiZO@vxZPnM1d0smubWVypFnG8qW2M5B28u2s4WVILByyyokQu9rHaY5hUJhlUQeMfYT@PHjr5eWYcU5VLgAk8p9HB7GsfiY79Mhb5abOV5Pn2Ojm3IScM2zmfj8mVZ/dsCUUAxRb0psX@r7SgmJQFEi4ckd6/toCfNKKQIxqJuqKbIBgT259MSrv7186QmfMw/X3RHT7oit3TsT9rsT@sAJTk5OrFMHwcGwf5yz9Ky7NEwvz6bWbT8qREWRLBsBL9qw@PqhQdc8yLF5CJCxdLrG97gWjzyCImXfT7@gi5W8Bt@lC5j4zOUq9mdTZzg4mD4pjaUtYVd8YBJRnZyPiimIDXVp9KtG@mEDLcS2T7iVst/65I2dIjP3Tdstfn0cX9KFU6x94hWKrc2dPJhBnUJPO1f93rnZavDWDjSPvvMW7L/tDiw6EA6pO0KNcqHnigGOHqmmrqHYEy9e/vLiL2/nr8/fAOleuEd4gWvSxyv2fq0Jrwnf3nXW13aM9ZaL7y79qI5k1cp2d7c/auQShkVHldK7g/k2xpbhIIDo80r@UDcHhpPJyeFkkhc5pvbH0Q43AkV2KzAWYTi7mKVX0pifJIrE6Jd9MSq6y8hbubWyGL1H12/0HmxSFYpRKWPqulHrDX75C99ja19AqBnmtYpw9TcIsPUnkVU9VIBWm/zrQNI3Rjb5YoOXpsR4rwfSmTgQJ@KzwEamStabrKnn@/5kOp/P5gfj5rbZUS1@FJJfUdyRFLgV36M0WxMJa33/9bsAmEzx3weAmE@mCo4dXalQZZZNnl5D6GGpCzH49rtohEXV5/o2WmUhvEmxtgI8w@M/gUG7V7jmUOuae87Q3KmeSBD1EDAAVFGIGpTBjMcGB3p5VUaqueaFFSt8U8i0pg9HPGesDHc691whZFQlJO5Z40O3KSlAexUbAMRg25BpADjWVGDofXR7Ft3KVFsSO4U5F@7XklofussqjOC6qr5PXxIA2ebInHpp9O1gq4U4wVt8@NkcVHYKBgh8sP6JuU3lRIToOlcAhTkYpcEJirHNBbq8VnMISte7uzgd5EMGxY4gkEJAHf0hKVWtCxVRsa6JqVSuUUlJt0GJYPjFi6d7e2aP/X1/OpngOgPjxZVZmIeqNdwT1FPdrIoKb4zA8eoGRoE@Miexuc9wEzMfwUbfYFndlbJaFFkKnp3aAXCn@tZLuhee1x1I@vrY6w2IMVaDN3DkTzNv/57rtdRyWAbX@MserHwdTPlzVhcQ3MgMpH4tuXN5Lel6JUpdgj2WdC@zFNhPqWq/3ABxLXSWv70t@ui6qIBm9SN9@gduXai2Q1fMtySb5VkLd5Fnd3R@/v6RxoEl77jp3s4e45y6VjGLUTX4vZQ4bEL8nMUmajbcNvTwl/Ke4jbnpsd/SdFfqYN6Ogu15sPJl08I6qX@QpinlE5odw9RObxt67Zak7Avhvu6izQ2HxdrE0f0LaZgQm/eI5eH@rtlXDhTFSRsispNJtVToou96KkJeNVbAtC@e0wZnaoK78RDPZ5RkWNRnHocOkPAs5ME3nO6zdDeLuCLC1jKszK87WWJtqMQK3o022mgR6Egfg1JY2ATkW5r7@mUeLiXXnPhe2m1DinlangBk8egifGSLQqOvk7cIp1Sbzc646hIQFXpdXiFxkLfiEcPAG@MGfRwgwKWv4kv@IoCtbClTffefZtvM8kObEdz8uOd72HYOibV9z0tc8AY5dJG@DFMM1LTfJNEs5fxZfVqF3mPl@4po9DeZ1KJB1LKpvnczT8oGwDIbb@aBkemA6vGMLtOHH8At0OrNfDkapIW2EPbI@yKMLkbrg2z7sBPaXWsadhN/PCt8VMFE2V4SE7dKzBOwod41TR5cOvDTtsoz5diABrV0kN56XT742w7/Q39BEKoLr@TUskgxMMSn2OJ1UzgwrzZUIjdVi/4Fr1suSXWHzNrkarQ3LIU3xKzL1/FEImuRswwnEbxFJ/mIYgHbWgusbHCpnQmOgLgEhCRWXVvBefqsgsQXPMWlt37vvtJ9RT6fCvNCRsFJX@Ojm9drdWnJ3Jx4j@mlswlTOOLSSUgh62ZasSn3irNafBaUq2vZ@unip7zqX97C468uRFHSjSWIQle3LKv9Lfu8imV0iE4ehdgOmuGhTxlCPce/15M4X/Ddoxuoex@Yk5fYcAvEWgYJ/7UhXGprxD24DTE2xHoXiUbFA9Esb49ZQBUV3PKApuhfHNnQyIxc2J7YArwm6p2Dt67Cata9b/hBxvSCDx6vjB5RRc6mhXFbkY9scnlFitEH/hqeCmsQk9cf1AmrYkW@rNj@PUgCiLo@2Pylu@Rdb4/NvUhiph@47QQh09PDvYO9o@PZwq481i8v8shini7An5KZQYR@98gWvtJRuwHTf2pT57Fly9fZl8Ovhx9mUz/Dw "C (gcc) – Try It Online")
In the ungolfed code, if you supply p, q, and n, it will try the size-n problem, then size-(n+1) and so on until something breaks. If limits are exceeded, the program is meant to terminate with a message. You can supply a fourth parameter to cap n.
The ungolfed code should handle finite grids (Platonic solids, or p=2 and/or q=2).
If you want to look at the different question of counts up to translation and rotation only, compile the ungolfed code with -DNOTFREE.
The golfed code can be checked against existing planar values as well as the values in the question. For example:
```
p=4,q=4, n=11: a000105(11)=17073
p=3,q=99999,n=13: a000207(13)=24834
p=6,q=3, n=10: a000228(10)=30490
p=3,q=6, n=14: a000577(14)=26166
p=4,q=99999,n=10: a005036(10)=32721
p=4,q=5, n=10: a119611(10)=21430
```
Most of these run within TIO's timeout of 60s. In other sequences, such as a330659 {3,7}, the golfed code can replicate and extend the current known values in OEIS:
```
p=3,q=7, n=10: a330659(10)= 637
p=3,q=7, n=11: a330659(11)= 1870
p=3,q=7, n=12: a330659(12)= 5797
p=3,q=7, n=13: a330659(13)=17866
p=3,q=7, n=14: a330659(14)=56237
```
The ungolfed code has more checks, uses more memory and runs quicker (because, for example, it uses a hash table rather than a flat array for storing characteristics), so I'll add to the OEIS using that code. For example, extending a330659 to n=19 takes around 1000 seconds:
```
p=3,q=7, n=14: a330659(14)=56237
p=3,q=7, n=15: a330659(15)=177573
p=3,q=7, n=16: a330659(16)=566904
p=3,q=7, n=17: a330659(17)=1818527
p=3,q=7, n=18: a330659(18)=5874180
p=3,q=7, n=19: a330659(19)=19065038
```
] |
[Question]
[
[Sandbox](https://codegolf.meta.stackexchange.com/a/18353/71546)
### What is Hexagonification™?
Hexagonification™ is a transformation that creates a hexagon with 3 copies of a rectangle block, each skewed to the right by 30 degrees and then rotated by 0, 120 and 240 degrees respectively, as shown in the following image. A triangle hole may appear in the middle, but that isn't a great deal.
[](https://i.stack.imgur.com/N13HQ.png)
### Challenge
Write a program or function that receives a block of string as an input and outputs the hexagonified™ input. You may assume that the input consists of only ASCII characters and new lines, and each line of the input has been padded so that all lines are of equal length. Empty spaces should be filled with space characters.
The input and output formats are flexible. You may receive a single string, a list of lines or a 2D array as input, and output a single string or a list of lines. You may have leading/trailing spaces on each line and leading/trailing newlines, provided that the hexagon is properly formed. See Sample IO for how the blocks should be positioned.
### Sample IO
Input:
```
3x3
squ
are
```
Output:
```
3 x 3
e s q u
u r a r e
3 q a a s 3
x s r q x
3 e u 3
```
Input:
```
longer.....
rectangular
block......
```
Output:
```
l o n g e r . . . . .
. r e c t a n g u l a r
r . b l o c k . . . . . .
. a . b r l
. l . l e o
. u . o c n
. g . c t g
. n k k a e
r a c . n r
e t o . g .
g c l . u .
n e b . l .
o r . a .
l . r .
```
Input:
```
vb
el
ro
tc
ik
c2
ax
l8
```
Output:
```
v b
8 e l
x l r o
2 a t c
k c i k
c i c 2
o t a x
l r l 8
b e l a c i t r e v
v 8 x 2 k c o l b
```
Input:
```
1.line
```
Output:
```
1 . l i n e
e 1
n .
i l
l i
. n
1 e
```
Input:
```
1
.
l
i
n
e
```
Output:
```
1
e .
n l
i i
l n
. e
1 e n i l . 1
```
### Scoring
Your score will be the area of the hexagonified™ source code (including the triangle hole). Assuming your code can just fit inside a rectangle of width \$w\$ and height \$h\$, the score will be:
$$3wh+\frac{(w-h)(w-h+1)}{2}$$
### Winning Criteria
The submission with the lowest score in each language wins. No standard loopholes.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), score ~~235~~ 168
```
→WS⊞υιFυF
«P↙ιM²←»F
M⊖⌈EυLκ↙F
Fυ«P↖κ↗»F
M⊖⌈EυLκ↖F
Fυ«P⪫κ ↘»
```
[Try it online!](https://tio.run/##S85ILErOT8z5//9R26T3e7a/37P5Ude8863ndr7fs@x8K5DgOrT6/Z4Nj9pmgoTWHtr0qG3Cod0gcSDvUde0Rz0d7/csBalcc24XUBVEBqgVqm0aSHQ6Hh3T0HSsWn1ul8KjthmHdg9GN3H9100EAA "Charcoal – Try It Online") Takes input as a newline-terminated list. Charcoal's problem here is that a newline is a command, so I can't just throw newlines in arbitrarily. Instead, I'm passing them as arguments to the `For` command, which loops over each character in the string, which here is just the one character, therefore not modifying the behaviour of the program (except to change the implicit loop variables). As such, these dummy `For` instructions are not included in the explanation. Explanation:
```
→
```
Another no-op, just to make the code exactly rectangular.
```
WS⊞υι
```
Input the list.
```
Fυ«P↙ιM²←»
```
Print the lower right diagonal side.
```
M⊖⌈EυLκ↙
```
Move to the bottom.
```
Fυ«P↖κ↗»
```
Print the lower left diagonal side.
```
M⊖⌈EυLκ↖
```
Move to the top left.
```
Fυ«P⪫κ ↘»
```
Print the top side.
[Answer]
# [Python 2](https://docs.python.org/2/), score 918
```
m=input()
d={};h=len(m)
w=len(m[0])
r=range
for i in r(h*w):
j,i=divmod(i,h)
d[(i,i+j*2)]=d[
(h+j,h+2*w-2*i-j
-2)]=d[(w-j+h+~i
,w+i-j+~h)]=m[i
][j]
y,x=zip(
*d.keys())
for i in r(min
(y),max(y)+1):
print''.join(d
.get((i,j),' ')
for j in r(min
(x),max(x)+1))
```
[Try it online!](https://tio.run/##TVDBboMwDL37K1AvSUhAK9OkaRNfgjhQkhWnkLCUFti0/nrnlEsj5cV59rOtN65T511xb7025W63uw8luvEycQG6/P377MreOD4ImLegeqkFhDI07mjgy4cEE3RJ4F06iw9IrMJS43XwmqPqBCS6ogClTQtRl7oC3kmrOlmkc1akmFnItgSfMys7eUNQsyRe3jrihwqhrmwNq1rKHxw5pDo/mfXMhXiePqADvgo1NAs9ch9XGQO6ibHcenRcQ340E6ddrFAsYZvaPqmXTb1Etbg/xEB@AJjFtEm0J327V@x1eWWKnb8vhE0wrIaK9Z7MCHk8xAbTTuTOpW8C/Q69b0/5lou11wORpo91nmBqCfBE0Bax40LQvz8q93mPbhuwJza2jjKk62IPVv8D "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), Score (8 by ~~9~~ 8) = ~~216~~ 192
```
¹¹ẈṀ_$⁶ẋ
ŒdṙLC$UŻ
ÇżUṚżZṚ$
ÇṚUF€ḟ€0
0ẋṂ;r/_Ṃ
Z,$ẈÇṖ⁶ẋ
4ĿŒHj¥"Ç
ỴÇµÑżK€Y
```
A full-program which prints the result.
**[Try it online!](https://tio.run/##ZU9NS8NAEL3vrxgkR6lV6wd4FETQaw/2UtI0BtrQQmgP3moRK/RkwbbrRVHqQT2qmDQgJOaH7PyR@JI2WOsGZjbvY95szbTtszgO3MBV3pVyO2WNzz@U1xfRoKpcebyvFaOpCHuRX1TubeSXUDX8oxUPuPuqPu9Q8yIPj3K7e85aGU2UVjXMS2TD@bzC91c0OKwFk5WwJ9T0LewF7@F15B/BfhLHRGRTkxpkkUkO5bJPEKoDzKAW6SnfhlInR6SySmozqP5rgSkHQY6WTwUOW4Cw/5E2EpppVnuJS4Y3wAC2/lDJQlZCAG0gPzt1ZJspjjgdstlJRM4MRlYLcykbOkdxNbDIfIkMhM3E5unSYmGr5PH6IpS@Cmi8zvJ5g0f9TZaPBZZPW3x5s81jf4fH3q5g@aKzvK/w0DNYTqrc8U0eXZyCtCAU6PDACiFMoKEGgaGQc@cBYpZd2BHxAw "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##xVAxS8NQGNzvZ0hGjY11EBwFEXTN0C4ljY@S9JHgs5V2s11S6GQFQRcHcXPU4GuDgZe8H/LyR55fsf/Bb7jjju9uuJhxPrVWSSXNemHkfc9pZrlZL6FX10Y@X505vt6gynThG/miiy6hQ5rIP2/mH@b7lbCFFmWMnJ@Kwx4RuvsO9W3fnnZ9x3WpVxexet@rMpjNZ5Wpr@pBF5cU71ivLqEfjXxrZj8qV/lBXZIf75S17UkbtzdjBIIBPE0GTLjbg2DhKEgGYx4I9HkaDt0/H3d9MA6RYhQiGiI8QjABPwE8l0cJtXhwwREhAYn/HuAX "Jelly – Try It Online").
### How?
Starts at the Main (unnumbered) Link, which is the bottom line of code.
```
¹¹ẈṀ_$⁶ẋ - Link 1: the output lines without leading spaces, A
¹ - no-op -> A
¹ - no-op -> A
Ẉ - length of each (A)
$ - last two links as a monad - f(Ẉ(A))
Ṁ - maximum
_ - subtract (vectorises)
⁶ - literal space character
ẋ - repeat (vectorises)
ŒdṙLC$UŻ - Link 2: lines
Œd - anti-diagonals (e.g. ["abcd","1234"] -> ["d3","c2","b1","a4"])
$ - last two links as a monad - f(lines)
L - length
C - complement (1 - that)
ṙ - rotate (anti-diagonals) left by (1 - length(lines))
i.e. rotate right by (#lines - 1)
U - reverse each
Ż - prepend a zero (allows us to start the join one further
down - removed in Link 4 with ḟ€0)
ÇżUṚżZṚ$ - Link 3: lines
Ç - call the last Link (2) as a monad = Link_2(lines)
U - reverse each (lines)
ż - zip together
$ - last two links as a monad - f(lines)
Z - transpose (lines)
Ṛ - reverse
ż - zip together
ÇṚUF€ḟ€0 - Link 4: lines
Ç - call the last Link (3) as a monad = Link_3(lines)
Ṛ - reverse
U - reverse each
F€ - flatten each
ḟ€0 - remove zeros from each
0ẋṂ;r/_Ṃ - Link 5: [w,h] e.g. [8,3]
0 - literal zero 0
Ṃ - minimum (of w and h) 3
ẋ - repeat [0,0,0]
/ - reduce ([w,h]) by:
r - inclusive range [8,7,6,5,4,3]
; - concatenate [0,0,0,8,7,6,5,4,3]
Ṃ - minimum (of w and h) 3
_ - subtract [-3,-3,-3,5,4,3,2,1,0]
Z,$ẈÇṖ⁶ẋ - Link 6: lines
$ - last two links as a monad:
Z - transpose
, - pair
Ẉ - length of each - i.e. [w=width(S), h=height(S)]
Ç - call the last Link (5) as a monad = f([w,h])
Ṗ - pop (remove rightmost)
⁶ - literal space character
ẋ - repeat (vectorises) - Note: z ẋ -n = []
4ĿŒHj¥"Ç - Link 7: lines
4Ŀ - call Link 4 as a monad = Link_4(lines)
Ç - call the last Link (6) as a monad = Link_6(lines)
" - zip with - i.e. for i in [1..] f(left[i],right[i]):
¥ - last two links as a dyad:
ŒH - split (Link_4(lines)[i]) into two halves
j - join with (Link_6(lines)[i])
ỴÇµÑżK€Y - Main Link: List of characters, S
Ỵ - split (S) at newline characters
Ç - call the last Link (7) as a monad = Link_7(lines)
µ - start a new monadic chain - i.e. f(Link_7(lines))
Ñ - call the next Link (1) as a monad = Link_1(Link_7(lines))
K€ - join each (line) with space characters
ż - zip these together
Y - join with newline characters
- implicit print
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), width × height = ~~9 × 9~~ 9 × 6, score = ~~243~~ 168
```
ṚZÑṚŻL}¡
J’0ẋ;"K€
ṚÇḟ€⁶ZUÇŻ
Z,ṖẈ+L0ẋ
Ṫ;Ɱ";⁶o/
U¹ƭṛĿ¥Ɱ4Ç
```
[Try it online!](https://tio.run/##y0rNyan8///hzllRhycCyaO7fWoPLVTg8nrUMNPg4a5uayXvR01rFLiAUofbH@6YD@Q8atwWFXq4/ehuriidhzunPdzVoe0DUgpStMr60cZ1StZAJfn6Clyhh3YeW/tw5@wj@w8tBYqbHG7//3D3lsPtkVxHJz/cufhR475D2w5tO9wONDQLyvn/37jCmKu4sJQrsSiViysnPy89tUgPBLiKUpNLEvPSS3MSi7iScvKTs/Ug4lxlSVypOVxF@VwlyVyZ2VzJRlyJFVw5Flxchno5mXlAUwy59LhyuDK58riAHDSvHtpJjl@BulA9CxTA9C0A "Jelly – Try It Online")
A set of links that takes a list of Jelly strings as its input and returns a list of Jelly strings.
# An alternative 8 × 7 with score of 169:
```
ṚZÑṚŻL}¡
J’0ẋ;"K€
ṚÇḟ€⁶ZUÇ
Z,ṖẈ+L0ẋ
Ṫ;Ɱ";⁶o/
ṛĿ"JŻ€3¦
U3СṚÇ5Ŀ
```
[Try it online!](https://tio.run/##y0rNyan8///hzllRhycCyaO7fWoPLeTyetQw0@Dhrm5rJe9HTWu4gBKH2x/umA9kP2rcFhV6uJ0rSufhzmkPd3Vo@4DUAVWssn60cZ2SNVA@Xx/InX1kv5LX0d1AHcaHlnGFGh@ecGgh2BjTI/v/P9y95XB7JNfRyQ93Ln7UuO/QtkPbDrcDlWZBOf//G1cYcxUXlnIlFqVyceXk56WnFumBAFdRanJJYl56aU5iEVdSTn5yth5EnKssiSs1h6son6skmSszmyvZiCuxgivHgovLUC8nMw9oiiGXHlcOVyZXHheQQ18PAwA "Jelly – Try It Online")
] |
[Question]
[
Given a number *n > 77*, write a program or function that finds a set of **distinct** positive integers such that the sum of the set equals *n*, and the sum of the reciprocals of the set equals 1.
Example for 80:
>
> 80 = 2 + 4 + 10 + 15 + 21 + 28 ⟶
> 1/2 + 1/4 + 1/10 + 1/15 + 1/21 + 1/28 = 1
>
>
>
Your program or function must (theoretically) work for any *n < 232*, and is not excused for floating point rounding errors. Note that solutions exist for all *n > 77*.
---
Shortest code in bytes wins.
There is a bonus incentive: I will award a bounty to the smallest solution that works for any *n* and runs *log(n)*. For small *n* it must be *fast* (determined at my discretion). Yes, this is possible.
[Answer]
# Python 3, 7306 1995 Bytes
This solution runs in log(n) complexity (as far as I can tell).
```
def i(s,t):
for n in s[::-1]:t=t.replace(*n)
return [[]]*78+[list(bytearray.fromhex(a))for a in t.split(",")]
def f(n):
g,h=lambda c,n:c+[[[2],[3,7,78,91]][n[len(c)]%2]+[i*2for i in c[-1]]],lambda n:[]if n<78 else h((n-[2,179][n%2])//2)+[n]
v=h(n);c=[i([['g',',03040'],['h',',,0306080'],['i',',020'],['j','b0c1'],['k','21'],['l','60'],['m','30'],['n','141'],['o','k24'],['p',',g'],['q','618'],['r','0c0'],['s','1e'],['t',',0ml'],['u','283c'],['v','e0f1'],['w','2a38'],['x','80'],['y','a0'],['z','01'],['A','50'],['B','24'],['C','i40'],['D','plb1'],['E','gl'],['F','48'],['G','bre1'],['H','28'],['I','6k'],['J','416s'],['K',',040Al'],['L','90'],['M','2a'],['N','54'],['O','k6o'],['P','3c'],['Q','il'],['R','18'],['S','px'],['T','im'],['U','70'],['V','b1'],['W','23'],['X','pj'],['Y','hj'],['Z','0n']],'020lxycHTaRHCyf1517CyfneC91k51cCLdneQU912MCyf0dBiALyf2dClfPEyfneT9s2dELdneEjIgmLydHg5rd14BKLardsE3n8sQ9rd1517Q9rdneplmdRBgUmcRMC5sPEyf102bgA6sPE91z2miAj41IQmc0dRBQUen7spl31z82bT9RFT3wE7neMgmyf0dRBgUmaHMELc1b36EUdBMQLyfs2d,C710M2bgLardRHT3BFQ9rf0dPQ7rdBMQm9Rs2d,0mAl9100d142bE710M2bQmc0fRPtxarfn8sEc1k4sBTfnePExcwtxarf1k8BExcuT3kkT91663C51964,0mAl71k4BMELe12NTcRwQjOT820ltmarf1z8mExeRNCqBFtmyjIHKLa100ds2bQU91bM36garf1k4sBTcRBFgxarfwE91keB2dtUxcn8sME9nbs36gm9rduC5R78,0mAUyf0d14BME91kbB36QLc12AB2dgyjqkHEUeMNT9157eQU9RMFT8s78C8neuixLc1zk4AtUxc1z8Mmt8re0fn8sWhLyc1bH36pl8neu,Kxycsw,iAxc1420l,K8ren8NS9n81bs36hc0vz8WmYzqkmhyv2WBHhyVOHXkJoSjIwSjIuSvz4WASVZIAXZ6skmSj6oFXzOmplvcsW46D61csk46plv8WBFDqoF,tarvk8WBH,tyjkqoHhGqkN,tmvZ8sWmhVZqskmpc0vZ8WAXZqkAplbnImASbn6skwSbn6skuSVOwSVOupGONSbn6soFpyVkJk5aSj6sk78YJkuDkIP5aYOuhvzk4WBAhVzk416oA,tyjkJ265a,,0mxyjk41q53sYzIHmPXkqowXkqouhyVqoHFYz6omFhb0e1zqkmNSyVIP78YJ20klpyVOHwYk620olpc0vz8WBmFXzqomFpG61ckH38PhyjIP78Yz620kmlDkImLDzINUhGIuNDzIA78hb0e1ZIANYkqk366chG6oFNXkJkP5ahVZ6somFSb0e1620kNlhVk41qomADzIFLXkqso78pGqoFNXzkImP5a,tyjk620oHlhG620kNlXzqskm78,tjZqskHmPYqouFD6sku78YzqkNU,tjZqsomF')[v[0]]]
for o in range(len(v)-1):c=g(c,v)
return c[-1]
```
You can test that `f(2**32 - 1)` runs almost instantly
I used [this paper](https://www.math.ucsd.edu/%7Eronspubs/63_02_partitions.pdf) on a method for computing it. With this method there is a massive chunk of data for the pre-determined values for n from 78 to 334 without the even numbers after 168. I wanted to turn this data into something small and I didn't know any good compression algorithms so I made my own.
The way I compressed it was by having a list of string replace rules. I created a method which found the string replace rule which would cut down the most content over all taking into account defining the rule. I then recursively applied this until I could create no more rules (I used characters g-z and A-Z). The string I made to replace with was a comma separated list of the hex values for each of the numbers. In retrospect, converting them to their hex values may not have been the wisest choice, it would probably be shorter to leave them in decimal, since having hex would only save for the 3 digit numbers but would add a 0 for single digit numbers.
The line where I set c you can see the list of replace rules and the text which it runs it on. The rules need to be applied in reverse as well because some rules include characters created from other rules.
There are also numerous places in this code where I could probably cut down on syntax, such as turning the list of lists into a single list and then using a different method to access the rules to replace the text with
[Answer]
## Mathematica, 54 bytes
```
Select[IntegerPartitions@#,Unequal@@#&&Tr[1/#]==1&,1]&
```
About as inefficient as it gets, but it does solve `n = 78` in about 9 seconds.
The result is returned as a list wrapped in a singleton list, e.g.:
```
{{45, 12, 9, 5, 4, 3}}
```
[Answer]
## Haskell, 93 bytes
```
import Data.List
import Data.Ratio
p n=[x|x<-subsequences[2..n],sum x==n,1==sum(map(1%)x)]!!0
```
Horribly slow1 but it runs in constant memory. Trivial solution: check all subsequences of `[2..n]` for sum and sum of reciprocals.
Returning all solutions instead of one is 3 bytes shorter: just remove the `!!0` (beware: the running time will always be off the charts).
---
1 The running time depends on how early the result appears in the list of subsequences. Haskell's laziness stops the search if the first match is found. When compiled, `p 89` (result: `[3,4,6,9,18,21,28]`) runs on my (4 year old) laptop in 35s. Other values, even smaller ones, can take hours.
[Answer]
# Julia, 77 bytes
```
n->collect(filter(i->i==∪(i)&&sum(j->Rational(1,j),i)==1,partitions(n)))[1]
```
This is an inefficient lambda function that accepts an integer and returns an integer array. To call it, assign it to a variable.
We get the partitions of the integer using `partitions`. We then filter the set of partitions to only those with unique elements whose reciprocals sum to 1. To ensure no roundoff error occurs, we use Julia's `Rational` type to construct the reciprocals. `filter` returns an iterator, so we have to `collect` it into an array. This gives us an array of arrays (with only a single element), so we can get the first using `[1]`.
Now, when I say inefficient, I mean it. Running this for *n* = 80 takes 39.113 seconds on my computer and allocates 13.759 GB of memory.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 14 bytes
```
ḟ§&o=1ṁ\o=¹ΣṖḣ
```
[Try it online!](https://tio.run/##ASQA2/9odXNr///huJ/CpyZvPTHhuYFcbz3Cuc6j4bmW4bij////NTA "Husk – Try It Online")
Husk's usage of fractions is really beneficial for this challenge.
Just like all the answers except Cameron's, is very slow for larger test cases.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes
```
œcL’$P€S=P
ŒṗQƑƇÇƇḢ
```
[Try it online!](https://tio.run/##AS0A0v9qZWxsef//xZNjTOKAmSRQ4oKsUz1QCsWS4bmXUcaRxofDh8aH4bii////NjA "Jelly – Try It Online")
Very inefficient. This times out for all valid inputs, but takes less than a minute for all \$n < 62\$
If we were able to ignore failures due to floating point issues, then this could be reduced to 12 bytes:
```
ŒṗQƑƇİS=1ƲƇḢ
```
[Try it online!](https://tio.run/##ASIA3f9qZWxsef//xZLhuZdRxpHGh8SwUz0xxrLGh@G4ov///zYw "Jelly – Try It Online")
Instead, to avoid division, we use the fact that a set of numbers \$a\_1, a\_2, ..., a\_n\$ such that \$\sum^n\_{i=1}a\_i = n\$ for an input \$n\$ has their reciprocals sum equal to \$1\$ iff:
$$
(a\_2a\_3\cdots a\_n)+(a\_1a\_3\cdots a\_n)+\cdots+(a\_1a\_2\cdots a\_{n-1}) = \prod^n\_{i=1}a\_i \tag{1}
$$
i.e. the sum of the products of each sublist of length \$n-1\$ equals the product of the set.
## How they work
```
œcL’$P€S=P - Helper link. Takes a list l on the left
$ - Group the previous two links together:
L - Take the length of l
’ - Decrement
œc - Combinations of length n
This returns all versions of l with a single element removed
P€ - Take the product of each
S - Take the sum
P - Product of l
= - Are the two equal?
This checks whether or not (1) is true for a given partition
ŒṗQƑƇÇƇḢ - Main link. Takes n on the left
Œṗ - Yield all partitions of n
QƑƇ - Remove those which contain duplicated elements
ÇƇ - Keep those for which the helper link is true
Ḣ - Return the first such list
```
The second one uses the basic
$$\sum^n\_{i=1}\frac1a\_i = 1$$
formula, which utterly fails for pretty much every input due to floating point issues. I think that, if it were up to date with Jelly, this code would work in [M](https://github.com/DennisMitchell/m), due to it's symbolic math functions. Unfortunately, however, M hasn't been updated in ~5 years, so it doesn't appear to have to have the integer partitions builtin.
```
ŒṗQƑƇİS=1ƲƇḢ - Main link. Takes n on the left
Œṗ - All partitions of n
QƑƇ - Remove those which contain duplicated elements
ƲƇ - Keep those for which the following is true:
İ - Yield 1/a for each element
S - Take the sum
=1 - Is equal to 1?
Ḣ - Return the first list found
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 12 bytes
```
ṄλĖ∑1=nÞu∧;c
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuYTOu8SW4oiRMT1uw5514oinO2MiLCIiLCI4MCJd)
No need to worry about floating point error, because everything is fractions under the hood.
## Explained
```
ṄλĖ∑1=nÞu∧;c
Ṅλ ;c # From all integer partitions of the input, get the first where
Ė∑ # the sum of reciprocals
1= # equals 1
∧ # and
nÞu # the partition has unique integers
```
] |
[Question]
[
It's back to school season! So for a part-time job, you're helping out at the school's library. The problem is, the head librarian has never even heard the words "Dewey Decimal," let alone implemented that system. Instead, the sorting system in use has grown "organically" as the library has expanded...
In an effort to keep your sanity, you've elected to write a program to help you sort books as they're returned, because woe unto you if you sort the books wrong. (The head librarian is VERY strict.)
## Input / Output
* The input will be a list of (hypothetical) book titles, one per line, from STDIN / language equivalent.
* You can assume no more than 100 books input at a time (you can only carry so many around the library at once).
* Books can have multiple words in their titles, and these words may be separated by spaces or other punctuation (e.g., a colon`:`, a dash`-`, etc.).
* For ease of calculation, assume all titles are UTF-8.
Output is the same titles, sorted according to the below rules, again one per line, to STDOUT / language equivalent.
## The Sorting Rules
Books are sorted numerically based on their average character value (i.e., cumulative character value divided the number of characters in the book title), counted by the following rules:
* All characters count for determining the number of characters in a title.
* Lowercase letters are counted by their position in the alphabet. (a=1,b=2,...z=26)
* If the title contains capital letters, those count for 1.5 their lowercase value (A=1.5,B=3,...Z=39). *("Capital letters are important!" says the librarian.)*
* Each punctuation mark / symbol in this list `!@#$%^&*()-=_+[]\{}|;':",./<>?~` counts -1 from the cumulative value before averaging. *("Grandiose titles are not!")*
* If the title contains a number, written in [Arabic numerals](https://en.wikipedia.org/wiki/Arabic_numerals), that number is subtracted from the average value before sorting. Multiple consecutive digits are treated as one number (e.g., `42` would subtract 42, not subtract 4 and then subtract 2). Individual digits don't count for the cumulative value (i.e., each digit contributes 0), but DO count for number of characters. Note that this may result in a negative value and should be treated appropriately. *(Rumor has it, the librarian has had a crush on a math instructor for several years, now.)*
* If the title contains two separate words that start with an `R`, the book gets a score of "infinity" and is dumped into a pile in the corner (i.e., randomly arranged at the end of the list). *(The librarian was once dumped by a person with those initials, or so you've heard.)*
* Spaces don't count for the cumulative character value (i.e., they contribute 0), but DO contribute to the number of characters in a title.
* Characters that don't fit the above rules (e.g, a `ÿ`) don't count for the cumulative character value (i.e., they contribute 0), but DO contribute to the number of characters in a title.
* For example, a hypothetical book `ÿÿÿÿÿ` would have a "score" of `(0+0+0+0+0) / 5 = 0`, but a hypothetical book `ÿÿyÿÿ` would have a "score" of `(0+0+25+0+0) / 5 = 5`.
* Two books that happen to "score" the same can be Output in your choice of order. *(They're on the same shelf, anyway)*
### Example Input 1
```
War and Peace
Reading Rainbow: The Best Unicorn Ever
Maus
Home for a Bunny
```
### Example Output 1 (with "scores" in parentheses to show reasoning - you don't need to print them)
```
War and Peace (8.5)
Home for a Bunny (10.125)
Maus (15.125)
Reading Rainbow: The Best Unicorn Ever (infinity)
```
### Example Input 2
```
Matthew
Mark
Luke
John
Revelations
```
### Example Output 2 (with "scores" in parentheses to show reasoning - you don't need to print them)
```
Mark (12.375)
John (13)
Revelations (13.545454...)
Luke (13.75)
Matthew (~13.786)
```
### Example Input 3
```
42
9 Kings
1:8
7th
```
### Example Output 3 (with "scores" in parentheses to show reasoning - you don't need to print them)
```
42 (-42)
1:8 (-9.3333...)
9 Kings (~0.36)
7th (2.3333...)
```
## Other restrictions
* This is Code-Golf, because you need to keep the program secret from the ever-watching eyes of the librarian, and the smaller the program, the easier it is to hide.
* Standard loophole restrictions apply
* Don't let the librarian catch you slacking off by spending all your time on PPCG.
[Answer]
# APL (132)
```
{⎕ML←3⋄⍵[⍋{2='R'+.=↑¨⍵⊂⍨⍵≠' ':!99⋄↑(+/⍎¨'0',⍵⊂⍨⍵∊⎕D)-⍨((+/∊1.5 1×(⍳×∊⍨)∘⍵¨G)-+/⍵∊(⎕UCS 32+⍳94)~'`',⎕D,∊G←(⊂⎕A),⊂⎕UCS 96+⍳26)÷⍴⍵}¨⍵]}
```
Since everyone else is doing the same thing, this too is a function that takes an array of titles and returns it sorted, e.g.:
```
titles
┌─────────────┬──────────────────────────────────────┬────┬────────────────┬───────┬────┬────┬────┬───────────┬──┬───────┬───┬───┐
│War and Peace│Reading Rainbow: The Best Unicorn Ever│Maus│Home for a Bunny│Matthew│Mark│Luke│John│Revelations│42│9 Kings│1:8│7th│
└─────────────┴──────────────────────────────────────┴────┴────────────────┴───────┴────┴────┴────┴───────────┴──┴───────┴───┴───┘
{⎕ML←3⋄⍵[⍋{2='R'+.=↑¨⍵⊂⍨⍵≠' ':!99⋄↑(+/⍎¨'0',⍵⊂⍨⍵∊⎕D)-⍨((+/∊1.5 1×(⍳×∊⍨)∘⍵¨G)-+/⍵∊(⎕UCS 32+⍳94)~'`',⎕D,∊G←(⊂⎕A),⊂⎕UCS 96+⍳26)÷⍴⍵}¨⍵]}titles
┌──┬───┬───────┬───┬─────────────┬────────────────┬────┬────┬───────────┬────┬───────┬────┬──────────────────────────────────────┐
│42│1:8│9 Kings│7th│War and Peace│Home for a Bunny│Mark│John│Revelations│Luke│Matthew│Maus│Reading Rainbow: The Best Unicorn Ever│
└──┴───┴───────┴───┴─────────────┴────────────────┴────┴────┴───────────┴────┴───────┴────┴──────────────────────────────────────┘
```
Explanation:
* `⎕ML←3`: set `⎕ML` to `3` (for `⊂`)
* `⍵[⍋{`...`}¨⍵]`: sort the input by the values returned from the inner function
+ `↑¨⍵⊂⍨⍵≠' '`: get the first character of each word
+ `2='R'+.=`: see if two of these are `'R'`.
+ `:!99`: if so, return 99! (≈ 9.3×10155). This is not quite infinity, but it'll do: a title can never have a score more than 38 times its length (ZZZZ...), so as long as no single title is bigger than about 2×10130 yottabytes, it is guaranteed that these will be at the end.
+ `⋄`: otherwise:
+ `(`...`)÷⍴⍵`: divide the score by the length of `⍵` after calculating it:
- `G←(⊂⎕A),(⎕UCS 96+⍳26)`: store in `G` the uppercase and lowercase letters
- `(⎕UCS 32+⍳94)~'`',⎕D,∊G`: the printable ASCII characters, except letters, digits, spaces and `'`'`, which are the characters for which a point is subtracted. (This is shorter than writing them all out, because `G` is used later on.)
- `+/⍵∊`: count the amount of these characters in `⍵`
- `-`: subtract this from:
- `+/∊1.5 1×(⍳×∊⍨)∘⍵¨G`: the sum of 1.5 × the scores for the capitals, and 1 × the scores for the lowercase letters.
+ `-⍨`: afterwards, subtract the total of the numbers in `⍵`:
- `⍵⊂⍨⍵∊⎕D`: find the groups of digits in `⍵`
- `'0',`: add `'0'`, to prevent the list being empty
- `⍎¨`: evaluate each string
- `+/`: find the sum
[Answer]
# Lua 5.3, ~~366~~ 364 Bytes
```
r={}for i,s in ipairs(arg)do n=0 s:gsub("%l",function(a)n=n+(a:byte()-96)end):gsub("%u",function(a)n=n+(a:byte()-64)*1.5 end):gsub("%p",function(a)n=n-1 end):gsub("^R?.- R.- ?R?",function()n=math.huge end)m=n/utf8.len(s)s:gsub("%d+",function(a)m=m-a end)table.insert(r,{s=s,n=m})end table.sort(r,function(a,b)return a.n<b.n end)for i,v in ipairs(r)do print(v.s)end
```
This code only works in Lua 5.3 because it needs to deal with Unicode characters. If you don't care about Unicode, then replace "utf8" with "string" and it will work fine with Lua 5.2 or 5.1.
It takes its inputs from command-line arguments, so either run it from the command line or put this code above my answer:
```
arg = {"Title 1", "Title 2", "Title 3"}
```
[Answer]
# Mathematica, ~~253~~ 216 bytes (214 chars)
```
r=RegularExpression;c=ToCharacterCode;f=SortBy[Tr@Flatten@Reap[StringCases[#,
{r@"(\\bR.*)+"->∞,r@"\\d+":>0Sow@-FromDigits@"$0",r@"[a-z]":>c@"$0"-96,
r@"[A-Z]":>1.5c@"$0"-96,r@"[!-/:-@[-_{-~]"->-1}]/StringLength@#]&]
```
Call the function like `f[{"42", "9 Kings", "1:8", "7th"}]`; it will return a sorted list of the inputs.
Just barely made it! *Mathematica*'s pattern matching is not as concise when strings are involved, and I just get killed by those long names. The extra two bytes are for the `Infinity` unicode character.
(Let me know if I've fallen afoul of any Standard Loopholes.)
## Update
Looking a little closer at edc65's answer, it looks like the OP will accept a function that sorts a list of strings. With that in mind we can use the curried form of `SortBy` (which *Mathematica* calls the "operator form"); with one argument (the function applied to the list elements to determine their order) it behaves like a function that takes one argument, returning the sorted form of the input; that is, `SortBy[list, f]` is equivalent to `(SortBy[f])[list]`.
# Ungolfed
```
Function[{titles},
SortBy[titles, Function[{str}, (* sort by function value *)
Total[Flatten[Reap[ (* total up all the parts *)
StringCases[str, {
RegularExpression["(\\bR.*){2}"] -> Infinity
(* matches R at the start of a word twice, adds infinity to the total *),
RegularExpression["\\d+"] :> 0 * Sow[-FromDigits["$0"]]
(* matches a number, Sows it for Reap to collect, then multiplies by zero
to not affect the average *),
RegularExpression["[a-z]"] :> ToCharacterCode["$0"] - 96
(* matches a lowercase letter and returns its value *),
RegularExpression["[A-Z]"] :> 1.5 ToCharacterCode["$0"] - 96
(* matches an uppercase letter and returns 1.5 its value *),
RegularExpression["[!-/:-@[-_{-~]"] -> -1
(* matches a 'grandiose' symbol and returns -1 *)
}] / StringLength[#] (* averages character values *)
]]]
]]
]
```
[Answer]
# JavaScript (ES6), 210 ~~218 251~~
As a function with an array argument, returned sorted.
```
f=L=>(S=s=>([...s].map(c=>t-=(a=s.charCodeAt(l++))>32&a<48|a>57&a<65|a>90&a<96|a>122&a<127?1:a>64&a<123?96-(a<96?a*1.5:a):0,l=t=0),s.split(/\D/).map(n=>t-=n,t/=l),t/!s.split(/\bR/)[2]),L.sort((a,b)=>S(a)-S(b)))
//TEST
test1=['War and Peace','Reading Rainbow: The Best Unicorn Ever','Maus','Home for a Bunny']
test2=['Matthew','Mark','Luke','John','Revelations']
test3=['42','9 Kings','1:8','7th']
;O.innerHTML=f(test1)+'\n\n'+f(test2)+'\n\n'+f(test3);
// The comparing function used to sort, more readable
Sort=s=>(
t = 0, // running total
l = 0, // to calc the string length avoiding the '.length' property
[...s].map(c=>{
a=s.charCodeAt(l++);
t-=a>32&a<48|a>57&a<65|a>90&a<96|a>122&a<127
? 1 // symbols (ASCII char except space, alphanumeric and backtick)
: a>64&a<123
? 96-(a<96?a*1.5:a) // alphabetic both upcase and lowcase, and backtick
// lowcase: 96-a, upcase (64-a)*1.5=>96-a*1.5, backtick is 96 and 96-96 == 0
: 0 // else space, non ASCII, and numeric : 0
}),
t = t/l, // average
s.split(/\D/).map(n=>t-=n), // sub number values
f = s.split(/\bR/)[2], // split at words starting with R, if less then 2 f is undefined
t/!f // dividing by not f I can get the infinity I need
)
```
```
<pre id=O></pre>
```
[Answer]
# C#, 352 349 Bytes
Due to the magic of linq:
```
class A{static void Main(string[]a){foreach(var x in a.OrderBy(b=>{var s="0";int j=0;return Regex.Split(b,@"[^\w]+").Count(l=>l[0]=='R')==2?(1/0d):b.Aggregate(0d,(d,e)=>{if(e>47&e<58){s+=e;return d;}d+=(e>64&e<91)?(e-64)*1.5:(e>96&e<123)?e-96:e>32&e<127&e!=96?-1:0;j+=int.Parse(s);s="0";return d;})/b.Length-j-int.Parse(s);}))Console.WriteLine(x);}}
```
Could have saved another 6 bytes if backtick would be included in the punctuation list!
```
class A
{
static void Main(string[] a)
{
foreach (var x in a.OrderBy(b =>
{
var s = "0";
int j = 0;
return Regex.Split(b, @"[^\w]+").Count(l => l[0] == 'R') == 2
? (1 / 0d)
: b.Aggregate(0d, (d, e) =>
{
if (e > 47 & e < 58) { s += e; return d; }
d += (e > 64 & e < 91) ? (e - 64) * 1.5 : (e > 96 & e < 123) ? e - 96 : e > 32 & e < 127 & e != 96 ? -1 : 0;
j += int.Parse(s);
s = "0";
return d;
}) / b.Length - j - int.Parse(s);
}))
Console.WriteLine(x);
}
}
```
[Answer]
# Go, 755 Bytes
```
package main
import("os"
"fmt"
"math"
"bufio"
"regexp"
"sort"
"strconv")
type F float64
type T []F
func(t T)Swap(i,j int){t[i],t[j],S[i],S[j]=t[j],t[i],S[j],S[i]}
func(t T)Len()int{return len(t)}
func(t T)Less(i,j int)bool{return t[i]<t[j]}
var S []string
func main(){var t T
for{b:=bufio.NewReader(os.Stdin)
w,_,_:=b.ReadLine()
if len(w)==0{break}
u:=string(w)
var v F
for _,c:=range u{if 96<c&&c<123{v+=F(c)-F(96)}else
if 64<c&&c<91{v+=(F(c)-64)*1.5}else
if (48>c&&c>32)||(c>57&&c<127){v-=1}}
a:=v/F(len(w))
r,_:=regexp.Compile("[0-9]+")
n:=r.FindAllString(string(w),-1)
for _,x:=range n{y,_:=strconv.Atoi(x);a-=F(y)}
if m,_:=regexp.Match("((^| )R.*){2}",w);m{a=F(math.Inf(1))}
S=append(S,u)
t=append(t,a)}
sort.Sort(t)
for _,o:=range S{fmt.Println(o)}}
```
The formatted version:
```
package main
import (
"bufio"
"fmt"
"math"
"os"
"regexp"
"sort"
"strconv"
)
type F float64
type T []F
func (t T) Swap(i, j int) { t[i], t[j], S[i], S[j] = t[j], t[i], S[j], S[i] }
func (t T) Len() int { return len(t) }
func (t T) Less(i, j int) bool { return t[i] < t[j] }
var S []string
func main() {
var t T
for {
b := bufio.NewReader(os.Stdin)
w, _, _ := b.ReadLine()
if len(w) == 0 {
break
}
u := string(w)
var v F
for _, c := range u {
if 96 < c && c < 123 {
v += F(c) - F(96)
} else if 64 < c && c < 91 {
v += (F(c) - 64) * 1.5
} else if (48 > c && c > 32) || (c > 57 && c < 127) {
v -= 1
}
}
a := v / F(len(w))
r, _ := regexp.Compile("[0-9]+")
n := r.FindAllString(string(w), -1)
for _, x := range n {
y, _ := strconv.Atoi(x)
a -= F(y)
}
if m, _ := regexp.Match("((^| )R.*){2}", w); m {
a = F(math.Inf(1))
}
S = append(S, u)
t = append(t, a)
}
sort.Sort(t)
for _, o := range S {
fmt.Println(o)
}
}
```
Implementing a custom sort interface made it longer than expected. The program reads from STDIN until end of input o a blank line is entered.
[Answer]
# PHP, 362 ~~367~~ Bytes
```
<?for(;$w=fgets(STDIN);$S[]=$w){for($l=$i=mb_strlen($w);$i--;){$c=array_sum(unpack("C*",mb_substr($w,$i,1)));96<$c&&$c<123 and $v+=$c-96 or 64<$c&&$c<91 and $v+=1.5*$c-96 or 48<$c&&$c>32||$c>57&&$c<127 and $v-=1;}$v/=$l;preg_match_all("/\d+/",$w,$m);$v-=array_sum($m[0]);preg_match("/((^| )R.*){2}/",$w)&&$v=INF;$t[]=$v;}array_multisort($t,$S);echo join("
",$S);
```
### Formatted version:
```
<?php
for (; $w = fgets(STDIN); $S[] = $w) {
for ($l = $i = mb_strlen($w); $i--;) {
$c = array_sum(unpack("C*", mb_substr($w, $i, 1)));
96 < $c && $c < 123 and $v += $c - 96
or 64 < $c && $c < 91 and $v += 1.5 * $c - 96
or 48 < $c && $c > 32 || $c > 57 && $c < 127 and $v -= 1;
}
$v /= $l;
preg_match_all("/\d+/", $w, $m);
$v -= array_sum($m[0]);
preg_match("/((^| )R.*){2}/", $w) && $v = INF;
$t[] = $v;
}
array_multisort($t, $S);
echo join("
", $S);
```
### Interesting lines:
```
$c = array_sum(unpack("C*", mb_substr($w, $i, 1)));
```
Converts a single UTF-8 character to its byte values and sums them, so that we get the real value for ASCII characters and a value higher than 127 for multibyte characters.
```
96 < $c && $c < 123 and $v += $c - 96
or 64 < $c && $c < 91 and $v += 1.5 * $c - 96
or 48 < $c && $c > 32 || $c > 57 && $c < 127 and $v -= 1;
```
Makes use of low operator precedence of `and` and `or` to assign the character value in a single statement without `if`.
[Answer]
# [Perl 5](https://www.perl.org/), 190 bytes
```
sub p{$_=pop;chomp;$c=-y/A-Za-z0-9 \\`//c;map$c+=(32&ord$_?1:1.5)*(31&ord),/[a-z]/gi;$c/=length;map$c-=$_,/\d+/g;$c}say(sort{$y=$b=~/\bR.*\bR/;($x=$a=~/\bR.*\bR/)||$y?$x-$y:(p($a)<=>p$b)}<>)
```
[Try it online!](https://tio.run/##TYxPS8MwHIbv/RQ5/JBkW5rW0YPtsuFA8DKQoghaqWka28KahP7R1W1@dGvFi5f38Lw8j1XNPhjHts@QPULKrbGRLE1tI5CcDuyaPgn66dErlCSvjMmoFhbknOPl5YVpckg3fui7AZnhpf8LyII9T8ILK6qpwPhe6aIr/yzKIV2wJJ@zYvrOrRhwa5ruCAOHjH@xJIvd2TQswnDgIP4jcjrBsIEDhSHEFoMgK762kJHzak3G8VE0SOgc3SkhlRMrkVe6QLGodGY@QnRfKrRVbYcedCVNo9HNu2qcnehb59bUCr2ZSUfbXuvh29iuMrod6S5wPd/7AQ "Perl 5 – Try It Online")
] |
[Question]
[
Write a [*GOLF*](https://github.com/orlp/golf-cpu) assembly program that reads an integer from stdin (followed by a trailing newline), and outputs its prime factors seperated by newlines, followed by a trailing newline on stdout.
The prime factors need not be in a particular order. `1` is not a prime factor.
**Your *GOLF* binary (after assembling) must fit in 8192 bytes.**
---
Your program will be scored by running it 10 times, each with one of the following inputs:
```
8831269065180497
2843901546547359024
6111061272747645669
11554045868611683619
6764921230558061729
16870180535862877896
3778974635503891117
204667546124958269
16927447722109721827
9929766466606501253
```
These numbers are roughly sorted in terms of difficulty. The first one should easily be solvable by trial division.
Optimization towards this set of numbers is against the spirit of the question, I may change the set of numbers at any point. Your program must work for any positive 64-bit input number, not just these.
### Your score is the sum of CPU cycles used to factor the above numbers.
---
Because *GOLF* is very new I'll include some pointers here. You should read [the *GOLF* specification with all instructions and cycle costs](https://github.com/orlp/golf-cpu/blob/master/specification.md). In the Github repository example programs can be found. In particular look at the [factorial example program](https://github.com/orlp/golf-cpu/blob/master/examples/factorial.golf), which demonstrates input/output.
Compile your program to a binary by running `python3 assemble.py your_source.golf`. Then run your program using `python3 golf.py your_source.bin`, this should print the cycle count as well. See the values of the register contents at program exit with the `-d` flag - use `--help` to see all flags.
[Answer]
# Total 36,757,269,913 cycles
830B assembled
```
Number Time (s) Cycles
8831269065180497 0.1 1148
2843901546547359024 55.0 9535194
6111061272747645669 351.4 60559378
11554045868611683619 0.8 135135
6764921230558061729 1.0 155407
16870180535862877896 43067.5 7126449414
3778974635503891117 148.7 22823483
204667546124958269 87.4 13635943
16927447722109721827 16119.0 2739172134
9929766466606501253 156158.3 26784802677
```
Factorization by trial division, with a few optimizations.
Probably not the fastest, but as no one else has posted yet, I'll kick it off.
```
main:
call read
call factor
halt 0
# Prints factors. Pass number to be factored in register `a'.
factor:
mov n, a # Write routine expects factor in `a', so we'll just keep it there.
# Handle 2 specially
_factor_twos: # do {
geu b, n, 1
jz _factor_ret, b # if (number <= 1) return
and b, n, 1
jnz _factor_rest, b # if (number & 1 != 0) break
mov a, 2
call write # printf("%llu\n", 2)
shr n, n, 1 # number >>= 1
jmp _factor_twos # } while (0)
_factor_rest:
mov a, 3 # factor = 3
_factor_rest_loop: # do {
cmp b, n, 1
jnz _factor_ret, b # if (number == 1) return
divu b, c, n, a # (quotient, remainder) = number / factor
jnz _factor_not_divisible, c # if (remainder == 0) {
call write # printf("%llu\n", factor)
mov n, b # number = quotient
jmp _factor_rest_loop
_factor_not_divisible: # } else {
leu c, b, a
jnz _factor_print_last, c # if quotient < a, print n and return.
add a, a, 2 # else a += 2 }
jmp _factor_rest_loop # } while (0)
_factor_print_last:
mov a, n
call write # printf("%llu", n)
_factor_ret:
ret
# Read stdin. Must be one decimal string, ending with a newline.
# Behavior on invalid input is unspecified.
# Return value stored in a.
read:
mov a, 0
_read_loop_start: # do {
lw c, 0xffffffffffffffff # c = getchar()
sub b, c, ord('\n')
jz _read_ret, b # if (c == '\n'), return
sub c, c, ord('0') # c -= '0'
mulu a, y, a, 10
add a, a, c # a = 10*a + c
jmp _read_loop_start # } while (0)
_read_ret:
ret a
# Write number in register a to stdout, followed by a newline.
# Fortunately, a 64-bit number has at most 20 digits, and we have 25 registers.
# So we can keep them in registers instead of pushing them onto the stack or heap,
# avoiding the fairly expensive read back.
write:
divu a, b, a, 10
jz _write_b, a
divu a, c, a, 10
jz _write_c, a
divu a, d, a, 10
jz _write_d, a
divu a, e, a, 10
jz _write_e, a
divu a, f, a, 10
jz _write_f, a
divu a, g, a, 10
jz _write_g, a
divu a, h, a, 10
jz _write_h, a
divu a, i, a, 10
jz _write_i, a
divu a, j, a, 10
jz _write_j, a
divu a, k, a, 10
jz _write_k, a
divu a, l, a, 10
jz _write_l, a
divu a, m, a, 10
jz _write_m, a
divu a, n, a, 10
jz _write_n, a
divu a, o, a, 10
jz _write_o, a
divu a, p, a, 10
jz _write_p, a
divu a, q, a, 10
jz _write_q, a
divu a, r, a, 10
jz _write_r, a
divu a, s, a, 10
jz _write_s, a
divu a, t, a, 10
jz _write_t, a
add a, a, ord('0')
sw 0xffffffffffffffff, a
_write_t:
add t, t, ord('0')
sw 0xffffffffffffffff, t
_write_s:
add s, s, ord('0')
sw 0xffffffffffffffff, s
_write_r:
add r, r, ord('0')
sw 0xffffffffffffffff, r
_write_q:
add q, q, ord('0')
sw 0xffffffffffffffff, q
_write_p:
add p, p, ord('0')
sw 0xffffffffffffffff, p
_write_o:
add o, o, ord('0')
sw 0xffffffffffffffff, o
_write_n:
add n, n, ord('0')
sw 0xffffffffffffffff, n
_write_m:
add m, m, ord('0')
sw 0xffffffffffffffff, m
_write_l:
add l, l, ord('0')
sw 0xffffffffffffffff, l
_write_k:
add k, k, ord('0')
sw 0xffffffffffffffff, k
_write_j:
add j, j, ord('0')
sw 0xffffffffffffffff, j
_write_i:
add i, i, ord('0')
sw 0xffffffffffffffff, i
_write_h:
add h, h, ord('0')
sw 0xffffffffffffffff, h
_write_g:
add g, g, ord('0')
sw 0xffffffffffffffff, g
_write_f:
add f, f, ord('0')
sw 0xffffffffffffffff, f
_write_e:
add e, e, ord('0')
sw 0xffffffffffffffff, e
_write_d:
add d, d, ord('0')
sw 0xffffffffffffffff, d
_write_c:
add c, c, ord('0')
sw 0xffffffffffffffff, c
_write_b:
add b, b, ord('0')
sw 0xffffffffffffffff, b
sw 0xffffffffffffffff, ord('\n')
ret
# End of write.
```
Full output from my timing loop, in case anyone wants to check the results and/or my copy-paste and math.
```
13
23
31
37
41
47
47
59
61
79
Execution terminated after 1148 cycles with exit code 0.
/usr/local/bin/golf.py factor.bin <<< $num 0.09s user 0.02s system 94% cpu 0.115 total
2
2
2
2
3
3
107
1121707
164546579
Execution terminated after 9535194 cycles with exit code 0.
/usr/local/bin/golf.py factor.bin <<< $num 55.03s user 0.07s system 99% cpu 55.136 total
3
3
3
7
7
7
13
50759273983933
Execution terminated after 60559378 cycles with exit code 0.
/usr/local/bin/golf.py factor.bin <<< $num 351.38s user 0.32s system 99% cpu 5:51.89 total
7
7
7
13
2531
4091
250250521
Execution terminated after 135135 cycles with exit code 0.
/usr/local/bin/golf.py factor.bin <<< $num 0.84s user 0.01s system 99% cpu 0.857 total
31
89
97
3881
18211
357653
Execution terminated after 155407 cycles with exit code 0.
/usr/local/bin/golf.py factor.bin <<< $num 0.98s user 0.01s system 99% cpu 0.997 total
2
2
2
3
702924188994286579
Execution terminated after 7126449414 cycles with exit code 0.
/usr/local/bin/golf.py factor.bin <<< $num 43067.49s user 86.38s system 99% cpu 12:04:12.58 total
7
103
727
7209485975851
Execution terminated after 22823483 cycles with exit code 0.
/usr/local/bin/golf.py factor.bin <<< $num 134.60s user 0.13s system 99% cpu 2:14.83 total
66449
1604167
1920043
Execution terminated after 13635943 cycles with exit code 0.
/usr/local/bin/golf.py factor.bin <<< $num 81.02s user 0.06s system 99% cpu 1:21.12 total
322255481
52528036667
Execution terminated after 2739172134 cycles with exit code 0.
/usr/local/bin/golf.py factor.bin <<< $num 16119.02s user 12.31s system 99% cpu 4:29:03.61 total
9929766466606501253
Execution terminated after 26784802677 cycles with exit code 0.
/usr/local/bin/golf.py factor.bin <<< $num 156158.25s user 186.81s system 49% cpu 88:35:03.65 total
```
[Answer]
## score = 378,867,816 cycles
[randomized - your results may vary]
Uses the Miller-Rabin primality test (a deterministic version that can handle up to 2^64), a bit of trial factoring, and [ECM](http://en.wikipedia.org/wiki/Lenstra_elliptic_curve_factorization) factoring. All the algebraic operations are in there, including modular addition, subtraction, multiplication, exponentiation, and inversion (mod n<2^64).
Modular multiplication is suboptimal - it does a binary search for the quotient. Computing the remainder of a 128 by 64 divide is tough without a matching builtin instruction. Speed that up and the whole thing will go faster.
2290 bytes compiled
```
step = i
test = j
tmp = k
# prints factors of number on stdin, one per line in arbitrary order, to stdout
main:
call read_int
mov a, x
two:
# remove factors of 2
and tmp, a, 1
jnz odd, tmp
mov x, 2
call write_int
sw -1, ord('\n')
shr a, a, 1
jmp two
odd:
cmp tmp, a, 1
jnz done2, tmp
call factorodd
done2:
halt 0
# a = input value >= 3 and odd. Prints factors of a and returns.
factorodd:
call isprime
jnz prime2, b
# n is composite. Try to find a (not necessarily prime) factor.
call trial
jnz split, b
call primepower
jnz split, b
call ecm
split:
# recurse on two parts
mov a, b
call factorodd
mov a, c
jmp factorodd
prime2:
mov x, a
call write_int
sw -1, ord('\n')
ret
# a = input value >= 3 and odd.
# b, c = output values, a = b*c, b,c > 1.
# returns b=0 if failure.
trial:
mov b, 3
loop5:
divu c, r, a, b
jz found, r
add b, b, 2
leu tmp, b, 1001 # TODO: tune max size
jnz loop5, tmp
mov b, 0
found:
ret b, c
# a = input value >= 3. Must be odd and have >=2 distinct prime factors.
# b, c = output values, a = b*c, b,c > 1.
ecm:
mov n, a
loop12:
# choose a random elliptic curve by picking m with 0 <= m < n
# y^2 = x^3 + mx + 1
rand a
mov b, 1
mov c, n
call mulmod
mov m, d
# check that the descriminant is nonzero. D = 4m^3+27
mov a, m
mov b, m
call mulmod
mov a, d
call mulmod
mov a, d
mov b, 4
call mulmod
mov a, d
mov b, 27
call addmod
jz loop12, d
# try to find factor of n with this elliptic curve
call ecmtry
jz loop12, b
divu c, tmp, n, b
ret b, c
# n = modulus
# m = curve param
# b = return value - 0 or a factor of n
ecmtry:
mov p, 0
mov q, 1
# multiply by 2
mov e, p
mov f, q
mov g, p
mov h, q
call ellipticadd
jnz foundfactor2, d
mov p, b
mov q, c
# continue multiplying by odd numbers
# TODO: just multiply by odd primes
mov i, 3
loop15:
mov e, p
mov f, q
mov g, i
call ellipticmul
jnz foundfactor3, d
mov p, b
mov q, c
add i, i, 2
jnz loop15, p
jnz loop15, q
mov b, 0
ret b
foundfactor3:
mov b, d
ret b
# multiplication by a constant in the elliptic curve "group"
# m = input curve parameter
# n = input modulus
# e,f = input x,y of point
# g = input multiplier
# b,c = output x,y of sum
# d = output 0 if successful, factor of n if not.
ellipticmul:
# compute g*(e,f) by repeated doubling
mov x, e
mov y, f
mov t, g
mov r, 0
mov s, 0
loop14:
jz done6, t
and tmp, t, 1
jz noadd, tmp
# r += x
mov e, r
mov f, s
mov g, x
mov h, y
call ellipticadd
jnz foundfactor2, d
mov r, b
mov s, c
noadd:
# x += x
mov e, x
mov f, y
mov g, x
mov h, y
call ellipticadd
jnz foundfactor2, d
mov x, b
mov y, c
shr t, t, 1
jmp loop14
done6:
mov b, r
mov c, s
mov d, 0
ret b, c, d
foundfactor2:
ret d
# addition in the elliptic curve "group"
# m = input curve parameter
# n = input modulus
# e,f = input x,y of first point (p)
# g,h = input x,y of second point (q)
# b,c = output x,y of sum
# d = output 0 if successful, factor of n if not.
ellipticadd:
px = e
py = f
qx = g
qy = h
rx = b
ry = c
gcd = d
# 0+q=q
or tmp, px, py
jz retq, tmp
# p+0=p
or tmp, qx, qy
jz retp, tmp
cmp tmp, px, qx
jz diffx, tmp
cmp tmp, py, qy
jz inf, tmp # px == qx, py != qy, return inf
jz inf, py # px == qx, py == qy, py==0, return inf
# px == qx, py == qy, py != 0. This is the double-root case
# u = numerator = 3 px^2 + a
mov a, px
mov b, px
mov c, n
call mulmod
mov a, d
mov b, 3
call mulmod
mov a, d
mov b, m
call addmod
mov u, d
# v = denominator = 2y
mov a, py
mov b, py
call addmod
mov v, d
jmp divide
diffx:
# px != qx
mov a, py
mov b, qy
call submod
mov u, d # u = numerator = py - qy
mov a, px
mov b, qx
call submod
mov v, d # v = denominator = px - qx
divide:
mov a, v
call inv
cmp tmp, c, 1 # gcd(v,n)==1?
jz foundfactor, tmp
mov v, d
# compute s = u/v mod n = u * v^-1 mod n
mov a, u
mov b, v
mov c, n
call mulmod
mov s, d
# compute x = s*s - px - qx
mov a, s
mov b, s
call mulmod
mov a, d
mov b, px
call submod
mov a, d
mov b, qx
call submod
mov x, d
# compute y = s * (px - x) - py
mov a, px
mov b, x
call submod
mov a, d
mov b, s
call mulmod
mov a, d
mov b, py
call submod
# return [s*s-px-qx, s*(px-x)-py]
mov rx, x
mov ry, d
mov gcd, 0
ret rx, ry, gcd
retp:
mov rx, px
mov ry, py
mov gcd, 0
ret rx, ry, gcd
retq:
mov rx, qx
mov ry, qy
mov gcd, 0
ret rx, ry, gcd
inf:
mov rx, 0
mov ry, 0
mov gcd, 0
ret rx, ry, gcd
foundfactor:
mov gcd, c
ret gcd
# a = input value >= 3. Must be odd.
# b = output factor of a.
# if a is a prime power, returns a factor of a.
# otherwise, returns 0.
primepower:
mov e, 2
loop6:
mov b, e
call nthroot
leu tmp, c, 3
jnz notprimepower, tmp
# compute c^e
mov r, 1
mov b, e
loop9:
mulu r, tmp, r, c
dec b
jnz loop9, b
cmp tmp, r, a
jnz isprimepower, tmp
inc e
cmp tmp, e, 41 # largest odd power in 2^64 is 3^40
jz loop6, tmp
ret
isprimepower:
mov b, c
ret
notprimepower:
mov b, 0
ret b
# a = input value
# b = input exponent
# c = output floor(a**(1/b))
nthroot:
# binary search for the root
mov c, 0
mov step, 0x80000000
loop7:
jz done3, step
add test, c, step
shr step, step, 1
# check if test^b > a
# test^b might overflow, so we can't just compute that and compare.
# so we start with e=a, divide by test b times, and check that
# the result is 0.
mov d, b
mov e, a
loop8:
divu e, tmp, e, test
dec d
jnz loop8, d
jz loop7, e # test is too big, don't change c
mov c, test # test is <= floor(a**(1/b)). Keep it.
jmp loop7
done3:
ret c
# a = input number >= 2
# b = ouput 1/0 if a is prime/composite
isprime:
# small primes (tests below require that we check these first)
cmp tmp, a, 2
jnz prime, tmp
cmp tmp, a, 3
jnz prime, tmp
cmp tmp, a, 5
jnz prime, tmp
cmp tmp, a, 7
jnz prime, tmp
cmp tmp, a, 11
jnz prime, tmp
cmp tmp, a, 13
jnz prime, tmp
cmp tmp, a, 17
jnz prime, tmp
cmp tmp, a, 19
jnz prime, tmp
cmp tmp, a, 23
jnz prime, tmp
cmp tmp, a, 29
jnz prime, tmp
cmp tmp, a, 31
jnz prime, tmp
cmp tmp, a, 37
jnz prime, tmp
# even numbers
and tmp, a, 1
jz composite, tmp
# uses Miller-Rabin with enough fixed bases to guarantee the
# correct result for numbers up to 2^64.
# see http://oeis.org/A014233
mov b, 2
call miller_rabin
jz composite, c
mov b, 3
call miller_rabin
jz composite, c
mov b, 5
call miller_rabin
jz composite, c
mov b, 7
call miller_rabin
jz composite, c
mov b, 11
call miller_rabin
jz composite, c
mov b, 13
call miller_rabin
jz composite, c
mov b, 17
call miller_rabin
jz composite, c
mov b, 19
call miller_rabin
jz composite, c
mov b, 23
call miller_rabin
jz composite, c
mov b, 29
call miller_rabin
jz composite, c
mov b, 31
call miller_rabin
jz composite, c
mov b, 37
call miller_rabin
jz composite, c
prime:
mov b, 1
ret b
composite:
mov b, 0
ret b
# a = input number >= 3
# b = input base value (1 < b < a-1)
# c = output 1 = may be prime, 0 = definitely composite
miller_rabin:
mov p, a
mov t, b
sub q, p, 1
mov s, 0
sub e, a, 1
loop2:
and tmp, e, 1
jnz endloop2, tmp
add s, s, 1
shr e, e, 1
jmp loop2
endloop2:
mov a, t
mov b, e
mov c, p
call pow
cmp tmp, d, 1
jnz unknown, tmp
cmp tmp, d, q
jnz unknown, tmp
mov x, d
loop4:
sub s, s, 1
jz composite2, s
mov a, x
mov b, x
mov c, p
call mulmod
cmp tmp, d, 1
jnz composite2, tmp
cmp tmp, d, q
jnz unknown, tmp
mov x, d
jmp loop4
composite2:
mov c, 0
ret c
unknown:
mov c, 1
ret c
# a = input value
# n = input modulus
# returns c, d such that
# c = gcd(a,n)
# d * a % n == gcd(a,n)
inv:
# extended euclidean algorithm, from
# http://stackoverflow.com/a/14093613/180090
new = e
old = f
pos = g
mov p, n
mov new, 1
mov old, 0
mov q, p
mov pos, 0
loop13:
jz done5, a
divu q, r, q, a
mulu h, tmp, q, new
add h, old, h
mov old, new
mov new, h
mov q, a
mov a, r
xor pos, pos, 1
jmp loop13
done5:
mov c, q
jnz positer, pos
sub old, p, old
positer:
mov d, old
ret c, d
# d = a ** b % c
pow:
mov r, 1
mov e, b
mov t, a
# t ** e % c
loop3:
jz endloop3, e
and tmp, e, 1
jz lowbitclear, tmp
mov a, t
mov b, r
call mulmod # r = t*r mod c
mov r, d
lowbitclear:
shr e, e, 1
mov a, t
mov b, t
call mulmod # t = t*t mod c
mov t, d
jmp loop3
endloop3:
mov d, r
ret d
# d = a * b % c
mulmod:
# do multiply
mulu e, f, a, b
# binary search for quotient
mov q, 0
mov step, 0x8000000000000000
loop:
jz done, step
# test = q + step
add test, q, step
shr step, step, 1
# check test*c
mulu g, h, test, c
geu tmp, h, f
jnz loop, tmp
leu tmp, h, f
jnz ok, tmp
geu tmp, g, e
jnz loop, tmp
ok:
# test*c <= a*b. Use test as the new q.
mov q, test
jmp loop
done:
# q == quotient of (a*b)/c
mulu g, h, q, c # q*c, g+h<<64 should be close to e+f<<64
sub d, e, g # remainder
ret d
# d = (a + b) % n
# requires 0 <= a, b < n
addmod:
add d, a, b
leu tmp, d, a # wrapped 2^64
jnz overflow, tmp
leu tmp, d, n # result less than modulus?
jnz inrange, tmp
overflow:
sub d, d, n
inrange:
ret d
# d = (a - b) % n
# requires 0 <= a, b < n
submod:
sub d, a, b
leu tmp, a, b # below 0?
jz nounderflow, tmp
add d, d, n
nounderflow:
ret d
read_int:
mov x, 0
read_int_loop:
lw c, -1
cmp q, c, ord("\n")
jnz read_int_done, q
sub c, c, ord("0")
mulu x, d, x, 10
add x, x, c
jmp read_int_loop
read_int_done:
ret x
write_int:
divu x, m, x, 10
jz write_int_done, x
call write_int
write_int_done:
add m, m, ord("0")
sw -1, m
ret
```
Output:
```
13
23
31
37
41
47
47
59
61
79
Execution terminated after 799601 cycles with exit code 0.
2
2
2
2
3
3
107
164546579
1121707
Execution terminated after 216769549 cycles with exit code 0.
3
3
3
7
7
7
13
50759273983933
Execution terminated after 939985 cycles with exit code 0.
7
7
7
13
2531
4091
250250521
Execution terminated after 34213849 cycles with exit code 0.
31
89
97
18211
3881
357653
Execution terminated after 9662357 cycles with exit code 0.
2
2
2
3
702924188994286579
Execution terminated after 748732 cycles with exit code 0.
7
103
727
7209485975851
Execution terminated after 912672 cycles with exit code 0.
66449
1920043
1604167
Execution terminated after 38514477 cycles with exit code 0.
322255481
52528036667
Execution terminated after 75568529 cycles with exit code 0.
9929766466606501253
Execution terminated after 738065 cycles with exit code 0.
```
[Answer]
# 2,279,635 cycles—7373 bytes (deterministic)
One-by-one:
```
robert@unity:~/golf-cpu/factor$ ./test.sh
13
23
31
37
41
47
47
59
61
79
Execution terminated after 1088 cycles with exit code 0.
2
2
2
2
3
3
107
164546579
1121707
Execution terminated after 41325 cycles with exit code 0.
3
3
3
7
7
7
13
50759273983933
Execution terminated after 9413 cycles with exit code 0.
7
7
7
13
250250521
2531
4091
Execution terminated after 22282 cycles with exit code 0.
31
89
97
357653
3881
18211
Execution terminated after 47656 cycles with exit code 0.
2
2
2
3
702924188994286579
Execution terminated after 17423 cycles with exit code 0.
7
103
7209485975851
727
Execution terminated after 15973 cycles with exit code 0.
1920043
66449
1604167
Execution terminated after 153683 cycles with exit code 0.
52528036667
322255481
Execution terminated after 1952229 cycles with exit code 0.
9929766466606501253
Execution terminated after 18563 cycles with exit code 0.
robert@unity:~/golf-cpu/factor$
```
Summary:
```
robert@unity:~/golf-cpu/factor$ ./test.py factor.golf factors_testset
binary length: 7373 bytes
10/10 passed in 0:00:08.53 s
2,279,635 cycles (227963.50 average)
(267.14 KCPS average)
0 ######################################################################
100000 ########
200000
300000
400000
500000
600000
700000
800000
900000
1000000
1100000
1200000
1300000
1400000
1500000
1600000
1700000
1800000
1900000 ########
robert@unity:~/golf-cpu/factor$
```
I use a combination of trial division and the Brent-Pollard rho algorithm for factorization, and table lookup plus Miller-Rabin for primality testing. I'll add some more explanation tomorrow.
Note that because of the character limit on post length, the second data table is truncated. [This gist](https://gist.github.com/2012rcampion/24ebd19353eff797b2b8) includes the full table.
```
primes_53 = \
b'\x03\x05\x07\x0b\x0d\x11\x13\x17\x1d\x1f\x25\x29\x2b\x2f\x35\x3b' \
b'\x3d\x43\x47\x49\x4f\x53\x59\x61\x65\x67\x6b\x6d\x71\x7f\x83\x89' \
b'\x8b\x95\x97\x9d\xa3\xa7\xad\xb3\xb5\xbf\xc1\xc5\xc7\xd3\xdf\xe3' \
b'\xe5\xe9\xef\xf1\xfb'
# for 2**16+1:2:2**17-1, 1 if prime, 0 otherwise
prime_bytes = \
b'\x8b\x24\x60\x82\x10\x41\x81\x12\x40\x08\x26\x0d\x03\x00\x01\x41' \
...
b'\x41\x30\x20\x10\x00\x00\x80\x00\x40\x50\x24\x00\x83\x00\x01\x8a'
main:
call input
# check if input is 1
cmp c, n, 1
sz c, 3
mov o, n
call print
halt 0
# remove factors of two
mov o, 2
div_2_loop:
and c, n, 1
snz c, 3
call print
shr n, n, 1
jmp div_2_loop
# check if n is a power of two
cmp c, n, 1
sz c, 1
halt 0
# trial division
mov d, data(primes_53)
mov i, 53
trial_division_loop:
lbu p, d
trial_division_check:
divu q, r, n, p
snz r, 4
mov o, p
call print
mov n, q
jmp trial_division_check
mulu s, t, p, p
leu c, n, s
sz c, 5
cmp c, n, 1
snz c, 2
mov o, n
call print
halt 0
sub i, i, 1
add d, d, 1
jnz trial_division_loop, i
# mov g, 0 # initialize factor list pointers
# mov h, 0 # all registers are zero at program start
# *g is the next factor to check for primality
# *h is the last factor we've found so far
# the first factor is always *0
sw g, n
prime_test:
# by this point we know that n has no prime factors less than 256,
# so if n is less than 256**2, then it must be prime
lequ c, n, 2**16
jnz is_prime, c
geu c, n, 2**17+1
jnz miller_rabin, c
sub d, n, 2**16+1 # table starts at 2**16+1 (by above argument)
shr d, d, 1 # we know n is odd, so we ignore the last bit
and m, d, 2**3-1 # each byte is 3-bit lookup table
shr d, d, 3
add d, d, data(prime_bytes)
lbu p, d
shr p, p, m
and p, p, 1
jnz is_prime, p
jmp pollard_rho # I should probably do trial division here
# since we only have around 20 more primes to check
################
# Miller-Rabin primality test; bases from https://miller-rabin.appspot.com/
# Note that this subroutine, as well as most of the ones before the 'utility
# functions' section are not proper functions, as they sometimes jump directly
# to the next step instead of returning!
#
# input: n
# output: n/a
################
miller_rabin:
shr d, n, 1
mov b, 1
mr_rd_loop: # n - 1 == d * 2**b, d is odd
and c, d, 1
snz c, 3
shr d, d, 1
inc b
jmp mr_rd_loop
geu c, n, 2**32-1 # test if we can use single-precision arithmetic
jnz miller_rabin_montgomery, c
sub m, n, 1
mr_test_1:
gequ c, n, 0x000000000005361b
jnz mr_test_2, c
mov a, 0x81b33f22efdceaa9
call miller_rabin_test
jmp is_prime
mr_test_2:
gequ c, n, 0x000000003e9de64d
jnz mr_test_3, c
mov a, 0x0000004e69b6552d
call miller_rabin_test
mov a, 0x00223f5bb83fc553
call miller_rabin_test
jmp is_prime
mr_test_3:
mov a, 0x3ab4f88ff0cc7c80
call miller_rabin_test
mov a, 0xcbee4cdf120c10aa
call miller_rabin_test
mov a, 0xe6f1343b0edca8e7
call miller_rabin_test
jmp is_prime
miller_rabin_montgomery:
call montgomery_precompute
sub m, n, r # montgomery representation of n-1
mr_test_mt_3:
gequ c, n, 0x000000518dafbfd1
jnz mr_test_mt_4, c
mov a, 0x3ab4f88ff0cc7c80
call miller_rabin_test_montgomery
mov a, 0xcbee4cdf120c10aa
call miller_rabin_test_montgomery
mov a, 0xe6f1343b0edca8e7
call miller_rabin_test_montgomery
jmp is_prime
mr_test_mt_4:
gequ c, n, 0x0000323ee0e55e6b
jnz mr_test_mt_5, c
mov a, 0x0000000000000002
call miller_rabin_test_montgomery
mov a, 0x0000810c207b08bf
call miller_rabin_test_montgomery
mov a, 0x10a42595b01d3765
call miller_rabin_test_montgomery
mov a, 0x99fd2b545eab5322
call miller_rabin_test_montgomery
jmp is_prime
mr_test_mt_5:
gequ c, n, 0x001c6b470864f683
jnz mr_test_mt_6, c
mov a, 0x0000000000000002
call miller_rabin_test_montgomery
mov a, 0x000003c1c7396f6d
call miller_rabin_test_montgomery
mov a, 0x02142e2e3f22de5c
call miller_rabin_test_montgomery
mov a, 0x0297105b6b7b29dd
call miller_rabin_test_montgomery
mov a, 0x370eb221a5f176dd
call miller_rabin_test_montgomery
jmp is_prime
mr_test_mt_6:
gequ c, n, 0x081f23f390affe89
jnz mr_test_mt_7, c
mov a, 0x0000000000000002
call miller_rabin_test_montgomery
mov a, 0x000070722e8f5cd0
call miller_rabin_test_montgomery
mov a, 0x0020cd6bd5ace2d1
call miller_rabin_test_montgomery
mov a, 0x009bbc940c751630
call miller_rabin_test_montgomery
mov a, 0x0a90404784bfcb4d
call miller_rabin_test_montgomery
mov a, 0x1189b3f265c2b0c7
call miller_rabin_test_montgomery
jmp is_prime
mr_test_mt_7:
mov a, 0x0000000000000002
call miller_rabin_test_montgomery
mov a, 0x0000000000000145
call miller_rabin_test_montgomery
mov a, 0x000000000000249f
call miller_rabin_test_montgomery
mov a, 0x0000000000006e12
call miller_rabin_test_montgomery
mov a, 0x000000000006e0d7
call miller_rabin_test_montgomery
mov a, 0x0000000000953d18
call miller_rabin_test_montgomery
mov a, 0x000000006b0191fe
call miller_rabin_test_montgomery
jmp is_prime
is_prime:
mov o, n
call print
cmp c, g, h
sz c, 1
halt 0
add g, g, 8
lw n, g
jmp prime_test
found_factor:
divu n, b, n, a
add h, h, 8
sw h, a
jmp prime_test
################
# Miller-Rabin primality test subroutine; needs m == n - 1
#
# input: a, n, m
# output: n/a
################
miller_rabin_test:
divu q, a, a, n # a = a mod n
snz a, 1
ret # a certifies primality if a == 0 mod n
call power # a = a**d mod n
cmp c, a, 1 # r == 1
sz c, 1
ret # a certifies primality if a**d == 1 mod n
cmp c, a, m # m == n-1
sz c, 1
ret # a certifies primality if a**d == -1 mod n
mov d, 2
mr_square_loop:
dec b
jz pollard_rho, b
mulu x, y, a, a # a = a**2 mod n
divu q, a, x, n # q is unused
cmp c, a, 1 # r == 1
jnz pollard_rho, c # a witnesses compositeness if a**(d*2**i) == 1 mod n
cmp c, a, m # m == n-1
sz c, 1
ret # a certifies primality if a**(d*2**i) == -1 mod n
jmp mr_square_loop
################
# Miller-Rabin primality test subroutine using Montgomery arithmetic; needs
# the values from the precomputation step as well as m == n - 1
#
# input: a, n, m, (u, v, r, s)
# output: n/a
################
miller_rabin_test_montgomery:
divu q, a, a, n # a = a mod n
snz a, 1
ret # a certifies primality if a == 0 mod n
mulu x, y, a, s
call montgomery_reduce # convert a to montgomery form
mov a, x
call montgomery_power # a = a**d mod n
cmp c, a, r # r == 1 (mongtomery form)
sz c, 1
ret # a certifies primality if a**d == 1 mod n
cmp c, a, m # m == n-1 (montgomery form)
sz c, 1
ret # a certifies primality if a**d == -1 mod n
mr_mt_square_loop:
dec b
jz pollard_rho_montgomery, b
mulu x, y, a, a # a = a**2 mod n
call montgomery_reduce
mov a, x
cmp c, a, r # r == 1 (mongtomery form)
jnz pollard_rho_montgomery, c # a witnesses compositeness if a**(d*2**i) == 1 mod n
cmp c, a, m # m == n-1 (montgomery form)
sz c, 1
ret # a certifies primality if a**(d*2**i) == -1 mod n
jmp mr_mt_square_loop
################
# Pollard-Brent rho factorization algorithm
#
# input: n
# output: n/a
################
pollard_rho:
rho_skip_count = 64
mov o, 42
rho_retry:
mov b, o
mov j, 1
mov f, 1
mov d, 1
rho_outer_loop:
mov a, b
mov i, j
rho_fast_loop:
mulu b, y, b, b
add b, b, 1
divu y, b, b, n
#mov o, b
#call print
sub i, i, 1
jnz rho_fast_loop, i
mov k, 0
rho_slow_loop:
mov e, b
sub i, j, k
leu c, rho_skip_count, i
sz c, 1
mov i, rho_skip_count
rho_inner_loop:
mulu b, y, b, b
add b, b, 1
divu y, b, b, n
leu c, a, b
sz c, 1
sub x, b, a
snz c, 1
sub x, a, b
mulu f, y, x, f
divu y, f, f, n
#add o, f, 1000000000
#call print
sub i, i, 1
jnz rho_inner_loop, i
mov x, f
call gcd
mov d, x
#mov o, d
#call print
add k, k, rho_skip_count
gequ c, k, j
snz c, 2
lequ c, d, 1
jnz rho_slow_loop, c
shl j, j, 1
lequ c, d, 1
jnz rho_outer_loop, c
cmp c, d, n
sz c, 12
rho_final_loop:
mulu e, y, e, e
add e, e, 1
divu y, e, e, n
#add o, e, 2000000000
#call print
leu c, a, e
sz c, 1
sub x, e, a
snz c, 1
sub x, a, e
call gcd
mov d, x
#mov o, d
#call print
lequ c, d, 1
jnz rho_final_loop, c
cmp c, d, n
sz c, 2
add o, o, 1
jmp rho_retry
mov a, d
jmp found_factor
################
# Pollard-Brent rho factorization algorithm using Montgomery arithmetic.
# Requires m = n - r
#
# input: n, (u, v, r, s, m)
# output: n/a
################
pollard_rho_montgomery:
rho_mt_skip_count = 64
mov o, 42
rho_mt_retry:
mulu x, y, o, s
call montgomery_reduce
mov b, x
mov j, 1
mov f, r
mov d, 1
rho_mt_outer_loop:
mov a, b
mov i, j
rho_mt_fast_loop:
mulu x, y, b, b
call montgomery_reduce
mov b, x
geu c, b, m
sz c, 1
sub b, b, m
snz c, 1
add b, b, r
#mov o, b
#call print
sub i, i, 1
jnz rho_mt_fast_loop, i
mov k, 0
rho_mt_slow_loop:
mov e, b
sub i, j, k
leu c, rho_mt_skip_count, i
sz c, 1
mov i, rho_mt_skip_count
rho_mt_inner_loop:
mulu x, y, b, b
call montgomery_reduce
mov b, x
geu c, b, m
sz c, 1
sub b, b, m
snz c, 1
add b, b, r
leu c, a, b
sz c, 1
sub x, b, a
snz c, 1
sub x, a, b
mulu x, y, x, f
call montgomery_reduce
mov f, x
sub i, i, 1
jnz rho_mt_inner_loop, i
mov x, f
#mov o, x
#call print
call gcd
mov d, x
#mov o, d
#call print
add k, k, rho_mt_skip_count
gequ c, k, j
snz c, 2
lequ c, d, 1
jnz rho_mt_slow_loop, c
shl j, j, 1
lequ c, d, 1
jnz rho_mt_outer_loop, c
cmp c, d, n
sz c, 15
rho_mt_final_loop:
mulu x, y, e, e
call montgomery_reduce
mov e, x
geu c, e, m
sz c, 1
sub e, e, m
snz c, 1
add e, e, r
leu c, a, e
sz c, 1
sub x, e, a
snz c, 1
sub x, a, e
call gcd
mov d, x
lequ c, d, 1
jnz rho_mt_final_loop, c
cmp c, d, n
sz c, 2
add o, o, 1
jmp rho_mt_retry
mov a, d
jmp found_factor
################ UTILITY FUNCTIONS ################
################
# Loads a decimal number terminated by a newline from stdin to register n.
#
# inputs: none
# outputs: n
################
input:
lw c, -1
input_add_digit:
sub c, c, ord('0')
mov o, c
mulu n, h, n, 10
add n, n, c
lw c, -1
cmp q, c, ord('\n')
jz input_add_digit, q
ret n
################
# Prints the value of register o to stdout in decimal, followed by a newline.
#
# inputs: o
# outputs: none
################
print:
call print_char
sw -1, ord('\n')
ret
print_char:
divu o, x, o, 10
sz o, 1
call print_char
add x, x, ord('0')
sw -1, x
ret
################
# Precomputes values used for Montgomery multiplication:
# * u = 1/2**64 mod n
# * v = -1/n mod 2**64
# * r = 2**64 mod n (montgomery representation of 1)
# * s = 2**128 mod n (montgomery representation of 2**64)
#
# inputs: n
# outputs: u, v, s, t
################
montgomery_precompute:
# first compute the inverses; based on xbinGCD from
# http://www.hackersdelight.org/MontgomeryMultiplication.pdf
# This step takes something like an average of 7 cycles per bit in the
# 'fast' mode, and 8 cycles per bit in 'safe' mode, for a total of around
# 500 cycles: but we only have to do it once per modulus
mov u, 1
mov v, 0
mov i, 64
# HD defensively computes (u+beta)/2 to avoid overflow, taking two extra
# instructions; however, since u < beta overflow is only possible when
# beta >= 2**63, in most cases we can use a faster version and save
# 2 * 64 = 128 cycles, at the expense of a couple cycles comparison
gequ c, n, 2**63
jz mt_pre_gcd_loop, c
mt_pre_gcd_loop_safe:
dec i
and c, u, 1
snz c, 3
shr u, u, 1
shr v, v, 1
sz 0, 6
and c, u, n
xor u, u, n
shr u, u, 1
add u, u, c
shr v, v, 1
add v, v, 2**63
jnz mt_pre_gcd_loop_safe, i
jmp mt_pre_gcd_end
mt_pre_gcd_loop:
dec i
and c, u, 1
snz c, 3
shr u, u, 1
shr v, v, 1
sz 0, 4
add u, u, n
shr u, u, 1
shr v, v, 1
add v, v, 2**63
jnz mt_pre_gcd_loop, i
mt_pre_gcd_end:
# compute 2**64 mod n; since 2**64 is too large to fit in a register, we
# first calculate r = 2**63 mod n, if it's greater than n/2, r = 2r - n,
# otherwise just r = 2r
divu q, r, 2**63, n # q is unused
shr c, n, 1
geu c, r, c
shl r, r, 1
sz c, 1
sub r, r, n
# It would be entirely possible to compute 2**128 mod n by starting with
# r and using repeated doubling (64 times); this would take something
# like 4*64 = 256 cycles. Instead I'll use a doubleword division
# algorithm from Hacker's Delight (ch. 9-4, fig. 9-3), which takes
# fewer than 100 cycles.
mov l, 0
# normalize the divisor (n)
and c, n, 2**64 - 2**32
snz c, 2
shl n, n, 32
add l, l, 32
and c, n, 2**64 - 2**48
snz c, 2
shl n, n, 16
add l, l, 16
and c, n, 2**64 - 2**56
snz c, 2
shl n, n, 8
add l, l, 8
and c, n, 2**64 - 2**60
snz c, 2
shl n, n, 4
add l, l, 4
and c, n, 2**64 - 2**62
snz c, 2
shl n, n, 2
add l, l, 2
and c, n, 2**64 - 2**63
snz c, 2
shl n, n, 1
add l, l, 1
# normalize the numerator
shl a, r, l
# split the divisor into halfwords
shr b, n, 32
and m, n, 2**32 - 1
# compute first halfword of remainder
divu q, p, a, b
mt_pre_div_adjust1: # loop runs at most two times, 035x on average
gequ c, q, 2**32
snz c, 4
mulu d, f, q, m # f is unused
shl c, p, 32
geu c, d, c
sz c, 4
sub q, q, 1
add p, p, b
leu c, p, 2**32
jnz mt_pre_div_adjust1, c
shl a, a, 32
mulu d, f, q, n
sub a, a, d
# compute second halfword of remainder
divu q, p, a, b
mt_pre_div_adjust2:
snz c, 4
mulu d, f, q, m
shl c, p, 32
geu c, d, c
sz c, 4
sub q, q, 1
add p, p, b
leu c, p, 2**32
jnz mt_pre_div_adjust2, c
shl a, a, 32
mulu d, f, q, n
sub a, a, d
# de-normalize remainder
shr s, a, l
ret u, v, r, s
################
# Performs the Montgomery reduction step, x = [yx]/2**64 mod n
# Requres the u and v calculated in mongomery_precompute.
#
# inputs: x, y, n, (u, v)
# outputs: x
################
montgomery_reduce:
mulu m, u, x, v # m = ([yx] mod 2**64) / (-n) mod 2**64
mulu z, w, m, n # [wz] = mN
add x, x, z # [yx] += [wz]
leu c, x, z # this is where I really miss an ADC instruction
sz c, 1
inc w
add x, y, w # x = [yx] / 2**64 = y (combined with y+w from above)
leu c, x, y # x -= n if overflow
sz c, 1
sub x, x, n
gequ c, x, n # if x >= n
sz c, 1
sub x, x, n # x -= n
ret x
################
# Computes a = a**d mod n by repeated squaring.
#
# inputs: a, d, n
# outputs: a
################
power:
mov b, a
mov a, 1
mt_pow_loop:
and c, d, 1
sz c, 2
mulu x, y, a, b # a = a*b mod n
divu q, a, x, n # q is unused
mulu x, y, b, b # b = b*b mod n
divu q, b, x, n
shr d, d, 1
jnz mt_pow_loop, d
ret a
################
# Uses Montgomery multiplication to compute a = a**d mod n. Treats d as an
# ordinary unsigned integer; treats d as an integer in Montgomery form.
# Requres the u, v, and r calculated in mongomery_precompute.
#
# inputs: a, d, n, (u, v, r)
# outputs: a
################
montgomery_power:
mov b, a
mov a, r
pow_loop:
and c, d, 1
sz c, 3
mulu x, y, a, b
call montgomery_reduce
mov a, x
mulu x, y, b, b
call montgomery_reduce
mov b, x
shr d, d, 1
jnz pow_loop, d
ret a
################
# Computes x = GCD(x,n) using the binary GCD algorithm. Assumes that x < n
# and that n is odd. Note that we don't need a separate Montgomery GCD,
# since, surprisingly, GCD(x*(2**64) mod n, n) == GCD(x, n).
#
# inputs: x, n
# outputs: x
################
gcd:
snz x, 2 # GCD(0, n) == n
mov x, n
ret x
gcd_loop:
and c, x, 1 # n is odd, so the GCD has no factors of two
snz c, 3
gcd_div_2_loop:
shr x, x, 1
and c, x, 1
jz gcd_div_2_loop, c
geu c, n, x
sz c, 5
sub x, n, x
sub n, n, x
jnz gcd_loop, x
mov x, n
ret x
sub x, x, n
jnz gcd_loop, x
mov x, n
ret x
```
] |
[Question]
[
I'm trying to read 4 ints in C in a golfing challenge and I'm bothered by the length of the code that I need to solve it:
```
scanf("%d%d%d%d",&w,&x,&y,&z)
```
that's 29 chars, which is huge considering that my total code size is 101 chars. I can rid of the first int since I don't really need it, so I get this code:
```
scanf("%*d%d%d%d",&x,&y,&z)
```
which is 27 chars, but it's still lengthy.
So my question is, is there any other way (tricks, functions, K&R stuff) to read ints that I don't know of that could help me reduce this bit of code?
---
Some users have reported that my question is similar to [Tips for golfing in C](https://codegolf.stackexchange.com/questions/2203/tips-for-golfing-in-c)
While this topic contain a lot of useful information to shorten C codes, it isn't relevant to my actual use case since it doesn't provide a better way to read inputs.
I don't know if there is actually a better way than scanf to read multiple integers (that's why I'm asking the question in the first place), but if there is, I think my question is relevant and is sufficiently different than global tips and tricks.
If there is no better way, my question can still be useful in the near future if someone find a better solution.
I'm looking for a full program (so no function trick) and all libraries possible. It needs to be C, not C++. Currently, my whole program looks like this:
```
main(w,x,y,z){scanf("%*d%d%d%d",&x,&y,&z)}
```
Any tricks are welcome, as long as they shorten the code (this is code golf) and work in C rather than C++.
[Answer]
Thanks to @DialFrost for drawing my attention to this question.
I believe for reading 4 numbers your solution is optimal. However, I found a solution that saves bytes when reading 5 or more numbers at a time.
It will also consume the entire input (i.e. it can't be used in a loop).
Depending on the context it might help you with only 4 variables too
If you define your variables in a sequence like this:
```
a,b,c,d,e;main(){
```
In this case, the variables will be layed out in successive memory addresses, we can abuse that.
```
for(;~scanf("%d",&a+e);e++);
```
Full program:
```
// new
a,b,c,d,e;main(){for(;~scanf("%d",&a+e);e++);}
// original
a,b,c,d;main(e){scanf("%d%d%d%d%d",&a,&b,&c,&d,&e);}
```
This 29 byte segment will paste all the input in successive variables starting in `a`. We re-use `e`, (the last variable) as the index variable. This saves declaring one variable.
## Size comparison
| Number of inputs | Original | New | Original (full program) | new (full program) |
| --- | --- | --- | --- | --- |
| 1 | 14 | 28 | 24 | 38 |
| 2 | 19 | 28 | 31 | 40 |
| 3 | 24 | 28 | 38 | 42 |
| 4 | 29 | 28 | 45 | 44 |
| 5 | 34 | 28 | 52 | 46 |
| 6 | 39 | 28 | 59 | 48 |
Note that the new method gains a 1 byte disadvantage in full programs because you can't use function arguments, however, this doesn't matter if you can use another variable as the argument to `main`.
Note there is also a slot in the initialization portion of the for loop. If you can put another expression there this method can save 1 byte even with only 4 arguments.
[Try it online!](https://tio.run/##S9YtSU7@n6iTpJOsk6KTap2bmJmnoVn9Py2/SMPawKY4OTEvTUNJNUVJRy1RO1XTOlVbW9P6f0FRZl4JWBwGlXTgZmha1/43VDBSMFYwUTAFAA "C (tcc) – Try It Online")
@JDT ponted out you can save 1 byte at the cost of having 1 added to `e` at the end:
```
for(;0<scanf("%d",&a+e++););
```
[Answer]
If you want to e.g. print all the inputs then we have this, being 64 bytes long:
```
main(x,y,z){scanf("%*d%d%d%d",&x,&y,&z);printf("%d%d%d",x,y,z);}
```
We can actually shorten this with a loop, bringing the total down to 47 bytes:
```
main(z){for(;scanf("%d",&z)>0;)printf("%d",z);}
```
So the reading part is only [23 bytes long](https://tio.run/##S9YtSU7@/z83MTNPo0qzOi2/SMO6ODkxL01DSTVFR0lHrUrTzsBas6AoM68ELKakU6VpXfv/v6EOGAIA):
```
for(;scanf("%d",&z)>0;)
```
Note that this only works when you don't want to assign a value to a specific variable and only want to **read** the values.
[A method that is 29 bytes long](https://tio.run/##S9YtSU7@n6iTpJOsk6KTaZ2bmJmnoVn9Py2/SMO6ODkxL01DSTVFR0lHLVE7U9POwDpTW1vT@n9BUWZeCVgKApV0oEZoWtf@N9Qx0jHWMQEA):
```
for(;scanf("%d",&a+i)>0;i++);
```
Shout out to @mousetail for helping me out!
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~44~~ 43 bytes
```
main(i,a,b,c,d){for(;i+=scanf("%d",i+&i););
```
[Try it online!](https://tio.run/##Pc3BCsIwEATQe75iCRiSdku19bb4MenGlAUbJa0n8deNWqnMHN8w3IzMpUxekhX0OCBjcI94zZakPs3sU7R6FzRKbcSRo9JWanW0jj74j37RaDyaAQ2jCY5U1apblrRE@BrYqhG2O4J8Xu45wZ6e5QAd9HB8cbz4cS7N1Hdv "C (gcc) – Try It Online")
This frees up an extra integer `i=0`, while [mousetail's solution](https://codegolf.stackexchange.com/a/252554/76323) make `i=5`(can't find a compiler that allow reusing `e` as index without adding extra 1)
Need `-m32` maybe because on x64 values are passed via registers
# [C (tcc)](http://savannah.nongnu.org/projects/tinycc), 44 bytes
```
a,b,c,d,i;main(){for(;i+=scanf("%d",i+&a););
```
[Try it online!](https://tio.run/##Tc1NCgIxDEDhfU8RCpZmJjL@7YKHyaQWsrBKravBs1dwRORtP3i6baq9C82klMj4KlYiLvlWI9t4fqiUHP0mebIxCDJynwb38atNuPzQmqcgFGYKSiEhu2Fy92qlZfg38H0iQ720Zy2w41ffwwGOcHoD "C (tcc) – Try It Online")
] |
[Question]
[
## Premise
So recently I was about half an hour early to an appointment, and decided to wait outside. I also determined that it would look strange if I just stood motionlessly in front of the house. Therefore, I decided to go on a quick walk, within a limited area. I also concluded that if I started walking in circles that would make it obvious that I was loitering. So I was inspired to create my first Code Golf challenge.
## Specification
You will be given a list, a map of the area, which will contain either `" "` or `"#"`, which represent free spaces and obstacles of some sort. Free spaces can only be crossed once, and it takes 1 minute to cross it. Your initial position will be signified with a `"@"` per roguelike tradition, and the target will be represented with a `"$"` because that's what you're going to lose there. You will also be given an integer which will represent how many minutes you have to waste before not seeming as if you were intruding. When you land on the `"$"`, it will have to have been the exact amount minutes (so if you were counting down, it will have to be 1 on an adjacent tile, and be 0 on the tile). It will always be possible to reach the destination. Your program or function will have to return a list showing the shortest path with <, >, ^, and v to represent the four possible directions.
## Examples
**Input:**
```
[[" ", " ", " ", " "],
["@", " ", " ", "$"],
[" ", " ", " ", " "],
[" ", " ", " ", " "]]
```
and
```
5
```
**Ouput:**
```
[[">", ">", ">", "v"],
["^", " ", " ", "$"],
[" ", " ", " ", " "],
[" ", " ", " ", " "]]
```
**Input:**
```
[[" ", "#", " ", " ", " "],
[" ", "#", " ", " ", " "],
["@", "#", " ", "$", " "],
[" ", " ", " ", " ", " "],
[" ", "#", " ", " ", " "],
[" ", "#", " ", " ", " "]]
```
and
```
7
```
**Output:**
```
[[" ", "#", " ", " ", " "],
[" ", "#", ">", "v", " "],
["v", "#", "^", "$", " "],
[">", ">", "^", " ", " "],
[" ", "#", " ", " ", " "],
[" ", "#", " ", " ", " "]]
```
**Input:**
```
[[" ", "#", " ", " ", " "],
[" ", "#", " ", " ", " "],
["@", "#", " ", "$", " "],
[" ", " ", " ", " ", " "],
[" ", "#", " ", " ", " "],
[" ", "#", " ", " ", " "]]
```
and
```
17
```
**Output:**
```
[[" ", "#", " ", "v", "<"],
[" ", "#", " ", "v", "^"],
["v", "#", " ", "$", "^"],
[">", ">", "v", ">", "^"],
[" ", "#", "v", "^", "<"],
[" ", "#", ">", ">", "^"]]
```
## Rules
* Standard loopholes apply
* Each tile must only be moved over once
* The exact amount of time must be spent on the board
* Only one path needs to be displayed in the case of multiple paths
* This is a code golfing question so shortest answer wins
* As per user202729's question in the comments, you may assume valid input.
Add a comment if any further clarification is required
[Answer]
# JavaScript (ES6), 171 bytes
Takes input in currying syntax `(a)(n)`. [Outputs by modifying](https://codegolf.meta.stackexchange.com/a/4942/58563) the input matrix.
```
a=>g=(n,y=a[F='findIndex'](r=>~(i=r[F](v=>v>'?'))),x=i,R=a[y])=>!n--|[-1,0,1,2].every(d=>(R[x]='<^>v'[d+1],(c=(a[Y=y+~-d%2]||0)[X=x+d%2])<1?g(n,Y,X):n|c!='$')&&(R[x]=' '))
```
[Try it online!](https://tio.run/##1Y5Na8JAEIbv@RXrR90ZMhEjFKE4a70IvXpSli2EfEiKbEqUkEDwr6dJaaHBKr32sjDPzL7v8xYUwSnM0/ezZ7MobhJuAlYHBksVB3rDMklt9GKjuJQGclYXSDnXGwMFq0LJlUREKjmlbXteGWQ1sJ5Xa8@nGfk0N9O4iPMKIlaw1aVhuXxVhdSR6xuCkCHQe67cixc9zE1dz1DvuHS7AZf@6tB67GmHT7YOByzHEieTrxjRNjfn@HQWLGBNwqJgJSCBNYJFEmFmT9kxnh6zQ4v6M6LjdF9BO0LooRiS6D2GPvlzn4@/@a37a@4YEo@/lI3uJYzu6Yx@6Nzt/nPsjWWnvvi/6v4Cmw8 "JavaScript (Node.js) – Try It Online")
### Commented
```
a => // a[] = input matrix
g = ( // g = recursive function taking:
n, // n = number of remaining moves
// (x, y) = current coordinates, initialized as follows:
y = a[F = 'findIndex'](r => // y = index of the row containing the starting point,
~(i = r[F](v => v > '?')) // found by iterating over all rows r until we
), // find some i such that r[i] > '?'
x = i, // x = index of the column of the starting point
R = a[y] // R[] = current row
) => //
!n-- | // decrement n; force failure if we're out of moves
[-1, 0, 1, 2].every(d => // for each direction d, where -1 = left, 0 = up,
( // 1 = right and 2 = down:
R[x] = '<^>v'[d + 1], ( // update the current cell with the direction symbol
c = ( // c = content of the new cell at (X, Y) with:
a[Y = y + ~-d % 2] // Y = y + dy
|| 0 // (use a dummy value if this row does not exist)
)[X = x + d % 2] // X = x + dx
) < 1 ? // if c is a space:
g(n, Y, X) // we can go on with a recursive call
: // else:
n | c != '$' // return false if n = 0 and we've reached the target
) && // unless the above result is falsy,
(R[x] = ' ') // restore the current cell to a space
) // end of every()
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~310~~ 256 bytes
Thanks @cairdcoinheringaahing for `except:0` -3 bytes
Thanks @Mnemonic for -8 bytes
Thanks @JonathanAllan for -3 bytes
Thanks @ovs for -5 bytes
```
G,L=input()
R=[]
def S(x,y,G,c,R):
try:
if x>-1<y<G[y][x]in' @':i=0;exec"T=[r[:]for r in G];T[y][x]='<v^>'[i];S(x+~-i/2,y+~-(i^2)/2,T,c-1,R);i+=1;"*4
R+=[G]*(0==c<'$'==G[y][x])
except:0
for i,y in enumerate(G):"@"in y>S(y.index("@"),i,G,L,R)
print R[0]
```
[Try it online!](https://tio.run/##1ZBBa4MwFMfPzad4aCGxTTd1GwU1pTcvPVlvIYVhU/YOiyJ2mMu@uot0g5XVsesuSfi9l//vJY3tXmoTD1V91CCAUjrkfCfQNOeOBaQQUpGjPsGe9dzynFe8CBICXWsTMsMT9JtVlNksl1bJXqGhsKUJijDVva68UshWJupUt9ACGshVWl46Bc3eDhsqUaUuevm@wvuYW7czPMSBO5e8WkVOluJSRKm3eCSzYilkrhYsFKLK6JwK8akNCOi@0k2XhGR0IbejTZvzq26fO83yIPG2nkN2s2f2Ds1R98yRgKN7085pSNOi6aCQoRrcJxAyzg/jryweyCClBx6Hq0VxkC7iis4v9HbvT@rwE/nK9qcv@dNu/5v7F9WfAidKrrb@F1NG6w8 "Python 2 – Try It Online")
Some explanation:
`try-except` is used to ensure, that both `x` and `y` coordinates are in boundaries. Exception will be raised upon access to `G[y][x]`. Python is too good and negative indices are acceptable, so check `x>-1<y` is added.
`T=[r[:]for r in G]` used to create copy of `G` by values
`~-i/2` and `~-(i^2)/2` are used to generate pairs `(-1, 0), (0, 1), (0, -1), (1, 0)`, that used to move in grid *(there still should be shorter way!)*
`R+=[G]*(0==c<'$'==G[y][x])` check, that `'$'` is reached in required number of steps. `R` is used to get this result from recursive function calls.
`for i,y in enumerate(G):"@"in y>S(y.index("@"),i,G,L,R)` Found `x` and `y` of `'@'` in input and call function `S`.
`print R[0]` `R` might contain more that one solution, so output just first
[Answer]
# [Python 2](https://docs.python.org/2/), ~~264~~ ~~261~~ ~~251~~ 249 bytes
```
def f(a,n,r=-1,s=0):
j=len(a[0]);x=1;z=y=0
if r<0:s,r=divmod(sum(a,[]).index('@'),j)
for c in'>v<^':
u=r+x;v=s+y;x,y=-y,x
if j>u>-1<v<len(a):b=[e[:]for e in a];b[s][r]=c;w=a[v][u];z=n*(w<'!')and f(b,n-1,u,v)or n==1and w=='$'and b
if z:return z
```
[Try it online!](https://tio.run/##rVHLboMwEDzHX7ENkcCNU0GlqiqwUZp8huVKUEAlKgaZRyA/T02SQ1Ab2kMvlj2zOzPrLbrqI5ePfR/FCSRWwCRTuHJYiTZ1CezxM5ZWwG1BvRYd74gd2gTSBJRvu6WujdImyyOrrDPdzAV9SGUUt5a5MSnbUwJJruAdUmmuG//NdMmsRrVsvQbLZee1rMNVx1oy04r7db1eOX7jnyypGyKPuSsGgVgLQCC8kJeCK4Hv3gED3gheCx1J3lsH37wzaSAjPUPIpB6gZg3VnRLRGeADorkwh1t4Mju6Kq5qJeHYJyrPoChUKitIsyJX1eVFSBWX1SsgcAJ8DnMGo0OwAd6M4cUFvlH9HRZnm@3IxpjoNiZyGFc5plz/qHmDu0Te3fyZ/4r8ayzjqmpyVB35vFQrsU5bZU@UkvOaR8SWPf9M7Jjzopn@Cw "Python 2 – Try It Online")
] |
[Question]
[
Here is an image:
```
%%%%%%%%%%%%%
% Hello, %
% world! %
%%%%%%%%%%%%%
```
But it is too confusing for our undersized brains to compute. So we average it like this:
1. Split it into 2 x 2 sections. If the picture ends before a section is complete, imagine that there are spaces there.
2. Average the values of the ASCII characters in each section.
3. Round this average and convert it to an ASCII character.
4. Finally, replace all characters in the section to the average character.
Repeat this for all sections.
So the average of the image above looks like this:
```
$$>>II99######
$$>>II99######
$$##88KKGG####
$$##88KKGG####
```
**Your task: Write a program that takes an ASCII image as input and outputs its average.**
*Note Integers are rounded by function `floor(x+0.5)` or similar function - in other words, round halves upwards.*
[Answer]
# JavaScript (ES6), 159 bytes
```
document.write("<pre>"+(
// --- Solution ---
s=>s.replace(/./g,(c,i)=>(a=String.fromCharCode([t=0,1,l=s.search`
`+1,l+1].map(o=>t+=(n=s.charCodeAt(p=i+o-i%l%2-(i/l|0)%2*l))>32?n:32)|t/4+.5))+(++p%l?"":a))
// ----------------
)(`%%%%%%%%%%%%%
% Hello, %
% world! %
%%%%%%%%%%%%%`))
```
Takes a multiline string as input.
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), ~~32~~ 30 bytes
```
2thZCO32XEoYmYocGZy2/Xke2t3$Y"
```
Input is a 2D char array, with rows separated by `;`.
[**Try it online!**](http://matl.tryitonline.net/#code=MnRoWkNPMzJYRW9ZbVlvY0daeTIvWGtlMnQzJFki&input=WyclJSUlJSUlJSUlJSUlJzsnJSBIZWxsbywgICAgJSc7JyUgICAgd29ybGQhICUnOyclJSUlJSUlJSUlJSUlJ10)
### Explanation
```
2th % push array [2 2]
ZC % take input implicitly. Arrange distinct 2x2 blocks as columns, padding with 0
O32XE % replace 0 by 32 (space)
oYm % convert to number. Take mean of each column
Yoc % round. Convert to char
GZy % size of input in the 2 dimensions
2/Xk % divide each dimension by 2, and round up to account for the padding
e % reshape into image with half original size in each dimension
2t3$Y" % replicate by a factor of 2 in each dimension. Display implicitly
```
[Answer]
# Pyth, 58 bytes
```
J2A,lQlhQV:0GJ
Ksm*C+csmsm?&<kG<bHC@@Qkb32hBdhBN4 .5J:0HJK
```
[Try it online!](https://pyth.herokuapp.com/?code=J2A%2ClQlhQV%3A0GJ%0AKsm*C%2Bcsmsm%3F%26%3CkG%3CbHC%40%40Qkb32hBdhBN4+.5J%3A0HJK&input=%5B%22%25%25%25%25%25%25%25%25%25%25%25%25%25%22%2C+%22%25+Hello%2C++++%25%22%2C+%22%25++++world!+%25%22%2C+%22%25%25%25%25%25%25%25%25%25%25%25%25%25%22%5D&debug=0)
[Answer]
# Lua, ~~382~~ ~~376~~ ~~367~~ ~~353~~ 348 bytes
```
r="\n"o=... n=o:find(r)-1
l=n+n%2
a=o:gsub(r,(n~=l and" "or"")..r).." "..(#o//(l+1)%2<1 and r..(" "):rep(l)or"")print(a:gsub("()([^\n])(.)",function(p,m,c)t=p//(l+1)%2==0return string.char(math.floor((m:byte()+c:byte()+(t and a:sub(p+l+1,p+l+1)or a:sub(p-l,p-l)):byte()+(t and a:sub(p+l+2,p+l+2)or a:sub(p-l-1,p-l-1)):byte())/4+.5)):rep(2)end).."")
```
Works on the command line; accepts a string like the test case.
[Answer]
# Ruby, ~~235~~ 230 bytes
```
->i{i=i.split($/).map{|s|s.bytes+[s.size%2>0?32:0]}
w=i[0].size;h=i.size;h+=h%2;r=[[]]*h
(h/2).times{|y|y*=2
(w/2).times{|x|x*=2
c=((i[y][x,2]+(i[y+1]||[32]*w)[x,2]).inject(:+)/4.0).round.chr
r[y+1]=r[y]+=[c,c]}}
r.map(&:join)*$/}
```
[Answer]
# Python, 319 bytes
```
def f(A):
L,R,S=len,range,A.split('\n')
if L(S[0])%2:S=[s+' 'for s in S]
m=L(S[0])
if L(S)%2:S+=[' '*m]
C=[chr(int(sum(map(ord,[S[i][j],S[i+1][j],S[i][j+1],S[i+1][j+1]]))/4.0+0.5))for i in R(0,L(S),2)for j in R(0,m,2)]
f=t='';i=0
while i<L(C):
t+=C[i]*2
i+=1
if i%(m/2)<1:f+=(t+'\n')*2;t=''
f=f[:-1]
print f
```
2nd indentation is tabs.
Stuff before `C` is padding, `C` is the averaging process to single letters and rest is output
[Answer]
## R, ~~433~~ 399 bytes
```
y=scan(,'',sep="\n")
h=nchar(y[1])
v=length(y)
p=function(x)paste(x,collapse="")
if(h%%2){y=sapply(y,function(x)paste0(x," "));h=h+1}
if(v%%2){y=c(y,p(rep(" ",h)));v=v+1}
z=matrix(unlist(lapply(y,function(x)strtoi(charToRaw(x),16))),ncol=h,byrow=T)
a=array(,c(v,h))
for(i in 1:(v/2)){for(j in 1:(h/2)){r=2*i-1:0;s=2*j-1:0;a[r,s]=rawToChar(as.raw(floor(mean(z[r,s])+.5)))}}
cat(apply(a,1,p),sep="\n")
```
I am getting desperate because this thing seems to be non-competing as heck. It prints
```
$$>>II99######
$$>>II99######
$$##88KKGG####
$$##88KKGG####
```
for the test case.
If you feed in the 7×3
```
%%%%%%%
Example
%%%%%%%
```
the output will be
```
BBFFJJ33
BBFFJJ33
######!!
######!!
```
because of the divisibility by 2 etc. etc.
Ungolfed:
```
y <- scan(, '', sep="\n") # Read STDIN and make it a character vector
h <- nchar(y[1]) # Get line width: how many chars per line
v <- length(y) # Get array height: how many lines
p <- function(x) paste(x, collapse="") # A function that merges a vector of strings
if (h%%2) {y <- sapply(y, function(x) paste0(x, " ")); h=h+1} # If height is odd, add an empty line
if (v%%2) {y <- c(y, p(rep(" ", h))); v=v+1} # If width is odd, add an empty column
z <- matrix(unlist(lapply(y, function(x) strtoi(charToRaw(x), 16))), ncol=h, byrow=T)
# z now stores ASCII codes in a matrix; analogous to C strtol
a <- array(, dim=c(v,h)) # Reserve an array for the final result
for (i in 1:(v/2)) {
for(j in 1:(h/2)) {
r <- 2*i - 1:0 # Range of rows to average
s <- 2*j - 1:0 # Range of columns to average
a[r, s] <- rawToChar(as.raw(floor(mean(z[r, s]) + .5))) # Average, round, convert the ASCII codes
} # and write them to the same place as in the original array
}
cat(apply(a, 1 , p), sep="\n") # Prints the array row-wise (index 1 for rows)
```
Just look how it handles this one gorgeous example (courtesy of chris.com):
```
M$$$$$$$$$$$$$$$$RMMMMM8MMX
<$$$$$$$$$$$$R????!!?MMMR$RMMh.
:M$$$$$$$R?!!~~~~!!!!!!!MMM$$$$X
:M$$$$$$$X!~~~ ~~~~~!!MM8$MM$$M!
:!XM$$$$$$R!~~~~~ ~~~~~!!M$$$$$$$R!
<!XM$$$$$$MR!~~~~ ~~ ~:!!<:!M$$$$$$$!
'<!XMBQQRMMMMX:::~~~<!?!!~~!!!!$$$M!$X
~!!MM$$$$$M8R!!!?!:~!!M$f?!~~~!M$8HXX?
<!!!XMM$$$$$MMRM$$!~!~~~~~~~~~~~!XM?!!M!
<!!!!XMM$$M$$MM$M!!~~~ ~~~ ~ :~!!!X!~~R!
!!!!XMMM$MMMMMMMM!!~~~ ~~~~ ~~~!!!X~~X!~
'~~!!MMMM@MMMX!!MM!:~!!!~~ `~~~~!!XXXX~
~!!!XMMMMMMMM!MMM!~~~~:: <<~~~~!!$$R!
'!!!!MM888M$MXMMM!!!!()!!~~~~~<!X$$$>
~!!!M???M$MRRMM$X<~!!!!~~~~~:!XN$$M
~!!!!!M$$$$@$@$$!!~~' ~~:XH8$$$WR
!!!!MM$RM$RRMMMM?t!:::XX8$$$$$$$$>
~~!!MMM$$$$$WX!!!!!!$$$$$$$RR$$$R"
' <!!MT!!!~~~!#BX!!!~~?T#?!!!M$$$X.
<!!!!~~~~~~~~~?$!!!~~~~~~:!M$$$$MXH:
~~~~~~~~~~~ ~~!M&!!!~~~<!!X$$$$$$$R$W>
<~~~~~~~~ '~~!$!!!!!!!!MMRM$R?#!!$N!
x~~~~~~~~~ ~~~!MX!!!!!!?!M!M!~~:!!$B!
M!~~~~~~~~~~ <~~:!$R!!!!!!!X!!!~~!!~!RR!
:M!~~~~~~~~~~~ `~~~!X$R!!!!!!!!~~~:!!~~tMM!
dR!!~~~~~~~~~~~~~~~~!M$R!!!!!!!~!!!!!!~~@$@~
tR!!!~~~~~~~~~~~~~~~!!M$R!!!!!!!!!!!!!~~!$$E~
d!~~~~~~~~~~~~~~~~~~~!!$$X!!!!!!!!!!!!~~~X$$!~
8R~~~~~~~~~~~~~~~~~~~<!X$$!!!!!!!!!!!<~~~!MR$~~
8$~~~~~~~!~~~~~~~~~~~<!!$$R!!!MX!!!!~~~~~<XR$!~<
:$$!~~~~~~!!~~~~~~~~~~~!!M$$!!!!MM!!!~~~~~<!8$F~<!
.x8$$$!~~~~::!~~~~~~~~~~~!!X$$$!!!!MM!!~~~~~!!M$R~~~!
.::xxxnHW8$$$$$$$$$$$$$$!!~~~~~~~~~~<!@$$X!!!!MM~~~~~<!!X$E~~~~!
:t$$$$$$$$$$$$$$$$$$$$$$$$$$$!!~~~~~~~~~~!X$$$X~!!!MX~~~~~!!X$$~~~~!!
~~~~#R$$$$$RR8$$$$$$$$$$$$$$$$$$!!~~~~~~~~~<!M$$$B~!!!M!~~~~~!X$$!~~~~!!
~~~~~~~~?$$$$$$$$$$$$$$$$$$$$$$$$$!!~~~~~~~~~!!$$$$$X!!X$!~~~~!X$$R~~~~<!f
:~~~~~~~~~`~?$$$$$$$$$$$$$$$$$$$$$$$$!!~~~~~~~~!!X$$$$$$X!M$~~~<!W$$R~~~~~!!
~~~~~~~~~~ ~~M$$$$$$$$$$$$$$$$$$$$$$$!!~~~~~~~~!!M$$$$$$$$$Bid$$$$$$!~~~~~!!
!~~~~~~~~~~~~~~~$$$$$$$$$$$$$$$$$$$$$$$!~~~~~~~~~!!$$$$$$$$$$$$$$$$$$!~~~~~~!~
!~~~~~~~~~~~~~~~M$$$$$$$$$$$$$$$$$$$$$$!:~~~~~~~<!X$$$$$$$$$$$$$$$$$!~~~~~~!!
~~~~~~~~~~~~~~!!!$$$$$$$$$$$$$$$$$$$$$R!!:~~~~~~!!M$$$$$$$$$$$$$$"XR~~~~~~~!!
~~~~~~~~~~~~~!!!!$$$$$$$$$$$$$$$$$$$$$R!<!~~~~~!!!X$$$$$$$$$$$P~ !~~~~~~~!!
~~~~~~~~~~~<!!!!!$$$$$$$$$$$$$$$$$$$$$X!!~~~~~<!!!@#""` ~~~~~~~~!!
~~~~~~~~~~~!!!!!X$$$$$$$$$$$$$$$$$$$$$X!~~~~~~!!! '~~~~~~~!!
~~~~~~~~~~~<!!!!M$$$$$$$$$$$$$$$$$$$$$X!~~~~~!!!f '~~~~~~<!!
~~~~~~~~~~~~~!!!$$$$$$$$$$$$$$$$$$$$$R!~~~~~~!!! '~~~~~<!!>
~~~~~~~~~~~~~~!!M$$$$$$$$$$$$$$$$$$$" !~~~~~!!!! ~~~~~~!!!
~~~~~~~~~~~~~~!!!$$$$$$$$$$$$$$$$$R~ .!~~~~~!!! ~~~~~!!!!
~~~~~~~~~~~~~~~!!!$$$$$$$$$$$$$*?!!!~!!~~~~<!!~ ~~~~!!!!!
~~~~~~~~~~~~~~~~!!!$$$$$$$$*"~!!!!!!!!!~~~~!!! <~~~:!!!!!
!~~~~~~~~~~~~~~~~!!M$$$$#~~~~~~~~~~~!!~~~~~!! ~~~~~~~!!!
!<~~~~~~~~~~~~~~~!!!R"~~~~~~~~~~~~~!!!~~~~<!! '~~~~~~<!!
!<~~~~~~~~~~~~~~~~!!!~~~~~~~~~~~~~~!!~~~~~!!!X: ~~~~~~~!!~
!!~~~~~~~~~~~~~~~~!!!!~~~~~~~~~~~~<!!~~~~!!!9$MX: ~~~~~~<!!
!!!!!~~~~~~~~~~~~~!!!!:~~~~~~~~~~~!!~~~~~!!X$$$X!~ '~~~~~~!!~
!!!!!!~~~~~~~~~~~<!!!!!!~~~~~~~~~~!!~~~~!!!M$$R!~~~~ ~~~~~~!!!
!!!!!!!<~~~~~~~~~~~!!!!!!!:<:~~~~~!!~~~~!!X$$R!~~~~~~ ~~~~~~!!
!!!!!!!!~~~~~~~~~~<!!!!!!!!!!!!!<!!!~~~~!!@$$!~~~~~~~~ ~~~~~!!~
!!!!!!!!!~~~~~~~~:<!!!!X!!!!!!!!!!!!~~~!!X$$!~~~~~~~~~~~~: '~~~~~!!
'!!!!!!!!!!~~~~~~~!!!!!!?!!!!!!!!!!!~~<!!M$M!~~~~~~~~~~~~~~~ '~~~~~!~
!!!!!!!!!!\~~~~~~~>!!!! `"MMMHX!!~~~<!!$R!~~~~~~~~~~~~~~~~~<~~~~!!
!!!!!!!!!!<~~~~~<!!!!! .::<!!!!<~~!!X8X!~~~~~~~~~~~~~~~~~~~~~~!!
`X!!!!!!!!~~~~~!<!!!!!!!!!!!!~~!!\~~!!M$MX!:~~~~~~~~~~~~~~~~<!~~!>
!X!!!!!!!!~!!:!!!!!!!!!!~!!!:~~!!~~~!!$M!~~!!<~~~~~~~~~~~~~~~!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!:!!~~:!9R!~~~~~~!~~~~~~~~~~~~~~<!!f
'CHAT!!!!!!!!!!!!!!!!!!!!!!!!!!!!~~~!!MX~~~~~~~~~~~~~~~~~~~~~~!!X
```
After:
```
''..$$$$$$$$$$662266??MMIIDDEE66
''..$$$$$$$$$$662266??MMIIDDEE66
''>>$$$$$$<<WWOOOOggPP88,,HH99..;;
''>>$$$$$$<<WWOOOOggPP88,,HH99..;;
..HH..$$$$EEPP~~ggOOggVV??22..$$$$00!!
..HH..$$$$EEPP~~ggOOggVV??22..$$$$00!!
99((PP77;;CCII5555VVVV4433WWPP88..<<==66
99((PP77;;CCII5555VVVV4433WWPP88..<<==66
..!!==MM$$..99DD8899gggg~~ggOOmm88HH@@PP!!
..!!==MM$$..99DD8899gggg~~ggOOmm88HH@@PP!!
::88EEMM@@MMPP77BB??gg88~~88__~~88==kkTT88
::88EEMM@@MMPP77BB??gg88~~88__~~88==kkTT88
::!!EEHHCCCCEEMM77PPQQ00??nn~~??0000((
::!!EEHHCCCCEEMM77PPQQ00??nn~~??0000((
8888,,00??..BB@@11??PP""ggmmVV55//GG
8888,,00??..BB@@11??PP""ggmmVV55//GG
8888,,MM00..HHEE77==((//>>));;$$00))
8888,,MM00..HHEE77==((//>>));;$$00))
""''((,,\\PP~~ggII00!!~~ddXX''88$$;;<<''
""''((,,\\PP~~ggII00!!~~ddXX''88$$;;<<''
VV~~~~~~ggOO99gg..!!88PP((EE::00++..;;((
VV~~~~~~ggOO99gg..!!88PP((EE::00++..;;((
BB~~~~~~~~gg VVmm--;;!!!!))::,,gg??88CC!!
BB~~~~~~~~gg VVmm--;;!!!!))::,,gg??88CC!!
11??PP~~~~~~~~~~__~~PP;;::!!!!!!PPPP''PPll@@88
11??PP~~~~~~~~~~__~~PP;;::!!!!!!PPPP''PPll@@88
11YYPPgg~~~~~~~~~~~~~~!!..;;!!!!!!!!!!88~~00,,OO
11YYPPgg~~~~~~~~~~~~~~!!..;;!!!!!!!!!!88~~00,,OO
&&KK~~~~~~gg~~~~~~~~~~FF0000!!,,//!!88VV~~MMEEPP??
&&KK~~~~~~gg~~~~~~~~~~FF0000!!,,//!!88VV~~MMEEPP??
::..$$PP~~mm??gg~~~~~~~~gg//..##!!777788~~~~??33OOnn!!
::..$$PP~~mm??gg~~~~~~~~gg//..##!!777788~~~~??33OOnn!!
<<""&&//NNLL::))$$$$$$$$$$$$##PP~~~~~~~~VV77$$TT!!77hh~~~~((==CC~~gg!!
<<""&&//NNLL::))$$$$$$$$$$$$##PP~~~~~~~~VV77$$TT!!77hh~~~~((==CC~~gg!!
88gg~~ggMM$$$$;;))$$$$$$$$$$$$$$$$##PP~~~~~~~~((..$$OO!!;;PP~~gg==00gg~~??22
88gg~~ggMM$$$$;;))$$$$$$$$$$$$$$$$##PP~~~~~~~~((..$$OO!!;;PP~~gg==00gg~~??22
88mm~~~~~~gg__LL$$$$$$$$$$$$$$$$$$$$$$##PP~~~~~~PP::$$$$$$0066rrAA00$$\\~~~~!!
88mm~~~~~~gg__LL$$$$$$$$$$$$$$$$$$$$$$##PP~~~~~~PP::$$$$$$0066rrAA00$$\\~~~~!!
PP~~~~~~~~~~~~~~..$$$$$$$$$$$$$$$$$$$$##mm~~~~~~??00$$$$$$$$$$$$$$$$99~~~~gg88
PP~~~~~~~~~~~~~~..$$$$$$$$$$$$$$$$$$$$##mm~~~~~~??00$$$$$$$$$$$$$$$$99~~~~gg88
~~~~~~~~~~~~gg!!##$$$$$$$$$$$$$$$$$$$$::..~~~~gg!!;;$$$$$$$$$$FF""RR~~~~~~88
~~~~~~~~~~~~gg!!##$$$$$$$$$$$$$$$$$$$$::..~~~~gg!!;;$$$$$$$$$$FF""RR~~~~~~88
~~~~~~~~~~VV!!!!00$$$$$$$$$$$$$$$$$$$$==gg~~~~((!!))!!00 ""~~~~~~gg!!
~~~~~~~~~~VV!!!!00$$$$$$$$$$$$$$$$$$$$==gg~~~~((!!))!!00 ""~~~~~~gg!!
~~~~~~~~~~nn88!!..$$$$$$$$$$$$$$$$$$00FF~~~~PP!!22 $$~~~~nn((((
~~~~~~~~~~nn88!!..$$$$$$$$$$$$$$$$$$00FF~~~~PP!!22 $$~~~~nn((((
~~~~~~~~~~~~~~!!..$$$$$$$$$$$$$$$$FF$$PP~~~~!!!! OO~~~~88!!
~~~~~~~~~~~~~~!!..$$$$$$$$$$$$$$$$FF$$PP~~~~!!!! OO~~~~88!!
~~~~~~~~~~~~~~gg!!##$$$$$$&&::$$))!!88PP~~VV!!88 VV~~??!!!!
~~~~~~~~~~~~~~gg!!##$$$$$$&&::$$))!!88PP~~VV!!88 VV~~??!!!!
??~~~~~~~~~~~~~~PP,,//QQgg~~~~~~~~gg!!~~~~??!! ""~~~~~~??!!
??~~~~~~~~~~~~~~PP,,//QQgg~~~~~~~~gg!!~~~~??!! ""~~~~~~??!!
((~~~~~~~~~~~~~~~~!!88~~~~~~~~~~~~??PP~~gg!!66@@'' OO~~~~nn!!88
((~~~~~~~~~~~~~~~~!!88~~~~~~~~~~~~??PP~~gg!!66@@'' OO~~~~nn!!88
!!!!88~~~~~~~~~~nn!!!!??~~~~~~~~~~!!~~~~88::$$<<ggOO hh~~~~8888
!!!!88~~~~~~~~~~nn!!!!??~~~~~~~~~~!!~~~~88::$$<<ggOO hh~~~~8888
!!!!!!((~~~~~~~~~~??!!!!!!..??PPVV!!~~~~!!88//gg~~~~gg ~~~~gg88
!!!!!!((~~~~~~~~~~??!!!!!!..??PPVV!!~~~~!!88//gg~~~~gg ~~~~gg88
##!!!!!!88gg~~~~mm((!!//))!!!!!!!!!!~~??::..PP~~~~~~~~~~mmOO$$~~~~PP88
##!!!!!!88gg~~~~mm((!!//))!!!!!!!!!!~~??::..PP~~~~~~~~~~mmOO$$~~~~PP88
!!!!!!!!00nn~~~~FF!!!! 44DD==//??~~((55;;~~~~~~~~~~~~~~~~nn~~~~!!
!!!!!!!!00nn~~~~FF!!!! 44DD==//??~~((55;;~~~~~~~~~~~~~~~~nn~~~~!!
LL!!!!!!!!ggVV88((!!!!!!88!!VVPPGG~~!!99QQ??VV~~~~~~~~~~~~~~??PP((
LL!!!!!!!!ggVV88((!!!!!!88!!VVPPGG~~!!99QQ??VV~~~~~~~~~~~~~~??PP((
""3366!!!!!!!!!!!!!!!!!!!!!!!!!!''ggVV22RR~~~~~~gg~~~~~~~~~~~~VV//22
""3366!!!!!!!!!!!!!!!!!!!!!!!!!!''ggVV22RR~~~~~~gg~~~~~~~~~~~~VV//22
```
[Answer]
# Ruby, ~~180~~ ~~158~~ ~~148~~ ~~128 + 4~~ 124 + 4 = 128 bytes
Run with `$ ruby -nl` (+4 bytes for `-nl` flags). Takes input on STDIN.
```
y,x=x,$_.scan(/..?/)
(puts [x.zip(y).map{|c|(("%2s"*2%c).bytes.reduce(:+)/4.0).round.chr*2}*""]*2
y,x=x,[])if$.%2<1||$<.eof?
```
See it on ideone: <http://ideone.com/brmP3L>
## Ungolfed & explanation
Per `man ruby`, the `-n` flag "[c]auses Ruby to assume the following loop around your script ... `while gets ... end`". The special variable `$_` contains the last line read by `gets`. The `-l` flag removes the `\n` from each line, equivalent to `$_.chop!`.
```
y, x = x, $_.scan(/..?/)
( puts [
x.zip(y).map {|c|
(("%2s" * 2 % c).bytes.reduce(:+) / 4.0).round.chr * 2
} * ""
] * 2
y, x = x, []
) if $. % 2 < 1 || $<.eof?
```
The special variable `$.` is the number of lines that have been read so far, and `$<` is STDIN. The pairs of characters from every second line gets zipped with the previous line's. The format string `%2s%2s` combines the characters and pads it with spaces, then the characters are averaged.
] |
[Question]
[
I'm a [teacher](https://en.wikipedia.org/wiki/Suspension_of_disbelief "because I'm not really one"), and in a few days I have to give my students a test. Now, I'm always worried about my loveliest students being hurt by the least loveliest ones when they cheat, so I want to randomize the tests so no one can cheat off of anyone.
Right now, I have my tests saved in this format:
```
When was Java invented?
Why does this matter?
1941
War was beginning
None of the above
What is the increment operator in Java?
Stack Overflow>how 2 incrememnt
Google>how 2 incrememnt
increment
++
```
That is, the questions are separated by a single blank line, and the answers are all preceded by two spaces. This is the output I need:
```
What is the increment operator in Java?
++
increment
Google>how 2 incrememnt
Stack Overflow>how 2 incrememnt
When was Java invented?
War was beginning
1941
Why does this matter?
None of the above
```
That is, each answer on a question in a random order, and the question order randomized as well. Keep in mind that if the answer choice is "None of the above", it should stay at the bottom. Every question always has exactly four answers, and "None of the above" only ever appears as the last answer choice -- and never appears as a substring of an answer choice that is not "None of the above". Unfortunately, I can't rewrite all of my tests, so you'll have to take them in that format. Also, my students have to be able to read it, so I can't really take output any other way (except as described below).
I don't need it to be perfectly random. As long as it's close.
[Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are banned.
---
### Bonus
Now, my students are used to that plain format, but if you can make it look like this...
```
1. What is the increment operator in Java?
A. ++
B. increment
C. Google>how 2 incrememnt
D. Stack Overflow>how 2 incrememnt
2. When was Java invented?
A. War was beginning
B. 1941
C. Why does this matter?
D. None of the above
```
I'll take 25% off of your final score. You'll get input the same way, though.
That is, if you number the questions and label the answers. Please keep in mind that questions should start at 1, and the answers are from A to D.
---
NB: The examples are different from the ones in the answers because I changed them after the fact. The specific examples aren't the point anyway; answers had to work with any arbitrary question(s).
[Answer]
# Pyth - ~~48~~ ~~42~~ ~~41~~ 39 bytes
Will packed string.
```
js.Sm++hd/D"None of the above".Stdkc.zk
```
[Try it online here](http://pyth.herokuapp.com/?code=js.Sm%2B%2Bhd%2FD%22None+of+the+above%22.Stdkc.zk&input=What+is+the+capital+of+France%3F%0A++F%0A++Nice%0A++46%0A++None+of+the+above%0A%0AWhen+was+the+War+of+1812%3F%0A++1821%0A++1776%0A++1812%0A++1812.5&debug=0).
[Answer]
# JavaScript ES6, 170 bytes
Is an anonymous function, name it. Note: this uses the random sort method, which isn't [entirely random](https://stackoverflow.com/a/18650169/4119004), but is sufficient, provided you aren't a probability teacher.
```
t=>t.split`
`.map(x=>(x=x.split`
`,R=[],(k=x.pop())==" None of the above"?(R=[k]):x.push(k),[x.shift(),...x.sort(r=_=>.5-Math.random()),...R].join`
`)).sort(r).join`
`
```
### With the bonus, 180.75 bytes
```
t=>t.split`
`.map(x=>(x=x.split`
`,R=[],(k=x.pop())==" None of the above"?(R=[k]):x.push(k),[x.shift(),...x.sort(r=_=>.5-Math.random()),...R].map((k,i)=>(i?` ${" ABCD"[i]}. `:"")+k.trim()).join`
`),a=0).sort(r).map(e=>++a+". "+e).join`
`
```
## Test it out!
```
F=t=>t.split`
`.map(x=>(x=x.split`
`,R=[],(k=x.pop())==" None of the above"?(R=[k]):x.push(k),[x.shift(),...x.sort(r=_=>.5-Math.random()),...R].join`
`)).sort(r).join`
`;
g.onclick=function(){o.innerHTML = ""; o.appendChild(document.createTextNode(F(i.value)));}
g.click();
```
```
textarea{width:100%;height:14em;}textarea,div,button{font-family:Consolas,monospace;white-space:pre;}
```
```
<textarea id=i>When was the War of 1812?
1812.5
1776
1812
1821
What is the capital of France?
46
F
Nice
None of the above
What is the square root of -1 (simplified)?
i
i don't know
square root of -1
wait this is a math test?</textarea><button id=g>go →</button><div id=o></div>
```
[Answer]
## CJam, ~~54~~ ~~53~~ ~~55~~ 52 bytes
Saved 1 byte from using a later release (avaliable on TIO). Gained 2 bytes because I forgot to randomize order of questions. Saved 2 bytes from yet another bug fixed on TIO.
```
qNN+/mr{N/(\mr_" None of the above"#3e\N*N\++}%NN+*
```
[Try it online!](http://cjam.tryitonline.net/#code=cU5OKy9tcntOLyhcbXJfIiAgTm9uZSBvZiB0aGUgYWJvdmUiIzNlXE4qTlwrK30lTk4rKg&input=V2hhdCBpcyB0aGUgY2FwaXRhbCBvZiBGcmFuY2U_CiAgRgogIE5pY2UKICA0NgogIE5vbmUgb2YgdGhlIGFib3ZlCgpXaGVuIHdhcyB0aGUgV2FyIG9mIDE4MTI_CiAgMTgyMQogIDE3NzYKICAxODEyCiAgMTgxMi41)
] |
[Question]
[
## Four integer sequences
In this challenge, you will test four different properties of a positive integer, given by the following sequences.
A positive integer **N** is
1. *perfect* ([OEIS A000396](https://oeis.org/A000396)), if the sum of proper divisors of **N** equals **N**. The sequence begins with 6, 28, 496, 8128, 33550336, 8589869056, 137438691328, 2305843008139952128...
2. *refactorable* ([OEIS A033950](https://oeis.org/A033950)), if the number of divisors of **N** is a divisor of **N**. The sequence begins with 1, 2, 8, 9, 12, 18, 24, 36, 40, 56, 60, 72, 80, 84, 88, 96, 104, 108, 128...
3. *practical* ([OEIS A005153](https://oeis.org/A005153)), if every integer **1 ≤ K ≤ N** is a sum of some distinct divisors of **N**. The sequence begins with 1, 2, 4, 6, 8, 12, 16, 18, 20, 24, 28, 30, 32, 36, 40, 42, 48, 54, 56...
4. *highly composite* ([OEIS A002128](https://oeis.org/A002182)), if every number **1 ≤ K < N** has strictly fewer divisors than **N**. The sequence begins with 1, 2, 4, 6, 12, 24, 36, 48, 60, 120, 180, 240, 360, 720, 840, 1260, 1680, 2520, 5040...
## Four programs
Your task is to write four programs (meaning full programs, function definitions or anonymous functions that perform I/O by any of the [standard methods](https://codegolf.meta.stackexchange.com/q/2447/32014)).
Each program shall solve the membership problem of one of these sequences.
In other words, each program will take a positive integer **N ≥ 1** as input, and output a truthy value if **N** is in the sequence, and a falsy value if not.
You can assume that **N** is within the bounds of the standard integer type of your programming language.
The programs must be related in the following way.
There are four strings `ABCD` such that
1. `AC` is the program that recognizes perfect numbers.
2. `AD` is the program that recognizes refactorable numbers.
3. `BC` is the program that recognizes practical numbers.
4. `BD` is the program that recognizes highly composite numbers.
## Scoring
Your score is the total length (in bytes) of the strings `ABCD`, or in other words, the total byte count of the four programs divided by two.
The lowest score in each programming language is the winner.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply.
For example, if the four strings are `a{`, `b{n`, `+n}` and `=n}?`, then the four programs are `a{+n}`, `a{=n}?`, `b{n+n}` and `b{n=n}?`, and the score is 2+3+3+4=12.
[Answer]
## JavaScript (ES6), 46 + 55 + 6 + 36 = ~~282~~ ~~274~~ ... ~~158~~ 143 bytes
A:
```
n=>(r=0,D=x=>x&&D(x-1,n%x||(r++?q-=x:q=n)))(n)
```
B:
```
n=>(q=(g=D=x=>x&&!(n%x||(g|=m>2*(m=x),0))+D(x-1))(m=n))
```
C:
```
?!g:!q
```
D:
```
?(P=k=>--k?D(n=k)<q&P(k):1)(n):n%r<1
```
The result is 4 anonymous functions which give truthy/falsy values for their respective inputs (`AC`, `AD`, and `BC` give `true`/`false`, `BD` gives `1`/`0`).
### Test snippet
```
let AC =
n=>(r=0,D=x=>x&&D(x-1,n%x||(r++?q-=x:q=n)))(n)
?!g:!q
let AD =
n=>(r=0,D=x=>x&&D(x-1,n%x||(r++?q-=x:q=n)))(n)
?(P=k=>--k?D(n=k)<q&P(k):1)(n):n%r<1
let BC =
n=>(q=(g=D=x=>x&&!(n%x||(g|=m>2*(m=x),0))+D(x-1))(m=n))
?!g:!q
let BD =
n=>(q=(g=D=x=>x&&!(n%x||(g|=m>2*(m=x),0))+D(x-1))(m=n))
?(P=k=>--k?D(n=k)<q&P(k):1)(n):n%r<1
let update = n => O.innerText = [
'perfect: ' + AC(n),
'refactorable: ' + AD(n),
'practical: ' + BC(n),
'highly composite: ' + BD(n)
].join("\n")
```
```
<input type=number value=1 min=1 oninput=update(this.value)>
<pre id=O></pre>
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 + 17 + ~~2~~ 1 + 2 = ~~29~~ 28 bytes
A:
```
Æṣ⁼$Ædḍ$
```
B:
```
ÆDŒPS€QṢwRµṖÆdṀ<Ʋ
```
C:
```
ƭ
```
D:
```
0?
```
For practical numbers (BC), `0` is falsy and any other result is truthy.
AC and BC are full programs, since they're not reusable as functions.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 + 16 + 1 + 0 = 25 bytes
A: `ѨO©QI®Ö`
B: `ÑæOILåPILÑ€gRć‹P`
C: `s`
D:
The long parts each calculate both values, `s` swaps to the first one.
```
Ñ # push list of divisors
© # store this list
¨ # remove the last (largest) value
O # take the sum
Q # is this equal to the input (perfect)
I # push the input
® # push the stored divisor list
g # take the length
Ö # does it divide the input? (refactorable)
(s)# (swap to perfect)
```
[Try *perfect* online!](https://tio.run/##yy9OTMpM/f//8MRDKw@t8A/0PLQu/fC04v//DS0A "05AB1E – Try It Online") or [Try *refactorable* online!](https://tio.run/##yy9OTMpM/f//8MRDKw@t8A/0PLQu/fC0//8NLQA "05AB1E – Try It Online")
```
ÑæOILåP # practical?
Ñ # push list of divisors
æ # take the powerset
O # sum of each subset
IL # push the range [1..input]
å # is each value in the sums of divisor-subsets?
P # take the product / boolean all
ILÑ€gRć‹P # highly composite?
IL # push the range [1..input]
Ñ # take the divisors of each integer
€g # take the length of each divisor list
R # reverse it (swap the input's to the front)
ć # push the first value seperately
‹ # is this larger
P # than all other values?
(s) # (swap to practical)
```
[Try *practical* online!](https://tio.run/##yy9OTMpM/f//8MTDy/w9fQ4vDQASEx81rUkPOtL@qGFnQPH//4YWAA "05AB1E – Try It Online") or [Try *highly composite* online](https://tio.run/##yy9OTMpM/f//8MTDy/w9fQ4vDQASEx81rUkPOtL@qGFnwP//hhYA "05AB1E – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 + 17 + 3 + 3 = 28 bytes
There's already a 28-byte Jelly answer, but I have a different approach, so why not add it too?
## Parts
The pilcrow `¶` represents a newline.
A: `S=¶ḍ¶` (5 bytes)
B: `ŒP§iⱮḶ}Ạ¶>ḶÆd$}Ạ¶` (17 bytes)
C: `ÆḌñ` (3 bytes)
D: `Ædç` (3 bytes)
## Perfect (8 bytes)
```
S=
ḍ
ÆḌñ
```
[Try it online!](https://tio.run/##y0rNyan8/z/Yluvhjl6uw20Pd/Qc3vj//38zAA "Jelly – Try It Online")
### Explanation
```
S= Auxiliary dyadic link
S Sum of items in left argument
= Equals right argument?
ḍ Ignored
ÆḌñ Main monadic link
ÆḌ Proper divisors
ñ Apply next link, with the number as right argument
```
## Refactorable (8 bytes)
```
S=
ḍ
Ædç
```
[Try it online!](https://tio.run/##y0rNyan8/z/Yluvhjl6uw20ph5f////fyAIA "Jelly – Try It Online")
### Explanation
```
S= Ignored
ḍ Auxiliary dyadic link: Divides?
Ædç Main monadic link
Æd Number of divisors
ç Apply previous link, with the number as right argument
```
## Practical (20 bytes)
```
ŒP§iⱮḶ}Ạ
>ḶÆd$}Ạ
ÆḌñ
```
[Try it online!](https://tio.run/##y0rNyan8///opIBDyzMfbVz3cMe22oe7FnDZARmH21JUwJzDbQ939Bze@P//f3MA "Jelly – Try It Online")
### Explanation
```
ŒP§iⱮḶ}Ạ Auxiliary dyadic link
ŒP Power set
§ Sum of each
iⱮ Find index of each item from
Ḷ} Lowered range [0..(right argument - 1)]
Ạ All?
>ḶÆd$}Ạ Ignored
ÆḌñ Main monadic link
ÆḌ Proper divisors
ñ Apply next link, with the number as right argument
```
## Highly composite (20 bytes)
```
ŒP§iⱮḶ}Ạ
>ḶÆd$}Ạ
Ædç
```
[Try it online!](https://tio.run/##y0rNyan8///opIBDyzMfbVz3cMe22oe7FnDZARmH21JUwBwg4/Dy////WwAA "Jelly – Try It Online")
### Explanation
```
ŒP§iⱮḶ}Ạ Ignored
>ḶÆd$}Ạ Auxiliary dyadic link
> Greater than?
$ (
Ḷ } Lowered range [0..(right argument - 1)]
Æd Number of divisors [of each]
$ )
Ạ All?
Ædç Main monadic link
Æd Number of divisors
ç Apply previous link, with the number as right argument
```
[Answer]
# [Haskell](https://www.haskell.org/), 69 + 133 + 3 + 3 = score 208
A:
```
d n=filter((<1).mod n)[1..n]
f n=[sum(d n)-n==n,length(d n)`elem`d n]
```
B:
```
import Data.List
d n=filter((<1).mod n)[1..n]
f n=[all(\n->any(==n)$sum$subsequences$d n)[1..n],all((<length(d n)).length.d)[1..n-1]]
```
C:
```
!!0
```
D:
```
!!1
```
[Try it online!](https://tio.run/##rU@7DsIwDNzzFanUIZWaiDBWFAnoyB9AJQJNISIxpQkDQnx7cal4jAwMlnxn@@58UP6ore1unM4yUlHIa2ODbhmbyES4EzLJSgoBJalxuPIXx3qOQ55DajXsw@FJbLTVboNdSfidENSbZ8S45tQGWqigxNL48IOBspatgU8VXBlaJDE6Ym29Pl807LSPPxdpv8wmXykSMQBRDStclu88i4xE0eiFih5JRN1fnkblzikDNKdNayDQmNZUjrsH "Haskell – Try It Online")
Yeah, it's pretty cheap but I'm not smart enough for a cooler solution. :P
] |
[Question]
[
A fun pair of equivalences is *1 + 5 = 2 · 3* and *1 · 5 = 2 + 3*. There are many like these, another one is *1 + 1 + 8 = 1 · 2 · 5* and *1 · 1 · 8 = 1 + 2 + 5*. In general a product of *n* positive integers equals a sum of *n* positive integers, and vice versa.
In this challenge you must generate all such combinations of positive integers **for an input *n > 1***, excluding permutations. You can output these in any reasonable format. For example, all the possible solutions for *n = 3* are:
```
(2, 2, 2) (1, 1, 6)
(1, 2, 3) (1, 2, 3)
(1, 3, 3) (1, 1, 7)
(1, 2, 5) (1, 1, 8)
```
The program that can generate the most combinations for the highest *n* in one minute on my **2GB RAM**, 64-bit Intel Ubuntu laptop wins. If your answer uses more than 2GB of RAM or is written in a language I can not test with freely available software, I will not score your answer. I will test the answers in two weeks time from now and choose the winner. Later non-competing answers can still be posted of course.
Since it's not known what the full sets of solutions for all *n* are, you are allowed to post answers that generate incomplete solutions. However if another answer generates a (more) complete solution, **even if their maximum *n* is smaller**, that answer wins.
---
# To clarify, here's the scoring process to decide the winner:
1. I will test your program with n=2, n=3, etc... I store all your outputs and stop when your program takes more than a minute or more than 2GB RAM. Each time the program is run for a given input n, it will be terminated if it takes more than 1 minute.
2. I look at all the results for all programs for n = 2. If a program produced less valid solutions than another, that program is eliminated.
3. Repeat step 2 for n=3, n=4, etc... The last program standing wins.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), n = 50000000 with 6499 results in 59 s
To avoid producing over a terabyte of output consisting almost entirely of 1s, a sequence of (say) 49999995 1s is abbreviated as `1x49999995`.
```
#include <stdio.h>
#include <stdlib.h>
static int n, *a1, k1 = 0, *a2, k2 = 0, s1, p1, *factor;
static void out() {
if (s1 == p1) {
for (int i = 0; i < k1 && i < k2; i++) {
if (a1[i] < a2[i])
return;
else if (a1[i] > a2[i])
break;
}
}
for (int i = 0; i < k1; i++)
printf("%d ", a1[i]);
printf("1x%d | ", n - k1);
for (int i = 0; i < k2; i++)
printf("%d ", a2[i]);
printf("1x%d\n", n - k2);
}
static void gen2(int p, int s, int m);
static void gen3(int p, int s, int m, int x, int q) {
int r = s - n + k2 + 2;
int d = factor[q];
do {
if (x * d <= m)
x *= d;
q /= d;
} while (q % d == 0);
do {
if (q == 1) {
a2[k2++] = x;
gen2(p / x, s - x, x);
k2--;
} else {
gen3(p, s, m, x, q);
}
if (x % d != 0)
break;
x /= d;
} while (p / (x * q) >= r - x * q);
}
static void gen2(int p, int s, int m) {
int n2 = n - k2;
if (p == 1) {
if (s == n2)
out();
} else if (n2 >= 1 && m > 1) {
int r = s - n2 + 1;
if (r < 2 || p < r)
return;
if (m > r)
m = r;
if (factor[p] <= m)
gen3(p, s, m, 1, p);
}
}
static void gen1(int p, int s, int m) {
int n1 = n - k1;
p1 = p;
s1 = s + n1;
gen2(s1, p1, s + n1 + 1 - n);
if (n1 != 0) {
int *p1 = &a1[k1++];
for (int x = 2; x <= m && p * x <= s + x + n1 - 1; x++) {
*p1 = x;
gen1(p * x, s + x, x);
}
k1--;
}
}
int main(int argc, char **argv) {
if (argc < 2)
return 1;
n = atoi(argv[1]);
if (n < 2)
return 1;
a1 = malloc(n * sizeof(int));
a2 = malloc(n * sizeof(int));
factor = calloc(4 * n - 1, sizeof(int));
for (int p = 2; p < 4 * n - 1; p++)
if (factor[p] == 0) {
factor[p] = p;
for (int i = p; i <= (4 * n - 2) / p; i++)
factor[p * i] = p;
} else if (factor[p] < factor[p / factor[p]]) {
factor[p] = factor[p / factor[p]];
}
gen1(1, 0, 3 * n - 1);
return 0;
}
```
[Try it online!](https://tio.run/##jVXbUtswEH3PV2zpwMR2UrDomwm/0A@geRC@BE0c27EN9RT49aZntZbtkPTCDCNr92i1e86uEi83cXw4fDZFnD8nKd01bWLKL0/3syNTbh7ZNmta3ZqYTNFSsSBfhwvahrSiG94obJRsGjgq/PuZjtuyjoaTL6VJqHxu5x69zohMRvMGAVZAi4UoK2ua8w2GY0VY7viSqyv5UrAEgQNLCB0@mDWcWmH1egdRnbbPdRH1@zRv0gn6/iP6sU71VsDvM/6f/SkXycAiqxrebH5xmdDFgmxkj2M4e9jB88a@gpY4ap1no6o/R1Xnon4vXFAF3/sxw5u0UPaGamHFamTZedEJ7vYcTpZOln2vFT5rJNzgzoIC1jogFfWeBB4R@2G/ZmNS9hIx5R35QNytkEHPNywrSoTuPV333@/048nkKc33dMkhQY93EmzP9nDsAPCzVUGwRgadE9sSUNE118AJY@k859yq5bIXWrridTx1OwcVoAEU4MzeGxvCVcKJfeLEZid9050WwjnY8sHi/QoELkl2/6/ZwH7B0yWSR/3wVEdc2HFiS6FcdnbWJKNhABAHqdiR2mEOxuNThVndMBrC1uhRRW9vVOGjdtGnE8YoDjc4dwhVj76@O6r1UR8cU87PhmR7hp3wH@yEjh2bdsXbir/4gUFNARC8tTy7B0rMXCrX7DlaYbIST4jxbcArjPg2RLNFx29VBx8muLO1MbEVRLY7vqGTW5YglLrp4yVBp10bzu1JyWzStdKB21A619Jj69emsAnoehMvKH7SNfk@Ni/jA8suVk8oF8lE2gKX67Y0DHl5CNdj/efxmrPd6TwvY0B8aszPtMz4fs8e1ervfmkBYGLBfAWGFWMhPkIds5Uwy203wLF1T@VxZ60mornrrF064eTnpbKP74qGTJSHea0mT/E0DjBmEmsyUZPeHtHXYwLr80mdhY5623YAN/hBvXWlW3J6TW74DTkcDuGN/fsVZ7neNIflt0w37W8 "C (gcc) – Try It Online")
[Answer]
# Mathematica, n=293 with 12 solutions
OP changed the challenge and asks for input
Here is the new code that takes any n as input
For n=293 you get the 12 solutions
```
If[#<5,Union[Sort/@Select[Tuples[{1,2,3,4,5,6,7,8,9},{#}],Tr@#==Times@@#&]],For[a=1,a<3,a++,For[b=a,b<3,b++,For[c=b,c<5,c++,For[d=c,d<10,d++,For[e=d,e<300,e++,If[Tr[s=Join[Table[1,#-5],{a,b,c,d,e}]]==Times@@s,Print[s]]]]]]]]&
```
**input**
>
> [n]
>
>
>
You can test this algorithm on [Wolfram Sandbox](https://sandbox.open.wolframcloud.com/app/objects/) which is an online **freely available software**
Just follow the link, paste the code (ctrl+v),**paste input at the end of the code** and press shift+enter to run.
You will get all my solutions in seconds
Here is also [Try it online!](https://tio.run/##bc9NbsIwEAXgfU7xRBeG2JUIFVJUh/Yi3Ti2QY6KQSSsUM6evpi/VCKbmeSbebHt8fi@s3YY3kK0v2fnUYVD25282X9l2bkNcYdo9r49GuvRdk5nWYgd9ibE@eKSAeObUagVrIJT8Pr2MSg0nAa2h9PcYINCw6DCB4uUC0KSmmI06qvUN0lkSbWGJa1Z7pTM0ayGoxVL1gcm9VSn4cfQJdk/mYfb8jiSf5SMloyQHJRYlSU2PAtyUk7KSTl8uuX9GcMDw5kZGL5iYfR0ArCHc4eqgrgI/Q/G5ea63IzLZcmG64@NWaFm@mWWSYFKjKWe9HbSu0nvX8eIPimv8A3xEwU@ISAW0@E@e3b9MPwB "C++ (gcc) – Try It Online") in C++(gcc)
(Many thanks to @ThePirateBay for supporting and translating my code to a free language)
this program generates only solutions of the form {a,b,c}{a,b,c}
which means a+b+c=a\*b\*c
**It takes 1 sec to compute**
the twelve solutions are:
>
> {1,1...,1,1,1,2,293} {1,1...,1,1,1,2,293}
>
> {1,1...,1,1,1,3,147} {1,1...,1,1,1,3,147}
>
> {1,1...,1,1,1,5,74} {1,1...,1,1,1,5,74}
>
> {1,1...,1,1,2,2,98} {1,1...,1,1,2,2,98}
>
> {1,1...,1,1,2,3,59} {1,1...,1,1,2,3,59}
>
> {1,1...,1,1,2,5,33} {1,1...,1,1,2,5,33}
>
> {1,1...,1,1,2,7,23} {1,1...,1,1,2,7,23}
>
> {1,1...,1,1,2,8,20} {1,1...,1,1,2,8,20}
>
> {1,1...,1,1,3,3,37} {1,1...,1,1,3,3,37}
>
> {1,1...,1,1,3,4,27} {1,1...,1,1,3,4,27}
>
> {1,1...,1,1,3,7,15} {1,1...,1,1,3,7,15}
>
> {1,1...,1,2,2,6,13} {1,1...,1,2,2,6,13}
>
>
>
[Answer]
# [Python 2](https://docs.python.org/2/), n=175, 28 results in 59s
Made it a little slower using a reduction factor 2, but gets more solutions starting with n=83
I get results for n up to 92 on TIO in a single run.
```
def submats(n, r):
if n == r:
return [[]]
elif r > 6:
base = 1
else:
base = 2
mx = max(base, int(n*2**(1-r)))
mats = []
subs = submats(n, r+1)
for m in subs:
if m:
mn = m[-1]
else:
mn = 1
for i in range(mn, mx + 1):
if i * mn < 3*n:
mats += [m + [i]]
return mats
def mats(n):
subs = []
for sub in submats(n, 0):
sum = 0
prod = 1
for m in sub:
sum += m
prod *= m
if prod > n and prod < n*3:
subs += [[sub, sum, prod]]
return subs
def sols(n):
mat = mats(n)
sol = [
[[1]*(n-1)+[3*n-1],[1]*(n-2)+[2,2*n-1]],
]
if n > 2:
sol += [[[1]*(n-1)+[2*n+1],[1]*(n-2)+[3,n]]]
for first in mat:
for second in mat:
if first[2] == second[1] and first[1] == second[2] and [second[0], first[0]] not in sol:
sol += [[first[0], second[0]]];
return sol
```
[Try it online!](https://tio.run/##bVTtiuMwDPyfpxBdFuzEgTiF@9Hb9kWMCek1vTXETrFT2H36nvzRJN5eoSWWRtLMWOnte/6cTPu42knDrPQASt8mO4fnx2W4grufdT87YhhYeigAP@oKBo5HsPHoP3aY79aAEFKG2DAiyMIJfq2Yc@8GOAJPADe8pNoQ0F/4qPsv4qMMlJmJKduyJLy2lNIigpATwkQchyT9acu14jSkrpMFjU0CZp2I9PR6Ch2NHytqLpdwTnIB8SXkmyvf3Pbm70A0Dkb2FXCal@E0BaWv/oB9afLkIqdCPRqrhUouJld9sij8ZUR1qXkSnSzwVDCSlD5taDZE3F0jvFnONztdXtQ8rcop@lJkp7NgqC@3UZQZgifcj95c4uEDTLn/2e4c1Qp8Yr47C9hctkdF2W4aV9koLexHcCIaMY3eh2WEEFyWxNScVgLdxhtlKdJipGVtiEkWCuS60idoN25h00Bx0wwLq7zZnhkp1wu4Kutm7yDSO2S@uuHPhI78TKXZoU600r9VEYkzgoUxw7eZNmZEOjaSJVQjJZgpzEf2r0u2SHrCGSw9pPydeT@ND@TVdabXQ9f56buu070yXbc7FP/Z/ZbxZrv2bu6tvyj/R0LoGj6Gy1R0s4b4hsPu/QL1CfCX4NfRHbwDUQzGwRBHWWoDdexLi7e83D2K4h8 "Python 2 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), n=12 gets 6 solutions
At least on TIO, usual results for 1 up to 11
```
->n{
arr=[*1..n*3].product(*(0..n-2).map{|x|
[*1..[n/3**x,2].max]|[1]
}).select{|a|
a.count(1) >= n-4
}.map(&:sort).uniq
arr.product(arr).map(&:sort).uniq.select{|r|
r[0].reduce(&:+) == r[1].reduce(&:*) &&
r[0].reduce(&:*) == r[1].reduce(&:+)
}
}
```
[Try it online!](https://tio.run/##bY/NCoMwEITvPsWexETdGu2pEF8k5GBtBKGNNipYf57dRgUp1Nsy@@3sjOnun6XgS5jq0QHIjOGCMkRNE4m1qR5d3nrUi6wSxgRfWT1O/WRJgI0T@pJQ2gextLteToJJu5wJNuqp8nacsh3OMK863XqMQMpBh9eVWu0899ZUpiXY6fK9Jzj@2pn8MYez2Z2NiCQaZQ@U5XwCnFuN/WiUgOuesPSE9ckazJkXwbZKW90aBl6IXgYDNuWg5uUL "Ruby – Try It Online")
Gets 10 results under a minute for n=13 on my laptop.
[Answer]
# Mathematica, n=19 with 11 solutions
this is my new answer according to OP's new criteria
```
(SOL = {};
For[a = 1, a < 3, a++,
For[b = a, b < 3, b++,
For[c = b, c < 5, c++,
For[d = c, d < 6, d++,
For[e = d, e < 3#, e++,
For[k = 1, k < 3, k++,
For[l = k, l < 3, l++,
For[m = l, m < 5, m++,
For[n = m, n < 6, n++, For[o = n, o < 3#, o++,
s = Join[Table[1, # - 5], {a, b, c, d, e}];
t = Join[Table[1, # - 5], {k, l, m, n, o}];
If[Tr[s[[-# ;;]]] == Times @@ t[[-# ;;]] &&
Tr[t[[-# ;;]]] == Times @@ s[[-# ;;]],
AppendTo[SOL,{s[[-#;;]],t[[-#;;]]}]]]]]]]]]]]];
Union[SortBy[#,Last]&/@SOL])&
```
if you give an input [n] at the end, the program displays the solutions
here are my results (on my old laptop 64-bit 2.4GHz)
>
> n->solutions
>
> 2 -> 2
>
> 3 -> 4
>
> 4 -> 3
>
> 5 -> 5
>
> 6 -> 4
>
> 7 -> 6
>
> 8 -> 5
>
> 9 -> 7
>
> 10 -> 7
>
> 11 -> 8
>
> 12 -> 6 (in 17 sec)
>
> 13 -> 10 (in 20 sec)
>
> 14 -> 7 (in 25 sec)
>
> 15 -> 7 (in 29 sec)
>
> 16 -> 9 (in 34 sec)
>
> 17 -> 10 (in 39 sec)
>
> 18 -> 9 (in 45 sec)
>
> 19 -> 11 (in 51 sec)
>
>
>
>
[Answer]
## Haskell, a lot of solutions fast
```
import System.Environment
pr n v = prh n v v
prh 1 v l = [ [v] | v<=l ]
prh n 1 _ = [ take n $ repeat 1 ]
prh _ _ 1 = []
prh n v l = [ d:r | d <-[2..l], v `mod` d == 0, r <- prh (n-1) (v`div`d) d ]
wo n v = [ (c,k) | c <- pr n v, let s = sum c, s>=v,
k <- pr n s, sum k == v, s>v || c>=k ]
f n = concatMap (wo n) [n+1..3*n]
main = do [ inp ] <- getArgs
let results = zip [1..] $ f (read inp)
mapM_ (\(n,s) -> putStrLn $ (show n) ++ ": " ++ (show s)) results
```
`f` computes the solutions, the `main` function adds getting the input from the command line and some formatting and counting.
[Answer]
# [Haskell](https://www.haskell.org/), n=10 with 2 solutions
```
import Data.List
removeDups = foldl' (\seen x -> if x `elem` seen then seen else x : seen) []
removeDups' = foldl' (\seen x -> if x `elem` seen then seen else x : seen) []
f n= removeDups $ map sort filterSums
where maxNumber = 4
func x y = if (((fst x) == (fst.snd$y)) && ((fst y) == (fst.snd$x)))
then [(snd.snd$x),(snd.snd$y)]
else [[],[]]
pOf = removeDups' $ (map sort (mapM (const [1..maxNumber]) [1..n]))
sumOf = map (\x->((sum x),((product x), x))) pOf
filterSums = filter (\x-> not$(x == [[],[]])) (funcsumOfsumOf)
```
This performs like crap, but I at least fixed it so I am actually addressing the challenge now!
[Try it online!](https://tio.run/##rVG7boMwFN35ijugxK4S1EqdqsCUsY@hI7EUGmwF1Q9kmxa@nl6blFApYz3Y93nuOdfnyn1yKcexUa2xHq5nX/kqe26cTxLLlfni@651kIMwspZrIAfHuYYetgU0At8jl1wdIUb9Ga9ocek4Jp@iR6FkC7D1P6AlAnQOC4IpqKoFF7SIRnpu3zvlEoDvM7ccc/1rpz64xdGPya9U0ekTwg4YxOGEEOE89BTyHIKZOV2nA6WwWsGUG/7mekppArdOpF4SLLoUbmZ7oOx2TxRZlmxTsmtF@yZgqXONQsmsNFgvQE5GI7nyIctmnYxGX7MFQ9epiBbayaHfFoRgCAI50lpTd6egfgNBVhh83dO80PBz0ZkAQBufkj4s5UIcO0lY6y4t4rjd3fTSZFRVo7G/NgF3In6Q26K1jfapABkY37PxBw "Haskell – Try It Online")
[Answer]
# Axiom, n=83 in 59 seconds here
```
-- copy the below text in the file name "thisfile.input"
-- and give something as the command below in the Axiom window:
-- )read C:\Users\thisuser\thisdirectory\thisfile
)cl all
)time on
-- controlla che l'array a e' formato da elementi a.i<=a.(i+1)
tv(a:List PI):Boolean==(for i in 1..#a-1 repeat if a.i> a.(i+1) then return false;true)
-- funzione incremento: incrementa a, con #a=n=b/3,sotto la regola di "reduce(+,a)+#a-1>=reduce(*,a)"
-- e che n<reduce(*,a)<3*n ed reduce(+,a)<3*n
inc3(a:List PI):INT==
i:=1; n:=#a; b:=3*n
repeat
if i>n then return 0
x:=reduce(*,a)
if x>=b then a.i:=1
else
y:=reduce(+,a)
if y>b then a.i=1
else if y+n-1>=x then
x:=x quo a.i
a.i:=a.i+1
x:=x*a.i
if tv(a) then break
else a.i:=1
else a.i:=1
i:=i+1
if x<=n then return inc3(a) -- x<=n non va
x
-- ritorna una lista di liste di 4 divisori di n
-- tali che il loro prodotto e' n
g4(n:PI):List List PI==
a:=divisors(n)
r:List List PI:=[]
for i in 1..#a repeat
for j in i..#a repeat
x:=a.i*a.j
if x*a.j>n then break
for k in j..#a repeat
y:=x*a.k
if y*a.k>n then break
for h in k..#a repeat
z:=y*a.h
if z=n then r:=cons([a.h,a.k,a.j,a.i],r)
if z>=n then break
r
-- ritorna una lista di liste di 3 divisori di n
-- tali che il loro prodotto e' n
g(n:PI):List List PI==
a:=divisors(n)
r:List List PI:=[]
for i in 1..#a repeat
for j in i..#a repeat
x:=a.i*a.j
if x*a.j>n then break
for k in j..#a repeat
y:=x*a.k
if y=n then r:=cons([a.k,a.j,a.i],r)
if y>=n then break
r
-- cerca che [a,b] nn si trovi gia' in r
searchr(r:List List List PI,a:List PI,b:List PI):Boolean==
aa:=sort(a); bb:=sort(b)
for i in 1..#r repeat
x:=sort(r.i.1);y:=sort(r.i.2)
if x=aa and y=bb then return false
if x=bb and y=aa then return false
true
-- input n:PI
-- ritorna r, tale che se [a,b] in r
-- allora #a=#b=n
-- ed reduce(+,a)=reduce(*,b) ed reduce(+,b)=reduce(*,a)
f(n:PI):List List List PI==
n>100000 or n<=1 =>[]
a:List PI:=[]; b:List PI:=[]; r:List List List PI:=[]
for i in 1..n repeat(a:=cons(1,a);b:=cons(1,b))
if n~=72 and n<86 then m:=min(3,n)
else m:=min(4,n)
q:=reduce(*,a)
repeat
w:=reduce(+,a)
if n~=72 and n<86 then x:= g(w)
else x:=g4(w)
if q=w then r:=cons([copy a, copy a],r)
for i in 1..#x repeat
for j in 1..m repeat
b.j:=(x.i).j
-- per costruzione abbiamo che reduce(+,a)= prodotto dei b.i=reduce(*,b)
-- manca solo di controllare che reduce(+,b)=reduce(*,a)=q
if reduce(+,b)=q and searchr(r,a,b) then r:=cons([copy a, copy b],r)
q:=inc3(a)
if q=0 then break
r
```
results:
```
for i in 2..83 repeat output [i, # f(i)]
[2,2][3,4][4,3][5,5][6,4][7,6][8,5][9,7][10,7][11,8][12,6][13,10][14,7][15,7]
[16,10][17,10][18,9][19,12][20,7][21,13][22,9][23,14][24,7][25,13][26,11]
[27,10][28,11][29,15][30,9][31,16][32,11][33,17][34,9][35,9][36,13][37,19]
[38,11][39,14][40,12][41,17][42,11][43,20][44,12][45,16][46,14][47,14][48,13]
[49,16][50,14][51,17][52,11][53,20][54,15][55,17]
[56,14][57,20][58,17][59,16][60,15][61,28][62,15][63,16][64,17][65,18]
[66,14][67,23][68,20][69,19][70,13][71,18][72,15][73,30][74,15][75,17][76,18]
[77,25][78,16][79,27][80,9][81,23][82,17][83,26]
f 3
[[[1,2,5],[8,1,1]],[[1,3,3],[7,1,1]],[[1,2,3],[1,2,3]],[[2,2,2],[6,1,1]]]
Type: List List List PositiveInteger
Time: 0.07 (IN) + 0.05 (OT) = 0.12 sec
```
The way for run above text in Axiom, would be, copy all that text in a file, save the file with the name: Name.input, in a Axiom window use ")read absolutepath/Name".
results: (# f(i) finds the length of the array f(i), that is the number of solutions)
] |
[Question]
[
A set of `n` positive numbers has `2^n` subsets. We'll call a set "nice" if none of those subsets have the same sum. `{2, 4, 5, 8}` is one such nice set. Since none of the subsets has the same sum, we can sort the subsets by sum:
`[{}, {2}, {4}, {5}, {2, 4}, {2, 5}, {8}, {4, 5}, {2, 8}, {2, 4, 5}, {4, 8}, {5, 8}, {2, 4, 8}, {2, 5, 8}, {4, 5, 8}, {2, 4, 5, 8}]`
If we label the numbers `[2, 4, 5, 8]` with the symbols `[a, b, c, d]` in increasing order, we get the following abstract ordering:
`[{}, {a}, {b}, {c}, {a, b}, {a, c}, {d}, {b, c}, {a, d}, {a, b, c}, {b, d}, {c, d}, {a, b, d}, {a, c, d}, {b, c, d}, {a, b, c, d}]`
Another nice set of positive numbers can have the same abstract ordering, or a different one. For instance, `[3, 4, 8, 10]` is a nice set with a different abstract ordering:
`[{}, {a}, {b}, {a, b}, {c}, {d}, {a, c}, {b, c}, {a, d}, {b, d}, {a, b, c}, {a, b, d}, {c, d}, {a, c, d}, {b, c, d}, {a, b, c, d}]`
In this challenge, you must count the number of distinct abstract orderings of nice sets of `n` positive numbers. This sequence is [OEIS A009997](https://oeis.org/A009997), and the known values, starting at `n=1`, are:
```
1, 1, 2, 14, 516, 124187, 214580603
```
For instance, for `n=3`, the following are the two possible abstract orderings:
```
[{}, {a}, {b}, {c}, {a, b}, {a, c}, {b, c}, {a, b, c}]
[{}, {a}, {b}, {a, b}, {c}, {a, c}, {b, c}, {a, b, c}]
```
For `n=4`, the following are the 14 possible abstract orderings, plus an example nice set with that ordering:
```
[{}, {a}, {b}, {a, b}, {c}, {a, c}, {b, c}, {a, b, c}, {d}, {a, d}, {b, d}, {a, b, d}, {c, d}, {a, c, d}, {b, c, d}, {a, b, c, d}], [8, 4, 2, 1]
[{}, {a}, {b}, {a, b}, {c}, {a, c}, {b, c}, {d}, {a, b, c}, {a, d}, {b, d}, {a, b, d}, {c, d}, {a, c, d}, {b, c, d}, {a, b, c, d}], [10, 6, 3, 2]
[{}, {a}, {b}, {a, b}, {c}, {a, c}, {d}, {b, c}, {a, d}, {a, b, c}, {b, d}, {a, b, d}, {c, d}, {a, c, d}, {b, c, d}, {a, b, c, d}], [10, 7, 4, 2]
[{}, {a}, {b}, {a, b}, {c}, {a, c}, {d}, {a, d}, {b, c}, {a, b, c}, {b, d}, {a, b, d}, {c, d}, {a, c, d}, {b, c, d}, {a, b, c, d}], [8, 6, 4, 1]
[{}, {a}, {b}, {a, b}, {c}, {d}, {a, c}, {b, c}, {a, d}, {b, d}, {a, b, c}, {a, b, d}, {c, d}, {a, c, d}, {b, c, d}, {a, b, c, d}], [10, 8, 4, 3]
[{}, {a}, {b}, {a, b}, {c}, {d}, {a, c}, {a, d}, {b, c}, {b, d}, {a, b, c}, {a, b, d}, {c, d}, {a, c, d}, {b, c, d}, {a, b, c, d}], [8, 7, 4, 2]
[{}, {a}, {b}, {c}, {a, b}, {a, c}, {b, c}, {a, b, c}, {d}, {a, d}, {b, d}, {c, d}, {a, b, d}, {a, c, d}, {b, c, d}, {a, b, c, d}], [10, 4, 3, 2]
[{}, {a}, {b}, {c}, {a, b}, {a, c}, {b, c}, {d}, {a, b, c}, {a, d}, {b, d}, {c, d}, {a, b, d}, {a, c, d}, {b, c, d}, {a, b, c, d}], [8, 4, 3, 2]
[{}, {a}, {b}, {c}, {a, b}, {a, c}, {d}, {b, c}, {a, d}, {a, b, c}, {b, d}, {c, d}, {a, b, d}, {a, c, d}, {b, c, d}, {a, b, c, d}], [8, 5, 4, 2]
[{}, {a}, {b}, {c}, {a, b}, {a, c}, {d}, {a, d}, {b, c}, {a, b, c}, {b, d}, {c, d}, {a, b, d}, {a, c, d}, {b, c, d}, {a, b, c, d}], [10, 7, 6, 2]
[{}, {a}, {b}, {c}, {a, b}, {d}, {a, c}, {b, c}, {a, d}, {b, d}, {a, b, c}, {c, d}, {a, b, d}, {a, c, d}, {b, c, d}, {a, b, c, d}], [8, 6, 4, 3]
[{}, {a}, {b}, {c}, {a, b}, {d}, {a, c}, {a, d}, {b, c}, {b, d}, {a, b, c}, {c, d}, {a, b, d}, {a, c, d}, {b, c, d}, {a, b, c, d}], [10, 8, 6, 3]
[{}, {a}, {b}, {c}, {d}, {a, b}, {a, c}, {b, c}, {a, d}, {b, d}, {c, d}, {a, b, c}, {a, b, d}, {a, c, d}, {b, c, d}, {a, b, c, d}], [8, 6, 5, 4]
[{}, {a}, {b}, {c}, {d}, {a, b}, {a, c}, {a, d}, {b, c}, {b, d}, {c, d}, {a, b, c}, {a, b, d}, {a, c, d}, {b, c, d}, {a, b, c, d}], [7, 6, 5, 3]
```
---
The following is not a valid abstract ordering:
`{}, {a}, {b}, {c}, {d}, {a,b}, {e}, {a,c}, {b,c}, {a,d}, {a,e}, {b,d}, {b,e}, {c,d}, {a,b,c}, {a,b,d}, {c,e}, {d,e}, {a,b,e}, {a,c,d}, {a,c,e}, {b,c,d}, {b,c,e}, {a,d,e}, {b,d,e}, {a,b,c,d}, {c,d,e}, {a,b,c,e}, {a,b,d,e}, {a,c,d,e}, {b,c,d,e}, {a,b,c,d,e}`
This ordering implies that:
```
d < a + b
b + c < a + d
a + e < b + d
a + b + d < c + e
```
Summing these inequalities gives:
```
2a + 2b + c + 2d + e < 2a + 2b + c + 2d + e
```
which is a contradiction. Your code must not count this ordering. Such counterexamples first appear at `n=5`. Example from [this paper](https://arxiv.org/pdf/math/9809134.pdf), example 2.5 on page 3.
This ordering is invalid despite the fact that `A < B` implies that `A U C < B U C`, for any `C` disjoint from `A` and `B`.
---
Your code or program must be fast enough that you can run it to completion on `n=4` before submitting it.
Submissions may be programs, functions, etc. as usual.
[Standard Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden, as always. This is code golf, so shortest answer in bytes wins. Feel free to ask clarifying questions in the comments.
[Answer]
# [Python 3](https://docs.python.org/3/) + SciPy, ~~396~~ ~~390~~ ~~385~~ ~~351~~ ~~336~~ 355 bytes
```
from scipy.optimize import*
n=int(input())
r=range(n)
def f(u):
s=linprog(r,u,[-n]*len(u),options={'tol':.1});c=s.success;y=sorted(range(c<<n),key=lambda a:s.x.round()@[a>>i&1for i in r])
for a,b in zip(y,y[1:]):
v=[(a>>i&1)-(b>>i&1)for i in r]
if~-(v in u):c+=f(u+[[-z for z in v]]);u+=v,
return+c
print(f([[(i==j-1)-(i==j)for i in r]for j in r]))
```
[Try it online!](https://tio.run/##TZDLboMwEEX3/gqvmnEwSFG7InHU/7BYEGNSJzC2/ECFqv11ipsusrt3Hmcebo4fFl/Xtfd2pEEZN1fWRTOaRVMzOuvjnqAwGMGgSxEYI174Fq8akJFO97SHxGpCgxi2Cm@v4HnissRmP2jccjzzLAbxtYt22NXV4ZsdlQhVSErpEI6zCNsY3cEDq04nZPyuZzG046VraVuH6rPyNmEH7F2257N5OfTWU0MNUt8wQrNr@SX7xTiY@SwPdZPXopOQ8GhhJVwe4ql5qzD9TwlTttshqhDbQYWU5fJHXXJ8ahp2TIWYOKFex@SxUMT5/JUepAQjxK3M/Cye6Vne/rdk6/r2Cw "Python 3 – Try It Online")
This now runs for *n* = 5 in about 5 seconds. The `if~-(v in u):` can be removed for −18 bytes but a huge performance penalty.
If you want to print all the abstract orderings as they’re found instead of just counting them, add `if c:print(s.x.round(),y)` before the `for` loop. (Subsets are represented by binary integers where each bit corresponds to the presence or absence of one element: {*a*, *c*, *d*} ↔ 1101₂ = 13.)
### How it works
`f` recursively counts the abstract orderings satisfying a given list of constraints. We start with the constraints *n* ≤ *a*, *a* + *n* ≤ *b*, *b* + *n* ≤ *c*, *c* + *n* ≤ *d*. Using linear programming, we find a solution to the constraints (or return 0 if there isn’t one)—in this case we get *a* = 4, *b* = 8, *c* = 12, *d* = 16. We round the solution to integers, then compute a reference ordering by sorting all its subsets by their sum:
{*a*}, {*b*}, {*c*}, {*a*, *b*}, {*d*}, {*a*, *c*}, {*a*, *d*}, {*b*, *c*}, {*b*, *d*}, {*a*, *b*, *c*}, {*c*, *d*}, {*a*, *b*, *d*}, {*a*, *c*, *d*}, {*b*, *c*, *d*}, {*a*, *b*, *c*, *d*}
The rounding can’t cause any constraints to be violated by more than *n*/2, which is why we added a margin of *n*.
Since Python’s `sorted` is stable, any ties between the subsets are broken in the same reverse-lexicographic order in which we generated them. So we could imagine replacing {*a*, *b*, *c*, *d*} with {*a*·2^*n* + 2^0, *b*·2^*n* + 2^1, *c*·2^*n* + 2^2, *d*·2^*n* + 2^3} to get the same ordering without any ties.
The plan is to categorize all other abstract orderings by case analysis based on where they *first* disagree with the reference ordering:
Either {*a*} > {*b*},
or {*a*} < {*b*} > {*c*},
or {*a*} < {*b*} < {*c*} > {*a*, *b*},
or {*a*} < {*b*} < {*c*} < {*a*, *b*} > {*d*},
⋮
Within each case, we add these new constraints with a margin of *n*, and recursively call `f` with the new constraints added.
### Notes
For a while I conjectured (but did not assume) that the linear program solutions with margin 1 on the constraints will always be integers. This turns out to be false: a counterexample with *n* = 7 is {2.5, 30, 62.5, 73.5, 82, 87.5, 99.5}.
# Python, 606 bytes (faster, no external libraries)
```
n=int(input())
r=range(n)
e=enumerate
def l(u,x):
for i,v in e(u):
for j,a in e(v):
if a<0:break
else:return[0]*len(x)
if sum(b*x[k]for k,b in e(v))>0:
x=l([[b*w[j]-a*w[k]for k,b in e(v)if k!=j]for w in u[:i]],x[:j]+x[j+1:]);x.insert(j,0)
for k,b in e(v):
if k!=j:x[j]+=b*x[k];x[k]*=-a
return x
def f(u,x):
x=l(u,x);c=any(x);y=sorted(range(c<<n),key=lambda a:sum(x[i]*(a>>i&1)for i in r))
for a,b in zip(y,y[1:]):
v=[(a>>i&1)-(b>>i&1)for i in r]+[1]
if~-(v in u):c+=f(u+[[-z for z in v[:-1]]+[1]],x);u+=v,
return+c
print(f([[(i==j-1)-(i==j)for i in r]+[1]for j in r],[1]*(n+1)))
```
[Try it online!](https://tio.run/##ZVLBcoMgEL37FfTSAcFOnPaEIT/CcECDLWqIg2Ixh/66BayX9ALsm923b98yrvPX3bxvm2HazFCb0c0QocwyK82nggZliinjbsrKWWVX1YIBOuIRzUB7t0CTBWgDFHQRSVBH5A4tCQK6BfJ8orVVsg@xGiZFrZqdNfwk8kEZ6FGW0iZ3g3XueS8iT0/qgwddTonKswFyXuffvBOFDNe/zMDSv7Auwd8RdJxqIYjntBPY8w6XVKDKv2kzKTvDjpxic/BEk7qBPzIaygRmu7IqHjkrZAb2IYBPrrSHK1FjfFYNk2YNs1Urm@52Vle4W9qczwaRXq1skLf6KoGkcXDPtcihvFz0a4mStVGMDbtI4uQu7qFHuJKVxymiyIXxo6aA9XOxwLwUydufAqZFhTU1mAWxmPPikZgfEV84LUqR8kUU7zBbyDEibrLRxu/RBvehZqwrYrv4eG6WPsAekhDm0OASIbRtH78 "Python 3 – Try It Online")
This runs for *n* = 5 in a quarter of a second, and *n* = 6 in 230 seconds (75 seconds in PyPy).
It includes a hand-coded linear programming solver using integer math in homogeneous coordinates to avoid floating point rounding issues.
[Answer]
# Ruby, 308 bytes, much faster
Runs the case 4 in ~150ms. No specialized library is used.
```
->n{t=2**(n-1)
n==0 ?[[0]]:P[n-1].map{|a|b=a.map{|i|i+t}
[*0..t].repeated_combination(t).select{|m|m[0]>=a.index(n-1)}.map{|m|c,d=a.dup,b.dup;m.reverse.map{|i|c.insert(i,d.pop)};c}}.flatten(1).select{|p|p.combination(2).all?{|(x,y)|x&~y==0||y&~x!=0&&n.times.all?{|i|x!=y<<i+1}&&p.index(x&~y)<p.index(y&~x)}}}
```
It recursively intersperse result of a minor case, for instance
>
> `[{}, {a}, {b}, {c}, {a, b}, {a, c}, {b, c}, {a, b, c}]`
>
>
>
with the corresponding subsets with an additional element added - they have to keep the same relative order. It also ensures that the new singleton is added after all the previous singletons.
The part that check for compliance is the same as before, but not the combinations to test are much much less.
Expanded and commented version:
```
->n{
t=2**(n-1)
if n==0
[[0]]
else
# for each one of the previous nice orderings
P[n-1].map { |a|
# create the missing sets, keep order
b = a.map{|i|i+t}
# intersperse the two sets
[*0..t].repeated_combination(t) # select t insertion points
.select do |m|
# ensure the new singleton is after the old ones
m[0] >= a.index(n-1)
end
.map do |m|
# do the interspersion
c,d=a.dup,b.dup
m.reverse.map{|i|c.insert(i, d.pop)}
c
end
}.flatten(1).select{ |p|
# check if the final ordering is still nice
p.combination(2).all? { |(x,y)|
(x&~y==0) ||
(y&~x!=0) &&
n.times.all?{|i|x!=y<<i+1} &&
(p.index(x&~y)<p.index(y&~x))
}
}
end
}
```
# Ruby, 151 bytes, quite slow
(the case of three elements takes << 1s, the case of four is still running)
```
->n{[*1...2**n-1].permutation.select{|p|p.combination(2).all?{|(x,y)|x&~y==0||y&~x!=0&&n.times.all?{|i|x!=y<<i+1}&&p.index(x&~y)<p.index(y&~x)}}.count}
```
It works on bitfield representation of the subsets, so one might have to massage the output if needed to display the subsets themselves.
formatted:
```
-> n {
[*1...2**n-1]. # prepare permutations of non-empty and non-full sets
permutation.
select { |p|
p.combination(2). # check all ordered pairs
all? { |(x, y)|
# first is subset of second
x &~ y == 0 ||
# second is not subset of first
y &~ x != 0 &&
# first is not a right shift of second
# (this normalizes the ordering on atoms)
n.times.all? { |i| x != y << i+1 } &&
# after taking out common elements, ordering agrees
p.index(x &~ y) < p.index(y &~ x)
}
}.
count
}
```
] |
[Question]
[
Using the the ten inferences of [the Natural Deduction System](https://en.wikipedia.org/wiki/Natural_deduction) prove [DeMorgan's laws](https://en.wikipedia.org/wiki/De_Morgan%27s_laws).
## The Rules of Natural Deduction
* Negation Introduction: `{(P → Q), (P → ¬Q)} ⊢ ¬P`
* Negation Elimination: `{(¬P → Q), (¬P → ¬Q)} ⊢ P`
* And Introduction: `{P, Q} ⊢ P ʌ Q`
* And Elimination: `P ʌ Q ⊢ {P, Q}`
* Or Introduction: `P ⊢ {(P ∨ Q),(Q ∨ P)}`
* Or Elimination: `{(P ∨ Q), (P → R), (Q → R)} ⊢ R`
* Iff Introduction: `{(P → Q), (Q → P)} ⊢ (P ≡ Q)`
* Iff Elimination: `(P ≡ Q) ⊢ {(P → Q), (Q → P)}`
* If Introduction: `(P ⊢ Q) ⊢ (P → Q)`
* If Elimination: `{(P → Q), P} ⊢ Q`
## Proof structure
Each statement in your proof must be the result of one of the ten rules applied to some previously derived propositions (no circular logic) or an assumption (described below). Each rule operates across some propositions on the left hand side of the `⊢` (logical consequence operator) and creates any number of propositions from the right hand side. The If Introduction works slightly differently from the rest of the operators (described in detail below). It operates across one statement that is the logical consequent of another.
### Example 1
You have the following statements:
`{(P → R), Q}`
You may use And Introduction to make:
`(P → R) ʌ Q`
### Example 2
You have the following statements:
`{(P → R), P}`
You may use If Elimination to make:
`R`
### Example 3
You have the following statements:
`(P ʌ Q)`
You may use And Elimination to make:
`P`
or to make:
`Q`
## Assumption Propagation
You may at any point assume any statement you wish. Any statement derived from these assumptions will be "reliant" on them. Statements will also be reliant on the assumptions their parent statements rely on. The only way to eliminate assumptions is by If Introduction. For If introduction you start with a Statement `Q` that is reliant on a statement `P` and end with `(P → Q)`. The new statement is reliant on every assumption `Q` relies on *except* for assumption `P`. Your final statement should rely on no assumptions.
## Specifics and scoring
You will construct one proof for each of DeMorgan's two laws using only the 10 inferences of the Natural Deduction Calculus.
The two rules are:
```
¬(P ∨ Q) ≡ ¬P ʌ ¬Q
¬(P ʌ Q) ≡ ¬P ∨ ¬Q
```
Your score is the number of inferences used plus the number of assumptions made. Your final statement should not rely on any assumptions (i.e. should be a theorem).
You are free to format your proof as you see fit.
You may carry over any Lemmas from one proof to another at no cost to score.
## Example Proof
I will prove that `(P and not(P)) implies Q`
(Each bullet point is +1 point)
* Assume `not (Q)`
* Assume `(P and not(P))`
* Using And Elim on `(P and not(P))` derive `{P, not(P)}`
* Use And Introduction on `P` and `not(Q)` to derive `(P and not(Q))`
* Use And Elim on the statement just derived to make `P`
The new `P` proposition is different from the other one we derive earlier. Namely it is reliant on the assumptions `not(Q)` and `(P and not(P))`. Whereas the original statement was reliant only on `(P and not(P))`. This allows us to do:
* If Introduction on `P` introducing `not(Q) implies P` (still reliant on the `(P and not(P))` assumption)
* Use And Introduction on `not(P)` and `not(Q)` (from step 3) to derive `(not(P) and not(Q))`
* Use And Elim on the statement just derived to make `not(P)`
(now reliant on `not(Q)`)
* If Introduction on the new `not(P)` introducing `not(Q) implies not(P)`
* We will now use negation elimination on `not(Q) implies not(P)` and `not(Q) implies P` to derive `Q`
This `Q` is reliant only on the assumption `(P and not(P))` so we can finish the proof with
* If Introduction on `Q` to derive `(P and not(P)) implies Q`
This proof scores a total of 11.
[Answer]
## Score: 81
Each line should be worth 1 point. The De Morgan's laws are found at statements (3) and (6). Labels in brackets denote the previous statement(s) a line depends on if they are not immediately preceding.
```
(a) assume P {
(aa) P ^ P
(ab) P
(ac) P v Q
} (a1) P -> P
(a2) P -> P v Q
(1) assume ~P ^ ~Q {
(1a) assume P v Q {
(1aa) assume Q {
(1aaa) assume ~P {
(1aaaa) Q ^ Q [1aa]
(1aaab) Q
(1aaac) ~Q [1]
} (1aaa1) ~P -> Q
(1aaa2) ~P -> ~Q
(1aab) P
} (1aa1) Q -> P
P [1a, a1, 1aa1]
~P [1]
} (1a1) P v Q -> P
(1a2) P v Q -> ~P
(1b) ~(P v Q)
} (11) ~P ^ ~Q -> ~(P v Q)
(2) assume ~(P v Q) {
(2a) ~(P v Q) ^ ~(P v Q)
(2b) assume P {
(2aa) ~(P v Q) [2a]
} (2b1) P -> ~(P v Q)
(2c) ~P [a2, 2b1]
(2d) assume Q {
(2da) ~(P v Q) [2a]
(2db) P v Q
} (2d1) Q -> ~(P v Q)
(2d2) Q -> P v Q
(2e) ~Q
(2f) ~P ^ ~Q
} (21) ~(P v Q) -> ~P ^ ~Q
(3) ~(P v Q) == ~P ^ ~Q [11, 21]
(4) assume ~P v ~Q {
(4a) assume ~P {
(4aa) assume P ^ Q {
(4aaa) P
(4aab) ~P ^ ~P [4a]
(4aac) ~P
} (4aa1) P ^ Q -> P
(4aa2) P ^ Q -> ~P
(4ab) ~(P ^ Q)
} (4a1) ~P -> ~(P ^ Q)
(4b) assume ~Q {
(4ba) assume P ^ Q {
(4baa) Q
(4bab) ~Q ^ ~Q [4b]
(4bac) ~Q
} (4ba1) P ^ Q -> Q
(4ba2) P ^ Q -> ~Q
(4bb) ~(P ^ Q)
} (4b1) ~P -> ~(P ^ Q)
(4c) ~(P ^ Q) [4, 4a1, 4b1]
} (41) ~P v ~Q -> ~(P ^ Q)
(5) assume ~(P ^ Q) {
(5a) assume ~(~P v ~Q) {
(5aa) ~(~P v ~Q) ^ ~(P ^ Q) [5, 5a]
(5ab) assume ~P {
(5aba) ~P v ~Q
(5abb) ~(~P v ~Q) [5aa]
} (5ab1) ~P -> ~P v ~Q
(5ab2) ~P -> ~(~P v ~Q)
(5ac) P
(5ad) assume ~Q {
(5ada) ~P v ~Q
(5adb) ~(~P v ~Q) [5aa]
} (5ad1) ~Q -> ~P v ~Q
(5ad2) ~Q -> ~(~P v ~Q)
(5ae) Q
(5af) P ^ Q [5ac, 5ae]
(5ag) ~(P ^ Q) [5aa]
} (5a1) ~(~P v ~Q) -> P ^ Q
(5a2) ~(~P v ~Q) -> ~(P ^ Q)
(5b) ~P v ~Q
} (51) ~(P ^ Q) -> ~P v ~Q
(6) ~(P ^ Q) == ~P v ~Q [41, 51]
```
[Answer]
# Score: 59
## Explanation
I'll use a tree like structure for the proof as I find this style quite readable. Each line is annotated by the count of used rules, for example the "Example 1" in the challenge would be represented as this tree (growing bottom to top):
[](https://i.stack.imgur.com/zV91c.png)
Note the unknown counts A,B and also the assumption Γ - so this is no theorem. To demonstrate how to prove a theorem, let us assume **A** and use an Or-introduction as follows:
[](https://i.stack.imgur.com/eSN0O.png)
Now this is still depending on the assumption **A** but we can derive a theorem by applying an If-introduction:
[](https://i.stack.imgur.com/5AoqX.png)
So we were able to derive the theorem ⊢ **A** → (**A** ∨ **B**) in a total of 3 steps (1 assumption & 2 applied rules).
With this we can go on to prove a few new rules that help us to prove DeMorgan's Laws.
## Additional Rules
Let's first derive the [Principle of Explosion](https://en.wikipedia.org/wiki/Principle_of_explosion) and denote it with **PE** in further proofs:
[](https://i.stack.imgur.com/JXDY1.png)
From this we derive another form of it: **A** ⊢ ¬**A** → **X** - we'll call it **CPE**:
[](https://i.stack.imgur.com/hD9if.png)
We'll need another one where the negated term (¬) is an assumption and refer to it as **CPE-**:
[](https://i.stack.imgur.com/n3quV.png)
From the two rules we just derived (**CPE** and **CPE-**), we can derive an important rule [Double Negation](https://en.wikipedia.org/wiki/Double_negation):
[](https://i.stack.imgur.com/ImOXO.png)
The next thing to do is to prove something like [Modus Tollens](https://en.wikipedia.org/wiki/Modus_tollens) - hence **MT**:
[](https://i.stack.imgur.com/FJrd2.png)
# Lemmas
## Lemma A
### Lemma A1
We'll need the following rule two times:
[](https://i.stack.imgur.com/i7nF7.png)
### Lemma A
By instantiating the just proved lemma twice we can show one direction of an equivalence, we will need it in the final proof:
[](https://i.stack.imgur.com/PZkWp.png)
## Lemma B
In order to show another direction, we'll need to do two times some quite repetitive stuff (for both arguments **A** and **B** in (**A** ∨ **B**)) - this means here I could possibly golf the proof further..
### Lemma B1'
[](https://i.stack.imgur.com/fwmgM.png)
### Lemma B1
[](https://i.stack.imgur.com/p4IQ5.png)
### Lemma B2'
[](https://i.stack.imgur.com/ZJtbg.png)
### Lemma B2
[](https://i.stack.imgur.com/RYXwM.png)
### Lemma B
Finally the conclusion of **B1** and **B2**:
[](https://i.stack.imgur.com/eGTkj.png)
## Actual proof
Once we proved these two statements:
* **Lemma A**: ⊢ (**A** ∨ **B**) → ¬(¬**A** ʌ ¬**B**)
* **Lemma B**: ⊢ ¬(**A** ∨ **B**) → (¬**A** ʌ ¬**B**)
We can prove the first equivalence (¬(**A** ∨ **B**) ≡ ¬**A** ʌ ¬**B**)) as follows:
[](https://i.stack.imgur.com/K2MJt.png)
And with the just proved rule together with Iff-Elimination we can prove the second equivalence too:
[](https://i.stack.imgur.com/sqbVP.png)
Not sure about the score - if I did it right, let me know if there's something wrong.
## Explanation
## Source
If somebody wants the tex source (needs [mathpartir](https://ctan.org/pkg/mathpartir?lang=en)):
```
In the following a rule \textbf{XYZ'} will denote the rule XYZ's second last
step, for example \textbf{PE'} will be $ A \land \lnot A \vdash X $.
\section*{Principle of Explosion [PE]}
\begin{mathpar}
\inferrule*[Left=$\to$-Intro,Right=10]
{\inferrule*[Left=$\lnot$-Elim,Right=9]
{\inferrule*[Left=$\to$-Intro,Right=4]
{\inferrule*[Left=$\land$-Elim,Right=3]
{\inferrule*[Left=Axiom,Right=2]
{ }
{ A \land \lnot A, \lnot X \vdash A \land \lnot A }
}
{ A \land \lnot A, \lnot X \vdash A }
}
{ A \land \lnot A \vdash \lnot X \to A } \\
\inferrule*[Right=$\to$-Intro,Left=4]
{\inferrule*[Right=$\land$-Elim,Left=3]
{\inferrule*[Right=Axiom,Left=2]
{ }
{ A \land \lnot A, \lnot X \vdash A \land \lnot A }
}
{ A \land \lnot A, \lnot X \vdash \lnot A }
}
{ A \land \lnot A \vdash \lnot X \to \lnot A }
}
{ A \land \lnot A \vdash X }
}
{ \vdash (A \land \lnot A) \to X }
\end{mathpar}
\section*{Conditioned PE [CPE]}
\begin{mathpar}
\inferrule*[Left=$\to$-Intro,Right=5]
{\inferrule*[Left=$\to$-Elim,Right=4]
{\inferrule*[Left=$\land$-Intro,Right=3]
{\inferrule*[Left=Axiom,Right=1]
{ } { A \vdash A } \\
\inferrule*[Right=Axiom,Left=1]
{ } { \lnot A \vdash \lnot A }
}
{ A, \lnot A \vdash A \land \lnot A } \\
\inferrule*[Right=PE,Left=0]
{ } { \vdash (A \land \lnot A) \to X }
}
{ A, \lnot A \vdash X }
}
{ A \vdash \lnot A \to X }
\end{mathpar}
to get \textbf{CPE$^-$}:
\begin{mathpar}
\inferrule*[Left=$\to$-Intro,Right=1]
{\inferrule*[Left=CPE',Right=0]
{ }
{ A, \lnot A \vdash X }
}
{ \lnot A \vdash A \to X }
\end{mathpar}
\section*{Double Negation [DN]}
\begin{mathpar}
\inferrule*[Left=$\equiv$-Intro,Right=5]
{\inferrule*[Left=$\to$-Intro,Right=2]
{\inferrule*[Left=$\lnot$-Elim,Right=1]
{\inferrule*[Left=CPE$^-$,Right=0]
{ }
{ \lnot\lnot A \vdash \lnot A \to X } \\
\inferrule*[Right=CPE$^-$,Left=0]
{ }
{ \lnot\lnot A \vdash \lnot A \to \lnot X }
}
{ \lnot\lnot A \vdash A }
}
{ \vdash \lnot\lnot A \to A } \\ \\ \\
\inferrule*[Left=$\to$-Intro,Right=2]
{\inferrule*[Left=$\lnot$-Intro,Right=1]
{\inferrule*[Left=CPE,Right=0]
{ }
{ A \vdash \lnot A \to X } \\
\inferrule*[Right=CPE,Left=0]
{ }
{ A \vdash \lnot A \to \lnot X }
}
{ A \vdash \lnot\lnot A }
}
{ \vdash A \to \lnot\lnot A }
}
{ \vdash \lnot\lnot A \equiv A }
\end{mathpar}
\section*{Modus Tollens [MT]}
\begin{mathpar}
\inferrule*[Left=$\to$-Intro,Right=6]
{\inferrule*[Left=$\lnot$-Intro,Right=5]
{\inferrule*[Left=Axiom,Right=1]
{ }
{ A \to \lnot B \vdash A \to \lnot B } \\
\inferrule*[Right=$\to$-Intro,Left=3]
{\inferrule*[Right=Axiom,Left=2]
{ }
{ A, B \vdash B }
}
{ B \vdash A \to B }
}
{ A \to \lnot B, B \vdash \lnot A }
}
{ A \to \lnot B \vdash B \to \lnot A }
\end{mathpar}
\section*{Lemma A}
\textbf{Lemma A1}:
\begin{mathpar}
\inferrule*[Left=$\to$-Intro,Right=9]
{\inferrule*[Left=$\lor$-Elim,Right=8]
{ \inferrule*[Left=CPE,Right=3]
{\inferrule*[Left=$\land$-Elim,Right=2]
{\inferrule*[Left=Axiom,Right=1]
{ }
{ A \land B \vdash A \land B }
}
{ A \land B \vdash B}
}
{ A \land B \vdash \lnot B \to X } \\
\inferrule*[Right=CPE,Left=3]
{\inferrule*[Right=$\land$-Elim,Left=2]
{\inferrule*[Right=Axiom,Left=1]
{ }
{ A \land B \vdash A \land B }
}
{ A \land B \vdash A }
}
{ A \land B \vdash \lnot A \to X } \\ \\ \\
\inferrule*[Right=Axiom,Left=1]
{ }
{ \lnot A \lor \lnot B \vdash \lnot A \lor \lnot B }
}
{ A \land B, \lnot A \lor \lnot B \vdash X }
}
{ \lnot A \lor \lnot B \vdash (A \land B) \to X }
\end{mathpar}
\textbf{Lemma A}:
```
[Answer]
# Score: 65
The de Morgan laws are line 30 and line 65.
(I haven't made any particular effort to golf this, for example to see if there are some repeated proofs that could be abstracted out at the beginning.)
```
1. assume ~(P\/Q)
2. assume P
3. P\/Q by or-introl, 2
4. P -> P\/Q by impl-intro, 2, 3
5. P -> ~(P\/Q) by impl-intro, 2, 1
6. ~P by neg-intro, 4, 5
7. assume Q
8. P\/Q by or-intror, 7
9. Q -> P\/Q by impl-intro, 7, 8
10. Q -> ~(P\/Q) by impl-intro, 7, 1
11. ~Q by neg-intro, 9, 10
12. ~P /\ ~Q by and-intro, 6, 11
13. ~(P\/Q) -> ~P/\~Q by impl-intro, 1, 12
14. assume ~P /\ ~Q
15. ~P, ~Q by and-elim, 14
16. assume P \/ Q
17. assume P
18. P -> P by impl-intro, 17, 17
19. assume Q
20. assume ~P
21. ~P -> Q by impl-intro, 20, 19
22. ~P -> ~Q by impl-intro, 20, 15
23. P by neg-elim, 21, 22
24. Q -> P by impl-intro, 19, 23
25. P by or-elim, 16, 18, 24
26. P\/Q -> P by impl-elim, 16, 25
27. P\/Q -> ~P by impl-elim, 16, 15
28. ~(P\/Q) by neg-intro, 26, 27
29. ~P/\~Q -> ~(P\/Q) by impl-intro, 14, 28
30. ~(P\/Q) <-> ~P/\~Q by iff-intro, 13, 29
31. assume ~(P/\Q)
32. assume ~(~P\/~Q)
33. assume ~P
34. ~P\/~Q by or-introl, 33
35. ~P -> ~P\/~Q by impl-intro, 33, 34
36. ~P -> ~(~P\/~Q) by impl-intro, 33, 32
37. P by neg-elim, 35, 36
38. assume ~Q
39. ~P\/~Q by or-intror, 38
40. ~Q -> ~P\/~Q by impl-intro, 38, 39
41. ~Q -> ~(~P\/~Q) by impl-intro, 38, 32
42. Q by neg-elim, 40, 41
43. P /\ Q by and-intro, 37, 42
44. ~(~P\/~Q) -> P /\ Q by impl-intro, 32, 43
45. ~(~P\/~Q) -> ~(P /\ Q) by impl-intro, 32, 31
46. ~P \/ ~Q by neg-elim, 44, 45
47. ~(P/\Q) -> ~P\/~Q by impl-intro, 31, 46
48. assume ~P\/~Q
49. assume ~P
50. assume P/\Q
51. P, Q by and-elim, 50
52. P/\Q -> P by impl-intro, 50, 51
53. P/\Q -> ~P by impl-intro, 50, 49
54. ~(P/\Q) by neg-intro, 52, 53
55. ~P -> ~(P/\Q) by impl-intro, 49, 54
56. assume ~Q
57. assume P/\Q
58. P, Q by and-elim, 57
59. P/\Q -> Q by impl-intro, 57, 58
60. P/\Q -> ~Q by impl-intro, 57, 56
61. ~(P/\Q) by neg-intro, 59, 60
62. ~Q -> ~(P/\Q) by impl-intro, 56, 61
63. ~(P/\Q) by or-elim, 48, 55, 62
64. ~P\/~Q -> ~(P/\Q) by impl-intro, 48, 63
65. ~(P/\Q) <-> ~P\/~Q by iff-intro, 47, 64
```
] |
[Question]
[
## Introduction
Let's define a *ternary function* as a function from the three-element set `S = {0,1,2}` to itself: it associates to each element of `S` another element of `S`.
One example of a ternary function `f` is
```
f(0) = 0; f(1) = 2; f(2) = 0
```
There are exactly 27 different ternary functions, and we represent them with integers from 0 to 26: a function `f` is encoded as `f(0) + 3*f(1) + 9*f(2)`.
The example function above is encoded as the number 6.
We can apply two ternary functions `f` and `g` in sequence, and if `f(g(k)) == g(f(k))` holds for all `k` in `S`, then the functions *commute*.
Your task is to verify whether this is the case.
## Input
Your inputs are two integers in the inclusive range from 0 to 26.
They represent two ternary functions `f` and `g`.
Input must be taken in decimal, binary or unary (string of `1`s) format.
## Output
Your output is a [truthy value](http://meta.codegolf.stackexchange.com/questions/2190/interpretation-of-truthy-falsey) if `f` and `g` commute, and a falsey value if they don't.
You may not assume that the inputs are ordered.
## Examples
Consider the inputs 5 and 16.
They encode the ternary functions
```
f(0) = 2; f(1) = 1; f(2) = 0
g(0) = 1; g(1) = 2; g(2) = 1
```
We have `f(g(1)) == f(2) == 0` and `g(f(1)) == g(1) == 2`, so `f` and `g` don't commute and the correct output is falsey.
On the other hand, the inputs 3 and 10 encode the ternary functions
```
f(0) = 0; f(1) = 1; f(2) = 0
g(0) = 1; g(1) = 0; g(2) = 1
```
and it can be verified that `f(g(k)) == g(f(k))` holds for all `k` in `S`.
Then the correct output is truthy.
Here is the 27×27 table of all possible inputs, with `+` marking a truthy output and `-` a falsey output:
```
+ - - + - - + - - + - - + - - + - - + - - + - - + - -
- + - - - - - - - - - - + - - - - - - - - + - - - - -
- - + - - - - - - - - - - - - - - - - - - + - - + - -
+ - - + - - - - - - + - - + - - - - + - - + - - - - -
- - - - + - - - - - - - - + - - - - - - - + - - - - -
- - - - - + - - - - - - - + - - - - - - - + - - - - -
+ - - - - - + - - - - - - - - - - - - - - + - - - - -
- - - - - - - + - - - + - - - - - - - - - + - - - - -
- - - - - - - - + - - - - - - - - - + - - + - - - - -
+ - - - - - - - - + - - - - - - - - - - - + - - - - -
- - - + - - - - - - + - - - - - - - - - - + - - - - -
- - - - - - - + - - - + - - - - - - - - - + - - - - -
+ + - - - - - - - - - - + + - - - - - - - + + - - - -
- - - + + + - - - - - - + + + - - - - - - + + + - - -
- - - - - - - - - - - - - + + - - - - - - + - - - - -
+ - - - - - - - - - - - - - - + - - - - - + - - - - -
- - - - - - - - - - - - - - - - + - - - - + - + - - -
- - - - - - - - - - - - - - - - - + - - - + + - - - -
+ - - + - - - - + - - - - - - - - - + - - + - - - - +
- - - - - - - - - - - - - - - - - - - + - + - - - - +
- - - - - - - - - - - - - - - - - - - - + + - - - - +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
- - - - - - - - - - - - + + - - - + - - - + + - - - +
- - - - - - - - - - - - - + - - + - - - - + - + + - +
+ - + - - - - - - - - - - - - - - - - - - + - + + - +
- - - - - - - - - - - - - - - - - - - - - + - - - + +
- - - - - - - - - - - - - - - - - - + + + + + + + + +
```
## Rules and scoring
You can write a full program or a function.
The lowest byte count wins, and [standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed.
[Answer]
# Jelly, ~~17~~ ~~14~~ 13 bytes
```
+13ḃ3Um0ị2/⁼/
```
[Try it online!](http://jelly.tryitonline.net/#code=KzEz4biDM1VtMOG7izIv4oG8Lw&input=&args=MywgMTA) or [verify all 27×27 cases](http://jelly.tryitonline.net/#code=KzEz4biDM1VtMOG7izIv4oG8LwoyN1LigJnhuZcyw4figqxzMjfhu4vigJwrLeKAnWrigqzigbZq4oG3&input=).
### How it works
```
+13ḃ3Um0ị2/⁼/ Main link. Argument: [f, g] (encoded as integers)
+13 Add 13 ([1, 1, 1] in base 3) to f and g.
ḃ3 Convert f + 13 and g + 13 to bijective base 3.
Bijective base 3 uses the digits 1 to 3 instead of 0 to 2.
This yields [[f(2)+1, f(1)+1, f(0)+1], [g(2)+1, g(1)+1, g(0)+1]].
The increments account for 1-based indexing.
U Reverse each digit array.
This yields [[f(0)+1, f(1)+1, f(2)+1], [g(0)+1, g(1)+1, g(2)+1]].
m0 Concatenate the list with a reversed copy of itself.
ị2/ Split the result into pairs, and reduce each one by indexing.
This computes g○f and f○g.
⁼/ Reduce by match; return 1 iff g○f = f○g.
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), ~~19~~ 18 bytes
```
I:PII$YAZ{Y:)1Mw)=
```
Truthy is an array with all ones. Falsy is an array containing at least one zero.
[Try it online!](http://matl.tryitonline.net/#code=STpQSUkkWUFae1k6KTFNdyk9&input=WzUgMTZd) or [verify all cases](http://matl.tryitonline.net/#code=Mjc6cUhaXiEiQCAgICAgICAgICAgICAlIHByZXBhcmUgaW5wdXRzCkk6UElJJFlBWntZOikxTXcpPSAgICAgJSBhY3R1YWwgY29kZQpBMnZdMjdFZVEnLSsgJ3cpISAgICAgICUgcmVhcnJhbmdlIG91dHB1dHMgZm9yIGRpc3BsYXkK&input=) (takes a few seconds).
```
% implicitly input an array of two numbers
I:P % push [3 2 1]
I % push 3
I$ % specify that the next function takes 3 inputs
YA % convert input to base 3 with alphabet [3 2 1] and 3 digits. Gives 2x3 array
Z{ % convert into cell of two cells, one with each row
Y: % split cell array. We have two arrays on the stack, one per function
) % index operation to compute f ∘ g. Function composition is indexing
1M % push the two arrays again
w % swap the two arrays
) % index operation to compute g ∘ f
= % test for equality element-wise
% implicitly display
```
[Answer]
## Python 2, 61 bytes
```
lambda m,n:all(n/3**(m/i%3)%3==m/3**(n/i%3)%3for i in[1,3,9])
```
Given an input `i`, we can implement the function represented by `n` by doing `n/3**i%3` to extract the `i`th ternary digit of `n`. The function checks that the same result is gotten for each of `0,1,2` when applying the functions in either order. Actually, since the first step is doing `3**`, this tests with `[1,3,9]` instead.
The code reuse looks wasteful, but I didn't see a better way. Compare:
```
q=lambda x,i:x/3**i%3;lambda m,n:all(q(m,q(n,i))==q(n,q(m,i))for i in[0,1,2])
```
[Answer]
# JavaScript (ES7), 68 bytes
```
(a,b)=>![0,1,2].some(n=>t(a,t(b,n))-t(b,t(a,n)),t=(a,n)=>a/3**n%3|0)
```
Unfortunately base 3 conversion was too expensive:
```
(a,b)=>[0,1,2].every(n=>a[b[n]]==b[a[n]],g=a=>(27+a).toString(3).slice(1),a=g(a),b=g(b))
```
[Answer]
# Mathematica, 77 bytes
```
Reverse[#][[#2+{1,1,1}]]==Reverse[#2][[#+{1,1,1}]]&@@IntegerDigits[{##},3,3]&
```
Mathematica's One-based indexing strikes again!
] |
[Question]
[
`figlet` is utility that converts plain text to an ascii-art representation for use in banners and the like. For example:
```
$ figlet "CODE GOLF"
____ ___ ____ _____ ____ ___ _ _____
/ ___/ _ \| _ \| ____| / ___|/ _ \| | | ___|
| | | | | | | | | _| | | _| | | | | | |_
| |__| |_| | |_| | |___ | |_| | |_| | |___| _|
\____\___/|____/|_____| \____|\___/|_____|_|
$
```
Write a program or function that takes the ascii-art output from `figlet` and returns it to its original plain text.
It may be helpful to you to install `figlet`. I have version 2.2.5 which is what you get if you `sudo apt-get install figlet` on Ubuntu 14.04. This figlet actually has several "fonts". For the purposes of this context, we will just be dealing with the default `standard` font.
Input text will be no more that 80 characters wide, and will have been generated from plain text containing only the uppercase characters and space.
Your program may not call `figlet` or its source code in any way.
### Example
Input:
```
_ ____ ____ ____ _____ _____ ____ _ _ ___
/ \ | __ ) / ___| _ \| ____| ___/ ___| | | |_ _|
/ _ \ | _ \| | | | | | _| | |_ | | _| |_| || |
/ ___ \| |_) | |___| |_| | |___| _|| |_| | _ || |
/_/ \_\____/ \____|____/|_____|_| \____|_| |_|___|
_ _ ___ __ __ _ _ ___ ____ ___ ____
| | |/ / | | \/ | \ | |/ _ \| _ \ / _ \| _ \
_ | | ' /| | | |\/| | \| | | | | |_) | | | | |_) |
| |_| | . \| |___| | | | |\ | |_| | __/| |_| | _ <
\___/|_|\_\_____|_| |_|_| \_|\___/|_| \__\_\_| \_\
____ _____ _ ___ ____ ____ ____ _______
/ ___|_ _| | | \ \ / /\ \ / /\ \/ /\ \ / /__ /
\___ \ | | | | | |\ \ / / \ \ /\ / / \ / \ V / / /
___) || | | |_| | \ V / \ V V / / \ | | / /_
|____/ |_| \___/ \_/ \_/\_/ /_/\_\ |_| /____|
```
Output:
```
ABCDEFGHI
JKLMNOPQR
STUVWXYZ
```
Input:
```
____ _____ _ ____ __ ___ ____ ____
/ ___|_ _|/ \ | _ \ \ \ / / \ | _ \/ ___|
\___ \ | | / _ \ | |_) | \ \ /\ / / _ \ | |_) \___ \
___) || |/ ___ \| _ < \ V V / ___ \| _ < ___) |
|____/ |_/_/ \_\_| \_\ \_/\_/_/ \_\_| \_\____/
```
Output:
```
STAR WARS
```
---
Note a previous edit of this question allowed inputs containing upper and lower case letters plus numerals. It was pointed out that this caused several points of ambiguity with certain adjacent character combinations. It became obvious that I needed to rigorously find a set of characters with no such collisions so that the contest is actually doable. At first I tried all lowercase letters plus numerals with this shell one-liner:
```
for t in {0..9}{a..z} {a..z}{a..z} {a..z}{0..9} {0..9}{0..9} ; do figlet $t | tr '\n' ':'; echo ; done | sort | uniq -d | tr ':' '\n'
```
This yielded {`j1`, `jl`} and {`i1`, `il`} as ambiguous pairs. So instead with all uppercase letters (as suggested by @AlexA.), there are no ambiguous pairs:
```
for t in {A-Z} ; do figlet $t | tr '\n' ':'; echo ; done | sort | uniq -d | tr ':' '\n'
```
[Answer]
# JavaScript, 946 bytes
```
i=>i.split(/\n *\n/).slice(n=0,-1).map(x=>[...(x=x.split`
`)[0]].map((_,i)=>parseInt([0,1,2,3,4].map(j=>"_/\\|".indexOf(x[j][i])+1).join(""),5)).map((n,i,x)=>o[x.slice(i).map(a=>v=v*5+a,v=0).find(v=>o[v])]||"").join``," 0JiivI1d5JysyKgx0X5qyZegzZfZ9mtZfO3288Q9CboCfG28CkO29Q9J1bg3N2d9pLh0dLfL2sLdwH14uLwdU1b4LkyYbbwY1Y2YhY1fjY1Y2YhY1fjY1Y2YhL3nfY126Y1Y2YhY20dY1Y2YhY1fjY1Y2YhR173PjP2P2P7RgjPjP2Fc6FsFtF1rDpcDhdB1ptBhdExgEfE2sSelvS6ySdwJ5wiSr3S6ySdwJaq4Jc21T8zaT1TrT2kA28bA2sAdwT3vT1TrT2kA1ufA1w2TwcT1TrT2kT1xlT1TrT2kA7ccTv58T1TrT2kT1crT1TrT2kT83tT1TrT2kT1crT1TrT2kO48kQ9CboCfG28CkO29Q9AvrtiA2sAdwA21mA1w2AacxM6z18A2cpp6A2sAdwA21mA1w2AacxA7yngA2sAdwA21mA1w2AacxA1ukibA2sAdwA21mA1w2AacxV1brpkV3V4VdV105jV3V4VdV2e9V3V4VdV105jV3V4VdV4md1V3V4VdV105jV3V4VdAruayA2sAdwA21mA1w2AacxAgc25A2sAdwA21mA1w2AacxWozq07rW3W4WdW3hl3vW3W4WdW8de5W3W4WdW3hl3vW3W4WdWg1p5dW3W4WdW3hl3vW3W4Wd".split(/(?=[A-Z ])/).map(x=>o[n+=parseInt(x.slice(1),36)]=x[0],o={})).join`
`
```
[Try it online!](https://tio.run/##hVNdc5pAFH33VzA8sQlBdhHFB@yQD9tYW5NotX6NIgu6qICAgJb@dgsCeQiZ6YXZPfecu@cyzF5TDVRPc4nj31k21i@Oa2u653Gej@2jz4Uu8XWGuRC5RTjP2RGfqc4s6mZmVQHn7YimM5bMs3cQcHvVYSK5NeU4LtmjrHpZWYIpP59fVWbBEiC3HNX19GfLZ6Y8C1nECmwt0025RS@qs1lMc8TCetQzmGhqzqdkDm6TBqZNLIamASuCrBtjsYSNEkd7GuUfQzJFlVuBHNyItyobyDzgjMSPCdLCYA7mcZy4XO2WS5am@A4hwTPEYufknb6vI/63eDhN9PV5Ykyae39i9AQkSa/Nh5X9YHxF0sO2h5qvzQ5crYWfCDed7obHXaOLvC4Ov8HasRviX3BV625P49UqHMMxGm/G0DA/oq5gGWOI6jmPePyx4g02hBfzBSVP421tprCt1dte229D99HRHjf4Hjr@/QY/Resn4wl5fX0X9OunPg47Ykj6rpAn6qHW0RAcSGd1AAfuAG0VJK0U5Ck4HAhBwcGjocAQDUItZwYw2hViQ9MGgSi9K5pbQEnwy2yvJm1Lf00JXJ9kbRUE92kzRdWiH/UzlBSkOU69LCqNk7X@hIbHLVmV@SFcuc52KAxrQzyEvGjmEOnNMlnbY1hiFfeonj5puNaQWKZH9vnAN9yRMKqN8EjY7IQgxxLWxU/oNXREXObpYsCYL/JUuZtQc1B9Hyt7at3K75NTXHcIWKEO5nKUzBhry3/@gvxeV5YXwLj64UhcnaENL7nvrq7iNtnp/ZOlMTxLH31DogEAF2qRRrFSaRRETlbilF7E1zSm4iSppjihk/SKKhQVXx9qke9Zkm7Jm55/L4kzl2zJ9OzctSSTru5pzAqYCpnL/6LyDw)
Note that `figlet` by default outputs two trailing blank lines; if those can be
assumed to not exist, like in the challenge examples, the initial `slice` can be
removed for [-10 bytes](https://tio.run/##bZRrc5pAFIa/51cwfGIbguwiijPFDrnYxtomrVar4iCyoKsGCCBgSn97utxspwZm2HOe9@x7FmaXrRmboRUQP7pyPWy/@oFn2WEohBH2DpGQBCSyOe6VqF0ihP6eRFxDd5l3utsAwpPpc6nanQuCQMe01JcXSzAXF4tC5QyeALXrm0Fo37sRNxd5yCNe4pulvlW7rNHQ9YwViIvt9MHh0vl2MScLcAmBsPWIy7Es4GVQduNcnvApdfTmtN2eWDZHSsVUu7Eav5MvTT5WRSA41I@L88J4ARZZRl0Ku@WSZxmxT0h8D7HcP4bHz@tU/Ck/H2f2@mXmzDpP0cx5kJCifOvcrLwb5yNSbnYPqPOt04ertfQV4Y4/2Ih44AxQOMDJJ9g8DBL8A66ag91xulolUzhF080UOtv/o4HkOlOIWhVHIv6/4jtsS4/bR0Tv9vf1Ng97VqsX9qIeDG5963aDr6EfXW/wXbq@c@5QOLT38bB1HOKkLydkGEhVYj43@xaCI@XFHMFRMEI7DSkrDYUaTkZSXDN4cDSYoFFiVWQE030tti1rFMvKSbGCOlSk6Jw@NJXd2VfT4iAiZVsNwae8mWZa6ZfWC1Q0ZPl@61zU2kd3/QaGhx1ZnfMxXAX@biyNm2M8hqK8rUJkd85h8wnDM6oFB/P4RsO1heRzPPFensV2MJEmzQmeSJu9FFexgm35DbyGvozPOVsfKe6DOteuZswC/D1W3ty9VE8np97uEPBSCyzUlJ4x3lN//eZdut2rvX2xfAVcYD8fSGBzrBPSPR/YJu6RvT08uhYn8uwhchQWAPDKGPlVPulYXXVas5P6r1DLF1nBsyLVGb20aNDbKDBj5CyXGUAjKhROZX2jnEo9MiMvyjmTmzSKyhLkIsifhZfOjKlUpKWs58vQy3WUxfmy8rKisgTF3PdM7VXMrTyy6l0ovsiMghvV0nX6WzIaJ1A008uMGle12Uku8B8). Otherwise, make sure the blank lines are
present in the "Input" field on TIO, or the last line of output will be omitted.
## Explanation
At a high level, this scans the strings for patterns, and outputs the ones it
finds.
A single character can have multiple patterns; for example, these are all valid
patterns for `A`: (the first and last column are omitted, as they are not
necessary for matching)
```
_
/ \
/ _ \
/ ___ \
_/ \_
```
```
_ _
_|/ \
/ _ \
/ ___ \
_/ \_
```
```
_____
/ / \ \
/ _ \
/ ___ \
_/ \_
```
The first appears in bare `A`s, or uncombined `A`s such as in `AX`, the second
appears in `TA`, and the third appears in e.g. `WAV`:
```
_ _____ _ __ _____ __
/ \ |_ _|/ \ \ \ / / \ \ / /
/ _ \ | | / _ \ \ \ /\ / / _ \ \ / /
/ ___ \ | |/ ___ \ \ V V / ___ \ V /
/_/ \_\ |_/_/ \_\ \_/\_/_/ \_\_/
------- ------- -------
```
Thus, for every character, there is a pattern for:
* Each triplet of characters with it at the center
* Each pair of characters containing it
* It on it's own
Some of these patterns are identical, for example, the `A`s in `VAV` and `WAV` are
identical, and the `A`s in `AX`, `XA`, and `A` are identical.
Each pattern needs a unique representation, and since this is code golf, it
should be as compact as possible.
Because the mega-characters have a fixed height of 5, but are not fixed-width,
the patterns are defined principally by columns.
First, each of the symbols in the pattern are converted to a single base-5 digit,
where `_/\|` respectively correspond to 0-4, and other symbols are treated as
spaces.
```
_
/ \
/ _ \
/ ___ \
_/ \_
0001000
0020300
0201030
2011103
1200032
```
Then, the 5 base-5 digits in a column are combined to make a single base-5
number.
```
00021, 00202, 02010, 10110, 03010, 00303, 00032
```
Represented in decimal, the column numbers are `11, 52, 255, 655, 380, 78, 16`.
These numbers must be combined into one number that identifies the pattern. The
correct way would be to concatenate all of the base-5 numbers (or, equivalently,
to treat the list of column numbers as a base-3125 number).
As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the correct way will not be used, due to a bug that
happened to not break stuff for this set of patterns and is now considered a
byte-saving feature.
Thus, the column numbers are combined into one number that identifies the pattern:
```
11 * 5^6
+ 52 * 5^5
+ 255 * 5^4
+ 655 * 5^3
+ 380 * 5^2
+ 78 * 5^1
+ 16 * 5^0
= 585531
```
Now, these numbers are inserted into a giant lookup table, along with `0` for :
```
{
0: " ",
585531: "A",
591231: "A",
// ...
}
```
At this point, the table could be serialized and plopped into the code, but it
is not very golfy. Thus, this explanation branches into two parts: matching the
patterns and compressing the lookup table.
## Matching the Patterns
Matching the patterns is fairly simple. First, the input is split into
paragraphs; each paragraph is a line of mega-text. The paragraphs/mega-lines are
converted independently, and then joined again with newlines.
Each mega-line is first converted into an array of column numbers:
```
____ ___ ____ _____ ____ ___ _ _____
/ ___/ _ \| _ \| ____| / ___|/ _ \| | | ___|
| | | | | | | | | _| | | _| | | | | | |_
| |__| |_| | |_| | |___ | |_| | |_| | |___| _|
\____\___/|____/|_____| \____|\___/|_____|_|
[
120, 253, 746, 756, 756, 871, 253, 746, 756,
746, 377, 624, 626, 746, 756, 746, 377, 624,
626, 771, 781, 856, 756, 504, 0, 120, 253,
746, 756, 771, 776, 624, 253, 746, 756, 746,
377, 624, 626, 621, 6, 6, 6, 624, 626,
729, 780, 770, 750, 500
]
```
Then, this array is iterated across; for every number in the array:
1. If this number is in the lookup table, add the corresponding character to the
string and continue iteration.
2. Multiply the number by `5`, and add the next number in the array. Go to #1,
and repeat until the number matches or there are no numbers left.
Note that it searches for a character starting at every column, regardless of
the previous matches. Additionally, the only way it finds no character starting
at a column is if it exhaustively checks all possible ending columns to the end
of the array, completely ignoring the fact that no patterns are longer than 12
columns.
After this highly inefficient process completes, the string will be `CODE GOLF`.
## Compressing the Lookup Table
If the lookup table were simply serialized, it would be a whopping 23,094 bytes,
which is clearly unacceptable.
The lookup table is transformed as follows:
```
Original:
0: " "
12: A
63: B
209: A
1040: C
30: A
512: C
Sorted:
0: " "
12: A
30: A
63: B
209: A
512: C
1040: C
Difference from last:
+0: " "
+12: A
+18: A
+33: B
+146: A
+303: C
+528: C
Final (numbers are encoded in base 36):
" 0AcAiBxA42C8fCeo"
```
The final string is:
```
0JiivI1d5JysyKgx0X5qyZegzZfZ9mtZfO3288Q9CboCfG28CkO29Q9J1bg3N2d9pLh0dLfL2sLdwH14uLwdU1b4LkyYbbwY1Y2YhY1fjY1Y2YhY1fjY1Y2YhL3nfY126Y1Y2YhY20dY1Y2YhY1fjY1Y2YhR173PjP2P2P7RgjPjP2Fc6FsFtF1rDpcDhdB1ptBhdExgEfE2sSelvS6ySdwJ5wiSr3S6ySdwJaq4Jc21T8zaT1TrT2kA28bA2sAdwT3vT1TrT2kA1ufA1w2TwcT1TrT2kT1xlT1TrT2kA7ccTv58T1TrT2kT1crT1TrT2kT83tT1TrT2kT1crT1TrT2kO48kQ9CboCfG28CkO29Q9AvrtiA2sAdwA21mA1w2AacxM6z18A2cpp6A2sAdwA21mA1w2AacxA7yngA2sAdwA21mA1w2AacxA1ukibA2sAdwA21mA1w2AacxV1brpkV3V4VdV105jV3V4VdV2e9V3V4VdV105jV3V4VdV4md1V3V4VdV105jV3V4VdAruayA2sAdwA21mA1w2AacxAgc25A2sAdwA21mA1w2AacxWozq07rW3W4WdW3hl3vW3W4WdW8de5W3W4WdW3hl3vW3W4WdWg1p5dW3W4WdW3hl3vW3W4Wd
```
I haven't done much [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'"), so if anyone has ideas on how to
compress this further, I'd love to hear them.
] |
[Question]
[
In this challenge you will write a program that takes two newline-separated strings, s1 (the first line) and s2 (the second line), as input (STDIN or closest). You can assume that the length of s1 will always be smaller than 30 and bigger than the length of s2. The program should then output each step in the levenshtein distance from s1 to s2.
To clarify what each step in the levenshtein distance means, the program will print n strings, where n is the levenshtein distance between s1 and s2, and the levenshtein distance between two adjacent strings will always be one. The order doesn't matter. The output should be newline-separated and not include s1, only the in-betweens and s2. The program should also run in under one minute on a modern computer.
Examples:
Input:
```
Programming
Codegolf
```
Output:
```
rogramming
Cogramming
Coramming
Coamming
Codmming
Codeming
Codeging
Codegong
Codegolg
Codegolf
```
Input:
```
Questions
Answers
```
Output:
```
uestions
Aestions
Anstions
Ansions
Answons
Answens
Answers
```
Input:
```
Offline
Online
```
Output:
```
Ofline
Online
```
Input:
```
Saturday
Sunday
```
Output:
```
Sturday
Surday
Sunday
```
[Here](http://ideone.com/w5zhpz) is a link to a python script that prints out the distance and the steps.
Additional rules:
* No use of the internet
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply
This is code-golf so keep you code short; shortest code wins!
[Answer]
# Haskell, ~~201~~ 194 bytes
```
l=length
g[]n u=map(\_->"")n
g(b:c)[]u=(u++c):g c[]u
g(b:c)n@(o:p)u|b==o=g c p(u++[o])|1<2=((u++o:c):g c p(u++[o]))!((u++c):g c n u)
a!b|l a<l b=a|1<2=b
p[a,n]=g a n""
f=interact$unlines.p.lines
```
Longer than expected. Maybe I can golf it down a little bit ...
Usage example:
```
*Main> f -- call via f
Questions -- User input
Answers -- no newline after second line!
uestions -- Output starts here
Aestions
Anstions
Ansions
Answons
Answens
Answers
```
It's a brute force that decides between changing and deleting if the initial characters differ.
[Answer]
# [APL (Dyalog 18.0)](https://www.dyalog.com/), 66 bytes
```
{⍺<Ö≢⍵:⍺∇⎕←0~⍨0@(⊃(⍸~p)~⍳⊃⌽⍸p←⍵=⍺↑⍨≢⍵)⊢⍵⋄j←⊃⍸⍺≠⍵⋄⍺≢⍵:⍺∇⎕←⍺[j]@j⊢⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT/9/eNqjtgnVGo96twKRwqPeXZpADEQIka2atf@rgSI2QKWdi4B8K5CKjvZHfVOBWg3qHvWuMHDQeNTVDNSyo65AEyiwGch71LMXyC8AKgFqsQVpaZsIVAoxQvNRF4h61N2SBVIAVN27A6SkcwFEFMzGsAvIjs6KdciCaK79nwYW6wNrX/Ood8uh9cYgS/qmBgc5A8kQD8/g/@qOTs4urm7qCmkKUGaEOhfEOHV1LjTZCBAbSdY5PyU1PT8nDSwfUJSfXpSYm5uZl45iQl5xeWpRMVhJYGlqcUlmfl6xOgA "APL (Dyalog Unicode) – Try It Online")
Works correctly now.
A recursive function submission, done with a lot of input from Adám and Bubbler.
Input is taken as `<s2> f <s1>`.
## Explanation
`⍺<⍥≢⍵:` if the strings have different lengths:
`0@(...)⊢⍵` put a zero at the following index:
`⊃` first element of:
`(⍸~p)` characters which do not match
`~` without
`⍳⊃⌽⍸p←⍵=⍺↑⍨≢⍵` all indices before last character match
`0~⍨` remove the zero(thereby removing the element)
`⍺∇⎕←` display the result and recurse
`⋄⍺≢⍵:` Otherwise, till the strings match:
`i←⊃⍸⍺≠⍵` find first non-matching element
`⍺[i]@i⊢⍵` and replace the element at that index
`⍺∇⎕←` display the result, and recurse
] |
[Question]
[
All those busy beavers made quite a mess. They wrote all over the tape. At this rate, our neighbour will stop lending us unbounded tapes.
We need a new way to play the busy beaver game, one that doesn't ruin every tape we use.
# The Rules
Brainfuck only. Memory tape is unbounded both ways. Input instruction will always read \$0\$, so it can be used to clear a value.
50 bytes source limit.
At the end of execution, memory must be all \$0\$s.
Score is distance between the memory pointer's starting location and final location - if it takes \$n\$ move instructions to go between them, your score is \$n\$. Higher is better. Provide an exact value if you can, otherwise provide an estimate.
# Example
## 32 bytes, \$2^{255}-1\$
```
-[-[[>]+>+[<]>-[[>]<+<+[<]>-]]>]
```
## Explanation
```
- Initialize the list to [255].
[ ] Repeat as long as the list is not empty.
[- ] Decrement the left end. We need to shrink the numbers so it ends eventually.
[ [ ] ] Skip if 0 already.
[ [[>] ] ] Move to the cell past the right end.
[ [ + ] ] Make this cell 1.
[ [ > ] ] Go right again.
[ [ + ] ] Make this cell 1. We've now appended [1, 1].
[ [ [<]> ] ] Go back to the first nonzero cell on the left.
[ [ - ] ] And decrement it.
[ [ [ ]] ] We will need to transfer the rest of the number from the left to the right, so keep looping.
[ [ [[>]< ]] ] Go to the last nonzero cell on the right.
[ [ [ +<+ ]] ] Increment this and the one on the left. These are the cells we appended earlier. We transfer to them.
[ [ [ [<]> ]] ] Go back to the first nonzero cell on the left, which we are transferring from.
[ [ [ -]] ] Decrement here on the left to balance out the incrementing on the right.
[ >] We end the iteration on a now empty cell. Move right, the new left end is there.
```
We begin with the list \$[255]\$. At each iteration, we consume the value \$n\$ on the left of the list, and if \$n>1\$, we append \$[n-1, n-1]\$ to the right. The numbers appended \$(n-1)\$ are lower than the original \$(n)\$, so they will get smaller until they are \$1\$, at which point they are consumed without expanding. Thus, the process ends eventually, with all \$0\$s in memory. However, at each step, the number of copies of the number doubles. The score of this program initialized with the list \$[n]\$ is \$2^n-1\$.
This example is meant to show some of the techniques used in creating a submission. It's not competitive for its size.
[Answer]
## Score: \$ A(255, 2) - 1 = (2 \uparrow^{253} 5) - 4 \$
```
+<+<<++>-[-[<+>>[-<[->+<]+>>]+<-]>[>]+[<]+<]>[->]
```
\$ A \$ here is the Péter-Ackermann formulation of the [Ackermann function](https://en.wikipedia.org/wiki/Ackermann_function), while the other score expression uses Knuth up-arrow notation. The 35-byte main loop `[-[<+>>[-<[->+<]+>>]+<-]>[>]+[<]+<]` can be used to compute \$ A(m,n) \$ by placing on the tape the values `1 - m, m, 1 <n times>` and entering the loop with the pointer on the `m` cell. After the loop terminates, the nonzero tape contents are \$ A(m,n) \$ ones starting immediately to the right of the pointer.
I used the following Python program for modeling the behavior of the program:
```
def a(M, N):
assert M > 0
m = [-M + 1, M]
n = N
while m[-1]:
while m[-1] > 1:
m[-1] -= 1
m[-2] += 1
while n:
m.insert(-1, 1)
n -= 1
n = 1
n += 2
m.pop()
return n
```
] |
[Question]
[
Write a program that takes as input a string and an integer `n`, and outputs:
1. The string that was passed to the program `n` times ago;
2. A new program that will be used for the next invocation.
You cannot store any data outside of the program, and your program cannot call previous programs in the chain. If the string does not exist, output an empty string (but still output the next program).
Example run, where I use the notation `program_n` for each successive program (Of course, `[This text is the nth program]` would be replaced with actual code.)
```
$ program_1 "One" 1
[This text is the second program]
$ program_2 "Two" 1
One
[This text is the third program]
$ program_3 "Three" 2
One
[This text is the fourth program]
$ program_4 "Four" 2
Two
[This text is the fifth program]
$ program_5 "Five" 1
Four
[This text is the sixth program]
```
[Answer]
# CJam, 25
```
L{\_l~(>1<lN+a@+`@"_~"}_~
```
[Try it online](http://cjam.aditsu.net/#code=L%7B%5C_l~(%3E1%3ClN%2Ba%40%2B%60%40%22_~%22%7D_~&input=1%0AOne)
**Explanation:**
```
L push an empty array (this is the array of previous strings)
{…} push this block
_ duplicate the block
~ execute the 2nd copy (the stack contains the array and the block)
```
The block:
```
\ swap the array with the block
_ duplicate the array
l read a line from the input (containing the integer n)
~( evaluate n and decrement it
> slice the array starting at that position
1< slice the resulting array to keep only the first string (if any)
l read the 2nd line from the input (containing the string)
N+ append a newline
a wrap in an array
@ bring the previous array to the top
+ concatenate the arrays, thus prepending the new string
` convert the array to its string representation
@ bring the block to the top
"_~" push this string
```
At the end, the requested string (if any), the array's representation, the block and the string "\_~" are printed automatically.
[Answer]
## Python, 221 bytes
```
import sys
o,p=[''],r'import sys;a,o,p=int(sys.argv[2]),[{2},{0}],{1};print o[a] if len(o)>a else "","\n",p.format(`sys.argv[1]`,`p`,",".join(`s`for s in o))'
print '\n',p.format(`sys.argv[1]`,`p`,','.join(`s`for s in o))
```
To test this easily, use `./thisgolf.py "yourfirststring" | python -c "import sys;exec(sys.stdin.read().split('\n')[1])" "your second string" <N>`, repeating the last bit as many times as you'd like.
[Answer]
# Python 2, 207 bytes
```
def r(O,R):import sys,marshal as m;a=sys.argv;b=int(a[2]);O.extend(["",""]*b);O[b]=a[1];print"%s\nfrom marshal import*;c=%r;i=lambda:0;i.__code__=loads(c);i(%r,i)"%(O[0],m.dumps(R.__code__),O[1:])
r([""],r)
```
Built on [my other quine but changes program](https://codegolf.stackexchange.com/questions/57171/mutant-pangolin/57232#57232), this task is simpler so I was able to golf this further. If I was able to take the input to stdin, this should be much shorter.
[Answer]
# [Python 3](https://docs.python.org/3/), 90 bytes
```
a=["a+=input(),;print(*a[1:-int(input())][-1:],'a=%r;exec(a[0])'%a,sep='\\n')"];exec(a[0])
```
[Try it online!](https://tio.run/##TU5Nb4MwDL37V1iWKkiXSmO7UeVf7AY5pMWUSDSJQli3X88Stkk9@NnS8/sI32ny7n27@oFVJKLNqI7Mi7IurKkW8hyidak@mq5pT@X6I4TuTk2rZWXUIZ75i6@16V61qA5GLhxU1feuEqSfqC3bwxj9HS@rnZN1C9p78DHhnoFmwQAw8Ij/mfG2SCxuhCSR3aCodyRawNvsL2bGUht2RIXlPZfSgOFZm@dXm0cAPCY7M37ElbPNXq7IRRGJzTuGBtLDF5wiM7zB6NdYlv3M3A8 "Python 3 – Try It Online")
## How it works:
* `a` store `[<code>, <first call>, ..., <last call>]`
* `a[1:-int(input())]` gives the sublist `[<first call>, ..., <wanted call>]` (or the empty list if the wanted call doesn't exist). Then `[-1:]` gives the singleton of the last element of that sublist if it exists (the empty list otherwise). `*` then unpack the sublist.
* The quine part is based on the quine `a="print('a=%r;exec(a)'%a)";exec(a)`
[Answer]
# Javascript ES6, ~~130~~ ~~128~~ ~~121~~ ~~120~~ 113 bytes
```
a=[];b=_=>{a.push(prompt());console.log((a[a.length-prompt()-1]||"")+`
a=`+JSON.stringify(a)+";b="+b+";b()")};b()
```
[Answer]
# [Julia 1.0](http://julialang.org/), 87 bytes
```
(a=:(a=[ARGS[1];a];print("(a=(println($a[parse(Int,ARGS[2])]);$a))[end]|>eval")))|>eval
```
[Try it online!](https://tio.run/##fVHBTgMhEL3PVxDSAyRrk91jmzXxovFgTNQbEoOFtjQENrNs68H/8gP8sBWW1qYeJAFmHu8Nb2A3OKvqj7FrUR0opSNT7SJNcfN09yxquVRy2aH1kdGEsil0ns2U6BT2ht37WE3URnLJlzPFuTBey89rs1eOcs5LNKbaANiiUdpZb3rGAbKQtERQWlEqAbRZq8HFtz7qMMR0UgKAdUBiifWkXjjjN3HLkH9/NUDSOBpNbBSNvarlGW1OaMEY6oockGfQaItmdboqmcmEbJQ9mKjmpbmOF/wv@9Jn4axcSIpUfcqK/XOzqAt@fL85@9WdXrRkdp36bFtST1keGxfelSNdKrcL1mdhReirp0fLrjf/cUWzyN9xIfEa0hwfvYEaXg4hr1s0Bhq4DQPmze7T2Q8 "Julia 1.0 – Try It Online")
smilar approach than [Jakque's answer](https://codegolf.stackexchange.com/a/231680/98541) but reversing the history order:
* `a` stores `[<last string>, ..., <first string>, <code>]`
* based on [this quine by Dennis](https://codegolf.stackexchange.com/a/92455/98541)
* the code is stored as a [`quote`](https://docs.julialang.org/en/v1/manual/metaprogramming/#Quoting), which adds some ugly formatting but is equivalent
] |
[Question]
[
[Related](https://codegolf.stackexchange.com/questions/241609/is-this-continuous-terrain-part-ii) | [Related](https://codegolf.stackexchange.com/q/199540)
---
Given an ASCII art with `|`, `_`, and , check if you can draw the art in one stroke.
## Description
Your task is, if the ASCII art is representing lines, then check if you can draw the whole art in one stroke, which means:
* without drawing an already drawn line again
* without lifting and continuing the stroke with skipping blocks
## Connection Rules
* A pipe is connected to the left end of the underscore when:
+ the pipe is left to the underscore `|_`
+ the pipe is bottom-left to the underscore, but only when it's below a space
```
_
|
```
* A pipe is connected to the right end of the underscore when:
+ the pipe is right to the underscore `_|`
+ the pipe is bottom-right to the underscore, but only when it's below a space
```
_
|
```
* An underscore is connected to another underscore if it is left/right to it `___`
* A pipe is connected to another pipe if it is above/under it
```
|
|
|
```
A space should not be viewed as a line but as a gap. It can't connect to a pipe or an underscore.
---
So this art can be drawn in one stroke:
[](https://i.stack.imgur.com/rZ6TV.png)
(Start at the red cross and end at the blue cross)
# Rules
* [Standard Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply
* The program must take the ASCII art as input
* Input will not be empty
* Input can be padded with spaces, so it's rectangular
* [Standard decision problem output](https://codegolf.meta.stackexchange.com/a/19205/96037)
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer wins
## Examples
```
[In]:
__
|__|
[Out]: True
[In]:
|__|
|__|
[Out]: False
[In]:
___
|___|_ |
[Out]: False (because of the space)
[In]:
_
|_|_
__|
|__|
[Out]: True
[In]:
_
|_|_
|_|
[Out]: True
[In]:
_ _
|_| |_|
[Out]: False
[In]:
_
|_||_|
[Out]: False (the middle pipes are not connected)
[In]:
__
|_|
[Out]: True (begin top-left)
[In]:
___
|_
[Out]: False (the pipe can't connect to the above underscore)
[In]:
___
|
|
|
[Out]: True
[In] (example by DLosc):
_
|_|_
|_
[Out]: False (the two pipes are connected to each other, and so is each underscore it the upper pipe, but the central underscores are not (because there's a pipe between them) and neither underscore to the lower pipe (because the pipe is not below a space)
```
Good luck!
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 524 bytes
```
def o(A,C=[5]*3,L=[],E=enumerate):d=A.split('\n');Q=A.count;l,c,r=C;return len(L)==Q('|')+Q('_')or any(r<5and[(T:=(Y:=[int(g)-1for g in str(U)])[:4]*all(len(d)>l+u>-1<c+v<len(d[0])!='|_ '[w]==d[l+u][c+v]for u,v,w in zip(Y[4::3],Y[5::3],Y[6::3])))and r==T[0]and(O:=[l+T[1],c+T[2]])not in L and o(A,O+T[3:],L+[O])for U in[3111,3213211,3124122,3102102,1113,1011011,1024013022,1002013002,4112,4124122,4121121,4223123221,2114,2102102,2101101,2203103201]]or[o(A,[i,j,e+(c<'|')])for i,l in E(d)for j,c in E(l)for e in[0,2]if' '<c])
```
[Try it online!](https://tio.run/##dVNda@MwEHz3r9h7klSrxZLd43CjQim9p0AopA9BFcY4Tuvik40iN/TIf8@t7H6l5YLQamdWo8lK7l/8Y2fTX707HNb1Bjp6xa@VPjcnKZ8rbfiNqu3wp3alr1m@Vldn275tPCX3lrCLW8yrbrD@ouUVd@r6wtV@cBba2tI5U@qWkj1hMYaCsM5BaV@om52Xdq3pMld0lSvdWE8f2KnYIP8AjYWtd/SOGabzzJyUbUuD2ppdtvFweSpmVfw8GxGdGPZDkX0BRO@MUmuNFUYjb4LWwJ/5Luj9bXq60lmep4av9Plr/BkiYwy9gFNqiWq4pAt01MZLLQyvMEhjmO18kJlDKA0NWiCR5obPY70wLJx1hwU6FULwVAocGIXMhJQYE4mDI5dykYgwMMosEWmCvEgSGZZYkgkRpmkfTpgKnkmJUqnEJQIZl696ctLiUiZ4RIoaxnROB3u64U@8jmk1C82fDDa8Df/hBvsY0ideTWk7pnWwn3Bpmg0BMqsMO7h6O7R@Cwq0iUIN3kpjx/vRESEkgqKAaF8U@zHj4zymbxh/KysAfwEu8KqOqAlHNAIIu@Dr3s8F@2/UaGD/hXjHj@DJ7BFQREH3MxBOQYMf09Fxo5HRR4BMHkE3@H7w2KKOTt3RIj8VhkXQu/CqJx7T12aelX1f4xt7w6OpjCye8ftqWw7@sYbNYCvfdBZ25RYIxKDJznX2gXAgVedcXXli9Pv14P0s3VBz@F22248wYf9nvif40A//AA "Python 3.8 (pre-release) – Try It Online")
**Input must be rectangular.**
What a mess. The ungolfed version (with long variable names) was a nice 2700 bytes (or so), but I have golfed it down so much that it's down to 524.
Brute-force method. We try to start at every point: for every character that is either a pipe or an underscore, we determine whether:
* it is possible to start at the top of that character if it is a pipe, or the left if it is an underscore, and follow the path of the art (recursively calling the function to move forward, and if there are two or more directions possible, try all of them) until all lines are used up and no line is used more than once; or
* the same is possible with the bottom if pipe, or right if underscore.
When trying to move forward, we store all possible connections according to which character we are currently at and which side of that character we are at, and we use all the connections that are not yet used. If there are none, then it is not possible to draw in one stroke.
] |
[Question]
[
The [λ-calculus](https://en.wikipedia.org/wiki/Lambda_calculus#Formal_definition), or lambda calculus, is a logical system based on anonymous functions. For example, this a λ-expression:
```
λf.(λx.xx)(λx.f(xx))
```
However, for the purposes of this challenge, we'll simplify the notation:
* Change `λ` to `\` (to make it easier to type): `\f.(\x.xx)(\x.f(xx))`
* The `.` in lambda headers is unnecessary, so we can drop it: `\f(\xxx)(\xf(xx))`
* Use the [Unlambda](https://esolangs.org/wiki/Unlambda)-style prefix notation with ``` for application rather than writing the two functions together (for a full explanation of how to do this, see [Convert between Lambda Calculus Notations](https://codegolf.stackexchange.com/q/110011/61384)): `\f`\x`xx\x`f`xx`
* This is the most complicated substitution. Replace each variable with a number in brackets based on how deeply nested the variable is relative to the lambda header it belongs to (i.e. use 0-based [De Bruijn indexing](https://en.wikipedia.org/wiki/De_Bruijn_index)). For example, in `\xx` (the identity function), the `x` in the body would be replaced with `[0]`, because it belongs to the first (0-based) header encountered when traversing the expression from the variable to the end; `\x\y``\x`xxxy` would be converted into `\x\y``\x`[0][0][1][0]`. We can now drop the variables in the headers, leaving `\\``\`[0][0][1][0]`.
Combinatory logic is basically a [Turing Tarpit](https://esolangs.org/wiki/Turing_tarpit) made out of the λ-calculus (Well, actually, it came first, but that's irrelevant here.)
"Combinatory logic can be viewed as a variant of the lambda calculus, in which lambda expressions (representing functional abstraction) are replaced by a limited set of combinators, primitive functions from which bound variables are absent."1
The most common type of combinatory logic is the [SK combinator calculus](https://en.wikipedia.org/wiki/SKI_combinator_calculus), which uses the following primitives:
```
K = λx.λy.x
S = λx.λy.λz.xz(yz)
```
Sometimes a combinator `I = λx.x` is added, but it is redundant, as `SKK` (or indeed `SKx` for any `x`) is equivalent to `I`.
All you need is K, S, and application to be able to encode any expression in the λ-calculus. As an example, here's a translation from the function `λf.(λx.xx)(λx.f(xx))` to combinatory logic:
```
λf.(λx.xx)(λx.f(xx)) = S(K(λx.xx))(λf.λx.f(xx))
λx.f(xx) = S(Kf)(S(SKK)(SKK))
λf.λx.f(xx) = λf.S(Kf)(S(SKK)(SKK))
λf.S(Sf)(S(SKK)(SKK)) = S(λf.S(Sf))(K(S(SKK)(SKK)))
λf.S(Sf) = S(KS)S
λf.λx.f(xx) = S(S(KS)S)(K(S(SKK)(SKK)))
λx.xx = S(SKK)(SKK)
λf.(λx.xx)(λx.f(xx)) = S(K(S(SKK)(SKK)))(S(S(KS)S)(K(S(SKK)(SKK))))
```
Since we are using the prefix notation, this is ````S`K``S``SKK``SKK``S``S`KSS`K``SKK``.
1 Source: [Wikipedia](https://en.wikipedia.org/wiki/Combinatory_logic#Combinatory_logic_in_computing)
## The Challenge
By now, you've probably guessed what is: Write a program that takes a valid λ-expression (in the notation described above) as input and outputs (or returns) the same function, rewritten in SK-combinator calculus. Note that there are an infinite number of ways to rewrite this; you only need to output one of the infinite ways.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid submission (measured in bytes) wins.
## Test Cases
Each test case shows one possible output. The expression on top is the equivalent λ-calculus expression.
```
λx.x:
\[0] -> ``SKK
λx.xx:
\`[0][0] -> ```SKK``SKK
λx.λy.y:
\\[0] -> `SK
λx.λy.x:
\\[1] -> K
λx.λy.λz.xz(yz):
\\\``[2][0]`[1][0] -> S
λw.w(λx.λy.λz.xz(yz))(λx.λy.x):
\``[0]\\[1]\\\``[2][0]`[1][0] -> ``S``SI`KS`KK
```
[Answer]
## Haskell, ~~251 237 222~~ 214 bytes
15 bytes saved thanks to @Ørjan\_Johansen (also see his TIO links in the remarks)!
8 more bytes saved thanks to @nimi!
```
data E=S|K|E:>E|V Int
p(h:s)|h>'_',(u,a)<-p s,(v,b)<-p u=(v,a:>b)|h>'['=a<$>p s|[(n,_:t)]<-reads s=(t,V n)
a(e:>f)=S:>a e:>a f
a(V 0)=S:>K:>K
a(V n)=K:>V(n-1)
a x=K:>x
o(e:>f)='`':o e++o f
o S="S"
o K="K"
f=o.snd.p
```
`p` parses the input, returning the remaining unparsed part in the first component of the resulting pair. The first character of its argument must be a backtick, a backslash or an opening bracket. The pattern guards of `p` check these cases in this order. In the first case, denoting an application, two more expressions are parsed and combined to an element of the `E` data type with the infix constructor `:>`. In the lambda case, the following expression is parsed and immediately given to the `a` function. Otherwise it is a variable, we get its number with the `reads` function (which returns a list) and drop the closing bracket by pattern matching with `(_:t)`.
The `a` function does the quite well known bracket abstraction. To abstract an application, we abstract the two subexpressions and use the `S` combinator to distribute the argument to both. This is always correct, but with more code we could [do much better](https://codegolf.stackexchange.com/q/105991/56725) by handling special cases in order to get shorter expressions. Abstracting the current variable gives `I` or, when we don't have that, `SKK`. Usually the remaining cases can just add a `K` to the front, but when using this notation we have to renumber the variables as the inner lambda is abstracted.
`o` turns the result to a string for output. `f` is the complete function.
As in many languages, backslash is an escape character, so it has to be given twice in a string literal:
```
*Main> f "\\[0]"
"``SKK"
*Main> f "\\`[0][0]"
"``S``SKK``SKK"
*Main> f "\\\\[0]"
"``S``S`KS`KK`KK"
*Main> f "\\\\[1]"
"``S`KK``SKK"
*Main> f "\\\\\\``[2][0]`[1][0]"
"``S``S`KS``S``S`KS``S`KK`KS``S``S`KS``S``S`KS``S`KK`KS``S``S`KS``S`KK`KK``S`KK``SKK``S``S`KS``S``S`KS``S`KK`KS``S`KK`KK``S`KK`KK``S``S`KS``S``S`KS``S`KK`KS``S``S`KS``S`KK`KK``S``S`KS`KK`KK``S``S`KS``S``S`KS``S`KK`KS``S`KK`KK``S`KK`KK"
```
] |
[Question]
[
In Magic: the Gathering, mages (known as "planeswalkers") battle each other by casting spells. Spells cost mana. Five colors of mana exist: White, Blue, Black, Red, and Green, represented as {W}, {U}, {B}, {R}, and {G}, respectively.
A spell's cost is slightly more complex. The cost can be any combination of the following:
* One or more colors
* One or more colorless, represented as {X}, where X is a positive integer
* One or more hybrids, represented as {Y/Z}, where Y and Z are either a color (represented by one of the five letters) or colorless, represented by a positive integer
The following rules apply when attempting to cast a spell:
* A color in a cost must be satisfied by one mana of that color
* A colorless cost {X} may be satisfied by X mana of any color
* A hybrid cost {Y/Z} may be satisfied by satisfying either Y or Z
+ Note that braces are not nested
+ Y and Z are not hybrid
Write a program or function that, given a pool of mana and a cost, prints or returns true (or some truthy value) if and only if the mana in that pool can satisfy the cost, else false (or some falsy value).
A mana pool is a non-empty string of the format:
```
Color1,Color2,Color3,...,Colorn-1,Colorn
```
A cost is a non-empty string of the format:
```
Cost1,Cost2,Cost3,...,Costn-1,Costn
```
**Examples**
In the format `Pool Cost -> ExpectedOutput` (with a space between Pool and Cost):
```
{R},{R},{G},{B},{R} {4},{R} -> True
{G},{G},{G},{G},{W},{W},{W} {2/W},{2/U},{2/B},{2/R},{2/G} -> False
{G},{G},{R} {R/G},{G/B},{B/R} -> True
{R},{R},{R},{G} {1},{G},{2/G}-> True
{R} {R},{R},{R},{R},{R} -> False
{W},{R},{R} {2/W},{W/B} -> True
{U},{U} {1} -> True
{W},{R},{G} {1},{2} -> True
```
[Answer]
# Pyth, ~~55~~ ~~53~~ ~~52~~ 50 bytes
```
FN*Fmsm?k}kG^Gvkcd\/ceKc-rz0`Hd\,#=sN)I!.-NhK1B)E0
```
Try it online: [Demonstration](https://pyth.herokuapp.com/?code=FN*Fmsm%3Fk%7DkG%5EGvkcd%5C%2FceKc-rz0%60Hd%5C%2C%23%3DsN)I!.-NhK1B)E0&input=%7BW%7D%2C%7BR%7D%2C%7BR%7D+%7B2%2FW%7D%2C%7BW%2FB%7D&debug=0) or [Test harness](https://pyth.herokuapp.com/?code=zFz.zp%22%20%3D%3E%20%22zFN*Fmsm%3Fk%7DkG%5EGvkcd%5C%2FceKc-rz0%60Hd%5C%2C%23%3DsN)I!.-NhK1B)E0&input=Test-Cases%3A%0A%7BR%7D%2C%7BR%7D%2C%7BG%7D%2C%7BB%7D%2C%7BR%7D%20%7B4%7D%2C%7BR%7D%0A%7BG%7D%2C%7BG%7D%2C%7BR%7D%20%7BR%2FG%7D%2C%7BG%2FB%7D%2C%7BB%2FR%7D%0A%7BR%7D%2C%7BR%7D%2C%7BR%7D%2C%7BG%7D%20%7B1%7D%2C%7BG%7D%2C%7B2%2FG%7D%0A%7BR%7D%20%7BR%7D%2C%7BR%7D%2C%7BR%7D%2C%7BR%7D%2C%7BR%7D%0A%7BW%7D%2C%7BR%7D%2C%7BR%7D%20%7B2%2FW%7D%2C%7BW%2FB%7D%0A%7BU%7D%2C%7BU%7D%20%7B1%7D%0A%7BW%7D%2C%7BR%7D%2C%7BG%7D%20%7B1%7D%2C%7B2%7D&debug=0)
Notice that the time and memory complexity is really bad. So the second example doesn't work. I allocates about 1.6 GB of Ram before it crashes on my machine.
### Explanation
The explanation is for the 53 solution. The only difference is, that the initial parsing happens in the middle instead of the beginning.
```
Kc-rz0"{}"dFN*Fmsm?k}kG^Gvkcd\/ceKc-rz0`H\,#=sN)I!.-NhK1B)E0
```
So here's the initial parsing.
```
Kc-rz0`Hd
rz0 convert input() to lowercase
- `H remove all curly brackets (`H = "{}")
c d split at the space
K assign to K
```
So the input `"{W},{R},{R} {2/W},{W/B}"` gets converted into `['w,r,r', '2/w,w/b']`.
```
m ceK\, map each cost d of the costs split by "," to:
s the sum of
m cd\/ map each value k of cost split by "/" to:
k k
? }kG if k in "abcdef...xyz" else
^Gvk Cartesian product with "abc...yz" of int(k) repeats
```
So what does this do? The cost input `'2/w,w/b'` gets converted into:
```
[['aa', 'ab', 'ac', ..., 'zx', 'zy', 'zz', 'w'], 'wb']
```
Every string in `['aa', 'ab', 'ac', ..., 'zx', 'zy', 'zz', 'w']` satisfies `{2/W}` and every char in `'wb'` satisfies `{w/b}`.
Now we generate the Cartesian product of these lists (or strings) and see, if any combination can be produced with the mana-pool.
```
FN*F... ) for N in Cartesian product of ...:
# ) while 1:
=sN N = sum(N)
this flattens N
I!.-NhK if not (subtract mana pool from N):
1 print 1 (True)
B break
E else:
0 print 0 (False)
```
[Answer]
# Python 2.7, 412 characters
```
import re,collections as C
r,C=re.findall,C.Counter
def g(m,h,c,v):
try:return t(m,h,c+int(v))
except:
if m[v]:return t(m-C({v:1}),h,c)
def t(m,h,c):return any(g(m,h[1:],c,v)for v in h[0].split('/'))if h else sum(m.values())>=c
def f(m,c):m=C(r(r'\w',m));c=[filter(None, x)for x in zip(*r(r'(\w+/\w+)|(\d+)|(\w)',c))];m.subtract(C(c[2]));print all(x>=0 for x in m.values())*t(m,c[0],sum(int(x)for x in c[1]))
```
The function `f` is the one that does the check. It takes the mana pool and cost as string arguments, and prints `1` when the mana satisfies the cost and `0` otherwise. For example, `f('{R},{R},{G},{B},{R}', '{4},{R}')` prints `1`.
Ungolfed, it basically looks like this
```
import re
from collections import Counter
def helper(mana, hybrids, colorless, option):
try:
option = int(option) # See if option is an integer
# For colorless hybrid, just add the value to the colorless amount
# to check at the end.
return check_hybrids(mana, hybrids, colorless + option)
except ValueError: # Option is a mana letter
# For colored hybrid costs, check if any of that color is
# available, then try to pay the rest of the cost with 1 less
# of that color.
if mana[option] >= 0:
return check_hybrids(mana - Counter({option: 1}), hybrids, colorless)
else:
return False
def check_hybrids(mana, hybrids, colorless):
'''Check whether the given mana pool can pay the given hybrid costs and colorless costs'''
if hybrids:
# For each option in the first hybrid cost, check whether the
# rest of the cost can be paid after paying that cost
return any(helper(mana, hybrids[1:], colorless, option) for option in hybrids[0].split('/'))
else:
# When there are no remaining hybrid costs, if there is enough
# remaining mana to pay the colorless costs, we have success
return sum(m.values()) > colorless
def can_cast(mana_str, cost_str):
mana = Counter(re.findall(r'\w', mana_str))
# transpose to get separate lists of hybrid, colorless, and colored symbols
cost = zip(*re.findall(r'(\w+/\w+)|(\d+)|(\w)',cost_str))
cost = [filter(None, sublist) for sublist in cost] # Remove unfound symbols
mana.subtract(Counter(cost[2]))
# After subtracting the single-colored cost from the mana pool, if
# anything in the mana pool is negative, we didn't have enough to
# pay for that color.
if any(x <=0 for x in mana.values()):
return False
return check_hybrids(mana, cost[0], sum(int(x)for x in cost[1]))
```
] |
[Question]
[
Given an input of a note, output an ASCII drawing of the corresponding major
key on the treble clef.
Here are all the major keys (that don't include double-sharps or double-flats)
and their corresponding key signatures:

*Circle of fifths deluxe 4* by Wikipedia user Just plain Bill, copyright CC BY-SA 3.0
If the input is a key with sharps, draw the following ASCII art with the
appropriate number of sharps:
```
#
-#-------
#
----#----
#
-------#-
#
---------
---------
```
And if the input is a key with flats:
```
---------
b
----b----
b
-b-------
b
-----b---
b
---------
```
Here is a concise summary of the possible inputs as well as how many sharps or
flats they use:
```
0 1 2 3 4 5 6 7
# C G D A E B F# C#
b C F Bb Eb Ab Db Gb Cb
```
All five lines of dashes must always be drawn, but there may be any number of
dashes per line such that the sharps or flats have at least one column of
padding on each side, as long as each line of dashes has the same length. For
example, these are all also acceptable outputs for the input `Ab`:
```
--------- ------ --------- ----------------
b b b b
----b---- ----b- -------b- ------b---------
-b------- -b---- ----b---- ---b------------
b b b b
--------- ------ --------- ----------------
--------- ------ --------- ----------------
```
In the case of C major, which has no sharps nor flats, any positive number of dashes per
line (even one) is acceptable.
Any amount of leading or trailing whitespace is fine, as are trailing spaces on
each line. Extra leading spaces are okay as long as there are the same number
on each line.
You may take input in lowercase or require that inputs without a sharp or flat contain a trailing space, if you so desire.
Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest solution in bytes will win.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~206 197 178 175 168~~ 161 bytes
*Thanks to Mr. Xcoder for -12 bytes!*
This is a function which returns the result as a 2D list of characters. If the input does not contain a sharp/flat, it should be padded with a space.
```
def f(k,r=range(10)):n="CGDAEB".find(k[0])+7*' #'.find(k[1]);return[[(' -'[i%2],'b#'[n>0])[0<j<=abs(n)and`i`==(n*"1403625"+"5263748")[j-1]]for j in r]for i in r]
```
**[Try it online!](https://tio.run/##RU/LboMwELzzFZZRtd6EREBeVRoqtSTtD/TmWgoUkxqiBTnkwNdTnLbKHmZnd2YO0/bdd0PxMBS6ZKWoA5vYjE5aRCHilhKevu9fDq98XhoqRC1DhdPNBJgP/59I4ZPV3dWSlALYDKR5iFUAuQ@Snke/DHfVLsnyiyDMqDiaY5IImvBoGS7W8YpP@SpeLzbLR46ymkVKlY1lFTPE7I2aXzr47ENfOkMn9tUU2vOcVuveqYbaaydw67FxWmuoc8r9EvBJMK8aQwL@9hld/uzSY23dI@LdP8CbDwGDlDnc3zDN4Qc "Python 2 – Try It Online")**
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 60 bytes
```
≔⁻⁺⊖﹪⊗℅§θ¬χ⁷×⁷№θ#×⁷№θbθ←UO⁹¦⁹-¶Fθ«Jι⊖﹪⊕׳ι⁷#»F±θ«Jι⊕﹪⁺³×⁴ι⁷b
```
[Try it online!](https://tio.run/##dZBNawJBDIbP7q8Y1ksWRrAoSOtJ9KK46sFjL/sRtwOzE3d2Rgqlv33MupaWoiEE8sGTNyk@MltQpkNYtK2qDKTK@BYOmsMKC4s1GoclpFR6TbAin2tO97ZUJtOwcGtT4ic0UuzIwcs4YZNi1oWjqrGFmRRL8sZ1I/EwTp508r7TJPMopQvC2xZPjpN9rslU8CoFezx6NzEXT2QFNIn4igYbX5@PBEqKB2rX5rfU75xIoe4CmTM4WMX7O1nz6LvH7rDKHDL9H/4v646/PWnyc870ITq/oUNYDsPooq8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⁻⁺⊖﹪⊗℅§θ¬χ⁷×⁷№θ#×⁷№θbθ
```
Calculate the number of sharps in the key signature.
```
←UO⁹¦⁹-¶
```
Print the stave, but one square left of the origin so that the first sharp/flat is in column zero.
```
Fθ«
```
Loop over any sharps.
```
Jι⊖﹪⊕׳ι⁷#»
```
Calculate the row of the sharp and print it.
```
F±θ«
```
Loop over any flats.
```
Jι⊕﹪⁺³×⁴ι⁷b
```
Calculate the row of the flat and print it.
[Answer]
# Befunge, 139 bytes
```
~9%:4%7*+4/7%~6%1-2/7*+vv\`0:\!-g02+*2g00+1%7+g00*+3g00::<<0+55p02:_@
- b#09p01*-1*2p00:`0:-8<>10g`!**:00g2+*\!20g2%*+1g,1+:8`!#^_>$,:1-\^1
```
[Try it online!](http://befunge.tryitonline.net/#code=fjklOjQlNyorNC83JX42JTEtMi83Kit2dlxgMDpcIS1nMDIrKjJnMDArMSU3K2cwMCorM2cwMDo6PDwwKzU1cDAyOl9ACi0gYiMwOXAwMSotMSoycDAwOmAwOi04PD4xMGdgISoqOjAwZzIrKlwhMjBnMiUqKzFnLDErOjhgISNeXz4kLDoxLVxeMQ&input=QyMK)
Note that the input is expected to be terminated with a linefeed, as would typically occur when running the program interactively.
**Explanation**
We start by reading two characters from stdin - the main note, *n*, and an accidental, *a* (which can be a linefeed if there is no accidental). Using those values, we calculate the key signature number, *signum*, as follows:
```
signum = (n%9 + n%9%4*7)/4%7 + (a%6 - 1)/2*7 - 8
```
This returns a value in the range -7 to 7, where the sign tells us whether we need sharps or flats (positive or negative), and the absolute value gives us the number of sharps or flats required. So for later use, we extract the sign, *s*, and the the accidental count, *cnt*, with:
```
s = (signum > 0)
cnt = abs(signum)
```
Then we have two nested loops, iterating a row number, *r*, from 9 down to 0, and a column number, *c*, from 0 up to 8. For a particular row and column, we calculate whether an accidental should be visible at that point with:
```
accidental = (r == (c*(s+3) + s)%7 + 1 + s*2) and (c > 0) and (c <= cnt)
```
If it's not an accidental, we need to output a line or space depending on whether the row, *r*, is odd or even. And if it is an accidental, we need to output a sharp or flat depending on the sign, *s*. So we evaluate the following formula:
```
index = (!accidental * (r%2)) + (accidental * (s+2))
```
Which gives us an index in the range 0 to 3, representing either a line, a space, a flat or a sharp. We simply use that index to lookup the required output character from a table, which you can see embedded at the start of the second line of code.
] |
[Question]
[
# The Challenge
Given a rectangular grid of characters
```
A B C D E
F G H I J
K L M N O
P Q R S T
```
and a grid with the same dimensions of dots and spaces
```
. . .
. . .
. .
. . .
```
Output the string which is generated by following the dots through the grid starting in the upper left corner. This example would yield `ABGLQRSNIJE`
## Notes
* You may take the input grids as 2D-arrays or the closest alternative in your language instead of a multiline string.
* You may use the NULL value of your language instead of spaces. But you have to use dots to mark the path.
* You don't need to separate dots on the same line with spaces. I just added them for readability.
* The smallest possible grid has the size 1x1.
* The start and end dot will have only one neighbour. The dots between them will always have exact two vertical or horizontal neighbours. This guarantees that the path is unambiguously.
* The path will not go diagonal.
* The characters in the grid will be either all upper- or lowercase characters in the range `[a-z]` whatever is most convenient for you.
* The path will always start in the upper left corner.
# Rules
* Function or full program allowed.
* [Default rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) for input/output.
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so lowest byte-count wins. Tiebreaker is earlier submission.
# Test cases
### Grid #1
```
A B C A B C W
D E F G H U Q
X L U S D Q Z
A S U K W X I
W U K O A I M
A I A I O U P
```
```
. .
. . .
.
. . . .
.
.
=> ABEFGSKUSAWA
```
```
. . . . . . .
.
. . . .
. . . .
. .
. . . . . . .
=> ABCABCWQZIMPUOIAIAWAXLUUK
```
### Grid #2
*Note the triple spaces in the second lines of the first and second examples.*
```
A B
C D
```
```
.
=> A
```
```
. .
=> AB
```
```
.
. .
=> ACD
```
### Grid #3
```
A
```
```
.
=> A
```
**Happy Coding!**
[Answer]
# APL, 63 bytes
```
{⍺[(⊂1 1){×≢⍵:⍺,(V/⍵)∇⍵/⍨~V←(+=⌊/)+/¨2*⍨⍺-⍵⋄⍺}1↓(,⍵='.')/,⍳⍴⍵]}
```
This is a function that takes two character matrices (they must be matrices), the character grid as its left argument and the dots grid as its right argument. The matrix of dots may be smaller than the matrix of characters.
Explanation:
* `(,⍵='.')/,⍳⍴⍵`: get the positions of the dots, in row-column order
* `1↓`: drop the first one (it is known to be at `1 1`)
* `(⊂1 1){`...`}`: starting from `1 1`, run the following function, which follows the path (its left argument is its current position, its right argument are unvisited positions). It works by selecting the nearest unvisited dot each time. (If the assumptions from the question hold, this is correct.)
+ `×≢⍵:`: if there are still unvisited positions:
- `+/¨2*⍨⍺-⍵`: find the Manhattan distance between each position and the current position
- `V←(+=⌊/)`: for each position, see if its distance is equal to the smallest distance, and store this in `V`.
- `⍵/⍨~`: select all positions for which this is not the case, these are the fields to visit next
- `(V/⍵)`: find the position for which it *is* the case, this will be the next field
- `∇`: run the function again with these new arguments
- `⍺,`: the result is the current position, followed by the result of doing this for the rest of the list
+ `⋄⍺`: otherwise, just return the current position and stop (it's the last one)
* `⍺[`...`]`: for each position, select the corresponding element in the character grid.
Test cases:
```
f←{⍺[(⊂1 1){×≢⍵:⍺,(V/⍵)∇⍵/⍨~V←(+=⌊/)+/¨2*⍨⍺-⍵⋄⍺}1↓(,⍵='.')/,⍳⍴⍵]}
⍝ example
g0 ← 4 5⍴'ABCDEFGHIJKLMNOPQRST'
d0 ← 4 5⍴'.. . . .. . . ... '
⍝ test case 1
g1 ← 6 7⍴'ABCACBWDEFGHUQXLUSDQZASUKWXIWUKOAIMAIAIOUP'
d1a ← 6 7⍴'.. ... . .... . . '
d1b ← 6 7⍴'....... .... .. .. .. ........'
⍝ test case 2
g2 ← 2 2⍴'ABCD'
d2a ← 1 1⍴'.'
d2b ← 1 2⍴'..'
d2c ← 2 2⍴'. ..'
⍝ test case 3
g3 ← 1 1⍴'A'
d3 ← 1 1⍴'.'
g0 f d0
ABGLQRSNIJE
(⊂g1) f¨ d1a d1b
┌────────────┬─────────────────────────┐
│ABEFGSKUSAWA│ABCACBWQZIMPUOIAIAWAXLUUK│
└────────────┴─────────────────────────┘
(⊂g2) f¨ d2a d2b d2c
┌─┬──┬───┐
│A│AB│ACD│
└─┴──┴───┘
g3 f d3
A
```
[Answer]
# JavaScript (ES6), 122 bytes
```
c=>g=>c[l=~c.search`
`,i=p=0]+[...g].map(_=>i|!p?c[i=(d=n=>g[i-n-p?i-n:c]>" "&&(p=i)-n)(1)||d(-1)||d(l)||d(-l)]:"").join``
```
## Explanation
Takes the grids as multiline strings.
Feels like a decent attempt but I ran out of time while golfing so it could probably be improved.
```
var solution =
c=>g=>
c[ // add the starting letter to the output
l=~c.search`
`, // l = line length
i=p=0 // i = current index, p = previous index
]+
[...g].map(_=> // loop
i|!p? // if we have not finished yet
c[i= // find the next index and return it's letter
(d=n=> // d = function to check for a dot at offset n
g[
i-n-p?i-n // if i - n != p, get the character at index i - n
:c // else get index "c" (will return undefined, not a dot)
]>" " // if the character is a dot
&&(p=i)-n // set p to i and return i - n
)
(1)||d(-1)||d(l)||d(-l) // search for the next adjacent dot
]
:"" // if we have finished, return no letter
)
.join`` // output all the returned letters
```
```
<textarea id="Characters" rows="6" cols="30">ABCABCW
DEFGHUQ
XLUSDQZ
ASUKWXI
WUKOAIM
AIAIOUP</textarea>
<textarea id="Grid" rows="6" cols="30">.......
.
... .
. .. .
. .
.......</textarea><br />
<button onclick="result.textContent=solution(Characters.value)(Grid.value)">Go</button>
<pre id="result"></pre>
```
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 43 bytes
```
{⍺[11 9∘○¨{⍵∪⍺∩∊⍵+⊂0j1*⍳4}⍣≡∘⊃⍨0j1⊥¨⍸⍵=⊃⍵]}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQb/04Bk9aPeXdGGhgqWjzpmPJrefWgFUGDro45VQOFHHSsfdXQBudqPupoMsgy1HvVuNql91Lv4UedCkOqu5ke9K4Dij7qWHlrxqHcHUKUtWHBrbO3//@qOTq5u7sHeocGO4Y7qCsgAqF/DTMH8Ue8WoCJnIAp3ASr1CA2M8AkNdgmMcgwO9Q6P8AwP9fZ39PR19HT09A8NUNdMU4Bq0tODmKMHZ0A4elAmglLngtkQGOXpGxDqDzQL6BygPaHe6pQ7Q09PD8ktEFeAkAJUFKpCT51LQ0fdUV0TZKORghHURheQWVCuHsyx6pDgwaFKD6IKKIhPlQKqjY96V4GYaSBaTx0A "APL (Dyalog Classic) – Try It Online")
] |
[Question]
[
# **TASK**
The goal is to write a program that rotates any two-dimensional list by 45 degrees, it must be able to do this up to 7\*45 (at once) before returning the list. The list will not necessarily be square or rectangular. You must include output for the examples in your answer. It must also work for cases that are not in the examples... circles, triangles etc. You cannot use a pre-existing function to do the whole thing.
All lists will have at least one axis of symmetry (N,S,E,W). All sublists are to be assumed as center-aligned. Odd-even lists will shift to the left one to align properly. See example 4 for gaps in the middle of a sublist.
## INPUT
Your program will use a variable named `l` containing the list, and a variable named `n` specifying the amount the list will be rotated (n\*45) (`n` will always be less than 7, and can be 0). It will have to accept `l` containing sublists of any printable data type (decimal, List, int, String[].. etc), but sublists will only contain one data type at a time.
You do not need to accept console input or use stdin. The lines specifying the test values of `l` and `n` are not included in the character count, but must be included in the submitted code.
## OUTPUT
Your program must print the list in the correct orientation, NIL can be used to pad lists if you desire, but padding is not necessary (you get a smiley face if they are padded, though). Sub-lists do not have to be indented or separated by newlines as in the examples.
## EXAMPLES
1
```
IN
l=
[[0 , 1 , 2],
[3 , 4 , 5],
[6 , 7 , 8]]
n=1
OUT
[ [0],
[3 , 1],
[6 , 4 , 2],
[7 , 5],
[8] ]
```
2
```
IN
l=
[[a , b , c , d],
[e , f , g , h]]
n=2
OUT
[[e , a],
[f , b],
[c , g],
[h , d]]
```
3
```
IN
l=
[[A , B , C , D , E , F],
[G , H , I , J],
[K , L],
[0 , 8],
[M , N],
[O , P , Q , R],
[S , T , U , V , W , X]]
n=7
OUT
[ [F],
[E],
[D , J],
[C , I],
[B , H , L],
[A , G , K , 8],
[0 , N , R , X],
[M , Q , W],
[P , V],
[O , U],
[T],
[U] ]
```
4
```
IN
l=
[[9 , 8 , 7 , 6],
[5],
[4 , 3 , 2 , 1],
[0] ]
n=3
OUT
[ [0 , 4],
[3],
[2 , 5 , 9],
[1 ,NIL, 8],
[7],
[6], ]
```
5
```
IN
l=
[ [Q],
[X ,NIL, Y],
[Z] ]
n=2
OUT
[ [X],
[Z ,NIL, Q],
[Y] ]
```
[Answer]
# Python – ~~234~~ 201
```
# example for defining lists and n
l=[[1,2,3,4],
[5],
[6,7,8,9]]
n=1
# counting code
j=1j
m=max(map(len,l))+len(l)
M=range(-m,m)
e=enumerate
d=[[v for x in M for i,u in e(l)for k,v in e(u)if[1,1+j,j,j-1,-1,-j-1,-j,1-j][n]*(k-(len(u)-1)/2+j*i)==x+y*j]for y in M]
print[x for x in d if x]
```
**Ungolfed Version**
```
rotation = [1,1+1j,1j,1j-1,-1,-1j-1,-1j,1-1j][n]
m = max(map(len,l))+len(l)
output = []
for y in range(-m,m):
line = []
for x in range(-m,m):
for i,sublist in enumerate(l):
for k,entry in enumerate(sublist):
if rotation * ( k-(len(sublist)-1)/2 + i*1j ) == x + y*1j:
line += [entry]
if line != []:
output += [line]
print output
```
This uses that multiplication (of a complex number) by a complex number corresponds to rotating and stretching. `[1,1+1j,1j,1j-1,-1,-1j-1,-1j,1-1j]` are complex numbers corresponding to the required angles and using the smallest scaling factor such that for an integer complex input the output is again integer complex.
] |
[Question]
[
## Background
Python 3 has many types of string literals. For example, the string `this 'is' an exa\\m/ple` can be represented as:
```
'this \'is\' an exa\\\\m/ple'
"this 'is' an exa\\\\m/ple"
r"this 'is' an exa\\m/ple"
'''this 'is' an exa\\\\m/ple'''
"""this 'is' an exa\\\\m/ple"""
r'''this 'is' an exa\\m/ple'''
r"""this 'is' an exa\\m/ple"""
```
As you can see, using different delimiters for strings can lengthen or shorten strings by changing the escaping needed for certain characters. Some delimiters can't be used for all strings: `r'` is missing above (see later for explanation). Knowing your strings is very useful in code golf.
One can also combine multiple string literals into one:
```
'this \'is\' an ''''exa\\\\m/ple'''
"this 'is' an "r'exa\\m/ple'
```
---
## Challenge
The challenge is, given a printable ASCII string, to output its *shortest* literal representation in Python.
### Details on string mechanics
Strings can be delimited using `'`, `"`, `'''` and `"""`. A string ends when the starting delimiter is hit again unescaped.
If a string literal starts with `'''` or `"""` it is consumed as the delimiter. Otherwise `'` or `"` is used.
Characters can be escaped by placing a `\` before them. This inserts the character in the string and eliminates any special meaning it may have. For example, in `'a \' b'` the middle `'` is escaped and thus doesn't end the literal, and the resulting string is `a ' b`.
Optionally, one of `r` or `R` may be inserted before the starting delimiter. If this is done, the escaping `\` will appear in the result. For example, `r'a \' b'` evaluates to `a \' b`. This is why `a ' b` cannot be delimited by `r'`.
To escape `'''` or `"""`, one only needs to escape one of the characters.
These literals can be concatenated together, which concatenates their contents.
### Rules
* The input is the string to golf. Printable ASCII only, so no newlines or other special characters.
* The output is the golfed string literal. If there are multiple solutions, output one.
* To simplify the challenge, in non-`r` strings any escapes except for `\\`, `\'` and `\"` are considered invalid. They must not be used in the output, even though `'\m'` is equal to `'\\m'` in Python. This removes the need to process special escape codes such as `\n`.
* Builtins for golfing Python strings are disallowed. Python's `repr` is allowed, since it's crappy anyway.
* Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply.
## Example inputs/outputs
I tried my best to verify these, but let me know if there are mistakes. If there are multiple valid outputs to the cases, they are all listed below the input.
```
test
-> 'test'
-> "test"
te\st
-> 'te\\st'
-> "te\\st"
-> r'te\st'
-> r"te\st"
te'st
-> "te'st"
te"st
-> 'te"st'
t"e"s't
-> 't"e"s\'t'
te\'st
-> "te\\'st"
-> r'te\'st'
-> r"te\'st"
te\'\"st
-> r'te\'\"st'
-> r"te\'\"st"
t"'e"'s"'t"'s"'t"'r"'i"'n"'g
-> """t"'e"'s"'t"'s"'t"'r"'i"'n"'g"""
-> '''t"'e"'s"'t"'s"'t"'r"'i"'n"'g'''
t"\e"\s"\t"\s'\t"\r"\i"\n"\g
-> r"""t"\e"\s"\t"\s'\t"\r"\i"\n"\g"""
-> r'''t"\e"\s"\t"\s'\t"\r"\i"\n"\g'''
t"""e"""s"""'''t'''s'''"""t"""r"""'''i'''n'''g
-> 't"""e"""s"""'"'''t'''s'''"'"""t"""r"""'"'''i'''n'''g"
t\"""e\"""s\"""'''t'''s'''\"""t\"""r\"""'''i'''n'''g
-> r"""t\"""e\"""s\"""'''t'''s'''\"""t\"""r\"""'''i'''n'''g"""
t"e"s"t"s"t"r"i"n"g"\'\'\'\'\'\'\'\
-> r't"e"s"t"s"t"r"i"n"g"\'\'\'\'\'\'\'''\\'
-> r't"e"s"t"s"t"r"i"n"g"\'\'\'\'\'\'\''"\\"
"""t"'e"'s"'t"'s"'t"'r"'i"'n"'g'''
-> """\"""t"'e"'s"'t"'s"'t"'r"'i"'n"'g'''"""
-> '''"""t"'e"'s"'t"'s"'t"'r"'i"'n"'g''\''''
```
Thanks to [Anders Kaseorg](https://codegolf.stackexchange.com/a/132192/30164) for these additional cases:
```
\\'"\\'\
-> "\\\\'\"\\\\'\\"
''"""''"""''
-> '''''"""''"""'\''''
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~264~~ 262 bytes
```
f=lambda s,b='\\',r=str.replace:min(sum([['r'+d+s+d,d+r(r(s[:-1],b,b+b),d,d[1:]+b+d[0])+b*(s[-1:]in[b,d[0]])+s[-1:]+d][d in r(r(s+d[1:],b+b,'x'),b+d[0],b)or r(s,b+b,'')[-1:]==b:]for d in["'",'"',"'''",'"""']],[f(s[:k])+f(s[k:])for k in range(1,len(s))]),key=len)
```
[Try it online!](https://tio.run/##hVLdrtsgDL7PUyDfOAx6tGp3kbJH2AsAmkJDeqKmpAJ6dM7TdzZJt96NyMb48@cfyO2rvK/xx@Mx9ctw9eMgsvY9Wos69bmktxRuy3AK3XWObb5fW2MwoRpVVqMeVWpTm013ODrttVdeavKaY@eUV6P57qTy3yjgQJ45Gq/ZR87No0ZnRjFHUbOoyuMkGj9R6i2B9nJNFJA3AGVl9r3v3EQA0w0gaATUgFgtAHROm4k7u1A1Ni6dk0y41HpDPIf2qJdAM0nppL6Er55O8jFfb2sqYrrHU1nXJTdT/9d@W9L992k4vYf21xqDbCfZcM7MOQ2WkAvqhnZrqwUlYC5QXbBjQJbFHaVbrnhiDtothtovgAEwA4XvOgHOgBHwTDARapANYDNYMjKyTmBnsBHsFkQ8oHIAmW@EL6eQZL4krHyA9ERmkkhyfia3zGWVWb1w7RNNO/CPuhelCSk5S4IZIpy5fRrv5YP6g/Go9j/jcrecFywtKr5tlivhhm3K8sl1jaB1S3Ms9LAvBxSHnwKFEhM/eAWGnAO9dPgYlrZ6Rd@L3OzxIz0wyscf "Python 3 – Try It Online")
This works but is very slow without memoization, which you can add with
```
import functools
f=functools.lru_cache(None)(f)
```
It found an improved solution for one of the test cases:
```
t"e"s"t"s"t"r"i"n"g"\'\'\'\'\'\'\'\
-> 't"e"s"t"s"t"r"i"n"g"'r"\'\'\'\'\'\'\'"'\\'
-> r't"e"s"t"s"t"r"i"n"g"\'\'\'\'\'\'\'''\\'
```
Previous versions of this answer returned incorrect results on the following, which could be added as test cases:
```
\\'"\\'\
-> "\\\\'\"\\\\'\\"
''"""''"""''
-> '''''"""''"""'\''''
```
] |
[Question]
[
Here is a very simple language definition:
```
A Variable is any string that does not contain ^, <, >, !, or ?
The empty string is a valid variable identifier
The value of every variable starts at 0.
A Statement is one of (var is a Variable, P is a Program):
var^ -> changes var to be equal to 1 more than itself
var<P> -> while var > 0, changes var to be equal to 1 less than itself, then runs P
var! -> output value of var
var? -> ask for non-negative integer as input, increase var by that value
A Program is a concatenation of Statements, running a Program means running each Statement in order
```
Example programs (note that the empty string is a variable, but I will use it sparingly for the sake of clarity, and some variables are zeroed out in the program when they are usually 0 by default):
```
<>: sets the value of the empty string variable to 0
b<>b?b<a^>: asks for b, then adds the value stored in b to a, zeroing b in the process
b<>b?a<>b<a^>: asks for b, then sets a to the value of b, zeroing b in the process
a<>c<>b<a^c^>c<b^> : copies the value in b into a without zeroing it
b<>c<>a<c^c^c<b^>>b! : outputs a multiplied by 2
b^b<a<>a?a!b^> : outputs what you input, forever
```
Your goal is to write the smallest interpreter for this language.
1. The value of a variable can be arbitrarily large and should only be limited by the total memory your language has access to, in theory, but you are only required to handle values up to 2^256.
2. Your program should be able to handle arbitrarily long programs, in theory, but you will only be required to work on programs under 2^32 characters long. You are required to handle nested loops of depth up to 2^32 as well.
3. You can assume that the program is a valid program, and that you will only ever get non-negative integers when you ask for input. You can also assume that only ASCII printable characters are included in the input string.
4. The speed of the program you interpret doesn't matter, it will already be painfully slow for things as simple as 5-digit multiplication, without optimization.
5. If you want to use a language which cannot reasonably accept input or produce output in the way described by the language, use any interpretation you want to make it possible. This applies to any reason your language can't implement some required behavior. I want all languages to be able to compete.
6. Shortest program wins. Standard loopholes apply.
[Answer]
# Ruby, 182 bytes
```
$h=Hash.new 0
def r(c)c.scan(/(([^!?^<>]*)(<(\g<1>*)>|[!?^]))/){$4?($1=~/(.*?)<(.*)>/
($h[$1]-=1;r$2)while$h[$1]>0):$3<?"?p($h[$2]):$h[$2]+=$3<?@?STDIN.gets.to_i:
1}end
r IO.read *$*
```
Try it like this:
```
$ cat code
a?b<>c<>a<c^c^c<b^>>b!
$ ruby lynn.rb code
3 <-- input
6 <-- output
```
## How it works
The `r` function tokenizes an input string and executes each token:
```
def r(c)
c.scan(/(([^!?^<>]*)(<(\g<1>*)>|[!?^]))/){
...
}
end
```
We look for some variable name `$2` matching `[^!?^<>]*`, followed by either
* `<...>` where `...` matches zero or more programs (`\g` is recursion), in which case `$4` isn't `nil`
* A `!`, `?`, or `^` character, captured by `$3`, in which case `$4` is `nil`.
Then the logic for executing a token is quite simple when indenting it a bit:
```
$4 ? ( # If it's a loop:
$1 =~ /(.*?)<(.*)>/ # Re-match token*
($h[$1]-=1; r $2) while $h[$1] > 0 # Recurse to run loop
) : # Else:
$3 < ?" # If it's an !:
? p($h[$2]) # Print the var
: $h[$2] += # Else, increment it by:
$3 < ?@ # If it's a ?:
? STDIN.gets.to_i # User input
: 1 # Else: 1
* There's an oniguruma bug, I think, that keeps me from simply using $3 here.
```
[Answer]
# JavaScript (ES6) 184 ~~194 209~~
**Edit** Simplified (using function parameters for input and output seemed a nice idea, but it was not), 1 more byte saved thx @ӍѲꝆΛҐӍΛПҒЦꝆ
**Edit 2** Modified parsing. The logic for increment/input is borrowed from @Lynn's answer
```
F=(p,i=0,v={},n='')=>eval("for(;c='>?^!<'.indexOf(q=p[i++]||'');n=~c?'':n+q)if(c>3){for(;v[n]--;)F(p,i,v);i=F(p,i,v[n]=0)}else~c&&v?c>2?alert(v[n]|0):v[n]=~~v[n]+(--c||+prompt()):0;i")
```
**Less golfed**
```
F=(p, // program
i = 0, // initial instruction pointer
v = {}, // variables (default to empty) or if 0, flag of dummy execution
n = '' // name of current variable (has to be local for recursive calls)
{
for(; c='>?^!<'.indexOf(q=p[i++]||''); )
// q = current character
// c = current command (int 0..4 or -1 id not recognized)
// note 0 end of subprogram or end of program
{
if(c>3) // 4='<' call subprogram - recursive
{
for(;v[n]--;)
F(p,i,v); // conditional call, repeated - using real environment
v[n] = 0; // Reset variable at loop end
i=F(p,i,0) // one more unconditional dummy call, just to advance i
}
else
~c&&v? // if valid command (1..3) and not dummy
c>2?
alert(v[n]|0) // output, undefined becomes 0
:v[n]=~~v[n]+(--c||+prompt()) // inc with 1 or user input
:0 // not valid command or dummy, do nothing
n=~c?'':n+q // reset or update current variable name
}
return i // return current istruction pointer (for recursive calls)
}
```
**TEST** The snippet start evaluating 2016 using the program posted by @Neil. Be patient...
```
F=(p,i=0,v={},n='')=>eval("for(;c='>?^!<'.indexOf(q=p[i++]||'');n=~c?'':n+q)if(c>3){for(;v[n]--;)F(p,i,v);i=F(p,i,v[n]=0)}else~c&&v?c>2?alert(v[n]|0):v[n]=~~v[n]+(--c||+prompt()):0;i")
// TEST
function definput(){ I.disabled = KI.checked; }
function defoutput(){ O.disabled = KO.checked; }
function run()
{
var prog=P.value, irows = I.value.split('\n'), pi=0;
var fout=x=>O.value+=x+'\n';
var fin=x=>irows[pi++];
var saveAlert=alert, savePrompt=prompt
if (!KO.checked) alert=fout,O.value=''
if (!KI.checked) prompt=fin
F(prog);
alert=saveAlert
prompt=savePrompt
}
P.value="^^^^<a^a^>a<^^^^><a^b^>a<c<b^^>b<c^^>>!"
run()
```
```
Program <button onclick="run()">RUN</button><br>
<textarea id=P></textarea><br>
Input (or <input type=checkbox id=KI onclick="definput()"> interactive prompt)<br>
<textarea id=I>5</textarea><br>
Output (or <input type=checkbox id=KO onclick="defoutput()"> popup)<br>
<textarea id=O readonly></textarea><br>
```
[Answer]
# C++, 301
**Thanks to @ceilingcat for some very nice pieces of golfing - now even shorter**
```
#import<bits/stdc++.h>
std::map<std::string,long>V;int r(char*s){char*p;for(long c;*s;s=p){p=strpbrk(s,"^<?!");c=*p-60;*p++=0;!c?[s](auto&p){char*e=p,c=0;for(;*e-62|c;e++)c+=*e-62?*e==60:-1;for(*e++=0;V[s];r(strdup(p)))V[s]--;p=e;}(p),0:c+27?c-3?c-34||V[s]++:scanf("%llu",&V[s]):printf("%llu",V[s]);}}
```
[Try it online!](https://tio.run/##PU9BboMwELzzioSqkY1xS9MqlVgMv8glCpLZQIKawMp2Tglvpzaqasn2zOzs2ItE8ow4zy/9jUbjiqZ39t26Ewrxdikjj/L8pqlYgHWmH87pdRzO5R76wa0Mw4s2ieWP5SboRsNCfYWQWLCK@IOU76PG/DCbxnVRrWMOqBKSuwwSEkJlsMbqYI9M3924ob@sVlGKvhYSIWnlbvtEaIXgKNRCK29RuyyXH4snaZeovQ8Cw/yTpzsx4pwHRUog1cLkhTTLUWy/K5SfYX89n8EgRG5RDx2LX6/Xe5xugshz8gO7f3HRYJrmMPpN9wPjjyh8dtWN4@Go4tqvQte6LnURcOlJEwgWjWdNgf4s1zFEhvkWDtE0/wI "C++ (gcc) – Try It Online")
[Answer]
# Perl, 251 bytes
```
@p=split/([<>!?^])/,<>;for$c(0..$#p){$_=$p[$c];/</&&push@j,$c;if(/>/){$a=pop@j;$p[$c]=">$a";$p[$a]="<$c";}}while($c<$#p){$_=$p[$c];/\^/&&$v{$l}++;/!/&&print$v{$l};/\?/&&($v{$l}=<>);/<(\d+)/&&($v{$l}?$v{$l}--:($c=$1));/>(\d+)/&&($c=$1-2);$l=$_;$c++;}
```
Easier to read version:
```
# treat the first line of input as a program
# split on punctuation keywords; @p will contain the program as a list
# of tokens (including whitespace between adjacent punctuation)
@p = split /([<>!?^])/, <>;
# rewrite jump addresses
# the interpreter could scan backwards to avoid this, but that idea
# makes me feel dirty
for $c (0..$#p) {
$_ = $p[$c];
# save loop-start address on stack
/</ && push @j, $c;
if (/>/) {
# if we encounter a loop-end instruction, rewrite it and the
# corresponding loop-start to include the address (of the
# instruction---jumps have to offset from this)
$a = pop @j;
$p[$c] = ">$a";
$p[$a] = "<$c";
}
}
# execute the program
# our program is already in @p
# $c will contain our program counter
# $l will contain the name of the last-referenced variable
while ($c < $#p) {
# move current instruction into $_ for shorter matching
$_ = $p[$c];
# increment instruction
/\^/ && $v{$l}++;
# output instruction
/!/ && print $v{$l};
# input instruction
/\?/ && ($v{$l} = <>);
# loop start, including address
/<(\d+)/ && ($v{$l} ? $v{$l}-- : ($c = $1));
# loop end, including address
/>(\d+)/ && ($c = $1-2);
# copy current instruction into "last variable name"---this will
# sometimes contain operators, but we have null-string
# instructions between adjacent operators, so it'll be fine
$l = $_;
# advance the program counter
$c++;
}
```
This wastes a bunch of bytes fixing up loops to be direct jumps, but scanning backwards for the loop start offended my sense of aesthetics.
] |
[Question]
[
Hexagonal grids have been become a fairly popular twist for challenges about 2-dimensional data recently. However, it seems that the equally interesting triangular grids have been largely neglected so far. I'd like to rectify that with a rather simple challenge.
First, how do we represent a triangular grid? Consider the following example (ignore the right diagram for now):
[](https://i.stack.imgur.com/cYKwg.png) [](https://i.stack.imgur.com/sln1m.png)
The cells neatly fall onto a regular grid (the difference to a regular grid being only which cells are considered adjacent):
```
1234567
89abcde
fghijkl
mnopqrs
```
Now, as the right diagram shows, a triangular grid has three main axes: a horizontal and two diagonal ones.
Highlighting these in the ASCII grid:
```
AVAVAVA
VAabcAV
fVAiAVl
mnVAVrs
```
### The Challenge
You're given a rectangular string representing a triangular grid (where the top left corner is an upwards-pointing triangle). Most of the cells with be `.`, but exactly two cells will be `#`, e.g.:
```
....#
.#...
.....
```
Determine whether the two `#` are aligned along any of the three axes of the grid (i.e. whether they lie on a single row in any of the three directions highlighted above). For this example, the answer is "no".
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.
Input may be a single string delimited by linefeeds or some other convenient character, or a list of strings. You may use any two (consistent) printable ASCII characters in place of `.` and `#`.
Output should be a [truthy](http://meta.codegolf.stackexchange.com/questions/2190/interpretation-of-truthy-falsey/2194#2194) value if the highlighted cells are aligned and a [falsy](http://meta.codegolf.stackexchange.com/questions/2190/interpretation-of-truthy-falsey/2194#2194) value otherwise.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply.
### Test Cases
Truthy grids:
```
.#..#.
#
#
...........
...#.......
...........
...........
...........
.......#...
...........
...........
.......#...
...........
...........
...........
...#.......
...........
.#.........
...........
...........
...........
...........
.......#...
...........
...........
...#.......
...........
...........
...........
...........
.......#...
.........#.
...........
...........
...........
...........
...#.......
...........
...........
.......#...
...........
...........
...........
...........
...#.......
...........
.#.....#...
...........
...........
...........
```
Falsy grids:
```
#.....
.....#
.....#
#.....
...#.......
...........
...........
...........
...........
.......#...
...........
...........
...#.......
...........
...........
...........
...........
.........#.
.......#...
...........
...........
...........
...........
...#.......
...........
...........
.......#...
...........
...........
...........
...........
.#.........
```
[Answer]
# [Snails](https://github.com/feresum/PMA), ~~40~~ 39 bytes
```
\#{z|=(ul.ul.`,l~a~)(l.a3|.a|d.ea5}.,\#
```
```
\# ,, match '#'
{
z | ,, Either turn in any octinilear direction, or do all the other stuff before the }
=( ,, If this assertion succeeds, the starting cell is an "upwards-pointing triangle"
ul.ul.`, ,, Go one cell up or left twice, any number of times.
,, This should have been one byte shorter with ul.`2 , or ul.`2+? but
,, the parsing of ` is buggy.
l~a~ ,, Check that we are on the top-left cell by matching out-of-bounds to the left and then northeast
)
( l.a3 | ,, Move leftward once, then set direction to northwest; or
.a | ,, Move right (the initial direction) once, then set direction to northeast; or
d.ea5 ,, Move down once, then set direction to either northwest or northeast
}
., ,, Match any number of arbitrary chars (moving in the current direction)
\# ,, match '#'
```
[Answer]
## CJam, 47 bytes
Well, now that there is a shorter solution I no longer feel bad sharing my own. :) (Mostly to show that this isn't particularly difficult, even if you don't have a 2D pattern matching language...)
```
qN%:eeee::f+:~{S&},2f<:P0f=P::+Xf|P::-Xf|]::=:|
```
This uses spaces in place of `#` and really anything else for `.`.
[Run all test cases online.](http://cjam.tryitonline.net/#code=cU4yKi97OlE7CgpRTiU6ZWVlZTo6Zis6fntTJn0sMmY8OlAwZj1QOjorWGZ8UDo6LVhmfF06Oj06fAoKXW9Ob30v&input=LiAuLiAuCgogCiAKCi4uLi4uLi4uLi4uCi4uLiAuLi4uLi4uCi4uLi4uLi4uLi4uCi4uLi4uLi4uLi4uCi4uLi4uLi4uLi4uCi4uLi4uLi4gLi4uCi4uLi4uLi4uLi4uCgouLi4uLi4uLi4uLgouLi4uLi4uIC4uLgouLi4uLi4uLi4uLgouLi4uLi4uLi4uLgouLi4uLi4uLi4uLgouLi4gLi4uLi4uLgouLi4uLi4uLi4uLgoKLiAuLi4uLi4uLi4KLi4uLi4uLi4uLi4KLi4uLi4uLi4uLi4KLi4uLi4uLi4uLi4KLi4uLi4uLi4uLi4KLi4uLi4uLiAuLi4KLi4uLi4uLi4uLi4KCi4uLi4uLi4uLi4uCi4uLiAuLi4uLi4uCi4uLi4uLi4uLi4uCi4uLi4uLi4uLi4uCi4uLi4uLi4uLi4uCi4uLi4uLi4uLi4uCi4uLi4uLi4gLi4uCgouLi4uLi4uLi4gLgouLi4uLi4uLi4uLgouLi4uLi4uLi4uLgouLi4uLi4uLi4uLgouLi4uLi4uLi4uLgouLi4gLi4uLi4uLgouLi4uLi4uLi4uLgoKLi4uLi4uLi4uLi4KLi4uLi4uLiAuLi4KLi4uLi4uLi4uLi4KLi4uLi4uLi4uLi4KLi4uLi4uLi4uLi4KLi4uLi4uLi4uLi4KLi4uIC4uLi4uLi4KCi4uLi4uLi4uLi4uCi4gLi4uLi4gLi4uCi4uLi4uLi4uLi4uCi4uLi4uLi4uLi4uCi4uLi4uLi4uLi4uCgogLi4uLi4KLi4uLi4gCgouLi4uLiAKIC4uLi4uCgouLi4gLi4uLi4uLgouLi4uLi4uLi4uLgouLi4uLi4uLi4uLgouLi4uLi4uLi4uLgouLi4uLi4uLi4uLgouLi4uLi4uIC4uLgouLi4uLi4uLi4uLgoKLi4uLi4uLi4uLi4KLi4uIC4uLi4uLi4KLi4uLi4uLi4uLi4KLi4uLi4uLi4uLi4KLi4uLi4uLi4uLi4KLi4uLi4uLi4uLi4KLi4uLi4uLi4uIC4KCi4uLi4uLi4gLi4uCi4uLi4uLi4uLi4uCi4uLi4uLi4uLi4uCi4uLi4uLi4uLi4uCi4uLi4uLi4uLi4uCi4uLiAuLi4uLi4uCi4uLi4uLi4uLi4uCgouLi4uLi4uLi4uLgouLi4uLi4uIC4uLgouLi4uLi4uLi4uLgouLi4uLi4uLi4uLgouLi4uLi4uLi4uLgouLi4uLi4uLi4uLgouIC4uLi4uLi4uLg&debug=on)
I really hate the duplication in `P::+Xf|P::-Xf|` but so far I haven't come up with anything to get rid of it.
### Explanation
Don't read on if you want to figure out a solution for yourself.
First, the boring part: getting the two coordinate pairs of the two spaces in the input grid:
```
qN% e# Read input and split into lines.
:ee e# Enumerate the characters in each line. I.e. turn each character 'x into a pair
e# [N 'x] where N is its horizontal 0-based index.
ee e# Enumerate the lines themselves, turning each line [...] into [M [...]] where M
e# is its vertical 0-based index.
::f+ e# This distributes the vertical index over the individual lines, by prepending it
e# to each pair in that line. So now we've got a 2-D array, where each character 'x
e# has been turned into [M N 'x].
:~ e# Flatten the outermost dimension, so that we have a flat list of characters with
e# their coordinates.
{S&}, e# Filter only those lists that contain a space.
2f< e# Truncate the two results to only their first two elements.
:P e# Store the result in P.
```
Now the interesting part is how to determine whether those coordinates are aligned or not. My code computes all three axes separately:
* The horizontal axis is trivial. Check whether the vertical coordinates match.
* Let's look at the north-east diagonal. In the ASCII grid, there are always two antidiagonals that belong to each tri-grid diagonal:
```
....AV..
...AV...
..AV....
```
We can identify the current antidiagonal by adding up the `x` and `y` coordinates:
```
01234567
12345678
23456789
```
So we'd want `0` and `1` to belong to the same diagonal, as well as `2` and `3`, and `4` and `5` and so on. That means, once we have our anti-diagonal index we want to round up to the next odd number. In other words, we take the bitwise OR with `1`. (We could also round down to the next even number by bitwise AND with `-2` but that's more expensive in code.)
* Now the south-east diagonals:
```
.VA.....
..VA....
...VA...
```
In order to give diagonals an index, we *subtract* the `x` from the `y` coordinate (representing negative numbers as letters):
```
0abcdefg
10abcdef
210abcde
```
In this case, we'd want `0` and `1` to belong to the same diagonal, as well as `-1` and `-2`, or `2` and `3`. So once again, we want to round up to the next odd number.
Here is the code for that:
```
0f= e# The coordinates are still on the stack. Replace each with its vertical coordinate
e# to check for the horizontal axis.
P e# Push the coordinates again.
::+ e# Sum each pair to get an anti-diagonal index.
Xf| e# OR each index with 1 to round up to the next odd number.
P e# Push the coordinates again.
::- e# In each pair, subtract the horizontal coordinate from the vertical, to
e# get a diagonal index.
Xf| e# OR each index with 1.
] e# Wrap all three index pairs in an array.
::= e# Check equality for each pair.
:| e# Fold bitwise OR over the results to check if at least one pair of indices
e# was equal.
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~36~~ 27 [bytes](https://codegolf.meta.stackexchange.com/questions/9428/when-can-apl-characters-be-counted-as-1-byte-each)
```
1∊=/¯1 0 1∘.(⊥-2|⊣×⊥)⍸⍉⍎¨↑⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97b/ho44uW/1D6w0VDBSA7Bl6Go@6luoa1TzqWnx4OpCp@ah3x6Pezke9fYdWPGqb@KhvKkjf/zQuIOtR24RHbZMNFcwe9W5RNzA0ACJ1LiQZI6CJQBlDQxRRcwVDsLABCjA0IA2gqSfCBlJswaIOuw2kOptCPxhSZhl@GwwpdD8N4gGLFhQbTLHYYEi8DWipFZyOkTQaYpOHyBji9a3hEEkTGDkWzQZDit1PyzRhiMUGsLnqCuBYBFLgSAQA "APL (Dyalog Unicode) – Try It Online")
*-9 bytes mostly from @Bubbler*
Full program that returns `0` or `1`. Takes input as an array of strings, where each character is `0` for `.` or `1` for `#`.
### How?
Uses the same general strategy as Martin Ender's [CJam Answer](https://codegolf.stackexchange.com/a/69064/68261). The two diagonals are indexed as `y+(-1)*x` and `y+1*x`, both rounded up to the nearest odd number. The horizontal axis is indexed as `y+0*x` with no rounding.
```
1∊=/¯1 0 1∘.(⊥-2|⊣×⊥)⍸⍉⍎¨↑⎕
↑⎕ ⍝ The input array of strings, converted to a matrix
⍎¨ ⍝ Evaluate each character to obtain either 0 or 1
⍸ ⍝ Find the (y,x) positions of both 1s
∘. ⍝ Outer product:
¯1 0 1 ⍝ For each ⍺ in 1, 0, -1:
⍝ And for each (y,x) position
(⊥ ) ⍝ Compute (⍺×x)+y (convert to base ⍺)
⍝ (⍉-Transposed earlier to get x left of y)
-2|⊣×⊥ ⍝ If odd and ⍺ is not 0: subtract 1
1∊=/ ⍝ Check if the two positions have equal indices on any axis
```
] |
[Question]
[
The flag of the United States of America contains, in its canton, 50 stars, representing the 50 states.

In the past, when there were fewer states, there were of course fewer stars, and they were arranged differently. For example, from 1912-1959 (after the admission of New Mexico and Arizona but before Alaska), there were 48 stars in a 6×8 rectangular arrangement.

The 37-star flag used from 1867-1877 (after the admission of Nebraska but before Colorado) had an asymmetric star pattern.

In case a [51st state](http://en.wikipedia.org/wiki/Statehood_movement_in_Puerto_Rico) is added in the future, the Army Institute of Heraldry has already developed a preliminary design for a new flag.

But there's no *general* algorithm for arranging the stars, so let's make one!
# The challenge
**Write a program that will, for a given number of stars to place in the canton (blue part) of a US flag, output optimal coordinates at which to place those stars.** The coordinate system is defined with the canton [*not* the flag as a whole] with 0≤x≤W and 0≤y≤H.
For the purpose of this challenge, an “optimal” arrangement is defined as one that **minimizes the mean (Euclidean) distance between a point in the canton and the center of the nearest star.**
A straightforward (if maybe suboptimal) algorithm to approximate this value is:
```
def mean_distance_to_nearest_star(stars, width, height, point_density=100):
"""
Approximate the mean distance between a point in the rectangle
0 < x < width and 0 < y < height, and the nearest point in stars.
stars -- list of (x, y) points
width, height -- dimensions of the canton
"""
total = 0.0
nx = round(width * point_density)
ny = round(height * point_density)
for ix in range(nx):
x = (ix + 0.5) * width / nx
for iy in range(ny):
y = (iy + 0.5) * width / ny
min_dist = float('inf')
for sx, sy in stars:
min_dist = min(min_dist, math.hypot(x - sx, y - sy))
total += min_dist
return total / (nx * ny)
```
Your program shall take three command-line arguments (not counting the program name itself):
1. The number of stars to put in the canton.
2. The width of the canton. (Must accept floating-point values.)
3. The height of the canton. (Must accept floating-point values.)
(If your preferred programming language doesn't support command-line arguments, do something reasonably equivalent, and document it in your answer.)
The output should consist of comma-separated X and Y values, one to a line. (Order of the points doesn't matter.)
For example:
```
~$ flagstar 5 1.4 1.0
0.20,0.20
0.20,0.80
0.70,0.50
1.20,0.20
1.20,0.80
```
# Additional rules & notes
* I have the right to close loopholes in the rules at any time.
* ~~Deadline for answers is **Friday, July 4** at 24:00 CDT (UTC-05:00).~~ Due to lack of answers, the deadline has been extended. TBA.
* Include in your answer:
+ Your program's code
+ An explanation of how it works
+ Its output with the command-line arguments `50 1.4 1.0`
* Your program must run within a reasonable amount of time: At most 5 min on a typical PC. I won't be ultra-strict about this, but will disqualify your program if it takes *hours*.
* Your program must be deterministic, i.e., always give exactly the same output for the same arguments. So, don't depend on `time()` or `rand()`. Monte Carlo methods are OK as long as you roll your own PRNG.
* Only the center points of the stars matter. Don't worry about trying to avoid overlap or anything like that.
# Scoring
* Minimize the mean distance from a point in the canton to the nearest star. (See above.)
* You may be scored based on any historical US flags, between 13 and 50 stars. The exact algorithm for weighting scores into a single ranking will be posted later.
* In case of a tie, the winner will be chosen by number of net upvotes.
* I will probably post a program of my own, but will exclude myself from being eligible for the checkmark.
[Answer]
# Javascript - move stars towards most isolated point
(with an animation of the process)
The approach is very simple:
* choose a large number of random points
* find the nearest star to each
* choose the point for which the nearest star is most distant
* move that star nearer to that point
This process is repeated a large number of times, gradually decreasing the amount by which the stars are moved. This reduces the maximum distance from a point to the nearest star, indirectly reducing the mean distance from a point to the nearest star.
As required by the question, this does not use the built in random function, instead using [xorshift](http://en.wikipedia.org/wiki/Xorshift).
Much of the code covers set up and animation - the part that applies the algorithm is the function `adjustStars`.
# Code
You can watch the process in progress in the Stack Snippet below.
```
stars = [];
timeoutId = 0;
resetRandomNumberGenerator();
function resetRandomNumberGenerator() {
rng_x = 114; // Numbers for the random number generator.
rng_y = 342;
rng_z = 982;
rng_w = 443;
}
$(document).ready(function() {
c = document.getElementById('canton');
ctx = c.getContext('2d');
resizeCanvas();
});
function stop() {
clearTimeout(timeoutId);
}
function arrange() {
clearTimeout(timeoutId);
resetStars();
resetRandomNumberGenerator();
maxStepSize = Math.min(cantonWidth, cantonHeight) / 4;
adjustStars(maxStepSize, 8000, 10000);
}
function resizeCanvas() {
cantonWidth = parseFloat($('#width').val());
cantonHeight = parseFloat($('#height').val());
starRadius = cantonHeight / 20;
document.getElementById('canton').width = cantonWidth;
document.getElementById('canton').height = cantonHeight;
ctx.fillStyle = 'white';
resetStars();
}
function resetStars() {
stop();
stars = [];
population = parseInt($('#stars').val(), 10);
shortSide = Math.floor(Math.sqrt(population));
longSide = Math.ceil(population / shortSide);
if (cantonWidth < cantonHeight) {
horizontalStars = shortSide;
verticalStars = longSide;
} else {
horizontalStars = longSide;
verticalStars = shortSide;
}
horizontalSpacing = cantonWidth / horizontalStars;
verticalSpacing = cantonHeight / verticalStars;
for (var i = 0; i < population; i++) {
x = (0.5 + (i % horizontalStars)) * horizontalSpacing;
y = (0.5 + Math.floor(i / horizontalStars)) * verticalSpacing;
stars.push([x, y]);
}
drawStars();
updateOutputText();
}
function adjustStars(stepSize, maxSteps, numberOfPoints) {
$('#stepsRemaining').text(maxSteps + ' steps remaining');
points = randomPoints(numberOfPoints);
mostIsolatedPoint = 0;
distanceToNearestStar = 0;
for (var i = 0; i < numberOfPoints; i++) {
point = points[i];
x = point[0];
y = point[1];
star = stars[nearestStar(x, y)];
d = distance(x, y, star[0], star[1]);
if (d > distanceToNearestStar) {
distanceToNearestStar = d;
mostIsolatedPoint = i;
}
}
point = points[mostIsolatedPoint];
x = point[0];
y = point[1];
starToMove = nearestStar(x, y);
star = stars[starToMove];
separationX = x - star[0];
separationY = y - star[1];
if (separationX || separationY) {
hypotenuse = distance(x, y, star[0], star[1]);
currentStep = Math.min(stepSize, hypotenuse / 2);
deltaX = currentStep * separationX / hypotenuse;
deltaY = currentStep * separationY / hypotenuse;
star[0] += deltaX;
star[1] += deltaY;
if (star[0] < 0) star[0] = 0;
if (star[0] > cantonWidth) star[0] = cantonWidth;
if (star[1] < 0) star[1] = 0;
if (star[1] > cantonHeight) star[1] = cantonHeight;
drawStars();
updateOutputText();
}
if (maxSteps > 0) {
timeoutId = setTimeout(adjustStars, 10, stepSize * 0.9992, maxSteps - 1, numberOfPoints);
}
}
function updateOutputText() {
starText = '';
for (var i = 0; i < stars.length; i++) {
starText += stars[i][0] + ', ' + stars[i][1] + '\n';
}
$('#coordinateList').text(starText);
}
function randomPoints(n) {
pointsToReturn = [];
for (i = 0; i < n; i++) {
x = xorshift() * cantonWidth;
y = xorshift() * cantonHeight;
pointsToReturn.push([x, y]);
}
return pointsToReturn;
}
function xorshift() {
rng_t = rng_x ^ (rng_x << 11);
rng_x = rng_y;
rng_y = rng_z;
rng_z = rng_w;
rng_w = rng_w ^ (rng_w >> 19) ^ rng_t ^ (rng_t >> 8);
result = rng_w / 2147483648
return result
}
function nearestStar(x, y) {
var distances = [];
for (var i = 0; i < stars.length; i++) {
star = stars[i];
distances.push(distance(x, y, star[0], star[1]));
}
minimum = Infinity;
for (i = 0; i < distances.length; i++) {
if (distances[i] < minimum) {
minimum = distances[i];
nearest = i;
}
}
return nearest;
}
function distance(x1, y1, x2, y2) {
var x = x2 - x1;
var y = y2 - y1;
return Math.sqrt(x * x + y * y);
}
function drawStars() {
ctx.clearRect(0, 0, cantonWidth, cantonHeight);
for (i = 0; i < stars.length; i++) {
star = stars[i];
x = star[0];
y = star[1];
drawStar(x, y);
}
}
function drawStar(x, y) {
ctx.beginPath();
ctx.moveTo(x, y - starRadius);
ctx.lineTo(x - 0.588 * starRadius, y + 0.809 * starRadius);
ctx.lineTo(x + 0.951 * starRadius, y - 0.309 * starRadius);
ctx.lineTo(x - 0.951 * starRadius, y - 0.309 * starRadius);
ctx.lineTo(x + 0.588 * starRadius, y + 0.809 * starRadius);
ctx.fill();
}
```
```
canvas {
margin: 0;
border: medium solid gray;
background-color: blue;
}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input id='stars' onchange='resetStars()' type='number' value='13' min='13' max='50' maxlength='2' step='1'>stars
<br>
<input id='width' onchange='resizeCanvas()' type='number' value='494' min='1' max='500' maxlength='3' step='any'>width
<br>
<input id='height' onchange='resizeCanvas()' type='number' value='350' min='1' max='500' maxlength='3' step='any'>height
<br>
<button type='button' onclick='resetStars()'>Reset Stars</button>
<button type='button' onclick='arrange()'>Arrange Stars</button>
<button type='button' onclick='stop()'>Stop</button>
<textarea id='stepsRemaining' rows='1' readonly></textarea>
<br>
<canvas id='canton' width='494' height='350'></canvas>
<br>
<textarea id='coordinateList' rows='50' cols='40' readonly></textarea>
```
# Output for 50 stars
(width = 1.4, height = 1.0)
Mean distance estimated at 0.0655106697162357.
Coordinates:
```
0.028377044205135808, 0.2128159150679491
0.10116766857540277, 0.05156676609341312
0.2903566419069437, 0.07216263690037035
0.49154061258041604, 0.004436102736309105
0.6930026352073071, 0.07060477929576484
1.0988644764108417, 0.022979778480838074
1.1735677936511582, 0.18600858289592742
1.3056806950504931, 0.062239869036660435
0.3967626880807638, 0.24483447327177033
0.27004118129346155, 0.40467589936498805
0.4996665039421278, 0.13023282430440133
0.5148978532656602, 0.6161298793146592
0.5907056537744844, 0.2614323599301046
0.8853042432872087, 0.048123917861564044
0.7753680330575412, 0.22938793622044834
1.365432954694329, 0.2355377720528128
0.1985172068244217, 0.23551298706793927
0.4477558465270544, 0.4170264112485973
0.6084424566752479, 0.7764909501169484
0.6099528761580699, 0.4395002434593519
0.9506038166406011, 0.34903243854585914
1.1898331497634231, 0.5756784243472182
1.0933574395540542, 0.46422120794648786
1.1516574254138159, 0.2930213338333888
0.07646053006349718, 0.40665000611360175
0.0634456093015551, 0.5853189455014883
0.3470036636019768, 0.5938838331082922
0.7591083341283029, 0.4005456925638841
0.9745306853981277, 0.184624209972443
1.3552011948311598, 0.549607060691302
1.3334000268566828, 0.7410204535471169
1.2990417572304487, 0.39571229988825735
0.05853941030364222, 0.7734808757471414
0.19396697551982484, 0.5678753467094985
0.7103231124251072, 0.5955041661956884
0.6168410756137566, 0.948561537739087
0.8967624790188228, 0.5368666961690878
0.9751229155529001, 0.8323724819557795
0.9987127931392165, 0.652902038374714
1.3231032600971289, 0.9164326184290812
0.20785221980162555, 0.7566700629874374
0.3987967842137651, 0.7678025218448816
0.44395949605458546, 0.9137553802571048
0.775611700149756, 0.9029717946067138
0.806442448003616, 0.7328147396477286
0.9481952441521928, 0.9872963855418118
1.1528689317425114, 0.9346775634274639
1.1651295140721658, 0.7591158327925681
0.09316709042512515, 0.934205211493484
0.2769325337580081, 0.9341145493466471
```
[Answer]
Here's a simple example. It always arranges the stars into a rectangular grid, and optimizes it by choosing the factorization in which the grid cells are as close to square as possible. It works great when the number of stars has a divisor close to its square root, and pessimally when the number of stars is prime.
```
from __future__ import division
import math
import sys
def divisors(n):
"""
Return all divisors of n (including n itself) as a set.
"""
result = {1, n}
# Use +2 instead of +1 to allow for floating-point error.
for i in range(2, int(math.sqrt(n)) + 2):
if n % i == 0:
result.add(i)
result.add(n // i)
return result
def squareness(width, height):
"""
Given the dimensions of a rectangle, return a value between 0 and 1
(1 iff width == height) measuring how close it is to being a square.
"""
if width and height:
return min(width / height, height / width)
else:
return 0.0
def star_grid(num_stars, width, height):
"""
Return the factors (x, y) of num_stars that optimize the mean
distance to the nearest star.
"""
best_squareness = 0.0
best_dimensions = (None, None)
for nx in divisors(num_stars):
ny = num_stars // nx
sq = squareness(width / nx, height / ny)
if sq > best_squareness:
best_squareness = sq
best_dimensions = (nx, ny)
return best_dimensions
def star_coords(num_stars, width, height):
"""
Return a list of (x, y) coordinates for the stars.
"""
nx, ny = star_grid(num_stars, width, height)
for ix in range(nx):
x = (ix + 0.5) * width / nx
for iy in range(ny):
y = (iy + 0.5) * height / ny
yield (x, y)
def _main(argv=sys.argv):
num_stars = int(argv[1])
width = float(argv[2])
height = float(argv[3])
for coord in star_coords(num_stars, width, height):
print('%g,%g' % coord)
if __name__ == '__main__':
_main()
```
# Output for 50 stars
(width = 1.4, height = 1.0)
A 10×5 rectangle.
```
0.07,0.1
0.07,0.3
0.07,0.5
0.07,0.7
0.07,0.9
0.21,0.1
0.21,0.3
0.21,0.5
0.21,0.7
0.21,0.9
0.35,0.1
0.35,0.3
0.35,0.5
0.35,0.7
0.35,0.9
0.49,0.1
0.49,0.3
0.49,0.5
0.49,0.7
0.49,0.9
0.63,0.1
0.63,0.3
0.63,0.5
0.63,0.7
0.63,0.9
0.77,0.1
0.77,0.3
0.77,0.5
0.77,0.7
0.77,0.9
0.91,0.1
0.91,0.3
0.91,0.5
0.91,0.7
0.91,0.9
1.05,0.1
1.05,0.3
1.05,0.5
1.05,0.7
1.05,0.9
1.19,0.1
1.19,0.3
1.19,0.5
1.19,0.7
1.19,0.9
1.33,0.1
1.33,0.3
1.33,0.5
1.33,0.7
1.33,0.9
```
[Answer]
# Javascript - move a star randomly if mean distance is reduced
(with an animation of the process)
This doesn't give such a busy animation as my first answer, having long periods with no movement as potential rearrangements are tested and rejected. However, the final result has a lower mean distance, so this method is an improvement.
The approach is still very simple:
* Choose a star at random
* Move it a random distance in a random direction
* If the mean distance is reduced, keep the new position
This process is repeated a large number of times, gradually decreasing the amount by which the stars are moved. The random choice of distance to move is biased towards smaller distances, so progress is in small alterations interspersed with the occasional larger jump. Each step takes longer than in my first answer, as measuring the mean distance is a slow process requiring sampling the entire canton.
As required by the question, this does not use the built in random function, instead using [xorshift](http://en.wikipedia.org/wiki/Xorshift).
Much of the code covers set up and animation - the part that applies the algorithm is the function `adjustStars`.
# Code
You can watch the process in progress in the Stack Snippet below.
```
stars = [];
timeoutId = 0;
resetRandomNumberGenerator();
function resetRandomNumberGenerator() {
rng_x = 114; // Numbers for the random number generator.
rng_y = 342;
rng_z = 982;
rng_w = 443;
}
$(document).ready(function() {
c = document.getElementById('canton');
ctx = c.getContext('2d');
resizeCanvas();
});
function stop() {
clearTimeout(timeoutId);
}
function arrange() {
clearTimeout(timeoutId);
resetStars();
resetRandomNumberGenerator();
maxStepSize = Math.min(cantonWidth, cantonHeight) / 16;
adjustStars(maxStepSize, 7000, 15000);
}
function resizeCanvas() {
cantonWidth = parseFloat($('#width').val());
cantonHeight = parseFloat($('#height').val());
starRadius = cantonHeight / 20;
document.getElementById('canton').width = cantonWidth;
document.getElementById('canton').height = cantonHeight;
ctx.fillStyle = 'white';
resetStars();
}
function resetStars() {
stop();
stars = [];
population = parseInt($('#stars').val(), 10);
shortSide = Math.floor(Math.sqrt(population));
longSide = Math.ceil(population / shortSide);
if (cantonWidth < cantonHeight) {
horizontalStars = shortSide;
verticalStars = longSide;
} else {
horizontalStars = longSide;
verticalStars = shortSide;
}
horizontalSpacing = cantonWidth / horizontalStars;
verticalSpacing = cantonHeight / verticalStars;
for (var i = 0; i < population; i++) {
x = (0.5 + (i % horizontalStars)) * horizontalSpacing;
y = (0.5 + Math.floor(i / horizontalStars)) * verticalSpacing;
stars.push([x, y]);
}
drawStars();
updateOutputText();
}
function adjustStars(stepSize, maxSteps, numberOfPoints) {
$('#stepsRemaining').text(maxSteps + ' steps remaining');
var points = randomPoints(numberOfPoints);
currentMean = meanDistance(stars, points);
potentialStars = shiftedStars(stepSize);
potentialMean = meanDistance(potentialStars, points);
if (potentialMean < currentMean) {
stars = potentialStars;
}
drawStars();
updateOutputText();
if (maxSteps > 0) {
timeoutId = setTimeout(adjustStars, 10, stepSize * 0.999, maxSteps - 1, numberOfPoints);
}
}
function shiftedStars(stepSize) {
shifted = [];
chosenOne = Math.floor(xorshift() * stars.length);
for (i = 0; i < stars.length; i++) {
star = stars[i];
x = star[0];
y = star[1];
if (i === chosenOne) {
for (n = 0; n < 10; n++) {
x += xorshift() * stepSize;
x -= xorshift() * stepSize;
y += xorshift() * stepSize;
y -= xorshift() * stepSize;
}
if (x < 0) x = 0;
if (x > cantonWidth) x = cantonWidth;
if (y < 0) y = 0;
if (y > cantonHeight) y = cantonHeight;
}
shifted.push([x, y]);
}
return shifted;
}
function meanDistance(arrayOfStars, arrayOfPoints) {
var totalDistance = 0;
for (i = 0; i < arrayOfPoints.length; i++) {
point = arrayOfPoints[i];
x = point[0];
y = point[1];
totalDistance += nearestStarDistance(x, y, arrayOfStars);
}
return totalDistance / arrayOfPoints.length;
}
function randomPoints(numberOfPoints) {
var arrayOfPoints = [];
for (i = 0; i < numberOfPoints; i++) {
x = xorshift() * cantonWidth;
y = xorshift() * cantonHeight;
arrayOfPoints.push([x, y]);
}
return arrayOfPoints;
}
function updateOutputText() {
starText = '';
for (var i = 0; i < stars.length; i++) {
starText += stars[i][0] + ', ' + stars[i][1] + '\n';
}
$('#coordinateList').text(starText);
}
function xorshift() {
rng_t = rng_x ^ (rng_x << 11);
rng_x = rng_y;
rng_y = rng_z;
rng_z = rng_w;
rng_w = rng_w ^ (rng_w >> 19) ^ rng_t ^ (rng_t >> 8);
result = rng_w / 2147483648
return result
}
function nearestStarDistance(x, y, starsToUse) {
var distances = [];
for (var i = 0; i < stars.length; i++) {
star = starsToUse[i];
distances.push(distance(x, y, star[0], star[1]));
}
minimum = Infinity;
for (i = 0; i < distances.length; i++) {
if (distances[i] < minimum) {
minimum = distances[i];
}
}
return minimum;
}
function distance(x1, y1, x2, y2) {
var x = x2 - x1;
var y = y2 - y1;
return Math.sqrt(x * x + y * y);
}
function drawStars() {
ctx.clearRect(0, 0, cantonWidth, cantonHeight);
for (i = 0; i < stars.length; i++) {
star = stars[i];
x = star[0];
y = star[1];
drawStar(x, y);
}
}
function drawStar(x, y) {
ctx.beginPath();
ctx.moveTo(x, y - starRadius);
ctx.lineTo(x - 0.588 * starRadius, y + 0.809 * starRadius);
ctx.lineTo(x + 0.951 * starRadius, y - 0.309 * starRadius);
ctx.lineTo(x - 0.951 * starRadius, y - 0.309 * starRadius);
ctx.lineTo(x + 0.588 * starRadius, y + 0.809 * starRadius);
ctx.fill();
}
```
```
canvas {
margin: 0;
border: medium solid gray;
background-color: blue;
}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input id='stars' onchange='resetStars()' type='number' value='13' min='13' max='50' maxlength='2' step='1'>stars
<br>
<input id='width' onchange='resizeCanvas()' type='number' value='494' min='1' max='500' maxlength='3' step='any'>width
<br>
<input id='height' onchange='resizeCanvas()' type='number' value='350' min='1' max='500' maxlength='3' step='any'>height
<br>
<button type='button' onclick='resetStars()'>Reset Stars</button>
<button type='button' onclick='arrange()'>Arrange Stars</button>
<button type='button' onclick='stop()'>Stop</button>
<textarea id='stepsRemaining' rows='1' readonly></textarea>
<br>
<canvas id='canton' width='494' height='350'></canvas>
<br>
<textarea id='coordinateList' rows='50' cols='40' readonly></textarea>
```
# Output for 50 stars
(width = 1.4, height = 1.0)
Mean distance estimated at 0.06402754713808706.
Coordinates:
```
0.08147037630270487, 0.07571240182553095
0.24516777356538358, 0.0803538189052793
0.431021735247462, 0.07821284835132788
0.6001163609128221, 0.08278495286739646
0.7668077034213632, 0.0821321119375313
0.941333266969696, 0.08040530195264808
1.1229190363750599, 0.07255685332834291
1.3074771164489858, 0.07681674948141588
0.09227450444336446, 0.2257047798057907
0.33559513774978766, 0.20668611954667682
0.5182463448452704, 0.23841239342827816
0.6630614113293541, 0.26097114328053417
0.821886619004045, 0.23577904321258844
1.012597304977012, 0.23308200382761057
1.174938874706673, 0.22593017096601203
1.3285181935709358, 0.24024108928169902
0.0746772556909648, 0.3920030109869904
0.23006559905554042, 0.3204287339854068
0.4086004105498357, 0.3507788129168045
0.5669847710831315, 0.4371913211100495
0.7399474422203116, 0.41599441829489137
0.9099913571857917, 0.36933063808924294
1.1170137101288482, 0.3905679602615213
1.3037811235560612, 0.3979526346564911
0.09290206345982034, 0.5678420747594305
0.23463227399157258, 0.47552307265325633
0.4042403660145938, 0.5030345851947539
0.6611151741402685, 0.5918138006294138
0.8237963249937061, 0.5663224022272697
0.9812774216782155, 0.5032518469083094
1.146386501309064, 0.570255729516661
1.3185563715676663, 0.5571870810112576
0.07541940949872694, 0.7356649763259809
0.2877585652075202, 0.6321535875762999
0.4952646673275116, 0.6343336480073624
0.6965646728710738, 0.9178076185211137
0.7903485281657828, 0.7508031981325222
0.9774998621426763, 0.6683301268754337
1.1539480102558823, 0.7513836972857155
1.3177199931376755, 0.7245296168327016
0.22215183098388988, 0.7769843436963862
0.4048364942297627, 0.7779653803681718
0.5021290208205218, 0.9254525763987298
0.6058821167972933, 0.7683130432395833
0.8777330967719849, 0.9201076171801651
0.9894820530574747, 0.8172934111543102
1.1143371956097312, 0.9265012354173626
1.3045771339439551, 0.9069856484512913
0.0930066325438706, 0.9157592790749175
0.2959676633891297, 0.9251379492518523
```
] |
[Question]
[
Your task is to generate a valid juggling pattern by completing a given template. But first, you probably need to know how such a pattern is denoted.

## Introduction to Siteswap
Siteswap is the established notation for juggling patterns. It works by dividing the pattern into beats. At each beat your left and right hand alternate at throwing a ball. Each throw (i.e. each beat) is denoted by a number which indicates when that ball is thrown next - this corresponds directly to the height of the throw.
Let's look at some examples. [See animations of all of these here](http://mbue1.libra.uberspace.de/public/juggling/siteswap.html).
### 3-Ball Cascade
The simplest 3-ball pattern. Each ball is thrown at every third beat (alternating hands). Writing out the beats this looks like follows (the ASCII lines connect two beats at which the same ball is thrown):
```
Beat 1 2 3 4 5 6 7 8 9
Hand L R L R L R L R L
Siteswap 3 3 3 3 3 3 3 3 3
└─┼─┼─┘ │ │
└─┼───┘ │
└─────┘
```
Note how every ball thrown at an `L` beat, is thrown next at an `R` beat.Siteswap patterns repeat implicitly, so this pattern is usually denoted as `333`, although simply `3` would also be sufficient.
### 441
Here is a slightly more complicated example with the siteswap **441**:
```
Beat 1 2 3 4 5 6 7 8 9
Hand L R L R L R L R L
Siteswap 4 4 1 4 4 1 4 4 1
│ │ └─┘ │ │
└─┼─────┘ │
└───────┘
```
Note how even-numbered throws go to the same hand they were thrown from, while odd-numbered throws go to the other hand.
### 423
Sometimes you just want to hold a ball through a beat instead of throwing it. All that means, that this ball is thrown the next time its this hand's turn - i.e. 2 beats later. So holding a ball is equivalent to a `2` in the pattern:
```
Beat 1 2 3 4 5 6 7 8 9
Hand L R L R L R L R L
Siteswap 4 2 3 4 2 3 4 2 3
│ └─┼─┘ │ │
│ └───┼─┘
└───────┘
```
### 50505
A `0` means that the current hand is empty at that beat, as this pattern shows:
```
Beat 1 2 3 4 5 6 7 8 9
Hand L R L R L R L R L
Siteswap 5 0 5 0 5 5 0 5 0
└───┼───┼─┘ │
└───┼─────┘
└───────>
```
## Multiplex Juggling
This problem would be a bit too simple with vanilla siteswap though. Enter multiplex patterns! Multiplex juggling means that you throw multiple balls from one hand at the same time. For instance, in the above 3-ball cascade, if you were two throw an additional ball at every third beat, the pattern would become `[33]33` and look like this:
```
Beat 1 2 3 4 5 6 7 8 9
Hand L R L R L R L R L
Siteswap [33] 3 3 [33] 3 3 [33] 3 3
└┴──┼─┼──┴┘ │ │
└─┼──────┘ │
└────────┘
```
Here is another example, where the multiplex throw has two different heights/lengths. It could be denoted as either `[34]11` or `[43]11`:
```
Beat 1 2 3 4 5 6 7 8 9
Hand L R L R L R L R L
Siteswap [43] 1 1 [43] 1 1 [43] 1 1
││ └─┴──┘│ │
│└────────┘ │
└────────────┘
```
(Note that the `1` thrown at beat `2` lands at beat `3` and is immediately thrown again (as another `1`) to land at beat `4` and be part of the second multiplex throw.)
*The siteswap for the animation at the beginning of this post was* `[53]15121`.
## Pattern Validity
For a pattern to be *semantically* valid the number of balls in a hand must always correspond to the number of throws indicated at that beat. This means, there must be no balls landing at a beat with a `0`, there must be only one ball landing at a beat with any other single digit, and there must be **n** balls landing at a multiplex beat, where **n** is the number of digits in that multiplex throw. The pattern must also be able to repeat seamlessly.
Examples of invalid patterns are `543` (all balls would land at the same beat), `240` (the `2` would land at the `0` beat) or `33[24]` (no ball lands at the multiplex beat, but two balls land at both of the other two beats).
## The Challenge
You will take a siteswap pattern which contains wildcards and output a valid pattern, with those wildcards filled in.
Take as **input (via stdin, command-line argument, file or function parameter)** a string of the format
```
n s
```
Where `n` is an integer indicating the number of balls to be used, and `s` is a siteswap pattern (*without* whitespace). You may assume that it is *syntactically* correct - all square brackets are matched and not nested, and there are no unexpected characters. All throws will be single-digit throws (`0` - `9`). **However**, some *beats* may just be denoted as a `_`, which is to be filled in with a single or a multiplex throw in the output.
*Note:* something like `[_3]` will *not* be part of the input. Either the entire beat is missing or the entire beat is given.
Output a valid pattern, which can be juggled with the given number of balls and agrees with the input pattern in all the specified beats. If no valid pattern is possible with the given inputs, output `!`. **Output** will also be **via stdout, to a file or as a function return value.**
*Note:* The output must not contain unnecessary square brackets or zeroes in multiplex throws. So outputs containing `[3]` or `[03]` are not accepted, you have to output `3` instead. The order of digits in a multiplex throw is not relevant.
*Note:* You *may* omit patterns that are duplicates under cyclic permutations. E.g. for input `3 __` (note the two wildcards), both `42` and `24` are valid answers (among others), but they actually describe the same pattern. You can either output both or just one of them, but you'll have to do it consistently.
This is **code golf**, the shortest code wins (subject to bonuses listed at the bottom of the question).
You can use [JugglingLab](http://jugglinglab.sourceforge.net/) to play around with patterns to see if they are valid and what they look like.
### Examples
```
Input Possible Outputs Comments
3 _ 3
[21]
[111]
3 4_3 423
4 4_2 4[51]2
4[42]2
4[321]2
3 _23_ 6231
4233
323[31]
2235
223[41]
0237
023[43]
[42]231
[32]23[11]
```
```
4 5_3 ! 5 and 3 will both land at the third beat, but
there is only a single throw at that beat. This
cannot be fixed with any throw in the blank.
2 5_4 ! Any possible throw in the wildcard (including a
0) will make a pattern for at least 3 balls.
3 54_ ! The only solution that would correspond to a
3-ball pattern is 540, which is not semantically
valid because the 5 and 4 both land at beat 3.
There are valid solutions, but they require at
least 4 balls.
```
### Bonuses
* If your answer can handle "digits" up to 35, denoted by letters (10 = A, 11 = B, ...), subtract **20 characters**. You may decide if those letters should be upper-case, lower-case or case-insensitive. (JugglingLab can handle them in lower-case if you want to look at some insane patterns.)
* If your answer outputs *all* valid solutions, subtract **20 characters**.
[Answer]
## Python, 587 - 20 = 567 chars
```
from itertools import *
E,J,L,R,X=enumerate,''.join,len,range,list
def f(x):
[u,p]=str.split(x);n=int(u);a=[[[x],x][type(x)==X]for x in eval("["+J(c if c=="["else"-1,"if c=="_"else c+","for c in p)+"]")];l,w=L(a),[i for i,x in E(a)if x==[-1]]
for j in product([[0]]+X(chain(*[combinations_with_replacement(R(1,10),i+1)for i in R(n+1)])),repeat=L(w)):
for k,m in zip(w,j):a[k]=m
b=[0]*l
for k,x in E(a):
for y in x:b[(k+y)%l]+=1
if all(x==L(y)for x,y in zip(b,a))&((sum(map(sum,a))/l)==n):
u=0;yield J([['['+J(map(str,x))+']',str(x[0])][L(x)==1]for x in a])
if u:yield"!"
```
] |
[Question]
[
### Background
[PICASCII](http://picascii.com/) is a neat tool that converts images into ASCII art.
It achieves different degrees of brightness by using the following ten ASCII characters:
```
@#+';:,.`
```
We'll say that these charxels (character elements) have brightnesses from 1 (at-sign) to 10 (space).
Below, you can see the results of converting a little code, the Welsh flag, an overhanded fractal, a large trout and a little golf, displayed with the correct font:

Your can see the images in [this fiddle](http://jsfiddle.net/14u3vw4p/embedded/result/) and download them from [Google Drive](https://drive.google.com/open?id=0Byb-iITM2Kk2flpycFdMZHltVEZIaEpFN2pLd1QtZHVNeS1Xak5NNGxCTmRCZ2pYRDhiU3M).
### Task
While the end results of PICASCII are visually pleasing, all five images combined weigh 153,559 bytes. How much could these images be compressed if we are willing to sacrifice part of their quality?
Your task is to write a program that accepts an ASCII art image such as the above ones and a minimum quality as input and prints a lossy compression of the image – in form of a full program or a function returning a single string – that satisfies the quality requirement.
**This means that you do not get to write a separate decompressor; it must be built-in into each of the compressed images.**
The original image will consist of charxels with brightnesses between 1 and 10, separated by linefeeds into lines of the same length. The compressed image must have the same dimensions and use the same set of characters.
For an uncompressed image consisting of **n** charxels, the quality of a compressed version of the image is defined as

where **ci** is the brightness of the **i**th charxel of the compressed image's output and **ui** the brightness of the **i**th charxel of the uncompressed image.
### Scoring
Your code will be run with the five images from above as input and minimum quality settings of 0.50, 0.60, 0.70, 0.80 and 0.90 for each of the images.
Your score is the geometric mean of the sizes of all compressed images, i.e., the twenty-fifth root of the product of the lengths of all twenty-five compressed images.
The lowest score wins!
### Additional rules
* Your code has to work for arbitrary images, not just the ones used for scoring.
It is expected that you optimize your code towards the test cases, but a program that does not even *attempt* to compress arbitrary images won't get an upvote from me.
* Your compressor may use built-in byte stream compressors (e.g., gzip), but you have to implement them yourself for the compressed images.
Bulit-ins normally used in byte stream decompressors (e.g., base conversion, run-length decoding) are allowed.
* Compressor and compressed images do not have to be in the same language.
However, you must pick a single language for all compressed images.
* For each compressed image, standard code golf rules apply.
### Verification
I've made a CJam script to easily verify all quality requirements and calculate a submission's score.
You can download the Java interpreter from [here](http://sourceforge.net/p/cjam/wiki/Home/) or [here](https://drive.google.com/open?id=0Byb-iITM2Kk2flpycFdMZHltVEZIaEpFN2pLd1QtZHVNeS1Xak5NNGxCTmRCZ2pYRDhiU3M).
```
e# URLs of the uncompressed images.
e# "%s" will get replaced by 1, 2, 3, 4, 5.
"file:///home/dennis/codegolf/53199/original/image%s.txt"
e# URLs of the compressed images (source code).
e# "%s-%s" will get replaced by "1-50", "1-60", ... "5-90".
"file:///home/dennis/codegolf/53199/code/image%s-%s.php"
e# URLs of the compressed images (output).
"file:///home/dennis/codegolf/53199/output/image%s-%s.txt"
e# Code
:O;:C;:U;5,:)
{
5,5f+Af*
{
C[IQ]e%g,X*:X;
ISQS
[U[I]e%O[IQ]e%]
{g_W=N&{W<}&}%
_Nf/::,:=
{
{N-"@#+';:,.` "f#}%z
_::m2f#:+\,81d*/mq1m8#
_"%04.4f"e%S
@100*iQ<"(too low)"*
}{
;"Dimension mismatch."
}?
N]o
}fQ
}fI
N"SCORE: %04.4f"X1d25/#e%N
```
### Example
>
> ### Bash → PHP, score 30344.0474
>
>
>
> ```
> cat
>
> ```
>
> Achieves 100% quality for all inputs.
>
>
>
> ```
> $ java -jar cjam-0.6.5.jar vrfy.cjam
> 1 50 1.0000
> 1 60 1.0000
> 1 70 1.0000
> 1 80 1.0000
> 1 90 1.0000
> 2 50 1.0000
> 2 60 1.0000
> 2 70 1.0000
> 2 80 1.0000
> 2 90 1.0000
> 3 50 1.0000
> 3 60 1.0000
> 3 70 1.0000
> 3 80 1.0000
> 3 90 1.0000
> 4 50 1.0000
> 4 60 1.0000
> 4 70 1.0000
> 4 80 1.0000
> 4 90 1.0000
> 5 50 1.0000
> 5 60 1.0000
> 5 70 1.0000
> 5 80 1.0000
> 5 90 1.0000
>
> SCORE: 30344.0474
>
> ```
>
>
[Answer]
# Java → CJam, score ≈4417.89
```
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import net.aditsu.cjam.CJam;
public class Compress {
protected static final char[] DIGITS = "0123456789ABCDEFGHIJK".toCharArray();
protected static final String CHARS = "@#+';:,.` ";
protected static final char[] CHR = CHARS.toCharArray();
private static class Img {
public final int rows;
public final int cols;
public final int[][] a;
public Img(final int rows, final int cols) {
this.rows = rows;
this.cols = cols;
a = new int[rows][cols];
}
public Img(final List<String> l) {
rows = l.size();
cols = l.get(0).length();
a = new int[rows][cols];
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
a[i][j] = CHARS.indexOf(l.get(i).charAt(j));
}
}
}
public static Img read(final Reader r) {
try {
final BufferedReader br = new BufferedReader(r);
final List<String> l = new ArrayList<>();
while (true) {
final String s = br.readLine();
if (s == null || s.isEmpty()) {
break;
}
l.add(s);
}
br.close();
return new Img(l);
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
public static Img read(final File f) {
try {
return read(new FileReader(f));
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
public Img scaleDown(final int fr, final int fc) {
final int r1 = (rows + fr - 1) / fr;
final int c1 = (cols + fc - 1) / fc;
final Img x = new Img(r1, c1);
final int[][] q = new int[r1][c1];
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
x.a[i / fr][j / fc] += a[i][j];
q[i / fr][j / fc]++;
}
}
for (int i = 0; i < r1; ++i) {
for (int j = 0; j < c1; ++j) {
x.a[i][j] /= q[i][j];
}
}
return x;
}
public Img scaleUp(final int fr, final int fc) {
final int r1 = rows * fr;
final int c1 = cols * fc;
final Img x = new Img(r1, c1);
for (int i = 0; i < r1; ++i) {
for (int j = 0; j < c1; ++j) {
x.a[i][j] = a[i / fr][j / fc];
}
}
return x;
}
public Img crop(final int r, final int c) {
if (r == rows && c == cols) {
return this;
}
final Img x = new Img(r, c);
for (int i = 0; i < r; ++i) {
for (int j = 0; j < c; ++j) {
x.a[i][j] = a[i][j];
}
}
return x;
}
public Img rescale(final int fr, final int fc) {
return scaleDown(fr, fc).scaleUp(fr, fc).crop(rows, cols);
}
public double quality(final Img x) {
if (x.rows != rows || x.cols != cols) {
throw new IllegalArgumentException();
}
double t = 0;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
final int y = a[i][j] - x.a[i][j];
t += y * y;
}
}
t /= 81 * rows * cols;
t = 1 - Math.sqrt(t);
return Math.pow(t, 8);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
sb.append(CHR[a[i][j]]);
}
sb.append('\n');
}
return sb.toString();
}
public Array toArray() {
final Array x = new Array(rows * cols);
int k = 0;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
x.a[k++] = a[i][j];
}
}
return x;
}
public String compress(final double quality) {
int bi = 1;
int bj = 1;
int bs = rows * cols;
Img bx = this;
for (int i = 1; i < 3; ++i) {
for (int j = 1; j < 3; ++j) {
Img x = rescale(i, j);
if (quality(x) >= quality) {
x = scaleDown(i, j);
if (x.rows * x.cols < bs) {
bi = i;
bj = j;
bs = x.rows * x.cols;
bx = x;
}
}
}
}
Array a = bx.toArray();
int bf = 0;
for (int i = 1; i <= 20; ++i) {
final int t = a.rle11(i).n;
if (t < bs) {
bs = t;
bf = i;
}
}
int b = 10;
if (bf > 0) {
b = 11;
a = a.rle11(bf);
}
String s = null;
for (int i = 92; i < 97; ++i) {
for (char c = ' '; c < '$'; ++c) {
final String t = a.cjamBase(b, i, c);
boolean ok = true;
for (int j = 0; j < t.length(); ++j) {
if (t.charAt(j) > '~') {
ok = false;
break;
}
}
if (!ok) {
continue;
}
if (s == null || t.length() < s.length()) {
s = t;
}
}
}
if (bf > 0) {
s += "{(_A={;()";
if (bf > 1) {
s += DIGITS[bf] + "*";
}
s += "\\(a@*}&\\}h]e_";
}
if (bi * bj == 1) {
return s + '"' + CHARS + "\"f=" + cols + "/N*";
}
s += bx.cols + "/";
if (bi > 1) {
s += bi + "e*";
if (rows % 2 == 1) {
s += "W<";
}
}
if (bj > 1) {
s += bj + "fe*";
if (cols % 2 == 1) {
s += "Wf<";
}
}
return s + '"' + CHARS + "\"ff=N*";
}
public void verify(final String s, final double quality) {
final String t = CJam.run(s, "");
final Img x = read(new StringReader(t));
final double q = quality(x);
if (q < quality) {
throw new RuntimeException(q + " < " + quality);
}
// System.out.println(q + " >= " + quality);
}
}
private static class Array {
public final int[] a;
public final int n;
public Array(final int n) {
this.n = n;
a = new int[n];
}
public Array(final int[] a) {
this.a = a;
n = a.length;
}
public String join() {
final StringBuilder sb = new StringBuilder();
for (int x : a) {
sb.append(x).append(' ');
}
sb.setLength(sb.length() - 1);
return sb.toString();
}
// public String cjamStr() {
// final StringBuilder sb = new StringBuilder("\"");
// for (int x : a) {
// sb.append(DIGITS[x]);
// }
// sb.append("\":~");
// return sb.toString();
// }
public String cjamBase(final int m, final int b, final char c) {
final boolean zero = a[0] == 0;
String s = join();
if (zero) {
s = "1 " + s;
}
s = CJam.run("q~]" + m + "b" + b + "b'" + c + "f+`", s);
s += "'" + c + "fm" + b + "b" + DIGITS[m] + "b";
if (zero) {
s += "1>";
}
return s;
}
public Array rle11(final int f) {
final int[] b = new int[n];
int m = 0;
int x = -1;
int k = 0;
for (int i = 0; i <= n; ++i) {
final int t = i == n ? -2 : a[i];
if (t == x && m < 11 * f) {
m++;
}
else {
if (m >= f && m > 3) {
b[k++] = 10;
b[k++] = m / f - 1;
b[k++] = x;
for (int j = 0; j < m % f; ++j) {
b[k++] = x;
}
}
else {
for (int j = 0; j < m; ++j) {
b[k++] = x;
}
}
m = 1;
x = t;
}
}
return new Array(Arrays.copyOf(b, k));
}
}
private static void score() {
double p = 1;
for (int i = 1; i < 6; ++i) {
final File f = new File("image" + i + ".txt");
final Img img = Img.read(f);
final int n = (int) f.length();
for (int j = 5; j < 10; ++j) {
final double q = j / 10.0;
final String s = img.compress(q);
System.out.println(f.getName() + ", " + q + ": " + n + " -> " + s.length());
img.verify(s, q);
p *= s.length();
}
}
System.out.println(Math.pow(p, 1 / 25.0));
}
public static void main(final String... args) {
if (args.length != 2) {
score();
return;
}
final String fname = args[0];
final double quality = Double.parseDouble(args[1]);
try {
final Img img = Img.read(new File(fname));
final String s = img.compress(quality);
img.verify(s, quality);
final FileWriter fw = new FileWriter(fname + ".cjam");
fw.write(s);
fw.close();
}
catch (IOException e) {
throw new RuntimeException();
}
}
}
```
Requires the CJam jar in the classpath. If you give it 2 command line arguments (file name and quality), it appends ".cjam" to the file name and writes the compressed image there. Otherwise it calculates its score on the 5 test images, which are assumed to be in the current directory. The program also verifies every compressed image automatically. You may want to double-check the score calculation in case there's any discrepancy.
The techniques used (so far) are: scaling to half (horizontally, vertically or both) if it doesn't reduce the quality too much, a custom-coded RLE, and base conversion to pack more data into each character while remaining in the printable ASCII range.
[Answer]
# Python 3.5 (main and output) (currently noncompeting)
Happy Birthday, Challenge! Here's your present: an answer!
EDIT: Converted output to python code, improved compression rate (slightly)
EDIT2: Made it print raw when `size` is 1. Improved score, but score needs to be calculated again.
EDIT3: @Dennis pointed out that I still haev bugs to fix, so I marked the answer as noncompeting
Code:
```
import sys
LIST = [' ','`','.',',',':',';',"'",'+','#','@']
def charxel_to_brightness(charxel):
return LIST.index(charxel)
def brightness_to_charxel(bright):
return LIST[bright]
def image_to_brightness(imagetext):
return [list(map(charxel_to_brightness,line)) for line in imagetext.split("\n")]
def brightness_to_image(brightarray):
return '\n'.join([''.join(map(brightness_to_charxel,line)) for line in brightarray])
def split_into_parts(lst,size):
return [lst[x:x+size] for x in range(0, len(lst), size)]
def gen_updown(startxel,endxel,size):
return [[int((size-r)*(endxel-startxel)/size+startxel) for c in range(size)] for r in range(size)]
def gen_leftright(startxel,endxel,size):
return [[int((size-c)*(endxel-startxel)/size+startxel) for c in range(size)] for r in range(size)]
def gen_tlbr(startxel,endxel,size):
return [[int((2*size-r-c)/2*(endxel-startxel)/size+startxel) for c in range(size)] for r in range(size)]
def gen_bltr(startxel,endxel,size):
return [[int((size-r+c)/2*(endxel-startxel)/size+startxel) for c in range(size)] for r in range(size)]
def gen_block(code,startxel,endxel,size):
if code==0:return gen_updown(startxel,endxel,size)
if code==1:return gen_leftright(startxel,endxel,size)
if code==2:return gen_bltr(startxel,endxel,size)
if code==3:return gen_tlbr(startxel,endxel,size)
def vars_to_data(code,startxel,endxel):
acc=endxel
acc+=startxel<<4
acc+=code<<8
return acc
def data_to_vars(data):
code=data>>8
startxel=(data>>4)&15
endxel=data&15
return code,startxel,endxel
def split_into_squares(imgarray,size):
rows = split_into_parts(imgarray,size)
allsquares = []
for rowblock in rows:
splitrows = []
for row in rowblock:
row = split_into_parts(row,size)
splitrows.append(row)
rowdict = []
for row in splitrows:
for x in range(len(row)):
if len(rowdict)<=x:
rowdict.append([])
rowdict[x].append(row[x])
allsquares.append(rowdict)
return allsquares
def calc_quality(imgarray,comparray):
acc=0
for row in range(len(imgarray)):
for col in range(len(imgarray[row])):
acc+=pow(imgarray[row][col]-comparray[row][col],2)
return (1-(acc/81.0/sum([len(row) for row in imgarray]))**.5)**8
def fuse_squares(squarray):
output=[]
counter=0
scounter=0
sqrow=0
while sqrow<len(squarray):
if scounter<len(squarray[sqrow][0]):
output.append([])
for square in squarray[sqrow]:
output[counter].extend(square[scounter])
scounter+=1
counter+=1
else:
scounter=0
sqrow+=1
return output
def main_calc(imgarray,threshold):
imgarray = image_to_brightness(imgarray)
size = 9
quality = 0
compimg=[]
datarray=[]
testdata = [vars_to_data(c,s,e) for c in range(4) for s in range(10) for e in range(10)]
while quality<threshold:
squares = split_into_squares(imgarray,size)
compimg = []
datarray = []
testblock = [gen_block(c,s,e,size) for c in range(4) for s in range(10) for e in range(10)]
for row in squares:
comprow = []
datrow=[]
for square in row:
quality_values = [calc_quality(square,block) for block in testblock]
best_quality = quality_values.index(max(quality_values))
comprow.append(testblock[best_quality])
datrow.append(testdata[best_quality])
compimg.append(comprow)
datarray.append(datrow)
compimg = fuse_squares(compimg)
quality = calc_quality(imgarray,compimg)
print("Size:{} Quality:{}".format(size,quality))
size-=1
return brightness_to_image(compimg),datarray,size+1
template = '''def s(d,s,e,z):
x=range(z)
return d<1 and[[int((z-r)*(e-s)/z+s)for c in x]for r in x]or d==1 and[[int((z-c)*(e-s)/z+s)for c in x]for r in x]or d==2 and[[int((2*z-r-c)/2*(e-s)/z+s)for c in x]for r in x]or d>2 and[[int((z-r+c)/2*(e-s)/z+s)for c in x] for r in x]
i=lambda a:'\\n'.join([''.join(map(lambda r:" `.,:;'+#@"[r],l))for l in a])
def f(a):
o=[];c=0;s=0;r=0
while r<len(a):
if s<len(a[r][0]):
o.append([])
for q in a[r]:
o[c].extend(q[s])
s+=1;c+=1
else:
s=0;r+=1
return o
t={};z={}
print(i(f([[s(D>>8,(D>>4)&15,D&15,z)for D in R]for R in t])))'''
template_size_1 = '''print("""{}""")'''
def main(filename,threshold):
print(filename+" "+str(threshold))
file = open(filename,'r')
compimg,datarray,size = main_calc(file.read(),threshold)
file.close()
textoutput = open(filename.split(".")[0]+"-"+str(threshold*100)+".txt",'w')
textoutput.write(compimg)
textoutput.close()
compoutput = open(filename.split(".")[0]+"-"+str(threshold*100)+".py",'w')
datarray = str(datarray).replace(" ","")
code = ""
if size==1:
code = template_size_1.format(compimg)
else:
code= template.format(datarray,str(size))
compoutput.write(code)
compoutput.close()
print("done")
if __name__ == "__main__":
main(sys.argv[1],float(sys.argv[2]))
```
This answer could use **a lot** of improvements, so I'll probably be working on it more over the weekend.
### How this works:
* Divide image into blocks of size `size`.
* Find best matching block
+ Blocks can have gradient now!
* Calculate quality (according to formula) for entire image.
* If correct, write zipped image to file.
* Otherwise, decrement `size` and try again.
This algorithm works well for low quality (0.5, 0.6) but doesn't work too well on the higher quality images (actually inflates). It is also really slow.
[Here](https://www.dropbox.com/sh/vqhzhu9pzmliegt/AABf3DQnh_U9-LWETFptV9bla?dl=0) I have all the generated files, so you won't have to re-generate them again.
] |
[Question]
[
This is not just another challenge asking you to color random maps... In this challenge, you are asked to write a program that is **actually used** in the formal proof of the Four Color Theorem.
First I shall describe the challenge without any background or motivation, for the impatient.
A **chromogram** is a list made of the symbols `-` `[` `]0` `]1`, where the brackets are required to match. A **coloring** is just a list made of 1, 2 and 3's whose bitwise sum (i.e. XOR) is zero. A coloring is said to **fit** a chromogram if:
* They are of the same length.
* `-`'s in the chromogram corresponds to `1`'s in the coloring at the same positions.
* Brackets corresponds to `2`'s and `3`'s. For matching brackets, if they are `[ ]0` then they correspond to the same color, and different colors if they are `[ ]1`.
Some examples:
```
Chromogram <-> Coloring
[ [ - ]1 - ]0 - <-> 2 3 1 2 1 2 1
[ [ - ]1 - ]0 - <-> 3 3 1 2 1 3 1
[ ]1 - <-> 2 3 1
[ ]1 - <-> 3 2 1
```
Given colorings \$C\$, a **compatible** coloring is one such that each of its chromograms fits with some \$c\in C\$ (different chromograms can fit different colorings). More formally, we define "\$c'\$ is compatible with \$C\$" as the logical proposition "for each chromogram \$\gamma\$ that fits \$c'\$, there exists \$c\in C\$ such that \$\gamma\$ fits \$c\$." We define a **suitable** coloring with the following rules:
* All colors in \$C\$ are suitable.
* For a suitable coloring, switching 1, 2 and 3's consistently produces another suitable coloring. E.g. `12321 -> 21312 or 32123 or 13231`, but not `11311` or `12331`. Formally, if \$\rho\$ is a permutation of \$\{1,2,3\}\$, then if \$\langle c\_1, c\_2, \dots, c\_n \rangle\$ is a suitable coloring, \$\langle \rho c\_1, \rho c\_2, \dots, \rho c\_n \rangle\$ is also one.
* For a set of suitable coloring \$D\$, all its compatible colorings are suitable. Note that if you put more suitable colorings into the set \$D\$, an originally compatible coloring will never cease to be compatible. So in your code, you can greedily add suitable colorings without worrying that you will "miss the chance" to apply this rule.
* All the suitable colorings are generated by the rules above.
As an example, take \$C\$ to have two colorings `1111, 2323`. You can use the second rule to claim that `2222` is suitable. Then `2233` is suitable using the third rule, because it fits two chromograms `[ ]0 [ ]0` and `[ [ ]1 ]1`, the first of which fits `2222`, and the second fits `2323`.
Now the challenge:
>
> **Challenge**. Input a set of coloring \$C\$, determine if all the colorings of the same length are suitable. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'").
>
>
>
A hint: A sequence of 1, 2 and 3's have the bitwise sum (XOR) zero if and only if the parity of each kind of number are the same, i.e. the numbers of occurrences of 1's, 2's and 3's are all odd or all even. But probably XOR'ing all of them is more golfy.
---
Now it's time for stories. The **Four Color Theorem** states that any planar map can be colored with four colors, so that the regions that meet at boundaries are colored differently.
I'll try to briefly describe the proof of the Four Color Theorem, in steps.
1. First, if you create a tiny region at every corner (i.e. where three or more regions meet), you get a map where no more than three regions meet at a point, and if you can color these kind of maps, you can remove the added region and recover a coloring of the original map. These special maps are called **cubic**.
2. Now we reason by reductio ad absurdum. Consider the *smallest* cubic counterexample. Any map smaller than that will be 4-colorable.
3. Next, by a method of **discharging**, we compute a score for each region, ensuring that the average score is less than 6. This means that there must be at least one region with score less than 6. In this way we locate a "weak spot" of the putative counterexample, where we are going to attack.
4. We, by the aid of a program (not related to this challenge), prove that the neighborhood of the weak spots that we may find always falls in one of the 633 possibilities. This allows us to do a case-by-case analysis.
5. In each case, we remove some boundaries in the neighborhood of the weak spot, creating a smaller map. By hypothesis, this map is 4-colorable. We then try to recolor the original map based on the smaller map, only adjusting the colors in the neighborhood. This is not always possible. So we try to adjust the outer regions also. This is difficult because changing one regions's color may affect other regions. We now develop a more convenient tool.
6. Notice that if, instead of coloring the regions by colors \$0,1,2,3\$, we color the *boundaries* of the map, by computing the bitwise sum of the two regions on either side of the boundaries, we can color the boundaries with \$1,2,3\$. It can be proven that the original coloring can always be recovered from the boundary coloring. Now the situation is clearer. Note that exactly 3 boundaries meet at a corner, and they always have different colors. Suppose we want to change an boundary color from 2 to 3 (the boundary sticks out from the neighborhood we just considered, so it will be consistent with the colors in the neighborhood), the only hinderance is the edge colored 3 connected to it (there is only one such edge extending outwards, can you see why?). If we change that 3 into 2, a further edge colored 2 will protest! In this way, we can go on and on in a chain. And the key insight is that **the chain cannot intersect itself**, so it will always come back sticking into the neighborhood again.
7. So now, the boundaries colored 2/3 will form *arches* standing on the edge of the neighborhood we are considering. These arching structures are captured by our **chromograms**, and the colors of the boundaries sticking out of the neighborhood are represented by the **colorings** in our challenge. Now if you reread the challenge, you will understand that, given the recoloring that we have for the neighborhood, the challenge is to determine if every possible coloring for the outer map can be adjusted to match.
---
Phew! That was, alas, the briefest that I can manage without losing too much detail! You can see that our challenge is only concerned with the *last* step, and there are more potential challenges lurking about. But this I leave to those who are interested. You can consult [this paper](https://www.cl.cam.ac.uk/%7Elp15/Pages/4colproof.pdf) for a more detailed account. I hope this challenge can kindle some interest in the four color theorem and its proof.
---
Routine code-golf test cases:
```
T 123
T 1111,2323
F 1111,2332
T 11123,12113,12311
F 11123,12113,12131
T 111111,123132,123231,123312,123213,112323,121222,122122,122212
F 123132,123231,123312,123213,112323,121222,122122,122212
F 123231,123312,123213,112323,121222,122122,122212
F 111111,123312,123213,112323,121222,122122,122212
T 111111,123231,123213,112323,121222,122122,122212
F 111111,123231,123312,112323,121222,122122,122212
F 111111,123231,123312,123213,121222,122122,122212
F 111111,123231,123312,123213,112323,122122,122212
T 111111,123231,123312,123213,112323,121222,122212
F 111111,123231,123312,123213,112323,121222,122122
F 111111,123132,123312,123213,112323,121222,122122,122212
T 111111,123132,123231,123213,112323,121222,122122,122212
F 111111,123132,123231,123312,112323,121222,122122,122212
F 111111,123132,123231,123312,123213,121222,122122,122212
F 111111,123132,123231,123312,123213,112323,122122,122212
T 111111,123132,123231,123312,123213,112323,121222,122212
F 111111,123132,123231,123312,123213,112323,121222,122122
```
I hesitate to include larger test cases, because to do those in reasonable time, some algorithm other than the most naive one is needed. I don't want to complicate things too much, since they are already so complicated. Better algorithms can be found in the linked paper.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 835 bytes
```
E=enumerate
G=len
def m(c,o):
i=o;b=0
for v in c[o:]:
b+=(v==1)-(v>1)
if b==0:break
i+=1
return i
f=lambda c,C:G(c)==G(C)and all(C[i]<2if V<1else V!=1or(h:=m(c,i))<G(C)and eval(f'1<C[i]{" =!"[c[h]]}=C[h]>1')for i,V in E(c))
def N(l,L):
if L<2:return[[V]for V in l]
r=[]
for V in l:
for g in N(l,L-1):r+=[[V,*g]]
return r
def A(s,B=[]):
W=[C for C in N([1,2,3],G(s[0]))if eval('^'.join(str(Q)for Q in C))==0]
S=s+[C for C in W if all(any(f(c,T)for T in s)for c in N([0,1,2,3],G(C))if all(V!=1or m(c,i)<G(c)for i,V in E(c))and c.count(1)==c.count(2)+c.count(3)and f(c,C))]
for C in[*S]:
for p in[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]:S+=[[p[o-1]for o in C]]
S=[''.join(str(o)for o in C)for C in S];S=[*{*S}];S=[[int(Y)for Y in C] for C in S];D=[G(B),G(W)]
if G(S)in D:return D.index(G(S))
return A(S,s)
```
[Try it online!](https://tio.run/##pVXfT@MwDH7vXxF4abKFaWlfTmVBggJ7QSehTUMol5O6roPelbZqu2kI8bcPO13LDrgT5fbLju0vtr90Tv5Y3Wep@y0vttsLGaWrh6gIqsgayyRKrUW0JA805BnzLBLL7HguhxZZZgVZkzgloco8DR4y70u6llKwI7o@EQws8ZLMpRx68yIKfuO6L4VFiqhaFSmJraVMgof5IiAh970xDZmUY@qzIF2QIEmor2I9cmCP2UhESRmR2YEUWUHvPYnlxIyNmvBoHSR0aYsRYp4OCZEHhypU91o/Sx/EibAZFhzzGZZ8AbmY6es7TfiV6WtJrkaOV9em1ExjuAlONJQsla5brk3YLq7ucGX2OBLMK/oSkLx3p3XbZWHSnNKSn8EemOlGKt@A/RqsBHe4q/mYlmqoGYNKTDv2T3vwK4tTWlYFvTblXyPCZ8DTEDJMZNnf3@oGm0DigvSRLoGhqQFN0VcaNdxlHPI2p28SIqpml9TUjvA43jKGTIeDMFulFRVQRKM7rN@orgnC5LDxjjIsTvUmuiEtx3XTNUiXOyAdqMk10uUCpIs1Ggkerb0Jkpur7EiYo8kMFdrQoOw9pjL26mYtNxN9DHG9p97k2WgqhmJvjf@23onsx55LNaZnDPi5wS6AoTGdMPCd754Qcj6I00W0oWhn7Wmf0gkv2TZO81VVEkls27aE41oCXtxxXzXXQc2BJh0h8NcV4o1FuMaC8eh2HRSgoHBFvcJAY8V4x0EjShQgrf/AdQS0dXYG7BJ1BphEnQG7RJ0BTaLOgCZRZwB83h9/Z3b/PP6v4j7P9d8ft6/i/s385x/vr@LwHOBvrIQHk2dQ5klcUftHajOr/ZfDMMkbD7eZmSRgwllSx@i92Hr0bOqojblAs6SePqDsMPqjPaxok0dhFS12g2UK78v2e/lO7q8@7sCqJ3yTqL34aZ0Sb6u8wHLty6mtTtHMNCdNHXDXsu0L "Python 3.8 (pre-release) – Try It Online")
Thanks @Steffan for -11 bytes.
Not exactly the golfiest version that could be produced. I will continue to golf this code.
Not very efficient. Takes at least ~~15~~ 3 minutes to complete all 22 testcases. Thus, don't expect the TIO link to work. You can, however, run it locally if Python is on your machine. The TIO link includes a test suite that compares the outputs against the expected outputs.
## Explanation
Just implements the question's spec literally. Defines a helper function `f` that checks if a chromogram fits a coloring. In the main function `A`, starts off with the inputted set plus set of compatible colorings (implemented based on the question's definition, making sure to check that lists that are purportedly chromograms and colorings are actually chromograms and colorings), then adds the permutations, removes duplicates, then:
* if every coloring of the same length as each coloring of the inputted set is in the set generated according to the above, then return 1.
* if no new colorings were added (i.e. length of generated set is the same as that of the previous set [c.f. below]), return 0. (once we add all the colorings of the same length, the function returns 1 before calling itself, thus avoiding returning 0)
* otherwise, recall the function with the new set and passing the previous set (which starts empty).
Ungolfed version (2778 bytes):
```
def matching_bracket(c,o):
index = opening
bracket_level = 0
for value in chromogram[opening:]:
if value == 1:
bracket_level += 1
if value > 1:
bracket_level -= 1
if bracket_level == 0:
break
index += 1
return index
def valid_brackets(chromogram, coloring, opening):
index = matching_bracket(chromogram, opening)
try:
if chromogram[index] == 2:
return 1 < coloring[opening] == coloring[index]
return 1 < coloring[opening] != coloring[index] > 1
except IndexError:
return False
def fits(chromogram, coloring):
return (len(chromogram) == len(coloring)) and \
(all([coloring[i] == 1 if value == 0 else value != 1 or valid_brackets(chromogram, coloring, i) for i, value in enumerate(chromogram)]))
def generate_nary(l, length):
if length < 2:
return [[val] for val in l]
return_list = []
for val in l:
for generated in generate_nary(l, length - 1):
return_list.append([val, *generated])
return return_list
def generate_all_chromograms(length):
return generate_nary([0, 1, 2, 3], length)
def all_fitted_chromograms(coloring):
return [chromogram for chromogram in generate_all_chromograms(len(coloring)) if [value != 1 or matching_bracket(chromogram, i) < len(chromogram) for i, value in enumerate(chromogram)] and chromogram.count(1) == chromogram.count(2) + chromogram.count(3) and fits(chromogram, coloring)]
def is_compatible(coloring, _set):
all_chromos = all_fitted_chromograms(coloring)
return all([
any([fits(chromo, c) for c in _set])
for chromo in all_chromos
])
def all_colorings(length):
return [c for c in generate_nary([1, 2, 3], length) if eval('^'.join([str(num) for num in c])) == 0]
def permutations_of_coloring(coloring):
colorings = []
for permutation in [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]:
colorings.append([permutation[num - 1] for num in coloring])
return colorings
def all_suitable_colorings(_set, before = []):
# 1) all colorings in _set are suitable.
colorings = all_colorings(len(_set[0]))
# let us add our compatible colorings.
initial_set = _set + [coloring for coloring in colorings if is_compatible(coloring, _set)]
# then, we get all the permutations of each of those colorings.
for coloring in [*initial_set]:
for permutated in permutations_of_coloring(coloring):
initial_set.append(permutated)
initial_set = [''.join([str(num) for num in coloring]) for coloring in initial_set]
initial_set = [*{*initial_set}] # remove duplicates
initial_set = [[int(char) for char in coloring] for coloring in initial_set]
if len(initial_set) in [len(before), len(colorings)]:
return initial_set
return all_suitable_colorings(initial_set, _set)
def main(_set):
return len(all_suitable_colorings(_set)) == len(all_colorings(len(_set[0])))
```
```
] |
[Question]
[
Input is an r by c matrix of non-negative integers (you may input r and c as other parameters if this helps with golf). This may be inputted as a 2D array or, if you prefer, a 1D array (though taking in r this time is necessary). Strings separated by spaces to distinguish rows and newlines to distinguish columns are also fine (below, the test cases have multiple spaces to distinguish rows for clarity -- you do not have to do this).
Consider a matrix of zeros. A *move* consists of replacing a rectangle of numbers with a rectangle of some *positive* integer (not zero). For example, these are all valid first moves:
```
0 0 0 0
0 2 0 0
0 0 0 0
0 0 0 0
0 3 0 0
0 3 0 0
0 3 0 0
0 3 0 0
1 1 1 0
1 1 1 0
0 0 0 0
0 0 0 0
```
These are *not* valid first moves:
```
0 0 0 0
0 2 0 0
0 0 0 0
0 2 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
```
**Make *golfed* code to answer the following the question:**
Given an r by c matrix, what is the smallest possible number of turns taken to construct this?
### Test Cases:
```
1 1 1 1
1 2 2 2
1 2 3 3
1 2 3 4
1 2 3 4
> 4
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
> 15
3 3 3 3 3 3
3 2 2 2 2 3
3 2 1 1 2 3
3 2 1 1 2 3
3 2 2 2 2 3
3 3 3 3 3 3
> 3
1 1 1 1 1 1
1 2 2 2 2 1
1 2 0 0 2 1
1 2 0 0 2 1
1 2 2 2 2 1
1 1 1 1 1 1
> 8
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
> 0
1 1 1 1
1 3 3 1
2 3 3 2
2 2 2 4
> 4
```
[Answer]
# [Python 2](https://docs.python.org/2/), 333 bytes
```
lambda g,l=len:min(i for i in r(l(g)*l(g[0])+1)if g in o(l(g[0]),l(g),[[0]*l(g[0])for _ in" "*l(g)],set(sum(g,[])),i))
o=lambda w,h,g,s,I:I and sum([o(w,h,n,s,I-1)for n in[[[x<=j<=X<[]>Y>=i>=y and S or E for j,E in e(R)]for i,R in e(g)]for x in r(w)for X in r(x,w)for y in r(h)for Y in r(y,h)for S in s]],[])or[g]
r=range
e=enumerate
```
[Try it online!](https://tio.run/##NU@xbsMgFNz5iqd2gZZGdbpFIVtUZU06JKKoIjImpDZYQOT4613A6YLe3bs73vVjvDi7nBr2PbWyO9cSNG1Zq@yqMxYbaJwHA8aCxy3W5CU9/F2Q14qYBnReOPzgaBZQnsZ/VTb/JM0TPGWKCBpUxOHWYU25IIQaQpBjj48HeqGaBrpb7UDaGrKOO5xpm@m3qgTaFMg5v6/Zdc2Oay42pw0zGzYW0wGSZFvOvtJtvk/hPRGlBt3PWM/4PtcaSupxBnc6w3GGlwJOMxjpDA8ZBiFyBee5FsgzL61WSDFlb53yMqrpGb7kr4J4UUne3yJCpuudjxDGgJCXA7A8LkKsjV14JWtMEEqum08NYzJFBxJS3ll50N7UCOU32XhrQsSd7HESUfBuWIS@NRETQkrzxJST5WPRGqsCJiLnf6pYjpI2DMoj1PsUAg3O2WSqYIk@oPoD "Python 2 – Try It Online")
This only works in theory, because in practice, it takes way too long if you have more than about 5 elements in the grid.
Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), I apologize for the inefficiency, but efficiency would require more thought and FAR more bytes.
[This](https://tio.run/##dVHBbgIhFDyXr3ixF2ipsT0a8WYar9qDhpAGs29X7C5sALPu11tg7bHZhGXemxneQD/Gs7Mf93uFNdS04a1o0bIlgdp5MGAseNrShr2kRS4Ue31PzSdTQ5N7jj7KPHO4TNs/YtZ/J84MZrnEFA8Yabh26RCpGOOGLT3Gq7dgiBOt7k6VhoGfecMD3y63oG0FmS8dzWWby2/vxThprJTythJmJQ4rqdbHtbisxVhEe0iUTUlw4Zs8J9IdUyUR3024mfBtSjgU18MEbnyC4wTPBRwnMPIJ7jMMSuUozstGES@8tg0SFGivHXod8f4MX/oHIZ4x0ftrJMR0vfMRwhgI8XoAkbfzECtj5x51RRkhSVVuJSZRdKAh@Z3QQ@NNRUhek0y2JkTa6Z4mEgfvhnnoWxMpY6wkT5Uysn40WmMxUKay/yfGMpS2YUBPSO@TSX7@5M3uCygf@ef/Cw) code does the same thing at the cost of 5 bytes, but short-circuits, meaning that a larger grid with a small answer may finish somewhat earlier... the difference in viable search space is negligible, but just in case you wanted to test it a bit more.
The reason this is so slow is because it looks from \$0\$ up to \$W\times H\$, generating every possible \$W\times H\$ grid that can be achieved with the elements of the grid with that many steps being used.
[Answer]
# Python3, 1288 bytes
Long, but crunches the test cases in under a second.
```
R=range
E=enumerate
M=[(1,0),(-1,0),(0,-1),(0,1)]
def D(b):
for x,j in E(b):
for y,_ in E(j):
for X in R(x,len(b)):
for Y in R(y,len(b[0])):yield[(u,i)for u in R(x,X+1)for i in R(y,Y+1)]
def r(b):
S={(x,y)for x,j in E(b)for y,_ in E(j)if _ not in['0']}
W={*S}
while S:
x,y=[(x,y)for x,y in S if b[x][y]!='-'][0];S=S-{(x,y)};d,s={x:[y]},[(x,y)]
V=b[x][y]
q=[(x,y)]
while q:
x,y=q.pop(0)
F=1
for X,Y in M:
J,K=x+X,y+Y
if(J,K)in S and(b[J][K]==V or'-'==b[J][K]):F=0;q+=[(J,K)];S=S-{(J,K)};d={**d,J:sorted(d.get(J,[])+[K])};s=s+[(J,K)]
if all(b==d[min(d)]for b in d.values()):yield s
def Z(B,s,i):
B=eval(str(B))
for x,y in s:B[x][y]=i
return B
V=lambda W,c,S,U:(W==-1 or c+1<W)and all(C>c for C,u in S if u==U)
def f(b):
q,S=[(b,0)],[(0,b)]
L=[i for i in D(b) if i]
W=-1
while q:
B,c=q.pop()
if all(not({*i}-{'-','0'})for i in B):W=c if W==-1 else min(W,c);continue
H=[*r(B)]
for i in H:
U=Z(B,i,'-')
if V(W,c,S,U):
q+=[(U,c+1)];S+=[(c,U)]
if len({sum(B[x][y]!='-'for x,y in j)for j in H})==1:break
U=Z(B,max([i for i in L if len(T:={B[x][y]for x,y in i})<3 and{'-'}!=T and'0'not in T and(len(T)==1 or'-'in T)],key=lambda X:sum(B[x][y]not in{'-','0'}for x,y in X)),'-')
if V(W,c,S,U):q+=[(U,c+1)];S+=[(c,U)]
return W
```
[Try it online!](https://tio.run/##dVRLc9pIED6vfkXHe2DGDC4JsJ0VmT2QR7mcxyHExl6tyiWkIRlHSKARu1AUv93peQhITEqH7unur7vn6x7N1/W3sui9nFdPT595lRRfhfeWi2I5E1VSC@8jj0jAfMpIxwqfdQIjAhp7mZjCGzKhoQfTsoIVewRZwFtrMaY1e7CmR2Mytjtt@UxWLBcFhlqH8dxbz9p6Ij9G51qKPIvIkkmqQ5YN@K4dGINsMPftpqXKNjDiG4xb019a@6UtOYUHKMoaz1HLb8VbD8Z8czpC@f83mQsY6f4wDzKxz7bW8BEgeBKt4mgdv@CtTivGlgcjPurYwttBxhTfrEL0b5mFx5jsljsQ6gu@t9t6C8OHLrg4m5dz4lN9fseDHX/M8PTR8nbN3vNV@46t2/fmLKcETdS0lxQZ0ngdR@9jzm@hrLBHzp2Fhu@4P1i0sQENaBrXOjaOFJxm7DpUZVWLjGRnX0WNviimbY3dDhRXbYf0TFlI8pxMOM@imSxIRmPd60R3mp39l@RLoUgzTlBmTv@QIVM4V7zIkAuMIaquyJDSZp0MyyocWra49KAS9bIqYOjd8jyZTbIExixlI3YTkjHnnQDvCGk7eDWmeHfT0eu/U5PtNVvuZrbk/IaaFqZ2VRZshDRMcMNjnJPPJvpSH3gkYbdies81VsZ6QTqBdziuIUvdtPSwHBe4VGRzKredDdLOcLe2@4Ud0nDMUx1p2xa5EqB5w@vQQVoWtSyWAnNd8ehUcxK7B2XQV2b0N1wTKBlmp24Et8TR4R6Vme4NS/XTGIz0IUVf7BYF9DPbqOWMDA@W@ID6R9OweTlXW8p5EE4qkXz3mtqzZEUOOfrQJP0S8o3LeZBObumrnl5KTcj2Bf@ideTFvj4wR2LgupZdV23HoXwX62bgd@FBxxa6I/ig2B2lDTM/E/NbTtxujZ9UABxOTk68AMyHsqs/I3vQc7K/kzpWdQ9ANthKBKDWs0G9XRD60AF9gHPvAuAS4CXAXwCB7wUI7UKAsD4E5xbYd0CdzX2od91ndVvxub6P2WNN0vOf73l4V53C6D5@x/R9zB5rkl64pL4J938rTfDlM6YNXZ7hGcmzVSzD@r3W5cOkTKqMKNzwP9zEInmm5rmsyf59TWVei4p8KgvBQDl369@iRXHSnjevZFGTKdmnCyj@dp6bu2iGP9VcpDLJoRaqhjRR4khk73iC/nHz@XHzxXHzJZqffgA)
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.