text
stringlengths 180
608k
|
---|
[Question]
[
Your should write a program or function that determines the language of a given word.
The task is to recognize some of the 5000 most common words in 4 languages:
* English
* German
* Italian
* Hungarian
The word lists can be found [in this GitHub repository.](http://github.com/randomra/languages)
You are **allowed to make mistakes in 40% of the provided test cases**. I.e. you can miscategorize 8000 of the 20000 inputs.
## Details
* The lists only contain words with lowercase letters `a-z` so e.g. `won't` and `möchte` are not included.
* A few words appear in multiple languages which means your code can't always guess the expected output correctly.
* For convenience you can download [all the test cases as one list](http://raw.githubusercontent.com/randomra/languages/master/all_languages). In each line a number indicates the language of the word. (`1` for English, `2` for German, `3` for Italian and `4` for Hungarian.)
* [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny/) are disallowed.
* Using word lists our similar data provided by your programming language is forbidden.
## Input
* A string containing only lowercase English letters (a-z).
* Trailing newline is optional.
## Output
* You can categorize the words by providing a distinct and consistent (always the same) output for each language. (E.g. `1` for English, `2` for German, `3` for Italian and `4` for Hungarian.)
This is code golf so the shortest program or function wins.
Related code golf question: [Is this even a word?](https://codegolf.stackexchange.com/questions/45295/is-this-even-a-word)
The word lists were taken from wiktionary.org and 101languages.net.
[Answer]
## [Retina](https://github.com/mbuettner/retina), 51 bytes
```
.*[aeio]$
1
A`en$|ch|ei|au
^$
2
A`[jkz]|gy|m$
\D+
4
```
I came up with the regexes and @MartinBüttner did the conversion to/golfing in Retina so ... hurray for team effort?
The mapping is `1 -> Italian, 2 -> German, (empty) -> Hungarian, 4 -> English`, with the amount classified in each category being `4506 + 1852 + 2092 + 3560 = 12010`.
[Try it online!](http://retina.tryitonline.net/#code=LipbYWVpb10kCjEKQWBlbiR8Y2h8ZWl8YXUKXiQKMgpBYFtqa3pdfGd5fG0kClxEKwo0&input=dGhl) | [Modified multiline version](http://retina.tryitonline.net/#code=bWAuKlthZWlvXSQKMQptYC4qKGVuJHxjaHxlaXxhdSkuKgoyCm1gLiooW2prel18Z3l8bSQpLioKClteXGRcbl0rCjQ&input=dGhlCmljaApuZW0Kbm9u)
### Explanation
First off, the equivalent Python is something like this:
```
import re
def f(s):
if re.search("[aeio]$", s):
return 1
if re.search("en$|ch|ei|au", s):
return 2
if re.search("[jkz]|gy|m$", s):
return ""
return 4
```
Let me just say that `o$` is an *excellent* indicator of Italian.
The Retina version is similar, with pairs of lines forming replacement stages. For example, the first two lines
```
.*[aeio]$
1
```
replaces matches of the first line with the contents of the second.
The next three lines do the same, but using Retina's anti-grep mode - anti-grep (specified with `A``) removes the line if it matches the given regex, and the following two lines is a replacement from an empty line to the desired output.
```
A`en$|ch|ei|au
^$
2
```
The following line uses anti-grep again, but doesn't replace the empty line, giving the fixed output for Hungarian.
```
A`[jkz]|gy|m$
```
Finally, the last two lines
```
\D+
4
```
replaces a non-empty non-digit line with `4`. All of the substitutions can only happen if no previous substitution activated, simulating an `if/else if` chain.
[Answer]
# LabVIEW, 29 [LabVIEW Primitives](http://meta.codegolf.stackexchange.com/a/7589/39490) and 148.950 Bytes
cycles through the languages and puts the iterator into an array if the word is there. This gets checked by the inner loop, picking the ith line and doing `=`. In LabVIEW it only gives a true if the Strings are exactly the same.
Now take the first element of output array so englishgoes over the rest.
The output for now is `0` for English, `1` for German, `2` for Italian and `3` for Hungarian.
[](https://i.stack.imgur.com/6x1FC.png)
[Answer]
# Java, 3416 bytes, 62%
this is my solution, i analyze list of given words and find 60 most commons bigrams and trigrams for each languages. Now i'm checking my n-grams against word, and choosing language with most n-grams in word.
```
public class Classificator {
String[][] triGr = {
{"ing","ion","ent","tio","ted","nce","ter","res","ati","con","ess","ate","pro","ain","est","ons","men","ect","red","rea","com","ere","ers","nte","ine","her","ble","ist","tin","for","per","der","ear","str","ght","pre","ver","int","nde","the","igh","ive","sta","ure","end","enc","ned","ste","dis","ous","all","and","anc","ant","oun","ten","tra","are","sed","cti"},
{"sch","che","ver","gen","ten","cht","ich","ein","ste","ter","hen","nde","nge","ach","ere","ung","den","sse","ers","and","eit","ier","ren","sen","ges","ang","ben","rei","est","nen","nte","men","aus","der","ent","hei","her","lle","ern","ert","uch","ine","ehe","auf","lie","tte","ige","ing","hte","mme","end","wei","len","hre","rau","ite","bes","ken","cha","ebe"},
{"ent","are","ato","nte","ett","ere","ion","chi","con","one","men","nti","gli","pre","ess","att","tto","par","per","sta","tra","zio","and","iam","end","ter","res","est","nto","tta","acc","sci","cia","ver","ndo","amo","ant","str","tro","ssi","pro","era","eri","nta","der","ate","ort","com","man","tor","rat","ell","ale","gio","ont","col","tti","ano","ore","ist"},
{"sze","ere","meg","ett","gye","ele","ond","egy","enn","ott","tte","ete","unk","ban","tem","agy","zer","esz","tet","ara","nek","hal","dol","mon","art","ala","ato","szt","len","men","ben","kap","ent","min","ndo","eze","sza","isz","fog","kez","ind","ten","tam","nak","fel","ene","all","asz","gon","mar","zem","szo","tek","zet","elm","het","eve","ssz","hat","ell"}
};
static String[][] biGr = {
{"in","ed","re","er","es","en","on","te","ng","st","nt","ti","ar","le","an","se","de","at","ea","co","ri","ce","or","io","al","is","it","ne","ra","ro","ou","ve","me","nd","el","li","he","ly","si","pr","ur","th","di","pe","la","ta","ss","ns","nc","ll","ec","tr","as","ai","ic","il","us","ch","un","ct"},
{"en","er","ch","te","ge","ei","st","an","re","in","he","ie","be","sc","de","es","le","au","se","ne","el","ng","nd","un","ra","ar","nt","ve","ic","et","me","ri","li","ss","it","ht","ha","la","is","al","eh","ll","we","or","ke","fe","us","rt","ig","on","ma","ti","nn","ac","rs","at","eg","ta","ck","ol"},
{"re","er","to","ar","en","te","ta","at","an","nt","ra","ri","co","on","ti","ia","or","io","in","st","tt","ca","es","ro","ci","di","li","no","ma","al","am","ne","me","le","sc","ve","sa","si","tr","nd","se","pa","ss","et","ic","na","pe","de","pr","ol","mo","do","so","it","la","ce","ie","is","mi","cc"},
{"el","en","sz","te","et","er","an","me","ta","on","al","ar","ha","le","gy","eg","re","ze","em","ol","at","ek","es","tt","ke","ni","la","ra","ne","ve","nd","ak","ka","in","am","ad","ye","is","ok","ba","na","ma","ed","to","mi","do","om","be","se","ag","as","ez","ot","ko","or","cs","he","ll","nn","ny"}
};
public int guess(String word) {
if (word.length() < 3) {
return 4; // most words below 2 characters on list are hungarians
}
int score[] = { 0, 0, 0, 0 };
for (int i = 0; i < 4; i++) {
for (String s : triGr[i]) {
if (word.contains(s)) {
score[i] = score[i] + 2;
}
}
for (String s : biGr[i]) {
if (word.contains(s)) {
score[i] = score[i] + 1;
}
}
}
int v = -1;
int max = 0;
for (int i = 0; i < 4; i++) {
if (score[i] > max) {
max = score[i];
v = i;
}
}
v++;
return v==0?Math.round(4)+1:v;
}
}
```
and this is my testcase
```
public class Test {
Map<String, List<Integer>> words = new HashMap<String, List<Integer>>();
boolean validate(String word, Integer lang) {
List<Integer> langs = words.get(word);
return langs.contains(lang);
}
public static void main(String[] args) throws FileNotFoundException {
FileReader reader = new FileReader("list.txt");
BufferedReader buf = new BufferedReader(reader);
Classificator cl = new Classificator();
Test test = new Test();
buf.lines().forEach(x -> test.process(x));
int guess = 0, words = 0;
for (String word : test.words.keySet()) {
int lang = cl.guess(word);
if (lang==0){
continue;
}
boolean result = test.validate(word, lang);
words++;
if (result) {
guess++;
}
}
System.out.println(guess+ " "+words+ " "+(guess*100f/words));
}
private void process(String x) {
String arr[] = x.split("\\s+");
String word = arr[0].trim();
List<Integer> langs = words.get(word);
if (langs == null) {
langs = new ArrayList<Integer>();
words.put(word, langs);
}
langs.add(Integer.parseInt(arr[1].trim()));
}
}
```
] |
[Question]
[
Given an input of a series of characters representing movements on a hexagonal
grid, output the final coordinates of the "pointer."
Our hexagons will be numbered like so (imagine a rectangular grid with every odd-numbered column shifted downwards slightly):
```
_____ _____ _____ _____
/ \ / \ / \ / \
/ -3,-2 \_____/ -1,-2 \_____/ 1,-2 \_____/ 3,-2 \
\ / \ / \ / \ /
\_____/ -2,-1 \_____/ 0,-1 \_____/ 2,-1 \_____/
/ \ / \ / \ / \
/ -3,-1 \_____/ -1,-1 \_____/ 1,-1 \_____/ 3,-1 \
\ / \ / \ / \ /
\_____/ -2,0 \_____/ 0,0 \_____/ 2,0 \_____/
/ \ / \ / \ / \
/ -3,0 \_____/ -1,0 \_____/ 1,0 \_____/ 3,0 \
\ / \ / \ / \ /
\_____/ -2,1 \_____/ 0,1 \_____/ 2,1 \_____/
/ \ / \ / \ / \
/ -3,1 \_____/ -1,1 \_____/ 1,1 \_____/ 3,1 \
\ / \ / \ / \ /
\_____/ \_____/ \_____/ \_____/
```
The pointer starts at (0, 0).
The instructions you must support are as follows:
* `q`: move up-left
* `w`: move up
* `e`: move up-right
* `a`: move down-left
* `s`: move down
* `d`: move down-right
* `r`: rotate grid clockwise
* `R`: rotate grid counterclockwise
The rotation commands rotate the entire grid while keeping the pointer at the same coordinates. (Why `qweasd`? They match up with the directions nicely on a QWERTY keyboard.)
To help visualize this, here's what the movement commands would do, assuming
the pointer starts in the middle:
```
_____
/ \
_____/ w \_____
/ \ / \
/ q \_____/ e \
\ / \ /
\_____/ \_____/
/ \ / \
/ a \_____/ d \
\ / \ /
\_____/ s \_____/
\ /
\_____/
```
After a clockwise rotation (`r`), the commands are remapped to (imagine it as
rotating the entire hex grid but still keeping "w" as up, etc., which is
equivalent to the following):
```
_____
/ \
_____/ e \_____
/ \ / \
/ w \_____/ d \
\ / \ /
\_____/ \_____/
/ \ / \
/ q \_____/ s \
\ / \ /
\_____/ a \_____/
\ /
\_____/
```
Similarly, rotating counterclockwise (`R`) after that would return the grid to
normal, and rotating counterclockwise again would "remap" `qwedsa` to `aqweds`.
Input must be given as a single string, and output can be either a single
string joined by any non-numerical characters (ex. `1 2` or `3,4`) or an array
of integers.
Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes will win.
Test cases:
```
In Out
---------------------------------
edeqaaaswwdqqs -2, 0
dddddddddd 10, 5
wswseaeadqdq 0, 0
<empty string> 0, 0
esaaqrweesrqrq -1, 0
wrwrwrwrw -1, 0
RRssrrrs -1, -1
aRRRRwddrqrrqqq -1, -4
rrrrrrrrrrrrRRRRRRrrrrrrq -1, -1
rrRrRrrRrrrrRRrRrRR 0, 0
```
[Answer]
## [Retina](https://github.com/mbuettner/retina/), ~~353~~ ~~339~~ ~~178~~ ~~175~~ ~~150~~ ~~130~~ ~~129~~ 117 bytes
```
R
5$*r
T`aq\we\ds`so`r.+
)`r(.*)
$1
^
:
a
sq
e
wd
+`(.+)q
w$1
+`(.+)d
s$1
+`sw
(.*)(\1w?):
$0$2
+`sw|ws
w+
-$0
\w
1
```
Output is in unary, separated by a colon. That means you won't really see zeroes in the output (although the presence of a colon will tell you which of the two coordinates is zero, if there is only one).
[Try it online!](http://retina.tryitonline.net/#code=Ugo1JCpyClRgYXFcd2VcZHNgc29gci4rCilgciguKikKJDEKXgo6CmEKc3EKZQp3ZAorYCguKylxCnckMQorYCguKylkCnMkMQorYHN3CgooLiopKFwxdz8pOgokMCQyCitgc3d8d3MKCncrCi0kMApcdwox&input=YVJSUlJ3ZGRycXJycXFx&debug=on)
This was really fun and ended up being surprisingly short. :)
### Explanation
Some background first. [There are several coordinate systems to describe hexagonal grids.](http://www.redblobgames.com/grids/hexagons/#coordinates) The one asked for uses offset coordinates. That's essentially like rectangular grid coordinates, except that one axis "wobbles" a bit. In particular, the question asks for the "odd-q" layout shown on the linked page. This coordinate system is a bit annoying to work with, because how the coordinates change during a move depends not only on the direction of the move but also on the current position.
Another coordinate system uses axial coordinates. That's essentially imagining the hexgrid as a diagonal slice through a volume of cubes, and using two of the axes (e.g. x and z) to find a position on the 2D plane. On the hex grid, that means that the two axes form an angle of 60 (or 120) degrees. This system is a bit less intuitive but much easier to work with, since every direction corresponds to a fixed "delta" vector. (For a better explanation of how to arrive at this coordinate system, check out the link and the lovely diagrams and animations there.)
So here's what we'll do: we compute the movement in axial coordinates (taking care of rotation as suggested in the challenge, by remapping the meaning of the commands), and when we're done we convert axial to to odd-q offset coordinates.
The six moves map to the following delta vectors in (x-z) axial coordinates:
```
q => (-1, 0)
w => ( 0, -1)
e => ( 1, -1)
d => ( 1, 0)
s => ( 0, 1)
a => (-1, 1)
```
Wait, this is Retina, we'll have to work with unary numbers. How do we work with negative unary numbers? The idea is to use two different digits. One represents `+1` and the other represents `-1`. That means regardless of whether we want add or subtract `1` from the current position, we can always do so by adding a digit. When we're done we collapse the result into its magnitude (of the corresponding digit) by cancelling balanced digits. Then we figure out the sign based on the remaining digit, and replace all digits with `1`.
The plan is to build up the axial x and z components to the left and right of a `:` (as a separator), in front of the input. `w` and `s` will add to the right-hand side. `q` and `d` will add to the left-hand side, and `e` and `a` will add to both sides. Since `w` and `s` are already on the correct side of the `:` (which will go in front), we will use those as the `-1` and `+1` digits, respectively.
Let's go through the code.
```
R
5$*r
```
We start by turning each `R` into five `r`s. Of course, one left turn is the same as five right turns on a hex grid, and by doing so we can a lot of duplication on the remapping step.
```
T`aq\we\ds`so`r.+
```
This is a transliteration stage which rotates the six commands, if they are found after the first `r` (thereby processing the first `r`). `w` and `d` need to be escaped to prevent them from expanding into character classes. The `o` inserts the source set into the target set which saves a bunch of bytes for these rotation tasks. The character mapping is therefore:
```
aqweds
saqweds
```
where the last `s` in the second row can simply be ignored.
```
)`r(.*)
$1
```
This removes the first `r` from the string, because it's been processed (I wish I had already implemented substitution limits...). The `)` also tells Retina to run all stages up to this one in a loop until the string stops changing. On subsequent iterations, the first stage is a no-op because there are no more `R`s and the second stage will apply another rotation as long as there are `r`s left in the string.
When we're done, we've mapped all commands to the direction they correspond to on the unrotated grid and can start processing those. Of course this movement is just a sum of those delta vectors, and sums are commutative, so it doesn't really matter in which order we process them now that rotations have been eliminated.
```
^
:
```
Insert the coordinate delimiter at the front.
Now we don't really need to process `s` and `w`. They are our `+1` and `-1` digits and they're already on the correct side of the `:` so they'll just drop out as required in the end. We can make another simplification: `a` is simply `s + q` and `e` is `w + d`. Let's do that:
```
a
sq
e
wd
```
Again, those `s` and `w` will just drop out. All we need to do is move those `q`s and `d`s to the front and turn them into `w`s and `s`s themselves. We do that with two separate loops:
```
+`(.+)q
w$1
+`(.+)d
s$1
```
So that's done. Time for the conversion from axial to offset coordinates. For that we need to collapse the digits. However, for now we only care about the left-hand side. Due to the way we've processed the `q`s and `d`s, we know that all the `s`s in the left-hand side will appear in front of any `w`s, so we only need to check one pair for collapsing the them:
```
+`sw
```
Now the actual conversion. Here is the pseudocode, taken from link above:
```
# convert cube to odd-q offset
col = x
row = z + (x - (x&1)) / 2
```
Right, so the left-hand side is already correct. The right-hand side needs the correction term `(x - (x&1)) / 2` though. Taking `&1` is the same as modulo 2. This basically parses as `x/2`, integer division, rounded towards minus infinity. So for positive `x`, we add half the number of digits (rounded down), and for negative `x`, we subtract half the number of digits (rounded up). This can be expressed surprisingly concisely in regex:
```
(.*)(\1w?):
$0$2
```
Due to the greediness, for even `x`, group 1 will match exactly half the digits, `\1` the other half and we can ignore the `w?`. We insert that half after the `:` (which is `x/2`). If `x` is even, then we need to distinguish positive and negative. If `x` is positive, then `w?` will never match, so the two groups will still have to match the same number of digits. That's no problem if the first `s` is simply skipped, so we round down. If `x` is negative and odd, then the possible match is with `\1` (half of `x` rounded down) and that optional `w`. Since both of those go into group `2`, we will write `x/2` with the magnitude rounded up (as required).
```
+`sw|ws
```
Now we collapse the digits on the right-hand side. This time, we don't know the order of the `s` and `w`, so we need to account for both pairs.
```
w+
-$0
```
Both parts are now reduced to a single repeated digit (or nothing). If that digit is `w`, we insert a minus sign in front.
```
\w
1
```
And finally we turn both into `w` and `s` into a single reasonable unary digit. (I suppose I could save a byte by using `w` or `s` as the unary digit, but that seems like a bit of a stretch.)
[Answer]
# Pyth, 81 bytes
```
J_K1=Y"qwedsa"A,ZZFNz=kxYN ?<kZ=Y?<x\rNZ.>Y1.<Y1A,+G@[JZ1KZJ)k+H@[J_2JK2K)k;,G/H2
```
Output is a list of integers representing the coordinates.
My solution is actually really boring; it just looks up the inputted character in an array (the `qwedsa`), and then accesses two arrays that represent the respective changes in the coordinates. For example, if the input is `w`, then we get 1 (as it is the second character in the array). Then we add `A[1]` to `x` (where `A` is the array for the changes in `x` in respect to the different inputs) and `B[1]` to `y` (where `B` is the changes for `y`). `r` and `R` are achieved by just rotating the `qwedsa` array.
I'm sure someone can do much better using Pyth. I'll continue to try to golf my answer though!
You can try it out [here](https://pyth.herokuapp.com/?code=J_K1%3DY%22qwedsa%22A%2CZZFNz%3DkxYN%20%3F%3CkZ%3DY%3F%3Cx%5CrNZ.%3EY1.%3CY1A%2C%2BG%40%5BJZ1KZJ%29k%2BH%40%5BJ_2JK2K%29k%3B%2CG%2FH2&input=rrrrrrrrrrrrRRRRRRrrrrrrq&test_suite=1&test_suite_input=edeqaaaswwdqqs%0Adddddddddd%0Awswseaeadqdq%0A%0Aesaaqrweesrqrq%0Awrwrwrwrw%0ARRssrrrs%0AaRRRRwddrqrrqqq%0ArrrrrrrrrrrrRRRRRRrrrrrrq%0ArrRrRrrRrrrrRRrRrRR&debug=0).
[Answer]
## Python (3.5) ~~193~~ ~~185~~ 182 bytes
I also calcul in [axial coordinates](http://www.redblobgames.com/grids/hexagons/#coordinates) and convert at the end.
I add some optimisation according to @Martin Büttner solution :
I replace R by r\*5, it doesn't change the bytes count. But with this change we can replace the second test `elif j=='r'` by just `else`
The solution assume we can't have invalid characters in the input.
```
def f(i):
x=y=0;u=-1,0,-1,1,0,1,1,0,1,-1,0,-1;v='dewqas'
for j in i.replace('R','r'*5):
w=v.find(j)*2
if-1<w:x+=u[w];y+=u[w+1]
else:u=u[2:]+u[:2]
print(-x,-x-y+(x-(x%2))/2)
```
## Ungolfed
```
def f(i):
x=y=0
u=-1,0,-1,1,0,1,1,0,1,-1,0,-1 # operations list xd,yd,xe,ye...
v='dewqas' # letters list in clockwise order
i.replace('R','r'*5) # replace 'R' by 5*'r'
for j in i:
w=v.find(j)*2 # extract letter index
if-1<w:
x+=u[w] # apply operations
y+=u[w+1]
else:
u=u[2:]+u[:2] # rotate clockwise the operation string
print(-x,-x-y+(x-(x%2))/2) # convert coordinates axial to "odd-q"
```
## Usage
```
>>> f('wrwrwrwrw')
-1 0.0
>>> f('dddddddddd')
10 5.0
>>> f('edeqaaaswwdqqs')
-2 0.0
```
[Answer]
## Batch, ~~708~~ ~~636~~ ~~586~~ 569 bytes
I used doubled y-coordinates because it made the maths simpler. I'm not sure I took the rotation into account in the most ideal way, but it beats counting the number of `r`s.
Edit: Saved 72 bytes by improving on the handling of `R`s. Saved 60 bytes by optimising my `set/a` statements. Saved 17 bytes with some minor optimisations.
```
@echo off
set m=%1
set/ay=x=0
set r=r
set g=goto l
:l
set/a"z=y>>1
if "%m%"=="" echo %x% %z%&exit/b
set c=%m:~0,1%
set m=%m:~1%
goto %r:rrrrrr=%%c%
:a
:rq
:rrw
:rrre
:rrrrd
:rrrrrs
set/ax-=2
:w
:re
:rrd
:rrrs
:rrrra
:rrrrrq
set/ax+=1,y-=1
%g%
:q
:rw
:rre
:rrrd
:rrrrs
:rrrrra
set/ay-=2
%g%
:s
:ra
:rrq
:rrrw
:rrrre
:rrrrrd
set/ax-=2
:e
:rd
:rrs
:rrra
:rrrrq
:rrrrrw
set/ax+=+1,y+=1
%g%
:d
:rs
:rra
:rrrq
:rrrrw
:rrrrre
set/ay+=2
%g%
:r
:rr
:rrr
:rrrr
:rrrrr
:rrrrrr
if %c%==R set c=rrrrr
set r=%c%%r%
%g%
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 60 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
.•F?äM•U2Å0IvXy'rQiÀUëy'RQiÁUëykÐ5α‚ßsD3%_s3›·+‚<+]Ć`DÉ-2÷+‚
```
[Try it online](https://tio.run/##yy9OTMpM/f9f71HDIjf7w0t8gXSo0eFWA8@yiEr1osDMww2hh1dXqgcBWY0gVvbhCabnNj5qmHV4frGLsWp8sfGjhl2HtmsDRWy0Y4@0Jbgc7tQ1OgwW@P8/tTgxsbCoPDW1uKiwqBAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/vUcNi9zsDy/xBdKhRodbDSrLIirViwIzDzeEHl5dqR4EZDWCWNmHJ5ie2/ioYdbh@cUuxqrxxcaPGnYd2q4NFLHRrq2tPdKW4HK4U9foMFjov87/aKXUlNTCxMTE4vLylMLCYiUdpRQ4AHLKi8uLUxNTE1MKUwqBXCBKLU5MLCwqT00tLiosAomVF0EhkB0UVFxcVFQEMiYxCAjKU1KAqooKC0EKi5BAEBhA2BC5ICAsCoLIgThBSrEA).
### Explanation:
***General explanation:***
We start with a string `"qwedsa"` and a coordinate `[0,0]`, and loop over the characters of the input.
If it's an "r" or "R" we rotate this string towards the left or right respectively.
If not, we get the 0-based index in this string, and map it as follows:
```
q → 0 → [-1, 0]
w → 1 → [ 0, -1]
e → 2 → [ 1, -1]
d → 3 → [ 1, 0]
s → 4 → [ 0, 1]
a → 5 → [-1, 1]
```
We'll need to convert the index-digits to the following \$x\$ and \$y\$ coordinates:
```
x indices y indices
-1 ← 0;5 -1 ← 1;2
0 ← 1;4 0 ← 0;3
1 ← 2;3 1 ← 4;5
```
We do this, by converting the index \$k\$ as follows:
\$x = min(k, abs(k-5))-1\$
\$y = (0\equiv k\pmod3) + 2(k\gt3) - 1\$
And after the entire loop, we have to fix the off-set of the \$y\$-coordinate based on the \$x\$-coordinate, which we do like this (\$x\$ remains the same):
\$y=y+\lfloor\frac{x-x\pmod2}{2}\rfloor\$
***Code explanation:***
```
.•F?äM• # Push compressed string "qwedsa"
U # Pop and store it in variable `X`
2Å0 # Push list [0,0]
# (many 3-byte alternatives for this: `00S`; `т¦S`; `0D‚`; `1¾‰`; etc.)
Iv # Loop over each character `y` of the input:
X # Push string `X`
y'rQi '# If `y` equals "r":
À # Rotate string `X` once towards the left
U # And pop and store it as new value for `X`
ëy'RQi '# Else-if `y` equals "R":
ÁU # Do the same, but rotate right instead
ë # Else:
yk # Get the 0-based index of `y` in the string `X`
Ð # Triplicate this index
5α # Take the absolute difference with 5
‚ß # Pair it with the original index, and pop and push the minimum
# (maps 0→[0,5]→0; 1→[1,4]→1; 2→[2,3]→2;
# 3→[3,2]→2; 4→[4,1]→1; 5→[5,0]→0)
sD # Swap to get the original index again, and duplicate it
3% # Take modulo 3
_ # And check if it's equals to 0 (1 if truthy; 0 if falsey)
s3› # Swap to take the index again, and check if it's larger than
# (again, 1 if truthy; 0 if falsey)
· # Double this
+ # And add both checks together
# (maps 0→1+0→1; 1→0+0→0; 2→0+0→0;
# 3→1+0→1; 4→0+2→2; 5→0+2→2)
‚ # Pair both mapped values together
< # Decrease both by 1, so it becomes: 0→-1; 1→0; 2→1
+ # And add it to the current coordinates
] # After the loop with inner if-else statements:
Ć # Enclose the coordinate, appending its own head: [x,y] becomes [x,y,x]
` # Push all three values separated to the stack
D # Duplicate this x
É # Check if its odd (1 if truthy; 0 if falsey)
- # Subtract it from the duplicated x
2÷ # Integer-divide it by 2
+ # Add it to y
‚ # And pair it with the original x again
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `.•F?äM•` is `"qwedsa"`.
[Answer]
## Python 3, 227 bytes
```
def G(s):
q='qwedsa'
d=[-1,0,1,1,0,-1,-1,-2,-1,1,2,1]
X=Y=0
for c in s:
if c in q:
n = q.find(c)
X += d[n]
Y += d[n+6]
if c == 'r':
q = q[1:]+q[0]
if c == 'R':
q = q[5]+q[0:5]
print(X, int((Y-X%2)/2))
```
] |
[Question]
[
One of the reasons I've always loved Pokemon is because for such a simple-seeming game, it has so many layers of complexity. Let's consider the move Hidden Power. In game, the type and power (at least before Generation VI) of Hidden Power is different for every Pokemon that uses it! That's pretty cool, right? Now, would you be surprised if I told you that the type and power of Hidden Power isn't generated randomly?
In all Pokemon games, all Pokemon (not just ones in your party, ALL POKEMON) have six internally-stored integers (one for the HP stat, one for the attack stat, one for the defense stat, one for the special attack stat, one for the special defense stat and one for the speed stat) called their ***individual values,*** or IVs. These values range between 0 and 31, and they essentially are one of a few factors that influence a Pokemon's overall stats. HOWEVER, they also determine the type and power of Hidden Power!
In Generation III to V (the generations whose algorithm we'll be implementing), the type of Hidden Power is determined by the following formula (note the floor brackets, that means you need to round down the result):
[](https://i.stack.imgur.com/tdamK.png)
where a, b, c, d, e and f are the least significant bits of the HP, Attack, Defense, Speed, Sp. Attack, and Sp. Defense IVs respectively. (Least significant bit is IV mod 2.) The number produced here then can be converted to the actual type using this chart:
```
0 Fighting
1 Flying
2 Poison
3 Ground
4 Rock
5 Bug
6 Ghost
7 Steel
8 Fire
9 Water
10 Grass
11 Electric
12 Psychic
13 Ice
14 Dragon
15 Dark
```
For power, a similar formula is used:
[](https://i.stack.imgur.com/eAK6d.png)
Here, however, u, v, w, x, y and z represent the second least significant bit of the HP, Attack, Defense, Speed, Sp. Attack and Sp. Defense IVs (in that order again). (Second least significant bit is more complicated then least significant bit. If IV mod 4 is 2 or 3, then the bit is 1, otherwise it is 0. If your language has some sort of built-in or at least a more clever way to do this, you should probably use it.)
---
So, as you probably figured out already, the challenge here is to write a program that takes in six integers separated by spaces via STDIN that represent the HP, Attack, Defense, Speed, Sp. Attack and Sp. Defense IVs of a Pokemon (in that order) and output the type and power of that Pokemon's Hidden Power.
Sample input:
```
30 31 31 31 30 31
```
Sample output:
```
Grass 70
```
Sample input:
```
16 18 25 13 30 22
```
Sample output:
```
Poison 61
```
This is code-golf, so shortest code wins. Good luck!
(And before people ask, I used the Generation V algorithm here because Generation VI gets rid of the power randomization and makes it always 60. Not only do I think this is incredibly lame, I think it makes the challenge a LOT LESS INTERESTING. So for the purposes of the challenge, we're running a Gen V game.)
[Answer]
# Ruby, 210
```
a=$*.map.with_index{|a,i|[a.to_i%2<<i,a.to_i[1]<<i]}.transpose.map{|a|a.inject &:+}
$><<"#{%w(Fighting
Flying
Poison
Ground
Rock
Bug
Ghost
Steel
Fire
Water
Grass
Electric
Psychic
Ice
Dragon
Dark)[a[0]*15/63]} #{a[1]*40/63+30}"
```
First time golfing, so I guess this is pretty obvious solution.
[Answer]
# Pyth, 110 bytes
```
J+dGA.b/*iN2CY63Cm_+0jd2_Q"("r@cs@LJjC"!�W��Zm�����A�zB0i��ȏ\"���?wC�ǀ�-#ך
?ЫܦO@�J/m���#"26)G3+30H
```
This contains unprintable chars. So here's a hexdump:
```
00000000: 4a 2b 64 47 41 2e 62 2f 2a 69 4e 32 43 59 36 33 J+dGA.b/*iN2CY63
00000010: 43 6d 5f 2b 30 6a 64 32 5f 51 22 0f 28 22 72 40 Cm_+0jd2_Q".("r@
00000020: 63 73 40 4c 4a 6a 43 22 10 21 de 57 ad c8 5a 1c cs@LJjC".!.W..Z.
00000030: 10 6d e0 d6 12 f6 80 bc 41 85 7a 42 30 69 ae 80 .m......A.zB0i..
00000040: c8 8f 5c 22 a0 84 ab 3f 77 43 01 ca c7 80 d0 1d ..\"...?wC......
00000050: 2d 23 d7 9a 0a 3f d0 ab dc a6 4f 40 b9 4a 2f 6d -#[[email protected]](/cdn-cgi/l/email-protection)/m
00000060: d2 ca c6 23 22 32 36 29 47 33 2b 33 30 48 ...#"26)G3+30H
```
You can also download the file [pokemon.pyth](https://www.dropbox.com/s/fdquivlvi9gzktp/pokemon.pyth?dl=0) and run it with `python3 pyth.py pokemon.pyth`
The input `30, 31, 31, 31, 30, 31` prints
```
Grass
70
```
### Explanation:
```
J+dGA.b/*iN2CY63Cm_+0jd2_Q".("
J+dG store the string " abc...xyz" in J
m _Q map each number d in reverse(input list) to:
jd2 convert d to base 2
+0 add a zero (list must have >= 2 items)
_ reverse the list
C zip
".(" string with the ascii values 15 and 40
.b map each N of ^^ and Y of ^ to:
iN2 convert N from base 2 to base 10
* CY multiply with the ascii value of Y
/ 63 and divide by 63
A G, H = ^
r@cs@LJjC"longstring"26)G3+30H
C"longstring" interpret the string as bytes and convert
from base 256 to base 10
j 26 convert to base 26
s@LJ lookup their value in J and create a string
this gives "fighting flying ... dark"
c ) split by spaces
@ G take the Gth element
r 3 make the first letter upper-case and print
+30H print 30 + H
```
[Answer]
# CJam, ~~140~~ 115 bytes
```
q~]W%_1f&2bF*63/"GMÿD>BÙl½}YÛöí6P¶;óKs¯¿/·dǯã®Å[YÑÌÞ%HJ9¹G4Àv"256b25b'af+'j/=(euooSo2f/1f&2b40*63/30+
```
Note that the code contains unprintable characters.
Try it online in the CJam interpreter: [Chrome](http://cjam.aditsu.net/#code=q~%5DW%25_1f%262bF*63%2F%22GM%C3%BF%06D%3EB%C3%99l%C2%BD%7D%15Y%C3%9B%C3%B6%C3%AD6%05P%C2%B6%3B%C3%B3K%C2%84s%C2%AF%C2%BF%06%12%2F%C2%B7d%C3%87%0B%C2%AF%18%C3%A3%C2%AE%07%C2%92%1E%C3%85%5BY%C3%91%C3%8C%C3%9E%0B%25%14HJ9%C2%B9G4%C3%80v%22256b25b'af%2B'j%2F%3D(euooSo2f%2F1f%262b40*63%2F30%2B&input=30%2031%2031%2031%2030%2031) | [Firefox](http://cjam.aditsu.net/#code=q~%5DW%2525_1f%262bF*63%2F%22GM%C3%BF%06D%3EB%C3%99l%C2%BD%7D%15Y%C3%9B%C3%B6%C3%AD6%05P%C2%B6%3B%C3%B3K%C2%84s%C2%AF%C2%BF%06%12%2F%C2%B7d%C3%87%0B%C2%AF%18%C3%A3%C2%AE%07%C2%92%1E%C3%85%5BY%C3%91%C3%8C%C3%9E%0B%2525%14HJ9%C2%B9G4%C3%80v%22256b25b'af%2B'j%2F%3D(euooSo2f%2F1f%262b40*63%2F30%2B&input=30%2031%2031%2031%2030%2031)
[Answer]
# Javascript (ES6), 251 bytes
Kinda long, at least for now. The list of types and the complex maths take up about the same amount of space. I'm looking for ways to shorten either/both of them.
```
x=>([a,b,c,d,e,f]=x.split` `,`Fighting
Flying
Poison
Ground
Rock
Bug
Ghost
Steel
Fire
Water
Grass
Electric
Psychic
Ice
Dragon
Dark`.split`
`[(a%2+b%2*2+c%2*4+d%2*8+e%2*16+f%2*32)*5/21|0]+' '+((a/2%2+(b&2)+(c&2)*2+(d&2)*4+(e&2)*8+(f&2)*16)*40/63+30|0))
```
As usual, suggestions welcome!
[Answer]
# Javascript (ES6), 203 bytes
```
f=(...l)=>(q=(b,m)=>~~(l.reduce((p,c,x)=>p+(!!(c&b)<<x),0)*m/63),'Fighting0Flying0Poison0Ground0Rock0Bug0Ghost0Steel0Fire0Water0Grass0Electric0Psychic0Ice0Dragon0Dark'.split(0)[q(1,15)]+' '+(q(2,40)+30))
```
Example runs:
```
f(30,31,31,31,30,31)
> "Grass 70"
f(16,18,25,13,30,22)
> "Poison 61"
```
] |
[Question]
[
# Untouchable Numbersα
An untouchable number is a positive integer that cannot be expressed as the sum of all the proper divisors of any positive integer (including the untouchable number itself).
For example, the number 4 is not untouchable as it is equal to the sum of the proper divisors of 9: 1 + 3 = 4. The number 5 is untouchable as it is not the sum of the proper divisors of any positive integer. 5 = 1 + 4 is the only way to write 5 as the sum of distinct positive integers including 1, but if 4 divides a number, 2 does also, so 1 + 4 cannot be the sum of all of any number's proper divisors (since the list of factors would have to contain both 4 and 2).
The number 5 is believed to be the only odd untouchable number, but this has not been proven: it would follow from a slightly stronger version of the Goldbach conjecture. β
There are infinitely many untouchable numbers, a fact that was proven by Paul Erdős.
A few properties of untouchables:
* No untouchable is 1 greater than a prime
* No untouchable is 3 greater than a prime, except 5
* No untouchable is a perfect number
* Up to now, all untouchables aside from 2 and 5 are composite.
# Objective
Create a *program or function* that takes a natural number `n` via **standard input or function parameters** and prints the first `n` untouchable numbers.
The output must have separation between the numbers, but this can be anything (i.e. newlines, commas, spaces, etc).
This should be able to work at least `1 <= n <= 8153`. This is based on the fact that the b-file provided for the OEIS entryγ goes up to `n = 8153`.
Standard loopholes are disallowed, as per usual.
# Example I/O
```
1 -> 2
2 -> 2, 5
4 -> 2, 5, 52, 88
10 -> 2, 5, 52, 88, 96, 120, 124, 146, 162, 188
8153 -> 2, 5, 52, 88, 96, 120, ..., ..., ..., 59996
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so least number of bytes wins.
---
α - [Wikipedia](https://en.wikipedia.org/wiki/Untouchable_number),
β - [MathWorld](http://mathworld.wolfram.com/UntouchableNumber.html),
γ - [OEIS](https://oeis.org/A005114)
---
For some reason this was marked as a duplicate to the 'finding semiperfect numbers' question, however the tasks are completely different. In this case, you must check to make sure that no sum of perfect divisors of any natural number can equal a certain number.
[Answer]
# Pyth, 21 bytes
```
.f!fqZsf!%TYStTSh^Z2Q
```
Warning: Incredibly slow. Test run and timing below.
```
$ time pyth -c '.f!fqZsf!%TYStTSh^Z2Q' <<< 3
[2, 5, 52]
real 2m46.463s
user 2m46.579s
sys 0m0.004s
```
It's basically as brute force as possible, tests factorizations up to the potential lonely number squared plus one.
[Answer]
# C, 104 bytes
```
j,i,z,w;u(y){for(z=2;y;z++)for(w=0;(++w<z*z||0&printf("%i ",z)+y--)&&j^z;)for(i=j=0;++i<w;j+=i*!(w%i));}
```
It will take a few minutes for *y* > 20, but whatever.
[Answer]
# Java, 310 Bytes
```
class U{int[] p;U(int e){p=new int[(int)4e9];for(int i=1,c=0;c<e;i++)if(u(i)>0){System.out.println(i);c++;}}int p(int n){if(p[n]!=0)return p[n];int i,s=1;for(i=2;i<=n-1;i++)s+=n%i==0?i+(n/i!=i?n/i:0):0;return(p[n]=s);}int u(int n){if(n==1)return 0;for(int i=2;i<=(n-1)*(n-1);i++)if(p(i)==n)return 0;return 1;}}
```
Golfed as well as I could but, I was more interested in making sure it ran in reasonable time. The unglofed version is probably more interesting
```
public class Untouchable {
int[] properDivisorSumMap;
public Untouchable(int estimatedMaxium){
properDivisorSumMap = new int[(estimatedMaxium-1)*(estimatedMaxium-1)];
}
public int properDivisorSum(int n){
if(properDivisorSumMap[n] != 0){
return properDivisorSumMap[n];
}
int sum = 1;
for(int i=2;i<=(int)Math.sqrt(n);i++){
if(n%i==0){
sum+=i;
if(n/i != i){
sum+=n/i;
}
}
}
properDivisorSumMap[n] = sum;
return sum;
}
public boolean untouchable(int n){
if(n==1){
return false;
}
for(int i=2;i<=(n-1)*(n-1);i++){
if(properDivisorSum(i) == n){
return false;
}
}
return true;
}
public static void main(String[] args){
Untouchable test = new Untouchable(8480);
int elements = Integer.parseInt(args[0]);
for(int i=1,count=0;count < elements;i++){
if(test.untouchable(i)){
System.out.printf("%4d: %4d%n",count,i);
count++;
}
}
}
}
```
[Answer]
## Go, 396 bytes
Not really golfed, but it can do all of the required range. Runs in about ~20min and needs ~7GB (independent of n). Makes a giant array to compute the sum of divisors for all numbers up to 59997 squared.
```
func untouchable(n int) {
const C = 59997
const N = C * C
s := make([]uint16, N)
for d := 1; d < N; d++ {
for i := 2 * d; i < N; i += d {
v := int(s[i]) + d
if v > C {
v = C + 1 // saturate at C+1
}
s[i] = uint16(v)
}
}
var m [C]bool
for i := 2; i < N; i++ {
if s[i] < C {
m[s[i]] = true
}
}
for i := 2; n > 0; i++ {
if !m[i] {
println(i)
n--
}
}
}
```
[Answer]
# [R](https://www.r-project.org/), 122 bytes
```
function(n)while(n){T=T+1
m=T^2
t=0
while(m<-m-1){i=s=0;while((i=i+1)<m)if(!m%%i)s=s+i;t=t+(T==s)}
if(!t){print(T);n=n-1}}
```
[Try it online!](https://tio.run/##VY4xCsMwDAB3/6JDQMIE4nZ09AvPhTYkRBArJZbpYPx2tyVTp4O75Y6WRfc8rY/nNidqS5ZJeRcQfK@8zV@WQME6Eyncr0ZpMGeIYx97h4Up0eBPB0xsHY4ReYFL7DrGRMmyV1ILgShhNb@kWF4Hi0JALyS9q/VvBG7YPg "R – Try It Online")
Anyone familiar with [R](https://www.r-project.org/) programming will certainly wince when they look at this. Loops in general are horribly inefficient in [R](https://www.r-project.org/), and the fast and idiomatic way to tackle this kind of question would normally be to use vectorized functions.
Unfortunately, the maximum size of a vector in [R](https://www.r-project.org/) is 2^31-1 elements, which is smaller than the square of 59996, the highest number that we need to test for untouchability, so we can't easily find divisors by checking a large vector.
So here we use a set of nested `while` loops to avoid making the big vectors that we really want. If you aren't used to [R](https://www.r-project.org/), this will probably seem quite unremarkable, and you'll probably also be surprised at just how slowly it runs (n=4 times-out on TIO!).
If only [R](https://www.r-project.org/) used *un*-signed integers to index vectors, and so could manage vectors with 2^32 elements, the code would be only 80 bytes:
**Imaginary [R](https://www.r-project.org/) with 2^32-sized vectors, 80 bytes**
```
function(n,m=1:4e9,a=!m){for(y in m)a[sum(which(!y%%(2:y-1)))]=T
which(!a)[1:n]}
```
[Try it online!](https://tio.run/##TZDNasMwEITveYoJJVQCF6I0gdbFb9FbyEG21pGKtSr6qTGlz@46poXcltll55uJc@EcSmd1O1Bq5r5wl11gwZVvVH2kY6WbrZfffYhigmN4qc@peDFa11mxnXY7cainJyWlvDTvmz9Zy7Oq@fIzP4BDphpdMITRDQMCDxNiYZRP5ABu1P4N2nyUlOFvDv8MMNQ7duu4HF4DrLtaihXakqF5GvVClDEGfsy3tW7DF@FArxVWDLiEJVVCtprBRIbM@onyIhFe1Ok5Gtw1AC6@pbi5L0WovZx/AQ "R – Try It Online") (but it won't work for large n)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 9 bytes
```
2²Æṣ€ḟƑƊ#
```
[Try it online!](https://tio.run/##AR0A4v9qZWxsef//MsKyw4bhuaPigqzhuJ/GkcaKI///Mw "Jelly – Try It Online")
Times out on TIO for \$n > 3\$, but works in theory for all \$n\$. Relies on the assumption that for a given \$x \ge 2\$, \$x\$ is untouchable if none of the proper divisor sums between \$1\$ and \$x^2\$ equals \$x\$. Takes \$n\$ on STDIN.
## How it works
```
2²Æṣ€ḟƑƊ# - Main link. Takes no arguments
Ɗ - Group the previous 3 links together into a monad f(k):
² - k²
€ - Over each 1, 2, ..., k²:
Æṣ - Proper divisor sum
Ƒ - Is the list of proper divisor sums unchanged after:
ḟ - removing k from it?
2 # - Count up k = 2, 3, ... until n such k's return true under f(k)
```
] |
[Question]
[
My attempt at stating [this question](https://codegolf.stackexchange.com/questions/5693/minimal-sudoku-generator), but with a more objective solving criterion.
Your task is to build a program or function that takes a solved Sudoku grid `S` in the format of your choice and attempts to generate a problem grid with as few clues as possible that has `S` as its unique solution. (It doesn't matter what method `S` is the unique solution by, including brute force, as long as the solution is provably unique.)
---
Your program will be scored by running it through a set of 100,000 solution grids found in [this file](https://github.com/joezeng/pcg-se-files/raw/master/ppcg_sudoku_testing.txt) (7.82 MB download), and adding up the number of clues in all 100,000 problem grids that your solution produces.
The Sudoku solutions in the above test file are expressed as an 81-character string, from left-to-right, then top-to-bottom. The code required to turn the input in the test file into a usable solution will not count towards your solution's byte count.
As in my [Flood Paint](https://codegolf.stackexchange.com/questions/26232/create-a-flood-paint-ai) challenge, your program must actually produce a valid output for all 100,000 puzzles to be considered a valid solution. The program that outputs the fewest total clues for all 100,000 test cases is the winner, with shorter code breaking a tie.
---
Current scoreboard:
1. [2,361,024](https://codegolf.stackexchange.com/a/48536/7110) - nutki, C
2. [2,580,210](https://codegolf.stackexchange.com/a/48526/7110) - es1024, PHP
3. [6,000,000](https://codegolf.stackexchange.com/a/48517/7110) - CarpetPython, Python 2
4. [7,200,000](https://codegolf.stackexchange.com/a/48510/7110) - Joe Z., Python
[Answer]
# C - 2,361,024 ~~2,509,949~~ clues
Remove clues starting from the last cell if a brute force solver finds only one unique solution.
Second try: use heuristic to decide in which order to remove clues instead of starting from the last. This makes the code run much slower (20 minutes instead of 2 to calculate the result). I could make the solver faster, to experiment with different heuristics, but for now it will do.
```
#include <stdio.h>
#include <string.h>
char ll[100];
short b[81];
char m[81];
char idx[81][24];
int s;
char lg[513];
void pri2() {
int i;
for(i=0;i<81;i++) putchar(lg[b[i]]);
putchar('\n');
}
void solve(pos){
int i,p;
if (s > 1) return;
if (pos == 81) { s++; return; }
if (b[pos]) return solve(pos+1);
for (p=i=0;i<24;i++) p |= b[idx[pos][i]];
for (i = 0; i < 9; i++) if (!(p&(1<<i))) {
b[pos] = 1 << i;
solve(pos + 1);
}
b[pos] = 0;
}
int main() {
int i,j,t;
for(i=0;i<9;i++) lg[1<<i]='1'+i;
lg[0] = '.';
for(i=0;i<81;i++) {
t = 0;
for(j=0;j<9;j++) if(i/9*9 + j != i) idx[i][t++] = i/9*9 + j;
for(j=0;j<9;j++) if(i%9 + j*9 != i) idx[i][t++] = i%9 + j*9;
for(j=0;j<81;j++) if(j/27 == i/27 && i%9/3 == j%9/3 && i!=j) idx[i][t++] = j;
}
while(scanf("%s ",ll)>0) {
memset(m, 0, sizeof(m));
for(i=0;i<81;i++) b[i] = 1 << (ll[i]-'1');
for(i=0;i<81;i++) {
int j,k,l = 99;
for(k=0;k<81;k++) if (m[k] <= l) l = m[k], j = k;
m[j] = 24;
t = b[j]; b[j] = 0;
s = 0; solve(0);
if (s > 1) b[j] = t;
else for(k=0;k<24;k++) m[idx[j][k]]++;
}
pri2();
}
return 0;
}
```
[Answer]
# C++ / Tdoku - 2,081,604 clues
Below are results from running random minimization using [tdoku](https://github.com/t-dillon/tdoku) on each puzzle N times and taking the result with the least clues. Results are shown for various N as powers of 2. No heuristics are involved at all. Each minimization just takes a random permutation of range(81) and then tries to remove clues in that order, putting a clue back whenever its removal results in multiple solutions.
Of note is the fact that the curve isn't flattening quickly and lower numbers can clearly be achieved without being any smarter just by running for larger N.
```
# (1) fetch tdoku
git clone https://github.com/t-dillon/tdoku.git
cd tdoku
# (2) pick your compiler (recent clang is best for tdoku):
export CC=clang-8
export CXX=clang++-8
# (3) place ppcg_sudoku_testing.txt, minimize.cc (below),
# and run.sh (below) in the current directory
# (4) build the tdoku solver library
./BUILD.sh
# (5) build minimize.cc
$CXX -std=c++11 -O3 -march=native -o minimize minimize.cc build/libtdoku.a
# (6) run with concurrency appropriate for your system.
# results below were run on a 32core/64thread TR-2990WX
chmod a+x run.sh
./run.sh 64
1: 2438970 0 sec
2: 2377595 1 sec
4: 2329366 2 sec
8: 2288410 3 sec
16: 2254275 7 sec
32: 2223342 14 sec
64: 2195642 27 sec
128: 2174050 55 sec
256: 2153351 109 sec
512: 2127972 218 sec
1024: 2105589 436 sec
2048: 2091738 871 sec
4096: 2081604 1740 sec
```
**minimize.cc:**
```
#include "include/tdoku.h"
#include <cstdio>
#include <cstring>
#include <fstream>
int NumClues(const char *puzzle) {
int num_clues = 0;
for (int i = 0; i < 81; i++) {
if (puzzle[i] != '.') num_clues++;
}
return num_clues;
}
int main(int argc, char **argv) {
int limit = std::stoi(argv[1]);
std::ifstream file;
file.open(argv[2]);
std::string line;
while (getline(file, line)) {
char puzzle[81], min_puzzle[81];
int min_clues = 81;
for (int j = 0; j < limit; j++) {
memcpy(puzzle, line.c_str(), 81);
TdokuMinimize(false, puzzle);
int clues = NumClues(puzzle);
if (clues <= min_clues) {
min_clues = clues;
memcpy(min_puzzle, puzzle, 81);
}
}
printf("%.81s %d\n", min_puzzle, min_clues);
}
}
```
**run.sh**
```
#!/bin/bash
concurrency=$1
killall minimize 2>/dev/null
rm -f ppcg_?? ppcg_??.done
split -n l/$concurrency ppcg_sudoku_testing.txt ppcg_
for p in {0..20}; do
t1=$(date +%s)
lim=$((2**p))
for f in ppcg_??; do
./minimize $lim $f > $f.done &
done
wait
t2=$(date +%s)
cat *.done | awk -F' ' -v t=$((t2 - t1)) -v n=$lim '{ x += $2 } END { printf("%5d: %10d %d sec\n",n,x,t); }'
done
```
[Answer]
# Python — 7,200,000 clues
As usual, here is a last-place reference solution:
```
def f(x): return x[:72] + "." * 9
```
Removing the bottom row of numbers provably leaves the puzzle solvable in all cases, as each column still has 8 of 9 numbers filled, and each number in the bottom row is simply the ninth number left over in the column.
If any serious contender manages to legally score worse than this one, I will be astonished.
[Answer]
# Python 2 - 6,000,000 clues
A simple solution that uses the 3 common methods of solving these puzzles:
```
def f(x):
return ''.join('.' if i<9 or i%9==0 or (i+23)%27 in (0,3) else c
for i,c in enumerate(x))
```
This function produces clue formats like this:
```
.........
.dddddddd
.dddddddd
.ddd.dd.d
.dddddddd
.dddddddd
.ddd.dd.d
.dddddddd
.dddddddd
```
This can always be solved. The 4 3x3 parts are solved first, then the 8 columns, then the 9 rows.
[Answer]
# PHP — 2,580,210 clues
This first removes the last row and column, and bottom right corner of every box. It then tries to clear out each cell, running the board through a simple solver after each change to ensure the board is still unambiguously solvable.
Much of the code below was modified from [one of my old answers](https://codegolf.stackexchange.com/a/41565/29611). `printBoard` uses 0s for empty cells.
```
<?php
// checks each row/col/block and removes impossible candidates
function reduce($cand){
do{
$old = $cand;
for($r = 0; $r < 9; ++$r){
for($c = 0; $c < 9; ++$c){
if(count($cand[$r][$c]) == 1){ // if filled in
// remove values from row and col and block
$remove = $cand[$r][$c];
for($i = 0; $i < 9; ++$i){
$cand[$r][$i] = array_diff($cand[$r][$i],$remove);
$cand[$i][$c] = array_diff($cand[$i][$c],$remove);
$br = floor($r/3)*3+$i/3;
$bc = floor($c/3)*3+$i%3;
$cand[$br][$bc] = array_diff($cand[$br][$bc],$remove);
}
$cand[$r][$c] = $remove;
}
}}
}while($old != $cand);
return $cand;
}
// checks candidate list for completion
function done($cand){
for($r = 0; $r < 9; ++$r){
for($c = 0; $c < 9; ++$c){
if(count($cand[$r][$c]) != 1)
return false;
}}
return true;
}
// board format: [[1,2,0,3,..],[..],..], $b[$row][$col]
function solve($board){
$cand = [[],[],[],[],[],[],[],[],[]];
for($r = 0; $r < 9; ++$r){
for($c = 0; $c < 9; ++$c){
if($board[$r][$c]){ // if filled in
$cand[$r][$c] = [$board[$r][$c]];
}else{
$cand[$r][$c] = range(1, 9);
}
}}
$cand = reduce($cand);
if(done($cand)) // goto not really necessary
goto end; // but it feels good to use it
else return false;
end:
// back to board format
$b = [];
for($r = 0; $r < 9; ++$r){
$b[$r] = [];
for($c = 0; $c < 9; ++$c){
if(count($cand[$r][$c]) == 1)
$b[$r][$c] = array_pop($cand[$r][$c]);
else
$b[$r][$c] = 0;
}
}
return $b;
}
function add_zeros($board, $ind){
for($r = 0; $r < 9; ++$r){
for($c = 0; $c < 9; ++$c){
$R = ($r + (int)($ind/9)) % 9;
$C = ($c + (int)($ind%9)) % 9;
if($board[$R][$C]){
$tmp = $board[$R][$C];
$board[$R][$C] = 0;
if(!solve($board))
$board[$R][$C] = $tmp;
}
}}
return $board;
}
function generate($board, $ind){
// remove last row+col
$board[8] = [0,0,0,0,0,0,0,0,0];
foreach($board as &$j) $j[8] = 0;
// remove bottom corner of each box
$board[2][2] = $board[2][5] = $board[5][2] = $board[5][5] = 0;
$board = add_zeros($board, $ind);
return $board;
}
function countClues($board){
$str = implode(array_map('implode', $board));
return 81 - substr_count($str, '0');
}
function generateBoard($board){
return generate($board, 0);
}
function printBoard($board){
for($i = 0; $i < 9; ++$i){
echo implode(' ', $board[$i]) . PHP_EOL;
}
flush();
}
function readBoard($str){
$tmp = str_split($str, 9);
$board = [];
for($i = 0; $i < 9; ++$i)
$board[] = str_split($tmp[$i], 1);
return $board;
}
// testing
$n = 0;
$f = fopen('ppcg_sudoku_testing.txt', 'r');
while(($l = fgets($f)) !== false){
$board = readBoard(trim($l));
$n += countClues(generateBoard($board));
}
echo $n;
```
] |
[Question]
[
Write a program or function that takes in a positive integer N, and prints or returns an N×N ASCII art string whose top half is a semicircle made of `(`'s and whose bottom half is a downward-pointing triangle made of `V`'s, with spaces used as padding.
In other words, make an ASCII ice cream cone: (output for N = 17)
```
(((((
(((((((((
(((((((((((((
(((((((((((((
(((((((((((((((
(((((((((((((((
(((((((((((((((((
(((((((((((((((((
VVVVVVVVVVVVVVVVV
VVVVVVVVVVVVVVV
VVVVVVVVVVVVV
VVVVVVVVVVV
VVVVVVVVV
VVVVVVV
VVVVV
VVV
V
```
# Examples
Here are the outputs for N = 1 to 5. **Note that for odd N, the triangle always must be the larger half.**
```
V
((
VV
(((
VVV
V
((
((((
VVVV
VV
(((
(((((
VVVVV
VVV
V
```
[Here's an N = 101 pastebin.](http://pastebin.com/dZH8nnEB)
And here's an ungolfed Python 3 reference implementation:
```
N = int(input())
ic = [[' '] * N for _ in range(N)]
for y in range(N//2):
for x in range(N):
if (x - (N - 1) / 2)**2 + (y - (N - 1) / 2)**2 < (N / 2)**2:
ic[y][x] = '('
for y in range(N//2, N):
for x in range(y - N//2, N - (y - N//2)):
ic[y][x] = 'V'
for line in ic:
print(''.join(line))
```
# Details
* Take input from stdin, command line, or as function argument. Output to stdout or similar, or you may return the string if you write a function.
* The cone portion should exactly match the reference implementation for all N.
* The ice cream portion does *not* need to exactly match the reference implementation as long as it is clearly in the shape of a semicircle for all N. (This is so you don't have to worry about slight differences in the semicircle due to roundoff errors.)
* There should not be any unnecessary leading spaces but there may be superfluous trailing spaces.
* The output may optionally contain a trailing newline.
* You may optionally use any 3 other distinct [printable ASCII](http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters) characters in place of `(`, `V`, and space.
# Scoring
The shortest submission [in bytes](https://mothereff.in/byte-counter) wins. Tiebreaker goes to the oldest submission.
[Answer]
# CJam, 46 bytes
[Try it online.](http://cjam.aditsu.net/#code=17%7B%3AZ%7BZ%7BZ(2.%2F%3AR-zYR%3C)%3AP%23YR-zP%23%2BZ2.%2FP%23%3ESP%3F%7D%2FN%7DfY%7D~)
```
{:Z{Z{Z(2./:R-zYR<):P#YR-zP#+Z2./P#>SP?}/N}fY}
```
I believe this currently mimics the original specification exactly, which was required when I started producing this answer. There may be potential to save a few bytes by making the math less accurate to the original specification, but until I see a way to save more than one or two bytes doing so, I'll leave it as-is.
### Explanation
```
{ "Begin block";
:Z{ "For each y from 0 to input-1";
Z{ "For each x from 0 to input-1";
Z(2./:R "Calculate the radius as (input-1)/2.0";
-z "Calculate the horizontal distance from the center";
YR<):P "Calculate the power to raise distances to: (y<radius)+1
(This results in Euclidean distance being calculated for
the ice cream and Manhattan distance being calculated
for the cone)";
# "Raise the horizontal distance to the determined power";
YR-zP# "Calculate the vertical distance from the center and
raise it to the determined power";
+ "Add the horizontal and vertical distances";
Z2./P# "Calculate the solid distance threshold and raise it to
the determined power";
>SP? "If the solid threshold is exceeded, produce a space;
otherwise, produce the determined power digit
(This results in ice cream being represented by the
digit '2' and the cone by the digit '1')";
}/ "End x loop";
N "Produce a new line";
}fY "End y loop";
} "End block";
```
[Answer]
## [inca2](https://github.com/luser-dr00g/inca/blob/master/README2.md) ~~129~~ ~~123~~ ~~121~~ ~~111~~ 107
This mostly uses the formulas from the python example, but using jot-dots and iotas instead of double-looping. The `i` function performs the circular test for the `j` function which invokes *jot-dot* upon it. And the `k` function performs the triangle test for the `l` function. The `c` function catenates the results of `j` and `l` and reshapes it to N×N.
*edit: -6* combine 2 maps into 1.
*edit: -2* remove useless ravels.
*edit:* nicer typescript.
*edit: -10* apply repeated expression array-wise.
*edit: -4* factor out repeated expression as a function.
*edit:* line-by-line commentary.
```
q:y-(n-1)%2
i:[((n%2)^2)>+/(qx y)^2
j:(~[y%2)i.(~y)
k:2*[x>[|qy
l:(@1+~]y%2)k.(~y)
c:y y#((jn<y),ly){' (V'
```
In more detail, the entry-point is the `c` function which takes one argument implicitly named `y`.
```
c:y y#((jn<y),ly){' (V'
n<y } assign y to 'n'
jn<y } call j(y)
ly } call l(y)
(( ), ) } catenate the results
( ){' (V' } map 0 1 2 to ' ' '(' 'V'
y y# } reshape to NxN
```
The `j` function receives the same input value as its `y` parameter.
```
j:(~[y%2)i.(~y)
y%2 } y divided by 2
[ } floor
~ } iota. this generates the row indices 0..y/2
~y } iota y. this generates the column indices 0..y
( )i.( ) } jot-dot with the function i
```
The jot-dot here does the double-loop. It calls the `i` function with every combination of elements from the left and right arrays (0..n/2 and 0..n). So the `i` function receives as `x` the *y* index of the table, and it receives as `y` the *x* index. The names got a little backwards here :).
```
i:[((n%2)^2)>+/(qx y)^2
n%2 } n divided by 2
(n%2)^2 } squared
x y } make a 2-element array (x,y)
qx y } call q on this array
```
where `q` does
```
q:y-(n-1)%2
n-1 } n minus 1
%2 } divided by 2
y- } y minus that
```
back to `i`
```
i:[((n%2)^2)>+/(qx y)^2
( )^2 } square the result from q(x,y)
+/ } sum the two numbers
> } compare the left side (above) with the right (=> 0/1)
[ } floor
```
The floor should not be necessary. But apparently there's a bug in the interpreter.
The `l` function works similarly to the `j` function, using a jot-dot.
```
l:(@1+~]y%2)k.(~y)
y%2 } y divided by 2
] } ceiling
~ } iota 0..ceil(y/2)-1
1+ } add 1 => 1..ceil(y/2)
@ } reverse => ceil(y/2)..1
~y } iota y 0..y-1
( )k.( ) } jot-dot using k
```
The `k` function yields a boolean scaled by 2 so the values can be distinguished from the ice cream values later on, in the mapping.
```
k:2*[x>[|qy
x } k's left arg
qy } y-(n-1)%2
| } abs
[ } floor
x } left-hand-side again
> } compare
[ } floor (should be unnecessary)
2* } scale by 2
```
In action (piping through `tr` to remove tab chars which are the REPL's prompt):
```
josh@Z1 ~/inca
$ ./inca2 <icecream | tr -d '\t'
c1
V
c2
((
VV
c3
(((
VVV
V
c4
((
((((
VVVV
VV
c5
(((
(((((
VVVVV
VVV
V
josh@Z1 ~/inca
$
```
[Answer]
# Python 2, ~~193~~ 192
Does not use strings, only math
```
N=input()
R=(N+1)/2;r=range(R)
s=lambda L,U:(10**U-10**L)/9
f=lambda N,m:s(0,N)+s(m,N-m)
g=lambda N,m:s(0,N)+s(m,N-m)*6
for i in r[1:]:print f(N,int(R-(2*R*i-i*i)**.5))
for i in r:print g(N,i)
```
`s(L,U)` returns a number of the form "`U`-digits with the rightmost `L` zeros and the rest ones"
`f(N,m)` returns an N-digit number with the inner section of `2` and an m-wide border of `1`on each side
`g(N,m)` does the same, but using `7` for the 'colour' of the inner section since it matches the texture of the cone more closely
Output
```
N=8 N=9
11122111 112222211
12222221 122222221
22222222 222222222
22222222 222222222
77777777 777777777
17777771 177777771
11777711 117777711
11177111 111777111
111171111
```
[Answer]
# Perl 6, 175
Pretty straightforward implementation without much golfing, just extraneous whitespace/punctuation elimination:
```
sub MAIN($d){my$r=($d/2).Int;for 1..$r ->$n
{my$y=$n-$r;my$h=sqrt($r*$r-$y*$y).Int;my$w=2*$h+$d%2;say
' 'x($r-$h)~'('x$w};for 1..($d-$r) ->$y {say ' 'x($y-1)~'V'x($d-2*$y+2)}}
```
] |
[Question]
[
Your task is to calculate the total number of key-presses required to enter a given text on an old cellphone.
The keymaps are:
```
1:1
2:abcABC2
3:defDEF3
4:ghiGHI4
5:jklJKL5
6:mnoMNO6
7:pqrsPQRS7
8:tuvTUV8
9:wxyzWXYZ9
0:<space><newline>0
```
To type `exaMPle TExt 01` , you would press `33 99 2 6666 77777 555 33 0 8888 33333 99 8 0 <a 1-sec pause here in real life but we'll ignore it>000 1` for a total of 37 keypresses.
The `*` key brings up a map of special characters:
```
.,'?!
"-()@
/:_;+
&%*=<
>£€$¥
¤[]{}
\~^¡¿
§#|`
```
with the first one (`.`) highlighted. You can move to highlight the required character using rectangular navigation keys and it takes another keypress to select.
So to insert `$`, you would press `*↓↓↓↓→→→<select>` i.e. a total of 9 key-presses.
* Input will be from a file called `source` placed in the current directory/directory of your program.
**EDIT:** Per requests in comments, I'm adding `STDIN` as a valid input method. Apologies for changing the spec after receiving answers.
* You must output `Total key presses <total_keypresses>`
* If the input file contains any character not in the given keymap, then your program must output `Invalid character <character> in source` and exit.
In short, the input and output of your program must resemble that of this(ungolfed) python script:
```
# This Python file uses the following encoding: utf-8
from __future__ import print_function
import sys
general_dict = { '1':1,
'a':1, 'b':2, 'c':3, 'A':4, 'B':5, 'C':6, '2':7,
'd':1, 'e':2, 'f':3, 'D':4, 'E':5, 'F':6, '3':7,
'g':1, 'h':2, 'i':3, 'G':4, 'H':5, 'I':6, '4':7,
'j':1, 'k':2, 'l':3, 'J':4, 'K':5, 'L':6, '5':7,
'm':1, 'n':2, 'o':3, 'M':4, 'N':5, 'O':6, '6':7,
'p':1, 'q':2, 'r':3, 's':4, 'P':5, 'Q':6, 'R':7, 'S':8, '7':9,
't':1, 'u':2, 'v':3, 'T':4, 'U':5, 'V':6, '8':7,
'w':1, 'x':2, 'y':3, 'z':4, 'W':5, 'X':6, 'Y':7, 'Z':8, '9':9,
' ':1, '\n':2, '0':3
}
special_chars = ['.',',',"'",'?','!','"','-','(',')','@','/',':','_',';','+','&','%','*','=','<','>','£','€','$','¥','¤','[',']','{','}','\\','~','^','¡','¿','§','#','|','`']
for x in special_chars:
general_dict[x]=(special_chars.index(x)/5) + (special_chars.index(x)%5) + 2
key_press_total = 0
with open('source') as f: # or # with sys.stdin as f:
for line in f:
for character in line:
if character in general_dict:
key_press_total+=general_dict[character]
else:
print('Invalid character',character,'in source')
sys.exit(1)
print('Total key presses',key_press_total)
```
This is code-golf, shortest program in bytes wins.
---
Shameless disclaimer: I made this challenge to have translations of the above python script in different languages which will be used to score [this challenge in the sandbox](http://meta.codegolf.stackexchange.com/a/1790/8766).
[Answer]
### GolfScript, 219 characters
Basic approach using a lookup table:
```
"Total key presses "0@1/{"1adgjmptw °behknqux\n.°cfilorvy0,\"°ADGJMsTz'-/°BEHKNPUW?(:&°CFILOQVX!)_%>°23456R8Y@;*£¤°SZ+=€[~°79<$]^§°¥{¡#°}¿|°`°".2$?)\1$<"°"/,{"Invalid character in source"18/*puts'"#{''exit}"'+~}if\;+}/
```
Try [here](http://golfscript.apphb.com/?c=OyJleGFNUGxlIFRFeHQgMDEiCgoiVG90YWwga2V5IHByZXNzZXMgIjBAMS97IjFhZGdqbXB0dyDCsGJlaGtucXV4XG4uwrBjZmlsb3J2eTAsXCLCsEFER0pNc1R6Jy0vwrBCRUhLTlBVVz8oOibCsENGSUxPUVZYISlfJT7CsDIzNDU2UjhZQDsqwqPCpMKwU1orPeKCrFt%2BwrA3OTwkXV7Cp8KwwqV7wqEjwrB9wr98wrBgwrAiLjIkPylcMSQ8IsKwIi8seyJJbnZhbGlkIGNoYXJhY3RlciAgaW4gc291cmNlIjE4LypwdXRzJyIjeycnZXhpdH0iJyt%2BfWlmXDsrfS8%3D&run=true).
[Answer]
## Ruby 2.0, 232
```
$.-=~(%W[1adgjmptw\s
behknqux.\n
cfilorvy0,"
ADGJMsTz-'/
BEHKNPUW?(:&
CFILOQVX!)_%>
23456R8Y@;*£¤
SZ+=€[\\
79<$]~§
¥{^{#
}¡|
¿`].index{|s|s[$c]}||$><<"Invalid character #$c in source"&exit)while$c=$<.getc
puts"Total key presses #$."
```
Very simple encoding scheme so far: over 75% of the characters are used for string/array literals ...
[Answer]
# CJam, 207 bytes
```
q:Q{" dptgwj1am hxk
.bnequ ,0flco\"rviy DT'/GsJz-AM (HP?KW&:BNEU LXCO_>FV!%)IQ 48@3;*26R¤£5Y €\+S[Z= $<§7~9] #{^¥ |¡} `¿"' /{1$#W>\}%1#)}%_0#){"Invalid character "Q@0#=" in source"}{:+"Total key presses "\}?
```
This program has 207 characters. With the appropriate encoding (Windows-1252), it fits in 207 bytes.
Note that Stack Exchange converts tabs (which I use as delimiter in the lookup table) into spaces, so you can't copy and paste the above code.
### Usage
Windows-1252 encoding
```
$ base64 -d > keys.cjam <<< cTpReyIgZHB0Z3dqMWFtCWh4awouYm5lcXUJLDBmbGNvXCJydml5CURUJy9Hc0p6LUFNCShIUD9LVyY6Qk5FVQlMWENPXz5GViElKUlRCTQ4QDM7KjI2UqSjNVkJgFwrU1taPQkkPKc3fjldCSN7XqUgfKF9CWC/IicJL3sxJCNXPlx9JTEjKX0lXzAjKXsiSW52YWxpZCBjaGFyYWN0ZXIgIlFAMCM9IiBpbiBzb3VyY2UifXs6KyJUb3RhbCBrZXkgcHJlc3NlcyAiXH0/
$ wc -c keys.cjam
207 keys.cjam
$ echo 'Hello, world!' | LANG=en_US.CP1252 cjam keys.cjam; echo
Total key presses 39
$ echo 'á' | LANG=en_US.CP1252 cjam keys.cjam; echo
Invalid character á in source
```
UTF-8 encoding
```
$ base64 -d > keys.cjam <<< cTpRezpDIiBkcHRnd2oxYW0JaHhrCi5ibmVxdQksMGZsY29cInJ2aXkJRFQnL0dzSnotQU0JKEhQP0tXJjpCTkVVCUxYQ09fPkZWISUpSVEJNDhAMzsqMjZSwqTCozVZCeKCrFwrU1taPQkkPMKnN345XQkje17CpSB8wqF9CWDCvyInCS97MSQjVz5cfSUxIyl9JV8wIyl7IkludmFsaWQgY2hhcmFjdGVyICJRQDAjPSIgaW4gc291cmNlIn17OisiVG90YWwga2V5IHByZXNzZXMgIlx9Pw==
$ wc -cm keys.cjam
209 217 keys.cjam
$ echo 'Hello, world!' | LANG=en_US.UTF8 cjam keys.cjam; echo
Total key presses 39
$ echo 'á' | LANG=en_US.UTF8 cjam keys.cjam; echo
Invalid character á in source
```
[Answer]
### PHP, 711 708 676 characters (reading from STDIN now)
```
<?php $message=iconv("UTF-8","CP1252",fread(STDIN,1024));@$s=str_split;$special=iconv("UTF-8","CP1252",'.,\'?!"-()@/:_;+&%*=<>£€$¥¤[]{}\~^¡¿§#|`');$z=0;foreach($s($message)as$l){$a=ord($l);$b=$a;if($a==13)continue;($a>114||($a>82&&$a<91))&&$a--;$w=$a<58?($a-48):($a<91?($a-64):($a-96));$y=($a<58?1:($w%3?$w%3:3));$a<91&&$y+=3;$a<58&&$y=7;if($a==55||$a==57)$y=9;if($b==115||$b==122)$y=4;if($b==90||$b==83)$y=8;if(($b>79&&$b<83)||($a>85&&$a<89))$y++;($a==32||$a==49)&&$y=1;$a==10&&$y=2;$a==48&&$y=3;$u=array_search($l,$s($special));if($u!==false){$y=2+floor($u/5)+$u%5;}$z+=$y;if(($a<32||$a>127)&&$a!=10){echo"Invalid character $l in source";exit();}}echo"Total key presses $z";
```
*My first golf so far :)*
Wanted to try a rather unconventional approach. Instead of having a list of every character and how many clicks are needed to create it, I am using the character's ASCII values and calculate their required keypresses. **Thought it would spare me some characters first, now I think it's even longer than an array-approach.**
My main problem are the keys 7 and 9, which have 4 letters, instead of 3. Therefore I needed to create a couple of fallbacks, which blew my code up by almost 200 characters.
**Ungolfed version**
```
<?php
@$source = source;
$h = fopen($source, @r);
$message = iconv("UTF-8", "CP1252", fread($h, filesize($source)));
@$split = str_split;
$special = iconv("UTF-8", "CP1252", '.,\'?!"-()@/:_;+&%*=<>£€$¥¤[]{}\~^¡¿§#|`');
$count = 0;
foreach ($split ($message) as $character) {
$ascii = ord($character);
$helper = $ascii;
if ($a == 13) continue;
($a > 114 || ($a > 82 && $a < 91)) && $ascii--;
$key = $ascii < 58 ? ($a - 48) : ($a < 91 ? ($a - 64) : ($a - 96));
$presses = ($a < 58 ? 1 : ($key % 3 ? $key % 3 : 3));
// This part uses a lot of (probably unnecessary or still optimizable) fallbacks
// for those characters, that are on "4-letter-keys"
$ascii < 91 && $presses += 3;
$ascii < 58 && $presses = 7;
if ($a == 55 || $a == 57) $presses = 9;
if ($helper == 115 || $helper == 122) $presses = 4;
if ($helper == 90 || $helper == 83) $presses = 8;
if (($helper > 79 && $helper < 83) || ($a > 85 && $a < 89)) $presses++;
$ascii == 32 && $presses = 1;
$ascii == 10 && $presses = 2;
$ascii == 48 && $presses = 3;
$ascii == 49 && $presses = 1;
$key = array_search($l, $split($special));
if ($key !== false){
$presses = 2 + floor($key/5) + $key % 5;
}
$count += $presses;
if ($a < 32 && $a > 127 && $a != 10) {
echo "Invalid character $l in source";
exit();
}
}
echo "Total key presses $count";
```
I assume there's still a lot of room for improvement, but I'm pretty happy with this.
Another bad thing is the required use of `iconv()` for the list of special characters. Some of these (`€`, `¥`, ...) are not natively supported by PHP.
[Answer]
## Python 3, 239 characters
```
s='1adgjmptw 1behknqux\n.1cfilorvy0,"1ADGJMsTz\'-/1BEHKNPUW?(:&1CFILOQVX!)_%>123456R8Y@;*£¤1SZ+=€[\\179<$]~§1¥{^#1}¡|1¿`'
print('Total key presses',sum(s[:s.find(c)+1].count('1')or exit('Invalid character %c in source'%c)for c in input()))
```
[Answer]
# JavaScript (E6) 291
**Edit**
Shell version, using spydermonkey shell. Read from a 'source' file, write to sdtout
```
z=t=0,[...read('source')].map(c=>t-=~((i=".\"/&>¤\\§,-:%£[~#'(_*€]^|?);=${¡`!@+<¥}¿".indexOf(c))<0?(p="0\n 9ZYXWzyxw8VUTvut7SRQPsrqp6ONMonm5LKJlkj4IHGihg3FEDfed2CBAcba10".split(c)[1])?p.search(/\d/):z="Invalid character "+c+" in source":i%8-~(i>>3))),print(z||"Total key presses "+t)
```
First try, works in FireFox console using popup for input and output
```
P=m=>(z=t=0,[...m].map(c=>t-=~((i=".\"/&>¤\\§,-:%£[~#'(_*€]^|?);=${¡`!@+<¥}¿".indexOf(c))<0
?(p="0\n 9ZYXWzyxw8VUTvut7SRQPsrqp6ONMonm5LKJlkj4IHGihg3FEDfed2CBAcba10".split(c)[1])
?p.search(/\d/):z="Invalid character "+c+" in source":i%8-~(i>>3))),z||"Total key presses "+t);
alert(P(prompt()))
```
**Readable**
```
P=m=>(
z=t=0,
[...m].map(
c=>t-=~(
(i = ".\"/&>¤\\§,-:%£[~#'(_*€]^|?);=${¡`!@+<¥}¿".indexOf(c)) < 0
? (p = "0\n 9ZYXWzyxw8VUTvut7SRQPsrqp6ONMonm5LKJlkj4IHGihg3FEDfed2CBAcba10".split(c)[1])
? p.search(/\d/)
: z="Invalid character "+c+" in source"
: i%8 - ~(i>>3)
)
),
z||"Total key presses "+t
);
```
[Answer]
## VBScript 435
Does not support non-ASCII chars. I was pretty far along with my code so I thought I'd post it for reference. I don't think anyone else used this approach.
```
i=inputbox(i)
a=SPLIT("1 abcABC2 defDEF3 ghiGHI4 jklJKL5 mnoMNO6 pqrsPQRS7 tuvTUV8 wxyzWXYZ9 0")
a(9)=" "+vbLf+"0"
b=SPLIT(".,'?! ""-()@ /:_;+ &%*=< >£€$¥ ¤[]{} \~^¡¿ §#|` x x")
for o=1 to len(i)
n=0
for x=0 to 9
for c=1 to 10
d=mid(i,o,1)
IF n=0 AND mid(b(x),c,1)=d THEN n=c+x
IF mid(a(x),c,1)=d THEN n=c
next
next
z=n+z
IF n=0 THEN EXIT FOR
next
o="Total key presses "+cstr(z)
IF n=0 THEN o="Invalid character "+d+" in source"
msgbox o
```
] |
[Question]
[
The 32-point compass is... interesting, to say the least.

By Denelson83 (Own work) [[GFDL](http://www.gnu.org/copyleft/fdl.html) or [CC-BY-SA-3.0](http://creativecommons.org/licenses/by-sa/3.0/)], via [Wikimedia Commons](http://commons.wikimedia.org/wiki/File:Compass_Card.png)
Your challenge is to take a degree measure, and convert it into a direction on the 32-point compass.
Each direction is 11.25 (360 / 32) degrees farther than the previous. For example, N (north) is 0 degrees, NbE (north by east) is 11.25 degrees, NNE (north-northeast) is 22.5 degrees, etc.
As for how you're supposed to get the directions,
* 0 degrees is N, 90 degrees is E, 180 degrees is S, and 270 degrees is W.
+ These are called cardinal directions.
* The halfway points between the cardinal directions are simply the cardinal directions they're between concatenated. N or S always go first, and W or E always are second.
+ These are called ordinal directions.
* The halfway points between the cardinal and ordinal directions are the directions they're between concatenated, again, with a "-" in between. Cardinal directions go first, ordinal second.
+ These are called secondary-intercardinal directions.
* The halfway points between secondary-intercardinal directions and other directions are the other directions "by" the cardinal direction they're closest to (other than the one directly next to them, of course).
+ I have no idea what these are called :P
If all this explanation hurts your brain as much as mine, you can refer to this chart:
```
1 North N
2 North by east NbE
3 North-northeast NNE
4 Northeast by north NEbN
5 Northeast NE
6 Northeast by east NEbE
7 East-northeast ENE
8 East by north EbN
9 East E
10 East by south EbS
11 East-southeast ESE
12 Southeast by east SEbE
13 Southeast SE
14 Southeast by south SEbS
15 South-southeast SSE
16 South by east SbE
17 South S
18 South by west SbW
19 South-southwest SSW
20 Southwest by south SWbS
21 Southwest SW
22 Southwest by west SWbW
23 West-southwest WSW
24 West by south WbS
25 West W
26 West by north WbN
27 West-northwest WNW
28 Northwest by west NWbW
29 Northwest NW
30 Northwest by north NWbN
31 North-northwest NNW
32 North by west NbW
```
[Here is a more detailed chart and possibly better explanation of the points of the compass.](http://en.wikipedia.org/wiki/Points_of_the_compass)
Your challenge is to take input in degrees, and output the full name of the compass direction it corresponds to, along with its abbreviation.
Test cases:
```
Input Output
0 North N
23.97 North-northeast NNE
33.7 Northeast by north NEbN
73.12 East-northeast ENE
73.13 East by north EbN
219 Southwest by south SWbS
275 West W
276 West by north WbN
287 West-northwest WNW
```
All capitalization must be preserved, as in the test cases. Maximum number of decimal places is 2. All input numbers will be greater than or equal to 0, and less than 360. If a decimal point is present, there will be digits on both sides (you don't have to handle `.1` or `1.`).
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
[Answer]
## Javascript ~~470~~ ~~453~~ ~~438~~ ~~434~~ ~~432~~ ~~421~~ 404
```
s=String;s.prototype.a=s.prototype.replace;var a=prompt()/11.25,a=a+0.5|0,b,k,c=a,d=c%8,c=c/8|0,e=["north","east","south","west"],f,g,h;f=e[c];g=e[(c+1)%4];h=f==e[0]|f==e[2]?f+g:g+f;b="1;1 by 2;1-C;C by 1;C;C by 2;2-C;2 by 1".split(";")[d].a(1,f).a(2,g).a("C",h);k=b.a(/north/g,"N").a(/east/g,"E").a(/south/g,"S").a(/west/g,"W").a(/by/g,"b").a(/[\s-]/g,"");b=b[0].toUpperCase()+b.slice(1);alert(b+" "+k)
```
You can copy this code to your console and execute it. It prompts you for the degrees input and outputs the result with `alert();`
Ungolfed Javascript can be found at this fiddle:
<http://jsfiddle.net/AezL3/11>
[Answer]
## Perl, ~~250 236 231 188~~ 187
**Edit:** Some bytes off exploiting symmetry (as I've seen in @bazzargh solution)
**+Edit:** And some evil tricks...
**+Edit**: Back to where I started (working with list, not string), and exploiting more symmetry = 1 byte off and a whole lot uglier.
```
$_=((@_=(1,@_=qw(1b3 1-13 13b1 13 13b3 3-13 3b1),3,map{y/1/2/r}reverse@_)),map{y/312/421/r}@_)[int<>/11.25+.5];print ucfirst s/\w/(' by ',north,south,east,west)[$&]/ger,' ',y/1-4-/NSEW/dr
```
Pretty-printed:
```
$_=(
(@_=
(
1,
@_=qw(1b3 1-13 13b1 13 13b3 3-13 3b1),
3,
map{y/1/2/r}reverse@_
)
),map{y/312/421/r}@_
)[int<>/11.25+.5];
print ucfirst s/\w/(' by ',north,south,east,west)[$&]/ger,' ',y/1-4-/NSEW/dr
```
5.014 required because of `r` modifier.
[Answer]
# Haskell ~~415~~ ~~372~~ ~~347~~ ~~330~~ ~~317~~ ~~304~~ 301C
Ended up converging on a solution like @VadimR's (and the symmetry's back!). Usage: `h 219` outputs `"Southwest by south SWbS"`
```
d"N"="north"
d"S"="south"
d"E"="east"
d"W"="west"
d"b"=" by "
d"-"="-"
d(x:y)=d[x]++d y
e(x:y)=x:tail(d$x:y)
k 'N'='S'
k 'S'='N'
k 'E'='W'
k x=x
r="N NbE N-NE NEbN NE NEbE E-NE EbN E EbS E-SE SEbE SE SEbS S-SE SbE "
p=words$r++(map k r)
g x=p!!mod(round$x/11.25)32
h x=e(g x)++(filter(/='-')$' ':g x)
```
3 more chars gone, thanks @shiona.
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), ~~482~~ ~~438~~ 424 bytes
```
lambda h:' '.join([b(h),a(a(a(b(h)),1),d={' by ':'b','-':''})])
L=str.lower
c={'North':'N','East':'E','South':'S','West':'W'}
a=lambda t,l=0,d=c:[*(t:=t.replace([i,L(i)][l],d[i])for i in[*d])][-1]
b=lambda h,k=[*c]:a('W|W by x|W-z|Z by w|Z|Z by x|X-z|X by w'.split('|')[int((q:=h*4/45+.5)%8)],d={'W':(W:=[*k][(v:=int(q//8)%4)]),'X':(X:=[*k][(v+1)%4]),'w':(w:=L(W)),'x':(x:=L(X)),'Z':(Z:=[W+x,X+w][W in'EastWest']),'z':L(Z)})
```
[Try it online!](https://tio.run/##VZJdj6IwFIbv@RWNyaStVhy/VqdJL929Md54USKSDSCu7LDAQGdgRvztzmnxazHBc97z9qF9If9Uhywdz/PivBfbc@L/C3Y@OnCMsP03i1PiBuRAmU/0T5eUDSnbiSNGwSfCHAeY4T784xP1qLUUpSrsJKuiwgrBtMoKdYDpClwLv1RQLqBcZ@9GXkMtIyNLfLJ8cXm@Yol4hqeE3O0SxYWyiyhP/DAibsyWJKaem3hs58Ye3WcFilGcut2dB3J/6FnBFXNgr8Lthh73CZaN1DuuG9n/aja6rJpNW9SNA5pjNGyXeRIrghtM3ThVhLxxcehOBpNpz57Spzn1zOkl5kRyoL96LvngQlvfBoM5fZpADgw7MHdu894QdC1XIFdcLImEIHENXa07R3cb6DawRPZq5vQqz5VwLJOaiUgv/8J8STb0RM8KpN@hX0YlEsi1EFzkmaGOCRytOpS12mhsv8yuej/V9wiIaLVa3DzjsX2zmCEEkbacRXBHzcb2cAQ@vaMH0uKBpC3ji@VOeYSMhi8wN@@/ilpTqRu0lsH67ppNwaWPjeSD@OMq3tDyET2fXebt7gxfrgBgeZalvxMT2oefMOUXfyIF8aJ7jtxQ8kK/yT3@Cfbj1X9iKKrzKFTRjqOt6hzb9aeOjel/q35lCh07cRpmRQH2jjvqEqIpXOzJlUapEC2Acu@E4PT5u@IGCw6AblNMz98 "Python 3.8 (pre-release) – Try It Online")
This is what I got after some golfing of [tony goodwin's answer](https://codegolf.stackexchange.com/a/196617); posted at its own answer due to the TIO link being too long for a comment. If he chooses to update his answer to the above, I will delete this answer.
I am assuming that it's acceptable to submit a function as a solution rather than a full program. If not, [here](https://tio.run/##PZBNj4IwEIbv/Aoupq1UXFbNmiY9eiNePJTQ9MCXoZEFxLqgi7@dnbLZTQ9932c6M51pH6Zs6s2@7aYp5DfT@VXTF52T8W90bDpTIoaOiKJDcjMgDyBPzX3GJ9CimLFALyfhVfKZ5olraMXfaM4zJpfYMG78rmirJCuw1DTEmihZKZpLrci56Vzt6loucwV4FSgn/StT0guXy0yxBCMxCjd9uMMoVs8xtrIf418xjBGwaGbIv7WVNhiNiEhdG4yvjJfL7Xq78/wdWewJ9IXBBGJYMKh@URJ/MW6fXtfrPVlsiSIURRCP/uNeANziHnDPeIgFATeAG6yLrIvBxZAivIFGXq@kgLHmrc0rsulPxEIckxdx2s52THHJ@LlqEoN13d4NJlAowfZACHRA5t/a0WDHKax7BTd6ETJNHxs/eP8B "Python 3.8 (pre-release) – Try It Online") is a full program at 426 bytes.
I expect that much can still be done to shorten `b`.
**Edit:** Golfed off 44 bytes, courtesy of the majestic walrus. Still don't feel like `b` is done being golfed.
**Edit2:** Shaved off another 14 by unpacking dicts instead of using `keys()` and `items()`.
[Answer]
# Python, ~~2103~~ ~~1647~~ ~~1103~~ ~~1034~~ ~~924~~ ~~889~~ 848 bytes
Very late, I know. Thanks for the challenge, I am setting up a magnetometer for wind direction with my Pi, and wanted a 16 point of compass solution like this to feed into weather forecasting algorithms. All my code is in Python, so here is version of the javascript solution already posted in Python, but with an extra twist that you can specify either 32, 16, or 8 points of the compass at variable j, and I have changed the offset of degHead in the statement before it, depending on the number of points. I used a modified rename alogorithm (and used variables I could rename without corrupting the words!) to ensure I met the case requirements of the question.
I know this won't win, as Python is more wordy, and so am I.
Short version:
```
def a(t,d,l):
for i,j in d.items():
if l:
i=i.lower()
t=t.replace(i,j)
return t
def b(h,q):
p=32
r=360
h=(h+(r/q/2))/(r/p)
j=int(int(int(h %8)%8/(p/q))*p/q)
h=int(h/8)%4
k=c.keys()
u=['W','W by x','W-z','Z by w','Z','Z by x','X-z','X by w']
d={}
d['W']=list(k)[h]
d['w']=d['W'].lower()
d['X']=list(k)[(h+1)%4]
d['x']=d['X'].lower()
if(d['W']=='North' or d['W']=='South'):
d['Z']=d['W']+d['x']
else:
d['Z']=d['X']+d['w']
d['z']=d['Z'].lower()
return a(u[j],d,0)
def g(n):
n=a(n,c,0)
n=a(n,c,1)
d={'by':'b',' ':'','-':''}
return a(n,d,0)
def v(m):
while True:
try:
return float(input(m))
except ValueError:
print("?")
c={'North':'N','East':'E','South':'S','West':'W'}
while True:
h=v("?")
n=b(h,32)
print(h,n,g(n))
```
Clear version
```
import math
import sys
def calcPoint(degHead, points):
maxPoints=32
if points not in(8,16,32):
sys.exit("not a good question")
degHead=(degHead+(360/points/2))/(360/maxPoints)
j =int(int( int(degHead % 8)%8/(maxPoints/points))*maxPoints/points)
degHead = int(degHead / 8) % 4
cardinal = ['North', 'East', 'South', 'West']
pointDesc = ['W', 'W by x', 'W-z', 'Z by w', 'Z', 'Z by x', 'X-z', 'X by w']#vars not compass points
W = cardinal[degHead]
X = cardinal[(degHead + 1) % 4]
w=W.lower()
x=X.lower()
if (W == cardinal[0] or W == cardinal[2]) :
Z =W + x
else:
Z =X + w
z=Z.lower()
return pointDesc[j].replace('W', W).replace('X', X).replace('w', w).replace('x', x).replace('Z', Z).replace('z', z);
def getShortName(name):
return name.replace('North', 'N').replace('East', 'E').replace('South', 'S').replace('West', 'W').replace('north', 'N').replace('east', 'E').replace('south', 'S').replace('west', 'W').replace('by', 'b').replace(' ', '').replace('-', '')
def input_number(msg, err_msg=None):
while True:
try:
return float(input(msg))
except ValueError:
sys.exit("not a number")
while True:
headingCalib=input_number("input a number: ")
print (headingCalib, end=' ')
name = calcPoint(headingCalib,32) #degrees heading, points of compass 8,16 or 32)
print (name, end=' ')
shortName = getShortName(name)
print (shortName)
```
] |
[Question]
[
This challenge is a *cut'n paste* from [Enlarge ASCII art](https://codegolf.stackexchange.com/q/19450/9424), but *reversed*, using [*PetSCII*](https://en.wikipedia.org/wiki/PETSCII) based *half-block* chars:
```
string=" ▝▘▀▗▐▚▜▖▞▌▛▄▟▙█"
```
There, [*PetSCII*](https://en.wikipedia.org/wiki/PETSCII) is emulated by using UTF-8 characters, you may found between *`U+2580 UPPER HALF BLOCK`* and *`U+259F QUADRANT UPPER RIGHT AND LOWER LEFT AND LOWER RIGHT`*.
So the goal is to reduce by `1/2` submited [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'").
You have to group 2 char from 2 lines to obtain one 2x2 pattern for one character:
```
|XX| |X | |X | | |
|XX| -> '█' |XX| -> '▙' | X| -> '▚' | X| -> '▗' and so on...
```
Some samples: From
```
OOOOOO OOOOOO OOOOOO OOOOOOO OOOOOO OOOOOO OO OOOOOOO
OO OO OO OO OO OO OO OO OO OO OO
OO OO OO OO OO OOOOO OO OOO OO OO OO OOOOO
OO OO OO OO OO OO OO OO OO OO OO OO
OOOOOO OOOOOO OOOOOO OOOOOOO OOOOOO OOOOOO OOOOOOO OO
```
you have to render:
```
▟▀▀▘▟▀▀▙▐▛▀▙▐▛▀▀ ▗▛▀▀ ▟▀▀▙▐▌ ▐▛▀▀
█ █ █▐▌ █▐▛▀ ▐▌ ▜▌█ █▐▌ ▐▛▀
▝▀▀▘▝▀▀▘▝▀▀▘▝▀▀▀ ▀▀▀ ▝▀▀▘▝▀▀▀▝▘
```
And from:
```
OOOOOO OOOOOO OOOOOO OOOOOOO OOOOOO OOOOOO OO OOOOOOO
OO OO OO OO OO OO OO OO OO OO OO
OO OO OO OO OO OOOOO OO OOO OO OO OO OOOOO
OO OO OO OO OO OO OO OO OO OO OO OO
OOOOOO OOOOOO OOOOOO OOOOOOO OOOOOO OOOOOO OOOOOOO OO
```
Where 1st column hold spaces you may render:
```
▗▛▀▀▗▛▀▜▖█▀▜▖█▀▀▘ ▟▀▀▘▗▛▀▜▖█ █▀▀▘
▐▌ ▐▌ ▐▌█ ▐▌█▀▘ █ ▝█▐▌ ▐▌█ █▀▘
▀▀▀ ▀▀▀ ▀▀▀ ▀▀▀▘ ▝▀▀▘ ▀▀▀ ▀▀▀▘▀
```
Piping:
```
wget -O - https://codegolf.stackexchange.com/q/19123/9424 |
sed -ne '/<pre><code>/,/<\/code><\/pre>/{//{/\//q};s/<pre><code>//;p}'
('l2v2l6v2'+ 'e1l1v3l2'+
'v3e1v7e1v7e1v7e1l2v6e1l4v5'+
'e1l6v4e1l8v3e1l7l3v2e1l9l3v1')
.replace(/[lve]\d/g,function
(c){return Array(-~c[1]).
join({l:' ',v:'Love'
,e:'\n'}[c[0
]])})
```
must give:
```
▗▟█████▙▟█████▄
▜█████████████▛▘
▝▀███▙▛█████▀
▝▀▜██▀▘
```
Other samples on my terminal:

## With standard rules:
* Input ASCII from STDIN or file, without special chars, tabulations or UTF-8.
* Each submited chars have to be represented, only whitespaces have to stay *empty*.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") too, so the lowest score win. Score is computed as:
+ `+1` by chars, to be counted **in chars, not in bytes!!** Ie: `s=' ▝▘▀▗▐▚▜▖▞▌▛▄▟▙█'` count for **20** chars, not **52** !!
+ `-10` for explanation;
+ `+20` for use of external font tool or library.
[Answer]
## GolfScript (90 chars)
```
n/.,1&[""]*+.{,}%$-1=.1&+{1$,-´' '*+}+%2/{zip 2/{~+0\{32=!1$++}/" ▗▝▐▖▄▞▟▘▚▀▜▌▙▛█"3/=}%n}%
```
A lot of this goes to handling ragged arrays. Nasty test case:
```
xx
xxx
xxx
xx
x
```
contains a 3 different 2x2 grids with only one of the 4 cells containing any character at all.
To make things worse, the `zip` transposition to chop the columns into pairs [gives the same output](http://golfscript.apphb.com/?c=WyJ4eCIgInh4eCJdemlwIHAKWyJ4eHgiICJ4eCJdemlwIHA%3D) for `["xx" "xxx"]zip` and `["xxx" "xx"]zip`. I therefore begin by padding out to ensure that all lines are the same even length, and that there are an even number of lines.
Note that this program assumes that the interpreter will treat " ▗▖▄▝▐▞▟▘▚▌▙▀▜▛█" as a string of length 48, even though as per instructions in the question I'm counting it as 16 chars plus delimiters.
I've tested this to the best of my ability, but I can't find a monospace font which actually renders those characters correctly.
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), ~~257 ... 254~~ 248 - 32 - 10 = 212 chars
```
#include<bits/stdc++.h>
namespace std{int f(){string a,b;for(int i:{1,3}){getline(cin,a={});b.resize(max(a.size()/2,b.size()));for(int j=a.size();j--;)b[j/2]+=(a[j]>32)<<i-j%2;}for(int i:b)cout.write(" ▝▘▀▗▐▚▜▖▞▌▛▄▟▙█"+i*3,3);cout<<endl;cin&&f();}}
```
[Try it online!](https://tio.run/##nVLNjpswEL7zFNZWXeMGSIFttgWyUu@V8gAsBzBOauQ4ERD3B1GttD300ENP7n/7bn6R1JAUdtUfqR2JmWG@z9@MrcHbrb3CeL@/Qzlmu5xEGa2raVXneDJxnl4YPF2TaptiAnStobwGSxM1VV1SvgKplYXLTWl2ZRo0ruW3qFmRmlFOTEy5lc6bFoWZU5KKviTmOn1upk6foqlnZccUoUGlmP/Ew8K2Q5TFxdRLJnMzjYvkwvdQFFG7uOuF7dg3Q3izq51nJa2JeaKurpX8quQHJa@UfK/kOyU/KflFSankNyXfKvlZyddKflfyo5JvTib0nm/5KOxEoojwnIV69NNTfc@wbfddj3VKeX/rPAj68h4segN/iDrpbMhH9CawAMZYOPojfWCO4C@sG8jfdBa3jy@G47d0Dqx/mef3Osd5/vt9DsmBYBiG9iZknvDYTHhwAgAkLnOFz/SPAaDwiSvOx08zZ9qfiQca7qgzcab9w47HzpkvPB0f6ehCZAC9llumV9ucxkyQ5DKfrqzljuOabnjfGaOmJPWu5OBxWaYvTPsVjt0EOcZh/GKj16JhAQTQEgF8shEEGsMrWSSAlxy2MY7vj9XOkgS16Ac "C++ (gcc) – Try It Online")
Explained:
```
#include<bits/stdc++.h> // Evil hack to include all STL headers
namespace std { // Shorter than using namespace std;
int f() { // int is one byte shorter than void
string a, b; // a will hold one input line, b will hold one reduced line
for (int i: {1, 3}) { // Do two iterations:
getline(cin, a = {}); // Read an input line, make sure it is empty first
b.resize(max(a.size() / 2, b.size())); // Resize b such that it is max of both inputs divided by 2
for (int j = a.size(); j--;) // Loop over all characters in the input line backwards (order doesn't matter here)
b[j/2] += (a[j] > 32) << i - j % 2; // Set the bits in b depending on the presence of non-whitespace in a
}
for (int i: b) // For each character in b:
cout.write("⠀▝▘▀▗▐▚▜▖▞▌▛▄▟▙█" + 3 * i, 3); // Write the corresponding multibyte character
cout << endl; // Write a newline and annoy people with an unnecessary flush
cin && f(); // If we didn't reach the end of the input yet:
// Tail recurse to the start of the function
}
}
```
Thanks to Razetime for fixing the wrong space character. I also found an issue if the input is an odd number of lines, which required three extra characters to fix. Thanks to ceilingcat for shaving off 9 bytes.
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 38 - 10 = 28 chars
```
' ▗▖▄▝▐▞▟▘▚▌▙▀▜▛█'[{2⊥∊⍵}⌺(2 2⍴2)≠⎕⍪0]
```
[Try it online!](https://tio.run/##nZC7CsJAEEX7fMV2q0Ug5C@s9gPEIpDEJqiFhSKChcQYEomF4/vR2Fhr4@fcH4kx5mHwATrFzmXvncMwWsuS9a5mNeuy0WkbDd3QQ0xmFQE7UCQ4IzPkDDQHEWgI2oIC0A60By1AK5AHWoIGoA1oDXJ4tafCPcJx4V/68K4llanwz2oZ40OEhn9SamFEDk0J9pQzERf70CNxr0zn7rMhOOP5T/Im@Syamy@p3PkOEsV5kc0XQHHqt43eg9KN/r7RQ6SgGw "APL (Dyalog Extended) – Try It Online")
-10 bytes for an explanation? Count me in!
-14 bytes from Adám.
Takes input as a list of lines from STDIN.
## Explanation
```
' ▗▖▄▝▐▞▟▘▚▌▙▀▜▛█'[{2⊥∊⍵}⌺(2 2⍴2)⊢↑{2|≢⍵:⍵,0⋄⍵}' '≠⎕]
⎕ take input
' '≠ convert spaces to 0, 1 otherwise
{2|≢⍵:⍵,0⋄⍵} if there are an odd number of rows, append a 0 to each column
⊢↑ convert to matrix, apply the following:
⌺(2 2⍴2) cut the matrix into 2x2 pieces, apply the following to them:
{2⊥∊⍵} enlist, decode from base 2
' ▗▖▄▝▐▞▟▘▚▌▙▀▜▛█'[ ] index those numbers into the box drawing characters
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 159 chars (192 bytes)
```
(|lines.map(*~' '),'')».comb(/../).rotor(2).map:{my@d=' 'xx.max(*.elems);say [~] map {"█▛▜▀▙▌▚▘▟▞▐▝▄▖▗ ".comb[:2(.trans([' ',/./]=>~⑩))]},[Z~] .map:{|$_,|@d}}
```
[Try it online!](https://tio.run/##RY9NTsMwEIX3PYWFkGyX4JC0pBBUVPacgDRCITWoyEkqJ7VapYlYsGDBAjbmH9acgR1HmYsEB5D6JM/I8z55nmdcCq9pyEpMU56zJJqRbo0RphbG9PuLxVlyRmzGbMpkVmSSuLSF/DJZjiZDjBBeLMxgQbqMC57k9CCPliioQ2QoVG6AvgH9AvoV9BXoJ9C3oJ9BP4L@AP0O@g70G@hr0Br0A9r43Rf4LmGFjNKcBCaKZTM7HB7WcP9JaVhZwYl5/S/EavPUWo0mVdU0CCGChatc4SkXb5lg3BGO6glz6SCsetxRg/UxpGdqX@0au0U91Td1r@XEQPSUa/q@6Q6mHcQkn4ko5sQOhOLheGJfWOfzNC6mWdppN8e0lLyYyxQdSRktyXYdB05IWWsaXWbTlJTCb3@jfHycKY7/LSOL@3ic4iqIg531tFUY0or@AA "Perl 6 – Try It Online")
[Answer]
## Bash (~~203~~, 197 chars)
```
#!/bin/bash
r=" ▝▘▀▗▐▚▜▖▞▌▛▄▟▙█" IFS=;while read -r m;do read -r n o;for((l=${#m}>${#n}?${#m}:${#n},i=0; i<l; i+=2)){
printf -ve %-2s "${n:i:2}" "${m:i:2}";e=${e//[^ ]/1};o+=${r:2#${e// /0}:1};};echo "$o";done
```
or
```
r=" ▝▘▀▗▐▚▜▖▞▌▛▄▟▙█" IFS=
while read -r m; do
read -r n o
for ((l=${#m}>${#n}?${#m}:${#n},i=0; i<l; i+=2)) {
printf -ve %-2s "${n:i:2}" "${m:i:2}"
e=${e//[^ ]/1}
o+=${r:2#${e// /0}:1}
}
echo "$o"
done
```
[Answer]
## Perl (192 chars)
```
#!/usr/bin/perl -CS
use utf8;my$r=" ▘▝▀▖▌▞▛▗▚▐▜▄▙▟█";while($v=<>){$w=<>;foreach my$i(0..length($v)/2){($x=substr($v,$i*2,2).substr($w,$i*2,2))=~s/\S/1/g;$x=~s/ /0/g;print substr($r,ord pack("b8",$x),1)}print"\n"}
```
or
```
#!/usr/bin/perl -CS
use utf8;
my $r = " ▘▝▀▖▌▞▛▗▚▐▜▄▙▟█";
while ( $v = <> ) {
$w = <>;
foreach my $i ( 0 .. length($v) / 2 ) {
( $x = substr( $v, $i * 2, 2 ) . substr( $w, $i * 2, 2 ) ) =~ s/\S/1/g;
$x =~ s/ /0/g;
print substr( $r, ord pack( "b8", $x ), 1 );
}
print "\n";
}
```
] |
[Question]
[
The way points are assigned on a dice follows a regular pattern, the center dot is present if and only if the number is odd. To represent the even numbers, pairs of dots on opposite sides of the center are added, which will stay present for all successive numbers.
```
1:
O
2: 3: 4: 5: 6:
O O O O O O O O
O O O O
O O O O O O O O
```
This "dice pattern" can be extended to numbers greater than 6.
* The dots are arranged in a square of size k with k being the smalest *odd* integer that satisfies k\*k>=n
* the dots are added in layers for the center outwards
* one each layer the corners are added first
* then the midpoints of the sides, first on the vertical, then on the horizontal sides.
* for the remaining pairs of dots on each level you can choose any convenient order
*Due to there already being solutions a the time it was added, the next constraint is an optional additional requirement:*
* If the number of dots is divisible by 4 the pattern should be symmetric under reflections along the coordinate axes (through the center)
```
// one possible way to add the remaining dots
7: 8:
O O OOO
OOO O O
O O OOO
10: 12: 14: 16: 18: 20: 22: 24:
O O O O O O O O O O O O O O OOO O OOOOO
OOO OOO OOO OOO OOOO OOOOO OOOOO OOOOO
O O O O OO OO OO OO OO OO OO OO OO OO OO OO
OOO OOO OOO OOO OOOO OOOOO OOOOO OOOOO
O O O O O O O O O O O O O O O OOO OOOOO
26: 30: 32: 36: 40: 44:
O O O O O O O O O OO O OO OO O OO
OOOOO OOOOO OOOOO OOOOOOO OOOOOOO OOOOOOO
OOOOO OOOOO OOOOO OOOOO OOOOO OOOOOOO
OO OO OOO OOO OOO OOO OOO OOO OOO OOO OOO OOO
OOOOO OOOOO OOOOO OOOOO OOOOO OOOOOOO
OOOOO OOOOO OOOOO OOOOOOO OOOOOOO OOOOOOO
O O O O O O O O O OO O OO OO O OO
46: 48:
OOOO OO OOOOOOO
OOOOOOO OOOOOOO
OOOOOOO OOOOOOO
OOO OOO OOO OOO
OOOOOOO OOOOOOO
OOOOOOO OOOOOOO
OO OOOO OOOOOOO
```
Your task is to write a program of function, that given a positive integer as input outputs the dice pattern for that number.
## Rules:
* Trailing white-spaces are allowed
* Additional white-spaces at the start of each line are allowed, as long as all lines are indented by the same amount
* You can replace `O` by any non-whitespace character
* You may return a matrix of Truthy/Falsey values instead of printing the outputs
* Your program has to work for inputs at least up to 2601=51\*51, but your algorithm should work for arbitrarily large numbers
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") the shortest solution in bytes wins
---
[related](https://codegolf.stackexchange.com/questions/2602/draw-dice-results-in-ascii)
[Answer]
# Python 3 (194 ~~199~~ ~~210~~ bytes) -16 (- 5 thanks to Kevin)
My First golf!
Returns a int, array, where `len(arr) == side ** 2`
```
def f(n):
s=2*round(.5*n**.5-1)+3;q=s*s;d,e=[1]*q,~-s>>1;r=*({*range(s-2,0,-1)}-{0,e}),e,0;d[s*s//2]=n&1;q&=-2;b=(q-n+3)//2
for k in*r[:b//2],*(s*~i for i in r[:~-b//2]):d[k]=d[~k]=0
return d
```
Inputs: `n`
Output: returns 1d array containing pips
[Attempt it online!](https://ato.pxeger.com/run?1=PZExbsMgGIX3nAJ5iIBAYjuKVNkiV-jQEXkgBTco0Z8Y26raKL5IlyztFbr3Fr1NAade0A_fe_rfEx9f57duf4Lb7bPvav7w-6NNjWoMpJihVuTUnXrQeLmhQOlywzOyWJeNaGlbamaEzCrasIG3221WOkHxhToFLwa3PGcp8_Irv6TMXAkzLC219MbVKq8EzLOymQuelzuBGw6LNfHvM1SfHDogC9TJYheUjOKWDjYC6wHyYOARkULLQyW0HPyZzpAzXe8A6XuT72CBaImRMrZJQyt0dhY639CPStTj8Lzv4fBk340I7GgAKxIKB_a6t0eDVLDehUwJJYvJUzElp0tRRd2UN4Ji3JksHxNpK2ZAiyQhUTgSMuUiY_z_D_kD)
## Formatting code:
```
print(n, sum(d), *(list((map(int, d[i:(i+s)]))) for i in l(0, s*s, s)), sep="\n")
```
## Explanation:
Calculates the correct odd-square size to have a proper center
```
s=2*round(.5*n**.5-1)+3
```
Sets a variable keeping track of how many pips there are currently
```
q=s*s
```
Creates a 1D pip array, all filled with 1s, and sets e to center index
```
d,e=[1]*q,~-s>>1
```
Creates a tuple of which order to delete pips.
Goes from right right-left, center, corner. (-4 bytes)
```
r=*({*range(s-2,0,-1)}-{0,e}),e,0
```
Sets the center pip based on if it's odd
```
d[s*s//2]=n&1
```
Clears the last bit of q (sets it to even)
```
q&=-2
```
Stores number of pip-pairs to remove
```
b=(q-n+3)//2
```
Clears pips over the limit in the pip-array
```
for k in*r[:b//2],*(s*~i for i in r[:~-b//2]):d[k]=d[~k]=0
```
Returns d
```
return d
```
[Answer]
# JavaScript (ES7), 180 bytes
Returns a binary matrix.
```
n=>[...Array(w=n**.5-n/~n&~1),W=w/2].map((_,y,a)=>a.map((_,x)=>x-W|y-W?(g=k=>k--?g(k)|y==W+(A=[d=k<4?W:(k&4?k:-k)/8|0,-d,W,-W])[k&=3]&x==W+A[6>>k&3]:x%w&&y%w>0)(n-w*w+2*w&~1):n&1))
```
[Try it online!](https://tio.run/##XU/dboIwGL33KRoXaz9oi39bNvSD@BS9YGRpFImWFVONhcz56gzNdrOr83txzkFf9Gnj9sezsPW26HbYWUwyKeXaOd0yjzYI5LOw0c3S2xS4Qh/Ncvmpj4x98JZrwET/yaYXjVDXVqiUlWgwMUKkJTNwbRFVyNaYbdGsFqmKmaGL1MTCQPR6nXCx5YoLlUNmKM5z2tz76@wlSQyd53Ez8pS2I59MgFnhAx/OAn8fFFs6Beh2tWNVcSaWIJkue1ghWbz1JAyBfA0I2dT2VFeFrOqSWVj@c3a99zjhCCbEyUO9t2w8BumKY6U3BYtkVHJyuadD@TTMLjnAb@vdjoGE5IHLwXf3Aw "JavaScript (Node.js) – Try It Online") (with post-processing for readability)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 50 bytes
```
NθF﹪θ²POW⁻θLKA«↙≔ⅉηF⁸«P✳&⁶κ×O⌊⟦η÷⁺ιI§4062κ⁸⟧Mη✳&⁶κ
```
[Try it online!](https://tio.run/##fY6xasMwEIZn@ymEpxOoEEIIoZmcejHEqYcupXRw7Ut8RJYSS7ILJc@uSp469ZaD4/vv/9q@GVvdSO9LdXP25IYvHOHO9@lZjwwq3Tmp4S7YmnNWOWmpHklZyF6zwMw9SQwUKWcidER1sT3UiNdcSuBh2E@aVHpCeC70rI54tiGX5MbQRcE7cMH6eFjadgud/KkpaMTWklZwIDuTwVx1sBXsykPwjQY00USwYECDG@CjF6xUtqCJOoRaBi0S7KUxFnJbqg6/IdustutseRF@7Phn2PvYGiVD/J/KyD3Sh/eblX@a5C8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ
```
Input `n`.
```
F﹪θ²PO
```
If `n` is odd then print an `O` at the origin.
```
W⁻θLKA«
```
Repeat while more `O`s are required.
```
↙
```
Move to the bottom left corner of the next size of square.
```
≔ⅉη
```
Get the new offset (which is an eighth of the perimeter of this square).
```
F⁸«
```
Repeat to complete the perimeter of this square.
```
P✳&⁶κ×O⌊⟦η÷⁺ιI§4062κ⁸⟧
```
Output a number of `O`s depending on how many more are needed and which part of the perimeter is being drawn, but no more than the current offset.
```
Mη✳&⁶κ
```
Move to the next compass point without printing anything, which would throw off the count of `O`s written.
Example: When `n` is between `2` and `9`, the number of `O`s is added to the given digit according to the following pattern:
```
604
2 2
406
```
This means that `O`s will only be drawn on the horizontal midpoints if `n` is `8` or `9`, but will be drawn for lower values of `n` in the other positions.
] |
[Question]
[
We are probably all used to the English alphabetical order:
```
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
```
When we compare words in English for the sake of alphabetization we first compare the first letter, whichever word has the later first letter comes later. If they are the same we check the second letter and so on until we reach two letters that are different or one of the words runs out of letters to check in which case the word that ran out of letters comes first.
However in the [Kiowa language](https://en.wikipedia.org/wiki/Kiowa_language), things work a little differently. The letters are ordered based on phonetic principles so the order is completely different:
```
A AU E I O U B F P V D J T TH G C K Q CH X S Z L Y W H M N
```
You will notice also that certain digraphs such as `TH` are considered single letters.
We can use the same process for alphabetization with the Kiowa alphabetical order to get very different results.
We start by comparing the first *letter*, noticing that the digraphs `AU`, `TH` and `CH` each count as a single letter. So if we are comparing `AN` and `AUN`, `AN` comes first because `A` comes before `AU`, even though `N` comes after `U`.
If the first letters are the same we move onto the second letter repeating the process and so on until we reach two letters that are different or one of the words runs out of letters to check in which case the word that ran out of letters comes first.
## Task
You will take two non-empty strings as input and output the string which comes first in terms of the alphabetization described above.
You may alternatively choose to always output the string which comes last or both strings in either ascending or descending order as long as you do so consistently.
The input strings will only consist of a sequence of letters from the Kiowa alphabet as described above in upper case.
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
Here we output the string which comes earlier.
```
A N -> A
N A -> A
EEED EEEE -> EEEE
EVEV EVEV -> EVEV
AN AUN -> AN
CH CN -> CN
CH CA -> CA
CH KH -> KH
CH XA -> CH
```
---
Some simplifications are made here to serve the purpose of this challenge. Natural languages are wonderfully complex things and you should not take anything here as fact. However if you are interested I encourage you to learn more as the details can be quite interesting.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 42 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Σžn29£S•3ž¶`ÆNιÐßóθ£÷•.Is.•1ƶ<ð•u2ôžRlS:Sk
```
I/O as a pair of string, where the output is correctly ordered.
[Try it online](https://tio.run/##yy9OTMpM/f//3OKj@/KMLA8tDn7UsMj46L5D2xIOt/md23l4wuH5hzef23Fo8eHtQBk9z2I9IGV4bJvN4Q1ARqnR4S1H9wXlBFsFZ///H63kGOqnpKPk6KcUCwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/c4uP7sszsjy0OPhRwyLjo/sObUs43OZ3bufhCYfnH958bsehxYe3A2X0PIv1gJThsW02hzcAGaVGh7cc3ReUE2wVnP2/Vud/dLSSo5KOkp9SrE40kNQB8kAsV1dXFyAHSLlC@GGuYSA@iALxHcFKQyHanD2AHGdktiOC7e2BYEcAxWMB).
**Explanation:**
```
Σ # Sort the (implicit) input-pair by:
žn # Push "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
29£ # Only leave the first 29: "ABC...XYZabc"
S # Convert it to a list of characters
•3ž¶`ÆNιÐßóθ£÷•
# Push compressed integer 273531916594452580416824730457
.I # Get the 273...457'th permutation of the earlier string:
# (as list) "AaEIOUBFPVDJTbGCKQcXSZLYWHMNR"
s # Swap so the current string is at the top
.•1ƶ<ð• # Push compressed string "authch"
u # Converted to uppercase: "AUTHCH"
2ô # Split into parts of size 2: ["AU","TH","CH"]
žR # Push builtin "ABC"
lS # Converted to lowercase list: ["a","b","c"]
: # Replace the ["AU","TH","CH"] to ["a","b","c"]
S # Then split the string to characters
k # And get the index of each in the earlier alphabet
# (after which the sorted pair is output implicitly)
```
[See this 05AB1E tip of mine (sections *How to compress strings not part of the dictionary?* and *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•3ž¶`ÆNιÐßóθ£÷•` is `273531916594452580416824730456` and `.•1ƶ<ð•` is `"authch"`.
The `273531916594452580416824730456` is [generated (as 1-based index instead of 0-based) with the Jelly builtin `Œ¿`](https://tio.run/##y0rNyan8///opEP7////75jo6ukf6uQWEObiFZLk7uwdmBwRHOUTGe7h6xcEAA).
[Answer]
# [R](https://www.r-project.org), ~~99~~ ~~96~~ 95 bytes
```
\(a)a[order(chartr("AEIOUBFPVDJTtGCKQcXSZLYWHMN","1A-Z",gsub("(A)U|(T|C)H","\\L\\1\\2",a,,T)))]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY342M0EjUTo_OLUlKLNJIzEotKijSUHF09_UOd3ALCXLxCStydvQOTI4KjfCLDPXz9lHSUDB11o5R00otLkzSUNBw1Q2s0QmqcNT2AMjExPjExhjExRko6iTo6IZqamrFQa66maSQDzQWq8VPS1FRW0LVTcOQCi4FMdEQTc3V1dQEKAylXmAyIDZUMcw0DSYIomCSQDZF0BBsXirDEDyLuDHKeM1zYGUUYbr2zI5KwtwdM2NsDSTgCodoD4rkFCyA0AA)
Outputs the sorted strings.
**Explanation outline:**
* substitutes digraphs with their first letter converted to lowercase (with some PERL regex magic)
* translates Kiowa's order to `A-Z` with `1` prepended (we omit the `a` as it's in the right place and notice that there's no `R` in Kiowa language so we need only two additional characters: `1` and `a`)
* orders with the built-in string method (digits first).
[Answer]
# [Perl 5](https://www.perl.org/), 81 bytes
```
s/(A)U|(T|C)H/$1$2_/g;s/C_/Q_/g;y/EIOUBFPVDJTGCKQXSZLYWHMN/B-Z/;/ /;$_=$F[$`gt$']
```
[Try it online!](https://tio.run/##JclBC4IwGIDh@37FDoP0IB8FnaTDnJ@trJXk1IywDiGBpKSXwN/ecnR5eOHtHu9maUwPDnf16KSjcCWwOVtUUPs9iAoSWx/AzUEH0TELt@laxElxKnfnXO4VBF4JPlDwWbVi0YXd6oHNrsZwqoiinCBiSCeQYIYZtRA@Da2IkFT85dZYWgv@bbvh2b5649275gc "Perl 5 – Try It Online")
```
s/(A)U|(T|C)H/$1$2_/g; #turn all AU, TH, CH in input into A_, T_, C_
s/C_/Q_/g; #turn all C_ into Q_ since CH lies right after Q
y/EIOUBFPVDJTGCKQXSZLYWHMN/B-Z/; #remap all letters into letters of correct order
#...as recognized by gt below
/ /; #sets $` to converted string before space
#...and $' to converted string after space
$_ = $F[ #output first or second word in input array @F
$` gt $' #gt is true(1) if first converted word is
] #...greater than(gt) the second, otherwise
#...false(0), using 0 or 1 as index in array @F
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~282~~ 277 bytes
* -5 thanks to ceilingcat
Returns the lowest-sorted input. The digraphs are converted into `[0..2]` and the source string advanced, then the characters are compared; comparisons continue until the end of one of the strings or a mismatch.
```
#define a(a,b,c,d,e)a-c|*b-d||(a=e,b++),
*n="A0EIOUBFPVDJT1GCKQ2XSZLYWHMN";f(s,t,e,u,v,c,d)char*s,*t,*u,*v,c,d;{for(u=s,v=t,e=0;!e&&(c=*u++)&&(d=*v++);)a(c,u,65,85,48)a(d,v,65,85,48)a(c,u,84,72,49)a(d,v,84,72,49)a(c,u,67,72,50)a(d,v,67,72,50)e=index(n,c)-index(n,d);s=e<0?s:t;}
```
[Try it online!](https://tio.run/##ZZFtT8IwEMff71PUEU1bbwYJKFqrmTCZiqgR8PnFaDtZosOwh5gAnx3bKgkJTXp3/7ver@lVeB9CLJcVqeIkVSjCEYxAgARFIk/M6ciT8zmOuILR7i4Bh6bc9avB5e3g/OJu2L7q73da1/e1p4eX7vNjeNNzWYwzyEFBAaUBETGOpjQDmgMtgNocm8WTKS54BiXXR3mVbamdHSw4LfQlOpKcljpiJMJCgw4a0GxAvaml1NQ1aarNOhzWoH70X12TtvfQyEZ11buSiiepVD84BUG8VSgJy7g6qZ5lxzlbLCtJKj4LqdBJlstksjc@dZwkzdFXlKS4nCSSoJmDkHkhotnrO5@5vgtuT@8gCNrGDYOhdr5JtcJN0w87LvQG3e4CNMgumluQ6fD/QMEaaGBJ1pjqtYE8@ZbUDzdQeuLalMzRmbWRM0QLhvSswUzZnv6e6ofF2H3dzt4BGYv4qfVvqashBlQCirH9REKYs1j@Ag "C (gcc) – Try It Online")
[Answer]
# JavaScript (ES6), ~~112~~ 111 bytes
*Saved 1 byte thanks to @l4m2*
Expects `(a)(b)`. Returns the string which comes earlier.
```
a=>b=>(g=s=>s.replace(/AU|[TC]H|./g,([a,b])=>10+"AA0EIOUBFPVDJTT0GCKQC0XSZLYWHMN".search(b?a+0:a)))(a)<g(b)?a:b
```
[Try it online!](https://tio.run/##fc5BT8IwFAfwu5@C9NQG3OqV2JFSitXp1LgNhHB4nWVqFkZW44nvPlYWDU70Xd7/8Mv7v3f4BJtVb9uP8035Yuo1q4EFmgU4Z5YF1qvMtoDMYJ8nu2UsVmrn@fkAL2GgV4QFF7SPOKfy@j4ZTx/SyU0c0ysRPgo6f1rcPs/UXYQ8a6DKXrEeQZ8OgRCCgVzmWJMRDHWdlRtbFsYryhyvMeKIYBQhQnrt@H6Pn3VM5Az/30gpJ441WzrZGBd/sVSmB3bYLWtil/G2Mvl6zDVGXSSUQ@L7@QaJvxA/Rvw0CtURCtVpNP9xSdV7 "JavaScript (Node.js) – Try It Online")
### How?
Using the regular expression `/AU|[TC]H|./g`, the helper function `g` replaces each Kiowa letter in a given string with a 2-digit number between 10 and 40 according to their position in the following lookup string:
```
AA0EIOUBFPVDJTT0GCKQC0XSZLYWHMN
^ ^ ^ ^
10 20 30 40
```
where the letters `AU`, `TH` and `CH` are first turned into `A0`, `T0` and `C0` respectively.
The final result is found with a standard lexicographic comparison between `g(a)` and `g(b)`.
[Answer]
# [Python 2](https://docs.python.org/2/), 120 bytes
```
lambda*a:min(a,key=lambda s:map("@EIOUBFPVDJT?GCKQ#XSZLYWHMN".find,R(R(R(s,"AU","@"),"TH","?"),"CH","#")))
R=str.replace
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728oLIkIz_PaMHiNNuYpaUlaboWNytyEnOTUhK1Eq1yM_M0EnWyUyttIUIKxVa5iQUaSg6unv6hTm4BYS5eIfbuzt6ByhHBUT6R4R6-fkp6aZl5KTpBGiBYrKPkGKqko-SgpKmjFOIBZNmDWM4glrKSpqYmV5BtcUmRXlFqQU5icirU_p8FRZl5JRppGkqOSjoKSn5AhQpQoKzgyAWX9QPJOuKSdXV1dQEpANKuYDXKCiAmkoIw1zCwAhANVQBkIhQ4QiwIhTsAaL4fQhrkCwUlZ4TzlBWcMaS9PZCkvT3QpSMckXV7QAJgwQIIDQA)
Replaces each digraph with a special character, and then uses the indices of each character in the magic string `@EIOUBFPVDJT?GCKQ#XSZLYWHMN` to choose the lexicographically earliest of the two strings.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 54 bytes
```
⊟⌊EE²S⁺E⪫⪪⪫⪪⪫⪪ιAUI⁰THI¹CHI²⌕”B↗3∧=◧$×⁸}U‹⌕VψωB↑?υ”λ⟦⁰ι
```
[Try it online!](https://tio.run/##dYtPC4IwAMW/ythpwgL12slWNjVrpfaXDsOgBnMOnX395TzUqQcPHr/3Xv3iXd1yaS3rhDKItRrlQolmaFDO9eQQg0TpwRRmnDyR52HA5NBPXdoKhQothfkTBQYwquD4Ibw3yHdvWNIvCCZAfiB0IBbqgeAh8lfJrlrE7LhMy2BNsn14Lq6by4nmW4iBdNObj4G4e05zawkFGbWzt/wA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
² Literal integer `2`
E Map over implicit range
S Next input string
E Map over input strings
ι Current string
⪪ AU Split on `AU`
⪫ I⁰ Joined with `0`
⪪ TH Split on `TH`
⪫ I¹ Joined with `1`
⪪ CH Split on `CH`
⪫ I² Joined with `2`
E Map over characters
⌕ Find index of
λ Current character
”...” In compressed lookup table
⁺ Concatenated with
⟦ List of
⁰ Zero terminator
ι Current string
⌊ Take the minimum
⊟ Pop the original input string
Implicitly print
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~70~~ 68 bytes
```
%`^
$',
T`L`06ga27fu3birvx48j_nc59tmsq`.+,
05
1
cu
e
gu
k
O^`
!`\w+$
```
[Try it online!](https://tio.run/##K0otycxL/K@qEZyg8181IY5LRV2HKyTBJ8HALD3RyDyt1Dgps6iswsQiKz4v2dSyJLe4MEFPW4fLwJTLkCu5lCuVK72UK5vLPy6BSzEhplxb5f9/Rx0/Lj8dRy5XV1cXHSDhyuUa5hqmAyK4HIESoX5czh46zhDSEUR6e4DICEcA "Retina 0.8.2 – Try It Online") Takes input on separate lines but link is to test suite that splits on commas for convenience. Explanation:
```
%`^
$',
```
Duplicate each word.
```
T`L`06ga27fu3birvx48j_nc59tmsq`.+,
```
Convert the (uppercase) letters in the first copy to an extended alphabet of digits and lowercase letters that aren't magic in Retina's Transliterate command, sorted in Kiowa order.
```
05
1
cu
e
gu
k
```
Fix up the digraphs.
```
O^`
```
Sort in reverse order, so that the required word is now at the very end.
```
!`\w+$
```
Output just that word.
] |
[Question]
[
## Background
A **maximal domino placement** (MDP) on a rectangular grid is a non-overlapping placement of zero or more dominoes, so that no more dominoes can be added without overlapping some existing domino.
Alternatively, it can be thought of as a tiling using dominoes and monominoes (single square pieces) so that no two monominoes are adjacent to each other.
For example, the following are a few MDPs on a 3x3 grid: (`-`s and `|`s represent horizontal and vertical dominoes, and `o`s represent holes respectively.)
```
--| --| --o
|o| --| o--
|-- --o --o
```
There are exactly five MDPs on 2x3, and eleven on 2x4. Rotation and/or reflection of a placement is different from original unless they exactly coincide.
```
||| |-- --| o-- --o
||| |-- --| --o o--
|||| ||-- |--| |o-- |--o --||
|||| ||-- |--| |--o |o-- --||
--o| ---- o--| o--o ----
o--| o--o --o| ---- ----
```
In the graph-theoretical sense, an MDP is equivalent to a [maximal matching (maximal independent edge set)](https://mathworld.wolfram.com/MaximalIndependentEdgeSet.html) in the [grid graph](https://mathworld.wolfram.com/GridGraph.html) of given size.
## Challenge
Given the width and height of a grid, count the number of distinct maximal domino placements on it.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
[A288026](https://oeis.org/A288026) is the table of values read by antidiagonals.
```
w|h| 1 2 3 4 5 6
---+------------------------------
1 | 1 1 2 2 3 4
2 | 1 2 5 11 24 51
3 | 2 5 22 75 264 941
4 | 2 11 75 400 2357 13407
5 | 3 24 264 2357 22228 207423
6 | 4 51 941 13407 207423 3136370
```
[Answer]
# JavaScript (ES2021), 177 bytes
```
m=>n=>(g=i=>m*n>i?![-1,1,3,4,6].map(k=>g(i+1,(a[i/n|0]??=[])[i%n]=k)):S+=!a.some((r,y)=>r.some((c,x)=>~c?(c%2?a[y+c-2]?.[x]^c:r[x+c-5]^c)-2:r[x+1]<0|a[y+1]?.[x]<0)))(S=0,a=[])|S
```
Certainly can be golfed, but I don't know how. Terrible performance \$O(5^{mn})\$.
```
f=m=>n=>(g=i=>m*n>i?![-1,1,3,4,6].map(k=>g(i+1,(a[i/n|0]??=[])[i%n]=k)):S+=!a.some((r,y)=>r.some((c,x)=>~c?(c%2?a[y+c-2]?.[x]^c:r[x+c-5]^c)-2:r[x+1]<0|a[y+1]?.[x]<0)))(S=0,a=[])|S
console.log(`f(2,4) =`,f(2)(4))
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 34 bytes
```
Ẏ⁹ḟƑƇṭ€⁸Ṣ€ȯW)ẎQ
;þ;Z$,Ɲ€ẎW€çƬ$ṪLo1
```
[Try it online!](https://tio.run/##y0rNyan8///hrr5HjTsf7ph/bOKx9oc71z5qWvOoccfDnYuAjBPrwzWB8oFc1of3WUep6BybCxQECoQDqcPLj61RebhzlU@@4f/Dyw/vS7B2AGltmFtj7eADpHQrHjVusw4/1nVsk4q1QxCEs8naQQnI3KegYH2sy/3/fxMA "Jelly – Try It Online")
A dyadic link taking the dimensions as the left and right arguments and returning an integer. The TIO footer generates a 4x4 table similar to the one in the question; the argument for the footer is the size of the table to generate.
Full explanation to follow, but in brief this generates all possible dominoes and then builds all possible lists of those dominoes that don’t have any overlaps. It would be fairly straightforward to extend this to larger polyominoes (though the first part of the code would be a bit more complex); [here’s an initial attempt](https://tio.run/##y0rNyan8///hrr5HjTsf7ph/bOKx9oc71z5qWvOoccfDnYuAjBPrwzWB8oFcQOLQujSg/I75ECUQYevD@/Sto1R0js0FCoHUrAwHMg63Aw2MNzq05NBCkCoVoBBYeOOxNSoPd67y@f//v4mO8X9jAA).
[Answer]
# [Python 3](https://docs.python.org/3/), ~~250~~ ~~225~~ 219 bytes
```
from itertools import*
def f(w,h):
p=[[0]*w]
while h:h-=1;p=[n for r in p for n in product(*[[k%3//2*3,1,2][::k%3+1]for k in r])if('0'in str(n).replace('0, 0',''))<1>("1, 1"in str(n))]
return sum(1-(2in u)for u in p)
```
*-25 bytes thanks to @ovs*
*-6 bytes thanks to @Jakque*
[Try it online!](https://tio.run/##TY/BbsMgEETv/opVpArWJY2xpRzcpj@COEQJLig2oA3I6te7mEpVb7OzT7sz8TvZ4Idtmygs4JKhFML8BLfEQKlt7maCia/C4thAvCjV6XbVDazWzQbsaI8X@V58D1MgIHAeYpW@Sgr3fEu8VerxMpxOfTsIKXqtxrHMr1Lv5GMnSaObOOtY0c9E3OMbmThfb6aYAjomGEP8kJ/8IAXIwx@GJQyZlKkYeeHyyPuyy7hfzjUDbrte65er/zK8HDjXOuR84uq3Xg1t/0Nn1Lj9AA "Python 3 – Try It Online")
## How it works
We store each row as a list of `w` values from `[0,1,2,3]`, then transition from each row to the next while following constraints. Vertical constraints are determined by the table at the start of "Rules" in the code below. Horizontal constraints are determined by checking run lengths to ensure that two `0`s are not adjacent, and runs of `1`s are an even length.
Probably can be golfed through a wise relabelling, but that would not be fun.
```
def possible(w, h):
"""
0: empty; now you must place a domino
1: is a horizontal domino; now you have freedom
2: starts a vertical domino; must end it
3: ends a vertical domino; now you have freedom
Rules:
0 → 1,2
1 → 0,1,2
2 → 3
3 → 0,1,2
0 cannot be next to a 0
1 is horizontal domino (must have runs of even length)
"""
if h == 0:
yield [1 for _ in range(w)]
else:
for row in possible(w, h - 1):
for new_row in itertools.product(
*[{0: [1, 2], 1: [0, 1, 2], 2: [3], 3: [0, 1, 2]}[k] for k in row]
):
valid = True
for i, j in itertools.groupby(new_row):
L = len(list(j))
if i == 0 and L > 1:
valid = False
elif i == 1 and L % 2 == 1:
valid = False
if valid:
yield new_row
def num_possible(w, h):
return len([p for p in possible(w, h) if 2 not in p])
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~45~~ 24 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
pŒcạ/S$ÐṂŒPẎ€f€ẠȧQƑʋ@ƇƊL
```
A dyadic Link that accepts the two dimensions and yields the count.
**[Try it online!](https://tio.run/##ATkAxv9qZWxsef//cMWSY@G6oS9TJMOQ4bmCxZJQ4bqO4oKsZuKCrOG6oMinUcaRyotAxofGikz///8z/zQ "Jelly – Try It Online")** Note: It brute forces across the powerset of all possible dominoes so is incredibly inefficient.
### How?
```
pŒcạ/S$ÐṂŒPẎ€f€ẠȧQƑʋ@ƇƊL - Link: integer, n; integer m
p - (n) cartesian product (m) -> list of all coordinates
Œc - pairs -> all pairs of coordinates, once each
ÐṂ - keep those which are minimal under:
$ - last two links as a monad, f(pair of coordinates):
/ - reduce (the pair of coordinates) by:
ạ - absolute difference
S - sum
-> all possible dominoes, once each, as pairs of coordinates
Ɗ - last three links as a monad, f(all dominoes):
ŒP - power set -> all sets of dominoes (including overlaps)
Ẏ€ - tighten each -> coordinates used by each set of dominoes
Ƈ - filter keep those (potential sets) for which:
@ - with swapped arguments...
ʋ - ...last four links as a dyad, f(all dominos, potential set):
€ - for each (domino in all dominoes):
f - keep those (coordinates of the domino) which are in (the coordinates used by the potential set)
Ạ - all? (i.e only single empties / no touching monominoes?)
Ƒ - is (potential set) invariant under:
Q - deduplication? -> truthy if no overlaps
ȧ - (only single empties) logical AND (no overlaps)
L - length
```
[Answer]
# JavaScript (ES6), ~~169~~ 164 bytes
Expects `(width)(height)`.
```
w=>h=>(g=(o,x,y,d,q)=>{for(d=2;d--;)for(x=w-!d;x--;)for(y=h-d;y--;)(o[y]|o[y+d])&(m=3>>d<<x)||g(b=[...o],[0,d,h].map(i=>q=b[y+i]|=m));q|g[o+=o]?0:g[o]=++n})(n=[])|n
```
[Try it online!](https://tio.run/##NY3LboNADEX3/Qp3E2wNjNI23WQw@Ygs0SxIJjyqwPBSAYV8O51RlYUf1z6@/sl@s@HaV@0YNdbctpy3iZOSEywYbTiHS2jCjjh55LZHw5/KRJEiL2aeonej5pdeuIyMWrxEmy56dUkYTTus@StJTBzPtK4FXjiVUlodpnvnXWpZZy1WnHR8cQeVXrkmUt1apFaw1af90XWahWiehA2nmtZm8w9LYPhQUELMcHBVCILHG4DfDW4XBCFM/8zkmW9XXwzAAILBe7hj2HnQEXCCIArgCDlOhCXJ0Z7HvmoKJJJtZs5j1o94IOUsni6uthns/SbvtsDBTZ/bHw "JavaScript (Node.js) – Try It Online")
Or much faster for **167 bytes**:
```
w=>h=>(g=(o,x,y,d,q=g[o+o])=>{for(d=2*!q;d--;)for(x=w-!d;x--;)for(y=h-d;y--;)(o[y]|o[y+d])&(m=3>>d<<x)||g(b=[...o],[0,d,h].map(i=>q=b[y+i]|=m));g[o+o]=q||++n})(n=[])|n
```
[Try it online!](https://tio.run/##NY3NboMwEITvfYrNpdmtwWqb5mTWL5Ej8oHECVAFzJ8KKObZqVGUw@5odr7V/GZ/WX/pymaIa2ev643XkXXBGnNGF03RHNmo5Tx1whli/bi5Di1/f@xaZeNY0eYnHuOdVdPLz1zEVs2bRZfOxoclrKF3rPigtU2SibzP8cyplNKZKP0MLYWRVdZgybrlc3gojeeKSD27ufVeiHohrDk15Ot1ayqA4UtBAQnDT1AhCB5vAFvWh2y/j2B8MuPGHIO@GIAeBMMNR8KC5OBOQ1fWOZJsMnsasm7AI6kALmEuru7d/SrvLsc@XJf1Hw "JavaScript (Node.js) – Try It Online")
### How?
We use \$o[\:]\$ as an array of bitmasks. This array is split into two areas. An exact representation of all dominoes is stored in the first area (\$0\le y <h\$), whereas only the upper parts of the dominoes are stored in the second area (\$h \le y < 2h\$).
It means that a horizontal domino is stored the same way in both areas, but a vertical domino is stored as a single cell in the second area:
[](https://i.stack.imgur.com/cDxQ5.png)
This allows us to distinguish between two grids which are filled the same way but with different orientations of the dominoes.
The recursive function \$g\$ attempts to insert dominoes at all possible positions \$(x,y)\$ and with either orientation (horizontal when \$d=0\$, vertical when \$d=1\$), using 3 nested `for` loops:
```
for(d = 2; d--;)
for(x = w - !d; x--;)
for(y = h - d; y--;)
```
The collision test is:
```
(o[y] | o[y + d]) & (m = 3 >> d << x)
```
which is:
* `o[y] & (m = 3 << x)` when \$d=0\$
* `(o[y] | o[y + 1]) & (m = 1 << x)` when \$d=1\$
Whenever a new domino is inserted, we make a copy of \$o[\:]\$ in \$b[\:]\$ and do:
```
[ 0, // insert the upper part in area 1
d, // insert the lower part in area 1 if d = 1
// (or just overwrite the upper part if d = 0)
h // insert the upper part in area 2
]
.map(i => q = b[y + i] |= m)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~112~~ ~~94~~ 86 bytes
```
NθNη≔⁰ζ⊞υE²ζFυ«≔ωδF×θηF²«≔×⊕X²∨ληX²κε¿∧⎇λ﹪⊕κη‹κ×⊖θη¬&εΣι«≔Eι⁺μ×⁼λνε먪№υδ⊞υδ»»≧⁺¬δζ»Iζ
```
[Try it online!](https://tio.run/##VZHLTsMwEEXXzVfMciwZCbVLVqV0UYmWCPoDIXEbK47d@EEEqN8ePDbhYXkzM9fnXo3rtrK1qdQ07fQl@EPoX4XFgd0Vf@s21mvn5FnjLYePWJXBtRg47KsLLqkVeydjAQODz2LxLR45NHGwSJOj7IXDgUPLGKTOMmlncZ7vdG1FL7QXDZZmjOYR/2RRpXeMw0@zo0oQfiFPgGvd4FFYXdl3Eu9NE5T5h@sYMTg8Cuew45ANH8SvYmCzy8F4vJd@lE4QWHB4CT1KRieFnlPTAmRMpYLDfmZuh1ApRzF0ykjEtIgcleAbE7SnDTZEnNeZRdeCbiRnj2d5bj2SQ87VsPwH16K0MkI2lfNIPzBNK1hNN2/qCw "Charcoal – Try It Online") Link is to verbose version of code. Takes 30s on TIO to do 4×4 but smaller areas are quicker. Explanation:
```
NθNη
```
Input the width and height.
```
≔⁰ζ⊞υ
```
Start with zero placements.
```
⊞υE²ζ
```
Start enumerating placements with one that has no vertical or horizontal dominoes.
```
Fυ«
```
Loop through the placements.
```
≔ωδ
```
Assume that there are no possible dominoes.
```
F×θηF²«
```
Loop through all potential dominoes.
```
≔×⊕X²∨ληX²κε
```
Create a bitmask for this domino.
```
¿∧⎇λ﹪⊕κη‹κ×⊖θη¬&εΣι«
```
If this domino doesn't wrap around, and there is room to place a domino without overlapping any existing domino, then...
```
≔Eι⁺μ×⁼λνεδ
```
Add a domino in the appropriate orientation.
```
¿¬№υδ⊞υδ
```
Add this if it is a new placement.
```
»»≧⁺¬δζ
```
Increment the number if this is a maximal placement i.e. no dominoes were found.
```
»Iζ
```
Output the final number of maximal placements.
] |
[Question]
[
Inspired by [this question](https://puzzling.stackexchange.com/questions/93177/minigolf-solitaire/) on the puzzling stack exchange.
## Rules
Given 5 stacks of 5 cards with numbers from 1 to 7, output the moves needed to empty all stacks. A move is defined as the index of a column to pull the card off of, and a move is only valid if:
1. The stack is non-empty
2. The value of the card at the top of the stack is exactly 1 lower or higher than the value of the last card removed *from any of the stacks*. Note 1 and 7 wrap.
## Input
This challenge has loose input rules. You can use any format as input for the 25 numbers so long as the input is unambiguous among all possible inputs. The same token must be used for every instance of a card's representation. That is, if you use `2` to represent a `2`, you must use that everywhere in your input. But you may use `2` to represent `2` and `532jv4q0fvq!@$$@VQea` to represent `3` if this is somehow beneficial.
## Output
The list of moves needed to empty all stacks without getting stuck. This format is also loose, but it needs to represent a list of indices, where `0` is the leftmost stack.
Your program may assume that the input provided is solvable. That is, you may have undefined behaviour in the case of unsolvable input.
Note: If the input has multiple possible solutions, outputting at least 1 valid solution is acceptable
## Example/Test Case explained
Input: Representing the 5 stacks, where stack one is `5,5,3,2,6` with `5` being the top of the stack. Likewise for the other 4 stacks. Again, as stated in the question, this input format is loose and can be changed to facilitate the answer
```
5 5 3 2 6
2 4 1 7 7
4 2 7 1 3
2 3 3 1 4
4 6 5 5 1
```
Output: List of moves representing the order in which the cards are pulled off the stacks. I'll explain the result of the first 3 moves. The first 3 pops `2` off of the 4th stack (`2 3 3 1 4` stack). The second 3 pops `3` off of the same stack. And then the 1 pops the `2` off of the 2nd stack. If you follow these moves on the input you will end up with empty stacks
```
[3, 3, 1, 3, 1, 0, 4, 0, 4, 4, 2, 0, 2, 1, 1, 3, 2, 2, 0, 2, 3, 4, 0, 1, 4]
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), 86 bytes
This version is similar to the other one but takes advantage of the loose input format.
The cards are expected as follows:
\$[\text{Ace}, 2, 3, 4, 5, 6, 7] = [ 16, 37, 31, 91, 44, 41, 1 ]\$
```
f=(a,p,o='')=>o[24]?print(o):a.map((c,i)=>(v=c.pop())&&c.push((p^v)%3?v|f(a,v,o+i):v))
```
[Try it online!](https://tio.run/##LYzRasMwDEXf8xV6aSsxteDYTbaC2w8xHpjQsgw2myTTU/89ldshLrqHK93vJGkeprEse3lf15vHxIWz3@3In3NoXbyUafxdMNMpHX5SQRx41AzFD4eSCxJtt@r@5i/E8im0sRe537RGOL@NdBKidbnOC3hI4M@g0bNnqjA9rVQbwHQMtlcZhg@VcyrdBmIQ2IOJRNQ0tQxDAxA6btnykY@RK/bcs2HH7QutQq8X7oVO0er8p6b@cadpE2l9AA "JavaScript (V8) – Try It Online")
### How?
The numbers \$a\_n\$ representing the card values were chosen in such a way that:
* \$a\_i \bmod 3\neq0\$ for any \$i\in[1..7]\$
* \$(a\_i \operatorname{xor} a\_j)\bmod 3\neq0\$ for any \$i,j\in[1..7]\$ iff the \$i\$-th and \$j\$-th cards are consecutive
*Example:*
Here is what we get for an Ace (\$v=16\$):
```
previous card | p | p xor 16 | (p xor 16) mod 3
---------------+-----------+----------+------------------
none | undefined | 16 | 1
ace | 16 | 0 | 0
2 | 37 | 53 | 2
3 | 31 | 15 | 0
4 | 91 | 75 | 0
5 | 44 | 60 | 0
6 | 41 | 57 | 0
7 | 1 | 17 | 2
```
---
# [JavaScript (V8)](https://v8.dev/), ~~105 ... 92~~ 91 bytes
Takes input as an array of 5 columns with 1-indexed cards (Ace = 1, Two = 2, etc.). Prints all solutions as strings of 0-indexed columns.
```
f=(a,p,o='')=>o[24]?print(o):a.map((c,i)=>(v=c.pop())&&c.push((p-~v*6)%7%5?v:v|f(a,v,o+i)))
```
[Try it online!](https://tio.run/##LYxBCoMwEEX3nsKNOtOOghpNEVIPIi6CII3QJqjNqvTq6YhlNv/x/p9Fe71Nq3F77m8hzAo0ObIqy1Dd7VCJsXeree1gsdPFUzuAiQw78GoqnHWAmKac3tsDwOVff2kxkUnT@85/Zv7myV4NIoYZhiiOh5YqqqmhZqQDJUkqSVB1Ys0guSFOFIw139@Wx45attGI4Qc "JavaScript (V8) – Try It Online")
### How?
Given the previous card \$p\$ and the current card \$v\$, we compute:
$$k=((p+(v+1)\times6) \bmod 7) \bmod 5$$
The cards are consecutive iff \$k=0\$.
$$
\begin{array}{c|ccccccc}
&1&2&3&4&5&6&7\\
\hline
1&1&0&4&3&2&1&0\\
2&0&1&0&4&3&2&1\\
3&1&0&1&0&4&3&2\\
4&2&1&0&1&0&4&3\\
5&3&2&1&0&1&0&4\\
6&4&3&2&1&0&1&0\\
7&0&4&3&2&1&0&1\\
\end{array}
$$
We could, in theory, use \$v+(p+1)\times 6\$ just as well. But in the JS implementation, we want the result to be *NaN* (falsy) if \$p\$ is *undefined* (first iteration), which is why the bitwise operation (`-~v`) may only be applied to \$v\$.
### Commented
```
f = ( // f is a recursive function taking:
a, // a[] = input
p, // p = previous card (initially undefined)
o = '' // o = solution
) => //
o[24] ? // if o has 25 characters:
print(o) // we have a complete solution: print it
: // else:
a.map((c, i) => // for each column c at position i in a[]:
(v = c.pop()) // pop the last card v from this column
&& // abort if it's undefined
c.push( // otherwise:
(p - ~v * 6) // use our magic formula
% 7 % 5 ? // if it's not equal to 0 or NaN:
v // just push v back
: // else:
v | // because v belongs to the global scope,
// we need to use its current value right away
f( // do a recursive call to f:
a, // pass a[]
v, // set p = v
o + i // append i to o
) // end of recursive call
) // end of push()
) // end of map()
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~31~~ 28 bytes
# The 31 byte answer:
```
ṖÞZṪs5J€Ƒ
ŒṪŒ!ÇƇðœịIA%5=1ẠðƇḢZḢ
```
Accepts the stacks as a list of lists, `[s1, s2, s3, s4, s5]` where each stack has the first playable card on its left; returns a list of the 1-indexed stacks to from which to play, left to be played first.
Get a list of all ways by replacing `ḢZḢ` with `Ḣ€€`.
Since this is way too inefficient for a 5 by 5...
**[Try a 3 by 3 version online!](https://tio.run/##y0rNyan8///hzmmH50U93Lmq2NjrUdOaYxO5jk4C8o5OUjzcfqz98Iajkx/u7vZ0VDW1NXy4a8HhDcfaH@5YFAXE////j44211Ew01EwjuXSiQbSQJ4JiGmoo2AEEo0FAA "Jelly – Try It Online")** (`5` replaced by `3` in the code)
- this still takes ~45s and the code is \$O(n^2!)\$.
### How?
```
ṖÞZṪs5J€Ƒ - Link 1: check each stack used in order: list [[stackIndex1, cardIndex1],...]
Þ - sort by:
Ṗ - pop (i.e. sort by stackIndex values)
Z - transpose -> [[1,1,1,1,1,2,2,...,4,4,5,5,5,5,5], cardIndicesSortedByStack]
Ṫ - tail -> cardIndicesSortedByStack
s5 - split into chunks of five - i.e. split up by stacks
Ƒ - invariant under?:
€ - for each:
J - range of length (i.e. equals [[1,2,3,4,5],[1,2,3,4,5],...]?)
ŒṪŒ!ÇƇðœịIA%5=1ẠðƇḢZḢ - Main Link: list of lists of integers, M
ŒṪ - truthy multi-dimensional indices
Œ! - all permutations
Ƈ - filter keep those for which:
Ç - call last Link (1) as a monad
Ƈ - filter keep those for which:
ð ð - the dyadic chain - i.e. checkCardOrder(2d-indices, M)
œị - multidimensional index into M (vectorises)
I - deltas - i.e. [a,b,c,d,...]->[b-a,c-b,d-c,...]
A - absolute values
%5 - mod five
=1 - equals one
Ạ - all?
Ḣ - head - i.e. first valid 2d-inices pemutation
Z - transpose -> [stackIndices, cardIndices]
Ḣ - head -> stackIndices
...OR: Ḣ€€ - head each of each -> list of all such stackIndices
```
---
# The 28 byte answer:
Using the rule `You can use any format as input for the 25 numbers so long as the input is unambiguous among all possible inputs` we may choose seven numbers such that a new dyadic function which accepts a list of such numbers and returns a list with `1`s for adjacent neighbouring numbers and `0` for non-adjacent neighbouring numbers replaces the code `IA%5=1`. I chose the following:
```
^ƝẒ - list of numbers from [2,7,12,14,25,28,91] (mapping to [1,2,3,4,5,6,7])
Ɲ - neighbours
^ - XOR
Ẓ - is prime?
```
Here is a table of the XOR results:
```
^ | 2 7 12 14 25 28 91
---+----------------------
2 | 0 5 14 12 27 30 89
7 | 5 0 11 9 30 27 92
12 | 14 11 0 2 21 16 87
14 | 12 9 2 0 23 18 85
25 | 27 30 21 23 0 5 66
28 | 30 27 16 18 5 0 71
91 | 89 92 87 85 66 71 0
```
And if we check primality:
```
^Ẓ | 2 7 12 14 25 28 91
---+----------------------
2 | 0 1 0 0 0 0 1
7 | 1 0 1 0 0 0 0
12 | 0 1 0 1 0 0 0
14 | 0 0 1 0 1 0 0
25 | 0 0 0 1 0 1 0
28 | 0 0 0 0 1 0 1
91 | 1 0 0 0 0 1 0
```
Here is **[the equivalent to the 3 by 3 version above](https://tio.run/##y0rNyan8///hzmmH50U93Lmq2NjrUdOaYxO5jk4C8o5OUjzcfqz98Iajkx/u7o47NvfhrkkPdy04vOFY@8Mdi6KA@P///9HRloY6CkYWOgqGRrFcOtEgFkjE0ATEUzDSUVAwB8vFAgA "Jelly – Try It Online")**
---
Many other mappings work with this code, e.g.:
```
[1, 2, 3, 4, 5, 6, 7] : [2, 5, 6, 13, 16, 37, 39]
```
or
```
[1, 2, 3, 4, 5, 6, 7] : [7, 12, 17, 18, 21, 32, 34]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 43 bytes
```
““”;WA;"ị@Ṫ;ɗ¥¥ⱮT>Ƈ2Ɗ$€ẎIḢAfƑʋƇ1,6Ʋ25¡2ịⱮ_3
```
[Try it online!](https://tio.run/##y0rNyan8//9Rwxwwmmsd7mit9HB3t8PDnausT04/tPTQ0kcb14XYHWs3Otal8qhpzcNdfZ4PdyxyTDs28VT3sXZDHbNjm4xMDy00AmoCqow3/n@4PfL//2iuaDMdIx1jHVMd01gdrmhzHXMdQx0THSMQxxjINAfKmoA4JkCOMRCCZQxB6nXMgDJcsQA "Jelly – Try It Online")
A monadic link taking a list of lists of integers (representing the stacks) and returning a list of lists of integers (representing the possible sequences of moves).
## Explanation (method)
Works iteratively on 1 or more lists, each of which contains the sequence of cards so far at index 1, the sequence of stacks used at index 2 and the current stacks at positions 3 through 7. As such, the stacks are 3-indexed, and get changed to 0-indexing at the end. At each iteration, all possible moves are created, and then the sequence of cards is tested to check that the differences are all either -1, -6, 1 or 6. All valid moves are kept, and the next cycle of the loop is processed.
## Explanation (code)
```
““”; | Prepend two empty lists
W | Wrap in a further list
Ʋ25¡ | Repeat the following 25 times:
$€ | - For each current working list:
Ɱ Ɗ | - Using each of the following as the right argument:
T | - Truthy indices (effectively here the indices of non-empty lists)
>Ƈ2 | - Keep only those greater than 2
¥ | - ... do the following as a dyad:
A | - Absolute (used here for the side effect of copying the list)
¥ | - Following as a dyad:
;" ɗ | - Concatenate to following, using zipped arguments:
ị@ | - Index into list using reversed arguments
Ṫ | - Tail, popping from list
; | - Concatenate (to the list index)
Ẏ | - Join outer lists together
ʋƇ | - Keep those lists where the following is true:
I | - Increments (vectorises)
Ḣ | - Head
A | - Absolute
fƑ 1,6 | - Invariant when filtered to only contain 1s and 6s
2ịⱮ | 2nd sublist of each (i.e. the sublist containing the list indices used)
_3 | Minus 3
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~140...121~~ 119 bytes
```
->n{w=[*0..4].product;w.find{|x|5.times{|j|((n[j][x.count j]||99)-n[a=x[-1]][~-x.count(a)])**2%35==1&&w<<x+[j]};x[24]}}
```
[Try it online!](https://tio.run/##LY1BCoMwFESv0k1F7TdUTRTR9CKfv7BaQaFRrGKKsVe3qZTZzLxhmHG@v/dG7sFNrYtE/8oYJzaMfT1XU76wplX1arQRbGqfj9dqOuO6CjtCzap@VtOpI2OyzAsUllJjEBLhJ/iXbumR5/vRORZSho6zFIW@2PGWa4w4bds@nBpEFCAghggSAoyAQwgppNZzy1Kb4oPHViHwgyfw29gz2r8 "Ruby – Try It Online")
### How:
Breadth-first search:
* initialize the solution vector with the single cards on top of the stacks. `(w=[[0],[1],[2],[3],[4]])`
* for every solution in the vector, check the possible next step. For example, `[0]` could expand to `[0,2]` or `[0,4]`. Append these new solutions to the vector.
* now check if the solution has 25 elements: if it does, it's complete, and we can stop.
The check could be more efficient, but since I only save the stack numbers, I have to get the cards from the stacks on every iteration. Changing the stack in a non-recursive solution is out of the question, and saving the card numbers would require more code.
] |
[Question]
[
**This question already has answers here**:
[Do you want to code a snowman?](/questions/49671/do-you-want-to-code-a-snowman)
(29 answers)
Closed 4 years ago.
Today is Halloween and it's time to carve some pumpkins!
```
&
((^.^))
```
Given an input integer, string, list of integers, etc., output the corresponding pumpkin. The input will always be of the form `Stem, Eyes, Mouth, Width`. For example, `2331` would be a valid input.
The pumpkin takes the form:
```
S
((EME))
```
where `S` is the stem, `E` are the eyes, `M` is the mouth, and the parens form the body.
### Definitions
Stem:
`0` for a curl `&`
`1` for a straight `|`
`2` for a slant left `\`
`3` for a slant right `/`
Eyes:
`0` for angled `^`
`1` for small dots `.`
`2` for medium dots `o`
`3` for large dots `O`
Mouth:
`0` for angled `v`
`1` for small dot `.`
`2` for medium dot `o`
`3` for large dot `O`
Width:
`0` for a skinny pumpkin (only one pair of parens)
`1` for a fat pumpkin (two pairs of parens)
### Examples
```
0011
&
((^.^))
3100
/
(.v.)
2331
\
((OOO))
1200
|
(ovo)
```
## Rules
* Input/output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963).
* You can print it to STDOUT or return it as a function result.
* Either a full program or a function are acceptable.
* Any amount of extraneous whitespace is permitted, provided the characters line up appropriately.
* You must use the numbering and ordering of the pumpkin carvings as they are described above.
* [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]
# [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 56 bytes
```
L,"&|\/^.oOv.oO ((("4$Tz£:BF"("+@32C3*$+Bh$2D-1A:1+")"*J
```
[Try it online!](https://tio.run/##S0xJKSj4/99HR0mtJkY/Ti/fvwyIFTQ0NJRMVEKqDi22cnJT0lDSdjA2cjbWUtF2ylAxctE1dLQy1FbSVNLy@q@Sk5iblJKoYGgXbaRgDISGsVz@XEiihgpGCgYKBkDR/wA "Add++ – Try It Online")
Add++ is not the best at string manipulation challenges
## How it works
We create an lambda function that takes a single argument - a list of integers - and outputs the final pumpkin.
```
L, - Define our function. Takes in a four element list e.g. [0 0 1 1]
STACK = [[0 0 1 1]]
"&|\/^.oOv.oO (((" - Push this string STACK = [[0 0 1 1] '&|\/^.oOv.oO (((']
4$T - Split it into 4 pieces STACK = [[0 0 1 1] ['&|\/' '^.oO' 'v.oO' ' (((']
z - Zip the lists together STACK = [[['&|\\/' 0] ['^.oO' 0] ['v.oO' 1] [' (((' 1]]]
£: - Index into each string STACK = [['&' '^' '.' '(']]
BF - Flatten the stack STACK = ['&' '^' '.' '(']
"("+ - Append a "(" to last element STACK = ['&' '^' '.' '((']
@ - Reverse stack STACK = ['((' '.' '^' '&']
32C3*$+ - Prepend 3 spaces to stalk STACK = ['((' '.' '^' ' &']
Bh - Output stack with newline STACK = ['((' '.' '^']
$2D - Push from under STACK = ['((' '^' '.' '^']
-1A:1+ - Add one the the last argument STACK = ['((' '^' '.' '^' 2]
")"* - Repeat ")" that many times STACK = ['((' '^' '.' '^' '))']
J - Join together STACK = ['((^.^))']
- Implicitly output
```
[Answer]
# JavaScript (ES6), 78 bytes
```
(s,e,m,w)=>` ${'&|\\/'[s]}
${' ('[w]}(${(e='^.oO'[e])+'v.oO'[m]+e})`+' )'[w]
```
[Try it online!](https://tio.run/##dYtNDoIwEIX3nGIWxOmkI/Kzxit4AKiBYDESoMYaWCBnr5WdC/I27@X7XldPtW1ej@f7OJqbdm3uhGXNA8@UnysACBc8fMryhIVVa@AXCCxmtYpwETrHa2QuWGhFEqetDkrqlSqJQD/PNWa0ptdRb@6iFTHHnHBCIAHLESn4x5mHXtnDKWc@u@@E0@1N7gs "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~96~~ ~~87~~ ~~86~~ 84 bytes
```
lambda s,e,m,w,a="^.oO":" "*(2+w)+"&|\/"[s]+"\n"+"("*-~w+a[e]+"v.oO"[m]+a[e]+")"*-~w
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaFYJ1UnV6dcJ9FWKU4v31/JSklBSUvDSLtcU1tJrSZGXym6OFZbKSZPSVtJQ0lLt65cOzE6FShSBlIcnRsL5WqC5f4XFGXmlWikaRjoGIKgpiYXTMQYyDfQMUASMdIxBkJkNYY6RhA1/wE "Python 3 – Try It Online")
Thanks to:
- [@79037662](https://codegolf.stackexchange.com/users/89930/79037662) for saving me 2 bytes
[Answer]
# [Wren](https://github.com/munificent/wren), ~~98~~ 90 bytes
A naive approach. I could have used a lookup table, it golfs out 8 bytes.
```
Fn.new{|a,b,c,d|" "*3+"&|\\/"[a]+"\n"+" ("[d]+"("+"^.oO"[b]+"v.oO"[c]+"^.oO"[b]+")"*(d+1)}
```
[Try it online!](https://tio.run/##TY2xDsIgFAB/hbzBQHlBGmdXVwdHqAkFTEzqa4K1xIjfjujkdnfL5RSpri6xy4M829cDKYr5VRyO6DEUYNDtJGyKtVswbpBgCSQwDiY04Y3Paj6CGZutP/LDfxPQ8SB78a6n532JN5XTdYn8u1PeTRPXqLFHLUT9AA)
# [Wren](https://github.com/munificent/wren), ~~148~~ 144 bytes
An even worse solution, yet I'd like to share it. Does a bunch of replaces on the specified string
```
Fn.new{|a,b,c,d|" S\nW(EME)w".replace("S","&|\\/"[a]).replace("W"," ("[d]).replace("w"," )"[d]).replace("E","^.oO"[b]).replace("M","v.oO"[c])}
```
[Try it online!](https://tio.run/##Xc4xDsIgFADQq5A/GEh@sLo74tY4MHSAmlCKiUlFg7XEiGdH6mLj@qYXg/N5MoGcHt6SXd577l18JYMdWuwTEEKk9g0VtWAReHC3wVhHQQLCKmm9BmVa9vOmOKGg@iXGGdkfioJHfj2A6pZcF56@bFv2zvJ5H92Fx3AeHZ2T3JphoBvcYoUVY/kD)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 28 bytes
```
↙§&|\/N§^.oON←§v.oON←←×(⊕N‖B
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMPKJb88zyc1rURHwbHEMy8ltUJDSa0mJkZfSUfBM6@gtMSvNDcptUhDU1PTmguiBa4uTi/fH7cyKzRTy3Co9s0vS4UoRtcakpmbWqyhpAHWlVyUmpuaV5KaooFmAlBXUGpaTmpyiVNpSUlqUVpOpYam9f//xlyGXAZcBv91y3IA "Charcoal – Try It Online") Link is to verbose version of code. Taking the inputs in a better order would save 2 bytes. Explanation:
```
↙§&|\/N
```
Input the stem and output the appropriate character, then move to the left eye.
```
§^.oON
```
Input the eyes and output the appropriate character.
```
←§v.oON←
```
Input the nose and output the appropriate character, then move to the left of the left eye.
```
←×(⊕N
```
Input the width and output the appropriate number of `(`s.
```
‖B
```
Reflect to complete the pumpkin.
[Answer]
# [PHP](https://php.net/) (7.4), 91 bytes
Generates the output string using a template string and `strtr` array replacement mode.
```
fn($s,$e,$m,$w)=>strtr(' 0
3(121)4',['&|\/'[$s],'^.oO'[$e],'v.oO'[$m],' ('[$w],' )'[$w]])
```
[Try it online!](https://tio.run/##NY3BDoIwDIbve4qGLG5LKjLwhuAj@ACACSFb4CAQRvSgPjuWge3l@/u3f8d2XC7XsR0Z4zZbbC@5Q26QP5C/VJa7eZonKQAgYonUsVZngYU4fMqTKLirUNzD4UZoCJ8bPghBErxWUB4qtaT0YjZudpBBwSixiDBCjbpCrxJimuwqxoT672mMd6@iGDtMpm5akHte7YB3kOXgtYL3egOdpYVOgWnaAYKyL/vjVisGqd/xHrcyDMPtNmXf5Qc "PHP – Try It Online")
---
# [PHP](https://php.net/) (7.4), 93 bytes
Generates the output string as it goes on.
```
fn($s,$e,$m,$w)=>' '.'&|\/'[$s].'
'.' ('[$w].'('.($y='^.oO'[$e]).'v.oO'[$m]."$y)".' )'[$w];
```
[Try it online!](https://tio.run/##NY1NbsIwEIX3PsUoGtW2NEwJLIPhCD1A4koI2UoW@RFGIER79nRwUnvzvnlv3kztNB9OUzsphdHNcTCYCANhT/iw7qgBQLP@@Gk@dY3Js1aCYAQeAkazwafT3zx@ySh4y/q@6N5zgU9bSNrmdDVXcuQW0i2Bg1pJc72lLZVUesq0Fy2TlXa0l//vlbRbPS81cbyG86UFs/adE2AH7giZLbzeO9BFCXQWwqUdoWiGZtgs7y2LKmeyh9Ew87Jbqd/5Dw "PHP – Try It Online")
[Answer]
# [Icon](https://github.com/gtownsend/icon), 121 bytes
```
procedure f(s,e,m,w)
return map(" s\nw(eme)u","semwu","&|\\/"[s+1]||"^.oO"[e+1]||"v.oO"[m+1]||" ("[w+1]||" )"[w+1])
end
```
[Try it online!](https://tio.run/##XY2xDoMwDER3vsLyUDmq1RL4kH4AtBICIzEkoASahX@noWFokYe7dz7phna02za5sZVucQI9eRY2HFTmZF6cBdNMhADgaxtIjKgFGb2YsOtlres7Vv6qn@uKr9v4wEoSvL9gEgBhFQ6rklWZ2O5n2TSDJZXFJQhumIV6yjlnzVr9p2XM4ueUFlzGO3c1F0d3H/sA "Icon – Try It Online")
[Answer]
# [Red](http://www.red-lang.org), 135 bytes
```
func[s e m w][a:["&|\/""^^.oO""v.oO"" ("" )"]rejoin[" "a/1/(s + 1) lf a/4/(t: w + 1) "("a/2/(u: e + 1) a/3/(m + 1) a/2/:u ")"a/5/:t]]
```
[Try it online!](https://tio.run/##TYzNCsIwEITvfYphD5IiuKbVS15C8BpTCDaBirbSH3vx3eNSqciyy8w3w/ahTudQW5dl0aQ4tVc7IOCB2VlvLG3eFyaqql13InotF0o2J9eHW9e0lgCQZ81qwBY6xz3C84HVaDB/CSkpFKwmI68X4rlk9Vh1wWYC5VI6shmdS8@@aUdE7GU0dLb6Upywny@ElH@5FiJ5@gA "Red – Try It Online")
] |
[Question]
[
# Introduction
It is somewhat like [DVORAK Keyboard layout](https://codegolf.stackexchange.com/questions/22704/dvorak-keyboard-layout) , but MUCH harder.
Let's talk about the Korean keyboard first. As you can see in [Wikipedia](https://en.wikipedia.org/wiki/Keyboard_layout#Hangul_.28for_Korean.29), there is a Kor/Eng key to change between Korean and English key sets.
Koreans sometime type wrong : they attempt to write in Korean on a qwerty keyboard or in English on a two-set keyboard.
So, here's the problem : if given Korean characters typed in two-set keyboard, convert it to alphabetic characters typed in qwerty keyboard. If given alphabetic characters typed in qwerty, change it to two-set keyboard.
# Two-set Keyboard
Here is the two-set keyboard layout :
```
ㅂㅈㄷㄱㅅㅛㅕㅑㅐㅔ
ㅁㄴㅇㄹㅎㅗㅓㅏㅣ
ㅋㅌㅊㅍㅠㅜㅡ
```
and with shift key :
```
ㅃㅉㄸㄲㅆㅛㅕㅑㅒㅖ
```
just the top row changes while the others do not.
# About Korean Characters
if it ended here, it could be easy, but no.
When you type
```
dkssud, tprP!
```
output is not shown in this way:
```
ㅇㅏㄴㄴㅕㅇ, ㅅㅔㄱㅖ!
```
but in this way :
```
안녕, 세계!(means Hello, World!)
```
and it makes things much harder.
Korean Characters separate into three parts : 'Choseong(consonant)', 'Jungseong(Vowel)', and 'Jongseong(consonant in the end of syllable : can be blank)', and you have to separate it.
Fortunately, there is way to do that.
# How to separate
There are 19 Choseong, 21 Jungseong, and 28 Jongseong(with blank), and 0xAC00 is '가', first character of the Korean characters. Using this, we can separate Korean characters into three parts. Here is the order of each and its position in two-set keyboard.
choseong order :
```
ㄱㄲㄴㄷㄸㄹㅁㅂㅃㅅㅆㅇㅈㅉㅊㅋㅌㅍㅎ
r R s e E f a q Q t T d w W c z x v g
```
jungseong order :
```
ㅏㅐㅑㅒㅓㅔㅕㅖㅗㅘㅙㅚㅛㅜㅝㅞㅟㅠㅡㅢㅣ
k o i O j p u P h hk ho hl y n nj np nl b m ml l
```
jongseong order :
```
()ㄱㄲㄳㄴㄵㄶㄷㄹㄺㄻㄼㄽㄾㄿㅀㅁㅂㅄㅅㅆㅇㅈㅊㅋㅌㅍㅎ
()r R rt s sw sg e f fr fa fq ft fx fv fg a q qt t T d w c z x v g
```
Let's say `(unicode value of some character) - 0xAC00` is `Korean_code`,
and index of Choseong, Jungseong, Jongseong is `Cho`, `Jung`, `Jong`.
Then, `Korean_code` is `(Cho * 21 * 28) + Jung * 28 + Jong`
Here is the javascript code which separate Korean character [from this Korean website,](http://dream.ahboom.net/entry/%ED%95%9C%EA%B8%80-%EC%9C%A0%EB%8B%88%EC%BD%94%EB%93%9C-%EC%9E%90%EC%86%8C-%EB%B6%84%EB%A6%AC-%EB%B0%A9%EB%B2%95) for your convenience.
```
var rCho = [ "ㄱ", "ㄲ", "ㄴ", "ㄷ", "ㄸ", "ㄹ", "ㅁ", "ㅂ", "ㅃ", "ㅅ", "ㅆ", "ㅇ", "ㅈ", "ㅉ", "ㅊ", "ㅋ", "ㅌ", "ㅍ", "ㅎ" ];
var rJung =[ "ㅏ", "ㅐ", "ㅑ", "ㅒ", "ㅓ", "ㅔ", "ㅕ", "ㅖ", "ㅗ", "ㅘ", "ㅙ", "ㅚ", "ㅛ", "ㅜ", "ㅝ", "ㅞ", "ㅟ", "ㅠ", "ㅡ", "ㅢ", "ㅣ" ];
var rJong = [ "", "ㄱ", "ㄲ", "ㄳ", "ㄴ", "ㄵ", "ㄶ", "ㄷ", "ㄹ", "ㄺ", "ㄻ", "ㄼ", "ㄽ", "ㄾ","ㄿ", "ㅀ", "ㅁ", "ㅂ", "ㅄ", "ㅅ", "ㅆ", "ㅇ", "ㅈ", "ㅊ", "ㅋ", "ㅌ", "ㅍ", "ㅎ" ];
var cho, jung, jong;
var sTest = "탱";
var nTmp = sTest.charCodeAt(0) - 0xAC00;
jong = nTmp % 28; // Jeongseong
jung = ((nTmp - jong) / 28 ) % 21 // Jungseong
cho = ( ( (nTmp - jong) / 28 ) - jung ) / 21 // Choseong
alert("Choseong:" + rCho[cho] + "\n" + "Jungseong:" + rJung[jung] + "\n" + "Jongseong:" + rJong[jong]);
```
# When assembled
1. Note that `ㅘ`, `ㅙ`, `ㅚ`, `ㅝ`, `ㅞ`, `ㅟ`, `ㅢ` is a combination of other jungseongs.
```
ㅗ+ㅏ=ㅘ, ㅗ+ㅐ=ㅙ, ㅗ+ㅣ=ㅚ, ㅜ+ㅓ=ㅝ, ㅜ+ㅔ=ㅞ, ㅜ+ㅣ=ㅟ, ㅡ+ㅣ=ㅢ
```
2. Choseong is necessary. That means, if `frk` is given, which is `ㄹㄱㅏ`, it can change in two way : `ㄺㅏ` and `ㄹ가`. Then, you have to convert it into a way which has choseong. If `jjjrjr` given, which is `ㅓㅓㅓㄱㅓㄱ`, leading `ㅓ`s don't have anything that can be choseong, but the fourth `ㅓ` has `ㄱ` that can be choseong, so it's changed into `ㅓㅓㅓ걱`.
Another example : `세계`(`tprP`). It can be changed to `섹ㅖ`(`(ㅅㅔㄱ)(ㅖ)`), but because choseong is necessary, it's changed into `세계`(`(ㅅㅔ)(ㄱㅖ)`)
# Examples
input 1
```
안녕하세요
```
output 1
```
dkssudgktpdy
```
input 2
```
input 2
```
output 2
```
ㅑㅞㅕㅅ 2
```
input 3
```
힘ㄴㄴ
```
output 3
```
glass
```
input 4
```
아희(Aheui) is esolang which you can program with pure Korean characters.
```
output 4
```
dkgml(모뎌ㅑ) ㅑㄴ ㄷ내ㅣ뭏 조ㅑ초 ㅛㅐㅕ ㅊ무 ㅔ갷ㄱ므 쟈소 ㅔㅕㄱㄷ ㅏㅐㄱㄷ무 촘ㄱㅁㅊㅅㄷㄱㄴ.
```
input 5
```
dkssud, tprP!
```
output 5
```
안녕, 세계!
```
input 6
```
ㅗ디ㅣㅐ, 째깅! Hello, World!
```
output 6
```
hello, World! ㅗ디ㅣㅐ, 째깅!
```
**Shortest code wins.**(in bytes)
# New rule for you convenience
You can dismiss characters like `A` which do not have its counterpart in two-set keyboard. so `Aheui` to `Aㅗ뎌ㅑ` is OK. But, if you change `Aheui` to `모뎌ㅑ`, you can get -5 point, so you can earn 5 bytes.
You can separate two jungseongs(like `ㅘ` to `ㅗ+ㅏ`). like `rhk` to `고ㅏ`, or `how` to `ㅗㅐㅈ`. But if you combine it(like `rhk` to `과` or `how` to `ㅙㅈ`), you can earn additional -5 points.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~296~~ 264 bytes
```
Ẏœṣjƭƒ
“ȮdȥŒ~ṙ7Ṗ:4Ȧịعʂ ="÷Ƥi-ẓdµ£f§ñỌ¥ẋaḣc~Ṡd1ÄḅQ¥_æ>VÑʠ|⁵Ċ³(Ė8ịẋs|Ṇdɼ⁼:Œẓİ,ḃṙɠX’ṃØẠs2ḟ€”A
“|zƒẉ“®6ẎẈ3°Ɠ“⁸)Ƙ¿’ḃ2’T€ị¢
¢ĖẈṪ$ÞṚƊ€
3£OŻ€3¦ŒpFḟ0Ɗ€J+“Ḥœ’,ƲyO2£OJ+⁽.[,Ʋ¤y¹ỌŒḊ?€µ¢ṖŒpZF€’ḋ588,28+“Ḥþ’Ʋ0;,ʋ/ṚƲ€ñṣ0ḊḢ+®Ṫ¤Ɗ;ṫ®$Ɗ¹Ḋ;⁶Ṫ⁼ṁ@¥¥Ƈ@¢ṪẈṪ‘;Ʋ€¤ḢƲ©?€ṭḢƲF2£żJ+⁽.[Ɗ$ẈṪ$ÞṚ¤ñỌ
```
[Try it online!](https://tio.run/##TZJNbxJBGMfvfIrFcNB0VQRfSIlaLxy8VBNjjB6McTVaSdoUjcEQwxbW1sUYhRbBaCXsLsbakkpTnQHU5Fl2QvkWz3Jr@Q7rs2sPPc3M8/L//@aZmXuQTmc9D7tvnQpyY05siXLIzX8atpWh5ZRfIq9fQF6dPjtsYa9k14CPlqSLx@xfwnx8ErsVBXbBeAhf7R/YewMWdkv3kBn3qa@hnLGLyLTrYN21W5du2u9HjZyr7g502Dk@qCZIjqozOeSvlL2@q/annTIJDrZlZAWy3WvccvN15AW7ht1GJobsi7u06eY/X/H5ci8EVb@mHbTPEz12V@KwLSoUcFV2QtTgr9/NCjFablAj2UEzBM1BlUqRb0TsdeQfhU6pUByMWadHuzi0nPJCiqyiQebqFOkhMx3Srcuik52NUSlF1d@n7tAZzCxwujiRM/0yNdA0mjQuErmdCmgJoXQukZBjiUMp@w8FRSealEel0z5Bh@poetyIkgay5hS0CQ9MoSeRf4d2ROjkwfSkq/6kBA0KuToDFlhiecZ32/h/ITdfSwZiYJIKsX3zgZBvBacUgTv9Q3KhR44OAczg9TzPG2sfDlZXx5ox1t5Jk/XNfa6FpUf0Real5/OLaSUsTdZWDrQ1WZoU2f5OMSwpTzKZZ4osPV1YvPYP "Jelly – Try It Online")
A full program that takes a string as its argument and returns a string (which is implicitly printed). This works in three passes: first it converts all Korean characters to lists of code points for the Latin letters. Then it identifies and builds the compound Korean characters. Finally, it turns any remaining stray Latin letters to the Korean equivalent. Note that other characters and Latin letters that don’t appear in the spec (e.g. `A`) are left alone.
If conversion to lower case of capital letters outside spec is needed, this can be done [at a cost of an additional 10 bytes](https://tio.run/##ZVDbahNRFH3PV0SZB6Vak4loaaiNCHkQoQjFiD5IMRWsoRXzECqpJI2XdiIFE0gT8RIyMxEvhBoJzplEhX0yhzR/sedHxjVtHwRh5pzN2mvttc5eW83lNoPAL72b9LIT26s9Y9G6zKIxf3HS5WFVNklMt6MLp@VPZT08z249SwMyH9An@Z2Hr8lmt7rCjnkfunY2Lp@z8@Im2fdk98ot@WbaLvrlwdigH2fGjTmMAztfZPEyezjyy6N5r4aB44Nz7FRge9i@7ZdaLCqyyW47r7Pz0d/@5pfeX40gX/GpAnsXFfUusbvH7k6CDlQdgF92zqom/QnVTkXHtQwh7KgToc64oaO8oQz5gcVbZaAFlMUXfKgLKRxyf4FsfZmdzpEKHbJgoFNXGTESixGdzCVvCGaCul7tcRrZYpmjWddnkIAdy0OSljdS/WQc3Mxxp/xr9m6IhdP2NpdIYGd4tGMsok/Cq@VWwwqKNFk0SJCJXeowuJMGrOH36ixM5Nkim8QaAsJFk91ZPS739TnVP3GXv4Eja1IZW9MqNiXMGGzAn6EeTrKUkWTxlXp@qUmWpgwS8hV9Dt2TKZjGNdVPZ8Ls3ih1klwZ2r@rI@u/MPC6gCcFQXBtZT1a2HjyKB9d3yic@gs "Jelly – Try It Online").
### Explanation
**Helper link 1**: dyadic link with arguments x and y. x is a list of pairs of search and replace sublists. y will have each search sublist replaced with the corresponding replace sublist
```
Ẏ | Tighten (reduce to a single list of alternating search and replace sublists)
ƒ | Reduce using y as starting argument and the following link:
ƭ | - Alternate between using the following two links:
œṣ | - Split at sublist
j | - Join using sublist
```
**Helper link 2**: List of Latin characters/character pairs in the order that corresponds to the Unicode order of the Korean characters
```
“Ȯ..X’ | Base 250 integer 912...
ṃØẠ | Base decompress into Latin letters (A..Za..z)
s2 | Split into twos
ḟ€”A | Filter out A from each (used as filler for the single characters)
```
**Helper link 3**: Lists of Latin characters used for Choseong, Jungseong and Jongseong
```
“|...¿’ | List of base 250 integers, [1960852478, 2251799815782398, 2143287262]
ḃ2 | Convert to bijective base 2
’ | Decrease by 1
T€ | List of indices of true values for each list
ị¢ | Index into helper link 2
```
**Helper link 4**: Above lists of Latin characters enumerated and sorted in decreasing order of length
```
¢ | Helper link 3 as a nilad
Ɗ€ | For each list, the following three links as a monad
Ė | - Enumerate (i.e. prepend a sequential index starting at 1 to each member of the list)
$Þ | - Sort using, as a key, the following two links as a monad
Ẉ | - Lengths of lists
Ṫ | - Tail (this will be the length of the original character or characters)
Ṛ | - Reverse
```
**Main link**: Monad that takes a Jelly string as its argument and returns the translated Jelly string
*Section 1*: Convert morphemic blocks to the Unicode codepoints of the corresponding Latin characters
*Section 1.1*: Get the list of Latin character(s) needed to make the blocks
```
3£ | Helper link 3 as a nilad (lists of Latin characters used for Choseong, Jungseong and Jongseong)
O | Convert to Unicode code points
Ż€3¦ | Prepend a zero to the third list (Jongseong)
```
*Section 1.2*: Create all combinations of these letters (19×21×28 = 11,172 combinations in the appropriate lexical order)
```
Œp | Cartesian product
Ɗ€ | For each combination:
F | - Flatten
ḟ0 | - Filter zero (i.e. combinations with an empty Jonseong)
```
*Section 1.3*: Pair the Unicode code points of the blocks with the corresponding list of Latin characters, and use these to translate the morphemic blocks in the input string
```
Ʋ | Following as a monad
J | - Sequence from 1..11172
+“Ḥœ’ | - Add 44031
, | - Pair with the blocks themelves
y | Translate the following using this pair of lists
O | - The input string converted to Unicode code points
```
*Section 2*: Convert the individual Korean characters in the output from section 1 to the code points of the Latin equivalent
```
¤ | Following as a nilad
2£ | Helper link 2 (list of Latin characters/character pairs in the order that corresponds to the Unicode order of the Korean characters)
O | Convert to Unicode code points
Ʋ | Following as a monad:
J | - Sequence along these (from 1..51)
+⁽.[ | - Add 12592
, | - Pair with list of Latin characters
y | Translate the output from section 1 using this mapping
```
*Section 3*: Tidy up untranslated characters in the output from section 2 (works because anything translated from Korean will now be in a sublist and so have depth 1)
```
ŒḊ?€ | For each member of list if the depth is 1:
¹ | - Keep as is
Ọ | Else: convert back from Unicode code points to characters
µ | Start a new monadic chain using the output from this section as its argument
```
*Section 4*: Convert morphemic blocks of Latin characters into Korean
*Section 4.1*: Get all possible combinations of Choseong and Jungseong
```
¢ | Helper link 4 (lists of Latin characters enumerated and sorted in decreasing order of length)
Ṗ | Discard last list (Jongseong)
Œp | Cartesian product
```
*Section 4.2*: Label each combination with the Unicode code point for the base morphemic block (i.e. with no Jongseong)
```
Ʋ€ | For each Choseong/Jungseong combination
Z | - Transpose, so that we now have e.g. [[1,1],["r","k"]]
F€ | - Flatten each, joining the strings together
ʋ/ | - Reduce using the following as a dyad (effectively using the numbers as left argument and string of Latin characters as right)
Ʋ | - Following links as a monad
’ | - Decrease by 1
ḋ588,28 | - Dot product with 21×28,28
+“Ḥþ’ | - Add 44032
0; | - Prepend zero; used for splitting in section 4.3 before each morphemic block (Ż won’t work because on a single integer it produces a range)
, | - Pair with the string of Latin characters
Ṛ | - Reverse (so we now have e.g. ["rk", 44032]
```
*Section 4.3*: Replace these strings of Latin characters in the output from section 3 with the Unicode code points of the base morphemic block
```
ñ | Call helper link 1 (effectively search and replace)
ṣ0 | Split at the zeros introduced in section 4.2
```
Section 4.4: Identify whether there is a Jongseong as part of each morphemic block
```
Ʋ | Following as a monad:
Ḋ | - Remove the first sublist (which won’t contain a morphemic block; note this will be restored later)
€ | - For each of the other lists Z returned by the split in section 4.3 (i.e. each will have a morphemic block at the beginning):
Ʋ©? | - If the following is true (capturing its value in the register in the process)
Ḋ | - Remove first item (i.e. the Unicode code point for the base morphemic block introduced in section 4.3)
;⁶ | - Append a space (avoids ending up with an empty list if there is nothing after the morphemic block code point)
| (Output from the above will be referred to as X below)
¤ | * Following as a nilad (call this Y):
¢ | * Helper link 4
Ṫ | * Jongseong
Ʋ€ | * For each Jongseong Latin list:
Ẉ | * Lengths of lists
Ṫ | * Tail (i.e. length of Latin character string)
‘ | * Increase by 1
; | * Prepend this (e.g. [1, 1, "r"]
¥Ƈ@ | - Filter Y using X from above and the following criteria
Ṫ | - Tail (i.e. the Latin characters for the relevant Jongseong
⁼ṁ@¥ | - is equal to the beginning of X trimmed to match the relevant Jongseong (or extended but this doesn’t matter since no Jongseong are a double letter)
Ḣ | - First matching Jongseong (which since they’re sorted by descending size order will prefer the longer one if there is a matching shorter one)
Ɗ | - Then: do the following as a monad (note this is now using the list Z mentioned much earlier):
Ɗ | - Following as a monad
Ḣ | - Head (the Unicode code point of the base morphemic block)
+®Ṫ¤ | - Add the tail of the register (the position of the matched Jongsepng in the list of Jongseong)
; | - Concatenate to:
ṫ®$ | - The rest of the list after removing the Latin characters representing the Jongseong
¹ | - Else: leave the list untouched (no matching Jongseong)
ṭ | - Prepend:
Ḣ | - The first sublist from the split that was removed at the beginning of this subsection
```
*Section 5*: Handle remaining Latin characters that match Korean ones but are not part of a morphemuc block
```
F | Flatten
¤ | Following as a nilad
2£ | - Helper link 2 (Latin characters/pairs of characters in Unicode order of corresponding Korean character)
$ | - Following as a monad
ż Ɗ | - zip with following as a monad
J | - Sequence along helper link 2 (1..51)
+⁽.[ | - Add 12592
$Þ | - Sort using following as key
Ẉ | - Lengths of lists
Ṫ | - Tail (i.e. length of Latin string)
Ṛ | - Reverse
ñ | Call helper link 1 (search Latin character strings and replace with Korean code points)
Ọ | Finally, convert all Unicode code points back to characters and implicitly output
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~587~~ ~~582~~ ~~575~~ ~~569~~ ~~557~~ ~~554~~ ~~550~~ 549 bytes
tfw you didn't know that `string.charCodeAt() == string.charCodeAt(0)`.
```
s=>s.replace(eval(`/[ㄱ-힣]|${M="(h[kol]?|n[jpl]?|ml?|[bi-puyOP])"}|([${S="rRseEfaqQtTdwWczxvg"}])(${M}((s[wg]|f[raqtxvg]|qt|[${S}])(?!${M}))?)?/g`,L="r,R,rt,s,sw,sg,e,E,f,fr,fa,fq,ft,fx,fv,fg,a,q,Q,qt,t,T,d,w,W,c,z,x,v,g,k,o,i,O,j,p,u,P,h,hk,ho,hl,y,n,nj,np,nl,n,m,ml,l".split`,`,l=L.filter(x=>!/[EQW]/.test(x)),I="indexOf"),(a,E,A,B,C,D)=>a<"~"?E?X(E):A&&C?F(43193+S[I](A)*588+L[I](C)*28+l[I](D)):X(A)+X(C)+X(D):(b=a.charCodeAt()-44032)<0?L[b+31439]||a:S[b/588|0]+L[30+b/28%21|0]+["",...l][b%28],F=String.fromCharCode,X=n=>n?F(L[I](n)+12593):"")
```
[Try it online!](https://tio.run/##bVNta9tWFP7eX3Et2nJvfSIndgqOqSI8x2WlKUmaQgJCkGtbb/G1JEvyS1plbMNqQyltx@I2bCxl5MPG6FjLDOl@j2CwWPkN2b32YPswENI5zznnuc95LtqnfRo2A8ePFlyvZVyZylWorIZyYPiMNg1s9CnDewUtHX1cuDw90@PrTx4oEra1tsd0NXa1fV98O0yNtYaz4PcONjZ1Ih3GWLv@ZFuRgoehUTdpdyt61BrsNB8P@5Z0qBPMaQ4xDrWBpcemFtBuxCt63I1iMSc61JzoIUQlasHag3XOBQ8hiCCEcAChBQbUwQQzAJOC2QUzAnMIZh9MCyh0YQu6EUTwCFowgB1owmMYQh8saIMHDmzAPvjQg02wwW6D7YHN4ABccPfB9cFlPOxAhwGT5NBnTrQHe8CUddl0WGQEeKis5gpafWtHL8iREUZ4SAjcUyTHbRnDDVMigCkXWIXPoAZrRFmld6QvJLWu7uI6qVRv3qypd/FyaWmllN/W7um4Sm7dLpfz6yKukVvFcp6JcI2Qyi4v5nc5yl9rpIIbCpWbNg1q/MKqESYLy8uLpSK5s6iua418aWm5tKLHMa1sa40C54wXdU5bWsw3CsXyjeKSyDVJAlmWma41bhTLOtxVtqPAcS3ZDLxO7R9u2FVcZdXlOmeqXJJfKt5eKZGKJJEr0wsQ7tMAtZFnIk3KxkfTZHw5PslGn7LvjiVAUqsdhr2W1Y781oHIHdfvRagowjT5Jk1O02ScJskcuTw9SUcT/ojEYjQMRZCNR5c/vMdV2@g5BDkhMkKPUddCA9tp2ujA66EmdZEfeFZAO2jgRDbye4GB7nuBwQvCJtrk9xXKc0VWh@HpLz9PX77gEggSOkYTlI7Op19P0uRs@usrlP34gcPZ5IhXv0@T11wlj55P3/O@5Pjiwzn/F6a/fYmyd0fZ0xcCE3uMPnISnrwSE7NEDGSTE5EkX3ECvipHZ7WJ/K8/gCI/2MzNtxUeAuIWXvw@ys2Nejs95geccVpe@OnTxR9JDn1uMOYB2vEC1pq12f8F0P8Ozdj4@cmzNHk51/pcCBOmn1fQX@@@/fPNM0kn11DTc7nLhsw8C7cBmbhNyLWrvwE "JavaScript (Node.js) – Try It Online")
547 if characters outside alphabets and korean jamos can be ignored.
Okay I struggled for so long to write this, but this should work. ~~No Korean jamo/syllable is used because they are too expensive (3 bytes per use).~~ Used in the regular expression to save bytes.
```
s=> // Main Function:
s.replace( // Replace all convertible strings:
eval(
`/ // Matching this regex:
[ㄱ-힣] // ($0) All Korean jamos and syllables
|${M="(h[kol]?|n[jpl]?|ml?|[bi-puyOP])"} // ($1) Isolated jungseong codes
|([${S="rRseEfaqQtTdwWczxvg"}]) // ($2) Choseong codes (also acts as lookup)
( // ($3) Jungseong and jongseong codes:
${M} // ($4) Jungseong codes
( // ($5) Jongseong codes:
( // ($6)
s[wg]|f[raqtxvg]|qt // Diagraphs unique to jongseongs
|[${S}] // Or jamos usable as choseongs
)
(?!${M}) // Not linked to the next jungseong
)? // Optional to match codes w/o jongseong
)? // Optional to match choseong-only codes
/g`, // Match all
L="(...LOOKUP TABLE...)".split`,`, // Lookup table of codes in jamo order
l=L.filter(x=>!/[EQW]/.test(x)), // Jongseong lookup - only first half is used
I="indexOf" // [String|Array].prototype.indexOf
),
(a,E,A,B,C,D)=> // Using this function:
a<"~"? // If the match is code (alphabets):
E? // If isolated jungseongs code:
X(E) // Return corresponding jamo
:A&&C? // Else if complete syllable code:
F(43193+S[I](A)*588+L[I](C)*28+l[I](D)) // Return the corresponding syllable
:X(A)+X(C)+X(D) // Else return corresponding jamos joined
:(b=a.charCodeAt()-44032)<0? // Else if not syllable:
L[b+31439]||a // Return code if jamo (if not, ignore)
:S[b/588|0]+L[30+b/28%21|0]+["",...l][b%28], // Else return code for the syllable
F=String.fromCharCode, // String.fromCharCode
X=n=> // Helper function to convert code to jamo
n? // If not undefined:
F(L[I](n)+12593) // Return the corresponding jamo
:"" // Else return empty string
)
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~405~~ ~~401~~ 400 bytes
```
c=CharacterRange
p=StringReplace
q=StringReverse
r=Reverse
t=Thread
j=Join
a=j[alphabet@"Korean",4520~c~4546]
x=j[#,r/@#]&@t[a->Characters@"rRseEfaqQtTdwWczxvgkoiOjpuPh"~j~StringSplit@"hk ho hl y n nj np nl b m ml l r R rt s sw sg e f fr fa fq ft fx fv fg a q qt t T d w c z x v g"]
y=t[""<>r@#&/@Tuples@TakeList[Insert[a,"",41]~p~x~p~x,{19,21,28}]->44032~c~55203]
f=q@p[q@#,#2]&
g=f[#,r/@y]~p~x~f~y&
```
[Try it online!](https://tio.run/##ZdJJb9NAFADgu3/FqyPl5KptmiKgODICpLJILWmkHiwfpvaMncTxMp5srWoJaKDsWwKlLGU5IG6AKtH@Hm4k/IYw4ckFxMH65tmeZ795r0GERxtEVG0yJn7kkXUqTPVyyCkJVAtO67Cpft/@omog@YocIN@QQ@ToN71ryHXkhkSZLHoY30RuITvIbeQOche5h9zPEjzA@CHyCHmMPEGeIn1kgDzLEjzHeBd5gewhL5FXyGvkDbKfJXiL8TvkPfJB3Rrb@jmPcGILysskcKkS6auCVwO3TCOf2FSJj@MW5QlVuJ6thF7x5Ek7Sk2/FFYDheg1M@uCkXVBKy4UZlM7LS4UT1hKR76S0/iMkbPyhjDJdOn464mh8nJCLzASXxUVp71mb3Rabj2sLtei5oqnprUUf2Q18qsyv1cHLwTPhy4EENQgiCDwYR0a0PDBBw5l4AISSNqQuECBAePACLAYmADWAdYC5gKBGGIBAirgQBts2IAOtMBVLaWry2FSz5S4kcvPGJVm5NPEqJA6vVJNhHkxSCiXJWiqrHHOSqO0M7m0zblTWmFOK5zcsqZLxeLsfEFWvyAPYd5SmB4bkRkbOS1XsPKKqzM8jS5uZ2k3P14OjLPJJPWigpquOZmAYb8vOyanR4PRx8MfR70pWKK@H2qwFnLfmZLzrus6qN7fN2Hp/22ysj@JWY2RZrZ1uH8w/PT5n@ejwc6wN/g52B1tH472@tmbTj1Jmo5bF5HTVa1FRVmRnZFNOR8GdEod/wI "Wolfram Language (Mathematica) – Try It Online")
[Slightly ungolfed](https://tio.run/##jdLLbtNAFAbgvZ/iryNl5apNmiKgODICpHKRWtpIXVheTJ0ZO41jO7bTJlSNBDRQ7rcESrmUywKxA1SJ9nnYkfAMYdIjV63YsLA@H3vmH3vO1Fji8hpLKjYbMi902TJPTPVqEHHmqxbO6lhXf21@VzVIfhB7xE9inzg4pHOTuEXcliijmw7Vd4i7xBZxj7hPPCAeEo/SgMdUPyGeEs@I58QLokv0iJdpwCuqt4nXxA7xhnhLvCPeE7tpwAeqPxKfiM/qxtDWL7gsYnbCowXmO1wJ9cUkqvjOAg89ZnOlflSv8ijmSqSnd4lecuVOlxWmXwkqvpl2wEg7oBWm85Ntu12YLpyylCaNymjRhJGxskZisvEiZS@GXkU2LsICYnBcggBDHdeRoIQy1rAEGzfQxCocVBGggjmsIEQD83DhVuEGcD204MNfgR/C97CMGmoePIxio0Qmx2uIHZkvICIIBlGHSCCaEKsQzuGS9eRozaMVVctSWrr8PvVcMTIy2Qmj1Ag9HhslVuXXKnFiXvZjHsn/0VT5zzmrHbabo0tbz53R8jktf3rDGi/aZqEwOZXXpuWmTMlIodeN0KwbGS2Tt7KKowvamxbNF@1WdjjnG@fjUfaM4pijc9DvdmXf5BnSMPiy//ugM4ZZ7nmBhqUg8spjqqXQBPN/x0PXdaju8YeY/XfaiWCxIlgjndrf3et//Xbi/aC31e/0/vS2B5v7g51uOrJcjeNG2akmYbmlWjOKMi@bL4/LxcDnY@rwLw "Wolfram Language (Mathematica) – Try It Online")
To test this in Mathematica just replace `alphabet` with `Alphabet`; however, TIO doesn't support the Wolfram Cloud so I defined `Alphabet["Korean"]` in the header.
We first decompose all Hangul syllables to the Hangul alphabet, then swap Latin and Hangul characters, then recompose the syllables.
[Answer]
# Java 19, ~~1133~~ ~~1126~~ 1133 bytes
```
s->{String r="",k="ㄱㄲㄴㄷㄸㄹㅁㅂㅃㅅㅆㅇㅈㅉㅊㅋㅌㅍㅎ ㅏㅐㅑㅒㅓㅔㅕㅖㅗㅘㅙㅚㅛㅜㅝㅞㅟㅠㅡㅢㅣ ㄱㄲㄳㄴㄵㄶㄷㄹㄺㄻㄼㄽㄾㄿㅀㅁㅂㅄㅅㅆㅇㅈㅊㅋㅌㅍㅎ",K[]=k.split(" "),a="r R s e E f a q Q t T d w W c z x v g k o i O j p u P h hk ho hl y n nj np nl b m ml l r R rt s sw sg e f fr fa fq ft fx fv fg a q qt t T d w c z x v g";var A=java.util.Arrays.asList(a.split(" "));k=k.replace(" ","");int i,z,y,x=44032;for(var c:s.toCharArray())if(c>=x&c<55204){z=(i=c-x)%28;y=(i=(i-z)/28)%21;s=s.replace(c+r,r+K[0].charAt((i-y)/21)+K[1].charAt(y)+(z>0?K[2].charAt(z-1):r));}for(var c:s.split(r))r+=c.charAt(0)<33?c:(i=k.indexOf(c))<0?(i=A.indexOf(c))<0?c:k.charAt(i):A.get(i);for(i=r.length()-1;i-->0;r=z>0?r.substring(0,i)+(char)(K[0].indexOf(r.charAt(i))*588+K[1].indexOf(r.charAt(i+1))*28+((z=K[2].indexOf(r.charAt(i+2)))<0?0:z+1)+x)+r.substring(z<0?i+2:i+3):r)for(z=y=2;y-->0;)z&=K[y].contains(r.charAt(i+y)+"")?2:0;for(var p:"ㅗㅏㅘㅗㅐㅙㅗㅣㅚㅜㅓㅝㅜㅔㅞㅜㅣㅟㅡㅣㅢ".split("(?<=\\G...)"))r=r.replace(p.substring(0,2),p.substring(2));return r;}
```
Outputs with capital letters `ASDFGHJKLZXCVBNM` unchanged, since `.toLowerCase()` costs more than the -5 bonus.
Back +7 bytes as a bug-fix for non-Korean characters above unicode value 20,000 (thanks *@NickKennedy* for noticing).
[Try it online.](https://tio.run/##bVXfc9NGEH7nr9hopoyuklXHgZmMFSXjYWjphAIFZnhI8qDIsq1YlpTTOdjOZCalOqCUEmiTEiiQFh76QqeluA305x9zb4kz0/8g3bvYIS59sU973@1@u3v73YK75OYWyvV9L3TTFD5yg2j5GEAQMZ9WXM@Hc/IT4BKjQVQFT@8vUmKjfeUY/qTMZYEH5yACB/bT3ORyH0MdTTPrjiayFyL7WWRdkW2L7JXIXgv@ieDXBP9UcC74dcFvCH5T8M8EvyX454LfFvwLwe@A4GuC3xX8nuBfCv6V4OuCbwj@teD3Bd8U/IHgDwX/RvBHgj8W/IngW4J/K/h3gj8V/BkMIr9UwX8R2a@KwmuR/Say30X2h8j@FNlfIvtb8NUBqWyY1BAjzZyemXPqVpqEAdM10IjpOhqFi5CCD6ehAi4swsfA4DKU4SpcAQ860IIlqEIdYgjgPCxAAk24ADWo1aEWQy2ENtYuWoAogSiEeWhAI4QQpFvK0HN6FdIq@q9AhULFhcoiVBhUWlBZgkpVhVxkhzEPI2r2kkuh5Cxgj60mC0KrRKnbTi03PRukTHePpEHsOqZF/STEpkuLqWnExmsAgdkx22bLOXEiP1awKzHVpVevmFosPlVzqfKpExJUdG/SaR33Jk6eLORPkOWOoweOl2uRdwrjdlt@6EGuQ94rjKNl1E6d9DCeZ1CTGtMz@TnLky6ZjtA2QkcJWkcPrW1i6J3J/NT0TOHQ1smNkiLFBFaOcjvIDM3UcLwBNE8mxsamvCJSqVtBVPZb55E0IRP5KTSV/mPyivXBwYAUS1bVlwtVgcChVuhHVVbTSW7UDnK5ybxNHUmNWmlzPlUDoOfNAAlLH0RXyQ0C0DeOybsnx8cPknx71xjF/cK4oesdR@X8P5ACUWzzxQ6ijRYxjjLo4A5CioExJoskuXectlOw24oy6RxHv22sZRwxHP30qGMsNt6BqUIxf9j1pKip0VtT03dfzeYDtXimJvGRGtLHarGu5vGR2tpSI4mLp9rgzulTE87s7AeWZRG8fRQLOrgMyVAFC8Q8asBsbeqzJo2A2iv7thSgpDkfogD1dWgpDsrQwGT6UjUzBy45EDHm463Xehs3d/nG3sZmL3vVe7iON71cT9NmuVpnSbmtKWEbYIMoaTIoIEaJ0BMlPxwNQ6i9J5tKYLqIq0odHd7ubWR7j5/rpZrfDAgEqBRpHLookAmNq9RtNHwc24DVMBHqw3RMfTcC2QbXQxVOLcWw2gj1EpZ69w5K0T0Ckk/WRYXb3r3Wxdru/rCGtvWdn1DfXuz@uCorjlrHb0Bv62bv@m3oi6dUxG2Ylq1Ty93nXeh1N@WH1L9bUvykRuJe1xrO46BMJrCEXhhBUgeFNAHruPMyGxkGS6rr66rpdxHy/aud13wEzvhhGJtwJaZhWbqoHf2GM2@fGHb6z9bmKp5Sf/0HCODNE6Rar5D9F0i1zxw8Xn4r8bGiZTL0pFE/bYYMn67I8nR1oB/yUjtlfsOKm8xKEMnCSNdmNc1QGAOXRc3QQFoOXEjTLJI09EEgy19suiEOldonU9qp8xcvnj51GU@@X/rw7AhcqsXNsAw1d8mHed@Pisrd4Lh0iCkgCxeLhdNIBkmv7P8L)
**Explanation:**
```
s->{ // Method with String as both parameter and return-type
String r="", // Result-String, starting empty
k="ㄱㄲㄴㄷㄸㄹㅁㅂㅃㅅㅆㅇㅈㅉㅊㅋㅌㅍㅎ ㅏㅐㅑㅒㅓㅔㅕㅖㅗㅘㅙㅚㅛㅜㅝㅞㅟㅠㅡㅢㅣ ㄱㄲㄳㄴㄵㄶㄷㄹㄺㄻㄼㄽㄾㄿㅀㅁㅂㅄㅅㅆㅇㅈㅊㅋㅌㅍㅎ",
// String containing the Korean characters
K[]=k.split(" "), // Array containing the three character-categories
a="r R s e E f a q Q t T d w W c z x v g k o i O j p u P h hk ho hl y n nj np nl b m ml l r R rt s sw sg e f fr fa fq ft fx fv fg a q qt t T d w c z x v g";
// String containing the English characters
var A=java.util.Arrays.asList(a.split(" "));
// List containing the English character-groups
k=k.replace(" ",""); // Remove the spaces from the Korean String
int i,z,y, // Temp integers
x=44032; // Integer for 0xAC00
for(var c:s.toCharArray()) // Loop over the characters of the input:
if(c>=x&c<55204){ // If the unicode value is in the range [44032,55203]
// (so a Korean combination character):
z=(i=c-x)%28; // Set `i` to this unicode value - 0xAC00,
// And then `z` to `i` modulo-28
y=(i=(i-z)/28)%21; // Then set `i` to `i`-`z` integer divided by 28
// And then `y` to `i` modulo-21
s=s.replace(c+r, // Replace the current non-Korean character with:
r+K[0].charAt((i-y)/21)
// The corresponding choseong
+K[1].charAt(y) // Appended with jungseong
+(z>0?K[2].charAt(z-1):r));}
// Appended with jongseong if necessary
for(var c:s.split(r)) // Then loop over the characters of the modified String:
r+= // Append to the result-String:
c.charAt(0)<33? // If the character is a space:
c // Simply append that space
:(i=k.indexOf(c))<0? // Else-if the character is NOT a Korean character:
(i=A.indexOf(c))<0? // If the character is NOT in the English group List:
c // Simply append that character
: // Else:
k.charAt(i) // Append the corresponding Korean character
: // Else:
A.get(i); // Append the corresponding letter
for(i=r.length()-1;i-->0 // Then loop `i` in the range (result-length - 2, 0]:
; // After every iteration:
r=z>0? // If a group of Korean characters can be merged:
r.substring(0,i) // Leave the leading part of the result unchanged
+(char)(K[0].indexOf(r.charAt(i))
// Get the index of the first Korean character,
*588 // multiplied by 588
+K[1].indexOf(r.charAt(i+1))
// Get the index of the second Korean character,
*28 // multiplied by 28
+((z=K[2].indexOf(r.charAt(i+2)))
// Get the index of the third character
<0? // And if it's a Korean character in the third group:
0:z+1) // Add that index + 1
+x // And add 0xAC00
) // Then convert that integer to a character
+r.substring(z<0?i+2:i+3)
// Leave the trailing part of the result unchanged as well
: // Else (these characters cannot be merged)
r) // Leave the result the same
for(z=y=2; // Reset `z` to 2
y-->0;) // Inner loop `y` in the range (2, 0]:
z&= // Bitwise-AND `z` with:
K[y].contains( // If the `y`'th Korean group contains
r.charAt(i+y)+"")?// the (`i`+`y`)'th character of the result
2 // Bitwise-AND `z` with 2
: // Else:
0; // Bitwise-AND `z` with 0
// (If `z` is still 2 after this inner loop, it means
// Korean characters can be merged)
for(var p:"ㅗㅏㅘㅗㅐㅙㅗㅣㅚㅜㅓㅝㅜㅔㅞㅜㅣㅟㅡㅣㅢ".split("(?<=\\G...)"))
// Loop over these Korean character per chunk of 3:
r=r.replace(p.substring(0,2),
// Replace the first 2 characters in this chunk
p.substring(2)); // With the third one in the result-String
return r;} // And finally return the result-String
```
] |
[Question]
[
### Kids-related intro
Whenever I take my kids to an amusement park, the kids get more nervous the closer we are to the park, with the nerve peak when we are in the parking lot and find no place to park. So I've decided I need a method to find the closest free parking space to minimise the time spent parking.
### Technical intro
Imagine a representation of a parking lot like this one:
```
*****************
* *
* ··CC··C··CC·· *
* ************* *
* ··CCCCCCCCC·· *
* *
**********E******
```
In this representation a `*` means a wall, a `·` a free parking space, a `E` the entry point and a `C` a car already parked. Every whitespace is a position the car to be parked can use to move around the parking lot. Now let's extend this concept to 3D to create a multi-level parking lot:
```
1st floor 2nd floor 3rd floor 4th floor
***************** ***************** ***************** *****************
* 1 * 2 * 3 * *
* CCCCCCCCCCCCC * * CCCCCCCCCCCCC * * ····C··CCCCCC * * ······C······ *
* ************* * * ************* * * ************* * * ************* *
* CCCCCCCCCCCCC * * CCCCCCCCCCCCC * * ···CCCCCCCCCC * * ··C·······C·· *
* * * 1 * 2 * 3
**********E****** ***************** ***************** *****************
```
The numbers `1`, `2` and `3` represent the connections between levels. The `1` from the first floor connects with the `1` in the second floor so a car stepping into the `1` position in the first floor appears in the `1` position in the second floor.
### Challenge
Giving a scheme of a parking lot like the previously shown, write the shortest program that calculates the distance to the nearest free parking space, according to the following
### Rules
* The input will be a 3D char array or a 2D string array or equivalent, and the output will be a single integer representing the number of steps the car must take to get to the nearest free parking space. If you receive a 3D char array the first index may represent the floor number and the second and third indices the (x,y) position for each floor, but this is up to you.
* There won't be more than 9 ramps, represented by `[1-9]`.
* The car starts from the `E` position (there will be only one entry point per map) and moves around using the whitespaces in one of four directions each time: up, down, left, right. The car can also step into `·` positions and `[1-9]` positions.
* Every change of position (step) counts as 1, and every time the car goes from one floor to another counts as 3 as the car must take a ramp. In this case, the movement from a whitespace beside a `1` to the `1` itself is what counts as 3 steps, because as a result of this movement the car appears in the `1` position on the other floor.
* The car can't go beyond the matrix limits.
* The count will end when the car to be parked is in the same position as a `·`. If there are no reachable free parking spaces you can return zero, a negative integer, a null value or an error.
### Examples
In the example above the result would be 32, as it is cheaper to go to the fourth floor and park in the closest parking space near the `3`. The nearest free parking spaces in the third floor are at a distance of 33 and 34.
Other examples:
```
1st floor 2nd floor 3rd floor 4th floor
***************** ***************** ***************** *****************
* 1 * 2 * 3 * *
* CCCCCCCCCCCCC * * CCCCCCCCCCCCC * * ····C··CCCCCC * * ······C······ *
* ************* * * ************* * * ************* * * ************* *
* CCCCCCCCCCCCC * * ·CCCCCCCCCCCC * * ···CCCCCCCCCC * * ··C·······C·· *
* * * 1 * 2 * 3
**********E****** ***************** ***************** *****************
Answer: 28 (now the parking space in the 2nd floor is closer)
1st floor 2nd floor 3rd floor 4th floor
***************** ***************** ***************** *****************
* 1 4 2 5 3 6 *
* CCCCCCCCCCCCC * * CCCCCCCCCCCCC * * ····C··CCCCCC * * ······C······ *
* ************* * * ************* * * ************* * * ************* *
* CCCCCCCCCCCCC * * CCCCCCCCCCCCC * * ···CCCCCCCCCC * * ··C·······C·· *
4 * 5 1 6 2 * 3
**********E****** ***************** ***************** *****************
Answer: 24 (now it's better to go to ramp 4 and then to ramp 5 to the third floor)
1st floor 2nd floor 3rd floor 4th floor
***************** ***************** ***************** *****************
* 1 * * * 3 * 2
* CCCCCCCCCCCCC * * CCCCCCCCCCCCC * * ····C··CCCCCC * * ······C······ *
* ************* * * ************* * * ************* * * ************* *
* CCCCCCCCCCCCC * * ·CCCCCCCCCCCC * * ···CCCCCCCCCC * * ··C·······C·· *
* * * 3 * 2 * 1
**********E****** ***************** ***************** *****************
Answer: 16 (now the parking space in the 4th floor is closer)
1st floor 2nd floor 3rd floor 4th floor 5th floor
************ ************ ************ ************ ************
*CCCCCCCCC 1 *CCCCCCCCC 2 *CCCCCCCCC 3 *·CCCCCCCC 4 *········C *
* * * * * * * * * *
*CCCCCCCCC E *CCCCCCCCC 1 *CCCCCCCCC 2 *··CCCCCCC 3 *·······CC 4
************ ************ ************ ************ ************
Answer: 29 (both the nearest parking spaces at the 4th and 5th floors are at the same distance)
1st floor 2nd floor 3rd floor
************ ************ ************
*CCCCCCCCC 1 *CCCCCCCCC 2 *CCCCCCCCC *
* * * * * *
*CCCCCCCCC E *CCCCCCCCC 1 *CCCCCCCCC 2
************ ************ ************
Answer: -1 (no free parking space)
1st floor
************
* *
* *
* E*
************
Answer: -1 (no parking space at all)
1st floor
************
* ····· *
*· ****
* ····· * E
*********
Answer: -1 (the parking lot designer was a genius)
```
### Alternatives
* You can use whatever characters you want to represent the parking lot map, just specify in your answer which are your chosen characters and what they mean.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so may the shortest program/method/lambda/whatever for each language win!
*If you need help with the algorithm, please check [my (ungolfed) implementation in C#](https://tio.run/##7Vhfb9s2EH/3p7j5oZYaWbAkp0Xr2EPgpUGBpA2QrBsQGIUmM4kym/IoOm3W@nP1vV8sI/XHkihRlNyl20MpxJGpu@Pd704/Hu2FfS8g6GEd@vgazu9DipajTv6bOQ0WC@RRP8CheYwwIr4nSJz4@K9Rp4PdJQpXrofgzCV/suevfDxHpPOpA2x4CzcM4YwE18RdRjPxPB8hdanvAUHuPMCLe/AxhdPD39@/Ozz59QjG8CIabAlB4S7w53Dq@lgLKWELXs7AJdehvpXLluDjziWwdP9GzCJGHyDRGRrPZ6OCHJe5HBgwmDHJ7lNxdKulrVgaisOSSNuJ9DQ/QGbbSaQLfkilh61s71f6LZN@JmByJMfEaoWgJUPQlki3QNBqhaDVCkFLhqAlkX7WHBO7FYK2DEFHIp0i@PVLfE2jj5pY7VY42hmOiX0FlLYMSlsi3QJKpxWUjgxKmbQI5RbO9JJqtgDUKQJasJ98lSruN68Mpw7YgviU7QnBApm/EZ8itgsgrfuLz7gZsz2ABnBFEIJVvBdAtDO8hC7swXmwuEMaX0vXBYtlet7nvjfl53pqzspPxcpKGnREi0f1XKwmv0FTwVIwKoKsD8aqCMaqp8VdWKuesLKlVVxVH4xdEYxdz0278EY9ZWREB0MFXSh5xUlNbo1K39lm8QybxjPMxSMQDcgUmoU1LISVsyvBayiJ7TtQ0Q@W@cEy/1OWmf7rJKOA5zEpRtEY7kAtCni@H6ekxjYP6d2K@HcuRekhlh92Y5Wk4zFmkY91p1iCQuZ8tpAB/Kx9FoQ@P6cnU72jnm6@8klItbwjfBBE1wRHZibj3FH7Z@hb8JLP5xzPQGnouQEX69UCHbDnBqQfE65FqCwq/woity8jKfM1RUtGBdkXe5Z7wnM8ht7XLz09DWVQDBAtQlSYKK6WazWniwAn2RpVysg9Ytr1Aub5@o8YGm2Qf@LosFdai4/e0x4roMZGcxaZmlURAC@WDzeIoIvgOGD@8jJ5gz5SoVTi1JTVeVa26uYhvmeVVBL6VBlKkpdM@xzxn5G0FYwnsIqcHhZeFiPq@qsqR1ulOMQ3dnrj6LpunvpYq3B9U5rhNZG6tS35ouKmQdVntR6XTvO31uPy8@LxhuuYx4ieIHxNb7SBboAwZenC8ecqIKDxd89npgYj9u8ASmbY9N5eOVdb3dtY97asy8oIbqt041/xeAiXvgG3EX1203KNZipJJlZpwicnjFwPsgJI/iaTIrmJXOPdRDXu0ouAy6lpk6MvLJXV2kSspf8S7S0pRuiabD@iro9DLRdttWIMf2gezuea9K3iRo1c9szXeI4@vr0qmJduHDskFASoy2zUaB/x1oQgTL8t0ZJsi3zZrlZ4vhLvYqLirFyV83LWcixbl7O8dcaHpcWKU46ucNDJOcjOEYOZGbv4KP4JvkU7lhLAPvOPtSiDx0GsvwNij@qRiFG/jBEjFeR6N6DxWl0xk9m6uqLl2fKJuKHOkpmksWLX58/QRJK3YI0bglo@Um31RhmJmm2@SaQsiT2rB0@eKCM9YJIvGgca5SUIk25L6LQUS6UNO@VdUlIi8NM4Eazq8FpAG4TbdZNbO7vl50A1wBv1bvAQy20e/gE).*
[Answer]
# JavaScript (ES6), 199 bytes
Takes input as an array of arrays of arrays of characters, using the characters described in the challenge. Returns \$0\$ if there's no free parking space.
```
a=>(m=g=(c,t,f,x,y,F=f||a.find(r=>r.some((a,i)=>~(y=i,x=a.indexOf(c)))),r=F[y])=>r&&(c=r[x])&&(r[x]=g,c>'z'?m=m<t?m:t:!f|c<1?[0,-1,0,1].map((d,i)=>g(0,-~t,F,x+d,y+~-i%2)):+c&&g(c,t+2),r[x]=c))('E')|m
```
[Try it online!](https://tio.run/##7VTLboJAFN37FXRRGOA6cbAr4@DC6LYfQFiQ4REaEYOkgYb4W933x@j4BgIW1LYb7yS8Lueec4Z7ebPerTWL/FXcX4a2k7s0t6iOAupRxCAGFxJIYU7dLLOw6y9tFFE9wuswcBCywJepvkEp9SGhFuZpJ3l1EZN5QETnRmryFyJRRIxGRmLK/Gp7ph4wXfqQJgENxvEkGMWjJzdjYzIxBtAnMABi4sBaIWTvKDzEH29imEOi2pCqm77/rMnySGWi6G11qhrn2xbm1EiaSXIW5CxcrsOFgxehh1xkGD1BMDDGklINyYRTTigHKeWmxRDKuFLFSu4Srhyl3ClmR509E66yof2xDVJrQ7nVxrCU@/rcr@nu0NXMAdvOj/Y7fpRaPydPx9XRVQl7uBVab2udO1OWe49pavhs19ooNt8PPoaPcer@l/u3cSL3GqdinfPGknrqhrdnDWKad7m@jtaJldyJddiJVbuJ9dy9wksL2kK7N85nW@JKhzV11wVUVfQdOq4wQDXkB0UXMArvPaFGksRxe0n5Nw "JavaScript (Node.js) – Try It Online")
### How?
The recursive function **g()** takes as input:
* **c** : the character of the entry point we're looking for if we've just left a floor or we are at the very beginning of the process; **0** otherwise
* **t** : the total number of moves so far (initially *undefined*)
* **f**, **x**, **y** : a pointer to the current floor and the current coordinates in this floor; they are all *undefined* if we're looking for a new floor
If **f** is defined, we simply copy it to the current floor **F**. Otherwise, we need to look for the new floor and the new coordinates by iterating over each floor and over each row until we find the entry point **c**:
```
F = f || a.find(r => r.some((a, i) => ~(y = i, x = a.indexOf(c))))
```
We define **r** as the current row in the current floor:
```
r = F[Y]
```
The next step is to make sure that the current cell **c** at **(x, y)** is defined:
```
r && (c = r[x]) && ...
```
If it is, we mark it as visited by setting it to **g**, a value that does not trigger any of the forthcoming tests:
```
r[x] = g
```
If **c** is a free parking space, we stop the recursion. And if the total number of moves is lower than our previous best score, we update **m** accordingly:
```
c > 'z' ? m = m < t ? m : t : ...
```
If we've just reached a new floor (**f** is *undefined*) or **c** is a space, we process a recursive call for each surrounding cell:
```
!f | c < 1 ?
[0, -1, 0, 1].map((d, i) =>
g(0, -~t, F, x + d, y + ~-i % 2)
)
:
...
```
Otherwise, if **c** is a ramp marker (i.e. a non-zero digit), we process a single recursive call to reach the new floor:
```
+c && g(c, t + 2)
```
Finally, we restore the current cell to its initial value so that it can be visited again in other recursion paths:
```
r[x] = c
```
[Answer]
# Powershell, ~~299~~ 292 bytes
It is assumed that the [map is rectangle](https://www.youtube.com/watch?v=OoYeDq-KmqM).
It uses `x` instead `·`. To get `·`, you need to save script as ASCII (not UTF-8) and replace `x` on `·`.
```
filter f{$l=($_-split"
")[0].length
$p,$d,$e='x','\d',' '|%{"$_(?=E)|(?<=E)$_|$_(?=[\s\S]{$l}E)|(?<=E[\s\S]{$l})$_"}
for($r=1;$_-notmatch$p;$r++){$m=$_-replace'F','E'-replace'G','F'-replace'H','G'
if($m-match$d){$m=$m-replace$Matches[0],'H'}$m=$m-replace$e,'E'
if($m-eq$_){return -1}$_=$m}$r}
```
Ungolfed and test script:
```
filter f{
#Write-Host "`nStep:`n$_" # uncomment this to display each step
$l = ($_ -split "`n")[0].length
$p,$d,$e = 'x', '\d', ' '| % {"$_(?=E)|(?<=E)$_|$_(?=[\s\S]{$l}E)|(?<=E[\s\S]{$l})$_"}
for($r = 1;$_ -notmatch $p;$r++) {
$m = $_ -replace 'F', 'E' -replace 'G', 'F' -replace 'H', 'G'
if ($m -match $d) {
$m = $m -replace $Matches[0], 'H'
}
$m = $m -replace $e, 'E'
if ($m -eq $_) {
return -1
}
$_=$m
}
$r
}
@(
, (2, @"
****
*x E
****
"@)
, (1, @"
****
* xE
****
"@)
, (1, @"
****
* x*
* E*
****
"@)
, (1, @"
****
* E*
* x*
****
"@)
, (-1, @"
****
2 E1
* *
****
"@)
, (28, @"
*****************
* 1
* CCCCCCCCCCCCC *
* ************* *
* CCCCCCCCCCCCC *
* *
**********E******
*****************
* 2
* CCCCCCCCCCCCC *
* ************* *
* xCCCCCCCCCCCC *
* 1
*****************
*****************
* 3
* xxxxCxxCCCCCC *
* ************* *
* xxxCCCCCCCCCC *
* 2
*****************
*****************
* *
* xxxxxxCxxxxxx *
* ************* *
* xxCxxxxxxxCxx *
* 3
*****************
"@)
, (16, @"
*****************
* 1
* CCCCCCCCCCCCC *
* ************* *
* CCCCCCCCCCCCC *
* *
**********E******
*****************
* *
* CCCCCCCCCCCCC *
* ************* *
* xCCCCCCCCCCCC *
* 3
*****************
*****************
* 3
* xxxxCxxCCCCCC *
* ************* *
* xxxCCCCCCCCCC *
* 2
*****************
*****************
* 2
* xxxxxxCxxxxxx *
* ************* *
* xxCxxxxxxxCxx *
* 1
*****************
"@)
, (29, @"
************
*CCCCCCCCC 1
* *
*CCCCCCCCC E
************
************
*CCCCCCCCC 2
* *
*CCCCCCCCC 1
************
************
*CCCCCCCCC 3
* *
*CCCCCCCCC 2
************
************
*xCCCCCCCC 4
* *
*xxCCCCCCC 3
************
************
*xxxxxxxxC *
* *
*xxxxxxxCC 4
************
"@
)
, (-1, @"
************
* *
* *
* E*
************
"@)
, (-1, @"
************
* xxxxx *
*x ****
* xxxxx * E
*********
"@)
) | % {
$e, $m = $_
$r = $m|f
"$($e-eq$r): $r $e"
}
```
Output:
```
True: 2 2
True: 1 1
True: 1 1
True: 1 1
True: -1 -1
True: 28 28
True: 16 16
True: 29 29
True: -1 -1
True: -1 -1
```
Extended output for parking with 16 steps:
```
Step:
*****************
* 1
* CCCCCCCCCCCCC *
* ************* *
* CCCCCCCCCCCCC *
* *
**********E******
*****************
* *
* CCCCCCCCCCCCC *
* ************* *
* xCCCCCCCCCCCC *
* 3
*****************
*****************
* 3
* xxxxCxxCCCCCC *
* ************* *
* xxxCCCCCCCCCC *
* 2
*****************
*****************
* 2
* xxxxxxCxxxxxx *
* ************* *
* xxCxxxxxxxCxx *
* 1
*****************
Step:
*****************
* 1
* CCCCCCCCCCCCC *
* ************* *
* CCCCCCCCCCCCC *
* E *
**********E******
*****************
* *
* CCCCCCCCCCCCC *
* ************* *
* xCCCCCCCCCCCC *
* 3
*****************
*****************
* 3
* xxxxCxxCCCCCC *
* ************* *
* xxxCCCCCCCCCC *
* 2
*****************
*****************
* 2
* xxxxxxCxxxxxx *
* ************* *
* xxCxxxxxxxCxx *
* 1
*****************
Step:
*****************
* 1
* CCCCCCCCCCCCC *
* ************* *
* CCCCCCCCCCCCC *
* EEE *
**********E******
*****************
* *
* CCCCCCCCCCCCC *
* ************* *
* xCCCCCCCCCCCC *
* 3
*****************
*****************
* 3
* xxxxCxxCCCCCC *
* ************* *
* xxxCCCCCCCCCC *
* 2
*****************
*****************
* 2
* xxxxxxCxxxxxx *
* ************* *
* xxCxxxxxxxCxx *
* 1
*****************
Step:
*****************
* 1
* CCCCCCCCCCCCC *
* ************* *
* CCCCCCCCCCCCC *
* EEEEE *
**********E******
*****************
* *
* CCCCCCCCCCCCC *
* ************* *
* xCCCCCCCCCCCC *
* 3
*****************
*****************
* 3
* xxxxCxxCCCCCC *
* ************* *
* xxxCCCCCCCCCC *
* 2
*****************
*****************
* 2
* xxxxxxCxxxxxx *
* ************* *
* xxCxxxxxxxCxx *
* 1
*****************
Step:
*****************
* 1
* CCCCCCCCCCCCC *
* ************* *
* CCCCCCCCCCCCC *
* EEEEEEE *
**********E******
*****************
* *
* CCCCCCCCCCCCC *
* ************* *
* xCCCCCCCCCCCC *
* 3
*****************
*****************
* 3
* xxxxCxxCCCCCC *
* ************* *
* xxxCCCCCCCCCC *
* 2
*****************
*****************
* 2
* xxxxxxCxxxxxx *
* ************* *
* xxCxxxxxxxCxx *
* 1
*****************
Step:
*****************
* 1
* CCCCCCCCCCCCC *
* ************* *
* CCCCCCCCCCCCC *
* EEEEEEEEE *
**********E******
*****************
* *
* CCCCCCCCCCCCC *
* ************* *
* xCCCCCCCCCCCC *
* 3
*****************
*****************
* 3
* xxxxCxxCCCCCC *
* ************* *
* xxxCCCCCCCCCC *
* 2
*****************
*****************
* 2
* xxxxxxCxxxxxx *
* ************* *
* xxCxxxxxxxCxx *
* 1
*****************
Step:
*****************
* 1
* CCCCCCCCCCCCC *
* ************* *
* CCCCCCCCCCCCC *
* EEEEEEEEEEE*
**********E******
*****************
* *
* CCCCCCCCCCCCC *
* ************* *
* xCCCCCCCCCCCC *
* 3
*****************
*****************
* 3
* xxxxCxxCCCCCC *
* ************* *
* xxxCCCCCCCCCC *
* 2
*****************
*****************
* 2
* xxxxxxCxxxxxx *
* ************* *
* xxCxxxxxxxCxx *
* 1
*****************
Step:
*****************
* 1
* CCCCCCCCCCCCC *
* ************* *
* CCCCCCCCCCCCCE*
* EEEEEEEEEEEE*
**********E******
*****************
* *
* CCCCCCCCCCCCC *
* ************* *
* xCCCCCCCCCCCC *
* 3
*****************
*****************
* 3
* xxxxCxxCCCCCC *
* ************* *
* xxxCCCCCCCCCC *
* 2
*****************
*****************
* 2
* xxxxxxCxxxxxx *
* ************* *
* xxCxxxxxxxCxx *
* 1
*****************
Step:
*****************
* 1
* CCCCCCCCCCCCC *
* *************E*
* CCCCCCCCCCCCCE*
* EEEEEEEEEEEEE*
**********E******
*****************
* *
* CCCCCCCCCCCCC *
* ************* *
* xCCCCCCCCCCCC *
* 3
*****************
*****************
* 3
* xxxxCxxCCCCCC *
* ************* *
* xxxCCCCCCCCCC *
* 2
*****************
*****************
* 2
* xxxxxxCxxxxxx *
* ************* *
* xxCxxxxxxxCxx *
* 1
*****************
Step:
*****************
* 1
* CCCCCCCCCCCCCE*
* *************E*
* CCCCCCCCCCCCCE*
* EEEEEEEEEEEEEE*
**********E******
*****************
* *
* CCCCCCCCCCCCC *
* ************* *
* xCCCCCCCCCCCC *
* 3
*****************
*****************
* 3
* xxxxCxxCCCCCC *
* ************* *
* xxxCCCCCCCCCC *
* 2
*****************
*****************
* 2
* xxxxxxCxxxxxx *
* ************* *
* xxCxxxxxxxCxx *
* 1
*****************
Step:
*****************
* E1
* CCCCCCCCCCCCCE*
* *************E*
* CCCCCCCCCCCCCE*
*EEEEEEEEEEEEEEE*
**********E******
*****************
* *
* CCCCCCCCCCCCC *
* ************* *
* xCCCCCCCCCCCC *
* 3
*****************
*****************
* 3
* xxxxCxxCCCCCC *
* ************* *
* xxxCCCCCCCCCC *
* 2
*****************
*****************
* 2
* xxxxxxCxxxxxx *
* ************* *
* xxCxxxxxxxCxx *
* 1
*****************
Step:
*****************
* EEH
* CCCCCCCCCCCCCE*
* *************E*
*ECCCCCCCCCCCCCE*
*EEEEEEEEEEEEEEE*
**********E******
*****************
* *
* CCCCCCCCCCCCC *
* ************* *
* xCCCCCCCCCCCC *
* 3
*****************
*****************
* 3
* xxxxCxxCCCCCC *
* ************* *
* xxxCCCCCCCCCC *
* 2
*****************
*****************
* 2
* xxxxxxCxxxxxx *
* ************* *
* xxCxxxxxxxCxx *
* H
*****************
Step:
*****************
* EEEG
* CCCCCCCCCCCCCE*
*E*************E*
*ECCCCCCCCCCCCCE*
*EEEEEEEEEEEEEEE*
**********E******
*****************
* *
* CCCCCCCCCCCCC *
* ************* *
* xCCCCCCCCCCCC *
* 3
*****************
*****************
* 3
* xxxxCxxCCCCCC *
* ************* *
* xxxCCCCCCCCCC *
* 2
*****************
*****************
* 2
* xxxxxxCxxxxxx *
* ************* *
* xxCxxxxxxxCxx *
* G
*****************
Step:
*****************
* EEEEF
*ECCCCCCCCCCCCCE*
*E*************E*
*ECCCCCCCCCCCCCE*
*EEEEEEEEEEEEEEE*
**********E******
*****************
* *
* CCCCCCCCCCCCC *
* ************* *
* xCCCCCCCCCCCC *
* 3
*****************
*****************
* 3
* xxxxCxxCCCCCC *
* ************* *
* xxxCCCCCCCCCC *
* 2
*****************
*****************
* 2
* xxxxxxCxxxxxx *
* ************* *
* xxCxxxxxxxCxx *
* F
*****************
Step:
*****************
*E EEEEEE
*ECCCCCCCCCCCCCE*
*E*************E*
*ECCCCCCCCCCCCCE*
*EEEEEEEEEEEEEEE*
**********E******
*****************
* *
* CCCCCCCCCCCCC *
* ************* *
* xCCCCCCCCCCCC *
* 3
*****************
*****************
* 3
* xxxxCxxCCCCCC *
* ************* *
* xxxCCCCCCCCCC *
* 2
*****************
*****************
* 2
* xxxxxxCxxxxxx *
* ************* *
* xxCxxxxxxxCxx *
* EE
*****************
Step:
*****************
*EE EEEEEEE
*ECCCCCCCCCCCCCE*
*E*************E*
*ECCCCCCCCCCCCCE*
*EEEEEEEEEEEEEEE*
**********E******
*****************
* *
* CCCCCCCCCCCCC *
* ************* *
* xCCCCCCCCCCCC *
* 3
*****************
*****************
* 3
* xxxxCxxCCCCCC *
* ************* *
* xxxCCCCCCCCCC *
* 2
*****************
*****************
* 2
* xxxxxxCxxxxxx *
* ************* *
* xxCxxxxxxxCxxE*
* EEE
*****************
True: 16 16
```
## Explanation
It's kind of [Lee pathfinding algorithm](https://en.wikipedia.org/wiki/Lee_algorithm). Only one smart thing: 3 steps on ramp are realized as a dummy states `H->G->F->E`
---
# Powershell for a genius parking lot designer, ~~377~~ 369 bytes
Parking design is an `2D string array`. No assumtions about map: any length strings, floors without walls, parking without an entry point, multi-floor-and-multi-exit-ramps. Genus cost is +26%.
```
filter f{for($r=1;$_-notmatch$p;$r++){$m=$_-replace'F','E'-replace'G','F'-replace'H','G'
if($m-match$d){$m=$m-replace$Matches[0],'H'}$m=$m-replace$e,'E'
if($m-eq$_){return-1}$_=$m}$r}$g={$l=($args|%{$_|%{$_.length}}|sort)[-1]
$p,$d,$e='x','\d',' '|%{"$_(?=E)|(?<=E)$_|$_(?=[\s\S]{$l}E)|(?<=E[\s\S]{$l})$_"}
(($args|%{$_.PadRight($l,'*')-join"
"})-join"
"+'-'*$l+"
")|f}
```
Ungolfed and test script:
```
filter f{
#Write-Host "`nStep:`n$_" # uncomment this to display each step
for($r = 1;$_ -notmatch $p;$r++) {
$m = $_ -replace 'F', 'E' -replace 'G', 'F' -replace 'H', 'G'
if ($m -match $d) {
$m = $m -replace $Matches[0], 'H'
}
$m = $m -replace $e, 'E'
if ($m -eq $_) {
return -1
}
$_=$m
}
$r
}
$g = {
$l = ($args| % {$_| % {$_.length}}|sort)[-1]
$p,$d,$e = 'x', '\d', ' '| % {"$_(?=E)|(?<=E)$_|$_(?=[\s\S]{$l}E)|(?<=E[\s\S]{$l})$_"}
(($args| % {$_.PadRight($l, '*') -join "`n"}) -join "`n"+'-' * $l+"`n")|f
}
@(
, (2, @(, (
"****",
"*x E",
"****"
)))
, (1, @(, (
"****",
"* xE",
"****"
)))
, (1, @(, (
"****",
"* x*",
"* E*",
"****"
)))
, (1, @(, (
"****",
"* E*",
"* x*",
"****"
)))
, (-1, @(, (
"****",
"2 E1",
"* *",
"****"
)))
, (28, @(, (
"*****************",
"* 1",
"* CCCCCCCCCCCCC *",
"* ************* *",
"* CCCCCCCCCCCCC *",
"* *",
"**********E******"
), (
"*****************",
"* 2",
"* CCCCCCCCCCCCC *",
"* ************* *",
"* xCCCCCCCCCCCC *",
"* 1",
"*****************"
), @(
"*****************",
"* 3",
"* xxxxCxxCCCCCC *",
"* ************* *",
"* xxxCCCCCCCCCC *",
"* 2",
"*****************"
), @(
"*****************",
"* *",
"* xxxxxxCxxxxxx *",
"* ************* *",
"* xxCxxxxxxxCxx *",
"* 3",
"*****************"
)))
, (16, @(, (
"*****************",
"* 1",
"* CCCCCCCCCCCCC *",
"* ************* *",
"* CCCCCCCCCCCCC *",
"* *",
"**********E******"
), @(
"*****************",
"* *",
"* CCCCCCCCCCCCC *",
"* ************* *",
"* xCCCCCCCCCCCC *",
"* 3",
"*****************"
), @(
"*****************",
"* 3",
"* xxxxCxxCCCCCC *",
"* ************* *",
"* xxxCCCCCCCCCC *",
"* 2",
"*****************"
), @(
"*****************",
"* 2",
"* xxxxxxCxxxxxx *",
"* ************* *",
"* xxCxxxxxxxCxx *",
"* 1",
"*****************"
)))
, (29, @(, (
"************",
"*CCCCCCCCC 1",
"* *",
"*CCCCCCCCC E",
"************"
), @(
"************",
"*CCCCCCCCC 2",
"* *",
"*CCCCCCCCC 1",
"************"
), @(
"************",
"*CCCCCCCCC 3",
"* *",
"*CCCCCCCCC 2",
"************"
), @(
"************",
"*xCCCCCCCC 4",
"* *",
"*xxCCCCCCC 3",
"************"
), @(
"************",
"*xxxxxxxxC *",
"* *",
"*xxxxxxxCC 4",
"************"
)))
, (-1, @(, (
"************",
"* *",
"* *",
"* E*",
"************"
)))
, (-1, @(, (
"************",
"* xxxxx *",
"*x ****",
"* xxxxx * E",
"*********"
)))
) | % {
$e, $m = $_
$r = &$g @m
"$($e-eq$r): $r $e"
}
```
[Answer]
# [Kotlin](https://kotlinlang.org), 768 bytes
used period . instead of ·. Wish I understood Arnauld's answer because losing 500 bytes would be nice.
```
fun s(l:List<List<CharArray>>)={val b=listOf(l.size-1,l[0].size-1,l[0][0].size-1)
val e=Int.MAX_VALUE
var r=e
var t=listOf(e,e,e)
val d=Array(b[0]+1){Array(b[1]+1){Array(b[2]+1){e}}}
val f={c:Char,n:List<Int>->var a=t
(0..b[0]).map{f->(0..b[1]).map{r->(0..b[2]).map{var s=listOf(f,r,it)
if(l[f][r][it]==c&&!s.equals(n))a=s}}}
a}
fun m(p:List<Int>,c:Int){if(p[0]in 0..b[0]&&p[1]in 0..b[1]&&p[2]in 0..b[2]&&d[p[0]][p[1]][p[2]]>c){d[p[0]][p[1]][p[2]]=c
val h=l[p[0]][p[1]][p[2]]
when(h){' ','E'->(-1..1 step 2).map{m(listOf(p[0],p[1]+it,p[2]),c+1)
m(listOf(p[0],p[1],p[2]+it),c+1)}
'.'->if(r>c)r=c
in '1'..'9'->{val n=f(h,p)
d[n[0]][n[1]][n[2]]=c+2
(-1..1 step 2).map{m(listOf(n[0],n[1]+it,n[2]),c+3)
m(listOf(n[0],n[1],n[2]+it),c+3)}}}}}
m(f('E',t),0)
if(r<e)r
else-1}()
```
[Try it online!](https://tio.run/##7RzbbttG9p1fMe0ClqjQdCRls40RGQgc78JAul003e0uDGMxpkYSNySH5ZCWVcPflff8WPacMxcOJfmWupcEVlJbnDkzc@63YfpO1llafNwbsMNK8FpM2UxWrF6kiiVyKthcZjOWLHiWiWIu9oNFXZdqf28PJ3EuVjVP3okLAIH5OJH53k@NUHUqC7U3fP7Ni/Hz4Nsmq9PdTJyLjM0qIVjJq3dpMWeq5Ilgs7SYiioIflyIAmAqdsxq/k6wfMXepVPFasl4wXjeKJGLoqbVEaAo9PRc1CyXlWCFqM5lo2gmyaSCnZaCcZiBHXBQL1ym9YIeER4GBX/HlnC0BU4LB4w4ZrKG46eEJSskKzPEGXZEgJi9ley4B9tMRZJOgXvHsC384iwX9UJOEZBWOqRUvY0HAJanRZqnShBoneYCpiy5ABgHP4hkUaQJzwDFupJBcJzzeVoA1qwSZSUUQHNkPJMzGPMJyNJ3QgtVFiDEYLD@CQas@8GRD@8/vD88pJ/tV5rprPVgzcfBbezpPkfm3OC40IitkcDZAFjICwXflqB9EfyGTfkW5uHUEXENVlcrVkrgD8mMs0P4L@EV4xlo93RFC8U0ZkegZysQe1oLLYAUDyqlSul0khYsA7GcCbMIBgrWKC0reY7KIhsjWY/XMfu7XLJM1D3FxEUtCIKsqUhEWePq8Wv8mZC9oaZ45uFtBGJCpg1RYTIJRul9RqiQ64PjasvgM1B2GtyUOYnk0wc3xDsksLXB0bbB8bZB3PDQ/2iIawZRxTzN3Dblpu2fbaqrl3zy4CfgvH28g6h53GZC2zh3D8ZvWuAv1YLgB3SlTX4mKsWGEZyLljdu7VkbkywKkVBUAIuqlwL8LWm8ihluMAS7ljmBztLKqbxZplqnPbT@WQmYtAqvpLFzVYuyRAMCFyDNAmfVZqV/AC/B/wPiZmoT2D8mDg5tIAyCv6XneA5nKllAXLrW54JzqMR5CoEpWzG1kMsCQlAFfkdvv5BVjTGhrOS84sgBXgMlWdJk4B10MJumEGSLxMWxAlDeHkfAFSaJrKY4YIBnMsvkEgaC75tMKO1UkOVpUTY1MDbL0Mdx9EoQxIElVcVXDHnDRq@BoRWRaQfFT016zoEHdUSCxiNkU3e3UrAkwxNqMYco7FSB0HLqgixDeSnnbiHE1zr2A/IY128lOGbHM7aSDZyRiPR8k45W4JhlXLAcxrqqqRXBoGRJMmLXjyk4VlidJkYe/YtoFbaaggmT4InxsxE7a2rt8uFvUyINgGBs@Q4ZxlIWvRo5RWkLSLxgLxgIv1RRixsEnLMVOxnuvjh1a42K8woswtnLUYtJv9b7G0HIAlQOAn4nLpZAZc7LkGjDOKZsIGuUlU8bF8kycAuQ1Uw2FehiZe2YaMZEZR/IjNiUVDsTM9CMKp0v6tihjJGTZ2CkKG5tmuDdLNqKUCFK2zFNsw7TOrdEFFpKcacQ/ENTAC84eR7cRdACyp6sUs2lMNxCOrS0KaWUyC1vizH@2FRFTqIBRTOJSsKV0Oknco8yUtqd@@nEmVCQDsLYkDk/lNZKQDINWyzJyL2DyQxAc0TCMcPginI6BYkBUk3HusMshte7LpPAaPqM5/I1CMQB@jfH3GYljcLnHAz9ApxWDmh64IikVijMZChP3pocpQ4RxYH5Dhci5cN7slOtnZhjQx5dofrwM3ATm1atyKRRaypRN1XBfhaVxDSvEHNID8@da6GxBpADl9QIcloFE1WFFAdHFyA3cnnHGjOhBxg/w/QNRwyPl7LJpkjMeBQhxmmN9IBf52gt6Itk606byqZUpHGIuCXdJvjd3B69F02PtUVc780cD7XPMYcgzyCfbcMAqMR4rMPsM6DzO5KzIU49po2fcdroZ4dfet74qlBLUe2z0TesX0DJ5NdRpibTxtBqLRolFfbhF6Hkgzsr@ehRyT9Vycd3VvLhr6jkw@e3KLnTxa6SdzW8q9pdnW43wM@ft6p2F8W7PwWDViygyd7TqPMEvB60MmTP6HFNdl25DTpiuMeTj9JRB4lNBD3FMih2MAJEH4ZLrUt7wfpn0rUZdbhfi/S8dnLHSO4EpmzAd7mUjfv30IfgoSV7d6HdWTDB/fm6O0Qr2pI4rbEmuM4XX/twNAhuPLJrs5iOZdkth3q@VR@mv2jauvMDdhRcc/Z6K3oKhcW8wNY2ZdZzUaSNAkxeZbWoCkqOTY3/H5NCY0GBBQe11rEy5kmNvRpMsZe8oCK7WxH750GpGLH/YTGkSpGksxU6rBVWgpywxKIHykDUWRpNFuC6Cv8cTnWDVugV9XRjbBrp@hivEXbxHiHCHk5uCvb1rsiebqbvZTw/m/I9R42rvDMoEBs@x9K3@Aryfd0ToE78QmRl2z7i2VxW8JBHDJJlqOQwy0/e4V1DvykQETENWYqZdO560UDx4Z/iYLAXBHt77OiiBJJgZ8BAUbMY6lqZna81dKhFXEtcgdXvOU8zqnYsc@keIWb/4Eph@URRAIHHr20tRpVft7cczJpCH9bHDjF7A67hJf04BIa/wo7HwUHIJuwSdQB2@5ZfpHmTm2YItUCwGrZ8m0KhXCARVNDqJVDnmQYaNW@ostL1btJUFeqIpVHDl7xemHrYHGaOaRtEjia9AghzHa6pc29UdcJp7Ay7EbxKAdEJFKSq/m6G1MYq/VnsQp0P30@entrHQBuVHmzHQ7MZVq0TqN3r@NtX//7vv169@ecRzVS29psgiBmqZdkeCcMRsz/sdq4GmzDidr9FFs5@MgyB8xqhjenhzdMjPQ1nXV1dGem9IX1nIPSkNprmLpOoDWR0RENbtalsQZ8sSG/oYkEt0llt1U3D26LVmqq9AAN3Rgo3k64fZhdo9TELzXlLYRoKdKIunw08djqoIaU3TmRO@1Yyj9lrMePIf7e79ic95Y7BexajUaSE5EoiRMssgLrfNfCwdSaX8HMHjsmavICv9oZFg6NY28tNVco6MsaPg9p3GU6Y/RWwAnufytBoKPTW77CmnMIZegE5GO0VqVuAYKhS1DVJwXfLVslJjmCn7sx9hiYcscLZNSjtAds9IIVB7TRbT1BNabD/NI47@hfG4K7ZpQ5IZuUWwKEFBI7dADayYA4AsUDCWyMxLU/YKAIKQweZzhja7AnNn57A/OlJWp@yycTTt52dwM@/v8KtY/FTwzMFMbcOQ@9o1pKPYFdoJO0ofL1CCSBXje18L8BdKewV@eajBa7dqnG8GpzIQk8OqUU660KYLphtVzvl7vj7JcYu2SoHChq9NcaBvm2HeZKN9K776JtC7a9p3@NZuwdZEESrrsGhTaZ1T9kV1FTVKAJ8JpTSPWVQ2gU/x162wKDBZqBedo3mA@ikbGrd7UOJWTRBlZDsdfXyBeZAh1tAh9tBR1tARx1Q615PPExOT7yzTk@2bXvKDjQDHCOJyLdIPRq2aa8uZDZlWg@8wNrCg8L2lKeflBhh@gR8IhvGhIK8p1mAktAX/zrDAbgKL0ggtLCGHNhUxsH9SVsjbqKJC6wRZpqSCQW9e29nhomgPm7kMY2o@tG8DIEeD1PtbGWTGSAQbyjQsIS/gnIJk648868IqDGOISB24D3Wi1jvqOc7HnA9u8M4HmpVHq27HfyQGRmn45Ec@Yr4BNAL1op6n/TQ2NyTYXjvvW/cGA7evveVjsvlJn91i3lrZqhv8vwVYJtOjfULLb7nMfbtL0BTB0Hlgi61ABoC7veCUs4p63143yO34q8ggxBVKqeeqOI1KaGPMGmTNbgOW1xKpfX1OqLt5S5e6yDBeL8Sad/trdCpA3XpYR6TMDBhHW7J/Tln3FJtUp9RuwpvcEwiem@9rbuKC66rN@zFce8FcqWjnmiShVgC4UgEGVWrPD6LnBMAaDJY/D00vz1TfzL6VNvQG0dMb4wWwfTe4aYG66PG4R03szuRtt9lM6f9nQHLxMAbQ2cUuKd0ZuM5ImPi@VvKd/WljY3sSvAKJdgJj3SN2SZkfjGL96CUveuXg7zAKWd6BV40oanQrZOzMlPj2DwOS@8ZhrDI1DNVezElC1IZ4iIpA7i6CDM2cBBPkTmeDb20lYW1HPgqMqOiu8Pgqh9SfMd6j0rPvzz/hp2twOg/Uh3Yz/a3F4CTS6qjJrZ4srVS5tVN2Vq5RMXSpFsoUZk0EfS7truJCP5o@OnElDG69rm0T8POE1U2lwIzNsp8J5fJPuW6xb7LhnYPKMOd1AEloTaXvZztHugBk7NeVnbAZKeXlJNa3GZRFWEamgLRJzPIOynrnEySnZ2vlEstw5BPFKLDr6igzvtli0mU7GNGdglblICGSVjg285OCVjY5yE9j9zzCJ6nJ6WOwmTSOHt6kISXW4YnCbFiMck25wJUs/4ivMRICdoDBG84gMvcxSs00NKYekl2nmAM2gSgWbJdBLgKwLvvHgCVFeBYAUKef9s9IAUqJrP@IirDYHqi0wudVxSaAvBRNyFGEdRG5cIgNvYQcwBR0SI2Dq8otc/7M7IcGHxK4qxeirAK0Dp2h2AXH8EafsDgN61S2wkyxax@QUe3SnKeFn1ezdW@LrhfvqXXWQ5C1yB51mm3@H1acBiuWsMJvxvR@WUc2dcb7f@v41o6s@w7n/n1xsXD9YBrFyjXA67dvTzAjmt3K9cCrt@ZrAGC33soPo0@Az4Nb@fT4Nfm0/h6wBg@h/D34fgU293ux6fRH4BPN1OlOYWfB@KT2Q1/sweQ5W18cqCP3urL91bxo7d69FaP3urRW/0K2vWH8VbjR2/12Xir0WfgrYa/hbe69gzvxZg7IHyXfY7uQs@9RH6HQ0cPhPzw90B@/EDIj3475OP29bpfhLxzLXdzqw@EvDXTOxnprfvcyIRH8/3izXfwe5rvQyjRnfKv@8AcDX43UnQ4v9ls2xcgb9tnwI7YraTgwzopoWns/tW@4@b1cyN9cWhfGKoXIq30a0N6zY75t6r0/pC9GNSvFZl/4@jvGNiXBtwbGd6LixxfOKT/cYHIy3rVXaP/6SK@IAJI9s3UG3zfo9CtZvvmC82b18IL1gLaWzaax7d4YJbA/FdmaFITg/MA5l/OlVVa1Ga6HafRrOiH/u2cfuOqnVQeymEYrK9za8z9X1p8/D8 "Kotlin – Try It Online")
] |
[Question]
[
# Note
This is the encryption challenge. The decryption challenge can be found [here](https://codegolf.stackexchange.com/questions/209945/lets-decrypt-it).
# Challenge
The challenge is to encrypt a given string, using the rules as specified below. The string will only contain **lowercase alphabets**, **digits**, and/or **blank spaces**.
# Equivalent of a Character
Now, firstly you would need to know how to find the "equivalent" of each character.
If the character is a consonant, this is the way of finding it's equivalent:
```
1) List all the consonants in alphabetical order
b c d f g h j k l m n p q r s t v w x y z
2) Get the position of the consonant you are finding the equivalent of.
3) The equivalent is the consonant at that position when starting from the end.
```
eg: 'h' and 't' are equivalents of each other because 'h', 't' are in the 6th position from start and end respectively.
The same procedure is followed to find the equivalent of vowels/digits. You list all the vowels or the digits (starting from 0) in order and find the equivalent.
Given below is the list of the equivalents of all the characters:
```
b <-> z
c <-> y
d <-> x
f <-> w
g <-> v
h <-> t
j <-> s
k <-> r
l <-> q
m <-> p
n <-> n
a <-> u
e <-> o
i <-> i
0 <-> 9
1 <-> 8
2 <-> 7
3 <-> 6
4 <-> 5
```
# Rules of Encrypting
1. You start moving from the left and go towards the right.
2. If the character is a consonant/digit, then its equivalent is taken and if it is a blank space, then a blank space is taken.
3. If the character is a vowel, you take it's equivalent and start to move in the opposite direction. For example, if you are moving right and encounter a vowel, encrypt that character then skip to the rightmost unencrypted character and begin encrypting in the left direction, and vice versa.
4. You shouldn't consider a character in the same position twice. The steps should be followed until all the characters in the input are covered.
5. The total number of characters in the input(including blank spaces) should be equal to the total number of characters in the output.
**Please note that the encrypted characters appear in the output in the order in which they were encrypted.**
Now let me encrypt a string for you.
```
String = "tre d1go3t is"
Moving left to right
"t" -> "h"
"r" -> "k"
"e" -> "o"
Vowel encountered. Now moving right to left.
"s" -> "j"
"i" -> "i"
Vowel encountered. Now moving left to right.
" " -> " "
"d" -> "x"
"1" -> "8"
"g" -> "v"
"o" -> "e"
Vowel encountered. Now moving right to left.
" " -> " "
"t" -> "h"
"3" -> "6"
Output -> "hkoji x8ve h6"
```
# Examples
```
"flyspy" -> "wqcjmc"
"hero" -> "toek"
"heroic" -> "toyike"
"ae" -> "uo"
"abe" -> "uoz"
"the space" -> "htoo jmuy"
"a d1g13t" -> "uh68v8x "
"we xi12" -> "fo78i d"
"this is a code" -> "htioj ixej uy "
```
You may also choose to use uppercase alphabets instead of lowercase.
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 22 bytes
```
vćžN‡žM‡žh‡D?žMsåiR
```
[Try it online!](https://tio.run/##MzBNTDJM/f@/7Ej70X1@h5seNSw8us8XSmeAaRd7oEjx4aWZQf//lxSlKqQYpucblyhkFgMA "05AB1E – Try It Online")
or as a [Test suite](https://tio.run/##MzBNTDJM/V9TVln5v@xI@9F9foebHjUsPLrPF0pngGkXe6BI8eGlmUH/a2sPbbP/n5ZTWVxQyZWRWpTPlZjKlZiUylWSkapQXJCYDOQppBimGxqXcJWnKlRkGhoBpTKLFYAoUSE5PyUVAA)
**Explanation**
```
v # for each char in input
ć # extract the head of the current string (initially input)
žN‡ # transform consonants
žM‡ # transofrm vowels
žh‡ # transform numbers
D? # print a copy of the current char
žMsåi # if the current char is a vowel
R # reverse the rest of the string
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~173~~ ... ~~166~~ ~~156~~ ... ~~124~~ 123 bytes
-28 byte Thanks Arnauld
```
f=([q,...s])=>q?(c="aeioubcdfghjklmpqrstvwxyz",t=c.search(q),q=="0"|+q?9-q:~t?c[(t<5?4:29)-t]:q)+f(~t&&t<5?s.reverse():s):s
```
[Try it online!](https://tio.run/##TZDdjoIwEIXveYpJY0yJgKvuuqiLPIgxsdYiBbT2RwRdfXW2mA2azM18Z87JzGSkJJoqfjL@UexY0yQRXkkvCAK9dqOljDGNEGFcnLd0l@zTLC8OJ6m0KS9VfUWeiWigGVE0xdL1ZBShD/Q7kPHMl/OHiekKm5@v@HM@nrm@Wc@lO0jww/T7LdWBYiVTmmF3rm01C6ckCghEsEJGMdiN9mJigGvkDYfgLwGlucg4VGHJIJ0iByVFrU91J18kzQ7U8pQp0VEjWP7POH2jNc@Z5YR17CzafvsOrpaYlIE@EfriqRECssO5bufbPUcT8zKl07AMK7DahUHFR@NOSsR3yGH3zOTaXmavpfbvb8FcZMArlsG5tgnrheMkQgFuP8NBJEBcx1qOWhQsKMQeb1Dvxu/o6e7dEszdO9q4C2j@AA "JavaScript (Node.js) – Try It Online")
In the first iteration the `String` will be changed to `Array`, and subsequent iterations will continue to use `Array`. Voilà!
Original Approach (166 bytes):
```
f=(s,i=0,r=s.length,d=1,c="bcdfghjklmnpqrstvwxyz",v="aeiou")=>(d^=!!(t=~v.search(q=s[d?i:r])),q<"0"|q>"9"?c[20-c.search(q)]||v[5+t]||q:9-q)+(i<r-1?f(s,i+d,r-!d,d):"")
```
[Answer]
# C, 196 bytes
```
#define C(k,m)for(i=m;i--;)k[i]-c||putchar(k[m+~i],r^=m==5);
r;p(c,i){C("bcdfghjklmnpqrstvwxyz",21)C("0123456789",10)C("aeiou",5)C(" ",1)}f(S){char*s=S,*t=s+strlen(s);for(r=1;s<t;)p(r?*s++:*--t);}
```
[Try it online!](https://tio.run/##dY/LboMwEEX3fIXlbmwwUkxKX67VRT4hyyiViDEw5VnbaZIm9NcpLLpzZzU6d@bOXBWXSk3TXa4L6DTakJq1tOgNAdkKiGNB6x3sY3W7DUenqsyQetdGP7Bn5l22UqZUBEYMRDGg1w3BB5UXZfVRN203fBrrvk7nyzdmCaezuOLJ@j59eHx6xoyvFpJp6I@YpUuPZkjHgmzpdTkUWrlloZM2ss40uiOWiuUxI7mwr07QgZi30EbRSxjHjopxgs6hNoOO0OAaoLkKgp3RKOdlv3YILKZiTmEJnpu/gaK52OHiUypt@v84KJ@SaS89eLGrNLJDpvw7y9N87XzaSaMz8MTvCXbOiTKk@nwxDsbpFw)
[Answer]
# [J](http://jsoftware.com/), 132 bytes
```
f=:3 :0
c=.(u:97+i.26)-.v=.'aeiou'
d=.u:48+i.10
g=.;"0|.
a=.''
while.*#y do.a=.a,{.y rplc(g c),(g d),g v
y=.|.^:({:a e.v)}.y
end.a
)
```
[Try it online!](https://tio.run/##VYvdisIwEIXv5ymG9SLNWodWZVcjeZWFmEzbSNkUa6tBffZubsQuDIf5zs9pmiqtNqgKsJqyQe2/l57WX3JFoyZh2IdBgNM0qO0uJWUBtabDR/EgMKkg4Nr4lulzEdEFSpbJ7xTx3LU2q9HKPKmTeY0jRE0P@lHZXRlkGuWTIvCvIwNyYtsErFBUbey7KODFDZ/Df/L2zYZn/3EGl4ax74yd5@jKutxc3s6V8ebL9Xzle0xn0AbHYvoD "J – Try It Online")
A verbose explicit verb this time.
Explanation:
`c=.(u:97+i.26)` makes a list a-z
`v=.'aeiou'` makes a list of vowels
`-.` removes the vowels from the list of letters
`d=.u:48+i.10` makes a list of digits
`g=.;"0|.` a utility verb for creating a list of boxed pairs of replacement symbols
```
g d
┌─┬─┐
│0│9│
├─┼─┤
│1│8│
├─┼─┤
│2│7│
├─┼─┤
│3│6│
├─┼─┤
│4│5│
├─┼─┤
│5│4│
├─┼─┤
│6│3│
├─┼─┤
│7│2│
├─┼─┤
│8│1│
├─┼─┤
│9│0│
└─┴─┘
```
`a=.''` a list to store the result
`while.*#y do.a=.a,{.y rplc(g c),(g d),g v` while the length of the list is > 0 take a symbol, replace it and append it to the result
`y=.|.^:({:a e.v)}.y` drop one symbol from the beginning of the list and if the symbol is a vowel, reverse the list
`end.` ends the `while` loop
`a` returns the result
[Answer]
# [Clean](https://clean.cs.ru.nl), ~~221~~ ~~206~~ ~~198~~ ~~190~~ ~~186~~ 178 bytes
```
import StdEnv
r=reverse
l=['bcdfghjklm01234aeou56789pqrstvwxyz']
$s#(a,b)=span(\e=all((<>)e)['aeiou'])s
|s>[]=[j\\e<-a++b%(0,0),i<-['in ':l]&j<-['in ':r l]|e==i]++ $(init(r b))=s
```
[Try it online!](https://tio.run/##Pc4/T4QwGIDxnU/RRLRtgITz/B96kw4mbjeWDi/wHhZLwbagZ@6zW29yfKbf0xoEG8epWwySEbSNepwnF8g@dC92TZxwuKLzmBghadN2h/59@DBjubne3gBOy@3d/cPj/Ol8WL@@jz9UJam/YJA3XPgZLKtRgDGMVTuOXFJAPS1UcZ@c/E4qIYe6xqqALGsuWZmXPNdVIam2hD4ZdTX8hyNGnVAIrbKMpExbHZgjDT8zcR/gfCxISiQNDkm36adtINpTFX/bg4Hex@L1LT4fLYy69X8 "Clean – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 24 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
╥j•td╢Ä;Sµ*ûⁿvÉ╫î▓J o╩π╗
```
[Run it](http://stax.tomtheisen.com/#c=%E2%95%A5j%E2%80%A2td%E2%95%A2%C3%84%3BS%C2%B5*%C3%BB%E2%81%BFv%C3%89%E2%95%AB%C3%AE%E2%96%93J+o%E2%95%A9%CF%80%E2%95%97&i=tre+d1go3t+is&a=1)
Here is the ascii representation of the same program.
```
VcGVdGVvGwB]qVvs#!Hv*c}cr\$|t
```
It translates each character class first, then begins a while loop. In the loop, it outputs the next character, and conditionally reverses the rest of the string if a vowel is encountered.
```
VcG Push lowercase consonants and jump to trailing }
VdG Push digits and jump to trailing }
VvG Push lowercase vowels and jump to trailing }
wB]qVvs#!Hv*c While; run this block until popped value is falsy
B] Split first character off string
q Output with no newline; keep on the stack
Vvs# 1 if letter is a vowel, 0 otherwise
!Hv Not, Double, then Decrement
-1 for vowels, 1 otherwise
* Multiply string. -1 causes reversal
c Copy value to be popped as while condition
} Jump target from above. Return when done.
cr\$ Copy, reverse, zip, and flatten.
|t Translate: use string as a character map
for replacements
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~43~~ 39 bytes
```
hX∧Ḅ;Ṿ,Ị,Ṣ∋C↔;Cz∋[X,H]&{h∈Ṿ&b↔|b}↰↔,H↔|
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3wPyPiUcfyhztarB/u3KfzcHeXzsOdix51dDs/apti7VwFZEVH6HjEqlVnPOroACpRSwJK1CTVggxpm6LjAeL9/x@tlJZTWVxQqaSjlJFalA@lMpOBjMRUEJEEIksyUhWKCxKTwSIKKYbphsYlQGZ5qkJFpqERWEFmsQIQJSok56ekKsUCAA "Brachylog – Try It Online")
I only bothered finishing this grand mess because I'm struggling to make Jelly cooperate...
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~78~~ 69 bytes
```
T`b-df-hj-maed\oup-tv-z`Ro
/[aeiou]/{*>0L`.*?[aeiou]
0`.*?[aeiou]
V`
```
[Try it online!](https://tio.run/##TYuxCsIwFEX39xVZBCmkbeyuo4uTiIsV8pq8mhQ1pUnV6sfHKA4uF8499w4U7BVFzGf1fC3jTjZct9x0/IKkazf2PNz4U24dFAck68Zj8cqW5Ubm2epXQPkPsJcxhoGYFidXBWY9tOfJ9xMYGtw3rAIkwIYgGGK@R5XosxdVgDuxhxWLpKxPZ4ZMOU1v "Retina – Try It Online") Link includes test cases. Explanation:
```
T`b-df-hj-maed\oup-tv-z`Ro
```
Swap each character with its equivalent. The `Ro` causes the string to transliterate to its reverse. The middle consonant `n` and vowel `i` map to themselves so don't need to be listed. The first 10 consonants are listed first and the last 10 last so that they transliterate to each other. The first and last two vowels then surround the digits. (The `o` is normally special so it has to be quoted here.)
```
/[aeiou]/{
```
Repeat while a vowel remains.
```
*>0L`.*?[aeiou]
```
Output the text up to the vowel.
```
0`.*?[aeiou]
```
Delete the text up to the vowel.
```
V`
```
Reverse the remaining text. When there are no vowels left, this is then implicitly output, however for the purposes of the test cases, the header outputs the text at the end of each line.
] |
[Question]
[
# The Challenge
Given a string indicating the symbolic notation of UNIX permission of a file and its ownership (user ID and group ID), decide whether a given user `A` has permission to read / write / execute it.
*[Related](https://codegolf.stackexchange.com/questions/93099/decode-the-chmod).*
## Permissions in UNIX system
In UNIX, every file has three classes of permissions (**user**, **group** and **others**) and ownership, including which user and which group it belongs to.
The symbolic notation consists of ten characters. The first character is not important in this challenge. The remaining nine characters are in three sets of three characters, representing permissions of user, group and others class. Characters in each set indicates whether reading / writing / executing is permitted. If permitted, it will be `r`, `w` or `x`. Otherwise, it will be `-`.
Note that *setuid*, *setgid* and *sticky bit* may change the third character of each set to `s`, `S`, `t` or `T`. Here's a simple rule: if the character is lowercase letter, then the permission is set; otherwise, it is not.
(For the details of symbolic notation of permissions, please refer to [here](https://en.wikipedia.org/wiki/File_system_permissions#Symbolic_notation).)
Every user has its user ID, and every group has its group ID. All IDs will be non-negative integers. A user will belong to at least one group. If a user `A` want to get access to a file, the system will check their permissions as follows:
* If the file belongs to user `A`, check the permissions of **user** class.
* If the file doesn't belong to `A`, but `A` belongs to the group which the file belongs to, check the permissions of **group** class.
* Otherwise, check the permissions of **others** class.
However, there is one exception: if the user ID is 0 (superuser), they have permission to do **anything**!
# Specifications
* Your program / function should take these as input in any reasonable format:
+ Permissions **in symbolic notation**.
+ User ID and group ID which the file belongs to.
+ The user ID of `A`, and a list of group IDs which `A` belongs to.
+ Type of access. You can use any three different one-digit or one-character values for read, write and execute.
* Return / output a truthy value if `A` has permission to access the file, or a falsy value if not.
* You can assume that the first character of the notation will always be `-` (regular file).
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest in bytes wins!
# Test Cases
The format here is `[permissions, user ID of file, group ID of file, user ID of A, group IDs of A, type(r/w/x)]`.
```
[-rwx------, 13, 15, 13, [15, 24], r]: True # user
[-rwxr-xr-x, 13, 24, 24, [15, 24], w]: False # group
[-rwxr-Sr-T, 13, 15, 24, [15, 35], x]: False # group
[-rwsr-xr-t, 13, 15, 24, [24, 35], x]: True # others
[----------, 13, 15, 0, [0, 1, 2], r]: True # superuser
[----------, 13, 15, 1, [0, 1, 2], r]: False # others
[----rwxrwx, 13, 15, 13, [15, 24], r]: False # user
```
[Answer]
# JavaScript (ES6), ~~61~~ ~~51~~ 50 bytes
Takes 6 distinct parameters as input, in the order described in the challenge. Expects the last parameter to be `1` for *read*, `2` for *write* or `3` for *execute*. Returns `0` or `1`.
```
(p,u,g,a,G,P)=>!a|p[u-a?6-3*G.includes(g)+P:P]>'Z'
```
### Test cases
```
let f =
(p,u,g,a,G,P)=>!a|p[u-a?6-3*G.includes(g)+P:P]>'Z'
// p u g a G P
console.log(f('-rwx------', 13, 15, 13, [15, 24], 1)) // True (user)
console.log(f('-rwxr-xr-x', 13, 24, 24, [15, 24], 2)) // False (group)
console.log(f('-rwxr-Sr-T', 13, 15, 24, [15, 35], 3)) // False (group)
console.log(f('-rwsr-xr-t', 13, 15, 24, [24, 35], 3)) // True (others)
console.log(f('----------', 13, 15, 0, [0, 1, 2], 1)) // True (superuser)
console.log(f('----------', 13, 15, 1, [0, 1, 2], 1)) // False (others)
console.log(f('----rwxrwx', 13, 15, 13, [15, 24], 1)) // False (user)
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~76~~ ~~70~~ ~~67~~ ~~63~~ ~~59~~ ~~58~~ ~~56~~ ~~55~~ ~~52~~ ~~49~~ 48 bytes
```
lambda p,u,g,A,G,t:A*'_'<p[~(u==A)*3*(g in G)-t]
```
[Try it online!](https://tio.run/##hZG9DoIwEIB3n@ISB37SJgK6GBlY5AFkU2MwVjRRaK5t0MVXx1ZNVTB46bW3fN9drvwqD1UZNvt41Zzy83aXAyeKFCQhKZHTxHc2zowvb66K48TzI98t4FhC6lG5bjgeSwl716FYX@gjHAJBpHPyfJemCMdrApEHQ8hQMQBdKMFw8IUjNeeFh@NnvvHQ4PP8JJjBC6wUb/MLpNlHe8tHE80Hf3jx6C/bvLnevB2/kgeG4ocg6xfYAToCGx@CkeZ1BlrVWaBQnGFri78cQdfRO4TZZH3p/0UrMP2bOw "Python 2 – Try It Online")
Takes type as `3` for read, `2` for write ,and `1` for execute
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 60 bytes
```
(p,u,g,U,G,t)->U<1|p.charAt(t+(u==U?0:G.contains(g)?3:6))>90
```
[Try it online!](https://tio.run/##nZJdb5swFIbv8yuOkCLhzSAIzaSFkqjaRTTto5PSXE27cIhDnRKw7EObqstvz8xHAaVMmmZh2eeYx@d9D@zZI3NyybP99uEsDjJXCHuTcwsUqfsuHDU5jQxF3Du6UYo9a5fpr0JjOJLFJjXnccq0hm9MZPAygldKZMjVjsUcfnB1EFqLPPt0z@OH6iWATZ6nnGUQlzl7hUpkCUhaclDUS1IvawplvevP5saEqzks6zyS0Nx06kpeFpJtDNHZlrSgCV3TJUXizNfX/m/pxvdM3aCN7@0iitYLb7Z04zxDY0XbCVkEsw@EzD9657Ar8piLLSDX@H@aaWucHyWPkW/JRUMU10WKEPXku3WT@g7Cilk9a@QHNy/QlUYM7mxr7HsaYBxsu@mUKXusCThzE003VTDOLArdlZanno5W2xFCax201RO1imEB1u0XC2Zgfb@9A7Ntv0TzS/R7dTDdbHr18xcwlehXx1UXLcfUdaph9PiBmdN6rX8zuwwnV4QC@BRQFbzx3tHKKZ@GnlzV8w09obBjqR7CV8q56xW/wINpiQd/wXVVHYfxctvib7W3o0eD19JmZyxPCB12Pkj7w/SAdDNK80/Hf2h7h59Gp/Mf "Java (OpenJDK 8) – Try It Online")
The mapping for the type is the following: `1` means `r`, `2` means `w` and `3` means `x`.
[Answer]
# Pyth, ~~22~~ 21 bytes
```
|!Q}@@c3tw*nEQ-2}EEEG
```
[Try it online.](http://pyth.herokuapp.com/?code=%7C%21Q%7D%40%40c3tw%2anEQ-2%7DEEEG&input=13%0A-rwx------%0A13%0A15%0A%5B15%2C+24%5D%0A0&test_suite_input=13%0A-rwx------%0A13%0A15%0A%5B15%2C+24%5D%0A0%0A24%0A-rwxr-xr-x%0A13%0A24%0A%5B15%2C+24%5D%0A1%0A24%0A-rwxr-Sr-T%0A13%0A15%0A%5B15%2C+35%5D%0A2%0A24%0A-rwsr-xr-t%0A13%0A15%0A%5B24%2C+35%5D%0A2%0A0%0A----------%0A13%0A15%0A%5B0%2C+1%2C+2%5D%0A0%0A1%0A----------%0A13%0A15%0A%5B0%2C+1%2C+2%5D%0A0%0A13%0A----rwxrwx%0A13%0A15%0A%5B15%2C+24%5D%0A0&debug=0&input_size=6) [Test suite.](http://pyth.herokuapp.com/?code=%7C%21Q%7D%40%40c3tw%2anEQ-2%7DEEEG&input=13%0A-rwx------%0A13%0A15%0A%5B15%2C+24%5D%0A0&test_suite=1&test_suite_input=13%0A-rwx------%0A13%0A15%0A%5B15%2C+24%5D%0A0%0A24%0A-rwxr-xr-x%0A13%0A24%0A%5B15%2C+24%5D%0A1%0A24%0A-rwxr-Sr-T%0A13%0A15%0A%5B15%2C+35%5D%0A2%0A24%0A-rwsr-xr-t%0A13%0A15%0A%5B24%2C+35%5D%0A2%0A0%0A----------%0A13%0A15%0A%5B0%2C+1%2C+2%5D%0A0%0A1%0A----------%0A13%0A15%0A%5B0%2C+1%2C+2%5D%0A0%0A13%0A----rwxrwx%0A13%0A15%0A%5B15%2C+24%5D%0A0&debug=0&input_size=6)
Takes input as six lines:
```
user id
permissions
file user id
file group
user groups
permission (0 = read, 1 = write, 2 = execute)
```
### Explanation
```
|!Q}@@c3tw*nEQ-2}EEEG Implicit: read user id to Q
!Q True if user id is 0, false otherwise
| If true, just return it
w Read permission string
- Omit first -
c3 Split in 3 parts
E Read file user id
n Q See if it doesn't equal Q
-> False (0) if user matches, true (1) otherwise
E Read file group
E Read user groups
} -> True (1) if group matches, false (0) otherwise
-2 Subtract from 2
-> 1 if group matches, 2 otherwise
* Multiply the two numbers
-> 0 if user matches, 1 if group matches, 2 otherwise
@ Take correct part of permission string
@ Take correct character of that part
} G See if it is in lowercase alphabet
```
[Answer]
# [Go](https://go.dev), 284 bytes
```
import(."unicode";."golang.org/x/exp/slices")
func X(P string,f,g,u,a int,s[]int)int{P=P[1:]
p,i:=0,0
for;i<3;i++{for j:= 0;j<3;j++{e:=0
if IsLower(rune(P[3*i+j])){e++}
p|=e<<(3*i+j)}}
if u==0{return 1}
p>>=a
if f==u{return p&1}else if Contains(s,g){return p>>3&1}else{return p>>6&1}}
```
[Attempt This Online!](https://staging.ato.pxeger.com/run?1=nZO7btswFIbRbuYzdCA0FFKtqy9Fa5teOhXoIKAdAhgeBIWS6dgky0ssQNGTdDEK5KHSve_RI9lNPNi9hNABxZ-H3xF_Ut--l2L_QKMIr4yRehJFubimpdgUoTZZfkOrfJXxkoa52EZfLdWGCa6jZPR-NB5E1yJgwSq7pYGkasu0hkkkYVlWUrzNGEdsK4Uy2Cm2xrm3pgje_Xjx6iC6oWM5a8s509CBklAnFKqMqohWMtIbllPteKiwPMdXboq1UYyXfuGXvvUzzLjx9WIJnQdRpyRdJJMlkj6bkNiPUSHUlM2GU9bv1_CO1xOC4-kalDUoFJIQK_BH_UnsqHKV5dRNF8M3rL9eel5N-_0GyTtCZzO3E72mafMtIXGtqLGK4wQy5nOStXpBiP2ty9dJQzeaYtA_CG7ACO1qv_QeE-bz4THnRHoLUnM06eXPHHw22EU9qdqtYoKZMBkMdxAVOvrSmux6uEYYWr6i-U0KJ6Ex7PUK9W4zhat2NepVAHiad51A7aqga46PkyHE-NBL5ePO1bpVBqPGQz04vTAF882Gu5UPSEJw4mG4NVZTdR6ugvY5wgejQ8jdv8HjDl4qYeUl-mcVfDn59I5endKH4-fSdfft5iK9HV2mH4wRZkWVPoN_bCf4-NR2GCRQ8c94beGPu2D-uQrJf1SI_7qB9gB21TMvTvx0cY63fb8_9L8A)
`rwx` is `012`.
### Explanation
```
import(."unicode";."golang.org/x/exp/slices")
func X(P string,f,g,u,a int,s[]int)int{
// load the perms
P=P[1:] // strip the leading char
p,i:=0,0
// for all chars in the string...
for;i<3;i++{for j:= 0;j<3;j++{
// if it's lowercase, bit-or it with its respective location in the perms variable
e:=0
if IsLower(rune(P[3*i+j])){e++}
p|=e<<(3*i+j)}}
// the perm variable is stored as
// 876543210
// xwrxwrxwr
// -o-|g|-u-
// other, group, user, with the lowest bit on the right.
if u==0{return 1} // superuser
p>>=a // constant offset based on the access type
if f==u{
// user's file
return p&1
}else if Contains(s,g){
// user's group's file
return p>>3&1
}else{
// other
return p>>6&1
}}
```
## Directly accessing the string, 145 bytes
```
import."golang.org/x/exp/slices"
func X(P string,f,g,u,a int,s[]int)bool{k:=0
if f==u{}else if Contains(s,g){k=3}else{k=6}
return u<1||P[a+k]>90}
```
[Attempt This Online!](https://staging.ato.pxeger.com/run?1=pZNLbtswEIZRdGWeYqCVhEii5UfRGFU3vYCBdhEgyIJRKInQgyofMQHHh-i6G6NADpWepiMpiL2w09dAxIikNN_8M-T3H4XcP3FKoTSm0ytKM3nHC1nnsTYsq7jLStYWPM5kQ79aro2QrabJ4nKxnNE7GYmoZPc86rhqhNa4STr8jRUcGiZaIppOKgNe3hjv0Zo8ev_0bVyLPaRg6FiqgjrKXUd1LTKuPZLbNoMrfw3aKNEWYR4WoQ0ZiNaE-voGXXArZb2tVumUiBzyNLXbHa81B5x9kq1BtPZ1WATbKp0PO_jybkcUN1a1YD8kDw_ra3ZR3Xy8nO7GxH6-fZOhNgM-mXSqh0EKQhp2keDCBocjwZhbL80PYEsALSt5Vq1Rv4ZVCldkcs8UOOgzJBOHMQ4f-F6kNi4azAshmeNYjr5TIQzStv3KbLELyASLFq-xAqZufRdizDQFoywPAPtlNVen46uof57jzxbj6DZ_Fj9nWKwBUChpu3OEzyr6cqRgILhjwnz5PwQ9aDBnCf3sPOGlRtKUXOkThBc7IkyPm4CTBKG_JWiLJ_9MK05Bkr-AHAr1mo6-HRv3j6fpgBg0PN-E_X70vwA)
Based on [@Olivier Grégoire](https://codegolf.stackexchange.com/a/149478/77309)'s answer, and `rwx` is also `123` here.
[Answer]
# [C (GCC)](https://gcc.gnu.org), 117 bytes
```
f(p,u,g,U,G,t,o)char*p;int*G;{t=t-'r'?t-117:1;if(o=u-U?6:0)for(;*G;++G)if(g==*G)o=3;return U==0|p[t+=o]>96&p[t]<123;}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=rZPRTsIwFIYvvKJPcYJRNtjCugEqtXLnHkC4wkXJ2MYS3ZauDSTIk3jDDQ-lT2O3McKiaFBP1vScnW5f_56e1437ELjuer0R3Ncv34SvJJrQAm2k2RrXYtWdTVgzIWHEmzZZcsr1BmsMuI7xRR-T0FdiKvTRoNc3VD9mCpGrWi1blYmA0qatxtQizOOCRTCi1HhJxrxFY-fmqncuXecamxZZFfD3k8fTqeeHkQdDJjzAqAxvJ0-pBwZCchvwPAkjRV2iWhbY445DEKot7bHhUNwl8g12qNnJHNOhYBDYWcLkJ75SP5vCfVTXQLo6my_03GSMLTm6xWxrIIWqQGmxGZXACqDdBpF67G88pmfPlmd2ipHx5gUvV7vjBSwWySeg1T0KeMf04Z7AErj4EVgIOxKY5gr5YWD1RGM-81haErP_50TAJdHMHKtIfUXc2R4RjG9qmIrEY_uF_C8orkCr51qV-YurIy0r5nxx-KpWiblCVNu2n0HQttHKbv8A)
] |
[Question]
[
*This is a [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") if you are not familiar with the format click the tag to go to the wiki. There will not be a robbers' thread for this question.*
# Cops
Your task as Cops is to select two sequences from the [Online Encyclopedia of Integer Sequences](http://oeis.org/) and write a program that takes the nth element of one sequence as input and outputs the nth element of the second sequence. You then make an answer including the code and omitting the sequences selected. Robbers will attempt to find the sequences you selected and if one manages to find the sequences you had in mind or some other sequences for which your program you must mark your answer as **Cracked**. If a robber informs you with a crack that you believe is not valid you may present a proof that it is not a crack. Otherwise you must mark it so.
As per the usual answers that have been uncracked for 7 days are eligible to be marked safe. A Cop may mark their answer as safe by revealing the sequences that they had in mind. Once safe an answer may no longer be cracked.
The goal is to minimize the byte count of your program while remaining uncracked.
## Example
The following Python code translates the nth element of [A000290](http://oeis.org/A000290) (the square numbers) into [A000217](http://oeis.org/A000217) (the triangular numbers):
```
lambda x:sum(range(0,int(x**.5+1)))
```
# Stipulations and Requirements
* If you choose a sequence that has not been proven to be finite you must output all terms that might exist not just the ones listed on the OEIS page
* As an exception to the previous rule languages without infinite precision integers do not have to output or input numbers outside of their range.
* The size of your input sequence must not have been proven to be smaller than the output sequence.
* Your input sequence must not have any repeat elements (otherwise the task is pretty much impossible)
* The OEIS includes an index on their page (the first number after the "OFFSET" header) by default this is your offset for n (n equals the index for the first element on the sequence) if you choose another index you must indicate so in your answer.
* If you choose a offset different from the one listed on the OEIS you must still map all elements in your input sequence to the corresponding element in your output sequence.
* If your program receives an input that is not in the input sequence it may do whatever it wishes (undefined behavior). However it is probably in your best interest for it to still output an integer.
* It is unsportsmanlike to intentionally make your code difficult to run, be it by making it time consuming to execute or through [non-free language selection](http://meta.codegolf.stackexchange.com/questions/7822/what-constitutes-a-free-language-for-cops-and-robbers). While I will enforce the latter I cannot objectively enforce the former. However I implore you, for the sake of fun, not to attempt the former as it makes the challenge specifically more difficult for those with weaker computers.
# Robbers
Your task as Robbers is to select uncracked, unsafe answers and find the sequences they map between. If you find solution a solution that works (not necessarily the Cops' intended solution) comment the sequences on the appropriate answer.
Robbers should not worry to much about verifying that two particular sequences are a solution, one should post a solution if it matches all of the entries on OEIS. If that is not the sequence that a cop had in mind the cop may offer a proof that it is incorrect or mark it as cracked if they cannot find one.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes (Cracked by @Wolfram)
```
+66%444µ111<µ¡
```
[Try it online!](https://tio.run/nexus/jelly#@69tZqZqYmJyaKuhoaHNoa2HFv7//x/IBwA "Jelly – TIO Nexus")
It should be fairly obvious what this does. In fact, for the benefit of the non-Jelly users, I'll even give an explanation:
## Explanation
```
+66%444µ111<µ¡
µ µ¡ Run the transformation
+66%444 "add 66, then modulo 444"
111< once if 111 is less than the input, zero times otherwise
```
The question is, why does it do this?
## Crack
The sequences in question were [A201647](http://oeis.org/A201647) and [A201647](http://oeis.org/A201647). They're finite, and differ only in the last 2 elements:
* 3, 5, 7, 9, 11, 15, 21, 165, 693
* 3, 5, 7, 9, 11, 15, 21, 231, 315
Thus, if the input is low, I leave it the same, and I simply fit a function to the transformation of the last two.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes (Cracked by @JonathanAllan)
```
ÆFḅÆdÆẸ
```
[Try it online!](https://tio.run/nexus/jelly#@3@4ze3hjtbDbSmH2x7u2vH/PwA "Jelly – TIO Nexus")
### What it does
```
ÆFḅÆdÆẸ Main link. Argument: n
ÆF Factor n into prime-exponent pairs.
Æd Compute σ, the number of divisors of n.
ḅ Convert each pair from base σ to integer.
ÆẸ Yield the integer whose prime signature (infinite sequence of all prime
exponents, including zeroes, in order) is equal to the result.
```
[Answer]
# Python 3, 256 bytes ([**Cracked!**](https://codegolf.stackexchange.com/questions/110142/lost-in-translation/110184#comment268374_110184))
```
from math import*
def p(i,m):
r=0;d=floor(log(i))
for y in range(d):r+=(pow(16,d-y-1)%(8*y+m))/(8*y+m)
o=-1;y=d
while r!=o:o=r;r+=pow(16,d-y-1)/(8*y+m);y+=1
return r
def q(n):r=4*p(n,1)-2*p(n,4)-p(n,5)-p(n,6);return floor((1-(-r%1)if r<0 else r%1)*16)
```
[Try it online!](https://tio.run/nexus/python3#VY5BbsMwDATP1iuUQwDSttCoSI3CKh8TQFIi1DJd1kGg17tqkh562uVhOLtF4azzab3olBeWtVU@RL1A6jOOqhE6OE9xYhaY@AwJUTWRRRedZi2n@RzA4ygdwcI3sEPvTTEW9/Deli4jvjyLapiMdZ/kXSGvmtslTUHLjnhkElcf/OP/MFc6snVGWK9SffdxXzBXIx3bBebeonm9lyOa33h7xIDuyTy2gzVgZG8xRS0fBx2m72qvd2sH3LYf "Python 3 – TIO Nexus")
Sorry if this code looks horrendous, I think this is my first Python golf. The casting in Python makes it easier to code.
[Answer]
# [Processing](https://processing.org/), 184 bytes, SAFE!
```
int x(int y){int b=TRIANGLES-MITER;for(int i=OVERLAY/BURN;i>#fffffe;b*=(int)pow(y,(MOVE-HAND+0.)/(int)sqrt(red(color(-1<<16))/(int)log(color(0)*color(-1)))),i-=QUAD/DARKEST);return b;}
```
A function that takes in an int and returns an int. As long as the input number is in `int`'s range, the program should work fine.
This isn't slow, just unreadable. Good luck!
---
I am surprised this submission has lasted this long. Oh well, at least it's the first safe submission :)
### [A000578](http://oeis.org/A000578) to [A000290](http://oeis.org/A000290)
In other words: the cubes to the squares.
### Explanation
While answering [No strings (or numbers) attached](https://codegolf.stackexchange.com/a/110021/41805), I discovered a list of Processing constants that represent ints. For example, `CORNER` has a value of `0`. The full list can be found [here](http://pastebin.com/7HEUjNga). To find the value of a constant, you can just `print` it.
Using this, I decided to swap certain numbers with combinations of these constants to obfuscate it. So, here's what you get when you substitute the constants with their respective int values.
```
int x(int y){int b=9-8;for(int i=512/8192;i>#fffffe;b*=(int)pow(y,(13-12+0.)/(int)sqrt(red(color(-1<<16))/(int)log(color(0)*color(-1)))),i-=16/16);return b;}
```
Even now, the full clear code isn't revealed. The colours are remaining. In Processing, colour variables have int values, for example white (`#ffffff`) is `-1`, `#fffffe` is `-2`, `#fffffd` is `-3`, and so on. This can be found by `print`ing the colour. So let's simplify the colours.
```
int x(int y){int b=9-8;for(int i=512/8192;i>-2;b*=(int)pow(y,(13-12+0.)/(int)sqrt(red(color(-1<<16))/(int)log(-16777216*-1))),i-=16/16);return b;}
```
We're about halfway there :) To understand the values, we need to simplify the numerical expressions.
```
int x(int y){int b=1;for(int i=0;i>-2;b*=(int)pow(y,(1.)/(int)sqrt(red(color(-65536))/(int)log(16777216))),i-=1);return b;}
```
Much clearer! Now let's simplify the logarithm.
```
int x(int y){int b=1;for(int i=0;i>-2;b*=(int)pow(y,(1.)/(int)sqrt(red(color(-65536))/(int)16.6...)),i-=1);return b;}
int x(int y){int b=1;for(int i=0;i>-2;b*=(int)pow(y,(1.)/(int)sqrt(red(color(-65536))/16)),i-=1);return b;}
```
Almost over! Now we have to figure out this `(int)sqrt(red(color(-65536))/16))` mouthful. `color(-65536)` is red, so `rgb(255, 0, 0)`. Now the `red()` function returns the value of the red component in the argument (which is a colour). So how much red is there in red? The answer is `255`. With that we get
```
(int)sqrt(255/16))
(int)sqrt(15)
(int)3.8...
3
```
Substituting this in the program results in:
```
int x(int y){int b=1;for(int i=0;i>-2;b*=(int)pow(y,(1.)/3),i-=1);return b;}
```
Yay, it's done!
```
int x(int y){ // y is the cube
int b=1; // variable that holds the final result
for(int i=0; // for-loop that
i>-2; // loops twice
b*=(int)pow(y,(1.)/3), // multiply b by the cube root of y
i-=1); // decrement the looping variable
return b; // finally return b
}
```
To sum it up, this returns the square (done by multiplying twice in the for-loop) of the cube root of the input number.
[Answer]
# Mathematica (or whatever) — [Cracked!](https://codegolf.stackexchange.com/questions/110142/lost-in-translation/110234?noredirect=1#comment268499_110234)
```
f[x_] := Quotient[ 366403414911466530559405368378193383110620062 -
755296348522256690003418238667147075159564695 x +
525778437135781349270885523650096958873079916 x^2 -
156594194215500250033652167655133583167162556 x^3 +
20861131421245483787723229627506507062999392 x^4 -
1181515772235154077024719095229309394979146 x^5 +
29382627265060088525632055454760915985604 x^6 -
308672970015057482559939241399297150364 x^7 +
1087516675449597417990589334580403666 x^8 -
312989984559486345089577524231879 x^9,
265451130886621254401938908479744271974400 ]
```
I know Mathematica is non-free software, but this function is trivial to port to whatever favorite language you want to run it in. It literally computes the value of the given degree-9 polynomial evaluated at the input integer, then takes the integer quotient of that value and the 42-digit number on the last line. For example, `f[100]` evaluates to `-3024847237`.
] |
[Question]
[
## Introduction
The *perimeter density matrix* is an infinite binary matrix **M** defined as follows.
Consider a (1-based) index **(x, y)**, and denote by **M[x, y]** the rectangular sub-matrix spanned by the corner **(1, 1)** and **(x, y)**.
Suppose that all values of **M[x, y]** except **Mx, y**, the value at index **(x, y)**, have already been determined.
Then the value **Mx, y** is whichever of **0** or **1** that puts the average value of **M[x, y]** closer to **1 / (x + y)**.
In case of a tie, choose **Mx, y = 1**.
This is the sub-matrix **M[20, 20]** with zeros replaced by dots for clarity:
```
1 . . . . . . . . . . . . . . . . . . .
. . . . . 1 . . . . . . . . . . . . . .
. . 1 . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . 1 . . . . . . . . . . . . . . .
. 1 . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . 1 . .
. . . . . . . . . . . . . . 1 . . . . .
. . . . . . . . . . . . 1 . . . . . . .
. . . . . . . . . . 1 . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . 1 . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . 1 . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . 1 . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
```
For example, we have **M1, 1 = 1** at the upper left corner, since **1 / (1 + 1) = ¬Ω**, and the average of the **1 √ó 1** sub-matrix **M[1, 1]** is either **0** or **1**; that's a tie, so we choose **1**.
Consider then the position **(3, 4)**.
We have **1 / (3 + 4) = 1/7**, and the average of the sub-matrix **M[3, 4]** is **1/6** if we choose **0**, and **3/12** if we choose **1**.
The former is closer to **1/7**, so we choose **M3, 4 = 0**.
[Here](https://i.stack.imgur.com/HQB48.png) is the sub-matrix **M[800, 800]** as an image, showing some of its intricate structure.
## The task
Given a positive integer **N < 1000**, output the **N √ó N** sub-matrix **M[N, N]**, in any reasonable format.
The lowest byte count wins.
[Answer]
# R, 158 154 141 bytes
Edit: Because the only `1` in the upper `2x2` submatrix is the top left `M[1,1]` we can start the search for `1s` when `{x,y}>1` so no need for the `if` statement.
```
M=matrix(0,n<-scan(),n);M[1]=1;for(i in 2:n)for(j in 2:n){y=x=M[1:i,1:j];x[i,j]=0;y[i,j]=1;d=1/(i+j);M[i,j]=abs(d-mean(x))>=abs(d-mean(y))};M
```
The solution is highly inefficient as the matrix is duplicated twice for each iteration. `n=1000` took just under two and a half hours to run and produces a matrix of `7.6` Mb.
**Ungolfed and explained**
```
M=matrix(0,n<-scan(),n); # Read input from stdin and initialize matrix with 0s
M[1]=1; # Set top left element to 1
for(i in 2:n){ # For each row
for(j in 2:n){ # For each column
y=x=M[1:i,1:j]; # Generate two copies of M with i rows and j columns
x[i,j]=0; # Set bottom right element to 0
y[i,j]=1; # Set bottom right element to 1
d=1/(i+j); # Calculate inverse of sum of indices
M[i,j]=abs(d-mean(x))>=abs(d-mean(y)) # Returns FALSE if mean(x) is closer to d and TRUE if mean(y) is
}
};
M # Print to stdout
```
Output for `n=20`
```
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15] [,16] [,17] [,18] [,19] [,20]
[1,] 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[2,] 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[3,] 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[4,] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[5,] 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[6,] 0 1 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 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[8,] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0
[9,] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0
[10,] 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0
[11,] 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0
[12,] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[13,] 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0
[14,] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[15,] 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0
[16,] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[17,] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[18,] 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0
[19,] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[20,] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
```
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 36 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn)
```
+`‚ź{ùîΩùîΩÀò>(‚ä£-‚åä`‚àò-)`<Àò‚åä0.5+(√ó√∑+)‚åúÀú1+‚Üïùï©}
```
[Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgK2Digbx78J2UvfCdlL3LmD4o4oqjLeKMimDiiJgtKWA8y5jijIowLjUrKMOXw7crKeKMnMucMSvihpXwnZWpfQoKRiAyMAoK)
Two observations:
* Minimizing distance of mean to `1/(x+y)` is the same as minimizing distance of sum to `x√óy/(x+y)`.
* At least up to 1000√ó1000, which is maximum size required in the challenge, there is no row or column with two ones.
The function performs three major steps:
`‚åä0.5+(√ó√∑+)‚åúÀú1+‚Üïùï©` Generate matrix **round(x√óy/(x+y))**.
`(⊣-⌊`∘-)`<˘` Calculate matrix **sum(M[x, y])**.
`+`⁼+`⁼˘` Convert that to the *perimeter density matrix* by performing *inverse cumulative sum* (`+`⁼`) on rows and columns.
This runs reasonably fast, generating the full 1000x1000 in ~60ms locally, but some less golfed version were a bit faster.
[Answer]
# [Python](https://www.python.org), ~~129~~ ~~119~~ ~~117~~ 115 bytes
* Replaced the loop with a list comprehension so everything can go on one line and can be lambda
* Replaced .append() with :=z+[]
* -2 bytes thanks to @ceilingcat for pointing out that `(1+a)*(1+c) = (-a-1)*(-b-1)`
* -1 bytes thanks to @ceilingcat for removing the 0 from .5
* -1 byte thanks to @thonnu for a more efficinet way to do `and z` at the end.
```
lambda x,z=[]:[z:=z+[~(i//x)*~(i%x)/(i//x+i%x+2)>=sum(z[k]&(k%x<=i%x)for k in range(i))+.5]for i in range(x*x)][-1]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZY1BCsIwEEX3PcVstJlGrRYEKcaLxCwqNhprorQpxC68iJuC6J28jakKgv7Nm3l8-Jf78WS3B9NeJVveaiuHs0e1z_RqnYEbNIyLlDcpayg_ExXHDiPPnsP49VF_0gQXrKo1aXgh-qTouTnrGvJQQgHKQJmZTU4UIh1NRWfV17rIoeDDifhM1xoYJOPAekiiMfjpa0wD8On07l93OZbKWBK6EJQEy1Wk6U5Avq9yCCEc5GbNPDH4dvE93rZvPgE)
Rust is no longer better than python. Port of my Rust answer. Outputs a flattened matrix
# [Python](https://www.python.org), ~~118~~ 111 bytes
```
def f(x,z=[]):
for i in range(x*x):z+=[~(i//x)*~(i%x)/(i//x+i%x+2)>=sum(z[k]&(k%x<=i%x)for k in range(i))+0.5]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZU_LCsIwELznK_ZSm22qLYIgxfgjpQfBRGNNWtoIsQd_xIsX_Sf_xsQHgs5ldodhZvd8a49225jL5Xqwcjy_N2shQVKXDryssCAgmw4UKAPdymwEdYnDYmC8PFGVZQ4Tz5HD7LkxP7IpLnl_0HQo62pE68gteHCEnPqboxBZPplV71qngcM0J9a3Ekl1apH8NOtwjUeQd_9yQNspY2nsYlASbKkSzXYViH0vIIY4FWbNPSP5evHV_3n_AQ)
Thanks to @xnor and @ceilingcat. Outputs my modifying the input in place.
[Answer]
# [Scala 3](https://www.scala-lang.org/), ~~565~~ ~~476~~ ~~460~~ ~~458~~ ~~447~~ 440 bytes
Golfed version. [Attempt this online!](https://ato.pxeger.com/run?1=dZHdasIwFMfZm5Rencyate5mGCMbuItdFC92KTKiTW1KPqRNh1V8kt3IYHuGPYtPs7QR2c0gJOfkd77yz8d3vWaS3Z9OX43Nhw_nm59HxYQOMp4Hih7emQw07WOwMPjVZi8aV5y5wwIiHU7pU1WxFpt8JtTC3S9BRxqRFGLkFk1IbioQk2ESNNoKV4-UfxzU99jTFNdSrDnEkRgkvvKO7rFiW3i7otIhz9p_2A4EghLRmLQXK-njM5rg-A7EoByMutk8Ezkw2EUZmjBo3YHigMuaB8mRpNiNzdm6AEOnB3P1JJ1uK-Fe73LlJEEhDn2Ka94DqSEM0RGRTkIGatzLs_B7J88yysYz06wkR1QxW2C2qiG7VVhyvbGFMwon8HxrhdGXN3qC8IbbefXs2jlhhwrnklnLNa4bhY7-Ay__ePocxd76BQ)
Saved 125 bytes (565->440) thanks to the comment of [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)
```
@main def m={val n=scala.io.StdIn.readInt();val M=Array.ofDim[Int](n,n);M(0)(0)=1;for(i<-1 until n;j<-1 until n){val z=M.slice(0,i+1);val x=z.map(_.slice(0,j+1));val y=z.map(_.slice(0,j+1));x(i)(j)=0;y(i)(j)=1;val d=1.0/(i+j+2);M(i)(j)=if(a(x,d)<a(y,d))0 else 1};M.foreach(o=>{o.foreach(l=>print(if(l<1)"."else 1));println("")});def a(m:Array[Array[Int]],d:Double)=math.abs(d*m.length*m.headOption.map(_.length).getOrElse(0)-m.flatten.sum)}
```
---
Ungolfed version. [Attempt this online!](https://ato.pxeger.com/run?1=lVNLTsMwEJVY5hSjrmygJoENqigSAhYsIhYsEUJu47SuHDtyXEiFOAmbCgkOxWVgHLvhu0FK4vjNvHnzsZ9emylX_GC9flm6cnj4tvUuq9pYBx3OpGFXrrjQzAqOi0sSM1mIqYOcSw2idUIXDZzUNTwkAHdcgYYxRGdCI5YjdmItXzFTnsnqGm03RO-C9g45SSk-6JIluC2NBSLhaAgZLLWTGJF2waNp8acp6LQYJGeNklNB0l2QsAMZZRWvye0nuuhQ-oW2-j-tJZKShU86jciqR7IvoQu_Zyns-Zp2uiD7NIkOeU-RJZCKuznjk4YUMIRKcE1aSuF4DL8NK4qWDIRqRNR_TPy7aZ81975L-bfGCSU8iLbPpnldj4-xDgq1lTi0ARvQEDrsM9orQICUJoMB3SgWogxZYZ5WtqMw6evw9ZO-oSM4M8uJ14nKvjWYyKnBMUJXITKZEnrm5r3D1KgfDnM8V5e1k0bH6QQGZTPhLu055owHqeNHQqm4wyPKmmXFnIlJ7HUNCqG3e5VQz2MS7kG8Duvn_TT8fQA)
```
import scala.io.StdIn.readInt
object Main extends App {
val n = readInt()
val M = Array.ofDim[Int](n, n)
M(0)(0) = 1
for (i <- 1 until n) {
for (j <- 1 until n) {
val x = M.slice(0, i + 1).map(_.slice(0, j + 1))
val y = M.slice(0, i + 1).map(_.slice(0, j + 1))
x(i)(j) = 0
y(i)(j) = 1
val d = 1.0 / (i + j + 2)
M(i)(j) = if (math.abs(d - mean(x)) >= math.abs(d - mean(y))) 1 else 0
}
}
for (row <- M) {
for (ele <- row) {
if (ele == 0) print(".") else print(1)
}
println("")
}
def mean(matrix: Array[Array[Int]]): Double = {
val rowCount = matrix.length
val colCount = matrix.headOption.map(_.length).getOrElse(0)
matrix.flatten.sum.toDouble / (rowCount * colCount)
}
}
```
[Answer]
# Python 2, 189 Bytes
There are no crazy tricks in here, it is just calculating as described in the introduction. It isn't particularly quick but I don't need to create any new matrices to do this.
```
n=input()
k=[n*[0]for x in range(n)]
for i in range(1,-~n):
for j in range(1,-~n):p=1.*i*j;f=sum(sum(k[l][:j])for l in range(i));d=1./(i+j);k[i-1][j-1]=0**(abs(f/p-d)<abs(-~f/p-d))
print k
```
Explanation:
```
n=input() # obtain size of matrix
k=[n*[0]for x in range(n)] # create the n x n 0-filled matrix
for i in range(1,-~n): # for every row:
for j in range(1,-~n): # and every column:
p=1.*i*j # the number of elements 'converted' to float
f=sum(sum(k[l][:j])for l in range(i)) # calculate the current sum of the submatrix
d=1./(i+j) # calculate the goal average
k[i-1][j-1]=0**(abs(f/p-d)<abs(-~f/p-d)) # decide whether cell should be 0 or 1
print k # print the final matrix
```
For those curious, here are some timings:
```
20 x 20 took 3 ms.
50 x 50 took 47 ms.
100 x 100 took 506 ms.
250 x 250 took 15033 ms.
999 x 999 took 3382162 ms.
```
"Pretty" output for `n = 20`:
```
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 1 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 0 0 0
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 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 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 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 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 0 0 0 1 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 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 0 0 0 0 0 0
0 0 0 0 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 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 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 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
```
[Answer]
# [Rust](https://www.rust-lang.org), 152 bytes
```
|z|{let mut b=vec![];for i in 0..z*z{b.push(((1+i/z)*(1+i%z))as f32/(i/z+i%z+2)as f32>=(0..i).map(|d|(d%z<=i%z&&b[d])as u8 as f32).sum::<f32>()+0.5)};b}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bZBLbsIwEIbXySkmkUDjpIQ0bSWUB8foBrEgEKtGeSBid-HE96jUDYv2UByid6hN0oqizmY03_wznt_vH0fR8tN5RmuoNqxGAp0NAGXBgca0RhmLlsmCzJbPxTbNm6ZcQvYpOJ0tzm-97DujrASHPHstts5qndDmCAxYDWEQSE92eXAQ7Qsi3vtsLoln8kQSsmmBPkRz1NAAPxrJMkM9yUhQbQ7Y73rcTWSaacV0mq92a6MSCxi0JGhFFcepGUPih8ETUUmuxvu-7MR4uZjhkMFjmNi_oNKAIieD5HBkNS9rB8f62gQfvmQI09hfNSzLYhSqFfO4v18PwLpsc9Dt4jSMlHvH9FaNFRRlW9xoANzxzZ9Qfyqw_2vc3qvs0fTpNORv)
Lots of wasted space due to needing `as f32` everywhere :(
[Answer]
## Racket 294 bytes
```
(define(g x y)(if(= 1 x y)1(let*((s(for*/sum((i(range 1(add1 x)))(j(range 1(add1 y)))#:unless(and(= i x)(= j y)))
(g i j)))(a(/ s(* x y)))(b(/(add1 s)(* x y)))(c(/ 1(+ x y))))(if(<(abs(- a c))(abs(- b c)))0 1))))
(for((i(range 1(add1 a))))(for((j(range 1(add1 b))))(print(g i j)))(displayln""))
```
Ungolfed:
```
(define(f a b)
(define (g x y)
(if (= 1 x y) 1
(let* ((s (for*/sum ((i (range 1 (add1 x)))
(j (range 1 (add1 y)))
#:unless (and (= i x) (= j y)))
(g i j)))
(a (/ s (* x y)))
(b (/ (add1 s) (* x y)))
(c (/ 1 (+ x y))))
(if (< (abs(- a c))
(abs(- b c)))
0 1))))
(for ((i (range 1 (add1 a))))
(for ((j (range 1 (add1 b))))
(print (g i j)))
(displayln ""))
)
```
Testing:
```
(f 8 8)
```
Output:
```
10000000
00000100
00100000
00000000
00001000
01000000
00000000
00000000
```
[Answer]
# Perl, 151 + 1 = 152 bytes
Run with the `-n` flag. The code will only work correctly every *other* iteration within the same instance of the program. To get it to work correctly every time, add 5 bytes by prepending `my%m;` to the code.
```
for$b(1..$_){for$c(1..$_){$f=0;for$d(1..$b){$f+=$m{"$d,$_"}/($b*$c)for 1..$c}$g=1/($b+$c);print($m{"$b,$c"}=abs$f-$g>=abs$f+1/($b*$c)-$g?1:_).$"}say""}''
```
Readable:
```
for$b(1..$_){
for$c(1..$_){
$f=0;
for$d(1..$b){
$f+=$m{"$d,$_"}/($b*$c)for 1..$c
}
$g=1/($b+$c);
print($m{"$b,$c"}=abs$f-$g>=abs$f+1/($b*$c)-$g?1:_).$"
}
say""
}
```
Output for input of 100:
```
1___________________________________________________________________________________________________
_____1______________________________________________________________________________________________
__1_________________________________________________________________________________________________
___________________________1________________________________________________________________________
____1_______________________________________________________________________________________________
_1__________________________________________________________________________________________________
_________________________1__________________________________________________________________________
_________________1__________________________________________________________________________________
______________1_____________________________________________________________________________________
____________1_______________________________________________________________________________________
__________1_________________________________________________________________________________________
____________________________________________________________________________________________________
_________1__________________________________________________________________________________________
____________________________________________________________________________________________________
________1___________________________________________________________________________________________
______________________________________________________________________________________1_____________
_________________________________________________________________1__________________________________
_______1____________________________________________________________________________________________
_____________________________________________________________1______________________________________
____________________________________________________1_______________________________________________
______________________________________________1_____________________________________________________
__________________________________________1_________________________________________________________
_______________________________________1____________________________________________________________
____________________________________1_______________________________________________________________
__________________________________1_________________________________________________________________
______1_____________________________________________________________________________________________
____________________________________________________________________________________________________
___1________________________________________________________________________________________________
____________________________________________________________________________________________________
____________________________________________________________________________________________________
____________________________________________________________________________________________________
____________________________________________________________________________________________________
________________________________1___________________________________________________________________
____________________________________________________________________________________________________
________________________1___________________________________________________________________________
____________________________________________________________________________________________________
_______________________1____________________________________________________________________________
____________________________________________________________________________________________________
____________________________________________________________________________________________________
______________________1_____________________________________________________________________________
____________________________________________________________________________________________________
___________________________________________________________________________________________________1
_____________________1______________________________________________________________________________
____________________________________________________________________________________________________
_____________________________________________________________________________________1______________
__________________________________________________________________________________1_________________
____________________1_______________________________________________________________________________
____________________________________________________________________________________________________
________________________________________________________________________________1___________________
______________________________________________________________________________1_____________________
___________________________________________________________________________1________________________
_________________________________________________________________________1__________________________
___________________1________________________________________________________________________________
____________________________________________________________________________________________________
____________________________________________________________________________________________________
_______________________________________________________________________1____________________________
______________________________________________________________________1_____________________________
____________________________________________________________1_______________________________________
___________________________________________________________1________________________________________
__________________________________________________________1_________________________________________
_________________________________________________________1__________________________________________
__________________1_________________________________________________________________________________
____________________________________________________________________________________________________
____________________________________________________________________________________________________
____________________________________________________________________________________________________
________________1___________________________________________________________________________________
____________________________________________________________________________________________________
____________________________________________________________________________________________________
____________________________________________________________________________________________________
____________________________________________________________________________________________________
________________________________________________________1___________________________________________
_______________________________________________________1____________________________________________
____________________________________________________________________________________________________
___________________________________________________1________________________________________________
____________________________________________________________________________________________________
__________________________________________________1_________________________________________________
____________________________________________________________________________________________________
____________________________________________________________________________________________________
_________________________________________________1__________________________________________________
____________________________________________________________________________________________________
________________________________________________1___________________________________________________
____________________________________________________________________________________________________
_____________________________________________1______________________________________________________
____________________________________________________________________________________________________
____________________________________________________________________________________________________
____________________________________________1_______________________________________________________
_______________1____________________________________________________________________________________
____________________________________________________________________________________________________
____________________________________________________________________________________________________
____________________________________________________________________________________________________
____________________________________________________________________________________________________
____________________________________________________________________________________________________
____________________________________________________________________________________________________
____________________________________________________________________________________________________
____________________________________________________________________________________________________
____________________________________________________________________________________________________
____________________________________________________________________________________________________
____________________________________________________________________________________________________
____________________________________________________________________________________________________
_________________________________________1__________________________________________________________
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 180 bytes
```
(a=SparseArray[{1,1}->1,{#,#},-1];({x,y}={##};If[(t=a[[##]])<0,s=0;Do[If[{i,j}!={##},s+=#0[i,j]],{i,#1},{j,#2}];l=s(q=1/x/y)-1/(x+y);r=l+q;a[[##]]=If[Abs@r>Abs@l,0,1],t])&[#,#];a)&
```
[Try it online!](https://tio.run/##LY5NT8QgGIT/CpakAfvWgh6RhiZe9GBM9ogcUFvtpl9LObQh/PaKGy8zkyeTyYzW/7Sj9f2nPTp5ECtPi3Vr2zhndx048FjWHAIGHKHkRpCwwR5lwDiK504TL63WGBtDHxmskomnWSceejjHm2sN1kJiphMwBhLHPEI4A76PRgxyJRfJq63aackrshU7FU4OxUX8z8o01nysytV/OgADbsAbmut0yQhL8@PN9ZNXJ5/s@2XuJ90sSzt9pQLK3qfMoBxVCpHX2Y12UJ16YKi6Q4GjskbZbQaIXRPKIjXHLw "Wolfram Language (Mathematica) – Try It Online")
Recursive approach: start from array filled with undefined `-1` items and `1` for first item.
For `n` 20-30 as faster, as Python.
Full version self-explained:
```
Clear[m];
n = 15;
arr = SparseArray[{1, 1} -> 1, {n, n}, -1];
m[x_, y_] :=
If[(current = arr[[x, y]]) < 0,
total = 0; Do[total += m[i, j], {i, x}, {j, If[i == x, y - 1, y]}];
tmp1 = total/x/y - 1/(x + y); tmp2 = tmp1 + 1/x/y;
arr[[x, y]] = If[Abs@tmp2 > Abs@tmp1, 0, 1]
, current
];
m[n, n];
StringJoin[Append[#, "\n"] & /@ (Normal@arr /. {1 -> "*", 0 -> " "})]
```
] |
[Question]
[
*(inspired by [this question](https://math.stackexchange.com/q/1886327) over on Math)*
### The Definitions
Given an `n x n` square matrix **A**, we can call it [`invertible`](https://en.wikipedia.org/wiki/Invertible_matrix) if there exists some `n x n` square matrix **B** such that **AB** = **BA** = **In**, with **In** being the identity matrix of size `n x n` (the matrix with the main diagonal `1`s and anything else `0`), and **AB** and **BA** representing usual [matrix multiplication](https://en.wikipedia.org/wiki/Matrix_multiplication) (I won't go into that here - go take a linear algebra class).
From that, we can call an `m x n` matrix **C** `totally invertible` if every `k x k` submatrix (defined below) of **C** is invertible for all `k > 1`, `k <= (smaller of m,n)`.
A submatrix is defined as the resulting matrix after deletion of any number of rows and/or columns from the original matrix. For example, the below `3x3` matrix **C** can be transformed into a `2x2` submatrix **C'** by removing the first row `1 2 3` and the middle column `2 5 8` as follows:
```
C = [[1 2 3]
[4 5 6] --> C' = [[4 6]
[7 8 9]] [7 9]]
```
Note that there are many different submatrix possibilities, the above is just an example. This challenge is only concerned with those where the resulting submatrix is a `k x k` *square matrix*.
### The Challenge
Given an input matrix, determine if it is totally invertible or not.
### The Input
* A single matrix of size `m x n`, in [any suitable format](http://meta.codegolf.stackexchange.com/q/2447/42963).
* Without loss of generality, you can assume `m <= n` or `m >= n`, whichever is golfier for your code, and take the input that way (i.e., you get a [transpose](https://en.wikipedia.org/wiki/Transpose) operation for free if you want it).
* The input matrix size will be no smaller than `3 x 3`, and no larger than your language can handle.
* The input matrix will consist of only numeric values from **Z+** (the [positive integers](https://en.wikipedia.org/wiki/Integer)).
### The Output
* A [truthy/falsey](http://meta.codegolf.stackexchange.com/a/2194/42963) value for whether the input matrix is totally invertible.
### The Rules
* Either a full program or a function are acceptable.
* [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins.
### The Examples
```
Truthy
[[1 2 3]
[2 3 1]
[3 1 2]]
[[2 6 3]
[1 12 2]
[5 3 1]]
[[1 2 3 4]
[2 3 4 1]
[3 4 1 2]]
[[2 3 5 7 11]
[13 17 19 23 29]
[31 37 41 43 47]]
Falsey
[[1 2 3]
[4 5 6]
[7 8 9]]
[[1 6 2 55 3]
[4 5 5 5 6]
[9 3 7 10 4]
[7 1 8 23 9]]
[[2 3 6]
[1 2 12]
[1 1 6]]
[[8 2 12 13 2]
[12 7 13 12 13]
[8 1 12 13 5]]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~26 24 23 20 19 17~~ 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 byte thanks to @miles (unnecessary for each, `€`, when taking determinants)
-2 bytes, @miles again! (unnecessary chain separation, and use of `Ѐ` quick)
```
ZœcLÆḊ
œcЀJÇ€€Ȧ
```
**[TryItOnline!](http://jelly.tryitonline.net/#code=WsWTY0zDhuG4igrFk2PDkOKCrErDh-KCrOKCrMim&input=&args=W1s4LCAyLCAxMiwgMTMsIDJdLAogWzEyLCA3LCAxMywgMTIsIDEzXSwKIFs4LCAxLCAxMiwgMTMsIDVdXQ)** or [all 8 tests](http://jelly.tryitonline.net/#code=WsWTY0zDhuG4igrFk2PDkOKCrErDh-KCrOKCrMimCsOH4oKs&input=&args=WwpbWzEsIDIsIDNdLAogWzIsIDMsIDFdLAogWzMsIDEsIDJdXSwKW1syLCA2LCAzXSwKIFsxLCAxMiwgMl0sCiBbNSwgMywgMV1dLApbWzEsIDIsIDMsIDRdLAogWzIsIDMsIDQsIDFdLAogWzMsIDQsIDEsIDJdXSwKW1syLCAgMywgIDUsICA3LCAgMTFdLAogWzEzLCAxNywgMTksIDIzLCAyOV0sCiBbMzEsIDM3LCA0MSwgNDMsIDQ3XV0sCltbMSwgMiwgM10sCiBbNCwgNSwgNl0sCiBbNywgOCwgOV1dLApbWzEsIDYsIDIsIDU1LCAzXSwKIFs0LCA1LCA1LCA1LCAgNl0sCiBbOSwgMywgNywgMTAsIDRdLAogWzcsIDEsIDgsIDIzLCA5XV0sCltbMiwgMywgNl0sCiBbMSwgMiwgMTJdLAogWzEsIDEsIDZdXSwKW1s4LCAyLCAxMiwgMTMsIDJdLAogWzEyLCA3LCAxMywgMTIsIDEzXSwKIFs4LCAxLCAxMiwgMTMsIDVdXQpd)
### How?
```
œcЀJÇ€€Ȧ - Main link: matrix as an array, M
J - range of length -> [1,2,...,len(a)] (n)
Ѐ - for each of right argument
œc - combinations of M numbering n
Ç€€ - call the last link (1) as a monad for €ach for €ach
Ȧ - all truthy (any determinant of zero results in 0, otherwise 1)
(this includes an implicit flattening of the list)
ZœcLÆḊ - Link 1, determinants of sub-matrices: row selection, s
Z - transpose s
L - length of s
œc - combinations of transposed s numbering length of s
ÆḊ - determinant
```
[Answer]
# Mathematica 10.0, 34 bytes
```
#~Minors~n~Table~{n,Tr@#}~FreeQ~0&
```
A 6-tilde chain... new personal record!
[Answer]
# MATL, 57 bytes
```
tZyt:Y@!"@w2)t:Y@!"@w:"3$t@:)w@:)w3$)0&|H*XHx]J)]xxtZy]H&
```
Of course, you can [Try it online!](http://matl.tryitonline.net/#code=dFp5dDpZQCEiQHcyKXQ6WUAhIkB3OiIzJHRAOil3QDopdzMkKTAmfEgqWEh4XUopXXh4dFp5XUgm&input=WzEgMiAzOzIgMyAxOzMgMSAyXQ)
Input should be in 'portrait' orientation (nRows>=nColumns). I feel that this may not be the most efficient solution... But at least I'm leaving some room for others to outgolf me. I would love to hear specific hints that could have made this particular approach shorter, but I think this massive bytecount should inspire others to make a MATL entry with a completely different approach. Displays 0 if falsy, or a massive value if truthy (will quickly become Inf if matrix too large; for 1 extra byte, one could replace `H*` with `H&Y` (logical and)). Saved a few bytes thanks to @LuisMendo.
```
tZy % Duplicate, get size. Note that n=<m.
% STACK: [m n], [C]
t: % Range 1:m
% STACK: [1...m], [m n], [C]
Y@ % Get all permutations of that range.
% STACK: [K],[m n],[C] with K all perms in m direction.
!" % Do a for loop over each permutation.
% STACK: [m n],[C], current permutation in @.
@b % Push current permutation. Bubble size to top.
% STACK: [m n],[pM],[C] with p current permutation in m direction.
2)t:Y@!" % Loop over all permutations again, now in n direction
% STACK: [n],[pM],[C] with current permutation in @.
@w:" % Push current permutation. Loop over 1:n (to get size @ x @ matrices)
% STACK: [pN],[pM],[C] with loop index in @.
3$t % Duplicate the entire stack.
% STACK: [pN],[pM],[C],[pN],[pM],[C]
@:) % Get first @ items from pN
% STACK: [pNsub],[pM],[C],[pN],[pM],[C]
w@:) % Get first @ items from pM
% STACK: [pMsub],[pNsub],[C],[pN],[pM],[C]
w3$) % Get submatrix. Needs a `w` to ensure correct order.
% STACK: [Csub],[pN],[pM],[C]
0&| % Determinant.
% STACK: [det],[pN],[pM],[C]
H*XHx% Multiply with clipboard H.
% STACK: [pN],[pM],[C]
] % Quit size loop
% STACK: [pN],[pM],[C]. Expected: [n],[pM],[C]
J) % Get last element from pN, which is n.
% STACK: [n],[pM],[C]
] % Quit first loop
xxtZy% Reset stack to
% STACK: [m n],[C]
] % Quit final loop.
H& % Output H only.
```
] |
[Question]
[
Or maybe it's not really a labyrinth, but still.
Rules:
1. **Input** is a two-line string, consisting of `*`, `1`, `x` and `X`. That string is a labyrinth to walk through. The lines have the **equal length**.
You could take the input as a string with `,` (comma) or any convenient separator between these two lines. Or you could take both lines as separate arguments to your function.
2. **Output** is the number of steps you have to take to exit the string (last step is the step which moves you out of the string).
3. You start in the top left corner (the higher line), **before** the first symbol.
4. For each step, you move forward by one symbol (from nth to (n+1)th *position*). Then, depending on the character you step on, the outcome is different. Here's what each char does:
* `*` - nothing. You just step on it normally.
* `x` - once you stepped on it, switch the line, but remain on the same horizontal distance from the beginning. For example, you stepped on the third position of the higher line, and met a lowercase `x` here. Then you immediately move to the lower line, but again at the third position.
* `X` - switch the line and go to the next position. The example is the same there, but you also move from the third to the forth position (thus you're on the second line at the forth position).
* `1` - just move forward by yet another position.
Once each character does its job, it's replaced with a space and no longer "works".
Examples follow.
1. **Input**:
```
x
*
```
As said before, you start before the first symbol of the first line. The first step moves you on letter `x` and this letter switches you to the second line. The letter `x` no longer functions as `x`, but replaced with `*`. This will be more relevant in the latter examples. You're now on an asterisk on the lower line, and it did nothing to you.
The second step is moving you forward and you exit the string, so the labyrinth is completed, and it took 2 steps.
**Output** `2`.
2. **Input**:
```
xX*
x1*
```
**1st step**: you move on `x`, which moves you on the `x` of the lower line. Here comes the rule which says that the used character is replaced with asterisk. Then you move back on the first line, but it's no longer `x` there, since it has been used and became an asterisk. So you move safely on this asterisk and the step is completed (you are now on the first position of the first line).
**2nd step**: you move on `X`, it pushes you to the lower line and then pushes you forward. You now reside on the third position of the second line (asterisk), having never visited the second position (which contains `1`).
**3rd step**: you move forward, exiting the string.
**Output**: `3`.
Test cases:
1. Input:
```
*1*
xxx
```
Output: `3`. (because `1` makes you jump on the third position). There you never visit the second line, but it's required part of the input.
2. Input:
```
*X*1*x
x*1xx*
```
Output: `4`.
3. Input:
```
1x1x
***X
```
Output: `3`.
4. Input:
```
1*x1xxx1*x
x*x1*11X1x
```
Output: `6`.
5. Input:
```
xXXXxxx111*
**xxx11*xxx
```
Output: `6`.
[Answer]
# Snails, 34 bytes
```
A^
\1r|\xud|\Xaa7},(\*|\xud=\x)r},
```
Expanded:
```
{
{
\1 r |
\x ud |
\X aa7
},
(\* | \x ud =\x)
r
},
```
For a path that takes N steps, the program finds one successful match for each traversal of 0 steps, 1 steps, ..., N - 1 steps.
[Answer]
## Haskell, ~~68~~ ~~66~~ 65 bytes
```
(a:b)#l@(c:d)|a<'+'=1+b#d|a>'w'=l#('*':b)|a>'W'=d#b|1<2=b#d
_#_=1
```
Function `#` takes both lines as separate parameters. Usage example: `"1x1x" # "***X"` -> `3`.
We just have to count the stars `*` we step on plus 1 for leaving.
```
(a:b)#l@(c:d) -- bind: a -> first char of first line
b -> rest of first line
l -> whole second line
c -> first char of second line (never used)
d -> rest of second line
|a < '+' = 1+b#d -- stepped on a *, so add 1 and go on
|a > 'w' = l#('*':b) -- x switches lines and replaces the x with *
|a > 'W' = d#b -- X switch lines and go on
|1<2 = b#d -- the rest (-> 1) simply walks forward
_#_=1 -- base case: the empty string counts 1 for leaving
```
Edit: @feersum saved a byte. Thanks!
[Answer]
# JavaScript (ES6), 119
```
l=>{z=-~l.search`
`,l=[...l+' '];for(n=p=0;(c=l[p%=2*z])>' ';p+=c>'X'?z:c>'1'?z+1:c>'0'?1:(++n,1))l[p]='*';return-~n}
```
*Less golfed*
```
l=>{
z=1+l.search`\n`;
l=[...l+' '];
for( n = p = 0;
(c=l[p%=2*z])>' ';
p += c>'X' ? z : c>'1' ? z+1 : c>'0'? 1 : (++n,1) )
l[p] = '*';
return 1+n
}
```
**Test**
```
f=l=>{z=-~l.search`
`,l=[...l+' '];for(n=p=0;(c=l[p%=2*z])>' ';p+=c>'X'?z:c>'1'?z+1:c>'0'?1:(++n,1))l[p]='*';return-~n}
[['x\n*',2]
,['xX*\nx1*',3]
,['*1*\nxxx',3]
,['*X*1*x\nx*1xx*',4]
,['1x1x\n***X',3]
,['1*x1xxx1*x\nx*x1*11X1x',6]
,['xXXXxxx111*\n**xxx11*xxx',6]
].forEach(t=>{
var i=t[0],k=t[1],r=f(i)
console.log('Test result '+r+(r==k?' OK ':' KO (expected '+k+')')+'\n'+i)
})
```
[Answer]
# TSQL(sqlserver 2012+), 276 bytes
**Golfed:**
```
DECLARE @i VARCHAR(99)=
'xXXXxxx111*'+CHAR(13)+CHAR(10)+
'**xxx11*xxx'
,@t BIT=0,@c INT=1,@ INT=1WHILE @<LEN(@i)/2SELECT @t-=IIF(a like'[1*]'or'xx'=a+b,0,1),@c+=IIF(a='*'or'xx'=a+b,1,0),@+=IIF(a='x'and'x'>b,0,1)FROM(SELECT SUBSTRING(d,@t*c+@,1)a,SUBSTRING(d,(1-@t)*c+@,1)b FROM(SELECT LEN(@i)/2+1c,REPLACE(@i,'X','q'COLLATE thai_bin)d)x)x PRINT @c
```
**Ungolfed:**
```
DECLARE @i VARCHAR(99)=
'xXXXxxx111*'+CHAR(13)+CHAR(10)+
'**xxx11*xxx'
,@t BIT=0,@c INT=1,@ INT=1
WHILE @<LEN(@i)/2
SELECT
@t-=IIF(a like'[1*]'or'xx'=a+b,0,1),
@c+=IIF(a='*'or'xx'=a+b,1,0),
@ +=IIF(a='x'and'x'>b,0,1)
FROM
(
SELECT
SUBSTRING(d,@t*c+@,1)a,
SUBSTRING(d,(1-@t)*c+@,1)b
FROM
(SELECT LEN(@i)/2+1c,REPLACE(@i,'X','q'COLLATE thai_bin)d)x
)x
PRINT @c
```
**[Fiddle](https://data.stackexchange.com/stackoverflow/query/511518/walk-the-labyrinth)**
[Answer]
# JavaScript, 211 bytes
I'm thinking about making a version that shows each step played after each other, displayed on a webpage.
```
(x,y)=>{t=0;l=0;n=1;while(t<x.length){c=(l?x:y);if(c[t]=='x'){l=!l;if(l){x=x.slice(0,t-2)+'*'+x.slice(t-1);}else{y=y.slice(0,t-2)+'*'+y.slice(t-1);}}if(c[t]=='X'){l=!l;t++;}if(c[t]=='1'){return n}
```
Used more bytes than I'd hoped to when replacing `x` with `*` because of JS immutable `Strings`. Suggestions to improve are appreciated, especially with the replacement part.
] |
[Question]
[
Alice and Bob are playing a little game. First, they draw a tree from a root node (indicated by a thick dot), with no internal nodes, with numbers at the leaves. Any node may have any number of children.
[](https://i.stack.imgur.com/eItFV.png)
We start at the root, and first to play is Alice (A). She must select one of the current node's children. Then it's Bob's turn, and he similarly selects a child node. This continues until a leaf node is reached.
When a leaf node is reached, the game is over. It is Alice's goal to end at a node with as large of a value as possible, and Bob's goal to end at a node with as small of a value as possible.
Given a tree in nested array form, return the value of the leaf that will be reached if both Alice and Bob play perfectly.
---
Examples:
```
18: [[67, [[100, [[67, 47], [86], 21, 16], [[46, [14], 35, 85], [71, [18, 63, 69], 99, 22], 3]]], [[18, 32, 42, 80]], [[36, 70], [86, 53, 46, 59], [[41], 86, 35]]], 3]
60: [[[84, 35], [44, 60]], [[24, 98], [16, 21]]]
58: [[53, 77], [58, [82, 41]], 52]
59: [[93, [100, 53], 58, 79], [63, 94, 59], [9, [55, 48]], [40, 10, 32]]
56: [[20, 10, [[[89, 22, 77, 10], 55], [24, 28, 30, 63]]], [[49, 31]], 17, 56]
0: [0]
```
You may assume that the root node never is a leaf node and points to at least one leaf node. You may assume that leafs are nonnegative numbers.
---
Shortest code in bytes wins.
[Answer]
## Python 2, 53 bytes
```
f=lambda l,c=1:c*l if l<[]else-min(f(x,-c)for x in l)
```
The main question is how to alternate between `max` and `min` each layer. Using the fact that `max(l) == -min([-x for x in l])`, we instead negate every second layer and recurse with `-min`. To negate every second layer, we pass down a multiplier `c` that alternates `+1` and `-1`, and when we reach a leaf, we adjust its value by the multiplier. We recognize being at a leaf via the condition `l<[]`, since Python 2 treats numbers as less than lists.
It's hard to shorten the `else/if` ternary because either branch could give a Truthy (nonzero) or Falsey (zero) value.
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
N߀¬¡ṂN
```
[Try it online!](http://jelly.tryitonline.net/#code=TsOf4oKswqzCoeG5gk4&input=&args=W1s2NywgW1sxMDAsIFtbNjcsIDQ3XSwgWzg2XSwgMjEsIDE2XSwgW1s0NiwgWzE0XSwgMzUsIDg1XSwgWzcxLCBbMTgsIDYzLCA2OV0sIDk5LCAyMl0sIDNdXV0sIFtbMTgsIDMyLCA0MiwgODBdXSwgW1szNiwgNzBdLCBbODYsIDUzLCA0NiwgNTldLCBbWzQxXSwgODYsIDM1XV1dLCAzXQ) or [verify all test cases](http://jelly.tryitonline.net/#code=TsOf4oKswqzCoeG5gk4Kw4figqw&input=&args=W1s2NywgW1sxMDAsIFtbNjcsIDQ3XSwgWzg2XSwgMjEsIDE2XSwgW1s0NiwgWzE0XSwgMzUsIDg1XSwgWzcxLCBbMTgsIDYzLCA2OV0sIDk5LCAyMl0sIDNdXV0sIFtbMTgsIDMyLCA0MiwgODBdXSwgW1szNiwgNzBdLCBbODYsIDUzLCA0NiwgNTldLCBbWzQxXSwgODYsIDM1XV1dLCAzXSwgW1tbODQsIDM1XSwgWzQ0LCA2MF1dLCBbWzI0LCA5OF0sIFsxNiwgMjFdXV0sIFtbNTMsIDc3XSwgWzU4LCBbODIsIDQxXV0sIDUyXSwgW1s5MywgWzEwMCwgNTNdLCA1OCwgNzldLCBbNjMsIDk0LCA1OV0sIFs5LCBbNTUsIDQ4XV0sIFs0MCwgMTAsIDMyXV0sIFtbMjAsIDEwLCBbW1s4OSwgMjIsIDc3LCAxMF0sIDU1XSwgWzI0LCAyOCwgMzAsIDYzXV1dLCBbWzQ5LCAzMV1dLCAxNywgNTZdLCBbMF0).
This uses the algorithm from [@xnor's answer](https://codegolf.stackexchange.com/a/76441). For comparison purposes, a more straightforward approach that alternately computes minima and maxima weighs **8 bytes**:
```
߀¬¡€Ṃ€Ṁ
```
### How it works
```
N߀¬¡ṂN Main link. Argument: x (array or integer)
N Negate. For an array, this negates all integers in it.
¬ Logical NOT. For an array, this applies to all integers in it.
¡ Apply the second link to the left once if ¬ returned an array or 1, or not
at all if it returned 0.
߀ Recursively call the main link on all elements at depth 1 of -x.
If -x == 0, € will cast 0 to range before mapping ß over it.
Since the range of 0 is [], mapping ß over it simply yields [].
Ṃ Minimum.
For an integer, Ṃ simply returns the integer. For [], Ṃ returns 0.
N Negate the minimum.
```
[Answer]
## JavaScript (ES6), 53 bytes
```
f=(a,s=1)=>a.map?s*Math.max(...a.map(b=>s*f(b,-s))):a
```
Uses a similar approach to @xnor's answer. If the numbers are nonzero, then only 49 bytes:
```
f=(a,s=1)=>+a||s*Math.max(...a.map(b=>s*f(b,-s)))
```
[Answer]
# Pyth, 21 bytes
```
M?sIG*GH_hSmgd_HGLgb1
```
My first Pyth answer! Thanks to Dennis for the help :).
```
M # define a binary function (G, H)
?sIG # if G (first argument) is the same with s applied
# (check if it's an integer, so, a leaf node)
*GH # in such a case, calculate G*H
_ # negation
hS # take the first element of the sorted list (that's the min)
mgd_HG # map over G, applying ourself (g) recursively,
# with the current lambda's value (d)
# and the negation of H
Lgb1 # Define a unary function to call our previous
# one with the correct base argument (1)
```
[Answer]
## Mathematica, 13 bytes
```
-Min[#0/@-#]&
```
or equivalently
```
Max[-#0/@-#]&
```
This evaluates to an unnamed function that takes the tree and returns the result.
This is also essentially the same as xnor's solution: at each level we swap the sign of the list and the result and use `Min` all the way down. This turned out incredibly golfy in Mathematica, because:
* `Min` can take either individual numbers or lists or even several lists. It just gives you the minimum value across all of its arguments. That means it works both on lists as well as leaves (where it just returns the leaf).
* `/@` which is short for `Map` is a very general higher-order function in Mathematica. It doesn't just map a function over lists, it can map them over any expression whatsoever. Numbers are such an expression, but they don't contain any elements to be mapped over. That means we can safely map any function over numbers, which doesn't affect the number at all.
Both of those things together mean we can write the code without any conditionals, since the `Min` and `Map` operations are no-ops on numbers, and subsequently the two negations cancel out so that the function becomes the identity when given a number.
Finally, [thanks to `#0`](https://codegolf.stackexchange.com/a/45188/8478) it is possible to write unnamed recursive functions in Mathematica, which saves a few more bytes.
[Answer]
# Ruby, 46 bytes
Used @xnor's trick with `min` for alternating between max and min.
```
f=->n,a=1{n==[*n]?-n.map{|c|f[c,-a]}.min: a*n}
```
[Answer]
# Julia, ~~27~~ 25 bytes
```
!a=0==0a?a:-minimum(!,-a)
```
This uses the algorithm from [@xnor's answer](https://codegolf.stackexchange.com/a/76441). [Try it online!](http://julia.tryitonline.net/#code=IWE9MD09MGE_YTotbWluaW11bSghLC1hKQoKcHJpbnRsbighKHt7NjcsIHt7MTAwLCB7ezY3LCA0N30sIHs4Nn0sIDIxLCAxNn0sIHt7NDYsIHsxNH0sIDM1LCA4NX0sIHs3MSwgezE4LCA2MywgNjl9LCA5OSwgMjJ9LCAzfX19LCB7ezE4LCAzMiwgNDIsIDgwfX0sIHt7MzYsIDcwfSwgezg2LCA1MywgNDYsIDU5fSwge3s0MX0sIDg2LCAzNX19fSwgM30pKQpwcmludGxuKCEoe3t7ODQsIDM1fSwgezQ0LCA2MH19LCB7ezI0LCA5OH0sIHsxNiwgMjF9fX0pKQpwcmludGxuKCEoe3s1MywgNzd9LCB7NTgsIHs4MiwgNDF9fSwgNTJ9KSkKcHJpbnRsbighKHt7OTMsIHsxMDAsIDUzfSwgNTgsIDc5fSwgezYzLCA5NCwgNTl9LCB7OSwgezU1LCA0OH19LCB7NDAsIDEwLCAzMn19KSkKcHJpbnRsbighKHt7MjAsIDEwLCB7e3s4OSwgMjIsIDc3LCAxMH0sIDU1fSwgezI0LCAyOCwgMzAsIDYzfX19LCB7ezQ5LCAzMX19LCAxNywgNTZ9KSkKcHJpbnRsbighKHswfSkp&input=)
] |
[Question]
[
# Challenge
Your task is to output the time (in 12 hour time) in ascii art.
All characters that will be used are as follows:
```
___ __ ___ ____ _ _ _____ __ ______
/ _ \ /_ | |__ \ |___ \ | || | | ____| / / |____ |
| | | | | | ) | __) | | || |_ | |__ / /_ / /
| | | | | | / / |__ < |__ _| |___ \ | '_ \ / /
| |_| | | | / /_ ___) | | | ___) | | (_) | / /
\___/ |_| |____| |____/ |_| |____/ \___/ /_/
___ ___
/ _ \ / _ \ _
| (_) | | (_) | __ _ _ __ _ __ _ __ (_)
> _ < \__, | / _` | ' \ | '_ \ ' \ _
| (_) | / / \__,_|_|_|_| | .__/_|_|_| (_)
\___/ /_/ |_|
```
(For each number/symbol individually, consult [this gist](https://gist.github.com/mathiasfoster/96d4f1bbc23cc35f71d4)).
You will receive input in an array of the form:
* `[hours, minutes, 'am/pm']`. For example, `[4, 57, 'am']`, with single quotes only used for am/pm
* or `"hours-minutes-am/pm"`. For example, `"4-56-am"`
* or `[hours, 'minutes', 'am/pm']` for languages that cannot handle leading zeroes on numbers. For example, `[4, '07', 'am']`
You may use either input method.
Output will be in the form `1 2 : 5 9 am`, where there is one initial space, two spaces between each number (in the gist, each number already has one space on each side), one space between : (colon) and the neighbouring numbers, and one space between the last number and `am/pm`, with an optional leading and/or trailing newline. All spaces are between the right-most point of the symbol on the left and the left-most point of the symbol on the right.
Implicit output is allowed.
Lowest byte size wins.
The `am/pm` are to be aligned such that the bottom of the `p` in `pm` is aligned with the bottom of the rest of the output, that is, the undercore denoting the top of `am/pm` starts on the third line down (not counting a leading newline).
The colon is to be aligned such that it's first character (an underscore) starts on the second line down (not counting a leading newline).
For `minutes < 10`, output the minutes with a leading `0` (you should receive this in the input). For example, `[8, 04, 'pm']` -> `8 : 0 4 pm`.
You must not fetch the data for the numbers from a library or external resource. All data must be contained within the program.
For example, for the input `[12, 47, 'am']`, the output would be as follows:
```
__ ___ _ _ ______
/_ | |__ \ _ | || | |____ |
| | ) | (_) | || |_ / / __ _ _ __
| | / / _ |__ _| / / / _` | ' \
| | / /_ (_) | | / / \__,_|_|_|_|
|_| |____| |_| /_/
```
(If you see any edge cases that you can't decide what to do with, please post in comments and I will add them to examples).
---
[Answer]
# Perl, ~~592~~ ~~579~~ ~~540~~ ~~522~~ 510 bytes
Under a sector!
```
($L,$C,$b)=unpack"W/aW/aB*",q!12346677889999 _|/\)(
'<,>.` PP¨
¨@T @ôäð˜SÀ§€fÌU`à¨Àäð'€GÖf`3 X½`fÍ5 s Î|½`gËÖ— $¡))õ™˜À8Sô BÁªx~O àÔýåËþÏÃÆ~O‡ŸY¬Àf s
½`À*õŸ/X8|½`p>^€<¯åkgúºÖ·Óʸ°ªÀj® kª¸•p¸å\× ô!;@c=map{$i<<=$_-$P if$_>$P;$P=$_;sprintf"%${l}b",$i++}$L=~/./g;while($b){$b=~s/^$c[$_]// and$g.=($C=~/./sg)[$_]for 0..$#c}$_=pop;s/-/:/;y/apm-/;</d;for$a(0..5){map{$o.=substr((split$/,$g)[$a],($x=-48+ord)*12,('6356766766099'=~/./g)[$x]+3)}/./g;$o.=$/}print$o
```
This program expects the time in the 2nd format (*"12-34-am"*) as a commandline argument.
Commented:
```
($L,$C,$b) = unpack "W/aW/aB*", # extract code lengths, chars, and bitstream
q!12346677889999 _|/\)(
'<,>.` PP¨
¨@T @ôäð˜SÀ§€fÌU`à¨Àäð'€GÖf`3 X½`fÍ5 s Î|½`gËÖ— $¡))õ™˜À8Sô BÁªx~O àÔýåËþÏÃÆ~O‡ŸY¬Àf s
½`À*õŸ/X8|½`p>^€<¯åkgúºÖ·Óʸ°ªÀj® kª¸•p¸å\× ô!;
@c = map { # reconstruct huffman prefix codes
$i <<= $_-$P if $_ > $P; # increase code size
$P = $_; # keep track of previous code
sprintf "%${l}b", $i++ # append code as bitstring
}
$L=~/./g; # canonical huffman prefix lengths
while ( $b ) { # decompress font
$b =~ s/^$c[$_]// # match and strip prefix code
and $g .= ($C=~/./sg)[$_] # append char for prefix code
for 0..$#c # iterate prefix codes in order
} # luckily we can omit checking trailing bytes
$_ = pop; # get cmdline arg "12-34-am"
s/-/:/; # ord(':')-ord('0')=10
y/apm-/;</d; # 'a'-> chr(11), 'p' -> chr(12), strip -,m
for $a (0..5) { # iterate 6 output lines
map { # iterate each char in input
$o .= substr(
( split $/, $g )[$a], # grab line $a
( $x=-48+ord ) * 12, # $x=glyph index, 12=glyph width
('6356766766099'=~/./g)[$x]+3 # glyph display width
)
} /./g;
$o .= $/ # append newline
}
print $o # output
```
Note that due to character encoding issues, when you paste the above code in a file, the output may be somewhat malformed. So here's the golfed version, base-64 encoded. Copy it, and paste it into `base64 -d > 510.pl`:
```
KCRMLCRDLCRiKT11bnBhY2siVy9hVy9hQioiLHEhDjEyMzQ2Njc3ODg5OTk5DiBffC9cKSgKJzws
Pi5gFQBQAVACqAIgCqgBQBVUAqAFQAH05PAOmANTwBqngGbMBlVgHOAaqMDk8AcngEfWZmAzAA9Y
Ar1gZs0DNQBzoAHOBny9YGfL1g+XoAUkoSkp9ZmYDMAHOANT9A1Cwap4Bn5PABzgH9T9AeV/GBAB
y/7Pw8Z+Tx+Hn1mswGYAc6AKvWAMwCr1gZ8vWAc4Bny9YA5wPl6APK/lrWtn+rrWt9PKuAawBqrA
aq4AawGquAeVcA64AeVcAdcAAAABrfQhO0BjPW1hcHskaTw8PSRfLSRQIGlmJF8+JFA7JFA9JF87
c3ByaW50ZiIlJHtsfWIiLCRpKyt9JEw9fi8uL2c7d2hpbGUoJGIpeyRiPX5zL14kY1skX10vLyBh
bmQkZy49KCRDPX4vLi9zZylbJF9dZm9yIDAuLiQjY30kXz1wb3A7cy8tLzovO3kvYXBtLS87PC9k
O2ZvciRhKDAuLjUpe21hcHskby49c3Vic3RyKChzcGxpdCQvLCRnKVskYV0sKCR4PS00OCtvcmQp
KjEyLCgnNjM1Njc2Njc2NjA5OSc9fi8uL2cpWyR4XSszKX0vLi9nOyRvLj0kL31wcmludCRv
```
Here's the font I'm using. I've spaced the glyphs 12 characters apart
(the size of the am/pm) for easy indexing.
```
___ __ ___ ____ _ _ _____ __ ______ ___ ___
/ _ \ /_ | |__ \ |___ \ | || | | ____| / / |____ | / _ \ / _ \ _
| | | | | | ) | __) | | || |_ | |__ / /_ / / | (_) | | (_) | (_) __ _ _ __ _ __ _ __
| | | | | | / / |__ < |__ _| |___ \ | '_ \ / / > _ < \__, | _ / _` | ' \ | '_ \ ' \
| |_| | | | / /_ ___) | | | ___) | | (_) | / / | (_) | / / (_) \__,_|_|_|_|| .__/_|_|_|
\___/ |_| |____| |____/ |_| |____/ \___/ /_/ \___/ /_/ |_|
```
This font is 592 bytes.
The previous approach used a few variations on RLE compression to reduce this to 353 bytes, at the cost of 78 bytes decompression code.
The Huffman coding compresses the font to 221 bytes at the cost of 154 bytes for the decompression algorithm.
[Answer]
# Haskell, ~~932~~ 699 bytes
Yay, under 700 bytes!!
```
t=transpose
i=intercalate
l=lines
u=unlines
s=show
c(h,m,a)=u$t$l(i(r"!!\n!!\n")(map d(s h++':':(if m<10 then '0':s m else s m)))++r"!!"++(d$a!!0))
e s z n=i s$splitOn z n
r=e" ""!"
d 'a'=b 10
d 'p'=b 11
d ':'=b 12
d n=b$read[n]
b n=splitOn(r"!!")(u$t$l$r$e" |""@"$e"___""$"$e"_|""~"$e"!!""*"$e"_ ""#"" $! __!$! $_! # _! $__! __! $$! $! $***** \n / #\\ /_@@_#\\ @$ \\ @@|@!| $~!/ /!|$#@ / #\\!/ #\\****! #\n|@@@ @@! )@!__)@@@|@#@@__! / /_* / / @ (_)@@ (_)@ _###__! #_##__!(_)\n|@@@ @@!/ /!|_#< @__!~@$ \\ @ '#\\! / /! > #<!\\__,@ / _`@ ' \\ @ '#\\ ' \\!#\n|@~@ @@ / /_!$)@!@@! $)@@ (_)@!/ /!@ (_)@! / / \\__,~~~~@ .__/~~~ (_)\n \\$/!|~@$~@$_/! @~!|$_/!\\$/!/_/*\\$/! /_/**!@~** ")!!n
```
Somewhat ungolfed
```
module Clock where
import Data.Lists
main :: IO ()
main = putStr $ clock (5,05,"am")
clock :: (Int, Int, String) -> String
clock (h,m,a) | m <- if m < 10 then '0':show m else show m
, hm <- intercalate " \n \n" (map digit (show h ++ ':' :m))
= unlines $ transpose $ lines (hm ++ " "++(digit$a!!0))
digit :: Char -> String
digit 'a' = numbers 10
digit 'p' = numbers 11
digit ':' = numbers 12
digit n = numbers (read [n])
numbers :: Int -> String
numbers n = splitOn " " (unlines $ transpose $ lines " ___ __ ___ ____ _ _ _____ __ ______ ___ ___ \n / _ \\ /_ | |__ \\ |___ \\ | || | | ____| / / |____ | / _ \\ / _ \\ _ \n| | | | | | ) | __) | | || |_ | |__ / /_ / / | (_) | | (_) | __ _ _ __ _ __ _ __ (_)\n| | | | | | / / |__ < |__ _| |___ \\ | '_ \\ / / > _ < \\__, | / _` | ' \\ | '_ \\ ' \\ _ \n| |_| | | | / /_ ___) | | | ___) | | (_) | / / | (_) | / / \\__,_|_|_|_| | .__/_|_|_| (_)\n \\___/ |_| |____| |____/ |_| |____/ \\___/ /_/ \\___/ /_/ |_| ") !! n
```
## How it works
(This is mostly how the ungolfed program works)
```
clock :: (Int, Int, String) -> String
clock (h,m,a) | m <- if m < 10 then '0':show m else show m
, hm <- intercalate " \n \n" (map digit (show h ++ ':' :m))
= unlines $ transpose $ lines (hm ++ " "++(digit$a!!0))
```
`clock` takes a tuple of the time and returns a string. `m` is the current minute with the leading `0` added if it is `<10`. `hm` is the hours and minutes joined with a `:`. The last thing it does is [transpose](https://en.wikipedia.org/wiki/Transpose) the output.
```
digit :: Char -> String
digit 'a' = numbers 10
digit 'p' = numbers 11
digit ':' = numbers 12
digit n = numbers (read [n])
```
Fairly simple here. `digit` is a function that maps the chars to locations in the stored string.
```
numbers :: Int -> String
numbers n = splitOn " " (unlines $ transpose $ lines replace" |""@"$replace"___""$"$replace"_|""~"$replace"!!""*"$replace"_ ""#"" $! __!$! $_! # _! $__! __! $$! $! $***** \n / #\\ /_@@_#\\ @$ \\ @@|@!| $~!/ /!|$#@ / #\\!/ #\\****! #\n|@@@ @@! )@!__)@@@|@#@@__! / /_* / / @ (_)@@ (_)@ _###__! #_##__!(_)\n|@@@ @@!/ /!|_#< @__!~@$ \\ @ '#\\! / /! > #<!\\__,@ / _`@ ' \\ @ '#\\ ' \\!#\n|@~@ @@ / /_!$)@!@@! $)@@ (_)@!/ /!@ (_)@! / / \\__,~~~~@ .__/~~~ (_)\n \\$/!|~@$~@$_/! @~!|$_/!\\$/!/_/*\\$/! /_/**!@~** ")!!n
```
This is the magic stored string.
The only real change between the golfed and ungolfed programs is that the golfed program adds some string compression by replacing some common char patterns with `!@$`. The original data string was `667` bytes, after the replace compression it is down to `390` bytes
[Answer]
# Bash + GNU utilities + [figlet](http://www.figlet.org/), 134
Not sure if figlet is allowed or not, but it does seem to provide the right fonts - `big` for the digits and `small` for the `:` and `{a,p}m`:
```
f=figlet\ -f
b()(date +%$1|sed 's/./& /g'|$f big)
b -I|paste - <(echo " ";$f small ": ") <(b M) <(echo;date +%P|$f small)|tr \\t \
```
The rest is just getting the right info from `date` and shuffling the formating around so it looks right:
```
___ _____ ___
/ _ \ _ | ____| / _ \
| (_) | (_) | |__ | | | | __ _ _ __
> _ < _ |___ \ | | | | / _` | ' \
| (_) | (_) ___) | | |_| | \__,_|_|_|_|
\___/ |____/ \___/
```
Figlet may be installed on Ubuntu with `sudo apt-get install figlet`.
[Answer]
# C++, 938 Bytes
Revised version with some basic compression of input data: Test [here](https://ideone.com/vB0yyX)
```
#include <stdio.h>
#include <time.h>
int main(){char e[]="!1`2!3`1!2`1!4`2!4`!1`!4`4!4`1!3`5!4`2!4`2!35^!`!]!1^`!}!}`1!]!1}`2!]!1}!}1!}!2}!`3}!2^!^!2}`3!1}!2^!`!]!2^!`!]!31`!}!}!}!}!1}!}!3*!}!2`1*!}!}!}1!}`!1}!}`1!3^!^`!6^!^!2}!)`*!}!}!)`*!}!2`1!`!`!`1!3`!`1!`!`1!4)`*}!}!}!}!1}!}!2^!^!2}`1!=!1}`1!2`}!}`2!]!1}!(`!]!4^!^!4?!`!=!2]`1-!}!1^!`a!}!(!1]!1}!(`!]!(!1]!4`!}!}`}!}!1}!}!1^!^`!2`2*!}!3}!}!3`2*!}!}!)`*!}!2^!^!4}!)`*!}!3^!^!2]`1-`}`}`}`}!}!/`1^`}`}`}!2)`*!]`2^!2}`}!}`3}!}`3^!4}`}!2}`3^!2]`2^!2^`^!6]`2^!3^`^!16}`}!14",l[]="8578988998>?3",f[666],*q=f,*p=e,c,r;time_t z;time(&z);tm*u=localtime(&z);while(*p){if(*p>47&&*p<58){r=*p++-48;if(*p>47&&*p<58)r=r*10+*p++-48;while(r--)*q++=c;}else{*q++=c=*p++==94?48:p[-1];}}c=u->tm_hour;sprintf(e,"%02d<%02d%c",c%12,u->tm_min,':'+c/12);for(int s,n,o,r=0;r<6;r++){for(q=e;*q;q++){o=r*111;for(n=0; n<*q-48;n++)o+=l[n]-48;s=l[n]-48;for(n=o;n<o+s;n++)putchar(f[n]-1);}putchar('\n');}return 0;}
```
[Answer]
# JavaScript (ES6), ~~994~~ 985 bytes
Terrible attempt with raw data not compressed at all, and a very tacky method for outputting.
But hey... it's only my second codegolf answer!
```
d=" ___ ! / _ \\ ! | | | | ! | | | | ! | |_| | ! \\___/ 0 __ ! /_ | ! | | ! | | ! | | ! |_| 0 ___ ! |__ \\ ! ) | ! / / ! / /_ ! |____| 0 ____ ! |___ \\ ! __) | ! |__ < ! ___) | ! |____/ 0 _ _ ! | || | ! | || |_ ! |__ _| ! | | ! |_| 0 _____ ! | ____| ! | |__ ! |___ \\ ! ___) | ! |____/ 0 __ ! / / ! / /_ ! | _ \\ ! | (_) | ! \\___/ 0 ______ ! |____ | ! / / ! / / ! / / ! /_/ 0 ___ ! / _ \\ ! | (_) | ! > _ < ! | (_) | ! \\___/ 0 ___ ! / _ \\ ! | (_) | ! \\__, | ! / / ! /_/ 0 ! _ !(_)! _ !(_)! 0!! __ _ _ __ !/ _` | ' \\!\\__,_|_|_|_|!0!! _ __ _ __ !| '_ \\ ' \\!| .__/_|_|_|!|_|".split(0);
f=a=>{t="toString",s="split",h=a[0][t]()[s](""),m=a[1][s](""),p=a[2]=='am'?11:12,g=h.length>1?1:0,r="";for(i=0;i<6;i++){r+=d[h[0]][s]('!')[i];r+=(g&&1)?d[h[1]][s]('!')[i]:"";r+=d[10][s]('!')[i]+d[m[0]][s]('!')[i]+d[m[1]][s]('!')[i]+d[p][s]('!')[i]+"\n"}return r}
```
**Old submission (994 bytes)**:
```
d=[" ___ ! / _ \\ ! | | | | ! | | | | ! | |_| | ! \\___/ "," __ ! /_ | ! | | ! | | ! | | ! |_| "," ___ ! |__ \\ ! ) | ! / / ! / /_ ! |____| "," ____ ! |___ \\ ! __) | ! |__ < ! ___) | ! |____/ "," _ _ ! | || | ! | || |_ ! |__ _| ! | | ! |_| "," _____ ! | ____| ! | |__ ! |___ \\ ! ___) | ! |____/ "," __ ! / / ! / /_ ! | _ \\ ! | (_) | ! \\___/ "," ______ ! |____ | ! / / ! / / ! / / ! /_/ "," ___ ! / _ \\ ! | (_) | ! > _ < ! | (_) | ! \\___/ "," ___ ! / _ \\ ! | (_) | ! \\__, | ! / / ! /_/ "," ! _ !(_)! _ !(_)! ","!! __ _ _ __ !/ _` | ' \\!\\__,_|_|_|_|!","!! _ __ _ __ !| '_ \\ ' \\!| .__/_|_|_|!|_|"];
f=a=>{
t="toString",s="split",h=a[0][t]()[s](""),m=a[1][s],p=(a[2]=='am')?11:12,g=(h.length>1)?1:0,r="";
for(i=0;i<6;i++){
r+=d[h[0]].s('!')[i];
r+=g&&1?d[h[1]].s('!')[i]:"";
r+=d[10].s('!')[i]+d[m[0]].s('!')[i]+d[m[1]].s('!')[i]+d[p].s('!')[i]+"\n"
}
return r
}
```
Split into lines to make it easier to read.
Basically:
```
var f = function (a) {
hours = a[0].toString().split(""), // convert hours to a string then array to
// handle single and and double numbers
minutes = a[1].split(""), // ditto with minutes
period = a[2] == "am" ? 11 : 12, // if it is am, get data[11], if pm, get data[12]
g = hours.length > 1 ? 1 : 0, // if hours > 9, then g is true
r = ""; // the string that will be returned
for (i = 0; i < 6; i++) {
r += data[hours[0]].split("!")[i]; // add the first digit of hours to r
r += g && 1 ? data[hours[1]].split("!")[i] : ""; // if g is true, add the second
//digit of hours to r
r += data[10].split("!")[i] + // colon
data[minutes[0]].split("!")[i] + // first digit of minutes
data[minutes[1]].split("!")[i] + // second digit of minutes
data[period].split("!")[i] + // am/pm
"\n"; // and finally linebreak.
} // entire loop repeated six times, each iteration adds one line to the string
return r; // return the string
};
```
[Answer]
## Python 3, ~~1085~~ 1072 bytes
### Golfed
```
def f(h,c="",n=[" ___ @ / _ \ @ | | | | @ | | | | @ | |_| | @ \___/ "," __ @ /_ | @ | | @ | | @ | | @ |_| "," ___ @ |__ \ @ ) | @ / / @ / /_ @ |____| "," ____ @ |___ \ @ __) | @ |__ < @ ___) | @ |____/ "," _ _ @ | || | @ | || |_ @ |__ _| @ | | @ |_| "," _____ @ | ____| @ | |__ @ |___ \ @ ___) | @ |____/ "," __ @ / / @ / /_ @ | _ \ @ | (_) | @ \___/ "," ______ @ |____ | @ / / @ / / @ / / @ /_/ "," ___ @ / _ \ @ | (_) | @ > _ < @ | (_) | @ \___/ "," ___ @ / _ \ @ | (_) | @ \__, | @ / / @ /_/ "," @ _ @(_)@ _ @(_)@ "," @ @ __ _ _ __ @/ _` | ' \@\__,_|_|_|_|@ "," @ @ _ __ _ __ @| '_ \ ' \@| .__/_|_|_|@|_|"]):
for i in range(6):
for j in range(3):
if j<2:
x=int(h[j]);d=x//10;u=x%10
if d>0 or j>0:c+=n[d].split("@")[i]
c+=n[u].split("@")[i]
if j==0:c+=" "+n[10].split("@")[i]+" "
else:y=11 if h[j]=="am" else 12;c+=" "+n[y].split("@")[i]
c+="\n"
return c
```
### Ungolfed
```
import os
from time import ctime
def asciiClock(hour):
num = [" ___ @ / _ \ @ | | | | @ | | | | @ | |_| | @ \___/ @"," __ @ /_ | @ | | @ | | @ | | @ |_| @",
" ___ @ |__ \ @ ) | @ / / @ / /_ @ |____| @"," ____ @ |___ \ @ __) | @ |__ < @ ___) | @ |____/ @",
" _ _ @ | || | @ | || |_ @ |__ _| @ | | @ |_| @"," _____ @ | ____| @ | |__ @ |___ \ @ ___) | @ |____/ @",
" __ @ / / @ / /_ @ | _ \ @ | (_) | @ \___/ @"," ______ @ |____ | @ / / @ / / @ / / @ /_/ @",
" ___ @ / _ \ @ | (_) | @ > _ < @ | (_) | @ \___/ @"," ___ @ / _ \ @ | (_) | @ \__, | @ / / @ /_/ @",
" @ _ @(_)@ _ @(_)@ @"," @ @ __ _ _ __ @/ _` | ' \@\__,_|_|_|_|@ @",
" @ @ _ __ _ __ @| '_ \ ' \@| .__/_|_|_|@|_|@"]
clock = ""
for i in range(6):
for j in range(3):
if j < 2:
x = int(hour[j])
d = x // 10
u = x % 10
if d > 0 or j > 0:
clock += num[d].split("@")[i]
clock += num[u].split("@")[i]
if j == 0:
clock += " " + num[10].split("@")[i] + " "
else:
y = 11 if hour[j] == "am" else 12
clock += " " + num[y].split("@")[i]
clock += "\n"
return clock
previousMinute = -1
while True:
hour = ctime().split()[3].split(":")
h = int(hour[0])
m = hour[1]
x = "am" if h < 12 else "pm"
if h > 12:
h -= 12
if previousMinute != m:
os.system("clear") # if using Windows change to "cls"
print(asciiClock([h, m, x]))
previousMinute = m
```
] |
[Question]
[
# Challenge:
Some ascii-art is a pain to make, but makes code comments easier to read, especially when the code is dense. The challenge is to make a simple tool that converts comments to simple ascii-art with arrows. The comments to modify are delimited by empty comments.
For example, supposing Haskell comment syntax, convert this:
```
--
-- Here's a thing
-- Here's another thing
-- The most important thing
-- * * *
--
f x=x+1*x*1*1*0
```
To this:
```
-- /------------< Here's a thing
-- | /-------< Here's another thing
-- | | /-< The most important thing
-- | | |
-- v v v
f x=x+1*x*1*1*0
```
# Rules:
* Your answer may be either a function or full program
* You may pick the language this is made to work with, replacing the "--" with two or more characters that delimit a comment in some language
* If using another comment format that requires beginning and ending delimiters, each line of the reformatted sections must be a proper comment
* The sections to be reformatted are delimited by the empty comment "\n--\n"
* Besides adding newlines, the program must not change any of the input except the delimited sections
* A comment filled with an arbitrary number of spaces may come immediately before a properly formatted section of output
* Standard loopholes are disallowed
# Additional Examples:
```
(input)
--
--
(output)
nothing
(input)
[Code Here]
--
-- important
-- *
--
(output)
[Code Here]
-- /-< important
-- |
-- v
(input)
--
-- Do
-- Re
-- Mi
-- Fa
-- So
-- *****
--
(output)
-- /-----< Do
-- |/----< Re
-- ||/---< Mi
-- |||/--< Fa
-- ||||/-< So
-- |||||
-- vvvvv
```
# Scoring:
* Fewest bytes wins
* Submissions without explanations or non-trivial example input/output will not be considered (though I will leave a grace period to allow time to add such)
[Answer]
# JavaScript(ES6), ~~418~~, ~~237~~, ~~233~~, 236 bytes
```
f=(s)=>(d='\n//',s.split(d+'\n').map((x,y)=>y%2?'//'+(l=x.slice(2).split(d),t=l.pop().split('*'),l.map((i,j)=>t.map((k,m)=>m==j?k+'/':m<j?k+'|':k.replace(/ /g,'-')+'-').join('')+'<'+i).join(d)+d+t.join('|')+d+t.join('v')):x).join('\n'))
```
Whew, this is my first submission on CG. ~~Took, I think, a totally different tack from Washington Guedes. Ended up 54 bytes shorter than his first pass. Minifying all this by hand was grueling. My one regret is not being able to eliminate the while loop yet, which would also let me cut the return.~~
Total rewrite, taking partial inspiration from a couple of the other answers. I got to close the whole thing in maps, making returning much better. The code snippet contains the commented version.
Took a few more bytes off, and made the example operate on itself. (You're gonna need a bigger monitor.) :)
Forgot an entire letter in the spec! Fortunately, adding the leading '<' was a tiny, trivial fix.
```
var comments = `
//
// New function, declare the comment delimiter
// Chop the string by the fancy comment delimiter
// Iterate over the array.
// Because of how it's delimited, and how JS splits strings, only the even elements will contain fancy comments.
// Add the original comment delimiter to the front of the first line, because join won't.
// we've got a single fancy comment, split it into lines.
// Take the last line, our asterisk template, and split it on the asterisks themselves. We were only gonna replace them anyway.
// Now we get to the real work. Iterate the remaining lines.
// For each chunk of whitespace in the template array, toss a different character on the end based on where we are in the series of lines.
// if we're at the matching asterisk, insert a slash
// Otherwise, if we're at a prior asterisk, add a pipe.
// Finally, replace anything afer the matching asterisk with dashes, join the template, and add it to the line text.
// Join the lines with the delimiter
// Add the pipe line...
// And the v line...
// For odd chunks, just return the chunk.
// Join all the code chunks and autoreturn.
// * * * * * * * * * * * * * * * * *
//
`
f=(s)=>(d='\n//',s.split(d+'\n').map((x,y)=>y%2?'//'+(l=x.slice(2).split(d),t=l.pop().split('*'),l.map((i,j)=>t.map((k,m)=>m==j?k+'/':m<j?k+'|':k.replace(/ /g,'-')+'-').join('')+'<'+i).join(d)+d+t.join('|')+d+t.join('v')):x).join('\n'))
str = `
//
// This is a test
// with two lines
// actually three
// * * *
//
var myCode = function () {
}
// This doesn't cause any trouble.
moreCode(stuff--)
//
// another test?
// *
//
`
document.getElementById('before').textContent = str;
document.getElementById('after').textContent = f(str);
document.getElementById('self').textContent = f(comments)+'f='+f.toString();
```
```
Test cases before:
<pre id="before" style="background:#eef"></pre>
Test cases after:
<pre id="after" style="background:#eef"></pre>
Self-annotated:
<pre id="self"></pre>
```
[Answer]
# Ruby, 160 characters
```
->c{c.gsub(/^--$(.+?)^--$/m){*t,a=$&.lines[1..-2]
a&&a.chop!&&(t.map{|l|a[?*]=?/
l[0,2]=a.gsub(/(?<=\/).*/){?-*$&.size}+'-<'
a[?/]=?|
l}<<a+$/+a.tr(?|,?v))*''}}
```
Sample run:
```
2.1.5 :001 > puts ->c{c.gsub(/^--$(.+?)^--$/m){*t,a=$&.lines[1..-2];a&&a.chop!&&(t.map{|l|a[?*]=?/;l[0,2]=a.gsub(/(?<=\/).*/){?-*$&.size}+'-<';a[?/]=?|;l}<<a+$/+a.tr(?|,?v))*''}}["
2.1.5 :002"> --
2.1.5 :003"> -- Here's a thing
2.1.5 :004"> -- Here's another thing
2.1.5 :005"> -- The most important thing
2.1.5 :006"> -- * * *
2.1.5 :007"> --
2.1.5 :008"> f x=x+1*x*1*1*0
2.1.5 :009"> "]
-- /------------< Here's a thing
-- | /-------< Here's another thing
-- | | /-< The most important thing
-- | | |
-- v v v
f x=x+1*x*1*1*0
=> nil
```
Brief description:
```
.lines splits the section to array items ─────────╮
▽
.gsub extracts ⎧ -- 0
these sections ⎪ -- Here's a thing 1 t[0]
for processing ⎨ -- Here's another thing 2 t[1]
and replaces ⎪ -- The most important thing ⋮ t[2]
them with the ⎪ -- * * * -2 a
pretty version ⎩ -- -1
rest untouched — f x=x+1*x*1*1*0
△
only the needed lines get into variables ─────────────╯
a = "-- * * *" + "-<" inside .gsub's block
↓↓ the first 2 characters
t[0] = "-- Here's a thing" of t's each item are
t[1] = "-- Here's another thing" replaced with a's value
t[2] = "-- The most important thing" and the the separator
not only t's items are transformed inside .gsub's block,
but a's value also gets changed in multiple small steps
change a's value change the value change a's value
a's initial value before insertion being inserted now after insertion
╭───────────────╮ ╭───────────────╮ ╭───────────────╮ ╭───────────────╮
0 "-- * * *" → "-- / * *" → "-- /-----------" → "-- | * *"
1 "-- | * *" → "-- | / *" → "-- | /------" → "-- | | *"
2 "-- | | *" → "-- | | /" → "-- | | /" → "-- | | |"
╰───────────────╯ ╰───────────────╯ ╰───────────────╯
change first * to / change everything change first / to |
after / with string
of - of same length
```
[Answer]
## Python 2, 299 bytes
Expects a trailing newline in the input
```
i=input().split('--\n')
a=0
for j in i:
a+=1
if a%2:print j,;continue
if''==j:continue
l=j.split('\n');n=l[-2];r=l[:-2];R=[n.replace('*','v'),n.replace('*','|')];L=R[1]
for x in range(len(l)-2)[::-1]:L=L[:L.rfind('|')]+'/';R+=[L.ljust(n.rfind('*')+2,'-')+'< '+r[x][3:]]
print'\n'.join(R[::-1])
```
---
**Explanation/Example**
Input:
```
[Code Here]
--
-- important
-- *
--
```
Splits the input by `--\n`. Every second string is a delimited comment block.
```
['[Code Here]\n',
'-- important\n-- stuff\n-- * *\n',
'']
```
Runs through each string. If the string is not a comment, then just prints the string. Otherwise:
Splits each line in the comment block.
```
['-- important', '-- stuff', '-- * *', '']
```
Makes the bottom two lines by replacing the lines of `*`s with `v` and `|`.
```
['-- v v', '-- | |']
```
For each line of comments(backwards) remove rightmost column, add `/`, pad with `-` and add comment.
```
'-- | /'
'-- /'
'-- /----< important'
```
Print Everything
```
-- /----< important
-- | /-< stuff
-- | |
-- v v
```
**Less golfed:**
```
i=input().split('--\n')
a=0
for j in i:
a+=1
if a%2:print j,;continue # Not commment
if''==j:continue # Empty comment
l=j.split('\n') # Split comment into lines
r=l[:-2]
# Replace line of *s with v and | respectively
R=[l[-2].replace('*','v'),l[-2].replace('*','|')]
L=R[1][3:] # line of |
for x in range(len(l)-2)[::-1]: # For each comment line
L=L[:L.rfind('|')]+'/' #Remove rightmost column
# Add a line with '-- ',columns, and comment
R+=['-- '+L.ljust(n.rfind('*')-1,'-')+'< '+r[x][3:]]
print'\n'.join(R[::-1]) #Print all comment lines
```
[Answer]
# JavaScript (ES6), 253
As an anonymous function, with the code to format as a string parameter and returning the formatted code.
*Notes*
1. The pair of marker comments must enclose the right text (comment lines, then stars)
2. ... or the pair must enclose nothing (additional example 1)
```
t=>(t=t.split`
`,t.map((r,i)=>r=='--'?(c++&&l.map((r,j)=>(p+=q[j],z+=~q[j].length,t[i-n+j]=p+`/${'-'.repeat(z+1)}<`+r.slice(3),p+=`|`),q=l.pop(c=p=``)||p,z=q.length,q=q.split`*`,t[i]=p+q.join`v`,t[i-1]=p+q.join`|`),l=[]):n=l.push(r),c=0,l=[]),t.join`
`)
```
**Less golfed**
```
f=t=>{
t = t.split`\n`; // string to array of lines
l = []; // special coment text
c = 0; // counter of marker comment '--'
t.forEach((r,i)=>{ // for each line of t - r: current line, i: index
if (r == '--') // if marker comment
{
++ c; // increment marker counter
if (c > 1) // this is a closing marker
{
c = 0; // reset marker counter
if (n > 0) // n is the length of array l
q = l.pop(); // get last line from l, have to be the star line
else
q = ''; // no text comment, no star line
p = ''; // prefix for drawing the tree
z = q.length; // length of star line, used to draw the tree horiz lines
q = q.split('*'); // split to get star count and position
// each element in q is the spaces between stars
// modifiy the current and previous text line
t[i] = p + q.join`v`; // current row was '--', becomes the V line
t[i-1] = p + q.join`|`; // previous row was the star line, becomes the last tree line
l.forEach((r,j)=>{ // for each line in l, r: current line, j: index
// each line in tree is: prefix("-- | |"...) + ... "---< " + text
p = p + q[j]; // adjust prefix
z = z - q[j].length - 1 // adjust length of '---'
// modify text in t
t[i-n+j] = p // prefix
+ '/' + '-'.repeat(z+1) + '<' // horiz line and <
+ r.slice(3); // text, removed '-- '
p = p + '|'; // add vertical bar to prefix
});
} // end if closing comment
l = []; // reset l
}
else // not a special comment marker
n = l.push(r) // add current line to l, set n to array size
});
return t.join`\n` // join to a single string
}
```
**Test**
```
f=t=>(
t=t.split`\n`,
t.map((r,i)=>
r=='--'
?(
c++&&l.map((r,j)=>(
p+=q[j],z+=~q[j].length,t[i-n+j]=p+`/${'-'.repeat(z+1)}<`+r.slice(3),p+=`|`),
q=l.pop(c=p=``)||p,z=q.length,q=q.split`*`,t[i]=p+q.join`v`,t[i-1]=p+q.join`|`
),l=[]
):n=l.push(r)
,c=0,l=[]
),
t.join`\n`
)
function update(){O.textContent=f(C.value)}
update()
```
```
textarea, pre { width:50%; height: 200px }
```
```
Input<br>
<textarea id=C>
code line 1
--
-- Do
-- Re
-- Mi
-- Fa
-- So
-- *****
--
code to explain
--
--
code line n
code line n+1
--
-- important
-- *
--
</textarea><br>
Output <button onclick="update()">Update</button><br>
<pre id=O></pre>
```
] |
[Question]
[
Time for a new [typography](/questions/tagged/typography "show questions tagged 'typography'") challenge! It’s a common problem when copy-pasting between various document formats: hyphenation. While it reduces the raggedness of a left-aligned layout or evens spacing in a justified layout, it’s a complete pain when your PDF is not properly constructed and retains the hyphens in the layout, making your copied text difficult to edit or reflow.
Luckily, if we are to believe the countless self-help books out there, nothing is a problem if you see it as a challenge. I believe these self-help books are without exception referring to PPCG, where any problem will be solved if presented as a challenge. Your task is to remove offending hyphenation and linebreaks from a text, so that it is ready to paste in any text editor.
# Problem description
You will write a program or function that removes hyphenation and line-breaks where applicable. The **input** will be a string on `stdin` (or closest alternative) or as a function input. The **output** (on `stdout` or closest alternative or function output) will be the 'corrected' text. This text should be **directly** copy-pastable. This means that leading or trailing output is OK, but additional output halfway your corrected text (e.g., leading spaces on every line) is **not**.
The most basic case is the following (note: no trailing spaces)
```
Lorem ipsum dolor sit amet, con-
sectetur adipiscing elit. Morbi
lacinia nisi sed mauris rhoncus.
```
The offending hyphen and linebreaks should be removed, to obtain
```
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi lacinia nisi sed mauris rhoncus.
```
However, a few exceptions should be observed.
* Double newlines indicate a paragraph break, and should be retained.
* Proper nouns and names are never broken across two lines, unless they already contain a hyphen (e.g. Navier-Stokes equations). The line-break should be removed, but the hyphen retained. These cases can be identified by having only the first letter capitalized.
* Sometimes, a hyphen indicates a word group (e.g. nineteenth- and twentieth century). When this happens across two lines, this is indicated with a leading space on the next line.
An example: *(views expressed in this example are fictional and do not necessarily represent the view of the author; opponents of the Runge-Kutta-Fehlberg method are equally welcome to participate in this challenge)*
```
Differential equations can
be solved with the Runge-Kutta-
Fehlberg method.
Developed in the nineteenth-
or twentieth century, this
method is completely FANTAS-
TIC.
```
will become
```
Differential equations can be solved with the Runge-Kutta-Fehlberg method.
Developed in the nineteenth- or twentieth century, this method is completely FANTASTIC.
```
The linebreaks can be either the `\n` or `\r\n` ASCII code-point depending on your preference, and the hyphen is a simple ASCII `-` (minus sign). UTF-8 support is not required. This challenge is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins.
[Answer]
# [Retina](https://github.com/mbuettner/retina), 58 bytes
```
(?<!\n)\n(?!\n)
<space>
- (?! |[A-Z][a-z])| (?= )|(?<=-) (?=[A-Z])
<empty>
```
`<space>` represents a single space on its own line and `<empty>` represents an empty trailing line. For counting purposes, each line goes into a separate file and the `\n` are replaced with actual linefeed characters. For convenience you can put all of the above in a single file though and run it with the `-s` flag.
I'm pretty sure there's a shorter way to do this, so I'll wait with an explanation until I'm done golfing.
[Answer]
# GNU Sed, 68
Score includes +2 for `-zr` options passed to `sed`.
```
s/\n\n/:/g
s/-\n([A-Z][a-z])/-\1/g
s/-\n /- /g
s/-\n//g
y/\n:/ \n/
```
Assumes that the input stream doesn't contain any `:` characters. If this is not acceptable, then the `:`'s in the code may be all replaced with some other non-printable ASCII character, e.g. 0x7 BEL.
[Answer]
# [TeaScript](http://github.com/vihanb/TeaScript), 76 bytes
```
xB(`([A-Z][a-z]+-)
(\\S)`,b="$1$2",`(\\S)-
(\\S)`,b,`(\\S-?)
?(.)`,"$1 $2")
```
Very "brute force" method.
[Try it online](http://vihanserver.tk/p/TeaScript/)
] |
[Question]
[
RoboCritters ([etymology](http://chat.stackexchange.com/transcript/message/21989912#21989912)) is a brand new [esoteric programming language](https://esolangs.org/wiki/Main_Page) (don't bother searching for it, I just invented it). It's a [variant](https://esolangs.org/wiki/Category:Brainfuck_equivalents) of [Brainfuck](https://esolangs.org/wiki/Brainfuck) (BF), slightly more complex than the usual operator substitution schemes. Every program in RoboCritters is a rectangular grid of text that only contains the seven characters `. []/\|`, plus newlines to shape the grid.
Example RoboCritters program:
```
|\/||./|[]||
[..][][] |
|/\|[..][..]
[..] \/\/
```
To translate a RoboCritters program into BF, look at each non-newline character in the grid in the normal reading order (left-to-right then top-to-bottom), e.g. `|\/||./|[]||[..][][] ||/\|[..][..][..] \/\/`.
If the 4×2 section of the grid extending right and down from the current character exactly matches one of the eight *robot critters* listed below, append the corresponding [BF command](http://en.wikipedia.org/wiki/Brainfuck#Commands) (`><+-.,[]`) to the (initially empty) BF program.
If the 4×2 grid section **does not match** any of the robot critters or **goes out of bounds**, nothing is added to the BF program.
1. Joybot, `>` command:
```
[..]
\][/
```
2. Calmbot, `<` command:
```
[..]
/][\
```
3. Squidbot, `+` command:
```
[..]
//\\
```
4. Spiderbot, `-` command:
```
[..]
||||
```
5. Bunnybot, `.` command:
```
[][]
[..]
```
6. Toothbot, `,` command:
```
[..]
|/\|
```
7. Foxbot, `[` command:
```
|\/|
[..]
```
8. Batbot, `]` command:
```
[..]
\/\/
```
So, reading the example program
```
|\/||./|[]||
[..][][] |
|/\|[..][..]
[..] \/\/
```
we can see that we first encounter a Foxbot (at column 1, row 1), then a Toothbot (c1,r2), then a Bunnybot (c5,r2), and finally a Batbot (c9,r3). This corresponds to the BF program `[,.]`.
Notice that the Foxbot and Toothbot overlap. This is intentional; **robot critters are not interpreted any differently when they overlap**.
# Challenge
Write the shortest program possible that takes in a RoboCritters program and outputs its BF equivalent. You don't need to run the BF or check that it's valid, only translate the RoboCritters code to BF code.
### Details
* All input RoboCritters programs will be valid, that is they will be an exactly rectangular block of text only containing the seven characters `. []/\|`, plus newlines to shape it. The newlines may be in any convenient [common representation](http://en.wikipedia.org/wiki/Newline#Representations). You may optionally assume the programs have a single trailing newline.
* **You must support RoboCritters programs that are smaller than 4×2, including the 0×0 empty (or single newline) program. These all correspond to the empty BF program (the empty string).**
* The output BF program should be a one-line string only containing the eight BF command characters `><+-.,[]`. There may optionally be a single trailing newline.
* Take input in any usual way (stdin/text file/command line) and output to stdout or your language's closest alternative.
* Instead of a program you may write a function that takes the RoboCritters program as a string and prints or returns the BF program string.
# Examples
1. Input: (variant of example above)
```
|\/|[][]
[..][][]
|/\|[..]
\/\/
```
Output: `[,.]`
2. Input: (tests all robot critters)
```
[..][[[[[..]]. ]|\/|
\][/[..]//\\[..][..]
[..]/][\[][]|/\|[..]
||||/\| [..]| |\/\/
```
Output: `>+[<,-.]`
3. Input:
```
[..] [..] [..] [..] [..] [..] [..] [..] |\/| [..] [..] [..] [..] [..] |\/| [..] [..] [..] [..] [..] [..] [..] [..] [..] [..] [..] [..] [..] [..] [..] [..] [..] [..] [..] [..] [..] [..] [..] [..] [..] [..] [..] [..] |\/| [..] [..] [..] [..] [..] [..] [..] [][] [..] [..] [..] [..] [][] [..] [..] [..] [..] [..] [..] [..] [][] [][] [..] [..] [..] [][] [..] [..] [][] [..] [..] [][] [..] [][] [..] [..] [..] [][] [..] [..] [..] [..] [..] [..] [][] [..] [..] [..] [..] [..] [..] [..] [..] [][] [..] [..] [..] [][] [..] [..] [..] [][]
//\\ //\\ //\\ //\\ //\\ //\\ //\\ //\\ [..] \][/ //\\ //\\ //\\ //\\ [..] \][/ //\\ //\\ \][/ //\\ //\\ //\\ \][/ //\\ //\\ //\\ \][/ //\\ /][\ /][\ /][\ /][\ |||| \/\/ \][/ //\\ \][/ //\\ \][/ |||| \][/ \][/ //\\ [..] /][\ \/\/ /][\ |||| \/\/ \][/ \][/ [..] \][/ |||| |||| |||| [..] //\\ //\\ //\\ //\\ //\\ //\\ //\\ [..] [..] //\\ //\\ //\\ [..] \][/ \][/ [..] /][\ |||| [..] /][\ [..] //\\ //\\ //\\ [..] |||| |||| |||| |||| |||| |||| [..] |||| |||| |||| |||| |||| |||| |||| |||| [..] \][/ \][/ //\\ [..] \][/ //\\ //\\ [..]
```
Output: ([BF Hello World program](http://en.wikipedia.org/wiki/Brainfuck#Hello_World.21))
```
++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.
```
4. Input: (no robot critters present)
```
/\\\[].
]..[..]
\\//||\
```
Output: (empty string)
# Scoring
The shortest submission in bytes wins. ([Handy byte counter.](https://mothereff.in/byte-counter)) Tiebreaker is highest voted post.
[Answer]
# CJam, ~~86~~ 85 bytes
```
qN/S4*f+_W<\1>]z:z4few:~"¨Ý³5&ágûò{wÉ](Ý"296b6b"|[\.]/"f=2/4/"><+-.,[]":Ler{L&},
```
[Test it here.](http://cjam.aditsu.net/#code=qN%2FS4*f%2B_W%3C%5C1%3E%5Dz%3Az4few%3A~%22%C2%A8%C2%9B%7F%C3%9D%C2%B35%26%C3%A1g%C3%BB%C3%B2%7Bw%C3%89%C2%8D%5D%11%C2%89(%C3%9D%22296b6b%22%7C%5B%5C.%5D%2F%22f%3D2%2F4%2F%22%3E%3C%2B-.%2C%5B%5D%22%3ALer%7BL%26%7D%2C&input=%5B..%5D%5B%5B%5B%5B%5B..%5D%5D.%20%5D%7C%5C%2F%7C%0A%5C%5D%5B%2F%5B..%5D%2F%2F%5C%5C%5B..%5D%5B..%5D%0A%5B..%5D%2F%5D%5B%5C%5B%5D%5B%5D%7C%2F%5C%7C%5B..%5D%0A%7C%7C%7C%7C%2F%5C%7C%20%5B..%5D%7C%20%20%7C%5C%2F%5C%2F)
## Explanation
```
qN/ e# Read input and split into lines.
S4*f+ e# Append four spaces to each line. This has two purposes. a) We can later join all
e# the lines together without worrying about critters appearing across the line
e# edges because no critter contains spaces. b) It works around a bug in CJam where
e# the command `ew` crashes when the substring length is longer than the string.
_W< e# Copy the lines and discard the last one.
\1> e# Swap with the other copy and discard the first one.
]z e# Wrap both in an array and zip them up. Now we've got an array which contains
e# all consecutive pairs of lines.
:z e# Zip up each of those pairs, such it becomes an array of two-character strings.
e# We can now find the critters as 4-element subarrays in each of those arrays.
4few e# Turn each of those arrays into a list of its (overlapping) 4-element subarrays.
:~ e# Flatten those lists, such that we get one huge array of all 4x2 blocks, in order.
"gibberish"296b6b
e# This is an encoded form of the critters. The above produces a string of the
e# critters in column-major order, all joined together, where the characters are
e# represented by numbers 0 to 5.
"|[\.]/"f=
e# Turn each number into the correct character.
2/4/ e# Split first into columns, then into critters. Now all we need to do is find these
e# the elements of this array in the processed input.
"><+-.,[]":L
e# A string of all BF characters in the same order as the critters. Store this in L.
er e# Do an element-wise replacement. This will leave non-critter blocks untouched.
{L&}, e# Filter the result. The elements are now either characters, or still full 4x2
e# blocks. We take the set intersection with the array (string) of BF characters.
e# If the current element is itself a character, it will be coerced into an array
e# containing that character, such that we get a non-empty intersection. If the
e# current element is a block instead, if contains arrays itself, so the set
e# intersection will always be empty.
e# The resulting array of characters is the desired BF program and will be printed
e# automatically at the end of the program.
```
The critters were encoded [with this script](http://cjam.aditsu.net/#code=qN%2F2%2F%3Azs__%261m%3E_pf%236b_p296b_%2Cp%3Acp&input=%5B..%5D%0A%5C%5D%5B%2F%0A%5B..%5D%0A%2F%5D%5B%5C%0A%5B..%5D%0A%2F%2F%5C%5C%0A%5B..%5D%0A%7C%7C%7C%7C%0A%5B%5D%5B%5D%0A%5B..%5D%0A%5B..%5D%0A%7C%2F%5C%7C%0A%7C%5C%2F%7C%0A%5B..%5D%0A%5B..%5D%0A%5C%2F%5C%2F). I found the base 296 for the encoding with the following, rather naive Mathematica script (which is still running in search for a better base):
```
b = 256;
While[True,
If[
FreeQ[
d = IntegerDigits[15177740418102340299431215985689972594497307279709, b],
x_ /; x > 255
],
Print@{b, Length@d}
];
b += 1;
]
```
[Answer]
# JavaScript ES6, ~~209~~ ~~198~~ 192 bytes
```
f=c=>{s=''
b=o=>c.substr(o,4)||1
for(i in c)s+=!~(d='1\\][/1/][\\1//\\\\1||||[][]11|/\\||\\/|11\\/\\/'.replace(/1/g,'[..]').indexOf(b(i)+b(++i+c.search(`
`))))|d%8?'':'><+-.,[]'[d/8]
return s}
```
The Stack Snippet below contains ungolfed code that you can easily run in any browser.
```
var f = function(c) {
var s = '';
var b = function(o) {
// If it is looking on the last line, this will return an empty string
// the second time, which could cause an inaccurate match.
// `||1` makes it return 1 instead of '', which won't match.
return c.substr(o, 4) || 1;
}
for (var i in c) {
r = b(i) + b(++i + c.search('\n'));
d = '1\\][/1/][\\1//\\\\1||||[][]11|/\\||\\/|11\\/\\/'.replace(/1/g, '[..]').indexOf(r);
s += !~d || d % 8 ? '' : '><+-.,[]' [d / 8];
}
return s;
}
// GUI code below
function run(){document.getElementById('s').innerHTML=f(document.getElementById('t').value);};document.getElementById('run').onclick=run;run()
```
```
<textarea id="t" cols="30" rows="10">
[..][[[[[..]]. ]|\/|
\][/[..]//\\[..][..]
[..]/][\[][]|/\|[..]
||||/\| [..]| |\/\/</textarea><br /><button id="run">Run</button><br /><code id="s"></code>
```
] |
[Question]
[
## Preface
As I was shooting an archery 900 round earlier today (10 ends at 6 arrows an end, and 10 ends at 3 arrows an end, for a total of 90 arrows and a maximum score of 900), I thought of this challenge.
In archery (assuming that you are shooting on a FITA supplied *target face* [the piece of paper that you shoot at]), for each arrow you can claim a maximum score of 10. The target face contains 10 or 11 rings of decreasing diameter, nested inside one another. From the inner ring outward, these are counted from 10 points, to one point (and in the case of 11 rings, there is a secondary innermost ring that counts as 'X', which scores as 10 but is used in tie breaking cases as the higher value). Observe:

Of course, I am referring to the FITA Metric scoring, as seen in the above illustration. If you look closely, you may observe the innermost ring, which is a faded dotted line, whose score is not marked. That is the 'X' that I was referring to, but you will not have to pay heed to that unless competing for the bonus.
## Challenge
Create a function (or full program, if the language doesn't support functions), that receives a perfectly square image as input (or image filename, if need be), containing some number of green (HEX #00FF00, RGB(0, 255, 0)) dots of some size, and returns the score. **The image may contain data other than the green dots**, but the green will always be the exact same shade.
You may imagine that the square image represents the target face, with the outermost ring touching at 4 points (top center, bottom center, right center, left center). The represented target face will always be of the same proportion, with all of the rings having a width of exactly 1/20th of the input target image's width. As an example, given an input image of input dimensions 400px by 400px, you may assume that each ring has an inner width of 20px, as illustrated below:

## Clarifications
* If touching two seperate rings, the higher of the two rings is counted
* You do not have to automatically account for misses or the 'x' case, unless trying for the bonus
* You may assume that no green circles are overlapping
* You may also assume that no other pixels of that shade of green are in the image
* The image will either be in a PNG, JPEG or PPM format (your choice)
* External image processing libraries are allowed, if authored before the posting of this question
* You may assume that all green circles on one target will have the same diameter
* If shooting (hah) for the overlapping circles bonus, you may assume that at least one circle in the image does not have another overlapping
* Standard loopholes are disallowed
## Test cases
The following two cases should each score ***52*** (or in the case of bonuses, 52 with 1 'x' and 1 miss):


And this last test case should score ***25***:

## Bonus
* -25 bytes if you also return the number of misses (outside any of the rings) as well
* -30 bytes if you also return the amount of Xs (assume that the innermost x is 3/100ths of the width of the image, and 10 is then 2/100ths of the width of the image. The 1-9 proportions remain unchanged)
* -35% byte count if you account for overlapping circles
This is code golf, so the least bytes wins. Have fun!
[Answer]
# Processing 2, 448-25=423 bytes
```
int x,y,w,b,v,c,m;color g;PImage i;void setup(){i=loadImage("f.png");w=i.width;size(w,w);g=#00ff00;image(i,0,0);b=v=x=y=c=m=0;loadPixels();while(y*w+x<w*w){if(pixels[y*w+x]==g){f(y,x);if(v>=0)c+=v;else m++;}v=-1;x++;if(x==w){x=0;y++;}}println(c+" "+m);}void f(int k,int l){pixels[k*w+l]=color(0);if(pixels[(k+1)*w+l]==g)f(k+1,l);if(pixels[k*w+l+1]==g)f(k,l+1);if(pixels[k*w+l-1]==g)f(k,l-1);k-=w/2;l-=w/2;b=10-(int)(sqrt(k*k+l*l)/(w/20));if(b>v)v=b;}
```
Reads in an image file f loops through the pixels until it finds green then flood fills the circle determining the point that is closest to the center. Then adds that score to a total. if the score is negative, it is added to a miss counter.
The program will output 2 numbers, the first is the score and the second is the number of misses.
```
int x,y,w,b,v,c,m;
color g;
PImage i;
void setup()
{
i=loadImage("f.png");
w=i.width;
size(w,w);
g=#00ff00;
image(i,0,0);
b=v=x=y=c=m=0;
loadPixels();
while(y*w+x<w*w)
{
if(pixels[y*w+x]==g)
{
f(y,x);
if(v>=0)c+=v;
else m++;
}
v=-1;
x++;
if(x==w){x=0;y++;}
}
print(c+" "+m);
}
void f(int k,int l)
{
pixels[k*w+l]=color(0);
if(pixels[(k+1)*w+l]==g)f(k+1,l);
if(pixels[k*w+l+1]==g)f(k,l+1);
if(pixels[k*w+l-1]==g)f(k,l-1);
k-=w/2;
l-=w/2;
b=10-(int)(sqrt(k*k+l*l)/(w/20));
if(b>v)v=b;
}
```
you can get processing [here](https://www.processing.org/download/)
[Answer]
# Perl 5 + GD: 225 - 25 = 200
Edit: Found [the reason](https://stackoverflow.com/questions/26586918/how-do-i-get-the-correct-rgb-value-for-a-pixel-with-gd) for the incorrect pixel reading in indexed PNGs and applied a workaround.
For some reason with the GD library the green pixel values are read as (4,254,4). I am not sure if this is specific to the PNG files included in the question. Line breaks can be removed in the code below.
```
use GD;$k=newFromPng GD::Image'-',1;
sub v{/ /;10-int((($'-@x/2)**2+($`-@x/2)**2)**.5/@x*20)}
map{v>0?($r+=v):$%++,fill$k @c,0if 65280==getPixel$k @c=split
}sort{v($_=$b)- v$_=$a}map{//;map"$_ $'",@x}@x=0..width$k-1;
print"$r $%"
```
Takes a PNG image on the input and prints 2 values: Number of points and misses. For example:
```
perl arch.pl <arch52.png
52 1
```
### Last minute change:
In true color mode that I needed anyway the color indexes used by `getPixel` and `fill` are simply integer encoded RGB values, so no need to use `rgb` and `colorAllocate` to convert to and from those indexes.
### Explanation:
* Generate list of all pixel coordinates (as space separated pairs of integers).
* Sort by potential score (using `sub v` which takes parameter through `$_` instead of standard parameters as it is shorter).
* For each pixel starting from the highest scoring ones if it is green add to the result and flood fill its location black.
[Answer]
# Haskell - 579-25 = 554 603-25-30 576-25-30 = 521 Bytes
Strategy:
* Make a list of (d,x,y) triples for all pixels (d is distance to center)
* sort the list by distance
* beginning with the greatest distance: if the pixel the only green pixel in a small neighborhood, keep it's distance in a list L, else blacken it
* calculate score from the distance list L
Output ist a triple (score,misses,Xs), e.g. `(52,1,1)` for the test image.
The program may fail if the pixel of a circle closest to the center is within 3 pixels of another circle.
```
import Data.List
import Codec.Picture
import Codec.Picture.RGBA8
import Codec.Picture.Canvas
z=fromIntegral
f(e,x,y)(v,h)|and$j x y:[not$j a b|a<-[x-3..x+3],b<-[y-3..y+3],not(a==x&&b==y)]=(v,e:h)|1<2=(setColor x y(PixelRGBA8 0 0 0 0)v,h)
where j n m|PixelRGBA8 0 255 0 _<-getColor n m v=0<1|0<1=0>1
d k r(h,i,j)|r>10*k=(h,i+1,j)|r<k*3/5=(h+10,i,j+1)|1<2=(10-(floor$r/k)+h,i,j)
main=do
i<-readImageRGBA8 "p.png"
let(Right c)=imageToCanvas i;s=canvasWidth c;q=[3..s-4];(_,g)=foldr f(c,[])$sort[(sqrt$(z x-z s/2)^2+(z y-z s/2)^2,x,y)|x<-q,y<-q]
print$foldr(d$z s/20)(0,0,0)g
```
[Answer]
# Mathematica - ~~371~~ 386 - 25 = 361
A more optimal solution. Computes the answer much faster than my Python solution.
```
i=IntegerPart;c=i/@((NestList[#+.01&,.1,10]~Prepend~1)*100);g[m_]:=Last@@c~Position~#-1&/@(i@Round@Last@#&/@(#*100&/@Riffle[RGBColor/@NestList[#+.01&,{.1,.1,.1},10],Table[Disk[{0,0},n],{n,1,.1,-.1}]]~Graphics~{ImageSize->ImageDimensions[m],PlotRangePadding->None}~ImageMultiply~ChanVeseBinarize[m,"TargetColor"->Green]~ComponentMeasurements~"Max"/.Rule[a_,b_]:>b))//{Total@#,#~Count~0}&
```
# Python with PIL - A trivial and non-optimal solution, 961 bytes
**This is simply to try to demonstrate a silly approach at solving the problem.**
It takes ~2 minutes to run the first two test cases, and ~20 minutes to run the third on my system because of the quickly made up, terribly resource intensive, and repulsively algorithmically complex circle detector. Despite this, it does meet requirements, though it is certainly not optimally golfed. The more green there is on the image, the longer it takes to run.
```
from PIL import Image,ImageDraw
a=lambda x,y,w,h:filter(lambda x:0<=x[0]<w and 0<=x[1]<h,[(x-1,y-1),(x,y-1),(x+1,y- 1),(x-1,y),(x,y),(x+1,y),(x-1,y+1),(x,y+1),(x+1,y+1)])
def b(c):
d=0,255,0;e,f=c.size;g=c.load();h,i=[],[];j=Image.new("RGB",(e,f));k=ImageDraw.Draw(j)
for l in range(e):
for m in range(e):
n=g[l,m][:-1]
if n==d and(l,m)not in i:
o=[(l,m)];p=[];q=1
while q:
q=0;r=o[:]
for s in o:
t=filter(lambda x:g[x[0],x[1]][:-1]==d and(x[0],x[1]) not in r,a(s[0],s[1],e,f))
if t:
r+=t
if len(t)<8:
p+=[s]
q=1
o=r
h+=[p]
for u in o:
i+=[u]
i+=[(l,m)]
p=map(lambda x:"#"+str(x)*6,'123456789ab');v=0;k.rectangle((0,0,e,f),fill=p[0])
for n in p[1:]:
w=e/20*v;x=e-w;k.ellipse((w,w,x,x),fill=n);v+=1
y=j.load();z=0
for l in h:
v=[]
for m in l:
s=y[m[0],m[1]]
if s not in v:
v+=[s]
v=max(v);z+=p.index("#"+''.join(map(lambda x:hex(x)[2:],v)))
return z
```
Takes a PIL image object, and returns the score.
## Steps it takes:
1. Isolate green circles (inefficiently)
* Find all neighbours of some pixel `n`, if any are green pixels then add them to the circle
* Determine rough outline by filtering out pixels that have 8 neighbours
2. Draw a target representation
* Create a blank canvas
* Draw a unique colored background (easy to implement misses)
* Draw nested ellipses with unique colors
3. Determine which scoring zones each circle is in by determining the color(s) of the target which would be underneath the circle
4. Choose the higher of the scoring zones (if multiple) and add the score to the total
5. Return the total
] |
[Question]
[
I've got a tough one for you!
My girlfriend recently came across a new show on MTV (USA). It's a terrible show, and everyone on it is trashy, but the "game" is pretty interesting. From Wikipedia:
>
> **Are You The One?** follows 20 people who are living together in Hawaii to find their perfect match. If the 10 men and 10 women are
> able to correctly choose all ten perfect matches in ten weeks, they
> will gain $1 million to split among them.
>
>
>
Now for the game portion (also from Wikipedia):
>
> Each episode the cast will pair up with who they believe their perfect
> match is to compete in a challenge. The winners of the challenge will
> go on a date, and have a chance to test their match in the truth
> booth. The cast members will choose one of the winning couples to go
> to the truth booth to determine if they are a perfect match or not.
> **This is the only way to confirm matches.** Each episode ends with a matching ceremony where the couples will be told how many perfect
> matches they have, but not which matches are correct.
>
>
>
**TL;DR:** This is a Mastermind derivative ( M(10,10) to be specific). The rules of the game are as follows:
1. You start with 2 sets of 10, let's call them Set A:
{A,B,C,D,E,F,G,H,I,J} and Set 2: {1,2,3,4,5,6,7,8,9,10}
2. The computer creates a solution (not visible to you) in the form
of {A1,B2,C3,D4,E5,F6,G7,H8,I9,J10}, where the members in set A are
mapped 1-to-1 to set 2. Another example of a solution could be
{A2,B5,C10,D8,E1,F7,G6,H4,I9,J3}.
3. Before your first turn, you get to ask if a single, particular
pair of your choice is correct. Your question would be in the form
of {A1} (e.g. {C8}), and you receive either a 1 (meaning correct) or
0 (meaning your guess is incorrect).
4. Your first actual turn. You make your first guess in the form of
{A1,B2,C3,D4,E5,F6,G7,H8,I9,J10}, or any permutation of your choice.
**Your guess cannot contain multiples of any item i.e. a guess of {A1,A2,A3,A4,A5,B6,B7,B8,B9,B10} is NOT a valid guess.** After each
turn, the computer tells you the **number of correct matches, but
NOT which matches are correct.**
5. Repeat steps 3 and 4 until you get every match correct (i.e. a
response of 10), or until your 10 moves are up (whichever is
sooner). If you solve it before or on your 10th turn, you win $1
million. Otherwise, you lose, and some people (or letters and
numbers) go home alone to spend eternity with their 10 cats.
This is NOT a shortest code contest. **The person who can solve a random matching in the least *average* number of guesses will be the winner.** Clever game playing and calculation speed will also likely factor in. I am assuming the average number of turns will almost certainly be greater than 10, so the odds of you winning the $1 million prize (presumably paid by MTV, not me) is slim. Just *how* impossible is it for the cast to win the grand prize?
Note: Putting it in the {A1, B2, ...} format is not necessarily required. I simply used that form in the question to make it absolutely clear what the puzzle is. If you do not put it in this form, please just explain how to call it.
*Good luck!*
[Answer]
## Python 2 (run faster if run using Pypy)
**Believed to almost always guess the correct pairing in 10 rounds or lower**
My algorithm is taken from my answer for mastermind as my hobby (see in [Ideone](http://ideone.com/fork/CVU0oL)). The idea is to find the guess which minimize the number of possibilities left in the worst case. My algorithm below just brute force it, but to save time, it just pick random guess if the number of possibilities left is larger than `RANDOM_THRESHOLD`. You can play around with this parameter to speed things up or to see better performance.
The algorithm is quite slow, on average 10s for one run if run using Pypy (if using normal CPython interpreter it's around 30s) so I can't test it on the whole permutations. But the performance is quite good, after around 30 tests I haven't seen any instance where it can't find the correct pairing in 10 rounds or lower.
Anyway, if this is used in real life show, it has plenty of time before the next round (one week?) so this algorithm can be used in real life =D
So I think it's safe to assume that on average this will find the correct pairings in 10 guesses or lower.
Try it yourself. I might improve the speed in the next few days (EDIT: it seems difficult to further improve, so I'll just leave the code as is. I tried only doing random pick, but even at `size=7`, it fails in 3 of the 5040 cases, so I decided to keep the cleverer method). You can run it as:
```
pypy are_you_the_one.py 10
```
Or, if you just want to see how it works, input smaller number (so that it runs faster)
To run a full test (warning: it'll take very long for `size` > 7), put a negative number.
Full test for `size=7` (completed in 2m 32s):
```
...
(6, 5, 4, 1, 3, 2, 0): 5 guesses
(6, 5, 4, 2, 0, 1, 3): 5 guesses
(6, 5, 4, 2, 0, 3, 1): 4 guesses
(6, 5, 4, 2, 1, 0, 3): 5 guesses
(6, 5, 4, 2, 1, 3, 0): 6 guesses
(6, 5, 4, 2, 3, 0, 1): 6 guesses
(6, 5, 4, 2, 3, 1, 0): 6 guesses
(6, 5, 4, 3, 0, 1, 2): 6 guesses
(6, 5, 4, 3, 0, 2, 1): 3 guesses
(6, 5, 4, 3, 1, 0, 2): 7 guesses
(6, 5, 4, 3, 1, 2, 0): 7 guesses
(6, 5, 4, 3, 2, 0, 1): 4 guesses
(6, 5, 4, 3, 2, 1, 0): 7 guesses
Average count: 5.05
Max count : 7
Min count : 1
Num success : 5040
```
If `RANDOM_THRESHOLD` and `CLEVER_THRESHOLD` are both set to a very high value (like 50000), it'll force the algorithm to find the optimal guess that minimizes the number of possibilities in the worst case. This is very slow, but very powerful. For example, running it on `size=6` asserts that it can find the correct pairings in maximum 5 rounds.
Although the average is higher compared to using the approximation (which is 4.11 rounds on average), but it always succeeds, even more with one round left to spare. This further strengthen our hypothesis that when `size=10`, it should almost always find the correct pairings in 10 rounds or less.
The result (completed in 3m 9s):
```
(5, 4, 2, 1, 0, 3): 5 guesses
(5, 4, 2, 1, 3, 0): 5 guesses
(5, 4, 2, 3, 0, 1): 4 guesses
(5, 4, 2, 3, 1, 0): 4 guesses
(5, 4, 3, 0, 1, 2): 5 guesses
(5, 4, 3, 0, 2, 1): 5 guesses
(5, 4, 3, 1, 0, 2): 5 guesses
(5, 4, 3, 1, 2, 0): 5 guesses
(5, 4, 3, 2, 0, 1): 5 guesses
(5, 4, 3, 2, 1, 0): 5 guesses
Average count: 4.41
Max count : 5
Min count : 1
Num success : 720
```
The code.
```
from itertools import permutations, combinations
import random, sys
from collections import Counter
INTERACTIVE = False
ORIG_PERMS = []
RANDOM_THRESHOLD = 100
CLEVER_THRESHOLD = 0
class Unbuffered():
def __init__(self, stream):
self.stream = stream
def write(self, data):
self.stream.write(data)
self.stream.flush()
def __getattr__(self, attr):
self.stream.getattr(attr)
sys.stdout = Unbuffered(sys.stdout)
def init(size):
global ORIG_PERMS
ORIG_PERMS = list(permutations(range(size)))
def evaluate(solution, guess):
if len(guess) == len(solution):
cor = 0
for sol, gss in zip(solution, guess):
if sol == gss:
cor += 1
return cor
else:
return 1 if solution[guess[0]] == guess[1] else 0
def remove_perms(perms, evaluation, guess):
return [perm for perm in perms if evaluate(perm, guess)==evaluation]
def guess_one(possible_perms, guessed_all, count):
if count == 1:
return (0,0)
pairs = Counter()
for perm in possible_perms:
for pair in enumerate(perm):
pairs[pair] += 1
perm_cnt = len(possible_perms)
return sorted(pairs.items(), key=lambda x: (abs(perm_cnt-x[1]) if x[1]<perm_cnt else perm_cnt,x[0]) )[0][0]
def guess_all(possible_perms, guessed_all, count):
size = len(possible_perms[0])
if count == 1:
fact = 1
for i in range(2, size):
fact *= i
if len(possible_perms) == fact:
return tuple(range(size))
else:
return tuple([1,0]+range(2,size))
if len(possible_perms) == 1:
return possible_perms[0]
if count < size and len(possible_perms) > RANDOM_THRESHOLD:
return possible_perms[random.randint(0, len(possible_perms)-1)]
elif count == size or len(possible_perms) > CLEVER_THRESHOLD:
(_, next_guess) = min((max(((len(remove_perms(possible_perms, evaluation, next_guess)), next_guess) for evaluation in range(len(next_guess))), key=lambda x: x[0])
for next_guess in possible_perms if next_guess not in guessed_all), key=lambda x: x[0])
return next_guess
else:
(_, next_guess) = min((max(((len(remove_perms(possible_perms, evaluation, next_guess)), next_guess) for evaluation in range(len(next_guess))), key=lambda x: x[0])
for next_guess in ORIG_PERMS if next_guess not in guessed_all), key=lambda x: x[0])
return next_guess
def main(size=4):
if size < 0:
size = -size
init(size)
counts = []
for solution in ORIG_PERMS:
count = run_one(solution, False)
counts.append(count)
print '%s: %d guesses' % (solution, count)
sum_count = float(sum(counts))
print 'Average count: %.2f' % (sum_count/len(counts))
print 'Max count : %d' % max(counts)
print 'Min count : %d' % min(counts)
print 'Num success : %d' % sum(1 for count in counts if count <= size)
else:
init(size)
solution = ORIG_PERMS[random.randint(0,len(ORIG_PERMS)-1)]
run_one(solution, True)
def run_one(solution, should_print):
if should_print:
print solution
size = len(solution)
cur_guess = None
possible_perms = list(ORIG_PERMS)
count = 0
guessed_one = []
guessed_all = []
while True:
count += 1
# Round A, guess one pair
if should_print:
print 'Round %dA' % count
if should_print:
print 'Num of possibilities: %d' % len(possible_perms)
cur_guess = guess_one(possible_perms, guessed_all, count)
if should_print:
print 'Guess: %s' % str(cur_guess)
if INTERACTIVE:
evaluation = int(raw_input('Number of correct pairs: '))
else:
evaluation = evaluate(solution, cur_guess)
if should_print:
print 'Evaluation: %s' % str(evaluation)
possible_perms = remove_perms(possible_perms, evaluation, cur_guess)
# Round B, guess all pairs
if should_print:
print 'Round %dB' % count
print 'Num of possibilities: %d' % len(possible_perms)
cur_guess = guess_all(possible_perms, guessed_all, count)
if should_print:
print 'Guess: %s' % str(cur_guess)
guessed_all.append(cur_guess)
if INTERACTIVE:
evaluation = int(raw_input('Number of correct pairs: '))
else:
evaluation = evaluate(solution, cur_guess)
if should_print: print 'Evaluation: %s' % str(evaluation)
if evaluation == size:
if should_print:
print 'Found %s in %d guesses' % (str(cur_guess), count)
else:
return count
break
possible_perms = remove_perms(possible_perms, evaluation, cur_guess)
if __name__=='__main__':
size = 4
if len(sys.argv) >= 2:
size = int(sys.argv[1])
if len(sys.argv) >= 3:
INTERACTIVE = bool(int(sys.argv[2]))
main(size)
```
[Answer]
# Fast Multi-Threaded C++ Version
I know it's been a while since this thread was active, but I have a cool addition to share: Here's a C++ implementation of the minimax algorithm for *Are You The One?*, which uses multi-threading to speed up the evaluation of each possible guess.
This version is much faster than the Python version (over 100x faster when original Python version is set to maximum `RANDOM_THRESHOLD` and `CLEVER_THRESHOLD`). It doesn't use any random guessing, but rather evaluates all permutations and submits as its guess the permutation that eliminates the greatest number of possible solutions (given the worst-case response).
For smaller games, calling "ayto -n" will run the game on all n! possible hidden matchings, and will give you a short summary of the results at the end.
Since it's still intractable to evaluate all 10! possible hidden matchings, if you call "ayto 10", for example, the simulator makes its fixed first three guesses, then runs minimax to choose its guess and assumes that it was given the worst-case evaluation. This leads us down a "worst-case path" to a hidden vector that is presumably in the class of vectors that takes the algorithm a maximum number of guesses to identify. This conjecture has not been tested.
Up to *n = 9*, there hasn't been a simulation that has taken more than *n* turns to solve.
To test this yourself, an example compilation would be the following:
```
g++ -std=c++11 -lpthread -o ayto ayto.cpp
```
Here's a small example with output:
```
$ ./ayto -4
Found (0, 1, 2, 3) in 2 guesses.
Found (0, 1, 3, 2) in 3 guesses.
Found (0, 2, 1, 3) in 2 guesses.
Found (0, 2, 3, 1) in 3 guesses.
Found (0, 3, 1, 2) in 2 guesses.
Found (0, 3, 2, 1) in 2 guesses.
Found (1, 0, 2, 3) in 1 guesses.
Found (1, 0, 3, 2) in 3 guesses.
Found (1, 2, 0, 3) in 3 guesses.
Found (1, 2, 3, 0) in 3 guesses.
Found (1, 3, 0, 2) in 3 guesses.
Found (1, 3, 2, 0) in 3 guesses.
Found (2, 0, 1, 3) in 3 guesses.
Found (2, 0, 3, 1) in 3 guesses.
Found (2, 1, 0, 3) in 3 guesses.
Found (2, 1, 3, 0) in 3 guesses.
Found (2, 3, 0, 1) in 3 guesses.
Found (2, 3, 1, 0) in 3 guesses.
Found (3, 0, 1, 2) in 3 guesses.
Found (3, 0, 2, 1) in 3 guesses.
Found (3, 1, 0, 2) in 3 guesses.
Found (3, 1, 2, 0) in 3 guesses.
Found (3, 2, 0, 1) in 3 guesses.
Found (3, 2, 1, 0) in 3 guesses.
***** SUMMARY *****
Avg. Turns: 2.75
Worst Hidden Vector: (0, 1, 3, 2) in 3 turns.
```
## Code
```
/* Multithreaded Mini-max Solver for MTV's Are You The One? */
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cassert>
#include <algorithm>
#include <numeric>
#include <string>
#include <vector>
#include <map>
#include <thread>
#include <cmath>
#define TEN_FACT (3628800)
#define NUM_CHUNKS (8)
using std::cout;
using std::cin;
using std::endl;
using std::vector;
using std::string;
using std::map;
using std::pair;
using std::find;
using std::abs;
using std::atoi;
using std::next_permutation;
using std::max_element;
using std::accumulate;
using std::reverse;
using std::thread;
struct args {
vector<string> *perms;
vector<string> *chunk;
pair<string, int> *cd;
int thread_id;
};
void simulate_game(const string &hidden, map<string, int> &turns_taken,
bool running_all);
bool picmp(const pair<string, int> &p1, const pair<string, int> &p2);
double map_avg(const map<string, int> &mp);
int nrand(int n);
int evaluate(const string &sol, const string &query);
vector<string> remove_perms(vector<string> &perms, int eval, string &query);
pair<string, int> guess_tb(vector<string> &perms, vector<string> &guessed_tb, int turn);
pair<string, int> guess_pm(vector<string> &perms, vector<string> &guessed, int turn);
void make_chunks(vector<string> &orig, vector<vector<string> > &chunks, int n);
string min_candidate(pair<string, int> *candidates, int n);
void get_score(struct args *args);
int wc_response(string &guess, vector<string> &perms);
bool prcmp(pair<int, int> x, pair<int, int> y);
void sequence_print(string s);
struct args **create_args(vector<string> &perms, pair<string, int> *cd, vector<string> &chunk, int thread_id);
vector<string> ORIGPERMS;
int main(int argc, char **argv)
{
int sz;
map<string, int> turns_taken;
const string digits = "0123456789";
bool running_all = false;
if (argc != 2) {
cout << "usage: 'ayto npairs'" << endl;
return 1;
} else {
if ((sz = atoi(argv[1])) < 0) {
sz = -sz;
running_all = true;
}
if (sz < 3 || sz > 10) {
cout << "usage: 'ayto npairs' where 3 <= npairs <= 10" << endl;;
return 1;
}
}
// initialize ORIGPERMS and possible_perms
string range = digits.substr(0, sz);
do {
ORIGPERMS.push_back(range);
} while (next_permutation(range.begin(), range.end()));
if (running_all) {
for (vector<string>::const_iterator it = ORIGPERMS.begin();
it != ORIGPERMS.end(); ++it) {
simulate_game(*it, turns_taken, running_all);
}
cout << "***** SUMMARY *****\n";
cout << "Avg. Turns: " << map_avg(turns_taken) << endl;
pair<string, int> wc = *max_element(turns_taken.begin(),
turns_taken.end(), picmp);
cout << "Worst Hidden Vector: ";
sequence_print(wc.first);
cout << " in " << wc.second << " turns." << endl;
} else {
string hidden = ORIGPERMS[nrand(ORIGPERMS.size())];
simulate_game(hidden, turns_taken, running_all);
}
return 0;
}
// simulate_game: run a single round of AYTO on hidden vector
void simulate_game(const string &hidden, map<string, int> &turns_taken,
bool running_all)
{
vector<string> possible_perms = ORIGPERMS;
pair<string, int> tbguess;
pair<string, int> pmguess;
vector<string> guessed;
vector<string> guessed_tb;
int e;
int sz = hidden.size();
if (!running_all) {
cout << "Running AYTO Simulator on Hidden Vector: ";
sequence_print(hidden);
cout << endl;
}
for (int turn = 1; ; ++turn) {
// stage one: truth booth
if (!running_all) {
cout << "**** Round " << turn << "A ****" << endl;
cout << "Num. Possibilities: " << possible_perms.size() << endl;
}
tbguess = guess_tb(possible_perms, guessed_tb, turn);
if (!running_all) {
cout << "Guess: ";
sequence_print(tbguess.first);
cout << endl;
e = tbguess.second;
cout << "Worst-Case Evaluation: " << e << endl;
} else {
e = evaluate(hidden, tbguess.first);
}
possible_perms = remove_perms(possible_perms, e, tbguess.first);
// stage two: perfect matching
if (!running_all) {
cout << "Round " << turn << "B" << endl;
cout << "Num. Possibilities: " << possible_perms.size() << endl;
}
pmguess = guess_pm(possible_perms, guessed, turn);
if (!running_all) {
cout << "Guess: ";
sequence_print(pmguess.first);
cout << endl;
e = pmguess.second;
cout << "Worst-Case Evaluation: " << e << endl;
} else {
e = evaluate(hidden, pmguess.first);
}
if (e == sz) {
cout << "Found ";
sequence_print(pmguess.first);
cout << " in " << turn << " guesses." << endl;
turns_taken[pmguess.first] = turn;
break;
}
possible_perms = remove_perms(possible_perms, e, pmguess.first);
}
}
// map_avg: returns average int component of a map<string, int> type
double map_avg(const map<string, int> &mp)
{
double sum = 0.0;
for (map<string, int>::const_iterator it = mp.begin();
it != mp.end(); ++it) {
sum += it->second;
}
return sum / mp.size();
}
// picmp: comparison function for pair<string, int> types, via int component
bool picmp(const pair<string, int> &p1, const pair<string, int> &p2)
{
return p1.second < p2.second;
}
// nrand: random integer in range [0, n)
int nrand(int n)
{
srand(time(NULL));
return rand() % n;
}
// evaluate: number of black hits from permutation or truth booth query
int evaluate(const string &sol, const string &query)
{
int hits = 0;
if (sol.size() == query.size()) {
// permutation query
int s = sol.size();
for (int i = 0; i < s; i++) {
if (sol[i] == query[i])
++hits;
}
} else {
// truth booth query
if (sol[atoi(query.substr(0, 1).c_str())] == query[1])
++hits;
}
return hits;
}
// remove_perms: remove solutions that are no longer possible after an eval
vector<string> remove_perms(vector<string> &perms, int eval, string &query)
{
vector<string> new_perms;
for (vector<string>::iterator i = perms.begin(); i != perms.end(); i++) {
if (evaluate(*i, query) == eval) {
new_perms.push_back(*i);
}
}
return new_perms;
}
// guess_tb: guesses best pair (pos, val) to go to the truth booth
pair<string, int> guess_tb(vector<string> &possible_perms,
vector<string> &guessed_tb, int turn)
{
static const string digits = "0123456789";
int n = possible_perms[0].size();
pair<string, int> next_guess;
if (turn == 1) {
next_guess.first = "00";
next_guess.second = 0;
} else if (possible_perms.size() == 1) {
next_guess.first = "0" + possible_perms[0].substr(0, 1);
next_guess.second = 1;
} else {
map<string, double> pair_to_count;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
pair_to_count[digits.substr(i, 1) + digits.substr(j, 1)] = 0;
}
}
// count up the occurrences of each pair in the possible perms
for (vector<string>::iterator p = possible_perms.begin();
p != possible_perms.end(); p++) {
int len = possible_perms[0].size();
for (int i = 0; i < len; i++) {
pair_to_count[digits.substr(i, 1) + (*p).substr(i, 1)] += 1;
}
}
double best_dist = 1;
int perm_cnt = possible_perms.size();
for (map<string, double>::iterator i = pair_to_count.begin();
i != pair_to_count.end(); i++) {
if (find(guessed_tb.begin(), guessed_tb.end(), i->first)
== guessed_tb.end()) {
// hasn't been guessed yet
if (abs(i->second/perm_cnt - .5) < best_dist) {
next_guess.first = i->first;
best_dist = abs(i->second/perm_cnt - .5);
if (i->second / perm_cnt < 0.5) // occurs in < half perms
next_guess.second = 0;
else // occurs in >= half perms
next_guess.second = 1;
}
}
}
}
guessed_tb.push_back(next_guess.first);
return next_guess;
}
// guess_pm: guess a full permutation using minimax
pair<string, int> guess_pm(vector<string> &possible_perms,
vector<string> &guessed, int turn)
{
static const string digits = "0123456789";
pair<string, int> next_guess;
vector<vector<string> > chunks;
int sz = possible_perms[0].size();
// on first turn, we guess "0, 1, ..., n-1" if truth booth was correct
// or "1, 0, ..., n-1" if truth booth was incorrect
if (turn == 1) {
int fact, i;
for (i = 2, fact = 1; i <= sz; fact *= i++)
;
if (possible_perms.size() == fact) {
next_guess.first = digits.substr(0, sz);
next_guess.second = 1;
} else {
next_guess.first = "10" + digits.substr(2, sz - 2);
next_guess.second = 1;
}
} else if (possible_perms.size() == 1) {
next_guess.first = possible_perms[0];
next_guess.second = possible_perms[0].size();
} else {
// run multi-threaded minimax to get next guess
pair<string, int> candidates[NUM_CHUNKS];
vector<thread> jobs;
make_chunks(ORIGPERMS, chunks, NUM_CHUNKS);
struct args **args = create_args(possible_perms, candidates, chunks[0], 0);
for (int j = 0; j < NUM_CHUNKS; j++) {
args[j]->chunk = &(chunks[j]);
args[j]->thread_id = j;
jobs.push_back(thread(get_score, args[j]));
}
for (int j = 0; j < NUM_CHUNKS; j++) {
jobs[j].join();
}
next_guess.first = min_candidate(candidates, NUM_CHUNKS);
next_guess.second = wc_response(next_guess.first, possible_perms);
for (int j = 0; j < NUM_CHUNKS; j++)
free(args[j]);
free(args);
}
guessed.push_back(next_guess.first);
return next_guess;
}
struct args **create_args(vector<string> &perms, pair<string, int> *cd, vector<string> &chunk, int thread_id)
{
struct args **args = (struct args **) malloc(sizeof(struct args*)*NUM_CHUNKS);
assert(args);
for (int i = 0; i < NUM_CHUNKS; i++) {
args[i] = (struct args *) malloc(sizeof(struct args));
assert(args[i]);
args[i]->perms = &perms;
args[i]->cd = cd;
}
return args;
}
// make_chunks: return pointers to n (nearly) equally sized vectors
// from the original vector
void make_chunks(vector<string> &orig, vector<vector<string> > &chunks, int n)
{
int sz = orig.size();
int chunk_sz = sz / n;
int n_with_extra = sz % n;
vector<string>::iterator b = orig.begin();
vector<string>::iterator e;
for (int i = 0; i < n; i++) {
int m = chunk_sz; // size of this chunk
if (n_with_extra) {
++m;
--n_with_extra;
}
e = b + m;
vector<string> subvec(b, e);
chunks.push_back(subvec);
b = e;
}
}
// min_candidate: string with min int from array of pair<string, ints>
string min_candidate(pair<string, int> *candidates, int n)
{
int i, minsofar;
string minstring;
minstring = candidates[0].first;
minsofar = candidates[0].second;
for (i = 1; i < n; ++i) {
if (candidates[i].second < minsofar) {
minsofar = candidates[i].second;
minstring = candidates[i].first;
}
}
return minstring;
}
// get_score: find the maximum number of remaining solutions over all
// possible responses to the query s
// this version takes a chunk and finds the guess with lowest score
// from that chunk
void get_score(struct args *args)
{
// parse the args struct
vector<string> &chunk = *(args->chunk);
vector<string> &perms = *(args->perms);
pair<string, int> *cd = args->cd;
int thread_id = args->thread_id;
typedef vector<string>::const_iterator vec_iter;
int sz = perms[0].size();
pair<string, int> best_guess;
best_guess.second = perms.size();
int wc_num_remaining;
for (vec_iter s = chunk.begin(); s != chunk.end(); ++s) {
vector<int> matches(sz + 1, 0);
for (vec_iter p = perms.begin(); p != perms.end(); ++p) {
++matches[evaluate(*s, *p)];
}
wc_num_remaining = *max_element(matches.begin(), matches.end());
if (wc_num_remaining < best_guess.second) {
best_guess.first = *s;
best_guess.second = wc_num_remaining;
}
}
cd[thread_id] = best_guess;
return;
}
// wc_response: the response to guess that eliminates the least solutions
int wc_response(string &guess, vector<string> &perms)
{
map<int, int> matches_eval;
for (vector<string>::iterator it = perms.begin(); it!=perms.end(); ++it) {
++matches_eval[evaluate(guess, *it)];
}
return max_element(matches_eval.begin(), matches_eval.end(), prcmp)->first;
}
// prcmp: comparison function for pair<int, int> types in map
bool prcmp(pair<int, int> x, pair<int, int> y)
{
return x.second < y.second;
}
void sequence_print(const string s)
{
for (string::const_iterator i = s.begin(); i != s.end(); i++) {
if (i == s.begin())
cout << "(";
cout << *i;
if (i != s.end() - 1)
cout << ", ";
else
cout << ")";
}
}
```
[Answer]
## CJam -19 turns- An Idiot's Strategy
This is not a serious answer but a demonstration. This is an idiot's solution where he does not take into account the number of correct pairings information provided from the second part of the turn. With completely random pairings, this takes an average of 27 weeks. This answer is insuffienct as I have said but indicates that the odds for an intellegent group (much more intellegent that this program) is likely not as slim as you might expect. The more intellegent algorithms i've written, however take alot more time to run so I can' actually get answers from them.
**Update:** The code below was updated to use state that it should remove ones that don't work if the only correct ones are ones we already knew were correct. It was also editted to show my random "correct answer" generator. The average result is now only 19. It is still a dumb solution but it is better than the previous marginally.
```
A,{__,mr=_@@-}A*;]sedS*:Z;
ZS/:i:G; "Set the input (goal) to G";
{UU@{G2$==@+\)}%~;}:C; "This is the tool to count how many of an array agree with G";
{:Y;1$1$<{Y-}%Yaa+@@)>{Y-}%+}:S; "for stack A X Y, sets the Xth value in the array to Y";
{:Y;1$1$<2$2$=Y-a+@@)>+}:R; "for stack A X Y, removes Y from the Xth value in the array";
1:D; "Set turn counter to one. if zero exits loop";
A,]A* "array of arrays that has all possible values for an ordering";
{ "start of loop";
_V=(\;_GV=={V\SV):V;}{V\R}? "Guesses a number for the first unknown. If right sets the pair; else erases it";
_[{(_,_{mr=}{;;11}?:Y\{Y-}%}A*;]_C "guesses random possible arrangement and determines how many are right, error=11";
\_{+}*45-:Y{Y;{_11={;BY-}{}?}%}{}?\ "error correct by including the missing number";
_V={;V:X>{X\RX):X;}%~LV}{}? "if all new are wrong, makes sure they aren't guessed again";
_A={Dp0:D;;p;}{D):D;;;}? "If all are right, prints it an tells loop to exit. Else increments counter";
D}g "repeat from start of loop";
```
] |
[Question]
[
*Bracket numbers* provide a simple way to express large integers using only left bracket, space, and right bracket (`[ ]`).
A bracket number is defined as a string of one or more pairs of matching brackets `[...]` called *chunks*, each separated from its neighbors by zero or more spaces.
The number of spaces between each chunk defines the [hyperoperation](http://en.wikipedia.org/wiki/Hyperoperation) between them. No spaces means addition, 1 space means multiplication, 2 spaces means exponentiation, 3 spaces means [tetration](http://en.wikipedia.org/wiki/Tetration), and so on. Higher order hyperoperations take precedence, so tetration occurs before exponentiation, exponentiation occurs before multiplication, etc. They are also right-associative, so `a^b^c` is computed as `a^(b^c)`. (But `a^b*c` is still `(a^b)*c`.)
Each chunk may either be empty (`[]`) or contain another bracket number. Empty chunks have the value 0. Non-empty chunks have the value of their contained bracket number plus 1.
**Examples:** (`^^` is tetration, `^^^` is [pentation](http://en.wikipedia.org/wiki/Pentation))
* `[[]]` has value 1 because it is 0 (`[]`) incremented by 1
* `[[[]]]` has value 2 but so does `[[]][[]]` since the two ones (`[[]]`) are added
* `[[[]]] [[[[]]] [[[[]]]]][[[]]]` has value 20 = (2\*((2^3)+1))+2
* `[[[]]] [[[[]]]]` has value 65536 = 2^^^3 = 2^^(2^^2) = 2^^4 == 2^(2^(2^2))
* `[[[[]]]] [[[]]] [[]]` has value 7625597484987 = 3^^^(2^^^1) = 3^^^2 = 3^^3 = 3^(3^3)
In valid bracket numbers:
* There will never be leading or trailing spaces.
* There will always be at least one pair of matching brackets.
* All left brackets will have a matching right bracket.
* A space will never appear directly to the right of `[` nor to the left of `]`.
* The value is always a non-negative integer.
# Challenge
Notice that there may be many forms for a bracket number that give the same value. `[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]` and `[[[]]] [[[[]]]]` both represent 16, but the latter is much shorter.
Your challenge is to write an algorithm that attempts to find the shortest bracket number representation of a given value. For example, I believe the shortest way to represent 16 is with 17 characters as `[[[]]] [[[[]]]]`.
# Scoring (Updated)
Let *S* be the set of integers from 1 to 256 (inclusive) as well as the following ten values:
```
8191 13071 524287 2147483647 1449565302 1746268229 126528612 778085967 1553783038 997599288
```
(The first 4 are Mersenne primes, the rest are random.)
The submission that generates the shortest set of bracket numbers for everything in *S* will win. Your score is the sum of the lengths of your bracket numbers for all values in *S* (smaller is better).
With your code please submit a list of your bracket numbers for all of *S*, the exact order is not terribly important. e.g.:
```
1=[[]]
2=[[[]]]
3=[[[[]]]]
...
2147483647=[...]
...
```
(I know this is not the optimal scoring method but I am not set up to run a bunch of random heuristic tests on each submission. Sorry :( )
# Rules
* You may **not** hardcode any bracket numbers besides the trivial incremental solutions (`[], [[]], [[[]]], ...`). Your program must actually be looking for optimally short representations. (Though the results may be suboptimal.)
* Your algorithm should work for all non-negative integers below 2,147,483,648 (2^31). **You may not specifically focus on the values in *S*.**
* For any particular input, your algorithm should run in at most 10 minutes on a decent modern computer (~2.5Ghz processor, ~6GB RAM).
* In the (seemingly) rare chance of a tie the highest voted submission wins.
* If you copy another solution or revise it without attribution you will be disqualified.
[Answer]
## Mathematica
**Note:** This algorithm is never going to be able to get anywhere near the larger test numbers. I'd need a substantially different approach, so I'll just leave it as is for others to check their lower numbers against. You may consider this submission invalid.
Here is a start for the first 256 numbers (the others were added after I started, and I probably need to find a separate solution for those)
```
1=[[]]
2=[[[]]]
3=[[[[]]]]
4=[[[[[]]]]]
5=[[[[[[]]]]]]
6=[[[[[[[]]]]]]]
7=[[[[[[[[]]]]]]]]
8=[[[]]] [[[[]]]]
9=[[[[]]]] [[[]]]
10=[[[[[]]]] [[[]]]]
11=[[[[[[]]]] [[[]]]]]
12=[[[[[]]]]] [[[[]]]]
13=[[[[[[]]]]] [[[[]]]]]
14=[[[[[[[]]]]] [[[[]]]]]]
15=[[[[[[]]]]]] [[[[]]]]
16=[[[]]] [[[[]]]]
17=[[[[]]] [[[[]]]]]
18=[[[[[]]] [[[[]]]]]]
19=[[[[[[]]] [[[[]]]]]]]
20=[[[[[[]]]]]] [[[[[]]]]]
21=[[[[[[[]]]]]] [[[[[]]]]]]
22=[[[[[[[[]]]]]] [[[[[]]]]]]]
23=[[[[[[[[[]]]]]] [[[[[]]]]]]]]
24=[[[[[[[]]]]]]] [[[[[]]]]]
25=[[[[[[]]]]]] [[[]]]
26=[[[[[[[]]]]]] [[[]]]]
27=[[[[]]]] [[[]]]
28=[[[[[]]]] [[[]]]]
29=[[[[[[]]]] [[[]]]]]
30=[[[[[[[]]]] [[[]]]]]]
31=[[[[[[[[]]]] [[[]]]]]]]
32=[[[]]] [[[[[[]]]]]]
33=[[[[]]] [[[[[[]]]]]]]
34=[[[[[]]] [[[[[[]]]]]]]]
35=[[[[[[]]] [[[[[[]]]]]]]]]
36=[[[[[[[]]]]]]] [[[]]]
37=[[[[[[[[]]]]]]] [[[]]]]
38=[[[[[[[[[]]]]]]] [[[]]]]]
39=[[[[[[[[[[]]]]]]] [[[]]]]]]
40=[[[]]] [[[[]]]] [[[[[[]]]]]]
41=[[[[]]] [[[[]]]] [[[[[[]]]]]]]
42=[[[[[[[[]]]]]]]] [[[[[[[]]]]]]]
43=[[[[[[[[[]]]]]]]] [[[[[[[]]]]]]]]
44=[[[[[[]]]] [[[]]]]] [[[[[]]]]]
45=[[[[]]]] [[[]]] [[[[[[]]]]]]
46=[[[[[]]]] [[[]]] [[[[[[]]]]]]]
47=[[[[[[]]]] [[[]]] [[[[[[]]]]]]]]
48=[[[]]] [[[[]]]] [[[[]]]]
49=[[[[[[[[]]]]]]]] [[[]]]
50=[[[[[[[[[]]]]]]]] [[[]]]]
51=[[[[[[[[[[]]]]]]]] [[[]]]]]
52=[[[[[[[]]]]]] [[[]]]] [[[]]]
53=[[[[[[[[]]]]]] [[[]]]] [[[]]]]
54=[[[[]]]] [[[]]] [[[]]]
55=[[[[[]]]] [[[]]] [[[]]]]
56=[[[[[]]]] [[[]]]] [[[]]]
57=[[[[[[]]]] [[[]]]] [[[]]]]
58=[[[[[[]]]] [[[]]]]] [[[]]]
59=[[[[[[[]]]] [[[]]]]] [[[]]]]
60=[[[[[[[]]]] [[[]]]]]] [[[]]]
61=[[[[[[[[]]]] [[[]]]]]] [[[]]]]
62=[[[[[[[[]]]] [[[]]]]]]] [[[]]]
63=[[[[]]]] [[[]]] [[[[[[[[]]]]]]]]
64=[[[[[]]]]] [[[[]]]]
65=[[[[[[]]]]] [[[[]]]]]
66=[[[[[[[]]]]] [[[[]]]]]]
67=[[[[[[[[]]]]] [[[[]]]]]]]
68=[[[[[[[[[]]]]] [[[[]]]]]]]]
69=[[[[[[[[[[]]]]] [[[[]]]]]]]]]
70=[[[[[[[[[[[]]]]] [[[[]]]]]]]]]]
71=[[[[[[[[[[[[]]]]] [[[[]]]]]]]]]]]
72=[[[[[[[]]]]]]] [[[]]] [[[]]]
73=[[[[[[[[]]]]]]] [[[]]] [[[]]]]
74=[[[[[[[[]]]]]]] [[[]]]] [[[]]]
75=[[[[[[]]]]]] [[[]]] [[[[]]]]
76=[[[[[[[]]]]]] [[[]]] [[[[]]]]]
77=[[[[[[[[]]]]]] [[[]]] [[[[]]]]]]
78=[[[[[[[]]]]]] [[[]]]] [[[[]]]]
79=[[[[[[[[]]]]]] [[[]]]] [[[[]]]]]
80=[[[]]] [[[[]]]] [[[[[[]]]]]]
81=[[[[]]]] [[[[[]]]]]
82=[[[[[]]]] [[[[[]]]]]]
83=[[[[[[]]]] [[[[[]]]]]]]
84=[[[[[[[]]]] [[[[[]]]]]]]]
85=[[[[[[[[]]]] [[[[[]]]]]]]]]
86=[[[[[[[[[]]]] [[[[[]]]]]]]]]]
87=[[[[[[]]]] [[[]]]]] [[[[]]]]
88=[[[[[[[]]]] [[[]]]]] [[[[]]]]]
89=[[[[[[[[]]]] [[[]]]]] [[[[]]]]]]
90=[[[[[[[]]]] [[[]]]]]] [[[[]]]]
91=[[[[[[[[]]]] [[[]]]]]] [[[[]]]]]
92=[[[[[[[[[]]]] [[[]]]]]] [[[[]]]]]]
93=[[[[[[[[]]]] [[[]]]]]]] [[[[]]]]
94=[[[[[[[[[]]]] [[[]]]]]]] [[[[]]]]]
95=[[[[[[]]] [[[[]]]]]]] [[[[[[]]]]]]
96=[[[]]] [[[[[[]]]]]] [[[[]]]]
97=[[[[]]] [[[[[[]]]]]] [[[[]]]]]
98=[[[[[[[[]]]]]]]] [[[]]] [[[]]]
99=[[[[]]] [[[[[[]]]]]]] [[[[]]]]
100=[[[[[]]]] [[[]]]] [[[]]]
101=[[[[[[]]]] [[[]]]] [[[]]]]
102=[[[[[[[]]]] [[[]]]] [[[]]]]]
103=[[[[[[[[]]]] [[[]]]] [[[]]]]]]
104=[[[[[[[]]]]]] [[[]]]] [[[[[]]]]]
105=[[[[[[[[]]]]]] [[[]]]] [[[[[]]]]]]
106=[[[[[[[[[]]]]]] [[[]]]] [[[[[]]]]]]]
107=[[[[[[[[[[]]]]]] [[[]]]] [[[[[]]]]]]]]
108=[[[[]]]] [[[]]] [[[[[]]]]]
109=[[[[[]]]] [[[]]] [[[[[]]]]]]
110=[[[[[[]]]] [[[]]] [[[[[]]]]]]]
111=[[[[[[[[]]]]]]] [[[]]]] [[[[]]]]
112=[[[[[]]]] [[[]]]] [[[[[]]]]]
113=[[[[[[]]]] [[[]]]] [[[[[]]]]]]
114=[[[[[[[]]]] [[[]]]] [[[[[]]]]]]]
115=[[[[[[[[]]]] [[[]]]] [[[[[]]]]]]]]
116=[[[[[[]]]] [[[]]]]] [[[[[]]]]]
117=[[[[[[[]]]] [[[]]]]] [[[[[]]]]]]
118=[[[[[[[[]]]] [[[]]]]] [[[[[]]]]]]]
119=[[[[]]] [[[[]]]]] [[[[[[[[]]]]]]]]
120=[[[[[[[]]]] [[[]]]]]] [[[[[]]]]]
121=[[[[[[]]]] [[[]]]]] [[[]]]
122=[[[[[[[]]]] [[[]]]]] [[[]]]]
123=[[[[[[[[]]]] [[[]]]]] [[[]]]]]
124=[[[[[[[[[]]]] [[[]]]]] [[[]]]]]]
125=[[[[[[]]]]]] [[[[]]]]
126=[[[[[[[]]]]]] [[[[]]]]]
127=[[[[[[[[]]]]]] [[[[]]]]]]
128=[[[]]] [[[[[[[[]]]]]]]]
129=[[[[]]] [[[[[[[[]]]]]]]]]
130=[[[[[]]] [[[[[[[[]]]]]]]]]]
131=[[[[[[]]] [[[[[[[[]]]]]]]]]]]
132=[[[[[[[]]]]] [[[[]]]]]] [[[]]]
133=[[[[[[[[]]]]] [[[[]]]]]] [[[]]]]
134=[[[[[[[[]]]]] [[[[]]]]]]] [[[]]]
135=[[[[]]]] [[[]]] [[[[[[]]]]]]
136=[[[[[]]]] [[[]]] [[[[[[]]]]]]]
137=[[[[[[]]]] [[[]]] [[[[[[]]]]]]]]
138=[[[[[[[]]]] [[[]]] [[[[[[]]]]]]]]]
139=[[[[[[[[]]]] [[[]]] [[[[[[]]]]]]]]]]
140=[[[[[]]]] [[[]]]] [[[[[[]]]]]]
141=[[[[[[]]]] [[[]]]] [[[[[[]]]]]]]
142=[[[[[[[]]]] [[[]]]] [[[[[[]]]]]]]]
143=[[[[[[[[]]]] [[[]]]] [[[[[[]]]]]]]]]
144=[[[[[[[]]]]]]] [[[]]] [[[[[]]]]]
145=[[[[[[]]]] [[[]]]]] [[[[[[]]]]]]
146=[[[[[[[]]]] [[[]]]]] [[[[[[]]]]]]]
147=[[[[[[[[]]]]]]]] [[[]]] [[[[]]]]
148=[[[[[[[[[]]]]]]]] [[[]]] [[[[]]]]]
149=[[[[[[[[[[]]]]]]]] [[[]]] [[[[]]]]]]
150=[[[[[[]]]]]] [[[]]] [[[[[[[]]]]]]]
151=[[[[[[[]]]]]] [[[]]] [[[[[[[]]]]]]]]
152=[[[[[[[[[]]]]]]] [[[]]]]] [[[[[]]]]]
153=[[[[]]] [[[[]]]]] [[[[]]]] [[[]]]
154=[[[[[]]] [[[[]]]]] [[[[]]]] [[[]]]]
155=[[[[[[[[]]]] [[[]]]]]]] [[[[[[]]]]]]
156=[[[[[[[]]]]]] [[[]]]] [[[[[[[]]]]]]]
157=[[[[[[[[]]]]]] [[[]]]] [[[[[[[]]]]]]]]
158=[[[[[[[[]]]]]] [[[]]]] [[[[]]]]] [[[]]]
159=[[[[[[[[]]]]]] [[[]]]] [[[]]]] [[[[]]]]
160=[[[]]] [[[[[[]]]]]] [[[[[[]]]]]]
161=[[[[]]] [[[[[[]]]]]] [[[[[[]]]]]]]
162=[[[[]]]] [[[[[]]]]] [[[]]]
163=[[[[[]]]] [[[[[]]]]] [[[]]]]
164=[[[[[]]]] [[[[[]]]]]] [[[]]]
165=[[[[[[]]]] [[[[[]]]]]] [[[]]]]
166=[[[[[[]]]] [[[[[]]]]]]] [[[]]]
167=[[[[[[[]]]] [[[[[]]]]]]] [[[]]]]
168=[[[[[[[]]]] [[[[[]]]]]]]] [[[]]]
169=[[[[[[]]]]] [[[[]]]]] [[[]]]
170=[[[[[[[]]]]] [[[[]]]]] [[[]]]]
171=[[[[[[[[]]]]] [[[[]]]]] [[[]]]]]
172=[[[[[[[[[]]]]] [[[[]]]]] [[[]]]]]]
173=[[[[[[[[[[]]]]] [[[[]]]]] [[[]]]]]]]
174=[[[[[[]]]] [[[]]]]] [[[[[[[]]]]]]]
175=[[[[[[]]]]]] [[[]]] [[[[[[[[]]]]]]]]
176=[[[]]] [[[[]]]] [[[[[[]]]] [[[]]]]]
177=[[[[[[[]]]] [[[]]]]] [[[]]]] [[[[]]]]
178=[[[[[[[[]]]] [[[]]]]] [[[]]]] [[[[]]]]]
179=[[[[[[[[[]]]] [[[]]]]] [[[]]]] [[[[]]]]]]
180=[[[[[[[]]]]]]] [[[]]] [[[[[[]]]]]]
181=[[[[[[[[]]]]]]] [[[]]] [[[[[[]]]]]]]
182=[[[[[[[[[]]]]]]] [[[]]] [[[[[[]]]]]]]]
183=[[[[[[[[[[]]]]]]] [[[]]] [[[[[[]]]]]]]]]
184=[[[[[]]]] [[[]]] [[[[[[]]]]]]] [[[[[]]]]]
185=[[[[[[[[]]]]]]] [[[]]]] [[[[[[]]]]]]
186=[[[[[[[[[]]]]]]] [[[]]]] [[[[[[]]]]]]]
187=[[[[]]] [[[[]]]]] [[[[[[]]]] [[[]]]]]
188=[[[[[]]] [[[[]]]]] [[[[[[]]]] [[[]]]]]]
189=[[[[]]]] [[[]]] [[[[[[[[]]]]]]]]
190=[[[[[]]]] [[[]]] [[[[[[[[]]]]]]]]]
191=[[[[[[]]]] [[[]]] [[[[[[[[]]]]]]]]]]
192=[[[[[]]]]] [[[[]]]] [[[[]]]]
193=[[[[[[]]]]] [[[[]]]] [[[[]]]]]
194=[[[[[[[]]]]] [[[[]]]] [[[[]]]]]]
195=[[[[[[]]]]] [[[[]]]]] [[[[]]]]
196=[[[[[[[]]]]] [[[[]]]]]] [[[]]]
197=[[[[[[[[]]]]] [[[[]]]]]] [[[]]]]
198=[[[[[[[]]]]] [[[[]]]]]] [[[[]]]]
199=[[[[[[[[]]]]] [[[[]]]]]] [[[[]]]]]
200=[[[[[]]]] [[[]]]] [[[]]] [[[]]]
201=[[[[[[]]]] [[[]]]] [[[]]] [[[]]]]
202=[[[[[[]]]] [[[]]]] [[[]]]] [[[]]]
203=[[[[[[[]]]] [[[]]]] [[[]]]] [[[]]]]
204=[[[[[[[[[]]]]] [[[[]]]]]]]] [[[[]]]]
205=[[[[[[[[[[]]]]] [[[[]]]]]]]] [[[[]]]]]
206=[[[[[[[[]]]] [[[]]]] [[[]]]]]] [[[]]]
207=[[[[[[[[[[]]]]] [[[[]]]]]]]]] [[[[]]]]
208=[[[]]] [[[[]]]] [[[[[[]]]]] [[[[]]]]]
209=[[[[]]] [[[[]]]] [[[[[[]]]]] [[[[]]]]]]
210=[[[[[[[]]]] [[[]]]]]] [[[[[[[[]]]]]]]]
211=[[[[[[[[]]]] [[[]]]]]] [[[[[[[[]]]]]]]]]
212=[[[[[[[[]]]]]] [[[]]]] [[[]]]] [[[[[]]]]]
213=[[[[[[[[[[[[]]]]] [[[[]]]]]]]]]]] [[[[]]]]
214=[[[[[[[[[[[[[]]]]] [[[[]]]]]]]]]]] [[[[]]]]]
215=[[[[[[[[[]]]]]]]] [[[[[[[]]]]]]]] [[[[[[]]]]]]
216=[[[[[[[]]]]]]] [[[[]]]]
217=[[[[[[[[]]]]]]] [[[[]]]]]
218=[[[[[[[[[]]]]]]] [[[[]]]]]]
219=[[[[[[[[[[]]]]]]] [[[[]]]]]]]
220=[[[[[[[[[[[]]]]]]] [[[[]]]]]]]]
221=[[[[[[[[[[[[]]]]]]] [[[[]]]]]]]]]
222=[[[[[[[[[[[[[]]]]]]] [[[[]]]]]]]]]]
223=[[[[[[[[[[[[[[]]]]]]] [[[[]]]]]]]]]]]
224=[[[[[]]]] [[[]]]] [[[]]] [[[[]]]]
225=[[[[[[]]]]]] [[[]]] [[[[]]]] [[[]]]
226=[[[[[[[]]]]]] [[[]]] [[[[]]]] [[[]]]]
227=[[[[[[[[]]]]]] [[[]]] [[[[]]]] [[[]]]]]
228=[[[[[[]]]] [[[]]]] [[[]]]] [[[[[]]]]]
229=[[[[[[[]]]] [[[]]]] [[[]]]] [[[[[]]]]]]
230=[[[[[[[[]]]] [[[]]]] [[[]]]] [[[[[]]]]]]]
231=[[[[]]] [[[[[[]]]]]]] [[[[[[[[]]]]]]]]
232=[[[[[[]]]] [[[]]]]] [[[]]] [[[[]]]]
233=[[[[[[[]]]] [[[]]]]] [[[]]] [[[[]]]]]
234=[[[[[[[]]]]]] [[[]]]] [[[[]]]] [[[]]]
235=[[[[[[[[]]]]]] [[[]]]] [[[[]]]] [[[]]]]
236=[[[[[[[]]]] [[[]]]]] [[[]]]] [[[[[]]]]]
237=[[[[[[[[]]]]]] [[[]]]] [[[[]]]]] [[[[]]]]
238=[[[[[]]] [[[[[[]]]]]]]] [[[[[[[[]]]]]]]]
239=[[[[[[]]] [[[[[[]]]]]]]] [[[[[[[[]]]]]]]]]
240=[[[]]] [[[[]]]] [[[[[[]]]]]] [[[[]]]]
241=[[[[]]] [[[[]]]] [[[[[[]]]]]] [[[[]]]]]
242=[[[[[[]]]] [[[]]]]] [[[]]] [[[]]]
243=[[[[]]]] [[[[[[]]]]]]
244=[[[[[]]]] [[[[[[]]]]]]]
245=[[[[[[]]]] [[[[[[]]]]]]]]
246=[[[[[[[]]]] [[[[[[]]]]]]]]]
247=[[[[[[[[]]]] [[[[[[]]]]]]]]]]
248=[[[[[[[[[]]]] [[[[[[]]]]]]]]]]]
249=[[[[[[]]]] [[[[[]]]]]]] [[[[]]]]
250=[[[[[[]]]]]] [[[[]]]] [[[]]]
251=[[[[[[[]]]]]] [[[[]]]] [[[]]]]
252=[[[[[[[]]]]]] [[[[]]]]] [[[]]]
253=[[[[[[[[]]]]]] [[[[]]]]] [[[]]]]
254=[[[[[[[[]]]]]] [[[[]]]]]] [[[]]]
255=[[[[[[[[[]]]]]] [[[[]]]]]] [[[]]]]
256=[[[[[]]]]] [[[]]]
```
The total length of the first 256 numbers is **7963** characters. I don't know if this is optimal.
Ignoring addition, the results for 8191 and 13071 were found in a few seconds and 524387 in a couple of minutes as
```
8191=[[[[[[[[]]]]]] [[[[]]]]] [[[[[[]]]]] [[[[]]]]]]
13071=[[[[[[[[]]]]] [[[[]]]]]] [[[]]]] [[[[]]]]
524387=[[[[[[[[]]]]] [[[[]]]]] [[[[[]]]]] [[[[]]]]] [[[[[[[]]]]]] [[[[]]]]]]
```
at **164** characters together.
Here is the code:
```
ClearAll[repr, sl, i, j, op, re, frontop, rearop, lastop];
repr[n_] = "";
repr[0] = "[]";
(*Hard-code higher-order solutions*)
repr[65536] = "[[[]]] [[[[]]]]";
repr[16] = "[[[]]] [[[[]]]]";
repr[27] = "[[[[]]]] [[[]]]";
repr[256] = "[[[[[]]]]] [[[]]]";
repr[3125] = "[[[[[[]]]]]] [[[]]]";
repr[46656] = "[[[[[[[]]]]]]] [[[]]]";
repr[823543] = "[[[[[[[[]]]]]]]] [[[]]]";
repr[16777216] = "[[[[[[[[[]]]]]]]]] [[[]]]";
repr[387420489] = "[[[[[[[[[[]]]]]]]]]] [[[]]]";
frontop[n_] = 2;
rearop[n_] = 2;
sl[n_] := If[repr[n] == "", Infinity, StringLength@repr@n];
n = 256;
op[0] := (# + #2) &
op[1] := (#*#2) &
op[2] := (#^#2) &
re[0] := (repr@# <> repr@#2) &
re[1] := (repr@# <> " " <> repr@#2) &
re[2] := (repr@# <> " " <> repr@#2) &
For[i = 0, i < n, ++i,
If[sl[i + 1] >= sl[i] + 2,
repr[i + 1] = "[" <> repr[i] <> "]";
frontop[i + 1] = 2; rearop[i + 1] = 2
];
For[m = 0, m < 3, ++m,
If[rearop[i] >= m,
For[j = 1, j <= i, ++j,
If[frontop[j] < m || (res = op[m][i, j]) > n, Break[]];
rep = re[m][i, j];
If[sl[res] > StringLength@rep ||
sl[res] == StringLength@rep && m > frontop[res],
repr[res] = rep;
If[m == 2,
frontop[res] = 2; rearop[res] = 1,
frontop[res] = m;
rearop[res] = m
]
]
]
];
If[frontop[i] >= m,
For[j = 1, j <= i, ++j,
If[rearop[j] < m || (res = op[m][j, i]) > n, Break[]];
rep = re[m][j, i];
If[sl[res] > StringLength@rep ||
sl[res] == StringLength@rep && m > frontop[res],
repr[res] = rep;
If[m == 2,
frontop[res] = 2; rearop[res] = 1,
frontop[res] = m;
rearop[res] = m
]
]
]
]
];
];
```
I used an exhaustive search up to exponentiation. There is no tetration or higher-order operations. I just tried the higher-order operations manually, and there's only a handful combinations which actually yield numbers below 231, so I just hardcoded those that work.
**Edit:** My previous solution didn't not bother about precedence, it just threw things together. ~~Now I *think* my new code fixes that,~~ but non of the first 256 numbers have changed, nor has 8191 (which was valid before, I checked)... and it's to late for me to tell right now if my code *actually* fixed it. I'll have another look tomorrow and also add an explanation, because now with the precedence checking it's a bit convoluted (hopefully it should reduce search time though).
**Edit:** Okay, there were some bugs as expected. I think I fixed it now, increasing the total length for 1 - 256 to **7963**. I'm not sure this is optimal any longer, because it might be possible to find shorter solutions from suboptimal parts if they allow higher-order operations. An explanation will follow when I manage to clean up the code a bit.
[Answer]
# Python 11455b
This solution takes a greedy approach to finding ways to break down prime numbers, rather than an exhaustive approach. I need 9875b for 1-256 compared to 8181 for Martin's probably-optimal solution in that space.
A larger table of multiplication and exponentiation results yields slight improvements in the larger test cases. The solution below took about 7 minutes. Increasing runtime beyond 30 minutes has minimal impact on the output.
I, like Martin, had a problem with precedence. My solution in restricting operation selection may not be optimal.
```
#!/usr/bin/env python
# http://codegolf.stackexchange.com/questions/35480/find-the-shortest-bracket-numbers
import sys, math
reps = {}
forwards = {}
backwards = {}
MAX = 2**31
TABLE_SIZE = 2**12
def op_dec(op):
if op>1:
return op-1
return op
def rep_op(a,op,b):
return rep_num(a) + (" "*op) + rep_num(b)
def min_rep_op(a,op,b,op_max):
return min_rep(a,op_max) + (" "*op) + min_rep(b,op_dec(op_max))
def rep_num(a):
return ("["*(a+1)) + ("]"*(a+1))
def min_rep(n,op_max):
if n < 9:
return ("["*(n+1))+("]"*(n+1))
for op in range(op_max,-1,-1):
if (n, op) in reps:
return reps[(n, op)]
for op in range(op_max,-1,-1):
if (n, op) in backwards:
a,op,b = backwards[(n, op)]
return min_rep_op(a,op,b,op_max)
else:
for m in rep_list:
c = m[0]
if c < n:
r = n - c
for op in range(op_max,-1,-1):
if (c, op) in backwards:
a,op,b = backwards[(c, op)]
if r<10:
return ("["*r) + min_rep_op(a,op,b,op_max) + ("]"*r)
else:
return "[" + min_rep(r-1,op_max) + min_rep_op(a,op,b,op_max) + "]"
break
def expand(a,op,b):
if op == 0:
n = a+b
elif op == 1:
n = a*b
elif op == 2:
if b*math.log10(a) > math.log10(MAX):
n = MAX
else:
n = a**b
elif (a,op,b) in forwards:
n = forwards[(a,op,b)]
else: # tetration and higher
t = a
for i in xrange(b-1):
t = expand(a,op-1,t)
if t>=MAX:
break
n = t
if n > MAX-1:
n = MAX
forwards[(a,op,b)] = n
if (n, op) in backwards:
c = len(rep_op(*backwards[(n, op)]))
if c > (a*2+op+b*2):
backwards[(n, op)] = (a,op,b)
else:
backwards[(n, op)] = (a,op,b)
return n
t = 0
# populate the multiplication, exponentiation, and tetration tables
for op in range(1,4):
for a in range((1,2,2,2)[op],TABLE_SIZE):
for b in range((1,2,2,2)[op],TABLE_SIZE):
t = expand(a,op,b)
if t == MAX:
break
rep_list = sorted(backwards.keys(),key=lambda x: x[0]*4-x[1],reverse=True)
for i in list(range(1, 257))+[8191,13071,524287,2147483647,1449565302,1746268229,126528612,778085967,1553783038,997599288]:
t = min_rep(i,3)
reps[i] = t
print i, t
```
Output:
```
1 [[]]
2 [[[]]]
3 [[[[]]]]
4 [[[[[]]]]]
5 [[[[[[]]]]]]
6 [[[[[[[]]]]]]]
7 [[[[[[[[]]]]]]]]
8 [[[[[[[[[]]]]]]]]]
9 [[[[]]]] [[[]]]
10 [[[[[[]]]]]] [[[]]]
11 [[[[[[[]]]]]] [[[]]]]
12 [[[[[[[]]]]]]] [[[]]]
13 [[[[[[[[]]]]]]] [[[]]]]
14 [[[[[[[[]]]]]]]] [[[]]]
15 [[[[[[]]]]]] [[[[]]]]
16 [[[]]] [[[[]]]]
17 [[[[]]] [[[[]]]]]
18 [[[[[[[]]]]]]] [[[[]]]]
19 [[[[[[[[]]]]]]] [[[[]]]]]
20 [[[[[[]]]]]] [[[[[]]]]]
21 [[[[[[[[]]]]]]]] [[[[]]]]
22 [[[[[[[]]]]]] [[[]]]] [[[]]]
23 [[[[[[[[]]]]]] [[[]]]] [[[]]]]
24 [[[[[[[[[]]]]]]]]] [[[[]]]]
25 [[[[[[]]]]]] [[[]]]
26 [[[[[[[[]]]]]]] [[[]]]] [[[]]]
27 [[[[]]]] [[[]]]
28 [[[[[[[[]]]]]]]] [[[[[]]]]]
29 [[[[[[[[[]]]]]]]] [[[[[]]]]]]
30 [[[[[[[]]]]]]] [[[[[[]]]]]]
31 [[[[[[[[]]]]]]] [[[[[[]]]]]]]
32 [[[]]] [[[[[[]]]]]]
33 [[[[[[[]]]]]] [[[]]]] [[[[]]]]
34 [[[[]]] [[[[]]]]] [[[]]]
35 [[[[[[[[]]]]]]]] [[[[[[]]]]]]
36 [[[[[[[]]]]]]] [[[]]]
37 [[[[[[[[]]]]]]] [[[]]]]
38 [[[[[[[[]]]]]]] [[[[]]]]] [[[]]]
39 [[[[[[[[]]]]]]] [[[]]]] [[[[]]]]
40 [[[[[[]]]]]] [[[]]] [[[[[]]]]]
41 [[[[[[[]]]]]] [[[]]] [[[[[]]]]]]
42 [[[[[[[[]]]]]]]] [[[[[[[]]]]]]]
43 [[[[[[[[[]]]]]]]] [[[[[[[]]]]]]]]
44 [[[[[[[]]]]]] [[[]]]] [[[[[]]]]]
45 [[[[]]]] [[[]]] [[[[[[]]]]]]
46 [[[[[[[[]]]]]] [[[]]]] [[[]]]] [[[]]]
47 [[[[[[[[[]]]]]] [[[]]]] [[[]]]] [[[]]]]
48 [[[[[[[[[]]]]]]]]] [[[[[[[]]]]]]]
49 [[[[[[[[]]]]]]]] [[[]]]
50 [[[[[[]]]]]] [[[]]] [[[[[[]]]]]]
51 [[[[]]] [[[[]]]]] [[[[]]]]
52 [[[[[[[[]]]]]]] [[[]]]] [[[[[]]]]]
53 [[[[[[[[[]]]]]]] [[[]]]] [[[[[]]]]]]
54 [[[[]]]] [[[]]] [[[[[[[]]]]]]]
55 [[[[[[[]]]]]] [[[]]]] [[[[[[]]]]]]
56 [[[[[[[[[]]]]]]]]] [[[[[[[[]]]]]]]]
57 [[[[[[[[]]]]]]] [[[[]]]]] [[[[]]]]
58 [[[[[[[[[]]]]]]]] [[[[[]]]]]] [[[]]]
59 [[[[[[[[[[]]]]]]]] [[[[[]]]]]] [[[]]]]
60 [[[[[[[]]]]]]] [[[]]] [[[[[[]]]]]]
61 [[[[[[[[]]]]]]] [[[]]] [[[[[[]]]]]]]
62 [[[[[[[[]]]]]]] [[[[[[]]]]]]] [[[]]]
63 [[[[]]]] [[[]]] [[[[[[[[]]]]]]]]
64 [[[[[]]]]] [[[[]]]]
65 [[[[[[[[]]]]]]] [[[]]]] [[[[[[]]]]]]
66 [[[[[[[]]]]]] [[[]]]] [[[[[[[]]]]]]]
67 [[[[[[[[]]]]]] [[[]]]] [[[[[[[]]]]]]]]
68 [[[[]]] [[[[]]]]] [[[[[]]]]]
69 [[[[[[[[]]]]]] [[[]]]] [[[]]]] [[[[]]]]
70 [[[[[[]]]]]] [[[]]] [[[[[[[[]]]]]]]]
71 [[[[[[[]]]]]] [[[]]] [[[[[[[[]]]]]]]]]
72 [[[[[[[]]]]]]] [[[]]] [[[[[[[]]]]]]]
73 [[[[[[[[]]]]]]] [[[]]] [[[[[[[]]]]]]]]
74 [[[[[[[[]]]]]]] [[[]]]] [[[]]]
75 [[[[[[]]]]]] [[[[]]]] [[[[[[]]]]]]
76 [[[[[[[[]]]]]]] [[[[]]]]] [[[[[]]]]]
77 [[[[[[[]]]]]] [[[]]]] [[[[[[[[]]]]]]]]
78 [[[[[[[[]]]]]]] [[[]]]] [[[[[[[]]]]]]]
79 [[[[[[[[[]]]]]]] [[[]]]] [[[[[[[]]]]]]]]
80 [[[[[[]]]]]] [[[]]] [[[[[[[[[]]]]]]]]]
81 [[[[]]]] [[[[[]]]]]
82 [[[[[[[]]]]]] [[[]]] [[[[[]]]]]] [[[]]]
83 [[[[[[[[]]]]]] [[[]]] [[[[[]]]]]] [[[]]]]
84 [[[[[[[[]]]]]]]] [[[]]] [[[[[[[]]]]]]]
85 [[[[]]] [[[[]]]]] [[[[[[]]]]]]
86 [[[[[[[[[]]]]]]]] [[[[[[[]]]]]]]] [[[]]]
87 [[[[[[[[[]]]]]]]] [[[[[]]]]]] [[[[]]]]
88 [[[[[[[]]]]]] [[[]]]] [[[[[[[[[]]]]]]]]]
89 [[[[[[[[]]]]]] [[[]]]] [[[[[[[[[]]]]]]]]]]
90 [[[[[[]]]]]] [[[]]] [[[[]]]] [[[]]]
91 [[[[[[[[]]]]]]] [[[]]]] [[[[[[[[]]]]]]]]
92 [[[[[[[[]]]]]] [[[]]]] [[[]]]] [[[[[]]]]]
93 [[[[[[[[]]]]]]] [[[[[[]]]]]]] [[[[]]]]
94 [[[[[[[[[]]]]]] [[[]]]] [[[]]]] [[[]]]] [[[]]]
95 [[[[[[[[]]]]]]] [[[[]]]]] [[[[[[]]]]]]
96 [[[[[[[]]]]]]] [[[]]] [[[[[[[[[]]]]]]]]]
97 [[[[[[[[]]]]]]] [[[]]] [[[[[[[[[]]]]]]]]]]
98 [[[[[[[[]]]]]]]] [[[]]] [[[[[[[[]]]]]]]]
99 [[[[[[[]]]]]] [[[]]]] [[[[]]]] [[[]]]
100 [[[[[[]]]]]] [[[]]] [[[]]]
101 [[[[[[[]]]]]] [[[]]] [[[]]]]
102 [[[[]]] [[[[]]]]] [[[[[[[]]]]]]]
103 [[[[[]]] [[[[]]]]] [[[[[[[]]]]]]]]
104 [[[[[[[[]]]]]]] [[[]]]] [[[[[[[[[]]]]]]]]]
105 [[[[[[]]]]]] [[[[]]]] [[[[[[[[]]]]]]]]
106 [[[[[[[[[]]]]]]] [[[]]]] [[[[[]]]]]] [[[]]]
107 [[[[[[[[[[]]]]]]] [[[]]]] [[[[[]]]]]] [[[]]]]
108 [[[[[[[]]]]]]] [[[]]] [[[[]]]] [[[]]]
109 [[[[[[[[]]]]]]] [[[]]] [[[[]]]] [[[]]]]
110 [[[[[[[]]]]]] [[[]]]] [[[[[[]]]]]] [[[]]]
111 [[[[[[[[]]]]]]] [[[]]]] [[[[]]]]
112 [[[]]] [[[[]]]] [[[[[[[[]]]]]]]]
113 [[[[]]] [[[[]]]] [[[[[[[[]]]]]]]]]
114 [[[[[[[[]]]]]]] [[[[]]]]] [[[[[[[]]]]]]]
115 [[[[[[[[]]]]]] [[[]]]] [[[]]]] [[[[[[]]]]]]
116 [[[[[[[[[]]]]]]]] [[[[[]]]]]] [[[[[]]]]]
117 [[[[[[[[]]]]]]] [[[]]]] [[[[]]]] [[[]]]
118 [[[[[[[[[[]]]]]]]] [[[[[]]]]]] [[[]]]] [[[]]]
119 [[[[]]] [[[[]]]]] [[[[[[[[]]]]]]]]
120 [[[[[[]]]]]] [[[[]]]] [[[[[[[[[]]]]]]]]]
121 [[[[[[[]]]]]] [[[]]]] [[[]]]
122 [[[[[[[[]]]]]]] [[[]]] [[[[[[]]]]]]] [[[]]]
123 [[[[[[[]]]]]] [[[]]] [[[[[]]]]]] [[[[]]]]
124 [[[[[[[[]]]]]]] [[[[[[]]]]]]] [[[[[]]]]]
125 [[[[[[]]]]]] [[[[]]]]
126 [[[[[[[[]]]]]]]] [[[]]] [[[[]]]] [[[]]]
127 [[[[[[[[[]]]]]]]] [[[]]] [[[[]]]] [[[]]]]
128 [[[]]] [[[[[[[[]]]]]]]]
129 [[[[[[[[[]]]]]]]] [[[[[[[]]]]]]]] [[[[]]]]
130 [[[[[[[[]]]]]]] [[[]]]] [[[[[[]]]]]] [[[]]]
131 [[[[[[[[[]]]]]]] [[[]]]] [[[[[[]]]]]] [[[]]]]
132 [[[[[[[]]]]]]] [[[]]] [[[[[[[]]]]]] [[[]]]]
133 [[[[[[[[]]]]]]] [[[[]]]]] [[[[[[[[]]]]]]]]
134 [[[[[[[[]]]]]] [[[]]]] [[[[[[[]]]]]]]] [[[]]]
135 [[[[[[]]]]]] [[[[]]]] [[[[]]]] [[[]]]
136 [[[[]]] [[[[]]]]] [[[[[[[[[]]]]]]]]]
137 [[[[[]]] [[[[]]]]] [[[[[[[[[]]]]]]]]]]
138 [[[[[[[[]]]]]] [[[]]]] [[[]]]] [[[[[[[]]]]]]]
139 [[[[[[[[[]]]]]] [[[]]]] [[[]]]] [[[[[[[]]]]]]]]
140 [[[[[[[[]]]]]]]] [[[]]] [[[[[[]]]]]] [[[]]]
141 [[[[[[[[[]]]]]] [[[]]]] [[[]]]] [[[]]]] [[[[]]]]
142 [[[[[[[]]]]]] [[[]]] [[[[[[[[]]]]]]]]] [[[]]]
143 [[[[[[[[]]]]]]] [[[]]]] [[[[[[[]]]]]] [[[]]]]
144 [[[[[[[]]]]]]] [[[]]] [[[]]]
145 [[[[[[[[[]]]]]]]] [[[[[]]]]]] [[[[[[]]]]]]
146 [[[[[[[[]]]]]]] [[[]]] [[[[[[[]]]]]]]] [[[]]]
147 [[[[[[[[]]]]]]]] [[[[]]]] [[[[[[[[]]]]]]]]
148 [[[[[[[[]]]]]]] [[[]]]] [[[[[]]]]]
149 [[[[[[[[[]]]]]]] [[[]]]] [[[[[]]]]]]
150 [[[[[[]]]]]] [[[[]]]] [[[[[[]]]]]] [[[]]]
151 [[[[[[[]]]]]] [[[[]]]] [[[[[[]]]]]] [[[]]]]
152 [[[[[[[[]]]]]]] [[[[]]]]] [[[[[[[[[]]]]]]]]]
153 [[[[]]] [[[[]]]]] [[[[]]]] [[[]]]
154 [[[[[[[[]]]]]]]] [[[]]] [[[[[[[]]]]]] [[[]]]]
155 [[[[[[[[]]]]]]] [[[[[[]]]]]]] [[[[[[]]]]]]
156 [[[[[[[[]]]]]]] [[[]]]] [[[[[[[]]]]]]] [[[]]]
157 [[[[[[[[[]]]]]]] [[[]]]] [[[[[[[]]]]]]] [[[]]]]
158 [[[[[[[[[]]]]]]] [[[]]]] [[[[[[[]]]]]]]] [[[]]]
159 [[[[[[[[[]]]]]]] [[[]]]] [[[[[]]]]]] [[[[]]]]
160 [[[]]] [[[[]]]] [[[[[[]]]]]] [[[]]]
161 [[[[[[[[]]]]]] [[[]]]] [[[]]]] [[[[[[[[]]]]]]]]
162 [[[[[[[]]]]]]] [[[[]]]] [[[[]]]] [[[]]]
163 [[[[[[[[]]]]]]] [[[[]]]] [[[[]]]] [[[]]]]
164 [[[[[[[]]]]]] [[[]]] [[[[[]]]]]] [[[[[]]]]]
165 [[[[[[]]]]]] [[[[]]]] [[[[[[[]]]]]] [[[]]]]
166 [[[[[[[[]]]]]] [[[]]] [[[[[]]]]]] [[[]]]] [[[]]]
167 [[[[[[[[[]]]]]] [[[]]] [[[[[]]]]]] [[[]]]] [[[]]]]
168 [[[[[[[[]]]]]]]] [[[]]] [[[[[[[]]]]]]] [[[]]]
169 [[[[[[[[]]]]]]] [[[]]]] [[[]]]
170 [[[[]]] [[[[]]]]] [[[[[[]]]]]] [[[]]]
171 [[[[[[[[]]]]]]] [[[[]]]]] [[[[]]]] [[[]]]
172 [[[[[[[[[]]]]]]]] [[[[[[[]]]]]]]] [[[[[]]]]]
173 [[[[[[[[[[]]]]]]]] [[[[[[[]]]]]]]] [[[[[]]]]]]
174 [[[[[[[[[]]]]]]]] [[[[[]]]]]] [[[[[[[]]]]]]]
175 [[[[[[]]]]]] [[[]]] [[[[[[[[]]]]]]]]
176 [[[]]] [[[[]]]] [[[[[[[]]]]]] [[[]]]]
177 [[[[[[[[[[]]]]]]]] [[[[[]]]]]] [[[]]]] [[[[]]]]
178 [[[[[[[[]]]]]] [[[]]]] [[[[[[[[[]]]]]]]]]] [[[]]]
179 [[[[[[[[[]]]]]] [[[]]]] [[[[[[[[[]]]]]]]]]] [[[]]]]
180 [[[[[[]]]]]] [[[[[]]]]] [[[[]]]] [[[]]]
181 [[[[[[[]]]]]] [[[[[]]]]] [[[[]]]] [[[]]]]
182 [[[[[[[[]]]]]]]] [[[]]] [[[[[[[[]]]]]]] [[[]]]]
183 [[[[[[[[]]]]]]] [[[]]] [[[[[[]]]]]]] [[[[]]]]
184 [[[[[[[[]]]]]] [[[]]]] [[[]]]] [[[[[[[[[]]]]]]]]]
185 [[[[[[[[]]]]]]] [[[]]]] [[[[[[]]]]]]
186 [[[[[[[[]]]]]]] [[[[[[]]]]]]] [[[[[[[]]]]]]]
187 [[[[]]] [[[[]]]]] [[[[[[[]]]]]] [[[]]]]
188 [[[[[[[[[]]]]]] [[[]]]] [[[]]]] [[[]]]] [[[[[]]]]]
189 [[[[[[[[]]]]]]]] [[[[]]]] [[[[]]]] [[[]]]
190 [[[[[[[[]]]]]]] [[[[]]]]] [[[[[[]]]]]] [[[]]]
191 [[[[[[[[[]]]]]]] [[[[]]]]] [[[[[[]]]]]] [[[]]]]
192 [[[]]] [[[[]]]] [[[[[[[]]]]]]] [[[]]]
193 [[[[]]] [[[[]]]] [[[[[[[]]]]]]] [[[]]]]
194 [[[[[[[[]]]]]]] [[[]]] [[[[[[[[[]]]]]]]]]] [[[]]]
195 [[[[[[]]]]]] [[[[]]]] [[[[[[[[]]]]]]] [[[]]]]
196 [[[[[[[[]]]]]]]] [[[]]] [[[]]]
197 [[[[[[[[[]]]]]]]] [[[]]] [[[]]]]
198 [[[[[[[]]]]]]] [[[[]]]] [[[[[[[]]]]]] [[[]]]]
199 [[[[[[[[]]]]]]] [[[[]]]] [[[[[[[]]]]]] [[[]]]]]
200 [[[[[[]]]]]] [[[[[]]]]] [[[[[[]]]]]] [[[]]]
201 [[[[[[[[]]]]]] [[[]]]] [[[[[[[]]]]]]]] [[[[]]]]
202 [[[[[[[]]]]]] [[[]]] [[[]]]] [[[]]]
203 [[[[[[[[[]]]]]]]] [[[[[]]]]]] [[[[[[[[]]]]]]]]
204 [[[[]]] [[[[]]]]] [[[[[[[]]]]]]] [[[]]]
205 [[[[[[[]]]]]] [[[]]] [[[[[]]]]]] [[[[[[]]]]]]
206 [[[[[]]] [[[[]]]]] [[[[[[[]]]]]]]] [[[]]]
207 [[[[[[[[]]]]]] [[[]]]] [[[]]]] [[[[]]]] [[[]]]
208 [[[]]] [[[[]]]] [[[[[[[[]]]]]]] [[[]]]]
209 [[[[[[[[]]]]]]] [[[[]]]]] [[[[[[[]]]]]] [[[]]]]
210 [[[[[[]]]]]] [[[[]]]] [[[[[[[[]]]]]]]] [[[]]]
211 [[[[[[[]]]]]] [[[[]]]] [[[[[[[[]]]]]]]] [[[]]]]
212 [[[[[[[[[]]]]]]] [[[]]]] [[[[[]]]]]] [[[[[]]]]]
213 [[[[[[[]]]]]] [[[]]] [[[[[[[[]]]]]]]]] [[[[]]]]
214 [[[[[[[[[[]]]]]]] [[[]]]] [[[[[]]]]]] [[[]]]] [[[]]]
215 [[[[[[[[[]]]]]]]] [[[[[[[]]]]]]]] [[[[[[]]]]]]
216 [[[[[[[]]]]]]] [[[[]]]]
217 [[[[[[[[]]]]]]] [[[[[[]]]]]]] [[[[[[[[]]]]]]]]
218 [[[[[[[[]]]]]]] [[[]]] [[[[]]]] [[[]]]] [[[]]]
219 [[[[[[[[]]]]]]] [[[]]] [[[[[[[]]]]]]]] [[[[]]]]
220 [[[[[[[]]]]]] [[[]]]] [[[]]] [[[[[[]]]]]] [[[]]]
221 [[[[]]] [[[[]]]]] [[[[[[[[]]]]]]] [[[]]]]
222 [[[[[[[[]]]]]]] [[[]]]] [[[[[[[]]]]]]]
223 [[[[[[[[[]]]]]]] [[[]]]] [[[[[[[]]]]]]]]
224 [[[]]] [[[[]]]] [[[[[[[[]]]]]]]] [[[]]]
225 [[[[[[]]]]]] [[[[]]]] [[[]]]
226 [[[[]]] [[[[]]]] [[[[[[[[]]]]]]]]] [[[]]]
227 [[[[[]]] [[[[]]]] [[[[[[[[]]]]]]]]] [[[]]]]
228 [[[[[[[[]]]]]]] [[[[]]]]] [[[[[[[]]]]]]] [[[]]]
229 [[[[[[[[[]]]]]]] [[[[]]]]] [[[[[[[]]]]]]] [[[]]]]
230 [[[[[[[[]]]]]] [[[]]]] [[[]]]] [[[[[[]]]]]] [[[]]]
231 [[[[[[[[]]]]]]]] [[[[]]]] [[[[[[[]]]]]] [[[]]]]
232 [[[[[[[[[]]]]]]]] [[[[[]]]]]] [[[[[[[[[]]]]]]]]]
233 [[[[[[[[[[]]]]]]]] [[[[[]]]]]] [[[[[[[[[]]]]]]]]]]
234 [[[[[[[]]]]]]] [[[[]]]] [[[[[[[[]]]]]]] [[[]]]]
235 [[[[[[[[[]]]]]] [[[]]]] [[[]]]] [[[]]]] [[[[[[]]]]]]
236 [[[[[[[[[[]]]]]]]] [[[[[]]]]]] [[[]]]] [[[[[]]]]]
237 [[[[[[[[[]]]]]]] [[[]]]] [[[[[[[]]]]]]]] [[[[]]]]
238 [[[[]]] [[[[]]]]] [[[[[[[[]]]]]]]] [[[]]]
239 [[[[[]]] [[[[]]]]] [[[[[[[[]]]]]]]] [[[]]]]
240 [[[[[[]]]]]] [[[[[]]]]] [[[[[[[]]]]]]] [[[]]]
241 [[[[[[[]]]]]] [[[[[]]]]] [[[[[[[]]]]]]] [[[]]]]
242 [[[[[[[]]]]]] [[[]]]] [[[]]] [[[[[[[]]]]]] [[[]]]]
243 [[[[]]]] [[[[[[]]]]]]
244 [[[[[[[[]]]]]]] [[[]]] [[[[[[]]]]]]] [[[[[]]]]]
245 [[[[[[[[]]]]]]]] [[[[[[]]]]]] [[[[[[[[]]]]]]]]
246 [[[[[[[]]]]]] [[[]]] [[[[[]]]]]] [[[[[[[]]]]]]]
247 [[[[[[[[]]]]]]] [[[[]]]]] [[[[[[[[]]]]]]] [[[]]]]
248 [[[[[[[[]]]]]]] [[[[[[]]]]]]] [[[[[[[[[]]]]]]]]]
249 [[[[[[[[]]]]]] [[[]]] [[[[[]]]]]] [[[]]]] [[[[]]]]
250 [[[[[[]]]]]] [[[]]] [[[[[[]]]]]] [[[]]]
251 [[[[[[[]]]]]] [[[]]] [[[[[[]]]]]] [[[]]]]
252 [[[[[[[[]]]]]]]] [[[[]]]] [[[[[[[]]]]]]] [[[]]]
253 [[[[[[[[]]]]]] [[[]]]] [[[]]]] [[[[[[[]]]]]] [[[]]]]
254 [[[[[[[[[]]]]]]]] [[[]]] [[[[]]]] [[[]]]] [[[]]]
255 [[[[]]] [[[[]]]]] [[[[[[]]]]]] [[[[]]]]
256 [[[[[]]]]] [[[]]]
8191 [[[[[[[[[]]]]]]] [[[]]]] [[[[[[[[]]]]]]]] [[[[[[]]]]]] [[[]]] [[[[]]]] [[[[]]]]]
13071 [[[[[[[[[[[]]]]]]] [[[[]]]] [[[[]]]] [[[]]]] [[[[[]]]]]] [[[]]]] [[[[[[]]]]]] [[[]]]]
524287 [[[[[[[[[]]]]]]] [[[[]]]]] [[[]]] [[[[[[[[]]]]]]]] [[[[]]]] [[[[[[[[]]]]]]] [[[]]] [[[[[[[]]]]]]]] [[[[]]]] [[[[]]]]]
2147483647 [[[[[[[[[[[]]]]]]]]] [[[[]]]] [[[[[[[[]]]]]]]] [[[]]]] [[[[]]]] [[[[[[[[[]]]]]]] [[[]]]] [[[[[[]]]]]] [[[]]]] [[[[[[[]]]]]]][[[[[[[[[]]]]]]]] [[[[[[[]]]]]]]] [[[[[[[]]]]]]] [[[[[[]]]]]] [[[[]]]]]
1449565302 [[[[[[[[[[[[[]]]]]]]] [[[]]] [[[[]]]] [[[]]]] [[[[[]]]]]] [[[]]]] [[[]]]] [[[[[[[[[]]]]]] [[[]]]] [[[]]]] [[[[[[[]]]]]]]] [[[[[[]]]]]] [[[]]][[[[[[[[]]]]]]] [[[]]]] [[[[]]]] [[[[[[[[[]]]]]]]] [[[[[]]]]]] [[[[]]]]]
1746268229 [[[[[[[[[[]]]]]] [[[]]]] [[[[[[[]]]]]]]] [[[[]]] [[[[[]]]]]] [[[[[[[[[]]]]]]]] [[[[[[[]]]]]]]] [[[[[[[[]]]]]]] [[[[]]]]]][[[[[[[[[]]]]]]]] [[[[[[[]]]]]]]] [[[[[[[[]]]]]]]] [[[[[]]]]] [[[[]]]]]
126528612 [[[[[[[[[[[]]]]]] [[[]]]] [[[[[[[]]]]]]]] [[[[[]]]]]] [[[[[[[]]]]]]] [[[]]]] [[[[[[[[]]]]]]]][[[[[[[]]]]]] [[[]]] [[[[[[]]]]]] [[[]]]] [[[]]] [[[[]]]]]
778085967 [[[[[[[[[[]]]]]]]] [[[[[[[]]]]]]] [[[[[[[[]]]]]]] [[[]]]] [[[]]]] [[[[[[[[[]]]]]]] [[[]]]] [[[[[]]]]]] [[[[[[]]]]]][[[[[[[[[]]]]]] [[[]]] [[[[[]]]]]] [[[]]]] [[[]]]] [[[[[]]]]]]
1553783038 [[[[[[[[[]]]]]]] [[[]]]] [[[[]]]] [[[[[[]]]]]] [[[]]] [[[[[[[[[]]]]]]] [[[]]] [[[[[[[[[]]]]]]]]]] [[[[[[]]]]]] [[[]]]][[[[]]] [[[[]]]] [[[[[[[]]]]]]] [[[]]]] [[[[[[[]]]]]]] [[[[]]]]]
997599288 [[[[[[[[]]]]]] [[[]]]] [[[[[[[[]]]]]]]] [[[[[[[]]]]]] [[[]]]] [[[]]] [[[[[[]]]]]] [[[[[[[]]]]]] [[[]]]] [[[]]][[[[[[[[]]]]]]] [[[]]]] [[[[]]]] [[[[]]]] [[[[]]]]]
```
[Answer]
# Python 9219b
This is my second entry. I started from scratch and tried a new arrangement of the data, including using the blist package for sorted lists and dicts, and some new approaches for finding large solutions. I think I've got an optimal 1-256. Increasing runtime from 30s to 4m shortened the big test cases by about 30 bytes.
```
# https://pypi.python.org/pypi/blist/
# provides sorteddict
from blist import *
import math, sys
TABLE_SIZE=2**8
MAX_INT = 2**31
repr = sorteddict()
for i in range(12):
repr[i] = sorteddict({(i*2+2,-1,-1):("["*(i+1)+"]"*(i+1), str(i))});
repr [65536] = sorteddict({(18, 4, 4):("[[[]]] [[[[]]]]", "2^^^3")}); # 2^^^3 = 2^^(2^^2) = 2^(2^(2^2))
repr [16] = sorteddict({(17, 3, 3):("[[[]]] [[[[]]]]", "2^^3")}); # 2^^3 = 2^(2^2)
repr [27] = sorteddict({(17, 3, 3):("[[[[]]]] [[[]]]", "3^^2")}); # 3^^2 = 3^3
repr [256] = sorteddict({(19, 3, 3):("[[[[[]]]]] [[[]]]", "4^^2")}); # 4^^2 = 4^4
repr [3125] = sorteddict({(21, 3, 3):("[[[[[[]]]]]] [[[]]]", "5^^2")}); # 5^^2 = 5^5
repr [46656] = sorteddict({(23, 3, 3):("[[[[[[[]]]]]]] [[[]]]", "6^^2")}); # 6^^2 = 6^6
repr [823543] = sorteddict({(25, 3, 3):("[[[[[[[[]]]]]]]] [[[]]]", "7^^2")}); # 7^^2 = 7^7
repr [16777216] = sorteddict({(27, 3, 3):("[[[[[[[[[]]]]]]]]] [[[]]]", "8^^2")}); # 8^^2 = 8^8
repr[387420489] = sorteddict({(29, 3, 3):("[[[[[[[[[[]]]]]]]]]] [[[]]]", "9^^2")}); # 9^^2 = 9^9
def expr_to_repr(a,op,b):
rep_a = None
for d,r in repr[a].iteritems():
op_min, op_max = ((0,9),(1,9),(3,9))[op]
if (d[1]==-1 or d[1]>=op_min) and d[2]<=op_max:
rep_a = (d,r)
break
if not rep_a:
rep_a = ((a*2+2,-1,-1),("["*(a+1)+"]"*(a+1), str(a)));
rep_b = None
for d,r in repr[b].iteritems():
op_min, op_max = ((0,9),(1,9),(3,9))[op]
if (d[1]==-1 or d[1]>=op_min) and d[2]<=op_max:
rep_b = (d,r)
break
if not rep_b:
rep_b = ((b*2+2,-1,-1),("["*(b+1)+"]"*(b+1), str(b)));
r = rep_a[1][0] + " "*op + rep_b[1][0]
return (
(
len(r),
min(op, rep_a[0][1] if rep_a[0][1]!=-1 else op, rep_b[0][1] if rep_b[0][1]!=-1 else op),
max(op, rep_a[0][2], rep_b[0][2])
),
(
r,
expr_to_string(rep_a[1][1],op,rep_b[1][1])
)
);
def opsym(op):
return ("+","*","^","^^")[op]
def expr_to_string(a,op,b):
return str(a) + opsym(op) + str(b)
def calc(a,op,b):
if op == 0:
return min(a+b,MAX_INT)
elif op == 1:
return min(a*b,MAX_INT)
elif op == 2:
if (b*math.log10(a)>math.log10(MAX_INT)):
return MAX_INT
return min(a**b,MAX_INT)
else:
t = a
for h in range(b):
t = calc(a,op-1,t)
if t>=MAX_INT:
t = MAX_INT
break
return t
def populate_repr(a,op,b):
o = (a,op,b)
n = calc(*o)
if n == MAX_INT:
return n
if n not in repr:
repr[n] = sorteddict()
r = expr_to_repr(*o)
if conditional_replace_repr(n,r):
for i in range(1,11):
conditional_replace_repr(n+i,
(
(
r[0][0]+i*2,
-1,
-1
),
(
"["*i + r[1][0] + "]"*i,
"(" + r[1][1] + "+" + str(i) + ")"
)
)
)
return n
def conditional_replace_repr(n,new_rep):
if n not in repr:
repr[n] = sorteddict()
repr[n][new_rep[0]] = new_rep[1]
return True
found = None
repl = False
for d, r in repr[n].iteritems():
if d[1] == new_rep[0][1] and d[2] == new_rep[0][2]:
found = d
if d[0] > new_rep[0][0]:
repl = True
break
if (not found) or (found and repl):
repr[n][new_rep[0]] = new_rep[1]
if found:
del repr[n][found]
return True
return False
def vaguely_decent_repr(n):
if n <= TABLE_SIZE:
return repr[n].iteritems().next()[1][0]
if n in repr:
return repr[n].iteritems().next()[1][0]
else:
keys = sorted(repr.keys(),reverse=True)
best_rep = None
tested = 0
for i in keys:
if i>n:
continue
if tested > 10:
break
tested += 1
cand_rep = vaguely_decent_repr(n-i) + repr[i].iteritems().next()[1][0]
if (not best_rep) or len(cand_rep) < len(best_rep):
best_rep = cand_rep
return best_rep
keys = repr.keys()
for k in keys:
for d,r in repr[k].iteritems():
for i in range(1,11):
conditional_replace_repr(k+i,
(
(
d[0]+i*2,
-1,
-1
),
(
"["*i + r[0] + "]"*i,
"(" + r[1] + "+" + str(i) + ")"
)
)
)
# initialize the repr array with results of 1..256, 2+2 up to TABLE_SIZE^TABLE_SIZE
for row in range(2,TABLE_SIZE+1):
for col in range(2,row):
for op in range(1,3):
populate_repr(row,op,col)
if op > 1:
populate_repr(col,op,row)
for op in range(1,3):
populate_repr(row,op,row)
if row > 10:
for frac in range(1,10):
rep_a = repr[row-frac].iteritems().next()
conditional_replace_repr(row,
(
(
rep_a[0][0] + frac*2,
-1,
-1
),
(
"["*frac + rep_a[1][0] + "]"*frac,
"(" + rep_a[1][1] + "+" + str(frac) + ")"
)
)
)
for frac in range(10,row/2):
rep_a = repr[frac].iteritems().next()
rep_b = repr[row-frac].iteritems().next()
conditional_replace_repr(row,
(
(
rep_a[0][0]+rep_b[0][0],
min(rep_a[0][1],rep_b[0][1]),
max(rep_a[0][2],rep_b[0][2])
),
(
rep_a[1][0] + rep_b[1][0],
rep_a[1][1] + "+" + rep_b[1][1]
)
)
)
# for n,reps in repr.iteritems():
# for d,r in reps.iteritems():
for n in range(1,257):
print str(n)+"="+repr[n].iteritems().next()[1][0]
for n in (8191,13071,524287,2147483647,1449565302,1746268229,126528612,778085967,1553783038,997599288):
print str(n)+"="+vaguely_decent_repr(n)
```
Output:
```
1=[[]]
2=[[[]]]
3=[[[[]]]]
4=[[[[[]]]]]
5=[[[[[[]]]]]]
6=[[[[[[[]]]]]]]
7=[[[[[[[[]]]]]]]]
8=[[[]]] [[[[]]]]
9=[[[[]]]] [[[]]]
10=[[[[[]]]] [[[]]]]
11=[[[[[[]]]] [[[]]]]]
12=[[[[[]]]]] [[[[]]]]
13=[[[[[[]]]]] [[[[]]]]]
14=[[[[[[[]]]]] [[[[]]]]]]
15=[[[[[[]]]]]] [[[[]]]]
16=[[[]]] [[[[]]]]
17=[[[[]]] [[[[]]]]]
18=[[[[[]]] [[[[]]]]]]
19=[[[[[[]]] [[[[]]]]]]]
20=[[[[[[]]]]]] [[[[[]]]]]
21=[[[[[[[]]]]]] [[[[[]]]]]]
22=[[[[[[[[]]]]]] [[[[[]]]]]]]
23=[[[[[[[[[]]]]]] [[[[[]]]]]]]]
24=[[[[[[[]]]]]]] [[[[[]]]]]
25=[[[[[[]]]]]] [[[]]]
26=[[[[[[[]]]]]] [[[]]]]
27=[[[[]]]] [[[]]]
28=[[[[[]]]] [[[]]]]
29=[[[[[[]]]] [[[]]]]]
30=[[[[[[[]]]] [[[]]]]]]
31=[[[[[[[[]]]] [[[]]]]]]]
32=[[[]]] [[[[[[]]]]]]
33=[[[[]]] [[[[[[]]]]]]]
34=[[[[[]]] [[[[[[]]]]]]]]
35=[[[[[[]]] [[[[[[]]]]]]]]]
36=[[[[[[[]]]]]]] [[[]]]
37=[[[[[[[[]]]]]]] [[[]]]]
38=[[[[[[[[[]]]]]]] [[[]]]]]
39=[[[[[[[[[[]]]]]]] [[[]]]]]]
40=[[[[[]]]] [[[]]]] [[[[[]]]]]
41=[[[[]]] [[[[]]]] [[[[[[]]]]]]]
42=[[[[[[[[]]]]]]]] [[[[[[[]]]]]]]
43=[[[[[[[[[]]]]]]]] [[[[[[[]]]]]]]]
44=[[[[[[]]]] [[[]]]]] [[[[[]]]]]
45=[[[[]]]] [[[]]] [[[[[[]]]]]]
46=[[[[[]]]] [[[]]] [[[[[[]]]]]]]
47=[[[[[[]]]] [[[]]] [[[[[[]]]]]]]]
48=[[[]]] [[[[]]]] [[[[]]]]
49=[[[[[[[[]]]]]]]] [[[]]]
50=[[[[[[[[[]]]]]]]] [[[]]]]
51=[[[[[[[[[[]]]]]]]] [[[]]]]]
52=[[[[[[[]]]]]] [[[]]]] [[[]]]
53=[[[[[[[[]]]]]] [[[]]]] [[[]]]]
54=[[[[]]]] [[[]]] [[[]]]
55=[[[[[]]]] [[[]]] [[[]]]]
56=[[[[[]]]] [[[]]]] [[[]]]
57=[[[[[[]]]] [[[]]]] [[[]]]]
58=[[[[[[]]]] [[[]]]]] [[[]]]
59=[[[[[[[]]]] [[[]]]]] [[[]]]]
60=[[[[[[[]]]] [[[]]]]]] [[[]]]
61=[[[[[[[[]]]] [[[]]]]]] [[[]]]]
62=[[[[[[[[]]]] [[[]]]]]]] [[[]]]
63=[[[[]]]] [[[]]] [[[[[[[[]]]]]]]]
64=[[[[[]]]]] [[[[]]]]
65=[[[[[[]]]]] [[[[]]]]]
66=[[[[[[[]]]]] [[[[]]]]]]
67=[[[[[[[[]]]]] [[[[]]]]]]]
68=[[[[[[[[[]]]]] [[[[]]]]]]]]
69=[[[[[[[[[[]]]]] [[[[]]]]]]]]]
70=[[[[[[[[[[[]]]]] [[[[]]]]]]]]]]
71=[[[[[[[[[[[[]]]]] [[[[]]]]]]]]]]]
72=[[[[[[[]]]]]]] [[[]]] [[[]]]
73=[[[[[[[[]]]]]]] [[[]]] [[[]]]]
74=[[[[[[[[]]]]]]] [[[]]]] [[[]]]
75=[[[[[[]]]]]] [[[]]] [[[[]]]]
76=[[[[[[[]]]]]] [[[]]] [[[[]]]]]
77=[[[[[[[[]]]]]] [[[]]] [[[[]]]]]]
78=[[[[[[[]]]]]] [[[]]]] [[[[]]]]
79=[[[[[[[[]]]]]] [[[]]]] [[[[]]]]]
80=[[[]]] [[[[]]]] [[[[[[]]]]]]
81=[[[[]]]] [[[[[]]]]]
82=[[[[[]]]] [[[[[]]]]]]
83=[[[[[[]]]] [[[[[]]]]]]]
84=[[[[[[[]]]] [[[[[]]]]]]]]
85=[[[[[[[[]]]] [[[[[]]]]]]]]]
86=[[[[[[[[[]]]] [[[[[]]]]]]]]]]
87=[[[[[[]]]] [[[]]]]] [[[[]]]]
88=[[[[[[[]]]] [[[]]]]] [[[[]]]]]
89=[[[[[[[[]]]] [[[]]]]] [[[[]]]]]]
90=[[[[[[[]]]] [[[]]]]]] [[[[]]]]
91=[[[[[[[[]]]] [[[]]]]]] [[[[]]]]]
92=[[[[[[[[[]]]] [[[]]]]]] [[[[]]]]]]
93=[[[[[[[[]]]] [[[]]]]]]] [[[[]]]]
94=[[[[[[[[[]]]] [[[]]]]]]] [[[[]]]]]
95=[[[[[[]]] [[[[]]]]]]] [[[[[[]]]]]]
96=[[[]]] [[[[[[]]]]]] [[[[]]]]
97=[[[[]]] [[[[[[]]]]]] [[[[]]]]]
98=[[[[[[[[]]]]]]]] [[[]]] [[[]]]
99=[[[[]]] [[[[[[]]]]]]] [[[[]]]]
100=[[[[[]]]] [[[]]]] [[[]]]
101=[[[[[[]]]] [[[]]]] [[[]]]]
102=[[[[[[[]]]] [[[]]]] [[[]]]]]
103=[[[[[[[[]]]] [[[]]]] [[[]]]]]]
104=[[[[[[[]]]]]] [[[]]]] [[[[[]]]]]
105=[[[[[[[[]]]]]] [[[]]]] [[[[[]]]]]]
106=[[[[[[[[[]]]]]] [[[]]]] [[[[[]]]]]]]
107=[[[[[[[[[[]]]]]] [[[]]]] [[[[[]]]]]]]]
108=[[[[]]]] [[[]]] [[[[[]]]]]
109=[[[[[]]]] [[[]]] [[[[[]]]]]]
110=[[[[[[]]]] [[[]]] [[[[[]]]]]]]
111=[[[[[[[[]]]]]]] [[[]]]] [[[[]]]]
112=[[[[[]]]] [[[]]]] [[[[[]]]]]
113=[[[[[[]]]] [[[]]]] [[[[[]]]]]]
114=[[[[[[[]]]] [[[]]]] [[[[[]]]]]]]
115=[[[[[[[[]]]] [[[]]]] [[[[[]]]]]]]]
116=[[[[[[]]]] [[[]]]]] [[[[[]]]]]
117=[[[[[[[]]]] [[[]]]]] [[[[[]]]]]]
118=[[[[[[[[]]]] [[[]]]]] [[[[[]]]]]]]
119=[[[[]]] [[[[]]]]] [[[[[[[[]]]]]]]]
120=[[[[[[[]]]] [[[]]]]]] [[[[[]]]]]
121=[[[[[[]]]] [[[]]]]] [[[]]]
122=[[[[[[[]]]] [[[]]]]] [[[]]]]
123=[[[[[[[[]]]] [[[]]]]] [[[]]]]]
124=[[[[[[[[[]]]] [[[]]]]] [[[]]]]]]
125=[[[[[[]]]]]] [[[[]]]]
126=[[[[[[[]]]]]] [[[[]]]]]
127=[[[[[[[[]]]]]] [[[[]]]]]]
128=[[[]]] [[[[[[[[]]]]]]]]
129=[[[[]]] [[[[[[[[]]]]]]]]]
130=[[[[[]]] [[[[[[[[]]]]]]]]]]
131=[[[[[[]]] [[[[[[[[]]]]]]]]]]]
132=[[[[[[[]]]]] [[[[]]]]]] [[[]]]
133=[[[[[[[[]]]]] [[[[]]]]]] [[[]]]]
134=[[[[[[[[]]]]] [[[[]]]]]]] [[[]]]
135=[[[[]]]] [[[]]] [[[[[[]]]]]]
136=[[[[[]]]] [[[]]] [[[[[[]]]]]]]
137=[[[[[[]]]] [[[]]] [[[[[[]]]]]]]]
138=[[[[[[[]]]] [[[]]] [[[[[[]]]]]]]]]
139=[[[[[[[[]]]] [[[]]] [[[[[[]]]]]]]]]]
140=[[[[[]]]] [[[]]]] [[[[[[]]]]]]
141=[[[[[[]]]] [[[]]]] [[[[[[]]]]]]]
142=[[[[[[[]]]] [[[]]]] [[[[[[]]]]]]]]
143=[[[[[[[[]]]] [[[]]]] [[[[[[]]]]]]]]]
144=[[[[[[[]]]] [[[]]]]]] [[[]]]
145=[[[[[[[[]]]] [[[]]]]]] [[[]]]]
146=[[[[[[[[[]]]] [[[]]]]]] [[[]]]]]
147=[[[[[[[[]]]]]]]] [[[]]] [[[[]]]]
148=[[[[[[[[[]]]]]]]] [[[]]] [[[[]]]]]
149=[[[[[[[[[]]]]]]] [[[]]]] [[[[[]]]]]]
150=[[[[[[[[[]]]]]]]] [[[]]]] [[[[]]]]
151=[[[[[[[]]]]]] [[[]]] [[[[[[[]]]]]]]]
152=[[[[[[[[[]]]]]]] [[[]]]]] [[[[[]]]]]
153=[[[[]]] [[[[]]]]] [[[[]]]] [[[]]]
154=[[[[[]]] [[[[]]]]] [[[[]]]] [[[]]]]
155=[[[[[[[[]]]] [[[]]]]]]] [[[[[[]]]]]]
156=[[[[[[[]]]]]] [[[]]]] [[[[[[[]]]]]]]
157=[[[[[[[[]]]]]] [[[]]]] [[[[[[[]]]]]]]]
158=[[[[[[[[]]]]]] [[[]]]] [[[[]]]]] [[[]]]
159=[[[[[[[[]]]]]] [[[]]]] [[[]]]] [[[[]]]]
160=[[[]]] [[[[[[]]]]]] [[[[[[]]]]]]
161=[[[[]]] [[[[[[]]]]]] [[[[[[]]]]]]]
162=[[[[]]]] [[[[[]]]]] [[[]]]
163=[[[[[]]]] [[[[[]]]]] [[[]]]]
164=[[[[[]]]] [[[[[]]]]]] [[[]]]
165=[[[[[[]]]] [[[[[]]]]]] [[[]]]]
166=[[[[[[]]]] [[[[[]]]]]]] [[[]]]
167=[[[[[[[]]]] [[[[[]]]]]]] [[[]]]]
168=[[[[[[[]]]] [[[[[]]]]]]]] [[[]]]
169=[[[[[[]]]]] [[[[]]]]] [[[]]]
170=[[[[[[[]]]]] [[[[]]]]] [[[]]]]
171=[[[[[[[[]]]]] [[[[]]]]] [[[]]]]]
172=[[[[[[[[[]]]]] [[[[]]]]] [[[]]]]]]
173=[[[[[[[[[[]]]]] [[[[]]]]] [[[]]]]]]]
174=[[[[[[]]]] [[[]]]]] [[[[[[[]]]]]]]
175=[[[[[[]]]]]] [[[]]] [[[[[[[[]]]]]]]]
176=[[[]]] [[[[]]]] [[[[[[]]]] [[[]]]]]
177=[[[[[[[]]]] [[[]]]]] [[[]]]] [[[[]]]]
178=[[[[[[[[]]]] [[[]]]]] [[[]]]] [[[[]]]]]
179=[[[[[[[[[]]]] [[[]]]]] [[[]]]] [[[[]]]]]]
180=[[[[[[[]]]]]]] [[[]]] [[[[[[]]]]]]
181=[[[[[[[[]]]]]]] [[[]]] [[[[[[]]]]]]]
182=[[[[[[[[[]]]]]]] [[[]]] [[[[[[]]]]]]]]
183=[[[[[[[[]]]]]] [[[]]]] [[[[[[[[]]]]]]]]]
184=[[[[[]]]] [[[]]] [[[[[[]]]]]]] [[[[[]]]]]
185=[[[[[[[[]]]]]]] [[[]]]] [[[[[[]]]]]]
186=[[[[[[[[[]]]]]]] [[[]]]] [[[[[[]]]]]]]
187=[[[[]]] [[[[]]]]] [[[[[[]]]] [[[]]]]]
188=[[[[[]]] [[[[]]]]] [[[[[[]]]] [[[]]]]]]
189=[[[[]]]] [[[]]] [[[[[[[[]]]]]]]]
190=[[[[[]]]] [[[]]] [[[[[[[[]]]]]]]]]
191=[[[[[[]]]] [[[]]] [[[[[[[[]]]]]]]]]]
192=[[[[[]]]]] [[[[]]]] [[[[]]]]
193=[[[[[[]]]]] [[[[]]]] [[[[]]]]]
194=[[[[[[[]]]]] [[[[]]]] [[[[]]]]]]
195=[[[[[[]]]]] [[[[]]]]] [[[[]]]]
196=[[[[[[[]]]]] [[[[]]]]]] [[[]]]
197=[[[[[[[[]]]]] [[[[]]]]]] [[[]]]]
198=[[[[[[[]]]]] [[[[]]]]]] [[[[]]]]
199=[[[[[[[[]]]]] [[[[]]]]]] [[[[]]]]]
200=[[[[[]]]] [[[]]]] [[[]]] [[[]]]
201=[[[[[[]]]] [[[]]]] [[[]]] [[[]]]]
202=[[[[[[]]]] [[[]]]] [[[]]]] [[[]]]
203=[[[[[[[]]]] [[[]]]] [[[]]]] [[[]]]]
204=[[[[[[[[[]]]]] [[[[]]]]]]]] [[[[]]]]
205=[[[[[[[[[[]]]]] [[[[]]]]]]]] [[[[]]]]]
206=[[[[[[[[]]]] [[[]]]] [[[]]]]]] [[[]]]
207=[[[[[[[[[[]]]]] [[[[]]]]]]]]] [[[[]]]]
208=[[[[[[[]]]]]] [[[]]]] [[[]]] [[[[]]]]
209=[[[[]]] [[[[]]]] [[[[[[]]]]] [[[[]]]]]]
210=[[[[[[[]]]] [[[]]]]]] [[[[[[[[]]]]]]]]
211=[[[[[[[[]]]] [[[]]]]]] [[[[[[[[]]]]]]]]]
212=[[[[[[[[]]]]]] [[[]]]] [[[]]]] [[[[[]]]]]
213=[[[[[[[[[[[[]]]]] [[[[]]]]]]]]]]] [[[[]]]]
214=[[[[[[[[[[[[[]]]]] [[[[]]]]]]]]]]] [[[[]]]]]
215=[[[[[[[[[]]]]]]]] [[[[[[[]]]]]]]] [[[[[[]]]]]]
216=[[[[[[[]]]]]]] [[[[]]]]
217=[[[[[[[[]]]]]]] [[[[]]]]]
218=[[[[[[[[[]]]]]]] [[[[]]]]]]
219=[[[[[[[[[[]]]]]]] [[[[]]]]]]]
220=[[[[[[[[[[[]]]]]]] [[[[]]]]]]]]
221=[[[[[[[[[[[[]]]]]]] [[[[]]]]]]]]]
222=[[[[[[[[[[[[[]]]]]]] [[[[]]]]]]]]]]
223=[[[[[[[[[[[[[[]]]]]]] [[[[]]]]]]]]]]]
224=[[[[[]]]] [[[]]]] [[[]]] [[[[]]]]
225=[[[[[[[[]]]]] [[[[]]]]]]] [[[]]]
226=[[[[[[[[[]]]]] [[[[]]]]]]] [[[]]]]
227=[[[[[[[[[[]]]]] [[[[]]]]]]] [[[]]]]]
228=[[[[[[[[[[[]]]]] [[[[]]]]]]] [[[]]]]]]
229=[[[[[[[[[[[[]]]]] [[[[]]]]]]] [[[]]]]]]]
230=[[[[[[[[[[[[[]]]]] [[[[]]]]]]] [[[]]]]]]]]
231=[[[[]]] [[[[[[]]]]]]] [[[[[[[[]]]]]]]]
232=[[[[[[]]]] [[[]]]]] [[[]]] [[[[]]]]
233=[[[[[[[]]]] [[[]]]]] [[[]]] [[[[]]]]]
234=[[[[[[[]]]]]] [[[]]]] [[[[]]]] [[[]]]
235=[[[[[[[[]]]]]] [[[]]]] [[[[]]]] [[[]]]]
236=[[[[[[[]]]] [[[]]]]] [[[]]]] [[[[[]]]]]
237=[[[[[[[[]]]]]] [[[]]]] [[[[]]]]] [[[[]]]]
238=[[[[[]]] [[[[[[]]]]]]]] [[[[[[[[]]]]]]]]
239=[[[[[[]]] [[[[[[]]]]]]]] [[[[[[[[]]]]]]]]]
240=[[[]]] [[[[]]]] [[[[[[]]]]]] [[[[]]]]
241=[[[[]]] [[[[]]]] [[[[[[]]]]]] [[[[]]]]]
242=[[[[[[]]]] [[[]]]]] [[[]]] [[[]]]
243=[[[[]]]] [[[[[[]]]]]]
244=[[[[[]]]] [[[[[[]]]]]]]
245=[[[[[[]]]] [[[[[[]]]]]]]]
246=[[[[[[[]]]] [[[[[[]]]]]]]]]
247=[[[[[[[[]]]] [[[[[[]]]]]]]]]]
248=[[[[[[[[[]]]] [[[[[[]]]]]]]]]]]
249=[[[[[[]]]] [[[[[]]]]]]] [[[[]]]]
250=[[[[[[]]]]]] [[[[]]]] [[[]]]
251=[[[[[[[]]]]]] [[[[]]]] [[[]]]]
252=[[[[[[[]]]]]] [[[[]]]]] [[[]]]
253=[[[[[[[[]]]]]] [[[[]]]]] [[[]]]]
254=[[[[[[[[]]]]]] [[[[]]]]]] [[[]]]
255=[[[[[[[[[]]]]]] [[[[]]]]]] [[[]]]]
256=[[[[[]]]]] [[[]]]
8191=[[[[[[[[]]]]]] [[[[]]]]] [[[[[[]]]]] [[[[]]]]]]
13071=[[[[[[[[[]]]] [[[]]]]] [[[]]] [[[[]]]] [[[]]] [[[[[]]]]]]]]
524287=[[[[]]]] [[[]]] [[[[[[[[]]]]]]]] [[[[[[]]]]] [[[[]]]]][[[[[[[[[[[]]]]]] [[[]]]] [[[[]]]]]] [[[[]]]]]]
2147483647=[[[[[[]]]]]] [[[[]]]] [[[[[]]]]] [[[[]]]][[[[]]] [[[[]]]]] [[[[[]]]]][[[[[[[[[[[]]]]]]] [[[[]]]]]]]] [[[[]]]][[[[[[[[[[[[[[[]]]]] [[[[]]]]]]]]]]] [[[[]]]]]] [[[[[]]]]]]
1449565302=[[[[[[[[[]]]] [[[]]]]]] [[[]]]]] [[[[[[[[]]]] [[[[[]]]]]]]]][[[[[]]] [[[[]]]]] [[[[]]]] [[[]]]] [[[[]]]][[[[[[[[[[[]]]]] [[[[]]]] [[[[]]]]]]] [[[[[]]]]]]]]
1746268229=[[[[[[[]]]]]]] [[[[]]]] [[[[]]] [[[[[[[[]]]]]]]]][[[[]]]] [[[]]] [[[[[[]]]]]][[[[[[[[[[]]]] [[[]]]] [[[]]]] [[[]]]]] [[[[[]]]]]]]
126528612=[[[[[[]]]] [[[[[[]]]]]]]] [[[[[]]]]][[[[[[[]]]]]]] [[[[[[[[]]]]]]]][[[[[[[[[]]]]]] [[[]]]] [[[[[]]]]]]] [[[[[]]]]]
778085967=[[[[[[[[[]]]] [[[[[]]]]]]]]]] [[[[[[]]]]]] [[[]]][[[[[[[]]]]] [[[[]]]]]] [[[[]]]][[[[[[[]]]] [[[[[]]]]]]] [[[]]]] [[[[[]]]]]
1553783038=[[[[[]]] [[[[[[[[]]]]]]]]]] [[[[[[[]]]] [[[]]]]]][[[[[]]] [[[[]]]]]] [[[[[]]]]][[[[[[[[[]]]] [[[]]]] [[[]]]]]] [[[]]]] [[[[]]]][[[[[[[[]]] [[[[[[]]]]]]]] [[[[[[[]]]]]]]]]]
997599288=[[[[[]]]] [[[]]] [[[[[[]]]]]]] [[[[[[[[]]]]] [[[[]]]]]]][[[[[[[[]]]]]] [[[[[]]]]]]] [[[[[[]]]]]][[[[[[[[[[]]]] [[[]]]]]]] [[[]]]] [[[[[[]]]]]]]
```
7944b for 1-256
1275b for the large cases
] |
[Question]
[
You are given two regexes and your task is to determine if the strings matched by the first regex are a subset of the strings matched by the second regex.
For this we are going to use a limited mathematical definition of a regex. A regex is defined recursively as one of:
* `ε` - This matches only the string `""`
* `0` - This matches only the string `"0"`
* `1` - This matches only the string `"1"`
* `r1|r2` - This matches iff `r1` or `r2` matches
* `r1r2` - This matches iff `r1` matches a prefix of the string and `r2` matches the remaining string
* `r1*` - This matches iff any of `ε`, `r1`, `r1r1`, `r1r1r1`, etc. matches.
Input format is flexible. If you use a string with some kind of syntax, make sure that it can represent every regex (you may need parenthesis). Output as per standard [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'") rules.
# Examples
```
(0|1)*, (0(1*))* -> False
The first regex matches every string, the second one only ones that start with a 0
0(0*)1(1*), (0*)(1*) -> True
The first regex matches strings that consists of a run of 0 and a run of 1, and both runs have to have length >0. The second regex allows runs of length 0.
((10)|(01)|0)*, (1001)*0 -> False
The first regex matches "10" which is not matched by the second regex.
0, 1 -> False
Neither is a subset of one another
1(1*), (1|ε)*1 -> True
Both regexes match nonempty strings that consist of only ones
10((10)*), 1((01)*)0 -> True
Both regexes match nonempty strings made by concatenating "10"
ε*, ε -> True
Both only match the empty string
```
```
[Answer]
# [Python 3](https://docs.python.org/3/), 1206 bytes
```
l=len
r=range
def R(a):return r(l(a))
def A(a,b):
for x in b:
for z in[0,1]:x[z]<<=l(a)-1
for x in a:
if x[2]:
x[2]=b[0][2]
for z in[0,1]:x[z]|=b[0][z]
return a+b[1:]
def B(a,b):
c=[]
for i in R(a):
for j in R(b):
c+=[[0,0,a[i][2]or b[j][2]]]
for z in[0,1]:
for k in R(a):
if(a[i][z]>>k)%2:c[-1][z]|=b[j][z]<<k*l(b)
return c
def C(s,i):
S=[];T=[]
while i<l(s):
c=s[i]
if c=="(":a,i=C(s,i+1);T+=[a]
if c==")":break
if c=="0"or c=="1":X=[[4,4,0],[4,4,1],[4,4,0]];X[0][int(c)]=2;T+=[X]
if c=="ε":T+=[[[2,2,1],[2,2,0]]]
if c=="|":
t=T[0]
for j in r(1,l(T)):t=A(t,T[j])
S+=[t];T=[]
if c=="*":
a=T[-1];a[0][2]=1
for x in a:
if x[2]:
for z in[0,1]:x[z]|=a[0][z]
i+=1
t=T[0]
for j in r(1,l(T)):t=A(t,T[j])
S+=[t]
t=S[0]
for j in r(1,l(S)):t=B(t,S[j])
return t,i
I=input().split(",")
a=C(I[0],0)[0]
b=C(I[1],0)[0]
Q=[(1,1)]
V=set(Q)
d=1
while l(Q):
p,q=Q.pop();f=any([(p>>i)%2 and a[i][2]for i in R(a)]);g=any([(q>>i)%2 and b[i][2]for i in R(b)])
if f and not g:d=0
for z in[0,1]:
s=0;t=0
for i in R(a):
if(p>>i)%2:s|=a[i][z]
for i in R(b):
if(q>>i)%2:t|=b[i][z]
u=(s,t)
if u not in V:V.add(u);Q.append(u)
print(d)
```
[Try it online!](https://tio.run/##hVPBbuIwEL3nK6xIK9ngopjtyamR2j31yIKqSpYPTgjUEIU0MdoW9bf2N/aX2Bkn2YKotCd7xs9v3oyf63f/sq@@n06lKosqalRjq00RrYo1@Uktk03hD01FGlpCxEL@nlqeMRmR9b4hb8RVJIMgREeIdMKFkW/6aO7uFN66EWdQi1C3Jm96anAbNirTiYEV42uaj@74CMe9GjvOtJAmqHkY1ORKm66Qw0JBfS9r2yUCjJB8rDSwJ9xqh1UBkOkt7swXCjATUrtzVoJN0EBwNLPZjn2bylzfCNPr3ZrQ/25UQtV/uvOg@AdtuUOWBShOl0H2rxdXFsTdlbQN/LlqgbsbVa5UTGNpuVPh6liwdAk92LNzFsusKezuM5PEoBk3IpbP0PAtv@WJ4WEV/ZoYkz7jbF3lac6Mmgbi5zPiP79jiTmtp3waLuKadKPqMR9xGIlXS@AaJhhm3lDBS7pkTHp1Tz1fwmAYIhZA6YfmB55Rx2OBByaZ2s4USgyUnwa6tNDXprGDaYgbI8cg73/iOmmIX3yFXwT8A@AXHb5/W89d9KhcVR88ZZO2Lp2nMY9ZZOHVHoGJJwz5shCKIZwrDbSCmehJtYWnc/hjoLbzQwkhdFjzVzWf1PuasnStbPVONa1nMwemI7Zakd7HF9Y3LN300NczaHYFzRg2AeNcB0C192QjVyqJrv9Bq5LU48n1L8Pf0EuSLc7e9bO/qDQge0XS41cZkAcF5vass8MhCIFrT/JpYlcremDpfGLruqhwH9UNWnbFTieafAg24jShYsTY6C8 "Python 3 – Try It Online")
## Input
The two regex expressions on one line, separated by a comma. The expressions are not allowed to be empty and they also must be well-formed. That means that each opening bracket has to have a corresponding closing one, there has to be a non-empty subexpression before every `*`, and two non-empty subexpressions left and right of every `|`. `ε` can be used to match the empty string. The order of precedence is `*`, concatenation, `|` (just as normal regex).
## Output
`1` when the first regex is a subset of the second one, else `0`.
## How it works
In the beginning, the algorithm converts both regex expressions into a [deterministic finite automaton](https://en.wikipedia.org/wiki/Deterministic_finite_automaton). Then it calculates the product of the two automatons and does a search beginning at the start node. If it finds a node that is an accepting state for the first regex but not for the second, the first regex can't be a subset of the second one. If it can't find such a node, it is a subset.
## Complexity
The worst-case time complexity is roughly \$O\left(2^{2^n}\right)\$ (I might have ignored some insignificant terms), where \$n\$ is the length of the input. In practice, the runtime is much better than expected: All the example test cases and even the example `0(0|ε)(00|ε)(0000|ε)(000000000)*,00000000(00000000)*` from [l4m2](https://codegolf.stackexchange.com/users/76323/l4m2) run in less than 0.1 seconds.
## Code length
I'm not good at minifying my code, so there might be still a lot of room for improvement.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~105~~ 99 bytes
```
a=>b=>(g=n=>!n||g(n-1)&(h=x=>!n.toString(2).slice(1).match(`^${x}$`))(a)>=h(b))(2**2**(a+b).length)
```
[Try it online!](https://tio.run/##jZPPjtMwEMbvfophtWLtkLr2ihtKDhw4cqFn6CR1k6DUrmL3nyiP1dfoK5WxU9pFWgSHKOOx5/fNfHG@4xZ9PXTrMLFuYS7L4oJFWRUlbwpblG/s8dhwO9HiLW@LfUzI4L6EobMNfxbS911tuBZyhaFu@fzr44/9z8e5EBxFWbS8okir5/fTjOO7Ssje2CabisuHOePqqEWWA1dcZ0JkMCnhE/besFlrYNkNPsBgGrOHxDYezNYMB/BJPIdAp7ypnV2As4ae/hADTxsY6BQOAXZdaAFBMaa4yoSOSlExEzGKirNh83fBUepKJCXf@eDBLQk5bGwMFCDp35Y6T@vKkSylPLS4NRDc@I7D00apJMzuzY@S2Pdu58ciAl2PKskYJwPFkSstjir5pRXFmfq3Xw9aPcCu7eoWOg/WhesONXh4aV@qkkAm5aDv2M@G3DNDrEXwm8qbEFuLZiPB4hZjvy3Vx/NJZPpm6cdkQQRTI0mWGrBmtQ6HV20dyddPSFiVxo5ozW/j/jd5hQsThyR4jcFYDJROfjB2PpGJ59OfvCQ9wqIxL2lsLgez7pHu@ZTLNKwc7058T@km8m855lVei6KM07jeyN41fMnxXnk@0cknLp7oh6heTVO9uPwC "JavaScript (Node.js) – Try It Online")
Assuming any mismatch found in \$2^{\left|a\right|+\left|b\right|}-1\$ length. Actually \$\left|a\right|\cdot\left|b\right|\$ should be enough because of number of states, but `2**(a+b).length` is shorter than `a.length*b.length`.
\${\left|a\right|+\left|b\right|}-1\$ is not enough for `0(0|)(00|)(0000|)(000000000)*` >= `00000000(00000000)*` (shortest counterexample 72 "0"s)
[Answer]
# Python3, 677 bytes
```
import itertools as it,re
I=isinstance
def t(q):
if I(q,str):yield q;return
if all(I(i,str)for i in q):yield from q;return
yield from map(''.join,it.product(*[[j for k in i for j in t(k)]for i in q]))
def p(s):
q=[];f=0
while s:
if(n:=s[0])==')':return s[1:],q
if n=='(':
s,v=p(s[1:])
if f:q[-1]=(q[-1],v);f=0
else:q+=v
elif n=='*':q[-1]=[*q[-1],''];s=s[1:]
elif n=='|':f=1;s=s[1:]
else:
s=s[len((v:=re.findall('^[10ε]+',s))[0]):]
v=[''.join([i if i in'10'else '' for i in v[0]])]
if f:q[-1]=[*q[-1],*v];f=0
else:q+=[v]
return s,q
G=lambda x:[*t(p(x)[1])]
def f(a,b):
j,k=G(a),G(b)
return all(i in k for i in j if len(i)<=max(map(len,k)))
```
[Try it online!](https://tio.run/##XVNNb9swDD3Pv4LoRaSrBRJ2KdzpuiCXnXbTPMBNbFSJ4y@5Xgvkb@Vv5C9louKkXU8m@cinxye5exuf2@bbQzecz27ftcMIbiyHsW1rD4UPiRzKZGWcd40fi2ZdJpuyghF7yhJwFaywl34cKHtzZb2B/nEox5ehiVhR17hCF/GqHcCBa6C/tlZDu//Q/6G4LzoUYrFtXSPduOiGdvOyHjG1dgvMs2MeF8MthyPuKH8/ICeKIjv0LLI3Nn@sjErg77OrS/ChFtRhkxlvVU7GCBLZRQZ4q7Nc9rEDmgCh4HbwcjKBj1HiPKBV1tuvOjcYP3KiyyEAZe3LrL83U8LxzJOKud2ml34h8kdvIuPHvoPIKqP/QwJblBBKddkgTpkZykXlmg0bLP5YrU7H/F5IT8QLxTGYjJ09ROtYL5sjtBJMCELAzbApDOWUf1rrqjOd8s@L2Sk0Xw0LZi1NXeyfNgW8ZjYdscNXspoZ@RYqLOQT38NW7swSC5JLfKLbPK8QVezeBW1ZB6/q6LvZF6/IDyLkckdEZ2/u7u4SVAdNqQRUqFPi6EcR5CUKVUqaa4yldIl@DS9lgqgVHVBpOqg4qlWIU3UblaCv8ZVBH05HSvXMoFXkYEQjE6WkZuh0DIyn45yxwts6lavDL4U/26aU4Be@q92I4ncjKNjyJbgj12DAXQEJgkLZ@/Abzu4ZY6OsC3tu1@GhcCTy8z8)
] |
[Question]
[
Given an ASCII-art shape made of the characters `/\|_`, your challenge is to return the number of sides it has.
A side is a straight line of one of those, for example:
```
\
\
\
/
/
|
|
|
|
_____
```
Are all sides.
For example, this shape:
```
___
/ \
/_____\
```
Has *four* sides. You can assume the input will be a single valid, closed shape - that is, things like this:
```
/
_
/ \
\
/
/_\
\_/
_ _
/_\ /_\
```
Will *not* occur, and the shape will never touch itself, so this is invalid:
```
/\/\
/ /\ \
/ /__\ \
|______|
```
## Testcases:
```
/\
/__\ -> 3
________
/ \
|_________\ -> 5
___
|_| -> 4
/\/\/\/\/\
|________| -> 13
_ _
| |_| |
| _ | -> 12
|_| |_|
/\
/ \
/\ / \ /\
/ \/ \ / \
/ \/ \
/____________________\ -> 7
_
/ |
_| |
/___/ -> 8
```
[Answer]
# [J](http://jsoftware.com/), 49 bytes
*-1 thanks to Jonah*
This answer has 6 sides.
```
[:+/@,i.@4(1==-{&(0 1,1,.i:1)@[|.!.0=)"{'_/|\'&i.
```
[Try it online!](https://tio.run/##bVDBDoIwDL33KyoHYBE2MJ5GlpCYePLklZkdjChe/AD679hNQBP3lmVtX/va7jklMuvRaMywwAo131Li4Xw6Tp3eqrYYZLvPa2PKMc0rrIu6kIOuRduR3MjKiGTMnCKbpYOcBNyNvl0frza/ND172DXS7TAPwgJQWVDOWRDwz7kZoHCGBVqC8RqfTY5ilLLL@YpQvC93YhlkISR@fYAgeNEKXAGrxV1W088dQsFmb03w1LycXRIV/uDDhj/6R/zX/Oxei3gRP78vVSCmNw "J – Try It Online")
* `'_/|\'&i.` Map walls to 0…4.
* `i.@4` For each possible wall …
* `|.!.0=` shift the corresponding bitmap …
* `{&(0 1,1,.i:1)@[` into the direction the wall points to.
* `1==-` Subtract this from the original bitmap and keep the 1s.
* `[:+/@,` Count the 1s.
Example for the `_`-lines in
```
____
|__| original
____
|__| shifted by 1 into a direction _ points to
X.... spots where _ is in the original image,
.X... but not in the shifted one.
```
Two Xs, thus two `_`-lines.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 94 bytes
```
(?<=(.)*)(\|(?=.*¶(?<-1>.)*\|)|\\(?=.*¶(?<-1>.)*.\\)|/(?=.*¶(?<-1>.)*(?<-1>/)))(?(1)^)
_+|\S
```
[Try it online!](https://tio.run/##ZU87DsIwDN19ikgRUgyiVndKD9HVImVgYGFAjD5XD9CLBdv9ofIy5Pm9F9t5Pz7P172MA0To@hjhkPoI41BSe2lShUdMLKltquM4qHSur6qxoDDv1YoZhfbqRAgRU5tqvCEEyCfhrpRADJQzA4Q8AyjMYJBFtIR5kgWAeDlbQKyDvtFI0FAQvU0Q8Mr9FRvVFiu1gS4512oNmDVvxUuQwg8m17/yD/bR2fuIbmnLWZC@ "Retina 0.8.2 – Try It Online")
Link includes test suite that takes double-spaced test cases. Explanation:
```
(?<=(.)*)(\|(?=.*¶(?<-1>.)*\|)|\\(?=.*¶(?<-1>.)*.\\)|/(?=.*¶(?<-1>.)*(?<-1>/)))(?(1)^)
```
Match any of `|`, `\` or `/` with the corresponding symbol on the next line, but indented to line up with it and replace it with a space. (This is slightly golfier than using negative lookaheads.)
```
_+|\S
```
Count any remaining non-whitespace, except a run of `_` only counts as one side.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 42 bytes
```
WS⊞υι≔⪫υ⸿θPθFθ⎇№⁺ ⊟KD²✳⊕|⌕/|\ι⁴ιψι≔LKAθ⎚Iθ
```
[Try it online!](https://tio.run/##bY5PS8QwEMXv/RRDThOoBMTbntaVhRXFgh4DUrpjOxiTmj8uC373mrTurgffJe83b4a8bmh951ozTYeBDQHu7Jjic/Rse5QSmhQGTDWwXFXrELi3eO/YlpHQXsgaPnPymEzkMd9ELPjmPGQDzTx5IW9bf8SNS5kakwIKEDU0bsSG6P2OPXWRncXrGi6ws52nD7KR9njL8cCBnjxu2e5RqG@tRSlVw42ctcCxPJemD2T7OMyfrI1B@dt2Y6j1mM3Sb9OGUluupglOUro6W4AZlJ59pvNCidSypU@LCv5oSXWlXv@RrqarL/MD "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of newline-terminated strings. Explanation:
```
WS⊞υι
```
Input the list of strings.
```
≔⪫υ⸿θ
```
Join them with carriage returns.
```
Pθ
```
Print the result to the canvas without moving the cursor.
```
Fθ
```
Loop over each character.
```
⎇№⁺ ⊟KD²✳⊕|⌕/|\ι⁴ιψι
```
If the character is a space or equal to the adjacent character in the appropriate direction (E, SE, S or SW as appropriate), then erase it, otherwise reprint it.
```
≔LKAθ
```
Count the number of remaining characters on the canvas.
```
⎚Iθ
```
Clear the canvas and output the result.
[Answer]
# Python3, 598 bytes:
```
import re
def f(b,c,l,s=[]):
k=0
for u,v in{'/':[[-1,1],[1,-1]],'\\':[[1,1],[-1,-1]]}[l]:
if(x:=c[0]+u)>=0 and(y:=c[1]+v)>=0 and(x,y)not in s:
try:
if b[x][y]==l:k=1;yield from f(b,(x,y),l,s+[(x,y)])
except:1
if k==0:yield tuple(sorted(s))
def g(b):
b=[*filter(None,b.split('\n'))]
e=enumerate;S=set;R=sum;L=len
t=[((x,y),j) for x,a in e(b)for y,j in e(a)if j=='/'or j=='\\']
n={m for i in t for m in f(b,i[0],i[-1],[i[0]])}
return R(not any(S(i)&S(j)==S(i)and L(j)>L(i)for j in n)for i in n)+R(L(re.findall('_+',i))for i in b)+R(L(re.findall('\|+',''.join(i)))for i in zip(*b))
```
Very simple algorithm: find the number of diagonal edges (using `f`), and then the number of horizontal and vertical edges (using `re.findall`)
[Try it online!](https://tio.run/##ZVLbbqMwEH33V1h5WOzGCaHXVSL3C6J9aB8BodCYrlNiEDhV2NJv787YhKLdiRLmHJ8zzIxTd/Z3ZW5@1s3Xlz7WVWNpo8heFbRguXgRpWhlnPI1oW9yRWhRNfQk3qk2H0EYrON4EYkoFXEkFlGaiiBJkPTcwpOfcZmCneqCndfyJV6l8xN/lCu6M3vWIROl8/eROYuOm8rCG2iLNmqbzj2hAM3jcxp3qZTl@k1Gm06rck@Lpjq6bp0XO57HLk05@tT5RdV2HREs8Cblau1t9lSXirUwsdqzlnM39CvLcdZcxleFLq1q2K/KKJEv27rUlgWJCThPCVVSmdNRNTurNs@yVXbzJNvTcbOVpTKEWhkz382Bu52dxQ4nUlAeYScOHu44NHWQEpYJNCawQahv5MfRGTXqrEuPmOKcGnYIPwtcMuYp/yRwa/bUGPrEcHk707FnpvmPZ3bgUmIKu6VbQI9bAFjOdWD4@BLD509syxq1LLTZ78qSBdk8EJp/S/L/JUkPmiBYHiptoPBE/EfX7Crn/KuVs9kMbiLLMkJDuJEEviTMMBJK8LCNvCZMkE88d@25bAiCVhfop6S/HECRocqNc6C2z3pP3ToqTC6fiW9Q3A2vgZoZnFKw0h6eyPTEoYv0fphkiDChkxj5cOhweoDScOx9YiReH46TDW6/qTGS0Tws7p@47PHh0mHmK/fwwAm8LfSqutHGslf3px/zaAqup@BmCm6n4G4K7qfgAe79Lw)
] |
[Question]
[
*Inspired by my geography class*, [*Sandboxed*](https://codegolf.meta.stackexchange.com/questions/2140/sandbox-for-proposed-challenges/23999#23999)
Simulate weathering / erosion.
### Input
Input will be given as a string of any 2 characters (or see below) you like in the shape of the rock (here i use spaces and hashes):
```
###
####
#####
#######
#######
########
```
Or if your language doesn't support strings, a square matrix of 1s and 0s, a matrix of chars, whatever makes your answer more golfier.
# Process
The rock will erode until it disappears completely.
Lets take example of input:
```
##
## ### #
#########
###########
```
First we find which part of the rock is exposed (that is there is no rock particle directly above / below / left / right) to the air (i use @ to show such particles here):
```
@@
@@ @#@ @
@##@###@@
@########@@
```
NOTE: The bottom most rock particles are touching the ground and they are not touching air, hence we don't count these particles.
Then we randomly (50% chance individually for each particle) remove the rock particles (here #) (apply gravity similar to [this challenge](https://codegolf.stackexchange.com/q/235493/103854) that are exposed to the air:
```
#
##
## ### #
##########
```
And be repeat the process until the rock disappears and output the rock in between each iteration (including the original input). In this case we output:
```
##
## ### #
#########
###########
#
##
## ### #
##########
## ##
#########
# #
## #### #
#
# # # #
# #
```
This is code-golf, answer in the shortest amount of bytes wins.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 58 bytes
```
≔Eθ⁰ηWSUMη⁺κ⁼#§ιλ⊞η⁰W⌈η«Mι↓↑Eη×#κ⸿UMη↨¹Eκ∨‹μ⌊⟦§η⊖λ⊖κ§η⊕λ⟧‽
```
[Try it online!](https://tio.run/##VY9Nb8MgDIbPza9A4WIkKnXX9tStO0RqtGgfp20HlKCCAiSFpK007bcz0w91sQQy5rHf17USvu6EiXEdgt45KEUPe04WjBPFVtlRaSMJFK4fh7fBa7cDxghCT521wjWgOKnMGKDl5Hk/ChMgpzkn66FwjTyB5sQwjFVWjUElenGfWoqTtqMFhSN/slnZHWRqWG66o0NqVqHeAMuPnifF1PyurbwqtOepVyb/8nl6TY09iiDh4dKM/l48bGUIYLGi3Vn58@YT6Y2svbTSDbIB9DwttOy@E7KFm7Df@PuKop2Fy7K/MRIMStNNspTQdDCnt/ifU5rF@cH8AQ "Charcoal – Try It Online") Link is to verbose version of code. Assumes input is a rectangular newline-terminated list of strings. Explanation:
```
≔Eθ⁰ηWSUMη⁺κ⁼#§ιλ
```
Calculate the height of each column of the rock.
```
⊞η⁰
```
Add a padding entry to prevent wrapping.
```
W⌈η«
```
Repeat until the rock has been eroded away.
```
Mι↓
```
Leave space to display the rock.
```
↑Eη×#κ
```
Output the rock.
```
⸿
```
Leave a blank line between rocks. (Otherwise they just crash into each other making the output impossible to interpret.)
```
UMη↨¹Eκ∨‹μ⌊⟦§η⊖λ⊖κ§η⊕λ⟧‽
```
For each column, for each particle, check whether it's exposed, and add up all of the unexposed particles and randomly the exposed particles.
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 42 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
0ì€Ć[ø€{ø=ÐSO_#ø‚εεDT‚00.:ø}}`ø‚øεøεSÚΩ}J
```
I/O as a list of equal-sized strings, with digits `0` for spaces and `1` for rocks. The output will be two wider than the input, due to a leading/trailing column of spaces/`0`s.
[Try it online](https://tio.run/##MzBNTDJM/f/f4PCaR01rjrRFH94BpKsP77A9PCHYP14ZyG2YdW7rua0uIYebgEwDAz2rwztqaxPAEod3nNsKwsGHZ51bWev1/3@0koGBgSEQGhgo6YDZhjC2IYJtCGYbYmFDgVIsAA) or [try it online pretty-printed](https://tio.run/##MzBNTDJM/V@j5JlXUFqiUFCUWlJSqVtQlJlXkppipaCk43Jotw6XkmNySWlijkImSBFQ1F7P6dzWRw3zlBVCHjUsrLU9tM3@v8HhNY@a1hxpiz68A0hXH97B5afkXwoyNLMktSixJDM/T@HwfpBmW7BMCboUNsvPbQ0BWwOyBegQoD1chycE@8crAy1pmHVu67mtLiGHm4BMAwM9q8M7amsTwBKHd5zbCsLBh2edW1nr9f@/goKCMhAqKHCBWMoQljKUBRbhUgZzlSE8JK4ylIsMAA).
Uses the legacy version of 05AB1E, because `ø` works on lists of strings. In the new 05AB1E version, most of the `ø` should be `€SøJ` instead.
**Explanation:**
```
0ì€Ć # Add a leading/trailing 0 to each line of the (implicit)
# input-list:
0ì # Prepend a 0 in front of each line
€ # Map over each line:
Ć # Enclose it, appending its own head
[ # Then start an infinite loop:
ø€{ø # Apply gravity:
ø # Zip/transpose; swapping rows/columns
€{ # Sort each row
ø # Zip/transpose back
= # Print the result with newline (without popping)
Ð # Triplicate the current result
S # Convert the top one to a flattened list of digits
O # Sum this list
_ # If it's 0:
# # Stop the infinite loop
ø # Zip/transpose the top; swapping rows/columns
‚ # Pair it with its untransposed list
ε # Map over this pair:
ε # Map over each row:
D # Duplicate the current row
T # Push 10
 # Bifurcate it; short for Duplicate & Reverse copy
‚ # Pair them together: [10,"01"]
00.: # Replace all "10" and "01" in the copy with "00"
ø # Create cell-pairs of the row and modified row
}} # Close both maps
` # Pop and push both separated to the stack
ø # Transpose the top copy back
‚ # Pair them back together
ø # Transpose this pair of matrices
ε # Map over each pair of rows
ø # Zip/transpose to pair together cell-pairs
ε # Map over each pair of cells-pairs:
S # Convert it to a flattened list of four digits
Ú # Uniquify it
Ω # Pop and push a random value from this list
} # Close the inner map
J # Join the list of characters back to a string-line
```
I'm not happy with `}}`ø‚øεøεSÚΩ}J` at all, but I'm unable to find something shorter to concat the values of two matrices. Adding values of two matrices together is no problem, since that is just `+`, but concatenation on the other hand.. (An equal-bytes alternative for this portion could be `}}`øδ+εNèεÚΩ}J`.)
[Feel free to try and find something shorter here.](https://tio.run/##MzBNTDJM/f8/4fCORw2zDu84txWEvQ7POrey1ksBDGJ1uICy57Zon9vqd3gFUAGGHFDG6PASdI2xOv//R0dHqzs6qusoqDs5gUhnZxDp4qIeq6MQre7qCuK5uYFId3cQ6eEBkfH0BPG8vECktzeI9PFRjwVJwcyD6AWqA6uHmA4xCagLLAaxC2Iu0AywGNBmiC0wE2MB)
[Answer]
# [Perl 5](https://www.perl.org/) + `-n0`, 99 bytes
I'm hoping to continue working on this tonight, but this is a start (which I *think* covers the requirements?)
Accepts a rectangular multi-line string of `1`s and `0`s which are transliterated from `#` and space in the link.
```
while(/1/){say;/
/;($-)=@-;s/1(?!1)|(?<!1)1|(?<=0.{$-})1/0|rand 2/ges;1while s/1(.{$-})0/0${1}1/gs}
```
[Try it online!](https://tio.run/##TU3RCoMwDHzvV3TWh/ahphnsqRP3K46JE6RKqwyp/fV17Yawg@SO3CWZOzte4gaUgULQhLj1Tl27eTLbwSx0y@Nk2qoghSYhvp7D2HFAED7FNBDQvJSivkntAHlzQrHz5poIM9eq8qUMAkHttjUPeoa@cxq/Z2je@PkKVOkxIPQuxOOpjjSBsdwpyYLlSpod@NeMvad5GSbjolTmAw "Perl 5 – Try It Online")
[Answer]
# Python 3, 356 bytes
```
import random as r,re
y=lambda _:[' ','#'][r.choice([0,1])]
g=lambda x:[*map(''.join,zip(*[(' '*(len(x)-i.count('#')))+('#'*i.count('#'))for i in zip(*x)]))]
f=lambda x:[w:=g([re.sub('#' if not i else'#(?=[^#])|(?<=[^#])#',y,a)for i,a in enumerate(x)])]+(f(w)if any(i.strip()for i in w)else[])
h=lambda x:[*map('\n'.join,f([f' {i} 'for i in x.split('\n')]))]
```
] |
[Question]
[
Forth is one of the few non-esoteric stack-based languages. For this challenge, we will use a small subset of Forth, which simply executes a sequence of words in a linear fashion — without any definitions or loops.
In good Forth code, each word definition includes a **stack effect** comment, which explains the layout of the stack before and after the word's execution. For example, `+` has the stack effect `a b -- sum`, `swap` has the stack effect `a b -- b a`, and `fill` does `ptr len byte --`. Both before and after the `--`, the top of the stack is to the right, and thus the stack elements are written in the order in which you'd have to push them.
Note that, if the word only manipulates the order of elements on stack, the stack effect is a complete specification of its behavior. **Your task** is to write a program or function that takes such a stack effect as input, and emits an implementation of it in the subset of Forth described below.
## The Forth subset
Your output may make use of the words `drop`, `dup`, `swap`, `>r` and `r>`. Three of those are fully specified by their stack effect:
```
drop ( a -- )
dup ( a -- a a )
swap ( a b -- b a )
```
The last two make use of the **return stack**. Apart from the main **data stack**, Forth also has another stack, which is used to save return addresses while calling user-defined words. However, since Forth implementers are trusting people, the programmer may also store their own data on the return stack within one procedure, as long as they clean it up before returning.
To use the return stack, we have the last two words:
* `>r ( x -- ; R: -- x )` moves an item from the data stack to the return stack
* `r> ( -- x ; R: x -- )` moves an item from the return stack back to the data stack
Your code must use the return stack on in a balanced manner.
## Example
Let's take a close look at one of the programs you could output given the input `c a b -- b a b`.
```
Data stack Return stack
c a b
swap c b a
>r c b a
swap b c a
drop b a
dup b b a
r> b b a
swap b a b
```
Here, `swap >r swap drop dup r> swap` would be your output.
## Input and output
Your input will consist of two lists of names, describing the before and after states of the stack. The names in the first list will all be unique. The names in the second list all occur in the first one.
The output list may contain duplicates, and it does not need to include every name from the input list.
Parsing is not a part of the challenge, so you may use any reasonable format for these lists. Some examples of the input formats you can choose:
```
"a b -- b a"
"a b", "b a"
"ab:ba"
["a", "b"], ["b", "a"]
[2, 7], [7, 2]
```
In particular, you are allowed to reverse the ordering, taking the top of the stack to be the *beginning* of each list.
Your output, which represents a Forth program, can also use any way of encoding a sequence of instructions. For example:
```
"drop swap dup >r swap r>"
"xsd>s<"
"earwax"
[3, 2, 1, 0, 2, 4]
```
## Test cases
Each test consists of two lines. The first is the input, but since the solution isn't unique, the second line is merely an example of what the output can look like. You can use [this Python program](https://tio.run/##lVQ9b9swEN35K66aZEAy0HYzYAMd0gwZsqRdDA80dUqIqCRxpOAERX@7yy9JsSwXqJaTeO/euy/KvLsXrb6ezw22gG8oeoeldVy8ViB0g6sNA//EE9gmu98c4iENp/v03WqCk6YGpIqxa2s66cpMER7ZJsB2C0VD2hSTa1RZG23K1XiO3UVQvxzDjUHVpMT39efDrXh74osEIaYaXr8cxkr9ezUhbpDuaEZJ10mlqm6lRbt/VUU3GCzOZLm0CD951@MdkaayLX6oV6VPKipt4Hcwf4rEwa1FcuMQwxSr/JWmi64nlTJhLKyHQ@sEt1hi26JwFwtyRD99rIC3Dsm37xc3vnBKK1BBisgLUdR1kQtx9D7VoHvnI4clHBijSMTgm0DjJrwhqTzbk08LWi47bDbFIDX1KXaF5e0LEp@2Kcv/Jcqoe@2C1zPNNOBb7KjUKnY/9ewZXScVDpcgvPsapTK9y0t@evGC0bH2DZN@xnElPizEQlAeTvAwNjYxUT1R/2ExUhU@fMxkdIXOLjqWB81S/@Hu8XssMGkYv0eM5d48PhSr85nDEeoaguFsR@AvLdAOwt1jLDuPwc3CEcwRAhYx0YafxjWfCGgR5S7Q16BgYk5L/iYgGi8qFkRzwAy7IDojH@10/hc) to check that the programs you are generating are correct.
If you'd like to generate some larger test cases, use [this script](https://tio.run/##ZY7BCoMwDIbvfYrcrK6Kw5uwV/AFRIa4qgFtSxsde/quo/W0QEj48@VPzIdWrRrvcTfaEjiyqBYBdlQvvbMOHnCvGSpzkAv9ho54ZKrRTYjPTb@lnUYn@7YbcqYPSmg/sFlbOAEVxP2WQYiLuAXkHKBIp6pfCblIXgtocpZktx7zvEkeLf7k5JYzE34iXkRMQFaWmYDiGnv/BQ).
```
a b -- a b a
>r dup r> swap
a b -- b a b
swap >r dup r> swap
c a b -- b a b
swap >r swap drop dup r> swap
a b c -- c b a
swap >r swap r> swap
a b c -- b c a
>r swap r> swap
a b c d -- d a c
swap >r swap drop swap r>
a b c d -- d c b a
swap >r swap >r swap r> swap r> swap >r swap r>
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 42 bytes
```
{,//a,({(x#2;|!3;x#,3 0)}'x?y),2+a,2+a:~x}
```
[Try it online!](https://ngn.bitbucket.io/k#eJxLs6rW0ddP1NGo1qhQNrKuUTS2rlDWMVYw0KxVr7Cv1NQx0k4EYau6ilouLsMEAyulmLyYPCUdJQUlfQ0luyIla6WU0gIgWWQHJIrLE0HslKL8AiXNtGilxCQgLzEpUSnWmmTNhgpGCsYKJtYmCiYKhkCWcaw1AJz0LNg=)
[Verify the test cases!](https://tio.run/##lVQ9j9swDN31K1hPDmAHaLsFSIAO1w4dbrl2CTLobLonnCsJtIzcoehvT6kP24lrFz3HsD4oPpKPT7Gv7snoj5dLjQ3gC1a9w7xzsnouoDI1bnYC@Ak7sI/jcXcKmzTsHuO6MQRnQzUoHXy3nW2VyxOEf1QTD@z3kNVkbDaZxihba2y@GfexvXHql32ktajrmPixfH9a8@/OchHA@xTD9MNprJTnxXRiBfRAM0j6O6lY1VpadPhXVbSC0OEsrFQdwnfZ9nhHZChvsm/6WZuzDpF28MsPv7OIIbsOyY1N9F0s0ip2F11POmYihJeHw85VssMcmwYrdyOQR@TuYwGycUhM309puXCKEiggeiRBZGWZpUIcvU41mN6x5yDCATEECWfwpULrpvOWlGa0B04LGqlarHfZEGriKbAikvp8iHf7mOVbgdKpL8Z5KyPNYsCnwKgyOrAfOfuBrlUah0vg51yj0rZ3SeTnJw4YDFsmTHGPgySuBLHglJrjLUKMJEaoB@qvhBGrYPcxk9HkmV00LDdaRP7h7v5zKDDGsKwjIRI391@zzeUi4RHKEvwgxYGAXzoAX900mxb@Oi6a@b8hfITwKBXUHrDmn@RFlUBH6PGdwc7Htx29yWjd47/t13VNnz8)
Takes the input as two lists of positive integers (or chars). Returns a list of integers, where `0 1 2 3 4` is mapped to `>r dup r> swap drop` respectively.
### How it works
This uses a simple, highly systematic approach. First, all items are moved to the return stack. Then the return stack is used like a "variable stack", so each requested item is fetched in order, preserving the return stack after each fetch. Finally, the return stack is cleared.
Using `( a b -- a b a )` as an example:
```
>r >r Move a and b to the return stack
a is the top (zeroth) item on the R-stack, b is the next one
r> dup >r Fetch a
r> r> dup >r swap >r Fetch b
r> dup >r Fetch a
r> r> drop drop Clear the return stack
```
In general, in order to fecth n-th item (0-based), the following sequence is used:
```
n+1 copies of r> Move n+1 items from return stack to main stack
dup >r Copy nth item and move one copy back to return stack
n copies of (swap >r) Move the unneeded items to return stack
```
[Answer]
# [Julia 0.7](http://julialang.org/), 188 bytes
```
b>a=push!(a,pop!(b))
a\b=for i=1:-1%UInt,j=Iterators.product(fill(1:5,i)...)
try
s=+a;r=[];z=[]
j.|>k->k<2?s>z:k<3?[s[end]]>s:k<4?(s>z;s>r;z>s;r>s):k<5?s>r:r>s
s==b&&return j
catch;end
end
```
[Try it online!](https://tio.run/##VVDBbqMwEL37K6aWWtkqIKVttBIU59wP2BPlYGx3a0INGpu2G@2/ZweURgkSfvPG82bGr58Hr38dOedgxo8PHWws2aYEi@PEHgjniT2WEL/0xJ5KUMi2JaBiJDh2StfTHN9vhM6mcboRnZRMv3b124jg602Zb25/v4SU9fVLcqjTiLGYcLSzSeLND4PYlNvMy6IoJEv4l8X6XldYN211oIP1xT@1z9X@@WEX1aHcPz/umti4YNtWRaJPO0H5KiqsDipWqKKk7JaKsSRC7eru7g5dmjFAz4xO5r0iOaP/6IIZrRNRQg1xGnwqxAoiZjzPuZQ03OeK1i9oV4wEnp5n3Sr7XGT96IP445IP1n0Xomn44hrPgJNrCyyuLahwOVHxts3gU1IMXDK22gQ@ADptBx9cFJIBfRP6kIZAA1eqs46mnRb21yWnfch1eX0h11dq6MBAngMF7JJQYC4T5vK@WxIrPRXrH9KtjQxc0bPOnEtPbcyZ2iVhl77/AQ "Julia 0.7 – Try It Online")
brute-force approach.
`b>a=push!(a,pop!(b))` is used a lot to shorten the code. `r` is the return stack, and `z` is a stack used for `swap` and `drop`
inputs are 2 lists of numbers, output is a list of number, where:
```
1: drop
2: dup
3: swap
4: >r
5: r>
```
last test case takes over 1 minute for TIO to compute
Bubbler's answer is probably smarter but let's say my program gives the shortest answer possible
[Answer]
# [Zsh](https://www.zsh.org/) `-e`, 86 bytes
```
echo $(for x<<<A
for y (`<i`)(<<<G\ A;for x;{<<<F;((x-y));<<<S\ A})|sort
for x<<<F\ X)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjWbSSbqpS7E07ZQVH25D8oNSS0qI8LmUFN1u3ovxcONfd1qW0ICczObEkFcgLtg0uTywAMiJsXYryC7jsMpeWlqTpWtwMS03OyFdQ0UjLL1KosLGxceQCsSoVNBJsMhM0NYAi7jEKjtZgaetqINfNWkOjQrdSU9MayAkGytVq1hTnF5VwwUxwi1GI0ISYvgBCrYxWMlTSUTJSil1qyGXEZQgRBQA)
It's hard to cut down on the `<<<` repetition.
Uses almost the same method as [Bubbler's answer](https://codegolf.stackexchange.com/a/233532), except it ends with `r> drop r> drop ...` instead of `r> r> ... drop drop ...`.
Names are integers. Expects the input stack on the command-line and the output stack in a file called `i`.
Output encoding:
```
A >r
F r>
G dup
S swap
X drop
```
The second line loops over the output stack and produces instructions to retrieve each item. The strange letter choices are to finagle the possible outputs into the right orders so that `sort` can arrange them correctly into the order of instructions Bubbler describes:
>
> To fetch the n'th item (0-indexed), the following sequence is used:
>
>
>
> ```
> n+1 copies of (r>) Move n+1 items from return stack to main stack
> (dup >r) Copy nth item and move one copy back to return stack
> n copies of (swap >r) Move the unneeded items to return stack
>
> ```
>
>
This saves over a `repeat` loop and finding the index using Zsh's builtin `${@[(i)$y]}` (which is quite a mouthful)
I use `((x-y))` to manually find the index of the item `y`. If `x` equals `y` then `x-y` is zero, the `(())` exits with a "failure" status code, and thanks to the `-e` option, that failure implicitly exits and breaks out of the loop, but only until the innermost layer of `()`. This is a much shorter than `break`.
`echo $()` collapses all newlines into spaces.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), (26?) 27 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
26 if the result need not be flat (while still consistent) - remove trailing `F`
```
iⱮ’“¡©“®¢‘xⱮj€12b4;,a"4,1ɗF
```
A dyadic Link that accepts the starting data stack in reverse on the left and the final data stack in reverse on the left and yields a list of integers:
```
0 >r
1 r>
2 swap
3 dup
4 drop
```
**[Try it online!](https://tio.run/##y0rNyan8/z/z0cZ1jxpmPmqYc2jhoZUgat2hRY8aZlQAxbMeNa0xNEoysdZJVDLRMTw53e3/4eUPd3cDVRXZAYni8sQCIJVSCiaL8kGUXdGjhrne//@nJCcl/k9MSk4BAA "Jelly – Try It Online")** (Footer formats like the question does.)
Or see the [Python suite of test results](https://tio.run/##vVRNj9MwEL37Vww5pVJSCbhVaiUOCwcOe1m4VD24zoS1NtiW46i7Qvz2Mv5I0naTwsKKKKo/5703byY1T@5eq/fHY4U14COKzmHeOi4eChC6wsWKAT1hB9Zx3K52YdP2u9u4rrWFg7YVSBVil61ppMsThH9kHS@s15BVVptsPBpYlkabfDHsY3MW1E3HcGNQVVH4tny7m4tvD3wSwMcU/fTdbsiU5sV4YwZ0Yy8g7XNRMas5WXZzLSs7g9DiBS2XLcJX3nR4Y622eZ19UQ9KH1RgWsEPP/zMIgZvW7RuKKKvYpFWsbroOquiEsZ8ezhsneAt5ljXKNxZg@yRqo8F8NqhJfu@c0OJ29gCBcSI1BBZWWYpEWefxhx05yiyb8IeMZCEO/go0LjxvrFSEdodyYKaywarVdZTjT4FV1jqPk/xZh1VvhQo3fqknT8lpAsO@BAclVoF96Nn39A1UmH/Efg55SiV6Vxq8sM9EYaDJRkmqcahJU4aYiIoFcefMDaYGKHubHfSGDELCh@UDEfe2cmD6UKz6D/c3H4MCUYOQ33EWPLm9nO2OB457KEswQ@cbSzYDfjvDujjBVqGedxOO9fv0P9E/KFFeBlLDHvPwf4IJO5MYQn4d7QJecJDit6CE7gZ2BN4el@H3g9/Rf@yukzSV15ARZaK6y0QaSYE/kboueBZV65pO63OKwj4P2U@S4jeXw "Python 3 – Try It Online").
### How?
This builds the reverse of the final data stack in the return stack one item at a time by "copying" the item from the data stack, leaving the data stack unaffected, then it drops all of the original items from the data stack and pulls all the copied items back.
To "copy" an item it pushes all those above it, then repeatedly pulls and swaps so that all the original main items are back on the data stack with the required item on top, then duplicates and pushes and then performs the conjugate of everything before the duplication to get main back to how it started.
For example, to push `d` from `abcd...` (where `a` is on top):
```
>r >r >r r> swap r> swap r> swap dup >r swap >r swap >r swap >r r> r> r>
```
...or
```
(>r)*3 (r> swap)*3 (dup >r) (swap >r)*3 (r>)*3
```
Where `3` is three because there are three items on top of `d`.
##### Code breakdown
```
iⱮ’“¡©“®¢‘xⱮj€12b4;,a"4,1ɗF - Link: starting (reversed); final (reversed)
Ɱ - map with:
i - first index of (final item) in (starting items)
’ - decrement -> 0-based indices
“¡©“®¢‘ - code-page indices = [[0,6],[8,1]]
Ɱ - map with:
x - times - e.g. 3 -> [[0,0,0,6,6,6],[8,8,8,1,1,1]]
j€12 - join each with twelves
b4 - convert from base four
0->[0]; 6->[1,2]; 12->[3,0]; 8->[2,0]; 1->[1]
ɗ - last three links as a dyad - f(starting, final):
, - pair -> [starting, final] e.g. ["abc","ba"]
4,1 - [4,1] [4,1]
" - zip with:
a - logical AND [[4,4,4],[1,1]]
; - concatenate
F - flatten
```
] |
[Question]
[
*Blokus* is a board game in which players take turns placing pieces on a \$ n \times n \$ square grid. In this version of the game, there will be just one person playing. The person is given \$ 21 \$ unique [polyominoes](https://en.wikipedia.org/wiki/Polyomino), ranging from \$ 1 \$ to \$ 5 \$ tiles each. They then proceed to place down a subset of the pieces onto the board. After the pieces have been placed, it is your job to determine whether it could be a valid *Blokus* board.
[](https://i.stack.imgur.com/zb6uA.png)
There are \$ 3 \$ key rules for placing down pieces, which must be followed:
\$ 1. \$ The first piece being placed must touch one of the four corners of the board
\$ 2. \$ After the first piece, each subsequent piece must *not* contain a tile that is adjacent to another piece in any of the four cardinal directions *(not including diagonals)*
\$ 3. \$ After the first piece, each subsequent piece must contain at least one tile that is diagonally adjacent to another piece, *(that is, all pieces should form a single connected component which are connected only by corners touching)*
## Task
The task is to determine, given an \$ n \times n \$ square grid, whether it could be a valid *Blokus* board. A *Blokus* board is considered valid if it obeys the \$ 3 \$ rules given above.
In addition, you can assume that the board will consist only of the \$ 21 \$ valid *Blokus* pieces. However, you may *not* assume that there are no duplicates. A board which contains a duplicate is automatically considered invalid.
### Very Important
You may notice that sometimes a single board can have multiple orientations of the pieces. For example,
```
...
.XX
XXX
```
might be a single `P` piece, but it could also be a `V3` piece directly adjacent to a `2` piece, among other things. If this is ever the case, you should output a Truthy value if *any* of these orientations match. So in the above example, it would return *true*, because while it could be a `V3` and a `2` piece, which breaks Rule 2, it could also be a single `P` piece, making it a valid board.
## Clarifications
* The board will be inputted as a grid of two distinct values, denoting whether a given tile is occupied by a [polyomino](https://en.wikipedia.org/wiki/Polyomino)
* The input can be taken in any reasonable format *(e.g. 2D array, flattened string, list of coordinates + dimensions)*
* The pieces can be rotated or reflected before placing on to the board
* Not all the pieces are required to be placed down to be considered a valid position
## Test Cases
### Truthy
```
('X' for occupied, '.' for unoccupied)
.X.
.XX
X..
XX.X
XXX.
...X
..XX
.....
.....
.....
.....
.....
......
......
......
......
......
X.....
X....XXX.
X..XX.X..
X..XX..X.
X.....XXX
X.XX.X.X.
.X.XX....
.X..X.XXX
.X.X.X...
.X.XXX...
```
### Falsey
```
('X' for occupied, '.' for unoccupied)
Invalid configuration, there is no such piece, unless two pieces are joined to
look as one (e.g. 'L4' piece is directly adjacent to '2' piece), which would
break Rule 2.
XXX
X.X
X..
Invalid, since a valid board can contain no duplicates.
X....
X....
X....
X....
.XXXX
Invalid configuration. Even though the pieces are all valid, it doesn't start in
one of the four corners, which breaks Rule 1.
.....
..X..
.XXX.
.X...
..X..
Invalid configuration. All pieces are valid and are not adjacent horizontally
or vertically, however they are disjoint (they do not form a single chain, which
breaks Rule 3).
X...XX
X.X.XX
X.X..X
..XXX.
.....X
X..XXX
Invalid configuration. The two components are disjoint.
.XX..
X....
X.X..
X..XX
X..XX
Invalid configuration. It breaks Rule 1, 2, and 3 (board may be portrayed as an
'L4' piece at the bottom, and an 'O' and a '2' piece at the top).
.....
.XXXX
...XX
.X...
.XXX.
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins!
[Answer]
# [Python 2](https://docs.python.org/2/), ~~446~~ ~~422~~ ~~385~~ 384 bytes
-1 byte thanks to @ovs
```
l=len
A=abs
s="""def v(O,N):
def c():
qp:
qp:
if(i!=j)*any(A(t-T)==1qiqj):i+=j;p.remove(j);c();return
p=[[a]qO];c();r=C=p[:1];i=[sum(A(b-a)*A(c-b)qPqPqP)qp];N-=1
qC:
if l(o)>5:r=0
qp:C+=[P]*(1-all(A(a-b)-2**0.5qoqP)-(P in C))
print(l(p)-l(C)+l(i)-l(set(i))==0)*any(k in Oq[0,N*1j,N+N*1j,N])*r,p>[]"""
exec eval("s"+".replace('q',' for %s in ',1)"*14%tuple("ijtTaabcPoPabk"))
```
The output format is a bit strange: it prints more than 7 characters for truthy output, and 7 or fewer characters for falsey output (7 characters is the length of `"[] True"`. This may be stretching it, so the `p>[]` can be replaced by `if p!=[] else 1` for +11 characters to give more traditional truthy/falsey output.
The input is a list of coordinates given as complex numbers, along with the dimension `n`.
[Try it online!](https://tio.run/##JVDNauMwGDxXT6FVKPk@/xFl24uNCsH3xIceAsYH2ZWpXNWWbCVsnz4r1whmRoIZZmR//Oc0Hh8PI4wayUnIdiGLYIx9qJ7e4ZKcMSd0vXSwKmdz8vQLT7oH/UcMGMnxB07g03cUgjvtBsx1LIbCZrP6nu4KBiyCu5iVv80joVbUtWzcpdleRSlsnfOm0KJebt8hqk0lRifo0hZdtR50tinOqeDElaEE1T01MOHbaz6Lw2@pMhZ11UTAU2lMiJDBm56Ax3xAN4WEFCqqR1oihgKzHj0YsJgaKDE2oFe1KB9EGHHYNn2thourD8k54kNyjjdqMJoT@1Y34ZeI@qc6qu7SAFtYzMJia2SnYO/2yZ7200yflzVmn3BkEX959jdrFDA9@Hcp266aKtl@McTHjvpPRXs9L556FaCTi8rJLrtmK1zJ7pplhNyhDqsOAyZ0Wxf4uPFxaBL6Fx//AQ "Python 2 – Try It Online")
[All testcases](https://tio.run/##fVNLb@MgED6XX8EiVQHHRnG1vSSiUpR7kkMPSK4PxCVaXIzxI9ntr8/ysJX2sCtLzPP7mBnG9nP81Zqn200zLQ3YMnEawMAQQu/yDK/4kO7JGkBvVNhrnV2Dh3A8qDNWP1hNEmE@8RaP2SthLO9UV5O1WrJ6Y2kvm/YqcU02Dr3p5XjpDYCWFYUou0MZvWzHbLHOy41ixXBpHNUpEyTZ4io7ke7oP9LZcrPPWA66nSsCqjPUuCUvz@uerUJRuyUrjmWC80xo7SiEw2ZPSbKiz13rCDJ8hMrAHSHu/l6ZEWtsSabxjiw1Vl4b5OgU18MqtvThAYeuWKX7JK/T/TKKkiR9al@K0g0JyD@ygvIqNEYDWiLXsNWiknjRLdIFPLc9fBw8zSLNCUryn4/jxWqJkarHVyFO1bE9itMHIuRWiUGGwVNOAeUccEoB4Jw6jXsXdRr1Aa9S@s8zCvpfwafUIAM995JyOmuUz1k81BKCobIQpUELBg8@b01RHqkjbGrjfuu302d/aYhPrkg@e0JuZJvFNAo@NcRj0XemQBtRc2Eu2Q93sFqNGL2ZN4MIAP6F/OT9G4UX8NsFYQMZLArJGOIovGJI6NvfZbCcMgPuhIiUAdtW1cUq@e4pqqVyOxMwKp1Q0lwa2YtR4oaESJVKLRtpxu9Rl078ok/BSG4cq/tRHTSYVzzflkITXWG5b38B "Python 2 – Try It Online")
The invariant may be the most interesting part. Since it must be conserved on rotations and reflections, distance between corresponding tiles is just about the only thing that stays constant. Also, I could not rely on the order that the tiles are listed in the piece. Using the product/sum of distances between every tile led to collisions, but using triples of tiles worked well.
I used `for _ in` fourteen times (wow), so the `exec`/`eval` saves 37 bytes.
Ungolfed:
```
def invariant(piece):
inv=1
for a in piece:
for b in piece:
for c in piece:
inv+=abs((b-a)*(c-b))
return inv
def valid(occupied,n):
# convert list of rows into coordinates of Xs
if not len(occupied):
return True
# generate list of pieces (this takes care of rule #2)
pieces = [[a] for a in occupied]
def consolidate():
for i in pieces:
for j in pieces:
# merge two pieces if they share an edge
if i!=j and any(abs(tile1-tile2)==1 for tile1 in i for tile2 in j):
i += j
pieces.remove(j)
# this repeats consolidate until no change (nothing left to combine)
consolidate()
return
consolidate()
# get a connected component of pieces (for rule #3)
connected = [pieces[0]]
for connected_piece in connected:
# eventually every piece should be connected if the board is otherwise valid, so
# we can check for valid-size pieces in this outer loop
# all polyominoes with at most 5 tiles are valid
if len(connected_piece) > 5:
return False
for piece in pieces:
if any(abs(a-b)==abs(1+1j) for a in connected_piece for b in piece) and piece not in connected:
connected += [piece]
# check that all pieces are only used once
ids = [invariant(piece) for piece in pieces]
used_once = len(ids) == len(set(ids))
nm = n-1
rule_1_met = any(k in occupied for k in [0, nm*1j, nm+nm*1j, nm])
return used_once and rule_1_met and len(pieces) == len(connected)
```
[Answer]
# JavaScript (ES7), ~~344 330 328~~ 326 bytes
Takes a binary matrix as input. Returns **0** or **1**.
```
m=>[-1,C=E=I=0,1,2,1,4].map(Z=t=>(m=m.sort(_=>t-3).map((r,y)=>r.map((_,x)=>m[x][y])),C|=!!m[0][0],g=(X,Y)=>m.map((r,y)=>r.map((v,x)=>(q=(x-X)**2+(y-Y)**2,t&1?v>0:v<0)?~t?1/X?q-1||g(x,y,S.push(x-H,y-V),r[x]=t?-v:I,n++):E|=Z[g(H=x,V=y,K=r[x]=t?-v:++I,S=[d=n=1]),S]-(Z[S]=K*K)|n>5|v==1:q<3|!I&&g(x,y,r[x]=-1,I=1):0)))())|I<2|C&!E
```
[Try it online!](https://tio.run/##pVNdb6pAEH33V9QX3ZXB7tr2hTjwYGxKfPSmsW5JY/ph742AAiWQkPvXvQvEiwsYa5pAsnNmzpnds7N/VvEqfA1@byPd89/e9x@4d9EUOocJTtFGBhxG8r91hu5qS5YYoUlcdIehH0TkBc1Iv6FFigSQUjSDMniBRAauSByROpTCJMNu1xXMkR@skSzgKc@3MOOCSXZIEn1BB4ORRlL9KV9A1ONWbDIjHjNq/Y0sfr2wdjrPsjVJIIX5cPsVfkraA6T6I4VAdsfI0mPDBk/TqDHNcCnW5AETeMQUZlhVaJoNcxRv6CF3KMwdnSzF3MHZYEYzz7zLYkRu7MY3Wdfu9cp@BVs6ZSOnBqOUEkozezzKJr3udP/qe6G/eR9u/DXpi1/BV/SZOn3aOcY/iOhcXYncZGnLYcnLpcQk2pHutXF4zqlK@bEEqzLFUganZMpipnIvDs@qNyg/ADicb1zVKNbw/1BheRvM6tVHMhVcSSg3V4kwFa6SXK0@pBsi/PiEyhH7z564X23CU9NU3@r3pqnd4u@Eh/1eNGS8ya8Z1ig@t/faBbUA9VdRfzOsZtelx@LqDSubarnosv9pdd6cUSVsm@B6mKvv/wE "JavaScript (Node.js) – Try It Online")
## How?
### About the 2nd rule
The 2nd rule is implicitly enforced if we:
1. Assume that adjacent tiles always belong to the same piece.
2. Make sure that all pieces are made of at most 5 tiles.
3. Make sure that there are no duplicate pieces (either rotated or reflected).
### Main algorithm
Our algorithm works with 6 iterations.
The pieces are identified by flood-filling the occupied tiles of the grid.
During the first iteration, we look for the first occupied tile as a starting point and flood-fill in all directions (including diagonals) with \$-1\$. If a piece is not connected to the other ones, it will still be filled with \$1\$'s after this process, as the secluded red tile in the example below.
During the second iteration, each piece is renumbered with a distinct ID, starting at \$2\$.
*Example:*
*(ignoring the transformations that are described in the next paragraph)*
$$\begin{pmatrix}
1&1&0&1\\
1&1&1&0\\
0&0&0&1\\
\color{red}1&0&1&1
\end{pmatrix}\rightarrow
\begin{pmatrix}
-1&-1&0&-1\\
-1&-1&-1&0\\
0&0&0&-1\\
\color{red}1&0&-1&-1
\end{pmatrix}\rightarrow
\begin{pmatrix}
2&2&0&3\\
2&2&2&0\\
0&0&0&4\\
\color{red}1&0&4&4
\end{pmatrix}
$$
During the next iterations, only the sign of the IDs is changed.
### Transformations
At each iteration, the matrix is either rotated or reflected in such a way that 2 duplicate pieces are guaranteed to eventually appear with the same shape at some point.
[](https://i.stack.imgur.com/weVE0.png)
For each piece, we build a shape key consisting of a flatten list \$S\$ of \$(dx,dy)\$ values. It describes the positions of the tiles, using the top-left one as the origin. The keys are stored in the object \$Z\$.
There is a duplicate if we encounter the same key at any iteration for two distinct piece IDs.
### Flags and final result
The flag \$E\$ (for error) is set if:
* a duplicate is found
* or a piece is made of more than 5 tiles
* or there's at least one tile which is still marked as \$1\$, meaning that a piece is not connected to the other ones
At each iteration, we test whether the tile at \$(0,0)\$ is occupied and set the flag \$C\$ (for corner) if it is. Because all rotations are tried, it is guaranteed to be set if there's at least one piece in any corner.
Because an empty board is valid although it has no corner, we also need the variable \$I\$, which is the number of pieces + 1.
The final result is given by:
$$(I<2)\text{ or }\big(C\text{ and }(\operatorname{not} E)\big)$$
[Answer]
# [J](http://jsoftware.com/), ~~134~~ 130 bytes
Takes the dimensions and a list of points. I'm not sure if this is the best approach, but it is shorter then a quick matrix attempt.
```
(((140*/@:>#"1)*[-:~.)@((5 2$0 0,i:1)&n)*2>[:#(,/,"0/~i:1)&n=.]/:~@,@:(-/~)/.~[:+./"2@#~^:_]e./"2+"1/~)@[*(+/@e.~0,3 2$0,<:)+0=#@[
```
[Try it online!](https://tio.run/##lVFRS8MwEH7vrwhtaZM2u6RVXzI7AoJPPvl0UOYY0uFEprj5NMhfr03SiLJNZyC5y913Xz6@PPcx5CvSKJITTiRRw54Aubm/u@0ppdWlLIRWsySuWNFOlAGmKb0idSqJ5GtVsWzDinrWqoRywWMpjC82MBfKaK4VnQjDBJhWlSDiWifmQS3mnc3LuBp6ui1oKXQHRvILy8yvFStlk@i2Z/3u/aNrgNAc86yZwqJmXmUECMPGCAEiFo0wG6bmEIwIAxLtCAwZ2ME/h8Cuk@d54/BrwDOpHM7JRxsBIWSAgQWdF67pnHFdcJm7oKvZ29hF//Rq@bI97vDIODoccC6eFHnktE/hOQTBGhyHvPZQOSAgxyV40SGMn42j5eht@48cp97zBvMsHYveXteb3XZgSMmUpIlqk4yvQafhM32fdMvHJ/exXy9@b7haFNG9IqtsRvbAhtOhf5Yc7hM "J – Try It Online")
### How it works
We check five things:
1. empty list OR all of …
2. corner is in the points
3. all points are connected to each other via 8 directions
4. all groups that are connected to each other via 4 directions have max length of 5
5. the groups of 4 are unique
Most components and the combination of them can probably be golfed further. The most interesting part will be the uniqueness check: it calculates all differences between points and sorts them, flattened down. So `1 2, 2 2 -> 1 0, _1 0 -> _1 0 0 1`. Not sure if this would be enough for all polyominoes, but for up to length 5 it seems to work.
A rough ungolfed version looks like this:
```
points=. 4 2 $ 0 1 , 1 1 , 1 2 , 2 0 NB. input
dims=. 3 3 NB. input
empty=. 0=# points NB. 1
corner=. points (+/@e.~0,3 2$0,<:) dims NB. 2
dir8=. ,/,"0/~i:1 NB. the 4 directions
dir4=. 5 2$0 0,i:1 NB. the 8 directions
borders=. ]e./"2+"1/~ NB. connection matrix: 1 iff. a borders b
expand=. +./"2@#~^:_ NB. repeat in the matrix:
if a<->b and b<->c then a<->c
group=. ] <./~ expand@borders NB. partitions points to groups
based on connection matrix
con8=. (2>[:#dir8&group) points NB. 3
con4=. ([:*/6>#&>) (dir4 group points) NB. 4
forms=. (/:~@,@:(-/~)&>) (dir4 group points)
unique=. (-:~.) forms NB. 5
f=. empty + corner * con4 * con8 * unique
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~231~~ 213 bytes
```
WS⊞υιυ≔⟦⟧ζ≔⟦⟧θ≔⟦⁰⊖Lυ⟧ηFηFηF⁼X§§υικ⊞θ⟦ικ⟧Wθ«≔…θ¹θFθ«J⊟κ⊟κ¿⁼XKK«↓#F⁴«M✳⊕⊗λ⊞θ⟦ⅉⅈ⟧»»»≔Φ⪪⭆KA⁼#κLυΣκθUMθ✂κ⌊Eθ⌕μ1⊕⌈Eθ⊟⌕Aμ1≔⟦⟧ηF⁴«⊞ηθ≔⮌θθ⊞ηθ≔E§θ⁰⭆θ§νμθ»⊞ζ⌊ηUMKA⎇⁼#κ*κ≔⟦⟧θF⌕AKAX«J﹪κLυ÷κLυ¿№KM*⊞θ⟦ⅉⅈ⟧»»¿№KAX⎚«⎚¬⊙ζ∨⊖№ζι‹⁵Σ⪫ιω
```
[Try it online!](https://tio.run/##bVPBjtowED0nX2Gxl3GVol2pvbQnBF2JVdOisodUKw5pmCUWjg1OAgsV386O7SQkVSOBxzNvxm@ex1memkyn8no95kIig7na1dWyMkJtgHO2qMsc6ogJ/jVckLOCmqxJWYqNgpdVxM7D7b63vY/YDDODBaoK1/Ad1aaiYpwTLifcqzYMcs4G67d9ncoSRskoYpNqrtb4Bu3qeERsy1ti@4i9CHKsqFrDf8/Z3zBoKExPmcRprncW@cA9vcCd43HBU13snjUsCLKluF8tKBCvQzILxC3Yk21a4LX4MtNHFbHR3cil@MqfGkgQ6wPCTBjMKqEVKXvTYqbrP5JWSQV9atA19BuISAJ85QOX0P0uXVOPQlZoYLmTogJ/U3G6A8tvIqVNbmnfjZxYEbtJH7FlXYBzOi0oc6qLIlVre/ZSigxhG7FYKFEQ0BYm/6OgeEGNPoy4Te23EqdvfahV0MItlS6j6bI3J3l3EY1crv28YdUif@EBTYl0WW3gvzB7dDsjROHedtnpsr/NEV1VwbvWSVFX7XxrN@f/aNIT9RmNSs0JhuJShx@8ysP@boPWitErRfPEB@MX63UttRW@f1NzVc3EQaxxGOimc6prmkFbN9baIHgy/bcxGKVLeAmHaQM6U4mpAQKiLNGS6xzNsP/QFUzUyer100D/ZfuKZ/s63bCVJXz2g/akhQJ6ocduCC7XazKmL0mScZjYdUz/jTX2Ph8mywXJN3YmfdZym8T57K6JOuv68SDfAQ "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for valid, nothing if invalid. Explanation:
```
WS⊞υιυ
```
Copy the board to the canvas.
```
≔⟦⟧ζ
```
Start with no pieces discovered.
```
≔⟦⟧θ
```
Start with no connected squares to check.
```
≔⟦⁰⊖Lυ⟧ηFηFη
```
Check the corners.
```
F⁼X§§υικ
```
If there is a piece in this corner, then...
```
⊞θ⟦ικ⟧
```
add that to the list of connected squares.
```
Wθ«
```
Repeat while there is at least one connected square.
```
≔…θ¹θ
```
Take the first square.
```
Fθ«J⊟κ⊟κ¿⁼XKK«↓#F⁴«M✳⊕⊗λ⊞θ⟦ⅉⅈ⟧»»»
```
Perform a flood fill to complete this piece.
```
≔Φ⪪⭆KA⁼#κLυΣκθUMθ✂κ⌊Eθ⌕μ1⊕⌈Eθ⊟⌕Aμ1
```
Represent the piece as a binary matrix (using strings of `0`s and `1`s originally because Charcoal apparently can't reverse a binary array but it turns out that strings allow me to save another byte anyway) and extract the minimum enclosing rectangle.
```
≔⟦⟧ηF⁴«⊞ηθ≔⮌θθ⊞ηθ≔E§θ⁰⭆θ§νμθ»
```
Generate all the rotations and reflections of the piece.
```
⊞ζ⌊η
```
Add the minimum to the list of discovered pieces.
```
UMKA⎇⁼#κ*κ
```
Change the piece character from `#` to `*`.
```
F⌕AKAX«J﹪κLυ÷κLυ¿№KM*⊞θ⟦ⅉⅈ⟧»
```
Find all `X`s that are adjacent to a `*`.
```
»¿№KAX⎚
```
If there are any `X`s left then they were disconnected so just clear the canvas.
```
«⎚¬⊙ζ∨⊖№ζι‹⁵Σ⪫ιω
```
Output a `-` only if all the discovered pieces are unique and have no more than 5 tiles.
] |
[Question]
[
Given a sequence of base-10 digits, output the longest list of integers that contains all the digits exactly once, in the order in which they appeared in the input, without repeating any integers.
# Examples
```
Input: 12345
Output: [1, 2, 3, 4, 5]
Input: 12123
Output: [1, 2, 12, 3]
Input: 10010
Output: [100, 1, 0]
Input: 35353
Output: [35, 3, 53] or [3, 5, 353]
Input: 988382
Output: [9, 88, 3, 8, 2]
```
# Rules
* Use any convenient formats for input and output
* You must support input sequences of up to 10,000 digits long.
* You must support integers of 18 decimal digits or more (This will fit in 64-bit integers, though you may want work with strings anyway)
* You may assume that the input given can be made into a sequences where the 18-digit number requirement is possible.
* If there is more than one possible longest sequence, you may output any one of them.
* Numbers in the output sequence may not be zero-padded.
* Zero is a valid element, but it can, of course, only be used once in the output.
* There is no time or complexity requirement.
* Shortest code wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
ŒṖḌD$ƑƇḌQƑƇLÞṪ
```
[Try it online!](https://tio.run/##y0rNyan8///opIc7pz3c0eOicmzisXYgIxBE@xye93Dnqv/WjxrmKOjaKTxqmGt9uN1bhcvlcPujpjWR//9HcxkaGZuY6gApIEOHy9gUCIE8AwMDUzAFRlyxAA "Jelly – Try It Online")
A monadic link taking a list of base-10 digits and returning a list of integers.
Added a byte (and switched to numbers) because of the zero padding issue.
Added 5 bytes to fix a further issue with zeros pointed out by @KevinCruijssen - thanks!
## Explanation
```
ŒṖ | Partitions of list
ḌD$ƑƇ | Keep only those invariant when converted to integers and back to lists of digits
Ḍ | Convert from lists of lists of lists of decimal digits to lists of lists of integers
QƑƇ | Keep only those invariant when uniquified
LÞ | Sort by ascending length
Ṫ | Tail
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 49 bytes
```
{m:ex/(0|<![0]>.+)+<!{$0>set ~<<$0}>/.max(+*[0])}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwvzrXKrVCX8OgxkYx2iDWTk9bU9tGsVrFwK44tUShzsZGxaDWTl8vN7FCQ1sLqECz9n9xYqVCjR5Qd1p@kYKlhYWxhZGOgqGRsYkpmAIiHQVjUyAEcg0MDA3@AwA "Perl 6 – Try It Online")
Outputs a regex match with a list of submatches as the integers.
### Explanation:
```
{ } # Anonymous code block
m:ex/ / # Match all
( )+ # Series of
0| # Zero or
<![0]>.+ # Numbers not starting with zero
<!{$0 }> # Where the series is not
>set ~<<$0 # Larger than the set of itself
.max(+*[0]) # Return the maximum by length of series
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
```
.œʒÙïJQ}éθ
```
[Try it online!](https://tio.run/##yy9OTMpM/f9f7@jkU5MOzzy83iuw9vDKczv@/zc0MAAjAA "05AB1E – Try It Online")
[Answer]
# JavaScript (ES6), 100 bytes
Takes input as a string.
```
f=([v,...a],p=o=[],c='')=>(v&&f(a,p,c+v),c?p.includes(c)|[+c]!=c||f(a,[...p,c],v):p[o.length]?o=p:o)
```
[Try it online!](https://tio.run/##bYzLDoMgFAX3/YtuCkRKfNTEmlA/hLAgV7Q2hEuqZeW/U7quObuZyXmZaFZ4L2G7ehxtSpOkKnIhhNE8SJRKc5CEMPmg8XKZqOGBQxEZhyGIxYP7jHalwHZVgD5L2Pdfo/JB7jSPrA8KhbN@3p56QBl6ZAnQr@iscDjTiZKqbm4tYez0x7M54E2bd9SXVVke8HvXNV2dRfoC "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f is a recursive function taking:
[v, // v = next digit
...a], // a[] = array of remaining digits
p = o = [], // p[] = current list, o[] = best list
c = '' // c = current pattern
) => ( //
v && // if v is defined:
f(a, p, c + v), // do a recursive call with c + v
c ? // if c is not empty:
p.includes(c) | // unless p[] already includes c
[+c] != c || // or c has leading zeros:
f(a, [...p, c], v) // do a recursive call with c appended to p[]
: // else:
p[o.length] ? o = p // update o[] to p[] if p[] is longer than o[]
: o // or just return o[] unchanged otherwise
) //
```
[Answer]
# [Perl 5](https://www.perl.org/), 119 bytes
```
sub f{($s=$_=shift)=~/\b(\d+)\b.*\b\1\b/?push@_,grep!/\b0\d/,map$s=~s/^((.*?,){$_}.*?),/$1/r,0..y/,//:return$s while@_}
```
[Try it online!](https://tio.run/##1ZDBbqMwEIbvPIWXtVQcRtiQItFkaam01731VrdWaUziVQLIBm2jKH317Bi67TOsOTD@/vn/Gei13eeXixtr0pwi6kqqSrczzcDKdy7rSG5iJutkIWuZyprf9aPbVQq2VvffUBdyw@Hw0qPx3fHnKEoWd8BOVJ2xYMBpyi2IJDly4Hxl9TDaljryZ2f2ulLny@g0edBuWK1@dVavg8ORVAPeSz@gospnP7p@bwb@CES2TzF/8ow4kG7xPVkAWCA/ft4/3N@ug6az0WRnp4DgORwjalqo9FvPSkxbf1BC9dtgX0oUcW2QMcCnVCGbB3JA/Ytvu2EWQgihiX53po18iQbG5jbjZnxFrsD3M/i6@h0gbC0JkzimJglXaMABpLwlXgwZMc3HYp9psU@B2OsQvnZjO6AlxGnnYNO1WvlvNe12HSjlf4FS5H85QZotr/MYqxQyWMI15IgQTiiDiQapEKmYiBCIRLDM8fEAX5Bjx01RLIsMyQ0UBeYUkM0ugb5UANqw/IfSCc7M513@Ag "Perl 5 – Try It Online")
```
sub f {
($s=$_=shift) #get next trial
=~ /\b(\d+)\b.*\b\1\b/ #duplicate exist in trial?
? push @_, #if so, add trials
grep !/\b0\d/, #without zero-leading
map $s=~s/^((.*?,){$_}.*?),/$1/r, #remove nth comma
0 .. y/,// #that many trials (-1)
: return $s #answer = 1st w.o. duplicate
while @_ #while trials left
}
```
Passes:
```
12345 → 1,2,3,4,5
12123 → 12,1,2,3
10010 → 100,1,0
35353 → 353,5,3
988382 → 9,88,3,8,2
1001000 → 10,0,1000
100100010 → 100,1000,1,0
```
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 24 bytes
```
PppPsu5cb{++pP==}f[:U_[~
```
[Try it online!](https://tio.run/##SyotykktLixN/f8/oKAgoLjUNDmpWlu7IMDWtjYt2io0Prru/39DI0MjYwA "Burlesque – Try It Online")
Not necessarily the best method, think I could probably save on some loading.
```
Pp #Save number (as str) for later use
pP #Load number
su #Find all substrings of number
5cb #Find all combinations of substrings of length 5 (as list of list of str)
{
++ #Concatenate all strings
pP #Load number
== #Is equal
}f[ #Filter for all substring combinations where
the concatenation is the same as original number
:U_ #Filter for all elements unique
[~ #Take the last one
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~115~~ ~~112~~ 114 bytes
Takes input as a string. A recursive function that takes a string and a list of previously-used numbers; it gets all substrings that start with the first character, and for each gets the result of the recursive call on the rest of the string. It then decides what the longest string that still matches is.
```
f=->s,*e{(1..l=s.size).map{|i|*q=x=s[0,i];q-e==[]||x=~/^0./?[]:q+f[s[i,l],*q+e]}.max_by{|i|s==i*''?i.size: 0}||[]}
```
[Try it online!](https://tio.run/##LcxRbsIwDAbg95wig0pAKSEp8AIyHCTKIhjpsFSgxUWUNdnVu4AmW/4tS59v98Oz7wuYbSlLXTdWQpRAgvDHTcR5X3UefVpDC6RlhmZTzxyANt638Dv/lGK@02ZdTwtNGrPSZGk9dSZE2drD84UJANPRaIfvn2sug/fahP5xwtLxb9cQ4zyx4ut0PVcfca/uDfHBMLF82BU6sSYMmLscGUMO/La/HMfK5VKIONVENFeL7J90GN4GX1eKrlf5YrliKo/JFqtYTEkZW/4B "Ruby – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 55 bytes
```
⊞υ⟦ωS⟧Fυ«≔⊟ιθFLθF∧I§θκ¬№ι…θκ⊞υ⁺ι⟦…θκ✂θκ⟧⊞ιθ»⊟Φυ⁼Lι⌈EυLλ
```
[Try it online!](https://tio.run/##XY69bsIwFIVn8hR3vFdyB2BkiiIqIZUqEiNisIJJrBo7ia8LVcWzGzspS892dH70NZ0cGydNjHXwHQYBx5uAne0DH3jUtkU60aa4uBEwEPwWi9J73VqsXY@aBAwpXUzxh7ItdzgQweRLe8ZKesaSd/as7jgI@KI0@XSMlQuWUQuofhqjqi69zXESvFBqE3zuHP@VBByMbtRsTpQJpomecR5Fnch5QnzXhtWYz7ZDkMa/KDP6Xt71NVxxL/tc@EsMzdrEuFwtV@v49m2e "Charcoal – Try It Online") Link is to verbose version of code. Outputs each integer preceded by a newline. Explanation:
```
⊞υ⟦ωS⟧Fυ«
```
Perform a breadth-first search starting from the input and having only seen the empty string before.
```
≔⊟ιθ
```
Temporarily separate the current suffix from the list of previously seen integers.
```
FLθ
```
Loop over the potential new suffixes. (The next integer is then the current suffix with the new suffix removed.)
```
F∧I§θκ¬№ι…θκ
```
Check that the new suffix does not begin with zero and the next integer has not already been seen.
```
⊞υ⁺ι⟦…θκ✂θκ⟧
```
If so then create a new entry including the next integer and the new suffix.
```
⊞ιθ»
```
Restore the suffix for the entry in case no suffixes were valid.
```
⊟Φυ⁼Lι⌈EυLλ
```
Print the last entry of those with the longest length.
[Answer]
# [PHP](https://php.net/), ~~380~~ ~~338~~ ~~287~~ 279 bytes
```
<?php $s=array_fill(0,$n=strlen($u=$argv[1]),0);$m=[];g:if(array_sum($s)==$n){$b=[];$p=0;$k=1;foreach($s as$c){$c&&($b[]=substr($u,$p,$c))[0]==0&&$c>1&&$k=0;$p+=$c;}if($k&&array_unique($b)==$b&&$b>$m)$m=$b;}for($i=0;;){if(++$s[$i]<=$n)goto g;$s[$i++]=0;$i==$n&&die(print_r($m));}
```
[Try it online!](https://tio.run/##JY7NbsQgDIRfJQcLgcgBeizr3QeJ0ArS/KD8UUgqVas8e2q6B/tgz8w3cYzXdXvEMVaQ0aXkfp99mGeualgx72nuVg4HgkvDT6OtqJUwsGBjzfAZev525GPhkAUirOIFvnwhojIwoTb9ljrXjiSoXIaWBC1jHHxjMR@eEJRfQ6zpJRplERVj0N417alkRInQmpNgMDH2Bh5r@D46CilMT0p/h0VQL/DmJCCHQFYjXuSSEnIDwd5Ku2Hbt2ow/xcpbckPpTZjX6HjMYV1f5J7EcKc13XpD6Vp1B8 "PHP – Try It Online")
## Ungolfed
```
<?php
$input= $argv[1];
$len=strlen($input);
$counts=array_fill(0,$len,0); // enumerator - basically a counter to base input-length, where each digit represents substring length
$max=0;
$max_sub=[];
do {
// add up size of all substring lengths
$size=0;
for($i=0;$i<$len;$i++) {
$size+=$counts[$i];
}
// size matches string length
if ($size==$len){
$subs=[];
$pos=0;
// get the substrings and ensure constraints
$ok=true;
for ($i=0;$i<$len;$i++) {
//exclude zero length substrings
if ($counts[$i]>0) {
$sub = $subs[] = substr($input, $pos, $counts[$i]);
if ($sub[0]=='0' && $counts[$i]>1) {
$ok=false;
break;
}
$pos+=$counts[$i];
}
}
// makes sure no repeated substrings
for($i=0;$i<count($subs);$i++){
for($j=0;$j<$i;$j++){
if($subs[$i]==$subs[$j]) {
$ok=false;
break(2);
}
}
}
// if all ok, then check this has maximal number of substrings
if ($ok) {
if (count($subs)>$max) {
$max=count($subs);
$max_sub=$subs;
}
}
}
// increment counter
for($i=0;$i<$len;$i++) {
$counts[$i]++;
if ($counts[$i]<=$len) {
break;
}
$counts[$i]=0;
}
// counter hasn't reached the end
} while ($i<$len);
echo json_encode($max_sub);
```
] |
[Question]
[
Inspired by [this lumosity mini game, Pinball Recall](https://www.lumosity.com/brain-games/pinball-recall)
We start with a rectangular grid (viewed from above) with several bumpers as follows. Entrances/exits are numbered counter-clockwise starting from the leftmost of the bottom of the grid, as number 0.
```
24 23 22 21 20 19 18 17 16 15
25 . . . . . / . . . . 14
26 . . . . . . . . . . 13
27 . / \ . . \ . . \ . 12
28 . . . . . . . . . . 11
29 . . . . . . / . . . 10
0 1 2 3 4 5 6 7 8 9
```
Pinballs can be fired from each entrance into the grid at a direction perpendicular to the grid wall, e.g. in the above example:
* 0 to 9: fired upwards
* 10 to 14: fired to the left
* 15 to 24: fired downwards
* 24 to 29: fired to the right
The pinballs will move in a straight line until they reach an exit, or a bumper, in which case the ball will bounce off the bumper and change direction. So in above diagram,
* from 0, ball goes straight to 24
* from 1, ball goes up to / and bounces off to reach \, then bounces off again and ends up at 2
* from 10, ball goes left to / and bounces off to 6
**Inputs**
Program shall receive the grid width and height.
Then program receives the bumper orientation (represented as / or \) followed by coordinates, which also start from 0 from bottom left, e.g.
```
4 . . . . . . . . . .
3 . . . . . . . . . .
2 . . . . . . . . . .
1 . . . . . . . . . .
0 . . . . . . . . . .
0 1 2 3 4 5 6 7 8 9
```
"done" keyword used to indicate end of input
*edit:* as suggested by ngn, program may receive list of bumper coordinates instead so the "done" keyword is not needed
**Output**
Program should print out the exit locations of a pinball if they are fired from 0 to the last entrance of grid, in above case, 0 to 29
**Sample input and output**
Input
```
10 5
/ 1 2 / 5 4 / 6 0 \ 2 2 \ 5 2 \ 8 2
done
```
Output
```
24 2 1 21 20 22 10 17 14 15 6 28 16 26 8 9 12 7 29 25 4 3 5 27 0 19 13 23 11 18
```
**Leaderboard (as of 20Oct2019)**
1. Neil, Charcoal, 133 bytes
2. Arnauld, JavaScript (ES6), 212 bytes
3. Embodiment of Ignorance, C# (Visual C# Interactive Compiler), 277 bytes
4. Chas Brown, Python 2, 290 bytes
*edit:* FryAmTheEggman points out a similar [question](https://codegolf.stackexchange.com/questions/37554/laser-mirror-portal-party) to try
[Answer]
# JavaScript (ES6), ~~218 215 213~~ 212 bytes
Takes input as `(w,h,o)` where \$o\$ is an object whose keys are the coordinates of the bumpers in `'x,y'` format and whose values are either `'/'` or `'\'`.
```
(w,h,o)=>(A=[...Array(w+h<<1)].map((_,n)=>(p=n-w)<0?[n,-1,3]:p<h?[w,p]:(p-=w)<h?[h+~p,h,1]:[-1,2*h+~p,2])).map(g=([x,y,d])=>A.every(([X,Y])=>X-x|Y-y&&++i,(c=o[[x+=~-d%2,y+=~-~-d%2]])?d^=c<{}||3:i=0)?g([x,y,d]):i)
```
[Try it online!](https://tio.run/##RY7hboIwEIBfhT@z13HtAOeyEDrCW2hqXQggYBxtcBGI6KszYGH7993dly93iq/xJalL880qnWbDUQzQYIGaig@IhOScR3Udd9DYRRC4VPGv2AB8YjUJRlSsoYETygqZi2vlm6AIZYNG@WCYGG/jWNgPMyZd5ctR8p7n2VOUzq1cgGyxw1SNxYhn16zuAOQWd9Niy9p@x7rVyrZLhERoKVtbPFj65GE3wYxK0TA9iCS43ft@7ZfCoWH@l/VLOiS6uuhzxs86hyO4DlobtG5kfIf45IWgRTb4uuAbOgt6s7Df/xr//L7wnfKTLisgFqF0@AE "JavaScript (Node.js) – Try It Online")
### Commented
We first create an array \$A[\:]\$ of tuples \$[x, y, d]\$ where \$(x, y)\$ is the starting position along the borders of the playfield and \$d\$ is the initial direction.
```
( A = [...Array(w + h << 1)] // create an array A[] of (w + h) * 2 items
.map((_, n) => // for each item at position n in A[]:
(p = n - w) < 0 ? // set p = n - w; if this is the bottom side:
[n, -1, 3] // start at (n, -1) in direction 3
: // else:
p < h ? // if this is the right side:
[w, p] // start at (w, p) in direction 0 (implicit)
: // else:
(p -= w) < h ? // subtract w from p; if this is the top side:
[h + ~p, h, 1] // start at (h + ~p, h) in direction 1
: // else (left side):
[-1, 2 * h + ~p, 2] // start at (-1, 2 * h + ~p) in direction 2
) // end of map()
) //
```
We then simulate the trajectory of the ball, starting at each position defined above, until it reaches another starting position.
```
.map(g = ([x, y, d]) => // for each tuple [x, y, d] in A[]:
A.every(([X, Y]) => // for each tuple [X, Y] in A[]:
X - x | Y - y // break if (x, y) = (X, Y)
&& ++i, // otherwise, increment i
( c = // define c as
o[[ // the bumper character at
x += ~-d % 2, // (x, y), once updated according to d
y += ~-~-d % 2 // (0 = West, 1 = South, 2 = East, 3 = North)
]] //
) ? // if c is set:
d ^= c < {} || 3 // XOR d with 1 (for '/') or 3 (for '\')
: // else:
i = 0 // initialize i to 0
) ? // end of every(); if truthy:
g([x, y, d]) // do a recursive call to move the ball further
: // else:
i // we've reached a starting position: yield i
) // end of map()
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~317~~ ~~300~~ ~~298~~ 290 bytes
```
def f(w,h,B):
A=[w*[-1]for c in' '*h];p=w+h
for x,y,c in B:A[y][x]=c<'0'
for i in range(2*p):
x,y,d=[[[(0,2*p+~i,0),(w+p+~i,h-1,1)][i<w+p],(w-1,i-w,3)][i<p],(i,0,2)][i<w]
while w>x>=0<=y<h:d^=1+A[y][x];x+=[1,0,0,-1][d];y+=[0,-1,1,0][d]
print[[y+w,2*p+~y][x<0],[w+p+~x,x][y<h]][0<d<3],
```
[Try it online!](https://tio.run/##TZBRb4IwFIWf5Vect6Jcs7aAolIT/Rtdlywig2RBYkwKL/vr7AKbW9Lc9Hz33JvTtv2jujV6GIpriTL0VNF5uQ9wMtav7Fq58nbHBXUjIFaVO7TGR1WAkXbU09jBeX@yvbOdM5dcSDF367Fzf28@rqFetbxyMfoLY60NJTGKvmqSSwp9NF2rtSK1dLbOGTjGrOu1p3hiI2E76dnhgoWv6s8r/LE7GpmbPq/2xZtR0U@SQxcZq3hAEr/BFu7QMxgFMR1BsGjvdfOwto/8HGcczKUjOyXqqHOW1zpnZV7ksaPhbGyoCJogXsSSEKaE5Ck2BPkUera9vv76/qnsT7kgKEMlKeVPD6Y8c4XQCTQUNB8JzVcJtYVKoFJsoDMorhtk2EFpbKF30CkSxEiht2A3N2LoGEpBZWL4Bg "Python 2 – Try It Online")
Takes the bumpers as a list of tuples `(x,y,c)`where `x` and `y` are the coordinates of the bumper and `c` is either `\` or `/`.
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 277 bytes
```
(w,h,d)=>{var z=new int[w+h<<1].Select((_,i)=>i<w?(i,-1,3):i<w+h?(w,i-w,0):(i-=w+w)<h?(h+~i,h,1):(-1,h+h+~i,2)).ToList();z.ForEach(x=>{var(a,b,c)=x;do{try{c^=d[(a,b)]<48?1:3;}catch{}a+=~-c%2;b+=(c-2)%2;}while(a>=0&a<w&b>=0&b<h);Print(z.FindIndex(l=>l.Item1==a&l.Item2==b));});}
```
[Try it online!](https://tio.run/##dVDRasJAEHzvV@Slukc2qYlaxNxFCm1B6EOhfVNbLpfIHdgEYuipIf56ulErfSnswsww7LCjtp7amvZBVabIuckr7PbRnLgs9xwuGkOlZRnHa9GCRY0pE3H9LUvnIPLMOuRYWFdzHqz8t2yTqQrgEw2ZDLczMOgFOGRTIq6e0QHjWRywKRhPWNcyTqJ2j4YOB6SSWbsnHjLmvxcvZlsBiw7@c1E@SaVhdw4HiQkqJnZRWtRVua/Vh0gXncpWfDSZBdNh1ChZKV030hVHT92GUeIKUF7ICDZWm00GMhaDnuS2l3Qg4ZpFryV9BBRo8nSep9kONiLe@PMq@wqEkL0zDIVIGIsamja6WUMwQGeMTlfI/xXWNQT0F/bv@g3WMMbRFd9TJ784PHmWy4vpD5lcCQW3Pw "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 133 bytes
```
NθNηUOθη.WS«JNNι»≔⟦⟧ζFθ⊞ζ⟦²ι±¹⟧Fη⊞ζ⟦⁰θι⟧Fθ⊞ζ⟦⁶⁻θ⊕ιη⟧Fη⊞ζ⟦⁴±¹⁻η⊕ι⟧Fζ«J§ι¹§ι²≔﹪⁺⁴§ι⁰¦⁸δM✳δW¬№ζ⟦δⅈⅉ⟧«≡KK/≦⁻⁶δ\≔﹪⁻χδ⁸δPωM✳δ»⊞υ⌕ζ⟦δⅈⅉ⟧»⎚Iυ
```
[Try it online!](https://tio.run/##bVJNb8IwDD2XX2FxcqVsFAQIjRNimsQ0GNJ22AQcShtItJJAm8DExG/v3A@movUQK47fc95zEgg/DrQfpelE7a2Z2d2ax3hwh41qLih/XUdabfHAQDBo3jfp6CRkxAFz5JuJJZVdF34azrPd7d81Vlu4DG5SojtzohiUtL00RkkitwoXKwZnOtjoGEgGzG0i8Mxg0WEgGcz41jcc2@7qihEVjMeA5MlVHb/PYCqVTTIDExXEfMeV4SHdTspEbbtu5b4rW/xj/1HPVesjM1Eh/0bSnJEraSe3Xtqd6tBGGucRte7ewLxM14BWmMGn@sjxUcY8MFIrDPMe5fhn2uBYW5pkJjpk8JEN@xNJWfEaTnKSJhCAc86/yhdyAj/h0Gw1H2jvTP19IeiFbwzmThn0y7tL6HJZYG@VF1Npexm2otcJ@ca3kSm600bu87c@5cULrVpHVMinbxk8SRXWGMq@yjjiPv2gYaP4P2M/MWiplKZtD3rQgjZ0KPagS7EPHiwp71Ds5XFAMb07Rr8 "Charcoal – Try It Online") Link is to verbose version of code. Takes input on separate lines with a blank trailing line but for convenience the test case uses spaces instead of newlines. Explanation:
```
NθNηUOθη.
```
Input the width and height and draw a box of `.`s of that size. I'm drawing with the origin at the top left but I'm flipping the vertical co-ordinate in all of my calculations so the results will be correct.
```
WS«JNNι»
```
Loop over the input list and print the `\` or `/` characters at the relevant positions.
```
≔⟦⟧ζFθ⊞ζ⟦²ι±¹⟧Fη⊞ζ⟦⁰θι⟧Fθ⊞ζ⟦⁶⁻θ⊕ιη⟧Fη⊞ζ⟦⁴±¹⁻η⊕ι⟧Fζ«
```
Build up a list for all of the entry/exit points giving the direction of exit and the coordinates and loop over the list.
```
J§ι¹§ι²≔﹪⁺⁴§ι⁰¦⁸δM✳δ
```
Jump to the exit point, calculate the direction of entry and take a step in that direction.
```
W¬№ζ⟦δⅈⅉ⟧«
```
Until an exit point is found...
```
≡KK/≦⁻⁶δ\≔﹪⁻χδ⁸δPω
```
... adjust the direction if the cursor is over a `/` or `\`...
```
M✳δ»
```
... and take a step in the current direction.
```
⊞υ⌕ζ⟦δⅈⅉ⟧
```
Remember the found exit point.
```
»⎚Iυ
```
Clear the grid and output the list of exit points.
] |
[Question]
[
I really like times that follow certain patterns. In particular, I like times where all the digits are the same, or all of the digits increase arithmetically by one from left to right. Further, I viscerally hate when people put letters in my times, so all of that AM/PM nonsense is dead to me. Thus, my favorite times are:
```
0000 0123 1111 1234 2222 2345
```
For my peace of mind, I need you to write me a single program that, given the current time as input, both: **(A)** if it is ***not*** now one of my favorite times, tells me both (i) how many minutes it's been since my last favorite time as well as (ii) how many minutes from now my next favorite time will occur; and **(B)** if it ***is*** now one of my favorite times, supplies a single 'signal value'.
### Input
Your program should accept (by whatever method: function argument, `stdin`, command line argument, etc.) the current time, in any of the following formats:
* A four-digit time as a string
* An integer that can be zero-padded on the left to make a four-digit time as a string
* A sequence of four (or fewer) integers, ordered such that the first integer in the sequence is the leftmost (significant) digit in the time input (e.g., `0951` could be validly represented as `[0, 9, 5, 1]` or `[9, 5, 1]`)
+ Representing `0000` as a zero-length sequence is acceptable
In the case of a string input, it should ***only*** contain digits, no colons or other punctuation. **Inputs can be assumed to always be valid 24-hour times:** `HHMM`, where `0 <= HH <= 23` and `0 <= MM <= 59`. Disregard the possibility of a leap second.
### Output
Your program must supply (function returns, `stdout`, etc. are all fine) either **(A)** or **(B)**, as appropriate to whether or not the input value is a target time.
**For (A):**
Supply two numeric values in any sensible format, such as:
* Single-string output with a suitable delimiter
* Sequential integer/string outputs, e.g., `bash` printing two lines to `stdout`:
```
49
34
```
* Length-two ordered return values, such as a Python list, a C array, etc.: `[49, 34]`
The values can come in either order. For example, both of the following would be valid outputs for an input of `1200`:
```
49 34
34 49
```
*The order and separator must be the same for all input values, however!*
**For (B):**
Produce any otherwise unattainable result. The *same* result must be produced for all six of the target times, however. Infinite loops are excluded.
### Sample Inputs/Outputs
`YAY!!!` is used here as a demonstrative example and is not prescriptive.
```
Input Output
------ --------
0000 YAY!!!
0020 20 63
0105 65 18
0122 82 1
0123 YAY!!!
0124 1 587
0852 449 139
1111 YAY!!!
1113 2 81
1200 49 34
1234 YAY!!!
1357 83 505
1759 325 263
1800 326 262
1801 327 261
2222 YAY!!!
2244 22 61
2345 YAY!!!
2351 6 9
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~34~~ ~~33~~ ~~32~~ ~~31~~ 28 bytes
*3 bytes thanks to Mr. Xcoder's `.ị` and `³` tricks.*
```
d³ḅ60;15j83,588ṁ5¤_\ṠÞAµ.ịxẠ
```
[Try it online!](https://tio.run/##y0rNyan8/z/l0OaHO1rNDKwNTbMsjHVMLSwe7mw0PbQkPubhzgWH5zke2qr3cHd3xcNdC/5HG@gYGegYGpjqGBoZAbExEJvoWJgC2UAAIkAiBgYgKRMdQ2NTcx1Dc1NLHUMLkJiFgaGOERAACRMTHaAKUyBhahh7dM/h9kdNa7IeNcypedQwVwXIdv8PAA "Jelly – Try It Online")
Some parts are exactly as in [Jonathan Allan's answer](https://codegolf.stackexchange.com/a/152279/30164), but I'm posting it as I think it is sufficiently different from it and independently written based on [my Pyth answer](https://codegolf.stackexchange.com/a/152282/30164) (and shorter :D). Should also have room for improvement.
Input is an integer, output is an array of previous and next times or the empty array for special times.
### Explanation
Using example input `1200`.
* `d³` converts the time to base 100, into hours and minutes: `[12,0]`.
* `ḅ60` converts from base 60 to get total minutes: `720`.
* `;15` pairs it with 15: `[720, 15]`.
* `83,588` creates the array `[83, 588]`.
* `ṁ5` makes it length 5: `[83, 588, 83, 588, 83]`.
* `¤` combines the two above actions. Just a technicality.
* `j` joins the pair with the array: `[720, 83, 588, 83, 588, 83, 15]`.
* `_\` subtracts each array value from the first and gets intermediate results: `[720, 637, 49, -34, -622, -705, -720]`.
* `ṠÞ` *stably* sorts these by signum: `[-34, -622, -705, -720, 720, 637, 49]`.
* `A` takes the absolute values: `[34, 622, 705, 720, 720, 637, 49]`.
* `µ` starts a new monadic chain. Again, a technicality.
* `.ị` takes the last and first items: `[49, 34]`.
* `×Ạ` repeats that once if there are no zeroes, or zero times otherwise: `[49, 34]`.
[Answer]
# JavaScript (ES6), ~~87~~ 83 bytes
*Saved 4 bytes thanks to @l4m2*
Takes input as a string. Returns either `0` or a 2-element array.
```
t=>[i=0,83,588,83,588,83,15].every(d=>(k=t-(t/25>>2)*40)>(j=i,i+=d))|i-k&&[k-j,i-k]
```
### Test cases
```
let f =
t=>[i=0,83,588,83,588,83,15].every(d=>(k=t-(t/25>>2)*40)>(j=i,i+=d))|i-k&&[k-j,i-k]
console.log(f('0000')) // YAY!!!
console.log(f('0020')) // 20 63
console.log(f('0105')) // 65 18
console.log(f('0122')) // 82 1
console.log(f('0123')) // YAY!!!
console.log(f('0124')) // 1 587
console.log(f('0852')) // 449 139
console.log(f('1111')) // YAY!!!
console.log(f('1113')) // 2 81
console.log(f('1200')) // 49 34
console.log(f('1234')) // YAY!!!
console.log(f('1357')) // 83 505
console.log(f('1759')) // 325 263
console.log(f('1800')) // 326 262
console.log(f('1801')) // 327 261
console.log(f('2222')) // YAY!!!
console.log(f('2244')) // 22 61
console.log(f('2345')) // YAY!!!
console.log(f('2351')) // 6 9
```
### How?
We do not care about the result of the `.every()` loop. Provided that the input is valid, it will *always* be falsy. What we're really interested in is *when* we exit this loop.
We exit as soon as we find a favorite time `i` (expressed in minutes) which is greater than or equal to the reference time `k` (the input time `t` converted in minutes). We then return `0` if `i == k` or the 2 delays otherwise.
[Answer]
# Befunge-93, ~~88~~ ~~85~~ ~~86~~ ~~80~~ 74 bytes
```
&:"d"/58**-:"S"-:"b"6*-:"S"v
@._v#!:<\-*53:-"S":-*6"b":-<
:$#<$$\^@.._\#`0
```
[Try it online!](http://befunge.tryitonline.net/#code=JjoiZCIvNTgqKi06IlMiLToiYiI2Ki06IlMidgpALl92IyE6PFwtKjUzOi0iUyI6LSo2ImIiOi08CjokIzwkJFxeQC4uX1wjYDA&input=MTc1OQ)
Outputs the number of minutes since the last favourite time, followed by the number of minutes until the next favourite time (separated by the two character sequence: space, hyphen). If it is already a favourite time, then a single zero is returned.
[Answer]
# C, 121 bytes
```
*p,l[]={0,83,671,754,1342,1425,1440};f(t){t=t%100+t/100*60;for(p=l;t>*p;++p);*p-t?printf("%d %d",t-p[-1],*p-t):puts("");}
```
Outputs a newline if the time is a favourite time.
[Try it online!](https://tio.run/##ZZDRboQgEEXf/QpiYiI6poCw2iVuP8T40GhtTLZbsjt9Mn67naGpSdN5OMDlchkYq/dx3PciwLUfulVBW8Op0dA4C7q2BrQ1jmDV5ucc5YodZlqpEp@IxUn5@fOeh@7q8VIEX5ZB@iJU@BLuyw3nPM0mkU0pYBX6Sg/Ae/IcvvCRp6n0204u8fG63HKZrImgYgHfHtgPohPUkNAgDA/KEYxh1AwLonW8pIqMqlLRYCGG/S1du4Z2G/dMbKOzVRxvONYYS5F01DEd6ZXefBJz@JHc2NIp/9PdMlx4XpaLjI71uO94ubLTWaTw65f@sNBP/tOOP4nKlmz7Nw)
[Answer]
# [Clean](https://clean.cs.ru.nl), 126 bytes
```
import StdEnv
f=[1440,1425,1342,754,671,83,0]
?t#t=t rem 100+t/100*60
=(\(a,b)=(t-hd b,last a-t))(span(\a=t<a||isMember t f)f)
```
Defines the function `?`, taking `Int` and returning `(Int, Int)`.
When the argument is a favourite time, it crashes the calling program with `hd of []`.
[Try it online!](https://tio.run/##Dc2xDoIwEADQna@4xKXVElso6mDDooOJTozqcEBREloNPU1M@Hary1tfM1j00T3a12DBYe9j756PkaCidu/fSWfOSmsplM4KoXKdiXWhxWqtxCYX8pqUNCNDMFoHSsoFLf/OVzIx7MJQ1NwwSu8t1GLAQIApcc7CEz27oKEtTlMfTtbVdgSCjnc8VoT/3UAJmYzfphvwFmJ6OMbdx6Prm/AD "Clean – Try It Online")
[Answer]
# Pyth, ~~48~~ ~~45~~ 42 bytes
```
&*FJ.u-NY+P*3,83 588 15isMcz2 60,eK._DJ_hK
```
[Try it online.](http://pyth.herokuapp.com/?code=%26*FJ.u-NY%2BP*3%2C83+588+15isMcz2+60%2CeK._DJ_hK&input=1200&test_suite_input=0000%0A0020%0A0105%0A0122%0A0123%0A0124%0A0852%0A1111%0A1113%0A1200%0A1234%0A1357%0A1759%0A1800%0A1801%0A2222%0A2244%0A2345%0A2351&debug=0) [Test suite.](http://pyth.herokuapp.com/?code=%26*FJ.u-NY%2BP*3%2C83+588+15isMcz2+60%2CeK._DJ_hK&input=1200&test_suite=1&test_suite_input=0000%0A0020%0A0105%0A0122%0A0123%0A0124%0A0852%0A1111%0A1113%0A1200%0A1234%0A1357%0A1759%0A1800%0A1801%0A2222%0A2244%0A2345%0A2351&debug=0)
The code takes in a time string and outputs the previous and next times as an array, or `0` if the time is special.
Interestingly, an imperative approach is also 42 bytes:
```
V+_isMcz2 60+P*3,83 588 15KZIg0=-ZNIZK)_ZB
```
### Explanation
* `cz2` splits input (`z`) into two-character pieces.
* `sM` evaluates them as integers.
* `i`…`60` parses the resulting two-item array as base 60.
* `,83 588` represents the array `[83, 588]`.
* `*3` triplicates that to `[83, 588, 83, 588, 83, 588]`.
* `P` removes the last `588`.
* `+`…`15` adds `15` to the end.
* `.u-NY` starts from the parsed number, subtracts each number in the array from it and returns the intermediate values. These are the differences from each special time.
* `J` assigns these differences to `J`.
* `*F` computes the product of the differences. This will be 0 if the time was special.
* `&` stops the evaluation here and returns 0 if the time was special.
* `._DJ` stable-sorts the differences by sign.
* `K` saves that array in `K`.
* `e` takes the last item in the array.
* `_hK` takes the first item in the array and negates it.
* `,` returns the two as an array.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~33 32~~ 34 [bytes](https://github.com/DennisMitchell/jelly/wiki/Cde-page)
~~+3~~ +2 bytes to fix up so all liked time outputs are equal.
gotta be a shorter way!
```
s2Ḍḅ60
83,588ṁ5“¡Ð‘j+\ṡ2>E¥ÞÇḢạÇa\
```
A monadic link taking a list of the four digits and returning a list containing two integers
- if it's a liked time the result both entries will be zeros.
**[Try it online!](https://tio.run/##AUsAtP9qZWxsef//czLhuIzhuIU2MAo4Myw1ODjhuYE14oCcwqHDkOKAmGorXOG5oTI@RcKlw57Dh@G4ouG6ocOHYVz///9bMiwzLDUsOV0 "Jelly – Try It Online")** or see the [test-suite](https://tio.run/##y0rNyan8/7/Y6OGOnoc7Ws0MuCyMdUwtLB7ubDR91DDn0MLDEx41zMjSjnm4c6GRneuhpYfnHW5/uGPRw10LD7cnxvw/uudw@6OmNUcnPdw5A0gDkfv//9HRBjpgGKsDZhlBWYZAtimUZaRjBGcZw1kmYJaFjilY1lAHDOEsYzDLCGoyWCdYB1AGqMMczDIHsizBLAu4OhALZIqRjhHUXhBtAtYLNgPsKiOwKYaxsQA "Jelly – Try It Online").
### How?
```
s2Ḍḅ60 - helper link, getMinuteOfDay: list of digits, D e.g. [1,2,3,3]
2 - literal two 2
s - split into chunks of length [[1,2],[3,3]]
Ḍ - un-decimal (convert from base 10) (vectorises) [12,33]
60 - literal sixty 60
ḅ - un-base (convert from base) 753
83,588ṁ5“¡Ð‘j+\ṡ2>E¥ÞÇḢạÇa\ - Link: list of digits e.g. [1,2,3,3]
83,588 - literal list of integers [83,588]
5 - literal five 5
ṁ - mould like (implicit range of) [83,588,83,588,83]
“¡Ð‘ - code-page index list [0,15]
j - join [0,83,588,83,588,83,15]
\ - cumulative reduce with:
+ - addition [0,83,671,754,1342,1425,1440]
2 - literal two 2
ṡ - overlapping slices of length [[0,83],[83,671],[671,754],[754,1342],[1342,1425],[1425,1440]]
Ç - last link (1) as a monad f(D) 753
Þ - sort by:
¥ - last two links as a dyad:
> - greater than? (vectorises) [0, 0] [ 0, 0] [ 0, 1] [ 1, 1] [ 1, 1] [ 1, 1]
E - equal? 1 1 0 1 1 1
- --> [[671,754],[0,83],[83,671],[754,1342],[1342,1425],[1425,1440]]
Ḣ - head [671,754]
Ç - last link (1) as a monad f(D) 753
ạ - absolute difference (vectorises) [ 82, 1]
\ - cumulative reduce with:
a - AND [ 82, 1]
- -- such that if "liked" then the [0,x] result becomes [0,0] so they are all equal
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 36 bytes
```
?↑2↑0Πṙ_1†aÖ±↔Ġ-::15t*3e588 83B60†d½
```
[Try it online!](https://tio.run/##yygtzv7/3/5R20QjIDY4t@Dhzpnxho8aFiQennZo46O2KUcW6FpZGZqWaBmnmlpYKFgYO5kZAKVTDu39//9/tKGOkY6BjkEsAA "Husk – Try It Online")
Thanks to [Zgarb](https://codegolf.stackexchange.com/users/32014/zgarb) for explaining me how ternaries work in chat. Trying to golf `↑0`, but I didn't get it to work otherwise for some reason (?). This is my first non-trivial Husk answer, and letting the aforementioned aside, I am pretty satisfied with it. The value used instead of `YAY!!!` is `[]` (but I hope that will change for golfing purposes).
### Explanation
```
?↑2↑0Πṙ_1†aÖ±↔Ġ-::15t*3e588 83B60†d½ | Input as a digit list from CLA, output to STDOUT.
½ | Split the list into two halves.
†d | Turn each half into a base-10 integer.
B60 | Convert from base 60.
: | Append the above to ↓ ([15, 83, 588, 83, 588, 83]).
e588 83 | Create the two element list [588, 83].
*3 | Repeat three times.
t | Remove the first element.
:15 | Prepend a 15.
Ġ- | Apply cumulative subtraction from the right.
↔ | Reverse.
Ö± | Stable sort by the sign (-1, 0 or 1).
†a | Map absolute value.
ṙ_1 | Rotate one right.
? Π | If the product is truthy, then:
↑2 | Take the first two elements.
↑0 | Return an empty list otherwise.
```
[Answer]
# [Kotlin](https://kotlinlang.org), 293 bytes
```
{fun i(l:List<Int>)=l.all{it==l[0]}|| l.mapIndexed{a,b->b-a}.all{it==l[0]}
val a=(0..1439+0).map{val h=it/60
val m=it%60
listOf(h/10,h%10,m/10,m%10)}+listOf(listOf(0,0,0,0))
val s=a.indexOf(it)
if(i(it))0 to 0 else
s-a.subList(0,s).indexOfLast{i(it)}to a.subList(s,a.size).indexOfFirst{i(it)}}
```
## Beautified
```
{
fun i(l:List<Int>)=l.all { it ==l[0] } || l.mapIndexed { a, b -> b - a }.all { it ==l[0] }
val a = (0..1439 + 0).map {
val h = it/60
val m = it%60
listOf(h/10,h%10,m/10,m%10)
} + listOf(listOf(0,0,0,0))
val s = a.indexOf(it)
if (i(it)) 0 to 0 else
s - a.subList(0, s).indexOfLast {i(it)} to a.subList(s, a.size).indexOfFirst {i(it)}
}
```
## Test
```
var t:(i:List<Int>)-> Pair<Int, Int> =
{fun i(l:List<Int>)=l.all{it==l[0]}|| l.mapIndexed{a,b->b-a}.all{it==l[0]}
val a=(0..1439+0).map{val h=it/60
val m=it%60
listOf(h/10,h%10,m/10,m%10)}+listOf(listOf(0,0,0,0))
val s=a.indexOf(it)
if(i(it))0 to 0 else
s-a.subList(0,s).indexOfLast{i(it)}to a.subList(s,a.size).indexOfFirst{i(it)}}
data class Test(val input: List<Int>, val output: Pair<Int, Int>)
val TEST = listOf(
Test(listOf(0,0,0,0), 0 to 0),
Test(listOf(0,0,2,0), 20 to 63),
Test(listOf(0,1,0,5), 65 to 18),
Test(listOf(0,1,2,2), 82 to 1),
Test(listOf(0,1,2,3), 0 to 0),
Test(listOf(0,1,2,4), 1 to 587),
Test(listOf(0,8,5,2), 449 to 139),
Test(listOf(1,1,1,1), 0 to 0),
Test(listOf(1,1,1,3), 2 to 81),
Test(listOf(1,2,0,0), 49 to 34),
Test(listOf(1,2,3,4), 0 to 0),
Test(listOf(1,3,5,7), 83 to 505),
Test(listOf(1,7,5,9), 325 to 263),
Test(listOf(1,8,0,0), 326 to 262),
Test(listOf(1,8,0,1), 327 to 261),
Test(listOf(2,2,2,2), 0 to 0),
Test(listOf(2,2,4,4), 22 to 61),
Test(listOf(2,3,4,5), 0 to 0),
Test(listOf(2,3,5,1), 6 to 9)
)
fun main(args: Array<String>) {
for (t in TEST) {
val v = t(t.input)
if (v != t.output) {
throw AssertionError("$t $v")
}
}
}
```
## TIO
[TryItOnline](https://tio.run/##fZRtb5swEMff8yluVSth1aFgyKNKpL7opEqVNql9N+2Fs5DGmgOV7WQPlM+enY80bSeIkeCwf7773+HjZ+W0KvfBThpws1DN7pV113elm7PBHL5KZfwLBz8D+b5ebUtQoX6H5TqSWtfK5bn+Fn9vXl5ARxv5fFcui9/FspZ8MZgvBrL5iGFEDTIP4yhKsnR6GTO/qfaz61y5q1FMxAbtC7Q1xvuyCtdXSczXF3jbeGuDFmsuD4uHR8zpYowc2FxGykvBFeVYoPDhDRaDqyCGQtsisAMZ2e3CJ4XbLXvdcS+tqwlvEH5jLEdb/S2O4GdljmSzD5bSSfihpbXwWCDvhajyeetmcCwcBz9bbR1Nf6w0C0j74+3DI+RwyCsAHOTuv0Q5tLkw3okIQgQxo7QTShAbIjQaeiiZ9ECCC4QmgqBeJj0tyCMZIolHhpNxJzThQ4qVZVMKlk47sITTdSpci3hFJHqSdDLiUMY2WJr1QCnpPhErRdVjX6GUcouHndQYKUwHUkHVFp3fJMEStKJSMWox0YslhI1brCtFwcXh4/Wq90BGCQoqVY8frAGdlBN+fBW8IpI9ZQEeZv/X2EhVhtI82RncGCP/XD84o8qnOYOanKwqA6HDNqFj/zrrh2+FHfaBC11EXcSOS2oF4Q4+4VrUdtL7fX64tal+wY21hXGqKm+NqUx4du7gfHf25qYJ2nuz/wc)
] |
[Question]
[
Write a program or function which, given a *non-empty* sequence of right or left turns, outputs the length of the shortest self-avoiding path on a 2D lattice with those turns.
The input should be taken as a string, with each character being `R` or `L` for a right or left turn respectively.
The output should be an integer, the length of the shortest path with the given turns.
This is a gode golf - shortest code wins.
# Example
Given the input
```
LLLLLLLLLLRRL
```
The shortest path is the following (starting at `#`):
```
+-+-+-+-+-+-+
| |
+ . + +-+-+ +
| | | | |
+ +-+ + #-+ +
| | | |
+ +-+ +-+-+-+
| |
+-+-+ . . . .
```
And the total length of this path is `29` (counting the `-`s and `|`s, not the `+`s).
# Test Cases
```
L 2
RRRRRRRRRR 23
LRRLRLRRRRL 15
LLRRLRRRRLLL 17
LLRRRRRRLLLL 21
LLLLRLLRRLLRL 16
LRLRLRLLRLRRL 14
RLLRRRRLLRRLRL 17
RRRRLLRLLLRLRL 20
LLLLRRLRLRRRLRL 19
RRRLRRRLRRLRLRL 20
```
[Answer]
# Prolog, 284 bytes
```
e(S,[0|X]):-e(S,X).
e([A|S],[A|X]):-S=X;e(S,X).
v(X/Y,76,Y/Z):-Z is -X.
v(X/Y,82,Z/X):-Z is -Y.
v(D,0,D).
c([],0/0-0/1,[0/0]).
c([H|T],K/L-D/E,[K/L|C]):-c(T,I/J-X/Y,C),v(X/Y,H,D/E),K is I+X,L is J+Y,\+member(K/L,C).
n(X):-X=0;n(Y),X#=Y+1.
p(S,L):-n(L),length(X,L),e([0|S],X),c(X,_,_).
```
This is a pretty straightforward statement of the algorithm, and fairly inefficient (not all the test cases ran in reasonable time, although most did). It works via generating all possible lengths for the output from 1 upwards (`n`); generating all possible sequences of left/forward/right of that length which are consistent with the input (implemented in `e`; the new path is called `X`); then checking for the first such path that's valid (`c`, which calls into `v` to handle the effects of left and right turns on the x and y deltas). The return length is the first output seen in `L`. (+2 penalty if you want to prevent the function returning other possible outputs for the length if you backtrack into it; it's never quite clear how Prolog's idiosyncratic function returns should be counted.)
There isn't much in the way of golfing tricks here, but there is some. `n` was implemented with a constraint solver because it allows more whitespace to be removed without confusing the parser; this might require GNU Prolog to be used, not sure on that. (I couldn't do the same in `c` as it needs to handle negative numbers.) The implementation of `e` is considerably less efficient than it needs to be, via matching a list in multiple ways; the more efficient `e([],[]).` would be six bytes longer (it'd allow the `S=X;` on line 2 to be removed, but that's only a gain of four compared to a loss of ten). To allow me to match coordinates and directions as a whole, or just part, I represent them as `X/Y` (i.e. an unevaluated AST, which can be matched on), allowing me to use infix notation.
# Prolog, 256 bytes, too inefficient to easily test
Of course, because this is Prolog, many of the functions are reversible, e.g. `c` can be used to generate all paths from the origin to a particular coordinate pair. Additionally, `c` naturally generates from shortest to longest. This means that instead of asking for a minimum length explicitly, we can just get `c` to generate *all paths that go anywhere*, then look for the first one that's consistent with the input:
```
e(S,[0|X]):-e(S,X).
e([A|S],[A|X]):-S=X;e(S,X).
v(X/Y,76,Y/Z):-Z is -X.
v(X/Y,82,Z/X):-Z is -Y.
v(D,0,D).
c([],0/0-0/1,[0/0]).
c([H|T],K/L-D/E,[K/L|C]):-c(T,I/J-X/Y,C),v(X/Y,H,D/E),K is I+X,L is J+Y,\+member(K/L,C).
p(S,L):-c(X,_,_),length(X,L),e([0|S],X).
```
This has exponential performance (O(3*n*), where *n* is the output). However, I did manage to verify it on some of the smaller tests (it takes around 7 seconds to output 14, and around 20 to output 15, on my computer).
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 36 bytes
```
ff{I.u+NYY0f>r8YlQ.C+1*M._m^.j)hCdQT
```
[Try it online!](https://tio.run/##K6gsyfj/Py2t2lOvVNsvMtIgza7IIjInUM9Z21DLVy8@N04vSzPDOSUw5P9/JR8gCPJRAgA "Pyth – Try It Online")
This is pretty slow, but it works, and it's fast enough for short inputs.
The program works by representing directions as complex units (1,-1,i,-i), and points as complex numbers. First I convert the list of turns into a list of directions, then generate all list of n steps, filter for those with at least one step between each turn, and convert the directions into a list of points visited, and check if that list is unique. I increment n in a loop until I succeed.
Map to complex numbers:
```
m^.j)hCdQ
m Q Map over the input
Cd Convert to ASCII codepoint
h Increment
^.j) Raise i to that power.
```
Since `L` has ASCII codepoint 76 and `R` has ASCII codepoint 82, this maps `L` to `i` and `R` to `-i`.
Map to absolute directions:
```
+1*M._ ...
._ Form all prefixes
*M Map each to its product
+1 Add the first direction, before any turns
```
Form lists of n steps with at least 1 step between each turn
```
f>r8YlQ.C ... T
.C T Form all list of T steps
f Filter for lists where
r8Y Run length encoding of list
> lQ With the first len(input) removed
is nonempty
```
There should be one more movement than there are turns in the input. Each movement is in a different direction, so the run length encoding should be longer than the input.
Map to points visited:
```
.u+NYY0 ...
.u Y0 Reduce the following function over
the list of steps, starting at 0.
Return all intermediates.
+NY Add the new step to the current position.
```
Filter on non-self-intersecting:
```
f{I ...
f Filter on
I Invariant under
{ Deduplication
```
Find the first `T` where this succeeds: `f`.
] |
[Question]
[
Today you will be doing another palindrome challenge!
So, your task today is to take a string, and determine the minimum amount of letters required to insert to turn it into a palindrome.
For example, let's take the string `fishes`.
In this, case the best way would be to add `h if`, so the result would be 3.
```
fishe s
h if
---------
fishehsif
```
Now let's try with `codegolf`. Since there is a repeated `o`, we can just do:
```
codeg o lf
fl ed c
-------------
flcodegedoclf
```
to get a result of 5.
## Test cases
```
ppcg -> 2
codegolf -> 5
palindrome -> 9
stackexchange -> 8
programmingpuzzlesandcodegolf -> 20
```
[Answer]
## Pyth, 10 bytes
[test suite.](http://pyth.herokuapp.com/?code=l.-Qe%40y_Qy&input=ppcg%0Acodegolf%0Apalindrome%0Astackexchange%0A&test_suite=1&test_suite_input=%22ppcg%22%0A%22codegolf%22%0A%22palindrome%22%0A%22stackexchange%22%0A%22toot%22&debug=1)
```
l.-Qe@y_Qy
y All subsequences of the input (implicit), sorted by length
y_Q All subsequences of the reversed input, sorted by length
@ Their setwise intersection: the common subsequences
e Last element: the longest common subsequence
.-Q Remove it bagwise from the input: the letters not in this LCS
l The length of that
```
There's a few equivalent characterizations of the value we're after:
* The fewest insertions needed to make a palindrome
* The fewest deletions needed to make a palindrome
* Half the number of delete or insert operations needed to transform the string to its reverse
* The length of the input with its longest palindromic subsequence removed
* The length of the input, removing the longest common subsequence between it and its reverse. (The code uses this one.)
The common idea is the "skeleton" of letters in the input that are matched with letters of the input in the final product.
```
codeg o lf
* * *
fl o gedoc
flcodegedoclf
```
This skeleton is always a palindrome, with letters matching to their reversed counterparts. Each non-skeleton letters is unmatched and must have its counterpart inserted.
A same-length alternative instead uses the fourth condition, the length of the input minus the length of its longest palindromic subsequence
```
l.-Qef_ITy
```
[Link to test suite.](http://pyth.herokuapp.com/?code=l.-Qef_ITy&input=%22codegolf%22&test_suite=1&test_suite_input=%22ppcg%22%0A%22codegolf%22%0A%22palindrome%22%0A%22stackexchange%22%0A%22toot%22&debug=1)
The part that's different is
```
f_ITy
y All subsequences of the input (implicit), sorted by length.
f Filtered on:
_IT being invariant under reversal, i.e. a palindrome
```
For both, instead of removing the palindromic subsequence from the input and taking the length, we could instead subtract its length from the length of the input. Either one costs 4 bytes: `-lQl` vs `l.-Q`.
[Answer]
# Python, 112 bytes
```
d=lambda x,l,h:0if h<l else d(x,l+1,h-1)if x[l]==x[h]else-~min(d(x,l+1,h),d(x,l,h-1));e=lambda x:d(x,0,len(x)-1)
```
Very inefficient.
[Try it online!](https://repl.it/EP4G/1) You have to wait a minute for the last case to finish.
Call with `e(<string>, 0, <length of string - 1>)`, like e("fishes", 0, 5)`.
Ungolfed (sort of) with explanation:
```
def minInsert(x, l, h): # Declare func, arugments for x, l, h # d=lambda x,l,h:
if l >= h: # If l is the same or past h # if h<l
return 0 # then return 0 # 0
elif x[l] == x[h]: # If first and last character are the same # else if x[l]==x[h]
return minInsert(x, l + 1, h - 1) # then return the min w/o first & last # d(x,l+1,h-1)
else: # If not, we shave off a character # else
a = minInsert(x, l, h - 1) # (last one) # d(x,l+1,h)
b = minInsert(x, l + 1, h) # (first one) # d(x,l,h-1)
return min(a, b) + 1 # and add one for the char we took off # -~min( , )
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 11 bytes
Uses [CP-1252](http://www.cp1252.com) encoding.
```
ÂæsæÃ¤g¹g-Ä
```
[Try it online!](http://05ab1e.tryitonline.net/#code=w4LDpnPDpsODwqRnwrlnLcOE&input=cGFsaW5kcm9tZQ) or as a [Test suite](http://05ab1e.tryitonline.net/#code=fHZ5w4LDpnPDpsODwqRneWctw4Qs&input=cHBjZwpmaXNoZXMKY29kZWdvbGYKcGFsaW5kcm9tZQpzdGFja2V4Y2hhbmdl)
**Explanation**
```
# implicit input
 # push a reversed copy
æ # compute powerset of the reversed string
sæ # compute powerset of the string
äg # get length of the longest common subset
¹g- # subtract the length of the original string
Ä # take absolute value
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 9 bytes
```
⊆P↔P;?lᵐ-
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1FXW8CjtikB1vY5D7dO0P3/Xyk5PyU1PT8nTel/FAA "Brachylog – Try It Online")
This challenge really needed a Brachylog v2 answer, as insertion palindromization is so intuitive in that language.
### Explanation
`⊆P↔P` really is what does palindromization by insertion (see [this example](https://tio.run/##SypKTM6ozMlPN/r//1FXm96jtin//ysl56ekpufnpCn9jwIA))
```
⊆P P is an ordered superset of the input
P↔P P reversed is P (i.e. P is a palindrome)
P;?lᵐ Compute the length of both P and the input
- Subtraction
```
[Answer]
# C, ~~89~~ 121 bytes
```
#define g(a) f(a,a+strlen(a)-1)
f(char*a,char*b){return a>=b?0:*a-*b?f(a+1,b)<f(a,b-1)?f(++a,b)+1:f(a,--b)+1:f(++a,--b);}
```
Shameless port of [Oliver](https://codegolf.stackexchange.com/a/98620/53667)'s answer, could not think of any shorter solution.
`g` calls `f` with the pointer to the first and the last char of a string (the last char is part of the string, not the `'\0'`). Gets even more inefficient because `f` is called two times for the `min` case.
Ungolfed:
```
f(char*a,char*b){
return a>=b ? 0 :
*a-*b ? //if the pointed chars are not the same
f(a+1,b)<f(a,b-1) ? f(a+1,b)+1 : f(a,b-1)+1 //min(f..,f..)+1
: f(a+1,b-1); //if they were the same, make it more narrow
}
```
Usage:
```
int main(){
char s[]="palindrome";
printf("%d\n",g(s));
}
```
[Answer]
# [Brachylog v1](http://github.com/JCumin/Brachylog), 13 bytes
```
,IrIs?:I:lar-
```
[Try it online!](http://brachylog.tryitonline.net/#code=LElySXM_Okk6bGFyLQ&input=InN0YWNrZXhjaGFuZ2Ui&args=Wg)
You can check the palindromes it finds with [this code](http://brachylog.tryitonline.net/#code=LC5yLnM_LA&input=InN0YWNrZXhjaGFuZ2Ui&args=Wg).
### Explanation
I'm almost surprised this even works, seeing how ridiculously simple it is.
```
,IrI I reversed is I (i.e. I is a palindrome)
Is? The Input is an ordered subset of I
?:I:la The list [length(Input), length(I)]
r- Output = length(I) - length(Input)
```
This is guaranteed to find the smallest palindrome because `IrI` will generate strings of increasing length when backtracking, starting from the empty string.
This is not efficient enough to compute the last test case on TIO, because of the use of `s - Ordered subset`.
[Answer]
## Batch, ~~234~~ 232 bytes
```
@echo off
set n=99
call:l 0 %1
echo %n%
exit/b
:g
set/am=%1
if %m% lss %n% set/an=m
exit/b
:l
if "%2"=="" goto g
set s=%2
if %s:~,1%==%s:~-1% call:l %1 %s:~1,-1%&exit/b
call:l %1+1 %s:~1%
set s=%2
call:l %1+1 %s:~,-1%
```
Works by recursively trying to insert nonmatching characters at both ends, so very slow (I didn't try the last test case). Recursion limits mean that this only works for a limited string length anyway, so the `99` is somewhat arbitrary. I have to use `call` parameters as local variables as I couldn't get `setlocal` to work for me, which means that `%1` parameter to the `:l` subroutine is an expression that evaluates to the number of insertions done so far.
] |
[Question]
[
In Chinese, numbers are written as follows:
`1 一` `2 二` `3 三` `4 四` `5 五` `6 六` `7 七` `8 八` `9 九` `10 十`
For numbers above 10, it is expressed as the number of tens and the number of ones. If there is only one ten, you do not need to explicitly say one, and if there are no ones, you don't need to put anything after:
`11 十一`
`24 二十四`
`83 八十三`
`90 九十`
For numbers above 100, you use the same logic, but with the character `百`. This time though, if there is only one hundred, you still need to write it out, and if there are no tens, you need to say `零`.
`100 一百` `231 二百三十一` `803 八百零三` `999 九百九十九`
Your task is to convert these Chinese numerals into Arabic numerals. Given a number *N* in Chinese (`一` (1) <= *N* <= `九百九十九` (999)), convert it into an Arabic number.
Remember, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the code with the smallest number of bytes wins.
[Answer]
## JavaScript (ES6), 112 bytes
```
s=>[...s].map(c=>d=(i="零一二三四五六七八九十百".search(c))>9?(n+=(d||1)*(i*90-890),0):i,n=d=0)&&n+d
```
Digits 一-九 are converted to decimal and saved in `d`, while 十 and 百 multiply the last digit by 10 or 100 respectively and accumulate it in `n`. `零` is effectively ignored, since `d` is already zero when it is encountered.
[Answer]
## Perl, 110 bytes
**98 bytes code + 12 for `-plC -Mutf8`.**
Perl does hate unicode. Hopefully I haven't missed any edge cases, I had an issue with numbers like `二百十` but I've addressed that now!
```
s/十/*10+/;s/百/*100+/;y/一二三四五六七八九零/123456789 /;s/^\*|\+\*/+/g;$_=eval"$_-0"
```
### Usage
```
perl -plC -Mutf8 -e 's/十/*10+/;s/百/*100+/;y/一二三四五六七八九零/123456789 /;s/^\*|\+\*/+/g;$_=eval"$_-0"' <<< '一
二
三
四
五
六
七
八
九
十
十一
二十四
八十三
九十
一百
二百三十一
八百零三
九百九十九'
1
2
3
4
5
6
7
8
9
10
11
24
83
90
100
231
803
999
```
[Answer]
# PHP, 225 Bytes
```
preg_match_all("#[1-9]?10+|[1-9]#",str_replace(["一","二","三","四","五","六","七","八","九","十","百"],[1,2,3,4,5,6,7,8,9,10,100],$argv[1]),$z);foreach($z[0]as$p)$s+=($b=substr_count($p,0))?$p[0]*10**$b:$p;echo$s;
```
[Answer]
# Java 7, ~~236~~ ~~233~~ 229 bytes
```
int c(String s){String x=" 一二三四五六七八九十百";int l=s.length(),i=x.indexOf(s.charAt(l-1)),j=x.indexOf(s.charAt(0)),q=j*100;return l<2?i:l<3?i==10?j*10:i>10?q:10+i:l<4?j*10+i:l<5?q+i:q+i+x.indexOf(s.charAt(2))*10;}
```
**Ungolfed & test code:**
[Try it here.](https://ideone.com/dgK2Cq)
```
class M{
static int c(String s){
String x = " 一二三四五六七八九十百";
int l = s.length(),
i = x.indexOf(s.charAt(l-1)),
j = x.indexOf(s.charAt(0));
if(l<2) return i; // 1-10
if(l<3){
if(i==10) return j*10; // 20,30,40,50,60,70,80,90
if(i>10) return j*100; // 100,200,300,400,500,600,700,800,900
return 10+i; // 11-19
}
if(l<4) return j*10+i; // 21-29,31-39,41-49,51-59,61-69,71-79,81-89,91-99
if(l<5) return j*100+i; // 101-109,201-209,301-309,401-409,501-509,601-609,701-709,801-809,901-909
return j*100+i+x.indexOf(s.charAt(2))*10; // 111-119,121-129,131-139,...,971-979,981-989,991-999
}
public static void main(String[] a){
System.out.println(c("一"));
System.out.println(c("二"));
System.out.println(c("三"));
System.out.println(c("四"));
System.out.println(c("五"));
System.out.println(c("六"));
System.out.println(c("七"));
System.out.println(c("八"));
System.out.println(c("九"));
System.out.println(c("十"));
System.out.println(c("十一"));
System.out.println(c("二十四"));
System.out.println(c("八十三"));
System.out.println(c("九十"));
System.out.println(c("一百"));
System.out.println(c("二百三十一"));
System.out.println(c("八百零三"));
System.out.println(c("九百九十九"));
}
}
```
**Output:**
```
1
2
3
4
5
6
7
8
9
10
11
24
83
90
100
231
803
999
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 107 bytes
```
switch -r($args){百{$s+=100*$d}十{$s+=10*($d+!$d)}.{$d='一二三四五六七八九'.IndexOf($_)+1}}$d+$s
```
[Try it online!](https://tio.run/##ZZHNSsNAEMfveYq1LDbpF431o0UKgVLBU8V6Eyk12Vql2ppNaSEuVEoPBb31IsEnkF4l9uDTJIhPEWeTbFJwDwvz/8/8ZmZ3NJwQk/bJYBDgHqojO6CTW0vvo6Ip4655QxX75@3bxjRfV8vlHDaY//ochzkZG/kdbCisZGOjnvXcmbd58dyl7zjeZuUv1p479xcf3td7tnT6YJBpqyfjjpJXGYNKTAMmSZosSQVNzkASNIIb@HBnCqhWqymhBQiwfp1PQINeLVciHZrxEugHJe4MrL2KGlvuDCxQYGihLEEBFCSDXqkKfbOKICAepOTVdsdUD7uoSXveMsFzajyw40Cwn7A4QqyyhuBQ1MwhOEqW5Lsp4jH4A8ROOLAK80oKekInQ7PZ1fvF1vUd0S1kSwgOtgi1Gl1KCgiT6QgMYsBv4k7kmoSOBxYIu/DJmsgNvcuzdmNMreF9xLvSIiA/7bGuE0o5JwYUyWPKP04SzwU@zkud5tYs/@su4kG4K4aKXCax4A8 "PowerShell – Try It Online")
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), 131 bytes
```
$args|%{if($i=("一二三四五六七八九"|% I*f $_)+1){$b=$i}if($_-eq"十"){$t+=(!$b+$b)*10
$b=0}if(!$i){$t+=$b*100
$b=0}}
$t+$b
```
[Try it online!](https://tio.run/##ZZHLasJAGIX38xRjGEviBbT2JiUQEAtdtdTuShGTTmqKJTYTaSEGFHFRaHduivgExW2JLvo0CaVPkf5joo50FrM43/nPnJnp2s/UYW3a6RQN26ExMVUvJi3nnvWznmXKxFJlKQwG4fItDF6j6TRcTqLxPAxG0fgzXMykfhaf50xMmkq@rHhEV4nl87lmkT5J0ftQAtHNq3KG6HmiK7lyCYGpxD0ZYiWQ6CCnuo9AIXrsI6TJCMMqaNBgMfv5@IYdEvmpBVytVpUNhi6Af6df0BHYSamyZdCcj0J5GA0GgPcrZQEHA8CgQoMdlUs7KXxSdPCThHPgbUA4EEcmIByKLecgHIkZIxCOd@7B6yvivfldBQe8KO@qIAX38Znt1FtGu3ihP1DDxd7KRlzK3FqL0QIm9KULgN5hFX4ooQ5lvY4Lwh4xsbb2rtjNZaPWY679mOTdakkgX42eYVDGeE4aAP@7zT/dGK/W8alvS@pCl/9z12kRTtelEuojH8V/ "PowerShell Core – Try It Online")
-10 bytes thanks to *Zaelin Goodman*!
[Answer]
# C#, ~~197~~ 210 bytes
```
int x(string s){if(s=="")return 0;if(s[0]=='零')s=s.Substring(1);if(s[0]=='十')s="一"+s;string t=" 一二三四五六七八九";return s.Length<2?t.IndexOf(s[0]):(t.IndexOf(s[0])*(s[1]=='百'?100:10)+x(s.Substring(2)));}
```
*Wrong byte count previously due to encoding ignored...*
Big5 Encoding
A recursive solution which pads the input if it's 10-19 for easier processing, then process from left 2 characters at a time.
Ungolfed
```
public int x(string s)
{
if (s == "")
return 0; // Recursion termination when input is divisible by 10 (no unit digit character)
if (s[0] == '零')
s = s.Substring(1); // Ignore '零'
if (s[0 ]== '十')
s = "一" + s; // Normalize 10-19 by padding with "一"
string t = " 一二三四五六七八九"; // Index lookup
return s.Length < 2
? t.IndexOf(s[0]) // 0-9
: (t.IndexOf(s[0]) * (s[1] == '百' ? 100 : 10) + x(s.Substring(2)));
// Get the first character's digit, multiply by 100 or 10 depends on 2nd character, and recursively process from 3rd character onwards
}
```
[Answer]
# Python 3, 128 bytes
Saving 2+3 bytes thanks to Shebang and 2 for replacing `(d>9)+(d>10)` with `max(d-9,0)`
```
n=a=0
for c in input():d=" 一二三四五六七八九十百".find(c);n+=[0,10*a**(a>0),a*100][max(d-9,0)];a=d*(d<10)
print(n+a)
```
Ungolfed:
```
n=a=0
for c in input():
d=" 一二三四五六七八九十百".find(c)
n+=[0, 10*a**(a>0), a*100][max(d-9,0)]
a=d*(d<10)
print(n+a)
```
Initial answer
```
n=a=0
for c in input():
d=" 一二三四五六七八九十百".find(c)
if d<=9:a=d
elif d==10:n+=[1,a][a>0]*10;a=0
elif d==11:n+=a*100;a=0
print(n+a)
```
`n` will be the final number and `a` is the previous digit.
] |
[Question]
[
A room can be made up of connected rectangles, for instance an L-shaped room. Such a room can be described by a list of dimensions describing the size of each rectangle.
Assume you have two input lists. The first contains the width of rectangles stacked vertically over each other. The second contains the height of the rectangles.
As an example, the input `[4 6][3 2]` will be a 4-by-3 rectangle on top of a 6-by-2 rectangle. The figure below shows this shape. Note that the walls are considered "thin", thus it's the spaces between the wall that's determined by the input.
```
[4 6][3 2]
____
| |
| |
| |_
| |
|______|
```
The challenge is: Take a list of dimensions as input, and output the shape of the room as ASCII-art. The format must be as in the sample figures:
* All horizontal walls are shown using underscores
* All vertical walls are shown using bars
* There shall be no walls where the rectangles are connected
* The left wall is straight
* For more details, have a look at the test cases
Assumptions you can make:
* All dimensions are in the range `[1 ... 20]`
+ All *horizonal* dimensions are even numbers
* The number of rectangles will be in the range `[1 ... 10]`
* Only valid input is given
* Optional input format (you can decide the order of the input dimensions, please specify in the answer).
**Test cases:**
```
[2][1]
__
|__|
---
[4][2]
____
| |
|____|
---
[2 6 2 4][2 2 1 3]
__
| |
| |___
| |
| ___|
| |_
| |
| |
|____|
---
[2 14 6 8 4 18 2 10 4 2][1 2 3 1 2 1 1 1 2 1]
__
| |___________
| |
| _______|
| |
| |
| |_
| ___|
| |
| |_____________
| _______________|
| |______
| ____|
| |
| _|
|__|
```
[Answer]
# JavaScript (ES6) 174
The only critical part is the horizontal row joining 2 parts of different widths, with the vertical bar on right side that can be in the middle or at the right end.
```
(p,h,q=-1,R=(n,s=' ')=>s.repeat(n))=>[...p,0].map((x,i)=>(x>q?p=x:(p=q,q=x),(~q?`
|`+R(q+(x<p)-!x)+R(x>q,'|'):' ')+R(p+~q+!x,'_')+R(x<p,'|')+R(h[i]-1,`
|${R(q=x)}|`))).join``
```
**TEST**
```
f=(p,h,q=-1,R=(n,s=' ')=>s.repeat(n))=>[...p,0].map((x,i)=>(x>q?p=x:(p=q,q=x),(~q?`
|`+R(q+(x<p)-!x)+R(x>q,'|'):' ')+R(p+~q+!x,'_')+R(x<p,'|')+R(h[i]-1,`
|${R(q=x)}|`))).join``
// Less golfed
F=(p,h, q=-1,
R=(n,s=' ')=>s.repeat(n)
)=>
[...p, 0].map((x,i)=> (
x>q? p=x : (p=q,q=x),
(q>=0?`\n|`+R(q+(x<p)-!x)+R(x>q,'|'):' ')
+ R(p+~q+!x,'_') + R(x<p,'|')
+ R(h[i]-1,`\n|${R(q=x)}|`)
)).join``
console.log=x=>O.textContent+=x+'\n'
;[
[[2],[1]],
[[4],[2]],
[[2, 6, 2, 4],[2, 2, 1, 3]],
[[2, 14, 6, 8, 4, 18, 2, 10, 4, 2],[1, 2, 3, 1, 2, 1, 1, 1, 2, 1]]
].forEach(t=>{
var w=t[0],h=t[1]
console.log('['+w+'] ['+h+']\n'+f(w,h)+'\n')
})
```
```
<pre id=O></pre>
```
[Answer]
## Python 3, ~~230~~ ~~223~~ ~~222~~ 217 bytes
```
def f(a):b=a[0]+[0];m=' _';print('\n'.join([' '+'_'*b[0]+' ']+['|'+' '*min(b[l],b[l+1])+m[b[l+1]<1]*(b[l]>b[l+1])+m[k]*(b[l]-b[l+1]-1)+'|'+m[k]*(b[l+1]-b[l]-1)for l,i in enumerate(zip(*a))for k in[0]*(i[1]-1)+[1]]))
```
*Thanks to @StewieGriffin @KevinLau for their help*
## Results
```
>>> f([[2, 14, 6, 8, 4, 18, 2, 10, 4, 2],[1, 2, 3, 1, 2, 1, 1, 1, 2, 1]])
__
| |___________
| |
| _______|
| |
| |
| |_
| ___|
| |
| |_____________
| _______________|
| |_______
| _____|
| |
| _|
|__|
```
[Answer]
# Ruby 191
First time golfing, also it's my first day with Ruby, so it's probably not the most elegant thing in the world, but it'll do?
```
def f(x)
a=x[0]+[0]
puts" #{'_'*a[0]} "
for i in 0..x[1].length-1
n,m=a[i,2].sort
puts"|#{' '*a[i]}|\n"*(x[1][i]-1)+'|'+' '*n+(a[i+1]<1?'_':m>a[i]?'|':' ')+'_'*(m-n-1)+(n<a[i]?'|':'')
end
end
```
[Answer]
# Retina, ~~169~~ ~~150~~ 113 bytes
Byte count assumes ISO 8859-1 encoding.
```
\d+
$*
{+r`1(1*¶[^|]*(1+))
$1¶|$2|
}` (¶.*) 1+
$1
1
_
(\|_+)\|(?=¶\1_(_+))
$1|$2
T`w` `(\|_+)_?(?=_*\|.*¶\1)
^¶
```
The code contains a trailing space on a trailing newline.
Input format:
```
Height (separated by spaces)
Width (also separated by spaces)
```
For example:
```
1 2 3 1 2 1 1 1 2 1
2 14 6 8 4 18 2 10 4 2
```
[Try it online!](http://retina.tryitonline.net/#code=XGQrCiQqCnsrcmAxKDEqwrZbXnxdKigxKykpCiQxwrZ8JDJ8Cn1gICjCti4qKSAxKwokMQoxCl8KKFx8XyspXHwoPz3CtlwxXyhfKykpCiQxfCQyClRgd2AgYChcfF8rKV8_KD89XypcfC4qwrZcMSkKXsK2CiA&input=MSAyIDMgMSAyIDEgMSAxIDIgMQoyIDE0IDYgOCA0IDE4IDIgMTAgNCAy)
] |
[Question]
[
Given an input of an ASCII art "road," output the road with all dead ends
labelled.
This is a road:
```
########.....######..#..###
#......#######....#..#..#.#
#.##......#...#####..#..###
#..#####..#....#..#######.#
#......#...#####.....##...#
#..###.#...#...###...#..###
##########.#..#..##..#.##.#
..#......#.######.#..#.#.#.
..#......#.#..#.#.#..#.#.#.
..######.###..##..#########
```
This is the road with *dead ends* labelled with the letter `X`:
```
########.....######..X..###
#......#######....#..X..#.#
#.XX......X...X####..X..###
#..XXXXX..X....#..#######.#
#......X...#####.....##...#
#..###.X...#...###...#..###
##########.#..X..##..#.##.X
..X......#.#XXXXX.#..#.#.X.
..X......#.#..X.X.#..#.#.X.
..XXXXXX.###..XX..######XXX
```
A *dead end* is defined as any road tile that borders *n* other road tiles, at
least *n-1* of which are considered *dead ends* already by this rule.
"Bordering" is in the four cardinal directions, so tiles bordering diagonally
don't count.
This rule is applied repeatedly, as newly created *dead ends* can, themselves,
create more *dead ends*. Also note that any road tile that borders only one
other road tile is considered a *dead end* the first time the rule is applied.
Input and output may be either a single string (with lines separated by any
character that is not `#` or `.`) or an array/list/etc. If your language
supports it, you may also take input with each line being a function argument.
You may assume the following about the input:
* There will always be at least one "loop"—that is, a group of `#` characters
that can be followed infinitely. (Otherwise every single tile would become a
dead end.)
* This implies that the input will always be 2×2 or larger, since the smallest
loop is:
```
##
##
```
(Which, incidentally, should be output with no change.)
* All `#` characters will be connected. That is, if you were to perform a flood
fill on any `#`, all of them would be affected.
Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes will win.
The example above and the tiny 2×2 grid can be used as test cases (there aren't
a lot of edge cases to cover in this challenge).
[Answer]
# CJam, 61 bytes
```
q_N/{{0f+zW%}4*3ew:z3few::z{e__4=_@1>2%'#e=*"#"='X@?}f%}@,*N*
```
Try it [here](http://cjam.aditsu.net/#code=q_N%2F%7B%7B0f%2B0%5Cf%2Bz%7D2*3ew%3Az3few%3A%3Az%7Be__4%3D_%401%3E2%25'%23e%3D*%22%23%22%3D'X%40%3F%7Df%25%7D%40%2C*N*&input=%23%23%23%23%23%23%23%23.....%23%23%23%23%23%23..%23..%23%23%23%0A%23......%23%23%23%23%23%23%23....%23..%23..%23.%23%0A%23.%23%23......%23...%23%23%23%23%23..%23..%23%23%23%0A%23..%23%23%23%23%23..%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..%23%23%23%0A%23%23%23%23%23%23%23%23%23%23.%23..%23..%23%23..%23.%23%23.%23%0A..%23......%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.%23%23%23..%23%23..%23%23%23%23%23%23%23%23%23).
### Explanation
```
Outline:
q_N/ Read input lines
{ }@,* Perform some operation as many times as there are bytes
N* Join lines
Operation:
{0f+zW%}4* Box the maze with zeroes
3ew:z3few::z Mystical 4D array neighborhood magic.
(Think: a 2D array of little 3x3 neighborhood arrays.)
{ }f% For each neighborhood, make a new char:
e_ Flatten the neighborhood
_4=_ Get the center tile, C
@1>2% Get the surrounding tiles
'#e= Count surrounding roads, n
* Repeat char C n times
"#"= Is it "#"? (i.e., C = '# and n = 1)
'X@? Then this becomes an 'X, else keep C.
```
(Martin saved two bytes, thanks!)
[Answer]
# JavaScript (ES6), ~~110~~ 109 bytes
```
r=>[...r].map(_=>r=r.replace(g=/#/g,(_,i)=>(r[i+1]+r[i-1]+r[i+l]+r[i-l]).match(g)[1]||"X"),l=~r.search`
`)&&r
```
*1 byte saved thanks to [@edc65](https://codegolf.stackexchange.com/users/21348/edc65)!*
## Explanation
Very simple approach to the problem. Searches for each `#`, and if there are less than 2 `#`s around it, replaces it with an `X`. Repeats this process many times until it's guaranteed all the dead-ends have been replaced with `X`s.
```
var solution =
r=>
[...r].map(_=> // repeat r.length times to guarantee completeness
r=r.replace(g=/#/g,(_,i)=> // search for each # at index i, update r once done
(r[i+1]+r[i-1]+r[i+l]+r[i-l]) // create a string of each character adjacent to i
.match(g) // get an array of all # matches in the string
[1] // if element 1 is set, return # (the match is a #)
||"X" // else if element 1 is undefined, return X
),
l=~r.search`
` // l = line length
)
&&r // return the updated r
```
```
<textarea id="input" rows="10" cols="40">########.....######..#..###
#......#######....#..#..#.#
#.##......#...#####..#..###
#..#####..#....#..#######.#
#......#...#####.....##...#
#..###.#...#...###...#..###
##########.#..#..##..#.##.#
..#......#.######.#..#.#.#.
..#......#.#..#.#.#..#.#.#.
..######.###..##..#########</textarea><br>
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```
[Answer]
## Python (3.5) ~~362~~ ~~331~~ ~~329~~ 314 bytes
thanks to @Alissa. she helps me to win ~33 bytes
```
d='.'
r=range
def f(s):
t=[list(d+i+d)for i in s.split()]
c=len(t[0])
u=[[d]*c]
t=u+t+u
l=len(t)
g=lambda h,x:t[h][x]=='#'
for k in r(l*c):
for h in r(1,l):
for x in r(1,c):
if g(h,x) and g(h+1,x)+g(h-1,x)+g(h,x+1)+g(h,x-1)<2:
t[h][x]='X'
print('\n'.join([''.join(i[1:-1])for i in t][1:-1]))
```
## Explanations
```
d='.'
r=range
```
Function definition
```
def f(s):
```
Add a border of '.' on right and left of the board
```
t=[list(d+i+d)for i in s.split()]
c=len(t[0])
u=[[d]*c]
```
Add a border of '.' on top and bottom
```
t=u+t+u
l=len(t)
```
Lambda function to test '#'
```
g=lambda h,x:t[h][x]=='#'
```
Loop on the input length to be sure we don't forget dead ends
```
for k in r(l*c):
```
Loop on columns and lines
```
for h in r(1,l):
for x in r(1,c):
```
Test if we have '#' around and on the position
```
if g(h,x) and g(h+1,x)+g(h-1,x)+g(h,x+1)+g(h,x-1)<2:
```
Replace '#' by 'X'
```
t[h][x]='X'
```
Crop the border filled with '.' and join in string
```
print('\n'.join([''.join(i[1:-1])for i in t][1:-1]))
```
## Usage
```
f("########.....######..#..###\n#......#######....#..#..#.#\n#.##......#...#####..#..###\n#..#####..#....#..#######.#\n#......#...#####.....##...#\n#..###.#...#...###...#..###\n##########.#..#..##..#.##.#\n..#......#.######.#..#.#.#.\n..#......#.#..#.#.#..#.#.#.\n..######.###..##..#########")
########.....######..X..###
#......#######....#..X..#.#
#.XX......X...X####..X..###
#..XXXXX..X....#..#######.#
#......X...#####.....##...#
#..###.X...#...###...#..###
##########.#..X..##..#.##.X
..X......#.#XXXXX.#..#.#.X.
..X......#.#..X.X.#..#.#.X.
..XXXXXX.###..XX..######XXX
```
] |
[Question]
[
As I have seen many questions asking tips for golfing in their interested language, I decided to ask for my favorite language: Groovy. People can give some tips and tricks that will be used in golfing with Groovy.
[Answer]
I'm new to this whole golfing thing, this is what I got so far:
Use Closures not functions:
```
def a(b){print b}
```
is longer than
```
a={print it}
```
You can use a negative index in arrays and lists as an alias for size()-
```
c = "abc"
d = ["a", "b", "c"]
assert c[c.size()-1] == c[-1]
assert c[c.size()-2] == c[-2]
assert d[d.size()-1] == d[-1]
assert d.last() == d[-1]
```
The spread operator is a shortcut for collect:
```
assert d*.size() == d.collect{it.size()}
```
For sorting use the spaceship operator:
```
e = [54,5,12]
assert e.sort{a,b->a<=>b}==e.sort{a,b->a<b?-1:+1}
assert e.sort{a,b->a<=>b}==e.sort{a,b->if (a>b) {return(-1)} else {return(+1)}}
```
Edit Conversions:
```
assert "123" as int == "123".toInteger()
```
[Answer]
As Groovy is a somewhat verbose language, you could use Groovys MOP to shorten method calls.
The following snippet for example would pay off after the fourth usage:
```
''.metaClass.r<<{i->(int)Math.random()*i}
''.r(12)
```
Tip golfing edit:
```
0.metaClass.r<<{i->(int)Math.random()*i}
0.r(12)
```
Or, you know:
```
r={(int)Math.random()*it}
r(12)
```
[Answer]
## `grep` is short and works on several problems
get the chars of a string as a list with spaces and without leading elements: `'ABC XYZ'.grep()` returns `[A, B, C, , X, Y, Z]`
grep with regexp is shorther than converting to upper case, if required: `it.grep(~/(?i)$c/)` instead of `it.toUpperCase().grep(c)`
[Answer]
**Getting An Array from a List of Objects**
If you have a list of objects like:
```
def users = [[user:'A',id:1],[user:'B',id:2],[user:'C',id:3]]
```
You can generate an ArrayList with a certain property using:
```
def userIds = users*.id // [1, 2, 3] no explicit loops!
```
**BONUS: Groovy... on Rails!**
Well, in [Grails Framework](https://grails.org/) we must get many values from a [select with multiple attribute](http://www.w3schools.com/tags/att_select_multiple.asp). You can use loops, flatten and other programming more typical structures, but you can save some lines. If you have a select like:
```
<select id="users" multiple="true" name="users">
<option value="193">User A</option>
<option value="378">User B</option>
<option value="377">User C</option>
</select><%-- No Grails tags for now --%>
```
Then, in your controller you can simple write:
```
def aListOfUsers = User.getAll(params.list('userIds'))
```
] |
[Question]
[
[](https://i.stack.imgur.com/J8ryq.jpg)
Credit: [Marco Verch](https://foto.wuestenigel.com/day-31-of-december-set-on-wooden-calendar/) [CC BY 2.0](https://creativecommons.org/licenses/by/2.0/)
A two-cube calendar, as shown in the picture, uses two cubes with digits painted on the faces to display the date. For dates in the range 1-9, a leading zero is used ("01", "02", ..., "09").
Now, if you do the math, you might come to the conclusion that these calendars should be impossible. After all, the numbers "0","1" and "2" must appear on both cubes (proof left to the reader). This means that there are only six faces remaining for the other seven numbers.
Two-cube calendars use a trick where the face with a "6" can be rotated upside down to look like a "9". For example, one cube may have faces "012345" and the other one "012678" where the "6" can also be a nine. For the purposes of this challenge these kind of font-dependent tricks are banned.
With these restrictions we can only display the numbers from 0 to 21 for a total of 22 numbers. We can display some other numbers too, but we are only interested in the longest possible sequence of numbers displayable (no gaps), starting from 0.
If, instead of using base 10, we would have used base 6, we could display \$0-55\_6\$ for a total of 36 numbers. (\$55\_6=35\_{10}\$)
If, instead of using cubes, we would have used octahedrons (8 faces), we could display 0-65 (using base 10).
And finally, with three cubes we can get 0-76 for a total of 77 numbers (using base 10).
The maximal amount of numbers we can get in the initial range is called the cube calendar number. It depends on the number of faces, on the number of dice ("cubes") and on the base of the numbers.
# Task
Given a base `b`, the number of faces `f` and the number of dice `d`, return the cube calendar number for those parameters.
`b`, `f` and `d` are natural numbers guaranteed to satisfy:
\$b\ge 2\$
\$b\ge f \ge 1\$
\$d\ge 1\$
# Test cases
```
d f b result
1 1 2 1
1 1 3 1
1 1 4 1
1 2 2 2
1 2 3 2
1 2 4 2
1 3 3 3
1 3 4 3
1 4 4 4
2 1 2 1
2 1 3 1
2 1 4 1
2 2 2 4
2 2 3 4
2 2 4 3
2 3 3 9
2 3 4 10
2 4 4 16
3 1 2 1
3 1 3 1
3 1 4 1
3 2 2 8
3 2 3 8
3 2 4 5
3 3 3 27
3 3 4 21
3 4 4 64
4 1 2 1
4 1 3 1
4 1 4 1
4 2 2 16
4 2 3 13
4 2 4 10
4 3 3 81
4 3 4 63
4 4 4 256
2 6 10 22
2 6 6 36
2 8 10 66
3 6 10 77
```
[Answer]
# [Python](https://www.python.org), 57 bytes (-8 thanks to @xnor)
```
lambda D,F,B:B**(D*~-F//~-B+1)//(B-(F<B>2))*(1+D*~-F%~-B)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LZDNSsNAEIDxuk8xLQi7aWK6P92kxXgIpdCLB89eIhoMpNlQ48FLX8RLQfSd9GncmQ4D-01mZr8M-_kzfkyvYTh_tdXj9_vUZuXvum8OT88NbNNdWm_qJJHb5JTt8vyU1Qut8lzWmdzd1ndGqUTqBXWvY1Ox4L4NR-ihGyCML4Ncqo2AZJ8GqODQjLIbprS_eRv7bpJKCRiPsSLjQBsPlYZ0PpsnMswq-lZsPf9dPWjQYEALpGU6osEgWqYjWgyiIzoMYdhj2GPYQxbqo-dCvGfIsybGuaUwJNJeWDZZNlk2WTKVRMt0sBK0D5iCkrgiTqLKO-FY5VjlWOVIFf_lyKUtJbSGI1upKYkSbGGYlY8r-jgCxlDmwWKpxJLHtalZFJe3_Qc)
#### Previous [Python](https://www.python.org), 65 bytes
```
lambda D,F,B:F//B*B**D or(B**(D*~-F//~-B+1)-1)//~-B*(1+D*~-F%~-B)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LZDNSsNAEIDxuk8xF2E3TWz3p5tYKGIoBa-ee4loMJBmQ4wHL30RLwXRd9KncWY6DOw3mZn9Muznz_gxv6bh_NVuD9_vc1tUv_d9c3x6bmCX7_N6s18u66zOsh2kSSP1LjsVWDwV9cKawhpOM20X3LjGDyOiuzZN0EM3QBpfBr0yGwXZQ55gC8dm1N0w5_3N29h3szZGwThhReNAi4fJk2jOf1ePFiw4sIrohYHpKJheGJieghmYgUI58TjxOPGwhfvkuZDuOfbcMnFupRyLbFReTF5MXkyeTRXTCwOsFe8DruQEV6RJUsWggqiCqIKoAqvwX4Fd1nPCawS2VZYTlFCLwq0jrhhxBJzjLIKnUkWlSGtzsywvb_sP)
#### Obsolete [Python](https://www.python.org), 69 bytes
```
lambda D,F,B:(B**-(D*~-F//-~-B)-1)//~-B*((x:=B+D*~-F%-~-B)-F//B)+x//B
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LZDNSsQwEIDxmqeYi5B0G7v52bQWilDWBa-e91LRYqHblrXCetkX8bIg-k76NGamw0C-YWbyZcjnz_Qxv47D5aut9t_vc6uL3_u-OTw9N7BNd2ldyjpJtNwmZ73LMn3WtdJGZVlMEilPZVWvqHe9tOJMrVaneLLsrh2P0EM3wDi9DHKtSgHJQzpCBYdmkt0wp_3N29R3s1RKwHSMFRkH2niodFSL5vJ39WjAgAUjkI7piRaD6Jie6DCInugxhGWPZY9lD1moj56FeM-S55YY59bCksgE4djk2OTY5MhUEB3Tw0bQPmBzSuKKOImq4IVnlWeVZ5UnVXzLk8s4SmgNT7bCUBIl2MKwmxBXDHEErKUsgMNSgaWAa1Mzz5e__Qc)
# How?
Given D,F,B a best set of dice has a zero on every die because 0 (with leading zeros) must be representable. The remaining D(F-1) faces should evenly split between the B-1 non-zero digits. Indeed, if we write
\$(1)\qquad M:=\lfloor D(F-1)/(B-1)\rfloor\$
then to get up to at least \$10\_{(B)}^M\$ we need \$11..11\_{(B)}, 22..22\_{(B)}, 33..33\_{(B)}\$ etc. (M digits each).
How much farther can we go? If the division in (1) splits cleanly (no remainder) then we top out at \$11..110\_{(B)}\$ (M+1 digits). This also shows that if the split was not clean then the first excess face should be a 1. If that is the only excess face it will carry us up to \$22..221\_{(B)}\$. The next excess face if it exists should therefore be a 2. Etc. Since we start at 0, the corresponding cube calendar numbers are \$11..11\_{(B)}=(10\_{(B)}^{M+1}-1)/(B-1),22..22\_{(B)},...\$
It remains to special case B=F and that's it.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 36 bytes
```
NθNηNζI×⊕﹪×θ⊖η⊖ζ÷Xζ⊕÷×θ⊖η⊖ζ⁻ζ∧‹ηζ›ζ²
```
[Try it online!](https://tio.run/##jY3LCsIwEEX3fkWWE6jgA9x0JRakYKULfyA2Awm0E5tHhf58bKhQdeXs7jnDvY0StjGijbGkR/DX0N3RQs/z1WdWP3mccm01eTgJ5@GmO3RQUmOxQ/IooTIytOYt@owVuDjF@TcYeSIl@UIPWiLU5pk2ElqeFv1/6YQqTcGlriNJuKBzoDI2TuJsUfh5Zsfny2PcswPbbuJ6aF8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Now uses @xnor's correction `F<B>2` (my previous correction `F<B` didn't work in some cases) which is still a byte golfier than special-casing `F=B`; this now makes my answer equivalent to a port of his golf to @loopywalt's answer.
```
Nθ Input `d` as a number
Nη Input `f` as a number
Nζ Input `b` as a number
ζ Input `b`
X Raised to power
θ Input `d`
× Multiplied by
η Input `f`
⊖ Decremented
÷ Integer divided by
ζ Input `b`
⊖ Decremented
⊕ Incremented
÷ Integer divided by
ζ Input `b`
⁻ Subtract
η Input `f`
‹ Is less than
ζ Input `b`
∧ Logical And
ζ Input `b`
› Is greater than
² Literal integer `2`
× Multiplied by
θ Input `d`
× Multiplied by
η Input `f`
⊖ Decremented
﹪ Modulo
ζ Input `b`
⊖ Decremented
⊕ Incremented
I Cast to string
Implicitly print
```
[Answer]
# JavaScript (ES7), 54 bytes
A port of [loopy walt's xnor-optimized answer](https://codegolf.stackexchange.com/a/261193/58563).
```
(d,f,b)=>~~(b**-~(d*--f/--b)/(b+(b<=f|b<2)))*(d*f%b+1)
```
[Try it online!](https://tio.run/##ZZExTsMwFIb3nsILip0mLrHdtNCmTCwMMDBWHey2LkVVXSUFCQE9ARILI70H5@kFOEJwagy2LP3y8OW9588v9/yRV9NyudmmazWb17Ko4SyRiUDFaLeDIo7THZzFaSo7aSpQB4o2FMNCvoghQQjF@ps8Ee0M1YNxC4AxyJImRJ9gkjiEBoT5hJj4hAaE@YSa@IT5hJlYQgJDEhiSwJBYQ@YTGhD3dmINz3zSTD51kFHMcoto4EgDRxo4UuvY9wkNiO7qOsSE9HzUrNqdbSTzv@eyQJIFkiyQZFby/7XMWmbUR96amPXsZz5qpNxGE9LNnQXnzSQNic90qFvWN2W5@yN@W3t6O61JC0tVXvLpHeSgGIFnXVTOK1AAjjdqA9FAA/Ww1UBCjDE/gqlaV2o1xyu1gFe3N9e42pbL9WIpnyBHSVOfmCnFsfcCRN9f74fPD31G4BxEh/1bpAe9ovoH "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES11), 50 bytes
An alternate version taking Bigints as input.
We have to use a ternary operator because we can't add a Boolean to a Bigint. This is however an opportunity to invert the sign of the division which allows to save one byte on the multiplication by just using `~`. And more importantly, we don't have to round the result of the division anymore.
```
(d,f,b)=>b**-~(d*--f/--b)/(b>f&b>1?-b:~b)*~(d*f%b)
```
[Try it online!](https://tio.run/##ZZExTsMwFIb3nsILxI4Sl9huWlollZAYYICBseoQt3UJKkmUFCSE6AmQWBjhHpynF@AIwakx2LL0y8Pn914@v9xlj1mzqPNqGxblctWKpIXLQAQcJSn3/XAHl34Yin4YctSHPBXHPI2mIR/vOPK7S3HEUTuZ9QCYgSjoQuQJ5oFBqEOYTYiKTahDmE2oik2YTZiKJsQxJI4hcQyJNmQ2oQ4xv0604alNusknBlKKUawRdRyp40gdR6odRzahDpFdA4OokKGNulWbs5Vk/Pdc5kgyR5I5kkxL/r@WacuI2shaE9Oeo8hGnZTZqEIGsbHguJskIbGZDDXLRqosNn/Eb@tQbqc372FR1ufZ4hZmIEnBsyyqVw1IQIarsoJoIkH5sJVAQIxxhu@zCp7l64tiiw6Xi7Joys0Kb8o1vLy5vsLNts6LdS6eYIaCrjdQE5PDnCnwvr/e9h/v8vTAGHj7z1dPDnpB7Q8 "JavaScript (Node.js) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 235 bytes
```
import Data.Bits
import Data.List
import Data.List.Ordered
o=0::Int
c d f b=length$fst$span(>[])$tail$scanl(\p n->nubSort$filter(all$(f>=).popCount)[sort$zipWith(.|.)q$bit<$>m|m<-permutations n,q<-p])[repeat o]$mapM id$[o..b-1]<$[1..d]
```
[Try it online!](https://tio.run/##ZcyxToRAEIDhnqeYYgpIZHNYmQtQqI2JxsLCAimGY5GJu7N7u0Nj7t3x7Exsvz/5V8pf1rl9Zx9DUngkJXPPmou/8MxZ/4F5TbNNdi5Cdzgen0SLE8ywwNQ5K5@64pIVcyQp@2GsUIkd5hOJKz8iSN3LNr1dh7iwU5tKcg7Lpe8qE0N8CJtoNeTf/s3xnXUtzcVUZ5xYW@z9xbd1tMlvSspBMsjN@SpjNSQbLSmEET3FF@AZh2DMVDdji0NjzDzunli6mFgUT3ALd9Ac9h8 "Haskell – Try It Online")
# [Haskell](https://www.haskell.org/), 251 bytes
```
import Data.Bits
import Data.List
import Data.List.Ordered
o=0::Int
c d f b=length$fst$break null$tail$scanl(\p n->nubSort$map sort$filter(all$(f>=).popCount)[zipWith(.|.)m q|m<-map(map bit)$permutations n,q<-p])[repeat o]$sequence$replicate d[o..b-1]
```
[Try it online!](https://tio.run/##ZYwxT8MwEEb3/IobPCQSsVomVDUdgAUJiYGBIXS4JJfmVPvs2JcF9b@HdENi@/T0vTdhvpJz68o@hqTwior2mTUXf8E7Z/0H7EcaKNFQhGZ3OLyJFj0MMELXOJKLTmbMarpEeAVZnDOK7EzuUVz5HUHqkyzd51Y0HiPk@xjZKaUSt3M5nprKxhBfwiJatT8cv1in0t5s5WG@@WO9aeVd7VgrEyn5RVE5SAZ5mI91PFdtokioEM4m07yQ9GQ25LhHJRjaYG1X78@rR5YmJhY1PTzCE@x36y8 "Haskell – Try It Online")
[Answer]
# Python3, 877 bytes
```
from numpy import*
from itertools import*
U=lambda D:[''.join(j)for k in permutations(D,len(D))for j in product(*k)]
I=lambda P,n,b:sorted({int(i,b)for i in P})[:n+1]==[*range(n+1)]
def F(d,f,b):
q,R,S=[([['0']],0,[])],[0],[]
while q:
D,n,C=q.pop(0)
if len(D)==d and all([f==len(i)for i in D]):R+=[n]
N=base_repr(n+1,base=b).zfill(len(D))
if N in C:q+=[(D,n+1,C)]
else:
if len(N)>len(D)and len(D)<d:D+=[['E']]
p=U(D)
for P in p:
if P!=N and(P[:-1]==N[:-1]or P[1:]==N[1:]):
V=N[0]if P[1:]==N[1:]else N[-1]
D=[[j for j in i if j!='E']for i in D]
if len(D[-1])<f:
if(Y:=[*D[:-1],D[-1]+[V]])not in S and I(u:=U(Y),n+1,b):q+=[(Y,n+1,u)];S+=[Y]
elif len(D)<d:
if f>1 and(Y:=D+[['0',V]])not in S and I(u:=U(Y),n+1,b):q+=[(Y,n+1,u)];S+=[Y]
if(Y:=D+[[V]])not in S and I(u:=U(Y),n+1,b):q+=[(Y,n+1,u)];S+=[Y]
return max(R)+1
```
[Try it online!](https://ato.pxeger.com/run?1=pVTNbtNAEBbiVD_FtBfvJm4U_zQNpttLDVIvUdSqlSJjIQfb1KljO7ZTKIgn4dILvArvwNMwM96EnkEr69udn2--nfXu95_1Y3dXlU9PP7Zddjz9_XKdNdUayu26foR8XVdNNzDYlHdp01VV0e7NN6qI18skhsAPTXO0qvJSrGRWNXAPeQl12qy3XdzlVdmKwCrSUgSS3St2N1Wy_dCJwb2MjMsd1dwqraXfIn-aiK952YncWnJSTknzbzL0y6EdKRUOmrj8mApcIUGSZvBWJFaG0b4BG-vKulahCENzbEaRNbbCSEZWOMYvMuDTXV6ksMFACLDghdqM6qoWY4mGPINeqlIJxCV-RSHCTCmy5n-lBJH0r4YqLJEPZmoZt-n7Jq0bEmTRSi3l6EuWY7beek8-o-QLf4Op2BUKvpBEkRZtSoJ2AmbyvM8jDf3sLPEDTAvNN7gnCq3VDZppRrLm3FbmIJL5oZrRBsQ89I-pYzNGCgxtn9cIso-HW1yOI0p75iRNMAsxqw8KsPgK9keYU5nVoSI9z_rSx-76SNnyLNNl0CwWPh5ewGIsdg_D2yiSZdVR_jU3_VJsfdzcQnKH8Ey5XwtebWX0-hqXC10pLfZnhh3a14Hs3Ob9Y71gyH-C9V91tHbi-meeJu22TQnr-LO4kkNb37oXv1pQcHR0ZIMNDtgGoavRY3RoMLoaPUaXBqPH6NEwHM3jaB5H8zAL-4mnR8pzmOcVI8aNDYeJ7InhaiZXM7mayWWmKaOr0YMTg_WAc8oTlEiRRDXxDE9TeZrK01QeU2Etj7lslycsw2O2qc0TJCEXDedkghInGAKOw7MJuGSakmlCstl5eopNNfb_Jt5GfMXErCpTC9pRWxd5J8x3pSnxGhwMHqwGj2Ed1wIfHgtyHYA39yBuW3z-8IkZPEhQChqjbuh1Mru07VqoyZ-Ysj_P3Wv6Bw)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 19 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
<*I<‰>`ŠmID¹2‚›P-÷*
```
Inputs in the order \$f,d,b\$.
Port of [*@Neil*'s Charcoal answer](https://codegolf.stackexchange.com/a/261196/52210), so make sure to upvote him as well!
[Try it online](https://tio.run/##ASwA0/9vc2FiaWX//zwqSTzigLA@YMWgbUlEwrky4oCa4oC6UC3Dtyr//zYKMwoxMA) or [verify all test cases](https://tio.run/##LY7PSsNAEIfv@xRrvNgSwZ2dbiJUe2g8ePFPUWlvsW2EHqSSiigo5OQDePTkVQrFm@KlkODVh8iLxJ1xGNhvsjP75TdfXI5nWfN497CZnicX@aJVvqfBdK9ah1d0jP2h6@cXHfTKVdp026NuXXzspz9v16OkXP1@QV281sX3yXb12W6S3vB0FuityTzPs8ltK6iWQ/95eNQ/HgwO@mehzu5v/CCb6mq90QqewsZoo0EbRbRCZAIV0wqRaamYyEQqBeIB8YB42MJz8vyT3gF7dpl@b0cBi4xTVkxWTFZMlk0x0wpRdxTn0RBx4yPSJqkcKhQVigpFhazy/0J2GcsNx0C2xYYbL6ERFXScj@j8igbgzmlLVzFdOYrNwyj6Aw).
**Explanation:**
Formula: `(d*(f-1)%(b-1)+1)*((b**(d*(f-1)//(b-1)+1))//(b-(b>f)*(b>2)))`
```
< # Decrease the first (implicit) input `f` by 1
# STACK: f-1
* # Multiply it to the second (implicit) input `d`
# STACK: d*(f-1)
‰ # Divmod it by
I< # the third input `b` minus 1
# STACK: [d*(f-1)//(b-1), d*(f-1)%(b-1)]
> # Increase both values in the pair by 1 (let's call them [A,B])
# STACK: [d*(f-1)//(b-1)+1, d*(f-1)%(b-1)+1]
` # Pop and push them separated to the stack
# STACK: d*(f-1)//(b-1)+1, d*(f-1)%(b-1)+1
Š # Tripleswap the stack using the implicit third input `b`
# STACK: d*(f-1)%(b-1)+1, b, d*(f-1)//(b-1)+1
m # Take `b` to the power `A`
# STACK: d*(f-1)%(b-1)+1, b**(d*(f-1)//(b-1)+1)
I # Push the third input `b` again
# STACK: d*(f-1)%(b-1)+1, b**(d*(f-1)//(b-1)+1), b
D # And again
# STACK: d*(f-1)%(b-1)+1, b**(d*(f-1)//(b-1)+1), b, b
¹2‚ # Push pair [f,2]
# STACK: d*(f-1)%(b-1)+1, b**(d*(f-1)//(b-1)+1), b, b, [f,2]
› # Pop the copy of `b`, and check [b>f, b>2]
# STACK: d*(f-1)%(b-1)+1, b**(d*(f-1)//(b-1)+1), b, [b>f,b>2]
P # Check if both are truthy by taking the product
# STACK: d*(f-1)%(b-1)+1, b**(d*(f-1)//(b-1)+1), b, (b>f)*(b>2)
- # Decrease the other `b` by this 0 or 1
# STACK: d*(f-1)%(b-1)+1, b**(d*(f-1)//(b-1)+1), b-(b>f)*(b>2)
÷ # Integer-divide `b to the power A` by this
# STACK: d*(f-1)%(b-1)+1, (b**(d*(f-1)//(b-1)+1))//(b-(b>f)*(b>2))
* # Multiply it to `B`
# STACK: (d*(f-1)%(b-1)+1)*((b**(d*(f-1)//(b-1)+1))//(b-(b>f)*(b>2)))
# (after which the result is output implicitly)
```
] |
[Question]
[
[Gemtext](https://communitywiki.org/wiki/GemText) is a very simple markup format used by the alternative web protocol Gemini. Write a Gemtext to HTML converter.
From the Wiki:
>
> A line of text is a paragraph, to be wrapped by the client. It is is
> independent from the lines coming before or after it.
>
>
> A list item starts with an asterisk and a space. Again, the rest of
> the line is the line item, to be wrapped by the client.
>
>
> A heading starts with one, two, or three number signs and a space. The
> rest of the line is the heading.
>
>
> A link is never an inline link like it is for HTML: it’s simply a line
> starting with an equal-sign and a greater-than sign: “=>”, a space, an
> URI, and some text. It could be formatted like a list item, or like a
> paragraph. Relative URIs are explicitly allowed.
>
>
> Example:
>
>
>
> ```
> # This is a heading
> This is the first paragraph.
> * a list item
> * another list item
> This is the second paragraph.
> => http://example.org/ Absolute URI
> => //example.org/ No scheme URI
> => /robots.txt Just a path URI
> => GemText a page link
>
> ```
>
>
This should produce this HTML tree (just the equivalent tree, not the exact formatting):
**EDIT** you don't need the `<ul>` tags to produce valid HTML
```
<h1>This is a heading</h1>
<p>This is the first paragraph.</p>
<li>a list item</li>
<li>another list item</li>
<p>This is the second paragraph.</p>
<a href="http://example.org/">Absolute URI</a>
<a href="//example.org/">No scheme URI</a>
<a href="/robots.txt">Just a path URI</a>
<a href="GemText">a page link</a>
```
All text must pass through. All of `<>"&` should be converted to HTML entities, even if they don't confuse browsers, to be safe
**EDIT**: For the sake of this question, you don't have to do 2nd and 3rd level headings
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins
[Answer]
# [Perl 5](https://www.perl.org/) (`-p`), 132 bytes
```
s,^((#)|(\*)|=> (\S+)|) *(.*?) *$,$t=$2?h1:$3?li:$4?a:p;"<$t".($4&&qq( href="$4")).">".($5=~s~[<>"&]~"&#".(ord$&).";"~ger)."</$t>",e
```
[Try it online!](https://tio.run/##XZBBT8MgFMfv@xSEkYbW2UbtLt3axpPRgwc3T04Ttr0VYlsYvCU7LP3oVhqzTE1IgN/v/3iAAVtP@95NPjgfhye@isJTXhC@WlyFp5BEPI5KP7EJw5zdlvImY3dlrTKWliIzMzpnSGPO0iDY7zmRFnY5ZSkNw5gWg5jmneve5gUN3jsajD3SdssCr2e0q8D6xTxhWNAJ9P2YLKVyxA9BJIitaisyOiOUQHbKOiRGWFFZYWQ8inyyVp4phGbYtdrn7IX9rXew0e329wH@rRLRZEkCR9GYGmJtq4Tcr52uDwjk9eVxyPzTz5q4jYTm4q1ea3QxHpE8HXxv4ZugPOsHaJZw/KEV@Nu1n6PhT760QaVb11@bbw "Perl 5 – Try It Online")
Another 132 bytes
```
s-^([#*]|=> (\S+)|) *(.*?) *$-"<".($t=(p,a,li,h1)[ord($1)%4]).($2&&qq( href="$2")).">".($3=~s~[<>"&]~"&#".(ord$&).";"~ger)."</$t>"-e
```
[Answer]
# Java + Android, ~~227~~ 206 bytes
```
l->l.map(s->android.text.Html.escapeHtml(s).replaceAll("^# (.*)","<h1>$1</h1>").replaceAll("^\\* (.*)","<li>$1</li>").replaceAll("^=> (.*?) (.*)","<a href='$1'>$2</a>").replaceAll("^[^<].*","<p>$0</p>"))
```
Accepts a `Stream` of lines as input and returns a `Stream` of lines.
[Try it online!](https://tio.run/##7VVbb9s2FH7XrzhQAluyHdreS4tY1pB1zbYC3YC6feoFoCXKYkqJGknlgia/PTuUVEW@VOnrABNBTB5@5zu3z/QVvaZnV/HXR54VUhm4wjMpDRckKfPIcJmT0cLZu9RGMZrZq6JcCx5BJKjW8JbyHL45gKuxa0MNflxLHkOGt97KKJ5vPn4Gqjbar7F2fcipuvunYIoaqYJVxR/U4DCEZPkozkJBMlp4@iykeayQkRh2a8ifJhOE6YgWzG497RPFCkEjdiGE5345AY@MfHfiBuk8PJ0HU/xwdzCfPo1alOAVCj92UcvBxiws7le/RVNIFUuWw9P5MDz9JZjSPa@PX4LPZGSxRXg6C6YFIvzHRVv5dq0geM40LBszkYnnnsD7lGvAP4zGaIw4QL7vRpMySLjSBgqq6EbRIiV4PUK04GjlhmX1OZeIVU/WXRbNIpnH2zTLEFJjivPplN3SrBCMSLWZwsVaS1EaBh/e/VWjdgB/S9BRyrIuQsm1NJqYWwNvSsyBYiiTPgH@YNl7HGll3zDbiq/uBNxESjiBNVX2EBimDbbwqYEJoUUh7ryqcz5JpHpNo9Rb3WkskcjSnJ8X2Fsj8sbpwXlwptOLWkS1dJ1awI2wKg030q0vrNIaZW/ZreIOKr4eJ3R0@SqlasX@LVkesYrPh29dESD8t5KLGAeEOaMCcnazbfc6Rd9wk/J8Ze4E8xA@qRgnMKs3RLB8Y1LP73goZkqVW25iZM3rtQ2pClD8muJEu9/Zbpi9HCewV9OkDde3cBg2ikIGu2V53O0FDhA8a@fYhAq2wG1gYbgZj7tYuyJMAiLEVpXb04XxOJa2heIJeAhawjAY7jLYZfuCOsIgnjsQZtFVWNUjYEKzDk34PM3mJ2gGz9Pgt6qfJ1zC7Pb3l7MZDAbYiaA6Xl5eHmKuPQKLeFU7cBjDvO7vIYe2xfFui63fTlrdKHGTVxMm7s@r9RyPF06fcCIZs0LanaWbzWe44L5SjI/Fn31vRRDA/Okiri8wlx@zbzX9BN/x5tBGbC3u3jzauTj9lu25YUovXsP9vR0aDOF5KXSyagruyWlPa4cD3KRcMPA6MrDj2p90D8VenvlaFz/s0cERPzh9ldu4B4vr7Ve06@Ns7@wPQf3/@JofX/Pja358zY@v@f/6NX/8Dw)
*Saved 21 bytes thanks to [Olivier Grégoire](https://codegolf.stackexchange.com/users/16236)*
## Explanation
```
l->l.map(
s->android.text.Html.escapeHtml(s) //Escape line using Android utility class
.replaceAll("^# (.*)","<h1>$1</h1>")
//Match headers
.replaceAll("^\\* (.*)","<li>$1</li>")
//Match list items
.replaceAll("^=> (.*?) (.*)","<a href='$1'>$2</a>")
//Match links (> is > after being escaped)
.replaceAll("^[^<].*","<p>$0</p>")
//If string does not start with <, then nothing has been replaced,
//so enclose entire line in paragraph element
)
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~104~~ 103 bytes
```
&
&
"
"
>
>
<
<
m`^
<p>
p>(#+)
h$.1>
p>\*
li>
p>=> (\S+)
a href="$1">
<(\w+).*
$&</$1>
```
[Try it online!](https://tio.run/##XY9BS8QwEIXv8yuGtoRuF1qKnmwb8CR68KDrrYjZ3dkm2DYhncX@@5oiy6owkHnvfZNJPLEZ1bIIEGpwFUQg4pvbCiSIjiuoQfThGD7eoXYSnEzj7QZ0kperaDPozdo0K4xp@xpChdrTqYmSMpJQp@3XdpNnkIi6SEq5LDHutJkwVABJHc3YIVws1oQn4ydGp7zqvHI6hyyQvQmeYRpWNdrA@av3d36igx2Pvy9oJGpmd1cUNIdP9pRb3xV4v59sf2bCt5fHlfkXP1ucDpqGa@7t3vKU88z4dA67VVjC@hI/0LCj@cftKLxu/IRaRuIb "Retina 0.8.2 – Try It Online") Works with multiple headers. Edit: Saved 1 byte thanks to @OlivierGrégoire. Explanation:
```
&
&
"
"
>
>
<
<
```
HTML encode everything.
```
m`^
<p>
```
Assume each line is a paragraph.
```
p>(#+)
h$.1>
p>\*
li>
p>=> (\S+)
a href="$1">
```
Fix up headings, lists and links.
```
<(\w+).*
$&</$1>
```
Add closing tags.
[Answer]
# [sed 4.2.2](https://www.gnu.org/software/sed/), 160 bytes
```
s!&!&!g
s!<!\<!g
s!>!\>!g
s!"!\"!g
ta
:a
s!^*\(.*\)!<li>\1</li>!
s!^#\(.*\)!<h1>\1</h1>!
s!=> \([^ ]*\)\(.*\)!<a href="\1">\2</a>!
t
i<p>
a</p>
```
[Try it online!](https://tio.run/##TZDBasMwEETv@oqVAybNwSZtT6ks0lNpDy2U9FQ3sIk3lqltGUkB/326SmJSEGj0ZjRa5Kk6nbxMZYrd8CRr4aWSZdqGi9as66tOWM8eHuMhoFgho@2inGeL8k6qttHlUuW8ychnEzfLM@ct8iKWQTn/3sIP21MIwTg6FEm5THR5r3LkcBCNGrRAlQ/6dJrBxjQeeHGWsGr6GhBRKKWEFqlIxOQHQ3BonA8woMPa4WCymFzwzbZh3ATqrqC3nHY3fK78X@Rpb/vq1gQpoz5QvyeQOhOFBhPCsMpzGvn/Wsqsq3N43nnbHgPB1@drzFxtNfnvFvzeUHcLOLuzwWdhDPB25GmQ3wwm2kqvP9bJOo2xF@o2NF7cmnju/jfiURTgjT22FezobDoUxQgeO/oD "sed 4.2.2 – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~243 215 210 194 193~~ 191 bytes
```
n=>n.split`
`.map(e=>`<${t={'#':'h1','*':'li','=>':'a'}[(s=e.split` `)[0]]||'p'}${a=t<'b'?` href="${s[1]}"`:''}>${s.slice(2-!a).join` `.replace(/./g,c=>`&#${Buffer(c)[0]};`)}</${t}>`).join`
`
```
[Try it online!](https://tio.run/##XVBNT@swELznVyy0wgkC58Gx1EHvXRAcOCDeqapkN93EBie2bBdVCvntZcOHEEg@zM7Ozo73Sb2oWAfj03nvtnhoxKEXVc@jtybJTPJO@RxFJZfzIYmBzdiC6Qt2xk4JWENAVIQUG1d5FPg5B7JY/VmvX1@ZZ@N8UCIt2YZdS9ABG3E8H@LqYj0eywVjY0UVj9bUmF@eH6mCPznTkwMP6K0ituRle1ZThJPZfPi3axoMeT35j1eyGJclBRsr@TmXyUPt@pigpt@AADmDR20i0FOgUW1N30L2RSWN0JhAcq@CaoPymmenpLSGOJOwm6rekS58cz/nI9LC7bcBnMDGKvIRFeiU/KIsca86b5G70JbwdxOd3SWE/w@3k@ZX@95BrDV2732oAN81wW1cijztE9ztKIaifUl/Wdxg94j7D7ZFCto/y2w6gyNX69q8yadzFMXV4Q0 "JavaScript (Node.js) – Try It Online")
As with most of my longer answers, I will golf this gradually.
Produces unreadable HTML, but still containing the same text. If this is disallowed, let me know and I will roll it back.
*-16 bytes thanks to @A Username*
[Answer]
# AWK, 171 bytes
```
awk '{if($1=="#"){$1="<h1>";$0=$0"</h1>"}else if($1=="*"){$1="<li>";$0=$0"</li>"}else if($1=="=>"){$1="<a href=\""$2"\">";$0=$0"</a>"}else{$1="<p>";$0=$0"</p>"}{print$0}}'
```
I'm learning AWK so probably can be done better.
Bugs:
* There are spaces after the opening tags
* Doesn't remove the URL (I've tried doing `$2=""`, but it breaks the lines)
] |
[Question]
[
Your task is to write a program or function
that determines whether a number is divisible by another.
The catch is that **it should give an answer as soon as possible**,
even if not all digits of the number have been given.
Your program should take an integer *D* ≥ 2
and then a series of digits as input.
These represent the digits of another integer *N* ≥ 1,
starting at the least significant digit.
At the first point that *N* either *must* or *must not* be divisble by *D*,
your program should output [the appropriate answer](https://codegolf.meta.stackexchange.com/q/2190/3808) and exit.
If the end of the input is reached,
it should output whether the full *N* is divisible by *D*.
Here is a list of acceptable input formats for *N*
(leave a comment if you think something that isn't included should be allowed):
* **Standard input**:
digits are given on separate lines;
*end of input* is EOF or a special value;
*exit* means that the function returns or the program exits.
* **Analog input**:
through e.g. keystrokes or ten buttons representing each digit;
*end of input* is a special value;
*exit* means that the function returns or the program exits.
* **Function with global state**:
called repeatedly with successive digits;
*end of input* is a special value;
*exit* means that the function returns a non-null value.
Note that if you use global state,
it must be cleared after a value is returned
or otherwise reset [such that the function works multiple times](https://codegolf.meta.stackexchange.com/q/4939/3808).
* **Curried function**:
returns either another function to be called with the next digit or a value;
*end of input* is a special value or calling the function with no argument;
*exit* means that the function returns an answer rather than another function.
* **GUI prompt or similar**:
displayed repeatedly;
*end of input* is "cancel" or equivalent, or a special value;
*exit* means that prompts stop appearing.
* **Iterator function**:
input is a stateful object or function that returns the next digit when called,
*end of input* is an exception or special value;
*exit* means that the iterator stops being called.
Input for *D* and the output
can be through any [acceptable standard method](https://codegolf.meta.stackexchange.com/q/2447/3808).
Test cases:
```
2; 6 => true
5; 6 => false
20; 0 3 => false
20; 0 4 => true
100; 1 => false
100; 0 0 => true
100; 0 2 => false
4; 2 4 => false
4; 2 5 => true
4; 2 [eof] => false
4; 4 [eof] => true
625; 5 5 => false
625; 5 7 2 => false
625; 5 7 3 6 => false
625; 5 7 3 4 => true
7; 9 3 4 [eof] => false
7; 9 3 4 5 [eof] => true
140; 0 3 => false
140; 0 4 5 [eof] => false
140; 0 4 5 1 [eof] => true
14; 4 5 1 4 [eof] => false
14; 4 5 1 4 1 [eof] => true
```
[Answer]
# JavaScript (ES6), 70 bytes
Input format: **Curried function**
A function that takes the divisor and returns a function that takes each digit or \$-1\$ for EOF. The second function returns either \$0\$ (false), \$1\$ (true) or itself (no answer).
```
p=>(q='',g=(d,t=k=z=!~d||(q=d+q,p))=>k--?g(d,t-=(k+q)%p<1):t?t-z&&g:1)
```
[Try it online!](https://tio.run/##jZJhb5swEIa/51dcIq3YiukChVbL5lSTtkmT@g/SfmDBEDcUE3CWtWv21zMbk0EYJUHiBOfn3veO4zH4GRSLnGfSTkXI9hHdZ3SG1tSySExRSCRd0Rc6/BO@vqpsOF6TDGM6W9n2bayPbYpW4zV@l31y8FTeSvvl4iKeOngvWSGBAsoIJLyQBMRGLsQTw0Bn8HsAsBBpIRJ2mYgYWZlCLRhDpm4L3pclKjXXOf18@Sh4iiwCFtbEg4WVQs4KxUQo0y/bJU8Yks8ZExFSJ8qHKs1oky4kF6mq06YAPELDUjFhaSyXhzSAXOZiC6Nvn7/fff0yhVTAk8gZhDzmshh9LKldGUPlWkoUSx5JhM3Z0Twp@yVNaTVYWFGmZxWRyezaXyJIiy3LqypNq3HvVfuDQdl7R@utxo0AC0EKASzIk@fRwYiXXwaGtF5Gp8SPIKxkqtLdYKD3iVyi4DlcQ/t6ICDzDQNsOL@Hi4KkYBXnTojmVLw6k/N6fZ2JQubgnPKtOBUm5@ip4PbqeWZet6u/bs7v9a052zlDz@vimnrXrq/n8Lt8m3o1d3M8ch93RepFn@C8N/q7MXN8MFBjmpZem/MPaHtv3mFv/f9VzTXFTnPOm76k2oeBvAZ3rPcfZyT/6e3/Ag "JavaScript (Node.js) – Try It Online")
### How?
Given a divisor \$p\$ and a dividend \$q\$ consisting of \$n\$ decimal digits, we compute the following expression for all \$0 \le k < p\$:
$$k\times 10^n+q \pmod p\tag{1}$$
For any \$x\ge p\$ there exists \$m\ge 1\$ and \$0 \le k < p\$ such that \$x=mp+k\$, leading to:
$$x\times 10^n+q \pmod p=\\
(mp+k)\times 10^n+q \pmod p=\\
(mp\times 10^n \pmod p)+ (k\times 10^n+q \pmod p)\pmod p=\\
0+(k\times 10^n+q \pmod p)\pmod p=\\
k\times 10^n+q \pmod p$$
Therefore, if \$(1)\$ is equal to \$0\$ for all \$0 \le k < p\$, it will also be equal to \$0\$ for any \$k \ge p\$ and the answer is *true*.
For the same reason, if \$(1)\$ is greater than \$0\$ for all \$0 \le k < p\$, the answer is *false*.
If the results of \$(1)\$ are mixed, we can't decide yet and need either more digits of \$q\$ or the EOF notification.
### Commented
```
p => ( // p = divisor
q = '', // q = dividend stored as a string, initially empty
g = ( // g() = curried function taking:
d, // d = next digit
t = // t = number of iterations yielding a non-zero value
k = // k = total number of iterations to process
z = // z = copy of k
!~d || // if d == -1 (meaning EOF), use only 1 iteration
// so that we simply test the current value of q
(q = d + q, p) // otherwise, prepend d to q and use p iterations
) => //
k-- ? // decrement k; if it was not equal to zero:
g( // do a recursive call to g():
d, // pass the current value of d (will be ignored anyway)
t -= (k + q) % p < 1 // test (k + q) % p and update t accordingly
) // end of recursive call
: // else:
t ? // if t is greater than 0:
t - z && g // return 0 if t == z, or g otherwise
: // else:
1 // return 1
) //
```
[Answer]
## Batch, ~~177~~ 169 bytes
```
@set n=
@set g=1
:l
@set/ps=
@if %s%==- goto g
@set n=%s%%n%
@set/ae=%1/g,g*=2-e%%2,g*=1+4*!(e%%5),r=n%%g
@if %g% neq %1 if %r%==0 goto l
:g
@cmd/cset/a!(n%%%1)
```
Takes `d` as a command-line parameter and reads digits of `n` on separate lines with `-` as the EOF marker. Outputs `1` for divisible, `0` if not. Explanation:
```
@set n=
```
Initialise `n` to the empty string.
```
@set g=1
```
`g` is `gcd(d, 10**len(n))`
```
:l
```
Begin a loop reading digits.
```
@set/ps=
```
Read the next digit.
```
@if %s%==- goto g
```
Stop processing at EOF.
```
@set n=%s%%n%
```
Prepend the next digit to `n`.
```
@set/ae=%1/g,g*=2-e%%2,g*=1+4*!(e%%5),r=n%%g
```
Update `g` now that `len(n)` has increased and calculate `n%g`.
```
@if %g% neq %1 if %r%==0 goto l
```
If `r` is non-zero then the `d` definitely does not divide `n`, because `g`, a factor of `d`, does not. If `r` is zero then we only know whether `d` divides `n` if `g` equals `d`, so if it isn't, continue the loop.
```
:g
```
Break out of the digit-reading loop here on EOF.
```
@cmd/cset/a!(n%%%1)
```
Calculate and implicitly output the result.
] |
[Question]
[
# I forgot towel day
[Sandbox link](https://codegolf.meta.stackexchange.com/a/16511/77963)
[PHP script for both examples (error, formatting the string)](https://tio.run/##pZHBT8IwGMXP9K/40ixhwASH8QSVgxqvJB48LAuprNuabGvTVqcIfzu2DAlDiAd32Lp87/feaytzuZ3OZC4BjUYeVdk7icIAMAXNS1kwKJnWNGOwpBVoQz@h5ia3wxXD8QShPTIO8IOougbmtOJLoFUCr4pXGVAwomaFfcPzI8yVyBQtSzeZv61WBdM77b1I2JMoUmc5u4OmEbLuJmcvQiUaCNT2Wysq/V1kFMZBOO436@v4yhZAuOcKpYpmJauMXlClbF8C7EMWNsC3igAOlk6M2DIXgCNCyBoPtVELxSSjxseA2/a9IV5bFYkRtlwqlO9xcj3x@PRH07@1f4NB7wt1eOqf1og8HrtRp0kE@6yhiZQ0OStvFbgJbCVXYu0KdDbACs3gxPDvLexphDboIkcucf8hWkAXd48BJ2@rz2zlcMzhuAk4IX4FHAFWvru27fYb)
[Corrected php script, the input is self explanatory](https://tio.run/##pZFBT@MwFITP9a8YWZVIIQs0iBME/sRKe6gi9DZ5SQxOYtkOXXbLb@86CVS0gDgQ5RDL872ZeTG12V7fmtpAnJ3NyVaP6WoZQxKcaoxmNOwcVYycWjhPT1grX4fLvyyzKyFekCSWNWvdQTW4752Hak3vVVuBUPIa684WDr5DXnP@AFXC1wzNbRWGUe570vppUD04UFuEW@XQtRzctMZvDm9OvWOoMRAX6M2UhJAEM@eZCnRlOF6AwgwYstSwZ4uys6Nb2be5V107hllbMvj56lIq74Y6tzeYtiFCs8D8GmOnOyIa666WWbxMjqfv8@zHRSyFXAzLKC1VDbfe3ZG1YVcp@I/RXcFRUMTYjRzEgvO6g1ylabqRp87bO8uGyUcScm98sjiVm6BKMyEDF@pEc5WeX83V9avm@DKcTk4W/8RMldFhjNVcZcPVbHJEeDaYLA0VH8oP@0EOITZDgNkzWIc/cTDw6wovtBDP4lMu/Yz7DrEHHMmjt8Ag31d/UGW35mUyGRwQ7wzeAEE@/rbt9j8)
[PHP script with more input comment/uncomment `$argv` to see different results](https://tio.run/##pVLfb9owEH5u/oqThQS0rBSqPbVZxdZMRa0AAR2aEIrcxEm8GttynDIY/dvZJWm7Aq36sMgPse77cd@ddaI35xc60eA0mxVq4gd32moAoZDyuRYM5ixNacwgoBJSS5ew4DbB4oqR2Rl89DWbPzo33cvX2uRn/xYm/V51DCPPg04Pur3B7RhuutcejK@6owZ0x0Am/eH1CK68oQdfvW@d25EH/e/Iu5wMO4PCutns9kr1J@12gyRMCAV8Dr@y1AKXOrNcxkAhYgtYKBOmYBUECQvugUdgEwaCyRgT0cBmVIhljrpPgcoQqzwFJRlGFgLuGJ6AZikDXkyFhZDpchwU2miWWkZDUBFeT4GiBmhq6JxZZiBSpnCLMhlYrmTRzMJQDeNnl4jbtJzp3tTauJFLJasWBlTyoOjuzpTJrFowkafCCQ2MitFxnld0tloJViYJVMhiJSKUf2MjQPKkPh4qfS4fqOChX8zOx7b9pcqMr0tlH@/PEfb3/28jF1@gfFaO41Qw96QYvfuSulaYT1uzRqt9WP6fzD6dNohD6mdIiQyN50xabMkYfHQusN9aYIoaIhrwIpmDHRYkCsjUdd01OU6t8Q3TjNoaAbIl364fkzWi3JlDkIfZahXunpxV@Pkz5vAz3o6O6n@cAx7VdtuYVvgsLx2UjnnkNZSWmoZvwnfzAcmbWOcNHDwCE/iadgQ/jvDEdpxH512e@x7vfxhbhCqpvibk8G30G1FextxqlwY7jD2DVwSEF2vbbP4C)
As you may know, May 25 is well known as [**Towel Day**](https://en.wikipedia.org/wiki/Towel_Day), because of the many uses a towel can have.
A simple extract of the book **"The Hitchhiker's Guide to the Galaxy"** (personally I took this book as an **"everyday guide"**) states:
>
> *"A towel is about the most massively useful thing an interstellar hitchhiker can have. Partly it has great practical value."*
>
>
>
If you need more information about towels check [**this SE.scifi answer**](https://scifi.stackexchange.com/a/11719/97479)
---
## The Challenge
Hopefully you will do this with a towel used as a blanket for your legs.
Write a full program or function in any valid programming language that takes two inputs
```
size Integer : #The size
message string : #A sentence
```
### How to draw a towel with these values?
**First using `size`**:
Draw a towel depending on the size input, [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") for our towel
```
width = 12*size
#the line that has the "bar" its always present with different sizes
Width is defined as:
from the first | to the second | has to be equal to size*12 including both ||
<- width->
[===| |====]
| 12 chars || 1 height starts here, just after the "bar"
| SIZE = 1 || 2
| || 3 height = 5*size
| || 4
| || 5 height ends here just before the first line |=======|
|==========|| # the lines with the #
|==========|| # are always fixed
""""""""""""| # it means, every towel
| | # always has this 5 rows
"""""""""""" # no matter the size
```
**Second, give it the `message`**
You have to give it a message, *what is a towel without a beautiful message sewed in golden thread?*
**Example 1**
```
input: size=1, message="a simple message can stay with size"
width = 12*size
#the line that has the "bar" it's always present with different sizes
#no words allowed at the bar level
[===| |====]
| a simple || 1 height starts here, just after the "bar"
| message || 2
| can stay || 3 height = 5*size
| with size|| 4
| || 5 height ends here just before the first line |=======|
|==========|| # the lines with the #
|==========|| # are always fixed
""""""""""""| # it means, every towel
| | # always has this 5 rows
"""""""""""" # no matter the size
```
**Example 2**
```
input size=2
message="Don't Panic and bring a towel to SE Programming Puzzles and CodeGolf"
The size is 2
That means 24 width and 10 heigth
<- 24 chars width ->
[===| |====]
| Don't Panic and bring|| 1
| a towel to SE || 2
| Programming Puzzles || 3
| and CodeGolf || 4
| || 5
| || 6
| || 7
| || 8
| || 9
| || 10
|======================|| # The lines with the "#"
|======================|| # always present and
""""""""""""""""""""""""| # adapted to
| | # the towel width
"""""""""""""""""""""""" #
```
**Accepted answer criteria**
* This is **codegolf** so normal rules apply.
**Rules**
* You are guaranteed that all the input strings will fit the size, so no input like `size=1; message="This string is just tooooooooooooooooooooo long to fit the width and height of your towel"`.
* The string format is up to you, if you want to center the substrings for example.
* **Word-breaks** are disallowed.
### Edits
I am truly sorry about any confussion, because the ansii towels i draw did not matched the parameters, added a [**PHP script for both examples**](https://tio.run/##pZHBT8IwGMXP9K/40ixhwASH8QSVgxqvJB48LAuprNuabGvTVqcIfzu2DAlDiAd32Lp87/feaytzuZ3OZC4BjUYeVdk7icIAMAXNS1kwKJnWNGOwpBVoQz@h5ia3wxXD8QShPTIO8IOougbmtOJLoFUCr4pXGVAwomaFfcPzI8yVyBQtSzeZv61WBdM77b1I2JMoUmc5u4OmEbLuJmcvQiUaCNT2Wysq/V1kFMZBOO436@v4yhZAuOcKpYpmJauMXlClbF8C7EMWNsC3igAOlk6M2DIXgCNCyBoPtVELxSSjxseA2/a9IV5bFYkRtlwqlO9xcj3x@PRH07@1f4NB7wt1eOqf1og8HrtRp0kE@6yhiZQ0OStvFbgJbCVXYu0KdDbACs3gxPDvLexphDboIkcucf8hWkAXd48BJ2@rz2zlcMzhuAk4IX4FHAFWvru27fYb) for you to check the expected outputs.
Also thank you to all the people who voted up and considered my first challenge :D.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~223~~ ~~210~~ ~~209~~ 204 bytes
```
def f(s,m):w=12*s-2;l=' |';print'[===|'+' '*w+'|====]';exec"j=(m+' ').rfind(' ',0,-~w);print l+'%*s||'%(w,m[:j]);m=m[j+1:];"*s*5;print(l+w*'='+'||\n')*2+' '*4+'"'*12*s+'|\n '+l+' '*w+'|\n ','"'*12*s
```
[Try it online!](https://tio.run/##PY5NawIxEIbv/RVDQGbzYamLvbjk1JZehR7VQ@pmNZJkZZOSKqF/fRtX2jkMMzzPMO/5Eo@9r8ex1R10VRCOrpJc1CzM68ZKhFIZm/NgfMSNlDIjR0CWOOayyR02@lvvyUlW7gbo49AZ31ZlFE9i/pPo/RYsxxkLOeOsSsJtVqcdbZx0mxNfrHYNYYE9383K8sRQljc5bz1SVk8PlxwJsluwArYekNv/IGUtheLPGLtqIYiCYNzZanA6BHXQsFceQlQXSCYeC7xqQh8mNWpvdYx6CEUw1nYmGj/BWpDX3mOEtfJmD8q38FlSHkBB7JO2pcPHG6yH/jAo525k/XW9Wh0m96Vv9XtvO0LHXw "Python 2 – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 375 bytes
This is the worst submission you will get, but at least I tried xD half of bytes are spaces though
```
(s,_,w=12*s-2,h=5*s)=>`
[===|${j=' '.repeat(w)}|====]
${[...Array(h)].map((g,i)=>_.split` `.reduce((a,b)=>((l=a.split`,`)[l.length-1]+b).length>w-1?a+','+b:a+' '+b,'').split`,`[i]).map(a=>` |${a?(r=a.length)<w?a+' '.repeat(w-r):a:j}|| `).join`\n`+
`
|${'='.repeat(w)}|| `.repeat(2)}
${y='"'.repeat(w+2)}|
|${j}|
${y}
`
```
[Try it online!](https://tio.run/##VZFPb@MgEMXv/hQoigTUGCmR9hItjVbbqtdIPaZRmTjEwcJggVsr/z57duJku1sOoJn3e49B1PAJqYy27QofNuayVReWxLvo1WT6kIqp2KkfD4mrR50tlVKn8bFWlFAZTWugYz0/n7CtVtn4uJRS/ooR9mzHV7KBlrFKWLS@y9Q622mi0bb5KA1jINYoMOYU3EWh@dJJZ3zV7YrJKl/ze/HYF5M55FTQfD3Dk@ApKOVfvqVd8eE6wCkJLhwS5ixi9C2B/@zng/Fr6iLyGczq8@l05TWXdbBev3mdZzq7R1D17ZU38m9nys8DNz7uFR39A3MUBnJQrzH1/zXi50xfyuBTcEa6ULEtmwoyegqedmQB3pYE/Iaso/UVAdKF3jjcyeszWcRQRWiaq7L4OBycSQP7G//tJbjtiPPse/IEk4Ek27TOkMakBJUhJXiSOtiT3nY7FA8GjZc/ "JavaScript (Node.js) – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~347 345 343 337 334 328~~ 326 bytes
```
b=>d=>`
[===|${M=" "[X="repeat"](c=12*b-2)}|====]
${[...Array(5*b)].map((a,b)=>d[Y="split"]` `.reduce((a,b)=>((l=a[Y]`,`)[l[Z="length"]-1]+b)[Z]>c-1?a+","+b:a+" "+b)[Y]`,`[b]).map(a=>` |${a?(r=a[Z])<c?a+" "[X](c-r):a:" "[X](c)}|| `).join`
`+`
|${"="[X](c)}|| `[X](2)}
${y='"'[X](c+2)}|
|${M}|
${y}
`
```
[Try it online!](https://tio.run/##XZDdioMwEIXvfQoJBZOqAQt7I53KPkDv24ZAJpq6lvhDdBdK22d3o2xvNjfJzHzn5CQ3/MGxdM0wpV1fmfkKs4ZDBQcVCAB4bh5HICERJyDODAYnImkJ2W6r0x17PT0CMtg8BOf80zm804@tZpK3OFCKiWbeS5yBjINtvFSFijtTfZfmPaXUAoqzVIliwooLEGu6evoiMs1krJm4yEOZZgXGJCGxzv0ekqW/SoSWbL0LfeDQL58XC@q85UWyfVmsuDj5zKljOebvykd/Lrxi/NY3nQpUrII/AwL/mKXyj13nm8cdIhKtQLz8wNpdZMf32SOvQM1l3429Ndz2Nb3SjNEIw7FpB2vC1owj1iZibP4F "JavaScript (Node.js) – Try It Online")
---
# Explanation :
```
b => // lambda function taking arg 1 : size
d => // arg 2 : message
` // begin string template for drawing
[===|${ // draw first part and now open literal
M = ' '[X='repeat'(c=12*b-2)] // set 3 variables, M, X , c to be used again
}|====] // close and draw the next part ====]
${[...Array(5*b)] // open and create an array of length 5 * b =width
.map(a,b=> // begin map function two args : a,b
d[Y='split']` ` // use d(message), split at whitespace, set to Y
.reduce((a,b) => // reduce to single value, arg 1 : a, arg 2 : b
((l = a[Y]`,`) // declare l and then find in l
[l[Z='length']-1] // set Z as length
+ b) // add value of b
[Z] // find the length
> c-1 ? // check if it's less than c - 1
a+','+b // then add `${a},${b}`
: a + ' ' + b // otherwise `${a} ${b}`
)[Y]`,` // close and split at comma
[b] // use b again
) // close
.map(a => // map over that arg 1 : a
` |${ // four space + | and open
a ? // if a is true or a truthy value
(r=a[Z]) // set value of r as a's length
< c ? // check if it's less than c
a+' '[X](c-r) // then draw a + space repeated c-r times
: a + ' '[X](c) // else draw a + space repeated c times
} // close
|| ` // add || and 4 spaces and close
) // end
.join`
` // and turn to string with new line as separator
+ // add to that
`
|{ // new line , 4 spaces and |
'='[X](c)} // repeat = c times
|| `[X](2)} // and repeat that 2 times
${ // new line + 4 space
y = '"'[X](c+2) // repeat " c + 2 times and set to y
}| // close and add |
|{ // add | and open
M}| // put M and close and add |
{y} // new line , 4 spaces and variable y
` // end with new line.
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 79 bytes
```
Nθ≔×⁵θε≔×¹²θδ←P←====[↓⁺³ε×"δ↖P↑⁺³ε←G↑²←⁻δ²↓²=↓↓↓¹×"δ↖↑⁺⁴ε====]F⪪S «×⸿›⁺ⅈLι⁻δ² ι
```
[Try it online!](https://tio.run/##jZHBS8MwFMbP7q945GIC9bCqF8WDOBnCJoE6EKaHrM26QJp0abrhxL@9vrSj0OLBHkLf916@75ck3QmXWqGb5sWUtX@ti410dM/uJ49VpXJD31QhK3obwZ5FIMf6NO4aGTaW9iDp3UJufShq7VXplPGdFAF5wG9NsMc7eWaPJgKu64peB@u@01mTD0KCce@8Kv/wXpUjiwEFt/ort6YbQ9QzylIZ3JGhhOhnjjgQkt4giONiwD39Ny4fkd4MDttey2cI3loHNCm18rR9i8TjQE4RkQBhDL4nF8NAh4FzJ4XHF2ud38PwQprc76hibHBQFiLPBsGvLxT@/jRNPJlZc@mBC6NSECaDTYgHAd4epcYVkmfgzuZOFEXo8Pp00rJqZ59sJudWb5urg/4F "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ≔×⁵θε≔×¹²θδ
```
Calculate the size of the towel.
```
←P←====[↓⁺³ε×"δ↖P↑⁺³ε←G↑²←⁻δ²↓²=↓↓↓¹×"δ↖↑⁺⁴ε====]
```
Draw the towel.
```
F⪪S «
```
Loop over each word of the message.
```
×⸿›⁺ⅈLι⁻δ² ι
```
Print each word without overflowing the width.
[Answer]
# [V](https://github.com/DJMcMayhem/V), ~~142~~, ~~128~~, ~~121~~, 119 bytes
```
:let @h=5*@a
:let @w=12*@a-2
O[===|@wá 4á=á]
:set tw=w
Vgq@hï{+@hjI |kf|@hjjyt=pjp+@hjkl@wr=Ùjlr|Ù@w««r"YkP0xÁ|
```
[Try it online!](https://tio.run/##K/v/3yontUTBIcPWVMshkQvCKbc1NALydI24/KNtbW1rpB3KDy9UMDm80Pbwwlguq2KgmpJyW6FyrrD0QoeMw@urtcUcMrI8FYCgRjo7rQbEy6ossS3IKtAGMrNzHMqLbA/PzMopqjk806H80OpDq4uUIrMDDCoON9b8/@@Sn6deolCQmJeZrJCYl6KQVJSZl66QqFCSX56aAyQVgl0VApwV1BSc3f8bAQA "V – Try It Online")
] |
[Question]
[
# Task
* Take input string separated by space.
* Sort the words alphabetically.
* Print them out vertically in 3 columns separated by space(s).
# Challenge
* All three column's heights should be as evenly weighted as possible.
* All three column's should be left aligned.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins!
# Example
If the input is:
```
"cat caterpillar pie frog elephant pizza",
```
The output should be:
```
cat elephant pie
caterpillar frog pizza
```
Please beware of cases, if input is:
```
"a b c d e f g"
```
Should be printed as:
```
a c e
b d f
g
# or
a d f
b e g
c
# and not
a d g
b e
c f
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~24~~ 17 bytes
```
TmoTT' §CȯmLTC3Ow
```
[Try it online!](https://tio.run/##yygtzv7/PyQ3PyREXeHQcucT63N9QpyN/cv///@vlKKQlKSQrJCYqJCamqqQppCukJGhkKWQqZCdrZCTo5CrBAA "Husk – Try It Online")
## Explanation
This was a surprisingly tricky challenge, as Husk currently lacks a builtin for breaking a list into a given number of parts.
```
TmoTT' §CȯmLTC3Ow Implicit input, say s="bbb a cc ddd e"
w Split at spaces: x=["bbb","a","cc","ddd","e"]
C3 Cut into slices of length 3: [["bbb","a","cc"],["ddd","e"]]
T Transpose: [["bbb","ddd"],["a","e"],["cc"]]
ȯmL Map length: [2,2,1]
These are the correct lengths of the columns.
§C O Sort x and split into these lengths: [["a","bbb"],["cc","ddd"],["e"]]
These are the columns of the correct output, without padding.
mo For each column,
T' transpose and pad with spaces: [["ab"," b"," b"],["cd","cd"," d"],["e"]]
T then transpose back: [["a ","bbb"],["cc ","ddd"],["e"]]
T Transpose the whole list: [["a ","cc ","e"],["bbb","ddd"]]
Implicitly join each row by spaces,
join the resulting strings by newlines and print.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
Ṣœs3ZG
```
[Try it online!](https://tio.run/##y0rNyan8///hzkVHJxcbR7n///8/Wj05sURdRwFEpRYVZObkJBaBuAWZqSAqrSg/HUSn5qQWZCTmlUCkqqoS1WMB "Jelly – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 148 bytes
*-6 bytes thanks to ovs.*
```
l=sorted(input().split())
n=-~len(l)//3
f=lambda l:[i.ljust(max(map(len,l)))for i in l+['']]
for i in zip(f(l[:n]),f(l[n:n*2]),f(l[n*2:])):print(*i)
```
[Try it online!](https://tio.run/##PYoxDoJAEEV7TjGdM4iQQLcJJyFbLMLKmGHYwJKohVdfsdDi5b/8vPCM06JNStJuyxrHAVnDHpHKLQgfS5m2l7eMikJV1WS@FTf3gwMxHZdy37eIs3scBDyqQojILyswsIKcu9PJ2ux/vDigR@mMWiq@okbz@ud5bSyRCStrxJwpJQc9XGGAETzcYPoA "Python 3 – Try It Online")
~~Workin' on it.~~ *Everything* I've tried makes the output lopsided...
[Answer]
# Mathematica, 115 bytes
```
Grid[Transpose@PadRight@TakeList[#,Last@IntegerPartitions[Tr[1^#],3]]&@Sort@StringSplit@#/. 0->"",Alignment->Left]&
```
try it on [wolfram sandbox](https://sandbox.open.wolframcloud.com/)
paste the following code and press shift+enter
```
Grid[Transpose@PadRight@TakeList[#,Last@IntegerPartitions[Tr[1^#],3]]&@Sort@StringSplit@#/. 0->"",Alignment->Left]&["cat caterpillar pie frog elephant pizza"]
```
[Answer]
# [Perl 5](https://www.perl.org/), 134 + 1 (`-a`) = 135 bytes
```
$.=(sort{$b=~y///c-length$a}(@F=sort@F))[0]=~y///c;@a=splice@F,0,@F/3;@b=splice@F,0,@F/2;printf"%-$.s "x3 .$/,shift@a,shift@b,$_ for@F
```
[Try it online!](https://tio.run/##XYnRCsIgFEB/5TIMNnBzFD0NwSd/IiLuRDdBpqgPtahPzxbsqYfDgXOCju5cCul4nXzMTzLy94MxplqnlynPBF@1kPz3hGyaS3/d/yCQp@Cs0kLSngrJToMY/9JxCNEu2VSHlnQJqvsJOsJomq3JAnePlNzA@ChkKQozbOgYrHMYIVgNJvoJtNNhxiVvZV0RENTHh2z9kkqLXw "Perl 5 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
#{.B3äζ»
```
[Try it online!](https://tio.run/##MzBNTDJM/f9fuVrPyfjwknPbDu3@/z9RIUkhWSFFIVUhTSEdAA "05AB1E – Try It Online")
---
```
# | Split on spaces.
{ | Sort aphabetically.
.B | Pad to max string length.
3ä | Split into columns.
ζ | Transpose.
» | Print with newlines.
```
[Answer]
# Javascript 181 175 bytes
```
f=a=>(a=a.split` `).sort().map(c=>(t[y]=[...t[y]||[],c],M[x]>(l=c.length)?0:M[x]=l,a[++y*3+x]?y:y=x++*0),M=[t=[x=y=0]])&&t.map(x=>x.map((c,y)=>c.padEnd(M[y])).join` `).join`
`
console.log(f("cat caterpillar pie frog elephant pizza"))
console.log("-------------------")
console.log(f("cat caterpillar pie frog frog123123 pizza"))
console.log("-------------------")
console.log(f("a b c d e f g"))
console.log("-------------------")
console.log(f("a b c d e f"))
console.log("-------------------")
console.log(f("a b c d e"))
console.log("-------------------")
console.log(f("a b c d"))
/*
f=a=>(a=a.split` `).sort().map(c=>((t[y] =t[y]||[])[x]=c,M[x]>(l=c.length)?0:M[x]=l,++y*3+x<a.length?0:y=x++*0),M=[t=[x=y=0]])&&t.map(x=>x.map((c,y)=>c.padEnd(M[y])).join` `).join`\n`
f=a=>(a=a.split` `).sort().map(c=>(t[y]=[...t[y]||[],c],M[x]>(l=c.length)?0:M[x]=l,++y*3+x<a.length?0:y=x++*0),M=[t=[x=y=0]])&&t.map(x=>x.map((c,y)=>c.padEnd(M[y])).join` `).join`\n`
*/
```
[Answer]
# [J](http://jsoftware.com/), 73 bytes
```
,.@(' ',"1[:>|:)@((](s,(s=.]{.1:),(1:{.~[-2*]))([:<.0.5+%&3))@#];.1])@/:~
```
I can explain this mess later if someone is interested.
[Try it online!](https://tio.run/##PY9JT8MwEIXv/RVWETiB1DQgLg5FYd/3nSoHN520pk4cOUkFLfSvh3iEennz5Pfm0/izTgrSY6RLOOnWHgsdSqjX9vt874e7oeNETuE5RY9Fc@Zz13N8PmeLfmdrPXJdp893WZftbKyubbtuuBIFzI/ccJMvarfVZoQmPU6JR345SYoWxGNNEkJjUdIAB5hcKiUMJSSguQScidEjNKAgH4us/E9nM2EdobkoSkGXOGFhAyRaGVoBK4mVBrVs7quGZx@fM5lok9KAHhgx1fbpCFSJ2etYFhP4tva42bPzRH@VRuPRp1oh9kyXoKw5z4YS9z4qVTXAi0pJwOqlVLh9JVMsXMsJnnWjp5AOwFh/W8QCzZ3IsXRfwQDwHw86Bdx/lGAMhodjYRq6tU8iG2H6IuNSI@KtYwSe/S6yCQCt6z8 "J – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~65~~ 64 bytes
```
≔⪪θ ηFη«⊞υ⌊η≔⟦⟧ηF⪪θ ¿¬№υκ⊞ηκ»FE³✂υ÷×ιLυ³÷×⊕ιLυ³I1«P⪫ι¶¿ιM⊕⌈EιLκ→
```
[Try it online!](https://tio.run/##ZZAxT8MwEIXn5lecMp2lMKBudEJlKSIIUTZgsNJLfMKxjXOJUBG/PdgpEqo6ePD53Xvfc2N0bLy283w7DNw53AfLgp8VlFCqCozaFK2PgEbBd7F6GgeDYwU1O@7HPk3T@@pv9fX9pF@lhXMfBdwCPnrBrR@dZIcPlaaLncmXTfFzyql1wHUFe8sNZd3OyR1PfCB84Z4G5AoeyHWSMFTiW6tLyc41kXpyQgdkdanf6kGwvE5YailVj1Y4RE5g955djijfXLlUy9ysoPYTnfnW@mv5gIz7j5RLpYCbZ@6M5E7z3GiBdCgGtlZHCEzQRt8BWQpGO0mT41EX89VkfwE "Charcoal – Try It Online") Link is to verbose version of code. Save 2 bytes if I don't have to handle the case of fewer than 3 words. There's probably a sorting "eval" I should be using... Explanation:
```
≔⪪θ η
```
Split the input on spaces.
```
Fη«⊞υ⌊η≔⟦⟧ηF⪪θ ¿¬№υκ⊞ηκ»
```
Sort the array.
```
FE³✂υ÷×ιLυ³÷×⊕ιLυ³I1«
```
Loop over three approximately equal slices of the array. (`I1` should really be `¦¹`.)
```
P⪫ι¶
```
Join the slice with newlines and print it without moving the cursor.
```
¿ιM⊕⌈EιLκ→
```
If the slice is not empty then move right by one more than the length of the longest word in the slice.
[Answer]
# 358 bytes of minified JS:
```
function f(b){let d=[,,,],e=b.split(" ").sort(),g=[],h=[];for(var j in e){var k=Math.min(2,Math.floor(j/Math.floor(e.length/3)));d[k]||(d[k]=[],g[k]=e[j].length),d[k].push(e[j]),2==k&&h.push(""),g[k]=Math.max(e[j].length,g[k])}for(var o in g)for(var p=0;p<g[o]+1;p++)for(var q in h)h[q]+=q>=d[o].length||p>=d[o][q].length?" ":d[o][q][p];return h.join("\n")}
```
```
function f(b){let d=[,,,],e=b.split(" ").sort(),g=[],h=[];for(var j in e){var k=Math.min(2,Math.floor(j/Math.floor(e.length/3)));d[k]||(d[k]=[],g[k]=e[j].length),d[k].push(e[j]),2==k&&h.push(""),g[k]=Math.max(e[j].length,g[k])}for(var o in g)for(var p=0;p<g[o]+1;p++)for(var q in h)h[q]+=q>=d[o].length||p>=d[o][q].length?" ":d[o][q][p];return h.join("\n")}
console.log(f("cat caterpillar pie frog elephant pizza"));
console.log(f("a b c d e f g"));
```
[Answer]
# [GNU sed](https://www.gnu.org/software/sed/), 92 + 1 = 93 bytes
+1 bytes for `-r` flag.
I haven’t golfed this at all, but it turned out to be a lot simpler than I expected.
```
s/$/ /
s/(\S+ ){1,3}/:&\n/g
:
s/:(\S)/\1:/g
/:\S/!bZ
s/: / &/g
t
:Z
s/: / :/g
t
s/ *:.*$//gm
```
[Try it online!](https://tio.run/##Nci9DsIgFAbQnae4Jk1j68@Xxu2@RreGBRWRBIEAU42vLqKJ4zlZX2vN6EAQGVs572h4TvvTC9xLDyO4NbcfICduBssZm/PybQL1rYrgP/nHDBr5OHaAedR6UYW00/GufKFoNbXQKVrnVKJbCqbluqp3iMUGn@shfQA "sed 4.2.2 – Try It Online")
[Answer]
# Bourne shell, 172 bytes
```
F=/tmp/t
<$1 tr \ \\n|sort>$F
N=$(wc -w $F|awk '{print $1/3}')
for i in 0 1 2
do
awk 'NR%N==C {print}' N=$N C=$i $F
done|awk '{printf "%s%s",$1,NR%3?" ":"\n"}'|column -t
```
It's more readable if formatted conventionally:
```
#! /bin/sh
F=/tmp/t
<$1 tr \ \\n | sort > $F
N=$(wc -w $F | awk '{print $1/3}')
for i in 0 1 2
do
awk -v N=$N -v C=$i 'NR % N == C {print}' $F
done |
awk '{printf "%s%s", $1, NR % 3 == 0? "\n" : " " }' | column -t
```
At the price of scanning the input once per column, it uses no arrays. A more complex awk program could open 3 files (one for every Nth word), processing the input in one pass. Then they could be concatenated and printed using the same last line.
The variable `N` isn't strictly needed, either; for the price of 4 bytes, we save scanning the input 3 more times.
] |
[Question]
[
### Input:
A string
### Output:
1) First we take remove character at the end of the input-string until we are left with a length that is a square (i.e. 1, 4, 9, 16, 25, 36, etc.)
So `abcdefghijklmnopqrstuvwxyz` (length 26) becomes `abcdefghijklmnopqrstuvwxy` (length 25).
2) Then we put this in a square, one line at a time, left to right:
```
abcde
fghij
klmno
pqrst
uvwxy
```
3) We fold it in all four directions, like this (we keep unfolding until the outer folded 'block' has no inner characters to unfold anymore):
```
m
qrs
l n
ghi
abcde
ihgf jihg
mn lk on lm
srqp tsrq
uvwxy
qrs
l n
ghi
m
```
Some things to note, when we fold outward, we basically mirror like this (numbers added as clarification, which represents the 'indexes' in these examples):
When we fold out the left side:
```
123 to: 321 123
fghij ihgf j
```
When we fold the right side:
```
123 to: 123 321
fghij f jihg
```
When we fold upwards:
```
3q
2l
1g
b to: b
1g 1
2l 2
3q 3
v v
```
When we fold downwards:
```
b b
1g 1
2l 2
3q 3
v to: v
3q
2l
1g
```
### Challenge rules:
* You can assume the input will always have at least 1 character (which will also be the output).
* Output format is flexible, so you can print to STDOUT or STDERR; return as string-array/list or character 2D-array; single string with new-lines; etc.
* The input will only contain alphanumeric characters (`a-zA-Z0-9`)
* You can also use a non-alphanumeric character to fill up the spaces in and/or around the ASCII-art output, like a dot `.`.
* Trailing spaces and a single trailing new-line are optional.
* We continue unfolding until the outer folded 'block' has no more centers to unfold.
### 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:
```
Input: abcdefghijklmnopqrstuvwxy
Output:
m
qrs
l n
ghi
abcde
ihgf jihg
mn lk on lm
srqp tsrq
uvwxy
qrs
l n
ghi
m
Input: A
Ouput:
A
Input: ThisIsATest
Output:
I
Thi
Is sI
ATe
I
Input: HowAboutAVeryLongExampleWhichIsAlsoAnEvenSquareInsteadOfOddOneAndExceeds64Chars
Output:
An
ch
xamp
i I
o E
quar
steadO
S e
s v
h s
E l
VeryLo
HowAbout
oLyreVA noLyreV
xampl Eg el Examp
hci Is hW As hi Ihc
nAo Ev sl ev so EnA
quare Sn Ie Squar
Odaetsn fOdaets
OddOneAn
steadO
S e
s v
h s
E l
VeryLo
xamp
i I
o E
quar
An
ch
Input: Lenght7
Output:
Le
ng
Input: abc
Output:
a
```
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), 75 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
l√u²m√lH»{ā;l⁾:A∫Ba{bIwFIWhFbž;FIbI@ž}};}¹K⁴{ē2\⌡±e{@Κ};⁴┼┼};0E{ē2\⌡№:h++}╚
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JTJDbCV1MjIxQXUlQjJtJXUyMjFBbEglQkIlN0IldTAxMDElM0JsJXUyMDdFJTNBQSV1MjIyQkJhJTdCYkl3RklXaEZiJXUwMTdFJTNCRkliSUAldTAxN0UlN0QlN0QlM0IlN0QlQjlLJXUyMDc0JTdCJXUwMTEzMiU1QyV1MjMyMSVCMWUlN0JAJXUwMzlBJTdEJTNCJXUyMDc0JXUyNTNDJXUyNTNDJTdEJTNCMEUlN0IldTAxMTMyJTVDJXUyMzIxJXUyMTE2JTNBaCsrJTdEJXUyNTVB,inputs=SG93QWJvdXRBVmVyeUxvbmdFeGFtcGxlV2hpY2hJc0Fsc29BbkV2ZW5QcmltZUluc3RlYWRPZk9kZE9uZUFuZEV4Y2VlZHM2NENoYXJz)
This expects the input on the stack, so for ease-of-use I added `,` at the start. That can cause issues if the input contains only numbers so [here](https://dzaima.github.io/SOGLOnline/?code=MTIzNDU2Nzg5JXUyMDFEbCV1MjIxQXUlQjJtJXUyMjFBbEglQkIlN0IldTAxMDElM0JsJXUyMDdFJTNBQSV1MjIyQkJhJTdCYkl3RklXaEZiJXUwMTdFJTNCRkliSUAldTAxN0UlN0QlN0QlM0IlN0QlQjlLJXUyMDc0JTdCJXUwMTEzMiU1QyV1MjMyMSVCMWUlN0JAJXUwMzlBJTdEJTNCJXUyMDc0JXUyNTNDJXUyNTNDJTdEJTNCMEUlN0IldTAxMTMyJTVDJXUyMzIxJXUyMTE2JTNBaCsrJTdEJXUyNTVB)
is a a test-suite for that.
70 bytes [`√lH»{ā;l⁾:A∫Ba{bIwFIWhFbž;FIbI@ž}};}¹K⁴{ē2\⌡±e{@Κ};⁴┼┼};0E{ē2\⌡№:h++}╚`](https://dzaima.github.io/SOGLOnline/?code=MTIzNDU2Nzg5MCV1MjAxRCV1MjIxQWxIJUJCJTdCJXUwMTAxJTNCbCV1MjA3RSUzQUEldTIyMkJCYSU3QmJJd0ZJV2hGYiV1MDE3RSUzQkZJYklAJXUwMTdFJTdEJTdEJTNCJTdEJUI5SyV1MjA3NCU3QiV1MDExMzIlNUMldTIzMjElQjFlJTdCQCV1MDM5QSU3RCUzQiV1MjA3NCV1MjUzQyV1MjUzQyU3RCUzQjBFJTdCJXUwMTEzMiU1QyV1MjMyMSV1MjExNiUzQWgrKyU3RCV1MjU1QQ__) works too, but as I only now implemented [`√` on strings](https://github.com/dzaima/SOGL/blob/c91057455cb528be96db5c5f5d3d93b9bdb06f80/P5ParserV0_12/data/charDefs.txt#L442-L443) and the documentation didn't mention that it would floor the length I won't count it.
Explanation:
```
creating a square from the input
l get the length of the input
√ get its square root
u floor that
² square it
m mold the input to that length
√ convert it to a square
creating the unfoldings of the square - the idea is to cut out the inner squares to a new array
lH»{ } (length-1)//2 times do
ā; push an empty array below ToS
l⁾ push ToS.length - 2 (ToS here is the square or the previous unfolding)
:A save a copy of that in the variable A
∫B } repeat that amount of times, saving iteration on B - cutting the inner square to the empty array
a{ } variable A times do
bIw get the b+1th row of the previous unfolding
FIW get the (current loops iteration + 1)th character of that
h swap the 2 items below ToS - so the stack now is [..., prevUnfolding, newArray, character]
Fbž at [current loops iteration; b] insert that character in the array
; swap the top 2 items - the stack now is [..., newArray, prevUnfolding]
FIbI@ž at [current loops iteration+1; b+1] insert a space
; get the now not empty array ontop of the stack
add the horizontal unfoldings
¹ wrap the stack in an array
K push the 1st item of that, which will function as the canvas
⁴{ } iterate over a copy of the remaining items
ē2\⌡ repeat (e++ divides by 2) times (default for the variable E is the input, which defaults to 0)
± reverse the array horizontally
e{ } repeat e times
@Κ add a space before ToS
;⁴┼┼ add that horizontally before and after the canvas
add the veertical unfoldings
; get the copy of the foldings above the canvas
0E reset the variable E to 0
{ } iterate the copy of the foldings
ē2\⌡ repeat (e++ divides by 2) times (default for the variable E is the input, which defaults to 0)
№ reverse the array vertically
:h++ add that vertically before and after the canvas
╚ center the canvas vertically
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~120~~ 109 bytes
```
AI§⪪IXLθ⁰·⁵.⁰ηFη⊞υ✂θ×ιηF⁴«AυεJ⁰¦⁰F÷⁺¹η²«F⁴«F⁻η⁺κκ§§εκ⁺μκ↷A⮌EεEε§ξνε¶»A⎇﹪ι²Eε⮌λ⮌εεA⎇‹ι²⁻⁺²⁺κκη⁻η⁺κκκ¿﹪ι²Mκ¹M¹κ
```
[Try it online!](https://tio.run/##RU7bTsJQEPwj/6lWAZWbeEF5siRgJMQnE1@Mb9pYxJDG0p72gMnyvvzD/sD5hDrbgOYkO7s7szPHb3g9v@M1y1Ienpz9oFCiCOhs5uwnZxIsKJUgOUDDqbPvnMrkdTuSlyFnm2c21VKCb5rBYDvixNlIj7BbgNngOCeoKKbZXllhwUoxHoUUcsK5jhYwTmElX1Nn39QOBfyaV8AlFco93jsTsaG4YiHlQkuCvmLlziiLEE2Pdzka@J@K3J8/lzkmA8BP87L0Dv2j41q9cXJ61my1O93z3sXl1XX/5nbwCw "Charcoal – Try It Online") Note that `A` has since been changed to `≔` and the link reflects this. Explanation:
```
θ Input string
L Length
X ⁰·⁵ Raise to the power 0.5
I Cast to string
⪪ . Split on the decimal point
§ ⁰ Take the first element (integer part)
I Cast to integer
A η Assign to h
```
Calculates `h = int(sqrt(len(q)))`. (`Floor` was yet to be implemented...)
```
Fη⊞υ✂θ×ιη
```
Extracts the `h` slices of length `h` from the input. (Actually I don't bother truncating the slices to length `h`.) I use a `for` loop rather than a `Map` because I need to `Assign` the result of the `Map` somewhere and this is nontrivial when dealing with a `Slice`.
```
F⁴«
```
The unfolding happens 4 times, once for each direction (down, right, up, left as coded). The loop variable for this loop is `i`.
```
Aυε
```
Take a copy of the sliced string.
```
J⁰¦⁰
```
Jump back to the origin of the canvas so that each unfold starts with the `h`-by-`h` square in the same place.
```
F÷⁺¹η²«
```
Repeat `(h+1)/2` times; once for each unfold, plus once for the original square. The loop variable for this loop is `k`.
```
F⁴«
```
Repeat 4 times, once for each side of the unfolded square. (I don't use the loop variable `l`.)
```
F⁻η⁺κκ Loop h-2k times, loop variable `m`
§εκ Take the `k`th row
§ ⁺μκ Take the `k+m`th column
Implicitly print the character
```
Print one side of the unfolded square. Since this is the `k`th unfold, the square's side is `h-2k`, and takes characters `k` away from the edge of the original square.
```
↷
```
Pivot ready to print the next side of the square.
```
Eε Map over the array (element `m`, index `n`)
Eε Map over the array (element `x`, index `p`)
§ξν Take the `n`th element of `x`
⮌ Reverse
A ε Replace the array with the result
```
Rotate the sliced string. (Yes, that's a `ξ`. I don't get to use it often!) `Eη` would also work for the outer `Map`. The rotation also has the convenient side-effect of truncating the array's width to `h`.
```
¶»
```
After printing the side, the cursor moves off the edge of the square. Printing one character fewer fails for squares of side 1 and is less golfy anyway. Having previously pivoted, printing a newline conveniently moves the cursor back to the corner.
```
﹪ι² Take `i` modulo 2
⎇ Choose either
⮌ε Reverse the array
Eε Map over the array (element `l`, index `m`)
⮌λ Reverse each element
A ε Replace the array with the result
```
Flip the square vertically or horizontally as appropriate.
```
⎇‹ι² If `i` < 2
⁺κκ Double `k`
⁺² Add 2
⁻ η Subtract `h`
⁺κκ Else double `k`
⁻η Subtract from `h`
≔ κ Assign back to `k`.
```
Calculate the displacement to the next unfold.
```
﹪ι² Take `i` modulo 2
¿ If not zero
Mκ¹ `k` across and 1 down
M¹κ Else 1 across and `k` down
```
Move horizontally or vertically to the next unfold as appropriate.
Here's a link to the 97-byte version obtained by making use of all the latest Charcoal features including `Floor`: [Try it online!](https://tio.run/##XZAxb8IwEIVn8issJltyK0Dt1AkJVaIqUkQZu4TkiN04NthOgFb57enFSRDtdLn43XfvXSoSm5pEte3SOZlr@qqMsTQ2Z7D0HXTuBT0xTmaPzwyLYC/RwVhCBSNx5QStOPlQMgV64mQnS3BUdio26p4Y@YkmAxvFgA@Tt6o87gydIbZrg3Ct/UrWMgP8Si2UoD1kuIaTBQuMyR1vaDZSV44KTmKFteCkwMUktlJ7uvRrncHlVqF7HZRlr3zpQLGsjd/KXHja/xi8bqEG64BukmM3O5SRduFEI4ENgRATlk4/9TT0TXQD7cDqxF7xmC4cZ4FDvfGVqfYKQ94HLvorjxLMNqqKsK4IeHnA8CarlOmJw1E2pobuDPPeE3r@G2Z02xBQDu5m5iP4f3q4JcRETdS0bbJPMzjkQn4VqtTmeLLOV/X5cv1uH2r1Cw "Charcoal – Try It Online") Link is to verbose version of code.
] |
[Question]
[
There was recently (a few years back) some buzz on [programming](http://www.i-programmer.info/news/167-javascript/3799-tetris-in-140-bytes.html) [websites](http://developers.slashdot.org/story/12/02/19/1351213/tetris-in-140-bytes) about an implementation of [Tetris in 140 Bytes](https://gist.github.com/1672254#file_annotated.js).
...
It turns out that although it is small, it is a simplified version of Tetris, and not even a complete implementation. Only the core logic function fits in 140 bytes of Javascript. To actually run it, you need another ~840 characters of HTML.
We can do better!
This challenge is to implement a complete version of "Binary Tetris" in as few tweets as possible.
**Binary Tetris Rules:**
* The program must display a playing field containing at least 5 columns and 6 rows of cells.
+ Any method of display may be used, as long as the blocks and the edges of the field are clearly marked.
* There must be at least two types of blocks: `#` and `##`. Additional block support such as `###` or angle blocks shaped like an L will get upvoted by me :P and the most complete game of binary tetris (the most blocks like the original and rotation features) will win my happiness and a possible bounty up 50 rep.
* New blocks are added to the field in the top row, and one block cell must occupy the center column.
* Blocks descend towards the bottom row at a fixed rate. Blocks must descend even without user input.
* When blocks touch the bottom of the field or a lower block, they stop falling and are fixed in place. A new block is added.
* When all the columns in the row are filled with blocks, the row is emptied, and all the fixed blocks above drop down one row.
* The program must respond to keypresses. There must be 3 unique keys that perform the following functions
+ shift current block left 1 column
+ shift current block right 1 column
+ shift current block down 1 row
* Each tweet may only have 140 characters. Using multi-byte characters that can be put in tweets is allowed.
* The rules for what can be in a tweet is simple. If you can tweet it you can use it.
* Interpreted languages follow the same rules. Each section must follow the specs. As long as no run time errors occur (and the rest is valid following the specs) your answer is valid
**Golfing Rules:**
Because the original implementation was "tweetable", this challenge requires the same. Entries must be able to be transmitted as a series of tweets (lines of 140 characters or less).
* The first tweet must contain the name of the compiler/interpreter, the name of the program, and any command line arguments
+ it will be saved as file "P0"
* The following N tweets must contain the program as a series of lines.
+ Each tweet will be stored in a file with the name T<n>, where n is 1..N
* Each line will be added to the previous lines and compiled or interpreted. It must produce a valid object file or program.
* The program does not need to be functional until the last line is added.
* The program will be run in the following manner *(pseudo-bash)*
```
interp,prog,args = split P0 /\s/
touch $prog
for file in ./T* do
cat $prog file > $prog
$interp $prog $args
die("FAIL") if $? #detect error
done
```
The interpreter must be a commonly available executable program that does not already implement Tetris.
**Scoring**:
Fewest Tweets, including P0. Ties broken by largest number of spare characters (140 \* num tweets - total character count).
**Example Entries**
```
chrome a.htm
<html><div id="output"></div></html>
<script>cool java script here</script>
```
Score = 3 (334 spare)
```
cc a.c ;a.out
main(){/*cool prog here*/}
```
Score = 2 (241 spare)
```
tetris
```
Score = 1 (134 spare) *if it were legal, which it's not*
# Special thanks
I was allowed to post this by Ashelly's consent [here](https://codegolf.meta.stackexchange.com/questions/2140/sandbox-for-proposed-challenges/487?noredirect=1#comment42067_487)
[Answer]
# Python 3, Score of 5 Tweets (242 spare, counting P0)
[](https://i.stack.imgur.com/53V0a.gif)
-19 bytes thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)!
The spare count does not take into account newlines from between tweets.
## Tweet 1 (Declaration, 12 bytes)
```
python3 t.py
```
## Tweet 2 (70 bytes)
```
import msvcrt as m,os;f=c=s=0;a=34636833;r=range;p=1<<32;t=30
while 1:
```
## Tweet 3 (129 bytes)
```
if m.kbhit()and b"\xe0"==m.getch():p=[p>>(not(a|f<<1)&p),p,p<<(not(a<<4|f>>1)&p),p>>5-5*(bool(f&p>>5)or p<t)][ord(m.getch())-77]
```
## Tweet 4 (113 bytes)
```
c+=1;print("\n".join("".join(".#"[1&(f|p)>>i*5+j]for j in r(5))for i in r(6))[::-1]);os.system("cls")
if c%t<1:
```
## Tweet 5 (134 bytes)
```
if f&p>>5or p<t:s=~s;f|=p;p=2-s<<26
else:p>>=5
for i in r(0,t,5):
if f|31<<i==f:b=bin(f)[2:].zfill(t);f=int(b[:-i-5]+b[t-i:],2)
```
## Full Program (449 bytes)
```
import msvcrt as m,os;f=c=s=0;a=34636833;r=range;p=1<<32;t=30
while 1:
if m.kbhit()and b"\xe0"==m.getch():p=[p>>(not(a|f<<1)&p),p,p<<(not(a<<4|f>>1)&p),p>>5-5*(bool(f&p>>5)or p<t)][ord(m.getch())-77]
c+=1;print("\n".join("".join(".#"[1&(f|p)>>i*5+j]for j in r(5))for i in r(6))[::-1]);os.system("cls")
if c%t<1:
if f&p>>5or p<t:s=~s;f|=p;p=2-s<<26
else:p>>=5
for i in r(0,t,5):
if f|31<<i==f:b=bin(f)[2:].zfill(t);f=int(b[:-i-5]+b[t-i:],2)
```
Does some evil bit point hacking and stores the field and piece in two integers. I'll try and post an explanation soon.
Note: This only runs on Windows, but it could be switched to Linux through `msvcrt` → `getch` and `"cls"` → `"clear"`. Additionally, character input doesn't work on Python's IDLE, so I'd recommend running it elsewhere.
[Answer]
# JavaScript (4 Tweets / 343 317 bytes / 243 spare)
Not quite sure about the requirements of the header & Tweets format, so please advise if it needs correcting. Still a bit more can be shaved off I'm certain.
### Tweet 1 - P0 (11 bytes)
```
chrome a.js
```
## Tweet 2 (82 bytes)
```
a=y=z=j=0,onkeyup=b=>R((k=b.keyCode-40)?z*2*(d=k+3?k+1?1:.5:2)&65|j*d&a||(z*=d):0)
```
## Tweet 3 (126 bytes)
```
R=d=>{d||(!(!y||a&j>>5)||(y>25?a=0:(31^31&(a|=j)>>y||(a=a>>y+5<<y|a&-1>>>-y-5>>5),y=0)),y-=5),y>=0||(y=30,z=12/(new Date%3+1))
```
## Tweet 4 (98 bytes)
```
j=z<<y;for(o="",i=30;i--;)o+=1<<i&(a|j)?"#":"_",o+=i%5?"":"<br>";O.innerHTML=o},setInterval(R,300)
```
# Run it in JSFiddle: <https://jsfiddle.net/CookieJon/7Lenhcge/>
(Click on the output pane to provide focus for keyboard events)
] |
[Question]
[
# Task
Given a ASCII diagram of a loop
*e.g.*
```
....................
......@@@@@.........
......@...@.........
.....@@...@@@@@.....
....@@........@.....
....@........@@.....
....@@@@@@@@@@......
....................
....................
```
And a location on the loop
*e.g.*
```
(7,1)
```
You must find the inside and outside of the loop
*e.g.*
```
00000000000000000000
00000011111000000000
00000011111000000000
00000111111111100000
00001111111111100000
00001111111111100000
00001111111111000000
00000000000000000000
00000000000000000000
```
# Specifications
* You may take input for the diagram as a string separated by newlines or obvious equivalent
* You will receive a coordinate on the loop (0 or 1 indexed) as part of your input. You may place your origin at any place you wish. You may take this coordinate in `(<row>, <column>)`, `(<column>, <row>)` or as the linear position on the string. You may receive these data in any reasonable method. All characters on the loop will be the same as the character at that index.
* Preferred output is a 2 dimensional array of truthy and falsy values, however strings of `1` and `0` separated by newlines or any obvious equivalent of the later two are accepted. The inside and outside must have different truth values but it does not matter which is which.
* A loop is defined as a group of characters such that they are all the same character (*e.g. `@`*) and so that every character in the loop has a path to the original character (The character at the coordinate of input) that only passes through that same character (Taxicab geometry *No diagonals*).
* The inside is all the loop itself and the places that cannot reach the edge of the diagram without crossing the loop.
* The outside is everywhere else
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")
# Test Cases
[PasteBin](http://pastebin.com/Sth0V6QT)
[Answer]
# MATLAB, ~~163 159 146~~ 78 bytes
```
function m=f(m,y,x);[~,i]=bwfill(m~=m(y,x),x,y,8);m=m*0;m(i)=1;m=bwfill(m,'h')
```
Thanks @rahnema1 for -66 bytes!!!
Now it does work on [Try it online!](https://tio.run/nexus/octave#jZC9boMwFIV3nuIuiTFiaNUMlSwP6VapVZdsUQYMJrEK1wibBJa@Or2GkDZSh2Ih@fh85/inlnuWrKeR3P5k0kxEbJaTu04WbrZu@n4s1sLO2KR@W4txpe6tfxROpewgoqiXTyIa5CNNV2WHuTcWQckyrtM@HbiAVYelbX2HmdfVAAvjIM8QrQelwTU6N6XRBRiE3esHZA78SQ@AmtacbrKWwlCaSrtoRYnKXgIAzrcGj8BOlhwWGqe6E@2nkaLeksdC6/t297Z9oXCIZe2xqzV62AS2q4qQouzzDwlxbhE1HfVs/ACFLk0oVHQB2@pjazss4OxAZfnnrPgo/vj2KjVFf5DqQqev4vpL1vGQ9jw8TrrhQkmVPAgVE8TpEdUCqvR6KS7GwrgmVnz8Bg "Octave – TIO Nexus") BUT a few adjustments were needed, as MATLAB and Octave are not entirely compatible.
### Explanation
First we make a binary image that just masks all the characters that are equal to the initial character. Then we determine the connected component the initial character is in.
```
% determine the connected component that is contains initial character
[~,i]=bwfill(m~=m(y,x),x,y,8); % i contains the indices of the connected component
m=m*0;m(i)=1; % create an image of the connected component
```
After that we create an image of that connected component and apply fill all the "holes" in the image.
```
m=bwfill(m,'h')
```
[Answer]
## MATLAB: 67 bytes
```
function A=f(A,r,c),A=bwlabel(A==A(r,c),4);A=imfill(A==A(r,c),'h');
```
A couple caveats:
* `A` is assumed to be a character array.
* Indices in MATLAB are 1-based, with rows indexed first. It is assumed these changes would be made to the function input (i.e. the question example would be called as `output = f(A,2,8)`).
* `bwlabel` and `imfill` are part of the Image Processing Toolbox.
] |
[Question]
[
Given an input of a list of blocks to drop at certain points, output the height
of the resulting "tower."
The best way to explain this challenge is by example. The input will be a list
of *2n* integers representing *n* blocks. The first integer is the block's x
position, 0-indexed, and the second is how wide the block is. For example, an
input of `2 4` represents the block (with x coordinates labeled below):
```
####
0123456789
```
Now, let's say the input is `2 4 4 6`. That is, one block at x=2 with a width
of 4, and one at x=4 with a width of 6:
```
######
####
```
Note that a.) blocks always "drop" from the very top of the tower and b.)
blocks will never "fall over" (i.e. they will always balance). So, an input of
`2 4 4 6 12 1` represents:
```
######
#### #
```
Note that the final block has fallen all the way to the "ground."
Your final output should be the maximum height of the tower at each x-value up
to the largest. Hence, the input `2 4 4 6 12 1` should result in output
`0011222222001`:
```
######
#### #
0011222222001
```
Input may be given as either a whitespace-/comma-separated string, an array of
integers, or function/command line arguments. The block positions (x values)
will always be integers 0 or greater, the width will always be an integer 1 or
greater, and there will always be at least one block.
Output may be given as a single string separated by non-numerical characters
(ex. `"0, 0, 1, ..."`), a single string listing all the digits (ex.
`"001..."`—the maximum height is guaranteed to be 9 or less), or an array of
integers.
Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes will win.
Test cases:
```
In Out
---------------------------------------------------------
2 4 4 6 12 1 0011222222001
0 5 9 1 6 4 2 5 1133333222
0 5 9 1 2 5 6 4 1122223333
0 5 2 5 6 4 9 1 1122223334
20 1 20 1 20 1 00000000000000000003
5 5 000011111
0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 4 123456789999
```
[Answer]
## Python 3, 89
```
def f(a):
h=[]
while a:x,w,*a=a;h[:x+w]=(h+[0]*x)[:x]+[max(h[x:x+w]+[0])+1]*w
return h
```
[Try it online](http://ideone.com/KJ3iNy).
The function takes and returns a list of integers.
```
def f(a): # input as list of integers
h=[] # list of heights
while a: # while there's input left
x,w,*a=a; # pop first 2 integers as x and w
h[:x+w]= # change the heights between 0 and x+w
(h+[0]*x)[:x]+ # left of x -> unchanged but padded with zeros
[max(h[x:x+w]+[0])+1]*w # between x and x+w -> set to the previous max + 1
return h # return the list of heights
```
[Answer]
## CJam, ~~34~~ 30 bytes
```
Lq~2/{eeWf%e~_2$:).*:e>f*.e>}/
```
Input as a CJam-style array, output as a string of digits.
[Run all test cases.](http://cjam.aditsu.net/#code=qN%2F%7B%3AQ%3B%0A%0ALQ~2%2F%7BeeWf%25e~_2%24%3A).*%3Ae%3Ef*.e%3E%7D%2F%0A%0A%5DoNo%7D%2F&input=%5B2%204%204%206%2012%201%5D%0A%5B0%205%209%201%206%204%202%205%5D%0A%5B0%205%209%201%202%205%206%204%5D%0A%5B0%205%202%205%206%204%209%201%5D%0A%5B20%201%2020%201%2020%201%5D%0A%5B5%205%5D%0A%5B0%202%201%202%202%202%203%202%204%202%205%202%206%202%207%202%208%204%5D)
Here are two variants of another idea, but it's currently 2 bytes longer:
```
Lq~2/{_:\3$><0+:e>)aeez.*e_.e>}/
LQ~2/{_:\3$><0+:e>)aeez.+e~.e>}/
```
[Answer]
## Ruby, ~~88~~ 87 bytes
```
f=->i{o=[]
(s,l,*i=i
r=s...s+l
o[r]=[([*o[r]]+[0]).max+1]*l
o.map! &:to_i)while i[0]
o}
```
[Try it online.](https://repl.it/BhJj/1)
Inspired by grc's answer, but in a different language and just slightly shorter.
**Explanation:**
```
f=->i # lambda with parameter i, expects array of ints
{
o=[] # output
(
s,l,*i=i # pop start and length
r = s...s+l # range is used twice, so shorten it to 1 char
o[r] =
[(
[*o[r]] # o[r] returns nil if out of bounds, so splat it into another array
+[0] # max doesn't like an empty array, so give it at least a 0
).max+1]*l # repeat max+1 to fill length
o.map! &:to_i # replace nil values with 0
) while i[0] # i[0] returns nil when i is empty, which is falsy
o # return o
}
```
[Answer]
## APL, 79 bytes
```
{⊃{o←(z←(≢⍵)⌈a←+/⍺)↑⍵⋄e←(z↑(-a)↑⍺[1]⍴1)⋄o+0⌈o-⍨e×e⌈.+e×o}/⌽(⊂⍬),↓(⌽2,0.5×≢⍵)⍴⍵}
```
Input as an APL Array, output as an APL array of digits.
[Answer]
### Java 1.8, ~~351~~ 329 bytes
Not thrilled with this first attempt - I'm sure the double looping, and all those Integer.valueOf's can be golfed some more.
```
interface B{static void main(String[]x){Byte b=1;int i=0,s,c,m=0,h,a=x.length,t[];for(;i<a;){s=b.valueOf(x[i++]);c=b.valueOf(x[i++]);m=m>s+c?m:s+c;}t=new int[m];for(i=0;i<a;){h=0;s=b.valueOf(x[i++]);c=b.valueOf(x[i++]);for(m=s;m<s+c;m++)if(t[m]>=h)h=t[m]+1;for(m=s;m<s+c;)t[m++]=h;}for(i=0;i<t.length;)System.out.print(t[i++]);}}
```
### Ungolfed
```
interface B {
static void main(String[]x){
int start, count, maxWidth=0, height, args=x.length, totals[];
Byte b=1;
for (int i=0; i<args;){
start = b.valueOf(x[i++]);
count = b.valueOf(x[i++]);
maxWidth = maxWidth>start+count ? maxWidth : start+count;
}
totals=new int[maxWidth];
for (int i=0; i<args;){
height=0;
start = b.valueOf(x[i++]);
count = b.valueOf(x[i++]);
for (int j = start; j<start+count; j++) {
if (totals[j]>=height) {
height=totals[j]+1;
}
}
for (int j = start; j<start+count; j++) {
totals[j] = height;
}
}
for (int i=0;i<totals.length; i++){
System.out.print(totals[i]);
}
}
}
```
] |
[Question]
[
This is a loose continuation of [my earlier challenge on constructing graphs](https://codegolf.stackexchange.com/questions/42890/construct-a-graph).
# Background
An eccentric artist has hired you to estimate the structural integrity of his sculptures. He creates his works of art by taking a bunch of cube-shaped magnets, and dropping them one by one into a huge pile. To better analyze his method, we use the following two-dimensional model. We start with an empty floor, and drop a magnet `#` at any integer coordinate, say `0`:
```
|
v
#
===============
0
```
If another magnet is dropped at `0`, it ends up on top of the previous one:
```
|
v
#
#
===============
0
```
Now, let us drop one more magnet at `0`, and then one at `1`:
```
|
#v
##
#
===============
0
```
As seen above, a falling magnet sticks to the *second* magnet it passes (the first one merely slows it down). The second magnet need not be directly below the first one, and a magnet on both sides still counts as one magnet:
```
# #
##|##
# v #
### #
# #
===============
0
```
The artists wants you to calculate the maximal vertical gap in the final sculpture, that is, the maximum number of empty spaces between two magnets on the same column, or a magnet and the ground below it. In the above picture, this number would be 3 (on column `2`).
# Input
A list of integers, representing the coordinates where the artist drops his magnets, read from left to right. You may assume that the coordinates satisfy `-1024 <= i < 1024` and that the length of the list is at most `1024`, if that helps.
# Output
The maximal vertical gap in the final sculpture. The empty sculpture has gap `-1`, and this case has to be included, since our sculptor is a dadaist.
# Additional rules
You may give a function or a full program. The shortest byte count wins, and standard loopholes are disallowed. Code with explanations is preferred.
# Test cases
```
[] -> -1
[0,2,1] -> 0
[0,0,0,0,0,1,-1] -> 3
[0,0,0,0,0,1,1,1,2] -> 4
[1,1,2,2,2,2,2,2,1] -> 2
[1,1,2,2,2,2,2,2,1,0,1,0] -> 2
[1,2,1,2,1,2,1,2,2,2,2,1,0] -> 3
[-1,-1,-1,1,1,1,0] -> 1
[-1,-1,-1,-1,2,2,1,1,2,2,2,1,0] -> 2
[-2,-2,-2,-1,-1,-1,0,0,0,1,1,1,2,2,2,3,3,4,4,5,5,5,6] -> 6
```
[Answer]
# Haskell - 217 185 182 Bytes
```
import Data.List
r g n m|m==n=max(head(g m)+1)((reverse.(0:).nub.sort$g(m-1)++g(m+1))!!1):g m|1<3=g m
j x=(-1)-minimum(0:(map(foldl r(\_->[0])x)[-1024..1024]>>=(tail>>=zipWith(-))))
```
Usage:
```
j [1,2,1,2,1,2,1,2,2,2,2,1,0]
```
This function builds up another function that returns a list of magnet y-positions for a given x-position. With it, it calculates the gaps for all x-positions -1024 .. 1024 and takes the maximum (Edit: now I'm taking the minimum, because gaps are negative: the lower the number the larger the gap).
[Answer]
# Javascript, 201 193
```
F=P=>{m=[];for(p of P){s=2;c=m[p]=m[p]||[];for(i=1e4;~i&&s;i--){if((m[p-1]||[])[i]||(m[p+1]||[])[i])s--;if(c[i-1]) s=0}c[++i]=1}g=-1;m.map(c=>{ d=0;for(i in c){g=i-d>g?i-d:g;d=++i} });return g}
```
>
> F([1,1,2,2,2,2,2,2,1]) === 2
>
>
>
Or readable version
```
F=P=>{
m=[]; // magnet positions
for(p of P){ // every dropped magnet
s=2; // initial speed
c=m[p]=m[p]||[]; // column where magnet is dropping
for(i=1e4;~i&&s;i--){ // continue until at floor or zero speed
if((m[p-1]||[])[i]||(m[p+1]||[])[i])s--; // magnet on either side, decrease speed
if(c[i-1]) s=0; // magnet is directly below
}
c[++i]=1;
}
g=-1; // maximum gap
m.map(c=>{
d=0;for(i in c){g=i-d>g?i-d:g;d=++i;}
});
return g;
};
```
[Answer]
## Python 2.7, 327
```
from itertools import *
s=input()
if s:m=min(s);l=[[] for _ in range(max(s)-m+3)]
for t in s:
i=t-m+1;r=l[i];c=[x or y for x,y in izip_longest(l[i-1],l[i+1])][::-1][1:];j=len(c)-c.index(1)-1-len(r) if any(c) else 0;l[i]=r+[0]*j+[1]
print -1 if not s else max([len(list(q)) if b==0 else 0 for k in l for b,q in groupby(k)])
```
Before white space golfing, it looks like this:
```
from itertools import *
s=input()
if s:
m=min(s)
l=[[] for _ in range(max(s)-m+3)]
for t in s:
i=t-m+1;r=l[i]
c=[x or y for x,y in izip_longest(l[i-1],l[i+1])][::-1][1:]
j=len(c)-c.index(1)-1-len(r) if any(c) else 0
l[i]=r+[0]*j+[1]
print -1 if not s else max([len(list(q)) if b==0 else 0 for k in l for b,q in groupby(k)])
```
Here's an explanation of the more complex lines, mostly for my own benefit.
```
l=[[] for _ in range(max(s)-m+3)]
```
This constructs an array of empty lists of length max(drops)-min(drops)+1 plus a placeholder on either side. I always want to write [ [ ] ]\*K to construct an array of empty lists, but that makes K pointers to the same empty list.
```
c=[x or y for x,y in izip_longest(l[i-1],l[i+1])][::-1][1:]
```
The function izip\_longest from itertools is like zip, but infills the shorter list with None in order to zip the lists together. The slicing [::-1] reverses the list of 0's and 1's from the "or" comparison. The list is reversed in order to use the index method in the next line, which finds the first instance of an element. Since the last element of a nonempty column must be 1, this is the first element in the reversed list and is ignored via the slice [1:].
```
j=len(c)-c.index(1)-1-len(r) if any(c) else 0
l[i]=r+[0]*j+[1]
```
First calculate the difference between the length of column i and the position of the second 1 in the adjacent columns. If the difference is positive, add that many zeros to column i before adding a 1. Any nonpositive number times [0] is the empty list.
```
max([len(list(q)) if b==0 else 0 for k in l for b,q in groupby(k)])
```
The function groupby from itertools splits a list into subsequences of consecutive elements. This line finds the max of the lengths of all the subsequences of zeros in all of the columns. It's necessary to cast each subsequence q to a list, because groupby returns a generator (like all the itertools functions) which naturally doesn't support a len method.
[Answer]
# Dyalog APL, ~~73~~ 70 characters
~~[`{y←⍬⋄⌈/¯1,,¯1-2-/0,x⊢⌸{y,←⌈/(1+y/⍨0=⍵),Y⊃⍨2⊃⍒Y←1 1,∪y/⍨1=⍵}¨|x-¯1↓¨,\x←⍵}`](http://tryapl.org/?a=%7By%u2190%u236C%u22C4%u2308/%AF1%2C%2C%AF1-2-/0%2Cx%u22A2%u2338%7By%2C%u2190%u2308/%281+y/%u23680%3D%u2375%29%2CY%u2283%u23682%u2283%u2352Y%u21901%201%2C%u222Ay/%u23681%3D%u2375%7D%A8%7Cx-%AF1%u2193%A8%2C%5Cx%u2190%u2375%7D%A8%u236C%280%202%201%29%280%200%200%200%200%201%20%AF1%29%280%200%200%200%200%201%201%201%202%29%281%201%202%202%202%202%202%202%201%29%281%201%202%202%202%202%202%202%201%200%201%200%29%281%202%201%202%201%202%201%202%202%202%202%201%200%29%28%AF1%20%AF1%20%AF1%201%201%201%200%29%28%AF1%20%AF1%20%AF1%20%AF1%202%202%201%201%202%202%202%201%200%29%28%AF2%20%AF2%20%AF2%20%AF1%20%AF1%20%AF1%200%200%200%201%201%201%202%202%202%203%203%204%204%205%205%205%206%29&run)~~
[`{y←⍬⋄¯1⌈⌈/,¯1-2-/¯1,⍵⊢⌸{y,←⌈/(1+y/⍨0=⍵),⊃1↓{⍵[⍒⍵]}∪y/⍨1=⍵}¨|⍵-¯1↓¨,\⍵}`](http://tryapl.org/?a=%7By%u2190%u236C%u22C4%AF1%u2308%u2308/%2C%AF1-2-/%AF1%2C%u2375%u22A2%u2338%7By%2C%u2190%u2308/%281+y/%u23680%3D%u2375%29%2C%u22831%u2193%7B%u2375%5B%u2352%u2375%5D%7D%u222Ay/%u23681%3D%u2375%7D%A8%7C%u2375-%AF1%u2193%A8%2C%5C%u2375%7D%A8%u236C%280%202%201%29%280%200%200%200%200%201%20%AF1%29%280%200%200%200%200%201%201%201%202%29%281%201%202%202%202%202%202%202%201%29%281%201%202%202%202%202%202%202%201%200%201%200%29%281%202%201%202%201%202%201%202%202%202%202%201%200%29%28%AF1%20%AF1%20%AF1%201%201%201%200%29%28%AF1%20%AF1%20%AF1%20%AF1%202%202%201%201%202%202%202%201%200%29%28%AF2%20%AF2%20%AF2%20%AF1%20%AF1%20%AF1%200%200%200%201%201%201%202%202%202%203%203%204%204%205%205%205%206%29&run)
```
First statement:
y←⍬ initialize semi-global variable y with an empty vector
Second statement, from right to left:
⍵ the vector of x coordinates
,\⍵ concat-scan: all prefixes of ⍵ of length 1, 2, ..., ≢⍵
¯1↓¨,\⍵ drop the last element of each prefix, lengths are 0, 1, ..., (≢⍵)-1
|⍵-¯1↓¨,\⍵ for each x: magnitudes of differences between x and its predecessors
{...}¨... execute the code in parens for each item of the argument
⍵ is now a single vector of differences from those described above
1=⍵ boolean mask, where are our neighbouring xs?
y/⍨1=⍵ select the ys corresponding to our neighbouring xs
∪y/⍨1=⍵ unique ys
{⍵[⍒⍵]} sort descending
⊃1↓ first of one-drop, i.e. get the second element if it exists, otherwise 0
0=⍵ which previous xs are the same as our x?
1+y/⍨0=⍵ select the corresponding ys and add 1 to them
⌈/ maximum of all the ys described so far
y,← append to the semi-global y
the result from {} will be identical to y
⍵⊢⌸{...} a matrix of ys, grouped in rows by x (which is now in ⍵) and zero-padded
¯1, prepend ¯1 to the left of each row
2-/ differences between consecutive horizontal elements, result is a matrix
¯1- negative one minus each element of the matrix
, ravel the matrix (linearize it to a vector)
⌈/ maximum; if the vector is empty, return ¯1.8e308, a very small number
¯1⌈⌈/ greater of ¯1 and the ⌈/ to avoid the very small number
```
[Answer]
# Java - 281 bytes
Pretty straight forward.
First it constructs the sculpture in an array
Then it finds the greatest gap.
```
int a(int[]b){
int[][]d=new int[9999][9999];
int g,r,t,y=-1;
for(int c:b){
c+=5000;
g=0;
for(r=9998;r>=0;r--){
if(r==0||d[c][r-1]==1){d[c][r]=1;break;}
if((d[c-1][r]==1||d[c+1][r]==1)&&++g==2){d[c][r]=1;break;}
}
}
for(int[] k:d){
t=0;
for(int i:k){
if(i==0)t++;
else{if(t>y)y=t;t=0;}
}
}
return y;
}
```
small -
```
int a(int[]b){int[][]d=new int[9999][9999];int g,r,t,y=-1;for(int c:b){c+=5000;g=0;for(r=9998;r>=0;r--){if(r==0||d[c][r-1]==1){d[c][r]=1;break;}if((d[c-1][r]==1||d[c+1][r]==1)&&++g==2){d[c][r]=1;break;}}}for(int[] k:d){t=0;for(int i:k){if(i==0)t++;else{if(t>y)y=t;t=0;}}}return y;}
```
] |
[Question]
[
# Pathological Sorting
Your boss has demanded that you develop a sorting algorithm to improve the performance of your company's application. However, having written the application, you know that you're unlikely to be able to make it significantly faster. Not wanting to disappoint your boss, you've decided to develop a new algorithm that works even better than \*sort on certain sets of data. Of course, you can't make it obvious that the algorithm only works on some cases, so you want to make it obscure as possible.
The objective of this contest is to write a sorting routine in the language of your choice that performs better on certain sets of data than others, with repeatable results. The more specific the classification that determines speed, the better. The algorithm must do sorting of some kind, so an algorithm that depends on the data already being completely sorted (as in, an algorithm that does nothing), or an algorithm that depends on the data being completely sorted in reverse, are both invalid. The sorting algorithm must correctly sort any set of data.
After presenting your routine, please include an explanation of why it only works on certain sets of data, and include test runs on at least one set of good (fast) data and one set of bad (slow) data. The point here is to be able to prove to your boss that you've stumbled upon a better way to sort, so more test data is better. Of course, you're only going to show your boss the test results from the good data, so the flaw in the required testing data can't be too obvious. If applicable to your language, please show that your algorithm is faster than your language's built-in sorting algorithm.
For example, one might submit an insertion sort algorithm, with the good data being data that is already nearly sorted, and bad data being completely random data, since insertion sort approaches O(n) on nearly-sorted data. However, this isn't very good, since my boss would probably notice that all of the testing data is nearly sorted to begin with.
This is a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"), so the answer with the most votes after 7 days (May 21) wins.
If no one beats me to it, I'd like to submit a community wiki answer that takes advantage of uniformly distributed data sets.
[Answer]
It's been a pretty long time, but I remember back in Algorithms 101 we were taught some sorting algorithm that used randomization. I wasn't a very good student so I don't really remember how it went or why it worked quickly on average.
Nevertheless, I've decided that this problem calls for a solution that uses randomization, which will hopefully work in my favor on average.
```
import random
def arrayIsSorted (arr) :
for i in range(len(arr)-1) :
if arr[i]>arr[i+1] : return False
return True
def rSort (arr) :
random.seed (42)
counter = 0
while not arrayIsSorted(arr) :
random.shuffle (arr)
counter+=1
print ("Sorted in %d iterations." % counter)
return arr
```
Since true randomization is important, I make sure to seed the RNG with the answer to Life, the Universe and Everything. After a bit of testing it turns out that that was a smart move! Check out how fast these 2 completely arbitrary lists get sorted:
```
rSort ([6,1,4,2,3,7,5])
rSort ([8,9,6,1,4,7,2,3,5])
```
Both of these get sorted in only 1 iteration - you couldn't possibly ask for a faster function than that!
Now, admittedly, some other lists produce slightly worse results...
```
rSort ([5,1,4,2,3,7,6])
rSort ([8,9,6,1,4,7,2,5,3])
```
These get sorted in 4,176 and 94,523 iterations respectively, which actually takes more than a second... but let's just keep that fact to ourselves so as not to distract anyone from how amazing this algorithm is!
Edit:
I've been asked to prove my algorithm's efficiency on a list of 100 items, so here you go:
```
rSort ([70, 6, 52, 97, 85, 61, 62, 48, 30, 3, 11, 88, 39, 91, 98, 8, 54, 92, 44, 65, 69, 21, 58, 41, 60, 76, 27, 82, 93, 81, 20, 94, 22, 29, 49, 95, 40, 19, 55, 42, 43, 1, 0, 67, 35, 15, 51, 31, 16, 25, 5, 53, 37, 74, 86, 12, 13, 72, 56, 32, 47, 46, 59, 33, 80, 4, 45, 63, 57, 89, 7, 77, 14, 10, 34, 87, 18, 79, 9, 66, 24, 99, 64, 26, 78, 38, 90, 28, 83, 75, 68, 2, 17, 73, 96, 71, 23, 84, 36, 50])
```
Even this long and completely arbitrary list gets sorted instantly! Truly I must have stumbled upon the best sorting algorithm in the world!
[Answer]
If you can create your own data, then it's pretty straightforward - get data that looks random, but includes a key for faster sorting. All other data uses the original sorting method, so the *average* times are better.
One easy way is to make sure each data item has a unique key, and then just hash the keys. Take for example a list with the numbers from 1-10,000, all multiplied by 16, and with a random number from 0-15 added to it (see **fillArray()** below). They will look random, but each one has a unique sequential key. For sorting, divide by 16 (in C the >>4 is very fast) and then just place the number into an array using the resulting key as the index. One pass and you're done. In testing, I found quicksort was 30 times slower on ten million numbers.
```
void fillArray(int *a,int len)
{
for (int i=0;i<len;++i)
a[i]=(i<<4)|(rand()&0xF);
// shuffle later
}
void sortArray(int *a,int len)
{
int key=0;
int *r=new int[len];
for (int i=0;i<len;++i)
{
key=a[i]>>4;
r[key]=a[i];
}
memcpy(a,r,len*sizeof(int));
delete[] r;
}
void shuffleArray(int *a,int len)
{
int swap=0, k=0;
for (int i=0;i<len;++i)
{
k=rand()%len;
swap=a[k];
a[k]=a[i];
a[i]=swap;
}
}
int qCompare(const void*a,const void*b)
{
int result=*((int*)a)-*((int*)b);
return result;
}
void main()
{
int aLen=10000;
int *a=new int[aLen];
srand (time(NULL));
fillArray(a,aLen);
// time them
long t0=0, d0=0, d1=0;
// qsort
shuffleArray(a,aLen);
t0=::GetTickCount();
qsort(a,aLen,sizeof(int),&qCompare);
d0=::GetTickCount()-t0;
// oursort
shuffleArray(a,aLen);
t0=::GetTickCount();
sortArray(a,aLen);
d1=::GetTickCount()-t0;
delete[] a;
}
```
Anything that has a unique key can be sorted this way - if you have the memory to store it, of course. For example, many databases use a unique numeric customer id - if the list is small/sequential enough this could be held in memory. Or some other way to translate a record into a unique number. For more info, research Hash Sorts, since that's what this is...
] |
[Question]
[
Create the shortest function to convert a string of [Roman numerals](http://en.wikipedia.org/wiki/Roman_numerals) to an integer.
The rules for each letter can be found at the [Wikipedia page](http://en.wikipedia.org/wiki/Roman_numerals). Letters above 1,000 will have parentheses placed around them to signal their higher value.
**Requirements:**
* Must convert Roman numerals 1 to 500,000
* Must complete in less than a minute
* Does not use built-in functions that could provide an advantage (Ex: A function that converts Roman numerals to integers)
* Is a function
The function does not need to support fractions. Any invalid input should return the number 0.
Shortest function wins. In the case of a tie, the one with the most votes wins.
## Test Cases
Input
```
III
```
Output
```
3
```
---
Input
```
IIII
```
Output
```
0
```
---
Input
```
XVI
```
Output
```
16
```
---
Input
```
(C)(D)(L)MMI
```
Output
```
452001
```
[Answer]
### C++: 914 855 chars
```
#include<map>
#include<string>
#include<iostream>
#include<sstream>
#define I istream
#define T(C) if(C)throw int(1);
#define X(c,v,f,m) D[c]=v;P[c]=D[f];M[c]=m;
#define S second
using namespace std;typedef map<char,int>R;R D,P,M;struct U{U():t(0),l(0),a(0){}int t,l,a;operator int(){return t+l;}I&d(I&s){char c,b;s>>c;if(c=='('){s>>c>>b;T(b!=')')c+=32;}if(s){R::iterator f=D.find(c);T(f==D.end())if(P[c]==l){l=f->S-l;a=0;}else{T(l&&(f->S>l))a=l==f->S?a+1:1;T(a>M[c])t+=l;l=f->S;}}return s;}};I&operator>>(I&s,U&d){return d.d(s);}int main(){D[' ']=-1;X(73,1,32,3)X(86,5,73,1)X(88,10,73,3)X(76,50,88,1)X(67,100,88,3)X(68,500,67,1)X(77,1000,67,3)X(118,5000,77,1)X(120,10000,77,3)X(108,50000,120,1)X(99,100000,120,3)X(100,500000,99,1)X(109,1000000,99,3)string w;while(cin>>w){try{stringstream s(w);U c;while(s>>c);cout<<c<<"\n";}catch(int x){cout<<"0\n";}}}
```
It could be compressed further.
```
> ./a.exe
III
3
IIII
0
XVI
16
(C)(D)(L)MMI
452001
```
Slightly nicer formatting: 1582 char
```
#include<map>
#include<string>
#include<iostream>
#include<sstream>
#define I istream
#define T(C) if(C)throw int(1);
#define X(c,v,f,m) D[c]=v;P[c]=D[f];M[c]=m;
#define S second
using namespace std;
typedef map<char,int> R;
R D,P,M;
struct U
{
U(): t(0), l(0), a(0) {}
int t,l,a;
operator int()
{
return t + l;
}
I& d(I& s)
{
char c,b;
s >> c;
if (c == '(')
{
s >> c >> b;
T(b != ')')
c = tolower(c);
}
if (s)
{
R::iterator f = D.find(c);
T(f == D.end())
if (P[c] == l)
{
l = f->S - l;
a = 0;
}
else
{
T(l&&(f->S > l))
a=l==f->S?a+1:1;
T(a>M[c])
t += l;
l = f->S;
}
}
return s;
}
};
I& operator>>(I& s,U& d)
{
return d.d(s);
}
int main()
{
D[' ']=-1;
X(73,1,32,3)
X(86,5,73,1)
X(88,10,73,3)
X(76,50,88,1)
X(67,100,88,3)
X(68,500,67,1)
X(77,1000,67,3)
X(118,5000,77,1)
X(120,10000,77,3)
X(108,50000,120,1)
X(99,100000,120,3)
X(100,500000,99,1)
X(109,1000000,99,3)
string w;
while(cin >> w)
{
try
{
stringstream s(w);
U c;
while(s >> c);
cout << c << "\n";
}
catch(int x)
{
cout << "0\n";
}
}
}
```
[Answer]
# Javascript, 317 chars
```
function f(s){for(r=/\(?(.\)?)/g,t=e=0;a=r.exec(s);l=a[0].length,d='IXCMVLD'.indexOf(a[1][0]),e=e||d<0||l==2||d*4+l==3,t+='+'+(d>3?5:1)*Math.pow(10,d%4+3*(l>1)));t=t&&t.replace(/1(0*).(10|5)\1(?!0)/g,'$2$1-1$1');return e||/[^0](0*)\+(10|5)\1/.test(t)||/(\+10*)\1{3}(?!-)/.test(t)||/-(10*)\+\1(?!-)/.test(t)?0:eval(t)}
```
Explaination:
```
function f(s){
// iterate over every character grabbing parens along the way
for(r=/\(?(.\)?)/g,t=e=0;a=r.exec(s);
// get a numerical value for each numeral and join together in a string
l=a[0].length,
d='IXCMVLD'.indexOf(a[1][0]),
e=e||d<0||l==2||d*4+l==3, // find invalid characters, and parens
t+='+'+(d>3?5:1)*Math.pow(10,d%4+3*(l>1))
);
// reorder and subtract to fix IV, IX and the like
t=t&&t.replace(/1(0*).(10|5)\1(?!0)/g,'$2$1-1$1');
return e||
/[^0](0*)\+(10|5)\1/.test(t)|| // find VV,IIV,IC,...
/(\+10*)\1{3}(?!-)/.test(t)|| // find IIII,... but not XXXIX
/-(10*)\+\1(?!-)/.test(t) // find IVI,... but not XCIX
?0:eval(t)
}
```
Without error detection it is only **180 chars**
```
function g(s){for(r=/\(?(.\)?)/g,t=0;a=r.exec(s);d='IXCMVLD'.indexOf(a[1][0]),t+='+'+(d>3?5:1)+'0'.repeat(d%4+3*(a[1].length>1)));return eval(t.replace(/(1(0*).(10|5)\2)/g,'-$1'))}
```
This works the same way, but here is better formatting:
```
function g(s){
for(r=/\(?(.\)?)/g,t=0;a=r.exec(s);
d='IXCMVLD'.indexOf(a[1][0]),
t+='+'+(d>3?5:1)+'0'.repeat(d%4+3*(a[1].length>1))
);
return eval(t.replace(/(1(0*).(10|5)\2)/g,'-$1'))
}
```
[Answer]
# [J](http://jsoftware.com/), 43 bytes
```
1#.2([*_1^<)/\0,~(*/\1,6$5 2){~'IVXLCDM'&i.
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DZX1jDSiteIN42w09WMMdOo0tPRjDHXMVEwVjDSr69Q9wyJ8nF181dUy9f5rcqUmZ@QrpCmoe3p6qiNzkHgRYUgcH18E29fX2TfC2TNM/T8A "J – Try It Online")
[Answer]
# Python3 - 144 chars
Follows [this](https://codegolf.stackexchange.com/q/16254/94065) question's rules, but its closed, so doesn't check for invalid input or support brackets, but thought I'd answer anyway.
```
def r(s):
if not s:return 0
l,v=[(s.split(x,1),6-i) for i,x in enumerate('MDCLXVI') if x in s][0]
return 10**(v//2)*(v%2*4+1)-r(l[0])+r(l[1])
```
Explanation:
This algorithm recursively finds the next largest letter, splits the string around it, then subtracts the left side's value and adds the right side's value.
Ungolfed:
```
def roman(string):
# base case. ends the recursion when either side string is empty.
if not string:
return 0
split_list, value =
[
# splits the string with the leftmost letter of 'MDCLXVI' successively.
# we take the first split string in the list (ignoring ones that didn't split)
# and use [0] and [1] as the left and right hand side parts to recurse.
# stores the split string ('1' means first split only), and the index of the
# letter used to split it in a tuple.
( string.split(letter, 1), 6-index )
# loops through each letter used in roman numerals.
for index, letter in enumerate('MDCLXVI')
# only stores split strings which actually split
if letter in string
# get the first split string tuple (so it was split with the highest value letter).
][0]
# takes the index of roman numeral letter and turns into its value (0->1, 1->5, 2->10).
return 10**(value//2)*(value%2*4+1)
# subtracts the value of the left hand side.
- roman(split_list[0])
# adds the value of the right hand side.
+ roman(split_list[1])
```
] |
[Question]
[
We once [made a Hexagony template without actually knowing it](https://codegolf.stackexchange.com/q/104604/78410). But after a bit of experience with Hexagony, it becomes apparent that it is not enough; sometimes the source code is too short for the given hexagon, and you get totally unexpected results.
So I came up with an idea: a template that gives a hint when the code is too short.
For the background: [Hexagony](https://github.com/m-ender/hexagony) detects the smallest hexagonal grid that fits the source code, and then fills each spot in the grid with each char in row-by-row fashion. E.g. the code
```
abcdefg@
```
contains 8 characters, and the smallest grid that can fit this is of size 3 (size 2 grid has only 7 spots)
```
. . .
. . . .
. . . . .
. . . .
. . .
```
so the code above is laid out like this:
```
a b c
d e f g
@ . . . .
. . . .
. . .
```
Now, to ensure that the code being written is actually laid out on the hexagon of size 3, the programmer has to make sure that the code has at least 8 characters; in other words, at least one of the spots marked `*` must be occupied by a command:
```
. . .
. . . .
* * * * *
* * * *
* * *
```
Math note: the number of spots in the hexagonal grid of size \$n \ge 1\$ is \$a(n)=3n(n-1)+1\$ ([A003215](https://oeis.org/A003215)). Since the Hexagony interpreter only has [hexagon sizes of 1 and higher](https://github.com/m-ender/hexagony/blob/b674f59a0c9e10c1867bd9cf34f676ba89f0fc1c/grid.rb#L66), \$a(0)\$ is undefined for this challenge.
## Task
Given a positive integer `n`, draw a hexagonal grid like the one above so that
* the first \$a(n-1)\$ spots are drawn with one kind of marker (e.g. `.`) and
* the rest are drawn with another (e.g. `*`).
For \$n=1\$, it is allowed to output any of the two possible grids (single `.` or single `*`).
For output format:
* You can choose the two markers, but the two must be distinct and not a whitespace character.
* Extra leading and trailing whitespaces, and whitespaces at the end of each line are allowed, as long as it doesn't break the hexagonal layout.
* Outputting as a list of strings (lines) is OK.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. Shortest code in bytes wins.
## Test cases
```
n=1
*
or
.
n=2
. *
* * *
* *
n=3
. . .
. . . .
* * * * *
* * * *
* * *
n=4
. . . .
. . . . .
. . . . . .
. . . . * * *
* * * * * *
* * * * *
* * * *
n=5
. . . . .
. . . . . .
. . . . . . .
. . . . . . . .
. . . . . . . . .
. . * * * * * *
* * * * * * *
* * * * * *
* * * * *
```
[Answer]
# [C (clang)](http://clang.llvm.org/), 92 bytes
Outputs a leading newline.
```
x,y,z;f(n){for(x=n,z=3*n*--n;~z;)printf(!y--?y=n-~n-abs(--x),"\n%*.s":z--<6*n?"* ":". ",x);}
```
[Try it online!](https://tio.run/##TY7NCoJAFIX3PsXtgjAzzhUiauE4@CJurDCEOoW28Ad9dRujRasD3@H8XORyr3Bb194OdnS1gp7qZ6t6Dzv6g4ERgVtGp19tg3etdoNIMXjIAqnOnRLpteUSsUk7zkaR/GRQsCHOOCW2vXbzGpL0qBooTVNEoZ/UhkCe9i5I7ukYNEm@Pv2mGD6@siVoF@B2zf2ZJUrwRuZoXj8 "C (clang) – Try It Online")
Some ideas are drawn from [@Quentin's answer](https://codegolf.stackexchange.com/a/104627/88546) to the other hexagon challenge.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 29 bytes
```
NθFθ«P^×*θ→→»‖B↓UM✂KA⁰±×⁶⊖θ¹.
```
[Try it online!](https://tio.run/##ZY49C8IwGIRn@ytCpzcSRUEc6uTH4lCR6izE9K0G81Hj24qIvz0GHB0O7rgH7tRVBuWliXHr2o52nT1jgDtfZI0PLBn2zgZlZ0i3QTuC4iTYUVt8QD7MBbvzRA5K3yMUlb5c6T9@sgobg4pWHRGGxryg2PinS1Up27W3VroaDkYrhD3ibWkMcMEmgu3wIgnhNzcXbIMqoEVHWKdjPEHTpHyc80WMszjqzRc "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Based on my golf to @KevinCruijssen's Charcoal answer to the linked question, except at the very end I replace all but the last `6n-6` `*`s with `.`s.
[Answer]
# [lin](https://github.com/molarmanful/lin), 76 bytes
```
1-.#n.n.>.n.<0\;.'.* <ls"\# \, ?s".n3*.n1- *1+ e*
1+.n +"# ".~ rep \.n5* pad
```
[Try it here!](https://replit.com/@molarmanful/try-lin)
For testing purposes:
```
1 10 .-> ( ; outln n\ out ).'
1-.#n.n.>.n.<0\;.'.* <ls"\# \, ?s".n3*.n1- *1+ e*
1+.n +"# ".~ rep \.n5* pad
```
## Explanation
Prettified code:
```
1-.#n .n.> .n.< 0 \;.'.* <ls .;
1+ .n + "# ".~ rep \ .n5* pad
( \# \, ?s ) .n3* .n1- * 1+ e*
```
* `1-.#n` input - 1 as \$n\$
* `.n.> .n.< 0` create palindromic range \$[0, n) \cup [n, 0]\$
* `\;.'` for each \$x\$...
+ `1+ .n + "# ".~ rep` repeat `#` \$x+n+1\$ times
+ `\ .n5* pad` pad with spaces to \$5n\$
* `.* <ls` join stack with newlines
* `(...) .n3* .n1- * 1+ e*` execute \$3n(n-1)+1\$ times...
+ `\# \, ?s` replace first `#` with `,`
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~21~~ 20 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
<‚εxŸ¨„1 ×û.c}`Sþ0.;
```
-1 byte thanks to *@Steffan*.
Outputs `1` for `*` and `0` for `.`, with \$n=1\$ being `*` (`1`) (thus \$a(0)=0\$).
[Try it online](https://tio.run/##ASkA1v9vc2FiaWX//zzigJrOtXjFuMKo4oCeMSDDl8O7LmN9YFPDvjAuO///NA) or [verify the first 10 test cases](https://tio.run/##yy9OTMpM/R/iquSZV1BaYqWgZO@nw6XkX1oC5en4ufy3edQw69zWiqM7Dq141DDPUOHw9MO79ZJrE4IP7zPQs/6vc2ib/X8A).
**Explanation:**
```
< # Decrease the (implicit) input-integer by 1
‚ # Pair it with the (implicit) input: [input,input-1]
ε # Map `y` over this pair:
x # Double the current value (without popping it)
Ÿ # Pop both, and push a list in the range [y,2y]
¨ # Remove the last item to make the range [y,2y)
„1 × # Repeat string "1 " that many times†
û # Palindromize the list
.c # Join the list by newlines, and pad leading spaces to centralize it
}` # After the map: Pop and push both the input'th and (input-1)'th hexagons
# separated to the stack
S # Convert the (input-1)'th hexagon from a string to a list of characters
þ # Only keep the digits of these characters
.; # Replace each first digit occurrence in the input'th hexagon
0 # to a 0†
# (after which the result is output implicitly)
```
† Any other digits besides `1`/`0` could be used.
[Answer]
# x86-64 machine code, 51 bytes
```
56 B8 20 C7 07 85 99 59 A8 AE 01 D1 75 02 F7 DA 51 F3 AA 89 F1 66 F3 AB 88 0F 59 29 D6 39 F1 75 E2 88 E0 6B CE 06 E3 0A FD AE 75 FD FE 4F 01 E2 F8 FC C3
```
[Try it online!](https://tio.run/##fVTdTtswFL62n@KsCClpC0q7FdKUbuLvEm2qkLYJepHaTmPkJlmcQArqDU@wiyHxIDzRHmTdcZqmRdrwRSyf7@/4R2F7U8aWS1/PwIJRw6L7UxVPfAUBDTyS5DqEVEuoxg4l@5N5JsApTtyqBL9//ZzFtyD8oo11t@ccnh52HdhQcVFTH6lyvBo5PdxC4PWobM@@fh6dwZfLEVylXI5NxLHb6/f7bm@T4Lzp87ghur0N8fktYr9fE59eGP/xX2Jvm5jECaSs@CfxePvAMqEz8FW5m3NDfN4inr/R49OLZr6eUOJzDoLhkQteUHIT3YOmJBLTcq3XV8cQS0UCOouNqLynUqTlBrhbAdX5MkVJtQ9KdD4x3CqFzZIt@U0kQDkrrdmKH1IiZ7mqKW04QBb63INAq4xT1fFI1X@p7lDCBYOT75fn9RW3OmNKVIwdGJgpToWHrWbUboA9oLex5BBYLPTTJug2yCiDCOt0R0ZM5VzAESbJeD/8SKkBZ76MLJs@oBdqIBU6V9lVr9MdD0ox9jofUBLEKVilGQyhM8DpaAguzq2WTQmqSWCttO0yj5AkRXpgNXaldx011tU80nIaCQ5lWjNBt5XMgHehVAKsAovNpDRGmzwzVFMcrl7oJ/Oij8GDYpWTZ9pqYIRZLWidex1d@CyUeI4s5sIrYR7DwxqHXaf7DfuaDy3rVVdNO7CvilZrbA8WULU0h3cm/fS9cakdrF0J5lVqu9yh6WexXP5hgfKnerk3O/iAH/x3DJEv1F8 "C (gcc) – Try It Online")
Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes in RDI an address at which to place the result, as a null-terminated byte string in [ISO-8859-1](https://en.wikipedia.org/wiki/ISO-8859-1), and takes the number \$n\$ in ESI.
In assembly:
```
f: push rsi #
.byte 0xB8 # ┐mov eax, 0x8507C720
.byte 0x20 # │
l0: .byte 0xC7 # │ ┐mov DWORD PTR [rdi], 0xA8599985
.byte 0x07 # │ │
.byte 0x85 # ┘ │
.byte 0x99 # ╴cdq │
.byte 0x59 # ╴pop rcx │
.byte 0xA8 # ┐test al, 0xAE ┘
.byte 0xAE # ┘ ╴scasb
add ecx, edx
jnz s
neg edx
s: push rcx
rep stosb
mov ecx, esi
rep stosw
mov [rdi], cl
pop rcx
sub esi, edx
cmp ecx, esi
jne l0
mov al, ah
imul ecx, esi, 6
jrcxz e
std
l1: scasb
jne l1
dec BYTE PTR [rdi+1]
loop l1
cld
e: ret
```
* ECX and ESI both start out being equal to \$n\$.
* At first, ECX is reduced by 1 at the start of each iteration, for the number of spaces at the start of the line.
* At first, ESI is increased by 1 at the end of each iteration, for the number of spots in the line.
* When ECX hits 0, at the middle line, those changes are reversed: from then on, ECX increases and ESI decreases. The `neg edx` instruction does this.
* EDX is initialised to 1 using the 1-byte `cdq` instruction (sign-extend from EAX). This requires the high bit of EAX to be 1; because of the way the overlapping instructions worked out, this necessitated using 0x85 (NEL) as a newline instead of 0x0A (LF). (Because TIO's output mechanism does not handle NEL, the additional code in the TIO demonstration converts NEL to LF.)
* The null terminator is added using `mov [rdi], cl` in the middle of the loop, taking advantage of ECX being 0 after `rep stosw` counts it down. This actually adds a null byte at the end of every line, but it is overwritten by the NEL except at the end.
* The final part of the code runs backwards through the string and modifies the last \$6(n-1)\$ spots.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 21 bytes
```
‹"ƛdr‛a *∞øĊ⁋;÷Ǎ(n0øḞ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigLlcIsabZHLigJthICriiJ7DuMSK4oGLO8O3x40objDDuOG4niIsIiIsIjQiXQ==)
Port of Kevin Cruijssen's 05AB1E answer.
[Answer]
# [Knight](https://github.com/knight-lang/knight-lang), ~~110~~ 105 bytes
```
;=n+~1P;=c~1;=i+1*2nW+1=i-iT;O+*' '=xI>=x-n iFx~x'\';=j~2;W<=j+1j-*2n xI<c-**3n n*3n;=c+1cO'. \'O'* \'O''
```
100% can be golfed but I'm too lazy to do that lol.
[Try It Online!](https://tio.run/##lVhpc9pGGP7eXyGrqdEiIYN7TZBlT@I6HU8bnMZuPS2QsFotIEesiA6bFOS/7r67ulZcTr8wkvbZ99rnPZY7fI8jEnrzuMUClz4RH0eR8hvzJtP4IgyDUKGLmDI3UsTbMs0A73AY0fq6tKdAvU9Y7M2ex13HIcWzJQlYFIcJiYNQw2gZT73IjIIkJNTGKax489upF9NojgnV8vUZjslUO/qg9QfDQX8Qwfe0O9RX3/Y/DNiwqQ3Y6gVCzSOUzin9BKshjZOQKZLwfnu4WrHE99NMmGMQu42WPo0VbDsmXVCiSXBk5SL4Ftu28Rl/6MoQW3o2o8QB2zUMakyfskk8RQbukyFK4wAc99hkq1VpKsKh3Pz97uLa7g@tLFR/YT@hyyjGsUeUOT8FzUFLx9wIjzWGKN7jEHxoW/hEiMn1W1jXM/@ILb738dAsZFneWCMot4ekkq9pmDAR9jB4UBh9yBiRutRJJlu@7/BOCDGrRcD1kplDwx24YhFwr4PAp5jtAJarac6q3yEYIfZL4mWhWyNZlMy5dEOI@ujiGAPXMkclJVucyd@rfds8yd/roA03ig8yjH72uXk5AiseWI0ZocE481py4/BQMh74mD0VUeDCyxDkIdngT8H1Kptu3gxR/1Xrn2HzyOiUlMeHh/yAuUxNvVG5NpS6yWxeOjMqnHkh8jNFo9SPp5UrB5Wth4e4dmwTGafIuIM6MM3IPE@iqca/IitLlYveX5fvr3pvL3o39jLNE@bSpSxe48Bz7vdx69@PQ/7bbr38CCFYD4AQCsam@9jkcRCwqR4fsdUbe4DLQpTheKDAXG/CuBzJk36FGZbUzAzegeIZfB94rtI@4OdTWG5VCSrXZW30J/vEggemeKVlSqNmWmNUj7lwARXxlaL7tfQauPpmSCGgebpgtE6qfKHiFHZdiSvF/oozOpZKB0qhBu@Ft@rwWeLvhTfrcNe7l72slvhJ1A6hEPUWx1MTeMOIJPUI/N51SOo5ZiyIFVAFZ6I4X5R/aRioYGrg/k/dlcLv8LP6QHziB5K@efCwX18lfrU60PBJG32V883mV3hPF/OAcZLimAqDlDiA2sjoBPh2TxUwjoZgpL@jkpzI57az3pzWUDXiV7TvQUPcz3upepfE7@UlFWWc50JqJaSoILzdruWAysEaUvd1BiEvd/6ZUJJgBmZSscVUy2D8z11ycPi3IjrQHJ8NDqeQY2Op56iNIYI5LhpcD5tnaNA5Mo4FrXg0gFmOTCTQwIeVbIjBZjbccbDa4G2JrFYNtcEfUOVSNbTyogdWzTwGTHKVz0kAhKKMBAn/TN2u8mKJ09G2li7sr@eR0Wmj1aq9VrPyAWFfzeJOjHJArnCz9HBQpcsM6Zxi6D1yBXqG8eWotZfxJUo@VPiYd1fYhd3rL4x0cWqH9HPihVRTx5GKjCUfkcWSIy2Rqee7H@dhQGjEUW/@7J3fXF71rqve/AZqwL7WLLEkO2CYzEsxfUfqdOKkpVnVknh11hVZp69MdJQxhvJ5ms/H/MWF@dg9IcVs7Baz8dgWFpmFKVzZwXgHnd560LvZRMHhJJnxgePF0tU7qQJKlDH3EjqqwxupRbPAjlEqnTEPhEYMx6BrIwV8ImtjBRdn4@yZ4Rm1newZVEc22ZxdxQbNNM0SVVaWrIqrXHvsBUxT9VJqGR5HKUZOsRXrtmooqu6YmYyyi@vqRm26cu4oiU0vEvw1YFxKx7kqJaQTL4qpcBEtIbQd3quKC9LaXUJTe2CSMktgyHMgUReYxP4XBXqBQqY4hDeYWfyATaAmWRVB8NB2JI0QmLJzyUebJxncQDVHygMk155qjMruG9ZWGqi9QLnnkqFQJr7LbRUq3AOolVJW8YAjowyB@k41NGSf5lcyVTUc@3UyHtPQxL4fEA0GcDfgQcJaGxjRhoncAMo7cKVEDhj@ySI6uPoAGUe1DnRhsSJucibPrVsPEl8dMBUhYhMz8j24IbYNpVVN9kWlISiVLXufWVZr3WM/AF9/OH75w8uffj5@@VNTfA0xc4MZD5u8/0I1sH3KQ4Zroa0gjVcNDikTPQtvbpUjdzcw4KwwM5NkjsNgdg4MOA9cGDTzuxPqFubKx2mSHPcq5jObbORrYSSWP51nn/LLpfiVl0diuexDded2OKr@ITblBdGkC2@9ikvYg1KBuGvVL0A15O8lknssG1Ikk4z@hXPrtBzfasEuLItiN0hi8yGExg0CszxHBq7F7KouqNKaS1MHA3E9zMkGTDvbIb9gI0BQdytmxHvjNyNklDOTbIkOFOVFpDou3mhz32rOtzaQ/F6wDdncQPK@vA15tIEUt4EtyO82ZQbb7fywgRRT9xbkSYksqVJs4RNBuUXec7p7z2TXnrPde3jJ37rnsNyj4SKva//TnOXburXMWz27DXedzYy0pG3ZqrEtYLYEq9UWfqVdrUCldL2vJzI28/u5Y5f6nZrw21L4kndPq5a0FlpLt61kvsxEQNO3T/HWYJFN33@VNomgVXYbTu2SZvDyL70WFQwX/1JyIauVqtajdp0rcIWKYtMzqlzb3dRcgotWz8f6M6zDVFmYAB0O6USvTNJd3ourhvHYkCte/eoOOIhOUUVgYrnvH0MnfHp6@vGbJ8tm@mPnnWWTx45le3qnecxu9Y7ttbwb60pvNpSGvbg8tRctpnhvFo@LxqBh2XePx9btiX2nd@5asEFZXJ6QVrP5PZwg/IAwvUOuGqYyaFw1muK38R8)
[Test Suite up to n=10](https://tio.run/##lVhrV9s4Gv48@RXC22IrdkzCdDsLxnBahs5yhga20OHsJmmRZSUxdezUF0hJzF9nX/kq5wKdLzmJ9Oi96Xkvyi25IyENnGnU8nybPVGXhCH603NG4@gkCPwAsVnEPDtE6a95kgEuSBCy@r5wpkB9ir3ImbyMu4wCRiZz6nthFMQ08gOF4Hk0dkI99OOAMpMksONMr8dOxMIpoUzJ9yckomNl54vS6w/6vX4I68n@QF38o/el7w2aSt9bvMK4uYOTKWPfYDdgURx4SBDeaw8WCy923SQTZmnUbOO5yyJETEtnM0YVAY6NXAQ/YpomOeJf9kWIKXzXw9gC2xUCanSXeaNojDXSowOcRD447nijtVYlSRoOdPXfi5NLszcwslD9RdyYzcOIRA5FU34LioXnlr4SHmMIUbwjAfjQNshBKibXbxBVzfyjZrreIwO9kGU4Q4Xi3B6aCL4mQeylYQ/8e@Sx@4wRic2seLRmfYN3qRC92gRcN55YLNiAKzYB9973XUa8DcByN8lZdQbBCIhbEi8L3RLJwnjKpWupqK82iQhwLXNUULLGmfx3dW6dJ/nvOmjFjWJBhLHvLjcvRxDkgNXEo8wfZl4LbmxvC8YDH7NvRRS48DIEeUhW@FNwvcqmqw8D3HvX@t@guaN1SsqT7W1@wVymIl1JXBtO7HgyLZ25KZx5leZngm8SNxpXrmxVtm5vk9q1jUQcEnFbdWCSkXkah2OFr2IjS5WT7l@nn867H0@6V@Y8yRPm1GZetMSBl9zvkdbD1wH/bLf2vkIIlgOQCgVjk@fY5HAQsKken/SoM3QAl4Uow/FAgbnOyONyBE96FWZQUjMzeAOKZ/Cd79iovcXvp7DcqBJUrMvKzWfvm@ffe8gpLUNyzTT5ph7z1AVcxFeI7s/Sq2@rqyGFgObpQvAyqfKNilPEtgWuFOcrzqhEKB04gRr8LLxVh09i91l4sw63nTvRy2qL30TtEgpRH0k01oE3HhWk7oDfmy5JOiae50cIVMGdIOsHemCBL4Gpvv03dVcKX5MX9YH42PUFfVP//nl9lfjFYkshB238U843mz/hPZtNfY@TlEQsNQhFPtRGj42Ab3cMgXEsACPdDZXkQLy3jfXmsIaqEb@ifRca4vO8F6p3SfxuXlJxxnkupFZCigrC2@1SDkgcrGDpuc6QysudfyGU1J@AmSw9oktlMP7mKTE4fK2IDjTHF4PDKWSZROg5kjzAMMeF/ctB8wj3OzvabkorHg1gliUSCTTwYSUbYoieDXccLMm8LdHFQpZk/gVXLlVDKy96YNXE8YBJNvoe@0Ao5lE/5svM3kev5iS5WdfSU/vreaR12nixaC/VrHxAeK5mcSduckCucLX0cFClSw/YlBHoPWIFeoHx5aj1LONLlHipsJh3VzhF7MsfHt0niRmw77ETMEUahhLW5nxETrcsYYuOHdf@Og18ykKO@vC5e3x1et69rHrzB6gBz7VmgSXZBcNkXorpWUKnS29amFUNgVdH@2nWqQsd72SMYXye5vMx/2HDfGwf0GI2tovZeGimFumFKVzZ1nADnT460Lu9ESLBKJ7wgePV3FY7CQIlaMi9hI5q8UZqsCywQ5wId8wDoVDN0tjSSAFLdGms4OJMkn33yISZVvYdVIcmXZ1d0wOKruslqqwsWRWXuPbI8T1FUkupZXgsVIyc6VGimpKGJNXSMxllF1elldp0bt0yGulOmPJXg3EpGeaqUMBGThix1EU8h9B2eK8qHkhLbwlF6oJJaBLDkGdBos4IjdwfCHoBomMSwC@YWVzfG0FNMiqCkIFpCRohMGXnEq82TzJ4gSqWkAdYrD3VGJW9N4y1NJC6PrrjkqFQxq7NbU1V2FtQK4Ws4gHHWhkC6ULSFGwe5k8ySdIs8308HLJAJ67rUwUGcNvnQSJKGxjRholcA8pb8KTEFhj@zaAquHoPGceUDnThdCd9yek8t64dSHyp70kYU5PqoevAC7GtoVY12ReVhuJEtOxTZlmtdQ9dH3x9s7v3Zu/tb7t7b5vpakA825/wsInnTySNmIc8ZKQW2goiv5M5pEz0LLy5VZbY3cCAo8LMTJI@DPzJMTDg2Ldh0MzfTni/MFe8Tp3muHcRn9lEI9@nRhJx6Thbyh@X6ae4fZNul32o7twGR6X/pIfygqizmbNcxQXsVqkgfWvVH0A15FmJ5B6LhhTJJKJ/59w6LMe3WrALy8LI9uNIvw@gcYPALM@xRmoxO68LqrTm0qR@P30e5mQDph1tkF@wESB4fy3mhvfGxg3WyplJtEQFivIiUl0Xb7S5bzXnWytI/i5Yh2yuIHlfXofcWUGmr4E1yNerMv31dn5ZQaZT9xrkQYksqVIc4RNBeUQ8c7j5zGjTmaPNZ3jJX3tmuzyjkCKva//THOXH9muZt3jxGNm3VjPSEI5lu9q6gJkCrFZb@JN2sQCVwvO@nshEz9/nllnqt2rCr0vhc949jVrSGngp3daS@TQTAU3fPCRrg0VXff9DOJQGrbJbs2qPNI2Xf@FnUcFI8S8lF7JYSFI9ape5AjtVURx6QZVt2quaS3DR6vlYf0RUmCoLE6DDYZWqlUmqzXtx1TAeZbHi1Z/ugIPoFFUEJpa73i50wqenp05jt/Fr403jn423jd8a/2rsNTrtxpNhDtH7s/PjPxu/GKanPnYuDJM@dgzTUTvNXe9a7ZhOy7kyztWmjGRzdnpozloecj7MHmdyXzbM28dd4/rAvFU7ty04gGanB7TVbP4K9wsfIEzt0HNZR335XG6mn3LDMB9Qu3H979OzE@UQdTpIMdGDoqIOegAPwJLzz1cXn68QLMmeKcMqrB2/OztDw8Yv@Z4s/x8)
] |
[Question]
[
## Challenge
Build the [Wheat Wizard's stove](https://codegolf.stackexchange.com/q/218360/78410) using 2-input NAND gates. The solution with the fewest NAND gates wins.
Externally, it works in the following way: (the first line is added from the original spec for physical output)
* It has 10 levels, from 0 to 9. The display has 9 lights, and if the current level is L, exactly L lights from the left are on and the rest are off.
* Two buttons, labeled `+` and `-`, are used to control the temperature level.
* Pressing `+` changes the level as follows:
+ 0 becomes 9
+ 9 becomes 0
+ any other number is incremented
* Pressing `-` changes the level as follows:
+ 0 becomes 4
+ any other number is decremented
In summary, the circuit must behave as a [sequential circuit](https://www.tutorialspoint.com/computer_logical_organization/sequential_circuits.htm) with two inputs (the buttons) and 9 outputs (the lights).
## Conditions
* You can use a clock signal generator if you want, at no cost in score.
* You don't need to make the power-up behavior correct.
* You will need at least a few [latches or flip-flops](https://en.wikipedia.org/wiki/Flip-flop_(electronics)) in your circuit, in order to keep track of the current temperature level. Different latches/flip-flops cost different number of NAND gates, which is included in your score. It is your job to choose the flip-flop that gives the fewest NAND gates overall.
* One button press must affect the level exactly once, but you can choose exactly when the level changes according to input, e.g.
+ when the button is pressed
+ when the button is released
+ at the first clock tick (you can choose rising or falling edge) while the button is pressed (that button is disabled until release) - you can assume the clock cycle is short enough for this to register
* You may assume both buttons won't be pressed simultaneously.
[Answer]
# [CircuitVerse](https://circuitverse.org/), 455 NANDs
* 1x NOT (1 NANDs)
* 2x AND (4 NANDs)
* 3x OR (9 NANDs)
* 1x 4-bit 2x4 multiplexer (96 NANDs)
* 1x 4x1 Decoder (6 NANDs)
* 1x 4-bit adder (108 NANDs)
* 1x 2-bit Memory (54 NANDS)
* 1x 4-bit Memory (108 NANDs)
* 1x (4-bit) Is 1 (9 NANDs)
* 1x (4-bit) Is 10 (8 NANDs)
* 1x (4-bit) Is neg (2 NANDs)
* 1x 1-9 encoder (50 NANDs)
Total = 455
[Try it out online! (version 1.1)](https://circuitverse.org/users/102409/projects/wheat-wizard-stove-a87bea05-b156-4ddc-91da-60e961837d97)
[version 1.0 (NANDs 543)](https://circuitverse.org/users/102409/projects/wheat-wizard-stove)
] |
[Question]
[
## Background
[**Mastermind**](https://en.wikipedia.org/wiki/Mastermind_(board_game)) is a game of code-breaking for two players. One of the players is *codemaker* (Alice) and the other is *codebreaker* (Bob).
4x4 means that the player should guess the length-4 sequence made of four alphabets (say `RGBY`). The hidden sequence may have duplicate letters, so there are \$4^4 = 256\$ possibilities in total.
At the start of the game, Alice sets up a hidden code, which Bob should guess correctly within a set number of turns. At each turn, Bob presents a guess, and Alice tells Bob how many of the positions are correct, and how many of the letters are correct but at a wrong position. For example, if the hidden code is `RRYG` and Bob guessed `BRGY`:
```
Code: R R Y G
Guess: B R G Y
Correct: R(2nd-2nd)
Wrong position: Y(3rd-4th), G(4th-3rd)
```
Then Alice tells Bob the two counts `1, 2`. (Note that the first `R` in the code does not contribute to the counts because the second `R` in the guess was already consumed as Correct.) Bob repeats the guess with different sequences, until the guess is identical to the code (getting `4, 0`) or he runs out of turns.
## Challenge
The [Dream World mastermind solver](http://dream-world.50webs.com/mastermind.html) features four specific guesses so that the unique answer can be derived from their outcomes in all cases. The guesses are as follows:
```
1. R G G R
2. B B R R
3. Y Y G R
4. G B B Y
```
Given the outcomes of the four combinations above (four pairs of integers), output the unique hidden code.
You can assume the input is valid and the answer exists. You can choose to output any four distinct values (numbers/characters) in place of `RGBY`.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
NB: Fetching the results from the linked website is a standard loophole, and therefore forbidden.
## Test cases
Each pair in the input represents `(correct, misplaced)`. Note that the answer can be one of the four predefined guesses (generating a `(4, 0)` in the input).
```
(2, 0), (2, 0), (1, 0), (0, 0) => R R R R
(2, 1), (1, 0), (1, 2), (1, 1) => G G Y R
(0, 2), (0, 2), (0, 3), (1, 2) => G R Y B
(2, 0), (0, 0), (2, 0), (0, 2) => Y G G G
(1, 1), (4, 0), (1, 0), (1, 1) => B B R R
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~38~~ ~~33~~ 32 bytes
-6 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)!
For each possible output this generates the input and selects the matching one. Colors are encoded as `B=0, G=1, R=2, Y=3`.
```
3Ý4ãʒU•˜ÐÐÛ•4в4äεœεX-0¢}¬Dràα‚}Q
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f@PBck8OLT00KfdSw6PScwxOAcDaQaXJhk8nhJee2Hp18bmuErsGhRbWH1rgUHV5wbuOjhlm1gf//R0cb6igYxuooRJvoKBiAaEMEbRgbCwA "05AB1E – Try It Online")
**Commented**:
```
3Ý4ã # Generate all possible outputs
3Ý # range [0 .. 3]
4и # to the 4th cartesian power
ʒU ... Q # filter the possible outputs
# where the following equals the input
# and assign the current output to variable X
•˜ÐÐÛ•4в4ä # encode the 4 guesses
•˜ÐÐÛ• # compressed integer 2517300803
4в # convert to base 4:
# [2,1,1,2,0,0,2,2,3,3,1,2,1,0,0,3]
4ä # split into 4 groups:
# [2,1,1,2],[0,0,2,2],[3,3,1,2],[1,0,0,3]
εœεX-0¢}¬Dràα‚} # compute the score for each guess
ε } # map over the guesses ...
œ # take all permutations
# the first will be the original guess
ε } # map over the permuations ...
X- # subtract the current output
0¢ # count the 0's
¬ # get the head without popping
# this is number of correct positions (c)
D # duplicate it => c, c, [...]
r # reverse the stack => [...], c, c
à # take the maximum
# this is number of correct colors,
# correct and misplaced (c+m)
# => c+m, c, c
α # absolut difference => |c-(c+m)|, c = m, c
‚ # pair up => [c, m]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~29~~ 28 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
4ṗ`ð“ßƙṫl‘ị⁸Œ!=§Ḣ,Ṁạ\ƲʋþZiị⁸
```
A monadic Link accepting a list of four lists of two integers (the `[correct, misplaced]` pairs in order) which yields a list of four integers (where `1,2,3,4` map to `R,G,B,Y` respectively).
**[Try it online!](https://tio.run/##y0rNyan8/9/k4c7pCYc3PGqYc3j@sZkPd67OedQw4@Hu7keNO45OUrQ9tPzhjkU6D3c2PNy1MObYplPdh/dFZUKk/x9uBzEa5gS5O0X@/x8dbaSjYBCroxBtAKWR@EaxsQA "Jelly – Try It Online")** (footer remaps back to the letters representing the colours.)
### How?
```
4ṗ`ð“ßƙṫl‘ị⁸Œ!=§Ḣ,Ṁạ\ƲʋþZiị⁸ - Link: scores
4ṗ` - 4 Cartesian power 4 -> all boards
ð - start a new dyadic chain f(boards, scores)
“ßƙṫl‘ - code-page indices = [21, 161, 245, 108]
⁸ - chain's left argument, boards
ị - index into -> the four test-boards
þ - make a table of:
ʋ - last four links as a dyad:
Œ! - all permutations (of the board in question)
= - equals? (vectorises across the boards & test-board)
§ - sums
Ʋ - last four links as a monad:
Ḣ - head -> total correctly placed
Ṁ - maximum -> total that could be correct by permuting
, - pair
\ - cumulative reduce by:
ạ - absolute difference -> [correct, misplaced]
Z - transpose
i - first index of (scores) in (that)
⁸ - chain's left argument, boards
ị - index into
```
[Answer]
# [Python 3](https://docs.python.org/3/), 171 bytes
```
def f(s,a=0):b='%04i'%a;return([(w,sum(min(b.count(x),t.count(x))for x in{*t})-w)for t in('0110','2200','3310','1223')for w in[sum(map(str.__eq__,b,t))]]==s)*b or f(s,a+1)
```
[Try it online!](https://tio.run/##ZY7fasMgFIfv@xTeFD2dC/7p1UaepISQdIYJi2Z6QlrGnj2zkmVZK8jnwe@c8xuu@O6dnm0/@IAkXuMu3SIaDOY8hmi9@7C9RSZFOjC/mY50LPKmFPDSlnQvjpbum9dgcAyOndjE49iz3jrWFmc/OmQX4Lg@ofOBXIh1Xwf8hucp15hqRoWUgnKqlLhB61xJpTTN0pSkU57dDCxiKOrafNY1bzkCVFVZRji0JIk53pOEeQg27exSKMWJAE5WyoXixgpg90@VWyVRLZR3qli@NtRry8PUv4WbIOJRlUuA413W3wDzDw "Python 3 – Try It Online")
-22 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)
Recursive function to test all possible combinations and find the matching input.
`sum(map(str.__eq__,b,t))` finds the number of correct positions for each combination.
`sum(min(b.count(x),t.count(x))for x in{*t})` finds the sum of the correct and misplaced positions. The number of misplaced positions is found by subtracting the number of correct positions.
Uses `0, 1, 2, 3` for `R, G, B, Y`, respectively.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 53 bytes
```
ΦE²⁵⁶⭆⁴﹪÷ιX⁴λ⁴⁼IθE⪪”)“∧.r⁹1”⁴⁺×⁹ΣEι⁼§λξνΣE⁴⌊⟦№ιIν№λIν
```
[Try it online!](https://tio.run/##RU/LasMwEPwVodMKVJDktFB6KmkDOQQC6c34IGKTLqylxJaS/L26cl86DMxoZnf2@OmnY/RUyn7CkGCDlIYJdv4M7vFJi0Ni@VTpSotd7DNF2Ib0hlfsB0At9vHGfv4kpbRYqYrvl@xphrWfE1yY1/jhTJhAGudM0xhjrTOuaaysGZ5CeYYPHIcZnnlpHpcG@DfqNW1DP9yBtLizPahlz6@vVsOAI9N2HTOfwclle6i2b4n@pU79vJdS2la62kJas6Bb0MquKw9X@gI "Charcoal – Try It Online") Link is to verbose version of code. Takes input as four strings containing pairs of digits in match mismatch order. Output uses digits `0-3` for the colours `RYGB`. Uses brute force. Explanation:
```
ΦE²⁵⁶⭆⁴﹪÷ιX⁴λ⁴
```
Filter through all possible 4-digit codes.
```
⁼Iθ
```
Convert the input pairs of digits to integers and compare with the result of...
```
E⪪”)“∧.r⁹1”⁴⁺
```
... checking the score of each of the patterns in the compressed string `0220330011202331` by taking the sum of...
```
×⁹ΣEι⁼§λξν
```
... nine times the number of matching digits and...
```
ΣE⁴⌊⟦№ιIν№λIν
```
... the sum of matching and mismatching digits.
58 bytes to output using `RYGB`:
```
ΦE²⁵⁶⭆⁴§RYGB÷ιX⁴λ⁼IθE⪪”{⊞‴⊗⁵÷∧p<8'”⁴⁺×⁹ΣEι⁼§λξνΣEα⌊⟦№ιν№λν
```
[Try it online!](https://tio.run/##PY9Pi8IwEMW/SuhphAhu1xXEk/FP8LBQopdSegha1oFpqm3q@u3jRK1zGPgNb96bOZ5te2wshZC16DxskXzVwq@9QPozk2LvefwXcSrF0u/cqbpDYnKtEil2zq/xhqcKUIqs@edFVtEolhSba2@pg5XtPFyZo8n@Quh5X2ujlDF5ro1WKmevKSsy6js4YF11MOfovn7egR@rIZ@kuLPcvXIGneUIdFgzFqum52cwaqR4AUUoR@9ahFAUySTl5KF/x/6VJmUZxjd6AA "Charcoal – Try It Online") Link is to verbose version of code.
[Answer]
# JavaScript (ES6), ~~169 ... 160~~ 153 bytes
Expects an array of 2-character strings `"CM"` with `C` = correct, `M` = misplaced. Returns an array of integers, with `0123` = `RGBY`.
```
f=(a,n)=>a.some((c,i)=>(g=n=>A=a.map(_=>4*(n/=4)&3))(n,b=g(3911125524>>>i*8)).map((v,k)=>c-=v^b[k]?b.some((w,j)=>v-w|v==A[j]?0:b[j]|=4):10)|c)?f(a,-~n):A
```
[Try it online!](https://tio.run/##bY9Ra4MwFIXf9yuCD@OmRE2ihU1IxL70vW9F3IhORdvGMod9kf11F4NtBy0HTkjId@65rRpUX3w35x9Xd1/lNFUCFNFYSOX13akEKEhjblALLWQilHdSZ/gUMlyB9kWIXwOMQZNc1BC8M8b4es1DKWWzesPYfoaBHExC4YrhI08PWZwvyRfSmvfBvYyDEEnaZjGNcnOMJjZiFI8FjivTxv3VOEqmotN9dyy9Y1dDBanDqUPQ4sw6pU6GMfJ9tFsEFFnhlwea3TnGrbMrvTXazzRDDAXPaGqJxYMl40bvDL2ZaWpo/mT2te2tP73Rezt9iyBA83T2SDPbPPy39735xsjuzRG3e09/ "JavaScript (Node.js) – Try It Online")
### How?
We generate all possible boards `A[]` and test them against the guesses `b[]` which are extracted from the 32-bit integer `3911125524` as follows:
```
3911125524 = 0xE91F0A14
0x14 = 00 01 01 00 -> R G G R
0x0A = 00 00 10 10 -> R R B B
0x1F = 00 01 11 11 -> R G Y Y
0xE9 = 11 10 10 01 -> Y B B G
```
We decrement the expected outcome `c` when a 'misplaced' digit is found and subtract 10 from `c` when a 'correct' digit is found. We stop when we have `c = 0` for all guesses.
### Commented
```
f = (a, n) => // a[] = input array, n = counter
a.some((c, i) => // for each entry c at position i in a[]:
( g = n => // g is a helper function turning a byte n
A = a.map(_ => // into an array of 4 2-bit values
4 * (n /= 4) & 3 // by isolating the 2 least significant bits
) // and dividing by 4 between each iteration
)( //
n, // invoke g with n to create the board A[]
b = g( // invoke g with a byte extracted from ...
3911125524 >>> i * 8 // ... this 32-bit integer ...
) // ... to create the i-th guess b[]
) //
.map((v, k) => // for each value v at position k in A[]:
c -= // update c:
v ^ b[k] ? // if v is not equal to b[k]:
b.some((w, j) => // decrement c if there's some w at position j
v - w | // in b[] such that v = w and v is not equal
v == A[j] ? // to A[j] (i.e. A[j] is not 'correct'),
0 // in which case ...
: //
b[j] |= 4 // ... we invalidate b[j] by OR'ing it with 4
) //
: // else:
10 // subtract 10 from c
) // end of map()
| c // yield a truthy value if c is ≠ 0
) ? // end of some(); if truthy:
f(a, -~n) // failure: do a recursive call with n + 1
: // else:
A // success: return A[]
```
[Answer]
# [R](https://www.r-project.org/), 194 bytes
```
function(r,a=apply,`~`=table,g=matrix(762201603%/%4^(15:0)%%4,4))(p=expand.grid(rep(list(t<-0:3),4)))[a(p,1,function(y)all(a(g,1,function(h)c(z<-sum(y==h),sum(pmin(~c(t,y),~c(t,h))-1)-z))==r)),]
```
[Try it online!](https://tio.run/##fY9Ba4NAEIXv@RVCEWZgTFy1KYRsD7nknlsobbNVq8JqlnVTYg7563ZX07QUEh7DDMt@vPd03@7lV/5ei9bkuq6ajPefhyY11b4BTYILpWRHu/OOG/Ehcyp4LYyujvA0j6KQzcPYn/nJG7DHRYi@n1CCCIrnRyWabFroKgOdK5BVa8Asg3ARo/uCLwIUMbp6dSikBAHF38cSUzgtg/ZQQ8d5ieQuZVPCOQVDHdKwS8SAYXBC5Fwj0muveQoRheSG2bFC78Hjz95m1OR/bdA4GSk2EIyG60KtrbZ3qNHJTezIK7Wx1OqO15CMxv1DbQe39U3K5UsuvX4Trqxu9eq/AQ "R – Try It Online")
Uses the integers 0,1,2,3 to indicate R,G,B,Y.
**How?** (commented and de-golfed gode)
```
solve_mastermind=
function(r, # get responses r as 8-element vector
a=apply, # a = alias to apply() function (not used in de-golfed code here)
`~`=table, # ~ = alias to table() function (not used in de-golfed code here)
g=matrix(762201603%/%4^(15:0)%%4,4)) # g = matrix of guesses, compressed as a base-4 integer,
# and decompressed here using DIV powers-of-4 MOD 4
(p=expand.grid(rep(list(0:3),4))) # p = all possible permutations of codes (a 256 x 4 matrix)
[ # Select & return the correct row from p:
apply(p,1,function(y) # apply this function to all rows of p:
all( ... )==r # return true if all these values are equal to the elements of r:
apply(g,1,function(h) # apply this function to all rows of g (that is, each of the 4 guesses):
c( # return a 2-element vector, consisting of:
z<-sum(y==h), # 1. z = sum of elements of this code (y) that are equal to elements of this guess (h)
# so: correct position + correct colour
sum( # 2. the sum of ...
pmin( # the minima of ...
table(c(0:3,y)), # the count of the digits 0..3 in this code (y), +1
# (the table() function counts the number of each type of instance.
# However, we aren't sure that all of the digits will be present, and
# absent digits would normally be uncounted (instead of counted as zero).
# So we join the series 0..3 to y before counting the digits.
table(c(0:3,h))) # and the count of the digits 0..3 in this guess (h), +1
-1) # minus one (to account for the digits that we added)
-z) # minus the number of correct position + correct colour
)==r)), # (see above)
]
```
] |
[Question]
[
# Introduction
A picross, also known as a nonogram, is a logic puzzle in which the player is given an initially blank grid and must shade in particular boxes on the grid to reveal an image. Numbers are written on the top and the left side, and they explain the image's coloration: each number corresponds to an unbroken line of shaded-in boxes in its row or column. Consider any individual row or column from this completed puzzle to see this correspondence:
[](https://i.stack.imgur.com/TwOc2.png)
Not shown in the image is the fact that one can write an "X" to indicate that a box is known not to be shaded in. Partially solving a row or column by shading in and crossing out boxes provides necessary information for the rest of the puzzle, as rows and columns usually cannot be completely solved on their own (for instance, in the image, this is only possible in the first row).
# The Challenge
To take the hints for a given row along with the state of each box in the row as inputs, and output the row solved to the fullest extent possible.
---
# Examples
In these examples, let `0` represent a box with an "X", `1` a shaded-in box, and `2` an unknown or unknowable (that is, blank) box.
---
[](https://i.stack.imgur.com/lczJL.png)
This row would be input as
```
[1,3,7,1], [2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2]
```
and the program should output the following:
```
[2,2,2,2,2,2,2,2,2,2,2,1,1,2,2,2,2,2,2,2]
```
This output corresponds to this row, and no more information can be found:
[](https://i.stack.imgur.com/Bf3YR.png)
The boxes marked `1` are always that way, [no matter the arrangement of the shading](https://i.stack.imgur.com/WndkT.png). Essentially, if a box always has the same state, it must assume that state, lest the shading contradicts what is known. If there is not a unanimous agreement, then the box is unknowable and is marked `2`.
---
```
Input: [1,3,7,1], [2,2,2,2,2,2,0,2,2,2,2,2,2,2,2,2,2,2,2,2]
Output: [2,2,2,2,2,2,0,2,2,2,2,1,1,1,2,2,2,2,2,2]
```
---
```
Input: [6], [2,2,2,2,2,2,2,2,2,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,2]
Output: [0,0,0,0,0,0,0,2,2,2,2,2,1,2,2,2,2,2,0,0,0,0,0,0,0]
```
If a 6-wide shading were to begin in any of the first 7 boxes, the row would have to have `[6,1]` or `[7]` as its hints, and so none of the first 7 boxes can be filled in. The same is true for the right side.
---
```
Input: [3], [2,0,2,2,2,2,0,2]
Output: [0,0,2,1,1,2,0,0]
```
Because a 3-wide shading can only fit in the 4-wide gap in the middle, the 1-wide gaps on the edges can be turned into `0`s
---
# Rules
* Any three distinct symbols may be used in the place of `0`, `1` and `2` so long as it is indicated which symbol corresponds to which state
* Assume the input hints and row never form an impossible combination
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program in bytes in each language wins
[Answer]
# [Python 2](https://docs.python.org/2/), ~~127 124~~ 123 bytes
*-1 byte thanks to @ovs !*
```
l,a,b,c=input()
x=y=i=a|b|c
while i:
if[len(z)for z in bin(i)[2:].split("0")if z]==l>i&a<1>~i&b:x&=~i;y&=i
i-=1
print x,y
```
[Try it online!](https://tio.run/##LcxBCoMwEEDRfU4xuAgJpCWxO9vxIuLCiOJAiMGm1Ih49dSWvtVf/ZDiNPsyZ6c6ZVWP5MMrCslWTEjY7Xbv2XsiNwBVDGhs3ODFJsd5gQ3IgyUvSDZl1V6fwVEUhS4kjbC1iK4m3j1MfRC31crxoHviSOfmgoaFhXyEVaWcm1urQFtt9MnoX/9922hz0uYD) or [Verify test cases](https://tio.run/##lVNdb5swFH33r7hypAhWJwIqbRKb87ynapr6htBqiEm9GhthskJV9a9n15Q06bJMC1dCcO/x/TrHzdDdW5PsSruWwIFSutNMsIKVXJlm2wUh6fnAFRfPxXNJHu@VlqBSAqrKtDTBU1jZFp5AGSiUCVSYJWm@dI1WXUAjGqoKnnLO9UrNxZd49aLmRdrP@Yv6PMy5wjQLHpNv329ug54N4Q7rEzL734fM4KvUjWyh2pqyU9Y48O100nXKbC5ItJYVdPZHLdyDC@oQ5xO4DWVwCLr8aXEyGsU06zmP8rFE7yeuQ5aEBIoz0PgUWp6BJqfQVnbb1sDIBRkbrFpbTy16r/FtakyYJfkHQ8YEyidohdnIYAwD8oQvscL9xynozCzUAvviEPmg1BguToPxW3lNSCvdVnfovbFGjo1MfMHgS2y0LYSGVxSBN7SPX8blLdJ2wQFVN7btwA2O@NG1MtJPj/9L162V8ePjeN6fpTGKkM5oCqU1qI2tBJiBe1ANOFvLUTFQCicdHgo08ySAMO4RtcWhFk0gfwl0@2R7dS9WNESekCEo2MjskYJ8bX9/0KtFXaxF6rNOUB@VvSzB3zr8Rukjbr/BwwqPCPfbxPJ44@qxaNOijCYkA5rRq7v9MT41fndFc7rLYnbNPrE4Z6gTdrCIJecsh8XqHDge7RhMZtnHP5MfW/zvMhE7tr8fe4fJSXb9Wi867u@QLZla9Njf)
(Timed-out in TIO for the 2nd test case, but I have verified the program on my PC.)
Reads from `STDIN` the list of streaks `l`, and 3 numbers `a, b, c` representing bit-masks of empty cells, filled cells, and unknown cells.
Prints to `STDOUT` 2 numbers, representing the bit-masks of guaranteed empty cells and guaranteed filled cells.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 129 bytes
```
SθWΣθ«⊞υιSθ»≔Eυ⁰ζ⊞ζ⁻Lθ⁺Συ⊖Lυ≔⟦⭆ζ⁺×:⊕ι×#§υκ⟧εW⌊ΦLζ∧κ§ζκ«UMζ⎇‹λι∧⁼λ⊖ι⊕Σ…ζι⁻κ⁼λι⊞ε⭆ζ⁺×:⊕κ×#§υλ»≔Φε⬤θ№⁺-§ι⊕μλε⭆θ§-#:⁻⬤ε⁼§λ⊕κ#⬤ε⁼§λ⊕κ:
```
[Try it online!](https://tio.run/##lVHRSsMwFH1eviJ0Lymk4PBBmE@lKgwcDLY38SF0YQ1L0rVJ1FX89nqTtmsVBb0PLcm959xzTvKC1XnJZNuu9MnZra2FPpAqvkWvhZAck61TcIzxO5ptnCmIo1hAd/Z9/AOlxoiDJmt28kNXMcUN3AdQQ/FaaGfII9cHWwCA4o2Es2d3cLjjec0V15bvhxkX@7odaJ@6XZ696cE7obgh0TKieKVHvIiBsO/NoZfald7zNy/q6CmfKeajP9AlFKh4ENLyeljeAEWq9@Q4wpseHqIAGVmpFIMRuN/xWrP6DGBjiPQBdej7yjEZbqb@gr6pYB9Cds4lz4oyuBN@zRAZSBh5RJdJ9xSc4j@Hcvw9FNkHfXnBPgqgT6UkFcVZ6bQlgT5KJmDxdYcKqmX4@oQ3oM2SUWI1IqNk7hV2Dv0WfnE5jMgfDIB0//sHYBnFnb22XaBrdIMWKAm1TKbVJi@SfQI "Charcoal – Try It Online") Link is to verbose version of code. I've used `-` for unknown, `:` for empty and `#` for shaded, but of course these could readily be changed to other characters. Explanation:
```
SθWΣθ«⊞υιSθ»
```
Input the runs and the known state.
```
≔Eυ⁰ζ⊞ζ⁻Lθ⁺Συ⊖Lυ
```
Start by putting all the spare space after the last run.
```
≔⟦⭆ζ⁺×:⊕ι×#§υκ⟧ε
```
Create a list whose entry is an image of that spacing, but with an extra space at the start and junk after the end.
```
W⌊ΦLζ∧κ§ζκ«
```
Repeat while runs can be moved.
```
UMζ⎇‹λι∧⁼λ⊖ι⊕Σ…ζι⁻κ⁼λι
```
Calculate the next permutation of runs. This is achieved by moving left the first run that can still be moved left, and then moving all the previous runs to its immediate left.
```
⊞ε⭆ζ⁺×:⊕κ×#§υλ»
```
Push an image of the new spacing to the list.
```
≔Φε⬤θ№⁺-§ι⊕μλε
```
Delete the runs that don't match the original input.
```
⭆θ§-#:⁻⬤ε⁼§λ⊕κ#⬤ε⁼§λ⊕κ:
```
Output the knowable state.
[Answer]
# [Wolfram Language](https://www.wolfram.com/language/), 155 bytes
```
Union@*List~MapThread~Cases[IntegerDigits[i,2,l]~Table~{i,0,2^(l=Length@#)}~Cases~#,
{0...,Splice@Riffle[1~Repeated~{#}&/@#2,0..],0...}]/.{0,1}->_/.{a_}->a&
```
(newline added for "readability")
[Try it online!](https://tio.run/##jY3BasMwEETv/g1DSMvWsd2eCi6C9FJIoSTpSShi66xtgaK4tnoS0q@7St1TDqUMzM7hzc4JbUcntKrG6d30w9lSbfmu16omkcyXaykeqx19fpGpiTGdNFWE1dmw240abXjFft8NhMewxpFG/mIstTQ8q1bZkSsoQYuwxw9NwSnIoTwsdbUh09qOpTd@boUUXJ5lGcyjbKuaRhMvwpZ6QkvH4FK/WLG0hIiJi2VerDKH0t89YQw5FDHJxfQ2KGNZw52MY/JXxcU9uAcvkj@BAq6QK/0gJdz/B4qfpm8 "Wolfram Language (Mathematica) – Try It Online")
Note: Since the version that tio.run has is apparently not the latest version (12.1), and [Splice](https://reference.wolfram.com/language/ref/Splice.html) was added in it, I have added an equivalent definition.
Uses `_` rather than `2` in the input to leverage built-in pattern-matching capabilities.
The method this answer uses is not very efficient, so don't try any massive inputs.
Program description:
1. Generates all sequences of `0` and `1` of the proper length: `IntegerDigits[i,2,l]~Table~{i,0,2^(l=Length@#)}`
2. Filter to those that match the already solved cells: `~Cases~#` (super easy because I specify the input to work as a pattern)
3. Filter to those that match the row description: `Cases[ ,{0...,Splice@Riffle[1~Repeated~{#}&/@#2,0..],0...}]`
4. Get list of options for each position: `Union@*List~MapThread~`
5. Convert back to input form: `/.{0,1}->_/.{a_}->a`
] |
[Question]
[
[Toki](https://en.wikipedia.org/wiki/Toki_Pona) [Pona](http://tokipona.net/tp/janpije/okamasona.php) is a linguist's code golf: A minimalist language with a vocabulary of around 120 words. Because of this, it has very few grammatical irregularities found in other languages, making it ideal for a code golf challenge.
Your task is to take the most simple form of a Toki Pona sentence and translate it into English, using the (even more) limited dictionary provided in this question.
## The dictionary
While 120 words isn't a lot for a language, it's a lot of bytes. So, for that reason, I'm limiting the input to only contain these 20 words (English translation in brackets, Toki Pona in **bold**):
* Pronouns: **mi** (I/me), **sina** (you) and **ona** (he/she/it/him/her)
* Grammatical constructs: **li** and **e**
* Verbs: **jo** (to have), **moku** (to eat), **pona** (to fix), **oko** (to see) and **wile** (to want)
* Adjectives: **pona** (good/simple), **ike** (bad), **wan** (one/unique) and **mute** (many)
* Nouns: **kili** (fruit), **oko** (eye), **jan** (person/man/woman), **moku** (food), **ilo** (tool) and **ijo** (thing)
In addition, sentences involving the verb *to be* are included (expanded on later).
As you can see, simple sentences such as **I want food** can be made from this list: **mi wile e moku**. We'll address the exact grammatical construction in the next section. However, note that a single word may be used for multiple different English words (e.g. **moku**), which is how such a limited vocabulary is possible.
## Grammar
All of the sentences you'll be required to handle will have one of the following forms:
* **pronoun/noun "li" verb**
+ e.g. **ona li oko** (he sees)
* **pronoun/noun "li" pronoun/noun**
+ e.g. **ona li jan** (she is a person)
* **pronoun/noun "li" noun adjective**
+ e.g. **ona li ijo ike** (it is a bad thing)
* **pronoun/noun "li" verb "e" pronoun/noun**
+ e.g. **jan li jo e kili** (the person has fruit)
* **pronoun/noun "li" verb "e" noun adjective**
+ e.g. **jan li jo e kili pona** (the person has good fruit)
We'll call the first **pronoun/noun** the *subject* of the sentence and the second the *object*. Notice that the adjective comes after the noun, not before, and that pronouns cannot be paired with adjectives.
For example, **ona li moku e moku** (He eats food) is of the fourth form. However, the one exception is that if the subject is **mi** (I/me) or **sina** (you), then **li** is omitted. So **mi moku e moku** would translate as I eat food.
You'll notice that forms 2 and 3 don't have a verb, but our translated examples do. This is because Toki Pona has no word for *to be*. While we would say "I am good", Toki Pona speakers would say **mi pona** instead (omitting the verb). If the subject is not **mi** or **sina**, then **li** is used as it would be usually: **kili li moku**.
The two constructs **li** and **e** are used in the following ways:
* If the pronoun preceding is not **mi** or **sina**, the verb in the sentence is preceded by **li**. For example, **moku li moku** or **ona li oko**
* The object in the sentence is always preceded by **e**. For example, **moku li moku e moku** or **mi pona e ilo mute**.
Notice that Toki Pona doesn't conjugate verbs, nor does it change the word when plural. Due to this, you should assume that all input is in the singular (**ijo** is translated as **thing**, not **things**)
## English translation
In comparison, all outputted sentences should be in the forms
* **pronoun/noun verb**
* **pronoun/noun verb pronoun/noun**
* **pronoun/noun verb adjective pronoun/noun**
As each word has multiple translations (**ona** is he, she or it), we'll use these translations:
```
mi (subject) -> I
mi (object) -> me
sina -> you
ona (subject) -> he
ona (object) -> him
jo -> to have
moku (verb) -> to eat
moku (noun) -> food
pona (verb) -> to fix
pona (adjective) -> good
oko (verb) -> to see
oko (noun) -> eye
wile -> to want
ike -> bad
wan -> one
mute -> many
kili -> fruit
jan -> person
ilo -> tool
ijo -> thing
```
However, because English has plenty of grammatical irregularities, and we have such a small vocabulary list, the English output should be as accurate as possible. Therefore:
* Verbs in English are to be conjugated. This means that for all verbs except *to be*:
+ The **I** and **you** forms are the same as the infinitive (to fix -> I fix, you fix etc.)
+ The *he* form (which includes nouns) modifies the infinitive to end with an `s`. Specfically, the 5 verbs become **has**, **eats**, **fixes**, **sees** and **wants** respectively.
* For *to be*, **I** becomes **am**, **you** becomes **are** and **he** (including nouns) become **is**
* Nouns are prefixed with a `the` (notice the space), unless the adjective after it is **wan** (one) or **mute** (many).
* Nouns before **mute** (many) should have a trailing `s` (yes even **fruit** and **food**). So **ilo mute** becomes **many tools**
## Your task
You are to take in a single sentence of Toki Pona consisting of only words from those 20, and always in one of the forms listed above (including the *to be* exceptions), and output the English translation. As is standard in Toki Pona, input will always be lowercase.
You may take input where the separator is any consistent non-alphabetic character or sequence of characters, including spaces (i.e. `mi@@@e@@@jan` is perfectly acceptable), or you may take input as a list of words, if you wish. The input does not have to make sense (e.g. **ijo li jo e jan mute**), but will always follow the grammatical rules.
Output rules are equally lax - you may output as a list of words, or as a single string with any consistent, non-alphabetical separator. Case is irrelevant.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins!
## Test cases
```
mi wile e moku - I want the food
mi moku e moku - I eat the food
mi pona - I fix+
mi jan - I am the person
ona li oko - He sees/He is the eye\*
ona li jan - He is the person
ona li ijo ike - He is the bad thing
jan li jo e kili - The person has the fruit
jan li oko e kili pona - The person sees the good fruit
kili li moku - The fruit is the food/The fruit eats\*
moku li moku - The food is the food/The food eats\*
moku li moku e moku - The food eats the food
ijo li jo e jan mute - The thing has many persons
ilo li pona e ijo - The tool fixes the thing
sina moku e kili mute - You eat many fruits
sina moku e kili ike - You eat the bad fruit
oko li oko e mi - The eye sees me
mi wile e sina - I want you
jan li moku e ona - The person eats him
mi jo e ijo wan - I have one thing
mi jo e ijo mute - I have many things
sina kili - you are the fruit
\*: Either translation is acceptable for output, as both are valid translations
+: **I am good** would be the natural translation, but using **pona** as an adjective doesn't fix as one of our five forms, so is not a valid translation in this case
```
[Answer]
# JavaScript (ES6), ~~498 ... 447~~ 445 bytes
Outputs in lowercase, except for `'I'`.
```
s=>(s.replace(/\w+/g,w=>(x='2want||2eat/5food||5you|2see/5eye|5thing|1I/4me|5person|8many|8bad|5fruit|1he/4him|5tool||2fix/8good||2have||8one'.split`|`[n=parseInt(w,35)%781%21])&&(x=(g=_=>x.split`/`.find(x=>x[0]>>t&1,t++)||g())(),o[t]=x.slice(1),O[t]=n),o=[t=-1],O=[]))&&([s,v,o,a]=o,[S,V,O,A]=O,g=n=>4241>>n&1?'':'the ')(S)+s+` ${y=144>>S&1,1/V?V^17|y?v:'ha':S^4?S^7?'i':'am':'are'}${y?'':V^15?'s':'es'} `+g(A%10^9&&O)+[a&&a+' ']+[o]+['s'[A^9]]
```
[Try it online!](https://tio.run/##hZVLb@IwFIX3/RVWNc1DSUnDgEorJai7YcWCUTeZMHiKCS6JjXB4qe5vZ65NIDySFglQLJ/P1@ceO@94hcXbgs7ze8bHZDcJdiIILdFYkHmK34jl/Vk7XuKuYXATmM01ZrmUTYJzrz3hfCxle8uXsikI8dpkS2Q7n1KWSL/ntTJ4mpOF4Ex2Msy2svMPj2V7sljSXPpT4rWmNAMB5ykgJ3TjdRKNbE7xikjZ4YyYDTFPaT6So4gFc7wQpMdya@3@bNt3jx3/runHtmFAaVYS/A3CTTHdGzUmlI1hPNxED3EY5obv5o5jS5lYtm3ZLo/yOIDpKYVN@rbbV88MxoMoD@792O0HUWwrdiTclctdHAfcjQbuq9t3X@Kg7yYBC8JWs@WHITP8rmk@m/mUINO2BrYjnBH68bEN/FYrDAewuO@9dl@H/qPcdlfP5hSbz4NhqzsYPnZNCkqcqZ8FMT9BpVgwt901BYwSYX6ikZNYL3f@w/DJMPq2E2HDwI6JzNiJOHxhYvQyfIrj3RtngqekkfLEmli3GUVrmhJEUMZny1vbRseP56EeUv1EqmzVzJtrsVLViiEFX2nnnOEz0akWZ0g12@shaHyF@B2zKu1RrNbdh@tSDKuilCI@41cAEP8iCLIqPPinQlMgtTWIqhr2iEL6ZQH0nSM6I5e2lWo4DUiflksArKuX5@D8jKb0BAGA38eF0RTvSfpI1VDAhwJTNuScovzQGNWQapaWp/Q6B0eWlh12pgLhlaOQE3HVYhWsr4mqmiugGvyOdxHYU56S1mZWdezgu3IvW@aH9hUM3S5tu7rQCgOvaqGp5ii7gQTUcoMHDtx5KviF8ZUpEBTkxXa0/2U5QIFbV58/XYe2WXwLKNN4AjgksbLvKjzHDGWnQTzsBE7PPkAZuam9e1QlNXcPlFET3KLys0vkPLi6mfAOqbo@@N55tchF1T2kXi/ArfH9VH2SgHO1tl3Lq22/OLalXtkO93x5bHf/AQ "JavaScript (Node.js) – Try It Online")
### How?
We first split the input string \$s\$ into words and interpret each of them as an integer in base \$35\$, modulo \$781\$ and modulo \$21\$, which gives a unique ID \$n\$ in \$[0..19]\$. We associate a data string to each ID as follows:
```
word | base 35 to decimal | mod 781 | mod 21 | data
--------+--------------------+---------+--------+--------------
'mi' | 788 | 7 | 7 | '1I/4me'
'sina' | 1223365 | 319 | 4 | '5you'
'ona' | 30215 | 537 | 12 | '1he/4him'
'jo' | 689 | 689 | 17 | '2have'
'moku' | 973380 | 254 | 2 | '2eat/5food'
'pona' | 1102090 | 99 | 15 | '2fix/8good'
'oko' | 30124 | 446 | 5 | '2see/5eye'
'wile' | 1394799 | 714 | 0 | '2want'
'ike' | 22764 | 115 | 10 | '8bad'
'wan' | 39573 | 523 | 19 | '8one'
'mute' | 981029 | 93 | 9 | '8many'
'kili' | 880303 | 116 | 11 | '5fruit'
'jan' | 23648 | 218 | 8 | '5person'
'ilo' | 22809 | 160 | 13 | '5tool'
'ijo' | 22739 | 90 | 6 | '5thing'
'li' | 753 | 753 | 18 | ''
'e' | 14 | 14 | 14 | ''
```
We keep track of the expected type of the next word in the variable \$t\$:
* \$t=0\$: subject
* \$t=1\$: verb
* \$t=2\$: object
* \$t=3\$: adjective
The leading digit in front of each translated word is a bitmask describing the types that the word can be associated with. For instance, `"5fruit"` means that `"fruit"` may be either the *subject* (\$2^0=1\$) or the *object* (\$2^2=4\$) of the sentence.
We use this information to assign the relevant type to each input word. At the end of this process, the array `[s,v,o,a]` holds the categorized words (subject, verb, object and adjective, respectively) while the array `[S,V,O,A]` holds the corresponding indices, as described in the penultimate column of the above table.
Using these variables, we can finally apply English rules to translate the sentence.
[Answer]
# [Python 3](https://docs.python.org/3/), 1902 bytes
```
import re
p='mi|sina|ona'
v='jo|moku|pona|oko|wile'
a='pona|ike|wan|mute'
n='kili|oko|jan|moku|ilo|ijo'
pn=p+'|'+n
d={'p':p,'v':v,'a':a,'n':n,'pn':pn,'li':'li','e':'e',
'f':'(?:(?:'+pn+') li|(?:mi|sina))'}
g=['f '+i for i in 'v,pn,n a,v e pn,v e n a'.split(',')]
ma=[re.compile('^%s$'%re.subn(r'\w+',lambda m:'({%s})'%m.group(0),i)[0].format(**d))
for i in g]
tr0=lambda ph:[m.match(ph) and m.match(ph).groups() for m in ma]
d_={'s':{'mi':'I','sina':'you','ona':'he'},'o':{'mi':'me','sina':'you','ona':'him'},'v':{'jo':'have','moku':'eat','pona':'fix','oko':'see','wile':'want'},'n':{'moku':'food','oko':'eye','kili':'fruit','jan':'person','ilo':'tool','ijo':'thing'},'a':{'pona':'good','ike':'bad','wan':'one','mute':'many'}}
md=lambda x:dict((k,v) for i in x for k,v in d_[i].items())
d_['pn']=md('on')
d_['f']=md('sn')
d_['e']={'e':'_'}
mc=lambda x:lambda t:(lambda d:d[t] if t in d else d['_'])(x)
be=mc({'I':'am','you':'are','_':'is'})
vs=lambda p:list(d_[p].values())
os=vs('o')+vs('s')
tr=lambda x:[(n_,[d_[p][w if n else w.split(' ')[0]] \
for n,(w,p) in enumerate(zip(i,pt.split(' ')))]) \
for n_,(i,pt) in enumerate(zip(x,g)) if i]
noun=lambda t:lambda n:n if n in os else t+n
the=noun('the ')
the2=lambda n:'' if n in os else 'the '
v_=mc({'I':'','you':'','_':'s'})
m_=lambda o,a:('s' if (a == 'many') and (o not in os) else '')
tr_={0:lambda n,v:[the(n),
v+v_(n)],
3:lambda s,v,e,o:[the(s),v+v_(s),the(o)],
1:lambda s,o:[the(s),be(s),the(o)],
2:lambda s,o,a:[the(s),be(s),the2(o)+a,o+m_(o,a)],
4:lambda s,v,e,o,a:[the(s),v+v_(s),the2(o)+a,o+m_(o,a)],
}
from functools import reduce
f_={'haves':'has','fixs':'fixes','the one':'one','the many':'many'}
fx=lambda s:reduce(lambda x,y:x.replace(y[0],y[1]),f_.items(),s)
c=lambda s:s[0].upper()+s[1:]
r=lambda s:[(n,c(fx(' '.join(tr_[n](*a))))) for n,a in tr(tr0(s))]
```
[Try it online!](https://tio.run/##dVXbbuM4DH33V@hhC0qNELSdfTJg7PN@g8cTqLGcqIkusGQnmSbf3iVlJynaHaOoSOqQOuJFCae09e7Hx0dhbPB9Yr0uQgXWnKNx6uydgmKs4M2frd8N5@DJuPPng9lrKFQF2WJ2@nxQ7myHhFZXwc7sTca9kZU8zd6fzZuHIrgqLOAMC1e01TsEKIOEEcpRgoJSSXBQOgkBl4Dr3kBJ/yRoFDTIgjEGHcr8nxL/YBHcAgTD81CbeQsBl2JT1dAxWBjW@Z4ZZhyDUWJMx5QcmWYo0oIqLGPYm8TxFNEUVlV1r5drbwPeksOvh/gXPKAlDq@O9/DzsAC5V/a1Vcwij/eHeBHwYJeb3g@BPwlpRP3ULPFYqxJ/fGyFINZ3HpumSP1TNccI27K2S4SutzxsBVOuZZ/0KWzkIvtb8reqKdoVZi9C@Y7Fwmz8i9zp6iie/ICKz/JWwwXlG8zqP@CMJeBIQKwSGtRIUKod5V0lVMKE7cyR/HYEi5pQuRtKwBZIFMXl4ybPzvv2htYnQlNz0E4/GIqKLYJa0H30DlVsFFST93tSMpe0NW5DgRUFnllspsDYeqi8KpIPOZJ3mTi1It5XuRNcLoVtr9k@lq1ZJ853chT3ihyziDZS2lVtmqVJ2mLWBWa6pnZsKttyjA6TpZsN8WrQaHjPXbrC7rPr@4GzkEo@S23Z1qlhpmMpn8f0PmrW1ujZCH4Uxauu7Jq/Y1VLUBavQ7VCsaerrVAyES6iGOOth8q9iYkjj9AsR7UfdKbuYzVGJA1iQWtEqqm/E6u5W8k6O9UHouMmJofrPDCgTm7Yz9y/94@S5SQ/yCDoAtoNVvcqaf7bBG5kSJ8CCNGIrwGy/0pm6P9EOMqNEMTHNIXzg6tuGZwFV7qJLrr6OJFO@KKkra7IgWPPaEa33eqX6uYE8M1rAhbj6p7wW7rnXOdU29U1jJeqpFRSKK5YVbGpy6bB5Z45n6YTxHxEzjqO69ONvhzLGg/mTsgvmc3fuBhXuNfMmz@uflGOUks/@UYhMw5XUv0N/nyH36Gv@jvw5RMQL/UN@oLYhZJ@YVccATe/v7/w@eT7idGfvC9F13vLusGtacoju/3ytMNaFx29a/T6xPwKRSwCPjhxenc0qVQxGvLrqJOeK3Ad96I7XosVyynsdfKO8lQel70Oe4XGEza3PNXPjZDd6jrwMopiffeP9JQPAd8nLhaxfi6bor/v4gTJNe@O1OnLN28cx0rXruGP@COE3zwpihoi9bj5hNkRzcfHfw "Python 3 – Try It Online")
The function `r` does the thing.
The testing:
```
s=r'''mi wile e moku - I want the food
mi moku e moku - I eat the food
mi pona - I am good/I fix*
mi jan - I am the person
ona li oko - He sees/He is the eye*
ona li jan - He is the person
ona li ijo ike - He is the bad thing
jan li jo e kili - The person has the fruit
jan li oko e kili pona - The person sees the good fruit
kili li moku - The fruit is the food/The fruit eats*
moku li moku - The food is the food/The food eats*
moku li moku e moku - The food eats the food
ijo li jo e jan mute - The thing has many persons
ilo li pona e ijo - The tool fixes the thing
sina moku e kili mute - you eat many fruits
sina moku e kili ike - you eat the bad fruit
oko li oko e mi - The eye sees me
mi wile e sina - I want you
jan li moku e ona - The person eats him
mi jo e ijo wan - I have one thing
mi jo e ijo mute - I have many things'''.split('\n')
print('\n'.join(str((r(j.split(' - ')[0]),
j.split(' - ')[1].rstrip('*').split('/'))) \
for j in s))
```
The test output:
```
([(3, 'I want the food')], ['I want the food'])
([(3, 'I eat the food')], ['I eat the food'])
([(0, 'I fix')], ['I am good', 'I fix'])
([(1, 'I am the person')], ['I am the person'])
([(0, 'He sees'), (1, 'He is the eye')], ['He sees', 'He is the eye'])
([(1, 'He is the person')], ['He is the person'])
([(2, 'He is the bad thing')], ['He is the bad thing'])
([(3, 'The person has the fruit')], ['The person has the fruit'])
([(4, 'The person sees the good fruit')], ['The person sees the good fruit'])
([(0, 'The fruit eats'), (1, 'The fruit is the food')], ['The fruit is the food', 'The fruit eats'])
([(0, 'The food eats'), (1, 'The food is the food')], ['The food is the food', 'The food eats'])
([(3, 'The food eats the food')], ['The food eats the food'])
([(4, 'The thing has many persons')], ['The thing has many persons'])
([(3, 'The tool fixes the thing')], ['The tool fixes the thing'])
([(4, 'You eat many fruits')], ['you eat many fruits'])
([(4, 'You eat the bad fruit')], ['you eat the bad fruit'])
([(3, 'The eye sees me')], ['The eye sees me'])
([(3, 'I want you')], ['I want you'])
([(3, 'The person eats him')], ['The person eats him'])
([(4, 'I have one thing')], ['I have one thing'])
([(4, 'I have many things')], ['I have many things'])
```
The raw thing:
```
import re
p='mi|sina|ona'
v='jo|moku|pona|oko|wile'
a='pona|ike|wan|mute'
n='kili|oko|jan|moku|ilo|ijo'
pn=p+'|'+n
d={'p':p,'v':v,'a':a,'n':n,'pn':pn,'li':'li','e':'e',
'f':'(?:(?:'+pn+') li|(?:mi|sina))'}
g=['f '+i for i in 'v,pn,n a,v e pn,v e n a'.split(',')]
ma=[re.compile('^%s$'%re.subn(r'\w+',lambda m:'({%s})'%m.group(0),i)[0].format(**d))
for i in g]
s=r'''mi wile e moku - I want the food
mi moku e moku - I eat the food
mi pona - I am good/I fix*
mi jan - I am the person
ona li oko - He sees/He is the eye*
ona li jan - He is the person
ona li ijo ike - He is the bad thing
jan li jo e kili - The person has the fruit
jan li oko e kili pona - The person sees the good fruit
kili li moku - The fruit is the food/The fruit eats*
moku li moku - The food is the food/The food eats*
moku li moku e moku - The food eats the food
ijo li jo e jan mute - The thing has many persons
ilo li pona e ijo - The tool fixes the thing
sina moku e kili mute - you eat many fruits
sina moku e kili ike - you eat the bad fruit
oko li oko e mi - The eye sees me
mi wile e sina - I want you
jan li moku e ona - The person eats him
mi jo e ijo wan - I have one thing
mi jo e ijo mute - I have many things'''.split('\n')
x=[(lambda ph:[m.match(ph) and m.match(ph).groups() for m in ma])\
(i.split(' - ')[0]) for i in s]
y=r'''mi (subject) -> I
mi (object) -> me
sina (subject) -> you
sina (object) -> you
ona (subject) -> he
ona (object) -> him
jo (verb) -> to have
moku (verb) -> to eat
moku (noun) -> food
pona (verb) -> to fix
pona (adjective) -> good
oko (verb) -> to see
oko (noun) -> eye
wile (verb) -> to want
ike (adjective) -> bad
wan (adjective) -> one
mute (adjective) -> many
kili (noun) -> fruit
jan (noun) -> person
ilo (noun) -> tool
ijo (noun) -> thing'''
from collections import defaultdict
d_=defaultdict(dict)
for w,p,t in re.findall(r'(\w+)\s*\((\w+)\)\s*\-\>\s*(?:to )?(\w+)',y):
d_[p[0]][w]=t
md=lambda x:dict((k,v) for i in x for k,v in d_[i].items())
d_['pn']=md('on')
d_['f']=md('sn')
d_['e']={'e':'_'}
#print(d_)
mc=lambda x:lambda t:(lambda d:d[t] if t in d else d['_'])(x)
be=mc({'I':'am','you':'are','_':'is'})
hv=mc({'I':'have','you':'have','_':'has'})
vs=lambda p:list(d_[p].values())
tr=lambda x:[(n_,[d_[p][w if n else w.split(' ')[0]] \
for n,(w,p) in enumerate(zip(i,pt.split(' ')))]) \
for n_,(i,pt) in enumerate(zip(x,g)) if i]
#print('\n'.join(str((tr(i),j.split(' - ')[1].rstrip('*').split('/'))) \
# for i,j in zip(x,s)))
noun=lambda t:lambda n:n if n in vs('o')+vs('s') else t+n
the=noun('the ')
the2=lambda n:'' if n in vs('o')+vs('s') else 'the '
v_=mc({'I':'','you':'','_':'s'})
a_=lambda s:('the ' if s not in vs('p') else '')
m_=lambda o,a:('s' if (a == 'many') and (o not in vs('o')+vs('s')) else '')
tr_={0:lambda n,v:[the(n),
v+v_(n)],
3:lambda s,v,e,o:[the(s),v+v_(s),the(o)],
1:lambda s,o:[the(s),be(s),the(o)],
2:lambda s,o,a:[the(s),be(s),the2(o)+a,o+m_(o,a)],
4:lambda s,v,e,o,a:[the(s),v+v_(s),the2(o)+a,o+m_(o,a)],
}
from functools import reduce
f_={'haves':'has','fixs':'fixes','the one':'one','the many':'many'}
fx=lambda s:reduce(lambda x,y:x.replace(y[0],y[1]),f_.items(),s)
c=lambda s:s[0].upper()+s[1:]
print('\n'.join(str(([(n,c(fx(' '.join(tr_[n](*a))))) for n,a in tr(i)],
j.split(' - ')[1].rstrip('*').split('/'))) \
for i,j in zip(x,s)))
#print('\n'.join(map(str,x)))
```
You can run it to see it passes all the cases)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~257~~ 249 bytes
```
OP€%59µ“:¤¥“ ı“¦1"ø“/“2¿“#“,3‘œiⱮ¹Ƈ’S,@ɗ>5Ḣ$¡"J1,3yƊ$ḢW;1,6y$1¦€ƲḢ,2,3;Ʋ2,1œị=3Ʋ¡+2¦=2Ḣ$¡€58,3iⱮ×7ḢƲḣ;Ṛḣ¥ɗL=4Ɗ¡2+2¦e€3,4Ḣ$¡€1,3¦7œị“¢ṇḃ#ṅ³©½øỴ£⁺Ṭḥ*4=LƤ`:[?SœGʠṂ4£¤ɦ5Ẉḃ⁵ƓOqȤ2MœṁṾġqÐU¤¶ṀẆ¶`ƝUḋ#ḳ#Ạ4Ẏ[`-ckṫ©4%ṙẎọkɲẠ¶{t}6ọ6Ṇ»ỴḲ€“the ”;Ɱ;@Ɗ€3,4¦¤K;11e”sxƲ
```
[Try it online!](https://tio.run/##bVFdaxNBFH3fX7E06Ytukf1Iql1S@ybYSoVSRPqSIgtOdtO1NKUGEZIWG0lRhDzEioWmSRaKRejWhp0EFe42i/FfzP6ReGeTjQF9mLn3nrnn3DMzOcOyisPh6uNw/2I2dQ@uw9LnBWhBG6N4c4k7OPKM72FyB5cCP3FP4JLUsPSxXyPh5VegQSUsHa9JS4P6Yop5Z0lozDyUJbUYVJNYPtFlKV1MyuDgkMBFRFIkVQ9cRZL7NdY7yqiBC43bCjgZZUTHxtRdSeXqfn0eMU5r6ox@wgDtQX0lowVVaCicZGC3KmkTJk4GZz5S5v7PGK0w7yDB6Bu4gnP47nus9w2aYbnL6AXz2re0zErQyi5s3F/r1x78PmV0X4MmtAZOinXfIjUsXwe11e1fLeURqtIyoz9uGtv@h3V8qA6jJdY9hE42OFln3lGCeVcJ1j3VWPf9RnbumcnoFzjXZhk9RoT13pkDF4@h86rwOo1lmtFD6KEh5rnoHQ0XnhtiWDrR8e76UlAdXQ4caC3rsmzgyc7LwB0u6/yH5hajVr8iTBT8Cm5Ph8M8EfeIZYiGmLfNXQFLHqfKF/bWJo@5zS0BU9Eiom3acTqFkpwtEtMQEIpObBQxiUViAFljZKQZZRYZD@JD/1fETrh6rMoF87sFQyBWBHI5hLFF2CGYjnnRgKjvH5T75H4mtvJE@PsSvD12PWbFj2CP5oh7eO/pmo/5Aw "Jelly – Try It Online")
A monadic link taking a list of words and returning a string. I’m sure this can be better golfed, but I was just pleased to have something that worked despite the various complexities of the English language!
## Explanation
### Stage 1
Convert to initial pairs of integers
Note the first of each pair is initially 1 for pronouns, 2 for verbs, 3 for nouns, 4 for adjectives, 5 for quantifiers, 6 for verb/adjective and 7 for verb/noun
```
O | Convert to Unicode codepoints
P€ | Product of each word
%59 | Mod 59
µ | Start a new monadic chain
“:...3‘œiⱮ | Multidimensional index of this in [[58, 3, 4], [32, 25], [5, 49, 34, 29], 47, [50, 11], 35, [44, 51]]
¹Ƈ | Filter ones that weren’t found (li and e)
```
### Stage 2
Determine meaning for words with two possible meanings; works because nouns can only appear in positions 1 and 3, verbs only in position 2 and adjectives in position 4
```
$ | Following as a monad:
" Ɗ | - Map a link using the following as a monad as the right argument zipped with each element of the input to stage 2 as the left
J | - Index along list
1,3y | - Substitute 1s for 3s (words in the first position
$¡ | - If:
>5 | - Greater than 5
Ḣ | - Head (i.e. if first number is >5)
| - Then:
’ | - Increment both items in the pair by 1
S | - Sum
,@ | - Pair the right argument with this
```
### Stage 3
Change pronouns appearing after position 1 to have 6 as their first integer (so that object versions can be used)
```
Ʋ | Following as a monad:
Ḣ | - Head
W | - Wrap in a list
; | - Concatenate to:
1,6y$1¦€ | - The other list members at input to stage 3, with 1 replaced by 6
```
### Stage 4
Insert ‘to be’ if there is no verb
```
Ɗ¡ | If:
2,1œị | - the word type of the second word
=3 | - is equal to 3 (noun)
Ʋ | Then following as a monad:
Ḣ | - Head
,2,3 | - Pair with [2,3] (verb to be)
; | - Concatenate to rest of list
```
### Stage 5
If first word is ‘I’ or ‘you’, add 7 or 14 respectively to the verb number
```
$¡€ | For each word, if:
=2 | - Equals 2
Ḣ | - Head (i.e. if word is a noun)
+2¦ Ʋ | Add to the second item (word number) the following as a monad:
58,3iⱮ | - Index of mod 59 words (from stage 1) within 58 (I), 3 (you)
×7 | - Multiply by 7
Ḣ | - Head (i.e. 7 if first word is ‘I’ and 14 if first word is ‘you’.
```
### Stage 6
Swap noun and adjective or quantifier around if present
```
Ɗ¡ | If (as a monad):
L | - Length
=4 | - Equals 4
ɗ 2 | Then (as a dyad), using 2 as the right argument:
ḣ | - First 2 words
; ¥ | - Concatenated to following as a dyad:
Ṛ | - Reverse
ḣ | - First two words (i.e. last 2 words in reverse order)
```
### Stage 7
Use version of nouns and adjectives with preceding ‘the’ if they appear in the third or first position
```
€1,3¦ | For each of first and third words
$¡ | - If (as a monad):
e€3,4 | - Is one of 3 or 4
Ḣ | - Head (i.e. if word type is noun or adjective)
| - Then:
+2¦ 7 | - Add 7 to the second item (i.e. word number)
```
### Stage 8
Index into word list
```
œị ¤ | Multidimensional index into following as a nilad
“¢...Ṇ» | - “I you he/wants has is fixes eats sees want have am fix eat see want have are fix eat see/fruit person tool thing food eye/good bad/one many/me you him” where / indicates newline
Ỵ | - Split at newlines
Ḳ€ | - Split each at spaces
Ɗ€3,4¦ | - For each of the third and fourth lists of words, do the following as a monad:
“the ”;Ɱ | - Concatenate “the “ to each
;@ | - Concatenate to end of list
```
### Stage 9
Add “s” to end if many is used
```
K | Join with spaces
; Ʋ | Concatenate to the following as a monad (applied to the mod 59 words from stage 1)
11e | - Contains 11 (many)
”sx | - that many “s”
```
] |
[Question]
[
## Challenge:
**Input:** Three integers: bottom-edge length; starting amount of grains of sand; index
**Output:** Output the state of the bottom part of an hourglass at the given index, based on the given bottom-edge length and amount of grains of sand.
## Challenge rules:
* We simulate the grains of sand with digits 1-9
* We put the currently remaining amount of grains of sand at the top in the middle, following by a single character of your own choice (excluding digits, whitespaces and new-lines; i.e. `-`) on the line below it
* When the hourglass is being filled, we fill it per row, one digit at a time
* When the sand can go either left or right, we ALWAYS go right (the same applies to balancing the remaining amount of grains of sand above the hour glass)
* When we've reached 9 it's filled, and we can't fit any more sand at that specific place in the hourglass
* The amount of grains of sand left are also always rightly aligned
* Once the bottom halve of the hourglass is completely filled, or the amounts of grains of sand left reaches 0, we can't go any further, and this would be the output for all indexes beyond this point
* Both 0-indexed or 1-indexed is allowed, and please specify what you've used in your answer.
* Trailing and leading spaces and a single trailing or leading new-line are optional
* You are allowed to use any other character instead of a zero to fill up empty spaces of the bottom part of the hourglass (excluding digits, new-lines, or the character you've used as neck), if you choose to display them.
* The bottom-edge length will always be odd
* The bottom-edge length will be `>= 3`; and the amounts of grains of sand `>= 0`
* If you want you are also allowed to print all states up to and including the given index
* You can assume the (0-indexed) index will never be larger than the total amount of grains of sand (so when there are 100 grains of sand, index 100 is the maximum valid index-input).
* The first index (0 for 0-indexed; 1 for 1-indexed) will output an empty hourglass with the amount of grains of sand above it.
**Example:** Pictures (or ascii-art) say more than a thousand words, so here is an example:
Input bottom-edge length: `5`
Input amount of grains of sand: `100`
Instead of a current index, I display all steps here:
Output for all possible indexes with bottom-edge length `5` and amount of grains of sand `100`:
```
100
-
0
000
00000
99
-
0
000
00100
98
-
0
000
00110
97
-
0
000
01110
96
-
0
000
01111
95
-
0
000
11111
94
-
0
000
11211
93
-
0
000
11221
92
-
0
000
12221
91
-
0
000
12222
90
-
0
000
22222
89
-
0
000
22322
88
-
0
000
22332
87
-
0
000
23332
86
-
0
000
23333
85
-
0
000
33333
84
-
0
000
33433
83
-
0
000
33443
82
-
0
000
34443
81
-
0
000
34444
80
-
0
000
44444
79
-
0
000
44544
78
-
0
000
44554
77
-
0
000
45554
76
-
0
000
45555
75
-
0
000
55555
74
-
0
000
55655
73
-
0
000
55665
72
-
0
000
56665
71
-
0
000
56666
70
-
0
000
66666
69
-
0
000
66766
68
-
0
000
66776
67
-
0
000
67776
66
-
0
000
67777
65
-
0
000
77777
64
-
0
000
77877
63
-
0
000
77887
62
-
0
000
78887
61
-
0
000
78888
60
-
0
000
88888
59
-
0
000
88988
58
-
0
000
88998
57
-
0
000
89998
56
-
0
000
89999
55
-
0
000
99999
54
-
0
010
99999
53
-
0
011
99999
52
-
0
111
99999
51
-
0
121
99999
50
-
0
122
99999
49
0
222
99999
48
-
0
232
99999
47
-
0
233
99999
46
-
0
333
99999
45
-
0
343
99999
44
-
0
344
99999
43
-
0
444
99999
42
-
0
454
99999
41
-
0
455
99999
40
-
0
555
99999
39
-
0
565
99999
38
-
0
566
99999
37
-
0
666
99999
36
-
0
676
99999
35
-
0
677
99999
34
-
0
777
99999
33
-
0
787
99999
32
-
0
788
99999
31
-
0
888
99999
30
-
0
898
99999
29
-
0
899
99999
28
-
0
999
99999
27
-
1
999
99999
26
-
2
999
99999
25
-
3
999
99999
24
-
4
999
99999
23
-
5
999
99999
22
-
6
999
99999
21
-
7
999
99999
20
-
8
999
99999
19
-
9
999
99999
```
So as example:
```
inputs: 5,100,1
output:
99
-
0
000
00100
Same example with another valid output format:
99
~
.
...
..1..
```
## 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, 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:
```
INPUTS: bottom-edge length, amount of grains of sand, index (0-indexed)
inputs: 5,100,1
output:
99
-
0
000
00100
inputs: 5,100,24
output:
76
-
0
000
45555
inputs: 5,100,100
output:
19
-
9
999
99999
inputs: 5,10,15
output:
0
-
0
000
22222
inputs: 3,30,20
output:
10
-
0
677
inputs: 3,3,0
3
-
0
000
inputs: 9,250,100
150
-
0
000
00000
2333332
999999999
inputs: 9,225,220
5
-
4
999
99999
9999999
999999999
inputs: 13,1234567890,250
1234567640
-
0
000
00000
0000000
344444443
99999999999
9999999999999
inputs: 25,25,25
0
-
0
000
00000
0000000
000000000
00000000000
0000000000000
000000000000000
00000000000000000
0000000000000000000
000000000000000000000
00000000000000000000000
1111111111111111111111111
```
[Answer]
# [Clean](https://clean.cs.ru.nl), ~~305~~ 289 bytes
```
import StdEnv
@[h:t]|all((==)9)h|t>[]=[h: @t]=[h]
#s=length h/2
#m=hd(sort h)+1
=[updateAt(hd[e\\e<-flatten[[s+i,s-i]\\i<-[0..s]]|h!!e<m])m h:t]
$a b c=flatlines(map(cjustify(a+1))[fromString(fromInt(b-c)),['-']:reverse(map(map(toChar o(+)48))((iterate@[repeatn(a-r)0\\r<-[0,2..a]])!!c))])
```
[Try it online!](https://tio.run/##HY7BasMwEETv/gqZBCLhyLVDC22ISkrbQ6G3HGUdFHsTqViykTaBQL69qt3DMsvAzLy2B@2TG7pLD8Rp65N14xCQHLD79NdsL80W1V33PaVCsBdm7vgqlZhsssdZVbaIogd/RkPMwyZbOGE6GucOw4o6E/IydhrhDanpJDQN7Pip14jgpYyFXUduVdPYHZdVWUal7ibPYecUc2TezpaaHEkr5kxvPUTq9Ejbn0tEe7pRXdSMyVMY3AGD9Wc6v18e6ZG3jK3liq/UNsAVQoT/5Hw4vBsdyEAL9vjMGKUWIUyMexlgBI2eah5Y1TRhplpvylIrxfJ8alQsHVAHzARZkidSVxWp02870Z1j4sfEv77Tx81rZ9v4Bw "Clean – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~68~~ ~~63~~ ~~59~~ ~~57~~ 56 bytes
```
IÅÉÅ9[DOO²Q#ćD_Piˆëć<¸«¸ì]ćā<ΣÉ}2äćR¸ì˜è¸ì¯ìJDSOIα'-‚ì.C
```
[Try it online!](https://tio.run/##MzBNTDJM/f/f83Dr4c7DrZbRLv7@hzYFKh9pd4kPyDzddnj1kXabQzsOrT604/Ca2CPtRxptzi0@3FlrdHjJkfYgkODpOYdXgOhD6w@v8XIJ9vc8t1Fd91HDrMNr9Jz//zc05jIyseQyNDAwAAA "05AB1E – Try It Online")
**Explanation**
`IÅÉÅ9`
We initialize the stack with a list of list of 9's.
Each list represents a row so the length of each list is odd and the length of the last list is equal to the first input.
An input of **5** would result in `[[9], [9, 9, 9], [9, 9, 9, 9, 9]]`
`[DOO²Q#ćD_Piˆëć<¸«¸ì]`
We then iterate over these lists decrementing elements in a list until the list consists only of zeroes, then moving on to the next. We stop when the total sum equals the second input.
```
[ # ] # loop until
DOO # the sum of the list of lists
²Q # equals the second input
ć # extract the first list
D_Pi # if the product of the logical negation of all elements is true
ˆ # add the list to the global list
ë # else
ć< # extract the head and decrement it
¸« # append it to the list
¸ì # and prepend the list to the list of lists
```
Now we need to unsort the final list simulating removing elements from alternating sides instead of left-to-right as we have been doing.
```
ć # extract the row we need to sort
ā< # push a list of indices of the elements [0 ... len(list)-1]
ΣÉ} # sort it by even-ness
2äćR¸ì˜ # reverse the run of even numbers
# the resulting list will have 0 in the middle,
odd number increasing to the right and
even numbers increasing to the left
è # index into our final row with this
¸ì¯ì # reattach all the rows to eachother
```
Now we format the output correctly
```
J # join list of lists to list of strings
DSOIα # calculate the absolute difference of sum of our triangle and the 3rd input
'-‚ì # pair it with the string "-" and append to the list of rows
.C # join by newlines and center each row
```
[Answer]
# [Perl 5](https://www.perl.org/), 301 bytes
```
($x,$t,$u)=<>;$s=$x;$t-=$g=$t>$u?$u:$t;while($s>0){@{$a[++$i]}=((0)x$s,($")x($x-$s));$a[$i][$_%$s]++for 0..($f=$g<$s*9?$g:$s*9)-1;$g-=$f;$s-=2}say$"x(($x-length($g+=$t))/2+.5),$g,$/,$"x($x/2),'-';while(@b=@{pop@a}){for($i=1;$i<@b;$i+=2){print$b[-$i]}print$b[0];for($i=1;$i<@b;$i+=2){print$b[$i]}say''}
```
[Try it online!](https://tio.run/##fY7RaoMwFIbv@xSj/MOcJdFUELamaX2BPUGRoVBtQFRMyhziq89F2G53cw6H8/P933Ab22xdGSYBL/AgczprOINJw0uDxsCf8bjgcYTXn3fb3hjcWdGczyivnMMWi2FM0QQnGPY0BZaEI9LhH75XfDzDFZzX/fik4pihDtgT3MvbBc1x2yQPGk1oq0O1NOniyi/sJ7aR2lvX@DtDw4MJUZLyOCOBRiARWwZTkpKIZPQrl1cmn4d@yMuF5lDJYE2g21NehclNSvMw2s6jusrN/e9Qhf4/vYWDVxQt65rtXrPdQanvfvC279wq37NYHdQP "Perl 5 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~68~~ ~~63~~ 62 bytes
```
NθNηNζF⊘⊕θF⁹F⁻θ⊗ι«J⊘⎇﹪λ²⊕λ±λ±ι≔¬¬ζλ↑I⁺λIKK≧⁻λη≧⁻λζ»↑-M⊘⊖LIη←Iη
```
[Try it online!](https://tio.run/##fVBBasMwEDzHrxA5rUCBkJwan0pzaEpsQkkfoDgby1SWbFkyNKVvd9d2TUIPEQjtaEazO8qUdJmVuut2pgo@DeUJHdQ8ju6x@oevhC/WMXiVusUz7EzmsETjqa4552wgn/7OpDChgVqwrQ0nTZKil3xHs7dQVkc7mRzRGem@ILHnoC1owVZcsHtrTTjFXHqkkt8A@cXR7LlpitxAav2wr71A98TBFcbD5qMS7EU2Hg6axtETQPwE3i9SJrIaXd6LXPlxcDIRTD1k@@/4ie7azBdzukpsi1O4Ld5i7NHkXsHQXvEhyGaPF09PRo@JibtuLdZLsVp2i1b/Ag "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 5 bytes by removing the now-unnecessary index range check. Explanation:
```
NθNηNζ
```
Input the length into `q`, the number of grains of sand into `h` and the index into `z`.
```
F⊘⊕θF⁹F⁻θ⊗ι«
```
Loop over the `(q+1)/2` rows (from bottom to top), then 9 grains in each cell in the row, then loop over the digits in the row.
```
J⊘⎇﹪λ²⊕λ±λ±ι
```
Jump to the digit.
```
≔¬¬ζλ↑I⁺λIKK≧⁻λη≧⁻λζ»
```
If possible, distribute a grain of sand to this digit, decrementing the amount of sand and index left. If we've passed the index, this still converts spaces to zeros, filling the hourglass. The digit is printed upwards because this means that the cursor will be on the neck after the last digit.
```
↑-
```
Print the neck.
```
M⊘⊖LIη←Iη
```
Centre and print the amount of sand remaining.
] |
[Question]
[
### Background
After applying the BWT (as seen in [Burrows, Wheeler and Back](https://codegolf.stackexchange.com/q/51397)) and the MTF (as seen in [Move to the printable ASCII front](https://codegolf.stackexchange.com/q/52592)), the [bzip2](https://en.wikipedia.org/wiki/Bzip2) compressor applies a rather unique form of run-length encoding.
### Definition
For the purpose of this challenge, we define the transformation BRLE as follows:
Given an input string **s** that consists solely of ASCII characters with code points between 0x20 and 0x7A, do the following:
1. Replace each run of equal characters by a single occurrence of the character and store number of repetitions after the first.
2. Encode the number of repetitions *after the first occurrence of the character*, using [bijective base-2 numeration](https://en.wikipedia.org/wiki/Bijective_numeration#Properties_of_bijective_base-k_numerals) and the symbols `{` and `}`.
A non-negative integer **n** is encoded as the string **bk…b0** such that **n = 2ki(bk)+…+20i(b0)**, where **i(`{`) = 1** and **i(`}`) = 2**.
Note that this representation is always unique. For example, the number **0** is encoded as an empty string.
3. Insert the string of curly brackets that encodes the number of repetitions after the single occurrence of the corresponding character.
# Step-by-step example
```
Input: "abbcccddddeeeeeffffffggggggghhhhhhhh"
Step 1: "abcdefgh" with repetitions 0, 1, 2, 3, 4, 5, 6, 7
Step 2: "" "{" "}" "{{" "{}" "}{" "}}" "{{{"
Step 3: "ab{c}d{{e{}f}{g}}h{{{"
```
### Task
Implement an involutive program or function that reads a single string from STDIN or as command-line or function argument and prints or returns either the BRLE or its inverse of the input string.
If the input contains no curly brackets, apply the BRLE. If the input contains curly brackets, apply its inverse.
### Examples
```
INPUT: CODEGOLF
OUTPUT: CODEGOLF
INPUT: PROGRAMMING
OUTPUT: PROGRAM{ING
INPUT: PUZ{LES
OUTPUT: PUZZLES
INPUT: 444488888888GGGGGGGGGGGGGGGGWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW
OUTPUT: 4{{8{{{G{{{{W{{{{{
INPUT: y}}}{{
OUTPUT: yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
```
### Additional rules
* You *cannot* use any built-ins that compute the BRLE or its inverse of a string.
* You *can* use built-ins that:
+ Compute the RLE or RLD of a string, as long as the number of repetitions is not stored in bijective base-2.
+ Perform base conversion of any kind.
* Your code may print a trailing newline if you choose STDOUT for output.
* Your code has to work for any input of 1000 or less ASCII characters in the range from 0x20 to 0x7A, plus curly brackets (0x7B and 0x7D).
* If the input contains curly brackets, you may assume that it is a valid result of applying the BRLE to a string.
* Standard code golf rules apply. The shortest submission in bytes wins.
[Answer]
# CJam, 50 48 bytes
```
l_{}`:T&1${_T#)_(@a?)+}%{(\2b)*}%@e`{(2b1>Tf=}%?
```
Thanks for Dennis for saving 2 bytes.
[Try it online.](http://cjam.aditsu.net/#code=l_%7B%7D%60%3AT%261%24%7B_T%23%29_%28%40a%3F%29%2B%7D%25%7B%28%5C2b%29*%7D%25%40e%60%7B%282b1%3ETf%3D%7D%25%3F&input=4%7B%7B8%7B%7B%7BG%7B%7B%7B%7BW%7B%7B%7B%7B%7B)
### Explanation
```
l_ e# Read and duplicate input.
{}`:T e# T = "{}"
& e# If the input has '{ or '}:
1$ e# Input.
{ e# For each character:
_T#) e# If it is '{ or '}:
_( e# Return 0 for '{ or 1 for '}.
@a e# Otherwise, convert the character itself to an array (string).
?
)+ e# If it is a number, increment and append to the previous array.
e# If it is a string with at least 1 character, do nothing.
}%
{(\ e# For each character and bijective base 2 number:
2b)* e# Repeat the character 1 + that many times.
}%
e# Else:
@ e# Input.
e` e# Run-length encoding.
{( e# For each character and length:
2b1> e# Convert the length to base 2 and remove the first bit.
Tf= e# Map 0 to '{ and 1 to '}.
}%
? e# End if.
```
[Answer]
# Pyth, 48 ~~50~~ bytes
```
J`Hs?m*hdi+1xLJtd2tczf-@zTJUz@Jzsm+ed@LJtjhd2rz8
```
*2 bytes thanks to @Maltysen.*
[Demonstration.](https://pyth.herokuapp.com/?code=J%60Hs%3Fm*hdi%2B1xLJtd2tczf-%40zTJUz%40Jzsm%2Bed%40LJtjhd2rz8&input=444488888888GGGGGGGGGGGGGGGGWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW&debug=0) [Test harness.](https://pyth.herokuapp.com/?code=Fz%2Bz.zJ%60Hs%3Fm*hdi%2B1xLJtd2tczf-%40zTJUz%40Jzsm%2Bed%40LJtjhd2rz8&input=CODEGOLF%0APROGRAMMING%0APUZ%7BLES%0A444488888888GGGGGGGGGGGGGGGGWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW%0Ay%7D%7D%7D%7B%7B&debug=0)
Explanation:
```
J`Hs?m*hdi+1xLJtd2tczf-@zTJUz@Jzsm+ed@LJtjhd2rz8
Implicit: z = input()
H is empty dict.
J`H J = repr(H) = "{}"
s Print the concatenation of
? @Jz If z and J share any chars:
f Uz Filter range(len(z))
-@zTJ On the absence of z[T] in J.
cz Chop z at these indices.
just before each non '{}'.
t Remove empty initial piece.
m*hd Map to d[0] *
i 2 the base 2 number
xLJtd index in J mapped over d[:-1]
+1 with a 1 prepended.
rz8 Otherwise, run len. encode z
m map over (len, char)
jhd2 Convert len to binary.
t Remove leading 1
@LJ Map to element of J.
+ed Prepend char.
s Concatenate.
```
[Answer]
# OCaml, 252
`t` is the function that does the transformation.
```
#load"str.cma"open Str
let rec(!)=group_beginning and
g=function|1->""|x->(g(x/2)^[|"{";"}"|].(x mod 2))and($)i s=if g i=s then i else(i+1)$s and
t s=global_substitute(regexp"\(.\)\1*\([{}]*\)")(fun s->String.make(1$matched_group 2 s)s.[!1]^g(!2- !1))s
```
At first I was thinking I had to check for the presence of curly braces, but it turned out to be unnecessary. The decoding clearly has no effect on strings that are already decoded, and the encoding part proved equally harmless to ones that were already encoded.
[Answer]
# JavaScript (*ES6*), 162
```
f=s=>
(t=s[R='replace'](/[^{}][{}]+/g,n=>n[0].repeat('0b'+n[R](/./g,c=>c!='{'|0))))==s
?s[R](/(.)\1*/g,(r,c)=>c+r.length.toString(2).slice(1)[R](/./g,c=>'{}'[c])):t
// TEST
out=x=>O.innerHTML += x + '\n';
test=s=>O.innerHTML = s+' -> '+f(s) +'\n\n' + O.innerHTML;
[['CODEGOLF','CODEGOLF']
,['PROGRAMMING','PROGRAM{ING']
,['PUZ{LES','PUZZLES']
,['444488888888GGGGGGGGGGGGGGGGWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW','4{{8{{{G{{{{W{{{{{']
,['y}}}{{','yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy']]
.forEach(v=>{
w=f(v[0])
out('Test ' + (w==v[1]?'OK':'Fail')+'\nInput: '+v[0]+'\nExpected: '+v[1]+'\nResult: '+w)
})
```
```
Your test: <input id=I style='width:300px'><button onclick='test(I.value)'>-></button>
<pre id=O></pre>
```
**Some explanation**
Number *n* to BB2 using 0 and 1: `(n+1).toString(2).slice(1)`
String in BB2 to number: to\_number ("0b1"+string) - that is, add a leftmost 1 binary digit and convert from binary (and decrease by 1, not needed in this specific instance).
Regular expression to find any character followed by `{` or `}`: `/[^{}][{}]+/g`
Regular expression to find repeated characters: `/(.)\1*/g`
Using that regexp in replace, first param is the "repeated" char (eventually repeat just 1 time), second param is the total repeated string, whose length is the number that I need to encode in BB2 *already incremented by 1*
... then put all together ...
] |
[Question]
[
[Atomic chess](https://en.wikipedia.org/wiki/Atomic_chess) is a (very fun)
variant of chess in which every capture causes an "explosion," destroying the
captured piece, the piece doing the capturing, and all non-pawns in a 1-square
radius. The goal of this challenge is not to play an entire game of atomic
chess, but simply to simulate what happens when a certain move is made.
Disclaimer: Explosion sound effects not included.
## Input
Board position will be given in [Forsyth-Edwards
Notation](https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation)
(commonly known as FEN), but with only the first field. For example, an input
of:
```
rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR
```
represents the starting position:

This must be taken as a string or your language's equivalent. It is guaranteed
to be valid; for example, you don't have to care if there are ten kings, or if
there is no king at all.
You will also be given the move that you are to simulate, which is represented
as two square names: the square on which the piece to be moved is, and the
square it is moving to. For example, moving the king's pawn two spaces forwards
on the above picture would be represented as:
```
e2e4
```
This must also be taken as a string. The move will always be valid, and you do
not need to support [castling](https://en.wikipedia.org/wiki/Castling). You do
need to support [*en passant*](https://en.wikipedia.org/wiki/En_passant), which
will be explained in further detail in the next section.
## Output
The output of your program should be in the same partial-FEN notation as the
input, with the specified move made (and any pieces exploded if necessary).
The exact rules for explosions are—when a piece is captured:
* Remove the piece being captured (this will always be the piece on the second
square named in the input, except for when the capture is an *en passant*).
* Remove the piece that is doing the capturing (this will always be the piece
on the first square named in the input).
* Remove every piece that is:
+ located on one of the 8 squares surrounding the one where the capture took
place (for *en passant*, this is the square that the capturing pawn would
be on, if it didn't explode).
+ not a pawn.
Quick overview of *en passant* rules, for those who are unfamiliar: if a pawn
moves two spaces forwards from its starting rank, and there is a pawn that
could have captured it if it only moved one square forward, it may capture it
anyway, but only on the subsequent move. This capture is said to be done "*in
passing*" (or in French: "*en passant*").
## Test cases
In the pictures, the green arrows represet the move about to be made, and the
green circles represents pieces that are exploded.
Input: `rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR`, `g1f3`
Output: `rnbqkbnr/pppppppp/8/8/8/5N2/PPPPPPPP/RNBQKB1R`

---
Input: `3kBb1r/pp5p/3p4/4pn2/P7/1P2P1pP/2rP1P2/R1B3RK`, `f2g3`
Output: `3kBb1r/pp5p/3p4/4pn2/P7/1P2P2P/2rP4/R1B3RK`

*(stolen from <http://en.lichess.org/ocoSfS5I/white#36>)*
---
Input: `rnbqk1nr/1pp5/p2pp1pp/5p2/1bN5/2P1PQ1N/PP1P1PPP/R1B1KB1R`, `f3b7`
Output: `3qk1nr/2p5/p2pp1pp/5p2/1bN5/2P1P2N/PP1P1PPP/R1B1KB1R`

*(stolen from <http://en.lichess.org/NCUnA6LV/white#14>)*
---
Input: `rnbqk2r/pp2p2p/2p3pb/3pP3/5P2/2N5/PPPP2P1/R1BQKB1R`, `e5d6`
Output: `rnbqk2r/pp2p2p/2p3pb/8/5P2/2N5/PPPP2P1/R1BQKB1R`

*(stolen from <http://en.lichess.org/AvgU4Skq/white#16>; this wasn't the actual
move, but I couldn't be bothered to find an atomic game that actually had en
passant :P)*
---
Input: `5r2/2k5/p1B5/1pP1p3/1P4P1/3P4/P7/1K3R1q`, `c6h1`
Output: `5r2/2k5/p7/1pP1p3/1P4P1/3P4/P7/1K3R2`

*(stolen from <http://en.lichess.org/l77efXEb/white#58>)*
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
[Answer]
# JavaScript (*ES6*) 305 ~~310 321~~
As a function with 2 real parameters (and a lot more with default values, used as a quick and dirty way to define locals)
Test running the snippet below (being EcmaScript 6, Firefox only)
```
F=(g,m,b=[...g.replace(/\d/g,c=>'0'.repeat(c))],P=p=>p=='p'|p=='P',n=parseInt(m,32),
s=n>>5&31,u=n>>15,x=b[y=u+62-(n>>10&31)*9])=>(
b[b[y]=0,z=s+62-(n&31)*9]<1&!(s!=u&P(x))?b[z]=x:
[-1,1,8,9,10,-8,-9,-10].map(i=>b[i+=z]>'/'&&!P(b[i])?b[i]=0:0,b[b[z]<1?z>y?z-9:z+9:z]=0),
b.join('').replace(/0+/g,x=>x.length)
)
//TEST
out=x=>O.innerHTML+=x+'\n'
test=[
['rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR', 'g1f3'
,'rnbqkbnr/pppppppp/8/8/8/5N2/PPPPPPPP/RNBQKB1R']
,['3kBb1r/pp5p/3p4/4pn2/P7/1P2P1pP/2rP1P2/R1B3RK', 'f2g3'
,'3kBb1r/pp5p/3p4/4pn2/P7/1P2P2P/2rP4/R1B3RK']
,['rnbqk1nr/1pp5/p2pp1pp/5p2/1bN5/2P1PQ1N/PP1P1PPP/R1B1KB1R', 'f3b7'
,'3qk1nr/2p5/p2pp1pp/5p2/1bN5/2P1P2N/PP1P1PPP/R1B1KB1R']
,['rnbqk2r/pp2p2p/2p3pb/3pP3/5P2/2N5/PPPP2P1/R1BQKB1R', 'e5d6'
,'rnbqk2r/pp2p2p/2p3pb/8/5P2/2N5/PPPP2P1/R1BQKB1R']
,['5r2/2k5/p1B5/1pP1p3/1P4P1/3P4/P7/1K3R1q', 'c6h1'
,'5r2/2k5/p7/1pP1p3/1P4P1/3P4/P7/1K3R2']
]
test.forEach(t=>(
r=F(t[0],t[1]),
out('Test '+(r==t[2]?'Ok':'Fail!')+' '+t[0]+' move '+t[1]
+'\nResult '+r+'\nExpected '+t[2]+'\n')))
```
```
<pre id=O></pre>
```
**Ungolfed**
```
B=(b,m)=>{
P=p=>p=='p'|p=='P'
m=parseInt(m,32)
r=m&31 // arrival row
s=(m/32&31)-10 // arrival column
z=s+(8-r)*9 // arrival position
t=m/32/32&31 // start row
u=(m/32/32/32&31)-10 // start column
y=u+(8-t)*9 // start position
b=[...b.replace(/\d/g,c=>'0'.repeat(c))] // board to array, empty squares as 0
x=b[y] // moving piece
b[y]=0
C=s!=u&P(x) // pawn capture
if (b[z]<1 && !C)
{ // no capture
b[z]=x
}
else
{
// capture and boom!
if (b[z]<1) // arrival empty: en passant
b[z>y?z-9:z+9]=0;
else
b[z]=0;
// zero to nearest 8 squares
[-1,1,8,9,10,-8,-9,-10].forEach(i=>b[i+=z]>'/'&&!P(b[i])?b[i]=0:0)
}
return b.join('').replace(/0+/g,x=>x.length)
}
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 240 bytes
```
e←' '@(p/⍨~(x←∊∘'Pp')(b←↑⊃¨,/¨{⍵∊⎕D:' '/⍨⍎⍵⋄⍵}¨¨'/'(≠⊆⊢)⎕)[p←p/⍨{∧/⍵∊⍳8}¨p←(⊃⌽c←{(9-⍎⊃⌽⍵),⎕A⍳⊃⍵}¨↓2 2⍴1⎕C⎕)∘+¨,∘.,⍨2-⍳3])
1↓⊃,/{'/',⊃,/{' '∊⍵:⍕≢⍵⋄⍵}¨⍵⊂⍨1,2≠/⍵}¨↓{(x⊃n)∧(≠/⊃¨⌽¨c)∧' '=⊃⌽n←b[c]:e' '@((⊃c)+0,1↓⊃-⍨/c)⊢b⋄' '∊n:(⌽n)@c⊢b⋄e' '@c⊢b}0
```
[Try it online!](https://tio.run/##ZZHBTttAEIbvforc1hZOh92NgUaqRN3eIkWOr4gDdpxUCnKXqAcqix5KlQZTo1YVEkeUC75Tjr3kUfZF0n@MqSrqlezZ2fn/@WZ9ZI67449Hx@@n3ez0Q5aPs/HGLr9ONpldfBcdse8aslX9yT3F3i5Lu7wRkRGem/B@8cOW5@vap3Vd2OqBz6@u3/ahY5Gtrjh5@QXvs3W9rgUJ117c2nJhy5WHUu/AwKbpUNjlHbUe1f0e6vnIhb/99jtFWLgvu@zYJFDo@TB4jVrONA3s4qfqKFv9kjh5w/ag3QIePi989FAwuNeHniNRCplPBZD8NuqIpvdD31bX9mL1LzrH5Wc4SF9hAPrbr8C9lOc5Gt25zQFfB/jWdco5eL56BM4xQXKQHvaz5lJ5rtTb2vZbEoDVBEm5StD0ESXvuyz09tM23Uibzdk2/6TNxBFTOdHCEfM8OZkl@ZxM@9Beu6L2oXgYjgbhMBYOboZ/rnCgn6gp6/UsTCSrA0Pa9KhnckXRLslIRdJEpOYRQoplqOPBMwed7D4RSBBImJBRxiCgwCiSyTAg2EQjOQSOxGIcGcpBKJ/hZMF458lMMY/CImW0ScAVaQpAoeDHI8GTbUb/26Q77yRsgjmKZ6CRYQAuTKIxUQ8yHfWa8QY6lifiDw "APL (Dyalog Extended) – Try It Online")
A full program which takes the FEN first, and the move second.
## Explanation
**First Line: Explode. Function**
```
e←' '@(p/⍨~(x←∊∘'Pp')(b←↑⊃¨,/¨{⍵∊⎕D:' '/⍨⍎⍵⋄⍵}¨¨'/'(≠⊆⊢)⎕)[p←p/⍨{∧/⍵∊⍳8}¨p←(⊃⌽c←{(9-⍎⊃⌽⍵),⎕A⍳⊃⍵}¨↓2 2⍴1⎕C⎕)∘+¨,∘.,⍨2-⍳3])
```
`1⎕C⎕` capitalize the first input
`↓2 2⍴` cut into halves
`{(9-⍎⊃⌽⍵),⎕A⍳⊃⍵}¨` apply the following to each square name:
`,⎕A⍳⊃⍵` get position of first char in the alphabet(column)
`(9-⍎⊃⌽⍵)` get 9-int(second char) (row number)
`c←` store that in c
`⊃⌽` take the last element
`∘+¨` and add that to:
`,∘.,⍨2-⍳3` the cartesian product of (-1,0,1), getting the von neumann neighborhood
`p←` assign the explosion indices to p
`p←p/⍨{∧/⍵∊⍳8}¨` remove the ones outside the board, and reassign to p
`(...)[...]` and index into the following:
`'/'(≠⊆⊢)⎕` split the second input on slashes
`⊃¨,/¨{⍵∊⎕D:' '/⍨⍎⍵⋄⍵}¨¨` convert each digit to the appropriate amount of spaces
`b←↑` and convert it to a matrix, storing in b. This is the chess board.
`x←∊∘'Pp'` store function to check for pawns in x
`p/⍨~(x←∊∘'Pp')` now, remove the points which map to pawns
`' '@` and insert a space at those indices in the right argument.
**Second line: capture calculator**
```
1↓⊃,/{'/',⊃,/{' '∊⍵:⍕≢⍵⋄⍵}¨⍵⊂⍨1,2≠/⍵}¨↓{(x⊃n)∧(≠/⊃¨⌽¨c)∧' '=⊃⌽n←b[c]:e' '@((⊃c)+0,1↓⊃-⍨/c)⊢b⋄' '∊n:(⌽n)@c⊢b⋄e' '@c⊢b}0
```
`n←b[c]` assign the starting and ending characters to n
`' '=⊃⌽n←b[c]` If ending square is empty,
`(≠/⊃¨⌽¨c)∧` start column and end column are not equal,
`(x⊃n)∧` and capturing piece is a pawn(en passant):
`0,1↓⊃-⍨/c` get the direction of capture
`(⊃c)+` add that to the start index
`' '@((⊃c)+0,1↓⊃-⍨/c)⊢b` insert a space at that point
`e` and **explode.**
`' '∊n` else, if ending point is a space(no capture):
`(⌽n)@c⊢b⋄` switch the places of the space and the piece
`' '@c⊢b` Otherwise, insert a space at the start and end index(normal capture)
`e` and **explode.**
`¨↓` then, take each row,
`⍵⊂⍨1,2≠/⍵` group it into equal runs
`{' '∊⍵:⍕≢⍵⋄⍵}¨` replace runs of spaces with their length.
`'/',⊃,/` join everything together and prepend a /
`1↓⊃,/` join the rows together and drop the first /.
[Answer]
# Java, (~~946~~ ~~777~~ 776 chars)
*1 char thanks to @edc65*
Note: Chars counted without test cases put in.
**Code**
```
class E{public static void main(String[]a){String i=a[0];char[]n=a[1].toCharArray();int j,k,z,w,y,u=56-n[3];char q,p,e ='e';char[][]b=new char[8][8];String[]r=i.split("/");for(j=0;j<8;j++){z=0;for(k=0;k<r[j].length();k++){p=r[j].charAt(k);if(Character.isDigit(p)){for(int l=k+z;l<k+z+p-48;l++)b[j][l]=e;z+=p-49;}else b[j][k+z]=p;}}z=n[0]-97;w=56-n[1];y=n[2]-97;p=b[w][z];q=b[u][y];b[w][z]=e;if(q!=e||((p|32)=='p'&&(w-u<0?u-w:w-u)==1&&(z-y<0?y-z:z-y)==1)){if(q!=e)b[u][y]=e;else b[w][y]=e;for(j=y-(y==0?0:1);j<y+(y==8?0:y==7?1:2);j++){for(k=u-(u==0?0:1);k<u+(u==8?0:u==7?1:2);k++)if((b[k][j]|32)!='p')b[k][j]=e;}}else b[u][y]=p;i="";for(j=0;j<8;j++){z=0;for(k=0;k<8;k++){if(b[j][k]==e)z++;else {if(z>0){i+=z;z=0;}i+=b[j][k];}}if(z>0)i+=z;i+=j!=7?"/":"";}System.out.print(i);}}
```
I'm not sure if this solution is optimal, but I'm working on golfing it more, any suggestions are welcome. I can comment all the code too if anyone would like, but I think it's mostly self explanatory, except for the confusing variable enumeration.
**Explanation**
* Unpack the board string into a char matrix
* Calculate the effect of the move
* Repack the board into a string
**Expanded**
```
class ExplosionChess{
public static void main(String[]a){
String i=a[0];
//"rnbqk1nr/1pp5/p2pp1pp/5p2/1bN5/2P1PQ1N/PP1P1PPP/R1B1KB1R";
//"f3b7";
char[]n=a[1].toCharArray();
int j,k,z,w,y,u=56-n[3];
char q,p,e ='e';
char[][]b=new char[8][8];
String[]r=i.split("/");
for(j=0;j<8;j++){
z=0;
for(k=0;k<r[j].length();k++){
p=r[j].charAt(k);
if(Character.isDigit(p)){
for(int l=k+z;l<k+z+p-48;l++)
b[j][l]=e;
z+=p-49;
}else
b[j][k+z]=p;
}
}
z=n[0]-97;
w=56-n[1];
y=n[2]-97;
p=b[w][z];
q=b[u][y];
b[w][z]=e;
if(q!=e||((p|32)=='p'&&(w-u<0?u-w:w-u)==1&&(z-y<0?y-z:z-y)==1)){
if(q!=e)
b[u][y]=e;
else
b[w][y]=e;
for(j=y-(y==0?0:1);j<y+(y==8?0:y==7?1:2);j++){
for(k=u-(u==0?0:1);k<u+(u==8?0:u==7?1:2);k++)
if((b[k][j]|32)!='p')
b[k][j]=e;
}
}else
b[u][y]=p;
i="";
for(j=0;j<8;j++){
z=0;
for(k=0;k<8;k++){
if(b[j][k]==e)
z++;
else {
if(z>0){
i+=z;
z=0;
}
i+=b[j][k];
}
}
if(z>0)
i+=z;
i+=j!=7?"/":"";
}
System.out.print(i);
}
}
```
**Old**
```
class E{public static void main(String[]a){String m,i="rnbqk1nr/1pp5/p2pp1pp/5p2/1bN5/2P1PQ1N/PP1P1PPP/R1B1KB1R";m="f3b7";char[]n=m.toCharArray();int z,w,y,u=56-n[3];z=n[0]-97;w=56-n[1];y=n[2]-97;char e='e';char[][]b=new char[8][8];String[]r=i.split("/");for(int j=0;j<8;j++){int o=0;for(int k=0;k<r[j].length();k++){char q=r[j].charAt(k);if(Character.isDigit(q)){for(int l=k+o;l<k+o+q-48;l++){b[j][l]=e;}o+=q-49;}else b[j][k+o]=q;}}char q,p=b[w][z];q=b[u][y];b[w][z]=e;if(q==e){if((p|32)=='p'&&(w-u<0?u-w:w-u)==1&&(z-y<0?y-z:z-y)==1){b[w][y]=e;for(int j=y-(y==0?0:1);j<y+(y==8?0:y==7?1:2);j++){for(int k=u-(u==0?0:1);k<u+(u==8?0:u==7?1:2);k++){if((b[k][j]|32)!='p')b[k][j]=e;}}}else{b[u][y]=p;}}else{b[u][y]=e;for(int j=y-(y==0?0:1);j<y+(y==8?0:y==7?1:2);j++){for(int k=u-(u==0?0:1);k<u+(u==8?0:u==7?1:2);k++){if((b[k][j]|32)!='p')b[k][j]=e;}}}i="";for(int j=0;j<8;j++){int x=0;for(int k=0;k<8;k++){if(b[j][k]==e)x++;else{if(x>0){i+=x;x=0;}i+=b[j][k];}}if(x>0)i+=x;i+=j!=7?"/":"";}System.out.println(i);}}
```
] |
[Question]
[
As the band's roadie, you have to pack the truck. Your program will place the packages so that they fit in the smallest height.
## A badly packed truck

## Rules
Packages may be rotated through multiples of 90 degrees. Packages may touch but must not overlap.
The output is the repacked image (to file or stdout). Your program may use any input or output raster image format.
Your program must accept any number of packages of various shapes in images up to 4000x4000 pixels. It must not be hardcoded for this test image. If I suspect any submission to be tailored towards this specific image, I reserve the right to replace it by a new test image.
## Score
Your score is the smallest height of a rectangle that will contain your arrangement (the width is the input rectangle width). In the case of a tie, the earliest entry wins.
Standard loopholes are prohibited as usual.
[Answer]
# Language : Java
# Score : 555 533
I just went for trying to brute force a solution by iterating over the shapes in order of decreasing area (perimeter in case of tie) and trying out all packing possibilities until a valid packing is found for that shape at which point the shape's position is fixed and the algorithm goes on to the next shape. In order to hopefully improve the quality of the result when searching for a valid packing first all possible positions are tried with the shape rotated such that it is taller than it is wider.
Note: this assumes that the input image(s) have all of the shapes separated by white space. It takes the maximum width of the output as the first argument and a list of shape images as the other arguments (each shape image can have one or more shape separated by at least one line of white pixels)
```
import java.awt.Color;
import java.awt.Graphics;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import javax.imageio.ImageIO;
public class Packer {
public static void main(String[] args) throws Exception {
long t1 = System.currentTimeMillis();
int width = Integer.valueOf(args[0]);
List<Item> itemList = new ArrayList<Item>();
for (int i = 1; i < args.length; i++) {
itemList.addAll(getItems(ImageIO.read(new File(args[i]))));
}
File outputFile = new File("output.png");
if (outputFile.exists()) {
outputFile.delete();
}
outputFile.createNewFile();
ImageIO.write(pack(itemList, width), "PNG", outputFile);
long t2 = System.currentTimeMillis();
System.out.println("Finished in " + (t2 - t1) + "ms");
}
private static BufferedImage pack(List<Item> itemList, int width) {
System.out.println("Packing " + itemList.size() + " items");
Collections.sort(itemList, new Comparator<Item>() {
@Override
public int compare(Item o1, Item o2) {
return o1.area < o2.area ? 1 : (o1.area > o2.area ? -1
: (o1.perimiter < o2.perimiter ? 1
: (o1.perimiter > o2.perimiter ? -1 : 0)));
}
});
Packing packing = new Packing(width);
PackedItem.Rotation[] widthRots = { PackedItem.Rotation.ZERO,
PackedItem.Rotation.ONE_EIGHTY };
PackedItem.Rotation[] heightRots = { PackedItem.Rotation.NINETY,
PackedItem.Rotation.TWO_SEVENTY };
int count = 0;
for (Item item : itemList) {
count++;
int minSize = Math.min(item.width, item.height);
int maxSize = Math.max(item.width, item.height);
int x = 0;
int y = 0;
int rot = 0;
PackedItem.Rotation[] rots = widthRots;
if (item.width > item.height) {
rots = heightRots;
}
boolean rotsSwitched = false;
PackedItem packedItem = new PackedItem(item, rots[rot], x, y);
System.out.format("Packing item %d which is %d by %d\n", count,
item.width, item.height);
while (!packing.isValidWith(packedItem)) {
if (rot == 0) {
rot = 1;
} else {
rot = 0;
if (x + minSize >= width) {
x = 0;
y++;
if (!rotsSwitched
&& y + maxSize > packing.height) {
rotsSwitched = true;
if (item.width > item.height) {
rots = widthRots;
} else {
rots = heightRots;
}
y = 0;
}
} else {
x++;
}
}
packedItem.set(x, y, rots[rot]);
}
packing.addItem(packedItem);
System.out.format("Packed item %d\n", count);
}
return packing.getDrawing();
}
private static List<Item> getItems(BufferedImage image) {
List<Item> itemList = new ArrayList<Item>();
boolean[][] pointsProcessed = new boolean[image.getWidth()][image
.getHeight()];
for (int i = 0; i < image.getWidth(); i++) {
for (int j = 0; j < image.getHeight(); j++) {
if (pointsProcessed[i][j]) {
continue;
}
ImagePoint point = ImagePoint.getPoint(i, j, image);
if (point.getColor().equals(Color.WHITE)) {
pointsProcessed[point.x][point.y] = true;
continue;
}
Collection<ImagePoint> itemPoints = new ArrayList<ImagePoint>();
Queue<ImagePoint> pointsToProcess = new LinkedList<ImagePoint>();
pointsToProcess.add(point);
while (!pointsToProcess.isEmpty()) {
point = pointsToProcess.poll();
if (pointsProcessed[point.x][point.y]) {
continue;
}
pointsProcessed[point.x][point.y] = true;
if (point.getColor().equals(Color.WHITE)) {
continue;
}
itemPoints.add(point);
pointsToProcess.addAll(point.getNeighbors());
}
itemList.add(new Item(itemPoints));
}
}
return itemList;
}
private interface Point {
int getX();
int getY();
Color getColor();
}
private static final class ImagePoint implements Point {
private static final Map<BufferedImage, Map<Integer, Map<Integer, ImagePoint>>> POINT_CACHE = new HashMap<BufferedImage, Map<Integer, Map<Integer, ImagePoint>>>();
private final int x;
private final int y;
private final Color color;
private final BufferedImage image;
private Collection<ImagePoint> neighbors;
private ImagePoint(int x, int y, BufferedImage image) {
this.x = x;
this.y = y;
this.image = image;
this.color = new Color(image.getRGB(x, y));
}
static ImagePoint getPoint(int x, int y, BufferedImage image) {
Map<Integer, Map<Integer, ImagePoint>> imageCache = POINT_CACHE
.get(image);
if (imageCache == null) {
imageCache = new HashMap<Integer, Map<Integer, ImagePoint>>();
POINT_CACHE.put(image, imageCache);
}
Map<Integer, ImagePoint> xCache = imageCache.get(x);
if (xCache == null) {
xCache = new HashMap<Integer, Packer.ImagePoint>();
imageCache.put(x, xCache);
}
ImagePoint point = xCache.get(y);
if (point == null) {
point = new ImagePoint(x, y, image);
xCache.put(y, point);
}
return point;
}
Collection<ImagePoint> getNeighbors() {
if (neighbors == null) {
neighbors = new ArrayList<ImagePoint>();
for (int i = -1; i <= 1; i++) {
if (x + i < 0 || x + i >= image.getWidth()) {
continue;
}
for (int j = -1; j <= 1; j++) {
if ((i == j && i == 0) || y + j < 0
|| y + j >= image.getHeight()) {
continue;
}
neighbors.add(getPoint(x + i, y + j, image));
}
}
}
return neighbors;
}
@Override
public int getX() {
return y;
}
@Override
public int getY() {
return x;
}
@Override
public Color getColor() {
return color;
}
}
private static final class Item {
private final Collection<ItemPoint> points;
private final int width;
private final int height;
private final int perimiter;
private final int area;
Item(Collection<ImagePoint> points) {
int maxX = Integer.MIN_VALUE;
int minX = Integer.MAX_VALUE;
int maxY = Integer.MIN_VALUE;
int minY = Integer.MAX_VALUE;
for (ImagePoint point : points) {
maxX = Math.max(maxX, point.x);
minX = Math.min(minX, point.x);
maxY = Math.max(maxY, point.y);
minY = Math.min(minY, point.y);
}
this.width = maxX - minX;
this.height = maxY - minY;
this.perimiter = this.width * 2 + this.height * 2;
this.area = this.width * this.height;
this.points = new ArrayList<ItemPoint>(points.size());
for (ImagePoint point : points) {
this.points.add(new ItemPoint(point.x - minX, point.y - minY,
point.getColor()));
}
}
private static final class ItemPoint implements Point {
private final int x;
private final int y;
private final Color color;
public ItemPoint(int x, int y, Color color) {
this.x = x;
this.y = y;
this.color = color;
}
@Override
public int getX() {
return x;
}
@Override
public int getY() {
return y;
}
@Override
public Color getColor() {
return color;
}
}
}
private static final class PackedItem {
private final Collection<PackedPoint> points;
private Rotation rotation;
private int x;
private int y;
private AffineTransform transform;
private int modCount;
PackedItem(Item item, Rotation rotation, int x, int y) {
this.set(x, y, rotation);
this.points = new ArrayList<PackedPoint>();
for (Point point : item.points) {
this.points.add(new PackedPoint(point));
}
}
void set(int newX, int newY, Rotation newRotation) {
modCount++;
x = newX;
y = newY;
rotation = newRotation;
transform = new AffineTransform();
transform.translate(x, y);
transform.rotate(this.rotation.getDegrees());
}
void draw(Graphics g) {
Color oldColor = g.getColor();
for (Point point : points) {
g.setColor(point.getColor());
g.drawLine(point.getX(), point.getY(), point.getX(),
point.getY());
}
g.setColor(oldColor);
}
private enum Rotation {
ZERO(0), NINETY(Math.PI / 2), ONE_EIGHTY(Math.PI), TWO_SEVENTY(
3 * Math.PI / 2);
private final double degrees;
Rotation(double degrees) {
this.degrees = degrees;
}
double getDegrees() {
return degrees;
}
}
private final class PackedPoint implements Point {
private final Point point;
private final Point2D point2D;
private int x;
private int y;
private int modCount;
public PackedPoint(Point point) {
this.point = point;
this.point2D = new Point2D.Float(point.getX(), point.getY());
}
@Override
public int getX() {
update();
return x;
}
@Override
public int getY() {
update();
return y;
}
private void update() {
if (this.modCount != PackedItem.this.modCount) {
this.modCount = PackedItem.this.modCount;
Point2D destPoint = new Point2D.Float();
transform.transform(point2D, destPoint);
x = (int) destPoint.getX();
y = (int) destPoint.getY();
}
}
@Override
public Color getColor() {
return point.getColor();
}
}
}
private static final class Packing {
private final Set<PackedItem> packedItems = new HashSet<PackedItem>();
private final int maxWidth;
private boolean[][] pointsFilled;
private int height;
Packing(int maxWidth) {
this.maxWidth = maxWidth;
this.pointsFilled = new boolean[maxWidth][0];
}
void addItem(PackedItem item) {
packedItems.add(item);
for (Point point : item.points) {
height = Math.max(height, point.getY() + 1);
if (pointsFilled[point.getX()].length < point.getY() + 1) {
pointsFilled[point.getX()] = Arrays.copyOf(
pointsFilled[point.getX()], point.getY() + 1);
}
pointsFilled[point.getX()][point.getY()] = true;
}
}
BufferedImage getDrawing() {
BufferedImage image = new BufferedImage(maxWidth, height,
BufferedImage.TYPE_INT_ARGB);
Graphics g = image.getGraphics();
g.setColor(Color.WHITE);
g.drawRect(0, 0, maxWidth, height);
for (PackedItem item : packedItems) {
item.draw(g);
}
return image;
}
boolean isValidWith(PackedItem item) {
for (Point point : item.points) {
int x = point.getX();
int y = point.getY();
if (y < 0 || x < 0 || x >= maxWidth) {
return false;
}
boolean[] column = pointsFilled[x];
if (y < column.length && column[y]) {
return false;
}
}
return true;
}
}
}
```
The solution this produces (takes about 4 minutes 30 seconds on my machine) is:

Looking at this picture it seems like the result can be improved by iterating over all of the shapes post packing and trying to move them all up a bit. I might try doing that later.
] |
[Question]
[
## Introduction
This is one of my favorite math puzzles.
Given a digit (say 3) and the number of times to use that digit (say 5), generate 10 expressions which result to 1, 2, 3, 4, 5, 6, 7, 8, 9 and 10 using just +, −, ×, ÷, ^ and √ (root) (brackets are allowed to group operations).
For example:
```
(3^3 + 3)/(3 + 3) = (33 - 3)/(3 + 3) = 3 + 3/3 + 3/3 = 5
```
Note that all of the above use five 3’s and the mathematical operations and result to 5. You can also use a 3 before √ to denote a cube root. Same goes for using 4 before √ to denote a fourth root.
Also note that two 3’s can be used to form 33, or three 3’s can be used to form 333 and so on.
## Challenge
* You will be given two numbers *(both ranging from 1 to 5)* as a function argument, STDIN or command line argument.
* The first number denotes which digit to use and the second number denotes the number of times that digit is to be used in the expression.
* Your program should output an array of size 10 (or 10 space-separated numbers) where each element denotes whether a mathematical expression (using just the allowed operators) resulting into the `(index + 1)` number is possible or not using a truthy/falsy value.
For example, if the input is
```
1 3
```
Then the output should be
```
[1, 1, 1, 0, 0, 0, 0, 0, 0, 1]
```
because only 1, 2, 3 and 10 can be expressed using three 1’s.
## Score
* This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the minimum code length in bytes wins.
## Bonus
### Print-em-all [−50]
Subtract 50 from your score if the output array elements are equal to the total number of plausible combinations to get the `(index + 1)` value instead of truthy or falsy values.
For example, if there are only 3 possible combinations of five 3’s which result to 5, then the output array’s 4th entry should be 3.
### Extreme Maths [−100]
Subtract 100 from your score if the output array elements contain at least one of the actual expressions which result to the `(index + 1)` value.
For example, if using five 3’s, the output array’s 4th entry can be either `(3^3 + 3)/(3 + 3)`, `(33 - 3)/(3 + 3)` or `3 + 3/3 + 3/3`
### Overkilled [−200]
Subtract 200 from your score if the output array elements contain all possible combinations (separated by `|`). This bonus is added on top of the *Extreme Maths* bonus, so you get −300 in total.
For example, if using five 3’s, the output array’s 4th element should be `(3^3 + 3)/(3 + 3)|(33 - 3)/(3 + 3)|3 + 3/3 + 3/3`
**Note:** Any two expressions to achieve the same result should be logically different with a different approach in both of them.
For instance, to get 5 using five 3’s, `3 + 3/3 + 3/3` is same as `3/3 + 3 + 3/3` or `3/3 + 3/3 + 3` because the same approach is taken for each of them. `(3^3 + 3)/(3 + 3)` and `(33 - 3)/(3 + 3)` differ, as the 30 in the numerator is achieved via different approaches.
**UPDATE** : After going through all answers, it was found that all answers had imperfections due to edge cases of unary `-` and √. Thus, missing those edge cases was considered okay as far as completeness of answers is involved.
This is a tough question, but a rather interesting one.
Happy golfing!
[Answer]
# Python (imperfect) ~~493~~ 474 - 300 = 174
There are a fair number of issues with this solution, firstly that it ignores any exponent that is too large (any in which the exponent is greater than 100). I actually don't think this removes any possibilities for inputs less than or equal to 5, but I'm not 100% sure.
Another thing is that it does not consider any unary square roots, as it would get complicated (any solution with any term equal to 0 or 1 would produce an infinite number of solutions). It also does not consider any unary negation (the '-' symbol) for the same reason, as well as the fact that I'm not actually sure if the question asked for it.
I also considered what criteria should decide if two expressions were equivalent, but I couldn't find a way to rigorously define it in a way I found to be intuitive, so (for now at least) I didn't implement anything like that. This does mean that it outputs quite a few results, and it also uses parenthesis in a fairly naive way.
On a side note I think that this might include the longest single line of code I've written, especially before it was fully golfed.
```
R=range
F=lambda s:lambda a,b:eval(s)
L=lambda D,N:[(int(str(D)*N),str(D)*N)]+[(o(u,v),"(%s%s%s)"%(s,c,t))for p in R(1,N)for u,s in L(D,p)for v,t in L(D,N-p)for c,o in[('+',F('a+b')),('-',F('a-b')),('*',F('a*b')),('/',F("1.*a/b if b else''")),('^',F("''if(a<0 and int(b)!=b)|(a and b<0)|(b>99)else a**b")),('v',F("b**(1./a)if a and(a>=0 or b)and(b>=0 or int(1./a)==1./a)&(1./a<99)else''"))]if o(u,v)!='']
A=L(*input())
for i in R(11):
for v,s in A:
if v==i:print i,s[1:-1]
```
Example: ('v' represents '√')
```
2,3
0 2*(2-2)
0 2v(2-2)
0 (2-2)*2
0 (2-2)/2
0 (2-2)^2
1 2^(2-2)
1 2-(2/2)
1 2v(2/2)
1 (2/2)^2
2 2v(2+2)
2 2+(2-2)
2 2-(2-2)
2 2v(2*2)
2 2*(2/2)
2 2/(2/2)
2 2^(2/2)
2 2v(2^2)
2 (2+2)-2
2 (2+2)/2
2 (2-2)+2
2 (2*2)-2
2 (2*2)/2
2 (2/2)*2
2 (2/2)v2
2 (2^2)-2
2 (2^2)/2
3 2+(2/2)
3 (2/2)+2
6 2+(2+2)
6 2+(2*2)
6 2+(2^2)
6 (2+2)+2
6 (2*2)+2
6 (2^2)+2
8 2*(2+2)
8 2*(2*2)
8 2*(2^2)
8 (2+2)*2
8 (2*2)*2
8 (2^2)*2
```
[Answer]
## Python 3 – ~~349~~ 346
```
r=range
l=lambda s:eval("lambda a"+s)
def T(u,f,X,Y):
try:return u(f(X,Y))
except:0
c=l(',x:{x}.union(*[{u(int("1"*a)*x)}|{T(u,f,X,Y)for j in r(1,a)for X in c(j,x)for Y in c(a-j,x)for f in[l(",b:a%sb"%o)for o in{"**"}|set("+-*/")]+[l(",b:a**b**-1")]}for u in[l(":-a")]+[l(":a**.5**%i"%k)for k in r(9)]])')
R=l(",i:[{n+1}<c(i,a)for n in r(10)]")
```
Here is a rather ungolfed version:
```
def R(x,i):
# Unary Operations
U = [lambda a:-a] + [eval("lambda a:a**(1/2.**%i)" % j) for j in range(9)]
# Binary Operations
F = [eval("lambda a,b:a%sb"%o) for o in ["+","-","*","/","**"]] + [lambda a,b:a**(1./b)]
def combos(i):
L = {x}
for u in U:
# 3, 33, 333, etc.
L |= {u(int(str(x)*i))}
for j in range(1,i):
for X in combos(j):
for Y in combos(i-j):
for f in F:
# To avoid trouble with division by zero, overflows and similar:
try:
L |= {u(f(X,Y))}
except:
pass
return L
return [n in combos(i) for n in range(1,11)]
```
For testing I recommend to change `(9)` to something smaller, since this is the number of multiple square roots taken into account, which has a huge impact on the performance.
Finally, this made me wonder, whether the unary minus is actually needed in some case …
[Answer]
### Mathematica - 246 characters (no bonuses claimed)
```
f[x_,y_]:=x-y
g[x_,y_]:=x/y
h[x_,y_]:=x^(1/y)
j[x_,y_]:=FromDigits@Join[IntegerDigits@x,{y}]
z[{r_,n_,L_}]:=z[{L[[1]][r,n],n,Rest@L}]
z[{r_,n_,{}}]:=r
a[n_,t_]:=Union@Select[z[{n,n,#}]&/@Tuples[{Plus,f,Times,g,Power,h,j},t-1],IntegerQ@#&&0<#<11&]
```
### Explanation
Function `j` concatenates two numbers digit-wise.
Function `z` takes a result `r`, number `n`, and list of functions `L`, each which operates on two arguments. It then applies the list of functions sequentially to argumnts `[r,n]` using recursion, until the list is empty, whereupon it returns the result.
Function `a` takes a number `n` and a number of copies `t`. It creates all tuples of length (t-1) from the list of functions `{Plus, f, Times, g, Power, h, j}` and sends each tuple through function z, then returns a list of all numbers 1 through 10 that were created.
Example execution `a[2,3]` returning `{1, 2, 3, 6, 8}`.
### Limitations
Because the list of functions is applied sequentially, consuming one copy of the number each time, it can miss some combinations. For example, when operating on four twos, it would miss 22/22 = 1 due to its inability to evaluate the list of functions out of order. Of course, 2/2\*2/2 = 1 covers this case.
[Answer]
# Python 3 (imperfect), 449 - 300 = 149
Suffers from all the same shortcomings as [KSab's solution](https://codegolf.stackexchange.com/a/38178/16766): no unary operators, fully parenthesized, contains equivalent expressions like `(1+1)+1` and `1+(1+1)`. I eliminated exact duplicates by passing the results to `set()`. The output could be a bit uglier to save a few bytes, but I like it this way. I also didn't do nth roots because it doesn't seem like they buy you much in this problem.
```
R=range
E=lambda z:eval(z.replace("^","**"))
def m(d,n):_=R(1,11);s={i:[]for i in _};r=R(1,n);n<2 and s[d].append(str(d));d=str(d);t=[[(d*i,i)for i in r]]+[[]]*n;h=[];[(h.append("("+A+o+B+")"),t[l].append((h[0],a+b))if a+b<n else E(*h)in _ and s[E(*h)].append(h[0]),h.pop())for l in r for j in R(l)for A,a in t[j]for k in R(l)for B,b in t[k]if a+b<=n for o in"+-*/^"if(o=="^"and-~-(0<E(B)<9)or 0==E(B)and"/"==o)-1];[print(i,set(s[i])or'')for i in _]
```
This will take several minutes to run if the second argument is 5. Test by calling `m(digit, number)`:
```
>>> m(1,3)
1 {'((1*1)^1)', '(1^(1+1))', '((1-1)+1)', '((1/1)/1)', '((1*1)*1)', '((1^1)/1)', '(1*(1*1))', '(1^(1*1))', '(1+(1-1))', '(1^(1^1))', '((1^1)*1)', '(1^(1/1))', '((1/1)*1)', '(1-(1-1))', '(1/(1^1))', '(1/(1*1))', '(1/(1/1))', '(1*(1^1))', '((1+1)-1)', '((1*1)/1)', '((1^1)^1)', '(1*(1/1))', '((1/1)^1)'}
2 {'(1*(1+1))', '((1^1)+1)', '((1+1)/1)', '((1*1)+1)', '((1+1)^1)', '(1+(1*1))', '((1/1)+1)', '(1+(1^1))', '(1+(1/1))', '((1+1)*1)'}
3 {'((1+1)+1)', '(1+(1+1))'}
4
5
6
7
8
9
10 {'(11-1)'}
>>> m(3,3)
1 {'((3/3)^3)'}
2 {'(3-(3/3))', '((3+3)/3)'}
3 {'(3-(3-3))', '((3-3)+3)', '((3/3)*3)', '(3*(3/3))', '(3/(3/3))', '((3+3)-3)', '(3^(3/3))', '(3+(3-3))', '((3*3)/3)'}
4 {'((3/3)+3)', '(3+(3/3))'}
5
6 {'((3*3)-3)'}
7
8
9 {'(3+(3+3))', '((3+3)+3)', '((3^3)/3)'}
10
```
] |
[Question]
[
As we all know, limericks are short, five-line, occasionally-lewd poems with an AABBA rhyming scheme and an anapestic meter (whatever that is):
>
> Writing a Limerick's absurd
>
> Line one and line five rhyme in word
>
> And just as you've reckoned
>
> They rhyme with the second
>
> The fourth line must rhyme with the third
>
>
>
You are tasked to write the *shortest* program that, when fed an input text, prints whether it thinks that the input is a valid limerick. Input can either be on the command line or through standard input, at your option, and output could either be a simple "Y"/"N" or a confidence score, again at your option.
Here's another example of a correct limerick:
>
> There was a Young Lady whose eyes
>
> Were unique as to colour and size
>
> When she opened them wide
>
> People all turned aside
>
> And started away in surprise
>
>
>
But the poem below is clearly *not* a limerick, since it doesn't rhyme:
>
> There was an old man of St. Bees
>
> Who was stung in the arm by a wasp.
>
> When asked, "Does it hurt?"
>
> He replied, "No, it doesn't,
>
> I'm so glad that it wasn't a hornet."
>
>
>
Nor is this one, as the meter is all wrong:
>
> I heard of a man from Berlin
>
> Who hated the room he was in
>
> When I asked as to why
>
> He would say with a sigh:
>
> "Well, you see, last night there were a couple of hoodlums around who were celebrating the Bears winning the darned World Cup, and they were really loud so I couldn't sleep because of the din."
>
>
>
### Clues
Here are some of the clues you could use to decide whether or not your input is a limerick:
* Limericks are always five lines long.
* Lines 1, 2 and 5 should rhyme.
* Lines 3 and 4 should rhyme.
* Lines 1, 2 and 5 have around 3x3=9 syllables, while the third and fourth have 2x3=6 syllables
Note that none of these except the first are hard-and-fast: a 100% correctness rating is impossible.
### Rules
* Your entry should *at the very least* correctly categorize examples 1 through 3 in a deterministic fashion.
* You *are* allowed to use any programming language you would like, except of course programming languages specifically designed for this contest (see [here](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny)).
* You *are not* allowed to use any library except your programming language's standard offerings.
* You *are* allowed to assume that [this file](http://svn.code.sf.net/p/cmusphinx/code/trunk/cmudict/cmudict.0.7a), the CMU Sphinx pronounciation dictionary, is in a file called 'c' in the current directory.
* You are *not* allowed to hard-code for the test inputs: your program should be a general limerick categorizer.
* You *are* allowed to assume that the input is ASCII, without any special formatting (like in the examples), but your program should not be confused by interpunction.
### Bonuses
The following bonuses are available:
* Your program outputs its result as a limerick? Subtract **150 characters** length bonus!
* Your program also correctly identifies sonnets? Subtract **150 characters** extra length bonus!
* Your program outputs its result as a sonnet when used on a sonnet? Subtract **100 characters** additional extra length bonus!
### Finally...
Remember to mention which bonuses you think you deserve, if any, and subtract the bonus from your number of characters to arrive at your score. This is a *code golf* contest: the shortest entry (i.e. the entry with the lowest score) wins.
If you need more (positive) test data, check out the [OEDILF](http://www.oedilf.com/db/Lim.php?ShowcaseAction=Author&ShowcaseAuthor=159) or the [Book of Nonsense](http://www.gutenberg.org/files/982/982-h/982-h.htm). Negative test data should be easy to construct.
Good luck!
[Answer]
# Python: 400 - 150 - 150 = 100
The shortest script I could come up with is that one...
```
import re,sys;f,e,c=re.findall,lambda l,w:f('^'+w.upper()+' (.+)',l),lambda*v:all([a[i]==a[v[0]]for i in v]);a=[sum([[e(l,w)[0].split()for l in open('c')if e(l,w)][0]for w in f(r'\w+',v)],[])[-2:]for v in sys.stdin];n=len(a);print n==14and c(0,3,4,7)*c(1,2,5,6)*c(8,11)*c(9,12)*c(10,13)*"Sonnet"or"For a critic\nOf limerick\nWell-equipped\nIs this script.\n%s limerick!"%(n==5and c(0,1,4)and c(2,3))
```
...but don't even try it. It parses the provided dictionary for every word it meets, thus being very slow. Also, an error is generated whenever a word is not in the dictionary.
The code still meets the requirements though: recognizing whether the text passed via *stdin* is a limerick, a sonnet, or neither of those.
With only 20 more characters, here is the optimized version:
```
import re,sys;f,e,c=re.findall,lambda l:f(r'^(\w+) (.+)',l),lambda*v:all([a[i]==a[v[0]]for i in v]);d={e(l)[0][0]:e(l)[0][1].split()for l in open('c')if e(l)};a=[sum([d.get(w.upper(),[])for w in f(r'\w+',v)],[])[-2:]for v in sys.stdin];n=len(a);print n==14and c(0,3,4,7)*c(1,2,5,6)*c(8,11)*c(9,12)*c(10,13)*"Sonnet"or"For a critic\nOf limerick\nWell-equipped\nIs this script.\n%s limerick!"%(n==5and c(0,1,4)and c(2,3))
```
**Features**
* able to recognize sonnets (-150)
* answers to limericks with a limerick (-150)
* relatively fast: only one file parsing per execution
**Usage**
```
cat poem.txt | python poem-check.py
```
3 different outputs are possible:
* a limmerick saying the input is one if it is the case
* a limmerick saying the input is not one if it is the case
* "Sonnet" if the input is recognized as such
**Expanded code with explanations**
```
import re, sys
# just a shortened version of the 're.findall' function...
f = re.findall
# function used to parse a line of the dictionary
e = lambda l:f(r'^(\w+) (.+)', l)
# create a cache of the dictionary, where each word is associated with the list of phonemes it contains
d = {e(l)[0][0]:e(l)[0][1].split(' ') for l in open('c') if e(l)}
# for each verse (line) 'v' found in the input 'sys.stdin', create a list of the phoneme it contains;
# the result array 'a' contains a list, each item of it corresponding to the last two phonemes of a verse
a = [sum([d.get(w.upper(), []) for w in f(r'\w+',v)],[])[-2:] for v in sys.stdin]
# let's store the length of 'a' in 'n'; it is actually the number of verses in the input
n = len(a)
# function used to compare the rhymes of the lines which indexes are passed as arguments
c = lambda*v:all([a[i] == a[v[0]] for i in v])
# test if the input is a sonnet, aka: it has 14 verses, verses 0, 3, 4 and 7 rhyme together, verses 1, 2, 5 and 6 rhyme together, verses 8 and 11 rhyme together, verses 9 and 12 rhyme together, verses 10 and 13 rhyme together
if n==14 and c(0,3,4,7) and c(1,2,5,6) and c(8,11) and c(9,12) and c(10,13):
print("Sonnet")
else:
# test if the input is a limerick, aka: it has 5 verses, verses 0, 1 and 4 rhyme together, verses 2 and 3 rhyme together
is_limerick = n==5 and c(0,1,4) and c(2,3)
print("For critics\nOf limericks,\nWell-equipped\nIs this script.\n%s limerick!", is_limmerick)
```
[Answer]
# ECMAScript 6 (138 points; try in Firefox):
`288` - `150` points bonus for including limerick (pinched from @MathieuRodic).
```
a=i.split(d=/\r?\n/).map(x=>x.split(' '));b=/^\W?(\w+) .*? (\w+\d( [A-Z]+)*)$/;c.split('\r\n').map(x=>b.test(x)&&eval(x.replace(b,'d["$1"]="$2"')));e=f=>d[a[f][a[f].length-1]];alert('For critics\nOf limericks,\nWell-equipped\nIs this script.\n'+(a[4]&&e(0)==e(1)&e(0)==e(4))+' limerick!')
```
## Notes:
Expects the variable `c` to contain the contents of the dictionary file, as you can't read files in plain ECMAScript.
ECMAScript doesn't have standard input, but `prompt` is generally considered "standard input"; however, as `prompt` converts line breaks to spaces in most (if not all) browsers, I'm accepting input from the variable `i`.
## Ungolfed code:
```
// If you paste a string with multiple lines into a `prompt`, the browser replaces each line break with a space, for some reason.
//input = prompt();
// Split into lines, with each line split into words
lines = input.split('\n').map(x => x.split(' '));
dictionaryEntryRegEx = /^\W?(\w+) .*? (\w+\d( [A-Z]+)*)$/;
dictionary = {};
// Split it into
c.split(/\r?\n/).map(x => dictionaryEntryRegEx && eval(x.replace(dictionaryEntryRegEx, 'dictionary["$1"] = "$2"')));
// Get the last word in the line
getLastWordOfLine = (lineNumber) => dictionary[line[lineNumber][line[lineNumber].length - 1]]
alert('For critics\nOf limericks,\nWell-equipped\nIs this script.\n' + (lines[4] && getLastWordOfLine(0) === getLastWordOfLine(1) && getLastWordOfLine(0) === getLastWordOfLine(4)) + ' limerick!');
```
] |
[Question]
[
The Nonary Game is a fictional game played in the video game trilogy of the same name. Your goal is to find how many players (at best) can escape a given game, in as few bytes of code as possible.
## Rules of the game
* There are 9 players, numbered 1 to 9.
* All players start in the same room.
* There are any number of doors, each one with a 1 to 9 number. There may be duplicate or missing door numbers.
* Door are **one-way** connections between rooms. Each door can **only be used once**.
* Only groups of **3 to 5 players** can go through a door.
* A group can only go through a door if the **sum of their numbers modulo 9** matches the door’s number modulo 9.
* Any player who goes through a 9 door escapes (wins).
## Examples
```
┌───┬───┬───┐
│ 6 4 9
│ < │ | |
│ 3 5 9
└───┴───┴───┘
```
`<` represents the starting point. All players start there.
In this setting, everybody can escape. There are various ways to achieve this, one of which is:
* [1, 2, 3, 4, 5] go though door 6 ((1+2+3+4+5) % 9 = 6), while [6, 7, 8, 9] go through door 3 ((6+7+8+9) % 9 = 3). Everybody meets up in the second room.
* [1, 2, 3, 7] go through door 4, while [4, 5, 6, 8, 9] go through door 5.
* [1, 2, 3, 4, 8] go through one of the 9 doors, [5, 6, 7, 9] go through the other one.
```
┌───┬───┐
│ │ |
│ < 8 9
│ │ |
└───┴───┘
```
This time, at most 4 people can escape:
* [1, 3, 5, 8, 9] go through door 8.
* [1, 3, 5, 9] go through door 9.
Other lists of survivors are possible, such as [2, 3, 4] or [1, 4, 6, 7], but there's no way for more than 4 people to escape.
## The challenge
Given a map, output the maximum numbers of player who can escape.
* Don’t worry, you don’t need to parse my awful diagrams! Input is a labeled directed graph, which you can represent in any convenient format (edge set, adjacency matrix...).
* If your representation requires labels for rooms, you can use any consistent set of values. However, doors must be represented by the integers 1 to 9.
* The input will always have at least one 9 door. All 9 doors always lead to the exit, while other doors never do.
* Your submission can be a function or full program.
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are banned.
## Test cases
Inputs are shown as lists of [door number, from room, to room] triplets, with 0 being the starting room and -1 being the exit. If you choose to use another format, you’ll have to convert them appropriately.
```
Input Output
[[6, 0, 1], [3, 0, 1], [4, 1, 2], [5, 1, 2], [9, 2, -1], [9, 2, -1]] 9
[[8, 0, 1], [9, 1, -1]] 4
[[9, 0, -1]] 5
[[2, 0, 1], [1, 1, 2], [9, 2, -1]] 0
[[2, 0, 1], [3, 1, 2], [9, 2, -1]] 3
[[1, 0, 1], [9, 1, -1], [1, 0, 2], [9, 2, -1]] 4
[[2, 0, 1], [3, 0, 1], [5, 1, 2], [4, 0, 2], [9, 2, -1], [9, 2, -1]] 8
[[3, 0, 1], [4, 0, 1], [5, 0, 1], [9, 1, -1], [7, 1, 2], [9, 2, -1]] 7
[[1, 0, 1], [2, 0, 1], [4, 0, 1], [9, 1, -1], [8, 1, 2], [9, 2, -1]] 6
[[6, 0, 1], [7, 0, 1], [9, 1, -1], [9, 1, -1]] 7
```
[Answer]
# JavaScript (ES6), 219 bytes
A slower but significantly shorter version using bitmasks instead of strings.
```
f=(D,P=[511],e=m=0)=>P.map((X,r)=>[...Array(-~X)].map((_,p)=>D.map(([d,s,t],j)=>(N=(g=(n,k)=>n&&n%2+g(n>>1,++k,x+=n%2*k))(p&=X,x=0))<3|N>5|r-s|x%9^d%9||f(D.filter(_=>j--),A=[...P],e+!~t*N,A[r]^=p,A[t]^=p))),m=m>e?m:e)|m
```
[Try it online!](https://tio.run/##pZFba8JAEIXf@yu2D8qsmcRcmtqUTorgs/goLFGCJuIlFzahWAj@9XQ1gtDYVum@HGYGvnNmdhN@hMVCrvNST7NlVNcxwQgnJFzLCjCihExO/sRIwhxgilIVwjCMoZThJ@iHKQ@a0RxzNRo1hVhigWWAG9WCMcGKIMWtKtJuN@3Y2gpS37dQ07a410h1elvOIe/SFPfKj7851dh3K6kX1b7jzZYdr6piGBnxeldGEubkb3Sd45COUSYqpvZ4KHtjHAoZzChXWh6Vc44JJX70nrxGvErqRZYW2S4ydtkKYhDiBZmJTO3JhKcUmW4FAbvncc76ffb08J3snch341pkt0W2L5mtU2b7HN@@1a8hm7@Rnf@QnRbZunLnJr95o8tPd36@kAfXTf762IY8qL8A "JavaScript (Node.js) – Try It Online")
NB: The reason why it's slower is that we do not compute the powersets of the players. Given a bitmask of players \$X\$, we iterate on all \$(X \operatorname{AND} p)\$ for \$0\le p\le X\$ without deduplicating.
---
# JavaScript (ES7), ~~293 272~~ 271 bytes
Takes input in the format described in the challenge. This is a brute force search.
```
f=(D,P=[17**6+'8'],e=m=0)=>P.map((X,r)=>X&&[...X].reduce((a,x)=>[...a,...a.map(y=>y+x)],['']).map(p=>D.map(([d,s,t],j)=>p<99|p[5]|r-s|eval([...p].join`+`)%9^d%9||f(D.filter(_=>j--),A=[...P],e+!~t*p.length,A[r]=X.replace(eval(`/[${p}]/g`),''),A[t]=[A[t]]+p))),m=m>e?m:e)|m
```
[Try it online!](https://tio.run/##pdLdboIwFAfw@z0FS6a0cqjiF7KsLCY@gJcmTTeJFqcBaZAZzdhe3fHhog50mnFR4KT9nT8nLJy1s5qEcxnpy2AqdjuXogEMKTPMWq2rqT2Vg6A@bWBqD4nvSIRGECYvo2qVEUJGnIRi@j4RCDmwSepp0YF0yXZvqb3VNpgDU1WOs5Kk9iCX2BRWEHFYJOfkk2XFknV4HOqrWKwdD6WU5GQRzJdjbYwr1su0YsWxiwbEnXuRCNErtRe6jqFP073DJKp2/xXVJPHEcha9QZ@FnI6ShNJzkoiZOq6zhw/5yeuzMQZVTQ6ziFOWrlyTGGPwqW@LZ/9R4NjfTYLlKvAE8YIZchFjPVAaoBgcFGYld1B0g3PllgtjpV5X2ne/ZSuTb@YKcqcgNw@ZjSxzcx@/eW2/XG5cklv/kVsF2SiZc56/cWWXc3M@zfzz2DnEb5f0OOmXy72CfMS1T@SyLzHL5pXL5qVpNEubHMu983K3IHcPhlnO/fWb7zPvvgE "JavaScript (Node.js) – Try It Online") (the first test case times out on TIO)
### How?
The array `P[]` holds a list of strings describing the players in each room.
We start with `P=['241375698']` (using \$17^6=24137569\$), which means that all players are initially located in room \$0\$.
For each room `X` at position `r`, we compute the powerset of `X`:
```
[...X].reduce((a, x) => [...a, ...a.map(y => y + x)], [''])
```
For each group of players `p` in there and for each door `[d,s,t]` at index `j`, we test if the group is unable to pass through the door:
```
// we can't pass if:
p < 99 | // there are less than 3 players
p[5] | // or there are more than 5 players
r - s | // or the source room s is not equal to the current room
eval([...p].join`+`) % 9 // or the sum of the players modulo 9
^ d % 9 // does not match the ID of the door modulo 9
```
If the group can pass, we do a recursive call:
```
f( //
D.filter(_ => j--), // remove the door that has just been used from D[]
A = [...P], // use a copy A[] of P[]
e + !~t * p.length, // if t = -1, add the length of p to e (number of escaped guys)
A[r] = X.replace( // remove the players from the source room A[r]
eval(`/[${p}]/g`), //
'' //
), //
A[t] = [A[t]] + p // and append them to the target room A[t]
) //
```
We keep track of the maximum number of escaped players in `m` and eventually return it.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 76 bytes
```
2ịịœc3r5¤ẎS,%9EʋƇ1ị${ḟ@;ƭⱮ€Ḋị¥ż€Ḋ{ṛṪ}¦ƒ€
ç@€Ẏ;ḷṢ€€Q
“”WẋḊ€FṀƊ9RW¤;Wçƒ@⁸ẈṪ$€Ṁ
```
[Try it online!](https://tio.run/##y0rNyan8/9/o4e5uIDo6Odm4yPTQkoe7@oJ1VC1dT3UfazcEiqtUP9wx38H62NpHG9c9alrzcEcXUPDQ0qN7IJzqhztnP9y5qvbQsmOTgCJch5c7gCR29Vk/3LH94c5FQA4QBXI9apjzqGFu@MNd3UBNQBG3hzsbjnVZBoUfWmIdfnj5sUkOjxp3PNzVATRLBWTAzob/Ryc93DnDGqhRQddOAajZ@nA71@F2oGTk///RXNHRZjoKhjoKRrE6CtHGCKYJkNZRMAYxTRFMSyCto2CAzIzVAZphgdBoCVYNFbcEi0M5RghFhphGoisxxqHEENMqiIGGhA2EMZF8ZIKpEd0M1FBBMgOLO8wJu9oIq3FIZljgMAMposyxaoQHPVcsAA)
A full program taking a single argument, a directed graph using rooms 1, 2, ... and 0 as exit. Returns an integer which is the maximum number that can escape. Full explanation to follow.
Should run without the `Ṣ€€Q` for a 4-byte saving but slow to rest.
[Answer]
# Python3, 402 bytes
Little long, but very fast:
```
from itertools import*
R=range
O=sorted
def f(r):
q=[({0:{*R(1,10)}},r,0)]
l,S=[],[]
for D,r,C in q:
l+=[len(D.get(-1,[]))]
for i in D:
for t in R(3,6):
for j in combinations(D[i],t):
for a,b in enumerate(r):
if b[0]%9==sum(j)%9 and b[1]==i:
if(str(U:={**D,i:O({*D[i]}-{*j}),b[2]:O({*D.get(b[2],[]),*j})}))not in S:q+=[(U,r[:a]+r[a+1:],C)];S+=[str(U)]
return max(l+[0])
```
[Try it online!](https://tio.run/##lZLNbqswEIX3PIU3lWwyqXDSn0DlVdlXStSV5QW5Mb2OwCTGke4V4tlT22kFVaiqsvHM4ZszM4bDf/u30cvVwZzPpWlqpKw0tmmqFqn60BgbR2tmCv0moxfWulzuop0sUYkNySJ0ZBx3SdbFa0yBJqTvwUBCRIQq2DAugLuwbAzKnf6MlEZHV4WqGeOV1Di/fZMWz6nDiC8KqPJY7rGQWp@u8RIeSNCCuPfin6beKl1Y1egW51wJsB9IYArYekrqUy1NYeVl4vCoEm15Im5SxtpTjffkJkWF3jmRCsbUJ@Y43FqDXzPWxXEOKnvBXew79fMu3vcEtnwhLmLYxKd@F/Ave0J0E6bfZEe3MH4Fw7NCzAwvZjQT8EzE08a9CC38@kbak9GoLv7haubmI@eDUdriEnP@ACgBRAUgvhzCO3cCWvjwfghTdwKa0y@xu@FosFsNHmkovCLSQFzJi6GQTnT8Fl7@CNOJkS5dkt90@QxH93E3YfG93dfrHdlNTff4m7UWk85ju9WPdqP/4HHaY/w9z@8)
] |
[Question]
[
# Who are they?
Primus-Orderus Primes (POP) are primes which contain their **order** in the sequence of primes.
So the `nth` prime, in order to be POP, must contain all the digits of `n` in a certain way which I'll explain.
# Examples
Let's get things clearer:
All digits of `n` must appear among the digits of POP in the same order they appear in `n`
The `6469th` prime is `64679` which is POP because it contains all digits of `6469` in the right order .
`1407647` is POP because it is the `107647th` prime number
**14968819** is **POP** (968819th prime).So this challenge is **NOT** [OEIS (A114924)](https://oeis.org/A114924)
1327 is **NOT POP** because it is the `217th` prime (digits are not in the right order)
# The Challenge
You guessed right!
Given an integer `n`, output the `nth` POP
# Test Cases
input-> output
```
1->17
3->14723
5->57089
10->64553
29->284833
34->14968819
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest answer in bytes wins!
**All these should be 1-Indexed**
[Answer]
# Mathematica, 104 bytes
Extremely **efficient**
```
(t=i=1;While[t<#+1,If[!FreeQ[Subsets[(r=IntegerDigits)@Prime@i,{Length@r@i}],r@i],t++];i++];Prime[i-1])&
```
finds n=34 in under a minute
[Answer]
# [Husk](https://github.com/barbuz/Husk), 11 bytes
```
!fS¤o€Ṗdṗİp
```
[Try it online!](https://tio.run/##AR0A4v9odXNr//8hZlPCpG/igqzhuZZk4bmXxLBw////NQ "Husk – Try It Online")
Not that fast, computes f(5) in around 30 seconds on TIO
### Explanation
```
!fS¤o€Ṗdṗİp
f İp Filter the list of prime numbers and keep only those for which:
S¤o€Ṗdṗ The "d"igits of its index in the "ṗ"rime numbers are an "€"lement of the
"Ṗ"owerset of its "d"igits
! Return the element at the desired index of this filtered list
```
[Answer]
# [Python 2](https://docs.python.org/2/) + [gmpy2](https://gmpy2.readthedocs.io/en/latest/), 188 162 bytes
Quite efficient, finds n=34 in 22 seconds on [TIO!](https://tio.run/##JYxBDoMgFAX3nOLHlVSbWNsV5nfpJYwpGrESCxICqXJ5Stvdy7zJmMMtm65jnO2m4KnMUYNUZrPuRCYxQ5sP5UgZAYkrVgTei3wJGDvJ@kFPMHQr69laYBo9YuJ9Iwu8ELDCeauzKrv/HLKj1Ma7nBKPIQn/0M4CarG7h7FSiTzQZj9jm3PPSx44bfy3lT7tIMR4vX0A)
Could probably be golfed a bit
```
from gmpy2 import*
def F(a,b):
i=k=0
while b[i:]and a[k:]:k+=a[k]==b[i];i+=1
return"0">a[k:]
x=input()
u=z=1
while x:z=next_prime(z);x-=F(`u`,`z`);u+=1
print z
```
[Try it online!](https://tio.run/##JYxBDoMgFAX3nOKnK6g2sSbdYH6XXsKYohErsSAhkCKXp7bdvcybjN39spk659ltGp7a7jUobTfnz2SSM7R0KEfGCShcsSLwXtRLwtgp3g9mgqFbec/XAo/RIx68b1SBVwJO@uDMqTrdfw6JqIwNnjISMB3CPxR5QiOjf1intKSJNfGCLRVBlCIJ1oRv6/iMh5Tz7QM)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes
```
µN<Ø©æNå½}®
```
[Try it online!](https://tio.run/##AR0A4v8wNWFiMWX//8K1TjzDmMKpw6ZOw6XCvX3Crv//MQ "05AB1E – Try It Online")
Extremely inefficient.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
ÆNDŒPḌċµ#ṪÆN
```
[Try it online!](https://tio.run/##y0rNyan8//9wm5/L0UkBD3f0HOk@tFX54c5VQJH///8bAQA "Jelly – Try It Online")
Extremely inefficient but works.
] |
[Question]
[
Let us say a substring is any continuous section of an original string. For example `cat` is a substring of `concatenate`. We will say that a *proper* substring is a substring that is not equal to the original string. For example `concatenate` is a substring of `concatenate` but not a proper substring. (single character strings have no proper substrings)
We will now define a sequence using these terms. The **n**th term in this sequence will be the smallest number such that there is a proper substring of its binary representation that is not a substring of any earlier term in the sequence. The first term is `10`.
As an exercise lets generate the first 5 terms. I will work in binary to make things easier.
The first term is `10`. Since `11`, the next smallest number, has only one proper substring, `1` which is also a substring of `10`, `11` is not in the sequence. `100` however does contain the proper substring `00` which is not a substring of `10` so `100` is our next term. Next is `101` which contains the unique proper substring `01` adding it to the sequence, then `110` contains the proper substring `11` which is new adding it to the sequence.
Now we have
```
10, 100, 101, 110
```
`111` is up next but it contains only the substrings `1` and `11` making it not a term. `1000` however contains `000` adding it to the sequence.
Here are the first couple terms in decimal
```
2, 4, 5, 6, 8, 9, 10, 11, 14, 16, 17, 18, 19, 20, 21, 22, 23, 24, 26, 30, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 50, 54, 56, 58
```
## Task
Either
* Take **n** as input and generate the **n**th term in this sequence (either 0 or 1 indexed)
* Continuously output terms of the sequence
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") answers are scored in bytes with less bytes being better.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~88~~ ~~80~~ ~~78~~ 75 bytes
-6 bytes thanks to Wheat Wizard
-2 bytes thanks to RootTwo
-3 bytes thanks to notjagan
```
s={0}
n=1
while 1:n+=1;b=f"{n:b}";p={b[1:],b[:-1]};s|=p-s and{b,print(n)}|p
```
[Try it online!](https://tio.run/##BcFBCoAgEADAu68IT0UKLd2UfYl4aKkoiG3JIMJ8u83Ie28nj7UmzENRjKCebT@WBhz3CJ5w1ZkdFe0FMwVw0VBwFmLx6UOxqZl4zmTk2vluuSuf1PoD "Python 3 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 22 bytes
```
BẆṖ
ṄÇ;ð⁹Çḟ¥?⁹⁸‘¤ß
2ç⁸
```
[Try it online!](https://tio.run/##y0rNyan8/9/p4a62hzuncT3c2XK43frwhkeNOw@3P9wx/9BSeyDzUeOORw0zDi05PJ/L6PByIO//fwA "Jelly – Try It Online")
[Answer]
## Mathematica, 116 110 bytes
```
x={};f=Subsequences[#~IntegerDigits~2]&;Do[MemberQ[Most@f@n,s_/;FreeQ[f/@x,s,2]]&&x~AppendTo~Echo@n,{n,2,∞}]
```
Infinitely outputs terms of the sequence.
# Explanation
```
x={};
```
`x` is the list of terms of the sequence so far.
```
f=Subsequences[#~IntegerDigits~2]&
```
`f` is a `Function` which takes an integer and returns all `Subsequences` of its base `2` representation (including the empty list `{}` and the full list of `IntegerDigits` itself).
```
Do[...,{n,2,∞}]
```
Evaluate `...` for value of `n` from `2` to `∞`.
```
...&&x~AppendTo~Echo@n
```
If `...` is `False`, then the second argument to `And` (`&&`) is never evaluated. If `...` is `True`, then `Echo@n` prints and returns `n`, which we then `AppendTo` the list `x`.
```
MemberQ[Most@f@n,s_/;FreeQ[f/@x,s,2]]
```
We want to check that some proper substring of `n` is not a substring of any previous term in the sequence. `Most@f@n` is the list of proper substrings of `n`, we then check whether there are any substrings `s_` which is a `MemberQ` of that list such that the list `f/@x` of lists of substrings of previous terms of the sequence is `FreeQ` of `s` at level `2`.
[Answer]
# Mathematica, ~~109~~ 94 bytes
```
s={};Do[!SubsetQ[s,(t=Subsequences@IntegerDigits[i,2])[[2;;-2]]]&&(s=s~Join~t;Echo@i),{i,∞}]
```
Continuously output terms of the sequence
*Special thanx to **@ngenisis** for -15 bytes*
# Mathematica, 123 bytes
```
(s=r={};For[i=2,i<2#,i++,If[!ContainsAll[s,(t=Subsequences@IntegerDigits[i,2])[[2;;-2]]],s=s~Join~t;r~AppendTo~i]];r[[#]])&
```
Take n as input and generate the nth term in this sequence (1 indexed)
**input**
>
> [1000]
>
>
>
**output**
>
> 1342
>
>
>
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 20 bytes
```
u+G
fP-Fm.:.Bd)+TG1Y
```
This prints the sequence infinitely. It can only be used offline as a consequence.
Explanation (The space is a newline):
```
u+G fP-Fm.:.Bd)+TG1Y
u Y Apply the following function to the previous output
until it stops changing (or forever, in this case),
starting with the empty list
f 1 Find the first positive integer where
+TG The integer prepended to the current list
m Map to
.Bd Convert to binary
.: ) Form all subsequences
-F Fold the filter-out function over the list
This iteratively removes all subsequences already seen
from the candidate
P Remove the last subsequence which is the whole number.
(newline) Print that first integer
+G Prepend that first integer to the list
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 20 bytes
```
.V2I-=ZP.:jb2)Yb=+YZ
```
[Try it online!](https://tio.run/##K6gsyfj/Xy/MyFPXNipAzyoryUgzMslWOzLq/38A "Pyth – Try It Online")
[Answer]
# Haskell, 172 bytes
```
import Data.List
b 0=""
b n=b(n`div`2)++(show$n`mod`2)
s=nub.(tails=<<).inits
p x=s x\\[x]
n(_,l)x|(p.b)x\\l/=[]=(x,l++(s.b)x)|1<2=(0,l)
filter(>1)$fst<$>scanl n(1,[])[1..]
```
[Try it online.](https://tio.run/##FYzBboMwEETv/opVxGGtIBci9cbm1GP/gKBiGlBWMQvCm9SH/Dt1TvPmaTQ3H@9jCPvO87psCl9evfvmqGaAig6HHEIDSn/lZ3@yxyPG2/JXSD8v19xNJHkMDtVziNQ01rGwRrNCogjpcmlTZwR/ymDTC1c32OzCB7UdYSrD@@7t7KtuToRVnpmJJg46bniubTFFbYpz/PUSQLAu2862tXPdPnsWIFg3FoUC1N9H@KwyTfs/)
### Explanation
The code generates the sequence continuously.
* `b` returns the binary representation of an `Int` as a `String`
* `s` returns all the substrings of a string
* `p` returns all the proper substrings of a string
* `n` is a function that is applied iteratively and returns a tuple containing:
+ the current element, if it is a member of the sequence, otherwise 0
+ a list of all substrings to check against for all following numbers
* finally, `scanl` is used to call `n` over and over again and its output is filtered to only contain elements greater than 1
Here's a slightly more readable version, before golfing:
```
import Data.List
binary :: Int -> String
binary 0=""
binary n|(d,r)<-divMod n 2=binary d++["01"!!r]
substrings :: String -> [String]
substrings xs = nub$inits xs>>=tails
properSubstrings :: String -> [String]
properSubstrings xs = substrings xs\\[xs]
sb = substrings.binary
psb = properSubstrings.binary
g = scanl step (1,[]) [1..]
where step (_,l) x | psb x \\ l /= [] = (x,l++sb x)
| otherwise = (0,l)
f=filter(>1)$fst<$>g
```
[Answer]
# JavaScript, 57 bytes
```
for(x=1;;x++)/^10|10(00)*$/.test(x.toString(2))&&alert(x)
```
```
alert=x=>{if(x>100)throw 'Let we stop here.';document.write(x+'<br/>');};
for(x=1;;x++)/^10|10(00)*$/.test(x.toString(2))&&alert(x)
```
Let we write the given number *n* in binary form, then:
* If the number is starts with `10`, *n* must in the sequence:
+ remove the first `1` in it, the remaining binary string must not be seen, since *n* is the smallest number which may contain such string
* If the number is starts with `11`:
+ By removing the first `1` in it, the remaining binary string (let we donate it as `1x` must be seen since:
- number `1x` is in the sequence, or
- number `1x0` is in the sequence, since it contain unique sub string `1x`
+ If it is odd (ends with 1), it must not in the sequence, since:
- (*n* - 1) / 2 in the sequence, or
- (*n* - 1) in the sequence, since it contain unique sub string (*n* - 1) / 2
+ If it is even (ends with 0), it is in the sequence iff *n* / 2 is not in the sequence
- with the same idea, *n* / 2 is *not* in the sequence iff *n* / 2 is odd, or n / 4 is in the sequence
Conclusion:
the binary form of the number starts with `10` or ends with `1` followed by odd number of `0`. Or describe in regex: x match `/^10|10(00)*$/`.
] |
[Question]
[
A stack state diagram shows how the values on one stack are changed into the other. For example, this is a stack state diagram:
```
3 0 2 1 0
```
This means that there is a stack initially containing 3 values (the `3` part). These values are indexed from 0 to 2, with 0 at the top: `2 1 0`. The next part `0 2 1 0` describes the final state of the stack: the value that was originally on top of the stack has been copied to the back as well.
These transformations happen on a stack that has support for several data types:
* The "value" type, which is what is originally on the stack. This could be a string, integer, etc. but its value does not need to be known.
* The "list" type, which is a list containing values of any data type.
To model this transformation, the following operations are permitted:
* `S`: Swap the two values on top of the stack: `2 1 0` → `2 0 1`
* `D`: Duplicate the value on top of the stack: `1 0` → `1 0 0`
* `R`: Remove the top value on the stack. `2 1 0` → `2 1`
* `L`: Turn the top value into a one-element list containing that value: `2 1 0` → `2 1 (0)`
* `C`: Concatenate the top two lists on the stack: `2 (1) (0)` → `2 (1 0)`
* `U`: Place all the values from a list onto the stack: `2 (1 0)` → `2 1 0`
These are equivalent to the [Underload](https://esolangs.org/wiki/Underload) commands `~ : ! a * ^`, provided that no other commands are used.
`S`, `D`, `R`, and `L` can be used with any values on top of the stack, but `C` and `U` must have lists on top of the stack to function. A submission whose generated sequences attempt to preform invalid operations (like `D` on an empty stack or `U` on a non-list) is *wrong* and must be ~~punished~~ fixed.
To solve a stack state diagram, find a sequence of commands that will correctly transform the initial stack state into the new one. For example, one solution to `3: 0 2 1 0` is `LSLCSLCULSLCLSLDCSC USLCU`:
```
2 1 0
L 2 1 (0)
S 2 (0) 1
L 2 (0) (1)
C 2 (0 1)
S (0 1) 2
L (0 1) (2)
C (0 1 2)
U 0 1 2
L 0 1 (2)
S 0 (2) 1
L 0 (2) (1)
C 0 (2 1)
L 0 ((2 1))
S ((2 1)) 0
L ((2 1)) (0)
D ((2 1)) (0) (0)
C ((2 1)) (0 0)
S (0 0) ((2 1))
C (0 0 (2 1))
U 0 0 (2 1)
S 0 (2 1) 0
L 0 (2 1) (0)
C 0 (2 1 0)
U 0 2 1 0
```
Your task is to write a program that takes a stack state diagram and outputs a solution.
# Test Cases
```
2 1 0 ->
3 2 0 -> SR
9 -> RRRRRRRRR
2 0 1 0 -> LSLCDCUR
2 0 1 1 -> SD
6 2 -> RRSRSRSR
5 0 1 2 3 4 -> LSLCSLCSLCSLCU
4 2 0 1 3 2 -> LSLCSLSCSLCULSLSCSLSCLSLDCSCUSLCU
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid answer (in bytes) wins.
[Answer]
# Python 3, 84 bytes
```
lambda n,*s:"DLL"+"L".join(i*"SLSC"+"LSLSCDURLCULCULSC"for i in s[::-1])+n*"SR"+"UR"
```
Usage:
```
# Example: 4 2 0 1 3 2 -> LSLCSLSCSLCULSLSCSLSCLSLDCSCUSLCU
>>> f = lambda ...
>>> f(4, 2, 0, 1, 3, 2)
'DLLSLSCSLSCLSLSCDURLCULCULSCLSLSCSLSCSLSCLSLSCDURLCULCULSCLSLSCLSLSCDURLCULCULSCLLSLSCDURLCULCULSCLSLSCSLSCLSLSCDURLCULCULSCSRSRSRSRUR'
```
**Explanation:** To start off we duplicate the zero and wrap it in a list:
```
DL -> 3 2 1 0 (0)
```
This is our base. Now I will explain a general algorithm that turns `... 1 0 (x)` into `... 1 0 (i x)` for arbitrary integer `i`. I will use as an example `i = 2`, and we have some arbitrary list `(x)`. We start by wrapping our current list `(x)` into another list:
```
L -> 3 2 1 0 ((x))
```
Now we repeat the following sequence `i` times:
```
SLSC -> 3 2 1 (0 (x))
SLSC -> 3 2 (1 0 (x))
```
Now we're ready to insert the 2 into list `(x)`. This goes as follows:
```
LSLSC -> 3 (2 (1 0 (x)))
DU -> 3 (2 (1 0 (x))) 2 (1 0 (x))
RLCU -> 3 2 (1 0 (x)) 2
LCU -> 3 2 1 0 (x) 2
LSC -> 3 2 1 0 (2 x)
```
Note that we keep pushing new integers on the left. So the very first `(0)` we started with stays on the right.
After we have inserted every integer we need into the list we remove the rest of the stack by swapping and removing *n* time (`SR`). Finally we unpack our list and delete the first `0` we inserted to start our list (`UR`).
[Answer]
## CJam, 54 bytes
Just a translation from orlp's Python solution into CJam. There's nothing new here.
```
"DLL"q~("SR"*\W%{"SLSC"*"LSLSCDURLCULCULSC"+}%'L*\"UR"
```
Explanation:
```
"DLL" e# Push string
q~ e# Read input and evaluate
( e# Pop the first value
"SR" e# Push string
* e# Repeat string n times
\ e# Swap (bring s to front)
W% e# Reverse
{ e# For each:
"SLSC" e# Push string
* e# Repeat i times
"LSLSCDURLCULCULSC"+ e# Append string to end
}% e# End
'L* e# Join with 'L'
\ e# Swap (bring "SR"*n to front)
"UR" e# Push string
e# [Stack is implicitly output.]
```
] |
[Question]
[
Snakes look like this:
```
>>>v
@ ^ v
^ >>>^ v
^ v
^<<<<<<<<<
```
The snake can cross over itself as in this case:
```
@
^
>^>v
^<<
```
For a crossover to be valid, the characters on either side must be moving the same direction. The case of
```
@
>^v
^<
```
can be considered unclear and invalid.
The output is a string of `WASD` representing going from the head to the tail (`@`).
**Given a snake that doesn't backtrack and isn't ambiguous, can you write a program that will output the string of moves that the snake takes?**
This is code-golf, so shortest answer wins!
### Test cases:
(Note: The `@` can be replaced with any character not in `v^<>`)
**Input:**
```
>>>>v
v
v<< @
v ^
>>>>>^
```
**Output:** `ddddssaassdddddww`
---
**Input:**
```
@>>v
^ v
^ v
^<<<
```
**Output:** `dddsssaaawww`
---
**Input:**
```
>>>v
v @
v ^
>>>>v ^
>>>>^
```
**Output:** `dddsssddddsddddwww`
---
**Input:**
```
@<< v
^ v
v<^<<
v ^
>>^
```
**Output:** `ssaaaassddwwwwaa`
---
**Input:**
```
@v<v
^v^v
^v^<
^<
```
**Output:** `ssawwasssawww`
[Answer]
## Java, ~~626~~ ~~539~~ ~~536~~ 529 bytes
*-87 bytes by saving a few in a lot of places. Thanks goes to Mr Public for pointing some out.*
*-3 bytes because I can't manage to remove all the spaces first try (thanks mbomb007)*
*+8 bytes to fix for this case:*
```
@v<v
^v^v
^v^<
^<
```
*-15 bytes by front-loading variable declaration*
```
s->{String o="",t;String[]p=s.split("\n");int h=p.length,w=p[0].length(),y=0,x,b=0,a,n,m;char[][]d=new char[h][w];for(;y<h;y++)for(x=0;x<w;x++){d[y][x]=p[y].charAt(x);if(d[y][x]=='@')d[y][x]=' ';}for(;b<h;b++)for(a=0;a<w;a++){t="";x=a;y=b;n=0;m=0;while(!(y<0|y>h|x<0|x>w||d[y][x]==' ')){if(y+m>=0&y+m<h&x+n>=0&x+n<w&&d[y+m][x+n]==d[y-m][x-n])d[y][x]=d[y-m][x-n];n=m=0;switch(d[y][x]){case'^':t+="W";m--;break;case'<':t+="A";n--;break;case'v':t+="S";m++;break;case'>':t+="D";n++;}x+=n;y+=m;}o=t.length()>o.length()?t:o;}return o;}
```
Readable version:
```
static Function<String,String> parser = snake -> {
// declare all variables in one place to minimize declaration overhead
String output = "", path;
String[] split = snake.split("\n");
int h=split.length, w=split[0].length(), y=0, x, startY=0, startX, dx, dy;
char[][] board = new char[h][w];
// setup char[][] board
for (; y<h; y++)
for (x=0; x<w; x++) {
board[y][x]=split[y].charAt(x);
if(board[y][x]=='@')board[y][x]=' ';
}
// find the longest possible path
for (; startY<h; startY++)
for (startX=0; startX<w; startX++) {
path = "";
x=startX; y=startY; dx=0; dy=0;
while (!(y<0 | y>h | x<0 | x>w || board[y][x] == ' ')) {
if (y + dy >= 0 & y + dy < h & x + dx >= 0 & x + dx < w
&& board[y + dy][x + dx] == board[y - dy][x - dx]) {
board[y][x] = board[y - dy][x - dx];
} dx = dy = 0;
switch(board[y][x]) {
case '^':path+="W";dy--;break;
case '<':path+="A";dx--;break;
case 'v':path+="S";dy++;break;
case '>':path+="D";dx++;break;
}
x+=dx; y+=dy;
}
output = path.length()>output.length()?path:output;
}
return output;
};
```
Takes a String like `v @\n>>>^`.
Creates a path starting at each coordinate, then returns the longest one.
The lookahead required for the overlapping paths was the hardest part.
[Answer]
# Ruby, 217
```
->a{r=''
z=a.index ?@
a.tr!('<^>v',b='awds').scan(/\w/){c=0
e,n=[a[z,c+=1][?\n]?p: c,d=c*a[/.*
/].size,a[z-c,c][?\n]?p: -c,-d].zip(b.chars).reject{|i,k|!i||a[v=i+z]!=k||0>v}.max_by{|q|q&[a[z]]}until n
z+=e
r=n*c+r}
r}
```
This starts at the `@` and walks backwards, looking for neighbors that point to the current position (`z`). In order to choose the right way at 4-way intersections, it favors neighbors pointing in the same direction (`max_by{...}`). If no immediate neighbors are found, it assumes that there must have been a cross-over and reaches out one level at a time until it finds one (`until n` and `c+=1`). This process repeats for the number of body segments (not including the head) (`.scan(/\w/){...}`).
The test case I added to the puzzle kept tripping me up, so I went form 182 char to 218. Those extra characters were all making sure my horizontal moves didn't go into the next/prev lines. I wonder if I can deal with that in a better way.
## Ungolfed:
```
f=->a{
result=''
position=a.index ?@ # start at the @
a.tr!('<^>v',b='awds') # translate arrows to letters
a.scan(/\w/){ # for each letter found...
search_distance=0
until distance
search_distance+=1
neighbors = [
a[position,search_distance][?\n]?p: search_distance, # look right by search_distance unless there's a newline
width=search_distance*a[/.*\n/].size, # look down (+width)
a[position-search_distance,search_distance][?\n]?p: -search_distance, # look left unless there's a newline
-width # look up (-width)
]
distance,letter = neighbors.zip(b.chars).reject{ |distance, letter_to_find|
!distance || # eliminate nulls
a[new_position=distance+position]!=letter_to_find || # only look for the letter that "points" at me
0>new_position # and make sure we're not going into negative indices
}.max_by{ |q|
# if there are two valid neighbors, we're at a 4-way intersection
# this will make sure we prefer the neighbor who points in the same
# direction we're pointing in. E.g., when position is in the middle of
# the below, the non-rejected array includes both the top and left.
# v
# >>>
# v
# We want to prefer left.
q & [a[position]]
# ['>',x] & ['>'] == ['>']
# ['v',x] & ['>'] == []
# ['>'] > [], so we select '>'.
}
end
position+=distance
result=(letter*search_distance)+result # prepend result
}
result # if anyone has a better way of returning result, I'm all ears
}
```
] |
[Question]
[
The first programming language I was exposed to was [Sinclair BASIC](https://en.wikipedia.org/wiki/Sinclair_BASIC). Like many BASIC dialects, it requires all [source code lines to be numbered](https://softwareengineering.stackexchange.com/questions/309767/why-did-basic-use-line-numbers).
As a result, use of the `GO TO` command was idiomatic and jumps execution to the given line number (no labels).
Also there is a related `GO SUB` command which can be used as a rudimentary function call. Again, execution jumps to the given line number, but when a `RETURN` command is reached, execution jumps back to the next instruction after the `GO SUB`.
Similarly the `RUN` command will restart program execution at the given line.
Anyone who has spent any time in a line-numbered BASIC interpreter will have learned to use a numbering scheme with gaps in it. This is so that it is easier to insert new lines of code. However even then, you may still find yourself needing to insert new lines in between consecutively numbered lines.
---
Given a line-numbered BASIC listing as input, output the same program but renumbered such that the line numbers start at 10 and increment by steps of 10. The input listing may have `GO TO` or `GO SUB` commands, so the numbers associated with these must also be adjusted.
* `GO TO` and `GO SUB` commands are either on their own lines or at the end of `IF` `THEN` lines. Its safe to say `^(\d+) .*GO (TO|SUB) (\d+)$` is sufficient to match such lines. These commands in quotes should be ignored.
* `RUN` commands will always be on their own lines. In this case a line number is optional. If it is missing, then the interpreter simply starts at the top of the program.
* If a `GO TO`, `GO SUB` or `RUN` command references a non-existent line, then it will instead jump to the next defined line. Your entry needs to deal with this and ensure any such line references are fixed so they point to the correct line. Behaviour may be undefined if a line number after the end of the program is given in one of these commands.
* Line numbers will always be positive integers 1 to 9999 (as per the manual). This means that input programs will never have more than 999 lines.
* Input lines will always be numbered in numerically ascending order.
* For the purposes of this challenge, input listings will only contain printable ASCII. You don't need to worry about the ZX character set. Having said that, if your entry is actually written in ZX BASIC or appropriate z80 assembly/machine code (and there are [emulators](http://fms.komkon.org/Speccy/) out [there](http://www.zxspectrum4.net/emulator.php)), then you may choose for your input to be encoded in the [ZX character set](https://web.archive.org/web/20150308193250/http://www.worldofspectrum.org/ZXBasicManual/zxmanappa.html) instead.
* You may not use any renumber libraries or utilities that are specifically tailored for this purpose.
### Example Input:
```
1 REM "A rearranged guessing game"
2 INPUT A: CLS
3 INPUT "Guess the number ", B
10 IF A=B THEN PRINT "Correct": STOP
100 IF A<B THEN GO SUB 125
120 IF A>B THEN GO SUB 122
121 GO TO 3
125 PRINT "Try again"
126 RETURN
127 REM "An example of GO TO 7 and GO SUB 13 in quotes"
```
### Example Output:
```
10 REM "A rearranged guessing game"
20 INPUT A: CLS
30 INPUT "Guess the number ", B
40 IF A=B THEN PRINT "Correct": STOP
50 IF A<B THEN GO SUB 80
60 IF A>B THEN GO SUB 80
70 GO TO 30
80 PRINT "Try again"
90 RETURN
100 REM "An example of GO TO 7 and GO SUB 13 in quotes"
```
---
I wanted to link to a ZX BASIC manual. The best I could find seems to be <http://www.worldofspectrum.org/ZXBasicManual/index.html> but this seems to be a dead link. The wayback machine [has a copy though](https://web.archive.org/web/20150308193244/http://www.worldofspectrum.org/ZXBasicManual/index.html).
[Answer]
# JavaScript (ES6) 177
**Edit** Added the (costly) scan for the next valid line number
```
l=>l.split`
`.map((x,i)=>([,n,t]=x.match(/(\d+)(.*)/),l[n]=10*-~i,t),l=[]).map((x,i)=>10*-~i+x.replace(/(UN |GO TO |UB )(\d+)$/,(a,b,c)=>(l.some((v,i)=>i<c?0:a=b+v),a))).join`
`
```
**TEST**
```
f=l=>
l.split`\n`
.map((x,i)=>([,n,t]=x.match(/(\d+)(.*)/),l[n]=10*-~i,t),l=[])
.map((x,i)=>10*-~i+x.replace(/(UN |GO TO |UB )(\d+)$/,(a,b,c)=>(l.some((v,i)=>i<c?0:a=b+v),a)))
.join`\n`
//TEST
console.log=x=>O.textContent+=x+'\n'
test=`1 REM "A rearranged guessing game"
2 INPUT A: CLS
3 INPUT "Guess the number ", B
10 IF A=B THEN PRINT "Correct": STOP
100 IF A<B THEN GO SUB 125
120 IF A>B THEN GO SUB 122
121 GO TO 3
125 PRINT "Try again"
126 RETURN`
console.log(test+'\n\n'+f(test))
```
```
<pre id=O></pre>
```
[Answer]
# Perl 6, ~~147~~ ~~145~~ ~~144~~ 142 bytes
```
{my%a;.trans(/^^(\d+)/=>{%a{$0}=$+=10}).trans(/:s<!after \"\N*>(UN |GO TO |UB )(\d+)<!before \N*\">/=>{$0~%a{%a.keys».Num.grep(*>=$1).min}})}
```
This can probably be golfed down a bit more.
**Expanded**
```
my &f = -> $s {
my %line-map; # This will map the old line numbers to the new ones
$s.trans(/^^(\d+)/ # This .trans creates the line number map
=> { %line-map{$0} = $+=10 } # as well as replaces the actual line numbers
)\
# This .trans replaces all the line numbers for each GO TO, GO SUB, RUN
.trans(/:s<!after \"\N*>(UN |GO TO |UB )(\d+)<!before \N*\">/
=> {$0 ~ %line-map{%line-map.keys».Num.grep(*>=$1).min} }
)
}
```
[Answer]
# Visual Basic for Applications, 288 bytes
I couldn't resist giving a solution in a BASIC dialect. Probably works with Visual Basic 6/.NET or other modern variants with minor changes.
```
Sub n(t,a)
f=Chr(10)
u=Chr(0)
Open t For Input As 1
a=f &Input(LOF(1),1)&f
Close
j=10
For i=1 To 9999
q=f &j &u
g=" GO TO "
w=i &f
m=j &f
a=Replace(Replace(Replace(Replace(a,g &w,g &m),f &i &" ",q),"B "&w,"B "&m),"UN "&w,"UN "&m)
If InStr(1,a,q)Then j=j+10
Next
a=Replace(a,u," ")
End Sub
```
I used a lot of one-letter variables for conciseness. Also, I supressed all unnecessary whitespaces (VBE expands them automatically on import). Byte count is for final .BAS file, with CHR(10) as newline.
The subroutine, that can be invoked from VBE immediate window, opens a Sinclair BASIC program (first parameter is the path to an ASCII file - with CHR(10) as newline - containing the program), renumber lines and write results to a Variant variable (second parameter).
The idea is to iterate on all possible source line numbers, ascending order, and for each one, replace at once all matching line numbers as well as `GO TO`, `GO SUB` and `RUN` references with the next available target line number. Using this approach we do not need any kind of translation table. The target line number is incremented each time a match in source line number is found, so "wrong" line references are adjusted automatically to the next valid number. Newline characters are used as markers of start- and end-of-line, and a CHR(0) - never used in the program as it is not printable - is used as a temporary marker, to avoid renumbering the same line multiple times.
Some remarks:
* For conciseness, we use the smaller possible string for a match with the jumping statements. Using the end-of-line on our search strings we do not run into the risk of including quoted occcurrences or user functions (that always use parenthesis in Sinclair). `GO TO` requires a larger string because of the `FOR ... TO` construct (e.g. compare `50 FOR X=AGO TO 100` and `50 GO TO 100`)
* The code does not support statements in the form `GO TO200` (without whitespace), although the ZX manual implies that it is valid code on several examples (It would cost a dozen more bytes to deal with it).
* The code adds a newline at the beginning and another at the end of the program. I could clean this up in the end (a dozen more bytes) but figure that the ZX would probably ignore blank lines.
Below, a more readable version:
```
Sub Renumber(ByVal ProgramPath As String, ByRef Program As Variant)
Open ProgramPath For Input As #1
Program = Chr(10) & Input(LOF(1), 1) & Chr(10)
Close
NewNumber = 10
For OldNumber = 1 To 9999
Program = Replace(Program, " GO TO" & OldNumber & Chr(10), " GO TO" & NewNumber & Chr(10)) 'self-explaining
Program = Replace(Program, Chr(10) & OldNumber & " ", Chr(10) & NewNumber & Chr(0)) 'matches line number (and replaces whistespace with Chr(0) to avoid re-replacing
Program = Replace(Program, "B " & OldNumber & Chr(10), "B " & NewNumber & Chr(10)) 'matches GO SUB
Program = Replace(Program, "UN " & OldNumber & Chr(10), "UN " & NewNumber & Chr(10)) 'matches RUN
If InStr(1, Program, Chr(10) & NewNumber & Chr(0)) Then NewNumber = NewNumber + 10 'if there is such a line, increment NewNumber
Next
Program = Replace(Program, Chr(0), " ") 'replace back Chr(0) with whitespace
End Sub
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip) `-rn`, 63 bytes
```
Ygn:#{_<aFIy}*t+tgR`(RUN|GO (SUB|TO)) (\d+)$`{b.s.(nd)}R`^\d+`n
```
[Try it online!](https://tio.run/##XY9BT4NAFITv/IrJ6gGsNgKpTUg1gaatJArNFg4mRtnKupLIUhdIbNr@dtym6MHbvDffe5nZFJuuexLSO9u9Ttg83B4umkEjaGbSNNovYpirNNgnsWXBfM4H1nm2Ww/roSlz60CzF73KZNfZoLNHEB@KM6WYFDyHaHldF1JAsJITw0EYLdMEvofpw8pw@5EsjhiaDw7ZlmuuQC4RGPY1wjn82wDJ/SzCkoaRZqeVUvytIR50ODiaOmGTHtNxdVrYzsiwnZN199/SV459HJMYrtaj3@eJ2oIJVkiitze6UJLSSMtx302Cf7Ny88lRvff3YzCZ/712UUh8tVXDa9JdKfkD "Pip – Try It Online")
## Explanation
### Setup
The `-r` flag reads all of stdin and stores it as a list of lines in the local variable `g`. The global variable `t` is preinitialized to 10, and the global variable `s` is preinitialized to `" "`.
```
Yg
```
Yanks the list of lines `g` into the global variable `y`, so that it's available inside the function we're about to define.
### Line number translation function
We construct a function that maps from any line number in the original numbering scheme (including a non-existent one) to the corresponding line number in the new numbering scheme.
Suppose we have these lines:
```
1 INPUT A
4 PRINT A
9 IF A=1 THEN GO TO 3
```
We want to map 1 to 10, 2-4 to 20, and 5-9 to 30. If we have a list of the original line numbers (`[1; 4; 9]`), we can use a filter operation to find out how many of these numbers are less than the line number we're trying to convert. Multiply that result by 10 and add 10, and we have the desired answer.
For example, when converting 9, there are two line numbers (1 and 4) less than 9. 2\*10+10 gives 30. When converting 3, there is one line number (1) less than 3. 1\*10+10 gives 20.
Here's the code (slightly modified to be easier to read):
```
n:{#(_<aFIy)*t+t}
{ } Lambda function with parameter a:
FIy Filter y (the list of program lines) for
_<a lines that are numerically less than a
(In a numeric context, only the first run of digits on the line is considered)
#( ) Number of items in the filtered list
*t+t Times 10, plus 10
n: Assign that function to global variable n
```
### First replacement: `GO TO`, `GO SUB`, and `RUN`
The rest of the program is a single expression that takes `g` and does a couple of regex replacements (which vectorize, applying to each line in `g`).
Here's the first replacement:
```
g R `(RUN|GO (SUB|TO)) (\d+)$` {b.s.(nd)}
```
The regex matches any of `RUN`, `GO SUB` and `GO TO`, followed by a number, followed by end of line. This ensures it doesn't match inside strings, nor does it match `RUN` without a line number.
The order of the capturing groups is important. The first group captures the command (one of `RUN`, `GO SUB`, or `GO TO`). The second group, if used, captures either `SUB` or `TO`. We don't need to capture this part, but a non-capturing group would require extra bytes. Then the third group captures the line number.
We use a callback function for the replacement. With callback functions in Pip, the whole match is the first argument `a`, and the capture groups in order are the subsequent arguments `b`, `c`, `d`, and `e`. So we have the command in the first group, which goes in `b`, and the line number in the third group, which goes in `d`. The only change we need to make is to pass the line number through our conversion function, which is called Lisp-style: `(nd)`. Then we concatenate that together with `b` and a space and return it.
### Second replacement: line numbers
All that's left to convert is the line numbers at the beginnings of lines.
```
(...) R `^\d+` n
```
The regex matches a run of digits at the beginning of a line. Again we use a callback function; this time, the conversion function `n` itself is sufficient, since the whole match (first argument, `a`) is the number we want converted.
Since this is the last expression in the program, Pip autoprints the result. The `-n` flag separates the result list with newlines.
] |
[Question]
[
Write a program or function that takes in a nonempty list of [mathematical inequalities](https://en.wikipedia.org/wiki/Inequality_(mathematics)) that use the less than operator (`<`). Each line in the list will have the form
```
[variable] < [variable]
```
where a `[variable]` may be any nonempty string of lowercase a-z characters. As in normal math and programming, variables with the same name are identical.
If a **positive integer** can be assigned to each variable such that **all** the inequalities are satisfied, then print or return a list of the variables with such an assignment. Each line in this list should have the form
```
[variable] = [positive integer]
```
and all variables must occur exactly once in any order.
Note that there may be many possible positive integer solutions to the set of inequalities. Any one of them is valid output.
If there are no solutions to the inequalities, then either don't output anything or output a [falsy value](http://meta.codegolf.stackexchange.com/a/2194/26997) (it's up to you).
**The shortest code in bytes wins.**
## Examples
If the input were
```
mouse < cat
mouse < dog
```
then all of these would be valid outputs:
```
mouse = 1
cat = 2
dog = 2
```
```
mouse = 37
cat = 194
dog = 204
```
```
mouse = 2
cat = 2000000004
dog = 3
```
If the input were
```
rickon < bran
bran < arya
arya < sansa
sansa < robb
robb < rickon
```
then no assignment is possible because it boils down to `rickon < rickon`, so there either is no output or a falsy output.
**More examples with solutions:**
```
x < y
x = 90
y = 91
---
p < q
p < q
p = 1
q = 2
---
q < p
q < p
p = 2
q = 1
---
abcdefghijklmnopqrstuvwxyz < abcdefghijklmnopqrstuvwxyzz
abcdefghijklmnopqrstuvwxyz = 123456789
abcdefghijklmnopqrstuvwxyzz = 1234567890
---
pot < spot
pot < spot
pot < spots
pot = 5
spot = 7
spots = 6
---
d < a
d < b
d < c
d < e
d = 1
a = 4
b = 4
c = 5
e = 4
---
aa < aaaaa
a < aa
aaa < aaaa
aa < aaaa
a < aaa
aaaa < aaaaa
aaa < aaaaa
a < aaaaa
aaaa = 4
aa = 2
aaaaa = 5
a = 1
aaa = 3
---
frog < toad
frog < toaster
toad < llama
llama < hippo
raccoon < science
science < toast
toaster < toad
tuna < salmon
hippo < science
toasted < toast
raccoon = 1
frog = 2
toaster = 3
toasted = 4
toad = 5
llama = 6
hippo = 7
science = 8
toast = 9
tuna = 10
salmon = 11
```
**More examples with no solutions:** (separated by empty lines)
```
z < z
ps < ps
ps < ps
q < p
p < q
p < q
q < p
a < b
b < c
c < a
d < a
d < b
d < c
d < d
abcdefghijklmnopqrstuvwxyz < abcdefghijklmnopqrstuvwxyz
bolero < minuet
minuet < bolero
aa < aaaaa
a < aa
aaa < aaaa
aa < aaaa
aaaaa < aaaa
a < aaa
aaaa < aaaaa
aaa < aaaaa
a < aaaaa
g < c
a < g
b < a
c < a
g < b
a < g
b < a
c < a
g < b
a < g
b < a
c < b
g < c
a < g
b < a
c < b
geobits < geoborts
geobrits < geoborts
geology < geobits
geoborts < geology
```
[Answer]
# Pyth, 39 bytes
```
V>1f.A<MxMLTN.pS{s=Nm%2cd).zVNjd[H\==hZ
```
Try it online: [Demonstration](http://pyth.herokuapp.com/?input=mouse%20%3C%20cat%0Amouse%20%3C%20dog&code=V%3E1f.A%3CMxMLTN.pS%7Bs%3DNm%252cd%29.zVNjd%5BH%5C%3D%3DhZ)
Brute-forces through all possible permutations (and interpret them as sortings), check if they match the inequalities, and assign them the values `1, 2, ...., n`.
### Explanation
```
f.A<MxMLTN.pS{s=Nm%2cd).z
m .z map each input line d to:
cd) split d by spaces
%2 and remove the second element
=N save this list of pairs to N
s combine these pairs to a big list of variable names
{ set (remove duplicates)
.pS generate all permutations
f filter for permutations T, which satisfy:
xMLTN replace each variable in N by their index in T
.A<M check if each pair is ascending
V>1...VNjd[H\==hZ implicit: Z = 0
>1 remove all but the last filtered permutation (if any)
V for each permutation N in ^ (runs zero times or once):
VN for each variable H in N:
[ generate a list containing:
H H
\= "="
=hZ Z incremented by 1 (and update Z)
jd join this list by spaces and print
```
[Answer]
## CJam (53 52 49 bytes)
```
qS-N/'<f/:A:|e!{A{1$1$&=!},!*},:ee{()" = "\N}f%1<
```
[Online demo](http://cjam.aditsu.net/#code=qS-N%2F'%3Cf%2F%3AA%3A%7Ce!%7BA%7B1%241%24%26%3D!%7D%2C!*%7D%2C%3Aee%7B()%22%20%3D%20%22%5CN%7Df%251%3C&input=aa%20%3C%20aaaaa%0Aa%20%3C%20aa%0Aaaa%20%3C%20aaaa%0Aaa%20%3C%20aaaa%0Aa%20%3C%20aaa%0Aaaaa%20%3C%20aaaaa%0Aaaa%20%3C%20aaaaa%0Aa%20%3C%20aaaaa)
This brute-forces all permutations of the distinct tokens, filtering for those assignments of the numbers `0` to `n-1` which obey all of the constraints, and then formats them, incrementing the numbers, and presents the first one. This is certain to find a solution if there is one, because it's essentially a topological sort.
Thanks to [Reto Koradi](https://codegolf.stackexchange.com/users/32852/reto-koradi) for 3 chars and [Martin Büttner](https://codegolf.stackexchange.com/users/8478/martin-b%c3%bcttner) for 1.
[Answer]
# Mathematica, 83 bytes
```
Quiet@Check[Equal@@@FindInstance[Join[#,#>0&/@(v=Sequence@@@#)],v,Integers][[1]],]&
```
Takes input as a list of inequalities. Either outputs a list of assignments or `Null` if it is impossible.
] |
[Question]
[
### Preamble
In Stack Exchange markdown, we use \*\* to bold out text. For example, this markdown:
```
The **quick brown fox jumps over the lazy** dog.
```
Renders as:
>
> The **quick brown fox jumps over the lazy** dog.
>
>
>
Of course, we use \*\* to close boldness as well. So less of the answer will be bold. For example:
```
The **quick** brown fox jumps over the **lazy** dog.
```
Renders as:
>
> The **quick** brown fox jumps over the **lazy** dog.
>
>
>
However, if the boldness is not closed, it renders as **not bold**:
```
The **quick brown fox jumps over the lazy dog.
```
Renders as:
>
> The \*\*quick brown fox jumps over the lazy dog.
>
>
>
If the text has a single backslash `\`, the boldness does not take effect, either:
```
The \**quick brown fox jumps over the lazy dog.**
```
Renders as:
>
> The \**quick brown fox jumps over the lazy dog.*\*
>
>
>
Trailing white space results in unbolded text (note, the white space after brown is a single tab):
```
The** quick** brown fox jumps over the lazy dog.**
```
Renders as:
>
> The\*\* quick\*\* brown fox jumps over the lazy dog.\*\*
>
>
>
We can also use \_\_ for bold, too, but note that only one can be active at a time. Here's a more complicated example:
```
The __quick**__ brown **fox__ jumps** over__ the__ lazy **dog.
```
Renders as:
>
> The **quick\*\*** brown **fox\_\_ jumps** over\_\_ the\_\_ lazy \*\*dog.
>
>
>
### The question:
Write a program or function that, given ASCII text either as an argument or on STDIN, where the only special characters are `**`, `__`, `\` (for escaping) and trailing whitespace, **determines how many bold characters there are.** This value should be printed to STDOUT or returned from your function. You do not need to support very long strings; String length is guaranteed to be no more than \$30{,}000\$, which is the limit for a Stack Exchange post.
### Fine print:
* Can I throw an exception / other error for one case, and return normally for the other?
+ No. It must be either a clear, unambiguous, non errored return value for both cases. STDERR output will be ignored.
* Are spaces in between words considered bold?
+ Yes. `**quick brown**` has 11 bold characters in it.
* Should the `\` in `\**`, if bold, be counted?
+ No. It renders as \*\*, so if it should be bolded it would only be 2 characters.
* Be completely clear: what do you mean by how many characters?
+ Total characters that would render bold. This means that `**` is *not rendered* if it transforms text, but it is rendered if it does not.
+ Note that it's possible to make `**` be bolded in several ways, e.g. `**\****` -> **\***\*.
+ Don't consider the possibility that some text could be converted to italics. The *only* markdown rule to consider is **\** = bold*.\*\*
* On Stack Exchange, HTML Bold works too. i.e. <b></b>
+ Yes, I am aware. Don't consider this case, this is normal text.
* What about HTML entites? e.g. `<` -> `<`
+ These also should be considered as normal text, there is no HTML entity conversion.
* I've thought of an example you didn't cover above!
+ The rules function *exactly* as if the text were posted on Stack Exchange, **in an answer** (not a comment), except that *code blocks are not considered special characters*. Both the four space type and the backtick type. If you are not sure about how text should be rendered, just throw it into an answer box somewhere as a test, those are the rules you should follow.
### Examples:
Input:
```
The **quick brown fox jumps over the lazy** dog.
```
Output:
```
35
```
Input:
```
The **quick brown fox jumps over the lazy dog.
```
Output:
```
0
```
Input:
```
The __quick**__ brown **fox__ jumps** over__ the__ lazy **dog.
```
Output:
```
18
```
Input:
```
The __quick\____ brown fox **jumps over\** the** lazy \**dog.
```
Output:
```
23
```
Input:
```
The****quick brown fox****jumps over **the****lazy** dog.
```
Output:
```
11
```
[Standard Loopholes](http://meta.codegolf.stackexchange.com/q/1061) are banned.
[Answer]
# [rs](https://github.com/kirbyfan64/rs), 107 bytes
```
\t/
(?<!\\)((\*|_){2})((?=\S)(?!\2)(\\\2|.)*?)?(?<=\S)\1/(\n)^^((^^\3))\3
\\(\*|_)/\t
[^\t\n]/
\n/_
\t_?/
(_*)/(^^\1)
```
[Live demo and test cases.](http://kirbyfan64.github.io/rs/index.html?script=%5Ct%2F%C2%A0%0A%28%3F%3C!%5C%5C%29%28%28%5C*%7C_%29%7B2%7D%29%28%28%3F%3D%5CS%29%28%3F!%5C2%29%28%5C%5C%5C2%7C.%29*%3F%29%3F%28%3F%3C%3D%5CS%29%5C1%2F%28%5Cn%29%5E%5E%28%28%5E%5E%5C3%29%29%5C3%0A%5C%5C%28%5C*%7C_%29%2F%5Ct%0A%5B%5E%5Ct%5Cn%5D%2F%0A%5Cn%2F_%0A%5Ct_%3F%2F%0A%28_*%29%2F%28%5E%5E%5C1%29&input=The%20**quick%20brown%20fox%20jumps%20over%20the%20lazy**%20dog.%0AThe%20**quick%20brown%20fox%20jumps%20over%20the%20lazy%20dog.%0AThe%20__quick**__%20brown%20**fox__%20jumps**%20over__%20the__%20lazy%20**dog.%0AThe%20__quick%5C____%20brown%20fox%20**jumps%20over%5C**%20the**%20lazy%20%5C**dog.%0AThe****quick%20brown%20fox****jumps%20over%20the%20lazy%20dog.)
This is a pretty crazy...thing.
**The newest test case does not work yet. WIP...**
## Explanation
```
\t/
```
Replace tabs with spaces. They have the same character count, and tabs are used later on as a special character.
```
(?<!\\)((\*|_){2})((?=\S)(?!\2)(\\\2|.)*?)?(?<=\S)\1/(\n)^^((^^\3))\3
```
Replace any text of length `N` that should be bolded
with `N` newlines followed by the original text.
```
\\(\*|_)/\t
```
Replace any occurrences of a delimiter immediately preceded by a slash with a tab. This is to make sure that entries like `**a\***` have a character count of 2 instead of 3.
```
[^\t\n]/
```
Remove any character that's not a tab or newline.
```
\n/_
```
Replace all the newlines with underscores.
```
\t_?/
```
Remove any tabs (which represent escaped delimiters), along with any underscores that may follow them. This is related to the above issue of character counts with escaped ending delimiters.
```
(_*)/(^^\1)
```
Replace the underscore sequence with its length. This is the character count.
[Answer]
# Python: 133 characters
```
import re
f=lambda s:sum(len(x[0])-4for x in re.findall(r'(([_*])\2\S.*?\2\2+)',re.sub(r'([_*])\1\1\1','xxxx',re.sub(r'\\.','x',s))))
```
This should work identically in both Python 2 and 3. The function `f` returns the number of bold characters that will be in the string it is passed when formatted by Stack Overflow's markdown system.
I think I get most of the corner cases right (including all the ones mentioned in comments so far), but its still not entirely perfect. I don't understand why `x***x**` doesn't render the `*x` in bold (like `***x**` does), so my code will get at least a few inputs wrong.
The code has four main steps. The first does a regex replacement of any backslash followed by any character with an 'x' character. The second step replaces any sequence of four asterixes or underscores with four 'x' characters. The third step uses a regex `findall` to find all the blocks that will be italicized. The final step is a generator expression inside a `sum` call, that adds up the lengths of those blocks, subtracting 4 characters from each, since we don't want to include the delimiters in our count.
Here's some test output:
```
>>> f('The **quick brown fox jumps over the lazy** dog.')
35
>>> f('The **quick brown fox jumps over the lazy dog.')
0
>>> f('The \**quick brown fox jumps over the lazy dog.**')
0
>>> f('The** quick** brown fox jumps over the lazy dog.**')
0
>>> f('The __quick\____ brown fox **jumps over\** the** lazy \**dog.')
23
>>> f('The****quick brown fox****jumps over **the****lazy** dog.')
11
>>> f('\***a**')
1
>>> f('x***x**') # this one doesn't match the Stack Overflow input box
2
```
[Answer]
# JavaScript ES6, 91 bytes
```
s=>(o=0,s.replace(/\\(.)\1/g,'..').replace(/(\*\*|__)(?=\S)(.*?\S)\1/g,l=>o+=l.length-4),o)
```
Deals with all escapes before hand, then uses a regular expression. Lots of golfing potential.
## Explanation
```
s=>( // Function with argument s
o=0, // Set var "o" to 0
s.replace( // Replace...
/\\(.)\1/g, // Matches \ followed by two the same characters. g means "global"
".." // Replace with two arbitrary characters
).replace( // Replace again...
/(\*\*|__) // Match ** or __, store in "group 1"
(?=\S) // Make sure next character isn't whitespace
(.*?\S)\1 // Match all characters until "group 1".
// Make sure last character isn't whitespace
/g, l=> // Take the match...
o+= // Increase o by...
l.length // the length of the match
- 4 // minus 4 to account for ** and __
), o) // Return o
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 115 bytes
```
'•Ë™I'\„\\.:'"„\".:’R޽™«.©Ì~r/’D’ÿ(\*\*|__)(?=\S)(.*?\S)\1/,(ÿ\\(.)\1/,"ÿ",".."),fn a->ÿ.àÉ"ǝ",(ÄÁ_„¬ a)-4„–’.E'ǝ¢
```
[Try it online!](https://tio.run/##yy9OTMpM/f9f/VHDosPdj1oWearHPGqYFxOjZ6WuBGIo6Vk9apgZdHTvob1A2UOr9Q6tPNxTV6QPFHQB4sP7NWK0YrRq4uM1NextY4I1NfS07IFUjKG@jsbh/TExGnpgttLh/Uo6Snp6Spo6aXkKibp2h/frHV5wuFPp@FwloMKWw43xQNsOrVFI1NQ1AbIeNUwGmq7nqn587qFF//@HZKQqxMcXlmYmZ2tpxccrJBXll@cpaGml5VcAeVmluQXFWloK@WWpRUBuSUYqkMxJrKoEqkjJT9cDAA) This code abuses the fact that input is guaranteed to be ASCII, as it replaces bold characters with `ǝ`, then counts the number of `ǝ`s in the output. If there were any `ǝ`s in the input, they would get counted as bold characters, but it is unnecessary to handle non-ASCII characters according to this rule:
>
> Write a program or function that, **given ASCII text** either as an argument or on STDIN, where the only special characters are `**`, `__`, `\` (for escaping) and trailing whitespace, determines how many bold characters there are.
>
>
>
] |
[Question]
[
We have 40 sticks of same widths but different heights. How many arrangements are there possible to put them next to each other so that when we look from right we see 10 sticks and when we look from left we again see exactly 10 sticks?
For example such an ordering is:
Black sticks are hidden, red sticks are the ones you can see when you look from left, the blue sticks are the ones you can see when you look from right and purple one(i.e. the longest one) is the one that can be see seen from both sides.
As test cases:
* If we had 3 sticks number of orderings to see 2 from left and 2 from right is 2
* If we had 5 sticks number of orderings to see 3 from left and 3 from right is 6
* If we had 10 sticks number of orderings to see 4 from left and 4 from right is 90720
[Answer]
# PARI/GP, 80
```
f(n,v)=abs(sum(k=1,n-1,binomial(n-1,k)*stirling(k,v-1,1)*stirling(n-k-1,v-1,1)))
```
The number of visible sticks is also called [Skyscraper Numbers](https://cs.uwaterloo.ca/journals/JIS/VOL16/Khovanova/khova6.pdf), after the pencil/grid game. This code is based on (only slightly altered) the formula from [OEIS A218531](https://oeis.org/A218531). I don't know much PARI, but I really don't think there's much to golf out here.
Test cases are all [shown at ideone.com](http://ideone.com/a0kj7g). The result for `f(40,10)` is:
```
192999500979320621703647808413866514749680
```
[Answer]
# Python 3, 259 bytes
Not very happy with this.
```
import itertools as i
x=input().split()
y,k=x
y=int(y)
c=0
x=list(i.permutations(list(range(1,y+1))))
for s in x:
t=d=0;l=s[::-1]
for i in range(y):
if max(s[:i+1])==s[i]:t+=1
for i in range(y):
if max(l[:i+1])==l[i]:d+=1
if t==d==int(k):c+=1
print(c)
```
Example input and output:
```
10 4
90720
```
It generates all the possible combinations of the provided range, and then loops through them, checking each number in them to see if it equal to the maximum of the previous numbers. It then does the same backwards, and if the count forwards (t) = the count backwards (d) = the given view number (k) it's a valid one. It adds this to a counter (c) and prints that at the end.
[Answer]
## R, 104
```
function(N,K)sum(sapply(combinat::permn(N),function(x)(z=function(i)sum(cummax(i)==i)==K)(x)&z(rev(x))))
```
De-golfed a little:
```
function(N,K) {
all_perm <- combinat::permn(N)
can_see_K_from_left <- function(i)sum(cummax(i) == i) == K
can_see_K_from_both <- function(x)can_see_K_from_left(x) &
can_see_K_from_left(rev(x))
return(sum(sapply(all_perm, can_see_K_from_both)))
}
```
[Answer]
# Pyth - 38 36 bytes
Basically a port of the R answer. Pretty slow, can't even complete `10, 4` online.
```
AGHQLlfqhS<bhT@bTUGlf!-,yTy_TH.pr1hG
```
The only things Pyth doesn't have are cummax and the `==` over vectors, but those only took a few bytes to implement.
Explanation and further golfing coming soon.
[Try it here online](http://pyth.herokuapp.com/?code=AGHQLlfqhS%3CbhT%40bTUGlf!-%2CyTy_TH.pr1hG&input=5%2C+3&debug=0).
] |
[Question]
[
Surprisingly, we haven't had any challenges on graph colouring yet!
Given an undirected graph, we can give each vertex a colour such that no two adjacent vertices share the same colour. The smallest number *χ* of distinct colours necessary to achieve this is called the *chromatic number* of the graph.
For example, the following shows a valid colouring using the minimum number of colours:

(Found on Wikipedia)
So this graph's chromatic number is *χ = 3*.
Write a program or function which, given a number of vertices *N < 16* (which are numbered from *1* to *N*) and a list of edges, determines a graph's chromatic number.
You may receive the input and produce the output in any convenient format, as long as the input is not pre-processed. That is, you can use a string or an array, add convenient delimiters to the string or use a nested array, but whatever you do, the flattened structure should contain the same numbers as the examples below (in the same order).
You may not use built-in graph-theory related functions (like Mathematica's `ChromaticNumber`).
You may assume that the graph has no loop (an edge connecting a vertex with itself) as that would make the graph uncolourable.
This is code golf, the shortest answer (in bytes) wins.
## Examples
Your program must at least solve all of these in a reasonable amount of time. (It must solve all inputs correctly, but it may take longer for larger inputs.)
To shorten the post, in the following examples, I present the edges in a single comma-separated list. You may instead use line breaks or expect the input in some convenient array format, if you prefer.
**Triangle** (χ = 3)
```
3
1 2, 2 3, 1 3
```
**"Ring" of 6 vertices** (χ = 2)
```
6
1 2, 2 3, 3 4, 4 5, 5 6, 6 1
```
**"Ring" of 5 vertices** (χ = 3)
```
5
1 2, 2 3, 3 4, 4 5, 5 1
```
**Example picture above** (χ = 3)
```
6
1 2, 2 3, 3 4, 4 5, 5 6, 6 1, 1 3, 2 4, 3 5, 4 6, 5 1, 6 2
```
**Generalisation of the above for 7 vertices** (χ = 4)
```
7
1 2, 2 3, 3 4, 4 5, 5 6, 6 7, 7 1, 1 3, 2 4, 3 5, 4 6, 5 7, 6 1, 7 2
```
[**Petersen graph**](http://en.wikipedia.org/wiki/Petersen_graph) (χ = 3)
```
10
1 2, 2 3, 3 4, 4 5, 5 1, 1 6, 2 7, 3 8, 4 9, 5 10, 6 8, 7 9, 8 10, 9 6, 10 7
```
**Complete graph of 5 vertices, plus disconnected vertex** (χ = 5)
```
6
1 2, 1 3, 1 4, 1 5, 2 3, 2 4, 2 5, 3 4, 3 5, 4 5
```
**Complete graph of 8 vertices** (χ = 8)
```
8
1 2, 1 3, 1 4, 1 5, 1 6, 1 7, 1 8, 2 3, 2 4, 2 5, 2 6, 2 7, 2 8, 3 4, 3 5, 3 6, 3 7, 3 8, 4 5, 4 6, 4 7, 4 8, 5 6, 5 7, 5 8, 6 7, 6 8, 7 8
```
**Triangular lattice with 15 vertices** (χ = 3)
```
15
1 2, 1 3, 2 3, 2 4, 2 5, 3 5, 3 6, 4 5, 5 6, 4 7, 4 8, 5 8, 5 9, 6 9, 6 10, 7 8, 8 9, 9 10, 7 11, 7 12, 8 12, 8 13, 9 13, 9 14, 10 14, 10 15, 11 12, 12 13, 13 14, 14 15
```
[Answer]
# Python 2.7 - ~~122~~ ~~109~~ ~~111~~ ~~109~~ ~~108~~ 103
```
f=lambda n,e,m=1:any(all(t*m//m**a%m!=t*m//m**b%m for(a,b)in e)for t in range(m**n))and m or f(n,e,m+1)
```
Usage:
```
print f(5, [(1, 2), (2, 3), (3, 4), (4, 5), (5, 1)])
```
Brute force by increasing the chromatic number (m) and check all possible colorings. One coloring can be described as a number in base m. So the possible colorings are 0, 1, ..., m^n-1.
edit: The complete graph of 8 vertices takes quite long. But my laptop solves it in about 10 minutes. The other test cases take only a few seconds.
---
edit 2: Read that preprocessing is allowed, so I let the index of the vertices start with 0: shortens t\*m//m\*\*x%m to t//m\*\*a%m (-2). Dissolve lambda and put m into function params (-11)
---
edit 3: preprocessing is **not** allowed -> back to t\*m (+4), simplified // to / (-2).
---
edit 4: remove square brackets in any (-2), thanks xnor.
---
edit 5: instead of taking modulo m twice, simply subtract them and afterwards use modulo (-1). This is also quite a performance improvement. All testcases together take about 25 seconds on my laptop.
---
edit 6: recursive call instead of while 1: and m+=1 (-5). Thanks again, xnor.
[Answer]
# Java - ~~241~~ 218
```
int k,j,c;int f(int n,int[]e){for(k=1;k<=n;k++)for(long p=0;p<x(n);p++){for(j=0,c=0;j<e.length;c=p%x(e[j])/x(e[j]-1)==p%x(e[j+1])/x(e[j+1]-1)?1:c,j+=2);if(c<1)return k;}return 0;}int x(int a){return(int)Math.pow(k,a);}
```
The most obvious way to do this given the constraints is brute force. Just step through each chromatic number `k`, and assign each color to each vertex. If no neighbors are the same color, you have your number. If not, move along.
This takes longest for the test case for `χ = 8` (complete graphs suck here), but it's still under 15 seconds (ok, about 100s with latest edit).
Input is the number of vertices `n`, and an array of edge vertices `e[]` given in the same order as the OPs comma separated values.
With line breaks:
```
int k,j,c;
int f(int n,int[]e){
for(k=1;k<=n;k++)
for(long p=0;p<x(n);p++){
for(j=0,c=0;
j<e.length;
c=p%x(e[j])/x(e[j]-1)==p%x(e[j+1])/x(e[j+1]-1)?1:c,
j+=2);
if(c<1)return k;
}
return 0;
}
int x(int a){return(int)Math.pow(k,a);}
```
Oh, and this assumes the input is some sort of colorable graph. If an edge loops from v1 to v1, or there are no vertices, it can't be colored and will output 0. It will still work for graphs with no edges `χ=1`, etc.
[Answer]
# Python 3 - 162
Uses the same brute-force approach, but uses the itertools library for hopefully faster combination generation. Solves the complete 8-graph in < 1 min on my fairly ordinary machine.
```
import itertools as I
def c(n,v):
for i in range(1,n+1):
for p in I.product(range(i),repeat=n):
if(0==len([x for x in v if(p[x[0]]==p[x[1]])])):return i
```
Example usage for the complete 8-graph case:
```
print(c(8,[x for x in I.combinations(range(8), 2)]))
```
[Answer]
# Haskell, 163 bytes
```
p x=f(length x)(transpose x)1
f a[b,c]d|or$map(\x->and$g x(h b)(h c))(sequence$replicate a[1..d])=d|0<1=f a b c(d+1)
g a=zipWith(\x y->a!!x/=a!!y)
h=map(flip(-)1)
```
Usage would be like this:
```
p [[1, 2],[2, 3],[3, 1]]
```
Basic brute force approach. Check all the possible coloring combinations if they are valid. Not much else to say here except that I am happy to hear any tips for shortening this even further ;)
] |
[Question]
[
I hate code bloat!
So I have decided to replace my Windows 7 system by a golfed version. However, I know that it is not easy, so let's build a prototype first. It will take a list of windows from the user and show them using a pseudo-graphic display on the standard output.
For example: user input:
```
0,0,15,10
15,10,20,15
10,13,15,15
9,1,16,3
17,5,20,7
11,2,17,4
15,4,19,6
13,3,18,5
```
The Code Golf® Window Manager™ outputs:
```
┌──────────────┐
│::::::::┌─────┴┐
│::::::::│:┌────┴┐
│::::::::└─┤:┌───┴┐
│::::::::::└─┤::::├┐
│::::::::::::└─┬──┘├┐
│::::::::::::::├─┬─┘│
│::::::::::::::│ └──┘
│::::::::::::::│
│::::::::::::::│
└──────────────┼────┐
│::::│
│::::│
┌────┤::::│
│::::│::::│
└────┴────┘
```
Input:
* Taken from standard input (or, if your system has no `stdin`, any method that can provide several lines of input)
* Each line contains 4 numbers, delimited by commas - coordinates of a window
* First two numbers: upper-left corner; last two numbers: lower-right corner
* Using `x,y` notation
Output:
* Write it to standard output (or, if your system has no `stdout`, anything that displays monospaced text)
* Use single box-drawing characters from [Code Page 437](http://en.wikipedia.org/wiki/Box-drawing_character) for drawing window boundaries
* Windows specified later in input obscure those specified earlier
* Fill the windows with the colon character: `:`
* Leading and trailing spaces are OK, as long as they don't break alignment of the windows
Notes:
* Maximum resolution I want to support: 76 (horizontal) by 57 (vertical)
* No need to support bad input
* Maximum number of windows: 255 (if you need a limit)
* My Windows 7 `cmd` shell displays codepage 437 characters by default; if anyone has a way to do that on linux (using `xterm` or whatever), please describe it here
For reference, the character codes are:
```
┌da ─c4 ┬c2 ┐bf
│b3 :3a │b3 │b3
├c3 ─c4 ┼c5 ┤b4
└c0 ─c4 ┴c1 ┘d9
```
Total: 12 different characters.
[Answer]
## JavaScript ES6 (FF ≥ 31.0), 404 chars
```
w=s=>{a=[];for(i=0;i<57;)a[i++]=Array(76).fill(0);s.split('\n').map(e=>{r=e.split(',');a[x=r[1]][w=r[0]]|=5;a[x][y=r[2]]|=6;a[z=r[3]][w]|=9;a[z][y]|=10;for(i=x;++i<z;)a[i][w]|=12,a[i][w]&=14,a[i][y]|=12,a[i][y]&=13;for(i=w;++i<y;)a[x][i]|=3,a[x][i]&=11,a[z][i]|=3,a[z][i]&=7;for(i=x;++i<z;)for(j=w;++j<y;)a[i][j]=16});console.log(a.map(e=>e.map(t=>t==16?':':' xx─x┌┐┬x└┘┴│├┤┼'[t&15]).join('')).join('\n'))}
```
Without ES6 :
```
function w(s){a=[];for(i=0;i<57;i++){a[i]=[];for(j=0;j<76;j++)a[i][j]=0}s.split('\n').forEach(function(e){r=e.split(',');a[r[1]][r[0]]|=5;a[r[1]][r[2]]|=6;a[r[3]][r[0]]|=9;a[r[3]][r[2]]|=10;for(i=r[1];++i<r[3];)a[i][r[0]]|=12,a[i][r[0]]&=14,a[i][r[2]]|=12,a[i][r[2]]&=13;for(i=r[0];++i<r[2];)a[r[1]][i]|=3,a[r[1]][i]&=11,a[r[3]][i]|=3,a[r[3]][i]&=7;for(i=r[1];++i<r[3];)for(j=r[0];++j<r[2];)a[i][j]=16});console.log(a.map(function(e){return e.map(function(t){return t==16?':':' xx─x┌┐┬x└┘┴│├┤┼'[t&15]}).join('')}).join('\n'))}
```
`w('0,0,15,10\n15,10,20,15\n10,13,15,15\n9,1,16,3\n17,5,20,7\n11,2,17,4\n15,4,19,6\n13,3,18,5');` outputs correctly the OP's example.
The edges of windows are built using bitwise operators (Up=8, Bottom=4, Left=2, Right=1).
[Answer]
# Python, 397 characters
```
#coding:437
import os
J=range
M=[[0]*76 for _ in J(57)]
for A,C,B,D in[map(int,q.split(','))for q in os.read(0,9999).split('\n')]:
for x in J(A+1,B):
for y in J(C+1,D):M[C][A]|=5;M[C][B]|=6;M[D][A]|=9;M[D][B]|=10;M[C][x]|=3;M[D][x]|=3;M[y][A]|=12;M[y][B]|=12;M[y][x]=16;M[y][x-1]&=~1;M[y][x+1]&=~2;M[y-1][x]&=~4;M[y+1][x]&=~8
C=" rl─d┌┐┬u└┘┴│├┤┼:"
for l in M:print''.join((C+C[1:])[m]for m in l)
```
Change `C="...` to `C=u"...` and it'll print in unicode instead! It might be tricky to get the file to save properly because the code page 437 characters are not escaped (the first 'coding' comment line is required).
The approach is to incrementally build a map using bit-wise operators. Less golfed version with comments:
```
#coding:437
import os
J=range
# set up the field
# Each element is a bitfield. Flags are:
# 16 - inside a window?
# 8 - up
# 4 - down
# 2 - left
# 1 - right
M=[[0]*76 for _ in J(57)]
# for each window...
for A,C,B,D in[map(int,q.split(','))for q in os.read(0,9999).split('\n')]:
# add the directions for the corners
M[C][A]|=5;M[C][B]|=6;M[D][A]|=9;M[D][B]|=10
# add the top and bottom edges
for y in J(C+1,D):M[y][A]|=12;M[y][B]|=12
# add the left and right edges
for x in J(A+1,B):M[C][x]|=3;M[D][x]|=3
# deal with the middle
for x in J(A+1,B):
for y in J(C+1,D):
# Clear the current spot by setting to inside a window
M[y][x]=16
# Remove the right direction from the left spot, top from the bottom, etc
M[y][x-1]&=~1;M[y][x+1]&=~2;M[y-1][x]&=~4;M[y+1][x]&=~8
# print it out
C=u" rl─d┌┐┬u└┘┴│├┤┼:"
for l in M:print''.join((C+C[1:])[m]for m in l)
```
[Answer]
## Python, 672 chars
The less readable version:
```
import sys
r=range
M=[0,0,0,191,0,196,218,194,0,217,179,180,192,193,195,197]
Z=[map(int,l.split(",")) for l in sys.stdin.readlines()]
S=[[[0]*5 for x in r(77) ] for y in r(58)]
for i in r(len(Z)):
A,C,B,D=Z[i]
for a,b,c in [(C,A,2),(C,A,3),(D,A,1),(D,A,2),(C,B,3),(C,B,4),(D,B,1),(D,B,4)]:S[a][b][c]=1
for x in r(A+1,B):
for a,b in [(C,2),(C,3),(C,4),(D,1),(D,2),(D,4)]:S[a][x][b]=(b+1)&1
for y in r(C+1,D):
for a,b in [(A,1),(A,2),(A,3),(B,1),(B,3),(B,4)]:S[y][a][b]=b&1
for x in r(A+1,B):
for y in r(C+1,D):S[y][x]=[i+1]+[0]*4
O=sys.stdout.write
for l in S:
for k in l:
c=' ';x=M[k[1]*8|k[2]*4|k[3]*2|k[4]]
if k[0]:c=':'
if x:c=chr(x)
O(c)
O('\n')
```
Started from the version below:
```
import sys
coords = [ tuple(map(int,l.strip().split(","))) for l in sys.stdin.readlines() ]
screen = [ [ [-1, [False,False,False,False]] for x in range(0, 77) ] for y in range(0, 58) ]
def mergeBorders(screen, w):
x0,y0,x1,y1 = w
screen[y0][x0][1][1] = True
screen[y0][x0][1][2] = True
screen[y1][x0][1][0] = True
screen[y1][x0][1][1] = True
screen[y0][x1][1][2] = True
screen[y0][x1][1][3] = True
screen[y1][x1][1][0] = True
screen[y1][x1][1][3] = True
for x in range(x0+1,x1):
screen[y0][x][1][1] = True
screen[y0][x][1][2] = False
screen[y0][x][1][3] = True
screen[y1][x][1][0] = False
screen[y1][x][1][1] = True
screen[y1][x][1][3] = True
for y in range(y0+1,y1):
screen[y][x0][1][0] = True
screen[y][x0][1][1] = False
screen[y][x0][1][2] = True
screen[y][x1][1][0] = True
screen[y][x1][1][2] = True
screen[y][x1][1][3] = False
def paintInside(screen, w, wId):
x0,y0,x1,y1 = w
for x in range(x0+1,x1):
for y in range(y0+1,y1):
screen[y][x][0] = wId
screen[y][x][1] = [False, False, False, False]
for wId in range(len(coords)):
w = coords[wId]
mergeBorders(screen, w)
paintInside(screen, w, wId)
borderMap = { (False, True, True, False): 0xda,
(False, True, False, True): 0xc4,
(False, True, True, True): 0xc2,
(False, False, True, True): 0xbf,
(True, False, True, False): 0xb3,
(True, True, True, False): 0xc3,
(True, True, True, True): 0xc5,
(True, False, True, True): 0xb4,
(True, True, False, False): 0xc0,
(True, True, False, True): 0xc1,
(True, False, False, True): 0xd9 }
def borderChar(c):
return chr(borderMap[(c[0],c[1],c[2],c[3])])
for screenLine in screen:
for contents in screenLine:
c = ' '
if True in contents[1]:
c = borderChar(contents[1])
elif contents[0] >= 0:
c = ':'
sys.stdout.write(c)
sys.stdout.write('\n')
```
] |
[Question]
[
In [this question](https://codegolf.stackexchange.com/questions/2357/1p5-iterated-prisoners-dilemma), a game was devised in which players would face each other off pair by pair in the Prisoner's Dilemma, to determine which iterative strategy scored the highest against others.
In [this question](https://math.stackexchange.com/questions/267384/does-this-multiplayer-generalization-of-the-prisoners-dilemma-exist), I devised a way for multiple people to play the Prisoners' Dilemma against each other all at the same time. In this variation, the payoff matrix is unnecessary, with each outcome between each pair of two players being the sum of two functionally independent decisions.
Your task is to build an AI to play this symmetric, generalized version of the multiplayer Prisoner's Dilemma that will achieve the highest score possible.
---
# Rules of the Game
In each round of this multiplayer, multi-round Prisoner's Dilemma, a player `A` can decide to "take 1" from some other player `B`. In this circumstance, `A`'s score increases by 1, while `B`'s score decreases by 2. This decision is allowed to happen between each ordered pair of players.
This is the only decision made for each player – either to "take 1" or not to "take 1" from each other player, which are homologous to defection and cooperation respectively. The effective payoff matrix between two players `P1` and `P2` looks as follows:
```
P1/P2 P1 Take1 P1 Don't
P2 Take1 -1/-1 -2/+1
P2 Don't +1/-2 0/ 0
```
---
# Tournament Procedure
The game will consist of `P * 25` rounds, where `P` is the number of participating players. All players start with a score of `0`. Each round will consist of the following procedure:
At the beginning of a round, each program will be given a history of the previous rounds **from standard input**, in the following format:
* One line containing 3 numbers, `P`, `D`, and `N`.
+ `P` is the total number of players in the game. Each player is randomly assigned an ID number from `1` to `P` at the beginning of the game.
+ `D` is the ID of the current player.
+ `N` is the number of rounds that have been played.
* `N` lines, each line representing the outcomes of a round. On line `k` of `N`, there will be some number `n_k` of ordered pairs `(a, b)`, separated by spaces, which represent that the player with ID `a` "took 1" from the player with ID `b` in that round.
* A uniformly random number `R` from `0` to `18446744073709551615` (264 - 1), to act as a pseudorandom seed. These numbers will be read from a pre-generated file, which will be released at the end of the tournament so that people can verify the results for themselves.
* One extra line that represents some form of state to be read into your program, if your program produced such an output in the previous round. At the beginning of the game, this line will always be empty. This line will not be modified by either the scoring code or other programs.
Each program will then use its strategy to produce the following **to standard output**:
* A list of `K` numbers, which are the IDs of the programs it will "take 1" from this round. An empty output means it will do nothing.
* Optionally, one extra line representing some form of state to pass on to later rounds. This exact line will be fed back to the program in the next round.
Below is an example input for the beginning of the game for a player of ID `3` in a 4-player game:
```
4 3 0
4696634734863777023
```
Below is an example input for the same game with a few rounds already played:
```
4 3 2
(1, 2) (1, 3) (1, 4) (4, 2)
(1, 3) (2, 1) (2, 4) (3, 1) (4, 1)
4675881156406346380
```
Each program will be fed exactly the same input for a round except for the ID number `D` which is unique to each program.
Below is an example output in which player `3` takes 1 from everybody else:
```
1 2 4
```
At the end of all the required rounds, the player with the highest final score will be the winner.
---
# Timeline
The coding for this tournament will last for a total of 7 days. The deadline for submissions is `2014-05-09 00:00 UTC`.
Do not post actual programs before this date – post the SHA256 hash of the source code of your program as a commitment. You may change this hash any time before the deadline, but commitments posted after the deadline will not be accepted for judgment. (Please use base 64 notation for your hashes, as my verification program spits out base 64 and it's a more compact notation.)
After the deadline is over, you will have 1 day (until `2014-05-10 00:00 UTC`) to post the actual source code of your program for your submission. If the SHA256 hash of your posted source code does not match any hash that you posted before the deadline, your code will not be accepted into the tournament.
After this, I will download all the submissions onto my own computer, and run all the tournament entries in this battle royale, hopefully posting the results within 2 days from then, by `2014-05-12 00:00 UTC`.
I will accept the answer with the highest score, and award a bounty of +100 to that answer if its final score is greater than `0`.
After the tournament is over, I will post the random seed file used to run the competition, and people may start posting other solutions trying to top the ones used in the tournament. However, they will not count for acceptance or the bounty.
# The Host Machine
I will be running these solutions on a virtual machine on my computer. This virtual machine will run Ubuntu Linux 14.04, with 2 gigabytes of RAM. My base machine has an Intel i7-2600K processor running at 3.40 GHz.
# Requirements
Your program must be written in a language for which a compiler or interpreter that will compile your program exists and is readily available for the latest version of Ubuntu Linux, so that I can run all the submissions and judge them in a virtual machine.
Your program must not take more than `2.000 seconds` to run each round. If your program runs out of time or produces an error, its output will be considered empty for that round.
Your program must be deterministic; that is, it must always return the same output for the same input. Pseudorandom solutions are allowed; however, their randomness must depend on the random seed given to it as input and nothing else. The seed file was generated using Python's `os.urandom`. It contains a total of 500 lines (more will be generated if necessary), and its SHA256 hash is `K+ics+sFq82lgiLanEnL/PABQKnn7rDAGmO48oiYxZk=`. It will be uploaded here once the tournament is over.
---
# Plants
To kick things off, there will be four "plants", representing initial naïve strategies. These will be playing in the tournament along with your submissions. However, in the unlikely case that one of them wins, the highest score obtained by a player other than a plant will be considered the winner.
To calculate the hash of each plant's file, replace every group of 4 spaces with a tab, since the formatter here doesn't seem to like tab characters.
**The Lazy** — never does anything.
`n1bnYdeb/bNDBKASWGywTRa0Ne9hMAkal3AuVZJgovI=`
```
pass
```
**The Greedy** — always takes 1 from everybody else.
`+k0L8NF27b8+Xf50quRaZFFuflZhZuTCQOR5t5b0nMI=`
```
import sys
line1 = sys.stdin.readline()
n = [int(i) for i in line1.split()]
for i in range(n[0]):
if i+1 != n[1]:
print i+1,
print
```
**The Wrathful** — takes 1 from everybody else on the first round, and takes 1 from everybody who took 1 from it the previous round afterwards.
`Ya2dIv8TCh0zWzRfzUIdFKWj1DF9GXWhbq/uN7+CzrY=`
```
import sys
import re
line1 = [int(i) for i in sys.stdin.readline().split()]
players = line1[0]
pid = line1[1]
rounds = line1[2]
lines = []
if rounds == 0:
for i in range(players):
if i+1 != pid:
print i+1,
print
else:
for i in range(rounds):
lines.append(sys.stdin.readline())
lastline = lines[-1]
takes = re.findall(r'\([0-9]+, [0-9]+\)', lastline)
for take in takes:
sides = [int(i) for i in re.findall(r'[0-9]+', take)]
if sides[1] == pid:
print sides[0],
print
```
**The Envious** — takes 1 from the 50% of players with the current highest score excluding itself, rounding down.
`YhLgqrz1Cm2pEcFlsiIL4b4MX9QiTxuIOBJF+wvukNk=`
```
import sys
import re
line1 = [int(i) for i in sys.stdin.readline().split()]
players = line1[0]
pid = line1[1]
rounds = line1[2]
lines = []
scores = [0] * players
if rounds == 0:
for i in range(players):
if i+1 != pid:
print i+1,
print
else:
for i in range(rounds):
takes = re.findall(r'\([0-9]+, [0-9]+\)', sys.stdin.readline())
for take in takes:
sides = [int(i) for i in re.findall(r'[0-9]+', take)]
scores[sides[0] - 1] += 1
scores[sides[1] - 1] -= 2
score_pairs = [(i+1, scores[i]) for i in range(players)]
score_pairs.sort(key=lambda x:(x[1], x[0]))
score_pairs.reverse()
taken = 0
j = 0
while taken < (players) / 2:
if score_pairs[j][0] != pid:
print score_pairs[j][0],
taken += 1
j += 1
```
In a tournament of 100 rounds just amongst these four, they receive scores of:
```
Lazy: -204
Greedy: -100
Wrathful: -199
Envious: -199
```
---
# Judging Program
I've posted the judge program I'll be using at [Github](https://github.com/joezeng/pdc2014). Download it and test it out. (And maybe fix a bug or two if you find one. :P)
It doesn't have compilation options for anything other than Python at the moment. I'll be including those later - if people could contribute compilation or interpretation scripts for other languages, I'd be much obliged.
---
# Phase 2: Source Code Submission
I've posted a new branch `tournament` to the Github repository for the contest, containing the pd\_rand file and other plant entries. You can either post your source code here or submit it to that branch as a pull request.
The order of the contestants will be as follows:
```
'begrudger'
'regular'
'patient'
'lazy'
'backstab'
'bully'
'lunatic'
'envious'
'titfortat'
'greedy'
'wrathful'
'judge'
'onepercent'
```
---
# Final Scores
The output of my testing program:
```
Final scores:
begrudger -2862
regular -204
patient -994
lazy -2886
backstab -1311
bully -1393
lunatic -1539
envious -2448
titfortat -985
greedy -724
wrathful -1478
judge -365
onepercent -1921
```
Rankings:
```
1. regular -204
2. judge -365
3. greedy -724
4. titfortat -985
5. patient -994
6. backstab -1311
7. bully -1393
8. wrathful -1478
9. lunatic -1539
10. onepercent -1921
11. envious -2448
12. begrudger -2862
13. lazy -2886
```
So it turns out that the winner is indeed a player - it's The Regular, with -204 points!
Unfortunately, its score wasn't positive, but we can hardly expect that in a simulation of the Iterated Prisoner's Dilemma where everybody's playing to win.
Some surprising results (at least that I thought were surprising):
* The Greedy scored more than Tit for Tat, and in fact, generally higher than most scorers at all.
* The Judge, which was meant to be a sort of "morality enforcer" character (it basically took 1 from whoever had taken 1 from anybody an above-average number of times) ended up scoring rather high, while in simulation testing, it would actually get a rather low score.
And others that (I thought) weren't so surprising:
* The Patient scored a full 484 points more than The Wrathful. It really pays to cooperate that first time.
* One Percent very quickly had almost nobody to kick while they were down. Seems that the 1% is only able to stay that way because they have more players in the game.
Anyway, now that the tournament is over, feel free to post as many extra players as you'd like, and test around with them using the judge program.
[Answer]
## The Regular
The version of this entry I have chosen for the tournament (SHA-256: `ggeo+G2psAnLAevepmUlGIX6uqD0MbD1aQxkcys64oc=`) uses [Joey](https://codegolf.stackexchange.com/users/15/joey)'s "[Random sucker](https://codegolf.stackexchange.com/a/2453/163)" strategy (albeit with a minor and likely insignificant change), which came in second place in the last contest. Unfortunately, a newer, more effective version submitted just 3 minutes 25 seconds before the deadline has a serious bug, so it could not be used. Nevertheless, this version still fares relatively well.
```
<?php
$secretKey = '95CFE71F76CF4CD2';
$hashOutput = '';
$hashSeq = 0;
$hashIndex = 64;
function psRand($min = null, $max = null) {
global $secretKey, $state, $hashOutput, $hashSeq, $hashIndex;
if ($hashIndex > 56) {
$hashOutput = hash_hmac('sha256', ++$hashSeq . ' ' . $state['rand'], $secretKey);
$hashIndex = 0;
}
$num = (int)(hexdec(substr($hashOutput, $hashIndex, 8)) / 2);
$hashIndex += 8;
return $min === null ? $num : (int)($min + $num * ($max - $min + 1) / 2147483648);
}
$line = fgets(STDIN);
sscanf($line, "%d %d %d", $numPlayers, $myPlayerId, $roundsPlayed);
$roundsCount = 25 * $numPlayers;
$roundsRemaining = $roundsCount - $roundsPlayed - 1;
$betrayalCount = array_fill(1, $numPlayers, 0);
for ($round = 0; $round < $roundsPlayed; ++$round) {
$line = fgets(STDIN);
preg_match_all('/\((\d+), (\d+)\)/', $line, $matches, PREG_SET_ORDER);
foreach ($matches as $m) {
$defector = (int)$m[1];
$victim = (int)$m[2];
if ($victim === $myPlayerId) {
++$betrayalCount[$defector];
}
}
}
$hashOutput = rtrim(fgets(STDIN), "\n");
$state = unserialize(rtrim(fgets(STDIN), "\n"));
if (!$state) {
$state = ['rand' => ''];
}
$state['rand'] = hash_hmac('sha256', $state['rand'] . $line, $secretKey);
$victims = [];
if ($roundsPlayed > 1) {
for ($other = 1; $other <= $numPlayers; ++$other) {
if ( $other === $myPlayerId) {
continue;
}
if ($betrayalCount[$other] > 7 || psRand() % 1024 < 32 || !$roundsRemaining ) {
$victims[] = $other;
}
}
}
echo implode(' ', $victims), "\n", serialize($state), "\n";
```
The buggy version has an SHA-256 hash of `2hNVloFt9W7/uA5aQXg+naG9o6WNmrZzRf9VsQNTMwo=`:
```
<?php
$secretKey = '95CFE71F76CF4CD2';
$hashOutput = '';
$hashSeq = 0;
$hashIndex = 64;
function psRand($min = null, $max = null) {
global $secretKey, $state, $hashOutput, $hashSeq, $hashIndex;
if ($hashIndex > 56) {
$hashOutput = hash_hmac('sha256', ++$hashSeq . ' ' . $state['rand'], $secretKey);
$hashIndex = 0;
}
$num = (int)(hexdec(substr($hashOutput, $hashIndex, 8)) / 2);
$hashIndex += 8;
return $min === null ? $num : (int)($min + $num * ($max - $min + 1) / 2147483648);
}
$line = fgets(STDIN);
sscanf($line, "%d %d %d", $numPlayers, $myPlayerId, $roundsPlayed);
$roundsCount = 25 * $numPlayers;
$roundsRemaining = $roundsCount - $roundsPlayed - 1;
$betrayalCount = array_fill(1, $numPlayers, 0);
$scoreWindow = array_fill(1, $numPlayers, array_fill(1, $numPlayers, 0));
$lastMove = array_fill(1, $numPlayers, array_fill(1, $numPlayers, false));
for ($round = 0; $round < $roundsPlayed; ++$round) {
$line = fgets(STDIN);
preg_match_all('/\((\d+), (\d+)\)/', $line, $matches, PREG_SET_ORDER);
foreach ($matches as $m) {
$defector = (int)$m[1];
$victim = (int)$m[2];
if ($victim === $myPlayerId) {
++$betrayalCount[$defector];
}
TAB>TAB>if ($round >= $roundsPlayed - 10) {
TAB>TAB>TAB>$scoreWindow[$defector][$victim] -= 2;
TAB>TAB>TAB>$scoreWindow[$victim][$defector] += 1;
TAB>TAB>}
TAB>TAB>if ($round === $roundsPlayed - 1) {
TAB>TAB>TAB>$lastMove[$defector][$victim] = true;
TAB>TAB>}
}
}
$line .= fgets(STDIN);
$state = unserialize(rtrim(fgets(STDIN), "\n"));
if (!$state) {
$state = ['rand' => '', 'copying' => array_fill(1, $numPlayers, 0)];
}
$state['rand'] = hash_hmac('sha256', $state['rand'] . $line, $secretKey);
$victims = [];
if ($roundsPlayed > 1) {
for ($other = 1; $other <= $numPlayers; ++$other) {
if ($other === $myPlayerId) {
continue;
}
TAB>TAB>if ($roundsPlayed >= 10) {
TAB>TAB>TAB>$myScore = $scoreWindow[$other][$myPlayerId];
TAB>TAB>TAB>foreach ($scoreWindow[$other] as $betterPlayer => $betterScore) {
TAB>TAB>TAB>TAB>if ($betterScore >= 0.5 * $myScore && !psRand(0, $betterPlayer)) {
TAB>TAB>TAB>TAB>TAB>$state['copying'][$other] = $betterPlayer;
TAB>TAB>TAB>TAB>}
TAB>TAB>TAB>}
TAB>TAB>}
TAB>TAB>if ($state['copying'][$other]) {
TAB>TAB>TAB>if ($lastMove[$state['copying'][$other]][$other]) {
TAB>TAB>TAB>TAB>$victims[] = $other;
TAB>TAB>TAB>}
} elseif ($betrayalCount[$other] > 7 || psRand() % 1024 < 32 || !$roundsRemaining ) {
$victims[] = $other;
}
}
}
echo implode(' ', $victims), "\n", serialize($state), "\n";
```
To fix it, make these replacements:
* Replace `$hashOutput = rtrim(fgets(STDIN), "\n");` with `$line .= fgets(STDIN);` (not that that really matters).
* Replace `if ($betterScore >= 3 * $myScore) {` with `if ($betterScore >= 0.5 * $myScore && !psRand(0, $betterPlayer)) {` (this is what killed it).
[Answer]
## One Percent
```
b61189399ae9494b333df8a71e36039f64f1d2932b838d354c688593d8f09477
```
Looks down on those prisoners he considers beneath him.
---
Simply takes from everyone that has points less than or equal to himself. The assumption is that those prisoners are less likely to take in return (or they'd have more). I don't know how *good* of an assumption that is, but that's what he's operating on.
Also takes from *everyone* on the last round. There is literally no downside to this, since nobody can revenge-steal after that.
If you have problems getting the hash because of tab/spaces from pasted code, [here's a link to the file itself.](https://drive.google.com/file/d/0B73QYv2Zz0SiY0xLR1RFd0VCLTQ/edit?usp=sharing)
```
import java.io.BufferedReader;
import java.io.InputStreamReader;
class OnePercent {
static int numPlayers;
static int me;
static int turn;
static int[] values;
public static void main(String[] args) {
if(!readInput())
return;
String out = "";
for(int i=1;i<values.length;i++){
if(i != me && (values[i] <= values[me] || turn > (numPlayers*25-2)))
out += i + " ";
}
out.trim();
System.out.print(out);
}
static boolean readInput(){
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line = reader.readLine();
if(line == null)
return false;
String[] tokens = line.split(" ");
if(tokens.length < 3)
return false;
numPlayers = Integer.valueOf(tokens[0]);
me = Integer.valueOf(tokens[1]);
turn = Integer.valueOf(tokens[2]);
values = new int[numPlayers+1];
for(int i=0;i<values.length;i++)
values[i]=0;
for(int i=0;i<turn;i++){
line = reader.readLine();
line = line.replaceAll("[)]",",");
line = line.replaceAll("[( ]", "");
tokens = line.split(",");
for(int j=0;j<tokens.length-1;j+=2){
int thief = Integer.valueOf(tokens[j]);
int poor = Integer.valueOf(tokens[j+1]);
if(thief<1||poor<1||thief>numPlayers||poor>numPlayers)
continue;
values[thief]++;
values[poor] -= 2;
}
}
reader.close();
} catch(Exception e) {
return false;
}
return true;
}
}
```
[Answer]
Here are a few more plants that will be participating in the game. These ones are more advanced, and their source code will not be revealed until the end of the coding phase.
Just like the four plants in the question, if they manage to score higher than all other players, only the highest score achieved by an actual contestant will be considered a winner.
---
# The Bully
`29AGVpvJmDEDI5Efe/afmMJRLaJ+TpjwVcz1GkxgYZs=`
Picks on people.
---
# The Judge
`yjdCQ3uQ4YKe7xAKxdTFLF4d72fD4ACYpDLwkbzdISI=`
Punishes wrongdoers.
---
# The Lunatic
`m3FsRPocekCcK6GDswgnobV2CYOxX8LquChnKxrx1Wo=`
Has no idea *what* it's doing.
---
# The Patient
`nd7Pt3bVpFnuvDVeHQ5T9EPTq7KjNraVzp/KGtI73Vo=`
Never makes the first move.
[Answer]
# Tit-for-tat
```
9GkjtTDD2jrnMYg/LSs2osiVWxDDoSOgLCpWvuqVmSM=
```
Similar to Wrathful, with a few (hopefully) performance-enhancing changes.
```
import sys
import re
line1 = [int(i) for i in sys.stdin.readline().split()]
players = line1[0]
pid = line1[1]
rounds = line1[2]
lines = []
if rounds == 0:
print
elif rounds == 25 * players - 1:
for i in range(players):
if i+1 != pid:
print i+1,
print
else:
for i in range(rounds):
lines.append(sys.stdin.readline())
lastline = lines[-1]
takes = re.findall(r'\([0-9]+, [0-9]+\)', lastline)
for take in takes:
sides = [int(i) for i in re.findall(r'[0-9]+', take)]
if sides[1] == pid:
print sides[0],
print
```
[Answer]
# Backstab
### Python 3
Despite the name, this bot is actually quite gracious. But don't tick it off.
```
import sys, math
inp = [int(i) for i in sys.stdin.readline().split()]
inp.append([])
for i in range(inp[2]):
inp[3].append(
[eval(i+')') for i in sys.stdin.readline().split(')')[:-1]]
)
inp += sys.stdin.readline()
# inp is [P, D, N, [M1, M2...], R]
dat = [[], inp[2] % 2] # average runlength take and don't per player, parity of round
lastatk = []
for i in range(inp[0]):
dat[0].append([])
lastatk.append(0)
for i,r in enumerate(inp[3]): # each round
for m in r: # each move
if m[1] == inp[1]:
dat[0][m[0]-1].append(i) # round num they attacked
lastatk[m[0]-1] = i # keep track of last attack
# now that we know who attacked me when, i can do some stats
nav = []
rl = []
for i in range(inp[0]):
nav.append([[0], False])
rl.append([[], []]) # attack, don't
for i in range(inp[2]): # each round
for p in range(1, inp[0]+1): # each player
if p != inp[1]: # let's not judge ourselves
if i in dat[0][p-1]: # p attacked me in round i
if nav[p-1][1]: # attack chain?
nav[p-1][0][-1] += 1
else: # start attack chain!
rl[p-1][1] += [nav[p-1][0][-1]] # copy peace chain
nav[p-1][0].append(1)
nav[p-1][1] = True
else: # peace!
if not nav[p-1][1]: # peace chain?
nav[p-1][0][-1] += 1
else: # peace to all!
rl[p-1][0] += [nav[p-1][0][-1]] # copy atk chain
nav[p-1][0].append(1)
nav[p-1][1] = False
print(nav)
print(inp[3])
# now, rl has runlengths for each player.
print(rl)
rl = [[sum(i[0])/len(i[0]+[0]), sum(i[1])/len(i[1]+[0])] for i in rl]
# rl now contains the averages w/ added zero.
# So, now we have average runtime and last attack. Let's quickly make some descisions.
out = []
for p in range(1, inp[0]+1): # each player
if p != inp[1]: # again, let's not judge ourselves
if lastatk[p-1] == inp[0]-1: # they attacked us!
out.append(p)
else: # whew, we can recover
if inp[0] - lastatk[p-1] > rl[p-1][0]: # they're due to defend!
out.append(p)
elif int(__import__('binascii').b2a_hex(inp[-1].encode()), 16) % 4 == 0: # 1 in 4 chance of doing this
out.append(p) # backstab!!1!!1one!!!1!!
print(*out)
```
**EDIT 2**: Posted source. Yay.
**EDIT**: After some testing I fixed some flaws I found. They aren't algorithmic, just some issues reading the input.
[Answer]
# The [Begrudger](http://en.wiktionary.org/wiki/begrudger)
```
g1TXBu2EfVz/uM/RS24VeJuYMKLOaRatLxsA+DN1Mto=
```
# Code
I will admit that I did not spend much time on this...
```
import sys
p, d, n, o = input().split(' ') + ['']
p, d, n = int(p), int(d), int(n)
for i in range(n):
r = input()
r = r[1:len(r)-1].split(') (')
for a in r:
if int(a.split(', ')[1]) == d and not a.split(', ')[0] in o:
o += a.split(', ')[0] + " "
input()
print(o)
```
] |
[Question]
[
Given is a board of variable size with a maximum size of 5 times 5 fields. Every field kann be filled with an 'x'. If it is not filled with an 'x', it is filled with an 'o'.
The starting state of every board is given (see below). With each board, 10 rounds have to be played (at max, conditions: see below) and the evolution of the x must be watched.
One round works the following way:
1. every 'x' spreads to orthogonally bordering fields, but dissapears itself
2. each time two 'x' are on one field, they neutralize each other
The evolution of all 'x' in each round has to happen simultaneously.
Example:
```
o o o o x o
o x o -> x o x
o o o o x o
```
With each round of evolution, you have to see if the board gets emptied of 'x'.
Is it not empty, a repeating pattern could be present. If this is also not the case,
we give up the analysis of the evolution.
Additionally you have to print out the maximum percentage of x fields for every starting board (rounded down to whole numbers).
**Input:**
The input data can be found [here](http://pastebin.com/8XDLSp5P) (Pastebin)
This data contains 100 starting states. As already mentioned, the boards vary in size. The number of rows is stated with number n from 1 to 5, followed by n rows that contain only 'x' and 'o', represent the starting pattern. Every row of a board has 1 to 5 fields.
**Output:**
The complete result must be printed out, one printed row for each starting board in the following form:
```
Round {0-10}: {repetition/empty/giveup}, {0-100} percent maximum-fill
```
**Examples:**
Example 1:
```
Input: 2 Starting state: x o x
xox x x
xx
Round 1: x x o
o x
Round 2: x o x
o x
Round 3: o x o
o o
Round 4: x o x -> The pattern repeats:
o x It is the same as in round 2,
therefore we stop. Maximum fill was
in the starting state with four times 'x'
of 5 fields altogether,
so we have 4/5 = 80 %.
Output: Round 4: repetition, 80 percent maximum-fill
```
Example 2:
```
Input: 1 Starting state: x x
xx
Round 1: x x -> We already have a repetition, because
the pattern is the same as in the starting
state. The board is always filled 100 %.
Output: Round 1: repetition, 100 percent maximum-fill
```
After eight dayst I will mark the working answer with the fewest characters as the winner. Additionally i will post the correct output for the 100 starting boards (input).
You can use your prefered (programming/scripting/whatever) language.
Have fun!
PS: If you have questions, feel free to ask.
PPS: In respect of the original creators:
For people capable of speaking german, the question was taken from DO NOT CLICK IF YOU DO NOT WANT SPOILERS
[here](http://mc.capgemini.de/magazin/expedition/coder-challenge-2/). Since the official time for completing the challenge has ended, I wanted to see if someone could come up with a short and elegant solution.
**22.04.2014:**
**Challenge Done! Winner marked as accepted. Correct output:**
```
Round 10: giveup, 50 percent maximum-fill
Round 5: empty, 66 percent maximum-fill
Round 1: repetition, 100 percent maximum-fill
Round 1: empty, 100 percent maximum-fill
Round 4: repetition, 100 percent maximum-fill
Round 4: repetition, 70 percent maximum-fill
Round 2: repetition, 60 percent maximum-fill
Round 4: empty, 88 percent maximum-fill
Round 10: giveup, 50 percent maximum-fill
Round 5: repetition, 80 percent maximum-fill
Round 10: repetition, 80 percent maximum-fill
Round 1: empty, 80 percent maximum-fill
Round 3: repetition, 60 percent maximum-fill
Round 4: repetition, 48 percent maximum-fill
Round 9: empty, 41 percent maximum-fill
Round 10: giveup, 92 percent maximum-fill
Round 10: giveup, 53 percent maximum-fill
Round 10: giveup, 66 percent maximum-fill
Round 6: repetition, 50 percent maximum-fill
Round 10: giveup, 88 percent maximum-fill
Round 10: giveup, 76 percent maximum-fill
Round 10: giveup, 68 percent maximum-fill
Round 10: giveup, 40 percent maximum-fill
Round 10: giveup, 100 percent maximum-fill
Round 10: giveup, 71 percent maximum-fill
Round 2: empty, 81 percent maximum-fill
Round 6: repetition, 36 percent maximum-fill
Round 10: giveup, 61 percent maximum-fill
Round 10: giveup, 60 percent maximum-fill
Round 4: repetition, 66 percent maximum-fill
Round 10: giveup, 72 percent maximum-fill
Round 3: empty, 80 percent maximum-fill
Round 10: giveup, 50 percent maximum-fill
Round 10: giveup, 83 percent maximum-fill
Round 7: repetition, 37 percent maximum-fill
Round 9: repetition, 85 percent maximum-fill
Round 5: repetition, 40 percent maximum-fill
Round 5: repetition, 60 percent maximum-fill
Round 4: empty, 80 percent maximum-fill
Round 10: giveup, 60 percent maximum-fill
Round 4: repetition, 46 percent maximum-fill
Round 6: repetition, 42 percent maximum-fill
Round 10: giveup, 72 percent maximum-fill
Round 4: repetition, 70 percent maximum-fill
Round 4: repetition, 80 percent maximum-fill
Round 6: repetition, 50 percent maximum-fill
Round 4: repetition, 56 percent maximum-fill
Round 10: giveup, 60 percent maximum-fill
Round 10: giveup, 54 percent maximum-fill
Round 10: giveup, 66 percent maximum-fill
Round 2: repetition, 40 percent maximum-fill
Round 2: repetition, 40 percent maximum-fill
Round 6: repetition, 75 percent maximum-fill
Round 7: empty, 85 percent maximum-fill
Round 10: giveup, 50 percent maximum-fill
Round 6: repetition, 70 percent maximum-fill
Round 2: empty, 66 percent maximum-fill
Round 1: empty, 66 percent maximum-fill
Round 3: empty, 100 percent maximum-fill
Round 3: empty, 66 percent maximum-fill
Round 8: repetition, 42 percent maximum-fill
Round 1: empty, 60 percent maximum-fill
Round 2: repetition, 100 percent maximum-fill
Round 2: repetition, 83 percent maximum-fill
Round 4: repetition, 66 percent maximum-fill
Round 6: repetition, 75 percent maximum-fill
Round 4: empty, 66 percent maximum-fill
Round 10: giveup, 61 percent maximum-fill
Round 10: giveup, 56 percent maximum-fill
Round 4: empty, 66 percent maximum-fill
Round 6: repetition, 33 percent maximum-fill
Round 3: empty, 57 percent maximum-fill
Round 3: repetition, 100 percent maximum-fill
Round 6: repetition, 73 percent maximum-fill
Round 10: giveup, 50 percent maximum-fill
Round 6: repetition, 50 percent maximum-fill
Round 10: giveup, 73 percent maximum-fill
Round 5: empty, 80 percent maximum-fill
Round 10: giveup, 61 percent maximum-fill
Round 3: repetition, 53 percent maximum-fill
Round 10: giveup, 33 percent maximum-fill
Round 10: giveup, 80 percent maximum-fill
Round 10: giveup, 63 percent maximum-fill
Round 10: giveup, 70 percent maximum-fill
Round 10: giveup, 84 percent maximum-fill
Round 7: repetition, 70 percent maximum-fill
Round 10: repetition, 57 percent maximum-fill
Round 10: giveup, 55 percent maximum-fill
Round 6: repetition, 36 percent maximum-fill
Round 4: repetition, 75 percent maximum-fill
Round 10: giveup, 72 percent maximum-fill
Round 10: giveup, 64 percent maximum-fill
Round 10: giveup, 84 percent maximum-fill
Round 10: giveup, 58 percent maximum-fill
Round 10: giveup, 60 percent maximum-fill
Round 10: giveup, 53 percent maximum-fill
Round 4: repetition, 40 percent maximum-fill
Round 4: empty, 40 percent maximum-fill
Round 10: giveup, 50 percent maximum-fill
Round 10: giveup, 68 percent maximum-fill
```
[Answer]
## Perl, ~~308, 304, 305, 293, 264~~, 262
**Edit:** A bug crept in after one of recent edits, causing wrong output for empty boards (test suite output was OK). Since `Round 0` in given output format can mean only that there can be empty boards in the input (though none is in test suite), the bug had to be fixed. Quick fix meant byte count increase (by 1, actually) - not an option, of course. Therefore, I had to golf it a little bit more.
Run with `-p` (+1 added to count), reads from STDIN. Requires 5.014 because of `r` substitution modifier.
```
(@a,%h,$m)=('',map<>=~y/ox\n/\0!/rd,1..$_);for$n(0..10){$_="Round $n: ".($h{$_="@a"}++?repetition:(($.=100*y/!///y/ //c)<$m?$.:$m=$.)?giveup:empty).", $m percent maximum-fill\n";@a=/g/?map{$_=$a[$i=$_];y//!/cr&(s/.//r.P^P.s/.$//r^$a[$i+1]^$a[$i-1])}0..$#a:last}
```
i.e.
```
# '-p' switch wraps code into the 'while(<>){....}continue{print}' loop,
# which reads a line from STDIN into $_, executes '....' and prints contents
# of $_. We use it to read board height and print current board's result.
# First line reads board's state into @a array, a line per element, at the same
# time replacing 'o' with 'x00', 'x' with '!' and chomping trailing newlines.
# '!' was chosen because it's just like 'x01' except 5th bit (which is not important)
# but saves several characters in source code.
# Note: array is prepended with an empty line, which automatically remains in this
# state during evolution, but saves us trouble of checking if actual (any non-empty)
# line has neighboring line below.
# %h hash and $m hold seen states and maximum fill percentage for current board,
# they are initialized to undef i.e empty and 0.
(@a,%h,$m)=('',map<>=~y/ox\n/\0!/rd,1..$_);
# /
# Then do required number of evolutions:
for$n(0..10){
# Stringify board state, i.e. concatenate lines with spaces ($") as separators.
# Calculate fill percentage - divide number of '!' by number of non-spaces.
# Note: using $. magick variable automatically takes care of rounding.
# Construct output string. It's not used if loop gets to next iteration.
# Check if current state was already seen (at the same time add it to %h)
# and if fill percentage is 0.
$_="Round $n: "
.($h{$_="@a"}++?repetition:(($.=100*y/!///y/ //c)<$m?$.:$m=$.)?giveup:empty)
.", $m percent maximum-fill\n";
# /
# Next is funny: if output string contains 'g' (of 'giveup' word), then evolve
# further, otherwise break-out of the loop.
@a=/g/
?map{
# Do evolution round. Act of evolution for a given line is none other than
# XOR-ing 4 strings: itself shifted right, itself shifted left, line above, line
# below. Result of this operation is truncated to original length using bitwise '&'.
# Note, when shifting string right or left we prepend (append) not an ascii-0,
# but 'P' character. It's shorter, and 4th and 6th bits will be annihilated anyway.
$_=$a[$i=$_];
y//!/cr
&(s/.//r.P
^P.s/.$//r
^$a[$i+1]
^$a[$i-1])
}0..$#a
:last
}
```
[Answer]
# **C# - 1164 chars**
This is my first participation in code-golf so please be indulgent ;-)
I know, I am far off the best results - really amazing by the way!
But I thought I'd share my solution in C# anyway.
```
using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Net;class Program{static void Main(string[] args){new WebClient().DownloadFile("http://mc.capgemini.de/challenge/in.txt",@"D:\in.txt");var a=File.ReadAllLines(@"D:\in.txt");int l=0;while(l<a.Length){int n=Int32.Parse(a[l]);var b=a.Skip(l+1).Take(n).ToArray();var f=new List<string[]>{b};var d=0;string g=null;while(d<10){var s=f.Last();if(s.All(e=>e.All(c=>c=='o'))){g="empty";break;}var h=new string[n];for(int r=0;r<n;r++){var k="";for(int c=0;c<b[r].Length;c++){int x=0;try{if(s[r][c-1]=='x')x++;}catch{}try{if(s[r][c+1]=='x')x++;}catch{}try{if(s[r-1][c]=='x')x++;}catch{}try{if(s[r+1][c]=='x')x++;}catch{}k+=((x%2)==1)?'x':'o';}h[r]=k;}d++;f.Add(h);var w=false;for(int i=0;i<f.Count-1;i++){var m=f[i];if (!h.Where((t,y)=>t!=m[y]).Any())w=true;}if(w){g="repetition";break;}}if(d==10&&g==null)g="giveup";File.AppendAllLines(@"D:\out.txt",new[]{string.Format("Round {0}: {1}, {2} percent maximum-fill",d,g,f.Select(z=>{int t=0;int x=0;foreach(var c in z.SelectMany(s=>s)){t++;if(c=='x')x++;}return(int)Math.Floor((double)x/t*100);}).Concat(new[]{0}).Max())});l=l+n+1;}}}
```
Solely the using directives already count 97 characters - so I think it is going to be quite hard to achieve the rest within less than 200 characters.
It is a fairly iterative approach, making use of LINQ in many places.
I also included the downloading of the input file and writing of the output file into the code.
Here is one little more readable version:
```
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
class Program
{
static void Main(string[] args)
{
// Download the file
new WebClient().DownloadFile("http://mc.capgemini.de/challenge/in.txt", @"D:\in.txt");
// Read of lines of downloaded file
var a = File.ReadAllLines(@"D:\in.txt");
// Line index in input file
int l = 0;
while (l < a.Length)
{
// Parse number of rows to take
int n = Int32.Parse(a[l]);
// Take the n rows
var b = a.Skip(l + 1).Take(n).ToArray();
var f = new List<string[]> { b };
var d = 0;
string g = null;
while (d < 10)
{
// Last state consists only of o's? ->
var s = f.Last();
if (s.All(e => e.All(c => c == 'o')))
{
g = "empty";
break;
}
// In h we will build up the new state
var h = new string[n];
// Loop through all rows of initial state
for (int r = 0; r < n; r++)
{
// This is our new row we will build up for the current state
var k = "";
// Count number of orthogonal adjacent x's
// And catch potential OutOfRangeExceptions
for (int c = 0; c < b[r].Length; c++)
{
int x = 0;
try { if (s[r][c - 1] == 'x') x++; }
catch { }
try { if (s[r][c + 1] == 'x') x++; }
catch { }
try { if (s[r - 1][c] == 'x') x++; }
catch { }
try { if (s[r + 1][c] == 'x') x++; }
catch { }
// Is number of adjacent x's odd? -> character will be 'x'
// otherwise -> 'o'
k += ((x % 2) == 1) ? 'x' : 'o';
}
// Add the new row to the current state
h[r] = k;
}
// Increase round count
d++;
// Add the new state to our state collection
f.Add(h);
// Now check, whether it is a repetition by comparing the last state (h) with all other states
bool w = false;
for (int i = 0; i < f.Count - 1; i++)
{
var m = f[i];
if (!h.Where((t, y) => t != m[y]).Any())
w = true;
}
if (w)
{
g = "repetition";
break;
}
}
// Check whether we reached maximum AND the last round wasn't a repetition
if (d == 10 && g == null)
g = "giveup";
// Now we append the final output row to our text file
File.AppendAllLines(@"D:\out.txt",
new[]
{
string.Format("Round {0}: {1}, {2} percent maximum-fill",
d,
g,
// Here we select all rates of x's per state
// and then grab the maximum of those rates
f.Select(z =>
{
int t=0;
int x=0;
foreach (char c in z.SelectMany(s => s))
{
t++;
if(c=='x')
x++;
}
return (int) Math.Floor((double) x / t *100);
}).Concat(new[] {0}).Max())
});
// finally we shift our index to the next (expected) number n in the input file
l = l + n + 1;
}
}
}
```
[Answer]
# J - 275 char
Oh, all these I/O specifications! Such a shamefully large score for J, in the end. Takes input on STDIN with a trailing newline, and assumes there aren't any carriage returns (`\r`) in the input. [Here's the result of applying it to the sample input file in the question.](http://pastebin.com/yih10HMH)
```
stdout;,&LF&.>}:(".@{~&0(('Round ',":@(#->/@t),': ',(empty`repetition`giveup{::~2<.#.@t=.11&=@#,0={:),', ',' percent maximum-fill',~0":>./)@(100*1&=%&(+/"1)_&~:)@,.@(a=:(a@,`[@.(e.~+.10<#@[)(_*_&=)+[:~:/((,-)(,:|.)0 1)|.!.0=&1){:)@,:@('ox'&i.^_:)@{.;$: ::]@}.)}.)];._2[1!:1]3
```
Ungolfed: (I may add a more thorough and J-newbie-friendly explanation later.)
```
input =: ];._2 [ 1!:1]3
convert =: 'ox'&i. ^ _: NB. 'x'=>1 'o'=>0 else=>infinity
spread =: ((,-)(,:|.)0 1) |.!.0 =&1 NB. x spreading outwards
cover =: (_*_&=) + [: ~:/ spread NB. collecting x`s and removing tiles not on board
iterate =: (iterate@, ` [ @. (e.~ +. 10<#@[) cover) {:
percent =: 100 * 1&= %&(+/"1) _&~: NB. percentage of x at each step
max =: 0 ": >./
stat =: 11&=@# , 0={: NB. information about the simulation
ending =: empty`repetition`giveup {::~ 2 <. #.@stat NB. how simulation ended
round =: ": @ (# - >/@stat) NB. round number
format =: 'Round ', round, ': ', ending, ', ', ' percent maximum-fill',~ max
evolvex =: format @ percent@,. @ iterate@,: @ convert
joinln =: ,&LF &.>
nlines =: ". @ {~&0
remain =: }.
stdout ; joinln }: (nlines (evolvex@{. ; $: ::]@}.) remain) input
```
The `$:` part makes the main body recurse over the input (a terribly inconvenient form for J to parse), applying the `@` daisy-chain over each section. `nlines` finds the number of lines for the next board.
The action on each board (`evolvex`) is neat: `iterate` (called `a` in the golf) constructs a list of each iteration of the simulation until we hit either something seen before or too many steps. Then `percent@,.` calculates the percentage of filled square in each result, and `format` runs some statistics (`stat`, called `t` in the golf) to figure out how the simulation ended, which percentage was the greatest, and so on, before formatting all of that into a string.
Finally, `}:` takes care of some garbage before `; joinln` joins all of the individual board outputs into one newline-separated string.
] |
[Question]
[
## Background
*Flow Free* is a series of puzzle games whose objective is to connect all the same-colored pairs of dots on the grid. In this challenge, we consider the original game on a rectangular grid (no variations like bridges, warps, or hexagonal grids).
A puzzle in *Flow Free* might look like this:
```
Puzzle Solution
....1 11111
..... 13333
..24. 13243
1.... 13243
23... 23243
...43 22243
```
One of the easiest techniques in the puzzle is that, if you can connect two dots by following the "border cells" in only one way, such a connection is always correct.
Border cells are unsolved cells that are (orthogonally or diagonally) adjacent to a solved cell (including those outside of the grid).
In order to use this technique, the two dots themselves must also be border cells, and two adjacent border cells can be connected only if they're adjacent to some common solved cell. See the explanation below for an illustration.
A puzzle is said to be "trivial" if this technique can be used from the start to the end.
The above example is an example of a trivial puzzle. Let's see how it is so.
```
Puzzle Border Trivial pair
....1 ##### 11111
..... #...# 1...#
..24. #...# 1...#
1.... #...# 1...#
23... #...# #...#
...43 ##### #####
.... #### 3333
.24. #..# 3..3
.... #..# 3..3
23... ##..# #3..3
...43 ##### ####3
24 ## 24
.. ## 24
2 .. # ## 2 24
...4 #### 2224
```
Note that, in the last step, the following paths are not considered because a horizontal connection in the middle of the width-2 strip is not valid ("two adjacent border cells can be connected only if they're adjacent to some common solved cell"):
```
2. .4
22 44
2 22 . 4.
222. ..44
```
## Challenge
Given a solved Flow Free puzzle, determine if it is trivial.
The input can be taken as a single string/array or a list of lines. You may assume only the digits 1-9 are used, and each line represented by each digit is a valid [polystrip](https://codegolf.stackexchange.com/q/155983/78410) of length 3 or higher.
For output, you can choose to
* output truthy/falsy using your language's convention (swapping is allowed), or
* use two distinct, fixed 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 in bytes wins.
## Test cases
### Truthy (is trivial)
```
11111
12221
11113
33333
32222
11111
13333
13243
13243
23243
22243
```
### Falsy (is not trivial)
m90 provided the last test case, which is specifically constructed to use an invalid bridge (the line 5).
```
11121
13121
13121
13111
11122
13121
13121
33111
13333
13443
13343
11243
21243
22244
1116777
1226666
1125555
5555344
8888334
9998444
```
[Answer]
# [Python 3](https://docs.python.org/3/), 331 bytes
```
def T(p):
w=len(p[0])+2;p='..'.join(p).join(['.'*(w+1)]*2);d={};N={}
for i,c in enumerate(p):d[c]=d.get(c,set())|{i};N[i]={i-w-1,i-w,i-w+1,i-1,i+1,i+w-1,i+w,i+w+1}
u=d.pop('.')
while d:
for k,v in d.items():
if not any(abs(a-b)in(1,w)and not(N[a]&N[b]&u)for a in v for b in v):u|=v;d.pop(k);break
else:return 0
return 1
```
[Try it online!](https://tio.run/##jVJNb6MwEL3zK6wcGrsQVANtmkRc95hTboiDCU7rDQWETVBF89uzM86WhFRZ7Ug288ZvPh6a@tO8V2V4OuVyRza0ZkuHdHEhS1onTylzg1UdT31/6v@uFMTY@ZtM/ekj7VzO0seArfK4P67WcDlkVzVEeVuiSiLL9kM2wkismifbNM79N2no1tNwM/bVK8hKVBr3atbNuAc3Hhc9OPh1bdzt8Lgc6rdQpK5qCgMwmPRdFZLkMLNtvPcO2Dj3lZEfmqIWQtSOlJUhovykItNUzDIGCrjXMVHm@ETXiUgf1kmWPrQMywgscrAVM@uyZfsVH1bnznu2yhop9lBbFlouG2napiRPDvnr8ZOR2mgSkx77k03TyiWZTCYWoXG0CwqCgDujx3BAIdoFATVw7tUZUXkYRPdQMEYBIBjPsxF7/RKo7Hbm4LrXPxEf64GZ/ycxvEm80RON9ITXiI/08Ft10Wial/l8fv3zX8CuSz2DDRgBdB7wKxj0HvBisXiNogj/1NFxrpbQ7sBoEW0ItiJJLUJuU3V2wXxdF8oUqpQDGQ2fY7x9bRpVUza8wFJD@ML8Lp/MeOqLupZlToFwSbCr@oP@TU1SNkyok30KXdE9C2qkbgvjka3QUt@RVjeqNPTMZIM8zMAEm3npfibvJoT0WVUVdEORwNiR9OgcJ@z0Bw "Python 3 – Try It Online")
Takes a list of strings. Returns 1 for a trivial solution, otherwise returns 0. On TIO it is run against all the test cases.
Here's brief explanation:
`p` is converted to a long string with '.' marking the initial out-of-bounds cells. This is so neighbors don't need to be checked if their outside the grid.
`d` is a dict mapping symbols in the solution to their set of indexes in `p`.
`N` maps indexes to neighbors.
`u` is a set of used (i.e., solved) cells. It gets initialized to the indices of the '.'s in `p`.
`k` and `v` are a symbol from the grid and it's set indices in `p`.
`if not any(...)` makes sure that any adjacent indices in `v` have a common neighbor cell in `u`. If True, `v` is a valid trivial path, it is added to `u` and removed from `d`; and the `for k,v` loop is exited early.
If the `for k,v...` loop runs to the end, there aren't any trivial paths, so return 0 (Falsey).
If `while d` ends, all the paths were trivial, so return 1 (Truthy).
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 124 114 [bytes](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn)
```
‚஬¥{0=ùîΩ‚•äùï©?1;W‚Üê(<4‚åΩ‚•ä)‚éâ2 3‚Äø3‚Üï‚䢂ÜëÀù¬∑‚âç‚üú¬¨2+‚⢂ãÑù既Ⰲó∂ùïä‚Äø0ùï©‚à߬¥¬¨(ùîΩ<‚â°¬®(ùï©(ùîΩ¬®0=1‚Ü쬮W)‚àò‚â•‚öá1ùîæ{ùï©ùïä‚çü‚â¢(‚åଥ√ó¬∑√ó‚äë)¬®Wùï©}+`‚ä∏√ó‚åæ‚•ä0=ùï©)‚à߬®<)¬®‚ä∏/ùîæùï©}(‚ç∑‚àò‚•ä=¬®<)
```
[Try it here.](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4oiowrR7MD3wnZS94qWK8J2VqT8xO1fihpAoPDTijL3ipYop4o6JMiAz4oC/M+KGleKKouKGkcudwrfiiY3in5zCrDIr4omi4ouE8J2VqeKJoeKXtvCdlYrigL8w8J2VqeKIp8K0wqwo8J2UvTziiaHCqCjwnZWpKPCdlL3CqDA9MeKGk8KoVyniiJjiiaXimocx8J2UvnvwnZWp8J2ViuKNn+KJoijijIjCtMOXwrfDl+KKkSnCqFfwnZWpfStg4oq4w5fijL7ipYowPfCdlakp4oinwqg8KcKo4oq4L/CdlL7wnZWpfSjijbfiiJjipYo9wqg8KQoK4oCiU2hvdyB0ZXN0Y2FzZXMg4oaQIOKfqAogID7in6gx4oC/MeKAvzHigL8x4oC/MSwKICAgIDHigL8y4oC/MuKAvzLigL8x4p+pLAogID7in6gx4oC/MeKAvzHigL8x4oC/MywKICAgIDPigL8z4oC/M+KAvzPigL8zLAogICAgM+KAvzLigL8y4oC/MuKAvzLin6ksCiAgPuKfqDHigL8x4oC/MeKAvzHigL8xLAogICAgMeKAvzPigL8z4oC/M+KAvzMsCiAgICAx4oC/M+KAvzLigL804oC/MywKICAgIDHigL8z4oC/MuKAvzTigL8zLAogICAgMuKAvzPigL8y4oC/NOKAvzMsCiAgICAy4oC/MuKAvzLigL804oC/M+KfqSwKCiAgPuKfqDHigL8x4oC/MeKAvzLigL8xLAogICAgMeKAvzPigL8x4oC/MuKAvzEsCiAgICAx4oC/M+KAvzHigL8y4oC/MSwKICAgIDHigL8z4oC/MeKAvzHigL8x4p+pLAogID7in6gx4oC/MeKAvzHigL8y4oC/MiwKICAgIDHigL8z4oC/MeKAvzLigL8xLAogICAgMeKAvzPigL8x4oC/MuKAvzEsCiAgICAz4oC/M+KAvzHigL8x4oC/MeKfqSwKICA+4p+oMeKAvzPigL8z4oC/M+KAvzMsCiAgICAx4oC/M+KAvzTigL804oC/MywKICAgIDHigL8z4oC/M+KAvzTigL8zLAogICAgMeKAvzHigL8y4oC/NOKAvzMsCiAgICAy4oC/MeKAvzLigL804oC/MywKICAgIDLigL8y4oC/MuKAvzTigL804p+pLAogID7in6gx4oC/MeKAvzHigL824oC/N+KAvzfigL83LAogICAgMeKAvzLigL8y4oC/NuKAvzbigL824oC/NiwKICAgIDHigL8x4oC/MuKAvzXigL814oC/NeKAvzUsCiAgICA14oC/NeKAvzXigL814oC/M+KAvzTigL80LAogICAgOOKAvzjigL844oC/OOKAvzPigL8z4oC/NCwKICAgIDnigL854oC/OeKAvzjigL804oC/NOKAvzTin6kK4p+pCkbCqHRlc3RjYXNlcw==)
Fairly unsophisticated method: it flood fills the solved cells to find disconnected regions, then marks as solved cells where all cells of the same number border the edge or a single solved region, then repeats until all cells are solved, or the input no longer changes.
Can definitely be golfed a lot more. In particular, I think it could probably be rewritten to avoid having to use rank 2 (`‚éâ2`) everywhere.
Edit: rewrote to use each (`¨`) instead of rank when possible and some other tweaks. Still a few parts I'm convinced can be improved, but I think ultimately trying a completely different approach would be better.
] |
[Question]
[
It's a funny accident that this world happens to have just 1 time dimension, but it doesn't have to be like that. It's easy to imagine worlds with 2 or more time dimensions, and in those worlds you could build computers and run software on them, just like in this one.
**The System**
Here is a system for running Brainf\*ck programs in two time dimensions:
The two time dimensions are x and y. Each Brainf\*ck program consists of an x half-program, and a y half-program, e.g., a program could be
```
x: +>+
y: [-]
```
The two half-programs each have their own program pointer, but they share a single tape pointer (that is, they both operate on the same cell of the tape).
Time is 2-dimensional, so it consists of a grid of moments:
[](https://i.stack.imgur.com/wY93u.png)
Moving along the x dimension, the x half-program executes one time step. Moving along the y dimension, the y half-program executes one time step.
So, for example, let's say the tape starts out as `[0] 0 0` (`[]` represents the tape pointer) and the x/y programs are `+` and `->-`. The execution of this program would look like this:
```
x y tape x-action y-action
0 0 [ 0] 0 0 + at 0 - at 0
1 0 [ 1] 0 0 (done) - at 0
0 1 [-1] 0 0 + at 0 move >
1 1 [ 0] 0 0 (done) move >
```
Notice that, as time moves in the y direction, the x half-program keeps doing the same thing over and over, because its time does not progress.
The tape at each moment includes the cumulative effect of all actions that feed into it (each action counts once). So, for example, the tape at time (2, 1) contains the cumulative effect of:
[](https://i.stack.imgur.com/eXHpV.png)
* the x-action from (0, 0)
* the x-action from (1, 0)
* the x-action from (0, 1)
* the x-action from (1, 1)
* the y-action from (0, 0)
* the y-action from (1, 0)
* the y-action from (2, 0)
Cumulative means:
* All the increments and decrements to a cell sum together.
* All the left (-1) and right (+1) movements to the tape pointer sum together.
Instruction pointers do not accumulate. Each half-program gets its instruction pointer from the previous moment in its dimension. That is, x program pointers progress only in the x dimension, and y program pointers progress only in the y dimension. So, for example, in the program (`[]`, `+`) starting from `[0] 0 0`, the execution would be
```
x y tape x-action y-action x-prog-ptr y-prog-ptr
0 0 0 0 0 + at 0 0 0
1 0 0 0 0 + at 0 2 (from jump) 0
0 1 1 0 0 0 1
1 1 2 0 0 1 (from NO jump) 1
```
Some more moments from the above (`+`, `->-`) simulation are:
```
x y tape x-action y-action x-prog-ptr y-prog-ptr
0 0 [ 0] 0 0 + at 0 - at 0 0 0
1 0 [ 1] 0 0 - at 0 1 0
2 0 [ 1] 0 0 - at 0 1 0
0 1 [-1] 0 0 + at 0 > 0 1
1 1 [ 0] 0 0 > 1 1
2 1 [-1] 0 0 > 1 1
0 2 -1 [ 0] 0 + at 1 - at 1 0 2
1 2 0 1 [ 0] - at 2 1 2
2 2 [-1] 1 0 - at 0 1 2
```
The Brainf\*ck operators allowed are the following (they have their standard meaning):
* `+`, `-`: increment, decrement;
* `[`, `]`: loop until zero (processing a `[` or `]` takes one time-step, as in standard Brainf\*ck);
* `<`, `>`: move left/right on the tape.
**Complex Example**
For the program (`>`, `+`) starting with `[0] 0 0`:
```
x y tape x-action y-action x-prog-ptr y-prog-ptr
0 0 [ 0] 0 0 > + at 0 0 0
1 0 0 [ 0] 0 + at 1 1 0
0 1 [ 1] 0 0 > 0 1
1 1 1 1 [ 0] 1 1
```
For (`+`, `-`) starting with `[0] 0 0`:
```
x y tape x-action y-action x-prog-ptr y-prog-ptr
0 0 [ 0] 0 0 + at 0 - at 0 0 0
1 0 [ 1] 0 0 - at 0 1 0
0 1 [-1] 0 0 + at 0 0 1
1 1 [ 0] 0 0 1 1
```
Note that the tape ends as `[0] 0 0` because each `+` and `-` happens twice, summing to 0.
For the program (`>+`, `[-]`) starting with `[0] 0 0`:
```
x y tape x-action y-action x-prog-ptr y-prog-ptr
0 0 [ 0] 0 0 > 0 0
1 0 0 [ 0] 0 + at 1 1 0
2 0 0 [ 1] 0 2 0
0 1 [ 0] 0 0 > 0 3
1 1 0 0 [ 0] + at 2 1 3
2 1 0 1 [ 1] - at 2 2 1
0 2 [ 0] 0 0 > 0 3
1 2 [ 0] 0 0 + at 0 1 3
2 2 [ 1] 1 0 2 2
```
**Diagram with Arrows**
The below diagram shows how to calculate the actions and the tape:
[](https://i.stack.imgur.com/TKCw0.png)
**The Puzzle**
Write a 2D Brainf\*ck program (with an x half-program and a y half-program) to run on a 3-cell tape, that satisfies both the following conditions:
* If the tape starts as `[0] 0 0`, at time (5, 5) it has a `0` in the zeroth cell.
* If the tape starts as `[1] 0 0`, at time (5, 5) it has a `0` in the zeroth cell.
Shortest program meeting the requirements wins.
[Answer]
# 4 bytes total: (`[-]`, `>`)
I [wrote a brute-forcer](https://github.com/PhiNotPi/BF2D) to find the smallest such program.
Here are the diagrams of this program in action. This grids are arranged in a similar manner to the grid in the spec, with (0,0) the bottom-left corner, x-time along the x-axis, and y-time along the y-axis. The upper-right corner contains the result.
First, with a tape of `0 0 0`:
```
| 0 ( 0) 0 | 0 0 ( 0)|( 0) 0 0 | 0 ( 0) 0 | 0 0 ( 0)|( 0) 0 0
|([)-] |[-] |[-] |[-] |[-] |[-]
|> |> |> |> |> |>
+------------+------------+------------+------------+------------+------------
| 0 ( 0) 0 | 0 0 ( 0)|( 0) 0 0 | 0 ( 0) 0 | 0 0 ( 0)|( 0) 0 0
|([)-] |[-] |[-] |[-] |[-] |[-]
|> |> |> |> |> |>
+------------+------------+------------+------------+------------+------------
| 0 ( 0) 0 | 0 0 ( 0)|( 0) 0 0 | 0 ( 0) 0 | 0 0 ( 0)|( 0) 0 0
|([)-] |[-] |[-] |[-] |[-] |[-]
|> |> |> |> |> |>
+------------+------------+------------+------------+------------+------------
| 0 ( 0) 0 | 0 0 ( 0)|( 0) 0 0 | 0 ( 0) 0 | 0 0 ( 0)|( 0) 0 0
|([)-] |[-] |[-] |[-] |[-] |[-]
|> |> |> |> |> |>
+------------+------------+------------+------------+------------+------------
| 0 ( 0) 0 | 0 0 ( 0)|( 0) 0 0 | 0 ( 0) 0 | 0 0 ( 0)|( 0) 0 0
|([)-] |[-] |[-] |[-] |[-] |[-]
|> |> |> |> |> |>
+------------+------------+------------+------------+------------+------------
|( 0) 0 0 |( 0) 0 0 |( 0) 0 0 |( 0) 0 0 |( 0) 0 0 |( 0) 0 0
|([)-] |[-] |[-] |[-] |[-] |[-]
|(>) |(>) |(>) |(>) |(>) |(>)
+------------+------------+------------+------------+------------+------------
```
Now with a tape of `1 0 0`:
```
| 1 ( 0) 0 | 1 0 ( 0)|( 0) 0 0 | 0 ( 0) 0 | 0 0 ( 0)|( 0) 0 0
|([)-] |[-] |[-] |[-] |[-] |[-]
|> |> |> |> |> |>
+------------+------------+------------+------------+------------+------------
| 1 ( 0) 0 | 1 0 ( 0)|( 0) 0 0 | 0 ( 0) 0 | 0 0 ( 0)|( 0) 0 0
|([)-] |[-] |[-] |[-] |[-] |[-]
|> |> |> |> |> |>
+------------+------------+------------+------------+------------+------------
| 1 ( 0) 0 | 1 0 ( 0)|( 0) 0 0 | 0 ( 0) 0 | 0 0 ( 0)|( 0) 0 0
|([)-] |[-] |[-] |[-] |[-] |[-]
|> |> |> |> |> |>
+------------+------------+------------+------------+------------+------------
| 1 ( 0) 0 | 1 0 ( 0)|( 0) 0 0 | 0 ( 0) 0 | 0 0 ( 0)|( 0) 0 0
|([)-] |[-] |[-] |[-] |[-] |[-]
|> |> |> |> |> |>
+------------+------------+------------+------------+------------+------------
| 1 ( 0) 0 | 1 0 ( 0)|( 0) 0 0 | 0 ( 0) 0 | 0 0 ( 0)|( 0) 0 0
|([)-] |[-] |[-] |[-] |[-] |[-]
|> |> |> |> |> |>
+------------+------------+------------+------------+------------+------------
|( 1) 0 0 |( 1) 0 0 |( 0) 0 0 |( 0) 0 0 |( 0) 0 0 |( 0) 0 0
|([)-] |[(-)] |[-(]) |[-] |[-] |[-]
|(>) |(>) |(>) |(>) |(>) |(>)
+------------+------------+------------+------------+------------+------------
```
There were a couple things that weren't clearly explained in the spec, such as the fact that the 3-cell tape wraps around.
---
As a bonus, here is the visualization of the (`>+`, `[-]`) example:
```
|( 0) 0 0 |( 0) 0 0 |( 1) 1 0
|(>)+ |>(+) |>+
|[-] |[-] |[-(])
+------------+------------+------------
|( 0) 0 0 | 0 0 ( 0)| 0 1 ( 1)
|(>)+ |>(+) |>+
|[-] |[-] |[(-)]
+------------+------------+------------
|( 0) 0 0 | 0 ( 0) 0 | 0 ( 1) 0
|(>)+ |>(+) |>+
|([)-] |([)-] |([)-]
+------------+------------+------------
```
And one of the (`>+`, `+>`) example:
```
|( 1) 0 0 | 1 1 ( 0)| 1 3 ( 1)
|(>)+ |>(+) |>+
|+(>) |+(>) |+(>)
+------------+------------+------------
|( 0) 0 0 | 0 ( 0) 0 | 0 ( 1) 0
|(>)+ |>(+) |>+
|(+)> |(+)> |(+)>
+------------+------------+------------
```
Note that the upper-right corner is different than what you have listed, I think this is an error in your example because my code matches every other example I've tried.
] |
[Question]
[
Here's an ASCII pumpkin carved into a Jack-o-Lantern. Isn't it cute?
```
((^v^))
```
Here's an ASCII ghost. Look how spooky it is!
```
\{O.O}/
```
Obviously, the pumpkins have to be on the ground, with a space between them so they don't rot.
Ghosts, however, like to stand on top of pumpkins, so they're *even spookier*. However, they have to stand on *two* pumpkins, else their ghostly weight will crush the pumpkin beneath them. But, due to how their ghostly *magic* works, multiple ghosts can stack and share pumpkins, provided that the ghosts are either split evenly on the lower pumpkins or the lower ghosts. In other words, forming a shape like a [human pyramid](https://en.wikipedia.org/wiki/Human_pyramid). Note that ghosts can't stack on ghosts unless there's a pumpkin underneath (that's how the magic works).
Given two non-negative integers, `g` and `p`, representing the number of `g`hosts and `p`umpkins, output the most-compact left-most formation possible, following the above pyramid stacking rules. Leftover pumpkins and ghosts (that is, those not forming the pyramid) go on the ground to the right.
For clarification, these formations are OK (blank newline separated), and serve as example I/O:
```
0p 1g
\{O.O}/
1p 0g
((^v^))
1p 1g
((^v^)) \{O.O}/
2p 1g
\{O.O}/
((^v^)) ((^v^))
2p 2g
\{O.O}/
((^v^)) ((^v^)) \{O.O}/
3p 1g
\{O.O}/
((^v^)) ((^v^)) ((^v^))
3p 2g
\{O.O}/ \{O.O}/
((^v^)) ((^v^)) ((^v^))
3p 3g
\{O.O}/
\{O.O}/ \{O.O}/
((^v^)) ((^v^)) ((^v^))
0p 4g
\{O.O}/ \{O.O}/ \{O.O}/ \{O.O}/
3p 0g
((^v^)) ((^v^)) ((^v^))
7p 6g
\{O.O}/
\{O.O}/ \{O.O}/
\{O.O}/ \{O.O}/ \{O.O}/
((^v^)) ((^v^)) ((^v^)) ((^v^)) ((^v^)) ((^v^)) ((^v^))
```
These formations are Not OK
```
\{O.O}/
((^v^))
\{O.O}/
((^v^))
((^v^)) ((^v^)) \{O.O}/
\{O.O}/
\{O.O}/
((^v^)) ((^v^))
\{O.O}/
\{O.O}/ ((^v^)) ((^v^))
((^v^))
((^v^)) ((^v^))
\{O.O}/
((^v^)) ((^v^))
```
### Input
Two non-negative integers [in any convenient format](https://codegolf.meta.stackexchange.com/q/2447/42963). At least one of the numbers will be non-zero. You can take the inputs in either order (i.e., in the examples I had pumpkins first) -- please specify how you take input in your answer.
### Output
An ASCII-art representation of the ghosts and pumpkins, following the above rules. Leading/trailing newlines or other whitespace are optional, provided that the ghosts and pumpkins line up appropriately.
### Rules
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* [Standard loopholes](https://codegolf.meta.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 (ES7), ~~166~~ ~~164~~ 159 bytes
*Saved 5 bytes thanks to Neil*
```
f=(p,g,j=(g*2)**.5+.5|0,G=j>p-1?p?p-1:0:j,P=`
`,i=~j?g-G*++G/2:G,n=i>0?i>g?g:i:0)=>p|g?f(0,g-n,-1,G-1,P+' ')+P+'((^v^)) '.repeat(p)+'\\{O.O}/ '.repeat(n):''
```
### Formatted and commented
```
f = ( // given:
p, // - p = number of pumpkins
g, // - g = number of ghosts
j = (g * 2) ** .5 + .5 | 0, // - j = ceil(triangular root of g)
G = j > p - 1 ? p ? p - 1 : 0 : j, // - G = max(0, min(p - 1, j))
P = '\n', // - P = padding string (+ line-break)
i = ~j ? // - i =
g - G * ++G / 2 // first iteration: g - G * (G + 1) / 2
: G, // next iterations: G
n = i > 0 ? i > g ? g : i : 0 // - n = max(0, min(i, g)) = number of
) => // ghosts to print at this iteration
p | g ? // if there's still something to print:
f( // do a recursive call with:
0, // - no pumpkin anymore
g - n, // - the updated number of ghosts
-1, // - j = -1 (so that ~j == 0)
G - 1, // - one less ghost on the pyramid row
P + ' ' // - updated padding string
) + //
P + // append padding string
'((^v^)) '.repeat(p) + // append pumpkins
'\\{O.O}/ '.repeat(n) // append ghosts
: '' // else: stop
```
### Underlying math
The tricky part is to find out the optimal width `G` of the ghost pyramid.
The number of ghosts `g` in such a pyramid is given by:
```
g = 1 + 2 + 3 + ... + G = G(G + 1) / 2
```
Reciprocally, the width of a pyramid containing `g` ghosts is the real root of the resulting quadratic equation:
```
G² + G - 2g = 0
Δ = 1² - 4(-2g)
Δ = 8g + 1
G = (-1 ± √Δ) / 2
```
Which leads to the following real root (also known as the *triangular root*):
```
G = (√(8g + 1) - 1) / 2
```
However, the width of the pyramid is also limited by the number of pumpkins: we can have no more than `p-1` ghosts over `p` pumpkins. Hence the final formula used in the code:
```
j = ⌈(√(8g + 1) - 1) / 2⌉
G = max(0, min(p - 1, j))
```
### ES6 version, ~~173~~ ~~171~~ 166 bytes
```
f=(p,g,j=Math.pow(g*2,.5)+.5|0,G=j>p-1?p?p-1:0:j,P=`
`,i=~j?g-G*++G/2:G,n=i>0?i>g?g:i:0)=>p|g?f(0,g-n,-1,G-1,P+' ')+P+'((^v^)) '.repeat(p)+'\\{O.O}/ '.repeat(n):''
```
### Test cases (ES6)
```
f=(p,g,j=Math.pow(g*2,.5)+.5|0,G=j>p-1?p?p-1:0:j,P=`
`,i=~j?g-G*++G/2:G,n=i>0?i>g?g:i:0)=>p|g?f(0,g-n,-1,G-1,P+' ')+P+'((^v^)) '.repeat(p)+'\\{O.O}/ '.repeat(n):''
console.log(f(0, 1));
console.log(f(1, 0));
console.log(f(1, 1));
console.log(f(2, 1));
console.log(f(2, 2));
console.log(f(3, 1));
console.log(f(3, 2));
console.log(f(3, 3));
console.log(f(0, 4));
console.log(f(3, 0));
console.log(f(7, 6));
```
[Answer]
# Perl, 246 bytes (newlines are not part of the code and are provided solely for readability)
```
($c,$d)=<>=~/(\d+)/g;
$p="((^v^)) ";$g="\\{O.O}/ ";
for($f[0]=$c;$d>0;$d--){$f[$b+1]+1<$f[$b]?$f[++$b]++:$f[$b]++;$f[0]+=$d,$d=0 if$b==$c-1;$f[$b]==1?$b=0:1}
$h[0]=($p x$c).$g x($f[0]-$c);$h[$_].=$"x(4*$_).$g x$f[$_]for(1..$#f);
say join$/,reverse@h;
```
Accepts two numbers: pumpkins first, followed by ghosts.
Sample input:
```
5 20
```
Sample output:
```
\{O.O}/
\{O.O}/ \{O.O}/
\{O.O}/ \{O.O}/ \{O.O}/
\{O.O}/ \{O.O}/ \{O.O}/ \{O.O}/
((^v^)) ((^v^)) ((^v^)) ((^v^)) ((^v^)) \{O.O}/ \{O.O}/ \{O.O}/ \{O.O}/ \{O.O}/ \{O.O}/ \{O.O}/ \{O.O}/ \{O.O}/ \{O.O}/ \{O.O}/
```
] |
[Question]
[
A nearly massless cat is dropped in space (don't worry, with a space suit and everything) at the point `(x, y, z)` with velocity `(vx, vy, vz)`. There is an fixed, infinitely dense planet (with volume of 0) at the point `(0, 0, 0)` and it attracts objects at distance `r` with acceleration `1/r^2`. According to Newtonian gravity, where does the object go after time `t`?
Nearly massless in this case means you are outputting the value of `lim (mass --> 0) <position of cat>`. The mass is affected by the planet's gravity, but the planet is not affected by the cat's gravity. In other words, the central body is fixed.
This is somewhat similar to [Code Golf: What is the spaceship's fate? [floating point version]](https://codegolf.stackexchange.com/questions/5520/code-golf-what-is-the-spaceships-fate-floating-point-version), but this is different because it is measuring accuracy.
You may implement a solution based on a simulation, which must run in less than 3 seconds, OR you may implement a program that gives an exact value (must also run in less than 3 seconds). See scoring details below. If you implement a simulation, it does not have to be exact, but your score will be lower because of the inaccuracy.
**Input**: `x y z vx vy vz t`, not necessarily integers representing x, y, z coordinates, velocity in the x, y, and z directions and time respectively. It is guaranteed that the speed of the cat is strictly less than the escape velocity at that altitude. Input may be taken from anywhere, including parameters to a function. The program must run in less than three seconds on my laptop for `t < 2^30`, which means, if you are running a simulation, you must adjust your timestep accordingly. If you are planning on hitting the 3 second limit for every test case, make sure there is a tuneable parameter that can make it more accurate/less accurate for speed gains, so that I can make it run in three seconds on my computer.
**Output**: `x y z`, the position after time `t`.
Since the two-body problem can be solved perfectly, it is in theory possible to get a perfect, correct answer.
**Scoring**: For any test case, the error is defined to be the distance between your output and the "true" output. The true output is defined to be the one that the test case snippet generates. If the error is less than `10^(-8)`, the error is rounded down to zero. Your score is the average error on 100 (or more) random test cases. If you write a perfectly accurate answer, you should get a score of 0; lowest score wins, and ties will be broken by code length.
**Test cases**:
```
1 0 0 0 -1 0 1000000000 --> 0.83789 -0.54584 0
```
In this case , the orbit is perfectly circular with period 2\*pi, so after circling 159154943 times, the cat ends up at approximately (0.83789, -0.54584). This isn't a test case your code will be tested on; if you submit a perfectly accurate answer, however, you may want to test it on this.
The snippet below generates random additional test cases and will be used to judge submissions; let me know if there is a bug with this:
```
var generateTestCase = function() {
var periapsis = Math.random() * 10 + 0.5;
var circularVelocity = Math.sqrt(1 / periapsis);
var escapeVelocity = Math.sqrt(2) * circularVelocity;
var v = Math.random() * (escapeVelocity - circularVelocity) + circularVelocity;
var a = 1 / (2 / periapsis - v * v);
var ecc = (a - periapsis) * (2 / periapsis - v * v);
var semiLatus = a * (1 - ecc * ecc);
var angM = Math.sqrt(semiLatus);
var period = 2 * Math.PI * a * Math.sqrt(a);
var getCoordAfterTime = function(t) {
var meanAnomaly = t / (a * Math.sqrt(a));
function E(e, M, n) {
var result = M;
for (var k = 1; k <= n; ++k) result = M + e * Math.sin(result);
return result;
}
var eAnomaly = E(ecc, meanAnomaly, 10000);
var radius = a * (1 - ecc * Math.cos(eAnomaly));
var theta = Math.acos((semiLatus / radius - 1) / ecc);
if (t > period / 2) theta = -theta;
return {
r: radius,
t: theta,
x: radius * Math.cos(theta),
y: radius * Math.sin(theta)
};
}
var t1 = Math.random() * period;
var p1 = getCoordAfterTime(t1);
var v1 = Math.sqrt(2 / p1.r - 1 / a);
var velocityAngle1 = Math.acos(angM / p1.r / v1);
var horizontal = Math.atan(-p1.x / p1.y);
if (t1 < period / 2) {
velocityAngle1 *= -1;
horizontal += Math.PI;
}
var vx = v1 * Math.cos(horizontal + velocityAngle1);
var vy = v1 * Math.sin(horizontal + velocityAngle1);
var t2 = Math.random() * period;
var p2 = getCoordAfterTime(t2);
var v2 = Math.sqrt(2 / p2.r - 1 / a);
var dummyPeriods = Math.floor(Math.random() * 100) * period + period;
var rotate = function(x, y, z, th1, th2, th3) {
var x1 = x * Math.cos(th1) - y * Math.sin(th1);
var y1 = x * Math.sin(th1) + y * Math.cos(th1);
var z1 = z;
var x2 = x1 * Math.cos(th2) + z1 * Math.sin(th2);
var y2 = y1;
var z2 = -x1 * Math.sin(th2) + z1 * Math.cos(th2);
var x3 = x2;
var y3 = y2 * Math.cos(th3) - z2 * Math.sin(th3);
var z3 = y2 * Math.sin(th3) + z2 * Math.cos(th3);
return [x3, y3, z3];
}
var th1 = Math.random() * Math.PI * 2,
th2 = Math.random() * 2 * Math.PI,
th3 = Math.random() * 2 * Math.PI;
var input = rotate(p1.x, p1.y, 0, th1, th2, th3)
.concat(rotate(vx, vy, 0, th1, th2, th3))
.concat([t2 - t1 + dummyPeriods]);
var output = rotate(p2.x, p2.y, 0, th1, th2, th3);
return input.join(" ") + " --> " + output.join(" ");
}
var $ = function(x) {
return document.querySelector(x);
}
$("#onetestcase").onclick = function() {
$("#result1").innerHTML = generateTestCase();
}
$("#huntestcases").onclick = function() {
var result = [];
for (var i = 0; i < 100; ++i) result.push(generateTestCase());
$("#result100").innerHTML = result.join("\n");
}
```
```
<div>
<button id="onetestcase">Generate</button>
<pre id="result1"></pre>
</div>
<div>
<button id="huntestcases">Generate 100 test cases</button>
<pre id="result100"></pre>
</div>
```
[Answer]
# Python 3.5 + NumPy, exact, 186 bytes
```
from math import*
def o(r,v,t):
d=(r@r)**.5;W=2/d-v@v;U=W**1.5;b=[0,t*U+9]
while 1:
a=sum(b)/2;x=1-cos(a);y=sin(a)/U;k=r@v*x/W+d*y*W
if a in b:return k*v-r*x/W/d+r
b[k+a/U-y>t]=a
```
This is an exact solution, using a formula I engineered based on [Jesper Göranssonhis, “Symmetries of the Kepler problem”, 2015](http://math.ucr.edu/home/baez/mathematical/Goransson_Kepler.pdf). It uses a binary search to solve the transcendental equation Ax + B cos x + C sin x = D, which has no closed-form solution.
The function expects the position and velocity to be passed in as NumPy arrays:
```
>>> from numpy import array
>>> o(array([1,0,0]),array([0,-1,0]),1000000000)
array([ 0.83788718, -0.54584345, 0. ])
>>> o(array([-1.1740058273269156,8.413493259550673,0.41996042044140003]),array([0.150014367067652,-0.09438816345868332,0.37294941703455975]),7999.348650387233)
array([-4.45269544, 6.93224929, -9.27292488])
```
[Answer]
# Javascript
This is just to get the ball rolling, since no one seems to be posting answers. Here is a very naive, simple way that can be improved a lot:
```
function simulate(x, y, z, vx, vy, vz, t) {
var loops = 1884955; // tune this parameter
var timestep = t / loops;
for (var i = 0; i < t; i += timestep) {
var distanceSq = x*x + y*y + z*z; // distance squared from origin
var distance = Math.sqrt(distanceSq);
var forceMag = 1/distanceSq; // get the force of gravity
var forceX = -x / distance * forceMag;
var forceY = -y / distance * forceMag;
var forceZ = -z / distance * forceMag;
vx += forceX * timestep;
vy += forceY * timestep;
vz += forceZ * timestep;
x += vx * timestep;
y += vy * timestep;
z += vz * timestep;
}
return [x, y, z];
}
```
Testing:
```
simulate(1, 0, 0, 0, -1, 0, Math.PI*2) --> [0.9999999999889703, -0.0000033332840909716455, 0]
```
Hey, that's pretty good. It has an error of about 3.333\*10^(-6) which isn't enough for it to be rounded down... it's close.
Just for fun:
```
console.log(simulate(1, 0, 0, 0, -1, 0, 1000000000))
--> [-530516643639.4616, -1000000000.0066016, 0]
```
Oh well; so it's not the best.
And on a random test case from the generator:
```
simulate(-1.1740058273269156,8.413493259550673,0.41996042044140003,0.150014367067652,-0.09438816345868332,0.37294941703455975,7999.348650387233)
--> [-4.528366392498373, 6.780385554803544, -9.547824236472668]
Actual:[-4.452695438880813, 6.932249293597744, -9.272924876103785]
```
With an error of only approximately 0.32305!
This can be improved a lot by using something like Verlet integration or some fancy algorithm. In fact, those algorithms may even get perfect scores, despite being simulations.
] |
[Question]
[
[Van der Waerden's theorem](https://en.wikipedia.org/wiki/Van_der_Waerden%27s_theorem) says that
>
> For any given positive integers `r` and `k`, there is some number `N` such
> that if the integers `{1, 2, ..., N}` are colored, each with one of `r`
> different colors, then there are at least `k` integers in arithmetic
> progression all of the same color. The least such `N` is the Van der
> Waerden number `W(r, k)`.
>
>
>
Your goal is to compute the Van der Waerden number `W(r, k)` given positive-integer inputs `r` and `k`. Fewest bytes wins.
Beware that this function grows [extremely quickly](https://wwwold.cs.umd.edu/~gasarch/TOPICS/vdw/gowers-sz-4AP.pdf) and is time-consuming to compute. Even `W(4, 4)` is unknown. You may assume your code runs on an ideal computer with unlimited resources (time, memory, stack depth, etc). Your code must theoretically give the right answer even for values for which the answer is not known.
Built-ins that compute this function are not allowed.
**Example**
For `r = 2` colors and progressions of length `k = 3`, there is a length-`8` sequence that avoids such a progression, i.e. `3` equally-spaced elements of the same color:
```
B R R B B R R B
```
But, there's no such length-`9` sequence, so `W(2, 3) == 9`. For instance,
```
R B B R B R R B R
^ ^ ^
```
contains the length-`3` same-color arithmetic progression shown.
**Test cases**
You'll probably only be able to test small cases.
```
+-----+-----+-----+-----+-----+-----+------+
| | k=1 | k=2 | k=3 | k=4 | k=5 | k=6 |
+-----+-----+-----+-----+-----+-----+------+
| r=1 | 1 | 2 | 3 | 4 | 5 | 6 |
| r=2 | 1 | 3 | 9 | 35 | 178 | 1132 |
| r=3 | 1 | 4 | 27 | 293 | | |
| r=4 | 1 | 5 | 76 | | | |
+-----+-----+-----+-----+-----+-----+------+
```
```
var QUESTION_ID=71776,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/71776/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```
[Answer]
## Python 3.5, ~~125~~ ~~124~~ 119 bytes
```
f=lambda r,k,*L:any(L[:x*k:x]==k*(*{*L[:x*k:x]},)for x in range(1,len(L)+1))*len(L)or max(f(r,k,i,*L)for i in range(r))
```
It's funny because, over the course of golfing this, the program actually got *more* efficient. Anything beyond `f(2,4)` or `f(3,3)` still takes forever, though.
### Explanation
The initial version checked whether a sequence contained a progression of length `k` by trying all possible start indices and steps.
```
def f(r,k,L=[]):
for i in range(len(L)):
for j in range(len(L)):
if len(set(L[i::j+1]))==1 and len(L[i::j+1])==k:
return len(L)
return max(f(r,k,L+[i])for i in range(r))
```
The golfed version only needs to try all possible steps since it *prepends* new sequence elements. The `x*k` cap is to take care of cases like `[0, 0, 1]`, which contains a progression of length 2 but would not satisfy the uniqueness check uncapped.
As for the check
```
L[:x*k:x]==k*(*{*L[:x*k:x]},)
```
On the first pass of the golfed version, when `L` is empty, `len(L)` is 0. Thus the second half of the `or` will always be executed. After that `L` is non-empty, so `{*L[:x*k:x]}` (which is just Python 3.5 for `set(L[:x*k:x])`) will have at least one element.
Since `L[:x*k:x]` can have at most `k` elements and for `L` non-empty `k*(*{*L[:x*k:x]},)` has at least `k` elements, the two can only be equal when there are exactly `k` elements in both. For this to happen `{*L[:x*k:x]}` must have exactly one element, i.e. we only have one colour in our progression.
] |
[Question]
[
From a challenge in a programming book long ago, PNZ is a game where the user must guess three unique digits in the correct order.
**Rules**:
1. A random 3 digit number with no repeating digits is generated. (This is what the user is trying to guess)
2. The user inputs a guess of 3 digits, which is to be evaluated by the program.
3. Output a "P" for every correct digit in a correct place.
4. Output a "N" for every correct digit in an incorrect place.
5. Output a "Z" only if no digits are correct.
6. Continue accepting inputs until all digits are correct and in the
correct place, then output "PPP" followed by the number of guesses
it took on a new line.
**Note**:
* A "Correct digit" means that one of the digits in the guess is also
one of the digits in the random 3 digit number.
* A "Correct place" means it is a "Correct digit" AND is in the same place as the 3 digit random number.
* The order of outputting should be all "P"'s first, then "N"'s, or only "Z" if nothing is correct.
* If an input contains repeating digits, "P" takes priority over "N" (Example: `Number: 123` `Input: 111` `Output: P`)
* (OPTIONAL) Inputs that are not exactly 3 digits in length should not be evaluated, nor count towards the running total of guesses
Example if the generated digits were 123
```
> 147
P
> 152
PN
> 126
PP
> 123
PPP
4
```
Example if the generated digits were 047
```
> 123
Z
> 456
N
> 478
NN
> 947
PP
> 047
PPP
5
```
This is CodeGolf, so the shortest program wins!
[Answer]
# JavaScript (ES6), ~~195~~ ~~187~~ 184 bytes
**Edit** Saved 8 bytes thx @Neil
**Edit** Saved 3 bytes thx @user81655
(newlines counted as 1 byte)
```
d=[...'0123456789']
x=[10,9,8].map(l=>d.splice(Math.random()*l,1))
for(c=p=a='';!p[2];++c)g=prompt(a),n=p='',x.map((d,i)=>d-g[i]?~g.search(d)?n+='N':0:p+='P'),a=p+n||'Z'
alert(a+' '+c)
```
**Test**
```
d=[...'0123456789']
x=[10,9,8].map(l=>d.splice(Math.random()*l,1))
for(c=p=a='';!p[2];++c)
g=prompt(a),
n=p='',
x.map((d,i)=>
d-g[i]?~g.search(d)?n+='N':0:p+='P'
),
a=p+n||'Z'
alert(a+' '+c)
```
[Answer]
## PowerShell v2+, ~~177~~ ~~231~~ 168 bytes
```
$g=-join(0..9|Random -c 3);for($c=0;$o-ne"PPP";$c++){$n=$p='';$i=read-host;$o=-join(0..2|%{((("","N")[$i.IndexOf($g[$_])-ge0]),"P")[$g[$_]-eq$i[$_]]}|sort -des);($o,"Z")[!$o]}$c
```
Oddly, I was able to golf the fixed version to be a shorter length than the unfixed version ... o.O
Many thanks to @[edc65](https://codegolf.stackexchange.com/users/21348/edc65) for his assistance and inspiration!
### Explanation:
```
$g=-join(0..9|Random -c 3) # Create an array @(0,1,2,...9) and choose 3 distinct elements
for($c=0;$o-ne"PPP";$c++){ # Loop until output = "PPP", incrementing $count each time
$i=read-host # Read input from the user
$o=-join(0..2|%{((("","N")[$i.IndexOf($g[$_])-ge0]),"P")[$g[$_]-eq$i[$_]]}|sort -des)
# OK, this is the convoluted part. We're constructing an array of "N", "P", or "",
# sorting them by descending order (so the P's are first), and then joining them
# together into a string. The array is constructed by essentially an if/elseif/else
# statement that is evaluated three times thanks to the 0..2|%{} loop.
# Starting from the innermost, we choose between "" and "N" based on whether the
# input number has the current-digit of the secret number somewhere within it. We
# then choose between that or "P" based on whether it's the _current_ digit of the
# user input number.
($o,"Z")[!$o]
# Here we output either $o from above or "Z" based on whether $o is empty
}
$c # The loop finished (meaning the user guessed), output $count
```
### Example run:
```
PS C:\Tools\Scripts\golfing> .\pnz.ps1
123
N
111
Z
222
P
452
PN
562
NN
275
PN
258
PPP
7
```
[Answer]
# [R](https://www.r-project.org/),~~178~~ 166 bytes
```
y=!(s<-sample(48:57,3))
while(any(y!=s)){F=F+1
y<-utf8ToInt(readline())
cat(rep("P",p<-sum(y==s)),rep("N",n<-sum(y%in%s)-p
),if(!(n+p))"Z","
",if(all(y==s))F,sep="")}
```
[Try it online!](https://tio.run/##LYzBisIwFEX3/YrXJ8J7mC6GGVHE7LQgQjNoQXAXNGIgpqGpSBjm2zvt4PIc7rltP4GN2h6hUjWc1GEPqoJ6p6CAuk1gPXR3Awe4ND42zvRJ5hTXRdSP4Ax9LVfzhfhkzl53O7D2iVIuI/NPKcvZR5bWxbO7Letm5ztqjb466w0N@4seORB@owjD3/NBSY6h@LcVCv@2U@unkYuQsbA3ysnPAjOeUWCGo9HOvdNSRBMkIv/2/R8 "R – Try It Online")
TIO link is just for byte count - try this in your R console! (or let me know if there is an alternate option).
See history for less-golfed, more readable version.
] |
[Question]
[
### Introduction
For the ones wondering what [Befunge](https://esolangs.org/wiki/Befunge) exactly is, it is a two-dimensional stack based language made in 1993 by Chris Pressy. I made **7 brain teasers** that need to be solved in **Befunge-93**. This is quite an experimental challenge, but I thought it's worth a shot :). A full list of all commands used in Befunge-93 can be found [here](https://esolangs.org/wiki/Befunge#Instructions).
### How to play?
The task is a bit like a cops-and-robbers without the cops. It's just basically cracking submissions in order to get points. Every puzzle contains question marks. These must be replaced by any printable ascii character in the range `32 - 127`, that includes whitespace. See the following example:
```
??????@
```
Given is that the output must be `hi`. After some puzzling, we can find out that the solution was:
```
"ih",,@
```
**But!** You **do not** give the solution. That is for the prevention of cheating. You don't post the solution, but the **hash**. The hash is generated with the following snippet:
```
String.prototype.hashCode = function() { var namevalue = document.getElementById("inputname").value; var namenumber = 123;for (var character = 0; character < namevalue.length; character++) {namenumber += namevalue.substring(0, 1).charCodeAt(0);}var hash = 123 + namenumber, i, chr, len;if (this.length === 0) {return 0;}for (i = 0, len = this.length; i < len; i++) {chr = this.charCodeAt(i);hash = ((hash << 5) - hash) + chr; hash |= 0; }hash = Math.abs(hash);if ((hash).toString(16).length < 20) {for (var rand = 123; rand < 199; rand++) {hash = hash * rand;if ((hash).toString(16).length >= 20) { break; }}}return (hash).toString(16).substring(2, 12);};function placeHash() { var pretext = document.getElementById("inputhash").value; var resultinghash = pretext.hashCode(); document.getElementById("resulthash").innerHTML = 'Your hash: <span class="hashtext">' + resultinghash + "</span>";}
```
```
p {font-family: monospace;color: black;} .hashtext{color: red;font-weight:bold}
```
```
<div class="container"><p>Personal hash generator:<p><textarea id="inputhash" placeholder="Your submission" cols="40" rows="4"></textarea><br><textarea id="inputname" placeholder="Your name" cols="40" rows="1"></textarea><br><button class="hashbutton" onclick="placeHash()">Generate Hash!</button><br><p id="resulthash">Your hash:</p></div><!-- Created by Adnan -->
```
### How to use the snippet?
* First, paste the solution into the submission section
* Second, enter your username (nothing else, this will actually be verified after the time limit)
* Third, press **Generate Hash!** to obtain your *personal* hash.
* Copy and paste the hash into your submission.
### The puzzles
**Puzzle 1** (Score: 3)
```
??
??? ?
??????????
@
```
Output (note the trailing whitespace):
```
1 2 3 4 5 6 7 8 9 10
```
---
**Puzzle 2** (Score: 3)
```
???? ?
??????????
?? ?
@
```
Output:
```
abcdefghijklmnopqrstuvwxyz
```
---
**Puzzle 3** (Score: 5)
```
?????????
????? ???
? ?
? ? ? ?
?
? ?
?????? ? ?
? ? ?
? ? @
??????? ?
? ?
???? ??
? ??
```
Output:
```
Hello World!
```
---
**Puzzle 4** (Score: 2)
```
??????@
```
Output (note the trailing whitespace):
```
123
```
---
**Puzzle 5** (Score: 5)
```
?
?????
???@?????
??????
?????????
```
Output:
```
Befunge
```
---
**Puzzle 6** (Score: 5)
```
? ? ?
?
??????????
?
?
???????? ??????????????
?????"floG edoC dna selzzuP gnimmargorP "??????
@
```
Output:
```
###################################
Programming Puzzles and Code Golf
###################################
```
---
**Puzzle 7** (Score: 3)
```
???? ?????
???????
@???????
```
Output:
```
012345678910
```
---
* This is [code-challenge](/questions/tagged/code-challenge "show questions tagged 'code-challenge'"), the person with the most amount of points wins!
* In case of a tie, the person who submitted *all* submissions first, wins.
* The **last day for submission** is **January 10 UTC**. After that, you have 2 days to post the full solution, with the hashes already included. These will be verified :).
### How to post?
Use the following snippet to post your submission:
```
#N solutions:
Puzzle 1: `[hash 1]`
Puzzle 2: `[hash 2]`
etc.
```
It is not necessary to solve the puzzles in order. **All programs have been tested [here](http://www.quirkster.com/iano/js/befunge.html)** and will be used for verification.
Good luck!
[Answer]
# 7 solutions, 26 points
I'm typing this on my phone, because I don't have access to my computer currently. I actually had to work out Puzzle 6 by pen & paper.
### Puzzle 1 (Score **3**): `4f52d5b243`
```
1v
v:< <
>.1+:56+-|
@
```
This one is fairly straight forward. Get a `1` on the stack, then print-increment-compare-loop until `11` is hit.
### Puzzle 2 (Score **3**): `85226eba20`
```
"`" v
v"z":,:+1<
>- |
@
```
Basically the same as the previous one, just with characters instead of numbers. Used a different IP route though.
### Puzzle 3 (Score **5**): `1ff5bcb1d9`
```
"!dlroW"v
>,,,, ,,v
, "
, ? ,
o
l
??,??? l
, e
? " @
??^,"H" <
? ?
???? ??
? ??
```
Here I cheaped out a little bit. Push the string to the stack and print characters manually, navigating through the spaces. I had loads of extra room, so I just left most of the question marks in. Note the trailing spaces on rows 6 to 8, I didn't remove them when calculating the hash.
### Puzzle 4 (Score **2**): `f8b7bdf741`
```
"{". @
```
Really simple, just get the character with the correct code and print as a number, with two free spaces.
### Puzzle 5 (Score **5**): `c4db4b6af9`
```
v
??"??
#,_@e">>:
<"B"<^
ung"<^"ef
```
This was a fun one to get right. May not work correctly on some interpreters due to wrapping strings & jumps, works on the linked one. Basically, the code pushes the output string and then enters the standard printing loop, wrapping on the sides.
### Puzzle 6 (Score **5**): `356e912eec`
```
1 v
#
v??v_
5
75<^ p15:-1g15,:*
>5+:,"floG edoC dna selzzuP gnimmargorP ">:#,_@
@
```
Now this was the "masterpiece". I [actually took a piece of paper](https://i.stack.imgur.com/cwBJ6.jpg) and spent some time on this. (Actually, I did some extra work by missing the space in the string when copying.) Note the trailing spaces on row 4, I didn't remove them when calculating the hash.
The code works by first pushing a one to enter the main loop. The loop uses the `#` on the second line as a counter, and both prints and pushes a `#` on every iteration. After that a newline is printed and pushed. Next, the given string is pushed. Finally, the code enters a printing loop, which prints everything on the stack in reverse, which means the string, then the newline, and finally the remaining `#`s.
### Puzzle 7 (Score **3**): `0881fc2619`
```
"0"> :,1+v
|-":":<
@>"10",,
```
This is almost the same as Puzzle 2, but with a different route, different output characters, an additional `01` in the end and a quick wrap to finish it off.
[Answer]
## 4 solutions, 15 points
I hope I didn't mess up the trailing whitespace anywhere when generating the hashes.
### Puzzle 1 (Score **3**): `de1de4c4c8`
```
v
v< >
>1+:.:9`!|
@
```
### Puzzle 3 (Score **5**): `071cad0879`
```
"!dlroW"v
>,,,, ,,v
, "
, ,
o
l
, l
, e
" @
^,"H" <
```
### Puzzle 4 (Score **2**): `531940bc43`
```
"{". @
```
### Puzzle 5 (Score **5**): `5bafaed8e9`
```
^
v >,,
n"<@,, ,"
"e"^>,
uge"<^"Bf
```
] |
[Question]
[
A top-front-side puzzle is a puzzle where you are required to construct a 3-D shape of (usually cubic) blocks given three orthogonal views: a top view, a front view, and a side view.
For example, given a top, front, and side view as follows:
```
Top: Front: Side:
. . . . . . . . . . . .
. x x . . x x . . x x .
. x x . . x x . . x x .
. . . . . . . . . . . .
In this problem, the side view is taken from the right.
```
A 2x2x2 cube (with volume 8) would satisfy this solution, but it's doable in volume 4, if we have the following layer structure:
```
. . . . . . . .
. x . . . . x .
. . x . . x . .
. . . . . . . .
```
There are also some unsolvable arrangements. Take, for example:
```
Top: Front: Side:
. . . . . . . . . . . .
. . . . . . x . . . . .
. x . . . . . . . x . .
. . . . . . . . . . . .
```
If the top view says the block is second from the left, there's no way that can match the front view that says the block must be third from the left. So this arrangement is impossible.
---
Your task is to build a program that, given an arbitrary 4x4 top-front-side puzzle, attempts to solve it in the fewest number of cubes, or declares it unsolvable.
Your program will take as input a series of 48 bits, representing the top, front, and side views. They may be in any format you want (a 6-byte string, a string of 0's and 1's, a 12-digit hex number, etc.), but the order of the bits must map as such:
```
Top: 0x00 Front: 0x10 Side: 0x20
0 1 2 3 0 1 2 3 0 1 2 3
4 5 6 7 4 5 6 7 4 5 6 7
8 9 a b 8 9 a b 8 9 a b
c d e f c d e f c d e f
```
In other words, the bits go in a left-to-right, top-to-bottom order, in the top, then front, then side view.
Your program will then output either a series of 64 bits indicating the cubes in the 4x4x4 grid that are filled in, or indicate that the grid is unsolvable.
---
Your program will be scored by running a battery of 1,000,000 test cases.
The test data will be generated by taking the MD5 hashes of the integers "000000" through "999999" as strings, extracting the first 48 bits (12 hexits) of each of these hashes, and using them as input for the top-front-side puzzle. As an example, here are some of the test inputs and the puzzles they generate:
```
Puzzle seed: 000000 hash: 670b14728ad9
Top: Front: Side:
. x x . . . . x x . . .
x x x x . x . x x . x .
. . . . . x x x x x . x
x . x x . . x . x . . x
Puzzle seed: 000001 hash: 04fc711301f3
Top: Front: Side:
. . . . . x x x . . . .
. x . . . . . x . . . x
x x x x . . . x x x x x
x x . . . . x x . . x x
Puzzle seed: 000157 hash: fe88e8f9b499
Top: Front: Side:
x x x x x x x . x . x x
x x x . x . . . . x . .
x . . . x x x x x . . x
x . . . x . . x x . . x
```
The first two are unsolvable, while the last one has a solution with the following layers, front to back:
```
x . . . . . . . x x x . x x x .
. . . . x . . . . . . . . . . .
x . . . . . . . . . . . x x x x
x . . . . . . . . . . . x . . x
There are a total of 16 blocks here, but it can probably be done in less.
```
Your program's score will be determined by the following criteria, in descending order of priority:
* The highest number of solved cases.
* The lowest number of blocks required to solve those cases.
* The shortest code in bytes.
You must submit and calculate the score by yourself, which requires your program to be able to run through all 1,000,000 test cases.
[Answer]
# Python: 5360 test-cases solved using 69519 blocks, 594 bytes
This should be the optimal values.
## Approach:
First I'll test if the test-case is actual solvable. I do this by initializing a list of length 64 by ones and set all positions to zero, if there the corresponding pixel of the three views is zero.
Then I simple view at the puzzle from all 3 directions, and look if the views are the same as the input views. If there're equal, the puzzle is solvable (we already found the worst solution), otherwise it's unsolvable.
Then I do a branch-and-bound approach for finding the optimal solution.
**Branching:** I have a recursive function. The recursion depth tells how many values are fixed already. In each call of the function I call itself twice, if the value at the current index is 1 (this value can be 0 or 1 in the optimal solution), or once, if the value is 0 (it has to be zero in the optimal solution).
**Bounding:** I use two different strategies here.
1. I calculate the views from the 3 sides in each function call and look If they still match the input values. If they don't match, I don't call the function recursively.
2. I keep the best solution in memory. It there already more fixed ones in the current branch than in the best solution, I can already close that branch. Additionally I can estimate a lower bound for the number of activated blocks, which are not fixed. And the condition becomes `#number of activated fixed blocks + #lower bound of activated blocks (under the not fixed blocks) < #number of activated blocks in the best solution.`
Here's the Python code. It defines a function `f` which expects 3 lists containing 1s and 0s and returns either 0 (not solvable) or a list of 1s and 0s representing the optimal solution.
```
S=sum;r=range
def f(t,f,s):
for i in r(4):s[4*i:4*i+4]=s[4*i:4*i+4][::-1]
c=[min(t[i%16],f[(i//16)*4+i%4],s[i//4])for i in r(64)]
m=lambda:([int(S(c[i::16])>0)for i in r(16)],[int(S(c[i+j:i+j+16:4])>0)for i in r(0,64,16)for j in r(4)],[int(S(c[i+j:i+j+4])>0)for i in r(0,64,16)for j in r(0,16,4)])==(t,f,s)
Z=[65,0];p=[]
def g(k):
if k>63and S(c)<Z[0]:Z[:]=[S(c),c[:]]
if k>63or S(c[:k])+p[k]>=Z[0]:return
if c[k]:c[k]=0;m()and g(k+1);c[k]=1
m()and g(k+1)
for i in r(64):h,R=(i//16)*4+4,(i//4)%4;p+=[max(S(f[h:]),S(s[h:]))+max((R<1)*S(f[h+i%4-3:h]),S(s[h+R-3:h]))]
g(0);return Z[1]
```
The code length is 596 bytes/chars. And here's the test framework:
```
from hashlib import md5
from time import time
N = 1000000
start=time();count=blocks=0
for n in range(N):
bits = list(map(int,"{:048b}".format(int(md5("{:06}".format(n).encode("utf-8")).hexdigest()[:12], 16))))
result = f(bits[:16], bits[16:32], bits[32:])
if result:
count += 1
blocks += sum(result)
print("Seed: {:06}, blocks: {}, cube: {}".format(n, sum(result), result))
print()
print("{} out of {} puzzles are solvable using {} blocks.".format(count, N, blocks))
print("Total time: {:.2f} seconds".format(time()-start))
```
You can find an ungolfed version of the program [here](https://gist.github.com/jakobkogler/5825d25ea9d0103b1f25). It's also a little bit faster.
## Results:
5360 out of 1000000 puzzles are solvable. In total we need 69519 blocks. The number of blocks varies from 6 blocks to 18 blocks. The hardest puzzle took about 1 second to solve. It's the puzzle with the seed `"347177"`, which looks like
```
Top: Front: Side:
x x . . x x x x x . x .
x x x x x x x x x x x x
x x x x x x x x x x x x
x x . x x x x x x . x x
```
and has an optimal solution with 18 cubes. The following is a few from top for each of the layers:
```
Top 1: Top 2: Top 3: Top 4:
. . . . . x . . . x . . x . . .
. . x x . . x . x . . . . x x .
. . . . . . . x x x x . . . . .
x x . . x . . . . . . x . . . x
```
The total running time for all test-cases was about 90 seconds. I used PyPy to execute the my program. CPython (the default Python interpreter) is a bit slower, but also solves all puzzles in only 7 minutes.
You can find the complete output [here](https://gist.githubusercontent.com/jakobkogler/2455be29f609caf1e9b2/raw/top-front-side-output.txt): The output is self-explanatory. E.g. the output for the puzzle above is:
```
Seed: 347177, blocks: 18, cube: [0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1]
```
[Answer]
# 5360 cases solved with 69519 blocks; 923 bytes
This is also optimal. Call with an array of ones and zeroes. Throws a `NullPointerException` for invalid input. Some efficiency is sacrificed to golf it. It still completes within a reasonable time for all 1000000 test inputs.
```
import java.util.*;int[]a(int[]a){a b=new a(a);b=b.b(64);return b.d();}class a{List<int[]>a=new ArrayList();List b=new ArrayList();int c;a(int[]d){int e=0,f,g,h,i[]=new int[48];for(;e<64;e++){f=e/16;g=(e%16)/4;h=e%4;if(d[f+12-4*h]+d[16+f+g*4]+d[32+h+g*4]>2){i[f+12-4*h]=i[16+f+g*4]=i[32+h+g*4]=1;a.add(new int[]{f,g,h});c++;}}if(!Arrays.equals(d,i))throw null;b=f();}a(){}a b(int d){if(c-b.size()>d|b.size()<1)return this;a e=c();e.a.remove(b.get(0));e.b.retainAll(e.f());e.c--;e=e.b(d);d=Math.min(e.c,d);a f=c();f=f.b(d);return e.c>f.c?f:e;}a c(){a c=new a();c.a=new ArrayList(a);c.b=new ArrayList(b);c.b.remove(0);c.c=this.c;return c;}int[]d(){int[]d=new int[64];for(int[]e:a)d[e[2]*16+e[1]*4+e[0]]=1;return d;}List f(){List d=new ArrayList();int e,f,g;for(int[]h:a){e=0;f=0;g=0;for(int[]p:a)if(p!=h){e|=h[0]==p[0]&h[1]==p[1]?1:0;f|=h[0]==p[0]&h[2]==p[2]?1:0;g|=h[1]==p[1]&h[2]==p[2]?1:0;}if(e+f+g>2)d.add(h);}return d;}}
```
## Strategy:
I actually used to play this puzzle quite a bit when I was 10. This uses my approach.
**Step 1:**
Form the cube with the most blocks that fits the given views.
**Step 2:**
Create a list of removable pieces. (Any piece with that has another piece on the row its in, the column its in, and the beam its in.)
**Step 3:**
Test every possible way to keep or remove each removable piece. (Via recursive brute-force with pruning.)
**Step 4:**
Keep the best valid cube.
**Ungolfed:**
```
int[] main(int[] bits) {
Cube cube = new Cube(bits);
cube = cube.optimize(64);
return cube.bits();
}
class Cube {
List<int[]> points = new ArrayList();
List removablePoints = new ArrayList();
int size;
Cube(int[] bits) {
int i = 0,x,y,z,placed[] = new int[48];
for (; i < 64; i++) {
x = i / 16;
y = (i % 16) / 4;
z = i % 4;
if (bits[x + 12 - 4 * z] + bits[16 + x + y * 4] + bits[32 + z + y * 4] > 2) {
placed[x + 12 - 4 * z] = placed[16 + x + y * 4] = placed[32 + z + y * 4] = 1;
points.add(new int[]{x, y, z});
size++;
}
}
if (!Arrays.equals(bits, placed))
throw null;
removablePoints = computeRemovablePoints();
}
Cube() {
}
Cube optimize(int smallestFound) {
if (size - removablePoints.size() > smallestFound | removablePoints.size() < 1)
return this;
Cube cube1 = duplicate();
cube1.points.remove(removablePoints.get(0));
cube1.removablePoints.retainAll(cube1.computeRemovablePoints());
cube1.size--;
cube1 = cube1.optimize(smallestFound);
smallestFound = Math.min(cube1.size, smallestFound);
Cube cube2 = duplicate();
cube2 = cube2.optimize(smallestFound);
return cube1.size > cube2.size ? cube2 : cube1;
}
Cube duplicate() {
Cube c = new Cube();
c.points = new ArrayList(points);
c.removablePoints = new ArrayList(removablePoints);
c.removablePoints.remove(0);
c.size = size;
return c;
}
int[] bits() {
int[] bits = new int[64];
for (int[] point : points)
bits[point[2] * 16 + point[1] * 4 + point[0]] = 1;
return bits;
}
List computeRemovablePoints(){
List removablePoints = new ArrayList();
int removableFront, removableTop, removableSide;
for (int[] point : points) {
removableFront = 0;
removableTop = 0;
removableSide = 0;
for (int[] p : points)
if (p != point) {
removableFront |= point[0] == p[0] & point[1] == p[1] ? 1 : 0;
removableTop |= point[0] == p[0] & point[2] == p[2] ? 1 : 0;
removableSide |= point[1] == p[1] & point[2] == p[2] ? 1 : 0;
}
if (removableFront + removableTop + removableSide > 2)
removablePoints.add(point);
}
return removablePoints;
}
public String toString() {
String result = "";
int bits[] = bits(),x,y,z;
for (z = 0; z < 4; z++) {
for (y = 0; y < 4; y++) {
for (x = 0; x < 4; x++) {
result += bits[x + 4 * y + 16 * z] > 0 ? 'x' : '.';
}
result += System.lineSeparator();
}
result += System.lineSeparator();
}
return result;
}
}
```
**Full program:**
```
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Example cube:
*
* origin
* | ........
* | . ..
* | . top . .
* v. . .
* ........ . <- side
* . . .
* . front. .
* . ..
* ........
*
* / z
* /
* /
* .-----> x
* |
* |
* |
* V y
*/
public class PPCG48247 {
public static void main(String[] args) throws Exception{
MessageDigest digest = MessageDigest.getInstance("MD5");
int totalSolved = 0;
int totalCubes = 0;
for (int i = 0; i < 1000000; i++){
byte[] input = String.format("%06d", i).getBytes();
byte[] hash = digest.digest(input);
int[] bits = new int[48];
for (int j = 0, k = 0; j < 6; j++, k += 8){
byte b = hash[j];
bits[k] = (b >> 7) & 1;
bits[k + 1] = (b >> 6) & 1;
bits[k + 2] = (b >> 5) & 1;
bits[k + 3] = (b >> 4) & 1;
bits[k + 4] = (b >> 3) & 1;
bits[k + 5] = (b >> 2) & 1;
bits[k + 6] = (b >> 1) & 1;
bits[k + 7] = b & 1;
}
try {
int[] solution = new PPCG48247().a(bits);
totalSolved++;
for (int b : solution){
totalCubes += b;
}
} catch (NullPointerException ignored){}
}
System.out.println(totalSolved);
System.out.println(totalCubes);
}
int[] main(int[] bits) {
Cube cube = new Cube(bits);
cube = cube.optimize(64);
return cube.bits();
}
class Cube {
List<int[]> points = new ArrayList();
List removablePoints = new ArrayList();
int size;
Cube(int[] bits) {
int i = 0,x,y,z,placed[] = new int[48];
for (; i < 64; i++) {
x = i / 16;
y = (i % 16) / 4;
z = i % 4;
if (bits[x + 12 - 4 * z] + bits[16 + x + y * 4] + bits[32 + z + y * 4] > 2) {
placed[x + 12 - 4 * z] = placed[16 + x + y * 4] = placed[32 + z + y * 4] = 1;
points.add(new int[]{x, y, z});
size++;
}
}
if (!Arrays.equals(bits, placed))
throw null;
removablePoints = computeRemovablePoints();
}
Cube() {
}
Cube optimize(int smallestFound) {
if (size - removablePoints.size() > smallestFound | removablePoints.size() < 1)
return this;
Cube cube1 = duplicate();
cube1.points.remove(removablePoints.get(0));
cube1.removablePoints.retainAll(cube1.computeRemovablePoints());
cube1.size--;
cube1 = cube1.optimize(smallestFound);
smallestFound = Math.min(cube1.size, smallestFound);
Cube cube2 = duplicate();
cube2 = cube2.optimize(smallestFound);
return cube1.size > cube2.size ? cube2 : cube1;
}
Cube duplicate() {
Cube c = new Cube();
c.points = new ArrayList(points);
c.removablePoints = new ArrayList(removablePoints);
c.removablePoints.remove(0);
c.size = size;
return c;
}
int[] bits() {
int[] bits = new int[64];
for (int[] point : points)
bits[point[2] * 16 + point[1] * 4 + point[0]] = 1;
return bits;
}
List computeRemovablePoints(){
List removablePoints = new ArrayList();
int removableFront, removableTop, removableSide;
for (int[] point : points) {
removableFront = 0;
removableTop = 0;
removableSide = 0;
for (int[] p : points)
if (p != point) {
removableFront |= point[0] == p[0] & point[1] == p[1] ? 1 : 0;
removableTop |= point[0] == p[0] & point[2] == p[2] ? 1 : 0;
removableSide |= point[1] == p[1] & point[2] == p[2] ? 1 : 0;
}
if (removableFront + removableTop + removableSide > 2)
removablePoints.add(point);
}
return removablePoints;
}
public String toString() {
String result = "";
int bits[] = bits(),x,y,z;
for (z = 0; z < 4; z++) {
for (y = 0; y < 4; y++) {
for (x = 0; x < 4; x++) {
result += bits[x + 4 * y + 16 * z] > 0 ? 'x' : '.';
}
result += System.lineSeparator();
}
result += System.lineSeparator();
}
return result;
}
}
}
```
] |
[Question]
[
Following on from the [third order quine](https://codegolf.stackexchange.com/questions/4171/write-a-third-order-quine) challenge, your task is to write an [Ouroboros](http://en.wikipedia.org/wiki/Ouroboros) program that uses as many languages as possible.
That is, in language A, write a program pA which outputs program pB in language B. Program pB should output program pC in language C, and so on until eventually a program outputs the original program pA in language A.
No two languages in your loop can be the same or subsets or supersets of each other. **None of the programs in the loop may be identical.**
The longest chain of languages win. The length of the source code will be the tie-breaker.
Here is an example solution of length 3 given by Ventero.
```
s='print q<puts %%q{s=%r;print s%%s}>';print s%s
```
with Python generates this Perl snippet
```
print q<puts %q{s='print q<puts %%q{s=%r;print s%%s}>';print s%s}>
```
which generates the following Ruby code
```
puts %q{s='print q<puts %%q{s=%r;print s%%s}>';print s%s}
```
which then prints the original Python snippet:
```
s='print q<puts %%q{s=%r;print s%%s}>';print s%s
```
[Answer]
Here's a loop of 4 languages:
C -> Bash -> Batch -> Python -> C
C
```
main(){char *c="echo %cecho print %cmain(){char *c=%c%c%s%c%c;printf(c,34,39,92,34,c,92,34,39,34);}%c%c";printf(c,34,39,92,34,c,92,34,39,34);}
```
Bash
```
echo "echo print 'main(){char *c=\"echo %cecho print %cmain(){char *c=%c%c%s%c%c;printf(c,34,39,92,34,c,92,34,39,34);}%c%c\";printf(c,34,39,92,34,c,92,34,39,34);}'"
```
Batch
```
echo print 'main(){char *c="echo %cecho print %cmain(){char *c=%c%c%s%c%c;printf(c,34,39,92,34,c,92,34,39,34);}%c%c";printf(c,34,39,92,34,c,92,34,39,34);}'
```
Python
```
print 'main(){char *c="echo %cecho print %cmain(){char *c=%c%c%s%c%c;printf(c,34,39,92,34,c,92,34,39,34);}%c%c";printf(c,34,39,92,34,c,92,34,39,34);}'
```
] |
[Question]
[
The recent volume of MAA's Mathematics Magazine had an article "[Connecting the Dots: Maximal Polygons on a Square Grid](https://doi.org/10.1080/0025570X.2021.1869493)" by Sam Chow, Ayla Gafni, and Paul Gafni about making (very convex) \$n^2\$-gons where each vertex is a different point of the \$n \times n\$ grid.
>
> One is not allowed to have two consecutive segments be collinear, since that would merge two sides of the polygon.
>
>
>
For example, the following images are from Figures 2 and 10 in the Chow, Gafni, Gafni paper, which show a \$49\$-gon on the \$7 \times 7\$ grid of dots and a \$100\$-gon on the \$10 \times 10\$ grid of dots:


In the paper, the authors show that it is possible to form these \$n^2\$-gons for all integers \$n \geq 2\$ except for \$n=3\$ and \$n=5\$.
# Challenge
This [fastest-code](/questions/tagged/fastest-code "show questions tagged 'fastest-code'") challenge will have you count the number of "essentially different" \$n^2\$-gons on the \$n \times n\$ grid, where two polygons are considered the same if you can reflect or rotate one to match the other.
To score this, I will run the code on my machine—a 2017 MacBook with an Intel chip and 8GB of RAM—for five minutes with increasing sizes of \$n\$. Your score will be the maximum value of \$n\$ that your program can produce, and ties will be broken by the amount of time it took to get to that value.
# Small test cases
(From the Chow, Gafni, Gafni paper.)
* When \$n = 2\$ there is only one \$4\$-gon, the square.
* When \$n = 3\$ there are no \$9\$-gons.
* When \$n = 4\$ there is only one \$16\$-gon:
[](https://i.stack.imgur.com/X9JKn.png)
* When \$n = 5\$ there are no \$25\$-gons.
[Answer]
# Python 3 + Z3, N=5
Not 100% sure if this is correct. Basically a standard SAT/SMT coding of the Hamiltonian cycle problem, with additional clauses to block intersecting diagonals and collinear segments. Each time a solution is found all of its distinct rotations/flips are blocked. I've run it up to N=6 (2120 solutions found), which took 30 minutes.
Edit: I just realized that this only allows edges between adjacent grid points, but this restriction wasn't intended by the challenge. Oh well, I'll leave it up for now.
```
import collections
import heapq
import itertools
import math
import random
import time
import sys
import z3
show_paths = len(sys.argv) >= 2 and 'show' in sys.argv[1]
if show_paths:
import numpy as np
import pylab as plt
from matplotlib import collections as mc
def show_path(path):
lines = list(zip(path, path[1:] + path[:1]))
c = np.array([(1, 0, 0, 1), (0, 1, 0, 1), (0, 0, 1, 1)])
lc = mc.LineCollection(lines, colors=c, linewidths=2)
fig, ax = plt.subplots()
ax.add_collection(lc)
ax.autoscale()
ax.margins(0.1)
plt.show()
def compute_min_distances(C, distance_matrix, starting_points, banned):
min_distances = collections.defaultdict(lambda: float('inf'))
open_set = []
for i in starting_points:
state = (i, C[i])
min_distances[state] = 1
open_set.append((1, state))
while open_set:
d, state = open_set.pop()
if d > min_distances[state]:
continue
i, delta = state
x0, y0 = c0 = C[i]
for j, _ in distance_matrix[i]:
if j in banned:
continue
x1, y1 = c1 = C[j]
delta1 = (x1 - x0, y1 - y0)
if delta in (delta1, (x0 - x1, y0 - y1)):
continue
state = (j, delta1)
if d + 1 < min_distances[state]:
min_distances[state] = d + 1
heapq.heappush(open_set, (d + 1, state))
distance_array = [float('inf') for _ in distance_matrix]
distance_array[0] = 0
for (i, _), d in min_distances.items():
distance_array[i] = min(distance_array[i], d)
return distance_array
def point_orientations(p, n):
for (x, y) in (p, p[::-1]):
for x1 in (x, n - 1 - x):
for y1 in (y, n - 1 - y):
yield (x1, y1)
def path_orientations(path, n):
orientations = list(zip(*map(lambda p: point_orientations(p, n), path)))
for o in orientations:
i = o.index((0, 0))
if o[i - 1] == (0, 1):
o = o[::-1]
i = (len(o) - 1) - i
if o[(i + 1) % len(o)] != (0, 1):
continue
yield o[i:] + o[:i]
start_time = time.time()
for N in itertools.count(2):
print("starting n = %d..." % N)
solver = z3.Solver()
C = [(x, y) for x in range(N) for y in range(N)]
C_inv = {c : i for i, c in enumerate(C)}
bit_width = math.ceil(math.log(N * N + 1, 2))
P = [z3.BitVec('P_%d' % i, bit_width) for i in range(N * N)]
V = [z3.BitVec('V_%d' % i, bit_width) for i in range(N * N)]
for v in V:
solver.add(z3.ULT(v, N * N))
A = [[] for _ in range(N * N)]
for i, (x, y) in enumerate(C):
for dx, dy in itertools.product(range(-1, 2), repeat=2):
if not (dx or dy):
continue
try:
A[i].append(C_inv[(x + dx, y + dy)])
except KeyError:
pass
H = [[(j, z3.Bool('H_%d_%d' % (i, j))) for j in A[i]] for i in range(N * N)]
start = C_inv[(0, 1)]
min_distances = compute_min_distances(C, H, [start], {0})
end0, end1 = C_inv[(1, 0)], C_inv[(1, 1)]
min_distances_rev = compute_min_distances(C, H, [end0, end1], {0, start})
for i, (d0, d1) in enumerate(zip(min_distances, min_distances_rev)):
if i not in (0, start):
solver.add(z3.UGE(P[i], d0))
solver.add(z3.ULE(P[i], N * N - d1))
H_t = [[] for _ in range(N * N)]
for i, row in enumerate(H):
x0, y0 = C[i]
for j, v in row:
H_t[j].append(v)
if i == 0:
e = P[j] == 1
elif j == 0:
e = P[i] == (N * N - 1)
else:
e = P[j] == (P[i] + 1)
clauses = [V[i] == j, e]
x1, y1 = C[j]
dy = y1 - y0
dx = x1 - x0
blocked = []
if dy and dx:
x_m = min(x0, x1)
y_m = min(y0, y1)
if dy == dx:
blocked.append(((x_m + 1, y_m), (x_m, y_m + 1)))
else:
blocked.append(((x_m, y_m), (x_m + 1, y_m + 1)))
blocked.append(blocked[-1][::-1])
x2 = x1 + dx
y2 = y1 + dy
if all(0 <= c < N for c in (x2, y2)):
blocked.append(((x1, y1), (x2, y2)))
for (c0, c1) in blocked:
k = C_inv[c0]
l = C_inv[c1]
clauses.append(z3.Not(next(w for m, w in H[k] if m == l)))
solver.add(z3.Implies(v, z3.And(*clauses)))
solver.add(P[0] == 0)
solver.add(P[start] == 1)
for row in H_t:
solver.add(z3.PbEq([(v, 1) for v in row], 1))
solutions = set()
old_len = 0
while solver.check() == z3.sat:
model = solver.model()
successors = [int(str(model.eval(v))) for v in V]
path = [0]
while len(path) < N * N:
path.append(successors[path[-1]])
path = tuple(C[i] for i in path)
if show_paths:
show_path(path)
orientations = set(path_orientations(path, N))
assert not any(reoriented in solutions for reoriented in orientations)
solutions.add(path)
for reoriented in orientations:
successor = {}
for p0, p1 in zip(reoriented, reoriented[1:] + reoriented[:1]):
successor[C_inv[p0]] = C_inv[p1]
solver.add(z3.Not(z3.And(*[v == successor[i] for i, v in enumerate(V)])))
s = "%d solutions found so far... (%.1f seconds elapsed)" % (len(solutions), time.time() - start_time)
sys.stdout.write(s + max(0, old_len - len(s)) * ' ' + '\r')
sys.stdout.flush()
old_len = len(s)
sys.stdout.write(' ' * old_len + '\r')
sys.stdout.flush()
end_time = time.time()
print("%d solution%s found for n = %d in %.2g seconds" % (len(solutions), 's' * (len(solutions) != 1), N, end_time - start_time))
start_time = end_time
```
[Answer]
Work in progress... Still far over the 5 minute deadline set by OP, but already sharing some code to show what I have done so far.
Output:
```
N=6
Found 2956807 solutions in 12953858177 iterations.
Running time 41 minutes 17 seconds.
```
(Note that the previous version reported 9358354 without filtering rotation/mirroring. It appears that version had too aggressive pruning of the search tree. Unfortunately, less pruning in this version increased the running time a lot)
The strategy is to simply brute-force all possible paths as fast as possible and apply some pruning rules to cut the search tree short. The most effective pruning rule is to enforce that edge points are visited in clock-wise order.
For efficiency, I use a lookup table for all possible lines starting from a each grid point. And another lookup table to check what other lines are blocked/crossed by a certain line. I use 1D arrays instead of 2D containers/arrays.
My first experiments were in Java, which I later ported to C++ in the hope that that would be faster. Guess what, this only saved a few percent. Modern Java is very fast and comparable to C++ (for this use-case at least).
Contrary the code of @user1502040, my code not only considers lines between adjacent points, but between any two points (as long as there are no other intermediate points on that line). That gives some nice arbitrary paths. For example:
[](https://i.stack.imgur.com/JvVM1.png)
As suggested by @PeterKagey, for each solution found I generate all 8 permutations (mirroring/rotating) and use lexicographical sorting to see if we found the "lowest" solution of these eight. If not, we ignore the solution and trust we will find the lowest solution later during the search.
Below is the unpolished, work-in-progress code. While the program is running, it will update the `output/progress.html` file every 5 seconds to show a diagram with the current search path. If you open this file in a browser, the browser will automatically keep refreshing the page.
In addition, it will save an `output/solution-xyz.html` file every few solutions. This enables you to sample a few example solutions.
To be continued...
```
// To compile:
// $ g++ -Wall --std=c++11 -DNDEBUG -O3 ConnectingTheDots.cpp \
// -o ConnectingTheDots
//
// Examples:
// N=2
// Found 1 solutions in 4 iterations.
// Running time 0 minutes 0 seconds.
//
// N=3
// Found 0 solutions in 9 iterations.
// Running time 0 minutes 0 seconds.
//
// N=4
// Found 1 solutions in 422 iterations.
// Running time 0 minutes 0 seconds.
//
// N=5
// Found 0 solutions in 376217 iterations.
// Running time 0 minutes 0 seconds.
//
// N=6
// Found 2956807 solutions in 12953858177 iterations.
// Running time 41 minutes 17 seconds.
//
// Improvement opportunities:
//
// - Parallelize: a brute-force search is trivial to run massively parallel on
// all available CPU cores. Use POSIX pthread to create worker threads.
//
// - Data locality: lookup tables currently use 32-bit integers and have large
// ROW_SIZEs. This reduces data locality and thus memory caching. Ideas:
// - Consider using 8-bit resp. 16-bit integers (for N <= 8)
// - Store data consecutively in array and use row pointers.
//
// - Roll back: making a step and rolling it back involves selectively saving
// and restoring parts of the state. The overhead of this bookkeeping is
// large. Perhaps it is faster to blindly copy the entire state.
//
// To make the copy fast, we could condense the state into a smaller memory
// footprint (at the cost of some bit masking and shifting). For example, the
// pointAvailable[] and lineAvailable[] boolean arrays could be bitmaps which
// makes them 32x times smaller.
//
// - Island pruning rule: when the path waves from an edge point inward and
// then back to the next edge point, it may not enclose an unvisited point.
// These islands can never be visited. Beware that the island must be really
// enclosed. Just checking neighbouring points is not enough, since sharp
// "spikes" can still reach far away isolated points.
#include <stdlib.h>
#include <stdio.h>
#include <algorithm> // std::min
#include <time.h>
#include <sys/stat.h> // mkdir
// User-specified dimensions
const int N = 6;
// Calculated dimensions
const int MAX_POS = N*N;
const int MAX_LINE = MAX_POS*MAX_POS;
/** ---------------------------------------------------------------------------
* Class to check whether two line segments intersect.
* 2D integer coordinates only.
*
* Reference:
* https://www.geeksforgeeks.org/check-if-two-given-line-segments-intersect/
* http://www.dcs.gla.ac.uk/~pat/52233/slides/Geometry1x1.pdf
*/
class Intersect {
public:
/**
* Check whether lines p1q1 and p2q2 cross eachother.
*
* @return `true` if crossed
*/
static bool isCrossed(int p1, int q1, int p2, int q2) {
assert(p1 >= 0 && p1 < MAX_POS);
assert(q1 >= 0 && q1 < MAX_POS);
assert(p2 >= 0 && p2 < MAX_POS);
assert(q2 >= 0 && q2 < MAX_POS);
assert(p1 != q1);
assert(p2 != q2);
// endpoints may touch
if (p1 == p2 || p1 == q2 || q1 == p2 || q1 == q2) return false;
// convert point IDs to 2D coordinates
int p1x = p1 % N; int p1y = p1 / N;
int q1x = q1 % N; int q1y = q1 / N;
int p2x = p2 % N; int p2y = p2 / N;
int q2x = q2 % N; int q2y = q2 / N;
// Find the four orientations needed for general and
// special cases
int o1 = orientation(p1x, p1y, q1x, q1y, p2x, p2y);
int o2 = orientation(p1x, p1y, q1x, q1y, q2x, q2y);
int o3 = orientation(p2x, p2y, q2x, q2y, p1x, p1y);
int o4 = orientation(p2x, p2y, q2x, q2y, q1x, q1y);
// General case
if (o1 != o2 && o3 != o4) return true;
// Special Cases
// p1, q1 and p2 are colinear and p2 lies on segment p1q1
if (o1 == 0 && onSegment(p1x, p1y, p2x, p2y, q1x, q1y)) return true;
// p1, q1 and q2 are colinear and q2 lies on segment p1q1
if (o2 == 0 && onSegment(p1x, p1y, q2x, q2y, q1x, q1y)) return true;
// p2, q2 and p1 are colinear and p1 lies on segment p2q2
if (o3 == 0 && onSegment(p2x, p2y, p1x, p1y, q2x, q2y)) return true;
// p2, q2 and q1 are colinear and q1 lies on segment p2q2
if (o4 == 0 && onSegment(p2x, p2y, q1x, q1y, q2x, q2y)) return true;
return false; // Doesn't fall in any of the above cases
}
private:
/**
* To find orientation of ordered triplet (p, q, r).
*
* @return 0 --> p, q and r are colinear
* 1 --> Clockwise
* 2 --> Counterclockwise
*/
static int orientation(int px, int py, int qx, int qy, int rx, int ry) {
int val = (qy - py)*(rx - qx) - (qx - px)*(ry - qy);
if (val == 0) return 0; // colinear
return (val > 0) ? 1 : 2; // clock or counterclock wise
}
/**
* Given three colinear points p, q, r, the function checks if
* point q lies on line segment 'pr'.
*
* @return `true` if point q lies on line segment pr
*/
static bool onSegment(int px, int py, int qx, int qy, int rx, int ry) {
if (qx <= std::max(px, rx) && qx >= std::min(px, rx) &&
qy <= std::max(py, ry) && qy >= std::min(py, ry)) {
return true;
}
return false;
}
};
/** ---------------------------------------------------------------------------
* Lookup table with all possible connections.
*/
class LinesLookupTable {
public:
/**
* Build look up table.
*/
void build() {
assert(ROW_SIZE >= (N*N)-1);
lines = new int[MAX_POS*ROW_SIZE];
// iterate point i over grid
for (int i = 0; i < MAX_POS; i++) {
int x = i%N;
int y = i/N;
int nrLines = 0;
// iterate point j over grid
for (int j = 0; j < MAX_POS; j++) {
if (i == j) continue;
int dx = (j%N) - x;
int dy = (j/N) - y;
// not allowed to have another point on the line
bool isValid = true;
for (int div = 2; div < N; div++) {
if ((abs(dx) % div) == 0 &&
(abs(dy) % div) == 0) {
isValid = false;
break;
}
}
if (!isValid) continue;
// found a valid line
assert(nrLines < ROW_SIZE);
lines[i*ROW_SIZE + nrLines++] = j;
}
// write end of list marker
assert(nrLines < ROW_SIZE);
lines[i*ROW_SIZE + nrLines] = -1;
}
}
/**
* Get list of lines connecting specified position.
* @param position start position
* @return array with connecting positions, terminated by -1
*/
const int *getLines(int position) const {
assert(position >= 0 && position < MAX_POS);
return &lines[position*ROW_SIZE];
}
private:
static const int ROW_SIZE = 64;
int *lines;
};
/** ---------------------------------------------------------------------------
* Create line ID based on two points.
* We choose a consistent order of begin and end point to prevent
* double counting.
*
* @param p begin point
* @param q end point
*/
inline int makeLineId(int p, int q) {
assert(p >= 0 && p < MAX_POS);
assert(q >= 0 && q < MAX_POS);
return std::min(p, q)*MAX_POS + std::max(p, q);
}
/** ---------------------------------------------------------------------------
* Lookup table with all other lines that are blocked by a certain line.
*/
class BlockedLookupTable {
public:
BlockedLookupTable(LinesLookupTable *linesLookupTable_) :
linesLookupTable(linesLookupTable_) {
}
/**
* Build look up table.
*/
void build() {
blocked = new int[MAX_LINE*ROW_SIZE];
// iterate point i over grid
for (int i = 0; i < MAX_POS; i++) {
// iterate point j over all lines connecting i
const int *jp = linesLookupTable->getLines(i);
for (int j = *jp++; j != -1; j = *jp++) {
assert(j >= 0 && j < MAX_POS);
int lineId = makeLineId(i, j);
int nrBlocked = 0;
// iterate point p over grid
for (int p = 0; p < MAX_POS; p++) {
// iterate point q over all lines connecting p
const int *qp = linesLookupTable->getLines(p);
for (int q = *qp++; q != -1; q = *qp++) {
assert(q >= 0 && q < MAX_POS);
int lineId2 = makeLineId(p, q);
if (lineId == lineId2) continue;
// check if line i-j crosses line p-q
if (Intersect::isCrossed(i, j, p, q)) {
assert(nrBlocked < ROW_SIZE);
blocked[lineId*ROW_SIZE + nrBlocked++] = lineId2;
}
}
}
// block lines colinear with line i-j
int dx = (j%N) - (i%N);
int dy = (j/N) - (i/N);
// extend out from i
int x = (i%N) - dx;
int y = (i/N) - dy;
if (x >= 0 && x < N && y >= 0 && y < N) {
int k = x + y*N;
int lineId2 = makeLineId(i, k);
assert(nrBlocked < ROW_SIZE);
blocked[lineId*ROW_SIZE + nrBlocked++] = lineId2;
}
// extend out from j
x = (j%N) + dx;
y = (j/N) + dy;
if (x >= 0 && x < N && y >= 0 && y < N) {
int k = x + y*N;
int lineId2 = makeLineId(j, k);
assert(nrBlocked < ROW_SIZE);
blocked[lineId*ROW_SIZE + nrBlocked++] = lineId2;
}
// write end of list marker
assert(nrBlocked < ROW_SIZE);
blocked[lineId*ROW_SIZE + nrBlocked] = -1;
}
}
}
/**
* Get list of lines blocked by the specified line
* @param lineId line
* @return array with blocked lines, terminated by -1
*/
const int *getBlockedLines(int lineId) {
assert(lineId >= 0 && lineId < MAX_LINE);
assert(lineId/MAX_POS < lineId%MAX_POS);
return &blocked[lineId*ROW_SIZE];
}
private:
static const int ROW_SIZE = 512;
LinesLookupTable *linesLookupTable;
int *blocked;
};
/** ---------------------------------------------------------------------------
* Class for printing paths to console and rendering path diagrams in HTML file
*/
class Output {
public:
Output() :
updateProgressTime(0) {
}
/**
* Show current path.
*/
void printPath(const int *path, int pathLen) {
if (pathLen > 0) {
printf("%d", path[0]);
for (int i = 1; i < pathLen; i++) {
printf(", %d", path[i]);
}
}
if (pathLen < MAX_POS+1) {
printf(", ...");
}
printf("\n");
}
/**
* Periodically dump path to console, and redraw diagram in HTML file.
*/
void updateProgress(const int *path, int pathLen) {
if (updateProgressInterval > 0 &&
time(NULL) >= updateProgressTime + updateProgressInterval) {
printPath(path, pathLen);
char filePath[256];
snprintf(filePath, sizeof(filePath), "%s/%s", outputDir,
progressFile);
drawPath(path, pathLen, filePath, true);
updateProgressTime = time(NULL);
}
}
/**
* Draw solution diagram in HTML file.
*/
void drawSolution(const int *path, int pathLen, int solutionId) {
char fileName[256];
snprintf(fileName, sizeof(fileName), solutionFile, solutionId);
char filePath[256];
snprintf(filePath, sizeof(filePath), "%s/%s", outputDir, fileName);
drawPath(path, pathLen, filePath, false);
printf("Written \"%s\"\n", filePath);
}
private:
static const int updateProgressInterval = 5; // in seconds (0=disable)
static constexpr const char *outputDir = "output";
static constexpr const char *progressFile = "progress.html";
static constexpr const char *solutionFile = "solution-%04d.html";
time_t updateProgressTime;
/**
* Ensure output directory exists.
*/
void makeOutputDir() {
struct stat st = {0};
if (stat(outputDir, &st) == -1) {
if (mkdir(outputDir, 0775)) {
perror("Failed to create output directory");
exit(-1);
}
}
}
/**
* Draw current (partial) path in SVG diagram and embed in HTML file.
* @param filePath directory and file name of HTML file
* @param refresh if `true` the HTML file will periodically reload in the
* browser
*/
void drawPath(const int *path, int pathLen, const char *filePath,
bool refresh) {
makeOutputDir();
char tempFilePath[256];
snprintf(tempFilePath, sizeof(tempFilePath), "%s.tmp", filePath);
FILE *fp = fopen(tempFilePath, "w");
if (fp == NULL) {
perror("Failed to create file");
return;
}
fprintf(fp, "<!DOCTYPE html>\n");
fprintf(fp, "<html>\n");
if (refresh) {
fprintf(fp, "<head>\n");
fprintf(fp, "<meta http-equiv=\"refresh\" content=\"%d\" />\n",
updateProgressInterval+1);
fprintf(fp, "</head>\n");
}
fprintf(fp, "<body>\n");
fprintf(fp, "<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\""
" width=\"%.1f\" height=\"%.1f\">\n", N*100.0, N*100.0);
for (int y = 0; y < N; y++) {
for (int x = 0; x < N; x++) {
fprintf(fp, "<circle cx=\"%.1f\" cy=\"%.1f\" r=\"5.0\" "
"fill=\"black\" />\n", 50.0 + x*100.0, 50.0 + y*100.0);
}
}
for (int i = 0; i+1 < pathLen; i++) {
int x1 = path[i]%N;
int y1 = path[i]/N;
int x2 = path[i+1]%N;
int y2 = path[i+1]/N;
fprintf(fp, "<polyline points=\"%.1f,%1.f %.1f,%.1f\" "
"style=\"fill:none;stroke:#000000;stroke-width:2.0;\" "
"/>\n",
50.0 + x1*100.0, 50.0 + y1*100.0,
50.0 + x2*100.0, 50.0 + y2*100.0);
}
fprintf(fp, "</svg>\n");
fprintf(fp, "</body>\n");
fprintf(fp, "</html>\n");
fclose(fp);
rename(tempFilePath, filePath);
}
};
/** ---------------------------------------------------------------------------
* Search all possible paths.
*/
class Solver {
public:
Solver(
LinesLookupTable *linesLookupTable_,
BlockedLookupTable *blockedLookupTable_,
Output *output_):
linesLookupTable(linesLookupTable_),
blockedLookupTable(blockedLookupTable_),
output(output_) {
}
/**
* Search all possible paths
*/
void solve() {
buildNextEdgePointTable();
pointAvailable = new bool[MAX_POS];
for (int i = 0; i < MAX_POS; i++) {
pointAvailable[i] = (nextEdgePoint[i] == -1);
}
pointAvailable[N] = false; // end of edge
pointAvailable[nextEdgePoint[0]] = true;
lineAvailable = new bool[MAX_LINE];
for (int i = 0; i < MAX_LINE; i++) {
lineAvailable[i] = true;
}
path = new int[MAX_POS+1];
pathLen = 0;
nrIterations = 0;
nrSolutions = 0;
path[pathLen++] = 0;
pointAvailable[0] = false;
recurseNextStep(0);
printf("Found %llu solutions in %llu iterations.\n",
nrSolutions, nrIterations);
}
private:
LinesLookupTable *linesLookupTable;
BlockedLookupTable *blockedLookupTable;
Output *output;
int *nextEdgePoint;
bool *pointAvailable;
bool *lineAvailable;
unsigned long long nrSolutions;
int *path;
int pathLen;
unsigned long long nrIterations;
/**
* Build nextEdgePoint[] lookup table
*/
void buildNextEdgePointTable() {
nextEdgePoint = new int[MAX_POS];
for (int i = 0; i < MAX_POS; i++) {
nextEdgePoint[i] = -1;
}
int prev = 0;
for (int x = 1; x < N; x++) {
int y = 0;
int point = y*N + x;
nextEdgePoint[prev] = point;
prev = point;
}
for (int y = 1; y < N; y++) {
int x = N-1;
int point = y*N + x;
nextEdgePoint[prev] = point;
prev = point;
}
for (int x = N-2; x >= 0; x--) {
int y = N-1;
int point = y*N + x;
nextEdgePoint[prev] = point;
prev = point;
}
for (int y = N-2; y >= 1; y--) {
int x = 0;
int point = y*N + x;
nextEdgePoint[prev] = point;
prev = point;
}
}
/**
* Iterate over all possible next steps starting at current position.
* @param i current 1D position
*/
void recurseNextStep(int i) {
nrIterations++;
if (pathLen == MAX_POS) {
// We are ready to make the last hop. Check if we can close the loop.
closeLoop(i);
} else {
int blockedLines[256];
int nrBlockedLines = 0;
bool isDeadEnd = true;
// Iterate over all possible next steps 'j' starting at
// current position 'i'.
const int *jp = linesLookupTable->getLines(i);
for (int j = *jp++; j >= 0; j = *jp++) {
assert(j >= 0 && j < MAX_POS);
// target point still available?
if (pointAvailable[j]) {
// line to target point still available?
int lineId = makeLineId(i, j);
assert(lineId >= 0 && lineId < MAX_LINE);
if (lineAvailable[lineId]) {
// found a valid next step
path[pathLen++] = j;
isDeadEnd = false;
// mark points and lines as used, but keep track of
// changes so we can roll them back later
lineAvailable[lineId] = false;
const int *bp = blockedLookupTable->getBlockedLines(lineId);
for (int lineId2 = *bp++; lineId2 != -1; lineId2 = *bp++) {
assert(lineId2 >= 0 && lineId2 < MAX_LINE);
if (lineAvailable[lineId2]) {
assert(nrBlockedLines < 256);
blockedLines[nrBlockedLines++] = lineId2;
lineAvailable[lineId2] = false;
}
}
pointAvailable[j] = false;
// make sure edge points are visited in order
if (nextEdgePoint[j] != -1) {
assert(!pointAvailable[nextEdgePoint[j]]);
pointAvailable[nextEdgePoint[j]] = true;
}
// search next step
recurseNextStep(j);
// roll back changes
if (nextEdgePoint[j] != -1) {
pointAvailable[nextEdgePoint[j]] = false;
}
pointAvailable[j] = true;
pathLen--;
while (nrBlockedLines > 0) {
nrBlockedLines--;
int lineId2 = blockedLines[nrBlockedLines];
assert(lineId2 >= 0 && lineId2 < MAX_LINE);
lineAvailable[lineId2] = true;
}
assert(lineId >= 0 && lineId < MAX_LINE);
lineAvailable[lineId] = true;
}
}
}
if (isDeadEnd) {
output->updateProgress(path, pathLen);
}
}
}
/**
* Try to close the loop back to position 0.
* @param position current 1D position
*/
void closeLoop(int i) {
// Iterate over all possible next steps 'j' starting at
// current position 'i'.
const int *jp = linesLookupTable->getLines(i);
for (int j = *jp++; j >= 0; j = *jp++) {
assert(j >= 0 && j < MAX_POS);
if (j != 0) continue;
// line to target point still available?
int lineId = makeLineId(i, j);
if (lineAvailable[lineId]) {
path[pathLen++] = j;
// found a valid loop! Now check if this is the "lowest" of all
// equivalent paths.
if (isLowestSolution()) {
// Sample some random paths by drawing every few solutions.
// for N=6, we will find 2956807 solutions. Aim for 100 examples.
if ((nrSolutions % 29568) == 0) {
output->drawSolution(path, pathLen, nrSolutions);
}
nrSolutions++;
}
pathLen--;
}
}
}
/**
* Check whether the solution found is the "lowest" equivalent solution
* when sorted lexicographically.
*
* By rotating and mirroring each path can result in up to 8 equivalent
* paths. We choose the lexicographically lowest solution as the "main"
* solution.
*
* @returns `true` if the current path equals lowest equivalent path
*/
bool isLowestSolution() {
assert(pathLen >= MAX_POS);
int rotatedPath[MAX_POS+1];
memcpy(rotatedPath, path, pathLen*sizeof(rotatedPath[0]));
for (int permutation = 1; permutation < 8; permutation++) {
// rotate clockwise
for (int i = 0; i < pathLen; i++) {
int x = rotatedPath[i]%N;
int y = rotatedPath[i]/N;
int rotX = N-1-y;
int rotY = x;
rotatedPath[i] = rotY*N + rotX;
}
// after 4 rotations we are upright again. Now mirror horizontally.
// note after mirroring the path runs counter-clockwise. We therefore
// also need to reverse the order of the points visited
if (permutation == 4) {
#ifndef NDEBUG
// assert we are upright again
for (int i = 0; i < pathLen; i++) {
assert(path[i] == rotatedPath[i]);
}
#endif
int mirroredPath[MAX_POS+1];
for (int i = 0; i < pathLen; i++) {
int x = rotatedPath[i]%N;
int y = rotatedPath[i]/N;
int rotX = N-1-x;
int rotY = y;
mirroredPath[pathLen-1-i] = rotY*N + rotX;
}
memcpy(rotatedPath, mirroredPath, pathLen*sizeof(rotatedPath[0]));
}
if (comparePaths(path, rotatedPath) > 0) return false;
}
// of all 8 permutations, the current path is the "lowest" (or equal
// to some of the permutations in case of symmetric, but since the path
// generator will only generate that path once, it is not a problem).
return true;
}
/**
* Compare two paths.
* Assumes path A starts at point 0, path B can start anywhere.
*
* @return -1 if A < B, +1 if A > B
*/
int comparePaths(const int *pathA, const int *pathB) {
assert(pathA[0] == 0);
// find point 0 in path B
int offset;
for (offset = 0; offset < MAX_POS && pathB[offset] != 0; offset++);
assert(pathB[offset] == 0);
// compare path A with path B
for (int i = 0, j = offset; i < MAX_POS; i++, j = (j+1) % MAX_POS) {
if (pathA[i] < pathB[j]) return -1;
if (pathA[i] > pathB[j]) return +1;
}
return 0;
}
};
/** ---------------------------------------------------------------------------
* Main program
*/
int main() {
LinesLookupTable *linesLookupTable;
BlockedLookupTable *blockedLookupTable;
Output *output;
Solver *solver;
time_t startTime = time(NULL);
linesLookupTable = new LinesLookupTable();
blockedLookupTable = new BlockedLookupTable(linesLookupTable);
output = new Output();
solver = new Solver(linesLookupTable, blockedLookupTable,
output);
printf("N=%d\n", N);
linesLookupTable->build();
blockedLookupTable->build();
solver->solve();
int seconds = time(NULL) - startTime;
printf("Running time %d minutes %d seconds.\n", seconds/60, seconds%60);
return 0;
}
```
] |
[Question]
[
Inspired in part by [this
Mathologer video on gorgeous visual "shrink" proofs](https://youtu.be/sDfzCIWpS7Q?t=799), and my [general interest](https://codegolf.stackexchange.com/q/204419/53884) [in the topic](http://oeis.org/wiki/User:Peter_Kagey), this challenge will have you count regular polygons with integer coordinates in 3D.
You'll be provided an input `n`, which is a non-negative integer. Your program should find the number of subsets of \$\{0, 1, \dots, n\}^3\$ such that the points are the vertices of a regular polygon. That is, the vertices should be 3D coordinates with nonnegative integers less than or equal to \$n\$.
### Examples
For \$n = 4\$, there are \$2190\$ regular polygons: \$1264\$ equilateral triangles, \$810\$ squares, and \$116\$ regular hexagons. An example of each:
* Triangle: \$(1,0,1), (0,4,0), (4,3,1)\$
* Square: \$(1,0,0), (4,3,0), (3,4,4), (0,1,4)\$
* Hexagon: \$(1,1,0), (0,3,1), (1,4,3), (3,3,4), (4,1,3), (3,0,1)\$
[](https://i.stack.imgur.com/HzOMO.png)
The (zero-indexed) sequence begins:
```
0, 14, 138, 640, 2190, 6042, 13824, 28400, 53484, 94126, 156462, 248568, 380802, 564242, 813528, 1146472, 1581936, 2143878, 2857194, 3749240, 4854942, 6210442
```
### Rules
To prevent the most naive and uninteresting kinds of brute-forcing, your program must be able to handle up to \$a(5) = 6042\$ on [TIO](https://tio.run/).
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so the shortest code wins.
---
This is now on the On-Line Encyclopedia of Integer Sequences as [A338323](https://oeis.org/A338323).
[Answer]
# [Python 2](https://docs.python.org/2/), 330 313 bytes
```
import numpy as N,itertools as I
L=list
D=N.dot
n=input()
def G((a,b,c)):
A=a
while 1:
u=b-a;v=c-b;d=D(v,v)
if D(u,u)-d:return 0
p=2*D(u,v)*v
a,b,c=b,c,c+a-b+p/d
if(p%d|(c<0)|(c>n)).any()or L(a)<L(A):return 0
if L(a)==L(A):return 1
print sum(map(G,I.permutations(N.indices((n+1,)*3).reshape(3,-1).T,3)))/2
```
[Try it online!](https://tio.run/##TZBNi4MwEIbP5lfksjBTo62VvdhmoVAoBfG0fyCaFAOahHy4FPa/d3VPPczAPPA@A697xtGa4@ulZ2d9pCbN7klFoB3TUflo7RS2805aPukQyZV3pbSRGK6NSxGQSPWgNwDBejYgNoReuCD0Z9STolVDssT7QpwWPhT9SfIrLGxBkukHvUJiCQvZeBWTN/RAMsePuw0vuFtI9q/k67AhF0Wfu73cguA@5C8M5wOu@8sglsI8Aa2nLQg8t3DBN@X6aMOcv/OKOK9NpCHNMAsHN3YvnfJziiJqawJ0pTZSDyoAmLxiuKux9CqMwimoWVFh@c1qRNyv1X3@AQ "Python 2 – Try It Online")
TIO spent `36.893 s` calculating `a(5) = 6042`, so this solution is just fast enough.
Given 3 consecutive points of a regular polygon `a,b,c`, the next point is `d = c + a - b + 2*proj(b-a, c-b)` (where `proj` is vector projection). My solution iterates through all triples of points and determines if they form a polygon using this formula.
Verified up to `a(7) = 28400` on my machine.
-17 bytes from ovs
] |
[Question]
[
In Vim, you can repeat a command by preceding it with a number, like `3dd` is equivalent to `dd dd dd`. Well, this repeating pattern is not restricted to Vim commands. String can be replicated in this way, too.
### Specification:
Given a string, consisting of only digits, alphabetical characters (both upper-case and lower-case) and spaces, with an optional trailing newline, as input, write a program that does the following job:
* Each "word" consists of digits and alphabets. If a letter is preceded with a number (there may be more than one digit in a number, or the number is zero), repeat that letter for the given times. For example:
```
a2bc -> abbc
3xx1yz -> xxxxyz
10ab0c0d0e -> aaaaaaaaaab # No 'cde' because there's a zero
2A2a2A2a -> AAaaAAaa
```
* Words are separated by spaces. There's a maximum of one space between every two adjacent words.
Easy, right? Here's the additional stuff:
* If there's a number before the space, repeat the next word for the given times. The number will always be attached to the end of the previous word, or at the start of the string. Example:
```
a2bc3 2d -> abbc dd dd dd
3 3a -> aaa aaa aaa
33a -> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
0 abcd0 efgh3 2x -> xx xx xx
a3 0xc b -> a c c c b
```
* If an empty word ought to be repeated, don't output multiple spaces in a row. Squash them:
```
a3 0x2 b -> a b b # NOT 'a b b'
```
In other words, your program should never output two spaces together.
* Input is never empty, but it's not necessary for the output to be non-empty:
```
0 3x -> (empty)
```
* Input and output can be taken in any preferred ways. A function taking input from arguments and giving output via return values is acceptable as well.
If it's a program, it must not exit with error (i.e. return value is zero).
* Numbers are always decimal, and never starts with a zero, unless the number itself is zero, in which case there's only one zero. I.e. you don't need to consider `077a` or `000a` given as input.
* All numbers are under 2^31 (2,147,483,648). Maximum output length is under 2^32 (4,294,967,296) bytes.
* The program may optionally output one trailing space and/or one trailing newline. Those space and newline do not affect the validity of output. Even if the correct output should be empty, an output of a space followed by a newline will qualify.
In short, a valid input matches this regular expression:
```
([0-9]+ )?([0-9A-Za-z]*[A-Za-z])([0-9]* [0-9A-Za-z]*[A-Za-z])*( ?\n?)
```
And for a valid output:
```
([A-Za-z]+)( [A-Za-z]+)*( ?\n?)
```
Sample test cases:
```
abcdefg -> abcdefg
a3bcd -> abbbcd
a3bbbc -> abbbbbc
3a0b -> aaa
abc 3d -> abc ddd
abc3 d -> abc d d d
5 1x5 1y0 z -> x x x x x y y y y y
a999 0x b -> a b
999 0s -> (empty)
0 999s -> (empty)
0 999s4 t -> t t t t
a3 0xc b -> a c c c b
ABC3 abc -> ABC abc abc abc
```
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program in bytes in each language wins!
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~102~~ ~~129~~ ~~110~~ 106 bytes
```
s=>s[p="replace"](/(\d+)( \w*[A-Z])/gi,g=(_,a,b)=>b.repeat(a))[p](/(\d+)(.)/g,g)[p](/ +/g,(_,i)=>i?" ":"")
```
[Try it online!](https://tio.run/##dVJNj5swEL3zK0a@YLokcUL3kI1Ixe69vfRUFq3GxlCqdEHY3UKq/vZ0bD721BmNGN68GfvZ/oFvaFTfdHbz2pb6VqU3k55N3qWs190FlWYF3/Hn8i7i8Pz7Q55tvhXRrm7iOuUvMcYySs9yS1yNlmMU5d3K3xIvricE7iinhobozScG7IGx6HYK3rAHq41VaLSBFPIAGB6kgs0ZUErFYgKSYdiPVwcNZOPVg3uBUihRCu25q0kWw24Hn1sIValDkFrhL6PBfte9Dg0gXHXf0oBDdkAXrj3LEF34yZiAGA4g/Vz6LBO/fIUQgYygkHgCksFxpiZJq1X1tG@fzrPoZxZD2YLJVaFcRaKQs5JlICRzq4KyLBc0gXfUucfvYT9QjAKmc1p9XHxqPx6PJG7V5kGPmUkJCeX6Z2fHyAuk0v8LH8G6mp3cj8oenxK/M3emj08@nYMFxSmo2h64u/MG2ur94iP4E4B/CvQEmq3pLo3lzC8cnaaKokrFbS4Kh6j21bQXvb20Nc8dGIOKweb7AtIUlOMEf2//AA "JavaScript (Node.js) – Try It Online")
Thanks for @Arnauld for -4 bytes.
[Answer]
# Perl 6, 88 bytes
```
{$_=$^a;s:g/(\d+):(\w)/{$1 x$0||'_'}/;s:g/(\d+)\s([\w& \D]+)/ {$1 xx$0}/;~S:g/_//.words}
```
[Test it](https://tio.run/##fVLJctNAEL3PV7wkqoyEHUm2IFW2yxgnOcOB3BC4ZovtKi9Co2DJCz/GjR8zM9rMgWJaLfW87nm9jBKVru7Pr1rhx70vRmRd4FZspcL4fHBmY@cbG@nhPHBj2fGGbrzzgoPTQ@6ExyOd0VNw8cba/RLvbhE/fe14AcowE2dCfn42MbMg8HfbVOrT2eT4kCmdYYzVcqO06/nzVCXuG18sWKq93798nayWmRuA4u69eR0R6w7oDUXg@WuWDC3sxstN8pp1Y5UnSmRKdp2JhwMBKhwuGg/Ud1BXrZOs8CgmE1CKq6uL2yMnYmfwbKoakWTFNuiUJY7Iyzatq7UpnYraaU7W@fSdVCpZFbCjq4O8LtqwLq4r0E/MvF3PcrXOGrsekdOZ9bmwTsa5IFGe94q93eZmFXvSCxkPRShDVca0i@MGH7egQioKrgSzvWQLlSqqwbBX6Zb0p31m1Z6cThmzSojNF6Evm5yQsnpIhIjVWRolUQv9f5HQkAkZQr3MF4Y@r3qoHpM0Qpj3wUsu8@GAbeDTMygzpkUoMRxRea6@NnPMUBrCqtTSNEzGqGs3lt3zdoC8nCELeV2zJUBUh9tOpUUiXBAr5B16udEiRDX6VopGCBsMBqaFtgNS7vXf1YYw2D@Qtyh/pKwSMn14jMrc9lYeHkuz1npOoskiSuF/AA "Perl 6 – Try It Online")
## Expanded:
```
{ # bare block lambda with placeholder parameter 「$a」
# store a copy of the argument in 「$_」
# (shorter than 「-> $_ is copy {…}」)
$_ = $^a;
# note that 「$_」 is the default scalar,
# and many things operate on it by default (like 「s///」)
# do the character repeats
s :global
/
(\d+) # repeat count
: # don't backtrack (prevents it from matching word repeats)
(\w) # character to repeat
/{
$1 x $0 # do the repeat
|| '_' # replace with 「_」 if the repeat was 0 (matched by [\w & \D])
# this is so “words” don't get removed yet
}/;
# do the word repeats
s :global
/
(\d+) # repeat count
\s # shortest way to match a space
([
\w & \D # word character and not a digit (doesn't match next repeat)
]+) # match that at least once
/ { # add a space (as we removed it by matching it)
$1 xx $0 # list repeat (adds a space between values when stringified)
}/;
# the following is the result
~ # stringify (adds spaces between values in a list) # (3)
S :global /_// # remove all _ not in-place # (1)
.words # get a list of words # (2)
}
```
The `~(…).words` combination removes extraneous spaces, which is useful if a “word” gets removed.
[Answer]
# Python 2, ~~286~~ ~~275~~ ~~260~~ ~~257~~ 238 bytes
-19 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)
```
def f(s,j=' '.join):exec"s=s.split(%s[-1]):s[i]=s[i][:-1];s[i-1]=j([s[i-1]]*int(w[-1]))\ns=list(j(s[::-1])%s):s[i]='';s[i-1]*=int(w)\nprint j(''.join(s[::-1]).strip().split())"%((')[::-1]\nfor i,w in enumerate(s):\n if str.isdigit(w',)*2)
```
`f` takes a string as an argument and prints the formatted string.
[Here's a repl.it](https://repl.it/repls/DimwittedDownrightIberianlynx) with the test cases.
Ungolfed code:
```
def f(s, j=' '.join):
s = s.split()[::-1]
for i, w in enumerate(s):
if str.isdigit(w[-1]):
s[i] = s[i][:-1]
s[i - 1] = j([s[i - 1]] * int(w[-1]))
s = list(j(s[::-1]))[::-1]
for i, w in enumerate(s):
if str.isdigit(w):
s[i] = ''
s[i - 1] *= int(w)
print j(''.join(s[::-1]).strip().split())
```
Still working on improvements.
[Answer]
# [Perl 5](https://www.perl.org/), 77 + 1 (`-p`) = 78 bytes
```
s/\d+( .*?)(\d*)( |$)/$1x$&.$2.$3/eg&&redo;s/\d+(\D)/$1x$&/eg;s/ +/ /g;s;^ +;
```
[Try it online!](https://tio.run/##K0gtyjH9/79YPyZFW0NBT8teUyMmRUtTQ6FGRVNfxbBCRU1PxUhPxVg/NV1NrSg1Jd8aojTGBSoNlAAKKWjrK@gDGdZxCtrW//8nGisYVCQrJP3LLyjJzM8r/q9bAAA "Perl 5 – Try It Online")
[Answer]
# [Clean](https://clean.cs.ru.nl), ~~443~~ ... 306 bytes
```
import StdEnv,StdLib
^ =last
$n|n>"9"=1=toInt n
?v c| ^v<c=init v=v
q=groupBy
f[a:t]|a<"a"=repeatn($a)(hd t)++f(tl t)|t>[]=[a:f t]=[a," "]
f e=e
@l#[h:t]=[[toString[c:if(c<'1')[]k]\\[c:k]<-q(\a b=max a b<'a')s]\\s<-q(\a b=min a b>' ')l|s>[' ']]
=flatten(map f[?h"a":[?u":"\\u<-t&v<-map^[h:t],_<-[1.. $v]]])
```
[Try it online!](https://tio.run/##RVDBboJAEL3vV0y2pkAUU4@QXTRNezDx5nFZmxFBN8KCMBCb8O2laz00c3hv3ptMXl5W5minqj71ZQ4VGjuZqqlbgj2dPu2wcLAzR3YAWWJHbGZHm/CIy5WkemsJLFsPkI1wGEQmjTUEgxzYTZ7bum/ev1mhMCY9ouDIZZs3OZL1Zxj4lxNQMJ8XPpWOjJQoLd1tAfTABQeuWQG5zNmmfFGX@CErqvfUGntWWWwKPxPeyguUvuo0dcpVi/DmpwhHWeEdHAoPvaBzbvfvGPtwEg@8oBy7RDmiNZNFiUS59StsoFDri4sbq3XPY56mvQjpdRCh8w5/SRZfIlSr5RJmg9Y6mPaErjEJG1AeRlEEb3c4PsbT00/mXp@7Kdzupo9vi5XJnsuz2V8 "Clean – Try It Online")
[Answer]
# [Lua](https://www.lua.org), 113 bytes
```
a="(%d+)(%a)"g=a.gsub function r(c,s)return s:rep(c)end g(g(g(g(...,a,r),"(%d+)( %a*)",r)," +"," "),"%a.*",print)
```
[Try it online!](https://tio.run/##LYzBCgIxDER/JQQKzW4oevAi7MfEbi0LEpe0Bdefr0VlmMfwDvNo0rss6N06k3dCmBcJubQb3JvGuj0VzEcuZKk2UyhXS7uPlHSF7H8JIbCwEf9vwMlE@BUw4wCO5SRMyLttWqn3foHza/Q4wfsD "Lua – Try It Online")
] |
[Question]
[
I am too bored and want a challenge to solve. But I do not see any interesting challenges, and I am too lazy to search for one. Can you (Well, technically your code) suggest me one?
---
# I/O
**Input:** None.
**Output:** A link to a random open(i.e. non-closed) challenge("Challenge" excludes [tips](/questions/tagged/tips "show questions tagged 'tips'")!) on PPCG. You may not link to an answer in a challenge, Just a challenge. (I didn't ask for an interesting answer!)
---
# Examples
**Valid:**
```
http://codegolf.stackexchange.com/questions/93288/make-me-a-mooncake
http://codegolf.stackexchange.com/questions/113796/raise-a-single-number
http://codegolf.stackexchange.com/questions/113898
```
**Invalid:**
```
http://codegolf.stackexchange.com/questions/78152/tips-for-golfing-in-matl (tips question)
http://codegolf.stackexchange.com/questions/113896/josephus-problem (closed)
http://codegolf.stackexchange.com/questions/84260/add-two-numbers/84365#84365 (linked to answer)
```
[Answer]
# JavaScript (ES6), 209 bytes
Does work, but will most likely hit the StackExchange API limit very quickly. It will probably take a while to output the link, as it's checking randomly for a valid question.
```
_=>fetch(`//api.stackexchange.com/2.2/questions/${new Date%2e4}?site=codegolf`).then(_=>_.json()).then((a,b=a.items)=>{if(!b.length||b[0].tags.includes`tips`||b[0].closed_date)f();else console.log(b[0].link)})
```
```
f=_=>fetch(`//api.stackexchange.com/2.2/questions/${new Date%2e4}?site=codegolf`).then(_=>_.json()).then((a,b=a.items)=>{if(!b.length||b[0].tags.includes`tips`||b[0].closed_date)f();else console.log(b[0].link)})
f();
```
[Answer]
# Python 3, ~~452~~ 339 bytes
```
from requests import*
from random import*
while 1:
n=randrange(999999)
r=get("http://api.stackexchange.com/questions/%d?site=codegolf"%n).json()
if r["items"]:
m=r["items"][0]
if "tips" not in m["tags"]:
try:m["closed_date"]
except:print("http://codegolf.stackexchange.com/q/%d"%n);break
```
A bit unsightly and not very golf-y, but I couldn't figure out a better way to do it. Since this more or less brute-forces the API, you'll spend up your quota quite quickly and start getting errors, but after a few hours it'll work again.
EDIT: Saved 113 bytes by removing multiple unnecessary things, thanks to NoOneIsHere.
[Answer]
# SEDE SQL: 79 bytes
```
Select Id from posts where ClosedDate IS NULL AND Tags !='tips' ORDER BY RAND()
```
There are 2 catches. One you have to wait for a while before running again or you have a cache hit (as a mod told me) and you only get the question id number.
] |
[Question]
[
## Introduction
In this challenge, we will be dealing with a certain infinite undirected graph, which I call the *high divisor graph*.
Its nodes are the integers starting from 2.
There is an edge between two nodes **a < b** if **a** divides **b** and **a2 ≥ b**.
The subgraph formed by the range from 2 to 18 looks like this:
```
16-8 12 18
\|/ |/|
4 6 9 10 15 14
| |/ |/ |
2 3 5 7 11 13 17
```
It can be shown that the infinite high divisor graph is connected, so we can ask about the shortest path between two nodes.
## Input and output
Your inputs are two integers **a** and **b**.
You can assume that **2 ≤ a ≤ b < 1000**.
Your output is the length of the shortest path between **a** and **b** in the infinite high divisor graph.
This means the number of edges in the path.
You may find the following fact useful: there always exists an optimal path from **a** to **b** that's first increasing and then decreasing, and only visits nodes that are strictly less than **2b2**.
In particular, since **b < 1000** you only need to consider nodes less than 2 000 000.
## Examples
Consider the inputs `3` and `32`.
One possible path between the nodes 3 and 32 is
```
3 -- 6 -- 12 -- 96 -- 32
```
This path has four edges, and it turns out there are no shorter paths, so the correct output is `4`.
As another example, an optimal path for `2` and `25` is
```
2 -- 4 -- 8 -- 40 -- 200 -- 25
```
so the correct output is `5`.
In this case, no optimal path contains the node `50 = lcm(2, 25)`.
## Rules and scoring
You can write a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.
There are no time or memory limits, so brute forcing is allowed.
## Test cases
```
2 2 -> 0
2 3 -> 4
2 4 -> 1
2 5 -> 5
3 5 -> 4
6 8 -> 2
8 16 -> 1
12 16 -> 2
16 16 -> 0
2 25 -> 5
3 32 -> 4
2 256 -> 3
60 77 -> 3
56 155 -> 3
339 540 -> 2
6 966 -> 4
7 966 -> 2
11 966 -> 4
2 997 -> 7
991 997 -> 4
```
[Answer]
# Matlab, ~~218~~ ~~190~~ 175 bytes
```
function f(a,b);q=a;l(b)=0;l(a)=1;while~l(b);x=q(1);q=q(2:end);l(end+1:x^2)=0;g=x+1:x^2;s=2:x-1;u=[g(~mod(g,x)),s(~mod(x,s)&s.^2>=x)];u=u(~l(u));q=[q,u];l(u)=l(x)+1;end;l(b)-1
```
Thanks @beaker for the shortcut in in the list lengthening step!
This is a relatively straightforward dijkstra implementation:
```
q=a; %queue
l(b)=0; %list of path lengths
l(a)=1;
while~l(b); %if there is no predecessor to b
x=q(1); %get first queue element
q=q(2:end);
%add edges
l(end+1:x^2)=0;% lengthen predecessor list if too short
g=x+1:x^2; % g=greater neighbours
s=2:x-1; % s=smaller neighbours %keep only valid/unvisited neighbours
u=[g(~mod(g,x)),s(~mod(x,s)&s.^2>=x)]; %-1byte
u=u(~l(u));
q=[q,u]; %add only hte valid nodes edges to queue
l(u)=l(x)+1; %mark x as predecessor
end;
l(b)-1 %output length to the end of the path
```
no convolution today
[Answer]
## JavaScript (ES6), 186 bytes
```
(m,n)=>(g=i=>{for(q=[i],r=[],r[i]=j=0;i=q[j++];)for(k=i+i;k<=i*i&(k<m*m*2|k<n*n*2);k+=i)r[k]-r[i]<2?0:r[q.push(k),k]=r[i]+1},g(m),s=r,g(n),Math.min(...r.map((i,j)=>i+s[j]).filter(i=>i)))
```
Uses a helper function `g` to calculate all the ascending paths from `m` and `n` in turn up to the provided limit, then sums the paths together and returns the lowest value.
[Answer]
# Mathematica 98 bytes
I am assuming that the built-in function, `FindShortestPath` does not violate the constraint about standard loopholes. If it does, just let me know and I'll delete this submission.
Brute force, hence slow with large values of `b`. I'm still thinking of ways to speed it up.
```
h@{a_,b_}:=Length@FindShortestPath[Graph[Apply[Join,Thread[#<->Range[2,#] #]&/@Range[b^2]]],a,b]-1
```
This sets up a graph with appropriate edges between the nodes from `a` to `b^2`. `FindShortestPath`finds the shortest path in the graph. `Length`counts the nodes; `Length -1` is the number of edges.
`Thread[# <-> Range[2, #] #] &` produces the edges of the full graph. For example, `Thread[# <-> Range[2, #] #]&[5]` would produce the edges `{5 <-> 2*5, 5 <-> 3*5, 5 <-> 4*5, 5 <-> 5*5}`, that is, `{5 <-> 10, 5 <-> 15, 5 <-> 20, 5 <-> 25}`.
[Answer]
## Matlab ~~(195)(185)(181)(179)~~(173)
>
> **Note:** Me the user Agawa001 personally I attest that I won over the user @flawr [making use of his assistance](https://codegolf.stackexchange.com/questions/79715/shortest-paths-in-a-divisor-graph#comment196123_79742)
>
>
>
```
function t(a,b,p),for r=0:1,d=(b*~r+r*a)/gcd(a,b);while(d>1)p=p+1;e=find(~rem(d,1:d));f=max(e(a^(1-r/2)>=e));a=a*min([find(1:a*a>=b) a])^~(f-1);d=d/f;a=a*f^(1-2*r);end,end,p
```
* This function is different drom others, it does follow a bunch of pure mathematical calculations and factorisations but has nothing to do with paths or graphs.
* Example of function call:
```
t(2,3,0)
p =
4
```
[All test cases are satisfied](http://www.tutorialspoint.com/execute_octave_online.php?PID=0Bw_CjBb95KQMWmNHY0Q1Mm1EdlE)
* ***Explanation:***
Before beginning with explanations lets prove some lemmas "not green ones":
***Lemma(1):** An optimal path between any two numbers `(a,b)` exists in a way the nodes are firstly increasing then decreasing.*
Why ? This is simply proven because the maximal integer amount that divides any number `a` is respectively big as the number `a` itself, so as a clever approach we must choose to multiply `a` as much as possible to make it sufficiently bigger, then dividing by bigger values. If ever we do the way round, the number `a` shrinks, so we need needlessly more iterations to multiply it gradually that we are dispensed with.
***Lemma(2):** From a number `a` to `b`, if `gcd(a,b)=1` `a` is multiplied by `b`, if `b` is bigger than `a` it will be multiplied by a known number `c`, if `gcd>1` `a` must be multiplied gradually by the biggest divisor of `b/gcd` named `d` that verifies the condition `a >= d` also when all `d`'s namely the minimum are bigger than `a`, `a` receives `a*c` again.*
This assumption is simple to prove any starting node `a` must be multiplied until it reaches the smallest multiple of `a` and `b` so either we multiply by proportions of `b*gcd` beginning by the maximum which verifies the main condition, that guarantees always the shortest path to smp before division process begins, or when `d` isnt available a number `c` is multiplied by `a` to make a valid condition `a>=d` for this first stage.
***Lemma(3):** From a graph-ultimum multiple of `a` to `b`, the gcd of this number and `b` is `b` itself*
Well this is just a consequence of the previous manipulations, and the last remaining steps are also done gradually dividing by the biggest divisor which doesnt exceed its square root.
**Dilemma:** What is the optimum number `c` to be iteratively multiplied by `a` that would lead straight along to the opening condition for stage 1 then the ultimum?
Good question, for any simple situation there is a simple parry, so assuming an example of two ends `(a,b)=(4,26)` factorized like this:
```
2 | 2
2 | 13
```
Apart from the `gcd=2` the smallest integer wich must be multiplied by `2` to reach `13` is `7`, but it is obviously ruled out, cuz it is bigger than 2, so a is squared.
```
2 | 2
5 | 13
```
Appearenlty in the second example `(a,b)=(10,26)` above `c` is measured as the lowest integer from `1` to `5` which exceeds `13/5` hence it satisfies the condition of graph-scaling, which is `3`, so the next step here is multiplying by `3`
```
2 | 2
5 | 13
3 |
```
Why ? this is because , once we have to multiply by `2*13/gcd=13` to match the second side of the table, the junk amount we added before is optimally smallest, and moving along the graph is minimized, if ever we multiplied by bigger value like `10` the chance of dividing by the least times reduces, and it would have been increased by 1 another dividing step to reach our goal `2*13`. which are enumerated to: `13*2*5*10/2*5` then `13*2*5/5`.
Whilst, obviously here the number to be divided by is `5*3<13*2`
and one more thing ........ HAIL MATHS...
---
[These are my comparative results with @flawr 's ones](http://www.tutorialspoint.com/execute_octave_online.php?PID=0Bw_CjBb95KQMQlY2R1J1LWpHYU0) just pay attention that i made an upper bound for time execution consering flawr's algorithm, it takes too much time!
You may insert the starting and ending scanning ranges as variables a and b in the header of online compilable code.
] |
[Question]
[
Totally not inspired by [Visualize long division with ASCII art](https://codegolf.stackexchange.com/questions/1624/visualize-long-division-with-ascii-art) ;)
Your job is to show long hand addition with ASCII art. You solve longhand addition by adding up the columns right to left, placing the value of the ones place in the result, and carrying the tens place over to the top of the next column.
## Input
Input can come basically in any format you want, just as long as you take from 2 to 9 numbers as input.
## Output
The formatting here likely matches how you learned it in school:
```
carry row
number1
number2
...
+ numX
--------
result
```
You can have just about any amount of trailing whitespace you want here ;)
## Examples
```
50, 50
1
50
+50
---
100
1651, 9879
1111
1651
+9879
-----
11530
6489789, 9874, 287
1122
6489789
9874
+ 287
--------
6499950
```
[Answer]
# Pyth, ~~59~~ 58 bytes
```
L.[dJhl`eSQ`b:jk_.u/+NsYT.t_MjRTQ00\0djbyMPQXyeQ0\+*J\-ysQ
```
[Try it online.](https://pyth.herokuapp.com/?code=L.[dJhl%60eSQ%60b%3Ajk_.u%2F%2BNssMYT.t_M%60MQ00%5C0djbyMPQXyeQ0%5C%2B*J%5C-ysQ&input=[6489789%2C+9874%2C+287]&debug=0) [Test suite.](https://pyth.herokuapp.com/?code=L.[dJhl%60eSQ%60b%3Ajk_.u%2F%2BNssMYT.t_M%60MQ00%5C0djbyMPQXyeQ0%5C%2B*J%5C-ysQ&test_suite=1&test_suite_input=50%2C+50%0A1651%2C+9879%0A6489789%2C+9874%2C+287&debug=0)
Way too long. Should golf more.
### Explanation
```
L helper function y = lambda b:
eSQ largest number in input
l` length as string
h increment
J save to J
.[d `b pad argument with spaces to that length
carry row:
jRTQ each input to base 10
_M reverse each result
.t 0 transpose, padding with zeroes
.u 0 cumulative reduce from 0:
sY sum digits of column
+N add previous carry
/ T floor-divide by 10
_ reverse
jk join by ""
: \0d replace 0 by space
number rows:
PQ all input numbers but last one
yM pad to correct length
jb print on separate lines
last number row:
eQ last input number
y pad to correct length
X 0\+ change first char to +
separator row:
J width of input (saved in helper)
* \- that many dashes
result row:
sQ sum of inputs
y pad to correct length
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 48 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
¢≈3ä⌂♪s♂N#┼DuΦeÑα▼dσÿóYRC├[♂≡α%┴&UZ≤§╟Ω^j╪♪■∞xëa
```
[Run and debug it](https://staxlang.xyz/#p=9bf733847f0d730b4e23c54475e865a5e01f64e598a2595243c35b0bf0e025c126555af315c7ea5e6ad80dfeec788961&i=%5B50,50%5D%0A%5B1651,+9879%5D%0A%5B6489789,+9874,+287%5D&m=2)
`)` is a lifesaver here, but it still feels too long.
[Answer]
## Batch, 326 bytes
Byte count does not include explanation, of course.
```
@echo off
set t=%* Get the space separated parameters
set t=%t: =+% Change the spaces into + signs
set/at=%t%,l=p=1 Add together, and initialise length and power
set c= Carry string
set d=- Dash string
:l Loop though each power of 10
set/al+=1,p*=10,s=t/p Divide the total by the power
for %%n in (%*)do set/as-=%%n/p Subtract each parameter divided
set c=%s%%c% Anything left must have been carried
set d=-%d% Add a - to the line of dashes
if %p% leq %t% goto l Keep going until we run out of powers
echo(%c:0= % Delete any zeros in the carry and output it
:i Loop through each parameter
set n=%d:-= %%1 Pad it with a whole bunch of spaces
call set n=%%n:~-%l%%% Extract the rightmost characters
if "%2"=="" set n=+%n:~1% Insert a + before the last parameter
echo %n% And output it
shift Move to the next parameter
if not "%1"=="" goto i Until they are all consumed
echo %d% Output the line of dashes
echo %t% Output the total (with an indent for the +)
```
[Answer]
## JavaScript (ES6), 199 bytes
```
a=>[[...t=` `+a.reduce((t,n)=>t+n)].map((_,i)=>a.reduce((c,n)=>c-n[i],90+t[i])%10||` `),a=a.map(n=>(` `.repeat(l=t.length)+n).slice(-l))).join``,...a,`-`.repeat(l),t].join`\n`.replace(/ (?=.*\n-)/,`+`)
```
Where the first `\n` represents a literal newline character, while the second one is a two-character regexp escape sequence. Explanation:
```
a=>[ Accept an array of numbers
[... Split the total into digits
t=` `+a.reduce((t,n)=>t+n) Calculate the total and add a space
].map((_,i)=>a.reduce((c,n)=> For each column
c-n[i],90+t[i]) Subtract the column from the total
%10||` `), Deduce the carry that was needed
a=a.map(n=> For each input value
(` `.repeat(l=t.length)+n) Pad to the length of the total
.slice(-l)) Remove excess padding
).join``, Join the carries together
...a, Append the padded input values
`-`.repeat(l), Append the dividing line
t].join`\n` Append the total and join together
.replace(/ (?=.*\n-)/,`+`) Insert the + on the line above the -
```
The carry calculation works by taking the total digit, prefixing `90`, subtracting all the input value digits in that column, and taking the result modulo 10. (The prefix is `90` rather than `9` so that the leading column generates a blank carry space.)
] |
[Question]
[
I have been recently told to read an entire physics textbook by the new year (true story, unfortunately). I need your help to determine what chapters I should read each day. This is where you come in.
## Input
* Two dates, in any format. The second date will always be later than the first.
* A list of chapter numbers. This comma-separated list can contain single chapters (`12`) or inclusive ranges (`1-3`). Ex. `1-3,5,6,10-13`.
* A list of weekdays (represented by the first two letters of the name: `Monday -> Mo`) to exclude from the schedule. Ex. `Mo,Tu,Fr`.
## Output
Output will be a newline-separated list of dates and chapter numbers (see format below). The chapters should be evenly distributed over all days in the range, excluding the weekdays provided. If the chapters do not distribute evenly, have the days with lower amounts of chapters at the end of the period of time. Dates in output can be in a different format than input. Days with no chapters can be ommited, or just have no chapters with it.
Example:
Input: `9/17/2015 9/27/2015 1-15 Tu`
Output:
```
9/17/2015: 1 2
9/18/2015: 3 4
9/19/2015: 5 6
9/20/2015: 7 8
9/21/2015: 9 10
9/23/2015: 11
9/24/2015: 12
9/25/2015: 13
9/26/2015: 14
9/27/2015: 15
```
[Answer]
# JavaScript (ES6), ~~317~~ ~~310~~ 291 bytes
```
(a,b,c,d)=>{u=0;c.split`,`.map(m=>{p=m[s]`-`;for(q=n=p[0];n<=(p[1]||q);r=++u)c+=","+n++},c="");c=c.split`,`;x=d.map(p=>"SuMoTuWeThFrSa".search(p)/2);for(g=[];a<b;a.setTime(+a+864e5))x.indexOf(a.getDay())<0&&(t=y=g.push(a+" "));return g.map(w=>w+c.slice(u-r+1,u-(r-=r/y--+.99|0)+1)).join`
`}
```
## Usage
```
f(new Date("2015-09-17"),new Date("2015-09-27"),"5,1-4,6,10-13,20-27",["Su","Tu"])
=> "Thu Sep 17 2015 10:00:00 GMT+1000 (AUS Eastern Standard Time) 5,1,2
Fri Sep 18 2015 10:00:00 GMT+1000 (AUS Eastern Standard Time) 3,4,6
Sat Sep 19 2015 10:00:00 GMT+1000 (AUS Eastern Standard Time) 10,11
Mon Sep 21 2015 10:00:00 GMT+1000 (AUS Eastern Standard Time) 12,13
Wed Sep 23 2015 10:00:00 GMT+1000 (AUS Eastern Standard Time) 20,21
Thu Sep 24 2015 10:00:00 GMT+1000 (AUS Eastern Standard Time) 22,23
Fri Sep 25 2015 10:00:00 GMT+1000 (AUS Eastern Standard Time) 24,25
Sat Sep 26 2015 10:00:00 GMT+1000 (AUS Eastern Standard Time) 26,27"
```
## Explanation
```
(a,b,c,d)=>{
u=0; // u = total chapters
c.split`,`.map(m=>{ // c = array of each chapter
p=m[s]`-`;
for(q=n=p[0];n<=(p[1]||q);r=++u) // get each chapter from ranges
c+=","+n++
},c="");
c=c.split`,`;
x=d.map(p=>"SuMoTuWeThFrSa".search(p)/2); // x = days to skip
for(g=[];a<b;a.setTime(+a+864e5)) // for each day between a and b
x.indexOf(a.getDay())<0&& // if this day is not skipped
(t=y=g.push(a+" ")); // add it to the list of days
// t = total days
// y = days remaining
return g.map(w=>w+
c.slice(u-r+1,u-(r-=r/y--+.99|0)+1) // add the chapters of the day
).join`
`
}
```
[Answer]
## PowerShell v4, ~~367~~ ~~357~~ ~~323~~ ~~313~~ ~~308~~ ~~307~~ ~~305~~ 277 Bytes
```
param($a,$b,$c,$d)$e=@();$c=-split('('+($c-replace'-','..'-replace',','),(')+')'|iex|%{$_-join' '});while($a-le$b){if(-join"$($a.DayOfWeek)"[0,1]-notin$d){$e+=$a;$z++}$a=$a.AddDays(1)}$g=,0*$z;$c|%{$g[$c.IndexOf($_)%$z]++};1..$z|%{"$($e[$_-1]): "+$c[$i..($i+=$g[$_-1]-1)];$i++}
```
Edit - golfed 28 bytes by using explicit input formatting.
### Explained:
```
param($a,$b,$c,$d) # Parameters, takes our four inputs
$e=@() # This is our array of valid output dates
$c=-split('('+($c-replace'-','..'-replace',','),(')+')'|iex|%{$_-join' '})
# Ridiculously complex way to turn the input chapters into an int array
# The first part changes "1,5-9,12" into a "(1),(5..9),(12)" format that
# PowerShell understands, then executes that with iex, which creates an
# array of arrays. Then iterate through each inner array and joins them all
# together with spaces, then finally splits on spaces to create a 1D array
while($a-le$b){ # Until we reach the end day
if(-join"$($a.DayOfWeek)"[0,1]-notin$d){
# Not an excluded day of the week
$e+=$a # Add it to our list of days
$z++ # Increment our count of total days
}
$a=$a.AddDays(1) # Move to the next day in the range
}
$g=,0*$z # Populate a new array with zeroes, same length as $e
$c|%{$g[$c.IndexOf($_)%$z]++}
# This populates $g for how many chapters we need each day
1..$z|%{"$($e[$_-1]): "+$c[$i..($i+=$g[$_-1]-1)];$i++}
# Goes through the days in $e, prints them, and slices $c based on $g
```
### Usage
Expects the dates to be in .NET `DateTime` format. Expects the "skipped" days to be in an array (PowerShell equivalent of a list).
```
PS C:\Tools\Scripts\golfing> .\help-me-manage-my-time.ps1 (Get-Date '9/17/2015') (Get-Date '9/27/2015') '5,1-3,6,10-13,20-27' @('Su','Tu')
09/17/2015 00:00:00: 5 1 2
09/18/2015 00:00:00: 3 6
09/19/2015 00:00:00: 10 11
09/21/2015 00:00:00: 12 13
09/23/2015 00:00:00: 20 21
09/24/2015 00:00:00: 22 23
09/25/2015 00:00:00: 24 25
09/26/2015 00:00:00: 26 27
```
[Answer]
# Python 2 - ~~338~~ ~~317~~ ~~308~~ ~~304~~ 300
Here we go to get the ball rolling ...
```
def f(a,b,c,d):
from pandas import*;import numpy as n
s=str.split;e=n.array([])
for g in s(c,','):h=s(g,'-');e=n.append(e,range(int(h[0]),int(h[-1])+1))
k=[t for t in date_range(a,b) if s('Mo Tu We Th Fr Sa Su')[t.weekday()]not in d];j=len(k);e=array_split(e,j)
for u in range(j):print k[u],e[u]
```
Example input:
```
f('9/17/2015','9/27/2015','5,1-3,6,10-13,20-27',['Su','Tu'])
```
Example Output:
```
2015-09-17 00:00:00 [ 5. 1. 2.]
2015-09-18 00:00:00 [ 3. 6.]
2015-09-19 00:00:00 [ 10. 11.]
2015-09-21 00:00:00 [ 12. 13.]
2015-09-23 00:00:00 [ 20. 21.]
2015-09-24 00:00:00 [ 22. 23.]
2015-09-25 00:00:00 [ 24. 25.]
2015-09-26 00:00:00 [ 26. 27.]
```
] |
[Question]
[
# Spherical excess of a triangle
As we all know, the sum of angles of any planar triangle is equal to 180 degrees.
However, for a spherical triangle, the sum of angles is always **greater** than 180 degrees. The difference between the sum of the spherical triangle angles and 180 degrees is called **spherical excess** . The task is to compute the spherical excess of a triangle with given vertex coordinates.
## Some background
A spherical triangle is a part of the sphere defined by three great circles of the sphere.
Both sides and angles of spherical triangle are measured in the term of angle measure, because each side can be considered as a intersection of the sphere and some planar angle with vertex at the center of the sphere:
[](https://i.stack.imgur.com/JzCfI.png)
Each three distinct great circles define 8 triangles, but we only take *proper triangles* into consideration, *ie.* triangles whose angle and side measures satisfy
[](https://i.stack.imgur.com/o4J5m.png)
It's convenient to define vertices of a triangle in terms of geographic coordinate system. To compute the length of an arc of sphere given the longitude λ and latitude Φ of its ends we can use formula:
[](https://i.stack.imgur.com/34xgt.png)
, where
[](https://i.stack.imgur.com/Vrx4D.png)
or more explicitely:
[](https://i.stack.imgur.com/hUhjO.png)
(source: <https://en.wikipedia.org/wiki/Haversine_formula>)
The two basic formulas that can be used to solve a spherical triangle are:
* the law of cosines:
[](https://i.stack.imgur.com/0iMyk.png)
* the law of sines:
[](https://i.stack.imgur.com/gejeT.png)
(source: <https://en.wikipedia.org/wiki/Spherical_trigonometry#Cosine_rules_and_sine_rules>)
Given three sides, it's easy to compute the angles using the cosine rule:
[](https://i.stack.imgur.com/AtqTJ.png)
Finally, the spherical excess of a triangle is defined:
[](https://i.stack.imgur.com/0eaCI.png)
What's interesting about the relation between the spherical excess of a triangle and its area:
[](https://i.stack.imgur.com/JcF2C.png)
So on a unit sphere, the excess of a triangle is equal to area of that triangle!
## The task
Write a function or a program that will compute spherical excess of a triangle in degrees given the triangle vertices coordinates.
The vertex coordinates are provided in terms of geographic coordinate system.
Each vertex should be passed in form `[latitude in degrees][N|S][longitude in degrees][E|W]`. Longitude and `E` or `W` can be skipped when latitude is 90 *ie.* `90N`, `90S`, `10N100E`, `30S20W` are proper vertex descriptions, while `80N` or `55S` are not.
The latitudes and longitudes are always integer in the test cases.
The answers with error less than one degree will be accepted (as in examples below). The result can be rendered as both real or integer therefore, up to your convenience.
**Examples**
Input
```
90N0E
0N0E
0N90E
```
Output
```
89.999989
```
Input
```
90N
0N0E
0N90E
```
Output
```
89.999989
```
Input
```
0N0E
0N179E
90N0E
```
Output
```
178.998863
```
Input
```
10N10E
70N20W
70N40E
```
Output
```
11.969793
```
In all test cases longitude and latitude are integer numbers.
Parsing the vertex coordinates is the part of the task, so a vertex must be passed as single string/literal , it's not allowed to pass `80N20E` as four parameters/strings: `80`, `N`, `20`, `E`.
This is guaranteed that vertices are all distinct and neither two of the three vertices make an antipodal points pair.
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins.
[Answer]
# Matlab, ~~288~~ 266 bytes
Here the commented version that should explain what is going on:
```
%parsing the input
for k=1:3;
s=input('','s'); %request input
if sum(s>57)<2; %if we have only one letter, add arbitrary second coordinate
s=[s,'0E'];
end;
S=1-2*(s(s>57)>80); %calculate the sign of the coordinates
s(s>57)=44; %replace letters with comma
L(k,:)=eval(['[',s,']']).*S; %evaluates string as list and multiply with signs
end;
i=[2,3,1];
%calculate the angular distance between each pair of points
a=arrayfun(@distance,L(:,1),L(:,2),L(i,1),L(i,2))*pi/180;
%evaluate the spherical excess
f=@(a,b,c)sum(acos((cos(a)-cos(b).*cos(c))./(sin(b).*sin(c))))-pi;
disp(f(a,a(i),a([3,1,2]))*180/pi)
```
Fully golfed (linebreaks can be removed):
```
for k=1:3;s=input('','s');if sum(s>57)<2;s=[s,'0E'];end;
s(s>57)=44;L(k,:)=eval([91,s,93]).*(1-2*(s(s<48)>80));end;
i=[2,3,1];p=pi/180;a=arrayfun(@distance,L(:,1),L(:,2),L(i,1),L(i,2))*p;
b=a(i);disp((sum(acos((cos(a([3,1,2]))-cos(b).*cos(a))./(sin(b).*sin(a))))-pi)/p)
```
[Answer]
# Ruby, Rev 3 ~~264~~ 255 bytes
Major changes:
New constant `r` = 180/PI defined and used throughout function. `e` had to be initialized to +PI, so excess now counts downwards and is negated before returning.
`t[]` eliminated: Ruby allows the data that was assigned to `t[]` to be directly assigned to `u,v,w.`
Single `i` loop to do the job of two, `?:` ternary operator switches between tasks.
Many other minor changes.
```
include Math
->s{r=180/e=PI
x=y=z=n=[]
9.times{|i|i<6?(u,v,w=eval(?[+s[i%3].gsub(/[NE]/,"/r,").gsub(/[SW]/,"/-r,")+"0]")
i%2<1&&x=y=z=1
n[i/2]=(z*=sin(u))+(y*=cos(v)*w=cos(u))+x*=w*sin(v)):e-=acos((n[i-7]-(c=n[i-6])*d=n[i-8])/sqrt((1-c*c)*(1-d*d)))}
-e*r}
```
# Ruby, Rev 1 ~~283~~ 277 bytes
Requires an array of 3 strings.
```
include Math
->s{x=y=z=n=[]
6.times{|i|t=eval(?[+s[i%3].gsub(/[NE]/,k="*PI/180,").gsub(/[SW]/,"*-1"+k)+"0]")
i%2<1&&x=y=z=1
n[i/2]=(z*=sin(u=t[0]))+(y*=cos(u)*cos(v=t[1]))+(x*=cos(u)*sin(v))}
e=-PI
3.times{|i|e+=acos((n[i-1]-n[i]*d=n[i-2])/sqrt((1-n[i]**2)*(1-d**2)))}
e/PI*180}
```
**Overview**
The lengths of the triangle sides on the unit sphere are equal to the angles between the vectors describing the two points. But we don't need to know that angle. It suffices to know the cosine of the angle, which is easily obtained from cartesian coordinates using the Dot Product.
**Explanation**
The input strings are converted into a string representation of an array, which is then evaluated and stored in `t`, as below. The final zero is not needed if two coordinates are given. If only latitude 90 is given, the zero is interpreted as the longitude.
```
Example: 70N20W --> [70*PI/180,20*-1*PI/180,0]
```
The Dot Products are of the form `a.b=ax*bx+ay*by+az*bz`. As the vectors are all of unit length, the dot product is equal to the cosine of the angle between the vectors.
In order to calculate them a loop is iterated 6 times passing twice through the input data. On even iterations 0,2,4 the variables `x,y,z` are set to 1 to start a new calculation. On each iteration these variables are multiplied by the x,y and z components of each vector, using the longitude and latitude data stored in `t[0],t[1]` (which for golfing reasons is also assigned to `u,v`). The sum of the variables is written to array `n` (the garbage values on even iterations being overwritten by the correct values on odd iterations) so that at the end `n` contains the 3 dot products `[a.b, c.a, b.c]`.
For the cosine rule, we need the cosines of the three included angles between vertices, but we also need the sines. These are obtained as `sqrt(1-cosine**2)`. As the sines are multiplied together the expression can be rearranged so that only one call to `sqrt` is required. The fact that we do not know if the sine was positive or negative does not matter, as the haversine formula always gives the positive sine anyway. The important physical quantity is the distance between the points, which is absolute and therefore always positive.
For each iteration `i=0..2`, we calculate the value for the angle opposite array element `i-1` using the other elements `i` and `i-2`. Negative array subscripts like this are legal in Ruby, they just wrap around to the beginning of the array.
**Ungolfed in test program**
Requires three sets of coordinates on the same line, with spaces between them.
```
include Math
g=->s{
n=[] #array for dot products
x=y=z=1 #it's required to use these variables once before the loop, for some bizarre reason
6.times{|i|
t=eval(?[+s[i%3].gsub(/[NE]/,k="*PI/180,").gsub(/[SW]/,"*-1"+k)+"0]")
i%2<1&&x=y=z=1
n[i/2]=(z*=sin(u=t[0]))+(y*=cos(u)*cos(v=t[1]))+(x*=cos(u)*sin(v))
}
e=-PI #set e to -PI and begin accumulating angles
3.times{|i|
e+=acos((n[i-1]-n[i]*n[i-2])/sqrt((1-n[i]**2)*(1-n[i-2]**2)))
}
e/PI*180} #return value
puts g[gets.split]
```
] |
[Question]
[
A linear [Diophantine equation](https://en.wikipedia.org/wiki/Diophantine_equation) in two variables is an equation of the form **ax + by = c**, where **a**, **b** and **c** are constant integers and **x** and **y** are integer variables.
For many naturally occurring Diophantine equations, **x** and **y** represent quantities that cannot be negative.
### Task
Write a program or function that accepts the coefficients **a**, **b** and **c** as input and returns an arbitrary pair of **natural numbers** (0, 1, 2, …) **x** and **y** that verify the equation **ax + by = c**, if such a pair exists.
### Additional rules
* You can choose any format for input and output that involves only the desired integers and, optionally, array/list/matrix/tuple/vector notation of your language, as long as you don't embed any code in the input.
* You may assume that the coefficients **a** and **b** are both non-zero.
* Your code must work for any triplet of integers between **-260** and **260**; it must finish in under a minute on my machine (Intel i7-3770, 16 GiB RAM).
* You may not use any built-ins that solve Diophantine equations and thus trivialize this task, such as Mathematica's [`FindInstance`](https://reference.wolfram.com/language/ref/FindInstance.html) or [`FrobeniusSolve`](https://reference.wolfram.com/language/ref/FrobeniusSolve.html).
* Your code may behave however you want if no solution can be found, as long as it complies with the time limit and its output cannot be confused with a valid solution.
* Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply.
### Examples
1. The examples below illustrate valid I/O for the equation **2x + 3y = 11**, which has exactly two valid solutions ( **(x,y) = (4,1)** and **(x,y) = (1,3)** ).
```
Input: 2 3 11
Output: [4 1]
Input: (11 (2,3))
Output: [3],(1)
```
2. The only valid solution of **2x + 3y = 2** is the pair **(x,y) = (1,0)**.
3. The examples below illustrate valid I/O for the equation **2x + 3y = 1**, which has **no valid solutions**.
```
Input: (2 3 1)
Output: []
Input: 1 2 3
Output: -1
Input: [[2], [3], [1]]
Output: (2, -1)
```
4. For **(a, b, c) = (1152921504606846883, -576460752303423433, 1)**, all correct solutions **(x,y)** satisfy that **(x,y) = (135637824071393749 - bn, 271275648142787502 + an)** for some non-negative integer **n**.
[Answer]
# Pyth, 92 bytes
```
I!%vzhK%2u?sm,ed-hd*ed/F<G2cG2@G1G+~Q,hQ_eQj9 2)J*L/vzhKtKeoSNm-VJ/RhK_*LdQsm+LdtM3/V*LhK_JQ
```
It's quite a monster.
Try it online: [Demonstration](https://pyth.herokuapp.com/?code=I!%25vzhK%252u%3Fsm%2Ced-hd*ed%2FF%3CG2cG2%40G1G%2B~Q%2ChQ_eQj9+2)J*L%2FvzhKtKeoSNm-VJ%2FRhK_*LdQsm%2BLdtM3%2FV*LhK_JQ&input=11%0A%5B2%2C+3%5D&debug=0). The input format is `c\n[a,b]` and the output format is `[x,y]`.
In the case that no integer solution exists, I'll print nothing, and in the case that no natural integer solution exists, I'll simply print a random integer solution.
### Explanation (Rough Overview)
1. At first I'll find an integer solution to the equation `ax + by = gcd(a,b)` by using the Extended Euclidean algorithm.
2. Then I'll modify the solution (my multiplying `a` and `b` with `c/gcd(a,b)`) to get an integer solution of `ax + by = c`. This works, if `c/gcd(a,b)` is an integer. Otherwise there doesn't exist a solution.
3. All the other integer solutions have the form `a(x+n*b/d) + b(y-n*a/d) = c` with `d = gcd(a,b)` for integer `n`. Using the two inequalities `x+n*b/d >= 0` and `y-n*a/d >= 0` I can determine 6 possible values for `n`. I'll try all 6 of them and print the solution with the highest lowest coefficient.
### Explanation (Detailed)
The first step is to find an integer solution to the equation `ax' + by' = gcd(a,b)`. This can be done by using the extended Euclidean algorithm. You can get an idea on how it works at [Wikipedia](https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm#Example). The only difference is, that instead of using 3 columns (`r_i s_i t_i`) I'll use 6 columns (`r_i-1 r_i s_i-1 s_i t_i-1 t_i`). This way I don't have to keep the last two rows in memory, only the last one.
```
K%2u?sm,ed-hd*ed/F<G2cG2@G1G+~Q,hQ_eQj9 2) implicit: Q = [a,b] (from input)
j9 2 convert 9 to base 2: [1,0,0,1]
+ Q add to Q => [a,b,1,0,0,1]
this is the initial row
u ) start with G = ^ and update G repeatedly
by the following expression, until
the value of G doesn't change anymore
? @G1 if G[1] != 0:
cG2 split G into parts of 2
m map the parts d to:
, the pair
ed d[1]
-hd*ed/F<G2 d[0]-d[1]*G[0]/G[1]
s unfold
else:
G G (don't change it, stop criterion for u)
%2 take every second element
we get the list [gcd(a,b),x',y']
K store this list in K
~Q,hQ_eQ afterwards change Q to [Q[0],-Q[1]] = [a,-b]
This will be important for the other parts.
```
Now I want to find a solution to `ax + by = c`. This is possible only, when `c mod gcd(a,b) == 0`. If this equation is satisfied, I simply multiplying `x',y'` with `c/gcd(a,b)`.
```
I!%vzhK...J*L/vzhKtK implicit: z = c in string format (from input)
%vzhK evaluated(z) mod K[0] (=gcd(a,b))
I! if not ^ than:
/vzhK c/K[0]
*L tK multipy ^ to each element in K[1:] (=[x',y'])
J and store the result in J, this is now [x,y]
```
We have an integer solution for `ax + by = c`. Notice, that `x`, `y` or both may be negative. So our goal is to transform these to non-negative.
The nice thing about Diophantine equations is, that we can describe all solution using only one initial solution. If `(x,y)` is a solution, that all other solutions are of the form `(x-n*b/gcd(a,b),y+n*a/gcd(a,b))` for `n` integer.
Therefore we want to find a `n`, where `x-n*b/gcd(a,b) >= 0` and `y+n*a/gcd(a,b >= 0`. After some transformation we end up with the two inequalities `n >= -x*gcd(a,b)/b` and `n >= y*gcd(a,b)/a`. Notice that the inequality symbol might look in the other direction due the division with a potential negative `a` or `b`. I don't care that much about it, I simply say that one number of `-x*gcd(a,b)/b - 1, -x*gcd(a,b)/b, -x*gcd(a,b)/b + 1` definitly satisfies inequality 1, and one number of `y*gcd(a,b)/a - 1, y*gcd(a,b)/a, y*gcd(a,b)/a + 1` satisfies inequality 2. It there is a `n`, that satisfies both inequalities, one of the 6 numbers also does.
Then I calculate the new solutions `(x-n*b/gcd(a,b),y+n*a/gcd(a,b))` for all 6 possible values of `n`. And I print the solution with the highest lowest value.
```
eoSNm-VJ/RhK_*LdQsm+LdtM3/V*LhK_JQ
_J reverse J => [y,x]
*LhK multiply each value with K[0] => [y*gcd,x*gcd]
/V Q vectorized division => [y*gcd/a,-x*gcd/b]
m map each d of ^ to:
tM3 [-1,0,1]
+Ld add d to each ^
s unfold
these are the possible values for n
m map each d (actually n) of ^ to:
*LdQ multiply d to Q => [a*n,-b*n]
_ reverse => [-b*n,a*n]
/RhK divide by K[0] => [-b*n/gcd,a*n/gcd]
-VJ vectorized subtraction with J
=> [x+b*n/gcd,y-a*n/gcd]
oSN order the solutions by their sorted order
e print the last one
```
The sort by their sorted order thing works the following way. I'm using the example `2x + 3y = 11`
I sort each of the 6 solutions (this are called keys), and sort the original solutions by their keys:
```
solutions: [1, 3], [4, 1], [7, -1], [-5, 7], [-2, 5], [1, 3]
keys: [1, 3], [1, 4], [-1, 7], [-5, 7], [-2, 5], [1, 3]
sort by key:
solutions: [-5, 7], [-2, 5], [7, -1], [1, 3], [1, 3], [4, 1]
keys: [-5, 7], [-2, 5], [-1, 7], [1, 3], [1, 3], [1, 4]
```
This sorts a complete non-negative solution to the end (if there is any).
[Answer]
* after Dennis' remarks, that made my previous idea upside-down, i had to change the code from its roots and it took me long term debugging, and cost me twice n° of bytes :'(.
## Matlab (660)
```
a=input('');b=input('');c=input('');if((min(a*c,b*c)>c*c)&&a*c>0&&b*c>0)||(a*c<0&&b*c<0),-1,return,end,g=abs(gcd(a,b));c=c/g;a=a/g;b=b/g;if(c~=floor(c)),-1,return,end,if(c/a==floor(c/a)&&c/a>0),e=c/a-b;if(e>0),e,a,return,else,c/a,0,return,end,end,if(c/b==floor(c/b)&&c/b>0),e=c/b-a;if(e>0),b,e,return,else,0,c/b,return,end,end,f=max(abs(a),abs(b));if f==abs(a),f=b;b=a;a=f;g=0.5;end,e=(c-b)/a;f=(c-2*b)/a;if(e<0&&f<e),-1,elseif(e<0&&f>e),for(i=abs(c*a):abs((c+1)*a)),e=(c-i*b);if(mod(e,a)==0)if(g==0.5),i,e/a;else,e/a,i,end,return,end,end,else for(i=1:abs(a)),e=(c-i*b);if(e/a<0),-1,elseif(mod(e,a)==0),if(g==0.5),i,e/a,else,e/a,i,end,return,end,end,end,-1
```
>
> * Well , i know its not golfed, since that type of languages isnt adapted for code length reduction, but, i can ensure that time-complexity is at its best.
>
>
>
## Explanation:
* the code takes three invariants a,b,c as input, these last ones are subdued to couple of conditions before proceeding to calculate:
1- if (a+b>c) and (a,b,c>0) no solution!
2- if (a+b < c) ,(a,b,c<0) no solution!
3- if (a, b) have common opposite signs of c : no solution!
4- if GCD(a,b) dosnt divide c, then no solution again! , otherwise, divide all variants by GCD.
* after this , we have to check another condition out, it should ease and shorteb the way to desired solution.
5- if c divide a or b , solution s= (x or y)=(c-[ax,yb])/[b,a]=C/[b,a]+[ax,yb]/[b,a]=S+[ax,yb]/[b,a] where S is natural so ax/b or by/a would have henceforth non-negative direct solutions which are respectively x=b or y=a . (notice that solutions can be just nil values in case previous arbitrary solutions are revealed negatives)
* when the program reaches this stage, a narrower range of solutions for x=(c-yb)/a is swept instead, thanks to congruence, of sweeping larger ranges of numbers ,which is come accross repetitively by regular cycles. the largest search field is [x-a,x+a] where a is the divisor.
## [TRY IT](http://rextester.com/NDXGP44424)
[Answer]
# Axiom, 460 bytes
```
w(a,b,x,u)==(a=0=>[b,x];w(b rem a,a,u,x-u*(b quo a)))
d(a,b,k)==(o:List List INT:=[];a=0 and b=0=>(k=0=>[1,1];[]);a=0=>(k=0=>[[1,0]];k rem b=0=>[1,k quo b];[]);b=0=>(k=0=>[[0,1]];k rem a=0=>[k quo a,1];[]);r:=w(a,b,0,1);q:=k quo r.1;(y,x,u,v):=(q*(r.1-r.2*a)quo b,q*r.2,b quo r.1,a quo r.1);m:=min(80,4+abs(k)quo min(abs(a),abs(b)));l:=y quo v;x:=x+l*u;y:=y-l*v;for n in -m..m repeat(t:=x+n*u;z:=y-n*v;t>=0 and z>=0 and t*a+z*b=k=>(o:=cons([t,z],o)));sort(o))
```
ungolf and some test
```
-- input a b and k for equation a*x+b*y=k
-- result one List of List of elments [x,y] of solution of
-- that equation with x and y NNI (not negative integers)
-- or Void list [] for no solution
diopanto(a,b,k)==
o:List List INT:=[]
a=0 and b=0=>(k=0=>[1,1];[])
a=0=>(k=0=>[[1,0]];k rem b=0=>[1,k quo b];[])
b=0=>(k=0=>[[0,1]];k rem a=0=>[k quo a,1];[])
r:=w(a,b,0,1)
q:=k quo r.1
(y,x,u,v):=(q*(r.1-r.2*a)quo b,q*r.2,b quo r.1,a quo r.1)
m:=min(80,4+abs(k)quo min(abs(a),abs(b)))
l:=y quo v -- center the interval
x:=x+l*u; y:=y-l*v
for n in -m..m repeat
t:=x+n*u;z:=y-n*v
t>=0 and z>=0 and t*a+z*b=k=>(o:=cons([t,z],o))
sort(o)
------------------------------------------------------
(4) -> d(0,-9,0)
(4) [[1,0]]
Type: List List Integer
(5) -> d(2,3,11)
(5) [[4,1],[1,3]]
Type: List List Integer
(6) -> d(2,3,2)
(6) [[1,0]]
Type: List List Integer
(7) -> d(2,3,1)
(7) []
Type: List List Integer
(8) -> d(1152921504606846883,-576460752303423433,1)
(8)
[[135637824071393749,271275648142787502],
[712098576374817182,1424197152749634385],
[1288559328678240615,2577118657356481268],
[1865020080981664048,3730040161963328151],
[2441480833285087481,4882961666570175034]]
Type: List List Integer
```
In the other 'solutions' possible there was a bug because
it tried to save the infinite solutions in one List; now it is
imposed the limit of 80 solutions max
] |
[Question]
[
In a puzzle in an old book of mine, a game is defined in which two players choose sequences of coin flips that they believe will appear first when a coin is repeatedly flipped. (It was actually odd and even dice rolls, but this little detail doesn't matter in terms of problem equivalence.)
It is noted that if player 1 chooses `TTT` and player 2 chooses `HTT`, that player 2 has a 7/8 chance of winning the game, since the only way `TTT` can come before `HTT` is if the first three flips are all tails.
Your job is to create a program or function that will deduce the probability that one of two chosen sequences will comes first. Your program will take two lines of input (or two strings as arguments), each representing a sequence of length 10 or less:
```
HTT
TTT
```
And output the probability that the *first* player will win, in either fraction or decimal form:
```
7/8
0.875
```
The shortest code to do this in any language wins.
[Answer]
## Python 3 (~~139~~ ~~136~~ ~~134~~ ~~132~~ ~~126~~ ~~115~~ 143)
Uses Conway's Algorithm as described at [here](http://plus.maths.org/content/os/issue55/features/nishiyama/index). Handles all sequence pairs as long as the first is not a terminating subsequence of the second (as per instructions).
```
def f(a,b):c=lambda x,y=a:sum((x[~i:]==y[:i+1])<<i for i in range(len(x)));return 0 if b in a else(1/(1+(c(a)-c(a,b))/(c(b,b)-c(b))),1)[a in b]
```
Thanks xnor for shaving 6 bytes off. Thanks Zgarb for spotting a bug with subsequences.
[Answer]
# CJam, ~~44 38~~ 36 bytes
Using the same Conway's Algorithm as in [here](http://plus.maths.org/content/os/issue55/features/nishiyama/index).
```
ll]_m*{~1$,,@f>\f{\#!}2b}/\-:X--Xd\/
```
Input is the two distinct sequences in two lines. The output is the probability of first winning over second. The inputs need not be of same lengths
I am using the formula for winning odds (*`p`*) for first player A as

Then the probability is defined as

which, after simplifying becomes

and after some simplification, becomes

---
Example input:
```
HTT
TTT
```
Output:
```
0.875
```
[Try it online here](http://cjam.aditsu.net/)
[Answer]
# Lua 211 190 184
Also using Conway's Algorithm.
Still new to Lua so this can be golfed more for sure.
```
z=io.read;e=function(s,t)r='';for d in s:gmatch"."do r=r..(d==t:sub(1,1)and 1 or 0);end;return tonumber(r,2);end;a=z();b=z();print((e(a,a)-e(a,b))/(e(b,b)-e(b,a))/(1/((1/2)^b:len())));
```
### Ungolfed
```
z=io.read;
e=function(s,t)
r='';
for d in s:gmatch"."do
r=r..(d==t:sub(1,1)and 1 or 0);
end;
return tonumber(r,2);
end;
a=z();
b=z();
print((e(a,a)-e(a,b))/(e(b,b)-e(b,a))/(1/((1/2)^b:len())));
```
### First version
```
z=io.read;
e=function(s,t)
r=0;
for d in s:gmatch"."do
r=r*10;
if d==t:sub(1,1)then r=r+1 end;
end
return tonumber(r,2);
end;
f=function(n,o)
return ((e(n,n)-e(n,o))/(e(o,o)-e(o,n)))/(1/((1/2)^3));
end;
print(f(z(),z()));
```
] |
[Question]
[
[Pi](http://en.wikipedia.org/wiki/Pi) is an [irrational number](http://en.wikipedia.org/wiki/Irrational_number), which means that its decimal representation never terminates or repeats itself.
Pi truncated to 41 decimal digits (40 places) is `3.1415926535897932384626433832795028841971`.
If we ignore the decimal point and list the digits as a sequence of positive integers, **avoiding duplicates**, we get `3 1 4 15 9 2 6 5 35 8 97 93 23 84 62 64 33 83 27 950 28 841 971` ([OEIS A064809](https://oeis.org/A064809)).
(Notice that `15` appears in the sequence instead of `1 5` because `1` had already occurred.
Also note that `0` does not occur because it is not positive; `950` contains the first zero.)
To construct the first ***pirrational number*** we use this sequence to index into the digits of Pi (the first digit being 3, the second 1, etc.).
So the first digit of the first pirrational number is the 3rd digit of Pi,
the second digit is the 1st digit of Pi,
the third digit is the 4th digit of Pi,
the fourth is the **15th** digit of Pi,
and so on.
A decimal point is added after the first digit to mimic Pi.
Thus the first pirrational number to 41 digits is `4.3195195867462520687356193644029372991880`.
(Note that for the 30th digit I had to go all the way to the 974th digit of Pi.)
To construct the second pirrational number the process is repeated using the first pirrational number instead of Pi. (Pi itself may be called the zeroth pirrational number.) So the new sequence is `4 3 1 9 5 19 58 ...` and the first piirational number is indexed to produce the second, which starts `9.14858...`.
Further pirrational numbers are created in the same way, each being generated from the one before.
# Challenge
Your task is to write the shortest program possible that takes in two integers, `N` and `D`, and outputs the `N`th pirrational number truncated to `D` decimal digits.
`D` is always positive but `N` is non-negative, and `D` digits of Pi should be output when `N` is 0.
When `D` is 1 it does not matter if the decimal point is present or not.
The input should come from stdin or the command line and output should go to stdout (or your language's closest alternatives).
Your program should work for all input values of `N` and `D` below 216, but it needn't be timely or efficient.
The shortest code [in bytes](https://mothereff.in/byte-counter) wins.
(Note that pirrational numbers exits in other bases but everything in this challenge is done in base 10.)
[Answer]
# Haskell, 431 400 369
```
import Data.List
g(q,r,t,k,n,l)|4*q+r-t<n*t=n:g(q#0,(r-n*t)#0,t,k,div(r#(30*q))t-n#0,l)|1<2=g(q*k,(2*q+r)*l,t*l,k+1,div(q*(7*k+2)+r*l)(t*l),l+2)
u w@(x:y:xs)=x:v y xs 0 w
v a(r:s)n w|a`elem`take n(u w)||r==0=v(a#r)s n w|1<2=a:v r s(n+1)w
m p=map(genericIndex p.pred)$u p
a#b=a*10+b
(x:s)%n=show x++'.':show(foldl1(#)$n`take`s)
f n d=print$iterate m(g(1,0,1,1,3,3))!!n%d
```
Gotta love infinite lists! Given enough time and memory, this program will eventually calculate the right answer for any N and D (I assume).
I'm generating the digits of pi with `g` using a [spigot algorithm](http://en.wikipedia.org/wiki/Spigot_algorithm) (shamelessly stolen from a guy called Stanley Rabinowitz), grouping the digits/creating the sequence using `v` and generating a pirrational number from these using `m`.
Here it is in action:
```
λ> f 0 10
"3.1415926535"
λ> f 1 10
"4.3195195867"
λ> f 2 10
"9.Interrupted. --didn't have the time to wait for this to finish
λ> f 2 4
"9.1485"
```
[Answer]
# Python 292 bytes
Quite inefficient, I've only been able to get a few digits of N=3 and none of N=4.
```
import sympy
def P(N,D,s=''):
if N<1:return'3'+`sympy.pi.evalf(D+9)`[2:-9]
for i in range(D):
h=[];l='';j=i;x=0
while-~j:
x+=1;d=P(N-1,x)[-1];l+=d
while'1'>P(N-1,x+1)[-1]:x+=1;l+='0'
if(l in h)<1:h+=[l];l='';j-=1
s+=P(N-1,int(h[i]))[-1]
return s
s=P(*input())
print s[0]+'.'+s[1:]
```
Sample input:
```
0,20
3.1415926535897932384
1,20
4.3195195867462520687
2,10
9.148583196
3,5
9.9815
```
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.